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
3a2dd47efe37655e32c5519bbc0715e86dcb64b4
C++
KushRohra/GFG_Codes
/Easy/Required Rooms.cpp
UTF-8
309
2.609375
3
[]
no_license
#include<iostream> int main() { int t; cin>>t; while(t--) { int a,b,c,f,g,q,hcf; cin>>a>>b; if(a<b) { c=a; a=b; b=c; } c=0; f=a; g=b; while(c==0) { q=f%g; if(q==0) { hcf=g; c=1; } else { f=g; g=q; } } cout<<(a/hcf)+(b/hcf)<<endl; } }
true
fd4f64aa2c20260548048c679565fda945976159
C++
Matth3wThomson/Octree
/GamingSim Entities/MeshManager.h
UTF-8
561
2.546875
3
[]
no_license
#pragma once #include "singleton.h" #include "Mesh.h" #include <string> #include <map> #define MESH_PATH "Resources\\Meshes\\" using std::map; using std::string; /** * A singleton used to represent the loading and deletion of meshes. */ class MeshManager : public Singleton<MeshManager> { friend class Singleton<MeshManager>; public: Mesh* GetMesh(const string& filename); Mesh* AddMesh(const string& filename); private: Mesh* LoadObjFile(const char* filename); protected: MeshManager(void){}; ~MeshManager(void); map<string, Mesh*> meshes; };
true
20d2389e7d6e4c9802281a76f807ef93446e05c8
C++
rrikhy/CS161
/Library.h
UTF-8
915
2.5625
3
[ "MIT" ]
permissive
// // Library.h // examples // // Created by Tim Alcon on 11/25/14. // Copyright (c) 2014 Tim Alcon. All rights reserved. // #ifndef __examples__Library__ #define __examples__Library__ #include <vector> #include <stdio.h> #include <string> using namespace std; class Patron; class Book; class Library { private: std::vector<Book> holdings; std::vector<Patron> members; int currentDate; public: static const double DAILY_FINE = 0.1; Library(); void addBook (); void addMember (); void checkOutBook (std::string patronID, std::string bookID); void returnBook (std::string bookID); void requestBook (std::string patronID, std::string bookID); void incrementCurrentDate (); void payFine (std::string patronID, double payment); void viewPatronInfo (std::string patronID); void viewBookInfo (std::string bookID); }; #endif /* defined(__examples__Library__) */
true
d9f434a199c1b39ad97afa417038fca0845546df
C++
Sergio081096/Practica2-1
/Practica2-1/main.cpp
ISO-8859-1
3,604
2.84375
3
[]
no_license
//Semestre 2018-1 //************************************************************// //************************************************************// //************** Alumno (s): *********************************// //************* Cano Olguin Luis Sergio ******// //************* Version de trabajo Visual 2012 ******// //************************************************************// #include "Main.h" void InitGL ( GLvoid ) // Inicializamos parametros { //glShadeModel(GL_FLAT); // Habilitamos Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Negro de fondo //glClearDepth(1.0f); // Configuramos Depth Buffer //glEnable(GL_DEPTH_TEST); // Habilitamos Depth Testing //glDepthFunc(GL_LEQUAL); // Tipo de Depth Testing a realizar } void display ( void ) // Creamos la funcion donde se dibuja { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Limiamos pantalla y Depth Buffer glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Reinicializamos la actual matriz Modelview //Poner aqui codigo ha dibujar //glPointSize(10.0);//tamao del punto glBegin(GL_POLYGON);//pluar,puntos(GL_POINTS), lineas(GL_LINES), todos unicdos(GL_LINE_LOOP),triangulos(GL_TRIANGLES),poligono(GL_POLYGON) glColor3f(1.0,0.0,0.0);//desde aqui empieza el color y continua hasta que encuentre otro color glVertex3f(130.0,- 20.0, -1.2);//1 3 ejes de coordenadas ---flotantes glVertex3f(150.0, -90.0, -1.2);//2 glVertex3f(110.0, -90.0, -1.2);//10 glEnd();//termina glColor3f(1.0,1.0,0.0); glBegin(GL_POLYGON); glVertex3f(150.0, -90.0, -1.2);//2 glVertex3f(210.0, -90.0, -1.2);//3 glVertex3f(160.0, -130.0, -1.2);//4 glEnd(); glColor3f(0.0,0.0,1.0); glBegin(GL_POLYGON); glVertex3f(160.0, -130.0, -1.2);//4 glVertex3f(180.0, -200.0, -1.2);//5/* glVertex3f(130.0, -160.0, -1.2);//6 glEnd(); glColor3f(0.0,1.0,0.0); glBegin(GL_POLYGON); glVertex3f(130.0, -160.0, -1.2);//6 glVertex3f(80.0, -200.0, -1.2);//7 glVertex3f(100.0, -130.0, -1.2);//8 glEnd(); glColor3f(1.0,0.0,1.0); glBegin(GL_POLYGON); glVertex3f(100.0, -130.0, -1.2);//8 glVertex3f(50.0, -90.0, -1.2);//9 glVertex3f(110.0, -90.0, -1.2);//10 glEnd();//termina*/ glFlush(); } void reshape ( int width , int height ) // Creamos funcion Reshape { if (height==0) // Prevenir division entre cero { height=1; } glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); // Seleccionamos Projection Matrix glLoadIdentity(); // Ortogonal glOrtho(0,250,-250,0,0.1,2);//dimenciones //horizontal, vertical,--- glMatrixMode(GL_MODELVIEW); // Seleccionamos Modelview Matrix glLoadIdentity(); } // Termina la ejecucion del programa cuando se presiona ESC void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; } glutPostRedisplay(); } int main ( int argc, char** argv ) // Main Function { glutInit (&argc, argv); // Inicializamos OpenGL glutInitDisplayMode (GLUT_RGBA | GLUT_SINGLE); // Display Mode (Clores RGB y alpha | Buffer Sencillo ) glutInitWindowSize (500, 500); // Tamao de la Ventana glutInitWindowPosition (0, 0); //Posicion de la Ventana glutCreateWindow ("Practica 2"); // Nombre de la Ventana InitGL (); // Parametros iniciales de la aplicacion glutDisplayFunc ( display ); //Indicamos a Glut funcin de dibujo glutReshapeFunc ( reshape ); //Indicamos a Glut funcin en caso de cambio de tamano glutKeyboardFunc (keyboard); //Indicamos a Glut funcin de manejo de teclado glutMainLoop ( ); // return 0; }
true
96c315bd50762730a101989bb81386ccce837403
C++
mrjvs/42-ft_containers
/tests/_includes/multiset_test.hpp
UTF-8
3,876
2.96875
3
[]
no_license
// // Created by jelle on 4/23/2021. // #include "main.hpp" #include <map> template <class T, class PairCIt> class multiset_tests { private: int num; void compareSet(const T &list, const std::string &result) { std::stringstream ss; int i = 0; for (typename T::const_iterator it = list.begin(); it != list.end(); ++it) { if (i != 0) ss << "-"; ss << "(" << *it << ")"; ++i; } if (ss.str() != result) fail_test(); } void constructTests() { test("Basic constructor tests"); { std::vector<int> vect; vect.push_back(5); vect.push_back(1); T l1; T l2(vect.begin(), vect.end()); T l3; l3 = l2; T l4(l2); l4.insert(3); compareSet(l1, ""); compareSet(l2, "(1)-(5)"); compareSet(l3, "(1)-(5)"); compareSet(l4, "(1)-(3)-(5)"); } end_test(); } void modifierTests() { test("insert iterator tests"); { T l1; l1.insert(3); std::vector<int> vect; vect.push_back(5); vect.push_back(1); l1.insert(vect.begin(), vect.end()); compareSet(l1, "(1)-(3)-(5)"); } end_test(); test("erase key tests"); { T l1; l1.insert(l1.begin(), 3); l1.insert(5); l1.insert(5); l1.insert(9); compareSet(l1, "(3)-(5)-(5)-(9)"); l1.erase(5); compareSet(l1, "(3)-(9)"); l1.erase(l1.begin()); compareSet(l1, "(9)"); l1.erase(42); compareSet(l1, "(9)"); l1.insert(5); l1.erase(l1.begin(), l1.end()); compareSet(l1, ""); } end_test(); } void operationTests() { test("find/count tests"); { T l1; const T &l2 = l1; T l3; const T &l4 = l3; l1.insert(3); l1.insert(5); l1.insert(5); l1.insert(9); compareSet(l1, "(3)-(5)-(5)-(9)"); // find tests if (l2.find(9) != --(l2.end())) fail_test(); if (l2.find(5) != ++(l2.begin())) fail_test(); // empty/nonexistent find if (l3.find(5) != l4.end()) fail_test(); if (l2.find(1) != l2.end()) fail_test(); // count tests if (l1.count(3) != 1) fail_test(); if (l1.count(5) != 2) fail_test(); if (l1.count(1) != 0) fail_test(); if (l2.count(3) != 1) fail_test(); if (l2.count(5) != 2) fail_test(); if (l2.count(1) != 0) fail_test(); if (l3.count(1) != 0) fail_test(); } end_test(); test("upper/lower/equal find tests"); { T l1; const T &l2 = l1; l1.insert(3); l1.insert(5); l1.insert(5); l1.insert(9); // lower bound tests if (l2.lower_bound(9) != --(l2.end())) fail_test(); if (l2.lower_bound(5) != ++(l2.begin())) fail_test(); if (l2.lower_bound(1) != l2.begin()) fail_test(); // upper bound tests if (l2.upper_bound(9) != l2.end()) fail_test(); if (l2.upper_bound(5) != ++ ++ ++(l2.begin())) fail_test(); if (l2.upper_bound(1) != l2.begin()) fail_test(); // equal range if (l2.equal_range(9) != PairCIt(--(l2.end()), l2.end())) fail_test(); if (l2.equal_range(5) != PairCIt(++(l2.begin()), --(l2.end()))) fail_test(); if (l2.equal_range(1) != PairCIt(l2.begin(), l2.begin())) fail_test(); } end_test(); } // calling these functions will make the template functions run at least once, so they dont have runtime errors void executionNonUsedTests() { test("other tests"); { T l1; const T &l2 = l1; T l3; // iterators (void) l1.begin(); (void) l1.rbegin(); (void) l1.end(); (void) l1.rend(); (void) l2.begin(); (void) l2.rbegin(); (void) l2.end(); (void) l2.rend(); // capacity (void) l1.empty(); (void) l1.size(); (void) l1.max_size(); // modifiers l1.clear(); l1.swap(l3); // observers (void) l1.key_comp(); (void) l1.value_comp(); (void) l1.get_allocator(); } end_test(); } public: // only test things that are different from orderedList void run() { start_batch("multiset"); constructTests(); modifierTests(); operationTests(); executionNonUsedTests(); } };
true
9865d32a4644fcdec7b93c417c5c7d4608a54cee
C++
alashworth/leetcode
/src/leetcode/0002-add-two-numbers.cpp
UTF-8
1,665
3.5625
4
[]
no_license
#include <doctest/doctest.h> #include <vector> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x) , next(nullptr) { } }; ListNode* add_aux(ListNode* l1, ListNode* l2, int c) { if (l1 == nullptr && l2 == nullptr) { if (c > 0) { auto v = new ListNode(c); return v; } return nullptr; } else if (l1 != nullptr && l2 == nullptr) { int rv = l1->val + c; c = 0; while (rv >= 10) { rv -= 10; c += 1; } auto v = new ListNode(rv); v->next = add_aux(l1->next, nullptr, c); return v; } else if (l1 == nullptr && l2 != nullptr) { int rv = l2->val + c; c = 0; while (rv >= 10) { rv -= 10; c += 1; } auto v = new ListNode(rv); v->next = add_aux(nullptr, l2->next, c); return v; } else { /* l1 != nullptr && l2 != nullptr */ int rv = l1->val + l2->val + c; c = 0; while (rv >= 10) { rv -= 10; c += 1; } auto v = new ListNode(rv); v->next = add_aux(l1->next, l2->next, c); return v; } } ListNode* add_two_numbers(ListNode* l1, ListNode* l2) { return add_aux(l1, l2, 0); } TEST_CASE("2: solution passes example") { ListNode a1(2), a2(4), a3(3); ListNode b1(5), b2(6), b3(4); a1.next = &a2; a2.next = &a3; b1.next = &b2; b2.next = &b3; auto result = add_two_numbers(&a1, &b1); REQUIRE_EQ(result->val, 7); REQUIRE_EQ(result->next->val, 0); REQUIRE_EQ(result->next->next->val, 8); REQUIRE_EQ(result->next->next->next, nullptr); } TEST_CASE("2: handle carry list expansion") { ListNode a1(5), b1(5); auto result = add_two_numbers(&a1, &b1); REQUIRE_EQ(result->val, 0); REQUIRE_NE(result->next, nullptr); REQUIRE_EQ(result->next->val, 1); }
true
046f8f8b7d22d648169b968742257f593739a31a
C++
Ripley6811/EvoGyre-CPP
/Spaceship/Tactical.h
UTF-8
1,159
3.015625
3
[]
no_license
#ifndef _TACTICAL #define _TACTICAL #include "../Engine/Vector3.h" #include "../EvoGyre/Weapons.h" #include "../EvoGyre/BulletManager.h" #include <string> using namespace std; /** * Tactical management class. Weapons and shields. */ class Tac { public: Tac(); Tac(float _hull, float _shield); ~Tac() {} void shield_damage(int amount); void shield_repair(int amount); void hull_damage(int amount); void hull_repair(int amount); void SetWeaponSelection(int newSelection); void SetShield(float val); float GetShield(); void SetHull(float val); float GetHull(); // The order layouts are added correspond to 'weaponSelection'. int AddWeaponSystem(weaponSystem x); // Returns false if weapon is still in cooldown phase. bool FireWeapon(const Vector3 & pos); // True if weapon ready. Delta-time used for cooldown timer. bool Update(double dt); void Render(); protected: private: float hull; float shield; // Weapon is ready to fire when cooldown is zero. float weaponCooldown; // Corresponds to added weapon systems. int weaponSelection; vector<weaponSystem> weaponSystems; BulletManager bulletManager; }; #endif // !_TACTICAL
true
2bb25787caed273baed239a9323edd05c7010422
C++
nachomonllor/Hackerearth
/Moriarty and the City.cpp
UTF-8
826
2.84375
3
[]
no_license
 #include <iostream> #include <stdio.h> using namespace std; int main() { int n; scanf("%d", &n); //int[] arr = { 1, 1, 1, 1, 1 }; int arr[n]; for(int i =0; i<n; i++) { scanf("%d", &arr[i]); } long unos = 0, max_unos = 0, ceros = 0, max_ceros = 0; for (int i = 0; i < n; i++){ if (arr[i] == 1) { unos++; max_ceros = max(ceros, max_ceros); ceros = 0; } else{ max_unos = max(unos, max_unos); unos = 0; ceros++; } } max_ceros = max(ceros, max_ceros); max_unos = max(unos, max_unos); //Console.WriteLine("max unos = {0}, max ceros = {1}", max_unos, max_ceros); printf("%d\n", max(max_ceros, max_unos)); //system("pause"); return 0; }
true
33cceac16b5b05920d3f05d56f1408ba9adf88e0
C++
ajpauwels/FingerprintScanner_GT511C1R
/FingerprintModule.h
UTF-8
6,997
2.53125
3
[ "MIT" ]
permissive
#ifndef FINGERPRINT_MODULE_H #define FINGERPRINT_MODULE_H /* Includes */ #include <Arduino.h> /* Symbolic constants */ // Symbolically define the serial interface to easily switch between Serial (HW or SW) #define COMMS Serial1 // The maximum number of times to re-try for a response packet before failing // Each try introduces a waiting period defined by WAITTIME // The maximum execution time for a command in milliseconds is therefore TIMEOUT * WAITTIME #define TIMEOUT 11 // The amount of time to wait between each response retry, in milliseconds #define WAITTIME 500 // Commonly used bytes for all packets #define DEVICE_ID_MSB 0x00 #define DEVICE_ID_LSB 0x01 // Commonly used command packet bytes #define CMD_START_CODE_1 0x55 #define CMD_START_CODE_2 0xAA // Commonly used response packet bytes #define RES_START_CODE_1 0x55 #define RES_START_CODE_2 0xAA // Commonly used data packet bytes #define DATA_START_CODE_1 0x5A #define DATA_START_CODE_2 0xA5 // Define packet sizes in bytes #define CMD_PKT_SIZE 12 #define RESP_PKT_SIZE 12 #define DATA_PKT_MAX_SIZE 51846 // The maximum possible size of a data packet #define DATA_PKT_ADD 6 // The size of the non-variable part of the data packet // Uncomment if you want debug messages printed to the USB serial monitor #define DEBUG /* Enumerations */ // Command codes enum COMMAND { CMD_OPEN = 0x01, // Initialize the fingerprint module CMD_CLOSE = 0x02, // Terminate the fingerprint module CMD_USB_INTERNAL_CHECK = 0x03, // Check if the connected USB device is valid (only for USB comms) CMD_CHANGE_BAUDRATE = 0x04, // Change the UART baudrate CMD_SET_IAP_MODE = 0x05, // Enter IAP mode (for firmware upgrade) CMD_CMOS_LED = 0x12, // Control the CMOS LED CMD_GET_ENROLL_COUNT = 0x20, // Get the number of enrolled fingerprints CMD_CHECK_ENROLLED = 0x21, // Check if given ID is enrolled CMD_ENROLL_START = 0x22, // Start enrolling CMD_ENROLL1 = 0x23, // 1st enrollment template (ENROLL_START -> ENROLL1) CMD_ENROLL2 = 0x24, // 2nd enrollment template (ENROLL_START -> ENROLL1 -> ENROLL2) CMD_ENROLL3 = 0x25, // 3rd enrollment template (ENROLL_START -> ENROLL1 -> ENROLL2 -> ENROLL3) CMD_IS_PRESS_FINGER = 0x26, // Check if a finger is on the sensor CMD_ACK = 0x30, // Acknowledge response (OK) CMD_NACK = 0x31, // Non-acknowledge response (ERROR) CMD_DELETE_ID = 0x40, // Delete fingerprint with specified ID CMD_DELETE_ALL = 0x41, // Delete all fingerprints CMD_VERIFY = 0x50, // Verify if captured print matches template with specified ID (1:1) CMD_IDENTIFY = 0x51, // Identify captured fingerprint (1:N) CMD_VERIFY_TEMPLATE = 0x52, // Verify the given fingerprint template matches the template with specified ID (1:1) CMD_IDENTIFY_TEMPLATE = 0x53, // Identify the given fingerprint template (1:N) CMD_CAPTURE_FINGER = 0x60, // Capture a fingerprint image if finger is pressed and store in RAM CMD_MAKE_TEMPLATE = 0x61, // Make template based off of previous CAPTURE_FINGER call and transmit CMD_GET_IMAGE = 0x62, // Transmit fingerprint image captured with CAPTURE_FINGER CMD_GET_RAW_IMAGE = 0x63, // Capture image (regardless of whether finger is placed) and transmit CMD_GET_TEMPLATE = 0x70, // Retrieve template with specified ID CMD_SET_TEMPLATE = 0x71, // Set template with specified ID to be new uploaded template }; // Whether or not the command and subsequent reply was successful enum RESPONSE { ACK = 0x30, NACK = 0x31 }; // Error codes for when response packet is NACK or no packet was received enum RESPONSE_ERROR { NACK_NOT_RECVD = 0x0001, // No response packet was received NACK_INVALID_ENROLLMENT_STAGE = 0x0002, // The stage of enrollment is not between 0 and 2 NACK_INVALID_POS = 0x1003, // Specified ID not between 0-19 NACK_IS_NOT_USED = 0x1004, // Specified ID is not in use NACK_IS_ALREADY_USED = 0x1005, // Specified ID is already in use NACK_COMM_ERR = 0x1006, // Communications error NACK_VERIFY_FAILED = 0x1007, // A 1:1 verification failed NACK_IDENTIFY_FAILED = 0x1008, // A 1:N identification failed NACK_DB_IS_FULL = 0x1009, // Database is full NACK_DB_IS_EMPTY = 0x100A, // Database is empty NACK_BAD_FINGER = 0x100C, // Fingerprint quality is too low NACK_ENROLL_FAILED = 0x100D, // Enrollment failed NACK_IS_NOT_SUPPORTED = 0x100E, // The command is not supported NACK_DEV_ERR = 0x100F, // Device error NACK_INVALID_PARAM = 0x1011, // Invalid parameter NACK_FINGER_IS_NOT_PRESSED = 0x1012, // Finger is not pressed NACK_BAD_HEADER = 0x1013, // Packet header is incorrect NACK_BAD_ID = 0x1014, // Device ID in packet does not match desired device ID NACK_BAD_CHKSUM = 0x1015 // Given checksum does not match computed checksum }; // The different states the fingerprint module can be in during enrolling enum ENROLL_STATE { START, CAPTURE, ENROLL, COMPLETE, REMOVE_FINGER }; /* Type definitions */ // Check if byte, word, and dword are defined, define them if not #ifndef byte typedef unsigned char byte; #endif #ifndef word typedef uint16_t word; #endif #ifndef dword typedef uint32_t dword; #endif // Used in enrollSequence, defines a type for a lambda function given to write to an output typedef void (*writeFunc)(const char* str); /* Class definition */ class FingerprintModule { private: byte mRespPkt[RESP_PKT_SIZE]; // Buffer to hold the response packet byte mDataPkt[DATA_PKT_MAX_SIZE]; // Buffer to hold data packets bool mRespStatus; // Holds whether an ACK or NACK was received dword mRespParam; // Holds the response parameter: either an error code or a response param uint8_t mEnrollmentStage; // Used during enrollment, keeps track of if this is the first, second, or third fingerprint image word flipEndianness(word); dword flipEndianness(dword); void split(word, byte*); void split(dword, byte*); word computeCheckSum(byte*, uint32_t); bool send(word, dword param = 0x00000000, bool isBigEndian = true); bool sendDataPkt(); bool recvResponsePkt(); bool recvDataPkt(uint32_t size); public: FingerprintModule(); ~FingerprintModule(); dword getResponseParam(); dword getErrorCode(); bool getResponseStatus(); String strFromError(word); bool enrollSequence(uint32_t, writeFunc out = 0x00); bool open(bool errChk = true); bool close(); bool powerCMOS(bool); bool changeBaudrate(uint32_t); bool getEnrollCount(); bool isIDEnrolled(uint32_t); bool startEnrollment(uint32_t); bool createEnrollmentTemplate(); bool isFingerPressed(); bool captureFingerprint(bool highQual = false); bool deleteID(uint32_t); bool deleteAll(); bool verify(uint32_t); bool identify(); bool verifyTemplate(uint32_t, byte[]); bool identifyTemplate(byte[]); }; #endif
true
c7e52ec27ce3edaa91a48b0a9ee9c47436fb026b
C++
shadlyd15/CSiS
/Modern_Programming/Exercises/exercise_5.cpp
UTF-8
272
2.828125
3
[ "MIT" ]
permissive
/* Exercise : 5 * ID : 1943290 * Name : Shadly Salahuddin */ #include <iostream> #include <iomanip> using namespace std; int main() { for (int i = 1; i < 20; ++i) { if(i&1) { cout << setw(i) << setfill('*') << "" << endl; } } return 0; }
true
0248027c2944c38bafde93c58427d3cd26d9068d
C++
Jae-Hyun-Park/Tutorial_Test
/Data structure/Stack_Head.cpp
UTF-8
1,891
3.921875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; struct Node *top = NULL; struct Node *stack = NULL; int Count = -1; void Interval() { printf("------------------------------------\n"); } void Push(int x) { struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = x; temp->next = top; top = temp; Count++; return; } void Pop() { struct Node* temp; if (top == NULL) { printf("Err!\n"); Interval(); return; } temp = top; top = temp->next; free(temp); Count--; return; } void Top() { stack = top; if (top == NULL) { printf("현재 스택의 top은 %d번지에 있으며, 안에 들어있는 값은 없습니다.\n", top); Interval(); return; } printf("현재 스택의 TOP은 %d번지에 있으며, 안에 들어있는 값은 %d 입니다.\n", Count, stack->data); Interval(); return; } void Print() { stack = top; while (stack != NULL) { printf("%d\n", stack->data); stack = stack->next; } Interval(); return; } void isEmpty() { stack = top; if (top == NULL) { printf("현재 스택은 비어있는 상태입니다.\n"); Interval(); return; } printf("현재 스택은 비어있지 않으며, %d개의 데이터가 들어있습니다.\n", Count + 1); Interval(); return; } void main() { int s, x = 0; while (1) { printf("번호를 선택하여 주십시오.\n 1: PUSH\n 2. POP\n 3. TOP\n 4. ISEmpty\n 5. EXIT\n"); scanf("%d", &s); Interval(); switch (s) { case 1: printf("입력할 데이터를 적어주십시오.\n"); scanf("%d", &x); Interval(); Push(x); Print(); break; case 2: Pop(); Print(); break; case 3: Top(); break; case 4: isEmpty(); break; case 5: return; default: printf("값을 잘못 입력하였습니다! 다시입력해주십시오\n"); Interval(); break; } } }
true
2c2ba185cf3a56076c496f50d0c30cad56cd7f1b
C++
lufovic77/AlgorithmStudy
/backtracking/2580.cpp
UHC
1,371
3.015625
3
[]
no_license
#include <iostream> #include <cstdio> #include <vector> #include <stdlib.h> using namespace std; typedef struct{ int x; int y; }POS; int len; vector <POS> q; bool check(int x, int y, int num, int map[][10]){ //簢 üũ int a = x/3; int b = y/3; a *=3; b *=3; for(int i=a;i<a+3;i++){ for(int j=b;j<b+3;j++){ if(i == x && j == y){ continue; } if(map[i][j]==num){ return false; } } } // / üũ for(int i=0;i<9;i++){ if( i ==y) continue; if(num == map[x][i]) return false; } for(int i=0;i<9;i++){ if( i ==x) continue; if( num == map[i][y]) return false; } return true; } void backtracking(int map[][10],int index){ if(index>=len){ cout<<endl; for(int i=0;i<9;i++){ for(int j=0;j<9;j++) cout<<map[i][j]<<" "; cout<<endl; } exit(0); return ; } POS temp ; temp = q[index]; int a = temp.x; int b = temp.y; int flag = 0; for(int i=1;i<=9;i++){ map[a][b] = i; if(check(a, b, i, map)==true){ flag =1; backtracking(map,index+1); map[a][b]=0; } else{ map[a][b]=0; continue; } } return ; } int main(){ int a; int map[10][10]; for(int i=0;i<9;i++){ for(int j=0;j<9;j++){ cin>>a; if(a == 0){ POS temp ; temp.x = i; temp.y = j; q.push_back(temp); } map[i][j] = a; } } len = q.size(); backtracking(map,0); }
true
b0a0bdee6db0db7e17cf6b3a1a9531af3b456e53
C++
mimseong/BaekJoon
/1100.cpp
UTF-8
343
2.875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { int count = 0; for(int i = 0; i < 8; i++){ string s; cin >> s; for(int j = 0; j < 8; j++){ if(s[j] == 'F' && (i+j) % 2 == 0) count++; } } printf("%d", count); return 0; }
true
0bb6a4f26fb2740f512a1890b42dbb8bb188c11b
C++
tdwong/leetcode
/c++_434_number-of-segments-in-a-string.cpp
UTF-8
1,722
3.609375
4
[]
no_license
/* //https://leetcode.com/contest/leetcode-weekly-contest-11/problems/number-of-segments-in-a-string/ # # 434. Number of Segments in a String # # Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters. # # Please note that the string does not contain any non-printable characters. # # Example: # # Input: "Hello, my name is John" # # Output: 5 # */ #include <iostream> //#include <string> //using namespace std; /* 0 for all test leetcode cases 38.46% leetcode ranking */ class Solution { public: int countSegments(std::string s) { int count = 0; int cip = 0; for (int ix = 0; ix < s.size(); ix++) { if (!isspace(s[ix])) { if (cip == 0) { cip++; count++; } } else { cip = 0; } } //std::cout << count << std::endl; return count; } }; void checkSolution(std::string s, int expected) { Solution solution; int ret = solution.countSegments(s); std::string retstr = (ret == expected) ? "ok" : "<-- wrong"; std::cout << "s='" << s << "', ret: " << ret << ", expected: " << expected << "\t" << retstr << std::endl; } int main() { checkSolution("Hello, my name is John", 5); checkSolution(" leading spaces line", 3); checkSolution("trailing spaces line ", 3); checkSolution(" spaces on both ends ", 4); checkSolution("extra spaces in between words ", 5); checkSolution(" combination in word spacing ", 4); checkSolution("", 0); checkSolution(" ", 0); // return 0; }
true
83c6e312ad274e071738699ce536685cebe47130
C++
clhongooo/trading_engine
/src/main/unit_tests/UnitTest/ut-cdq.hpp
UTF-8
6,945
2.71875
3
[]
no_license
#include "UTest.h" #include "Math/RandomEngine.h" #include "Math/CirDataQue.hpp" #include <iostream> using namespace std; int TestCDQ() { UTest ut; CirDataQue<double> cb1; ut.AssertF(cb1.Ready(), __FILE__,__FUNCTION__,__LINE__); for (int i = 0; i < 10; i++) cb1.Add(10); ut.AssertF(cb1.Ready(), __FILE__,__FUNCTION__,__LINE__); //Half full cb1.Reset(3,true); cb1.Add(876); cb1.Add(9869); ut.AssertF(cb1.Count() != 2, __FILE__,__FUNCTION__,__LINE__); //Get half full array int iSize=0; const double *da; da = cb1.GetArrayUnord(iSize); ut.AssertF(da[0] != 876, __FILE__,__FUNCTION__,__LINE__); ut.AssertF(da[1] != 9869, __FILE__,__FUNCTION__,__LINE__); ut.AssertF(iSize != 2, __FILE__,__FUNCTION__,__LINE__); //Test cycle cb1.Add(234123); cb1.Add(30247); cb1.Add(8946); ut.AssertF(cb1.Count() != 3, __FILE__,__FUNCTION__,__LINE__); const double *db = cb1.GetArrayUnord(iSize); ut.AssertF(db[0] != 30247, __FILE__,__FUNCTION__,__LINE__); ut.AssertF(db[1] != 8946, __FILE__,__FUNCTION__,__LINE__); ut.AssertF(db[2] != 234123, __FILE__,__FUNCTION__,__LINE__); ut.AssertF(iSize != 3, __FILE__,__FUNCTION__,__LINE__); //Stress test cb1.Reset(100,true); RandomEngine re = RandomEngine::Instance(); for (int i = 0; i < 100000; i++) cb1.Add(re.NextInt(1,1000)); ut.AssertF(cb1.Count() != 100, __FILE__,__FUNCTION__,__LINE__); //Test erroneous input cb1.Reset(2,true); cb1.Add(-4); cb1.Add(-4.5); cb1.Add(0.00000001); ut.AssertF(cb1.Count() != 0, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, no opulent vector cb1.Reset(10,true); for (int i = 1; i < 77; i++) cb1.Add(i); const double *da2 = cb1.GetArrayInInsOrd(); ut.Assert(da2[0] == 67, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[1] == 68, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[2] == 69, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[3] == 70, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[4] == 71, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[5] == 72, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[6] == 73, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[7] == 74, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[8] == 75, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da2[9] == 76, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, with opulent vector cb1.Reset(10,55,true); for (int i = 1; i < 77; i++) cb1.Add(i); const double *db2 = cb1.GetArrayInInsOrd(); ut.Assert(db2[0] == 67, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[1] == 68, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[2] == 69, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[3] == 70, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[4] == 71, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[5] == 72, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[6] == 73, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[7] == 74, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[8] == 75, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db2[9] == 76, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, no opulent vector //not completely filled, throw exception cb1.Reset(10,true); for (int i = 1; i < 3; i++) cb1.Add(i); const double *da3 = 0; // try { da3 = cb1.GetArrayInInsOrd(); ut.FailIfReached(__FILE__,__FUNCTION__,__LINE__); } catch (exception& e) {} ut.Assert(da3 == NULL, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, with opulent vector //not completely filled, throw exception cb1.Reset(10,55,true); for (int i = 1; i < 3; i++) cb1.Add(i); const double *db3 = 0; // try { db3 = cb1.GetArrayInInsOrd(); ut.FailIfReached(__FILE__,__FUNCTION__,__LINE__); } catch (exception& e) {} ut.Assert(db3 == NULL, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, no opulent vector //more tests, cir array ptr == 0 cb1.Reset(5,true); for (int i = 1; i < 4556; i++) cb1.Add(i); const double *da4 = cb1.GetArrayInInsOrd(); ut.Assert(da4[0] == 4551, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da4[1] == 4552, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da4[2] == 4553, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da4[3] == 4554, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da4[4] == 4555, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, with opulent vector //more tests, cir array ptr == 0 cb1.Reset(5, 911,true); for (int i = 1; i < 4554; i++) cb1.Add(i); cb1.Add(4554); ut.Assert(cb1.CirPsn() == 910, __FILE__,__FUNCTION__,__LINE__); cb1.Add(4555); ut.Assert(cb1.CirPsn() == 0, __FILE__,__FUNCTION__,__LINE__); const double *db4 = cb1.GetArrayInInsOrd(); ut.Assert(db4[0] == 4551, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db4[1] == 4552, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db4[2] == 4553, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db4[3] == 4554, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db4[4] == 4555, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, no opulent vector //more tests, 1 item dangling cb1.Reset(5,true); for (int i = 1; i < 4554; i++) cb1.Add(i); cb1.Add(4554); ut.Assert(cb1.CirPsn() == 4, __FILE__,__FUNCTION__,__LINE__); cb1.Add(4555); ut.Assert(cb1.CirPsn() == 0, __FILE__,__FUNCTION__,__LINE__); cb1.Add(4556); ut.Assert(cb1.CirPsn() == 1, __FILE__,__FUNCTION__,__LINE__); const double *da5 = cb1.GetArrayInInsOrd(); ut.Assert(da5[0] == 4552, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da5[1] == 4553, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da5[2] == 4554, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da5[3] == 4555, __FILE__,__FUNCTION__,__LINE__); ut.Assert(da5[4] == 4556, __FILE__,__FUNCTION__,__LINE__); //GetArrayInInsOrd, with opulent vector //more tests, 1 item dangling cb1.Reset(5, 911,true); for (int i = 1; i < 4554; i++) cb1.Add(i); cb1.Add(4554); ut.Assert(cb1.CirPsn() == 910, __FILE__,__FUNCTION__,__LINE__); cb1.Add(4555); ut.Assert(cb1.CirPsn() == 0, __FILE__,__FUNCTION__,__LINE__); cb1.Add(4556); ut.Assert(cb1.CirPsn() == 1, __FILE__,__FUNCTION__,__LINE__); const double *db5 = cb1.GetArrayInInsOrd(); ut.Assert(db5[0] == 4552, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db5[1] == 4553, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db5[2] == 4554, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db5[3] == 4555, __FILE__,__FUNCTION__,__LINE__); ut.Assert(db5[4] == 4556, __FILE__,__FUNCTION__,__LINE__); //GetArrayUnord ok if no opulent vector cb1.Reset(5,true); try { const double *da6 = cb1.GetArrayUnord(iSize); if (da6 != NULL) da6 = NULL; //dummy use to avoid compiler warning } catch (exception& e) { ut.FailIfReached(__FILE__,__FUNCTION__,__LINE__); } //GetArrayUnord doesn't support opulent vector cb1.Reset(5,10,true); // try { // const double *da6 = cb1.GetArrayUnord(iSize); // ut.FailIfReached(__FILE__,__FUNCTION__,__LINE__); // if (da6 != NULL) da6 = NULL; //dummy use to avoid compiler warning // } catch (exception& e) {} const double *da6 = cb1.GetArrayUnord(iSize); ut.Assert(da6 == NULL, __FILE__,__FUNCTION__,__LINE__); ut.PrintResult(); return 0; }
true
eddc78b670f0cac4322b26d079559aea16ac2df0
C++
aseppmaulana/Matriks
/Matriks_penjumlahan.cpp
UTF-8
594
2.671875
3
[]
no_license
#include <iostream> using namespace std; int main () { int M[3][3]; int M1[3][3]; int M2[3][3]; for ( int i = 0 ; i < 3 ; i++){ for ( int j = 0; j < 3 ; j++){ cout << "masukkan data baris ke " << "[" <<i<< "]" << " kolom ke " << "[" <<j<< cin >> M1[i][j]; cout << "masukkan data baris ke " << "[" <<i<< "]" << " kolom ke " << "[" <<j<< cin >> M2[i][j]; M[i][j] = M1[i][j] + M2[i][j]; } } for ( int i = 0 ; i< 3 ; i++){ cout << "___________" << endl; for ( int j = 0 ; j < 3 ; j++){ cout << M[i][j] << " | " ; } cout << endl; } cout << "___________" ; return 0 ; }
true
a90a54fa19c62cf406d2071c6a80e534cd242d92
C++
trando46/Projects
/lab4/lab4.cpp
UTF-8
2,334
4.03125
4
[]
no_license
// Bao Tran Do // File: lab4.cpp // October 12, 2020 // Purpose: The purpose for this is to reused the same code from the LinkList // class but for different data types and to display the last negative // value entered. // INPUT: none // OUTPUT: Display the LinkedList contents and the last negative number #include <iostream> #include "LinkedList.h" using namespace std; void callingDouble(); // This function instantiate the LinkList class for data type that is double. // Append any value double value to the LinkedList, print out the content of the // content of the list and display the last negative value entered // IN: none // MODIFY: none // OUTPUT: none void callingInt(); // This function instantiate the LinkList class for data type that is double. // Append any value double value to the LinkedList, print out the content of the // content of the list and display the last negative value entered // IN: none // MODIFY: none // OUTPUT: none // Main application method int main() { //Calling the functions for int and doubles callingInt(); cout << "-------------------------------------------------" << endl; callingDouble(); return 0; } void callingDouble(){ //Creating a linked list that takes the doubles LinkedList<double> listDouble; cout << "DOUBLES" << endl; cout << "Adding -3.2, 2.14, -5.7, -12.01, -2.99, 4.6, 5.2..." << endl; listDouble.appendNode(-3.2); listDouble.appendNode(2.14); listDouble.appendNode(-5.7); listDouble.appendNode(-12.01); listDouble.appendNode(-2.99); listDouble.appendNode(4.6); listDouble.appendNode(5.2); // print list cout << "Linked list contents: " << listDouble.to_string(); cout << "Last negative number: " << listDouble.getLastNegative() << endl; } void callingInt(){ //Creating a linked list that takes the integers LinkedList<int> listInt; cout << "INTEGERS" << endl; cout << "Adding 3, -2, 5, 12, -2, -4, 5...\n"; listInt.appendNode(3); listInt.appendNode(-2); listInt.appendNode(5); listInt.appendNode(12); listInt.appendNode(-2); listInt.appendNode(-4); listInt.appendNode(5); // print list cout << "Linked list contents: " << listInt.to_string(); cout << "Last negative number: " << listInt.getLastNegative() << endl; }
true
05e9dd9e6aa9cdee4e2bace02e7abfee13c6de3b
C++
atafoa/oopSamples
/Homework 7/full_credit/aaa2575_Powered_Arm.h
UTF-8
481
2.703125
3
[]
no_license
#ifndef POWERED_ARM_H #define POWERED_ARM_H #include "aaa2575_Arm_Robot.h" using namespace std; class Powered_Arm : public virtual Arm_Robot { public: Powered_Arm(int mn, string n, int bl, int l, int wl, int ml, string t) : motor_limit(ml), motor_on(false), Robot(mn, n, bl, t), Arm_Robot(mn, n, bl, l, wl, t) {}; bool move(int x, int y); bool pick_up(int weight); bool drop(); protected: int motor_limit; bool motor_on; void power_on(); void power_off(); }; #endif
true
36719723920e4e72f095a82a111908c649adaf52
C++
berdoezt/TOKI
/Training/kompetitif/matdis/bagi.cpp
UTF-8
381
2.8125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; long long int gcd(long long int a, long long int b) { if(b == 0) return a; else return gcd(b, a % b); } int main() { long long int A, B, C, D; long long int E, F; long long int temp; cin >> A >> B >> C >> D; E = A * D + B * C; F = B * D; temp = gcd(E, F); cout << E / temp << " " << F / temp << endl; return 0; }
true
5aeb707acb04bbaf27d45c6115a06d5a2cbc8110
C++
matsumoto0112/DXR
/Application/Application/Source/DX/Raytracing/DXRDevice.h
SHIFT_JIS
1,229
2.671875
3
[]
no_license
/** * @file DXRDevice.h * @brief DXRpfoCXǗ */ #pragma once #include "DX/DeviceResource.h" namespace Framework::DX { /** * @class DXRDevice * @brief DXRpfoCX */ class DXRDevice { public: /** * @brief RXgN^ */ DXRDevice(); /** * @brief fXgN^ */ ~DXRDevice(); /** * @brief foCX̃Zbg */ void reset(); /** * @brief foCX̐ */ void create(ID3D12Device* device, ID3D12GraphicsCommandList* commandList); /** * @brief foCX̎擾 */ ID3D12Device5* getDXRDevice() const { return mDXRDevice.Get(); } /** * @brief R}hXg̎擾 */ ID3D12GraphicsCommandList5* getDXRCommandList() const { return mDXRCommandList.Get(); } private: Comptr<ID3D12Device5> mDXRDevice; //!< DXRɑΉfoCX Comptr<ID3D12GraphicsCommandList5> mDXRCommandList; //!< DXRɑΉR}hXg }; } // namespace Framework::DX
true
6d3e4ac23bfd716bae37efecb8ceabf9d1ea0082
C++
sasaxopajic/OOP
/Preklapanje operatora 2/main/main/main.cpp
UTF-8
1,191
3.3125
3
[]
no_license
#include "intarray.hpp" int main() { const int a1[] = { 1,2,3,4,5 }; const int a2[] = { 6,7,8 }; const int a3[] = { 0,1,2,3,4,5,6,7,8,9 }; const int a4[] = { 100,101,102,103 }; IntArray ia0, ia1(a1, 5), ia2(a2, 3), ia3(a3, 10), ia4(a4, 4); cout << "ia0: " << ia0 << endl; cout << "ia1: " << ia1 << endl; cout << "ia2: " << ia2 << endl; cout << "ia3: " << ia3 << endl; cout << "ia4: " << ia4 << endl; IntArray ia5(ia0), ia6(ia1), ia7(ia2), ia8(ia3), ia9(ia4); cout << "ia5: " << ia5 << endl; cout << "ia6: " << ia6 << endl; cout << "ia7: " << ia7 << endl; cout << "ia8: " << ia8 << endl; cout << "ia9: " << ia9 << endl; cout << endl << "Testiranje +=" << endl; ia1 += ia2; ia3 += ia4; cout << "ia1: " << ia1 << endl; cout << "ia3: " << ia3 << endl; cout << endl << "Testiranje +" << endl; ia0 = ia5 + ia6; cout << "ia0: " << ia0 << endl; cout << endl << "Testiranje []" << endl; int x = ia1[5]; cout << "x=ia1[5] x: " << x << endl; cout << endl << "Testiranje ==, = i !=" << endl; cout << "ia4: " << ia4 << endl; cout << "ia9: " << ia9 << endl; cout << "ia4==ia9? " << (ia4 == ia9) << endl; cout << "ia4!=ia9? " << (ia4 != ia9) << endl; return 0; }
true
560e2ea68d1f573ede251dd7719938aef92d7b56
C++
desperadoespoir/TP_INF1010
/changeymindset_/ConsoleApplication1/Specialite.h
UTF-8
386
2.875
3
[]
no_license
#ifndef SPECIALITE_H #define SPECIALITE_H # include <string> using namespace std; class Specialite { public: Specialite(); Specialite(string domaine, int niveau); ~Specialite(); string getDomaine() const; void setDomaine(string domaine); int getNiveau() const ; void setNiveau(int niveau); private: string domaine_; int niveau_; }; #endif
true
bb1cd65ba90dd5c47dc00caa17a6fe621b89bb80
C++
zuselegacy/leetcode
/recursion_backtracking/78-subsets-dfs.cpp
UTF-8
476
2.734375
3
[]
no_license
class Solution { public: vector<vector<int>> soln; void generate(vector<int>& nums,vector<int>& result,int pos) { soln.push_back(result); for(int i=pos;i<nums.size();i++) { result.push_back(nums[i]); generate(nums,result,i+1); result.pop_back(); } } vector<vector<int>> subsets(vector<int>& nums) { vector<int> result; generate(nums,result,0); return soln; } };
true
9e5d71fee4b215489631f9ba83baf536126bf182
C++
Leo-Chen-CM/Completed-Games-and-Projects
/Cube Avoidance Sim 2k21/SFMLOpenGL/Player.cpp
UTF-8
891
2.953125
3
[]
no_license
#include "Player.h" Player::Player() { player_object = new GameObject; player_object->setPosition(vec3(0.5f, 0.8f, 4.0f)); } void Player::draw(GLint x_offsetID, GLint y_offsetID, GLint z_offsetID) { glUniform1f(x_offsetID, player_object->getPosition().x); glUniform1f(y_offsetID, player_object->getPosition().y); glUniform1f(z_offsetID, player_object->getPosition().z); glDrawElements(GL_TRIANGLES, 3 * INDICES, GL_UNSIGNED_INT, NULL); } void Player::move() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) { player_object->setPosition(player_object->getPosition() + (-movementSpeed)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) { player_object->setPosition(player_object->getPosition() + (movementSpeed)); } } GameObject Player::getPlayerObject() { return *player_object; } vec3 Player::getPlayerPosition() { return player_object->getPosition(); }
true
35650419daca7c332d2932afd9a74eec870f48db
C++
TaeYongHwang/HyHIT
/TaeWook/ch8. dynamic-programming/jumpgame_solution.cpp
UTF-8
716
2.96875
3
[]
no_license
#include <iostream> using namespace std; int n, board[100][100]; int cache[100][100]; int jump(int a, int b); int main() { int cases; int i, j, k; cin >> cases; for(i = 0; i < cases; i++) { cin >> n; for(j = 0; j < n; j++) { for(k = 0; k < n; k++) { int temp; cin >> temp; board[j][k] = temp; cache[j][k] = -1; } } if(jump(0, 0) == 1) { cout << "YES" << endl; } else { cout << "NO" << endl; } } } int jump(int a, int b) { if(a >= n || b >= n) { return 0; } if(a == n-1 && b == n-1) { return 1; } int& ret = cache[a][b]; if(ret != -1) { return ret; } int jump_size = board[a][b]; return ret = (jump(a, b+jump_size)) || (jump(a+jump_size, b)); };
true
b498ce800802b24df6499237cfc343242246a7d9
C++
JaeJang/COMP_3512_Lab3
/Matrix/Matrix/Matrix.hpp
UTF-8
996
3.0625
3
[]
no_license
#pragma once #include <iostream> class Matrix { public: Matrix(); explicit Matrix(int); Matrix(int*, int); Matrix(const Matrix&); ~Matrix(); void set_value(const int, const int, const int); int get_value(const int, const int); void clear(); int* identity(); friend std::ostream& operator<<(std::ostream&, const Matrix&); bool operator==(const Matrix&); bool operator!=(const Matrix&); bool operator>(const Matrix&); bool operator<(const Matrix&); bool operator<=(const Matrix&); bool operator>=(const Matrix&); Matrix& operator++(); Matrix operator++(int); Matrix& operator--(); Matrix operator--(int); friend void swap(Matrix &, Matrix &); Matrix& operator=(Matrix); Matrix& operator+=(const Matrix&); friend Matrix operator+(Matrix,const Matrix&); Matrix & operator-=(const Matrix&); friend Matrix operator-(Matrix, const Matrix&); int get_Arraysize(); private: //I called it size but this is more like row and column size which is 'n' int size; int *array; };
true
41a93c53c72c3e06bf5694d6e64ce8d3a7fa4264
C++
ecosnail/ecosnail
/projects/argo/parser.cpp
UTF-8
4,204
2.59375
3
[ "MIT" ]
permissive
#include <ecosnail/argo/parser.hpp> #include <cassert> #include <iomanip> #include <sstream> #include <utility> namespace ecosnail::argo { bool Parser::parse(int argc, char* argv[]) { if (argc > 0) { programName(argv[0]); } std::vector<std::string> args; for (int i = 1; i < argc; i++) { args.push_back(argv[i]); } return parse(args); } void Parser::programName(std::string name) { _programName = std::move(name); } void Parser::output(std::ostream& outputStream) { _output = &outputStream; } void Parser::message(Message id, std::string text) { _messageTexts.update(id, std::move(text)); } void Parser::preParseCheck() { } bool Parser::parse(const std::vector<std::string>& args) { preParseCheck(); bool helpRequested = false; auto freeArgIt = _arguments.begin(); while (freeArgIt != _arguments.end() && !(*freeArgIt)->flags.empty()) { ++freeArgIt; } for (auto arg = args.begin(); arg != args.end(); ++arg) { if (_helpKeys.count(*arg)) { helpRequested = true; continue; } auto it = _argsByFlag.find(*arg); if (it != _argsByFlag.end()) { auto& data = _arguments.at(it->second); data->timesUsed++; if (data->takesArgument) { ++arg; if (arg == args.end()) { *_output << message(Message::NoValueForArgument) << std::endl; break; } data->provide(*arg); } } else { if (freeArgIt != _arguments.end()) { (*freeArgIt)->provide(*arg); if (!(*freeArgIt)->multi) { while (freeArgIt != _arguments.end() && !(*freeArgIt)->flags.empty()) { ++freeArgIt; } } } else { _freeArgs.push_back(*arg); } } } if (helpRequested) { printHelp(); return false; } postParseCheck(); return !_messagesWritten; } void Parser::postParseCheck() { for (const auto& data : _arguments) { if (data->required && data->timesUsed == 0) { *_output << message(Message::RequiredArgumentNotUsed) << ": "; for (auto it = data->flags.begin(); it != data->flags.end(); ) { *_output << *it++; for (; it != data->flags.end(); ++it) { *_output << ", " << *it; } } *_output << "\n"; } if (!data->multi && data->timesUsed > 1) { assert(!data->flags.empty()); *_output << message(Message::NonMultiUsedMultipleTimes) << std::endl; } } } const std::string& Parser::message(Message id) { _messagesWritten = true; return _messageTexts[id]; } void Parser::helpOption(const std::vector<std::string>& flags) { for (const auto& flag : flags) { _helpKeys.insert(flag); } } void Parser::printHelp() const { struct ArgumentInfo { std::string keys; std::string help; }; size_t maxKeyStringWidth = 0; std::vector<ArgumentInfo> infos; for (const auto& argument : _arguments) { std::ostringstream keyStream; const auto& flags = argument->flags; for (auto it = flags.begin(); it != flags.end(); ) { keyStream << *it++; for (; it != flags.end(); ++it) { keyStream << ", " << *it; } } auto keyString = keyStream.str(); auto width = keyString.length(); if (width > maxKeyStringWidth) { maxKeyStringWidth = width; } infos.push_back({std::move(keyString), argument->helpText}); } *_output << "usage: " << _programName << "\n" << "\n" << "Options:\n"; for (const auto& info : infos) { std::cout << " " << std::setw(maxKeyStringWidth) << std::left << info.keys << " " << info.help << "\n"; } std::cout.flush(); } } // namespace ecosnail::argo
true
47bd6ba51730a8e1637ca4f0ad9e45ee82ac917d
C++
temporaryhub/AISD2
/Audiophobia/main.cpp
UTF-8
3,448
2.53125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <queue> #include "UnionFind.cpp" using namespace std; int comp (const void * a, const void * b) { const unsigned int *av = reinterpret_cast<const unsigned int*>(a); const unsigned int *bv = reinterpret_cast<const unsigned int*>(b); if(av[2] > bv[2]) { return 1; } else if(av[2] < bv[2]) { return -1; } else { return 0; } } int main(int argc, char** argv) { int c, s, q, cnum = 1; scanf("%d %d %d", &c, &s, &q); while ((c != 0) || (s != 0) || (q != 0)) { printf("Case #%d\n", cnum); cnum++; int graf[s][3]; int adj[c+1][c+1]; bool wynik[s]; for (int i = 1; i <= c; i++) { for (int j = 1; j <= c; j++) { adj[i][j] = -1; } } for (int i = 0; i < s; i++) { wynik[i] = false; scanf("%d %d %d", &graf[i][0], &graf[i][1], &graf[i][2]); } qsort(graf, s, sizeof(*graf), comp); UF<int> *unionFind = new UF<int>(c+1); unionFind->Initialization(); // Kruskall for (int i = 0; i < s; i++) { int a = unionFind->Find(graf[i][0]); int b = unionFind->Find(graf[i][1]); if (a != b) { unionFind->Union(a, b, a); adj[a][b] = graf[i][2]; adj[b][a] = graf[i][2]; } } for (int i = 0; i < q; i++) { int src, dst; scanf("%d %d", &src, &dst); // BFS int k[c+1], p[c+1], d[c+1]; queue<int> Q; for (int j = 1; j <= c; j++) { k[j] = 0; p[j] = -1; d[j] = -1; } k[src] = 1; d[src] = 0; Q.push(src); while (!Q.empty()) { int u = Q.front(); Q.pop(); for (int j = 1; j <= c; j++) { if (adj[u][j] > -1) { if (k[j] == 0) { k[j] = 1; p[j] = u; d[j] = d[u]+1; Q.push(j); } } } k[u] = 2; } if (d[dst] == -1) { printf("no path\n"); } else { int child = dst; int max = 0; for (int j = 1; j <= c; j++) { int parent = p[child]; if (adj[parent][child] > max) { max = adj[parent][child]; } if (parent == src) { break; } else { child = parent; } } printf("%d\n",max); } } printf("\n"); scanf("%d %d %d", &c, &s, &q); } return 0; }
true
3c266eab1327058b30aa8a8ee31b808be339bb72
C++
diarodriguezva/uni_projects
/cognitive_systems/src/demo_cogsys_cpp_viz/src/main.cpp
UTF-8
6,076
2.90625
3
[]
no_license
#include <tf/transform_listener.h> #include <QApplication> #include <stdexcept> #include <exception> #include <signal.h> #include "main.h" #include <robot_control_srvs/MoveToCS.h> #include <opencv2/opencv.hpp> using namespace std; /*Declaring the clients and message containers for the connection to cambot*/ ros::ServiceClient cambot_client; robot_control_srvs::MoveToCS cambot_srv; ros::ServiceClient gripperbot_client; robot_control_srvs::MoveToCS gripperbot_srv; void movegripperbot(float x, float y, float z) { /* PUT YOUR CODE HERE Implement a function to move the gripperbot to position x,y,z (similar to movecambot) */ /*creating the service request*/ gripperbot_srv.request.x = x; gripperbot_srv.request.y = y; gripperbot_srv.request.z = z; gripperbot_srv.request.effector = "gripper"; /*calling the move service*/ if (gripperbot_client.call(gripperbot_srv)) { /*checking for success of the move*/ if(gripperbot_srv.response.success) std::cout << "Gripperbot Approach successfull " <<std::endl; else std::cout << "Gripperbot Approach failed to " << x << " " << y << " " << z << std::endl; } else { ROS_ERROR("Failed to call service /gripperbot_control/move_to_cs"); throw; } } /* Moves the cambot to position x,y,z The service definitions have been defined in the robot_control_srvs/srv/MoveToCS.srv file */ void movecambot(float x, float y, float z) { /*creating the service request*/ cambot_srv.request.x=x; cambot_srv.request.y=y; cambot_srv.request.z=z; cambot_srv.request.effector="camera"; /*calling the move service*/ if (cambot_client.call(cambot_srv)) { /*checking for success of the move*/ if(cambot_srv.response.success) std::cout << "Approach successfull " <<std::endl; else std::cout << "Approach failed to " << x << " " << y << " " << z << std::endl; } else { ROS_ERROR("Failed to call service /cambot_control/move_to_cs"); throw; } } /* Function to grasp an object located at position (x,y,z). */ void grasp(float &x, float &y, float &z) { /* PUT YOUR CODE HERE! An example of the steps required: 1. move to an approach pose (e.g. 5cm above the object) 2. move down to the object 3. move up to the approach pose */ movegripperbot(x - 0.15, y, z); movegripperbot(x - 0.05, y, z); } void track(float &x, float &y, float &z) { movegripperbot(x - 0.15, y, z); } int main(int argc, char** argv) { try { ros::init(argc, argv, "demo_cogsys_viz_cpp"); cv::Mat demoImg(480,640, CV_8UC3); cv::namedWindow("demo", 1); demoImg=cv::Scalar(0,0,0); cv::putText(demoImg, "Press ESC to quit app", cv::Point(30,30), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,255,0), 1, CV_AA); cv::putText(demoImg, "Press g to grasp GREEN object", cv::Point(30,70), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,255,0), 1, CV_AA); cv::putText(demoImg, "Press t to track GREEN object", cv::Point(30,110), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cv::Scalar(0,255,0), 1, CV_AA); int k; ros::NodeHandle n; /*creating the client for moving the cambot to a given cartesian pose*/ cambot_client = n.serviceClient<robot_control_srvs::MoveToCS>("/cambot_control/move_to_cs"); /*creating the client for moving the gripperbot to a given cartesian pose*/ gripperbot_client = n.serviceClient<robot_control_srvs::MoveToCS>("/gripperbot_control/move_to_cs"); /*move the cambot to the position, where the bag file was recorded from*/ movecambot(0.215,0,0.4); tf::TransformListener listener; bool graspObject = false, trackObject = false; while(ros::ok()) { std::string type="BOX"; std::string prop="GREEN"; int id=0; std::stringstream ss_object_name; ss_object_name << prop << "_" << type << "_" << id; tf::StampedTransform stamped_transform; try{ /* get the pose of the object w.r.t gripperbot_base frame */ listener.waitForTransform(ss_object_name.str(), "gripperbot_base", ros::Time(0), ros::Duration(1.0)); listener.lookupTransform(ss_object_name.str(), "gripperbot_base", ros::Time(0), stamped_transform); float x,y,z; x = stamped_transform.getOrigin().getX(); y = stamped_transform.getOrigin().getY(); z = stamped_transform.getOrigin().getZ(); /*checking for invalid/unreachable/noisy pose estimated from the camera*/ if(z < 0) z = -z; if(x < 0) continue; /* move the gripperbot using the obtained object position */ if(graspObject){ grasp(x,y,z); graspObject=false; } if(trackObject) track(x,y,z); } catch (tf::TransformException ex){ std::cout << "NO " << prop << " " << type << "found to grasp" << std::endl; ros::Duration(1.0).sleep(); } imshow("demo", demoImg); k = cv::waitKey(100); if((int)(k & 0xFF) == 27) break; if((int)(k & 0xFF) == 'g') graspObject = true; if((int)(k & 0xFF) == 't') trackObject = !trackObject; } demoImg.release(); cv::destroyWindow("demoImg"); cambot_client.shutdown(); return 1; } catch (std::exception& e) { std::cout << e.what() << endl; } return 0; };
true
af36435bb0080f318dc71c6ff93dfaa8b27f7421
C++
syoyo/lfwatch
/src/lfwatch_linux.cpp
UTF-8
2,505
2.859375
3
[ "MIT" ]
permissive
#ifdef __linux #include <iostream> #include <string> #include <map> #include <algorithm> #include <cassert> #include <functional> #include <sys/inotify.h> #include <unistd.h> #include <stdio.h> #include <errno.h> #include "lfwatch_linux.h" namespace lfw { WatchData::WatchData(int wd, const std::string &dir, uint32_t filter, const Callback &cb) : watch_descriptor(wd), dir_name(dir), filter(filter), callback(cb) {} WatchLinux::WatchLinux() : notify_fd(inotify_init1(IN_NONBLOCK)){ if (notify_fd == -1){ perror("lfw Error: Failed to initialize inotify"); assert(false); } } WatchLinux::~WatchLinux(){ close(notify_fd); } void WatchLinux::watch(const std::string &dir, uint32_t filters, const Callback &callback){ auto fnd = find_dir(dir); if (fnd != watchers.end() && fnd->second.filter != filters){ fnd->second.filter = filters; fnd->second.callback = callback; } //When modifying an existing watch we get back the existing descriptor, so no //need to update it int wd = inotify_add_watch(notify_fd, dir.c_str(), filters); if (wd == -1){ std::string msg = "lfw Error: Failed to watch " + dir; perror(msg.c_str()); return; } if (fnd == watchers.end()){ watchers.emplace(std::make_pair(wd, WatchData{wd, dir, filters, callback})); } } void WatchLinux::remove(const std::string &dir){ auto it = find_dir(dir); if (it != watchers.end()){ inotify_rm_watch(notify_fd, it->first); watchers.erase(it); } } void WatchLinux::update(){ int len; do { char buf[4 * 1024] = { 0 }; len = read(notify_fd, buf, sizeof(buf)); if (len == -1 && errno != EAGAIN){ perror("lfw Error: error reading event information"); } else if (len > 0){ emit_events(buf, len); } } while (len > 0); } void WatchLinux::emit_events(const char *buf, int len){ const struct inotify_event *event; for (const char *evt = buf; evt < buf + len; evt += sizeof(struct inotify_event) + event->len) { event = reinterpret_cast<const struct inotify_event*>(evt); //Check that the listener hasn't been removed between when //we got this event and now auto it = watchers.find(event->wd); if (it != watchers.end()){ it->second.callback(EventData{it->second.dir_name, event->name, it->second.filter, event->mask}); } } } std::map<int, WatchData>::iterator WatchLinux::find_dir(const std::string &dir){ return std::find_if(watchers.begin(), watchers.end(), [&dir](const std::pair<const int, WatchData> &pair){ return dir == pair.second.dir_name; }); } } #endif
true
8c4a10f01abe70c367b364410a194afbe38e62ad
C++
yish0000/leetcode_exercise
/LeetCode/AddOneRowToTree.cpp
UTF-8
1,783
3.34375
3
[]
no_license
#include "TestCase.h" #include "BinaryTreeCommon.h" using namespace std; class SolutionAddOneRowToTree : public BinaryTreeCommmon { public: TreeNode* addOneRow(TreeNode* root, int v, int d) { if (d == 1) { TreeNode* newRoot = new TreeNode(v); newRoot->left = root; return newRoot; } else { addOneRowHelper(root, NULL, v, d, false); return root; } } void addOneRowHelper(TreeNode* root, TreeNode* parent, int v, int d, bool bLeft) { if (d > 1) { if (!root) return; addOneRowHelper(root->left, root, v, d - 1, true); addOneRowHelper(root->right, root, v, d - 1, false); } else { TreeNode* newRoot = new TreeNode(v); if (bLeft) { newRoot->left = root; parent->left = newRoot; } else { newRoot->right = root; parent->right = newRoot; } } } }; RUN_TESTCASE(AddOneRowToTree) { SolutionAddOneRowToTree sln; vector<string> arr1 = { "4","2","6","3","1","5","null" }; vector<string> res1 = { "4","1","1","2","null","null","6","3","1","5","null" }; TreeNode* tree1 = sln.MakeTree(arr1); tree1 = sln.addOneRow(tree1, 1, 2); TESTCASE_ASSERT(sln.TreeEqual(tree1, res1)); sln.FreeTree(tree1); vector<string> arr2 = { "4","2","null","3","1" }; vector<string> res2 = { "4","2","null","1","1","3","null","null","1" }; TreeNode* tree2 = sln.MakeTree(arr2); tree2 = sln.addOneRow(tree2, 1, 3); TESTCASE_ASSERT(sln.TreeEqual(tree2, res2)); sln.FreeTree(tree2); vector<string> arr3 = { "1","2","3","4" }; vector<string> res3 = { "1","2","3","4","null","null","null","5","5" }; TreeNode* tree3 = sln.MakeTree(arr3); tree3 = sln.addOneRow(tree3, 5, 4); TESTCASE_ASSERT(sln.TreeEqual(tree3, res3)); sln.FreeTree(tree3); }
true
d74d908ffcfa5054a0e2c3936e90d86aa121212f
C++
pat-laugh/websson-libraries
/parser/nameType.hpp
UTF-8
551
2.625
3
[ "MIT" ]
permissive
//MIT License //Copyright 2017 Patrick Laughrea #pragma once #include <string> #include "entityManager.hpp" #include "tagIterator.hpp" #include "structures/entity.hpp" #include "structures/keywords.hpp" namespace webss { class NameType { public: enum Type { NAME, KEYWORD, ENTITY_ABSTRACT, ENTITY_CONCRETE }; NameType(std::string&& name); NameType(Keyword keyword); NameType(const Entity& entity); Type type; std::string name; Keyword keyword; Entity entity; }; NameType parseNameType(TagIterator& tagit, const EntityManager& ents); }
true
560fb29f21ec09c696fca27732d4d1c81741a106
C++
xsusov/ICP
/src/game.h
UTF-8
1,466
2.90625
3
[]
no_license
#ifndef GAME_H #define GAME_H #include <string> #include "gameboard.h" #include "player.h" #include "gameitem.h" #include "deck.h" class Game { public: Game(); Game(const std::size_t size, const int playerCount, const int itemCount ); ~Game(); std::vector<Player*> &getPlayers() {return players;} void addPlayer( const std::string playerName ); void addPlayer( Player *newPlayer, const int x = -1, const int y = -1 ); void setUp(); void nextRound(); std::string getRoundHeader(); std::string getRoundStr(); std::string getBoardStr(); std::string getFreeFieldString(); GameBoard *getBoard() {return &board;} bool finish(); static Game *loadGame(const std::string savegame); bool saveGame(const std::string savegame); bool shift(const int num, const int direction); bool isUndoPossible(); bool undo(); bool move(const int direction); bool turnEnd(); void setRound(const int newRound) {round = newRound;} int getRound() {return round;} GameItem* getItemByName(const char figure); /// Methods for gui. Player * get_actual_player() {return currentPlayer;} int get_game_size() {return board.getSize();} private: int round; int lastNum; int lastDirection; Player *currentPlayer; int winScore; GameBoard board; std::vector<Player*> players; std::vector<GameItem*> items; Deck *deck; Deck *discardpile; }; #endif // GAME_H
true
bc685abb5517934e20289de91cfed7553bd70ae8
C++
paco89lol/CandCppReference
/Cpp/reference_variable/Reference/main.cpp
UTF-8
191
2.796875
3
[]
no_license
#include <Windows.h> #include <iostream> using namespace std; int main(int argc, char **argv) { int x; int &ref = x; ref = 10; cout << x << endl; // output 10 Sleep(2000); return 0; }
true
734686c944635f27921d4d116169365261917dff
C++
Servicerobotics-Ulm/SmartDG
/src/Dependency.cpp
UTF-8
3,531
2.609375
3
[ "BSD-3-Clause" ]
permissive
//////////////////////////////////////////////////////////////////////////////// /// \file Dependency.cpp /// \brief Source file for Dependency class /// \author Vineet Nagrath /// \date June 2, 2020 /// /// \copyright Service Robotics Research Center\n /// University of Applied Sciences Ulm\n /// Prittwitzstr. 10\n /// 89075 Ulm (Germany)\n /// /// Information about the SmartSoft MDSD Toolchain is available at:\n /// www.servicerobotik-ulm.de //////////////////////////////////////////////////////////////////////////////// #include "SmartDG.h" namespace SmartDG { Dependency::Dependency() { // Sets Default Name Name = "NA_DD"; // Sets Default From and To URLs URL z(0, 0, 0, 0); From = z; To = z; // errorflag set to true by default errorflag = true; setNULL(); } Dependency::Dependency(string name, URL f, URL t) { Name = name; From = f; To = t; // Error if connection originates from an input port or ends at an output port if ((f.InOutIndex == 1) || (t.InOutIndex == 0)) errorflag = true; // Error else errorflag = false; // No Error setNULL(); } Dependency::Dependency(string name, unsigned int fni, unsigned int fioi, unsigned int fpi, unsigned int foi, unsigned int tni, unsigned int tioi, unsigned int tpi, unsigned int toi) { // Sets From and To URLs URL f(fni, fioi, fpi, foi); URL t(fni, fioi, fpi, foi); // errorflag set to true before call to Dependency(string name, URL f, URL t) errorflag = true; setNULL(); Dependency(name, f, t); } Dependency::Dependency(string name, unsigned int fni, unsigned int fpi, unsigned int foi, unsigned int tni, unsigned int tpi, unsigned int toi) { // Sets From and To URLs URL f(fni, 0, fpi, foi); URL t(fni, 1, fpi, foi); // errorflag set to true before call to Dependency(string name, URL f, URL t) errorflag = false; setNULL(); Dependency(name, f, t); } void Dependency::setNULL() { // Sets Transfer/Inverse transfer Function pointers to ideal connector's Transfer/Inverse transfer Functions // In case the connector is a dependency node, these TF and FT function pointers are later assigned to // transfer/inverse transfer function associated with the connector. TF = &SmartDG::TransferFunctionsIdealConnector::Instance001::TF; FT = &SmartDG::TransferFunctionsIdealConnector::Instance001::FT; // Sets GUIConnection to null con = NULL; } void Dependency::Display() { // Displays full URLs // {Connector} Source URL - DependencyObject -> Target URL cout << "{" << Name << "}" << From.str << "----" << From.stro << "---->" << To.str << endl; } void Dependency::DisplayMini() { // Displays {Connector} // Source DependencyNode . Source DependencyPort - DependencyObject -> Target DependencyNode . Target DependencyPort cout << "{" << Name << "}" << From.strn << "." << From.strp << "-" << From.stro << "->" << To.strn << "." << To.strp << endl; } void Dependency::DisplayValues(vector<DependencyNode> &DN) { // Displays full URLs with Values // {Connector} Source URL{Source DependencyDataPackage} ---- DependencyObject ----> Target URL{Target DependencyDataPackage} DependencyDataPackage FROMVAL = DN[From.NodeIndex].DP[From.InOutIndex][From.PortIndex].DO[From.ObjectIndex].udi[To.str]; DependencyDataPackage TOVAL = DN[To.NodeIndex].DP[To.InOutIndex][To.PortIndex].DO[To.ObjectIndex].udi[From.str]; cout << "{" << Name << "}" << From.str << "{" << FROMVAL << "}" << "----" << From.stro << "---->" << "{" << TOVAL << "}" << To.str << endl; } Dependency::~Dependency() { } } /* namespace SmartDG */
true
a0d3e2efc81239f6493c042a5aaacd1e03af4247
C++
HRsniper/CPP
/c++ aulas extraa/aula__ template.cpp
UTF-8
1,218
3.671875
4
[]
no_license
#include <iostream> using namespace std; template <typename T> T funcao(T n) { cout << typeid(n).name() << " - "; // if (typeid(n).name() == typeid(int).name()) { // cout << "inteiro - "; // } return n*2; } template <class T1> class aula { private: public: T1 nome; T1 idade; aula(T1 n , T1 i){ this->nome = n; this->idade = i; } // ~aula() { // cout << "destrutor ativo \n"; // } }; int main() { cout << funcao(10) << endl; cout << funcao(10.51) << endl; cout << funcao(10.55555) << endl; cout << funcao(1000000000000000000) << endl; aula *carro1=new aula("fiat",200); aula p1{"hr", 23}; system("pause"); return 0; } /* Modelos de funções Escrevemos uma função genérica que pode ser usada para diferentes tipos de dados. Exemplos de modelos de função são sort (), max (), min (), printArray () e etc. template <typename T> Modelos de classe Como os modelos de função, os modelos de classe são úteis quando uma classe define algo que é independente do tipo de dados. Pode ser útil para classes como LinkedList, BinaryTree, Stack, Queue, Array, etc. template <class T> */
true
1cb1563afec9f038dd5e33de0a4d154bb2ae8c06
C++
imos/nineserver
/nineserver/arena/arena_buffer.cc
UTF-8
1,642
2.78125
3
[]
no_license
#include "nineserver/arena/arena_buffer.h" #include "base/base.h" DEFINE_int32(arena_buffer_size, 16 * 1024, "Initial arena buffer size."); ArenaBuffer::ArenaBuffer() { buffers_.emplace_back(FLAGS_arena_buffer_size); } void ArenaBuffer::DeleteAll() { buffers_.erase(buffers_.begin() + 1, buffers_.end()); buffers_[0].size_ = 0; usage_ = 0; } void ArenaBuffer::Init() { size_ = 0; } void ArenaBuffer::clear() { resize(0); } void ArenaBuffer::push_back(char c) { resize(size() + 1); buffers_.back().data_[buffers_.back().size_ - 1] = c; } void ArenaBuffer::resize(int64 size) { reserve(size); buffers_.back().size_ += size - size_; size_ = size; } void ArenaBuffer::append(StringPiece str) { resize(size() + str.size()); memcpy(buffers_.back().data_.get() + buffers_.back().size_ - str.size(), str.data(), str.size()); } void ArenaBuffer::reserve(int64 size) { if (capacity() < size) { AddBuffer(size); } } int64 ArenaBuffer::capacity() const { return buffers_.back().capacity_ - buffers_.back().size_ + size_; } int64 ArenaBuffer::usage() const { return usage_ + buffers_.back().size_; } void ArenaBuffer::AddBuffer(int length) { DVLOG(10) << "ArenaBuffer::AddBuffer(" << length << ")"; if (length < buffers_.back().capacity_ * 2) { length = buffers_.back().capacity_ * 2; } usage_ += buffers_.back().capacity_; length = (length + 8191) / 8192 * 8192; StringPiece original = *this; buffers_.emplace_back(length); DCHECK_LE(original.size(), length); buffers_.back().size_ = original.size(); memcpy(buffers_.back().data_.get(), original.data(), original.size()); }
true
4b9faf4b4a528e478a330a3416c392c38ee9a799
C++
StevenSavold/SQLiteFictionEngine
/Engine/src/Database.h
UTF-8
5,970
2.90625
3
[]
no_license
#pragma once #include "Common.h" #include "Parsing/ParseUtils.h" #include "sqlite3/sqlite3.h" #include <cstdarg> #include <string> #define OFFSCREEN_ID 0 #define PLAYER_ID 1 union Directions { int dirs[6]; struct { int North, South, East, West, Up, Down; }; }; class Database { private: sqlite3* db_; public: using SQLCallbackFn = int(*)(void*, int, char**, char**); using ID_type = int; using DBInt = int; Database(const char* dbfile) { int rc = sqlite3_open(dbfile, &db_); // If we fail to make the db then make the db a nullptr if (rc) { sqlite3_close(db_); db_ = nullptr; } } ~Database() { sqlite3_close(db_); db_ = nullptr; } bool is_open() { return (db_ != nullptr); } int Exec(const char* sql_code, SQLCallbackFn callbk) { char* errMsg; int rc = sqlite3_exec(db_, sql_code, callbk, 0, &errMsg); if (rc != SQLITE_OK) { err("SQL ERROR: %s\n", errMsg); sqlite3_free(errMsg); } return rc; } template <typename T> std::unique_ptr<T> GetFrom(const char* tableName, const char* colNames, SQLCallbackFn callbk) const { char* errMsg; std::unique_ptr<T> output = std::make_unique<T>(); std::string code; code += "SELECT "; code += colNames; code += " FROM "; code += tableName; int rc = sqlite3_exec(db_, code.c_str(), callbk, output.get(), &errMsg); if (rc != SQLITE_OK) { err("SQL ERROR: %s\n", errMsg); sqlite3_free(errMsg); return nullptr; } return std::move(output); } template <typename T> std::unique_ptr<T> GetFrom(const char* tableName, const char* colNames, const char* whereCondition, SQLCallbackFn callbk) const { char* errMsg; std::unique_ptr<T> output = std::make_unique<T>(); std::string code; code += "SELECT "; code += colNames; code += " FROM "; code += tableName; code += " WHERE "; code += whereCondition; int rc = sqlite3_exec(db_, code.c_str(), callbk, output.get(), &errMsg); if (rc != SQLITE_OK) { err("SQL ERROR: %s\n", errMsg); sqlite3_free(errMsg); return nullptr; } return std::move(output); } std::unique_ptr<std::string> GetDescription(ID_type itemId) const { std::string whereClause = "id="; whereClause += std::to_string(itemId); return std::move(GetFrom<std::string>("object", "desc", whereClause.c_str(), [](void* output, int argc, char** argv, char** colName) -> int { if (argc > 1) { err("Too many columns!\n"); return 1; } (*(static_cast<std::string*>(output))) += argv[0]; return 0; })); } std::unique_ptr<Directions> GetDirections(ID_type itemId) const { std::string whereClause = "id="; whereClause += std::to_string(itemId); return std::move(GetFrom<Directions>("object", "N, S, E, W, U, D", whereClause.c_str(), [](void* output, int argc, char** argv, char** colName) -> int { if (argc > 6) { err("Too many columns!\n"); return 1; } for (int i = 0; i < argc; ++i) { static_cast<Directions*>(output)->dirs[i] = atoi((argv[i] != nullptr) ? argv[i] : "-1"); } return 0; })); } std::unique_ptr<GameObject> GetObject(ID_type objID) const { std::string code = "id="; code += std::to_string(objID); return std::move(GetFrom<GameObject>("object", "*", code.c_str(), [](void* output, int argc, char** argv, char** colNames) -> int { GameObject* object = static_cast<GameObject*>(output); object->id = atoi(argv[0]); object->name = argv[1]; object->holder = (argv[2] != nullptr) ? atoi(argv[2]) : -1; object->short_desc = (argv[3] != nullptr) ? argv[3] : ""; object->first_time_desc = (argv[4] != nullptr) ? argv[4] : ""; object->desc = (argv[5] != nullptr) ? argv[5] : ""; object->N = (argv[6] != nullptr) ? atoi(argv[6]) : -1; object->E = (argv[7] != nullptr) ? atoi(argv[7]) : -1; object->W = (argv[8] != nullptr) ? atoi(argv[8]) : -1; object->S = (argv[9] != nullptr) ? atoi(argv[9]) : -1; object->U = (argv[10] != nullptr) ? atoi(argv[10]) : -1; object->D = (argv[11] != nullptr) ? atoi(argv[11]) : -1; object->is_viewed = atoi(argv[12]); object->is_getable = atoi(argv[13]); return 0; })); } void UpdateObject(const GameObject& obj) { std::string sqlCode = "UPDATE object SET id="; sqlCode += std::to_string(obj.id); sqlCode += ", name="; sqlCode += SafeWrap(obj.name); sqlCode += ", holder="; sqlCode += (obj.holder != -1) ? std::to_string(obj.holder) : "NULL"; sqlCode += ", short_desc="; sqlCode += (obj.short_desc.empty()) ? "NULL" : SafeWrap(obj.short_desc).c_str(); sqlCode += ", first_time_desc="; sqlCode += (obj.first_time_desc.empty()) ? "NULL" : SafeWrap(obj.first_time_desc).c_str(); sqlCode += ", desc="; sqlCode += (obj.desc.empty()) ? "NULL" : SafeWrap(obj.desc).c_str(); sqlCode += ", N="; sqlCode += (obj.N != -1) ? std::to_string(obj.N) : "NULL"; sqlCode += ", E="; sqlCode += (obj.E != -1) ? std::to_string(obj.E) : "NULL"; sqlCode += ", W="; sqlCode += (obj.W != -1) ? std::to_string(obj.W) : "NULL"; sqlCode += ", S="; sqlCode += (obj.S != -1) ? std::to_string(obj.S) : "NULL"; sqlCode += ", U="; sqlCode += (obj.U != -1) ? std::to_string(obj.U) : "NULL"; sqlCode += ", D="; sqlCode += (obj.D != -1) ? std::to_string(obj.D) : "NULL"; sqlCode += ", is_viewed="; sqlCode += std::to_string(obj.is_viewed); sqlCode += ", is_getable="; sqlCode += std::to_string(obj.is_getable); sqlCode += " WHERE id="; sqlCode += std::to_string(obj.id); Exec(sqlCode.c_str(), [](void* output, int argc, char** argv, char** colNames) -> int { /* DO NOTHING, ONLY EXEC THE STATEMENT */ return 0; }); } };
true
326d0db1efdc8fd66bf0748f4f03dfb932e57696
C++
hehesnail/algorithm_practice
/poj_2385/main.cc
UTF-8
1,246
3.359375
3
[]
no_license
/* dp F[i][j]表示在第i次下落,移动了j次可以接到苹果的最大值 等于第i-1次下落,移动了j-1次(F[i-1][j-1])和第i-1次下落,移动了j次(F[i-1][j])两者的较大值 加上j次移动过后是否在对应的树下面,是则加上1否则为0 */ #include <iostream> using namespace std; #define MAXT 1001 #define MAXW 31 int t[MAXT]; int F[MAXT][MAXW]; int main() { int T, W; cin >> T >> W; for (int i = 1; i<= T; i++) cin >> t[i]; // first drop T = 1 for (int i = 0; i <= W; i++) { F[1][i] = (i%2+1 == t[1]); } // along whole T drops, no move, test t[i] == 1 thus under first tree for (int i = 2; i <= T; i++) { if (t[i] == 1) F[i][0] = F[i-1][0] + 1; else F[i][0] = F[i-1][0]; } //F[1][0->W], F[1->T][0] initialized for (int i = 2; i <= T; i++) { for (int j = 1; j <= W; j++) { F[i][j] = max(F[i-1][j-1], F[i-1][j]); //if after j moves under the right tree if (j % 2 + 1 == t[i]) F[i][j]++; } } int res = 0; for (int i = 0; i <= W; i++) res = max(res, F[T][i]); cout << res << endl; return 0; }
true
173f96b2893896b0293ebb8b62db10362859ba28
C++
shifuxiang/NvrControl
/NvrControl/NvrControl/jobs/TMSSensor.h
GB18030
2,691
2.546875
3
[]
no_license
//@file:TMSSensor.h //@brief:TMSز //@author:luyan@oristartech.com //date:2014-09-17 #ifndef _H_SOFTWARESTATE_ #define _H_SOFTWARESTATE_ #include <iostream> #include <string> #include "DataManager.h" #include "../threadManage/C_CS.h" #include "parser_xml.h" struct stNotifySmsSwitchInfo { std::string strHallId; std::string strNewIp; unsigned short port; stNotifySmsSwitchInfo(): port(0) { } stNotifySmsSwitchInfo(std::string HallId,std::string NewIp,unsigned short Port) { strHallId = HallId; strNewIp = NewIp; port = Port; } stNotifySmsSwitchInfo(const stNotifySmsSwitchInfo &obj) { strHallId = obj.strHallId; strNewIp = obj.strNewIp; port = obj.port; } stNotifySmsSwitchInfo& operator=(const stNotifySmsSwitchInfo &obj) { if(this != &obj) { strHallId = obj.strHallId; strNewIp = obj.strNewIp; port = obj.port; } return *this; } }; class CTMSSensor { public: CTMSSensor(); ~CTMSSensor(); // tms bool StartTMS(); // лtms bool SwitchTMS(); // ȡTMS PID int GetTMSPID(); // ȡԶTMS״̬ bool GetTMSWorkState(); // ʼ bool Init(std::string strIP,int nPort,int nTMSWSPort); // ֪ͨtms smsлµ bool NotifyTMSSMSSwitch(std::string strHallId,std::string strNewIp,unsigned short port); // ѯtmsǷ bool AskTMSReboot(); // kill tms PID bool ShutDownTMS(); private: // òͬķʽtms bool StartTMS_CurTerminal(std::string strTMSPath); bool StartTMS_NewTerminal(std::string strTMSPath); // webserviceӿڣbTMSWS:Ƿñtmsӿ int InvokerWebServer(bool bTMSWS,std::string strURI,std::string &xml,std::string &strResponse); int GetHttpContent(const std::string &http, std::string &response); int SendAndRecvResponse(bool bTMSWS,const std::string &request, std::string &response, int delayTime = 3); bool ParseXmlFromOtherMonitor(std::string &retXml,int &nRet); bool ParseXmlFromTMS(std::string &retXml,int &nRet); bool ParseXmlFromTMSState(std::string &retXml,int &nRet); bool ParseIsRebootXml(std::string &retXml,int &nRet); // ñϵлtmsӿ bool CallStandbySwitchTMS(); // µĽִнű int ForkExeSh(std::string strExe); // ݿtmsλ bool UpdateDataBaseTMSPos(int nPosition); // ȡ̵ָpid int Getpid(std::string strName,std::vector<int>& vecPID); private: CDataManager * m_ptrDM; int m_nPid; std::vector<stNotifySmsSwitchInfo> m_vecSwitchInfo; //ԶϢ std::string m_strIP; int m_nPort; int m_nTMSWBPort; C_CS m_csPID; }; #endif //
true
ef923ba6c3553b401831995538e0804ad4ddb7da
C++
flipperfipper/CPP
/Ej_5_05.cpp
UTF-8
1,054
3.453125
3
[]
no_license
//5. Funcion que lea un vector e intercambie los datos que estan en posiciones pares por los que estan en posiciones impares adyacentes (Ej: 1.2, 3.4, ...). #include<stdio.h> #include<conio.h> #define TAM 10 //DECLARACION void EscribirVector (int v[ ]); void desplazamiento_izq_Vector (int v[ ]); //DEFINICION void EscribirVector (int v[ ]) {int cont,dato; printf(" POSICION DATO\n"); for(cont=0;cont<10;cont++) {dato=v[cont]; printf(" %d %d\n ",cont+1,dato); } } void desplazamiento_izq_Vector (int v[ ]) {int cont, dato, aux; for(cont=1;cont<=10;cont++) {printf("Escribe el valor de la posicion %d del vector",cont); scanf("%d",&dato); v[cont-1]=dato; } for(cont=0;cont<9;cont=cont+2) {aux=v[cont]; v[cont]=v[cont+1]; v[cont+1]=aux; } } int main(void) {int v[TAM]; desplazamiento_izq_Vector(v); EscribirVector(v); getch(); }
true
dd9957d1bdd6cd93322096eefe32ee51bab1b71f
C++
JeongJiAn/Hacker_Study_OOP
/Week_5/problems/프렌드와 연산자 중복/number_07.cpp
UTF-8
226
2.984375
3
[]
no_license
#include"Matrix.h" #include"number_07.h" void solution_07() { Matrix a(4, 3, 2, 1), b; int x[4], y[4] = { 1, 2, 3, 4 }; a >> x; b << y; for (int i = 0; i < 4; i++) { cout << x[i] << ' '; } cout << endl; b.show(); }
true
04d6a6d0db11d51276cffdbfd6333595b9a3de7e
C++
CJunette/CPP_Learning
/009/实验/9_Experiment_004_Stack/9_Experiment_004_Stack/Stack.h
UTF-8
733
3.515625
4
[]
no_license
#pragma once #include <cassert> #include "LinkedList.h" #include "Node.h" template<class T> class Stack { public: Stack(); void push(const T &item); T pop(); void clear(); const T &peek() const; bool isEmpty(); private: int count; LinkedList<T> list; }; template<class T> Stack<T>::Stack(): count(0) {} template<class T> void Stack<T>::push(const T &item) { list.insertFront(item); count++; } template<class T> T Stack<T>::pop() { assert(!isEmpty()); count--; return list.deleteFront(); } template<class T> void Stack<T>::clear() { list.clear(); count = 0; } template<class T> const T &Stack<T>::peek() const { return list.frontData(); } template<class T> bool Stack<T>::isEmpty() { return count == 0; }
true
1da04ffc1b1b3ba70d7fa33d442c8847d44ccb37
C++
abraxaslee/ACM-ICPC
/489.cpp
UTF-8
834
2.734375
3
[ "MIT" ]
permissive
//2012/01/19 //489.cpp //Run time: 0.104 #include <stdio.h> char buff[100000]; int wordcount, LIFE, round, c, z; void solve(int ans[]){ int repeat[125] = {}; LIFE = 7; for(z=0; buff[z] != '\0'; ++z){ if(!repeat[buff[z]]){ if(ans[buff[z]]) wordcount--; else LIFE--; repeat[buff[z]] = 1; } if(!wordcount){ puts("You win."); return; } if(!LIFE){ puts("You lose."); return; } } puts("You chickened out."); return; } int main(){ while(scanf("%d", &round)!=EOF){ if(round == -1) break; getchar(); int ans[125] = {}; while( (c = getchar()) != 10){ ans[c] = 1; } wordcount = 0; for(c=97; c<123; ++c) if(ans[c]) wordcount++; gets(buff); printf("Round %d\n", round); solve(ans); } return 0; }
true
2fbf7ba35cb1ab13b438a5919578ab3f7e9fd172
C++
1432849339/Trans_shm
/Trans_shm/Trans.cpp
UTF-8
11,488
2.6875
3
[]
no_license
#include "Trans.h" int64_t GetMsTime(int64_t ymd, int64_t hmsu) { struct tm timeinfo = { 0 }; time_t second; int64_t usecond; timeinfo.tm_year = ymd / 10000 - 1900; timeinfo.tm_mon = (ymd % 10000) / 100 - 1; timeinfo.tm_mday = ymd % 100; second = mktime(&timeinfo); //80000000 int hou = hmsu / 10000000; int min = (hmsu % 10000000) / 100000; int sed = (hmsu % 100000) / 1000; int used = hmsu % 1000; usecond = second + hou * 3600 + min * 60 + sed; usecond *= 1000000; usecond += used * 1000; return usecond; } time_t GetTr_time() { time_t tt; struct tm* pstm = nullptr; tt = time(nullptr); pstm = localtime(&tt); if (pstm->tm_wday == 6)//星期6 { tt += 2 * 24 * 60 * 60; } else if (pstm->tm_wday == 0)//星期天 { tt += 1 * 24 * 60 * 60; } else if ((pstm->tm_wday == 5) && ((pstm->tm_hour == SPLIT_HROUS && pstm->tm_min >= SPLIT_MINN) || (pstm->tm_hour > SPLIT_HROUS)) ) { tt += 3 * 24 * 60 * 60; } else if ((pstm->tm_wday >= 1 && pstm->tm_wday <= 4) && ((pstm->tm_hour == SPLIT_HROUS && pstm->tm_min >= SPLIT_MINN) || (pstm->tm_hour > SPLIT_HROUS)) )//星期1到星期4 { tt += 1 * 24 * 60 * 60; } return tt; } string GetTime() { time_t tt; struct tm* pstm = nullptr; tt = time(nullptr); pstm = localtime(&tt); int year = pstm->tm_year + 1900; int mon = pstm->tm_mon + 1; int day = pstm->tm_mday; char time_c[32]; sprintf(time_c, "%04d%02d%02d %02d:%02d:%02d", year, mon, day, pstm->tm_hour, pstm->tm_min, pstm->tm_sec); return time_c; } int GetTrday() { time_t tt; struct tm* pstm = nullptr; tt = time(nullptr); pstm = localtime(&tt); if (pstm->tm_wday == 6)//星期6 { tt += 2 * 24 * 60 * 60; } else if(pstm->tm_wday == 0)//星期天 { tt += 1 * 24 * 60 * 60; } else if((pstm->tm_wday == 5) && ((pstm->tm_hour == SPLIT_HROUS && pstm->tm_min >= SPLIT_MINN) || (pstm->tm_hour > SPLIT_HROUS)) ) { tt += 3 * 24 * 60 * 60; } else if((pstm->tm_wday >= 1 && pstm->tm_wday <= 4) && ((pstm->tm_hour == SPLIT_HROUS && pstm->tm_min >= SPLIT_MINN) || (pstm->tm_hour > SPLIT_HROUS)) )//星期1到星期4 { tt += 1 * 24 * 60 * 60; } pstm = localtime(&tt); int year = pstm->tm_year + 1900; int mon = pstm->tm_mon + 1; int day = pstm->tm_mday; return year * 10000 + mon * 100 + day; } void Snapshot2str(Snapshot *ptr, string &str) { stringstream ss; ss << ptr->ukey << "," << ptr->trday << "," << ptr->timeus << "," << ptr->recvus << "," << ptr->status << "," << ptr->pre_close << "," << ptr->high << "," << ptr->low << "," << ptr->open << "," << ptr->last << "," << ptr->match_num << "," << ptr->volume << "," << ptr->turnover << ","; for (int i = 0; i < 10; ++i) ss << ptr->info[i] << ","; for (int i = 0; i < 10; ++i) ss << ptr->ask_price[i] << ","; for (int i = 0; i < 10; ++i) ss << ptr->ask_volume[i] << ","; for (int i = 0; i < 10; ++i) ss << ptr->bid_price[i] << ","; for (int i = 0; i < 10; ++i) ss << ptr->bid_volume[i] << ","; ss << ptr->ask_orders_num << "," << ptr->bid_orders_num << ","; for (int i = 0; i < 50; ++i) ss << ptr->ask_queue[i] << ","; for (int i = 0; i < 49; ++i) ss << ptr->bid_queue[i] << ","; ss << ptr->bid_queue[49] << endl; str = ss.str(); } void Order2str(Order *ptr, string &str) { stringstream ss; ss << ptr->ukey << "," << ptr->trday << "," << ptr->timeus << "," << ptr->recvus << "," << ptr->index << "," << ptr->price << "," << ptr->volume << "," << ptr->order_type << endl; str = ss.str(); } void Trans2str(Transaction* ptr, string &str) { stringstream ss; ss << ptr->ukey << "," << ptr->trday << "," << ptr->timeus << "," << ptr->recvus << "," << ptr->index << "," << ptr->price << "," << ptr->volume << "," << ptr->ask_order << "," << ptr->bid_order << "," << ptr->trade_type << endl; str = ss.str(); } void Orderque2str(OrderQueue *ptr, string &str) { stringstream ss; ss << ptr->ukey << "," << ptr->trday << "," << ptr->timeus << "," << ptr->recvus << "," << ptr->side << "," << ptr->price << "," << ptr->orders_num << ","; for (int i = 0; i < 49; ++i) ss << ptr->queue[i] << ","; ss << ptr->queue[49] << endl; str = ss.str(); } void SH_IndexCodeTrans(char *ChCode) { switch (atoi(ChCode)) { case 999999: memcpy(ChCode, "000001", 6); break; case 999998: memcpy(ChCode, "000002", 6); break; case 999997: memcpy(ChCode, "000003", 6); break; case 999996: memcpy(ChCode, "000004", 6); break; case 999995: memcpy(ChCode, "000005", 6); break; case 999994: memcpy(ChCode, "000006", 6); break; case 999993: memcpy(ChCode, "000007", 6); break; case 999992: memcpy(ChCode, "000008", 6); break; case 999991: memcpy(ChCode, "000010", 6); break; case 999990: memcpy(ChCode, "000011", 6); break; case 999989: memcpy(ChCode, "000012", 6); break; case 999988: memcpy(ChCode, "000013", 6); break; case 999987: memcpy(ChCode, "000016", 6); break; case 999986: memcpy(ChCode, "000015", 6); break; default: if (strlen(ChCode) > 2) memcpy(ChCode, "00", 2); break; } } bool LvtToSnapshot(Snapshot& OutPut, SDS20LEVEL2& Input) { string windcode = string(Input.szWindCode); int64_t ukey = GetUkey(windcode.substr(windcode.rfind('.') + 1), windcode.substr(0, windcode.rfind('.'))); if (ukey == 0) { return false; } else { OutPut.ukey = ukey; OutPut.trday = Input.nActionDay; OutPut.timeus = GetMsTime(OutPut.trday, Input.nTime); OutPut.recvus = (Input.nRecvTime < Input.nTime ? OutPut.timeus : GetMsTime(OutPut.trday, Input.nRecvTime)); OutPut.status = 0; OutPut.pre_close = Input.nPreClose; OutPut.high = Input.nHigh; OutPut.low = Input.nLow; OutPut.open = Input.nOpen; OutPut.last = Input.nMatch; OutPut.match_num = Input.nNumTrades; OutPut.volume = Input.iVolume; OutPut.turnover = Input.iTurnover; OutPut.info[0] = Input.nHighLimited; OutPut.info[1] = Input.nLowLimited; OutPut.info[2] = Input.nTotalBidVol; OutPut.info[3] = Input.nTotalAskVol; OutPut.info[4] = Input.nWeightedAvgBidPrice; OutPut.info[5] = Input.nWeightedAvgAskPrice; OutPut.info[6] = Input.nIOPV; OutPut.info[7] = Input.nYieldToMaturity; OutPut.info[8] = Input.nSyl1; OutPut.info[9] = Input.nSyl2; for (int i = 0; i < 10; ++i) { OutPut.ask_price[i] = Input.nAskPrice[i]; } for (int i = 0; i < 10; ++i) { OutPut.ask_volume[i] = Input.nAskVol[i]; } for (int i = 0; i < 10; ++i) { OutPut.bid_price[i] = Input.nBidPrice[i]; } for (int i = 0; i < 10; ++i) { OutPut.bid_volume[i] = Input.nBidVol[i]; } return true; } } bool IdxToSnapshot(Snapshot& OutPut, SDS20INDEX& InPut) { char code[32]{ 0 }; strncpy(code, InPut.szWindCode, 32); if (0 == strcasecmp(code + 7, "SH")) { SH_IndexCodeTrans(code); } string windcode = code; int64_t ukey = GetUkey(windcode.substr(windcode.rfind('.') + 1), windcode.substr(0, windcode.rfind('.'))); if (0 == ukey) { return false; } else { OutPut.ukey = ukey; OutPut.trday = InPut.nActionDay; OutPut.timeus = GetMsTime(OutPut.trday, InPut.nTime); OutPut.recvus = (InPut.nRecvTime < InPut.nTime ? OutPut.timeus : GetMsTime(OutPut.trday, InPut.nRecvTime)); OutPut.status = 0; OutPut.pre_close = InPut.nPreCloseIndex; OutPut.high = InPut.nHighIndex; OutPut.low = InPut.nLowIndex; OutPut.open = InPut.nOpenIndex; OutPut.last = InPut.nLastIndex; OutPut.match_num = 0; OutPut.volume = InPut.iTotalVolume; OutPut.turnover = InPut.iTurnover; return true; } } bool Cfe_SpiToSnapshot(Snapshot& OutPut, SDS20FUTURE& InPut) { string windcode = string(InPut.szWindCode); int64_t ukey = GetUkey(windcode.substr(windcode.rfind('.') + 1), windcode.substr(0, windcode.rfind('.'))); if (0 == ukey) { return false; } else { OutPut.ukey = ukey; OutPut.trday = InPut.nActionDay; OutPut.timeus = GetMsTime(OutPut.trday, InPut.nTime); OutPut.recvus = (InPut.nRecvTime < InPut.nTime ? OutPut.timeus : GetMsTime(OutPut.trday, InPut.nRecvTime)); OutPut.status = 0; OutPut.pre_close = InPut.nPreClose; OutPut.high = InPut.nHigh; OutPut.low = InPut.nLow; OutPut.open = InPut.nOpen; OutPut.last = InPut.nMatch; OutPut.match_num = 0; OutPut.volume = InPut.iVolume; OutPut.turnover = InPut.iTurnover; OutPut.info[0] = InPut.nHighLimited; OutPut.info[1] = InPut.nLowLimited; OutPut.info[2] = InPut.nSettlePrice; OutPut.info[3] = InPut.nPreSettlePrice; OutPut.info[4] = InPut.iOpenInterest; OutPut.info[5] = InPut.iPreOpenInterest; OutPut.info[6] = InPut.nCurrDelta; OutPut.info[7] = InPut.nPreDelta; OutPut.info[8] = 0; OutPut.info[9] = 0; for (int i = 0; i < 10; ++i) { if (i < 5) { OutPut.ask_price[i] = InPut.nAskPrice[i]; } else { OutPut.ask_price[i] = 0; } } for (int i = 0; i < 10; ++i) { if (i < 5) { OutPut.ask_volume[i] = InPut.nAskVol[i]; } else { OutPut.ask_volume[i] = 0; } } for (int i = 0; i < 10; ++i) { if (i < 5) { OutPut.bid_price[i] = InPut.nBidPrice[i]; } else { OutPut.bid_price[i] = 0; } } for (int i = 0; i < 10; ++i) { if (i < 5) { OutPut.bid_volume[i] = InPut.nBidVol[i]; } else { OutPut.bid_volume[i] = 0; } } return true; } } bool TrdToTransaction(Transaction& OutPut, SDS20TRANSACTION& InPut) { string windcode = string(InPut.szWindCode); int64_t ukey = GetUkey(windcode.substr(windcode.rfind('.') + 1), windcode.substr(0, windcode.rfind('.'))); if (0 == ukey) { return false; } else { OutPut.ukey = ukey; OutPut.trday = InPut.nActionDay; OutPut.timeus = GetMsTime(OutPut.trday, InPut.nTime); OutPut.recvus = (InPut.nRecvTime < InPut.nTime ? OutPut.timeus : GetMsTime(OutPut.trday, InPut.nRecvTime)); OutPut.index = InPut.nIndex; OutPut.price = InPut.nPrice; OutPut.volume = InPut.nVolume; OutPut.ask_order = InPut.nAskOrder; OutPut.bid_order = InPut.nBidOrder; OutPut.trade_type = make_trade_type((char)InPut.nBSFlag, InPut.chOrderKind, InPut.chFunctionCode); return true; } } bool OrdToOrder(Order& OutPut, SDS20ORDER& InPut) { string windcode = string(InPut.szWindCode); int64_t ukey = GetUkey(windcode.substr(windcode.rfind('.') + 1), windcode.substr(0, windcode.rfind('.'))); if (0 == ukey) { return false; } else { OutPut.ukey = ukey; OutPut.trday = InPut.nActionDay; OutPut.timeus = GetMsTime(OutPut.trday, InPut.nTime); OutPut.recvus = (InPut.nRecvTime < InPut.nTime ? OutPut.timeus : GetMsTime(OutPut.trday, InPut.nRecvTime)); OutPut.index = InPut.nOrder; OutPut.price = InPut.nPrice; OutPut.volume = InPut.nVolume; OutPut.order_type = make_order_type(InPut.chOrderKind, InPut.chFunctionCode); return true; } } bool OrqToOrderqueue(OrderQueue& OutPut, SDS20ORDERQUEUE& InPut) { string windcode = string(InPut.szWindCode); int64_t ukey = GetUkey(windcode.substr(windcode.rfind('.') + 1), windcode.substr(0, windcode.rfind('.'))); if (0 == ukey) { return false; } else { OutPut.ukey = ukey; OutPut.trday = InPut.nActionDay; OutPut.timeus = GetMsTime(OutPut.trday, InPut.nTime); OutPut.recvus = (InPut.nRecvTime < InPut.nTime ? OutPut.timeus : GetMsTime(OutPut.trday, InPut.nRecvTime)); OutPut.side = InPut.nSide; OutPut.price = InPut.nPrice; OutPut.orders_num = InPut.nOrders; for (int i = 0; i < 50; ++i) { if (i < InPut.nABItems) { OutPut.queue[i] = InPut.nABVolume[i]; } else { OutPut.queue[i] = 0; } } return true; } }
true
56b679c655faa92a7897f267f2392c3c72564ddb
C++
skyllar/Problem-Solving
/geeksForGeeks/dynamicProgramming/Optimal Strategy for a Game.cpp
UTF-8
3,295
2.90625
3
[]
no_license
/* * Optimal Strategy for a Game.cpp * * Created on: Nov 16, 2014 * Author: Apratim */ #include <cstdio> #include <iostream> using namespace std; #define TRACE #define DEBUG #ifdef TRACE #define trace1(x) cerr <<"\n"<< #x << ": " << x << endl; #define trace2(x, y) cerr<<"\n" << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr<<"\n" << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define trace4(a, b, c, d) cerr <<"\n"<< #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #define trace5(a, b, c, d, e) cerr <<"\n"<< #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl; #define trace6(a, b, c, d, e, f) cerr <<"\n"<< #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl; #else #define trace1(x) #define trace2(x, y) #define trace3(x, y, z) #define trace4(a, b, c, d) #define trace5(a, b, c, d, e) #define trace6(a, b, c, d, e, f) #endif #define si(x) scanf("%d" , &x) #define sl(x) scanf("%ld" , &x) #define sll(x) scanf("%lld" , &x) #define sc(x) scanf("%c" , &x) #define ss(x) scanf("%s" , &x) #define pi(x) printf("%d\n" , x) #define pl(x) printf("%ld\n" , x) #define pll(x) printf("%lld\n" , x) #define pc(x) printf("%c\n" , x) #define ps(x) printf("%s\n" , x) #define fup(i,a,b) for(int i=a;i<b;i++) #define fdn(i,a,b) for(int i=a;i>=b;i--) #define gc getchar #define ll long long // C program to find out maximum value from a given sequence of coins #include <stdio.h> #include <limits.h> // Utility functions to get maximum and minimum of two intgers int max(int a, int b) { return a > b ? a : b; } int min(int a, int b) { return a < b ? a : b; } // Returns optimal value possible that a player can collect from // an array of coins of size n. Note than n must be even int optimalStrategyOfGame(int* arr, int n) { int dp[n][n]; for (int i = 0; i < n; i++) dp[i][i] = arr[i]; for (int i = 0; i < n - 1; i++) dp[i][i + 1] = max(arr[i], arr[i + 1]); for (int gap = 2; gap < n; gap++) { for (int i = 0; i < n - gap; i++) { int j = i + gap; // x = ((i + 2) <= j) ? dp[i + 2][j] : 0; // y = ((i + 1) <= (j - 1)) ? dp[i + 1][j - 1] : 0; // z = (i <= (j - 2)) ? dp[i][j - 2] : 0; // // dp[i][j] = max(arr[i] + min(x, y), arr[j] + min(y, z)); int s1 = min(dp[i + 2][j], dp[i + 1][j - 1]) + arr[i]; int s2 = min(dp[i][j - 2], dp[i + 1][j - 1]) + arr[j]; dp[i][j] = max(s1, s2); } } return dp[0][n - 1]; } // Driver program to test above function int main() { int arr1[] = { 8, 15, 3, 7 }; int n = sizeof(arr1) / sizeof(arr1[0]); printf("%d\n", optimalStrategyOfGame(arr1, n)); int arr2[] = { 2, 2, 2, 2 }; n = sizeof(arr2) / sizeof(arr2[0]); printf("%d\n", optimalStrategyOfGame(arr2, n)); int arr3[] = { 20, 30, 2, 2, 2, 10 }; n = sizeof(arr3) / sizeof(arr3[0]); printf("%d\n", optimalStrategyOfGame(arr3, n)); return 0; }
true
7cefac465da7ed33957ae1b7cf859e08811acdc8
C++
ivanasen/suffix_automata
/tests/SuffixAutomataTests.cpp
UTF-8
1,605
3.125
3
[]
no_license
#include <iostream> #include <string.h> #include "../src/SuffixAutomata.h" using namespace std; void testSingle(char *s, int states, int transitions, int finals) { SuffixAutomata a(s, strlen(s)); cout << (a.getStatesCount() == states) << (a.getTransitionsCount() == transitions) << (a.getFinalsCount() == finals); } void testStatesTransitionsAndFinals() { testSingle("", 1, 0, 1); testSingle("b", 2, 1, 2); testSingle("aa", 3, 2, 3); testSingle("abcbc", 8, 9, 3); testSingle("bbacbba", 8, 10, 3); testSingle("bbacbbaa", 10, 14, 3); testSingle("cpalgorithmspageauthorssuffixautomatontableofcontentsdefinition", 88, 144, 4); testSingle("abcbcbcbcbcbcbcbc", 32, 33, 9); cout << '\n'; } void squaresSingle(char *s, int expectedSquares) { SuffixAutomata a(s, strlen(s)); cout << (a.getSquaresCount() == expectedSquares); } void testSquares() { squaresSingle("", 1); squaresSingle("abcbc", 1); squaresSingle("aaaa", 3); squaresSingle("cacaac", 2); squaresSingle("bbaacaa", 3); squaresSingle("bcbcc", 2); squaresSingle("bcbcbcbc", 3); squaresSingle("abcabc", 2); squaresSingle("abbcbb", 2); squaresSingle("abbb", 2); squaresSingle("abcbcbcbc", 2); squaresSingle("abcdbcdebcdbcd", 2); squaresSingle("abbbbb", 3); squaresSingle("ebcbcbabc", 1); squaresSingle("ebcbcbcbcebabcbabc", 2); squaresSingle("baacaaddeddeddedd", 4); squaresSingle("baaaab", 2); cout << '\n'; } void runSuffixAutomataTests() { testStatesTransitionsAndFinals(); testSquares(); }
true
66323f1ccc21de8dde5456335150ef1f4feb9d5e
C++
leyvae/C-GoFish
/deck.cpp
UTF-8
2,996
3.953125
4
[ "MIT" ]
permissive
#include "deck.hpp" /****************************************************************** * Function: Deck() * Description: Default Deck constructor that initializes a dinamic array of Cards and sets their rank and suit * Parameters: None * Pre-Conditions: None * Post-Conditions: A full new deck is created ******************************************************************/ Deck::Deck(){ cards = new Card[52]; numCards = 52; int count = 0; for(int r = 0; r < 13; r++){ for(int s = 0; s < 4; s++){ cards[count].setRank(r); cards[count].setSuit(s); count++; } } } /****************************************************************** * Function: ~Deck() * Description: Destructor that deletes the dynamically created array of cards * Parameters: None * Pre-Conditions: cards must be instantiated * Post-Conditions: cards is deleted ******************************************************************/ Deck::~Deck(){ delete[] cards; } /****************************************************************** * Function: getCards() * Description: gets this Deck's cards * Parameters: None * Pre-Conditions: cards has been initialized * Post-Conditions: cards' value is accessible ******************************************************************/ Card* Deck::getCards(){ return cards; } /****************************************************************** * Function: shuffleDeck() * Description: randomly shuffles the deck of cards by switching two random Cards repeatedly * Parameters: None * Pre-Conditions: cards must be instantiated * Post-Conditions: cards is shuffled ******************************************************************/ void Deck::shuffleDeck(){ srand(time(NULL)); /* change two card positions 1000 times to shuffle */ for(int i = 0; i < 1000; i++){ int card1 = rand() % 52; int card2 = rand() % 52; Card temp = cards[card1]; cards[card1] = cards[card2]; cards[card2] = temp; } } /****************************************************************** * Function: deal() * Description: removes and returns a single card from cards * Parameters: None * Pre-Conditions: cards must be instantiated * Post-Conditions: cards loses one card ******************************************************************/ Card Deck::deal(){ Card draw = cards[numCards-1]; numCards--; return draw; } /****************************************************************** * Function: printDeck() * Description: prints rank and Suit of every card in this Deck * Parameters: None * Pre-Conditions: None * Post-Conditions: None ******************************************************************/ void Deck::printDeck(){ for(int i = 0; i < numCards; i++){ cout << "Rank: " << cards[i].getRank() << " "; cout << "Suit: " << cards[i].getSuit() << endl; } }
true
b05a501bb76926ba9f625df87e7722a6095d633b
C++
sudnya/sudnya-template-library
/test/test-type-list.cpp
UTF-8
2,295
3.265625
3
[]
no_license
#include <iostream> class NullType; template<typename Payload, typename Next> class TypeList { public: typedef Payload payload_type; typedef Next next_type; }; // TODO : append_type template<typename List, typename Value> class append_type { // value not nullType static_assert(); public: typedef TypeList<typename List::payload_type, typename append_type<typename List::next_type, Value>::type> type; }; template<typename Value> class append_type<TypeList<NullType, NullType>, Value> { public: typedef TypeList<Value, NullType> type; }; template<typename Payload, typename Value> class append_type<TypeList<Payload, NullType>, Value> { public: typedef TypeList<Payload, TypeList<Value, NullType>> type; }; // TODO: new_type_list class new_type_list { public: typedef TypeList<NullType, NullType> type; }; template<typename T> class get_first_type { public: typedef typename T::payload_type type; }; template<typename T> class get_second_type { public: typedef typename T::next_type type; }; template<typename T> class print_types { public: void operator()() const { typedef typename get_first_type<T>::type first; typedef typename get_second_type<T>::type second; print_types<first>()(); print_types<second>()(); } }; template<> class print_types<int> { public: void operator()() const { std::cout << "int "; } }; template<> class print_types<float> { public: void operator()() const { std::cout << "float "; } }; template<> class print_types<char> { public: void operator()() const { std::cout << "char\n"; } }; template<> class print_types<NullType> { public: void operator()() const { //intentionally blank } }; int main(int argc, char** argv) { typedef typename new_type_list::type empty_list; typedef typename append_type<empty_list, int>::type temp1; typedef typename append_type<temp1, float>::type temp2; typedef typename append_type<temp2, float>::type temp3; typedef typename append_type<temp3, float>::type temp4; typedef typename append_type<temp4, char>::type complete_list; print_types<complete_list>()(); return 0; }
true
182f6f16060042ec8b95de71e1b13d2dfb9254da
C++
ZHOURUIH/GameEditor
/CodeGenerator_Normal/Frame/Utility/StringUtility.cpp
UTF-8
57,546
2.953125
3
[]
no_license
#include "Utility.h" const char StringUtility::BOM[4]{ (char)0xEF, (char)0xBB, (char)0xBF, 0 }; myVector<int> StringUtility::mTempIntList; string StringUtility::removeStartString(const string& fileName, const string& startStr) { if (startWith(fileName, startStr.c_str())) { return fileName.substr(startStr.length(), fileName.length() - startStr.length()); } return fileName; } string StringUtility::removeSuffix(const string& str) { int dotPos = (int)str.find_last_of('.'); if (dotPos != -1) { return str.substr(0, dotPos); } return str; } void StringUtility::removeStartAll(string& stream, char key) { int firstNotPos = -1; uint streamSize = (uint)stream.length(); FOR_I(streamSize) { if (stream[i] != key) { firstNotPos = i; break; } } if (firstNotPos > 0) { stream.erase(0, firstNotPos); } } void StringUtility::removeStart(string& stream, char key) { uint streamSize = (uint)stream.length(); FOR_I(streamSize) { if (stream[streamSize - i - 1] == key) { stream.erase(streamSize - i - 1, 1); break; } } } void StringUtility::removeLastAll(string& stream, char key) { int lastNotPos = -1; uint streamSize = (uint)stream.length(); FOR_I(streamSize) { if (stream[streamSize - i - 1] != key) { lastNotPos = streamSize - i - 1; break; } } if (lastNotPos != -1 && lastNotPos != streamSize - 1) { stream.erase(lastNotPos + 1); } } void StringUtility::removeLast(string& stream, char key) { uint streamSize = (uint)stream.length(); FOR_I(streamSize) { if (stream[streamSize - i - 1] == key) { stream.erase(streamSize - i - 1, 1); break; } } } void StringUtility::removeLastComma(string& stream) { removeLast(stream, ','); } void StringUtility::removeEnd(string& str, char key) { if (str[str.length() - 1] == key) { str.erase(str.length() - 1, 1); } } int StringUtility::findCharCount(const string& str, char key) { int count = 0; uint length = (uint)str.length(); FOR_I(length) { if (str[i] == key) { ++count; } } return count; } string StringUtility::getFileName(string str) { rightToLeft(str); int dotPos = (int)str.find_last_of('/'); if (dotPos != -1) { return str.substr(dotPos + 1, str.length() - 1); } return str; } string StringUtility::getFileNameNoSuffix(string str, bool removePath) { rightToLeft(str); int dotPos = (int)str.find_last_of('.'); if (removePath) { int namePos = (int)str.find_last_of('/'); if (namePos != -1) { if (dotPos != -1) { return str.substr(namePos + 1, dotPos - namePos - 1); } else { return str.substr(namePos + 1); } } } else { if (dotPos != -1) { return str.substr(0, dotPos); } } return str; } string StringUtility::getFilePath(const string& dir) { string tempDir = dir; rightToLeft(tempDir); if (tempDir[tempDir.length() - 1] == '/') { tempDir.erase(tempDir.length() - 1); } int pos = (int)tempDir.find_last_of('/'); return pos != -1 ? dir.substr(0, pos) : "./"; } string StringUtility::getFileSuffix(const string& fileName) { int dotPos = (int)fileName.find_last_of('.'); if (dotPos != -1) { return fileName.substr(dotPos + 1, fileName.length() - dotPos - 1); } return fileName; } string StringUtility::replaceSuffix(const string& fileName, const string& suffix) { return getFileNameNoSuffix(fileName, false) + suffix; } int StringUtility::getLastNotNumberPos(const string& str) { uint strLen = (uint)str.length(); FOR_I(strLen) { if (str[strLen - i - 1] > '9' || str[strLen - i - 1] < '0') { return strLen - i - 1; } } return -1; } int StringUtility::getLastNumber(const string& str) { int lastPos = getLastNotNumberPos(str); if (lastPos == -1) { return -1; } string numStr = str.substr(lastPos + 1, str.length() - lastPos - 1); if (numStr.length() == 0) { return 0; } return stringToInt(numStr); } string StringUtility::getNotNumberSubString(string str) { return str.substr(0, getLastNotNumberPos(str) + 1); } void StringUtility::replace(char* str, int strBufferSize, int begin, int end, const char* reStr) { uint curLength = (uint)strlen(str); uint replaceLength = (uint)strlen(reStr); int lengthAfterReplace = begin + replaceLength + curLength - end; if (lengthAfterReplace >= strBufferSize) { ERROR("buffer is too small!"); return; } memmove(str + begin + replaceLength, str + end, curLength - end); memcpy(str + begin, reStr, replaceLength); } void StringUtility::replace(string& str, int begin, int end, const string& reStr) { string sub1 = str.substr(0, begin); string sub2 = str.substr(end, str.length() - end); str = sub1 + reStr + sub2; } void StringUtility::replaceAll(char* str, int strBufferSize, const char* key, const char* newWords) { uint keyLength = (uint)strlen(key); uint newWordsLength = (uint)strlen(newWords); int startPos = 0; while (true) { int pos = 0; if (!findString(str, key, &pos, startPos)) { break; } replace(str, strBufferSize, pos, pos + keyLength, newWords); startPos = pos + newWordsLength; } } void StringUtility::replaceAll(string& str, const string& key, const string& newWords) { uint keyLength = (uint)key.length(); uint newWordsLength = (uint)newWords.length(); int startPos = 0; while (true) { int pos = 0; if (!findString(str.c_str(), key.c_str(), &pos, startPos)) { break; } replace(str, pos, pos + keyLength, newWords); startPos = pos + newWordsLength; } } void StringUtility::removeAll(string& str, char value) { int strLength = (int)str.length(); char* tempBuffer = ArrayPool::newArray<char>(MathUtility::getGreaterPower2(strLength + 1)); memcpy(tempBuffer, str.c_str(), strLength); tempBuffer[strLength] = '\0'; for (int i = strLength; i >= 0; --i) { if (tempBuffer[i] == value) { // 移动数据 if (i != strLength - 1) { memmove(tempBuffer + i, tempBuffer + i + 1, strLength - i - 1); } --strLength; } } tempBuffer[strLength] = '\0'; str.assign(tempBuffer); } void StringUtility::removeAll(string& str, char value0, char value1) { int strLength = (int)str.length(); char* tempBuffer = ArrayPool::newArray<char>(MathUtility::getGreaterPower2(strLength + 1)); memcpy(tempBuffer, str.c_str(), strLength); tempBuffer[strLength] = '\0'; for (int i = strLength; i >= 0; --i) { if (tempBuffer[i] == value0 || tempBuffer[i] == value1) { // 移动数据 if (i != strLength - 1) { memmove(tempBuffer + i, tempBuffer + i + 1, strLength - i - 1); } --strLength; } } tempBuffer[strLength] = '\0'; str.assign(tempBuffer); } void StringUtility::split(const char* str, const char* key, myVector<string>& vec, bool removeEmpty) { int startPos = 0; int keyLen = (int)strlen(key); int sourceLen = (int)strlen(str); const int STRING_BUFFER = 1024; char curString[STRING_BUFFER]; int devidePos = -1; while (true) { bool ret = findString(str, key, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { if (devidePos - startPos >= STRING_BUFFER) { ERROR("分隔字符串失败,缓冲区太小,当前缓冲区为" + intToString(STRING_BUFFER) + "字节, 字符串:" + str + ", key:" + key); return; } MEMCPY(curString, STRING_BUFFER, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { if (sourceLen - startPos >= STRING_BUFFER) { ERROR("分隔字符串失败,缓冲区太小,当前缓冲区为" + intToString(STRING_BUFFER) + "字节, 字符串:" + str + ", key:" + key); return; } MEMCPY(curString, STRING_BUFFER, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 放入列表 if (curString[0] != '\0' || !removeEmpty) { vec.push_back(curString); } if (!ret) { break; } startPos = devidePos + keyLen; } } uint StringUtility::split(const char* str, const char* key, string* stringBuffer, uint bufferSize, bool removeEmpty) { int startPos = 0; int keyLen = (int)strlen(key); int sourceLen = (int)strlen(str); const int STRING_BUFFER = 1024; char curString[STRING_BUFFER]; int devidePos = -1; uint curCount = 0; while (true) { bool ret = findString(str, key, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { if (devidePos - startPos >= STRING_BUFFER) { ERROR("分隔字符串失败,缓冲区太小,当前缓冲区为" + intToString(STRING_BUFFER) + "字节, 字符串:" + str + ", key:" + key); return 0; } MEMCPY(curString, STRING_BUFFER, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { if (sourceLen - startPos >= STRING_BUFFER) { ERROR("分隔字符串失败,缓冲区太小,当前缓冲区为" + intToString(STRING_BUFFER) + "字节, 字符串:" + str + ", key:" + key); return 0; } MEMCPY(curString, STRING_BUFFER, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 放入列表 if (curString[0] != '\0' || !removeEmpty) { if (curCount >= bufferSize) { ERROR("string buffer is too small! bufferSize:" + intToString(bufferSize)); } stringBuffer[curCount++] = curString; } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } string StringUtility::strReplace(const string& str, uint begin, uint end, const string& reStr) { string sub1 = str.substr(0, begin); string sub2 = str.substr(end, str.length() - end); return sub1 + reStr + sub2; } void StringUtility::strReplaceAll(string& str, const char* key, const string& newWords) { int keyLen = (int)strlen(key); int startPos = 0; while (true) { int pos = -1; if (!findSubstr(str, key, &pos, startPos)) { break; } str = strReplace(str, pos, pos + keyLen, newWords); startPos = pos + (int)newWords.length(); } } void StringUtility::_itoa_s(int value, char* charArray, uint size) { if (value == 0) { charArray[0] = '0'; charArray[1] = '\0'; return; } int sign = 1; if (value < 0) { value = -value; sign = -1; } static array<ullong, 11> power{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 }; if ((ullong)value > power[power.size() - 1]) { ERROR("int value is too large:" + ullongToString((ullong)value)); return; } uint index = 0; while (true) { // 如果是正数,则数字个数不能超过size - 1 // 如果是负数,则数字个数不能超过size - 2 if ((sign > 0 && index >= size) || (sign < 0 && index >= size - 1)) { ERROR("buffer is too small!"); break; } // 将数字放入numberArray的尾部 if ((ullong)value < power[index]) { break; } charArray[size - 1 - index] = (int)((ullong)value % power[index + 1] / power[index]); ++index; } // 将数字从数组末尾移动到开头,并且将数字转换为数字字符 if (sign > 0) { uint lengthToHead = size - index; FOR_I(index) { charArray[i] = charArray[i + lengthToHead] + '0'; } charArray[index] = '\0'; } else { uint lengthToHead = size - index; FOR_I(index) { charArray[i + 1] = charArray[i + lengthToHead] + '0'; } charArray[0] = '-'; charArray[index + 1] = '\0'; } } void StringUtility::_i64toa_s(const ullong& value, char* charArray, uint size) { if (value == 0) { charArray[0] = '0'; charArray[1] = '\0'; return; } static array<ullong, 20> power = { 1ul, 10ul, 100ul, 1000ul, 10000ul, 100000ul, 1000000ul, 10000000ul, 100000000ul, 1000000000ul, 10000000000ul, 100000000000ul, 1000000000000ul, 10000000000000ul, 100000000000000ul, 1000000000000000ul, 10000000000000000ul, 100000000000000000ul, 1000000000000000000ul, 10000000000000000000ul }; if (value > power[power.size() - 1]) { ERROR("long long value is too large"); return; } uint index = 0; while (true) { // 如果是正数,则数字个数不能超过size - 1 if (index >= size) { ERROR("buffer is too small!"); break; } // 将数字放入numberArray的尾部 if (value < power[index]) { break; } charArray[size - 1 - index] = (int)(value % power[index + 1] / power[index]); ++index; } // 将数字从数组末尾移动到开头,并且将数字转换为数字字符 uint lengthToHead = size - index; FOR_I(index) { charArray[i] = charArray[i + lengthToHead] + '0'; } charArray[index] = '\0'; } void StringUtility::strcat_s(char* destBuffer, uint size, const char* source) { FOR_I((uint)size) { // 找到字符串的末尾 if (destBuffer[i] == '\0') { uint index = 0; while (true) { if (index + i >= (uint)size) { ERROR("strcat_s buffer is too small"); break; } destBuffer[i + index] = source[index]; if (source[index] == '\0') { break; } ++index; } break; } } } void StringUtility::strcpy_s(char* destBuffer, uint size, const char* source) { uint index = 0; while (true) { if (index >= size) { ERROR("strcat_s buffer is too small"); break; } destBuffer[index] = source[index]; if (source[index] == '\0') { break; } ++index; } } string StringUtility::intToString(int value, uint limitLen) { array<char, 16> temp; _itoa_s(value, temp); uint len = (uint)strlen(temp._Elems); if (limitLen > len) { return zeroString(limitLen - len) + temp._Elems; } return temp._Elems; } void StringUtility::intToString(char* charArray, uint size, int value, uint limitLen) { if (limitLen == 0) { _itoa_s(value, charArray, size); } else { // 因为当前函数设计为线程安全,所以只能使用栈内存中的数组 array<char, 16> temp; _itoa_s(value, temp); // 判断是否需要在前面补0 if (limitLen > 0) { uint len = (uint)strlen(temp._Elems); if (limitLen > len) { // 因为当前函数设计为线程安全,所以只能使用栈内存中的数组 array<char, 16> zeroArray; zeroString(zeroArray, limitLen - len); STRCAT2_N(charArray, size, zeroArray._Elems, temp._Elems); return; } } strcpy_s(charArray, size, temp._Elems); } } string StringUtility::ullongToString(const ullong& value, uint limitLen) { array<char, 32> temp; _i64toa_s(value, temp); uint len = (uint)strlen(temp._Elems); if (limitLen > len) { return zeroString(limitLen - len) + temp._Elems; } return temp._Elems; } void StringUtility::ullongToString(char* charArray, uint size, const ullong& value, uint limitLen) { if (limitLen == 0) { _i64toa_s(value, charArray, size); } else { array<char, 32> temp; _i64toa_s(value, temp); // 判断是否需要在前面补0 if (limitLen > 0) { uint len = (uint)strlen(temp._Elems); if (limitLen > len) { array<char, 16> zeroArray; zeroString(zeroArray, limitLen - len); STRCAT2_N(charArray, size, zeroArray._Elems, temp._Elems); return; } } strcpy_s(charArray, size, temp._Elems); } } string StringUtility::ullongArrayToString(ullong* valueList, uint llongCount, uint limitLen, const char* seperate) { // 根据列表长度选择适当的数组长度,每个llong默认数字长度为32个字符 int arrayLen = 32 * MathUtility::getGreaterPower2(llongCount); char* charArray = ArrayPool::newArray<char>(arrayLen); charArray[0] = 0; array<char, 32> temp; FOR_I(llongCount) { ullongToString(temp, valueList[i], limitLen); if (i != llongCount - 1) { STR_APPEND2_N(charArray, arrayLen, temp._Elems, seperate); } else { STR_APPEND1_N(charArray, arrayLen, temp._Elems); } } string str(charArray); ArrayPool::deleteArray(charArray); return str; } void StringUtility::ullongArrayToString(char* buffer, uint bufferSize, ullong* valueList, uint count, const char* seperate) { buffer[0] = '\0'; array<char, 32> temp; FOR_I(count) { ullongToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(buffer, bufferSize, temp._Elems, seperate); } else { STR_APPEND1_N(buffer, bufferSize, temp._Elems); } } } string StringUtility::uintArrayToString(uint* valueList, uint uintCount, uint limitLen, const char* seperate) { // 根据列表长度选择适当的数组长度,每个uint默认数字长度为16个字符 int arrayLen = 16 * MathUtility::getGreaterPower2(uintCount); char* charArray = ArrayPool::newArray<char>(arrayLen); charArray[0] = 0; array<char, 16> temp; FOR_I(uintCount) { intToString(temp, valueList[i], limitLen); if (i != uintCount - 1) { STR_APPEND2_N(charArray, arrayLen, temp._Elems, seperate); } else { STR_APPEND1_N(charArray, arrayLen, temp._Elems); } } string str(charArray); ArrayPool::deleteArray(charArray); return str; } void StringUtility::uintArrayToString(char* buffer, uint bufferSize, uint* valueList, uint count, const char* seperate) { buffer[0] = '\0'; array<char, 16> temp; FOR_I(count) { intToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(buffer, bufferSize, temp._Elems, seperate); } else { STR_APPEND1_N(buffer, bufferSize, temp._Elems); } } } string StringUtility::byteArrayToString(byte* valueList, uint intCount, uint limitLen, const char* seperate) { int arrayLen = 4 * MathUtility::getGreaterPower2(intCount); char* charArray = ArrayPool::newArray<char>(arrayLen); charArray[0] = 0; array<char, 4> temp; FOR_I(intCount) { intToString(temp, valueList[i], limitLen); if (i != intCount - 1) { STR_APPEND2_N(charArray, arrayLen, temp._Elems, seperate); } else { STR_APPEND1_N(charArray, arrayLen, temp._Elems); } } string str(charArray); ArrayPool::deleteArray(charArray); return str; } void StringUtility::byteArrayToString(char* buffer, uint bufferSize, byte* valueList, uint count, const char* seperate) { buffer[0] = '\0'; array<char, 4> temp; FOR_I(count) { intToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(buffer, bufferSize, temp._Elems, seperate); } else { STR_APPEND1_N(buffer, bufferSize, temp._Elems); } } } string StringUtility::ushortArrayToString(ushort* valueList, uint intCount, uint limitLen, const char* seperate) { int arrayLen = 8 * MathUtility::getGreaterPower2(intCount); char* charArray = ArrayPool::newArray<char>(arrayLen); charArray[0] = 0; array<char, 8> temp; FOR_I(intCount) { intToString(temp, valueList[i], limitLen); if (i != intCount - 1) { STR_APPEND2_N(charArray, arrayLen, temp._Elems, seperate); } else { STR_APPEND1_N(charArray, arrayLen, temp._Elems); } } string str(charArray); ArrayPool::deleteArray(charArray); return str; } void StringUtility::ushortArrayToString(char* buffer, uint bufferSize, ushort* valueList, uint count, const char* seperate) { buffer[0] = '\0'; array<char, 8> temp; FOR_I(count) { intToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(buffer, bufferSize, temp._Elems, seperate); } else { STR_APPEND1_N(buffer, bufferSize, temp._Elems); } } } string StringUtility::intArrayToString(int* valueList, uint intCount, uint limitLen, const char* seperate) { // 根据列表长度选择适当的数组长度,每个int默认数字长度为16个字符 int arrayLen = 16 * MathUtility::getGreaterPower2(intCount); char* charArray = ArrayPool::newArray<char>(arrayLen); charArray[0] = 0; array<char, 16> temp; FOR_I(intCount) { intToString(temp, valueList[i], limitLen); if (i != intCount - 1) { STR_APPEND2_N(charArray, arrayLen, temp._Elems, seperate); } else { STR_APPEND1_N(charArray, arrayLen, temp._Elems); } } string str(charArray); ArrayPool::deleteArray(charArray); return str; } void StringUtility::intArrayToString(char* buffer, uint bufferSize, int* valueList, uint count, const char* seperate) { buffer[0] = '\0'; array<char, 16> temp; FOR_I(count) { intToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(buffer, bufferSize, temp._Elems, seperate); } else { STR_APPEND1_N(buffer, bufferSize, temp._Elems); } } } void StringUtility::stringToByteArray(const string& str, myVector<byte>& valueList, const char* seperate) { myVector<string> strList; split(str.c_str(), seperate, strList); FOR_VECTOR_CONST(strList) { valueList.push_back(stringToInt(strList[i])); } } uint StringUtility::stringToByteArray(const char* str, byte* buffer, uint bufferSize, const char* seperate) { uint curCount = 0; uint startPos = 0; uint keyLen = (uint)strlen(seperate); uint sourceLen = (uint)strlen(str); const int BUFFER_SIZE = 4; array<char, BUFFER_SIZE> curString; int devidePos = -1; while (true) { bool ret = findString(str, seperate, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 转换为整数放入列表 if (curString[0] != '\0') { buffer[curCount++] = stringToInt(curString._Elems); if (curCount >= bufferSize) { ERROR("int buffer size is too small, bufferSize:" + intToString(bufferSize)); break; } } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } void StringUtility::stringToUShortArray(const string& str, myVector<ushort>& valueList, const char* seperate) { myVector<string> strList; split(str.c_str(), seperate, strList); FOR_VECTOR_CONST(strList) { valueList.push_back(stringToInt(strList[i])); } } uint StringUtility::stringToUShortArray(const char* str, ushort* buffer, uint bufferSize, const char* seperate) { uint curCount = 0; uint startPos = 0; uint keyLen = (uint)strlen(seperate); uint sourceLen = (uint)strlen(str); const int BUFFER_SIZE = 8; array<char, BUFFER_SIZE> curString; int devidePos = -1; while (true) { bool ret = findString(str, seperate, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 转换为整数放入列表 if (curString[0] != '\0') { buffer[curCount++] = stringToInt(curString._Elems); if (curCount >= bufferSize) { ERROR("int buffer size is too small, bufferSize:" + intToString(bufferSize)); break; } } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } void StringUtility::stringToIntArray(const string& str, myVector<int>& valueList, const char* seperate) { myVector<string> strList; split(str.c_str(), seperate, strList); FOR_VECTOR_CONST(strList) { valueList.push_back(stringToInt(strList[i])); } } uint StringUtility::stringToIntArray(const char* str, int* buffer, uint bufferSize, const char* seperate) { uint curCount = 0; uint startPos = 0; uint keyLen = (uint)strlen(seperate); uint sourceLen = (uint)strlen(str); const int BUFFER_SIZE = 16; array<char, BUFFER_SIZE> curString; int devidePos = -1; while (true) { bool ret = findString(str, seperate, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 转换为整数放入列表 if (curString[0] != '\0') { buffer[curCount++] = stringToInt(curString._Elems); if (curCount >= bufferSize) { ERROR("int buffer size is too small, bufferSize:" + intToString(bufferSize)); break; } } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } void StringUtility::stringToUIntArray(const string& str, myVector<uint>& valueList, const char* seperate) { myVector<string> strList; split(str.c_str(), seperate, strList); FOR_VECTOR_CONST(strList) { valueList.push_back((uint)stringToInt(strList[i])); } } uint StringUtility::stringToUIntArray(const char* str, uint* buffer, uint bufferSize, const char* seperate) { uint curCount = 0; uint startPos = 0; uint keyLen = (uint)strlen(seperate); uint sourceLen = (uint)strlen(str); const int BUFFER_SIZE = 16; array<char, BUFFER_SIZE> curString; int devidePos = -1; while (true) { bool ret = findString(str, seperate, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 转换为长整数放入列表 if (curString[0] != '\0') { buffer[curCount++] = stringToInt(curString._Elems); if (curCount >= bufferSize) { ERROR("uint buffer size is too small, bufferSize:" + intToString(bufferSize)); break; } } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } void StringUtility::stringToULLongArray(const string& str, myVector<ullong>& valueList, const char* seperate) { myVector<string> strList; split(str.c_str(), seperate, strList); FOR_VECTOR_CONST(strList) { valueList.push_back(stringToULLong(strList[i])); } } uint StringUtility::stringToULLongArray(const char* str, ullong* buffer, uint bufferSize, const char* seperate) { uint curCount = 0; uint startPos = 0; uint keyLen = (uint)strlen(seperate); uint sourceLen = (uint)strlen(str); const int BUFFER_SIZE = 32; array<char, BUFFER_SIZE> curString; int devidePos = -1; while (true) { bool ret = findString(str, seperate, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 转换为长整数放入列表 if (curString[0] != '\0') { buffer[curCount++] = stringToULLong(curString._Elems); if (curCount > bufferSize) { ERROR("ullong buffer size is too small, bufferSize:" + intToString(bufferSize)); break; } } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } string StringUtility::zeroString(uint count) { array<char, 16> charArray; FOR_I(count) { charArray[i] = '0'; } charArray[count] = '\0'; return charArray._Elems; } void StringUtility::zeroString(char* charArray, uint size, uint count) { if (size < count) { ERROR("buffer is too small"); return; } FOR_I(count) { charArray[i] = '0'; } charArray[count] = '\0'; } string StringUtility::floatToStringExtra(float f, uint precision, bool removeTailZero) { const static string zeroDot = "0."; string retString; do { if (!IS_FLOAT_ZERO(f)) { float powerValue = MathUtility::powerFloat(10.0f, precision); float totalValue = f * powerValue + MathUtility::sign(f) * 0.5f; if ((int)totalValue == 0) { if (precision > 0) { array<char, 16> temp; zeroString(temp, precision); retString += zeroDot + temp._Elems; } else { retString = "0"; } } else { array<char, 16> temp; intToString(temp, abs((int)totalValue)); retString = temp._Elems; int dotPosition = (int)strlen(retString.c_str()) - precision; if (dotPosition <= 0) { array<char, 16> tempZero; zeroString(tempZero, -dotPosition); retString = zeroDot + tempZero._Elems + retString; } else { retString.insert(dotPosition, "."); } // 为负数时,确保负号始终在最前面 if ((int)totalValue < 0) { retString = "-" + retString; } } } else { if (precision > 0) { array<char, 16> tempZero; zeroString(tempZero, precision); retString = zeroDot + tempZero._Elems; } else { retString = "0"; } } } while (false); // 移除末尾无用的0 if (removeTailZero && retString[retString.length() - 1] == '0') { int dotPos = (int)retString.find_last_of('.'); if (dotPos != -1) { string floatPart = retString.substr(dotPos + 1, retString.length() - dotPos - 1); // 找到最后一个不是0的位置,然后将后面的所有0都去掉 int notZeroPos = (int)floatPart.find_last_not_of('0'); // 如果小数部分全是0,则将小数点也一起去掉 if (notZeroPos == -1) { retString = retString.substr(0, dotPos); } // 去除小数部分末尾所有0 else if (notZeroPos != (int)floatPart.length() - 1) { retString = retString.substr(0, dotPos + 1) + floatPart.substr(0, notZeroPos + 1); } } } return retString; } string StringUtility::floatToString(float f) { array<char, 16> temp; floatToString(temp, f); return temp._Elems; } void StringUtility::floatToString(char* charArray, uint size, float f) { SPRINTF(charArray, size, "%f", f); // 先查找小数点和结束符的位置 int dotPos = -1; uint strLen = 0; FOR_I(size) { if (charArray[i] == '.') { dotPos = i; } else if (charArray[i] == '\0') { strLen = i; break; } } if (dotPos >= 0) { // 从结束符往前查找 bool findEnd = false; FOR_I(strLen) { uint index = strLen - 1 - i; // 如果找到了小数点仍然没有找到一个不为'0'的字符,则从小数点部分截断字符串 if (index == (uint)dotPos) { charArray[dotPos] = '\0'; break; } // 找到小数点后的从后往前的第一个不为'0'的字符,从此处截断字符串 if (charArray[index] != '0' && index + 1 < strLen) { charArray[index + 1] = '\0'; break; } } } } string StringUtility::floatArrayToString(float* valueList, uint count, const char* seperate) { // 根据列表长度选择适当的数组长度,每个float默认数字长度为16个字符 int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); charArray[0] = 0; array<char, 16> temp; FOR_I(count) { floatToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(charArray, arrayLen, temp._Elems, seperate); } else { STR_APPEND1_N(charArray, arrayLen, temp._Elems); } } string str(charArray); ArrayPool::deleteArray(charArray); return str; } void StringUtility::floatArrayToString(char* buffer, uint bufferSize, float* valueList, uint count, const char* seperate) { buffer[0] = '\0'; array<char, 16> temp; FOR_I(count) { floatToString(temp, valueList[i]); if (i != count - 1) { STR_APPEND2_N(buffer, bufferSize, temp._Elems, seperate); } else { STR_APPEND1_N(buffer, bufferSize, temp._Elems); } } } void StringUtility::stringToFloatArray(const string& str, myVector<float>& valueList, const char* seperate) { myVector<string> strList; split(str.c_str(), seperate, strList); uint count = strList.size(); FOR_I(count) { if (strList[i].length() > 0) { valueList.push_back(stringToFloat(strList[i])); } } } uint StringUtility::stringToFloatArray(const char* str, float* buffer, uint bufferSize, const char* seperate) { uint curCount = 0; uint startPos = 0; uint keyLen = (uint)strlen(seperate); uint sourceLen = (uint)strlen(str); const int BUFFER_SIZE = 32; array<char, BUFFER_SIZE> curString; int devidePos = -1; while (true) { bool ret = findString(str, seperate, &devidePos, startPos); // 无论是否查找到,都将前面一段字符串截取出来 if (ret) { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, devidePos - startPos); curString[devidePos - startPos] = '\0'; } else { MEMCPY(curString._Elems, BUFFER_SIZE, str + startPos, sourceLen - startPos); curString[sourceLen - startPos] = '\0'; } // 转换为长整数放入列表 if (curString[0] != '\0') { buffer[curCount++] = stringToFloat(curString._Elems); if (curCount > bufferSize) { ERROR("float buffer size is too small, bufferSize:" + intToString(bufferSize)); break; } } if (!ret) { break; } startPos = devidePos + keyLen; } return curCount; } string StringUtility::vector2ToString(const Vector2& vec, const char* seperate) { return floatToString(vec.x) + seperate + floatToString(vec.y); } void StringUtility::vector2ToString(char* buffer, uint bufferSize, const Vector2& vec, const char* seperate) { buffer[0] = '\0'; FLOAT_TO_STRING(xStr, vec.x); FLOAT_TO_STRING(yStr, vec.y); STR_APPEND3_N(buffer, bufferSize, xStr, seperate, yStr); } Vector2 StringUtility::stringToVector2(const string& str, const char* seperate) { Vector2 value; array<string, 2> valueList; if (split(str.c_str(), seperate, valueList) == valueList.size()) { value.x = stringToFloat(valueList[0]); value.y = stringToFloat(valueList[1]); } return value; } Vector2Int StringUtility::stringToVector2Int(const string& str, const char* seperate) { Vector2Int value; array<string, 2> valueList; if (split(str.c_str(), seperate, valueList) == valueList.size()) { value.x = stringToInt(valueList[0]); value.y = stringToInt(valueList[1]); } return value; } Vector2UShort StringUtility::stringToVector2UShort(const string& str, const char* seperate) { Vector2UShort value; array<string, 2> valueList; if (split(str.c_str(), seperate, valueList) == valueList.size()) { value.x = stringToInt(valueList[0]); value.y = stringToInt(valueList[1]); } return value; } string StringUtility::vector3ToString(const Vector3& vec, const char* seperate) { return floatToString(vec.x) + seperate + floatToString(vec.y) + seperate + floatToString(vec.z); } void StringUtility::vector3ToString(char* buffer, uint bufferSize, const Vector3& vec, const char* seperate) { buffer[0] = '\0'; FLOAT_TO_STRING(xStr, vec.x); FLOAT_TO_STRING(yStr, vec.y); FLOAT_TO_STRING(zStr, vec.z); STR_APPEND5_N(buffer, bufferSize, xStr, seperate, yStr, seperate, zStr); } string StringUtility::vector2IntToString(const Vector2Int& value, const char* seperate) { return intToString(value.x) + seperate + intToString(value.y); } string StringUtility::vector2UShortToString(const Vector2UShort& value, const char* seperate) { return intToString(value.x) + seperate + intToString(value.y); } void StringUtility::vector2IntToString(char* buffer, uint bufferSize, const Vector2Int& value, const char* seperate) { buffer[0] = '\0'; INT_TO_STRING(xStr, value.x); INT_TO_STRING(yStr, value.y); STR_APPEND3_N(buffer, bufferSize, xStr, seperate, yStr); } void StringUtility::vector2UShortToString(char* buffer, uint bufferSize, const Vector2UShort& value, const char* seperate) { buffer[0] = '\0'; INT_TO_STRING(xStr, value.x); INT_TO_STRING(yStr, value.y); STR_APPEND3_N(buffer, bufferSize, xStr, seperate, yStr); } Vector3 StringUtility::stringToVector3(const string& str, const char* seperate) { Vector3 value; array<string, 3> valueList; if (split(str.c_str(), seperate, valueList) == valueList.size()) { value.x = stringToFloat(valueList[0]); value.y = stringToFloat(valueList[1]); value.z = stringToFloat(valueList[2]); } return value; } string StringUtility::bytesToString(const char* buffer, uint length) { int size = MathUtility::getGreaterPower2(length + 1); char* tempBuffer = ArrayPool::newArray<char>(size); tempBuffer[length] = '\0'; memcpy(tempBuffer, buffer, length); string str(tempBuffer); ArrayPool::deleteArray(tempBuffer); return str; } bool StringUtility::endWith(const string& oriString, const string& pattern, bool sensitive) { if (oriString.length() < pattern.length()) { return false; } string endString = oriString.substr(oriString.length() - pattern.length(), pattern.length()); if (sensitive) { return endString == pattern; } else { return toLower(endString) == toLower(pattern); } } bool StringUtility::startWith(const string& oriString, const string& pattern, bool sensitive) { if (oriString.length() < pattern.length()) { return false; } string startString = oriString.substr(0, pattern.length()); if (sensitive) { return startString == pattern; } else { return toLower(startString) == toLower(pattern); } } string StringUtility::removePreNumber(const string& str) { uint length = (uint)str.length(); FOR_I(length) { if (str[i] < '0' || str[i] > '9') { return str.substr(i); } } return str; } string StringUtility::stringArrayToString(string* strList, uint stringCount, const char* seperate) { string str; FOR_I(stringCount) { str += strList[i]; if (i != stringCount - 1) { str += seperate; } } return str; } #if RUN_PLATFORM == PLATFORM_WINDOWS wstring StringUtility::ANSIToUnicode(const char* str) { if (str == NULL || str[0] == 0) { return L""; } int unicodeLen = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0); int allocSize = MathUtility::getGreaterPower2(unicodeLen + 1); wchar_t* pUnicode = ArrayPool::newArray<wchar_t>(allocSize); MultiByteToWideChar(CP_ACP, 0, str, -1, (LPWSTR)pUnicode, unicodeLen); wstring rt(pUnicode); ArrayPool::deleteArray(pUnicode); return rt; } string StringUtility::UnicodeToANSI(const wchar_t* str) { if (str == NULL || str[0] == 0) { ""; } int iTextLen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL); int allocSize = MathUtility::getGreaterPower2(iTextLen + 1); char* pElementText = ArrayPool::newArray<char>(allocSize); WideCharToMultiByte(CP_ACP, 0, str, -1, pElementText, iTextLen, NULL, NULL); string strText(pElementText); ArrayPool::deleteArray(pElementText); return strText; } string StringUtility::UnicodeToUTF8(const wchar_t* str) { if (str == NULL || str[0] == 0) { return ""; } // wide char to multi char int iTextLen = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); int allocSize = MathUtility::getGreaterPower2(iTextLen + 1); char* pElementText = ArrayPool::newArray<char>(allocSize); WideCharToMultiByte(CP_UTF8, 0, str, -1, pElementText, iTextLen, NULL, NULL); string strText(pElementText); ArrayPool::deleteArray(pElementText); return strText; } wstring StringUtility::UTF8ToUnicode(const char* str) { if (str == NULL || str[0] == 0) { return L""; } int unicodeLen = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0); int allocSize = MathUtility::getGreaterPower2(unicodeLen + 1); wchar_t* pUnicode = ArrayPool::newArray<wchar_t>(allocSize); MultiByteToWideChar(CP_UTF8, 0, str, -1, (LPWSTR)pUnicode, unicodeLen); wstring rt(pUnicode); ArrayPool::deleteArray(pUnicode); return rt; } #elif RUN_PLATFORM == PLATFORM_LINUX wstring StringUtility::ANSIToUnicode(const char* str) { if (str == NULL || str[0] == 0) { return L""; } char* oldname = setlocale(LC_ALL, NULL); try { setlocale(LC_ALL, LC_NAME_zh_CN_GBK); } catch (exception) { ERROR("当前系统不支持GBK编码"); return L""; } int dSize = mbstowcs(NULL, str, 0) + 1; int allocSize = MathUtility::getGreaterPower2(dSize); wchar_t* dBuf = ArrayPool::newArray<wchar_t>(allocSize); mbstowcs(dBuf, str, dSize); setlocale(LC_ALL, oldname); wstring strText(dBuf); ArrayPool::deleteArray(dBuf); return strText; } string StringUtility::UnicodeToANSI(const wchar_t* str) { if (str == NULL || str[0] == 0) { return ""; } char* oldname = setlocale(LC_ALL, NULL); try { setlocale(LC_ALL, LC_NAME_zh_CN_GBK); } catch (exception) { ERROR("当前系统不支持GBK编码"); return EMPTY_STRING; } int dSize = wcstombs(NULL, str, 0) + 1; int allocSize = MathUtility::getGreaterPower2(dSize); char* dBuf = ArrayPool::newArray<char>(allocSize); wcstombs(dBuf, str, dSize); setlocale(LC_ALL, oldname); string strText(dBuf); ArrayPool::deleteArray(dBuf); return strText; } string StringUtility::UnicodeToUTF8(const wchar_t* str) { if (str == NULL || str[0] == 0) { return ""; } char* oldname = setlocale(LC_ALL, NULL); try { setlocale(LC_ALL, LC_NAME_zh_CN_UTF8); } catch (exception) { ERROR("当前系统不支持UTF8编码"); return EMPTY_STRING; } int dSize = wcstombs(NULL, str, 0) + 1; int allocSize = MathUtility::getGreaterPower2(dSize); char* dBuf = ArrayPool::newArray<char>(allocSize); wcstombs(dBuf, str, dSize); setlocale(LC_ALL, oldname); string strText(dBuf); ArrayPool::deleteArray(dBuf); return strText; } wstring StringUtility::UTF8ToUnicode(const char* str) { if (str == NULL || str[0] == 0) { return L""; } char* oldname = setlocale(LC_ALL, NULL); try { setlocale(LC_ALL, LC_NAME_zh_CN_UTF8); } catch (exception) { ERROR("当前系统不支持UTF8编码"); return L""; } int dSize = mbstowcs(NULL, str, 0) + 1; int allocSize = MathUtility::getGreaterPower2(dSize); wchar_t* dBuf = ArrayPool::newArray<wchar_t>(allocSize); mbstowcs(dBuf, str, dSize); setlocale(LC_ALL, oldname); wstring strText(dBuf); ArrayPool::deleteArray(dBuf); return strText; } #endif string StringUtility::ANSIToUTF8(const char* str, bool addBOM) { wstring unicodeStr = ANSIToUnicode(str); string utf8Str = UnicodeToUTF8(unicodeStr.c_str()); if (addBOM) { utf8Str = BOM + utf8Str; } return utf8Str; } string StringUtility::UTF8ToANSI(const char* str, bool eraseBOM) { wstring unicodeStr; if (eraseBOM) { string newStr = str; removeBOM(newStr); unicodeStr = UTF8ToUnicode(newStr.c_str()); } else { unicodeStr = UTF8ToUnicode(str); } return UnicodeToANSI(unicodeStr.c_str()); } void StringUtility::removeBOM(string& str) { if (str.length() >= 3 && str[0] == BOM[0] && str[1] == BOM[1] && str[2] == BOM[2]) { str = str.erase(0, 3); } } void StringUtility::jsonStartArray(string& str, uint preTableCount, bool returnLine) { FOR_I(preTableCount) { str += "\t"; } str += "["; if (returnLine) { str += "\r\n"; } } void StringUtility::jsonEndArray(string& str, uint preTableCount, bool returnLine) { removeLastComma(str); FOR_I(preTableCount) { str += "\t"; } str += "],"; if (returnLine) { str += "\r\n"; } } void StringUtility::jsonStartStruct(string& str, uint preTableCount, bool returnLine) { FOR_I(preTableCount) { str += "\t"; } str += "{"; if (returnLine) { str += "\r\n"; } } void StringUtility::jsonEndStruct(string& str, uint preTableCount, bool returnLine) { removeLastComma(str); FOR_I(preTableCount) { str += "\t"; } str += "},"; if (returnLine) { str += "\r\n"; } } void StringUtility::jsonAddPair(string& str, const string& name, const string& value, uint preTableCount, bool returnLine) { FOR_I(preTableCount) { str += "\t"; } str += "\"" + name + "\": \"" + value + "\","; if (returnLine) { str += "\r\n"; } } void StringUtility::jsonAddObject(string& str, const string& name, const string& value, uint preTableCount, bool returnLine) { FOR_I(preTableCount) { str += "\t"; } str += "\"" + name + "\": " + value + ","; if (returnLine) { str += "\r\n"; } } char StringUtility::toLower(char str) { if (str >= 'A' && str <= 'Z') { return str + 'a' - 'A'; } return str; } char StringUtility::toUpper(char str) { if (str >= 'a' && str <= 'z') { return str - ('a' - 'A'); } return str; } string StringUtility::toLower(const string& str) { string ret = str; uint size = (uint)ret.length(); FOR_I(size) { ret[i] = toLower(ret[i]); } return ret; } string StringUtility::toUpper(const string& str) { string ret = str; uint size = (uint)ret.length(); FOR_I(size) { ret[i] = toUpper(ret[i]); } return ret; } void StringUtility::rightToLeft(string& str) { uint pathLength = (uint)str.length(); FOR_I(pathLength) { if (str[i] == '\\') { str[i] = '/'; } } } void StringUtility::leftToRight(string& str) { uint pathLength = (uint)str.length(); FOR_I(pathLength) { if (str[i] == '/') { str[i] = '\\'; } } } bool StringUtility::findSubstrLower(const string& res, const string& sub, int* pos, uint startIndex, bool direction) { // 全转换为小写 string lowerRes = toLower(res); string lowerSub = toLower(sub); return findSubstr(lowerRes, lowerSub, pos, startIndex, direction); } bool StringUtility::findSubstr(const string& res, const string& sub, int* pos, uint startIndex, bool direction) { int posFind = -1; uint subLen = (uint)sub.length(); int searchLength = (int)res.length() - subLen; if (searchLength < 0) { return false; } if (direction) { for (int i = startIndex; i <= searchLength; ++i) { uint j = 0; for (j = 0; j < subLen; ++j) { if (res[i + j] != sub[j]) { break; } } if (j == subLen) { posFind = i; break; } } } else { for (uint i = searchLength; i >= startIndex; --i) { uint j = 0; for (j = 0; j < subLen; ++j) { if (res[i + j] != sub[j]) { break; } } if (j == subLen) { posFind = i; break; } } } if (pos != NULL) { *pos = posFind; } return posFind != -1; } bool StringUtility::findString(const char* str, const char* key, int* pos, uint startPos) { CLAMP_MIN(startPos, 0); uint length = (uint)strlen(str); uint keyLen = (uint)strlen(key); for (uint i = startPos; i < length; ++i) { bool find = true; FOR_J(keyLen) { if (str[i + j] != key[j]) { find = false; break; } } if (find) { if (pos != NULL) { *pos = i; } return true; } } if (pos != NULL) { *pos = -1; } return false; } string StringUtility::checkString(const string& str, const string& valid) { string newString = ""; uint validCount = (uint)valid.length(); uint oldStrLen = (uint)str.length(); FOR_I(oldStrLen) { bool keep = false; FOR_J(validCount) { if (str[i] == valid[j]) { keep = true; break; } } if (keep) { newString += str[i]; } } return newString; } string StringUtility::checkFloatString(const string& str, const string& valid) { return checkIntString(str, "." + valid); } string StringUtility::checkIntString(const string& str, const string& valid) { return checkString(str, "0123456789" + valid); } string StringUtility::charToHexString(byte value, bool upper) { char byteHex[3]{ 0 }; const char* charPool = upper ? "ABCDEF" : "abcdef"; byte highBit = value >> 4; // 高字节的十六进制 byteHex[0] = (highBit < (byte)10) ? ('0' + highBit) : charPool[highBit - 10]; // 低字节的十六进制 byte lowBit = value & 0x0F; byteHex[1] = (lowBit < (byte)10) ? ('0' + lowBit) : charPool[lowBit - 10]; return byteHex; } string StringUtility::charArrayToHexString(byte* data, uint dataCount, bool addSpace, bool upper) { uint oneLength = addSpace ? 3 : 2; uint showCount = MathUtility::getGreaterPower2(dataCount * oneLength + 1); char* byteData = ArrayPool::newArray<char>(showCount); FOR_J(dataCount) { string byteStr = charToHexString(data[j]); byteData[j * oneLength + 0] = byteStr[0]; byteData[j * oneLength + 1] = byteStr[1]; if (oneLength >= 3) { byteData[j * oneLength + 2] = ' '; } } byteData[dataCount * oneLength] = '\0'; string str(byteData); ArrayPool::deleteArray(byteData); return str; } uint StringUtility::getCharCount(const string& str, char key) { uint count = 0; uint length = (uint)str.length(); FOR_I(length) { if (str[i] == key) { ++count; } } return count; } uint StringUtility::getStringWidth(const string& str) { return (uint)str.length() + getCharCount(str, '\t') * 3; } uint StringUtility::generateAlignTableCount(const string& str, int alignWidth) { int remainChar = alignWidth - getStringWidth(str); MathUtility::clampMin(remainChar, 0); return (uint)ceil(remainChar / 4.0f); } void StringUtility::appendValueString(char* queryStr, uint size, const char* str, bool toUTF8, bool addComma) { if (toUTF8) { if (addComma) { STR_APPEND3_N(queryStr, size, "\"", ANSIToUTF8(str).c_str(), "\","); } else { STR_APPEND3_N(queryStr, size, "\"", ANSIToUTF8(str).c_str(), "\""); } } else { if (addComma) { STR_APPEND3_N(queryStr, size, "\"", str, "\","); } else { STR_APPEND3_N(queryStr, size, "\"", str, "\""); } } } void StringUtility::appendValueInt(char* queryStr, uint size, int value, bool addComma) { array<char, 16> temp; intToString(temp, value); if (addComma) { STR_APPEND2_N(queryStr, size, temp._Elems, ","); } else { STR_APPEND1_N(queryStr, size, temp._Elems); } } void StringUtility::appendValueFloat(char* queryStr, uint size, float value, bool addComma) { array<char, 16> temp; floatToString(temp, value); if (addComma) { STR_APPEND2_N(queryStr, size, temp._Elems, ","); } else { STR_APPEND1_N(queryStr, size, temp._Elems); } } void StringUtility::appendValueLLong(char* queryStr, uint size, const ullong& value, bool addComma) { array<char, 32> temp; ullongToString(temp, value); if (addComma) { STR_APPEND2_N(queryStr, size, temp._Elems, ","); } else { STR_APPEND1_N(queryStr, size, temp._Elems); } } void StringUtility::appendValueByteArray(char* queryStr, uint size, byte* ushortArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); byteArrayToString(charArray, arrayLen, ushortArray, count); appendValueString(queryStr, size, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendValueUShortArray(char* queryStr, uint size, ushort* ushortArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); ushortArrayToString(charArray, arrayLen, ushortArray, count); appendValueString(queryStr, size, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendValueIntArray(char* queryStr, uint size, int* intArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); intArrayToString(charArray, arrayLen, intArray, count); appendValueString(queryStr, size, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendValueFloatArray(char* queryStr, uint size, float* floatArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); floatArrayToString(charArray, arrayLen, floatArray, count); appendValueString(queryStr, size, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendValueULLongArray(char* queryStr, uint size, ullong* longArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); ullongArrayToString(charArray, arrayLen, longArray, count); appendValueString(queryStr, size, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendValueVector2Int(char* queryStr, uint size, const Vector2Int& value, bool addComma) { array<char, 32> temp; vector2IntToString(temp, value); appendValueString(queryStr, size, temp._Elems, false, addComma); } void StringUtility::appendValueVector2UShort(char* queryStr, uint size, const Vector2UShort& value, bool addComma) { array<char, 16> temp; vector2UShortToString(temp, value); appendValueString(queryStr, size, temp._Elems, false, addComma); } void StringUtility::appendConditionString(char* condition, uint size, const char* col, const char* str, bool toUTF8, const char* operate) { if (toUTF8) { if (operate == NULL) { STR_APPEND5_N(condition, size, col, " = ", "\"", ANSIToUTF8(str).c_str(), "\""); } else { STR_APPEND6_N(condition, size, col, " = ", "\"", ANSIToUTF8(str).c_str(), "\"", operate); } } else { if (operate == NULL) { STR_APPEND5_N(condition, size, col, " = ", "\"", str, "\""); } else { STR_APPEND6_N(condition, size, col, " = ", "\"", str, "\"", operate); } } } void StringUtility::appendConditionInt(char* condition, uint size, const char* col, int value, const char* operate) { array<char, 16> temp; intToString(temp, value); if (operate == NULL) { STR_APPEND3_N(condition, size, col, " = ", temp._Elems); } else { STR_APPEND4_N(condition, size, col, " = ", temp._Elems, operate); } } void StringUtility::appendConditionFloat(char* condition, uint size, const char* col, float value, const char* operate) { array<char, 16> temp; floatToString(temp, value); if (operate == NULL) { STR_APPEND3_N(condition, size, col, " = ", temp._Elems); } else { STR_APPEND4_N(condition, size, col, " = ", temp._Elems, operate); } } void StringUtility::appendConditionULLong(char* condition, uint size, const char* col, const ullong& value, const char* operate) { array<char, 32> temp; ullongToString(temp, value); if (operate == NULL) { STR_APPEND3_N(condition, size, col, " = ", temp._Elems); } else { STR_APPEND4_N(condition, size, col, " = ", temp._Elems, operate); } } void StringUtility::appendUpdateString(char* updateInfo, uint size, const char* col, const char* str, bool toUTF8, bool addComma) { if (toUTF8) { if (addComma) { STR_APPEND5_N(updateInfo, size, col, " = ", "\"", ANSIToUTF8(str).c_str(), "\","); } else { STR_APPEND5_N(updateInfo, size, col, " = ", "\"", ANSIToUTF8(str).c_str(), "\""); } } else { if (addComma) { STR_APPEND5_N(updateInfo, size, col, " = ", "\"", str, "\","); } else { STR_APPEND5_N(updateInfo, size, col, " = ", "\"", str, "\""); } } } void StringUtility::appendUpdateInt(char* updateInfo, uint size, const char* col, int value, bool addComma) { array<char, 16> temp; intToString(temp, value); if (addComma) { STR_APPEND4_N(updateInfo, size, col, " = ", temp._Elems, ","); } else { STR_APPEND3_N(updateInfo, size, col, " = ", temp._Elems); } } void StringUtility::appendUpdateFloat(char* updateInfo, uint size, const char* col, float value, bool addComma) { array<char, 16> temp; floatToString(temp, value); if (addComma) { STR_APPEND4_N(updateInfo, size, col, " = ", temp._Elems, ","); } else { STR_APPEND3_N(updateInfo, size, col, " = ", temp._Elems); } } void StringUtility::appendUpdateULLong(char* updateInfo, uint size, const char* col, const ullong& value, bool addComma) { array<char, 32> temp; ullongToString(temp, value); if (addComma) { STR_APPEND4_N(updateInfo, size, col, " = ", temp._Elems, ","); } else { STR_APPEND3_N(updateInfo, size, col, " = ", temp._Elems); } } void StringUtility::appendUpdateByteArray(char* updateInfo, uint size, const char* col, byte* ushortArray, uint count, bool addComma) { int arrayLen = 4 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); byteArrayToString(charArray, arrayLen, ushortArray, count); appendUpdateString(updateInfo, size, col, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendUpdateUShortArray(char* updateInfo, uint size, const char* col, ushort* ushortArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); ushortArrayToString(charArray, arrayLen, ushortArray, count); appendUpdateString(updateInfo, size, col, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendUpdateIntArray(char* updateInfo, uint size, const char* col, int* intArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); intArrayToString(charArray, arrayLen, intArray, count); appendUpdateString(updateInfo, size, col, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendUpdateFloatArray(char* updateInfo, uint size, const char* col, float* floatArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); floatArrayToString(charArray, arrayLen, floatArray, count); appendUpdateString(updateInfo, size, col, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendUpdateULLongArray(char* updateInfo, uint size, const char* col, ullong* longArray, uint count, bool addComma) { int arrayLen = 16 * MathUtility::getGreaterPower2(count); char* charArray = ArrayPool::newArray<char>(arrayLen); ullongArrayToString(charArray, arrayLen, longArray, count); appendUpdateString(updateInfo, size, col, charArray, false, addComma); ArrayPool::deleteArray(charArray); } void StringUtility::appendUpdateVector2Int(char* updateInfo, uint size, const char* col, const Vector2Int& value, bool addComma) { array<char, 32> temp; vector2IntToString(temp, value); appendUpdateString(updateInfo, size, col, temp._Elems, false, addComma); } void StringUtility::appendUpdateVector2UShort(char* updateInfo, uint size, const char* col, const Vector2UShort& value, bool addComma) { array<char, 16> temp; vector2UShortToString(temp, value); appendUpdateString(updateInfo, size, col, temp._Elems, false, addComma); }
true
415c94c39a5d026e72948643c233de155a43f946
C++
andrew-suh/Freefall_Engine
/the_engine/the_engine/src/window/text.cpp
UTF-8
6,260
2.578125
3
[]
no_license
#include <iostream> #include <sstream> #include <fstream> #include <glm/gtc/matrix_transform.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include "text.h" std::map<std::string, Shader> Shaders; Shader loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile) { // 1. Retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; try { // Open files std::ifstream vertexShaderFile(vShaderFile); std::ifstream fragmentShaderFile(fShaderFile); std::stringstream vShaderStream, fShaderStream; // Read file's buffer contents into streams vShaderStream << vertexShaderFile.rdbuf(); fShaderStream << fragmentShaderFile.rdbuf(); // close file handlers vertexShaderFile.close(); fragmentShaderFile.close(); // Convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // If geometry shader path is present, also load a geometry shader if (gShaderFile != nullptr) { std::ifstream geometryShaderFile(gShaderFile); std::stringstream gShaderStream; gShaderStream << geometryShaderFile.rdbuf(); geometryShaderFile.close(); geometryCode = gShaderStream.str(); } } catch (std::exception e) { std::cout << "ERROR::SHADER: Failed to read shader files" << std::endl; } const GLchar *vShaderCode = vertexCode.c_str(); const GLchar *fShaderCode = fragmentCode.c_str(); const GLchar *gShaderCode = geometryCode.c_str(); // 2. Now create shader object from source code Shader shader; shader.Compile(vShaderCode, fShaderCode, gShaderFile != nullptr ? gShaderCode : nullptr); return shader; } Shader LoadShader(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile, std::string name) { Shaders[name] = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile); return Shaders[name]; } TextRenderer::TextRenderer(GLuint width, GLuint height) { // Load and configure shader this->TextShader = LoadShader("src/window/shader/text.vs", "src/window/shader/text.frag", nullptr, "text"); this->TextShader.SetMatrix4("projection", glm::ortho(0.0f, static_cast<GLfloat>(width), static_cast<GLfloat>(height), 0.0f), GL_TRUE); this->TextShader.SetInteger("text", 0); // Configure VAO/VBO for texture quads glGenVertexArrays(1, &this->VAO); glGenBuffers(1, &this->VBO); glBindVertexArray(this->VAO); glBindBuffer(GL_ARRAY_BUFFER, this->VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void TextRenderer::Load(std::string font, GLuint fontSize) { // First clear the previously loaded Characters this->Characters.clear(); // Then initialize and load the FreeType library FT_Library ft; if (FT_Init_FreeType(&ft)) // All functions return a value different than 0 whenever an error occurred std::cout << "ERROR::FREETYPE: Could not init FreeType Library" << std::endl; // Load font as face FT_Face face; if (FT_New_Face(ft, font.c_str(), 0, &face)) std::cout << "ERROR::FREETYPE: Failed to load font" << std::endl; // Set size to load glyphs as FT_Set_Pixel_Sizes(face, 0, fontSize); // Disable byte-alignment restriction glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Then for the first 128 ASCII characters, pre-load/compile their characters and store them for (GLubyte c = 0; c < 128; c++) // lol see what I did there { // Load character glyph if (FT_Load_Char(face, c, FT_LOAD_RENDER)) { std::cout << "ERROR::FREETYTPE: Failed to load Glyph" << std::endl; continue; } // Generate texture GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width, face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, face->glyph->bitmap.buffer ); // Set texture options glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Now store character for later use Character character = { texture, glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows), glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top), face->glyph->advance.x }; Characters.insert(std::pair<GLchar, Character>(c, character)); } glBindTexture(GL_TEXTURE_2D, 0); // Destroy FreeType once we're finished FT_Done_Face(face); FT_Done_FreeType(ft); } void TextRenderer::RenderText(std::string text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color) { // Activate corresponding render state this->TextShader.Use(); this->TextShader.SetVector3f("textColor", color); glActiveTexture(GL_TEXTURE0); glBindVertexArray(this->VAO); // Iterate through all characters std::string::const_iterator c; for (c = text.begin(); c != text.end(); c++) { Character ch = Characters[*c]; GLfloat xpos = x + ch.Bearing.x * scale; GLfloat ypos = y + (this->Characters['H'].Bearing.y - ch.Bearing.y) * scale; GLfloat w = ch.Size.x * scale; GLfloat h = ch.Size.y * scale; // Update VBO for each character GLfloat vertices[6][4] = { { xpos, ypos + h, 0.0, 1.0 }, { xpos + w, ypos, 1.0, 0.0 }, { xpos, ypos, 0.0, 0.0 }, { xpos, ypos + h, 0.0, 1.0 }, { xpos + w, ypos + h, 1.0, 1.0 }, { xpos + w, ypos, 1.0, 0.0 } }; // Render glyph texture over quad glBindTexture(GL_TEXTURE_2D, ch.TextureID); // Update content of VBO memory glBindBuffer(GL_ARRAY_BUFFER, this->VBO); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices); // Be sure to use glBufferSubData and not glBufferData glBindBuffer(GL_ARRAY_BUFFER, 0); // Render quad glDrawArrays(GL_TRIANGLES, 0, 6); // Now advance cursors for next glyph x += (ch.Advance >> 6) * scale; // Bitshift by 6 to get value in pixels (1/64th times 2^6 = 64) } glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); }
true
3e57ece18c98aefbfb62132bba40e2c970520d5c
C++
thegamer1907/Code_Analysis
/CodesNew/909.cpp
UTF-8
421
2.703125
3
[]
no_license
#include<iostream> #include<cstring> #include <set> #include <cmath> #include <vector> using namespace std; set <string> c; main() { int a,b; cin >>a >>b; string s; for(int i=0;i<a+b;i++){ cin >>s; c.insert(s);} int x=0; x=a+b-c.size(); if(x%2==0) { if(a>b) cout <<"YES"; else cout <<"NO"; } if(x%2==1) { if(a+1>b) cout <<"YES"; else cout <<"NO"; } }
true
7e25864b96c3479faac231bd1c132388a2df5e41
C++
Lemutar/cucumber-cpp
/src/main.cpp
UTF-8
1,516
2.734375
3
[ "MIT" ]
permissive
#include <cucumber-cpp/internal/CukeEngineImpl.hpp> #include <cucumber-cpp/internal/connectors/wire/WireServer.hpp> #include <cucumber-cpp/internal/connectors/wire/WireProtocol.hpp> #include <iostream> #include <boost/program_options.hpp> using boost::program_options::value; namespace { void acceptWireProtocol(int port) { using namespace ::cucumber::internal; CukeEngineImpl cukeEngine; JsonSpiritWireMessageCodec wireCodec; WireProtocolHandler protocolHandler(&wireCodec, &cukeEngine); SocketServer server(&protocolHandler); server.listen(port); server.acceptOnce(); } } int main(int argc, char **argv) { boost::program_options::options_description optionDescription("Allowed options"); optionDescription.add_options() ("help", "help for cucumber-cpp") ("port", value<int>(), "listening port of wireserver") ; boost::program_options::variables_map optionVariableMap; boost::program_options::store( boost::program_options::parse_command_line(argc, argv, optionDescription), optionVariableMap); boost::program_options::notify(optionVariableMap); if (optionVariableMap.count("help")) { std::cout << optionDescription << std::endl; } int port = 3902; if (optionVariableMap.count("port")) { port = optionVariableMap["port"].as<int>(); } try { acceptWireProtocol(port); } catch (std::exception &e) { std::cerr << e.what() << std::endl; exit(1); } return 0; }
true
f927913df4da713148df40644ecca0a13a05356d
C++
kxjjuneau/KnightGame
/Rabbit.cpp
UTF-8
4,663
3.15625
3
[]
no_license
///////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: project 2: Rabbit game // Filename: rabbit.cpp // Description: function definitions for the rabbit class // Author: Joseph Juneau (juneau@etsu.edu) // Created: Thursday, 2/1/2020 // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "Rabbit.h" #include "Log.h" #include <iostream> #include <string> #include <time.h> #include <fstream> using namespace std; using namespace os_logging; //default constructor Rabbit::Rabbit() { hp = 0; attackRate = 0; biteChance = 0; quickChance = 0; throatChance = 0; weakDamage = 0; strongDamage = 0; evasionChance = 0; initialized = false; } //constructor with a given filename and game log Rabbit::Rabbit(string FileName, Log& gameLog ) { initialized = false; //set the rabbit to unitialized ifstream RabbitFile; //create file string LineOfRabbitFile; //holds the given line from the rabbit file RabbitFile.open(FileName.c_str()); if (RabbitFile.fail() || !RabbitFile.good()) { cout << "Required Rabbit text input file " << FileName << " does not exist " << endl; return; } //checks the file that it is correctly formated and that fill in the uninitialized variables getline(RabbitFile, LineOfRabbitFile); hp = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (hp < 25 || hp > 100) { gameLog.writeLogRecord("hp is not within bounds"); return; } getline(RabbitFile, LineOfRabbitFile); attackRate = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (attackRate < 3 || attackRate > 10) { gameLog.writeLogRecord("attack rate is not within bounds"); return; } getline(RabbitFile, LineOfRabbitFile); biteChance = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (biteChance < 60 || biteChance > 75) { gameLog.writeLogRecord("bitechance is not within bounds"); return; } getline(RabbitFile, LineOfRabbitFile); quickChance = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (quickChance < 10 || quickChance > 20) { gameLog.writeLogRecord("quickchance is not within bounds"); return; } getline(RabbitFile, LineOfRabbitFile); throatChance = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (throatChance < 5 || throatChance > 20) { gameLog.writeLogRecord("throatchance is not within bounds"); return; } else if ((throatChance + quickChance + biteChance) != 100) { gameLog.writeLogRecord("percentages do not add to 100"); return; } getline(RabbitFile, LineOfRabbitFile); weakDamage = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (weakDamage < 1 || weakDamage > 9) { gameLog.writeLogRecord("weakDamage is out of bounds"); return; } getline(RabbitFile, LineOfRabbitFile); strongDamage = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (strongDamage < 30 || strongDamage > 40) { gameLog.writeLogRecord("strongdamage is out of bounds"); return; } getline(RabbitFile, LineOfRabbitFile); evasionChance = atoi(LineOfRabbitFile.substr(LineOfRabbitFile.find(":") + 1).c_str()); if (evasionChance < 5 || evasionChance > 95) { gameLog.writeLogRecord("evasion chance is out of bounds"); return; } initialized = true; return; } void Rabbit::sethp(int hpOfRabbit) { hp = hpOfRabbit; } void Rabbit::setattackRate(int attackRateOfRabbit) { attackRate = attackRateOfRabbit; } void Rabbit::setbiteChance(int biteChanceOfRabbit) { biteChance = biteChanceOfRabbit; } void Rabbit::setquickChance(int quickChanceOfRabbit) { quickChance = quickChanceOfRabbit; } void Rabbit::setThroatChance(int throatChanceOfRabbit) { throatChance = throatChanceOfRabbit; } void Rabbit::setWeakDamage(int weakDamageOfRabbit) { weakDamage = weakDamageOfRabbit; } void Rabbit::setStrongDamage(int strongDamageOfRabbit) { strongDamage = strongDamageOfRabbit; } void Rabbit::setEvasionChance(int evasionOfRabbit) { evasionChance = evasionOfRabbit; } void Rabbit::setInitialized(bool init) { initialized = init; } int Rabbit::gethp() { return hp; } int Rabbit::getAttackRate() { return attackRate; } int Rabbit::getBiteChance() { return biteChance; } int Rabbit::getQuickChance() { return quickChance; } int Rabbit::getThroatChance() { return throatChance; } int Rabbit::getWeakDamage() { return weakDamage; } int Rabbit::getStrongDamage() { return strongDamage; } int Rabbit::getEvasionChance() { return evasionChance; } bool Rabbit::getInitialized() { return initialized; }
true
430f6957b7d0c1f2bb7bf20f49982149c195ada6
C++
acoustictime/CollegeCode
/Cal State San Bernardino (CSUSB)/CSE202 - Computer Science 2/lab10/Mlist.cpp
UTF-8
960
3.71875
4
[]
no_license
#include <iostream> #include "Mlist.h" #include <vector> template<class T> //creates the list with a firstinline entry Mlist<T>::Mlist(T firstinline) { mlist.push_back(firstinline); } template<class T>//returns the front of the list and moves every entry up one position; T Mlist<T>::next() { T x; if (mlist.size() > 0) { x= mlist[0]; for (int i=0; i<mlist.size()-1; i++) { mlist[i]=mlist[i+1]; } mlist.pop_back(); } return x; } template<class T> //searches the list and removes the entry with value n void Mlist<T>::remove(T n) { if(mlist.size() > 0) { for(int i =0;i < mlist.size()-1;i++) { if(mlist[i] == n) { for(int j = i;j < mlist.size()-1;j++) { mlist[j] = mlist[j+1]; } mlist.pop_back(); } } } }
true
8171f4fc4d21ccda40fe9d23f8f9ecf7589cedd2
C++
ZhdanovichTimofey/sem2
/3/H.cpp
UTF-8
295
2.859375
3
[]
no_license
Cat* get_home_for_a_cats_pride(unsigned int n){ Cat* r = new Cat[n]; for (unsigned int i = 0; i < n; i++) r[i].name = new char[10]; return r; } void clear_home_of_a_cats_pride(Cat *cats, unsigned int n){ for (unsigned int i = 0; i < n; i++) delete[] cats[i].name; delete[] cats; }
true
131183f53175b2a68343a4ff0cced773f6e307cf
C++
jin1xiao3long2/CompilerLearning
/Experience/Tiny/Tiny_Nodes.cpp
UTF-8
4,898
2.796875
3
[ "Apache-2.0" ]
permissive
#include <Tiny_Nodes.hpp> namespace tn { void build_tree_version(int l, const std::string &info, std::deque<std::string> &Messages) { std::string mes = ""; for (int i = 0; i < l; i++) mes.append(" "); mes.append(info); Messages.push_back(mes); } node_base *node_Program::Eval(int i, std::deque<std::string> &Messages) { if (Stmt_sequence) { Stmt_sequence->Eval(i, Messages); } return nullptr; } node_base *node_Stmt_sequence::Eval(int i, std::deque<std::string> &Messages) { if(Stmt_1) Stmt_1->Eval(i, Messages); if(Stmt_2) Stmt_2->Eval(i, Messages); return nullptr; } node_base *node_Statement::Eval(int i, std::deque<std::string> &Messages) { if (If_stmt) { If_stmt->Eval(i, Messages); return nullptr; } else if (Repeat_stmt) { Repeat_stmt->Eval(i, Messages); return nullptr; } else if (Assign_stmt) { Assign_stmt->Eval(i, Messages); return nullptr; } else if (Read_stmt) { Read_stmt->Eval(i, Messages); return nullptr; } else if (Write_stmt) { Write_stmt->Eval(i, Messages); return nullptr; } return nullptr; } node_base *node_If_stmt::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; build_tree_version(i, std::string("If"), Messages); Exp->Eval(j, Messages); Stmt_sequence_1->Eval(j, Messages); if (Else) { Stmt_sequence_2->Eval(j, Messages); } return nullptr; } node_base *node_Repeat_stmt::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; build_tree_version(i, std::string("Repeat"), Messages);; Stmt_sequence->Eval(j, Messages); Exp->Eval(j, Messages); return nullptr; } node_base *node_Assign_stmt::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; build_tree_version(i, std::string("Assign to: " + Identifier->get_string()), Messages); Exp->Eval(j, Messages); return nullptr; } node_base *node_Read_stmt::Eval(int i, std::deque<std::string> &Messages) { build_tree_version(i, std::string("Read: " + Identifier->get_string()), Messages); return nullptr; } node_base *node_Write_stmt::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; build_tree_version(i, std::string("Write"), Messages); Exp->Eval(j, Messages); return nullptr; } node_base *node_Exp::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; if (Comparison_op) { Comparison_op->Eval(i, Messages); Simple_exp_1->Eval(j, Messages); Simple_exp_2->Eval(j, Messages); } else { Simple_exp_1->Eval(i, Messages); } return nullptr; } node_base *node_Comparison_op::Eval(int i, std::deque<std::string> &Messages) { build_tree_version(i, std::string("Op: " + Comparison_op->get_string()), Messages); return nullptr; } node_base *node_Simple_exp::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; if (AddOp) { AddOp->Eval(i, Messages); Term_1->Eval(j, Messages); Term_2->Eval(j, Messages); } else { Term_1->Eval(i, Messages); } return nullptr; } node_base *node_AddOp::Eval(int i, std::deque<std::string> &Messages) { build_tree_version(i, std::string("Op: " + AddOp->get_string()), Messages); return nullptr; } node_base *node_Term::Eval(int i, std::deque<std::string> &Messages) { int j = i + 1; if (MulOp) { MulOp->Eval(i, Messages); if(Factor_1) Factor_1->Eval(j, Messages); if(Factor_2) Factor_2->Eval(j, Messages); } else { if(Factor_1) Factor_1->Eval(i, Messages); } return nullptr; } node_base *node_MulOp::Eval(int i, std::deque<std::string> &Messages) { build_tree_version(i, std::string("Op: " + MulOp->get_string()), Messages); return nullptr; } node_base *node_Factor::Eval(int i, std::deque<std::string> &Messages) { if (Left_B) { Exp->Eval(i, Messages); return nullptr; } else if (Number) { build_tree_version(i, std::string("Const: " + Number->get_string()), Messages); return nullptr; } else if (Identifier) { build_tree_version(i, std::string("Id: " + Identifier->get_string()), Messages); return nullptr; } return nullptr; } }
true
abb7c07d5ad8a41b358793cbdf4b7f6481802ed5
C++
facebook/redex
/sparta/include/sparta/HashedSetAbstractDomain.h
UTF-8
5,611
2.703125
3
[ "MIT" ]
permissive
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <cstddef> #include <initializer_list> #include <memory> #include <unordered_set> #include <sparta/PowersetAbstractDomain.h> namespace sparta { // Forward declaration. template <typename Element, typename Hash, typename Equal> class HashedSetAbstractDomain; namespace hsad_impl { /* * An abstract value from a powerset is implemented as a hash table. */ template <typename Element, typename Hash, typename Equal> class SetValue final : public PowersetImplementation< Element, const std::unordered_set<Element, Hash, Equal>&, SetValue<Element, Hash, Equal>> { public: using SetImplType = std::unordered_set<Element, Hash, Equal>; SetValue() = default; SetValue(Element e) { add(std::move(e)); } SetValue(std::initializer_list<Element> l) { if (l.begin() != l.end()) { m_set = std::make_unique<SetImplType>(l.begin(), l.end()); } } SetValue(const SetValue& other) { if (other.m_set) { m_set = std::make_unique<SetImplType>(*other.m_set); } } SetValue(SetValue&& other) noexcept = default; SetValue& operator=(const SetValue& other) { if (other.m_set) { m_set = std::make_unique<SetImplType>(*other.m_set); } return *this; } SetValue& operator=(SetValue&& other) noexcept = default; const SetImplType& elements() const { if (m_set) { return *m_set; } else { return s_empty_set; } } size_t size() const { return m_set ? m_set->size() : 0; } bool contains(const Element& e) const { return m_set && m_set->count(e) > 0; } void add(const Element& e) { set().emplace(e); } void add(Element&& e) { set().emplace(std::move(e)); } void remove(const Element& e) { if (m_set) { if (m_set->erase(e) && m_set->empty()) { m_set = nullptr; } } } void clear() { m_set = nullptr; } AbstractValueKind kind() const { return AbstractValueKind::Value; } bool leq(const SetValue& other) const { if (size() > other.size()) { return false; } if (m_set) { for (const Element& e : *m_set) { if (other.contains(e) == 0) { return false; } } } return true; } bool equals(const SetValue& other) const { return (size() == other.size()) && leq(other); } AbstractValueKind join_with(const SetValue& other) { if (other.m_set) { auto& this_set = set(); for (const Element& e : *other.m_set) { this_set.insert(e); } } return AbstractValueKind::Value; } AbstractValueKind meet_with(const SetValue& other) { if (m_set) { for (auto it = m_set->begin(); it != m_set->end();) { if (other.contains(*it) == 0) { it = m_set->erase(it); } else { ++it; } } } return AbstractValueKind::Value; } AbstractValueKind difference_with(const SetValue& other) { if (m_set) { for (auto it = m_set->begin(); it != m_set->end();) { if (other.contains(*it) != 0) { it = m_set->erase(it); } else { ++it; } } } return AbstractValueKind::Value; } friend std::ostream& operator<<(std::ostream& o, const SetValue& value) { o << "[#" << value.size() << "]"; const auto& elements = value.elements(); o << "{"; for (auto it = elements.begin(); it != elements.end();) { o << *it++; if (it != elements.end()) { o << ", "; } } o << "}"; return o; } private: static inline const SetImplType s_empty_set{}; std::unique_ptr<SetImplType> m_set; SetImplType& set() { if (!m_set) { m_set = std::make_unique<SetImplType>(); } return *m_set; } template <typename T1, typename T2, typename T3> friend class sparta::HashedSetAbstractDomain; }; } // namespace hsad_impl /* * An implementation of powerset abstract domains using hash tables. */ template <typename Element, typename Hash = std::hash<Element>, typename Equal = std::equal_to<Element>> class HashedSetAbstractDomain final : public PowersetAbstractDomain< Element, hsad_impl::SetValue<Element, Hash, Equal>, const std::unordered_set<Element, Hash, Equal>&, HashedSetAbstractDomain<Element, Hash, Equal>> { public: using Value = hsad_impl::SetValue<Element, Hash, Equal>; HashedSetAbstractDomain() : PowersetAbstractDomain<Element, Value, const std::unordered_set<Element, Hash, Equal>&, HashedSetAbstractDomain>() {} HashedSetAbstractDomain(AbstractValueKind kind) : PowersetAbstractDomain<Element, Value, const std::unordered_set<Element, Hash, Equal>&, HashedSetAbstractDomain>(kind) {} explicit HashedSetAbstractDomain(Element e) { this->set_to_value(Value(std::move(e))); } explicit HashedSetAbstractDomain(std::initializer_list<Element> l) { this->set_to_value(Value(l)); } static HashedSetAbstractDomain bottom() { return HashedSetAbstractDomain(AbstractValueKind::Bottom); } static HashedSetAbstractDomain top() { return HashedSetAbstractDomain(AbstractValueKind::Top); } }; } // namespace sparta
true
226cd1d34b178121eeda2c8ed502f76813137947
C++
dipprog/Data-Structure
/Queue/linkedListImplementation.cpp
UTF-8
1,782
4.40625
4
[]
no_license
/*Queue - Linked List implementation*/ #include <iostream> using namespace std; struct Node { int data; Node *next; }; // Two glboal variables to store address of front and rear nodes. Node *front = NULL; Node *rear = NULL; class Queue { public: // To Enqueue an integer void Enqueue(int x) { Node *newNode = new Node(); newNode->data = x; newNode->next = NULL; if (front == NULL && rear == NULL) { front = rear = newNode; return; } rear->next = newNode; rear = newNode; } // To Dequeue an integer. void Dequeue() { Node *temp = front; if (front == NULL) { cout << "Queue is empty" << endl; return; } if (front == rear) front = rear = NULL; else front = front->next; delete temp; } // Returning front element of the Queue int Front() { if (front == NULL) { cout << "Queue is empty" << endl; return -1; } return front->data; } // Printing element of the Queue void Print() { Node *temp = front; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << "\n"; } }; /* Drive code to test the implementation. */ // Printing elements in Queue after each Enqueue or Dequeue int main() { Queue Q; Q.Enqueue(2); Q.Print(); Q.Enqueue(8); Q.Print(); Q.Enqueue(6); Q.Print(); Q.Enqueue(4); Q.Print(); Q.Enqueue(10); Q.Print(); Q.Dequeue(); Q.Print(); int fron = Q.Front(); cout << "Front of the Queue: " << fron << endl; }
true
4694cfd15ec06a91d8b94da90399d1bd4cf76a4d
C++
RaduAlbastroiu/AdventOfCode
/2018/Day6.cpp
UTF-8
1,804
2.75
3
[]
no_license
// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> #include <fstream> #include <cstdio> #include <algorithm> #include <string> #include <cmath> #include <vector> #include <string> #include <deque> #include <set> #include <unordered_set> #include <unordered_map> #include <cstdint> using namespace std; ifstream fin("date.txt"); ofstream fout("date.out"); int viz[1000001]; vector<pair<int, int>> all; int main() { int x, y; while (true) { fin >> x >> y; all.push_back(make_pair(x, y)); if (fin.eof()) break; } for (int i = 0; i < 1000; ++i) { for (int j = 0; j < 1000; ++j) { int MIN = 99999, nrMIN = 0, pozMIN; int k = 0; for (auto point : all) { if (abs(i - point.first) + abs(j - point.second) == MIN) { nrMIN++; } if (abs(i - point.first) + abs(j - point.second) < MIN) { MIN = abs(i - point.first) + abs(j - point.second); nrMIN = 1; pozMIN = k; } k++; } if (nrMIN == 1) { if (i == 0 || j == 0 || i == 999 || j == 999) viz[pozMIN] += 100000; viz[pozMIN]++; } } } int MAX = 0; for (int i = 0; i < 51; ++i) { if (viz[i] > MAX && viz[i] < 100000) { MAX = viz[i]; } } fout << "part1: " << MAX << endl; int count = 0; for (int i = 0; i < 1000; ++i) { for (int j = 0; j < 1000; ++j) { int dist = 0; for (auto point : all) { dist += abs(point.first - i) + abs(point.second - j); } if (dist < 10000) { count++; } } } fout << "part2: " << count << endl; return 0; }
true
7e46d57ef52c7d76e914c4e190879c0de5644790
C++
AbuHorairaTarif/UvaProject
/UVA/10005.cpp
UTF-8
1,985
3
3
[]
no_license
#include <stdio.h> #include <math.h> #include <algorithm> using namespace std; const int maxn=105; const double eps=1e-6; struct Point { double x,y; }p[maxn]; struct Line{Point a,b;}; int dbcmp(double n) { return n<-eps?-1:n>eps; } double dis(Point a,Point b) { return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } Point intersection(Line u,Line v) { Point ret=u.a; double t=((u.a.x-v.a.x)*(v.b.y-v.a.y)-(u.a.y-v.a.y)*(v.b.x-v.a.x))/((u.a.x-u.b.x)*(v.b.y-v.a.y)-(u.a.y-u.b.y)*(v.b.x-v.a.x)); ret.x+=(u.b.x-u.a.x)*t; ret.y+=(u.b.y-u.a.y)*t; return ret; } Point center(Point a,Point b,Point c) { Line u,v; u.a.x=(a.x+b.x)/2; u.a.y=(a.y+b.y)/2; u.b.x=u.a.x+(u.a.y-a.y); u.b.y=u.a.y-(u.a.x-a.x); v.a.x=(a.x+c.x)/2; v.a.y=(a.y+c.y)/2; v.b.x=v.a.x+(v.a.y-a.y); v.b.y=v.a.y-(v.a.x-a.x); return intersection(u,v); } void min_cir(Point *p,int n,Point &cir,double &r) { random_shuffle(p,p+n); cir=p[0]; r=0; for(int i=1;i<n;++i) { if(dbcmp(dis(p[i],cir)-r)<=0) continue; cir=p[i]; r=0; for(int j=0;j<i;++j) { if(dbcmp(dis(p[j],cir)-r)<=0) continue; cir.x=(p[i].x+p[j].x)/2; cir.y=(p[i].y+p[j].y)/2; r=dis(cir,p[j]); for(int k=0;k<j;++k) { if(dbcmp(dis(p[k],cir)-r)<=0) continue; cir=center(p[i],p[j],p[k]); r=dis(cir,p[k]); } } } } int main() { Point cir; double len,r; int n,i,j; while(scanf("%d",&n)!=EOF) { if(n==0) break; for(i=0;i<n;i++) scanf("%lf%lf",&p[i].x,&p[i].y); scanf("%lf",&len); min_cir(p,n,cir,r); if(len>r-eps) printf("The polygon can be packed in the circle.\n"); else printf("There is no way of packing that polygon.\n"); } return 0; }
true
47fb80b3dde5bc8eb84f4978450574c681dd86e6
C++
UNMECE231Sp2020/homework-2-jrhoades
/con_fun.cpp
UTF-8
2,992
3.3125
3
[]
no_license
//con_fun.cpp #include <iostream> #include "declarations.h" #include<cmath> Complex::Complex() { _real = 0; _imag = 0; } Complex::Complex(double real,double imag) { _real = real; _imag = imag; } Complex::Complex(double real) { _real = real; _imag = 0; } void Complex::print() { if(_imag>=0) std::cout<<_real<<'+'<<_imag<<'j'<<std::endl; else std::cout<<_real<<'-'<<_imag*-1<<'j'<<std::endl; } Complex::Complex(const Complex &Value) { _real = Value._real; _imag = Value._imag; } double Complex::real() { return _real; } double Complex::imag() { return _imag; } //void Complex::print() { // std::cout<< " "<<_real<< " " <<_imag<< std::endl; //} Complex Complex::add(Complex a) { Complex value_add; value_add._real = (_real)+(a._real); value_add._imag = (_imag)+(a._imag); return value_add; } Complex Complex::sub(Complex b) { Complex value_sub; value_sub._real = (_real)-(b._real); value_sub._imag = (_imag)-(b._imag); return value_sub; } Complex Complex::mult(Complex c) { Complex value_mult; value_mult._real = (_real * c._real)-(_imag * c._imag); value_mult._imag = (_real * c._imag)+(_imag * c._real); return value_mult; } Complex Complex::div(Complex d) { Complex value_div; double denom = ((pow(d._real,2))+(pow(d._imag,2))); if (denom == 0) { std::cout << "You know what a chazzer is? It's a pig that can't divide by zero, and neither can you." << std::endl; value_div._real = 0; value_div._imag = 0; return value_div; } value_div._real = ((_real)*(d._real)+(_imag)*(d._imag))/(denom); value_div._imag = ((_imag)*(d._real)-(_real)*(d._imag))/(denom); return value_div; } Complex Complex::conjugate() { Complex value_conj; value_conj._real = _real; value_conj._imag = (_imag)/(-1); return value_conj; } double Complex::magnitude() { double mag; mag = sqrt(pow(_real,2)+pow(_imag,2)); return mag; } double Complex::phase() { double ph = atan(_imag/_real); ph = ph * (180/M_PI); return (ph<0) ? -ph : ph; } Complex Complex::operator+ (Complex v) { Complex temp = add(v); //temp._real = _real + value._real; //temp._imag = _imag + value._imag; return temp; } Complex Complex::operator- (Complex v) { Complex temp = sub(v); //temp._real = _real - value._real; //temp._imag = _imag - value._imag; return temp; } Complex Complex::operator* (Complex v) { Complex temp = mult(v); //temp._real = _real * value._real; //temp._imag = _imag * value._imag; return temp; } Complex Complex::operator/ (Complex v) { Complex temp = div(v); //temp._real = _real / value._real; //temp._imag = _imag / value._imag; return temp; } Complex Complex::operator= (Complex v) { _real = v._real; _imag = v._imag; return *this; } std::ostream& operator<<(std::ostream &out, const Complex Value) { out << Value._real << " " << Value._imag; return out; } std::istream& operator>>(std::istream &in, Complex &Value) { in >> Value._real >> Value._imag; return in; }
true
597bde3d36788e62b037104bcf9690fbaa47bc22
C++
Wulala1119/myLeetCode
/139_WordBreak/139_WordBreak.cpp
UTF-8
1,072
3.015625
3
[]
no_license
#include <iostream> #include <vector> #include <math.h> #include <string> #include <unordered_set> using namespace std; class Solution { public: bool wordBreak(string s, unordered_set<string>& wordDict) { if(s == "") return false; bool *isFind = new bool[s.size()]; memset(isFind, false, sizeof(bool) * s.size()); for(int i = 0; i < s.size(); i ++) { if(i == 0 || isFind[i - 1] == true) { int j = i; for(; j <= s.size(); j ++) { if(wordDict.find(s.substr(i, j - i + 1)) != wordDict.end()) { isFind[j] = true; } } } } return isFind[s.size() - 1]; } }; void Test() { Solution solution0; unordered_set<string> wordD; wordD.insert("a"); wordD.insert("b"); //wordD.insert("b"); //wordD.insert("cd"); cout << solution0.wordBreak("ab", wordD) << endl; } int main() { Test(); system("pause"); return 0; }
true
0ce8d6c8f71647019798f3ffdc262f5f979b3a81
C++
gembancud/CompetitiveProgramming
/codeforces/threematrices/a.cpp
UTF-8
942
2.90625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<vector<double>> v(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double x; cin >> x; v[i].push_back(x); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) cout << setprecision(10) << fixed << v[i][j] << " "; else cout << setprecision(10) << fixed << (v[i][j] + v[j][i]) / 2.0 << " "; } cout << "\n"; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) cout << setprecision(10) << fixed << 0.0 << " "; else cout << setprecision(10) << fixed << (v[i][j]) - (v[i][j] + v[j][i]) / 2.0 << " "; } cout << "\n"; } }
true
61ec4c9949a16d69ff5d1678842b276ed49fbda0
C++
Anehta/AGE-lua
/src/render/age_node.cpp
UTF-8
726
2.875
3
[]
no_license
#include <../include/age_matrix4x4.h> #include <../include/age_node.h> namespace AGE2D { ANode::~ANode() { } ANode::ANode() { m_x = 0; m_y = 0; } void ANode::setX(float x) { m_x = x; } void ANode::setY(float y) { m_y = y; } void ANode::setPos(AVector2D pos) { m_x=pos.x (); m_y=pos.y (); } void ANode::setScale(float value) { m_scale = value; } float ANode::getX() { return m_x; } float ANode::getY() { return m_y; } AVector2D ANode::pos() { AVector2D a; a.setX (getX()); a.setY (getY()); return a; } float ANode::getScale() { return m_scale; } AMatrix4x4 ANode::getMatrix() { AMatrix4x4 temp; temp.translate(m_x,m_y,0); //m_matrix.scale(m_scale); return temp; } }
true
ed3e0d5b7541c4dea75681dddbffd5e87ec645fb
C++
emberian/cs142-proj1
/browser.h
UTF-8
786
2.703125
3
[]
no_license
#pragma once #include <unordered_map> #include <vector> #include <string> #include <tuple> #include "option.h" struct word { unsigned int index, length; bool is_link; unsigned int linkidx; }; struct link { std::string destination; std::string text; }; // the contents of the file, the offsets of words in the file, and the links // in the file. // // this is kept around to make reflow fast. typedef std::tuple<std::string, std::vector<word>, std::vector<std::string> > fileinfo; option<link> parse_link(std::istream&); word parse_word(std::istream&, std::ostream&); std::string eat_word(std::istream&); class browser { // Store a mapping from filename to its offset information. std::unordered_map<std::string, fileinfo> data; public: void add_file(std::string); };
true
fc4306a90f4cef4dd6aa97add87501dfa2fce7bf
C++
GIBIS-UNIFESP/BIAL
/tst/src/Matrix-3DCompare.cpp
UTF-8
1,023
2.90625
3
[]
no_license
/* Biomedical Image Analysis Library */ /* See README file in the root instalation directory for more information. */ /* Author: Fábio Augusto Menocci Cappabianco */ /* Date: 2012/Jun/29 */ /* Version: 1.0.00 */ /* Content: Test file. */ /* Description: Test with Matrix class. */ #include "Matrix.hpp" using namespace std; using namespace Bial; int main( int, char** ) { Matrix< double > M1( 5, 5, 5 ); Matrix< double > M2( 10, 10 ); double scalar; bool equals; M1.Set( 10.34 ); scalar = 10.0; cout << "M1." << endl << M1 << endl; M2 = M1 * scalar; cout << "M2 = M1 * 10.0." << endl << M2 << endl; M1 *= scalar; cout << "M1 *= 10.0." << endl << M1 << endl; equals = M1.Equals( M2, 0.01 ); cout << "M1 is equal to M2? " << equals << endl; M2( 0 ) = -100.1; M2( 0, 3, 2 ) = M2( 0 ); M2( 1 ) = M2( 0, 3, 2 ); cout << "M2 modified by operator () in indexes ( 0 ), ( 1 ), and ( 0, 3, 2 )." << endl << M2 << endl; equals = M1.Equals( M2, 0.01 ); cout << "M1 is equal to M2? " << equals << endl; return( 0 ); }
true
399a74baf34def302c50b5972f1d68d6ca183b39
C++
codgician/Competitive-Programming
/Codeforces-Gym/101620J/dp_tree.cpp
UTF-8
2,196
2.6875
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <functional> #include <iterator> using namespace std; #define EDGE_SIZE 2000020 #define VERTEX_SIZE 1000010 typedef struct _Edge { int to; int next; } Edge; Edge arr[EDGE_SIZE]; int head[VERTEX_SIZE], arrPt; int vertexNum; int sizeArr[VERTEX_SIZE], sizeNum[VERTEX_SIZE]; int ansArr[VERTEX_SIZE], ansPt; void addEdge(int from, int to) { arr[arrPt] = {to, head[from]}; head[from] = arrPt++; } void dfs(int cntPt, int fatherPt) { sizeArr[cntPt] = 1; for (int i = head[cntPt]; i != -1; i = arr[i].next) { int nextPt = arr[i].to; if (nextPt == fatherPt) continue; dfs(nextPt, cntPt); sizeArr[cntPt] += sizeArr[nextPt]; } sizeNum[sizeArr[cntPt]]++; } bool check(int subNum) { int subSize = vertexNum / subNum, cntNum = 0; for (int i = subSize; i <= vertexNum; i += subSize) cntNum += sizeNum[i]; return cntNum == subNum; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); while (cin >> vertexNum) { memset(head, -1, sizeof(head)); memset(sizeArr, 0, sizeof(sizeArr)); memset(sizeNum, 0, sizeof(sizeNum)); arrPt = 0; for (int i = 0; i < vertexNum - 1; i++) { int from, to; cin >> from >> to; from--; to--; addEdge(from, to); addEdge(to, from); } dfs(0, -1); ansPt = 0; for (int i = 2; i * i <= vertexNum; i++) { if (vertexNum % i != 0) continue; if (check(i)) ansArr[ansPt++] = i - 1; if (i * i != vertexNum && check(vertexNum / i)) ansArr[ansPt++] = vertexNum / i - 1; } sort(ansArr + 0, ansArr + ansPt); for (int i = 0; i < ansPt; i++) cout << ansArr[i] << " "; cout << vertexNum - 1 << endl; } return 0; }
true
b860f2bcc70bf878f314aef12ef8ad953bed669d
C++
baozizhenmeixian/DoubleFaultDiagnosis
/GlpkDoubleDiagnosis/HierarchyNode.h
GB18030
1,341
3.296875
3
[]
no_license
#pragma once #include <string> #include <vector> using namespace std; class HierarchyNode { public: HierarchyNode(string); HierarchyNode(); //~HierarchyNode(void); void setValue(string v){ value = v; }; string getValue()const{ return value; }; void setNextCondition(vector<int> v){ nextConditon = v; }; vector<int> getNextCondition(){ return nextConditon; }; void setNeedliteral(bool v){ needliteral = v; }; int getNeedliteral()const{ return needliteral; }; void setIsOut(bool v){ isOut = v; }; int getIsOut()const{ return isOut; }; void setNext(vector<HierarchyNode *> v){ next = v; }; vector<HierarchyNode *> getNext(){ return next; }; bool operator==(const HierarchyNode & my) const{ return (value == my.value); } bool operator<(const HierarchyNode & my) const{ return (value.compare(my.value)); } private: string value; vector<HierarchyNode*> next; vector<int> nextConditon;//12 bool isOut; bool needliteral;//ųʱǷҪȷʣ }; struct hash_HierarchyNode{ size_t operator()(const class HierarchyNode & A)const{ return std::hash<string>()(A.getValue()); //return A.getvalue(); } }; struct equal_HierarchyNode{ bool operator()(const class HierarchyNode & a1, const class HierarchyNode & a2)const{ return a1.getValue().compare(a2.getValue())==0; } };
true
85db5266a18d332a379fdf7c76552cf5490589fd
C++
js2203/scheme_cpp
/scheme_builtInFunc.cpp
UTF-8
9,483
2.84375
3
[]
no_license
#include "scheme_builtInFunc.h" #include <iostream> namespace scm::trampoline { /** * * @return */ Continuation* addition() { int nArgs{popArg<int>()}; auto arguments = popArgs<Object*>(nArgs); if (std::any_of(arguments.begin(), arguments.end(), isFloat)) { auto lambda = [](double a, Object* b) { if (hasTag(b, TAG_FLOAT)) { return getFloatValue(b) + a; } else { return static_cast<double>(getIntValue(b) + a); } }; lastReturnValue = newFloat(std::accumulate(arguments.begin(), arguments.end(), 0, lambda)); return popFunc(); } else { auto lambda = [](int a, Object* b) { int result = getIntValue(b) + a; return result; }; lastReturnValue = newInteger(std::accumulate(arguments.begin(), arguments.end(), 0, lambda)); return popFunc(); } } /** * * @return */ Continuation* subtraction() { int nArgs{popArg<int>()}; auto subtrahends = popArgs<Object*>(nArgs - 1); int intSubtrahend{}; double doubleSubtrahend; auto* minuendObj = popArg<Object*>(); double minuend = hasTag(minuendObj, TAG_FLOAT) ? getFloatValue(minuendObj) : static_cast<double>(getIntValue(minuendObj)); if (subtrahends.empty()) { if (hasTag(minuendObj, TAG_FLOAT)) { lastReturnValue = newFloat(-getFloatValue(minuendObj)); return popFunc(); } lastReturnValue = newInteger(-getIntValue(minuendObj)); return popFunc(); } else if (hasTag(minuendObj, TAG_FLOAT) || std::any_of(subtrahends.begin(), subtrahends.end(), isFloat)) { auto lambda = [](double a, Object* b) { if (hasTag(b, TAG_INT)) { return a + static_cast<double>(getIntValue(b)); } return a + getFloatValue(b); }; doubleSubtrahend = std::accumulate(subtrahends.begin(), subtrahends.end(), double(0.0), lambda); lastReturnValue = newFloat(minuend - doubleSubtrahend); return popFunc(); } else { auto lambda = [](int a, Object* b) { return a + getIntValue(b); }; intSubtrahend = std::accumulate(subtrahends.begin(), subtrahends.end(), int(0), lambda); lastReturnValue = newInteger(static_cast<int>(minuend) - intSubtrahend); return popFunc(); } } /** * * @return */ Continuation* multiplication() { int nArgs{popArg<int>()}; ObjectVec arguments{popArgs<Object*>(nArgs)}; if (std::any_of(arguments.begin(), arguments.end(), isFloat)) { auto lambda = [](double a, Object* b) { if (hasTag(b, TAG_INT)) { return static_cast<double>(getIntValue(b)) * a; } return a * getFloatValue(b); }; lastReturnValue = newFloat(std::accumulate(arguments.begin(), arguments.end(), double(1), lambda)); return popFunc(); } else { auto lambda = [](int a, Object* b) { return a * getIntValue(b); }; lastReturnValue = newInteger(std::accumulate(arguments.begin(), arguments.end(), int{1}, lambda)); return popFunc(); } } /** * * @return */ Continuation* division_second() { Object* divisor{lastReturnValue}; Object* dividend{popArg<Object*>()}; if (isFloat(dividend) && isFloat(divisor)) { lastReturnValue = newFloat(getFloatValue(dividend) / getFloatValue(divisor)); return popFunc(); } else if (isFloat(dividend)) { lastReturnValue = newFloat(getFloatValue(dividend) / static_cast<double>(getIntValue(divisor))); return popFunc(); } else if (isFloat(divisor)) { lastReturnValue = newFloat(static_cast<double>(getIntValue(dividend)) / getFloatValue(divisor)); return popFunc(); } else { lastReturnValue = newFloat(static_cast<double>(getIntValue(dividend)) / static_cast<double>(getIntValue(divisor))); return popFunc(); } } /** * * @return */ Continuation* division() { int nArgs{popArg<int>()}; return trampolineCall((Continuation*)(multiplication), (Continuation*)(division_second), {nArgs - 1}); } /** * * @return */ Continuation* equal() { popArg<int>(); Object* b{popArg<Object*>()}; Object* a{popArg<Object*>()}; lastReturnValue = (a == b) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* equalString() { popArg<int>(); Object* b{popArg<Object*>()}; Object* a{popArg<Object*>()}; lastReturnValue = (scm::getStringValue(a) == scm::getStringValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* equalNumber() { popArg<int>(); Object* a{popArg<Object*>()}; Object* b{popArg<Object*>()}; if (!isNumber(a) || !isNumber(b)){ throw schemeException("incorrect type at '='", __FILE__, __LINE__); } if (isFloat(a) && isFloat(b)) { lastReturnValue = (scm::getFloatValue(a) == scm::getFloatValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else if (isFloat(a)) { lastReturnValue = (scm::getFloatValue(a) == scm::getIntValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else if (isFloat(b)) { lastReturnValue = (scm::getIntValue(a) == scm::getFloatValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else { lastReturnValue = (scm::getIntValue(a) == scm::getIntValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } } /** * * @return */ Continuation* greaterThan() { popArg<int>(); Object* b{popArg<Object*>()}; Object* a{popArg<Object*>()}; if (isFloat(a) && isFloat(b)) { lastReturnValue = (scm::getFloatValue(a) > scm::getFloatValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else if (isFloat(a)) { lastReturnValue = (scm::getFloatValue(a) > scm::getIntValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else if (isFloat(b)) { lastReturnValue = (scm::getIntValue(a) > scm::getFloatValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else { lastReturnValue = (scm::getIntValue(a) > scm::getIntValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } } /** * * @return */ Continuation* lesserThan() { popArg<int>(); Object* b{popArg<Object*>()}; Object* a{popArg<Object*>()}; if (isFloat(a) && isFloat(b)) { lastReturnValue = (scm::getFloatValue(a) < scm::getFloatValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else if (isFloat(a)) { lastReturnValue = (scm::getFloatValue(a) < scm::getIntValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else if (isFloat(b)) { lastReturnValue = (scm::getIntValue(a) < scm::getFloatValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } else { lastReturnValue = (scm::getIntValue(a) < scm::getIntValue(b)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } } /** * * @return */ Continuation* buildCons() { popArg<int>(); Object* cdr{popArg<Object*>()}; Object* car{popArg<Object*>()}; lastReturnValue = newCons(car, cdr); return popFunc(); } /** * * @return */ Continuation* getCarFunc() { popArg<int>(); Object* cons{popArg<Object*>()}; if (hasTag(cons, TAG_CONS)) { lastReturnValue = getCar(cons); return popFunc(); } return nullptr; } /** * * @return */ Continuation* getCdrFunc() { popArg<int>(); Object* cons{popArg<Object*>()}; if (hasTag(cons, TAG_CONS)) { lastReturnValue = getCdr(cons); return popFunc(); } return nullptr; } /** * * @return */ Continuation* buildList() { int nArgs{popArg<int>()}; Object* rest = SCM_NIL; while (nArgs--) { Object* currentArgument{popArg<Object*>()}; rest = newCons(currentArgument, rest); } lastReturnValue = rest; return popFunc(); } /** * * @return */ Continuation* display() { int nArgs{popArg<int>()}; ObjectVec arguments{popArgs<Object*>(nArgs)}; for (auto argument{arguments.rbegin()}; argument != arguments.rend(); argument++) { std::cout << toString(*argument) << " "; } std::cout << '\n'; lastReturnValue = SCM_VOID; return popFunc(); } /** * * @return */ Continuation* returnFuncBody() { popArg<int>(); Object* obj{popArg<Object*>()}; if (hasTag(obj, TAG_FUNC_USER)) { lastReturnValue = getUserFunctionBody(obj); return popFunc(); } return nullptr; } /** * * @return */ Continuation* returnFuncArguments() { popArg<int>(); Object* obj{popArg<Object*>()}; if (hasTag(obj, TAG_FUNC_USER)) { lastReturnValue = getUserFunctionArgs(obj); return popFunc(); } return nullptr; } /** * * @return */ Continuation* isStringFunc() { popArg<int>(); Object* obj{popArg<Object*>()}; lastReturnValue = (isString(obj)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* isNumberFunc() { popArg<int>(); Object* obj{popArg<Object*>()}; lastReturnValue = (isNumber(obj)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* isConsFunc() { popArg<int>(); Object* obj{popArg<Object*>()}; lastReturnValue = (hasTag(obj, TAG_CONS)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* isBuiltinFunc() { popArg<int>(); Object* obj{popArg<Object*>()}; lastReturnValue = (hasTag(obj, TAG_FUNC_BUILTIN)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* isUserFunc() { popArg<int>(); Object* obj{popArg<Object*>()}; lastReturnValue = (hasTag(obj, TAG_FUNC_USER)) ? SCM_TRUE : SCM_FALSE; return popFunc(); } /** * * @return */ Continuation* isBoolFunc() { popArg<int>(); Object* obj{popArg<Object*>()}; lastReturnValue = (scm::isSameType(obj, {TAG_TRUE, TAG_FALSE})) ? SCM_TRUE : SCM_FALSE; return popFunc(); } } // namespace scm::trampoline
true
a4448b9a1f069bc0f3e15ed83cfd77f5b55a5093
C++
stelro/Vulkan-GPU-Real-time-RayTracing-BS-Thesis-
/source/IOManager.cc
UTF-8
4,320
2.71875
3
[]
no_license
/* ======================================================================= $File: IOManager.cc $Date: 7/1/2019 $Revision: $Creator: Rostislav Orestis Stelmach $Notice: This file is a part of Thesis project ( stracer ) for the Technical Educational Institute of Western Macedonia Supervisor: Dr. George Sisias ======================================================================== */ #include <cassert> #include "IOManager.hh" #include "VulkanEngine.hh" namespace ost { IOManager *IOManager::m_instance = nullptr; IOManager *IOManager::getInstance() noexcept { if ( m_instance ) return m_instance; m_instance = new IOManager(); return m_instance; } void IOManager::destroy() noexcept { OST_ASSERT_LOG(m_instance != nullptr, "IOManager already destroyed!"); delete m_instance; m_instance = nullptr; } void IOManager::pressKey(int key) noexcept { m_pressedKeys[key] = true; } void IOManager::releaseKey(int key) noexcept { m_pressedKeys[key] = false; } bool IOManager::isKeyPressed(int key) const noexcept { return isKeyHoldDown(key); } void IOManager::update([[maybe_unused]] float dt) noexcept { OST_ASSERT_LOG(m_window != nullptr, "Window has not been set in IOManager class!"); glfwPollEvents(); for ( auto &it : m_pressedKeys ) { m_previousKeys[it.first] = it.second; } // Handle special case where we should close window when // ESCAPE is pressed if ( glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_PRESS ) { glfwSetWindowShouldClose(m_window, true); } glfwSetWindowUserPointer(m_window, this); glfwSetKeyCallback(m_window, key_callback); glfwSetMouseButtonCallback(m_window, mouse_callback); glfwGetCursorPos(m_window, &m_MousePosX, &m_MousePoxY); } void IOManager::setWindow(GLFWwindow* w) noexcept { m_window = w; } void IOManager::key_callback(GLFWwindow *window, int key, [[maybe_unused]] int scan_code, int action, [[maybe_unused]] int mods) { auto *io_manager = static_cast<IOManager*>(glfwGetWindowUserPointer(window)); io_manager->m_inputIsActive = ( action != GLFW_RELEASE ); switch (action) { case GLFW_PRESS: io_manager->pressKey(key); break; case GLFW_RELEASE: io_manager->releaseKey(key); break; case GLFW_REPEAT: //io_manager->pressKey(key); break; default: break; } } bool IOManager::wasKeyDown(int key) const noexcept { auto it = m_previousKeys.find(key); if ( it != m_previousKeys.end() ) { return it->second; } else { return false; } } bool IOManager::isKeyHoldDown(int key) const noexcept { auto it = m_pressedKeys.find(key); if ( it != m_pressedKeys.end() ) { return it->second; } else { return false; } } float IOManager::getMousePosX() const noexcept { return static_cast<float>(m_MousePosX); } float IOManager::getMousePosY() const noexcept { return static_cast<float>(m_MousePoxY); } void IOManager::mouse_callback(GLFWwindow *window, int button, int action, int mods) { auto *io_manager = static_cast<IOManager*>(glfwGetWindowUserPointer(window)); auto flag = ( action != GLFW_RELEASE ); io_manager->m_inputIsActive = flag; switch (button) { case GLFW_MOUSE_BUTTON_RIGHT: io_manager->pressRightMouse( flag ); break; case GLFW_MOUSE_BUTTON_LEFT: io_manager->pressLeftMouse( flag ); break; case GLFW_MOUSE_BUTTON_MIDDLE: io_manager->pressMiddleMouse( flag ); break; } } void IOManager::pressLeftMouse(bool value) noexcept { m_mouseButtons.left = value; } void IOManager::pressRightMouse(bool value) noexcept { m_mouseButtons.right = value; } void IOManager::pressMiddleMouse(bool value) noexcept { m_mouseButtons.middle = value; } bool IOManager::isLeftMousePressed() const noexcept { return m_mouseButtons.left; } bool IOManager::isRightMousePressed() const noexcept { return m_mouseButtons.right; } bool IOManager::isMiddleMousePressed() const noexcept { return m_mouseButtons.middle; } bool IOManager::inputIsActive() const noexcept { return m_inputIsActive; } }
true
fcc0f0163ae22e0371f3b199fb71663f4671b047
C++
albicilla/-
/ant/Cable.cc
UTF-8
453
2.65625
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstdio> #include <cmath> using namespace std; int n; int k; double l[10010]; int f(double x){ int ans=0; for(int i=0;i<n;i++){ ans+=(int)(l[i]/x); } return ans; } int main(){ cin>>n>>k; for(int i=0;i<n;i++){ cin>>l[i]; } double lb=0.0,rb=1e9; for(int i=0;i<100;i++){ double mid=(rb+lb)/2; if(f(mid)>=k){ lb=mid; }else{ rb=mid; } } printf("%.2f\n",floor(rb*100)/100); }
true
f5eaa5f8c335c8505f2c41ceb0f7c0e7b99c4635
C++
e3ntity/aithena
/test/test_alphazero.cc
UTF-8
2,092
2.5625
3
[]
no_license
/** * @Copyright 2020 All Rights Reserved */ #include <torch/torch.h> #include <iostream> #include "alphazero/alphazero.h" #include "chess/game.h" #include "chess/util.h" #include "gtest/gtest.h" using namespace aithena; class AlphaZeroTest : public ::testing::Test { protected: void SetUp() { chess::Game::Options options = {{"board_width", 8}, {"board_height", 8}}; game_ = std::make_shared<chess::Game>(options); az_ = std::make_shared<AlphaZero>(game_); az_->SetSimulations(50); } chess::Game::GamePtr game_; std::shared_ptr<AlphaZero> az_; }; TEST_F(AlphaZeroTest, TestNNInput) { auto state = chess::State::FromFEN("7k/8/8/8/8/8/8/K7 w - - 0 1"); std::vector<AZNode::AZNodePtr> nodes = {std::make_shared<AZNode>(game_, state)}; AZNode::AZNodePtr next_node; for (int i = 0; i < 10; ++i) { next_node = az_->DrawAction(std::make_shared<AZNode>(game_, nodes.back()->GetState())); next_node->SetParent(nodes.back()); nodes.push_back(next_node); EXPECT_FALSE(nodes.back()->IsTerminal()); } EXPECT_EQ(nodes.size(), 11); auto player = nodes.back()->GetState()->GetPlayer(); torch::Tensor input = GetNNInput(nodes.back()); EXPECT_EQ(input.sizes(), std::vector<int64_t>({1, 119, 8, 8})); std::reverse(nodes.begin(), nodes.end()); for (int i = 0; i < 8; ++i) { torch::Tensor true_state_tensor = EncodeNodeState(nodes.at(i), player); torch::Tensor state_tensor = input[0].slice(0, i * 14, (i + 1) * 14); EXPECT_TRUE(state_tensor.equal(true_state_tensor)); } } TEST_F(AlphaZeroTest, TestNNOutput) { auto state = chess::State::FromFEN("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); auto node = std::make_shared<AZNode>(game_, state); for (int i = 0; i < 1000; ++i) az_->Simulate(node); torch::Tensor output = GetNNOutput(node); for (auto child : node->GetChildren()) { double true_prior = static_cast<double>(child->GetVisitCount()) / static_cast<double>(node->GetVisitCount()); double prior = GetNNOutput(output, child); EXPECT_NEAR(true_prior, prior, 1e-5); } }
true
508b5eb1279c67d6180554c8e77d6f415060c1af
C++
LaLlorona/Algorithms
/CodeForce/R634D3C.cpp
UTF-8
1,276
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; vector<int> input_arr; int MaxTeamMatching () { int num_keys = 0; map<int, int> occurance; map<int, int> :: iterator it; for (int i = 0; i < input_arr.size(); i++) { int count = 0; it = occurance.find(input_arr[i]); if (it == occurance.end()) { num_keys++; occurance[input_arr[i]] = 1; } else { occurance[input_arr[i]]++; } } if (input_arr.size() == 1) { return 0; } else{ int max_count = 0; for (auto iter = occurance.begin(); iter != occurance.end(); iter++) { max_count = max(max_count, iter -> second); } if (num_keys - 1 >= max_count) { return max_count; } else { return min(num_keys, max_count - 1); } } } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(NULL); std::cout.tie(NULL); std::ifstream in("in.txt"); std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt! int num_testcase; int input_num; int len_arr; cin >> num_testcase; while (num_testcase--) { input_arr.clear(); cin >> len_arr; for (int i = 0; i < len_arr; i++) { cin >> input_num; input_arr.push_back(input_num); } cout << MaxTeamMatching() << "\n"; } return 0; }
true
33c461d7d7593dbdefc904d3e9bcad5daacf711a
C++
Code-Diamond/AnonymousBeeper
/AnonymousBeeper.cpp
UTF-8
836
3.1875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int z=10, d=10, e=10, q = 10; vector<int> BEEP = {z, d, e, q}; cout << "Tell me a number: ", cin >> z; auto a = [&z](int x, int y) { z=100; cout << "\n\079\tBEEP \bBOOP\a\007\t\rBEEPBOOP\007\008\069\n" << endl; return x + y + z; }; auto b = [=](int x, int y) { cout << "\b\e\e\b\bB\bE\bE\bP\b \bB\bE\bE\bP\b\n\079\tBEEP \bBOOP\007\t\rBEEPBOOP\007\008\069\n" << endl; return x + y + z; }; auto c = [&](int x, int y) { q = z; cout << "\b\b\n\079\tBEEP \bBOOP\e\007\t\rBEEPBOOP\007\008\069\n" << endl; return x + y + z; }; cout << a(d,e); cout << b(d,e); cout << c(d,e); if(q == z) { double QQ = 0; std::for_each(begin(BEEP),end(BEEP),[&](int x){QQ+=x;}); cout<<"HELP COMPUTER"<<QQ<<endl; } return 0; }
true
1a73d69bb025ccec1b461962ad75df112b6e1f34
C++
jbjihwan/Innabus
/Engine/Interop/Vector3.cs.h
UTF-8
3,885
2.8125
3
[]
no_license
#pragma once using namespace System; #include "ibVec3.h" #include "Matrix3.cs.h" namespace Innabus { namespace Math { public ref class Vector3 { public: Vector3() { m_vector = new ibVec3; }; // No default init! Vector3( const f32 _x, const f32 _y, const f32 _z ) { m_vector = new ibVec3(_x, _y, _z); } Vector3( const ibVec3& rhs ) { m_vector = new ibVec3(rhs); } Vector3( Vector3% rhs ) { m_vector = new ibVec3(*rhs.m_vector); } Vector3( Vector3^ rhs ) { m_vector = new ibVec3(*rhs->m_vector); } Vector3% operator= ( Vector3% rhs ) { *m_vector = *rhs.m_vector; return *this; } ~Vector3() { this->!Vector3(); } !Vector3() { delete m_vector; } f32 Magnitude() { return m_vector->Magnitude(); } f32 MagnitudeS() { return m_vector->MagnitudeS(); } Vector3^ Normalize() { m_vector->Normalize(); return this; } Vector3^ NormalizeCopy( Vector3^ to ) { m_vector->NormalizeCopy(*to->m_vector); return to; } // Member versions work "in place" Vector3^ Add( Vector3^ rhs ) { m_vector->Add(*rhs->m_vector); return this; } Vector3^ Sub( Vector3^ rhs ) { m_vector->Sub(*rhs->m_vector); return this; } Vector3^ Mul( const f32 rhs ) { m_vector->Mul(rhs); return this; } Vector3^ Mul( Matrix3^ rhs) { m_vector->Mul(*rhs->m_matrix); return this; } f32 Dot( Vector3^ rhs ) { return m_vector->Dot(*rhs->m_vector); } Vector3^ Cross( Vector3^ rhs ) { m_vector->Cross(*rhs->m_vector); return this; } Vector3^ Stabelize() { m_vector->Stabelize(); return this; } // Non-member static Vector3^ Add( Vector3^ lhs, Vector3^ rhs ) { return (gcnew Vector3(lhs))->Add(rhs); } static Vector3^ Sub( Vector3^ lhs, Vector3^ rhs ) { return (gcnew Vector3(lhs))->Sub(rhs); } static Vector3^ Mul( const f32 lhs, Vector3^ rhs ) { return (gcnew Vector3(rhs))->Mul(lhs); } static Vector3^ Mul( Vector3^ lhs, const f32 rhs ) { return (gcnew Vector3(lhs))->Mul(rhs); } static Vector3^ Mul( Vector3^ lhs, Matrix3^ rhs ) { return (gcnew Vector3(lhs))->Mul(rhs); } static f32 Dot( Vector3^ lhs, Vector3^ rhs ) { return (gcnew Vector3(lhs))->Dot(rhs); } static Vector3^ Cross( Vector3^ lhs, Vector3^ rhs ) { return (gcnew Vector3(lhs))->Cross(rhs); } static Vector3^ Stabelize( Vector3^ v ) { return (gcnew Vector3(v))->Stabelize(); } virtual String^ ToString() override { return String::Format("[{0}, {1}, {2}]", x, y, z); } property float x { float get() { return m_vector->x; } void set(float val) { m_vector->x = val; } } property float y { float get() { return m_vector->y; } void set(float val) { m_vector->y = val; } } property float z { float get() { return m_vector->z; } void set(float val) { m_vector->z = val; } } static Vector3^ operator+ ( Vector3^ lhs, Vector3^ rhs ) { return Vector3::Add(lhs, rhs); } static Vector3^ operator- ( Vector3^ lhs, Vector3^ rhs ) { return Vector3::Sub(lhs, rhs); } static Vector3^ operator* ( const f32 scale, Vector3^ rhs ) { return Vector3::Mul(rhs, scale); } static Vector3^ operator* ( Vector3^ lhs, const f32 scale ) { return Vector3::Mul(lhs, scale); } static f32 operator* ( Vector3^ lhs, Vector3^ rhs ) { return Vector3::Dot(lhs, rhs); } static Vector3^ operator* ( Vector3^ lhs, Matrix3^ rhs ) { return Vector3::Mul(lhs, rhs); } static Vector3^ operator+= ( Vector3^ lhs, Vector3^ rhs ) { return lhs->Add(rhs); } static Vector3^ operator-= ( Vector3^ lhs, Vector3^ rhs ) { return lhs->Sub(rhs); } static Vector3^ operator*= ( Vector3^ lhs, const f32 scale ) { return lhs->Mul(scale); } static f32 operator*= ( Vector3^ lhs, Vector3^ rhs ) { return lhs->Dot(rhs); } static bool operator==( Vector3^ lhs, Vector3^ rhs ) { return *lhs->m_vector == *rhs->m_vector; } static bool operator!=( Vector3^ lhs, Vector3^ rhs ) { return !(lhs == rhs); } ibVec3* m_vector; }; } }
true
d59544cff24ee3b6433718fccb6234c6c9c31e92
C++
mmanley/Antares
/antares/src/tests/kits/storage/QueryTest.cpp
UTF-8
41,450
2.59375
3
[]
no_license
// QueryTest.cpp #include <ctype.h> #include <fs_info.h> #include <stdio.h> #include <string> #include <unistd.h> #include "QueryTest.h" #include <Application.h> #include <Message.h> #include <MessageQueue.h> #include <Messenger.h> #include <NodeMonitor.h> #include <OS.h> #include <Path.h> #include <Query.h> #include <String.h> #include <Volume.h> #include <TestApp.h> #include <TestUtils.h> // Query class Query : public BQuery { public: #if TEST_R5 status_t PushValue(int32 value) { PushInt32(value); return B_OK; } status_t PushValue(uint32 value) { PushUInt32(value); return B_OK; } status_t PushValue(int64 value) { PushInt64(value); return B_OK; } status_t PushValue(uint64 value) { PushUInt64(value); return B_OK; } status_t PushValue(float value) { PushFloat(value); return B_OK; } status_t PushValue(double value) { PushDouble(value); return B_OK; } status_t PushValue(const BString value, bool caseInsensitive = false) { PushString(value.String(), caseInsensitive); return B_OK; } status_t PushAttr(const char *attribute) { BQuery::PushAttr(attribute); return B_OK; } status_t PushOp(query_op op) { BQuery::PushOp(op); return B_OK; } #else status_t PushValue(int32 value) { return PushInt32(value); } status_t PushValue(uint32 value) { return PushUInt32(value); } status_t PushValue(int64 value) { return PushInt64(value); } status_t PushValue(uint64 value) { return PushUInt64(value); } status_t PushValue(float value) { return PushFloat(value); } status_t PushValue(double value) { return PushDouble(value); } status_t PushValue(const BString value, bool caseInsensitive = false) { return PushString(value.String(), caseInsensitive); } #endif }; // PredicateNode class PredicateNode { public: virtual ~PredicateNode() {} virtual status_t push(Query &query) const = 0; virtual BString toString() const = 0; }; // ValueNode template<typename ValueType> class ValueNode : public PredicateNode { public: ValueNode(ValueType v) : value(v) {} virtual ~ValueNode() {} virtual status_t push(Query &query) const { return query.PushValue(value); } virtual BString toString() const { return BString() << value; } ValueType value; }; // float specialization BString ValueNode<float>::toString() const { char buffer[32]; sprintf(buffer, "0x%08lx", *(int32*)&value); return BString() << buffer; } // double specialization BString ValueNode<double>::toString() const { char buffer[32]; sprintf(buffer, "0x%016Lx", *(int64*)&value); return BString() << buffer; } // StringNode class StringNode : public PredicateNode { public: StringNode(BString v, bool caseInsensitive = false) : value(v), caseInsensitive(caseInsensitive) { } virtual ~StringNode() {} virtual status_t push(Query &query) const { return query.PushValue(value, caseInsensitive); } virtual BString toString() const { BString escaped; if (caseInsensitive) { const char *str = value.String(); int32 len = value.Length(); for (int32 i = 0; i < len; i++) { char c = str[i]; if (isalpha(c)) { int lower = tolower(c); int upper = toupper(c); if (lower < 0 || upper < 0) escaped << c; else escaped << "[" << (char)lower << (char)upper << "]"; } else escaped << c; } } else escaped = value; escaped.CharacterEscape("\"\\'", '\\'); return BString("\"") << escaped << "\""; } BString value; bool caseInsensitive; }; // DateNode class DateNode : public PredicateNode { public: DateNode(BString v) : value(v) {} virtual ~DateNode() {} virtual status_t push(Query &query) const { return query.PushDate(value.String()); } virtual BString toString() const { BString escaped(value); escaped.CharacterEscape("%\"\\'", '\\'); return BString("%") << escaped << "%"; } BString value; }; // AttributeNode class AttributeNode : public PredicateNode { public: AttributeNode(BString v) : value(v) {} virtual ~AttributeNode() {} virtual status_t push(Query &query) const { return query.PushAttr(value.String()); } virtual BString toString() const { return value; } BString value; }; // short hands typedef ValueNode<int32> Int32Node; typedef ValueNode<uint32> UInt32Node; typedef ValueNode<int64> Int64Node; typedef ValueNode<uint64> UInt64Node; typedef ValueNode<float> FloatNode; typedef ValueNode<double> DoubleNode; // ListNode class ListNode : public PredicateNode { public: ListNode(PredicateNode *child1 = NULL, PredicateNode *child2 = NULL, PredicateNode *child3 = NULL, PredicateNode *child4 = NULL, PredicateNode *child5 = NULL, PredicateNode *child6 = NULL) : children() { addChild(child1); addChild(child2); addChild(child3); addChild(child4); addChild(child5); addChild(child6); } virtual ~ListNode() { for (int32 i = 0; PredicateNode *child = childAt(i); i++) delete child; } virtual status_t push(Query &query) const { status_t error = B_OK; for (int32 i = 0; PredicateNode *child = childAt(i); i++) { error = child->push(query); if (error != B_OK) break; } return error; } virtual BString toString() const { return BString("INVALID"); } ListNode &addChild(PredicateNode *child) { if (child) children.AddItem(child); return *this; } PredicateNode *childAt(int32 index) const { return (PredicateNode*)children.ItemAt(index); } BList children; }; // OpNode class OpNode : public ListNode { public: OpNode(query_op op, PredicateNode *left, PredicateNode *right = NULL) : ListNode(left, right), op(op) {} virtual ~OpNode() { } virtual status_t push(Query &query) const { status_t error = ListNode::push(query); if (error == B_OK) error = query.PushOp(op); return error; } virtual BString toString() const { PredicateNode *left = childAt(0); PredicateNode *right = childAt(1); if (!left) return "INVALID ARGS"; BString result; BString leftString = left->toString(); BString rightString; if (right) rightString = right->toString(); switch (op) { case B_INVALID_OP: result = "INVALID"; break; case B_EQ: result << "(" << leftString << "==" << rightString << ")"; break; case B_GT: result << "(" << leftString << ">" << rightString << ")"; break; case B_GE: result << "(" << leftString << ">=" << rightString << ")"; break; case B_LT: result << "(" << leftString << "<" << rightString << ")"; break; case B_LE: result << "(" << leftString << "<=" << rightString << ")"; break; case B_NE: result << "(" << leftString << "!=" << rightString << ")"; break; case B_CONTAINS: { StringNode *strNode = dynamic_cast<StringNode*>(right); if (strNode) { rightString = StringNode(BString("*") << strNode->value << "*").toString(); } result << "(" << leftString << "==" << rightString << ")"; break; } case B_BEGINS_WITH: { StringNode *strNode = dynamic_cast<StringNode*>(right); if (strNode) { rightString = StringNode(BString(strNode->value) << "*") .toString(); } result << "(" << leftString << "==" << rightString << ")"; break; } case B_ENDS_WITH: { StringNode *strNode = dynamic_cast<StringNode*>(right); if (strNode) { rightString = StringNode(BString("*") << strNode->value) .toString(); } result << "(" << leftString << "==" << rightString << ")"; break; } case B_AND: result << "(" << leftString << "&&" << rightString << ")"; break; case B_OR: result << "(" << leftString << "||" << rightString << ")"; break; case B_NOT: result << "(" << "!" << leftString << ")"; break; case _B_RESERVED_OP_: result = "RESERVED"; break; } return result; } query_op op; }; // QueryTestEntry class QueryTestEntry { public: QueryTestEntry(string path, node_flavor kind, const QueryTestEntry *linkTarget = NULL) : path(path), cpath(NULL), kind(kind), linkToPath(), clinkToPath(NULL), directory(-1), node(-1), name() { cpath = this->path.c_str(); if (linkTarget) linkToPath = linkTarget->path; clinkToPath = this->linkToPath.c_str(); } string operator+(string leaf) const { return path + "/" + leaf; } string path; const char *cpath; node_flavor kind; string linkToPath; const char *clinkToPath; ino_t directory; ino_t node; string name; }; static const char *testVolumeImage = "/tmp/query-test-image"; static const char *testMountPoint = "/non-existing-mount-point"; // the test entry hierarchy: // mountPoint // + dir1 // + subdir11 // + subdir12 // + file11 // + file12 // + link11 // + dir2 // + subdir21 // + subdir22 // + subdir23 // + file21 // + file22 // + link21 // + dir3 // + subdir31 // + subdir32 // + file31 // + file32 // + link31 // + file1 // + file2 // + file3 // + link1 // + link2 // + link3 static QueryTestEntry mountPoint(testMountPoint, B_DIRECTORY_NODE); static QueryTestEntry dir1(mountPoint + "dir1", B_DIRECTORY_NODE); static QueryTestEntry subdir11(dir1 + "subdir11", B_DIRECTORY_NODE); static QueryTestEntry subdir12(dir1 + "subdir12", B_DIRECTORY_NODE); static QueryTestEntry file11(dir1 + "file11", B_FILE_NODE); static QueryTestEntry file12(dir1 + "file12", B_FILE_NODE); static QueryTestEntry link11(dir1 + "link11", B_SYMLINK_NODE, &file11); static QueryTestEntry dir2(mountPoint + "dir2", B_DIRECTORY_NODE); static QueryTestEntry subdir21(dir2 + "subdir21", B_DIRECTORY_NODE); static QueryTestEntry subdir22(dir2 + "subdir22", B_DIRECTORY_NODE); static QueryTestEntry subdir23(dir2 + "subdir23", B_DIRECTORY_NODE); static QueryTestEntry file21(dir2 + "file21", B_FILE_NODE); static QueryTestEntry file22(dir2 + "file22", B_FILE_NODE); static QueryTestEntry link21(dir2 + "link21", B_SYMLINK_NODE, &file12); static QueryTestEntry dir3(mountPoint + "dir3", B_DIRECTORY_NODE); static QueryTestEntry subdir31(dir3 + "subdir31", B_DIRECTORY_NODE); static QueryTestEntry subdir32(dir3 + "subdir32", B_DIRECTORY_NODE); static QueryTestEntry file31(dir3 + "file31", B_FILE_NODE); static QueryTestEntry file32(dir3 + "file32", B_FILE_NODE); static QueryTestEntry link31(dir3 + "link31", B_SYMLINK_NODE, &file22); static QueryTestEntry file1(mountPoint + "file1", B_FILE_NODE); static QueryTestEntry file2(mountPoint + "file2", B_FILE_NODE); static QueryTestEntry file3(mountPoint + "file3", B_FILE_NODE); static QueryTestEntry link1(mountPoint + "link1", B_SYMLINK_NODE, &file1); static QueryTestEntry link2(mountPoint + "link2", B_SYMLINK_NODE, &file2); static QueryTestEntry link3(mountPoint + "link3", B_SYMLINK_NODE, &file3); static QueryTestEntry *allTestEntries[] = { &dir1, &subdir11, &subdir12, &file11, &file12, &link11, &dir2, &subdir21, &subdir22, &subdir23, &file21, &file22, &link21, &dir3, &subdir31, &subdir32, &file31, &file32, &link31, &file1, &file2, &file3, &link1, &link2, &link3 }; static const int32 allTestEntryCount = sizeof(allTestEntries) / sizeof(QueryTestEntry*); // create_test_entries void create_test_entries(QueryTestEntry **testEntries, int32 count) { // create the command line string cmdLine("true"); for (int32 i = 0; i < count; i++) { const QueryTestEntry *entry = testEntries[i]; switch (entry->kind) { case B_DIRECTORY_NODE: cmdLine += " ; mkdir " + entry->path; break; case B_FILE_NODE: cmdLine += " ; touch " + entry->path; break; case B_SYMLINK_NODE: cmdLine += " ; ln -s " + entry->linkToPath + " " + entry->path; break; case B_ANY_NODE: default: printf("WARNING: invalid node kind\n"); break; } } BasicTest::execCommand(cmdLine); } // delete_test_entries void delete_test_entries(QueryTestEntry **testEntries, int32 count) { // create the command line string cmdLine("true"); for (int32 i = 0; i < count; i++) { const QueryTestEntry *entry = testEntries[i]; switch (entry->kind) { case B_DIRECTORY_NODE: case B_FILE_NODE: case B_SYMLINK_NODE: cmdLine += " ; rm -rf " + entry->path; break; case B_ANY_NODE: default: printf("WARNING: invalid node kind\n"); break; } } BasicTest::execCommand(cmdLine); } // QueryTest // Suite CppUnit::Test* QueryTest::Suite() { CppUnit::TestSuite *suite = new CppUnit::TestSuite(); typedef CppUnit::TestCaller<QueryTest> TC; suite->addTest( new TC("BQuery::Predicate Test", &QueryTest::PredicateTest) ); suite->addTest( new TC("BQuery::Parameter Test", &QueryTest::ParameterTest) ); suite->addTest( new TC("BQuery::Fetch Test", &QueryTest::FetchTest) ); suite->addTest( new TC("BQuery::Live Test", &QueryTest::LiveTest) ); return suite; } // setUp void QueryTest::setUp() { BasicTest::setUp(); fApplication = new BTestApp("application/x-vnd.obos.query-test"); if (fApplication->Init() != B_OK) { fprintf(stderr, "Failed to initialize application.\n"); delete fApplication; fApplication = NULL; } fVolumeCreated = false; } // tearDown void QueryTest::tearDown() { BasicTest::tearDown(); if (fApplication) { fApplication->Terminate(); delete fApplication; fApplication = NULL; } if (fVolumeCreated) { deleteVolume(testVolumeImage, testMountPoint); fVolumeCreated = false; } } // TestPredicate static void TestPredicate(const PredicateNode &predicateNode, status_t pushResult = B_OK, status_t getResult = B_OK) { BString predicateString = predicateNode.toString().String(); //printf("predicate: `%s'\n", predicateString.String()); // GetPredicate(BString *) { Query query; // CPPUNIT_ASSERT( predicateNode.push(query) == pushResult ); status_t error = predicateNode.push(query); if (error != pushResult) { printf("predicate: `%s'\n", predicateString.String()); printf("error: %lx vs %lx\n", error, pushResult); } CPPUNIT_ASSERT( error == pushResult ); if (pushResult == B_OK) { BString predicate; // CPPUNIT_ASSERT( query.GetPredicate(&predicate) == getResult ); error = query.GetPredicate(&predicate); if (error != getResult) { printf("predicate: `%s'\n", predicateString.String()); printf("error: %lx vs %lx\n", error, getResult); } CPPUNIT_ASSERT( error == getResult ); if (getResult == B_OK) { CPPUNIT_ASSERT( (int32)query.PredicateLength() == predicateString.Length() + 1 ); CPPUNIT_ASSERT( predicateString == predicate ); } } } // GetPredicate(char *, size_t) { Query query; CPPUNIT_ASSERT( predicateNode.push(query) == pushResult ); if (pushResult == B_OK) { char buffer[1024]; CPPUNIT_ASSERT( query.GetPredicate(buffer, sizeof(buffer)) == getResult ); if (getResult == B_OK) CPPUNIT_ASSERT( predicateString == buffer ); } } // PredicateLength() { Query query; CPPUNIT_ASSERT( predicateNode.push(query) == pushResult ); if (pushResult == B_OK) { size_t expectedLength = (getResult == B_OK ? predicateString.Length() + 1 : 0); CPPUNIT_ASSERT( query.PredicateLength() == expectedLength ); } } // SetPredicate() { Query query; CPPUNIT_ASSERT( query.SetPredicate(predicateString.String()) == B_OK ); CPPUNIT_ASSERT( (int32)query.PredicateLength() == predicateString.Length() + 1 ); BString predicate; CPPUNIT_ASSERT( query.GetPredicate(&predicate) == B_OK ); CPPUNIT_ASSERT( predicateString == predicate ); } } // TestOperator static void TestOperator(query_op op) { // well formed TestPredicate(OpNode(op, new AttributeNode("attribute"), new Int32Node(42) )); TestPredicate(OpNode(op, new AttributeNode("attribute"), new StringNode("some string") )); TestPredicate(OpNode(op, new AttributeNode("attribute"), new DateNode("22 May 2002") )); // ill formed TestPredicate(OpNode(op, new AttributeNode("attribute"), NULL), B_OK, B_NO_INIT); // R5: crashs when pushing B_CONTAINS/B_BEGINS/ENDS_WITH on an empty stack #if TEST_R5 if (op < B_CONTAINS || op > B_ENDS_WITH) #endif TestPredicate(OpNode(op, NULL, NULL), B_OK, B_NO_INIT); TestPredicate(OpNode(op, new AttributeNode("attribute"), new DateNode("22 May 2002") ).addChild(new Int32Node(42)), B_OK, B_NO_INIT); } // PredicateTest void QueryTest::PredicateTest() { // tests: // * Push*() // * Set/GetPredicate(), PredicateLength() // empty predicate NextSubTest(); char buffer[1024]; { Query query; BString predicate; CPPUNIT_ASSERT( query.GetPredicate(&predicate) == B_NO_INIT ); } { Query query; CPPUNIT_ASSERT( query.GetPredicate(buffer, sizeof(buffer)) == B_NO_INIT ); } // one element predicates NextSubTest(); TestPredicate(Int32Node(42)); TestPredicate(UInt32Node(42)); TestPredicate(Int64Node(42)); // R5: buggy PushUInt64() implementation. #if !TEST_R5 TestPredicate(UInt64Node(42)); #endif TestPredicate(FloatNode(42)); TestPredicate(DoubleNode(42)); TestPredicate(StringNode("some \" chars ' to \\ be ( escaped ) or " "% not!")); TestPredicate(StringNode("some \" chars ' to \\ be ( escaped ) or " "% not!", true)); TestPredicate(DateNode("+15 min")); TestPredicate(DateNode("22 May 2002")); TestPredicate(DateNode("tomorrow")); TestPredicate(DateNode("17:57")); TestPredicate(DateNode("invalid date"), B_BAD_VALUE); TestPredicate(AttributeNode("some attribute")); // operators NextSubTest(); TestOperator(B_EQ); TestOperator(B_GT); TestOperator(B_GE); TestOperator(B_LT); TestOperator(B_LE); TestOperator(B_NE); TestOperator(B_CONTAINS); TestOperator(B_BEGINS_WITH); TestOperator(B_ENDS_WITH); TestOperator(B_AND); TestOperator(B_OR); { // B_NOT TestPredicate(OpNode(B_NOT, new AttributeNode("attribute"))); TestPredicate(OpNode(B_NOT, new Int32Node(42))); TestPredicate(OpNode(B_NOT, new StringNode("some string"))); TestPredicate(OpNode(B_NOT, new StringNode("some string", true))); TestPredicate(OpNode(B_NOT, new DateNode("22 May 2002"))); TestPredicate(OpNode(B_NOT, NULL), B_OK, B_NO_INIT); } // well formed, legal predicate NextSubTest(); TestPredicate(OpNode(B_AND, new OpNode(B_CONTAINS, new AttributeNode("attribute"), new StringNode("hello") ), new OpNode(B_OR, new OpNode(B_NOT, new OpNode(B_EQ, new AttributeNode("attribute2"), new UInt32Node(7) ), NULL ), new OpNode(B_GE, new AttributeNode("attribute3"), new DateNode("20 May 2002") ) ) )); // well formed, illegal predicate NextSubTest(); TestPredicate(OpNode(B_EQ, new StringNode("hello"), new OpNode(B_LE, new OpNode(B_NOT, new Int32Node(17), NULL ), new DateNode("20 May 2002") ) )); // ill formed predicates // Some have already been tested in TestOperator, so we only test a few // special ones. NextSubTest(); TestPredicate(ListNode(new Int32Node(42), new StringNode("hello!")), B_OK, B_NO_INIT); TestPredicate(OpNode(B_EQ, new StringNode("hello"), new OpNode(B_NOT, NULL) ), B_OK, B_NO_INIT); // precedence Push*() over SetPredicate() NextSubTest(); { Query query; OpNode predicate1(B_CONTAINS, new AttributeNode("attribute"), new StringNode("hello") ); StringNode predicate2("I'm the loser. :´-("); CPPUNIT_ASSERT( predicate1.push(query) == B_OK ); CPPUNIT_ASSERT( query.SetPredicate(predicate2.toString().String()) == B_OK ); BString predicate; CPPUNIT_ASSERT( query.GetPredicate(&predicate) == B_OK ); CPPUNIT_ASSERT( predicate == predicate1.toString() ); } // GetPredicate() clears the stack NextSubTest(); { Query query; OpNode predicate1(B_CONTAINS, new AttributeNode("attribute"), new StringNode("hello") ); StringNode predicate2("I'm the winner. :-)"); CPPUNIT_ASSERT( predicate1.push(query) == B_OK ); BString predicate; CPPUNIT_ASSERT( query.GetPredicate(&predicate) == B_OK ); CPPUNIT_ASSERT( predicate == predicate1.toString() ); CPPUNIT_ASSERT( query.SetPredicate(predicate2.toString().String()) == B_OK ); CPPUNIT_ASSERT( query.GetPredicate(&predicate) == B_OK ); CPPUNIT_ASSERT( predicate == predicate2.toString() ); } // PredicateLength() clears the stack NextSubTest(); { Query query; OpNode predicate1(B_CONTAINS, new AttributeNode("attribute"), new StringNode("hello") ); StringNode predicate2("I'm the winner. :-)"); CPPUNIT_ASSERT( predicate1.push(query) == B_OK ); CPPUNIT_ASSERT( (int32)query.PredicateLength() == predicate1.toString().Length() + 1 ); CPPUNIT_ASSERT( query.SetPredicate(predicate2.toString().String()) == B_OK ); BString predicate; CPPUNIT_ASSERT( query.GetPredicate(&predicate) == B_OK ); CPPUNIT_ASSERT( predicate == predicate2.toString() ); } // SetPredicate(), Push*() fail after Fetch() NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExistEither\"") == B_NOT_ALLOWED ); // R5: Push*()ing a new predicate does work, though it doesn't make any sense #if TEST_R5 CPPUNIT_ASSERT( query.PushDate("20 May 2002") == B_OK ); CPPUNIT_ASSERT( query.PushValue((int32)42) == B_OK ); CPPUNIT_ASSERT( query.PushValue((uint32)42) == B_OK ); CPPUNIT_ASSERT( query.PushValue((int64)42) == B_OK ); CPPUNIT_ASSERT( query.PushValue((uint64)42) == B_OK ); CPPUNIT_ASSERT( query.PushValue((float)42) == B_OK ); CPPUNIT_ASSERT( query.PushValue((double)42) == B_OK ); CPPUNIT_ASSERT( query.PushValue("hello") == B_OK ); CPPUNIT_ASSERT( query.PushAttr("attribute") == B_OK ); CPPUNIT_ASSERT( query.PushOp(B_EQ) == B_OK ); #else CPPUNIT_ASSERT( query.PushDate("20 May 2002") == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue((int32)42) == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue((uint32)42) == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue((int64)42) == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue((uint64)42) == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue((float)42) == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue((double)42) == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushValue("hello") == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushAttr("attribute") == B_NOT_ALLOWED ); CPPUNIT_ASSERT( query.PushOp(B_EQ) == B_NOT_ALLOWED ); #endif } // SetPredicate(): bad args // R5: crashes when passing NULL to Set/GetPredicate() #if !TEST_R5 NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate(NULL) == B_BAD_VALUE ); CPPUNIT_ASSERT( query.SetPredicate("hello") == B_OK ); CPPUNIT_ASSERT( query.GetPredicate(NULL) == B_BAD_VALUE ); CPPUNIT_ASSERT( query.GetPredicate(NULL, 10) == B_BAD_VALUE ); } #endif } // ParameterTest void QueryTest::ParameterTest() { // tests: // * SetVolume, TargetDevice() // * SetTarget(), IsLive() // SetVolume(), TargetDevice() // uninitialized BQuery NextSubTest(); { BQuery query; CPPUNIT_ASSERT( query.TargetDevice() == B_ERROR ); } // NULL volume // R5: crashs when passing a NULL BVolume #if !TEST_R5 NextSubTest(); { BQuery query; CPPUNIT_ASSERT( query.SetVolume(NULL) == B_BAD_VALUE ); CPPUNIT_ASSERT( query.TargetDevice() == B_ERROR ); } #endif // invalid volume NextSubTest(); { BQuery query; BVolume volume(-2); CPPUNIT_ASSERT( volume.InitCheck() == B_BAD_VALUE ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.TargetDevice() == B_ERROR ); } // valid volume NextSubTest(); { BQuery query; dev_t device = dev_for_path("/boot"); BVolume volume(device); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.TargetDevice() == device ); } // SetTarget(), IsLive() // uninitialized BQuery NextSubTest(); { BQuery query; CPPUNIT_ASSERT( query.IsLive() == false ); } // uninitialized BMessenger NextSubTest(); { BQuery query; BMessenger messenger; CPPUNIT_ASSERT( messenger.IsValid() == false ); CPPUNIT_ASSERT( query.SetTarget(messenger) == B_BAD_VALUE ); CPPUNIT_ASSERT( query.IsLive() == false ); } // valid BMessenger NextSubTest(); { BQuery query; BMessenger messenger(&fApplication->Handler()); CPPUNIT_ASSERT( messenger.IsValid() == true ); CPPUNIT_ASSERT( query.SetTarget(messenger) == B_OK ); CPPUNIT_ASSERT( query.IsLive() == true ); } // SetVolume/Target() fail after Fetch() NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_NOT_ALLOWED ); BMessenger messenger(&fApplication->Handler()); CPPUNIT_ASSERT( messenger.IsValid() == true ); CPPUNIT_ASSERT( query.SetTarget(messenger) == B_NOT_ALLOWED ); } // Fetch() fails without a valid volume set NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_NO_INIT ); } } // TestFetchPredicateInit static void TestFetchPredicateInit(Query &query, TestSet &testSet, const char *mountPoint, const char *predicate, QueryTestEntry **entries, int32 entryCount) { // init the query CPPUNIT_ASSERT( query.SetPredicate(predicate) == B_OK ); BVolume volume(dev_for_path(mountPoint)); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); // init the test set testSet.clear(); for (int32 i = 0; i < entryCount; i++) testSet.add(entries[i]->path); } // TestFetchPredicate static void TestFetchPredicate(const char *mountPoint, const char *predicate, QueryTestEntry **entries, int32 entryCount) { // GetNextEntry() { Query query; TestSet testSet; TestFetchPredicateInit(query, testSet, mountPoint, predicate, entries, entryCount); BEntry entry; while (query.GetNextEntry(&entry) == B_OK) { // Antares supports rewinding queries, R5 does not. #ifdef TEST_R5 CPPUNIT_ASSERT( query.Rewind() == B_ERROR ); #endif CPPUNIT_ASSERT( query.CountEntries() == B_ERROR ); BPath path; CPPUNIT_ASSERT( entry.InitCheck() == B_OK ); CPPUNIT_ASSERT( entry.GetPath(&path) == B_OK ); CPPUNIT_ASSERT( testSet.test(path.Path()) == true ); } CPPUNIT_ASSERT( testSet.testDone() == true ); CPPUNIT_ASSERT( query.GetNextEntry(&entry) == B_ENTRY_NOT_FOUND ); } // GetNextRef() { Query query; TestSet testSet; TestFetchPredicateInit(query, testSet, mountPoint, predicate, entries, entryCount); entry_ref ref; while (query.GetNextRef(&ref) == B_OK) { // Antares supports rewinding queries, R5 does not. #ifdef TEST_R5 CPPUNIT_ASSERT( query.Rewind() == B_ERROR ); #endif CPPUNIT_ASSERT( query.CountEntries() == B_ERROR ); BPath path(&ref); CPPUNIT_ASSERT( path.InitCheck() == B_OK ); CPPUNIT_ASSERT( testSet.test(path.Path()) == true ); } CPPUNIT_ASSERT( testSet.testDone() == true ); CPPUNIT_ASSERT( query.GetNextRef(&ref) == B_ENTRY_NOT_FOUND ); } // GetNextDirents() { Query query; TestSet testSet; TestFetchPredicateInit(query, testSet, mountPoint, predicate, entries, entryCount); size_t bufSize = (sizeof(dirent) + B_FILE_NAME_LENGTH) * 10; char buffer[bufSize]; dirent *ents = (dirent *)buffer; while (query.GetNextDirents(ents, bufSize, 1) == 1) { // Antares supports rewinding queries, R5 does not. #ifdef TEST_R5 CPPUNIT_ASSERT( query.Rewind() == B_ERROR ); #endif CPPUNIT_ASSERT( query.CountEntries() == B_ERROR ); entry_ref ref(ents->d_pdev, ents->d_pino, ents->d_name); BPath path(&ref); CPPUNIT_ASSERT( path.InitCheck() == B_OK ); CPPUNIT_ASSERT( testSet.test(path.Path()) == true ); } CPPUNIT_ASSERT( testSet.testDone() == true ); CPPUNIT_ASSERT( query.GetNextDirents(ents, bufSize, 1) == 0 ); } // interleaving use of the different methods { Query query; TestSet testSet; TestFetchPredicateInit(query, testSet, mountPoint, predicate, entries, entryCount); size_t bufSize = (sizeof(dirent) + B_FILE_NAME_LENGTH) * 10; char buffer[bufSize]; dirent *ents = (dirent *)buffer; entry_ref ref; BEntry entry; while (query.GetNextDirents(ents, bufSize, 1) == 1) { // Antares supports rewinding queries, R5 does not. #ifdef TEST_R5 CPPUNIT_ASSERT( query.Rewind() == B_ERROR ); #endif CPPUNIT_ASSERT( query.CountEntries() == B_ERROR ); entry_ref entref(ents->d_pdev, ents->d_pino, ents->d_name); BPath entpath(&entref); CPPUNIT_ASSERT( entpath.InitCheck() == B_OK ); CPPUNIT_ASSERT( testSet.test(entpath.Path()) == true ); if (query.GetNextRef(&ref) == B_OK) { BPath refpath(&ref); CPPUNIT_ASSERT( refpath.InitCheck() == B_OK ); CPPUNIT_ASSERT( testSet.test(refpath.Path()) == true ); } if (query.GetNextEntry(&entry) == B_OK) { BPath path; CPPUNIT_ASSERT( entry.InitCheck() == B_OK ); CPPUNIT_ASSERT( entry.GetPath(&path) == B_OK ); CPPUNIT_ASSERT( testSet.test(path.Path()) == true ); } } CPPUNIT_ASSERT( query.GetNextEntry(&entry) == B_ENTRY_NOT_FOUND ); CPPUNIT_ASSERT( query.GetNextRef(&ref) == B_ENTRY_NOT_FOUND ); CPPUNIT_ASSERT( query.GetNextDirents(ents, bufSize, 1) == 0 ); } } // FetchTest void QueryTest::FetchTest() { // tests: // * Clear()/Fetch() // * BEntryList interface // Fetch() // uninitialized BQuery NextSubTest(); { Query query; CPPUNIT_ASSERT( query.Fetch() == B_NO_INIT ); } // incompletely initialized BQuery (no predicate) NextSubTest(); { Query query; BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_NO_INIT ); } // incompletely initialized BQuery (no volume) NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_NO_INIT ); } // incompletely initialized BQuery (invalid predicate) NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"&&") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_BAD_VALUE ); } // initialized BQuery, Fetch() twice NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_NOT_ALLOWED ); } // initialized BQuery, successful Fetch(), different predicates createVolume(testVolumeImage, testMountPoint, 2); fVolumeCreated = true; create_test_entries(allTestEntries, allTestEntryCount); // ... all files NextSubTest(); { QueryTestEntry *entries[] = { &file11, &file12, &file21, &file22, &file31, &file32, &file1, &file2, &file3 }; const int32 entryCount = sizeof(entries) / sizeof(QueryTestEntry*); TestFetchPredicate(testMountPoint, "name=\"file*\"", entries, entryCount); } // ... all entries containing a "l" NextSubTest(); { QueryTestEntry *entries[] = { &file11, &file12, &link11, &file21, &file22, &link21, &file31, &file32, &link31, &file1, &file2, &file3, &link1, &link2, &link3 }; const int32 entryCount = sizeof(entries) / sizeof(QueryTestEntry*); TestFetchPredicate(testMountPoint, "name=\"*l*\"", entries, entryCount); } // ... all entries ending on "2" NextSubTest(); { QueryTestEntry *entries[] = { &subdir12, &file12, &dir2, &subdir22, &file22, &subdir32, &file32, &file2, &link2 }; const int32 entryCount = sizeof(entries) / sizeof(QueryTestEntry*); TestFetchPredicate(testMountPoint, "name=\"*2\"", entries, entryCount); } // Clear() // uninitialized BQuery NextSubTest(); { Query query; CPPUNIT_ASSERT( query.Clear() == B_OK ); } // initialized BQuery, Fetch(), Clear(), Fetch() NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); CPPUNIT_ASSERT( query.Clear() == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_NO_INIT ); } // initialized BQuery, Fetch(), Clear(), re-init, Fetch() NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); CPPUNIT_ASSERT( query.Clear() == B_OK ); CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); CPPUNIT_ASSERT( volume.SetTo(dev_for_path("/boot")) == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); } // BEntryList interface: // empty queries NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); BEntry entry; entry_ref ref; size_t bufSize = (sizeof(dirent) + B_FILE_NAME_LENGTH) * 10; char buffer[bufSize]; dirent *ents = (dirent *)buffer; CPPUNIT_ASSERT( query.GetNextEntry(&entry) == B_ENTRY_NOT_FOUND ); CPPUNIT_ASSERT( query.GetNextRef(&ref) == B_ENTRY_NOT_FOUND ); CPPUNIT_ASSERT( query.GetNextDirents(ents, bufSize, 1) == 0 ); } // uninitialized queries NextSubTest(); { Query query; BEntry entry; entry_ref ref; size_t bufSize = (sizeof(dirent) + B_FILE_NAME_LENGTH) * 10; char buffer[bufSize]; dirent *ents = (dirent *)buffer; CPPUNIT_ASSERT( query.GetNextEntry(&entry) == B_FILE_ERROR ); CPPUNIT_ASSERT( query.GetNextRef(&ref) == B_FILE_ERROR ); CPPUNIT_ASSERT( query.GetNextDirents(ents, bufSize, 1) == B_FILE_ERROR ); } // bad args NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"ThisShouldNotExist\"") == B_OK ); BVolume volume(dev_for_path("/boot")); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); size_t bufSize = (sizeof(dirent) + B_FILE_NAME_LENGTH) * 10; // R5: crashs when passing a NULL BEntry or entry_ref #if !TEST_R5 CPPUNIT_ASSERT( query.GetNextEntry(NULL) == B_BAD_VALUE ); CPPUNIT_ASSERT( query.GetNextRef(NULL) == B_BAD_VALUE ); #endif CPPUNIT_ASSERT( equals(query.GetNextDirents(NULL, bufSize, 1), B_BAD_ADDRESS, B_BAD_VALUE) ); } } // AddLiveEntries void QueryTest::AddLiveEntries(QueryTestEntry **entries, int32 entryCount, QueryTestEntry **queryEntries, int32 queryEntryCount) { create_test_entries(entries, entryCount); for (int32 i = 0; i < entryCount; i++) { QueryTestEntry *entry = entries[i]; BNode node(entry->cpath); CPPUNIT_ASSERT( node.InitCheck() == B_OK ); node_ref nref; CPPUNIT_ASSERT( node.GetNodeRef(&nref) == B_OK ); entry->node = nref.node; entry_ref ref; CPPUNIT_ASSERT( get_ref_for_path(entry->cpath, &ref) == B_OK ); entry->directory = ref.directory; entry->name = ref.name; } CheckUpdateMessages(B_ENTRY_CREATED, queryEntries, queryEntryCount); } // RemoveLiveEntries void QueryTest::RemoveLiveEntries(QueryTestEntry **entries, int32 entryCount, QueryTestEntry **queryEntries, int32 queryEntryCount) { delete_test_entries(entries, entryCount); CheckUpdateMessages(B_ENTRY_REMOVED, queryEntries, queryEntryCount); for (int32 i = 0; i < entryCount; i++) { QueryTestEntry *entry = entries[i]; entry->directory = -1; entry->node = -1; entry->name = ""; } } // CheckUpdateMessages void QueryTest::CheckUpdateMessages(uint32 opcode, QueryTestEntry **entries, int32 entryCount) { // wait for the messages snooze(100000); if (fApplication) { BMessageQueue &queue = fApplication->Handler().Queue(); CPPUNIT_ASSERT( queue.Lock() ); try { int32 entryNum = 0; while (BMessage *_message = queue.NextMessage()) { BMessage message(*_message); delete _message; CPPUNIT_ASSERT( entryNum < entryCount ); QueryTestEntry *entry = entries[entryNum]; CPPUNIT_ASSERT( message.what == B_QUERY_UPDATE ); uint32 msgOpcode; CPPUNIT_ASSERT( message.FindInt32("opcode", (int32*)&msgOpcode) == B_OK ); CPPUNIT_ASSERT( msgOpcode == opcode ); dev_t device; CPPUNIT_ASSERT( message.FindInt32("device", &device) == B_OK ); CPPUNIT_ASSERT( device == dev_for_path(testMountPoint) ); ino_t directory; CPPUNIT_ASSERT( message.FindInt64("directory", &directory) == B_OK ); CPPUNIT_ASSERT( directory == entry->directory ); ino_t node; CPPUNIT_ASSERT( message.FindInt64("node", &node) == B_OK ); CPPUNIT_ASSERT( node == entry->node ); if (opcode == B_ENTRY_CREATED) { const char *name; CPPUNIT_ASSERT( message.FindString("name", &name) == B_OK ); CPPUNIT_ASSERT( entry->name == name ); } entryNum++; } CPPUNIT_ASSERT( entryNum == entryCount ); } catch (CppUnit::Exception exception) { queue.Unlock(); throw exception; } queue.Unlock(); } } // LiveTest void QueryTest::LiveTest() { // tests: // * live queries CPPUNIT_ASSERT( fApplication != NULL ); createVolume(testVolumeImage, testMountPoint, 2); fVolumeCreated = true; create_test_entries(allTestEntries, allTestEntryCount); BMessenger target(&fApplication->Handler()); // empty query, add some files, remove some files NextSubTest(); { Query query; CPPUNIT_ASSERT( query.SetPredicate("name=\"*Argh\"") == B_OK ); BVolume volume(dev_for_path(testMountPoint)); CPPUNIT_ASSERT( volume.InitCheck() == B_OK ); CPPUNIT_ASSERT( query.SetVolume(&volume) == B_OK ); CPPUNIT_ASSERT( query.SetTarget(target) == B_OK ); CPPUNIT_ASSERT( query.Fetch() == B_OK ); BEntry entry; CPPUNIT_ASSERT( query.GetNextEntry(&entry) == B_ENTRY_NOT_FOUND ); // the test entries QueryTestEntry testDir1(dir1 + "testDirArgh", B_DIRECTORY_NODE); QueryTestEntry testDir2(dir1 + "testDir2", B_DIRECTORY_NODE); QueryTestEntry testFile1(subdir21 + "testFileArgh", B_FILE_NODE); QueryTestEntry testFile2(subdir21 + "testFile2", B_FILE_NODE); QueryTestEntry testLink1(subdir32 + "testLinkArgh", B_SYMLINK_NODE, &file11); QueryTestEntry testLink2(subdir32 + "testLink2", B_SYMLINK_NODE, &file11); QueryTestEntry *entries[] = { &testDir1, &testDir2, &testFile1, &testFile2, &testLink1, &testLink2 }; int32 entryCount = sizeof(entries) / sizeof(QueryTestEntry*); QueryTestEntry *queryEntries[] = { &testDir1, &testFile1, &testLink1 }; int32 queryEntryCount = sizeof(queryEntries) / sizeof(QueryTestEntry*); AddLiveEntries(entries, entryCount, queryEntries, queryEntryCount); RemoveLiveEntries(entries, entryCount, queryEntries, queryEntryCount); } // non-empty query, add some files, remove some files NextSubTest(); { Query query; TestSet testSet; CPPUNIT_ASSERT( query.SetTarget(target) == B_OK ); QueryTestEntry *initialEntries[] = { &file11, &file12, &file21, &file22, &file31, &file32, &file1, &file2, &file3 }; int32 initialEntryCount = sizeof(initialEntries) / sizeof(QueryTestEntry*); TestFetchPredicateInit(query, testSet, testMountPoint, "name=\"*ile*\"", initialEntries, initialEntryCount); BEntry entry; while (query.GetNextEntry(&entry) == B_OK) { BPath path; CPPUNIT_ASSERT( entry.InitCheck() == B_OK ); CPPUNIT_ASSERT( entry.GetPath(&path) == B_OK ); CPPUNIT_ASSERT( testSet.test(path.Path()) == true ); } CPPUNIT_ASSERT( testSet.testDone() == true ); CPPUNIT_ASSERT( query.GetNextEntry(&entry) == B_ENTRY_NOT_FOUND ); // the test entries QueryTestEntry testDir1(dir1 + "testDir1", B_DIRECTORY_NODE); QueryTestEntry testDir2(dir1 + "testDir2", B_DIRECTORY_NODE); QueryTestEntry testFile1(subdir21 + "testFile1", B_FILE_NODE); QueryTestEntry testFile2(subdir21 + "testFile2", B_FILE_NODE); QueryTestEntry testLink1(subdir32 + "testLink1", B_SYMLINK_NODE, &file11); QueryTestEntry testLink2(subdir32 + "testLink2", B_SYMLINK_NODE, &file11); QueryTestEntry testFile3(subdir32 + "testFile3", B_FILE_NODE); QueryTestEntry *entries[] = { &testDir1, &testDir2, &testFile1, &testFile2, &testLink1, &testLink2, &testFile3 }; int32 entryCount = sizeof(entries) / sizeof(QueryTestEntry*); QueryTestEntry *queryEntries[] = { &testFile1, &testFile2, &testFile3 }; int32 queryEntryCount = sizeof(queryEntries) / sizeof(QueryTestEntry*); AddLiveEntries(entries, entryCount, queryEntries, queryEntryCount); RemoveLiveEntries(entries, entryCount, queryEntries, queryEntryCount); } }
true
171befe80defecaf0665fde11fdc926f43b36a6e
C++
golovniaanna/dz
/DZ1.cpp
UTF-8
191
2.84375
3
[]
no_license
#include <iostream> using namespace std; int main(){ int a = 0, b = 0; a = 15; b = 20; std::cout << a << " + " << b << " = " << a + b << endl; return 0; }
true
87113ce80409f9f84bcc6840faca6d50724a784a
C++
moffel/iptap
/nettool/nettool.cpp
UTF-8
1,770
2.65625
3
[ "CC-BY-4.0" ]
permissive
#include <WinSock2.h> #include <Windows.h> #include <stdio.h> #include <time.h> #include <assert.h> #pragma comment(lib, "WS2_32.lib") struct get_header { unsigned long offset; unsigned short size; }; SOCKADDR_IN addr; void put(unsigned long address, const void* data, unsigned long size) { SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); const long zero = 0; int err = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*)&zero, 4); addr.sin_port = htons(81); err = connect(s, (sockaddr*)&addr, sizeof(addr)); address = htonl(address); err = send(s, (const char*)&address, 4, 0); err = send(s, (const char*)data, size, 0); err = closesocket(s); } void get(unsigned long address, void* data, unsigned long size) { SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); const long zero = 0; int err = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*)&zero, 4); addr.sin_port = htons(82); err = connect(s, (sockaddr*)&addr, sizeof(addr)); const get_header header = { htonl(address), htons(size) }; err = send(s, (const char*)&header, 6, 0); err = recv(s, (char*)data, size, 0); err = closesocket(s); } void main() { WSADATA wsaData; WSAStartup(MAKEWORD(1, 1), &wsaData); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("10.0.0.2"); srand(time(NULL)); while (1) { char testdata[1024]; char getdata[1024]; int len = rand() % 1024; for (int i = 0; i < len; ++i) testdata[i] = 'a' + rand() % 26; const unsigned addr_led = 0; const unsigned addr_uart = 0x80000000u; const unsigned addr_mem = 0xC0000000u; put(addr_mem, testdata, len); get(addr_mem, getdata, len); int equal = memcmp(testdata, getdata, len); assert(equal == 0); } }
true
2f4419b1e1cf6338c04eec9290ed59b7e9ef0910
C++
Aplikacjacpp/Drzewo_genealogiczne
/Drzewo_genealogiczne/Data/Personaly/gender.h
UTF-8
1,417
2.6875
3
[]
no_license
/*************************************************************************************************************** *"gender.h" * * * * * *CONTENTS: * "Klasa dziecko po C_data" *HISTORY: *version Date Changes Author/Programmer *1.0 26.04.2017 Orginal design Mateusz Marchelewicz *1.1 02.05.2015 Adding a virtual destructor Lukasz Witek vel Witkowski *1.2 02.05.2015 Adding a virtual methods Lukasz Witek vel Witkowski *1.3 02.05.2015 Adding parameter constructors Lukasz Witek vel Witkowski *1.4 13.05.2015 Adding a method "m_set_variable()" Lukasz Witek vel Witkowski ****************************************************************************************************************/ #ifndef GENDER_H #define GENDER_H #include "data.h" class C_gender: public C_data { public: C_gender(); C_gender(bool gender); C_gender(N_striing &gender); C_gender(const C_gender &C); C_gender& operator=(const C_gender &C); bool operator==(const C_gender &C); bool operator!=(const C_gender &C); friend std::ostream& operator<<(std::ostream& is,const C_gender &gender); virtual ~C_gender(); virtual bool m_wchat_is(); virtual void m_get_contens(N_striing &contens); virtual N_striing m_set_contens(); virtual int m_set_variable(); protected: private: virtual N_striing m_is_there_contens(N_striing &Word); N_striing s_data_gender; }; #endif // !GENDER_H
true
8bfb9a29279925554c16bce2b43f83208c91dd20
C++
AntonioShi/dataStructure
/school/XXX.cpp
UTF-8
649
2.84375
3
[]
no_license
// // Created by niracler on 17-9-4. // /* * 这个是关于矩阵转置的题目 * */ #include <iostream> using namespace std; int main9(void) { int n; cin >> n; int ** b = new int * [n]; for (int i = 0; i < n; ++i) { int * a = new int[n]; b[i] = a; } for (int j = 0; j < n; ++j) { for (int i = 0; i < n; ++i) { cin >> b[j][i]; } } for (int j = 0; j < n; j++) { if (j != 0) cout << endl; for (int i = 0; i < n; i++) { if(i != 0) cout << " "; cout << b[i][j]; } } return 0; }
true
9e13bf4e301fefe2df4ea8de886d55b771b1bc7e
C++
mugdhakapure/GeeksForGeeks-Practice-Solutions
/Snake_and_Ladder_Problem.cpp
UTF-8
2,308
3.796875
4
[]
no_license
/* Given a snake and ladder board of order 5x6, find the minimum number of dice throws required to reach the destination or last cell (30th cell) from source (1st cell) . Example ​For the above board output will be 3 For 1st throw get a 2 For 2nd throw get a 6 For 3rd throw get a 2 Input: The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains two lines. The first line of input contains an integer N denoting the no of ladders and snakes present. Then in the next line are 2*N space separated values a,b which denotes a ladder or a snake at position 'a' which takes to a position 'b'. Output: For each test case in a new line print the required answer denoting the min no of dice throws. Constraints: 1 <= T <= 100 1 <= N <= 10 1 <= a <= 30 1 <= b <= 30 Example: Input: 2 6 11 26 3 22 5 8 20 29 27 1 21 9 1 2 30 Output: 3 1 Explanation: Testcase 1: For 1st throw get a 2, which contains ladder to reach 22 For 2nd throw get a 6, which will lead to 28 Finally get a 2, to reach at the end 30. Thus 3 dice throws required to reach 30. */ using namespace std; int snakeAndLadder(vector<int> &board){ vector<int> visited(31, false); visited[0] = true; queue<pair<int, int> > q; q.push(make_pair(1, 0)); visited[1] = true; while(!q.empty()){ pair<int, int> p; p = q.front(); if(p.first == 30) return p.second; q.pop(); for(int i=p.first+1; i<=p.first+6 && i<31; i++){ if(!visited[i]){ pair<int, int> p1; p1.second = p.second + 1; visited[i] = true; if(board[i] != -1) p1.first = board[i]; else p1.first = i; q.push(p1); } } } } int main() { //code int t; cin>>t; for(int l=0; l<t; l++){ int n; cin>>n; vector<int> board(31, -1); for(int i=0; i<n; i++){ int a, b; cin>>a>>b; board[a] = b; } cout<<snakeAndLadder(board)<<endl; } return 0; }
true
2f0eb1dbdb6a88f0a95af444bfc72fde881d6072
C++
mmalakhova/tasks
/treap_refactoring/treap_refactoring.cpp
UTF-8
841
2.625
3
[]
no_license
#include "treap.h" #include <stdio.h> #define NumItems 12000 int main() { Treap T; Position P; int i; int j = 0; T = Initialize(); T = MakeEmpty(NullNode); for (i = 0; i < NumItems; i++, j = (j + 7) % NumItems) T = Insert(j, T); for (i = 0; i < NumItems; i++) if ((P = Find(i, T)) == NullNode || Retrieve(P) != i) printf("Error1 at %d\n", i); for (i = 0; i < NumItems; i += 2) T = Remove(i, T); for (i = 1; i < NumItems; i += 2) if ((P = Find(i, T)) == NullNode || Retrieve(P) != i) printf("Error2 at %d\n", i); for (i = 0; i < NumItems; i += 2) if ((P = Find(i, T)) != NullNode) printf("Error3 at %d\n", i); printf("Min is %d, Max is %d\n", Retrieve(FindMin(T)), Retrieve(FindMax(T))); return 0; }
true
a893de3fe78cc8d9433e0dc3f7938167557a1a78
C++
bangiao/C_plus_plus
/[stl]容器的begin和end成员/[stl]容器的begin和end成员/删除容器.cpp
UTF-8
362
2.984375
3
[]
no_license
#include <iostream> #include <map> #include <string> using namespace std; int main(void) { map<int, string> m_map; map<int, string>::iterator it = m_map.begin(); for (int i = 0; i < 10; i++) { m_map.insert(make_pair(i, "zhazha")); } for (auto &c : m_map) { cout << "ID:" << c.first << " Val: " << c.second << endl; } system("pause"); return 0; }
true
1ff6a5a67686e3c7af7e0e287cad222f1faf792e
C++
zhangchenghgd/zeroballistics
/code/bluebeard/src/HudBar.cpp
UTF-8
3,634
2.75
3
[]
no_license
#include "HudBar.h" #include "ParameterManager.h" #include "Vector2d.h" #include "SceneManager.h" //------------------------------------------------------------------------------ HudBar::HudBar(const std::string & section) : HudTextureElement(section), value_(0.0f) { const std::string & fill_dir = s_params.get<std::string>("hud." + section + ".fill_direction"); if (fill_dir == "RL") fill_direction_ = HBFD_RIGHT_LEFT; else if (fill_dir == "LR") fill_direction_ = HBFD_LEFT_RIGHT; else if (fill_dir == "TD") fill_direction_ = HBFD_TOP_DOWN; else if (fill_dir == "BU") fill_direction_ = HBFD_BOTTOM_UP; else { throw Exception("Fill dir must be RL, LR, TD or BU"); } setValue(1.0f); } //------------------------------------------------------------------------------ void HudBar::setValue(float val) { val = clamp(val, 0.0f, 1.0f); if (val == value_) return; value_ = val; updateVb(); } //------------------------------------------------------------------------------ float HudBar::getValue() { return value_; } //------------------------------------------------------------------------------ void HudBar::updateVb() { // Recreate buffers to reflect new size osg::Vec3Array * vertex = new osg::Vec3Array(4); // vec3 or computeBounds will complain setVertexArray(vertex); osg::Vec2Array* texcoord = new osg::Vec2Array(4); setTexCoordArray(0,texcoord); Vector2d pos; float size; getPositionAndSize(pos, size); switch (fill_direction_) { case HBFD_LEFT_RIGHT: (*vertex)[0].set(pos.x_, pos.y_, 0.0f); (*vertex)[1].set(pos.x_+size*aspect_ratio_*value_, pos.y_, 0.0f); (*vertex)[2].set(pos.x_+size*aspect_ratio_*value_, pos.y_+size, 0.0f); (*vertex)[3].set(pos.x_, pos.y_+size, 0.0f); (*texcoord)[0].set(0,0); (*texcoord)[1].set(value_,0); (*texcoord)[2].set(value_,1); (*texcoord)[3].set(0,1); break; case HBFD_RIGHT_LEFT: (*vertex)[0].set(pos.x_+size*aspect_ratio_*(1.0f-value_), pos.y_, 0.0f); (*vertex)[1].set(pos.x_+size*aspect_ratio_, pos.y_, 0.0f); (*vertex)[2].set(pos.x_+size*aspect_ratio_, pos.y_+size, 0.0f); (*vertex)[3].set(pos.x_+size*aspect_ratio_*(1.0f-value_), pos.y_+size, 0.0f); (*texcoord)[0].set(1-value_, 0); (*texcoord)[1].set(1, 0); (*texcoord)[2].set(1, 1); (*texcoord)[3].set(1-value_, 1); break; case HBFD_TOP_DOWN: (*vertex)[0].set(pos.x_, pos.y_+size*(1.0f-value_), 0.0f); (*vertex)[1].set(pos.x_+size*aspect_ratio_, pos.y_+size*(1.0f-value_), 0.0f); (*vertex)[2].set(pos.x_+size*aspect_ratio_, pos.y_+size, 0.0f); (*vertex)[3].set(pos.x_, pos.y_+size, 0.0f); (*texcoord)[0].set(0,1-value_); (*texcoord)[1].set(1,1-value_); (*texcoord)[2].set(1,1); (*texcoord)[3].set(0,1); break; case HBFD_BOTTOM_UP: (*vertex)[0].set(pos.x_, pos.y_, 0.0f); (*vertex)[1].set(pos.x_+size*aspect_ratio_, pos.y_, 0.0f); (*vertex)[2].set(pos.x_+size*aspect_ratio_, pos.y_+size*value_, 0.0f); (*vertex)[3].set(pos.x_, pos.y_+size*value_, 0.0f); (*texcoord)[0].set(0,0); (*texcoord)[1].set(1,0); (*texcoord)[2].set(1,value_); (*texcoord)[3].set(0,value_); break; } }
true
e23a282b04da1e39da5995167f021bf204c5424a
C++
FelipeNascimentods/Estruturas-De-Dados
/Recursividade/questao 01 (SLIDE).cpp
ISO-8859-1
355
3.65625
4
[]
no_license
// Escreva uma funo recursiva para computar o produto de dois nmeros inteiros positivos em termos da adio. #include <stdio.h> int funcao(int n1, int n2); int main(){ printf("%d\n", funcao(3, 2)); return 0; } int funcao(int n1, int n2){ int result = n1; if(n2==0){ result = 0; }else{ result += funcao(n1, n2-1); } return result; }
true
45de2cda03de21442509e906e620541200396571
C++
aiboatum/c-cpp
/Cpp实现Join函数/join.cpp
UTF-8
423
3.28125
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; string join(vector<string> &str,const string & delim = " "){ string ret; for(auto iter=str.begin();iter!=str.end();++iter){ ret += *iter; if(iter!=str.end()-1)ret += delim; } return ret; } int main() { vector<string> input(3); for(int i=0;i<3;++i)getline(cin,input[i]); cout<<join(input,"----->"); }
true
c0065781764c1ce5c7fe06a98f2fa667c963742a
C++
hmoevip/myprogram
/test/reverseCalcu.h
UTF-8
904
2.75
3
[]
no_license
#include "stdio.h" #include<iomanip> #include<iostream> #include<math.h> #include <vector> #include <list> using namespace std; //矩阵 class matrix { public: double data[3][3]; int row; int col; }; class matrixly { public: double dataly[3][1]; int rowly; int colly; }; class MyCalcu { public: vector<double> calculate(double a, double b, double c, double X, double Y, double Z); matrix mult(matrix a, matrix b); matrixly mult1(matrix a,matrixly b); matrixly add(matrixly a,matrixly b); //移动量 vector<double> move1(double a, double b, double c, double X, double Y, double Z,double aa, double bb, double cc, double XX, double YY, double ZZ); vector<double> move(vector<double> a,vector<double> b); void show(matrix a); void showly(matrixly a); //求两点距离函数 double distance(matrixly p,matrixly q); };
true
1ed39c75ad46982e675ffcaf5fb1c1e2b578044c
C++
3dapi/bs01_c
/strTrim2.cpp
UTF-8
1,324
3.625
4
[]
no_license
#include <stdio.h> void LcStr_TrimLeft(char* sBuf, const char *sTrm) { char* D= (char*)sBuf; char* L= (char*)sBuf; char* T= NULL; while( *L ) { T= (char*)sTrm; for(; *T && *T != *L; ++T); if(!*T) break; ++L; } while( *L ) *(D++) = *(L++); *D = '\0'; } void LcStr_TrimRight(char* sBuf, const char *sTrm) { char* D= (char*)sBuf; char* R= (char*)sBuf; char* L= (char*)sBuf; char* T= NULL; if('\0' == *R) { *D = '\0'; return; } while( *R ) ++R; --R; while(*R) { T= (char*)sTrm; for(; *T && *T != *R; ++T); if(!*T) break; --R; } while( L <= R) *(D++) = *(L++); *D = '\0'; } void LcStr_Trim(char* sBuf, const char *sTrm) { char* D= (char*)sBuf; char* R= (char*)sBuf; char* L= (char*)sBuf; char* T= NULL; // find L while( *L ) { T= (char*)sTrm; for(; *T && *T != *L; ++T); if(!*T) break; ++L; } // Find R R = L; while( *R ) ++R; // NULL string if(L >= R) { *D = '\0'; return; } --R; while(*R) { T= (char*)sTrm; for(; *T && *T != *R; ++T); if(!*T) break; --R; } while( L <= R) *(D++) = *(L++); *D = '\0'; } void main() { char str[] = " ,, 1, , 2 world , , "; // LcStr_TrimLeft(str, "\t ,"); // LcStr_TrimRight(str, "\t ,"); LcStr_Trim(str, "\t ,1world"); printf("%s\n", str); }
true
0d7dc3bf80f86742584fe45bdff341f6f1ac1d5f
C++
yuyilei/Daily-Notes
/offer/圆圈中最后剩下的数.cpp
UTF-8
1,585
3.234375
3
[]
no_license
/* 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1) */ // 法一:用链表进行过程模拟 struct node { int val; struct node* next; node(int v): val(v), next(NULL) {} }; class Solution { public: int LastRemaining_Solution(int n, int m) { if ( n <= 0 ) return -1; struct node* head = new struct node(0); struct node* now = head; for ( int i = 1 ; i <= n-1 ; i++ ) { struct node* tmp = new struct node(i); now->next = tmp; now = tmp; } now->next = head; for ( int i = 0 ; i < n-1 ; i++ ) { // 每次前进m-1步 for ( int j = 0 ; j < m-1 ; j++ ) { now = now->next; } // 被删除的节点是 now->next now->next = now->next->next; } return now->val; } };
true
ec60739067e9f00570ba42300717be2c109d1d2e
C++
TGlad/FractalColour2D
/FractalColour2D/graph_quantifying.cpp
UTF-8
4,639
3.046875
3
[]
no_license
// experiments with structural coloration of fractal curves, in particular Koch, Levy, Dragon and random curves. #include "stdafx.h" #include "bmp.h" #include "spectrumToRGB.h" #include <set> static int width = 4000; static int height = 1600; static int gap = 50; void setpixel(vector<BYTE> &out, const Vector2i &pos, const Vector3d &colour) { if (pos[0] < 0 || pos[0] >= width || pos[1] < 0 || pos[1] >= height) return; int ind = 3 * (pos[0] + width*(height - 1 - pos[1])); out[ind + 0] = max(0, min((int)(255.0*colour[0]), 255)); out[ind + 1] = max(0, min((int)(255.0*colour[1]), 255)); out[ind + 2] = max(0, min((int)(255.0*colour[2]), 255)); } void drawLineX(vector<BYTE> &out, double y, const Vector3d &colour, bool thick) { for (int x = 0; x < gap; x++) { setpixel(out, Vector2i(x, y-1), Vector3d(0, 0, 0)); setpixel(out, Vector2i(x, y), Vector3d(0, 0, 0)); setpixel(out, Vector2i(x, y+1), Vector3d(0, 0, 0)); } for (int x = gap; x < width; x++) { setpixel(out, Vector2i(x, y), colour); if (thick) { setpixel(out, Vector2i(x, y-1), colour); setpixel(out, Vector2i(x, y+1), colour); } } } void drawLineY(vector<BYTE> &out, double x, const Vector3d &colour, bool thick) { for (int y = 0; y < gap; y++) { setpixel(out, Vector2i(x-1, y), Vector3d(0, 0, 0)); setpixel(out, Vector2i(x, y), Vector3d(0, 0, 0)); setpixel(out, Vector2i(x+1, y), Vector3d(0, 0, 0)); } for (int y = gap; y < height; y++) { setpixel(out, Vector2i(x, y), colour); if (thick) { setpixel(out, Vector2i(x-1, y), colour); setpixel(out, Vector2i(x+1, y), colour); } } } void drawLine(vector<BYTE> &out, double y0, double y1, const Vector3d &colour) { for (int x = gap; x < width; x++) { double y = y0 + (y1 - y0) * (double)(x - gap) / (double)(width - gap); setpixel(out, Vector2i(x, y - 2.0), colour); setpixel(out, Vector2i(x, y - 1.0), colour); setpixel(out, Vector2i(x, y), colour); setpixel(out, Vector2i(x, y+1.0), colour); setpixel(out, Vector2i(x, y+2.0), colour); } } void drawTri(vector<BYTE> &out, double y0, double y1, double x, double y, const Vector3d &colour) { double top = y0 + (y1 - y0) * (double)(x - gap) / (double)(width - gap); double left = gap + (y - y0)*(double)(width - gap) / (y1 - y0); for (int i = left; i < x; i++) { setpixel(out, Vector2i(i, y-1), colour); setpixel(out, Vector2i(i, y), colour); setpixel(out, Vector2i(i, y+1), colour); } for (int j = y; j < top; j++) { setpixel(out, Vector2i(x-1, j), colour); setpixel(out, Vector2i(x, j), colour); setpixel(out, Vector2i(x+1, j), colour); } } void drawPoint(vector<BYTE> &out, double x, double y, double radius, const Vector3d &colour) { for (int i = x - radius; i <= x + radius; i++) { for (int j = y - radius; j <= y + radius; j++) { double r2 = sqr((double)i - x) + sqr((double)j - y); if (r2 <= sqr(radius)) setpixel(out, Vector2i(i, j), colour); } } } int _tmain(int argc, _TCHAR* argv[]) { long s2; vector<BYTE> out(width*height * 3); // .bmp pixel buffer memset(&out[0], 255, out.size() * sizeof(BYTE)); // background is grey for (int x = gap; x < width; x++) for (int y = gap; y < height; y++) setpixel(out, Vector2i(x, y), Vector3d(0.6, 0.8, 1.0)); int s = 1; int cols = 5; for (int j = 0; j < cols; j++) { for (int i = 1; i <= 10; i++) { double pos = log10((double)(i*s)) * (double)(width-gap) / (double)cols; double shade = 0.5; drawLineY(out, pos + (double)gap, Vector3d(shade, shade, shade), i==1); } s *= 10; } int rows = 2; s = 1; for (int j = 0; j < rows; j++) { for (int i = 1; i <= 10; i++) { double pos = log10((double)(i*s)) * (double)(height-gap) / (double)rows; double shade = 0.5; drawLineX(out, pos + (double)gap, Vector3d(shade, shade, shade), i==1); } s *= 10; } double start = height / 10; double end = 1.1*(double)height; drawLine(out, start, end, Vector3d(0, 0, 0.6)); drawTri(out, start, end, width / 2, height / 2, Vector3d(0, 0, 0)); double alongs[] = { 0.15, 0.3, 0.4, 0.54, 0.6, 0.75 }; for (int i = 0; i < 6; i++) { double x = alongs[i] * (double)width; double y = start + (end - start) * (double)(x - gap) / (double)(width - gap); y += random(-0.05, 0.05) * (double)height; drawPoint(out, x, y, 15.0, Vector3d(0.9, 0, 0)); } BYTE* c = ConvertRGBToBMPBuffer(&out[0], width, height, &s2); LPCTSTR file = L"graph.bmp"; SaveBMP(c, width, height, s2, file); delete[] c; }
true
9d0c3338ded625a7e49dd0febebd1a3b9f0b823a
C++
richieyan/RapidJsonSerialization
/Main/Player.h
UTF-8
1,217
2.96875
3
[]
no_license
#pragma once #include <string> #include <vector> #include <map> #include "Serializable.h" #include "Hero.h" #include "Preference.h" class Player : public Serializable { protected: virtual void __exSerialize(FastWriter& writer){ Serializable::put(writer, "ex1", preference); Serializable::put(writer, "ex2", heros); Serializable::put(writer, "ex3", hero); } virtual void __exDeserialize(FastReader & reader) { Serializable::get(reader,"ex1",preference); Serializable::get(reader,"ex2",heros); hero = new Hero(); Serializable::get(reader, "ex3", hero); } public: int level; int age; std::string name; std::map<int, int> skills;//key-value,key must be string std::vector<std::string> titles; std::vector<Hero> heros; Hero* hero = nullptr; Hero* master = nullptr; Preference preference; protected: virtual void regFields(){ reg("1", FieldType::INT, &level); reg("2", FieldType::INT, &age); reg("3", FieldType::STRING, &name); reg("4", FieldType::MAP_INT_INT, &skills); reg("5", FieldType::VECTOR_STRING, &titles); } };
true
50a9b09c63315cb39c5a4edb9275304a2b3608ea
C++
akashs2795/Learn-Cpp
/Sorting/Quick Sort.cpp
UTF-8
1,570
4.1875
4
[]
no_license
#include <iostream> using namespace std; void SwapRef(int &a, int &b) //to swap using call by reference { int temp = a; a = b; b = temp; } void print(int A[],int n) //to print the array { cout<<"The array is "; for (int i=0;i<n;i++) { cout<<A[i]<<" "; } cout<<endl; } int partitionEnd(int A[], int start, int end) { int pivot =A[end]; int pIndex=start; for (int i=start;i<end; i++) //to check each value with respect to pivot { if(A[i]<=pivot) //if a value is less than pivot, swap it with the pIndex element. { swap (A[i], A[pIndex]); pIndex++; } //now the array has values less than pivot till pIndex element } swap (A[pIndex],A[end]); //putting the pivot element in place return pIndex; } int partitionStart(int A[], int start, int end) { int pivot =A[start]; int pIndex=start+1; for (int i=start+1;i<=end; i++) { if(A[i]<=pivot) { swap (A[i], A[pIndex]); pIndex++; } } swap (A[pIndex-1],A[start]); return pIndex; } quickSort(int A[], int start, int end) { if (start<end) { int pInd=partitionEnd(A,start,end); //getting the index of pivot element quickSort(A,start, pInd-1); //sorting array before pivot quickSort(A, pInd+1, end); //sorting array after pivot } } int main() { int i,size; cout<<"Enter the number of elements"<<endl; cin>>size; int A[size]; // initializing a dynamic array of size 'size' cout<<"Enter the elements"<<endl; for (i=0;i<size;i++) //taking the array as input { cin>>A[i]; } print(A,size); quickSort(A,0,size-1); cout<<"yo"; print(A,size); }
true
09feeacb9a8bd79a053d5bcac3be04b85b1d3c18
C++
Myna65/RR
/src/objects/Mesh.h
UTF-8
714
2.71875
3
[]
no_license
#ifndef _3D_MESH_H #define _3D_MESH_H #include <set> #include "Point.h" #include "Polygon.h" #include "Surface.h" namespace RR::Objects { struct Mesh { private: std::string name; std::set<std::shared_ptr<Point>> points; std::set<std::shared_ptr<Polygon>> polygons; std::set<std::shared_ptr<Surface>> surfaces; public: void addPoint(std::shared_ptr<Point> point); void addPolygon(std::shared_ptr<Polygon> polygon); void addSurface(std::shared_ptr<Surface> surface); const std::set<std::shared_ptr<Point>> &getPoints() const; const std::set<std::shared_ptr<Polygon>> &getPolygons() const; }; } #endif //_3D_MESH_H
true
ae02b75c1a27d044bf90a56c82a97bc3283af83b
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/5/53.c
UTF-8
577
2.765625
3
[]
no_license
int atgc(char a){ if(a=='A'||a=='G'||a=='C'||a=='T'){ return 1; }else{ return 0; } } int main(){ double m; char xl1[500]={'\0'},xl2[500]={'\0'}; scanf("%lf %s %s",&m,xl1,xl2); int len1,len2; len1=strlen(xl1); len2=strlen(xl2); if(len1!=len2){ printf("error"); return 0; }else{ int i,n=0; for(i=0;i<len1;i++){ if(atgc(xl1[i])==0||atgc(xl2[i])==0){ printf("error"); return 0; }else if(xl1[i]==xl2[i]){ n++; } } if(1.0*n/len1>=m){ printf("yes"); }else{ printf("no"); } } return 0; }
true
748be9983ea9d9a120a3466df2c752b6c7cbf73f
C++
Hyski/ParadiseCracked
/Common/Sound/sndcompiler.h
UTF-8
524
2.609375
3
[]
no_license
#ifndef __SNDCOMPILER_H__ #define __SNDCOMPILER_H__ enum SND_ERRORS{ SUCCESSED, FILE_OPEN_ERROR, LEXER_ERROR, PARSER_ERROR, TOKEN_ERROR, TOKEN_BUFFER_ERROR, UNKNOWN_ERROR }; class SndCompiler{ public: SndCompiler() { m_line = 0; m_error = 0; }; ~SndCompiler() {}; bool Compile (const char* file_name); int GetLine () const { return m_line; } int GetLastError() const { return m_error;} private: int m_line; int m_error; }; #endif //__SNDCOMPILER_H__
true
b750c8e7ffb339a60008ed6cf61b9cd5b6b20473
C++
kunhuicho/crawl-tools
/codecrawler/_code/hdu2181/16210004.cpp
UTF-8
1,105
2.59375
3
[]
no_license
#include<iostream> #include<vector> #include<cstdio> #include<cstring> using namespace std; vector<int > map[25]; bool vis[25]; int pre[25]; int m,num; void print_ans(int cur){ if(cur!=m){ print_ans(pre[cur]); printf(" %d",cur); } } void dfs(int cur,int cnt){ if(cnt<20&&vis[m]) return; if(cnt==20&&cur==m){ printf("%d: %d",num++,m); print_ans(pre[m]); printf(" %d\n",m); // cout<<4342<<endl; return ; } for(int i=0;i<=2;i++){ int temp=map[cur][i]; if(!vis[temp]){ vis[temp]=true; pre[temp]=cur; dfs(temp,cnt+1); vis[temp]=false; } } } int main() { int a,b,c; for(int i=1; i<=20; i++) map[i].clear(); for(int i=1; i<=20; i++) { scanf("%d%d%d",&a,&b,&c); map[i].push_back(a);map[i].push_back(b);map[i].push_back(c); } while( scanf("%d",&m),m){ memset(vis,false,sizeof(vis)); memset(pre,0,sizeof(pre)); num=1; // cout<<m<<endl; dfs(m,0); } }
true
3da9319a28c4966d28b148bfd0852f0e89225aa7
C++
Jacajack/voxels
/include/lobor/shader.hpp
UTF-8
688
2.671875
3
[]
no_license
#ifndef LOBOR_SHADER_HPP #define LOBOR_SHADER_HPP #include <initializer_list> #include <vector> #include <string> #include <map> #include <GL/glew.h> #include <GLFW/glfw3.h> namespace lobor { //Struct used just by Shader constructor struct ShaderSpec { std::string filename; GLenum shader_type; }; //Shader set class Shader { private: GLuint program_id; std::map <std::string, GLint> uniforms; bool ready; public: //Utilities void use( ); GLuint uniform( std::string name ); //Constructor and destructor Shader( std::initializer_list <struct ShaderSpec> specs, std::initializer_list <std::string> uniform_names ); ~Shader( ); }; }; #endif
true
963437b4fc655a16add8dddcd50fecae7a70f341
C++
my-hoang-huu/My-hh
/1. Nhap mon lap trinh_chuong05_kieu cau truc/bai015.cpp
UTF-8
714
3.640625
4
[]
no_license
#include<iostream> #include<iomanip> #include<string> using namespace std; struct HOCSINH { string HoTen; int Toan; int Van; float TrungBinh; }; void Nhap(HOCSINH&); void Xuat(HOCSINH); int main() { HOCSINH A; Nhap(A); Xuat(A); return 1; } void Nhap(HOCSINH& a) { cout << "Nhap Ho va ten hoc sinh: "; getline(cin, a.HoTen); cout << "Nhap diem Toan: "; cin >> a.Toan; cout << "Nhap diem Van: "; cin >> a.Van; a.TrungBinh = (a.Toan + a.Van) * 1.0 / 2; } void Xuat(HOCSINH a) { cout << "\nThong tin hoc sinh: "; cout << "\nHo ten: " << a.HoTen; cout << "\nDiem Toan: " << a.Toan; cout << "\nDiem Van: " << a.Van; cout << "\nDiem trung binh: " << fixed << setprecision(2) << a.TrungBinh << endl; }
true
9acfc2680a48980882c7e9005ce19903dd24a54b
C++
cowtony/ACM
/LeetCode/2500-2599/2571. Minimum Operations to Reduce an Integer to 0.cpp
UTF-8
671
3.046875
3
[]
no_license
class Solution { public: int minOperations(int n) { int ops = 0; int continious_one = 0; while (n > 0) { if (n % 2 == 1) { continious_one++; } else { // == 0 if (continious_one == 1) { ops++; continious_one = 0; } else if (continious_one > 1) { ops++; continious_one = 1; } } n >>= 1; } if (continious_one > 1) { ops += 2; } else if (continious_one == 1) { ops++; } return ops; } };
true