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
deecdf1728a5fd6648b525567856db24d2e58bb6
C++
AndresFelipeRG/Algorithms
/checkLinkedListPalinDromeLinearTimeConstantSpace.cpp
UTF-8
1,020
3.0625
3
[]
no_license
** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ int Solution::lPalin(ListNode* A) { ListNode * root = A; ListNode * compare = A; if(A == NULL){ return 0; } if(A->next == NULL){ return 1; } ListNode * beginning = new ListNode(A->val); beginning->next = NULL; while(root->next != NULL){ ListNode * node = new ListNode(root->next->val); node->next = beginning; beginning = node; root = root->next; } while(compare != NULL){ if(compare->val != beginning->val){ return 0; } compare = compare->next; beginning = beginning->next; } return 1; }
true
e2146557c71b64ede2dfb48805cddeac50edba93
C++
0APOCALYPSE0/Algorithm-Concepts
/Tree/BinaryTree_ZigZag_Level_order.cc
UTF-8
1,398
3.078125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long int #define endl "\n" class Node { public: int data; Node* left; Node* right; Node(const int data){ this->data = data; left = NULL; right = NULL; } }; Node* buildTree(){ int data; cin >> data; string left,right; Node* root = new Node(data); cin >> left; if(left=="true"){ root->left = buildTree(); } cin >> right; if(right=="true"){ root->right = buildTree(); } return root; } int height(Node*root){ if(root==NULL){ return 0; } return max(height(root->left),height(root->right))+1; } void getKthLevel(Node*root,int k,vector<Node*> &nodes){ if(root==NULL){ return; } if(k==1){ // cout<<root->data<<" "; nodes.push_back(root); return; } getKthLevel(root->left,k-1,nodes); getKthLevel(root->right,k-1,nodes); } void zigZaglevelorder(Node* root){ int h = height(root); for(int i=1;i<=h;++i){ vector<Node*> vec; getKthLevel(root,i,vec); if(i&1){ for(int k=0;k<vec.size();++k){ cout << vec[k]->data << " "; } }else{ for(int k=vec.size()-1;k>=0;--k){ cout << vec[k]->data << " "; } } } } int main(){ #ifndef ONLINE_JUGDE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); freopen("error.txt","w",stderr); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); Node* root = buildTree(); zigZaglevelorder(root); return 0; }
true
57c42af702293754a9492d0fe2718d76691d4fdf
C++
fukaoi/crystal-v8
/src/ext/v8pp/ptr_traits.hpp
UTF-8
2,893
2.625
3
[ "MIT" ]
permissive
// // Copyright (c) 2013-2016 Pavel Medvedev. All rights reserved. // // This file is part of v8pp (https://github.com/pmed/v8pp) project. // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef V8PP_PTR_TRAITS_HPP_INCLUDED #define V8PP_PTR_TRAITS_HPP_INCLUDED #include <memory> namespace v8pp { template<typename T, typename Enable = void> struct convert; struct raw_ptr_traits { using pointer_type = void*; using const_pointer_type = void const*; template<typename T> using object_pointer_type = T*; template<typename T> using object_const_pointer_type = T const*; using object_id = void*; static object_id pointer_id(void* ptr) { return ptr; } static pointer_type key(object_id id) { return id; } static pointer_type const_pointer_cast(const_pointer_type ptr) { return const_cast<void*>(ptr); } template<typename T, typename U> static T* static_pointer_cast(U* ptr) { return static_cast<T*>(ptr); } template<typename T> using convert_ptr = convert<T*>; template<typename T> using convert_ref = convert<T&>; template<typename T, typename ...Args> static object_pointer_type<T> create(Args&&... args) { return new T(std::forward<Args>(args)...); } template<typename T> static void destroy(object_pointer_type<T> const& object) { delete object; } template<typename T> static size_t object_size(object_pointer_type<T> const&) { return sizeof(T); } }; struct ref_from_shared_ptr {}; struct shared_ptr_traits { using pointer_type = std::shared_ptr<void>; using const_pointer_type = std::shared_ptr<void const>; template<typename T> using object_pointer_type = std::shared_ptr<T>; template<typename T> using object_const_pointer_type = std::shared_ptr<T const>; using object_id = void*; static object_id pointer_id(pointer_type const& ptr) { return ptr.get(); } static pointer_type key(object_id id) { return std::shared_ptr<void>(id, [](void*) {}); } static pointer_type const_pointer_cast(const_pointer_type const& ptr) { return std::const_pointer_cast<void>(ptr); } template<typename T, typename U> static std::shared_ptr<T> static_pointer_cast(std::shared_ptr<U> const& ptr) { return std::static_pointer_cast<T>(ptr); } template<typename T> using convert_ptr = convert<std::shared_ptr<T>>; template<typename T> using convert_ref = convert<T, ref_from_shared_ptr>; template<typename T, typename ...Args> static object_pointer_type<T> create(Args&&... args) { return std::make_shared<T>(std::forward<Args>(args)...); } template<typename T> static void destroy(object_pointer_type<T> const&) { // do nothing with reference-counted object } template<typename T> static size_t object_size(object_pointer_type<T> const&) { return sizeof(T); } }; } //namespace v8pp #endif // V8PP_PTR_TRAITS_HPP_INCLUDED
true
fc1ffae6309ee3c064f2eafe2848b48a2a2bc027
C++
Menci/TuringAdvancedProgramming19A
/Task 1/double-checker/src/main.cc
UTF-8
14,713
2.90625
3
[]
no_license
#include <iostream> #include <iomanip> #include <random> #include <chrono> #include <bitset> #include <cstdint> #include <math.h> #include <dlfcn.h> #include "TerminalColor/TerminalColor.h" #include "Arguments.h" #include "Utility.h" const double RELATIVE_ERROR_LIMIT = 1e-8; using double_calc_t = uint64_t (*)(uint64_t, uint64_t, char); double calcAnswer(double a, double b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: return 0; } } double randDouble(std::mt19937_64 &rng) { // The first method can generate more edge case while the second // method can prevent one number is less/greater than too many times // of another. if (rng() & 1) { return i2f(rng()); } else { double a = (double)rng() * (double)(1ull << 63) + rng(), b = (double)rng() * (double)(1ull << 63) + rng(); int sign = (rng() & 1) ? 1 : -1; return a / b * sign; } } constexpr size_t FP_LENGTH_SIGN = 1; constexpr size_t FP_LENGTH_EXPONENT = 11; constexpr size_t FP_LENGTH_FRACTION = 52; constexpr size_t FP_BIAS = (int64_t)((1ULL << (FP_LENGTH_EXPONENT - 1)) - 1); struct DoubleDetail { double value; std::string type, hexadecimal, decimalExponentNotation; bool sign; std::bitset<FP_LENGTH_EXPONENT> exponent; std::bitset<FP_LENGTH_FRACTION> fraction; }; DoubleDetail inspectDouble(double x) { if (f2i(x) == 0x43dffc0000000000) throw 1; DoubleDetail result; result.value = x; switch (fpclassify(x)) { case FP_NAN: result.type = "not a number"; break; case FP_INFINITE: result.type = "infinity"; break; case FP_ZERO: result.type = "zero"; break; case FP_SUBNORMAL: result.type = "denormalized"; break; case FP_NORMAL: result.type = "normalized"; break; default: throw; } constexpr size_t DOUBLE_PRINTF_BUFFER_LENGTH = 1024; char buffer[DOUBLE_PRINTF_BUFFER_LENGTH]; sprintf(buffer, "0x%016llx", (unsigned long long)f2i(x)); result.hexadecimal = buffer; sprintf(buffer, "%.8le", x); result.decimalExponentNotation = buffer; union { double x; struct { // On GNU/Linux x86_64 it's little endian, so we declare them // in reverse order. uint64_t fraction : FP_LENGTH_FRACTION; uint64_t exponent : FP_LENGTH_EXPONENT; uint64_t sign : FP_LENGTH_SIGN; } structure; } inspector; inspector.x = x; result.sign = inspector.structure.sign; result.exponent = inspector.structure.exponent; result.fraction = inspector.structure.fraction; return result; } std::string formatPercentage(double x) { char buffer[sizeof("100.00%")]; sprintf(buffer, "%05.2f%%", x * 100); std::string str = buffer; return str == "100.00%" ? "100.0%" : str; } void printDoubleDetail(std::string name, DoubleDetail detail, bool highlightSign = false, size_t highlightExponentFrom = FP_LENGTH_EXPONENT, size_t highlightFractionFrom = FP_LENGTH_FRACTION) { constexpr size_t NAME_LENGTH = 14 + 4; name = std::string(NAME_LENGTH - name.length(), ' ') + name; std::string fraction = detail.fraction.to_string(), fractionL = fraction.substr(0, highlightFractionFrom), fractionR = fraction.substr(highlightFractionFrom, fraction.length()), exponent = detail.exponent.to_string(), exponentL = exponent.substr(0, highlightExponentFrom), exponentR = exponent.substr(highlightExponentFrom, exponent.length()); std::cout << name << " = " << TerminalColor::ForegroundMagenta << detail.decimalExponentNotation << TerminalColor::Reset << " (" << TerminalColor::ForegroundCyan << detail.type << TerminalColor::Reset << ")" << ", in 64-bit unsigned integer " << TerminalColor::ForegroundYellow << detail.hexadecimal << TerminalColor::Reset << std::endl << " sign = " << (highlightSign ? TerminalColor::ForegroundRed : TerminalColor::Reset) << TerminalColor::Bold << (detail.sign ? '-' : '+') << TerminalColor::Reset << ", " << "fraction = " << TerminalColor::Bold << fractionL << TerminalColor::ForegroundRed << fractionR << TerminalColor::Reset << ", " << "exponent = " << TerminalColor::Bold << exponentL << TerminalColor::ForegroundRed << exponentR << TerminalColor::Reset << " = " << TerminalColor::Bold << TerminalColor::ForegroundBlue << ((long long)detail.exponent.to_ullong() - (long long)FP_BIAS) << TerminalColor::Reset << " + " << FP_BIAS << " = " << detail.exponent.to_ullong() << std::endl; } void printDiagnosticMessage(double a, double b, double answer, double userOutput) { DoubleDetail aDetail = inspectDouble(a), bDetail = inspectDouble(b), answerDetail = inspectDouble(answer), userOutputDetail = inspectDouble(userOutput); printDoubleDetail("Operand a", aDetail); printDoubleDetail("Operand b", bDetail); bool highlightSign = answerDetail.sign != userOutputDetail.sign; size_t highlightExponentFrom = 0, highlightFractionFrom = 0; while (highlightExponentFrom < FP_LENGTH_EXPONENT && answerDetail.exponent[FP_LENGTH_EXPONENT - highlightExponentFrom - 1] == userOutputDetail.exponent[FP_LENGTH_EXPONENT - highlightExponentFrom - 1]) highlightExponentFrom++; while (highlightFractionFrom < FP_LENGTH_FRACTION && answerDetail.fraction[FP_LENGTH_FRACTION - highlightFractionFrom - 1] == userOutputDetail.fraction[FP_LENGTH_FRACTION - highlightFractionFrom - 1]) highlightFractionFrom++; printDoubleDetail("Correct answer", answerDetail, highlightSign, highlightExponentFrom, highlightFractionFrom); printDoubleDetail("Your result", userOutputDetail, highlightSign, highlightExponentFrom, highlightFractionFrom); } void printStatistics(size_t checkRounds, double timeElapsedInSeconds, size_t correctCount, size_t partiallyCorrectCount, size_t wrongCount) { const size_t CPS_GREEN = 3000000, CPS_YELLOW = 500000; double calcPerSecond = checkRounds / timeElapsedInSeconds; TerminalColor cpsColor; if (calcPerSecond >= CPS_GREEN) cpsColor = TerminalColor::ForegroundGreen; else if (calcPerSecond >= CPS_YELLOW) cpsColor = TerminalColor::ForegroundYellow; else cpsColor = TerminalColor::ForegroundRed; std::cout << "Finished in " << std::setprecision(3) << std::fixed << cpsColor << TerminalColor::Bold << timeElapsedInSeconds << TerminalColor::Reset << " seconds, " << cpsColor << TerminalColor::Bold << calcPerSecond << TerminalColor::Reset << " calcs per second." << std::endl; if (correctCount == checkRounds + 1) { std::cout << TerminalColor::ForegroundGreen << TerminalColor::Bold << "All" << TerminalColor::Reset << " correct!" << std::endl; } else { std::string strCorrectCount = std::to_string(correctCount), strPartiallyCorrectCount = std::to_string(partiallyCorrectCount), strWrongCount = std::to_string(wrongCount); size_t length = std::max(std::max(strCorrectCount.length(), strPartiallyCorrectCount.length()), strWrongCount.length()) + 4; strCorrectCount = std::string(length - strCorrectCount.length(), ' ') + strCorrectCount; strPartiallyCorrectCount = std::string(length - strPartiallyCorrectCount.length(), ' ') + strPartiallyCorrectCount; strWrongCount = std::string(length - strWrongCount.length(), ' ') + strWrongCount; std::cout << TerminalColor::ForegroundGreen << TerminalColor::Bold << strCorrectCount << " " << TerminalColor::Reset << TerminalColor::ForegroundGreen << "(" + formatPercentage((double)correctCount / checkRounds) + ")" << TerminalColor::Reset << TerminalColor::ForegroundGreen << " correct" << std::endl << TerminalColor::ForegroundYellow << TerminalColor::Bold << strPartiallyCorrectCount << " " << TerminalColor::Reset << TerminalColor::ForegroundYellow << "(" + formatPercentage((double)partiallyCorrectCount / checkRounds) + ")" << TerminalColor::Reset << TerminalColor::ForegroundYellow << " partially correct (0 < relative error < 1e-8)" << std::endl << TerminalColor::ForegroundRed << TerminalColor::Bold << strWrongCount << " " << TerminalColor::Reset << TerminalColor::ForegroundRed << "(" + formatPercentage((double)wrongCount / checkRounds) + ")" << TerminalColor::Reset << TerminalColor::ForegroundRed << " wrong" << std::endl; } } void check(char op, double_calc_t calcFunction, std::mt19937_64 &rng, size_t checkRounds) { std::uniform_int_distribution<uint64_t> gen; auto calc = [&](double a, double b, char op) { return i2f(calcFunction(f2i(a), f2i(b), op)); }; std::cout << TerminalColor::Reset << "Checking operator " << TerminalColor::Bold << op << TerminalColor::Reset << " for " << TerminalColor::Bold << checkRounds << TerminalColor::Reset << " rounds:" << std::endl; struct Question { double a, b, answer, userOutput; }; // Generate random questions and calculate answer std::vector<Question> questions(checkRounds); for (Question &question : questions) { question.a = randDouble(rng), question.b = randDouble(rng); question.answer = calcAnswer(question.a, question.b, op); } // Get user's output for each question and measure the time auto startTime = std::chrono::high_resolution_clock::now(); for (Question &question : questions) { question.userOutput = calc(question.a, question.b, op); } auto endTime = std::chrono::high_resolution_clock::now(); // Check bool nonCorrectOccured = false; size_t correctCount = 0, partiallyCorrectCount = 0, wrongCount = 0; for (size_t i = 0; i < checkRounds; i++) { double a = questions[i].a, b = questions[i].b; double userOutput = questions[i].userOutput, answer = questions[i].answer; bool correct = false, partiallyCorrect = false; if (isnan(answer)) { if (isnan(userOutput)) { correctCount++; correct = true; } else wrongCount++; } else if (isinf(answer)) { if (isinf(userOutput)) { correctCount++; correct = true; } else wrongCount++; } else if (userOutput == answer) { correctCount++; correct = true; } else { double relativeError = fabs(userOutput - answer) / fabs(answer); if (relativeError < RELATIVE_ERROR_LIMIT) partiallyCorrectCount++, partiallyCorrect = true; else wrongCount++; } if (!correct && !nonCorrectOccured) { // First non-correct nonCorrectOccured = true; std::cout << "First non-correct calculation "; if (partiallyCorrect) { std::cout << TerminalColor::ForegroundYellow << "(partially correct)" << TerminalColor::Reset; } else { std::cout << TerminalColor::ForegroundRed << "(wrong)" << TerminalColor::Reset; } std::cout << " occurs on round " << TerminalColor::Bold << (i + 1) << TerminalColor::Reset << " (" + formatPercentage((double)i / checkRounds) + "):" << std::endl; printDiagnosticMessage(a, b, answer, userOutput); } } double timeElapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime).count(), timeElapsedInSeconds = timeElapsed / 1000000000; printStatistics(checkRounds, timeElapsedInSeconds, correctCount, partiallyCorrectCount, wrongCount); } int main(int argc, char *argv[]) { Arguments arguments = parseArguments(argc, argv); // Load dynamic library void *handle = dlopen(arguments.dynamicLibrary.c_str(), RTLD_LAZY); if (!handle) { std::cerr << "Can't open dynamic library, error: " << dlerror() << std::endl; return 1; } else dlerror(); // Reset dlerror on success // Get function double_calc_t calcFunction = (double_calc_t)dlsym(handle, arguments.functionName.c_str()); if (!calcFunction) { std::cerr << "Can't get function, error: " << dlerror() << std::endl; return 1; } // Initialize dynamic library calcFunction(0, 0, '+'); // Initialize RNG uint64_t seed = arguments.seed; if (seed == 0) { seed = std::random_device()(); std::cout << "Running double checker with random seed " << seed << "." << std::endl; } else { std::cout << "Running double checker with specfied seed " << seed << "." << std::endl; } std::mt19937_64 rng(seed); for (char op : arguments.operators) { std::cout << std::endl; check(op, calcFunction, rng, arguments.checkRounds); } }
true
36e128ab85560932cc0b2bdfaeb7c395c3ed90f9
C++
liuyi2008/3D-display
/3D display/test3.cpp
GB18030
1,916
2.71875
3
[]
no_license
#include<stdio.h> #include<iostream> #include <vector> #include<math.h> #include<windows.h> #include<GL/glut.h> void init(int argc, char** argv) { glutInit(&argc, argv); //Iʼ GLUT. glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); //ʾģʽʹRGBģ glutInitWindowPosition(50, 100); //ôڵĶλ glutInitWindowSize(400, 300); //ôڵĸ߶ȺͿ glutCreateWindow("draw cell structure"); glShadeModel(GL_SMOOTH); glClearColor(1.0, 1.0, 1.0, 1.0); //ڱɫΪɫ glMatrixMode(GL_PROJECTION); gluOrtho2D(0, 600, 0, 450); } void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT); glPointSize(1); glBegin(GL_LINES); //glBegin(GL_LINES); //for (int i = 1; i < tripoint.size(); i+=2) //{ // glColor3f(1.0f, 0.0f, 0.0f); //Ǻɫ // glVertex2f(tripoint[i-1].x, tripoint[i-1].y); // glVertex2f(tripoint[i].x, tripoint[i].y); // //printf("i=%d,x=%f,y=%f\n",i , tripoint[i].x, tripoint[i].y); //} //glEnd(); glColor3f(0.0f, 1.0f, 0.0f); glBegin(GL_LINES); glVertex2f(0, 0); glVertex2f(200, 0); glVertex2f(200, 0); glVertex2f(200, 200); glVertex2f(200, 200); glVertex2f(0, 200); glVertex2f(0, 200); glVertex2f(0, 0); glEnd(); //glBegin(GL_LINES); //for (int i = 0; i < new_tripoint.size(); i++) //{ // glColor3f(1.0f, 0.0f, 0.0f); //Ǻɫ // glVertex2f(new_tripoint[i].x, new_tripoint[i].y); // //printf("i=%d,x=%f,y=%f\n",i , tripoint[i].x, tripoint[i].y); //} //glEnd(); //glBegin(GL_LINE_LOOP); //for (int i = 0; i < polypoint.size(); i++) //{ // glColor3f(0.0f, 0.0f, 1.0f); //Ǻɫ // glVertex2f(polypoint[i].x, polypoint[i].y); // //printf("i=%d,x=%f,y=%f\n",i , tripoint[i].x, tripoint[i].y); //} //glEnd(); glFlush(); } int main(int argc, char** argv) { init(argc, argv); glutDisplayFunc(myDisplay); glutMainLoop(); return 0; }
true
6d095882eb8b048b8ed11442c2f2393d610ef1d6
C++
Superdanby/YEE
/AP325/P-8-11.cpp
UTF-8
1,214
2.578125
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; typedef long long ll; // constexpr const int INF = 0x3f3f3f3f; constexpr const ll INF = 1L << 60; constexpr const ll MOD = 1e9 + 9; void traverse(const vector<vector<pair<int, int>>> &graph, vector<vector<ll>> &dp, const int node) { for (const auto &x : graph[node]) { if (!dp[0][x.first]) { dp[0][x.first] += x.second; traverse(graph, dp, x.first); dp[1][node] += dp[0][x.first] > dp[1][x.first] ? dp[0][x.first] : dp[1][x.first]; dp[0][node] += dp[1][x.first]; } } } ll solve(vector<vector<pair<int, int>>> &graph) { vector<vector<ll>> dp(2, vector<ll>(graph.size())); // select, give up dp[0][1] = graph[0][0].second; traverse(graph, dp, 1); return dp[0][1] > dp[1][1] ? dp[0][1] : dp[1][1]; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int node_cnt; cin >> node_cnt; vector<vector<pair<int, int>>> graph(node_cnt + 1); // node, value int from, value; cin >> value; graph[0].push_back({1, value}); for (int i = 2; i <= node_cnt; ++i) { cin >> from >> value; graph[from].push_back({i, value}); } cout << solve(graph) << "\n"; return 0; }
true
b547c06b653b08d29ed261bdcf855a080c58f8ac
C++
zhangke8/MSU-CS
/Programming-II/scheduler.h
UTF-8
800
2.53125
3
[]
no_license
/* * File: scheduler.h * Author: zhangke8 * Section: 007 * Created on April 3, 2014, 1:55 PM */ #ifndef SCHEDULER_H #define SCHEDULER_H #include "job.h" #include<string> using std::string; #include<vector> using std::vector; #include<algorithm> using std::swap; class Scheduler { private: vector<Job> arrivals; vector<Job> process; vector<Job> finish; long clock_time = 0; long job_count = 0; long total = 0; public: //constructors Scheduler() {}; // Scheduler(long x, long y, long z, vector<vector<long>>v1,vector<vector<long>>v2, vector<vector<long>>v3):arrivals(v1), process(v2), finish(v3), clock_time(0), job_count(0),total(0) {}; // members void load_jobs(string); void round_robin(); bool finished(); void display(); }; #endif /* SCHEDULER_H */
true
fa4c663b136daf665d49a3892c52dfdf2973c25f
C++
yvc74/wrmos
/lib/containers/bitmap.h
UTF-8
2,961
3.046875
3
[ "MIT" ]
permissive
//################################################################################################## // // bitmap.h - template container. // //################################################################################################## #ifndef BITMAP_H #define BITMAP_H template <unsigned MAX_BITS> class bitmap_t { enum { Bits_per_word = 8 * sizeof(long) }; unsigned long _words [MAX_BITS / Bits_per_word + 1]; unsigned _capacity; unsigned _count; public: bitmap_t() : _capacity(0), _count(0) { for (unsigned i=0; i<(sizeof(_words)/sizeof(_words[0])); ++i) _words[i] = 0; } inline int init(unsigned capacity) { if (capacity > MAX_BITS) return -1; _capacity = capacity; _count = 0; return 0; } inline unsigned capacity() const { return _capacity; } inline unsigned count() const { return _count; } inline int get(unsigned pos) const { if (pos >= _capacity) return -1; return (_words[pos / Bits_per_word] >> (pos % Bits_per_word)) & 1; } inline int set(unsigned pos) { if (pos >= _capacity) return -1; if (get(pos) == 1) return 0; _count++; _words[pos / Bits_per_word] |= 1 << (pos % Bits_per_word); return 0; } inline int clear(unsigned pos) { if (pos >= _capacity) return -1; if (get(pos) == 0) return 0; _count--; _words[pos / Bits_per_word] &= ~(1 << (pos % Bits_per_word)); return 0; } // find bit=0, set 1, return bit pos inline int getfree() { // find not full-busy word unsigned words_count = _capacity / Bits_per_word; for (unsigned i=0; i<words_count; ++i) { long w = _words[i]; if (_words[i] != (unsigned long)-1) { // find free bit for (unsigned j=0; j<Bits_per_word; ++j) { if (!(w & (1 << j))) { unsigned pos = i * Bits_per_word + j; set(pos); return pos; } } } } // find free bit in tail unsigned bits_count = _capacity % Bits_per_word; long last_word = _words[words_count]; for (unsigned i=0; i<bits_count; ++i) { if (!(last_word & (1 << i))) { unsigned pos = words_count * Bits_per_word + i; set(pos); return pos; } } return -1; } inline int getbusy() { // find not full-free word unsigned words_count = _capacity / Bits_per_word; for (unsigned i=0; i<words_count; ++i) { long w = _words[i]; if (_words[i] != 0) { // find busy bit for (unsigned j=0; j<Bits_per_word; ++j) { if (w & (1 << j)) { unsigned pos = i * Bits_per_word + j; clear(pos); return pos; } } } } // find busy bit in tail unsigned bits_count = _capacity % Bits_per_word; long last_word = _words[words_count]; for (unsigned i=0; i<bits_count; ++i) { if (last_word & (1 << i)) { unsigned pos = words_count * Bits_per_word + i; clear(pos); return pos; } } return -1; } inline int getany(int val) { return val ? getbusy() : getfree(); } }; #endif // BITMAP_H
true
3f35d98d25d41b724a6db44ae1da182b7ed081ba
C++
shamrice/EngineMonitor
/src/time/ClockTime.cpp
UTF-8
1,286
2.96875
3
[]
no_license
#include "ClockTime.h" time_t getTeensy3Time() { return Teensy3Clock.get(); } ClockTime::ClockTime() { setSyncProvider(getTeensy3Time); if (timeStatus()!= timeSet) { SerialLogger::getInstance().log(LogLevel::ERROR, "ClockTime::ClockTime()" "Unable to sync with RTC"); } else { SerialLogger::getInstance().log(LogLevel::INFO, "ClockTime::ClockTime()" "RTC has set the system time"); } } void ClockTime::logCurrentTime() { DateTime datetime(year(), month(), day(), hour(), minute(), second()); SerialLogger::getInstance().log(LogLevel::INFO, "ClockTime::ClockTime()", datetime.toString()); } DateTime ClockTime::getDateTime() { //TODO : current manually adjusting timestamp to EST DateTime datetime(year(), month(), day(), hour() - 5, minute(), second()); return datetime; } void ClockTime::setDateTime(DateTime currentDateTime) { //TODO : get unix timestamp from datetime passed in and used that for the set call. time_t t = 0L; Teensy3Clock.set(t); // set the RTC setTime( currentDateTime.getHour(), currentDateTime.getMinute(), currentDateTime.getSecond(), currentDateTime.getDay(), currentDateTime.getMonth(), currentDateTime.getYear() ); }
true
e1faae393ba9330ee37f20f5d26646f511440794
C++
InsightSoftwareConsortium/ITK
/Modules/ThirdParty/GDCM/src/gdcm/Utilities/gdcmrle/info.cxx
UTF-8
3,394
2.8125
3
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", ...
permissive
/*========================================================================= Program: librle, a minimal RLE library for DICOM Copyright (c) 2014 Mathieu Malaterre All rights reserved. See Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "info.h" #include <stdexcept> #include <cassert> namespace rle { // The byte of a multibyte number with the greatest importance: that is, the // byte stored first on a big-endian system or last on a little-endian // system. pixel_info::pixel_info( unsigned char nc, unsigned char bpp ): number_components(nc), bits_per_pixel(bpp) { if ( nc != 1 && nc != 3 ) throw std::runtime_error( "invalid samples per pixel" ); if( bpp != 8 && bpp != 16 && bpp != 32 ) throw std::runtime_error( "invalid bits per pixel" ); } static inline int compute_num_segments_impl( int nc, int bpp ) { // pre assert( bpp % 8 == 0 && (nc == 1 || nc == 3) ); const int mult = bpp / 8; const int res = nc * mult; // post assert( res <= 12 && res > 0 ); return res; } bool pixel_info::check_num_segments( const int num_segments ) { bool ok = false; // DICOM restrict number of possible values: switch( num_segments ) { case 1: // 1 -> Grayscale / 8bits case 2: // 2 -> 16bits case 3: // 3 -> RGB / 8bits case 4: // 4 -> 32bits case 6: // 6 -> RGB / 16bits case 12: // 12 -> RGB / 32 bits ok = true; break; } return ok; } static inline void compute_nc_bpp_from_num_segments( const int num_segments, int & nc, int & bpp ) { // pre condition: assert( pixel_info::check_num_segments( num_segments ) ); if( num_segments % 3 == 0 ) { nc = 3; bpp = ( num_segments / 3 ) * 8; } else { nc = 1; bpp = num_segments; } // post condition assert( compute_num_segments_impl( nc, bpp ) == num_segments ); } pixel_info::pixel_info( int num_segments ) { int nc, bpp; compute_nc_bpp_from_num_segments( num_segments, nc, bpp ); number_components = nc; bits_per_pixel = bpp; } int pixel_info::get_number_of_bits_per_pixel() const { return bits_per_pixel; } int pixel_info::get_number_of_components() const { return number_components; } // Segments are organised as follow, eg 16bits RGB: /* NumSeg: 6 Offset: 64 // Most Significant / Red Offset: 12752 // Least Significant / Red Offset: 62208 // Most Significant / Green Offset: 74896 // Least Significant / Green Offset: 124352 // Most Significant / Blue Offset: 137040 // Least Significant / Blue Offset: 0 Offset: 0 Offset: 0 Offset: 0 Offset: 0 Offset: 0 Offset: 0 Offset: 0 Offset: 0 */ int pixel_info::compute_num_segments() const { return compute_num_segments_impl(number_components, bits_per_pixel); } image_info::image_info(int w, int h, pixel_info const & pi, bool pc, bool le): width(w), height(h), pix(pi), planarconfiguration(pc), littleendian(le) { if( width < 0 || height < 0 ) throw std::runtime_error( "invalid dimensions" ); if( pc && pix.get_number_of_components() != 3 ) throw std::runtime_error( "invalid planar configuration" ); } } // end namespace rle
true
89f4df29439ed72020c8d6cf17ab9362403ff30b
C++
UBCOrbit/ADCS
/Control/Quaternion_Library/quaternion.cpp
UTF-8
2,485
3.15625
3
[]
no_license
#include <math.h> #include "quaternion.h" using namespace Quaternion; quat& quat::operator= (const quat &q) { this->a = q.a; this->b = q.b; this->c = q.c; this->d = q.d; return *this; } quat& quat::operator+= (const quat &q) { this->a += q.a; this->b += q.b; this->c += q.c; this->d += q.d; return *this; } quat& quat::operator-= (const quat &q) { this->a -= q.a; this->b -= q.b; this->c -= q.c; this->d -= q.d; return *this; } quat& quat::operator*= (const quat &q) { double a = this->a*q.a - this->b*q.b - this->c*q.c - this->d*q.d; double b = this->a*q.b + this->b*q.a + this->c*q.d - this->d*q.c; double c = this->a*q.c - this->b*q.d + this->c*q.a + this->d*q.b; double d = this->a*q.d + this->b*q.c - this->c*q.b + this->d*q.a; this->a = a; this->b = b; this->c = c; this->d = d; return *this; } bool quat::operator== (const quat &q) { return (this->a == q.a && this->b == q.b && this->c == q.c && this->d == q.d); } const quat Quaternion::operator+ (const quat &q1, const quat &q2) { return quat(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + q2.d); } const quat Quaternion::operator+ (const quat &q, double r) { return quat(q.a + r, q.b + r, q.c + r, q.d + r); } const quat Quaternion::operator+ (double r, const quat &q) { return quat(r + q.a, r + q.b, r + q.c, r + q.d); } const quat Quaternion::operator- (const quat &q1, const quat &q2) { return quat(q1.a - q2.a, q1.b - q2.b, q1.c - q2.c, q1.d - q2.d); } const quat Quaternion::operator- (const quat &q, double r) { return quat(q.a - r, q.b - r, q.c - r, q.d - r); } const quat Quaternion::operator- (double r, const quat &q) { return quat(r - q.a, r - q.b, r - q.c, r - q.d); } const quat Quaternion::operator* (const quat &q1, const quat &q2) { return quat( q1.a*q2.a - q1.b*q2.b - q1.c*q2.c - q1.d*q2.d, q1.a*q2.b + q1.b*q2.a + q1.c*q2.d - q1.d*q2.c, q1.a*q2.c - q1.b*q2.d + q1.c*q2.a + q1.d*q2.b, q1.a*q2.d + q1.b*q2.c - q1.c*q2.b + q1.d*q2.a ); } const quat Quaternion::operator* (const quat &q, double r) { return quat(r*q.a, r*q.b, r*q.c, r*q.d); } const quat Quaternion::operator* (double r, const quat &q) { return quat(r*q.a, r*q.b, r*q.c, r*q.d); } const quat quat::negate(void) { return quat(-this->a, -this->b, -this->c, -this->d); } const quat quat::conjugate(void) { return quat(this->a, -this->b, -this->c, -this->d); } double quat::norm(void) { return sqrt( this->a*this->a + this->b*this->b + this->c*this->c + this->d*this->d ); }
true
048deafa2dbab9fe3b55ae8e55e1ab0d789f93bc
C++
basilwang/datastructure
/chapter2/iterator/main.cpp
UTF-8
307
2.84375
3
[]
no_license
#include "list.h" #include <iostream> using std::cout; int main() { list<int> l; l.insert(0,3); l.insert(0,2); l.insert(0,1); l.insert(3,4); l.printList(cout); for(iterator<int> it=l.begin();it!=l.end();it++) { cout<<*it<<endl; } system("pause"); }
true
c193725049e6a872f5cd617593baddf9112ce443
C++
scott-mao/NISwGSP_test
/Feature/ImageData.cpp
UTF-8
9,084
3.046875
3
[]
no_license
#include "ImageData.h" LineData::LineData(const Point2f & _a, const Point2f & _b, const double _width, const double _length) { data[0] = _a; data[1] = _b; width = _width; length = _length; } void ImageData::init_data(const char *img_path) { get_img(img_path); get_size(); } void ImageData::get_img(const char *img_path) { data = imread(img_path); rgba_data = imread(img_path, IMREAD_UNCHANGED); grey_data = Mat();// 灰色图 cvtColor(data, grey_data, CV_BGR2GRAY); float original_img_size = data.rows * data.cols; if (original_img_size > DOWN_SAMPLE_IMAGE_SIZE) { float scale = sqrt(DOWN_SAMPLE_IMAGE_SIZE / original_img_size); resize(data, data, Size(), scale, scale); resize(rgba_data, rgba_data, Size(), scale, scale); } assert(rgba_data.channels() >= 3); if (rgba_data.channels() == 3) { cvtColor(rgba_data, rgba_data, CV_BGR2BGRA); } vector<Mat> channels; split(rgba_data, channels); alpha_mask = channels[3]; } /** Mesh2D **/ void ImageData::get_size() { nw = data.cols / GRID_SIZE + (data.cols % GRID_SIZE != 0); nh = data.rows / GRID_SIZE + (data.rows % GRID_SIZE != 0); lw = data.cols / (double)nw; lh = data.rows / (double)nh; } int ImageData::getGridIndexOfPoint(const Point2f & _p) { Point2i grid_p(_p.x / lw, _p.y / lh); grid_p.x = grid_p.x - (grid_p.x == nw); grid_p.y = grid_p.y - (grid_p.y == nh); return grid_p.x + grid_p.y * nw; } /** MeshGrid **/ vector<int> ImageData::getBoundaryVertexIndices() { if (boundary_edge_indices.empty()) { const int memory = DIMENSION_2D * (nh + nw); boundary_edge_indices.reserve(memory); const int bottom_shift = DIMENSION_2D * nh * nw + nh; for (int w = 0; w < nw; w ++) { boundary_edge_indices.emplace_back(2 * w); boundary_edge_indices.emplace_back(bottom_shift + w); } const int dh = 2 * nw + 1; for (int h = 0; h < nh; h ++) { int tmp = h * dh; boundary_edge_indices.emplace_back(tmp + 1); boundary_edge_indices.emplace_back(tmp + dh - 1); } assert(memory == boundary_edge_indices.size()); } return boundary_edge_indices; } vector<Point2f> ImageData::getVertices() { if (mesh_points.empty()) { const int memory = (nh + 1) * (nw + 1); mesh_points.reserve(memory); for (int h = 0; h <= nh; h ++) { for (int w = 0; w <= nw; w ++) { mesh_points.emplace_back(w * lw, h * lh); } } assert(memory == mesh_points.size()); } return mesh_points; } vector<vector<int> > ImageData::getTriangulationIndices() { if (triangulation_indices.empty()) { // 三角填充区域, 原值[[0, 1, 2], [0, 2, 3]], 即用两个三角形填满[0, 1, 2, 3](顺时针)的矩形区域 triangulation_indices.resize(2); triangulation_indices[0].emplace_back(0); triangulation_indices[0].emplace_back(1); triangulation_indices[0].emplace_back(2); triangulation_indices[1].emplace_back(0); triangulation_indices[1].emplace_back(2); triangulation_indices[1].emplace_back(3); } return triangulation_indices; } vector<vector<int> > ImageData::getPolygonsIndices() { // 获取每个mesh格子的4个顶点 if (polygons_indices.empty()) { const Point2i nexts[GRID_VERTEX_SIZE] = {// 左上, 右上, 右下, 左下 Point2i(0, 0), Point2i(1, 0), Point2i(1, 1), Point2i(0, 1) }; const int memory = nh * nw;// mesh点数目 polygons_indices.resize(memory); int index = 0; for (int h = 0; h < nh; h ++) {// 从上到下 for (int w = 0; w < nw; w ++) {// 从左到右 const Point2i p1(w, h); polygons_indices[index].reserve(GRID_VERTEX_SIZE); for (int n = 0; n < GRID_VERTEX_SIZE; n ++) { const Point2i p2 = p1 + nexts[n]; polygons_indices[index].emplace_back(p2.x + p2.y * (nw + 1));// 横向索引 + 纵向索引 * (横向mesh数目) } index ++; } } assert(memory == polygons_indices.size()); } return polygons_indices; } vector<Edge> ImageData::getEdges() { // 每个vertex的right, down邻接的vertex if (edges.empty()) { const vector<Point2i> nexts = { Point2i(1, 0), Point2i(0, 1) }; const int memory = DIMENSION_2D * nh * nw + nh + nw; edges.reserve(memory); for (int h = 0; h <= nh; h ++) { for (int w = 0; w <= nw; w ++) { const Point2i p1(w, h); for (int n = 0; n < nexts.size(); n ++) { const Point2i p2 = p1 + nexts[n]; if (p2.x >= 0 && p2.y >= 0 && p2.x <= nw && p2.y <= nh) { edges.emplace_back(p1.x + p1.y * (nw + 1), p2.x + p2.y * (nw + 1)); } } } } assert(memory == edges.size()); } return edges; } vector<vector<int> > ImageData::getPolygonsNeighbors() { // 所有vertex邻接vertex的索引(不包含边界) if (polygons_neighbors.empty()) { const vector<Point2i> nexts = { Point2i(1, 0), Point2i(0, 1), Point2i(-1, 0), Point2i(0, -1) }; const int memory = nh * nw; polygons_neighbors.resize(memory); int index = 0; for (int h = 0; h < nh; h ++) { for (int w = 0; w < nw; w ++) { const Point2i p1(w, h); for (int n = 0; n < nexts.size(); n ++) { const Point2i p2 = p1 + nexts[n]; if (p2.x >= 0 && p2.y >= 0 && p2.x < nw && p2.y < nh) { polygons_neighbors[index].emplace_back(p2.x + p2.y * nw); } } index ++; } } assert(memory == polygons_neighbors.size()); } return polygons_neighbors; } vector<vector<int> > ImageData::getVertexStructures() { // 所有vertex邻接vertex的索引(包含边界) if (vertex_structures.empty()) { const vector<Point2i> nexts = { Point2i(1, 0), Point2i(0, 1), Point2i(-1, 0), Point2i(0, -1) }; const int memory = (nh + 1) * (nw + 1); vertex_structures.resize(memory); int index = 0; for (int h = 0; h <= nh; h ++) { for (int w = 0; w <= nw; w ++) { Point2i p1(w, h); for (int n = 0; n < nexts.size(); n ++) { Point2i p2 = p1 + nexts[n]; if (p2.x >= 0 && p2.y >= 0 && p2.x <= nw && p2.y <= nh) { vertex_structures[index].emplace_back(p2.x + p2.y * (nw + 1)); } } index ++; } } assert(memory == vertex_structures.size()); } return vertex_structures; } vector<Point2f> ImageData::getPolygonsCenter() { // 所有vertex的中心 if (polygons_center.empty()) { const vector<Point2f> mesh_points = getVertices(); const vector<vector<int> > polygons_indices = getPolygonsIndices(); polygons_center.reserve(polygons_indices.size()); for (int i = 0; i < polygons_indices.size(); i ++) { Point2f center(0, 0); for (int j = 0; j < polygons_indices[i].size(); j ++) { center += mesh_points[polygons_indices[i][j]]; } polygons_center.emplace_back(center / (float)polygons_indices[i].size()); } } return polygons_center; } vector<vector<int> > ImageData::getEdgeStructures() { // TODO if (edge_structures.empty()) { const vector<Point2i> nexts = { Point2i(1, 0), Point2i(0, 1) }; const vector<Point2i> grid_neighbor = { Point2i(0, -1), Point2i(-1, 0) }; const int memory = DIMENSION_2D * nh * nw + nh + nw; edge_structures.resize(memory); int index = 0; for (int h = 0; h <= nh; h ++) { for (int w = 0; w <= nw; w ++) { Point2i p1(w, h); for (int n = 0; n < nexts.size(); n ++) { Point2i p2 = p1 + nexts[n]; if (p2.x >= 0 && p2.y >= 0 && p2.x <= nw && p2.y <= nh) { for (int j = 0; j < grid_neighbor.size(); j ++) { Point2i p3 = p1 + grid_neighbor[n] * j; if (p3.x >= 0 && p3.y >= 0 && p3.x < nw && p3.y < nh) { edge_structures[index].emplace_back(p3.x + p3.y * nw); } } index ++; } } } } assert(memory == edge_structures.size()); } return edge_structures; } InterpolateVertex ImageData::getInterpolateVertex(const Point2f & _p) { const vector<Point2f> vertices = getVertices(); const vector<vector<int> > & grids = getPolygonsIndices(); const int grid_index = getGridIndexOfPoint(_p); const vector<int> & g = grids[grid_index];// TODO Indices const vector<int> diagonal_indices = {2, 3, 0, 1};/* 0 1 2 3 -> 3 2 1 0 */ assert(g.size() == GRID_VERTEX_SIZE); vector<double> weights(GRID_VERTEX_SIZE); double sum_inv = 0; for (int i = 0; i < diagonal_indices.size(); i ++) { Point2f tmp(_p.x - vertices[g[diagonal_indices[i]]].x, _p.y - vertices[g[diagonal_indices[i]]].y); weights[i] = fabs(tmp.x * tmp.y); sum_inv += weights[i]; } sum_inv = 1. / sum_inv; for (int i = 0; i < GRID_VERTEX_SIZE; i ++) { weights[i] = weights[i] * sum_inv; } return InterpolateVertex(grid_index, weights);// 构造函数 }
true
a23eb204aeb1154621ce26c64838f0ee4ca71ee1
C++
weimingtom/HereticTrainer
/heretictrainer/Classes/GameSetting.h
GB18030
1,135
2.703125
3
[]
no_license
#ifndef __GANESETTING_CORE_H__ #define __GANESETTING_CORE_H__ #include"cocos2d.h" #include<string> #include<map> USING_NS_CC; /* Ϸ࣬һЩá */ class GameSetting { public: static const int JUDGETIME_MISS=0; static const int JUDGETIME_BAD = 1; static const int JUDGETIME_GOOD = 2; static const int JUDGETIME_GREAT = 3; //beat Vec2 getBornPosition(); //beatŸĿ Vec2 getTargetPosition(int pos); //ƷһЩļҪڹͶ̬滻 std::string getFileName(std::string name); //жʱ䷧ֵ double getJudgeTime(int type); //liveٶ double getSpeed(); //liveٶ void setSpeed(double speed); //ıļڶ̬滻üص void changeFileName(std::string name, std::string fileName); GameSetting(); //ȡ static GameSetting*getInstance(); private: double speed; static GameSetting*instance; std::map<std::string, std::string> fileNameMap; double judgeTimeTable[5]; Vec2 targetPosition[9]; Vec2 bornPosition; }; #endif
true
86974f5bf1ffa316fc61c1d644f9f2846689e7b8
C++
DPAttila/AGL2.0
/src/Point.cpp
UTF-8
2,200
3.34375
3
[]
no_license
#ifndef POINT_CPP #define POINT_CPP #include "Point.h" #include <cmath> #include <cstdlib> #include "Quaternion.h" using namespace std; namespace agl { Point::Point() {} Point::Point(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } float Point::pyth() { return sqrt(x*x + y*y + z*z); } void Point::normalize() { const float length = pyth(); x /= length; y /= length; z /= length; } Point Point::cross_product(const Point& p) { return Point( this->y * p.z - this->z * p.y, this->z * p.x - this->x * p.z, this->x * p.y - this->y * p.x ); } void Point::rotate(float angle, Point vector) { Quaternion p(0, this->x, this->y, this->z); Quaternion q( cos(angle/2), vector.x * sin(angle/2), vector.y * sin(angle/2), vector.z * sin(angle/2) ); Quaternion q_conjugate = q; q_conjugate.conjugate(); Quaternion a = q * p * q_conjugate; this->x = a.y; this->y = a.z; this->z = a.w; } bool Point::operator==(const Point& p) const { return (this->x == p.x && this->y == p.y && this->z == p.z); } Point Point::operator+(const Point& p) { return Point(this->x + p.x, this->y + p.y, this->z + p.z); } Point Point::operator-(const Point& p) { return Point(this->x - p.x, this->y - p.y, this->z - p.z); } Point Point::operator*(const float f) { return Point(this->x * f, this->y * f, this->z * f); } Point Point::operator/(const float f) { return Point(this->x / f, this->y / f, this->z / f); } Point& Point::operator+=(const Point& p) { this->x += p.x; this->y += p.y; this->z += p.z; return *this; } Point& Point::operator*=(const float f) { this->x *= f; this->y *= f; this->z *= f; return *this; } Point& Point::operator/=(const float f) { this->x *= f; this->y *= f; this->z *= f; return *this; } string Point::to_string() { return std::to_string(x) + "\t" + std::to_string(y) + "\t" + std::to_string(z); } } #endif
true
7153bcb2962fb3416201ec035f07a96d939b10fd
C++
pilgarlicx/rendering-fw
/RFW/system/utils/src/rfw/utils/file.h
UTF-8
2,204
2.828125
3
[ "Apache-2.0" ]
permissive
#pragma once #include <cassert> #include <fstream> #include <istream> #include <string> #ifdef WIN32 #include <direct.h> #else #include <unistd.h> #ifdef __linux__ #include <limits.h> #endif #endif #include "Logger.h" namespace rfw::utils::file { static std::string get_working_path() { #ifdef WIN32 const char *buffer = _getcwd(nullptr, 0); return std::string(buffer); #else char temp[PATH_MAX]; return (getcwd(temp, sizeof(temp)) ? std::string(temp) : std::string("")); #endif } static long filesize(const std::string_view &path) { std::ifstream in(path.data(), std::ifstream::binary | std::ifstream::ate); const auto value = in.tellg(); return static_cast<long>(value); } static std::vector<char> read_binary(const std::string_view &path) { std::ifstream file(path.data(), std::ios::binary); assert(file.is_open()); if (!file.is_open()) { WARNING("Could not open file: %s", path.data()); return {}; } const auto s = utils::file::filesize(path); std::vector<char> buffer(s); file.read(buffer.data(), s); file.close(); return buffer; } static std::string read(const std::string_view &path) { std::ifstream file = std::ifstream(path.data()); std::string line; std::string text; if (!file.is_open()) { const std::string cwdPath = utils::file::get_working_path(); const std::string filePath = cwdPath + '/' + path.data(); file = std::ifstream(filePath.data()); assert(file.is_open()); } if (!file.is_open()) WARNING("Could not open file: %s", path.data()); while (std::getline(file, line)) text += line + "\n"; return text; } static bool exists(const std::string_view &path) { std::ifstream file(path.data()); return file.is_open(); } static void write(const std::string_view &path, const std::string_view &contents, bool append) { std::ofstream file; file.open(path.data(), (append ? std::ios::app : std::ios::out)); file.write(contents.data(), contents.size()); file.close(); } static void write(const std::string_view &path, const std::vector<char> &contents) { std::ofstream file; file.open(path.data(), std::ios::out | std::ios::binary); file.write(contents.data(), contents.size()); file.close(); } } // namespace rfw::utils::file
true
1b560c9affcc54c4d06db01743fd3e03603024bf
C++
pufit/FCS-PFaM-2019
/2/2-palindrome.cpp
UTF-8
685
3.15625
3
[]
no_license
// // Created by pufit on 25.01.2020. // #include <algorithm> #include <cstdint> #include <iostream> #include <cctype> using i32 = int32_t; bool IsLetter(char c); int main() { std::string inp, out = "YES", str; std::getline(std::cin, inp); std::copy_if(inp.begin(), inp.end(), std::back_inserter(str), IsLetter); for (i32 i = 0; i < str.size() / 2; i++) { if (std::tolower(str[i]) != std::tolower(str[str.size() - 1 - i])) { out = "NO"; break; } } std::cout << out << "\n"; return 0; } bool IsLetter(char c) { return (c >= 65 && c <= 90) || (c >= 97 && c <= 122); }
true
dceb67d270bd4e52c4a9a238de91291b9e1decd3
C++
nobuyuki83/delfem2
/include/delfem2/vec2.cpp
UTF-8
13,486
2.609375
3
[ "MIT" ]
permissive
/* * Copyright (c) 2019 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cstdlib> #include "delfem2/vec2.h" DFM2_INLINE bool delfem2::IsCrossLines( const double po_s0[2], const double po_e0[2], const double po_s1[2], const double po_e1[2]) { const double area1 = Area_Tri2(po_s0, po_e0, po_s1); const double area2 = Area_Tri2(po_s0, po_e0, po_e1); if (area1 * area2 > 0.0) return false; const double area3 = Area_Tri2(po_s1, po_e1, po_s0); const double area4 = Area_Tri2(po_s1, po_e1, po_e0); if (area3 * area4 > 0.0) return false; return true; } // ================================================ template<typename T> T delfem2::Area_Tri2( const T v1[2], const T v2[2], const T v3[2]) { T v0 = (v2[0] - v1[0]) * (v3[1] - v1[1]) - (v3[0] - v1[0]) * (v2[1] - v1[1]); return v0 / 2; } #ifdef DFM2_STATIC_LIBRARY template float delfem2::Area_Tri2(const float v1[2], const float v2[2], const float v3[2]); template double delfem2::Area_Tri2(const double v1[2], const double v2[2], const double v3[2]); #endif // -------------------------------------- template<typename T> T delfem2::Dot2(const T w[2], const T v[2]) { return w[0] * v[0] + w[1] * v[1]; } #ifdef DFM2_STATIC_LIBRARY template float delfem2::Dot2(const float v1[2], const float v2[2]); template double delfem2::Dot2(const double v1[2], const double v2[2]); #endif // -------------------------------------- // template specialization need to be done in the namespace namespace delfem2 { template<> DFM2_INLINE double Length2( const double v[2]) { return sqrt(v[0] * v[0] + v[1] * v[1]); } template<> DFM2_INLINE float Length2( const float v[2]) { return sqrtf(v[0] * v[0] + v[1] * v[1]); } } // -------------------------------------- // template specialization need to be done in the namespace namespace delfem2 { template<> DFM2_INLINE double Distance2( const double v1[2], const double v2[2]) { return sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1])); } template<> DFM2_INLINE float Distance2( const float v1[2], const float v2[2]) { return sqrtf((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1])); } } // -------------------------------------------------- template<typename T> T delfem2::SquareLength2(const T v[2]) { return v[0] * v[0] + v[1] * v[1]; } #ifdef DFM2_STATIC_LIBRARY template float delfem2::SquareLength2(const float v[2]); template double delfem2::SquareLength2(const double v[2]); #endif // ------------------------------------------------ template<typename T> T delfem2::SquareDistance2(const T v1[2], const T v2[2]) { return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]); } #ifdef DFM2_STATIC_LIBRARY template float delfem2::SquareDistance2(const float v1[2], const float v2[2]); template double delfem2::SquareDistance2(const double v1[2], const double v2[2]); #endif // ------------------------------------------------ // specification of template requires namespace namespace delfem2 { template<> DFM2_INLINE void GaussianDistribution2(float noise[2]) { float a0 = (float) (rand() / (RAND_MAX + 1.0)); float a1 = (float) (rand() / (RAND_MAX + 1.0)); noise[0] = (float) (sqrtf(-2.f * logf(a0)) * cosf(3.1415f * 2.f * a1)); noise[1] = (float) (sqrtf(-2.f * logf(a0)) * sinf(3.1415f * 2.f * a1)); } template<> DFM2_INLINE void GaussianDistribution2(double noise[2]) { double a0 = rand() / (RAND_MAX + 1.0); double a1 = rand() / (RAND_MAX + 1.0); noise[0] = sqrt(-2.0 * log(a0)) * cos(3.1415 * 2 * a1); noise[1] = sqrt(-2.0 * log(a0)) * sin(3.1415 * 2 * a1); } } // ------------------------------------------------ template<typename T> void delfem2::Normalize2(T w[2]) { const T l = Length2(w); const T invl = 1 / l; w[0] *= invl; w[1] *= invl; } #ifdef DFM2_STATIC_LIBRARY template void delfem2::Normalize2(float w[2]); template void delfem2::Normalize2(double w[2]); #endif // ------------------------------------------------------------------------ // definining operator requires defining namespace namespace delfem2 { template<typename T> std::ostream &operator<<(std::ostream &output, const CVec2<T> &v) { output.setf(std::ios::scientific); output << v.p[0] << " " << v.p[1]; return output; } template<typename T> std::istream &operator>>(std::istream &input, CVec2<T> &v) { input >> v.p[0] >> v.p[1]; return input; } template<typename T1, typename T0> DFM2_INLINE delfem2::CVec2<T1> operator*(T0 c, const CVec2<T1> &v0) { return CVec2<T1>(v0.p[0] * c, v0.p[1] * c); } #ifdef DFM2_STATIC_LIBRARY template CVec2d operator*(double, const CVec2d&); template CVec2f operator*(double, const CVec2f&); template CVec2d operator*(float, const CVec2d&); template CVec2f operator*(float, const CVec2f&); template CVec2d operator*(int, const CVec2d&); template CVec2f operator*(int, const CVec2f&); template CVec2d operator*(unsigned int, const CVec2d&); template CVec2f operator*(unsigned int, const CVec2f&); #endif // --------------------- template<typename T, typename T1> delfem2::CVec2<T> operator*(const CVec2<T> &v0, T1 c) { return CVec2<T>(v0.p[0] * c, v0.p[1] * c); } #ifdef DFM2_STATIC_LIBRARY template CVec2d operator*(const CVec2d& v0, double c); template CVec2d operator*(const CVec2d& v0, float c); template CVec2d operator*(const CVec2d& v0, int c); template CVec2d operator*(const CVec2d& v0, unsigned int c); template CVec2f operator*(const CVec2f& v0, double c); template CVec2f operator*(const CVec2f& v0, float c); template CVec2f operator*(const CVec2f& v0, int c); template CVec2f operator*(const CVec2f& v0, unsigned int c); #endif // --------------------- template<typename T> T operator^(const CVec2<T> &lhs, const CVec2<T> &rhs) { return lhs.p[0] * rhs.p[1] - lhs.p[1] * rhs.p[0]; } #ifdef DFM2_STATIC_LIBRARY template double operator ^ (const CVec2d& lhs, const CVec2d& rhs); template float operator ^ (const CVec2f& lhs, const CVec2f& rhs); #endif // ------------------- //! divide by real number template<typename T> CVec2<T> operator/(const CVec2<T> &vec, double d) { CVec2<T> temp = vec; temp /= d; return temp; } #ifdef DFM2_STATIC_LIBRARY template CVec2d operator / (const CVec2d& vec, double d); #endif } // namespace delfem2 // ----------------------------------------------------------------- template<typename T> delfem2::CVec2<T> delfem2::rotate( const CVec2<T> &p0, double theta) { CVec2<T> p1; double c = cos(theta), s = sin(theta); p1.p[0] = c * p0.p[0] - s * p0.p[1]; p1.p[1] = s * p0.p[0] + c * p0.p[1]; return p1; } template<typename T> delfem2::CVec2<T> delfem2::rotate90( const CVec2<T> &p0) { return CVec2<T>(-p0.p[1], p0.p[0]); } // --------------------------------------------------------------- template<typename T> delfem2::CVec2<T> delfem2::Mat2Vec( const double A[4], const CVec2<T> &v) { return CVec2<T>(A[0] * v.x + A[1] * v.y, A[2] * v.x + A[3] * v.y); } #ifdef DFM2_STATIC_LIBRARY template delfem2::CVec2d delfem2::Mat2Vec(const double A[4], const CVec2d& v); #endif // -------------------------------- //! Area of the Triangle template<class VEC> typename VEC::Scalar delfem2::Area_Tri2( const VEC &v1, const VEC &v2, const VEC &v3) { return ((v2[0] - v1[0]) * (v3[1] - v1[1]) - (v3[0] - v1[0]) * (v2[1] - v1[1])) / 2; } #ifdef DFM2_STATIC_LIBRARY template double delfem2::Area_Tri2(const CVec2d& v1, const CVec2d& v2, const CVec2d& v3); template float delfem2::Area_Tri2(const CVec2f& v1, const CVec2f& v2, const CVec2f& v3); #endif template<typename T> double delfem2::Cross(const CVec2<T> &v1, const CVec2<T> &v2) { return v1.p[0] * v2.p[1] - v2.p[0] * v1.p[1]; } #ifdef DFM2_STATIC_LIBRARY template double delfem2::Cross(const CVec2d& v1, const CVec2d& v2); #endif template<typename T> double delfem2::SquareLength(const CVec2<T> &point) { return point.p[0] * point.p[0] + point.p[1] * point.p[1]; } #ifdef DFM2_STATIC_LIBRARY template double delfem2::SquareLength(const CVec2d& point); #endif // -------------------- template<typename T> double delfem2::Length(const CVec2<T> &point) { return Length2(point.p); } #ifdef DFM2_STATIC_LIBRARY template double delfem2::Length(const CVec2d& point); #endif // --------------------- // Distance between two points template<typename T> T delfem2::Distance( const CVec2<T> &ipo0, const CVec2<T> &ipo1) { return Distance2(ipo0.p, ipo1.p); } #ifdef DFM2_STATIC_LIBRARY template double delfem2::Distance(const CVec2d& ipo0, const CVec2d& ipo1); #endif // --------------------- // Distance between two points template<typename T> double delfem2::SquareDistance( const CVec2<T> &ipo0, const CVec2<T> &ipo1) { return delfem2::SquareDistance2(ipo0.p, ipo1.p); } // Hight of a triangle : between v1 and line of v2-v3 template<typename T> double delfem2::TriHeight(const CVec2<T> &v1, const CVec2<T> &v2, const CVec2<T> &v3) { const double area = Area_Tri(v1, v2, v3); const double len = sqrt(SquareDistance(v2, v3)); return area * 2.0 / len; } // compute dot product template<typename T> double delfem2::Dot(const CVec2<T> &ipo0, const CVec2<T> &ipo1) { return Dot2(ipo0.p, ipo1.p); } #ifdef DFM2_STATIC_LIBRARY template double delfem2::Dot(const CVec2d& ipo0, const CVec2d& ipo1); #endif // -------------------------------------- // square root of circumradius template<typename T> double delfem2::SquareCircumradius( const CVec2<T> &p0, const CVec2<T> &p1, const CVec2<T> &p2) { const double area = Area_Tri(p0, p1, p2); const double dtmp0 = SquareDistance(p1, p2); const double dtmp1 = SquareDistance(p0, p2); const double dtmp2 = SquareDistance(p0, p1); return dtmp0 * dtmp1 * dtmp2 / (16.0 * area * area); } //! center of the circumcircle template<typename T> bool delfem2::CenterCircumcircle( const CVec2<T> &p0, const CVec2<T> &p1, const CVec2<T> &p2, CVec2<T> &center) { const double area = Area_Tri(p0, p1, p2); if (fabs(area) < 1.0e-10) { return false; } const double tmp_val = 1.0 / (area * area * 16.0); const double dtmp0 = SquareDistance(p1, p2); const double dtmp1 = SquareDistance(p0, p2); const double dtmp2 = SquareDistance(p0, p1); const double etmp0 = tmp_val * dtmp0 * (dtmp1 + dtmp2 - dtmp0); const double etmp1 = tmp_val * dtmp1 * (dtmp0 + dtmp2 - dtmp1); const double etmp2 = tmp_val * dtmp2 * (dtmp0 + dtmp1 - dtmp2); center.p[0] = etmp0 * p0.p[0] + etmp1 * p1.p[0] + etmp2 * p2.p[0]; center.p[1] = etmp0 * p0.p[1] + etmp1 * p1.p[1] + etmp2 * p2.p[1]; return true; } // check if Delaunay condition satisfied // 0 : p3 is inside circum circle on the p0,p1,p2 // 1 : on // 2 : outsdie template<typename T> int delfem2::DetDelaunay( const CVec2<T> &p0, const CVec2<T> &p1, const CVec2<T> &p2, const CVec2<T> &p3) { const double area = Area_Tri2(p0, p1, p2); if (fabs(area) < 1.0e-10) { return 3; } const double tmp_val = 1.0 / (area * area * 16.0); const double dtmp0 = SquareDistance(p1, p2); const double dtmp1 = SquareDistance(p0, p2); const double dtmp2 = SquareDistance(p0, p1); const double etmp0 = tmp_val * dtmp0 * (dtmp1 + dtmp2 - dtmp0); const double etmp1 = tmp_val * dtmp1 * (dtmp0 + dtmp2 - dtmp1); const double etmp2 = tmp_val * dtmp2 * (dtmp0 + dtmp1 - dtmp2); const CVec2<T> out_center(etmp0 * p0.p[0] + etmp1 * p1.p[0] + etmp2 * p2.p[0], etmp0 * p0.p[1] + etmp1 * p1.p[1] + etmp2 * p2.p[1]); const double qradius = SquareDistance(out_center, p0); const double qdistance = SquareDistance(out_center, p3); // assert( fabs( qradius - SquareLength(out_center,p1) ) < 1.0e-10*qradius ); // assert( fabs( qradius - SquareLength(out_center,p2) ) < 1.0e-10*qradius ); const double tol = 1.0e-20; if (qdistance > qradius * (1.0 + tol)) { return 2; } // outside the circumcircle else { if (qdistance < qradius * (1.0 - tol)) { return 0; } // inside the circumcircle else { return 1; } // on the circumcircle } } #ifdef DFM2_STATIC_LIBRARY template int delfem2::DetDelaunay(const CVec2d& p0, const CVec2d& p1, const CVec2d& p2, const CVec2d& p3); #endif // ---------------------------------------------------------------------------------- // std::vector starts from here //! Area of the Triangle (3 indexes and vertex array) template<typename T> double delfem2::Area_Tri( const int iv1, const int iv2, const int iv3, const std::vector<CVec2 <T> >& point ) { return Area_Tri2(point[iv1], point[iv2], point[iv3]); } // ----------------------------------------------------------- template<typename T> void delfem2::MakeMassMatrixTri( double M[9], double rho, const unsigned int aIP[3], const std::vector< CVec2<T> >& aVec2) { assert(aIP[0] < aVec2.size()); assert(aIP[1] < aVec2.size()); assert(aIP[2] < aVec2.size()); const double P[3][2] = { {aVec2[aIP[0]].p[0], aVec2[aIP[0]].p[1]}, {aVec2[aIP[1]].p[0], aVec2[aIP[1]].p[1]}, {aVec2[aIP[2]].p[0], aVec2[aIP[2]].p[1]}}; const double Area = delfem2::Area_Tri2(P[0], P[1], P[2]); { const double tmp = rho * Area / 3.0; M[0] = M[4] = M[8] = tmp; M[1] = M[2] = M[3] = M[5] = M[6] = M[7] = 0.0; } { const double tmp = rho * Area / 12.0; M[0] = M[4] = M[8] = tmp * 2.0; M[1] = M[2] = M[3] = M[5] = M[6] = M[7] = tmp; } }
true
612005d03658f06fd237ae4d7a878ac50a46e6c9
C++
vastyellowNew/contour-tree
/ContourTree/TriMesh.cpp
UTF-8
1,567
3.03125
3
[ "BSD-3-Clause" ]
permissive
#include "TriMesh.hpp" #include <fstream> #include <iostream> #include <set> #include <algorithm> #include <cassert> namespace contourtree { TriMesh::TriMesh() { } int TriMesh::getMaxDegree() { return maxStar; } int TriMesh::getVertexCount() { return nv; } int TriMesh::getStar(int64_t v, std::vector<int64_t> &star) { int ct = 0; for(uint32_t vv: vertices[v].adj) { star[ct] = vv; ct ++; } return ct; } bool TriMesh::lessThan(int64_t v1, int64_t v2) { if(fnVals[v1] < fnVals[v2]) { return true; } else if(fnVals[v1] == fnVals[v2]) { return (v1 < v2); } return false; } scalar_t TriMesh::getFunctionValue(int64_t v) { return (scalar_t) this->fnVals[v]; } void TriMesh::loadData(std::string fileName) { std::ifstream ip(fileName); std::string s; ip >> s; int nt; ip >> nv >> nt; vertices.resize(nv); fnVals.resize(nv); for(int i = 0;i < nv;i ++) { float x,y,z,fn; ip >> x >> y >> z >> fn; fnVals[i] = fn; } for(int i = 0;i < nt;i ++) { int ps,v1,v2,v3; ip >> ps >> v1 >> v2 >> v3; assert(ps == 3); vertices[v1].adj.insert(v2); vertices[v1].adj.insert(v3); vertices[v2].adj.insert(v1); vertices[v2].adj.insert(v3); vertices[v3].adj.insert(v2); vertices[v3].adj.insert(v1); } maxStar = 0; for(int i = 0;i < nv;i ++) { maxStar = std::max(maxStar,(int)vertices[i].adj.size()); } std::cout << maxStar << std::endl; } }
true
1959bfa5be52c342f7aa5d9d3929df2d16abe482
C++
lineCode/Berserk
/Engine/Source/RenderSystem/Public/Managers/DebugDrawManager.h
UTF-8
4,909
2.859375
3
[]
no_license
// // Created by Egor Orachyov on 13.04.2019. // #ifndef BERSERK_DEBUGDRAWMANAGER_H #define BERSERK_DEBUGDRAWMANAGER_H #include <Math/MathInclude.h> #include <Memory/IAllocator.h> #include <Misc/UsageDescriptors.h> #include <Containers/ArrayList.h> #include <mutex> namespace Berserk::Render { /** * Debug draw manager allows to submit debug primitive to the queue from anywhere * in the program code in CURRENT frame to be rendered in the NEXT frame. * Allows to be used in multi-threaded mode (synchronization used). * * @note Renders in the perspective projection (except text) of the active camera * @note Provided primitives: line, triangle, box, basis, 2D text, text, sphere. */ class ENGINE_API DebugDrawManager { public: GEN_NEW_DELETE(DebugDrawManager); /** Local typedefs */ typedef Vec3f Color; typedef Vec3f Point; /** Default color palette for the debug draw */ static const Color WHITE; static const Color RED; static const Color GREEN; static const Color BLUE; /** * Initial queue buffers size for submitting draw tasks * (Consider this number of primitives will have significant impact on performance) */ static const uint32 INITIAL_PRIMITIVES_MAX_COUNT = 100; /** * Types of the primitives, which can be submitted * to the debug draw queue */ enum DrawRequestType { eDRT_BASIS = 0, eDRT_AABB , eDRT_LINE , eDRT_TRIANGLE , eDRT_SPHERE , eDRT_TEXT , }; /** Stores info about one debug draw primitive (for queue) */ struct DrawRequest { DrawRequestType mType; bool mDepthTest; Color mColor; union { //! Info for basis struct { Point mPosition; }; //! Info for oriented basis struct { Mat4x4f mTransformation; }; //! Info for line struct { Point mLineStart; Point mLineEnd; }; //! Info for triangle struct { Point mTriangleA; Point mTriangleB; Point mTriangleC; }; //! Axis aligned bounding box AABB mAABB; //! Sphere info Sphere mSphere; //! 3D text (fixed size, should be valid for at least 2 frames) char* mStringBuffer; }; }; public: /* Requires engine allocator for internal usages */ explicit DebugDrawManager(IAllocator* allocator); /* Free used resources */ ~DebugDrawManager(); /** Add AABB to the debug draw queue [for next frame] */ void submit(const AABB& box, const Color& color, bool depthTest = true); /** Add Sphere to the debug draw queue [for next frame] */ void submit(const Sphere& sphere, const Color& color, bool depthTest = true); /** Add aligned basis to the debug draw queue [for next frame] */ void submit(const Point& position, const Color& color, bool depthTest = true); /** Add oriented basis to the debug draw queue [for next frame] */ void submit(const Mat4x4f& transformation, const Color& color, bool depthTest = true); /** Add line to the debug draw queue [for next frame] */ void submit(const Point& start, const Point& end, const Color& color, bool depthTest = true); /** Add triangle to the debug draw queue [for next frame] */ void submit(const Point& A, const Point& B, const Point& C, const Color& color, bool depthTest = true); /** Add text to the debug draw queue [for next frame] */ void submit(const Point& position, const char* text, const Color& color, bool depthTest = true); /** Swaps current render and submit buffers */ void update(); protected: /** For synchronization */ std::mutex mMutex; /** Data buffer 1 [will be swapped with 2] */ ArrayList<DrawRequest> mQueue1; /** Data buffer 2 [will be swapped with 1] */ ArrayList<DrawRequest> mQueue2; /** List which contains data to be rendered in the current frame */ ArrayList<DrawRequest>* mCurrentRender; /** List which allows to submit data to be rendered in the next frame */ ArrayList<DrawRequest>* mCurrentSubmit; }; } // namespace Berserk::Render #endif //BERSERK_DEBUGDRAWMANAGER_H
true
4f20028e58eb5b1339142856a1829a3f646ee49b
C++
mylonabusiness28/cpp_design_patterns
/Patterns/Singleton/ConceptualExample01.cpp
UTF-8
1,637
3.390625
3
[]
no_license
// =========================================================================== // ConceptualExample01.cpp // =========================================================================== #include <iostream> #include <thread> #include <mutex> namespace ConceptualExample01 { class Singleton final { private: Singleton() {}; static Singleton* m_instance; static std::mutex m_mutex; public: static Singleton* getInstance() { if (m_instance == nullptr) { m_instance = new Singleton(); } return m_instance; } static Singleton* getInstanceThreadSafe() { { std::scoped_lock<std::mutex> lock{ m_mutex }; if (m_instance == nullptr) { m_instance = new Singleton(); } } return m_instance; } }; Singleton* Singleton::m_instance{ nullptr }; std::mutex Singleton::m_mutex; } void test_singleton_01() { using namespace ConceptualExample01; auto singleton1 = Singleton::getInstance(); auto singleton2 = Singleton::getInstance(); std::cout << std::boolalpha << (singleton1 == singleton2) << std::endl; auto singleton3 = Singleton::getInstanceThreadSafe(); auto singleton4 = Singleton::getInstanceThreadSafe(); std::cout << std::boolalpha << (singleton3 == singleton4) << std::endl; } // =========================================================================== // End-of-File // ===========================================================================
true
62fc1c5ae0f687d344a77cc9c346e181e2704b64
C++
qs8607a/algorithm-10
/C++/Boyer-Moore/boyermoore.h
UTF-8
2,744
2.890625
3
[]
no_license
#ifndef __BOYERMOORE_H #define __BOYERMOORE_H #include <queue> #include <vector> typedef unsigned int uint; typedef unsigned char uchar; using namespace std; class BoyerMoore{ public: BoyerMoore(const uchar* prefix,uint _prefixlength); void search(queue<const uchar*>& store,const uchar* text, uint textlength); int wrong_char(int i, int j, uchar k); int wrong_char_expanded(int i, int j, uchar k); int wrong_horspool(int i, int j, uchar k); int good_suffix(int j); private: vector<int> prepare; vector<vector<int> > prepare_exp; vector<int> suffix; uint prefixlength; const uchar* prefix; }; BoyerMoore::BoyerMoore(const uchar* _prefix,uint _prefixlength):prefixlength(_prefixlength),prefix(_prefix){ prepare.resize(256,0); // initialize table most right occurrence in prefix // prefix : aba // prepare : .... a(3) b(2) c(0) .... for(uint i = 0; i < _prefixlength;i++) prepare[prefix[i]] = i+1; // initialize expanded table most right occurrence in prefix from specific position // prefix : aba // prepare : a : 1 1 3 // b : 0 2 2 // c : 0 0 0 prepare_exp.resize(256,vector<int>(prefixlength)); for(uint i = 0; i < 256;i++) for(uint j = 0; j < _prefixlength;j++) if(i == prefix[j]) for(uint f = j; f < _prefixlength; f++) prepare_exp[i][f] = j+1; suffix.resize(_prefixlength,0); for(int i = _prefixlength-2; i >= 0; --i) { uint j = suffix[i+1]; while(j>0 && prefix[_prefixlength-1-j] != prefix[i]) j = suffix[_prefixlength-j]; if(prefix[_prefixlength-1-j] == prefix[i]) j = j+1; suffix[i] = j; } } int BoyerMoore::wrong_char(int i, int j, uchar k){ int jump; jump = j + 1 - prepare[k]; if(jump<0) jump = 1; return jump; } int BoyerMoore::wrong_char_expanded(int i, int j, uchar k){ int jump = j + 1 - prepare_exp[k][j]; return jump; } int BoyerMoore::wrong_horspool(int i, int j, uchar k){ int jump = prefixlength - prepare[k]; return jump; } int BoyerMoore::good_suffix(int j){ return suffix[j]+1; } void BoyerMoore::search(queue<const uchar*>& store,const uchar* text, uint textlength){ int n = textlength; int m = prefixlength; int i = 0; int count = 0; int count_loops = 0; int d1; int d3; int k; while(i < n-m+1){ k=1; int j = m-1; bool good = true; while(j >= 0 && good){ count_loops++; if(text[i+j]!=prefix[j]){ d1 = wrong_char(i,j,text[i+j]); //d2 = wrong_char_expanded(i,j,text[i+j]); //d3 = wrong_horspool(i,j,text[i+m]); d3 = good_suffix(j); k = max(d1,d3); good = false; } else j--; } if(j==-1){ store.push(&text[i]); count++; } i+=k; } cout <<"#found: " << count << " in " << count_loops << " loops. (length text: " << n << ")" << endl; } #endif
true
a745da7c25952056ab93eda22158e346da62e6df
C++
Sanzhar479/Midstone-Project---GameEngine
/Engine/MidStone Engine/Spawner.cpp
UTF-8
622
2.765625
3
[]
no_license
#include "Spawner.h" Spawner::Spawner() { } Spawner::Spawner(Vec3 pos_[6]) { //setting new spawn points for (size_t i = 0; i < 6; i++) pos[i] = pos_[i]; } Spawner::~Spawner() { } Vec3 Spawner::Rand() { //setting randomizer srand(time(NULL)); //set number of the array member int num = 0; //checking if current number isn't equal the previous random numbers while (num == lastNum[0] || num == lastNum[1] || num == lastNum[2]) //randomizer itself num = rand() % 6; //updating previous numbers lastNum[2] = lastNum[1]; lastNum[1] = lastNum[0]; lastNum[0] = num; //return random position return pos[num]; }
true
ab1f90b128b66814bc5fcf4ff6629c3b5ba423ca
C++
15831944/Utility
/ScheduleNotifier.h
UTF-8
2,513
2.625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: ScheduleNotifier.h * Author: Justin Lin * * Created on 2017年5月17日, 下午 12:59 */ #ifndef UTILITY_SCHEDULENOTIFIER_H #define UTILITY_SCHEDULENOTIFIER_H #include <chrono> #include <functional> #include <thread> #include "DateTime.h" #include "MT/ManualResetEvent.h" #include "SimpleTime.h" namespace KGI_TW_Der_Utility{ template<typename TData> class ScheduleNotifier { public: typedef std::function<KGI_TW_Der_Utility::SimpleTime(const KGI_TW_Der_Utility::SimpleTime&, TData&)> GetNextScheduleFunc; typedef std::function<void(const TData&)> ReceiveNotifyFunc; ScheduleNotifier(GetNextScheduleFunc func, ReceiveNotifyFunc recvFunc ):GetNextSchedule_(func), ReceiveNotify_(recvFunc){} ScheduleNotifier(const ScheduleNotifier& orig){} virtual ~ScheduleNotifier(){} void Start(){ std::thread tScheduleThread( std::bind(&ScheduleNotifier::ScheduleThread,this) ); tScheduleThread.detach(); } void Stop(){ EventStop_.Set(true); } private: GetNextScheduleFunc GetNextSchedule_; ReceiveNotifyFunc ReceiveNotify_; KGI_TW_Der_Utility::ManualResetEvent EventStop_; private: void ScheduleThread(){ TData data; while( true ){ if( GetNextSchedule_ != NULL ){ DateTime now; SimpleTime stNow( now.GetHour(), now.GetMinute(), now.GetSecond() ); SimpleTime next = GetNextSchedule_(stNow, data); if( next.IsValid() ){ auto tpStart = next.to_time_point(); auto tpNow = stNow.to_time_point(); auto waitTime = std::chrono::duration_cast<std::chrono::milliseconds>(tpStart - tpNow); if( waitTime.count() > 0 ){ if( EventStop_.Wait( waitTime.count() ) == false ){ if( ReceiveNotify_ != NULL ){ ReceiveNotify_( data ); } }else{ break; // stopped by external trigger } } }else break; // no more jobs } } } }; } #endif /* UTILITY_SCHEDULENOTIFIER_H */
true
5a3addf8b1c34791efe854d47f22c0f8b390be67
C++
ericXin95616/hackerrank
/Swap_Nodes.cpp
UTF-8
849
2.9375
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> #include "source.h" using namespace std; /* typedef struct node { int data; node *left; node *right; } node; void addNode(node *root, const int leftData, const int rightData, const int parentNode); void swapNode(node *root, const int baseLevelNum); string inorderPrint(node *root); void freeBT(node *root); */ int main() { node *root = new node; root->data = 1; root->left = NULL; root->right = NULL; int N = 0, T = 0; cin >> N; for(int i = 1; i <= N; ++i) { int left = 0, right = 0; cin >> left >> right; addNode(root, left, right, i); } cin >> T; for(int i = 0; i < T; ++i) { int baseLevel = 0; cin >> baseLevel; swapNode(root, baseLevel); inorderPrint(root); } freeBT(&root); return 0; }
true
97b47a987482ee174fd686cffa77a8cbc921c282
C++
Mekanikles/fudgelang_cpp
/fudge/tests/inputtests.cpp
UTF-8
1,118
3.09375
3
[]
no_license
#include "gtest/gtest.h" #include "input/source.h" #include "input/bufferedinputstream.h" using namespace fudge; TEST(Input, EmptyInputStream) { BufferSource source(""); BufferedInputStream inStream(source.createStream()); char c = inStream.peek(); EXPECT_TRUE(c == EOF) << "Expected EOF but was: " << c; } TEST(Input, NonEmptyInputStream) { const char* input = "abcdefghijklmnopqrstuvxy0123456789"; BufferSource source(input); BufferedInputStream inStream(source.createStream()); char c; int p = 0; while ((c = inStream.peek()) != EOF) { EXPECT_TRUE(c == input[p]) << "Character mismatch at position " << p; inStream.advance(); ++p; } } TEST(Input, CurrentPos) { const char* input = "123456789\n" "123456789\n" "123456789\n" "123456789\n" "123456789\n" "123456789\n" "123456789\n" "123456789\n" "123456789\n" "123456789\n"; BufferSource source(input); BufferedInputStream inStream(source.createStream()); int p = 0; while (inStream.peek() != EOF) { EXPECT_EQ(inStream.currentPos(), p++); inStream.advance(); } EXPECT_EQ(inStream.currentPos(), 100); }
true
44976902651e92e098236e47eb87864e17d9b2b3
C++
serjik85kg/MineSweeperSolver
/MineSweeperSolver/game.h
UTF-8
280
2.625
3
[ "MIT" ]
permissive
#pragma once #include "group.h" class Game { public: int ** mField; int mM; int mN; int mMines; std::vector<Group> mGroups; public: Game(int ** field, int m, int n, std::vector<Group> groups, int mines) : mField(field), mM(m), mN(n), mGroups(groups), mMines(mines) {} };
true
b9ac198ae2f164eb3b7b679c02a6921ae6ba3657
C++
osak/Contest
/AOJ/0540.cc
UTF-8
1,726
2.703125
3
[]
no_license
#include <iostream> #include <vector> #include <utility> #include <climits> #include <algorithm> using namespace std; int main() { while(true) { int N, M, H, K; cin >> N >> M >> H >> K; if(!N && !M && !H && !K) break; vector<int> scores; vector<int> goals; vector<pair<int, int> > swaps; for(int i = 0; i < N; ++i) { int s; cin >> s; scores.push_back(s); goals.push_back(i); } vector<pair<int, int> > bars; for(int i = 0; i < M; ++i) { int a, b; cin >> a >> b; --a; bars.push_back(make_pair(b, a)); } sort(bars.begin(), bars.end()); for(int i = 0; i < M; ++i) { int a = bars[i].second; swaps.push_back(make_pair(goals[a], goals[a+1])); //cout << "swap " << goals[a] << ' ' << goals[a+1] << endl; swap(goals[a], goals[a+1]); } vector<int> to_goal(N); for(int i = 0; i < N; ++i) { to_goal[goals[i]] = i; } int ans = INT_MAX; int sum = 0; for(int i = 0; i < K; ++i) { sum += scores[to_goal[i]]; } ans = sum; for(int i = 0; i < M; ++i) { int a = swaps[i].first; int b = swaps[i].second; if(a < K && b < K) continue; if(a >= K && b >= K) continue; int minus = (a<K) ? scores[to_goal[a]] : scores[to_goal[b]]; int plus = (a<K) ? scores[to_goal[b]] : scores[to_goal[a]]; int tmp = sum-minus+plus; ans = min(ans, tmp); } cout << ans << endl; } }
true
4eb49f162edcf26ca0e7e81a4619e173794360f2
C++
Calypso3362/Yahtzee2020
/normal.cpp
UTF-8
26,111
2.90625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> #include <cstring> #include <iostream> #include <string> #include <algorithm> #include "normal.h" using namespace std; //functions for checking// int is_aces(int array[5]){ int sum = 0; for(int i=0; i<5; i++){ if (array[i]==1){ sum+=1; } } return sum; } int is_twos(int array[5]){ int sum = 0; for(int i=0; i<5; i++){ if (array[i]==2){ sum+=2; } } return sum; } int is_threes(int array[5]){ int sum = 0; for(int i=0; i<5; i++){ if (array[i]==3){ sum+=3; } } return sum; } int is_fours(int array[5]){ int sum = 0; for(int i=0; i<5; i++){ if (array[i]==1){ sum+=4; } } return sum; } int is_fives(int array[5]){ int sum = 0; for(int i=0; i<5; i++){ if (array[i]==5){ sum+=5; } } return sum; } int is_sixes(int array[5]){ int sum = 0; for(int i=0; i<5; i++){ if (array[i]==6){ sum+=6; } } return sum; } int is_threeofakind(int array[5]){ int sum = 0; bool threeofakind=false; for(int i=1;i<=6;i++){ int Count = 0; for(int j=0;j<5;j++){ if (array[j]== i) Count++; } if (Count>2) threeofakind = true; } if (threeofakind){ for(int k = 0;k<5; k++) sum += array[k]; } return sum; } int is_fourofakind(int array[5]){ int sum = 0; bool fourofakind=false; for(int i=1;i<=6;i++){ int Count = 0; for(int j=0;j<5;j++){ if (array[j]== i) Count++; } if (Count>3) fourofakind = true; } if (fourofakind){ for(int k = 0;k<5; k++) sum += array[k]; } return sum; } int is_yahtzee(int array[5]){ int res = 0; bool yahtzee=false; for(int i=1;i<=6;i++){ int Count = 0; for(int j=0;j<5;j++){ if (array[j]== i) Count++; } if (Count>4) yahtzee = true; } if (yahtzee){ res = 50; } return res; } int is_chance(int array[5]){ int sum = 0; for(int i=0;i<5;i++){ sum+=array[i]; } return sum; } int is_fullhouse(int array[5]){ int sum = 0; int i[5]; int n = sizeof(i) / sizeof(i[0]); i[0]=array[0]; i[1]=array[1]; i[2]=array[2]; i[3]=array[3]; i[4]=array[4]; sort(i, i + n); if( (((i[0] == i[1]) && (i[1] == i[2])) &&(i[3] == i[4])) || ((i[0] == i[1]) &&((i[2] == i[3]) && (i[3] == i[4]))) ) { sum = 25; } return sum; } int is_largestraight(int array[5]){ int sum = 0; int i[5]; int n = sizeof(i) / sizeof(i[0]); i[0]=array[0]; i[1]=array[1]; i[2]=array[2]; i[3]=array[3]; i[4]=array[4]; sort(i, i + n); if( ((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5)) || ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6)) ) { sum = 40; } return sum; } int is_smallstraight(int array[5]){ int sum = 0; int i[5]; int n = sizeof(i) / sizeof(i[0]); i[0]=array[0]; i[1]=array[1]; i[2]=array[2]; i[3]=array[3]; i[4]=array[4]; sort(i, i + n); for( int j = 0; j < 4; j++ ) { int temp = 0; if( i[j] == i[j+1] ) { temp = i[j]; for( int k = j; k < 4; k++ ) { i[k] = i[k+1]; } i[4] = temp; } } if( ((i[0] == 1) && (i[1] == 2) && (i[2] == 3) && (i[3] == 4)) || ((i[0] == 2) && (i[1] == 3) && (i[2] == 4) && (i[3] == 5)) || ((i[0] == 3) && (i[1] == 4) && (i[2] == 5) && (i[3] == 6)) || ((i[1] == 1) && (i[2] == 2) && (i[3] == 3) && (i[4] == 4)) || ((i[1] == 2) && (i[2] == 3) && (i[3] == 4) && (i[4] == 5)) || ((i[1] == 3) && (i[2] == 4) && (i[3] == 5) && (i[4] == 6)) ) { sum = 30; } return sum; } //end of functions for checking// string main_combination[13]={"Aces","Twos","Threes","Fours","Fives","Sixes","Three of a Kind","Four of a Kind","Full House","Small Straight","Large Straight","YAHTZEE","Chances"}; int player_turn_count=0; int dice_count=0; int player_one_dice[5]={0,0,0,0,0}; int player_two_dice[5]={0,0,0,0,0}; int player_one_expected_score[13]={0,0,0,0,0,0,0,0,0,0,0,0,0}; int player_two_expected_score[13]={0,0,0,0,0,0,0,0,0,0,0,0,0}; int player_one_upper_total=0; int player_two_upper_total=0; int player_one_score=0; int player_two_score=0; int player_one_check_list[13]={0,0,0,0,0,0,0,0,0,0,0,0,0}; int player_two_check_list[13]={0,0,0,0,0,0,0,0,0,0,0,0,0}; int Yahtzee_count_one=1; int Yahtzee_count_two=1; int normal(){ string dice; int dice_num; int com_num; //dice rolling// srand( time(0) ); cout<<"It's player "<<player_turn_count+1<<"'s turn"<<endl; if(dice_count==0){ cout<<"please roll the dices by inputing 'roll': "; string input_one; cin>>input_one; if(input_one== "roll"){ if(player_turn_count==0){ for (int i=0;i<5;++i){ player_one_dice[i] = (int) (1+rand()%6); cout<<"Dice "<<i+1<<" is: "<<player_one_dice[i]<<endl; } }else if (player_turn_count==1){ for (int d=0;d<5;++d){ player_two_dice[d] = (int) (1+rand()%6); cout<<"Dice "<<d+1<<" is: "<<player_one_dice[d]<<endl; } } } //providing expected score// if(player_turn_count==0){ player_one_expected_score[0]=is_aces(player_one_dice); player_one_expected_score[1]=is_twos(player_one_dice); player_one_expected_score[2]=is_threes(player_one_dice); player_one_expected_score[3]=is_fours(player_one_dice); player_one_expected_score[4]=is_fives(player_one_dice); player_one_expected_score[5]=is_sixes(player_one_dice); player_one_expected_score[6]=is_threeofakind(player_one_dice); player_one_expected_score[7]=is_fourofakind(player_one_dice); player_one_expected_score[8]=is_fullhouse(player_one_dice); player_one_expected_score[9]=is_smallstraight(player_one_dice); player_one_expected_score[10]=is_largestraight(player_one_dice); player_one_expected_score[11]=is_yahtzee(player_one_dice); player_one_expected_score[12]=is_chance(player_one_dice); cout<<"Here are the expected score of the combinations:"<<endl; cout<<"1. Aces: "<<player_one_expected_score[0]<<endl; cout<<"2. Twos: "<<player_one_expected_score[1]<<endl; cout<<"3. Threes: "<<player_one_expected_score[2]<<endl; cout<<"4. Fours: "<<player_one_expected_score[3]<<endl; cout<<"5. Fives: "<<player_one_expected_score[4]<<endl; cout<<"6. Sixes: "<<player_one_expected_score[5]<<endl; cout<<"7. Three of a kind: "<<player_one_expected_score[6]<<endl; cout<<"8. Four of a kind: "<<player_one_expected_score[7]<<endl; cout<<"9. Full house: "<<player_one_expected_score[8]<<endl; cout<<"10. Small straight: "<<player_one_expected_score[9]<<endl; cout<<"11. Large straight: "<<player_one_expected_score[10]<<endl; cout<<"12. Yahtzee: "<<player_one_expected_score[11]<<endl; cout<<"13. Chances: "<<player_one_expected_score[12]<<endl; } else if(player_turn_count==1){ player_two_expected_score[0]=is_aces(player_two_dice); player_two_expected_score[1]=is_twos(player_two_dice); player_two_expected_score[2]=is_threes(player_two_dice); player_two_expected_score[3]=is_fours(player_two_dice); player_two_expected_score[4]=is_fives(player_two_dice); player_two_expected_score[5]=is_sixes(player_two_dice); player_two_expected_score[6]=is_threeofakind(player_two_dice); player_two_expected_score[7]=is_fourofakind(player_two_dice); player_two_expected_score[8]=is_fullhouse(player_two_dice); player_two_expected_score[9]=is_smallstraight(player_two_dice); player_two_expected_score[10]=is_largestraight(player_two_dice); player_two_expected_score[11]=is_yahtzee(player_two_dice); player_two_expected_score[12]=is_chance(player_two_dice); cout<<"Here are the expected score of the combinations:"<<endl; cout<<"1. Aces: "<<player_two_expected_score[0]<<endl; cout<<"2. Twos: "<<player_two_expected_score[1]<<endl; cout<<"3. Threes: "<<player_two_expected_score[2]<<endl; cout<<"4. Fours: "<<player_two_expected_score[3]<<endl; cout<<"5. Fives: "<<player_two_expected_score[4]<<endl; cout<<"6. Sixes: "<<player_two_expected_score[5]<<endl; cout<<"7. Three of a kind: "<<player_two_expected_score[6]<<endl; cout<<"8. Four of a kind: "<<player_two_expected_score[7]<<endl; cout<<"9. Full house: "<<player_two_expected_score[8]<<endl; cout<<"10. Small straight: "<<player_two_expected_score[9]<<endl; cout<<"11. Large straight: "<<player_two_expected_score[10]<<endl; cout<<"12. Yahtzee: "<<player_two_expected_score[11]<<endl; cout<<"13. Chances: "<<player_two_expected_score[12]<<endl; } dice_count++; } if(dice_count==1){ cout<<"Do you want to reroll the dice? You have "<<3-dice_count<<" chances left! (yes/no): "; string input_two; cin>>input_two; if(input_two=="yes"){ cout<<"Please input the order of the dice to be rerolled with space separated: "; cin.ignore(); getline(cin, dice); for (int f=0;f<dice.length();f=f+2){ dice_num=(int)dice[f]- 48; dice_num=dice_num-1; if(player_turn_count==0){ player_one_dice[dice_num]=(int) (1+rand()%6); } else if (player_turn_count==1){ player_two_dice[dice_num]=(int) (1+rand()%6); } } for (int g=0;g<5;g++){ if(player_turn_count==0){ cout<<"Dice "<<g+1<<" is: "<<player_one_dice[g]<<endl; } else if (player_turn_count==1){ cout<<"Dice "<<g+1<<" is: "<<player_two_dice[g]<<endl; } } //providing expected score// if(player_turn_count==0){ player_one_expected_score[0]=is_aces(player_one_dice); player_one_expected_score[1]=is_twos(player_one_dice); player_one_expected_score[2]=is_threes(player_one_dice); player_one_expected_score[3]=is_fours(player_one_dice); player_one_expected_score[4]=is_fives(player_one_dice); player_one_expected_score[5]=is_sixes(player_one_dice); player_one_expected_score[6]=is_threeofakind(player_one_dice); player_one_expected_score[7]=is_fourofakind(player_one_dice); player_one_expected_score[8]=is_fullhouse(player_one_dice); player_one_expected_score[9]=is_smallstraight(player_one_dice); player_one_expected_score[10]=is_largestraight(player_one_dice); player_one_expected_score[11]=is_yahtzee(player_one_dice); player_one_expected_score[12]=is_chance(player_one_dice); cout<<"Here are the expected score of the combinations:"<<endl; cout<<"1. Aces: "<<player_one_expected_score[0]<<endl; cout<<"2. Twos: "<<player_one_expected_score[1]<<endl; cout<<"3. Threes: "<<player_one_expected_score[2]<<endl; cout<<"4. Fours: "<<player_one_expected_score[3]<<endl; cout<<"5. Fives: "<<player_one_expected_score[4]<<endl; cout<<"6. Sixes: "<<player_one_expected_score[5]<<endl; cout<<"7. Three of a kind: "<<player_one_expected_score[6]<<endl; cout<<"8. Four of a kind: "<<player_one_expected_score[7]<<endl; cout<<"9. Full house: "<<player_one_expected_score[8]<<endl; cout<<"10. Small straight: "<<player_one_expected_score[9]<<endl; cout<<"11. Large straight: "<<player_one_expected_score[10]<<endl; cout<<"12. Yahtzee: "<<player_one_expected_score[11]<<endl; cout<<"13. Chances: "<<player_one_expected_score[12]<<endl; } else if(player_turn_count==1){ player_two_expected_score[0]=is_aces(player_two_dice); player_two_expected_score[1]=is_twos(player_two_dice); player_two_expected_score[2]=is_threes(player_two_dice); player_two_expected_score[3]=is_fours(player_two_dice); player_two_expected_score[4]=is_fives(player_two_dice); player_two_expected_score[5]=is_sixes(player_two_dice); player_two_expected_score[6]=is_threeofakind(player_two_dice); player_two_expected_score[7]=is_fourofakind(player_two_dice); player_two_expected_score[8]=is_fullhouse(player_two_dice); player_two_expected_score[9]=is_smallstraight(player_two_dice); player_two_expected_score[10]=is_largestraight(player_two_dice); player_two_expected_score[11]=is_yahtzee(player_two_dice); player_two_expected_score[12]=is_chance(player_two_dice); cout<<"Here are the expected score of the combinations:"<<endl; cout<<"1. Aces: "<<player_two_expected_score[0]<<endl; cout<<"2. Twos: "<<player_two_expected_score[1]<<endl; cout<<"3. Threes: "<<player_two_expected_score[2]<<endl; cout<<"4. Fours: "<<player_two_expected_score[3]<<endl; cout<<"5. Fives: "<<player_two_expected_score[4]<<endl; cout<<"6. Sixes: "<<player_two_expected_score[5]<<endl; cout<<"7. Three of a kind: "<<player_two_expected_score[6]<<endl; cout<<"8. Four of a kind: "<<player_two_expected_score[7]<<endl; cout<<"9. Full house: "<<player_two_expected_score[8]<<endl; cout<<"10. Small straight: "<<player_two_expected_score[9]<<endl; cout<<"11. Large straight: "<<player_two_expected_score[10]<<endl; cout<<"12. Yahtzee: "<<player_two_expected_score[11]<<endl; cout<<"13. Chances: "<<player_two_expected_score[12]<<endl; } dice_count++; } else if(input_two=="no"){ dice_count=0; } } if(dice_count==2){ cout<<"Do you want to reroll the dice? You have the last chance! (yes/no): "; string input_three; cin>>input_three; if(input_three=="yes"){ cout<<"Please input the order of the dice to be rerolled with space separated: "; cin.ignore(); getline(cin, dice); for (int h=0;h<dice.length();h=h+2){ dice_num=(int)dice[h]- 48; dice_num=dice_num-1; if(player_turn_count==0){ player_one_dice[dice_num]=(int) (1+rand()%6); } else if (player_turn_count==1){ player_two_dice[dice_num]=(int) (1+rand()%6); } } for (int j=0;j<5;j++){ if(player_turn_count==0){ cout<<"Dice "<<j+1<<" is: "<<player_one_dice[j]<<endl; } else if (player_turn_count==1){ cout<<"Dice "<<j+1<<" is: "<<player_two_dice[j]<<endl; } } //providing expected score// if(player_turn_count==0){ player_one_expected_score[0]=is_aces(player_one_dice); player_one_expected_score[1]=is_twos(player_one_dice); player_one_expected_score[2]=is_threes(player_one_dice); player_one_expected_score[3]=is_fours(player_one_dice); player_one_expected_score[4]=is_fives(player_one_dice); player_one_expected_score[5]=is_sixes(player_one_dice); player_one_expected_score[6]=is_threeofakind(player_one_dice); player_one_expected_score[7]=is_fourofakind(player_one_dice); player_one_expected_score[8]=is_fullhouse(player_one_dice); player_one_expected_score[9]=is_smallstraight(player_one_dice); player_one_expected_score[10]=is_largestraight(player_one_dice); player_one_expected_score[11]=is_yahtzee(player_one_dice); player_one_expected_score[12]=is_chance(player_one_dice); cout<<"Here are the expected score of the combinations:"<<endl; cout<<"1. Aces: "<<player_one_expected_score[0]<<endl; cout<<"2. Twos: "<<player_one_expected_score[1]<<endl; cout<<"3. Threes: "<<player_one_expected_score[2]<<endl; cout<<"4. Fours: "<<player_one_expected_score[3]<<endl; cout<<"5. Fives: "<<player_one_expected_score[4]<<endl; cout<<"6. Sixes: "<<player_one_expected_score[5]<<endl; cout<<"7. Three of a kind: "<<player_one_expected_score[6]<<endl; cout<<"8. Four of a kind: "<<player_one_expected_score[7]<<endl; cout<<"9. Full house: "<<player_one_expected_score[8]<<endl; cout<<"10. Small straight: "<<player_one_expected_score[9]<<endl; cout<<"11. Large straight: "<<player_one_expected_score[10]<<endl; cout<<"12. Yahtzee: "<<player_one_expected_score[11]<<endl; cout<<"13. Chances: "<<player_one_expected_score[12]<<endl; } else if(player_turn_count==1){ player_two_expected_score[0]=is_aces(player_two_dice); player_two_expected_score[1]=is_twos(player_two_dice); player_two_expected_score[2]=is_threes(player_two_dice); player_two_expected_score[3]=is_fours(player_two_dice); player_two_expected_score[4]=is_fives(player_two_dice); player_two_expected_score[5]=is_sixes(player_two_dice); player_two_expected_score[6]=is_threeofakind(player_two_dice); player_two_expected_score[7]=is_fourofakind(player_two_dice); player_two_expected_score[8]=is_fullhouse(player_two_dice); player_two_expected_score[9]=is_smallstraight(player_two_dice); player_two_expected_score[10]=is_largestraight(player_two_dice); player_two_expected_score[11]=is_yahtzee(player_two_dice); player_two_expected_score[12]=is_chance(player_two_dice); cout<<"Here are the expected score of the combinations:"<<endl; cout<<"1. Aces: "<<player_two_expected_score[0]<<endl; cout<<"2. Twos: "<<player_two_expected_score[1]<<endl; cout<<"3. Threes: "<<player_two_expected_score[2]<<endl; cout<<"4. Fours: "<<player_two_expected_score[3]<<endl; cout<<"5. Fives: "<<player_two_expected_score[4]<<endl; cout<<"6. Sixes: "<<player_two_expected_score[5]<<endl; cout<<"7. Three of a kind: "<<player_two_expected_score[6]<<endl; cout<<"8. Four of a kind: "<<player_two_expected_score[7]<<endl; cout<<"9. Full house: "<<player_two_expected_score[8]<<endl; cout<<"10. Small straight: "<<player_two_expected_score[9]<<endl; cout<<"11. Large straight: "<<player_two_expected_score[10]<<endl; cout<<"12. Yahtzee: "<<player_two_expected_score[11]<<endl; cout<<"13. Chances: "<<player_two_expected_score[12]<<endl; } dice_count=0; } else if(input_three=="no"){ dice_count=0; } } //choose combinations// while(true){ cout<<"Which combinations do you want to choose? Type in the represented number: "; cin>>com_num; com_num=com_num-1; string input_four; if (player_turn_count==0){ cout<<"You have choosen "<<main_combination[com_num]<<" with score of "<<player_one_expected_score[com_num]<<". Are you sure? (yes/no): "; cin>>input_four; if(input_four=="yes"){ if(com_num==11 && player_one_expected_score[com_num]>0){ Yahtzee_count_two+=1; } if(player_one_check_list[11]==1 && com_num==12){ if(Yahtzee_count_one>1){ player_one_score+=100; }else{ int special_yahtzee; cout<<"You need to occupy a non-used combination: "; cin>>special_yahtzee; while(true){ cin>>special_yahtzee; if(player_two_check_list[special_yahtzee-1]==1){ cout<<"It has been occupied. Try again: "; } else { player_one_check_list[special_yahtzee-1]=1; player_turn_count++; return player_one_score; break; } } break; } } if(player_one_check_list[com_num]!=1){ if(com_num==0||com_num==1||com_num==2||com_num==3||com_num==4||com_num==5){ player_one_upper_total+=player_one_expected_score[com_num]; } if (player_one_upper_total>=63){ player_one_score+=35; } player_one_score=player_one_score+player_one_expected_score[com_num]; player_one_check_list[com_num]=1; player_turn_count++; return player_one_score; break; } else{ cout<<"This combinations has been occupied! Please choose again! "; continue; } } else if (input_four=="no"){ continue; } } else if (player_turn_count==1){ cout<<"You have choosen "<<main_combination[com_num]<<" with score of "<<player_two_expected_score[com_num]<<". Are you sure? (yes/no): "; cin>>input_four; if(input_four=="yes"){ if(com_num==11 && player_two_expected_score[com_num]>0){ Yahtzee_count_two+=1; } if(player_two_check_list[11]==1 && com_num==12){ if(Yahtzee_count_two>1){ player_two_score+=100; }else{ int special_yahtzee; cout<<"You need to occupy a non-used combination: "; cin>>special_yahtzee; while(true){ cin>>special_yahtzee; if(player_two_check_list[special_yahtzee-1]==1){ cout<<"It has been occupied. Try again: "; } else { player_two_check_list[special_yahtzee-1]=1; player_turn_count++; return player_two_score; break; } } break; } } if(player_two_check_list[com_num]!=1){ if(com_num==0||com_num==1||com_num==2||com_num==3||com_num==4||com_num==5){ player_two_upper_total+=player_two_expected_score[com_num]; } if (player_two_upper_total>=63){ player_two_score+=35; } player_two_score=player_two_score+player_two_expected_score[com_num]; player_two_check_list[com_num]=1; player_turn_count=0; return player_two_score; break; } else{ cout<<"This combinations has been occupied! Please choose again! "; continue; } } else if (input_four=="no"){ continue; } } } }
true
2d26bb0c37519c159f8baa638707f70d746c4199
C++
HypnoMix12/LAB9
/lab94.cpp
UTF-8
4,159
3.21875
3
[]
no_license
// lab94.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> using namespace std; int main() { setlocale(0, ""); int N; div_t N1, N2, N3; cout << "Введите число от 100 до 999: "; cin >> N; N1 = div(N, 100); N2 = div(N1.rem, 10); switch (N1.quot) { case 1:cout << "Сто "; break; case 2:cout << "Двести "; break; case 3:cout << "Триста "; break; case 4:cout << "Четыреста "; break; case 5:cout << "Пятсот "; break; case 6:cout << "Шестьсот "; break; case 7:cout << "Семьсот "; break; case 8:cout << "Восемьсот "; break; case 9:cout << "Девятьсот "; break; default: cout << "Введите трехзначное число"; break; } switch (N1.rem) { case 1: cout << "один."; break; case 2: cout << "два."; break; case 3: cout << "три."; break; case 4: cout << "четыре."; break; case 5: cout << "пять."; break; case 6: cout << "шесть."; break; case 7: cout << "семь."; break; case 8: cout << "восемь."; break; case 9: cout << "девять."; break; case 10: cout << "десять."; break; case 11: cout << "одиннадцать."; break; case 12: cout << "двенадцать."; break; case 13: cout << "тринадцать."; break; case 14: cout << "четырнадцать."; break; case 15: cout << "пятнадцать."; break; case 16: cout << "шестнадцать."; break; case 17: cout << "семнадцать."; break; case 18: cout << "восемнадцать."; break; case 19: cout << "девятнадцать."; break; default: break; } switch (N2.quot) { case 2: cout << "двадцать "; break; case 3: cout << "тридцать "; break; case 4: cout << "сорок "; break; case 5: cout << "пятьдесят "; break; case 6: cout << "шестьдесят "; break; case 7: cout << "семьдесят "; break; case 8: cout << "восемьдесят "; break; case 9: cout << "девяносто "; break; default: break; } switch (N2.rem) { case 1: cout << "один."; break; case 2: cout << "два."; break; case 3: cout << "три."; break; case 4: cout << "четыре."; break; case 5: cout << "пять."; break; case 6: cout << "шесть."; break; case 7: cout << "семь."; break; case 8: cout << "восемь."; break; case 9: cout << "девять."; break; default: break; } } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
true
8cb9fe0470dc9b359af9fb52d33df8330aea977b
C++
VincentZ-42/ROBOLAB1
/MOVEMENTS.ino
UTF-8
7,530
3.125
3
[]
no_license
///////////////////////////////////////////////////////////////// MOVEMENTS /////////////////////////////////////////////////////// void goUp(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputLeft, vol); analogWrite(LPWMOutputLeft, 0); analogWrite(RPWMOutputRight, 0); analogWrite(LPWMOutputRight, vol); } void goUp_v2(int volL, int volR) { if (volL >= 255) volL = 255; if (volR >= 255) volR = 255; analogWrite(RPWMOutputLeft, volL); analogWrite(LPWMOutputLeft, 0); analogWrite(RPWMOutputRight, 0); analogWrite(LPWMOutputRight, volR); } void goDown(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputLeft, 0); analogWrite(LPWMOutputLeft, vol); analogWrite(RPWMOutputRight, vol); analogWrite(LPWMOutputRight, 0); } void goDown_v2(int volL, int volR) { if (volL >= 255) volL = 255; if (volR >= 255) volR = 255; analogWrite(RPWMOutputLeft, 0); analogWrite(LPWMOutputLeft, volL); analogWrite(RPWMOutputRight, volR); analogWrite(LPWMOutputRight, 0); } void goRight(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputLeft, vol); analogWrite(LPWMOutputLeft, 0); analogWrite(RPWMOutputRight, vol); analogWrite(LPWMOutputRight, 0); } void goRight_v2(int volL, int volR) { if (volL >= 255) volL = 255; if (volR >= 255) volR = 255; analogWrite(RPWMOutputLeft, volL); analogWrite(LPWMOutputLeft, 0); analogWrite(RPWMOutputRight, volR); analogWrite(LPWMOutputRight, 0); } void goLeft(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputLeft, 0); analogWrite(LPWMOutputLeft, vol); analogWrite(RPWMOutputRight, 0); analogWrite(LPWMOutputRight, vol); } void goLeft_v2(int volL, int volR) { if (volL >= 255) volL = 255; if (volR >= 255) volR = 255; analogWrite(RPWMOutputLeft, 0); analogWrite(LPWMOutputLeft, volL); analogWrite(RPWMOutputRight, 0); analogWrite(LPWMOutputRight, volR); } void goUpRight(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputRight, vol); analogWrite(LPWMOutputRight, 0); } void goDownLeft(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputRight, 0); analogWrite(LPWMOutputRight, vol); } void goUpLeft(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputLeft, 0); analogWrite(LPWMOutputLeft, vol); } void goDownRight(int vol) { if (vol >= 255) vol = 255; analogWrite(RPWMOutputLeft, vol); analogWrite(LPWMOutputLeft, 0); } void doStop() { analogWrite(RPWMOutputLeft, 0); analogWrite(LPWMOutputLeft, 0); analogWrite(RPWMOutputRight, 0); analogWrite(LPWMOutputRight, 0); } ///////////////////////////////////////////////////////////////// SQUARE /////////////////////////////////////////////////////// void square_v2() { Serial.print("Encoder Left = "); Serial.println(encoderLeft); Serial.print("Encoder Right = "); Serial.println(encoderRight); Serial.println("start left"); // spray(); while (1) { goLeft_v2(195, 125); //155, 100 if ((encoderLeft > (encLprev + encL * 2.5)) && (encoderRight > (encRprev + encR * 2.5))) { doStop(); encoderLeft = 0; encoderRight = 0; encLprev = encoderLeft; encRprev = encoderRight; break ; } } // while (1) { // if (stopSpraying()) { // break ; // } // } Serial.print("Encoder Left = "); Serial.println(encoderLeft); Serial.print("Encoder Right = "); Serial.println(encoderRight); Serial.println("start down"); while (1) { goDown_v2(90, 140); if ((encoderLeft < (encLprev - encL * 0.5)) && (encoderRight > (encLprev + encR * 0.5))) { doStop(); encoderLeft = 0; encoderRight = 0; encLprev = encoderLeft; encRprev = encoderRight; break ; } } Serial.print("Encoder Left = "); Serial.println(encoderLeft); Serial.print("Encoder Right = "); Serial.println(encoderRight); Serial.println("start right"); // spray(); while (1) { goRight_v2(120, 150); //100 : 150 if ((encoderLeft < (encLprev - encL * 2.1)) && (encoderRight < (encRprev - encR * 2.1))) { doStop(); encoderLeft = 0; encoderRight = 0; encLprev = encoderLeft; encRprev = encoderRight; break ; } } // while (1) { // if (stopSpraying()) { // break ; // } // } Serial.print("Encoder Left = "); Serial.println(encoderLeft); Serial.print("Encoder Right = "); Serial.println(encoderRight); Serial.println("start down"); while (1) { goDown_v2(100, 140); if ((encoderLeft < (encLprev - encL * 0.5)) && (encoderRight > (encLprev + encR * 0.5))) { doStop(); encoderLeft = 0; encoderRight = 0; encLprev = encoderLeft; encRprev = encoderRight; break ; } } Serial.print("Encoder Left = "); Serial.println(encoderLeft); Serial.print("Encoder Right = "); Serial.println(encoderRight); Serial.println("start left"); // spray(); while (1) { goLeft_v2(125, 165); // 15 left : 19 right if ((encoderLeft > (encLprev + encL * 1.9)) && (encoderRight > (encRprev + encR * 1.9))) { doStop(); encoderLeft = 0; encoderRight = 0; encLprev = encoderLeft; encRprev = encoderRight; break ; } } // while (1) { // if (stopSpraying()) { // break ; // } // } Serial.print("Encoder Left = "); Serial.println(encoderLeft); Serial.print("Encoder Right = "); Serial.println(encoderRight); Serial.println("end"); } bool joystick(const int VRx, const int VRy, int encoderLeft, int encoderRight, int vol) { readX = analogRead(VRx); readY = analogRead(VRy); Serial.print("X-axis: "); Serial.println(readX); Serial.print("Y-axis: "); Serial.println(readY); Serial.print(encoderLeft); Serial.print(" - "); Serial.println(encoderRight); Serial.print("\n\n"); while (readX < 300 && readY > 600) { goDownRight(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readY > 600 && readX < 300) { goUpRight(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readY < 300 && readX < 300) { goDownRight(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readY > 600 && readX > 600) { goUpLeft(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readX < 300) { // goRight_v2(140, 200); goRight(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readX > 700) { // goLeft_v2(150, 165); goLeft(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readY < 300) { // goDown_v2(145, 200); goDown(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); while (readY > 700) { // goUp_v2(145, 200); goUp(vol); readX = analogRead(VRx); readY = analogRead(VRy); } doStop(); }
true
7ad526d1338b2d6a153f8926195ceeff696f73fb
C++
MatheusKunnen/Jogo-TecProg
/src/Jogo/Gerenciadores/GerenciadorColisoes.cpp
UTF-8
4,641
2.78125
3
[ "MIT" ]
permissive
// // GerenciadorColisoes.cpp // Jogo-SFML // // Created by Matheus Kunnen Ledesma on 11/13/19. // Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved. // #include "GerenciadorColisoes.hpp" namespace Game { namespace Gerenciadores { // Constructor & Destructor GerenciadorColisoes::GerenciadorColisoes(Mapa& mapa): l_personagens(), l_obstaculos(), mapa(mapa) { } GerenciadorColisoes::~GerenciadorColisoes(){ this->l_personagens.clear(); // Limpa lista personagens } // Methods void GerenciadorColisoes::gerenciarColisoes(){ this->clearEndingObj(); // Chama gerenciadores de colisoes this->gerenciarColisoesPM(); this->gerenciarColisoesPP(); this->gerenciarColisoesPO(); } void GerenciadorColisoes::gerenciarColisoesPM() { if (!this->l_personagens.beginItr()) return; // Verifica colisao com o mapa con todos os personagens do { checkCollision(this->l_personagens.getItr()); } while (this->l_personagens.nextItr()); } void GerenciadorColisoes::gerenciarColisoesPP() { int i, j; // Obtem nro de jogadores long count = this->l_personagens.getCount(); // Verifica colisoes entre todos os personagens da lista for(i = 0; i<count-1 ; i++) for(j = i+1; j < count; j++) if(!this->l_personagens[i]->isEnding() && !this->l_personagens[j]->isEnding()) checkCollision(this->l_personagens[i], this->l_personagens[j]); } void GerenciadorColisoes::gerenciarColisoesPO() { int i, j; // Obtem nro de personagens e obstaculos long count_personagens = this->l_personagens.getCount(), count_obstaculos = this->l_obstaculos.getCount(); // Verifica colisoes entre todos os personagens e obstaculos for(i = 0; i < count_personagens; i++) for (j = 0; j < count_obstaculos; j++) if(!this->l_personagens[i]->isEnding() && !this->l_obstaculos[j]->isEnding()) checkCollision(this->l_personagens[i], this->l_obstaculos[j]); } void GerenciadorColisoes::checkCollision(Personagem *personagem){ // Obtem posicao/tamanho personagem const FloatRect& bounds = personagem->getGlobalBounds(); // Verifica colisao com chao do mapa if (this->mapa.isSolidPixel(Vector2f(bounds.left, bounds.top + bounds.height)) || this->mapa.isSolidPixel(Vector2f(bounds.left + bounds.width, bounds.top + bounds.height))) personagem->onYCollision(true); else personagem->onYCollision(false); // Verifica colisao com paredes if (this->mapa.isSolidPixel(Vector2f(bounds.left, bounds.top + bounds.height-10)) || this->mapa.isSolidPixel(Vector2f(bounds.left + bounds.width, bounds.top + bounds.height-10))) personagem->onXCollision(true); else personagem->onXCollision(false); } void GerenciadorColisoes::checkCollision(Personagem *personagem_a, Personagem *personagem_b) { // Calcula vetor de distancia e distancia maxima const Vector2f distance = Entidade::distanceV(personagem_a, personagem_b), max_distance = Entidade::maxDistanceV(personagem_a, personagem_b); // Verifica colisao em X if (distance.x <= max_distance.x && sqrt(distance.y < max_distance.y - 100)){ personagem_a->onXCollision(true); personagem_b->onXCollision(true); } // Verifica colisao em Y if (distance.y <= max_distance.y && distance.x < max_distance.x - 100){ personagem_a->onYCollision(true); personagem_b->onYCollision(true); } } void GerenciadorColisoes::checkCollision(Personagem *personagem, Obstaculo *obstaculo) { // Calcula vetor de distancia e distancia maxima const Vector2f distance = Entidade::distanceV(personagem, obstaculo), max_distance = Entidade::maxDistanceV(personagem, obstaculo); // Verifica colisao if ((distance.x <= max_distance.x && distance.y < max_distance.y) && (distance.y <= max_distance.y && distance.x < max_distance.x)) { obstaculo->onCollision(personagem); } } void GerenciadorColisoes::add(Personagem *personagem) { this->l_personagens += personagem; } void GerenciadorColisoes::add(Obstaculo *obstaculo) { this->l_obstaculos += obstaculo; } void GerenciadorColisoes::clearEndingObj() { this->l_personagens.clearEnding(); this->l_obstaculos.clearEnding(); } void GerenciadorColisoes::clear(){ this->l_personagens.clear(); } // Operators void GerenciadorColisoes::operator+=(Personagem *personagem){ this->add(personagem); } void GerenciadorColisoes::operator+=(Obstaculo *obstaculo){ this->add(obstaculo); } }}
true
a544955ab8e723b44ba6ee3c2483b388ec36ca1c
C++
mdevman/CSC016
/Node/list.cpp
UTF-8
6,788
3.5
4
[]
no_license
# include "list.h" # include <cstddef> # include <iostream> using namespace std; //# include <stddef.h> List::List() //:next(0), data(0) { first = NULL; } /* List::List(DataType data, Node * next) { this->data = data; this->next = next; } */ void List::insert(DataType data) { Node * tempPtr = new Node(data, first); first = tempPtr; } void List::pushFront(DataType data) { Node * tempPtr = new Node(data, first); first = tempPtr; } void List::pushEnd(DataType data) { Node * tempPtr = new Node(data, last); first = tempPtr; } void List::pushAt(DataType data) { Node * tempPtr = new Node(data, first); first = tempPtr; } void List::display() { Node * tempPtr = first; while (tempPtr != NULL) { cout<<tempPtr->data<<" "; tempPtr = tempPtr->next; } cout<<endl; } void List::deleteByVal(DataType data) { Node * tempPtr = first; Node * prevPtr = first; while (tempPtr != NULL) { if (tempPtr->data == data) { //Possible function call //deleteNode(prevPtr, tempPtr, first); //Does first point to the current Node // then first needs to be changed to point to the next if (tempPtr == first) { first = tempPtr->next; break; } //Does the current Node's next points to Null // change the previous Node's next to point to Null else if (tempPtr->next == NULL) { //prevPtr->next = 0; prevPtr->next = NULL; break; } //Else we are in middle of list // change the previous Node's next to be the current Node's next else { prevPtr->next = tempPtr->next; break; } } // prevPtr = tempPtr; tempPtr = tempPtr->next; } //Does the current Node's next points to Null // change the previous Node's next to point to Null //if (tempPtr->data == data) && (tempPtr->next = NULL) //If I am on the last node, check to see if the data matches /* if (tempPtr->data == data) { //prevPtr->next = 0; prevPtr->next = NULL; } */ delete tempPtr; //delete prevPtr; } void List::deleteByPosition(int pos) { Node * tempPtr = first; Node * prevPtr = first; //The user will give us a number associated to the position, but the list is zero based... int intEndPos = pos - 1; //Check to see if the user has entered a bad position if (intEndPos < 0) { //delete tempPtr; return; } for (int i = 0; i <= intEndPos; i++) { //if we have looped to the pos minus 1, then delete the node if (i == intEndPos) { //Does first point to the current Node // then first needs to be changed to point to the next if (tempPtr == first) { first = tempPtr->next; //cout << "In tempPtr == first" << endl; break; } //Does the current Node's next points to Null // change the previous Node's next to point to Null else if (tempPtr->next == NULL) { //prevPtr->next = 0; prevPtr->next = NULL; //cout << "tempPtr->next == NULL" << endl; break; } //Else we are in middle of list // change the previous Node's next to be the current Node's next else { prevPtr->next = tempPtr->next; //cout << "ELSE" << endl; break; } } //if we get to the node whose next points to null break, did not find Node at position if (tempPtr->next == NULL) { //break; //cout << "ELSE" << endl; //delete tempPtr; return; } prevPtr = tempPtr; tempPtr = tempPtr->next; } //delete tempPtr; } /* void deleteNode(Node prevPtr, Node tempPtr, Node first) { //Does first point to the current Node // then first needs to be changed to point to the next if (tempPtr == first) { first = tempPtr->next; break; } //Does the current Node's next points to Null // change the previous Node's next to point to Null else if (tempPtr->next == NULL) { //prevPtr->next = 0; prevPtr->next = NULL; break; } //Else we are in middle of list // change the previous Node's next to be the current Node's next else { prevPtr->next = tempPtr->next; break; } } */ void List::insert(int pos, DataType data) { //Initial insert code //Node * tempPtr = new Node(data, first); //first = tempPtr; //See if the list is empty if (first == NULL) { //cout << "list is empty" << endl; Node * tempPtr = new Node(data, first); first = tempPtr; return; } Node * tempPtr = first; Node * prevPtr = first; //The user will give us a number associated to the position, but the list is zero based... int intEndPos = pos - 1; //Check to see if the user has entered a bad position if (intEndPos < 0) { return; } for (int i = 0; i <= intEndPos; i++) { //if we have looped to the pos minus 1, then delete the node if (i == intEndPos) { //Does first point to the current Node and next point to NULL and inserting into zeroth position // then first needs to be changed to point to the current and current next need to point to first if (tempPtr == first && tempPtr->next == NULL && intEndPos == 0) { //cout << "In tempPtr == first and next is null and endpos = 0" << endl; Node * newPtr = new Node(data, NULL); tempPtr->next = newPtr; //first = newPtr; break; } //Does first point to the current Node and next point to NULL and inserting into first position // then first needs to be changed to point to the current and current next need to point to first else if (tempPtr == first && tempPtr->next == NULL && intEndPos == 1) { //cout << "In tempPtr == first anbd next is null and endpos = 1" << endl; Node * newPtr = new Node(data, first); first = newPtr; break; } //Does first point to NULL, the list is empty // then first needs to be changed to point to the current and current next need to point to first else if (first == NULL) { //cout << "first == NULL" << endl; Node * newPtr = new Node(data, first); first = newPtr; break; } //Does tempPtr == first, insert in front // then first needs to be changed to point to the current and current next need to point to first else if (tempPtr == first) { //cout << "tempPtr == first" << endl; Node * newPtr = new Node(data, tempPtr->next); tempPtr->next = newPtr; first = newPtr; break; } //Else we are in middle of list // change the previous Node's next to be the current Node's next else { //cout << "ELSE in loop" << endl; Node * newPtr = new Node(data, tempPtr->next); tempPtr->next = newPtr; //first = newPtr; break; } } //if we get to the node whose next points to null break, did not find Node at position if (tempPtr->next == NULL) { //cout << "ELSE" << endl; //delete tempPtr; //return; continue; } prevPtr = tempPtr; tempPtr = tempPtr->next; } //delete tempPtr; }
true
6249852cd705de29f11a298d04e8bf5e2896f378
C++
spectrum968/dfwbi
/httpd/svm/LSFitting.h
UTF-8
2,373
2.65625
3
[]
no_license
#ifndef LSFITTING_H #define LSFITTING_H #include <boost/numeric/ublas/io.hpp> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/ublas/vector_expression.hpp> #include <boost/numeric/ublas/matrix_expression.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics/stats.hpp> #include <boost/accumulators/statistics/mean.hpp> #include <boost/accumulators/statistics/variance.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> using namespace boost::accumulators; using namespace boost::numeric::ublas; namespace lsf { template <typename T> bool InvertMatrix(const matrix<T> &input, matrix<T> &inverse) { typedef permutation_matrix<std::size_t> pmatrix; // create a working copy of the input matrix<T> A(input); // create a permutation matrix for the LU-factorization pmatrix pm(A.size1()); // perform LU-factorization int res = lu_factorize(A,pm); if( res != 0 ) return false; // create identity matrix of "inverse" inverse.assign(identity_matrix<T>(A.size1())); // backsubstitute to get the inverse lu_substitute(A, pm, inverse); return true; } template <typename Type> class LSFitting { public: LSFitting( const matrix<Type> &xn, const vector<Type> &yn) { m_x=xn; m_y=yn; pars.resize(xn.size2()); } ~LSFitting() { } void calcParams() { matrix<Type> xx=prod(trans (m_x),m_x); vector<Type> xy=prod(trans (m_x),m_y); matrix<Type> Invxx(xx.size1(),xx.size2()); InvertMatrix(xx,Invxx); pars=prod(Invxx,xy); } void calcVar() { vector<Type> u=m_y-prod(m_x,pars); accumulator_set<Type, stats<tag::variance > > acc; for(typename vector<Type>::iterator it=u.begin();it!=u.end();++it) { acc(*it); } var=variance(acc); } vector<Type> getParams() const { return pars; } Type getVar() const { return var; } private: matrix<Type> m_x; vector<Type> m_y; vector<Type> pars; // fitted parameters Type var; // fitted functions }; } // namespace itlab #endif // LSFITTING_H
true
521a24ee60ac098aa9998ce8397f087a2a1aab81
C++
steventfan/CS14
/Week5/Tree.cpp
UTF-8
20,980
3.34375
3
[ "BSD-3-Clause" ]
permissive
#include <iostream> #include <string> #include "Tree.h" Tree::Tree( ) { root = 0; } Tree::~Tree( ) { //calls deconstructor helper function deletion(root); } void Tree::insert(const string &data) { if(root == 0) { root = new Node(data); return; } Node *current = root; while(1) { //if current has no children if(current->left == 0 && current->middle == 0 && current->right == 0) { if(current->large.empty() ) { if(data > current->small) { current->large = data; } else { current->large = current->small; current->small = data; } } else { split(current, data, 0, 0); } return; } //else current has children else { if(data < current->small) { current = current->left; } else if( !(current->large.empty() ) ) { if(data < current->large) { current = current->middle; } else if(data > current->large) { current = current->right; } } else if(data > current->large) { current = current->right; } } } } void Tree::preOrder( ) const { preOrder(root); std::cout << std::endl; } void Tree::inOrder( ) const { inOrder(root); std::cout << std::endl; } void Tree::postOrder( ) const { postOrder(root); std::cout << std::endl; } void Tree::remove(const string &data) { if( !(search(data) ) ) { return; } Node *current = search(root, data); Node *swap = current; //find successor or itself if none //initial movement from node if(current->middle != 0 && current->small == data) { swap = current->middle; } else if(current->right != 0) { swap = current->right; } //find inorder successor while(swap->left != 0 || swap->middle != 0 || swap->right != 0) { swap = swap->left; } if(current->small == data) { current->small = swap->small; //if node to delete is a 2-node, fix if(swap->large.empty() ) { swap->small.clear(); fix(swap, 0); } else { swap->small = swap->large; swap->large.clear(); } } else { if(current != swap) { current->large = swap->small; //if node to delete is a 2-node, fix if(swap->large.empty() ) { swap->small.clear(); fix(swap, 0); } else { swap->small = swap->large; swap->large.clear(); } } else { swap->large.clear(); } } } bool Tree::search(const string &data) const { //if search is true, returns Node*, else returns 0 (false) return search(root, data); } void Tree::split(Node *current, const string& data, Node *leftChild, Node *rightChild) { std::string midValue; Node *leftNode; Node *rightNode; //find small, middle, and large value if(data > current->small && data < current->large) { midValue = data; leftNode = new Node(current->small); rightNode = new Node(current->large); } else if(current->small > data) { midValue = current->small; leftNode = new Node(data); rightNode = new Node(current->large); } else { midValue = current->large; leftNode = new Node(current->small); rightNode = new Node(data); } //append middle value to parent/create new parent if(current->parent == 0) { root = new Node(midValue); root->left = leftNode; leftNode->parent = root; root->right = rightNode; rightNode->parent = root; } else if(current->parent->large.empty() ) { if(midValue > current->parent->small) { current->parent->large = midValue; } else { current->parent->large = current->parent->small; current->parent->small = midValue; } if(leftNode->small < current->parent->small) { current->parent->left = leftNode; current->parent->middle = rightNode; } else { current->parent->middle = leftNode; current->parent->right = rightNode; } leftNode->parent = current->parent; rightNode->parent = current->parent; } else { split(current->parent, midValue, leftNode, rightNode); } //if current is not a leaf, connect with previous values from recursion if(current->left != 0 || current->middle != 0 || current->right != 0) { if(leftChild->small < leftNode->small) { leftNode->left = leftChild; leftChild->parent = leftNode; leftNode->right = rightChild; rightChild->parent = leftNode; rightNode->left = current->middle; rightNode->left->parent = rightNode; rightNode->right = current->right; rightNode->right->parent = rightNode; } else if(rightChild->small > rightNode->small) { leftNode->left = current->left; leftNode->left->parent = leftNode; leftNode->right = current->middle; leftNode->right->parent = leftNode; rightNode->left = leftChild; leftChild->parent = rightNode; rightNode->right = rightChild; rightChild->parent = rightNode; } else { leftNode->left = current->left; leftNode->left->parent = leftNode; leftNode->right = leftChild; leftChild->parent = leftNode; rightNode->left = rightChild; rightChild->parent = rightNode; rightNode->right = current->right; rightNode->right->parent = rightNode; } } delete current; } void Tree::preOrder(Node *current) const { if(current != 0) { if(current->large.empty() ) { std::cout << current->small << ", "; preOrder(current->left); preOrder(current->right); } else { std::cout << current->small << ", "; preOrder(current->left); std::cout << current->large << ", "; preOrder(current->middle); preOrder(current->right); } } } void Tree::inOrder(Node *current) const { if(current != 0) { if(current->large.empty() ) { inOrder(current->left); std::cout << current->small << ", "; inOrder(current->right); } else { inOrder(current->left); std::cout << current->small << ", "; inOrder(current->middle); std::cout << current->large << ", "; inOrder(current->right); } } } void Tree::postOrder(Node *current) const { if(current != 0) { if(current->large.empty() ) { postOrder(current->left); postOrder(current->right); std::cout << current->small << ", "; } else { postOrder(current->left); postOrder(current->middle); std::cout << current->small << ", "; postOrder(current->right); std::cout << current->large << ", "; } } } Node * Tree::search(Node *current, const string &data) const { if(current != 0) { if(data == current->small) { return current; } if(data < current->small) { return search(current->left, data); } else if(current->large.empty() ) { return search(current->right, data); } else { if(data == current->large) { return current; } else if(data < current->large) { return search(current->middle, data); } else { return search(current->right, data); } } } return 0; } void Tree::fix(Node *current, Node *child) { if(current == root) { if(current->left != 0 || current->right != 0) { root = child; } else { root = 0; } delete current; return; } //if node to delete has no 3-node siblings (merge) if(current->parent->left->large.empty() && current->parent->middle->large.empty() && current->parent->right->large.empty() ) { //if node is parent's left child if(current->parent->left == current) { current = current->parent; current->left->small = current->small; if(current->large.empty() ) { current->left->large = current->right->small; current->small.clear(); if(child != 0) { current->left->left = child; child->parent = current->left; current->left->middle = current->right->left; current->left->middle->parent = current->left; current->left->right = current->right->right; current->left->right->parent = current->left; } delete current->right; current->right = 0; fix(current, current->left); } else { current->left->large = current->middle->small; current->small = current->large; current->large.clear(); if(child != 0) { current->left->left = child; child->parent = current->left; current->left->middle = current->middle->left; current->left->middle->parent = current->left; current->left->right = current->middle->right; current->left->right->parent = current->left; } delete current->middle; current->middle = 0; } } //else if node is parent's right child else if(current->parent->right == current) { current = current->parent; if(current->large.empty() ) { current->left->large = current->small; current->small.clear(); delete current->right; current->right = 0; if(child != 0) { current->left->middle = current->left->right; current->left->middle->parent = current->left; current->left->right = child; child->parent = current->left; } fix(current, current->left); } else { current->right->large = current->large; current->large.clear(); current->right->small = current->middle->small; if(child != 0) { current->right->right = child; child->parent = current->right; current->right->middle = current->middle->right; current->right->middle->parent = current->right; current->right->left = current->middle->left; current->right->left->parent = current->right; } delete current->middle; current->middle = 0; } } //else node is parent's middle child else { current = current->parent; current->left->large = current->small; current->small = current->large; current->large.clear(); if(child != 0) { current->left->middle = current->left->right; current->left->middle->parent = current->left; current->left->right = child; child->parent = current->left; } delete current->middle; current->middle = 0; } } //else node to delete has 3-node siblings (redistribute) else { //if node is parent's left child if(current->parent->left == current) { current = current->parent; current->left->small = current->small; if(current->large.empty() ) { current->small = current->right->small; current->right->small = current->right->large; current->right->large.clear(); if(child != 0) { current->left->left = child; child->parent = current->left; current->left->right = current->right->left; current->left->right->parent = current->left; current->right->left = current->right->middle; current->right->left->parent = current->right; current->right->middle = 0; } } else { current->small = current->middle->small; if(current->middle->large.empty() ) { current->middle->small = current->large; current->large = current->right->small; current->right->small = current->right->large; current->right->large.clear(); if(child != 0) { current->left->left = child; child->parent = current->left; current->left->right = current->middle->left; current->left->right->parent = current->left; current->middle->left = current->middle->right; current->middle->left->parent = current->middle; current->middle->right = current->right->left; current->middle->right->parent = current->middle; current->right->left = current->right->middle; current->right->left->parent = current->right; current->right->middle = 0; } } else { current->middle->small = current->middle->large; current->middle->large.clear(); if(child != 0) { current->left->left = child; child->parent = current->left; current->left->right = current->middle->left; current->left->right->parent = current->left; current->middle->left = current->middle->right; current->middle->left->parent = current->middle; current->middle->right = current->right->left; current->middle->right->parent = current->middle; current->right->left = current->right->middle; current->right->left->parent = current->right; current->right->middle = 0; } } } } //else if node is parent's right child else if(current->parent->right == current) { current = current->parent; if(current->large.empty() ) { current->right->small = current->small; current->small = current->left->large; current->left->large.clear(); if(child != 0) { current->right->right = child; child->parent = current->right; current->right->left = current->left->right; current->right->left->parent = current->right; current->left->right = current->left->middle; current->left->right->parent = current->left; current->left->middle = 0; } } else { current->right->small = current->large; if(current->middle->large.empty() ) { current->large = current->middle->small; current->middle->small = current->small; current->small = current->left->large; current->left->large.clear(); if(child != 0) { current->right->right = child; child->parent = current->right; current->right->left = current->middle->right; current->right->left->parent = current->right; current->middle->right = current->middle->left; current->middle->right->parent = current->middle; current->middle->left = current->left->right; current->middle->left->parent = current->middle; current->left->right = current->left->middle; current->left->right->parent = current->left; current->left->middle = 0; } } else { current->large = current->middle->large; current->middle->large.clear(); if(child != 0) { current->right->right = child; child->parent = current->right; current->right->left = current->middle->right; current->right->left->parent = current->right; current->middle->right = current->middle->middle; current->middle->right->parent = current->middle; current->middle->middle = 0; } } } } //else node is parent's middle child else { current = current->parent; if(current->right->large.empty() ) { current->middle->small = current->small; current->small = current->left->large; current->left->large.clear(); if(child != 0) { current->middle->right = child; child->parent = current->middle; current->middle->left = current->left->right; current->middle->left->parent = current->middle; current->left->right = current->left->middle; current->left->right->parent = current->left; current->left->middle = 0; } } else { current->middle->small = current->large; current->large = current->right->small; current->right->small = current->right->large; current->right->large.clear(); if(child != 0) { current->middle->left = child; child->parent = current->middle; current->middle->right = current->right->left; current->middle->right->parent = current->middle; current->right->left = current->right->middle; current->right->left->parent = current->right; current->right->middle = 0; } } } } } void Tree::deletion(Node *current) { if(current != 0) { if(current->large.empty() ) { deletion(current->left); deletion(current->right); delete current; } else { deletion(current->left); deletion(current->middle); deletion(current->right); delete current; } } }
true
8b5202646503f082a0742f930308db716059bdce
C++
Wei-YB/WebServer
/EventLoopThreadPool.h
UTF-8
905
2.734375
3
[]
no_license
#pragma once #include <functional> #include <memory> #include <vector> #include "EventLoopThread.h" #include "Util.h" START_NAMESPACE class EventLoop; class EventLoopThread; class EventLoopThreadPool { public: using ThreadInitCallback = std::function<void(EventLoop*)>; EventLoopThreadPool(size_t size = 4,const std::string& name = "",const ThreadInitCallback& func = ThreadInitCallback()); void start(); EventLoop* getLoop(); [[nodiscard]] const std::vector<EventLoop*>& getAllLoop() const; private: size_t inc() { ++next_; if (next_ == loopSize_) next_ = 0; return next_; } bool started_; const size_t loopSize_; size_t next_; std::string name_; ThreadInitCallback threadInitCallback_; std::vector<EventLoop*> loops_; std::vector<std::unique_ptr<EventLoopThread>> threads_; }; END_NAMESPACE
true
448ba808dbc8f8a7cca76c12230b8e4e8bdf20ae
C++
Danil5656/Lab_4_TiMP
/2_Project/Exception.h
UTF-8
1,353
3.390625
3
[]
no_license
/** * @file Exception.h * @author Соколов Д.А. * @version 1.0 * @brief Описание класса Error * @date 28.05.2021 * @copyright ИБСТ ПГУ */ #pragma once #include <stdexcept> #include <string> using namespace std; /// @brief Класс для обработки ошибок, которые могут возникнуть при взаимодействии с программой /// @details Класс наследует существующий класс обработки исключений с именем "invalid_argument" из библиотеки " class Error : public invalid_argument { public: /// @brief Метод, проверяющий строку для шифрования/расшифрования на наличие ошибки static int Check_s(string str); /// @brief Метод, проверяющий ключ для шифрования/расшифрования на наличие ошибок static int Check_k(wstring str, string sKey); /// @brief Конструктор с параметром /// @details Перегружается вызовом конструктора базового класса Error (const string error) : invalid_argument(error) {}; /// @brief Запрещающий конструктор без параметров Error ()=delete; };
true
3e16d861dceef04a03b65e480e53d55612841967
C++
konstantint/Silverware-H345
/Goldenware/Hardware/Peripherals/mpu6050.h
WINDOWS-1252
7,671
2.734375
3
[ "MIT" ]
permissive
// Generic interface to the MPU6050 (or compatible) I2C six axis accelerometer/gyro chip // See e.g. https://cdn.sparkfun.com/datasheets/Sensors/Accelerometers/RM-MPU-6000A.pdf // Also: https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Datasheet1.pdf // // License: MIT // Author: konstantint, silverx // Based on the work of silverx and other contributors to the Silverware project. #pragma once #include <algorithm> #include <array> #include "../../Common/defines.h" #include "../../Common/point3d.h" enum class Mpu6050GyroRange { D250 = 0, D500 = 1, D1000 = 2, D2000 = 3 }; enum class Mpu6050AccRange { G2 = 0, G4 = 1, G8 = 2, G16 = 3 }; template<Mpu6050GyroRange GyroRange, Mpu6050AccRange AccRange> struct Mpu6050Data { // Each 16-bit accelerometer measurement has a full scale defined in ACCEL_FS (Register 28). For // each full scale setting, the accelerometers sensitivity per LSB in ACCEL_xOUT is shown in the table // below. // ACCEL_FS Range Sensitivity // 0 2g 16384 LSB/g // 1 4g 8192 LSB/g // 2 8g 4096 LSB/g // 3 16g 2048 LSB/g Point3d<int16_t> acc; // Each 16-bit gyroscope measurement has a full scale defined in FS_SEL (Register 27). For each full // scale setting, the gyroscopes sensitivity per LSB in GYRO_xOUT is shown in the table below: // FS_SEL Range Sensitivity // 0 250 /s 131 LSB//s // 1 500 /s 65.5 LSB//s // 2 1000 /s 32.8 LSB//s // 3 2000 /s 16.4 LSB//s Point3d<int16_t> gyro; #ifdef MPU6050_USE_TEMPERATURE_SENSOR // Temperature in C = (TEMP_OUT Register Value as a signed quantity)/340 + 36.53 int16_t temp; // Temperature in Celsius inline float temp_c() { // Actually every MPU6050 clone has its own calibration parameters, // these are from the original MPU6050 datasheet // TODO: Make the code chip-specific return (float)temp / 340.0f + 36.53; } #endif // Acceleration in Gs (assuming max sensitivity setting) inline Point3d<float> acc_g() { if (AccRange == Mpu6050AccRange::G2) return acc.cast<float>() / 16384.0; if (AccRange == Mpu6050AccRange::G4) return acc.cast<float>() / 8192.5; if (AccRange == Mpu6050AccRange::G8) return acc.cast<float>() / 4096.8; else // G16 return acc.cast<float>() / 2048.0; } // Gyro readings in degrees per second (assuming max sensitivity setting) inline Point3d<float> gyro_dps() { if (GyroRange == Mpu6050GyroRange::D250) return gyro.cast<float>() / 131.0; if (GyroRange == Mpu6050GyroRange::D500) return gyro.cast<float>() / 65.5; if (GyroRange == Mpu6050GyroRange::D1000) return gyro.cast<float>() / 32.8; else // D2000 return gyro.cast<float>() / 16.4; } }; // Registers constexpr uint8_t R_PWR_MGMT_1 = 0x6B; constexpr uint8_t R_GYRO_CONFIG = 0x1B; constexpr uint8_t R_ACCEL_CONFIG = 0x1C; constexpr uint8_t R_WHO_AM_I = 0x75; constexpr uint8_t R_CONFIG = 0x1A; constexpr uint8_t R_ACCEL_DATA = 0x3B; constexpr uint8_t R_TEMP_DATA = 0x41; constexpr uint8_t R_GYRO_DATA = 0x43; template<typename I2c, typename Clock, // Default = Max range / min sensitivity for both gyro and accelerometer Mpu6050GyroRange GyroRange = Mpu6050GyroRange::D2000, Mpu6050AccRange AccRange = Mpu6050AccRange::G16> class Mpu6050 { I2c& _i2c; Clock& _clock; Mpu6050Data<GyroRange, AccRange> _data; uint8_t _slave_id; public: inline Mpu6050(I2c& i2c, Clock& clock, uint8_t slave_id) : _i2c(i2c), _clock(clock), _data(), _slave_id(slave_id) { // Reset all registers to 0 (in particular this sets max sensitivities for Gyro and Accel) device_reset(); // This is important (otherwise the sensitivity setting is not respected) _clock.delay_us(40000); // Upon power up, the MPU-60X0 clock source defaults to the internal oscillator. However, it is highly // recommended that the device be configured to use one of the gyroscopes (or an external clock // source) as the clock reference for improved stability constexpr uint8_t TEMP_DIS_BIT = 1 << 3; constexpr uint8_t CLKSRC_PLL_GYRO_X = 1; // Set Gyro X as the oscillator. i2c.write_register(slave_id, R_PWR_MGMT_1, CLKSRC_PLL_GYRO_X #ifndef MPU6050_USE_TEMPERATURE_SENSOR // .. and disable the temperature sensor | TEMP_DIS_BIT #endif ); // Configure Gyro and Accel sensitivity i2c.write_register(slave_id, R_GYRO_CONFIG, (int) GyroRange << 3); i2c.write_register(slave_id, R_ACCEL_CONFIG, (int) AccRange << 3); // Enable low-pass filtering for Gyro & Accelerometer // DBPL_CFG Acc_LP_Bandwidth_Hz Acc_LP_Delay_ms Gyro_Bandwidth_Hz Gyro_Delay_ms Gyro_Fs_kHz // 0 260 0 256 0.98 8 // 1 184 2 188 1.9 1 // 2 94 3 98 2.8 1 // 3 44 4.9 42 4.8 1 // 4 21 8.5 20 8.3 1 // 5 10 13.8 10 13.4 1 // 6 5 19.0 5 18.6 1 i2c.write_register(slave_id, R_CONFIG, 3); // Silverware had this as well, not applicable to JJRC H345 (the only board tested so far) // int newboard = !(0x68 == i2c_readreg(117) ); // if (newboard) i2c_writereg(29, ACC_LOW_PASS_FILTER); } void device_reset() { constexpr uint8_t DEVICE_RESET_BIT = 1 << 7; _i2c.write_register(_slave_id, R_PWR_MGMT_1, DEVICE_RESET_BIT); } // Read accelerometer, Gyro and temperature values bool read_all() { uint8_t buffer[14]; bool status = _i2c.read_data(_slave_id, R_ACCEL_DATA, buffer, 14); _data.acc.x() = (int16_t) ((buffer[0] << 8) | buffer[1]); _data.acc.y() = (int16_t) ((buffer[2] << 8) | buffer[3]); _data.acc.z() = (int16_t) ((buffer[4] << 8) | buffer[5]); _data.gyro.x() = (int16_t)((buffer[8] << 8) | buffer[9]); _data.gyro.y() = (int16_t)((buffer[10] << 8) | buffer[11]); _data.gyro.z() = (int16_t)((buffer[12] << 8) | buffer[13]); #ifdef MPU6050_USE_TEMPERATURE_SENSOR _data.temp = (int16_t)((buffer[6] << 8) | buffer[7]); #endif return status; } #ifdef MPU6050_USE_TEMPERATURE_SENSOR // Read temperature data bool read_temperature() { uint8_t buffer[6]; bool status = _i2c.read_data(_slave_id, R_TEMP_DATA, buffer, 2); _data.temp = (int16_t)((buffer[0] << 8) | buffer[1]); return status; } #endif // Read only the accelerometer values bool read_acc() { uint8_t buffer[6]; bool status = _i2c.read_data(_slave_id, R_ACCEL_DATA, buffer, 6); _data.acc.x() = (int16_t) ((buffer[0] << 8) | buffer[1]); _data.acc.y() = (int16_t) ((buffer[2] << 8) | buffer[3]); _data.acc.z() = (int16_t) ((buffer[4] << 8) | buffer[5]); return status; } // Read only the gyro values bool read_gyro() { uint8_t buffer[6]; bool status = _i2c.read_data(_slave_id, R_GYRO_DATA, buffer, 6); _data.gyro.x() = (int16_t) ((buffer[0] << 8) | buffer[1]); _data.gyro.y() = (int16_t) ((buffer[2] << 8) | buffer[3]); _data.gyro.z() = (int16_t) ((buffer[4] << 8) | buffer[5]); return status; } // Verify that the Gyro responds to a "whoami" request with one of known gyro board ids. // NB: There's actualy a real 'self-test' function built into MPU6050, but we don't use it here inline bool self_test() { constexpr static std::array<uint8_t, 4> known_gyros = { 0x68 /* MPU6050 datasheet */, 0x98, 0x7D /* H345's M540 */, 0x72 }; uint8_t who_am_i = _i2c.read_register(_slave_id, R_WHO_AM_I); return std::find(known_gyros.begin(), known_gyros.end(), who_am_i) != known_gyros.end(); } inline Mpu6050Data<GyroRange, AccRange>& data() { return _data; } };
true
3a6bd47eb1d0c5b16cc87b89db1868b2f2be2963
C++
aberry5621/COMP235-Lab-20170425-Sets-And-Maps
/COMP235 Lab 20170425/main.cpp
UTF-8
3,851
3.328125
3
[]
no_license
#include <set> #include <map> #include <iterator> //for ostream_iterator #include <regex> #include <sstream> #include <string> #include <iostream> using namespace std; int main() { /* Part 1 (STL::set) Copy and paste this into your IDE. Extract words into a set, display the set. */ string gdp = { "GDP is commonly used as an indicator of the economic\ health of a country, as well as a gauge of a country's \ standard of living. Since the mode of measuring GDP is\ uniform from country to country, GDP can be used to \ compare the productivity of various countries with a \ high degree of accuracy. Adjusting for inflation from \ year to year allows for the seamless comparison of \ current GDP measurements with measurements from previous \ years or quarters. In this way, a nation's GDP from any \ period can be measured as a percentage relative to \ previous years or quarters. When measured in this way, \ GDP can be tracked over long spans of time and used in \ measuring a nation's economic growth or decline, as well \ as in determining if an economy is in recession. GDP's \ popularity as an economic indicator in part stems from \ its measuring of value added through economic processes. \ For example, when a ship is built, GDP does not reflect \ the total value of the completed ship, but rather the \ difference in values of the completed ship and of the \ materials used in its construction. Measuring total \ value instead of value added would greatly reduce GDP's \ functionality as an indicator of progress or decline, \ specifically within individual industries and sectors. \ Proponents of the use of GDP as an economic measure \ tout its ability to be broken down in this way and \ thereby serve as an indicator of the failure or success \ of economic policy as well. For example, from 2004 to \ 2014 France's GDP increased by 53.1%, while Japan's \ increased by 6.9% during the same period." }; //Convert everthing to lowercase for (int i = 0; i < gdp.length(); i++) gdp[i] = tolower(gdp[i]); //Get rid of everything except a-z or space regex e("[^a-zA-Z\\s]"); gdp = regex_replace(gdp, e, ""); //TO DO (1): Move words into a set multiset<string> gdpMultiSet; stringstream ss; ss << gdp; string line; while (!ss.eof()) { ss >> line; gdpMultiSet.insert(line); } set<string>::iterator setIterator = gdpMultiSet.begin(); cout << "CONTENT: \n"; for (; setIterator != gdpMultiSet.end(); setIterator++) { cout << *setIterator << endl; } //TO DO (2): Use the copy algorithm to iterate and display your set cout << "PART 2!====================\n"; // mapped dictionary map<string, int> word_counts; set<string>::iterator another_set_iterator = gdpMultiSet.begin(); cout << "CONTENT: \n"; for (; another_set_iterator != gdpMultiSet.end(); another_set_iterator++) { string word = *another_set_iterator; cout << "WORD: " << word << "\n"; if (word_counts.count(word) == 0) { word_counts[*another_set_iterator]; word_counts[*another_set_iterator]++; } else if (word_counts.count(word) > 0) { word_counts[*another_set_iterator]++; } } // iterator map<string, int>::iterator map_itr = word_counts.begin(); while (map_itr != word_counts.end()) { cout << map_itr->first << " " << map_itr->second << endl; map_itr++; } cout << endl; return 0; }
true
2f352d407c5ca0eb0b037938e0ecb30349b81fbb
C++
hellonaro/BOJ
/14002.cpp
UTF-8
1,375
3.59375
4
[]
no_license
#include <iostream> #include <vector> #include <stack> using namespace std; /* 수열 A가 주어졌을 때, 가장 긴 증가하는 부분 수열을 구하는 프로그램을 작성하시오. 예를 들어, 수열 A = {10, 20, 10, 30, 20, 50} 인 경우에 가장 긴 증가하는 부분 수열은 A = {10, 20, 10, 30, 20, 50} 이고, 길이는 4이다. */ int main(){ int a; cin >> a; vector<pair<int, int>> numbers(a); vector<int> dist(a, 1); int ans = 1; int ans_idx = 0; for(int i=0; i<a; i++){ int num; cin >> num; numbers[i].first = num; numbers[i].second = -1; } for(int i=0; i<a; i++){ for(int j=i+1; j<a; j++){ if(numbers[i].first < numbers[j].first){ if(dist[i]+1 > dist[j]){ dist[j] = dist[i]+1; numbers[j].second = i; if(dist[j] > ans){ ans = dist[j]; ans_idx = j; } } } } } stack<pair<int, int>> s; s.push(numbers[ans_idx]); while(s.top().second >= 0){ int before_idx = s.top().second; s.push(numbers[before_idx]); } cout << ans << endl; while(!s.empty()){ cout << s.top().first << " "; s.pop(); } return 0; }
true
f95cb028348c706af0625ce18f4aee65826b2d99
C++
evgen1a/homework1
/mai5.cpp
UTF-8
293
3.265625
3
[]
no_license
#include <iostream> using namespace std; void fun (float a) { float b; b = 1.8 * a + 32.0; cout<< a << " degrees Celsius is " << b <<" degrees Fahnrenheit"; } int main() { float a; cout << "Please enter a Celsius value:"; cin >> a; fun(a); return 0; }
true
526b7442359adbc8bfd53d81ddb3dbd86b415913
C++
gengyouchen/leetcode
/minimum-window-substring/sliding-window-solution.cpp
UTF-8
964
3.078125
3
[]
no_license
class Counter { private: int char2count[128] = {}, char2threshold[128] = {}; int nMatched = 0, nTargeted; public: Counter(const string& target) : nTargeted(target.size()) { for (char c : target) ++char2threshold[c]; } void add(char c) { if (char2threshold[c] && char2count[c]++ < char2threshold[c]) ++nMatched; }; void remove(char c) { if (char2threshold[c] && --char2count[c] < char2threshold[c]) --nMatched; } bool isMatched() const { return nMatched == nTargeted; } }; class Solution { public: /* time: O(|s| + |t|), space: O(|charset|) */ static string minWindow(const string& s, const string& t) { const int n = s.size(); Counter window(t); int ansL = 0, ansR = INT_MAX, L = 0; for (int R = 0; R < n; ++R) { window.add(s[R]); while (window.isMatched()) { if (R - L < ansR - ansL) ansL = L, ansR = R; window.remove(s[L++]); } } return (ansR == INT_MAX) ? "" : s.substr(ansL, ansR - ansL + 1); } };
true
cb52bab15b45c8e69eef90f73fbbebe267f786d7
C++
cqd123123/complier
/complier/Quadcode.h
UTF-8
1,446
2.5625
3
[]
no_license
#ifndef _COMPILER_QUADCODE #define _COMPILER_QUADCODE #pragma warning(disable:4786) #include "symbol.h" #include "SymbolTable.h" #include <VECTOR> class Quadcode { public: const enum Quad_type { ADD, // ASSIGN, // MUL, // SUB, // DIV,//divide INV,//inverse CALL,//call FUNC, PROC, //not uesd JMP, JGT,//jump greater than JGE,//jump great equal JEQ,//jump eq JNE, JLE,//jump less equal JLT,//jump less than LABEL, READ, WRITE, PARAM,//parameter SREF,//set reference ENDF, ENDP, RET, PUSH, POP, MAIN,//main proc begin ENDM,//whole proc end SIND, LINE, }; Quadcode(); static Quadcode* new_Quad_code(Quad_type,symbol*, symbol* , symbol*);//arithmetic static Quadcode* new_Quad_code(Quad_type,symbol*,symbol*);//inverse, etc static Quadcode* new_Quad_code(Quad_type,symbol*);//jmp label static Quadcode* new_Quad_code(Quad_type);//fun,proc.. unsigned int get_index() const; void set_index(unsigned int index); unsigned int get_args_size() const; Quad_type get_quad_type() const; bool is_enable() const; void disable(); symbol* get_obj_arg(); std::vector<symbol*> get_src_arg(); std::vector<symbol*> get_all_sym(); static void reset(); friend void operator<<(std::ostream&, const Quadcode&); private: Quad_type type; symbol* obj; std::vector<symbol*> src; unsigned int index; std::vector<symbol*> symbols; static unsigned int counter; bool enable; }; #endif
true
8a5b18d0af824091caa72bc58ca5353ca6a8b3ac
C++
Ilyazykov/DNA-methylation
/DNAmethylation/CourseWork/OrdinaryLeastSquares.cpp
UTF-8
855
3.03125
3
[]
no_license
#include "OrdinaryLeastSquares.h" OrdinaryLeastSquares::OrdinaryLeastSquares() { } OrdinaryLeastSquares::OrdinaryLeastSquares( vector<double> x, vector<double> y ) { getLinearRegression(x, y); } void OrdinaryLeastSquares::getLinearRegression( vector<double> x, vector<double> y ) { if (x.size() != y.size()) throw exception("Size of vectors is different"); int n = x.size(); double sumOfY = 0; double sumOfX = 0; double sumOfXY = 0; double sumOfXsq = 0; for (int i=0;i<n;i++) { sumOfY += y[i]; sumOfX += x[i]; sumOfXY += x[i] * y[i]; sumOfXsq += x[i] * x[i]; } beta = (n*sumOfXY - sumOfX*sumOfY)/(n*sumOfXsq - sumOfX*sumOfX); alpha = (sumOfY - beta*sumOfX)/(double)n; } double OrdinaryLeastSquares::getError( double x, double y ) const { return y - beta*x - alpha; } OrdinaryLeastSquares::~OrdinaryLeastSquares( void ) { }
true
8d10478ecdd3e3f266ba9d668736fe0619cd9d6a
C++
tleek135/university
/CS202/lab1/Account.h
UTF-8
745
3.203125
3
[]
no_license
#ifndef ACCOUNT_H #define ACCOUNT_H /*************************************** * Kyle Lee * Account.h * April 8, 2015 * This file declares the Account class. ***************************************/ //This class simulates a bank account, with a balance and deposit/withdrawal options. //It can also accept an interest rate and calculate the interest. class Account { private: double balance; double interest_rate; //for example, interest_rate = 6 means 6% public: Account(); Account(double amount, double rate); void deposit(double); bool withdraw(double); //returns true if enough money, returns false otherwise double query(); void set_interest_rate (double rate); double get_interest_rate(); void add_interest(); }; #endif
true
ef6dfe93a6a3c3126cfac393c4b5cbc0cc13c992
C++
mickkn/E2PRJ2
/Implementering/SW PC/Release/Release/Release/brugerUI.cpp
ISO-8859-15
8,197
3.3125
3
[]
no_license
#include "brugerUI.h" #include <iostream> #include <conio.h> #include <string> #include <iomanip> using namespace std; brugerUI::brugerUI(hukommelse *hu) { huPtr = hu; } void brugerUI::showMenu(int menu) { while(1) { if(menu == 0) // vis prelogin menu. Login og vis status kan vlges { menu = preLogin(); } if(menu == 1) // login menu. bruger skal login p DE2 eller tryk ESC { login(); } if(menu == 2) // main menu. { menu = mainMenu(); } if(menu == 3) // vis status menu { } if(menu == 4) // aktiver menu { } if(menu == 5) // deaktiver menu { } if(menu == 6) // rediger sms modtager menu {} if(menu == 7) // tilfj / fjern enheder menu {} } } int brugerUI::preLogin() const { system("cls"); // clear screen. cout << "CSS: Child Security System" << endl << endl; cout << " 1. Login" << endl; cout << " 2. Udlaes status" << endl; char temp; while(1) { string retur; cin.clear(); getline(cin, retur,'\n'); if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); } if(retur == "1") return 1; if(retur == "2") return 2; cin.clear(); } } void brugerUI::login() const { system("cls"); // clear screen cout << "CSS: Child Security System" << endl << endl; cout << " Login paa DE2 boardet" << endl << endl << endl << endl; cout << " Tryk paa en vilkaarlig tast for at annullere" << endl; } int brugerUI::mainMenu() const { system("cls"); // clear screen cout << "CSS: Child Security System" << endl << endl; cout << " 1. Aktiver enheder" << endl; cout << " 2. Deaktiver enheder" << endl; cout << " 3. Udlaes status" << endl; cout << " 4. Rediger sms-modtager" << endl; cout << " 5. Tilfoej / fjern enheder" << endl; return 0; } int brugerUI::aktiverMenu() const { system("cls"); // clear screen string temp; cout << "Foelgende enheder er aktiveret:" << endl << endl; int myArray[15] = {0}; int count; vector<string> tempVector = huPtr->getEnheder(); for(int i = 1; i<tempVector.size(); i++) { if(tempVector[i] == "true") { if(i == 1) count = 1; else count = i/3; temp = tempVector[i-1]; cout << " " << int(count) << ". Udtag " << temp << endl; } } cout << endl << "Foelgende enheder kan aktiveres: " << endl << endl; int counter2 = 0; for(int i = 1; i<tempVector.size(); i++) { if(tempVector[i] == "false") { temp = tempVector[i-1]; if(i == 1) count = 1; else count = i/3; cout << " " << int(count) << ". Udtag " << temp << endl; myArray[counter2] = i; counter2++; } } cout << endl << "Tast 27 for at gaa tilbage til hovedemenuen" << endl; int num; cin >> num; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); return 100; } if(num == 27) // Controller loop bliver exited return 27; // loop til at kontrollere om indtastet vrdi var en valid valgmulighed for(int i = 0; i<15; i++) { if(num*3 == myArray[i] || num == 1) { if(num == 1) return 1; return num; } } // ikke ndret p noget da der er tastet forkert return 100; } int brugerUI::deaktiverMenu() const { system("cls"); // clear screen string temp; cout << "Foelgende enheder er deaktiveret:" << endl << endl; int myArray[15] = {0}; int count; vector<string> tempVector = huPtr->getEnheder(); for(int i = 1; i<tempVector.size(); i++) { if(tempVector[i] == "false") { if(i == 1) count = 1; else count = i/3; temp = tempVector[i-1]; cout << " " << int(count) << ". Udtag " << temp << endl; } } cout << endl << "Foelgende enheder kan deaktiveres: " << endl << endl; int counter2 = 0; for(int i = 1; i<tempVector.size(); i++) { if(tempVector[i] == "true") { temp = tempVector[i-1]; if(i == 1) count = 1; else count = i/3; cout << " " << int(count) << ". Udtag " << temp << endl; myArray[counter2] = i; counter2++; } } cout << endl << "Tast 27 for at gaa tilbage til hovedemenuen" << endl; int num; cin >> num; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); return 100; } if(num == 27) return 27; // Controller loop bliver exited for(int i = 0; i<15; i++) { if(num*3 == myArray[i] || num == 1) { if(num == 1) return 1; return num; } } return 100; // ikke ndret p noget da der er tastet forkert } int brugerUI::visStatusMenu() const { system("cls"); // clear screen vector<string> tempVector = huPtr->getEnheder(); cout << "Enhederne har foelgende status" << endl << endl; int size = (tempVector.size() - 1) / 3; int counter; for(int i = 1; i<size+1; i++) { counter = ((i*3) - 2); string navn = tempVector[counter+1]; cout << setw(15) << navn << ": "; if(tempVector[counter+2] == "false") cout << setw(15) << "Deaktiv" << endl; if(tempVector[counter+2] == "true") cout << setw(15) << "Aktiv" << endl; } cout << endl << "Tast 27 for at gaa tilbage til hovedemenuen" << endl; int num; cin >> num; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); return 0; } if(num == 27) mainMenu(); return 0; // return nada } int brugerUI::redigerSmsMenu() const { system("cls"); // clear screen int num = huPtr->getNumber(); cout << "SMS modtager:" << endl; cout << "Tlf nr: " << num << endl << endl; cout << "Tryk 1. for at aendre tlf nr." << endl << endl; cout << "Tryk 27 for at gaa tilbage til hovedmenu" << endl << endl; int retur; cin >> retur; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); return 100; } if(retur == 27) return 0; if(retur == 1) { do { cout << "Indtast et 8 cifret tlf nr." << endl << endl; cin >> retur; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); } if(retur == 27) return 0; if(retur > 99999999 || retur <10000000) cout << "Nummer er ikke rigtigt. Det skal vre mindre end 99999999 og stoerre end 10000000" << endl; }while(retur > 99999999 || retur <10000000); } return retur; } int brugerUI::addRemoveMenu() const { system("cls"); // clear screen vector<string> tempVector = huPtr->getEnheder(); int move; cout << endl << "Du har foelgende enheder:" << endl << endl; for(int i = 1; i<=(tempVector.size()-1)/3; i++) { int move = ((i*3) - 2); string text = tempVector[move+1]; string adres = tempVector[move]; cout << setw(4) << int(i) << ". " << setw(16) << text << setw(16) << adres << endl; } int retur; if(tempVector.size() >= 46) { cout << "Der kan ikke tilfoejes flere enheder" << endl << "Slet nogle enheder hvis der oenskes at tilfoeje nye" << endl; cout << endl << "Tryk 1 for fjern enhed" << endl << endl; cout << "Tast 27 for at annullere" << endl; while(1) { cin >> retur; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); } if(retur == 1) return 0; if(retur == 27) return 27; } } else { cout << "Oensker du at tilfoeje eller fjerne udtag?" << endl << endl; cout << "Tast 1 for fjerne enhed" << endl; cout << "Tast 2 for tilfoeje enhed." << endl << endl; cout << "Tast 27 for at annullere" << endl; while(1) { int retur; cin >> retur; if(!cin) // Hvis brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); } if(!cin) // Hvi brugeren indtaster nogeet der ikke er int { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); } if(retur == 1) return 0; if(retur == 27) return 27; if(retur == 2); return 1; } } }
true
3f5ba60117a473f5924a9ea595d63f57ef2ac6c0
C++
KryEdge/Pong-Raylib
/Project1/src/cpp/GameOVER.cpp
UTF-8
1,298
2.53125
3
[]
no_license
#include "GOver.h" #include "raylib.h" #include "Players.h" #include "game.h" #include "GMenu.h" namespace Carceglia { const int victory = 5; void endGame() { BeginDrawing(); ClearBackground(BLACK); if (contadorP1 == victory) { DrawText("Felicidades Jugador 1!", 100, screenHeight / 4, 50, WHITE); } if (contadorP2 == victory && !IA) { DrawText("Felicidades Jugador 2!", 100, screenHeight / 4, 50, WHITE); } else if (contadorP2 == victory && IA) { DrawText("Ha ganado la maquina", 180, screenHeight / 4, 40, WHITE); DrawText("sos una decepcion para la humanidad", 20, (screenHeight / 4) + 40, 40, WHITE); } DrawText(FormatText(" %i", contadorP1), 260, 300, 30, WHITE); DrawText(FormatText("Puntaje J1:"), 100, 300, 30, WHITE); DrawText(FormatText(" %i", contadorP2), 570, 300, 30, WHITE); DrawText(FormatText("Puntaje J2:"), 400, 300, 30, WHITE); DrawText("Para jugar otra vez presione Enter", 100, 350, 35, WHITE); if (IsKeyPressed(KEY_ENTER)) { game = true; contadorP1 = 0; contadorP2 = 0; } DrawText("Para volver al menu presione Q", 100, 390, 35, WHITE); if (IsKeyPressed(KEY_Q)) { Initialize = false; contadorP1 = 0; contadorP2 = 0; } EndDrawing(); } }
true
45fcb017edce10eaa1e4531c0c5282329ae7e1a6
C++
ysh4296/compiler
/syntax_analyzer/lexical_analyzer.cpp
UTF-8
7,884
3.28125
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <cstring> using namespace std; typedef pair<int, int> ii; //New type definition for token table typedef pair<string, string> ss; //New type definition for Output String ii DFA_table[15][56][127]; // DFA table //in(current_automata, current_state,input_character) -> out(next_automata,next_state) string EndState_table[15][56]; // EndState table //in(current_automata, current_state) -> out(token_type) void DFA_table_in() //Fill in the DFA table from "table.txt" which is in same directory { ifstream is; is.open("table.txt"); int input[5]; //"table.txt" is consist of five integer ( current automata, current state, input character, next automata, next state) if (is.is_open()) { while (!is.eof()) { for (int i = 0; i < 5; i++) is >> input[i]; DFA_table[input[0]][input[1]][input[2]] = { input[3],input[4] }; //fill the table with certain order } } is.close(); } void EndState_table_in() //Fill in the EndState table from "type.txt" which is in same directory { ifstream is; is.open("type.txt"); //"type.txt" is consist of two integer and one string ( current automata, current state, token type) string re; int input[2]; if (is.is_open()) { while (!is.eof()) { for (int i = 0; i < 2; i++) is >> input[i]; is >> re; EndState_table[input[0]][input[1]] = re; //fill the type with certain order } } is.close(); } int main(int argc, char* argv[]) { #pragma region Initialization int auto_num = 1; //current automata, default==1 /* automata_num [0]: end automata_num [1]: start point automata_num [2]: single charactor automata_num [3]: string automata_num [4]: signed integer + operator’-’ automata_num [5]: semicolon automata_num [6]: id + special statement + boolean + Vtype automata_num [7]: () automata_num [8]: [] automata_num [9]: {} automata_num [10]: arithmetic operator(except for ‘-’) automata_num [11]: assign &comparison operator automata_num [12]: comma automata_num [13]: white space */ int cur_state = 0; //current state, default==0 int line_num = 1; //current line number int token_index = 1;//indicate which position of current token in current line char input; //input character for current index vector<ss> answer; //output string for the result of parsing string str = ""; //temp variable for literal string //open input file from parameter of main function ifstream readFile; readFile.open(argv[1]); //save input strings to buffer string buf = string((std::istreambuf_iterator<char>(readFile)), std::istreambuf_iterator<char>()); // get the table for parsing DFA_table_in(); EndState_table_in(); #pragma endregion for (int i = 0; i < (int)buf.size(); i++) //iterate by lenghth of string { input = buf[i]; //get current character from buffer ii next = DFA_table[auto_num][cur_state][(int)input]; //by searching DFA_table with current automata, current state, input character, find the next state if ((next.first == 0 && next.second == 0)) //if the result==(0,0), which means not defined in DFA_table( end state) { if (EndState_table[auto_num][cur_state] == "") {// if the pair of automata and state is not defined in EndState_table when the token ends, break if ((int)input != 10) str += buf[i];//make the wrong array break; } else //if the pair of automata and state is defined in the EndState_table = normal exit { //condition checking for '-'operator if (auto_num == 4 && cur_state != 2)//if current automata is 4(single integer), and state is not 2(operator '-') { if (str[0] == '-') {//if the token next to '-'(except blanks) is one of identifier,integer, or right paren, push the token as operator '-' if (answer.size() != 0) { if (strcmp(answer[(int)answer.size() - 1].first.c_str(), "Identifier") == 0 || strcmp(answer[(int)answer.size() - 1].first.c_str(), "Signed_integer") == 0 || strcmp(answer[(int)answer.size() - 1].first.c_str(), "RSparen") == 0) { answer.push_back({ EndState_table[4][2],"-" }); //push as operator str.erase(0, 1); //erase '-' } } } } //if the token is not white space(automata number==13), push token to result string if (auto_num != 13) answer.push_back({ EndState_table[auto_num][cur_state],str }); //increase token index token_index++; //initialize variables auto_num = 1; cur_state = 0; i--; str = ""; continue; //continue the loop } } if ((int)input == 10) { line_num++; token_index = 1; answer.push_back({ "newLine","" }); } //if the token is not in end state //move the pointer to next stage and concatenate the input character auto_num = next.first; cur_state = next.second; if ((int)input != 10) str += input; } if (EndState_table[auto_num][cur_state] == "") //if the last token is not defined in EndState_table after end of parsing, print error { answer.clear(); answer.push_back({ "error", "lexical_error : there can't be token named '" + str + "' in " + to_string(token_index / 2) + "th token of line number " + to_string(line_num) }); } else {//condition checking for '-'operator if (auto_num == 4 && cur_state != 2)//if current automata is 4(single integer), and state is not 2(operator '-') { if (str[0] == '-') { //if the token next to '-'(except blanks) is one of identifier,integer, or right paren, push the token as operator '-' if (strcmp(answer[(int)answer.size() - 1].first.c_str(), "Identifier") == 0 || strcmp(answer[(int)answer.size() - 1].first.c_str(), "Signed_integer") == 0 || strcmp(answer[(int)answer.size() - 1].first.c_str(), "RSparen") == 0) { answer.push_back({ EndState_table[4][2],"-" }); //push as operator str.erase(0, 1); //erase '-' } } } //if the token is not white space(automata number==13), push token to result string if (auto_num != 13) answer.push_back({ EndState_table[auto_num][cur_state],str }); } //file out ofstream writeFile; writeFile.open("output.txt"); for (int i = 0; i < (int)answer.size(); i++) //after end of parsing, print all the result on console screen { //if the token name is error, print error if (strcmp(answer[i].first.c_str(), "error") == 0) { cout << answer[i].second << endl; writeFile.write(answer[i].second.c_str(), (int)answer[i].second.size()); break; } if (strcmp(answer[i].first.c_str(), "newLine") == 0) { writeFile.write("\n", 1); continue; } //format : <Token_Type,Token_Name> string line = "~" + answer[i].first + ":" + answer[i].second + "|"; writeFile.write(line.c_str(), (int)line.size()); } return 0; }
true
9149c12fa00d664aee49a910d6200a404d3a4f0d
C++
mln-lchs/Moteur3D
/Moteur3D/RigidBody.cpp
ISO-8859-1
3,527
2.859375
3
[]
no_license
#include "pch.h" #include "RigidBody.h" #include <math.h> /* Constructeur */ RigidBody::RigidBody() { inverseMass = 0; linearDamping = 0; position = Vecteur3D(); velocity = Vecteur3D(); orientation = Quaternion(); rotation = Vecteur3D(); transformMatrix = Matrix4(); inverseInertiaTensor = Matrix3(); forceAccum = Vecteur3D(); torqueAccum = Vecteur3D(); } /* Constructeur */ RigidBody::RigidBody(float inverseMass, float linearDamping, float angularDamping, Vecteur3D position, Vecteur3D velocity, Quaternion orientation, Vecteur3D rotation, Matrix3 inverseInertiaTensor) { this->inverseMass = inverseMass; this->linearDamping = linearDamping; this->angularDamping = angularDamping; this->position = position; this->velocity = velocity; this->orientation = orientation; this->rotation = rotation; this->transformMatrix = Matrix4(); this->inverseInertiaTensor = inverseInertiaTensor; computeDerivedData(); } /* Destructeur */ RigidBody::~RigidBody() { } /* Renvoie la masse du corps rigide */ float RigidBody::getMass() { return 1.0f/inverseMass; } /* Renvoie l'inverse de la masse du corps rigide */ float RigidBody::getInverseMass() { return inverseMass; } /* Renvoie la matrice de transformation */ Matrix4 RigidBody::getTransformMatrix() { return transformMatrix; } /* Calcule l'inverse du nouveau tenseur d'inertie */ void RigidBody::computeDerivedData() { transformMatrix = Matrix4(); transformMatrix.setOrientation(orientation); transformMatrix.setTranslation(position); Matrix3 transformMatrix3 = transformMatrix.extractMatrix3(); inverseInertiaTensorUpdated = transformMatrix3.multiplicationMat(inverseInertiaTensor.multiplicationMat(transformMatrix3.inverse())); } /* Vide les accumulateurs de forces et de torques */ void RigidBody::clearAccumulators() { forceAccum.setCoordonnees(0, 0, 0); torqueAccum.setCoordonnees(0, 0, 0); } /* Ajoute une force un point dans le repre du monde */ void RigidBody::addForceAtPoint(Vecteur3D force, Vecteur3D point) { forceAccum.addition(force); Vecteur3D torque = position.soustractionFun(point).produitVectoriel(force); torqueAccum.addition(torque); } /* Ajoute une force un point dans le repre du corps */ void RigidBody::addForceAtBodyPoint(Vecteur3D force, Vecteur3D point) { Vecteur3D newPoint = transformMatrix.inverse().multiplicationVect(point); addForceAtPoint(force, newPoint); } /* Cette mthode met jour les vlocits, la position et l'orientation partir des acclrations */ void RigidBody::integrate(float duration) { // Computing acceleration and angular acceleration Vecteur3D acceleration = forceAccum.multiplicationFun(inverseMass); Vecteur3D angularAcceleration = inverseInertiaTensorUpdated.multiplicationVect(torqueAccum); // Updating velocity acceleration.multiplication(duration); velocity.multiplication(pow(linearDamping,duration)); velocity.addition(acceleration); // Updating rotation angularAcceleration.multiplication(duration); rotation.multiplication(pow(angularDamping, duration)); rotation.addition(angularAcceleration); // Updating position Vecteur3D aux = velocity.multiplicationFun(duration); position.addition(aux); // Updating orientation orientation.updateAngularVelocity(rotation, duration); orientation.normalize(); // Computing transformation matrix and inertia tensor computeDerivedData(); // Clearing accumulators clearAccumulators(); } /* Renvoie la position du corps rigide */ Vecteur3D RigidBody::getPosition() { return position; }
true
0a13cb8c53d0c137fb3e343119d5e6d4d9ca85ed
C++
syamashi/cppmodule
/cpp08/ex02/mutantstack.hpp
UTF-8
3,082
2.859375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mutantstack.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: syamashi <syamashi@student.42tokyo.jp> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/11 10:10:22 by syamashi #+# #+# */ /* Updated: 2021/06/27 18:43:21 by syamashi ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MUTANTSTACK_HPP #define MUTANTSTACK_HPP #include <stack> #include <iostream> template <typename T> class MutantStack : public std::stack<T> { private: public: MutantStack(); ~MutantStack(); MutantStack(const MutantStack &src); MutantStack<T>& operator = (const MutantStack<T> &src); typedef typename std::stack<T>::container_type::iterator iterator; typedef typename std::stack<T>::container_type::const_iterator const_iterator; typedef typename std::stack<T>::container_type::reverse_iterator reverse_iterator; typedef typename std::stack<T>::container_type::const_reverse_iterator const_reverse_iterator; iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; reverse_iterator rbegin(); reverse_iterator rend(); const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; }; template <typename T> MutantStack<T>::MutantStack() : std::stack<T>(){} template <typename T> MutantStack<T>::~MutantStack() {} template <typename T> MutantStack<T>::MutantStack(const MutantStack<T> &src) : std::stack<T>(src) {} template <typename T> MutantStack<T>& MutantStack<T>::operator = (const MutantStack<T> &src) { this->c = src.c; } template <typename T> typename MutantStack<T>::iterator MutantStack<T>::begin(){ return (this->c.begin());} template <typename T> typename MutantStack<T>::iterator MutantStack<T>::end(){ return (this->c.end());} template <typename T> typename MutantStack<T>::const_iterator MutantStack<T>::begin() const { return (this->c.begin());} template <typename T> typename MutantStack<T>::const_iterator MutantStack<T>::end() const { return (this->c.end());} template <typename T> typename MutantStack<T>::reverse_iterator MutantStack<T>::rbegin(){ return (this->c.rbegin());} template <typename T> typename MutantStack<T>::reverse_iterator MutantStack<T>::rend(){ return (this->c.rend());} template <typename T> typename MutantStack<T>::const_reverse_iterator MutantStack<T>::rbegin() const { return (this->c.rbegin());} template <typename T> typename MutantStack<T>::const_reverse_iterator MutantStack<T>::rend() const { return (this->c.rend());} #endif
true
3b2b9171f0739dc9313878b5169a7c23865b46a5
C++
naindejardin/financial_software_projects
/phase1/mmain.cc
UTF-8
4,145
2.625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> #include "SBB_util.h" #include "SBB_date.h" #include "SBB_io.h" #include <math.h> #include "BondCalculator.h" #include "Portfolio.h" using namespace std; int main (int argc, char** argv) { SBB_util util_obj; util_obj.start_clock(); // for(int i=0; i<10000000; i++){} char data_input_file[128]; char yc_input_file[128]; strcpy(data_input_file, argv[1]); strcpy(yc_input_file, argv[2]); SBB_date from_dt; SBB_date to_dt; SBB_instrument_input_file yc_input(yc_input_file); int yc_count; SBB_instrument_fields* yc_array; yc_array = yc_input.get_records(yc_count); int *maturity = new int[yc_count](); //unit is in year for(int i=0;i<yc_count;i++) { from_dt.set_from_yyyymmdd((long)yc_array[i].SettlementDate); to_dt.set_from_yyyymmdd((long)yc_array[i].MaturityDate); maturity[i] = get_num_of_periods(yc_array[i].Frequency,from_dt,to_dt)/yc_array[i].Frequency; } SBB_instrument_input_file data_input(data_input_file); int data_count; //number of data records SBB_instrument_fields* bond_array; bond_array = data_input.get_records(data_count); int total_line = data_input.get_line_count(); //number of lines, include # lines int comment_num = total_line - data_count; int *num_periods = new int[data_count](); double *ytm = new double[data_count](); Portfolio port(data_count,bond_array); //File pointer for read and write FILE * p_rw = fopen(data_input_file,"r+"); if (p_rw == NULL) printf("Error opening file"); char (*lines)[SBB_LINE_BUFFER_LENGTH] = new char[total_line][SBB_LINE_BUFFER_LENGTH]; int *len_arr = new int[total_line]; //record the string length of each line for (int k=0; k<total_line; k++) { fgets(lines[k],SBB_LINE_BUFFER_LENGTH,p_rw); len_arr[k] = strlen(lines[k]); if (k>=comment_num) lines[k][len_arr[k]-1] = ' '; //overwrite \n to be a space } for(int i=0;i<data_count;i++) { /*bond_array[i].show(); cout<<endl;*/ SBB_instrument_fields* bond_record_ptr = &bond_array[i]; from_dt.set_from_yyyymmdd((long)bond_record_ptr->SettlementDate); to_dt.set_from_yyyymmdd((long)bond_record_ptr->MaturityDate); num_periods[i] = get_num_of_periods(bond_record_ptr->Frequency,from_dt,to_dt); if (0==strcmp(bond_record_ptr->RateType,"SPREAD")) { int mat_yrs = num_periods[i]/bond_record_ptr->Frequency; int min_index=0; int min_dis = abs(mat_yrs-maturity[0]); for (int k=0;k<yc_count;k++) { if (abs(mat_yrs-maturity[k])<min_dis) { min_dis = abs(mat_yrs-maturity[k]); min_index=k; } else if (abs(mat_yrs-maturity[k])==min_dis && maturity[k]<mat_yrs) { min_dis = abs(mat_yrs-maturity[k]); min_index=k; } } ytm[i] = yc_array[min_index].Rate + bond_record_ptr->Rate/100; } else { ytm[i] = bond_record_ptr->Rate; } AbstractBondCalculator * calculator_p; if (0 == bond_record_ptr->CouponRate) { calculator_p = new ZeroCouponCalculator( num_periods[i], bond_record_ptr, ytm[i]); } else { calculator_p = new CouponBearingCalculator( num_periods[i], bond_record_ptr, ytm[i]); } port.set_collection_elem(calculator_p,i); char append_str[128]; sprintf(append_str,"%.3f %.3f %.3f %.3f\n", calculator_p->cal_price(), calculator_p->cal_dv01(), calculator_p->cal_risk(), calculator_p->cal_LGD()); strcat(lines[comment_num+i],append_str); //cout<<"after change string read:"<<lines[comment_num+i]<< "length:"<<strlen(lines[comment_num+i])<<endl; //calculator_p->show(); } rewind(p_rw); for (int n=0;n<total_line;n++) { fputs(lines[n],p_rw); } fclose (p_rw); FILE * p_wFile; p_wFile = fopen("results.txt","w"); if (p_wFile==NULL) { printf("ERROR: create results.txt failed! \n"); } fprintf(p_wFile,"%d\n%d\n%.3f\n%.3f\n", port.largest_long_pos(), port.largest_short_pos(), port.most_risk_pos(), port.total_risk()); fclose (p_wFile); //port.show(); delete [] lines; delete [] maturity; delete [] num_periods; delete [] ytm; yc_input.free_records(); data_input.free_records(); util_obj.end_clock(); return 0; }
true
cc020f496bda29561be1fd0c3cdf4970843593bd
C++
AverJing/LeetCode
/LeetCode/PointToOffer/CH05/Ex31FindGreatestSumOfSubArray.cpp
UTF-8
419
3.0625
3
[]
no_license
/* * * *@author: Aver Jing *@description: *@date: * * */ #include <iostream> #include <vector> using std::vector; class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { if (array.empty()) return; int sum = 0, maxNumber = INT_MIN; for (auto e : array) { sum += e; if (e > sum) sum = e; if (sum > maxNumber) maxNumber = sum; } return maxNumber; } }; int main(){ }
true
26643b848ee26ee51909e76d99c3214ab3be9e29
C++
sgluebbert/CISS465NetworkGame
/app/Main.cpp
UTF-8
626
2.71875
3
[]
no_license
#include "../Source/Application/Application.h" int main(int argc, char* argv[]) { bool gui = true; if (argc >= 2) { if (strcmp(argv[1], "help") == 0 || strcmp(argv[1], "h") == 0) { std::cout << "Usage:\n"; std::cout << "\t" << argv[0] << "\n"; std::cout << "\t" << argv[0] << " server [port] [lobby name] [map scale]\n"; return 0; } if (strcmp(argv[1], "server") == 0) gui = false; if (argc >= 3) lobbySetPort = atoi(argv[2]); if (argc >= 4) lobbySetName = argv[3]; if (argc >= 5) lobbySetMapScale = atof(argv[4]); } Application GameApp; return GameApp.Execute(gui); }
true
35b4c179fd7d35c0017d8dbae9eac78e51b676c4
C++
lana555/dynamatic
/resource_sharing/src/bb_graph_reader.h
UTF-8
741
2.578125
3
[ "MIT" ]
permissive
// // Created by pejic on 21/08/19. // #ifndef RESOURCE_MINIMIZATION_BB_GRAPH_READER_H #define RESOURCE_MINIMIZATION_BB_GRAPH_READER_H #include <string> #include <iostream> #include <vector> #include <fstream> using namespace std; class BB_graph { public: struct Link{ int src; int dst; int set_id; vector<int> markedGraphs; Link(string line); Link(int src, int dst, int set_id, vector<int> mgs); friend bool operator== (Link l1, Link l2); friend bool operator!= (Link l1, Link l2); static bool isLink(string line); }; vector<int> bbs; vector<Link> links; static bool isBlock(string line); static int blockId(string line); BB_graph(string filename); }; #endif //RESOURCE_MINIMIZATION_BB_GRAPH_READER_H
true
0f7e4d7b30ae47b4c004cd9523a64ed158a9752b
C++
wutongtoby/mbed13
/13_2_Distance/main.cpp
UTF-8
545
2.53125
3
[]
no_license
#include "mbed.h" #include "bbcar.h" Ticker servo_ticker; Ticker encoder_ticker; PwmOut pin8(D8), pin9(D9); DigitalIn pin3(D3); BBCar car(pin8, pin9, servo_ticker); int main(void) { parallax_encoder encoder0(pin3, encoder_ticker); // set the initial step to 0 encoder0.reset(); car.goStraight(100); // detect if we have arrived at 30cm every 50ms while(encoder0.get_cm() < 30) wait_ms(50); // if we jump out from the loop then we have gone through 30cm, so we // can stop the car! car.stop(); }
true
d084bd7d861de026f5ed13061d889137d9ca2b05
C++
EneRgYCZ/Problems
/Numere_Lipsa/Numere_Lipsa.cpp
UTF-8
340
2.546875
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> using namespace std; ifstream fin ("numere.in"); int n; int main() { fin >> n; int y = n + 1, x; while (fin >> x) { if (x == y) { continue; } else { n--; y = x; } } cout << n; return 0; }
true
8310c01e6e16d3d64955fd86f11480edf6a068df
C++
doctoroyy/algorithm
/天梯赛刷题/L2-011 玩转二叉树 (25 分).cpp
UTF-8
1,121
3.390625
3
[]
no_license
#include<iostream> #include<queue> using namespace std; struct node { node *lchild, *rchild; int ele; node (int x) { ele = x; lchild = rchild = NULL; } }; node* build(int *PreOrder, int *InOrder, int len) { node* root = new node(PreOrder[0]); int root_pos; for (int i = 0; i < len; i++) { if (PreOrder[0] == InOrder[i]) { root_pos = i; break; } } if (root_pos > 0) { root->lchild = build(PreOrder + 1, InOrder, root_pos); } if (len - root_pos - 1) { root->rchild = build(PreOrder + root_pos + 1, InOrder + root_pos + 1, len - root_pos - 1); } return root; } void levelOrder(node* root) { queue<node*> q; q.push(root); while (!q.empty()) { node* tmp = q.front(); q.pop(); if (tmp->rchild) { cout << " " << tmp->ele; } if (tmp->lchild) { cout << " " << tmp->ele; } } } int main() { int n; int PreOrder[100], InOrder[100]; cin >> n; for (int i = 0; i < n; i++) cin >> InOrder[i]; for (int i = 0; i < n; i++) cin >> PreOrder[i]; node* root = build(PreOrder, InOrder, n); levelOrder(root); return 0; }
true
2eab53f8fd884d36d84833ecd0ad678333a58f10
C++
ninc/tddc78
/lab3/main.cpp
UTF-8
3,508
2.734375
3
[]
no_license
// my first program in C++ //export OMP_NUM_THREADS=16 // icpc -xHost -openmp -o main main.cpp //./main //10 times faster as OMP_NUM_THREADS=16 vs 1 //$ompsalloc ./main #include <iostream> #include <stdio.h> #include <math.h> #include <vector> #include "omp.h" const int n = 1000; const int maxiter = 1000; const double tol = 0.001; using namespace std; //Set boundary conditions and initial values for the unknowns int setBoundary(double **T) { int x; int y; for(y = 0; y<n; y++) { for(x = 0; x<n; x++) { //cout << "x, y: " << x << ", " << y << endl; // Set the boundary values if(y == 0 || y == n) { T[x][y] = 1.0f; } else if(x == n) { T[x][y] = 2.0f; } else { T[x][y] = 0.0f; } } } return 0; } //Solve the linear system of equations using the Jacobi method int jacobi(double **T) { int k = 0; int x = 0; int y = 0; double t1, t2; int rank; int threads; double old_value = 0.0f; double global_error = 0.0f; double local_error = 0.0f; double tmp_error = 0.0f; t1 = omp_get_wtime(); for(k = 1; k<maxiter; k++) { global_error = 0.0f; #pragma omp parallel shared(global_error, T, k) private(local_error, tmp_error, old_value, y, x, rank, threads) { local_error = 0.0f; rank = omp_get_thread_num(); threads = omp_get_num_threads(); #pragma omp for //reduction(max: global_error) //Black chess squares for(y = 1; y<n-1; y++) { //Diagonal correction if(y%2) { x = 1; } else { x = 2; } for(; x<n-1; x+=2) { old_value = T[x][y]; T[x][y] = (T[x-1][y] + T[x+1][y] + T[x][y-1] + T[x][y+1]) / 4.0; tmp_error = fabs(old_value - T[x][y]); // Error estimation if(local_error < tmp_error) { local_error = tmp_error; } } } #pragma omp barrier #pragma omp for reduction(max: global_error) //White chess squares for(y = 1; y<n-1; y++) { //Diagonal correction if(y%2) { x = 2; } else { x = 1; } for(; x<n-1; x+=2) { old_value = T[x][y]; T[x][y] = (T[x-1][y] + T[x+1][y] + T[x][y-1] + T[x][y+1]) / 4.0; tmp_error = fabs(old_value - T[x][y]); // Error estimation if(local_error < tmp_error) { local_error = tmp_error; } } // Reduce the amount of updates on shared variable if(global_error < local_error) { global_error = local_error; } } } if(global_error<tol) { break; } } t2 = omp_get_wtime(); cout << "Error estimate: " << global_error << endl; cout << "Number of iterations: " << k << endl; cout << "Temperature of element T(1,1): " << T[1][1] << endl; cout << "Time: " << t2-t1 << endl; return 0; } // Allocates memory double ** initMatrix() { double **T; // Allocate memory T = new double*[n]; for (int i = 0; i < n; ++i) T[i] = new double[n]; return T; } // Cleans the memory bool cleanupMatrix(double **T) { // De-Allocate memory to prevent memory leak for (int i = 0; i < n; ++i) delete [] T[i]; delete [] T; return true; } int main (int argc, char ** argv) { cout << "Initiating matrix" << endl; double **T = initMatrix(); cout << "Initiating boundries" << endl; setBoundary(T); cout << "Boundaries set, calling Jacobi" << endl; jacobi(T); cout << "Cleaning up" << endl; cleanupMatrix(T); return 0; }
true
5e4694a2db99f47c99aae4523a5302cdfb06478f
C++
spraetor/amdis2
/test/utility/int_seq.hpp
UTF-8
1,001
2.984375
3
[ "MIT" ]
permissive
#pragma once // from http://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence/17426611#17426611 namespace AMDiS { template <int...> struct Seq {}; namespace detail { template <int s, class S> struct Concat; template <int s, int ... i> struct Concat<s, Seq<i... >> { using type = Seq<i..., (s + i)... >; }; template <bool, class S> struct IncSeq_if { using type = S; }; template <int... Is> struct IncSeq_if<true, Seq<Is...>> { using type = Seq<Is..., sizeof...(Is)>; }; } // end namespace detail template <int N> struct MakeSeq { using type = typename detail::IncSeq_if< (N % 2 != 0), typename detail::Concat<N/2, typename MakeSeq<N/2>::type>::type >::type; }; // break condition template <> struct MakeSeq<0> { using type = Seq<>; }; // alias template template <int N> using MakeSeq_t = typename MakeSeq<N>::type; } // end namespace AMDiS
true
14dc06cca9250fccac6d70b7c4a3735b2ab6fc60
C++
Harshil-Gupta/ubiquitous-robot
/MinMaxDiff.cpp
UTF-8
838
2.703125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int smallestRangeII(vector<int>& A, int K) { sort(A.begin(),A.end()); int dp1[A.size()],dp2[A.size()]; for(int i=0;i<A.size();i++) { dp1[i]=A[i]+K; dp2[i]=A[i]-K; } if(A.size()==1) return 0; int sum=A[A.size()-1]-A[0]; int n=A.size(); for(int i=0;i<A.size()-1;i++) { int m1=max(dp2[n-1],dp1[i]); int m2=min(dp1[0],dp2[i+1]); sum=min(sum,m1-m2); } return sum; } int main(){ int n;cin>>n; vector<int>v(n); int k;cin>>k; for(int i=0;i<n;i++){ int a;cin>>a; v.push_back(a); } cout << smallestRangeII(v,k) << endl; return 0; }
true
3a377ec54e13489dbebff7ad8df51d81d7a4424b
C++
vt167098/cpp
/[200324]HW6-2.cpp
UTF-8
2,942
2.71875
3
[]
no_license
#include <iostream> #include <vector> #include<sstream> #include <algorithm> using namespace std; int main() { struct Animals { string animal; int qty; }; struct Places { /* data */ string place; vector<struct Animals> result; }; vector<struct Places> data; int i; string data1, data3, input, tmp; int data2; int qty; stringstream ss; struct Animals am; struct Places pl; getline(cin,input); ss<<input; ss>>i; for(int j=0;j<i&&j<1000;j++){ getline(cin, input); tmp.clear(); int l = 0; for (int k=0; k<input.size(); k++){ if (input[k]==' '){ ss.clear(); ss<<tmp; if (l==0){ ss>>am.animal; l++; } else if (l==1){ ss>>am.qty; l++; } else if (l==2){ ss>>pl.place; if (data.empty()){ pl.result.push_back(am); data.push_back(pl); } else { int ds = data.size(); bool place_not_found = true; bool animal_not_found = true; for (int i=0; i<ds; i++){ if (data[i].place == pl.place){ place_not_found = false; int rs=data[i].result.size(); for (int j=0; j<rs; j++){ if (data[i].result[j].animal == am.animal){ data[i].result[j].qty += am.qty; animal_not_found = false; } } } if (i==ds-1){ if (place_not_found && animal_not_found){ pl.result[0] = am; data.push_back(pl); animal_not_found = false; } } if (animal_not_found && data[i].place == pl.place){ data[i].result.push_back(am); animal_not_found = false; } } } l++; } tmp.clear(); } else { tmp+=input[k]; } } } ss>>pl.place; if (data.empty()){ pl.result.push_back(am); data.push_back(pl); } else { int ds = data.size(); bool animal_not_found=true; for (int i=0; i<ds; i++){ if (data[i].place==pl.place){ int rs=data[i].result.size(); for (int j=0; j<rs; j++){ if (data[i].result[j].animal==am.animal){ data[i].result[j].qty+=am.qty; animal_not_found=false; } } } } if (animal_not_found){ pl.result.push_back(am); data.push_back(pl); } } //cout<<rows.size()<<endl; for (vector<struct Places>::iterator it=data.begin(); it!=data.end(); it++){ pl=*it; cout<<pl.place<<":"; for (vector<struct Animals>::iterator it1=pl.result.begin(); it1!=pl.result.end(); it1++){ am=*it1; cout<<am.animal<<" "<<am.qty; if (pl.result.end()!=it1+1) cout<<", "; } cout<<endl; } cout<<endl; return 0; }
true
ba940216ef6c21c9c55227a5b7fd7cc76e6159fc
C++
rekotiira/xd
/include/xd/vendor/glm/core/func_packing.hpp
UTF-8
7,829
2.765625
3
[ "BSL-1.0" ]
permissive
/////////////////////////////////////////////////////////////////////////////////////////////////// // OpenGL Mathematics Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /////////////////////////////////////////////////////////////////////////////////////////////////// // Created : 2010-03-17 // Updated : 2010-03-17 // Licence : This source is under MIT License // File : glm/core/func_packing.hpp /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef glm_core_func_packing #define glm_core_func_packing namespace glm { namespace test{ void main_core_func_packing(); }//namespace test namespace core{ namespace function{ //! Define packing functions from section 8.4 floating-point pack and unpack functions of GLSL 4.00.8 specification namespace packing { /// \addtogroup core_funcs ///@{ //! First, converts each component of the normalized floating-point value v into 8- or 16-bit integer values. //! Then, the results are packed into the returned 32-bit unsigned integer. //! //! The conversion for component c of v to fixed point is done as follows: //! packUnorm2x16: round(clamp(c, 0, +1) * 65535.0) //! //! The first component of the vector will be written to the least significant bits of the output; //! the last component will be written to the most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/packUnorm2x16.xml">GLSL packUnorm2x16 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::uint32 packUnorm2x16(detail::tvec2<detail::float32> const & v); //! First, converts each component of the normalized floating-point value v into 8- or 16-bit integer values. //! Then, the results are packed into the returned 32-bit unsigned integer. //! //! The conversion for component c of v to fixed point is done as follows: //! packUnorm4x8: round(clamp(c, 0, +1) * 255.0) //! //! The first component of the vector will be written to the least significant bits of the output; //! the last component will be written to the most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/packUnorm4x8.xml">GLSL packUnorm4x8 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::uint32 packUnorm4x8(detail::tvec4<detail::float32> const & v); //! First, converts each component of the normalized floating-point value v into 8- or 16-bit integer values. //! Then, the results are packed into the returned 32-bit unsigned integer. //! //! The conversion for component c of v to fixed point is done as follows: //! packSnorm4x8: round(clamp(c, -1, +1) * 127.0) //! //! The first component of the vector will be written to the least significant bits of the output; //! the last component will be written to the most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/packSnorm4x8.xml">GLSL packSnorm4x8 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::uint32 packSnorm4x8(detail::tvec4<detail::float32> const & v); //! First, unpacks a single 32-bit unsigned integer p into a pair of 16-bit unsigned integers, four 8-bit unsigned integers, or four 8-bit signed integers. //! Then, each component is converted to a normalized floating-point value to generate the returned two- or four-component vector. //! //! The conversion for unpacked fixed-point value f to floating point is done as follows: //! unpackUnorm2x16: f / 65535.0 //! //! The first component of the returned vector will be extracted from the least significant bits of the input; //! the last component will be extracted from the most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/unpackUnorm2x16.xml">GLSL unpackUnorm2x16 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::tvec2<detail::float32> unpackUnorm2x16(detail::uint32 const & p); //! First, unpacks a single 32-bit unsigned integer p into a pair of 16-bit unsigned integers, four 8-bit unsigned integers, or four 8-bit signed integers. //! Then, each component is converted to a normalized floating-point value to generate the returned two- or four-component vector. //! //! The conversion for unpacked fixed-point value f to floating point is done as follows: //! unpackUnorm4x8: f / 255.0 //! //! The first component of the returned vector will be extracted from the least significant bits of the input; //! the last component will be extracted from the most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/unpackUnorm4x8.xml">GLSL unpackUnorm4x8 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::tvec4<detail::float32> unpackUnorm4x8(detail::uint32 const & p); //! First, unpacks a single 32-bit unsigned integer p into a pair of 16-bit unsigned integers, four 8-bit unsigned integers, or four 8-bit signed integers. //! Then, each component is converted to a normalized floating-point value to generate the returned two- or four-component vector. //! //! The conversion for unpacked fixed-point value f to floating point is done as follows: //! unpackSnorm4x8: clamp(f / 127.0, -1, +1) //! //! The first component of the returned vector will be extracted from the least significant bits of the input; //! the last component will be extracted from the most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/unpackSnorm4x8.xml">GLSL unpackSnorm4x8 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::tvec4<detail::float32> unpackSnorm4x8(detail::uint32 const & p); //! Returns a double-precision value obtained by packing the components of v into a 64-bit value. //! If an IEEE 754 Inf or NaN is created, it will not signal, and the resulting floating point value is unspecified. //! Otherwise, the bit- level representation of v is preserved. //! The first vector component specifies the 32 least significant bits; //! the second component specifies the 32 most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/packDouble2x32.xml">GLSL packDouble2x32 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 double packDouble2x32(detail::tvec2<detail::uint32> const & v); //! Returns a two-component unsigned integer vector representation of v. //! The bit-level representation of v is preserved. //! The first component of the vector contains the 32 least significant bits of the double; //! the second component consists the 32 most significant bits. //! //! \li <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/unpackDouble2x32.xml">GLSL unpackDouble2x32 man page</a> //! \li GLSL 4.00.08 specification, section 8.4 detail::tvec2<detail::uint32> unpackDouble2x32(double const & v); ///@} }//namespace packing }//namespace function }//namespace core using namespace core::function::packing; }//namespace glm #include "func_packing.inl" #endif//glm_core_func_packing
true
ff26a7f8185f8dc9cd09c5bb912fc7facbfb1cec
C++
chenyuxiaodhr/hacker_rank_solutions
/Algorithms/Bit_Manipulation/Cipher.cpp
UTF-8
959
2.703125
3
[ "MIT" ]
permissive
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <bitset> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n, k; cin >> n >> k; bitset<2000000> b; cin >> b; bitset<1000000> s; if (k >= n) { cout << b[k + n - 2]; s[0] = b[k + n - 2]; for (int i = 1; i < n; i++) { s[i] = b[k + n - 2 - i] ^ b[k + n - 2 - i + 1]; cout << s[i]; } cout << endl; } else { cout << b[k + n - 2]; s[0] = b[k + n - 2]; for (int i = 1; i < k; i++) { s[i] = b[k + n - 2 - i] ^ b[k + n - 2 - i + 1]; cout << s[i]; } for (int i = k; i < n; i++) { s[i] = b[k + n - 2 - i] ^ b[k + n - 2 - i + 1] ^ s[i - k]; cout << s[i]; } cout << endl; } return 0; }
true
8008091ac8a73f64e191bb71ade0f63680835717
C++
innocentboy/myrepository
/src/codee/codchef/PPTEST.cpp
UTF-8
1,167
2.84375
3
[]
no_license
/** http://www.codechef.com/problems/PPTEST NOTE: It's similare to 0-1 knapsack problem. */ /** INPUT: 1 3 7 1 2 3 2 3 5 3 3 3 OUTPUT: 11 */ #include<cstdio> #include<iostream> #include<algorithm> #define N 105 using namespace std; int c[N],p[N],t[N]; int pt[N]; int dp[N][N]; int main() { int i,j,k,test,n,w; scanf("%d",&test); while(test--) { scanf("%d%d",&n,&w); //reset the dp array; for(i=0;i<=w;i++) for(j=0;j<=n;j++) dp[i][j]=0; for(i=0;i<n;i++) scanf("%d%d%d",&c[i],&p[i],&t[i]); for(i=0;i<n;i++) pt[i]=p[i]*c[i]; //calculate the best by knapsack problem. for(i=0;i<=w;i++) { for(j=0;j<n;j++) { if(j==0){ dp[i][j]=(t[j]<=i)?pt[j]:0; continue; } if(i-t[j]>=0&&dp[i][j]<dp[i-t[j]][j-1]+pt[j]) dp[i][j]=max(dp[i][j-1],dp[i-t[j]][j-1]+pt[j]); else dp[i][j]=dp[i][j-1]; } } printf("%d\n",dp[w][n-1]); } return 0; }
true
40580f3d119cf345a3a0413321ec931bbfab06ce
C++
foreignbill/program_training
/NJFU 蓝桥杯模拟赛3/3.cpp
UTF-8
1,449
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int g[6][6], res = 0; bool vis[10]; const int dx[] = {0,0,1,-1,1,1,-1,-1}; const int dy[] = {1,-1,0,0,1,-1,1,-1}; bool check() { for(int i = 1; i <= 3; i++) { for(int j = 1; j <=4; j++) { if( (i == 1 && j == 1) || (i == 3 && j == 4) ) continue; bool ok = true; for(int ii = 0; ii < 8; ii ++) { int nx = i + dx[ii]; int ny = j + dy[ii]; if(g[nx][ny] == -1) continue; if(abs(g[nx][ny] - g[i][j]) == 1) return false; } } } return true; } void dfs(int x, int y) { if(x == 3 && y == 4) { if(check()) res ++; } if((x == 1 && y == 4) || (x == 2 && y == 4)) { for(int i = 0; i < 10; i++) { if(vis[i]) continue; vis[i] = true; g[x][y] = i; dfs(x + 1, 1); g[x][y] = -1; vis[i] = false; } } else { for(int i = 0; i < 10; i++) { if(vis[i]) continue; vis[i] = true; g[x][y] = i; dfs(x, y + 1); g[x][y] = -1; vis[i] = false; } } } int main () { memset(g, -1, sizeof g); memset(vis, 0, sizeof vis); dfs(1, 2); cout << res << endl; return 0; } /* +--+--+--+--+ | | 1| 2| 3| +--+--+--+--+ | 4| 5| 6| 7| +--+--+--+--+ | 8| 9|10| | +--+--+--+--+ */
true
f18af199b548f4dfaef1cdccdbd1470f48582299
C++
jamiehayes45/JamieHayes-CSCI20-Fall2016
/lab6/lab6.cpp
UTF-8
2,267
3.484375
3
[]
no_license
// Created by Jamie Hayes // Description: copyright for ascii // Titile: lab six Intro to Functions // Class: CSCI-20-Fall 2016 MW programming 1 #include <iostream> #include <string> using namespace std; void copyRight () // function { string creator = "Jamie Hayes"; string copyright = "Copy Right"; int year = 2016; // ascii of R2D2 from star wars cout << " ________ " << endl; cout << " / (0) Y " << endl; cout << " __|__________|__ " << endl; cout << " | | * * * | | " << endl; cout << " |__| R2D2 |__| " << endl; cout << " | | (^) | | " << endl; cout << " | |_____:____| | " << endl; cout << " |~ `________/ ~| " << endl; cout << " / = | / = | / = | " << endl; cout << " (____] (____] (____] " << endl; cout << endl; cout << " Star Wars R2D2 " << endl; cout << endl; cout << creator << " " << copyright << " " << year << endl; } int main () { // calls function copyRight(); //Previous lab---------- int favoriteNum; // users favorite number float decimal; // 0.0 char letter; // alphabet a-z string adjective; //users choice cout << "Let's play a mad lib game!!!" << endl; // asks user questions cout << "What is your favotite large number?" << endl; cin >> favoriteNum; cout << endl; cout << "Please choose any decimal number" << endl; cin >> decimal; cout << endl; cout << "Please choose a leter between a-z: " << endl; cin >> letter; cout << endl; cout << "Please choose an adjective: " << endl; cin >> adjective; cout << endl; cout <<"A "<< adjective <<" whale was seen floating "<< decimal; cout <<" feet in the air. Mean while, as the whale floated in the air, a hellium balloon truck "; cout << "crashed on "<< letter <<" street in Sacramento. The sheer amount of "; cout << favoriteNum <<" balloons pushed the "<< adjective; cout <<" whale all the way back to the sea. However, the whale was still stuck "<< decimal; cout <<" feet above the ocean's surface. The poor thing."<< endl; cout <<"Finished! Thanks for playing!"<< endl; return 0; }
true
cf82d31b210abc6ce2ed10cbe153a2f26add271b
C++
adityabettadapura/Algorithms-and-Datastructures
/sorting/wave_sort.cpp
UTF-8
888
3.75
4
[]
no_license
/**************************** Wave Sort algorithm Sorts elements such that a[0] > a[1] < a[2] ... Time: O(n) Space: O(n) Author: Aditya Bettadapura ****************************/ #include<iostream> #include<vector> #include<cstdlib> using namespace std; void PopulateVector(vector<int>& input, int size){ for(int i=0; i<size; i++){ input.push_back(rand()%(size*2)); } } void PrintVector(vector<int>& input){ for(int i=0; i<input.size(); i++){ cout << input[i] << " "; } cout << endl; } void WaveSort(vector<int>& input){ if(input[0] < input[1]) swap(input[0], input[1]); for(int i=2; i<input.size()-1; i+=2){ if(input[i] < input[i-1]) swap(input[i], input[i-1]); if(input[i] < input[i+1]) swap(input[i], input[i+1]); } } int main(){ srand(time(NULL)); vector<int> input; PopulateVector(input, 10); PrintVector(input); WaveSort(input); PrintVector(input); return 0; }
true
22065dfc64e338087319c29b2c5bae3f64415aa5
C++
Lime5005/epitech-1
/tek2/C++/cpp_arcade/src/interfaces/Structures.hpp
UTF-8
2,529
2.65625
3
[]
no_license
/* ** Structures.hpp for cpp_arcade in /home/ventinc/epitech/cpp/cpp_arcade/interfaces/Structures.hpp ** ** Made by Vincent DUSAUTOIR ** Login <vincent.dusautoir@epitech.eu> ** ** Started on Fri Mar 17 15:55:42 2017 Vincent DUSAUTOIR ** Last update Fri Mar 17 15:55:42 2017 Vincent DUSAUTOIR */ #ifndef CPP_ARCADE_STRUCTURES_HPP #define CPP_ARCADE_STRUCTURES_HPP #include <string> namespace arcade { enum eventType { ET_KEYBOARD_CLICK, ET_KEYBOARD_RELEASE, ET_WINDOW_CLOSED, ET_NONE }; enum eventValue { EV_SPACE, EV_ESCAPE, EV_A, EV_B, EV_C, EV_D, EV_E, EV_F, EV_G, EV_H, EV_I, EV_J, EV_K, EV_L, EV_M, EV_N, EV_O, EV_P, EV_Q, EV_R, EV_S, EV_T, EV_U, EV_V, EV_W, EV_X, EV_Y, EV_Z, EV_ENTER, EV_BACKSPACE, EV_UP, // 30 and 2 in protocol EV_DOWN, EV_RIGHT, EV_LEFT, EV_0, EV_1, EV_2, EV_3, EV_4, EV_5, EV_6, EV_7, EV_8, EV_9, EV_UNKNOWN }; typedef struct s_rectangle rectangle; typedef struct s_pos pos; typedef union u_rgb rgb; typedef struct s_text text; typedef struct s_circle circle; struct s_pos { s_pos(uint64_t x = 0, uint64_t y = 0) : x(x), y(y){}; uint64_t x; uint64_t y; }; union u_rgb { u_rgb(unsigned int full) : full(full){}; u_rgb(unsigned char a, unsigned char r, unsigned char g, unsigned char b) { argb[0] = a; argb[1] = r; argb[2] = g; argb[3] = b; }; unsigned char argb[4]; unsigned int full; }; struct s_rectangle { s_rectangle(pos s = pos(0, 0), rgb c = rgb(255, 0, 0, 0), float r = 0, bool f = true, uint64_t t = 0) : size(s), color(c), rotate(r), full(f), thickness(t) {} pos size; rgb color; float rotate; bool full; uint64_t thickness; }; struct s_text { s_text(rgb c = rgb(255, 0, 0, 0), uint64_t fS = 18, float r = 0.0, bool b = false, bool u = false, bool i = false) : color(c), fontSize(fS), rotate(r), bold(b), underline(u), italic(i) {} rgb color; uint64_t fontSize; float rotate; bool bold; bool underline; bool italic; }; struct s_circle { s_circle(rgb c = rgb(255, 0, 0, 0), uint64_t r = 1, bool f = true, uint64_t t = 0) : color(c), radius(r), full(f), thickness(t) {} rgb color; uint64_t radius; bool full; uint64_t thickness; }; } #endif //CPP_ARCADE_STRUCTURES_HPP
true
d75a1f93bdfdc40957cee8f549ebbf674b1db099
C++
veedee2000/SDE_30_DAYS
/Day17/Vertical_View.cpp
UTF-8
698
2.734375
3
[]
no_license
vector<int> verticalOrder(Node *root) { vector<int>ans; map<int, vector<int>>mp; queue<pair<Node*, int>>q; if(root) q.push({root, 0}); while(!q.empty()){ int sz = q.size(); while(sz--){ auto current = q.front(); q.pop(); Node* curr = current.first; int y = current.second; mp[y].push_back(curr -> data); if(curr -> left) q.push({curr -> left, y - 1}); if(curr -> right) q.push({curr -> right, y + 1}); } } for(auto x:mp){ for(auto y:x.second){ ans.push_back(y); } } return ans; }
true
b00551b8cfd0d3538001bfc1b7ce7aea70aa0511
C++
ImLegend4658/Inform-211
/Aldawk_lab4_pro5.cpp
UTF-8
2,288
4.03125
4
[]
no_license
/* Author :Aziz Aldawk Date : 2/10/2016 Language : C++ Purpose : This program about arithmetic calculations (addition, subtraction, multiplication, division) */ #include<iostream> using namespace std; int main() { int value1 = 1, value2 = 2, value3 = 3, value4 = 4; int Num, add, sub, div, mult; int ad, su, di, mu; int result1, result2, result3, result4; //declare variables cout << "Please enter number 1 if you want to addition\n" "Please enter number 2 if you want to subtraction\n" "Please enter number 3 if you want to multiplication\n" "Please enter number 4 if you want to division\n"; //Ask user to choice number if he/she wants //addition, subtraction, multpli or division. cin >> Num; //receive from user. if (Num == value1) // if user choice number 1 than user choice to addition. { cout << "Please enter number twice to calculate addition\n"; //Ask user to enter number twice to calculate. cin >> ad; cin >> add; result1 = add + ad; //Calculate additions. cout << "The result is: " << result1 << endl; //prompt and receive. } if (Num == value2) //if user choice number 2 than user choice to subtraction. { cout << "Please enter number twice to calculate subtraction\n"; //Ask user to enter number twice to calculate subtract. cin >> sub; cin >> su; result2 = sub - su; //Calculate subtraction. cout << "The result is: " << result2 << endl; //prompt and receive. } if (Num == value3) //if user choice number 3 than user choice to multipli. { cout << "Please enter number twice to calculate multiplication\n"; //Ask user to enter number twice to calculate multipli. cin >> mult; cin >> mu; result3 = mult*mu; //Calculate multiplication. cout << "The result is: " << result3 << endl; //prompt and receive. } if (Num == value4) //if user choice number 4 than user choice to division. { cout << "Please enter number twice to calculate division\n"; //Ask user to enter number twice to calcilate division. cin >> di; cin >> div; result4 = di / div; //Calculate division. cout << "The result is: " << result4 << endl; //propt and receive } system("Pause"); //Please pause program. }
true
4e9edafd5af9d98568d442ea2cbf7faf03896380
C++
Mereco/ACM-ZS
/ACM-ZS/ACM1016.cpp
UTF-8
305
2.578125
3
[]
no_license
#include<iostream> using namespace std; int main() { int a=0,b=0,c=0,d=0; cin>>a; b=a%100; if(b>0) { c=a%4; if(c>0) { cout<<"no"<<endl; } else { cout<<"yes"<<endl; } } else { d=a%400; if(d>0) { cout<<"no"<<endl; } else { cout<<"yes"<<endl; } } return 0; }
true
e01e23f37a9a91d73a6b4a2d9674ca51fa1278be
C++
ch812248495/nowcoder
/4.stackAndQueue/MaxInWin.cpp
UTF-8
525
2.75
3
[]
no_license
#include "head.cpp" #include <utility> typedef pair<int, int> Pair; vector<int> maxInWin(vector<int> &num, int size) { vector<int> result; priority_queue<Pair> Q; for(int i = 0; i<size-1; i++) { Q.push(Pair(num[i], i)); } for(int i = size-1; i < num.size(); i++) { Q.push(Pair(num[i], i)); Pair p = Q.top(); while(p.second < i-size+1) { Q.pop(); p = Q.top(); } result.push_back(p.first); } return result; }
true
484066c07b585c06af96f1542dd45c872ba2ca2a
C++
antonidass/BaumanStudy
/sem4/OOP/lab_3/src/scene/scene.cpp
UTF-8
881
2.84375
3
[]
no_license
#include <iterator> #include "../../inc/scene/scene.h" #include "../../inc/object/composite.h" Scene::Scene() : _figures(new Composite) {}; std::vector<std::shared_ptr<Object>> Scene::getFigures() { return _figures->_elements; } std::vector<std::shared_ptr<Camera>> Scene::getCameras() { return _cameras; } std::shared_ptr<Composite> Scene::getComposite() { return _figures; } void Scene::addFigure(const std::shared_ptr<Object> &figure) { _figures->add(figure); } void Scene::removeFigure(const std::size_t index) { auto iter = _figures->begin(); std::advance(iter, index); _figures->remove(iter); } void Scene::addCamera(const std::shared_ptr<Camera> &camera) { _cameras.push_back(camera); } void Scene::removeCamera(const std::size_t index) { auto iter = _cameras.begin(); std::advance(iter, index); _cameras.erase(iter); }
true
3388fc0c9f9ce55ffc9ae89350d480801d28398e
C++
strawberryfg/pascal
/NOIP2010/20100924/all/program/A汤舒扬/concert.cpp
UTF-8
1,005
2.53125
3
[]
no_license
#include<iostream> #include<fstream> #include<cstdio> #include<cstring> #include<cstdlib> #include<string> #include<cmath> #include<algorithm> using namespace std; ifstream fin ("concert.in" ); ofstream fout("concert.out"); #define MAXN 1005 #define MS(S) memset(S,0,sizeof(S)) #define sqr(X) ((X)*(X)) int n,g[MAXN],b[MAXN],sigg[MAXN],sigb[MAXN]; int f[MAXN][MAXN]; int main() { fin >>n; MS(sigg); MS(sigb); for(int i=1;i<=n;++i) { fin >>g[i]; sigg[i] = sigg[i-1]+g[i] ; } for(int i=1;i<=n;++i) { fin >>b[i]; sigb[i] = sigb[i-1]+b[i] ; } MS(f); int p; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) { p=-(0x7FFFFFFF); for(int k1=0;k1<i;++k1) for(int k2=0;k2<j;++k2) p = max( p , f[k1][k2] +g[i]*b[j] -sqr( sigg[i-1] - sigg[k1] ) -sqr( sigb[j-1]-sigb[k2] ) ); f[i][j]=p; } int ans=-(0x7FFFFFFF); for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) ans = max( ans , f[i][j] - sqr( sigg[n]-sigg[i] ) - sqr( sigb[n]-sigg[j] ) ); fout <<ans <<endl; return 0; }
true
d11f7b224d1299ffb2b5ccb72e20d4568901d74c
C++
harpreets152/interviewbit-problems
/Bit Manipulation/min_xor_value.cpp
UTF-8
652
3.5625
4
[]
no_license
/* Given an array of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value. Examples : Input 0 2 5 7 Output 2 (0 XOR 2) Input 0 4 7 9 Output 3 (4 XOR 7) Constraints: 2 <= N <= 100 000 0 <= A[i] <= 1 000 000 000 */ //this is not the best solution to this. int Solution::findMinXor(vector<int> &a) { int i,j,min,n=a.size(); sort(a.begin(),a.end()); min=a[0]^a[1]; for(i=2;i<n;i++){ if((a[i]^a[i-1])<min) min=a[i]^a[i-1]; } return min; } //for best solution,try to implement this with trie(link->https://www.geeksforgeeks.org/minimum-xor-value-pair/)
true
2bc1f3cc1fef0b856e0054fce900cc932fd273ce
C++
abdalimran/Competitive_Programming
/Mathematics Techniques/GCD/GCD.cpp
UTF-8
494
2.96875
3
[]
no_license
/* Bismillah hir rahmanir raheem. Thanks to Allah for everything. Coder: Abdullah Al Imran Email: abdalimran@gmail.com */ #include<bits/stdc++.h> using namespace std; //Recursively int gcd(int a, int b) { if(b==0) return a; else return gcd(b, a%b); } //Shortly int gcd(int a, int b) { return b == 0?a:gcd(b,a%b); } int main() { ios_base::sync_with_stdio(false); //cout<<gcd(8,10)<<endl; cout<< __gcd(8,12)<<endl; //This function works only in gnu gcc/g++ compilers. return 0; }
true
eb28821e62852ed90cdcd7230be5af53b4c0bbcd
C++
GuyOded/Fraction
/Fraction.cpp
UTF-8
9,892
3.703125
4
[]
no_license
/* * fraction.cpp * * Created on: Jan 22, 2016 * Author: guy */ #include "Fraction.h" #include <iostream> #include <stdexcept> #include <cmath> /** * Fraction(int num, int denum = 1) * * @param num * @param denom */ Fraction::Fraction(int num, int denom) { if(denom == 0) { throw std::overflow_error("Division by zero exception"); } /* if the denominator is negative pass the minus sign to * the numerator: -1 1 * --- ---> --- * -1 1 * * 1 -1 * --- ---> --- * -1 1 */ if(denom < 0) { denom *= -1; num *= -1; } m_num = num; m_denom = denom; this->reduceFraction(); } /** * Fraction(const Fraction& f) * * a copy constructor. * * @param f-instance to copy */ Fraction::Fraction(const Fraction& f) { this->m_num = f.m_num; this->m_denom = f.m_denom; } Fraction::~Fraction() { // TODO Auto-generated destructor stub } /** * static Fraction crossAddition(const Fraction& frac1, * const Fraction& frac2) * adds the given fractions using cross multiplication * * @param frac1 * @param frac2 * @return a new fraction that is the addition of the parameters */ Fraction Fraction::crossAddition(const Fraction& frac1, const Fraction& frac2) { int new_num = frac1.m_num * frac2.m_denom; new_num += frac1.m_denom * frac2.m_num; int new_denum = frac1.m_denom* frac2.m_denom; return Fraction(new_num, new_denum); } /** * static Fraction crossSubtraction(const Fraction& frac1, * const Fraction& frac2); * * same as crossAddition except it subtracts * * @param frac1 * @param frac2 * @return a new fraction that is the subtraction of the given parameters */ Fraction Fraction::crossSubtraction(const Fraction& frac1, const Fraction& frac2) { int new_num = frac1.m_num * frac2.m_denom; new_num -= frac1.m_denom * frac2.m_num; int new_denum = frac1.m_denom* frac2.m_denom; return Fraction(new_num, new_denum); } /** * void crossAdd(const Fraction& frac) * * same as crossAddition but changes the instance * that called it * * @param frac- the fraction that is added */ void Fraction::crossAdd(const Fraction& frac) { this->m_num *= frac.m_denom; this->m_num += this->m_denom * frac.m_num; this->m_denom *= frac.m_denom; } /** * void crossSub(const Fraction& frac) * * same as crossSubstraction but changes the instance * that called it * * @param frac */ void Fraction::crossSub(const Fraction& frac) { this->m_num *= frac.m_denom; this->m_num -= this->m_denom * frac.m_num; this->m_denom *= frac.m_denom; } /** * void reduceFraction() * * Reduce the fraction as in 4/6 ---> 2/3 */ void Fraction::reduceFraction() { if(m_num == 0) { m_denom = 1; return; } if(m_num == m_denom) { m_num = 1, m_denom = 1; return; } int min = std::abs(m_num) > m_denom ? m_denom : std::abs(m_num); for(; min > 0; min--) { if((m_num % min == 0) && (m_denom % min == 0)) { m_num /= min; m_denom /= min; return; } } } /** * Fraction getInverse() const * * Inverses the fraction as in- 1/2 ---> 2/1 * * @return a new copy of the inverse fraction */ Fraction Fraction::getInverse() const { return Fraction(this->m_denom, this->m_num); } /** * friend std::ostream& operator <<(std::ostream& lhs, const Fraction& rhs) * * overload insertion operator so Fraction type can be printed * to an output stream * * @param lhs-reference to output stream * @param rhs-the inserted fraction * @return a reference to the left hand operand */ std::ostream& operator<<(std::ostream& lhs, const Fraction& rhs) { lhs << rhs.m_num << '/' << rhs.m_denom; return lhs; } /** * friend Fraction operator+(const Fraction& frac1, const Fraction& frac2) * * overload binary operator +: frac1 + frac2 * * @param frac1 * @param frac2 * @return */ Fraction operator+(const Fraction& lhs, const Fraction& rhs) { Fraction result = Fraction::crossAddition(lhs, rhs); result.reduceFraction(); return result; } /** * friend Fraction operator-(const Fraction& frac1, const Fraction& frac2) * * overload of the binary operator -: lhs - rhs * * @param lhs-left hand operand * @param rhs-right hand operand * @return a new result that is the reduced version of the subtraction */ Fraction operator-(const Fraction& lhs, const Fraction& rhs) { Fraction result = Fraction::crossSubtraction(lhs, rhs); result.reduceFraction(); return result; } /** * friend Fraction operator/(const Fraction& lhs, const Fraction& rhs) * * overload division operator: 1/2 / 2/1 = 1/2 * 1/2 = 1/4 * @param lhs-left hand fraction * @param rhs-right hand fraction * @return a new instance of fraction that is the result of the division */ Fraction operator/(const Fraction& lhs, const Fraction& rhs) { return lhs * rhs.getInverse(); } /** * friend Fraction operator*(const Fraction& lhs, const Fraction& rhs) * * operator of multiplication operator * * @param lhs-left hand operand * @param rhs-right hand operand * @return a new fraction-result */ Fraction operator*(const Fraction& lhs, const Fraction& rhs) { /* note that calling reduce fraction is not needed * as it is called within the constructor */ Fraction result(lhs.m_num * rhs.m_num, lhs.m_denom * rhs.m_denom); /* if the denominator is negative pass the minus sign to * the numerator: -1 1 * --- ---> --- * -1 1 * * 1 -1 * --- ---> --- * -1 1 */ if(result.m_denom < 0) { result.m_num *= -1; result.m_denom *= -1; } return result; } /** * Fraction& operator+=(const Fraction& rhs) * * Addition assignment overload * @param rhs-the added fraction * @return a reference to the current instance */ Fraction& Fraction::operator+=(const Fraction& rhs) { this->crossAdd(rhs); this->reduceFraction(); return *this; } /** * Fraction& operator-=(const Fraction& rhs) * * Subtraction assignment overload * @param rhs-the substructed fraction * @return a reference to this instance to allow chaining */ Fraction& Fraction::operator-=(const Fraction& rhs) { this->crossSub(rhs); this->reduceFraction(); return *this; } /** * Fraction& operator*=(const Fraction& rhs) * * overloading of multiplication assignment operator * * @param rhs-right hand side of the equation * @return a reference to this instance to allow chaining */ Fraction& Fraction::operator*=(const Fraction& rhs) { this->m_num *= rhs.m_num; this->m_denom *= rhs.m_denom; /* if the denominator is negative pass the minus sign to * the numerator: -1 1 * --- ---> --- * -1 1 * * 1 -1 * --- ---> --- * -1 1 */ if(this->m_denom < 0) { this->m_num *= -1; this->m_denom *= -1; } this->reduceFraction(); return *this; } /** * Fraction& operator/=(const Fraction& rhs) * * division assignment operator * * @param rhs-right hand operand * @return a reference to this instance to allow chaining */ Fraction& Fraction::operator/=(const Fraction& rhs) { *this *= rhs.getInverse(); return *this; } /** * Fraction operator-() const * * overload unary negation operator -: fraction = 1/2 * -fraction = -1/2 * Note that the function doesn't change the operand and returns * a new instance * * @return */ Fraction Fraction::operator-() const { return Fraction(-1*this->m_num, this->m_denom); } /** * friend bool operator==(const Fraction& lhs, const Fraction& rhs) * * overload of equality operator == * Fractions are considered equal if their numerators and denumerators * are equal. Note that all the fractions will always be there * most reduced version: 4/6-->2/3 * * @param lhs-left hand fraction * @param rhs-right hand fraction * @return true if the fractions are equal or false if they aren't */ bool operator==(const Fraction& lhs, const Fraction& rhs) { return (lhs.m_num == rhs.m_num) && (lhs.m_denom == rhs.m_denom); } /** * friend bool operator>(const Fraction& lhs, const Fraction& rhs) * * @param lhs-left hand operand * @param rhs-right hand operand * @return true if lhs is greater than rhs or false otherwise */ bool operator>(const Fraction& lhs, const Fraction& rhs) { return (lhs.m_num * rhs.m_denom) > (rhs.m_num * lhs.m_denom); } /** * friend bool operator<(const Fraction& lhs, const Fraction& rhs) * * @param lhs-left hand operand * @param rhs-right hand operand * @return true if rhs is greater than lhs or false otherwise */ bool operator<(const Fraction& lhs, const Fraction& rhs) { return rhs > lhs; } /** * friend bool operator<(const Fraction& lhs, const Fraction& rhs) * * @param lhs-left hand operand * @param rhs-right hand operand * @return true if lhs is greater than or equals to rhs or false otherwise */ bool operator>=(const Fraction& lhs, const Fraction& rhs) { return rhs > lhs || rhs == lhs; } /** * friend bool operator<(const Fraction& lhs, const Fraction& rhs) * * @param lhs-left hand operand * @param rhs-right hand operand * @return true if rhs is greater than or equals to lhs or false otherwise */ bool operator<=(const Fraction& lhs, const Fraction& rhs) { return rhs >= lhs; } /** * Fraction& operator=(const Fraction& rhs) * * overload the assignment operator to return a copy * * @param rhs-the right hand operand- the one that is copied * @return a copy of the right hand operand */ Fraction& Fraction::operator=(const Fraction& rhs) { /*return a copy by calling the copy constructor*/ this->m_num = rhs.m_num; this->m_denom = rhs.m_denom; return *this; } /** * explicit float operator float() const * * converts a Fraction to float - explicit to avoid ambiguity * * @return the ratio represented as a decimal fraction with * the precision of a single floating point */ Fraction::operator float() const { return (float)this->m_num / this->m_denom; }
true
1b2a8b885c093b9537b0d8ff1a3f75d2492aba3f
C++
cwj5012/rdm-cppserver
/src/rdm/database/mysql/DBServiceManager.cpp
UTF-8
2,562
2.546875
3
[ "MIT" ]
permissive
#include <sstream> #include "DBServiceManager.h" #include "DBConnectionPool.h" #include "IDBConnection.h" #include "../../log/Logger.h" #include "../../service/Service.h" #include "../../config/ServerNetConfig.h" namespace rdm { DBServiceManager::DBServiceManager() { if (mDBConnectionPool == nullptr) { // todo 默认登录信息,等没用了删除 db_info_.name = "root"; db_info_.passwd = "1234"; db_info_.ip = "127.0.0.1"; db_info_.port = 3306; mDBConnectionPool = new DBConnectionPool(db_info_); } } DBServiceManager::DBServiceManager(const std::shared_ptr<Service>& service) : service_(service) { if (mDBConnectionPool == nullptr) { auto info = service_.lock()->getServerNetConfig()->getServerNetInfo(); if (!info->mysql_info.host.empty()) { // mysql 信息找到配置 db_info_.name = info->mysql_info.user_name; db_info_.passwd = info->mysql_info.password; db_info_.ip = info->mysql_info.host; try { db_info_.port = std::stoi(info->mysql_info.port); } catch (std::exception& ex) { status_ = 1; LOG_ERROR("{}", ex.what()); return; } mDBConnectionPool = new DBConnectionPool(db_info_); } else { LOG_WARN("mysql host is empty."); status_ = 2; return; } status_ = 0; } } DBServiceManager::~DBServiceManager() { LOG_DEBUG("{}", __PRETTY_FUNCTION__); } DBServiceManager& DBServiceManager::inst() { static DBServiceManager obj; return obj; } void DBServiceManager::setThreadNum(int32_t num) { thread_num_ = num; } int32_t DBServiceManager::getThreadNum() const { return thread_num_; } DBConnectionPool* DBServiceManager::getDBConnectionPool() { return mDBConnectionPool; } bool DBServiceManager::init() { LOG_DEBUG("{}", __PRETTY_FUNCTION__); if (status_ != 0) { return false; } if (mDBConnectionPool == nullptr) { return false; } mDBConnectionPool->initPool(4); LOG_INFO("mysql connection pool num: 4, create success, {}:{}.", db_info_.ip, db_info_.port); for (auto i = 0; i < thread_num_; ++i) { DatabaseLoginInfo info; // DBConnection db_service(info); // db_service.connect(); // // db_connections_.push_back(&db_service); } return true; } int32_t DBServiceManager::status() const { return status_; } }
true
abc16b24a9f46ffa69e6258b94c14c8e2fe4d196
C++
samfubuki/lbcodessolution
/Graph Algorithm Codes/hamiltonianpath2.cpp
UTF-8
681
2.765625
3
[]
no_license
#include <iostream> using namespace std; int result; bool visit[16]; void backtrack(int board[][16],int i,int v,int count){ visit[i]=true; for(int j=1;j<=v;j++){ if(visit[j]==false && board[i][j]==1) backtrack(board,j,v,count+1); } if(count==v-1) result=1; visit[i]=false; return; } int main() { int t; cin>>t; while(t-->0){ int v,e; cin>>v>>e; int board[16][16]; for(int i=0;i<16;i++) for(int j=0;j<16;j++) board[i][j]=0; int u,w; for(int i=0;i<e;i++){ cin>>u>>w; board[u][w]=1; board[w][u]=1; } for(int i=0;i<16;i++) visit[i]=false; result=0; for(int m=1;m<=v;m++) backtrack(board,m,v,0); if(result==1) { cout<<"1"<<endl; } else { cout<<"0"<<endl; } } return 0; }
true
3283fb28c055f27b29c3eeb0c82f8c00f4eece40
C++
chenghui-lee/leetcode
/Code/1326 Minimum Number of Taps to Open to Water a Garden.cpp
UTF-8
735
2.859375
3
[]
no_license
class Solution { public: int minTaps(int n, vector<int>& ranges) { vector<int> jumps(ranges.size(), 0); for(int i=0; i<ranges.size(); i++){ int left = max(0, i - ranges[i]); int right = min(n, i + ranges[i]); jumps[left] = max(jumps[left], right - left); } int curEnd = 0, curFurthest = 0, count = 0; for(int i=0; i<jumps.size()-1; i++){ // jump game II if (i > curFurthest) return -1; curFurthest = max(curFurthest, i + jumps[i]); if (i == curEnd){ curEnd = curFurthest; count++; } } return curFurthest >= n ? count : -1; } };
true
4961ae94da2b1d47458323677601e55893196456
C++
thomas-huet/mapbox-gl-native
/include/mbgl/map/camera.hpp
UTF-8
1,256
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "NCSA", "ISC", "blessing", "BSD-3-Clause", "OpenSSL", "IJG", "BSL-1.0", "Zlib", "Apache-2.0", "Libpng", "curl", "MIT", "BSD-2-Clause", "LicenseRef-scancode-openssl", "LicenseRef-scancode-sslea...
permissive
#pragma once #include <mbgl/util/chrono.hpp> #include <mbgl/util/geo.hpp> #include <mbgl/util/optional.hpp> #include <mbgl/util/unitbezier.hpp> #include <functional> namespace mbgl { /** Various options for describing the viewpoint of a map. All fields are optional. */ struct CameraOptions { /** Coordinate at the center of the map. */ optional<LatLng> center; /** Padding around the interior of the view that affects the frame of reference for `center`. */ EdgeInsets padding; /** Zero-based zoom level. Constrained to the minimum and maximum zoom levels. */ optional<double> zoom; /** Bearing, measured in radians counterclockwise from true north. Wrapped to [−π rad, π rad). */ optional<double> angle; /** Pitch toward the horizon measured in radians, with 0 rad resulting in a two-dimensional map. */ optional<double> pitch; }; constexpr bool operator==(const CameraOptions& a, const CameraOptions& b) { return a.center == b.center && a.padding == b.padding && a.zoom == b.zoom && a.angle == b.angle && a.pitch == b.pitch; } constexpr bool operator!=(const CameraOptions& a, const CameraOptions& b) { return !(a == b); } } // namespace mbgl
true
5079b760f2948ffc63a37e4c91f8fef0bd710bb3
C++
fwsGonzo/IncludeOS
/api/net/addr.hpp
UTF-8
2,676
2.984375
3
[ "Apache-2.0" ]
permissive
#pragma once #include <net/ip4/addr.hpp> #include <net/ip6/addr.hpp> namespace net { union Addr { public: static const Addr addr_any; constexpr Addr() noexcept : ip6_{} {} Addr(ip4::Addr addr) noexcept : ip4_{0, ip4_sign_be, std::move(addr)} {} Addr(ip6::Addr addr) noexcept : ip6_{std::move(addr)} {} // IP4 variant Addr(uint8_t a, uint8_t b, uint8_t c, uint8_t d) : ip4_{0, ip4_sign_be, {a, b, c, d}} {} // IP6 variant Addr(uint16_t a, uint16_t b, uint16_t c, uint16_t d, uint16_t e, uint16_t f, uint16_t g, uint16_t h) : ip6_{a, b, c, d, e, f, g, h} {} bool is_v4() const noexcept { return ip4_.big == 0 and ip4_.sign == ip4_sign_be; } bool is_v6() const noexcept { return not is_v4(); } void set_v4(ip4::Addr addr) noexcept { ip4_.big = 0; ip4_.sign = ip4_sign_be; ip4_.addr = std::move(addr); } void set_v6(ip6::Addr addr) noexcept { ip6_ = std::move(addr); } ip4::Addr v4() const { if(UNLIKELY(not is_v4())) throw ip4::Invalid_address{"Address is not v4"}; return ip4_.addr; } const ip6::Addr& v6() const noexcept { return ip6_; } bool is_any() const noexcept { return ip6_ == ip6::Addr::addr_any or (is_v4() and ip4_.addr == 0); } Addr any_addr() const noexcept { return is_v4() ? Addr{ip4::Addr::addr_any} : Addr{ip6::Addr::addr_any}; } std::string to_string() const { return is_v4() ? ip4_.addr.to_string() : ip6_.to_string(); } Addr(const Addr& other) noexcept : ip6_{other.ip6_} {} Addr(Addr&& other) noexcept : ip6_{std::move(other.ip6_)} {} Addr& operator=(const Addr& other) noexcept { ip6_ = other.ip6_; return *this; } Addr& operator=(Addr&& other) noexcept { ip6_ = std::move(other.ip6_); return *this; } //operator ip4::Addr() const //{ return v4(); } //operator const ip6::Addr&() const //{ return v6(); } bool operator==(const Addr& other) const noexcept { return ip6_ == other.ip6_; } bool operator!=(const Addr& other) const noexcept { return ip6_ != other.ip6_; } bool operator<(const Addr& other) const noexcept { return ip6_ < other.ip6_; } bool operator>(const Addr& other) const noexcept { return ip6_ > other.ip6_; } bool operator>=(const Addr& other) const noexcept { return (*this > other or *this == other); } bool operator<=(const Addr& other) const noexcept { return (*this < other or *this == other); } private: struct { uint64_t big; uint32_t sign; ip4::Addr addr; } ip4_; ip6::Addr ip6_; static constexpr uint32_t ip4_sign_be{0xFFFF0000}; }; static_assert(sizeof(Addr) == sizeof(ip6::Addr)); }
true
c8a09c8e9e1661ecd7d45f075923901336df5a29
C++
krthush/programming-principles-book
/Chapter 9/Drill/Drill/Chrono.cpp
UTF-8
7,531
3.421875
3
[]
no_license
#include "Chrono.h"; /* q1 */ //namespace Chrono { // std::ostream& operator<<(std::ostream& os, const Date& d) // { // return os << '(' << d.y << ',' << int(d.m) << ',' << d.d << ')'; // } // // helper functions // void init_day(Date& dd, int y, int m, int d) { // // // check that (y,m,d) is a valid date // // if (d <= 0) throw Invalid(); // d must be positive // // if (m < 1 || 12 < m) throw Invalid(); // // int days_in_month = get_days_in_month(dd.m); // // if (days_in_month < d) throw Invalid(); // // // if it is, use it to initialize dd // dd.d = d; // dd.m = m; // dd.y = y; // } // // increase dd by n days // void add_day(Date& dd, int n) { // // if (n < 0) throw Invalid (); // // // add run checks and relevant no. of day, then run recursively with days add // int days_in_month = get_days_in_month(dd.m); // if (dd.d + n <= days_in_month) { // dd.d += n; // } else { // if (dd.m == 12) { // dd.y += 1; // dd.m = 1; // } // else { // dd.m += 1; // } // n -= (days_in_month - dd.d) + 1; // dd.d = 1; // Chrono::add_day(dd, n); // } // } // int get_days_in_month(int m) { // int days_in_month = 31; // most months have 31 days // switch (m) { // case 2: // the length of February varies // days_in_month = 28; // break; // case 4: case 6: case 9: case 11: // days_in_month = 30; // the rest have 30 days // break; // default: // break; // } // return days_in_month; // } //} /* q2 */ //namespace Chrono { // std::ostream& operator<<(std::ostream& os, const Date& d) // { // return os << '(' << d.y << ',' << int(d.m) << ',' << d.d << ')'; // } // Date::Date(int yy, int mm, int dd) { // // // check that (y,m,d) is a valid date // // if (dd <= 0) throw Invalid(); // d must be positive // // if (mm < 1 || 12 < mm) throw Invalid(); // // int days_in_month = get_days_in_month(mm); // // if (days_in_month < dd) throw Invalid(); // // y = yy; // m = mm; // d = dd; // } // // helper functions // // increase dd by n days // void Date::add_day(Date& dd, int n) { // if (n < 0) throw Invalid(); // // // add run checks and relevant no. of day, then run recursively with days add // int days_in_month = get_days_in_month(dd.m); // if (dd.d + n <= days_in_month) { // dd.d += n; // } // else { // if (dd.m == 12) { // dd.y += 1; // dd.m = 1; // } // else { // dd.m += 1; // } // n -= (days_in_month - dd.d) + 1; // dd.d = 1; // Date::add_day(dd, n); // } // } // int get_days_in_month(int m) { // int days_in_month = 31; // most months have 31 days // switch (m) { // case 2: // the length of February varies // days_in_month = 28; // break; // case 4: case 6: case 9: case 11: // days_in_month = 30; // the rest have 30 days // break; // default: // break; // } // return days_in_month; // } //} /* q3 */ //namespace Chrono { // Date::Date(int yy, int mm, int dd) { // // // check that (y,m,d) is a valid date // // if (dd <= 0) throw Invalid(); // d must be positive // // if (mm < 1 || 12 < mm) throw Invalid(); // // int days_in_month = Date::get_days_in_month(mm); // // if (days_in_month < dd) throw Invalid(); // // y = yy; // m = mm; // d = dd; // } // // helper functions // // increase dd by n days // void Date::add_day(Date& dd, int n) { // if (n < 0) throw Invalid(); // // // add run checks and relevant no. of day, then run recursively with days add // int days_in_month = Date::get_days_in_month(dd.m); // if (dd.d + n <= days_in_month) { // dd.d += n; // } // else { // if (dd.m == 12) { // dd.y += 1; // dd.m = 1; // } // else { // dd.m += 1; // } // n -= (days_in_month - dd.d) + 1; // dd.d = 1; // Date::add_day(dd, n); // } // } // // cout // std::ostream& operator<<(std::ostream& os, Date& d) // { // return os << '(' << d.year() << ',' << int(d.month()) << ',' << d.day() << ')'; // } // // private functions // int Date::get_days_in_month(int m) { // int days_in_month = 31; // most months have 31 days // switch (m) { // case 2: // the length of February varies // days_in_month = 28; // break; // case 4: case 6: case 9: case 11: // days_in_month = 30; // the rest have 30 days // break; // default: // break; // } // return days_in_month; // } //} /* q4 */ //namespace Chrono { // Date::Date(int yy, Month mm, int dd) // :y{ yy }, m{ mm }, d{ dd } // { // // // check that (y,m,d) is a valid date // // if (dd <= 0) throw Invalid(); // d must be positive // // if (mm < Month::jan || Month::dec < mm) throw Invalid(); // // int days_in_month = Date::get_days_in_month(mm); // // if (days_in_month < dd) throw Invalid(); // } // // helper functions // // increase dd by n days // void Date::add_day(Date& dd, int n) { // if (n < 0) throw Invalid(); // // // add run checks and relevant no. of day, then run recursively with days add // int days_in_month = Date::get_days_in_month(dd.m); // if (dd.d + n <= days_in_month) { // dd.d += n; // } // else { // if (dd.m == Month::dec) { // dd.y += 1; // dd.m = Month::jan; // } // else { // dd.m = Month(int(m) + 1); // } // n -= (days_in_month - dd.d) + 1; // dd.d = 1; // Date::add_day(dd, n); // } // } // // cout // std::ostream& operator<<(std::ostream& os, Date& d) // { // return os << '(' << d.year() << ',' << int(d.month()) << ',' << d.day() << ')'; // } // // private functions // int Date::get_days_in_month(Month m) { // int days_in_month = 31; // most months have 31 days // switch (m) { // case Month::feb: // the length of February varies // days_in_month = 28; // break; // case Month::apr: case Month::jun: case Month::sep: case Month::nov: // days_in_month = 30; // the rest have 30 days // break; // default: // break; // } // return days_in_month; // } //} /* q5 */ namespace Chrono { Date::Date(int yy, Month mm, int dd) :y{ yy }, m{ mm }, d{ dd } { // check that (y,m,d) is a valid date if (!is_date(yy, mm, dd)) throw Invalid{}; } const Date& default_date() { static Date dd{ 2001, Month::jan, 1 }; // start of 21st century return dd; } Date::Date() :y{ default_date().year() }, m{ default_date().month() }, d{ default_date().day() } { } // helper functions bool is_date(int y, Month m, int d) { if (d <= 0) return false; // d must be positive if (m < Month::jan || Month::dec < m) return false; int days_in_month = get_days_in_month(m); if (days_in_month < d) return false; return true; } // increase dd by n days void Date::add_day(Date& dd, int n) { if (n < 0) throw Invalid(); // add run checks and relevant no. of day, then run recursively with days add int days_in_month = get_days_in_month(dd.m); if (dd.d + n <= days_in_month) { dd.d += n; } else { if (dd.m == Month::dec) { dd.y += 1; dd.m = Month::jan; } else { dd.m = Month(int(m) + 1); } n -= (days_in_month - dd.d) + 1; dd.d = 1; Date::add_day(dd, n); } } // cout std::ostream& operator<<(std::ostream& os, const Date& d) { return os << '(' << d.year() << ',' << int(d.month()) << ',' << d.day() << ')'; } // private functions int get_days_in_month(Month m) { int days_in_month = 31; // most months have 31 days switch (m) { case Month::feb: // the length of February varies days_in_month = 28; break; case Month::apr: case Month::jun: case Month::sep: case Month::nov: days_in_month = 30; // the rest have 30 days break; default: break; } return days_in_month; } }
true
a33db9481c76b7ffbb26f790919de7f2df301d8f
C++
sardort96/Stationery-Delivery
/main.cpp
UTF-8
1,029
3.03125
3
[]
no_license
/*///////////////////////// / Name: Assignment 3 ////// / Author: Sardor ////////// *////////////////////////// #include<iostream> #include"Gazel.h" #include"Damas.h" #include"Nexia.h" #include"Lorry.h" #include"CalculateFuel.h" using namespace std; int main() { Vehicle *ptr; cout << "1-Gazel\n2-Damas\n3-Nexia\n4-Lorry" << endl; cout << "Enter the car whose driver you want to test:" << endl; int choice; cin >> choice; switch (choice) { case 1: Gazel g; ptr = &g; g->defineQuantity(); g.calculate(); g.printInfo(); break; case 2: Damas d; ptr = &d; d->defineQuantity(); d.calculate(); d.printInfo(); break; case 3: Nexia n; ptr = &n; n->defineQuantity(); n.calculate(); n.printInfo(); break; case 4: Lorry l; ptr = &l; l->defineQuantity(); l.calculate(); l.printInfo(); break; default: { cout << "No such option" << endl; break; } } system("pause"); return 0; }
true
b53390d8c684f573aee29c50428e83b71cead07f
C++
deucalionAlpha/3D-Chinesechess
/Chinese Chess/CHESSMANAGER.h
UTF-8
6,929
2.59375
3
[]
no_license
#ifndef CHESSMANAGER_H #define CHESSMANAGER_H #include"CHESSGO.h" #include "WATERFLOW.h" class boardCross { private: Square *cross[2]; glm::mat4 *modelMatrix; Material *crossMaterial; public: boardCross(float cx, float cz, float gap) { cross[0] = new Square(0, 0, 2.2, 0.5, gap * 2 * sqrt(2.0)); cross[1] = new Square(0, 0, 2.2, gap * 2 * sqrt(2.0), 0.5); modelMatrix = new glm::mat4; *modelMatrix = glm::translate(*modelMatrix, glm::vec3(cx, 0, cz)); *modelMatrix = glm::rotate(*modelMatrix, glm::radians(45.0f), glm::vec3(0.0, 1.0, 0.0)); //*modelMatrix = glm::translate(*modelMatrix, glm::vec3(cx, 0, cz)); cross[0]->setModelMatrix(modelMatrix); cross[1]->setModelMatrix(modelMatrix); crossMaterial = Material::getMaterialByName("emerald"); } void drawCross() { cross[0]->drawGround(crossMaterial); cross[1]->drawGround(crossMaterial); } }; class Tag { private: Square *tag[8]; static int offsetX[4]; static int offsetZ[4]; glm::mat4 * model[8]; Material *tagMaterial; public: Tag(float cx, float cz, float gap, bool split = false,float height=2.2,string materialName="brass") { float offsetL, offsetH; float len = gap / 6.0; float thin = gap / 15.0; offsetL = gap / 20.0; offsetH = gap / 12.0 + offsetL; for (int i = 0; i < 4; i++) { tag[i] = new Square(0, 0,height , thin, len); model[i] = new glm::mat4; *model[i] = glm::translate(*model[i], glm::vec3(offsetH*offsetX[i] + cx, 0, offsetL*offsetZ[i] + cz)); //tag[i]->setModelMatrix(model[i]); } for (int i = 4; i < 8; i++) { tag[i] = new Square(0, 0, height, len, thin); model[i] = new glm::mat4; *model[i] = glm::translate(*model[i], glm::vec3(offsetL*offsetX[i - 4] + cx, 0, offsetH*offsetZ[i - 4] + cz)); //tag[i]->setModelMatrix(model[i]); } if (split == true) { for (int i = 0; i < 2; i++) { *model[i] = glm::translate(*model[i], glm::vec3(0, 0, -8 * gap)); *model[i + 4] = glm::translate(*model[i + 4], glm::vec3(0, 0, -8 * gap)); } } for (int i = 0; i < 8; i++)tag[i]->setModelMatrix(model[i]); tagMaterial = Material::getMaterialByName(materialName); } void drawTag() { for (int i = 0; i < 8; i++)tag[i]->drawGround(tagMaterial); } void translateTag(glm::vec3&trans) { for(int i=0;i<8;i++) *model[i]= glm::translate(*model[i], trans); } }; class Focus { private: glm::vec3 trans; int row, col; float gap; Tag *myFocus; Square *chosen; chessGo *myChess; bool focusComfirmed; int locX, locY; int targetId; int turn; Material * focusMaterial; public: Focus(int row, int col, float gap,chessGo* myChess) { this->row = row; this->col = col; this->gap = gap; this->myChess = myChess; trans.x = (col - 4.5)*gap; trans.y = 0; trans.z = (row - 4.0)*gap; myFocus = new Tag(0, 0, 2 * gap,false,2.4, "copper"); myFocus->translateTag(trans); focusComfirmed = false; turn = 0; focusMaterial = Material::getMaterialByName("jade"); } void drawFocus() { myFocus->drawTag(); if (focusComfirmed )chosen->drawGround(focusMaterial); } void moveFocus(int dRow, int dCol) { static int trow, tcol; trow = row + dRow; tcol = col + dCol; if (trow < 0 || trow>8)return; if (tcol < 0 || tcol>9)return; row = trow; col = tcol; trans.x = dCol * gap; trans.z = dRow * gap; myFocus->translateTag(trans); } bool targetConfirm() { if (myChess->focusLock ||!focusComfirmed)return false; focusComfirmed = false; delete chosen; if (myChess->moveChess(targetId, row, col) == true) { turn = !turn; return true; } else { trans.x = (locY - col)*gap; trans.z = (locX - row)*gap; myFocus->translateTag(trans); row = locX; col = locY; return false; } } bool focusConfirm() { static int k; if (myChess->focusLock ||focusComfirmed)return false; if (myChess->target(row, col) == 0)return false; targetId = myChess->target(row, col); k = myChess->getType(targetId); if ((!turn&&k > 7)||(turn&&k<8))return false; focusComfirmed = true; chosen = new Square((col - 4.5)*gap, (row - 4)*gap, 2.3, gap, gap); locX = row; locY = col; return true; } }; class chessManager { private: static glm::vec3 upDir; GLFWwindow* window; int frontDeltaRow, frontDeltaCol; int rightDeltaRow, rightDeltaCol; chessGo *myChess; float gap; Focus *myFocus; waterFlow *myWaterFlow[2]; void updateDirSystem() { static float x, z; x = Toolkit::myCamera->cameraFront.x; z = Toolkit::myCamera->cameraFront.z; if (fabs(x) > fabs(z)) { if (x > 0) { frontDeltaRow = 0; frontDeltaCol = 1; } else { frontDeltaRow = 0; frontDeltaCol = -1; } } else { if (z > 0) { frontDeltaRow = 1; frontDeltaCol = 0; } else { frontDeltaRow = -1; frontDeltaCol = 0; } } rightDeltaRow = frontDeltaCol; rightDeltaCol = -frontDeltaRow; } public: chessManager(float gap) { this->gap = gap; myChess = new chessGo(gap); updateDirSystem(); myFocus = new Focus(4, 3, gap,myChess); window = Camera::currentWindow; //cout <<"gap:"<< gap << endl; myWaterFlow[0] = new waterFlow(45, 500, gap / 50.0 , 0, 0); myWaterFlow[1] = new waterFlow(200, 200, gap / 10.0, 0, 0,0.0f); } void processInput() { static bool leftPressed=false, rightPressed=false, upPressed=false, downPressed=false; static bool enterPressed = false; updateDirSystem(); if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { if (leftPressed == false) { myFocus->moveFocus(-rightDeltaRow, -rightDeltaCol); leftPressed = true; } } if (glfwGetKey(window, GLFW_KEY_LEFT) ==GLFW_RELEASE)leftPressed = false; if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { if (rightPressed == false) { myFocus->moveFocus(rightDeltaRow, rightDeltaCol); rightPressed = true; } } if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_RELEASE)rightPressed = false; if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { if (upPressed == false) { myFocus->moveFocus(frontDeltaRow, frontDeltaCol); upPressed = true; } } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_RELEASE)upPressed = false; if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { if (downPressed == false) { myFocus->moveFocus(-frontDeltaRow, -frontDeltaCol); downPressed = true; } } if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_RELEASE)downPressed = false; if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS) { if (enterPressed == false) { if (myFocus->focusConfirm() == false) { myFocus->targetConfirm(); } enterPressed = true; } } if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_RELEASE)enterPressed = false; } void display() { processInput(); myWaterFlow[0]->draw(); myWaterFlow[1]->draw(); myFocus->drawFocus(); myChess->drawChess(); } }; int Tag::offsetX[4] = { -1,1,-1,1 }; int Tag::offsetZ[4] = { 1,1,-1,-1 }; glm::vec3 chessManager::upDir(0.0f,1.0f,0.0f); #endif // !
true
3a5b137a7b6c908626589fd2315f4aa0144fcb3c
C++
jcohen1964/MadCow
/totalClinicalVisitor.cpp
UTF-8
654
3
3
[]
no_license
#include "totalClinicalVisitor.h" //Visits all BovineGroups in herd and tallies number of clinical bovines void TotalClinicalVisitor::visit(BovineHerd* herd) { total = 0; BovineHerd::iterator end = herd->end(); for(BovineHerd::iterator it = herd->begin(); it != end; ++it) it->accept(*this); } //Loops through SickBovine list and increments total each time a clinical bovine is //identified. void TotalClinicalVisitor::visit(BovineGroup* group) { BovineGroup::SickBovineIterator end = group->getSickEnd(); for(BovineGroup::SickBovineIterator it = group->getSickBegin(); it != end; ++it) { if(it->isClinical) {total++;}; } }
true
b6fcc1e24412be685e1270c4af57efa341b39dd0
C++
scottshotgg/AsyncClientCpp
/main.cpp
UTF-8
4,842
2.609375
3
[]
no_license
// asynchronous client event loop #include <iostream> #include <thread> #include <map> // fkin boosted m8 #include <boost/asio.hpp> #include <boost/uuid/uuid.hpp> // uuid class #include <boost/uuid/uuid_generators.hpp> // generators #include <boost/uuid/uuid_io.hpp> // streaming operators etc. #include <boost/array.hpp> using boost::asio::ip::tcp; std::thread t; //std::map <boost::uuids::uuid, tcp::socket> clientList; std::map <boost::uuids::uuid, boost::shared_ptr<tcp::socket>> clientList; boost::uuids::random_generator generator; // tid = 1 void clientManager() { try { boost::asio::io_service io_service; tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 60000)); for (;;) { tcp::socket socket(io_service); acceptor.accept(socket); boost::uuids::uuid uuid1 = generator(); std::cout << "accepted client at " << socket.remote_endpoint() << " with UUID " << uuid1 << std::endl; boost::shared_ptr<tcp::socket> ptr(new tcp::socket()); clientList[uuid1] = ptr; //boost::system::error_code ignored_error; //boost::asio::write(socket, boost::asio::buffer(message), //boost::asio::transfer_all(), ignored_error); std::string message = "this is a cool message"; boost::array<char, 128> buf; std::copy(message.begin(),message.end(),buf.begin()); boost::system::error_code error; //tcp::socket& newClient = *clientList[uuid1]; //newClient.write_some(boost::asio::buffer(buf, message.size()), error); } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } void beginExport(int id) { printf("i am thread %d\n", id); } // tid = 0 int main(int argc, char* argv[]) { printf("loop test \n"); //int i = 1; // for(int i = 1; i < 100; i++) { // t[i] = std::thread(beginExport, i); // } // for(int i = 1; i < 100; i++) { // t[i].join(); // } int i = 1; t = std::thread(clientManager); t.join(); } // void quitThread() { // UDPClient tempClient(io_service, ip.c_str(), "6000"); // //tempClient.Send(std::string(cmd + "\n")); // //printf("this is the command: %s", cmd.c_str()); // std::string returnstring; // while(quit == 0) { // returnstring = tempClient.Recv(); // if(returnstring[0] == 'd' && returnstring[1] == 'o' && returnstring[2] == 'n' && returnstring[3] == 'e') { // break; // } // //printf("this is the return string: %s", returnstring.c_str()); // sync_cout << returnstring << sync_endl; // } // //sync_cout << "Thread" << id << " done!" << sync_endl; // } // //void beginExport(std::string cmd, std::string token, int id, UDPClient client) { // void beginExport(std::string cmd, std::string token, UDPClient* client) { // client->Send(std::string(cmd + "\n")); // //printf("this is the command: %s", cmd.c_str()); // std::string returnstring; // while(quit == 0) { // returnstring = client->Recv(); // if(returnstring[0] == 'd' && returnstring[1] == 'o' && returnstring[2] == 'n' && returnstring[3] == 'e' && token != "bench") { // break; // } else if(returnstring[0] == 'b' && returnstring[1] == 'd' && returnstring[2] == 'o' && returnstring[3] == 'n' && returnstring[4] == 'e' && token == "bench") { // break; // } // //printf("this is the return string: %s", returnstring.c_str()); // sync_cout << returnstring << sync_endl; // } // //sync_cout << "Thread" << id << " done!" << sync_endl; // } // void UCI::loop(int argc, char* argv[]) { // #ifdef WIN32 // WSAStartup(MAKEWORD(2, 2), &wsaData); // #endif // UDPClient client(io_service, ip.c_str(), "6000"); // Position pos; // string token, cmd; // pos.set(StartFEN, false, &States->back(), Threads.main()); // for (int i = 1; i < argc; ++i) // cmd += std::string(argv[i]) + " "; // do { // // Block here waiting for input or EOF // if (argc == 1 && !getline(cin, cmd)) // cmd = "quit"; // istringstream is(cmd); // token.clear(); // getline() could return empty or blank line // is >> skipws >> token; // if (token == "quit") { // //std::thread t1(quitThread, "stop", tid); // std::thread t1(quitThread); // quit = 1; // t1.join(); // Search::Signals.stop = true; // Threads.main()->start_searching(true); // } else { // //std::thread t1(beginExport, cmd, token, tid, client); // std::thread t1(beginExport, cmd, token, &client); // //sync_cout << "Thread " << tid << " waiting..." << sync_endl; // tid++; // t1.detach(); // } // } while (token != "quit" && argc == 1); // // may want to make a function like this that waits for everything // //waitForJoin() // quit = 1; // Threads.main()->wait_for_search_finished(); // }
true
598c12264a8183848461a1b667de7f58fb87e158
C++
TheKillerAboy/programming-olympiad
/C++_Solutions/SAPO/School_Round_2017/Round_2/Problem_2_Polynacci_Solution_1.cpp
UTF-8
335
2.734375
3
[]
no_license
#include <iostream> #include <valarray> using namespace std; int main(int argc, char const *argv[]) { valarray<int> tri = {2,8,15,4,4,3,8,9,10,3}; int N = 36; int sum; for(int i = 0; i < N-tri.size();i++){ sum = tri.sum(); tri = tri.shift(1); tri[tri.size()-1]=sum; } cout<<tri[tri.size()-1]; return 0; }
true
1511e74a2f43d6f0a96a70267617c3a35341aed7
C++
carlitomm/python_prog_course
/practica26/practica26.ino
UTF-8
871
2.640625
3
[]
no_license
const int potInt = A2; const int buttonInt = 2; boolean automatic = true; float x = 1.57; boolean going_up = false; float value; void setup() { Serial.begin(9600); } float scale(float meassure) { meassure = (meassure * 0.0048 * 16) + 40; return meassure; } void loop() { if (automatic == true) { if (x > 1.57) { going_up = false; } else if (x < -1.57) { going_up = true; } if (going_up) { x += 0.1; } else { x -= 0.1; } //Serial.print(x); value = sin(x); value = value + 1; value = (value * 40) + 40; Serial.println(value); } else { value = analogRead(potInt); value = scale(value); Serial.println(value); } if (digitalRead(buttonInt) == HIGH) { while (digitalRead(buttonInt) == HIGH); automatic = !automatic; Serial.print(automatic); } delay(100); }
true
2be86df943469bd90093eb582737040e4a010928
C++
liviabelirocha/mtn2-ck0048
/tarefa_14/src/VectorN.hpp
UTF-8
493
2.859375
3
[ "MIT" ]
permissive
#ifndef VECTOR_HPP #define VECTOR_HPP #include <iostream> #include <cmath> #include <vector> using namespace std; class VectorN { private: int size_; vector<double> vector_; public: VectorN(); VectorN(int size); void setElement(int i, double element); int getSize(); double getElement(int i); double norm(); void normalize(); void copyVector(VectorN v); double operator*(VectorN v); VectorN operator-(VectorN v); void print(); }; #endif
true
c0153a9ae0ce949e5d6e18a6024ba8cfff5fbc7d
C++
Effective12/VGTU-Procedural-Programming
/Lab_1/Lab_17.cpp
UTF-8
342
3.15625
3
[]
no_license
#include <iostream> using namespace std; int main () { double money = 1000000; int years = 0; double interest; while ( money >= 0) { interest = (money * 0.08) - 100000; money += interest; years += 1; if ( money <= 0 ) { break; } cout << "Money left in the account: " << money << " , years: " << years << "\n"; } }
true
5c0ea9046ae6316df3c7485052d3f12d76192e61
C++
losvald/algo
/icpc/qual-purdue/f.cpp
UTF-8
1,145
2.953125
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <map> #include <set> #include <utility> #include <vector> using namespace std; int n, m; vector<vector<int> > a; int dfs(int u, int s, vector<bool>& vis) { int ret = 0; for (vector<int>::iterator v = a[u].begin(); v != a[u].end(); ++v) { if (*v == s) ++ret; else if (!vis[*v]) { vis[*v] = true; ret += dfs(*v, s, vis); vis[*v] = false; } } return ret; } int main() { scanf("%d%d", &n, &m); a.resize(n); for (int i = 0; i < m; ++i) { int from, to; scanf("%d%d", &from, &to); a[from].push_back(to); } // make the graph simple for (int i = 0; i < n; ++i) { sort(a[i].begin(), a[i].end()); a[i].erase(unique(a[i].begin(), a[i].end()), a[i].end()); a[i].erase(remove(a[i].begin(), a[i].end(), i), a[i].end()); } int sol = 0; for (int i = 0; i < n - 1; ++i) { vector<bool> vis(n); vis[i] = true; sol += dfs(i, i, vis); a[i].clear(); for (int u = 0; u < n; ++u) a[u].erase(remove(a[u].begin(), a[u].end(), i), a[u].end()); } printf("%d\n", sol); return 0; }
true
aa5fed8afa4a8bc33d39cf4e45e01da650127c31
C++
pavel-zeman/CodeChef
/CodeChef/src/y2014/m03/cookoff/ABCStrings.cpp
UTF-8
1,150
3.15625
3
[]
no_license
// Go through the input string character after character, calculate the difference of B's - A's and C's - A's and find the same differences in a map // http://www.codechef.com/COOK44/problems/ABCSTR #include <stdio.h> #include <string.h> #include <limits.h> #include <math.h> #include <stdlib.h> #include <ctype.h> #include <assert.h> #include <map> #include <utility> #define FOR(c, m) for(int c=0;c<(m);c++) #define FORE(c, f, t) for(int c=(f);c<(t);c++) using namespace std; map< pair<int, int>, int > occ; char s[1000010]; int main(void) { scanf("%s", s); int a = 0, b = 0, c = 0; char *t = s; long long int total = 0; occ.insert(make_pair(make_pair(0, 0), 1)); while (*t) { switch (*t) { case 'A': a++; break; case 'B': b++; break; case 'C': c++; break; } t++; map<pair<int, int>, int>::iterator it = occ.find(make_pair(b - a, c - a)); if (it != occ.end()) total += it->second; if (it != occ.end()) it->second++; else { occ.insert(make_pair(make_pair(b - a, c - a), 1)); } } printf("%lld\n", total); }
true
2c031e7a010f23fb7e9fd8e9d8bebc02f661bf10
C++
ErolB/preach_sampling
/Probing.cpp
UTF-8
3,611
2.53125
3
[]
no_license
// // Created by erol on 5/9/16. // #include "Probing.h" /* This function does random probing. ** Does multiple random sampling and selects the edge set that makes the least runtime on average if weighted = true: weighted by their sizes, disappearance probability and invloved cut size ** The resulting edges should be in sampleEdges */ void ProbeRandom(ListDigraph& gOrig, WeightMap& wMapOrig, ArcIntMap& arcIdMap, ListDigraph::Node& sourceOrig, ListDigraph::Node& targetOrig, double samplingProb, Edges_T& sampleEdges, int probeSize, int probeRepeats, bool weighted){ vector<EdgeSubset> chancesOrig; if (weighted){ vector<Cut> cuts; vector< pair< vector<int>, int > > edgeSubsets; FindSomeGoodCuts(gOrig, sourceOrig, targetOrig, cuts, edgeSubsets); //Compile a vector of EdgeSubset objects vector<EdgeSubset> ess; double minScore = 1000000000.0; double maxScore = -1.0; int idCounter = 0; FOREACH_STL(subset, edgeSubsets){ idCounter ++; EdgeSubset es; es.id = idCounter; es.subset = subset.first; es.cutsize = subset.second; es.successProb = SuccessProb(subset.first, gOrig, wMapOrig); // bool jump = false; // FOREACH_STL(arcId, es.subset){ // ListDigraph::Arc arc = gOrig.arcFromId(arcId); // jump = jump || gOrig.source(arc) == sourceOrig || gOrig.target(arc) == targetOrig; // }END_FOREACH; // if (jump) continue; // we don't want any subset that is involved with wource or target ess.push_back(es); if (es.score() < minScore) minScore = es.score(); if (es.score() > maxScore) maxScore = es.score(); }END_FOREACH; // form a chances vector FOREACH_STL(es, ess){ double range = maxScore - minScore; double esScore = es.score(); double esRatio = (esScore - minScore) * 100.0 / range; //normalization int esChances = (int) ceil(esRatio); for (int i=0; i<esChances; i++) chancesOrig.push_back(es); }END_FOREACH; } map< string, vector<double> > durations; map<string, Edges_T> samples; for (int i=0; i<probeSize; i++){ Edges_T sample; vector<EdgeSubset> chances = chancesOrig; iteration(gOrig, wMapOrig, arcIdMap, sourceOrig, targetOrig, false, samplingProb, sample, false, weighted, chances); string sampleString = sample.to_string<char,std::string::traits_type,std::string::allocator_type>(); samples[sampleString] = sample; for (int j=0; j<probeRepeats; j++){ cout << "."; cout.flush(); double startCPUTime = getCPUTime(); iteration(gOrig, wMapOrig, arcIdMap, sourceOrig, targetOrig, true, samplingProb, sample, false, weighted, chances); //last two parameters don't matter here double duration = getCPUTime() - startCPUTime; durations[sampleString].push_back(duration); } } // get the min average time sample Edges_T minSample; double minAvg = 1000000000; for (map< string, vector<double> >::iterator it=durations.begin(); it != durations.end(); ++it){ double avg = std::accumulate(it->second.begin(), it->second.end(), 0.0) / it->second.size(); if (avg < minAvg){ minAvg = avg; minSample = samples[it->first]; } } sampleEdges = minSample; }
true
441be32beb9288bcd342038e799f2eda70b28013
C++
sckomoroh/InfoView
/plugins/MongoDBPlugin/BsonElement.cpp
UTF-8
4,651
2.671875
3
[]
no_license
#include "BsonElement.h" #include "BsonDocument.h" BsonElement::BsonElement() : m_sName(NULL) { m_value.m_binaryData = NULL; m_value.m_boolData = false; m_value.m_doubleData = 0; m_value.m_int32Data = 0; m_value.m_int64Data = 0; m_value.m_utfStrData = NULL; } BsonElement::~BsonElement(void) { delete[] m_sName; if (m_valueType == BsonElement::Array || m_valueType == BsonElement::BinaryData) { delete m_value.m_binaryData; return; } if (m_valueType == BsonElement::Utf8String) { delete m_value.m_utfStrData; } } bool BsonElement::isArray() { return m_valueType == BsonElement::Array; } char* BsonElement::name() { return m_sName; } BsonDocument* BsonElement::asArrayDocument() { return (BsonDocument*)m_value.m_binaryData; } std::vector<BsonElement*> BsonElement::asArray() { std::vector<BsonElement*> result; BsonDocument* pDocument = (BsonDocument*)m_value.m_binaryData; std::list<BsonElement*>::iterator iter = pDocument->m_elements.begin(); for (; iter != pDocument->m_elements.end(); iter++) { result.push_back(*iter); } return result; } UInt BsonElement::parseElement(UChar* sDocBuffer) { parseElementName(sDocBuffer); UInt nNameLenght = strlen(m_sName); UInt nValueSize = parseValue(sDocBuffer); if (m_valueType == BsonElement::Array) { UInt valueOffset = 1 /*Type*/ + nNameLenght + 1/*Zero-end string*/; BsonDocument* pTempDocument = new BsonDocument(sDocBuffer + valueOffset, nValueSize - 4 - 4); m_value.m_binaryData = pTempDocument; } return nValueSize + 2 + nNameLenght; } void BsonElement::parseElementName(UChar* sDocBuffer) { int nNameSize = strlen((char*)(sDocBuffer + 1)); m_sName = new char[nNameSize + 1]; memset(m_sName, 0, nNameSize + 1); strcpy_s(m_sName, nNameSize + 1, (char*)(sDocBuffer + 1)); } BsonElement::BsonType BsonElement::valueType() { return m_valueType; } BsonElement::BsonBinarySubtype BsonElement::valueSubType() { return m_valueSubType; } char* BsonElement::asUtfString() { return m_value.m_utfStrData; } double BsonElement::asDouble() { return m_value.m_doubleData; } void* BsonElement::asBinary() { return m_value.m_binaryData; } bool BsonElement::asBool() { return m_value.m_boolData; } Int32 BsonElement::asInt32() { return m_value.m_int32Data; } Int64 BsonElement::asInt64() { return m_value.m_int64Data; } bool BsonElement::isNull() { return m_valueType == BsonElement::NullValue; } UInt BsonElement::parseValue(UChar* sBuffer) { m_valueType = (BsonType)(*sBuffer); sBuffer += 1/*Type byte*/ + strlen(m_sName) + 1/*Zero byte*/; switch (m_valueType) { case BinaryData: return parseBinaryData(sBuffer); break; case UtcDateTime: return parseUtcDateTimeData(sBuffer); break; case Utf8String: return parseUtf8StringData(sBuffer); break; case Bool: return parseBoolData(sBuffer); break; case Array: return parseArrayData(sBuffer); break; case NullValue: return 0; break; case Integer32: return parseInt32Data(sBuffer); break; case Integer64: return parseInt64Data(sBuffer); break; } return 0; } UInt BsonElement::parseInt32Data(UChar* sBuffer) { memcpy(&m_value.m_int32Data, sBuffer, 4); return 4; } UInt BsonElement::parseInt64Data(UChar* sBuffer) { memcpy(&m_value.m_int32Data, sBuffer, 8); return 8; } UInt BsonElement::parseArrayData(UChar* sBuffer) { // Get array document size UInt nDocumentSize = 0; memcpy(&nDocumentSize, sBuffer, 4); return nDocumentSize; } UInt BsonElement::parseBoolData(UChar* sBuffer) { m_value.m_boolData = *sBuffer; return 1; } UInt BsonElement::parseNullData(UChar* sBuffer) { // No any need to implement return 0; } UInt BsonElement::parseBinaryData(UChar* sBuffer) { __int32 nByteBufferSize = 0; memcpy(&nByteBufferSize, sBuffer, 4); sBuffer += 4; m_valueSubType = (BsonBinarySubtype)(*sBuffer); sBuffer += 1; m_value.m_binaryData = new char[nByteBufferSize]; memcpy(m_value.m_binaryData, sBuffer, nByteBufferSize); return 4 /*Size of buffer*/ + 1/*Subtype*/ + nByteBufferSize; } UInt BsonElement::parseUtcDateTimeData(UChar* sBuffer) { memcpy(&(m_value.m_int64Data), sBuffer, 8); return 8; } UInt BsonElement::parseUtf8StringData(UChar* sBuffer) { UInt nStrLen = 0; memcpy(&nStrLen, sBuffer, 4); sBuffer += 4; m_value.m_utfStrData = new char[nStrLen]; strcpy_s(m_value.m_utfStrData, nStrLen, (char*)sBuffer); return 4 /*string size*/ + nStrLen; }
true
2b9606594d9372279d3b626cb8d8ae082ac5b283
C++
dhidas/CExamplesBasic
/AHelloWorld.cc
UTF-8
513
2.953125
3
[]
no_license
//////////////////////////////////////////////////////////////////// // // Dean Andrew Hidas <dhidas@bnl.gov> // // Created on: Wed Feb 8 17:09:47 EST 2017 // //////////////////////////////////////////////////////////////////// #include <iostream> // You MUST define the function 'main' int main (int argc, char* argv[]) { // Print a message to the standard outpt std::cout << "Hello world!" << std::endl; // Return zero from main to indicate that all is ok. Other numbers are // indications of errors return 0; }
true
78be54f238ee6bbbcc700551e63736a71216b11b
C++
klaashofman/arduino-projects
/simple_buzzer_pin3/simple_buzzer_pin3.ino
UTF-8
1,057
3.34375
3
[]
no_license
/* Blink Turns on an buz on for one second, then off for one second, repeatedly. This example code is in the public domain. */ // Pin 13 has an buz connected on most Arduino boards. // give it a name: int buz = 3; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(buz, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(buz, HIGH); // turn the buz on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(buz, LOW); // turn the buz on (HIGH is the voltage level) delay(10); // wait for a second digitalWrite(buz, HIGH); // turn the buz on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(buz, LOW); // turn the buz on (HIGH is the voltage level) delay(10); digitalWrite(buz, LOW); // turn the buz off by making the voltage LOW delay(1000); // wait for a second }
true
300df83c3672c13a3c7878785b708de32b38a12f
C++
hardik20sharma/C_plus_plus
/STACK PUSH AND POP (ARRAY BASED).cpp
UTF-8
1,024
3.5
4
[]
no_license
#include<iostream> using namespace std; const int size =50; int push(int stack[size], int &top, int info) { if(top==size-1) { cout<<"Overflow Aborting !"; return -1; } else { top++; stack[top]=info; } return 0; } int pop(int stack[size], int &top) { if(top==-1) return -1; else top--; return 0; } void display(int stack[size], int top) { cout<<stack[top]<<"<--\n"; for(int i=top-1; i>=0; i--) cout<<stack[i]<<endl; } int main() { int stack[size], top=-1, info, res; char ch='y'; while(ch=='y' || ch=='Y') { cout<<"Enter information for insertions:"; cin>>info; res=push(stack,top,info); if(res==-1) return 0; cout<<"\nThe stack is:\n"; display(stack,top); cout<<"Want to add more information?"; cin>>ch; } cout<<"Want to delete information?:"; cin>>ch; while(ch=='y' || ch=='Y') { if(pop(stack,top)==-1) { cout<<"UNDERFLOW!"; return 0; } display(stack, top); cout<<"Want to delete more information?:"; cin>>ch; } }
true
333f382b268f978fd1291e33952596dbf404c236
C++
bertus11/C-2-periodo-SI
/Switch Case 2.cpp
UTF-8
1,455
3.640625
4
[]
no_license
// Autor: Gabriel Bertussi // Data: 30/08/2021 #include <stdio.h> #include <stdlib.h> main () { int opcao; float numero, numero2; printf("----------CALCULADORA----------\n"); printf("\n"); printf("----------Digite [1] para SOMAR: \n"); printf("----------Digite [2] para SUBTRAIR: \n"); printf("----------Digite [3] para MULTIPLICAR: \n"); printf("----------Digite [4] para DIVIDIR: \n"); printf("----------Digite [5] para SAIR: \n"); printf("\n"); scanf("%d", &opcao); switch (opcao) { case 1: printf("Insira um valor: "); scanf("%f", &numero); printf("Insira um valor: "); scanf("%f", &numero2); printf("A SOMA dos numeros e: %.f\n", numero+numero2); break; case 2: printf("Insira um valor: "); scanf("%f", &numero); printf("Insira um valor: "); scanf("%f", &numero2); printf("A SUBTRACAO dos numeros e: %.f\n", numero-numero2); break; case 3: printf("Insira um valor: "); scanf("%f", &numero); printf("Insira um valor: "); scanf("%f", &numero2); printf("A MULTIPLICACAO dos numeros e: %.f\n", numero*numero2); break; case 4: printf("Insira um valor: "); scanf("%f", &numero); printf("Insira um valor: "); scanf("%f", &numero2); printf("A DIVISAO dos numeros e: %.1f\n", numero/numero2); break; case 5: printf("Programa FINALIZADO\n"); break; default: printf("Invalido!\n"); break; } }
true
13cd0dfe30c9183bc6f2f470cd9ce8f8807b263a
C++
awardak/CMinusMinus
/SymbolTable/SymbolTable.cpp
UTF-8
3,600
3.390625
3
[]
no_license
/* * SymbolTable.cpp */ #include <iostream> #include "SymbolTable.h" using namespace std; int SymbolTable::counter = 0; /* Nothing special to do in constructor, yet. */ SymbolTable::SymbolTable() { } /* Destructor responsible for deleting all symbols added to ST and ST itself. */ SymbolTable::~SymbolTable() { /* Get an iterator to iterate through the list of scopes. */ auto listItr = oldScopes.begin(); while (listItr != oldScopes.end()) { auto hashtableItr = (*listItr)->begin(); while (hashtableItr != (*listItr)->end()) { // cout << (*hashtableItr)->name << ' '; delete *hashtableItr; hashtableItr++; } delete *listItr; // cout << endl; listItr++; } } Symbol *SymbolTable::getStringLabel() { Symbol *newSymbol = new Symbol; newSymbol->name = "str_" + to_string(counter++); insert(newSymbol); return newSymbol; } Symbol *SymbolTable::getTemp() { /* create a new symbol */ Symbol *newSymbol = new Symbol; newSymbol->name = "t#" + to_string(counter++); /* insert into symbol table */ insert(newSymbol); return newSymbol; } /* This method is called when a new scope is entered. A new symbol table is pushed onto the stack for this scope. */ void SymbolTable::enterNewScope() { activeScopes.push_back(new unordered_set<Symbol *, SymbolHash, SymbolEqual>); } /* When a scope is exited, its symbol table is popped off the stack. */ void SymbolTable::leaveScope() { oldScopes.push_back(activeScopes.back()); activeScopes.pop_back(); } /* Simply insert next symbol into hash table. */ void SymbolTable::insert(Symbol *newSymbol) { activeScopes.back()->insert(newSymbol); } /* Lookup symbol in all active scopes */ Symbol * SymbolTable::lookup(Symbol * symbol) { Symbol *temp = find(symbol); if (!temp) { temp = findAll(symbol); if (!temp) throw "symbol not found"; } return temp; } Symbol * SymbolTable::lookup(string &symbol) { return lookup(new Symbol {.name = symbol}); } /* To find a symbol in the current scope, we try to find it in the hash table. */ Symbol * SymbolTable::find(Symbol * symbol) { /* Get an iterator to the symbol requested. If not found, return nullptr. */ auto hashtableItr = activeScopes.back()->find(symbol); if (hashtableItr != activeScopes.back()->end()) return *hashtableItr; else return nullptr; } /* Another find method that takes just a string */ Symbol * SymbolTable::find(string &symbol) { auto hashtableItr = activeScopes.back()->find(new Symbol {.name = symbol}); if (hashtableItr != activeScopes.back()->end()) return *hashtableItr; else return nullptr; } /* This method attempts to find the requested symbol in all active scopes. */ Symbol * SymbolTable::findAll(Symbol * symbol) { /* Get an iterator to iterate through the list of active scopes. */ auto listItr = activeScopes.crbegin(); while (listItr != activeScopes.crend()) { auto hashtableItr = (*listItr)->find(symbol); if (hashtableItr != (*listItr)->end()) return *hashtableItr; listItr++; } return nullptr; } Symbol * SymbolTable::findAll(string &symbol) { return findAll(new Symbol {.name = symbol}); } /* Display all identifiers in all active scopes. */ void SymbolTable::display() { int i = 1; auto listItr = activeScopes.cbegin(); while (listItr != activeScopes.cend()) { cout << "scope " << i++ << ": "; auto hashtableItr = (*listItr)->cbegin(); while (hashtableItr != (*listItr)->cend()) { cout << (*hashtableItr)->name << ' '; hashtableItr++; } cout << endl; listItr++; } }
true