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
65f1e0babab2113a1bc7c287c390ebdb8bcd5788
C++
L0mion/Makes-a-Click
/Source/DigitalSmoothControl.cpp
UTF-8
3,403
2.78125
3
[ "MIT" ]
permissive
#include "DigitalSmoothControl.h" #include "XInputFetcher.h" DigitalSmoothControl::DigitalSmoothControl( XInputFetcher* p_xinput, InputHelper::Xbox360Digitals p_lower, InputHelper::Xbox360Digitals p_raise, vector<int> p_points, float p_smoothSpeed, float p_smoothTime, float p_vibrationDuration ) { m_xinput = p_xinput; m_next = p_raise; m_prev = p_lower; m_points = p_points; m_smoothTime = p_smoothTime; m_smoothSpeed = p_smoothSpeed; m_vibrationDuration = p_vibrationDuration; m_pressedTime = 0.0f; m_vibbedTime = 0.0f; m_curPoint = p_points[0]; m_curSmooth = (float)p_points[0]; } DigitalSmoothControl::~DigitalSmoothControl() { } void DigitalSmoothControl::update( const float p_dt ) { if( m_vibbedTime > m_vibrationDuration ) { m_xinput->vibrate( 0, 0 ); } else { m_vibbedTime += p_dt; } InputHelper::KeyStates ksNext = m_xinput->getBtnState( m_next); InputHelper::KeyStates ksPrev = m_xinput->getBtnState( m_prev ); if( ksNext == InputHelper::KeyStates_KEY_PRESSED ) { m_pressedTime = 0.0f; } else if( ksNext == InputHelper::KeyStates_KEY_DOWN ) { m_pressedTime += p_dt; if( m_pressedTime > m_smoothTime ) { m_curSmooth += p_dt * m_smoothSpeed; } } else if( ksNext == InputHelper::KeyStates_KEY_RELEASED ) { if( m_pressedTime < m_smoothTime ) { nextPoint(); } } if( ksPrev == InputHelper::KeyStates_KEY_PRESSED ) { m_pressedTime = 0.0f; } else if( ksPrev == InputHelper::KeyStates_KEY_DOWN ) { m_pressedTime += p_dt; if( m_pressedTime > m_smoothTime ) { m_curSmooth -= p_dt * m_smoothSpeed; } } else if( ksPrev == InputHelper::KeyStates_KEY_RELEASED ) { if( m_pressedTime < m_smoothTime ) { prevPoint(); } } // Make sure not out of bounds m_curPoint = pointFromSmooth( m_curSmooth ); m_curSmooth = inBoundSmooth( m_curSmooth ); } int DigitalSmoothControl::getCurrentPoint() const { return m_curPoint; } void DigitalSmoothControl::setCurrentPoint( const int p_point ) { m_curPoint = p_point; m_curSmooth = (float)m_points[p_point]; } float DigitalSmoothControl::getCurrentSmooth() const { return m_curSmooth; } void DigitalSmoothControl::setCurrentSmooth( const float p_smooth ) { m_curSmooth = p_smooth; m_curPoint = pointFromSmooth( p_smooth ); } void DigitalSmoothControl::nextPoint() { m_curPoint++; m_curPoint = inBoundPoint( m_curPoint ); m_curSmooth = (float)m_points[m_curPoint]; } void DigitalSmoothControl::prevPoint() { m_curPoint--; m_curPoint = inBoundPoint( m_curPoint ); m_curSmooth = (float)m_points[m_curPoint]; } int DigitalSmoothControl::pointFromSmooth( float p_smooth ) { int vantage = (int)p_smooth; for( unsigned int i=m_points.size()-1; i>0; i-- ) { if( vantage >= m_points[i] ) { return i; } } return 0; } int DigitalSmoothControl::inBoundPoint( int p_point ) { if( p_point < 0 ) { p_point = 0; vibrate(); } else if( p_point >= (int)m_points.size() ) { p_point = (int)m_points.size()-1; vibrate(); } return p_point; } float DigitalSmoothControl::inBoundSmooth( float p_smooth ) { if( p_smooth < m_points[0] ) { p_smooth = (float)m_points[0]; vibrate(); } else if( p_smooth > m_points[m_points.size()-1] ) { p_smooth = (float)m_points[m_points.size()-1]; vibrate(); } return p_smooth; } void DigitalSmoothControl::vibrate() { unsigned short motorSpeed = USHRT_MAX; m_vibbedTime = 0.0f; m_xinput->vibrate( motorSpeed, motorSpeed ); }
true
3189744ccc5262d46126c02c87a16d943e8ea5d2
C++
arthurteisseire-epitech/Bomberman
/src/Entities/Orientation.cpp
UTF-8
459
2.96875
3
[]
no_license
/* ** EPITECH PROJECT, 2018 ** bomberman ** File description: ** Orientation.cpp */ #include "Orientation.hpp" std::ostream &ind::operator<<(std::ostream &os, Orientation orientation) { if (orientation == NORTH) os << "NORTH"; else if (orientation == SOUTH) os << "SOUTH"; else if (orientation == WEST) os << "WEST"; else if (orientation == EAST) os << "EAST"; else os << "NONE"; return os; }
true
15337d91418ca4bdff0b31dce50d8a06d9cdb3f6
C++
arkadiuszneuman/Socoban
/Socoban_Projekt/Button.h
UTF-8
656
2.609375
3
[]
no_license
#ifndef BUTTON_H #define BUTTON_H #include "BaseObject.h" #include "IButtonClickedEvent.h" #include "IMouseEvents.h" #include <string> #include <vector> class Button : public BaseObject, public IMouseEvents { private: Bitmap *bitmaps[3]; IButtonClickedEvent *buttonClickedEvent; bool IsMouseOver(Mouse mouse); bool isMouseDown; bool threeState, isClickable; std::string name; public: Button(std::string name, Point &location, IButtonClickedEvent *buttonClickedEvent, bool threeState); void MouseMove(Mouse mouse); void MouseButtonDown(Mouse mouse); void MouseButtonUp(Mouse mouse); void SetIsClickable(bool isClickable); ~Button(); }; #endif
true
26e1c0c8e638556c024c067fb83166e16b5411cf
C++
JesseLeal/NCGame
/Engine/KinematicComponent.cpp
UTF-8
1,226
2.75
3
[]
no_license
#include "KinematicComponent.h" #include "Timer.h" #include "Physics.h" void KinematicComponent::Create(float maxVel, float dampening, bool grav) { m_maxVelocity = maxVel; m_dampening = dampening; m_enableGrav = grav; m_forceType = eForceType::FORCE; m_force = Vector2D::zero; m_velocity = Vector2D::zero; } void KinematicComponent::Destroy() { // } void KinematicComponent::Update() { float dt = Timer::Instance()->DeltaTime(); Vector2D force = (m_enableGrav) ? m_force + Physics::Instance()->GetGravity() : m_force; m_velocity += (m_force * dt); float magnitude = m_velocity.Length(); if (magnitude > m_maxVelocity) { m_velocity = m_velocity.Normalized() * m_maxVelocity; } m_owner->GetTransform().position = m_owner->GetTransform().position + (m_velocity * dt); m_velocity = m_velocity * pow(m_dampening, dt); if (m_forceType == eForceType::IMPULSE) { m_force = Vector2D::zero; } } void KinematicComponent::ApplyForce(const Vector2D & force, eForceType forceType) { m_forceType = forceType; switch (m_forceType) //treat force and impulse the same here { case FORCE: case IMPULSE: m_force = force; break; case VELOCITY: m_force = Vector2D::zero; m_velocity = force; break; } }
true
c27b56d1f19d4aaab080cdcadcfe244888754ac2
C++
EstherTsai4/Homework3
/HW03/HW03/EvenNumbers.h
UTF-8
390
3.0625
3
[]
no_license
#pragma once class EvenNumbers { private: int value; public: //constructor no argument EvenNumbers(); //constructor with argument EvenNumbers(int); //function to return value of object int getValue(); //function to return the next even number after current even number int getNext(); //function to get previous even number before current even number int getPrevious(); };
true
e148fee90639c272cec365dad49880a3a02b46b1
C++
vitoriam19/tp1-algorithms2
/includes/match.hpp
UTF-8
601
2.6875
3
[]
no_license
#ifndef MATCH_HPP #define MATCH_HPP #include <iostream> #include <vector> using namespace std; /* Verifica se existe um match parcial entre o sufixo que queremos adicionar e a string presente do vértice que estamos visitando Essa função retorna a posição onde ocorreu o match na string que queremos adicionar na árvore. Caso não exista match entre essa string e o vértice que estamos comparando, essa função vai retornar a posição inicial da string de interesse */ int checkPartialMatch(int suffix_init, int suffix_end, int vertex_init, int vertex_end, vector<char> &genomas); #endif
true
c6a003386b94f4a5b4fbc27aae7742b0cb986ef3
C++
mattberkem/Robot_Contest
/include/UserInterface.h
UTF-8
1,324
2.65625
3
[]
no_license
#ifndef USER_INTERFACE_H #define USER_INTERFACE_H #include "Vector.h" #include "HardwareSimulator.h" // GHOST type was added to allow for erasing the robots enum RobotType { PURSUING = 0, EVADING = 1, GHOST }; class UserInterface { public: UserInterface( HardwareSimulator & ); ~UserInterface(); void printGraphics(); void printStatus(); void printMenu(); char processUserResponse(); int getPursuerNumber(); int getEvaderNumber(); void setPursuerNumber( int ); void setEvaderNumber( int ); private: HardwareSimulator & theHardwareSimulator; void getRobotStates(); void writeFieldBorder(); void writeRobotFromState( RobotType ); void writeRobotFromIndex( short, short, RobotType ); void eraseRobots(); void setPursuingRobotState(); void setEvadingRobotState(); Vector getUserStateInput(); void incrementSimulationTime(); void resetSimulation(); bool userStateInputBad( double, int ); // double nearestInteger( double ); void displayProcessorState(); void changePlayers(); void showCurrentPlayers(); void showListOfPlayers(); char screenBuffer[ 18 ][ 63 ]; short lastRobotLocations[ 2 ][ 2 ]; Vector pursuingRobotState; Vector evadingRobotState; bool firstCollisionNotOccurred; int pursuerNumber; int evaderNumber; }; #endif // USER_INTERFACE_H
true
2ad090527251d5938f38d0bf0fb7ca4b171a954e
C++
bbanerjee/VaangoUI
/Prototype/src/Utils/UtilsGoBag.h
UTF-8
828
2.671875
3
[]
no_license
#ifndef __VAANGO_UI_UTILS_GOBAG_H__ #define __VAANGO_UI_UTILS_GOBAG_H__ #include <Core/Point.h> #include <Utils/nanoflann.hpp> #include <memory> namespace VaangoUI { /* linspace function */ template <typename T, std::enable_if_t<std::is_arithmetic_v<T>, bool> = true> std::vector<T> linspace(T start, T end, int num) { std::vector<T> linspaced; if (num > 0) { double delta = static_cast<double>(end - start) / static_cast<double>(num); for (int i = 0; i < num + 1; ++i) { double val = start + delta * static_cast<double>(i); if (std::is_integral_v<T>) { linspaced.push_back(static_cast<T>(std::round(val))); } else { linspaced.push_back(static_cast<T>(val)); } } } return linspaced; } } // end namespace VaangoUI #endif // __VAANGO_UI_UTILS_GOBAG_H__
true
d3ef2292885e200d5a1c04f1c6d1b0aca8210d7f
C++
SunNEET/LeetCode
/E22_E27/535. Encode and Decode TinyURL.cpp
UTF-8
1,194
2.828125
3
[]
no_license
class Solution { // 用map分別做url->code跟code->url的hash // code就是隨便挑6個字母數字組合起來, 然後去對應當前的url public: // Encodes a URL to a shortened URL. string encode(string longUrl) { string code; if (!url_code.count(longUrl)) { for (int i = 0; i < 6; i++) code.push_back(charset[rd() % charset.size()]); url_code.insert(pair<string, string>(longUrl, code)); code_url.insert(pair<string, string>(code, longUrl)); } else code = url_code[longUrl]; return "http://tinyurl.com/" + code; } // Decodes a shortened URL to its original URL. string decode(string shortUrl) { if (shortUrl.size() != 25 || !code_url.count(shortUrl.substr(19, 6))) return ""; return code_url[shortUrl.substr(19,6)]; } private: const string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; unordered_map<string, string> url_code, code_url; random_device rd; }; // Your Solution object will be instantiated and called as such: // Solution solution; // solution.decode(solution.encode(url));
true
79eb5fc52ed892f33fb0b8000f367501d6d1b887
C++
bujosa/entertainment-in-c-plus-2018
/Simple aplication/ConsoleApplication1.cpp
UTF-8
2,303
3.046875
3
[]
no_license
// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> using namespace std; void Pago(int&TOTAL, double&Cargo); int main() { int TOTAL = 0; double Cargo = 0.01; char data = 'a'; int Combo1 = 350, Combo2 = 450, Combo3 = 400, Combo4 = 500, Combo5 = 300; int Combo6 = 50, Combo7 = 75, Combo8 = 100; while (data != 'S') { std::system("cls"); std::cout << "\t Restaurante La Seccion 01\n\n"; std::cout << "\t\t 1. Combo del Dia - $350\n"; std::cout << "\t\t 2. Especial del Chef - $450\n"; std::cout << "\t\t 3. Especial de Pasta - $400\n"; std::cout << "\t\t 4. Parrilla - $500\n"; std::cout << "\t\t 5. Ensalada Mixta - $300\n\n"; std::cout << "\t\t -- Bebidas -- \n\n"; std::cout << "\t\t 6. Refrescos - $50\n"; std::cout << "\t\t 7. Agua - $75\n"; std::cout << "\t\t 8. Poste - $100\n"; std::cout << "\n\n\tEliga una de las opciones (1-8) del Restaurante | P para Pagar | S para salir: "; std::cin >> data; if (data == 's') { data = 'S'; } switch (data) { case '1': TOTAL = TOTAL + Combo1; break; case '2': TOTAL += Combo2; break; case '3': TOTAL += Combo3; break; case '4': TOTAL += Combo4; break; case '5': TOTAL += Combo5; break; case '6': TOTAL += Combo6; break; case '7': TOTAL += Combo7; break; case '8': TOTAL += Combo8; break; case 'S': case 's': break; case 'P': case 'p': Pago(TOTAL, Cargo); TOTAL = 0; break; default: break; } } std::system("CLS"); std::cout << "Hasta Luego (:\n"; } void Pago(int& TOTAL, double&Cargo) { system("cls"); int TMP = TOTAL; double Impuesto = 0.18; int Cargo2 = 10; int contador = 0; int Monto = 100; while (TMP >= 100) { contador++; TMP -= 100; } Cargo2 *= contador; double NewTotal = TOTAL * Cargo + TOTAL * Impuesto + Cargo2 + TOTAL; std::cout << "\n\t Restaurante La Seccion 01\n\n"; std::cout << "\n\t Monto del pedido: " << TOTAL << std::endl; std::cout << "\n\t Impuesto de Ley: " << TOTAL * Impuesto << std::endl; std::cout << "\n\t Cargo Por Servicio: " << TOTAL * Cargo + Cargo2 << std::endl; std::cout << "\n\t Total a pagar: " << NewTotal << std::endl << std::endl; std::system("Pause"); }
true
38a359ebb08e1854b696019077b60783776b6197
C++
ZainArif/Data-algorithm-and-analysis-programs
/linear search.cpp
UTF-8
309
2.6875
3
[]
no_license
#include<stdio.h> #include<conio.h> int main() { int a[5]={2,6,5,8,1},n,i,j=4,p=1; printf("Enter Number to be search\n"); scanf("%d",&n); for(i=0;i<=j;i++) { if(n==a[i]) { p=i+1; printf("Number %d found at Position %d",n,p); break; } } if(n!=a[i]) printf("Number not found"); }
true
ea42966d9953f874bedc6ffd356e739140f13475
C++
tomerpq/All-Projects-Of-Tomer-Paz
/C++ Projects/Interpreter for Flight Simulator new programming language - C++ Project/src/openServerCommand.h
UTF-8
1,043
2.578125
3
[]
no_license
#include <thread> #include <chrono> #include <mutex> #include <netdb.h> #include <unistd.h> #include <netinet/in.h> #include <string.h> #include <sys/socket.h> #include "Command.h" #include "DataReaderServer.h" #ifndef FIRST_STEP_OPENSERVERCOMMAND_H #define FIRST_STEP_OPENSERVERCOMMAND_H /** For command Open Data Server we call to this class **/ /** The server opener will receive a pointer to both parser map : map symbol table which contains variables names * and their value. * Map varAddresses which contains variables names and their "bind" addresses in the simulator**/ class openServerCommand : public Command { std::map<std::string, double> *symbolTable; std::map<std::string,std::string> *varAddresses; DataReaderServer* data; public: openServerCommand(std::map<std::string, double> *symbolTable, std::map<std::string,std::string> *varAddresses); virtual int execute(std::string order[], int index); virtual ~openServerCommand(){ delete data; } }; #endif //FIRST_STEP_OPENSERVERCOMMAND_H
true
748c2dbe7ae100b1c4c7bdc7d2c5e03a51c37f52
C++
kit-cpp-course/gerus-aa
/Checkers/project/State.h
UTF-8
2,146
3.0625
3
[]
no_license
// // Expressing board state and current player. // #ifndef CHECKERS_STATE_H #define CHECKERS_STATE_H #include <vector> #include "Turn.h" #include "Coord.h" class Turn; class State { public: const static int boardSize = 8; const static int idIndex = boardSize * boardSize; const static int dataLength = idIndex + 1 + 1; State(); ~State() {} void buildListValidTurns(); void print() const; bool checkMatchingValidTurn(Turn *turn) const; void move(Turn *turn); void setNextPlayer(); void setInvalidTurn(); char getPlayer() const; int getWinnerCode() const; char* data() { return data_; } private: const static int manKingDiff = 'a' - 'A'; const static char legalSpace = '.'; const static char illegalSpace = ' '; const static char validPlayerO = 'o'; const static char validPlayerX = 'x'; const static char invalidPlayerO = 'p'; const static char invalidPlayerX = 'y'; const static char winningPlayerO = 'O'; const static char winningPlayerX = 'X'; void checkValidTurns(Coord *coord); bool checkValidJumpTurns( Coord *pre_coord, Coord *new_coord, std::vector<Coord *> coords, bool king); void checkValidMoveTurns(Coord *coord); void addValidJumpTurn(const std::vector<Coord *> coords); void addValidMoveTurn(Coord *pre_coord, Coord *new_coord); bool isValidCoord(const Coord *coord) const; bool isOwnPiece(const Coord *coord) const; bool isOpponentPiece(const Coord *coord) const; bool isLegal(const Coord *coord) const; bool isKing(const Coord *coord) const; bool isValidDirection(Coord *pre_coord, Coord *new_coord) const; bool isMoveable(Coord *pre_coord, Coord *new_coord) const; bool isJumpable(Coord *pre_coord, Coord *new_coord, bool king) const; char getOpponent() const; void setPlayer(const char player); void setPiece(const Coord *coord, const char piece); char getPiece(const Coord *coord) const; char data_[dataLength]; std::vector<Turn*> validTurns; bool forcedCapture; int oCount; int xCount; }; #endif //CHECKERS_STATE_H
true
b6871067ef3f752f947d0958598e83552fa446a1
C++
IEclipseI/ITMO_labs
/Algorithms_and_data_structures/lab_graph_1/H/main.cpp
UTF-8
1,708
2.59375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <set> #include <unordered_set> #include <fstream> #include <list> template<typename T> using vec = std::vector<T>; using ui = uint32_t; using uill = uint64_t; using namespace std; void dfs_check(ui v, vec<vec<ui>> &gr, vec<bool> &visited, int dist) { visited[v] = true; for (size_t i = 0; i < gr[v].size(); i++) { if (!visited[i] && gr[v][i] <= dist) { dfs_check(i, gr, visited, dist); } } } void dfs_check_back(ui v, vec<vec<ui>> &gr, vec<bool> &visited, int dist) { visited[v] = true; for (size_t i = 0; i < gr[v].size(); i++) { if (!visited[i] && gr[i][v] <= dist) { dfs_check_back(i, gr, visited, dist); } } } bool is_connected_by_dist(vec<vec<ui>> &gr, int dist) { vec<bool> a(gr.size(), false); dfs_check(0, gr, a, dist); for (bool v : a) { if (!v) return false; } vec<bool> b(gr.size(), false); dfs_check_back(0, gr, b, dist); for (bool v : b) { if (!v) return false; } return true; } int main() { std::ios_base::sync_with_stdio(false); ifstream fin("avia.in"); ofstream fout("avia.out"); cin.tie(nullptr); ui n; cin >> n; vec<vec<ui>> gr(n, vec<ui>(n)); for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) { cin >> gr[i][j]; } } vec<bool> a(n, false); int lb = -1; int ub = 1000000000; while (lb < ub - 1) { if (is_connected_by_dist(gr, (ub + lb) / 2)) ub = (ub + lb) / 2; else lb = (ub + lb) / 2; } cout << ub << '\n'; fout.close(); return 0; }
true
7b6ac614711d90147edcfeb86cbea0499a3d8615
C++
Spritutu/hiquotion_cpp
/FoundationLib/BarCodeLib/Code39.cpp
GB18030
1,941
2.59375
3
[]
no_license
// Code39.cpp: implementation of the CCode39 class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Code39.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CCode39::CCode39() { } CCode39::~CCode39() { } int CCode39::Code39Verify(LPCSTR text) { if(text[0]=='\0') return -1; while(*text&&((*text>='A'&&*text<='z')|| (*text>='0'&&*text<='9')|| (*text=='-')|| (*text=='.')|| (*text=='$')|| (*text==' ')|| (*text=='/')|| (*text=='+')|| (*text=='%')|| (*text=='*'))) text++; if(*text) return -1; return 0;//OK } int CCode39::Code39Encode(LPSTR text, LPSTR partial) { unsigned i; //char *str=text; if(!partial) { return -1; } //ַΪ* strcpy(partial,code39set[43]); strcat(partial,"2"); //ַΪգ򷵻 if(!(*text)) { delete partial; return -1; } unsigned kk; kk=strlen(text); for(i=0;i<kk;i++) { if(*text>='A'&&*text<='z') strcat(partial,code39set[*text-'A'+10]); else if(*text>='0'&&*text<='9') strcat(partial,code39set[*text-'0']); else if(*text=='-') strcat(partial,code39set[36]); else if(*text=='.') strcat(partial,code39set[37]); else if(*text==' ') strcat(partial,code39set[38]); else if(*text=='$') strcat(partial,code39set[39]); else if(*text=='/') strcat(partial,code39set[40]); else if(*text=='+') strcat(partial,code39set[41]); else if(*text=='%') strcat(partial,code39set[42]); else if(*text=='*') strcat(partial,code39set[43]); else { delete partial; return -1; } text++; //ÿַ֮һ strcat(partial,"2"); } //Ϊ* strcat(partial,code39set[43]); return 0; }
true
448e2c5eb99e681b8d682e6eed788106030e5764
C++
MatheusDantas19/Aed-1
/AED ARQUIVO/aula.cpp
UTF-8
803
2.84375
3
[]
no_license
//lendo gravando strings #include <iostream> #include <fstream> using namespace std; typedef struct agenda{ int idade; char nome[50]; char endereco[120]; double salario; }pessoa; //ios::app gravar no final do arquivo int main(){ ofstream arqout("aqrstruct.dat",ios::binary|ios::app); //ofstream arqout("aqrstruct.dat",ios::binary|ios::app); pessoa aux; int n,i; cout<<"Digite a qtd de pessoas: "; cin>>n; for (int i = 0; i < n; i++){ cin.ignore(); cout<<"Digite o nome: "; cin.getline(aux.nome,50); cout<<"Digite o endereco: "; cin.getline(aux.endereco,50); cout<<"Digite a idade: "; cin>>aux.idade; cout<<"Digite o salario: "; cin>>aux.salario; arqout.write((char*)&aux,sizeof(pessoa)); cout<<"\n"; } //cout<<"Tamanho da struct: "; //cout<<sizeof(pessoa)<<endl; }
true
38429b7c44bbfe33e3acf171153358a2f5106251
C++
rnikhori/Daily_code
/sortfun.cpp
UTF-8
600
2.734375
3
[]
no_license
#include<iostream> #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; int A[n]; int even[n]={0}; int odd[n]={0}; int p=0,q=0; for (int i = 0; i < n; i++) { cin>>A[i]; } for (int i = 0; i < n; i++) { if(A[i]%2==0) even[p++]=A[i]; else odd[q++]=A[i]; } sort(odd,odd+n,greater<int>()); sort(even,even+n); for(int i=0;i<n;i++) { A[i]=odd[i]+even[i]; cout<<A[i]<<" "; } cout<<endl; return 0; }
true
bc790113f66f78455f12436c641edf8ee4a1025d
C++
nvictoria987/project1
/pricelist.cpp
UTF-8
1,993
3.40625
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include <stdexcept> #include "PriceList.h" #include "PriceListItem.h" using namespace std; PriceList::PriceList() { PLI = new PriceListItem[1000000]; size = 0; } // Load information from a text file with the given filename. void PriceList::createPriceListFromDatafile(string filename) { ifstream myfile(filename); if (myfile.is_open()) { cout << "Successfully opened file " << filename << endl; string name; string code; double price; bool taxable; while (myfile >> name >> code >> price >> taxable) { // cout << code << " " << taxable << endl; addEntry(name, code, price, taxable); } myfile.close(); } else throw invalid_argument("Could not open file " + filename); } // return true only if the code is valid just checks if the barcode exsists, so it needs to check if its in the price list bool PriceList::isValid(string code) const { for (size_t i = 0; i < code.size(); i++) { if (!isdigit(code[i])) return false; } if (code == "No_Code") return false; else return true; } // return price, item name, taxable? as an ItemPrice object; throw exception if code is not found PriceListItem PriceList::getItem(string code) const { for (int i = 0; i <= size; i++) { if (PLI[i].getCode() == code) return PLI[i]; } throw invalid_argument("\nNo Matching barcode found!\n"); } // add to the price list information about a new item void PriceList::addEntry(string itemName, string code, double price, bool taxable) { PLI[size].addAll(itemName, code, price, taxable); size++; } PriceList& PriceList::operator=(const PriceList& PL) { delete[] PLI; PLI = new PriceListItem[1000000]; size = PL.size; for (int i = 0; 0 < size; i++) { PLI[i] = PL.PLI[i]; } return PL; // I havee no idea why this isnt working this is the only error i know about } PriceList::~PriceList() { delete[] PLI; PLI = NULL; }
true
959d9f9aa452db3178f96c9c94636c7ce94c1697
C++
kiso-x/Rain
/rain.h
UTF-8
2,441
2.875
3
[]
no_license
/** * \file rain.h * \class Rain * * \brief Read a wave file and play it back in a granular style, with modification through OSC. * * \author Henrik von Coler modified by Marquis Fields and Malte Schneider * * \date 2019/10/04 * */ #include<stdio.h> #include<string.h> #include<stdlib.h> #include<unistd.h> #include<jack/jack.h> #include "oscman.h" #include "grainplayer.h" #include "Biquad.h" using std::cout; using std::endl; class Rain{ private: /// /// \brief /// creates an GrainPlayer array with all necessary parameters GrainPlayer *grainer[2]; /// /// \brief /// filter is a lowpass filter with variable cutoff frequency Biquad *filter; /// /// \brief /// sample rate of the jack server int fs = 0; /// /// \brief /// gain of bit crushed output double crush_gain = 0; /// /// \brief /// number off jack output ports int nOutputs = 2; /// /// \brief /// number of channels in the sample int nChannels; /// /// \brief /// cutoff represents the cutoff frequency of the lowpass fitler double cutoff; /// /// \brief /// determines bit depth of bitcrushing int bit; /// /// \brief /// the jack output ports const char **ports; /// /// \brief pointer to Jack client jack_client_t *client; /// /// \brief Jack status jack_status_t status; /// /// \brief pointer to Jack audio output port jack_port_t **output_port; /// /// \brief pointer to OSC manager object OscMan *oscman; /// /// \brief get the next buffer from the sample and playback /// \param nframes buffer size /// \return output of rain int process(jack_nframes_t nframes); /// /// \brief reduce bit depth of input sample /// \param sample current sample to be crushed /// \return bitcrushed input sample double crush(double sample); /// /// \brief sets gain of bitcrushed signale in dependence of filter cutoff frequency /// \param fc filter cutoff frequency void set_gain(double fc); /// /// \brief /// \param x /// \param object static int callback_process(jack_nframes_t x, void* object); public: /// /// \brief Constructor /// \param filename path to wav file /// \param win_size window size of triangular window Rain(std::string filename, int win_size); };
true
1190cc7e1b8e29c8ae466a1f9042a40d8c1b11d3
C++
duythanhphan/rtf-parser
/example.cpp
UTF-8
211
2.640625
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main(){ string line; ifstream file("borat"); while(!file.eof()){ getline(file, line, '\n'); cout << line << endl; } return 0; }
true
5e028cc8a630b98cac9f5db3d3d7a6a69d8abd57
C++
ianbarreto22/lp1
/aula13/include/conta.hpp
UTF-8
279
2.671875
3
[]
no_license
#ifndef CONTA_HPP #define CONTA_HPP #include <string> using namespace std; class Conta { public: int numero; string titular; double saldo; void saca(double valor); void deposita(double valor); void transferencia(double valor, Conta &c); }; #endif
true
44727a630b5bc21dad0c56641dca40cbd59145ea
C++
Girl-Code-It/Beginner-CPP-Submissions
/Milijolly/Milestone 17a/CapitalLetter.cpp
UTF-8
387
3.53125
4
[]
no_license
// to find the first capital letter in a string using recursion #include <bits/stdc++.h> using namespace std; char capital(char stng[30], int ctr) { if(isupper(stng[ctr])) return stng[ctr]; return capital(stng,ctr+1); } int main() { char str1[30]; cin>>str1; cout<<capital(str1,0)<<" is the first capital letter"; //cout<<"Copied String "<<endl; //cout<<str2; }
true
a371299a17125c26ba5becc23a25ad20c7e6bed7
C++
cpvrlab/SLProject
/modules/utils/source/FtpUtils.cpp
UTF-8
18,850
2.78125
3
[]
no_license
//############################################################################# // File: FtpUtils.cpp // Authors: Marcus Hudritsch, Michael Goettlicher // Date: May 2019 // Codestyle: https://github.com/cpvrlab/SLProject/wiki/SLProject-Coding-Style // License: This software is provided under the GNU General Public License // Please visit: http://opensource.org/licenses/GPL-3.0 //############################################################################# #include <sstream> #include <algorithm> #include <ftplib.h> #include <FtpUtils.h> #include <Utils.h> using namespace std; namespace FtpUtils { //----------------------------------------------------------------------------- //! Uploads the file to the ftp server. checks if the filename already exists and adds a version number /*! * * @param fileDir * @param fileName * @param ftpHost * @param ftpUser * @param ftpPwd * @param ftpDir * @param errorMsg * @return */ bool uploadFileLatestVersion(const string& fileDir, const string& fileName, const string& ftpHost, const string& ftpUser, const string& ftpPwd, const string& ftpDir, string& errorMsg) { string fullPathAndFilename = fileDir + fileName; if (!Utils::fileExists(fullPathAndFilename)) { errorMsg = "File doesn't exist: " + fullPathAndFilename; return false; } bool success = true; ftplib ftp; // enable active mode ftp.SetConnmode(ftplib::connmode::port); if (ftp.Connect(ftpHost.c_str())) { if (ftp.Login(ftpUser.c_str(), ftpPwd.c_str())) { if (ftp.Chdir(ftpDir.c_str())) { // Get the latest fileName on the ftp string latestFile = getLatestFilename(ftp, fileDir, fileName); // Set the file version int versionNO = 0; if (!latestFile.empty()) { versionNO = getVersionInFilename(latestFile); } // Increase the version versionNO++; stringstream versionSS; versionSS << "(" << versionNO << ")"; // Build new fileName on ftp with version number string fileWOExt = Utils::getFileNameWOExt(fullPathAndFilename); string newVersionFilename = fileWOExt + versionSS.str() + ".xml"; // Upload if (!ftp.Put(fullPathAndFilename.c_str(), newVersionFilename.c_str(), ftplib::transfermode::image)) { errorMsg = "*** ERROR: ftp.Put failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Chdir failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Login failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Connect failed. ***\n"; success = false; } ftp.Quit(); return success; } //----------------------------------------------------------------------------- //! Download the file from the ftp server which has the latest version and store it as fileName locally /*! * * @param fileDir * @param fileName * @param ftpHost * @param ftpUser * @param ftpPwd * @param ftpDir * @param errorMsg * @return */ bool downloadFileLatestVersion(const string& fileDir, const string& fileName, const string& ftpHost, const string& ftpUser, const string& ftpPwd, const string& ftpDir, string& errorMsg) { bool success = true; ftplib ftp; // enable active mode ftp.SetConnmode(ftplib::connmode::port); if (ftp.Connect(ftpHost.c_str())) { if (ftp.Login(ftpUser.c_str(), ftpPwd.c_str())) { if (ftp.Chdir(ftpDir.c_str())) { // Get the latest fileName on the ftp string fullPathAndFilename = fileDir + fileName; string latestFile = getLatestFilename(ftp, fileDir, fileName); int remoteSize = 0; ftp.Size(latestFile.c_str(), &remoteSize, ftplib::transfermode::image); if (remoteSize > 0) { if (!ftp.Get(fullPathAndFilename.c_str(), latestFile.c_str(), ftplib::transfermode::image)) { errorMsg = "*** ERROR: ftp.Get failed. ***\n"; success = false; } } else { errorMsg = "*** No file to download ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Chdir failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Login failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Connect failed. ***\n"; success = false; } ftp.Quit(); return success; } //----------------------------------------------------------------------------- //! Uploads file to the ftp server /*! * * @param fileDir * @param fileName * @param ftpHost * @param ftpUser * @param ftpPwd * @param ftpDir * @param errorMsg * @return */ bool uploadFile(const string& fileDir, const string& fileName, const string& ftpHost, const string& ftpUser, const string& ftpPwd, const string& ftpDir, string& errorMsg) { string fullPathAndFilename = fileDir + fileName; if (!Utils::fileExists(fullPathAndFilename)) { errorMsg = "File doesn't exist: " + fullPathAndFilename; return false; } bool success = true; ftplib ftp; // enable active mode ftp.SetConnmode(ftplib::connmode::port); if (ftp.Connect(ftpHost.c_str())) { if (ftp.Login(ftpUser.c_str(), ftpPwd.c_str())) { if (ftp.Chdir(ftpDir.c_str())) { // Upload if (!ftp.Put(fullPathAndFilename.c_str(), fileName.c_str(), ftplib::transfermode::image)) { errorMsg = "*** ERROR: ftp.Put failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Chdir failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Login failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Connect failed. ***\n"; success = false; } ftp.Quit(); return success; } //----------------------------------------------------------------------------- //! Download file from the ftp server /*! * * @param fileDir * @param fileName * @param ftpHost * @param ftpUser * @param ftpPwd * @param ftpDir * @param errorMsg * @return */ bool downloadFile(const string& fileDir, const string& fileName, const string& ftpHost, const string& ftpUser, const string& ftpPwd, const string& ftpDir, string& errorMsg) { bool success = true; ftplib ftp; // enable active mode ftp.SetConnmode(ftplib::connmode::port); if (ftp.Connect(ftpHost.c_str())) { if (ftp.Login(ftpUser.c_str(), ftpPwd.c_str())) { if (ftp.Chdir(ftpDir.c_str())) { // Get the latest fileName on the ftp string fullPathAndFilename = fileDir + fileName; int remoteSize = 0; ftp.Size(fileName.c_str(), &remoteSize, ftplib::transfermode::image); if (remoteSize > 0) { if (!ftp.Get(fullPathAndFilename.c_str(), fileName.c_str(), ftplib::transfermode::image)) { errorMsg = "*** ERROR: ftp.Get failed. ***\n"; success = false; } } else { errorMsg = "*** No file to download ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Chdir failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Login failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Connect failed. ***\n"; success = false; } ftp.Quit(); return success; } //----------------------------------------------------------------------------- /*! * * @param fileDir * @param ftpHost * @param ftpUser * @param ftpPwd * @param ftpDir * @param searchFileTag * @param errorMsg * @return */ bool downloadAllFilesFromDir(const string& fileDir, const string& ftpHost, const string& ftpUser, const string& ftpPwd, const string& ftpDir, const string& searchFileTag, string& errorMsg) { bool success = true; ftplib ftp; // enable active mode ftp.SetConnmode(ftplib::connmode::port); if (ftp.Connect(ftpHost.c_str())) { if (ftp.Login(ftpUser.c_str(), ftpPwd.c_str())) { if (ftp.Chdir(ftpDir.c_str())) { // get all names in directory vector<string> retrievedFileNames; if ((success = getAllFileNamesWithTag(ftp, fileDir, searchFileTag, retrievedFileNames, errorMsg))) { for (auto& retrievedFileName : retrievedFileNames) { int remoteSize = 0; ftp.Size(retrievedFileName.c_str(), &remoteSize, ftplib::transfermode::image); if (remoteSize > 0) { string targetFilename = fileDir + retrievedFileName; if (!ftp.Get(targetFilename.c_str(), retrievedFileName.c_str(), ftplib::transfermode::image)) { errorMsg = "*** ERROR: ftp.Get failed. ***\n"; success = false; } } } } } else { errorMsg = "*** ERROR: ftp.Chdir failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Login failed. ***\n"; success = false; } } else { errorMsg = "*** ERROR: ftp.Connect failed. ***\n"; success = false; } ftp.Quit(); return success; } //----------------------------------------------------------------------------- //! Get a list of all filenames with given search file tag in remote directory /*! * * @param ftp * @param localDir * @param searchFileTag * @param retrievedFileNames * @param errorMsg * @return */ bool getAllFileNamesWithTag(ftplib& ftp, const string& localDir, const string& searchFileTag, vector<string>& retrievedFileNames, string& errorMsg) { bool success = true; string ftpDirResult = localDir + "ftpDirResult.txt"; string searchDirAndFileType = "*." + searchFileTag; // Get result of ftp.Dir into the text file ftpDirResult if (ftp.Dir(ftpDirResult.c_str(), searchDirAndFileType.c_str())) { // analyse ftpDirResult content vector<string> vecFilesInDir; vector<string> strippedFiles; if (Utils::getFileContent(ftpDirResult, vecFilesInDir)) { for (string& fileInfoLine : vecFilesInDir) { vector<string> splits; Utils::splitString(fileInfoLine, ' ', splits); // we have to remove the first 8 strings with first 8 "holes" of unknown length from info line int numOfFoundNonEmpty = 0; bool found = false; int pos = 0; while (pos < splits.size()) { if (!splits[pos].empty()) numOfFoundNonEmpty++; if (numOfFoundNonEmpty == 8) { found = true; break; } pos++; } // remove next string that we assume to be empty (before interesting part) pos++; // we need minumum 9 splits (compare content of ftpDirResult.txt). The splits after the 8th we combine to one string again if (found && pos < splits.size()) { std::string name; std::string space(" "); for (int i = pos; i < splits.size(); ++i) { name.append(splits[i]); if (i != splits.size() - 1) name.append(space); } if (name.size()) retrievedFileNames.push_back(name); } else { // if more than two splits double point is not unique and we get an undefined result errorMsg = "*** ERROR: getAllFileNamesWithTag: Unexpected result: Ftp info line was not formatted as expected. ***\n"; success = false; } } } } else { if (!Utils::dirExists(localDir)) { errorMsg = "*** ERROR: getAllFileNamesWithTag: directory " + localDir + "does not exist. ***\n"; } else { errorMsg = "*** ERROR: getAllFileNamesWithTag failed. ***\n"; } success = false; } return success; } //----------------------------------------------------------------------------- //! Returns the latest fileName of the same fullPathAndFilename /*! * * @param ftp * @param fileDir * @param fileName * @return */ string getLatestFilename(ftplib& ftp, const string& fileDir, const string& fileName) { // Get a list of files string fullPathAndFilename = fileDir + fileName; string ftpDirResult = fileDir + "ftpDirResult.txt"; string filenameWOExt = Utils::getFileNameWOExt(fullPathAndFilename); string filenameWOExtStar = filenameWOExt + "*"; // Get result of ftp.Dir into the textfile ftpDirResult if (ftp.Dir(ftpDirResult.c_str(), filenameWOExtStar.c_str())) { vector<string> vecFilesInDir; vector<string> strippedFiles; if (Utils::getFileContent(ftpDirResult, vecFilesInDir)) { for (string& fileInfoLine : vecFilesInDir) { size_t foundAt = fileInfoLine.find(filenameWOExt); if (foundAt != string::npos) { string fileWExt = fileInfoLine.substr(foundAt); string fileWOExt = Utils::getFileNameWOExt(fileWExt); strippedFiles.push_back(fileWOExt); } } } if (!strippedFiles.empty()) { // sort fileName naturally as many file systems do. sort(strippedFiles.begin(), strippedFiles.end(), Utils::compareNatural); string latest = strippedFiles.back() + ".xml"; return latest; } else return ""; } // Return empty for not found return ""; } //----------------------------------------------------------------------------- //! Returns the version number at the end of the fileName /*! * * @param filename Filename on ftp server with an ending *(#).ext * @return Returns the number in the brackets at the end of the filename */ int getVersionInFilename(const string& filename) { string filenameWOExt = Utils::getFileNameWOExt(filename); int versionNO = 0; if (!filenameWOExt.empty()) { size_t len = filenameWOExt.length(); if (filenameWOExt.at(len - 1) == ')') { size_t leftPos = filenameWOExt.rfind('('); string verStr = filenameWOExt.substr(leftPos + 1, len - leftPos - 2); versionNO = stoi(verStr); } } return versionNO; } //----------------------------------------------------------------------------- // off64_t ftpUploadSizeMax = 0; //----------------------------------------------------------------------------- //! Calibration Upload callback for progress feedback // int ftpCallbackUpload(off64_t xfered, void* arg) //{ // if (ftpUploadSizeMax) // { // int xferedPC = (int)((float)xfered / (float)ftpUploadSizeMax * 100.0f); // cout << "Bytes saved: " << xfered << " (" << xferedPC << ")" << endl; // } // else // { // cout << "Bytes saved: " << xfered << endl; // } // return xfered ? 1 : 0; // } };
true
138f0e32fa08874cbf6183942416802891d21122
C++
IsaiahA21/LinkedList
/OLList.cpp
UTF-8
2,585
3.390625
3
[]
no_license
// OLList.cpp #include <iostream> #include <stdlib.h> using namespace std; #include "OLList.h" OLList::OLList() : headM(0) { } OLList::OLList(const OLList& source) { copy(source); } OLList& OLList::operator =(const OLList& rhs) { if (this != &rhs) { destroy(); copy(rhs); } return *this; } OLList::~OLList() { destroy(); } void OLList::print() const { cout << '['; if (headM != 0) { cout << ' ' << headM->item; for (const Node *p = headM->next; p != 0; p = p->next) cout << ", " << p->item; } cout << " ]\n"; } void OLList::insert(const ListItem& itemA) { Node *new_node = new Node; new_node->item = itemA; if (headM == 0 || itemA <= headM->item ) { new_node->next = headM; headM = new_node; } else { Node *before = headM; // will point to node in front of new node Node *after = headM->next; // will be 0 or point to node after new node while(after != 0 && itemA > after->item) { before = after; after = after->next; } new_node->next = after; before->next = new_node; } } void OLList::remove(const ListItem& itemA) { // if list is empty, do nothing if (headM == 0 || itemA < headM->item) return; Node *doomed_node = 0; // if the eleemnt to be removed is the first element if (itemA == headM->item) { doomed_node = headM; headM = headM->next; delete doomed_node; return; } else { Node *before = headM; Node *maybe_doomed = headM->next; while(maybe_doomed != 0 && itemA != maybe_doomed->item) { before = maybe_doomed; maybe_doomed = maybe_doomed->next; } if (maybe_doomed->item == itemA) { // move before next to the next node pass the doomed node before->next = maybe_doomed->next; // now delete where maybe_doomed points delete maybe_doomed; } } } void OLList::destroy(){ Node *to_be_delete = headM; Node *forward = new Node; while (headM != nullptr) { forward = to_be_delete->next; delete to_be_delete; headM = forward; to_be_delete = headM; } //default line headM =0; } void OLList::copy(const OLList& source){ Node *temp = source.headM; Node *current = new Node; headM = current; while (1) { current->item = temp->item; if (temp->next == nullptr) { break; } current->next = new Node; current = current->next; temp = temp->next; } current->next = nullptr; }
true
a5fb2524cc01b2221862ebcb19fca54440b8ca76
C++
Chris-Dodds-s6086643/GPP
/S6086643_CDodds_GPP_Server/S6086643_CDodds_GPP_Server/ThreadSafeQueue.h
UTF-8
908
3.6875
4
[]
no_license
#pragma once #include <queue> #include <mutex> #include <condition_variable> template <class T> class ThreadSafeQueue { private: std::queue<T> queue; mutable std::mutex mutex; std::condition_variable condition; public: ThreadSafeQueue() : queue(), mutex(), condition() {} ~ThreadSafeQueue() {} void push(T valueToPush) { std::lock_guard<std::mutex> lock(mutex); queue.push(valueToPush); condition.notify_one(); } void waitPop(T& poppedValue) { std::unique_lock<std::mutex> lock(mutex); while (queue.empty()) { condition.wait(lock); } poppedValue = std::move(queue.front); queue.pop(); } bool tryPop(T& value) { std::unique_lock<std::mutex> lock(mutex); if (queue.empty()) { return false; } value = std::move(queue.front()); queue.pop(); return true; } bool isEmpty() { std::unique_lock<std::mutex> lock(mutex); return queue.empty(); } };
true
cc1e4f9308fd0c7ca05c8594de068f22f2336d43
C++
woshixixi/myLeetCode
/035-SearchInsertPosition.cpp
UTF-8
884
3.53125
4
[]
no_license
/** * * 最初的想法:直接就是O(n) * 还可以用:二分法,O(logn) * 二分法要注意,low<=high 为截止条件,同时,每次low=mid+1,high=mid-1 * */ //O(n) class Solution { public: int searchInsert(vector<int>& nums, int target) { for(int i =0;i<nums.size();i++) { if(target<=nums[i]) return i; } return nums.size(); } }; //O(logn) class Solution { public: int searchInsert(vector<int>& nums, int target) { int low = 0,high = nums.size() - 1,mid; while(low <= high) { mid =(high + low)/2; if(nums[mid] == target) return mid; if(target > nums[mid]) { low = mid + 1; }else{ high = mid - 1; } } if(nums[mid] > target)return mid; else return mid + 1; } };
true
cbfd1552455deb90188b272feb4af7989b12e58e
C++
jrtomps/spectcl
/5.0dev/SpecTclPackage/CSpecTclHistogrammerFactory.cpp
UTF-8
10,025
2.875
3
[]
no_license
/* This software is Copyright by the Board of Trustees of Michigan State University (c) Copyright 2013. You may use this software under the terms of the GNU public license (GPL). The terms of this license are described at: http://www.gnu.org/licenses/gpl.txt Author: Ron Fox NSCL Michigan State University East Lansing, MI 48824-1321 */ #include "CSpecTclHistogrammerFactory.h" /** * @file CSpecTclHistogrammerFactory.cpp * @brief Implementation of the SpecTcl type histogrammer factory. */ #include "CSpecTclSpectrumAllocator.h" #include "CParameterDictionary.h" #include "CSpecTcl1dIncrementer.h" #include "CSpecTcl2dIncrementer.h" #include "CSpecTclSum1dIncrementer.h" #include <sstream> /** * create1dAllocator * * @return CSpectrumAllocator* - Pointer to what is actually a CSpecTclSpectrumAllocator */ CSpectrumAllocator* CSpecTclHistogrammerFactory::create1dAllocator() { return new CSpecTclSpectrumAllocator; } /** * create1dIncrementer * * Creates an incrementer for a normal 1d spectrum. * * @param xParmas - One element array containing the x parameter name to use. * @param yParams - 0 element array, unused. * * @return CSpectrumIncrementer* a dynamically allocated spectrum incrementer * @throw histogrammer_factory_exception if: * - There is not exactly 1 x parameter. * - There is not exactly 0 y parameters. * - The x parameter is nonexistent. * */ CSpectrumIncrementer* CSpecTclHistogrammerFactory::create1dIncrementer(std::vector<std::string> xParams, std::vector<std::string> yParams) { // Check that we have the right number of x/y params: checkExactParamCount(xParams, 1, "CSpecTclHistogrammerFactory::create1dIncrementer", "X parameter"); checkExactParamCount(yParams, 0, "CSpecTclHistogrammerFactory::create1dIncrementer", "Y parameters"); // Check that the X parameter is defined: checkParameterExists(xParams[0], "CSpecTclHistogrammerFactory::create1dIncrementer", "X parameter"); return new CSpecTcl1dIncrementer(xParams[0]); } /** * create2dIncrementer * Creates an incrementer for a standard 2d spectrum (an x and y parameter). * * @param xParams - Should be a 1 element array containing the X parameter. * @param yparams - Should be a 1 element array containing the Y parameter. * * @return CSpectrumIncrementer* - A dynamically allocated spectrum incrementer. * @throw histogrammer_factory_exception if: * - There is not exactly one X parameter. * - There is not exactly 1 Y parameter. * - Either the x or y parameter are not defined. */ CSpectrumIncrementer* CSpecTclHistogrammerFactory::create2dIncrementer(std::vector<std::string> xParams, std::vector<std::string> yParams) { // Check that we have the right number of x/y params: checkExactParamCount(xParams, 1, "CSpecTclHistogrammerFactory::create2dIncrementer", "X parameter"); checkExactParamCount(yParams, 1, "CSpecTclHistogrammerFactory::create2dIncrementer", "Y parameter"); // Validate existence of the parameters: checkParameterExists(xParams[0], "CSpecTclHistogrammerFactory::create2dIncrementer", "X parameter"); checkParameterExists(yParams[0], "CSpecTclHistogrammerFactory::create2dIncrementer", "Y parameter"); return new CSpecTcl2dIncrementer(xParams[0], yParams[0]); } /** * createSum1dIncrementer * * Create a summary spectrum incrementer. This takes an array of x parameters * and no Y parameters. The spectrum managed basically is a bunch of 1-d * spectra where the y axis for each channel is the spectrum for the corresponding * parameter, e.g. 0,y is the y'th channel of the spectrum xParams[0]... * * @param xParams - vector of at least one x parameter (really boring if only 1). * @param yParams - empty vector unused. * * @return CSpectrumIncrementer* - Pointer to a dynamically allocated spectrum incrementer. * @throw histogrammer_factory_exception if: * - There are no X parmaeters. * - There are Y parameters. * - Any X parameter does not exist. */ CSpectrumIncrementer* CSpecTclHistogrammerFactory::createSum1dIncrementer(std::vector<std::string> xParams, std::vector<std::string> yParams) { // Need at least 1 x parameter and 0 y: checkAtLeastParamCount(xParams, 1, "CSpecTclHistogrammerFactory::createSum1dIncrementer", "X parameter"); checkExactParamCount(yParams, 0, "CSpecTclHistogrammerFactory::createSum1dIncrementer", "Y parameters"); // The x parameters must exist. for (int i =0; i < xParams.size(); i++) { checkParameterExists(xParams[i], "CSpecTclHistogrammerFactory::createSum1dIncrementer", xParams[i]); } // Everything's going to work now: return new CSpecTclSum1dIncrementer(xParams); } /** * create2dComboIterator * * Creates an incrementer for what used to be called a 'gamma deluxe' spectrum. * This is a spectrum with independent x/y parameter sets that is incremented * for each valid pair of parameters. * * @param xParams - vector of names of parameters on the x axis. * @param yParams - vector of names of parameters on the y axis. * * @return CSpectrumIncrementer* - pointer to a dynamically allocatd spectrum incrementer. * @throw histogrammer_factory_exception if: * - There are no X parameters. * - There are no Y parameters. * - Any of the X parameters is not yet defined. * - Any of the Y parameters is not yet defined. */ CSpectrumIncrementer* CSpecTclHistogrammerFactory::create2dComboIncrementer(std::vector<std::string> xParams, std::vector<std::string> yParams) { checkAtLeastParamCount(xParams, 1, "CSpecTclHistogrammerFactory::create2dComboIncrementer", "X parameter"); checkAtLeastParamCount(yParams, 1, "CSpecTclHistogrammerFactory::create2dComboIncrementer", "Y parameter"); return 0; } /*-------------------------------------------------------------------------------- * Private utility methods: */ /** * checkExactParamCount * * Ensures that a vector of parameter names has exactly the required number * of elements: * * @param params - Vector of parameter names. * @param requiredCount - Number of parameter names that must be present. * @param method - Name of the method that wants to know (see exceptions below). * @param tail - Tail end of the exception string (see exceptions below). * * @throw histogrammer_factory_exception - if the condition is false. The string that defines the error * is put together as follows: * @method@ needs exactly @requiredCount@ @tail@ * Where @xxx@ means substitute the stringified version of the paramter named xxx */ void CSpecTclHistogrammerFactory::checkExactParamCount(std::vector<std::string> params, size_t requiredCount, std::string method, std::string tail) { if(params.size() != requiredCount) { std::stringstream msg; msg << method << " needs exactly " << requiredCount << " " << tail; throw histogrammer_factory_exception(msg.str().c_str()); } } /** * checkAtLeastParamCount * * Ensures a vector of parameters has at least the requested number of elements. * * @param params - Vector of parameter names. * @param requiredCount - Number of parameter names that must be present. * @param method - Name of the method that wants to know (see exceptions below). * @param tail - Tail end of the exception string (see exceptions below). * * @throw histogrammer_factory_exception - if the condition is false. The string that defines the error * is put together as follows: * @method@ needs at least @requiredCount@ @tail@ * Where @xxx@ means substitute the stringified version of the paramter named xxx */ void CSpecTclHistogrammerFactory::checkAtLeastParamCount(std::vector<std::string> params, size_t requiredCount, std::string method, std::string tail) { if(params.size() < requiredCount) { std::stringstream msg; msg << method << " needs at least " << requiredCount << " " << tail; throw histogrammer_factory_exception(msg.str().c_str()); }} /** * checkParameterExists * * If a named parameter has not yet been defined, throws a histogram_factory_exception * with a 'well formed' error message. See the exceptions specification. * * @param pName - The name of the parameter (p in this case is short for parameter not pointer * @param method - The method that wants to know, this is used in the exception string. * @param name - String that's used to describe what we'd like to see in the name part of the * exception string may or may not be the same as pName. * * @throw histogrammer_factor_exception - If the parameter does not exist. The exception * string is of the form: * "@method@ @name@ must exist" * where @xxx@ means subsitute the value of that parameter * in the string. * @note A use case for the name parameter being differnet than the name of the parameter is when * the caller wants to identify and axis rather than a parameter e.g.: * "CSpecTclHistogrammerFactory::create2dIncrementer X parameter does not exist" * where: * - @method@ is 'CSpecTclHistogrammerFactory::create2dIncrementer' * - @name@ is 'X parameter' */ void CSpecTclHistogrammerFactory::checkParameterExists(std::string pName, std::string method, std::string name) { CParameterDictionary* pDict = CParameterDictionary::instance(); CParameterDictionary::DictionaryIterator pParam = pDict->find(pName); if (pParam == pDict->end()) { std::string msg(method); method += " "; method += name; method += " does not exist"; throw histogrammer_factory_exception(method.c_str()); } }
true
1d17635ea5b5261159214fb4ff09ee94f8a85ca5
C++
sagar-adval/GFGIP
/Graphs/DetectCycleInADirectedGraph.cpp
UTF-8
1,296
2.890625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: int vis[100005], recVis[100005]; bool dfs(int node, int par, vector<int> g[]) { if(!vis[node]) { vis[node] = 1; recVis[node] = 1; } for(auto x:g[node]) { if(!vis[x]) { if(dfs(x, node, g)) return true; } else if(recVis[x]) return true; } recVis[node] = 0; return false; } bool isCyclic(int N, vector<int> adj[]) { memset(vis, 0, sizeof(vis)); memset(recVis, 0, sizeof(recVis)); for(int i= 0;i<N;i++) { if(!vis[i]) { bool isCyclic = dfs(i, -1, adj); if(isCyclic) return 1; } } return 0; } }; // { Driver Code Starts. int main() { int t; cin >> t; while(t--) { int n, m; cin >> n >> m; vector<int> adj[n]; for(int i = 0; i < m; i++) { int u, v; cin >> u >> v; adj[u].push_back(v); } Solution obj; cout << obj.isCyclic(n, adj) << "\n"; } return 0; } // } Driver Code Ends
true
6eb0e047ef5120a7840fddd5c114ad85ddc88b2d
C++
KDE/kdeplasma-addons
/plasmacalendarplugins/alternatecalendar/provider/icucalendar_p.h
UTF-8
1,684
2.546875
3
[]
no_license
/* SPDX-FileCopyrightText: 2021 Gary Wang <wzc782970009@gmail.com> SPDX-FileCopyrightText: 2022 Fushan Wen <qydwhotmail@gmail.com> SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include <unicode/calendar.h> #include <unicode/smpdtfmt.h> #include <QCalendar> class QString; class ICUCalendarPrivate { public: /** * Initialize the Gregorian Calendar, which will be used in date conversion. */ explicit ICUCalendarPrivate(); virtual ~ICUCalendarPrivate(); /** * Returns the value for a given time field in the alternate calendar. */ int32_t year() const; int32_t month() const; int32_t day() const; /** * Returns the date from the alternate calendar. * * @return the date from the alternate calendar */ QCalendar::YearMonthDay date() const; /** * Sets the date in the Gregorian Calendar, and convert the date to * the alternate calendar. * * @param date the Gregorian Calendar's date to be converted * @return @c true if the date is successfully set, @c false otherwise */ bool setDate(const QDate &date); /** * Sets the alternate calendar's current time with the given time. * * @param time the Gregorian Calendar's time as milliseconds * @return @c true if the time is successfully set, @c false otherwise */ bool setTime(double time); protected: /** * Alternate calendar */ std::unique_ptr<icu::Calendar> m_calendar; /** * Standard ICU4C error code. */ mutable UErrorCode m_errorCode; private: /** * Gregorian Calendar */ const std::unique_ptr<icu::Calendar> m_GregorianCalendar; };
true
93171b4d477fcfa2784b1af8631bb598dfb7610a
C++
sustcoderboy/competitive-programming-archive
/dmoj/ccc/2008/stage-1/body_mass_index.cpp
UTF-8
519
3.09375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); double weight; double height; cin >> weight >> height; double bmi {weight / (height * height)}; if (bmi > 25) { cout << "Overweight"; } else if (bmi >= 18.5) { cout << "Normal weight"; } else { cout << "Underweight"; } cout << '\n'; return 0; }
true
b32f34f6f5c02887642dfd9ad462a46056faa28c
C++
pascal-canuel/ColorDetection
/VisionLab1/VisionLab1.cpp
UTF-8
960
2.75
3
[ "MIT" ]
permissive
// VisionLab1.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit. // Lab 1 Vision par ordinateur // Par Pascal Canuel et Justin Roberge-Lavoie #include "pch.h" #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include "CGrabber.h" using namespace std; using namespace cv; int main() { CGrabber grab; VideoCapture cap(0); if (!cap.isOpened()) { cout << "The camera is not opened" << endl; return -1; } Mat frame; namedWindow("CamView", WINDOW_NORMAL); resizeWindow("CamView", 700, 500); while (true) { cap >> frame; if (frame.empty()) { break; } imshow("CamView", frame); // Detect only the two biggest forms of a given colors for performance purpose grab.getHSV(frame); if (waitKey(30) >= 0) break; // Quit if key entered } cap.release(); // Closes all the windows destroyAllWindows(); return 0; }
true
7fe764588992b944f82db3ec17abdeb4e05d5205
C++
pedroccufc/programming-challenges
/01 - Contest - Nivelamento/K - Summing Digits.cpp
UTF-8
663
3.421875
3
[]
no_license
#include <iostream> #include <list> using namespace std; int f(int x){ // Exemplo 255 int resto = x % 10; int div = x / 10; if(x < 10){ return x; }else{ return resto + f(div); } } int main(){ int input; cin >> input; list<int> numbers; numbers.push_back(input); while(input != 0){ cin >> input; numbers.push_back(input); } numbers.pop_back(); int gn, new_number; for(list<int>::iterator it = numbers.begin(); it != numbers.end(); it++){ gn = f(*it); if(gn < 10){ cout << gn << endl; }else{ gn = f(*it); while(!(gn < 10)){ new_number = f(gn); gn = new_number; } cout << gn << endl; } } return 0; }
true
c699592f133fa7e56b0af67ce3df668d9ad1f752
C++
Unidata/LDM
/noaaport/FrameBuf.h
UTF-8
3,452
3.125
3
[ "BSD-2-Clause" ]
permissive
/** * This file declares a buffer for putting real-time frames in strictly monotonic order. * * @file: FrameBuf.h * @author: Steven R. Emmerson <emmerson@ucar.edu> * * Copyright 2023 University Corporation for Atmospheric Research * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef NOAAPORT_FRAMEBUF_H_ #define NOAAPORT_FRAMEBUF_H_ #include <memory> /** * Buffer for putting real-time frames in strictly increasing monotonic order. * @tparam Key Type of key for sorting frames in increasing order. Must have a copy * constructor, the operators "=", and "++", and support for the expression * `Key < Key`. The "++" operator must increment to the next expected value. * @tparam Frame Type of frame to be sequenced. Must have a copy constructor. * @tparam Duration Type of the timeout value */ template<class Key, class Frame, class Duration> class FrameBuf { private: class Impl; ///< Implementation std::shared_ptr<Impl> pImpl; ///< Smart pointer to an implementation /** * Constructs from an implementation. * @param[in] impl Pointer to an implementation */ FrameBuf(Impl* const impl); public: /** * Constructs. * @param[in] timeout Failsafe timeout for consuming the next frame even if it's not the * expected one. Increasing the value will decrease the risk of gaps but * increase latency when they occur. */ FrameBuf(const Duration& timeout); /// Copy constructs. FrameBuf(const FrameBuf& frameBuf) =delete; /// Copy assigns. FrameBuf& operator=(const FrameBuf& frameBuf) =delete; /** * Tries to insert a frame. The frame will not be inserted if its key doesn't compare greater * than that of the last consumed frame or if the frame is already in the buffer. * @param[in] key The key of the frame to insert * @param[in] frame The frame to insert * @retval `true` The frame was inserted * @retval `false` The frame was not inserted * @throws Whatever `Key.operator<(const Key&)` throws * @throws Whatever `Consumer.consume(const Key&, Frame&)` throws * @threadsafety Safe * @exceptionsafety Strong guarantee */ bool tryInsert( const Key& key, Frame& frame) const; /** * Returns the next frame. * @param[out] key Key of the next frame * @param[out] frame The next frame * @throws Whatever `Key < Key` throws * @throws Whatever `Key = Key` throws * @throws Whatever `++Key` throws * @threadsafety Safe * @exceptionsafety If the `Key` operations throw, then strong guarantee; else no throw */ void getFrame( Key& key, Frame& frame) const; }; #endif /* NOAAPORT_FRAMEBUF_H_ */
true
1bf6cc8667a3142b6df907856d070b289ce957ba
C++
tkrs/challenge.book
/2-1_FullSearch/perm.cpp
UTF-8
448
2.9375
3
[]
no_license
#include<cstdio> #include<algorithm> using namespace std; const int MAX_N = 50; int perm2[MAX_N]; void permutation2(int); void permutation2(int n) { for (int i = 0; i < n; i++) { perm2[i] = i; } do { for (int i = 0; i < n; i++) { printf("%d ", perm2[i]); } printf("\n"); } while (next_permutation(perm2, perm2 + n)); return; } int main() { permutation2(5); return 0; }
true
5ab1095ac652172c1ecc5160fc7b3a0befc3292d
C++
jiezhou0731/programming
/algorithm/datastructure/binaryLifting.cpp
UTF-8
927
2.90625
3
[]
no_license
// https://leetcode.com/problems/kth-ancestor-of-a-tree-node/submissions/ #include <bits/stdc++.h> using namespace std; vector<vector<int>> f; TreeAncestor(int n, vector<int>& parent) { f = vector<vector<int>> (n, vector<int>(20,-1)); for (int i = 0; i < n; i++) { f[i][0] = parent[i]; } for (int l = 1; l <= 19; l++) { for (int i = 0; i < n; i++) { if (f[i][l-1] >= 0) { if (f[f[i][l-1]][l-1] >= 0) { f[i][l] = f[f[i][l-1]][l-1]; } } } } } int getKthAncestor(int x, int k) { if (x == -1) { return -1; } if (k == 1) { return f[x][0]; } if (k == 0) { return x; } int cur = 1; int next = 0; while (cur * 2 <= k) { cur *= 2; next += 1; } return getKthAncestor(f[x][next], k - cur); }
true
11eeea01b55e8d95d5d7d223b8b8c17397ea5fe5
C++
rbruno95/codeforces-ladders
/< 1300/057-puzzles.cpp
UTF-8
390
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<int> puzzles(m); for(int i=0;i<m;++i) cin >> puzzles[i]; sort(puzzles.begin(), puzzles.end()); int min_diff = 1e9+10; for(int i=0;i<=m-n;++i) min_diff = min(min_diff, puzzles[i+n-1]-puzzles[i]); cout << min_diff << '\n'; return 0; }
true
f05acd2bc989cf06dc5de202273bae8a72510465
C++
michaellin/neurosky
/arduino/NeuroskyCar/NeuroskyDriver/NeuroskyDriver.ino
UTF-8
630
2.890625
3
[]
no_license
//Constants int pinF = 13; int pinL = 11; int pinR = 10; void setup() { Serial.begin(115200); pinMode(pinF, OUTPUT); pinMode(pinL, OUTPUT); pinMode(pinR, OUTPUT); } void loop() { if (Serial.available()) { char rsp = Serial.read(); if (rsp == 'F') { digitalWrite(pinF, HIGH); } else if (rsp == 'S') { digitalWrite(pinF, LOW); } else if (rsp == 'L') { digitalWrite(pinL, HIGH); digitalWrite(pinR, LOW); } else if (rsp == 'R') { digitalWrite(pinL, LOW); digitalWrite(pinR, HIGH); } } }
true
9fce7d7dece1d4242e95534c3de218b424bd41f4
C++
gunlinia/wk15
/wk15/wk15.ino
UTF-8
669
2.96875
3
[]
no_license
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to const int analogOutPin = 9; // Analog output pin that the LED is attached to int sensorValue = 0; // value read from the pot int outputValue = 0; // value output to the PWM (analog out) void setup() { // initialize serial communications at 9600 bps: Serial.begin(9600);} void loop() { // put your main code here, to run repeatedly: int sensorRead =analogRead(A0); if (sensorRead<600)sensorRead=600; else if(sensorRead>900)sensorRead=900; int outputValue=map(sensorRead,600,900,0,255); analogWrite(9,outputValue); Serial.println(outputValue); delay(200); }
true
dbc59a6003faa258a3e3d25ed1c29546c785da89
C++
KMS-TEAM/kmslogger
/Logger.cpp
UTF-8
608
2.921875
3
[ "MIT" ]
permissive
#include "Logger.h" using namespace std; Logger* Logger::m_instance = nullptr; std::fstream Logger::outFile = fstream(); Logger::Logger() { outFile.open(LOG_FILE, ios::out | ios::app); } Logger::~Logger() { if (nullptr != m_instance) { delete m_instance; } m_instance = nullptr; outFile.close(); } Logger* Logger::instance() { if (nullptr == m_instance) { m_instance = new Logger(); } return m_instance; } std::fstream& Logger::output() { return outFile; } void Logger::writeLog(const std::string& msg) { outFile << "[Logger]" << msg; }
true
e2f3fe54f1d70a34353dccc2db7232be455946c0
C++
IonicArgon/2020-2021-bionic-beaver
/include/subsystems/hardware/sensors.hpp
UTF-8
2,095
2.78125
3
[ "MIT" ]
permissive
//* Discobots 1104A comp code. //* Marco Tan, Neil Sachdeva, Dev Patel //* //* File Created: 2020-09-29 //* Desc: Sensors class declarations. //! Prefix all objects here with "h_" except for child members and namespaces. #ifndef H_SENSORS_HPP #define H_SENSORS_HPP //* Headers #include "api.h" //* User-defined types /// enum - Vision Sensor IDs enum class h_sVision_IDs { RED_ID = 1, BLUE_ID }; /// enum - Encoder IDs enum class h_Encoder_IDs { LEFT, RIGHT, MIDDLE, AVG_SIDES }; /// struct - Smart sensor ports. //? In order of: IMU, Vision struct h_Smart_Sen_Ports { std::uint8_t pt_IMU; // Smart sensor port, IMU. std::uint8_t pt_Vision; // Smart sensor port, Vision. }; /// struct - Analog sensor ports. //! Use only the top port number. //? In order of: Left tracking wheel, right tracking wheel, middle tracking wheel. struct h_Analog_Sen_Ports { std::uint8_t pt_Enc_LT; // Analog port, encoder left top. std::uint8_t pt_Enc_LB; // Analog port, encoder left bottom. std::uint8_t pt_Enc_RT; // Analog port, encoder right top. std::uint8_t pt_Enc_RB; // Analog port, encoder right bottom. std::uint8_t pt_Enc_MT; // Analog port, encoder middle top. std::uint8_t pt_Enc_MB; // Analog port, encoder middle bottom. h_Analog_Sen_Ports(std::uint8_t LT, std::uint8_t RT, std::uint8_t MT); }; /// class - Sensors /// Has all the necessary objects and functions. class h_Sensors { public: h_Sensors( const h_Smart_Sen_Ports &s_ports, const h_Analog_Sen_Ports &a_ports, bool tr_w_left_rev = true, bool tr_w_right_rev = false, bool tr_w_middle_rev = false ); void initialize(); h_Sensors& add_sig(pros::vision_signature_s_t sig, h_sVision_IDs ID); pros::vision_object_s_t get_obj_sig(int size, h_sVision_IDs ID); double get_heading(); h_Sensors& reset(); int32_t get_enc(h_Encoder_IDs ID); private: pros::Vision m_sVision; pros::Imu m_sIMU; pros::ADIEncoder m_aL; pros::ADIEncoder m_aR; pros::ADIEncoder m_aM; }; #endif // H_SENSORS_HPP
true
2f6acf11f65c05570034c501b5157135ef76f2af
C++
magnusl/FlashPlayer
/src/swf/oglShaders.cpp
UTF-8
7,169
2.8125
3
[]
no_license
/** * \file oglShader.cpp * \brief Defines the OpenGL Shader Language (GLSL) shader programs used by the SWF renderer. * \author Magnus Leksell */ #include "CGLRenderer.h" #include <iostream> namespace swf { namespace ogl { const char * g_SolidVertexSource = "#version 130\n" "uniform mat4 projection;\n" "uniform mat4 transform;\n" "\n" "in vec2 vVertex;\n" "void main()" "{\n" " gl_Position = projection * transform * vec4(vVertex, 0, 1.0);\n" "}"; const char * g_SolidFragmentSource = "#version 130\n" "uniform vec4 color;\n" "out vec4 vFragColor;\n" "" "void main() {\n" " vFragColor = color;\n" "}"; const char * g_1DFragmentShader = "#version 130\n" "out vec4 vFragColor;\n" "uniform sampler1D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" "vFragColor = texture(_texture0, vVaryingTexCoords.s);\n" "}"; const char * g_2DFragmentShader = "#version 130\n" "out vec4 vFragColor;\n" "uniform sampler2D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" "vFragColor = texture(_texture0, vVaryingTexCoords.st);\n" "}"; /** * Solid color shader with Color transformation */ const char * g_SolidFragmentSource_CX = "#version 130\n" "uniform vec4 color;\n" "uniform vec4 vAddTerms;\n" "uniform vec4 vMulTerms;\n" "out vec4 vFragColor;\n" "" "void main() {\n" " vFragColor.r = color.r * vMulTerms.r + vAddTerms.r;\n" " vFragColor.g = color.g * vMulTerms.g + vAddTerms.g;\n" " vFragColor.b = color.b * vMulTerms.b + vAddTerms.b;\n" " vFragColor.a = color.a * vMulTerms.a + vAddTerms.a;\n" "}"; const char * g_2DFragmentShader_CX = "#version 130\n" "out vec4 vFragColor;\n" "uniform vec4 vAddTerms;\n" "uniform vec4 vMulTerms;\n" "uniform sampler2D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" " vec4 color = texture(_texture0, vVaryingTexCoords.st);\n" " vFragColor.r = color.r * vMulTerms.r + vAddTerms.r;\n" " vFragColor.g = color.g * vMulTerms.g + vAddTerms.g;\n" " vFragColor.b = color.b * vMulTerms.b + vAddTerms.b;\n" " vFragColor.a = color.a * vMulTerms.a + vAddTerms.a;\n" "}"; /** * 1D fragment shader with color transformation. */ const char * g_1DFragmentShader_CX = "#version 130\n" "out vec4 vFragColor;\n" "uniform vec4 vAddTerms;\n" "uniform vec4 vMulTerms;\n" "uniform sampler1D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" " vec4 color = texture(_texture0, vVaryingTexCoords.s);\n" " vFragColor.r = color.r * vMulTerms.r + vAddTerms.r;\n" " vFragColor.g = color.g * vMulTerms.g + vAddTerms.g;\n" " vFragColor.b = color.b * vMulTerms.b + vAddTerms.b;\n" " vFragColor.a = color.a * vMulTerms.a + vAddTerms.a;\n" "}"; /** * Radial fragment shader with color transformation. */ const char * g_RadialFragmentSource_CX = "#version 130\n" "out vec4 vFragColor;\n" "uniform vec4 vAddTerms;\n" "uniform vec4 vMulTerms;\n" "uniform sampler1D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" " float s = 0.5 - vVaryingTexCoords.s;\n" " float t = 0.5 - vVaryingTexCoords.t;\n" " float c = sqrt(s*s + t*t);\n" " vec4 color = texture(_texture0, c);\n" " vFragColor.r = color.r * vMulTerms.r + vAddTerms.r;\n" " vFragColor.g = color.g * vMulTerms.g + vAddTerms.g;\n" " vFragColor.b = color.b * vMulTerms.b + vAddTerms.b;\n" " vFragColor.a = color.a * vMulTerms.a + vAddTerms.a;\n" "}"; /*************************************************************************/ /* Vertex shader for texturing */ /*************************************************************************/ const char * g_TextureVertexSource = "#version 130\n" "uniform mat4 projection;\n" "uniform mat4 transform;\n" "in vec2 vVertex;\n" "in vec2 vTexCoords;\n" "smooth out vec2 vVaryingTexCoords;\n" "\n" "void main()\n" "{\n" " gl_Position = projection * transform * vec4(vVertex, 0, 1.0);\n" " vVaryingTexCoords = vTexCoords;\n" "}"; const char * g_TextFragmentShader = "#version 130\n" "out vec4 vFragColor;\n" "uniform sampler2D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" " float alpha = texture(_texture0, vVaryingTexCoords.st).r;\n" " vFragColor.a = alpha;\n" " vFragColor.r = 0.0;" " vFragColor.g = 0.0;" " vFragColor.b = 1.0;" "}"; const char * g_RadialFragmentSource = "#version 130\n" "out vec4 vFragColor;\n" "uniform sampler1D _texture0;\n" "smooth in vec2 vVaryingTexCoords;\n" "void main()\n" "{\n" " float s = 0.5 - vVaryingTexCoords.s;\n" " float t = 0.5 - vVaryingTexCoords.t;\n" " float c = sqrt(s*s + t*t);\n" " vFragColor = texture(_texture0, c);\n" "}"; const char * g_WhiteFragmentSource = "#version 130\n" "out vec4 vFragColor;\n" "void main() {\n" " vFragColor = vec4(1, 1, 1, 1);\n" "}"; static struct { const char * VertexSource; const char * FragmentSource; } g_ShaderSources[] = { {g_SolidVertexSource, g_SolidFragmentSource}, // eSOLID_COLOR_SHADER {g_TextureVertexSource, g_1DFragmentShader}, // e1D_TEXTURE_SHADER {g_TextureVertexSource, g_2DFragmentShader}, // e2D_TEXTURE_SHADER {g_TextureVertexSource, g_RadialFragmentSource}, // eRADIAL_1D_TEXTURE_SHADER {g_TextureVertexSource, g_TextFragmentShader}, // eTEXT_SHADER {g_SolidVertexSource, g_WhiteFragmentSource}, // eSTENCIL_SHADER {g_SolidVertexSource, g_SolidFragmentSource_CX}, // eSOLID_COLOR_SHADER_CX {g_TextureVertexSource, g_1DFragmentShader_CX}, // e1D_TEXTURE_SHADER_CX {g_TextureVertexSource, g_2DFragmentShader_CX}, // e2D_TEXTURE_SHADER_CX {g_TextureVertexSource, g_RadialFragmentSource_CX}, // eRADIAL_1D_TEXTURE_SHADER_CX }; static float g_RectangleVerticies[] = { -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, -0.5 }; static unsigned int g_RectangleIndicies[] = { 0, 1, 2, 2, 3, 0 }; static unsigned int g_RectangeStrokeIndicies[] = { 0, 1, 1, 2, 2, 3, 3, 0 }; /** * Initializes the shaders */ bool CGLRenderer::initShaders() { shaders.resize(eSHADER_MAX); for(size_t i = 0; i < eSHADER_MAX; ++i) { std::cout << "compiling shader " << i << std::endl; if (!(shaders[i] = CShaderProgram::FromSource(g_ShaderSources[i].VertexSource, g_ShaderSources[i].FragmentSource))) { return false; } } return true; } } }
true
1c063d94c53c4b41fa875653d3ff5bd165d9166b
C++
PeterZs/Simulation-meshlessDeformations
/glmeEncode.cpp
UTF-8
6,848
2.765625
3
[]
no_license
#include "render.h" void glm_mix(double * A, double * source, double * dest) { dest[0] = A[0] * source[0] + A[1] * source[1] + A[2] * source[2]; dest[1] = A[3] * source[0] + A[4] * source[1] + A[5] * source[2]; dest[2] = A[6] * source[0] + A[7] * source[1] + A[8] * source[2]; } void glm_mix2(double * A, double * source, double * dest) { dest[0] = A[0] * source[0] + A[1] * source[1]; dest[1] = A[2] * source[0] + A[3] * source[1]; } void glmEncode(GLMmodel * mesh) { /* for(unsigned int i=0; i <= ~0; i++) { if (i != glm_invf(glm_f(i))) printf("Error at i=%d\n", i); } */ double mixingMatrix[9] = {1, 0, -1, 2, 1, 0, -1, 1, 2}; double mixingMatrix2[4] = {1, 0, -1, 2}; //encode vertices GLfloat * verticesTemp = (GLfloat*) malloc (sizeof(GLfloat) * 3 * (mesh->numvertices + 1)); verticesTemp[0] = verticesTemp[1] = verticesTemp[2] = 0.0; #define VERTEX(i,j) (mesh->vertices[3*(i) + 3 + (j)]) for(unsigned int i=0; i<mesh->numvertices; i++) { int m1 = i; int m2 = (i+1) % mesh->numvertices; int m3 = (i+2) % mesh->numvertices; double source[3] = {VERTEX(m1,0), VERTEX(m2, 1), VERTEX(m3, 2)}; double dest[3]; glm_mix(mixingMatrix, source, dest); verticesTemp[3 * i + 3] = dest[0]; verticesTemp[3 * i + 4] = dest[1]; verticesTemp[3 * i + 5] = dest[2]; } memcpy(mesh->vertices, verticesTemp, sizeof(GLfloat) * 3 * (mesh->numvertices + 1)); free(verticesTemp); //encode normals if (mesh->normals != NULL) { GLfloat * normalsTemp = (GLfloat*) malloc (sizeof(GLfloat) * 3 * (mesh->numnormals + 1)); normalsTemp[0] = normalsTemp[1] = normalsTemp[2] = 0.0; #define NORMAL(i,j) (mesh->normals[3*(i) + 3 + (j)]) for(unsigned int i=0; i<mesh->numnormals; i++) { int m1 = i; int m2 = (i+1) % mesh->numnormals; int m3 = (i+2) % mesh->numnormals; double source[3] = {NORMAL(m1,0), NORMAL(m2, 1), NORMAL(m3, 2)}; double dest[3]; glm_mix(mixingMatrix, source, dest); normalsTemp[3 * i + 3] = dest[0]; normalsTemp[3 * i + 4] = dest[1]; normalsTemp[3 * i + 5] = dest[2]; } memcpy(mesh->normals, normalsTemp, sizeof(GLfloat) * 3 * (mesh->numnormals + 1)); free(normalsTemp); } // encode texture coords if (mesh->texcoords != NULL) { GLfloat * uvTemp = (GLfloat*) malloc (sizeof(GLfloat) * 2 * (mesh->numtexcoords + 1)); uvTemp[0] = uvTemp[1] = 0.0; #define UV(i,j) (mesh->texcoords[2*(i) + 2 + (j)]) for(unsigned int i=0; i<mesh->numtexcoords; i++) { int m1 = i; int m2 = (i+1) % mesh->numtexcoords; double source[2] = {UV(m1,0), UV(m2, 1)}; double dest[2]; glm_mix2(mixingMatrix2, source, dest); uvTemp[2 * i + 2] = dest[0]; uvTemp[2 * i + 3] = dest[1]; } memcpy(mesh->texcoords, uvTemp, sizeof(GLfloat) * 2 * (mesh->numtexcoords + 1)); free(uvTemp); } // encode triangles for(unsigned int i=0; i<mesh->numtriangles; i++) { for(int j=0; j<3; j++) { unsigned int value = (mesh->triangles)[i].vindices[j]; (mesh->triangles)[i].vindices[j] = glm_f(value); } for(int j=0; j<3; j++) { unsigned int value = (mesh->triangles)[i].nindices[j]; (mesh->triangles)[i].nindices[j] = glm_f(value); } for(int j=0; j<3; j++) { unsigned int value = (mesh->triangles)[i].tindices[j]; (mesh->triangles)[i].tindices[j] = glm_f(value); } } } void glmDecode(GLMmodel * mesh) { double invMixingMatrix[9] = {-2, 1, -1, 4, -1, 2, -3, 1, -1}; double invMixingMatrix2[4] = {1, 0, 0.5, 0.5}; //decode vertices GLfloat * verticesTemp = (GLfloat*) malloc (sizeof(GLfloat) * 3 * (mesh->numvertices + 1)); verticesTemp[0] = verticesTemp[1] = verticesTemp[2] = 0.0; #define VERTEX(i,j) (mesh->vertices[3*(i) + 3 + (j)]) for(unsigned int i=0; i<mesh->numvertices; i++) { double source[3] = {VERTEX(i,0), VERTEX(i, 1), VERTEX(i, 2)}; double dest[3]; glm_mix(invMixingMatrix, source, dest); int m1 = i; int m2 = (i+1) % mesh->numvertices; int m3 = (i+2) % mesh->numvertices; verticesTemp[3 * m1 + 3] = dest[0]; verticesTemp[3 * m2 + 4] = dest[1]; verticesTemp[3 * m3 + 5] = dest[2]; } memcpy(mesh->vertices, verticesTemp, sizeof(GLfloat) * 3 * (mesh->numvertices + 1)); memcpy(mesh->verticesRest, verticesTemp, sizeof(GLfloat) * 3 * (mesh->numvertices + 1)); free(verticesTemp); // decode normals if (mesh->normals != NULL) { GLfloat * normalsTemp = (GLfloat*) malloc (sizeof(GLfloat) * 3 * (mesh->numnormals + 1)); normalsTemp[0] = normalsTemp[1] = normalsTemp[2] = 0.0; #define NORMAL(i,j) (mesh->normals[3*(i) + 3 + (j)]) for(unsigned int i=0; i<mesh->numnormals; i++) { double source[3] = {NORMAL(i,0), NORMAL(i, 1), NORMAL(i, 2)}; double dest[3]; glm_mix(invMixingMatrix, source, dest); int m1 = i; int m2 = (i+1) % mesh->numnormals; int m3 = (i+2) % mesh->numnormals; normalsTemp[3 * m1 + 3] = dest[0]; normalsTemp[3 * m2 + 4] = dest[1]; normalsTemp[3 * m3 + 5] = dest[2]; } memcpy(mesh->normals, normalsTemp, sizeof(GLfloat) * 3 * (mesh->numnormals + 1)); free(normalsTemp); } // decode texture coords if (mesh->texcoords != NULL) { GLfloat * uvTemp = (GLfloat*) malloc (sizeof(GLfloat) * 2 * (mesh->numtexcoords + 1)); uvTemp[0] = uvTemp[1] = 0.0; #define UV(i,j) (mesh->texcoords[2*(i) + 2 + (j)]) for(unsigned int i=0; i<mesh->numtexcoords; i++) { double source[2] = {UV(i,0), UV(i,1)}; double dest[2]; glm_mix2(invMixingMatrix2, source, dest); int m1 = i; int m2 = (i+1) % mesh->numtexcoords; uvTemp[2 * m1 + 2] = dest[0]; uvTemp[2 * m2 + 3] = dest[1]; } memcpy(mesh->texcoords, uvTemp, sizeof(GLfloat) * 2 * (mesh->numtexcoords + 1)); free(uvTemp); } // decode triangles for(unsigned int i=0; i<mesh->numtriangles; i++) { for(int j=0; j<3; j++) { unsigned int value = (mesh->triangles)[i].vindices[j]; (mesh->triangles)[i].vindices[j] = glm_invf(value); } for(int j=0; j<3; j++) { unsigned int value = (mesh->triangles)[i].nindices[j]; (mesh->triangles)[i].nindices[j] = glm_invf(value); } for(int j=0; j<3; j++) { unsigned int value = (mesh->triangles)[i].tindices[j]; (mesh->triangles)[i].tindices[j] = glm_invf(value); } } // update edges GLMgroup * group = mesh->groups; while(group) { for(unsigned int i=0; i< group->numEdges; i++) { unsigned int value; value = (group->edges)[2*i+0]; (group->edges)[2*i+0] = glm_invf(value); value = (group->edges)[2*i+1]; (group->edges)[2*i+1] = glm_invf(value); } group = group->next; } }
true
8027c82082f3af9a1b5cc397efce883247dc785e
C++
mjww3/hackerrank
/hurdlerace.cpp
UTF-8
559
2.796875
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n; int k; cin>>n>>k; vector<int> hurdles; while(n--) { int g; cin>>g; hurdles.push_back(g); } sort(hurdles.begin(),hurdles.end()); if(hurdles[hurdles.size()-1]<=k) { cout<<0<<endl; } else{ cout<<hurdles[hurdles.size()-1]-k<<endl; } /* Enter your code here. Read input from STDIN. Print output to STDOUT */ return 0; }
true
53fe5fd34753abd3eecc1c8245b20f9ff76a92cd
C++
kamyu104/LeetCode-Solutions
/C++/find-servers-that-handled-most-number-of-requests.cpp
UTF-8
3,178
3.15625
3
[ "MIT" ]
permissive
// Time: O(nlogk) // Space: O(k) class Solution { public: vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap_of_endtimes; priority_queue<int, vector<int>, greater<int>> min_heap_of_nodes_after_curr; priority_queue<int, vector<int>, greater<int>> min_heap_of_nodes_before_curr; for (int i = 0; i < k; ++i) { min_heap_of_nodes_before_curr.emplace(i); } vector<int> count(k); for (int i = 0; i < size(arrival); ++i) { if (i % k == 0) { min_heap_of_nodes_after_curr = move(min_heap_of_nodes_before_curr); } while (!empty(min_heap_of_endtimes) && min_heap_of_endtimes.top().first <= arrival[i]) { const auto [_, free] = min_heap_of_endtimes.top(); min_heap_of_endtimes.pop(); if (free < i % k) { min_heap_of_nodes_before_curr.emplace(free); } else { min_heap_of_nodes_after_curr.emplace(free); } } auto& min_heap_of_candidates = !empty(min_heap_of_nodes_after_curr) ? min_heap_of_nodes_after_curr : min_heap_of_nodes_before_curr; if (empty(min_heap_of_candidates)) { continue; } const auto node = min_heap_of_candidates.top(); min_heap_of_candidates.pop(); ++count[node]; min_heap_of_endtimes.emplace(arrival[i] + load[i], node); } int max_count = *max_element(cbegin(count), cend(count)); vector<int> result; for (int i = 0; i < k; ++i) { if (count[i] == max_count) { result.emplace_back(i); } } return result; } }; // Time: O(nlogk) // Space: O(k) class Solution2 { public: vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_heap_of_endtimes; set<int> availables; for (int i = 0; i < k; ++i) { availables.emplace(i); } vector<int> count(k); for (int i = 0; i < size(arrival); ++i) { while (!empty(min_heap_of_endtimes) && min_heap_of_endtimes.top().first <= arrival[i]) { const auto [_, free] = min_heap_of_endtimes.top(); min_heap_of_endtimes.pop(); availables.emplace(free); } if (empty(availables)) { continue; } auto it = availables.lower_bound(i % k); if (it == end(availables)) { it = begin(availables); } ++count[*it]; min_heap_of_endtimes.emplace(arrival[i] + load[i], *it); availables.erase(it); } int max_count = *max_element(cbegin(count), cend(count)); vector<int> result; for (int i = 0; i < k; ++i) { if (count[i] == max_count) { result.emplace_back(i); } } return result; } };
true
a301009af91cc340549bc41834f5731c1ab46658
C++
minavadamee20/Command-Design-Pattern
/noCommand.h
UTF-8
501
2.6875
3
[]
no_license
// // noCommand.h // command_pattern // // #ifndef noCommand_h #define noCommand_h #include <iostream> class noCommand : public command { public: void execute() { std::cout << *this << " cannot execute"; } void undo() { std::cout << *this << " cannot undo"; } std::ostream& name(std::ostream& os) const { return os << *this; } friend std::ostream& operator<<(std::ostream& os, const noCommand& nc) { return os << "noCommand[]"; } }; #endif /* noCommand_h */
true
45148f71a4910b99287fe1428e9286b9f0653804
C++
g-akash/spoj_codes
/teams.cpp
UTF-8
438
2.859375
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int t; cin>>t; for(int i=0;i<t;i++) { int n; cin>>n; vector<int> v; v.resize(n); for(int j=0;j<n;j++)cin>>v[j]; sort(v.begin(),v.end()); int maxx=-1000000000,minn=1000000000; for(int j=0;j<n/2;j++) { if(v[j]+v[n-1-j]>maxx)maxx=v[j]+v[n-1-j]; if(v[j]+v[n-1-j]<minn)minn=v[j]+v[n-1-j]; } cout<<maxx-minn<<endl; } }
true
f1b67ce23681f410d51f61c16b6e0266876f538c
C++
shahriercse/Online-Judge-Solutions
/Codeforces/p959A.cpp
UTF-8
171
2.8125
3
[]
no_license
#include<iostream> using namespace std ; int main() { int a ; cin >> a ; if ( a % 2 == 0 ) cout << "Mahmoud" << endl ; else cout << "Ehab" << endl ; }
true
b374017b817be0fe1d37df3c7612b5b9c2229f71
C++
bhushansp07/cl1
/a6Displayhistogram.cpp
UTF-8
1,087
2.625
3
[]
no_license
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> using namespace std; using namespace cv; int main( int argc, char** argv ) { Mat image, dst; Vec3b intensity; image = imread("/home/bhushan/Labs/CL1/CL1/A6/image.tiff", 1 ); if( !image.data ) { return -1; } cvtColor(image, image, cv::COLOR_BGR2GRAY); Mat new_image = Mat::zeros( 320,520, image.type() ); long int *count=new long int[256]; for(int j=0;j<256;j++) { count[j]=0; } for( int y = 1; y < image.rows-1; y++ ) { for( int x = 1; x < image.cols-1; x++ ) { int p=image.at<Vec3b>(y,x)[0]; count[p]++; } } long int max=0; for(int j=0;j<256;j++) { //cout<<count[j]<<"\t"; if(count[j]>max) max=count[j]; } cout<<max; long int d=max/300; Scalar col; col=Scalar(255,255,255); for(int j=0;j<254;j++) { line( new_image, Point( j*2, 310-(count[j]/d) ), Point((j+1)*2, 310-(count[j+1]/d)), col, 2, 8 ); } namedWindow("Image", WINDOW_NORMAL); imshow("Image",image); imshow("Histogram",new_image); waitKey(0); return 0; }
true
d3980313b7027f177f11aacb0d99d41f32e6d432
C++
dajensen/Esp32WavI2s
/Esp32WavI2s.ino
UTF-8
597
2.578125
3
[ "MIT" ]
permissive
#include "WavPlayer.h" #include "sound/WavData.h" WavPlayer player; enum SpeechState { WAITING, HOUR, MINUTE }; SpeechState speechstate; void setup() { Serial.begin(115200); delay(1000); speechstate = HOUR; Serial.println("Starting to play"); if(!player.StartPlaying(hourWav[11])) Serial.println("ERROR SETTING UP THE DATA"); } void loop() { if(!player.Update()){ if(speechstate == HOUR) { speechstate = MINUTE; player.StartPlaying(minuteWav[39]); } else if(speechstate == MINUTE) speechstate = WAITING; else delay(10); } }
true
858fffc3310f51eb9dc0c7c7bf8ad3dd120a811c
C++
tianer2820/BetterSkins
/src/dataStructure/tools/moveTool.hpp
UTF-8
2,798
2.890625
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#if !defined(MOVE_TOOL_H) #define MOVE_TOOL_H #include "Tool.hpp" #include "../layer.hpp" #include "../../color/color.h" /** * Moves the whole layer. */ class MoveTool : public Tool { public: MoveTool() { setProperty("R", 0); setProperty("G", 0); setProperty("b", 0); setProperty("a", 255); setProperty("SIZE", 1); tool_type = ToolType::MOVE; } virtual void moveTo(int x, int y) { if(this->x == x && this->y == y){ return; // not moved } this->x = x; this->y = y; if (is_down && current_layer != NULL) { int w = image_cache.GetWidth(); int h = image_cache.GetHeight(); int offset_x = x - start_x; int offset_y = y - start_y; for (int c_y = 0; c_y < h; c_y++) { for (int c_x = 0; c_x < w; c_x++) { int map_to_x = c_x - offset_x; int map_to_y = c_y - offset_y; if(map_to_x < 0 || map_to_y < 0 || map_to_x >= w || map_to_y >= h){ // if the pixel maps to outside the cache current_layer->paint(c_x, c_y, RGBColor(0, 0, 0, 0)); continue; } // if the pixel maps to a correct pixel current_layer->paint(c_x, c_y, RGBColor(image_cache.GetRed(map_to_x, map_to_y), image_cache.GetGreen(map_to_x, map_to_y), image_cache.GetBlue(map_to_x, map_to_y), image_cache.GetAlpha(map_to_x, map_to_y))); } } } } virtual void penDown() { if (current_layer != nullptr) { is_down = true; start_x = x; // store initial position start_y = y; image_cache = current_layer->getImage()->Copy(); moveTo(x, y); } } virtual void penUp() { if (is_down && current_layer != NULL) { current_layer->stroke(); } is_down = false; } void mirrorX(){ if(current_layer == nullptr){ return; } wxImage img = current_layer->getImage()->Mirror(true); current_layer->getImage()->Paste(img, 0, 0); } void mirrorY(){ if(current_layer == nullptr){ return; } wxImage img = current_layer->getImage()->Mirror(false); current_layer->getImage()->Paste(img, 0, 0); } virtual void setFunctionalKeys(bool shift, bool ctrl) { } protected: int x, y; int start_x, start_y; wxImage image_cache; }; #endif // MOVE_TOOL_H
true
7717bd8bd7615ba70e700cd7cdbb91aecf156efd
C++
seikhchilli/cplusplus
/check_prime_number.cpp
UTF-8
297
3.28125
3
[]
no_license
#include<iostream> using namespace std; int main() { int n; cout<<"Enter the number to checked: "; cin>>n; int i; for (i = 2; i <= n; i++) { if (n%i == 0) { break; } } if (i == n) { cout<<n<<" is prime."; } else { cout<<n<<" is not prime."; } }
true
4ddc7f77a6f9d67003e9e44a3de45835442c4f68
C++
NIA/seismoreg
/src/protocol.h
UTF-8
6,900
2.734375
3
[]
no_license
#ifndef PROTOCOL_H #define PROTOCOL_H #include <QObject> #include <QVector> #include <QDateTime> typedef int DataType; const unsigned CHANNELS_NUM = 3; struct DataItem { DataType byChannel[CHANNELS_NUM]; }; typedef QVector<DataItem> DataVector; typedef double TimeStampType; // Now use milliseconds from Epoch as TimeStampType for performance reasons typedef QVector<TimeStampType> TimeStampsVector; /*! * \interface Protocol * \brief The common Protocol interface (abstract class, to be precise - \see Protocol::state) * * Specifies higher-order abstraction for commands of * data-transferring protocol, *independent* on transport type * (socket, serial port etc). * * \remarks You would like to use some of the implementations of this * interface: SerialProtocol, TestProtocol or any other. */ class Protocol : public QObject { Q_OBJECT public: /*! * Possible states of protocol */ enum SingleState { NoState = 0, /*!< Initial state: just created, nothing done */ Open = 1 << 0, /*!< Established connection, now can transmit and receive data */ ADCWaiting= 1 << 1, /*!< Requested ADC confirmation, waiting for response */ ADCReady = 1 << 2, /*!< Validated ADC */ GPSWaiting= 1 << 3, /*!< Requested GPS time/position, waiting for response */ GPSReady = 1 << 4, /*!< Validated GPS */ GPSHasTime= 1 << 5, /*!< Received GPS Time */ GPSHasPos = 1 << 6, /*!< Received GPS Position */ Receiving = 1 << 7 /*!< Listening for incoming data. Possible when: (1) connected, (2) validated ADC, (3) validated GPS */ }; Q_DECLARE_FLAGS(State, SingleState) /*! * \brief Standart QObject-like constructor for Protocol * * \warning When subclassing, don't forget to call this constructor * from your initializer list and pass the parent, in order * to let QObject's memory management work properly * \param parent QObject parent */ explicit Protocol(QObject * parent = nullptr) : QObject(parent) { resetState(); } /*! * \brief Short description of protocol * \return translatable description of protocol type and its parameters (like port, etc) */ virtual QString description() = 0; /*! * \brief initialize protocol communication * \todo probably this method should be async * \returns true if successful, false otherwise */ virtual bool open() = 0; /*! * \brief sends ADC checking command * * Result is returned asynchronously via checkedADC signal * \see Protocol::checkedADC */ virtual void checkADC() = 0; /*! * \brief sends GPS checking command * * Result is returned asynchronously via checkedGPS signal * \see Protocol::checkedGPS */ virtual void checkGPS() = 0; virtual int samplingFrequency() = 0; virtual void setSamplingFrequency(int value) = 0; virtual int filterFrequency() = 0; virtual void setFilterFrequency(int value) = 0; /*! * \brief initiate data receiving * * Sends command to ADC so that it will begin sending data. * When new data is available, it is returned asynchronously via dataAvailable signal; * \see Protocol::dataAvailable */ virtual void startReceiving() = 0; /*! * \brief initiate data receiving * * Stops processing received data. * In means simply ignoring all later data: */ virtual void stopReceiving() = 0; /*! * \return current state */ State state() const { return state_; } /*! * \brief checks if given state flag is set * \param flag flag to check * \return true if flag set, false otherwise */ bool hasState(SingleState flag) const { return state_.testFlag(flag); } /*! * \brief Close all opened ports and finalize all work with protocol */ virtual void close() = 0; virtual ~Protocol() {} signals: /*! * \brief emitted when ADC check result is ready * \param success is true if ADC reported to be ready, false otherwise * \see Protocol::checkADC */ void checkedADC(bool success); /*! * \brief emitted when GPS check result is ready * \param success is true if GPS reported to be ready, false otherwise * \see Protocol::checkGPS */ void checkedGPS(bool success); /*! * \brief emitted when received current precise time from GPS * \param timeGPS - current time * \see Protocol::checkGPS */ void timeAvailable(QDateTime timeGPS); /*! * \brief emitted when received current position from GPS * \param latitiude - latitude in degrees * \param longitude - longitude in degrees * \param altitude - altitude in meters * \see Protocol::checkGPS */ void positionAvailable(double latitiude, double longitude, double altitude); /*! * \brief emitted when new data from ADC is available * \param data - newly received data * \param timestamps - timestamps for \a data * \see Protocol::startReceiving, Protocol::stopReceiving */ void dataAvailable(TimeStampsVector timestamps, DataVector data); /*! * \brief emitted when state is changed * \param newState state value after change * \see Protocol::state */ void stateChanged(State newState); protected: void resetState() { setState(NoState); } void addState(State newState) { setState(state_ | newState); } void removeState(SingleState oldState) { setState(state_ & (~oldState)); } void setState(State newState) { State oldState = state_; state_ = newState; if(oldState != newState) { emit stateChanged(newState); } } private: State state_; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Protocol::State) /*! * \interface ProtocolCreator * \brief Instance of this class is passed to \a Worker so that * is can create \a Protocol in it's own thread * (Like 'Factory method' pattern) * \todo - transform this into an AbstractFactory? * - should it have a QObject*parent c-tor param? */ class ProtocolCreator { public: virtual Protocol * createProtocol() = 0; /*! * \brief An unique identifier of particular * implementation of \a Protocol and its parameters * (like port name). * * If these strings are equal for two * given ProtocolCreators, createProtocol will * be called once, and same Protocol will be used * for both cases. */ virtual QString protocolId() = 0; }; #endif // PROTOCOL_H
true
58e702bf75f5b24c168aa0dbeca29dbb42bad413
C++
inpicksys/stepik_yandex_Introduction_to_Programming_Cpp
/1.6 Real numbers/task_7.cpp
UTF-8
1,650
3.40625
3
[]
no_license
/* Дана последовательность натуральных чисел x1, x2, ..., xn. Стандартным отклонением называется величина σ = sqrt( ( (x_1 - s)^2 + (x_2 - s)^2 + ... + (x_n - s)^2 ) / n-1 ) , где s = (x_1 + x_2 + ... + x_n) / n - среднее значение последовательности. // Формулы есть во вложениях Определите стандартное отклонение для данной последовательности натуральных чисел, завершающейся числом 0. Формат входных данных Вводится последовательность натуральных чисел, оканчивающаяся числом 0 (само число 0 в последовательность не входит, а служит как признак ее окончания). В последовательности не менее двух чисел до 0. Формат выходных данных Выведите ответ на задачу. Sample Input: 1 7 9 0 Sample Output: 4.16333199893 */ #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { double number, counter = 0, sum, sum_of_powers; cin >> number; sum = number; sum_of_powers = pow(number, 2.0); while (number != 0) { counter++; cin >> number; sum += number; sum_of_powers += pow(number, 2.0); } cout.precision(11); cout << sqrt((sum_of_powers - (pow(sum, 2.0) / counter)) / (counter - 1)); return 0; }
true
d2599bff84357af9542e8b10fb017af7ad50c728
C++
markushoehn/GDV1_WS17
/Ex2p/TriangleMesh.h
MacCentralEurope
3,889
2.875
3
[]
no_license
// ========================================================================= // // Authors: Roman Getto, Matthias Bein // // mailto:roman.getto@gris.informatik.tu-darmstadt.de // // // // GRIS - Graphisch Interaktive Systeme // // Technische Universitt Darmstadt // // Fraunhoferstrasse 5 // // D-64283 Darmstadt, Germany // // // // Content: Simple class for reading and rendering triangle meshes // // * readOFF // // * draw // // * transformations // // ========================================================================== // #ifndef TRIANGLEMESH_H #define TRIANGLEMESH_H #include <vector> #include "Vec3.h" #include <GL/glew.h> #include <GL/glut.h> #include <algorithm> #define M_PI 3.14159265358979f using namespace std; class TriangleMesh { private: // typedefs for data typedef Vec3ui Triangle; typedef Vec3f Normal; typedef Vec3f Vertex; typedef vector<Triangle> Triangles; typedef vector<Normal> Normals; typedef vector<Vertex> Vertices; // data of TriangleMesh Vertices vertices; Normals normals; Triangles triangles; // VBO ids for vertices, normals and faces bool VBOsupported; unsigned int VBOv, VBOn, VBOf; // bounding box data Vec3f boundingBoxMin; Vec3f boundingBoxMax; Vec3f boundingBoxMid; Vec3f boundingBoxSize; // ========================= // === PRIVATE FUNCTIONS === // ========================= // calculate normals void calculateNormals(); // create VBOs for vertices, faces and normals void createAllVBOs(); // clean up VBO data (delete from gpu memory) void cleanupVBO(); public: // =============================== // === CONSTRUCTOR, DESTRUCTOR === // =============================== TriangleMesh(); ~TriangleMesh(); // clears all data, sets defaults void clear(); // ================ // === RAW DATA === // ================ // get raw data references vector<Vec3f>& getVertices() { return vertices; } vector<Vec3ui>& getTriangles() { return triangles; } vector<Vec3f>& getNormals() { return normals; } // get size of all elements unsigned int getNumVertices() { return vertices.size(); } unsigned int getNumNormals() { return normals.size(); } unsigned int getNumTriangles() { return triangles.size(); } // flip all normals void flipNormals(); // translates vertices so that the bounding box center is at newBBmid void translateToCenter(const Vec3f& newBBmid); // scales vertices so that the largest bounding box size has length newLength void scaleToLength(const float newLength); // ================= // === LOAD MESH === // ================= // read from an OFF file. also calculates normals if not given in the file. void loadOFF(const char* filename); // read from an OFF file. also calculates normals if not given in the file. // translates and scales vertices with bounding box center at BBmid and largest side BBlength void loadOFF(const char* filename, const Vec3f& BBmid, const float BBlength); // ============== // === RENDER === // ============== // draw mesh with immediate mode void drawImmediate(); // draw mesh with vertex array void drawArray(); // draw VBO void drawVBO(); }; #endif
true
169f2a9e33a400bcb870dd458cfe0d22788d1a00
C++
pavelsimo/ProgrammingContest
/codeforces/PastContest/Codeforces Round #142 (Div. 2)/C.cpp
UTF-8
1,319
2.5625
3
[]
no_license
#include <algorithm> #include <iostream> #include <cstring> using namespace std; string B[102]; int DL[102][10002]; int DR[102][10002]; const int INF = 0x3f3f3f3f; int main(int argc, char *argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); memset(DL, 0x3f, sizeof(DL)); memset(DR, 0x3f, sizeof(DR)); int n, m; cin >> n >> m; for(int i = 0; i < n; ++i) cin >> B[i]; for(int i = 0; i < n; ++i) { int first = B[i].find('1'); int last = B[i].rfind('1'); if(first == -1) { cout << -1 << endl; return 0; } int prev = first; for(int j = 0; j < m; ++j) { if(B[i][j] == '1') { DL[i][j] = 0; prev = j; } else { DL[i][j] = min(abs(prev - j), m - last + j); } } prev = last; for(int j = m - 1; j >= 0; --j) { if(B[i][j] == '1') { DR[i][j] = 0; prev = j; } else { DR[i][j] = min(abs(prev - j), first + m - j); } } } int res = INF; for(int j = 0; j < m; ++j) { int sum = 0; for(int i = 0; i < n; ++i) { sum += min(DL[i][j], DR[i][j]); } res = min(res, sum); } cout << res << endl; return 0; }
true
66563cdefc0e7ba69a872f40abee39bf05b50572
C++
Valtis/EuroNeuro
/EuroNeuro/EuroNeuro.cpp
UTF-8
2,955
2.953125
3
[]
no_license
#include "FileReader.h" #include "NeuralNetwork.h" #include <clocale> #include <cstdio> #include <cstdlib> #include <ctime> #include <fstream> void NormalizeFields(std::vector<std::vector<double>> &data) { double min[6]; double max[6]; for (int i = 0; i < 6; ++i) { min[i] = 9999999; max[i] = -9999999; } int offset = 0; if (data[0].size() == 7) { offset = 1; // ignore first field which is normalized anyway } for (auto &passenger : data) { for (int i = 0 + offset; i < 6 + offset; ++i) { min[i-offset] = std::min(min[i-offset], passenger[i]); max[i-offset] = std::max(max[i-offset], passenger[i]); } } for (auto &passenger : data) { for (int i = 0 + offset; i < 6 + offset; ++i) { passenger[i] = (passenger[i] - min[i-offset])/(max[i-offset] - min[i-offset]); } } } void CreateLearningAndVerificationData(const std::vector<std::vector<double>> &allData, std::vector<std::vector<double>> &learningData, std::vector<std::vector<double>> &verificationData) { learningData.clear(); verificationData.clear(); for (const auto &data : allData) { if (rand() % 1000 < 200) { verificationData.push_back(data); } else { learningData.push_back(data); } } } void VerifyModel(const std::vector<std::vector<double>> &data) { double result = 0; int verificationSetSize = 0; for (int k = 0; k < 1; ++k) { printf("Verification step: %i\n", k); std::vector<std::vector<double>> learningData; std::vector<std::vector<double>> verificationData; CreateLearningAndVerificationData(data, learningData, verificationData); verificationSetSize += verificationData.size(); NeuralNetwork skynet(6, 20, 1); skynet.Learn(learningData); for (const auto &passenger : verificationData) { std::vector<double> input; for (int i = 1; i < passenger.size(); ++i) { input.push_back(passenger[i]); } std::vector<double> ret = skynet.Classify(input); int value = ret[0] < 0.5 ? 0 : 1; printf("Returned: %i Expected: %f\n", value, passenger[0] ); if (value == passenger[0]) { ++result; } } double temp = result / verificationSetSize; temp *= 100; printf("Verification set size: %i\n", verificationSetSize); printf("Results: %f\n", result); printf("Accuracy: %f\n", temp); } } int main() { srand(time(nullptr)); setlocale(LC_ALL, ""); auto data = ReadData("training_set.csv", true); auto testData = ReadData("test_set.csv", false); setlocale(LC_ALL, "C"); NormalizeFields(data); VerifyModel(data); /* NeuralNetwork skynet(6, 20, 1); skynet.Learn(data); std::ofstream out("out.txt"); for (auto p : testData) { auto result = skynet.Classify(p); if (result[0] < 0.5) { out << "0\n"; } else { out << "1\n"; } } */ system("pause"); }
true
01f33a674f090e60b5480c5931640a085e7d7888
C++
masterbulla/Cpp-Event-Driven-Pong
/main_menu_overlay.cpp
UTF-8
1,805
2.640625
3
[]
no_license
#include "main_menu_overlay.h" void main_menu_overlay::AddToDrawingQueue() { Data.DrawingQueue.push({ [this] {this->DrawMainMenu(); }, DrawingPriority::Overlay }); } void main_menu_overlay::DrawMainMenu() { UpdateMenuScreen(); int DrawingCursor = Data.BorderUp.Padding + 2; DrawingCursor += Data.ScreenY / 10; ecur::DrawLineOfText(Data.Screen, DrawingCursor, 0, GameName, Title, A_BOLD); DrawingCursor += Data.ScreenY / 10; MenuScreen->DrawOverlay(DrawingCursor, Data.ScreenY / 12); DrawingCursor = Data.ScreenY - ((Data.BorderDown.Padding > 0) ? Data.BorderDown.Padding : 0) - 2; ecur::DrawLineOfText(Data.Screen, DrawingCursor, 0, Credits, Text); } void main_menu_overlay::SendUserCommand(CommandType Command) { switch (Command) { case (PaddleLeftMoveUp) : case (PaddleRightMoveUp) : MenuScreen->MoveCursor(-1); break; case (PaddleLeftMoveDown) : case (PaddleRightMoveDown) : MenuScreen->MoveCursor(1); break; case (Accept) : MenuScreen->AcceptSelectedOption(); break; case (Exit) : Data.GameShouldEndFlag = true; break; default: break; } } main_menu_overlay::main_menu_overlay(DataBus& Data) : Data{ Data }, MenuScreen{new MainMenuScreen(Data) } { Data.Events.AddHandler<CE::PrepareFrame>([this](Event arg) { this->AddToDrawingQueue(); return HandlerReturnCall::Succeed; }); GameName = "PONG SIMULATOR 2016"; Credits = "Game made by ErykCoa, v 1.4"; } void main_menu_overlay::UpdateMenuScreen() { switch (Data.ChangeMenuScreenTo) { case (SelectedMenuScreen::MainMenu) : MenuScreen.reset(new MainMenuScreen(Data)); break; case (SelectedMenuScreen::ConfiguratonMenu) : MenuScreen.reset(new ConfigurationMenuScreen(Data)); break; default: break; } Data.ChangeMenuScreenTo = SelectedMenuScreen::None; }
true
2cdb3a9ce0bdb71ccb858d3fa4fe8e7f24ad8c88
C++
gregxsunday/Stara-Matura-2016-zadanie-5
/main.cpp
UTF-8
3,586
3.3125
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> using namespace std; struct Field { bool alive[12][20]; Field() { fstream file; string line; int rowc = 0; file.open("gra.txt", ios::in); while(getline(file, line)) { int colc = 0; for(char c : line) { if (c == '.') alive[rowc][colc] = 0; else if (c == 'X') alive[rowc][colc] = 1; colc++; } rowc++; } file.close(); } void show_field() { for(int row = 0; row < 12; row++) { for (int col = 0; col < 20; col++) { cout << alive[row][col];//[i][j]; } cout << endl; } cout << "\n\n"; } int round_row (int row) { if (row < 0) return 11; else if(row > 11) return 0; else return row; } int round_column(int col) { if (col < 0) return 19; else if(col > 19) return 0; else return col; } int count_neighbours(int row, int col) { int neighs = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { int currentrow = round_row(row + i); int currentcol = round_column(col + j); if (alive[currentrow][currentcol] && (currentrow != row || currentcol != col)) neighs++; } } return neighs; } bool still_alive(int row, int col) { int neighs = count_neighbours(row, col); if(alive[row][col] && (neighs == 2 || neighs == 3)) return 1; else if (!(alive[row][col]) && neighs == 3) return 1; else return 0; } void next_gen(Field f) { Field *previousgen = &f; for (int row = 0; row < 12; row++) { for (int col = 0; col < 20; col++) { alive[row][col] = previousgen->still_alive(row, col); } } } int countalive() { int stayinalive = 0; for(int row = 0; row < 12; row++) { for (int col = 0; col < 20; col++) { if(alive[row][col]) stayinalive++; } } return stayinalive; } }; int main() { Field game; vector<Field> thegame; thegame.push_back(game); for (int i = 0; i < 36; i++) { Field newgen; newgen.next_gen(thegame.at(i)); thegame.push_back(newgen); } Field *after = &thegame.back(); after->show_field(); cout << "A) \nW 37. pokoleniu liczba zywych siasiadow dla komorki w 2. wierszu i 19 kolumnie wynosi: " << after->count_neighbours(1, 18) << endl; Field game_b; game_b.next_gen(game_b); cout << "\nB)\nW 2. pokoleniu liczba zywych komorek wynosi: " << game_b.countalive() << endl; Field game_c; int ans_c; vector<Field> thegame_c; thegame_c.push_back(game_c); for(int i = 0; i < 100; i++) { int currentgen = i + 2; bool ans_c = 1; Field newgen, prevgen; prevgen = thegame_c.at(i); newgen.next_gen(thegame_c.at(i)); for(int row = 0; row < 12; row++) { for (int col = 0; col < 20; col++) { if(newgen.alive[row][col] != prevgen.alive[row][col]) ans_c = 0; } } if(ans_c) { cout << "\nC)\nUklad ustali sie w: " << currentgen << " pokoleniu\n"; cout << "Liczba zywych komorek bedzie wynosic: " << newgen.countalive() << endl; break; } thegame_c.push_back(newgen); } return 0; }
true
b1412471eb2909d270d9bea793924842687fd81d
C++
order/lcp-research
/cdiscrete/mcts.h
UTF-8
2,997
2.515625
3
[]
no_license
#ifndef __Z_MCTS_INCLUDED__ #define __Z_MCTS_INCLUDED__ #include <armadillo> #include <vector> #include <iostream> #include <fstream> #include <string> #include "costs.h" #include "function.h" #include "policy.h" #include "simulate.h" #include "transfer.h" #define ACTION_Q 1 #define ACTION_FREQ 2 #define ACTION_ROLLOUT 3 #define ACTION_UCB 4 #define UPDATE_RET_V 1 #define UPDATE_RET_Q 2 #define UPDATE_RET_GAIN 4 using namespace arma; class MCTSNode; //forward declare // List (indexed by action id) of lists of children typedef std::vector<MCTSNode*> NodeList; typedef std::vector<uint> ActionList; typedef std::pair<NodeList,ActionList> Path; struct MCTSContext{ uint _NODE_ID = 0; std::vector<MCTSNode*> master_list; Problem * problem_ptr; uint n_actions; RealFunction * v_fn; MultiFunction * q_fn; ProbFunction * prob_fn; DiscretePolicy * rollout; double p_scale; // weight for initial probability double ucb_scale; // weight for UCB term uint rollout_horizon; double init_q_mult; // Multiplier for init Q estimates double q_min_step; uint update_ret_mode; uint action_select_mode; uint mcts_budget; }; class MCTSNode{ public: MCTSNode(const vec & state, MCTSContext * context); ~MCTSNode(); void print_debug() const; uint get_id() const; vec get_state() const; bool is_leaf() const; bool has_unexplored() const; double get_nudge(uint a_idx) const; vec get_all_nudges() const; vec get_all_ucb_scores() const; double get_ucb_score(uint a_idx) const; uint get_action(uint mode) const; uint get_q_action() const; uint get_freq_action() const; uint get_ucb_action() const; MCTSNode * pick_child(uint a_idx); MCTSNode * sample_new_node(uint a_idx); MCTSNode * add_child(uint a_idx, const vec & state); MCTSNode * find_child(uint a_idx, const vec & state, double thresh=1e-15); double update(uint a_idx, double gain); bool is_fresh() const; void set_stale(); double update_status(uint a_id, double G); friend void write_dot_file(std::string filename, MCTSNode * root); friend void grow_tree(MCTSNode * root, uint budget); friend Path find_path_and_make_leaf(MCTSNode * root); friend double simulate_leaf(Path & path); friend void update_path(const Path & path, double gain); protected: // Identity uint _id; // Node ID vec _state; MCTSContext * _context_ptr; uint _n_actions; double _discount; bool _fresh; // Visit counts uint _total_visits; uvec _child_visits; double _ucb_scale; // Values and costs double _v; vec _q; vec _costs; // Initial probability double _p_scale; vec _prob; uint _n_children; std::vector<NodeList> _children; }; void add_root(MCTSContext * context, MCTSNode * root); void delete_tree(MCTSContext * context); void delete_context(MCTSContext * context); void print_nodes(const MCTSContext & context); string node_name(uint id); string action_name(uint id, uint a_idx); #endif
true
69a5c365e6661bb86856ffbd910290a68b8f2848
C++
MakinoRuki/TopCoder
/SRM620Div1Med.cpp
UTF-8
1,308
2.59375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #define N 52 #define pii pair<int, int> #define mp make_pair using namespace std; class CandidatesSelection { public: int n, m; bool vis[N]; string possible (vector<string> score, vector<int> result) { n = score.size(); m = score[0].size(); vector<pii> cans; cans.clear(); for (int i = 0; i < n - 1; ++i) { cans.push_back(mp(result[i], result[i + 1])); } memset(vis, false, sizeof(vis)); while(true) { int i; for (i = 0; i < cans.size(); ++i) { if (cans[i].first > cans[i].second) break; } if (i >= cans.size()) break; bool ok = false; for (int i = 0; i < m; ++i) { if (vis[i]) continue; int j; for (j = 0; j < cans.size(); ++j) { int u = cans[j].first; int v = cans[j].second; if (score[u][i] > score[v][i]) break; } if (j < cans.size()) continue; ok = true; vis[i] = true; vector<pii> ncans; ncans.clear(); for (j = 0; j < cans.size(); ++j) { int u = cans[j].first; int v = cans[j].second; if (score[u][i] == score[v][i]) ncans.push_back(cans[j]); } cans = ncans; break; } if (!ok) return "Impossible"; } return "Possible"; } };
true
c30dfd3747cf3f1a5e4e192f0e5f336cce065038
C++
mariolew/CS106B
/practiceMid2/simple-project/src/hello.cpp
UTF-8
2,630
3.34375
3
[]
no_license
#include <iostream> #include "hello.h" #include "console.h" #include "vector.h" #include "map.h" using namespace std; /* Function Prototypes */ string removeDoubledLetters(string str); void tryAllOperators(string exp, int target); void tryAllOperatorsRec(string prefix, string rest, int target); Vector<int> extract3x3Subsquare(Grid<int> & grid,int bigRow, int bigCol); int countHailstoneSteps(int n, Map<int,int> & cache); int countHailstoneStepsRec(int n, Map<int,int> & cache); int main() { cout << "Hello, World!" << endl; return 0; } string removeDoubledLetters(string str) { if (str.length() <= 1) return str; else { if (str[0] == str[1]) return removeDoubledLetters(str.substr(1)); else return str[0] + removeDoubledLetters(str.substr(1)); } } void tryAllOperators(string exp, int target) { tryAllOperatorsRec("", exp, target); } void tryAllOperatorsRec(string prefix, string rest, int target) { if (evaluateExpression(prefix) == target && rest == "") cout << prefix << endl; if (rest[0] == '?') { rest = rest.substr(1); tryAllOperatorsRec(prefix + '+', rest, target); tryAllOperatorsRec(prefix + '-', rest, target); tryAllOperatorsRec(prefix + '*', rest, target); tryAllOperatorsRec(prefix + '/', rest, target); } else { tryAllOperatorsRec(prefix + rest[0], rest.substr(1), target); } } Vector<int> extract3x3Subsquare(Grid<int> & grid,int bigRow, int bigCol) { Vector<int> subsquare; for (int i = bigRow * 3; i < bigRow * 4; i++) { for (int j = bigCol * 3; j < bigRow * 4; j++) { subsquare.add(grid[i][j]); } } return subsquare; } int countHailstoneSteps(int n, Map<int,int> & cache) { int len = 0; while (n != 1) { if (cache.containsKey(n)) { len += cache[n]; break; } else { if (n % 2 == 0) n /= 2; else n = 3 * n + 1; len++; } } if (!cache.containsKey(n)) cache[n] = len; return len; } int countHailstoneStepsRec(int n, Map<int,int> & cache) { if (cache.containsKey(n)) return cache[n]; if (n == 1) return 0; else { int count = 0; if (n % 2 ==0) { count = countHailstoneStepsRec(n / 2, cache) + 1; } else { count = countHailstoneStepsRec(3 * n + 1, cache) + 1; } cache[n] = count; return count; } }
true
34bcc325d34f06318ea2363e80424456a0ed1f42
C++
mattiatritto/arduinoProjects
/03. LED RGB/LED_RGB_software/LED_RGB_software.ino
UTF-8
1,305
2.625
3
[]
no_license
const int Pin_Led_Verde = 9; const int Pin_Led_Rosso = 11; const int Pin_Led_Blu = 10; const int Pin_Sensore_Rosso = A0; const int Pin_Sensore_Verde = A1; const int Pin_Sensore_Blu = A2; int Valore_Rosso = 0; int Valore_Verde = 0; int Valore_Blu = 0; int Valore_Sensore_Rosso = 0; int Valore_Sensore_Verde = 0; int Valore_Sensore_Blu = 0; void setup() { Serial.begin(9600); //Apre la comunicazione seriale con il computer. pinMode(Pin_Led_Verde, OUTPUT); pinMode(Pin_Led_Rosso, OUTPUT); pinMode(Pin_Led_Blu, OUTPUT); } void loop() { Valore_Sensore_Rosso = analogRead(Pin_Sensore_Rosso); delay(5); Valore_Sensore_Verde = analogRead(Pin_Sensore_Verde); delay(5); Valore_Sensore_Blu = analogRead(Pin_Sensore_Blu); Valore_Rosso = Valore_Sensore_Rosso/4; //Divide per quattro la lettura dei sensori. Valore_Verde = Valore_Sensore_Verde/4; Valore_Blu = Valore_Sensore_Blu/4; Serial.print("\n Valori\t Rosso: "); Serial.print(Valore_Rosso); Serial.print("\t Verde: "); Serial.print(Valore_Verde); Serial.print("\t Blu: "); Serial.print(Valore_Blu); analogWrite(Pin_Led_Rosso, Valore_Rosso); analogWrite(Pin_Led_Verde, Valore_Verde); analogWrite(Pin_Led_Blu, Valore_Blu); }
true
050062f62eb8fbebde700aebedcb87ba55c5c040
C++
gary-robotics/vision_lane_detection
/test/Spline.cpp
UTF-8
3,476
2.984375
3
[]
no_license
/** * @file Spline.cpp * @author: Kuang Fangjun <csukuangfj at gmail dot com> * @date July 02, 2018 */ #include <glog/logging.h> #include <gtest/gtest.h> #include <fstream> // NOLINT #include <vector> #include "lane_line/Spline.h" class SplineTest : public ::testing::Test { protected: tt::Spline spline_; }; /* * data from http://fac.ksu.edu.sa/sites/default/files/textbook-9th_edition.pdf * page 147 */ TEST_F(SplineTest, case1) { std::vector<tt::Point> points = { {1, 2}, {2, 3}, {3, 5} }; spline_.compute(points); LOG(INFO) << spline_.toString(); auto &seg = spline_.getSegments(); EXPECT_EQ(seg.size(), 2); const float eps = 1e-6; EXPECT_NEAR(seg[0].a_, 2, eps); EXPECT_NEAR(seg[0].b_, 3.f/4, eps); EXPECT_NEAR(seg[0].c_, 0, eps); EXPECT_NEAR(seg[0].d_, 1.f/4, eps); EXPECT_NEAR(seg[0].x_, 1, eps); EXPECT_NEAR(seg[1].a_, 3, eps); EXPECT_NEAR(seg[1].b_, 3.f/2, eps); EXPECT_NEAR(seg[1].c_, 3.f/4, eps); EXPECT_NEAR(seg[1].d_, -1.f/4, eps); EXPECT_NEAR(seg[1].x_, 2, eps); } /* * data from http://fac.ksu.edu.sa/sites/default/files/textbook-9th_edition.pdf * page 150 */ TEST_F(SplineTest, case2) { std::vector<tt::Point> points = { {0, 1}, {1, std::exp(1)}, {2, std::exp(2)}, {3, std::exp(3)}, }; spline_.compute(points); LOG(INFO) << spline_.toString(); auto &seg = spline_.getSegments(); EXPECT_EQ(seg.size(), 3); const float eps = 1e-3; EXPECT_NEAR(seg[0].a_, 1, eps); EXPECT_NEAR(seg[0].b_, 1.46600f, eps); EXPECT_NEAR(seg[0].c_, 0, eps); EXPECT_NEAR(seg[0].d_, 0.25228f, eps); EXPECT_NEAR(seg[0].x_, 0, eps); EXPECT_NEAR(seg[1].a_, 2.71828f, eps); EXPECT_NEAR(seg[1].b_, 2.22285f, eps); EXPECT_NEAR(seg[1].c_, 0.75685f, eps); EXPECT_NEAR(seg[1].d_, 1.69107f, eps); EXPECT_NEAR(seg[1].x_, 1, eps); EXPECT_NEAR(seg[2].a_, 7.38906f, eps); EXPECT_NEAR(seg[2].b_, 8.80977f, eps); EXPECT_NEAR(seg[2].c_, 5.83007f, eps); EXPECT_NEAR(seg[2].d_, -1.94336, eps); EXPECT_NEAR(seg[2].x_, 2, eps); } /* * data is from course slide http://banach.millersville.edu/~bob/math375/CubicSpline/main.pdf * page 8 * */ TEST_F(SplineTest, case3) { std::vector<tt::Point> points = { {5, 5}, {7, 2}, {9, 4}, }; spline_.compute(points); LOG(INFO) << spline_.toString(); auto &seg = spline_.getSegments(); EXPECT_EQ(seg.size(), 2); const float eps = 1e-6; EXPECT_NEAR(seg[0].a_, 5, eps); EXPECT_NEAR(seg[0].b_, -17/8.f, eps); EXPECT_NEAR(seg[0].c_, 0, eps); EXPECT_NEAR(seg[0].d_, 5/32.f, eps); EXPECT_NEAR(seg[0].x_, 5, eps); EXPECT_NEAR(seg[1].a_, 2, eps); EXPECT_NEAR(seg[1].b_, -1/4.f, eps); EXPECT_NEAR(seg[1].c_, 15/16.f, eps); EXPECT_NEAR(seg[1].d_, -5/32.f, eps); EXPECT_NEAR(seg[1].x_, 7, eps); } /** * gnuplot * gnuplot> plot "/tmp/a.txt" w lp */ TEST_F(SplineTest, case4) { std::vector<tt::Point> points = { {0, 0}, {0.5*M_PI, 1}, {M_PI, 0}, {1.5*M_PI, -1}, {2*M_PI, 0}, }; auto pp = spline_.interpolate(points, 50); std::stringstream ss; for (const auto &p : pp) { ss << p.x() << " " << p.y() << "\n"; } std::ofstream of("/tmp/a.txt", std::ofstream::out); of << ss.str(); of.close(); LOG(INFO) << ss.str(); }
true
06bf8b9fd0d554228ba43b16050a3e97ab3a46b1
C++
andrewtrotman/JASSv2
/source/compress_integer_stream_vbyte.h
UTF-8
2,933
2.84375
3
[]
no_license
/* COMPRESS_INTEGER_STREAM_VBYTE.H ------------------------------- Copyright (c) 2016 Andrew Trotman Released under the 2-clause BSD license (See:https://en.wikipedia.org/wiki/BSD_licenses) */ /*! @file @brief Interface to Lemire's Stream VByte source code. @author Andrew Trotman @copyright 2016 Andrew Trotman */ #pragma once #include "compress_integer.h" namespace JASS { /* CLASS COMPRESS_INTEGER_STREAM_VBYTE ----------------------------------- */ /*! @brief Stream VByte is an SIMD byte-aligned encoding scheme by Lemire et al. @details A byte-aligned encoding scheme that places the selectors before the payloads and uses SIMD instructions to decode. See: D. Lemire, N. Kurz, C. Rupp (2018), Stream VByte: Faster byte-oriented integer compression, Information Processing Letters 130:(1-6) */ class compress_integer_stream_vbyte : public compress_integer { public: /* COMPRESS_INTEGER_STREAM_VBYTE::COMPRESS_INTEGER_VARIABLE_BYTE() --------------------------------------------------------------- */ /*! @brief Constructor. */ compress_integer_stream_vbyte() { /* Nothing */ } /* COMPRESS_INTEGER_STREAM_VBYTE::~COMPRESS_INTEGER_VARIABLE_BYTE() ---------------------------------------------------------------- */ /*! @brief Constructor. */ virtual ~compress_integer_stream_vbyte() { /* Nothing */ } /* COMPRESS_INTEGER_STREAM_VBYTE::ENCODE() --------------------------------------- */ /*! @brief Encode a sequence of integers returning the number of bytes used for the encoding, or 0 if the encoded sequence doesn't fit in the buffer. @param encoded [out] The sequence of bytes that is the encoded sequence. @param encoded_buffer_length [in] The length (in bytes) of the output buffer, encoded. @param source [in] The sequence of integers to encode. @param source_integers [in] The length (in integers) of the source buffer. @return The number of bytes used to encode the integer sequence, or 0 on error (i.e. overflow). */ virtual size_t encode(void *encoded, size_t encoded_buffer_length, const integer *source, size_t source_integers); /* COMPRESS_INTEGER_STREAM_VBYTE::DECODE() --------------------------------------- */ /*! @brief Decode a sequence of integers encoded with this codex. @param decoded [out] The sequence of decoded integers. @param integers_to_decode [in] The minimum number of integers to decode (it may decode more). @param source [in] The encoded integers. @param source_length [in] The length (in bytes) of the source buffer. */ virtual void decode(integer *decoded, size_t integers_to_decode, const void *source, size_t source_length); /* COMPRESS_INTEGER_STREAM_VBYTE::UNITTEST() ----------------------------------------- */ /*! @brief Unit test this class */ static void unittest(void); } ; }
true
61643b5baef74710323547c166bd40a79b5f85fe
C++
ProjektarbeitPapeWS16/ClassicGameFramework
/ClassicGameFramework/Display.h
UTF-8
372
2.640625
3
[]
no_license
#pragma once #include <vector> class Drawable; class Display { std::vector<Drawable*>* drawables = new std::vector<Drawable*>(); public: std::vector<Drawable*>* getDrawables() const; void setDrawables(std::vector<Drawable*>* drawables); void addDrawable(Drawable* drawable) const; void removeDrawable(Drawable* drawable) const; void clearDrawables() const; };
true
e0ba3c808035fba5ef722eb57eb1411838538958
C++
Brilliantrocks/leetcodelib
/318test.cpp
UTF-8
962
3.109375
3
[]
no_license
#include<vector> #include<string> #include<iostream> using namespace std; class Solution { public: int maxProduct(vector<string>& words) { int n = words.size(),ans=0; vector<int> mask(n,0); vector<int> size(n,0); for (int i = 0; i < n; ++i) { size[i] = words[i].size(); for(auto x:words[i]){ mask[i] |= 1 << (x - 'a'); } cout<<"mask["<<i<<"] "<<mask[i]<<endl; for(int j =0;j<i;++j){ int m =mask[j]&mask[i]; cout<<m<<endl; if(m==0){ ans=max(ans,size[i]*size[j]); } } } return ans; } }; main(){ Solution s1; vector<string> s = {"abcw","baz","foo","bar","xtfn","abcdef"}; int ans = s1.maxProduct(s); cout<<ans<<endl; // int a = 0,b='w'-'a'; // a= 1 << b; // cout<<b<<endl; // cout<<a<<endl; }
true
6d7a6bc5c8a02db9fba8cc4bf42e6d75977b6f40
C++
cherry247/Code-Jam-2020
/nesting depth.cpp
UTF-8
1,415
2.640625
3
[]
no_license
//nesting depth #include<iostream> #include <bits/stdc++.h> #define int long long //toggles on or off the synchronization (this is used for faster I/O #define Fastio ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); using namespace std; signed main() { Fastio int t; int k=1; cin>>t; //for the test case while(t--) { string st; //input a string cin>>st; int pt=0; int y; int g=st[0]-'0'; string ans=""; if(g==0) { ans+="0"; } else{ pt=g; while(g--) { ans+="("; } ans+=st[0]; } for(int i=1;i<st.length();i++) { x=st[i]-'0'; y=st[i-1]-'0'; if(y>x) { int z=y-x; pt=pt-z; while(z--) { ans+=")"; } ans+=st[i]; } else if(x>y) { int z=x-y; pt+=z; while(z--) { ans+="("; } ans+=st[i]; } else{ ans+=st[i]; } } while(pt--) { ans+=")"; } //Case #1: 0000 cout<<"Case #"<<k++<<": "<<ans<<endl; } }
true
5d38b5c9687b5dd82269cfbe5f6a9436cb3da41d
C++
morgan-139117/oop2
/Painting.cpp
UTF-8
2,167
2.609375
3
[]
no_license
#include "Painting.h" int Painting::timeval_to_msec(struct timeval *t) { return t->tv_sec*1000+t->tv_usec/1000; } int Painting::current_msec() { struct timeval t; gettimeofday(&t,0); return timeval_to_msec(&t); } bool Painting::same_artist(String _fname, String _lname){ if ( fname == _fname && lname == _lname ){ return true; }else{ return false; }; } bool Painting:: dup_painting(ulong _id){ if ( id == _id ){ return true; }else{ return false; }; } bool Painting:: dup_painting(String _title, String _fname, String _lname){ if ( title == _title && fname == _fname && lname == _lname ){ return true; }else{ return false; }; } bool Painting:: operator==(const Painting & obj){ if( fname == obj.fname && lname == obj.lname && title == obj.title && h == obj.h && w == obj.w ) return true; return false; }; Painting::Painting(const Painting & src){ if(NULL!=&src){ fname=src.fname; lname=src.lname; id = src.id; title=src.title; lname=src.lname; h=src.h; w=src.w; } }; void Painting::deep_copy_(const Painting & src){ if(&src){ fname=src.fname; lname=src.lname; char tmp[10]; char ccopy[]=" version2"; //Painting::incre_title_number(); //sprintf(tmp,"%d",Painting::title_number()); String scopy=String(ccopy); // String stmp=String(tmp); title=src.title + scopy; // title=title; lname=src.lname; h=src.h; w=src.w; } }; /* int main(){ String first; String last; String title; int h; int w; cin>>first>>last>>title>>h>>w; Painting *p=new Painting(first,last,title,h,w); Painting *q=new Painting (*p); cout<<"q"<<*q; delete(p); cout<<*q; Painting *o=new Painting(*q); if(*o==*o) cout<<"*o==*q"; else cout<<"noo"; if(*o==*q) cout<<"*o==*q"; else cout<<"noo"; if(o==q) cout<<"o==q"; else cout<<"noo"; cout<<o->get_title(); return 0; } */
true
cb5cb83b99c9929ec9787a3c466a7482b43c79fe
C++
anirudhtomer/UndergradCAssignments
/TREES/CONVERSION TO A TREE WHEN (IN & PRE)order traversals are given.CPP
UTF-8
4,587
3.421875
3
[]
no_license
/* TO CREATE A TREE FROM A GIVEN preorder & inorder SEQUENCE */ #include<iostream.h> #include<conio.h> class node { char data; node *left,*right; public: node() { data = '@'; left = NULL; right = NULL; } friend class stackk; friend class btree; }; class array { char *arr; array *down; public: array() { arr = NULL; down = NULL; } friend class stackk; friend class btree; }; class stackk { array *top; public: stackk() { top = NULL; } int empty() { if(top==NULL) return 1; return 0; } void pushit(array *psharr) { psharr->down = top; top = psharr; } array* popit() { array *retpop; retpop = top; top = top->down; retpop->down = NULL; return retpop; } }; class btree { node *root; char *oriprearr,*oriinarr; array *tempprearr,*tempinarr; int n; const int LEFT,RIGHT; stackk s1; public: btree():LEFT(48),RIGHT(49) { n = 0; root = new node; oriprearr = NULL; oriinarr = NULL; tempprearr = NULL; tempinarr = NULL; } ~btree() { delete []tempprearr->arr; delete []tempinarr->arr; delete tempprearr; delete tempinarr; delete []oriprearr; delete []oriinarr; } void enter(); void inorder(node*); void conversion(); node* search(char,node*); void inorder() { inorder(root); cout<<"\b "; } }; int main() { btree b1; clrscr(); b1.enter(); b1.conversion(); getch(); clrscr(); cout<<"THE CONVERTED TREE IS (inorder):-\t"; b1.inorder(); getch(); return 0; } //ENTER THE PREORDER & INORDER ARRAYS void btree::enter() { int i; cout<<"\n\nENTER THE NUMBER OF NODES IN THE ARRAY:-\t"; cin>>n; oriprearr = new char[n+1]; oriinarr = new char[n+1]; tempprearr = new array; tempinarr = new array; tempprearr->arr = new char[n+1]; tempinarr->arr = new char[n+2]; cout<<"\n\nENTER THE PREORDER TRAVERSAL:-\t"; cin>>oriprearr; for(i=0;i<=n;i++) *(tempprearr->arr + i) = *(oriprearr+i); cout<<"\n\nENTER THE INORDER TRAVERSAL:-\t"; cin>>oriinarr; tempinarr->arr[0] = LEFT; for(i=0;i<=n;i++) tempinarr->arr[i+1] = *(oriinarr+i); } //CONVERSION TO A TREE void btree::conversion() { int i,j; int cnt = 0,pcnt = 0,clcnt = 0 ,crcnt = 0; array *parent[5],*cleft[5],*cright[5]; node *temp; temp = root; for(i=0;i<5;i++) { parent[i] = new array; cleft[i] = new array; cright[i] = new array; cleft[i]->arr = new char[20]; cright[i]->arr = new char[20]; parent[i]->arr = new char[2]; *( (*(cleft+i))->arr + 0) = LEFT; //cleft[i]->arr[0] cright[i]->arr[0] = RIGHT; parent[i]->arr[0] = root->data; parent[i]->arr[1] = '\0'; } s1.pushit(tempinarr); clcnt++; s1.pushit(parent[pcnt++]); while(!s1.empty()) { parent[--pcnt] = s1.popit(); tempinarr = s1.popit(); if(tempinarr->arr[0]==LEFT) clcnt--; else crcnt--; temp = search(parent[pcnt]->arr[0],root); if(tempinarr->arr[0] == LEFT) { temp->left = new node; temp->left->data = tempprearr->arr[cnt++]; temp = temp->left; } else { temp->right = new node; temp->right->data = tempprearr->arr[cnt++]; temp = temp->right; } for(i=1;tempinarr->arr[i]!=temp->data;i++) cleft[clcnt]->arr[i] = tempinarr->arr[i]; cleft[clcnt]->arr[i] = '\0'; for(i++,j=1;tempinarr->arr[i]!='\0';i++,j++) cright[crcnt]->arr[j] = tempinarr->arr[i]; cright[crcnt]->arr[j] = '\0'; if(cright[crcnt]->arr[1] != '\0') { parent[pcnt]->arr[0] = temp->data; s1.pushit(cright[crcnt++]); s1.pushit(parent[pcnt++]); } if(cleft[clcnt]->arr[1] != '\0') { parent[pcnt]->arr[0] = temp->data; s1.pushit(cleft[clcnt++]); s1.pushit(parent[pcnt++]); } } temp = root; root = root->left; delete(temp); for(i=0;i<5;i++) { delete []parent[i]->arr; delete []cleft[i]->arr; delete []cright[i]->arr; delete parent[i]; delete cleft[i]; delete cright[i]; } } //INORDER TRAVERSAL TO CHECK THE RESULT void btree::inorder(node *jade) { if(jade->left!=NULL) inorder(jade->left); cout<<jade->data<<","; if(jade->right!=NULL) inorder(jade->right); } //SEARCH node* btree::search(char tar,node *jade) { if(tar == jade->data) return jade; if(jade->left!=NULL) search(tar,jade->left); if(jade->right!=NULL) search(tar,jade->right); }
true
82a03a11e949ccc84168367fd98e657eb8b84947
C++
hugomarquez/cpp-toolkit
/src/sdl/Renderer.cpp
UTF-8
1,114
3.015625
3
[ "MIT" ]
permissive
#include "Renderer.h" namespace hm { Renderer::Renderer(Window& w, int i) : window(w), index(i) { setFlags(0); } Renderer::~Renderer() { destroySDLRenderer(); } bool Renderer::createSDLRenderer() { // Create SDL renderer renderer = SDL_CreateRenderer(window.getSDLWindow(), index, flags); if (renderer == 0) { return false; } return true; } bool Renderer::setDrawColor(Color& c) { return SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, c.a); } bool Renderer::clear() { // clear the renderer to the draw color return SDL_RenderClear(renderer); } void Renderer::present() { // draw to the screen SDL_RenderPresent(renderer); } void Renderer::setFlags(int f) { switch (f) { case 1: flags = SDL_RENDERER_SOFTWARE; break; case 2: flags = SDL_RENDERER_ACCELERATED; break; case 3: flags = SDL_RENDERER_PRESENTVSYNC; break; case 4: flags = SDL_RENDERER_TARGETTEXTURE; break; default: flags = 0; break; } } void Renderer::destroySDLRenderer() { SDL_DestroyRenderer(renderer); } }
true
d9056247ebc64fa27e1961630a3de1911466349d
C++
aayushi-kunwar13/algs4cplusplus
/ch4/head/EdgeWeightedDigraph.h
UTF-8
8,296
3.484375
3
[]
no_license
#ifndef CH4_EDGEWEIGHTEDDIGRAPH_H #define CH4_EDGEWEIGHTEDDIGRAPH_H #include "../head/DirectedEdge.h" #include <vector> #include <forward_list> #include <random> #include <fstream> #include <sstream> #include <iostream> using std::vector; using std::forward_list; using std::uniform_int_distribution; using std::to_string; using std::string; using std::fstream; using std::distance; using std::stringstream; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of {@link Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="https://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ class EdgeWeightedDigraph { public: /** * Initializes an empty edge-weighted digraph with {@code V} vertices and 0 edges. * * @param V the number of vertices * @throws IllegalArgumentException if {@code V < 0} */ EdgeWeightedDigraph(int V) : V(V), E(0), indegree(V, 0), adj(V) { if (V < 0) throw runtime_error("Number of vertices in a Digraph must be nonnegative"); } /** * Initializes a random edge-weighted digraph with {@code V} vertices and <em>E</em> edges. * * @param V the number of vertices * @param E the number of edges * @throws IllegalArgumentException if {@code V < 0} * @throws IllegalArgumentException if {@code E < 0} */ EdgeWeightedDigraph(int V, int E) : EdgeWeightedDigraph(V) { if (E < 0) throw runtime_error("Number of edges in a Digraph must be nonnegative"); uniform_int_distribution<> dis(0, V - 1); uniform_int_distribution<> dis1(0, 100); for (int i = 0; i < E; i++) { int v = dis(g); int w = dis(g); double weight = 0.01 * dis1(g); DirectedEdge e(v, w, weight); addEdge(e); } } /** * Initializes an edge-weighted digraph from the specified input stream. * The format is the number of vertices <em>V</em>, * followed by the number of edges <em>E</em>, * followed by <em>E</em> pairs of vertices and edge weights, * with each entry separated by whitespace. * * @param in the input stream * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range * @throws IllegalArgumentException if the number of vertices or edges is negative */ EdgeWeightedDigraph(string filename) { fstream in(filename); in >> V; E = 0; indegree.resize(V, 0); adj.resize(V); int tmpE; in >> tmpE; if (tmpE < 0) throw runtime_error("Number of edges must be nonnegative"); int v, w; double weight; for (int i = 0; i < tmpE; i++) { in >> v >> w; validateVertex(v); validateVertex(w); in >> weight; addEdge(DirectedEdge(v, w, weight)); } } /** * Initializes a new edge-weighted digraph that is a deep copy of {@code G}. * * @param G the edge-weighted digraph to copy */ EdgeWeightedDigraph(const EdgeWeightedDigraph &G) : EdgeWeightedDigraph(G.V_()) { E = G.E_(); for (int v = 0; v < G.V_(); v++) indegree[v] = G.indegree_(v); for (int v = 0; v < G.V_(); v++) { // reverse so that adjacency list is in same order as original forward_list<DirectedEdge> reverse; for (DirectedEdge e : G.adj[v]) { reverse.push_front(e); } for (DirectedEdge e : reverse) { adj[v].push_front(e); } } } /** * Returns the number of vertices in this edge-weighted digraph. * * @return the number of vertices in this edge-weighted digraph */ int V_() const { return V; } /** * Returns the number of edges in this edge-weighted digraph. * * @return the number of edges in this edge-weighted digraph */ int E_() const { return E; } /** * Adds the directed edge {@code e} to this edge-weighted digraph. * * @param e the edge * @throws IllegalArgumentException unless endpoints of edge are between {@code 0} * and {@code V-1} */ void addEdge(DirectedEdge e) { int v = e.from(); int w = e.to(); validateVertex(v); validateVertex(w); adj[v].push_front(e); indegree[w]++; E++; } /** * Returns the directed edges incident from vertex {@code v}. * * @param v the vertex * @return the directed edges incident from vertex {@code v} as an Iterable * @throws IllegalArgumentException unless {@code 0 <= v < V} */ forward_list<DirectedEdge> adj_(int v) const { validateVertex(v); return adj[v]; } /** * Returns the number of directed edges incident from vertex {@code v}. * This is known as the <em>outdegree</em> of vertex {@code v}. * * @param v the vertex * @return the outdegree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ int outdegree(int v) const { validateVertex(v); return distance(adj[v].begin(), adj[v].end()); } /** * Returns the number of directed edges incident to vertex {@code v}. * This is known as the <em>indegree</em> of vertex {@code v}. * * @param v the vertex * @return the indegree of vertex {@code v} * @throws IllegalArgumentException unless {@code 0 <= v < V} */ int indegree_(int v) const { validateVertex(v); return indegree[v]; } /** * Returns all directed edges in this edge-weighted digraph. * To iterate over the edges in this edge-weighted digraph, use foreach notation: * {@code for (DirectedEdge e : G.edges())}. * * @return all edges in this edge-weighted digraph, as an iterable */ forward_list<DirectedEdge> edges() { forward_list<DirectedEdge> list; for (int v = 0; v < V; v++) { for (DirectedEdge e : adj_(v)) { list.push_front(e); } } return list; } /** * Returns a string representation of this edge-weighted digraph. * * @return the number of vertices <em>V</em>, followed by the number of edges <em>E</em>, * followed by the <em>V</em> adjacency lists of edges */ friend ostream &operator<<(ostream &stream, const EdgeWeightedDigraph &e) { stringstream ss; ss << e.V << " " << e.E << std::endl; for (int v = 0; v < e.V; ++v) { ss << v << ": "; for (auto de: e.adj[v]) ss << de << " "; ss << std::endl; } stream << ss.str(); return stream; } private: // throw an IllegalArgumentException unless {@code 0 <= v < V} void validateVertex(int v) const { if (v < 0 || v >= V) throw runtime_error("vertex " + to_string(v) + " is not between 0 and " + to_string(V - 1)); } private: int V; // number of vertices in this digraph int E; // number of edges in this digraph vector<forward_list<DirectedEdge>> adj; // adj[v] = adjacency list for vertex v vector<int> indegree; // indegree[v] = indegree of vertex v }; #endif //CH4_EDGEWEIGHTEDDIGRAPH_H
true
510b49116ffaa64dc7595ed5cfcfb66e3b87bfe5
C++
ArturKaminskiSzczecin/TestC-
/mojaclasatestowa.cpp
UTF-8
470
3.390625
3
[]
no_license
#include<iostream> #include<string> class User{ private: std::string name = "Artur"; int age = 5; public: void userAsk(); void setAge(int newAge){ this->age = newAge; } void getName(){ std::cout << this->name << ": " << this->age << std::endl; } }; void User::userAsk(){ std::cout << "What is his age" << std::endl; } int main(){ User artur; artur.getName(); artur.setAge(10); artur.getName(); artur.userAsk(); return 0; }
true
fec0d815d3e872694042f5ad6b8c772ec202839a
C++
MGniew/MeWeX
/mwextractor/mwextractor/structure/storage/RawFrequencyStorage.cpp
UTF-8
3,591
2.59375
3
[]
no_license
/* * RawFrequencyStorage.cpp * * Created on: 08-07-2014 * Author: michalw */ #include <sstream> #include "../../utils/Math.h" #include "RawFrequencyStorage.h" namespace structure { namespace storage { RawFrequencyStorage::RawFrequencyStorage( double pGlobalFrequency, size_t pSourceCount) : mGlobalFrequency(pGlobalFrequency), mLocalFrequencies(pSourceCount, 0) { } RawFrequencyStorage::RawFrequencyStorage( double pGlobalFrequency, FrequencyVector pSourceFrequencies) : mGlobalFrequency(pGlobalFrequency), mLocalFrequencies(pSourceFrequencies) { } void RawFrequencyStorage::addNewLocalFrequency(size_t pSource, size_t pFrequency) { if (pSource >= getSourceCount()) { mLocalFrequencies.resize(pSource + 1); } mLocalFrequencies[pSource] = pFrequency; } void RawFrequencyStorage::addFrequencies(RawFrequencyStorage const& pStorage) { if (pStorage.getSourceCount() > getSourceCount()) { mLocalFrequencies.resize(pStorage.getSourceCount()); } for (size_t i = 0; i < pStorage.mLocalFrequencies.size(); ++i) { mLocalFrequencies[i] += pStorage.mLocalFrequencies[i]; } mGlobalFrequency += pStorage.mGlobalFrequency; } void RawFrequencyStorage::subtractFrequencies(RawFrequencyStorage const& pStorage) { for (size_t i = 0; i < pStorage.mLocalFrequencies.size(); ++i) { mLocalFrequencies[i] -= pStorage.mLocalFrequencies[i]; } mGlobalFrequency -= pStorage.mGlobalFrequency; } double RawFrequencyStorage::getGlobalFrequency() const { return mGlobalFrequency; } size_t RawFrequencyStorage::getSourceCount() const { return mLocalFrequencies.size(); } size_t RawFrequencyStorage::getLocalFrequency(size_t pSource) const { return mLocalFrequencies[pSource]; } void RawFrequencyStorage::setGlobalFrequency(double pFrequency) { mGlobalFrequency = pFrequency; } void RawFrequencyStorage::setLocalFrequency(size_t pSource, size_t pFrequency) { mLocalFrequencies[pSource] = pFrequency; } void RawFrequencyStorage::modifyGlobalFrequency(double pDelta) { mGlobalFrequency += pDelta; } void RawFrequencyStorage::modifyLocalFrequency(size_t pSource, size_t pDelta) { mLocalFrequencies[pSource] += pDelta; } void RawFrequencyStorage::modifyFrequency(size_t pSource, size_t pDelta) { modifyLocalFrequency(pSource, pDelta); mGlobalFrequency += pDelta; } double RawFrequencyStorage::sumLocalFrequencies() const { return utils::sum<double>(mLocalFrequencies.begin(), mLocalFrequencies.end()); } void RawFrequencyStorage::computeGlobalFrequency() { mGlobalFrequency = sumLocalFrequencies(); } size_t RawFrequencyStorage::countNonZeroSources() const { size_t c = 0; for (size_t i = 0; i < mLocalFrequencies.size(); ++i) { if (mLocalFrequencies[i] != 0) { ++c; } } return c; } std::ostream& RawFrequencyStorage::writeFrequenciesReprezentation(std::ostream& pStream) const { for (size_t i = 0; i < mLocalFrequencies.size(); ++i) { pStream << mLocalFrequencies[i]; if (i < mLocalFrequencies.size() - 1) { pStream << '\t'; } } return pStream; } std::string RawFrequencyStorage::createFrequenciesReprezentation() const { std::stringstream str; writeFrequenciesReprezentation(str); return str.str(); } auto RawFrequencyStorage::begin() const -> ValueIteratorConst { return mLocalFrequencies.begin(); } auto RawFrequencyStorage::begin() -> ValueIterator { return mLocalFrequencies.begin(); } auto RawFrequencyStorage::end() const -> ValueIteratorConst { return mLocalFrequencies.end(); } auto RawFrequencyStorage::end() -> ValueIterator { return mLocalFrequencies.end(); } } }
true
489582a05a03fe53a33ce1bfccd7026d21681093
C++
Stefan28BU/CSI1440_IntroToComputerScience2_Programs
/pc15-5/filter.h
UTF-8
588
2.59375
3
[]
no_license
/* * author: Yufan Xu * assignment: program challenge 15-5 * date due: 10/27/2017 */ #ifndef PC15_5_FILTER_H #define PC15_5_FILTER_H #include <fstream> using namespace std; class Filter { public: virtual char transform(char ) = 0; void doFilter(ifstream &in, ofstream &out); }; class Encrypt:public Filter { private: int key; public: Encrypt(int ); virtual char transform(char ); }; class ToUpper:public Filter { public: virtual char transform(char ); }; class Copy:public Filter { public: virtual char transform(char ); }; #endif //PC15_5_FILTER_H
true
078e7f2de361ce67a488a4ecdba7e96cd510d453
C++
uejun/FoodAR
/FoodModification/Model/featureReference.h
UTF-8
2,026
2.5625
3
[]
no_license
#ifndef FEATUREREFERENCE_H #define FEATUREREFERENCE_H #include "./Param/colorThreshold.h" #include "../Utils/xmlUtils.h" #include "./Param/channelFunc/channelFunc.h" #include "./TypeDef.h" class FeatureReference { /*method*/ public: static FeatureReference& getInstance(); void loadFeaturesFromFile(QDomDocument doc); void updateAverages(vint averages) { _colorThresholds[1].updateAverages(averages); } void updateMedianAndTolerance(vint medians, vint upperTolerances, vint underTolerances) { _colorThresholds[1].updateMedianAndTolerance(medians, upperTolerances, underTolerances); } void updateThresholds(QVis averages, QVis tolerances); bool isWithinThreshold(MatSet& matSet, Point& point) { // if( _colorThresholds[1].isWithinThreshold(matSet, point)) { // return true; // } else if ( _colorThresholds[0].isWithinThreshold(matSet, point)) { // return true; // } else { // return false; // } if( _colorThresholds[1].isWithinThreshold(matSet, point)) { return true; } else { return false; } } void updateEngagedChannels(const vector<ChannelType> list, const int thresholdIndex); /** * リアルタイムの閾値調整 * @param degree 閾値の変更度合い * @param type どのチャンネルの閾値を変更するか * @param index 何個目のcolorThreshold か * @see ColorThresholdクラスのupdateChannelThresholdValue() */ void updateChannelThresholdValue(int degree, ChannelType type, int index); void displayThreshold(); int channelThresholdDegree(ChannelType type, int index){ return _colorThresholds[0].channelThresholdDegree(type); //ほんとはindexで区別すべし } private: FeatureReference(); FeatureReference(const FeatureReference&); /*property*/ private: vector<ColorThreshold> _colorThresholds; }; #endif // FEATUREREFERENCE_H
true
a659da7e890930c47b12087d26ff4c4875c18d88
C++
KsGin-Fork/DX11Tutorial
/DX11Tutorial-Instancing/graphicsclass.cpp
UTF-8
3,205
2.75
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // Filename: graphicsclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "graphicsclass.h" GraphicsClass::GraphicsClass() { m_D3D = 0; m_Camera = 0; m_Model = 0; m_TextureShader = 0; } GraphicsClass::GraphicsClass(const GraphicsClass& other) { } GraphicsClass::~GraphicsClass() { } bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) { bool result; // Create the Direct3D object. m_D3D = new D3DClass; if(!m_D3D) { return false; } // Initialize the Direct3D object. result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, "Could not initialize Direct3D.", "Error", MB_OK); return false; } // Create the camera object. m_Camera = new CameraClass; if(!m_Camera) { return false; } // Create the ground model object. m_Model = new ModelClass; if(!m_Model) { return false; } char seafloor_dds[] = "./data/seafloor.dds"; char square_txt[] = "./data/square.txt"; // Initialize the square model object. result = m_Model->Initialize(m_D3D->GetDevice(), seafloor_dds, square_txt); if(!result) { MessageBox(hwnd, "Could not initialize the square model object.", "Error", MB_OK); return false; } m_TextureShader = new TextureShaderClass; if (!m_TextureShader) { return false; } result = m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd); if (!result) { MessageBox(hwnd, "Could not initialize the texture shader object.", "Error", MB_OK); return false; } return true; } void GraphicsClass::Shutdown() { // Release the BillBoarding Model object. if(m_Model) { m_Model->Shutdown(); delete m_Model; m_Model = 0; } // Release the camera object. if(m_Camera) { delete m_Camera; m_Camera = 0; } // Release the D3D object. if(m_D3D) { m_D3D->Shutdown(); delete m_D3D; m_D3D = 0; } if (m_TextureShader) { m_TextureShader->Shutdown(); delete m_TextureShader; m_TextureShader = 0; } return; } bool GraphicsClass::Frame() { bool result; // Set the position and rotation of the camera. m_Camera->SetPosition(0.0f , 1.0f , -20.0f); result = Render(); if (!result) { return false; } return true; } bool GraphicsClass::Render() { DirectX::XMMATRIX worldMatrix, viewMatrix, projectionMatrix; bool result; // Clear the buffers to begin the scene. m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world, view, and projection matrices from the camera and d3d objects. m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetProjectionMatrix(projectionMatrix); m_D3D->GetWorldMatrix(worldMatrix); m_Model->Render(m_D3D->GetDeviceContext()); result = m_TextureShader->Render( m_D3D->GetDeviceContext(), m_Model->GetVertexCount(), m_Model->GetInstanceCount(), worldMatrix, viewMatrix, projectionMatrix, m_Model->GetTexture()); if (!result) { return false; } // Present the rendered scene to the screen. m_D3D->EndScene(); return true; }
true
48ba5c8d4d656e74fd5dd1dbc580d55c63821e4c
C++
wanggan768q/RpcCoder_SY
/bin/Release/Grent/CPP/Config/StringMiscCfg.h
UTF-8
3,085
2.953125
3
[]
no_license
#ifndef __STRINGMISC_CONFIG_H #define __STRINGMISC_CONFIG_H #include "ConfigUtil.h" #define printf_message(_argg) printf(_argg) //杂项文本表配置数据结构 struct StringMiscElement { friend class StringMiscTable; int id; //序号 1 string comment; //文本内容备注 快捷用语1 string sc; //简体中文 认识你很开心 private: bool m_bIsValidate; void SetIsValidate(bool isValid) { m_bIsValidate=isValid; } public: bool IsValidate() { return m_bIsValidate; } StringMiscElement() { id = -1; m_bIsValidate=false; } }; //杂项文本表配置封装类 class StringMiscTable { friend class TableData; private: StringMiscTable(){} ~StringMiscTable(){} map<int, StringMiscElement> m_mapElements; vector<StringMiscElement> m_vecAllElements; StringMiscElement m_emptyItem; public: static StringMiscTable& Instance() { static StringMiscTable sInstance; return sInstance; } StringMiscElement GetElement(int key) { if( m_mapElements.count(key)>0 ) return m_mapElements[key]; return m_emptyItem; } bool HasElement(int key) { return m_mapElements.find(key) != m_mapElements.end(); } vector<StringMiscElement>& GetAllElement() { if(!m_vecAllElements.empty()) return m_vecAllElements; m_vecAllElements.reserve(m_mapElements.size()); for(auto iter=m_mapElements.begin(); iter != m_mapElements.end(); ++iter) { if(iter->second.IsValidate()) m_vecAllElements.push_back(iter->second); } return m_vecAllElements; } bool Load() { string strTableContent; if( LoadConfigContent("StringMisc.csv", strTableContent ) ) return LoadCsv( strTableContent ); if( !LoadConfigContent("StringMisc.bin", strTableContent ) ) { printf_message("配置文件[StringMisc.bin]未找到"); assert(false); return false; } return LoadBin(strTableContent); } bool LoadBin(string strContent) { return true; } bool LoadCsv(string strContent) { m_vecAllElements.clear(); m_mapElements.clear(); int contentOffset = 0; vector<string> vecLine; vecLine = ReadCsvLine( strContent, contentOffset ); if(vecLine.size() != 3) { printf_message("StringMisc.csv中列数量与生成的代码不匹配!"); assert(false); return false; } if(vecLine[0]!="id"){printf_message("StringMisc.csv中字段[id]位置不对应 ");assert(false); return false; } if(vecLine[1]!="comment"){printf_message("StringMisc.csv中字段[comment]位置不对应 ");assert(false); return false; } if(vecLine[2]!="sc"){printf_message("StringMisc.csv中字段[sc]位置不对应 ");assert(false); return false; } while(true) { vecLine = ReadCsvLine( strContent, contentOffset ); if((int)vecLine.size() == 0 ) break; if((int)vecLine.size() != (int)3) { assert(false); return false; } StringMiscElement member; member.id=(int)atoi(vecLine[0].c_str()); member.comment=vecLine[1]; member.sc=vecLine[2]; member.SetIsValidate(true); m_mapElements[member.id] = member; } return true; } }; #endif
true
6fb57becc4c04a3dd558d4dff48e7ec5069bb953
C++
Frazzle17/CMP105_W5
/Week5/CMP105App/Mario.cpp
UTF-8
2,061
2.625
3
[]
no_license
#include "Mario.h" Mario::Mario() { animation = &walk; crouched = false; swimming = false; walk.addFrame(sf::IntRect(0, 0, 15, 21)); walk.addFrame(sf::IntRect(15, 0, 15, 21)); walk.addFrame(sf::IntRect(30, 0, 15, 21)); walk.addFrame(sf::IntRect(45, 0, 15, 21)); walk.setFrameSpeed(0.1); swim.addFrame(sf::IntRect(0, 21, 16, 20)); swim.addFrame(sf::IntRect(16, 21, 16, 20)); swim.addFrame(sf::IntRect(32, 21, 16, 20)); swim.setFrameSpeed(0.1); crouch.addFrame(sf::IntRect(16, 41, 16, 20)); crouch.addFrame(sf::IntRect(0, 41, 16, 20)); crouch.setFrameSpeed(0.1); crouch.setLooping(false); } Mario::~Mario() { } void Mario::handleInput(float dt) { velocity.x = 0; if (input->isKeyDown(sf::Keyboard::Left)) { animation = &walk; animation->setFlipped(true); velocity.x = -250; setSize(sf::Vector2f(15, 21)); animation->animate(dt); } if (input->isKeyDown(sf::Keyboard::Right)) { animation = &walk; animation->setFlipped(false); velocity.x = 250; setSize(sf::Vector2f(15, 21)); animation->animate(dt); } if (input->isKeyDown(sf::Keyboard::Down) && crouched == false) { bool flip = animation->getFlipped(); animation = &crouch; animation->setFlipped(flip); velocity.x = 0; setSize(sf::Vector2f(16, 20)); move(0, 1); animation->animate(dt); animation->reset(); crouched = true; } if (!input->isKeyDown(sf::Keyboard::Down) && crouched == true) { animation = &walk; animation->reset(); setSize(sf::Vector2f(15, 21)); move(0, -1); crouched = false; } if (input->isKeyDown(sf::Keyboard::Space)) { bool flip = animation->getFlipped(); animation = &swim; animation->setFlipped(flip); velocity.x = 0; setSize(sf::Vector2f(16, 20)); animation->animate(dt); swimming = true; } if (!input->isKeyDown(sf::Keyboard::Space) && swimming == true) { animation->reset(); animation = &walk; animation->reset(); setSize(sf::Vector2f(15, 21)); swimming = false; } } void Mario::update(float dt) { setTextureRect(animation->getCurrentFrame()); move(velocity * dt); }
true
137b351771f67206b0cc94a64d8197c9b425e389
C++
dafengchuixiaoshu/aiai
/server/imserver/core/util/include/BaseQueue.h
UTF-8
2,990
2.859375
3
[]
no_license
#ifndef QUEUE_H #define QUEUE_H #ifdef WIN32 #include "ResourceBase.h" #else #include <iostream> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <pthread.h> #include <unistd.h> #include <signal.h> #endif #include <map> #include <list> using std::map; using std::list; #ifdef WIN32 #define _BaseQueue_Lock m_lock.Lock(); #define _BaseQueue_Unlock m_lock.Unlock(); #else #define _BaseQueue_Lock pthread_mutex_lock(&mutex); #define _BaseQueue_Unlock pthread_mutex_unlock(&mutex); #endif namespace kernel { template<class T> class BaseQueue { typedef map< int,list<T> > queue_map; public: BaseQueue(); ~BaseQueue(); int TryPut(T& data, int index = 1); int TryGet(T& data, int millisecond = 0); int GetSize(); private: #ifndef WIN32 pthread_cond_t more; pthread_mutex_t mutex; #else CTCriticalSection m_lock; #endif queue_map m_queuemap; }; template<class T> BaseQueue<T>::BaseQueue() { #ifndef WIN32 pthread_mutex_init(&mutex, NULL); pthread_cond_init(&more, NULL); #endif } template<class T> BaseQueue<T>::~BaseQueue() { } template<class T> int BaseQueue<T>::TryPut(T& data, int index) { _BaseQueue_Lock; m_queuemap[index].push_back(data); _BaseQueue_Unlock; #ifndef WIN32 pthread_cond_signal(&more); #endif return 0; } template<class T> int BaseQueue<T>::TryGet(T& data, int millisecond) { _BaseQueue_Lock; if(!m_queuemap.empty()) { typename queue_map::iterator it = m_queuemap.end(); while(1) { --it; if(!it->second.empty()) { data = it->second.front(); it->second.pop_front(); _BaseQueue_Unlock; return 0 ; } if(it == m_queuemap.begin()) break; } } #ifdef WIN32 //sleep_ms(1); #else if(millisecond <= 0) { pthread_cond_wait(&more,&mutex); } else { struct timespec timer; timer.tv_sec=time(0)+ (millisecond /1000) ; timer.tv_nsec= (millisecond % 1000) * 1000000; pthread_cond_timedwait(&more,&mutex,&timer); } #endif _BaseQueue_Unlock; return -1; } template<class T> int BaseQueue<T>::GetSize() { int datasize = 0; _BaseQueue_Lock; typename queue_map::iterator it = m_queuemap.begin(); while(it != m_queuemap.end()) { datasize += it->second.size(); ++it; } _BaseQueue_Unlock; return datasize; } } typedef kernel::BaseQueue<int> TIntQueue; #endif
true
9040295384b9e3e853261db32172b2526c0a7995
C++
444-555-fatima/DSA
/main.cpp
UTF-8
1,739
2.953125
3
[]
no_license
// Binary_Tree.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include "Tree.cpp" using namespace std; int main() { Tree myTree; Node* n1, *n2, *n3, *n4, *n5, *n6; n1 = new Node(55); n2 = new Node(54); n3 = new Node(522); n4 = new Node(65); n5 = new Node(11); n6 = new Node(90); myTree.insert(n1); myTree.insert(n2); myTree.insert(n3); myTree.insert(n4); myTree.insert(n5); myTree.insert(n6); if (myTree.search(522)) cout << 522 << " Found\n"; else cout << 522 << " Not Found\n"; if (myTree.search(34)) cout << 34 << " Found\n"; else cout << 34 << " Not Found\n"; //cout << "Root is: "; //cout << myTree.getRoot() << endl; cout << "Nodes: "; cout << myTree.getCount() << endl; myTree.remove(54); cout << "Hence the node is deletsd!"; cout << "The roots are:"; myTree.display(); cout << "Root is: "; cout << myTree.getRoot() << endl; cout << "The Value of max Node is:"; cout << myTree.getMax() << endl; system("Pause"); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
true
2e22b5139cf69ee6ffaa4c3d2e44b2099891fd60
C++
JacobGunnell/64w-ai-2021-official
/include/SMP.h
UTF-8
1,124
2.78125
3
[]
no_license
#ifndef SMP_H #define SMP_H #include <string> #include <fstream> using namespace std; #include "Brain.h" #include "armadillo" class SMP : public Brain { public: SMP() {} SMP(int, int); // create a random brain with specific dimensions SMP(int inputSize) : SMP(inputSize, 3) {} // TODO: random number of hidden cells SMP(arma::mat &, arma::mat &, arma::mat &); // create a brain from matrices ~SMP() {} arma::mat getWL1() const { return WL1; } // TODO: input validation void setWL1(arma::mat &weights) { WL1 = weights; } arma::mat getWL2() const { return WL2; } void setWL2(arma::mat &weights) { WL2 = weights; } arma::mat getB() const { return B; } void setB(arma::mat &bias) { B = bias; } arma::mat integrate(arma::mat) override; bool save(string) override; bool load(string) override; void mutate() override; SMP *clone() override { return new SMP(*this); } static string getExtension() { return ".smp"; } private: arma::mat WL1, WL2; arma::mat B; arma::mat f(arma::mat x) { return x; } // Activation function; TODO: make a lambda function in its place }; #endif // SMP_H
true
94691c818da9c294d637e9cef07a93f9b7b7ab74
C++
akshaygupta533/OpenGL-3D-Game
/src/para.cpp
UTF-8
2,353
3.109375
3
[]
no_license
#include "para.h" #include "main.h" Para::Para(glm::vec3 para_pos) { this->position = para_pos; this->rot_yaw = 0; this->rot_pitch = 0; this->rot_roll = 0; this->speed = 0.5; this->Iden = glm::mat4(1.0f); // Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices GLfloat vertex_buffer_datas[50][25*9]; GLfloat vertex_buffer_data[]={ 0,0,0, cos(M_PI/4),sin(M_PI/4),-0.5, cos(M_PI/4),sin(M_PI/4),0.5, 0,0,0, -cos(M_PI/4),sin(M_PI/4),-0.5, -cos(M_PI/4),sin(M_PI/4),0.5, }; float angle=0; float rot_angle = 2*M_PI/100; for(int j=0;j<50;j++){ for(int i=0;i<25;i++){ vertex_buffer_datas[j][9*i] = 0; vertex_buffer_datas[j][9*i+1] = 0; vertex_buffer_datas[j][9*i+2] = 0; vertex_buffer_datas[j][9*i+3] = cos(angle+M_PI/4); vertex_buffer_datas[j][9*i+4] = sin(angle+M_PI/4); vertex_buffer_datas[j][9*i+5] = float(j-25)/50; vertex_buffer_datas[j][9*i+6] = cos(angle+M_PI/4+rot_angle); vertex_buffer_datas[j][9*i+7] = sin(angle+M_PI/4+rot_angle); vertex_buffer_datas[j][9*i+8] = float(j-25)/50; angle+=rot_angle; } angle = 0; } glPointSize(3); for(int i=0;i<50;i++) this->object[i] = create3DObject(GL_TRIANGLES, 25*3, vertex_buffer_datas[i], COLOR_RED, GL_POINT); glLineWidth(2); this->object1 = create3DObject(GL_TRIANGLES, 2*3, vertex_buffer_data, COLOR_BLACK, GL_LINE); } void Para::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef // No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate // rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0)); Matrices.model *= (translate * this->Iden); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); for(int i=0;i<50;i++) draw3DObject(this->object[i]); draw3DObject(this->object1); } void Para::tick() { // this->rotation += speed; this->position.y-=0.01; }
true
2e798e144d653a33dd9f5fabac3a551a07214f35
C++
marromlam/lhcb-software
/Online/Online/Controller/src/fsm_internal_test.cpp
UTF-8
3,033
2.53125
3
[]
no_license
/*============================================================ ** ** Ctrl process management on a HLT worker node ** ** Test program to execute a FSM using internal slaves ** ** AUTHORS: ** ** M.Frank ** **==========================================================*/ // Framework include files #include "FiniteStateMachine/Slave.h" #include "FiniteStateMachine/Machine.h" #include "FiniteStateMachine/FSMTypes.h" #include "FiniteStateMachine/TestAutoTrans.h" #include "CPP/IocSensor.h" #include "CPP/Event.h" #include "RTL/rtl.h" using namespace std; using namespace FiniteStateMachine; /* * Anyonymous namespace */ namespace { /// Helper class InternalSlave /** * \author M.Frank * \date 01/03/2013 * \version 0.1 */ struct InternalSlave : public Slave { /// Sleep between transitions [milli seconds] int m_sleep; public: typedef FSM::ErrCond ErrCond; /// Initializing constructor InternalSlave(const Type* typ, const string& nam, int msleep, Machine* machine) : Slave(typ,nam,machine,true), m_sleep(msleep) {} /// Defautl constructor virtual ~InternalSlave() {} /// Inquire slave state. The reply may come later! virtual ErrCond inquireState() { return FSM::SUCCESS; } /// Start slave process. Base class implementation will throw an exception virtual ErrCond start() { return FSM::SUCCESS; } /// Kill slave process. Base class implementation will throw an exception virtual ErrCond kill() { return FSM::SUCCESS; } /// Kill slave process. Base class implementation will throw an exception virtual ErrCond forceKill() { return FSM::SUCCESS; } /// Virtual method -- must be overloaded -- Send transition request to the slave //virtual ErrCond sendRequest(const Transition* ) { return FSM::SUCCESS; } /// Start the slave's transition timeout virtual Slave& startTimer(int, const void*) { return *this; } /// Stop the slave's transition timeout virtual Slave& stopTimer() { return *this; } /// Helper to send internal interrupts virtual ErrCond send(int cmd, const State* state=0) const { if ( m_sleep > 0 ) ::lib_rtl_sleep(m_sleep); return Slave::send(cmd,state); } }; } extern "C" int internal_fsm_test(int argc, char** argv) { int msleep = -1, print = -1, rounds = -1; RTL::CLI cli(argc, argv, 0); cli.getopt("sleep", 1,msleep); cli.getopt("rounds",1,rounds); cli.getopt("print", 1,print); TypedObject::setPrintLevel(print); const Type* t = fsm_type("DAQ"); Machine* m = new Machine(t,"daq++"); TestAutoTrans* a = new TestAutoTrans(m,rounds); a->configDAQ(); m->addSlave(new InternalSlave(t,"SLAVE_0",msleep,m)); m->addSlave(new InternalSlave(t,"SLAVE_1",msleep,m)); m->addSlave(new InternalSlave(t,"SLAVE_2",msleep,m)); m->addSlave(new InternalSlave(t,"SLAVE_3",msleep,m)); m->addSlave(new InternalSlave(t,"SLAVE_4",msleep,m)); a->go_to(DAQ::ST_NAME_NOT_READY); IocSensor::instance().run(); return 1; }
true
159e5c0c8e055b60000c173e3775e13adeb79b8c
C++
LFKOKAMI/AlgebraicAttackOnRasta
/map.cpp
UTF-8
1,475
2.59375
3
[]
no_license
#include "Rasta.h" #include <iostream> #include <ctime> using namespace std; int main() { srand(time(NULL)); Rasta rasta; rasta.initialize(); int cnt0[100], cnt1[100]; for (int i = 0; i < 100; i++) { cnt0[i] = 0; cnt1[i] = 0; } bool** eq; eq = new bool* [ES - 1]; for (int i = 0; i < ES - 1; i++) { eq[i] = new bool[ES]; for (int j = 0; j < ES; j++) { eq[i][j] = 0; } } int testTimes = 100; bool m[BS], k[BS],c[BS]; for (int t = 0; t < testTimes; t++) { for (int i = 0; i < BS; i++) { m[i] = 0; k[i] = rand() % 2; } rasta.setKey(k); for (int i = 0; i < ES - 1; i++) { for (int j = 0; j < ES; j++) { eq[i][j] = 0; } } int dataCom = (ES - 1) / (3 * BS) + 1; for (int i = 0; i < dataCom; i++) { rasta.encrypt(m, c); rasta.constructEqs(m, c, i, eq); } cout <<endl<< "current times: " << t + 1 << endl; cout << "start gaussian elimination..." << endl; rasta.gauss(eq, ES - 1, ES, cnt0, cnt1); } cout << "number of polynomials: "<<ES - 1 << endl; cout << "number of monomials:" << ES << endl; cout << "key size:" << BS << endl; cout << "EQB-EQA:" << endl; for (int i = 0; i < 100; i++) { if (cnt0[i] > 0) { cout << i << ": " << cnt0[i] << endl; } } /*cout << "n-EQL:" << endl; for (int i = 0; i < 100; i++) { if (cnt1[i] > 0) { cout << i << ": " << cnt1[i] << endl; } }*/ rasta.freeMatrix(eq, ES - 1); return 0; }
true
55620d0b3dc55f1f04d2e681947373b0ba57a201
C++
ranseyer/home-automatics
/RGBWW-H801/ESPeasy/Arduino/libraries/ArduinoJson/test/JsonObject_Invalid_Tests.cpp
UTF-8
915
2.8125
3
[ "MIT" ]
permissive
// Copyright Benoit Blanchon 2014-2016 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson // If you like this project, please add a star! #include <ArduinoJson.h> #include <gtest/gtest.h> TEST(JsonObject_Invalid_Tests, SubscriptFails) { ASSERT_FALSE(JsonObject::invalid()["key"].success()); } TEST(JsonObject_Invalid_Tests, AddFails) { JsonObject& object = JsonObject::invalid(); object.set("hello", "world"); ASSERT_EQ(0, object.size()); } TEST(JsonObject_Invalid_Tests, CreateNestedArrayFails) { ASSERT_FALSE(JsonObject::invalid().createNestedArray("hello").success()); } TEST(JsonObject_Invalid_Tests, CreateNestedObjectFails) { ASSERT_FALSE(JsonObject::invalid().createNestedObject("world").success()); } TEST(JsonObject_Invalid_Tests, PrintToWritesBraces) { char buffer[32]; JsonObject::invalid().printTo(buffer, sizeof(buffer)); ASSERT_STREQ("{}", buffer); }
true
714ce8bae91776c424b9d9e7154af4e325d9f250
C++
jeonka1001/Cpp_language
/Twinkle_Little_Star.cpp
UTF-8
1,327
2.796875
3
[]
no_license
#include<iostream> using namespace std; #include<windows.h> #include<time.h> #include<stdlib.h> #define BLACK 0 #define BLUE 1 #define GREEN 2 #define CYAN 3 #define RED 4 #define MAGENTA 5 #define BROWN 6 #define LIGHTGRAY 7 #define DARKGRAY 8 #define LIGHTBLUE 9 #define LIGHTGREEN 10 #define LIGHTCYAN 11 #define LIGHTRED 12 #define LIGHTMAGENTA 13 #define YELLOW 14 #define WHITE 15 #define STAR_NUM 50 #define APPEAR_STAR 8 void textcolor(int foreground, int background); void gotoxy(int x,int y); int main() { int fore, x[STAR_NUM+1], y[STAR_NUM+1],i=0,j=0; srand((unsigned int)time(0)); while (i<=STAR_NUM&&j< STAR_NUM) { if (i < STAR_NUM) { fore = rand() % 16; textcolor(fore, BLACK); x[i] = rand() % 81; y[i] = rand() % 26; gotoxy(x[i], y[i]); putchar('*'); Sleep(800); i++; } if (i >= APPEAR_STAR) { textcolor(BLACK, BLACK); gotoxy(x[j], y[j]); putchar('*'); j++; Sleep(500); } } textcolor(WHITE, BLACK); return 0; } void textcolor(int foreground, int background) { int color = foreground + background * 16; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } void gotoxy(int x,int y){ COORD Pos={x,y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),Pos); }
true
4592eb9a9ec819f8dab5f7c3c021715ac939ae53
C++
btroycraft/tda-compute
/include/VecCompr.hpp
UTF-8
1,067
2.640625
3
[]
no_license
#ifndef VECCOMPR_HPP #define VECCOMPR_HPP #include <cstdint> #include <climits> #ifndef UINT_VEC_COMPR_MAX #define UINT_VEC_COMPR_MAX UINT_FAST32_MAX #endif #ifndef UINT_VEC_COMPR_BIT #define UINT_VEC_COMPR_BIT (CHAR_BIT*sizeof(std::uint_fast32_t)) #endif #ifndef SIZE_INIT_VEC_COMPR #define SIZE_INIT_VEC_COMPR 16 #endif #ifndef SIZE_MULT_VEC_COMPR #define SIZE_MULT_VEC_COMPR 1.5 #endif typedef uint_vec_compr_t std::uint_fast32_t; class VecCompr{ public: class Index; VecCompr(std::size_t, void*); ~VecCompr(); uint_vec_compr_t operator[](Index) &&; _Index operator[](Index) &; _Index operator[](std::size_t) &; private: class Index_; std::size_t width_; Index end_; std::size_t size_; void *add_; }; class VecCompr::Index{ public: Index(); Index(std::size_t); Index& operator--(); Index operator--(int); Index& operator++(); Index operator++(int); private: std::size_t ind_; std::size_t off_; std::size_t offComp_; std::size_t widthComp_; }; #endif
true
e90862b823ec63c5afc73e27781e90b2760446ef
C++
gldraphael/GameBase
/Gbase/GraphicsDevice.cpp
UTF-8
1,933
2.9375
3
[]
no_license
#include "GraphicsDevice.h" //namespace GameBase //{ GraphicsDevice::GraphicsDevice(int width, int height, unsigned int bitsPerPixel, bool isFullscreen, bool HardwareBuffering, bool useOpenGL) { window = new Surface; windowInitialized = false; int fs = 0x0, hw = 0x0,gl=0x0 ; //0x0 code for SWSURFACE if (isFullscreen) fs = 0x80000000; //Code for Full Screen if (HardwareBuffering) hw = 0x00000001; //Code for HWSURFACE if(useOpenGL) gl = 0x00000002; window->_surface = SDL_SetVideoMode (width, height, bitsPerPixel, fs|hw|gl); if(!window) throw GameBaseException(SDL_GetError()); windowInitialized = true; viewport.Height = height; viewport.Width = width; viewport.X = viewport.Y = 0; usesGL = useOpenGL; if(useOpenGL) throw GameBaseException("OpenGL Not Implemented"); } GraphicsDevice::GraphicsDevice(const GraphicsDevice& source) { viewport = source.viewport; usesGL = source.usesGL; *window = *source.window; } GraphicsDevice& GraphicsDevice::operator=(const GraphicsDevice& source) { if (this == &source) return *this; viewport = source.viewport; usesGL = source.usesGL; *window = *source.window; return *this; } Viewport GraphicsDevice::Viewport() { return viewport; } SDL_Surface* GraphicsDevice::Window() { return window->GetSurface(); } void GraphicsDevice::ToggleFullScreen() { SDL_WM_ToggleFullScreen(window->_surface); } void GraphicsDevice::Clear (Color& color) { SDL_FillRect(window->_surface, &(SDL_Rect) Rectangle(0, 0, static_cast<float>(viewport.Width), static_cast<float>(viewport.Height) ), SDL_MapRGB(window->_surface->format, color.R(),color.G(),color.B()) ); } void GraphicsDevice::Draw() { if(usesGL) SDL_GL_SwapBuffers(); else if(SDL_Flip(window->_surface) == -1) throw GameBaseException(SDL_GetError()); } GraphicsDevice::~GraphicsDevice(void) { delete window; } //}
true
d2d4d1175835941a84574a32c1c3a7e096d4f355
C++
obayemi/rt
/includes/Ray.hh
UTF-8
793
2.5625
3
[]
no_license
#ifndef _RAY_HH #define _RAY_HH /*! * \file Ray.hh * \author obayemi */ #include <iostream> #include "Coordinates.hpp" #include "Ray.hh" class Intersection; class Scene; class Mesh; class Ray { private: Ray(); private: Position _origin; Direction _direction; unsigned int _depth; public: Ray(Position origin, Direction direction, unsigned int depth = 0); Ray(const Ray &orig); virtual ~Ray(); const Position &getOrigin() const; const Direction &getDirection() const; unsigned int getDepth() const; Intersection *intersect(const Scene &scene, const Mesh *ignore = NULL); friend std::ostream& operator<<(std::ostream& out, const Ray& ray); }; #endif // _RAY_HH
true
badf136ebfa40d6869ff8ecd298bf902ccaffedd
C++
angelalim1010/CS235
/Project3/PlayList.h
UTF-8
1,044
3.28125
3
[]
no_license
#pragma once #include "LinkedSet.h" #include "Song.h" /* Author: Angela Lim Course: CSCI 235 Professor: Tiziana Ligorio Project 3: To create a LinkedSet for a playlist that will store your songs */ class PlayList : public LinkedSet<Song>{ public: PlayList(); //default constructor PlayList(const Song& a_song); //parameterized constructor PlayList(const PlayList& a_play_list); // copy constructor ~PlayList(); // Destructor bool add(const Song& new_song) override; bool remove(const Song& a_song) override; // post: previous_ptr is null if target is not in PlayList or if target is the // first node, otherwise it points to the node preceding target // return: either a pointer to the node containing target // or the null pointer if the target is not in the PlayList. void loop(); void unloop(); void displayPlayList(); private: Node<Song>* tail_ptr_; // Pointer to last node Node<Song>* getPointerTo(const Song& target, Node<Song>*& previous_ptr) const; Node<Song>* getPointerToLastNode() const; };
true
2780375bc9a0c00d65c2661eb568f5f7be8fa91c
C++
Sourabh-Kishore-Sharma/Cpp-Programs
/Pointers/basic.cpp
UTF-8
538
3.984375
4
[]
no_license
#include "iostream" using namespace std; int main(){ int a = 10; //Initializing a int type pointer int* a_ptr; //Storing address of variable a a_ptr = &a; //Change value of 'a' using dereferencing cout<<"Value of 'a' before dereferencing : "<<a<<endl; *a_ptr = 100; cout<<"Value of 'a' after dereferencing : "<<a<<endl; //Increment to next memory location for type int(4 bytes) cout<<"Address value before incrementing : "<<a_ptr<<endl; a_ptr++; cout<<"Address value after incrementing : "<<a_ptr<<endl; }
true
b52d32d366668842adffdfdea07e95702e88eec1
C++
Kladdy/deltaXi
/src/Objects/Clickables/Menu/MenuButton.hpp
UTF-8
1,009
2.546875
3
[]
no_license
#ifndef MENUBUTTON_HPP #define MENUBUTTON_HPP #include "../RoundClickable.h" #include "PCH.hpp" class MenuButton : public RoundClickable { private: sf::Vector2f pos; std::wstring name; sf::CircleShape circleShape; sf::Text label; public: int index; float buttonRadius; float outlineThicknessFraction; bool soundPlayed; bool isHeld; sf::Color normalColor; sf::Color holdColor; bool isHovered(); bool isClicked(); void onHover(); void onDeHover(); void onClick(); void draw(); sf::Vector2f getPosition(); void setPosition(sf::Vector2f pos); void setOutlineColor(sf::Color color); void setFillColor(sf::Color color); void setRadius(float radius); MenuButton(std::wstring name, float radius, int pointCount, sf::Color fillColor, sf::Color outlineColor, float outlineThickness, sf::Color holdColor, int menuButtonIndex, stringvector enlistedScenes = stringvector{"default"}, bool isActive = true); MenuButton(); ~MenuButton(); }; #endif // !MENUBUTTON_HPP
true
b0a29dc445f714135509083e962dcbf7d810ef25
C++
zeno15/zeno
/include/zeno/System/Vector3.hpp
UTF-8
8,272
3.265625
3
[ "MIT" ]
permissive
#ifndef INCLUDED_ZENO_SYSTEM_VECTOR_3_HPP #define INCLUDED_ZENO_SYSTEM_VECTOR_3_HPP #include <ostream> #include <cmath> //////////////////////////////////////////////////////////// /// /// \namespace zeno /// //////////////////////////////////////////////////////////// namespace zeno { //////////////////////////////////////////////////////////// /// /// \brief Template class for 3D Vectors /// //////////////////////////////////////////////////////////// template <typename T> class Vector3 { public: //////////////////////////////////////////////////////////// /// /// \brief Default constructor /// /// Creates a Vector3 with x, y and z equal to 0 /// //////////////////////////////////////////////////////////// Vector3(); //////////////////////////////////////////////////////////// /// /// \brief Initialises x, y and z to the given values /// /// \param _x value that x is set to /// /// \param _y value that y is set to /// /// \param _z value that z is set to /// //////////////////////////////////////////////////////////// Vector3(T _x, T _y, T _z); //////////////////////////////////////////////////////////// /// /// \brief Copy constructor /// /// Initialises the vector to have the same values as that /// of the parameter /// /// \param _vec Vector3 that is used to initialise this /// Vector3 /// //////////////////////////////////////////////////////////// template <typename U> Vector3(const Vector3<U>& _vec); public: T x; ///< x component T y; ///< y component T z; ///< z component }; //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of negate operator /// /// \param _right Vector3 to negate /// /// \return Component-wise negated version of the Vector3 /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator -(const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of minus-equals operator /// /// \param _left Vector3 to be modified /// /// \param _right Vector3 to subtract /// /// \return Reference to \a _left Vector3 // //////////////////////////////////////////////////////////// template <typename T> Vector3<T>& operator -=(Vector3<T>& _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of minus operator /// /// \param _left Vector3 to be subtracted from /// /// \param _right Vector3 to subtract /// /// \return Vector3 which is component-wise subtraction /// of \a _right from \a _left /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator -(const Vector3<T>& _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of plus-equals operator /// /// \param _left Vector3 to be added to /// /// \param _right Vector3 to add /// /// \return Reference to \a _left Vector3 /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator +=(Vector3<T>& _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of plus operator /// /// \param _left Left Vector3 to add /// /// \param _right Right Vector3 to add /// /// \return Vector3 which is component-wise addition of /// \a _left and \a _right /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator +(const Vector3<T>& _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of divide-equals operator /// /// \param _left Vector3 to be divided /// /// \param _right Value to divide the Vector3 by /// /// \return Reference to \a _left Vector3 /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T>& operator /=(Vector3<T>& _left, T _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of divide operator /// /// \param _left Vector3 to be divided /// /// \param _right Value to divide Vector3 by /// /// \return Vector3 which is the component-wise division /// of \a _left by \a _right /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator /(const Vector3<T>& _left, T _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of multiply-equal operator /// /// \param _left Vector3 to be multiplied /// /// \param _right Value to multiply Vector3 by /// /// \return Reference to \a _left which is a componen- /// wise multiplication of \a _left by \a _right\ /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator *=(Vector3<T>& _left, T _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of multiply operator /// /// \param _left Vector3 to be multiplied /// /// \param _right Value to multiply Vector3 by /// /// \return Vector3 which is a component-wise /// multiplication of \a _left by \a _right /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator *(const Vector3<T>& _left, T _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of multiply operator /// /// \param _left Value to multiply Vector3 by /// /// \param _right Vector3 to be multiplied /// /// \return Vector3 which is a component-wise /// multiplication of \a _right by \a _left /// //////////////////////////////////////////////////////////// template <typename T> Vector3<T> operator *(T _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of boolean equals operator /// /// \param _left Vector3 to be compared /// /// \param _right Vector3 to be compared /// /// \return Boolean value representing whether or not /// all of the components of \a _left are equal /// to those of \a _right /// //////////////////////////////////////////////////////////// template <typename T> bool operator ==(const Vector3<T>& _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of boolean not-equals operator /// /// \param _left Vector3 to be compared /// /// \param _right Vector3 to be compared /// /// \return Boolean value representing whether or not /// any of the components of \a _left are not /// equal to those of \a _right /// //////////////////////////////////////////////////////////// template <typename T> bool operator !=(const Vector3<T>& _left, const Vector3<T>& _right); //////////////////////////////////////////////////////////// /// /// \relates zeno::Vector3 /// /// \brief Overload of << operator /// /// \param os std::ostream reference /// /// \param _vec Vector3 to be output /// /// \return std::ostream reference with formatted Vector3 /// output insertted into it /// //////////////////////////////////////////////////////////// template <typename T> std::ostream& operator <<(std::ostream& os, zeno::Vector3<T> const& _vec); #include "Vector3.inl" typedef Vector3<int> Vector3i; typedef Vector3<unsigned int> Vector3u; typedef Vector3<float> Vector3f; typedef Vector3<double> Vector3d; } //~ namespace zeno #endif //~ INCLUDED_ZENO_SYSTEM_VECTOR_3_HPP //////////////////////////////////////////////////////////// /// /// \class zeno::Vector3 /// \ingroup System /// /// Explanation of how this all works /// /// \code /// zeno::Vector3<float> vec = zeno::Vector3<float>(); /// \endcode /// ////////////////////////////////////////////////////////////
true
43bef2640b6e53ee9ebfed6d1a73ba4a936c0e0c
C++
jupeos/EmbeddedSerialFiller
/test/CrcTests.cpp
UTF-8
1,417
2.984375
3
[ "MIT" ]
permissive
/** * \file CrcTests.cpp * \author Julian Mitchell * \date 11 Sep 2019 */ #include <etl/crc16_ccitt.h> #include "EmbeddedSerialFiller/EmbeddedSerialFiller.h" #include "EmbeddedSerialFiller/Utilities.h" #include "gtest/gtest.h" using namespace esf; namespace { // The fixture for testing class Foo. class CrcTests : public ::testing::Test { protected: CrcTests() {} virtual ~CrcTests() {} }; TEST_F( CrcTests, StandardCheckTest ) { auto packet = ByteArray( { '1', '2', '3', '4', '5', '6', '7', '8', '9' } ); uint16_t crcVal2 = etl::crc16_ccitt( packet.begin(), packet.end() ); EXPECT_EQ( 0x29B1, crcVal2 ); } TEST_F( CrcTests, EmptyTest ) { auto packet = ByteArray(); uint16_t crcVal2 = etl::crc16_ccitt( packet.begin(), packet.end() ); EXPECT_EQ( 0xFFFF, crcVal2 ); } TEST_F( CrcTests, ZeroTest ) { auto packet = ByteArray( { 0 } ); uint16_t crcVal2 = etl::crc16_ccitt( packet.begin(), packet.end() ); EXPECT_EQ( 0xE1F0, crcVal2 ); } TEST_F( CrcTests, LargeTest ) { ByteArray data; ByteArray sequence( { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' } ); // Populate data with 300 characters for( int i = 0; i < 30; i++ ) { std::copy( sequence.begin(), sequence.end(), std::back_inserter( data ) ); } uint16_t crcVal2 = etl::crc16_ccitt( data.begin(), data.end() ); EXPECT_EQ( 0xC347, crcVal2 ); } } // namespace
true
f1163ef7f20edea71cc7690fff1c6d00bb3723d6
C++
CbIpok/repos
/Study Data/Student.cpp
UTF-8
409
3.15625
3
[]
no_license
#include "Student.h" Student::Student() { } Student::~Student() { } void Student::save(std::ostream & ostream) { ostream << "Student\t"; ostream << id << '\t' << name << '\t'<<courses.size()<<'\t'; for (auto& i : courses) { ostream << i << '\t'; } } bool Student::operator==(const Student & student) const { return student.id == id && student.name == name && student.courses == courses; }
true
6c4f447551bb0833e0cb119902b61c74d205316f
C++
dianazhanseit/lab-5
/case_insensitive_cmp.h
UTF-8
519
3.671875
4
[]
no_license
// Subtask 3: Case insensitive compare // Write bool operator( ) in a reasonable fashion! Making a lower case // copy of the strings, and using < is not reasonable! struct case_insensitive_cmp { bool operator()(const std::string& lhs, const std::string& rhs) const { auto len = (lhs.size() < rhs.size()) ? lhs.size() : rhs.size(); for(size_t i = 0; i<len; ++i) if (std::tolower(lhs[i]) != std::tolower(rhs[i])) return std::tolower(lhs[i]) < std::tolower(rhs[i]); return lhs.size() < rhs.size(); } };
true
2e8b1d1a2b2407271c0a19a9ff17881a0abacf63
C++
DanyloShyshla/IoT
/waterpump.h
UTF-8
606
2.6875
3
[]
no_license
#include <string> using namespace std; class WaterPump { public: int publicFirst; string publicSecond; int powerConsumptions; string brand; int waterCapacity; void getClass(); int getPowerConsumptions(); string getBrand(); int getWaterCapacity(); WaterPump(); WaterPump(int powerConsumptions, string brand, int waterCapacity, string name, string type, int amount, int lengthOfCable, int publicFirst, string publicSecond); ~WaterPump(); private: string name; string type; protected: int amount; int lengthOfCable; };
true
7f33e649521c616b9a599a10b562a308a29b49b6
C++
zhanghuanzj/cpp
/Leetcode/UniquePathsII.cpp
UTF-8
550
2.734375
3
[ "Apache-2.0" ]
permissive
class Solution { public: int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { if(obstacleGrid.empty()) return 0; int m = obstacleGrid.size(); int n = obstacleGrid.front().size(); vector<int> dp(n,0); dp[0] = 1; for(int i=0;i<m;++i){ for(int j=0;j<n;++j){ if(obstacleGrid[i][j]==1){ dp[j] = 0; }else if(j>0){ dp[j] += dp[j-1]; } } } return dp[n-1]; } };
true
268afde44458a860c2641e22ec7a5d8f504e7f31
C++
DanMargera/SO-synch
/Synch C++/Worker.h
UTF-8
590
2.71875
3
[]
no_license
#ifndef READER_H #define READER_H #include "Database.h" #include "Observer.h" class Worker { public: Worker(Database* db, Observer* parent); void startReading(int position, int executionTime, int* target); void startWriting(int position, int executionTime, int value); void read(); void write(); private: Database* db; Observer* parent; // Observador à ser notificado int* target; // Ponteiro para o endereço de escrita ao realizar uma leitura int position, time, value; HANDLE thread; // Handle da thread trabalhadora DWORD threadID; void done(); }; #endif
true
0cbd6bdeb7fcc803ae13550a7c16e1158b3885b0
C++
lordloop4700/Playground
/python/L1_cube_third.cpp
UTF-8
430
3.171875
3
[]
no_license
#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; int solution(int n) { int answer = 0; string check = ""; for (int i = n; i > 0;) { check = to_string(i % 3) + check; i /= 3; } int cube = 1; for (int i = 0; i < check.length(); i++) { answer += (check[i] - '0') * cube; cube *= 3; } return answer; } int main() { int num = 45; solution(num); return 0; }
true