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
5a269f4928cfba2cc808a1c4d58c0e8e5bb0d2c4
C++
lukaszjanus/CPP-various-programs-and-algorithmes
/CS-Science Club/OOP calculator XI 2017/kalkulator/variables.h
UTF-8
1,127
2.5625
3
[]
no_license
/*************************************************************************************************************** *"variables.h" * * *CONTENTS: * "Variables for cBasic class" *HISTORY: *version Date Changes Author/Programmer *1.0 07.12.2017 Orginal design Lukasz Janus * ****************************************************************************************************************/ #ifndef VARIABLES_H #define MENU_H class cVariables { private: double m_da; double m_db; unsigned long long m_ullc; unsigned long long m_ulld; public: /*----konstruktory, destruktor-----*/ cVariables(); ~cVariables(); /*----Metody dostepowe do pol--------*/ void SetA(double da); void SetB(double db); void SetC(unsigned long long ullc); void SetD(unsigned long long ulld); double GetA(); double GetB(); unsigned long long GetC(); unsigned long long GetD(); /*----Inicjalizacja--------*/ void c_fnFirstVariable(); void c_fnSecondVariable(); void c_fnOneVariableC(); void c_fnOneVariableD(); }; #endif // VARIABLES_H
true
6c4da86f5d8281e3a7199da455e4a974fea13b72
C++
acm-icpc-training/acm-icpc-training
/aoj/1244/main.cpp
UTF-8
2,209
3.546875
4
[ "MIT" ]
permissive
#include <cassert> #include <iostream> #include <unordered_map> using namespace std; unordered_map<string, int> atom_to_weight; class Parser { string str; int cur; bool IsDigit(char c) { return '0' <= c && c <= '9'; } bool IsUpperCase(char c) { return 'A' <= c && c <= 'Z'; } bool IsLowerCase(char c) { return 'a' <= c && c <= 'z'; } int EvaluateMolecule() { int weight = 0; while (true) { weight += EvaluateTerm(); if (!IsUpperCase(str[cur]) && str[cur] != '(') return weight; } } int EvaluateTerm() { if (str[cur] == '(') { ++cur; int weight = EvaluateMolecule(); assert(str[cur] == ')'); ++cur; int number = EvaluateNumber(); return weight * number; } int atom_weight = EvaluateAtom(); if (IsDigit(str[cur])) { int number = EvaluateNumber(); return atom_weight * number; } return atom_weight; } int EvaluateNumber() { int num = 0; while (IsDigit(str[cur])) { num *= 10; num += str[cur] - '0'; ++cur; } return num; } int EvaluateAtom() { assert(IsUpperCase(str[cur])); if (IsLowerCase(str[cur + 1])) { string atom = str.substr(cur, 2); cur += 2; if (atom_to_weight.find(atom) == atom_to_weight.end()) { throw "UNKNOWN"; } return atom_to_weight[atom]; } else { string atom = str.substr(cur, 1); ++cur; if (atom_to_weight.find(atom) == atom_to_weight.end()) { throw "UNKNOWN"; } return atom_to_weight[atom]; } } public: Parser(string str_in) : str(str_in) {} int Evaluate() { cur = 0; return EvaluateMolecule(); } }; int main() { // First part. while (true) { string atom; cin >> atom; if (atom == "END_OF_FIRST_PART") break; int weight; cin >> weight; atom_to_weight[atom] = weight; } // Second part. while (true) { string molecule; cin >> molecule; if (molecule == "0") break; Parser parser(molecule + "$"); try { int weight = parser.Evaluate(); cout << weight << endl; } catch(...) { cout << "UNKNOWN" << endl; } } return 0; }
true
2e01058c3e70fa05b0748f261f450ee552e26ed1
C++
JUNGEEYOU/algorithm
/5.stack/2_stl_stack.cpp
UTF-8
485
3.296875
3
[]
no_license
// stl stack 사용하기 #include <bits/stdc++.h> using namespace std; int main(void) { stack<int> S; S.push(10); S.push(20); S.push(30); cout << S.size() << '\n'; if(S.empty()) cout << "S is empty \n"; else cout << "S is not empty \n"; S.pop(); cout << S.top() << '\n'; S.pop(); cout << S.top() << '\n'; S.pop(); if(S.empty()) cout << "S is empty \n"; else cout << "S is not empty \n"; cout << S.top() << '\n'; // 빈 경우, runtime error 발생함. }
true
cfde0c8739c97704d4883058227e45cdb54b49c5
C++
spartanPAGE/spartsi-deprecated-
/spartsi/test/builder/ref-nodes.cpp
UTF-8
1,392
2.875
3
[ "MIT" ]
permissive
#include "catch/catch.hpp" #include "builder/tree-builder.hpp" TEST_CASE("Ref nodes", "[spartsi::builder]") { using namespace spartsi::builder; auto tree = build() .treestructinfo("2.0").name("ref nodes") ("foo") .req_node("refnode") .end_tree() ("bar") .ref_node("refnode") .attr("attr", "test val") .req_node("refsec") ("1") .req_node("reflast") .end_ref_node() .ref_node("refsec") .attr("attr", "test another val") .end_ref_node() ("2") .ref_node("reflast") .attr(":)", "last") .end_ref_node() .get(); SECTION("asserts") { SECTION("comment") { REQUIRE((tree->children.at("refnode")->comment == "foo\nbar")); } SECTION("normal attr") { REQUIRE((tree->children.at("refnode")->attributes.at("attr").first == "test val")); } SECTION("attr in refsec") { REQUIRE((tree->children["refnode"]->children["refsec"]->attributes["attr"].first == "test another val")); } SECTION("reflast") { REQUIRE((tree->children["refnode"]->children["reflast"]->attributes[":)"].first == "last")); REQUIRE((tree->children["refnode"]->children["reflast"]->comment == "1\n2")); } } }
true
03cdc3c041b4e0362acec7945b3bc3ce146a74dd
C++
shtanriverdi/Full-Time-Interviews-Preparation-Process
/Weekly Questions/767. Reorganize String.cpp
UTF-8
1,200
3.390625
3
[]
no_license
// Question Link ---> https://leetcode.com/problems/reorganize-string/ class Solution { public: string reorganizeString(string S) { if (S.size() <= 1) { return S; } unordered_map<char, int> letterFreqMP; for (char c : S) { letterFreqMP[c]++; } priority_queue<pair<int, char>> freqLetterPQ; for (auto tuple : letterFreqMP) { freqLetterPQ.push({tuple.second, tuple.first}); } string result = ""; while (!freqLetterPQ.empty()) { pair<int, char> A = freqLetterPQ.top(); freqLetterPQ.pop(); A.first--; result += A.second; if (freqLetterPQ.empty()) { if (A.first > 0) { return ""; } return result; } pair<int, char> B = freqLetterPQ.top(); freqLetterPQ.pop(); B.first--; result += B.second; if (A.first > 0) { freqLetterPQ.push(A); } if (B.first > 0) { freqLetterPQ.push(B); } } return result; } };
true
a95ac61111535b761a64946c8fea59e894258ddf
C++
gabrielfsil/estrutura-de-dados-2
/NoAVL.h
UTF-8
582
2.625
3
[]
no_license
#ifndef NoAVL_H_INCLUDED #define NoAVL_H_INCLUDED class NoAVL { public: NoAVL(); ~NoAVL(); void setEsq(NoAVL *p); void setInfo(int val); void setDir(NoAVL *p); void setAltura(int k); void setFB(int k); NoAVL* getEsq(); int getInfo(); NoAVL* getDir(); int getAltura(); private: NoAVL* esq; // ponteiro para o filho a esquerda int info; // informação do No (int) NoAVL* dir; // ponteiro para o filho a direita int altura; //altura int fb; //fator de balanceamento }; #endif // NoAVL_H_INCLUDED
true
9573985a7e9e835d166a1591a7955a32e5fff55f
C++
jobrittain/ball-sim
/Source/Influencer.cpp
UTF-8
2,417
2.875
3
[ "MIT" ]
permissive
#include "Influencer.h" Influencer::Influencer() : _influentialForce(0), _online(false) { } Influencer::~Influencer() { } void Influencer::SetRadius(float radius) { _radius = radius; } void Influencer::SetSightRadius(float sightRadius) { _sightRadius = sightRadius; } void Influencer::SetMovementSpeed(float speed) { _movementSpeed = speed; _keyMovementSpeed = speed + 100; } void Influencer::SetInfluenceRate(float influenceRate) { _influenceRate = influenceRate; } void Influencer::SetOnlineState(bool state) { _online = state; } void Influencer::SetForce(float force) { _influentialForce = force; } float Influencer::GetForce() { return _influentialForce; } float Influencer::GetSightRadius() { return _sightRadius; } bool Influencer::IsOnline() { return _online; } bool Influencer::BallInSight(DirectX::SimpleMath::Vector3 ballPosition, float ballRadius) { DirectX::SimpleMath::Vector3 iPosition; { std::lock_guard<std::mutex> lock(posLock); iPosition = _position; } auto dist = DirectX::SimpleMath::Vector3::Distance(ballPosition, iPosition); if (dist < (ballRadius + _sightRadius)) { return true; } return false; } void Influencer::MoveUp(float deltaTime) { std::lock_guard<std::mutex> lock(posLock); _position.y += _keyMovementSpeed * deltaTime; } void Influencer::MoveDown(float deltaTime) { std::lock_guard<std::mutex> lock(posLock); _position.y -= _keyMovementSpeed * deltaTime; } void Influencer::MoveLeft(float deltaTime) { std::lock_guard<std::mutex> lock(posLock); _position.x -= _keyMovementSpeed * deltaTime; } void Influencer::MoveRight(float deltaTime) { std::lock_guard<std::mutex> lock(posLock); _position.x += _keyMovementSpeed * deltaTime; } void Influencer::MoveForwards(float deltaTime) { std::lock_guard<std::mutex> lock(posLock); _position.z -= _keyMovementSpeed * deltaTime; } void Influencer::MoveBackwards(float deltaTime) { std::lock_guard<std::mutex> lock(posLock); _position.z += _keyMovementSpeed * deltaTime; } void Influencer::MouseMove(int x, int y) { std::lock_guard<std::mutex> lock(posLock); _position.x += x * _movementSpeed; _position.z += y * _movementSpeed; } void Influencer::Attract(float deltaTime) { _influentialForce += _influenceRate * deltaTime; } void Influencer::Repel(float deltaTime) { _influentialForce -= _influenceRate * deltaTime; } void Influencer::CancelForce() { _influentialForce = 0; }
true
54bafdabebe82337c30d8c03c0fb866e1385b34a
C++
fviel/projetos_arduino
/Códigos/UltrassomComMotor/baseRobo/baseRobo.ino
UTF-8
1,757
3.125
3
[]
no_license
#include <Stepper.h> #define trigPin 13 #define echoPin 12 #define blockedLedPin 5 #define cleanLedPin 6 //define a quantidade de passos por volta const int passosPorVolta = 200; //inicializa o motor e seus pinos Stepper motor(passosPorVolta, 8,9,10,11); //inicializa o contador de voltas int contaGiro = 0; void setup() { Serial.begin (9600); //define a velocidade do motor motor.setSpeed(70); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); //inicializa os leds pinMode(blockedLedPin, OUTPUT); pinMode(cleanLedPin, OUTPUT); } void loop() { //LÊ o sensor de ultrasom int distance=leDistancia(); if ((distance >= 200) || (distance <= 0)) { //Acende o led de livre leds(true); Serial.println("Livre"); //dá giro no motor //volta 360 graus = 2040 passos. giraMotor(20); } else { //Acende o led de bloqueio leds(false); Serial.print("Obstruido - Distancia medida: "); Serial.print(distance); Serial.println(" cm"); } } void giraMotor(int passos) { int i = 0; for(i=0;i<=passos;i++) { motor.step(1); } Serial.print("Passos: " ); Serial.println(contaGiro); contaGiro = contaGiro + (i-1); } void leds(boolean estado) { if(estado == true) { //LIVRE digitalWrite(blockedLedPin,LOW); digitalWrite(cleanLedPin,HIGH); } else { //OBSTRUÍDO digitalWrite(blockedLedPin,HIGH); digitalWrite(cleanLedPin,LOW); } } int leDistancia() { long duration, distance; digitalWrite(trigPin, LOW); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; return distance; }
true
bf409d8a704a734d6dba9ae95c09e7eb94dd35d0
C++
tdm1223/Algorithm
/programmers/source/1-27.cpp
UTF-8
458
3.359375
3
[ "MIT" ]
permissive
//문자열 내림차순으로 배치하기 // sort(s.begin(), s.end(), greater<char>()); // sort(s.rbegin(),s.rend()); // 2019.03.08 #include<string> #include<vector> #include<algorithm> using namespace std; string solution(string s) { string answer = ""; vector<char> v; for (int i = 0; i<s.size(); i++) { v.push_back(s[i]); } sort(v.begin(), v.end(), greater<char>()); for (int i = 0; i<v.size(); i++) { answer += v[i]; } return answer; }
true
82b5c5659bce516bbf66183120911fb799598dc0
C++
Strongc/MyBase
/Common/Thread.h
UTF-8
1,486
2.640625
3
[]
no_license
#ifndef __SYNCHRONIZATION_THREAD_H__ #define __SYNCHRONIZATION_THREAD_H__ #include "Type.h" #ifdef WIN32 typedef UINT THREAD_ID; typedef UINT THREAD_FUNC_RET_TYPE; #else typedef pthread_t THREAD_ID; typedef VOID * THREAD_FUNC_RET_TYPE; #endif typedef enum _ThreadStatus{ eNone, eActive, eSuspend }emThreadStatus; class IThread : private UnCopyable { private: emThreadStatus m_eFlag; THREAD_ID m_threadID; #ifdef WIN32 HANDLE m_hThread; HANDLE GetHandle() CONST; static THREAD_FUNC_RET_TYPE WINAPI ThreadFunction(VOID *); #else pthread_mutex_t mutex; pthread_cond_t cond; static THREAD_FUNC_RET_TYPE ThreadFunction(VOID *); #endif protected: IThread(); virtual ~IThread(); public: virtual BOOL Init(); THREAD_ID GetThreadID() CONST; virtual BOOL Start(); virtual BOOL Stop(DWORD dwExitCode = 0); virtual BOOL SuspendThread(); virtual BOOL ResumeThread(); private: virtual VOID PreRun(); virtual UINT Run() = 0; }; typedef VOID(*ThreadFun)(VOID*); class SimpleThread : private UnCopyable { public: SimpleThread(); ~SimpleThread(); BOOL Start(ThreadFun pFunction, VOID* pParam); VOID Stop(); private: ThreadFun m_pFunction; VOID* m_pParam; THREAD_ID m_uThreadId; #ifdef PLATFORM_OS_WINDOWS HANDLE m_hThread; static THREAD_FUNC_RET_TYPE WINAPI ThreadFunction(VOID *pValue); #else static THREAD_FUNC_RET_TYPE ThreadFunction(VOID* pParam); #endif //PLATFORM_OS_WINDOWS }; #endif //__SYNCHRONIZATION_THREAD_H__
true
c41c65f2466e8d38e3df2d8772cf85b42ccc8b8c
C++
murilobnt/vulnus
/src/playermousecontrol.cpp
UTF-8
282
2.53125
3
[ "CC-BY-3.0", "MIT" ]
permissive
#include "structures/playermousecontrol.hpp" void PlayerMouseControl::controlEntityByMouse(sf::Event event, SpritedEntity& spritedEntity, sf::Vector2f mousePos){ switch(event.type){ case sf::Event::MouseButtonPressed : spritedEntity.setSpritePosition(mousePos); break; } }
true
a1443ca42e6764c54af6bc1cc5e10144e0dc7dca
C++
asu126/summary
/src/374_guessNumber.cpp
UTF-8
630
3.671875
4
[]
no_license
// Forward declaration of guess API. // @param num, your guess // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 int guess(int num); class Solution { public: int guessNumber(int n) { int low = 1; int higt = n; int mid = low + (higt-low)/2; while(low <= higt){ int g = guess(mid); if(g == 0) { break; } else if(g>0){ low = mid + 1; } else { higt = mid - 1; } mid = low + (higt-low)/2; } return mid; } };
true
4ef08eb1111998225f275463ae1d3971b428dc7d
C++
XapiMa/procon
/prac/first/ABC_081_B-Shift_Only.cpp
UTF-8
577
2.875
3
[]
no_license
#include <iostream> using namespace std; int main(){ int N; int A[200]; cin >> N; for(int i = 0; i<N; i++) cin >> A[i]; int res = 0; while(true) { bool exist_odd = false; for (int i = 0; i < N; i++) { if(A[i]%2 != 0) exist_odd = true; } if(exist_odd) break; for (int i = 0; i < N; i++) { A[i] /= 2; } res++; } cout << res << endl; return 0; }
true
aa9576fba9fadadfc7bcef1850d113efbc6a9d60
C++
HU-R2D2/adt
/source/include/ADT_Base.hpp
UTF-8
5,753
2.625
3
[]
no_license
// ++--++ // @file <ADT_Base.hpp> // @date Created: <5-3-16> // @version <0.0.1> // // // @section LICENSE // License: newBSD // // Copyright © 2016, HU University of Applied Sciences Utrecht. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // - Neither the name of the HU University of Applied Sciences Utrecht nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE HU UNIVERSITY OF APPLIED SCIENCES UTRECHT // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ++--++ //! //! @author Job Verhaar //! @date 05-04-16 //! @version 0.1 //! @brief Base class for standard ADT classes with one value //! #ifndef _ADT_BASE_HPP #define _ADT_BASE_HPP namespace r2d2{ template <class T> class ADT_Base { protected: double value; //! @fn ADT_Base::ADT_Base(double) //! //! @brief Constructor of a Weight //! //! @param value the value to assign ADT_Base(double value):value{value}{} public: //! @fn ADT_Base::ADT_Base() //! //! @brief Default constructor ADT_Base():value{0.0}{} //! @fn T& ADT_Base::operator=(cost T& rhs) //! //! @brief Assignment operator for a T //! //! @param T the T that is assigned to the other T& operator= (const T& rhs){ value = rhs.value; return *static_cast<T*>(this); } //! @fn ADT_Base::operator+(const T& rhs) const //! //! @brief Add operator of a T //! //! @param number the number to add to the T T operator+ (const T& rhs) const{ return T{value + rhs.value}; } //! @fn ADT_Base::operator+=(const T& rhs) //! //! @brief Add assign operator of a T //! //! @param number the number to add to the T T& operator+= (const T& rhs){ value += rhs.value; return *static_cast<T*>(this); } //! @fn ADT_Base::operator-(const T& rhs) const //! //! @brief substract operator of a T //! //! @param number the number to subtrackt from the T T operator- (const T& rhs) const{ return T{value - rhs.value}; } //! @fn ADT_Base::operator-=(const T& rhs) //! //! @brief subtract assign operator of a T //! //! @param number the number to subtract from the T T& operator-= ( const T& rhs){ value -= rhs.value; return *static_cast<T*>(this); } //! @fn ADT_Base::operator*(double number) //! //! @brief multiply operator of a T //! //! @param number the number to multyply the T by T operator* (double number) const{ return T{value * number}; } //! @fn ADT_Base::operator*=(double number) //! //! @brief multiply operator of a T //! //! @param number the number to multyply the T by T operator*= (double number){ value *= number; return *static_cast<T*>(this); } //! @fn ADT_Base::operator/(double number) //! //! @brief division operator of a T //! //! @param number the number to devide the T by T operator/ (double number) const{ if(number != 0){ return T{value / number}; } return T{value}; } //! @fn ADT_Base::operator/=(const T& rhs) //! //! @brief division operator of a T //! //! @param number the number to devide the T by T operator/= (double number){ if(number != 0){ value /= number; } return *static_cast<T*>(this); } //! @fn ADT_Base::operator/(const T& rhs) //! //! @brief division operator of a T //! //! @param number the number to devide the T by double operator/ (const T & rhs) const{ if(rhs.value != 0){ return value / rhs.value; } return value; } //! @fn T operator *(double n, const T& rhs) //! //! @brief Multiplies a T by a double //! //! @param n a double. //! @param rhs a T. //! @return the calculated T. friend T operator * (double n, const T & rhs){ return T{n * rhs.value}; } //! @fn T::T(const T& rhs) //! //! @brief greater then operator of a T //! //! @param rhs the right hand side to compare bool operator> (const T& rhs) const{ return value > rhs.value; } //! @fn T::T(const T& rhs) //! //! @brief smaller then operator of a T //! //! @param rhs the right hand side to compare bool operator< (const T& rhs) const{ return value < rhs.value; } }; } #endif
true
9a30d3899723459b95bb738fc7edcfed9db5dc53
C++
eindacor/OpenGL-Calculator
/keypress.cpp
UTF-8
8,930
2.734375
3
[]
no_license
#include "keypress.h" bool key_handler::checkPress(int key, GLFWwindow* window) { int state = glfwGetKey(window, key); //check list of keys pressed for a match, acts according to the press state for (list<int>::iterator i = keysPressed.begin(); i != keysPressed.end(); ++i) { if (*i == key) { if (state == GLFW_RELEASE) { keysPressed.erase(i); } return false; } } switch (state) { case GLFW_PRESS: keysPressed.push_back(key); return true; case GLFW_RELEASE: return false; default: return false; } } KEYRETURN key_handler::checkKeys(line_group &lines, display_handler &display_context, settings &user_settings) { GLFWwindow* window = display_context.getWindow(); if (checkPress(GLFW_KEY_BACKSPACE, window)) { lines.removeChar(); } if (checkPress(GLFW_KEY_0, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar(')') : lines.addChar('0')); } if (checkPress(GLFW_KEY_1, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('!') : lines.addChar('1')); } if (checkPress(GLFW_KEY_2, window)) { lines.addChar('2'); } if (checkPress(GLFW_KEY_3, window)) { lines.addChar('3'); } if (checkPress(GLFW_KEY_4, window)) { lines.addChar('4'); } if (checkPress(GLFW_KEY_5, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('%') : lines.addChar('5')); } if (checkPress(GLFW_KEY_6, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('^') : lines.addChar('6')); } if (checkPress(GLFW_KEY_7, window)) { lines.addChar('7'); } if (checkPress(GLFW_KEY_8, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('*') : lines.addChar('8')); } if (checkPress(GLFW_KEY_9, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('(') : lines.addChar('9')); } if (checkPress(GLFW_KEY_A, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('A') : lines.addChar('a')); } if (checkPress(GLFW_KEY_B, window)) { if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) return BASE; else { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('B') : lines.addChar('b')); } } if (checkPress(GLFW_KEY_C, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('C') : lines.addChar('c')); } if (checkPress(GLFW_KEY_D, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('D') : lines.addChar('d')); } if (checkPress(GLFW_KEY_E, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('E') : lines.addChar('e')); } if (checkPress(GLFW_KEY_F, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('F') : lines.addChar('f')); } if (checkPress(GLFW_KEY_G, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('G') : lines.addChar('g')); } if (checkPress(GLFW_KEY_H, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('H') : lines.addChar('h')); } if (checkPress(GLFW_KEY_I, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('I') : lines.addChar('i')); } if (checkPress(GLFW_KEY_J, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('J') : lines.addChar('j')); } if (checkPress(GLFW_KEY_K, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('K') : lines.addChar('k')); } if (checkPress(GLFW_KEY_L, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('L') : lines.addChar('l')); } if (checkPress(GLFW_KEY_M, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('M') : lines.addChar('m')); } if (checkPress(GLFW_KEY_N, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('N') : lines.addChar('n')); } if (checkPress(GLFW_KEY_O, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('O') : lines.addChar('o')); } if (checkPress(GLFW_KEY_P, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('P') : lines.addChar('p')); } if (checkPress(GLFW_KEY_Q, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('Q') : lines.addChar('q')); } if (checkPress(GLFW_KEY_R, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('R') : lines.addChar('r')); } if (checkPress(GLFW_KEY_S, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('S') : lines.addChar('s')); } if (checkPress(GLFW_KEY_T, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('T') : lines.addChar('t')); } if (checkPress(GLFW_KEY_U, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('U') : lines.addChar('u')); } if (checkPress(GLFW_KEY_V, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('V') : lines.addChar('v')); } if (checkPress(GLFW_KEY_W, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('W') : lines.addChar('w')); } if (checkPress(GLFW_KEY_X, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('X') : lines.addChar('x')); } if (checkPress(GLFW_KEY_Y, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('Y') : lines.addChar('y')); } if (checkPress(GLFW_KEY_Z, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('Z') : lines.addChar('z')); } if (checkPress(GLFW_KEY_SPACE, window)) { lines.addChar(' '); } if (checkPress(GLFW_KEY_EQUAL, window)) { (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS ? lines.addChar('+') : lines.addChar('=')); } if (checkPress(GLFW_KEY_MINUS, window)) { lines.addChar('-'); } if (checkPress(GLFW_KEY_SLASH, window)) { lines.addChar('/'); } if (checkPress(GLFW_KEY_PERIOD, window)) { lines.addChar('.'); } if (checkPress(GLFW_KEY_COMMA, window)) { lines.addChar(','); } if (checkPress(GLFW_KEY_ENTER, window)) { return ENTER; //lines.addLine(line(origin)); //entered = lines.convertCurrentLine(); //solution answer = solve(entered, previous, user_settings); } if (checkPress(GLFW_KEY_UP, window)) { display_context.scrollTextColor(1); } if (checkPress(GLFW_KEY_DOWN, window)) { display_context.scrollTextColor(-1); } if (checkPress(GLFW_KEY_LEFT, window)) { display_context.scrollBackgroundColor(1); } if (checkPress(GLFW_KEY_RIGHT, window)) { display_context.scrollBackgroundColor(-1); } return NULL_RETURN; }
true
bd481b1b7f245842c9a0725fad737f41d474ffc8
C++
JLUCProject2020/cproject2020-group6
/tb.cpp
GB18030
9,116
2.890625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #define N 6 //֧ #define ATTN 11 // int Player[N][ATTN]; int n_player = -1; // ս const int ZD_HP = 0;//Ѫ const int ZD_DEX = 1;//ս const int ZD_FANJI = 2;//񶷡 const int ZD_SHANBI = 3;//ս const int ZD_YILIAO = 4;// ҽ const int ZD_TIZHI = 5;// const int ZD_SHJZ = 6;//˺ֵ const int ZD_JIJIU = 7;// // ׷ const int RUN_MOVE = 8;//׷ const int RUN_PANPA = 9;//׷ const int RUN_JUMP = 10;//׷Ծ const char* Name(int id) { if (id == 0)return "Ѫ"; if (id == 1)return ""; if (id == 2)return ""; if (id == 3)return ""; if (id == 4)return "ҽ"; if (id == 5)return ""; if (id == 6)return ""; if (id == 7)return ""; if (id == 8)return ""; if (id == 9)return ""; if (id == 10)return "Ծ"; return "δ֪"; } void input_player_info() { printf("Ϸ:"); scanf("%d", &n_player); if (n_player < 2 || n_player > N) { printf("ϷҪ2~%dˣ%d\n", N, n_player); return; } printf("Ѫݣ񶷣, ҽƣʣ˺ֵȣ٣Ծ\n"); for (int i = 0; i < n_player; i++) { printf("%d˵:\n", i); for (int j = 0; j < ATTN; j++) { scanf("%d", &Player[i][j]); } } printf("ɹ\n"); } int random_int(int min, int max) { return (rand() % (max + 1 - min)) + min; } //׷ģʽ void trace_mode() { int move[2] = { 1, Player [1][RUN_MOVE]- Player [0][RUN_MOVE] + 1}; int pos[2] = { 0, 2 }; int player = 1; int val; do { printf("=======================\n"); printf("0λ:%d\n", pos[0]); printf("1λ:%d\n", pos[1]); printf(":%d\n", pos[1] - pos[0]); printf("=======================\n"); int moved = 0; for (int i = 0; i < move[player]; i++) { printf("%d1һжʣж:%d\n", player, move[player]-i); scanf("%d", &val); if (val != 1) { printf("Ч\n"); continue; } int action = random_int(RUN_MOVE, RUN_JUMP); printf("ϰ,Ҫ:%s%d", Name(action), action); int point = random_int(1, 100); if (point < Player[player][action]) { pos[player]++; moved++; printf("жֵ(%d)жɹǰһ\n", point); } else { printf("жֵ(%d)жʧܣͣԭ\n", point); } } printf("%dǰ%d\n", player, moved); player = (player == 0) ? 1 : 0; } while (pos[1] - pos[0] >= 1); } // սݶ void sort_by_ZD_DEX() { for (int i = 0; i < n_player; i++) { for (int j = 0; j < n_player - i - 1; j++) { if (Player[j][ZD_DEX] < Player[j + 1][ZD_DEX]) { int t[N]; memmove(t, Player[j], sizeof(int) * N); memmove(Player[j], Player[j + 1], sizeof(int) * N); memmove(Player[j + 1], t, sizeof(int) * N); } } } } // ҵ״̬ void print_player_info() { printf("Ѫ ҽ Ծ\n"); for (int i = 0; i < n_player; i++) { for (int j = 0; j < ATTN; j++) { printf("%-5d", Player[i][j]); } printf("\n"); } } // ˶սģʽ void pvps_mode() { printf("սģʽ\n"); sort_by_ZD_DEX(); print_player_info(); int player = 0; int lives = n_player; int MD[] = {2,4,7}; int dying[N] = {0}; int dead[N] = {0}; int point; while (lives > 1) { printf("===================================\n"); print_player_info(); printf("===================================\n"); player = player % n_player; if (dead[player]) { printf("ǰж:%dѾغ\n", player); player++; continue; } printf("ǰж:%d\n", player); if (dying[player]) { point = random_int(1, 100); printf("Ҵڱ״̬жֵ%d,", point); if (point >= Player[player][ZD_TIZHI]) { printf("%d\n", player); dead[player] = 1; lives--; } continue; } int act = 0; while(1) { printf("ȡж: 0. 1.ҽ 2.\n"); scanf("%d", &act); if (act == 0 || act == 1|| act == 2) { break; } else { printf("Ч\n"); } } int level = random_int(1, 100); if (level > Player[player][MD[act]]) { printf("жֵ%dжʧ!\n", level); level = 1; player++; continue; }else if (level > Player[player][MD[act]] / 2) { printf("жֵ%dͨɹ\n",level); level = 2; }else if (level > Player[player][MD[act]] / 3) { printf("жֵ%dѳɹ\n", level); level = 3; }else{ printf("жֵ%dѳɹ\n", level); level = 4; } int index; if (act == 0) { // ѡж while (1) { printf("Ҫ:\n"); scanf("%d", &index); if (dying[index]) { printf("㲻ܹ\n"); } else if (dead[index]) { printf("㲻ܹѾ\n"); } else { break; } } // int defen_lv; act = random_int(2, 3); printf("ߴ%s", Name(act)); defen_lv = random_int(1, 100); if (defen_lv > Player[index][act]) { printf("жֵ%dжʧ!\n", defen_lv); defen_lv = 1; } else if (defen_lv > Player[index][act] / 2) { printf("жֵ%dͨɹ\n", defen_lv); defen_lv = 2; } else if (defen_lv > Player[index][act] / 3) { printf("жֵ%dѳɹ\n", defen_lv); defen_lv = 3; } else { printf("жֵ%dѳɹ\n", defen_lv); defen_lv = 4; } if (defen_lv > level) { printf("%dسɹ!\n", index); if (act == ZD_FANJI) { int damage = random_int(1, 3); for (int i = 0; i < Player[player][ZD_SHJZ]; i++) { damage += random_int(1, 4); } Player[player][ZD_HP] -= damage;//յ˺ printf("%dܵ˺%dʣֵ%d", player, damage, Player[player][ZD_HP]); if (Player[player][ZD_HP] < 0) { // ұ״̬ Player[player][ZD_HP] = 1; dying[player] = 1; printf(",%d״̬\n", player); } printf("\n"); } } else { int damage = random_int(1, 3); for (int i = 0; i < Player[player][ZD_SHJZ]; i++) { damage += random_int(1, 4); } Player[index][ZD_HP] -= damage; printf("%dܵ˺%dʣֵ%d", index, damage, Player[index][ZD_HP]); if (Player[index][ZD_HP] < 0) { // ұ״̬ Player[index][ZD_HP] = 1; dying[index] = 1; printf(",%d״̬\n", index); } printf("\n"); } }else if(act==1){ // ҽ while (1) { printf("ҪƵĶ:\n"); scanf("%d", &index); if (dying[index] || dead[index]) { printf("㲻ƱѾĶ\n"); } else { break; } } int point = random_int(1, 100); if (point > Player[player][ZD_YILIAO]) { printf("жֵ%dжʧ\n", point); player++; continue; } else { printf("жֵ%dжɹ\n", point); int cure = 0; if (Player[index][ZD_HP] + Player[player][ZD_YILIAO] > 100) { cure = 100 - Player[index][ZD_HP]; Player[index][ZD_HP] = 100; } else { cure = Player[player][ZD_YILIAO]; Player[index][ZD_HP] += Player[player][ZD_YILIAO]; } printf("%dܵ%d\n", index, cure); } } else { // while (1) { printf("ҪȵĶ:\n"); scanf("%d", &index); if (!dying[index]) { printf("㲻ܶûбĶм\n"); } else { break; } } int point = random_int(1, 100); if (point > Player[player][ZD_JIJIU]) { printf("жֵ%dжʧ\n", point); player++; continue; } else { printf("жֵ%dжɹ\n", point); int cure = 0; cure = Player[player][ZD_YILIAO]; Player[index][ZD_HP] += Player[player][ZD_YILIAO]; printf("%dܵȣѪظ%d\n", index, cure); } } player++; } } int main() { srand((unsigned int)(time(0))); freopen("input.txt", "r", stdin); input_player_info(); fclose(stdin); freopen("CON", "r", stdin); print_player_info(); if (n_player == 2) { trace_mode(); } pvps_mode(); return 0; }
true
8a779fd3d6c2aad42d9bbde0993373c0b9adb97e
C++
btcup/sb-admin
/exams/2559/02204111/2/midterm/4_2_835_5820551567.cpp
UTF-8
500
2.953125
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main() { int n,i,m,j,t; cout<<"Enter a positive integer : "; cin>>n; if(n>0) { i=0; do { n=n/10; i++; } while(n>0); cout<<"\n\n"; cout<<"Number of digit is "<<i<<endl; cout<<"Factor of "<<n<<" are : \n"; j=1; do { { m=m/j; cout<<j<<" * "<<(m)<<endl; j++; } j++; } while(j<1); } else {cout<<"Invalid number !!\n";} system("pause"); return 0; }
true
b176c129ef4569b34419c607c74c6dd30baab2d4
C++
raulMrello/BspManagers
/FSManager/FSManager.cpp
ISO-8859-1
6,426
2.640625
3
[]
no_license
/* * FSManager.cpp * * Created on: Sep 2017 * Author: raulMrello */ #include "FSManager.h" //------------------------------------------------------------------------------------ //--- EXTERN TYPES ------------------------------------------------------------------ //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ //-- PUBLIC METHODS IMPLEMENTATION --------------------------------------------------- //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ FSManager::FSManager(const char *name, PinName mosi, PinName miso, PinName sclk, PinName csel, int freq) : FATFileSystem(name) { // Creo el block device para la spi flash _name = name; _bd = new SPIFBlockDevice(mosi, miso, sclk, csel, freq); _bd->init(); // Monto el sistema de ficheros en el blockdevice _error = FATFileSystem::mount(_bd); // Chequeo si hay informacin de formato, en caso de error formateo y creo archivo if(!ready()){ _error = FATFileSystem::format(_bd); FILE* fd = fopen("/fs/format_info.txt", "w"); if(fd){ _error = fputs("Formateado correctamente\r\n", fd); _error = fclose(fd); } } } //------------------------------------------------------------------------------------ bool FSManager::ready() { FILE* fd = fopen("/fs/format_info.txt", "r"); if(!fd){ return false; } char buff[32] = {0}; if(fgets(&buff[0], 32, fd) == 0){ _error = fclose(fd); return false; } _error = fclose(fd); if(strcmp(buff, "Formateado correctamente\r\n") != 0){ return false; } return true; } //------------------------------------------------------------------------------------ int FSManager::save(const char* data_id, void* data, uint32_t size){ char * filename = (char*)Heap::memAlloc(strlen(data_id) + strlen("/fs/.dat") + 1); if(!filename){ return -1; } sprintf(filename, "/fs/%s.dat", data_id); FILE* fd = fopen(filename, "w"); int written = 0; if(fd){ // reescribe desde el comienzo fseek(fd, 0, SEEK_SET); if(data && size){ written = fwrite(data, 1, size, fd); } fclose(fd); } Heap::memFree(filename); return written; } //------------------------------------------------------------------------------------ int FSManager::restore(const char* data_id, void* data, uint32_t size){ char * filename = (char*)Heap::memAlloc(strlen(data_id) + strlen("/fs/.dat") + 1); if(!filename){ return -1; } sprintf(filename, "/fs/%s.dat", data_id); FILE* fd = fopen(filename, "r"); int rd = 0; if(fd){ if(data && size){ rd = fread(data, 1, size, fd); } fclose(fd); } Heap::memFree(filename); return rd; } //------------------------------------------------------------------------------------ int32_t FSManager::openRecordSet(const char* data_id){ char * filename = (char*)Heap::memAlloc(strlen(data_id) + strlen("/fs/.dat") + 1); if(!filename){ return 0; } sprintf(filename, "/fs/%s.dat", data_id); FILE* fd = fopen(filename, "r+"); Heap::memFree(filename); return (int32_t)fd; } //------------------------------------------------------------------------------------ int32_t FSManager::closeRecordSet(int32_t recordset){ return (int32_t)fclose((FILE*)recordset); } //------------------------------------------------------------------------------------ int32_t FSManager::writeRecordSet(int32_t recordset, void* data, uint32_t record_size, int32_t* pos){ if(!recordset || !data || !record_size){ return 0; } int wr = 0; int32_t vpos = (pos)? (*pos) : 0; // se sita en la posicin deseada if(pos){ fseek((FILE*)recordset, vpos, SEEK_SET); } // actualiza el registro wr = fwrite(data, 1, record_size, (FILE*)recordset); vpos += wr; if(pos){ *pos = vpos; } return wr; } //------------------------------------------------------------------------------------ int32_t FSManager::readRecordSet(int32_t recordset, void* data, uint32_t record_size, int32_t* pos){ if(!recordset || !data || !record_size){ return 0; } int rd = 0; int32_t vpos = (pos)? (*pos) : 0; // se sita en la posicin deseada, o a continuacin if(pos){ fseek((FILE*)recordset, vpos, SEEK_SET); } // lee el registro rd = fread(data, 1, record_size, (FILE*)recordset); vpos += rd; if(pos){ *pos = vpos; } return rd; } //------------------------------------------------------------------------------------ int32_t FSManager::getRecord(const char* data_id, void* data, uint32_t record_size, int32_t* pos){ if(!data || !record_size){ return 0; } char * filename = (char*)Heap::memAlloc(strlen(data_id) + strlen("/fs/.dat") + 1); if(!filename){ return -1; } sprintf(filename, "/fs/%s.dat", data_id); FILE* fd = fopen(filename, "r"); int rd = 0; int32_t vpos = (pos)? (*pos) : 0; if(fd){ // se sita en la posicin deseada fseek(fd, vpos, SEEK_SET); // lee el registro rd = fread(data, 1, record_size, fd); fclose(fd); } vpos += rd; if(pos){ *pos = vpos; } return rd; } //------------------------------------------------------------------------------------ int32_t FSManager::setRecord(const char* data_id, void* data, uint32_t record_size, int32_t* pos){ if(!data || !record_size){ return 0; } char * filename = (char*)Heap::memAlloc(strlen(data_id) + strlen("/fs/.dat") + 1); if(!filename){ return -1; } sprintf(filename, "/fs/%s.dat", data_id); FILE* fd = fopen(filename, "r+"); int wr = 0; int32_t vpos = (pos)? (*pos) : 0; if(fd){ // se sita en la posicin deseada fseek(fd, vpos, SEEK_SET); // actualiza el registro wr = fwrite(data, 1, record_size, fd); fclose(fd); } vpos += wr; if(pos){ *pos = vpos; } return wr; }
true
f98500ced529816e6a20cfcc7267d2d8df964001
C++
srxdev0619/eos-expression-aware-proxy
/3rdparty/toml11/tests/test_get_or.cpp
UTF-8
3,547
2.71875
3
[ "MIT", "Apache-2.0" ]
permissive
#define BOOST_TEST_MODULE "test_get_or" #ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST #include <boost/test/unit_test.hpp> #else #define BOOST_TEST_NO_LIB #include <boost/test/included/unit_test.hpp> #endif #include <toml.hpp> #include <map> #include <unordered_map> #include <list> #include <deque> #include <array> BOOST_AUTO_TEST_CASE(test_get_or_exist) { toml::Boolean raw_v1(true); toml::Integer raw_v2(42); toml::Float raw_v3(3.14); toml::String raw_v4("hoge"); toml::Array raw_v5{2,7,1,8,2}; toml::Table raw_v6{{"key", 42}}; toml::value v1(raw_v1); toml::value v2(raw_v2); toml::value v3(raw_v3); toml::value v4(raw_v4); toml::value v5(raw_v5); toml::value v6(raw_v6); toml::Table table{ {"value1", v1}, {"value2", v2}, {"value3", v3}, {"value4", v4}, {"value5", v5}, {"value6", v6} }; toml::Boolean u1 = toml::get_or(table, "value1", raw_v1); toml::Integer u2 = toml::get_or(table, "value2", raw_v2); toml::Float u3 = toml::get_or(table, "value3", raw_v3); toml::String u4 = toml::get_or(table, "value4", raw_v4); toml::Array u5 = toml::get_or(table, "value5", raw_v5); toml::Table u6 = toml::get_or(table, "value6", raw_v6); BOOST_CHECK_EQUAL(u1, raw_v1); BOOST_CHECK_EQUAL(u2, raw_v2); BOOST_CHECK_EQUAL(u3, raw_v3); BOOST_CHECK_EQUAL(u4, raw_v4); BOOST_CHECK_EQUAL(u5.at(0).cast<toml::value_t::Integer>(), raw_v5.at(0).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(1).cast<toml::value_t::Integer>(), raw_v5.at(1).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(2).cast<toml::value_t::Integer>(), raw_v5.at(2).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(3).cast<toml::value_t::Integer>(), raw_v5.at(3).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(4).cast<toml::value_t::Integer>(), raw_v5.at(4).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at("key").cast<toml::value_t::Integer>(), 42); } BOOST_AUTO_TEST_CASE(test_get_or_empty) { toml::Boolean raw_v1(true); toml::Integer raw_v2(42); toml::Float raw_v3(3.14); toml::String raw_v4("hoge"); toml::Array raw_v5{2,7,1,8,2}; toml::Table raw_v6{{"key", 42}}; toml::Table table; // empty! toml::Boolean u1 = toml::get_or(table, std::string("value1"), raw_v1); toml::Integer u2 = toml::get_or(table, std::string("value2"), raw_v2); toml::Float u3 = toml::get_or(table, std::string("value3"), raw_v3); toml::String u4 = toml::get_or(table, std::string("value4"), raw_v4); toml::Array u5 = toml::get_or(table, std::string("value5"), raw_v5); toml::Table u6 = toml::get_or(table, std::string("value6"), raw_v6); BOOST_CHECK_EQUAL(u1, raw_v1); BOOST_CHECK_EQUAL(u2, raw_v2); BOOST_CHECK_EQUAL(u3, raw_v3); BOOST_CHECK_EQUAL(u4, raw_v4); BOOST_CHECK_EQUAL(u5.at(0).cast<toml::value_t::Integer>(), raw_v5.at(0).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(1).cast<toml::value_t::Integer>(), raw_v5.at(1).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(2).cast<toml::value_t::Integer>(), raw_v5.at(2).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(3).cast<toml::value_t::Integer>(), raw_v5.at(3).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u5.at(4).cast<toml::value_t::Integer>(), raw_v5.at(4).cast<toml::value_t::Integer>()); BOOST_CHECK_EQUAL(u6.at("key").cast<toml::value_t::Integer>(), 42); }
true
dda600c54b800bddda5a12fb3f97accb13b69d40
C++
nursakzhol/Algorithms
/new.cpp
UTF-8
3,144
3.359375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Node { public: int data; Node *left, *right; Node(int data){ this->data = data; left = NULL; right = NULL; } }; class BST { public: vector<int> ct; Node *root; BST(){ root = NULL; } void insert(Node *&node, int data){ if(node == NULL) { node = new Node(data); } if (data == node -> data) { return; } if(data < node->data) { insert(node->left, data); } else { insert(node->right, data); } return; } void inOrder (Node *node) { if (node == NULL) return; inOrder(node->left); if((node->left != NULL) && (node->right == NULL) || (node->left == NULL) && (node->right != NULL) ) cout << node->data << endl; inOrder(node->right); } int findSpace(Node *node){ if (node == NULL) return 0; node = node->right; return findSpace(node->left) + 1; } Node *deleteNode(Node *node, int data){ if(node == NULL) return NULL; if(data < node->data) node->left = deleteNode(node->left, data); else if (data > node->data) node->right = deleteNode(node->right, data); else { if(node->left == NULL && node->right == NULL) return NULL; else if(node->left == NULL) node = node->right; else if(node->right == NULL) node = node->right; else { Node *tmp = findMax(node->left); node->data = tmp->data; node->left = deleteNode(node->left, tmp->data); } } return node; } Node *findMIn(Node *node) { while(node->left != NULL) node = node->left; return node; } Node *findMax(Node *node) { while (node->right!= NULL) { node = node->right; } if(node->left != 0){ findMax(node->left); return node->left; } if (node->left == NULL){ return node; } } void triangles(Node *node){ int cnt = 0; if(node == NULL) return; if(node!= NULL){ if(node->left != NULL && node->right!= NULL) cnt++; triangles(node->right); triangles(node->left); } ct.push_back(cnt); } }; int main(){ BST *bst = new BST(); int n; cin >> n; for (int i = 0; i < n; i++) { int a; cin >> a; bst->insert(bst->root, a); } // Node *node_max = bst->findMax(bst->root); // cout << node_max->data; // bst->inOrder(bst->root); bst->triangles(bst->root); int l = 0; for (int i = 0; i < bst->ct.size(); i++) { if(bst->ct[i] == 1) l++; } cout << l; return 0; }
true
6c72d2a576d678da11a93624640210bd7c9eeabe
C++
LeonardoADS08/Repositorio
/Validaciones C++.cpp
UTF-8
865
3.359375
3
[]
no_license
#include <iostream> #include <cstring> #include <limits> using namespace std; bool verif_solo_numeros(char cad[]) { bool k = true; int i = 0; while(i < strlen(cad) && k==true) { if((cad[i] >= '0') && (cad[i] <= '9')) i++; else k = false; } if (strlen(cad)==0) k = false; return k; } int leerNumeros() { char numero[200]; if (cin.peek() == '\n') cin.ignore(); do { gets(numero); if (!verif_solo_numeros(numero)) cout << "Ingrese un numero" << endl; } while (!verif_solo_numeros(numero)); return atoi(numero); } float leerDecimales() { float res; cin >> res; while (cin.fail()) { cout << "Ingrese un valor valido" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n');; cin >> res; } return res; } int main() { int a; a = leerNumeros(); return 0; }
true
3f80b692a6224365056db3fc80bddba990e9618d
C++
zlaval/ELTE_Prog
/objektum_elvu_programozas/bead2/AnglerEnumerator.h
UTF-8
540
2.53125
3
[]
no_license
#include "ContestEnumerator.h" #ifndef OOP_ANGLERENUMERATOR_H #define OOP_ANGLERENUMERATOR_H struct Angler { std::string name; bool catchOnlyCarp = true; }; class AnglerEnumerator { private: Angler cur; ContestEnumerator contCur; bool eof; public: AnglerEnumerator(const std::string &file) : contCur(file) {}; void next(); bool end() const { return eof; } void first() { contCur.first(); next(); } Angler current() const { return cur; } }; #endif //OOP_ANGLERENUMERATOR_H
true
cd7fb02911e5452a70c9f326dc3eba9e3c89031f
C++
Aditya-013/Hackerrank-Stuff
/DP/FrodulentNotification.cpp
UTF-8
920
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; // int arr[] = {2, 1, 4, 3, 4}; int arr[] = {2, 3, 4, 2, 3, 6, 8, 4, 5}; int cnt[210]; int median(int d){ int p = 0; for(int i=0; i<210; i++){ p += cnt[i]; if(2*p > d){ return 2*i; }else if(2*p == d){ for(int j=i+1;;j++){ if(cnt[j] != 0){ return i + j; } } } } } int main(){ int d = 5; int n = sizeof(arr)/sizeof(int); int count = 0; // int n, d; // std::cin>>n>>d; // int arr[n]; // for(int i=0; i<n; i++){ // std::cin>>arr[i]; // } memset(cnt, 0, sizeof(cnt)); for(int i=0; i<n; i++){ if(i >= d){ if(arr[i] >= median(d)){ count++; } cnt[arr[i-d]]--; } cnt[arr[i]]++; } std::cout<<count<<std::endl; }
true
2360d998566a53dac27b9456e943b4909b51e7ed
C++
InvictusInnovations/keyhotee
/qtreusable/LoginInputBox.cpp
UTF-8
827
2.609375
3
[]
no_license
#include "LoginInputBox.hpp" #include "ui_LoginInputBox.h" LoginInputBox::LoginInputBox(QWidget *parent, const QString& title, QString* userName, QString* password) : QDialog(parent), ui(new Ui::LoginInputBox), _userName(userName), _password(password) { ui->setupUi(this); connect(ui->showPassword, SIGNAL(stateChanged(int)), this, SLOT(onShowPassword(int))); setWindowTitle(title); } LoginInputBox::~LoginInputBox() { delete ui; } void LoginInputBox::accept() { *_userName = ui->userName->text(); *_password = ui->password->text(); QDialog::accept(); } void LoginInputBox::onShowPassword(int checkState) { if (checkState == Qt::Checked) ui->password->setEchoMode(QLineEdit::Normal); else ui->password->setEchoMode(QLineEdit::Password); }
true
82052af0a647eed709edcffcb81efb3aed64d3fe
C++
mshicom/wolf
/src/sensor_gps.cpp
UTF-8
2,391
2.546875
3
[]
no_license
#include "sensor_gps.h" #include "state_block.h" #include "state_quaternion.h" namespace wolf { SensorGPS::SensorGPS(StateBlock* _p_ptr, //GPS sensor position with respect to the car frame (base frame) StateBlock* _o_ptr, //GPS sensor orientation with respect to the car frame (base frame) StateBlock* _bias_ptr, //GPS sensor time bias StateBlock* _map_p_ptr, //initial position of vehicle's frame with respect to starting point frame StateBlock* _map_o_ptr) //initial orientation of vehicle's frame with respect to the starting point frame : SensorBase(SEN_GPS_RAW, "GPS", _p_ptr, _o_ptr, _bias_ptr, 0), map_p_ptr_(_map_p_ptr), map_o_ptr_(_map_o_ptr) { // } SensorGPS::~SensorGPS() { // TODO Check carefully this destructor! } StateBlock *SensorGPS::getMapPPtr() const { return map_p_ptr_; } StateBlock *SensorGPS::getMapOPtr() const { return map_o_ptr_; } void SensorGPS::registerNewStateBlocks() { if (getProblem() != nullptr) { if (p_ptr_ != nullptr) getProblem()->addStateBlockPtr(p_ptr_); if (o_ptr_ != nullptr) getProblem()->addStateBlockPtr(o_ptr_); if (intrinsic_ptr_ != nullptr) getProblem()->addStateBlockPtr(intrinsic_ptr_); if (map_p_ptr_ != nullptr) getProblem()->addStateBlockPtr(map_p_ptr_); if (map_o_ptr_ != nullptr) getProblem()->addStateBlockPtr(map_o_ptr_); } } // Define the factory method SensorBase* SensorGPS::create(const std::string& _unique_name, const Eigen::VectorXs& _extrinsics_p, const IntrinsicsBase* _intrinsics) { // decode extrinsics vector assert(_extrinsics_p.size() == 3 && "Bad extrinsics vector length. Should be 3 for 3D."); StateBlock* pos_ptr = new StateBlock(_extrinsics_p, true); StateBlock* ori_ptr = nullptr; SensorBase* sen = new SensorGPS(pos_ptr, ori_ptr, nullptr, nullptr, nullptr); // TODO: how to init these last three pointers? sen->setName(_unique_name); return sen; } } // namespace wolf // Register in the SensorFactory #include "sensor_factory.h" //#include "factory.h" namespace wolf { namespace { const bool registered_gps = SensorFactory::get().registerCreator("GPS", SensorGPS::create); } } // namespace wolf
true
6452f2da55f5fe7a888e66622f057d8e7a38342e
C++
kjnh10/pcw
/work/atcoder/arc/arc072/F/answers/237760_es.cpp
UTF-8
1,046
2.828125
3
[]
no_license
#include <iostream> #include <vector> #include <deque> #include <cstdio> using namespace std; int main(){ int N, L; while(cin >> N >> L){ deque< pair<double, double> > dq; int t, v; cin >> t >> v; dq.push_back(make_pair(t, v)); printf("%.8lf\n", (double)t); double sumT = t * (double)v; for(int i=1;i<N;i++){ cin >> t >> v; double sub = v; for(int j=0;j<dq.size();j++){ if(dq[j].second <= sub){ sumT -= dq[j].first * dq[j].second; sub -= dq[j].second; dq[j].second = 0; } else { sumT -= dq[j].first * sub; dq[j].second -= sub; break; } } sumT += t * (double)v; printf("%.8lf\n", sumT/L); while(!dq.empty() && dq[0].second < 1e-8) dq.pop_front(); pair<double, double> p = make_pair(t, v); while(!dq.empty()){ if(dq.back().first < p.first) break; double nt = dq.back().first * dq.back().second + p.first * p.second; double nv = dq.back().second + p.second; p.first = nt/nv; p.second = nv; dq.pop_back(); } dq.push_back(p); } } }
true
c38942742170906d218b06ffec774c611d48d344
C++
rjtshrm/point-normals-upsampling
/sampling/sampling.cpp
UTF-8
3,052
2.671875
3
[ "MIT" ]
permissive
#include <torch/extension.h> #include <iostream> // CUDA forward declarations at::Tensor furthest_sampling_cuda_forward( int b, int n, int m, at::Tensor input, at::Tensor temp, at::Tensor idx); at::Tensor gather_points_cuda_forward(int b, int c, int n, int npoints, at::Tensor points, at::Tensor idx, at::Tensor out); at::Tensor gather_points_cuda_backward(int b, int c, int n, int npoints, at::Tensor grad_out, at::Tensor idx, at::Tensor grad_points); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) \ CHECK_CUDA(x); \ CHECK_CONTIGUOUS(x) at::Tensor furthest_sampling_forward( int b, int n, int m, at::Tensor input, at::Tensor temp, at::Tensor idx) { CHECK_INPUT(input); CHECK_INPUT(temp); return furthest_sampling_cuda_forward(b, n, m, input, temp, idx); } at::Tensor gather_points_forward(int b, int c, int n, int npoints, at::Tensor points_tensor, at::Tensor idx_tensor, at::Tensor out_tensor) { CHECK_INPUT(points_tensor); CHECK_INPUT(idx_tensor); return gather_points_cuda_forward(b, c, n, npoints, points_tensor, idx_tensor, out_tensor); } at::Tensor gather_points_backward(int b, int c, int n, int npoints, at::Tensor grad_out_tensor, at::Tensor idx_tensor, at::Tensor grad_points_tensor) { return gather_points_cuda_backward(b, c, n, npoints, grad_out_tensor, idx_tensor, grad_points_tensor); } at::Tensor ball_query_cuda_forward(int b, int n, int m, float radius, int nsample, at::Tensor new_xyz, at::Tensor xyz, at::Tensor out_idx); at::Tensor ball_query_forward(at::Tensor query, at::Tensor xyz, const float radius, const int nsample) { CHECK_INPUT(query); CHECK_INPUT(xyz); at::Tensor idx = torch::zeros({query.size(0), query.size(1), nsample}, at::device(query.device()).dtype(at::ScalarType::Int)); if (query.type().is_cuda()) { ball_query_cuda_forward(xyz.size(0), xyz.size(1), query.size(1), radius, nsample, query, xyz, idx); } else { AT_CHECK(false, "CPU not supported"); } return idx; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("furthest_sampling", &furthest_sampling_forward, "furthest point sampling (no gradient)"); m.def("gather_forward", &gather_points_forward, "gather npoints points along an axis"); m.def("gather_backward", &gather_points_backward, "gather npoints points along an axis backward"); m.def("ball_query", &ball_query_forward, "ball query"); }
true
ce5a059d773a68bf0f0267ca7a9b72225ff0fd37
C++
BackupTheBerlios/wsjt-svn
/branches/wsjtx_w/Detector.hpp
UTF-8
2,012
2.796875
3
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
#ifndef DETECTOR_HPP__ #define DETECTOR_HPP__ #include "AudioDevice.hpp" #include <QScopedArrayPointer> // // output device that distributes data in predefined chunks via a signal // // the underlying device for this abstraction is just the buffer that // stores samples throughout a receiving period // class Detector : public AudioDevice { Q_OBJECT; Q_PROPERTY (bool monitoring READ isMonitoring WRITE setMonitoring); public: // // if the data buffer were not global storage and fixed size then we // might want maximum size passed as constructor arguments // // we down sample by a factor of 4 // // the framesPerSignal argument is the number after down sampling // Detector (unsigned frameRate, unsigned periodLengthInSeconds, unsigned framesPerSignal, unsigned downSampleFactor = 4u, QObject * parent = 0); bool isMonitoring () const {return m_monitoring;} protected: qint64 readData (char * /* data */, qint64 /* maxSize */) { return -1; // we don't produce data } qint64 writeData (char const * data, qint64 maxSize); private: // these are private because we want thread safety, must be called via Qt queued connections Q_SLOT void open (AudioDevice::Channel channel = Mono) {AudioDevice::open (QIODevice::WriteOnly, channel);} Q_SLOT void setMonitoring (bool newState) {m_monitoring = newState; m_bufferPos = 0;} Q_SLOT bool reset (); Q_SLOT void close () {AudioDevice::close ();} Q_SIGNAL void framesWritten (qint64); void clear (); // discard buffer contents unsigned secondInPeriod () const; unsigned m_frameRate; unsigned m_period; unsigned m_downSampleFactor; qint32 m_framesPerSignal; // after any down sampling bool volatile m_monitoring; bool m_starting; QScopedArrayPointer<short> m_buffer; // de-interleaved sample buffer // big enough for all the // samples for one increment of // data (a signals worth) at // the input sample rate unsigned m_bufferPos; }; #endif
true
4df852fc25e6c0432bd718a99e171e0bd5835a47
C++
ill/illEngine
/Input/serial/InputContextStack.cpp
UTF-8
1,421
2.6875
3
[]
no_license
#include <cstdlib> #include "InputContextStack.h" #include "InputContext.h" #include "InputBinding.h" namespace illInput { InputContext * InputContextStack::popInputContext() { InputContext * res = m_stack.back(); //reset states of all input listeners res->resetListeners(); m_stack.pop_back(); return res; } bool InputContextStack::findInputContextStackPos(InputContext * input, size_t& dest) { for(size_t pos = 0; pos < m_stack.size(); pos++) { if(m_stack[pos] == input) { dest = pos; return true; } } return false; } void InputContextStack::replaceInputContext(InputContext * input, size_t stackPos) { m_stack[stackPos] = input; } ListenerBase * InputContextStack::lookupBinding(const char *action) { for(std::vector<InputContext *>::reverse_iterator iter = m_stack.rbegin(); iter != m_stack.rend(); iter++) { ListenerBase * retVal = (*iter)->lookupBinding(action); if(retVal != NULL) { return retVal; } } return NULL; } ValueListener * InputContextStack::lookupValueBinding(const char * action) { for(std::vector<InputContext *>::reverse_iterator iter = m_stack.rbegin(); iter != m_stack.rend(); iter++) { ValueListener * retVal = (*iter)->lookupValueBinding(action); if(retVal != NULL) { return retVal; } } return NULL; } }
true
d580a9af2fd77c101eff36a007953f36ce06cb88
C++
deathcat05/CS450HW4
/FlatPageTable.cpp
UTF-8
900
2.9375
3
[]
no_license
#include<iomanip> // for setw if needed #include<iostream> #include "FlatPageTable.hpp" // my assumption here is that each array will be size 4 // so I'm going to set a const variable to 4 for the size static const int defaultSize = 4; FPTable::FPTable(): size(defaultSize) { fpTable = new int[defaultSize]; } FPTable::FPTable(int valid, int pAddress, int pageBytes) { int _vAddress = vAddress; int _pAddress = pAddress; int _pageBytes = pageBytes; int valid_index = 0; int permission_index = 1; int pageBytes_index = 2; int use_bit_index = 3; } queue FPTable::populate() { // Push a nullptr in to keep track of the start fptQ.push(nullptr); // iteration hard-coded at 4 could have more entries for(int i = 0; i < 4; i++) { // create new array FPTable *ftp = new FPTable(); // I'm just pushing to the back so it stays in order ftpQ.push_back(ftp); } }
true
382c2b53bc5113ff898b47338df8e0a5d1325853
C++
zhanying26252625/leetcode
/MedianOfTwoSortedArrays.h
UTF-8
1,009
3.65625
4
[]
no_license
/* There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). */ class Solution { public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int t = m + n; if(!t) return 0.0; if(t%2) return (double)findkth(A,m,B,n,t/2+1); else return ( findkth(A,m,B,n,t/2+1) + findkth(A,m,B,n,t/2) ) / 2.0 ; } double findkth(int A[], int m, int B[], int n, int k){ if(m>n) return findkth(B,n,A,m,k); if(m==0) return B[k-1]; if(k==1) return min(A[0],B[0]); int a = min(k/2,m); int b = k - a; if(A[a-1]==B[b-1]) return B[b-1]; else if(A[a-1]<B[b-1]) return findkth(A+a,m-a,B,n,k-a); else return findkth(A,m,B+b,n-b,k-b); } };
true
3f2220f88b305c94f14c033841304a40e3e6232a
C++
SvenJo/demo_mandelbrot
/include/easy/picture.h
UTF-8
764
3.3125
3
[ "MIT" ]
permissive
#pragma once namespace easy { template<typename RES_TYPE> struct Picture { Picture(int x, int y) : width_(x) , height_(y) , data_(size_t(x*y)) {} void resize(int w, int h) { width_ = w; height_ = h; data_.resize(size_t(w*h)); } int width() const { return width_; } int height() const { return height_; } const std::vector<RES_TYPE>& data() const { return data_; } std::vector<RES_TYPE>& data() { return data_; } const RES_TYPE* raw() const { return data_.data(); } size_t size() const { return data_.size(); } private: // memory (in the most case the same as width and height) int width_; int height_; std::vector<RES_TYPE> data_; }; }
true
2c3ac4f403099ae97f22ca858509e10a4ba4a311
C++
piash76/Linked-List
/linked_list_2_insert_at_first.cpp
UTF-8
1,089
3.21875
3
[]
no_license
///Bismillahir Rahmanir Rahim ///ALLAHU AKBAR #include<bits/stdc++.h> using namespace std; int a[50]; int n; struct node ///self referential structure { int data; struct node *next; ///pointing to next node }; struct node *head=NULL,*last; void creation() { int i; struct node *t; head=new node; head->data=a[0]; head->next=NULL; last=head; ///saving head in last for(i=1;i<n;i++) { t=new node; t->data=a[i]; t->next=NULL; last->next=t; last=t; } } void display() { struct node *p=new node; p=head; while(p) { printf("%d\n",p->data); p=p->next; } } void insert_at_first(int val) /// 0(1) { struct node *t=new node; t->data=val; t->next=head; head=t; } int main() { cin>>n; for(int i=0;i<n;i++) cin>>a[i]; creation(); display(); ///insert at first int val=0; cout<<"AFTER INSERTING AT FIRST "<<endl; insert_at_first(val); display(); }
true
850f4b34309d1cd775f14cd215128cb60c0f7083
C++
Jerrybubbles/RPGgame
/RPGgame/battle.cpp
UTF-8
6,917
3.015625
3
[]
no_license
#include "battle.h" #include "enemy.h" #include <vector> #include <experimental/random> #include <stdlib.h> #include <time.h> #include <sstream> #include <fstream> #include <string> void menu(){ cout << "a) attack\nb) heal\nUw keuze:" << endl; } Battle::Battle(string path): path{path} { loadMonsters(); } Battle::~Battle() { for (unsigned long i = 0; i < monsterlijst.size(); i++) { delete monsterlijst[i]; monsterlijst[i] = nullptr; } monsterlijst.clear(); std::cout << "each monster deconstructed" << std::endl; } void Battle::loadMonsters() { string fileNaam = getPath(); string gelezenRij = " ",kolom,temp; fstream fileIn; vector<string> rij; fileIn.open(fileNaam, ios::in); while(gelezenRij != ""){ rij.clear(); getline(fileIn, gelezenRij); if( fileIn.eof() ){ break; } stringstream strstrm(gelezenRij); while (getline(strstrm, kolom, ',')) { rij.push_back(kolom); } string name = rij[0]; int hp = stoi(rij[1],nullptr,0), mindmg = stoi(rij[2],nullptr,0), maxdmg = stoi(rij[3],nullptr,0); Enemy * enemyptr = new Enemy{rij[0], hp, mindmg, maxdmg}; monsterlijst.push_back(enemyptr); } } // lambda void Battle::sortMonsters(){ sort(monsterlijst.begin(), monsterlijst.end(), [](Enemy * enemy1, Enemy * enemy2) { return *enemy2 < *enemy1; }); } void Battle::Battletime() { Enemy enemy; Entity * newEnemy = new Enemy{"heks", 10,0,0}; newEnemy->setMaxDamage(5); newEnemy ->printInfo(); //To show the operator overloading Enemy testEnemy{"dummy", 50,5,5}, testEnemy2{"dummy",45,5,5}, testEnemy3{"nietDummy", 55,5,5}; cout << ((testEnemy==testEnemy2)?"true":"false") << ((testEnemy==testEnemy3)?"true":"false") << endl; srand (time(NULL)); unsigned char action; for(int i = 1; i <= 3; i++) { int random_number = (rand() % (monsterlijst.size()-1))+1; switch (i) { case 1: case 2: sortMonsters(); enemy = *monsterlijst[random_number]; cout << "Een " << enemy.getName() << " springt voor je, deze heeft " << enemy.getHitpoints() << " levenspunten." << endl; while(enemy.getHitpoints() > 0 && player1.getHitpoints() > 0) { cout << "Jij hebt " << player1.getHitpoints() << " levenspunten. De "<< enemy.getName() <<" heeft er " << enemy.getHitpoints() << "." << endl; menu(); cin >> action; while (cin.fail() || (action != 'a' && action != 'b')){ cin.clear(); cin.ignore(); cout << "Geef een correcte input!" << endl; cin >> action; } if (action == 'a') { int attackValue; int roll = rand() % 5; if (roll >= 4) { attackValue = rand() % (player1.getMaxDamage() - player1.getMinDamage() +1) +player1.getMinDamage(); attackValue *= 2; cout << "Crit Attack! Je valt aan voor " << attackValue << endl; } else { attackValue = rand() % (player1.getMaxDamage() - player1.getMinDamage() +1) +player1.getMinDamage(); //+1 to include the max damage; cout << "Je valt aan voor " << attackValue << endl; } enemy.hit(attackValue); } else { int randomValue; randomValue = rand() % 8 + 6; player1.heal(randomValue); cout << "Je geneest voor " << randomValue << endl; } int attackValue; attackValue = rand() % (enemy.getMaxDamage() - enemy.getMinDamage() +1) +enemy.getMinDamage(); cout << "De "<< enemy.getName() <<" valt aan voor " << attackValue << endl; player1.hit(attackValue); } if (enemy.getHitpoints() <= 0) { cout << "Je hebt gewonnen, hier komt de volgende vijand!" << endl << endl; } else { cout << "Je bent dood!" << endl; i = 3; } break; case 3: enemy = *monsterlijst[0]; cout << "Een " << enemy.getName() << " springt voor je, deze heeft " << enemy.getHitpoints() << " levenspunten." << endl; while(enemy.getHitpoints() > 0 && player1.getHitpoints() > 0) { cout << "Jij hebt " << player1.getHitpoints() << " levenspunten. De " << enemy.getName() <<" heeft er " << enemy.getHitpoints() << "." << endl; menu(); cin >> action; if (action == 'a') { int attackValue; int roll = rand() % 5; if (roll >= 4) { attackValue = rand() % (player1.getMaxDamage() - player1.getMinDamage() +1) +player1.getMinDamage(); attackValue *= 2; cout << "Crit Attack! Je valt aan voor " << attackValue << endl; } else { attackValue = rand() % (player1.getMaxDamage() - player1.getMinDamage() +1) +player1.getMinDamage(); //+1 to include the max damage; cout << "Je valt aan voor " << attackValue << endl; } enemy.hit(attackValue); } else { cout << "genees" << endl; int randomValue; randomValue = rand() % 8 + 3; player1.heal(randomValue); } int attackValue; attackValue = rand() % (enemy.getMaxDamage() - enemy.getMinDamage() +1) +enemy.getMinDamage(); cout << "De "<< enemy.getName() <<" valt aan voor " << attackValue << endl; player1.hit(attackValue); } if (enemy.getHitpoints() <= 0) { cout << "Je hebt gewonnen, de draak is verslagen!" << endl << endl; } else { cout << "Je bent dood!" << endl; i = 3; } } } cout << "einde!" << endl; delete newEnemy; }
true
913ed185b7c2de83189a48f9a8ec12b338508a4a
C++
kgadgil/block_sparse
/include/print_funcs.h
UTF-8
227
2.671875
3
[]
no_license
/* Print Functions Header file */ #include <iostream> #include <vector> void printVec (const std::vector<auto> vec) { for (auto i : vec){ //pythonic range-based for loops std::cout << i << "\t"; } std::cout << std::endl; }
true
7aad141ce01d7b130279998059bc50c4c571b1dd
C++
naskapal/cPlusPlus
/assignment1/main.cpp
UTF-8
2,773
3.1875
3
[]
no_license
/* * Created by : Rizky Agung Saputro * E1200267 * Assignment 1 C++ */ #include <cstdlib> #include <iostream> using namespace std; struct node{ int num[6]; char name[3]; struct node *next; }; typedef node *nodeptr; void insert(nodeptr &head, int data[], char name[]); nodeptr head = NULL; int holder; int main(){ int i, j, spooler[6], input, *max, choice; max = &holder; char savedName[3]; cout << "--------------------------------------------------"; cout << "--------WELCOME TO RIZKY'S SORTING PROGRAM--------"; cout << "--------------------------------------------------"; cout << "1. Add New Node(s)"; cout << "2. View Current Node(s)"; cout << "3. Delete a Node"; cout << "4. Edit a Node"; cout << "How many times do you want this process to be repeated?" << '\t'; cin >> *max; for (int count = 0; count < *max; count++){ for(i = 0; i < 6; i++){ cout << "type number no "<< (i+1) << '\t'; cin >> input; for(j = 0; j < i; j++){ while (input == spooler[j]){ cout << "duplicate number within this node, please input another number" << '\t'; cin >> input; j=0; } } spooler[i] = input; } cout << "give a name for this struct" << '\t'; cin >> savedName; insert (head,spooler,savedName); if (count != (*max)-1 ) cout << "saved, new node below ..." << endl; else cout << "the result is as follows" << endl << endl; } nodeptr temp = head; bool swap = true; int x = 0,y = 0, temporary; char tempName[3]; for (i = 0; i < holder-1; i++){ if (swap == true){ if (temp->next != NULL){ for (j = 0; j < 6; j++){ x = x + temp->num[j]; y = y + temp->next->num[j]; } if (y < x){ for (j = 0; j < 6; j++){ temporary = temp->next->num[j]; temp->next->num[j] = temp->num[j]; temp->num[j] = temporary; } for (j = 0; j < 3; j++){ tempName[j] = temp->next->name[j]; temp->next->name[j] = temp->name[j]; temp->name[j] = tempName[j]; } swap = true; i = 0; } } } else { swap = false; } x = 0; y = 0; if (i < holder) swap = true; temp = temp->next; } temp = head; for (i = 0; i < holder; i++) { for (j = 0; j < 3; j++) { tempName[j] = temp->name[j]; cout << tempName[j]; } if (i !=(*max) - 1) cout << " -> "; temp = temp->next; } return 0; } void insert(nodeptr &head, int data[], char name[]){ nodeptr temp; int i = 0; temp = new node; for (i = 0; i < 3; i++) temp->name[i] = name[i]; for (i = 0; i < 6; i++) temp->num[i] = data[i]; temp->next = NULL; if(head == NULL){ head = temp; } else{ temp->next=head; head=temp; } }
true
6b17269a1614e9ba887158c03440ece790c34aac
C++
komiga/hord
/src/Hord/Cmd/Object/CmdObjectSetParent.cpp
UTF-8
2,157
2.53125
3
[ "MIT" ]
permissive
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <Hord/aux.hpp> #include <Hord/utility.hpp> #include <Hord/Log.hpp> #include <Hord/IO/Defs.hpp> #include <Hord/Object/Defs.hpp> #include <Hord/Object/Unit.hpp> #include <Hord/Object/Ops.hpp> #include <Hord/Cmd/Object.hpp> #include <exception> #include <Hord/detail/gr_core.hpp> namespace Hord { namespace Cmd { namespace Object { #define HORD_SCOPE_CLASS Cmd::Object::SetParent #define HORD_SCOPE_FUNC exec // pseudo HORD_SCOPE_CLASS::exec_result_type HORD_SCOPE_CLASS::operator()( Hord::Object::Unit& object, Hord::Object::ID const new_parent ) noexcept try { auto& datastore = this->datastore(); m_object_id = object.id(); auto const* parent_obj = datastore.find_ptr(new_parent); if (object.id() == new_parent) { return commit_error("cannot parent object to itself"); } else if (object.parent() == new_parent) { // NB: Circumvents Object::set_parent() making the parent ID_NULL return commit_with(Cmd::Result::success_no_action); } else if (!new_parent.is_null() && !parent_obj) { return commit_error("new parent does not exist"); } else if (parent_obj) { auto const& parent_children = parent_obj ? parent_obj->children() : datastore.root_objects(); for (auto child_id : parent_children) { auto child_obj = datastore.find_ptr(child_id); if (child_obj && object.slug() == child_obj->slug()) { return commit_error("slug would not be unique in new parent"); } } } bool const success = Hord::Object::set_parent(object, datastore, new_parent); auto const end = datastore.root_objects().end(); auto const it = datastore.root_objects().find(object.id()); if (object.parent().is_null()) { if (it == end) { datastore.root_objects().emplace(object.id()); } } else if (it != end) { datastore.root_objects().erase(it); } if (success) { return commit(); } else { return commit_error("Object::set_parent() failed"); } } catch (...) { notify_exception_current(); return commit_error("unknown error"); } #undef HORD_SCOPE_FUNC #undef HORD_SCOPE_CLASS } // namespace Object } // namespace Cmd } // namespace Hord
true
d6cf33e3b5459104c21b035efe105da41918f5d6
C++
bmonte/2018.2
/LP1/lista_1/soma_pares.cpp
UTF-8
359
3
3
[]
no_license
#include <iostream> using namespace std; int main() { int x; while (cin >> x) { int inicio, quantidade, fim, soma = 0; cout << "Insira dois pares: " << endl; cin >> inicio >> quantidade; fim = inicio + quantidade; for (inicio; inicio < fim; inicio++) { soma += inicio; } std::cout << "Soma = " << soma << '\n'; } return 0; }
true
6a82bec1e37f167dba41f91ff03a7cf8c79e4a72
C++
mplucinski/TialVFS
/TialVFS/src/MemoryDriver.cpp
UTF-8
6,223
2.640625
3
[ "BSD-2-Clause" ]
permissive
#include "MemoryDriver.hpp" #include "Exception.hpp" #include <TialUtility/TialUtility.hpp> #define TIAL_MODULE "Tial::VFS::MemoryDriver" Tial::VFS::MemoryDriver::Node::Node(bool directory): directory(directory) { LOGN3; } Tial::VFS::MemoryDriver::FileEntry Tial::VFS::MemoryDriver::Node::get(const Path &path) { auto node = getNode(path); return {path[path.size()-1], node->directory}; } std::shared_ptr<Tial::VFS::MemoryDriver::Node> Tial::VFS::MemoryDriver::Node::getNode(const Path &path) { LOGN2 << "path = " << path; assert(!path.empty()); if(path.size() == 1) return elements.at(path[0]); return elements.at(path[0])->getNode(path.subpath(1)); } std::vector<Tial::VFS::MemoryDriver::FileEntry> Tial::VFS::MemoryDriver::Node::listDirectory(const Path &path) { LOGN2 << "path = " << path; if(path.empty()) { std::vector<Tial::VFS::MemoryDriver::FileEntry> v; for(auto &&i: elements) { LOGN3 << "adding element " << i.first; v.push_back({i.first, i.second->directory}); } return v; } return elements.at(path[0])->listDirectory(path.subpath(1)); } void Tial::VFS::MemoryDriver::Node::createNode(const Path &path, bool directory) { LOGN3 << "Creating node " << path << " (directory = " << directory << ")"; assert(!path.empty()); if(path.size() == 1) { if(elements.find(path[0]) != elements.end()) THROW Exceptions::ElementAlreadyExists(path); elements.emplace(std::make_pair(path[0], std::make_shared<Node>(directory))); } else if(path.size() >= 2) elements[path[0]]->createNode(path.subpath(1), directory); } void Tial::VFS::MemoryDriver::Node::removeNode(const Path &path) { LOGN3 << "Removing node " << path; assert(!path.empty()); if(path.size() == 1) elements.erase(path[0]); else if(path.size() >= 2) elements[path[0]]->removeNode(path.subpath(1)); } Tial::VFS::MemoryDriver::MemoryOpenFile::MemoryOpenFile( const std::shared_ptr<Node> &node): node(node) {} size_t Tial::VFS::MemoryDriver::MemoryOpenFile::read(size_t pos, void *buffer, size_t bufferSize) { LOGN3 << "buffer = " << buffer << ", bufferSize = " << bufferSize; size_t toRead = std::min(node->data.size() - pos, bufferSize); auto inputStart = node->data.cbegin()+pos; auto inputEnd = inputStart+toRead; auto outputStart = reinterpret_cast<uint8_t*>(buffer); auto outputEnd = std::copy(inputStart, inputEnd, outputStart); assert(outputEnd == outputStart+toRead); unused(outputEnd); return toRead; } size_t Tial::VFS::MemoryDriver::MemoryOpenFile::write(size_t pos, const void *buffer, size_t bufferSize) { LOGN3 << "buffer = " << buffer << ", bufferSize = " << bufferSize; auto inputStart = reinterpret_cast<const uint8_t*>(buffer); auto inputSize = bufferSize; auto outputStart = node->data.begin()+pos; auto outputSize = node->data.end()-outputStart; assert(outputSize >= 0); auto overwritePartSize = std::min(inputSize, static_cast<size_t>(outputSize)); std::copy(inputStart, inputStart+overwritePartSize, outputStart); std::copy(inputStart+overwritePartSize, inputStart+inputSize, std::inserter(node->data, node->data.end())); return bufferSize; } size_t Tial::VFS::MemoryDriver::MemoryOpenFile::size() { LOGN3; return node->data.size(); } Tial::VFS::MemoryDriver::MemoryMappedFile::MemoryMappedFile(const std::weak_ptr<Node> &node): node(node) {} void *Tial::VFS::MemoryDriver::MemoryMappedFile::get() { LOGN3 << "this = " << reinterpret_cast<void*>(this); return reinterpret_cast<void*>(node.lock()->data.data()); } size_t Tial::VFS::MemoryDriver::MemoryMappedFile::size() { return node.lock()->data.size(); } void Tial::VFS::MemoryDriver::MemoryMappedFile::resize(size_t size) { LOGN3 << "size = " << size; node.lock()->data.resize(size); } Tial::VFS::MemoryDriver::MemoryDriver(const std::string &name): Driver(name) {} Tial::VFS::MemoryDriver::FileEntry Tial::VFS::MemoryDriver::get(const Path &path) { LOGN2 << "Getting file " << path; assert(path.absolute()); return root->get(path.subpath(1)); } std::vector<Tial::VFS::MemoryDriver::FileEntry> Tial::VFS::MemoryDriver::listDirectory(const Path &path) { LOGN2 << "Listing directory " << path; assert(path.absolute()); return root->listDirectory(path.subpath(1)); } uintmax_t Tial::VFS::MemoryDriver::size(const Path &path) { LOGN2 << "path = " << path; assert(path.absolute()); return root->getNode(path.subpath(1))->data.size(); } void Tial::VFS::MemoryDriver::resize(const Path &path, uintmax_t size) { LOGN2 << "path = " << path << " size = " << size; assert(path.absolute()); root->getNode(path.subpath(1))->data.resize(size); } void Tial::VFS::MemoryDriver::createFile(const Path &path) { LOGN2 << "Creating file " << path; assert(path.absolute()); root->createNode(path.subpath(1), false); } void Tial::VFS::MemoryDriver::removeFile(const Path &path) { LOGN2 << "Removing file " << path; assert(path.absolute()); if(root->getNode(path.subpath(1))->directory) THROW Exceptions::ElementKindInvalid(path, "expected file"); root->removeNode(path.subpath(1)); } void Tial::VFS::MemoryDriver::createDirectory(const Path &path) { LOGN2 << "Creating directory " << path; assert(path.absolute()); root->createNode(path.subpath(1), true); } void Tial::VFS::MemoryDriver::removeDirectory(const Path &path) { LOGN2 << "Removing directory " << path; assert(path.absolute()); if(!root->getNode(path.subpath(1))->directory) THROW Exceptions::ElementKindInvalid(path, "expected directory"); root->removeNode(path.subpath(1)); } std::shared_ptr<Tial::VFS::Driver::OpenFile> Tial::VFS::MemoryDriver::open(const Path &path) { LOGN2 << "Opening file " << path; assert(path.absolute()); auto node = root->getNode(path.subpath(1)); if(node->directory) THROW Exceptions::ElementKindInvalid(path, "expected file"); return std::shared_ptr<MemoryOpenFile>(new MemoryOpenFile(node)); } std::shared_ptr<Tial::VFS::Driver::MappedFile> Tial::VFS::MemoryDriver::map(const Path &path) { LOGN2 << "Mapping file " << path; assert(path.absolute()); auto node = root->getNode(path.subpath(1)); if(node->directory) THROW Exceptions::ElementKindInvalid(path, "expected file"); if(!node->mapping) node->mapping.reset(new MemoryMappedFile(node)); return node->mapping; }
true
17b3362ca5ae4ba0b0ab03873204ec3c7bc828c6
C++
TazzerLabs/Interpreter
/Range.cpp
UTF-8
3,329
3.140625
3
[ "MIT" ]
permissive
/* * Created by Tyler Gearing 3/14/19 * */ #include "Range.hpp" Range::Range(): _start{0}, _end{0}, _step{0} {} Range::Range( int start, int end, int step ): _start{start}, _end{end}, _step{step} {} Range::Range(std::string const &varName, std::vector<std::shared_ptr<ExprNode>> rangeList, SymTab &symTab, std::unique_ptr<FuncTab> &funcTab) { if(rangeList.empty() || rangeList.size() > 3) { std::cout << "Error: Incorrect number of arguments to Range()\n"; exit(1); } else if(rangeList.size() == 1) { // only have an end value std::shared_ptr<NumberDescriptor> start = std::make_shared<NumberDescriptor>(TypeDescriptor::INTEGER); start->value.intValue = 0; // set start to 0 by default symTab.setValueFor( varName, start ); // set value of ID to start auto end = rangeList[0]->evaluate(symTab, funcTab); auto endVal = dynamic_cast<NumberDescriptor *>(end.get()); if( endVal == nullptr ) { std::cout << "Range::Range error casting TypeDescriptor\n"; exit(1); } else if( endVal->type() != TypeDescriptor::INTEGER ) { std::cout << "Error: range can only accept integer values\n"; exit(1); } else { _start = 0; _end = endVal->value.intValue; _step = 1; } } else if(rangeList.size() == 2) { // start and end only, step is 1 auto start = rangeList[0]->evaluate(symTab, funcTab); symTab.setValueFor(varName, start); // set value of ID to start auto end = rangeList[1]->evaluate(symTab, funcTab); auto startVal = dynamic_cast<NumberDescriptor *>(start.get()); if(startVal == nullptr) { std::cout << "startVal error casting TypeDescriptor\n"; exit(1); } auto endVal = dynamic_cast<NumberDescriptor *>(end.get()); if(endVal == nullptr) { std::cout << "endVal error casting TypeDescriptor\n"; exit(1); } else if( startVal->type() != TypeDescriptor::INTEGER || endVal->type() != TypeDescriptor::INTEGER ) { std::cout << "Error: range can only accept integer values\n"; exit(1); } else { _start = startVal->value.intValue; _end = endVal->value.intValue; _step = 1; } } else { // start, end, and step auto start = rangeList[0]->evaluate(symTab, funcTab); symTab.setValueFor(varName, start); // set value of ID to start auto end = rangeList[1]->evaluate(symTab, funcTab); auto step = rangeList[2]->evaluate(symTab, funcTab); auto startVal = dynamic_cast<NumberDescriptor *>(start.get()); auto endVal = dynamic_cast<NumberDescriptor *>(end.get()); auto stepVal = dynamic_cast<NumberDescriptor *>(step.get()); if( startVal == nullptr || endVal == nullptr || stepVal == nullptr) { std::cout << "Range::Range error casting TypeDescriptor\n"; exit(1); } else if( startVal->type() != TypeDescriptor::INTEGER || endVal->type() != TypeDescriptor::INTEGER || stepVal->type() != TypeDescriptor::INTEGER ) { std::cout << "Error: range can only accept integer values\n"; exit(1); } else { _start = startVal->value.intValue; _end = endVal->value.intValue; _step = stepVal->value.intValue; } } } int Range::getNext() { return _start += _step; } bool Range::atEnd() { if(_start > _end && _step < 0) return _start <= _end; else return _start >= _end; } int &Range::start() { return _start; } int &Range::end() { return _end; } int &Range::step() { return _step; }
true
e09aae6c37653addb076c03fb8c414dc2dc3ebe7
C++
oymin2001/DataStructure
/pre/Object-Oriented Programming/Inheritance/Virtual Function/Shape.h
UTF-8
613
3.09375
3
[]
no_license
#ifndef SHAPE_H #define SHAPE_H #include<string> #include"Position.h" using namespace std; enum COLORS{RED,BLUE,BLACK,ORANGE}; extern const char* shapeColor[]; class Shape { friend ostream& operator<<(ostream& S, Shape&); public: Shape(); Shape(Position p, COLORS color, string name); virtual ~Shape(); virtual void draw(); Position getPosition() { return pos; } void setPosition(Position p) { pos.pos_x = p.pos_x; pos.pos_y = p.pos_y; } COLORS getColor() { return color; } void setColor(COLORS c) { color = c; } protected: Position pos; COLORS color; string name; }; #endif // !SHAPE_H
true
b61041893dd1926aa5c6240d4ff0e24ce12219fd
C++
NUC-NCE/algorithm-codes
/codes - ac/HDU/1263/18632852_AC_15ms_1476kB.cpp
UTF-8
1,161
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long ll; using namespace std; struct info { string name; string place; int weight; }m[250]; bool cmp(info a,info b) { if(a.place!=b.place) return a.place<b.place; if(a.place==b.place) return a.name<b.name; } int main() { int n; cin>>n; while(n--) { int x; cin>>x; for(int i=0;i<x;i++) cin>>m[i].name>>m[i].place>>m[i].weight; sort(m,m+x,cmp); for(int i=x-1;i>=1;i--){ if(m[i].name==m[i-1].name&&m[i].place==m[i-1].place) m[i-1].weight+=m[i].weight; } cout<<m[0].place<<endl; cout<<" |----"<<m[0].name<<"("<<m[0].weight<<")"<<endl; for(int i=1;i<x;i++){ if(m[i].place==m[i-1].place&&m[i].name!=m[i-1].name) cout<<" |----"<<m[i].name<<"("<<m[i].weight<<")"<<endl; else if(m[i].place!=m[i-1].place){ cout<<m[i].place<<endl; cout<<" |----"<<m[i].name<<"("<<m[i].weight<<")"<<endl; } } if(n) cout<<endl; } return 0; }
true
b4acd6742991f704178e18f5503bc859f696c184
C++
Maxerum/yo_avp_loot
/mainwindow.cpp
UTF-8
3,400
2.8125
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include <windows.h> #include <iostream> #include <iomanip> #include <intrin.h> #pragma intrinsic(__rdtsc) struct CacheSize { size_t size; size_t lineSize; }; int* arrray; int offset = 1 * 1024 * 1024; int const maxWay = 20; CacheSize getCacheSize(int level) { CacheSize cacheLevel; cacheLevel.lineSize = 0; cacheLevel.size = 0; DWORD bufferSize = 0; DWORD i = 0; SYSTEM_LOGICAL_PROCESSOR_INFORMATION * buffer = 0; GetLogicalProcessorInformation(0, &bufferSize); buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION *)malloc(bufferSize); GetLogicalProcessorInformation(&buffer[0], &bufferSize); for (i = 0; i != bufferSize / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i) { if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == level) { cacheLevel.size = buffer[i].Cache.Size; cacheLevel.lineSize = buffer[i].Cache.LineSize; break; } } free(buffer); return cacheLevel; } int cacheSize = (int)(getCacheSize(1).size); using namespace std; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); chart = new QChart; ui->widget->setChart(chart); QLineSeries *series = new QLineSeries(); chart->legend()->hide(); QFont font; font.setPixelSize(18); QPen pen(QRgb(0x000000)); pen.setWidth(5); series->setPen(pen); cout << "Cache Size: " << cacheSize << " Bytes." << endl; arrray = (int*)malloc(offset * maxWay * sizeof(int)); double timerArray[maxWay]; register unsigned long long startTicks = 0; register unsigned long long endTicks = 0; register unsigned long long resultTicks = 0; register int index = 0; for (int i = 1; i <= maxWay; i++) { startTicks = 0; endTicks = 0; index = 0; init(cacheSize / i, offset, i);//инициализируем массив размером, который будет составлять часть размера кэш-памяти , смещение между блоками, startTicks = __rdtsc(); for (int i = 1; i <= maxWay; i++) { do { index = arrray[index]; } while (index != 0); } endTicks = __rdtsc(); resultTicks = endTicks - startTicks; timerArray[i - 1] = (double)(resultTicks) ; series->append(i, (double)(resultTicks)); } show_time(timerArray); chart->addSeries(series); chart->createDefaultAxes(); } void MainWindow::init(int blockSize, int offset, int n){ for (int i = 0; i < blockSize; i++) { for (int j = 0; j < n; j++) { if (j < n - 1) { arrray[j * offset + i] = (j + 1) * offset + i; } else if (i < blockSize - 1) { arrray[j * offset + i] = i + 1; } else { arrray[j * offset + i] = 0; } } } } void MainWindow::show_time(double* timerArray) { double value = 0; for (int i = 0; i < maxWay; i++) { printf("%02i ", i + 1); value = 0.0; printf("Time - %.0lf ticks\n", timerArray[i]); } } MainWindow::~MainWindow() { delete ui; }
true
ead4ed9252cd3d14b77a288c423ec382803d4240
C++
WeiningLi/Object_Oriented_Programming
/mastermindGame/mastermind.h
UTF-8
783
2.90625
3
[ "MIT" ]
permissive
#ifndef _MASTERMIND_H_ #define _MASTERMIND_H_ #include <random> struct Mastermind { int seed; int codeLength; int guessLimit; char* code; // You may add any data members you require // as well as any member functions you like. // So long as all the methods below are properly // implemented. Mastermind(int seed, int codeLength, int guessLimit); ~Mastermind(); void playGame(); // Do not modify this function char genCodeChar() { static std::default_random_engine gen; static std::uniform_int_distribution<int> dist(0,5); static bool flag = false; if (!flag) { gen.seed(seed); flag = true; } char ret = 'A' + dist(gen); return ret; } }; #endif
true
a228230f78be3652883152b508859b4a6960c55b
C++
sarthak5620/Data-structures-and-Algorithms
/Geeks for Geeks/Arrays/01-maximum in an array.cpp
UTF-8
855
3.5
4
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Height { int feet; int inches; }; int findMax(Height arr[], int n); int main() { int t; cin>>t; while(t--) { int n, tmp1, tmp2; cin>>n; Height arr[n]; for(int i=0; i<n; i++) { cin>>tmp1>>tmp2; arr[i]={tmp1, tmp2}; } int res = findMax(arr, n); cout<<res<<endl; } return 0; } /* Structure of the element of the array is as struct Height { int feet; int inches; }; */ // function must return the maximum Height // return the height in inches int findMax(Height arr[], int n) { int height; int max = (arr[0].feet)*12 + arr[0].inches; for(int i = 0; i < n; i++) { height = (arr[i].feet)*12 + arr[i].inches; if(height > max){ max = height; } } return max; }
true
6f48501a5f11c2077c9fec19362ce8502fc119b3
C++
cvora23/CodingInterviewQ
/BitManipulation/CheckSetCountFind/LittleOrBigEndian.cpp
UTF-8
1,974
4.3125
4
[]
no_license
/* * LittleOrBigEndian.cpp * * Created on: Aug 28, 2013 * Author: cvora */ #include <stdio.h> /** * Little and big endian are two ways of storing multibyte data-types * ( int, float, etc). In little endian machines, last byte of binary * representation of the multibyte data-type is stored first. * On the other hand, in big endian machines, first byte of binary representation * of the multibyte data-type is stored first. * * Suppose integer is stored as 4 bytes (For those who are using DOS based compilers such as C++ 3.0 , integer is 2 bytes) * then a variable x with value 0x01234567 will be stored as following. * * Big Endian * ============== * Address : 0x100 0x101 0x102 0x103 * Value : 01 23 45 67 * * Little Endian * =============== * Address : 0x100 0x101 0x102 0x103 * Value : 67 23 45 67 * */ /* function to show bytes in memory, from location start to start+n*/ void show_mem_rep(unsigned char *start, int n) { int i; for (i = 0; i < n; i++) printf(" %.2x", start[i]); printf("\n"); } /* * In the below program, a character pointer c is pointing to an integer i. * Since size of character is 1 byte when the character pointer is * de-referenced it will contain only first byte of integer. * If machine is little endian then *c will be 1 (because last byte is stored first) and if machine is big endian then *c will be 0 */ void bigOrLittleEndian() { unsigned int i = 1; char *c = (char*)&i; if (*c) printf("Little endian"); else printf("Big endian"); } /*Main function to call above function for 0x01234567*/ int main() { int i = 0x01234567; show_mem_rep((unsigned char *)&i, sizeof(i)); /* * When above program is run on little endian machine, gives “67 45 23 01″ as output , * while if it is run on endian machine, gives “01 23 45 67″ as output. */ bigOrLittleEndian(); getchar(); return 0; }
true
bd112cfa5a070ecbe1ab7816345e49ae567c5728
C++
phartley1/PA1
/PA1Q2.cpp
UTF-8
2,118
3.78125
4
[]
no_license
#include <iostream> #include <math.h> using namespace std; struct pt { float x; float y; }; pt rightcoord(pt, float); bool dooverlap(pt, pt, pt, pt); int main() { float x1; float y1; float a1; float x2; float y2; float a2; pt r1; pt r2; pt l1; pt l2; cout << "enter the upper left x and y coordinates and the area for the first square:" << endl; cout << "\nx-coordinate: " << endl; cin >> x1; while (cin.fail()) { cin.clear(); cin.ignore(10000, '\n'); cout << "enter a number: " << endl; cin >> x1; } cout << "\ny-coordinate: " << endl; cin >> y1; while (cin.fail()) { cin.clear(); cin.ignore(10000, '\n'); cout << "enter a number: " << endl; cin >> y1; } cout << "\narea: " << endl; cin >> a1; while (cin.fail()) { cin.clear(); cin.ignore(10000, '\n'); cout << "enter a number: " << endl; cin >> a1; } cout << "and the second square:" << endl; cout << "\nx-coordinate: " << endl; cin >> x2; while (cin.fail()) { cin.clear(); cin.ignore(10000, '\n'); cout << "enter a number: " << endl; cin >> x2; } cout << "\ny-coordinate: " << endl; cin >> y2; while (cin.fail()) { cin.clear(); cin.ignore(10000, '\n'); cout << "enter a number: " << endl; cin >> y2; } cout << "\narea: " << endl; cin >> a2; while (cin.fail()) { cin.clear(); cin.ignore(10000, '\n'); cout << "enter a number: " << endl; cin >> a2; } l1.x = x1; l1.y = y1; l2.x = x2; l2.y = y2; r1 = rightcoord(l1, a1); r2 = rightcoord(l2, a2); if (dooverlap(l1, r1, l2, r2)) { cout << "squares overlap"; } else { cout << "squares don't overlap"; } return 0; } pt rightcoord(pt l, float a) { pt r; float sidelength; sidelength = sqrt(a); r.x = l.x + sidelength; r.y = l.y - sidelength; return r; } bool dooverlap(pt l1, pt r1, pt l2, pt r2) { if (l1.x > r2.x || l2.x > r1.x) { return false; } else if (l1.y < r2.y || l2.y < r1.y) { return false; } else return true; }
true
1fa0bc581d134fc49e42ba2e45972cbc6c1119d2
C++
alfaisallly/Lectures
/Phd/METU_EEE_ComputerGraphics_642/workshop/EE642Project/ee642_sent_5/LoftedSurfaceContext.cpp
UTF-8
2,967
2.53125
3
[]
no_license
#include "stdafx.h" #include "642Manager.h" #include "userContext.h" CLoftedSurfaceContext* CLoftedSurfaceContext::m_context = 0; CLoftedSurfaceContext::CLoftedSurfaceContext() { recentInputPointCount = 0; m_contextName = "Main Menu"; m_contextInfo = "Main Menu -- You can select an action from the upper right buttons. You can load a predefined object from the 'LOAD' menu. You can draw an arbitrary 2D Object or many type of plane curves from the 'DRAW' menu. You can apply transformation on objects from the 'EDIT' menu. You can close this program by clicking 'EXIT' button."; m_menuCount = 4; m_menuItems = new SMenuItem[m_menuCount]; m_menuItems[0].menuInfo = "Draw a 2D object to render"; m_menuItems[0].menuText = "Bilinear Surface"; m_menuItems[1].menuInfo = "Select a transformation on the current graphics object"; m_menuItems[1].menuText = "Lofted Surface"; m_menuItems[2].menuInfo = "Draw a 3D object to render"; m_menuItems[2].menuText = "Edit"; m_menuItems[3].menuInfo = "Select a transformation on the current 3D graphics object"; m_menuItems[3].menuText = "Main"; } CLoftedSurfaceContext::~CLoftedSurfaceContext() { } CUserContext* CLoftedSurfaceContext::GetInstance() { if (CLoftedSurfaceContext::m_context == 0) { CLoftedSurfaceContext::m_context = new CLoftedSurfaceContext(); } return CLoftedSurfaceContext::m_context; } void CLoftedSurfaceContext::Menu1Selected() { CUserContext::Menu1Selected(); m_manager->ClearRadio(); m_manager->ClearInputArea(); m_manager->SetInput1Name("1.Z"); m_manager->SetInput4Name("2.Z"); m_manager->SetInput2Name("3.Z"); m_manager->SetInput5Name("4.Z"); } void CLoftedSurfaceContext::Menu2Selected() { CUserContext::Menu2Selected(); m_manager->ClearInputArea(); m_manager->SetRadio1(""); } void CLoftedSurfaceContext::Menu3Selected() { CUserContext::Menu3Selected(); m_manager->ChangeContext(C3DTransformContext::GetInstance()); } void CLoftedSurfaceContext::Menu4Selected() { CUserContext::Menu4Selected(); m_manager->ChangeContext(CMainContext2::GetInstance()); } void CLoftedSurfaceContext::Menu5Selected() { } void CLoftedSurfaceContext::Menu6Selected() { } void CLoftedSurfaceContext::Menu7Selected() { } void CLoftedSurfaceContext::Menu8Selected() { } void CLoftedSurfaceContext::Menu9Selected() { } void CLoftedSurfaceContext::ApplyBtnPressed() { (this->*ApplyTransformation)(); } void CLoftedSurfaceContext::RenderAreaLButtonDown(UINT nFlags, CPoint point) { CPoint pt = m_manager->GetMouseLoc(); m_guideXs[recentInputPointCount] = pt.x; m_guideYs[recentInputPointCount] = pt.y; CDC* pDC = m_manager->GetRenderAreaDC(); DrawPrinciplePoint(pDC, pt); m_manager->ReleaseRenderAreaDC(pDC); recentInputPointCount++; } void CLoftedSurfaceContext::DrawPrinciplePoint(CDC* pDC, CPoint pt) { pDC->MoveTo(pt); CBrush br; br.CreateSolidBrush(0xff00); CRect r(pt.x-2, -(pt.y-2), pt.x+2, -(pt.y+2)); pDC->FillRect(r, &br); br.DeleteObject(); }
true
b91d07d21dc59813529692e8d15ffa2172550d41
C++
KevinMathewT/Competitive-Programming
/BrokenClock.cpp
UTF-8
2,079
2.640625
3
[]
no_license
#include <bits/stdc++.h> #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; typedef long long ll; typedef long double ld; typedef vector<ll> vl; typedef vector<vl> vvl; #define F0(i,n) for (ll i = 0; i < n; i++) #define F1(i,n) for (ll i = 1; i <= n; i++) #define CL(a,x) memset(x, a, sizeof(x)); #define SZ(x) ((ll)x.size()) void read(ll &x){ cin >> x; } void read(ll &x,ll &y){ cin >> x >> y; } void read(ll &x,ll &y,ll &z){ cin >> x >> y >> z; } void read(ll &x,ll &y,ll &z,ll &w){ cin >> x >> y >> z >> w; } clock_t t_start,t_end; void start_clock(){ t_start = clock(); } void end_clock(){ t_end = clock(); ld timeis = t_end - t_start; printf("\n\nTime taken : %f s", ((float)timeis)/CLOCKS_PER_SEC); } bool IsOdd(ll n){ return n % 2 == 1; } ld dx = 0.01; pair<ll, ll> doubleToFraction(ld d){ ll i = floor(d); ld f = d - (ld)i; if(f <= dx) return make_pair(1, i); ld next = 1 / f; pair<ll, ll> p = doubleToFraction(next); return make_pair(p.second, (i*p.second) + p.first); } ll gcdExtended(ll a, ll b, ll *x, ll *y) { if (a == 0) { *x = 0, *y = 1; return b; } ll x1, y1; ll gcd = gcdExtended(b%a, a, &x1, &y1); *x = y1 - (b/a) * x1; *y = x1; return gcd; } ll modInverse(ll a, ll m) { ll x, y; ll g = gcdExtended(a, m, &x, &y); ll res = (x % m + m) % m; return res; } void te(){ ld l, d, t; cin >> l >> d >> t; pair<ld, ld> pr = doubleToFraction(l * cos(t * acos(d / l))); ll p = pr.second; ll q = pr.first; cout << p << "/" << q << "\n"; ll r = modInverse(q, 1000000007); //cout << r << "\n"; //cout << (((p*r) % (1000000007)) > 0 ? ((p*r) % (1000000007)) : 1000000007 + ((p*r) % (1000000007))) << "\n"; } int main() { freopen("input.txt", "r", stdin); //Comment freopen("output.txt", "w", stdout); //this start_clock(); //out. ios::sync_with_stdio(false); //Not cin.tie(NULL); //this. cout.tie(0); //or this. ll T; read(T); while(T--) te(); end_clock(); //This too. return 0; }
true
ad5060fe1a2368c3d17b7538f92e105bb953d767
C++
jrmrjnck/jrmrmine
/Radix.cpp
UTF-8
3,999
3.0625
3
[ "Unlicense" ]
permissive
/** * This is free and unencumbered software released into the public domain. **/ #include "Radix.h" #include "Sha256.h" #include <cassert> #include <algorithm> #include <cmath> #include <climits> #include <iostream> #include <iomanip> const int ALPHABET_INVALID_LETTER = -1; // The "system radix" corresponds to the range of the smallest addressable unit, // aka char in C. Data converted to system radix will therefore look like its // raw big-endian representation. const int SYSTEM_RADIX = 1 << CHAR_BIT; const Radix::Alphabet BASE_58_ALPHABET( "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ); Radix::Alphabet::Alphabet( const std::string& encodeTable ) : _encodeTable( encodeTable ) { // Need to find bounds manually since characters in the alphabet may be // out-of-order relative to their numeric value. _lowerBound = std::numeric_limits<char>::max(); _upperBound = 0; for( char ch : encodeTable ) { if( ch < _lowerBound ) { _lowerBound = ch; } if( ch > _upperBound ) { _upperBound = ch; } } // The decode table will be larger than the encode table if there are gaps // in the alphabet. int alphabetRange = _upperBound - _lowerBound; _decodeTable.resize( alphabetRange, ALPHABET_INVALID_LETTER ); for( unsigned int i = 0; i < _encodeTable.size(); ++i ) { char ch = _encodeTable[i]; _decodeTable[ch - _lowerBound] = i; } } ByteArray Radix::base58DecodeCheck( const std::string& base58Str ) { const Alphabet& srcAlphabet = BASE_58_ALPHABET; ByteArray input = decodeAlphabet( base58Str, srcAlphabet ); ByteArray output = convert( input, srcAlphabet._encodeTable.size(), SYSTEM_RADIX ); // If we have enough data to constitute a payload, do a // SHA256(SHA256(payload)) check if( output.size() > 4 ) { ByteArray checkCode( output.end() - 4, output.end() ); output.erase( output.end() - 4, output.end() ); auto rawDigest = Sha256::doubleHash( output ); if( !std::equal(checkCode.begin(), checkCode.end(), rawDigest.begin()) ) throw std::runtime_error( "address check code failed" ); } return output; } ByteArray Radix::decodeAlphabet( const std::string& inputStr, const Alphabet& alphabet ) { ByteArray output; output.reserve( inputStr.size() ); for( int ch : inputStr ) { ch -= alphabet._lowerBound; assert( ch >= 0 && ch <= alphabet._upperBound ); int value = alphabet._decodeTable[ch]; assert( value != ALPHABET_INVALID_LETTER ); output.push_back( value ); } return output; } ByteArray Radix::convert( const ByteArray& input, int srcRadix, int destRadix ) { assert( srcRadix <= SYSTEM_RADIX ); assert( destRadix <= SYSTEM_RADIX ); auto it = std::find_if( input.begin(), input.end(), [](int8_t a){return a != 0;} ); int inputSize = input.size() - (it - input.begin()); // Equivalent of (inputSize / log_srcRadix(destRadix)) int outputSize = std::ceil(inputSize * std::log(srcRadix) / std::log(destRadix)) + 0.5; ByteArray output( outputSize, 0 ); // The conversion algorithm takes a src digit (from the top) and attempts to // stuff it into the dest number (at the bottom). As the digits in the dest // overflow, the remainder is cascaded into the next upper digit. for( auto srcUnit : input ) { int value = srcUnit; for( int outputPos = outputSize - 1; outputPos >= 0; --outputPos ) { value += srcRadix * output[outputPos]; output[outputPos] = value % destRadix; value /= destRadix; } } // The output size calculation has to be conservative, so there may be // leading bytes in the output which have to be removed. Shouldn't be more // than one, though. int removedCount = 0; while( output[0] == 0 ) { output.erase( output.begin() ); ++removedCount; } assert( removedCount <= 1 ); return output; }
true
365b5ef018dd61e7b296c2dd2a7d84be44a341d2
C++
loveyacper/ananas
/net/http/HttpServer.h
UTF-8
1,694
2.734375
3
[ "MIT" ]
permissive
#pragma once #include <functional> #include <memory> #include <string> #include <unordered_map> #include "HttpParser.h" namespace ananas { class Connection; class HttpContext; class HttpServer { public: using Handler = std::function<std::unique_ptr<HttpResponse>(const HttpRequest&, std::shared_ptr<HttpContext>)>; using HandlerMap = std::unordered_map<std::string, Handler>; using OnNewClient = std::function<void(HttpContext*)>; const Handler& GetHandler(const std::string& url) const; void HandleFunc(const std::string& url, Handler handle); void SetOnNewHttpContext(OnNewClient on_new_http); void OnNewConnection(Connection* conn); private: void OnDisconnect(Connection* conn); std::unordered_map<int, std::shared_ptr<HttpContext>> contexts_; HandlerMap handlers_; OnNewClient on_new_http_ctx_; static Handler default_; }; class HttpContext : public std::enable_shared_from_this<HttpContext> { public: HttpContext(llhttp_type type, std::shared_ptr<Connection> c, HttpServer* server); int Parse(Connection*, const char* data, int len); template <typename T> std::shared_ptr<T> GetUserData() const; void SetUserData(std::shared_ptr<void> data) { user_data_ = std::move(data); } void SendResponse(const HttpResponse& rsp); private: // entry for handle http request void HandleRequest(const HttpRequest& req); HttpParser parser_; std::weak_ptr<Connection> conn_; // users may prolong life of ctx HttpServer* server_ = nullptr; std::shared_ptr<void> user_data_; }; template <typename T> inline std::shared_ptr<T> HttpContext::GetUserData() const { return std::static_pointer_cast<T>(user_data_); } } // namespace ananas
true
8b683787992fb8a0be8de63f8ab99679b33c51cc
C++
zhongxinghong/LeetCode
/submissions/169-多数元素-90511379.cpp
UTF-8
719
3.140625
3
[ "MIT" ]
permissive
/** * Submission ID: 90511379 * Question ID: 169 * Question Title: 多数元素 * Question URL: https://leetcode-cn.com/problems/majority-element/ * Solution Time: 2020-07-22 22:52:27 * Solution Test Result: 46 / 46 * Solution Status: Accepted * Solution Memory: 8.7 MB * Solution Runtime: 20 ms */ class Solution { public: int majorityElement(vector<int>& nums) { int i, n = nums.size(), x = nums[0], cnt = 1; for (i = 1; i < n; ++i) { if (nums[i] == x) cnt++; else cnt--; if (cnt == -1) { x = nums[i]; cnt = 1; } } return x; } };
true
54109e825973ed3e301b526675d0db2f38a61376
C++
SChen1024/COJ
/Contest/code1.cpp
UTF-8
1,687
2.859375
3
[]
no_license
/*****************************************************************/ // 包含必须的头文件 #include <iostream> #include <vector> #include <queue> #include <limits.h> #include <bits/stdc++.h> using namespace std; // 定义本地 #define LOCAL_ 1 typedef vector<int> Vint; typedef vector<string> Vstr; typedef vector<vector<int>> VVint; // 常用输出函数 // 一维 数组输出 template <typename T> std::string CoutVec(const T& vec,int flg =0) { std::string str=""; for(int i=0;i<vec.size();i++) { str = to_string(vec[i]), +", "; } // 默认不输出 换行 if(flg) str += "\n"; // cout<<str; return str; } // 二维数组输出 template <typename T> std::string CoutVec2(const T& vec,int flg =0) { std::string str=""; for(int i=0;i<vec.size();i++) { str += CoutVec(vec[i],flg); } return str; } /*****************************************************************/ #define PI 3.1415926535897929894 // 根据精度x 输出小数点后面的数值 string coutPrecision(double y,int x) { string str = to_string(y); int pos = str.find("."); string sub_ = str.substr(0,pos); if(x != 0) sub_ += str.substr(pos,x+1); return sub_; } int main(void) { int N=0; #if LOCAL_ N = 1; #else cin>>N; #endif for(int i=0;i<N;i++) { int n=0,x=0; #if LOCAL_ // n = 1,x=3; n = 7,x=6; // n = 9,x=1; #else cin>>n>>x; #endif double y = pow(n,PI); cout<<coutPrecision(y,x)<<endl; } return 0; }
true
776cf8cebb9631c383b5fb3570961392844d14eb
C++
anonymokata/ae85d9b8-4c15-11ea-90ff-52e448637004
/PencilPoint.h
UTF-8
451
2.609375
3
[]
no_license
#ifndef PENCILDURABILITYKATA_PENCILPOINT_H #define PENCILDURABILITYKATA_PENCILPOINT_H #include <string> class PencilPoint { public: explicit PencilPoint(size_t durability = 20, size_t length = 10); std::string write(const std::string& to_write); void sharpen(); private: char write(char character); size_t mDurability; const size_t mInitialDurability; size_t mLength; }; #endif // PENCILDURABILITYKATA_PENCILPOINT_H
true
2732a8d29ba9e0c946ac14e9e54932cda9218c74
C++
joann8/CPP
/C04/ex00/Cat.hpp
UTF-8
266
2.578125
3
[]
no_license
#ifndef CAT_HPP #define CAT_HPP #include <string> #include <iostream> #include "Animal.hpp" class Cat : public Animal { public: Cat(void); Cat(Cat const & src); ~Cat(void); Cat & operator=(Cat const & src); void makeSound(void) const; }; #endif
true
3f29760a50bf4ba409f87bc35c7d3bf3aba02e8d
C++
soomrack/MR2020
/PanteleevMD/Sorting_Algorithms/insertionsort.cpp
UTF-8
537
3.75
4
[ "MIT" ]
permissive
#include <iostream> void insertion_sort(int* array, int length) { for (int i = 1; i < length; i++) //iterates through { for (int j = i; j>0 && array[j-1]>array[j]; j--) // looks for a A[i]'s place in the sorted part of the list std::swap(array[j], array[j-1]); // by swaps with larger elements - inserts A[i] } } int main() { int a[9] = {-1, 5, -1, 25, -5, 33, 789, -22, -11}; insertion_sort(a, 9); for (int k = 0; k < 9; k++) printf("%d ", a[k]); }
true
4fcfc986752cd6bc0d7000e6640947a53701b443
C++
dzt2/MSGen
/MSGen/ctrace.h
UTF-8
6,143
2.734375
3
[]
no_license
#pragma once /* -File : ctrace.h -Arth : Lin Huan -Date : May 15th 2017 -Purp : to define interfaces for coverage -Clas : [1] LineCoverage [2] FileCoverage [3] CoverageSpace [4] CoverageSource [5] CoverageLoader [6] CTrace */ #include "bitseq.h" #include "cerror.h" #include "cfile.h" #include "ctest.h" #include <map> // declarations class LineCoverage; class FileCoverage; class CoverageSpace; class CoverageSource; class CoverageLoader; class CTrace; /* to represent tests that cover the specific line in code file */ class LineCoverage { protected: /* construct a line coverage in code file */ LineCoverage(const FileCoverage & fil, size_t lin, BitSeq::size_t tnum) : file(fil), line(lin), vec(tnum) {} /* deconstructor */ ~LineCoverage() {} /* set the kth bit in bit-string as 1 */ void cover(const BitSeq::size_t); public: /* get the file coverage of this line */ const FileCoverage & get_file() const { return file; } /* get the line of coverage in code file, starting from 1*/ const size_t & get_line() const { return line; } /* get the bit-string that represents */ const BitSeq & get_vector() const { return vec; } /* create and delete and set coverage */ friend class FileCoverage; private: /* file coverage where this line is defined */ const FileCoverage & file; /* number of line to be covered, starting from 1 */ const size_t line; /* bitstring to represent the tests that covers this line */ BitSeq vec; }; /* coverage of a code file */ class FileCoverage { protected: /* constructor */ FileCoverage(const CoverageSpace &, const CodeFile &, const TestSet &); /* deconstructor */ ~FileCoverage() { release(); } /* load the lines in code file, and update the map from bit-string index to test case id at the same time! */ void load_in(); /* clear the lines, delete all its line coverage in it, and clear test-template at the same time */ void release(); /* set kth line is covered by specified test case */ void cover(size_t, TestCase::ID); public: /* get the space where the file coverage is defined */ const CoverageSpace & get_space() const { return space; } /* get the code file of this coverage */ const CodeFile & get_file() const { return cfile; } /* get the set of tests of this file coverage */ const TestSet & get_tests() const { return tests; } /* whether the kth line is covered */ bool is_covered(const size_t) const; /* get the coverage of kth line */ const LineCoverage & get_line_coverage(const size_t) const; /* create, delete */ friend class CoverageSpace; /* load-release and set-cover */ friend class CoverageLoader; private: /* space where this file coverage is defined */ const CoverageSpace & space; /* code file of this coverage */ const CodeFile & cfile; /* set of tests to cover this file */ const TestSet & tests; /* list that refers to coverage in each line */ std::vector<LineCoverage *> lines; }; /* space for all coverage information */ class CoverageSpace { protected: /* construct a coverage space of all code files in code space */ CoverageSpace(const CTrace &, const CoverageSource &, const CodeSpace &, const TestSpace &); /* deconstructor */ ~CoverageSpace() { this->clear(); } public: /* get the project where this space is defined */ const CTrace & get_project() const { return project; } /* get the source of the coverage space */ const CoverageSource & get_source() const { return source; } /* get the code space for reference */ const CodeSpace & get_code_space() const { return code_space; } /* get the test space for reference */ const TestSpace & get_test_space() const { return test_space; } /* whether there has file coverage for code file */ bool has_file_coverage(const CodeFile &) const; /* get the coverage of specified code file */ FileCoverage & get_file_coverage(const CodeFile &) const; /* set the specified code file as covered by specified test set, this will clear original file coverage! */ void add_file_coverage(const CodeFile &, const TestSet &); /* remove the coverage of specified code file from space */ void del_file_coverage(const CodeFile &); /* clear all the coverage in the space */ void clear(); // create and delete friend class CTrace; private: /* project of coverage */ const CTrace & project; /* coverage source */ const CoverageSource & source; /* code space for reference */ const CodeSpace & code_space; /* test space for reference */ const TestSpace & test_space; /* map from code file to their file coverage */ std::map<const CodeFile *, FileCoverage *> files; }; /* source of ../traces/ */ class CoverageSource { protected: /* constructor */ CoverageSource(const File & d) : dir(d) {} /* deconstructor */ ~CoverageSource() {} public: /* get ../traces/ */ const File & get_trace_dir() const { return dir; } friend class CTrace; private: /* ../traces/ */ const File & dir; }; /* to load the lines in code file and extract coverage from ../trace */ class CoverageLoader { protected: CoverageLoader() {} ~CoverageLoader() {} /* load the lines in code file to the file coverage */ void load_in(FileCoverage & fcov) const { fcov.load_in(); } /* release all lines in file coverage */ void release(FileCoverage & fcov) const { fcov.release(); } /* parse the xxx.c.gcov to coverage information in file coverage */ void parse(FileCoverage &) const; public: // create and delete and load friend class CTrace; private: /* set the coverage of test in specified txx for .gcov file */ void parse(FileCoverage &, TestCase::ID, const File &) const; }; /* project for trace */ class CTrace { public: /* construct project for trace analysis */ CTrace(const File &, const CodeSpace &, const TestSpace &); /* deconstructor */ ~CTrace() { delete space; delete source; } /* get ../ */ const File & get_root() const { return dir; } /* get the coverage space of this project */ CoverageSpace & get_space() const { return *space; } /* load the coverage in file-coverage by ../traces/xxx.c/ */ bool load_coverage(const CodeFile &); private: const File & dir; CoverageSpace * space; CoverageSource * source; CoverageLoader loader; };
true
a12827b8f2d00a54068d8e1f5d5af4a2a07dedf7
C++
657122411/LidarBathymetry
/cpp/LevmarDemo.cpp
UTF-8
3,810
2.8125
3
[]
no_license
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <levmar.h> #ifndef LM_DBL_PREC #error Example program assumes that levmar has been compiled with double precision, see LM_DBL_PREC! #endif #define M_PI 3.14 /* the following macros concern the initialization of a random number generator for adding noise */ #undef REPEATABLE_RANDOM /* #define this for repeatable program behavior across runs */ #define DBL_RAND_MAX (double)(RAND_MAX) #ifdef _MSC_VER // MSVC #include <process.h> #define GETPID _getpid #elif defined(__GNUC__) // GCC #include <sys/types.h> #include <unistd.h> #define GETPID getpid #else #warning Do not know the name of the function returning the process id for your OS / compiler combination #define GETPID 0 #endif /* _MSC_VER */ #ifdef REPEATABLE_RANDOM #define INIT_RANDOM(seed) srandom(seed) #else #define INIT_RANDOM(seed) srandom((int)GETPID()) // seed unused #endif /* Gaussian noise with mean m and variance s, uses the Box-Muller transformation */ double gNoise(double m, double s) { double r1, r2, val; r1 = ((double) rand()) / DBL_RAND_MAX; r2 = ((double) rand()) / DBL_RAND_MAX; val = sqrt(-2.0 * log(r1)) * cos(2.0 * M_PI * r2); val = s * val + m; return val; } /* structure for passing user-supplied data to the objective function and its Jacobian */ struct xtradata { char msg[128]; /* more can be added here... */ }; /* model to be fitted to measurements: x_i = p[0]*exp(-p[1]*i) + p[2], i=0...n-1 */ void expfunc(double *p, double *x, int m, int n, void *data) { register int i; struct xtradata *dat; dat = (struct xtradata *) data; /* user-supplied data can now be accessed as dat->msg, etc */ for (i = 0; i < n; ++i) { x[i] = p[0] * exp(-p[1] * i) + p[2]; } } /* Jacobian of expfunc() */ void jacexpfunc(double *p, double *jac, int m, int n, void *data) { register int i, j; struct xtradata *dat; dat = (struct xtradata *) data; /* user-supplied data can now be accessed as dat->msg, etc */ /* fill Jacobian row by row */ for (i = j = 0; i < n; ++i) { jac[j++] = exp(-p[1] * i); jac[j++] = -p[0] * i * exp(-p[1] * i); jac[j++] = 1.0; } } int main() { const int n = 40, m = 3; // 40 measurements, 3 parameters double p[m], x[n], opts[LM_OPTS_SZ], info[LM_INFO_SZ]; register int i; int ret; struct xtradata data; /* used as an example of passing user-supplied data to expfunc() and jacexpfunc() */ /* generate some measurement using the exponential model with * parameters (5.0, 0.1, 1.0), corrupted with zero-mean * Gaussian noise of s=0.1 */ // INIT_RANDOM(0); for (i = 0; i < n; ++i) x[i] = (5.0 * exp(-0.1 * i) + 1.0) + gNoise(0.0, 0.1); /* initial parameters estimate: (1.0, 0.0, 0.0) */ p[0] = 1.0; p[1] = 0.0; p[2] = 0.0; /* optimization control parameters; passing to levmar NULL instead of opts reverts to defaults */ opts[0] = LM_INIT_MU; opts[1] = 1E-15; opts[2] = 1E-15; opts[3] = 1E-20; opts[4] = LM_DIFF_DELTA; // relevant only if the finite difference Jacobian version is used /* example of user-supplied data */ strcpy(data.msg, "Hello there!"); /* invoke the optimization function */ ret = dlevmar_der(expfunc, jacexpfunc, p, x, m, n, 1000, opts, info, NULL, NULL, (void *) &data); // with analytic Jacobian //ret=dlevmar_dif(expfunc, p, x, m, n, 1000, opts, info, NULL, NULL, (void *)&data); // without Jacobian printf("Levenberg-Marquardt returned in %g iter, reason %g, sumsq %g [%g]\n", info[5], info[6], info[1], info[0]); printf("Best fit parameters: %.7g %.7g %.7g\n", p[0], p[1], p[2]); exit(0); system("pause"); }
true
d6be3f108f5744d8c715d8454a1ea19a1e5574de
C++
gibule/gibule
/gblthread.cpp
UTF-8
341
2.578125
3
[]
no_license
#include "gblthread.h" GBLThread::GBLThread() { } GBLThread::~GBLThread() { } void GBLThread::start() { running=true; thr=thread(&GBLThread::run,this); } void GBLThread::stop() { running=false; } bool GBLThread::isRunning() { return running; } void GBLThread::run() { } void GBLThread::wait() { thr.join(); }
true
b6527197ad4858d3ef15210dcd51aebcd3e8dfd5
C++
extinguish/Cpp17CompleteGuide
/cpp_move/src/generic/universaltype.cpp
UTF-8
1,687
3.4375
3
[]
no_license
//******************************************************** // The following code example is taken from the book // C++ Move Semantics - The Complete Guide // by Nicolai M. Josuttis (www.josuttis.com) // http://www.cppmove.com // // The code is licensed under a // Creative Commons Attribution 4.0 International License // http://creativecommons.org/licenses/by/4.0/ //******************************************************** #include <iostream> #include <string> #include <string_view> // require a universal reference of a specific type: // - no implicit type conversions supported template<typename T> requires std::is_same_v<std::remove_cvref_t<T>, std::string> void requireSame(T&&) { //... } // require a universal reference of a specific type: // - implicit but no explicit type conversions supported template<typename T> requires std::is_convertible_v<T, std::string> void requireConvertible(T&&) { //... } // require a universal reference of a specific type: // - even explicit type conversions supported // note: the order of arguments differs template<typename T> requires std::is_constructible_v<std::string, T> void requireConstructible(T&&) { //... } int main() { std::string s = "hi"; std::string_view sv = "hi"; requireSame(s); // OK //requireSame(sv); // ERROR: no std::string //requireSame("hi"); // ERROR: no std::string requireConvertible(s); // OK //requireConvertible(sv); // ERROR: not implicit conversion to std::string requireConvertible("hi"); // OK requireConstructible(s); // OK requireConstructible(sv); // OK (explicit conversion used) requireConstructible("hi"); // OK }
true
bbac29a9961a6f970966d843497fc1c559a2f58b
C++
Paranauerj/Crosswords
/Source/Classes/jogador.cpp
MacCentralEurope
4,011
2.734375
3
[ "MIT" ]
permissive
#include "imports.h" #include "ponto.h" #include "letra.h" #include "palavra.h" #include "tabuleiro.h" #include "jogador.h" Jogador::Jogador() { this->nome = "a"; this->idade = 0; this->pontos = 0; } Jogador::~Jogador() { } Jogador::Jogador(string nomeP, int idadeP, int pontosP) { this->nome = nomeP; this->idade = idadeP; this->pontos = pontosP; } Jogador::Jogador(string nomeP, int idadeP) { this->nome = nomeP; this->idade = idadeP; this->pontos = 0; } bool Jogador::existeJogador() { char caminho[80]; strcpy_s(caminho, "./Saves/"); strcat_s(caminho, this->nome.c_str()); int check = _mkdir(caminho); if (check == -1) { return true; } else { return false; } } void Jogador::saveScore() { char caminho[80]; char caminhoScore[90]; strcpy_s(caminho, "./Saves/"); strcat_s(caminho, this->nome.c_str()); int check = _mkdir(caminho); if (check == -1) { // J existe } else { // Nao existe } strcpy_s(caminhoScore, caminho); strcat_s(caminhoScore, "/"); strcat_s(caminhoScore, "score.db"); ofstream os {caminhoScore, std::ios_base::app }; os << this->pontos << endl; os.close(); } int* Jogador::loadScore() { int* scores; int aux = 1; string laux; char caminho[80]; char caminhoScore[90]; strcpy_s(caminho, "./Saves/"); strcat_s(caminho, this->nome.c_str()); int check = _mkdir(caminho); if (check == -1) { strcpy_s(caminhoScore, caminho); strcat_s(caminhoScore, "/"); strcat_s(caminhoScore, "score.db"); ifstream is; is.open(caminhoScore); while (getline(is, laux)) { aux++; // cout << aux << endl; } is.close(); scores = new int(aux); scores[0] = aux; is.open(caminhoScore); for(int j = 1; j < aux; j++) { is >> scores[j]; } is.close(); return scores; } else { // Nao existe } } void Jogador::showScore() { int b = loadScore()[0]; int* a; a = new int(b); a = loadScore(); for (int i = 1; i < b; i++) { cout << "Pontuacao " << i << " : " << a[i] << endl; } } void Jogador::saveInfo() { char caminho[80]; char caminhoInfo[90]; strcpy_s(caminho, "./Saves/"); strcat_s(caminho, this->nome.c_str()); int check = _mkdir(caminho); if (check == -1) { // J existe } else { // Nao existe } strcpy_s(caminhoInfo, caminho); strcat_s(caminhoInfo, "/"); strcat_s(caminhoInfo, "info.db"); ofstream os; os.open(caminhoInfo); os << this->nome << endl << this->idade << endl << this->pontos; os.close(); } void Jogador::loadInfo(string a) { char caminho[80]; char caminhoInfo[90]; strcpy_s(caminho, "./Saves/"); strcat_s(caminho, a.c_str()); int check = _mkdir(caminho); if (check == -1) { strcpy_s(caminhoInfo, caminho); strcat_s(caminhoInfo, "/"); strcat_s(caminhoInfo, "info.db"); ifstream is; is.open(caminhoInfo); for (int i = 0; i < 3; i++) { if (i == 0) { getline(is, this->nome); } else { if (i == 1) { is >> this->idade; } else { is >> this->pontos; } } } is.close(); } else { // Nao existe } } bool Jogador::inArray(string* arr, string a, int n) { bool retorno = false; for (int i = 0; i < n; i++) { if (arr[i] == a) { retorno = true; } } return retorno; } bool Jogador::inArray(Palavra* arr, string a, int n) { bool retorno = false; for (int i = 0; i < n; i++) { if (arr[i].getVetLetrasStr() == a) { retorno = true; } } return retorno; } string Jogador::readPlayOpt(int c) { bool a = true; string b; cout << "Escreva a palavra do caca palavras ('sair' para sair): " << endl; if (c == 0) { cin.ignore(256, '\n'); getline(cin, b); } else{ getline(cin, b); } return b; } bool Jogador::tryWord(Tabuleiro tl, string a) { if (inArray(tl.getPalavras(), a, tl.getNPalavras())) { return true; } else { return false; } }
true
48b0c63842728a8855b9b0bbea68ba5ddac34488
C++
watashi/AlgoSolution
/leetcode/weekly-261/2027.cpp
UTF-8
233
2.875
3
[]
no_license
class Solution { public: int minimumMoves(string s) { int x = 0, y = 0; for (char c : s) { if (c != 'O') { if (x <= 0) { x = 3; ++y; } } --x; } return y; } };
true
079d0be2613044d7bda9467a72207fc55689e52f
C++
ultrablox/ultra_planner
/src/core/bit_container.cpp
UTF-8
3,644
2.5625
3
[]
no_license
#include "bit_container.h" #include "UError.h" //#include <vld.h> //#include <intrin.h> #include <type_traits> #include <assert.h> //========================Bitset========================== bit_vector::bit_vector(const std::initializer_list<bool> & _value) { resize(_value.size()); size_t i = 0; for (auto _bit : _value) set(i++, _bit); } void bit_vector::setValues(const bool value) { //T val = 0; if(value) memset(mData.data(), 0xff, sizeof(value_type) * mData.size()); else memset(mData.data(), 0x0, sizeof(value_type) * mData.size()); // clearTail(); } vector<size_t> bit_vector::toIndices() const { vector<size_t> result; for(size_t i = 0; i < mBitCount; ++i) { if((*this)[i]) result.push_back(i); } return result; } int bit_vector::trueCount() const { #if USE_INTRINSIC int res(0); //for(auto el : mData) // res += __popcnt(el.m); return res; #else return toIndices().size(); #endif } /* void bit_vector::setMasked(const bit_vector & value, const bit_vector & mask) { #if _DEBUG checkSizes(*this, value, mask); #endif value_type * cur_ptr = mData.data(); const value_type * val_ptr = value.mData.data(), *mask_ptr = mask.mData.data(); for(size_t bit_index = 0, max_bit = mData.size(); bit_index < max_bit; ++bit_index) { *cur_ptr = ((*cur_ptr) & (~(*mask_ptr))) | ((*val_ptr) & (*mask_ptr)); ++cur_ptr; ++val_ptr; ++mask_ptr; } } bool bit_vector::equalMasked(const bit_vector & value, const bit_vector & mask) const { #if _DEBUG checkSizes(*this, value, mask); #endif const value_type * cur_ptr = mData.data(), * val_ptr = value.mData.data(), *mask_ptr = mask.mData.data(); bool r = true; for(size_t i = mData.size(); i > 0 ; --i) { if(!((*val_ptr) == ((*cur_ptr) & (*mask_ptr)))) { return false; } ++cur_ptr; ++val_ptr; ++mask_ptr; } return r; }*/ /* size_t bit_vector::equalCountMasked(const bit_vector & _value, const bit_vector & _mask) const { const value_type * cur_ptr = mData.data(), * val_ptr = _value.mData.data(), *mask_ptr = _mask.mData.data(); size_t sum(0); for(size_t i = mData.size(); i > 0 ; --i) { value_type cur_value = *cur_ptr, value = *val_ptr, mask = *mask_ptr; //T cv_nm = cur_value & mask, v_nm = value & mask; //T x = (cv_nm) ^ (v_nm); value_type res = mask & (~((cur_value & mask) ^ (value & mask))); for(int i = sizeof(value_type) * 8; i > 0; --i) { sum += res & 1; res >>= 1; } ++cur_ptr; ++val_ptr; ++mask_ptr; } return sum; }*/ /* size_t bit_vector::serialize(void * dest) const { char * cdest = (char*)dest; size_t res = 0; //Byte Count res += serialize_int(cdest, mData.size()); //Byte Data memcpy(&cdest[res], mData.data(), byteCount()); res += byteCount(); return res; }*/ /* size_t bit_vector::deserialize(char * dest) { size_t r(0); int element_count; r += deserialize_int(dest, element_count); mData.resize(element_count); const size_t data_size = element_count * sizeof(value_type); memcpy(mData.data(), dest + r, data_size); r += data_size; return r; } void bit_vector::serialize(std::ofstream & os) const { serialize_int(os, mBitCount); serialize_vector(os, mData); } int bit_vector::deserialize(std::ifstream & is) { mBitCount = deserialize_int(is); mData = deserialize_vector<vector<value_type>>(is); return 0; }*/ void bit_vector::checkSizes(const bit_vector & bc1, const bit_vector & bc2, const bit_vector & bc3) { const size_t s1 = bc1.mData.size(), s2 = bc2.mData.size(), s3 = bc3.mData.size(); if(!((s1 == s2) && (s2 == s3))) throw core_exception("UBitContainer::checkSizes error: Can't process bitsets with different size."); }
true
df7d542ad41fd199f98dcb98810eed698c7d314f
C++
mfkiwl/HDRView
/src/MultiGraph.h
UTF-8
3,150
2.578125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
// // Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE.txt file. // #pragma once #include <nanogui/widget.h> using namespace nanogui; /** * \class MultiGraph multigraph.h * * \brief A generalization of nanogui's graph widget which can plot multiple graphs on top of each other */ class MultiGraph : public Widget { public: MultiGraph(Widget *parent, const Color & fg = Color(255, 192, 0, 128), const VectorXf & v = VectorXf()); const Color &backgroundColor() const { return mBackgroundColor; } void setBackgroundColor(const Color &backgroundColor) { mBackgroundColor = backgroundColor; } const Color &textColor() const { return mTextColor; } void setTextColor(const Color &textColor) { mTextColor = textColor; } int numPlots() const {return mValues.size();} void addPlot(const Color & fg = Color(), const VectorXf & v = VectorXf()) {mValues.push_back(v); mForegroundColors.push_back(fg);} void popPlot() {mValues.pop_back(); mForegroundColors.pop_back();} bool well() const { return mInWell; } void setWell(bool b) { mInWell = b; } bool filled() const { return mFilled; } void setFilled(bool b) { mFilled = b; } const Color &foregroundColor(int plot = 0) const { return mForegroundColors[plot]; } void setForegroundColor(const Color &foregroundColor, int plot = 0) { mForegroundColors[plot] = foregroundColor; } const VectorXf &values(int plot = 0) const { return mValues[plot]; } VectorXf &values(int plot = 0) { return mValues[plot]; } void setValues(const VectorXf &values, int plot = 0) { mValues[plot] = values; } void setXTicks(const VectorXf & ticks, const std::vector<std::string> & labels); void setYTicks(const VectorXf & ticks) { mYTicks = ticks; } void setLeftHeader(const std::string & s) { mLeftHeader = s; } void setCenterHeader(const std::string & s) { mCenterHeader = s; } void setRightHeader(const std::string & s) { mRightHeader = s; } std::function<void(const Vector2f &)> dragCallback() const { return mDragCallback; } void setDragCallback(const std::function<void(const Vector2f &)> &callback) { mDragCallback = callback; } virtual Vector2i preferredSize(NVGcontext *ctx) const override; virtual void draw(NVGcontext *ctx) override; virtual bool mouseDragEvent(const Vector2i &p, const Vector2i &rel, int button, int modifiers) override; virtual bool mouseButtonEvent(const Vector2i &p, int button, bool down, int modifiers) override; virtual void save(Serializer &s) const override; virtual bool load(Serializer &s) override; protected: Vector2f graphCoordinateAt(const Vector2f& position) const; float xPosition(float xfrac) const; float yPosition(float yfrac) const; Color mBackgroundColor, mTextColor; std::vector<Color> mForegroundColors; std::vector<VectorXf> mValues; bool mFilled = true, mInWell = true; std::string mLeftHeader, mCenterHeader, mRightHeader; VectorXf mXTicks, mYTicks; std::vector<std::string> mXTickLabels; std::function<void(const Vector2f &)> mDragCallback; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW };
true
9473f39c961edecbf6e3c58ea433baf40f61ebe6
C++
jpollock0010/TheGameCostCalculator
/Game Cost Calculator/Game Cost Calculator.cpp
UTF-8
12,344
3.1875
3
[]
no_license
/*Game Cost Calculator Author: Jamie Pollock Date: 7/8/2016 3:51 PM Eastern Time Edited: 7/9/2016 8:11 AM Eastern Time Edited 2: 7/29/2016 11:05 AM Eastern Time*/ #include <iomanip> // Allows the output of monetary values to contain only TWO (2) decimal points. #include <istream> #include <string> #include <stdlib.h> // Allows program to clear screen. #include <fstream> // Allows writing to a text file. #include <iostream> using namespace std; int main() { // Variables string gameTitle, gameXtra1, gameXtra2; char insuranceAnswer, saveFileAnswer; float fullPrice, deposit, gameXtraCost1, gameXtraCost2, insurance, salesTax, currentBalance, remainingBalance, spendingMoney; float fullPriceWTax, xtra1WTax, xtra2WTax, insuranceWTax, totalPrice, totalTax, totalPriceWTax, priceWDeposit, priceWDepWTax; // Program code begins here. cout << "Please enter the TITLE of the game you would like to buy." << endl; getline(cin, gameTitle); cout << endl; cout << "Please enter the full cost of " << gameTitle << " (WITHOUT tax)." << endl; cout << "$"; cin >> fullPrice; cout << endl; cout << "Please enter the cost of the DEPOSIT placed to secure your copy of the game." << endl; cout << "$"; cin >> deposit; cout << endl; cout << "Please enter the FIRST type of extra content you will be purchasing." << endl; cin.ignore(); getline(cin, gameXtra1); cout << endl; cout << "Please enter the cost of " << gameXtra1 << "." << endl; cout << "$"; cin >> gameXtraCost1; cout << endl; cout << "Please enter the SECOND type of extra content you will be purchasing." << endl; cin.ignore(); getline(cin, gameXtra2); cout << endl; cout << "Please enter the cost of " << gameXtra2 << "." << endl; cout << "$"; cin >> gameXtraCost2; cout << endl; cout << "Will you be purchasing insurance for " << gameTitle << " ?" << endl; cout << "Please type (Y) or (y) for (YES) or (N) or (n) for (NO)." << endl; cin >> insuranceAnswer; if (insuranceAnswer == 'Y' || 'y') { insuranceAnswer == 'y'; } if (insuranceAnswer == 'N' || 'n') { insuranceAnswer == 'n'; } switch (insuranceAnswer) { case 'y': { cout << endl; cout << "Please enter the cost of the insurance for the " << gameTitle << " game." << endl; cout << "$"; cin >> insurance; cout << endl; break; } case 'n': { cout << endl; cout << "You have chosen NOT to purchase insurance for the " << gameTitle << " game." << endl; cout << endl; insurance = 0; break; } default: { cout << endl; cout << "Invalid answer. Please try again." << endl; cin >> insuranceAnswer; } } cout << "Please enter the SALES TAX for your state (WITHOUT % SYMBOL)." << endl; cin >> salesTax; cout << endl; cout << "Please enter the current balance you have saved for the " << gameTitle << " game." << endl; cout << "$"; cin >> currentBalance; cout << endl; cout << "We will now calculate your remaining necessary balance or, if you have reached the required total amount, the amount of spending money you have left." << endl; cout << endl; // The following prevents the program from automatically clearing the screen. do { cout << '\n' << "Press any key to continue."; cin.get(); } while (cin.get() != '\n'); system("cls"); // This prevents the program from showing more than 2 decimal points in the output. cout << setiosflags(ios::fixed | ios::showpoint); cout.precision(2); // Necessary equations for the final output. totalPrice = (((fullPrice-deposit)+insurance) + (gameXtraCost1 + gameXtraCost2)); priceWDeposit = (fullPrice - deposit); salesTax = (salesTax/100); fullPriceWTax = ((fullPrice*salesTax) + fullPrice); xtra1WTax = ((gameXtraCost1*salesTax) + gameXtraCost1); xtra2WTax = ((gameXtraCost2*salesTax) + gameXtraCost2); insuranceWTax = ((insurance*salesTax) + insurance); totalPriceWTax = (((fullPriceWTax-deposit)+insuranceWTax) + (xtra1WTax + xtra2WTax)); totalTax = (totalPriceWTax-totalPrice); priceWDepWTax = (fullPriceWTax - deposit); remainingBalance = (totalPriceWTax - currentBalance); spendingMoney = (currentBalance - totalPriceWTax); cout << "WITHOUT SALES TAX:" << endl; cout << endl; cout << gameTitle << ": $" << fullPrice << endl; cout << "Deposit: -$" << deposit << endl; cout << "Price After Deposit: $" << priceWDeposit << endl; cout << gameXtra1 << ": $" << gameXtraCost1 << endl; cout << gameXtra2 << ": $" << gameXtraCost2 << endl; switch (insuranceAnswer) { case 'y': { cout << "Game Insurance: $" << insurance << endl; break; } case 'n': { break; } default: { break; } } cout << "____________________________________________________" << endl; cout << "TOTAL PRICE: $" << totalPrice << endl; cout << "====================================================" << endl; cout << endl; cout << "WITH SALES TAX:" << endl; cout << endl; cout << gameTitle << ": $" << fullPriceWTax << endl; cout << "Deposit: -$" << deposit << endl; cout << "Price After Deposit: $" << priceWDepWTax << endl; cout << gameXtra1 << ": $" << xtra1WTax << endl; cout << gameXtra2 << ": $" << xtra2WTax << endl; switch (insuranceAnswer) { case 'y': { cout << "Game Insurance: $" << insuranceWTax << endl; break; } case 'n': { break; } default: { break; } } cout << "Tax: $" << totalTax << endl; cout << "____________________________________________________" << endl; cout << "TOTAL PRICE: $" << totalPriceWTax << endl; cout << "====================================================" << endl; cout << endl; cout << "Your current balance:" << endl; cout << "$" << currentBalance << endl; cout << endl; if (currentBalance >= totalPriceWTax) { cout << "You have reached the required amount to purchase " << gameTitle << " and the extra content!" << endl; cout << "Spending Money: $" << spendingMoney << endl; cout << endl; } else if (currentBalance <= totalPriceWTax) { cout << "REMAINING FUNDS REQUIRED: $" << remainingBalance << endl; cout << endl; } cout << "Would you like to save this information to a file?" << endl; cout << "Please type (Y) or (y) for (YES) or (N) or (n) for (NO)." << endl; cin >> saveFileAnswer; if (saveFileAnswer == 'Y' || 'y') { saveFileAnswer == 'y'; } if (saveFileAnswer == 'N' || 'n') { saveFileAnswer == 'n'; } switch (saveFileAnswer) { case 'y': { cout << "Writing to file..." << endl << endl; ofstream SaveFile; SaveFile.open("Game Cost Calculator.txt"); SaveFile << "WITHOUT SALES TAX:" << endl; SaveFile << endl; SaveFile << gameTitle << ": $" << fullPrice << endl; SaveFile << "Deposit: -$" << deposit << endl; SaveFile << "Price After Deposit: $" << priceWDeposit << endl; SaveFile << gameXtra1 << ": $" << gameXtraCost1 << endl; SaveFile << gameXtra2 << ": $" << gameXtraCost2 << endl; switch (insuranceAnswer) { case 'y': { SaveFile << "Game Insurance: $" << insurance << endl; break; } case 'n': { break; } default: { break; } } SaveFile << "____________________________________________________" << endl; SaveFile << "TOTAL PRICE: $" << totalPrice << endl; SaveFile << "====================================================" << endl; SaveFile << endl; SaveFile << "WITH SALES TAX:" << endl; SaveFile << endl; SaveFile << gameTitle << ": $" << fullPriceWTax << endl; SaveFile << "Deposit: -$" << deposit << endl; SaveFile << "Price After Deposit: $" << priceWDepWTax << endl; SaveFile << gameXtra1 << ": $" << xtra1WTax << endl; SaveFile << gameXtra2 << ": $" << xtra2WTax << endl; switch (insuranceAnswer) { case 'y': { SaveFile << "Game Insurance: $" << insuranceWTax << endl; break; } case 'n': { break; } default: { break; } } SaveFile << "Tax: $" << totalTax << endl; SaveFile << "____________________________________________________" << endl; SaveFile << "TOTAL PRICE: $" << totalPriceWTax << endl; SaveFile << "====================================================" << endl; SaveFile << endl; SaveFile << "Your current balance:" << endl; SaveFile << "$" << currentBalance << endl; SaveFile << endl; if (currentBalance >= totalPriceWTax) { SaveFile << "You have reached the required amount to purchase " << gameTitle << " and the extra content!" << endl; SaveFile << "Spending Money: $" << spendingMoney << endl; SaveFile << endl; } else if (currentBalance <= totalPriceWTax) { SaveFile << "REMAINING FUNDS REQUIRED: $" << remainingBalance << endl; SaveFile << endl; } SaveFile.close(); cout << "Done! Your file \"Game Cost Calculator\" is saved!" << endl; break; } case 'n': { cout << "You have chosen NOT to save this information." << endl << endl; break; } default: { cout << "Invalid answer. Please try again." << endl; cin >> insuranceAnswer; } } // The following prevents the program from automatically closing its window before the user can see the output. do { cout << '\n' << "Press any key to exit the program."; cin.get(); } while (cin.get() != '\n'); return 0; }
true
ef5a20b67607a3be4746ec11d575ead2922ed0f4
C++
trinhlehainam/ASO_3rd_year_GameArchitecture
/ProgramStudy/Source/Component/SpriteComponent.cpp
UTF-8
3,702
2.515625
3
[]
no_license
#include "SpriteComponent.h" #include <DxLib.h> #include "../_debug/_DebugConOut.h" #include "../Math/MathHelper.h" #include "../Systems/AnimationMng.h" #include "../GameObject/Entity.h" #include "TransformComponent.h" SpriteComponent::SpriteComponent(const std::shared_ptr<Entity>& owner): IComponent(owner), m_transform(owner->GetComponent<TransformComponent>()), m_currentDurationId(0), m_timer_ms(0), m_loopCount(0), m_updateFunc(&SpriteComponent::UpdateSleep) { } SpriteComponent::~SpriteComponent() { } bool SpriteComponent::PickAnimationList(const std::string& listKey) { auto& AnimMng = AnimationMng::Instance(); if (!AnimMng.HasAnimationList(listKey)) return false; m_listKey = listKey; return true; } bool SpriteComponent::Play(const std::string& state) { return Play(m_listKey, state); } bool SpriteComponent::Play(const std::string& listKey, const std::string& state) { auto& AnimMng = AnimationMng::Instance(); // Check function's arguments before assign to member variables if (!AnimMng.HasAnimation(listKey, state)) return false; if (IsPlaying(listKey, state)) return true; m_listKey = listKey; m_state = state; // auto& animation = AnimMng.GetAnimation(m_listKey, m_state); m_currentDurationId = animation.celBaseId; m_timer_ms = AnimMng.GetDuration_ms(m_currentDurationId); switch (animation.loop) { case -1: m_updateFunc = &SpriteComponent::UpdateInfinite; break; default: m_updateFunc = &SpriteComponent::UpdateLoop; m_loopCount = animation.loop; break; } return true; } bool SpriteComponent::IsPlaying(const std::string& listKey, const std::string& state) { return m_listKey == listKey && m_state == state; } void SpriteComponent::Init() { } void SpriteComponent::Update(float deltaTime_s) { (this->*m_updateFunc)(deltaTime_s); } void SpriteComponent::UpdateInfinite(float deltaTime_s) { if (m_timer_ms <= 0) { auto& animMng = AnimationMng::Instance(); const auto& animtion = animMng.GetAnimation(m_listKey, m_state); m_currentDurationId = (m_currentDurationId - animtion.celBaseId + 1) % animtion.celCount + animtion.celBaseId; m_timer_ms = animMng.GetDuration_ms(m_currentDurationId); } m_timer_ms -= static_cast<int>(deltaTime_s / MathHelper::kMsToSecond); } void SpriteComponent::UpdateLoop(float deltaTime_s) { auto& animMng = AnimationMng::Instance(); const auto& animation = animMng.GetAnimation(m_listKey, m_state);; if (m_timer_ms <= 0) { ++m_currentDurationId; m_timer_ms = animMng.GetDuration_ms(m_currentDurationId); } if (m_currentDurationId >= (animation.celBaseId + animation.celCount)) { --m_loopCount; m_currentDurationId = animation.celBaseId; m_timer_ms = animMng.GetDuration_ms(m_currentDurationId); } if (m_loopCount < 0) { // Last durationId of current animation m_currentDurationId = animation.celBaseId + animation.celCount - 1; m_updateFunc = &SpriteComponent::UpdateSleep; return; } m_timer_ms -= static_cast<int>(deltaTime_s / MathHelper::kMsToSecond); } void SpriteComponent::UpdateSleep(float deltaTime_s) { } void SpriteComponent::Render() { auto& animMng = AnimationMng::Instance(); const auto& transform = m_transform.lock(); const auto& animation = animMng.GetAnimation(m_listKey, m_state); auto sourceX = (m_currentDurationId % animation.texColumns) * animation.celWidth; auto sourceY = (m_currentDurationId / animation.texColumns) * animation.celHeight; // TODO: Implement pivot(rotation center) variable DxLib::DrawRectRotaGraphFast3F(transform->Pos.x, transform->Pos.y, sourceX, sourceY, animation.celWidth, animation.celHeight, 32.0f, 32.0f, transform->Scale.x, transform->Scale.y, transform->Rotation, animation.texId, 1); }
true
dbb1440abbb6bf7d8dc5e98e66747e50132d29d3
C++
Junotja/httpservertest
/httpservertest/httpservertest/Guard.h
UTF-8
1,998
3.15625
3
[]
no_license
#ifndef GUARD_H #define GUARD_H #include <windows.h> #include <memory> #include <vector> #include "config.h" namespace GUARD { //mutex class Lock { private: CRITICAL_SECTION _cs; public: Lock() { InitializeCriticalSection(&_cs); } ~Lock() { DeleteCriticalSection(&_cs); } void lock() { EnterCriticalSection(&_cs); } void unlock() { LeaveCriticalSection(&_cs); } }; //rw class RWLock { private: int _st; int _rlockcount; int _rwaitcount; int _wwaitcount; HANDLE _notifyevent; CRITICAL_SECTION _stLock; public: RWLock(void); ~RWLock(void); void rlock(); void wlock(); void unlock(); }; //lock pool template <typename lock_t> class LockPool:private NoCopyable { public: typedef std::vector<std::shared_ptr<lock_t>> lock_type; private: size_t _size; //lock_t** _locklist; lock_type _locklist; size_t _index; public: LockPool(); ~LockPool(); bool init(void); bool destroy(); std::shared_ptr<lock_t> alloc(); void recycle(std::shared_ptr<lock_t> lockptr); }; template <typename lock_t> LockPool<lock_t>::LockPool() :_locklist(nullptr), _size(0), _index(0) { } template <typename lock_t> LockPool<lock_t>::~LockPool() { } template <typename lock_t> bool LockPool<lock_t>::init() { SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); _size = sysinfo.dwNumberOfProcessors; //_locklist = std::make_shared<vector<lock_t>>(_size); if (_size <= 0) { return false; } for (lock_type::iterator pos = _locklist.begin(); pos != _size; ++pos) { *pos = std::make_shared<lock_t>(); } return true; } template <typename lock_t> bool LockPool<lock_t>::destroy() { _locklist = nullptr; _size = 0; _index = 0; } template <typename lock_t> std::shared_ptr<lock_t> LockPool<lock_t>::alloc() { return _locklist[(_index++) % _size]; } template <typename lock_t> void LockPool<lock_t>::recycle(std::shared_ptr<lock_t> lockptr) { } } #endif
true
dd54204c747130b9a53051a09b6af7d2d16ec6c0
C++
Abraham1314/My_code
/编程程序/C++/text/text2/text2.cpp
UTF-8
609
2.796875
3
[]
no_license
#include<iostream> #include<cstring> #define NCE 3 using namespace std ; void sorenameNo(string p[] , int n) ; int main(){ int i ; string name[]={"张三","李四","王麻子"}; string no[]={"1811010001","1811010002","1811010003"}; sorenameNo(name,NCE); for(i=0;i<NCE;i++) { cout << name[i] ; } sorenameNo(no,NCE); for(i=0;i<NCE;i++) { cout << no[i] ; } return 0 ; } void sorenameNo(string p[] , int n) { string q; int i,j ; for (j=0;j<n-1;j++) { for(i=0;i<n-j;i++) { } } }
true
30501a40dc40b8b284e30cf9e411ecc174d953ed
C++
gwkdgwkd/leetcode
/c_c++/array/differentialarray/面试题1610生存人数.cpp
UTF-8
2,043
3.625
4
[]
no_license
/* 给定N个人的出生年份和死亡年份,第i个人的出生年份为birth[i], 死亡年份为death[i],实现一个方法以计算生存人数最多的年份。 你可以假设所有人都出生于1900年至2000年(含1900和2000)之间。 如果一个人在某一年的任意时期处于生存状态,那么他应该被纳入那一年的统计中。 例如,生于1908年、死于1909年的人应当被列入1908年和1909年的计数。 如果有多个年份生存人数相同且均为最大值,输出其中最小的年份。 示例: 输入: birth = {1900, 1901, 1950} death = {1948, 1951, 2000} 输出: 1901 提示: 0 < birth.length == death.length <= 10000 birth[i] <= death[i] */ #define MMAX(a, b) ((a) > (b) ? (a) : (b)) #define MMIN(a, b) ((a) < (b) ? (a) : (b)) #define BASE_YEAR 1900 #define MAX_LEN 102 // 实际大小是101 int maxAliveYear(int* birth, int birthSize, int* death, int deathSize) { int* years = (int*)calloc(MAX_LEN, sizeof(int)); for (int i = 0; i < birthSize; i++) { years[birth[i] - BASE_YEAR]++; // 对于2000,实际不用减,但是数组长度多了1个,所以这里不用判断: years[death[i] - BASE_YEAR + 1]--; } int sum = 0; int max = 0; int max_year; for (int i = 0; i < MAX_LEN; i++) { sum += years[i]; if (sum > max) { max = sum; max_year = i + BASE_YEAR; } } return max_year; } class Solution { static const int kBaseYear = 1900; static const int kMaxYear = 2000; static const int kLen = 101; public: int maxAliveYear(vector<int>& birth, vector<int>& death) { vector<int> nums(kLen, 0); for (int i = 0; i < birth.size(); ++i) { nums[birth[i] - kBaseYear]++; if (death[i] < kMaxYear) { nums[death[i] - kBaseYear + 1]--; } } int m = nums[0]; int year = kBaseYear; for (int i = 1; i < kLen; ++i) { nums[i] += nums[i - 1]; if (nums[i] > m) { m = nums[i]; year = kBaseYear + i; } } return year; } };
true
8d0163aefe4f3337b850ae1777ddb43469b9bebf
C++
AnirudhaKulkarni-prog/MyPrograms
/BOLT_codechef.cpp
UTF-8
491
2.71875
3
[]
no_license
#include<iostream> using namespace std; double rnd(double x) { double val=long(x*100+0.5); return double(val/100); } int main() { // your code goes here ios_base::sync_with_stdio(false); cin.tie(NULL); long t; double a,b,c,v; cin>>t; while(t--) { cin>>a; cin>>b; cin>>c; cin>>v; double x=a*b*c*v; cout<<x; double y=rnd(100/x); cout<<y; if(y<9.58) cout<<"YES"; else cout<<"NO"; } return 0; }
true
88d92fc0a922f719ffe5e751cc0ce328816906ce
C++
NaTaes/Algorithm
/백준/Software_CodingTest/15685번 드래곤 커브.cpp
UTF-8
2,260
3.5
4
[]
no_license
#include<iostream> #include<vector> using namespace std; bool Map[101][101]; vector<pair<int, int>> vec; //선분의 (x,y)값을 저장하는 vector int dx[4] = {-1, 0, 1, 0}; //←, ↑, →, ↓방향일때 시계방향 90도 int dy[4] = {0, 1, 0, -1}; int x, y, d, g; void Dragon(int gen) { int index = vec.size() - 1; //현재 세대의 선분의 크기를 index값에 저장한다. int dir; for(int i=index; i>0; i--) //선분의 길이만큼만 실행한다.(끝점 부터 실행) { int ex = vec[i].first - vec[i-1].first; //점 과 점의 방향을 알기 위한 ex, ey int ey = vec[i].second - vec[i-1].second; //방향에 맞는 dir을 대입 if(ex == 0 && ey == 1) dir = 0; else if(ex == 1 && ey == 0) dir = 1; else if(ex == 0 && ey == -1) dir = 2; else dir = 3; //계속해서 선분은 추가 될 것이고, 그 추가된 위치를 기준으로 선을 이동시켜야한다. int mx = vec[vec.size() - 1].first; int my = vec[vec.size() - 1].second; vec.push_back(make_pair(mx+dx[dir], my+dy[dir])); //90도 회전된 (x,y)를 선분vector에 추가한다. Map[mx+dx[dir]][my+dy[dir]] = true; //Map에 체크해준다. } gen++; if(gen == g) //원하는 세대를 채웠다면 빠져 나온다. return; else Dragon(gen); //원하는 세대가 아니므로 드래곤 커브를 계속 한다. } int main(void) { int N, rec = 0; cin>> N; while(N--) { cin >> y >> x >> d >> g; vec.push_back(make_pair(x, y)); //시작 점을 선분에 넣어준다. Map[x][y] = true; //Map 체크 //d의 값에 맞춰 다음 점을 선분에 넣어준다. if(d % 2==0) { vec.push_back(make_pair(x+dx[d+1], y+dy[d+1])); Map[x+dx[d+1]][y+dy[d+1]] = true; } else { vec.push_back(make_pair(x+dx[d-1], y+dy[d-1])); Map[x+dx[d-1]][y+dy[d-1]] = true; } if(g!=0) //세대가 0이라면 드래곤 커브를 실행할 필요없다. Dragon(0); vec.clear(); //모든 드래곤 커브가 끝나면 선분vector를 clear해준다. } //1x1의 사각형을 찾아 rec을 증가시킨다. for(int i=0; i<100; i++) for(int j=0; j<100; j++) { if(Map[i][j] == false || Map[i][j+1] == false || Map[i+1][j] == false || Map[i+1][j+1] == false) continue; rec++; } cout << rec << endl; }
true
cac2bb2c3dcde8cef9edb9d2867a977265ab2895
C++
harjotscs/cpp-programmes
/exception at home.cpp
UTF-8
258
3.015625
3
[]
no_license
#include<iostream> using namespace std; int main() { int a,b; cout<<"Enter two Numbers\n"; cin>>a>>b; int x=a-b; try{ if(x!=0) { cout<<"Result(a/x)="<<a/x; } else { throw(x); } } catch(int j) { cout<<"Exception found "<<x; } }
true
814035563fb1d96763ffc5f1e7bc822235428d31
C++
Lundar/IIAG-Script
/Arbiter.cpp
UTF-8
5,595
2.78125
3
[]
no_license
#include "Arbiter.h" #include "Predef.h" #include <iostream> #include <fstream> #include <sstream> #include <cstdlib> Arbiter::Arbiter() { predef["]"]= new EndList(); predef["["]= new BList(); predef["print"]= new Print(); predef["func"]= new Func(); predef["class"]= new ClassKey(this); predef["return"]= new Return(); predef["done"]= new Done(); predef["if"]= new If(this); predef["ifell"]= new Ifell(this); predef["while"]= new While(this); predef["="]= new Assign(); predef[":"]= new Dereference(); predef["+"]= new Add(); predef["-"]= new Sub(); predef["*"]= new Mul(); predef["/"]= new Div(); predef["%"]= new Rem(); predef["break"]= new Break(); predef["continue"]= new Continue(); predef["true"]= new True(); predef["false"]= new False(); predef[">"]= new Greater(); predef["<"]= new Less(); predef[">="]= new EGreater(); predef["<="]= new ELess(); predef["=="]= new Equal(); predef["!="]= new NEqual(); } Arbiter::~Arbiter() { //dtor } void Arbiter::loadFile(string s) { ifstream in(s.c_str()); string code; char temp; bool quote=false; bool esc=false; if(in.good()) temp=in.get(); while(in.good()) { if(temp=='"'&& !esc) quote=!quote; if(temp =='\\') esc=true; else esc=false; if(temp=='['||temp==']'||temp=='{'||temp=='}') code = code+" "+temp+" "; else code = code+temp; temp=in.get(); } //cout<<code<<endl; list<Object*> newStack; executeString(code,newStack,global); } void Arbiter::main(){ if(global.find("main") != global.end()){ list<Object*> stack; executeFunction((Function*)((Name*)global["main"])->getObj(),stack); }else cerr<<"no main function found!"<<endl; } void Arbiter::executeFunction(Function* f, list<Object*> &stack) { //cout<<f->getCode()<<" | "<<f->getParam()->length()<<endl; map<string,Object*> context; List* param = f->getParam(); for(int x=0;x<param->length();x++){ if(param->at(x)->getType()!= NAME) continue; if(!stack.size()){ cerr<<"not enough args for function\n"<<f->getCode()<<endl; return; } context[((Name*)param->at(x))->getName()]=stack.back(); stack.pop_back(); } list<Object*> newStack; executeString(f->getCode(),newStack,context); if(context.find("return") != context.end()){ List *l = (List*)context["return"]; for(int x=0;x<l->length();x++){ stack.push_back(l->at(x)); l->at(x)->incCount(); } } for(map<string,Object*>::iterator it = context.begin(); it != context.end(); it++) (it)->second->decCount(); } ///TODO check for illegal names Object* Arbiter::str2Obj(string s, map<string,Object*> &context, bool globe, bool deref) { if(isdigit(s[0]) || s[0]=='.' || (s[0]=='-' && (isdigit(s[1]) || s[1]=='.'))){ if(s[s.length()-1]=='i') return new Int(atoi(s.substr(0,s.length()-1).c_str())); return new Float(atof(s.c_str())); } if(s[0]=='('){ deref=true; s=s.substr(1); } string sub=""; if(s.find(".") != string::npos){ sub= s.substr(s.find(".")+1); s=s.substr(0,s.find(".")); //cout<<s<<" "<<sub<<endl; } Object* ret=NULL;//&theNix; if(globe){ //check for predefs if(predef.find(s) != predef.end()) ret= predef[s]; //check global if(global.find(s) != global.end()){ global[s]->incCount(); ret= global[s]; } } //check local if(context.find(s) != context.end()){ context[s]->incCount(); ret= context[s]; } if(ret && ret->getType()==CLASS&& !sub.empty()){ ret = str2Obj(sub,((Class*)ret)->getContext(),false,deref); //cout<<sub<<"."<<" "<<ret->getType()<<endl; } if(!deref) if(ret && ret->getType()==NAME){ ((Name*)ret)->getObj()->incCount(); ret=((Name*)ret)->getObj(); } if(ret==NULL){ ret= new Name(s); context[s]=ret; } if(deref) if(ret->getType()!=NAME){ ret->incCount(); ret=new Name("",ret); } return ret; } void Arbiter::executeString(string s,list<Object*> &stack, map<string,Object*> &context) { //list<Object*> stack; stringstream code(s); string temp; while(code.good()) { if(context.find("done") != context.end()) break; code >> temp; if(temp[0]=='"') { string str; str+= temp; while(code.good()) { if(temp[temp.length()-1]=='"') break; code >> temp; str+= " "+temp; } str=str.substr(1,str.length()-2); while(str.find("\\n") != string::npos) str.replace(str.find("\\n"),2,"\n"); stack.push_back(new String(str)); continue; } if(temp[0]=='{') { int level=1; string str; while(code.good()) { code >> temp; if(temp[0]=='{') level++; if(temp[0]=='}') level--; if(level == 0) break; str+= " "+temp; } stack.push_back(new String(str)); continue; } Object *o = str2Obj(temp, context); if(o->getType()==FUNC){ executeFunction((Function*)o,stack); } else if(o->getType()==PREDEF_FUNC){ ((PredefFunc*)o)->execute(stack,context); } else { o->incCount(); stack.push_back(o); } } }
true
e5b043ffb32a909b1132661442e481cf4582f41f
C++
FrankieV/Fondamenti-di-Informatica
/ProvaIntermedia Es.2/main.cpp
WINDOWS-1252
1,062
3.578125
4
[]
no_license
/* Esercizio 2. Si scriva in C++ un programma che, letta da input una sequenza di naturali terminata dal tappo 0 0 (ZERO ZERO), ed evitando luso degli array, stampi su standard output la stringa TROVATO se nella sequenza presente almeno un elemento il cui valore pari alla posizione che occupa nella sequenza (si noti che il primo elemento occupa la posizione 1). ESEMPIO: Se la sequenza letta da input fosse 5 3 2 1 6 8 7 5 9 0 0 il programma dovrebbe stampare TROVATO poich lelemento 7 occupa la posizione 7. Si noti che anche lelemento 9 soddisfa la propriet ma il programma deve stampare la stringa TROVATO una sola volta.*/ #include <iostream> using namespace std; int main() { int prec; int corr; int pos = 0; bool trovato = false; cin >> prec; cin >> corr; while(prec != 0 || corr != 0 ) { pos++; if(pos == corr) { trovato = true; } prec = corr; cin >> corr; } if(trovato) { cout << "TROVATO"; } }
true
56d0b497bfc725d5d24a184f72c553e9fd25b050
C++
saibulusu/Data-Structures
/LinkedList/Test.cpp
UTF-8
4,299
3.75
4
[]
no_license
#include <stdio.h> #include <iostream> #include <exception> #include <gtest/gtest.h> #include <string> #include "LinkedList.cpp" /** Fixture class **/ class LinkedListTest : public ::testing::Test { protected: virtual void SetUp() { list = new LinkedList<int>; } virtual void TearDown() { delete list; } LinkedList<int>* list; }; /** Check the size of an empty list */ TEST_F(LinkedListTest, SizeNoElements) { try { int size = list->getSize(); ASSERT_EQ(size, 0); } catch (std::exception& e) { FAIL(); } } /** Check the size after inserting a few values */ TEST_F(LinkedListTest, InsertFewSize) { try { list->insert(0); list->insert(-1); list->insert(-100); list->insert(200); int size = list->getSize(); ASSERT_EQ(size, 4); } catch (std::exception& e) { FAIL(); } } /** Insert a few values and then check the value at the end */ TEST_F(LinkedListTest, InsertCheckValue) { try { list->insert(0); list->insert(-1); list->insert(10); list->insert(4); int val = list->get(3); ASSERT_EQ(val, 4); } catch (std::exception& e) { FAIL(); } } /** Get an element from an empty list */ TEST_F(LinkedListTest, GetEmpty) { try { int doesnotexist = list->get(0); FAIL(); } catch (std::exception& e) { ASSERT_STREQ(e.what(), "Getting out of bounds"); } } /** Alter an empty list */ TEST_F(LinkedListTest, AlterEmpty) { try { int doesnotexist = list->alter(2, 100); FAIL(); } catch (std::exception& e) { ASSERT_STREQ(e.what(), "Altering out of bounds"); } } /** Alter with a negative index */ TEST_F(LinkedListTest, AlterNegative) { try { int doesnotexist = list->alter(-2, 100); FAIL(); } catch (std::exception& e) { ASSERT_STREQ(e.what(), "Altering out of bounds"); } } /** Removing from an empty list */ TEST_F(LinkedListTest, RemoveEmpty) { try { int doesnotexist = list->remove(2); FAIL(); } catch (std::exception& e) { ASSERT_STREQ(e.what(), "Removing out of bounds"); } } /** Insert and remove in alternate fashion then check size */ TEST_F(LinkedListTest, InsertRemoveAlternateSize) { try { list->insert(0); int a = list->remove(0); list->insert(100); int b = list->remove(0); list->insert(99); int size = list->getSize(); ASSERT_EQ(size, 1); } catch (std::exception& e) { FAIL(); } } /** Insert and remove in alternate fashion then check any value */ TEST_F(LinkedListTest, InsertRemoveAlternateValue) { try { list->insert(-100); list->insert(3030); list->insert(-1000); int b = list->remove(0); int val = list->get(0); ASSERT_EQ(val, 3030); } catch (std::exception& e) { FAIL(); } } /** Insert at 0 to an empty list */ TEST_F(LinkedListTest, InsertAtZeroEmptySize) { try { list->insert(0, 100); int size = list->getSize(); ASSERT_EQ(size, 1); } catch (std::exception& e) { FAIL(); } } /** Insert a few values then check inserting at an index */ TEST_F(LinkedListTest, InsertFewInsertAtIndexValue) { try { list->insert(0, 100); list->insert(0, 200); list->insert(0, 300); int val = list->get(2); ASSERT_EQ(val, 100); } catch (std::exception& e) { FAIL(); } } /** Insert a few values then alter a value and check the return */ TEST_F(LinkedListTest, InsertFewAlterReturn) { try { list->insert(0); list->insert(0, 100); list->insert(2, 900); int val = list->alter(1, 200); ASSERT_EQ(val, 0); } catch (std::exception& e) { FAIL(); } } /** Insert a few values then alter a value and check the value */ TEST_F(LinkedListTest, InsertFewAlterValue) { try { list->insert(0); list->insert(0, 100); list->insert(2, 900); int ret = list->alter(1, 200); int val = list->get(1); ASSERT_EQ(val, 200); } catch (std::exception& e) { FAIL(); } } // Run the tests int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
5297ea88298cdc9746f3f75f1fe820940591b7f8
C++
lakshaywadhwacse/Leetcode-Solutions
/sriram_asteroidcollision.cpp
UTF-8
1,402
2.96875
3
[]
no_license
class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { stack<int>s; for(int i=0;i<asteroids.size();i++) { //collison condition if(!s.empty() and s.top()>0 and asteroids[i]<0) { bool flag=false; while(!s.empty() and s.top()>0 and asteroids[i]<0) { if(abs(asteroids[i])==abs(s.top())) { s.pop(); flag=false; break; } else if(abs(asteroids[i])>abs(s.top())) { s.pop(); flag=true; } else if(abs(asteroids[i])<abs(s.top())) { flag=false; break; } } if(flag) s.push(asteroids[i]); } else { // Not collide just need to insert the element in stack s.push(asteroids[i]); } } vector<int>ans; while(!s.empty()) { ans.push_back(s.top()); s.pop(); } reverse(ans.begin(),ans.end()); return ans; } };
true
8fc80822bc5e74829642fffd247f39c14ab33a8d
C++
Tanisha03-cyber/C_codes
/14_half pyramid using numbers.cpp
UTF-8
274
2.984375
3
[]
no_license
//half pyramid using numbers #include<iostream> using namespace std; int main() { int row,col,i,j; cout<<"enter number of row and columns"; cin>>row>>col; for(int i=1;i<=row;i++) { for(j=1;j<=i;j++) { cout<<i; } cout<<"\n"; } return 0; }
true
1012f3c91f74eb5c22a5d4f65832391376a42d41
C++
13besebali/APAssignment1
/CP_RefCount/Source.cpp
UTF-8
925
3.84375
4
[]
no_license
#include "StringBuffer.h" #include <cstdlib> #include <cstring> #include <iostream> using namespace std; int main(int argc, char** argv) { //create a smart string with const char* char* hello = "hello"; StringBuffer* object = new StringBuffer("Testing", 7); StringBuffer* object2 = new StringBuffer(); *object2 = *object; // Checking Append Fucntion object2->append('A'); // 1st character append to object 2 object2->append('B'); // 2nd character appedn to object 2 // Checking Length Function cout << "COW with Reference Counting "<< std::endl; cout << "Original Object Length =" << object->length() << std::endl; cout << "Copy Object Length =" << object2->length() << std::endl; std::cout << "new ss charAt 0 = " << object->charAt(0) << std::endl; std::cout<<"Printing Original: "<<std::endl; object->print(); std::cout<<endl; std::cout<<"Printing Copy: "<<std::endl; object2->print(); return 0; }
true
f475c280712a2bce842bd9b7d15a6068449bc5f7
C++
abhay123lp/online-image-clustering-project
/kmedroid/src/distance_matrix.cc
UTF-8
1,059
2.9375
3
[]
no_license
// HERC 2012 // zhangf@email.sc.edu #include <cassert> #include <utility> #include <iostream> #include "distance_matrix.h" namespace kmedroid { using std::make_pair; using std::cerr; using std::endl; float DistanceMatrix::Get(int x, int y) const { // Always set the point with smaller number in the front of the pair if (x == y) return 0.0; CoordinatePair xy; if (x > y) xy = make_pair(y, x); else xy = make_pair(x, y); unordered_map<CoordinatePair, float>::const_iterator it = find(xy); if (it == end()) { return MAX_DISTANCE; } else { return it->second; } } void DistanceMatrix::Set(int x, int y, float distance) { if (x ==y) return; CoordinatePair xy; if (x > y) xy = make_pair(y, x); else xy = make_pair(x, y); (*this)[xy] = distance; } void DistanceMatrix::Print() const { for (DistanceMatrix::const_iterator it = begin(); it != end(); ++it) { cerr << "(" << it->first.first << "," <<it->first.second << ") : " << it->second <<endl; } } } // namespace kmedroid
true
05fd21d8ad49d82e891c41f75a3203506792a2e9
C++
adam4321/CS-162_Programming_2
/Lab3- loaded dice game/LoadedDie.cpp
UTF-8
1,486
3.171875
3
[]
no_license
/********************************************************************* ** Program name: War Game ** Author: Adam Wright ** Date: 4/17/2019 ** Description: Derived class of Die that implements the Loaded Die *********************************************************************/ #include "LoadedDie.hpp" #include "Die.hpp" #include "Game.hpp" /********************************************************************* ** Description: Default constructor that initializes the loaded die ** using the base Die class *********************************************************************/ LoadedDie::LoadedDie() : Die() {} /********************************************************************* ** Description: Constructor function that initializes the die with ** using the base Die class and passes in the number of ** sides for the die as the argument *********************************************************************/ LoadedDie::LoadedDie(int sides) : Die(sides) {} /********************************************************************* ** Description: Function that implements the Loaded Die's rolling ** behavior. It will always roll higher than a random ** average *********************************************************************/ int LoadedDie::roll() { rollSide = rand() % numDieSides + 3; if (rollSide > numDieSides) { rollSide = numDieSides; } return rollSide; }
true
ef547d4f593803bd8beb6be63ce02cbc12a66ebc
C++
daniel-m-campos/grid-mapper
/test/test_grid_mapper.cpp
UTF-8
2,295
2.71875
3
[]
no_license
#include <cmath> #include <fstream> #include "grid_mapper.h" #include "grid_mapper_io.h" #include "gtest/gtest.h" using namespace grid_mapper; using namespace grid_mapper_io; class MapperFixture : public ::testing::Test { public: static constexpr double range_max = 5000, range_min = 170; static constexpr double cell_width = 100, cell_height = 100; static constexpr double map_width = 30000, map_height = 15000; static constexpr double robot_width = map_width / 5, robot_height = map_height / 3; void AssertEqual(const OccupancyGrid& actual, const OccupancyGrid& expected) { ASSERT_EQ(actual.size(), expected.size()); ASSERT_EQ(actual[0].size(), expected[0].size()); for (size_t i = 0; i < expected.size(); ++i) { for (size_t j = 0; j < expected[0].size(); ++j) { ASSERT_NEAR(actual[i][j], expected[i][j], 1e-6); } } } }; TEST_F(MapperFixture, DataTestWithConstantModel) { std::ifstream pose_stream{"../data/pose.txt"}; std::ifstream measurement_stream{"../data/measurement.txt"}; MapGrid map_grid{cell_width, cell_height, map_width, map_height}; Robot robot{robot_width, robot_height, {range_min, range_max}}; auto model = [](const Pose& pose, const Measurement& measurement, const Coordinate& coordinate, const SensorRange& sensor_range) -> double { return 0.4; }; while (pose_stream.good() && measurement_stream.good()) { robot.SetPose(ReadPose(pose_stream)); UpdateOccupancyGrid(map_grid, robot, ReadMeasurement(measurement_stream), model); } AssertEqual(map_grid.GetOccupancyGrid(), ReadGrid("../data/grid1.txt")); } TEST_F(MapperFixture, DataTestWithDefaultModel) { std::ifstream pose_stream{"../data/pose.txt"}; std::ifstream measurement_stream{"../data/measurement.txt"}; auto expected = ReadGrid("../data/grid2.txt"); MapGrid map_grid{cell_width, cell_height, map_width, map_height}; Robot robot{robot_width, robot_height, {range_min, range_max}}; while (pose_stream.good() && measurement_stream.good()) { robot.SetPose(ReadPose(pose_stream)); UpdateOccupancyGrid(map_grid, robot, ReadMeasurement(measurement_stream)); } AssertEqual(map_grid.GetOccupancyGrid(), ReadGrid("../data/grid2.txt")); }
true
199cea1dede7c1397430bbee780c14459e370ff2
C++
yongjianmu/leetcode
/TEMP/getCallID/sol2.cpp
UTF-8
3,621
2.78125
3
[]
no_license
#include "../../second/include/header.h" #include <pthread.h> #include <semaphore.h> #include <unistd.h> static int gCnt = 0; vector<int> get_ids() { vector<int> ret(10, 0); for(int i = 0; i < 10; ++i) { ret[i] = gCnt++; } usleep(3000); return ret; } class Solution { private: static pthread_mutex_t mMutex; static queue<int> mID1; static queue<int> mID2; static pthread_cond_t mGetIDCond; static pthread_cond_t mSwitchCond; static pthread_t mGetID_tid; static bool mGetIDCondFlag; static bool mSwitchCondFlag; static int lock() { return pthread_mutex_lock(&mMutex); } static int unlock() { return pthread_mutex_unlock(&mMutex); } static void cleanup_function(void* a) { cout << "clean up" << endl; } static void* get_idx(void* x) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); pthread_cleanup_push(cleanup_function, NULL); while(true) { pthread_testcancel(); lock(); if(!mGetIDCondFlag) pthread_cond_wait(&mGetIDCond, &mMutex); mSwitchCondFlag = false; unlock(); vector<int> vec = get_ids(); for(auto v : vec) mID2.push(v); lock(); mSwitchCondFlag = true; mGetIDCondFlag = false; unlock(); pthread_cond_signal(&mSwitchCond); } pthread_cleanup_pop(0); pthread_exit(NULL); } public: Solution() { pthread_mutex_init(&mMutex, NULL); pthread_cond_init(&mGetIDCond, NULL); pthread_cond_init(&mSwitchCond, NULL); vector<int> vec = get_ids(); for(auto v : vec) mID1.push(v); vec = get_ids(); for(auto v : vec) mID2.push(v); pthread_create(&mGetID_tid, NULL, get_idx, NULL); mGetIDCondFlag = false; mSwitchCondFlag = true; cout << "Construction" << endl; } ~Solution() { pthread_cancel(mGetID_tid); pthread_cond_broadcast(&mGetIDCond); pthread_join(mGetID_tid, NULL); pthread_cond_destroy(&mGetIDCond); pthread_cond_destroy(&mSwitchCond); pthread_mutex_destroy(&mMutex); } static int get_one_id() { int ret = 0; lock(); if(mID1.empty()) { if(!mSwitchCondFlag) pthread_cond_wait(&mSwitchCond, &mMutex); mID1.swap(mID2); mGetIDCondFlag = true; pthread_cond_signal(&mGetIDCond); } ret = mID1.front(); mID1.pop(); unlock(); return ret; } }; static void* printID(void* obj) { Solution* sol = (Solution*) obj; for(int i = 0; i < 20; ++i) { usleep(1000); cout << sol->get_one_id() << endl; } cout << "Leave user" << endl; return NULL; } pthread_mutex_t Solution::mMutex; queue<int> Solution::mID1; queue<int> Solution::mID2; pthread_cond_t Solution::mGetIDCond; pthread_cond_t Solution::mSwitchCond; pthread_t Solution::mGetID_tid; bool Solution::mGetIDCondFlag; bool Solution::mSwitchCondFlag; int main() { Solution sol; pthread_t tid1, tid2, tid3; pthread_create(&tid1, NULL, printID, (void*) &sol); pthread_create(&tid2, NULL, printID, (void*) &sol); pthread_create(&tid3, NULL, printID, (void*) &sol); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_join(tid3, NULL); cout << "Main func join finished" << endl; return 0; }
true
dacec1b39d35c4b9d2e4ace82acc9a46bf5b003a
C++
cocealx/Code_cpp
/容器适配器实现栈和队列/容器适配器实现栈和队列/Seqlist.h
GB18030
1,552
3.578125
4
[]
no_license
#pragma #include<iostream> #include<assert.h> using namespace std; template<class T> struct ListNode { ListNode(const T x = 0) :data (x), next( NULL), prev ( NULL){} T data; ListNode<T>*next; ListNode<T>*prev; }; template<class T> class Seqlist { public: typedef ListNode<T> Node; Seqlist(); ~Seqlist(); void PushBack(const T&x); void PopBack(); void Print(); bool Empty(); const T&Top(); size_t Size(); private: Node* _head; Node* _tail; }; //ĬϹ캯 template< class T> Seqlist<T>::Seqlist() :_head( NULL), _tail(NULL){} // template<class T> Seqlist<T>::~Seqlist() { Node*temp = _head; while (temp != NULL) { Node*next = temp->next; delete temp; temp = next; } _head = _tail = NULL; } //β template<class T> void Seqlist<T>::PushBack(const T&x) { if (_head == NULL) { _head = _tail = new Node(x); return; } else { Node*temp = new Node(x); _tail->next = temp; temp->prev = _tail; _tail = temp; } } template<class T> void Seqlist<T>::Print() { Node*cur = _head; while (cur) { cout << cur->data << " "; cur = cur->next; } cout << endl; } template<class T> void Seqlist<T>::PopBack() { Node*temp = _tail; _tail = _tail->prev; _tail->next = NULL; delete temp; } template<class T> bool Seqlist<T>::Empty() { return _head == NULL; } template<class T> const T& Seqlist<T>::Top() { assert(_tail); return _tail->data; } template<class T> size_t Seqlist<T>::Size() { Node*cur = _head; size_t count = 0; while (cur) { count++; cur = cur->next; } return count; }
true
b306eaf97a7d8fee1e50190243d6092881d8356d
C++
luningcowboy/DesignPatternTest
/DesignPattern/Composite.cpp
UTF-8
598
2.828125
3
[]
no_license
#include "Com.h" #include "Composite.h" Composite::Composite() {} Composite::~Composite() {} void Composite::Operation() { vector<Com*>::iterator comIter = comVec.begin(); for (; comIter != comVec.end();comIter++) { (*comIter)->Operation(); } } void Composite::Add(Com * com) { comVec.push_back(com); } void Composite::Remove(Com * com) { //comVec.erase(comVec.begin()); vector<Com*>::iterator ite = comVec.begin(); for (; ite != comVec.end(); ite++) { if ((*ite) == com) { comVec.erase(ite); break; } } } Com * Composite::GetChild(int index) { return comVec[index]; }
true
7f491b32183db05d25ef752b4282412370de8afb
C++
Dugy/memory_mapped_file
/memory_mapped_file_base.cpp
UTF-8
1,275
2.84375
3
[ "MIT" ]
permissive
#include "memory_mapped_file_base.hpp" MemoryMappedFileBase::MemoryMappedFileBase(const std::string &fileName) : modified_(false), fileName_(fileName), loadedUntil_(0), fileSize_(-1) { } MemoryMappedFileBase::~MemoryMappedFileBase() { } const std::string &MemoryMappedFileBase::fileName() const { return fileName_; } const std::string MemoryMappedFileBase::extendedFileName(const std::string &from) const { return from + fileNameExtension(); } void MemoryMappedFileBase::append(const std::vector<std::uint8_t> &added) { load(); modified_ = true; data_.insert(data_.end(), added.begin(), added.end()); } void MemoryMappedFileBase::append(const std::uint8_t* added, int size) { load(); modified_ = true; for (int i = 0; i < size; i++) data_.push_back(added[i]); } void MemoryMappedFileBase::push_back(uint8_t added) { load(); modified_ = true; data_.push_back(added); } void MemoryMappedFileBase::clear() { if (!data_.empty() || !fullyLoaded()) { modified_ = true; data_.clear(); loadedUntil_ = 0; fileSize_ = 0; } } const std::vector<std::uint8_t> &MemoryMappedFileBase::data() const { load(); return data_; } void MemoryMappedFileBase::swapContents(std::vector<std::uint8_t> &other) { load(); modified_ = true; swap(data_, other); }
true
36461e7a60eca556941d40ea311db4367e776d6a
C++
dianestar/CSP
/hw8-1/number.cc
UTF-8
274
2.609375
3
[]
no_license
#include "number.h" void Number::setNumber(int num){ _num=num; } int Number::getNumber(){ return _num; } int Square::getSquare(){ int square_num=_num*_num; return square_num; } int Cube::getCube(){ int cube_num=_num*_num*_num; return cube_num; }
true
71890cf15f35d156c9e0dd2679907a61538d3433
C++
wuQAQ/Algorithms
/NowCoder_2017/P01_TheChoir_DP/main.cpp
UTF-8
1,013
2.8125
3
[]
no_license
#include <cstring> #include <iostream> #include <algorithm> using namespace std; #define MAXN 50 const long long minn = -1e17; struct DP { long long mins; long long maxs; }dp[MAXN][10]; void GetMaxValue(int a[], int n, int k, int d); int main() { int n; int a[MAXN]; int k, d; cin >> n; for (int i = 0; i < n; ++i) { cin >> a[i]; } cin >> k >> d; GetMaxValue(a, n, k, d); return 0; } void GetMaxValue(int a[], int n, int k, int d) { long long res = minn; memset(dp, 0, sizeof(dp)); for (int i = 0; i < n; ++i) dp[i][0].mins = dp[i][0].maxs = a[i]; for (int i = 0; i < n; ++i) { for (int ki = 1; ki < k; ++ki) { int j = i - d; if (j < 0) j = 0; for (; j < i; ++j) { dp[i][ki].mins = min(dp[i][ki].mins, min(dp[j][ki - 1].mins * a[i], dp[j][ki - 1].maxs * a[i])); dp[i][ki].maxs = max(dp[i][ki].maxs, max(dp[j][ki - 1].mins * a[i], dp[j][ki - 1].maxs * a[i])); } } } for (int i = 0; i < n; ++i) { res = max(res, dp[i][k-1].maxs); } cout << res; }
true
1bfebbf4b382bdfc97d0386777035b652b374de1
C++
ssnyder2525/Educational
/C/CS 235 Lab 6/Lab6/Tree.h
UTF-8
12,723
3.453125
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <queue> using namespace std; template <typename ItemType> class Tree { private: struct Node { //struct simply makes everything public. ItemType item; Node* left = NULL; Node* right = NULL; Node* parent = NULL; int height = 0; }; public: Node* root = NULL; int size = 0; void clear() { while (size != 0) { remove(root->item); } }; void updateheight(Node* n) { int l = getheight(n->left); int r = getheight(n->right); if (l >= r) { n->height = l + 1; } else { n->height = r + 1; } } //---------------------------------------------------------------------------------------------------------------------------------------- string haschildren(Node* n) { if (n == NULL) { return "0"; } else if ((n->left != NULL) && (n->right == NULL)) return "left"; else if ((n->left != NULL) && (n->right != NULL)) return "both"; else if ((n->left == NULL) && (n->right != NULL)) return "right"; else return "childless"; } //---------------------------------------------------------------------------------------------------------------------------------------- void setH2(Node* n) { string t = haschildren(root); if (t == "both") { if (root->left->height > root->right->height)// set the roots height root->height = root->left->height + 1; else root->height = root->right->height + 1; } else if (t == "right") root->height = root->right->height + 1; else if (t == "left") root->height = root->left->height + 1; } //---------------------------------------------------------------------------------------------------------------------------------------- void setH(Node* n) { if (n != NULL) { updateheight(n); while (n != root) { n = n->parent; updateheight(n); } } }; //---------------------------------------------------------------------------------------------------------------------------------------- /*int setbalancedheight(Node* n) { int nsheight = 0; int nsheight2 = 0; string t = haschildren(n); if (t == "both") { nsheight = setbalancedheight(n->left); nsheight2 = setbalancedheight(n->right); if (nsheight > nsheight2) n->height = ++nsheight; else n->height = ++nsheight2; return n->height; } else if (t == "left") { nsheight = setbalancedheight(n->left); n->height = ++nsheight; return nsheight; } else if (t == "right") { nsheight = setbalancedheight(n->right); n->height = ++nsheight; return nsheight; } else if (t == "childless") { n->height = 1; return 1; } }*/ //---------------------------------------------------------------------------------------------------------------------------------------- Node* insert(Node* n, ItemType&item) { if (item < n->item) { Node* newnode = new Node; n->left = newnode; // set new node as a child newnode->item = item; newnode->parent = n; //set new node's parent size++; return newnode; } else if (item > n->item) { Node* newnode = new Node; n->right = newnode; // set new node as a child newnode->item = item; newnode->parent = n; //set new node's parent size++; return newnode; } else { return NULL; } }; //---------------------------------------------------------------------------------------------------------------------------------------- void add(ItemType& item) { Node* newitem = add(root, root, item); if (newitem != NULL) { setH(newitem); while (newitem != root) { newitem = newitem->parent; Balance(newitem); } } } //---------------------------------------------------------------------------------------------------------------------------------------- Node* add(Node* n, Node* prevnode, ItemType& item) { Node* newitem=NULL; if (root == NULL) { newitem = new Node; root = newitem; newitem->item = item; newitem->height = 0; size++; return newitem; } else if (n == NULL) { newitem = insert(prevnode, item); return newitem; } else { if (item < n->item) { prevnode = n; newitem = add(n->left, prevnode, item); return newitem; } else if (item > n->item) { prevnode = n; newitem = add(n->right, prevnode, item); return newitem; } return newitem; } return newitem; }; //---------------------------------------------------------------------------------------------------------------------------------------- Node* findleftmost(Node* n) { while (n->left != NULL) { n = n->left; } return n; }; //---------------------------------------------------------------------------------------------------------------------------------------- void finalbalance(Node* p2) { if (p2 != NULL) { Balance(p2); while (p2 != root) { p2 = p2->parent; Balance(p2); } } else if (root != NULL) Balance(root); } //---------------------------------------------------------------------------------------------------------------------------------------- string remove(const ItemType& item) { string item2 = item; Node* n = root; if (n != NULL) { while (n->item != item) { if ((item < n->item) && (n->left != NULL)) n = n->left; else if ((item > n->item) && (n->right != NULL)) n = n->right; else return "-1"; } if (n->item == item) rembal(n, item); } return item2; }; //---------------------------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------------------------- void rembal(Node* n, string item) { Node* a = NULL;// only initialized for the sake of initializing. Will not be n for long. Node* p2 = NULL; string t = haschildren(n); if (n->right != NULL) a = findleftmost(n->right); else a = n->left; if ((size != 1) && (a != NULL)) { if (a->parent != n) p2 = a->parent; else p2 = a; } else p2 = n->parent; if (n == root) { root = a; } simp1(n, a, t, item); simp2(n, a, item, t); if (p2 == n) p2 = NULL; updatetheheights(a, p2); delete n; size--; finalbalance(p2); }; void simp2(Node* n, Node* a, string item, string t) { if (a == NULL) { if (n == root) root = NULL; } else { a->parent = n->parent; if ((n->parent != NULL) && (t != "childless")) { if (n->parent->item > item) n->parent->left = a; if (n->parent->item < item) n->parent->right = a; } } } //---------------------------------------------------------------------------------------------------------------------------------------- void updatetheheights(Node* a, Node* p2) { if (a != NULL) { updateheight(a); } if (p2 != NULL) { updateheight(p2); if (a!=NULL) { updateheight(a); if (a->height < p2 -> height) { while (a -> height) { a = a->parent; updateheight(a); } } else { while (p2 != root) { p2 = p2->parent; updateheight(p2); } } } else { while (p2 != root) { p2 = p2->parent; updateheight(p2); } } } } //---------------------------------------------------------------------------------------------------------------------------------------- bool find(Node* n, const ItemType& item) { if (n != NULL) { string t = haschildren(n); if (n->item == item) { return true; } else if ((n->left != NULL) && (item < n->item)) { return find(n->left, item); } else if ((n->right != NULL) && (item > n->item)) return find(n->right, item); else { return false; } } return false; }; void simp1(Node* n, Node* a, string t, string item) { if ((t == "both") || (t == "right")) { a->left = n->left; if (n->left != NULL) { n->left->parent = a; } if (n->right != a) { if (a->right == NULL) //new { a->parent->left = NULL; } else { a->parent->left = a->right; a->right->parent = a->parent; } a->right = n->right; n->right->parent = a; } } else { childless(n, a, item, t); } } //---------------------------------------------------------------------------------------------------------------------------------------- void childless(Node* n, Node* a, string item, string t) { if ((t == "childless") && (a != root)) { if (n->parent->item > item) n->parent->left = NULL; if (n->parent->item < item) n->parent->right = NULL; } } //---------------------------------------------------------------------------------------------------------------------------------------- int getheight(Node* n) { if (n == NULL) return 0; else return (n->height); }; //---------------------------------------------------------------------------------------------------------------------------------------- void Balance(Node* n) { int n1 = getheight(n->left); int n2 = getheight(n->right); if ((n1 - n2) > 1) balancetoright(n); else if ((n2 - n1) > 1) { balancetoleft(n); } }; //---------------------------------------------------------------------------------------------------------------------------------------- void balancetoright(Node* n)//is it a single or double rotate? { if ((getheight(n->left->right)) > (getheight(n->left->left)))//crooked greater than straight? { n->left = rotateleft(n->left); //Dbl rotate R; } rotateright(n); }; //---------------------------------------------------------------------------------------------------------------------------------------- void balancetoleft(Node* n)//is it a single or double rotate? { if ((getheight(n->right->left)) > (getheight(n->right->right)))//crooked greater than straight? { n->right = rotateright(n->right); //Dbl rotate R; } rotateleft(n); }; //---------------------------------------------------------------------------------------------------------------------------------------- Node* rotateright(Node*n) { Node* prev = n->parent; Node* t = n->left; if (n == root) { root = t; root->parent = NULL; } n->left = t->right; if (t->right != NULL) t->right->parent = n;//setting infinite loop used to be n->left instead of n t->right = n; n->parent = t; if (prev != NULL)//added if (t->item > prev->item) { prev->right = t; t->parent = prev; } else if (t->item < prev->item) { prev->left = t; t->parent = prev; } updateheight(n); while (n != root) { n = n->parent; updateheight(n); } return t; }; //---------------------------------------------------------------------------------------------------------------------------------------- Node* rotateleft(Node*n) { Node* prev = n->parent; Node* t = n->right; if (n == root) { root = t; root->parent = NULL; } n->right = t->left; if (t->left != NULL) t->left->parent = n;//used to be n->right.... caused infinite loop. t->left = n; n->parent = t; if (prev != NULL) if (t->item > prev->item) { prev->right = t; t->parent = prev; } else if (t->item < prev->item) { prev->left = t; t->parent = prev; } updateheight(n); while (n != root) { n = n->parent; updateheight(n); } return t; }; //---------------------------------------------------------------------------------------------------------------------------------------- void Print(ostream& out) { if (root != NULL) { queue <Node*> levels; levels.push(root); int level = 0; int levelsize = 1; int nextlevelsize = 1; int added = 0; while (nextlevelsize > 0) { Node* temp = levels.front(); out << "level " << level << ": "; levelsize = nextlevelsize; nextlevelsize = 0; added = 0; while (levelsize > 0)//should keep levels separate from each other { temp = levels.front(); out << temp->item << "(" << temp->height << ") "; added++; if ((added % 8 == 0) && (levelsize > 1)) { out << endl; out << "level " << level << ": "; } if (temp->left != NULL) { levels.push(temp->left); nextlevelsize++; } if (temp->right != NULL) { levels.push(temp->right); nextlevelsize++; } levels.pop(); levelsize--; } out << endl; level++; } } }; ~Tree() { } };
true
447ba70338a64373952055ec324169217396b226
C++
huangshen/Leet
/src/SumOfTwoIntegers.cpp
UTF-8
306
2.921875
3
[]
no_license
#include "SumOfTwoIntegers.h" Solution::Solution() { } Solution::~Solution() { } int Solution::getSum(int a, int b) { //return a+b; int tmp_or, tmp_and; do { tmp_or = a ^ b; tmp_and = a & b; a = tmp_or; b = tmp_and << 1; } while(tmp_and); return tmp_or; }
true
726e0be2a86c8ec0f4b9f222eae71cba1e3e0888
C++
ybouret/yocto4
/src/mk/yocto/math/stat/recursive-sum.hpp
UTF-8
2,293
2.625
3
[]
no_license
#ifndef YOCTO_RECURSIVE_SUM_INCLUDED #define YOCTO_RECURSIVE_SUM_INCLUDED 1 #include "yocto/sequence/vector.hpp" #include "yocto/sequence/list.hpp" #include "yocto/math/math.hpp" namespace yocto { namespace math { namespace kernel { //! recursive sum subroutine /** T must accept T temp=0;' and 'T temp[NVAR];' and '+=' */ template < typename T, //!< sumable type, must accept 'T temp=0;' and 'T temp[NVAR];' size_t NVAR, //!< #parallel ops typename ITERATOR, //!< range type typename FUNCTION //!< array of callable type > inline void recursive_sum( typename type_traits<T>::mutable_type sum[NVAR], //!< current sums ITERATOR i, //!< current iterator const size_t n, //!< range size FUNCTION pfn //!< callable entities ) { assert( sum ); #if !defined(NDEBUG) for( size_t j=0;j<NVAR;++j) assert( pfn[j] != NULL ); #endif switch( n ) { case 0: { for( size_t j=0;j<NVAR;++j) sum[j] = 0; } return; case 1: { const typename type_traits<T>::mutable_type &v = *i; for( size_t j=0;j<NVAR;++j) sum[j] = pfn[j]( v ); } return; default: { const size_t half = n >> 1; //< bitwise half typename type_traits<T>::mutable_type rsum[NVAR]; //< temporary right sum recursive_sum<T,NVAR,ITERATOR,FUNCTION>( sum, i, half, pfn ); //< left sum recursive_sum<T,NVAR,ITERATOR,FUNCTION>( rsum, i+half, n-half, pfn ); //< right sum for( size_t j=0;j<NVAR;++j ) sum[j] += rsum[j]; } break; } } template < typename SEQ, size_t NVAR, typename FUNCTION > inline void recursive_sum(const SEQ & seq, typename SEQ::mutable_T sum[NVAR], FUNCTION pfn ) { recursive_sum< typename SEQ::mutable_type, NVAR, typename SEQ::const_iterator, FUNCTION>( sum, seq.begin(), seq.size(), pfn ); } } // kernel } // math } #endif
true
53873af3e77dd0d26a18c247a1fb50dec8f4fefc
C++
solanik/testowe
/heapsort.h
UTF-8
458
2.671875
3
[]
no_license
// // Created by filwo on 03.10.2018. // #pragma once #include "SortingFactory.h" class HeapSort : public RegisteredInFactory<HeapSort> { public: static std::string getAlgorithmName(); static void sort(std::vector<unsigned>& values); private: HeapSort() { (void)RegisteredInFactory<HeapSort>::registered; } static void heapify(std::vector<unsigned>::iterator begin, std::vector<unsigned>::iterator end, unsigned index); };
true
cd9caca262144786b684829b183f72a69052837f
C++
edonyzpc/PLC
/pat/pairprime.cc
UTF-8
1,970
2.703125
3
[]
no_license
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------. \ .'_ (`-')----. ,--./ ,--/ ,--.' ,-. # // / / / `\/ '-- | .---' '`'-..__)( OO).-. ' | \ | | (`-')'.' / # // //..\\ (| '--. | | ' |( _) | | | | . '| |)(OO \ / # ============UU====UU==== | .--' | | / : \| |)| | | |\ | | / /) # '//||\\` | `---. | '-' / ' '-' ' | | \ | `-/ /` # ''`` `------' `------' `-----' `--' `--' `--' # ###################################################################################### # # Author: edony - edonyzpc@gmail.com # # twitter : @edonyzpc # # Last modified: 2015-06-23 16:50 # # Filename: pairprime.cc # # Description: All Rights Are Reserved ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #include <iostream> #include <vector> #include <cmath> using std::cout; using std::cin; using std::endl; using std::vector; bool IsPrime(int num) { for (int i=2; i <= int(sqrt(num)); ++i) { if (num % i == 0) return 0; } return 1; } vector<int> PrimeList(int n) { vector<int> pri_lis; for (int i=2; i <= n; ++i) { if (IsPrime(i)) pri_lis.push_back(i); } return pri_lis; } int PairPrime(int pri1, int pri2) { if ((pri2 - pri1) == 2) { return 1; } else { return 0; } } int main() { int n; cin >> n; vector<int> pri_list; pri_list = PrimeList(n); int counter = 0; for (size_t i=pri_list.size(); i > 1; --i) { counter += PairPrime(pri_list[i-1], pri_list[i]); } cout << counter << endl; }
true
12b862c2e9134f3860ceb66c9c5d8fc0a701a396
C++
Dakshi1/dp-problems
/Dynamic Programming/max_path/main.cpp
UTF-8
1,096
2.96875
3
[]
no_license
// You can do it bro #include<bits/stdc++.h> using namespace std; int max(int x, int y, int z) { return max(max(x, y), z); } int max_cost(int n, int cost[][20]) { int helper[n+1][n+2]; for(int i=0;i<n+1;i++) { helper[i][n+1]=0; } for(int i=0;i<=n;i++) { for(int j=0;j<=n;j++) { if(i==0 || j==0) { helper[i][j]=0; } else { helper[i][j]=cost[i-1][j-1]+max(helper[i-1][j-1], helper[i-1][j], helper[i-1][j+1]); } } } int max=0; for(int i=0;i<n+2;i++) { if(helper[n][i]>max) max=helper[n][i]; } return max; } int main() { //code int t; cin >> t; while(t>0) { int n; cin >> n; int cost[n][20]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin >> cost[i][j]; } } cout << max_cost(n, cost) << endl; t--; } return 0; }
true
dcf23cbcafd2a27d2755d8e1db9b3b1cca3d956b
C++
DrKend/Week-1-Introduction
/Program21_SmallestElement/Program21_SmallestElement/Program21_SmallestElement.cpp
UTF-8
615
3.90625
4
[]
no_license
#include <iostream> using namespace std; int main() { int numberList[10]; int numberChoice; for (int i = 0; i < 10; i++) { cout << "Enter a number" << endl; cin >> numberChoice; numberList[i] = numberChoice; } int min = numberList[0]; int post = 1; for (int i = 0; i < 10; i++) { if (min > numberList[i]) { min = numberList[i]; post = i + 1; } } cout << "The smallest value you have inputted is: " << min << endl; cout << "The position of that number is: " << post << endl; return 0; }
true
67adceee4200bff6f6bd7974266ab9e25650c450
C++
AlbertMakesGames/UPC_SCHOOL_TEST
/zork-master/world.cpp
UTF-8
5,513
3.078125
3
[]
no_license
#include <iostream> #include "globals.h" #include "entity.h" #include "creature.h" #include "item.h" #include "exit.h" #include "room.h" #include "player.h" #include "world.h" // ---------------------------------------------------- World::World() { tick_timer = clock(); // Rooms ---- Room* forest = new Room("Forest", "You are surrounded by tall trees. It feels like a huge forest someone could get lost easily."); Room* house = new Room("House", "You are inside a beautiful but small white house."); Room* basement = new Room("Basement", "The basement features old furniture and dim light."); Exit* ex1 = new Exit("west", "east", "Little path", house, forest); Exit* ex2 = new Exit("down", "up", "Stairs", house, basement); ex2->locked = true; entities.push_back(forest); entities.push_back(house); entities.push_back(basement); entities.push_back(ex1); entities.push_back(ex2); // Creatures ---- Creature* butler = new Creature("Butler", "It's James, the house Butler.", house); butler->hit_points = 10; entities.push_back(butler); // Items ----- Item* mailbox = new Item("Mailbox", "Looks like it might contain something.", house); Item* key = new Item("Key", "Old iron key.", mailbox); ex2->key = key; Item* sword = new Item("Sword", "A simple old and rusty sword.", forest, WEAPON); sword->min_value = 2; sword->max_value = 6; Item* sword2(sword); sword2->parent = butler; Item* shield = new Item("Shield", "An old wooden shield.", butler, ARMOUR); shield->min_value = 1; shield->max_value = 3; butler->AutoEquip(); entities.push_back(mailbox); entities.push_back(sword); entities.push_back(shield); // Player ---- player = new Player("Hero", "You are an awesome adventurer!", forest); player->hit_points = 25; entities.push_back(player); } // ---------------------------------------------------- World::~World() { for(list<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it) delete *it; entities.clear(); } // ---------------------------------------------------- bool World::Tick(vector<string>& args) { bool ret = true; if(args.size() > 0 && args[0].length() > 0) ret = ParseCommand(args); GameLoop(); return ret; } // ---------------------------------------------------- void World::GameLoop() { clock_t now = clock(); if((now - tick_timer) / CLOCKS_PER_SEC > TICK_FREQUENCY) { for(list<Entity*>::iterator it = entities.begin(); it != entities.end(); ++it) (*it)->Tick(); tick_timer = now; } } // ---------------------------------------------------- bool World::ParseCommand(vector<string>& args) { bool ret = true; switch(args.size()) { case 1: // commands with no arguments ------------------------------ { if(Same(args[0], "look") || Same(args[0], "l")) { player->Look(args); } else if(Same(args[0], "north") || Same(args[0], "n")) { (args.size() == 1) ? args.push_back("north") : args[1] = "north"; player->Go(args); } else if(Same(args[0], "south") || Same(args[0], "s")) { (args.size() == 1) ? args.push_back("south") : args[1] = "south"; player->Go(args); } else if(Same(args[0], "east") || Same(args[0], "e")) { (args.size() == 1) ? args.push_back("east") : args[1] = "east"; player->Go(args); } else if(Same(args[0], "west") || Same(args[0], "w")) { (args.size() == 1) ? args.push_back("west") : args[1] = "west"; player->Go(args); } else if(Same(args[0], "up") || Same(args[0], "u")) { (args.size() == 1) ? args.push_back("up") : args[1] = "up"; player->Go(args); } else if(Same(args[0], "down") || Same(args[0], "d")) { (args.size() == 1) ? args.push_back("down") : args[1] = "down"; player->Go(args); } else if(Same(args[0], "stats") || Same(args[0], "st")) { player->Stats(); } else if(Same(args[0], "inventory") || Same(args[0], "i")) { player->Inventory(); } else ret = false; break; } case 2: // commands with one argument ------------------------------ { if(Same(args[0], "look") || Same(args[0], "l")) { player->Look(args); } else if(Same(args[0], "go")) { player->Go(args); } else if(Same(args[0], "take") || Same(args[0], "pick")) { player->Take(args); } else if(Same(args[0], "drop") || Same(args[0], "put")) { player->Drop(args); } else if(Same(args[0], "equip") || Same(args[0], "eq")) { player->Equip(args); } else if(Same(args[0], "unequip") || Same(args[0], "uneq")) { player->UnEquip(args); } else if(Same(args[0], "examine") || Same(args[0], "ex")) { player->Examine(args); } else if(Same(args[0], "attack") || Same(args[0], "at")) { player->Attack(args); } else if(Same(args[0], "loot") || Same(args[0], "lt")) { player->Loot(args); } else ret = false; break; } case 3: // commands with two arguments ------------------------------ { break; } case 4: // commands with three arguments ------------------------------ { if(Same(args[0], "unlock") || Same(args[0], "unlk")) { player->UnLock(args); } else if(Same(args[0], "lock") || Same(args[0], "lk")) { player->Lock(args); } else if(Same(args[0], "take") || Same(args[0], "pick")) { player->Take(args); } else if(Same(args[0], "drop") || Same(args[0], "put")) { player->Drop(args); } else ret = false; break; } default: ret = false; } return ret; }
true
659bf0dd48f825591f4baf4bb9fc39bdd6b083a2
C++
signhuwei/node-jvt
/includes/win/ia32/API/GESS/PeerSDK_IPAddress.h
UTF-8
1,464
2.5625
3
[ "Apache-2.0" ]
permissive
#pragma once #ifndef PEERSDK_PROTECT #pragma message("please include PeerSDK.h instead of me") #endif /** * @brief Provides an Internet Protocol (IP) address. */ class PEERSDK_API IPAddress { PEERSDK_DECLARE_IMPL() public: /** @name Constructors */ //@{ /** * @private */ IPAddress(); /** * @private */ IPAddress(_R* ipv4, _R* ipv6); /** * @private */ IPAddress(IPAddress const& value); /** * @private */ ~IPAddress(); //@} public: /** @name Methods */ //@{ /** * Gets the address family of the IP address. */ String ToString() const; //@} public: /** @name Static Methods */ //@{ /** * Gets the address family of the IP address. */ static IPAddress Parse(String const& s); //@} public: /** @name Static Fields */ //@{ /** * Gets the address family of the IP address. */ static IPAddress Any(); //@} public: /** @name Properties */ //@{ /** * Gets the address family of the IP address. */ AddressFamily Family() const; /** * Get the IPAddress as an array of bytes. */ Memory AddressBytes() const; //@} public: /** @name Operators */ //@{ /** * Replaces the elements of the <b>DateTime</b> with a copy of another <b>DateTime</b>. */ IPAddress& operator=(IPAddress const& value); //@} };
true
8c0566056fd118dfdc0dbf6da912a251bd4cbc51
C++
Garanyan/made
/advanced-algorithms/HW8/HW8_task_A.cpp
UTF-8
6,379
3.203125
3
[]
no_license
// // A. Просто поток // ограничение по времени на тест 5 секунд // ограничение по памяти на тест 1024 мегабайта // ввод стандартный ввод // вывод стандартный вывод // // Дана система из узлов и труб, по которым может течь вода. // Для каждой трубы известна наибольшая скорость, с которой вода может протекать через нее. // Известно, что вода течет по трубам таким образом, что за единицу времени в каждый узел // (за исключением двух — источника и стока) втекает ровно столько воды, сколько из него вытекает. // // Ваша задача — найти наибольшее количество воды, которое за единицу времени может протекать // между источником и стоком, а также скорость течения воды по каждой из труб. // // Трубы являются двусторонними, то есть вода в них может течь в любом направлении. // Между любой парой узлов может быть более одной трубы. // // Входные данные // В первой строке записано натуральное число N — количество узлов в системе (2≤N≤100). // Известно, что источник имеет номер 1, а сток номер N. Во второй строке записано // натуральное M (1≤M≤5000) — количество труб в системе. Далее в M строках идет описание труб. // Каждая труба задается тройкой целых чисел // Ai, Bi, Ci, где Ai, Bi — номера узлов, которые соединяет данная труба (Ai≠Bi), // а Ci (0 ≤ Ci ≤ 10^4) — наибольшая допустимая скорость течения воды через данную трубу. // // Выходные данные // В первой строке выведите наибольшее количество воды, которое протекает между источником и // стоком за единицу времени. Далее выведите M строк, в каждой из которых выведите скорость // течения воды по соответствующей трубе. Если направление не совпадает с порядком узлов, // заданным во входных данных, то выводите скорость со знаком минус. Числа выводите с точностью 10^{−3}. #include <iostream> #include <vector> #include <cstring> #include <climits> struct edge { int a, b, capacity, flow; }; class Dinic { public: Dinic(int kVertexNum, int kEndesNum); void AddEdge(int a, int b, int cap); void SetSource(int e); void SetSink(int e); int GetMaxFlow(); void PrintEdgesFlow(); private: bool bfs(); int dfs(int v, int flow); std::vector<edge> edges; std::vector<std::vector<int>> graph; std::vector<int> d; std::vector<int> ptr; std::vector<int> q; int source, sink; }; Dinic::Dinic(const int kVertexNum, const int kEndesNum) { edges.reserve(kEndesNum); graph.resize(kVertexNum); ptr.reserve(kEndesNum); q.reserve(kEndesNum); d.reserve(kEndesNum); source = 0; sink = kVertexNum - 1; } void Dinic::AddEdge(const int a, const int b, const int cap) { edge e1 = {a, b, cap, 0}; edge e2 = {b, a, cap, 0}; graph[a].push_back(edges.size()); edges.push_back(e1); graph[b].push_back(edges.size()); edges.push_back(e2); } void Dinic::SetSource(const int e) { source = e; } void Dinic::SetSink(const int e) { sink = e; } int Dinic::dfs(const int v, int flow) { if (!flow) { return 0; } if (v == sink) { return flow; } for (; ptr[v] < graph[v].size(); ++ptr[v]) { int id = graph[v][ptr[v]]; int to = edges[id].b; if (d[to] != d[v] + 1) { continue; } int pushed = dfs(to, std::min(flow, edges[id].capacity - edges[id].flow)); if (pushed) { edges[id].flow += pushed; if (id % 2 == 0) edges[id + 1].flow -= pushed; else edges[id - 1].flow -= pushed; return pushed; } } return 0; } bool Dinic::bfs() { int qh = 0, qt = 0; q[qt++] = source; d = std::vector<int>(graph.size(), -1); d[source] = 0; while (qh < qt && d[sink] == -1) { int v = q[qh++]; for (size_t i = 0; i < graph[v].size(); ++i) { int edge_id = graph[v][i]; int to = edges[edge_id].b; if (d[to] == -1 && edges[edge_id].flow < edges[edge_id].capacity) { q[qt++] = to; d[to] = d[v] + 1; } } } return d[sink] != -1;//sink reachable } int Dinic::GetMaxFlow() { int flow = 0; while (bfs()) { ptr = std::vector<int>(graph.size(), 0); while (int subflow = dfs(source, INT_MAX)) { flow += subflow; } } return flow; } void Dinic::PrintEdgesFlow() { for (int i = 0; i < edges.size(); i += 2) { if (edges[i].flow == 0) { std::cout << -edges[i + 1].flow << std::endl; } else { std::cout << edges[i].flow << std::endl; } } } //2 //2 //1 2 1 //2 1 3 int main() { int v, e; std::cin >> v >> e; Dinic dinic(v, e); int g, f, capacity; for (int i = 0; i < e; ++i) { std::cin >> g >> f >> capacity; dinic.AddEdge(g - 1, f - 1, capacity); } dinic.SetSource(0); dinic.SetSink(v - 1); std::cout << dinic.GetMaxFlow() << std::endl; dinic.PrintEdgesFlow(); return 0; }
true
0f4a813e2b2ab6a0a4c997997172bab39ec15c20
C++
Graphics-Physics-Libraries/Tiny3D
/Win32Project1/shader/shadermanager.cpp
UTF-8
910
2.9375
3
[]
no_license
#include "shadermanager.h" using namespace std; ShaderManager::ShaderManager() {} ShaderManager::~ShaderManager() { map<string,Shader*>::iterator itor; for(itor=shaders.begin();itor!=shaders.end();itor++) delete itor->second; shaders.clear(); } Shader* ShaderManager::addShader(const char* name,const char* vs,const char* fs) { Shader* shader=new Shader(vs,fs); shader->name = name; shaders.insert(pair<string,Shader*>(name,shader)); return shader; } Shader* ShaderManager::addShader(const char* name, const char* vs, const char* fs, const char* gs) { Shader* shader = new Shader(vs, fs, gs); shader->name = name; shaders.insert(pair<string, Shader*>(name, shader)); return shader; } Shader* ShaderManager::findShader(const char* name) { map<string,Shader*>::iterator itor=shaders.find(name); if(itor!=shaders.end()) return itor->second; return NULL; }
true
645b86029f7ca33d91e81e5fd988db394a755f42
C++
rcamejo01/data-structures-class
/VecExpense/expense.h
UTF-8
2,080
3.3125
3
[]
no_license
#ifndef EXPENSE_H_ #define EXPENSE_H_ #include <iostream> #include <string> #include <fstream> #include <iomanip> using namespace std; // const array to remember days of month (not doing leap year) // start with 0 so months start at 1 const int mday[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; // expense class class expense { private: double amt; string purpose; public: // default constructor expense(); // setter void setExpense(double,string); // getter double getAmt() { return amt; } // print an expense void print(ostream&); }; class vecexpense { private: expense *exps; int numexp; int currexp; int factor; public: vecexpense(); ~vecexpense(); int addExpense(expense e); void print(ostream&); expense getExpense(int e); }; // daily expense class class daily { private: vecexpense exps; int numexp; int day; public: // default constructor daily(); // add an expense int addExpense(double, string); // setter void setDay(int d) { day = d; } // get total for day double getDailyExpense(); // print all expenses for day void print(ostream&); }; class monthly { private: daily days[31]; int maxdays; int month; public: monthly(); // setter // setting the month also sets the maxdays // and sets the day value for each day void setMonth(int m); // add and expense for a day void addExpense(int, double, string); // get totals double getDailyExpense(int); double getMonthlyExpense(); // print void printOneDay(ostream&, int); void print(ostream&); }; class yearly { private: monthly months[12]; int year; public: // constructor // creating a year also sets all the months yearly(); // setter void setYear(int y) { year = y; } // add an expense for a month and day void addExpense(int, int, double, string); // get totals double getDailyExpense(int,int); double getMonthlyExpense(int); double getYearlyExpense(); // load data int loadDataFromFile(string); // print void printOneDay(ostream&, int, int); void printOneMonth(ostream&, int); void print(ostream&); }; #endif
true
9785a0e15a96ccfbc6a23a52f2be15d3319864e0
C++
readex-eu/readex-apps
/production_apps/BEM4I/WavePreconditioner.cpp
UTF-8
15,768
2.546875
3
[ "BSD-3-Clause" ]
permissive
/*! * @file WavePreconditioner.cpp * @author Michal Merta * @date March 14, 2014 * */ #ifdef WAVEPRECONDITIONER_H namespace bem4i { template<class LO, class SC> WavePreconditioner<LO, SC>::WavePreconditioner( ) { this->sysMatrix = nullptr; this->preconditioner = nullptr; this->sysMatrixMPI = nullptr; this->preconditionerMPI = nullptr; } template<class LO, class SC> WavePreconditioner<LO, SC>::WavePreconditioner( const WavePreconditioner& orig ) { } template<class LO, class SC> WavePreconditioner<LO, SC>::WavePreconditioner( BlockMatrix<LO, SC> * A, int maxLevel, int * maxIters ) { this->sysMatrix = A; preconditioner = new BlockMatrix<LO, SC>( *A ); this->maxLevel = maxLevel; this->level = 1; if ( maxIters == nullptr ) { int size = maxLevel; if ( size < 1 ) { size = 1; } maxIters = new int[size]; for ( int i = 0; i < size; i++ ) { maxIters[i] = defaultMaxIters; } deleteMaxIters = true; } else { deleteMaxIters = false; } this->maxIters = maxIters; // set MPI matrices to null this->sysMatrixMPI = nullptr; this->preconditionerMPI = nullptr; } template<class LO, class SC> WavePreconditioner<LO, SC>::WavePreconditioner( MPIBlockMatrix<LO, SC> * A, int maxLevel, int * maxIters ) { this->sysMatrixMPI = A; preconditionerMPI = new MPIBlockMatrix<LO, SC>( *A ); this->maxLevel = maxLevel; this->level = 1; if ( maxIters == nullptr ) { int size = maxLevel; if ( size < 1 ) { size = 1; } maxIters = new int[size]; for ( int i = 0; i < size; i++ ) { maxIters[i] = defaultMaxIters; } deleteMaxIters = true; } else { deleteMaxIters = false; } this->maxIters = maxIters; // set not MPI matrices to null this->sysMatrix = nullptr; this->preconditioner = nullptr; } template<class LO, class SC> WavePreconditioner<LO, SC>::~WavePreconditioner( ) { delete this->preconditioner; if ( deleteMaxIters == true ) { delete [] maxIters; } } template<class LO, class SC> void WavePreconditioner<LO, SC>::apply( const Vector<LO, SC> & x, Vector<LO, SC> & y, bool transA, SC alpha, SC beta ) { // call appropriate apply method depending on type of matrix if ( preconditioner ) { this->applyPreconditioner( *this->preconditioner, x, y ); } else if ( preconditionerMPI ) { this->applyPreconditioner( *this->preconditionerMPI, x, y ); } } template<class LO, class SC> void WavePreconditioner<LO, SC>::applyPreconditioner( BlockMatrix<LO, SC> & matrix, const Vector<LO, SC>& x, Vector<LO, SC>& y ) { int nBlockRowsM1 = 0; int nBlockRowsM2 = 0; int nBlockColsM1 = 0; int nBlockColsM2 = 0; LO * numsOfRowsM1; LO * numsOfRowsM2; LO * numsOfColsM1; LO * numsOfColsM2; nBlockRowsM1 = (int) ceil( preconditioner->getNBlockRows( ) / 2.0 ); nBlockRowsM2 = preconditioner->getNBlockRows( ) - nBlockRowsM1; nBlockColsM1 = (int) ceil( preconditioner->getNBlockCols( ) / 2.0 ); nBlockColsM2 = preconditioner->getNBlockCols( ) - nBlockColsM1; numsOfRowsM1 = new LO[nBlockRowsM1]; numsOfRowsM2 = new LO[nBlockRowsM2]; numsOfColsM1 = new LO[nBlockColsM1]; numsOfColsM2 = new LO[nBlockColsM2]; for ( int i = 0; i < nBlockRowsM1; i++ ) { numsOfRowsM1[i] = preconditioner->getNRowsOfBlock( i ); numsOfColsM1[i] = preconditioner->getNColsOfBlock( i ); } for ( int i = 0; i < nBlockRowsM2; i++ ) { numsOfRowsM2[i] = preconditioner->getNRowsOfBlock( nBlockRowsM1 + i ); numsOfColsM2[i] = preconditioner->getNColsOfBlock( nBlockColsM1 + i ); } BlockMatrix<LO, SC> * M11 = new BlockMatrix<LO, SC>( nBlockRowsM1, nBlockColsM1, numsOfRowsM1, numsOfColsM1 ); BlockMatrix<LO, SC> * M21 = new BlockMatrix<LO, SC>( nBlockRowsM2, nBlockColsM1, numsOfRowsM2, numsOfColsM1 ); BlockMatrix<LO, SC> * M22 = new BlockMatrix<LO, SC>( nBlockRowsM2, nBlockColsM2, numsOfRowsM2, numsOfColsM2 ); for ( int i = 0; i < nBlockRowsM1; i++ ) { for ( int j = 0; j < nBlockColsM1; j++ ) { M11->setBlock( i, j, preconditioner->getBlock( i, j ) ); } } for ( int i = 0; i < nBlockRowsM2; i++ ) { for ( int j = 0; j < nBlockColsM1; j++ ) { M21->setBlock( i, j, preconditioner->getBlock( nBlockRowsM1 + i, j ) ); } } for ( int i = 0; i < nBlockRowsM2; i++ ) { for ( int j = 0; j < nBlockColsM2; j++ ) { M22->setBlock( i, j, preconditioner->getBlock( nBlockRowsM1 + i, nBlockColsM1 + j ) ); } } Vector<LO, SC> * x1 = new Vector<LO, SC>( M11->getNRows( ) ); Vector<LO, SC> * x2 = new Vector<LO, SC>( M21->getNRows( ) ); Vector<LO, SC> * y1 = new Vector<LO, SC>( M11->getNRows( ) ); Vector<LO, SC> * y2 = new Vector<LO, SC>( M21->getNRows( ) ); y1->setAll( 0.0 ); y2->setAll( 0.0 ); for ( LO i = 0; i < M11->getNRows( ); i++ ) { x1->set( i, x.get( i ) ); } for ( LO i = 0; i < M21->getNRows( ); i++ ) { x2->set( i, x.get( M11->getNRows( ) + i ) ); } //x1->print();x2->print() LeftPreconditioner<LO, SC> * precM11; //( M11 ); LeftPreconditioner<LO, SC> * precM22; if ( maxLevel != -1 && level >= maxLevel ) { // if we are deep enough do not use preconditioner any more precM11 = new LeftIdentityPreconditioner<LO, SC>; //WavePreconditionerTriangular<LO, SC>(M11);// precM22 = new LeftIdentityPreconditioner<LO, SC>; //new WavePreconditionerTriangular<LO, SC>(M22);// } else { // precM11 = new LeftIdentityPreconditioner<LO, SC>; //WavePreconditionerTriangular<LO, SC>(M11);// // precM22 = new LeftIdentityPreconditioner<LO, SC>; precM11 = new WavePreconditioner<LO, SC>( M11, this->maxLevel, this->maxIters ); precM22 = new WavePreconditioner<LO, SC>( M22, this->maxLevel, this->maxIters ); ( ( WavePreconditioner<LO, SC>* ) precM11 )->setCurrentLevel( this->level + 1 ); ( ( WavePreconditioner<LO, SC>* ) precM22 )->setCurrentLevel( this->level + 1 ); } if ( M11->getNBlockRows( ) > 1 ) { //WavePreconditioner<LO, SC> precM11( M11 ); M11->FGMRESSolve( *x1, *y1, 1e-9, maxIters[level - 1], 200, precM11 ); //M11->DGMRESSolve( *x1, *y1, 1e-9, 1000, 200, 200, 2, precM11 ); } else { SparseMatrix<LO, SC>* diagMatrix = ( SparseMatrix<LO, SC>* ) M11->getBlock( 0, 0 ); diagMatrix->LUSolve( *x1, *y1 ); } M21->apply( *y1, *x2, false, -1.0, 1.0 ); if ( M22->getNBlockRows( ) > 1 ) { //WavePreconditioner<LO, SC> precM22( M22 ); M22->FGMRESSolve( *x2, *y2, 1e-9, maxIters[level - 1], 200, precM22 ); //M22->DGMRESSolve( *x2, *y2, 1e-9, 1000, 200,200, 2, precM22 ); } else { SparseMatrix<LO, SC>* diagMatrix = ( SparseMatrix<LO, SC>* ) M22->getBlock( 0, 0 ); diagMatrix->LUSolve( *x2, *y2 ); } for ( LO i = 0; i < y1->getLength( ); i++ ) { y.set( i, y1->get( i ) ); } for ( LO i = 0; i < y2->getLength( ); i++ ) { y.set( M11->getNRows( ) + i, y2->get( i ) ); } delete M11; delete M22; delete M21; delete precM11; delete precM22; delete x1; delete y1; delete x2; delete y2; delete [] numsOfRowsM1; delete [] numsOfRowsM2; delete [] numsOfColsM1; delete [] numsOfColsM2; } template<class LO, class SC> void WavePreconditioner<LO, SC>::applyPreconditioner( MPIBlockMatrix<LO, SC> & matrix, const Vector<LO, SC> & x, Vector<LO, SC>& y ) { int nBlockRowsM1 = 0; int nBlockRowsM2 = 0; int nBlockColsM1 = 0; int nBlockColsM2 = 0; LO * numsOfRowsM1; LO * numsOfRowsM2; LO * numsOfColsM1; LO * numsOfColsM2; int * ranksM11, * ranksM21, * ranksM22; nBlockRowsM1 = (int) ceil( preconditionerMPI->getNBlockRows( ) / 2.0 ); nBlockRowsM2 = preconditionerMPI->getNBlockRows( ) - nBlockRowsM1; nBlockColsM1 = (int) ceil( preconditionerMPI->getNBlockCols( ) / 2.0 ); nBlockColsM2 = preconditionerMPI->getNBlockCols( ) - nBlockColsM1; numsOfRowsM1 = new LO[nBlockRowsM1]; numsOfRowsM2 = new LO[nBlockRowsM2]; numsOfColsM1 = new LO[nBlockColsM1]; numsOfColsM2 = new LO[nBlockColsM2]; ranksM11 = new int[nBlockRowsM1 * nBlockColsM1]; ranksM21 = new int[nBlockRowsM2 * nBlockColsM1]; ranksM22 = new int[nBlockRowsM2 * nBlockColsM2]; for ( int i = 0; i < nBlockRowsM1; i++ ) { for ( int j = 0; j < nBlockColsM1; j++ ) { ranksM11[j * nBlockRowsM1 + i] = matrix.getOwner( i, j ); } } for ( int i = 0; i < nBlockRowsM2; i++ ) { for ( int j = 0; j < nBlockColsM1; j++ ) { ranksM21[j * nBlockRowsM2 + i] = matrix.getOwner( nBlockRowsM1 + i, j ); } } for ( int i = 0; i < nBlockRowsM2; i++ ) { for ( int j = 0; j < nBlockColsM2; j++ ) { ranksM22[j * nBlockRowsM2 + i] = matrix.getOwner( nBlockRowsM1 + i, nBlockColsM1 + j ); } } for ( int i = 0; i < nBlockRowsM1; i++ ) { numsOfRowsM1[i] = preconditionerMPI->getNRowsOfBlock( i ); numsOfColsM1[i] = preconditionerMPI->getNColsOfBlock( i ); } for ( int i = 0; i < nBlockRowsM2; i++ ) { numsOfRowsM2[i] = preconditionerMPI->getNRowsOfBlock( nBlockRowsM1 + i ); numsOfColsM2[i] = preconditionerMPI->getNColsOfBlock( nBlockColsM1 + i ); } MPIBlockMatrix<LO, SC> * M11 = new MPIBlockMatrix<LO, SC>( nBlockRowsM1, nBlockColsM1, numsOfRowsM1, numsOfColsM1, ranksM11, matrix.getCommunicator( ) ); MPIBlockMatrix<LO, SC> * M21 = new MPIBlockMatrix<LO, SC>( nBlockRowsM2, nBlockColsM1, numsOfRowsM2, numsOfColsM1, ranksM21, matrix.getCommunicator( ) ); MPIBlockMatrix<LO, SC> * M22 = new MPIBlockMatrix<LO, SC>( nBlockRowsM2, nBlockColsM2, numsOfRowsM2, numsOfColsM2, ranksM22, matrix.getCommunicator( ) ); for ( int i = 0; i < nBlockRowsM1; i++ ) { for ( int j = 0; j < nBlockColsM1; j++ ) { M11->setBlock( i, j, preconditionerMPI->getBlock( i, j ) ); } } for ( int i = 0; i < nBlockRowsM2; i++ ) { for ( int j = 0; j < nBlockColsM1; j++ ) { M21->setBlock( i, j, preconditionerMPI->getBlock( nBlockRowsM1 + i, j ) ); } } for ( int i = 0; i < nBlockRowsM2; i++ ) { for ( int j = 0; j < nBlockColsM2; j++ ) { M22->setBlock( i, j, preconditionerMPI->getBlock( nBlockRowsM1 + i, nBlockColsM1 + j ) ); } } Vector<LO, SC> * x1 = new Vector<LO, SC>( M11->getNRows( ) ); Vector<LO, SC> * x2 = new Vector<LO, SC>( M21->getNRows( ) ); Vector<LO, SC> * y1 = new Vector<LO, SC>( M11->getNRows( ) ); Vector<LO, SC> * y2 = new Vector<LO, SC>( M21->getNRows( ) ); y1->setAll( 0.0 ); y2->setAll( 0.0 ); for ( LO i = 0; i < M11->getNRows( ); i++ ) { x1->set( i, x.get( i ) ); } for ( LO i = 0; i < M21->getNRows( ); i++ ) { x2->set( i, x.get( M11->getNRows( ) + i ) ); } //x1->print();x2->print() LeftPreconditioner<LO, SC> * precM11; //( M11 ); LeftPreconditioner<LO, SC> * precM22; if ( maxLevel != -1 && level >= maxLevel ) { // if we are deep enough do not use preconditionerMPI any more precM11 = new LeftIdentityPreconditioner<LO, SC>; //WavePreconditionerTriangular<LO, SC>(M11);// precM22 = new LeftIdentityPreconditioner<LO, SC>; //new WavePreconditionerTriangular<LO, SC>(M22);// } else { precM11 = new WavePreconditioner<LO, SC>( M11, this->maxLevel ); precM22 = new WavePreconditioner<LO, SC>( M22, this->maxLevel ); ( ( WavePreconditioner<LO, SC>* ) precM11 )->setCurrentLevel( this->level + 1 ); ( ( WavePreconditioner<LO, SC>* ) precM22 )->setCurrentLevel( this->level + 1 ); } MPI_Barrier( preconditionerMPI->getCommunicator( ) ); if ( M11->getNBlockRows( ) > 1 ) { //WavePreconditioner<LO, SC> precM11( M11 ); M11->FGMRESSolve( *x1, *y1, 1e-5, 10, 200, precM11 ); } else { SparseMatrix<LO, SC>* diagMatrix = ( SparseMatrix<LO, SC>* ) M11->getBlock( 0, 0 ); diagMatrix->LUSolve( *x1, *y1 ); } MPI_Barrier( preconditionerMPI->getCommunicator( ) ); M21->apply( *y1, *x2, false, -1.0, 1.0 ); MPI_Barrier( preconditionerMPI->getCommunicator( ) ); if ( M22->getNBlockRows( ) > 1 ) { //WavePreconditioner<LO, SC> precM22( M22 ); M22->FGMRESSolve( *x2, *y2, 1e-5, 10, 200, precM22 ); } else { SparseMatrix<LO, SC>* diagMatrix = ( SparseMatrix<LO, SC>* ) M22->getBlock( 0, 0 ); diagMatrix->LUSolve( *x2, *y2 ); } MPI_Barrier( preconditionerMPI->getCommunicator( ) ); for ( LO i = 0; i < y1->getLength( ); i++ ) { y.set( i, y1->get( i ) ); } for ( LO i = 0; i < y2->getLength( ); i++ ) { y.set( M11->getNRows( ) + i, y2->get( i ) ); } MPI_Barrier( preconditionerMPI->getCommunicator( ) ); delete M11; delete M22; delete M21; delete precM11; delete precM22; delete x1; delete y1; delete x2; delete y2; delete [] numsOfRowsM1; delete [] numsOfRowsM2; delete [] numsOfColsM1; delete [] numsOfColsM2; delete [] ranksM11; delete [] ranksM21; delete [] ranksM22; } //template<class LO, class SC> //void WavePreconditioner<LO, SC>::applyGSPreconditioner( // BlockMatrix<LO, SC> & matrix, // const Vector<LO, SC>& x, // Vector<LO, SC>& y ) { // // // x(k+1)= -(L+D)^(-1)*U*x(k) + (L+D)^(-1)*b // // LO nIters = 10; // //y.print(); // y.setAll( 0.0 ); // for ( LO i = 0; i < nIters; i++ ) { // Vector<LO, SC> Uxk( x.getLength( ) ); // // for ( LO j = 0; j < matrix.getNBlockRows( ) - 1; j++ ) { // // SparseMatrix<LO, SC> *M = ( SparseMatrix<LO, SC>* ) // matrix.getBlock( j, j + 1 ); // // LO n = M->getNRows( ); // Vector<LO, SC> yLocal( n ); // Vector<LO, SC> UxkLocal( n ); // for ( LO k = 0; k < n; k++ ) { // yLocal.set( k, y.get( ( j + 1 ) * n + k ) ); // //std::cout << y.get( (j) * n + k ) << std::endl; // } // M->apply( yLocal, UxkLocal ); // for ( LO k = 0; k < n; k++ ) { // Uxk.set( j * n + k, -UxkLocal.get( k ) ); // } // } // SC omega = 0.5; // Uxk.scale( omega ); // Uxk.add( x, omega ); // Vector<LO, SC> yy( y ); // // applyLInverse( matrix, Uxk, yy ); // y.scale( 1.0 - omega ); // y.add( yy, omega ); // // // y.print(); // } // //} // //template<class LO, class SC> //void WavePreconditioner<LO, SC>::applyLInverse( // BlockMatrix<LO, SC> & matrix, // const Vector<LO, SC>& x, // Vector<LO, SC>& y ) { // // // apply only the diagonal and lower triangle of the matrix // Vector<LO, SC> xLocal( x ); // LO currentRow = 0; // // for ( LO i = 0; i < matrix.getNBlockRows( ); i++ ) { // SparseMatrix<LO, SC> *Mii = ( SparseMatrix<LO, SC>* ) // matrix.getBlock( i, i ); // LO ni = Mii->getNRows( ); // // Vector<LO, SC> xi( ni ); // Vector<LO, SC> yi( ni ); // // yi.setAll( 0.0 ); // // for ( LO j = 0; j < ni; j++ ) { // xi.set( j, xLocal.get( ni * i + j ) ); // } // //LeftIdentityPreconditioner<LO, SC>* prc = new LeftIdentityPreconditioner<LO, SC>; // //Mii->GMRESSolve( xi, yi, 1e-9, 2000, 200 , prc); // // //if (i==19) { // // Mii->print(); // // exit(0); // //} // // Mii->LUSolve( xi, yi ); // // for ( LO j = 0; j < ni; j++ ) { // // if (isnan(yi.get( j ))) { // // std::cout << i << " " <<j <<std::endl; // // } // y.set( ni * i + j, yi.get( j ) ); // } // // for ( LO j = i + 1; j < matrix.getNBlockRows( ); j++ ) { // SparseMatrix<LO, SC> *Mji = ( SparseMatrix<LO, SC>* ) // matrix.getBlock( j, i ); // if ( Mji != nullptr ) { // Vector<LO, SC> MjiXi( ni ); // Mji->apply( yi, MjiXi ); // for ( LO k = 0; k < ni; k++ ) { // xLocal.set( j * ni + k, xLocal.get( j * ni + k ) - 0.5 * MjiXi.get( k ) ); // } // } // } // // currentRow += ni; // } // //} } #endif
true