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
edbdceceda5060a18edd6d7f7d3258433ee96191
C++
pdicerbo/P1.5
/D2-codes/oop_fundamentals/rectangle.cpp
UTF-8
396
3.21875
3
[]
no_license
/* Created by G.P. Brandino for the Course P1.5 - Object Oriented Programming @ MHPC * Last Revision: October 2015 */ #include <iostream> using namespace std; class rectangle { public: float width, height; float area(); }; float rectangle::area() { return width*height; } int main() { rectangle a; a.width=5.0; a.height=2.0; cout << a.area() << endl; return 0; }
true
2be13deb53855299bb07f0173e9a1f89c80ebc5c
C++
jbreitbart/OpenSteer
/TRY-JB-cmake-build-system/unittests/tests/omp_stop_watch_test.cpp
UTF-8
5,688
2.5625
3
[ "MIT" ]
permissive
/** * Kapaga: Kassel Parallel Games * * Copyright (c) 2006-2007, Kapaga Development Group * All rights reserved. * * This file is part of the Kapaga project. * For conditions of distribution and use, see copyright notice in kapaga_license.txt. */ /** * @file * * Unit test for @c omp_stop_watch. */ #include <UnitTest++/UnitTest++.h> // Include kapaga::omp_stop_watch #include "kapaga/omp_stop_watch.h" // Include kapaga::omp_timer #include "kapaga/omp_timer.h" // Include kapaga::os_process_sleep_ms #include "kapaga/os_process_utilities.h" // Include kapaga::duration, kapaga::omp_time_t, kapaga::omp_time_conversion_s_to_ms namespace { double const time_comparison_epsilon_ms = 1.0; double const time_comparison_epsilon_s = 0.1; } // anonymous namespace SUITE(omp_stop_watch_test) { TEST(elapsed_time) { // Test that a stop watch and a timer are near each other when measuring elasped time // without any pauses or restarts. // As @c kapaga::os_process_sleep_ms is used this also tests if the stop watch measures // wall clock time or cpu ticks (it should/must measure wall clock time). using namespace kapaga; omp_stop_watch watch; omp_timer timer; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_stop_watch::time_type stop_watch_time = watch.elapsed_time(); omp_timer::time_type timer_time = timer.elapsed_time(); double stop_watch_ms = convert_time_to_ms< double >( stop_watch_time ); double timer_ms = convert_time_to_ms< double >( timer_time ); CHECK_CLOSE( timer_ms, stop_watch_ms, time_comparison_epsilon_ms ); } TEST(suspend_and_resume) { // Check that a stop watch doesn't measure time while suspended using namespace kapaga; omp_stop_watch watch; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_stop_watch::time_type time0 = watch.elapsed_time(); watch.suspend(); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_stop_watch::time_type time1 = watch.elapsed_time(); CHECK_CLOSE( convert_time_to_ms< double >( time0 ), convert_time_to_ms< double >( time1 ), static_cast< double >( time_comparison_epsilon_ms ) ); watch.resume(); omp_timer timer2; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_stop_watch::time_type watch_time2 = watch.elapsed_time(); omp_timer::time_type timer2_time = timer2.elapsed_time(); CHECK_CLOSE( convert_time_to_ms< double >( time1 ) + convert_time_to_ms< double >( timer2_time ), convert_time_to_ms< double >( watch_time2 ), time_comparison_epsilon_ms ); } TEST(restart_while_running) { using namespace kapaga; // Restart while running. omp_stop_watch watch; omp_timer timer; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.restart(); timer.restart(); omp_stop_watch::time_type watch_time0 = watch.elapsed_time(); omp_timer::time_type timer_time0 = timer.elapsed_time(); CHECK_CLOSE( convert_time_to_ms< double >( timer_time0 ), convert_time_to_ms< double >( watch_time0 ), time_comparison_epsilon_ms ); } TEST(restart_while_suspended) { using namespace kapaga; // Restart while running. omp_stop_watch watch; omp_timer timer; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.suspend(); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.restart(); timer.restart(); omp_stop_watch::time_type watch_time0 = watch.elapsed_time(); omp_timer::time_type timer_time0 = timer.elapsed_time(); CHECK_CLOSE( convert_time_to_ms< double >( timer_time0 ), convert_time_to_ms< double >( watch_time0 ), time_comparison_epsilon_ms ); } TEST(start_suspended) { using namespace kapaga; omp_stop_watch watch( omp_stop_watch::start_suspended ); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_timer timer; watch.resume(); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_timer::time_type timer_time = timer.elapsed_time(); omp_stop_watch::time_type watch_time = watch.elapsed_time(); CHECK_CLOSE( convert_time_to_ms< double >( timer_time ), convert_time_to_ms< double >( watch_time ), time_comparison_epsilon_ms ); } TEST(restart_suspended) { using namespace kapaga; omp_stop_watch watch; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.restart( omp_stop_watch::start_suspended ); omp_stop_watch other_watch( omp_stop_watch::start_suspended ); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); CHECK_CLOSE( convert_time_to_ms< double >( watch.elapsed_time() ), convert_time_to_ms< double >( other_watch.elapsed_time() ), time_comparison_epsilon_ms ); } TEST(restart_suspended_while_suspended) { using namespace kapaga; omp_stop_watch watch; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.suspend(); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.restart( omp_stop_watch::start_suspended ); os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); watch.resume(); omp_timer timer; os_process_sleep_ms( static_cast< os_process_sleep_ms_t >( 1000 ) ); omp_stop_watch::time_type watch_time = watch.elapsed_time(); omp_timer::time_type timer_time = timer.elapsed_time(); CHECK_CLOSE( convert_time_to_ms< double >( timer_time ), convert_time_to_ms< double >( watch_time ), time_comparison_epsilon_ms ); } } // SUITE(omp_stop_watch_test)
true
bf5fecb6d74e3e3c232054081658b30cb1009357
C++
rjcostales/school
/cs177_c++/SwampRunner/SCell.h
UTF-8
432
3.28125
3
[]
no_license
/* Raphael J. S. Costale * SCell.h - Abstract Base Class * 5/5/93 */ #ifndef SCELL_H #define SCELL_H #include <iostream> using namespace std; #include <stdbool.h> class SCell { public: // Constructor SCell(const char image, const bool safe) { mImage = image; isSafe = safe; } bool safe() { return isSafe; }; // returns true is cell can be stood on void draw() { cout << mImage; } protected: char mImage; bool isSafe; }; #endif
true
802ea3abbcbf9552d8722de9c1ffd2181cb96111
C++
sagar-barapatre/Data-Structures-and-Algorithms
/Graphs/knight_moves.cpp
UTF-8
1,263
3.5
4
[]
no_license
#include<bits/stdc++.h> #define M 8 #define N 8 using namespace std; // The time complexity of above solution will be O(m*n), where m and n are size // of 2D matrix given; /* The solution will be same for the shortest path in a binary maze, we just need to update dx[] = { -1, 0, 0, 1 }; and dy[] ={ 0, -1, 1, 0 }; and run loop from i = 0 to i = 4 and that's it we are done. */ class cell { public : int x; int y; int dist; cell(int x, int y, int dist) { this->x = x; this->y = y; this->dist = dist; } }; bool isInside(int x, int y, int M, int N) { if ((x >= 0 && x < M) && (y >= 0 && y < N)) return true; return false; } int numberOfMoves(int x1, int y1, int x2, int y2) { queue<cell> q; cell src(x1 - 1, y1 - 1, 0); q.push(src); bool visited[M][N]; memset(visited, 0, sizeof(visited)); int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 }; int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 }; int x, y; while (!q.empty()) { cell t = q.front(); q.pop(); if (t.x == x2 - 1 && t.y == y2 - 1) return t.dist; for (int i = 0 ; i < 8 ; i++) { x = t.x + dx[i]; y = t.y + dy[i]; if (isInside(x, y, M, N) && !visited[x][y]) { visited[x][y] = true; cell dest(x, y, t.dist + 1); q.push(dest); } } } return -1; }
true
7acf80fdb5df03bb8952dfbbb75ab5c90bdb6bfb
C++
Crispelinho/RobotAutomata
/Prueba_motores1.ino
UTF-8
2,516
2.78125
3
[]
no_license
int izqA = 2; int izqB = 3; int derA = 4; int derB = 5; int vel = 255; // Velocidad de los motores (0-255) int estado = 'g'; // inicia detenido int pecho=10; int ptrig=9; int duracion,distancia; void setup() { Serial.begin(9600); // inicia el puerto serial para comunicacion con el Bluetooth pinMode(11, OUTPUT); pinMode(derA, OUTPUT); pinMode(derB, OUTPUT); pinMode(izqA, OUTPUT); pinMode(izqB, OUTPUT); pinMode(pecho, INPUT); pinMode(ptrig, OUTPUT); pinMode(13, OUTPUT); } void loop() { digitalWrite(11,HIGH); if(Serial.available()>0){ // lee el bluetooth y almacena en estado estado = Serial.read(); } if(estado=='a'){ // Boton desplazar al Frente analogWrite(derB, 0); analogWrite(izqB, 0); analogWrite(derA, vel); analogWrite(izqA, vel); } if(estado=='b'){ // Boton IZQ analogWrite(derB, 0); analogWrite(izqB, 0); analogWrite(derA, 0); analogWrite(izqA, vel); } if(estado=='c'){ // Boton Parar analogWrite(derB, 0); analogWrite(izqB, 0); analogWrite(derA, 0); analogWrite(izqA, 0); } if(estado=='d'){ // Boton DER analogWrite(derB, 0); analogWrite(izqB, 0); analogWrite(izqA, 0); analogWrite(derA, vel); } if(estado=='e'){ // Boton Reversa analogWrite(derA, 0); analogWrite(izqA, 0); analogWrite(derB, vel); analogWrite(izqB, vel); } if (estado =='f'){ // Boton ON se mueve sensando distancia digitalWrite(ptrig,HIGH); delay(0.01); digitalWrite(ptrig,LOW); duracion = pulseIn(pecho,HIGH); distancia = (duracion/2)/29; delay(10); if(distancia <= 15 && distancia >= 2) { digitalWrite(13,HIGH); analogWrite(derB,0); analogWrite(izqB,0); analogWrite(derA,0); analogWrite(izqA,0); delay(200); analogWrite(derB,vel); analogWrite(izqB,vel); delay(500); analogWrite(derB,0); analogWrite(izqB,0); analogWrite(derA,0); analogWrite(izqA,vel); delay(1100); digitalWrite(13,LOW); } else {//Sino hay obstáculos se desplaza al frente analogWrite(derB,0); analogWrite(izqB,0); analogWrite(derA,vel); analogWrite(izqA,vel); } } if (estado=='g'){ // Boton OFF, detiene los motores no hace nada analogWrite(derB,0); analogWrite(izqB,0); analogWrite(derA,0); analogWrite(izqA,0); } }
true
329e515644c331b2a7e89f76a2cdedba99749e1c
C++
SeungWookJung/Cpp_Study
/6_26/6_26/Calulator.cpp
WINDOWS-1252
424
3.4375
3
[]
no_license
#include "Add.h" #include "Min.h" #include "Mul.h" #include "Div.h" int Add(int num1, int num2) // { int result = num1 + num2; return result; } int Min(int num1, int num2) // { int result = num1 - num2; return result; } int Mul(int num1, int num2) // { int result = num1 * num2; return result; } int Div(int num1, int num2) // { int result = num1 / num2; return result; }
true
beb60d5d4e89224dea9f8b5b0259567862606c61
C++
NDU-CSC413/c-review
/51inclass2/51inclass2.cpp
UTF-8
1,541
3.921875
4
[]
no_license
#include <iostream> /* Make the Container class * moveable but not copyable * */ class Container { int _size; int* _data=nullptr; public: Container(int size) :_size(size), _data(new int[size] {}) {} int& operator[](int idx) { return _data[idx]; } void resize(int newsize) { if (newsize <= _size)return; int* tmp = new int[newsize]();//initialize with 0 for (int i = 0; i < _size; ++i) tmp[i] = _data[i]; _size = newsize; delete[] _data; _data = tmp; } Container(const Container& rhs) = delete; Container& operator=(Container& rhs) = delete; Container(Container&& rhs) noexcept{ _size = rhs._size; _data = rhs._data; rhs._size = 0; rhs._data = nullptr; } Container& operator=(Container&& rhs) noexcept { if (_data != nullptr) delete[] _data; _size = rhs._size; _data = rhs._data; rhs._size = 0; rhs._data = nullptr; return *this; } int size() { return _size; } ~Container() { if (_data != nullptr) delete[] _data; } }; int main() { const int n = 8; /* create a container of size n */ Container c(n); /* initial values */ for (int i = 0; i < c.size(); ++i)std::cout << c[i] << ","; std::cout << "\n"; /* change the initial values */ for (int i = 0; i < c.size(); ++i)c[i] = i; /* resize */ c.resize(12); /* use move ctor d of c */ //Container d = c;// error Container d = std::move(c);//move ctor if(c.size()>0) std::cout << "c[0]=" << c[0] << "\n"; for (int i = 0; i < d.size(); ++i) std::cout<<d[i]<<","; std::cout << "\n"; c = std::move(d); }
true
64631a6c411c0b9eddc1d089a50e4d485ed9bdf8
C++
Jake-Baum/Vulkan
/Vulkan/RenderPass.cpp
UTF-8
1,919
2.921875
3
[]
no_license
#include "RenderPass.h" RenderPass::RenderPass(VkDevice device, VkFormat swapChainImageFormat) : device(device), swapChainImageFormat(swapChainImageFormat) {} void RenderPass::createRenderPass() { VkAttachmentDescription colourAttachment{}; colourAttachment.format = swapChainImageFormat; colourAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colourAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colourAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colourAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colourAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colourAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colourAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colourAttachmentRef{}; colourAttachmentRef.attachment = 0; colourAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colourAttachmentRef; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colourAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass"); } }
true
84e74071a870c6c9db8b5144329c8ccbbaf6ca36
C++
dothithuy/ElastosRDK5_0
/Sources/Elastos/Frameworks/Droid/Base/Core/src/graphics/drawable/shapes/ArcShape.cpp
UTF-8
1,179
2.6875
3
[]
no_license
#include "graphics/drawable/shapes/ArcShape.h" namespace Elastos { namespace Droid { namespace Graphics { namespace Drawable { namespace Shapes { ArcShape::ArcShape() : mStart(0) , mSweep(0) {} /** * ArcShape constructor. * * @param startAngle the angle (in degrees) where the arc begins * @param sweepAngle the sweep angle (in degrees). Anything equal to or * greater than 360 results in a complete circle/oval. */ ArcShape::ArcShape( /* [in] */ Float startAngle, /* [in] */ Float sweepAngle) : mStart(startAngle) , mSweep(sweepAngle) {} ECode ArcShape::Draw( /* [in] */ ICanvas* canvas, /* [in] */ IPaint* paint) { return canvas->DrawArc(Rect(), mStart, mSweep, TRUE, paint); } ECode ArcShape::Init( /* [in] */ Float startAngle, /* [in] */ Float sweepAngle) { mStart = startAngle; mSweep = sweepAngle; return NOERROR; } void ArcShape::Clone( /* [in] */ ArcShape* other) { RectShape::Clone((RectShape*)other); other->mStart = mStart; other->mSweep = mSweep; } } // namespace Shapes } // namespace Drawable } // namespace Graphics } // namespace Droid } // namespace Elastos
true
902d003cae5bd8b68f4b54d3404f82b898f4df10
C++
sandexp/Pat-Algorithm
/Example/DataStrunct.cpp
UTF-8
4,101
3.390625
3
[]
no_license
#include <iostream> #include <math.h> #include <algorithm> #include <string> #include <stack> using namespace std; struct MyStack{ // top最顶层元素 int top; int* arr; MyStack(){ this->top=-1; this->arr=NULL; } void clear(){ this->top=-1; } int size(){ return this->top+1; } bool empty(){ if(this->top==-1) return true; else return false; } void push(int x){ this->top++; if(this->top==0) this->arr=&x; else *(this->arr+this->top)=x; std::cout << "push end" << std::endl; } void pop(){ if(this->top!=-1){ this->top--; } else{ std::cout << "Error: 空数组不能pop" << std::endl; } } int topElement(){ return *(arr+this->top); } }s; struct MyQueue{ int* arr; int front; int end; MyQueue() { this->arr=NULL; this->front=-1; this->end=-1; } void clear(){ this->arr=NULL; this->front=this->end=-1; } bool empty(){ if(this->front==-1 || this->end==-1) return true; else return false; } int size(){ return this->end-this->front+1; } // 入队 void push(int x){ int x1=0; if(this->empty()){ // 给野指针地址 this->arr=&x; this->front=0; this->end=0; } else { int deta=++this->end; *(this->arr+deta)=x; std::cout <<"Addr: "<< this->arr <<"\tValue= "<<*this->arr<<"\tAddr+deta= "<<this->arr+deta<<"\tDetaValue= "<<*(this->arr+deta)<< std::endl; } } // 出队 队首出队 void pop(){ if(this->front!=-1){ this->front++; } } // 取队首 int get_front(){ if(this->empty()) return -999; else{ return *(this->arr+this->front); } } // 取队尾 int get_end(){ if(this->empty()) return -999; else return *(this->arr+this->end); } }q; struct StaticList{ int data; // 使用数组下标来表示指针的位置 int index; }; struct MyLinkList{ // 数据域 int data; // 指针域 MyLinkList* next; }; MyLinkList* create(int* arr,int len){ MyLinkList *p,*pre,*head; head=new MyLinkList; head->next=NULL; pre=head; for (int i = 0; i < len; i++) { p=new MyLinkList; p->data=*(arr+i); pre->next=p; pre=p; } return head; } int search(MyLinkList* head,int x){ int cnt=0; MyLinkList* p=head->next; while (p!=NULL) { if(p->data==x) cnt++; p=p->next; } return cnt; } void insert(int* head,int pos,int x){ MyLinkList* p=head; // 移动到pos-1位置 for (int i = 0; i < pos-1; i++) { p=p->next; } MyLinkList* e=new MyLinkList; e->data=x; e->next=p->next; p->next=e; } void del(MyLinkList* head,int x){ MyLinkList* p=head->next; MyLinkList* pre=head->next; while (p!=null) { if (p->data==x) { pre->next=p->next; // 处理内存泄漏 delete(p); // 重新建立新的连接 p=pre->next; }else { p=p->next; } } } int main(int argc, char const *argv[]) { // s.push(2); // s.push(4); // s.push(5); // std::cout << s.topElement()<< std::endl; // s.pop(); // std::cout << s.topElement()<< std::endl; // q.push(1); // q.push(4); // q.push(8); // std::cout <<"Front= "<<q.get_front()<<"\tEnd= "<<q.get_end() << std::endl; // q.push(7); // std::cout <<"Front= "<<q.get_front()<<"\tEnd= "<<q.get_end() << std::endl; // C++ 解决内存泄漏的问题 // delete(link1); // 创建链表 int a[5]={1,7,2,3,4}; MyLinkList* m=create(a,5); return 0; }
true
e03b64368f8e9ff23ecacbd7e2010484cd904863
C++
NamanKhurana/PEP_DS_ALGO
/PEP_DS_ADV/Recursion/l002.cpp
UTF-8
10,479
3.28125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int queenCombination1D(vector<bool> &boxes, int qpsf, int tnq, int idx, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < boxes.size(); i++) { count += queenCombination1D(boxes, qpsf + 1, tnq - 1, i + 1, ans + "B" + to_string(i + 1) + "Q" + to_string(qpsf + 1) + " "); } return count; } int queenCombination1DSub(vector<bool> &boxes, int qpsf, int tnq, int idx, string ans) { if (idx == boxes.size() + 1) { return 0; } if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; count += queenCombination1DSub(boxes, qpsf + 1, tnq - 1, idx + 1, ans + "B" + to_string(idx + 1) + "Q" + to_string(qpsf + 1) + " "); count += queenCombination1DSub(boxes, qpsf, tnq, idx + 1, ans); return count; } int queenPermutation1D(vector<bool> &boxes, int qpsf, int tnq, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = 0; i < boxes.size(); i++) { if (!boxes[i]) { boxes[i] = true; count += queenPermutation1D(boxes, qpsf + 1, tnq - 1, ans + "B" + to_string(i + 1) + "Q" + to_string(qpsf + 1) + " "); boxes[i] = false; } } return count; } int queenPermutation1DSub(vector<bool> &boxes, int idx, int qpsf, int tnq, string ans) { if (idx == boxes.size()) { return 0; } if (qpsf == tnq) { cout << ans << endl; return 1; } int count = 0; if (!boxes[idx]) { boxes[idx] = true; count += queenPermutation1DSub(boxes, 0, qpsf + 1, tnq, ans + "B" + to_string(idx + 1) + "Q" + to_string(qpsf + 1) + " "); boxes[idx] = false; } count += queenPermutation1DSub(boxes, idx + 1, qpsf, tnq, ans); return count; } int queenCombination2D(vector<vector<bool>> &boxes, int qpsf, int idx, int tnq, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < boxes.size() * boxes[0].size(); i++) { //to convert 2-D to 1-D int x = i / boxes[0].size(); int y = i % boxes[0].size(); count += queenCombination2D(boxes, qpsf + 1, i + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ") "); } return count; } int queenPermutation2D(vector<vector<bool>> &boxes, int qpsf, int tnq, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = 0; i < boxes.size() * boxes[0].size(); i++) { int x = i / boxes[0].size(); int y = i % boxes[0].size(); if (!boxes[x][y]) { boxes[x][y] = true; count += queenPermutation2D(boxes, qpsf + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ") "); boxes[x][y] = false; } } return count; } void queenSet() { // vector<bool> boxes(4, false); vector<vector<bool>> boxes(4, vector<bool>(4, false)); // cout<<queenCombination1D(boxes,0,3,0,""); // cout<<queenCombination1DSub(boxes,0,3,0,""); // cout << queenPermutation1D(boxes, 0, 3, ""); // cout<<endl<<endl<<endl; // cout << queenPermutation1DSub(boxes, 0, 0,3, ""); // cout << queenCombination2D(boxes, 0, 0, 3, ""); cout << queenPermutation2D(boxes, 0, 3, ""); } //HELPER FUNCTION bool isSafe(vector<vector<bool>> &boxes, int sr, int sc) { vector<vector<int>> dir = {{0, -1}, {-1, -1}, {-1, 0}, {-1, 1}}; for (int i = 0; i < dir.size(); i++) { for (int jump = 1; jump <= boxes.size(); jump++) { int nr = sr + jump * dir[i][0]; int nc = sc + jump * dir[i][1]; if (nr >= 0 && nc >= 0 && nr < boxes.size() && nc < boxes.size()) { if (boxes[nr][nc]) { return false; } } else { break; } } } return true; } //NQUEEN VARIATIONS.................................................................................. int Nqueen_01(vector<vector<bool>> &boxes, int idx, int tnq, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < boxes.size() * boxes[0].size(); i++) { //to convert 2-D to 1-D int x = i / boxes[0].size(); int y = i % boxes[0].size(); if (isSafe(boxes, x, y)) { boxes[x][y] = true; count += Nqueen_01(boxes, i + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ") "); boxes[x][y] = false; } } return count; } vector<bool> row(4, false); vector<bool> col(4, false); vector<bool> dia(7, false); //m+n-1 = 7 vector<bool> antiDia(7, false); //m+n-1 = 7 int Nqueen_02(int m, int n, int idx, int tnq, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < m * n; i++) { int x = i / n; int y = i % n; if (!row[x] && !col[y] && !dia[x - y + n - 1] && !antiDia[x + y]) { row[x] = true; col[y] = true; dia[x - y + n - 1] = true; antiDia[x + y] = true; count += Nqueen_02(m, n, i + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ") "); row[x] = false; col[y] = false; dia[x - y + n - 1] = false; antiDia[x + y] = false; } } return count; } int rowBit = 0; int colBit = 0; int diaBit = 0; int antiDiaBit = 0; int Nqueen_03_bits(int m, int n, int idx, int tnq, string ans) { if (tnq == 0) { cout << ans << endl; return 1; } int count = 0; for (int i = idx; i < m * n; i++) { int x = i / n; int y = i % n; if (!(rowBit & (1 << x)) && !(colBit & (1 << y)) && !(diaBit & (1 << (x - y + n - 1))) && !(antiDiaBit & (1 << (x + y)))) { rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + n - 1)); antiDiaBit ^= (1 << (x + y)); count += Nqueen_03_bits(m, n, i + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ") "); rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + n - 1)); antiDiaBit ^= (1 << (x + y)); } } return count; } int Nqueen_03_bits_sub(int m, int n, int idx, int tnq, string ans) { if (idx == m * n || tnq == 0) { if (tnq == 0) { return 1; } return 0; } int count = 0; int x = idx / n; int y = idx % n; if (!(rowBit & (1 << x)) && !(colBit & (1 << y)) && !(diaBit & (1 << (x - y + n - 1))) && !(antiDiaBit & (1 << (x + y)))) { rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + n - 1)); antiDiaBit ^= (1 << (x + y)); count += Nqueen_03_bits_sub(m, n, idx + 1, tnq - 1, ans + "(" + to_string(x) + "," + to_string(y) + ") "); rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + n - 1)); antiDiaBit ^= (1 << (x + y)); } count += Nqueen_03_bits_sub(m, n, idx + 1, tnq, ans); return count; } int Nqueen_04(int n, int m, int tnq, int r, string ans) // n means houses and m means rooms { //qpsf : queen place so far, tnq: total no of queen if (r == n || tnq == 0) { if (tnq == 0) { cout << ans << endl; return 1; } return 0; } int count = 0; for (int i = 0; i < m; i++) { int x = r; int y = i; if (!(rowBit & (1 << x)) && !(colBit & (1 << y)) && !(diaBit & (1 << (x - y + m - 1))) && !(antiDiaBit & (1 << (x + y)))) { rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + m - 1)); antiDiaBit ^= (1 << (x + y)); count += Nqueen_04(n, m, tnq - 1, r + 1, ans + "(" + to_string(x) + ", " + to_string(y) + ") "); rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + m - 1)); antiDiaBit ^= (1 << (x + y)); } } return count; } //!if the board size is greater than the queens int Nqueen_04_generic_sub(int n, int m, int tnq, int r, string ans) // n means houses and m means rooms { //qpsf : queen place so far, tnq: total no of queen if (r == n || tnq == 0) { if (tnq == 0) { cout << ans << endl; return 1; } return 0; } int count = 0; for (int i = 0; i < m; i++) { int x = r; int y = i; if (!(rowBit & (1 << x)) && !(colBit & (1 << y)) && !(diaBit & (1 << (x - y + m - 1))) && !(antiDiaBit & (1 << (x + y)))) { rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + m - 1)); antiDiaBit ^= (1 << (x + y)); count += Nqueen_04_generic_sub(n, m, tnq - 1, r + 1, ans + "(" + to_string(x) + ", " + to_string(y) + ") "); rowBit ^= (1 << x); colBit ^= (1 << y); diaBit ^= (1 << (x - y + m - 1)); antiDiaBit ^= (1 << (x + y)); } } count += Nqueen_04_generic_sub(n, m, tnq, r + 1, ans); return count; } void Nqueen() { vector<vector<bool>> boxes(4, vector<bool>(4, false)); // cout<<Nqueen_01(boxes,0,4,""); // int n = 6; // int m = 6; // rowA.resize(n, false); // colA.resize(m, false); // diag.resize(n + m - 1, false); // adiag.resize(n + m - 1, false); // cout<<Nqueen_02(4,4,0,4,""); // cout << Nqueen_03_bits(4, 4, 0, 4, ""); // cout << Nqueen_03_bits_sub(4, 4, 0, 4, ""); // cout << Nqueen_04(4, 4, 4, 0, "") << endl; cout << Nqueen_04_generic_sub(4, 4, 4, 0, "") << endl; } int main() { // queenSet(); Nqueen(); }
true
6abe7020dfbac42f233ebe30d8520b8dc9cfac5c
C++
IceCube-22/darkreign2
/coregame/damage.cpp
UTF-8
2,320
2.65625
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// // // Copyright 1997-1999 Pandemic Studios, Dark Reign II // // Firing system // /////////////////////////////////////////////////////////////////////////////// // // Includes // #include "damage.h" /////////////////////////////////////////////////////////////////////////////// // // NameSpace Damage // namespace Damage { /////////////////////////////////////////////////////////////////////////////// // // Class Type // // // Type::Type // Type::Type() : amount(InstanceModifierType::INTEGER) { } // // Type::Setup // void Type::Setup(const GameIdent &ident, FScope *fScope) { // Register this damage with the armour class system damageId = ArmourClass::RegisterDamage(ident); // Amount of damage // Keep within range of 16 bits so that 16:16 calculations don't overflow amount.LoadInteger(fScope->GetFunction("Amount"), 0, Range<S32>(0, 65535), 0.25F, 2.0F); // Get the effectiveness of this damage against armour classes FScope *sScope; while ((sScope = fScope->NextFunction()) != NULL) { switch (sScope->NameCrc()) { case 0x1831BFDA: // "Effective" { GameIdent armourClass = StdLoad::TypeString(sScope); F32 modifier = StdLoad::TypeF32(sScope, Range<F32>(0.0f, 1.0f)); ArmourClass::Define(damageId, armourClass, modifier); break; } default: break; } } // Load the instance modifiers if ((sScope = fScope->GetFunction("Modifiers", FALSE)) != NULL) { modifiers.Load(sScope); } } // // Get the amount of damage to a given armour class // S32 Type::GetAmount(U32 armourClass) const { return (amount.GetInteger() * ArmourClass::Lookup(damageId, armourClass) >> 16); } /////////////////////////////////////////////////////////////////////////////// // // Class Object // // // Constructor // Object::Object(Type &type) : type(type), amount(&type.amount) { } // // Get the amount of damage to a given armour class // S32 Object::GetAmount(U32 armourClass) const { return (FIXED_ROUND(16, amount.GetInteger() * ArmourClass::Lookup(type.damageId, armourClass))); } }
true
fc2dadccb6dc015d342b71ef1a4dac8436eaa7e4
C++
chenghu17/Algorithm
/Leetcode/c_104_Maximum_Depth_of_Binary_Tree.cpp
UTF-8
1,936
3.71875
4
[]
no_license
// // Created by Mr.Hu on 2018/12/8. // // leetcode 104 maximum depth of binary tree // // 题目要求求出给定二叉的树的深度,即二叉树所有路径中最长的路径。 // // 可以使用DFS的思想,每次计算一条路径的长度,判断当前路径长度与当前最长路径的大小,取最大值保存在为最长路径, // 直到最终遍历完所有路径,循环结束,输出此时最长路径即为二叉树深度 // // DFS的思想需要记住stack来存储之前的节点 // #include <iostream> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; class Solution { public: int maxDepth(TreeNode *root) { int max_depth = 0; int tmp_depth; stack<TreeNode *> cur_node; if (root != nullptr) { cur_node.push(root); tmp_depth = 1; } else { return max_depth; } while (!cur_node.empty()) { TreeNode *top = cur_node.top(); if (top->left != nullptr) { tmp_depth += 1; cur_node.push(top->left); top->left = nullptr; } else if (top->right != nullptr) { tmp_depth += 1; cur_node.push(top->right); top->right = nullptr; } else { max_depth = max(max_depth, tmp_depth); tmp_depth -= 1; cur_node.pop(); } } return max_depth; } }; int main() { TreeNode a(1); TreeNode b(2); TreeNode c(3); TreeNode d(4); TreeNode e(5); TreeNode f(6); a.left = &b; a.right = &c; b.right = &d; c.left = &e; e.left = &f; Solution solution; int max_depth = solution.maxDepth(&a); cout << "max depth = " << max_depth; return 0; }
true
5358631ef2209572712a84022d975f4f450672eb
C++
ZeroLRS/EGP-405-Project-3
/Plugin/include/egp-net/fw/egpNetSerializableData.h
UTF-8
851
2.59375
3
[]
no_license
/* egpNetSerializableData.h By Dan Buckstein (c) 2017-2018 Base class for some pure data or component that can serialize its data to a RakNet bitstream. Additional contributions by (and date): */ #ifndef __EGP_NET_SERIALIZABLEDATA_H_ #define __EGP_NET_SERIALIZABLEDATA_H_ #include "RakNet/BitStream.h" // serializable data class egpSerializableData { public: // serialize: defines how the data should be written to the bitstream // bs: pointer to bitstream // return number of bytes written virtual int Serialize(RakNet::BitStream *bs) const = 0; // deserialize: defines how the data should be read from the bitstream // bs: pointer to bitstream // return number of bytes read virtual int Deserialize(RakNet::BitStream *bs) = 0; // virtual dtor virtual ~egpSerializableData() {}; }; #endif // !__EGP_NET_SERIALIZABLEDATA_H_
true
fdec1c3ab7ce7ec226f54623157ec8ebe9822a01
C++
pbysu/BOJ
/~2017/1890.cpp
UTF-8
840
2.84375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; vector<vector<long long>> dp; int t; long long func(int r, int c, vector<vector<long long>>& count) { long long& ret = dp[r][c]; //dp 는 &ret 으로 배열 가져오기 : 정형화 if (ret != -1) return ret; //기저 조건 정형화 ret = 0; if (r == t - 1 && c == t - 1)return ret = 1; int temp = count[r][c]; if (temp == 0) return 0; if (c + temp < t) ret += func(r, c + temp, count); if (r + temp < t) ret += func(r+temp, c, count); return ret; } int main() { scanf("%d", &t); int temp; vector<vector<long long>> count(t, vector<long long>( t,0 )); dp.resize(t, vector<long long>(t, -1)); count[0][0] = 1; for (int i = 0; i < t; i++) { for (int k = 0; k < t; k++) { scanf("%d", &count[i][k]); } } printf("%lld", func(0,0,count)); return 0; }
true
6ee52d015a74b4e1f1e181472a9e78be08fc9699
C++
MrKarimiD/Shape-Detector-based-on-colors
/src/shape.cpp
UTF-8
273
2.640625
3
[]
no_license
#include "shape.h" Shape::Shape() { } void Shape::set(float x, float y, double roundedRadios, std::string color, std::string type) { this->position_x = x; this->position_y = y; this->roundedRadios=roundedRadios; this->color=color; this->type=type; }
true
41ef4c86ef28e7f9088553b399b03cc1d7e8215d
C++
afcarl/Stock-Performance-Evaluation-Based-on-EPS
/StockGroup.h
UTF-8
2,411
2.578125
3
[]
no_license
#pragma once #include "stdafx.h" #include <string> #include <iostream> #include <vector> #include <map> #include "Stock.h" #include <process.h> #include <Windows.h> #include <time.h> //#include <algorithm> class StockGroup { private: struct node { StockGroup* object; int num; }; HANDLE threads[3]; void(*pfun) (vector<stock>& stVec, map<string, stock>& stMap); map<string, stock> mpHigh; map<string, stock> mpMid; map<string, stock> mpLow; vector<stock> high; vector<stock> mid; vector<stock> low; vector<map<string, stock>> groups; int flag[3]; //double timebegin; bool sig; public: static unsigned int __stdcall procWork(void * lpParam) { node * pthis = (node *)lpParam; int mark = 0; switch (pthis->num) { case 0: pthis->object->pfun(pthis->object->high, pthis->object->mpHigh); mark = 1; break; case 1: pthis->object->pfun(pthis->object->mid, pthis->object->mpMid); mark = 1; break; case 2: pthis->object->pfun(pthis->object->low, pthis->object->mpLow); mark = 1; break; default: break; } pthis->object->flag[pthis->num] = 1; return pthis->num; } StockGroup(void(*pfun) (vector<stock>& stVec, map<string, stock>& stMap), vector<stock> &high, vector<stock> &low, vector<stock> &mid) { sig = true; flag[0] = 0; flag[1] = 0; flag[2] = 0; //timebegin = time(0); this->high = high; this->mid = mid; this->low = low; this->pfun = pfun; struct node *temp[3]; for (int i = 0; i <= 2; i++) { temp[i] = new node; temp[i]->num = i; temp[i]->object = this; } for (int i = 0; i <= 2; i++) { threads[i] = (HANDLE)_beginthreadex(NULL, 0, procWork, temp[i], 0, NULL); } } vector<map<string, stock>> GetResult() { while (1) //loop forever until break { int k = flag[0] + flag[1] + flag[2]; if (k == 3) { for (int i = 0; i <= 2; i++) { CloseHandle(threads[i]); threads[i] = NULL; } break; } } vector < map<string, stock>> groups; groups.push_back(mpLow); groups.push_back(mpMid); groups.push_back(mpHigh); return groups; } vector<stock> GetHigh() { return high; } vector<stock> GetMid() { return mid; } vector<stock> GetLow() { return low; } //double TimeCost(){ return (time(0) -timebegin) / 60.000;} };
true
46185520a5e696d867810b63ae35e07ba998b288
C++
dearinjani/Tugas-Algoritma-Pemrograman
/Pertemuan Ke 3,4,5/tanpaclass.cpp
UTF-8
748
3.796875
4
[]
no_license
#include <iostream> // Program Perhitungan Tanpa Class // I.S Program Mengolah Data // F.S Program Menampilkan Data using namespace std; // Prototype void print(int i); void print(double f); void print(string c); // Fungsi int menampilkan angka bilangan bulat void print(int i) { cout << "Printing int : " << i << endl;} // Fungsi double menampilkan angka bilangan pecahan void print(double f){ cout << "Printing float :" << f << endl;} // Fungsi string menampilkan karakter teks atau kalimat void print(string c){ cout << "Printing Character : " << c << endl;} // Rumus // Variable Data int main(void){ print(5); print(500.263); print("Hello C++"); // Akhir Program return 0; }
true
cafc87d44b14481abe99c0f64f8f1443571b0101
C++
oclero/luna
/include/luna/controls/Vector3dEditorTemplate.hpp
UTF-8
1,870
2.875
3
[ "MIT" ]
permissive
#pragma once #include <QQuickItem> #include <QVector3D> namespace luna::controls { /** * @brief Allows to edit the 3 values of a QVector3D. */ class Vector3dEditorTemplate : public QQuickItem { Q_OBJECT Q_PROPERTY(QVector3D value READ value WRITE setValue NOTIFY valueChanged) Q_PROPERTY(float x READ x WRITE setX NOTIFY xChanged) Q_PROPERTY(float y READ y WRITE setY NOTIFY yChanged) Q_PROPERTY(float z READ z WRITE setZ NOTIFY zChanged) Q_PROPERTY(float from READ from WRITE setFrom NOTIFY fromChanged) Q_PROPERTY(float to READ to WRITE setTo NOTIFY toChanged) Q_PROPERTY(float stepSize READ stepSize WRITE setStepSize NOTIFY stepSizeChanged) Q_PROPERTY(int decimals READ decimals WRITE setDecimals NOTIFY decimalsChanged) public: Vector3dEditorTemplate(QQuickItem* parent = nullptr); const QVector3D& value() const; void setValue(const QVector3D& value); Q_SIGNAL void valueChanged(); Q_SLOT void modifyValue(const QVector3D& value); Q_SIGNAL void valueModified(); float x() const; void setX(float x); Q_SIGNAL void xChanged(); Q_SLOT void modifyX(float x); Q_SIGNAL void xModified(); float y() const; void setY(float y); Q_SIGNAL void yChanged(); Q_SLOT void modifyY(float y); Q_SIGNAL void yModified(); float z() const; void setZ(float z); Q_SIGNAL void zChanged(); Q_SLOT void modifyZ(float z); Q_SIGNAL void zModified(); float from() const; void setFrom(float from); Q_SIGNAL void fromChanged(); float to() const; void setTo(float to); Q_SIGNAL void toChanged(); float stepSize() const; void setStepSize(float stepSize); Q_SIGNAL void stepSizeChanged(); int decimals() const; void setDecimals(int decimals); Q_SIGNAL void decimalsChanged(); private: QVector3D _value{ 0.f, 0.f, 0.f }; float _from{ 0.f }; float _to{ 1.f }; float _stepSize{ 0.1f }; int _decimals{ 3 }; }; } // namespace luna::controls
true
f7cbc38702695e9f754e75b61eb0fa015690bf29
C++
jjfsq1985/Algorithm
/Coding/rbTree.hpp
WINDOWS-1252
8,002
3
3
[]
no_license
//RB_Tree.hpp //The code of red black trees //2011/12/31 by Adoo // The foundation :http://www.roading.org/?p=691 #ifndef RB_TREES_HPP #define RB_TREES_HPP #include<iterator> #include<iomanip> #include<deque> enum RB_Color{ red, black }; template<typename Type> class RB_Tree{ private: struct rb_node; class node_iterator; public: typedef node_iterator iterator; typedef const node_iterator const_iterator; RB_Tree(){ _nil->_color=black; _root=_nil; }; ~RB_Tree() { for(iterator iter=begin(); iter !=end();) { eraser(iter++); } _root=_nil; } iterator begin(){ return sub_min(_root); } iterator end(){ return iterator(_nil); } static iterator sub_min(iterator iter){ rb_node *min=iter.pointer(); while(min->_left !=_nil) { min=min->_left; } return min; } iterator insert(Type value){ rb_node *y=_nil; rb_node *z=new rb_node; //create a node by the value //needn't set the z's color ,because red is rb_node's default color z->_value=value; z->_left=_nil; z->_right=_nil; rb_node* x=_root; //x iterator from _root while(x !=_nil ) { y=x; if(x->_value< z->_value) x=x->_right; else x=x->_left; } z->_parent=y; if(y==_nil) //determine z should be y's left or right _root=z; else if(y->_value < z->_value) y->_right=z; else y->_left=z; rb_insert_fixup(z); //restore the red black properties return z; } iterator eraser(iterator iter){ rb_node* z=iter.pointer(); rb_node* y=z; RB_Color y_color=y->_color; rb_node *x=NULL; if(z->_left==_nil ){ //case1: z's left child is nil x=z->_right; transplant(z, z->_right); } else{ if(z->_right==_nil){// case2: z's right child is nil x=z->_left; transplant(z, z->_left); } else{//case3: both children of z are not nil y=sub_min(z->_right).pointer(); y_color=y->_color; x=y->_right; if(y->_parent==z) x->_parent=y; else{ transplant(y, y->_right); //link z's right subtree into y, only y isn't z's child; y->_right=z->_right; y->_right->_parent=y; } transplant(z, y); //link z's subtree into y. y->_left=z->_left; y->_left->_parent=y; y->_color=z->_color; } } iterator result = ++iterator(z); delete z; if(y_color==black) eraser_fixup(x); return result; }; private: void transplant(rb_node *u, rb_node *v){ if(u->_parent == _nil) { _root=v; } else if(u== u->_parent->_left) u->_parent->_left=v; else u->_parent->_right=v; v->_parent=u->_parent; }; void left_rotate(rb_node *x){ rb_node* y=x->_right; //set y x->_right=y->_left; //turn y's left subtree into x's right subtree if(y->_left !=_nil) y->_left->_parent=x; y->_parent=x->_parent; //link y to x's parent if(x->_parent != _nil ) { if(x->_parent->_left==x) x->_parent->_left=y; else x->_parent->_right=y; } else _root=y; y->_left=x; //put x on y's left x->_parent=y; } void right_rotate(rb_node *x) { rb_node* y=x->_left; //set y; x->_left=y->_right; //turn y's right subtree into x's left subtree if(y->_right != _nil) y->_right->_parent=x; y->_parent=x->_parent; //link y to x's parent if(x->_parent != _nil) { if(x==x->_parent->_left) x->_parent->_left=y; else x->_parent->_right=y; } else _root=y; y->_right=x; //put x on y's right; x->_parent=y; } void rb_insert_fixup(rb_node* z){ while(z->_parent->_color==red){ if(z->_parent==z->_parent->_parent->_left){ rb_node* y=z->_parent->_parent->_right; if(y->_color==red){ z->_parent->_color=black; y->_color=black; z->_parent->_parent->_color=red; z=z->_parent->_parent; } else{ if(z==z->_parent->_right){ z=z->_parent; left_rotate(z); } z->_parent->_color=black; z->_parent->_parent->_color=red; right_rotate(z->_parent->_parent); } } else{ rb_node* y=z->_parent->_parent->_left; if(y->_color==red){ z->_parent->_color=black; y->_color=black; z->_parent->_parent->_color=red; z=z->_parent->_parent; } else{ if(z==z->_parent->_left){ z=z->_parent; right_rotate(z); } z->_parent->_color=black; z->_parent->_parent->_color=red; left_rotate(z->_parent->_parent); } } } _root->_color=black; };; void eraser_fixup(rb_node* x){ while(x != _root && x->_color ==black){ if(x==x->_parent->_left){ rb_node* w=x->_parent->_right; if(w->_color == red){ //case 1: x's sbling w is red. x->_parent->_color=red; w->_color=black; left_rotate(x->_parent); //convert case 1 to case 2. } else{//case 2 : x's sbling w is black. if(w->_left->_color == black && w->_right->_color == black){ //case 2.1 : both children of w are black w->_color=red; x=x->_parent; } else{ if(w->_left->_color==red && w->_right->_color==black){ //case 2.2: w's left child is red and w's right child is black. //we convert this case to case 2.3. w->_left->_color=black; w->_color=red; right_rotate(w); w=x->_parent->_right; } //case 2.3: w's right child is red; w->_color=x->_parent->_color; w->_parent->_color=black; w->_right->_color= black; left_rotate(x->_parent); x=_root; //terminate the loop; } } } else{ rb_node* w=x->_parent->_right; if(w->_color == red){ x->_parent->_color=red; w->_color=black; left_rotate(x->_parent); } else{ if(w->_right->_color == black && w->_left->_color == black){ w->_color=red; x=x->_parent; } else{ if(w->_right->_color==red && w->_left->_color == black){ w->_right->_color=black; w->_color=red; left_rotate(w); w=x->_parent->_left; } w->_color=x->_parent->_color; w->_parent->_color=black; w->_left->_color= black; right_rotate(x->_parent); x=_root; //terminate the loop; } } } } x->_color=black; }; private: rb_node* _root; public: static rb_node* _nil; }; template<typename Type> struct RB_Tree<Type>::rb_node { Type _value; rb_node *_left; rb_node *_right; rb_node *_parent; RB_Color _color; rb_node() :_value(Type()),_left(NULL),_right(NULL),_parent(NULL),_color(red) {}; }; template<typename Type> class RB_Tree<Type>::node_iterator: public std::iterator<std::bidirectional_iterator_tag ,rb_node> { public: node_iterator(rb_node* n): _node(n){}; Type& operator* () const{ return _node->_value; }; rb_node* operator ->()const { return _node; }; node_iterator operator++ () { if(_node==RB_Tree<Type>::_nil) return _node; if(_node->_right!=RB_Tree<Type>::_nil) { *this=RB_Tree<Type>::sub_min(_node->_right); } else { rb_node *parent=_node->_parent; while(parent !=RB_Tree<Type>::_nil&& _node==parent->_right) { _node=parent; parent=parent->_parent; } _node=parent; } return *this; } node_iterator operator++(int){ node_iterator ret(*this); ++*this; return ret; } bool operator ==( node_iterator r_iter) { return _node == r_iter._node; }; bool operator !=( node_iterator r_iter){ return _node != r_iter._node; } rb_node* pointer() { return _node; } private: rb_node* _node; }; #endif //
true
edc25f9c78e71b3d0f3cf0110c7e245a1f6a7537
C++
AmonShokhinAhmed/KDTree
/KDTree/KDTree/ControlledCamera.cpp
UTF-8
1,229
2.53125
3
[ "MIT" ]
permissive
#include "ControlledCamera.h" #include "InputManager.h" #include "Entity.h" ControlledCamera::ControlledCamera() { SystemManager::CameraSystem.AddComponent(this); } ControlledCamera::~ControlledCamera() { SystemManager::CameraSystem.RemoveComponent(this); } void ControlledCamera::Update() { float velocity = MovementSpeed * InputManager::DeltaTime(); if (InputManager::WIsDown()) _owner->transform.Position += WorldFront*_owner->transform.Rotation * velocity; if (InputManager::AIsDown()) _owner->transform.Position += WorldRight * _owner->transform.Rotation * velocity; if (InputManager::SIsDown()) _owner->transform.Position -= WorldFront * _owner->transform.Rotation * velocity; if (InputManager::DIsDown()) _owner->transform.Position -= WorldRight * _owner->transform.Rotation * velocity; _owner->transform.Rotation *= glm::angleAxis(InputManager::DeltaMouseX() * MouseSensitivity, WorldUp); _owner->transform.Rotation = glm::angleAxis(InputManager::DeltaMouseY() * MouseSensitivity, WorldRight) * _owner->transform.Rotation; Zoom -= InputManager::DeltaScrollY(); if (Zoom < 1.0f) Zoom = 1.0f; if (Zoom > 45.0f) Zoom = 45.0f; }
true
6763a3dde27da9cb2dded7197d4b0d2b14ff9a1d
C++
Shaharafat/My-C-plus-plus-Codes
/new and delete2.cpp
UTF-8
264
2.875
3
[]
no_license
#include<iostream> using namespace std; struct Courseinfo { char *id; int credit; float gpa; Courseinfo *next; }; int main() { Courseinfo *course; course=new Courseinfo; course->credit=3; cout<<course->credit; delete course; }
true
546c81bb1d0d6005f9f205450676af37937ce7bc
C++
faterer/cpm
/cpp/DesignPatterns/CreationalPatterns/Singleton00.cpp
UTF-8
436
3.296875
3
[]
no_license
#include <iostream> class Singleton { public: static Singleton * getInstance() { if (instance == nullptr) { instance = new Singleton(); } return instance; } void print() { std::cout << "singleton" << std::endl; } private: Singleton() {} static Singleton *instance; }; Singleton* Singleton::instance = nullptr; int main() { Singleton::getInstance()->print(); }
true
6205306e97526fdf8e6404006f98e9ded921c1ca
C++
bashirtamim/C-
/Typing game/abdullah2.cpp
UTF-8
4,142
3.1875
3
[]
no_license
//Bashir Abdullah //typing game #include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> #include<math.h> #include<chrono> #include<ctime> typedef struct str{ char string[100]; }; str generateString() { srand(time(NULL)); str string; //strcpy_s(string.string, "Hi"); static const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 7; ++i) { int random_chance = rand() % 10; //20% chance of wild card if (random_chance == 0) { string.string[i] = '0'; } else if (random_chance == 1) { string.string[i] = '*'; } else { string.string[i] = alphanum[rand() % (sizeof(alphanum)-1)]; } } string.string[7] = 0; //strcpy_s(string.string, "Game"); return string; } int get_offset(str string1, str string2) { //check max length int max_length = 0; if (sizeof(string1.string) < sizeof(string2.string)) max_length = sizeof(string1.string); else max_length = sizeof(string2.string); int offset = 0; for (int i = 0; i < sizeof(max_length); i++) { //pad with space if (string1.string[i] == 0) string1.string[i] = ' '; if (string2.string[i] == 0) string2.string[i] = ' '; //calculate offset if (string1.string[i] == '0') { if (!isdigit(string2.string[i])) offset += abs(string1.string[i] - string2.string[i]); } else if (string1.string[i] == '*') { if (isalnum(string2.string[i])) offset += abs(string1.string[i] - string2.string[i]); } else offset += abs(string1.string[i] - string2.string[i]); } return offset; } str translate_wildcard(str string) { str new_string; int j = 0; for (int i = 0; i < 7; i++) { if (string.string[i] == '0') { new_string.string[j] = '['; new_string.string[++j] = '0'; new_string.string[++j] = '-'; new_string.string[++j] = '9'; new_string.string[++j] = ']'; } else if (string.string[i] == '*') { new_string.string[j] = '['; new_string.string[++j] = '%'; new_string.string[++j] = '-'; new_string.string[++j] = '&'; new_string.string[++j] = ']'; } else new_string.string[j] = string.string[i]; j++; } new_string.string[j] = 0; return new_string; } int main() { str string, question; int score = 1000; int time_limit = 7000; while (true) { //save current time std::chrono::steady_clock::time_point c_start = std::chrono::steady_clock::now(); question = generateString(); std::cout << "Your current points " << score << ", just type -> " << translate_wildcard(question).string << ": "; std::cin >> (string.string); //save end time std::chrono::steady_clock::time_point c_end = std::chrono::steady_clock::now(); int offset = get_offset(question, string); //calculate time int elapsed_time = std::chrono::duration_cast<std::chrono::microseconds>(c_end - c_start).count()/1000; std::cout << elapsed_time << " milliseconds"; //if the string is correct if (offset == 0) { //if within time frame if (elapsed_time <= time_limit) { std::cout << ", you made it within the interval of 7000...\n"; score += 500; } else { std::cout << ", you *failed* it within the interval of 7000...\n" << "Your total penalty is " << elapsed_time - time_limit << "...\n"; score -= (elapsed_time - time_limit); } } else { int time_penalty = 0; int offset_penalty = 0; //if within time frame if (elapsed_time <= time_limit) { std::cout << ", you made it within the interval of 7000...\n"; offset_penalty = offset; } else { std::cout << ", you *failed* it within the interval of 7000...\n"; time_penalty = (elapsed_time - time_limit); offset_penalty = offset * 2; } score -= (time_penalty + offset_penalty); std::cout << "String offset is " << offset << ", your total penalty is " << time_penalty + offset_penalty << "...\n"; } //calculate end game if (score <= 0) { std::cout << "Bye...\n"; std::cin >> (string.string); break; } else if (score >= 5000) { std::cout << "You Win! Bye...\n"; std::cin >> (string.string); break; } } return 0; }
true
e2de9732f3eb3505d0d7a6852dce64dbc63d66aa
C++
soapunny/Strikers1945
/210317_WinAPI/Timer.cpp
UHC
1,252
2.96875
3
[]
no_license
#include "Timer.h" HRESULT Timer::init() { isHardware = false; timeScale = 0.0f; timeElapsed = 0.0f; currTime = 0.0; lastTime = 0.0; periodFrequency = 0.0; fpsTimeElapsed = 0.0f; fpsFrameCount = 0; gameSecond = 0; if (QueryPerformanceFrequency((LARGE_INTEGER*)&periodFrequency)) // cpu ʴ ޾ ִ { isHardware = true; QueryPerformanceCounter((LARGE_INTEGER*)&lastTime); // timeScale = 1.0f / periodFrequency; // (1 / cpu ʴ ) (1/10 ..) } else { isHardware = false; lastTime = timeGetTime(); timeScale = 0.001f; } return S_OK; } void Timer::Tick() { // or ð ؼ ð if(isHardware) { QueryPerformanceCounter((LARGE_INTEGER*)&currTime); } else { currTime = timeGetTime(); } timeElapsed = (currTime - lastTime) * timeScale; // ð ((6-3)*(1/10) ..) // fpsTimeElapsed += timeElapsed; fpsFrameCount++; if (fpsTimeElapsed >= 1.0f) { gameSecond += 1; FPS = fpsFrameCount; fpsFrameCount = 0.0f; fpsTimeElapsed -= 1.0f; } lastTime = currTime; //timeElapsed ϴ }
true
9553417ea6c7074018e5fec42f9021e701cad1ef
C++
adrian-stanciu/adventofcode
/2015/23/main.cpp
UTF-8
3,597
2.796875
3
[ "MIT" ]
permissive
#include <array> #include <iostream> #include <optional> #include <regex> #include <string> #include <variant> #include <vector> using Regs = std::array<long, 2>; struct Computer; struct Hlf { long r; void exec(Computer& c) const; }; struct Tpl { long r; void exec(Computer& c) const; }; struct Inc { long r; void exec(Computer& c) const; }; struct Jmp { long off; void exec(Computer& c) const; }; struct Jie { long r; long off; void exec(Computer& c) const; }; struct Jio { long r; long off; void exec(Computer& c) const; }; using Instr = std::variant<Hlf, Tpl, Inc, Jmp, Jie, Jio>; std::optional<Instr> decode(const std::string& instr) { static const std::regex hlf_re{"hlf ([a-b])"}; static const std::regex tpl_re{"tpl ([a-b])"}; static const std::regex inc_re{"inc ([a-b])"}; static const std::regex jmp_re{"jmp ([+-])([0-9]+)"}; static const std::regex jie_re{"jie ([a-b]), ([+-])([0-9]+)"}; static const std::regex jio_re{"jio ([a-b]), ([+-])([0-9]+)"}; auto to_reg = [] (char r) { return r - 'a'; }; auto to_num = [] (char sign, const std::string& value) { return strtol(value.data(), nullptr, 10) * (sign == '-' ? -1 : 1); }; std::smatch matched; if (regex_match(instr, matched, hlf_re)) return Hlf{to_reg(matched[1].str()[0])}; else if (regex_match(instr, matched, tpl_re)) return Tpl{to_reg(matched[1].str()[0])}; else if (regex_match(instr, matched, inc_re)) return Inc{to_reg(matched[1].str()[0])}; else if (regex_match(instr, matched, jmp_re)) return Jmp{to_num(matched[1].str()[0], matched[2].str())}; else if (regex_match(instr, matched, jie_re)) return Jie{to_reg(matched[1].str()[0]), to_num(matched[2].str()[0], matched[3].str())}; else if (regex_match(instr, matched, jio_re)) return Jio{to_reg(matched[1].str()[0]), to_num(matched[2].str()[0], matched[3].str())}; return std::nullopt; } struct Computer { unsigned long ip{0}; Regs regs{}; std::vector<Instr> prog; Computer(const std::vector<std::string>& instructions) { for (const auto& instr : instructions) { auto decoded_instr = decode(instr); if (decoded_instr.has_value()) prog.push_back(std::move(decoded_instr.value())); } } void reset() { ip = 0; regs.fill(0); } auto get_reg(char r) const { return regs[r - 'a']; } void set_reg(char r, long value) { regs[r - 'a'] = value; } void run() { while (ip < prog.size()) visit([&] (const auto& _) { _.exec(*this); }, prog[ip]); } }; void Hlf::exec(Computer& c) const { c.regs[r] /= 2; ++c.ip; } void Tpl::exec(Computer& c) const { c.regs[r] *= 3; ++c.ip; } void Inc::exec(Computer& c) const { ++c.regs[r]; ++c.ip; } void Jmp::exec(Computer& c) const { c.ip += off; } void Jie::exec(Computer& c) const { if (c.regs[r] % 2 == 0) c.ip += off; else ++c.ip; } void Jio::exec(Computer& c) const { if (c.regs[r] == 1) c.ip += off; else ++c.ip; } int main() { std::vector<std::string> instructions; std::string line; while (getline(std::cin, line)) instructions.push_back(std::move(line)); Computer c{instructions}; c.run(); std::cout << c.get_reg('b') << "\n"; c.reset(); c.set_reg('a', 1); c.run(); std::cout << c.get_reg('b') << "\n"; return 0; }
true
f448c05e158664706af7359561cbcadbe0acfd19
C++
jackthgu/K-AR_HYU_Deform_Simulation
/src/taesooLib/BaseLib/math/optimize.h
UTF-8
9,751
2.890625
3
[ "MIT" ]
permissive
#ifndef _OPTIMIZE_H_ #define _OPTIMIZE_H_ #if _MSC_VER>1000 #pragma once #endif #include "OperatorStitch.h" class Optimize { public: struct Opt_dimension { TString title; double curval; double max_step; double grad_step; }; class Method { public: vectorn _opos; Method(); virtual ~Method(); virtual vectorn& getInout(){ return _x;} // implement optimize function using the following two functions. double func(const vectorn& x); double func_dfunc(const vectorn& x,vectorn& dx); protected: void prepareOptimization(Optimize& objectiveFunction); virtual void optimize(vectorn & initial )=0; void finalizeOptimization(); friend class Optimize_impl; private: vectorn _x, _gradient; Optimize* _optimizer; double _oeval; void _getCurPos(vectorn &opos); void _normalize(vectorn& pos, vectorn const& opos); void _unnormalize(vectorn& opos, vectorn const& pos); }; class ConjugateGradient: public Method { public: double tol, thr; int max_iter; // tol is tolerence for termination, thr is tolerence for linmin. ConjugateGradient(){max_iter=200, tol=0.001, thr=0.01;} ConjugateGradient(int maxiter){max_iter=maxiter, tol=0.001, thr=0.01;} protected: virtual void optimize(vectorn & initial); }; // a reference to the method object is stored, so do not delete the method object until optimization finishes. Optimize(); void init(double stepSize, int ndim, double max_step, double grad_step, Method & method); Optimize(double stepSize, std::vector<Opt_dimension> const& dim, Method & method); Optimize(double stepSize, int ndim, double max_step, double grad_step, Method & method); virtual ~Optimize(); virtual double objectiveFunction(vectorn const& pos)=0; virtual double gradientFunction(vectorn const& _pos, vectorn& gradient); void optimize(vectorn const& initialSolution); vectorn& getResult(); private: friend class Method; void* _data; std::vector<Opt_dimension> _opt_dimension; }; // IndexMapping can be many-to-one, or one-to-one mapping // :: sizeRange should be smaller than or equal to sizeDomain // in case of many-to-one mapping, inverseMapping stores only the first index. // one-to-many mapping is also supported since inverse of one-to-many mapping is many-to-one mapping. class IndexMapping { public: intvectorn mapping; intvectorn inverseMapping; IndexMapping(int max=0){init(max);} // sizeRange should be smaller than or equal to sizeDomain void init(int sizeDomain, int sizeRange=INT_MAX) { mapping.setSize(sizeDomain); if(sizeRange>sizeDomain) sizeRange=sizeDomain; inverseMapping.setSize(sizeRange); mapping.setAllValue(-1); // denotes no mapping inverseMapping.setAllValue(-1); } int size() const {return mapping.size();} int sizeRange() const { return inverseMapping.size();} // set mapping such that map(i)==j void map(int i, int j) { ASSERT(mapping(i)==-1 || mapping(i)==j); mapping(i)=j; ASSERT(j>=0 && j< sizeRange()); //if(inverseMapping(j)==-1 || inverseMapping(j)>i); inverseMapping(j)=i; } int operator()(int i) const { return mapping(i);} void operator()(intvectorn const& domain, intvectorn & range) const { range.reserve(domain.size()); range.setSize(0); for(int i=0; i<domain.size(); i++) { int r=mapping(domain(i)); if(r!=-1 && range.findFirstIndex(r)==-1) range.pushBack(r); } } int inverse(int j) const { return inverseMapping(j);} }; // analytic constrained SQP solver // - template argument baseSolver는 // QuadraticFunction, SparseQuadraticFunction, // QuadraticFunctionHardConm, SparseQuadraticFunctionHardCon등이 사용될 수 있다. // QuadraticFunctionHardCon이나 SparseQuadraticFunctionHardCon과는 달리 // equality constraint를 예외처리해서 실제 최적화과정에 사용되는 변수 개수를 줄인다. // 사용법: QuadraticFunctionHardCon 이나 SparseQuadraticFunctionHardCon과 동일하지만, // 항상 모든 addCon이 addSquared나 addSquaredWeighted보다 먼저 수행되어야한다. template <class baseSolver> class ConstrainedSQPsolver { int mNumVar; int mNumCon; bitvectorn mEqCon; intvectorn mEqConIndex; vectorn mEqConValue; baseSolver* mSolver; IndexMapping toReorderedIndex; int mCurCon; public: ConstrainedSQPsolver(int numVar, int numCon, int numCon2=0):mNumVar(numVar), mNumCon(numCon) { Msg::verify(numCon2==0, "linear equality constraints are not supported in this class yet - use sparseQuadraticFunctionHardCon instead."); mSolver=NULL; mEqCon.resize(numVar); mEqConIndex.setSize(numCon); mEqConValue.setSize(numCon); mCurCon=0; } virtual ~ConstrainedSQPsolver(){ delete mSolver;} void addCon(int n, m_real coef1, int index1, ...) { Msg::verify(n==1, "linear combination constraints are not supported in this class yet - use sparseQuadraticFunctionHardCon instead."); m_real coef2; va_list marker; va_start( marker, index1); coef2=va_arg(marker, m_real); va_end(marker); mEqConIndex[mCurCon]=index1; mEqConValue[mCurCon]=-1.0*coef2/coef1; // ax+b=0 -> x=-b/a ASSERT(!mEqCon[index1]); mEqCon.setAt(index1); mCurCon++; if(mCurCon==mNumCon) { // index map을 구성한다. toReorderedIndex.init(mNumVar, mNumVar-mNumCon); int reorderedIndex=0; for(int i=0; i<mNumVar; i++) { if(mEqCon[i]) toReorderedIndex.map(i, mEqConIndex.findFirstIndex(i)); else { toReorderedIndex.map(i, reorderedIndex); reorderedIndex++; } } mSolver=new baseSolver(mNumVar-mNumCon); } } // 4*(3x+4y+5z+1)^2 를 추가하고 싶으면, addSquaredWeighted(4.0, 3, 3.0, x, 4.0, y, 5.0, z, 1.0); where x=0, y=1, z=2 void addSquaredWeighted(m_real weight, int N, ...) { ASSERT(toReorderedIndex.size()); QuadraticFunction::SquaredTerm* term=new QuadraticFunction::SquaredTerm; term->index.reserve(N); term->coef.reserve(N+1); va_list marker; va_start( marker, N); /* Initialize variable arguments. */ m_real constants=0.0; term->index.setSize(0); term->coef.setSize(0); int i; for(i=0; i<N; i++) { m_real coef=va_arg(marker, m_real); m_real index=va_arg(marker, int); if(mEqCon[index]) constants+=coef*mEqConValue[toReorderedIndex(index)]; else { term->coef.pushBack(coef); term->index.push_back(toReorderedIndex(index)); } } term->coef.pushBack(va_arg(marker, m_real)+constants); va_end(marker); term->coef*=sqrt(weight); if(term->index.size()) mSolver->mListSQTerms.push_back(term); } // (3x+4y+5z+1)^2 을 추가하고 싶으면, addSquared(3, 3.0, x, 4.0, y, 5.0, z, 1.0); where x=0, y=1, z=2 void addSquared(int N, m_real coef1, int index1, ...) { QuadraticFunction::SquaredTerm* term=new QuadraticFunction::SquaredTerm; term->index.reserve(N); term->coef.reserve(N+1); va_list marker; va_start( marker, N); /* Initialize variable arguments. */ m_real constants=0.0; term->index.setSize(0); term->coef.setSize(0); int i; for(i=0; i<N; i++) { m_real coef=va_arg(marker, m_real); m_real index=va_arg(marker, int); if(mEqCon[index]) constants+=coef*mEqConValue[toReorderedIndex(index)]; else { term->coef.pushBack(coef); term->index.push_back(toReorderedIndex(index)); } } term->coef.pushBack(va_arg(marker, m_real)+constants); va_end(marker); mSolver->mListSQTerms.push_back(term); } template <class MAT_TYPE> void buildSystem(MAT_TYPE & A, vectorn &b) { mSolver->buildSystem(A, b); } template <class MAT_TYPE> void solve(MAT_TYPE const& A, vectorn const& b, vectorn & x2) { vectorn x; mSolver->solve(A,b,x); x2.setSize(mNumVar); for(int i=0; i<mNumVar; i++) { if(mEqCon[i]) x2[i]=mEqConValue[toReorderedIndex(i)]; else x2[i]=x[toReorderedIndex(i)]; } } }; namespace _NRSolver { // non-thread-safe extern void* mFunc; } // do not need to inherit this class. Just to demonstrate the interface. class FuncAbstractClass { public: // return value should contain the initial solution. vectorn& getInout(){} inline m_real func(vectorn const& x){} inline void dfunc(vectorn const& x, vectorn& dx){} }; // minimization of Func (conjugate gradient and gradient descent solvers are supported.) // There also exists GSLsolver which has exactly the same interface with a lot more options.) // usage: // NRSolver<functionType> solver(pfunction); // solver.conjugateGradientSolve(); template <class Func> // Func should have three functions: getInout, func, dfunc // vectorn& getInout() // m_real func(vectorn const& x) // void dfunc(vectorn const& x, vectorn& dx) class NRSolver { public: NRSolver(Func* function) { _NRSolver::mFunc=(void*)function; } void conjugateGradientSolve( m_real tolerance=1.0e-6) { vectorn& x=((Func*)_NRSolver::mFunc)->getInout(); Msg::error("cgsolve"); /* int iter; DP fret; NR::frprmn(x, tolerance, iter, fret, func, dfunc); */ } void gradientDescentSolve( m_real ftol=1.0e-6) { int iter; double fret; vectorn& x=((Func*)_NRSolver::mFunc)->getInout(); ASSERT(0); // NR_OLD::gradient_descent(x, x.size(), ftol, iter, fret, func, dfunc); } /* static DP func(Vec_I_DP & x) { return ((Func*)_NRSolver::mFunc)->func(x); } static void dfunc(Vec_I_DP &x, Vec_O_DP &dx) { ((Func*)_NRSolver::mFunc)->dfunc(x, dx); } */ }; // deprecated.. namespace NR_OLD { void mnbrak(m_real&, m_real&, m_real&, m_real&, m_real&, m_real&, m_real (*func)(m_real)) ; m_real brent(m_real, m_real, m_real, m_real (*f)(m_real), m_real, m_real&) ; void frprmn(vectorn&, int, m_real, int&, m_real&, m_real (*func)(vectorn const&), m_real (*dfunc)(vectorn const&, vectorn&)); void error( char* ); } #endif
true
feffeb2660bf40d9bdb393ca3c25513d50200338
C++
a-kashirin-official/spbspu-labs-2018
/dudina.anna/A2/main.cpp
UTF-8
2,214
3.21875
3
[]
no_license
#include <iostream> #include "circle.hpp" #include "rectangle.hpp" #include "triangle.hpp" void testOfShape(dudina::Shape & cObject) { std::cout << "Shape test:" << std::endl; cObject.printInformation(); std::cout << "Area of figure:" << cObject.getArea() << std::endl; std::cout << "Rectangle frame:" << std::endl; std::cout << " Center: {" << cObject.getFrameRect().pos.x << ";" << cObject.getFrameRect().pos.y << "}" << std::endl; std::cout << " Width:" << cObject.getFrameRect().width << std::endl; std::cout << " Height:" << cObject.getFrameRect().height << std::endl; cObject.move({ 5,2 }); std::cout << "After move to {5,2}:" << std::endl; std::cout << "Rectangle frame:" << std::endl; std::cout << " Center: {" << cObject.getFrameRect().pos.x << ";" << cObject.getFrameRect().pos.y << "}" << std::endl; std::cout << " Width:" << cObject.getFrameRect().width << std::endl; std::cout << " Height:" << cObject.getFrameRect().height << std::endl; cObject.move(5, 2); std::cout << "After move on x=5 and y=2:" << std::endl; std::cout << "Rectangle frame:" << std::endl; std::cout << " Center: {" << cObject.getFrameRect().pos.x << ";" << cObject.getFrameRect().pos.y << "}" << std::endl; std::cout << " Width:" << cObject.getFrameRect().width << std::endl; std::cout << " Height:" << cObject.getFrameRect().height << std::endl; cObject.scale(2); std::cout << "After scale:" << std::endl; std::cout << "Area after scale:" << cObject.getArea() << std::endl; std::cout << "Rectangle frame:" << std::endl; std::cout << " Center: {" << cObject.getFrameRect().pos.x << ";" << cObject.getFrameRect().pos.y << "}" << std::endl; std::cout << " Width:" << cObject.getFrameRect().width << std::endl; std::cout << " Height:" << cObject.getFrameRect().height << std::endl; } int main() { try { dudina::Rectangle rect({ 2.0, 3.0 }, 4, 5); dudina::Circle circl({ 2.0, 3.0 }, 4); dudina::Triangle triangl({ 0.0, 0.0 }, { 2.0, 4.0 }, { 4.0, 0.0 }); testOfShape(rect); testOfShape(circl); testOfShape(triangl); } catch (const std::invalid_argument & e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
true
add60c7a40ffd8adcd3c4eb331d51f600750958f
C++
shehryarnaeem/SamplePrograms
/HackerRank/SaveThePrisoner.cpp
UTF-8
688
2.890625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; /*int saveThePrisoner(int n, int m, int s){ // Complete this functions if(m>s) { int diff=n-s; ++diff; int r=m-diff; return r; } else{ int diff=(m-1)+s; if(diff>5) { diff=diff-5; } return diff; } }*/ int saveThePrisoner(int n, int m, int s){ // Complete this functions for } int main() { int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; int m; int s; cin >> n >> m >> s; int result = saveThePrisoner(n, m, s); cout << result << endl; } return 0; }
true
8da87ff7b3336528d8b0bb264ea29afd79555c65
C++
Dindaaprlia/Ini_Contoh_UAS
/main.cpp
UTF-8
724
3.609375
4
[]
no_license
#include <iostream> using namespace std; int main() { int array1[2], array2[2], array3[2]; int a; for (a=0; a<2; a++) { cout << "\nMasukkan array 1 indeks ke-" << a << ": "; cin >> array1[a]; } for (a=0; a<2; a++) { cout << "\nMasukkan array 2 indeks ke-" << a << ": "; cin >> array2[a]; } cout << "\nArray 1:\n"; for (a=0; a<2; a++) { cout << array1[a] << "\n"; } cout << "\nArray 2:\n"; for (a=0; a<2; a++) { cout << array2[a] << "\n"; } cout << "\nAray 1 + Array 2\n"; for (a=0; a<2; a++) { array3[a] = array1[a]+array2[a] cout << array3[a] << "\n"; } }
true
b009c4a95b8307df194f33d6fe3446b8cc3011e0
C++
jhonber/Programming-Contest
/codeforces/VK Cup 2016 - Round 1/A.cpp
UTF-8
765
2.59375
3
[]
no_license
// http://codeforces.com/contest/639/problem/A #include<bits/stdc++.h> using namespace std; #define D(x) cout << #x << " = " << (x) << endl; int main() { int n, k, q; cin >> n >> k >> q; map<int, int> all; for (int i = 0 ; i < n; ++i) { int a; cin >> a; all[i + 1] = a; } set<int> online; for (int i = 0; i < q; ++i) { int a, b; cin >> a >> b; if (a == 1) { if (online.size() < k) online.insert(all[b]); else { set<int> :: iterator it = online.begin(); if (*it < all[b]) { online.erase(it); online.insert(all[b]); } } } else { if (online.count(all[b]) > 0) cout << "YES" << endl; else cout << "NO" << endl; } } return 0; }
true
1da2b0b973f850439d9e70dea3f4ea54cd1d1a37
C++
RabbitThief/SerialPortMon
/Common/MultimediaTimer.h
UHC
533
2.546875
3
[]
no_license
// Multimedia timer ϱ Լ #pragma once #pragma comment (lib,"winmm.lib") typedef unsigned long DWORD; typedef unsigned int UINT; class CMultimediaTimer { private: UINT _timerRes; DWORD _timerId; public: CMultimediaTimer (); ~CMultimediaTimer (); virtual void OnTimer (UINT timerId, UINT msg) { } void Start (UINT executionPeriod); void Stop (); bool IsRunning () { return _timerId != -1; } static DWORD GetTime (); static void Sleep (DWORD ms); public: UINT _period; // ms };
true
a40613b0cabb3fd46be976f6d564882397a8e23b
C++
evan-carey/raytracer
/Raytracer/Material.cpp
UTF-8
723
2.8125
3
[]
no_license
#include "Material.h" Material::Material() { m_diffuse = Vector3(1.0f); m_specular = Vector3(0.0f); m_transparency = Vector3(0.0f); m_shininess = 0.0f; m_refractionIndex = 1.0f; m_texture = NULL; } Material::~Material() { delete m_texture; } bool Material::isDiffuse() const { return m_diffuse.x > 0.0f || m_diffuse.y > 0.0f || m_diffuse.z > 0.0f; } bool Material::isSpecular() const { return m_specular.x > 0.0f || m_specular.y > 0.0f || m_specular.z > 0.0f; } bool Material::isTransparent() const { return m_transparency.x > 0.0f || m_transparency.y > 0.0f || m_transparency.z > 0.0f; } Vector3 Material::shade(const Ray&, const HitInfo&, const Scene&) const { return Vector3(1.0f, 1.0f, 1.0f); }
true
16b95f13acf84afa94faa1e6e239eb72f5d4b217
C++
mjannat/Online-Judge-Problems-Solution-in-Cpp
/Cook a Dish.cpp
UTF-8
730
2.625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef long long ll; int result[1000] = {0}; void fact_dp() { result[0] = 1; for (int i = 1; i <= 11; ++i) { result[i] = i * result[i - 1]; } } int main() { int test; cin >> test; fact_dp(); while(test--) { string str; ll r,cnt = 0; cin >> str >> r; ll temp = str.size(); for(int i = 0 ; i < str.size(); i++)if(str[i] == '0')cnt++; ll val = result[temp]/(result[temp-r]); if(cnt != 0) { temp--; r--; cout << val - result[temp]/(result[temp-r]) << endl; } else cout << val << endl; } }
true
9d739c49e7904d0f9c9f742484caed30b3d0fab7
C++
obikata/Space_Partitioning_Octree_BVH
/CppSpacePartitioning/src/include/OctreeBuilder.hpp
UTF-8
9,400
2.640625
3
[]
no_license
#include "Octree.hpp" #include "OctreeNode.hpp" #include "OBJ_File.hpp" #include "Vec3.hpp" #include <iostream> #include <chrono> #include <string> namespace Octree { class OctreeBuilder { // public static float OCTANT_POS[][] = // { // //i&4, i&2, i&1 // { 0, 0, 0 }, // [0] - 000 // { 0, 0, 1 }, // [1] - 001 // { 0, 1, 0 }, // [2] - 010 // { 0, 1, 1 }, // [3] - 011 // // { 1, 0, 0 }, // [4] - 100 // { 1, 0, 1 }, // [5] - 101 // { 1, 1, 0 }, // [6] - 110 // { 1, 1, 1 }, // [7] - 111 // }; private: Octree octree; OctreeNode root; OBJ_File obj; Vec3 vector3; bool assureChilds(OctreeNode ot, int max_depth) { if( ot.depth >= max_depth) { return false; } if( ot.isLeaf() ) { ot.childs = new OctreeNode[8]; float* half_size = ot.aabb.getHalfSize(); int child_depth = ot.depth+1; for(int i = 0; i < ot.childs.length; i++) { // float[] ch_bb_min = DwVec3.add_new(ot.aabb.min, DwVec3.multiply_new(half_size, OCTANT_POS[i])); float ch_bb_min[3] = { ot.aabb.min[0] + (((i&4)>0)?half_size[0]:0), ot.aabb.min[1] + (((i&2)>0)?half_size[1]:0), ot.aabb.min[2] + (((i&1)>0)?half_size[2]:0) }; float ch_bb_max[3] = vector3.add_new(ch_bb_min, half_size); ot.childs[i] = new OctreeNode(child_depth, new AABB(ch_bb_min, ch_bb_max)); } } return true; } bool saveTriangleToNode(OctreeNode ot, int idx) { if( !ot.IDX_triangles.contains(idx)) { // just in case ot.IDX_triangles.add(idx); } return true; } public: // most important value, small values makes deep trees, especially for big scenes!! float MIN_DEPTH_FILL_RATIO = 1.5f; int MAX_DEPTH = 10; OctreeBuilder(Octree octree) { this->octree = octree; this->root = octree.root; this->obj = octree.obj; } static std::string toStr(double a, int prec) { std::ostringstream text; text.precision(prec); text << std::fixed << a; return text.str(); } void BUILD_defaultRoutine() { std::chrono::system_clock::time_point start, timer; // auto start, end; double elapsed; std::string txt_time; std::cout << " > start building" << std::endl; start = std::chrono::system_clock::now(); for(int i = 0; i < obj.f.length; i++) { if( obj.f[i].isDegenerate()) { continue; } storeAtFirstFit(root, i); } timer = std::chrono::system_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timer-start).count(); txt_time = toStr(elapsed, 3); std::cout < " 1) storeAtFirstFit (" + txt_time + ") stored items: " + octree.getNumberOfStoredItems() << std::endl; timer = std::chrono::system_clock::now(); pushToLeafes(root); elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timer-start).count(); std::cout < " 2) pushToLeafes (" + txt_time + ") stored items: " + octree.getNumberOfStoredItems() < std::endl; timer = std::chrono::system_clock::now(); optimizeSpaceCost(root); elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timer-start).count(); std::cout < " 3) optimizeSpaceCost (" + txt_time + ") stored items: " + octree.getNumberOfStoredItems() < std::endl; // timer = std::chrono::system_clock::now(); // optimizeMaxItemsPerNode(octree, obj); // std::cout < " ____ octree.getNumberOfStoredItems() = " + octree.getNumberOfStoredItems() + " optimizeMaxItemsPerNode" < std::endl; cleanUp(root); std::cout << " > finished building" << std::endl; } ////////////////////////////////////////////////////////////////////////////// // BUILD OCTREE ////////////////////////////////////////////////////////////////////////////// // save in smallest nodes, that fully contains the triangle bool storeAtFirstFit(OctreeNode ot, int idx) { // 1) if we reached the max depth, save the triangle and return if( ot.depth >= MAX_DEPTH ){ saveTriangleToNode(ot, idx); return true; } // 2) generate childs, if not possible, this node is a leaf, so save the item here if(!assureChilds(ot, MAX_DEPTH) ) { saveTriangleToNode(ot, idx); return true; } // 3)) check if one child fully contains the triangle. if so, step down to the child for(OctreeNode child : ot.childs) { if( fullyContains(child, obj.f[idx]) ) { if(storeAtFirstFit(child, idx)) { return true; } } } // 4) no child fully contains the triangle. so push it to the leafes for(OctreeNode child : ot.childs) { storeInLeafes(child, idx); } // saveTriangleToNode(ot, idx); return true; } // make sure all triangles are in leaves void pushToLeafes(OctreeNode ot) { if(ot.isLeaf()) { return; } // since current node is no leaf, if it isn't empty either, then move its items down it childs if( !ot.isEmpty() ) { for( int idx: ot.IDX_triangles) { for(OctreeNode child : ot.childs) { storeInLeafes(child, idx); } } ot.IDX_triangles.clear(); } // repeat routine for all childs for(OctreeNode child : ot.childs) { pushToLeafes(child); } } void storeInLeafes(OctreeNode ot, int idx) { // if there's no overlap between the current node and the triangle, return if(!overlapsWithTriangle(ot, obj.f[idx])) { return; } // current node is leaf, and overlaps with the triangle, so save it here if(ot.isLeaf()) { saveTriangleToNode(ot, idx); return; } // if the current node is no leaf, so step down the childs for(OctreeNode child : ot.childs) { storeInLeafes(child, idx); } } void optimizeSpaceCost(OctreeNode ot) { if( !ot.isEmpty()) { if( !positiveFillRatio(ot)) { assureChilds(ot, MAX_DEPTH); pushToLeafes(ot); } } if(ot.isLeaf()) { return; } for(OctreeNode child : ot.childs) { optimizeSpaceCost(child); } } bool positiveFillRatio(OctreeNode ot) { float ratio_items_depth = ot.itemCount() / (float) (ot.depth); return ratio_items_depth < MIN_DEPTH_FILL_RATIO; } bool cleanUp(OctreeNode ot) { if(ot.isLeaf()) { return ot.isEmpty(); } bool delete_all_childs = true; for(int i = 0; i < ot.childs.length; i++) { if(ot.childs[i]==null) { continue; } if(cleanUp(ot.childs[i])) { ot.childs[i] = null; } else { delete_all_childs = false; } } if( delete_all_childs ) { ot.childs = null; return ot.isEmpty(); } else { return false; } } bool fullyContains(OctreeNode ot, OBJ_Face f) { return ot.aabb.isInside(f.A(), f.B(), f.C()); } bool overlapsWithTriangle(OctreeNode ot, OBJ_Face f) { return Intersect_AABB_TRIANGLE.overlaps(ot.aabb.min, ot.aabb.max, f.A(), f.B(), f.C()); } }; }
true
3e975dee117776a76b46a3e036564380365f5fcb
C++
balrog-kun/ApolloVentilator
/Firmware/aire_apollo/src/ApolloConfiguration.h
UTF-8
2,479
2.75
3
[]
no_license
#ifndef _APOLLO_CONFIGURATION_H #define _APOLLO_CONFIGURATION_H #include "../include/defaults.h" #include "Arduino.h" #include "Display.h" class ApolloConfiguration { public: ApolloConfiguration(); int getMlTidalVolumen() { return this->mlTidalVolume; }; int getPressionPeep() { return this->pressionPeep; }; int getPorcentajeInspiratorio() { return this->porcentajeInspiratorio; }; int getPorcetajeFiO2() { return this->porcentajeFiO2; }; int getRpm() { return this->rpm; }; int getSexo() { return this->sexo; }; int getWeight() { return this->weight; }; int getHeight() { return this->height; }; float getPresionTriggerInspiration() { return this->presionTriggerInspiration; }; bool isUpdated() { return this->updated; }; //Return true if the configuration has been updated void resetUpdated() { this->updated = false; } bool begin(); // Set tidal volume void setTidalVolume(float mlTidalVolume); //Set RPM void setRpm(int rpm); //Set Porcentaje inspiratorio void setPorcentajeInspiratorio(int porcentajeInspiratorio); // Set presion peep void setPressionPeep(float presionPeep); void setSexo(int sexo); void setWeight(int weight); void setHeight(int height); String getConfig(); bool parseConfig(String *strings); /** * @brief estima el volumen tidal en función de estatura y sexo, en ml. * * @param estatura en cm, del paciente * @param sexo 0: varón, 1: mujer, sexo del paciente * @return *volumenTidal volumen tidal estimado, en mililitros */ int static calcularVolumenTidal(int estatura, int sexo, float mlByKgWeight = DEFAULT_ML_POR_KG_DE_PESO_IDEAL) { float peso0, pesoIdeal; if (sexo == 0) { // Varón peso0 = 50.0; } else if (sexo == 1) { // Mujer peso0 = 45.5; } pesoIdeal = peso0 + 0.91 * (estatura - 152.4); // en kg return ((int)(round(pesoIdeal * mlByKgWeight))); } private: int weight; int height; int sexo; int rpm; int mlTidalVolume; int pressionPeep; int porcentajeInspiratorio; int porcentajeFiO2; float presionTriggerInspiration; void calcularCiclo(); float secCiclo = 0; float secTimeInsufflation = 0; float secTimeExsufflation = 0; bool updated = false; bool ready = false; bool defaultConfig(); }; #endif //_APOLLO_CONFIGURATION_H
true
babd6004c1e3e3fcdf1738d637353b63e9bd0b13
C++
mke01/BasicC-
/Day 03/03 Returning exit code from main/Source01.cpp
UTF-8
346
2.84375
3
[]
no_license
int main() { return 0; } /* A value returned from main function is known as exit code. This code is reported to operating system. If an application exits with exit code 0, it implies application was terminated successfully. If it exits with number other than zero, then refer its user manual to learn the reason behind the value returned. */
true
1328272f74644d869ffca081d10072df2a3eb2fe
C++
JackEdwards/Pazuzu
/GLEngine/ShaderAttribute.cpp
UTF-8
359
2.90625
3
[]
no_license
#include "ShaderAttribute.hpp" /** * @brief Sets the location of the attribute and * enables the vertex attribute array */ ShaderAttribute::ShaderAttribute(GLint location) { m_location = location; Enable(); } /** * @brief Enables the vertex attribute array */ void ShaderAttribute::Enable() { glEnableVertexAttribArray(m_location); }
true
29f69133c51682adf210f06d7eca987a52046825
C++
Serasvatie/GearsOfKMU
/GearsOfKMU/Classes/College.h
UTF-8
1,062
2.609375
3
[ "MIT" ]
permissive
#ifndef __COLLEGE_H__ #define __COLLEGE_H__ #include <string> #include "Major.h" #include "cocos2d.h" #define TXT_POPUP "Not enough " class College : public cocos2d::Sprite { private: Major *one; Major *two; std::string name; bool unlock; int MoneyToUnlock; int KnowledgeToUnlock; cocos2d::Menu* Lock; cocos2d::Label* LabelMoney; cocos2d::Label* LabelKnowledge; cocos2d::Label* Popup; cocos2d::Sequence* PopupSequence; public: static College* setSpriteWithFile(const char * file); void Reset(bool unlock, int moneytounlock, int knowledgetounlock, int major1MaxStudent, float major1TimeToGraduate, int major2MaxStudent, float major2TimeToGraduate); void Unlock(Ref *pSender); void setNameOfCollege(std::string, float, bool unlock, int moneyToUnlock, int knowledgeToUnlock); void setMajor(std::string, int, float, float timeOne, std::string, int, float, float timeSecond); virtual void update(float dt); int getNumberOfStudents(); College(); ~College(); }; #endif // __COLLEGE_H__
true
559ae0aa512e2bda2545d5a592596ea355cb50a3
C++
JimEli/maze_solver
/main.cpp
UTF-8
528
2.921875
3
[]
no_license
#include <iostream> #include <string> #include "vector.h" #include "maze.h" int main() { myVector::Vector<std::string> puzzle; puzzle.push_back(" #######"); puzzle.push_back("# # ##"); puzzle.push_back("# #### #"); puzzle.push_back("# ##"); puzzle.push_back("# ### ###"); puzzle.push_back("# #"); puzzle.push_back("#######!#"); maze m = maze(puzzle); std::cout << std::endl; if (m.solve()) std::cout << m; else std::cout << "Could not solve maze!\n"; return 0; }
true
0033e08d4284e2f8c6ba3b25969f229a2fd45f93
C++
zhaishuai/ERASuffixTree
/utils/Combinations.hpp
UTF-8
865
3.15625
3
[]
no_license
#pragma once #include <vector> #include <tuple> #include "Types.hpp" template<typename T> class Combinations { public: using Result = std::vector<std::tuple<T, T>>; Combinations(const std::vector<T>& values) : values(values), generated(false) { } const Result& getResult() { if (!generated) { generate(); } return result; }; private: void generate() { result.reserve(values.size() * values.size()); for (uint64 i = 0; i < values.size(); i++) { for (uint64 k = 0; k < values.size(); k++) { if (values[i] != values[k]) { result.push_back(std::make_tuple(values[i], values[k])); } } } result.shrink_to_fit(); } bool generated; const std::vector<T>& values; Result result; };
true
d04fa114180550f2a323905865825936858d282a
C++
yutateno/RPGproject
/RPGproject/RPGproject/GameOver.cpp
SHIFT_JIS
2,313
3.03125
3
[]
no_license
#include "Manager.h" GameOver::GameOver() { this->endFlag = false; this->nextScene = eScene::S_End; this->step = eStep::Start; this->startCount = 0; this->endCount = 0; } GameOver::~GameOver() { } void GameOver::UpDate() { switch (this->step) { case eStep::Start: // Jn this->UpDate_Start(); break; case eStep::Main: // C this->UpDate_Main(); break; case eStep::End: // I this->UpDate_End(); break; default: this->endFlag = true; // G[I break; } } void GameOver::UpDate_Start() { this->startCount++; if (this->startCount < 50) return; // 50t[ŊJnʏI this->step = eStep::Main; } void GameOver::UpDate_Main() { // ZL[Ń^Cgʂ if (KeyData::Get(KEY_INPUT_Z) == 1) { this->nextScene = eScene::S_Title; this->step = eStep::End; } // XL[ŃQ[I if (KeyData::Get(KEY_INPUT_X) == 1) { this->nextScene = eScene::S_End; this->step = eStep::End; } } void GameOver::UpDate_End() { this->endCount++; if (this->endCount < 50) return; // 50t[ŏIʏI this->endFlag = true; } void GameOver::Draw() { switch (this->step) { case eStep::Start: // Jn this->Draw_Start(); break; case eStep::Main: // C this->Draw_Main(); break; case eStep::End: // I this->Draw_End(); break; default: this->endFlag = true; // G[I break; } } void GameOver::Draw_Start() { DrawStringToHandle(0, 0, "Q[I[o[", WHITE, Font::Get(eFont::SELECT)); DrawFormatStringToHandle(0, 100, WHITE, Font::Get(eFont::SELECT), "Jn%d", this->startCount); } void GameOver::Draw_Main() { DrawStringToHandle(0, 0, "Q[I[o[", WHITE, Font::Get(eFont::SELECT)); DrawStringToHandle(0, 100, "C", WHITE, Font::Get(eFont::SELECT)); DrawStringToHandle(0, 200, "ZL[Ń^Cgʂ", WHITE, Font::Get(eFont::SELECT)); DrawStringToHandle(0, 300, "XL[ŃQ[I", WHITE, Font::Get(eFont::SELECT)); } void GameOver::Draw_End() { DrawStringToHandle(0, 0, "Q[I[o[", WHITE, Font::Get(eFont::SELECT)); DrawFormatStringToHandle(0, 100, WHITE, Font::Get(eFont::SELECT), "I%d", this->endCount); }
true
c5bdd1206094376e1cdcdc8e1f4110bbd18f0b64
C++
LafeLabs/geometron
/arduino/trash2/trash2.ino
UTF-8
2,400
3.546875
4
[]
no_license
/* Reading a serial ASCII-encoded string. This sketch demonstrates the Serial parseInt() function. It looks for an ASCII string of comma-separated values. It parses them into ints, and uses those to fade an RGB LED. Circuit: Common-Cathode RGB LED wired like so: * Red anode: digital pin 3 * Green anode: digital pin 5 * Blue anode: digital pin 6 * Cathode : GND created 13 Apr 2012 by Tom Igoe modified 14 Mar 2016 by Arturo Guadalupi This example code is in the public domain. */ int myInts[64]; int index = 0; int readIndex = 0; float scaleFactor = 2.0; float side = 1000; int pin1A = 13; int pin1B = 12; int pin2A = 5; int pin2B = 6; void setup() { // initialize serial: Serial.begin(115200); pinMode(pin1A, OUTPUT); digitalWrite(pin1A,LOW); pinMode(pin1B, OUTPUT); digitalWrite(pin1B,LOW); pinMode(pin2A, OUTPUT); digitalWrite(pin2A,LOW); pinMode(pin2B, OUTPUT); digitalWrite(pin2B,LOW); for(index = 0;index < 64;index++){ myInts[index] = 0; } } void loop() { // if there's any serial available, read it: while (Serial.available() > 0) { myInts[readIndex] = Serial.parseInt(); // look for the newline. That's the end of your // sentence: readIndex++; if (Serial.read() == '\n') { for(index = 0;index < 64;index++){ doTheThing(myInts[index]); } for(index = 0;index < 64;index++){ myInts[index] = 0; } index = 0; } } } void drawGlyph(int currentGlyph[]){ for(int i=0;i < 16;i++){ doTheThing(currentGlyph[index]); } } void doTheThing(int localCommand){ if(localCommand == 0){ delay(side); digitalWrite(pin1A,HIGH); delay(side); digitalWrite(pin1A,LOW); } if(localCommand == 1){ delay(side); digitalWrite(pin1B,HIGH); delay(side); digitalWrite(pin1B,LOW); } if(localCommand == 2){ delay(side); digitalWrite(pin2A,HIGH); delay(side); digitalWrite(pin2A,LOW); } if(localCommand == 3){ delay(side); digitalWrite(pin2B,HIGH); delay(side); digitalWrite(pin2B,LOW); } if(localCommand == 4){ side /= scaleFactor; // - } if(localCommand == 5){ side *= scaleFactor; // + } if(localCommand == 6){ // pen down } if(localCommand == 7){ // pen up } }
true
9eb90286433e30edf63fe74ab3c187458ec62461
C++
oscoder/QDataServer
/utils/uniqueid.cpp
UTF-8
3,390
2.71875
3
[]
no_license
#include "uniqueid.h" #if defined(QT_DEBUG) #include <QtCore/QRegExp> #endif using namespace Utils; /*! * \class Utils::UniqueId * \brief Fast manipulation with human-readable unique identifiers */ /*! \var UniqueId::m_idMap id map */ QHash<QString, int> UniqueId::m_idMap; /*! * \fn Utils::UniqueId::UniqueId() * \brief Constructs an invalid ID * \see isValid() */ /*! * \fn Utils::UniqueId::UniqueId(const char *id) * \brief This is an overloaded contructor */ /*! * \fn Utils::UniqueId::UniqueId(const QString &id) * \brief Primary constructor */ int UniqueId::uniqueId(const QString &id) { Q_ASSERT(!id.isEmpty()); const QHash<QString, int>::const_iterator it = m_idMap.find(id); if (it != m_idMap.end()) return *it; #if defined(QT_DEBUG) static QRegExp *const space = new QRegExp("\\s"); if (id.contains(*space)) qWarning("%s: id contains spaces <%s>", Q_FUNC_INFO, qPrintable(id)); #endif const int uid = m_idMap.size(); m_idMap.insert(id, uid); return uid; } /*! * \fn bool Utils::UniqueId::isValid() const * \brief ID contructed using the default constructor is invalid */ /*! * \fn QString Utils::UniqueId::toString() const * \brief Query the human-readable form of the identifier it represents */ /*! * \fn QByteArray Utils::UniqueId::toLocal8Bit() const * \brief Enables use of \c qPrintable() macro to print UniqueId values */ /*! * \fn int Utils::UniqueId::toInt() const * \brief Enables to store UniqueId in \c union * \attention The only valid case you can use this function is to store the * represented value into a C \c union which can not store values of types with * constructor. DO NOT MISUSE! * \see fromInt(int id), fromInt(int id, bool *ok) */ /*! * \fn Utils::UniqueId::fromInt(int id) * \brief Enables to store UniqueId on \c union * * This version may abort you application when an invalid \c id is given * * \attention The only valid case you can use this function is to store the * represented value into a C \c union which can not store values of types with * constructor. DO NOT MISUSE! * \see toInt(), fromInt(int id, bool *ok) */ /*! * \fn Utils::UniqueId::fromInt(int id, bool *ok) * \brief Enables to store UniqueId on \c union * * It will set \c *ok to \c false when an invalid \c id is given * * \attention The only valid case you can use this function is to store the * represented value into a C \c union which can not store values of types with * constructor. DO NOT MISUSE! * \see toInt(), fromInt(int id) */ /*! * \fn Utils::UniqueId::operator=(const QString &id) * \brief Assignment operator */ /*! * \fn Utils::UniqueId::operator=(const char *id) * \brief Assignment operator */ /*! * \fn Utils::operator==(const UniqueId &id1, const UniqueId &id2) * \brief Comparison operator * \relates UniqueId */ /*! * \fn Utils::operator!=(const UniqueId &id1, const UniqueId &id2) * \brief Comparison operator * \relates UniqueId */ /*! * \fn Utils::UniqueId::operator<(const UniqueId &other) const * \brief Comparison operator */ /*! * \fn bool Utils::UniqueId::hasUniqueId(const char *id) * \brief Query if any instance has been instantiated for the given \a id */ /*! * \fn bool Utils::UniqueId::hasUniqueId(const QString &id) * \brief Query if any instance has been instantiated for the given \a id */
true
6c0308460391e533d0a4a8b2cd72ac86a449fe13
C++
PoundKey/Algorithms
/LintCode/383. Container With Most Water.cpp
UTF-8
981
3.4375
3
[]
no_license
class Solution { public: /** * @param heights: a vector of integers * @return: an integer */ int maxArea(vector<int> &heights) { if (heights.empty()) return 0; int n = heights.size(), maxArea = 0; int start = 0, end = n - 1; while (start < end) { int curArea = min(heights[start], heights[end]) * (end - start); maxArea = max(maxArea, curArea); if (heights[start] <= heights[end]) { start++; } else { end--; } } return maxArea; } int maxAreaN2(vector<int> &heights) { if (heights.empty()) return 0; int n = heights.size(), maxArea = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int area = min(heights[i], heights[j]) * (j - i); maxArea = max(maxArea, area); } } return maxArea; } };
true
8751030818decaf7bc2be589e24096d941c5df32
C++
sanjusss/leetcode-cpp
/C/C200/C280/C289/3.cpp
UTF-8
2,603
2.875
3
[]
no_license
/* * @Author: sanjusss * @Date: 2022-04-17 10:28:09 * @LastEditors: sanjusss * @LastEditTime: 2022-04-17 11:15:37 * @FilePath: \C\C200\C280\C289\3.cpp */ #include "leetcode.h" class Solution { public: int maxTrailingZeros(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); // if (m <= 1 || n <= 1) { // return 0; // } vector<vector<int>> row2(m + 1, vector<int>(n + 1)); vector<vector<int>> row5(m + 1, vector<int>(n + 1)); vector<vector<int>> col2(m + 1, vector<int>(n + 1)); vector<vector<int>> col5(m + 1, vector<int>(n + 1)); vector<vector<int>> cnts2(m + 1, vector<int>(n + 1)); vector<vector<int>> cnts5(m + 1, vector<int>(n + 1)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int cnt2 = getCnt(grid[i][j], 2); int cnt5 = getCnt(grid[i][j], 5); cnts2[i + 1][j + 1] = cnt2; cnts5[i + 1][j + 1] = cnt5; row2[i + 1][j + 1] = row2[i + 1][j] + cnt2; row5[i + 1][j + 1] = row5[i + 1][j] + cnt5; col2[i + 1][j + 1] = col2[i][j + 1] + cnt2; col5[i + 1][j + 1] = col5[i][j + 1] + cnt5; } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int left2 = row2[i + 1][j]; int left5 = row5[i + 1][j]; int right2 = row2[i + 1][n] - row2[i + 1][j + 1]; int right5 = row5[i + 1][n] - row5[i + 1][j + 1]; int top2 = col2[i][j + 1]; int top5 = col5[i][j + 1]; int bottom2 = col2[m][j + 1] - col2[i + 1][j + 1]; int bottom5 = col5[m][j + 1] - col5[i + 1][j + 1]; int cnt2 = cnts2[i + 1][j + 1]; int cnt5 = cnts5[i + 1][j + 1]; int lt = min(left2 + top2 + cnt2, left5 + top5 + cnt5); int lb = min(left2 + bottom2 + cnt2, left5 + bottom5 + cnt5); int rt = min(right2 + top2 + cnt2, right5 + top5 + cnt5); int rb = min(right2 + bottom2 + cnt2, right5 + bottom5 + cnt5); ans = max({ ans, lt, lb, rt, rb }); } } return ans; } private: int getCnt(int n, int base) { int cnt = 0; if (n > 0) { while (n % base == 0) { ++cnt; n /= base; } } return cnt; } }; TEST(&Solution::maxTrailingZeros)
true
7476bbe3d7fbcdf0c52f54f0a2be5298ffedd6ef
C++
jongtae0509/codeup
/1000/1618_1.cpp
UTF-8
547
2.875
3
[]
no_license
/************************************************************** 1618번 jongtae0509 C++ 정확한 풀이코드 길이:334 byte(s) 수행 시간:0 ms 메모리 :1120 kb ****************************************************************/ #include<stdio.h> #include<algorithm> using namespace std; struct weight{ int a; }; bool cmp(const weight &u, const weight &v){ return u.a<v.a; } int main(){ struct weight aa[3]; int i; for(i=0;i<3;i++){ scanf("%d",&aa[i].a); } sort(aa,aa+3,cmp); for(i=0;i<3;i++){ printf("%d ",aa[i].a); } }
true
fbe41bd0c38ace97685da0ea06f4bbdb0e72e3ae
C++
josemalone/Poulailler
/Context.h
UTF-8
4,649
2.96875
3
[]
no_license
/* Persisting context b/w runs * * 30/10/2017 First version * 20/12/2017 Full redesign */ #ifndef CONTEXT_H #define CONTEXT_H /* 1-wire */ #include <OWBus.h> class Network; class Context { bool RTCvalid; // Is stored memory valid ? class Network *net; uint32_t offset; // Offset in memory for next data OneWire oneWire; OWBus bus; public: enum Steps { STARTUP_STARTUP = 0, STARTUP_AUXPWR, // Aux powered STARTUP_WAIT4DOOR, // Wait for door to stops WORKING }; private: struct { uint32_t key; // is RTC valid ? unsigned long int timeoffset; // Offset for millis() enum Steps status; // startup status unsigned int daylight : 1; // day or night } keep; public: Context() : RTCvalid(false), net(NULL), oneWire(ONE_WIRE_BUS), bus(&this->oneWire) { /* Check if RTC memory contains valuable data */ if(ESP.rtcUserMemoryRead(0, (uint32_t *)&this->keep, sizeof(this->keep))){ if( this->keep.key == ESP.getFlashChipId() ) this->RTCvalid = true; } if( !this->RTCvalid ){ // Initial values keep.timeoffset = 0; // Reset timekeeper keep.key = ESP.getFlashChipId(); keep.status = Steps::STARTUP_STARTUP; /* RTCvalid remains invalid in order to let other modules * to initialise themselves to default values */ } offset = sizeof(keep); } void setStatus( enum Steps s ){ this->keep.status = s; this->save(); } enum Steps getStatus( void ){ return this->keep.status; } bool getDaylight( void ){ return this->keep.daylight; } void setDaylight( bool v ){ this->keep.daylight = v; this->save(); } void setNetwork( Network *n ){ net = n; } OWBus &getOWBus( void ){ return bus; } bool isValid( void ){ return RTCvalid; } /* This method has to be called ONLY after all other stuffs * to be kept are initialised and saved */ void save( void ){ ESP.rtcUserMemoryWrite(0, (uint32_t *)&this->keep, sizeof(this->keep)); // RTCvalid = true; } /* Store current time offset before going to deep sleep * * This methods *MUST* be called just before deepsleep otherwise * the offset will be corrupted * * <- tts : time to stay in deep sleep (ms) */ void keepTimeBeforeSleep( unsigned long tts ){ keep.timeoffset += millis() + tts; this->save(); } unsigned long getTime( void ){ return( this->keep.timeoffset + millis() ); } uint32_t reserveData( uint32_t s ){ uint32_t start = this->offset; this->offset += s; return( start ); } void status( void ){ #ifdef DEV_ONLY String msg = "Context : RTC "; msg += this->isValid() ? "valid" : "invalid"; msg += "\n\tRTC data size : "; msg += offset; msg += "\n\tTime offset : "; msg += this->keep.timeoffset; this->Output( msg ); #endif } void Output( const char *msg ){ # ifdef SERIAL_ENABLED Serial.println( msg ); # endif this->publish( MQTT_Output, msg ); } void Output( String &msg ){ this->Output( msg.c_str() ); } class keepInRTC { uint32_t *what; uint32_t size; uint32_t offset; public: keepInRTC( Context &ctx, uint32_t *w, uint32_t s ) : what(w), size(s) { /* -> ctx : context managing the RTC memory * w : which data to save * s : size of the data to save */ this->offset = ctx.reserveData( s ); if(ctx.isValid()) // previous data can be retrieved ESP.rtcUserMemoryRead(this->offset, this->what, this->size); } void save( void ){ ESP.rtcUserMemoryWrite( this->offset, this->what, this->size ); } }; /******** * Helpers ********/ String toString( float number, uint8_t digits=2){ // Largely inspired by Print::printFloat() String res; if (isnan(number)) return "nan"; if (isinf(number)) return "inf"; bool negative = false; if(number < 0.0){ number = - number; negative = true; } // Round correctly so that print(1.999, 2) prints as "2.00" float rounding = 0.5; for (uint8_t i=0; i<digits; ++i) rounding /= 10.0; number += rounding; unsigned long int_part = (unsigned long)number; float remainder = number - (double)int_part; do { char c = int_part % 10; int_part /= 10; res = (char)(c+'0') + res; } while( int_part ); if( negative ) res = '-' + res; res += '.'; if( digits ) while(digits--){ remainder *= 10.0; res += (char)((char)remainder + '0'); remainder -= (int)remainder; } return res; } /****** * MQTT publishing ******/ void publish( const char *topic, const char *msg ); void publish( String &topic, String &msg ){ this->publish( topic.c_str(), msg.c_str() ); } void publish( String &topic, const char *msg ){ this->publish( topic.c_str(), msg ); } }; #endif
true
d714d39d6793258f1303434774e0d334d160cb3b
C++
prajogotio/upsolving
/CF:526:C/a.cpp
UTF-8
1,162
3.328125
3
[]
no_license
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; /** Cool! given xWa + yWb <= C, maximize xHa + yHb. 1. if either Wa or Wb > sqrt C, iterate through those sqrt C choices 2. otherwise Wa & Wb < sqrt C. WLOG Ha/Wa < Hb/Wb. suppose x > Wb. then xWa + yWb <= C => (x-Wb)Wa + WbWa + yWb <= C => (x-Wb)Wa + (y+Wa)Wb <= C and (x-Wb)Ha + (y+Wa)Hb = xHa + yHb + HbWa - WbHa > xHa + yHb hence if x > Wb, there is more optimal arrangement such that x < Wb. So we only need to iterate through all possibilities where x < Wb, since Wb < sqrt C, the choices is less than sqrt C */ int main(){ long long C,Ha,Hb,Wa,Wb; cin >> C >> Ha >> Hb >> Wa >> Wb; if (Wa*Wa >= C || Wb*Wb >= C){ if(Wa > Wb) { swap(Wa,Wb); swap(Ha,Hb); } long long ans = -1; for(long long y=0;y*Wb<=C;++y){ long long x = (C - y*Wb)/Wa; ans = max(x*Ha+y*Hb, ans); } cout << ans << endl; } else { if(Ha * Wb > Hb * Wa) { swap(Wa,Wb); swap(Ha,Hb); } long long ans = -1; for(long long x=0; x<=Wb;++x){ long long y = (C - x*Wa)/Wb; ans = max(x*Ha+y*Hb, ans); } cout << ans << endl; } return 0; }
true
72de1d36680dc768a41e5f6460d13d7459b1050e
C++
AleksandarDincic/Zinda-OS
/ThreadList.cpp
UTF-8
1,248
3.09375
3
[]
no_license
/* * ThreadList.cpp * * Created on: Apr 9, 2020 * Author: OS1 */ #include "PCB.h" ThreadList::Node* ThreadList::add(PCB *t, Time waitTime){ Node *newNode = new Node(t, 0, 0, waitTime); if(!head){ head = tail = newNode; } else{ newNode->prev=tail; tail=tail->next=newNode; } return newNode; } PCB* ThreadList::getByID(ID id){ Node *curr = head; while(curr){ if(curr->thread->id==id) return curr->thread; curr=curr->next; } return 0; } void ThreadList::remove(Node *node){ if(!node) return; if(node->next){ node->next->prev = node->prev; } else{ tail = node->prev; } if(node->prev){ node->prev->next = node->next; } else{ head = node->next; } delete node; } PCB* ThreadList::removeFirst(){ if(!head) return 0; PCB *temp = head->thread; Node *tempNode = head->next; delete head; head = tempNode; if(!head) tail = head; return temp; } ThreadList::~ThreadList(){ while(head){ Node *temp = head; head = head->next; delete temp; } } void ThreadList::globalWipe(){ while(PCB::masterList->head){ Node *temp = PCB::masterList->head; PCB::masterList->head = PCB::masterList->head->next; temp->thread->masterListNode=0; delete temp; } //brises sve iz master liste }
true
64c1da8cb7ea9bf286da50211554227624c3b5a0
C++
MoneyKicks/Codechef
/LONGSEQ.cpp
UTF-8
1,260
2.75
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; char a[100001]; cin>>t; cin.get(); while(t>0) { cin>>a; if(a[0]=='\0') {cout<<"Yes"<<endl;t--;continue;} if(a[1]=='\0') {cout<<"Yes"<<endl;t--;continue;} int ftrend,trend1=a[0]; int i=2; int flag=0; int trend2=a[1]; if(trend1==trend2) { ftrend=trend1; } if(trend1!=trend2) { if(a[2]==trend1) ftrend=trend1; else ftrend=trend2; flag=1; i=3; } for(i;a[i]!='\0';i++) { if(ftrend==a[i]) continue; if(ftrend!=a[i]&&flag==0) { flag=1; continue; } if(ftrend!=a[i]&&flag==1) { flag=2; cout<<"No"<<endl; break; } } if(flag==0) cout<<"No"<<endl; if(flag==1) cout<<"Yes"<<endl; t--; } }
true
507dc1a86fd9aaaabd66679c64bbed8c9fa593ea
C++
HelgeID/SnakeConsoleAPP
/build4_Snake, the final build/SnakeConsoleApp/SnakeConsoleApp/main.cpp
UTF-8
2,944
2.703125
3
[]
no_license
#include <Windows.h> #include <tchar.h> #include "interface.h" #include "engine.h" #include "colors.h" #define MAX_WIDTH 82 //width of the console #define MAX_HIGHT 42 //height of the console //flags CHAR bKey; BOOL gameOver; BOOL closeConsole; HANDLE hOut; //function of the console void SetWindowTitle(const LPTSTR); void SetWindowSize(const SHORT, const SHORT); void HideCursor(); int main() { //get handle// hOut = GetStdHandle(STD_OUTPUT_HANDLE);//-11 if (hOut == INVALID_HANDLE_VALUE) { MessageBox(NULL, TEXT("GetStdHandle"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } SetWindowTitle("Snake Demo"); SetWindowSize(MAX_WIDTH, MAX_HIGHT); HideCursor(); MainMenu(hOut, bKey, gameOver, closeConsole); while (closeConsole == FALSE) { GameInit(); while (gameOver == TRUE) { GameController(bKey, gameOver, closeConsole); GameUpdate(); } if (gameOver == FALSE) GameOverMenu(bKey); MainMenu(hOut, bKey, gameOver, closeConsole); } return EXIT_SUCCESS; } void SetWindowTitle(const LPTSTR lpConsoleTitle) { TCHAR* tcConsoleTitle = _T(lpConsoleTitle); if (!SetConsoleTitle(tcConsoleTitle)) { MessageBox(NULL, TEXT("SetConsoleTitle"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } return; } void SetWindowSize(const SHORT wd, const SHORT ht) { //get handle// hOut = GetStdHandle(STD_OUTPUT_HANDLE);//-11 if (hOut == INVALID_HANDLE_VALUE) { MessageBox(NULL, TEXT("GetStdHandle"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } //CONSOLE_SCREEN_BUFFER_INFO csbiInfo;//not uses //set size of buffer// COORD coordBuff = { wd, ht }; if (!SetConsoleScreenBufferSize(hOut, coordBuff)) { MessageBox(NULL, TEXT("SetConsoleScreenBufferSize"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } /* not uses if (!GetConsoleScreenBufferInfo(hOut, &csbiInfo)) { MessageBox(NULL, TEXT("GetConsoleScreenBufferInfo"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } */ //set size of window// SMALL_RECT srectWin; srectWin.Left = 0; srectWin.Top = 0; srectWin.Right = wd - 1; srectWin.Bottom = ht - 1; if (!SetConsoleWindowInfo(hOut, TRUE, &srectWin)) { MessageBox(NULL, TEXT("SetConsoleWindowInfo"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } return; } void HideCursor() { hOut = GetStdHandle(STD_OUTPUT_HANDLE);//-11 if (hOut == INVALID_HANDLE_VALUE) { MessageBox(NULL, TEXT("GetStdHandle"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } CONSOLE_CURSOR_INFO ci; if (!GetConsoleCursorInfo(hOut, &ci)) { MessageBox(NULL, TEXT("GetConsoleCursorInfo"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } ci.bVisible = FALSE; if (!SetConsoleCursorInfo(hOut, &ci)) { MessageBox(NULL, TEXT("SetConsoleCursorInfo"), TEXT("Console Error"), MB_OK); exit(EXIT_FAILURE); } return; }
true
e2eee59a5cb8f3731e3f608f7a34d5893befa14b
C++
petr-konovalov/c-projects
/cdb proj/timus/Паутина Ананси/main.cpp
UTF-8
1,413
2.75
3
[]
no_license
#include <iostream> #include <stdio.h> #include <vector> using namespace std; int parent[100000]; int rankSet[100000]; int ccomp = 0; int findSet(int v) { return parent[v] == v ? v : parent[v] = findSet(parent[v]); } void makeSet(int v) { parent[v] = v; rankSet[v] = 0; ++ccomp; } void unionSet(int a, int b) { a = findSet(a); b = findSet(b); if (a != b) { --ccomp; if (rankSet[a] < rankSet[b]) swap(a, b); parent[b] = a; if (rankSet[a] == rankSet[b]) ++rankSet[a]; } } bool breaks[100000]; int breakOrd[100000]; int l[100000]; int r[100000]; void printAns(int i) { int c = ccomp; if (i >= 0) { unionSet(l[breakOrd[i]], r[breakOrd[i]]); printAns(i - 1); printf("%i ", c); } } int main() { int n, m; scanf("%i %i", &n, &m); for (int i = 0; i < n; ++i) makeSet(i); for (int i = 0; i < m; ++i) { scanf("%i %i", l + i, r + i); --l[i]; --r[i]; } int q; scanf("%i", &q); for (int i = 0; i < q; ++i) { scanf("%i", breakOrd + i); --breakOrd[i]; breaks[breakOrd[i]] = true; } for (int i = 0; i < m; ++i) if (!breaks[i]) unionSet(l[i], r[i]); printAns(q - 1); return 0; }
true
77232feb76b9a361261694921fb987418afa1d04
C++
chinudev/program_cpp
/coding_interview/list/test_list.cpp
UTF-8
1,630
3.515625
4
[]
no_license
#include "list.hpp" void test_makeList() { { // We need to explicitly provide template type in absence of any arguments auto head = makeList<int>({}); printList(head); } { auto head = makeList({1,3,4}); printList(head); } { auto head = makeList({"apple", "orange", "banana", "wow"}); printList(head); } } void test_compare() { { auto head1 = makeList({1,2,3}); auto head2 = makeList({"apple"}); auto head3 = makeList({1,2,3}); auto head4 = makeList<int>({}); auto head5 = makeList({1,2,3,4}); auto head6 = makeList({1,2}); // This code doesn't compile because the two lists are templatized with different types. // As expected but highlights the benefit of strong typing. //assert(compareList(head1, head2) == false); printList(head1); printList(head3); assert(compareList(head1, head3) == true); assert(compareList(head1, head3) == true); assert(compareList(head4, head4) == true); assert(compareList(head1, head3) == true); assert(compareList(head1, head5) == false); assert(compareList(head1, head6) == false); } { auto head1 = makeList({"apple", "orange", "banana", "wow"}); auto head2 = makeList({"apple", "orange", "banana", "wow"}); auto head3 = makeList({"apple", "orange", "banana"}); assert(compareList(head1, head2) == true); assert(compareList(head1, head3) == false); } } int main(void) { test_makeList(); test_compare(); }
true
5e6792b7537c6c4ce6b7b29ee232efa16ae3b647
C++
Ernesuma/replacerMpv
/ReplacerMPV/tagmapmodel.h
UTF-8
2,193
2.8125
3
[ "MIT" ]
permissive
#ifndef TAGMAPMODEL_H #define TAGMAPMODEL_H #include <QDebug> #include <QAbstractTableModel> #include <QObject> #include <QMap> #include <QRegularExpression> class TagMapModel : public QAbstractTableModel { Q_OBJECT public: // define types of the tag map typedef QString tagMapKey; typedef QString tagMapValue; typedef QMap<tagMapKey, tagMapValue> tagMap; private: // private Member tagMap m_map{}; tagMapKey m_newKey{""}; tagMapKey m_newValue{""}; // define regex to test key validity static const QRegularExpression reKeyValid; // give a string for messages to show valid characters for map key static const QString validKeyChars; public: // declare constructors TagMapModel(QObject *pParent=0); TagMapModel(const tagMap &map, QObject* pParent = 0); // empty destructor ~TagMapModel(){} // implement abstract methods int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; bool insertRows(int row, int count, const QModelIndex &parent); bool removeRows(int row, int count, const QModelIndex &parent); Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &newValue, int role = Qt::EditRole); // own methods to add and remove values with custom parameters bool insert(const tagMapKey& key, const tagMapValue& value); bool removeRows(const QModelIndexList rows); bool removeAllRows(); bool isKeyInUse(const tagMapKey& key) const; static bool isKeyValid(const QString& key); static QString filterKey(const QString& key); static const QString &getValidKeyCharsString(); // getter to access the map as const reference const tagMap& getTagMap() const {return m_map;}; signals: void setData_filteredKey(const QString orig, const QString filtered); void setData_emptyKey(); void setData_doubletKey(const QString tag); }; #endif // TAGMAPMODEL_H
true
1f8fad54e2ff7e84434220911acf2fdb535b4e27
C++
PavelErsh/C-
/s.cpp
UTF-8
282
2.6875
3
[]
no_license
#include<iostream> #include <cctype> using namespace std; int main (){ cout << "Enter doukv\n"; char word; int kolvo = 0; int kn = 0; while (word != '@'){ if (isalnum(word)) kolvo++; if (isdigit(word)) kn++; cin.get(word); } cout <<"boukv " << kolvo << "nambers "<< kn << endl; }
true
f63ae6807ac22469ece73778d93fa8a14c710a26
C++
wangxb96/PAT-Notes
/chapter1/21Boys vs Girls.cpp
GB18030
822
3.234375
3
[]
no_license
//Boys vs Girls #include<cstdio> struct person{ char name[15]; char id[15]; int score; }M,F,temp; //MΪͷϢFΪŮ߷Ϣ void Init(){ M.score=10; F.score=-1; } int main() { Init(); int n; char gender; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%s %c %s %d",temp.name,&gender,temp.id,&temp.score); if(gender=='M'&&temp.score<M.score) { M=temp; } else if(gender=='F'&&temp.score>F.score){ F=temp; } } if(F.score==-1) printf("Absent!\n");//ûŮ else printf("%s %s\n",F.name,F.id); if(M.score==101) printf("Absent!\n");//û else printf("%s %s\n",M.name,M.id); if(F.score==-1||M.score==101) printf("NA!\n");//ûŮ else printf("%d\n",F.score-M.score); return 0; }
true
f4dc6226f6425d5dbb0bd09b875eb081c263819d
C++
verstecken/trampolin_final
/taste.cpp
UTF-8
1,682
2.71875
3
[]
no_license
#include "taste.h" //include the declaration for this class #include <MIDI.h> MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI); // using TX1 for sending MIDI signal int Taste::globalVelo = 0; static void Taste::overrideVelo(int velo) { globalVelo = velo; } static void Taste::midibegin() { MIDI.begin(MIDI_CHANNEL_OMNI); } static void Taste::setPedal(bool press) { if(press) { Serial.println("PRESS DOWN "); MIDI.sendControlChange(64, 127, 1); } else { Serial.println("RELEASE "); MIDI.sendControlChange(64, 0, 1); } } Taste::Taste() { timer.stop(); delayTimer.stop(); } Taste::~Taste() { /*nothing to destruct*/ } void Taste::playDelayed(int delay, int duration, int velo) { this->delay = delay; delayDuration = duration; delayVelo = velo; delayTimer.restart(); } void Taste::play(int duration, int velo) { if (!timer.isRunning()) { /*Serial.print("Note: "); Serial.print(midinote); Serial.print(" Duration: "); Serial.println(duration);*/ this->duration = duration; timer.restart(); if(globalVelo == 0) { MIDI.sendNoteOn(midinote, velo, 1); } else { MIDI.sendNoteOn(midinote, globalVelo, 1); } } } void Taste::update() { if (timer.hasPassed(duration) && timer.isRunning()) { timer.stop(); MIDI.sendNoteOff(midinote, 0, 1); } if (delayTimer.hasPassed(delay) && delayTimer.isRunning()){ delayTimer.stop(); play(delayDuration, delayVelo); } } void Taste::stop() { if (delayTimer.isRunning()) { delayTimer.stop(); } } bool Taste::isPlaying() { return timer.isRunning(); } void Taste::setNote(int midinote) { this->midinote = midinote; }
true
b263841821dbb1fea7ba7497adc536cb87d8a75b
C++
MiohitoKiri5474/CodesBackUp
/C++/TIOJ/1055.cpp
UTF-8
324
2.78125
3
[]
no_license
#include<iostream> using namespace std; int main(){ long long a, b; cin >> a >> b; if ( a > b ) for ( int i = a ; i >= b ; i-- ){ for ( int j = 0 ; j < i ; j++ ) cout << '*'; cout << endl; } else for ( int i = a ; i <= b ; i++ ){ for ( int j = 0 ; j < i ; j++ ) cout << '*'; cout << endl; } }
true
e7d5d61618b45d5284303d71f6c24677a735941e
C++
Kiranchawla09/GFG
/Diameter_of_a_binary_tree.cpp
UTF-8
786
3.703125
4
[]
no_license
/* Tree node structure used in the program struct Node { int data; struct Node* left; struct Node* right; Node(int x){ data = x; left = right = NULL; } }; */ int height(struct Node* node) { if(node == NULL) return 0; return (1 + max(height(node->left), height(node->right))); } /* Computes the diameter of binary tree with given root. */ int diameter(Node* node) { // Your code here if (node==NULL) return 0; int left_height = height(node->left); int right_height = height(node->right); int left_diameter = diameter(node->left); int right_diameter = diameter(node->right); return (max(left_height+right_height+1,max(left_diameter, right_diameter))); }
true
3661e81725f9e81a8320d91b376dbd79bdc13e0b
C++
google-code/2013taller1c
/TpTaller/src/Menu.cpp
UTF-8
3,458
2.5625
3
[]
no_license
/* * Menu.cpp * * Created on: 23/03/2013 * Author: tomas */ #include <stdlib.h> #include <iostream> #include <Menu.h> #include <view/Button.h> #include <SDL/SDL_events.h> const char* buttons_released[NUM_BUTTONS] = { "resources/menu/buttons/SP.png", "resources/menu/buttons/MP.png", "resources/menu/buttons/Server.png", "resources/menu/buttons/Exit.png" }; const char* buttons_pressed[NUM_BUTTONS] = { "resources/menu/buttons/SP_pressed.png", "resources/menu/buttons/MP_pressed.png", "resources/menu/buttons/Server_pressed.png", "resources/menu/buttons/Exit_pressed.png" }; const char* buttons_hovered[NUM_BUTTONS] = { "resources/menu/buttons/SP_hovered.png", "resources/menu/buttons/MP_hovered.png", "resources/menu/buttons/Server_hovered.png", "resources/menu/buttons/Exit_hovered.png" }; const MenuEvent buttons_events[NUM_BUTTONS] = { NEWGAME_EVENT, MULTIPLAYER_GAME_EVENT, SERVER_EVENT, EXIT_EVENT }; Menu::Menu(GameConfiguration* configuration) { view = new MenuView(configuration); view->initScreen(); view->initButtons(NUM_BUTTONS, buttons_released, buttons_pressed, buttons_hovered, buttons_events); view->initMusic(); closed = false; } /* * <run> */ // Funcion fea bool mouseIsOnButton(Button* button, SDL_Event event) { return (event.button.x > button->pos.x && event.button.x < button->pos.x + button->pos.w && event.button.y > button->pos.y && event.button.y < button->pos.y + button->pos.h); } bool mouseHoversOnButton(Button* button) { int x, y; SDL_GetMouseState(&x, &y); return (x > button->pos.x && x < button->pos.x + button->pos.w && y > button->pos.y && y < button->pos.y + button->pos.h); } void Menu::checkHoveredButton(SDL_Event event) { for (int i = 0; i < NUM_BUTTONS; i++) { if (mouseHoversOnButton(view->buttons[i])) { if (!view->buttons[i]->isPressed()) { view->buttons[i]->changeState(BUTTON_HOVERED); view->buttons[i]->draw(view->screen); } } else { if (!view->buttons[i]->isPressed()) { view->buttons[i]->changeState(BUTTON_RELEASED); view->buttons[i]->draw(view->screen); } else { view->buttons[i]->changeState(BUTTON_PRESSED); view->buttons[i]->draw(view->screen); } } } } void Menu::checkPressedButton(SDL_Event event) { for (int i = 0; i < NUM_BUTTONS; i++) { if (mouseIsOnButton(view->buttons[i], event)) { if (!view->buttons[i]->isPressed()) { view->buttons[i]->changeState(BUTTON_PRESSED); view->buttons[i]->draw(view->screen); } } } } MenuEvent Menu::checkReleasedButton(SDL_Event event) { for (int i = 0; i < NUM_BUTTONS; i++) { if (view->buttons[i]->isPressed()) { view->buttons[i]->changeState(BUTTON_RELEASED); view->buttons[i]->draw(view->screen); } if (mouseIsOnButton(view->buttons[i], event)) { return view->buttons[i]->event; } } return NOTHING_EVENT; } MenuEvent Menu::run() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: return EXIT_EVENT; break; case SDL_MOUSEBUTTONDOWN: checkPressedButton(event); return NOTHING_EVENT; break; case SDL_MOUSEBUTTONUP: return checkReleasedButton(event); default: checkHoveredButton(event); return NOTHING_EVENT; break; } } return NOTHING_EVENT; } /* * </run> */ void Menu::close() { view->close(); closed = true; } void Menu::runConfigMenu() { } Menu::~Menu() { if (!closed) close(); delete view; }
true
c3e4033b62403de83ade1de26fca1f231f30574d
C++
nikcherr/QTcpConnection
/QClient/client.cpp
UTF-8
1,480
3
3
[]
no_license
#include "client.h" Client::Client(QObject *parent) { socket = new QTcpSocket(this); } PortValid Client::setPortNumber(const std::__cxx11::string &port) { int socketPort = 0; for(auto item : port){ if(isdigit(item)){ socketPort *= 10; socketPort += item - '0'; } else break; } if(socketPort > 0 && socketPort < 65535){ this->port = socketPort; return PortValid::CORRECT; } return PortValid::INCORRECT; } Client::~Client() { socket->close(); } bool Client::isConnected() { return socket->isOpen(); } void Client::readData() { QByteArray data = socket->readAll(); } void Client::set_address_port(const QString &address, const QString &port) { switch(setPortNumber(port.toStdString())){ case PortValid::CORRECT: connect(socket, SIGNAL(readyRead()), this, SLOT(readData())); socket->connectToHost(address, this->port); if(socket->waitForConnected(2000)){ emit send_to_mainwindow("Connect to server."); } else{ emit send_to_mainwindow("Connection timeout."); } break; case PortValid::INCORRECT: emit send_to_mainwindow("Port number is incorrect."); break; } } void Client::write_data_to_socket(const GeographicalPoint& data) { QString out = QString::number(data.getLatitude()) + " " + QString::number(data.getLongitude()); socket->write(out.toUtf8()); }
true
ed5040eea47478db4cdc7be0cd930639e24dddf7
C++
backupbrain/arduino-projects
/Nick/MOM_GET_THE_CAMRA/MOM_GET_THE_CAMRA.ino
UTF-8
1,364
2.765625
3
[]
no_license
#include <Adafruit_NeoPixel.h> const byte neopixelPin = 6; const byte micPin = A5; const uint8_t numPixels = 12; const uint8_t numMicReadings = 255; const uint8_t micReadDelay_ms = 200; const uint8_t micRangeCutoff = 20; uint8_t colors[numPixels] = { 0 }; Adafruit_NeoPixel pixels = Adafruit_NeoPixel(numPixels, neopixelPin, NEO_GRB + NEO_KHZ800); void setup() { // put your setup code here, to run once: Serial.begin(9600); pixels.begin(); // This initializes the NeoPixel library. for (int i=0; i<numPixels; i++) { pixels.setPixelColor(i, pixels.Color(0,0,0)); } pixels.show(); } void loop() { int micMin = 255; int micMax = 0; for (int i=0; i< numMicReadings; i++) { int micValue = analogRead(micPin); micMax = max(micMax, micValue); micMin = min(micMin, micValue); } // calculate range int range = micMax - micMin; range = constrain(range, micRangeCutoff, 1023); int brightness = map(range, micRangeCutoff, 1023, 0, 100); Serial.println(brightness); for (int i=0; i< numPixels-1; i++) { colors[i] = colors[i+1]; pixels.setPixelColor(i, pixels.Color(colors[i],colors[i],colors[i])); } colors[numPixels-1] = brightness; pixels.setPixelColor(numPixels-1, pixels.Color(brightness, brightness, brightness)); pixels.show(); // This sends the updated pixel color to the hardware. }
true
e80bc850459835186d275e76205e1823af40444a
C++
ANUPPRAMANIK/CS-ASSIGNMENT-3
/Lab3_question21.cpp
UTF-8
315
2.796875
3
[]
no_license
#include<iostream> using namespace std; main() { float a,b; cout<<" enter electric units used: "; cin>>a; if(a<=50) b=a*0.5; else if(a>50 & a<=150) b=(50*0.5)+(0.75*(a-50)); else if(a>150 & a<=250) b=100+(1.20*(a-150)); else b=220+(1.5*(a-250)); b+=0.2*b; cout<<" total electricity bill: "<<b; }
true
2c7e9c44261def9eb9745f795bd4577fd915e2fc
C++
jesus-barrera/process-scheduler
/src/main.cpp
UTF-8
1,313
2.6875
3
[]
no_license
#include <cstdlib> #include <ctime> #include "ui/screen.h" #include "ui/scheduler/MemoryView.h" #include "ProcessScheduler.h" #include "util.h" void initialize(); void finalize(); void pause(std::string message); ProcessScheduler *scheduler; int main(void) { int num_of_processes; int quantum; initialize(); wprintw(content, "Numero de procesos: "); wscanw(content, "%d", &num_of_processes); wprintw(content, "Quantum: "); wscanw(content, "%d", &quantum); curs_set(0); // hide cursor noecho(); // disable echoing scheduler->setQuantum(quantum); scheduler->generateProcesses(num_of_processes); scheduler->post(); pause("Presiona una tecla para comenzar..."); scheduler->runSimulation(); pause("Presiona una tecla para continuar..."); scheduler->showResults(); pause("Presiona una tecla para salir..."); finalize(); return 0; } void pause(std::string message) { setFooter(message); getch(); } void initialize() { srand(time(NULL)); // initialize ncurses initscr(); cbreak(); start_color(); MemoryView::init(); startScreen(); setHeader("PAGINACION SIMPLE"); scheduler = new ProcessScheduler(); } void finalize() { delete(scheduler); endScreen(); endwin(); }
true
78782cd77e917f4021c24c10a68b07dc58bef828
C++
openhome/ohNetGenerated
/OpenHome/Net/Bindings/Cpp/Device/Providers/DvAvOpenhomeOrgTime1.h
UTF-8
3,505
2.515625
3
[ "MIT" ]
permissive
#ifndef HEADER_DVAVOPENHOMEORGTIME1CPP #define HEADER_DVAVOPENHOMEORGTIME1CPP #include <OpenHome/Types.h> #include <OpenHome/Buffer.h> #include <OpenHome/Net/Cpp/DvDevice.h> #include <OpenHome/Net/Core/DvProvider.h> #include <OpenHome/Net/Cpp/DvInvocation.h> #include <string> namespace OpenHome { namespace Net { class IDviInvocation; class PropertyInt; class PropertyUint; class PropertyBool; class PropertyString; class PropertyBinary; /** * Provider for the av.openhome.org:Time:1 UPnP service * @ingroup Providers */ class DvProviderAvOpenhomeOrgTime1Cpp : public DvProvider { public: virtual ~DvProviderAvOpenhomeOrgTime1Cpp() {} /** * Set the value of the TrackCount property * * Can only be called if EnablePropertyTrackCount has previously been called. * * @return true if the value has been updated; false if aValue was the same as the previous value */ bool SetPropertyTrackCount(uint32_t aValue); /** * Get a copy of the value of the TrackCount property * * Can only be called if EnablePropertyTrackCount has previously been called. */ void GetPropertyTrackCount(uint32_t& aValue); /** * Set the value of the Duration property * * Can only be called if EnablePropertyDuration has previously been called. * * @return true if the value has been updated; false if aValue was the same as the previous value */ bool SetPropertyDuration(uint32_t aValue); /** * Get a copy of the value of the Duration property * * Can only be called if EnablePropertyDuration has previously been called. */ void GetPropertyDuration(uint32_t& aValue); /** * Set the value of the Seconds property * * Can only be called if EnablePropertySeconds has previously been called. * * @return true if the value has been updated; false if aValue was the same as the previous value */ bool SetPropertySeconds(uint32_t aValue); /** * Get a copy of the value of the Seconds property * * Can only be called if EnablePropertySeconds has previously been called. */ void GetPropertySeconds(uint32_t& aValue); protected: /** * Constructor * * @param[in] aDevice Device which owns this provider */ DvProviderAvOpenhomeOrgTime1Cpp(DvDeviceStd& aDevice); /** * Enable the TrackCount property. */ void EnablePropertyTrackCount(); /** * Enable the Duration property. */ void EnablePropertyDuration(); /** * Enable the Seconds property. */ void EnablePropertySeconds(); /** * Signal that the action Time is supported. * The action's availability will be published in the device's service.xml. * Time must be overridden if this is called. */ void EnableActionTime(); private: /** * Time action. * * Will be called when the device stack receives an invocation of the * Time action for the owning device. * Must be implemented iff EnableActionTime was called. */ virtual void Time(IDvInvocationStd& aInvocation, uint32_t& aTrackCount, uint32_t& aDuration, uint32_t& aSeconds); private: DvProviderAvOpenhomeOrgTime1Cpp(); void DoTime(IDviInvocation& aInvocation); private: PropertyUint* iPropertyTrackCount; PropertyUint* iPropertyDuration; PropertyUint* iPropertySeconds; }; } // namespace Net } // namespace OpenHome #endif // HEADER_DVAVOPENHOMEORGTIME1CPP
true
4b90f78bd7b1b491ce3e5f83461be0129299d8a2
C++
write2maka/2021-Algo-1-Coursera-Princeton
/week-1-union-find/src/quickUnion.cpp
UTF-8
1,496
3.5625
4
[]
no_license
/* * quickUnion.cpp * * Created on: Aug 29, 2021 * Author: write2maka */ #include <quickUnion.h> #include <iostream> using namespace std; // // Constructor // QuickUnion::QuickUnion(int N) { cout << "QuickUnion initialized with N=" << N << endl; // Needed to print array arraySize = N; // Allocate memory for the array arr = new int[N]; // Initialize the array for (int i = 0; i < N; i++) { arr[i] = i; } } // // Destructor // QuickUnion::~QuickUnion() { cout << "\nQuickUnion Destructor called" << endl; // Free the memory delete arr; } // // Connect nodes p and q // void QuickUnion::connect(int p, int q) { cout << "Connect called with " << p << " and " << q << endl; int pRoot = getRoot(arr[p]); int qRoot = getRoot(arr[q]); // Connect root of p with root of q arr[pRoot] = qRoot; // Print the array post connection printArray(); } // // Check if nodes p and q are connected // bool QuickUnion::fConnected(int p, int q) { return (getRoot(p) == getRoot(q)); } int QuickUnion::getRoot(int num) { while (arr[num] != num) { num = arr[num]; } return num; } // // Helper function to print array // void QuickUnion::printArray() { cout << "Array: "; for (int i = 0; i < arraySize; i++) { cout << arr[i] << " "; } cout << endl; cout << endl; }
true
939df3942c87f86256b01669d3c432d9c481ff5f
C++
dariadryha/Piscine_CPlusPlus
/GitDay01++/ex00/Pony.cpp
UTF-8
1,520
2.65625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Pony.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddryha <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/19 12:42:25 by ddryha #+# #+# */ /* Updated: 2018/06/19 12:55:47 by ddryha ### ########.fr */ /* */ /* ************************************************************************** */ #include "Pony.hpp" Pony::Pony() { std::cout << "Pony is born!" << std::endl; } Pony::~Pony() { std::cout << "Pony " << this->name << " died!" << std::endl; } int Pony::GetGrowth(void) { return (this->growth); } int Pony::GetWeight(void) { return (this->weight); } int Pony::GetAge(void) { return (this->age); } void Pony::SetGrowth(int data) { this->growth = data; } void Pony::SetWeight(int data) { this->weight = data; } void Pony::SetAge(int data) { this->age = data; } void Pony::SetName(std::string _name) { this->name = _name; } std::string Pony::GetName(void) { return (this->name); }
true
2ffc934cfcc1f7c0ae210c3845f9b607b9d9bce8
C++
codingNonGuru/PlanetSimulator
/Source/Transform.cpp
UTF-8
1,495
2.671875
3
[]
no_license
/* * Transform.cpp * * Created on: Sep 25, 2016 * Author: andrei */ #include <math.h> #include <gtc/matrix_transform.hpp> #include "Transform.hpp" #include "Scene.hpp" Transform::Transform(Position position, Rotation rotation, Scale scale) { position_ = position; rotation_ = rotation; scale_ = scale; } void Transform::Initialize(Position position, Rotation rotation, Scale scale) { position_ = position; rotation_ = rotation; scale_ = scale; } Direction Transform::GetForward() { return Direction(cos(rotation_), sin(rotation_)); } Matrix Transform::GetMatrix() { Matrix worldMatrix = glm::translate(Matrix(1.0f), glm::vec3(position_, 0.0f)) * glm::rotate(Matrix(1.0f), rotation_, glm::vec3(0.0f, 0.0f, 1.0f)) * glm::scale(Matrix(1.0f), glm::vec3(1.0f, 1.0f, 1.0f)); return worldMatrix; } Matrix Transform::GetPositionMatrix() { Matrix worldMatrix = glm::translate(Matrix(1.0f), glm::vec3(position_, 0.0f)) * glm::scale(Matrix(1.0f), glm::vec3(1.0f, 1.0f, 1.0f)); return worldMatrix; } Transform* Transform::Allocate(Scene* scene, Position position, Rotation rotation, Scale scale) { auto transform = scene->transforms_.allocate(); transform->Initialize(position, rotation, scale); return transform; } Transform* Transform::Allocate(Scene* scene, Transform* otherTransform) { auto transform = scene->transforms_.allocate(); *transform = *otherTransform; return transform; } Transform::~Transform() { // TODO Auto-generated destructor stub }
true
6721ba98ffaba50fdbb09dc4bea2199bf8e7910a
C++
Yunena/Solution-to-PTA
/1001 A+B Format.cpp
UTF-8
653
2.75
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main(int argc, char** argv) { int a, b; cin>>a>>b; int c = a+b; string sign="", res=""; if(c==0) {cout<<"0"<<endl;return 0;} //cout<<a<<" "<<b<<" "<<c<<endl; if(c<0){ sign = "-"; c = -c; } int cnt = 0, mod = 10; //cout<<"???: "<<c<<endl; while(c>0){ string s = to_string(c%mod); //cout<<res<<" "<<s<<endl; cnt++; res = s+res; c/=mod; if(c!=0&&cnt==3){ cnt=0; res = ","+res; } } res = sign+res; cout<<res<<endl; return 0; }
true
1d7e144d3298b2053dc54e2ff5217950d28e9c58
C++
mojtabaahn/simple-swagger
/app/Http/Livewire/Display.php.cp
UTF-8
1,161
2.75
3
[]
no_license
<?php namespace App\Http\Livewire; use App\Support\SpecFactory; use Livewire\Component; use Symfony\Component\Yaml\Exception\ParseException; class Display extends Component { protected $listeners = ['update' => 'setValue']; public $value = ''; public function setValue($value) { $this->value = $value; } public function render() { try { $output = SpecFactory::make($this->value); } catch (ParseException $exception) { $error = $exception->getMessage(); $output = false; } $spec = [ 'openapi' => '3.0.0', 'info' => [ 'title' => 'IQoala', 'version' => '1.0.0' ], 'paths' => [ '/' => [ 'get' => [ 'summary' => 'Home: ' . $this->value, 'operationId' => 'home', ] ] ], ]; return view('livewire.display', [ 'output' => $output, 'error' => $error ?? false, 'spec' => $spec ]); } }
true
9b100778c76b8def729ab4b864e240a2937f05ec
C++
sml0399/implementation_of_algorithms
/BOJ/code/018258_queue2.cpp
UTF-8
837
3
3
[]
no_license
#include <iostream> #include <queue> #include <string> using namespace std; int main(void){ cin.tie(NULL); ios_base::sync_with_stdio(false); int num_operations,number; string oper=""; queue<int> q; cin>>num_operations; for(int i=0;i<num_operations;i++){ cin>>oper; if(oper=="push"){ cin>>number; q.push(number); }else if(oper=="pop"){ if(q.empty()) cout<<-1<<"\n"; else{ cout<<q.front()<<"\n"; q.pop(); } }else if(oper=="size"){ cout<<q.size()<<"\n"; }else if(oper=="empty"){ if(q.empty()) cout<<1<<"\n"; else cout<<0<<"\n"; }else if(oper=="front"){ if(q.empty()) cout<<-1<<"\n"; else cout<<q.front()<<"\n"; }else if(oper=="back"){ if(q.empty()) cout<<-1<<"\n"; else cout<<q.back()<<"\n"; } } return 0; }
true
31b4e9ecb2bf7d6ac2cad856eef581c0e5785029
C++
royks07/plankesorteringsanlegg-simulator-styringssystem
/PlankesorteringsAnlegg/Testbed/Tests/PlankesorteringsAnlegg/BaneSynkronisator.h
UTF-8
3,256
2.8125
3
[ "Zlib" ]
permissive
/* * BaneSynkronisator.h * * Created on: 17. nov. 2012 * Author: roy */ #ifndef BANESYNKRONISATOR_H_ #define BANESYNKRONISATOR_H_ #include <list> #include <algorithm> class BaneSensorPar{ public: BaneSensorPar(Bane* bane,FaseSensor* sensor){ m_bane=bane; m_sensor=sensor; } Bane * m_bane; FaseSensor * m_sensor; }; class BaneSynkronisator{ public: BaneSynkronisator(){ } void addBaneSensorPar(BaneSensorPar* baneSensorPar){ m_baneSensorParListe.push_back(baneSensorPar); //m_timer = new b2Timer; } void run(){ m_tellere.clear(); list<BaneSensorPar*>::iterator it; it = m_baneSensorParListe.begin(); while(it!=m_baneSensorParListe.end()){ FaseSensor* faseSensor = ((*it)->m_sensor); int teller = faseSensor->getTeller(); m_tellere.push_back(teller); it++; } m_currentHighestCount = *max_element(m_tellere.begin(),m_tellere.end()); m_currentLowestCount = *min_element(m_tellere.begin(),m_tellere.end()); cout<<"m_currentHighestCount: "<<m_currentHighestCount<<" m_currentLowestCount: "<<m_currentLowestCount<<endl; if(m_currentHighestCount!=m_currentLowestCount){ it = m_baneSensorParListe.begin(); while(it!=m_baneSensorParListe.end()){ FaseSensor* faseSensor = ((*it)->m_sensor); int teller = faseSensor->getTeller(); if(teller>=m_currentHighestCount) ((*it)->m_bane)->stop(); else ((*it)->m_bane)->start(); it++; } }else{ it = m_baneSensorParListe.begin(); while(it!=m_baneSensorParListe.end()){ FaseSensor* faseSensor = ((*it)->m_sensor); int teller = faseSensor->getTeller(); ((*it)->m_bane)->start(); it++; } } } private: //b2Timer* m_timer; list<BaneSensorPar*> m_baneSensorParListe; int m_currentHighestCount; int m_currentLowestCount; list<int> m_tellere; }; /*class BaneSynkronisator2{ public: BaneSynkronisator2(Bane* bane1,Bane* bane2,FaseSensor* sensor1,FaseSensor* sensor2){ m_bane1=bane1; m_bane2=bane2; m_sensor1=sensor1; m_sensor2=sensor2; m_timer = new b2Timer; } void run(){ float32 timeSensor1 = m_sensor1->getTime(); float32 timeSensor2 = m_sensor2->getTime(); float32 timeDiff = timeSensor2-timeSensor1; unsigned int tellerSensor1 = m_sensor1->getTeller(); unsigned int tellerSensor2 = m_sensor2->getTeller(); signed int tellerDiff = tellerSensor2-tellerSensor1; float32 speedBane1=m_bane1->getSpeed(); float32 speedBane2=m_bane2->getSpeed(); float32 speedDiff=speedBane2-speedBane1; signed int synkError; if(tellerDiff==0){ m_bane2->restart(); m_bane1->restart(); if(timeDiff>0&speedDiff>=0){ m_bane2->stop(); }else if(timeDiff<0&speedDiff<=0){ m_bane1->stop(); }else m_bane2->restart(); m_bane1->restart(); cout<<"FaseSensor timeDiff: "<<timeDiff <<" tellerDiff: "<<tellerDiff<<endl; synkError=timeDiff; }else{ if(tellerDiff>0){ m_bane2->stop(); m_bane1->restart(); }else if(tellerDiff<0){ m_bane1->stop(); m_bane2->restart(); } } } private: Bane* m_bane1; Bane* m_bane2; FaseSensor* m_sensor1; FaseSensor* m_sensor2; b2Timer* m_timer; }; */ #endif /* BANESYNKRONISATOR_H_ */
true
d1c0051954b50f384a8125ccb45f67a78ffcee8a
C++
AmiraliMohayaee/HMLite3D-Clone
/Handmade/Text.cpp
UTF-8
5,608
3.15625
3
[]
no_license
#include <glew.h> #include "ScreenManager.h" #include "PipelineManager.h" #include "Text.h" //------------------------------------------------------------------------------------------------------ //constructor that assigns all default values //------------------------------------------------------------------------------------------------------ Text::Text() { m_text = ""; m_charSpace = 0.0f; m_spriteType = DYNAMIC; //default font texture dimensions are set to 16x16 //as is setup in the Bitmap Font Builder textures m_textureDimension.x = 16; m_textureDimension.y = 16; } //------------------------------------------------------------------------------------------------------ //setter function that assigns string text to object //------------------------------------------------------------------------------------------------------ void Text::SetText(const std::string& text) { m_text = text; //offsets for VBO data loading below //buffers have different sizes GLuint offsetVert = 0; GLuint offsetColor = 0; GLuint offsetText = 0; GLuint offsetIndex = 0; glm::vec2 textureCell; //loop through the entire text string and //create buffer data for each character for (size_t i = 0; i < m_text.size(); i++) { //*********************** //vertices //*********************** //data that represents vertices for text image //they are whole number values since a pixel is whole GLuint vertices[] = { 0 + i, 1, 0, 1 + i, 1, 0, 1 + i, 0, 0, 0 + i, 0, 0 }; //fill vertex VBO and progress offset m_buffer.AppendVBO(Buffer::VERTEX_BUFFER, vertices, sizeof(vertices), offsetVert); offsetVert += sizeof(vertices); //*********************** //colors //*********************** //data that represents colors for text image //they will all be white for each letter by default GLfloat colors[] = { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; //fill color VBO and progress offset m_buffer.AppendVBO(Buffer::COLOR_BUFFER, colors, sizeof(colors), offsetColor); offsetColor += sizeof(colors); //*********************** //UVs //*********************** //the texture index is the actual ASCII value of the letter int textureIndex = m_text[i]; //use modulo and divide with the texture index to get exact column/row //index to "cut out", because with text, the texture cell is dynamic textureCell.x = (float)(textureIndex % 16); textureCell.y = (float)(textureIndex / 16); //calculate the width and height of each cell relative to the entire texture //this gives us a normalized dimension value for each "cell" in the sprite sheet glm::vec2 cellDimension(0.0625f, 0.0625f); //take the desired cell to "cut out" and multiply it by the cell's dimension value //this gives us a normalized texture coordinate value that is our "starting point" glm::vec2 texCoordOrigin = textureCell * cellDimension; //create new UV data that for our texture coordinates GLfloat UVs[] = { texCoordOrigin.x, texCoordOrigin.y, texCoordOrigin.x + cellDimension.x, texCoordOrigin.y, texCoordOrigin.x + cellDimension.x, texCoordOrigin.y + cellDimension.y, texCoordOrigin.x, texCoordOrigin.y + cellDimension.y }; //fill UV VBO and progress offset m_buffer.AppendVBO(Buffer::TEXTURE_BUFFER, UVs, sizeof(UVs), offsetText); offsetText += sizeof(UVs); //*********************** //indices //*********************** //data that represents indeces for text image GLuint indices[] = { 0 + 4 * i, 1 + 4 * i, 3 + 4 * i, 3 + 4 * i, 1 + 4 * i, 2 + 4 * i }; //fill UV VBO and progress offset m_buffer.AppendEBO(indices, sizeof(indices), offsetIndex); offsetIndex += sizeof(indices); } } //------------------------------------------------------------------------------------------------------ //setter function that assigns spacing size between text letters //------------------------------------------------------------------------------------------------------ void Text::SetCharSpace(GLfloat charSpace) { m_charSpace = charSpace; } //------------------------------------------------------------------------------------------------------ //function that creates and fills all buffers with vertex and color data //------------------------------------------------------------------------------------------------------ bool Text::Create(const std::string bufferID) { //create VAO, VBOs and EBO and if there is an error //it means the buffer has already been created in memory if (!m_buffer.CreateBuffers(bufferID, 1000, true)) { return false; } //bind EBO and all VBOs and shader attributes together with VAO m_buffer.BindEBO(); m_buffer.BindVBO(Buffer::VERTEX_BUFFER, "vertexIn", Buffer::XYZ, Buffer::U_INT); m_buffer.BindVBO(Buffer::COLOR_BUFFER, "colorIn", Buffer::RGB, Buffer::FLOAT); m_buffer.BindVBO(Buffer::TEXTURE_BUFFER, "textureIn", Buffer::UV, Buffer::FLOAT); //fill vertex and color VBOs with data m_buffer.FillEBO((GLuint*)nullptr, 10000, Buffer::DYNAMIC_FILL); m_buffer.FillVBO(Buffer::VERTEX_BUFFER, (GLfloat*)nullptr, 10000, Buffer::DYNAMIC_FILL); m_buffer.FillVBO(Buffer::COLOR_BUFFER, (GLfloat*)nullptr, 10000, Buffer::DYNAMIC_FILL); m_buffer.FillVBO(Buffer::TEXTURE_BUFFER, (GLfloat*)nullptr, 10000, Buffer::DYNAMIC_FILL); return true; }
true
05dba6220190eaaf6d96cea2fe5af0af98d2a334
C++
Morcki/DataStructureTest
/MySTD/LinkHeap.h
UTF-8
1,131
3.296875
3
[]
no_license
#pragma once #ifndef LINKHEAP_H #define LINKHEAP_H template<class T,typename Tw> class HNode { T value; Tw weight; HNode<T,Tw>* left; HNode<T,Tw>* right; HNode() :value(0),weight(0) left(0), right(0) {}; HNode(T data.Tw w) :value(data), weight(w), left(0), right(0) {}; ~HNode() { delete left; delete right; }; }; template<class T,typename Tw> class MaxHeap // not completed yet { public: MaxHeap(); ~MaxHeap(); bool empty(); void insert(T value,Tw w); HNode<T,Tw>* Max(); HNode<T,Tw>* delMax(); private: HNode<T,Tw> *root; int size; void swim(HNode<T,Tw> *p); void sink(HNode<T, Tw> *p); }; template<class T, typename Tw> MaxHeap<T,Tw>::MaxHeap() { root = 0; size = 0; } template<class T, typename Tw> MaxHeap<T,Tw>::~MaxHeap() { delete root; } template<class T, typename Tw> inline bool MaxHeap<T, Tw>::empty() { return size > 0 ? 0 : 1; } template<class T, typename Tw> void MaxHeap<T,Tw>::insert(T value,Tw w) { HNode<T,Tw>* node = new HNode<T,Tw>(value, w); if (!root) { root = node; return; } } template<class T, typename Tw> void MaxHeap<T, Tw>::swim(HNode<T, Tw> *p) { } #endif // !LINKHEAP_H
true
1a8269047d6a009686e716ca5eb10b044237fc80
C++
HowLeeHi/Reciter
/worditem.cpp
UTF-8
1,786
3.28125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include "worditem.h" using namespace std; WordItem::WordItem() { } WordItem::~WordItem() { } ofstream & operator <<(ofstream & ofs, WordItem & wl) { ofs << wl.word << endl << wl.part_of_speech << endl << wl.meaning << endl << wl.example << endl << wl.example_meaning << endl << endl; return ofs; } ifstream & operator >>(ifstream & ifs, WordItem & wl) { getline(ifs, wl.word); getline(ifs, wl.part_of_speech); getline(ifs, wl.meaning); getline(ifs, wl.example); getline(ifs, wl.example_meaning); ifs.get(); return ifs; } ostream & operator <<(ostream & os, WordItem & wl) { if (wl.word == "") { os << "<暂无拼写>"; } else { os << wl.word; } os << endl; if (wl.part_of_speech == "") { os << "<暂无词性>"; } else { os << wl.part_of_speech; } os << endl; if (wl.meaning == "") { os << "<暂无中文释义>"; } else { os << wl.meaning; } os << endl; if (wl.example == "") { os << "<暂无例句>"; } else { os << wl.example; } os << endl; if (wl.example_meaning == "") { os << "<暂无例句翻译>"; } else { os << wl.example_meaning; } os << endl << endl; return os; } istream & operator >>(istream & is, WordItem & wl) { cout << "单词拼写:"; getline(is, wl.word); cout << "单词词性:"; getline(is, wl.part_of_speech); cout << "中文释义:"; getline(is, wl.meaning); cout << "例句:"; getline(is, wl.example); cout << "例句翻译:"; getline(is, wl.example_meaning); return is; }
true
e05b328b9fe4c9f352211c75c8701822e4d3f40c
C++
chillpert/matrix
/matrix/src/platform/gui/editor/Editor_Console.cpp
UTF-8
4,548
2.59375
3
[]
no_license
#include "Editor_Console.h" #include "Logger.h" namespace MX { Editor_Console::Editor_Console(const char* name, ImGuiWindowFlags flags) { initialize(name, flags); } bool Editor_Console::initialize(const char* name, ImGuiWindowFlags flags) { m_clear_popup.initialize("Warning##Clear Console", ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove); return ImGui_Window::initialize(name, flags); } bool Editor_Console::update() { return ImGui_Window::update(); } void Editor_Console::render() { if (ImGui_Window::begin()) { static bool fully_colored = false; static bool messages_info = true; static bool messages_warn = true; static bool messages_fatal = true; static bool messages_success = true; if (ImGui::BeginMenuBar()) { if (ImGui::BeginMenu("Type")) { ImGui::MenuItem("Info", NULL, &messages_info); ImGui::MenuItem("Warn", NULL, &messages_warn); ImGui::MenuItem("Success", NULL, &messages_success); ImGui::MenuItem("Fatal", NULL, &messages_fatal); ImGui::Separator(); if (ImGui::MenuItem("Reset")) { messages_info = true; messages_warn = true; messages_fatal = true; messages_success = true; } ImGui::EndMenu(); } if (ImGui::BeginMenu("Color")) { ImGui::MenuItem("All", NULL, &fully_colored); ImGui::EndMenu(); } ImGui::EndMenuBar(); } static ImGuiTextFilter filter; float avail_width = ImGui::GetContentRegionAvailWidth(); filter.Draw("##console filter label", avail_width * 4.0f / 5.0f); ImGui::SameLine(); if (ImGui::Button("Clear##Confirm Clear Console Button", ImVec2(avail_width / 5.0f - 8.0f, 0.0f))) m_clear_popup.open(); ImGui::Separator(); for (auto &it : Logger::get_messages_gui()) { if (filter.PassFilter(it.first.c_str())) { switch (it.second) { case mx_info: { if (!messages_info) break; else { if (fully_colored) ImGui::TextColored(ImVec4(1.0f, 1.0f, 1.0f, 1.0f), it.first.c_str()); else ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), it.first.c_str()); break; } } case mx_warn: { if (!messages_warn) break; else { if (fully_colored) ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), it.first.c_str()); else ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), it.first.c_str()); break; } } case mx_fatal: { if (!messages_fatal) break; else { if (fully_colored) ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), it.first.c_str()); else ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), it.first.c_str()); break; } } case mx_success: { if (!messages_success) break; else { if (fully_colored) ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), it.first.c_str()); else ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), it.first.c_str()); break; } } default: break; } } } } // clear console confirmation popup if (m_clear_popup.begin()) { ImGui::Text("Do you really want to clear the console?"); ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); float avail_width = ImGui::GetContentRegionAvailWidth(); if (ImGui::Button("Yes", ImVec2(avail_width / 2.0f - 5.0f, 0.0f))) { ImGui::CloseCurrentPopup(); Logger::get_messages_gui().clear(); } ImGui::SameLine(); if (ImGui::Button("No", ImVec2(avail_width / 2.0f - 5.0f, 0.0f))) ImGui::CloseCurrentPopup(); m_clear_popup.end(); } ImGui_Window::end(); } }
true
53aeb6537581d56b2b30fb5e670b575ca7020241
C++
arunsiddharth/ESPHA
/ESP8266_BASE/setup_ESP.ino
UTF-8
3,330
2.578125
3
[]
no_license
boolean setup_ESP(){ //Send AT to check it ESP8266.print("AT\r\n"); if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0))//go look for keyword "OK" with a 5sec timeout Serial.println("ESP CHECK OK"); else Serial.println("ESP CHECK FAILED"); serial_dump_ESP();//this just reads everything in the buffer and what's still coming from the ESP // Start fresh ESP8266.print("AT+RST\r\n"); if(read_until_ESP(keyword_Ready,sizeof(keyword_Ready),7000,0))//go look for keyword "Ready" Serial.println("ESP RESET OK");//depneding on the FW version on the ESP, sometimes the Ready is with a lowercase r - ready else Serial.println("ESP RESET FAILED"); serial_dump_ESP(); //Set CWMODE ESP8266.print("AT+CWMODE=");// set the CWMODE ESP8266.print(CWMODE);//just send what is set in the constant ESP8266.print("\r\n"); if(read_until_ESP(keyword_OK,sizeof(keyword_OK),5000,0))//go look for keyword "OK" Serial.println("ESP CWMODE SET"); else Serial.println("ESP CWMODE SET FAILED"); //probably going to fail, since a 'no change' is returned if already set serial_dump_ESP(); //Here's where the SSID and PW are set ESP8266.print("AT+CWJAP=\"");// set the SSID AT+CWJAP="SSID","PW" ESP8266.print(SSID_ESP);//from constant ESP8266.print("\",\""); ESP8266.print(SSID_KEY);//form constant ESP8266.print("\"\r\n"); if(read_until_ESP(keyword_OK,sizeof(keyword_OK),10000,0))//go look for keyword "OK" Serial.println("ESP SSID SET OK"); else Serial.println("ESP SSID SET FAILED"); serial_dump_ESP(); //This checks for and stores the IP address Serial.println("CHECKING FOR AN IP ADDRESS"); ESP8266.print("AT+CIFSR\r\n");//command to retrieve IP address from ESP if(read_until_ESP(keyword_rn,sizeof(keyword_rn),10000,0)){//look for first \r\n after AT+CIFSR echo - note mode is '0', the ip address is right after this if(read_until_ESP(keyword_rn,sizeof(keyword_rn),7000,1)){//look for second \r\n, and store everything it receives, mode='1' //store the ip adress in its variable, ip_address[]+'/r/n' for(int i=1; i<=(scratch_data_from_ESP[0]-sizeof(keyword_rn)+1); i++) ip_address[i] = scratch_data_from_ESP[i]; //i=1 because i=0 is the length of the data found between the two keywords, BUT this includes the length of the second keyword, so i<= to the length minus //size of the keyword, but remember, sizeof() will return one extra, which is going to be subtracted, so I just added it back in +1 ip_address[0] = (scratch_data_from_ESP[0]-sizeof(keyword_rn)+1);//store the length of ip_address in [0], same thing as before Serial.print("IP ADDRESS = ");//print it off to verify for(int i=1; i<=ip_address[0]; i++)//send out the ip address Serial.print(ip_address[i]); Serial.println(""); } }//if first \r\n else Serial.print("IP ADDRESS FAIL"); serial_dump_ESP(); ESP8266.print("AT+CIPMUX=");// set the CIPMUX ESP8266.print(CIPMUX);//from constant ESP8266.print("\r\n"); if(read_until_ESP(keyword_OK,sizeof(keyword_OK),15000,0))//go look for keyword "OK" or "no change Serial.println("ESP CIPMUX SET"); else Serial.println("ESP CIPMUX SET FAILED"); serial_dump_ESP(); }//setup ESP
true
c3ce7e290fe872ce845a90de50ae21307ef740ce
C++
vaniugata/OnTargetEGT2017
/04.xml-Student/src/Student.cpp
UTF-8
2,731
3.21875
3
[]
no_license
#include "Student.h" #include <sstream> Student::Student(const std::string& firstName, const std::string& lastName, const std::string& gender, const std::string& birthday, const std::string& phoneNumber, const std::string& email, int course, const std::string& speciality, long int facultyNumber, const std::vector<Exam*>& exams) { setFirstName(firstName); setLastName(lastName); setGender(gender); setPhoneNumber(phoneNumber); setBirthday(birthday); setEmail(email); setCourse(course); setSpeciality(speciality); setFacultyNumber(facultyNumber); setExams(exams); } const std::string& Student::getBirthday() const { return _birthday; } int Student::getCourse() const { return _course; } const std::string& Student::getEmail() const { return _email; } long int Student::getFacultyNumber() const { return _facultyNumber; } const std::string& Student::getFirstName() const { return _firstName; } const std::string& Student::getGender() const { return _gender; } const std::string& Student::getLastName() const { return _lastName; } const std::string& Student::getPhoneNumber() const { return _phoneNumber; } const std::string& Student::getSpeciality() const { return _speciality; } const std::vector<Exam*>& Student::getExams() const { return exams; } void Student::setBirthday(const std::string& birthday) { _birthday = birthday; } void Student::setCourse(int course) { _course = course; } void Student::setEmail(const std::string& email) { _email = email; } void Student::setFacultyNumber(long int facultyNumber) { _facultyNumber = facultyNumber; } void Student::setFirstName(const std::string& firstName) { _firstName = firstName; } void Student::setGender(const std::string& gender) { _gender = gender; } void Student::setLastName(const std::string& lastName) { _lastName = lastName; } void Student::setPhoneNumber(const std::string& phoneNumber) { _phoneNumber = phoneNumber; } void Student::setSpeciality(const std::string& speciality) { _speciality = speciality; } void Student::setExams(const std::vector<Exam*>& exams) { this->exams = exams; } Student::~Student() { // TODO Auto-generated destructor stub } std::string Student::print() const { std::stringstream result; result << getFirstName() << "\t" << getLastName() << "\n" << getGender() << "\n" << getBirthday() << "\n" << getPhoneNumber() << "\n" << getEmail() << "\n" << getSpeciality() << "\n" <<getFacultyNumber() << "\n" << "Exams:\n"; std::vector<Exam*>::const_iterator exam; for (exam = getExams().begin(); exam != getExams().end(); exam++) { result << (*exam)->print(); } return result.str(); } void Student::addExam(Exam& exam) { this->exams.push_back(&exam); }
true
43b470b3fd19b98b9d266b3759166bf72091ac4f
C++
KhandokerEbrahim/OOP
/lab 2.cpp
UTF-8
904
2.875
3
[]
no_license
// singlelab 2.cpp #include<iostream> using namespace std; int n,i; struct roo { double length; double width; } room[1000]; struct dis { double ft; double inch; char dumycah; } distance[1000]; void input() { for(i=1; i<=n; i++) { cout <<"ENTER " <<i<<"th room length" <<endl; cin >> distance[i].ft >> distance[i].dumycah >> distance[i].inch; room[i].length=distance[i].ft+ .83*distance[i].inch; cout <<"ENTER " <<i<<"th room width" <<endl; cin >> distance[i].ft >> distance[i].dumycah>>distance[i].inch; room[i].width = distance[i].ft+ .8333*distance[i].inch; } } void output() { for(i=1; i<=n; i++) { cout << "Size of " << i <<"th room = "<<room[i].width * room[i].length<<""<<endl; } } int main() { cout <<"ENTER NUMBER OF ROOM"<<endl; cin >>n; input(); output(); }
true
f01a9cf75ff4af2e5c5bc3106632328d28170a96
C++
JesusPacheco19/Programaci-n-II
/Sars.h
WINDOWS-1250
1,346
2.65625
3
[]
no_license
#pragma once #include"Virus.h" class Sars:public Virus { public: Sars(bool fiebre = 0, bool tos = 0, bool disnea = 0, bool escalofrios = 0, bool dolorMuscular = 0, bool dolorCabeza = 0, bool diarrea = 0) :Virus(fiebre, tos, disnea) { this->escalofrios = escalofrios; this->dolorMuscular = dolorMuscular; this->dolorCabeza = dolorCabeza; } void setEscalofrios (bool x){ escalofrios =x;} void setDolorMuscular (bool x){ dolorMuscular =x;} void setDolorCabeza (bool x){ dolorCabeza =x;} bool getEscalofrios() { return escalofrios; } bool getDolorMuscular() { return dolorMuscular; } bool getDolorCabeza() { return dolorCabeza; } bool Resultado() { if (fiebre == 1 && tos == 1 && disnea == 1 && escalofrios == 1 && dolorMuscular == 1&&dolorCabeza==1) return true; else return false; } void ReportePositivo() { cout << "el virus <Sars> " << endl; cout << "<Debe aislarse por precaucin>:SI " << endl; cout << "<Es paciente de alto riesgo>:Si" << endl; } void ReporteNegatico() { cout << "el virus <Sars> " << endl; cout << "<Debe aislarse por precaucin>:NO " << endl; cout << "<Es paciente de alto riesgo>:No" << endl; } ~Sars() {} private: bool escalofrios; bool dolorMuscular; bool dolorCabeza; };
true
10999673b34f76c9ecafa97af8a7c2fa0f82a9c2
C++
chelseali2001/CS162-Introduction-to-Computer-Science-II
/Labs/Lab 7/shape.cpp
UTF-8
411
3.015625
3
[]
no_license
#include <iostream> #include <string> #include <cmath> #include <stdexcept> #include <exception> #include "./shape.h" using namespace std; Shape::Shape(string n, string c) { this->name = n; this->color = c; } void Shape::print_shape_info(Shape &shape) { cout << "Shape name: " << shape.name <<endl; cout << "Shape color: " << shape.color <<endl; cout << "Shape area: " << area() <<endl; }
true
6791283f7987a3ebcee90baee7322def58b1e973
C++
snogglethorpe/compiler-algo
/fun-text-reader.cc
UTF-8
3,561
2.890625
3
[]
no_license
// fun-text-reader.cc -- Text-format input of an IR function // // Copyright © 2019 Miles Bader // // Author: Miles Bader <snogglethorpe@gmail.com> // Created: 2019-11-03 // #include <stdexcept> #include "fun.h" #include "reg.h" #include "value.h" #include "cond-branch-insn.h" #include "nop-insn.h" #include "calc-insn.h" #include "copy-insn.h" #include "fun-arg-insn.h" #include "fun-result-insn.h" #include "src-file-input.h" #include "prog-text-reader.h" #include "fun-text-reader.h" FunTextReader::FunTextReader (ProgTextReader &prog_reader) : _prog_reader (prog_reader) { } // Return the text input source we're reading from. // SrcFileInput & FunTextReader::input () const { return _prog_reader.input (); } // Read a text representation of a function, and return the new // function. // Fun * FunTextReader::read () { // We need to be in line-oriented mode. // input ().set_line_oriented (true); // Cannot be called recursively. // if (cur_fun) throw std::runtime_error ("Recursive call to FunTextReader::read"); Fun *fun = new Fun (); cur_fun = fun; cur_block = fun->entry_block (); parse_fun (); cur_fun = 0; cur_block = 0; // Clear any left over parsing state. // clear_state (); return fun; } // Read a block label. // BB * FunTextReader::read_label () { SrcFileInput &inp = input (); inp.skip ('<'); return label_block (inp.read_delimited_string ('>')); } // Read a register (which must exist). // Reg * FunTextReader::read_lvalue_reg () { return get_reg (input ().read_id ()); } // Return the register (which must exist) called NAME // Reg * FunTextReader::get_reg (const std::string &name) { auto reg_it = registers.find (name); if (reg_it == registers.end ()) input ().error (std::string ("Unknown register \"") + name + "\""); return reg_it->second; } // Read a comma-separated list of lvalue registers, as for // FunTextReader::read_lvalue_reg, and return them as a vector. // std::vector<Reg *> FunTextReader::read_lvalue_reg_list () { std::vector<Reg *> regs; do regs.push_back (read_lvalue_reg ()); while (input ().skip (',')); return regs; } // Read either a register (which must exist), or a constant value // (which will be added to the current function if necessary), and // return the resulting register. // Reg * FunTextReader::read_rvalue_reg () { SrcFileInput &inp = input (); inp.skip_whitespace (); if (inp.is_id_start_char (inp.peek ())) { return read_lvalue_reg (); } else { int int_value = inp.read_int (); for (auto existing_value_reg : cur_fun->regs ()) if (existing_value_reg->is_constant () && existing_value_reg->value ()->int_value () == int_value) return existing_value_reg; return new Reg (new Value (int_value, cur_fun)); } } // Read a comma-separated list of rvalue registers, as for // FunTextReader::read_rvalue_reg, and return them as a vector. // std::vector<Reg *> FunTextReader::read_rvalue_reg_list () { std::vector<Reg *> regs; do regs.push_back (read_rvalue_reg ()); while (input ().skip (',')); return regs; } // Clear any parsing state used while parsing a function. // void FunTextReader::clear_state () { labeled_blocks.clear (); } // Return the block corresponding to the label LABEL. If no such // label has yet been encountered, a new block is added and returned. // BB * FunTextReader::label_block (const std::string &label) { BB *&block_ptr = labeled_blocks[label]; if (! block_ptr) block_ptr = new BB (cur_fun); return block_ptr; }
true
a96f4c9ad299066b4df53f8242cc00de56dd124b
C++
lazymonday/PS
/atcoder/abc_155/main.cpp
UTF-8
1,345
2.84375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; typedef long long ll; const int MAX = 2e5; int a[MAX + 1]; ll n, k; bool lessThanK(ll x, ll k) { ll skip = 0; for (int i = 0; i < n; ++i) { if (a[i] < 0) { int l = -1, h = n; while (l + 1 < h) { int m = l + (h - l) / 2; if (1ll * a[i] * a[m] < x) { h = m; } else { l = m; } } skip += n - h; } else { int l = -1, h = n; while (l + 1 < h) { int m = l + (h - l) / 2; if (1ll * a[i] * a[m] < x) { l = m; } else { h = m; } } skip += h; } if (1ll * a[i] * a[i] < x) skip--; } skip /= 2; return skip < k; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> k; for (int i = 0; i < n; ++i) { cin >> a[i]; } sort(a, a + n); ll lo = ll(-1e18); ll hi = ll(1e18) + 1; while (lo < hi) { ll x = lo + (hi - lo) / 2; if (lessThanK(x, k)) { lo = x + 1; } else { hi = x; } } cout << lo - 1; return 0; }
true
eaa1121147c0209e1ebe8f537122b962f5c5a15b
C++
Jmiceli17/ASEN5519
/Homework1/src/rect_obstacle.hpp
UTF-8
648
2.5625
3
[]
no_license
/* * rect_obstacle.hpp * * Created on: Sep 18, 2020 * Author: Joe */ #ifndef RECT_OBSTACLE_HPP_ #define RECT_OBSTACLE_HPP_ #include <vector> #include <cmath> #include <iostream> #include <windows.h> class rect_obstacle { public: // Member variables to store the locations of the obstacles vertices std::vector<double> v1; std::vector<double> v2; std::vector<double> v3; std::vector<double> v4; rect_obstacle(); rect_obstacle(std::vector<double> vertex1, std::vector<double> vertex2, std::vector<double> vertex3, std::vector<double> vertex4); // default destructor ~rect_obstacle(); }; #endif /* RECT_OBSTACLE_HPP_ */
true
2c1dfa79b2aa89fd12826bbfcc362ecd37fa25d7
C++
ibasanta69/C-programming-all-problems-solved-codes-Beignners-
/Enter 10 num in array.cxx
UTF-8
349
3.203125
3
[]
no_license
//The program is Coded By Basanta Chaudhary /* wap to enter in array and display */ #include <stdio.h> #include <conio.h> int main() { int a[10], i; printf("Enter any Ten numbers:"); for (i = 0; i < 5; i++) { scanf("%d", &a[i]); } printf("You have entered 5 numbers!!"); for (i = 0; i < 5; i++) { printf("\n[%d]=%d", i, a[i]); } return 0; }
true
8ed18d3c0df2d7368be2e6da4f41365fb72ba025
C++
elbaum/phys
/data/schunk_canopen_driver/src/icl_hardware_canopen/src/icl_hardware_canopen/PDO.h
UTF-8
10,583
2.890625
3
[ "MIT", "BSD-2-Clause" ]
permissive
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- // -- BEGIN LICENSE BLOCK ---------------------------------------------- // This file is part of the SCHUNK Canopen Driver suite. // // This program is free software licensed under the LGPL // (GNU LESSER GENERAL PUBLIC LICENSE Version 3). // You can find a copy of this license in LICENSE folder in the top // directory of the source code. // // © Copyright 2016 SCHUNK GmbH, Lauffen/Neckar Germany // © Copyright 2016 FZI Forschungszentrum Informatik, Karlsruhe, Germany // -- END LICENSE BLOCK ------------------------------------------------ //---------------------------------------------------------------------- /*!\file * * \author Georg Heppner <heppner@fzi.de> * \author Felix Mauch <mauch@fzi.de> * \date 2015-10-1 * */ //---------------------------------------------------------------------- #ifndef PDO_H #define PDO_H #include <boost/shared_ptr.hpp> #include <vector> #include "helper.h" #include "SDO.h" namespace icl_hardware { namespace canopen_schunk { /*! * \brief The PDO class provides access to one (of the possible multiple) Process Data Object of a canOpen node. The class provides structures for transmit and received data and the functions to trigger down- and uploads * * The class implements PDO access by providing data structures for the userdata and interfaces to trigger a down and upload. These functions will be called * periodically in order to transmit userdata to the actual devices and vice versa. The Class also offers the functionality to trigger a PDO remap which is done during * the setup phase of the devices. A node may hold 1-4 PDOs in the standard case but up to 512 in the extended case. */ class PDO { public: /*! * \brief Mapping of a PDO. This is basically a description that says where to look in the object * dictionary and how many bits to read * \note the \a length attribute describes the data length in Bits, not Bytes. An unsigned32 * for example will be of length 0x20. */ struct MappingConfiguration { uint16_t index; uint8_t subindex; uint8_t length; std::string name; /*! * \brief MappingConfiguration Create a new mapping configuration entry * \param index_ Object Dictionary Index * \param subindex_ Object Dictionary Sub-Index * \param length_ length in BITS not bytes. For exammple: An unsigned32 will have the length of 0x20 * \param name_ Arbitrary name to identify and acces the pdo mapped value later on (for example: "speed") */ MappingConfiguration (const uint16_t index_, const uint8_t subindex_, const uint8_t length_, const std::string& name_) : index(index_), subindex(subindex_), length(length_), name(name_) {} }; //! The MappingConfigurationList holds multiple Mapping configurations. The Mapping of a single PDO is defined by one such configuration list typedef std::vector<MappingConfiguration> MappingConfigurationList; /*! * \brief Holds the mapping parameter plus the actual data. * * The Mapping of the PDO contains mapping information and data at the same time * Each PDO Stores a mapping configuration containing the individual entries of the PDO to transmit or Receive * These entries can be referenced by name so the user is able to get a specific value of the PDO by referring to it * by name. The Actuall data is stored in the data vector if the Mapping object. * This vector contains the data of all values mapped on this pdo in sequenc of their entries in the * Mapping Configurarion. Each PDO may transmit or receive up to 8 bytes of data. * The Mapping may be appended at a later time or completely destroyed with a new mapping. * \note Remapping of PDOs is only allowed if the NMT State is in pre operational. */ class Mapping { public: /*! * \brief Mapping Creates a new mapping that stores the mapping information and the mapped data * \param mapping_configuration_ Description of the values to map */ Mapping (const MappingConfiguration& mapping_configuration_) : mapping_configuration ( mapping_configuration_ ) { data.resize( mapping_configuration.length / 8, 0); } //! Actual data of the PDO is stored in this data vector std::vector<uint8_t> data; /*! * \brief getConfiguration Returns the current mapping configuration of the PDO * \return Currently active mapping configuration */ MappingConfiguration getConfiguration() const { return mapping_configuration;} private: MappingConfiguration mapping_configuration; }; typedef std::vector<Mapping> MappingList; /*! * \brief Unique index to find a mapped Object dictionary item in a PDO. * * The \a name String identifier of the mapped register * The \a pdo_mapping_index Internal vector index inside the PDO. */ struct PDOStringMatch { std::string name; uint8_t pdo_mapping_index; }; typedef std::vector<PDOStringMatch> PDOStringMatchVec; //! Transmission types of a PDO, needed when mapping PDOs enum eTransmissionType { SYNCHRONOUS_ACYCLIC = 0, RTR_ONLY_SYNCHRONOUS = 252, RTR_ONLY_EVENT_DRIVEN = 253, EVENT_DRIVEN_MANUFACTURER_SPECIFIC = 254, EVENT_DRIVEN_PROFILE_SPECIFIC = 255, SYNCHRONOUS_CYCLIC = 1 // Note: There are many many more synchronous cyclic variants but as they are easily calculated we omit having enums for them }; //! Convenience typedef to use PDOs with shared pointers typedef boost::shared_ptr<PDO> Ptr; //! Convenience typedef to use PDO lists with shared pointers typedef std::vector<boost::shared_ptr<PDO> > PtrList; /*! * \brief Construct a new PDO * * \param node_id ID of the node this PDO belongs to * \param pdo_nr numbering of this PDO inside the node * \param can_device handle to the CAN device */ PDO(const uint8_t node_id, const uint8_t pdo_nr, const CanDevPtr& can_device); /*! * \brief Configure a PDO by sending some SDO packages. This can be either done during * NMT state pre-operational or during the NMT state Operational. * If an empty mapping is given, we leave the mapping as is. * * \note Do not call this method by hand, but use the wrapper functions in the DS301Node class. * Otherwise the node will not know of the new mapping and won't be able to find a PDO by it's * identifier string. * * \param sdo Handle to the SDO object * \param mappings List of MappingConfigurations that should be mapped into this PDO * \param transmission_type Transmission type of this PDO * \param pdo_cob_id CANOPEN-ID of this pdo * \param pdo_communication_parameter object dictionary entry of this pdo's communication parameter * \param pdo_mapping_parameter object dictionary entry of this pdo's mapping parameter * \param dummy_mapping if set to True, no download to the device will be performed, but * the mapping will be done on host side. This is especially useful if a device has preconfigured * PDOs which you like to use. * \param cyclic_timeout_cycles If the transmission type SYNCHRONOUS_CYCLIC is used, this * parameter defines the PDO's frequency by defining the number of cycles between two send * attempts. For example, a parameter value of 4 means, that the PDO is sent every 5th cycle. * \throws PDOException when an error occurs or an exception is thrown in an underlying * structure like SDO communication. * \return PDOStringMatchVec Vector of string to vec_index matchings. If an error occurs, * the returned vector will be empty. */ PDOStringMatchVec remap (SDO& sdo, const MappingConfigurationList& mappings, const eTransmissionType& transmission_type, const uint16_t pdo_cob_id, const uint16_t pdo_communication_parameter, const uint16_t pdo_mapping_parameter, const bool dummy_mapping = false, const uint8_t cyclic_timeout_cycles = 0); /*! * \brief Appends one or more mapping parameters to the existing mapping. Note that the PDO will * be disabled while appending another mapping. * * \note Do not call this method by hand, but use the wrapper functions in the DS301Node class. * Otherwise the node will not know of the new mapping and won't be able to find a PDO by it's * identifier string. * * \param sdo Handle to the SDO object * \param mappings List of MappingConfigurations that should be mapped into this PDO * \param transmission_type Transmission type of this PDO * \param pdo_cob_id CANOPEN-ID of this pdo * \param pdo_communication_parameter object dictionary entry of this pdo's communication parameter * \param pdo_mapping_parameter object dictionary entry of this pdo's mapping parameter * \param dummy_mapping if set to True, no download to the device will be performed, but * the mapping will be done on host side. This is especially useful if a device has preconfigured * PDOs which you like to use. * \param cyclic_timeout_cycles If the transmission type SYNCHRONOUS_CYCLIC is used, this * parameter defines the PDO's frequency by defining the number of cycles between two send * attempts. For example, a parameter value of 4 means, that the PDO is sent every 5th cycle. * \throws PDOException when an error occurs or an exception is thrown in an underlying * structure like SDO communication. * \return PDOStringMatchVec Vector of string to vec_index matchings. If an error occurs, * the returned vector will be empty. */ PDOStringMatchVec appendMapping(SDO& sdo, const MappingConfigurationList& mappings, const eTransmissionType& transmission_type, const uint16_t pdo_cob_id, const uint16_t pdo_communication_parameter, const uint16_t pdo_mapping_parameter, const bool dummy_mapping = false, const uint8_t cyclic_timeout_cycles = 0); //! List of all mappings inside this PDO MappingList m_mapping_list; protected: //! CANOPEN ID of the node this PDO belongs to uint8_t m_node_id; //! The PDO number inside the logical device. Theoretically this can be in 0 to 511 uint8_t m_pdo_nr; //! Can Device handle CanDevPtr m_can_device; }; }}// end of NS #endif // PDO_H
true
95c82a4ca09c7b42b49d1718d243d829a941501b
C++
naccuracy/3d-maze-shooter
/game_engine_cdb/src/3D/point3f.h
UTF-8
787
3.078125
3
[]
no_license
#ifndef POINT3F_H #define POINT3F_H class Point3f { public: Point3f(const Point3f &p);//copy constructor Point3f(float x = 0.0, float y = 0.0, float z = 0.0);//constructor ~Point3f(); float data[4];//data data[0] = x data[1]= y data[2] = z data[3] = w; void operator=(const Point3f& p); Point3f operator+(const Point3f& p); Point3f operator-(const Point3f& p); Point3f operator*(float a); bool operator==(const Point3f& p); bool operator>(const Point3f& p); bool operator<(const Point3f& p); bool operator!=(const Point3f& p); float operator[](int i); float length(void);//return length of vector void normalize(void);//set vector length = 1 float dotProduct(const Point3f& p);//calculate dot product Point3f crossProduct(const Point3f &p);//cross product }; #endif
true
f96da2c4d3761bc26001be4106be450b2b46eb94
C++
xuguocong/LeetCodeAnswer
/leetCodemianshi/140.cpp
UTF-8
2,711
3.265625
3
[]
no_license
// 140. 单词拆分 II // 给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。 // 说明: // 分隔时可以重复使用字典中的单词。 // 你可以假设字典中没有重复的单词。 // 示例 1: // 输入: // s = "catsanddog" // wordDict = ["cat", "cats", "and", "sand", "dog"] // 输出: // [ // "cats and dog", // "cat sand dog" // ] // 示例 2: // 输入: // s = "pineapplepenapple" // wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] // 输出: // [ // "pine apple pen apple", // "pineapple pen apple", // "pine applepen apple" // ] // 解释: 注意你可以重复使用字典中的单词。 // 示例 3: // 输入: // s = "catsandog" // wordDict = ["cats", "dog", "sand", "and", "cat"] // 输出: // [] #include<iostream> #include<unordered_map> #include<vector> #include<string> #include<algorithm> #include<stack> #include<queue> #include<string.h> #include<unordered_set> using namespace std; class Solution { public: vector<string> wordBreak_dp(string s, vector<string>& wordDict) { if(!wordBreak139(s, wordDict)) return {}; int validEnd = 0; vector<vector<string>> dp(s.length() + 1, vector<string>()); for(int i = 0; i < s.length(); ++i) { if(i != 0 && dp[i].empty()) continue; for(auto& word : wordDict) { int newEnd = i + word.size(); if(newEnd > s.size()) continue; if(memcmp(&s[i], &word[0], word.size()) != 0) continue; validEnd = max(validEnd, newEnd); if(i == 0) { dp[newEnd].push_back(word); continue; } for(auto& w : dp[i]) { dp[newEnd].push_back(w + " " + word); } } } return dp.back(); } bool wordBreak139(string &s, vector<string>& wordDict) { int validEnd = 0; vector<bool> dp(s.length() + 1, false); dp[0] = true; for(int i = 0; i < s.length(); ++i) { if(i == validEnd + 1) return false; if(!dp[i]) continue; for(auto& word : wordDict) { int newEnd = i + word.size(); if(newEnd > s.size()) continue; if(memcmp(&s[i], &word[0], word.size()) == 0) { dp[newEnd] = true; validEnd = max(validEnd, newEnd); } } } return dp.back(); } }; int main() { Solution test; return 0; }
true
12d9645c4a5cbd66e85e262d69b22f35ea29a110
C++
jeffcore/intro-self-driving-cars-udacity
/Exercises/robot-localization/main.cpp
UTF-8
1,861
3.21875
3
[]
no_license
#include <iostream> #include <vector> #include<numeric> using namespace std; vector<float> sense(vector<float> p, string Z, vector<string> world, float pHit, float pMiss) ; vector<float> move(vector<float> p, int U); int main() { vector<float> p (5, 0.2); vector<string> world (5); world[0] = "green"; world[1] = "red"; world[2] = "red"; world[3] = "green"; world[4] = "green"; vector<string> measurements (2); measurements[0] = "red"; measurements[1] = "green"; vector<int> motions (2, 1); float pHit = 0.6; float pMiss = 0.2; for (int i = 0; i < measurements.size(); i++) { p = sense(p, measurements[i], world, pHit, pMiss); p = move(p, motions[i]); } for (int i = 0; i < p.size(); i++) { cout << p[i] << endl; } return 0; } vector<float> sense(vector<float> p, string Z, vector<string> world, float pHit, float pMiss) { vector<float> q (5); int hit; float sum; for (int i = 0; i < p.size(); i++) { if (Z == world[i]) { hit = 1; } else { hit = 0; } q[i] = (p[i] * (hit * pHit + (1-hit) * pMiss)); } sum = accumulate(q.begin(), q.end(), 0.0); for (int i = 0; i < q.size(); i++) { q[i] = q[i] / sum; } return q; } vector<float> move(vector<float> p, int U) { vector<float> q (5); float s; float pExact = 0.8; float pOvershoot = 0.1; float pUndershoot = 0.1; for (int i = 0; i < p.size(); i++) { s = pExact * p[(p.size() + (i-U % p.size())) % p.size()]; s = s + pOvershoot * p[(p.size() + (i-U-1 % p.size())) % p.size()]; s = s + pUndershoot * p[(p.size() + (i-U+1 % p.size())) % p.size()]; q[i] = s; } return q; }
true
5788ff10f287e5036da69739df659b42bc175831
C++
JacobMillward/opencl_fluids
/nclgl/Mesh.h
UTF-8
2,312
2.984375
3
[]
no_license
/****************************************************************************** Class:Mesh Implements: Author:Rich Davison <richard.davison4@newcastle.ac.uk> Description:Wrapper around OpenGL primitives, geometry and related OGL functions. There's a couple of extra functions in here that you didn't get in the tutorial series, to draw debug normals and tangents. -_-_-_-_-_-_-_,------, _-_-_-_-_-_-_-| /\_/\ NYANYANYAN -_-_-_-_-_-_-~|__( ^ .^) / _-_-_-_-_-_-_-"" "" *////////////////////////////////////////////////////////////////////////////// #pragma once #include "OGLRenderer.h" #include <vector> using std::ifstream; using std::string; //A handy enumerator, to determine which member of the bufferObject array //holds which data enum MeshBuffer { VERTEX_BUFFER =0, COLOUR_BUFFER =1, TEXTURE_BUFFER, NORMAL_BUFFER, TANGENT_BUFFER, INDEX_BUFFER, MAX_BUFFER }; class Mesh { public: friend class MD5Mesh; Mesh(void); virtual ~Mesh(void); virtual void Draw(); //Generates a single triangle, with RGB colours static Mesh* GenerateTriangle(); //Generates an X by X plane of points static Mesh* GeneratePlane(float sideLength, int pointsPerSide); static Mesh* LoadMeshFile(const string& filename); Vector3* getVertices() const { return vertices; }; GLuint getVertexBuffer() { return bufferObject[VERTEX_BUFFER]; }; Vector3* getNormals() const { return normals; }; GLuint getNormalBuffer() { return bufferObject[NORMAL_BUFFER]; }; //Generates normals for the vertexes void GenerateNormals(); GLuint type; //Primitive type for this mesh (GL_TRIANGLES...etc) protected: //Buffers all VBO data into graphics memory. Required before drawing! void BufferData(); //VAO for this mesh GLuint arrayObject; //VBOs for this mesh GLuint bufferObject[MAX_BUFFER]; //Number of vertices for this mesh GLuint numVertices; //Number of indices for this mesh GLuint numIndices; //Pointer to vertex position attribute data (badly named...?) Vector3* vertices; //Pointer to vertex colour attribute data Vector4* colours; //Pointer to vertex texture coordinate attribute data Vector2* textureCoords; //Pointer to vertex normals attribute data Vector3* normals; //Pointer to vertex tangents attribute data Vector3* tangents; //Pointer to vertex indices attribute data unsigned int* indices; };
true
150e31f080cf8c295c178a5ed7ea8d2795ba50a7
C++
GOOOL-UFMS/Algoritmos-e-Programacao-II
/1 - Introdução à linguagem C e C++/Questionário 1 sobre a linguagem C e C++/Thiago Dias/somadigitos.cpp
UTF-8
259
2.90625
3
[ "MIT" ]
permissive
#include<stdio.h> int main() { int intNum, umDigito, doisDigito, soma; scanf("%d", &intNum); umDigito = intNum % 10; doisDigito = (intNum / 10) % 10; soma = umDigito + doisDigito; printf("%d\n", soma); return 0; }
true
80ed43d57cea58ce401bce9b14dc4f983de44d82
C++
dh00n/Algorithm
/code/pg12901.cpp
UTF-8
484
3.265625
3
[]
no_license
#include <string> #include <vector> #include <iostream> using namespace std; string day[] = {"FRI", "SAT", "SUN", "MON", "TUE", "WED", "THU"}; int month[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; string solution(int a, int b) { int total = 0; string answer = ""; for (int i = 0; i < a - 1; i++) { total += month[i]; } total += b - 1; answer = day[total % 7]; return answer; } int main() { cout << solution(1, 6); return 0; }
true
2d25ea2ac1fd8e75275625e1a4521a23a9ac4803
C++
shenyan0712/PDS
/src/ArcZeeMath/cldev.cpp
GB18030
12,517
2.5625
3
[]
no_license
#include <iostream> #include <fstream> #include <cstdio> #include <cstdlib> #include "cldev.h" #include "clBufferEx.h" using namespace std; //ʼCL豸, ҼϵopenCLƽ̨豸 int cldev::init(bool dispInfo) { cl::Platform::get(&platforms); if (platforms.size() == 0) { std::cout << "Platform size 0\n"; return -1; } for (int i = 0; i < platforms.size(); i++) { cl::STRING_CLASS str; //ȡ汾ֵ platforms[i].getInfo((cl_platform_info)CL_PLATFORM_VERSION, &str); float versionNum; #ifdef _MSC_VER sscanf_s(str.c_str() + 6, "%f", &versionNum); #else sscanf(str.c_str() + 6, "%f", &versionNum); #endif // _MSC_VER pfVersions.push_back(versionNum); if (dispInfo) { //* cout << "==========Platform " << i << "==========" << endl; cout << "Version: " << versionNum << endl; platforms[i].getInfo((cl_platform_info)CL_PLATFORM_NAME, &str); cout<<"Name: " << str << endl; platforms[i].getInfo((cl_platform_info)CL_PLATFORM_PROFILE, &str); cout << "Profile: " << str << endl; vector<cl::Device> pDevs; platforms[i].getDevices(CL_DEVICE_TYPE_CPU | CL_DEVICE_TYPE_GPU, &pDevs); for (int j = 0; j < pDevs.size(); j++) { cout << "=====Device " << j <<"====="<< endl; string str; pDevs[j].getInfo(CL_DEVICE_NAME, &str); cout << "Device Name: " << str << endl; cl_device_type type; pDevs[j].getInfo(CL_DEVICE_TYPE, &type); cout << "Device Type: "; if (type== CL_DEVICE_TYPE_CPU) cout << "CPU" << endl; else if(type == CL_DEVICE_TYPE_GPU) cout<< "GPU" << endl; //ȡ豸local memory size cl_ulong lm_size; pDevs[j].getInfo(CL_DEVICE_LOCAL_MEM_SIZE, &lm_size); cout << "Local mem size:" << lm_size << endl; //ж豸SVM֧ cl_device_svm_capabilities caps; pDevs[j].getInfo(CL_DEVICE_SVM_CAPABILITIES,&caps); if (caps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER) { cout << "Coarse grain SVM is supported" << endl; SVMmode = MODE_COARSE_SVM; } else { cout << "SVM is not supported." << endl; SVMmode = MODE_NO_SVM; } cl_command_queue_properties cqps; pDevs[j].getInfo(CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES, &cqps); if ( (cqps & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) && (cqps & CL_QUEUE_PROFILING_ENABLE) ){ printf("This device does support QUEUE_ON_DEVICE\n"); } else{ printf("This device does not support QUEUE_ON_DEVICE\n"); } } cout << endl; //*/ } } return 0; } /* versionReq: 汾Ҫ󣬱ڵversionReq SVMsupport: SVMsupport֧Ҫ0SVM֧֣1=SVM 2=ϸSVM */ int cldev::selectPfWithMostDev(cl_device_type useType, float versionReq, int SVMsupport) { cl_int err; cl_device_svm_capabilities caps; cl_command_queue_properties cqps; bool deviceQueueSupported; int idx=-1, maxDevs=0; vector<cl::Device> pDevs; vector<pair<int, cl::Device>> candidates; //<platform index, dev> vector<bool> devQueSupport; int* devCntForPf = new int[platforms.size()]; for (int i = 0; i < platforms.size(); i++) { devCntForPf[i] = 0; //汾Ҫ if (pfVersions[i]<versionReq) continue; try { platforms[i].getDevices(useType, &pDevs); } catch (exception ex) { continue; } //SVMҪԼDEVICE_QUEUEҪ int svm ; deviceQueueSupported=false; for (int j = 0; j < pDevs.size(); j++) { svm = 0; pDevs[j].getInfo(CL_DEVICE_SVM_CAPABILITIES, &caps); if (caps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER) svm = 1; else {} pDevs[j].getInfo(CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES, &cqps); if ( (cqps & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) && (cqps & CL_QUEUE_PROFILING_ENABLE) ){ printf("This device does support QUEUE_ON_DEVICE\n"); deviceQueueSupported = true; } else{ printf("This device does not support QUEUE_ON_DEVICE\n"); } if (svm >= SVMsupport) { candidates.push_back(make_pair(i, pDevs[j])); if (deviceQueueSupported) devQueSupport.push_back(true); else devQueSupport.push_back(false); devCntForPf[i]++; } } if (devCntForPf[i] > maxDevs) { maxDevs = devCntForPf[i]; idx = i; } } delete[] devCntForPf; selectedPf = idx; if (idx < 0) return -1; //д豸 for (int i = 0; i < candidates.size(); i++) { if (candidates[i].first == selectedPf) { selectedDevs.push_back(candidates[i].second); devQueSupFlag.push_back(devQueSupport[i]); cl_int cu_size; candidates[i].second.getInfo(CL_DEVICE_MAX_COMPUTE_UNITS, &cu_size); selDevCUsize.push_back(cu_size); cout << "CU size:" << cu_size << endl; } } if (candidates.size() < 1) { cout << "There is no device meet the requirements." << endl; return -1; } cout << "Selected platform " << idx << endl; // cl::Context context_(selectedDevs, NULL,NULL); context = context_; //Ϊÿ豸 for (int i = 0; i < selectedDevs.size(); i++) { cl::CommandQueue queue(context, selectedDevs[i], 0, &err); if (err != 0) return -1; queues.push_back(queue); /* 豸ϴһ */ if(false){ //if (devQueSupFlag[i]) { cl_queue_properties properties[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE | CL_QUEUE_ON_DEVICE | CL_QUEUE_ON_DEVICE_DEFAULT, CL_QUEUE_SIZE, 65536, //8192, 0 }; clCreateCommandQueueWithProperties(context(), selectedDevs[i](), properties, &err); } //else // clCreateCommandQueueWithProperties(context(), selectedDevs[i](), NULL, &err); } return 0; } /* ļkernel ============ ==-1 ==0 OK */ int cldev::createKernels(vector<string> kernelFiles, vector<string> kernelNames) { string combFileContent, singFileContent; try { int err; //clļݽкϲ for (int i = 0; i < kernelFiles.size(); i++) { //err = fileToString(kernelFiles[i].c_str(), singFileContent); //ļopenCL //if (err != 0) return i; combFileContent.append("#include \""); combFileContent.append(kernelFiles[i].c_str()); combFileContent.append("\"\n"); } //clļ cl::Program::Sources source(1, std::make_pair(combFileContent.c_str(), combFileContent.size())); cl::Program program_(context, source, &err); program = program_; err = program.build(selectedDevs, "-cl-std=CL2.0", NULL,NULL); // //kernel for (int i = 0; i < kernelNames.size(); i++) { cl::Kernel kernel(program, kernelNames[i].c_str(), &err); if (err != 0) return -i; kernels[kernelNames[i]] = kernel; } } catch (cl::Error err) { char *program_log; size_t program_size, log_size; cout << "Err Code:" << err.err() << endl; /* Find size of log and print to std output */ clGetProgramBuildInfo(program(), selectedDevs[0](), CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); program_log = (char*)malloc(log_size + 1); program_log[log_size] = '\0'; clGetProgramBuildInfo(program(), selectedDevs[0](), CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL); printf("%s\n", program_log); free(program_log); system("pause"); exit(1); } return 0; } /* ļkernel kernelContents ==>firstΪļ, secondΪļ ============ ==-1 ==0 OK */ int cldev::createKernelsFromStr(vector<std::pair<string, string>> kernelContents, vector<string> kernelNames) { vector<string> kernelFiles; vector<std::pair<string, string>>::iterator iter = kernelContents.begin(); for (; iter != kernelContents.end(); iter++) { kernelFiles.push_back(iter->first); //дļ std::fstream f(iter->first, (std::fstream::out | std::fstream::binary)); if (f.is_open()) { f.write(iter->second.c_str(), iter->second.size()); } f.close(); } return createKernels(kernelFiles, kernelNames); } /** ȡļתΪַ */ int cldev::fileToString(const char *filename, std::string& s) { size_t size; char* str; std::fstream f(filename, (std::fstream::in | std::fstream::binary)); if (f.is_open()) { size_t fileSize; f.seekg(0, std::fstream::end); size = fileSize = (size_t)f.tellg(); f.seekg(0, std::fstream::beg); str = new char[size + 1]; if (!str) { f.close(); return 0; } f.read(str, fileSize); f.close(); str[size] = '\0'; s = str; delete[] str; return 0; } cout << "Error: failed to open file\n:" << filename << endl; return -1; } void cldev::getKernelInfo(string kernelName) { size_t size[3]; //kernels[kernelName].getWorkGroupInfo(selectedDevs[0], CL_KERNEL_GLOBAL_WORK_SIZE, &size[0]); //printf("Max size of global work items:%d,%d,%d", size[0], size[1], size[2]); kernels[kernelName].getWorkGroupInfo(selectedDevs[0], CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, &size[0]); printf("Prefered size of work group:%d\n", size[0]); kernels[kernelName].getWorkGroupInfo(selectedDevs[0], CL_KERNEL_WORK_GROUP_SIZE, &size[0]); printf("Max work group:%d\n", size[0]); } void cldev::test() { cl_int err; float data[5]; float *x; //SVM //pts3D, Pts2D, Posesݻ map<string, clBufferEx<float>> buffers; buffers["test1"]=clBufferEx<float>(context, queues[0], 10, MODE_COARSE_SVM); data[0] = 1.23; data[1] = 2.34; data[2] = 3.45; data[3] = 4.56; data[4] = 5.67; buffers["test1"].write(0, data, 5); cl::Kernel kernel = kernels["test1"]; buffers["test1"].SetArgForKernel(kernel, 0); //ڵڶdeviceϵں cl::Event event; try { queues[0].enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(4), cl::NullRange, NULL, NULL); //event.wait(); queues[0].finish(); clBufferPtr<float> ptr = buffers["test1"].get_ptr(false); float *ptr2=ptr.get(); buffers["test1"].read(0, data, 5); } catch (cl::Error err) { std::cerr << "ERROR: " << err.what() << "(" << err.err() << ")" << std::endl; } buffers["test2"] = clBufferEx<float>(context, queues[0], 100, MODE_COARSE_SVM); } void cldev_test() { cldev cd; cd.init(false); if (cd.selectPfWithMostDev(CL_DEVICE_TYPE_ALL, 2.0, 1)) { cout << "No devices satisfy the requirement."; } vector<string> kernelFiles; vector<string> kernelNames; kernelNames.push_back("test1"); kernelFiles.push_back("E:\\sync_directory\\workspace\\PSBA\\CL_files\\test1.cl"); kernelNames.push_back("test2"); kernelFiles.push_back("E:\\sync_directory\\workspace\\PSBA\\CL_files\\test2.cl"); if (cd.createKernels(kernelFiles, kernelNames) != 0) cout << "cldev_test(): create Kernel failed" << endl; cd.test(); }
true
26779f37c8c5efb33c5664c4dd36aded0d91b83d
C++
romux09/SOA
/Proyecto1/NodeMCU Code/SOAMkII.ino
UTF-8
4,676
2.5625
3
[]
no_license
#include <PubSubClient.h> #include <NTPClient.h> #include <ESP8266WiFi.h> #include <WiFiUdp.h> // defines pins numbers const int trigPin = D1; //D8 const int echoPin = D0; //D3 const int trigPin2 = D3; const int echoPin2 = D2; const char* ssid = "AndroidAPFAC7"; const char* password = "iwau2541"; const char* mqttServer = "3.83.223.148"; const int mqttPort = 16331; const char* mqttUser = "user1"; const char* mqttPassword = "0000"; const long utcOffsetInSeconds = -21600; char charMessageUltrasonic1[20]; char charMessageUltrasonic2[20]; WiFiClient espClient; PubSubClient client(espClient); WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds); int getDistanceFirstSensor() { long duration; int distance; // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance distance = (duration * 0.034) / 2; return distance; } int getDistanceSecondSensor() { long duration; int distance; // Clears the trigPin digitalWrite(trigPin2, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin2, HIGH); delayMicroseconds(10); digitalWrite(trigPin2, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin2, HIGH); // Calculating the distance distance = (duration * 0.034) / 2; return distance; } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived in topic: "); Serial.println(topic); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); Serial.println("-----------------------"); } void reconnect() { uint8_t retries = 3; while (!client.connected()) { Serial.print("Intentando conexion MQTT..."); if (client.connect("ESP8266Client", mqttUser, mqttPassword)) { Serial.println("conectado"); client.subscribe("/user1/ultrasonic/1"); client.subscribe("/user1/ultrasonic/2"); } else { Serial.print("fallo, rc="); Serial.print(client.state()); Serial.println(" intenta nuevamente en 5 segundos"); // espera 5 segundos antes de reintentar delay(5000); } retries--; if (retries == 0) { // esperar a que el WDT lo reinicie while (1); } } } void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input pinMode(trigPin2, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin2, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } client.setServer(mqttServer, mqttPort); client.setCallback(callback); while (!client.connected()) { Serial.println("Connecting to MQTT..."); if (client.connect("ESP8266Client", mqttUser, mqttPassword )) { Serial.println("connected"); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } } timeClient.begin(); client.publish("/user1/ultrasonic/1", "Hello from ESP8266-2"); client.publish("/user1/ultrasonic/2", "Hello from ESP8266-2"); client.subscribe("/user1/ultrasonic/1"); client.subscribe("/user1/ultrasonic/2"); } void loop() { int distance1_cm = getDistanceFirstSensor(); int distance2_cm = getDistanceSecondSensor(); if (!client.connected()) { Serial.println("Disconnected"); reconnect(); } timeClient.update(); client.loop(); String timer = timeClient.getFormattedTime(); timer.concat(","); timer.concat(timeClient.getDay()); String ultrasonicMessage1 = timer; ultrasonicMessage1.concat(","); ultrasonicMessage1.concat(distance1_cm); String ultrasonicMessage2 = timer; ultrasonicMessage2.concat(","); ultrasonicMessage2.concat(distance2_cm); ultrasonicMessage1.toCharArray(charMessageUltrasonic1, 20); ultrasonicMessage2.toCharArray(charMessageUltrasonic2, 20); // Prints the distance on the Serial Monitor client.publish("/user1/ultrasonic/1", charMessageUltrasonic1); client.publish("/user1/ultrasonic/2", charMessageUltrasonic2); delay(1000); }
true
c242eb14a5bf737b89252ee038181fbc1b3feb2f
C++
hisyamsk/tlx-toki
/pemrogaman-dasar/12 Rekursi/12_b.cpp
UTF-8
298
3.296875
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; int f(int x) { if (x == 1) { return 1; } if (x % 2 == 0) { return (x/2) * f(x-1); } else { return x * f(x-1); } } int main() { int n; cin >> n; int res = f(n); cout << res << endl; }
true
f0683699acbd1257fe77aa16891bcf59e598725e
C++
vikrant911998/C-Morning
/29Aug2019/first.cpp
UTF-8
371
3.390625
3
[]
no_license
#include<iostream> using namespace std; // private,protected,public --> access specifiers class A{ protected: void play(){ cout<<"I am play of Class A in protected"<<endl; } }; class B:public A{ public: void play1(){ play(); } }; int main(){ A obj1; B obj; obj.play1(); return 0; }
true
cea4cfcd5ce8f917f12ebaa6572e1be6b570e22f
C++
EnesALTUN/c-dungeon-game
/c-dungeon-game/Equipment.h
UTF-8
641
3.28125
3
[]
no_license
#pragma once class Equipment { int _effect; int _count; int _cost; public: Equipment(int effect, int count, int cost) { this->_effect = effect; this->_count = count; this->_cost = cost; } #pragma region Getter Setter void setFullVariable(int effect, int count) { this->_effect = effect; this->_count = count; } void setEffect(int effect) { this->_effect = effect; } int getEffect() { return _effect; } void setCount(int count) { this->_count = count; } int getCount() { return _count; } void setCost(int cost) { this->_cost = cost; } int getCost() { return _cost; } #pragma endregion };
true
36c2ed1b0a76f0b9ceaed400c084bffc8ae48aac
C++
Yura52/teaching
/2018_hse_cpp_seminars/seminar_6/std_vector.cpp
UTF-8
875
3.421875
3
[]
no_license
#include <algorithm> #include <initializer_list> #include <iostream> #include <iterator> #include <utility> class Vector { public: Vector() = default; ~Vector() { delete[] data_; } const int* data() const { return data_; } int* data() { return const_cast<int*>(const_cast<const Vector*>(this)->data()); } size_t size() const { return size_; } private: size_t size_{0}; size_t capacity_{0}; int* data_{nullptr}; }; std::ostream& operator<<(std::ostream& os, const Vector& vec) { const auto size = vec.size(); const auto data = vec.data(); os << "size: " << size << '\n'; for (size_t i = 0; i < size; ++ i) { os << data[i] << " "; } os << "\n"; return os; } int main() { int *a = nullptr; delete a; std::cout << a << '\n'; return 0; }
true
ae3cb44564c284a7bc05898f7136ef91605ecc9c
C++
kedebug/AlgoTraining
/poj/3613/11533566_AC_250MS_1048K.cpp
UTF-8
1,492
2.734375
3
[]
no_license
#include <iostream> #include <algorithm> #include <map> using namespace std; const int MAXN = 210; class Matrix { public: int e[MAXN][MAXN], n; void setn(int n) { this->n = n; } void initvalue() { memset(e, 0x3F, sizeof(e)); } Matrix operator = (const Matrix& o) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) e[i][j] = o.e[i][j]; return *this; } Matrix operator * (const Matrix& o) { Matrix m; m.initvalue(); for (int k = 1; k <= n; k++) for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) m.e[i][j] = min(m.e[i][j], e[i][k] + o.e[k][j]); return m; } }; Matrix M1, M2; map<int, int> my; int main() { int n, t, s, e; while (~scanf("%d%d%d%d", &n, &t, &s, &e)) { int cflag = 0; M1.initvalue(); M2.initvalue(); for (int i = 0; i < t; i++) { int cost, u, v; scanf("%d%d%d", &cost, &u, &v); if (!my[u]) my[u] = ++cflag; if (!my[v]) my[v] = ++cflag; int a = my[u], b = my[v]; M1.e[a][b] = M1.e[b][a] = cost; } for (int i = 1; i <= cflag; i++) M2.e[i][i] = 0; M1.setn(cflag), M2.setn(cflag); while (n) { if (n & 1) M2 = M1 * M2; M1 = M1 * M1; n >>= 1; } printf("%d\n", M2.e[my[s]][my[e]]); } return 0; }
true