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
c756f92d3fc61ff87d1b36d7abb17667bb5b4d49
C++
mishadolgih/study
/hse/2020/11/lvl1/B/simple.cpp
UTF-8
1,493
2.703125
3
[]
no_license
#include <iostream> #include <set> #include <map> #define ll long long #define X first #define Y second using namespace std; int n, k, *a, *b; struct trio {int i, j, h;}; inline int idx(trio t) {return t.i * k * 4 + t.j * 4 + t.h; } bool operator<(const trio &l, const trio &r) {return idx(l) < idx(r);} map<trio, ll> cache; pair<ll, int> g(int i, int j, int h); ll f(int i, int j, int h) {trio t = {i,j,h}; return j > 0 ? (cache.count(t)>0?cache[t]:cache[t]=g(i, j, h).X) : 0;} pair<ll, int> g(int i, int j, int h){ set<pair<ll, int>> s; if (n - i > j) s.insert({f(i + 1, j , 0), 0}); if ((n - i > j) && (h != 1)) s.insert({f(i + 1, j - 1, 1) + b[i] + b[i+1], 1}); if ((n - i > j) && (h != 2)) s.insert({f(i + 1, j - 1, 2) + a[i] + a[i+1], 2}); if ((h != 1) && (h != 2)) s.insert({f(i + 1, j - 1, 3) + a[i] + b[i], 3}); return *(--s.end()); } int main() { freopen("tests/03", "r", stdin); cin >> n >> k; a = new int[n], b = new int[n]; for (int i = 0; i < n; i++) cin >> a[i] >> b[i]; pair<int, int> *r = new pair<int, int>[n] {}; for (int i = 0, j = k, h = 0, m = 0; j > 0; i++) switch(h = g(i, j, h).Y){ case 1: j--; r[i].Y = r[i+1].Y = ++m; break; case 2: j--; r[i].X = r[i+1].X = ++m; break; case 3: j--; r[i].X = r[i].Y = ++m; break; } for (int i = 0; i < n; i++) cout << r[i].X << ' ' << r[i].Y << endl; return 0; }
true
b1a4eaddea66c1f82cff83b405c04b7ed90fea20
C++
isaacdvid1596/DataStructures_1
/Class_Examples/DLLMangoTree/mangoFruit.cpp
UTF-8
405
2.90625
3
[]
no_license
#include "mangoFruit.h" mangoFruit::mangoFruit() { setWeight(0); this->next = NULL; this->prev = NULL; } mangoFruit::mangoFruit(double w) { setWeight(w); this->next = nullptr; this->prev = nullptr; } mangoFruit::~mangoFruit() { } void mangoFruit::setWeight(double w) { this->weight = w - (0.1*w); } double mangoFruit::getWeight() { return this->weight; }
true
8bc4dcc855ca35d377d9ecb9c2861f09a22e22ee
C++
Sherrydqy/physical-computing
/Arduino Exercises/190207/190207.ino
UTF-8
1,002
2.59375
3
[]
no_license
int pot1 = A0; int ledPin1 = 10; int ledPin2 = 11; int potRead = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); // we are telling arduino to send back infomation, like read a sensor, read a switch and send // back to your pc. 9600 is the speed limit of the communication between cmoputer and arduino pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); } void loop() { // put your main code here, to run repeatedly: //digitalWrite(ledPin1,HIGH); //digitalWrite(ledPin2,HIGH); //analogWrite(ledPin1, 127); //analogWrite(ledPin2, 255); //potRead = analogRead(pot1)/4; //This will constantly read my potentiometer . 1023/4 约等于255 potRead = analogRead(pot1); int mapped = map(potRead, 0,200,0,255); Serial.println(mapped); analogWrite(ledPin1, mapped); // if (potRead < 512) { // analogWrite(ledPin1, 64); // analogWrite(ledPin2, 0); // } // else { // analogWrite(ledPin2, 255); // analogWrite(ledPin1, 0); // } }
true
bfc09a0321b79f8b7e45f6ff23a02903b5d3ae1c
C++
camilo1765684/proyecto
/IPOO-master/Usuario.h
UTF-8
897
2.75
3
[]
no_license
#ifndef USUARIO_H #define USUARIO_H #include <string> using namespace std; class Usuario { private: int codigo; string nombre; int telefono; string direccion; int valorM; string tipo; public: Usuario(); ~Usuario(); Usuario(int codigo, string nombre, int telefono, string direccion,int multa); Usuario(int codigo, string nombre, int telefono, string direccion); int obtenerCodigoUsuario(); void darCodigoUsuario(int codigo); string obtenerNombreUsuario(); void darNombreUsuario(string nombre); int obtenerTelefonosuario(); void darTelefonoUsuario(int telefono); string obtenerDireccionUsuario(); void darDireccionUsuario(string direccion); void asignarFecha(int fecha); struct tm obtenerFecha(); int obtenerValorMEstudiante(); void darValorMEstudiante(int valorM); }; #endif
true
049cb45f247ff06fc1d85e6521faf237287235a7
C++
singhashish-26/Leetcode
/Algorithms/Binary Search/find-smallest-letter-greater-than-target.cpp
UTF-8
347
3.375
3
[]
no_license
#https://leetcode.com/problems/find-smallest-letter-greater-than-target/ class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { int x= upper_bound(letters.begin(), letters.end(), target)- letters.begin(); if(x>=letters.size()) return letters[0]; return letters[x]; } };
true
cbfdfeb169b28b8959cbad4f9c7bf523c1e4ebc5
C++
logsniper/ACM-code
/ZOJ Accepted/2286-Sum of Divisors.cpp
UTF-8
349
2.609375
3
[]
no_license
#include<cstdio> #include<cstdlib> int f[1000001]; void init() { int k,p; f[0]=0; for(k=1;k<=1000000;++k) f[k]=1; for(k=2;k<=1000000;++k) for(p=k+k;p<=1000000;p+=k) f[p]+=k; } int main() { init(); int m; while(scanf("%d",&m)!=EOF){ int res=0; for(int i=1;i<=1000000;++i) if(f[i]<=m) ++res; printf("%d\n",res); } return 0; }
true
b9bab4847e0beb3ca6fb6cef5647ac832d2e2305
C++
krovma/glare
/glare/math/utilities.h
UTF-8
1,116
2.671875
3
[ "MIT" ]
permissive
#pragma once #include "glare/core/common.h" namespace glare { #if defined(__cpp_lib_math_constants) #include <numbers> constexpr float32 PI = std::numbers:pi_v<float32>; constexpr float32 SQRT_2 = std::numbers::sqrt2_v<float32> #else constexpr float32 PI = static_cast<float32>(3.14159265358979323846); constexpr float32 SQRT_2 = static_cast<float32>(1.41421356237309504880); #endif template<typename T> constexpr decltype(auto) clamp(const T& value, const T& min, const T& max) { return value < min ? min : (value > max ? max : value); } template<typename T> constexpr int32 sgn(const T& value) { const T zero(0); return static_cast<int32>(zero < value) - static_cast<int32>(value < zero); } template<typename T, typename P> constexpr decltype(auto) lerp(const T& a, const T& b, const P alpha) { return (static_cast<P>(1.f) - alpha)* a + (alpha * b); } inline float32 rtd(float32 rad) { return rad / PI * 180.f; } inline float32 dtr(float32 deg) { return deg / 180.f * PI; } inline float32 cos_deg(float32 deg) { return cosf(dtr(deg)); } inline float32 sin_deg(float32 deg) { return sinf(dtr(deg)); } };
true
47970631e7d947cefdb9e229065327a3e4630899
C++
l-paz91/principles-practice
/Chapter 18/Exercise 11/main.cpp
UTF-8
1,266
2.921875
3
[]
no_license
// ----------------------------------------------------------------------------- // https://lptcp.blogspot.com/ // Chapter 18 - Exercise 11 /* Look up (e.g., on the web) skip list and implement that kind of list. This is not an easy exercise. */ // https://github.com/l-paz91/principles-practice/ // ----------------------------------------------------------------------------- //--INCLUDES--// #include "Skiplist.h" // ----------------------------------------------------------------------------- vector<Node> v(100); int main() { Skiplist sList(3); sList.insert(4); sList.insert(7); sList.insert(2); sList.remove(7); Node* findByValue = sList.findByValue(4); cout << findByValue->mValue << endl; Node* findByIndex = sList.findByValue(sList.mSize-1); cout << findByIndex->mValue << endl << endl; sList.insert(10); sList.insert(5); sList.insert(12); sList.print(); for (int i = 0; i < 100; ++i) { sList.insert(i + i + 1); } cout << endl; sList.print(); keep_window_open(); return 0; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
true
d20d40d964efa928d653de44a4ecd1990d0b584a
C++
etb10/PAndT
/pingB.ino
UTF-8
4,799
2.75
3
[]
no_license
#include <neopixel.h> #include "application.h" #include "Particle.h" void colorAll(uint32_t c, uint8_t wait); void colorWipe(uint32_t c, uint8_t wait); void rainbow(uint8_t wait); void rainbowCycle(uint8_t wait); uint32_t Wheel(byte WheelPos); SYSTEM_MODE(AUTOMATIC); #define PIXEL_COUNT 24 #define CIRCLE_ONE_PIN D5 #define CIRCLE_TWO_PIN D6 #define CIRCLE_THREE_PIN D7 #define PIXEL_TYPE WS2812 Adafruit_NeoPixel circleOne(PIXEL_COUNT, CIRCLE_ONE_PIN, PIXEL_TYPE); Adafruit_NeoPixel circleTwo(PIXEL_COUNT, CIRCLE_TWO_PIN, PIXEL_TYPE); Adafruit_NeoPixel circleThree(PIXEL_COUNT, CIRCLE_THREE_PIN, PIXEL_TYPE); int state = 0; void setup() { //Serial.begin(115200); Particle.subscribe("transmitter_ECE364_Megaton", myHandler); Serial.begin(9600); circleOne.begin(); circleOne.show(); circleOne.setPixelColor(0, circleOne.Color(0,0,0)); circleTwo.begin(); circleTwo.show(); circleTwo.setPixelColor(0, circleTwo.Color(0,0,0)); circleThree.begin(); circleThree.show(); circleThree.setPixelColor(0, circleThree.Color(0,0,0)); } void loop() { // Trigger pin, Echo pin, delay (ms), visual=true|info=false ping(D2, D3, 20, true); } void ping(pin_t trig_pin, pin_t echo_pin, uint32_t wait, bool info) { uint32_t duration, inches, cm; static bool init = false; if (!init) { pinMode(trig_pin, OUTPUT); digitalWriteFast(trig_pin, LOW); pinMode(echo_pin, INPUT); delay(50); init = true; } /* Trigger the sensor by sending a HIGH pulse of 10 or more microseconds */ digitalWriteFast(trig_pin, HIGH); delayMicroseconds(10); digitalWriteFast(trig_pin, LOW); duration = pulseIn(echo_pin, HIGH); inches = duration / 74 / 2; cm = duration / 29 / 2; if (inches < 24){ if (state == 1) { colorAllCircleOne(circleOne.Color(0, 0, 150), 5000); colorAllCircleTwo(circleTwo.Color(0, 150, 0), 5000); colorAllCircleThree(circleThree.Color(150, 0, 0), 5000); Particle.publish("transmitter_ECE364_Megaton", "state1"); state = 2; } else { Particle.publish("transmitter_ECE364_Megaton", "reset"); state = 0; } } if (info) { /* Visual Output */ Serial.printf("%2d:", inches); for(int x=0;x<inches;x++) Serial.print("#"); Serial.println(); } else { /* Informational Output */ Serial.printlnf("%6d in / %6d cm / %6d us", inches, cm, duration); } delay(wait); // slow down the output } void colorAllCircleOne(uint32_t c, uint8_t wait) { uint16_t i; for(i=0; i<circleOne.numPixels(); i++) { circleOne.setPixelColor(i, c); } circleOne.show(); delay(wait); } void colorAllCircleTwo(uint32_t c, uint8_t wait) { uint16_t i; for(i=0; i<circleOne.numPixels(); i++) { circleTwo.setPixelColor(i, c); } circleTwo.show(); delay(wait); } void colorAllCircleThree(uint32_t c, uint8_t wait) { uint16_t i; for(i=0; i<circleOne.numPixels(); i++) { circleThree.setPixelColor(i, c); } circleThree.show(); delay(wait); } void colorWipeCircleOne(uint32_t c, uint8_t wait) { for(uint16_t i=0; i<circleOne.numPixels(); i++) { circleOne.setPixelColor(i, c); circleOne.show(); delay(wait); } } void rainbowCircleOne(uint8_t wait) { uint16_t i, j; for(j=0; j<256; j++) { for(i=0; i<circleOne.numPixels(); i++) { circleOne.setPixelColor(i, Wheel((i+j) & 255)); } circleOne.show(); delay(wait); } } // Slightly different, this makes the rainbow equally distributed throughout, then wait (ms) void rainbowCycleCircleOne(uint8_t wait) { uint16_t i, j; for(j=0; j<256; j++) { // 1 cycle of all colors on wheel for(i=0; i< circleOne.numPixels(); i++) { circleOne.setPixelColor(i, Wheel(((i * 256 / circleOne.numPixels()) + j) & 255)); } circleOne.show(); delay(wait); } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { if(WheelPos < 85) { return circleOne.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } else if(WheelPos < 170) { WheelPos -= 85; return circleOne.Color(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return circleOne.Color(0, WheelPos * 3, 255 - WheelPos * 3); } } // HANDLER ------------------- void myHandler(const char *event, const char *data) { if (data) { if (strcmp(data,"reset")==0) { colorAllCircleOne(circleOne.Color(0, 0, 0), 5000); colorAllCircleTwo(circleTwo.Color(0, 0, 0), 5000); colorAllCircleThree(circleThree.Color(0, 0, 0), 5000); } else { state++; } } }
true
a970a551e7fe40b57c9eda3371f21bb902ea149c
C++
Mjolnir-MD/Mjolnir
/test/core/test_neighbor_list.cpp
UTF-8
2,822
2.546875
3
[ "MIT" ]
permissive
#define BOOST_TEST_MODULE "test_neighbor_list" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/util/empty.hpp> #include <mjolnir/util/logger.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/NeighborList.hpp> BOOST_AUTO_TEST_CASE(test_NeighborList_no_parameter) { mjolnir::LoggerManager::set_default_logger("test_neighbor_list.log"); using parameter_type = mjolnir::empty_t; // XXX mjolnir::NeighborList<parameter_type> nlist; using neighbor_type = typename mjolnir::NeighborList<parameter_type>::neighbor_type; static_assert(sizeof(neighbor_type) == sizeof(std::size_t), ""); // construct dummy neighbor list const std::size_t N = 100; const std::size_t M = 10; for(std::size_t i=0; i<N; ++i) { std::vector<neighbor_type> partner; for(std::size_t j = i + 1; j < i + 1 + M; ++j) { partner.emplace_back(j, parameter_type{}); } nlist.add_list_for(i, partner.begin(), partner.end()); } // check the list is correctly built for(std::size_t i=0; i<N; ++i) { const auto partners = nlist.at(i); BOOST_TEST(partners.size() == M); for(std::size_t k=0; k<M; ++k) { BOOST_TEST(partners.at(k).index == i + 1 + k); // no partner here. } } } BOOST_AUTO_TEST_CASE(test_NeighborList_with_parameter) { mjolnir::LoggerManager::set_default_logger("test_neighbor_list.log"); // contain this parameter to neighbor list using parameter_type = std::pair<std::size_t, std::size_t>; mjolnir::NeighborList<parameter_type> nlist; using neighbor_type = typename mjolnir::NeighborList<parameter_type>::neighbor_type; static_assert( sizeof(neighbor_type) == sizeof(std::size_t) + sizeof(parameter_type), ""); // construct dummy neighbor list const std::size_t N = 100; const std::size_t M = 10; for(std::size_t i=0; i<N; ++i) { std::vector<neighbor_type> partner; for(std::size_t j = i + 1; j < i + 1 + M; ++j) { partner.emplace_back(j, parameter_type{i, j}); } nlist.add_list_for(i, partner.begin(), partner.end()); } // check the list is correctly built for(std::size_t i=0; i<N; ++i) { const auto partners = nlist.at(i); BOOST_TEST(partners.size() == M); for(std::size_t k=0; k<M; ++k) { BOOST_TEST(partners.at(k).index == i + 1 + k); BOOST_TEST(partners.at(k).parameter().first == i ); BOOST_TEST(partners.at(k).parameter().second == i + 1 + k); } } }
true
6c946460e173d8c011a555961a3467ac199a87f2
C++
waleywen/BubuJump
/BubuJumpClient/Classes/GamePlay/Obstruction/Effect/BaseEffect.cpp
UTF-8
2,008
2.53125
3
[]
no_license
#include "BaseEffect.h" #include "FlyBootEffect.h" #include "RocketEffect.h" #include "MagnetEffect.h" #include "AngelWingEffect.h" #include "EvilCloudEffect.h" #include "VortexEffect.h" #include "TransitionEffect.h" USING_NS_CC; BaseEffect::~BaseEffect() { } float BaseEffect::changeSpeed(float speed) { return speed; } float BaseEffect::changeAcceleration(float acceleration) { return acceleration; } float BaseEffect::changeHorizontalSpeedPercentage(float percentage) { return percentage; } bool BaseEffect::isFrozen() { return false; } EffectFactory* EffectFactory::getInstance() { static EffectFactory s_instance; return &s_instance; } BaseEffect* EffectFactory::getEffect(EffectType type, ObstructionNode* sender) { for(auto& effect : this->_effectVector) { if (effect->getType() == type) { if (VortexEffectType == type) { VortexEffect* tempEffect = static_cast<VortexEffect*>(effect); tempEffect->setTarget(sender); } effect->reset(); return effect; } } BaseEffect* tEffect = nullptr; if (FlyBootEffectType == type) { tEffect = FlyBootEffect::create(); } else if (RocketEffectType == type) { tEffect = RocketEffect::create(); } else if (MagnetEffectType == type) { tEffect = MagnetEffect::create(); } else if (AngelWingEffectType == type) { tEffect = AngelWingEffect::create(); } else if (EvilCloudEffectType == type) { tEffect = EvilCloudEffect::create(); } else if (VortexEffectType == type) { VortexEffect* tempEffect = VortexEffect::create(); tempEffect->setTarget(sender); tEffect = tempEffect; } else if (TransitionEffectType == type) { tEffect = TransitionEffect::create(); } tEffect->reset(); this->_effectVector.pushBack(tEffect); return tEffect; }
true
79f4649a85cf2a8395d35dba3d151f35c9b7a0e6
C++
jasfin/CPP-Programming
/linkedlist/intersection_llist.cpp
UTF-8
2,506
3.65625
4
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef struct node node; struct node { int data; node *next; }*root; void disp(node *ptr) { while(ptr!=NULL) { cout<<ptr->data<<"\t"; ptr=ptr->next; } cout<<"\n"; } void FindIntersection(node *ptr1,node *ptr2) { int count1=0; int count2=0; node *temp1=ptr1,*temp2=ptr2; while(temp1!=NULL) { count1++; temp1=temp1->next; } while(temp2!=NULL) { count2++; temp2=temp2->next; } if(count1!=count2) { int big=(count1>count2)?1:2; int d=abs(count1-count2); if(big==1) for(int i=0;i<d;i++) ptr1=ptr1->next; else for(int i=0;i<d;i++) ptr2=ptr2->next; } while(ptr1!=ptr2) { ptr1=ptr1->next; ptr2=ptr2->next; } cout<<ptr1->data<<endl; return; } int nthfromlast(node *ptr,int n) { int len=0; node *temp=ptr; while(temp!=NULL) { len++; temp=temp->next; } int pos=len-n; temp=ptr; for(int i=0;i<pos;i++) temp=temp->next; return temp->data; } bool checkpalindrome(node *root) //check if the ll is a palindrome by revesing the { //list from the middle int len=0; node *ptr=root,*nptr; while(ptr!=NULL) { len++; ptr=ptr->next; } cout<<"len is "<<len<<endl; ptr=root; for(int i=0;i<len/2;i++) { nptr=ptr; ptr=ptr->next; } nptr->next=NULL; node *prev=NULL,*current=ptr; while(current!=NULL) { node *nextone=current->next; current->next=prev; prev=current; current=nextone; } ptr=root; while(ptr!=NULL && prev!=NULL && ptr->data==prev->data) { cout<<ptr->data<<" is equal to "<<prev->data<<endl; ptr=ptr->next; prev=prev->next; } if(ptr==NULL) return true; return false; } int main() { int n; cin>>n; int item; cin>>item; root=new node; root->data=item; for(int i=0;i<n-1;i++) { cin>>item; node *ptr=new node; ptr->data=item; ptr->next=root->next; root->next=ptr; } disp(root); if(checkpalindrome(root)) //to check if the linkedlist is a palindrome cout<<"palindrome"<<endl; else cout<<"not a palindrome"<<endl; //to find nth node from the end of a linkedlist; //int n; cout<<"enter n, ie;nth node from the last \n"; cin>>n; cout<<"nth from last is "<<nthfromlast(root,n)<<"\n"; //create a new intersection linkedlist to the first one node *ptr=new node; ptr->data=4400; ptr->next=root->next->next->next; disp(ptr); FindIntersection(root,ptr); }
true
1cacebd28022a9f2e5e880c1b7252674a867d01e
C++
mdiepart/Lanternfish
/firmware/lanternfish/daySchedule.cpp
UTF-8
8,128
3.4375
3
[ "MIT" ]
permissive
#include <stddef.h> #include "daySchedule.h" #include <EEPROM.h> DaySchedule::DaySchedule(unsigned char dayOfWeek){ nbPts = 0; dow = MONDAY; changeDay(dow); } /* * Returns the number of points in the selected schedule * */ unsigned char DaySchedule::getSize() const{ return nbPts; } point DaySchedule::getPoint(const unsigned char pos) const{ if(pos >= getSize()){ return point{0, 0, 0}; }else{ return point{ptHour[pos], ptMin[pos], ptDC[pos]}; } } /* * Adds a point to the schedule. * Automatically sorts the point at the correct position according to it's time. * If a point already exists for that time, the duty cycle is simply updated. * * In: * pt: a point containing hour, minute, duty cycle * Out: * bool: true if the point was successfully added. * false otherwise (error or schedule full) */ bool DaySchedule::addPoint(const point pt){ //If the list is full we return false if(getSize() == NB_PTS_MAX){ return false; } //Search for the correct position unsigned char i = 0; while( (pt.h < ptHour[i]) && (i < getSize()) ){ i++; } while( (pt.m < ptMin[i]) && (i < getSize()) ){ i++; } //Add the point if(pt.m == ptMin[i]){ ptDC[i] = pt.dc; }else{ unsigned char tmp1 = 0, tmp2 = 0; //Hours tmp1 = ptHour[i]; ptHour[i] = pt.h; for(unsigned char j = i; j < getSize()-1; j++){ tmp2 = ptHour[j+1]; ptHour[j+1] = tmp1; tmp1 = tmp2; } //Minutes tmp1 = ptMin[i]; ptMin[i] = pt.m; for(unsigned char j = i; j < getSize()-1; j++){ tmp2 = ptMin[j+1]; ptMin[j+1] = tmp1; tmp1 = tmp2; } //Duty Cycles tmp1 = ptDC[i]; ptDC[i] = pt.dc; for(unsigned char j = i; j < getSize()-1; j++){ tmp2 = ptDC[j+1]; ptDC[j+1] = tmp1; tmp1 = tmp2; } setSize(getSize()+1); } return save(); } /* * Deletes a point from the schedule given it's position. * * In: * pos : unsigned char containing the position [0; size[ * Out: * bool: true if point was successfully found and deleted * false otherwise */ bool DaySchedule::delPoint(const unsigned char pos){ if( pos >= getSize() ){ return false; } // Shifts the remaining points for(unsigned char i = pos; i < getSize()-1; i++){ ptHour[i] = ptHour[i+1]; ptMin[i] = ptMin[i+1]; ptDC[i] = ptDC[i+1]; } //Sets the last point to zeros ptHour[getSize()-1] = 0; ptMin[getSize()-1] = 0; ptDC[getSize()-1] = 0; //Update size setSize(getSize()-1); return save(); } /* * Update the schedule to another day of the week. The data will come from * the internal EEPROM of the device. * * In: * unsigned char day: number of the day of the week [0;6]. 0 is monday. * Out: * bool: true if successful * false otherwise */ bool DaySchedule::changeDay(const unsigned char day){ if( day >= 7 ){ return false; } size_t offset = day*BYTES_PER_DAY; unsigned char n = EEPROM.read(offset); // If the size we read is higher than NB_PTS_MAX we consider the memory // as unitialized if(n > NB_PTS_MAX){ setSize(0); }else{ setSize(n); } // Read memory for(unsigned char i = 0; i < getSize(); i++){ ptHour[i] = EEPROM.read(offset + 3*i + 1); ptMin[i] = EEPROM.read(offset + 3*i + 2); ptDC[i] = EEPROM.read(offset + 3*i + 3); } for(unsigned char i = getSize(); i < NB_PTS_MAX; i++){ ptHour[i] = 0; ptMin[i] = 0; ptDC[i] = 0; } dow = day; // Loads last point of previous day with > 0 points unsigned int counter = 0, i = dow-1; while(EEPROM.read(i*BYTES_PER_DAY) == 0 || counter <= 7){ i--; counter++; if(i > 6){ // if we underflow i = 6; } } // i now contains the previous DOW with at least 1 point (if counter <= 6) if(counter > 7){ // There is no point in the schedule prevD = prevH = prevM = prevDC = 0; nextD = nextH = nextM = nextDC = 0; return true; } // Load value of prev point prevD = i; n = EEPROM.read(i*BYTES_PER_DAY); prevH = EEPROM.read(i*BYTES_PER_DAY + 3*(n-1) + 1); prevM = EEPROM.read(i*BYTES_PER_DAY + 3*(n-1) + 2); prevDC = EEPROM.read(i*BYTES_PER_DAY + 3*(n-1) + 3); // Load first point of next day with > 0 points i = dow+1; while(EEPROM.read(i*BYTES_PER_DAY) == 0){ i = (i+1)%7; } // Load value of next point nextD = i; nextH = EEPROM.read(i*BYTES_PER_DAY + 1); nextM = EEPROM.read(i*BYTES_PER_DAY + 2); nextDC = EEPROM.read(i*BYTES_PER_DAY + 3); return true; } /* * Saves the schedule for the current day in the EEPROM of the device * In: * / * Out: * bool: true if successfully saved * false otherwise */ bool DaySchedule::save(){ size_t offset = dow*BYTES_PER_DAY; EEPROM.update(offset, getSize()); for(unsigned char i = 0; i < NB_PTS_MAX; i++){ EEPROM.update(offset + 3*i + 1, ptHour[i]); EEPROM.update(offset + 3*i + 2, ptMin[i]); EEPROM.update(offset + 3*i + 3, ptDC[i]); } } void DaySchedule::setSize(const unsigned char n){ nbPts = n; } void DaySchedule::reset(){ for(unsigned char i = 0; i < getSize(); i++){ ptHour[i] = 0; ptMin[i] = 0; ptDC[i] = 0; } setSize(0); } unsigned char DaySchedule::getPower(const unsigned char hh, const unsigned char mm, const unsigned char ss) const{ unsigned char pt1D = 0, pt1H = 0, pt1M = 0, pt1DC = 0; unsigned char pt2D = 0, pt2H = 0, pt2M = 0, pt2DC = 0; if(nbPts > 0){ //Determine point before int i = 0; while(ptHour[i] < hh && i < nbPts){ i++; } while(ptHour[i] == hh && ptMin[i] < mm && i < nbPts){ i++; } i--; if(i < 0){ pt1D = prevD; pt1H = prevH; pt1M = prevM; pt1DC = prevDC*2.56; }else{ pt1D = dow; pt1H = ptHour[i]; pt1M = ptMin[i]; pt1DC = ptDC[i]*2.56; } //i+1 is the next point. If >= nbPts we take the one of the next day i++; if(i >= nbPts ){ pt2D = nextD; pt2H = nextH; pt2M = nextM; pt2DC = nextDC*2.56; }else{ pt2D = dow; pt2H = ptHour[i]; pt2M = ptMin[i]; pt2DC = ptDC[i]*2.56; } }else{ pt1D = prevD; pt1H = prevH; pt1M = prevM; pt1DC = prevDC*2.56; pt2D = nextD; pt2H = nextH; pt2M = nextM; pt2DC = nextDC*2.56; } //Compute adequate power //Compute time from pt1 to pt2 unsigned int nbHours = (24 + pt2H - pt1H)%24; if((pt1D == pt2D) && (pt1H <= pt2H && pt1M <= pt2M)){ nbHours += 6*24; }else{ nbHours += 24*(7 + pt2D - pt1D)%7; } int nbMin = pt2M - pt1M; unsigned long int length_12 = 60*(nbHours*60+nbMin); // length in seconds //compute time from pt1 to hh:mm:ss nbHours = (24 + hh - pt1H)%24; if((pt1D == dow) && (pt1H <= hh && pt1M <= mm)){ nbHours += 6*24; }else{ nbHours += 24*(7 + dow - pt1D)%7; } nbMin = mm - pt1M; unsigned long int length_1t = 60*(nbHours*60+nbMin)+ss; // length in seconds return pt1DC + (pt2DC-pt1DC)*length_1t/length_12; }
true
0098d74baae2546046c43c0c45e74a84c7f49c18
C++
wokickic/Algorithm
/Algorithms/DFS/[BOJ]2468_안전영역.cpp
UHC
3,145
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #define max(a, b) ((a) > (b) ? (a) : (b)) using namespace std; const int dy[] = { 0, 1, 0, -1 }; const int dx[] = { 1, 0, -1, 0 }; const int NSIZE = 101; int n; vector<vector<int>> map, visit; void dfs(int y, int x, int h) { visit[y][x] = 1; for (int i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (ny >= 0 && nx >= 0 && ny < n && nx < n) { if (map[ny][nx] > h && visit[ny][nx] == 0) dfs(ny, nx, h); } } } int main(void) { cin >> n; map = vector<vector<int>>(n, vector<int>(n, 0)); vector<bool> heightCheck(NSIZE, false); queue<int> height; // create map for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> map[i][j]; // Է° ε true ٲ if (!heightCheck[map[i][j]]) heightCheck[map[i][j]] = true; } } // 0 ~ 101 鼭 true̸ heightť ߰ for (int i = 0; i < NSIZE; i++) if (heightCheck[i]) height.push(i); int ans = 1; // height迭 ݺ while(!height.empty()){ int h = height.front(); height.pop(); visit = vector<vector<int>>(n, vector<int>(n, 0)); int areaCnt = 0; for (int y = 0; y < n; y++) { for (int x = 0; x < n; x++) { // map[y][x] h κ̱⶧ dfs ȵ if (map[y][x] > h && !visit[y][x]) { dfs(y, x, h); areaCnt++; } } } ans = max(ans, areaCnt); } printf("%d\n", ans); } /* , ٽ ϰ ݺ, ȿ */ //#include <iostream> //#include <vector> //#define max(a, b) ((a > b) ? (a) : (b)) //using namespace std; // //int dy[] = { 0, 1, 0, -1 }; //int dx[] = { 1, 0, -1, 0 }; //vector<vector<int>> map; //vector<vector<int>> check; //vector<bool> height; // //class safeArea{ // int n; //public: // // safeArea(int n_) : n(n_){ // map = vector<vector<int>>(n, vector<int>(n, 0)); // check = vector<vector<int>>(n, vector<int>(n, 0)); // height = vector<bool> (101, 0); // // for (int i = 0; i < n; i++){ // for (int j = 0; j < n; j++){ // cin >> map[i][j]; // if (!height[map[i][j]]) height[map[i][j]] = true; // } // } // } // // void makeMap(int remove){ // for (int i = 0; i < n; i++){ // for (int j = 0; j < n; j++){ // if (check[i][j]) check[i][j] = 0; // map[i][j] -= remove; // map[i][j] = map[i][j] - (remove); // } // } // } // // void dfs(int y, int x){ // check[y][x] = 1; // for (int i = 0; i < 4; i++){ // int ny = y + dy[i]; // int nx = x + dx[i]; // if (ny >= 0 && nx >= 0 && ny < n && nx < n){ // if (map[ny][nx] >0 && check[ny][nx] == 0) dfs(ny, nx); // } // } // } //}; // //int main(void){ // int n; cin >> n; // int ans = 0; // safeArea safe(n); // // for (int i = 0; i < height.size(); i++){ // if (!height[i]) continue; // int area = 0; // safe.makeMap(i); // ̱ // for (int y = 0; y < n; y++){ // for (int x = 0; x < n; x++){ // if (map[y][x] > 0 && check[y][x] == 0) { safe.dfs(y, x); area++; } // } // } // safe.makeMap(-i);// // ans = max(ans, area); // } // printf("%d\n", ans); //}
true
f02f51efdf4cc5562a483cbdc5fe21185930c736
C++
jnonline/gdk
/Source/Gdk/System/Memory.h
UTF-8
5,531
2.875
3
[]
no_license
/* * Copyright (c) 2011, Raincity Games LLC * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */ // // Memory: // This file contains implemenation for the GDK memory system. Useable in GDK components & games // // Configuration: // // Usage: // Single object // Foo *foo = GdkNew Foo(); // GdkDelete foo; // 1D Array of created objects // Foo **foo = GdkNew1DArray<Foo>(10); // GdkDelete1DArray foo; // 2D Array of created objects // Foo ***foo = GdkNew2DArray<Foo>(10,20); // GdkDelete2DArray foo; // malloc & free // Byte* buffer = GdkAlloc(100); // GdkFree(buffer); // // #pragma once // Comment this line to disable memory tracking #if defined(DEBUG) || defined(_DEBUG) //#define GDK_MEMORY_TRACKING #endif // --------------------- #ifdef GDK_MEMORY_TRACKING namespace Gdk { // ================================================================================= /// @brief /// Provides access to the GDK memory management and tracking system /// /// @todo TODO(P2): Needs documentation, faster tracking, release mode usage, etc... // ================================================================================= class Memory { typedef void* (*AllocatorFunc)(size_t numBytes, const char* file, int line); typedef void (*DeallocatorFunc)(void* memblock, const char* file, int line); private: // MemoryEntry class: used to represent data for a single memory allocation class MemoryEntry { public: inline MemoryEntry () {} inline MemoryEntry (int numBytes, int numDimensions, const char* file, int line) : numBytes(numBytes), numDimensions(numDimensions), file(file), line(line), uniqueId(++uniqueIdCounter) { } int numBytes; int numDimensions; const char* file; int line; unsigned int uniqueId; static unsigned int uniqueIdCounter; }; typedef std::map<void*, MemoryEntry> MemoryMap; typedef std::map<unsigned int, std::pair<void*,MemoryEntry> > SortedMap; // Static Properties & Methods // ------------------------------------- // Init & Shutdown - called by the Application private: friend class Application; static void Init(); static void Shutdown(); // Standard C malloc/free pass-through allocators private: static void* CAllocator (size_t numBytes, const char* file, int line); static void CDeallocator (void* memBlock, const char* file, int line); // Properties private: static MemoryMap* memoryMap; static AllocatorFunc allocatorFunc; static DeallocatorFunc deallocatorFunc; // TODO(P2): Mutex locked thread safe allocations... static Mutex mutex; // Instance Properties & Methods // ------------------------------------- // Constructor public: inline Memory (const char* file, int line) : file(file), line(line) {} inline ~Memory () {} // Memory allocation void* CreateBlock (size_t numBytes, int numDimensions) const; // For 1D arrays: data[bound0] template <typename T> T* New1DArray (const int bound0); // For 2D arrays: data[bound1][bound0] template <typename T> T** New2DArray (const int bound0, const int bound1); // For singletons. template <typename T> void Delete (T*& data); // For 1D arrays: data[bound0] template <typename T> void Delete1DArray (T*& data); // For 2D arrays: data[bound1][bound0] template <typename T> void Delete2DArray (T**& data); // C-style alloc & free void* Alloc(size_t numBytes); void Free(void* ptr); private: // Instance properties const char* file; int line; }; #include "Memory.inl" } //---------------------------------------------------------------------------- // Operator: new (Memory&) inline void* operator new (size_t numBytes, const Gdk::Memory& memory) { return memory.CreateBlock(numBytes, 0); } //---------------------------------------------------------------------------- // Operator: delete (Memory&) inline void operator delete (void*, const Gdk::Memory&) { // Only called during exception handling. } //---------------------------------------------------------------------------- // Allocation Macros (for tracked memory) #define GdkNew new(Gdk::Memory(__FILE__,__LINE__)) #define GdkNew1DArray Gdk::Memory(__FILE__,__LINE__).New1DArray #define GdkNew2DArray Gdk::Memory(__FILE__,__LINE__).New2DArray #define GdkDelete Gdk::Memory(__FILE__,__LINE__).Delete #define GdkDelete1DArray Gdk::Memory(__FILE__,__LINE__).Delete1DArray #define GdkDelete2DArray Gdk::Memory(__FILE__,__LINE__).Delete2DArray #define GdkAlloc(size) Gdk::Memory(__FILE__,__LINE__).Alloc(size) #define GdkFree(ptr) Gdk::Memory(__FILE__,__LINE__).Free(ptr) #else // ifdef GDK_MEMORY_TRACKING namespace Gdk { class Memory { public: // Init & Shutdown - called by the Application static void Init(); static void Shutdown(); }; } // Allocation Macros (pass-throughs) #define GdkNew new #define GdkAlloc(size) malloc(size) #define GdkFree(ptr) free(ptr) // For 1D arrays: data[bound0] template <typename T> T* GdkNew1DArray (const int bound0); // For 2D arrays: data[bound1][bound0] template <typename T> T** GdkNew2DArray (const int bound0, const int bound1); // For singletons. template <typename T> void GdkDelete (T*& data); // For 1D arrays: data[bound0] template <typename T> void GdkDelete1DArray (T*& data); // For 2D arrays: data[bound1][bound0] template <typename T> void GdkDelete2DArray (T**& data); #include "Memory.inl" #endif // ifdef GDK_MEMORY_TRACKING
true
1b1218a2870e961436e5acc62d90253426531976
C++
Alexsanchoo/2labOOP4sem
/2 laba OOP (4 sem)/ElectricalDevices.cpp
UTF-8
411
2.90625
3
[]
no_license
#include "ElectricalDevices.h" void ElectricalDevices::setName(string name) { this->name = name; } void ElectricalDevices::setCost(double cost) { this->cost = cost; } void ElectricalDevices::setType(TypeGood type) { this->type = type; } string ElectricalDevices::getName() { return name; } double ElectricalDevices::getCost() { return cost; } TypeGood ElectricalDevices::getType() { return type; }
true
9918ad7392df1d195f66b190fbe1bf8f5be2e6b6
C++
bitcoin/bitcoin
/src/core_read.cpp
UTF-8
9,067
2.59375
3
[ "MIT" ]
permissive
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <script/script.h> #include <script/sign.h> #include <serialize.h> #include <streams.h> #include <util/result.h> #include <util/strencodings.h> #include <version.h> #include <algorithm> #include <string> namespace { class OpCodeParser { private: std::map<std::string, opcodetype> mapOpNames; public: OpCodeParser() { for (unsigned int op = 0; op <= MAX_OPCODE; ++op) { // Allow OP_RESERVED to get into mapOpNames if (op < OP_NOP && op != OP_RESERVED) { continue; } std::string strName = GetOpName(static_cast<opcodetype>(op)); if (strName == "OP_UNKNOWN") { continue; } mapOpNames[strName] = static_cast<opcodetype>(op); // Convenience: OP_ADD and just ADD are both recognized: if (strName.compare(0, 3, "OP_") == 0) { // strName starts with "OP_" mapOpNames[strName.substr(3)] = static_cast<opcodetype>(op); } } } opcodetype Parse(const std::string& s) const { auto it = mapOpNames.find(s); if (it == mapOpNames.end()) throw std::runtime_error("script parse error: unknown opcode"); return it->second; } }; opcodetype ParseOpCode(const std::string& s) { static const OpCodeParser ocp; return ocp.Parse(s); } } // namespace CScript ParseScript(const std::string& s) { CScript result; std::vector<std::string> words = SplitString(s, " \t\n"); for (const std::string& w : words) { if (w.empty()) { // Empty string, ignore. (SplitString doesn't combine multiple separators) } else if (std::all_of(w.begin(), w.end(), ::IsDigit) || (w.front() == '-' && w.size() > 1 && std::all_of(w.begin() + 1, w.end(), ::IsDigit))) { // Number const auto num{ToIntegral<int64_t>(w)}; // limit the range of numbers ParseScript accepts in decimal // since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts if (!num.has_value() || num > int64_t{0xffffffff} || num < -1 * int64_t{0xffffffff}) { throw std::runtime_error("script parse error: decimal numeric value only allowed in the " "range -0xFFFFFFFF...0xFFFFFFFF"); } result << num.value(); } else if (w.substr(0, 2) == "0x" && w.size() > 2 && IsHex(std::string(w.begin() + 2, w.end()))) { // Raw hex data, inserted NOT pushed onto stack: std::vector<unsigned char> raw = ParseHex(std::string(w.begin() + 2, w.end())); result.insert(result.end(), raw.begin(), raw.end()); } else if (w.size() >= 2 && w.front() == '\'' && w.back() == '\'') { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. std::vector<unsigned char> value(w.begin() + 1, w.end() - 1); result << value; } else { // opcode, e.g. OP_ADD or ADD: result << ParseOpCode(w); } } return result; } // Check that all of the input and output scripts of a transaction contains valid opcodes static bool CheckTxScriptsSanity(const CMutableTransaction& tx) { // Check input scripts for non-coinbase txs if (!CTransaction(tx).IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) { return false; } } } // Check output scripts for (unsigned int i = 0; i < tx.vout.size(); i++) { if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) { return false; } } return true; } static bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness) { // General strategy: // - Decode both with extended serialization (which interprets the 0x0001 tag as a marker for // the presence of witnesses) and with legacy serialization (which interprets the tag as a // 0-input 1-output incomplete transaction). // - Restricted by try_no_witness (which disables legacy if false) and try_witness (which // disables extended if false). // - Ignore serializations that do not fully consume the hex string. // - If neither succeeds, fail. // - If only one succeeds, return that one. // - If both decode attempts succeed: // - If only one passes the CheckTxScriptsSanity check, return that one. // - If neither or both pass CheckTxScriptsSanity, return the extended one. CMutableTransaction tx_extended, tx_legacy; bool ok_extended = false, ok_legacy = false; // Try decoding with extended serialization support, and remember if the result successfully // consumes the entire input. if (try_witness) { CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION); try { ssData >> tx_extended; if (ssData.empty()) ok_extended = true; } catch (const std::exception&) { // Fall through. } } // Optimization: if extended decoding succeeded and the result passes CheckTxScriptsSanity, // don't bother decoding the other way. if (ok_extended && CheckTxScriptsSanity(tx_extended)) { tx = std::move(tx_extended); return true; } // Try decoding with legacy serialization, and remember if the result successfully consumes the entire input. if (try_no_witness) { CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS); try { ssData >> tx_legacy; if (ssData.empty()) ok_legacy = true; } catch (const std::exception&) { // Fall through. } } // If legacy decoding succeeded and passes CheckTxScriptsSanity, that's our answer, as we know // at this point that extended decoding either failed or doesn't pass the sanity check. if (ok_legacy && CheckTxScriptsSanity(tx_legacy)) { tx = std::move(tx_legacy); return true; } // If extended decoding succeeded, and neither decoding passes sanity, return the extended one. if (ok_extended) { tx = std::move(tx_extended); return true; } // If legacy decoding succeeded and extended didn't, return the legacy one. if (ok_legacy) { tx = std::move(tx_legacy); return true; } // If none succeeded, we failed. return false; } bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness) { if (!IsHex(hex_tx)) { return false; } std::vector<unsigned char> txData(ParseHex(hex_tx)); return DecodeTx(tx, txData, try_no_witness, try_witness); } bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header) { if (!IsHex(hex_header)) return false; const std::vector<unsigned char> header_data{ParseHex(hex_header)}; DataStream ser_header{header_data}; try { ser_header >> header; } catch (const std::exception&) { return false; } return true; } bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk) { if (!IsHex(strHexBlk)) return false; std::vector<unsigned char> blockData(ParseHex(strHexBlk)); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); try { ssBlock >> block; } catch (const std::exception&) { return false; } return true; } bool ParseHashStr(const std::string& strHex, uint256& result) { if ((strHex.size() != 64) || !IsHex(strHex)) return false; result.SetHex(strHex); return true; } util::Result<int> SighashFromStr(const std::string& sighash) { static std::map<std::string, int> map_sighash_values = { {std::string("DEFAULT"), int(SIGHASH_DEFAULT)}, {std::string("ALL"), int(SIGHASH_ALL)}, {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)}, {std::string("NONE"), int(SIGHASH_NONE)}, {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)}, {std::string("SINGLE"), int(SIGHASH_SINGLE)}, {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)}, }; const auto& it = map_sighash_values.find(sighash); if (it != map_sighash_values.end()) { return it->second; } else { return util::Error{Untranslated(sighash + " is not a valid sighash parameter.")}; } }
true
b41d9914f8c52b8b9f78613aafde200f0ef423e9
C++
luckeciano/competitive-programming
/10919.cpp
UTF-8
705
3.09375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int k; cin >> k; while (k > 0) { int m; cin >> m; bool grads = true; vector <int> freddieCourses; for (int i = 0; i < k; i++) { int course; cin >> course; freddieCourses.push_back(course); } for (int j = 0; j < m; j++) { int c; int r; cin >> c >> r; for (int k = 0; k < c; k++){ int givenCourse; cin >> givenCourse; for (int i = 0; i < freddieCourses.size(); i++) { if (freddieCourses[i] == givenCourse) { r--; } } } if (r > 0) { grads = false; } } if (grads) cout << "yes" << endl; else cout << "no" << endl; cin >> k; } return 0; }
true
93783af2376cb445b5f047e9e3ad442c3402c07f
C++
Adam-J-Harris/ImageEditor
/MVCImage - Commented/MVCImage/ImageFactory.h
UTF-8
751
2.71875
3
[]
no_license
// Class: ImageFactory // Inherits from: IFactory<shared_ptr<IImage> // Definition: Factory to create objects of type IImage // // Duncan Baldwin & Adam Harris // 01/05/2017 #pragma once #include "stdafx.h" #include <string> #include <iostream> #include <memory> #include <FreeImagePlus.h> #include "IFactory.h" #include "IImage.h" using namespace std; class ImageFactory : public IFactory<shared_ptr<IImage>> { public: ImageFactory(); ~ImageFactory(); // Method: Create // Definition: Factory Method Pattern // Param 1: string uID; a unique ID which will be applied to the created object // Param 2: string fileName; the fileName were the object is located // Return: shared_ptr<IImage> shared_ptr<IImage> Create(string uID, string fileName); };
true
d0249230ad3ff231b0b2e74628dcb365648937a8
C++
Pasalc/OOP
/Lab03/Rectangle.h
UTF-8
541
2.921875
3
[]
no_license
#ifndef RECTANGLE_H #define RECTANGLE_H #include <cstdlib> #include <iostream> #include "Figure.h" class Rectangle : public Figure{ public: Rectangle(); Rectangle(std::istream &is); Rectangle(size_t i,size_t j); Rectangle(const Rectangle& orig); double Square() override; void Print() override; std::ostream& PrintInOs(std::ostream& os) override; friend std::ostream& operator<<(std::ostream& os, const Rectangle& obj); virtual ~Rectangle(); private: size_t side_a; size_t side_b; }; #endif
true
50ef9e736eecdb881973bd26622817e73119b4b6
C++
Brkys/minimalcode
/model.cpp
UTF-8
661
2.796875
3
[]
no_license
#include "model.h" MyModel::~MyModel(){ qDeleteAll(itemList_); itemList_.clear(); } int MyModel::rowCount(const QModelIndex &parent) const{ return parent.isValid() ? 0 : itemList_.size(); } QVariant MyModel::data(const QModelIndex &index, int role) const{ if(role == Qt::UserRole){ Item *item = itemList_[index.row()]; return QVariant::fromValue(item); } return QVariant(); } void MyModel::appendItem(Item *item) { itemList_.append(item); } QHash<int, QByteArray> MyModel::roleNames() const{ QHash<int, QByteArray> roles; roles[Qt::UserRole] = "sample"; return roles; }
true
53d141307f7f87269f7ae483613aff0f7bf565f1
C++
mpardalos/MIPS-Simulator
/src/memory.cpp
UTF-8
6,725
3.234375
3
[ "MIT" ]
permissive
#include <vector> #include <array> #include <stdexcept> #include <algorithm> #include <sstream> #include "opcodes.hpp" #include "typedefs.hpp" #include "memory.hpp" #include "exceptions.hpp" #include "show.hpp" using namespace std; // We pass in the vector by unique_ptr so that the memory object "owns" the vector. // That means that there can't be any other pointers to this vector and thus no one else // can modify it. Memory::Memory( unique_ptr<vector<Word>> i_instruction_memory) : instruction_memory(move(i_instruction_memory)), data_memory(new vector<Word>()) { assert (instruction_start+(instruction_memory->size()*4) <= data_start); } /** * Check if and address is within instruction memory */ bool is_instruction(Address addr) { return addr >= instruction_start && addr < (instruction_start+instruction_size); } /** * Check if and address is within data memory */ bool is_data(Address addr) { return addr >= data_start && addr < (data_start+data_size); } /** * Check if and address is within data memory */ bool is_getc(Address addr) { return addr >= 0x30000000 && addr < 0x30000004; } /** * Check if and address is within data memory */ bool is_putc(Address addr) { return addr >= 0x30000004 && addr < 0x30000008; } void Memory::memwrite(Address addr, std::function<Word(Word current)> cb) { Address word_address = addr & (~0b11); auto current = memread_word(word_address); write_word(word_address, cb(current)); } /** * Read the word in which an address is contained **/ Word Memory::memread_word(Address addr) const { Address word_address = addr & (~0b11); if (is_instruction(word_address)) { unsigned int inst_index = (word_address - instruction_start) / 4; if (inst_index >= instruction_memory->size()) { return 0; } else { return instruction_memory->at(inst_index); } } else if (is_data(word_address)) { unsigned int data_index = (word_address - data_start) / 4; if (data_index >= data_memory->size()) { return 0; } else { return data_memory->at(data_index); } } else if (is_putc(word_address)) { return 0; } else if (is_getc(word_address)) { return 0; } else { throw MemoryError("Address " + show(as_hex(word_address)) + " is out of bounds"); } } /** * Get a word (4 bytes) from memory. * * Throws invalid_argument if the address is not word-aligned (i.e. it refers to a byte) * or if it is out of bounds of the instruction and data memories. */ Word Memory::get_word(Address addr) const { DEBUG_PRINT("Reading word " << show(as_hex(addr))); if (addr % 4 != 0) throw MemoryError("Word access must be word-aligned"); if (is_putc(addr)) throw MemoryError("Can't read from putc address"); if (is_getc(addr)) return getchar(); return memread_word(addr); } /** * Get a halfword from memory. * * Throws invalid_argument if the address is out of bounds of the instruction and data memories. */ Halfword Memory::get_halfword(Address addr) const { DEBUG_PRINT("Reading halfword " + show(as_hex(addr))); if((addr % 2) != 0) { throw MemoryError("Address not naturally-aligned"); } // Gets the word to which the halfword belongs // by bitmasking the low 2 bits Word word = get_word(addr & (~0b11)); // Shifts the bits we want to the lowest 16 bits // addr % 4 can only be 0 or 2 since we are checking that addr % 2 == 0. // If it's zero then we are trying to read the upper halfword and so we need to shift // right by 16. // If it's 2 then we are trying to read the lower halfword and so we don't need to shift Word shifted = word >> (8 * (2 - (addr % 4))); // And shifts them to the lowest 16 bits Halfword halfword = shifted & 0xFFFF; return halfword; } /** * Get a byte from memory. * * Throws invalid_argument if the address is out of bounds of the instruction and data memories. */ Byte Memory::get_byte(Address addr) const { DEBUG_PRINT("Reading byte " + show(as_hex(addr))); int shift_amount = 8 * (3 - (addr % 4)); // Gets the word to which the byte belongs // by masking the low 2 bits Word word = get_word(addr & (~0b11)); // Shifts the bits we want to the lowest 8 bits Word shifted = word >> shift_amount; // And masks everything else Byte byte = shifted & 0xFF; return byte; } /** * Write a word to memory * * Throws invalid_argument if the address is out of bounds of the instruction and data memories. */ void Memory::write_word(Address addr, Word value) { DEBUG_PRINT("mem(" << show(as_hex(addr)) << ") = " << show(value)) if (addr % 4 != 0) throw MemoryError("Word access must be word-aligned"); if (is_instruction(addr)) { throw MemoryError("Instruction memory is read-only"); } else if (is_data(addr)) { unsigned int data_index = (addr - data_start) / 4; if (data_index >= data_memory->size()) { data_memory->resize(data_memory->size() + data_index + 100, 0); } data_memory->at(data_index) = value; } else if (is_putc(addr)) { cout << static_cast<char>(value & 0xFF); } else if (is_getc(addr)) { throw MemoryError("Can't write to getc address"); } else { throw MemoryError("Address " + show(as_hex(addr)) + " is out of bounds"); } } /** * Write a word to memory * * Throws invalid_argument if the address is out of bounds of the instruction and data memories. */ void Memory::write_halfword(Address addr, Halfword value) { if (addr % 2 != 0) throw MemoryError("Halfword access must be halfword-aligned"); memwrite(addr, [&addr, &value] (Word current) { return (addr % 4 == 0) ? ((Word) value << 16) | (current & 0x0000FFFF) : ((Word) value) | (current & 0xFFFF0000); }); } /** * Write a word to memory * * Throws invalid_argument if the address is out of bounds of the instruction and data memories. */ void Memory::write_byte(Address addr, Byte value) { memwrite(addr, [&addr, &value] (Word current) { Word result = 0; switch (addr % 4) { case 0: result = (static_cast<Word>(value) << 24) | (current & 0x00FFFFFF); break; case 1: result = (static_cast<Word>(value) << 16) | (current & 0xFF00FFFF); break; case 2: result = (static_cast<Word>(value) << 8 ) | (current & 0xFFFF00FF); break; case 3: result = (static_cast<Word>(value) ) | (current & 0xFFFFFF00); break; } return result; }); }
true
78e0642ce731e59c310f3075cee0c98c489f082c
C++
somnath-saha/silver-parakeet
/hello_world/hello.cpp
UTF-8
437
3.1875
3
[]
no_license
#include <iostream> using namespace std; string caesarCypherEncryptor(string str, int key) { // Write your code here. // 97 + 25 = 122 int s = 0; for(int i=0; i<str.size(); i++) { s = (static_cast<int>(str[i]) + key); str[i] = (s > 122) ? static_cast<char>(96 + (s % 122)) : static_cast<char>(s); } return str; } //test int main() { //cout<<"Hello World"; cout << caesarCypherEncryptor("axm", 3); return 0; }
true
62352f8f06153394eb9d9c840f8b9f3710822d9c
C++
kjohnnyk91/Cell-viewer
/Line.cpp
UTF-8
2,262
2.734375
3
[]
no_license
// -*- explicit-buffer-name: "Line.cpp<M1-MOBJ/7>" -*- #include <iostream> #include "xmlutil.hpp" #include "line.hpp" #include "cell.hpp" #include "net.hpp" #include "stringToInt.hpp" namespace Netlist { Line::Line ( Node* source, Node* target ): source_(source), target_(target) { source_-> attach( this ); target_-> attach( this ); } Line::~Line() { source_-> detach( this ); target_-> detach( this ); target_-> getNet()->remove( this ); } void Line::toXml ( std::ostream& stream ) const { stream << indent << "<Line source=\"" << source_-> getId() << "\" target=\"" << target_-> getId() << "\"/>\n"; } bool Line::fromXml( Net* net, xmlTextReaderPtr reader ) { const xmlChar* lineTag = xmlTextReaderConstString ( reader, (const xmlChar*)"line" ); const xmlChar* nodeName = xmlTextReaderConstLocalName ( reader ); if (lineTag == nodeName) { int iidSource = 0; int iidTarget = 0; std::string idSource; std::string idTarget; idSource = xmlCharToString(xmlTextReaderGetAttribute( reader, (const xmlChar*) "source")); idTarget = xmlCharToString(xmlTextReaderGetAttribute( reader, (const xmlChar*) "target")); try { iidSource = stringToInt(idSource); } catch(const char& unexp) { std::cerr << "The character " << unexp << " is not a figure in the attribute source" << std::endl; return NULL; } try { iidTarget = stringToInt(idTarget); } catch(const char& unexp) { std::cerr << "The character " << unexp << " is not a figure in the attribute target" << std::endl; return NULL; } Node* source = net-> getNode( iidSource ); Node* target = net-> getNode( iidTarget ); if(not source) { std::cerr << "[ERROR] Line::fromXml(): Unknown source node id:" << idSource << " (line:" << xmlTextReaderGetParserLineNumber(reader) << ")." << std::endl; return false; } if (not target) { std::cerr << "[ERROR] Line::fromXml(): Unknown target node id:" << idTarget << " (line:" << xmlTextReaderGetParserLineNumber(reader) << ")." << std::endl; return false; } net-> add( new Line(source,target) ); return true; } return false; } } // Netlist namespace.
true
a805cb3a9713cb0ddb52a681fecbc12c6b6dfe65
C++
paolocaraos/EECS-111
/p2_54702118/types_p2.cpp
UTF-8
5,961
2.984375
3
[]
no_license
#include "types_p2.h" #include "utils.h" Person::Person(){ gettimeofday(&t_create, NULL); started = false; } Person::Person(int g, long t_stay, unsigned long n) : gender(g), order(n){ gettimeofday(&t_create, NULL); time_to_stay_ms = t_stay; started = false; } Person::Person(struct timeval t, long stay, int gen){ t_create = t; time_to_stay_ms = stay; gender = gen; started = false; } void Person::set_gender(int data) { gender = data; } int Person::get_gender(void) { return gender; } void Person::set_order(unsigned long data) { order = data; } unsigned long Person::get_order(void) { return order; } void Person::set_use_order(unsigned long data) { use_order = data; } unsigned long Person::get_use_order(void) { return use_order; } void Person::set_time(long data) { time_to_stay_ms = data; } long Person::get_stay_time(void) {return time_to_stay_ms;} struct timeval Person::get_start_time(void) {return t_start;} int Person::ready_to_leave(void) { struct timeval t_curr; gettimeofday(&t_curr, NULL); if (get_elasped_time(t_start, t_curr) >= time_to_stay_ms) { return 1; } else { //std::cout<<"Not yet, "<< get_elasped_time(t_start, t_curr)<< " more milliseconds" <<std::endl; return 0; } } void Person::start(void) { started = true; gettimeofday(&t_start, NULL); printf("(%lu)th person enters the restroom: \n", order); printf(" - (%lu) milliseconds after the creation\n", get_elasped_time(t_create, t_start)); } void Person::complete(void) { gettimeofday(&t_end, NULL); printf("(%lu)th person comes out of the restroom: \n", order); printf(" - (%lu) milliseconds after the creation\n", get_elasped_time(t_create, t_end)); printf(" - (%lu) milliseconds after using the restroom\n", get_elasped_time(t_start, t_end)); } struct timeval Person::get_time_created(void){ return t_create; } Restroom::Restroom(){ status = EMPTY; is_full = false; } Restroom::Restroom(int number_of_ppl, struct timeval t){ srand(time(NULL)); struct timeval current_time; status = EMPTY; global_start_t = t; ppl_peeing[MALE] = ppl_peeing[FEMALE] = 0; int number_per_gender[2]; ppl_waiting[MALE] = ppl_waiting[FEMALE] = number_per_gender[MALE] = number_per_gender[FEMALE] = number_of_ppl; for(int i = 0; 0 < number_per_gender[MALE] + number_per_gender[FEMALE]; i++){ int x = rand(); int r = x % 2; long t_stay = (long) (x % 8) + 3; int other; if(number_per_gender[r] > 0){ i_gotta_pee.push_back(Person(r, t_stay, i+1)); number_per_gender[r]--; }else if(number_per_gender[other = (r+1) % 2] > 0){ i_gotta_pee.push_back(Person(other, t_stay, i+1)); number_per_gender[other]--; } gettimeofday(&current_time, NULL); std::cout<< "[" << get_elasped_time(global_start_t, current_time) << " ms ] [Input] A person goes into the queue." <<std::endl; } std::cout<<"Restroom ready queue:"<<std::endl; for(int i = 0; i < number_of_ppl*2; i++){ (i_gotta_pee[i].get_gender() == MALE)? std::cout <<i+1 <<" : MALE ": std::cout <<i+1 <<" : FEMALE "; std::cout<<" PEE TIME: "<< i_gotta_pee[i].get_stay_time() <<" ms "<<std::endl; } } // You need to use this function to print the Restroom's status void Restroom::print_status(void) { struct timeval current_time; gettimeofday(&current_time, NULL); std::cout<<"Print restroom status"<<std::endl; switch(status){ case EMPTY: std::cout<<"["<< get_elasped_time(global_start_t, current_time) <<" ms ] [Restroom] State: EMPTY, "; break; case WOMENPRESENT: std::cout<<"["<< get_elasped_time(global_start_t, current_time) <<" ms ] [Restroom] State: WOMENPRESENT (Number: " <<ppl_peeing[FEMALE]<<"), "; break; case MENPRESENT: std::cout<<"["<< get_elasped_time(global_start_t, current_time) <<" ms ] [Restroom] State: MENPRESENT (Number: " <<ppl_peeing[MALE]<<"), "; break; default: std::cout<<"¯\_(ツ)_/¯"<<std::endl; break; } std::cout<<"Queue status: Total: "<< ppl_waiting[MALE] + ppl_waiting[FEMALE] <<"(Men: "<< ppl_waiting[MALE] <<", Women: "<<ppl_waiting[FEMALE]<< ")"<<std::endl; } int Restroom::get_status(){ if(ppl_peeing[MALE] > 0) status = MENPRESENT; else if( ppl_peeing[FEMALE] > 0) status = WOMENPRESENT; else{ status = EMPTY; } return status; } // Call by reference // This is just an example. You can implement any function you need void Restroom::add_person_into_restroom(int n) { Person p = i_gotta_pee.at(n); int gen = p.get_gender(), x; struct timeval current_time; gettimeofday(&current_time, NULL); ppl_waiting[gen]--; ppl_peeing[gen]++; for(int i = 0 ; i < MAX_SIZE; i++){ try{ peeing.at(i); }catch(const std::out_of_range& oor) { peeing.insert(peeing.begin() + i, &i_gotta_pee[n]); x = i; break; } } peeing.at(x)->start(); if(gen == MALE){ std::cout<<"[" << get_elasped_time(global_start_t, current_time) <<"ms ] A man goes into the restroom. (Stay "<< p.get_stay_time() << " ms )" <<std::endl; status = MENPRESENT; }else{ std::cout<<"[" << get_elasped_time(global_start_t, current_time) <<"ms ] A woman goes into the restroom. (Stay "<< p.get_stay_time() << " ms )" <<std::endl; status = WOMENPRESENT; } } void Restroom::remove_person_from_restroom(int n){ int gen = peeing.at(n)->get_gender(); (gen == MALE)? man_wants_to_leave(n) : woman_wants_to_leave(n); } void Restroom::woman_wants_to_leave(int n){ peeing[n]->complete(); peeing.erase(peeing.begin() +n); status = (--ppl_peeing[FEMALE] == 0)? EMPTY : WOMENPRESENT; } void Restroom::man_wants_to_leave(int n){ peeing[n]->complete(); peeing.erase(peeing.begin() +n); status = (--ppl_peeing[MALE] == 0)? EMPTY : MENPRESENT; } bool Restroom::isFull(){ return is_full = (ppl_peeing[MALE] >= MAX_SIZE || ppl_peeing[FEMALE] >= MAX_SIZE); } std::deque<Person> Restroom::get_ready_q(){ return i_gotta_pee; } std::deque<Person*> Restroom::get_restroom_q(){ return peeing; }
true
e4f259c595a858e6348d2add6a9e346899500df1
C++
teresalazar13/CG
/rain.cpp
UTF-8
1,232
2.65625
3
[]
no_license
#include "rain.h" float slowdown = 1; float velocity = 0.6; int w; void Rain::setup_particle(int i) { par_sys[i].alive = true; par_sys[i].life = 1.0; par_sys[i].fade = (rand() % 100) / 1000.0f + 0.003f; par_sys[i].ypos = 20.0; par_sys[i].vel = velocity; par_sys[i].gravity = -0.8; } void Rain::init_particles() { for (int i = 0; i < NUMBER_OF_RAIN_PARTICLES; i++) { setup_particle(i); } } void Rain::render_rain() { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE); for (w = 0; w < NUMBER_OF_RAIN_PARTICLES; w = w + 2) { if (par_sys[w].alive == true) { float y = par_sys[w].ypos; for (int i = -20; i < 20; i += 2) { for (int j = -20; j < 20; j += 3) { glColor4f(1, 1, 1, par_sys[w].life); glBegin(GL_LINES); glVertex3f(i, y, j); glVertex3f(i, y + 0.1, j); glEnd(); } } par_sys[w].ypos += par_sys[w].vel / (slowdown * 1000); par_sys[w].vel += par_sys[w].gravity; par_sys[w].life -= par_sys[w].fade; if (par_sys[w].ypos <= -20) { par_sys[w].life = -1.0; } if (par_sys[w].life < -1.0) { setup_particle(w); } } } glDisable(GL_BLEND); }
true
fedacf1b35918222d043df460cc7777577e1681e
C++
nfj5/salsa-server
/salsa.cpp
UTF-8
4,889
3.0625
3
[]
no_license
/** * Nicholas Jones * CPSC5510 - SQ20 * Professor Lillethun * Project1 - HTTP Server */ #include <iostream> #include <fstream> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <netdb.h> #include <time.h> #include <unistd.h> #include <cstdio> #include <array> #include <memory> #include "NetworkHelper.h" using namespace std; map<string, string> MimeType = { {".txt", "text/plain"}, {".html", "text/html"}, {".htm", "text/htm"}, {".css", "text/css"}, {".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".png", "image/png"}, {".php", "text/html"} }; // for handling the network methods string date_string(tm* t) { char buffer[80]; strftime(buffer, 80, "%a, %d %h %G %T %Z", t); string temp = buffer; return temp; } bool get_file(string &path, string &content) { struct stat file_info; string temp_path; if (stat(path.c_str(), &file_info) != 0) return false; if (S_ISDIR(file_info.st_mode)){ if (path.substr(path.length()-1, path.length()-2) != "/") path += "/"; path += "index.html"; return get_file(path, content); } ifstream file(path, ios::binary); content.assign(istreambuf_iterator<char>(file), istreambuf_iterator<char>()); file.close(); return true; } int main(int argc, char **argv) { if (argc != 2) { cerr << "Usage: salsa [port]" << endl; return 1; } int port = strtol(argv[1], NULL, 0); // create the socket int sock; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { cerr << "Unable to create socket" << endl; return 1; } // bind the port struct sockaddr_in srv_addr; srv_addr.sin_family = AF_INET; srv_addr.sin_addr.s_addr = htonl(INADDR_ANY); srv_addr.sin_port = htons(port); if (bind(sock, (struct sockaddr *) &srv_addr, sizeof(srv_addr)) < 0) { cerr << "Unable to bind to the specified port. Exiting..." << endl; exit(1); } // set the queue length listen(sock, 5); cout << "SalsaServer listening on port " << port << endl; // handle incoming connections struct sockaddr_in cli_addr; int client_sock; socklen_t client_len; while (true) { client_len = sizeof(cli_addr); client_sock = accept(sock, (struct sockaddr *) &cli_addr, &client_len); // read the request string requestHeader, requestBody; NetworkHelper::getContent(client_sock, requestHeader, requestBody); // parse the request header into an object NetworkHelper::HTTPHeader request; NetworkHelper::parseRequestHeader(requestHeader, request); cout << request.method << " " << request.path << endl; string body = ""; // get the GMT date as a string time_t now = time(0); tm* gmt = gmtime(&now); string date = date_string(gmt); // create the default response object NetworkHelper::HTTPHeader response; response.type = NetworkHelper::HTTPHeader::HeaderType::RESPONSE; response.code = 200; response.fields.insert({"Connection", "close"}); response.fields.insert({"Date", date}); string local_path = "./web_root" + request.path; // get the file content, but also indicate whether it exists or not string file_content; bool fileExists = get_file(local_path, file_content); // only allow GET requests if (request.method != "GET") response.code = 501; // do not allow directory manipulation else if (request.path.find("/../") != string::npos) response.code = 400; else if (!fileExists) { response.code = 404; } else { int typeIndex = local_path.rfind("."); string fileType = local_path.substr(typeIndex); if (MimeType.find(fileType) == MimeType.end()) response.code = 501; else { response.fields.insert({"Content-Type", MimeType[fileType]}); body = file_content; if (fileType == ".php") { body = ""; array<char, 128> buffer; string cmd = "php-cgi -q " + local_path; unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd.c_str(), "r"), pclose); while(fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { body += buffer.data(); } } } } // construct the response response.fields.insert({"Content-Length", to_string(body.length())}); // send the response NetworkHelper::sendResponse(client_sock, response.toString(), body); close(client_sock); } return 0; }
true
1339e27f9f02891b58fedec8d49757a0ce87dac4
C++
minhaz1217/My-C-Journey
/0. Vision 2019/2. February/Accepted/uva_406 - Prime Cuts_AC.cpp
UTF-8
1,951
2.71875
3
[]
no_license
/* Minhazul Hayat Khan minhaz1217.github.io EWU, Bangladesh Problem Name: Problem Link: https://vjudge.net/problem/UVA-406 Date : 19 / February / 2019 Comment: very very easy problem, mistook the sieve range */ #include<bits/stdc++.h> //#include<iostream> using namespace std; #define check(a) cout << a << endl; #define cc(a) cout << a << endl; #define msg(a,b) cout << a << " : " << b << endl; #define msg2(a,b,c) cout << a << " : " << b << " : " << c << endl; #define msg3(a,b,c,d) cout << a << " : " << b << " : " << c << " : " << d << endl; #define _INIT ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define SIEVE 1500 bitset<SIEVE +5>mark; vector<int>prime; void sieve(){ prime.push_back(1); prime.push_back(2); for(int i=3;i<SIEVE;i+=2){ if(!mark[i]){ prime.push_back(i); for(int j=i*i;j<SIEVE;j+=(2*i)){ mark[j] = 1; } } } } int main(){ sieve(); int n,c,pos,l,r,sz; while(cin >> n >> c){ pos = lower_bound(prime.begin(), prime.end(), n) - prime.begin(); if(prime[pos] > n){ pos--; } sz = pos+1; if(sz %2 == 0){ if(sz <= 2*c){ l = 0; r = sz; }else{ l = (sz-2*c)/2; r = l+ 2*c; } }else{ if(sz<= 2*c - 1){ for(int i=0;i<sz;i++){ l = 0; r = sz; } }else{ l = (sz-(2*c-1))/2; r = l+ (2*c-1); if(2*c -1 == 0){ r = -1; } } } cout << n << " "<< c << ":"; if(r == -1){ cout << endl; }else{ for(int i=l;i<r;i++){ cout << " " << prime[i]; } cout << endl; } cout << endl; } return 0; }
true
e3049f1f3cf20700fbe81b368632d79975d7426c
C++
lymven-io/OOP
/oop-rubook/cp8/8-6.cpp
UTF-8
1,285
3.9375
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; class Retangle { double width, height; double area; public: Retangle() { width = height = area = 0.0; } Retangle(double w, double h) { width = w; height = h; area = width * height; } double getMin() { return(width < height ? width : height); } void show() { cout << "Rectangle: " << width << " x " << height << " = " << area << endl; } }; class Cube { double width; double volume; public: Cube() { width = volume = 0.0; } Cube(double w) { // convert to cube width = w; volume = w * w * w; } Cube(Retangle r) { // convert to Rectangle width = r.getMin(); volume = width * width * width; } void show() { cout << "Cube: " << width << " x " << width << " x " << width << " = " << volume << endl; } }; int main() { Retangle r1(3.0, 4.0), r2; Cube c1(5.0), c2; r2 = c1; // convert to Rectangle c2 = r1; // convert to Cube r2.show(); c2.show(); return 0; }
true
b6211fcf1037c40c1b5ed17ac20ee18c5a96fed7
C++
rwang067/rocksGraph
/test/testPMEM/hello_world_pmem.cpp
UTF-8
7,736
2.984375
3
[]
no_license
/* 这是一个PMEM的hello world程序,主要展示如何libpmemobj-cpp工具库进行持久内存C++编程。 * 除了基本的新建/打开PMEM pool、PMEM对象分配、释放、读写等API的介绍外, * 还介绍了pmem::obj::vector<>这个与标准vector用法非常相似的PMEM版vector的用法。 * 关于libpmemobj-cpp的其它API详细介绍,可参考官方文档https://pmem.io/libpmemobj-cpp/v1.12/doxygen/index.html。 * * 此程序同时提供了Makefile,可使用符合要求的编译环境直接运行make编译。 */ #include <iostream> #include <sys/stat.h> #include <unistd.h> #include <string> #include <libpmemobj++/make_persistent.hpp> #include <libpmemobj++/make_persistent_atomic.hpp> #include <libpmemobj++/p.hpp> #include <libpmemobj++/persistent_ptr.hpp> #include <libpmemobj++/pool.hpp> #include <libpmemobj++/transaction.hpp> #include <libpmemobj++/container/vector.hpp> using namespace pmem::obj; #define LAYOUT "Hello World PMEM" #define HELLO_PMEM_POOL_SIZE ((size_t)(1024 * 1024 * 10)) #define MAX_HISTORY 10 int main(int argc, char *argv[]) { /* 一个简单的复合数据类型 */ struct compound_type { compound_type(int val, double dval) : var_int(val), var_double(dval) { } void set_var_int(int val) { var_int = val; } int var_int; double var_double; }; /* 放置于pmem_pool的root位置的复合数据结构,每次打开pmem_pool(pop),可以直接调用pop.root()自动定位获取。*/ struct root { p<int> count; /* p<>模板用来申明存储在pmem的上基础数据结构,以确保之后在transaction中对其的修改能自动被pmdk捕捉并flush进pmem */ persistent_ptr<compound_type> comp; /* persistent_ptr<>模板用来申明存储在pmem上的对象的持久化指针。 */ pmem::obj::vector<persistent_ptr<compound_type>> history; /* 持久化vector模板使用方法与标准vector非常相似,此示例中用此记录comp变量的历史值。 */ }; /* 此hello_world_pmem例子需要传入一个运行时参数,即包括pmem_pool文件名在内的全路径,用于创建pmem_pool文件 */ if (argc < 2) { std::cerr << "usage: " << argv[0] << " pmem_pool_filename " << std::endl; return 1; } const char *path = argv[1]; bool create = false; pool<root> pop; if (access(path, F_OK) == 0) { /* 如果pmem_pool文件已存在,则直接打开pmem_pool。pool<>中的模板用来定义pmem_pool的root数据类型。*/ pop = pool<root>::open(path, LAYOUT); } else { /* 如果pmem_pool文件不存在,则以HELLO_PMEM_POOL_SIZE的大小创建一个新的pmem_pool。*/ pop = pool<root>::create( path, LAYOUT, HELLO_PMEM_POOL_SIZE, S_IWUSR | S_IRUSR); create = true; } /* 调用.root()直接获取root对象的持久化指针 */ auto proot = pop.root(); if (create) { /* 对新建的pmem_pool,将初始化root对象中的1个基础类型变量count、1个复合类型变量comp、及持久化vector变量history */ std::cout << "Create new pmem data: " << std::endl; /* libpmemobj-cpp利用c++11的Lambda functions,定义transaction,帮助程序员以最省心的方式保证pmem上的数据修改可以持久化, * 并避免memory leak/dangling pointer等错误。 */ transaction::run(pop, [&] { /* make_persistent<> 是最基本的用来分配pmem内存对象的方法,与传统的关键字new在dram上的作用类似。 * 模板中传入对象的数据类型,并支持传入初始化对象用的参数。 */ proot->comp = make_persistent<compound_type>(1, 2.0); /* Transaction中可以直接对p<>申明的基础数据类型进行修改,此修改具有原子性, * 即如果程序在transaction未成功完成前终止(如进程被终止或掉电关机),此修改无效,同样的, * 如果程序在transaction完成后以任何方式终止,此修改可保证被持久化到pmem。 */ proot->count = 1; }); std::cout << "count = " << proot->count << std::endl; std::cout << "comp = (" << proot->comp->var_int << ", " << proot->comp->var_double << ")" << std::endl; std::cout << "number of comp history = " << proot->history.size() << " (max = " << MAX_HISTORY << ") " << std::endl; } else { /* 对已经存在的pmem_pool,将读取root对象中的1个基础类型变量count和1个复合类型变量comp * 输出它们的值后,做一定修改,并将更新的值持久化写入pmem, * 同时还会将旧值加入到comp的历史值vector中,并以旧到新的顺序,输出其所有历史值。 */ std::cout << "Read old pmem data: " << std::endl; std::cout << "old count = " << proot->count << std::endl; std::cout << "old comp = (" << proot->comp->var_int << ", " << proot->comp->var_double << ")" << std::endl; /* 持久化指针persistent_ptr<>可以直接使用"*"来获取其指向的pmem内存对象 */ compound_type tmp = *(proot->comp); /* 持久化指针persistent_ptr<>可以直接使用get()函数来获取pmem内存对象的普通指针 */ compound_type *ptr_tmp = proot->comp.get(); /* make_persistent必须在transaction中使用,否则会抛异常,如果只对单独变量分配PMEM并无相关其它修改操作, * 也可以在transaction外直接使用make_persistent_atomic分配pmem内存对象。 * make_persistent_atomic也保证在分配pmem对象过程中程序意外终止,不会出现memory leak/dangling pointer等错误。 */ persistent_ptr<compound_type> pptr_tmp; make_persistent_atomic<compound_type>(pop, pptr_tmp, tmp.var_int, ptr_tmp->var_double); transaction::run(pop, [&] { /* 修改pmem对象,也可以在transaction中直接使用"->"调用对象的成员函数,或者访问对象的成员变量,并保证修改的持久化和原子性。*/ proot->comp->set_var_int(tmp.var_int + 1); proot->comp->var_double = tmp.var_double + 0.1; proot->count = proot->count + 1; /* 持久化vector,pmem::obj::vector<>使用方法和标准的std::vector<>非常相似,此示例将原先的旧数据加入到history中 */ proot->history.emplace_back(pptr_tmp); }); std::cout << "Update new pmem data: " << std::endl; std::cout << "new count = " << proot->count << std::endl; std::cout << "new comp = (" << proot->comp->var_int << ", " << proot->comp->var_double << ")" << std::endl; std::cout << "number of comp history = " << proot->history.size() << " (max = " << MAX_HISTORY << ") " << std::endl; std::cout << "last " << MAX_HISTORY << " comp values (from oldest to lastest) are :" << std::endl; size_t pos = 1; /* 和标准vector一样,持久化vector也支持迭代器,此示例程序使用它遍历持久化vector输出comp历史值 */ for (auto it = proot->history.begin(); it != proot->history.end(); it++) { std::cout << "\t[" << pos++ << "] : "; std::cout << "(" << (*it)->var_int << ", " << (*it)->var_double << ")" << std::endl; } /* 当此时comp的历史值数量达到预设值MAX_HISTORY,我们将丢弃最旧的那个历史值 */ if (proot->history.size() == MAX_HISTORY) { /* 使用迭代器获取最旧的历史值 */ auto it_comp = proot->history.begin(); transaction::run(pop, [&] { /* delete_persistent必须在transaction中调用,它会保证pmem空间被正确释放,同时会自动调用compound_type的析构函数。 * 此示例程序使用它释放comp的最旧历史值所占的PMEM内存,*it_comp会返回persistent_ptr<compound_type> */ delete_persistent<compound_type>(*it_comp); /* 同时将最旧的历史值从持久化vector中移除 */ proot->history.erase(it_comp); }); } } /* 关闭pmem pool可以确保数据持久化 */ pop.close(); }
true
e284b0b902301d449bbfc1c25f271a6e8a741e62
C++
lojpark/CodeForces
/Round #568 Div. 2/B - Email from Polycarp.cpp
UTF-8
905
2.78125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(NULL); int n; string s, t; cin >> n; for (int i = 1; i <= n; i++) { cin >> s; cin >> t; int sn = (int)s.size(); int tn = (int)t.size(); if (sn > tn) { cout << "NO" << endl; continue; } int si = 0, sc; int ti = 0, tc; char sv, tv; bool flag = false; while (true) { sc = tc = sv = tv = 0; for (; si < sn; si++) { sv = s[si]; sc++; if (si + 1 > sn - 1 || s[si] != s[si + 1]) { si++; break; } } for (; ti < tn; ti++) { tv = t[ti]; tc++; if (ti + 1 > tn - 1 || t[ti] != t[ti + 1]) { ti++; break; } } if (sv != tv || sc > tc) break; if (si == sn && ti == tn) { flag = true; break; } } if (flag) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
true
e9e500dc8e513cf5cdd6e657c39ab8e4401f1f79
C++
RobertKraaijeveld/GrandeOmegaVisualization
/lib/DataProcesser/src/Utilities/JSONEncoder.cpp
UTF-8
2,721
2.8125
3
[]
no_license
#include "Utilities.h" #include "../StatisticalAnalyzer/GenericVector/GenericVector.h" #include "../StatisticalAnalyzer/Point/IClusteringPoint.h" #include "JSONEncoder.h" #include <vector> #include <string> /* This .cpp file is separate from the .inl file exists because clustersToJSON does not use any template parameters; Putting its implementation in JSONEncoder.inl and then including JSONEncoder.inl in JSONEncoder.h would therefore produce linker errors. SO, we define it in a normal cpp file instead. */ std::string JSONEncoder::clustersToJSON(std::vector<std::vector<std::shared_ptr<IClusteringPoint>>> clusters) { stringstream returnJSONStr; //obj opening brace returnJSONStr << "[" << "\n"; int clusterCounter = 0; std::vector<std::vector<std::shared_ptr<IClusteringPoint>>> nonEmptyClusters; //removing empty clusters for (size_t j = 0; j < clusters.size(); j++) if (clusters[j].size() > 0) nonEmptyClusters.push_back(clusters[j]); //all clusters for (int i = 0; i < nonEmptyClusters.size(); i++) { size_t lastClusterIndex = nonEmptyClusters.size(); clusterCounter++; //opening brace for cluster returnJSONStr << "{ \"name\": \"" << clusterCounter << "\", \"data\": [" << endl; //vectors in a single cluster for (int j = 0; j < nonEmptyClusters[i].size(); j++) { //opening brace for vector pair returnJSONStr << "{"; //values in a single vector for (int z = 0; z < nonEmptyClusters[i][j]->getVector().values.size(); z++) { size_t currVectorSize = nonEmptyClusters[i][j]->getVector().values.size(); //todo: generify for > 2 dimensional KMeans if (z == 0) returnJSONStr << "\"x\": " << '"' << nonEmptyClusters[i][j]->getVector().values[z] << '"' << ','; else returnJSONStr << "\"y\": " << '"' << nonEmptyClusters[i][j]->getVector().values[z] << '"'; } size_t lastClusterVectorIndex = nonEmptyClusters[i].size() - 1; //closing brace for vector pair returnJSONStr << "}"; //comma if theres clusters left to go if (i != lastClusterIndex && j != lastClusterVectorIndex) returnJSONStr << ", "; } //closing brace of entire cluster if (i != (lastClusterIndex - 1)) { returnJSONStr << "] }," << endl; } else returnJSONStr << "] }" << endl; } //final json obj closing brace returnJSONStr << " ]"; return returnJSONStr.str(); }
true
6c08e74481a3bc3f64bea047f4ba4a6e2bc0e8a4
C++
46ccac1474d000676430445ffc4b160a/Algo
/term_paper/Term_paper/App/Trie/trie.cpp
UTF-8
3,883
2.953125
3
[]
no_license
#include "trie.hpp" int Node_p::p_indexHelper(const QChar &c) { QChar ch = c.toLower(); int index = ( ch.row() << 8 ) | ch.cell(); if ('a' <= index && index <= 'z') return index - 'a'; else if (1072 <= index && index <= 1103) return (index - 1072) + 26; //ru а-я else if (index == 1105) return 58; //ru ё else if('0' <= index && index <= '9') return (index - '0') + 59; else if (index == '-') return 69; else return -1; } QChar Node_p::p_letterHelper(int index) { if (0 <= index && index <= 25) return QChar(index + 'a'); else if (26 <= index && index <= 57) return QChar(index - 26 + 1072); //ru а-я else if (index == 58) return QChar(1105); //ru ё else if (59 <= index && index <= 68) return QChar(index - 59 + '0'); else if (index == 69) return QChar('-'); else return QChar(); } Node_p::Node_p(Node_p *parent) : m_parent(parent), isEnd(false) { } Node_p *Node_p::parent() const { return m_parent; } Node_p *Node_p::at(const QChar &c) const { int index = p_indexHelper(c); if (index < 0) throw std::range_error("in \"Node_p *Node_p::operator [](const QChar &c)\" range error"); return d[index]; } bool Node_p::isEmpty() const { for (int i = 0; i < CAP; i++) { if (d[i] != 0x0) return false; } return !isEnd; } void Node_p::set(const QChar &c, Node_p *node) { int index = p_indexHelper(c); if (index < 0) throw std::range_error("in \"void Node_p::set(const QChar &c, Node_p *node)\" range error"); delete d[index]; d[index] = node; } void Node_p::setParent(Node_p *parent) { m_parent = parent; } Node_p::~Node_p() { for (int i = 0; i < CAP; i++) delete d[i]; } void Trie::p_wordsHelper(Node_p *node, QString word, QStringList &list, int n) { for (int i = 0; i < CAP; i++) { Node_p *t = node->d[i]; if (t) { QChar c = Node_p::p_letterHelper(i); if (t->isEnd) { list << word+c; n--; } if (n) p_wordsHelper(t, word+c, list, n); else return; } } } Trie Trie::s_trie = Trie(); Trie &Trie::obj() { return s_trie; } Trie::~Trie() { delete root; } bool Trie::isEmpty() const { return root->isEmpty(); } QStringList Trie::words(const QString &preffix, int n) const { Node_p *node = root; foreach (const QChar &c, preffix) { if ( (node = node->at(c)) == 0x0) return QStringList(); } QStringList s_list; QString str = preffix; p_wordsHelper(node, str, s_list, n); return s_list; } bool Trie::contains(const QString &word) const { Node_p *node = root; foreach (const QChar &c, word) { if ( (node = node->at(c)) == 0x0) return false; } return node->isEnd; } void Trie::addWord(const QString &word) { Node_p *node = root; foreach (QChar c, word) { if (Node_p::p_indexHelper(c) < 0) c = '-'; Node_p *t = node->at(c); if (t == 0x0) { t = new Node_p(node); node->set(c, t); } node = t; } node->isEnd = true; } Trie &Trie::operator <<(const QString &word) { addWord(word); return *this; } Trie &Trie::operator <<(const QStringList &dict) { foreach (const QString &word, dict) { addWord(word); } return *this; } void Trie::remove(const QString &word) { Node_p *node = root; QString stack; foreach (const QChar &c, word) { if ( (node = node->at(c)) == 0x0) return; stack.prepend(c); } node->isEnd = false; foreach (const QChar &c, stack) { if ( (node = node->parent()) == 0x0) return; if (!node->isEmpty()) return; node->set(c, 0x0); } } void Trie::clear() { delete root; root = new Node_p(); }
true
8ea470e324213bed6d0d45752191e8032fd15ea7
C++
lpkruger/sfe-tools
/sfe/C-sfe/src/crypto/cipher/EVPCipher.h
UTF-8
1,953
2.609375
3
[]
no_license
/* * EVPCipher.h * * Created on: Sep 3, 2009 * Author: louis */ #ifndef EVPCIPHER_H_ #define EVPCIPHER_H_ #include <openssl/evp.h> #include <openssl/rand.h> #include "cipher.h" #include "sillytype.h" namespace crypto { void throwCipherError(const char* localerr = NULL); namespace cipher { struct EVPParams : public AlgorithmParams { byte_buf *IV; uint rounds; // EVP_BytesToKey is used if rounds>0 EVP_MD *md; uchar *salt; // 8 bytes bool nopadding; EVPParams(byte_buf *I0=NULL, uint r0=0, EVP_MD *m0=NULL, uchar *s=NULL, bool nopad=false) : IV(I0), rounds(r0), md(m0), salt(s), nopadding(nopad) {} EVPParams(bool nopad, byte_buf *I0=NULL, uint r0=0, EVP_MD *m0=NULL, uchar *s=NULL) : IV(I0), rounds(r0), md(m0), salt(s), nopadding(nopad) {} }; class EVPCipher : public Cipher { modes mode; //const EVP_CIPHER *cipher; EVP_CIPHER_CTX c_ctx; byte_buf out_buffer; public: EVPCipher(const EVP_CIPHER *c, int keylen=0); EVPCipher(const char *name, int keylen=0); ~EVPCipher(); virtual void init(modes mode, const SecretKey *sk, const AlgorithmParams *params=NULL); virtual void update(const byte *input, int len); virtual byte_buf doFinal(const byte *input, int len); virtual uint bytesAvailable() { return out_buffer.size(); } virtual byte_buf getOutput() { byte_buf ret_buffer; ret_buffer.swap(out_buffer); return silly_move(ret_buffer); } int getBlockSize() { return EVP_CIPHER_CTX_block_size(&c_ctx); //return EVP_CIPHER_block_size(cipher); } int getKeySize() { return EVP_CIPHER_CTX_key_length(&c_ctx); //return EVP_CIPHER_key_length(cipher); } int getIVSize() { return EVP_CIPHER_CTX_iv_length(&c_ctx); //return EVP_CIPHER_iv_length(cipher); } const char* getCipherName() { return EVP_CIPHER_name(c_ctx.cipher); } static void init_all_algorithms(); static vector<string> enumerate_ciphers(); static vector<string> enumerate_digests(); }; } } #endif /* EVPCIPHER_H_ */
true
c1b8cf3427b946b818ab8efed481ea422ebe1343
C++
VitaliyOschepkov/Labs_PSTU2
/14. Базы данных/Lab_14/List.h
WINDOWS-1251
3,533
3.296875
3
[]
no_license
#pragma once #include <iostream> #include <iomanip> #include <list> #include "Temperature.h" using namespace std; typedef list<Temperature> List; typedef List::iterator Lit; List listMake(int n) { List l; for (int i = 0; i < n; i++) { int d = rand() % 30; int t = rand() % 60 - 30; Temperature a(d, t); l.push_back(a); } return l; } void listPrint(List l) { cout << "| : |\n"; for (Lit i = l.begin(); i != l.end(); i++) cout << (*i); cout << "\n"; } void Reserve(List l, List& r) { r.clear(); for (Lit i = l.begin(); i != l.end(); i++) r.push_back((*i)); } void Recover(List& l, List r) { l.clear(); for (Lit i = r.begin(); i != r.end(); i++) l.push_back((*i)); } void positionDel(List& l, int p) { if (p > l.size()) { cout << " \n"; return; } Lit i = l.begin(); while (--p) i++; (*i).set_del(true); } void markedDel(List& l) { List t; for (Lit i = l.begin(); i != l.end(); i++) { if (!(*i).get_del()) t.push_back((*i)); } l = t; } int markedCount(List l) { int c = 0; for (Lit i = l.begin(); i != l.end(); i++) if ((*i).get_del()) c++; return c; } void operationDel(List& l, List& b) { if (markedCount(l) > (l.size() / 2)) { markedDel(l); cout << " \n"; } b.clear(); b = l; } void delByKey(List& l, Temperature k) { Lit i = l.begin(); while ((*i) != k) { i++; if (i == l.end()) { cout << " \n"; return; } } (*i).set_del(true); } void positionAdd(List& l, Temperature e, int p) { Lit i = l.begin(); while (p--) i++; l.emplace(i, e); } void positionCheange(List& l, Temperature e, int p) { Lit i = l.begin(); while (p--) i++; (*i) = e; } void cheangeByKey(List& l, Temperature e, Temperature k) { for (Lit i = l.begin(); i != l.end(); i++) if ((*i) == k) (*i) = e; } void endAdd(List& l, Temperature e) { l.push_back(e); } void beginAdd(List& l, Temperature e) { l.push_front(e); } Temperature Average(List l) { Temperature a; int n = l.size() - markedCount(l); for (Lit i = l.begin(); i != l.end(); i++) a = a + (*i); return a / n; } void AverageByDay(List l) { List t; Temperature a = Average(l); cout << " " << a.get_temp() << "\n"; for (Lit i = l.begin(); i != l.end(); i++) if ((*i) > a) t.push_back((*i)); listPrint(t); } int minimalTempRange(List l) { list<int> lt; list<int>::iterator it; int r = 0; int mr = 0; for (Lit i = l.begin(); i != l.end(); i++) { if ((*i) > 0) { if (!(*i).get_del()) r++; lt.push_back(r); } else r = 0; } for (it = lt.begin(); it != lt.end(); it++) { if (mr < (*it)) mr = (*it); } return mr; } void elementAdd(List& l, Temperature e) { for (Lit i = l.begin(); i != l.end(); i++) (*i) = (*i) + e; }
true
679d91fe1df48f9936017945249e6f1ebd8f5e90
C++
sarachour/topaz
/src/common/scheduler/scheduler.cpp
UTF-8
679
2.78125
3
[]
no_license
#include "machine.h" #include "task.h" #include "scheduler.h" Scheduler::Scheduler(MachineNetwork * network){ this->size = network->getSize(); this->nodes = new ScheduleNode[this->size]; int main_id = network->getMain().getId(); this->nodes[main_id].setBaselineCost(1.0); } //dummy scheduler int Scheduler::schedule(Task * t){ float cost = 1.0; float mach = -1; //find the cheapest machine for(int i=0; i < this->size; i++){ float mcost = this->nodes[i].getCost(t); if(mcost <= cost || mach == -1){ cost = mcost; mach = i; } } return mach; } void Scheduler::addTask(TASK_HANDLE t){ for(int i=0; i < this->size; i++){ this->nodes[i].addTask(t); } }
true
7411524092eb62c87008d0fd00f94e367fa03cc2
C++
MariusGrumer/Info2Labor
/CStackQueue/CStackQueue/CStack.h
ISO-8859-1
382
2.796875
3
[]
no_license
#pragma once #include"CMessage.h" class CStack // LIFO wchst nach oben, zeigt auf Leerelement { public: CStack(int pSize); // ctor mit param, Groee bei Aufruf ~CStack(); bool add(CMessage& pMsg); bool get(CMessage& pMsg); private: int mSize; // store Size unsigned int mIndex; // Stackpointer CMessage* mStackPtr; // zeigt auf dynamisches Array };
true
d8ff1a222d15633dda052f9bf6a2e0daae4b5167
C++
kamontesanti/Advanced-Digital-Design-using-SystemVerilog
/temperature_app.cpp
UTF-8
6,540
3
3
[]
no_license
/* * ECE 4305L - EXP #11 "Temperature Reading" * * APPLICATION FILE FOR READING THE TEMPERATURE FROM THE ADT7420 ONBOARD TEMPERATURE SENSOR: * * AUTHOR: KYLE A. MONTESANTI */ // required libraries for application file: #include "chu_init.h" #include "gpio_cores.h" #include "sseg_core.h" #include "i2c_core.h" // define any function prototypes: void btn_ctrl(DebounceCore); void temp_control(I2cCore, SsegCore); void init_system(SsegCore); // array for turning each 7-Segment Display off: const uint8_t off_ptn[]={0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}; // all off encodings int btn_val = 0; // constant button value reading for operations // control the button operations: void btn_ctrl(DebounceCore *btn_p) { // keep an integer for operations for real-time results: if (btn_p -> read_db(0)) btn_val = 1; else if (btn_p -> read_db(2)) btn_val = 2; else if (btn_p -> read_db(3)) btn_val = 3; else if (btn_p -> read_db(1)) btn_val = 0; } // function to initialize the system: void init_system(SsegCore *sseg_p) { // initialize system with display off: sseg_p -> set_dp(0x00); // ensure all decimal points are off sseg_p -> write_8ptn((uint8_t *)off_ptn); // turn the display off } // function to read the temperature data and provide the required output specified by directions: void temp_control(I2cCore *adt7420_p, SsegCore *sseg_p) { const uint8_t DEV_ADDR = 0x4b; // device address for ADT7420 temperature sensor uint8_t wbytes[2], bytes[2]; // arrays for writing/reading data uint16_t temp; float temp_c, temp_f; // variables for celsius temperature and farhenheit temperature // variables for isolating the decimal values of the temperature: int c_tenths, c_hundths, c_ones, c_tens; int f_tenths, f_hundths, f_ones, f_tens; // read the device ID to verify the connection and proper communication location: wbytes[0] = 0x0b; // location of ID for ADT7420 register adt7420_p -> write_transaction(DEV_ADDR, wbytes, 1, 1); // write transaction then restart adt7420_p -> read_transaction(DEV_ADDR, bytes, 1, 0); // read transaction // access the temperature information from the sensor: wbytes[0] = 0x00; // location of base information for the temperature values adt7420_p->write_transaction(DEV_ADDR, wbytes, 1, 1); // write transaction then restart adt7420_p->read_transaction(DEV_ADDR, bytes, 2, 0); // read into the array // perform an automatic celsius conversion: temp = (uint16_t) bytes[0]; // cast 8-bit value into 16-bit integer value temp = (temp << 8) + (uint16_t) bytes[1]; // pack data accordingly (Reg 0 -> Upper Byte ; Reg 1 -> Lower Byte) temp = temp >> 3; // right shift since 13 bits // calculate the temperature value in celsius as default: temp_c = (float) temp / 16; // equation for a positive value temp_f = (temp_c * 1.8) + 32.0; // convert to fahrenheit value /*uart.disp("temperature (C): "); uart.disp(temp_c); uart.disp("\n\r"); uart.disp("temperature (F): "); uart.disp(temp_f); uart.disp("\n\r");*/ // isolate the values: c_tens = (int) (temp_c / 10.0); // isolate the ten's place c_ones = (int) (temp_c) % 10; // isolate the one's place c_tenths = (int) (temp_c * 10) % 10; // isolate the tenth's place c_hundths = (int) (temp_c * 100) % 10; // isolate the hundredth's place f_tens = (int) (temp_f / 10.0); // isolate the ten's place f_ones = (int) (temp_f) % 10; // isolate the one's place f_tenths = (int) (temp_f * 10) % 10; // isolate the tenth's place f_hundths = (int) (temp_f * 100) % 10; // isolate the hundredth's place // determine the control operation for which output to display to user: if (btn_val == 1) { // up button (BTN 0) indicates only celsius output: sseg_p -> set_dp(0x40); // turn appropriate decimal point on // write the celsius values to the sseg: sseg_p -> write_1ptn(sseg_p->h2s(12), 3); // output "C" for unit sseg_p -> write_1ptn(sseg_p->h2s(c_hundths), 4); // cast values to the 7-seg display sseg_p -> write_1ptn(sseg_p->h2s(c_tenths), 5); sseg_p -> write_1ptn(sseg_p->h2s(c_ones), 6); sseg_p -> write_1ptn(sseg_p->h2s(c_tens), 7); // ensure the other segments are off as well: for (int i = 0; i < 3; i++) { sseg_p -> write_1ptn(0xff, i); } } else if (btn_val == 2) { // down button (BTN 2) indicates only fahrenheit output: sseg_p -> set_dp(0x40); // turn appropriate decimal point on // write the fahrenheit values to the sseg: sseg_p -> write_1ptn(sseg_p->h2s(15), 3); // output "F" for unit sseg_p -> write_1ptn(sseg_p->h2s(f_hundths), 4); // cast values to the 7-seg display sseg_p -> write_1ptn(sseg_p->h2s(f_tenths), 5); sseg_p -> write_1ptn(sseg_p->h2s(f_ones), 6); sseg_p -> write_1ptn(sseg_p->h2s(f_tens), 7); // ensure the other segments are off as well: for (int i = 0; i < 3; i++) { sseg_p -> write_1ptn(0xff, i); } } else if (btn_val == 3) { // left button (BTN 3) indicates both fahrenheit and celsius output: sseg_p -> set_dp(0x44); // turn appropriate decimal point on // wirte the celsius values to the sseg: sseg_p -> write_1ptn(sseg_p->h2s(c_hundths), 0); // cast values to the 7-seg display sseg_p -> write_1ptn(sseg_p->h2s(c_tenths), 1); sseg_p -> write_1ptn(sseg_p->h2s(c_ones), 2); sseg_p -> write_1ptn(sseg_p->h2s(c_tens), 3); // write the fahrenheit values to the sseg: sseg_p -> write_1ptn(sseg_p->h2s(f_hundths), 4); // cast values to the 7-seg display sseg_p -> write_1ptn(sseg_p->h2s(f_tenths), 5); sseg_p -> write_1ptn(sseg_p->h2s(f_ones), 6); sseg_p -> write_1ptn(sseg_p->h2s(f_tens), 7); } else if (btn_val == 0) { // right button (BTN 1) indicates the display is off: sseg_p -> set_dp(0x00); // ensure all decimal points are off sseg_p -> write_8ptn((uint8_t *)off_ptn); // turn the display off } } // instantiate objects of the required classes: DebounceCore btn(get_slot_addr(BRIDGE_BASE, S7_BTN)); SsegCore sseg(get_slot_addr(BRIDGE_BASE, S8_SSEG)); I2cCore adt7420(get_slot_addr(BRIDGE_BASE, S10_I2C)); // main function: int main() { init_system(&sseg); // infinitely loop the following function: while (1) { btn_ctrl(&btn); temp_control(&adt7420, &sseg); } }
true
8a79d5d101e1cd4088e5f25619ef7e14f6723c38
C++
oyugibillbrian2017/c-codes
/a.cpp
UTF-8
232
3.515625
4
[]
no_license
// a program which computes and displays the average of 3 numbers entered by the user. #include <iostream> using namespace std; int main() { int a; int b; int c; float average; average=(a+b+c)/3; cout<<"average"; return 0; }
true
a76ec03453293d53ca75e8bf29f60cff2b1403d8
C++
braedenb/SSE662
/Battle_Ship/Battleship/Battleship/battleship_matt.cpp
UTF-8
5,021
3.421875
3
[]
no_license
// roytest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <string> using namespace std; void InitializeBoards(); void PrintBoard(int n); void SetupBoards(); void setShip(int n, string ship); bool validShipPlacement(int n, int pos); void playGame(); void fire(); void countHits(); void printHits(int n); bool validTarget(int pos); string board1[8][8], board2[8][8]; bool board1hit[8][8], board2hit[8][8]; int hits1, hits2; int main() { InitializeBoards(); PrintBoard(1); PrintBoard(2); SetupBoards(); playGame(); string end; cin >> end; return 0; } void InitializeBoards() { hits1 = 0; hits2 = 0; for (int i = 0; i<8; i++) { for (int j = 0; j<8; j++) { board1[i][j] = to_string(10*(i+1) + (j+1)); board2[i][j] = to_string(10*(i+1) + (j+1)); board1hit[i][j] = false; board2hit[i][j] = false; } } } void PrintBoard(int n) { cout << "Player " << n << "'s Board:" << endl; if (n == 1) { for (int i = 0; i<8; i++) { for (int j = 0; j < 8; j++) cout << board1[i][j] << " "; cout << endl; } } else if (n == 2) { for (int i = 0; i<8; i++) { for (int j = 0; j<8; j++) cout << board2[i][j] << " "; cout << endl; } } cout << endl; } void SetupBoards() { for (int n = 1; n < 3; n++) { cout << "Player " << n << ", enter your ships' positions:" << endl; cout << "Battle ship (3 spaces)" << endl; for (int i = 0; i < 3; i++) { setShip(n, "BA"); } cout << "Patrol boat (2 spaces)" << endl; for (int i = 0; i < 2; i++) { setShip(n, "PA"); } cout << "Submarine (3 spaces)" << endl; for (int i = 0; i < 3; i++) { setShip(n, "SU"); } cout << "Destroyer (4 spaces)" << endl; for (int i = 0; i < 4; i++) { setShip(n, "DA"); } cout << "Aircraft carrier (5 spaces)" << endl; for (int i = 0; i < 5; i++) { setShip(n, "AC"); } cout << endl << "Here is your board:" << endl << endl; PrintBoard(n); } } void setShip(int n, string ship) { cout << "Position : "; int pos; cin >> pos; while (!validShipPlacement(n, pos)) { cout << "Invalid position, try again : "; cin >> pos; } int i = pos / 10; int j = pos - (i*10); if (n == 1) board1[i-1][j-1] = ship; if (n == 2) board2[i-1][j-1] = ship; } bool validShipPlacement(int n, int pos) { if (validTarget(pos)) { int i = pos / 10; int j = pos - (i * 10); if (n == 1) { if (board1[i - 1][j - 1] == to_string(10 * i + j)) return true; else return false; } if (n == 2) { if (board2[i - 1][j - 1] == to_string(10 * i + j)) return true; else return false; } } else return false; } void playGame() { while (hits1 < 17 && hits2 < 17) { fire(); countHits(); } if (hits1 == 17) cout << "Player 2 wins!" << endl; if (hits2 == 17) cout << "Player 1 wins!" << endl; } void fire() { //Player 1 fire on Player 2's board //Pick target cout << "Player 1, enter your target : "; int pos; cin >> pos; while (!validTarget(pos)) { cout << "Invalid target, try again : "; cin >> pos; } //Fire int i = pos / 10; int j = pos - (i * 10); if (board2[i - 1][j - 1] != to_string(10 * i + j)) { board2hit[i - 1][j - 1] = true; cout << "Target hit!" << endl; } else cout << "Miss!" << endl; printHits(1); //Player 2 fire on Player 1's board //Pick target cout << "Player 2, enter your target : "; cin >> pos; while (!validTarget(pos)) { cout << "Invalid target, enter new target : "; cin >> pos; } //Fire i = pos / 10; j = pos - (i * 10); if (board1[i - 1][j - 1] != to_string(10 * i + j)) { board1hit[i - 1][j - 1] = true; cout << "Target hit!" << endl; } else cout << "Miss!" << endl; printHits(2); } bool validTarget(int pos) { if ((pos > 10 && pos < 19) || (pos > 20 && pos < 29) || (pos > 30 && pos < 39) || (pos > 40 && pos < 49) || (pos > 50 && pos < 59) || (pos > 60 && pos < 69) || (pos > 70 && pos < 79) || (pos > 80 && pos < 89)) { return true; } else return false; } void countHits() { //Total hits on each board hits1 = 0; hits2 = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board1hit[i][j]) hits1++; if (board2hit[i][j]) hits2++; } } } void printHits(int n) { countHits(); cout << "Targets hit : " << endl; //Hits on board 2 by player 1 if (n == 1) { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) if (board2hit[i][j]) cout << i + 1 << j + 1 << endl; cout << hits2 << " total hits" << endl; } //Hits on board 1 by player 2 if (n == 2) { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) if (board1hit[i][j]) cout << i + 1 << j + 1 << endl; cout << hits1 << " total hits" << endl; } }
true
7cd769af06f3d2ec039d6969ebf5ea68457b1b21
C++
orbs-network/orbs-network-typescript
/client/crypto-sdk/lib/utils.cpp
UTF-8
987
3.28125
3
[ "MIT", "LGPL-2.0-only" ]
permissive
#include "utils.h" #include <iomanip> #include <iostream> #include <stdexcept> using namespace std; using namespace Orbs; const string Utils::Vec2Hex(const vector<uint8_t> &data) { stringstream ss; ss << hex << setfill('0'); for (uint8_t i : data) { ss << setw(2) << static_cast<unsigned>(i); } return ss.str(); } static const string HEX_ALPHABET("0123456789abcdefABCDEF"); const vector<uint8_t> Utils::Hex2Vec(const string &data) { if (data.length() % 2 != 0) { throw invalid_argument("Invalid data length!"); } if (data.find_first_not_of(HEX_ALPHABET) != string::npos) { throw invalid_argument("Invalid hex data!"); } vector<uint8_t> res; res.reserve(data.length() / 2); for (string::size_type i = 0; i < data.length(); i += 2) { unsigned byte; istringstream strm(data.substr(i, 2)); strm >> hex >> byte; res.push_back(static_cast<uint8_t>(byte)); } return res; }
true
009ecddb2776fc8c3d644cd60bb5f36e7a291028
C++
redknotmiaoyuqiao/VideoHomework
/common/RedVideoFormat/RedByte.cpp
UTF-8
605
2.875
3
[]
no_license
#include "RedByte.hpp" RedByte::RedByte() { } RedByte::~RedByte() { if(data != NULL){ free(data); data = NULL; } } int RedByte::PushData(unsigned char * _data, int _length) { unsigned char * tempData = (unsigned char *)malloc(dataLength + _length); int pos = 0; if(data != NULL){ memcpy(tempData + pos, data, dataLength); pos += dataLength; } memcpy(tempData + pos, _data, _length); pos += _length; dataLength += _length; if(data != NULL){ free(data); data = NULL; } data = tempData; return 0; }
true
b79786dca085c8beb05c6443f94915c39c72c095
C++
adamikandras/error_or
/examples/foo.hpp
UTF-8
5,011
2.609375
3
[ "Apache-2.0" ]
permissive
// Copyright 2013 Andrew C. Morrow // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef included_1194ba38_e51a_4c64_b628_3f907e697307 #define included_1194ba38_e51a_4c64_b628_3f907e697307 #include <memory> #include <cstdio> #include "../detail/is_nothrow_swappable.hpp" namespace acm { class __attribute__((visibility("default"))) Foo { public: std::unique_ptr<int> token; Foo(); Foo(const Foo& other); Foo(Foo&& other); Foo& operator=(const Foo& other); Foo& operator=(Foo&& other); ~Foo(); }; static_assert(acm::detail::is_swappable<Foo>::value, "Foo should be swappable"); static_assert(!acm::detail::is_nothrow_swappable<Foo>::value, "Foo should not be nothrow swappable"); class __attribute__((visibility("default"))) FooNoExcept { public: std::unique_ptr<int> token; FooNoExcept() noexcept; FooNoExcept(const FooNoExcept& other) noexcept; FooNoExcept(FooNoExcept&& other) noexcept; FooNoExcept& operator=(const FooNoExcept& other) noexcept; FooNoExcept& operator=(FooNoExcept&& other) noexcept; ~FooNoExcept() noexcept; }; static_assert(acm::detail::is_swappable<FooNoExcept>::value, "FooNoExcept should be swappable"); static_assert(acm::detail::is_nothrow_swappable<FooNoExcept>::value, "FooNoExcept should be nothrow swappable"); class __attribute__((visibility("default"))) FooInline { public: std::unique_ptr<int> token; FooInline(); FooInline(const FooInline& other); FooInline(FooInline&& other); FooInline& operator=(const FooInline& other); FooInline& operator=(FooInline&& other); ~FooInline(); }; class __attribute__((visibility("default"))) FooInlineNoExcept { public: std::unique_ptr<int> token; FooInlineNoExcept() noexcept; FooInlineNoExcept(const FooInlineNoExcept& other) noexcept; FooInlineNoExcept(FooInlineNoExcept&& other) noexcept; FooInlineNoExcept& operator=(const FooInlineNoExcept& other) noexcept; FooInlineNoExcept& operator=(FooInlineNoExcept&& other) noexcept; ~FooInlineNoExcept() noexcept; }; FooInline::FooInline() : token(new int(17)) { printf("X FooInline()\n"); } FooInline::FooInline(const FooInline& other) : token(new(std::nothrow) int(*other.token.get())) { printf("X FooInline(const FooInline&)\n"); } FooInline::FooInline(FooInline&& other) : token(std::move(other.token)) { printf(" FooInline(FooInline&&)\n"); } FooInline& FooInline::operator=(const FooInline& other) { token.reset(new(std::nothrow) int(*other.token.get())); printf("X FooInline& operator=(const FooInline&)\n"); return *this; } FooInline& FooInline::operator=(FooInline&& other) { token = std::move(other.token); printf(" FooInline& operator=(FooInline&&)\n"); return *this; } FooInline::~FooInline() { if (token) printf("X"); else printf(" "); printf(" ~FooInline()\n"); } FooInlineNoExcept::FooInlineNoExcept() noexcept : token(new(std::nothrow) int(17)) { printf("X FooInlineNoExcept()\n"); } FooInlineNoExcept::FooInlineNoExcept(const FooInlineNoExcept& other) noexcept : token(new(std::nothrow) int(*other.token.get())) { printf("X FooInlineNoExcept(const FooInlineNoExcept&)\n"); } FooInlineNoExcept::FooInlineNoExcept(FooInlineNoExcept&& other) noexcept : token(std::move(other.token)) { printf(" FooInlineNoExcept(FooInlineNoExcept&&)\n"); } FooInlineNoExcept& FooInlineNoExcept::operator=(const FooInlineNoExcept& other) noexcept { token.reset(new(std::nothrow) int(*other.token.get())); printf("X FooInlineNoExcept& operator=(const FooInlineNoExcept&)\n"); return *this; } FooInlineNoExcept& FooInlineNoExcept::operator=(FooInlineNoExcept&& other) noexcept { token = std::move(other.token); printf(" FooInlineNoExcept& operator=(FooInlineNoExcept&&)\n"); return *this; } FooInlineNoExcept::~FooInlineNoExcept() noexcept { if (token) printf("X"); else printf(" "); printf(" ~FooInlineNoExcept()\n"); } } // namespace acm #endif // included_1194ba38_e51a_4c64_b628_3f907e697307
true
a542fc3fd021bd350b5159a72746df6d65d706d4
C++
israelElad/AP1-FlightSimulator-Interpreter
/BindCommand.cpp
UTF-8
931
2.8125
3
[]
no_license
#include <regex> #include "BindCommand.h" BindCommand::BindCommand(DataCommands *dataCommands, DataBinds *dataBinds) { this->dataCommands = dataCommands; this->dataBinds = dataBinds; } void BindCommand::doCommand() { // get the index from dataCommands unsigned long index = this->dataCommands->getIndex(); // skip the command index++; // get the nameInSimulator from the vector in dataCommands string nameInSimulator = this->dataCommands->getSeparated().at(index); // skip the nameInSimulator index++; unsigned long indexOfVarName = this->dataCommands->getIndex() - 2; // get the varName from the vector in dataCommands string varName = this->dataCommands->getSeparated().at(indexOfVarName); // add to the varToNameInSimulator map this->dataBinds->addNewBind(nameInSimulator, varName); // set the new index of dataCommands this->dataCommands->setIndex(index); }
true
71ae7a9d554003f47e86c3aa019fa6dda909e04d
C++
KadrusBAG/vector-0.0.2-2nd-sem-
/include/vector.hpp
UTF-8
3,956
3.671875
4
[]
no_license
#include <iostream> template <typename T> class vector_t { private: T* elements_; std::size_t size_; std::size_t capacity_; public: vector_t(); vector_t(vector_t const& other); vector_t& operator=(vector_t const& other); ~vector_t(); std::size_t size() const; std::size_t capacity() const; void push_back(T value); void pop_back(); T& operator[](std::size_t index); T operator[](std::size_t index) const; bool operator==(vector_t const& other) const; T& at(std::size_t index) { if (index >= size_) { throw std::out_of_range("Error"); } return (*this)[index]; } }; template <typename T> vector_t<T>::vector_t() { elements_ = nullptr; size_ = 0; capacity_ = 0; } template <typename T> vector_t<T>::vector_t(vector_t const& other) { size_ = other.size_; capacity_ = other.capacity_; elements_ = new T[capacity_]; for (std::size_t i = 0; i < size_; ++i) { elements_[i] = other.elements_[i]; } } template <typename T> vector_t<T>& vector_t<T>::operator=(vector_t const& other) { if (this != &other) { delete[] elements_; size_ = other.size_; capacity_ = other.capacity_; elements_ = new T[capacity_]; for (std::size_t i = 0; i < size_; ++i) { elements_[i] = other.elements_[i]; } } return *this; } template <typename T> bool vector_t<T>::operator==(vector_t const& other) const { bool success = true; if (size_ == other.size_ && capacity_ == other.capacity_) { for (std::size_t i = 0; i < size_; ++i) { if (elements_[i] != other.elements_[i]) { success = false; break; } } } else { success = false; } return success; } template <typename T> vector_t<T>::~vector_t() { delete[] elements_; } template <typename T> std::size_t vector_t<T>::size() const { return size_; } template <typename T> std::size_t vector_t<T>::capacity() const { return capacity_; } template <typename T> void vector_t<T>::push_back(T value) { if (capacity_ == 0) { capacity_ = 1; size_ = 1; elements_ = new T[capacity_]; elements_[0] = value; } else { if (size_ == capacity_) { T* massive; massive = new T[size_]; for (std::size_t i = 0; i < size_; ++i) { massive[i] = elements_[i]; } delete[] elements_; capacity_ = 2 * capacity_; elements_ = new T[capacity_]; for (std::size_t i = 0; i < size_; ++i) { elements_[i] = massive[i]; } delete[] massive; elements_[size_] = value; size_++; } else { elements_[size_] = value; size_++; } } } template <typename T> void vector_t<T>::pop_back() { size_--; if (size_ == 0 || size_ * 4 == capacity_) { T* massive; massive = new T[size_]; for (std::size_t i = 0; i < size_; ++i) { massive[i] = elements_[i]; } delete[] elements_; capacity_ = capacity_ / 2; elements_ = new T[capacity_]; for (std::size_t i = 0; i < size_; ++i) { elements_[i] = massive[i]; } delete[] massive; } } template <typename T> T& vector_t<T>::operator[](std::size_t index) { return elements_[index]; } template <typename T> T vector_t<T>::operator[](std::size_t index) const { return elements_[index]; } template <typename T> bool operator!=(vector_t<T> const& lhs, vector_t<T> const& rhs) { bool success = true; if (lhs == rhs) { success = !success; } return success; }
true
c25a3b59828368ee94b8cd84bada1497c4a4125a
C++
thien926/Thien
/UPCoder/DAYNP.cpp
UTF-8
446
2.5625
3
[]
no_license
#include<iostream> using namespace std; typedef unsigned long long int ll; typedef unsigned short int usi; void xuat(usi *a,ll n){ for(ll i=0;i<n;i++) cout<<a[i]; cout<<endl; } void quaylui(usi *a,ll n,ll j){ for(ll i=0;i<2;i++){ a[j]=i; if(j==n-1) xuat(a,n); else quaylui(a,n,j+1); } } int main(){ ll n; usi *a; cin>>n; a=new usi[n]; quaylui(a,n,0); delete []a; return 0; }
true
6a77711a4e679418546397a2470034e790056b0b
C++
mugisaku/pglang
/parser/pglang_parser__stream_character.cpp
UTF-8
1,333
2.96875
3
[]
no_license
#include"pglang_parser__stream.hpp" #include<cctype> #include<cstring> namespace pglang{ namespace parser{ uint64_t Stream:: get_character() { pointer = std::strchr(pointer,'\'')+1; uint64_t c = *pointer++; if(c == '\\') { auto uc = get_escchar(); c = uc; } if(*pointer != '\'') { throw invalid_character(); } ++pointer; return c; } char32_t Stream:: get_escchar() { char32_t c = *pointer++; switch(c) { case('n'): c = '\n';break; case('r'): c = '\r';break; case('f'): c = '\f';break; case('b'): c = '\b';break; case('0'): c = '\0';break; case('t'): c = '\t';break; case('u'): c = get_unichar16();break; case('U'): c = get_unichar32();break; default:; } return c; } char16_t Stream:: get_unichar16() { char16_t c = 0; for(int n = 0; n < 4; ++n) { int t; if(!get_hexadecimal_number(t)) { printf("error"); throw invalid_unicode(); } c <<= 4; c |= t; } return c; } char32_t Stream:: get_unichar32() { char32_t c = 0; for(int n = 0; n < 8; ++n) { int t; if(!get_hexadecimal_number(t)) { throw invalid_unicode(); } c <<= 4; c |= t; } return c; } }}
true
ced84dce4fec4d76b3652f800b5a5a938526ea48
C++
Stjowa/CS1
/Lab11_1/src/Lab11_1.cpp
UTF-8
2,397
4.34375
4
[]
no_license
//============================================================================ // Name : Lab11_1.cpp // Author : Stephen Walentik // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class RationalNumber { public: int num1, num2, denom1, denom2; int newNum1, newNum2, newNum3, newDenom1, newDenom2; void input(); void addition(); void subtraction(); void product(); void division(); void compareTo(); }; void RationalNumber::input() { cout<<"Please input the first fraction"<<endl; cin >> num1 >> denom1; cout<<"Please input the second fraction"<<endl; cin >> num2 >> denom2; } void RationalNumber::addition() { cout << "Addition:" <<endl; newNum1=num1*denom2; newDenom1=denom1*denom2; newNum2=num2*denom1; newDenom2=denom2*denom1; newNum3=newNum1+newNum2; cout << " " << newNum3 << "/" << newDenom1 <<endl; double num3=newNum3; cout << " " << num3/newDenom1<<endl; } void RationalNumber::subtraction() { cout << "Subtraction:" <<endl; newNum3=newNum1-newNum2; cout << " " << newNum3 << "/" << newDenom1 <<endl; double num3=newNum3; cout << " " << num3/newDenom1<<endl; } void RationalNumber::product() { cout << "Multiplication:" <<endl; cout << " " << num1*num2 << "/" << denom1*denom2 <<endl; double newerNum=num1*num2, newerDenom=denom1*denom2; cout << " " << newerNum/newerDenom<<endl; } void RationalNumber::division() { cout << "Division:" <<endl; cout << " " << num1*denom2 << "/" << denom1*num2 <<endl; double newerNum=num1*denom2, newerDenom=denom1*num2; cout << " " << newerNum/newerDenom<<endl; } void RationalNumber::compareTo() { cout << "Compare:" <<endl; double newerNum1=num1,newerNum2=num2,frac1,frac2; frac1= newerNum1/denom1; frac2= newerNum2/denom2; if(frac1>frac2) { cout << " " << num1 << "/" << denom1 <<endl; cout << " " << newerNum1/denom1 <<endl; } else if(frac1<frac2) { cout << " " << num2 << "/" << denom2 <<endl; cout << " " << newerNum2/denom2 <<endl; } else { cout << " " << "The fractions are equal."; } } int main() { RationalNumber ratNum; ratNum.input(); ratNum.addition(); ratNum.subtraction(); ratNum.product(); ratNum.division(); ratNum.compareTo(); return 0; }
true
f11ab3e45d17c24b7c99b6c15631bee39d48dcc4
C++
lepexys/projects
/SDL_Programm/SDL_Programm/main.cpp
UTF-8
34,576
2.640625
3
[]
no_license
#include <iostream> #include <fstream> #include <clocale> #include <stdlib.h> #include <SDL.h> #include <SDL_ttf.h> #include <SDL_image.h> using namespace std; struct Window { SDL_Window *win; SDL_Renderer *rend; }; struct Sym { int row, pos; char symbol; bool ihl; Sym(char s,int r, int p , bool b) { row = r; pos = p; symbol = s; ihl = b; } }; struct text { Sym *syms, *cs,*bff; TTF_Font *font; SDL_Rect symbox; SDL_Texture *list; char* nf; long i; int c; bool Load_Text(SDL_Renderer *rend, SDL_Rect wc, char* name) { bff = nullptr; nf = new char[20]; char *cur = (char*)malloc(1 * sizeof(char)); SDL_Rect rect; symbox.x = wc.x + 30; symbox.y = wc.y + 15; symbox.h = 16; symbox.w = 10; ifstream f; f.open(name); SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); SDL_RenderFillRect(rend, &wc); if (!f.is_open()) return false; strcpy(nf, name); i = 0; int r = 0, p = 0, w = 0, h = 0; syms = nullptr; while (!f.eof()) { f.read(cur, 1 * sizeof(char)); if (wc.w + wc.x < wc.x + 30 + p * symbox.w) { r++; p = 0; } if (cur[0] == '\n') { syms = (Sym*)realloc(syms, (i + 1) * sizeof(struct Sym)); syms[i] = Sym('\n', r, p, false); r++; p = 0; i++; } else { syms = (Sym*)realloc(syms, (i + 1) * sizeof(struct Sym)); syms[i] = Sym(cur[0], r, p, false); i++; p++; } } f.close(); cs = &syms[i]; if (symbox.y + symbox.h*r < wc.h) list = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, wc.w, wc.h); else list = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, wc.w, symbox.y + symbox.h*(r+1)); Draw(rend, wc); return true; } SDL_Rect Centrd(SDL_Rect r, int w, int h) { SDL_Rect ret; ret.x = r.x + r.w / 2 - w / 2; ret.y = r.y + r.h / 2 - h / 2; ret.w = w; ret.h = h; return ret; } void Draw(SDL_Renderer *rend,SDL_Rect wc) { SDL_Color color; color.r = 0; color.g = 0; color.b = 0; SDL_Rect rect; int w, h; SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); SDL_SetTextureBlendMode(list, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(rend, list); SDL_RenderClear(rend); for (int j = 0; j < i; j++) { if (syms[j].symbol != '\n') { SDL_Texture *t = SDL_CreateTextureFromSurface(rend, TTF_RenderUTF8_Blended(font, (char*)&syms[j].symbol, color)); SDL_QueryTexture(t, NULL, NULL, &w, &h); symbox.x = 30 + syms[j].pos * symbox.w; symbox.y = 15 + syms[j].row * symbox.h; rect = Centrd(symbox, w, h); SDL_RenderCopy(rend, t, NULL, &rect); SDL_DestroyTexture(t); } } rect = wc; rect.x = 0; rect.y = 0; SDL_SetRenderTarget(rend, NULL); SDL_RenderCopy(rend, list, &rect, &wc); SDL_RenderPresent(rend); } bool Search(SDL_Renderer *rend, SDL_Rect wc, int x, int y, int lx, int ly, int scrolled) { int r1, r2, p1, p2; if (x - wc.x - 30 < 0) p1 = 0; else p1 = (x - wc.x - 30) / symbox.w; if (lx - wc.x - 30 < 0) p2 = 0; else p2 = (lx - wc.x - 30) / symbox.w; if (y - wc.y - 15 < 0) r1 = 0; else r1 = (y - wc.y - 15 - scrolled) / symbox.h; if (ly - wc.y - 15 < 0) r2 = 0; else r2 = (ly - wc.y - 15 - scrolled) / symbox.h; if (r1 > r2) { return OutLine(rend, wc, r2, p2, r1, p1); } else if (r1 < r2) { return OutLine(rend, wc, r1, p1, r2, p2); } else { if (p1 > p2) return OutLine(rend, wc, r2, p2, r1, p1); else return OutLine(rend, wc, r1, p1, r2, p2); } } void Backspace(SDL_Renderer * rend) { i--; SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); SDL_Rect rt; rt.h = symbox.h; rt.w = symbox.w; rt.x = 30 + syms[i].pos * symbox.w; rt.y = 15 + syms[i].row * symbox.h; SDL_RenderFillRect(rend, &rt); syms = (Sym*)realloc(syms, i * sizeof(Sym)); } bool OutLine(SDL_Renderer *rend,SDL_Rect wc,int r1, int p1, int r2, int p2) { bool k = false; SDL_SetRenderTarget(rend, list); for (int j = 0; j < i; j++) { if (syms[j].row == r1) { while (j < i && syms[j].row == r1) { if (syms[j].pos == p1) break; j++; } if (syms[j].row != r1) break; SDL_Rect r = symbox; r.x = 30 + syms[j].pos * symbox.w; r.y = 15 + syms[j].row * symbox.h; while (j < i) { if (!syms[j].ihl) { r.x = 30 + syms[j].pos * symbox.w; r.y = 15 + syms[j].row * symbox.h; SDL_SetRenderDrawColor(rend, 0, 0, 255, 100); SDL_RenderFillRect(rend, &r); syms[j].ihl = !syms[j].ihl; k = true; } if (syms[j].row == r2) break; j++; } while (syms[j].row == r2 && j < i) { if (!syms[j].ihl) { r.x = 30 + syms[j].pos * symbox.w; SDL_SetRenderDrawColor(rend, 0, 0, 255, 100); SDL_RenderFillRect(rend, &r); syms[j].ihl = !syms[j].ihl; k = true; } if (syms[j].pos == p2) break; j++; } break; } } SDL_SetRenderTarget(rend, NULL); SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); return k; } void Put(SDL_Renderer *rend,SDL_Rect wc, char * chr) { char *buf = (char*)calloc(1, sizeof(char)); strcpy(buf, chr); SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); SDL_SetTextureBlendMode(list, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(rend, list); SDL_Color color; color.r = 0; color.g = 0; color.b = 0; SDL_Rect rect; int r = syms[i - 1].row, p = syms[i - 1].pos, w, h; if (syms[i - 1].symbol == '\n') { r++; p = 0; } else p++; if (wc.w + wc.x < wc.x + 30 + p * symbox.w) { r++; p = 0; } if (chr[0] == '\n') { syms = (Sym*)realloc(syms, (i + 1) * sizeof(struct Sym)); syms[i] = Sym('\n', r, p, false); i++; } else { syms = (Sym*)realloc(syms, (i + 1) * sizeof(struct Sym)); syms[i] = Sym(buf[0], r, p, false); i++; SDL_Texture *t = SDL_CreateTextureFromSurface(rend, TTF_RenderUTF8_Blended(font, (char*)&syms[i - 1].symbol, color)); SDL_QueryTexture(t, NULL, NULL, &w, &h); symbox.x = 30 + syms[i - 1].pos * symbox.w; symbox.y = 15 + syms[i - 1].row * symbox.h; rect = Centrd(symbox, w, h); SDL_RenderCopy(rend, t, NULL, &rect); SDL_DestroyTexture(t); } SDL_SetRenderTarget(rend, NULL); rect = wc; rect.x = 0; rect.y = 0; SDL_RenderCopy(rend, list, &rect, &wc); SDL_RenderPresent(rend); } void Click(SDL_Renderer* rend, SDL_Rect wc) { int w, h; SDL_Color color; color.r = 0; color.g = 0; color.b = 0; SDL_Rect rect; SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); SDL_SetTextureBlendMode(list, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(rend, list); for (int j = 0; j < i; j++) { if (syms[j].ihl) { if (syms[j].symbol != '\n') { SDL_Texture *t = SDL_CreateTextureFromSurface(rend, TTF_RenderUTF8_Blended(font, (char*)&syms[j].symbol, color)); SDL_QueryTexture(t, NULL, NULL, &w, &h); symbox.x = 30 + syms[j].pos * symbox.w; symbox.y = 15 + syms[j].row * symbox.h; SDL_RenderFillRect(rend, &symbox); rect = Centrd(symbox, w, h); SDL_RenderCopy(rend, t, NULL, &rect); syms[j].ihl = false; SDL_DestroyTexture(t); } else { symbox.x = 30 + syms[j].pos * symbox.w; symbox.y = 15 + syms[j].row * symbox.h; SDL_RenderFillRect(rend, &symbox); syms[j].ihl = false; } } } rect = wc; rect.x = 0; rect.y = 0; SDL_SetRenderTarget(rend, NULL); SDL_RenderCopy(rend, list, &rect, &wc); SDL_RenderPresent(rend); } void Paste(SDL_Renderer *rend, SDL_Rect wc) { if (bff != nullptr) { for (int j = 0; j < c; j++) { SDL_Color color; color.r = 0; color.g = 0; color.b = 0; SDL_Rect rect; int r = syms[i - 1].row, p = syms[i - 1].pos, w, h; p++; if (wc.w + wc.x < wc.x + 30 + p * symbox.w) { r++; p = 0; } syms = (Sym*)realloc(syms, (i + 1) * sizeof(struct Sym)); syms[i] = Sym(bff[j].symbol, r, p, false); i++; SDL_Texture *t = SDL_CreateTextureFromSurface(rend, TTF_RenderUTF8_Blended(font, (char*)&syms[i-1].symbol, color)); SDL_QueryTexture(t, NULL, NULL, &w, &h); symbox.x = 30 + syms[i-1].pos * symbox.w; symbox.y = 15 + syms[i-1].row * symbox.h; rect = Centrd(symbox, w, h); SDL_RenderCopy(rend, t, NULL, &rect); SDL_DestroyTexture(t); } } c = 0; } void Copy() { c = 0; bool on = false; for (int j = 0; j < i; j++) { if (syms[j].ihl) { bff = (Sym*)realloc(bff, (c + 1) * sizeof(Sym)); bff[c] = syms[j]; c++; on = true; } else if (on) break; } } }; struct button { bool is_pressed; SDL_Rect box; SDL_Texture *pressed, *unpressed; button(SDL_Renderer *rend, const char* unpr, const char* prsd, int x, int y) { is_pressed = false; box.x = x; box.y = y; SDL_Surface *image = SDL_LoadBMP(prsd); box.h = image->h; box.w = image->w; pressed = SDL_CreateTextureFromSurface(rend, image); image = SDL_LoadBMP(unpr); unpressed = SDL_CreateTextureFromSurface(rend, image); } button(SDL_Renderer *rend, TTF_Font* font, const char* text, int x, int y) { is_pressed = false; SDL_Color color; SDL_Rect rect; color.r = 0; color.g = 0; color.b = 0; box.x = x; box.y = y; SDL_Surface *tr = TTF_RenderUTF8_Solid(font, text, color); SDL_Surface *su = SDL_CreateRGBSurface(0, 120, 30, 24, 255, 255, 255, 255); box.h = su->h; box.w = su->w; su = common_button(su, false); rect = Centrd(tr, su); SDL_BlitSurface(tr, NULL, su, &rect); SDL_SetClipRect(su, &box); pressed = SDL_CreateTextureFromSurface(rend, su); SDL_Surface *sp = SDL_CreateRGBSurface(0, 120, 30, 24, 255, 255, 255, 255); sp = common_button(sp, true); rect = Centrd(tr, sp); SDL_BlitSurface(tr, NULL, sp, &rect); SDL_SetClipRect(sp, &box); unpressed = SDL_CreateTextureFromSurface(rend, sp); } button(SDL_Renderer *rend,const char* file_name, SDL_Rect r) { is_pressed = false; box = r; SDL_Color color; SDL_Rect rect; color.r = 0; color.g = 0; color.b = 0; SDL_Surface *ic = SDL_LoadBMP(file_name); SDL_Surface *su = SDL_CreateRGBSurface(0, r.h, r.w, 24, 255, 255, 255, 255); su = common_button(su, false); rect = Centrd(ic, su); SDL_BlitSurface(ic, NULL, su, &rect); SDL_SetClipRect(su, &box); pressed = SDL_CreateTextureFromSurface(rend, su); SDL_Surface *sp = SDL_CreateRGBSurface(0, r.h, r.w, 24, 255, 255, 255, 255); sp = common_button(sp, true); rect = Centrd(ic, sp); SDL_BlitSurface(ic, NULL, sp, &rect); SDL_SetClipRect(sp, &box); unpressed = SDL_CreateTextureFromSurface(rend, sp); } SDL_Rect Centrd(SDL_Surface* one, SDL_Surface* two) { SDL_Rect o = one->clip_rect, t = two->clip_rect,ret; ret.x = t.w / 2 - o.w / 2; ret.y = t.h / 2 - o.h / 2; ret.h = o.h; ret.w = o.w; return ret; } SDL_Surface *common_button(SDL_Surface* sur,bool prsd) { if (prsd) { Uint32 color = SDL_MapRGB(sur->format, 200, 200, 200); SDL_Rect but; but.x = 0; but.y = 0; but.h = sur->h; but.w = sur->w; SDL_FillRect(sur, &but, color); color = SDL_MapRGB(sur->format, 170, 170, 170); but.x = 3; but.y = 3; but.h = sur->h - 6; but.w = sur->w - 6; SDL_FillRect(sur, &but, color); } else { Uint32 color = SDL_MapRGB(sur->format, 170, 170, 170); SDL_Rect but; but.x = 0; but.y = 0; but.h = sur->h; but.w = sur->w; SDL_FillRect(sur, &but, color); color = SDL_MapRGB(sur->format, 200, 200, 200); but.x = 3; but.y = 3; but.h = sur->h - 6; but.w = sur->w - 6; SDL_FillRect(sur, &but, color); } return sur; } }; struct picture { SDL_Texture *texture; char *nf; SDL_Texture *Load_Pic(const char* file_name, SDL_Renderer *rend) { SDL_Surface *image = SDL_LoadBMP(file_name); SDL_Texture *t = SDL_CreateTextureFromSurface(rend, image); if (t == nullptr) return NULL; return t; } SDL_Texture *Load_Pic(char* file_name, SDL_Renderer *rend) { nf = new char[20]; SDL_Texture *t = nullptr; SDL_Surface *image = SDL_LoadBMP(file_name); if(image != nullptr) t = SDL_CreateTextureFromSurface(rend, image); if (t == nullptr) return NULL; else { strcpy(nf, file_name); texture = t; return t; } } void Blit(SDL_Renderer* rend,SDL_Texture* t, int x, int y) { int w, h; SDL_QueryTexture(t, NULL, NULL, &w, &h); SDL_Rect rect; rect.x = x; rect.y = y; rect.h = h; rect.w = w; if (t) { SDL_RenderCopy(rend, t, NULL, &rect); } } void Blit(SDL_Renderer* rend, button *b) { if (b->is_pressed) { SDL_RenderCopy(rend, b->pressed, NULL, &b->box); } else { SDL_RenderCopy(rend, b->unpressed, NULL, &b->box); } } void DrawLine(SDL_Renderer* rend,double mul,SDL_Rect r,SDL_Rect wc,int x, int y, int lx, int ly) { SDL_SetRenderDrawColor(rend, 120, 120, 120, 255); SDL_RenderDrawLine(rend, r.x + ((x - wc.x) * mul), r.y + ((y - wc.y) * mul), r.x + ((lx - wc.x) * mul), r.y + ((ly - wc.y) * mul)); } void PrintDraw(SDL_Renderer* rend,SDL_Texture* print , double mul, SDL_Rect r, SDL_Rect wc, int x, int y) { int w, h; SDL_QueryTexture(print, NULL, NULL, &w, &h); SDL_Rect pd; pd.h = h; pd.w = w; pd.x = r.x - w / 2 + ((x - wc.x)*mul); pd.y = r.y - h / 2 + ((y - wc.y)*mul); SDL_RenderCopy(rend, print, NULL, &pd); } }; struct interf : public Window { SDL_Texture *back; button *b1, *b2, *bx; SDL_Rect work_space; picture Pred; text Wred; interf(const char* t, int w, int h) { win = SDL_CreateWindow(t, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_BORDERLESS); rend = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC); Pred.texture = nullptr; Wred.syms = nullptr; Wred.nf = nullptr; Pred.nf = nullptr; Wred.font = TTF_OpenFont("cour.ttf", 14); } bool in_check(SDL_Rect r, int x, int y) { if ((r.x + r.w > x && r.x < x) && (r.y + r.h > y && r.y < y)) return true; else return false; } void Overdraw(button *b) { int w,h; SDL_GetWindowSize(win, &w, &h); SDL_Rect top, side; top.x = 0; top.y = 0; top.h = b->box.h; top.w = w; side.x = 0; side.y = 0; side.h = h; side.w = b->box.w/3; SDL_SetRenderDrawColor(rend, 200, 200, 200, 255); SDL_RenderFillRect(rend, &top); SDL_RenderFillRect(rend, &side); top.x = 0; top.y = b->box.h-3; top.h = 3; top.w = w; side.x = b->box.w / 3-3; side.y = 0; side.h = h; side.w = 3; SDL_SetRenderDrawColor(rend, 220, 220, 220, 255); SDL_RenderFillRect(rend, &top); SDL_RenderFillRect(rend, &side); work_space.h = h - b->box.h; work_space.w = w - b->box.w / 3; work_space.x = b->box.w / 3; work_space.y = b->box.h; } char *Open(bool is_there) { char* fname; char text[18] = { 0 }; SDL_Rect top, rinp, inp; SDL_Color color; color.r = 0; color.g = 0; color.b = 0; int x, y, wig, hei,counter = 0; TTF_Font *font = TTF_OpenFont("cour.ttf", 13); Window w = Window(); w.win = SDL_CreateWindow(nullptr, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 400, 300, SDL_WINDOW_BORDERLESS); w.rend = SDL_CreateRenderer(w.win, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE); button *bo1, *bo2, *bxo, *boi; SDL_GetWindowSize(w.win, &wig, &hei); bxo = new button(w.rend, "xbut1.bmp", "xbut2.bmp", wig - 80, 0); bo1 = new button(w.rend, font, "Открыть", 240, 80); boi = new button(w.rend, font, "Продолжить", 140, 160); SDL_SetRenderDrawColor(w.rend, 230, 230, 230, 255); SDL_RenderClear(w.rend); SDL_SetRenderDrawColor(w.rend, 200, 200, 200, 255); top.h = 35; top.w = wig; top.x = 0; top.y = 0; SDL_RenderFillRect(w.rend, &top); rinp.h = bo1->box.h; rinp.w = 216; rinp.x = 10; rinp.y = bo1->box.y; SDL_SetRenderDrawColor(w.rend, 255, 255, 255, 255); SDL_RenderFillRect(w.rend, &rinp); SDL_SetRenderDrawColor(w.rend, 200, 200, 200, 255); SDL_RenderDrawRect(w.rend, &rinp); if (is_there) { Pred.Blit(w.rend, boi); } Pred.Blit(w.rend, bo1); Pred.Blit(w.rend, bxo); SDL_RenderPresent(w.rend); SDL_Event e; inp.h = 16; inp.w = 8; inp.x = rinp.x + 2; inp.y = rinp.y + 7; while (true) { while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: { SDL_HideWindow(w.win); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return nullptr; } case SDL_TEXTINPUT: { char* chr; if (counter < 18) { chr = e.text.text; text[counter] = chr[0]; SDL_RenderCopy(w.rend, SDL_CreateTextureFromSurface(w.rend, TTF_RenderUTF8_Blended(font, chr, color)), NULL, &inp); SDL_RenderPresent(w.rend); inp.x += 12; counter++; } break; } case SDL_KEYDOWN: { if (e.key.keysym.scancode == SDL_SCANCODE_BACKSPACE) { if (counter > 0) { const char *cr = " "; inp.x -= 12; counter--; text[counter] = cr[0]; SDL_SetRenderDrawColor(w.rend, 255, 255, 255, 255); SDL_RenderFillRect(w.rend, &inp); SDL_RenderPresent(w.rend); break; } } if (e.key.keysym.scancode == SDL_SCANCODE_KP_ENTER) { if (text[0] != NULL) { SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); fname = (char*)calloc(strlen(text) + 1, sizeof(char)); strcpy_s(fname, strlen(text) + 1, text); return fname; } } break; } case SDL_MOUSEBUTTONDOWN: { SDL_GetMouseState(&x, &y); if (is_there) { if (in_check(boi->box, x, y)) { Press(w.rend, boi); break; } } if (in_check(bo1->box, x, y)) { Press(w.rend,bo1); break; } if (in_check(bxo->box, x, y)) { Press(w.rend,bxo); break; } break; } case SDL_MOUSEBUTTONUP: { SDL_GetMouseState(&x, &y); if (is_there) { if (in_check(boi->box, x, y) && boi->is_pressed) { Press(w.rend, boi); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return nullptr; } } if (bo1->is_pressed && in_check(bo1->box, x, y)) { Press(w.rend,bo1); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); fname = (char*)calloc(strlen(text) + 1,sizeof(char)); strcpy_s(fname, strlen(text) + 1, text); return fname; } if (bxo->is_pressed && in_check(bxo->box, x, y)) { Press(w.rend,bxo); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return nullptr; } if (bo1->is_pressed) { Press(w.rend,bo1); break; } if (bxo->is_pressed) { Press(w.rend,bxo); break; } break; } } } } } int Save(char* name) { TTF_Font *font = TTF_OpenFont("cour.ttf", 13); int x, y, wig, hei; SDL_Rect top; button *bxo, *bo1, *bo2, *bo3; Window w = Window(); char buff[20],b[30]; strcpy(buff, name); SDL_Color color; color.r = 0; color.g = 0; color.b = 0; sprintf(b, "Сохранить %s?", buff); w.win = SDL_CreateWindow(nullptr, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 400, 300, SDL_WINDOW_BORDERLESS); w.rend = SDL_CreateRenderer(w.win, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE); SDL_Texture *t = SDL_CreateTextureFromSurface(w.rend, TTF_RenderUTF8_Blended(Wred.font, b, color)); SDL_GetWindowSize(w.win, &wig, &hei); bxo = new button(w.rend, "xbut1.bmp", "xbut2.bmp", wig - 80, 0); bo1 = new button(w.rend, font, "Да", 40, 80); bo2 = new button(w.rend, font, "Нет", 240, 80); bo3 = new button(w.rend, font, "Отмена", 140, 160); SDL_SetRenderDrawColor(w.rend, 230, 230, 230, 255); SDL_RenderClear(w.rend); SDL_SetRenderDrawColor(w.rend, 200, 200, 200, 255); top.h = 35; top.w = wig; top.x = 0; top.y = 0; SDL_RenderFillRect(w.rend, &top); SDL_QueryTexture(t, NULL, NULL, &wig, &hei); top.w = wig; top.h = hei; SDL_RenderCopy(w.rend, t, NULL, &top); Pred.Blit(w.rend, bxo); Pred.Blit(w.rend, bo1); Pred.Blit(w.rend, bo2); Pred.Blit(w.rend, bo3); SDL_RenderPresent(w.rend); SDL_Event e; while (true) { while (SDL_PollEvent(&e)) { SDL_GetMouseState(&x, &y); switch (e.type) { case SDL_MOUSEBUTTONDOWN: { if (in_check(bxo->box, x, y)) { Press(w.rend,bxo); } if (in_check(bo1->box, x, y)) { Press(w.rend, bo1); } if (in_check(bo2->box, x, y)) { Press(w.rend, bo2); } if (in_check(bo3->box, x, y)) { Press(w.rend, bo3); } break; } case SDL_MOUSEBUTTONUP: { if (bxo->is_pressed && in_check(bxo->box, x, y)) { Press(w.rend, bxo); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return 1; } if (bo1->is_pressed && in_check(bo1->box, x, y)) { Press(w.rend, bo1); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return 0; } if (bo2->is_pressed && in_check(bo2->box, x, y)) { Press(w.rend, bo2); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return 2; } if (bo3->is_pressed && in_check(bo3->box, x, y)) { Press(w.rend, bo3); SDL_DestroyRenderer(w.rend); SDL_DestroyWindow(w.win); return 1; } break; } } } } } void Show_Interface() { int x, y, w, h; SDL_GetWindowSize(win, &w, &h); b1 = new button(rend, "but1.1.bmp", "but1.2.bmp", 0, 0); b2 = new button(rend, "but2.1.bmp", "but2.2.bmp", b1->box.w, 0); bx = new button(rend, "xbut1.bmp", "xbut2.bmp", w - 80, 0); SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); SDL_RenderClear(rend); Overdraw(b1); Pred.Blit(rend, b1); Pred.Blit(rend, b2); Pred.Blit(rend, bx); SDL_RenderPresent(rend); SDL_Event e; while (true) { while (SDL_PollEvent(&e)) { I_Events(e); } } } bool I_Events(SDL_Event e) { int x, y; switch (e.type) { case SDL_KEYDOWN: { switch (e.key.keysym.sym) { case SDLK_ESCAPE: { SDL_DestroyRenderer(rend); SDL_DestroyWindow(win); SDL_Quit(); exit(0); } break; } break; } case SDL_MOUSEBUTTONDOWN: { SDL_GetMouseState(&x, &y); char* word, *name; if (in_check(b1->box, x, y)) { Press(rend, b1); if (Wred.nf == nullptr) { word = Open(false); if (word == nullptr) { Press(rend, b1); return true; } else { if (Wred.Load_Text(rend, work_space, word)) { if (b2->is_pressed) { Overdraw(b1); Pred.Blit(rend, b1); Pred.Blit(rend, b2); Pred.Blit(rend, bx); SDL_RenderPresent(rend); Press(rend, b2); } Word(); } else Press(rend, b1); return true; } } else { word = Open(true); if (word == nullptr) { Word(); return true; } else { if (Wred.Load_Text(rend, work_space, word)) { if (b2->is_pressed) { Overdraw(b1); Pred.Blit(rend, b1); Pred.Blit(rend, b2); Pred.Blit(rend, bx); SDL_RenderPresent(rend); Press(rend, b2); } Word(); } else Press(rend, b1); return true; } } return true; break; } if (in_check(b2->box, x, y)) { if (b1->is_pressed) { Press(rend, b1); } Press(rend, b2); if (Pred.texture == nullptr) { word = Open(false); if (word == nullptr) { Press(rend, b2); return true; } else { if (Pred.Load_Pic(word, rend) != NULL) Paint(); return true; break; } } else { word = Open(true); if (word == nullptr) { Paint(); return true; } else { if(Pred.Load_Pic(word, rend)!=NULL) Paint(); return true; break; } } return true; break; } if (in_check(bx->box, x, y)) { Press(rend, bx); return true; } break; } case SDL_MOUSEBUTTONUP: { SDL_GetMouseState(&x, &y); if (bx->is_pressed && in_check(bx->box, x, y)) { Press(rend, bx); if (Pred.nf!=nullptr) { switch (Save(Pred.nf)) { case 0: { SDL_SetRenderTarget(rend, back); int width, height; SDL_QueryTexture(Pred.texture, NULL, NULL, &width, &height); SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0); SDL_RenderReadPixels(rend, NULL, surface->format->format, surface->pixels, surface->pitch); SDL_SaveBMP(surface, Pred.nf); SDL_FreeSurface(surface); SDL_SetRenderTarget(rend, NULL); break; } case 1: { return true; } case 2: { break; } } } if (Wred.nf != nullptr) { switch (Save(Wred.nf)) { case 0: { ofstream f; f.open(Wred.nf, ios::beg | ios::trunc); for (int j = 0; j < Wred.i; j++) { f << Wred.syms[j].symbol; } f.close(); break; } case 1: { return true; } case 2: { break; } } } SDL_DestroyRenderer(rend); SDL_DestroyWindow(win); SDL_Quit(); exit(0); } if (bx->is_pressed) { Press(rend, bx); return true; } break; } } return false; } void Press(SDL_Renderer* rnd,button *b) { b->is_pressed = !b->is_pressed; Pred.Blit(rnd, b); SDL_RenderPresent(rnd); } void Word() { SDL_Rect cur_space = work_space; cur_space.x = 0; cur_space.y = 0; SDL_Event e; int x = 0, y = 0, xl = 0, yl = 0; int scrolled = 0, t_size; char *buff; SDL_QueryTexture(Wred.list, NULL, NULL, NULL, &t_size); SDL_RenderCopy(rend, Wred.list, &cur_space, &work_space); SDL_RenderPresent(rend); while (true) { while (SDL_PollEvent(&e)) { if (!I_Events(e)) { SDL_GetMouseState(&x, &y); switch (e.type) { case SDL_KEYDOWN: { switch (e.key.keysym.scancode) { case SDL_SCANCODE_KP_ENTER: { char *chr = new char[1]; chr[0] = '\n'; Wred.Click(rend, work_space); Wred.Put(rend, work_space, chr); break; } case SDL_SCANCODE_BACKSPACE: { if (Wred.i > 0 && e.button.state != SDL_PRESSED) { SDL_SetRenderTarget(rend, Wred.list); Wred.Backspace(rend); SDL_SetRenderTarget(rend, NULL); SDL_RenderCopy(rend, Wred.list, &cur_space, &work_space); SDL_RenderPresent(rend); } break; } case SDL_SCANCODE_LCTRL: { if (e.button.state != SDL_PRESSED) { Wred.Copy(); } break; } case SDL_SCANCODE_LALT: { if (e.button.state != SDL_PRESSED) { SDL_SetRenderTarget(rend, Wred.list); Wred.Paste(rend, work_space); SDL_SetRenderTarget(rend, NULL); SDL_RenderCopy(rend, Wred.list, &cur_space, &work_space); SDL_RenderPresent(rend); } break; } } break; } case SDL_TEXTINPUT: { if (e.button.state != SDL_PRESSED) { char* chr; chr = e.text.text; Wred.Click(rend, work_space); Wred.Put(rend, work_space, chr); } break; } case SDL_MOUSEBUTTONDOWN: { if (in_check(work_space, x, y)) { Wred.Click(rend,work_space); xl = x; yl = y; } break; } case SDL_MOUSEBUTTONUP: { if (xl != 0) { Wred.Search(rend, work_space, xl, yl, x, y, scrolled); SDL_RenderCopy(rend, Wred.list, &cur_space, &work_space); SDL_RenderPresent(rend); } xl = 0; yl = 0; break; } case SDL_MOUSEWHEEL: { if (e.button.state != SDL_PRESSED) { if (e.button.x > 0) if (scrolled >= Wred.symbox.h) scrolled -= Wred.symbox.h; else scrolled = 0; else if (scrolled <= t_size - work_space.h - Wred.symbox.h) scrolled += Wred.symbox.h; else scrolled = t_size - work_space.h; cur_space.y = scrolled; SDL_RenderCopy(rend, Wred.list, &cur_space, &work_space); SDL_RenderPresent(rend); break; } break; } } } } } } void Paint() { int w,h,x = 0, y = 0, xl = 0, yl = 0; double mul = 1; SDL_Rect r,fp; button *sb1, *sb2,*sb3,*act=nullptr; r.w = b1->box.w / 6; r.h = r.w; r.x = 0; r.y = b1->box.h; sb1 = new button(rend, "pbut1.bmp", r); r.x = r.w; sb2 = new button(rend, "pbut2.bmp", r); r.x = 0; r.y = b1->box.h + r.w; sb3 = new button(rend, "pbut3.bmp", r); Pred.Blit(rend, sb1); Pred.Blit(rend, sb2); Pred.Blit(rend, sb3); r.h = work_space.h; r.w = work_space.w; r.x = 0; r.y = 0; int iw = r.w, ih = r.h; auto cur_space = work_space; fp = work_space; SDL_QueryTexture(Pred.texture, NULL, NULL, &w, &h); SDL_RenderCopy(rend, Pred.texture, &r, &work_space); back = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, w, h); SDL_Texture *print = SDL_CreateTextureFromSurface(rend, SDL_LoadBMP("tod.bmp")); SDL_SetTextureBlendMode(back, SDL_BLENDMODE_BLEND); SDL_SetRenderTarget(rend, back); SDL_RenderCopy(rend, Pred.texture, NULL, NULL); SDL_SetRenderTarget(rend, NULL); SDL_RenderPresent(rend); SDL_Event e; while (true) { while (SDL_PollEvent(&e)) { SDL_GetMouseState(&x, &y); if(!I_Events(e)) switch (e.type) { case SDL_MOUSEWHEEL: { if (e.button.x > 0) { if (mul > 0.0625) { mul /= 2; r.h = r.h / 2; r.w = r.w / 2; if (r.w > w || r.h > h) { r.x = 0; r.y = 0; cur_space.w = iw / mul; cur_space.h = ih / mul; SDL_RenderCopy(rend, back, &r, &cur_space); SDL_RenderPresent(rend); } else { SDL_RenderCopy(rend, back, &r, &work_space); SDL_RenderPresent(rend); } } break; } else { if (mul < 16.0) { mul *= 2; r.h = r.h * 2; r.w = r.w * 2; if (r.w > w || r.h > h) { r.x = 0; r.y = 0; cur_space.w = iw / mul; cur_space.h = ih / mul; SDL_SetRenderDrawColor(rend, 228, 228, 228, 255); SDL_RenderFillRect(rend, &work_space); SDL_RenderCopy(rend, back, &r, &cur_space); SDL_RenderPresent(rend); } else { if (w - r.x < r.w) r.x = w - r.w; if (h - r.y < r.h) r.y = h - r.h; SDL_RenderCopy(rend, back, &r, &work_space); SDL_RenderPresent(rend); } } break; } break; } case SDL_MOUSEBUTTONDOWN: { if (in_check(sb1->box, x, y)) { if(act!=nullptr) Press(rend, act); act = sb1; Press(rend,sb1); } if (in_check(sb2->box, x, y)) { if (act != nullptr) Press(rend, act); act = sb2; Press(rend,sb2); } if (in_check(sb3->box, x, y)) { if (act != nullptr) Press(rend, act); act = sb3; Press(rend, sb3); } if (in_check(work_space, x, y)) { xl = x; yl = y; if (act == sb2) { SDL_SetRenderTarget(rend, back); Pred.PrintDraw(rend, print, mul, r, work_space, x, y); SDL_SetRenderTarget(rend, NULL); if (r.w > w || r.h > h) { SDL_RenderCopy(rend, back, &r, &cur_space); } else { SDL_RenderCopy(rend, back, &r, &work_space); } SDL_RenderPresent(rend); } if (act == sb1) { SDL_SetRenderTarget(rend, back); Pred.DrawLine(rend, mul, r, work_space, x, y, xl, yl); xl = x; yl = y; SDL_SetRenderTarget(rend, NULL); if (r.w > w || r.h > h) { SDL_RenderCopy(rend, back, &r, &cur_space); } else { SDL_RenderCopy(rend, back, &r, &work_space); } SDL_RenderPresent(rend); } } break; } case SDL_MOUSEMOTION: { if (xl!=0) { if (in_check(work_space, x, y)) { if (act == sb3) { if (r.w > w || r.h > h) {} else { if (x - xl > 0) { if (r.x > x - xl) r.x -= (x - xl)*mul; else r.x -= r.x; } else { if (w - (r.x + r.w) > -(x - xl)) r.x -= (x - xl)*mul; else r.x = w - r.w; } if (y - yl > 0) { if (r.y > y - yl) r.y -= (y - yl)*mul; else r.y -= r.y; } else { if (h - (r.y + r.h) > -(y - yl)) r.y -= (y - yl)*mul; else r.y = h - r.h; } SDL_RenderCopy(rend, back, &r, &work_space); SDL_RenderPresent(rend); } xl = x; yl = y; } if (act == sb1) { SDL_SetRenderTarget(rend, back); Pred.DrawLine(rend, mul, r, work_space, x, y, xl, yl); xl = x; yl = y; SDL_SetRenderTarget(rend, NULL); if (r.w > w || r.h > h) { SDL_RenderCopy(rend, back, &r, &cur_space); } else { SDL_RenderCopy(rend, back, &r, &work_space); } SDL_RenderPresent(rend); } if (act == sb2) { SDL_SetRenderTarget(rend, back); Pred.PrintDraw(rend,print, mul, r, work_space, x, y); SDL_SetRenderTarget(rend, NULL); if (r.w > w || r.h > h) { SDL_RenderCopy(rend, back, &r, &cur_space); } else { SDL_RenderCopy(rend, back, &r, &work_space); } SDL_RenderPresent(rend); } } } break; } case SDL_MOUSEBUTTONUP: { xl = 0; yl = 0; break; } } } } } }; int main(int argc, char **argv) { setlocale(LC_ALL, "Russian"); if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { cout << "Can't init everything"<< endl; return 1; } if (IMG_Init(IMG_INIT_JPG) != 1) { cout << "Can't init jpg" << endl; return 1; } if (TTF_Init() == -1) { cout << "Can't init ttf" << endl; return 1; } interf interf("Redactor 2019", 800, 600); interf.Show_Interface(); return 0; }
true
ebaea40b05edcdad21b707ef0ceb0c170e2b0d43
C++
Soveu/algothings
/themis/6/klm2_2.cpp
UTF-8
1,682
3.28125
3
[]
no_license
#include <algorithm> #include <cmath> #include <iostream> #include <vector> #include <stdint.h> struct Position { int x, int y }; struct Edge { int from, int to; int64_t weight; }; struct DisjoinSet { struct Item { int repr; int count; }; std::vector<Item> vi; void init(size_t n) { this->vi.resize(n); size_t i=0; for(auto& x : this->vi) { x.repr = ++i; x.count = 1; } } int find(int x) { if(this->vi[x].repr == x) { return x; } return this->vi[x].repr = find(this->vi[x].repr); } void join(int _a, int _b) { Item* a = &(this->vi[this->find(_a)]); Item* b = &(this->vi[this->find(_b)]); if(a->count > b->count) { b->repr = a->repr; a->count += b->count; } else { a->repr = b->repr; b->count += a->count; } } }; int main() { std::cin.tie(0); std::ios_base::sync_with_stdio(false); int n; std::cin >> n; std::vector<Position> vp(n); for(auto* p : vp) { std::cin >> p->x >> p->y; } std::vector<Edge> ve; ve.reserve(n*n/2); for(int i=0; i<n; ++i) { for(int j=i+1; j<n; ++j) { int64_t x = std::abs(vp[i].x - vp[j].x); int64_t y = std::abs(vp[i].y - vp[j].y); ve.push_back(i, j, x*x+y*y); } } std::sort(ve.begin(), ve.end(), [](const Edge& a, const Edge& b) { return a.weight < b.weight; }); DisjoinSet ds; ds.init(n); for(const auto& e : ve) { int a = ds.find(e.from); int b = ds.find(e.to); if(a + b == 1) { std::cout << std::sqrt(e.weight) << '\n'; return 0; } ds.join(a, b); } std::cout << std::sqrt(ve.back().weight) << '\n'; return 0; }
true
94f01dd02235c6bd1e4bee2f628fc43443bb25f4
C++
danhellem/send-github-issues-to-azure-boards
/sketches/GetWorkItemCount.ino
UTF-8
3,076
2.765625
3
[ "MIT" ]
permissive
/* ESP8266 Blink by Simon Peter Blink the blue LED on the ESP-01 module This example code is in the public domain The blue LED on the ESP-01 module is connected to GPIO1 (which is also the TXD pin; so we cannot use Serial.print() at the same time) Note that this sketch uses LED_BUILTIN to find the pin with the internal LED */ //#define LED 2 #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> //#include <JsonListener.h> /** * WiFi Settings */ const char *ESP_HOST_NAME = "esp-" + ESP.getFlashChipId(); const char *WIFI_SSID = "<wifi_ssid>"; const char *WIFI_PASSWORD = "<wifi_password>"; // initiate the WifiClient WiFiClient wifiClient; HTTPClient http; void setup() { Serial.begin(74880); delay(500); connectWifi(); pinMode(D7, OUTPUT); // Initialize the LED_BUILTIN pin as an output pinMode(D6, OUTPUT); } // the loop function runs over and over again forever void loop() { //turn on LED so we know it is working digitalWrite(D6, HIGH); delay(1000); digitalWrite(D6, LOW); delay(1000); Serial.printf("[WiFi Status]: %d\n\n", WiFi.status()); //Serial.printf("[WiFi Status] : %s\n", WiFi.status()); int count = GetWorkItemCount(); for (int x = 0; x <= 2; x++) { for (int i = 1; i <= count; i++) { digitalWrite(D7, HIGH); // Turn the LED on (Note that LOW is the voltage level delay(1000); digitalWrite(D7, LOW); delay(500); } delay(3000); } delay(120000); //delay loop 10 minutes } int GetWorkItemCount() { //Serial.println(WiFi.localIP()); WiFiClient client; HTTPClient http; int count = 0; Serial.print("[HTTP] begin...\n"); //url for your rest endpoint to get the count of github work items in the new column if (http.begin(client, "http://sync-github-issues-to-azure-boards.azurewebsites.net/api/workitems/new/count")) { //Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { String payload = http.getString(); count = payload.toInt(); Serial.printf("[HTTP] GET... count: %d\n", count); } } else { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); Serial.print("[HTTP] end...\n"); } else { Serial.printf("[HTTP} Unable to connect\n"); } Serial.println(""); return count; } void connectWifi() { WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("Connecting to "); Serial.println(WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected!"); Serial.println(WiFi.localIP()); Serial.println(); }
true
cee353e8aa9a0746981d32ff3121aa5b8b29f62f
C++
uiucCme/Practicum
/Assignment1/buildOrderBook.cpp
UTF-8
15,325
2.9375
3
[]
no_license
#include<iostream> #include<string> #include<fstream> #include<sstream> #include<stdlib.h> #include<queue> #include<unordered_set> #include<vector> #include<unordered_map> using namespace std; class generalInfo{ string code; int stockLocate; int trackingNumber; long timestamp; public: string getcode() const{return code;} long gettimestamp() const{return timestamp;} int getStockLocate() const{return stockLocate;} int getTrackingNumber() const{return trackingNumber;} generalInfo(string code,int stockLocate,int trackingNumber,long timestamp):code(code),stockLocate(stockLocate),trackingNumber(trackingNumber), timestamp(timestamp){} //copy constructor generalInfo(const generalInfo& x):code(x.getcode()),stockLocate(x.getStockLocate()),trackingNumber(x.getTrackingNumber()), timestamp(x.gettimestamp()){} generalInfo(generalInfo&& x):code(x.getcode()),stockLocate(x.getStockLocate()),trackingNumber(x.getTrackingNumber()), timestamp(x.gettimestamp()){} generalInfo& operator= (generalInfo&& x){ code = x.getcode(); stockLocate = x.getStockLocate(); trackingNumber = x.getTrackingNumber(); timestamp = x.gettimestamp(); return *this; } generalInfo& operator= (const generalInfo& x){ code = x.getcode(); stockLocate = x.getStockLocate(); trackingNumber = x.getTrackingNumber(); timestamp = x.gettimestamp(); return *this; } ~generalInfo(){} }; class xclusiveInfo{ string stock = ""; string indicator = ""; int shares = 0; int canceledShares = 0; double price = 0.0; string attribution = ""; public: string getStock() const{return stock;} string getIndicator() const{return indicator;} int getCanceledShares() const{return canceledShares;} int getShares() const{return shares;} double getPrice() const{return price;} string getAttribution() const{return attribution;} void updateShares(int nshares) { cout << " nshares "<< nshares << endl; this->shares = nshares; cout << " this shares " << shares << endl; cout << " ..." << getShares() << endl; } void setPrice(double nprice) {price = nprice;} void setShares(int nshares){ shares = nshares;} xclusiveInfo(string stock,string indicator,int shares,double price,string attribution,int canceledShares):stock(stock),indicator(indicator),shares(shares), price(price),attribution(attribution),canceledShares(canceledShares){} xclusiveInfo(const xclusiveInfo& x):stock(x.getStock()),indicator(x.getIndicator()),shares(x.getShares()), price(x.getPrice()),attribution(x.getAttribution()),canceledShares(x.getCanceledShares()){} xclusiveInfo(xclusiveInfo&& x):stock(x.getStock()),indicator(x.getIndicator()),shares(x.getShares()),price(x.getPrice()) ,attribution(x.getAttribution()),canceledShares(x.getCanceledShares()){} xclusiveInfo& operator=(const xclusiveInfo& x) { stock = x.getStock(); indicator = x.getIndicator(); shares = x.getShares(); price = x.getPrice(); attribution = x.getAttribution(); canceledShares = x.getCanceledShares(); return *this; } xclusiveInfo& operator=(xclusiveInfo&& x) { stock = x.getStock(); indicator = x.getIndicator(); shares = x.getShares(); price = x.getPrice(); attribution = x.getAttribution(); canceledShares = x.getCanceledShares(); return *this; } ~xclusiveInfo(){} }; class order{ generalInfo ginfo; long orderReferenceNumber; long oldOrderReferenceNumber; xclusiveInfo xinfo; public: generalInfo getGeneralInfo() const{return ginfo;} long getOrderReferenceNumber() const{return orderReferenceNumber;} long getOldOrderReferenceNumber() const{return oldOrderReferenceNumber;} xclusiveInfo getXclusiveInfo() const{return xinfo;} void setOrderReferenceNumber(const long& norderReferenceNumber) { orderReferenceNumber = norderReferenceNumber;} order(string code,int stockLocate,int trackingNumber,long timestamp,long orderReferenceNumber,long oldOrderReferenceNumber,string stock, string indicator,int shares,double price,string attribution,int canceledShares): ginfo{generalInfo(code,stockLocate,trackingNumber,timestamp)},orderReferenceNumber{orderReferenceNumber}, xinfo{xclusiveInfo(stock,indicator,shares,price,attribution,canceledShares)},oldOrderReferenceNumber{oldOrderReferenceNumber}{} order(const order& x):ginfo(x.getGeneralInfo()),orderReferenceNumber(x.getOrderReferenceNumber()),xinfo(x.getXclusiveInfo()), oldOrderReferenceNumber{x.getOldOrderReferenceNumber()}{} order(order&& x):ginfo(x.getGeneralInfo()),orderReferenceNumber(x.getOrderReferenceNumber()),xinfo(x.getXclusiveInfo()) ,oldOrderReferenceNumber{x.getOldOrderReferenceNumber()}{} order& operator=(const order& x){ ginfo = x.getGeneralInfo(); orderReferenceNumber = x.getOrderReferenceNumber(); oldOrderReferenceNumber = x.getOldOrderReferenceNumber(); xinfo = x.getXclusiveInfo(); return *this; } order& operator=(order&& x){ ginfo = x.getGeneralInfo(); orderReferenceNumber = x.getOrderReferenceNumber(); oldOrderReferenceNumber = x.getOldOrderReferenceNumber(); xinfo = x.getXclusiveInfo(); return *this; } void printOrder() const { cout << ginfo.getcode() << "," << ginfo.getStockLocate() << ","<<ginfo.getTrackingNumber()<<","<<ginfo.gettimestamp()<<","<< orderReferenceNumber << "," << oldOrderReferenceNumber << "," << xinfo.getIndicator() << "," << xinfo.getShares() << "," << xinfo.getStock() << "," << xinfo.getPrice()<< ", Executed/Canceled shaers: "<< xinfo.getCanceledShares()<< endl; } ~order(){} }; class orderFactoryClass{ public: static order getOrderObj(string s) { stringstream ss(s); string token; string code; int stockLocate,trackingNumber; long timestamp,orderReferenceNumber,oldOrderReferenceNumber; string stock=""; string indicator=""; int shares=0,canceledShares=0; double price= 0; string attribution = ""; getline(ss,code,','); getline(ss,token,',');stockLocate = stoi(token); getline(ss,token,',');trackingNumber = stoi(token); getline(ss,token,',');timestamp = stol(token); getline(ss,token,',');orderReferenceNumber = stol(token); oldOrderReferenceNumber = orderReferenceNumber; if(code=="A" || code=="F") { getline(ss,indicator,','); getline(ss,token,','); shares = stoi(token); getline(ss,stock,','); getline(ss,token,','); price = stof(token); if(code=="F") getline(ss,attribution,','); }else if(code=="X" || code=="E" || code=="C") { getline(ss,token,','); canceledShares = stoi(token); }else if(code=="U") { getline(ss,token,','); orderReferenceNumber = stol(token); getline(ss,token,','); shares = stoi(token); getline(ss,token,','); price = stof(token); } order x = order(code,stockLocate,trackingNumber,timestamp,orderReferenceNumber,oldOrderReferenceNumber,stock,indicator,shares,price, attribution,canceledShares); return x; } }; struct compareMin{ bool operator()(const order& l,const order& r) { if(l.getXclusiveInfo().getPrice() > r.getXclusiveInfo().getPrice()) { return true; }else if(l.getXclusiveInfo().getPrice() < r.getXclusiveInfo().getPrice()) { return false; } else if(l.getOrderReferenceNumber() > r.getOrderReferenceNumber()) { return true; } else return false; } }; struct compareMax{ bool operator()(const order& l,const order& r) { if(l.getXclusiveInfo().getPrice() < r.getXclusiveInfo().getPrice()) return true; else if(l.getXclusiveInfo().getPrice() > r.getXclusiveInfo().getPrice()) return false; else if(l.getOrderReferenceNumber() > r.getOrderReferenceNumber()) return true; else return false; } }; static priority_queue<order,vector<order>,compareMax> bid; static priority_queue<order,vector<order>,compareMin> ask; static queue<double> bidAskSpread; unordered_map<long,int> mp; class orderAction{ public: static void takeAction(string s) { order t = orderFactoryClass::getOrderObj(s); string messageType = t.getGeneralInfo().getcode(); string indicator = t.getXclusiveInfo().getIndicator(); if(messageType=="A" || messageType=="F") { if(indicator=="B"){ bid.push(t); mp[t.getOrderReferenceNumber()]=1;} else {ask.push(t);} }else if(messageType=="X" || messageType=="E" || messageType=="C" ) { /* cout << endl << endl << "*************" << messageType << "********" << endl; cout << " shares executed/Cancelled " << t.getXclusiveInfo().getCanceledShares() << endl; if(bid.top().getOrderReferenceNumber()==t.getOrderReferenceNumber()) { cout << " orderReference Number " << bid.top().getOrderReferenceNumber(); cout << endl << " before execution " << bid.top().getXclusiveInfo().getShares() << endl; bid.top().getXclusiveInfo().updateShares(bid.top().getXclusiveInfo().getShares() - t.getXclusiveInfo().getCanceledShares()); cout << endl<< " top bid executed shares "<< t.getXclusiveInfo().getCanceledShares() << endl; cout << endl << " after execution " << bid.top().getXclusiveInfo().getShares() << endl; bid.top().printOrder(); if(bid.top().getXclusiveInfo().getShares()<=0) {cout <<" fully executed"<<endl; bid.pop();} }else if(ask.top().getOrderReferenceNumber()==t.getOrderReferenceNumber()){ cout << endl<< " top ask executed shares "<< t.getXclusiveInfo().getCanceledShares() << endl; ask.top().getXclusiveInfo().updateShares(t.getXclusiveInfo().getCanceledShares()); if(ask.top().getXclusiveInfo().getShares()==0) { cout <<" fully executed"<<endl;ask.pop();} }else{ cout << " code cancellation execution error :" << endl; } */ //cout << endl << endl << " ********* " << endl << " Executing order:"; //t.printOrder(); if(mp[t.getOrderReferenceNumber()]) { queue<order> q; while(!bid.empty()){ if(bid.top().getOrderReferenceNumber()==t.getOrderReferenceNumber()) { //cout << endl << " before Execution " ; bid.top().printOrder();cout<<endl; int shares = bid.top().getXclusiveInfo().getShares()-t.getXclusiveInfo().getCanceledShares(); if(shares){ order a = order(bid.top().getGeneralInfo().getcode(),bid.top().getGeneralInfo().getStockLocate(),bid.top().getGeneralInfo().getTrackingNumber(), bid.top().getGeneralInfo().gettimestamp(),bid.top().getOrderReferenceNumber(),bid.top().getOldOrderReferenceNumber(),bid.top().getXclusiveInfo().getStock(), "B",shares,bid.top().getXclusiveInfo().getPrice(),bid.top().getXclusiveInfo().getAttribution(),0); q.push(a); //cout << "after Execution " ; a.printOrder();cout<<endl; } }else{ q.push(bid.top()); } bid.pop(); } while(!q.empty()) {bid.push(q.front());q.pop();} }else { queue<order> q; while(!ask.empty()){ if(ask.top().getOrderReferenceNumber()==t.getOrderReferenceNumber()) { int shares = bid.top().getXclusiveInfo().getShares()-t.getXclusiveInfo().getCanceledShares(); if(shares) { order a = order(ask.top().getGeneralInfo().getcode(),ask.top().getGeneralInfo().getStockLocate(),ask.top().getGeneralInfo().getTrackingNumber(), ask.top().getGeneralInfo().gettimestamp(),ask.top().getOrderReferenceNumber(),ask.top().getOldOrderReferenceNumber(),ask.top().getXclusiveInfo().getStock(), "S",ask.top().getXclusiveInfo().getShares()-t.getXclusiveInfo().getCanceledShares(),ask.top().getXclusiveInfo().getPrice(),ask.top().getXclusiveInfo().getAttribution(),0); q.push(a); } }else q.push(ask.top()); ask.pop(); } while(!q.empty()) {ask.push(q.front());q.pop();} } }else if(messageType=="D") { /* cout << endl << endl << " ********* " << endl << " Executing order:"; t.printOrder(); */ if(mp[t.getOrderReferenceNumber()]) { queue<order> q; while(!bid.empty()){ if(bid.top().getOrderReferenceNumber()!=t.getOrderReferenceNumber()) q.push(bid.top()); //else{ cout << " deleted: " << t.getOrderReferenceNumber() << endl;} bid.pop(); } while(!q.empty()) {bid.push(q.front());q.pop();} }else { queue<order> q; while(!ask.empty()){ if(ask.top().getOrderReferenceNumber()!=t.getOrderReferenceNumber()) q.push(ask.top()); //else{ cout << " deleted: " << t.getOrderReferenceNumber() << endl;} ask.pop(); } while(!q.empty()) {ask.push(q.front());q.pop();} } }else if(messageType=="U") { //cout << endl << endl << " ********* " << endl << " Executing order:"; //t.printOrder(); if(mp[t.getOldOrderReferenceNumber()]) { queue<order> q; while(!bid.empty()){ if(bid.top().getOldOrderReferenceNumber()==t.getOldOrderReferenceNumber()) { //cout << "before Exectuion : "; bid.top().printOrder();cout<< endl; order a = order(bid.top().getGeneralInfo().getcode(),bid.top().getGeneralInfo().getStockLocate(),bid.top().getGeneralInfo().getTrackingNumber(), bid.top().getGeneralInfo().gettimestamp(),t.getOrderReferenceNumber(),bid.top().getOldOrderReferenceNumber(),bid.top().getXclusiveInfo().getStock(), "B",t.getXclusiveInfo().getShares(),t.getXclusiveInfo().getPrice(),bid.top().getXclusiveInfo().getAttribution(),0); q.push(a); mp[a.getOldOrderReferenceNumber()]=0; mp[a.getOrderReferenceNumber()] = 1; //cout << " updated order: "; a.printOrder(); cout << endl; }else q.push(bid.top()); bid.pop(); } while(!q.empty()) {bid.push(q.front());q.pop();} }else { //cout << " in else " << endl; queue<order> q; while(!ask.empty()){ if(ask.top().getOldOrderReferenceNumber()==t.getOldOrderReferenceNumber()) { //cout << "before Exectuion : "; bid.top().printOrder();cout<< endl; order a = order(ask.top().getGeneralInfo().getcode(),ask.top().getGeneralInfo().getStockLocate(),ask.top().getGeneralInfo().getTrackingNumber(), ask.top().getGeneralInfo().gettimestamp(),t.getOrderReferenceNumber(),ask.top().getOldOrderReferenceNumber(),ask.top().getXclusiveInfo().getStock(), "S",t.getXclusiveInfo().getShares(),t.getXclusiveInfo().getPrice(),ask.top().getXclusiveInfo().getAttribution(),0); q.push(a); //cout << " updated order: "; a.printOrder(); cout << endl; }else q.push(ask.top()); ask.pop(); } while(!q.empty()) {ask.push(q.front());q.pop();} } } } }; int main() { ifstream f("spy.csv"); string row; long count = 0; if(f.is_open()) { while(getline(f,row)) { //cout << row << endl; if(count%10000==0 || count > 90000) cout << count << endl; orderAction::takeAction(row); ++count; } } cout << "------output -----"<< endl; while(!bid.empty()) { bid.top().printOrder(); cout << endl; bid.pop(); } cout << endl << endl << " ask " << endl; while(!ask.empty()) { ask.top().printOrder();cout << endl; ask.pop(); } f.close(); return 0; }
true
a3239bf24a5d0e78d58742f50db767195d3ae3ee
C++
wangchaomail/methods
/algorithms/sorting/quicksortclassic.cpp
UTF-8
1,544
3.703125
4
[]
no_license
#include <iostream> #include <algorithm> using namespace std; template <class A, class I> void print(A *a, I lo, I hi) { cout << "Array (size: " << hi - lo + 1 << "):"; for(I i = lo; i <= hi; ++i) { cout << ' ' << a[i]; } cout << endl; } template <class A, class I> I partition(A *a, I lo, I hi) { A p = a[hi]; I i = lo; cout << "Before partitioning, first at " << lo << ", last at " << hi << ", partition a[" << hi << "] = " << p << ", "; print(a, lo, hi); for(I j = lo; j < hi; ++j) { if(a[j] <= p) { swap(a[i], a[j]); cout << "Swapped a[j = " << i << "] = " << a[i] << " with a[i = " << j << "] = " << a[j] << ", "; print(a, lo, hi); ++i; } } swap(a[i], a[hi]); cout << "After partitioning, swapped a[partiotion = " << i << "] = " << a[i] << " with a[" << hi << "] = " << a[hi] << ", "; print(a, lo, hi); return i; } template <class A, class I> void quicksort(A *a, I lo, I hi) { if(lo < hi) { A p = partition(a, lo, hi); quicksort(a, lo, p - 1); quicksort(a, p + 1, hi); } } template <class A, class I> void fill_random(A *a, I lo, I hi) { srand(time(NULL)); I f = 1; for(I i = lo, j = 1; i <= hi; ++i, ++j) { a[i] = i; f *= j; } I p = static_cast<I>(static_cast<double>(rand()) / RAND_MAX * f); for(I i = 0; i < p; ++i) { next_permutation(a + lo, a + hi + 1); } } int main() { int a[10], lo = 0, hi = sizeof(a) / sizeof(a[0]) - 1; fill_random(a, lo, hi); cout << "Initially, "; print(a, lo, hi); quicksort(a, lo, hi); cout << "Sorted, "; print(a, lo, hi); return 0; }
true
73c94e7901c6475186206732f550020b8f566a6e
C++
advancevillage/trace
/core/object.h
UTF-8
1,022
2.859375
3
[]
no_license
#ifndef __OBJECT__ #define __OBJECT__ #ifndef __USED_OPENCV__ #define __USED_OPENCV__ #include <opencv2/opencv.hpp> using namespace cv; #endif class Object{ protected: int _x; int _y; int _width; int _height; cv::Scalar _color; bool _ishow; public: Object(); Object(int x, int y, int width, int height, cv::Scalar color, bool ishow = false); Object(Object& obj); Object(const Object& obj); ~Object(); void operator=(Object& obj); void operator=(const Object& obj); public: void SetX(const int x); int GetX()const; void SetY(const int y); int GetY()const; void SetWidth(const int width); int GetWidth()const; void SetHeight(const int height); int GetHeight()const; void SetColor(const cv::Scalar color); cv::Scalar GetColor()const; void SetShow(const bool ishow); bool GetShow()const; void SetPoint(cv::Point pos); void SetPoint(const int x, const int y); cv::Point GetPoint()const; }; #endif // OBJECT
true
1f7d8a12cd0c6ff8845532629a49a53113709c2d
C++
REDFOX1899/Interview-Bit
/Bit Manipulation/NumberOf1Bits.cpp
UTF-8
502
3.53125
4
[]
no_license
/* Write a function that takes an unsigned integer and returns the number of 1 bits it has. Example: The 32-bit integer 11 has binary representation 00000000000000000000000000001011 so the function should return 3. */ int Solution::numSetBits(unsigned int A) { int count =0; vector<int> bits (32, 0); int n = 31; while(A!=0){ bits[n--] = A%2; A = A/2; } for(int i =0; i<32; i++){ if(bits[i] ==1 ) count++; } return count; }
true
8e23ce4e6140d76f37dac7251f5b7a7abf209619
C++
xiayifan-1984/optionHedge
/memoryManage/journal/Page.h
UTF-8
1,903
2.640625
3
[]
no_license
#ifndef MM_PAGE_H #define MM_PAGE_H #include "../utils/memoryManage_declare.h" #include "../utils/constants.h" #include "FrameHeader.h" #include "Frame.hpp" MM_NAMESPACE_START FORWARD_DECLARE_PTR(Page) class Page { private: //current frame Frame frame; //address of mmap-file associated with this page void* const buffer; //current pos in page int position; //index of current frame in the page int frameNum; //num of page for the journal short pageNum; Page(void* buffer); private: inline FH_TYPE_STATUS getCurStatus() const { return frame.getStatus(); } public: inline void* getBuffer() { return buffer; } inline short getPageNum() const { return pageNum; } void finishPage(); void* locateWritableFrame(); void* locateReadableFrame(); bool isAtPageEnd() const; void passFrame(); void passWrittenFrame(); void passToTime(long time); public: static PagePtr load(const string&dir, const string& jname, short pageNum, bool isWriting, bool quickMode); }; inline bool Page::isAtPageEnd() const { return getCurStatus() == JOURNAL_FRAME_STATUS_PAGE_END; } inline void Page::passFrame() { position += frame.next(); frameNum++; } inline void Page::passWrittenFrame() { while (getCurStatus() == JOURNAL_FRAME_STATUS_WRITTEN) { passFrame(); } } inline void Page::passToTime(long time) { while (getCurStatus() == JOURNAL_FRAME_STATUS_WRITTEN && frame.getNano() < time) { passFrame(); } } inline void* Page::locateWritableFrame() { passWrittenFrame(); return (getCurStatus() == JOURNAL_FRAME_STATUS_RAW && (position + PAGE_MIN_HEADROOM < JOURNAL_PAGE_SIZE)) ? frame.get_address() : nullptr; } inline void* Page::locateReadableFrame() { return (getCurStatus() == JOURNAL_FRAME_STATUS_WRITTEN) ? frame.get_address() : nullptr; } MM_NAMESPACE_END #endif
true
e3d810224c57d2823ee246ae7819cbb94d58a21e
C++
jiadaizhao/LeetCode
/0401-0500/0489-Robot Room Cleaner/0489-Robot Room Cleaner.cpp
UTF-8
2,122
3.609375
4
[ "MIT" ]
permissive
/** * // This is the robot's control interface. * // You should not implement it, or speculate about its implementation * class Robot { * public: * // Returns true if the cell in front is open and robot moves into the cell. * // Returns false if the cell in front is blocked and robot stays in the current cell. * bool move(); * * // Robot will stay in the same cell after calling turnLeft/turnRight. * // Each turn will be 90 degrees. * void turnLeft(); * void turnRight(); * * // Clean the current cell. * void clean(); * }; */ struct pairhash { template<typename T, typename U> size_t operator()(const pair<T, U> &p) const { return hash<T>()(p.first) ^ hash<U>()(p.second); } }; class Solution { public: void cleanRoom(Robot& robot) { return dfs(robot, 0, 0); } private: unordered_set<pair<int, int>, pairhash> visited; void dfs(Robot& robot, int row, int col) { if (visited.count({row, col})) { return; } robot.clean(); visited.insert({row, col}); if (moveUp(robot)) { dfs(robot, row - 1, col); moveDown(robot); } if (moveDown(robot)) { dfs(robot, row + 1, col); moveUp(robot); } if (moveLeft(robot)) { dfs(robot, row, col - 1); moveRight(robot); } if (moveRight(robot)) { dfs(robot, row, col + 1); moveLeft(robot); } } bool moveUp(Robot& robot) { return robot.move(); } bool moveDown(Robot& robot) { robot.turnRight(); robot.turnRight(); bool ok = robot.move(); robot.turnLeft(); robot.turnLeft(); return ok; } bool moveLeft(Robot& robot) { robot.turnLeft(); bool ok = robot.move(); robot.turnRight(); return ok; } bool moveRight(Robot& robot) { robot.turnRight(); bool ok = robot.move(); robot.turnLeft(); return ok; } };
true
c22c2b9f7e7f92464feca3834f6f9174fc2eef77
C++
alissastanderwick/OpenKODE-Framework
/01_Develop/libXMCocos2D-v3/Source/3d/C3DBatchMesh.cpp
UTF-8
5,818
2.6875
3
[ "MIT" ]
permissive
#include "3d/C3DBatchMesh.h" #include "3d/C3DVertexFormat.h" #include "3d/Vertex.h" namespace cocos3d { C3DBatchMesh::C3DBatchMesh(const C3DVertexFormat* vertexFormat, PrimitiveType primitiveType, bool bIndex, unsigned int initialCapacity, unsigned int growSize) : _vertexFormat(NULL), _primitiveType(primitiveType), _capacity(0), _growSize(growSize), _vertexCapacity(0), _vertexCount(0), _vertices(NULL), _verticesPtr(NULL), _indices(NULL), _indicesPtr(NULL), _indexCount(0) { _vertexFormat = new C3DVertexFormat(vertexFormat); _bUseIndex = bIndex; _indexCapacity = 0; resize(initialCapacity); } C3DBatchMesh::~C3DBatchMesh() { SAFE_DELETE_ARRAY(_vertices); SAFE_DELETE_ARRAY(_indices); _verticesPtr = NULL; _indicesPtr = NULL; SAFE_DELETE(_vertexFormat); } unsigned int C3DBatchMesh::getCapacity() const { return _capacity; } void C3DBatchMesh::setCapacity(unsigned int capacity) { resize(capacity); } void C3DBatchMesh::setIndexCapacity(unsigned int capacity) { resizeIndex(capacity); } bool C3DBatchMesh::resize(unsigned int capacity) { if (capacity == 0) return false; if (capacity == _capacity) return true; unsigned char* oldVertices = _vertices; unsigned int vertexCapacity = 0; switch (_primitiveType) { case PrimitiveType_LINES: vertexCapacity = capacity * 2; break; case PrimitiveType_TRIANGLES: vertexCapacity = capacity * 3; break; default: assert(0); break; } // Allocate new data and reset pointers unsigned int voffset = _verticesPtr - _vertices; unsigned int vBytes = vertexCapacity * _vertexFormat->getVertexSize(); _vertices = new unsigned char[vBytes]; if (voffset >= vBytes) voffset = vBytes - 1; _verticesPtr = _vertices + voffset; // Copy old data back in if (oldVertices) memcpy(_vertices, oldVertices, std::min(_vertexCapacity, vertexCapacity) * _vertexFormat->getVertexSize()); SAFE_DELETE_ARRAY(oldVertices); // Assign new capacities _capacity = capacity; _vertexCapacity = vertexCapacity; return true; } bool C3DBatchMesh::resizeIndex(unsigned int capacity) { if (_bUseIndex) { unsigned short* oldIndex = _indices; unsigned int voffset = _indicesPtr - _indices; unsigned int vBytes = capacity * sizeof(unsigned short); _indices = new unsigned short[capacity]; if (voffset >= vBytes) voffset = vBytes - 1; _indicesPtr = _indices + voffset; if (oldIndex) { if (voffset) memcpy(_indices, oldIndex, voffset); SAFE_DELETE_ARRAY(oldIndex); } _indexCapacity = capacity; } return true; } void C3DBatchMesh::add(const BBVertex* vertices, unsigned int vertexCount) { assert(sizeof(BBVertex) == _vertexFormat->getVertexSize() && !_bUseIndex); unsigned int newVertexCount = _vertexCount + vertexCount; if (newVertexCount > _vertexCapacity) { if (_growSize == 0) return; int growSize = ((newVertexCount - _vertexCapacity) / _growSize + 1) * _growSize; if (!resize(_capacity + growSize)) return; } unsigned int vBytes = vertexCount * _vertexFormat->getVertexSize(); memcpy(_verticesPtr, vertices, vBytes); _verticesPtr += vBytes; _vertexCount = newVertexCount; } void C3DBatchMesh::add(const BBVertex* vertices, unsigned int vertexCount, const unsigned short* indices, unsigned int indexCount) { assert(sizeof(BBVertex) == _vertexFormat->getVertexSize() && _bUseIndex); unsigned int newVertexCount = _vertexCount + vertexCount; unsigned int newIdxCount = _indexCount + indexCount; unsigned int oldVertexCount = _vertexCount; if (newVertexCount > _vertexCapacity) { if (_growSize == 0) return; int growSize = ((newVertexCount - _vertexCapacity) / _growSize + 1) * _growSize; if (!resize(_capacity + growSize)) return; } if (newIdxCount > _indexCapacity) { int growSize = ((newIdxCount - _indexCount) / _growSize + 1) * _growSize; if (!resizeIndex(_capacity + growSize)) return; } unsigned int vBytes = vertexCount * _vertexFormat->getVertexSize(); memcpy(_verticesPtr, vertices, vBytes); _verticesPtr += vBytes; _vertexCount = newVertexCount; for (int i = 0; i < indexCount; i++) { *_indicesPtr = indices[i] + oldVertexCount; _indicesPtr++; } _indexCount = newIdxCount; } void C3DBatchMesh::add(const VertexColorCoord1* vertices, unsigned int vertexCount, const unsigned short* indices, unsigned int indexCount) { //make sure use index unsigned int newVertexCount = _vertexCount + vertexCount; unsigned int newIndexCount = _indexCount + indexCount; unsigned int oldVertexCount = _vertexCount; while (newVertexCount > _vertexCapacity) { if (_growSize == 0) return; if (!resize(_capacity + _growSize)) return; } if (newIndexCount > _indexCapacity) { if (!resizeIndex(std::max(newIndexCount, _indexCapacity + _indexCapacity) ) ) return; } unsigned int vBytes = vertexCount * _vertexFormat->getVertexSize(); memcpy(_verticesPtr, vertices, vBytes); _verticesPtr += vBytes; _vertexCount = newVertexCount; for (int i = 0; i < indexCount; i++) { *_indicesPtr = indices[i] + oldVertexCount; _indicesPtr++; } _indexCount = newIndexCount; } void C3DBatchMesh::begin() { _vertexCount = 0; _verticesPtr = _vertices; _indicesPtr = _indices; _indexCount = 0; } void C3DBatchMesh::end() { } }
true
42f4a6c1b4663302691523bb611e3cb41294b9d9
C++
jamellknows/rationalPointsEllipse
/main.cpp
UTF-8
5,262
3.390625
3
[ "MIT" ]
permissive
#include <iostream> #include <cmath> #include <cstdlib> #include <vector> #include <string> #include <math.h> using namespace std; int primes(); int conversion(); void curve(); void rational(); int conversion(long double number) //This function converts decimals to integers { string stringDouble = to_string(number); cout << "As a string: " << stringDouble << endl; int decimal = stringDouble.find("."); int length = stringDouble.length(); length = length - decimal; int exponent = pow(10, length); int wholeNumber = number * exponent; //remove unnnecessary 0's //coversion issues return wholeNumber; } void rational(double number2) { int numberTest = conversion(number2); int primeTest = conversion(M_PI); cout << "PI converted too: " << primeTest <<endl; int test = numberTest % primeTest; cout << "The test results were: " << test << endl; } int fPrime(int number3) //This function calculates finalPrime { string stringDouble = to_string(number3); int length = stringDouble.length(); char firstchar = stringDouble[0]; int firstNum = atoi(&firstchar); int finalPrime = (firstNum + 1) * pow(10, length); return finalPrime; } int lengthOf(int number) { string stringDouble = to_string(number); int length = stringDouble.length(); return length; } int primes(int testLength, int primechoice){ int number = testLength; vector <long double> arr1; vector <long double> arr2; vector <long double> prime1; vector <long double> prime2; long double theta = M_PI / 3; for( int i = 0; i < number ; i++) { double y_1 = theta * (1 + 6 * i); y_1 = sqrt(pow(y_1/theta, 2) - 0.25); arr1.push_back(y_1); double y_2 = 5 * theta * (1 + ((6 / 5) * i)); y_2 = sqrt(pow(y_2/theta, 2) - 0.25); arr1.push_back(y_2); } int lArr1 = arr1.size(); sort(arr1.begin(), arr1.begin() + lArr1); for (int k = 0; k < lArr1; k++){ if(((k + 1) % 4) == 0){ arr1[k] = arr1[k] + 1; } prime1.push_back(floor(arr1[k]) - 1); prime1.push_back(floor(arr1[k]) + 1); } return prime1[primechoice]; } void curve(double a, double b) { // cout << "To what precision do you want to plot the curve? integer value " << endl; vector <long double> y2; vector <long double> y; vector <long double> x; double start; double step = 0.1; //will be precions double stoppingValue; cout << "What is the starting value of x (double 0.0)/ STARTING RANGE" << endl; cin >> start; cout << "To what value of x would you want to find the rational points to ?\n This is a double (0.0)/ ENDING RANGE" <<endl; cin >> stoppingValue; for(double x_run = 0.0; x_run < stoppingValue; x_run+=step) { long double y2_run = pow(x_run, 3) + a * x_run + b; long double y_run = sqrt(y2_run); y.push_back(y_run); y2.push_back(y2_run); x.push_back(x_run); // cout << "The value of y^2 is " << y2_run << endl; // cout << "The value of y is " << y_run << endl; // cout << "For the value of x " << x_run << endl; } for(int i = 0; i < y.size(); i++) { int convertedY = conversion(y[i]); int lengthY = lengthOf(convertedY); int finalPrimeY = fPrime(convertedY/30); int k; cout << "y is " << y[i] <<endl; cout << "The length of the y value is " << lengthY << endl; cout << "y converted to an equivalent whole number " << convertedY << endl; cout << "Therefore the final prime to test too is " << finalPrimeY <<endl; for(int k = 0; k < 2; k++) { cout << "loop"; if(convertedY % primes(finalPrimeY, k) == 0){ cout << "\n\nRATIONAL POINT!!!\n"; cout << "The point y is :" << y[i] <<endl; cout << "The point x is :" << x[i] <<endl; } } } } int main() { double a, b; double root = sqrt(2); double x, y; int testLength = 50; double step = 0.1; double start; double stop = 2 * M_PI; //y^2 = x^3 + ax + b //draw the curve //input a input b //find y //find the points //find rational points cout << "\n\n\tWELCOME TO THE RATIONAL POINTS ON A CURVE FINDER!!!\n\n"; cout << "What value of a and b do you want to use?\n"; cout << "The fomula for a curve is y^2 = x^3 + ax + b\n"; cout << "Enter a\n"; cin>>a; cout << "Enter b\n"; cin>>b; curve(a,b); // for(double thetaM = start; thetaM <= stop ; thetaM+=step) // { // x = cos(thetaM); // cout << "The point x is " << x << endl; // y = root/x; // int z = conversion(y); // for(int i; i < testLength; i++){ // if(z % primes(testLength, i) == 0 ){ // cout << "Rational point"<<endl; // cout << "The point y is " << y << endl; // cout << z << endl; // } // } // } //cool we can find rational points return 0; }
true
3dcbb359efa7b9e68a5c3ba364d06ad482194660
C++
xiezilailai-xkh/MS_DAKA
/Week32/longest-univalue-path.cpp
UTF-8
942
3.140625
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ans; int dfs(TreeNode* root){ if(!root)return 0; int tmp = 1; int left_one = 1; int right_one = 1; int left = dfs(root->left); int right = dfs(root->right); if(root->left&&root->left->val == root->val) { tmp += left; left_one += left; } if(root->right&&root->right->val == root->val){ right_one += right; tmp += right; } int tmp_ans = max(max(left, right), tmp); ans = max(ans, tmp_ans); return max(left_one, right_one); } int longestUnivaluePath(TreeNode* root) { ans = 0; dfs(root); return max(0, ans-1); } };
true
d9cccad6d498f6f51d77eafe754216f56dea8e2b
C++
ljjhome/CPrimerPractice
/chp3/ex_3_1.cpp
UTF-8
564
3.65625
4
[]
no_license
#include <iostream> using std::cout; using std::endl; using std::cin; int main(){ /* exercise 1.9*/ int i = 50; int sum = 0; while(i<101){ sum = sum + i; i++; } cout<<"the sum from 50 to 100 is: "<<sum<<endl; /* exercise 1.10*/ for (int i = 10; i>-1; i--){ cout<<i<<endl; } /* exercise 1.11*/ int num1,num2; cout<<"input two numbers like 10 20: "<<endl; cin>>num1>>num2; int count = num1; while(count<=num2){ cout<<count<<endl; count++; } return 0; }
true
88d912b10677ef1f2ff4c5b9ce60e5aaad8d8988
C++
schmcory/CS161
/week1/gardenCost.cpp
UTF-8
2,015
3.875
4
[]
no_license
#include <iostream> #include <stdint.h> #include <iomanip> //function prototype int inputValidation(double &input); // a simple example program int main() { double soilCost; //variable holds cost of soil input by user double flowerSeedsCost; //variable holds cost of flowers input by user double fenceCost; //variable holds cost of fence input by user double totalCost; //variable holds total cost calculated by the program //initial statement prints to introduce the program std::cout << "This program will calculate the cost of your garden center." << std::endl; //Asks user for the cost of their soil std::cout << "What does the soil cost?" << std::endl; std::cout << "$"; std::cin >> soilCost; //input validation inputValidation(soilCost); //Asks user for cost of flower seeds std::cout << "What do the flower seeds cost?" << std::endl; std::cout << "$"; std::cin >> flowerSeedsCost; //input validation inputValidation(flowerSeedsCost); //Asks user for cost of fence std::cout << "What does the fence cost?" << std::endl; std::cout << "$"; std::cin >> fenceCost; //input validation inputValidation(fenceCost); //test input //std::cout << "soil cost: $" << soilCost << " flower seeds cost: $" << flowerSeedsCost << " fence cost: $" << fenceCost << std::endl; //calculates the total cost totalCost = soilCost + flowerSeedsCost + fenceCost; //prints total cost with two decimal places std::cout << "The total cost of your garden center is $" << std::setprecision(2) << std::fixed << totalCost << "." << std::endl; //terminates program return 0; } //input validation function int inputValidation(double &input) { while(std::cin.fail()) { std::cout << "Please only enter a number." << std::endl; std::cin.clear(); std::cin.ignore(); std::cout << "$"; std::cin >> input; } return input; }
true
abfd579fa05c9a85b379074a8312e081f9499c82
C++
ssong86/leetcode-problem-solving
/Top-Interview-Questions/DynamicProgramming-Easy-Collection/53-maximum-subarray.cpp
UTF-8
552
2.90625
3
[]
no_license
// Kadane's algorithm // TC: O(n) // SC: O(1) // Runtime: 12 ms, faster than 64.48% // Memory Usage: 13.4 MB, less than 22.87% class Solution { public: int maxSubArray(vector<int>& nums) { if(!nums.size()) return 0; int max = INT_MIN, sum = 0; for(int i = 0; i < nums.size(); i++){ sum += nums[i]; if(sum > max) max = sum; if(sum < 0) sum = 0; } return max; } };
true
9b9ef1a5826ea1294aff5fdcf75385f27a90c65a
C++
zetrax1/POS
/src/controller/Hra.cpp
UTF-8
5,641
2.734375
3
[]
no_license
#include "Hra.hpp" #include <iostream> #include <future> #include <thread> #include <chrono> namespace controler { Hra::Hra() { } Hra::~Hra() { } void Hra::moveItems() { while (m_isRun) { for (int i = 0; i < (int)m_postava.size(); i++) { auto x = getPostava(i).getPozicia().first; auto y = getPostava(i).getPozicia().second; std::tuple<bool, bool, bool,bool> smer = readSmerFromVector(i); //left, right ,up ,down if (std::get<0>(smer)) x -= SPRITE_SPEED; if (std::get<1>(smer)) x += SPRITE_SPEED; if (std::get<2>(smer)) y -= SPRITE_SPEED; if (std::get<3>(smer)) y += SPRITE_SPEED; // Check screen boundaries if (x < 0) x = 0; if (x > sizeWin.first) x = sizeWin.first; if (y < 0) y = 0; if (y > sizeWin.second) y = sizeWin.second; writeToVector(x, y, i); } std::this_thread::sleep_for(std::chrono::milliseconds(30)); } } std::tuple<bool, bool, bool,bool> Hra::readSmerFromVector(int index) { return m_postava[index].getSmer(); } void Hra::writeToVector(int x, int y, int index) { std::unique_lock<std::mutex> mlock(mutex_); m_postava[index].setPozicia(x, y); mutex_.unlock(); } void Hra::writeToVector(std::tuple<bool, bool, bool,bool> smer,int index) { std::cout << "prisla mi od servera" << std::get<0>(smer)<< std::get<1>(smer) << std::get<2>(smer) << std::get<3>(smer) << "\n"; std::unique_lock<std::mutex> mlock(mutex_); m_postava[index].setSmer(smer); mutex_.unlock(); } void Hra::setMapa(model::Mapa map) { m_mapa = map; } void Hra::addNewPostava(const model::Postava &postava) { m_postava.push_back(postava); m_postava.back().setSprite(); } model::Postava &Hra::getPostava(int i_postava) { return m_postava[i_postava]; } void Hra::ovladanie_hry(sf::RenderWindow &window) { // Process events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) { switch (event.key.code) { case sf::Keyboard::Escape: window.close(); break; case sf::Keyboard::Up: upFlag = true; change = true; break; case sf::Keyboard::Down: downFlag = true; change = true; break; case sf::Keyboard::Left: leftFlag = true; change = true; break; case sf::Keyboard::Right: rightFlag = true; change = true; break; default: break; } } if (event.type == sf::Event::KeyReleased) { switch (event.key.code) { case sf::Keyboard::Up: upFlag = false; change = true; break; case sf::Keyboard::Down: downFlag = false; change = true; break; case sf::Keyboard::Left: leftFlag = false; change = true; break; case sf::Keyboard::Right: rightFlag = false; change = true; break; default: break; } } } if (change == true && initialized ) { client.sendMsg(Data(m_postava[m_indexClient].getPozicia().first, m_postava[m_indexClient].getPozicia().second, m_indexClient, std::make_tuple(leftFlag, rightFlag, upFlag, downFlag))); change = false; } } bool Hra::messageReaction() { while(m_isRun) { Data data = client.getFromReadQueue(); switch (data.getType()) { case typeMessage::pohyb: messagePohyb(data); break; case typeMessage::newClient: messageNewClient(data); break; case typeMessage::initMessage: messageInit(data); break; default: break; } } return true; } void Hra::messagePohyb(Data &data) { writeToVector(data.getSmer(),data.getIndex()); writeToVector(data.getSuradnice().first ,data.getSuradnice().second ,data.getIndex() ); } void Hra::messageInit(Data &data) { m_indexClient = data.getIndex(); std::cout << m_indexClient << " index clienta pri init \n"; std::unique_lock<std::mutex> mlock(mutex_); for (int i = 0; i < m_indexClient+1 ; i++) { addNewPostava(model::Postava(100 ,100 )); } mutex_.unlock(); initialized = true; } void Hra::messageNewClient(Data &data) { std::unique_lock<std::mutex> mlock(mutex_); addNewPostava(model::Postava(data.getSuradnice().first,data.getSuradnice().second)); mutex_.unlock(); } void Hra::init_hra() { view::Monitor_view monitorView; sf::RenderWindow &window = monitorView.get(); sizeWin = monitorView.getSize(); std::thread(&controler::Hra::moveItems, this).detach(); std::future<bool> fut = std::async(&controler::Hra::messageReaction, this); while (window.isOpen()) { ovladanie_hry(std::ref(monitorView.get())); window.clear(); if(initialized) { for (model::Postava n : m_postava) { window.draw(n.getSprite()); } } window.display(); } if (fut.get()) { return; } std::unique_lock<std::mutex> mlock(mutex_); m_isRun = false; mutex_.unlock(); } } // namespace controler
true
7bae6927714c047cdde6cc24ba164e771e349748
C++
RostyslavMV/OOP_Module1
/Task2/Task2/Function.h
UTF-8
4,409
3.546875
4
[ "MIT" ]
permissive
#pragma once #include <sstream> #include <string> #include <vector> #include <cmath> #include <set> using std::string; using std::to_string; using std::vector; using std::istringstream; using std::pair; using std::set; class Function { private: int IntPow(int arg, int pow) { int ret = 1; for (int i = 1; i <= pow; i++) { ret *= arg; } return ret; } string IntName(int a) { string ret; switch (a / 100) { case 1: ret += "one "; break; case 2: ret += "two "; break; case 3: ret += "three "; break; case 4: ret += "four "; break; case 5: ret += "five "; break; case 6: ret += "six "; break; case 7: ret += "seven "; break; case 8: ret += "eight "; break; case 9: ret += "nine "; break; } if (a / 100 > 0) ret += "hundred "; switch ((a % 100) / 10) { case 2: ret += "twenty "; break; case 3: ret += "thirty "; break; case 4: ret += "forty "; break; case 5: ret += "fifty "; break; case 6: ret += "sixty "; break; case 7: ret += "seventy "; break; case 8: ret += "eighty "; break; case 9: ret += "ninety "; break; } if (a % 100 >= 10 & a % 100 < 20) { switch (a % 100) { case 10: ret += "ten "; break; case 11: ret += "eleven "; break; case 12: ret += "twelve "; break; case 13: ret += "thirteen "; break; case 14: ret += "fourteen "; break; case 15: ret += "fifteen "; break; case 16: ret += "sixteen "; break; case 17: ret += "seventeen "; break; case 18: ret += "eighteen "; break; case 19: ret += "nineteen"; break; } } else { switch (a % 10) { case 1: ret += "one "; break; case 2: ret += "two "; break; case 3: ret += "three "; break; case 4: ret += "four "; break; case 5: ret += "five "; break; case 6: ret += "six "; break; case 7: ret += "seven "; break; case 8: ret += "eight "; break; case 9: ret += "nine "; break; } } return ret; } public: template <typename T> string func(T argument) { return "sorry try again please"; } template <> string func(int argument) { int a; string ret; if (argument >= 0) a = (argument * argument) % 117; else a = (IntPow(argument, 5) + IntPow(argument, 3)) % 217; if (a < 0) { a += 217; } int bil = a / 1000000000; if (bil > 0) { ret += IntName(bil) + "billions "; } int mil = (a - (bil * 1000000000)) / 1000000; if (mil > 0) { ret += IntName(mil) + "millions "; } int th = (a - (bil * 1000000000) - (mil * 1000000)) / 1000; if (th > 0) { ret += IntName(th) + "thousands "; } int rest = a - (bil * 1000000000) - (mil * 1000000) - (th * 1000); if (rest > 0) { ret += IntName(rest); } return ret; } template <> string func(double argument) { string a, ret; a = to_string(sin(argument + 317)); string s = a.substr(a.find('.') + 1, 2); ret = IntName(((int)s.at(0) - 48) * 10 + (int)s.at(1) - 48); return ret; } template <> string func(string argument) { string ret; vector<string> words; istringstream iss(argument); for (string s; iss >> s; ) words.push_back(s); for (int i = words.size() - 1; i >= 0; i--) { ret += words[i] + " "; } if (ret.at(ret.size() - 1) == ' ') ret.erase(ret.size() - 1); return ret; } template <typename T1, typename T2> string func(pair<T1, T2> pair) { string ret; string s1 = func(pair.first), s2 = func(pair.second); istringstream iss1(s1), iss2(s2); string buff1, buff2; while (iss1 >> buff1 && iss2 >> buff2) { ret += buff2 + " " + buff1 + " "; } while (iss1 >> buff1) { ret += buff1 + " "; } while (iss2 >> buff2) { ret += buff2 + " "; } if (ret.at(ret.size() - 1) == ' ') ret.erase(ret.size() - 1); return ret; } template <typename T> string func(vector<T> argument) { set<string> words; string ret; for (int i = 0; i < argument.size(); i++) { string s = func(argument[i]); istringstream iss(s); while (iss >> s) words.insert(s); } set<string>::iterator it; for (it = words.begin(); it != words.end(); it++) { ret += *it + " "; } if (ret.at(ret.size() - 1) == ' ') ret.erase(ret.size() - 1); return ret; } };
true
cc7161289d65bbabe80502c4402167ab540643bd
C++
HeliumProject/Engine
/Source/Engine/Engine/AssetPath.cpp
UTF-8
30,486
2.8125
3
[ "BSD-3-Clause" ]
permissive
#include "Precompile.h" #include "Engine/AssetPath.h" #include "Foundation/FilePath.h" #include "Foundation/ReferenceCounting.h" #include "Engine/Asset.h" struct Helium::AssetPath::PendingLink { PendingLink *rpNext; //struct Entry *pObjectPath; AssetWPtr wpOwner; // TODO: Maybe this ought to be a relative pointer from pObjectPath's instance? AssetPtr *rpPointerToLink; }; using namespace Helium; AssetPath::TableBucket* AssetPath::sm_pTable = NULL; StackMemoryHeap<>* AssetPath::sm_pEntryMemoryHeap = NULL; ObjectPool<AssetPath::PendingLink> *AssetPath::sm_pPendingLinksPool = NULL; /// Parse the object path in the specified string and store it in this object. /// /// @param[in] pString Asset path string to set. If this is null or empty, the path will be cleared. /// /// @return True if the string was parsed successfully and the path was set (or cleared, if the string was null or /// empty), false if not. /// /// @see Clear(), ToString() bool AssetPath::Set( const char* pString ) { // Check for empty strings first. if( !pString || pString[ 0 ] == '\0' ) { m_pEntry = NULL; return true; } StackMemoryHeap<>& rStackHeap = ThreadLocalStackAllocator::GetMemoryHeap(); StackMemoryHeap<>::Marker stackMarker( rStackHeap ); Name* pEntryNames; uint32_t* pInstanceIndices; size_t nameCount; size_t packageCount; if( !Parse( pString, rStackHeap, pEntryNames, pInstanceIndices, nameCount, packageCount ) ) { return false; } HELIUM_ASSERT( pEntryNames ); HELIUM_ASSERT( pInstanceIndices ); HELIUM_ASSERT( nameCount != 0 ); Set( pEntryNames, pInstanceIndices, nameCount, packageCount ); return true; } /// Parse the object path in the specified string and store it in this object. /// /// @param[in] rString Asset path string to set. If this is empty, the path will be cleared. /// /// @return True if the string was parsed successfully and the path was set (or cleared, if the string was empty), /// false if not. /// /// @see Clear(), ToString() bool AssetPath::Set( const String& rString ) { return Set( rString.GetData() ); } /// Set this path based on the given parameters. /// /// @param[in] name Asset name. /// @param[in] bPackage True if the object is a package, false if not. /// @param[in] parentPath FilePath to the parent object. /// @param[in] instanceIndex Asset instance index. Invalid index values are excluded from the path name string. /// /// @return True if the parameters can represent a valid path and the path was set, false if not. bool AssetPath::Set( Name name, bool bPackage, AssetPath parentPath, uint32_t instanceIndex ) { Entry* pParentEntry = parentPath.m_pEntry; // Make sure we aren't trying to build a path to a package with a non-package parent. if( bPackage && pParentEntry && !pParentEntry->bPackage ) { return false; } // Build a representation of the path table entry for the given path. Entry entry; entry.pParent = pParentEntry; entry.name = name; entry.instanceIndex = instanceIndex; entry.bPackage = bPackage; // Look up/add the entry. m_pEntry = Add( entry ); HELIUM_ASSERT( m_pEntry ); return true; } /// Set this path to the combination of two paths. /// /// @param[in] rootPath Root portion of the path. /// @param[in] subPath Sub-path component. /// /// @return True if the paths could be joined into a valid path (to which this path was set), false if joining was /// invalid. bool AssetPath::Join( AssetPath rootPath, AssetPath subPath ) { if( subPath.IsEmpty() ) { m_pEntry = rootPath.m_pEntry; return true; } if( rootPath.IsEmpty() ) { m_pEntry = subPath.m_pEntry; return true; } if( !rootPath.IsPackage() ) { AssetPath testSubPathComponent = subPath.GetParent(); AssetPath subPathComponent; do { subPathComponent = testSubPathComponent; testSubPathComponent = testSubPathComponent.GetParent(); if( subPathComponent.IsPackage() ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath::Join(): Cannot combine \"%s\" and \"%s\" (second path is rooted in a package, while the first path ends in an object).\n", *rootPath.ToString(), *subPath.ToString() ); return false; } } while( !testSubPathComponent.IsEmpty() ); } // Assemble the list of path names in reverse order for performing the object path lookup/add. size_t nameCount = 0; size_t packageCount = 0; AssetPath testPath; for( testPath = subPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { ++nameCount; if( subPath.IsPackage() ) { ++packageCount; } } for( testPath = rootPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { ++nameCount; if( testPath.IsPackage() ) { ++packageCount; } } StackMemoryHeap<>& rStackHeap = ThreadLocalStackAllocator::GetMemoryHeap(); StackMemoryHeap<>::Marker stackMarker( rStackHeap ); Name* pEntryNames = static_cast< Name* >( rStackHeap.Allocate( sizeof( Name ) * nameCount ) ); HELIUM_ASSERT( pEntryNames ); uint32_t* pInstanceIndices = static_cast< uint32_t* >( rStackHeap.Allocate( sizeof( uint32_t ) * nameCount ) ); HELIUM_ASSERT( pInstanceIndices ); Name* pCurrentName = pEntryNames; uint32_t* pCurrentIndex = pInstanceIndices; for( testPath = subPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { *pCurrentName = testPath.GetName(); *pCurrentIndex = testPath.GetInstanceIndex(); ++pCurrentName; ++pCurrentIndex; } for( testPath = rootPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { *pCurrentName = testPath.GetName(); *pCurrentIndex = testPath.GetInstanceIndex(); ++pCurrentName; ++pCurrentIndex; } // Set the path. Set( pEntryNames, pInstanceIndices, nameCount, packageCount ); return true; } /// Set this path to the combination of two paths. /// /// @param[in] rootPath Root portion of the path. /// @param[in] pSubPath Sub-path component. /// /// @return True if the paths could be joined into a valid path (to which this path was set), false if joining was /// invalid. bool AssetPath::Join( AssetPath rootPath, const char* pSubPath ) { if( !pSubPath || pSubPath[ 0 ] == '\0' ) { m_pEntry = rootPath.m_pEntry; return true; } // Parse the sub-path into a series of names. StackMemoryHeap<>& rStackHeap = ThreadLocalStackAllocator::GetMemoryHeap(); StackMemoryHeap<>::Marker stackMarker( rStackHeap ); Name* pSubPathNames; uint32_t* pSubPathIndices; size_t subPathNameCount; size_t subPathPackageCount; if( !Parse( pSubPath, rStackHeap, pSubPathNames, pSubPathIndices, subPathNameCount, subPathPackageCount ) ) { return false; } if( !rootPath.IsPackage() && subPathPackageCount != 0 ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath::Join(): Cannot combine \"%s\" and \"%s\" (second path is rooted in a package, while the first path ends in an object).\n", *rootPath.ToString(), pSubPath ); return false; } // Assemble the list of path names in reverse order for performing the object path lookup/add. size_t nameCount = subPathNameCount; size_t packageCount = subPathPackageCount; AssetPath testPath; for( testPath = rootPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { ++nameCount; if( testPath.IsPackage() ) { ++packageCount; } } Name* pEntryNames = static_cast< Name* >( rStackHeap.Allocate( sizeof( Name ) * nameCount ) ); HELIUM_ASSERT( pEntryNames ); ArrayCopy( pEntryNames, pSubPathNames, subPathNameCount ); uint32_t* pInstanceIndices = static_cast< uint32_t* >( rStackHeap.Allocate( sizeof( uint32_t ) * nameCount ) ); HELIUM_ASSERT( pInstanceIndices ); ArrayCopy( pInstanceIndices, pSubPathIndices, subPathNameCount ); Name* pCurrentName = &pEntryNames[ subPathNameCount ]; uint32_t* pCurrentIndex = &pInstanceIndices[ subPathNameCount ]; for( testPath = rootPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { *pCurrentName = testPath.GetName(); *pCurrentIndex = testPath.GetInstanceIndex(); ++pCurrentName; ++pCurrentIndex; } // Set the path. Set( pEntryNames, pInstanceIndices, nameCount, packageCount ); return true; } /// Set this path to the combination of two paths. /// /// @param[in] pRootPath Root portion of the path. /// @param[in] subPath Sub-path component. /// /// @return True if the paths could be joined into a valid path (to which this path was set), false if joining was /// invalid. bool AssetPath::Join( const char* pRootPath, AssetPath subPath ) { if( !pRootPath || pRootPath[ 0 ] == '\0' ) { m_pEntry = subPath.m_pEntry; return true; } // Parse the root path into a series of names. StackMemoryHeap<>& rStackHeap = ThreadLocalStackAllocator::GetMemoryHeap(); StackMemoryHeap<>::Marker stackMarker( rStackHeap ); Name* pRootPathNames; uint32_t* pRootPathIndices; size_t rootPathNameCount; size_t rootPathPackageCount; if( !Parse( pRootPath, rStackHeap, pRootPathNames, pRootPathIndices, rootPathNameCount, rootPathPackageCount ) ) { return false; } if( rootPathNameCount != rootPathPackageCount ) { AssetPath testSubPathComponent = subPath.GetParent(); AssetPath subPathComponent; do { subPathComponent = testSubPathComponent; testSubPathComponent = testSubPathComponent.GetParent(); if( subPathComponent.IsPackage() ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath::Join(): Cannot combine \"%s\" and \"%s\" (second path is rooted in a package, while the first path ends in an object).\n", pRootPath, *subPath.ToString() ); return false; } } while( !testSubPathComponent.IsEmpty() ); } // Assemble the list of path names in reverse order for performing the object path lookup/add. size_t nameCount = rootPathNameCount; size_t packageCount = rootPathPackageCount; AssetPath testPath; for( testPath = subPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { ++nameCount; if( testPath.IsPackage() ) { ++packageCount; } } Name* pEntryNames = static_cast< Name* >( rStackHeap.Allocate( sizeof( Name ) * nameCount ) ); HELIUM_ASSERT( pEntryNames ); uint32_t* pInstanceIndices = static_cast< uint32_t* >( rStackHeap.Allocate( sizeof( uint32_t ) * nameCount ) ); HELIUM_ASSERT( pInstanceIndices ); Name* pCurrentName = pEntryNames; uint32_t* pCurrentIndex = pInstanceIndices; for( testPath = subPath; !testPath.IsEmpty(); testPath = testPath.GetParent() ) { *pCurrentName = testPath.GetName(); *pCurrentIndex = testPath.GetInstanceIndex(); ++pCurrentName; ++pCurrentIndex; } ArrayCopy( pCurrentName, pRootPathNames, rootPathNameCount ); ArrayCopy( pCurrentIndex, pRootPathIndices, rootPathNameCount ); // Set the path. Set( pEntryNames, pInstanceIndices, nameCount, packageCount ); return true; } /// Set this path to the combination of two paths. /// /// @param[in] pRootPath Root portion of the path. /// @param[in] pSubPath Sub-path component. /// /// @return True if the paths could be joined into a valid path (to which this path was set), false if joining was /// invalid. bool AssetPath::Join( const char* pRootPath, const char* pSubPath ) { if( !pRootPath || pRootPath[ 0 ] == '\0' ) { return Set( pSubPath ); } if( !pSubPath || pSubPath[ 0 ] == '\0' ) { return Set( pRootPath ); } // Parse both path components into separate series of names. StackMemoryHeap<>& rStackHeap = ThreadLocalStackAllocator::GetMemoryHeap(); StackMemoryHeap<>::Marker stackMarker( rStackHeap ); Name* pRootPathNames; uint32_t* pRootPathIndices; size_t rootPathNameCount; size_t rootPathPackageCount; if( !Parse( pRootPath, rStackHeap, pRootPathNames, pRootPathIndices, rootPathNameCount, rootPathPackageCount ) ) { return false; } Name* pSubPathNames; uint32_t* pSubPathIndices; size_t subPathNameCount; size_t subPathPackageCount; if( !Parse( pSubPath, rStackHeap, pSubPathNames, pSubPathIndices, subPathNameCount, subPathPackageCount ) ) { return false; } if( rootPathNameCount != rootPathPackageCount && subPathPackageCount != 0 ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath::Join(): Cannot combine \"%s\" and \"%s\" (second path is rooted in a package, while the first path ends in an object).\n", pRootPath, pSubPath ); return false; } // Assemble the list of path names in reverse order for performing the object path lookup/add. size_t nameCount = rootPathNameCount + subPathNameCount; size_t packageCount = rootPathPackageCount + subPathPackageCount; Name* pEntryNames = static_cast< Name* >( rStackHeap.Allocate( sizeof( Name ) * nameCount ) ); HELIUM_ASSERT( pEntryNames ); ArrayCopy( pEntryNames, pSubPathNames, subPathNameCount ); ArrayCopy( pEntryNames + subPathNameCount, pRootPathNames, rootPathNameCount ); uint32_t* pInstanceIndices = static_cast< uint32_t* >( rStackHeap.Allocate( sizeof( uint32_t ) * nameCount ) ); HELIUM_ASSERT( pInstanceIndices ); ArrayCopy( pInstanceIndices, pSubPathIndices, subPathNameCount ); ArrayCopy( pInstanceIndices + subPathNameCount, pRootPathIndices, rootPathNameCount ); // Set the path. Set( pEntryNames, pInstanceIndices, nameCount, packageCount ); return true; } /// Generate the string representation of this object path. /// /// @param[out] rString String representation of this path. /// /// @see Set() void AssetPath::ToString( String& rString ) const { rString.Remove( 0, rString.GetSize() ); if( !m_pEntry ) { return; } EntryToString( *m_pEntry, rString ); } /// Generate a string representation of this object path with all package and object delimiters converted to valid /// directory delimiters for the current platform. /// /// @param[out] rString File path string representation of this path. void AssetPath::ToFilePathString( String& rString ) const { rString.Remove( 0, rString.GetSize() ); if( !m_pEntry ) { return; } EntryToFilePathString( *m_pEntry, rString ); } /// Clear out this object path. /// /// @see Set() void AssetPath::Clear() { m_pEntry = NULL; } /// Release the object path table and free all allocated memory. /// /// This should only be called immediately prior to application exit. void AssetPath::Shutdown() { HELIUM_TRACE( TraceLevels::Info, "Shutting down AssetPath table.\n" ); delete [] sm_pTable; sm_pTable = NULL; delete sm_pEntryMemoryHeap; sm_pEntryMemoryHeap = NULL; delete sm_pPendingLinksPool; sm_pPendingLinksPool = NULL; HELIUM_TRACE( TraceLevels::Info, "AssetPath table shutdown complete.\n" ); } /// Convert the path separator characters in the given object path to valid directory delimiters for the current /// platform. /// /// Note that objects with instance indices are not supported for file paths. Instance index delimiters will not be /// converted, and may be invalid file name characters on certain platforms. /// /// @param[out] rFilePath Converted file path. /// @param[in] rPackagePath Asset path string to convert (can be the same as the output file path). void AssetPath::ConvertStringToFilePath( String& rFilePath, const String& rPackagePath ) { #if HELIUM_PACKAGE_PATH_CHAR != HELIUM_PATH_SEPARATOR_CHAR && HELIUM_PACKAGE_PATH_CHAR != HELIUM_ALT_PATH_SEPARATOR_CHAR size_t pathLength = rPackagePath.GetSize(); if( &rFilePath == &rPackagePath ) { for( size_t characterIndex = 0; characterIndex < pathLength; ++characterIndex ) { char& rCharacter = rFilePath[ characterIndex ]; if( rCharacter == HELIUM_PACKAGE_PATH_CHAR || rCharacter == HELIUM_OBJECT_PATH_CHAR ) { rCharacter = Helium::s_InternalPathSeparator; } } } else { rFilePath.Remove( 0, rFilePath.GetSize() ); rFilePath.Reserve( rPackagePath.GetSize() ); for( size_t characterIndex = 0; characterIndex < pathLength; ++characterIndex ) { char character = rPackagePath[ characterIndex ]; if( character == HELIUM_PACKAGE_PATH_CHAR || character == HELIUM_OBJECT_PATH_CHAR ) { character = Helium::s_InternalPathSeparator; } rFilePath.Add( character ); } } #else rFilePath = rPackagePath; #endif } /// Set this object path based on the given parameters. /// /// @param[in] pNames Array of object names in the path, starting from the bottom level on up. /// @param[in] pInstanceIndices Array of object instance indices in the path, starting from the bottom level on up. /// @param[in] nameCount Number of object names. /// @param[in] packageCount Number of object names that are packages. void AssetPath::Set( const Name* pNames, const uint32_t* pInstanceIndices, size_t nameCount, size_t packageCount ) { HELIUM_ASSERT( pNames ); HELIUM_ASSERT( pInstanceIndices ); HELIUM_ASSERT( nameCount != 0 ); // Set up the entry for this path. Entry entry; entry.pParent = NULL; entry.name = pNames[ 0 ]; entry.instanceIndex = pInstanceIndices[ 0 ]; entry.bPackage = ( nameCount <= packageCount ); if( nameCount > 1 ) { size_t parentNameCount = nameCount - 1; AssetPath parentPath; parentPath.Set( pNames + 1, pInstanceIndices + 1, parentNameCount, Min( parentNameCount, packageCount ) ); entry.pParent = parentPath.m_pEntry; HELIUM_ASSERT( entry.pParent ); } // Look up/add the entry. m_pEntry = Add( entry ); HELIUM_ASSERT( m_pEntry ); } /// Parse a string into separate path name components. /// /// @param[in] pString String to parse. This must *not* be empty. /// @param[in] rStackHeap Stack memory heap from which to allocate the resulting name array. /// @param[out] rpNames Parsed array of names, in reverse order (top-level path name stored at the end of /// the array). Note that this will be allocated using the given heap and must be /// deallocated by the caller. /// @param[out] rpInstanceIndices Parsed array of instance indices, with each index corresponding to each name /// entry in the parsed names array. This is also allocated using the given heap and /// must be deallocated by the caller. /// @param[out] rNameCount Number of names in the parsed array. /// @param[out] rPackageCount Number of names specifying packages. /// /// @return True if the string was parsed successfully, false if not. bool AssetPath::Parse( const char* pString, StackMemoryHeap<>& rStackHeap, Name*& rpNames, uint32_t*& rpInstanceIndices, size_t& rNameCount, size_t& rPackageCount ) { HELIUM_ASSERT( pString ); HELIUM_ASSERT( pString[ 0 ] != '\0' ); rpNames = NULL; rpInstanceIndices = NULL; rNameCount = 0; rPackageCount = 0; // Make sure the entry specifies an absolute path. if( pString[ 0 ] != HELIUM_PACKAGE_PATH_CHAR && pString[ 0 ] != HELIUM_OBJECT_PATH_CHAR ) { HELIUM_TRACE( TraceLevels::Warning, "AssetPath: FilePath string \"%s\" does not contain a leading path separator.\n", pString ); return false; } // Count the number of path separators in the path. size_t nameCount = 0; size_t packageCount = 0; size_t nameLengthMax = 0; const char* pTestCharacter = pString; const char* pNameStartPos = pTestCharacter; for( ; ; ) { char character = *pTestCharacter; if( character == '\0' ) { size_t nameLength = static_cast< size_t >( pTestCharacter - pNameStartPos ); if( nameLength > nameLengthMax ) { nameLengthMax = nameLength; } break; } // Any adjacent colons (i.e. like in /Types:Helium::ConfigAsset) but being careful to not look behind beginning of pString // So it is not legal for a name to start or end with a :, but we can support fully qualified C++ types as names bool bIsObjectPathChar = (character == HELIUM_OBJECT_PATH_CHAR && pTestCharacter[1] != HELIUM_OBJECT_PATH_CHAR && (pTestCharacter == pString || pTestCharacter[-1] != HELIUM_OBJECT_PATH_CHAR)); if( character == HELIUM_PACKAGE_PATH_CHAR ) { if( packageCount != nameCount ) { HELIUM_TRACE( TraceLevels::Warning, "AssetPath: Unexpected package path separator at character %" PRIdPD " of path string \"%s\".\n", pTestCharacter - pString, pString ); return false; } ++nameCount; ++packageCount; size_t nameLength = static_cast< size_t >( pTestCharacter - pNameStartPos ); if( nameLength > nameLengthMax ) { nameLengthMax = nameLength; } pNameStartPos = pTestCharacter + 1; } else if( bIsObjectPathChar ) { ++nameCount; size_t nameLength = static_cast< size_t >( pTestCharacter - pNameStartPos ); if( nameLength > nameLengthMax ) { nameLengthMax = nameLength; } pNameStartPos = pTestCharacter + 1; } ++pTestCharacter; } HELIUM_ASSERT( nameCount != 0 ); // Parse the names from the string. rpNames = static_cast< Name* >( rStackHeap.Allocate( sizeof( Name ) * nameCount ) ); HELIUM_ASSERT( rpNames ); rpInstanceIndices = static_cast< uint32_t* >( rStackHeap.Allocate( sizeof( uint32_t ) * nameCount ) ); HELIUM_ASSERT( rpInstanceIndices ); char* pTempNameString = static_cast< char* >( rStackHeap.Allocate( sizeof( char ) * ( nameLengthMax + 1 ) ) ); HELIUM_ASSERT( pTempNameString ); char* pTempNameCharacter = pTempNameString; Name* pTargetName = &rpNames[ nameCount - 1 ]; uint32_t* pTargetIndex = &rpInstanceIndices[ nameCount - 1 ]; bool bParsingName = true; pTestCharacter = pString + 1; for( ; ; ) { char character = *pTestCharacter; // Any adjacent colons (i.e. like in /Types:Helium::ConfigAsset). Since the string begins with '/' and ends with '\0' we can just index away // So it is not legal for a name to start or end with a :, but we can support fully qualified C++ types as names bool bIsObjectPathChar = false; if (character == HELIUM_OBJECT_PATH_CHAR && pTestCharacter[1] != HELIUM_OBJECT_PATH_CHAR && pTestCharacter[-1] != HELIUM_OBJECT_PATH_CHAR) { bIsObjectPathChar = true; } if( character != HELIUM_PACKAGE_PATH_CHAR && !bIsObjectPathChar && character != '\0' ) { // Make sure the character is a valid number when parsing the instance index. if( !bParsingName && ( character < '0' || character > '9' ) ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath: Encountered non-numeric instance index value in path string \"%s\".\n", *pString ); return false; } if( bParsingName && character == HELIUM_INSTANCE_PATH_CHAR ) { // Encountered a separator for the instance index, so begin parsing it. *pTempNameCharacter = '\0'; pTargetName->Set( pTempNameString ); --pTargetName; pTempNameCharacter = pTempNameString; bParsingName = false; } else { HELIUM_ASSERT( static_cast< size_t >( pTempNameCharacter - pTempNameString ) < nameLengthMax ); *pTempNameCharacter = character; ++pTempNameCharacter; } } else { *pTempNameCharacter = '\0'; if( bParsingName ) { pTargetName->Set( pTempNameString ); --pTargetName; SetInvalid( *pTargetIndex ); --pTargetIndex; } else { if( pTempNameCharacter == pTempNameString ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath: Empty instance index encountered in path string \"%s\".\n", pString ); return false; } if( pTempNameCharacter - pTempNameString > 1 && *pTempNameString == '0' ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath: Encountered instance index \"%s\" with leading zeros in path string \"%s\".\n", pTempNameString, pString ); return false; } int parseCount = StringScan( pTempNameString, "%" SCNu32, pTargetIndex ); if( parseCount != 1 ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath: Failed to parse object instance index \"%s\" in path string \"%s\".\n", pTempNameString, pString ); return false; } if( IsInvalid( *pTargetIndex ) ) { HELIUM_TRACE( TraceLevels::Error, "AssetPath: Instance index \"%s\" in path string \"%s\" is a reserved value.\n", pTempNameString, pString ); return false; } --pTargetIndex; } if( character == '\0' ) { break; } pTempNameCharacter = pTempNameString; bParsingName = true; } ++pTestCharacter; } rNameCount = nameCount; rPackageCount = packageCount; return true; } /// Look up a table entry, adding it if it does not exist. /// /// This also handles lazy initialization of the path table and allocator. /// /// @param[in] rEntry Entry to locate or add. /// /// @return Pointer to the actual table entry. AssetPath::Entry* AssetPath::Add( const Entry& rEntry ) { // Lazily initialize the hash table. Note that this is not inherently thread-safe, but there should always be // at least one path created before any sub-threads are spawned. if( !sm_pEntryMemoryHeap ) { sm_pEntryMemoryHeap = new StackMemoryHeap<>( STACK_HEAP_BLOCK_SIZE ); HELIUM_ASSERT( sm_pEntryMemoryHeap ); sm_pPendingLinksPool = new ObjectPool<PendingLink>( PENDING_LINKS_POOL_BLOCK_SIZE ); HELIUM_ASSERT( sm_pPendingLinksPool ); HELIUM_ASSERT( !sm_pTable ); sm_pTable = new TableBucket [ TABLE_BUCKET_COUNT ]; HELIUM_ASSERT( sm_pTable ); } HELIUM_ASSERT( sm_pTable ); // Compute the entry's hash table index and retrieve the corresponding bucket. uint32_t bucketIndex = ComputeEntryStringHash( rEntry ) % TABLE_BUCKET_COUNT; TableBucket& rBucket = sm_pTable[ bucketIndex ]; // Locate the entry in the table. If it does not exist, add it. size_t entryCount = 0; Entry* pTableEntry = rBucket.Find( rEntry, entryCount ); if( !pTableEntry ) { pTableEntry = rBucket.Add( rEntry, entryCount ); HELIUM_ASSERT( pTableEntry ); } return pTableEntry; } /// Recursive function for building the string representation of an object path entry. /// /// @param[in] rEntry FilePath entry. /// @param[out] rString FilePath string. void AssetPath::EntryToString( const Entry& rEntry, String& rString ) { Entry* pParent = rEntry.pParent; if( pParent ) { EntryToString( *pParent, rString ); } rString += ( rEntry.bPackage ? HELIUM_PACKAGE_PATH_CHAR : HELIUM_OBJECT_PATH_CHAR ); rString += rEntry.name.Get(); if( IsValid( rEntry.instanceIndex ) ) { char instanceIndexString[ 16 ]; StringPrint( instanceIndexString, HELIUM_INSTANCE_PATH_CHAR_STRING "%" PRIu32, rEntry.instanceIndex ); instanceIndexString[ HELIUM_ARRAY_COUNT( instanceIndexString ) - 1 ] = '\0'; rString += instanceIndexString; } } /// Recursive function for building the file path string representation of an object path entry. /// /// @param[in] rEntry FilePath entry. /// @param[out] rString File path string. void AssetPath::EntryToFilePathString( const Entry& rEntry, String& rString ) { Entry* pParent = rEntry.pParent; if( pParent ) { EntryToFilePathString( *pParent, rString ); } rString += Helium::s_InternalPathSeparator; rString += rEntry.name.Get(); } /// Compute a hash value for an object path entry based on the contents of the name strings (slow, should only be /// used internally when a string comparison is needed). /// /// @param[in] rEntry Asset path entry. /// /// @return Hash value. size_t AssetPath::ComputeEntryStringHash( const Entry& rEntry ) { size_t hash = StringHash( rEntry.name.GetDirect() ); hash = ( ( hash * 33 ) ^ rEntry.instanceIndex ); hash = ( ( hash * 33 ) ^ ( rEntry.bPackage ? static_cast< size_t >( HELIUM_PACKAGE_PATH_CHAR ) : static_cast< size_t >( HELIUM_OBJECT_PATH_CHAR ) ) ); Entry* pParent = rEntry.pParent; if( pParent ) { size_t parentHash = ComputeEntryStringHash( *pParent ); hash = ( ( hash * 33 ) ^ parentHash ); } return hash; } /// Get whether the contents of the two given object path entries match. /// /// @param[in] rEntry0 Asset path entry. /// @param[in] rEntry1 Asset path entry. /// /// @return True if the contents match, false if not. bool AssetPath::EntryContentsMatch( const Entry& rEntry0, const Entry& rEntry1 ) { return ( rEntry0.name == rEntry1.name && rEntry0.instanceIndex == rEntry1.instanceIndex && ( rEntry0.bPackage ? rEntry1.bPackage : !rEntry1.bPackage ) && rEntry0.pParent == rEntry1.pParent ); } /// Find an existing object path entry in this table. /// /// @param[in] rEntry Externally defined entry to match. /// @param[out] rEntryCount Number of entries in this bucket when the search was performed. /// /// @return Table entry if found, null if not found. /// /// @see Add() AssetPath::Entry* AssetPath::TableBucket::Find( const Entry& rEntry, size_t& rEntryCount ) { ScopeReadLock readLock( m_lock ); Entry* const * ppTableEntries = m_entries.GetData(); size_t entryCount = m_entries.GetSize(); HELIUM_ASSERT( ppTableEntries || entryCount == 0 ); rEntryCount = entryCount; for( size_t entryIndex = 0; entryIndex < entryCount; ++entryIndex ) { Entry* pTableEntry = ppTableEntries[ entryIndex ]; HELIUM_ASSERT( pTableEntry ); if( EntryContentsMatch( rEntry, *pTableEntry ) ) { return pTableEntry; } } return NULL; } /// Add an object path entry to this table if it does not already exist. /// /// @param[in] rEntry Externally defined entry to locate or add. /// @param[in] previousEntryCount Number of entries already checked during a previous Find() call (existing entries /// are not expected to change). In other words, the entry index from which to start /// checking for any additional string entries that may have been added since the /// previous Find() call. /// /// @return Pointer to the object path table entry. /// /// @see Find() AssetPath::Entry* AssetPath::TableBucket::Add( const Entry& rEntry, size_t previousEntryCount ) { ScopeWriteLock writeLock( m_lock ); Entry* const * ppTableEntries = m_entries.GetData(); size_t entryCount = m_entries.GetSize(); HELIUM_ASSERT( ppTableEntries || entryCount == 0 ); HELIUM_ASSERT( previousEntryCount <= entryCount ); for( size_t entryIndex = previousEntryCount; entryIndex < entryCount; ++entryIndex ) { Entry* pTableEntry = ppTableEntries[ entryIndex ]; HELIUM_ASSERT( pTableEntry ); if( EntryContentsMatch( rEntry, *pTableEntry ) ) { return pTableEntry; } } HELIUM_ASSERT( sm_pEntryMemoryHeap ); Entry* pNewEntry = static_cast< Entry* >( sm_pEntryMemoryHeap->Allocate( sizeof( Entry ) ) ); HELIUM_ASSERT( pNewEntry ); new( pNewEntry ) Entry( rEntry ); m_entries.Push( pNewEntry ); return pNewEntry; }
true
841b74f876a4cd135674864db471f2098fa3630e
C++
MacroStones/MacroStonePTA
/Hello-Word/2006.cpp
UTF-8
690
3.25
3
[]
no_license
//2006 //Problem Description //给你n个整数,求他们中所有奇数的乘积。 //Input //输入数据包含多个测试实例,每个测试实例占一行,每行的第一个数为n,表示本组数据一共有n个,接着是n个整数,你可以假设每组数据必定至少存在一个奇数。 //Output //输出每组数中的所有奇数的乘积,对于测试实例,输出一行。 #include<stdio.h> int main() { int product; int n,tmp; while(scanf("%d",&n)==1) { product=1; while(n-->0) { scanf("%d",&tmp); if(tmp%2==1) { product*=tmp; } } printf("%d\n",product); } return 0; }
true
b5de35a049c6ea8c5396e8c412f71d32835209fc
C++
Luminarys/acsl
/acsl/array.hh
UTF-8
1,219
3.375
3
[]
no_license
// // Templated safe array class. // #ifndef ACSL_ARRAY_HH #define ACSL_ARRAY_HH #include "maybe.hh" #include "types.hh" #include "utility.hh" #include <initializer_list> namespace acsl { template<typename T, usize N> class Array { static_assert(N > 0, "Array must be of size 1 or more"); T buffer_[N]; public: Array(std::initializer_list<T> l) { int i = 0; for (T e : l) { buffer_[i++] = std::move(e); } } T& operator[](usize i) { if (i >= N) { panic("Out of bounds array access!"); } return buffer_[i]; } T const& operator[](usize i) const { if (i >= N) { panic("Out of bounds array access!"); } return buffer_[i]; } template<usize I> T &at() { static_assert(I < N, "Cannot access array element at invalid index"); return buffer_[I]; } template<usize I> T const &at() const { static_assert(I < N, "Cannot access array element at invalid index"); return buffer_[I]; } T &front() { return this->at<0>(); } T const &front() const { return this->at<0>(); } T &back() { return this->at<N - 1>(); } T const &back() const { return this->at<N - 1>(); } }; } #endif //ACSL_ARRAY_HH
true
17d214e950a1f7bf74f6a8f4c8a4ec676119e9d6
C++
LexxaPressF/Programing_C
/Lab12C++/SchoolCpp/SchoolCpp/SchoolCpp.cpp
UTF-8
1,051
2.875
3
[]
no_license
#include <iostream> #include "human.h" #include "Student.h" #include <string> #include <vector> #include <Windows.h> #include "teacher.h" using namespace std; int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); human id1("Leonidovich", "Pavel", "Efimov"); cout << "ФИО человека: " << id1.get_full_name() << endl; vector <int> scores; scores.push_back(5); scores.push_back(3); scores.push_back(4); scores.push_back(4); scores.push_back(5); scores.push_back(3); scores.push_back(3); scores.push_back(3); Student id2("Andreevich", "Aleksey", "Malyshev", scores); cout << "ФИО студента: " << id2.get_full_name() << endl; cout << "Средний балл студента: " << id2.get_average_score() << endl; unsigned int teacher_work_time = 40; teacher* tch = new teacher("Сергеев", "Дмитрий", "Сергеевич",teacher_work_time); std::cout << tch->get_full_name() << std::endl; std::cout << "Количество часов: " << tch->get_work_time() <<std::endl; return 0; }
true
a010261aa3fafc1b34fa9dd0d9d680400d1be262
C++
LearningAchievements-masdevas/RungeKutta4
/RungeKuttaGraphic/Tokenizer.cpp
UTF-8
1,895
3.078125
3
[]
no_license
#include "Tokenizer.h" void SkipSpaces(std::stringstream& stream) { while (stream.peek() != EOF && std::isspace(stream.peek())) { stream.get(); } } Tokens ParseToTokens(const std::string& data, const std::unordered_map<std::string, double>& variables) { Tokens tokens; std::stringstream buffer(data); bool may_unary = true; while (buffer.peek() != EOF) { SkipSpaces(buffer); if (buffer.peek() == EOF) { break; } std::stringstream current_token; MyTokenType token_type; if (std::isdigit(buffer.peek())) { token_type = MyTokenType::NUMBER; while (buffer.peek() != EOF && (std::isdigit(buffer.peek()) || buffer.peek() == ',' || buffer.peek() == '.')) { current_token << static_cast<char>(buffer.get()); } may_unary = false; } else if (std::isalpha(buffer.peek())) { token_type = MyTokenType::VARIABLE; while (buffer.peek() != EOF && std::isalpha(buffer.peek())) { current_token << static_cast<char>(buffer.get()); } may_unary = false; if (variables.find(current_token.str()) == variables.end()) { throw std::runtime_error("Error while tokenizing"); } } else if (buffer.peek() == '(') { token_type = MyTokenType::OPEN_BRACKET; current_token << static_cast<char>(buffer.get()); may_unary = true; } else if (buffer.peek() == ')') { token_type = MyTokenType::CLOSE_BRACKET; current_token << static_cast<char>(buffer.get()); may_unary = false; } else if (!may_unary) { token_type = MyTokenType::OPERATION; current_token << static_cast<char>(buffer.get()); may_unary = true; } else if (may_unary) { token_type = MyTokenType::UNARY_OPERATION; current_token << static_cast<char>(buffer.get()); may_unary = false; } if (current_token.peek() != EOF) { tokens.emplace_back(current_token.str(), token_type); } } return tokens; }
true
a6ddfe2f91e83ce9b2b9e8e77d50264e6d585d33
C++
AhJo53589/leetcode-cn
/problems_test/17.13-lcci/SOLUTION.cpp
UTF-8
1,223
2.8125
3
[]
no_license
////////////////////////////////////////////////////////////////////////// class Solution { public: int respace(vector<string>& dictionary, string sentence) { vector<int> dp(sentence.size() + 1, 0); for (int i = 0; i < sentence.size(); i++) { dp[i + 1] = (i == 0) ? i + 1 : min(i + 1, dp[i] + 1); for (auto& w : dictionary) { if (i + 1 < w.size()) continue; if (memcmp(&sentence[i + 1 - w.size()], &w[0], w.size()) == 0) { dp[i + 1] = min(dp[i + 1], dp[i + 1 - w.size()]); } } } return dp.back(); } }; ////////////////////////////////////////////////////////////////////////// int _solution_run(vector<string>& dictionary, string sentence) { //int caseNo = -1; //static int caseCnt = 0; //if (caseNo != -1 && caseCnt++ != caseNo) return {}; Solution sln; return sln.respace(dictionary, sentence); } //#define USE_SOLUTION_CUSTOM //string _solution_custom(TestCases &tc) //{ // return {}; //} ////////////////////////////////////////////////////////////////////////// //#define USE_GET_TEST_CASES_IN_CPP //vector<string> _get_test_cases_string() //{ // return {}; //}
true
1ab1a868edfee021812b018e88ea5fddd7f07292
C++
valleyceo/code_journal
/1. Problems/f. Trees/2_Top_K_Frequent_Elements.cpp
UTF-8
1,096
3.359375
3
[]
no_license
// Top K Frequent Elements /* Given a non-empty array of integers, return the k most frequent elements. For example, Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. */ // my solution //https://leetcode.com/problems/top-k-frequent-elements/discuss/81760/Five-efficient-solutions-in-C++-well-explained class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> umap; vector<int> v; for (int n : nums) { umap[n]++; } vector<vector<int>> buckets(nums.size() + 1); for (auto& pair: umap) buckets[pair.second].push_back(pair.first); for (int i = nums.size(); i; --i) { for (int j = 0; j < buckets[i].size(); ++j) { v.push_back(buckets[i][j]); if (v.size() == k) return v; } } return v; } };
true
696923513c395558c20b46f208b4d0c31ca27cf5
C++
fapablazacl-old/xe.old
/src/xe/xe/io/IosStream.cpp
UTF-8
2,900
2.9375
3
[]
no_license
#include "IosStream.hpp" #include <cassert> #include <fstream> #include <iostream> namespace xe { struct IosStream::Private { mutable std::istream *stdStream = nullptr; }; IosStream::IosStream(std::istream *stdStream) : m_impl(new IosStream::Private()) { assert(m_impl); assert(stdStream); m_impl->stdStream = stdStream; } IosStream::~IosStream() { assert(m_impl); delete m_impl; } bool IosStream::isReadable() const { assert(m_impl); assert(m_impl->stdStream); return true; } int IosStream::read(void *bufferOut, const int size, const int count) { std::cout << "xe::IosStream::read: size=" << size << ", count=" << count << std::endl; assert(m_impl); assert(m_impl->stdStream); assert(bufferOut); assert(size >= 0); assert(count >= 0); auto ios = m_impl->stdStream; if (size == 1) { ios->read((char*) bufferOut, size * count); return (int)ios->gcount(); } else { // emulate C's fread. for (int i=0; i<count; i++) { ios->read((char*)bufferOut, size); const auto readed = ios->gcount(); if (readed < size) { std::cout << "xe::IosStream::read: Unsuccessful read: readed=" << readed << std::endl; //ios->seekg(-readed, std::ios_base::cur); return i; } } return count; } } bool IosStream::seek(const int offset, const StreamOffset position) { std::cout << "xe::IosStream::seek: offset=" << offset << ", count=" << (int)position << std::endl; assert(m_impl); assert(m_impl->stdStream); switch (position) { case StreamOffset::Current: m_impl->stdStream->seekg(offset, std::ios_base::cur); break; case StreamOffset::Set: assert(offset >= 0); m_impl->stdStream->seekg(offset, std::ios_base::beg); break; case StreamOffset::End: assert(offset == 0); m_impl->stdStream->seekg(offset, std::ios_base::end); break; default: assert(false); } return true; } int IosStream::tell() const { std::cout << "xe::IosStream::tell: " << m_impl->stdStream->tellg() << std::endl; assert(m_impl); assert(m_impl->stdStream); assert(m_impl->stdStream->tellg() >= 0); return static_cast<int>(m_impl->stdStream->tellg()); } }
true
1ac1eb3632f26ca2f7af71bfb9876321b4ab1fff
C++
Genixi/Cpp_yellow
/decomposition_2/responses.cpp
UTF-8
1,148
3.015625
3
[]
no_license
#include <string> #include <iostream> #include <vector> #include <map> using namespace std; #include "responses.h" ostream& operator << (ostream& os, const BusesForStopResponse& r) { if (r.buses_count == 0) { os << "No stop" << endl; } else { for (const string& bus : r.buses) { os << bus << " "; } os << endl; } return os; } ostream& operator << (ostream& os, const StopsForBusResponse& r) { if (r.stops_count == 0) { os << "No bus" << endl; } else { for (const auto& stop_bus : r.stops_buses) { os << "Stop " << stop_bus.first << ": "; if (stop_bus.second.size() == 1) { os << "no interchange"; } else { for (const auto& other_bus : stop_bus.second) { if (other_bus != r.bus) { os << other_bus << " "; } } } os << endl; } } return os; } ostream& operator << (ostream& os, const AllBusesResponse& r) { if (r.buses_count == 0) { os << "No buses" << endl; } else { for (const auto& bus_item : r.buses_to_stops) { os << "Bus " << bus_item.first << ": "; for (const string& stop : bus_item.second) { os << stop << " "; } os << endl; } } return os; }
true
844bfb9d3e5444df78a0b2da18bd26c54a102550
C++
Joe-Feng/PAT
/A1025 PAT Rianking/main.cpp
GB18030
1,892
3.6875
4
[]
no_license
/* 1 ˼ṹӦü¼ʲôֵ 2 sortʹ 3 ִ 4 СӦΪ */ #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; struct student { char id[15]; int score; int location_num; int location_rank; }stu[30010]; //Ŀгn<=100, ÿ<=300, С>=30000,UI δ bool cmp(student a, student b) { if(a.score != b.score) return a.score > b.score; else return strcmp(a.id, b.id) < 0; } int main() { int n, k, num = 0; scanf("%d", &n);//nΪ for(int i=1; i<=n; i++) { scanf("%d", &k); //kΪ for(int j=0; j<k; j++) {//ÿϢһб棬±Ϊnum scanf("%s %d", stu[num].id, &stu[num].score ); stu[num].location_num = i; num++; } sort(stu + num - k, stu + num, cmp); //stu+num-kʾһstu+numʾһ˵ĺһ //һδ洢 stu[num - k].location_rank = 1; //һΪһ for(int j=num - k + 1; j<num; j++) { if(stu[j].score == stu[j-1].score) stu[j].location_rank = stu[j-1].location_rank; else stu[j].location_rank = j - (num - k) + 1;//num-kʾǰж } } printf("%d\n", num); sort(stu, stu + num, cmp); //ĵڶִ洢Σֱ int r = 1; for(int i=0; i<num; i++) { if(i>0 && stu[i].score != stu[i-1].score) r = i + 1; //+1 printf("%s ", stu[i].id); printf("%d %d %d\n", r, stu[i].location_num, stu[i].location_rank); } return 0; }
true
8ddf557abc95b94a6464a29eedb368f9715efbd8
C++
fsps60312/old-C-code
/C++ code/Polish Olympiad in Informatics/XX OI/Maze(3).cpp
UTF-8
4,757
2.859375
3
[]
no_license
#include<cstdio> #include<cassert> #include<vector> #include<algorithm> #include<deque> #include<set> using namespace std; const int INF=2147483647; void getmin(int &a,const int b){if(b<a)a=b;} void getmax(int &a,const int b){if(b>a)a=b;} struct Point { int x,y; Point(){} Point(const int _x,const int _y):x(_x),y(_y){} Point Move(const int dx,const int dy)const{return Point(x+dx,y+dy);} bool operator==(const Point &p)const{return x==p.x&&y==p.y;} }; struct ManyPoints { Point UL,DR; int D1,D2; deque<Point>ps; ManyPoints(const Point &p,const int _d1,const int _d2):UL(p.Move(-1,-1)),DR(p.Move(1,1)),D1(((_d1+2)%4+4)%4),D2((_d2%4+4)%4){ps.push_back(p);} // ManyPoints(const int _d1,const int _d2):UL(Point(INF,INF)),DR(Point(-INF,-INF)),D1(((_d1+2)%4+4)%4),D2((_d2%4+4)%4){} void Move(const int dx,const int dy) { UL=UL.Move(dx,dy),DR=DR.Move(dx,dy); for(int i=0;i<(int)ps.size();i++)ps[i]=ps[i].Move(dx,dy); } Point Reflection(const Point &p,const int d)const { switch(d) { case 0:return Point(p.x,UL.y); case 1:return Point(DR.x,p.y); case 2:return Point(p.x,DR.y); case 3:return Point(UL.x,p.y); default:assert(0);return Point(-1,-1); } } Point Entry()const{return Reflection(ps.front(),D1);} Point Exit()const{return Reflection(ps.back(),D2);} int SpanX()const{return abs(Entry().x-Exit().x);} int SpanY()const{return abs(Entry().y-Exit().y);} }; ManyPoints* Merge(ManyPoints *a,ManyPoints *b) { // swap(a,b); // printf("%d %d\n",a->D2,b->D1); assert(abs(a->D2-b->D1)==2); const Point pa=a->Exit(),pb=b->Entry(); if(a->ps.size()<b->ps.size()) { a->Move(pb.x-pa.x,pb.y-pa.y); assert(a->Exit()==b->Entry()); getmin(b->UL.x,a->UL.x),getmin(b->UL.y,a->UL.y); getmax(b->DR.x,a->DR.x),getmax(b->DR.y,a->DR.y); for(int i=(int)a->ps.size()-1;i>=0;i--)b->ps.push_front(a->ps[i]); b->D1=a->D1; delete a; return b; } else { b->Move(pa.x-pb.x,pa.y-pb.y); assert(a->Exit()==b->Entry()); getmin(a->UL.x,b->UL.x),getmin(a->UL.y,b->UL.y); getmax(a->DR.x,b->DR.x),getmax(a->DR.y,b->DR.y); for(int i=0;i<(int)b->ps.size();i++)a->ps.push_back(b->ps[i]); a->D2=b->D2; delete b; return a; } } int N,D[100001]; set<int>LOCS[200001]; struct QdTree { int begin,end; QdTree *chs[3]; vector<int>nodes; QdTree(const int _begin,const int _end):begin(_begin),end(_end) { if(end-begin==1)return; vector<int>&s=nodes; s.push_back(begin); s.push_back(begin+1); if(D[begin+1]==D[end])s.push_back(begin+2); else s.push_back(*LOCS[N+(D[begin+1]+D[end])/2].upper_bound(begin+1)); s.push_back(end); assert((int)s.size()==4); for(int i=0;i<3;i++)chs[i]=new QdTree(s[i],s[i+1]); } ManyPoints *Build() { // printf("(%d,%d)(%d,%d)\n",begin,end,D[begin],D[end]); if(end-begin==1)return new ManyPoints(Point(0,0),D[begin],D[end]); ManyPoints *s[3]; for(int i=0;i<3;i++) { s[i]=chs[i]->Build(); delete chs[i]; } ManyPoints *ans; if(D[nodes[1]]-D[nodes[0]]==D[nodes[2]]-D[nodes[1]]) { ans=s[2]; ans=Merge(s[1],ans); ans=Merge(s[0],ans); } else { ans=s[0]; ans=Merge(ans,s[1]); ans=Merge(ans,s[2]); } return ans; } }; char S[100001]; void Solve() { D[0]=0; for(int i=0;i<N;i++) { if(S[i]=='P')D[i+1]=D[i]+1; else if(S[i]=='L')D[i+1]=D[i]-1; else assert(0); } bool flipped=false; if(D[N]==-4) { for(int i=0;i<N;i++)S[i]=(S[i]=='P'?'L':'P'); for(int i=0;i<=N;i++)D[i]*=-1; flipped=true; } else//if(D[N]!=4) { puts("NIE"); return; } for(int i=0;i<=N*2;i++)LOCS[i].clear(); for(int i=0;i<=N;i++)LOCS[N+D[i]].insert(i); QdTree **trees=new QdTree*[4]; int pre=0,cur=0; for(int d=1;d<4;d++) { while(D[cur]!=d)cur++; assert(cur<N); trees[d-1]=new QdTree(pre,cur); pre=cur; } trees[3]=new QdTree(pre,N); ManyPoints **s=new ManyPoints*[4]; for(int i=0;i<4;i++) { s[i]=trees[i]->Build(); delete trees[i]; } delete[]trees; int xmx=-INF,ymx=-INF; for(int i=0;i<4;i++)getmax(xmx,s[i]->SpanX()),getmax(ymx,s[i]->SpanY()); s[0]->Move(-xmx-s[0]->Entry().x,-ymx-s[0]->Exit().y ); s[1]->Move( xmx-s[1]->Exit().x ,-ymx-s[1]->Entry().y); s[2]->Move( xmx-s[2]->Entry().x, ymx-s[2]->Exit().y ); s[3]->Move(-xmx-s[3]->Exit().x , ymx-s[3]->Entry().y); vector<Point>ans; for(int i=0;i<4;i++) { for(int j=0;j<(int)s[i]->ps.size();j++)ans.push_back(s[i]->ps[j]); // printf("(%d,%d)(%d,%d)\n",s[i]->Entry().x,s[i]->Entry().y,s[i]->Exit().x,s[i]->Exit().y); delete s[i]; } delete[]s; assert((int)ans.size()==N); for(int i=0;i<N;i++)ans[i].y*=-1; if(flipped)for(int i=0;i<N;i++)ans[i].x*=-1; else reverse(ans.begin(),ans.end()); for(int i=0;i<N;i++)printf("%d %d\n",ans[i].x,ans[i].y); } int main() { // freopen("in.txt","r",stdin); scanf("%s",S);N=-1;while(S[++N]); Solve(); return 0; }
true
6382ba2c2033dfb26bb80a967a15bc984f925604
C++
kottofy/CPlusPlus-Projects
/Assignment 2-Rot13/a2-g++/main.cpp
UTF-8
581
3.0625
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; void rot13(char *str); int main(int argc, char ** argv ) { char buf[4096]; int i; if (argc < 2 ) { printf("Usage: %s e (for encode) or %s d (for decode) \n", argv[0], argv[0]); exit(-1); } i=0; while (cin.get(buf[i]) && i<4095) { i++; if (cin.fail()) break; } buf[i]=0; switch (argv[1][0]) { case 'e': case 'd': rot13(buf); cout << buf; break; default: printf("Usage: %s e (for encode) or %s d (for decode) \n", argv[0], argv[0]); } }
true
8b169745d4c75abeb8448db9ae4c13a560840b6d
C++
Zwlin98/Learn_ACM
/1143.cpp
UTF-8
317
3.140625
3
[]
no_license
#include <stdio.h> void move(char f ,char t) { printf("%c->%c\n",f,t); } void hanota(int n,char from,char depend,char to) { if(n==1) move(from,to); else { hanota(n-1,from,to,depend); move(from,to); hanota(n-1,depend,from,to); } } int main() { int n; scanf("%d",&n); hanota(n,'a','b','c'); return 0; }
true
24942c7fc0973b2df4a817de3b6546b0d2c247ca
C++
8BitSec/DS_practicals
/ds_10.cpp
UTF-8
7,072
4.21875
4
[]
no_license
/* Q. Implementation of Linked list using templates. Include functions for insertion, deletion and search of a number, reverse the list and concatenate two linked lists(include a function and also overload operator +). */ #include<iostream> using namespace std; //NODE CLASS template <class t> class Node { public: t info; Node *next; Node(t data) { info = data; next = NULL; } };//NODE CLASS //LIST CLASS template <class T> class SLList { Node <T> *head, *tail ; public : SLList() { head = tail = NULL ; } //operations on list void add_at_head(T data) { if( head == NULL ) head = tail = new Node<T>(data); else { Node <T> *p = new Node<T>(data); p->next = head; head = p; } }//add_at_head() void add_at_tail(T data) { if( tail == NULL ) head = tail = new Node<T>(data); else { Node <T> *p = new Node<T>(data); tail = tail->next = p; } }//add_at_tail() bool traverse() { if( head == NULL ) return false; else { std::cout << "\nThe present list is :\t"; Node <T> *p = head; while( p != NULL ) { std::cout << p->info << ' '; p = p->next; } return true; } }//traverse() int search(T element) { if( head == NULL ) return -2; Node <T> *p = head; while( p!= NULL && p->info!=element ) p = p->next; return ( p == NULL )? -1 : 0 ; }//search() int count_nodes() { if( head == NULL ) return 0; int count = 0; Node <T> *p =head; while( p!=NULL && count++ ) p = p->next; return count; }//count_nodes() bool delete_from_head() { if( head == NULL ) return false; else if( head == tail ) { delete(head); head = tail = NULL; return true; } else { Node <T> *p =head; head = head->next; delete(p); return true; } }//delete_from_head() bool delete_from_tail() { if( tail == NULL ) return false; else if( head == tail ) { delete(head); head = tail = NULL; return true; } else { Node <T> *p = head; while( p->next->next != NULL ) p = p->next; tail = p; p = p->next; tail->next = NULL; delete(p); return true; } }//delete_from_tail() void reverse() { IntSLLNode<t> *temp1 = head; IntSLLNode<t> *temp2 = NULL; IntSLLNode<t> *next = NULL; while(temp1!=NULL) { next = temp1->next; temp1->next = temp2; temp2 = temp1; temp1 = next; } head = temp2; traverse(); } };//LIST CLASS //function to print input errors void printerror(string str="\nInvalid input, enter again :") { cin.clear(); cin.ignore(100,'\n'); cout << str ; } template <class T> void operations() { SLList <T> list; int choice; T data; while(1){ cout << "\nOperations available are :\n"; cout << "\t1. Add new element at Head\n"; cout << "\t2. Add new element at Tail\n"; cout << "\t3. Print the list\n"; cout << "\t4. Search the list for presence of an element\n"; cout << "\t5. Print the number of elements in list\n"; cout << "\t6. Delete an element from head\n"; cout << "\t7. Delete an element from tail\n"; cout << "\t8. Reverse the list\n"; cout << "\t9. EXIT"; cout << "\nEnter your choice :"; while( !(cin>>choice) || choice<=0 || choice>9 ) printerror("Invalid choice, enter again :"); switch(choice) { case 1: cout << "\nEnter the data :"; while( !(cin>>data) ) printerror("Not a valid data for your list, enter again :"); list.add_at_head(data); cout << "\nDone!\n"; break; case 2: cout << "\nEnter the data :"; while( !(cin>>data) ) printerror("Not a valid data for your list, enter again :"); list.add_at_tail(data); cout << "\nDone!\n"; break; case 3: if( list.traverse() ); else cout << "\nThe list is Empty!"; break; case 4: T element; cout << "\nEnter the element to search for :"; while( !(cin>>element) ) printerror("Invalid element, enter again :"); int stat; stat = list.search(element); if( stat == -2 ) cout << "\nSearch failed, list is empty!\n"; else { cout << "\nThe element " << element << " is "; if( stat == -1 ) cout << "NOT "; cout << "present in the list.\n"; } break; case 5: cout << "\nThere are " << list.count_nodes() << " nodes in the list.\n"; break; case 6: if( list.delete_from_head() ) cout << "\nSuccessfull!\n"; else cout << "\nFailed, list is empty!\n"; break; case 7: if( list.delete_from_tail() ) cout << "\nSuccessfull!"; else cout << "\nFailed, list is empty!"; break; case 8: if( list.reverse_list() ) { cout << "\nAfter reversing: "; list.traverse(); } else { cout << "\n[!] Current list empty.\n"; } break; case 9: return; }//switch(choice) cout << "\nPress ENTER to continue ..."; cin.ignore(100,'\n'); char ch = getchar(); }//while(1) return; }//operations() int main() { int type; char ch; cout << "\n\t\t<--- SINGLE LINKED LISTS --->\n"; do{ cout << "\nAvailable list types are :-"; cout << "\n\t1. Linked list of Integers"; cout << "\n\t2. Linked list of Characters"; cout << "\n\t3. Linked list of Floats"; cout << "\n\nEnter your choice :"; while( !(cin>>type) || type <= 0 || type>3 ) printerror("Invalid choice, enter again :"); if( type == 1) operations <int> (); else if( type == 2) operations <char>(); else operations <float>(); cout << "\n\nTry another type of linked list? (y/n) :"; while( !(cin>>ch) || ( tolower(ch)!='y' && tolower(ch)!='n' ) ) printerror("Please enter only 'y' or 'n' :"); }while( tolower(ch) == 'y' ); //do-while return 0; }//main()
true
34be5646a5b99e4c3c5a36c0b1cd0820bf7f5240
C++
yyt12345/Leetcode
/链表/021.cpp
UTF-8
1,979
3.90625
4
[]
no_license
/* 21. 合并两个有序链表 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 */ #include <string> #include <vector> #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; //20 ms 13.02% 7.2 MB 100.00% 时间复杂度 O(m+n) ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // if(l1==nullptr && l2==nullptr) return NULL; // else if(l1==nullptr) return l2; // else if (l2==nullptr) return l1; ListNode* preHead = new ListNode(-1); // if(l1->val <= l2->val) head=l1; // else head=l2; ListNode* t=preHead; while(l1!=nullptr && l2!=nullptr){ if(l1->val <= l2->val){ t->next=l1; l1=l1->next; }else{ t->next=l2; l2=l2->next; } t=t->next; } t->next= l1 == nullptr ? l2 : l1; return preHead->next; } //使用递归法 20 ms 13.02% 7.1 MB 100.00% ListNode* mergeTwoLists2(ListNode* l1, ListNode* l2) { if(l1==nullptr) return l2; else if(l2==nullptr) return l1; else if(l1->val < l2->val){ l1->next=mergeTwoLists(l1->next,l2); return l1; }else{ l2->next=mergeTwoLists(l1,l2->next); return l2; } } int main(){ ListNode* l1=(ListNode*)malloc(sizeof(ListNode)); ListNode* temp; temp=l1; temp->val=1; temp->next=NULL; ListNode t2(2); temp->next=&t2; temp=temp->next; ListNode t3(4); temp->next=&t3; ListNode* l2=(ListNode*)malloc(sizeof(ListNode)); temp=l2; temp->val=1; temp->next=NULL; ListNode t4(3); temp->next=&t4; temp=temp->next; ListNode t5(4); temp->next=&t5; ListNode* head=mergeTwoLists(l1,l2); temp=head; while(temp->next!=NULL){ cout << temp->val << " "; temp=temp->next; } cout << temp->val; }
true
448b3926b97c64fca76503a49276fc3bf9bfb21a
C++
anita-sharma/cpp
/binary_tree_problem/bfs.cpp
UTF-8
994
3.703125
4
[]
no_license
#include<iostream> #include<queue> using namespace std; struct node{ int data; struct node* left; struct node* right; }; struct node* newnode(int data) { struct node* temp=(struct node*)malloc(sizeof(struct node)); temp->data=data; temp->left=NULL; temp->right=NULL; return(temp); } //func to print tree data in level order void bfs(struct node* root) { queue<struct node*> q1; if(root==NULL) return; q1.push(root); while(!q1.empty()) { struct node* temp=q1.front(); q1.pop(); cout<<temp->data<<" "; if(temp->left!=NULL) q1.push(temp->left); if(temp->right!=NULL) { q1.push(temp->right); } } } int main(){ struct node* root=newnode(1); root->left=newnode(2); root->right=newnode(3); root->left->left=newnode(4); root->left->right=newnode(5); root->right->left=newnode(6); root->right->right=newnode(7); root->right->left->right=newnode(13); root->right->right->left=newnode(14); //inorder(root); bfs(root); cout<<endl; return(0); }
true
319e10f28515a3dbba96c531a9653e3e65a21f4c
C++
KCCTdensan/Procon30th-KCCT
/Solver/engine_loader.cpp
SHIFT_JIS
1,037
2.828125
3
[]
no_license
#include "engine_loader.hpp" namespace solver { EngineLoader::EngineLoader(const std::wstring &engineName) { const std::wstring dllPath = engineName + L".dll"; moduleHandle = LoadLibrary(engineName.c_str()); if(moduleHandle == NULL) { throw L"EngineManager : DLL̓ǂݍ݂Ɏs܂"; } creator = reinterpret_cast<creator_t>(GetProcAddress(moduleHandle, "createEngine")); if(creator == NULL) { FreeLibrary(moduleHandle); throw L"EngineManager : CX^X֐̎擾Ɏs܂"; } destroyer = reinterpret_cast<destroyer_t>(GetProcAddress(moduleHandle, "destroyEngine")); if(destroyer == NULL) { FreeLibrary(moduleHandle); throw L"EngineManager : CX^Xj֐̎擾Ɏs܂"; } } EngineLoader::~EngineLoader() { FreeLibrary(moduleHandle); } engine::Interface *EngineLoader::createEngine() { return creator(); } void EngineLoader::destroyEngine(engine::Interface *engine) { destroyer(engine); } }
true
e9a3e3d3745c05eb61024d660386755ac0876ab8
C++
walterar/pioneer-sp
/src/ui/Widget.h
UTF-8
17,499
2.640625
3
[]
no_license
// Copyright © 2008-2016 Pioneer Developers. See AUTHORS.txt for details // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt #ifndef UI_WIDGET_H #define UI_WIDGET_H #include "libs.h" #include "Point.h" #include "Event.h" #include "RefCounted.h" #include "WidgetSet.h" #include "PropertiedObject.h" #include <climits> #include <set> // Widget is the base class for all UI elements. There's a couple of things it // must implement, and a few more it might want to implement if it wants to do // something fancy. // // At minimum, a widget must implement Draw(). // // - Draw() actually draws the widget, using regular renderer calls. The // renderer state will be set such that the widget's top-left corner is at // [0,0] with a scissor region to prevent drawing outside of the widget's // allocated space. // // Widgets can implement PreferredSize(), Layout() and Draw() to do more // advanced things. // // - PreferredSize() returns a Point that tells the layout manager the ideal // size the widget would like to receive to do its job. The container is // under absolutely no obligation to allocate that amount of space to the // widget, and the widget should be prepared for that. In the worst case the // widget will not handle this and will draw something that either doesn't // use enough of its allocated space or uses too much and gets clipped. // // - Layout() is called to tell a container widget (or a widget that does not // intend to use its entire allocated area) to ask its children for their // preferred size, position and size them according to its layout strategy, // and then ask them to lay out their children. As such, when Layout is called // a widget can assume that its size and position have been set. It is only // called occassionally when the layout becomes invalid, typically after a // widget is added or removed. See Container.h for more information about // implementing a container. Widgets that aren't containers but don't intend // to use their entire allocation should implement Layout() and call // SetActiveArea() from it. // // - Update() is called every frame before Draw(). The widget may get its // allocated size by calling GetSize() and can do any preparation for the // actual draw at this point. // // Each frame a widget will receive calls in the following order: // // - event handlers (user input) // - Layout() (if layout needs recalculating) // - event handlers (from layout changes) // - Update() // - Draw() // // Input is fed into the context's event dispatcher and used to generate the // various events in the Widget class. A widget must connect to any event // signals that it is interested in. External users may also connect to // signals to do things (eg register button click handlers). // // Event handlers for events generated from user input are called before // Layout(). Layout() may also generate events (such as mouse over/out events) // as widgets move. // // Event handlers from user input are called before Layout(), which gives a // widget an opportunity to modify the layout based on input. If a widget // wants to change its size it must call GetContext()->RequestLayout() to // force a layout change to occur. // // Event handlers are called against the "leaf" widgets first. Handlers return // a bool to indicate if the event was "handled" or not. If a widget has no // handlers for the event, or they all return false, then handlers for the // widget's container are called, and so on until either a handler returns // true or the root widget (context) is reached. Note that no guarantees are // made about the order that multiple handlers attached to a single widget // event will be called, so attaching more than one handler to an individual // widget event is highly discouraged. namespace UI { class Context; class Container; class Layer; class Widget : public RefCounted { protected: // can't instantiate a base widget directly Widget(Context *context); public: virtual ~Widget(); virtual Point PreferredSize() { return Point(); } virtual void Layout() {} virtual void Update() {} virtual void Draw() = 0; // gui context Context *GetContext() const { return m_context; } // enclosing container Container *GetContainer() const { return m_container; } // size allocated to widget by container const Point &GetSize() const { return m_size; } // position relative to container const Point &GetPosition() const { return m_position; } // position relative to top container Point GetAbsolutePosition() const; // size control flags let a widget tell its container how it wants to be // sized when it can't get its preferred size Uint32 GetSizeControlFlags() const { return m_sizeControlFlags; } enum SizeControl { // <enum scope='UI::Widget' name=UISizeControl public> NO_WIDTH = 0x01, // do not contribute preferred width to the layout NO_HEIGHT = 0x02, // do not contribute preferred height to the layout EXPAND_WIDTH = 0x04, // ignore preferred width, give me as much as possible EXPAND_HEIGHT = 0x08, // ignore preferred height, give me as much as possible PRESERVE_ASPECT = 0x10, // allocate same aspect ratio as preferred size }; // draw offset. used to move a widget "under" its visible area (scissor) void SetDrawOffset(const Point &drawOffset) { m_drawOffset = drawOffset; } const Point &GetDrawOffset() const { return m_drawOffset; } // active area of the widget. the widget may only want to use part of its // allocated space. drawing will be clipped to the active area, and events // that fall outside of the active area will be ignored. if a widget // doesn't set its active area it defaults to its allocated space. const Point &GetActiveOffset() const { return m_activeOffset; } const Point &GetActiveArea() const { return m_activeArea; } // determine if a point is inside a widgets active area bool Contains(const Point &point) const { const Point min_corner = (m_activeOffset - m_drawOffset); const Point max_corner = (min_corner + m_activeArea); return (point.x >= min_corner.x && point.y >= min_corner.y && point.x < max_corner.x && point.y < max_corner.y); } // calculate layout contribution based on preferred size and flags Point CalcLayoutContribution(); // calculate size based on available space, preferred size and flags Point CalcSize(const Point &avail); // fast way to determine if the widget is a container virtual bool IsContainer() const { return false; } // selectable widgets may receive keyboard focus virtual bool IsSelectable() const { return false; } // disabled widgets do not receive input virtual void Disable(); virtual void Enable(); virtual void Hidden(); bool IsDisabled() const { return m_disabled; } bool IsHidden() const { return m_hidden; } bool IsMouseOver() const { return m_mouseOver; } bool IsOnTopLayer() const; // register a key that, when pressed and not handled by any other widget, // will cause a click event to be sent to this widget void AddShortcut(const KeySym &keysym) { m_shortcuts.insert(keysym); } void RemoveShortcut(const KeySym &keysym) { m_shortcuts.erase(keysym); } // font size. obviously used for text size but also sometimes used for // general widget size (eg space size). might do nothing, depends on the // widget enum Font { // <enum scope='UI::Widget' name=UIFont prefix=FONT_ public> FONT_XSMALL, FONT_SMALL, FONT_NORMAL, FONT_LARGE, FONT_XLARGE, FONT_HEADING_XSMALL, FONT_HEADING_SMALL, FONT_HEADING_NORMAL, FONT_HEADING_LARGE, FONT_HEADING_XLARGE, FONT_MONO_XSMALL, FONT_MONO_SMALL, FONT_MONO_NORMAL, FONT_MONO_LARGE, FONT_MONO_XLARGE, FONT_MAX, // <enum skip> FONT_INHERIT, FONT_SMALLEST = FONT_XSMALL, // <enum skip> FONT_LARGEST = FONT_XLARGE, // <enum skip> FONT_HEADING_SMALLEST = FONT_HEADING_XSMALL, // <enum skip> FONT_HEADING_LARGEST = FONT_HEADING_XLARGE, // <enum skip> FONT_MONO_SMALLEST = FONT_MONO_XSMALL, // <enum skip> FONT_MONO_LARGEST = FONT_MONO_XLARGE, // <enum skip> }; virtual Widget *SetFont(Font font); Font GetFont() const; // bind an object property to a widget bind point void Bind(const std::string &bindName, PropertiedObject *object, const std::string &propertyName); // this sigc accumulator calls all the handlers for an event. if any of // them return true, it returns true (indicating the event was handled), // otherwise it returns false struct EventHandlerResultAccumulator { typedef bool result_type; template <typename T> result_type operator()(T first, T last) const { bool result = false; for (; first != last; ++first) if (*first) result = true; return result; } }; // raw key events sigc::signal<bool,const KeyboardEvent &>::accumulated<EventHandlerResultAccumulator> onKeyDown; sigc::signal<bool,const KeyboardEvent &>::accumulated<EventHandlerResultAccumulator> onKeyUp; // text input, full unicode codepoint sigc::signal<bool,const TextInputEvent &>::accumulated<EventHandlerResultAccumulator> onTextInput; // mouse button presses sigc::signal<bool,const MouseButtonEvent &>::accumulated<EventHandlerResultAccumulator> onMouseDown; sigc::signal<bool,const MouseButtonEvent &>::accumulated<EventHandlerResultAccumulator> onMouseUp; // mouse movement sigc::signal<bool,const MouseMotionEvent &>::accumulated<EventHandlerResultAccumulator> onMouseMove; // mouse wheel moving sigc::signal<bool,const MouseWheelEvent &>::accumulated<EventHandlerResultAccumulator> onMouseWheel; // joystick events sigc::signal<bool,const JoystickAxisMotionEvent &>::accumulated<EventHandlerResultAccumulator> onJoystickAxisMove; sigc::signal<bool,const JoystickHatMotionEvent &>::accumulated<EventHandlerResultAccumulator> onJoystickHatMove; sigc::signal<bool,const JoystickButtonEvent &>::accumulated<EventHandlerResultAccumulator> onJoystickButtonDown; sigc::signal<bool,const JoystickButtonEvent &>::accumulated<EventHandlerResultAccumulator> onJoystickButtonUp; // mouse entering or exiting widget area sigc::signal<bool>::accumulated<EventHandlerResultAccumulator> onMouseOver; sigc::signal<bool>::accumulated<EventHandlerResultAccumulator> onMouseOut; // click - primary mouse button press/release over widget. also // synthesised when keyboard shortcut is used sigc::signal<bool>::accumulated<EventHandlerResultAccumulator> onClick; // Widget events sigc::signal<void,bool> onVisibilityChanged; protected: // magic constant for PreferredSize to indicate "as much as possible" static const int SIZE_EXPAND = INT_MAX; // safely add two sizes, preserving SIZE_EXPAND static inline int SizeAdd(int a, int b) { return a == SIZE_EXPAND || b == SIZE_EXPAND ? SIZE_EXPAND : a+b; } static inline Point SizeAdd(const Point &a, const Point &b) { return Point(SizeAdd(a.x,b.x), SizeAdd(a.y,b.y)); } // set size control flags. no flags by default void SetSizeControlFlags(Uint32 flags) { m_sizeControlFlags = flags; } // set the active area. defaults to the size allocated by the container void SetActiveArea(const Point &activeArea, const Point &activeOffset = Point()); // mouse active. if a widget is mouse-active, it receives all mouse events // regardless of mouse position bool IsMouseActive() const; bool IsSelected() const; Point GetMousePos() const; // indicates whether the widget is part of the visible tree of widgets // (ie, its chain of parents links to a Context) bool IsVisible() const { return m_visible; } void SetDisabled(bool disabled) { m_disabled = disabled; } void SetHidden(bool hidden) { m_hidden = hidden; } // internal event handlers. override to handle events. unlike the external // on* signals, every widget in the stack is guaranteed to receive a call // - there's no facility for stopping propogation up the stack // // as such, if you need to respond to an event inside a widget always // without worrying about it being blocked, you should override the // Handle* method instead of attaching to the signal. virtual void HandleKeyDown(const KeyboardEvent &event) {} virtual void HandleKeyUp(const KeyboardEvent &event) {} virtual void HandleMouseDown(const MouseButtonEvent &event) {} virtual void HandleMouseUp(const MouseButtonEvent &event) {} virtual void HandleMouseMove(const MouseMotionEvent &event) {} virtual void HandleMouseWheel(const MouseWheelEvent &event) {} virtual void HandleJoystickAxisMove(const JoystickAxisMotionEvent &event) {} virtual void HandleJoystickHatMove(const JoystickHatMotionEvent &event) {} virtual void HandleJoystickButtonDown(const JoystickButtonEvent &event) {} virtual void HandleJoystickButtonUp(const JoystickButtonEvent &event) {} virtual void HandleClick() {} virtual void HandleMouseOver() {} virtual void HandleMouseOut() {} // internal synthesized events to indicate that a widget is being mouse // activated or deactivated. very much like MouseDown/MouseUp except you // get a guarantee that you will get a MouseDeactivate() call for every // MouseActivate(). mouse clicks trigger this virtual void HandleMouseActivate() {} virtual void HandleMouseDeactivate() {} // text input event, a full unicode codepoint virtual void HandleTextInput(const TextInputEvent &event) {} // internal synthesized events fired when a widget is selected or // deselected. on mousedown, a widget becomes the selected widget unless // its IsSelectable method returns false. the previously-selected widget // (if there was one) gets deselected virtual void HandleSelect() {} virtual void HandleDeselect() {} virtual void HandleVisible() {} virtual void HandleInvisible() {} void RegisterBindPoint(const std::string &bindName, sigc::slot<void,PropertyMap &,const std::string &> method); float GetAnimatedOpacity() const { return m_animatedOpacity; } float GetAnimatedPositionX() const { return m_animatedPositionX; } float GetAnimatedPositionY() const { return m_animatedPositionY; } private: // EventDispatcher needs to give us events friend class EventDispatcher; // event triggers. when called: // - calls the corresponding Handle* method on this widget (always) // - fires the corresponding on* signal on this widget (iff handled is false) // - calls the container Trigger* method with the new handled value returned // by the on* signal // // what this means in practic is that Handle* will be called for every // widget from here to the root, whereas signals will only be fired as // long as the signals continue to return false (unhandled). bool TriggerKeyDown(const KeyboardEvent &event, bool handled = false); bool TriggerKeyUp(const KeyboardEvent &event, bool handled = false); bool TriggerTextInput(const TextInputEvent &event, bool handled = false); bool TriggerMouseDown(const MouseButtonEvent &event, bool handled = false); bool TriggerMouseUp(const MouseButtonEvent &event, bool handled = false); bool TriggerMouseMove(const MouseMotionEvent &event, bool handled = false); bool TriggerMouseWheel(const MouseWheelEvent &event, bool handled = false); bool TriggerJoystickButtonDown(const JoystickButtonEvent &event, bool handled = false); bool TriggerJoystickButtonUp(const JoystickButtonEvent &event, bool handled = false); bool TriggerJoystickAxisMove(const JoystickAxisMotionEvent &event, bool handled = false); bool TriggerJoystickHatMove(const JoystickHatMotionEvent &event, bool handled = false); bool TriggerClick(bool handled = false); // stop is used during disable/enable to stop delivery at the given widget bool TriggerMouseOver(const Point &pos, bool handled = false, Widget *stop = 0); bool TriggerMouseOut(const Point &pos, bool handled = false, Widget *stop = 0); void TriggerMouseActivate(); void TriggerMouseDeactivate(); void TriggerSelect(); void TriggerDeselect(); void TriggerVisibilityChanged(); // let container set our attributes. none of them make any sense if // we're not in a container friend class Container; // things for the container to call to attach, detach and position the // widget. it could modify our data directly but that's ugly void Attach(Container *container); void Detach(); void SetDimensions(const Point &position, const Point &size); virtual void NotifyVisible(bool visible); // called by Container::CollectShortcuts const std::set<KeySym> &GetShortcuts() const { return m_shortcuts; } // Context is the top-level container and needs to set its own context // and size directly friend class Context; void SetSize(const Point &size) { m_size = size; SetActiveArea(size); } // Animation needs to change our animation attributes friend class Animation; void SetAnimatedOpacity(float opacity) { m_animatedOpacity = opacity; } void SetAnimatedPositionX(float pos) { m_animatedPositionX = pos; } void SetAnimatedPositionY(float pos) { m_animatedPositionY = pos; } Context *m_context; Container *m_container; Point m_position; Point m_size; Uint32 m_sizeControlFlags; Point m_drawOffset; Point m_activeOffset; Point m_activeArea; Font m_font; bool m_disabled; bool m_hidden; bool m_mouseOver; bool m_visible; std::set<KeySym> m_shortcuts; std::map< std::string,sigc::slot<void,PropertyMap &,const std::string &> > m_bindPoints; std::map< std::string,sigc::connection > m_binds; float m_animatedOpacity; float m_animatedPositionX; float m_animatedPositionY; }; } #endif
true
0d6fcffdfe5c7399578b9d7726b7b1afb8bbf427
C++
mahkons/Software-design-course-HSE2020
/CLI/inc/commands/pwd_command.h
UTF-8
927
2.78125
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <vector> #include <memory> #include "result.h" #include "commands/command.h" #include "commands/execution_result.h" namespace NCLI::NCommand { /** * Command that writes current directory absolute path to output stream */ class PwdCommand : public Command { public: PwdCommand() = default; /** * Writes current directory absolute path to output stream * Always terminates with status ExecutionStatus::success */ virtual ExecutionResult execute(std::istream& is, std::ostream& os) override; /** * Creates new PwdCommand and returns pointer to it * Always terminated successfully */ static Result<std::shared_ptr<Command>, std::string> create_command( const std::vector<std::string>& args); }; } // namespace NCLI::NCommand
true
a78d4b0a6759b9bb89fe308cf6ec073823c98d59
C++
markkun/galaxy
/galaxy/src/galaxy/fs/FileSystem.hpp
UTF-8
2,002
2.734375
3
[ "Apache-2.0" ]
permissive
/// /// FileSystem.hpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #ifndef GALAXY_FS_FILESYSTEM_HPP_ #define GALAXY_FS_FILESYSTEM_HPP_ #include <string> namespace galaxy { namespace fs { /// /// Open an open file dialog using pfd. /// /// \param filter See: https://github.com/samhocevar/portable-file-dialogs/blob/master/doc/open_file.md. /// Defaults to all files. /// \param def_path Default starting path to open dialog at. /// std::string open_file_dialog(const std::string& filter = "*", const std::string& def_path = "."); /// /// Open a save file dialog using pfd. /// /// \param def_path Default starting path to open dialog at. /// std::string save_file_dialog(const std::string& def_path = "."); /// /// Open a folder using a file dialog. /// /// \param def_path Default starting path to open dialog at. /// std::string folder_select_dialog(const std::string& def_path = "."); /// /// Root directory of all files. /// inline std::string s_root; /// /// \brief Root directory of textures. /// /// Should be a subdirectory of s_root. /// inline std::string s_textures; /// /// \brief Root directory of shaders. /// /// Should be a subdirectory of s_root. /// inline std::string s_shaders; /// /// \brief Root directory of scripts. /// /// Should be a subdirectory of s_root. /// inline std::string s_scripts; /// /// \brief Root directory of audio. /// /// Should be a subdirectory of s_root. /// inline std::string s_audio; /// /// \brief Root directory of json. /// /// Should be a subdirectory of s_root. /// inline std::string s_json; /// /// \brief Root directory of fonts. /// /// Should be a subdirectory of s_root. /// inline std::string s_fonts; /// /// \brief Root directory of save files. /// /// Should be a subdirectory of s_root. /// inline std::string s_saves; } // namespace fs } // namespace galaxy #endif
true
7586e94bf3db37f5d66a51be3337a2508852900b
C++
Zhenghao-Liu/LeetCode_problem-and-solution
/0990.等式方程的可满足性/solution_union_find.cpp
UTF-8
1,421
3.171875
3
[]
no_license
class Solution { unordered_map<char,char> parent; public: bool equationsPossible(vector<string>& equations) { parent.clear(); int equations_size=equations.size(); vector<int> unequal; vector<int> equeal; for (int i=0;i<equations_size;++i) { if (equations.at(i).at(1)=='=') equeal.push_back(i); else unequal.push_back(i); initialise(equations.at(i).at(0)); initialise(equations.at(i).at(3)); } for (int &i:equeal) union_vertices(equations.at(i).at(0),equations.at(i).at(3)); for (int &i:unequal) { char a_root=find_root(equations.at(i).at(0)); char b_root=find_root(equations.at(i).at(3)); if (a_root==b_root) return false; } return true; } void initialise(char c) { if (parent.find(c)==parent.end()) parent.insert({c,c}); } char find_root(char c) { if (parent.at(c)!=c) { char root=find_root(parent.at(c)); parent.at(c)=root; return root; } return c; } void union_vertices(char a,char b) { char a_root=find_root(a); char b_root=find_root(b); if (a_root==b_root) return; parent.at(a_root)=b_root; } };
true
086937c1864824ba76f9f6c7eb25984512448bc8
C++
hyedoii/ite1015_2017029716
/HW5/draw_shape/draw_shape_main.cc
UTF-8
2,097
3.0625
3
[]
no_license
#include <iostream> #include <string> #include "draw_shape.h" using namespace std; int main() { int row, col; cin>>col>>row; Canvas canvas(row, col); canvas.Draw(cout); Shape shape; while(true) { string word; cin>>word; if(word=="add") { cin>>word; if(word=="rect") { shape.type = RECTANGLE; cin >> shape.y >> shape.x >> shape.height >> shape.width >> shape.brush; int a = canvas.AddShape(shape); if(a == -1 || a == -2){ if(a == -1) cout << "error out of canvas" << endl; if(a == -2) cout << "error invalid input" << endl; } } else if(word=="tri_up") { shape.type = TRIANGLE_UP; cin >> shape.y >> shape.x >> shape.width >> shape.brush; int a = canvas.AddShape(shape); if(a == -1 || a == -2){ if(a == -1) cout << "error out of canvas" << endl; if(a == -2) cout << "error invalid input" << endl; } } else if(word=="tri_down") { shape.type = TRIANGLE_DOWN; cin >> shape.y >> shape.x >> shape.width >> shape.brush; int a = canvas.AddShape(shape); if(a == -1 || a == -2){ if(a == -1) cout << "error out of canvas" << endl; if(a == -2) cout << "error invalid input" << endl; } } else break; } else if(word=="delete") { int index; cin >> index; canvas.DeleteShape(index); } else if(word=="draw") { canvas.Draw(cout); } else if(word=="dump") { canvas.Dump(cout); } else break; } }
true
768b797b2e6f718248f4e5867ab1e0f7572fd48d
C++
StK1729/SK-Game-Engine
/SK-Game-Engine/src/SK-Game-Engine/Renderer/VertexArray.h
UTF-8
561
2.546875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <memory> #include "SK-Game-Engine/Core/Core.h" #include "Buffer.h" namespace SK_Game_Engine { class SKGE_API VertexArray { public: virtual ~VertexArray() {}; virtual void Bind() = 0; virtual void Unbind() = 0; virtual void AddVertexBuffer(const Ref<VertexBuffer>& vertexBuffer) = 0; virtual void AddIndexBuffer(const Ref<IndexBuffer>& indexBuffer) = 0; virtual const std::vector<Ref<VertexBuffer>>& GetVertexBuffers() = 0; virtual const Ref<IndexBuffer>& GetIndexBuffer() = 0; static Ref<VertexArray> Create(); }; }
true
3ec71fdbcc7b16db20d8ac6aa062f2fee6563a8c
C++
imnick002/hackerrank
/divisible sum pairs.cpp
UTF-8
503
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int n,s; cin>>n>>s; int arr[n]; int sum=0; int count=0; for(int i=0;i<n;i++){ cin>>arr[i]; } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ sum=arr[i]+arr[j]; if(i!=j){ if(sum%s==0 && sum>=s){ count++; } } } } count=count/2; cout<<count<<endl; }
true
24e5a0411fd4a526a9dc0dfdc643ee33e9a35f20
C++
Le0nRoy/BerkleyAPI_App
/src/client/client.cpp
UTF-8
2,624
2.96875
3
[]
no_license
// // Created by lap on 9/5/20. // #include <iostream> #include "client.h" #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <cstring> #include <unistd.h> /// Good void Client::run() { if (createConnection() == EXIT_FAILURE) { return; } std::string str; int res; while (true) { std::cout << ">> "; std::getline(std::cin, str); if (str == "exit") { sendMessage(serverFd, str); break; } if (str == "help") { std::cout << "Type your message to send it on server." << std::endl << "As answer you'll get sum of all numbers in your message." << std::endl << "If no numbers were then you'll get back your message." << std::endl << std::endl << "Some words are reserved as special commands:" << std::endl << "help - show this message" << std::endl << "exit - stop application" << std::endl; } res = sendMessage(serverFd, str); if (res == -1) { logger->error("Failed to send message"); logger->error(strerror(errno)); break; } res = getMessage(serverFd); if (res == -1) { logger->error("Failed to receive message"); logger->error(strerror(errno)); break; } std::cout << buffer << std::endl; } logger->info("Closing client..."); } // TODO check UDP /// Good for TCP int Client::createConnection() { int res; res = Socket::createConnection(); if (res != EXIT_SUCCESS) { logger->error("Failed to create socket."); logger->error(strerror(errno)); return res; } memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_port = htons(port); res = inet_pton(AF_INET, ip.data(), &sa.sin_addr); if (conType == TCP) { if (res < 0) { logger->error("Failed to parse IP."); logger->error(strerror(errno)); return res; } res = connect(serverFd, (sockaddr *)&sa, sizeof sa); if (res < 0) { logger->error("Failed to create connection with " + ip + ":" + std::to_string(port) ); logger->error(strerror(errno)); close(serverFd); return res; } logger->info("Connection established!"); } return EXIT_SUCCESS; }
true
8ec4da28b043e3c98ce800bd787024ac597872fe
C++
heronsousa/PPC
/prova2/d.cpp
UTF-8
581
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; int main(){ ll t; double m; cin >> m >> t; vector<double> taxa; for(int i=0;i<t;i++){ double aux; cin >> aux; taxa.push_back(aux/100.0); } double lo=0,hi=m,mid; while(lo <= hi){ mid = lo+(hi-lo)/2; double ans = mid; for(int i=0;i<t;i++){ ans += (ans + (ans*taxa[i])); } ll h = ans,y=m; //cout << mid << " " << h << " " << endl; if(h < y) lo = mid + 0.01; else hi = mid - 0.01; } cout << mid << endl; return 0; }
true
b05c14004f69f141cc082dc16d9034285840fe17
C++
tek1031/AOJ
/2014/2014.cpp
UTF-8
1,067
2.734375
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include<string.h> using namespace std; int h,w; bool is_next[2][50][50]; vector<string> M; int dx[]={1,0,-1,0}; int dy[]={0,1,0,-1}; void dfs(int x,int y,int is_black){ if(x<0 || y<0 || x>=w || y>=h) return; if(M[y][x]!='.') return; if(is_next[is_black][y][x]) return; is_next[is_black][y][x]=true; for(int r=0;r<4;r++) dfs(x+dx[r],y+dy[r],is_black); } int main() { while(cin>>w>>h && w!=0){ M.clear(); memset(is_next,false,sizeof(is_next)); for(int i=0;i<h;i++){ string s; cin>>s; M.push_back(s); } for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ if(M[y][x]=='W'){ for(int r=0;r<4;r++){ dfs(x+dx[r],y+dy[r],1); } } else if(M[y][x]=='B'){ for(int r=0;r<4;r++){ dfs(x+dx[r],y+dy[r],0); } } } } int ans_b=0,ans_w=0; for(int y=0;y<h;y++){ for(int x=0;x<w;x++){ if(is_next[0][y][x] && !is_next[1][y][x]) ans_b++; if(is_next[1][y][x] && !is_next[0][y][x]) ans_w++; } } cout<<ans_b<<" "<<ans_w<<endl; } return 0; }
true
ef60438dee5cca548a1a797193c23c0ed86845ed
C++
Meet57/programming
/c++ practicals/5.18.cpp
UTF-8
512
3.578125
4
[]
no_license
#include<iostream> using namespace std; class TEST { private: int maths; public: TEST() { cout << "contructor" << endl; maths = 0; } void Setdetails(int a) { maths = a; } ~TEST() { cout << "Destructor" << endl; } friend int find_square(TEST temp); }; int find_square(TEST temp) { temp.maths = temp.maths*temp.maths; return temp.maths; } int main() { TEST meet; { meet.Setdetails(91); cout << "Maths marks:" << find_square(meet) << endl; } return 0; }
true
81a8f6bada5eb31151eff51e862dd006a2fb302b
C++
CompPhysics/ThesisProjects
/doc/MSc/msc_students/former/ChristianF/ThesisCodes/diagonalization/WaveFunctions/wavefunction.cpp
UTF-8
1,602
3.09375
3
[ "CC0-1.0" ]
permissive
#include "wavefunction.h" WaveFunction::WaveFunction(System* system, double omega) { m_system = system; m_omega = omega; } vec WaveFunction::computeHermitePolynomial(int nValue, vec position) { // Computes Hermite polynomials. double omegaSqrt = sqrt(m_omega); vec factor = 2*omegaSqrt*position; vec HermitePolynomialPP = zeros(position.size()); // H_{n-2} vec HermitePolynomialP = ones(position.size()); // H_{n-1} vec HermitePolynomial = HermitePolynomialP; // H_n for (int n=1; n <= nValue; n++) { HermitePolynomial = factor%HermitePolynomialP - 2*(n-1)*HermitePolynomialPP; HermitePolynomialPP = HermitePolynomialP; HermitePolynomialP = HermitePolynomial; } return HermitePolynomial; } // vec x = position*omegaSqrt; // if (nValue == 0) { // return ones(x.size()); // } // else if (nValue == 1) { // return 2*x; // } // else if (nValue == 2) { // return 4*x%x - 2; // } // else if (nValue == 3) { // return 8*x%x%x - 12*x; // } // else if (nValue == 4) { // return 16*x%x%x%x - 48*x%x + 12; // } // else if (nValue == 5) { // return 32*x%x%x%x%x -160*x%x%x +120*x; // } // else if (nValue == 6) { // return 64*x%x%x%x%x%x - 480*x%x%x%x + 720*x%x - 120; // } // else if (nValue == 7) { // return 128*x%x%x%x%x%x%x - 1344*x%x%x%x%x + 3360*x%x%x - 1680; // } // else if (nValue == 8) { // return 256*x%x%x%x%x%x%x%x - 3584*x%x%x%x%x%x + 13440*x%x%x%x - 13440*x%x + 1680; // }
true
ab37d71d8de069116090468ca5cf88d683b6209c
C++
ore13/rocketThermal
/src/AeroHeating.cpp
UTF-8
3,572
2.609375
3
[]
no_license
#include "AeroHeating.hpp" #include "AirProperties.hpp" #include "CsvWriter.hpp" #include "vectorMath.hpp" #include <cmath> #include <vector> using namespace std; class flightData { vector<double> *time_ptr; vector<double> *temperature_ptr; vector<double> *pressure_ptr; vector<double> *velocity_ptr; flightData(vector<double> &t, vector<double> &Temp, vector<double> &P, vector<double> &V) { time_ptr = &t; temperature_ptr = &Temp; pressure_ptr = &P; velocity_ptr = &V; } }; double adiabatic_temperature(double &T, double &V) { double T1 = T + pow(V, 2) / (2.0f * specific_heat(T)); T1 = (T1 + T) / (2.0f); double T2 = T + pow(V, 2) / (2.0f * specific_heat(T1)); return T2; } double boundary_layer_temperature_eber(double &T, double &V) { double Tst = adiabatic_temperature(T, V); return T + 0.89*(Tst - T); } double convective_coefficient_eber(double &T, double &V, double &P, double &vertex_angle, double &l) { double Tbl = boundary_layer_temperature_eber(T, V); double rho = density(P, Tbl); double mu = viscosity(Tbl); double k = thermal_conductivity(Tbl); double Pr = prandtl_number(Tbl); double Re = rho * V * l / mu; // double Nu = (0.0071 + 0.0154*sqrt(vertex_angle*3.1415f/180.0f)) * pow(Re, 0.8f); double Nu = 0.037 * pow(Re, 0.8f) * pow(Pr, 1.0f/3.0f); if (vertex_angle > 1e-6) { Nu = Nu * 1.15; // only apply cone correction for cones } return Nu * k / l; } int transient_0d(vector<double> &time, vector<double> &air_temperature, vector<double> &pressure, vector<double> &velocity, double &vertex_angle, double &nose_length, double &G, double &emissivity, double &absorptivity, string filename) { // Loop variables: double Ts, P, V, T_free, T_bl, h, dt, qdot_rad_absorb, qdot_rad_emit, f, Ts_next; const double STEFAN_BOLTZMANN = 5.670374419e-8; // Vectors of output variables vector<double> boundary_layer_temperature(time.size(), 0); vector<double> skin_temperature(time.size(), 0); vector<double> convection_coefficient(time.size(), 0); // Initialise the skin temperature to the ambient air temperature at t = 0 skin_temperature[0] = air_temperature[0]; Ts = air_temperature[0]; for (int i = 0; i < time.size(); i++) { P = pressure[i]; V = velocity[i]; T_free = air_temperature[i]; // Calculations T_bl = boundary_layer_temperature_eber(T_free, V); h = convective_coefficient_eber(T_bl, V, P, vertex_angle, nose_length); dt = time[i+1] - time[i]; // Heat transfer rates qdot_rad_absorb = absorptivity * STEFAN_BOLTZMANN * pow(T_free, 4); qdot_rad_emit = emissivity * STEFAN_BOLTZMANN * pow(Ts, 4); f = (h * (T_bl - Ts) + qdot_rad_absorb - qdot_rad_emit) / G; Ts_next = Ts + dt * f; // Logging of variables boundary_layer_temperature[i] = T_bl; convection_coefficient[i] = h; if (i != time.size() - 1) { skin_temperature[i + 1] = Ts_next; } Ts = Ts_next; } CsvWriter writer; writer.addColumn("Time [s]", time); writer.addColumn("Free Stream Temperature [K]", air_temperature); writer.addColumn("Boundary Layer Temperature [K]", boundary_layer_temperature); writer.addColumn("Skin Temperature [K]", skin_temperature); writer.addColumn("Convective Heat Transfer Coefficient [W/m^2-K]", convection_coefficient); return writer.writeFile(filename, '\t'); }
true
6ba88a43563145b2bc88199cd3a3104db6778acf
C++
MohammadJRanjbar/Dataset-and-NeuralNet-Class
/cpp/dataset.cpp
UTF-8
6,275
2.890625
3
[ "MIT" ]
permissive
#include "dataset.h" #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <cmath> void Dataset::show() { std::cout << "Dataset:" << std::endl; std::cout << " " << "No of sampels: " << no_of_samples << std::endl; std::cout << " " << "Train sampels " << train_inputs.getSize()[1] << std::endl; std::cout << " " << "Test sampels: " << test_inputs.getSize()[1] << std::endl; std::cout << " " << "Input dimensions: " << input_dim << std::endl; std::cout << " " << "Target dimensions: " << target_dim << std::endl; } Dataset::Dataset(Matrix inputs, Matrix targets, double percentage) { //initializing values this->inputs = inputs; this->targets = targets; this->percentage = percentage; this->no_of_samples = inputs.getSize()[1]; this->input_dim = inputs.getSize()[0]; this->target_dim = targets.getSize()[0]; Train_test_split(); } void Dataset::Train_test_split() { //n is the number if train inputs size_t n = static_cast <size_t> ((no_of_samples*percentage) / 100); Matrix traininputs{ input_dim ,n,0 }; Matrix traintargets{ target_dim ,n,0 }; //the remaining data are for test Matrix testinputs{ input_dim ,no_of_samples - n,0 }; Matrix testtargets{ target_dim ,no_of_samples - n,0 }; for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < input_dim; j++) { traininputs[j][i] = inputs[j][i]; } } for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < target_dim; j++) { traintargets[j][i] = targets[j][i]; } } size_t Te{ 0 }; for (size_t i = n; i < no_of_samples; i++) { for (size_t j = 0; j < input_dim; j++) { testinputs[j][Te] = inputs[j][i]; } Te++; } Te = 0; for (size_t i = n; i < no_of_samples; i++) { for (size_t j = 0; j < target_dim; j++) { testtargets[j][Te] = targets[j][i]; } Te++; } this->train_inputs = traininputs; this->train_targets = traintargets; this->test_inputs = testinputs; this->test_targets = testtargets; } void Dataset::shuffle() { //make a vector of number of sampels std::vector<size_t> temp; for (size_t i = 0; i < no_of_samples; i++) { temp.push_back(i); } std::vector<size_t> temp2; //intializing a random seed based on the computer time srand(static_cast <size_t> (time(0))); Matrix shuffled_inputs{ inputs }; Matrix shuffled_targets{ targets }; for (size_t i = 0; i < no_of_samples; i++) { for (size_t j = 0; j < input_dim; j++) { //get a random index of that vector size_t index = rand() % temp.size(); //and give to element of that to the inputs and outputs shuffled_inputs[j][i] = inputs[j][temp[index]]; temp2.push_back(temp[index]); //and erase that element temp.erase(temp.begin() + index); } } for (size_t i = 0; i < no_of_samples; i++) { for (size_t j = 0; j < target_dim; j++) { shuffled_targets[j][i] = targets[j][temp2[i]]; } } this->inputs = shuffled_inputs; this->targets = shuffled_targets; //to intialize train and test data Train_test_split(); } std::vector<Matrix> Dataset::operator[](size_t j) { std::vector<Matrix> temp{ inputs.col(j), targets.col(j) }; return temp; } size_t Dataset::getNoOfSamples()const { return no_of_samples; } size_t Dataset::getNoOfTrainSamples() { return train_inputs.getSize()[1]; } size_t Dataset::getNoOfTestSamples() { return test_inputs.getSize()[1]; } size_t Dataset::getInputDim() { return inputs.getSize()[0]; } size_t Dataset::getTargetDim() { return targets.getSize()[0]; } Matrix Dataset::getInputs()const { return inputs; } Matrix Dataset::getTargets()const { return targets; } Matrix Dataset::getTrainInputs() { return train_inputs; } Matrix Dataset::getTrainTargets() { return train_targets; } Matrix Dataset::getTestInputs() { return test_inputs; } Matrix Dataset::getTestTargets() { return test_targets; } Dataset Dataset::operator+(const Dataset& dataset) { //new matrices with no sampels of two datasets Matrix new_input{ input_dim ,no_of_samples + dataset.getNoOfSamples(),0 }; Matrix new_targets{ target_dim ,no_of_samples + dataset.getNoOfSamples(),0 }; //and initialize the value of each matrices for (size_t i = 0; i < input_dim; i++) { for (size_t j = 0; j < no_of_samples; j++) { new_input[i][j] = inputs[i][j]; } } for (size_t i = 0; i < input_dim; i++) { for (size_t j = no_of_samples; j < no_of_samples + dataset.getNoOfSamples(); j++) { new_input[i][j] = dataset.getInputs()[i][j]; } } for (size_t i = 0; i < target_dim; i++) { for (size_t j = 0; j < no_of_samples; j++) { new_targets[i][j] = targets[i][j]; } } for (size_t i = 0; i < target_dim; i++) { for (size_t j = no_of_samples; j < no_of_samples + dataset.getNoOfSamples(); j++) { new_targets[i][j] = dataset.getTargets()[i][j]; } } //make new dataset with the new inputs and targets Dataset DT{new_input,new_targets,percentage}; return DT; } std::ostream &operator<<(std::ostream &os, Dataset &ds) { //this opreator is friend so it does have access to private variables os << "Dataset:" << std::endl; os << " " << "No of sampels: " << ds.no_of_samples << std::endl; os << " " << "Train sampels " << ds.train_inputs.getSize()[1] << std::endl; os << " " << "Test sampels: " << ds.test_inputs.getSize()[1] << std::endl; os<< " " << "Input dimensions: " << ds.input_dim << std::endl; os << " " << "Target dimensions: " << ds.target_dim << std::endl; return os ; }
true
bcdb75f9981dc479c67ef96c18984f283a49fbd5
C++
Muret/Zephyr
/Zephyr/CatmullClark.h
UTF-8
1,661
2.71875
3
[]
no_license
#ifndef __INCLUDE_CATMULLCLARK_H #define __INCLUDE_CATMULLCLARK_H #include "includes.h" class Mesh; class CatmullClark { struct CC_Edge { int edge_points[2]; //int touching_faces[2]; int newly_added_midpoint; int face; }; struct CC_Face { vector<int> edges_of_face; vector<int> vertices_of_face; vector<int> newly_added_edges_from_face_center_to_edge_midpoint; int newly_added_face_point; vector<int> new_added_midpoints; }; struct CC_Vertex { D3DXVECTOR4 position; D3DXVECTOR4 v2_new_position; vector<int> edges; vector<int> faces; }; struct CC_MeshRepresenation { vector<CC_Face> faces; vector<CC_Edge> edges; vector<CC_Vertex> vertices; }; public: CatmullClark(Mesh *mesh_to_edit, int mode); void subdivide(int count); void fill_mesh_representation(CC_MeshRepresenation &mesh_r) const; void sub_divide_imp_v1(CC_MeshRepresenation &mesh_r); void sub_divide_imp_v2(CC_MeshRepresenation &mesh_r); bool get_common_face_indexes_of_an_edge(const CC_MeshRepresenation & mesh_r, int i, int &first_face_index, int &second_face_index, int &face1, int &face2); void remove_from_vector(vector<int> & vertices, int i); int get_last_vertex_from_face(const CC_Face &get_other_vertex, int v1, int v2); int get_other_vertex_index_from_edge(const CC_Edge &edge, int v1) const; void refill_mesh_render_buffers(CC_MeshRepresenation &mesh_r); D3DXVECTOR3 get_normal_of_face(int face_index, const CC_MeshRepresenation &mesh_r) const; bool get_twin_edge_midpoint(const CC_MeshRepresenation &mesh_r, int edge_index, int &twin_edge_midpoint) const; private: Mesh *mesh_to_edit_; int mode_; }; #endif
true
f70adc01b03032ee415c8124949e7d7d5adfbf60
C++
serman/muncyt_tests
/nuclear_Fuerte/src/Emisor.h
UTF-8
1,957
2.671875
3
[]
no_license
/* * Emisor.h * nuclear_Fuerte * * Created by guillermo casado on 03/09/14. * Copyright 2014 __MyCompanyName__. All rights reserved. * */ #ifndef _EMISOR #define _EMISOR class Emisor { public: // posicion float rho; float ang; ofVec2f posXY; // hacia donde van las particulas ofVec2f pointTo; ofVec2f dir; // Tipo Particula int tpPartic; // para dibujar float lado; ofVboMesh icono; ofColor c; Emisor() { setPos_Radial(0,0); tpPartic = 0; c = ofColor::red; // preparar forma a dibujar setupIcono(); } Emisor(float _rho, float _ang, int _tpPartic = 0) { setPos_Radial(_rho, _ang); tpPartic = _tpPartic; c = ofColor::red; // preparar forma a dibujar setupIcono(); } void setColor(ofColor cc) { c = cc; setupIcono(); } void setupIcono() { // También puede ser un png! lado = 30.0; float altura = lado*sin(PI/3.0); icono.clear(); icono.addVertex(ofVec3f(-lado/2.0, -0.2*altura, 0.0)); icono.addColor(ofColor::fromHsb(c.getHue(), c.getSaturation(), c.getBrightness()*0.2)); icono.addVertex(ofVec3f(+lado/2, -0.2*altura, 0.0)); icono.addColor(ofColor::fromHsb(c.getHue(), c.getSaturation(), c.getBrightness()*0.2)); icono.addVertex(ofVec3f(0,0.8*altura,0.0)); icono.addColor(c); } void setPos_Radial(float _rho, float _ang) { rho = _rho; ang = _ang; calcPosXY(); } void setPos_XY(float _x, float _y) { posXY = ofVec2f(_x, _y); rho = posXY.length(); ang = atan2(posXY.y, posXY.x); // ofLogNotice(ofToString(ang)); } ofVec2f calcPosXY() { posXY = ofVec2f(rho*cos(ang), rho*sin(ang)); return posXY; } void draw() { ofPushStyle(); // linea de union ofSetColor(c); ofLine(0,0, posXY.x, posXY.y); // dibuja el icono ofPushMatrix(); // translate ofTranslate(posXY.x, posXY.y); // rotate ofRotateZ(90+RAD_TO_DEG*(ang)); // draw icono.draw(); ofPopMatrix(); ofPopStyle(); } }; #endif
true
23828cb055a58e86ee3cfb5fb9da2f060f9a1b5c
C++
borispeeters/cpp
/module00/ex01/contact.cpp
UTF-8
5,520
3.046875
3
[]
no_license
/* ************************************************************************** */ /* */ /* :::::::: */ /* contact.cpp :+: :+: */ /* +:+ */ /* By: bpeeters <bpeeters@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/03/29 03:45:34 by bpeeters #+# #+# */ /* Updated: 2020/04/01 05:30:38 by bpeeters ######## odam.nl */ /* */ /* ************************************************************************** */ #include <string> #include <iostream> #include "contact.hpp" Contact::Contact(const std::string &firstName, const std::string &lastName, const std::string &nickName, const std::string &login, const std::string &postalAddress, const std::string &emailAddress, const std::string &phoneNumber, const std::string &birthdayDate, const std::string &favoriteMeal, const std::string &underwearColor, const std::string &darkestSecret) : m_firstName(firstName), m_lastName(lastName), m_nickName(nickName), m_login(login), m_postalAddress(postalAddress), m_emailAddress(emailAddress), m_phoneNumber(phoneNumber), m_birthdayDate(birthdayDate), m_favoriteMeal(favoriteMeal), m_underwearColor(underwearColor), m_darkestSecret(darkestSecret) { } std::string Contact::readInfo() { std::string info; std::getline(std::cin, info); return info; } void Contact::resizeString(std::string &str) { str.resize(9); str.resize(10, '.'); } void Contact::displayFields(std::string temp) { std::cout << '|'; for (int i = temp.length(); i < 10; ++i) std::cout << ' '; if (temp.length() > 10) resizeString(temp); std::cout << temp; } void Contact::addContact() { std::cout << "Enter first name: "; setFirstName(readInfo()); std::cout << "Enter last name: "; setLastName(readInfo()); std::cout << "Enter nickname: "; setNickName(readInfo()); std::cout << "Enter login: "; setLogin(readInfo()); std::cout << "Enter postal address: "; setPostalAddress(readInfo()); std::cout << "Enter email address: "; setEmailAddress(readInfo()); std::cout << "Enter phone number: "; setPhoneNumber(readInfo()); std::cout << "Enter birthday date: "; setBirthdayDate(readInfo()); std::cout << "Enter favorite meal: "; setFavoriteMeal(readInfo()); std::cout << "Enter underwear color: "; setUnderwearColor(readInfo()); std::cout << "Enter darkest secret: "; setDarkestSecret(readInfo()); } void Contact::displayInfo(int index) { std::cout << " " << index; displayFields(m_firstName); displayFields(m_lastName); displayFields(m_nickName); std::cout << std::endl; } void Contact::printFields() { std::cout << "First Name: " << getFirstName() << std::endl; std::cout << "Last Name: " << getLastName() << std::endl; std::cout << "Nickname: " << getNickName() << std::endl; std::cout << "Login: " << getLogin() << std::endl; std::cout << "Postal Address: " << getPostalAddress() << std::endl; std::cout << "Email Address: " << getEmailAddress() << std::endl; std::cout << "Phone Number: " << getPhoneNumber() << std::endl; std::cout << "Birthday Date: " << getBirthdayDate() << std::endl; std::cout << "Favorite Meal: " << getFavoriteMeal() << std::endl; std::cout << "Underwear Color: " << getUnderwearColor() << std::endl; std::cout << "Darkest Secret: " << getDarkestSecret() << std::endl; } std::string Contact::getFirstName() const { return m_firstName; } void Contact::setFirstName(const std::string &firstName) { m_firstName = firstName; } std::string Contact::getLastName() const { return m_lastName; } void Contact::setLastName(const std::string &lastName) { m_lastName = lastName; } std::string Contact::getNickName() const { return m_nickName; } void Contact::setNickName(const std::string &nickName) { m_nickName = nickName; } std::string Contact::getLogin() const { return m_login; } void Contact::setLogin(const std::string &login) { m_login = login; } std::string Contact::getPostalAddress() const { return m_postalAddress; } void Contact::setPostalAddress(const std::string &postalAddress) { m_postalAddress = postalAddress; } std::string Contact::getEmailAddress() const { return m_emailAddress; } void Contact::setEmailAddress(const std::string &emailAddress) { m_emailAddress = emailAddress; } std::string Contact::getPhoneNumber() const { return m_phoneNumber; } void Contact::setPhoneNumber(const std::string &phoneNumber) { m_phoneNumber = phoneNumber; } std::string Contact::getBirthdayDate() const { return m_birthdayDate; } void Contact::setBirthdayDate(const std::string &birthdayDate) { m_birthdayDate = birthdayDate; } std::string Contact::getFavoriteMeal() const { return m_favoriteMeal; } void Contact::setFavoriteMeal(const std::string &favoriteMeal) { m_favoriteMeal = favoriteMeal; } std::string Contact::getUnderwearColor() const { return m_underwearColor; } void Contact::setUnderwearColor(const std::string &underwearColor) { m_underwearColor = underwearColor; } std::string Contact::getDarkestSecret() const { return m_darkestSecret; } void Contact::setDarkestSecret(const std::string &darkestSecret) { m_darkestSecret = darkestSecret; }
true
18034963bae21fa30207442ac3251e2e0dd3fcd7
C++
wangqifei/leetcode
/152_MaximumProductSubarray.cpp
UTF-8
1,340
3.6875
4
[]
no_license
// 152 Maximum Product Subarray // Find the contiguous subarray within an array (containing at least one number) which has the largest product. // For example, given the array [2,3,-2,4], // the contiguous subarray [2,3] has the largest product = 6. // Hide Tags Array Dynamic Programming #include <iostream> #include <vector> #include <climits> using namespace::std; class Solution { public: int maxProduct(vector<int>& nums) { if(nums.empty()) return 0; int min_prod = nums[0]; int max_prod = nums[0]; int max_res = nums[0]; //Caution!!! do not use INT_MIN, it is not necessary and it may not be updated when nums.size()<2 for(int i = 1; i < nums.size(); ++i) { int prev_min_prod = min_prod; int prev_max_prod = max_prod; min_prod = min(min(prev_max_prod*nums[i], prev_min_prod*nums[i]), nums[i]); max_prod = max(max(prev_max_prod*nums[i], prev_min_prod*nums[i]), nums[i]); max_res = max(max_res, max(min_prod, max_prod)); } return max_res; } }; int main(int argc, char const *argv[]) { // int A[] = {-4,-3,-2}; // int len = 3; int A[] = {-2}; int len = 1; Solution mySolution; vector<int> nums(A, A+len); int res = mySolution.maxProduct(nums); cout<<res<<endl; return 0; }
true