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
2a4f03c039692f6beb9b3d4afa4338e46bc0e64c
C++
PowerFire/prg_OpenCv
/Ex_B2/ImProc_module/MatchTemplate_Demo.cpp
UTF-8
2,408
3.046875
3
[]
no_license
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <stdio.h> using namespace std; using namespace cv; //宣告全域變數 Mat img, templ, result; const char* image_window = "Source Image"; const char* result_window = "Result Image"; int match_method; //拉桿最大值 int max_Trackbar = 5; //宣告函式 void MatchingMethod(int, void*); int main(int, char** argv) { // 載入圖擋 img = imread("lena.jpg", 1); // 載入範本 templ = imread("crop-lena.jpg", 1); // 建立視窗 namedWindow(image_window , WINDOW_AUTOSIZE); namedWindow(result_window, WINDOW_AUTOSIZE); // 建立拉桿(指定比較的方式) // 0:SQDIFF 1:SQDIFF_NORMED 2: TM CCORR // 3:TM CCORR NORMED 4:TM COEDD 5: TM COEFF NORMED const char* trackbar_lavel = "Method: "; createTrackbar(trackbar_lavel, image_window, &match_method, max_Trackbar, MatchingMethod); //比對 MatchingMethod(0,0); waitKey(0); return 0; } //因為傳遞參數但又不會使用到 void MatchingMethod( int, void*) { //複製原圖 Mat img_display; img.copyTo(img_display); //建立範本與原圖比對結果的矩陣 int result_cols = img.cols -templ.cols +1; int result_rows = img.rows -templ.rows +1; result.create(result_cols, result_rows, CV_32FC1); //執行比對與正規化 //比對 matchTemplate(img, templ, result, match_method); //正規化 //ps可以不用正規化也可以找出範圍 normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat()); double minVal, maxVal; Point minLoc, maxLoc, matchLoc; //尋找正規畫後的圖內之最大值與最小值及其位置 minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat()); // SQIFF 與 SQDIFF_NORMED 是值愈低,比較結果愈好 // 其他方法是越高越好 // CV_TM_CCORR 不管取大或是取小都不准 是此範例的問題? if(match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ) { matchLoc = minLoc; } else { matchLoc = maxLoc; } //繪製比對結果範圍(使用長方形) //原圖 rectangle(img_display, matchLoc, Point(matchLoc.x +templ.cols, matchLoc.y +templ.rows), Scalar::all(0), 2, 8, 0); //正規化結果 rectangle(result, matchLoc, Point(matchLoc.x +templ.cols, matchLoc.y +templ.rows), Scalar::all(0), 2, 8, 0); //顯示結果 imshow(image_window, img_display); imshow(result_window, result); return; }
true
f4492d8eecdcd7bffcc66d864959eba3d4388182
C++
17342983498/zhuxu
/Code/C++ 11-7-1/C++ 11-7-1/test.cpp
GB18030
2,336
3.1875
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; #include <vector> #include <stack> #include<string> //bool IsPopOrder(vector<int> pushV, vector<int> popV) //{ // if (pushV.size() != popV.size()) // { // return false; // } // size_t outIdx = 0; // size_t inIdx = 0; // stack<int> s; // while (outIdx<popV.size()) // { // while (s.empty() || s.top() != popV[outIdx]) // { // if (inIdx<pushV.size()) // { // s.push(pushV[inIdx++]); // } // else // return false; // } // s.pop(); // outIdx++; // } // return true; //} // //int main() //{ // vector<int> V1{ 1, 2, 3, 4, 5 }; // //vector<int> V2{ 1, 2, 3, 4, 5 }; // vector<int> V2{ 1, 2, 7, 4, 5 }; // if (IsPopOrder(V1, V2)) // { // cout << "true" << endl; // } // else // cout << "false" << endl; // return 0; //} void Teststring2() { //string s1("hello, bit!!!"); //// reserveǷıstringЧԪظ //s.reserve(100); //cout << s.size() << endl; //cout << s.capacity() << endl; //// reserveСstringĵײռСʱǷὫռС //s.reserve(50); //cout << s.size() << endl; //cout << s.capacity() << endl; //s.reserve(5); //cout << s.size() << endl; //cout << s.capacity() << endl; //s.resize(5); //cout << s.size() << endl; //cout << s.capacity() << endl; //size_t sz1 = s1.capacity(); //cout << "making s grow:\n"; //for (int i = 0; i < 100; ++i) //{ // s1.push_back('c'); // if (sz1 != s1.capacity()) // { // sz1 = s1.capacity(); // cout << "capacity changed: " << sz1 << '\n'; // } //} //string s; //s.reserve(100); //size_t sz = s.capacity(); //cout << "making s grow:\n"; //for (int i = 0; i < 100; ++i) //{ // s.push_back('c'); // if (sz != s.capacity()) // { // sz = s.capacity(); // cout << "capacity changed: " << sz << '\n'; // } //} string url("http://www.cplusplus.com/reference/string/string/find/"); cout << url << endl; size_t start = url.find("://"); if (start == string::npos) { cout << "invalid url" << endl; return; } start += 3; size_t finish = url.find('/', start); string address = url.substr(start, finish - start); cout << address << endl; // ɾurlЭǰ׺ /* pos = url.find("://"); url.erase(0, pos + 3); cout << url << endl*/; } int main() { Teststring2(); return 0; }
true
a81129ec01fa8f6fcdc2bd74ae198b60dd43a02c
C++
anio0/printers
/HW_11/HW_11/HidingLinePrinter.cpp
UTF-8
936
3.078125
3
[]
no_license
#include "HidingLinePrinter.h" string HidingLinePrinter::PadFancy(const string & line, int N) { string new_line = line; int sharps = N - new_line.size(); int num; if (sharps > 0) { for (int i = 0; i < sharps; i++) { num = rand() % 10; new_line += std::to_string(num); } } return new_line; } HidingLinePrinter::HidingLinePrinter(int n, const vector<char> a):LinePrinter (n) { } void HidingLinePrinter::Print(const string & line) const { string str = line; for (int i = 0; i < line.length(); i++) { if (line[i]=='a') str[i] = '*'; if (line[i] == 'o') str[i] = '*'; if (line[i] == 'e') str[i] = '*'; if (line[i] == 'p') str[i] = '*'; if (line[i] == 't') str[i] = '*'; } cout << line << endl << endl; cout << "The N is " << _n << endl; for (int i = 0; i < line.size(); i += _n) { cout << str.substr(i, _n); cout << endl; } } HidingLinePrinter::~HidingLinePrinter() { }
true
bd2e4cbc66dfc9a74663f43207c78a3fb98fe200
C++
thefullarcticfox/cpp_experiments
/time/ft_gmtime.cpp
UTF-8
3,444
2.96875
3
[]
no_license
/* ** gmtime function replacement ** made it in case i ever needed to convert from unix timestamp to tm struct ** compile with: ** clang++ -g -Wall -Wextra -Werror ft_gmtime.cpp -o ft_gmtime && ./ft_gmtime */ #include <iostream> #include <string> #include <sstream> #include <ctime> // time_t, struct tm, gmtime, strftime struct tm* ft_gmtime(const time_t* rawtime) { struct tm* res = new struct tm; res->tm_sec = 0; // Seconds. [0-60] (1 leap second) res->tm_min = 0; // Minutes. [0-59] res->tm_hour = 0; // Hours. [0-23] res->tm_mday = 1; // Day. [1-31] res->tm_mon = 0; // Month. [0-11] res->tm_year = 70; // Year - 1900. [1970-...] res->tm_wday = 0; // Day of week. [0-6] res->tm_yday = 0; // Days in year. [0-365] res->tm_isdst = 0; // DST. [-1/0/1] #if defined(__USE_MISC) || defined(__DARWIN_STRUCT_STAT64) res->tm_gmtoff = 0; // Seconds east of UTC. res->tm_zone = "GMT"; // Timezone abbreviation. #endif if (*rawtime < 0) return (res); time_t timepart = (*rawtime) % 86400; time_t datepart = (*rawtime) / 86400; res->tm_sec += timepart % 60; timepart /= 60; res->tm_min += timepart % 60; timepart /= 60; res->tm_hour += timepart; res->tm_hour %= 24; res->tm_wday += (datepart + 4) % 7; int daysinmonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; while (datepart > 0) { /* if (year is not divisible by 4) then (it is a common year) else if (year is not divisible by 100) then (it is a leap year) else if (year is not divisible by 400) then (it is a common year) else (it is a leap year) */ daysinmonth[1] = 28; int year = res->tm_year + 1900; if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) daysinmonth[1] = 29; int yday = 0; int month = -1; while (++month < 12 && daysinmonth[month] <= datepart) { yday += daysinmonth[month]; datepart -= daysinmonth[month]; } if (month < 12 && datepart <= daysinmonth[month]) { res->tm_mon += month; res->tm_mday += datepart; res->tm_yday += yday + datepart; break ; } res->tm_year++; } return (res); } int main(void) { time_t rawtime = time(NULL); while (rawtime >= 0 && rawtime < 17777777777) { char str1[100], str2[100]; struct tm *res1, *res2; std::cout << "rawtime: " << rawtime << std::endl; res1 = gmtime(&rawtime); if (strftime(str1, sizeof(str1), "%a, %d %b %Y %T %z", res1)) std::cout << str1 << std::endl; res2 = ft_gmtime(&rawtime); if (strftime(str2, sizeof(str2), "%a, %d %b %Y %T %z", res2)) std::cout << str2 << std::endl; std::stringstream ss1, ss2; ss1 << res1->tm_sec << " " << res1->tm_min << " " << res1->tm_hour << " " << res1->tm_mday << " " << res1->tm_mon << " " << res1->tm_year << " " << res1->tm_wday << " " << res1->tm_yday << " " << res1->tm_isdst << " " << res1->tm_gmtoff << " " << res1->tm_zone; ss2 << res2->tm_sec << " " << res2->tm_min << " " << res2->tm_hour << " " << res2->tm_mday << " " << res2->tm_mon << " " << res2->tm_year << " " << res2->tm_wday << " " << res2->tm_yday << " " << res2->tm_isdst << " " << res2->tm_gmtoff << " " << res2->tm_zone; delete(res2); if (ss1.str() != ss2.str()) { std::cerr << "errored at " << rawtime << std::endl << ss1.str() << std::endl << ss2.str() << std::endl; return (1); } rawtime += 6000; std::cout << "-------------------------------" << std::endl; } return (0); }
true
315ff9310f8796f4e839e4d6c12cfa74d913ad13
C++
damian-pisaturo/datos7506
/CapaIndices/Hash/Hash.h
UTF-8
4,481
2.921875
3
[]
no_license
//////////////////////////////////////////////////////////////////////// // Archivo : Hash.h // Namespace : CapaIndice //////////////////////////////////////////////////////////////////////////// // 75.06 Organizacion de Datos // Trabajo practico: Framework de Persistencia //////////////////////////////////////////////////////////////////////////// // Descripcion // Cabeceras e interfaz de las clase Hash. /////////////////////////////////////////////////////////////////////////// // Integrantes // - Alvarez Fantone, Nicolas; // - Caravatti, Estefania; // - Garcia Cabrera, Manuel; // - Grisolia, Nahuel; // - Pisaturo, Damian; // - Rodriguez, Maria Laura. /////////////////////////////////////////////////////////////////////////// #ifndef HASH_H_ #define HASH_H_ #include <string> #include "Tabla.h" #include "Bucket.h" /////////////////////////////////////////////////////////////////////////// // Clase //------------------------------------------------------------------------ // Nombre: Hash (Implementa indices de dispersion extensible) ////////////////////////////////////////////////////////////////////////// class Hash { private: ////////////////////////////////////////////////////////////////////// // Atributos ////////////////////////////////////////////////////////////////////// Tabla* tabla; IndiceHashManager* archivo; ListaInfoRegistro* listaInfoRegistro; public: /////////////////////////////////////////////////////////////////////// // Constructor/Destructor /////////////////////////////////////////////////////////////////////// Hash(IndiceHashManager* indiceHash, ListaInfoRegistro* lista, unsigned int tamBucket); virtual ~Hash(); /////////////////////////////////////////////////////////////////////// // Metodos publicos /////////////////////////////////////////////////////////////////////// /* * Este método se utiliza para hacer una operación de alta en el archivo. * Si el registro se puede insertar devuelve OK; si ya existe un registro * con la misma clave, devuelve DUPLICATED. * En caso de que el registro no entre en el bucket correspondiente, se * toman las medidas necesarias para hacer extensible la función de hash. * Si el registro es variable "registro" contendrá su longitud en los * primeros bytes. **/ int insertarRegistro(char *registro,Clave &clave); /* Este método se utiliza para hacer una operación de baja en el archivo. * Si el registro se puede eliminar devuelve OK, si no existe el registro * a eliminar, se devuelve NO_ENCONTRADO. * En caso de que el bucket quede vacío, se considera la posibilidad de * disminuir el tamaño de la tabla de hash. **/ int eliminarRegistro(Clave &clave); int modificarRegistro(Clave &claveVieja, Clave &claveNueva, char* registroNuevo); /* * A partir de una clave recupera un registro. * Si lo encuentra devuelve true; de lo contrario, devuelve false. **/ bool recuperarRegistro(Clave &clave, char* &registro, unsigned short &tamanioBloque); /* * Busca el bucket donde se encuantra almacenado el registro de clave "clave", y devuelve * una copia de sus datos dentro de datosBucket tal como se almacenan en disco. **/ bool recuperarBucket(Clave &clave, char* &datosBucket, unsigned short &tamanioBucket); unsigned int* getCopiaTabla(unsigned int& tamanioTabla); Bucket* leerBucket(unsigned int nroBucket); /* * Retorna el tipo de organizacion de los bloques * */ int getTipoOrganizacion(); char* serializarClave(void** clave); ListaInfoRegistro* getListaInfoRegistro(); private: /////////////////////////////////////////////////////////////////////// // Metodos privados /////////////////////////////////////////////////////////////////////// /* * Este método aplica una función de dispersión a la clave. **/ unsigned int aplicarHash(Clave &clave); /* * Método utilizado internamente cuando se aplica la función de dispersión a una clave. **/ int hashInterno(unsigned char *clave); /* * Este método se encarga de redistribuir los registros contenidos en bucket * entre este mismo y bucketNuevo. **/ void redistribuirElementos(Bucket* &bucket, Bucket* bucketNuevo); /* * Este método se engarga de dividir el tamaño de dispersión del bucket nroBucket * y actualizarlo en el archivo. **/ void dividirDispersion(unsigned int nroBucket); bool esRegistroVariable(); }; #endif /*HASH_H_*/
true
54135b9ebba569fde78a42509853c33de955b889
C++
fan3750060/OpenWow
/owGameM2/M2_Animated.h
UTF-8
3,779
2.609375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "M2_AnimatedConverters.h" #include "M2_Types.h" /* Generic animated value class: T is the values type to animate D is the values type stored in the file (by default this is the same as T) Conv is a conversion object that defines T conv(D) to convert from D to T (by default this is an identity function) (there might be a nicer way to do this? meh meh) */ template <class T, class D = T, class Conv = NoConvert<T> > class M2_Animated { public: void init(const M2Track<D>& b, std::shared_ptr<IFile> f, cGlobalLoopSeq _globalSec, T fixfunc(const T&) = NoFix) { m_Type = b.interpolation_type; m_GlobalSecIndex = b.global_sequence; m_GlobalSec = _globalSec; // If hasn't index, then use global sec if (m_GlobalSecIndex != -1) { assert1(m_GlobalSec != nullptr); } assert1((b.interpolation_ranges.size > 0) || (m_GlobalSecIndex != -1) || (m_Type == INTERPOLATION_NONE)); // ranges if (b.interpolation_ranges.size > 0) { uint32* ranges = (uint32*)(f->getData() + b.interpolation_ranges.offset); for (uint32 i = 0; i < b.interpolation_ranges.size; i += 2) { m_Ranges.push_back(std::make_pair(ranges[i], ranges[i + 1])); } } // times uint32* times = (uint32*)(f->getData() + b.timestamps.offset); for (uint32 i = 0; i < b.timestamps.size; i++) { m_Times.push_back(times[i]); } assert1(b.timestamps.size == b.values.size); // keyframes D* values = (D*)(f->getData() + b.values.offset); for (uint32 i = 0; i < b.values.size; i++) { switch (m_Type) { case INTERPOLATION_LINEAR: m_Values.push_back(fixfunc(Conv::conv(values[i]))); break; case INTERPOLATION_HERMITE: m_Values.push_back(fixfunc(Conv::conv(values[i * 3 + 0]))); m_ValuesHermiteIn.push_back(fixfunc(Conv::conv(values[i * 3 + 1]))); m_ValuesHermiteOut.push_back(fixfunc(Conv::conv(values[i * 3 + 2]))); break; } } } bool uses(uint16 anim) const { if (m_Type == INTERPOLATION_NONE) { return false; } if (m_GlobalSecIndex == -1 && m_Ranges.size() <= anim) { return false; } return true; } T getValue(uint16 anim, uint32 time, uint32 globalTime) const { assert1(m_Type != INTERPOLATION_NONE); std::pair<uint32, uint32> range = std::make_pair(0, m_Values.size() - 1); // obtain a time value and a values range if (m_GlobalSecIndex != -1) { if (m_GlobalSec->at(m_GlobalSecIndex).timestamp == 0) { time = 0; } else { time = globalTime % m_GlobalSec->at(m_GlobalSecIndex).timestamp; } } else { assert1(time >= m_Times[0] && time < m_Times[m_Times.size() - 1]); range = m_Ranges[anim]; } // If simple frame if (range.first == range.second) { return m_Values[range.first]; } // Get pos by time uint32 pos = UINT32_MAX; for (uint32 i = range.first; i < range.second; i++) { if (time >= m_Times[i] && time < m_Times[i + 1]) { pos = i; break; } } assert1(pos != UINT32_MAX); uint32 t1 = m_Times[pos]; uint32 t2 = m_Times[pos + 1]; assert1(t2 > t1); assert1(time >= t1 && time < t2); float r = (float)(time - t1) / (float)(t2 - t1); switch (m_Type) { case INTERPOLATION_LINEAR: return interpolate<T>(r, m_Values[pos], m_Values[pos + 1]); break; case INTERPOLATION_HERMITE: return interpolateHermite<T>(r, m_Values[pos], m_Values[pos + 1], m_ValuesHermiteIn[pos], m_ValuesHermiteOut[pos]); break; } return m_Values[0]; } private: Interpolations m_Type; int16 m_GlobalSecIndex; cGlobalLoopSeq m_GlobalSec; std::vector<std::pair<uint32, uint32>>m_Ranges; std::vector<int32> m_Times; std::vector<T> m_Values; std::vector<T> m_ValuesHermiteIn; std::vector<T> m_ValuesHermiteOut; };
true
6783169d981e8c21c38af533558e0d4498b5c50e
C++
marvellouz/fmi_projects
/vsoz/fn71112/graph.h
UTF-8
4,771
3.359375
3
[]
no_license
#ifndef GRAPH_H #define GRAPH_H /*! \file \breif Definition of generic graph. */ #include <map> #include <set> #include <string> #include <vector> #include <iostream> #include <cassert> namespace vss { /*!This class represents a generic graph implementation. \tparam Type of data stored in each vertix. */ template <typename Data> class Graph { public: typedef std::pair<double, std::string> Successor; typedef std::vector<Successor> SuccessorList; Graph(); ~Graph(); std::ostream& printout(std::ostream& out) const; SuccessorList getSuccessors(std::string const& vertixName) const; bool empty() const; bool addVertix(std::string const& vertixName, Data const& data); bool hasVertix(std::string const& vertixName) const; bool getData(std::string const& vertixName, Data& outData) const; bool addEdge(std::string const& from, std::string const& to, double value = 1.0); bool hasEdge(std::string const& from, std::string const& to) const; std::set<std::string> vertices() const; private: struct Vertix { Data data; SuccessorList* successors; }; typedef std::map<std::string, Vertix> ContentsMap; ContentsMap contents; //to ensure that the graph is noncopyable Graph(Graph const&); Graph& operator=(Graph const&); }; template <typename Data> inline Graph<Data>::Graph() :contents() {} template <typename Data> inline Graph<Data>::~Graph() { for(typename ContentsMap::iterator it = contents.begin(); it!=contents.end(); ++it) { delete it->second.successors; } } template <typename Data> inline typename Graph<Data>::SuccessorList Graph<Data>::getSuccessors(std::string const& vertixName) const { SuccessorList result; typename ContentsMap::const_iterator found = contents.find(vertixName); if (found != contents.end()) result = *(found->second.successors); return result; } template <typename Data> inline bool Graph<Data>::empty() const { return contents.empty(); } template <typename Data> inline bool Graph<Data>::addVertix(std::string const& vertixName, Data const& data) { bool result = true; if (contents.find(vertixName) != contents.end()) { result = false; } else { Vertix newVertix; newVertix.data = data; newVertix.successors = new SuccessorList(); contents[vertixName] = newVertix; } return result; } template <typename Data> inline bool Graph<Data>::hasVertix(std::string const& vertixName) const { return contents.find(vertixName) != contents.end(); } template <typename Data> inline bool Graph<Data>::getData(std::string const& vertixName, Data& outData) const { bool result = true; typename ContentsMap::const_iterator found = contents.find(vertixName); if (found == contents.end()) { result = false; } else { outData = found->second.data; } return result; } template <typename Data> inline bool Graph<Data>::addEdge(std::string const& from, std::string const& to, double value) { if (!hasVertix(from) || !hasVertix(to)) return false; typename ContentsMap::iterator found = contents.find(from); assert(found != contents.end()); found->second.successors->push_back(Successor(value,to)); return true; } template <typename Data> inline bool Graph<Data>::hasEdge(std::string const& from, std::string const& to) const { return hasVertix(from) && hasVertix(to); } template <typename Data> inline std::set<std::string> Graph<Data>::vertices() const { std::set<std::string> result; for (typename ContentsMap::iterator it = contents.begin; it != contents.end(); ++it) { result.insert(it->first); } return result; } template <typename Data> std::ostream& Graph<Data>::printout(std::ostream& out) const { out << "Vertices: "; for (typename ContentsMap::const_iterator it = contents.begin(); it != contents.end(); ++it) { out << " v(" << it->first << ',' << it->second.data << ") "; } out << std::endl << "Arcs: "; for (typename ContentsMap::const_iterator it = contents.begin(); it != contents.end(); ++it) { for (typename SuccessorList::const_iterator nextNodeIt = it->second.successors->begin(); nextNodeIt != it->second.successors->end(); ++nextNodeIt) { out << " arc(" << it->first << ',' << nextNodeIt->second << ',' << nextNodeIt->first << ") "; } } out << std::endl; return out; } } //namespace vss #endif
true
c85c69b2de572ec76973a6b7e2dace6380650047
C++
Moonshile/AlgorithmCandy
/leetcode/131.cpp
UTF-8
1,210
3.078125
3
[ "Apache-2.0" ]
permissive
class Solution { private: vector<vector<bool>> getPalindromeMap(string &s) { vector<vector<bool>> res(s.size(), vector<bool>(s.size(), false)); for (int i = s.size() - 1; i >= 0; --i) { for (int j = i; j < s.size(); ++j) { if (s[i] == s[j] && (j - i < 2 || res[i + 1][j - 1])) { res[i][j] = true; } } } return res; } void dfs(string &s, int last, vector<vector<string>> &res, vector<vector<bool>> &palMap) { if (last == -1) { res.push_back(vector<string>()); return; } for (int i = last; i >= 0; --i) { if (palMap[i][last]) { vector<vector<string>> parts; dfs(s, i - 1, parts, palMap); for (auto &part: parts) { part.push_back(s.substr(i, last - i + 1)); res.push_back(part); } } } } public: vector<vector<string>> partition(string s) { vector<vector<string>> res; auto palMap = getPalindromeMap(s); dfs(s, s.size() - 1, res, palMap); return res; } };
true
2ce3697acad4a29015283828d0eb7aa168367c7c
C++
Monkeyman520/CPP
/CCF/真题练习/201312-3.cpp
UTF-8
566
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; vector<int> rect; for (int i = 0; i < n; ++i) { int x; cin >> x; rect.push_back(x); } int ans = 0; for (int i = 0; i < n; ++i) { int hight = rect[i]; for (int j = i; j < n; ++j) { if (rect[j] < hight) { hight = rect[j]; } int sum = (j - i + 1) * hight; if (ans < sum) { ans = sum; } } } cout << ans << endl; }
true
50bf7795485341ebdb71a20c2df169e6c43af8ec
C++
geoffpaulsen/utilities
/include/utility/bit_array.hpp
UTF-8
4,387
3.84375
4
[]
no_license
#ifndef UTILITY_BIT_ARRAY_HPP #define UTILITY_BIT_ARRAY_HPP #include <climits> #include <cstddef> #include <initializer_list> #include <stdexcept> #include <type_traits> namespace utility { /// Holds an array of bools with a built in data type. /** Size is equal to the number of bits in the data type. Array types work, * bools and floats do not.*/ template <typename Storage_t> class Bit_array { public: /// Default construct with all values false. constexpr Bit_array() = default; /// Construct with initializer list. /** Allows for partial constructions with remaining values set to false. */ constexpr Bit_array(std::initializer_list<bool> const& init) { auto i = std::size_t{0}; for (bool b : init) this->set(i++, b); } // Const Forward Iterator class Const_iterator { public: constexpr auto operator++() -> Const_iterator& { ++index_; return *this; } constexpr auto operator++(int) -> Const_iterator { auto temp = Const_iterator{*this}; this->operator++(); return temp; } constexpr auto operator*() const -> bool { return array_[index_]; } constexpr auto operator==(Const_iterator const& iter) -> bool { return (&array_ == &iter.array_) && (index_ == iter.index_); } constexpr auto operator!=(Const_iterator const& iter) -> bool { return !(*this == iter); } private: Bit_array const& array_; std::size_t index_; private: friend Bit_array; constexpr Const_iterator(Bit_array const& array, std::size_t index_init) : array_{array}, index_{index_init} {} }; /// Return a const forward iterator to the first element. constexpr auto begin() const -> Const_iterator { return {*this, 0}; } /// Return a const forward iterator to the one past the end element. constexpr auto end() const -> Const_iterator { return {*this, this->size()}; } /// Return the value at index \p position. /** No bounds checking. */ constexpr auto operator[](std::size_t position) const -> bool { if constexpr (std::is_array_v<Storage_t>) { auto const bit_count = unit_bit_count(); return data_[position / bit_count] & (unit() << (position % bit_count)); } else return data_ & (unit() << position); } /// Return the value at index \p position. /** Throws std::out_of_range if \p position is >= size(). */ constexpr auto at(std::size_t position) const -> bool { if (position >= this->size()) throw std::out_of_range{"Out of bounds access"}; return (*this)[position]; } /// Set the value at index \p position. /** No bounds checking. */ constexpr void set(std::size_t position, bool value) { if constexpr (std::is_array_v<Storage_t>) { auto const bit_count = unit_bit_count(); value ? data_[position / bit_count] |= unit() << (position % bit_count) : data_[position / bit_count] &= ~(unit() << (position % bit_count)); } else { value ? data_ |= unit() << position : data_ &= ~(unit() << position); } } /// Return the number of elements in the container. constexpr static auto size() -> std::size_t { return sizeof(Storage_t) * CHAR_BIT; } private: Storage_t data_ = {0}; private: /// Return number of bits in a single object of the type held by Storage_t. /** Only for array types. */ constexpr auto unit_bit_count() const -> std::size_t { return sizeof(data_[0]) * CHAR_BIT; } /// Return the value 1. /** The type returned is Storage_t if it is not an array, and the type held * by an array Storage_t if it is. Used for safe bit shifting. */ static constexpr auto unit() { if constexpr (std::is_array_v<Storage_t>) return std::remove_reference_t<decltype(data_[0])>(1); else return Storage_t(1); } }; } // namespace utility #endif // UTILITY_BIT_ARRAY_HPP
true
091e47048aa31ed7f4965c8136d5697d0715f819
C++
Liuyi-Wang/LeetCode
/src/1038_Binary_Search_Tree_to_Greater_Sum_Tree.cpp
UTF-8
717
3.234375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int resolve(TreeNode* root, const int base) { if (NULL == root) { return 0; } int r_s = 0; if (root->right) { r_s = resolve(root->right, base); }; root->val += r_s+base; int l_s = 0; if (root->left) { l_s = resolve(root->left, root->val); } return root->val+l_s-base; } TreeNode* bstToGst(TreeNode* root) { resolve(root, 0); return root; } };
true
a5c47126a5d2822e9e06bb685a466c54f80af2ff
C++
gautamshah6/Coding_Blocks_Solution-c-
/all_indices_by_recursion.cpp
UTF-8
351
2.734375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void all_indices(int a[],int n,int key,int i) { if(n==0) return; if(a[0]==key) { cout<<i<<" "; } all_indices(a+1,n-1,key,i+1); } int main() { int n; cin>>n; int *a=new int[n]; for(int i=0;i<n;i++) cin>>a[i]; int key; cin>>key; all_indices(a,n,key,0); return 0; }
true
86efcd8ab85fa3bfb53c19d00e85a60205da1019
C++
Xion-C/practice
/817/flocking_system/StateVector.h
UTF-8
2,873
3.40625
3
[]
no_license
#ifndef __STATEVECTOR_H__ #define __STATEVECTOR_H__ #include <cstring> #include <iostream> #include "Utility.h" template<class T> class StateVector { public: int N; // particle numbers T* data; StateVector(int n); StateVector(const StateVector&); ~StateVector(); StateVector<T>& operator=(const StateVector<T> &s); template<class Y> friend std::ostream& operator<<(std::ostream& os, const StateVector<Y>& s); StateVector<T> operator+(const StateVector<T>& s) const; StateVector<T> operator-(const StateVector<T>& s) const; StateVector<T> operator*(float k) const; template<class Y> friend StateVector<Y> operator*(float k, const StateVector<Y>& s); }; template<class T> StateVector<T>::StateVector(int n) : N(n) { if(n > 0) { data = new T[2 * N]; memset(data, 0, N * 2 * sizeof(T)); } else { error("not valid size"); n = 0; data = nullptr; } } template<class T> StateVector<T>::StateVector(const StateVector& s) : N(s.N) { data = new T[s.N * 2]; memcpy(data, s.data, N * 2 * sizeof(T)); } template<class T> StateVector<T>::~StateVector() { delete[] data; } template<class T> StateVector<T>& StateVector<T>::operator=(const StateVector<T> &s) { if(&s == this) return *this; if(N != s.N) { N = s.N; delete[] data; data = new T[N * 2]; } memcpy(data, s.data, N * 2 * sizeof(T)); return *this; } template<class T> StateVector<T> StateVector<T>::operator+(const StateVector<T>& s) const { if(N != s.N) { error("not same size "); return StateVector<T>(0); } StateVector<T> res(N); for(int i = 0; i < 2 * N; i++) { res.data[i] = data[i] + s.data[i]; } return res; } template<class T> StateVector<T> StateVector<T>::operator-(const StateVector<T>& s) const { if(N != s.N) { error("not same size "); return StateVector<T>(0); } StateVector<T> res(N); for(int i = 0; i < 2 * N; i++) { res.data[i] = data[i] - s.data[i]; } return res; } template<class T> StateVector<T> StateVector<T>::operator*(float k) const { StateVector<T> res(N); for(int i = 0; i < 2 * N; i++) { res.data[i] = data[i] * k; } return res; } template<class Y> std::ostream& operator<<(std::ostream& os, const StateVector<Y>& s) { if(s.N == 0) return os << "empty" << std::endl; else { os << "[ " << s.data[0] << "," << std::endl; for(int i = 1; i < 2 * s.N; i++) { os << " " << s.data[i]; if(i != 2 * s.N - 1) os << "," << std::endl; } os << " ]" << std::endl; } return os; } template<class Y> StateVector<Y> operator*(float k, const StateVector<Y>& s) { return s * k; } #endif
true
d457ad8b53b7e8828353c94cee3c0afb92a441f4
C++
JustARegularPlayer/Spotlight
/Spotlight/src/Spotlight/Renderer/Buffer.h
UTF-8
4,770
3.1875
3
[ "MIT" ]
permissive
#pragma once namespace Spotlight { // VERTEX BUFFER LAYOUT ========================================================== enum class ShaderDataType { None = 0, Bool, Float, Float2, Float3, Float4, Int, Int2, Int3, Int4, uInt, uInt2, uInt3, uInt4, Byte, Byte2, Byte3, Byte4, Mat3, Mat4 }; static uint32_t ShaderDataTypeToSize(ShaderDataType type) { switch (type) { case ShaderDataType::Bool: return 1; case ShaderDataType::Float: return 4; case ShaderDataType::Float2: return 4 * 2; case ShaderDataType::Float3: return 4 * 3; case ShaderDataType::Float4: return 4 * 4; case ShaderDataType::Int: return 4; case ShaderDataType::Int2: return 4 * 2; case ShaderDataType::Int3: return 4 * 3; case ShaderDataType::Int4: return 4 * 4; case ShaderDataType::uInt: return 4; case ShaderDataType::uInt2: return 4 * 2; case ShaderDataType::uInt3: return 4 * 3; case ShaderDataType::uInt4: return 4 * 4; case ShaderDataType::Byte: return 1; case ShaderDataType::Byte2: return 1 * 2; case ShaderDataType::Byte3: return 1 * 3; case ShaderDataType::Byte4: return 1 * 4; case ShaderDataType::Mat3: return 4 * 3 * 3; case ShaderDataType::Mat4: return 4 * 4 * 4; } SPL_CORE_ASSERT(false, "Specified ShaderDataType unknown!"); return 0; } // BUFFER ELEMENT STRUCTURE struct BufferElement { std::string Name; ShaderDataType Type; bool Normalized; uint32_t Size; uint32_t Offset; // Default constructor BufferElement() : Name("Unknown"), Type(ShaderDataType::None), Normalized(false), Size(0), Offset(0) {} // Main constructor BufferElement(ShaderDataType type, const std::string& name, bool isNormalized = false) : Name(name), Type(type), Normalized(isNormalized), Size(ShaderDataTypeToSize(type)), Offset(0) {} uint32_t GetComponentCount() const { switch (Type) { case ShaderDataType::Bool: return 1; case ShaderDataType::Float: return 1; case ShaderDataType::Float2: return 2; case ShaderDataType::Float3: return 3; case ShaderDataType::Float4: return 4; case ShaderDataType::Int: return 1; case ShaderDataType::Int2: return 2; case ShaderDataType::Int3: return 3; case ShaderDataType::Int4: return 4; case ShaderDataType::Byte: return 1; case ShaderDataType::Byte2: return 2; case ShaderDataType::Byte3: return 3; case ShaderDataType::Byte4: return 4; case ShaderDataType::Mat3: return 3 * 3; case ShaderDataType::Mat4: return 4 * 4; } SPL_CORE_ASSERT(false, "Specified ShaderDataType unknown!"); return 0; } }; // BUFFER LAYOUT ==================================================================== class BufferLayout { public: BufferLayout() : m_Elements({BufferElement()}), m_Stride(0) {} BufferLayout(const std::initializer_list<BufferElement>& element /*Take in one or multiple arrays of BufferElement as argument*/ ) : m_Elements(element), m_Stride(0) { ComputeOffsetAndStride(); } // Getters inline const std::vector<BufferElement>& GetAllElements() const { return m_Elements; } inline uint32_t GetStride() const { return m_Stride; } // begin/end iterator functions for for-each statements inline std::vector<BufferElement>::iterator begin() { return m_Elements.begin(); } inline std::vector<BufferElement>::iterator end() { return m_Elements.end(); } inline std::vector<BufferElement>::const_iterator begin() const { return m_Elements.begin(); } inline std::vector<BufferElement>::const_iterator end() const { return m_Elements.end(); } private: void ComputeOffsetAndStride() { uint32_t offset = 0; m_Stride = 0; for (auto& element : m_Elements) { element.Offset = offset; offset += element.Size; m_Stride += element.Size; } } private: std::vector<BufferElement> m_Elements; uint32_t m_Stride; }; // VERTEX BUFFER ================================================================= class VertexBuffer { public: virtual ~VertexBuffer() = default; virtual void Bind() const = 0; virtual void Unbind() const = 0; virtual void SetData(const void *data, size_t size) = 0; virtual const BufferLayout& GetLayout() const = 0; virtual void SetLayout(const BufferLayout& layout) = 0; static Ref<VertexBuffer> Create(size_t size); static Ref<VertexBuffer> Create(float* vertices, size_t size); }; // INDEX BUFFER ================================================================== class IndexBuffer { public: virtual ~IndexBuffer() = default; virtual void Bind() const= 0; virtual void Unbind() const = 0; virtual uint32_t GetCount() const = 0; static Ref<IndexBuffer> Create(uint32_t* indices, uint32_t count); }; }
true
31b97af4c5210d89b79cb0669585aa4bd510b0a5
C++
i-yana/Study
/Games/Parser.h
UTF-8
9,182
2.53125
3
[]
no_license
#ifndef PARSER_H #define PARSER_H #include "Factory_of_Strategy.h" #include <iostream> #include <memory> using namespace std; namespace Games { struct Arguments { string out_file = ""; string in_file = ""; size_t iteratons = 0; std::shared_ptr<Field<Cell>> universe; std::shared_ptr<Strategy> strategy; }; namespace Parser_Fire { class Parser_of_Arguments { public: Parser_of_Arguments() :has_size(false), has_iterations(false) {}; ~Parser_of_Arguments(){}; Arguments& parse_arguments(std::vector<std::string>& keys); private: void parse_input_file(const string& file_name); void parse_arg_line(std::vector<std::string>& keys); void parse_coordinate(const string& file_line); void parse_config(const string& file_line); string name_of_universe; int width; int height; bool has_size; bool has_iterations; Arguments a; std::unique_ptr<Factory_of_Strategy> factory; }; namespace Exception { class parse_arguments : public std::exception { public: explicit parse_arguments(const std::string& why) : m_reason(why) {} const char* what() const throw() { return m_reason.c_str(); } private: std::string m_reason; }; class wrong_number_of_arguments : public parse_arguments { public: explicit wrong_number_of_arguments(const std::string& why) : parse_arguments("Wrong number of arguments" + why) {} }; class redefiniton_of_argument : public parse_arguments { public: explicit redefiniton_of_argument(const std::string& why) : parse_arguments("Redefinition of argument number " + why) {} }; class expected_number_of_iterations : public parse_arguments { public: explicit expected_number_of_iterations(const std::string& why) : parse_arguments("Wrong argument " + why + ", expected -i or --iterations=x") {} }; class expected_output_file : public parse_arguments { public: explicit expected_output_file(const std::string& why) : parse_arguments("Wrong argument " + why + ", expected -o or --output=""file name""") {} }; class wrong_number_of_iterations : public parse_arguments { public: explicit wrong_number_of_iterations(const std::string& why) : parse_arguments("Wrong number of iterations " + why) {} }; class incorrect_output_file : public parse_arguments { public: explicit incorrect_output_file(const std::string& why) : parse_arguments("Incorrect the output file " + why) {} }; class parse_input_file : public std::exception { public: explicit parse_input_file(const std::string& why) : m_reason(why) {} const char* what() const throw() { return m_reason.c_str(); } private: std::string m_reason; }; class not_found_version : public parse_input_file { public: explicit not_found_version(const std::string& why) : parse_input_file("Not found version " + why) {} }; class cannot_open_input_file : public parse_input_file { public: explicit cannot_open_input_file(const std::string& why) : parse_input_file("Can not open input file: " + why) {} }; class wrong_place_for_conditions : public parse_input_file { public: explicit wrong_place_for_conditions(const std::string& why) : parse_input_file("Wrong place for condition in line " + why) {} }; class bad_configuration : public parse_input_file { public: explicit bad_configuration(const std::string& why) : parse_input_file("Incorrect configuration in line " + why) {} }; class bad_coordinates : public parse_input_file { public: explicit bad_coordinates(const std::string& why) : parse_input_file("Incorrect coordinates in line " + why) {} }; class bad_version : public parse_input_file { public: explicit bad_version(const std::string& why) : parse_input_file("Incorrect version in line " + why) {} }; class bad_size : public parse_input_file { public: explicit bad_size(const std::string& why) : parse_input_file("Incorrect sizes in line " + why) {} }; class bad_rules : public parse_input_file { public: explicit bad_rules(const std::string& why) : parse_input_file("Incorrect rules in line " + why) {} }; class redefinition_of_configuration : public parse_input_file { public: explicit redefinition_of_configuration(const std::string& why) : parse_input_file("Redifinition of configuration in line " + why) {} }; } } namespace Parser_Life { class Parser_of_Arguments { public: Parser_of_Arguments() :has_size(false), has_iterations(false), has_rules(false){}; ~Parser_of_Arguments(){}; Arguments& parse_arguments(std::vector<std::string>& keys); private: void parse_input_file(const string& file_name); void parse_arg_line(std::vector<std::string>& keys); void parse_coordinate(const string& file_line); void parse_config(const string& file_line); string name_of_universe; int width; int height; bool has_size; bool has_iterations; bool has_rules; Arguments a; std::unique_ptr<Factory_of_Strategy> factory; }; namespace Exception { class parse_arguments : public std::exception { public: explicit parse_arguments(const std::string& why) : m_reason(why) {} const char* what() const throw() { return m_reason.c_str(); } private: std::string m_reason; }; class wrong_number_of_arguments : public parse_arguments { public: explicit wrong_number_of_arguments(const std::string& why) : parse_arguments("Wrong number of arguments " + why) {} }; class redefiniton_of_argument : public parse_arguments { public: explicit redefiniton_of_argument(const std::string& why) : parse_arguments("Redefinition of argument number" + why) {} }; class expected_number_of_iterations : public parse_arguments { public: explicit expected_number_of_iterations(const std::string& why) : parse_arguments("Wrong argument " + why + ", expected -i or --iterations=x") {} }; class expected_output_file : public parse_arguments { public: explicit expected_output_file(const std::string& why) : parse_arguments("Wrong argument " + why + ", expected -o or --output=""file name""") {} }; class wrong_number_of_iterations : public parse_arguments { public: explicit wrong_number_of_iterations(const std::string& why) : parse_arguments("Wrong number of iterations " + why) {} }; class incorrect_output_file : public parse_arguments { public: explicit incorrect_output_file(const std::string& why) : parse_arguments("Incorrect the output file " + why) {} }; class parse_input_file : public std::exception { public: explicit parse_input_file(const std::string& why) : m_reason(why) {} const char* what() const throw() { return m_reason.c_str(); } private: std::string m_reason; }; class not_found_version : public parse_input_file { public: explicit not_found_version(const std::string& why) : parse_input_file("Not found version " + why) {} }; class cannot_open_input_file : public parse_input_file { public: explicit cannot_open_input_file(const std::string& why) : parse_input_file("Can not open input file: " + why) {} }; class wrong_place_for_conditions : public parse_input_file { public: explicit wrong_place_for_conditions(const std::string& why) : parse_input_file("Wrong place for condition in line " + why) {} }; class bad_configuration : public parse_input_file { public: explicit bad_configuration(const std::string& why) : parse_input_file("Incorrect configuration in line " + why) {} }; class bad_coordinates : public parse_input_file { public: explicit bad_coordinates(const std::string& why) : parse_input_file("Incorrect coordinates in line " + why) {} }; class bad_version : public parse_input_file { public: explicit bad_version(const std::string& why) : parse_input_file("Incorrect version in line " + why) {} }; class bad_size : public parse_input_file { public: explicit bad_size(const std::string& why) : parse_input_file("Incorrect sizes in line " + why) {} }; class bad_rules : public parse_input_file { public: explicit bad_rules(const std::string& why) : parse_input_file("Incorrect rules in line " + why) {} }; class redefinition_of_configuration : public parse_input_file { public: explicit redefinition_of_configuration(const std::string& why) : parse_input_file("Redifinition of configuration in line " + why) {} }; } } } #endif
true
de32592381b914ba097e3c7f0641f652886a2a7e
C++
gutt/figures
/src/app/main.cpp
UTF-8
1,261
2.984375
3
[ "MIT" ]
permissive
#include "area_sumator.h" #include "data_source/binary_data_figures_reader.h" #include "dom/figures/rectangle.h" #include "dom/figures/square.h" #include <iostream> using namespace dom::figures; using namespace std; int main() { try { const char data[] = { 1, 0, 0, 20, // square 2, 10, 10, 20, 30, // rectangle 3, 6, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, // polygon 4, -10, -10, 5 // circle }; // create reader for binary data data_source::BinaryDataFiguresReader sr; // read figures data from array sr.read(data, sizeof(data)); // create standard area calculator implementation DefaultFigureAreaCalculator area_calculator; // create sumator with default area calculator FigureAreaSumator area_sumator(area_calculator); // read figure from source and move it to sumator while (!sr.isFigureQueueEmpty()) { area_sumator.addFigure(sr.popFigure()); } // output data cout << "Sum of all figures area:" << area_sumator.calculate() << endl; } catch (std::exception) { cout << "Exception occured! Exiting. " << endl; return 1; } return 0; }
true
b0902bbc00375da4726aff5b9995bba20a821390
C++
llylly/LapisParser
/exec/log/Logger.cpp
UTF-8
1,067
3.078125
3
[]
no_license
// // Created by lly on 06/10/2017. // #include "Logger.h" std::vector<Logger*> Logger::logs; Logger::Logger() { this->timestamp = time(0); this->level = 0; this->msg = ""; } BaseDataObject *Logger::toDataObject() { ObjectDataObject *obj = new ObjectDataObject(); (*obj)["timestamp"] = new IntegerDataObject(this->timestamp); (*obj)["level"] = new IntegerDataObject(this->level); (*obj)["msg"] = new StringDataObject(this->msg); return obj; } void Logger::addLog(Logger *_log) { Logger::logs.push_back(_log); } void Logger::cleanLog() { Logger::logs.clear(); } void Logger::printLog(std::ostream &os, int level) { for (std::vector<Logger*>::iterator ite = Logger::logs.begin(); ite != Logger::logs.end(); ++ite) { Logger *now = *ite; if (now->level >= level) { os << "[time: " << (now->timestamp) << " level: " << (now->level) << "] " << now->msg << std::endl; } } } std::vector<Logger*> *Logger::getLogs() { return &Logger::logs; }
true
c967f18a2c0c8d38bfbaf1f732d182713620602b
C++
storytold/RuntimeAudioImporter
/RuntimeAudioImporter/Source/RuntimeAudioImporter/Public/RuntimeAudioImporterLibrary.h
UTF-8
13,178
2.71875
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
// Georgy Treshchev 2021. #pragma once #include "Sound/SoundWave.h" #include "Async/Async.h" #include "RuntimeAudioImporterLibrary.generated.h" /** Possible audio importing results */ UENUM(BlueprintType, Category = "RuntimeAudioImporter") enum ETranscodingStatus { /** Success importing */ SuccessImporting UMETA(DisplayName = "Success Importing"), /** Failed to read Audio Data Array */ FailedToReadAudioDataArray UMETA(DisplayName = "Failed to read Audio Data Array"), /** SoundWave declaration error */ SoundWaveDeclarationError UMETA(DisplayName = "SoundWave declaration error"), /** Invalid audio format (Can't determine the format of the audio file) */ InvalidAudioFormat UMETA(DisplayName = "Invalid audio format"), /** The audio file does not exist */ AudioDoesNotExist UMETA(DisplayName = "Audio does not exist"), /** Load file to array error */ LoadFileToArrayError UMETA(DisplayName = "Load file to array error"), /** Transcoding PCM to Wav data error */ PCMToWavDataError UMETA(DisplayName = "PCM to Wav data error"), /** Generate compressed data error */ GenerateCompressedDataError UMETA(DisplayName = "Generate compressed data error"), /** Invalid compressed format error */ InvalidCompressedFormat UMETA(DisplayName = "Invalid compressed format") }; /** Possible audio formats (extensions) */ UENUM(BlueprintType, Category = "RuntimeAudioImporter") enum EAudioFormat { /** Determine format automatically */ Auto UMETA(DisplayName = "Determine format automatically"), /** MP3 format */ Mp3 UMETA(DisplayName = "mp3"), /** WAV format */ Wav UMETA(DisplayName = "wav"), /** FLAC format */ Flac UMETA(DisplayName = "flac"), /** Invalid format */ Invalid UMETA(DisplayName = "invalid (not defined format, CPP use only)", Hidden) }; /** List of all supported compression formats */ UENUM(BlueprintType, Category = "RuntimeAudioImporter") enum ECompressionFormat { /** Raw (Wav) data format. Not recommended because it doesn't work on packaged build */ RawData UMETA(DisplayName = "Raw Data"), /** Ogg Vorbis format. It is used, for example, on Android and Windows */ OggVorbis UMETA(DisplayName = "Ogg Vorbis"), /** ADPCM or LPCM formats. LPCM will be used if the compression quality is 100%, otherwise ADPCM */ ADPCMLPCM UMETA(DisplayName = "ADPCM/LPCM"), /** Ogg Opus format. Mostly not used anywhere, but can be used for personal purposes */ OggOpus UMETA(DisplayName = "Ogg Opus") }; /** Information about which buffers to fill */ USTRUCT(BlueprintType, Category = "RuntimeAudioImporter") struct FBuffersDetailsStruct { GENERATED_BODY() /** Needed compression format */ UPROPERTY(BlueprintReadWrite) TEnumAsByte<ECompressionFormat> CompressionFormat = OggVorbis; /** * Sound compression quality. The range of numbers is from 0 to 100, in percent. How much to compress the sound, where 0 is the maximum loss, 100 is the minimum. * Not used if CompressionFormat is "RawData" */ UPROPERTY(BlueprintReadWrite) int32 SoundCompressionQuality = 100; }; /** Basic SoundWave data. CPP use only. */ struct FSoundWaveBasicStruct { /** Number of channels */ int32 ChannelsNum; /** Sample rate (samples per second, sampling frequency) */ uint32 SampleRate; /** Sound wave duration, sec */ float Duration; }; /** Raw PCM Data */ struct FPCMStruct { /** Raw PCM data pointer */ uint8* RawPCMData; /** Number of PCM frames */ uint64 RawPCMNumOfFrames; /** Raw PCM data size */ uint32 RawPCMDataSize; }; /** Wav (or Raw) Data */ struct FWAVStruct { /** Wave data pointer */ uint8* WaveData; /** Wave data size */ int32 WaveDataSize; }; /** Compressed Data (Ogg Vorbis, ADPCM, etc) */ struct FCompressedStruct { /** Array, which contains compressed format data */ TArray<uint8> CompressedFormatData; }; /** Main, mostly in-memory information (like PCM, Wav, etc) */ struct FTranscodingFillStruct { /** SoundWave basic info (e.g. duration, number of channels, etc) */ FSoundWaveBasicStruct SoundWaveBasicInfo; /** Raw PCM Data info */ FPCMStruct PCMInfo; /** Wav (or Raw) Data info */ FWAVStruct WAVInfo; /** Compressed Data info (Ogg Vorbis, ADPCM, etc) */ FCompressedStruct CompressedInfo; }; /** Advanced CPP only structure which contains information about which buffers to fill */ struct FAdvancedBuffersStruct { /** Needed compression format. Do not select RawData here! If you want to fill Raw (Wav) Data, check the "FillRawData" parameter */ TEnumAsByte<ECompressionFormat> CompressionFormat; /** Whether to fill the compressed data or not */ bool FillCompressedData = false; /** Whether to fill PCM Data or not */ bool FillPCMData = false; /** Whether to fill Raw (Wav) data */ bool FillRawData = false; }; // Forward declaration of the FSoundQualityInfo structure struct FSoundQualityInfo; // Forward declaration of the UPreimportedSoundAsset class class UPreimportedSoundAsset; /** * Declare delegate which will be called during the transcoding process * * @param Percentage Percentage of importing completed (0-100%) */ DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnAudioProgress, const int32, Percentage); /** * Declare a delegate that will be called on the transcoding result * * @param RuntimeAudioImporterObject Runtime Audio Importer object reference * @param ReadySoundWave Ready SoundWave object reference * @param Status TranscodingStatus Enum in case an error occurs */ DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnAudioResult, class URuntimeAudioImporterLibrary*, RuntimeAudioImporterObjectRef, const USoundWave*, SoundWaveRef, const TEnumAsByte < ETranscodingStatus >&, Status); /** * Runtime Audio Importer object * Allows you to do various things with audio files in real time, for example, import audio files into a SoundWave engine object */ UCLASS(BlueprintType, Category = "RuntimeAudioImporter") class RUNTIMEAUDIOIMPORTER_API URuntimeAudioImporterLibrary : public UObject { GENERATED_BODY() public: /** Bind to know when the transcoding is on progress */ UPROPERTY(BlueprintAssignable, Category = "RuntimeAudioImporter") FOnAudioProgress OnProgress; /** Bind to know when the transcoding is complete (even if it fails) */ UPROPERTY(BlueprintAssignable, Category = "RuntimeAudioImporter") FOnAudioResult OnResult; /** Transcoding fill info. CPP use only */ FTranscodingFillStruct TranscodingFillInfo = FTranscodingFillStruct(); /** Buffers details info. CPP use only */ FBuffersDetailsStruct BuffersDetailsInfo = FBuffersDetailsStruct(); /** Advanced buffer details info. CPP use only (even as an input parameter) */ FAdvancedBuffersStruct AdvancedBuffersInfo = FAdvancedBuffersStruct(); bool bUseOfAdvancedBuffersInfo = false; /** * Instantiates a RuntimeAudioImporter object * * @return The RuntimeAudioImporter object. Bind to it's OnProgress and OnResult events to know when it is in the process of transcoding and imported * @note You must place the returned reference to the RuntimeAudioImporterLibrary in a separate variable so that the UObject is not removed during garbage collection */ UFUNCTION(BlueprintCallable, meta = (Keywords = "Create, Audio, Runtime, MP3, FLAC, WAV"), Category = "RuntimeAudioImporter") static URuntimeAudioImporterLibrary* CreateRuntimeAudioImporter(); /** * If you want to select a separate formats to fill (using of "FAdvancedBuffersStruct"), then use this method in CPP * * @param UseOfAdvancedBufferInfo Whether to use the advanced buffer info or not */ UFUNCTION() static URuntimeAudioImporterLibrary* CreateAdvancedRuntimeAudioImporter(const bool UseOfAdvancedBufferInfo); /** * Transcode audio file to SoundWave object * * @param FilePath Path to the audio file to import * @param Format Audio file format (extension) * @param BuffersDetails Information about which buffers to fill */ UFUNCTION(BlueprintCallable, meta = (Keywords = "Importer, Transcoder, Converter, Runtime, MP3, FLAC, WAV"), Category = "RuntimeAudioImporter") void ImportAudioFromFile(const FString& FilePath, TEnumAsByte<EAudioFormat> Format, const FBuffersDetailsStruct& BuffersDetails); /** * Import audio file from the preimported sound asset * * @param PreimportedSoundAssetRef PreimportedSoundAsset object reference. Should contains "BaseAudioDataArray" buffer * @param BuffersDetails Information about which buffers to fill */ UFUNCTION(BlueprintCallable, meta = (Keywords = "Importer, Transcoder, Converter, Runtime, MP3"), Category = "RuntimeAudioImporter") void ImportAudioFromPreimportedSound(UPreimportedSoundAsset* PreimportedSoundAssetRef, const FBuffersDetailsStruct& BuffersDetails); /** * Transcode audio file to USoundWave static object * * @param AudioDataArray Array of Audio byte data * @param Format Audio file format (extension) * @param BuffersDetails Information about which buffers to fill */ UFUNCTION(BlueprintCallable, meta = (Keywords = "Importer, Transcoder, Converter, Runtime, MP3, FLAC, WAV"), Category = "RuntimeAudioImporter") void ImportAudioFromBuffer(const TArray<uint8>& AudioDataArray, const TEnumAsByte<EAudioFormat>& Format, const FBuffersDetailsStruct& BuffersDetails); /** * Destroy SoundWave object. After the SoundWave is no longer needed, you need to call this function to free memory * * @param ReadySoundWave SoundWave object reference need to be destroyed * @return Whether the destruction of the SoundWave was successful or not */ UFUNCTION(BlueprintCallable, meta = (Keywords = "MP3, FLAC, WAV, Destroy"), Category = "RuntimeAudioImporter") static bool DestroySoundWave(USoundWave* ReadySoundWave); private: /** * Internal main audio transcoding function * * @param AudioDataArray Array of Audio byte data * @param Format Audio file format (extension) * @param BuffersDetails Information about which buffers to fill */ void ImportAudioFromBuffer_Internal(const TArray<uint8>& AudioDataArray, const TEnumAsByte<EAudioFormat>& Format, const FBuffersDetailsStruct& BuffersDetails); /** * Define SoundWave object reference * * @return Returns a ready USoundWave object */ USoundWave* DefineSoundWave(); /** * Fill SoundWave basic information (e.g. duration, number of channels, etc) * * @param SoundWaveRef SoundWave object reference */ void FillSoundWaveBasicInfo(USoundWave* SoundWaveRef) const; /** * Fill SoundWave Raw (Wave) data buffer * * @param SoundWaveRef SoundWave object reference */ void FillRawWaveData(USoundWave* SoundWaveRef) const; /** * Fill SoundWave compressed data buffer * * @param SoundWaveRef SoundWave object reference */ void FillCompressedData(USoundWave* SoundWaveRef); /** * Fill SoundWave PCM data buffer * * @param SoundWaveRef SoundWave object reference */ void FillPCMData(USoundWave* SoundWaveRef); /** * Transcode Audio from PCM to 16-bit WAV data * * @return Whether the transcoding was successful or not */ bool TranscodePCMToCompressedData(USoundWave* SoundWaveToGetData); /** * Transcode Audio from Audio Data to PCM Data * * @param AudioData Pointer to memory location of Audio byte data * @param AudioDataSize Memory size allocated for Audio byte data * @param Format Format of the audio file (e.g. mp3. flac, etc) * @return Whether the transcoding was successful or not */ bool TranscodeAudioDataArrayToPCMData(const uint8* AudioData, uint32 AudioDataSize, TEnumAsByte<EAudioFormat> Format); /** * Transcode Audio from PCM to 16-bit WAV data * * @return Whether the transcoding was successful or not */ bool TranscodePCMToWAVData(); /** * Get Audio Format by extension * * @param FilePath File path, where to find the format (by extension) * @return Returns the found audio format (e.g. mp3. flac, etc) by EAudioFormat Enum */ UFUNCTION(BlueprintCallable, Category = "RuntimeAudioImporter") static TEnumAsByte<EAudioFormat> GetAudioFormat(const FString& FilePath); /** * Generate FSoundQualityInfo Enum based on SoundWave and already defined Sample Rate */ FSoundQualityInfo GenerateSoundQualityInfo(USoundWave* SoundWaveToGetData) const; /** * Get the platform-specific format name based on the base format to find the compressed buffer to fill * * @param Format Base format name (it can be "OGG", "LPCM", etc) */ static FName GetPlatformSpecificFormat(const FName Format); /** * Audio transcoding progress callback * @param Percentage Percentage of importing completion (0-100%) */ void OnProgress_Internal(int32 Percentage); /** * Audio transcoding finished callback * * @param ReadySoundWave A ready SoundWave object * @param Status TranscodingStatus Enum in case an error occurs */ void OnResult_Internal(USoundWave* ReadySoundWave, const TEnumAsByte<ETranscodingStatus>& Status); };
true
7813ef1df4b83f07a1233399fc6a2fde1328a963
C++
ojasvishaklya/competitive
/4.Tree/lec027/AVL_basics.cpp
UTF-8
3,062
4.0625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; class Node { public: int val; Node *left = nullptr; Node *right = nullptr; int height; int balance; Node(int val) { this->val = val; this->height = 0; this->balance = 0; } }; Node *create(vector<int> &arr, int si, int ei) { if (ei < si) return nullptr; int mid = (si + ei) / 2; Node *node = new Node(arr[mid]); node->left = create(arr, si, mid - 1); node->right = create(arr, mid + 1, ei); return node; } void display(Node *node) { string s = ""; if (node->left != nullptr) { s += to_string(node->left->val) + "[" + to_string(node->left->balance) + "," + to_string(node->left->height) + "]"; } s += " <- " + to_string(node->val) + "[" + to_string(node->balance) + "," + to_string(node->height) + "]" + " -> "; if (node->right != nullptr) { s += to_string(node->right->val) + "[" + to_string(node->right->balance) + "," + to_string(node->right->height) + "]"; } cout << s << endl; if (node->left != nullptr) { display(node->left); } if (node->right != nullptr) { display(node->right); } return; } void update_balance_height(Node *root) { int lh = -1; int rh = -1; if (root->left) lh = root->left->height; if (root->right) lh = root->right->height; root->height = max(lh, rh) + 1; root->balance = lh - rh; } Node *rotateLL(Node *A) { Node *B = A->left; Node *BR = B->right; B->right = A; A->left = BR; update_balance_height(A); update_balance_height(B); return B; } Node *rotateRR(Node *A) { Node *B = A->right; Node *BL = B->left; B->left = A; A->right = BL; update_balance_height(A); update_balance_height(B); return B; } Node *decide_rotation(Node *root) { update_balance_height(root); if (root->balance == 2) { if (root->left->balance == 1) return rotateLL(root); else if (root->left->balance == -1) { root->left = rotateRR(root->left); return rotateLL(root); } } else if (root->balance == -2) { if (root->right->balance == 1) { root->right = rotateLL(root->right); return rotateRR(root); } else if (root->right->balance == -1) return rotateRR(root); } return root; } Node *addNode(Node *root, int val) { if (!root) return new Node(val); if (val < root->val) root->left = addNode(root->left, val); if (val > root->val) root->right = addNode(root->right, val); return decide_rotation(root); } int main() { vector<int> arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130}; Node *root = create(arr, 0, arr.size() - 1); display(root); addNode(root, 65); addNode(root, 66); addNode(root, 67); addNode(root, 68); display(root); return 0; }
true
8dff6b76e3c775e138a1c4c8f47742872c429ee9
C++
i12n/VortexApplication
/Dynamics/cDirectorModule.h
UTF-8
846
2.671875
3
[]
no_license
#ifndef __C_DIRECTOR_MODULE_H__ #define __C_DIRECTOR_MODULE_H__ #include "cSceneModule.h" #include "cControllerModule.h" class cDirector{ public: cDirector(){ scene = cScene::getInstance();} /// regist entity and controller for sene, override in derived class /// virtual void regist()=0; /// configure scene,as an interface /// static void action(cDirector *director); /// send command to scene,as an interface /// static void sendCommand( const char *name, sCommand cmd ); virtual ~cDirector(){}; protected: cScene *scene; }; void cDirector::action(cDirector *director){ director->regist(); } void cDirector::sendCommand(const char *name, sCommand cmd){ cController * controller = cScene::getInstance()->getController( name ); if( controller ) controller->regist( cmd ); }; #endif //__C_DIRECTOR_MODULE_H__
true
9af07021731db0f181cadf908298c0c03982d95b
C++
shivangraina/cf
/codeforces/1283/C.cpp
UTF-8
957
2.53125
3
[]
no_license
#include <bits/stdc++.h> #include <iostream> #define ll long long using namespace std; ll Ceil(ll a, ll b) { return ((a / b) + (a % b != 0)); } # define MAXX 10000000000000 int main() { // out [i]=v[i] // in [v[i]]=i ll n; cin >> n; vector<ll> in(200005, -1); vector<ll> out(200005, -1); for (int i = 1; i <= n; i++) { ll e; cin >> e; if(e!=0){ out[i] = e; in[e] = i; } } vector<ll>a,b; for (int i = 1; i <= n; i++) { if (in[i] ==-1) a.push_back(i); if (out[i] == -1) b.push_back(i); } sort(a.begin(), a.end()); sort(b.rbegin(), b.rend()); int trouble=-1; for (int i = 0; i < a.size(); i++) { out[b[i]] = a[i]; if(b[i]==a[i]) trouble=i; } if(trouble!=-1){ for (int i = 0; i < a.size(); i++) { if (i != trouble) { swap(out[b[trouble]], out[b[i]]); break; } } } for (int i = 1; i <= n; i++) cout << out[i] << " "; cout<<"\n"; }
true
7e7f0d25a89a242fa158dfbd811790a7e8bf0487
C++
IvanVan/Algorithms-and-data-structures-at-university
/queue by vector/main.cpp
UTF-8
2,201
2.578125
3
[]
no_license
#include <bits/stdc++.h> #include <malloc.h> using namespace std; int* a = (int*)(malloc(2 * sizeof(int))); int sz = 2, it1 = 0, it2 = 0; void add (int x){ if (it2 == sz && it1 != 0){ it2 = 0; } if (it1 == it2 && it2 != 0){ int* b = (int*)(malloc(2 * sz * sizeof(int))); int j = 0; for (int i = it1; i < sz; i++, j++){ b[j] = a[i]; } for (int i = 0; i < it2; i++, j++){ b[j] = a[i]; } a = b; a[sz] = x; it1 = 0; it2 = sz + 1; sz *= 2; return; } if (it1 == 0 && it2 == sz){ int* b = (int*)(malloc(2 * sz * sizeof(int))); int j = 0; for (int i = it1; i < sz; i++, j++){ b[j] = a[i]; } a = b; a[sz] = x; it1 = 0; it2 = sz + 1; sz *= 2; } else { a[it2] = x; it2++; } } int get_dist (){ if (it2 > it1){ return (it2 - it1); } else { return (sz - it1 + it2); } } int dist = 0; void er (){ printf("%d\n", a[it1]); it1++; if (it1 == it2){ it1 = 0; it2 = 0; } if (it1 == sz){ it1 = 0; } dist = get_dist(); if (sz / get_dist() == 4){ int* b = (int*)(malloc((sz /2) * sizeof(int))); int j = 0; if (it2 > it1){ for (int i = it1; i < it2; i++, j++){ b[j] = a[i]; } } else { for (int i = it1; i < sz; i++, j++){ b[j] = a[i]; } for (int i = 0; i < it2; i++, j++){ b[j] = a[i]; } } a = b; it1 = 0; it2 = j; sz /= 2; } } int main() { // freopen("input.txt", "r", stdin); freopen("queue1.in", "r", stdin); freopen("queue1.out", "w", stdout); int n; scanf("%d\n", &n); for (int i = 0; i < n; i++){ char c; int x; scanf("%c", &c); if (c == '+'){ scanf(" %d", &x); add(x); } else { er(); } if (i != n - 1){ scanf("\n"); } } return 0; }
true
c240a60db8cbdb379c02ca9867594c8765b3e928
C++
netanelyo/AdvancedProgramming
/AdvancedProgramming-HW3Official/BoardDataImpl.cpp
UTF-8
445
2.8125
3
[]
no_license
#include "BoardDataImpl.h" #include "BattleshipGameUtils.h" char BoardDataImpl::charAt(Coordinate c) const { auto sq = m_board.getBoardSquare(c); if (sq != BattleshipGameUtils::Constants::EMPTY_SIGN) { if ((isupper(sq) && m_player == BattleshipGameUtils::Constants::PLAYER_A) || (islower(sq) && m_player == BattleshipGameUtils::Constants::PLAYER_B)) return sq; return BattleshipGameUtils::Constants::EMPTY_SIGN; } return sq; }
true
aff8c1cfdffe88c48b55b4d6ed65e0e1b3c0ff68
C++
mmhancxt/HashCode2016
/code/OrderFirst.hpp
UTF-8
2,734
2.8125
3
[]
no_license
#pragma once #include "OrderFirst.hpp" #include "../Common.h" #include "InputLoader.h" #include "Objects.h" #include <iostream> #include <map> #include <numeric> #include <algorithm> using namespace std; fstream fout; class Distribution { public: InputLoader & loader; Distribution(InputLoader & _loader) : loader(_loader) {} virtual void run() = 0; }; class OrderFirstDistribution : public Distribution { public: OrderFirstDistribution(InputLoader & _loader) : Distribution(_loader) {} void send_product(Drone& drone, WareHouse& warehouse, int productId, Order & order) { int flight_available_capacity = loader.const_maxDroneLoad; int warehouse_product_count = warehouse.availableProducts[productId]; int order_product_count = order.purchasedProducts[productId]; Product const& product = getProductById(productId); int max_flight_product_count = flight_available_capacity / product.weight; int deliver_product_count = std::min(std::min(warehouse_product_count, order_product_count), max_flight_product_count); load(drone.id, warehouse.id, productId, deliver_product_count); warehouse.availableProducts[productId] -= deliver_product_count; deliver(drone.id, order.id, productId, deliver_product_count); order.purchasedProducts[productId] -= deliver_product_count; int expense = CalculateEula(warehouse.position, drone.position); expense += CalculateEula(warehouse.position, order.deliverPosition); expense += 2; drone.nextUsableTurn += expense; drone.position = order.deliverPosition; } Drone & getFlight() { std::sort(loader.drones.begin(), loader.drones.end(), [](Drone const& l, Drone const& r) { return l.nextUsableTurn < r.nextUsableTurn; }); return loader.drones.front(); } WareHouse* getWarehouse(Product const & p, Position const& order, Position const& flight) { int minimum = numeric_limits<int>::max(); WareHouse* w; for (auto & warehouse : loader.warehouses) { if (warehouse.containsProduct(p.id)) { int d = CalculateEula(warehouse.position, order) + CalculateEula(warehouse.position, flight); if (d < minimum) { minimum = d; w = &warehouse; } } } return w; } Product& getProductById(int id) { return loader.products[id]; } void scheduleFlightForOrder(Order & order) { auto products = order.purchasedProducts; for (auto& product : products) { while (order.purchasedProducts[product.first] > 0) { Drone & flight = getFlight(); WareHouse * w = getWarehouse(getProductById(product.first), order.deliverPosition, flight.position); send_product(flight, *w, product.first, order); } } } void run() { for (auto& order : loader.orders) { scheduleFlightForOrder(order); } } };
true
6103cc2391b4cd9e7befdbfe9c829f9deb5325da
C++
g-ernade/DS2VS2019
/实验报告程序/实验3.cpp
GB18030
3,128
3.21875
3
[ "MIT" ]
permissive
<<<<<<< HEAD #include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node* next; } Lnode; Lnode* create(int n) { int i; Lnode* h, * p, * r = (Lnode*)malloc(sizeof(Lnode)); //*ṹָ*h*p*r,ֱrһLnodeʹСڴռ䣬ѷռ׵ַǿתLnode *͵* r->data = n;h = r; //*nֵڵrdata,*r*hָβ* for (i = n - 1; i > 0; i--) { p = (Lnode*)malloc(sizeof(Lnode)); //*ֱpһLnodeʹСڴռ䣬ѷռ׵ַǿתLnode *͵* p ->data = i; p->next = h; h = p; } r->next = h; return h; } void jeseph(Lnode* p, int m) { Lnode* q; int j = 0; printf("outqueue order : "); if (m == 1) { //*޸m=1ʱѭ㷨߼* do { printf(" %d ", p->data); p = p->next; } while (((p->next)->data) != 1); printf(" %d ", p->data); exit(0); }; do { j++; if (j == m-1) { q = p->next; //*pĺ̽ڵ㸳ֵΪq* p->next = q->next; //*qĺ̽ڵ,Ҳԭpĺ̵ĺ̽ڵ,ֵpĺ̽ڵ,൱ԭpĺ̽ڵ* printf(" %d ", q->data); j = 0; free(q); //*,ͷԭpĺ̽ڵڴ* } p = p->next; } while (p->next != p); printf(" %d\n", p->data); free(p); } void main() { Lnode* h; int m, n; printf("\n input n, m = "); scanf(" %d, %d", &n, &m); h = create(n); jeseph(h, m); } ======= #include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node* next; } Lnode; Lnode* create(int n) { int i; Lnode* h, * p, * r = (Lnode*)malloc(sizeof(Lnode)); //*ṹָ*h*p*r,ֱrһLnodeʹСڴռ䣬ѷռ׵ַǿתLnode *͵* r->data = n;h = r; //*nֵڵrdata,*r*hָβ* for (i = n - 1; i > 0; i--) { p = (Lnode*)malloc(sizeof(Lnode)); //*ֱpһLnodeʹСڴռ䣬ѷռ׵ַǿתLnode *͵* p ->data = i; p->next = h; h = p; } r->next = h; return h; } void jeseph(Lnode* p, int m) { Lnode* q; int j = 0; printf("outqueue order : "); if (m == 1) { //*޸m=1ʱѭ㷨߼* do { printf(" %d ", p->data); p = p->next; } while (((p->next)->data) != 1); printf(" %d ", p->data); exit(0); }; do { j++; if (j == m-1) { q = p->next; //*pĺ̽ڵ㸳ֵΪq* p->next = q->next; //*qĺ̽ڵ,Ҳԭpĺ̵ĺ̽ڵ,ֵpĺ̽ڵ,൱ԭpĺ̽ڵ* printf(" %d ", q->data); j = 0; free(q); //*,ͷԭpĺ̽ڵڴ* } p = p->next; } while (p->next != p); printf(" %d\n", p->data); free(p); } void main() { Lnode* h; int m, n; printf("\n input n, m = "); scanf(" %d, %d", &n, &m); h = create(n); jeseph(h, m); } >>>>>>> 1d32ec6b7d158dfc809fded408863afffdfe1337
true
97747aff22967010e0498850705806c8e4a55f99
C++
Leandro-Rodrigues/Olimpiada-Brasileira-de-Informatica
/OBI 2017/Fase2/dario_xerxes.cpp
UTF-8
543
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define lli long long int #define ulli long long unsigned #define INF 0x3f3f3f3f #define LINF 0x3f3f3f3f3f3f3f3fL int main() { ios::sync_with_stdio(false); cin.tie(0); int vet[] = {0, 1, 2, 3, 4, 0, 1}; int n, d, x; int contd = 0, contx = 0; cin >> n; for (int i = 0; i < n; i++) { cin >> d >> x; if (vet[d + 2] == x || vet[d + 1] == x) contd++; else contx++; } puts(contx > contd ? "xerxes" : "dario"); return 0; }
true
912f8881061549a17ffd8266ab5e7996e225fb11
C++
JG-11/competitive-programming
/General/Trees/BinaryTree/BinaryTree.cpp
UTF-8
2,596
3.734375
4
[]
no_license
#include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; class Node { public: int data; Node* left; Node* right; }; int main(void){ Node* root = new Node(); Node* leftChild = new Node(); Node* rightChild = new Node(); Node* leftLeftChild = new Node(); Node* leftRightChild = new Node(); root->data = 1; root->left = leftChild; root->right = rightChild; leftChild->data = 2; leftChild->left = leftLeftChild; leftChild->right = leftRightChild; rightChild->data = 3; rightChild->left = NULL; rightChild->right = NULL; leftLeftChild->data = 4; leftLeftChild->left = NULL; leftLeftChild->right = NULL; leftRightChild->data = 5; leftRightChild->left = NULL; leftRightChild->right = NULL; //Preorder traversal vector<int> preorder; stack<Node*> preorderNodes; if(root == NULL){ cout << "Empty tree" << endl; } else { preorderNodes.push(root); while(!preorderNodes.empty()){ Node* newNode = new Node(); newNode = preorderNodes.top(); preorderNodes.pop(); preorder.emplace_back(newNode->data); if(newNode->right != NULL){ preorderNodes.push(newNode->right); } if(newNode->left != NULL){ preorderNodes.push(newNode->left); } } cout << "Preorder" << endl; for(auto x : preorder){ cout << x << " "; } cout << endl; } //Inorder traversal vector<int> inorder; stack<Node*> inorderNodes; Node* current = root; if(current != NULL){ while(current != NULL || !inorderNodes.empty()){ while(current != NULL){ inorderNodes.push(current); current = current->left; } current = inorderNodes.top(); inorderNodes.pop(); inorder.emplace_back(current->data); current = current->right; } cout << "Inorder" << endl; for(auto x : inorder){ cout << x << " "; } cout << endl; } else { cout << "Empty tree" << endl; } //Postorder traversal vector<int> postorder; stack<Node*> postorderNodes; if(root == NULL){ cout << "Empty tree" << endl; } else { postorderNodes.push(root); while(!postorderNodes.empty()){ Node* newNode = postorderNodes.top(); postorderNodes.pop(); postorder.emplace_back(newNode->data); if(newNode->left != NULL){ postorderNodes.push(newNode->left); } if(newNode->right != NULL){ postorderNodes.push(newNode->right); } } cout << "Postorder" << endl; reverse(postorder.begin(), postorder.end()); for(auto x : postorder){ cout << x << " "; } cout << endl; } return 0; }
true
f01bdddf72dfda27bb82b1b444a867ef42fb1f26
C++
tantrojan/GFG-Questions
/BinarySearch/first_occur.cpp
UTF-8
599
3.359375
3
[]
no_license
// Returns the index of first occurence of the element if present else returns -1 #include<bits/stdc++.h> using namespace std; int first_occur(int arr[], int l, int r, int key) { int m; while(l<=r) { m=l+(r-l)/2; if(arr[m]==key && ( m==0 || arr[m-1]<key)) { return m+1; } else if(arr[m]>=key) { r=m-1; } else { l=m+1; } } return -1; } int main() { int n,i; cin>>n; int arr[n]; for(i=0;i<n;i++)cin>>arr[i]; int key; cin>>key; sort(arr,arr+n); int res=first_occur(arr,0,n-1,key); cout<<res; // res=Floor(arr,0,n-1,key); // cout<<endl<<res; return 0; }
true
2b9e5f2057883415dcd2c126bf75816f8744b51e
C++
theShaswato/CppEasyString
/example07.cpp
UTF-8
348
2.78125
3
[]
no_license
#include <iostream> #include <string> #include "easystring.hpp" using namespace std; int main() { // Writing string to a file string file_name, text; cout << "Enter file name: "; getline(cin, file_name); cout << "Enter your text: "; getline(cin, text); easystring::strtof(text, file_name, "error"); return 0; }
true
aa1b162b7567bbcbbd47d63c5ba97304d16bfd0e
C++
onesketchyguy/LetsBeATroll
/Project/ConsoleGameEngine/Engine.h
UTF-8
53,951
2.65625
3
[ "Unlicense" ]
permissive
/* OneLoneCoder.com - Command Line Game Engine "Who needs a frame buffer?" - @Javidx9 The Original & Best :P One Lone Coder License ~~~~~~~~~~~~~~~~~~~~~~ - This software is Copyright (C) 2018 Javidx9 - This is free software - This software comes with absolutely no warranty - The copyright holder is not liable or responsible for anything this software does or does not - You use this software at your own risk - You can distribute this software - You can modify this software - Redistribution of this software or a derivative of this software must attribute the Copyright holder named above, in a manner visible to the end user License ~~~~~~~ One Lone Coder Console Game Engine Copyright (C) 2018 Javidx9 This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions; See license for details. Original works located at: https://www.github.com/onelonecoder https://www.onelonecoder.com https://www.youtube.com/javidx9 GNU GPLv3 https://github.com/OneLoneCoder/videos/blob/master/LICENSE From Javidx9 :) ~~~~~~~~~~~~~~~ Hello! Ultimately I don't care what you use this for. It's intended to be educational, and perhaps to the oddly minded - a little bit of fun. Please hack this, change it and use it in any way you see fit. You acknowledge that I am not responsible for anything bad that happens as a result of your actions. However this code is protected by GNU GPLv3, see the license in the github repo. This means you must attribute me if you use it. You can view this license here: https://github.com/OneLoneCoder/videos/blob/master/LICENSE Cheers! Background ~~~~~~~~~~ If you've seen any of my videos - I like to do things using the windows console. It's quick and easy, and allows you to focus on just the code that matters - ideal when you're experimenting. Thing is, I have to keep doing the same initialisation and display code each time, so this class wraps that up. Author ~~~~~~ Twitter: @javidx9 http://twitter.com/javidx9 Blog: http://www.onelonecoder.com YouTube: http://www.youtube.com/javidx9 Videos: ~~~~~~ Original: https://youtu.be/cWc0hgYwZyc Added mouse support: https://youtu.be/tdqc9hZhHxM Beginners Guide: https://youtu.be/u5BhrA8ED0o Shout Outs! ~~~~~~~~~~~ Thanks to cool people who helped with testing, bug-finding and fixing! wowLinh, JavaJack59, idkwid, kingtatgi, Return Null, CPP Guy, MaGetzUb Last Updated: 02/07/2018 Usage: ~~~~~~ This class is abstract, so you must inherit from it. Override the OnUserCreate() function with all the stuff you need for your application (for thready reasons it's best to do this in this function and not your class constructor). Override the OnUserUpdate(float fElapsedTime) function with the good stuff, it gives you the elapsed time since the last call so you can modify your stuff dynamically. Both functions should return true, unless you need the application to close. int main() { // Use olcConsoleGameEngine derived app OneLoneCoder_Example game; // Create a console with resolution 160x100 characters // Each character occupies 8x8 pixels game.ConstructConsole(160, 100, 8, 8); // Start the engine! game.Start(); return 0; } Input is also handled for you - interrogate the m_keys[] array with the virtual keycode you want to know about. bPressed is set for the frame the key is pressed down in, bHeld is set if the key is held down, bReleased is set for the frame the key is released in. The same applies to mouse! m_mousePosX and Y can be used to get the current cursor position, and m_mouse[1..5] returns the mouse buttons. The draw routines treat characters like pixels. By default they are set to white solid blocks - but you can draw any unicode character, using any of the colours listed below. There may be bugs! See my other videos for examples! http://www.youtube.com/javidx9 Lots of programs to try: http://www.github.com/OneLoneCoder/videos Chat on the Discord server: https://discord.gg/WhwHUMV Be bored by Twitch: http://www.twitch.tv/javidx9 */ #pragma once #pragma comment(lib, "winmm.lib") #ifndef UNICODE #error Please enable UNICODE for your compiler! VS: Project Properties -> General -> \ Character Set -> Use Unicode. Thanks! - Javidx9 #endif #include <windows.h> #include <iostream> #include <chrono> #include <vector> #include <list> #include <thread> #include <atomic> #include <condition_variable> const double PI = 3.14159265f; struct TimeConstruct { float timeSinceLevelLoad; float time; float elapsedTime; void UpdateTime(float _elapsedTime) { time += _elapsedTime; timeSinceLevelLoad += _elapsedTime; elapsedTime = _elapsedTime; } }; TimeConstruct* Time; class Collider { public: Collider() = default; Collider(std::wstring spriteData, int spriteWidth, int spriteHeight) { this->posX = this->posY = 0; this->width = -1; this->height = -1; this->offX = spriteWidth; this->offY = spriteHeight; for (size_t i = 0; i < spriteWidth * spriteHeight; i++) { int ix = i % spriteWidth; int iy = i / spriteWidth; if (spriteData[i] != '.') { // Calculate the start position if (ix < this->offX) { this->offX = ix; } if (iy < this->offY) { this->offY = iy; } // Calculate the bounds if (ix - this->offX > this->width) { this->width = ix - this->offX; } if (iy - this->offY > this->height) { this->height = iy - this->offY; } } } } Collider(int width, int height) { this->width = width; this->height = height; } public: int width = 0, height = 0; int offX = 0, offY = 0; int posX = 0, posY = 0; public: int GetTop() { return posY + offY; } int GetBottom() { return posY + offY + height; } int GetMiddleY() { return (int)(posY + offY + (height / 2.0f)); } int GetLeft() { return posX + offX; } int GetRight() { return posX + offX + width; } int GetMiddleX() { return (int)(posX + offX + (width / 2.0f)); } public: void UpdatePosition(int x, int y) { posX = x; posY = y; } bool CheckOverlaps(int x, int y) { bool withinY = y <= GetBottom() && y >= GetTop(); bool withinX = x >= GetLeft() && x <= GetRight(); return withinX && withinY; } bool CheckCollision(Collider* other) { int otherRight = other->GetRight(); int otherLeft = other->GetLeft(); int otherTop = other->GetTop(); int otherBot = other->GetBottom(); bool withinY = (otherTop <= GetBottom() && otherTop >= GetTop()) || (otherBot <= GetBottom() && otherBot >= GetTop()); bool withinX = (otherRight >= GetLeft() && otherRight <= GetRight()) || (otherLeft >= GetLeft() && otherLeft <= GetRight()); return withinX && withinY; } }; int Loop(int value, int min, int max) { if (value > max) { return min; } if (value < min) { return max; } return value; } int Clamp(int value, int min, int max) { if (value > max) { return max; } if (value < min) { return min; } return value; } float Clamp(float value, float min, float max) { if (value > max) { return max; } if (value < min) { return min; } return value; } float GetAngleToTarget(float targetX, float targetY, float startX, float startY) { float angle = 0; float distX = targetX - startX; float distY = targetY - startY; return atan2(distY, distX); } enum Key { NONE, UP = 38, DOWN = 40, LEFT = 37, RIGHT = 39, SPACE = 32, BACK = 8, TAB = 9, SHIFT = 16, CTRL, INS = 45, DEL, HOME, END, PGUP, PGDN, ESCAPE = 27, RETURN = 13, ENTER, PAUSE, SCROLL, NP0 = 96, NP1, NP2, NP3, NP4, NP5, NP6, NP7, NP8, NP9, NP_MUL, NP_DIV, NP_ADD, NP_SUB, NP_DECIMAL, PERIOD, EQUALS, COMMA, MINUS, OEM_1, OEM_2, OEM_3, OEM_4, OEM_5, OEM_6, OEM_7, OEM_8, CAPS_LOCK, ENUM_END, K0 = 49, K1, K2, K3, K4, K5, K6, K7, K8, K9, A = 65, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, }; enum COLOUR { FG_BLACK = 0x0000, FG_DARK_BLUE = 0x0001, FG_DARK_GREEN = 0x0002, FG_DARK_CYAN = 0x0003, FG_DARK_RED = 0x0004, FG_DARK_MAGENTA = 0x0005, FG_DARK_YELLOW = 0x0006, FG_GREY = 0x0007, // Thanks MS :-/ FG_DARK_GREY = 0x0008, FG_BLUE = 0x0009, FG_GREEN = 0x000A, FG_CYAN = 0x000B, FG_RED = 0x000C, FG_MAGENTA = 0x000D, FG_YELLOW = 0x000E, FG_WHITE = 0x000F, BG_BLACK = 0x0000, BG_DARK_BLUE = 0x0010, BG_DARK_GREEN = 0x0020, BG_DARK_CYAN = 0x0030, BG_DARK_RED = 0x0040, BG_DARK_MAGENTA = 0x0050, BG_DARK_YELLOW = 0x0060, BG_GREY = 0x0070, BG_DARK_GREY = 0x0080, BG_BLUE = 0x0090, BG_GREEN = 0x00A0, BG_CYAN = 0x00B0, BG_RED = 0x00C0, BG_MAGENTA = 0x00D0, BG_YELLOW = 0x00E0, BG_WHITE = 0x00F0, }; enum PIXEL_TYPE { PIXEL_SOLID = 0x2588, PIXEL_THREEQUARTERS = 0x2593, PIXEL_HALF = 0x2592, PIXEL_QUARTER = 0x2591, }; int GetPixel(PIXEL_TYPE type) { switch (type) { case PIXEL_SOLID: return 0; case PIXEL_THREEQUARTERS: return 1; case PIXEL_HALF: return 2; case PIXEL_QUARTER: return 3; default: return 0x1; // Debug char } } int GetPixelFromChar(char type) { switch (type) { case (char)'4': return 0; case (char)'3': return 1; case (char)'2': return 2; case (char)'1': return 3; default: return 0x1; // Debug char } } namespace SPRITES { std::wstring GetTrollSprite(int no) { switch (no) { case 0: // Idle return L"................4444......44444444..444333333444.4311331134...43333334....44444444.....422224......442244......444444......44..44..............."; case 1: // Walk 1 return L"................4444......44444444..444333333444.4311331134...43333334....44444444.....422224......442244......444444..........44..............."; case 2: // Walk 2 return L"................4444......44444444..444333333444.4311331134...43333334....44444444.....422224......442244......444444......44..................."; case 3: return L"...........##....#....#..#...#........#.............#..#.......#....#......#......####.....#.........##.......#.....#....#.......#.............."; default: break; } return L""; } std::wstring GetPersonSprite(int no) { std::wstring map; switch (no) { case 0: // Idle map = L"............................4444.......433334......413314......433334......444444.......4334........4444........4444........4..4................"; break; case 1: // Walk 1 map = L"............................4444.......433334......413314......433334......444444.......4334........44444.......444.........4..................."; break; case 2: // Walk 2 map = L"............................4444.......433334......413314......433334......444444.......4334.......44444.........444...........4................"; break; case 3: return L"...........##....#....#..#...#........#.............#..#.......#....#......#......####.....#.........##.......#.....#....#.......#.............."; default: break; } return map; } std::wstring GetExplosionSprite() { return L"...........##....#....#..#...#........#.............#..#.......#....#......#......####.....#.........##.......#.....#....#.......#.............."; } std::wstring GetProjectileSprite() { return L"...............22322........232..........3...........3...........3...........3...........3...........3..........444..........4.................."; } std::wstring GetBridgeStrut() { return L"...............................................................444444.....44333344....43222234....43211234....43211234....43211234....43211234.."; } enum SpriteTag { Troll, Person, Explosion, Projectile, BridgeStrut }; std::wstring GetSprite(SpriteTag tag, int index = 0) { switch (tag) { case 0: return GetTrollSprite(index); case 1: return GetPersonSprite(index); case 2: return GetExplosionSprite(); case 3: return GetProjectileSprite(); case 4: return GetBridgeStrut(); default: break; } } } class Sprite { private: int width, height; int spriteLength; short* glyphs = nullptr; short* colors = nullptr; int currentSpriteIndex = 0; std::wstring spriteData; SPRITES::SpriteTag spriteTag; public: int GetWidth() { return width; } int GetHeight() { return height; } void SetSpriteIndex(int index) { currentSpriteIndex = index; } int GetSpriteIndex() { return currentSpriteIndex; } std::wstring GetSprite(int index = 0) { return SPRITES::GetSprite(spriteTag, index); } std::wstring GetCurrentSprite() { return SPRITES::GetSprite(spriteTag, currentSpriteIndex); } void ResetSprite() { SetSpriteIndex(0); SetupSprite(); } void SetupSprite() { spriteData = GetSprite(); // Calculate the sprite for (size_t i = 0; i < spriteLength; i++) { int x = i % width; int y = i / width; SetGlyph(x, y, spriteData[i]); SetColor(x, y, spriteData[i] != '.' ? FG_WHITE : FG_BLACK); } } public: void SetGlyph(int x, int y, short c) { if (x < 0 || x >= width || y < 0 || y >= height) return; else glyphs[y * width + x] = c; } void SetColor(int x, int y, short c) { if (x < 0 || x >= width || y < 0 || y >= height) return; else colors[y * width + x] = c; } short GetGlyph(int x, int y) { if (x < 0 || x >= width || y < 0 || y >= height) return L' '; else return glyphs[y * width + x]; } short GetColor(int x, int y) { if (x < 0 || x >= width || y < 0 || y >= height) return FG_BLACK; else return colors[y * width + x]; } public: Sprite() = default; Sprite(int width, int height, SPRITES::SpriteTag spriteTag) { this->width = width; this->height = height; this->spriteTag = spriteTag; spriteLength = width * height; glyphs = new short[spriteLength]; colors = new short[spriteLength]; SetupSprite(); } }; class olcSprite { public: olcSprite() { } olcSprite(int w, int h) { Create(w, h); } olcSprite(std::wstring sFile) { if (!Load(sFile)) Create(8, 8); } int nWidth = 0; int nHeight = 0; private: short* m_Glyphs = nullptr; short* m_Colours = nullptr; void Create(int w, int h) { nWidth = w; nHeight = h; m_Glyphs = new short[w * h]; m_Colours = new short[w * h]; for (int i = 0; i < w * h; i++) { m_Glyphs[i] = L' '; m_Colours[i] = FG_BLACK; } } public: void SetGlyph(int x, int y, short c) { if (x < 0 || x >= nWidth || y < 0 || y >= nHeight) return; else m_Glyphs[y * nWidth + x] = c; } void SetColour(int x, int y, short c) { if (x < 0 || x >= nWidth || y < 0 || y >= nHeight) return; else m_Colours[y * nWidth + x] = c; } short GetGlyph(int x, int y) { if (x < 0 || x >= nWidth || y < 0 || y >= nHeight) return L' '; else return m_Glyphs[y * nWidth + x]; } short GetColour(int x, int y) { if (x < 0 || x >= nWidth || y < 0 || y >= nHeight) return FG_BLACK; else return m_Colours[y * nWidth + x]; } short SampleGlyph(float x, float y) { int sx = (int)(x * (float)nWidth); int sy = (int)(y * (float)nHeight - 1.0f); if (sx < 0 || sx >= nWidth || sy < 0 || sy >= nHeight) return L' '; else return m_Glyphs[sy * nWidth + sx]; } short SampleColour(float x, float y) { int sx = (int)(x * (float)nWidth); int sy = (int)(y * (float)nHeight - 1.0f); if (sx < 0 || sx >= nWidth || sy < 0 || sy >= nHeight) return FG_BLACK; else return m_Colours[sy * nWidth + sx]; } bool Save(std::wstring sFile) { FILE* f = nullptr; _wfopen_s(&f, sFile.c_str(), L"wb"); if (f == nullptr) return false; fwrite(&nWidth, sizeof(int), 1, f); fwrite(&nHeight, sizeof(int), 1, f); fwrite(m_Colours, sizeof(short), nWidth * nHeight, f); fwrite(m_Glyphs, sizeof(short), nWidth * nHeight, f); fclose(f); return true; } bool Load(std::wstring sFile) { delete[] m_Glyphs; delete[] m_Colours; nWidth = 0; nHeight = 0; FILE* f = nullptr; _wfopen_s(&f, sFile.c_str(), L"rb"); if (f == nullptr) return false; std::fread(&nWidth, sizeof(int), 1, f); std::fread(&nHeight, sizeof(int), 1, f); Create(nWidth, nHeight); std::fread(m_Colours, sizeof(short), nWidth * nHeight, f); std::fread(m_Glyphs, sizeof(short), nWidth * nHeight, f); std::fclose(f); return true; } }; class olcConsoleGameEngine { public: olcConsoleGameEngine() { screenWidth = 80; screenHeight = 30; Time = new TimeConstruct(); m_hConsole = GetStdHandle(STD_OUTPUT_HANDLE); m_hConsoleIn = GetStdHandle(STD_INPUT_HANDLE); std::memset(m_keyNewState, 0, 256 * sizeof(short)); std::memset(m_keyOldState, 0, 256 * sizeof(short)); std::memset(m_keys, 0, 256 * sizeof(sKeyState)); mousePosX = 0; mousePosY = 0; m_bEnableSound = false; SetAppInfo(L"Default", L"ConsoleGameEngine - "); } void SetAppInfo(std::wstring name, std::wstring info = L"") { m_appName = name; m_appInfo = info; } void EnableSound() { m_bEnableSound = true; } int ConstructConsole(int width, int height, int fontw, int fonth) { if (m_hConsole == INVALID_HANDLE_VALUE) return Error(L"Bad Handle"); screenWidth = width; screenHeight = height; bufferSize = screenWidth * screenHeight; // Update 13/09/2017 - It seems that the console behaves differently on some systems // and I'm unsure why this is. It could be to do with windows default settings, or // screen resolutions, or system languages. Unfortunately, MSDN does not offer much // by way of useful information, and so the resulting sequence is the reult of experiment // that seems to work in multiple cases. // // The problem seems to be that the SetConsoleXXX functions are somewhat circular and // fail depending on the state of the current console properties, i.e. you can't set // the buffer size until you set the screen size, but you can't change the screen size // until the buffer size is correct. This coupled with a precise ordering of calls // makes this procedure seem a little mystical :-P. Thanks to wowLinh for helping - Jx9 // Change console visual size to a minimum so ScreenBuffer can shrink // below the actual visual size m_rectWindow = { 0, 0, 1, 1 }; SetConsoleWindowInfo(m_hConsole, TRUE, &m_rectWindow); // Set the size of the screen buffer COORD coord = { (short)screenWidth, (short)screenHeight }; if (!SetConsoleScreenBufferSize(m_hConsole, coord)) Error(L"SetConsoleScreenBufferSize"); // Assign screen buffer to the console if (!SetConsoleActiveScreenBuffer(m_hConsole)) return Error(L"SetConsoleActiveScreenBuffer"); // Set the font size now that the screen buffer has been assigned to the console CONSOLE_FONT_INFOEX cfi; cfi.cbSize = sizeof(cfi); cfi.nFont = 0; cfi.dwFontSize.X = fontw; cfi.dwFontSize.Y = fonth; cfi.FontFamily = FF_DONTCARE; cfi.FontWeight = FW_NORMAL; /* DWORD version = GetVersion(); DWORD major = (DWORD)(LOBYTE(LOWORD(version))); DWORD minor = (DWORD)(HIBYTE(LOWORD(version)));*/ //if ((major > 6) || ((major == 6) && (minor >= 2) && (minor < 4))) // wcscpy_s(cfi.FaceName, L"Raster"); // Windows 8 :( //else // wcscpy_s(cfi.FaceName, L"Lucida Console"); // Everything else :P //wcscpy_s(cfi.FaceName, L"Liberation Mono"); wcscpy_s(cfi.FaceName, L"Consolas"); if (!SetCurrentConsoleFontEx(m_hConsole, false, &cfi)) return Error(L"SetCurrentConsoleFontEx"); // Get screen buffer info and check the maximum allowed window size. Return // error if exceeded, so user knows their dimensions/fontsize are too large CONSOLE_SCREEN_BUFFER_INFO csbi; if (!GetConsoleScreenBufferInfo(m_hConsole, &csbi)) return Error(L"GetConsoleScreenBufferInfo"); if (screenHeight > csbi.dwMaximumWindowSize.Y) return Error(L"Screen Height / Font Height Too Big"); if (screenWidth > csbi.dwMaximumWindowSize.X) return Error(L"Screen Width / Font Width Too Big"); // Set Physical Console Window Size m_rectWindow = { 0, 0, (short)screenWidth - 1, (short)screenHeight - 1 }; if (!SetConsoleWindowInfo(m_hConsole, TRUE, &m_rectWindow)) return Error(L"SetConsoleWindowInfo"); // Set flags to allow mouse input if (!SetConsoleMode(m_hConsoleIn, ENABLE_EXTENDED_FLAGS | ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT)) return Error(L"SetConsoleMode"); // Allocate memory for screen buffer m_bufScreen = new CHAR_INFO[screenWidth * screenHeight]; memset(m_bufScreen, 0, sizeof(CHAR_INFO) * screenWidth * screenHeight); SetConsoleCtrlHandler((PHANDLER_ROUTINE)CloseHandler, TRUE); return 1; } virtual void Draw(int x, int y, short c = 0x2588, short col = 0x000F) { if (x >= 0 && x < screenWidth && y >= 0 && y < screenHeight) { int index = y * screenWidth + x; m_bufScreen[index].Char.UnicodeChar = c; m_bufScreen[index].Attributes = col; } } void Fill(int x1, int y1, int x2, int y2, short c = 0x2588, short col = 0x000F) { Clip(x1, y1); Clip(x2, y2); for (int x = x1; x < x2; x++) for (int y = y1; y < y2; y++) Draw(x, y, c, col); } void DrawStringToBuffer(int x, int y, std::wstring c, short col = 0x000F) { for (size_t i = 0; i < c.size(); i++) { m_bufScreen[y * screenWidth + x + i].Char.UnicodeChar = c[i]; m_bufScreen[y * screenWidth + x + i].Attributes = col; } } void DrawStringAlpha(int x, int y, std::wstring c, short col = 0x000F) { for (size_t i = 0; i < c.size(); i++) { if (c[i] != L' ') { m_bufScreen[y * screenWidth + x + i].Char.UnicodeChar = c[i]; m_bufScreen[y * screenWidth + x + i].Attributes = col; } } } void DrawString(int32_t x, int32_t y, const std::string& sText, uint32_t scale = 1, short col = 0x000f) { int32_t sx = 0; int32_t sy = 0; for (auto c : sText) { if (c == '\n') { sx = 0; sy += 8 * scale; } else { int32_t ox = (c - 32) % 16; int32_t oy = (c - 32) / 16; if (scale > 1) { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetColour(i + ox * 8, j + oy * 8) > 0) for (uint32_t is = 0; is < scale; is++) for (uint32_t js = 0; js < scale; js++) Draw(x + sx + (i * scale) + is, y + sy + (j * scale) + js, col); } else { for (uint32_t i = 0; i < 8; i++) for (uint32_t j = 0; j < 8; j++) if (fontSprite->GetColour(i + ox * 8, j + oy * 8) > 0) Draw(x + sx + i, y + sy + j, col); } sx += 8 * scale; } } } void ConstructFontSheet() { std::string data; data += "?Q`0001oOch0o01o@F40o0<AGD4090LAGD<090@A7ch0?00O7Q`0600>00000000"; data += "O000000nOT0063Qo4d8>?7a14Gno94AA4gno94AaOT0>o3`oO400o7QN00000400"; data += "Of80001oOg<7O7moBGT7O7lABET024@aBEd714AiOdl717a_=TH013Q>00000000"; data += "720D000V?V5oB3Q_HdUoE7a9@DdDE4A9@DmoE4A;Hg]oM4Aj8S4D84@`00000000"; data += "OaPT1000Oa`^13P1@AI[?g`1@A=[OdAoHgljA4Ao?WlBA7l1710007l100000000"; data += "ObM6000oOfMV?3QoBDD`O7a0BDDH@5A0BDD<@5A0BGeVO5ao@CQR?5Po00000000"; data += "Oc``000?Ogij70PO2D]??0Ph2DUM@7i`2DTg@7lh2GUj?0TO0C1870T?00000000"; data += "70<4001o?P<7?1QoHg43O;`h@GT0@:@LB@d0>:@hN@L0@?aoN@<0O7ao0000?000"; data += "OcH0001SOglLA7mg24TnK7ln24US>0PL24U140PnOgl0>7QgOcH0K71S0000A000"; data += "00H00000@Dm1S007@DUSg00?OdTnH7YhOfTL<7Yh@Cl0700?@Ah0300700000000"; data += "<008001QL00ZA41a@6HnI<1i@FHLM81M@@0LG81?O`0nC?Y7?`0ZA7Y300080000"; data += "O`082000Oh0827mo6>Hn?Wmo?6HnMb11MP08@C11H`08@FP0@@0004@000000000"; data += "00P00001Oab00003OcKP0006@6=PMgl<@440MglH@000000`@000001P00000000"; data += "Ob@8@@00Ob@8@Ga13R@8Mga172@8?PAo3R@827QoOb@820@0O`0007`0000007P0"; data += "O`000P08Od400g`<3V=P0G`673IP0`@3>1`00P@6O`P00g`<O`000GP800000000"; data += "?P9PL020O`<`N3R0@E4HC7b0@ET<ATB0@@l6C4B0O`H3N7b0?P01L3R000000020"; fontSprite = new olcSprite(128, 48); int px = 0, py = 0; for (size_t b = 0; b < 1024; b += 4) { uint32_t sym1 = (uint32_t)data[b + 0] - 48; uint32_t sym2 = (uint32_t)data[b + 1] - 48; uint32_t sym3 = (uint32_t)data[b + 2] - 48; uint32_t sym4 = (uint32_t)data[b + 3] - 48; uint32_t r = sym1 << 18 | sym2 << 12 | sym3 << 6 | sym4; for (int i = 0; i < 24; i++) { int k = r & (1 << i) ? 255 : 0; // Figure this out fontSprite->SetColour(px, py, k); if (++py == 48) { px++; py = 0; } } } } void Clip(int& x, int& y) { if (x < 0) x = 0; if (x >= screenWidth) x = screenWidth; if (y < 0) y = 0; if (y >= screenHeight) y = screenHeight; } void IncrementPixel(int x, int y) { long index = y * screenWidth + x; switch (m_bufScreen[index].Char.UnicodeChar) { case PIXEL_SOLID: break; case PIXEL_THREEQUARTERS: SetPixel(x, y, 0); break; case PIXEL_HALF: SetPixel(x, y, 1); break; case PIXEL_QUARTER: SetPixel(x, y, 2); break; default: SetPixel(x, y, 3); break; } } void SetPixel(int x, int y, int fillType) { if (x >= screenWidth || x < 0 || y > screenHeight || y < 0) return; long index = y * screenWidth + x; m_bufScreen[index].Attributes = FG_WHITE; switch (fillType) { case 0: m_bufScreen[index].Char.UnicodeChar = PIXEL_SOLID; break; case 1: m_bufScreen[index].Char.UnicodeChar = PIXEL_THREEQUARTERS; break; case 2: m_bufScreen[index].Char.UnicodeChar = PIXEL_HALF; break; case 3: m_bufScreen[index].Char.UnicodeChar = PIXEL_QUARTER; break; default: m_bufScreen[index].Attributes = FG_BLACK; m_bufScreen[index].Char.UnicodeChar = PIXEL_SOLID; break; } } void SetPixel(int x, int y, bool colored, int fillType) { if (x >= screenWidth || x < 0 || y > screenHeight || y < 0) return; long index = y * screenWidth + x; if (colored == false) { m_bufScreen[index].Attributes = FG_BLACK; } else { switch (fillType) { case 0: m_bufScreen[index].Char.UnicodeChar = PIXEL_SOLID; break; case 1: m_bufScreen[index].Char.UnicodeChar = PIXEL_THREEQUARTERS; break; case 2: m_bufScreen[index].Char.UnicodeChar = PIXEL_HALF; break; case 3: m_bufScreen[index].Char.UnicodeChar = PIXEL_QUARTER; break; default: m_bufScreen[index].Char.UnicodeChar = PIXEL_SOLID; break; } m_bufScreen[index].Attributes = FG_WHITE; } } void DrawLine(int x1, int y1, int x2, int y2, short c = 0x2588, short col = 0x000F) { int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; dx1 = abs(dx); dy1 = abs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 <= dx1) { if (dx >= 0) { x = x1; y = y1; xe = x2; } else { x = x2; y = y2; xe = x1; } Draw(x, y, c, col); for (i = 0; x < xe; i++) { x = x + 1; if (px < 0) px = px + 2 * dy1; else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) y = y + 1; else y = y - 1; px = px + 2 * (dy1 - dx1); } Draw(x, y, c, col); } } else { if (dy >= 0) { x = x1; y = y1; ye = y2; } else { x = x2; y = y2; ye = y1; } Draw(x, y, c, col); for (i = 0; y < ye; i++) { y = y + 1; if (py <= 0) py = py + 2 * dx1; else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) x = x + 1; else x = x - 1; py = py + 2 * (dx1 - dy1); } Draw(x, y, c, col); } } } void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, short c = 0x2588, short col = 0x000F) { DrawLine(x1, y1, x2, y2, c, col); DrawLine(x2, y2, x3, y3, c, col); DrawLine(x3, y3, x1, y1, c, col); } // https://www.avrfreaks.net/sites/default/files/triangles.c void FillTriangle(int x1, int y1, int x2, int y2, int x3, int y3, short c = 0x2588, short col = 0x000F) { auto SWAP = [](int& x, int& y) { int t = x; x = y; y = t; }; auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, c, col); }; int t1x, t2x, y, minx, maxx, t1xp, t2xp; bool changed1 = false; bool changed2 = false; int signx1, signx2, dx1, dy1, dx2, dy2; int e1, e2; // Sort vertices if (y1 > y2) { SWAP(y1, y2); SWAP(x1, x2); } if (y1 > y3) { SWAP(y1, y3); SWAP(x1, x3); } if (y2 > y3) { SWAP(y2, y3); SWAP(x2, x3); } t1x = t2x = x1; y = y1; // Starting points dx1 = (int)(x2 - x1); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y2 - y1); dx2 = (int)(x3 - x1); if (dx2 < 0) { dx2 = -dx2; signx2 = -1; } else signx2 = 1; dy2 = (int)(y3 - y1); if (dy1 > dx1) { // swap values SWAP(dx1, dy1); changed1 = true; } if (dy2 > dx2) { // swap values SWAP(dy2, dx2); changed2 = true; } e2 = (int)(dx2 >> 1); // Flat top, just process the second half if (y1 == y2) goto next; e1 = (int)(dx1 >> 1); for (int i = 0; i < dx1;) { t1xp = 0; t2xp = 0; if (t1x < t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i < dx1) { i++; e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) t1xp = signx1;//t1x += signx1; else goto next1; } if (changed1) break; else t1x += signx1; } // Move line next1: // process second line until y value is about to change while (1) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2;//t2x += signx2; else goto next2; } if (changed2) break; else t2x += signx2; } next2: if (minx > t1x) minx = t1x; if (minx > t2x) minx = t2x; if (maxx < t1x) maxx = t1x; if (maxx < t2x) maxx = t2x; drawline(minx, maxx, y); // Draw line from min to max points found on the y // Now increase y if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y == y2) break; } next: // Second half dx1 = (int)(x3 - x2); if (dx1 < 0) { dx1 = -dx1; signx1 = -1; } else signx1 = 1; dy1 = (int)(y3 - y2); t1x = x2; if (dy1 > dx1) { // swap values SWAP(dy1, dx1); changed1 = true; } else changed1 = false; e1 = (int)(dx1 >> 1); for (int i = 0; i <= dx1; i++) { t1xp = 0; t2xp = 0; if (t1x < t2x) { minx = t1x; maxx = t2x; } else { minx = t2x; maxx = t1x; } // process first line until y value is about to change while (i < dx1) { e1 += dy1; while (e1 >= dx1) { e1 -= dx1; if (changed1) { t1xp = signx1; break; }//t1x += signx1; else goto next3; } if (changed1) break; else t1x += signx1; if (i < dx1) i++; } next3: // process second line until y value is about to change while (t2x != x3) { e2 += dy2; while (e2 >= dx2) { e2 -= dx2; if (changed2) t2xp = signx2; else goto next4; } if (changed2) break; else t2x += signx2; } next4: if (minx > t1x) minx = t1x; if (minx > t2x) minx = t2x; if (maxx < t1x) maxx = t1x; if (maxx < t2x) maxx = t2x; drawline(minx, maxx, y); if (!changed1) t1x += signx1; t1x += t1xp; if (!changed2) t2x += signx2; t2x += t2xp; y += 1; if (y > y3) return; } } void DrawCircle(int xc, int yc, int r, short c = 0x2588, short col = 0x000F) { int x = 0; int y = r; int p = 3 - 2 * r; if (!r) return; while (y >= x) // only formulate 1/8 of circle { Draw(xc - x, yc - y, c, col);//upper left left Draw(xc - y, yc - x, c, col);//upper upper left Draw(xc + y, yc - x, c, col);//upper upper right Draw(xc + x, yc - y, c, col);//upper right right Draw(xc - x, yc + y, c, col);//lower left left Draw(xc - y, yc + x, c, col);//lower lower left Draw(xc + y, yc + x, c, col);//lower lower right Draw(xc + x, yc + y, c, col);//lower right right if (p < 0) p += 4 * x++ + 6; else p += 4 * (x++ - y--) + 10; } } void FillCircle(int xc, int yc, int r, short c = 0x2588, short col = 0x000F) { // Taken from wikipedia int x = 0; int y = r; int p = 3 - 2 * r; if (!r) return; auto drawline = [&](int sx, int ex, int ny) { for (int i = sx; i <= ex; i++) Draw(i, ny, c, col); }; while (y >= x) { // Modified to draw scan-lines instead of edges drawline(xc - x, xc + x, yc - y); drawline(xc - y, xc + y, yc - x); drawline(xc - x, xc + x, yc + y); drawline(xc - y, xc + y, yc + x); if (p < 0) p += 4 * x++ + 6; else p += 4 * (x++ - y--) + 10; } }; void DrawSprite(int x, int y, olcSprite* sprite) { if (sprite == nullptr) return; for (int i = 0; i < sprite->nWidth; i++) { for (int j = 0; j < sprite->nHeight; j++) { if (sprite->GetGlyph(i, j) != L' ') Draw(x + i, y + j, sprite->GetGlyph(i, j), sprite->GetColour(i, j)); } } } void DrawPartialSprite(int x, int y, olcSprite* sprite, int ox, int oy, int w, int h) { if (sprite == nullptr) return; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (sprite->GetGlyph(i + ox, j + oy) != L' ') { Draw(x + i, y + j, sprite->GetGlyph(i + ox, j + oy), sprite->GetColour(i + ox, j + oy)); } } } } void DrawSprite(int x, int y, Sprite* sprite) { if (sprite == nullptr) return; for (int i = 0; i < sprite->GetWidth(); i++) { for (int j = 0; j < sprite->GetHeight(); j++) { if (sprite->GetGlyph(i, j) != L' ') Draw(x + i, y + j, sprite->GetGlyph(i, j), sprite->GetColor(i, j)); } } for (size_t w = 0; w < sprite->GetWidth(); w++) { for (size_t h = 0; h < sprite->GetHeight(); h++) { short color = sprite->GetColor(w, h); if (color != FG_BLACK) { short glyph = sprite->GetGlyph(w, h); SetPixel(x + w, y + h, GetPixelFromChar(glyph)); } } } } void DrawWireFrameModel(const std::vector<std::pair<float, float>>& vecModelCoordinates, float x, float y, float r = 0.0f, float s = 1.0f, short col = FG_WHITE, short c = PIXEL_SOLID) { // pair.first = x coordinate // pair.second = y coordinate // Create translated model vector of coordinate pairs std::vector<std::pair<float, float>> vecTransformedCoordinates; int verts = vecModelCoordinates.size(); vecTransformedCoordinates.resize(verts); // Rotate for (int i = 0; i < verts; i++) { vecTransformedCoordinates[i].first = vecModelCoordinates[i].first * cosf(r) - vecModelCoordinates[i].second * sinf(r); vecTransformedCoordinates[i].second = vecModelCoordinates[i].first * sinf(r) + vecModelCoordinates[i].second * cosf(r); } // Scale for (int i = 0; i < verts; i++) { vecTransformedCoordinates[i].first = vecTransformedCoordinates[i].first * s; vecTransformedCoordinates[i].second = vecTransformedCoordinates[i].second * s; } // Translate for (int i = 0; i < verts; i++) { vecTransformedCoordinates[i].first = vecTransformedCoordinates[i].first + x; vecTransformedCoordinates[i].second = vecTransformedCoordinates[i].second + y; } // Draw Closed Polygon for (int i = 0; i < verts + 1; i++) { int j = (i + 1); DrawLine((int)vecTransformedCoordinates[i % verts].first, (int)vecTransformedCoordinates[i % verts].second, (int)vecTransformedCoordinates[j % verts].first, (int)vecTransformedCoordinates[j % verts].second, c, col); } } void ClearScreen() { for (int i = 0; i < bufferSize; i++) { m_bufScreen[i].Attributes = FG_BLACK; m_bufScreen[i].Char.UnicodeChar = 0; } } void FadeScreen() { for (int i = 0; i < bufferSize; i++) { switch (m_bufScreen[i].Char.UnicodeChar) { case PIXEL_SOLID: m_bufScreen[i].Attributes = FG_WHITE; m_bufScreen[i].Char.UnicodeChar = PIXEL_THREEQUARTERS; break; case PIXEL_THREEQUARTERS: m_bufScreen[i].Attributes = FG_WHITE; m_bufScreen[i].Char.UnicodeChar = PIXEL_HALF; break; case PIXEL_HALF: m_bufScreen[i].Attributes = FG_WHITE; m_bufScreen[i].Char.UnicodeChar = PIXEL_QUARTER; break; default: m_bufScreen[i].Attributes = FG_BLACK; m_bufScreen[i].Char.UnicodeChar = 0; break; } } } ~olcConsoleGameEngine() { SetConsoleActiveScreenBuffer(m_hOriginalConsole); delete[] m_bufScreen; } public: void Start() { // Start the thread m_bAtomActive = true; std::thread t = std::thread(&olcConsoleGameEngine::GameThread, this); ConstructFontSheet(); // Wait for thread to be exited t.join(); } private: void GameThread() { // Create user resources as part of this thread if (!OnUserCreate()) m_bAtomActive = false; // Check if sound system should be enabled if (m_bEnableSound) { if (!CreateAudio()) { m_bAtomActive = false; // Failed to create audio system m_bEnableSound = false; } } auto tp1 = std::chrono::system_clock::now(); auto tp2 = std::chrono::system_clock::now(); while (m_bAtomActive) { // Run as fast as possible while (m_bAtomActive) { // Handle Timing tp2 = std::chrono::system_clock::now(); std::chrono::duration<float> elapsedTime = tp2 - tp1; tp1 = tp2; float fElapsedTime = elapsedTime.count(); // Handle Keyboard Input for (int i = 0; i < 256; i++) { m_keyNewState[i] = GetAsyncKeyState(i); m_keys[i].bPressed = false; m_keys[i].bReleased = false; if (m_keyNewState[i] != m_keyOldState[i]) { if (m_keyNewState[i] & 0x8000) { m_keys[i].bPressed = !m_keys[i].bHeld; m_keys[i].bHeld = true; } else { m_keys[i].bReleased = true; m_keys[i].bHeld = false; } } m_keyOldState[i] = m_keyNewState[i]; } // Handle Mouse Input - Check for window events INPUT_RECORD inBuf[32]; DWORD events = 0; GetNumberOfConsoleInputEvents(m_hConsoleIn, &events); if (events > 0) ReadConsoleInput(m_hConsoleIn, inBuf, events, &events); // Handle events - we only care about mouse clicks and movement // for now for (DWORD i = 0; i < events; i++) { switch (inBuf[i].EventType) { case FOCUS_EVENT: { m_bConsoleInFocus = inBuf[i].Event.FocusEvent.bSetFocus; } break; case MOUSE_EVENT: { switch (inBuf[i].Event.MouseEvent.dwEventFlags) { case MOUSE_MOVED: { mousePosX = inBuf[i].Event.MouseEvent.dwMousePosition.X; mousePosY = inBuf[i].Event.MouseEvent.dwMousePosition.Y; } break; case 0: { for (int m = 0; m < 5; m++) m_mouseNewState[m] = (inBuf[i].Event.MouseEvent.dwButtonState & (1 << m)) > 0; } break; default: break; } } break; default: break; // We don't care just at the moment } } for (int m = 0; m < 5; m++) { m_mouse[m].bPressed = false; m_mouse[m].bReleased = false; if (m_mouseNewState[m] != m_mouseOldState[m]) { if (m_mouseNewState[m]) { m_mouse[m].bPressed = true; m_mouse[m].bHeld = true; } else { m_mouse[m].bReleased = true; m_mouse[m].bHeld = false; } } m_mouseOldState[m] = m_mouseNewState[m]; } // Handle Frame Update /// <summary> /// /// </summary> if (frameCount % (256 - fadeSpeed) == 0) FadeScreen(); Time->UpdateTime(fElapsedTime); if (!OnUserUpdate()) m_bAtomActive = false; frameCount++; if (frameCount >= SHRT_MAX - 100) frameCount = 0; // Update Title & Present Screen Buffer wchar_t s[256]; swprintf_s(s, 256, L"%s%s - FPS: %3.2f", m_appInfo.c_str(), m_appName.c_str(), 1.0f / fElapsedTime); SetConsoleTitle(s); WriteConsoleOutput(m_hConsole, m_bufScreen, { (short)screenWidth, (short)screenHeight }, { 0,0 }, &m_rectWindow); } if (m_bEnableSound) { // Close and Clean up audio system } // Allow the user to free resources if they have overrided the destroy function if (OnUserDestroy()) { // User has permitted destroy, so exit and clean up delete[] m_bufScreen; SetConsoleActiveScreenBuffer(m_hOriginalConsole); m_cvGameFinished.notify_one(); } else { // User denied destroy for some reason, so continue running m_bAtomActive = true; } } } public: // User MUST OVERRIDE THESE!! virtual bool OnUserCreate() = 0; virtual bool OnUserUpdate() = 0; // Optional for clean up virtual bool OnUserDestroy() { return true; } protected: // Audio Engine ===================================================================== class olcAudioSample { public: olcAudioSample() { } olcAudioSample(std::wstring sWavFile) { // Load Wav file and convert to float format FILE* f = nullptr; _wfopen_s(&f, sWavFile.c_str(), L"rb"); if (f == nullptr) return; char dump[4]; std::fread(&dump, sizeof(char), 4, f); // Read "RIFF" if (strncmp(dump, "RIFF", 4) != 0) return; std::fread(&dump, sizeof(char), 4, f); // Not Interested std::fread(&dump, sizeof(char), 4, f); // Read "WAVE" if (strncmp(dump, "WAVE", 4) != 0) return; // Read Wave description chunk std::fread(&dump, sizeof(char), 4, f); // Read "fmt " std::fread(&dump, sizeof(char), 4, f); // Not Interested std::fread(&wavHeader, sizeof(WAVEFORMATEX) - 2, 1, f); // Read Wave Format Structure chunk // Note the -2, because the structure has 2 bytes to indicate its own size // which are not in the wav file // Just check if wave format is compatible with olcCGE if (wavHeader.wBitsPerSample != 16 || wavHeader.nSamplesPerSec != 44100) { std::fclose(f); return; } // Search for audio data chunk long nChunksize = 0; std::fread(&dump, sizeof(char), 4, f); // Read chunk header std::fread(&nChunksize, sizeof(long), 1, f); // Read chunk size while (strncmp(dump, "data", 4) != 0) { // Not audio data, so just skip it std::fseek(f, nChunksize, SEEK_CUR); std::fread(&dump, sizeof(char), 4, f); std::fread(&nChunksize, sizeof(long), 1, f); } // Finally got to data, so read it all in and convert to float samples nSamples = nChunksize / (wavHeader.nChannels * (wavHeader.wBitsPerSample >> 3)); nChannels = wavHeader.nChannels; // Create floating point buffer to hold audio sample fSample = new float[nSamples * nChannels]; float* pSample = fSample; // Read in audio data and normalise for (long i = 0; i < nSamples; i++) { for (int c = 0; c < nChannels; c++) { short s = 0; std::fread(&s, sizeof(short), 1, f); *pSample = (float)s / (float)(MAXSHORT); pSample++; } } // All done, flag sound as valid std::fclose(f); bSampleValid = true; } WAVEFORMATEX wavHeader; float* fSample = nullptr; long nSamples = 0; int nChannels = 0; bool bSampleValid = false; }; // This vector holds all loaded sound samples in memory std::vector<olcAudioSample> vecAudioSamples; struct BeepSample { public: float freq = 0; float dur = 0; bool finished = false; }; std::list<BeepSample> listActiveBeepSamples; // This structure represents a sound that is currently playing. It only // holds the sound ID and where this instance of it is up to for its // current playback struct sCurrentlyPlayingSample { int nAudioSampleID = 0; long nSamplePosition = 0; bool bFinished = false; bool bLoop = false; }; std::list<sCurrentlyPlayingSample> listActiveSamples; // Load a 16-bit WAVE file @ 44100Hz ONLY into memory. A sample ID // number is returned if successful, otherwise -1 unsigned int LoadAudioSample(std::wstring sWavFile) { if (!m_bEnableSound) return -1; olcAudioSample a(sWavFile); if (a.bSampleValid) { vecAudioSamples.push_back(a); return vecAudioSamples.size(); } else return -1; } void PlayBeep(float freq, float duration) { BeepSample a; a.freq = freq; a.dur = duration; listActiveBeepSamples.push_back(a); } // Add sample 'id' to the mixers sounds to play list void PlaySample(int id, bool bLoop = false) { sCurrentlyPlayingSample a; a.nAudioSampleID = id; a.nSamplePosition = 0; a.bFinished = false; a.bLoop = bLoop; listActiveSamples.push_back(a); } void StopSample(int id) { } // The audio system uses by default a specific wave format bool CreateAudio(unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512) { // Initialise Sound Engine m_bAudioThreadActive = false; m_nSampleRate = nSampleRate; m_nChannels = nChannels; m_nBlockCount = nBlocks; m_nBlockSamples = nBlockSamples; m_nBlockFree = m_nBlockCount; m_nBlockCurrent = 0; m_pBlockMemory = nullptr; m_pWaveHeaders = nullptr; // Device is available WAVEFORMATEX waveFormat; waveFormat.wFormatTag = WAVE_FORMAT_PCM; waveFormat.nSamplesPerSec = m_nSampleRate; waveFormat.wBitsPerSample = sizeof(short) * 8; waveFormat.nChannels = m_nChannels; waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels; waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; waveFormat.cbSize = 0; // Open Device if valid if (waveOutOpen(&m_hwDevice, WAVE_MAPPER, &waveFormat, (DWORD_PTR)waveOutProcWrap, (DWORD_PTR)this, CALLBACK_FUNCTION) != S_OK) return DestroyAudio(); // Allocate Wave|Block Memory m_pBlockMemory = new short[m_nBlockCount * m_nBlockSamples]; if (m_pBlockMemory == nullptr) return DestroyAudio(); ZeroMemory(m_pBlockMemory, sizeof(short) * m_nBlockCount * m_nBlockSamples); m_pWaveHeaders = new WAVEHDR[m_nBlockCount]; if (m_pWaveHeaders == nullptr) return DestroyAudio(); ZeroMemory(m_pWaveHeaders, sizeof(WAVEHDR) * m_nBlockCount); // Link headers to block memory for (unsigned int n = 0; n < m_nBlockCount; n++) { m_pWaveHeaders[n].dwBufferLength = m_nBlockSamples * sizeof(short); m_pWaveHeaders[n].lpData = (LPSTR)(m_pBlockMemory + (n * m_nBlockSamples)); } m_bAudioThreadActive = true; m_AudioThread = std::thread(&olcConsoleGameEngine::AudioThread, this); // Start the ball rolling with the sound delivery thread std::unique_lock<std::mutex> lm(m_muxBlockNotZero); m_cvBlockNotZero.notify_one(); return true; } // Stop and clean up audio system bool DestroyAudio() { m_bAudioThreadActive = false; return false; } // Handler for soundcard request for more data void waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2) { if (uMsg != WOM_DONE) return; m_nBlockFree++; std::unique_lock<std::mutex> lm(m_muxBlockNotZero); m_cvBlockNotZero.notify_one(); } // Static wrapper for sound card handler static void CALLBACK waveOutProcWrap(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2) { ((olcConsoleGameEngine*)dwInstance)->waveOutProc(hWaveOut, uMsg, dwParam1, dwParam2); } // Audio thread. This loop responds to requests from the soundcard to fill 'blocks' // with audio data. If no requests are available it goes dormant until the sound // card is ready for more data. The block is fille by the "user" in some manner // and then issued to the soundcard. void AudioThread() { m_fGlobalTime = 0.0f; float fTimeStep = 1.0f / (float)m_nSampleRate; // Goofy hack to get maximum integer for a type at run-time short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1; float fMaxSample = (float)nMaxSample; short nPreviousSample = 0; while (m_bAudioThreadActive) { // Wait for block to become available if (m_nBlockFree == 0) { std::unique_lock<std::mutex> lm(m_muxBlockNotZero); while (m_nBlockFree == 0) // sometimes, Windows signals incorrectly m_cvBlockNotZero.wait(lm); } // Block is here, so use it m_nBlockFree--; // Prepare block for processing if (m_pWaveHeaders[m_nBlockCurrent].dwFlags & WHDR_PREPARED) waveOutUnprepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR)); short nNewSample = 0; int nCurrentBlock = m_nBlockCurrent * m_nBlockSamples; auto clip = [](float fSample, float fMax) { if (fSample >= 0.0) return fmin(fSample, fMax); else return fmax(fSample, -fMax); }; for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels) { // User Process for (unsigned int c = 0; c < m_nChannels; c++) { nNewSample = (short)(clip(GetMixerOutput(c, m_fGlobalTime, fTimeStep), 1.0) * fMaxSample); m_pBlockMemory[nCurrentBlock + n + c] = nNewSample; nPreviousSample = nNewSample; } m_fGlobalTime = m_fGlobalTime + fTimeStep; } // Send block to sound device waveOutPrepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR)); waveOutWrite(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR)); m_nBlockCurrent++; m_nBlockCurrent %= m_nBlockCount; } } // Overridden by user if they want to generate sound in real-time virtual float onUserSoundSample(int nChannel, float fGlobalTime, float fTimeStep) { return 0.0f; } // Overriden by user if they want to manipulate the sound before it is played virtual float onUserSoundFilter(int nChannel, float fGlobalTime, float fSample) { return fSample; } // The Sound Mixer - If the user wants to play many sounds simultaneously, and // perhaps the same sound overlapping itself, then you need a mixer, which // takes input from all sound sources for that audio frame. This mixer maintains // a list of sound locations for all concurrently playing audio samples. Instead // of duplicating audio data, we simply store the fact that a sound sample is in // use and an offset into its sample data. As time progresses we update this offset // until it is beyound the length of the sound sample it is attached to. At this // point we remove the playing souind from the list. // // Additionally, the users application may want to generate sound instead of just // playing audio clips (think a synthesizer for example) in whcih case we also // provide an "onUser..." event to allow the user to return a sound for that point // in time. // // Finally, before the sound is issued to the operating system for performing, the // user gets one final chance to "filter" the sound, perhaps changing the volume // or adding funky effects float GetMixerOutput(int nChannel, float fGlobalTime, float fTimeStep) { // Accumulate sample for this channel float fMixerSample = 0.0f; for (auto& s : listActiveBeepSamples) { Beep(s.freq, s.dur); s.finished = true; } //listActiveBeepSamples.clear(); listActiveBeepSamples.remove_if([](const BeepSample& s) {return s.finished; }); for (auto& s : listActiveSamples) { // Calculate sample position s.nSamplePosition += (long)((float)vecAudioSamples[s.nAudioSampleID - 1].wavHeader.nSamplesPerSec * fTimeStep); // If sample position is valid add to the mix if (s.nSamplePosition < vecAudioSamples[s.nAudioSampleID - 1].nSamples) fMixerSample += vecAudioSamples[s.nAudioSampleID - 1].fSample[(s.nSamplePosition * vecAudioSamples[s.nAudioSampleID - 1].nChannels) + nChannel]; else s.bFinished = true; // Else sound has completed } // If sounds have completed then remove them listActiveSamples.remove_if([](const sCurrentlyPlayingSample& s) {return s.bFinished; }); // The users application might be generating sound, so grab that if it exists fMixerSample += onUserSoundSample(nChannel, fGlobalTime, fTimeStep); // Return the sample via an optional user override to filter the sound return onUserSoundFilter(nChannel, fGlobalTime, fMixerSample); } unsigned int m_nSampleRate; unsigned int m_nChannels; unsigned int m_nBlockCount; unsigned int m_nBlockSamples; unsigned int m_nBlockCurrent; short* m_pBlockMemory = nullptr; WAVEHDR* m_pWaveHeaders = nullptr; HWAVEOUT m_hwDevice = nullptr; std::thread m_AudioThread; std::atomic<bool> m_bAudioThreadActive = false; std::atomic<unsigned int> m_nBlockFree = 0; std::condition_variable m_cvBlockNotZero; std::mutex m_muxBlockNotZero; std::atomic<float> m_fGlobalTime = 0.0f; protected: struct sKeyState { bool bPressed; bool bReleased; bool bHeld; } m_keys[256], m_mouse[5]; public: int mousePosX; int mousePosY; int screenWidth; int screenHeight; sKeyState GetKey(int nKeyID) { return m_keys[nKeyID]; } sKeyState GetMouse(int nMouseButtonID) { return m_mouse[nMouseButtonID]; } bool IsFocused() { return m_bConsoleInFocus; } protected: int Error(const wchar_t* msg) { wchar_t buf[256]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, 256, NULL); SetConsoleActiveScreenBuffer(m_hOriginalConsole); wprintf(L"ERROR: %s\n\t%s\n", msg, buf); return 0; } static BOOL CloseHandler(DWORD evt) { // Note this gets called in a seperate OS thread, so it must // only exit when the game has finished cleaning up, or else // the process will be killed before OnUserDestroy() has finished if (evt == CTRL_CLOSE_EVENT) { m_bAtomActive = false; // Wait for thread to be exited std::unique_lock<std::mutex> ul(m_muxGame); m_cvGameFinished.wait(ul); } return true; } public: olcSprite* fontSprite; byte fadeSpeed = 255; int bufferSize; short frameCount = 0; CHAR_INFO* m_bufScreen; std::wstring m_appName; std::wstring m_appInfo; HANDLE m_hOriginalConsole; CONSOLE_SCREEN_BUFFER_INFO m_OriginalConsoleInfo; HANDLE m_hConsole; HANDLE m_hConsoleIn; SMALL_RECT m_rectWindow; short m_keyOldState[256] = { 0 }; short m_keyNewState[256] = { 0 }; bool m_mouseOldState[5] = { 0 }; bool m_mouseNewState[5] = { 0 }; bool m_bConsoleInFocus = true; bool m_bEnableSound = false; // These need to be static because of the OnDestroy call the OS may make. The OS // spawns a special thread just for that static std::atomic<bool> m_bAtomActive; static std::condition_variable m_cvGameFinished; static std::mutex m_muxGame; }; // Define our static variables std::atomic<bool> olcConsoleGameEngine::m_bAtomActive(false); std::condition_variable olcConsoleGameEngine::m_cvGameFinished; std::mutex olcConsoleGameEngine::m_muxGame;
true
4b452f53510c9814e36ecc2c5ad2a4cf6f3d48be
C++
douglasbravimbraga/programming-contests
/UVa Online Judge/00410 - Station Balance/main.cpp
UTF-8
1,189
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int C, S; int set_num = 0; while (scanf("%d %d", &C, &S) == 2) { int mass[2 * C]; set_num++; for (int i = 0; i < S; i++) { scanf("%d", &mass[i]); } for (int i = S; i < 2 * C; i++) { mass[i] = 0; } sort(mass, mass + 2 * C); vector<int> centrifuge[C]; int sum[C]; double sum_of_all = 0; for (int i = 0; i < C; i++) { if (mass[i]) centrifuge[i].push_back(mass[i]); if (mass[2 * C - 1 - i]) centrifuge[i].push_back(mass[2 * C - 1 - i]); sum[i] = 0; sum[i] += mass[i]; sum[i] += mass[2 * C - 1 - i]; sum_of_all += sum[i]; } double avg = sum_of_all / (double) C; double diff = 0; printf("Set #%d\n", set_num); for (int i = 0; i < C; i++) { printf("%2d:", i); for (auto j : centrifuge[i]) printf(" %d", j); printf("\n"); diff += abs(avg - sum[i]); } printf("IMBALANCE = %.5f\n\n", diff); } }
true
2083bb41b4389550667fc35d7daaaf01b3bbc75b
C++
hilkojj/CG-windesheim-OpenGL
/Project1/source/loaders/texture_loader.cpp
UTF-8
1,673
2.65625
3
[]
no_license
#include "texture_loader.h" #define STB_IMAGE_IMPLEMENTATION #include "../external/stb_image.h" #include <stdexcept> #include <unordered_map> #include <iostream> SharedTexture texture_loader::load(const char* path) { std::cout << "Loading " << path << std::endl; int width, height, channels; unsigned char* imgData = stbi_load(path, &width, &height, &channels, 0); if (imgData == NULL) throw std::runtime_error("Could not load image using STB: " + std::string(path)); GLuint id; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // todo: shouldnt be hardcoded glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // todo: mipmapping stuff glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); if (channels == 3) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, imgData); else if (channels == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imgData); else throw std::runtime_error("Loaded an image with unsupported amount of channels (" + std::to_string(channels) + ")."); glGenerateMipmap(GL_TEXTURE_2D); stbi_image_free(imgData); return SharedTexture(new Texture(id)); } SharedTexture texture_loader::getOrLoad(const char* path) { static std::unordered_map<std::string, SharedTexture> sharedTextures; if (!sharedTextures[path]) sharedTextures[path] = load(path); return sharedTextures[path]; }
true
c582ed4eee0d04692853fc8566eb89d04e7a658c
C++
gcc-tan/leetcode
/43.cpp
UTF-8
2,241
4
4
[]
no_license
//Multiply Strings /* Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2. Note: The length of both num1 and num2 is < 110. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert the inputs to integer directly. */ /* 一个简单的大数乘法 ------------------------------------------------------------------------------------ 感觉写了不下一万次,但是动起手来还是不怎么会写 */ class Solution { public: string multiply(string num1, string num2) { int i, j, len1 = num1.size(), len2 = num2.size(), carry, tmp; string sum(len1 + len2, '0'); for(i = len1 - 1; i >= 0; --i) { carry = 0; for(j = len2 - 1; j >= 0; --j) { tmp = (num1[i] - '0') * (num2[j] - '0') + (sum[i+j+1] - '0') + carry;//将上位的进位,这次乘法的数,以及当前的和都加起来 carry = tmp / 10; sum[i+j+1] = tmp % 10 + '0'; } if(carry) sum[i+j+1] = carry + '0'; } for(i = 0; i < len1 + len2 - 1 && sum[i] == '0'; ++i); //去掉前导0,这里i不取等号为了防止结果是0,把所有的0都去掉了 string ans(len1 + len2 - i, '0'); for(j = 0; j < ans.size(); ++j, ++i) ans[j] = sum[i]; return ans; } }; //在看看别人写的c++代码,很简介明了 string multiply(string num1, string num2) { string sum(num1.size() + num2.size(), '0');//预先分配可能的空间 for (int i = num1.size() - 1; 0 <= i; --i) { int carry = 0; for (int j = num2.size() - 1; 0 <= j; --j) { int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; sum[i + j + 1] = tmp % 10 + '0'; carry = tmp / 10; } sum[i] += carry;//这个进位处理很厉害,不需要判断0就相当于没加,而且不需要i+j+1,j+1肯定是0 } size_t startpos = sum.find_first_not_of("0");//npos表示容器中不存在的位置,这里直接使用substr,没有像我一样又重复造车轮子 if (string::npos != startpos) { return sum.substr(startpos); } return "0"; }
true
a5ec2ca0232502eeb50051bf426285033e8a61c2
C++
vFones/rbhash-galacticgraph
/rbhash/include/nodes/genericnode.hpp
UTF-8
796
3.203125
3
[]
no_license
#ifndef _GENERICNODE_HPP_ #define _GENERICNODE_HPP_ #include <string> #include <iostream> #include <other/item.hpp> /** * @brief Generic Node class * @tparam N template base class */ template <typename D> class GenericNode : public Item<D> { public: GenericNode() : Item<D>() {}; GenericNode(double &k) : Item<D>(k) {}; GenericNode(double &k, D &d) : Item<D>(k, d){}; ~GenericNode() {}; std::string toString(){return "["+std::to_string((int)this->getKey())+"] : "+ std::string(this->getData())+"\n";} friend std::ostream& operator<<(std::ostream &Str, GenericNode<D> &c){ Str<<c.toString(); return Str; } friend std::ostream& operator<<(std::ostream &Str, GenericNode<D> *c){ Str<<c->toString(); return Str; } }; #endif //_GENERICNODE_HPP_
true
b404da2993f7d24f5b294f00dfd8fb851d9c0eea
C++
BPI-SINOVOIP/BPI-1296-Android6
/android/device/realtek/proprietary/libs/libRTKExtractor/RTKExtractor/Filters/NavigationFilter/InputHDMV/Common/Geometry/GeometryTemplates.h
UTF-8
31,196
2.828125
3
[]
no_license
//----------------------------------------------------------------------------- // GeometryTemplates.h // Copyright (c) 2000 - 2004, Sonic Solutions. All rights reserved. //----------------------------------------------------------------------------- #ifndef GEOMETRY_TEMPLATES #define GEOMETRY_TEMPLATES #include <cmath> #include <algorithm> // A workaround to avoid compile errors due to conflicts with std::min/std::max. #undef min #undef max #if defined(_WIN32) #pragma warning(disable:4068) // unknown pragma #endif namespace gt { template <class T> T minzero(const T& arg) { return (arg >= T(0) ? arg : T(0)); } #if defined(_WIN32) #pragma mark - #pragma mark Class Size #pragma mark - #endif //----------------------------------------------------------------------------- // class Size //----------------------------------------------------------------------------- template <class T, class Scale = double > class Size // **CodeWizzard** - Severe Violation: Universal Coding Standards item 28 - Do not overload functions within a template clas { public: typedef gt::Size<T, Scale> SizeType; typedef T CoordType; typedef Scale ScaleType; private: T x; T y; public: Size() : x(T(1)), y(T(1)) {} Size(const T& inX, const T& inY) : x(gt::minzero(inX)), y(gt::minzero(inY)) {} template <class U, class UScale> Size(const gt::Size<U, UScale>& arg) : x(static_cast<T>(arg.X())), y(static_cast<T>(arg.Y())) {} // **CodeWizzard** - Violation: More Effective C++ item 24 - Understand the costs of virtual functions ... virtual ~Size() {} SizeType& operator=(const SizeType& arg) { if (&arg == this) return *this; x = arg.x; y = arg.y; return *this; } const T& X() const { return x; } const T& Y() const { return y; } void SetX(const T& inX) { x = inX; } void SetY(const T& inY) { y = inY; } bool operator!() const { return (x == T(0)) || (y == T(0)); } bool IsZero() const { return(!x && !y); } // Binary operations with Size bool operator==(const SizeType& arg) const { if (arg.x != x) return false; if (arg.y != y) return false; return true; } bool operator!=(const SizeType& arg) const { return !(arg == *this); } const SizeType& operator*=(const SizeType& arg) { x *= arg.x; y *= arg.y; return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const SizeType operator*(const SizeType& arg) const { SizeType temp(*this); temp *= arg; return temp; } const SizeType& operator/=(const SizeType& arg) { x /= arg.x; y /= arg.y; return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const SizeType operator/(const SizeType& arg) const { SizeType temp(*this); temp /= arg; return temp; } // Binary operations with Scale const SizeType& operator*=(Scale factor) { factor = minzero(factor); // fixes GCC 4.0 error about double being assinged to SInt32. x = static_cast<T>(x * factor); y = static_cast<T>(y * factor); return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o SizeType operator*(Scale factor) const { SizeType temp(*this); temp *= factor; return temp; } const SizeType& operator/=(Scale factor) { factor = minzero(factor); x = static_cast<T>(x / factor); y = static_cast<T>(y / factor); return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o SizeType operator/(Scale factor) const { SizeType temp(*this); temp /= factor; return temp; } }; template <class T, class Scale> Size<T, Scale> operator*(Scale factor, const Size<T, Scale>& sz) { return sz*factor; } #if defined(_WIN32) #pragma mark - #pragma mark Class Point #pragma mark - #endif //----------------------------------------------------------------------------- // class Point //----------------------------------------------------------------------------- template <class T, class Scale = double > class Point // **CodeWizzard** - Severe Violation: Universal Coding Standards item 28 - Do not overload functions within a template clas { public: typedef gt::Size<T, Scale> SizeType; typedef gt::Point<T, Scale> PointType; typedef T CoordType; typedef Scale ScaleType; private: T x; T y; public: Point() : x(T(0)), y(T(0)) {} Point(const T& inX, const T& inY) : x(inX), y(inY) {} template <class U, class UScale> Point(const gt::Point<U, UScale>& arg) : x(static_cast<T>(arg.X())), y(static_cast<T>(arg.Y())) {} explicit Point(const SizeType& arg) : x(arg.X()), y(arg.Y()) {} // **CodeWizzard** - Violation: More Effective C++ item 24 - Understand the costs of virtual functions ... virtual ~Point() {} PointType& operator=(const PointType& arg) { if (&arg == this) return *this; x = arg.x; y = arg.y; return *this; } // Accessors const T& X() const { return x; } void SetX(const T& inX) { x = inX; } const T& Y() const { return y; } void SetY(const T& inY) { y = inY; } bool IsZero() const { return(!x && !y); } // Binary operations with points bool operator==(const PointType& arg) const { if (arg.x != x) return false; if (arg.y != y) return false; return true; } bool operator!=(const PointType& arg) const { return !(arg == *this); } const PointType& operator+=(const PointType& arg) { x = static_cast<T>(x+arg.x); y = static_cast<T>(y+arg.y); return *this; } const PointType& operator+=(const SizeType& arg) { x = static_cast<T>(x+arg.X()); y = static_cast<T>(y+arg.Y()); return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator+(const PointType& arg) const { PointType temp(*this); temp += arg; return temp; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator+(const SizeType& arg) const { PointType temp(*this); temp += arg; return temp; } const PointType& operator-=(const PointType& arg) { x = static_cast<T>(x-arg.x); y = static_cast<T>(y-arg.y); return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator-(const PointType& arg) const { PointType temp(*this); temp -= arg; return temp; } // Binary operations with Scale const PointType& operator*=(Scale factor) { x = static_cast<T>(x*factor); y = static_cast<T>(y*factor); return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator*(Scale factor) const { PointType temp(*this); temp *= factor; return temp; } const PointType& operator/=(Scale factor) { x = static_cast<T>(x/factor); y = static_cast<T>(y/factor); return *this; } // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator/(Scale factor) const { PointType temp(*this); temp /= factor; return temp; } // Binary operations with Size template <class U> const PointType& operator*=(const gt::Size<U>& arg) { x = static_cast<T>(x*arg.X()); y = static_cast<T>(y*arg.Y()); return *this; } template <class U> const PointType& operator/=(const gt::Size<U>& arg) { x = static_cast<T>(x/arg.X()); y = static_cast<T>(y/arg.Y()); return *this; } template <class U> // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator/(const gt::Size<U>& arg) const { PointType temp(*this); temp /= arg; return temp; } template <class U> // **CodeWizzard** - Violation: Effective C++ item 19 - Differentiate among member functions, global functions and friend function // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o const PointType operator*(const gt::Size<U>& arg) const { PointType temp(*this); temp *= arg; return temp; } }; template <class T, class Scale> gt::Point<T, Scale> operator*(Scale factor, const Point<T, Scale>& pt) { return pt*factor; } template <class T, class Scale, class U, class UScale> gt::Point<T, Scale> operator*(const Size<U, UScale>& sz, const gt::Point<T, Scale>& pt) { gt::Point<T, Scale> temp(pt); temp *= sz; return temp; } #if defined(_WIN32) #pragma mark - #pragma mark Class Rect #pragma mark - #endif template< class T, class Scale = double > class OriginTopLeft { public: typedef gt::Size<T, Scale> SizeType; typedef gt::Point<T, Scale> PointType; // typedef gt::Rect<T, Scale> RectType; typedef T CoordType; typedef Scale ScaleType; static bool IsLeftOf(T c1, T c2) { return c1 < c2; } static bool IsLeftOrEqual(T c1, T c2) { return c1 <= c2; } static T Leftmost(T c1, T c2) { return std::min(c1, c2); } static bool IsRightOf(T c1, T c2) { return c1 > c2; } static bool IsRightOrEqual(T c1, T c2) { return c1 >= c2; } static T Rightmost(T c1, T c2) { return std::max(c1, c2); } static bool IsAbove(T c1, T c2) { return c1 < c2; } static bool IsAboveOrEqual(T c1, T c2) { return c1 <= c2; } static T Topmost(T c1, T c2) { return std::min(c1, c2); } static bool IsBelow(T c1, T c2) { return c1 > c2; } static bool IsBelowOrEqual(T c1, T c2) { return c1 >= c2; } static T Bottommost(T c1, T c2) { return std::max(c1, c2); } static SizeType Size(const PointType& tl, const PointType& br) { return SizeType(br - tl); } }; template< class T, class Scale = double > class OriginBottomLeft { public: typedef gt::Size<T, Scale> SizeType; typedef gt::Point<T, Scale> PointType; // typedef gt::Rect<T, Scale> RectType; typedef T CoordType; typedef Scale ScaleType; static bool IsLeftOf(T c1, T c2) { return c1 < c2; } static bool IsLeftOrEqual(T c1, T c2) { return c1 <= c2; } static T Leftmost(T c1, T c2) { return std::min(c1, c2); } static bool IsRightOf(T c1, T c2) { return c1 > c2; } static bool IsRightOrEqual(T c1, T c2) { return c1 >= c2; } static T Rightmost(T c1, T c2) { return std::max(c1, c2); } static bool IsAbove(T c1, T c2) { return c1 > c2; } static bool IsAboveOrEqual(T c1, T c2) { return c1 >= c2; } static T Topmost(T c1, T c2) { return std::max(c1, c2); } static bool IsBelow(T c1, T c2) { return c1 < c2; } static bool IsBelowOrEqual(T c1, T c2) { return c1 <= c2; } static T Bottommost(T c1, T c2) { return std::min(c1, c2); } static SizeType Size(const PointType& tl, const PointType& br) { return SizeType(br.X() - tl.X(), tl.Y() - br.Y()); } }; //----------------------------------------------------------------------------- // class Rect //----------------------------------------------------------------------------- template < class T, class Scale = double, class coord = OriginTopLeft< T, Scale > > class Rect // **CodeWizzard** - Severe Violation: Universal Coding Standards item 28 - Do not overload functions within a template clas { public: typedef gt::Size<T, Scale> SizeType; typedef gt::Point<T, Scale> PointType; typedef gt::Rect<T, Scale> RectType; typedef T CoordType; typedef Scale ScaleType; private: Point<T, Scale> tl; gt::Size<T, Scale> wh; public: Rect() : wh(0, 0) {} template <class U, class UScale> Rect(const gt::Rect<U, UScale>& r) : tl(r.TL()), wh(static_cast<T>(r.Width()), static_cast<T>(r.Height())) {} Rect(const PointType& inTL, const PointType& inBR) : tl(inTL), wh(inBR.X() - inTL.X(), inBR.Y() - inTL.Y()) {} Rect(const PointType& inTL, const SizeType& inSize): tl(inTL), wh(inSize) {} Rect(const T& left, const T& top, const T& right, const T& bottom) : tl(left, top), wh(right - left, bottom - top) {} // **CodeWizzard** - Violation: More Effective C++ item 24 - Understand the costs of virtual functions ... virtual ~Rect() {} gt::Rect<T>& operator=(const gt::Rect<T>& arg) { if (&arg == this) return *this; tl = arg.tl; wh = arg.wh; return *this; } // Accessors void Set(const T& left, const T& top, const T& right, const T& bottom) { tl.SetX(left); tl.SetY(top); wh.SetX(right - left); wh.SetY(bottom - top); } T Width() const { return (wh.X()); } void SetWidth(const T& a) { wh.SetX(a); FixRectSize(); } T Height() const { return (wh.Y()); } void SetHeight(const T& a) { wh.SetY(a); FixRectSize(); } T Left() const { return tl.X(); } void SetLeft(const T& a) { CoordType temp = Right(); tl.SetX(a); SetRight(temp); FixRectSize(); } T Top() const { return tl.Y(); } void SetTop(const T& a) { CoordType temp = Bottom(); tl.SetY(a); SetBottom(temp); FixRectSize(); } T Right() const { return CoordType(tl.X() + wh.X()); } void SetRight(const T& a) { wh.SetX(a - tl.X()); FixRectSize(); } T Bottom() const { return CoordType(tl.Y() + wh.Y()); } void SetBottom(const T& a) { wh.SetY(a - tl.Y()); FixRectSize(); } const PointType& TL() const { return tl; } void SetTL(const PointType& pt) { PointType br = BR(); tl = pt; SetBR(br); FixRectSize(); } PointType BR() const { return PointType(tl.X() + wh.X(), tl.Y() + wh.Y()); } void SetBR(const PointType& pt) { wh.SetX(pt.X() - tl.X()); wh.SetY(pt.Y() - tl.Y()); FixRectSize(); } PointType TR() const { return PointType(tl.X() + wh.X(), tl.Y()); } void SetTR(const PointType& pt) { wh.SetX(pt.X() - tl.X()); tl.SetY(pt.Y()); FixRectSize(); } PointType BL() const { return PointType(tl.X(), tl.Y() + wh.Y()); } void SetBL(const PointType& pt) { tl.SetX(pt.X()); wh.SetY(pt.Y() - tl.Y()); FixRectSize(); } PointType Center() const { return PointType(tl.X() + (wh.X()/CoordType(2)), tl.Y() + (wh.Y()/CoordType(2))); } void SetCenter(const PointType& pt) { tl = pt - PointType(Size()/Scale(2)); } void CenterRectInRect(const RectType& arg) { SetCenter(arg.Center()); } const SizeType &Size() const { return wh; } void SetSize(const SizeType& sz) { wh = sz; FixRectSize(); } const PointType &GetPosition() const { return tl; } void SetPosition(const PointType& pt) { tl = pt; } void SetPosition(const T& x, const T& y) { tl.SetX(x); tl.SetY(y); } SizeType Radius() const { return Size()/Scale(2); } void SetRadius(const SizeType& sz) { SetSize(sz*Scale(2)); } bool IsEmpty() const { return(wh.X() <= CoordType(0) || wh.Y() <= CoordType(0)); } bool IsZero() const { return(tl.IsZero() && wh.IsZero()); } // Note; this used to be "FixEmptyRect()", but it didn't do that. // ie; a call to IsEmpty() would return true after a call to FixEmptyRect(). // it does ensure that the Right >= Left, and Bottom >= Top, so I changed // the name to "FixRectSize()" instead. // -sds 2/6/02 void FixRectSize() { if (wh.X() < CoordType(0)) wh.SetX(CoordType(0)); if (wh.Y() < CoordType(0)) wh.SetY(CoordType(0)); } bool IsIn(const PointType& p) { T temp = p.X() - tl.X(); if (temp < CoordType(0) || temp >= wh.X()) return false; temp = p.Y() - tl.Y(); if (temp < CoordType(0) || temp >= wh.Y()) return false; return true; } bool IsIn(const RectType& p) { return IsIn(p.TL()) && IsIn(p.BR()); } void Inset(CoordType dX, CoordType dY) { tl.SetX(tl.X() + dX); tl.SetY(tl.Y() + dY); wh.SetX(wh.X() - dX - dX); // width -= dX * 2 wh.SetY(wh.Y() - dY - dY); // height -= dY * 2; FixRectSize(); } void Inset(CoordType delta) { Inset(delta, delta); } void Inset(const PointType& delta) { Inset(delta.X(), delta.Y()); } void Inset(const SizeType& delta) { Inset(delta.X(), delta.Y()); } const RectType& SetMinimumSize(const SizeType& minSz) { if (wh.X() < minSz.X()) { wh.SetX(minSz.X()); } if (wh.Y() < minSz.Y()) { wh.SetY(minSz.Y()); } return *this; } void Offset(CoordType dX, CoordType dY) { tl.SetX(tl.X() + dX); tl.SetY(tl.Y() + dY); } void Offset(PointType const &rOffset) { tl += rOffset; } void NegativeOffset(PointType const &rOffset) { tl -= rOffset; } bool Intersects(RectType const &rOther) const { PointType otherBR = rOther.BR(); // here 'cause this isn't a native operation if (tl.X() >= otherBR.X()) return(false); if (tl.Y() >= otherBR.Y()) return(false); PointType br = BR(); // here 'cause this isn't a native operation if (br.X() < rOther.TL().X()) return(false); if (br.Y() < rOther.TL().Y()) return(false); return(true); } // Binary operations with Rect bool operator==(const RectType& arg) const { if (tl != arg.tl) return false; if (wh != arg.wh) return false; return true; } bool operator!=(const RectType& arg) const { return !((*this) == arg); } /* // "and"ing and "or"ing rectangles is alot less // clear than Union and Intersect, so I've changed them... // -sds 4/8/02 */ const RectType& Union(RectType const &rArg) { // Compute the union of two rects. if (rArg.IsEmpty()) { // arg is empty. Union is just *this. } else if (this->IsEmpty()) { // *this is empty. Union is just arg. *this = rArg; } else { RectType temp(*this); SetLeft(coord::Leftmost(temp.Left(), rArg.Left())); SetTop(coord::Topmost(temp.Top(), rArg.Top())); SetRight(coord::Rightmost(temp.Right(), rArg.Right())); SetBottom(coord::Bottommost(temp.Bottom(), rArg.Bottom())); } return *this; } const RectType& Intersect(RectType const &rArg) { // Compute the intersection of two rects. if (rArg.IsEmpty()) { // arg is empty. Intersection is therefore empty. *this = rArg; } else if (this->IsEmpty()) { // *this is empty. Intersection is therefore *this. } else { RectType temp(*this); SetLeft(coord::Rightmost(temp.Left(), rArg.Left())); SetTop(coord::Bottommost(temp.Top(), rArg.Top())); SetRight(coord::Leftmost(temp.Right(), rArg.Right())); SetBottom(coord::Topmost(temp.Bottom(), rArg.Bottom())); } FixRectSize(); return *this; } /* // depreciated in favor of the clearer // Offset() methods. -sds 2/7/02 // Binary operations with Point */ // Binary operations with Size const RectType& operator*=(const SizeType& arg) { tl *= arg; wh *= arg; return *this; } const RectType& operator*=(const Scale scale) { tl *= scale; wh *= scale; return *this; } const RectType& operator/=(const Scale scale) { tl /= scale; wh /= scale; return *this; } }; template <class T, class Scale> gt::Rect<T,Scale> operator+(const gt::Point<T,Scale>& a, const gt::Rect<T,Scale>& b) { Rect<T,Scale> temp(b); temp += a; return temp; } template <class T, class Scale> gt::Rect<T,Scale> operator-(const gt::Point<T,Scale>& a, const gt::Rect<T,Scale>& b) { Rect<T,Scale> temp(b); temp -= a; return temp; } template <class T, class Scale> gt::Size<T,Scale> operator-(const gt::Size<T,Scale>& a, const gt::Rect<T,Scale>& b) // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o { Rect<T,Scale> temp(b); temp += a; return temp; } template <class T, class Scale> gt::Size<T,Scale> operator-(const gt::Size<T,Scale>& a, const gt::Size<T,Scale>& b) // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o { gt::Size<T,Scale> temp; temp.SetX(a.X() - b.X()); temp.SetY(a.Y() - b.Y()); return temp; } template <class T, class Scale> gt::Rect<T,Scale> operator*(const gt::Size<T,Scale>& a, const gt::Rect<T,Scale>& b) { gt::Rect<T,Scale> temp(b); temp *= a; return temp; } template <class T, class Scale> gt::Rect<T,Scale> operator*(const Scale a, const gt::Rect<T,Scale>& b) { gt::Rect<T,Scale> temp(b); temp *= a; return temp; } template <class T, class Scale> gt::Rect<T,Scale> operator/(const gt::Rect<T,Scale>& a, const Scale b) { gt::Rect<T,Scale> temp(a); temp /= b; return temp; } #if defined(_WIN32) #pragma mark - #pragma mark Class Arc #pragma mark - #endif //----------------------------------------------------------------------------- // class Arc //----------------------------------------------------------------------------- template <class T, class Scale = double > class Arc // **CodeWizzard** - Severe Violation: Universal Coding Standards item 28 - Do not overload functions within a template clas { public: typedef gt::Size<T, Scale> SizeType; typedef gt::Point<T, Scale> PointType; typedef gt::Arc<T, Scale> ArcType; typedef T CoordType; typedef Scale ScaleType; private: Point<T, Scale> xy; gt::Size<T, Scale> wh; T s; T e; public: Arc() : xy(0, 0), wh(0, 0), s(T(0)), e(T(0)) {} template <class U, class UScale> Arc(const gt::Arc<U, UScale>& r) : xy(r.XY()), wh(static_cast<T>(r.Width()), static_cast<T>(r.Height())), s(static_cast<T>(r.StartAngle())), e(static_cast<T>(r.EndAngle())) {} Arc(const PointType& inXY, const SizeType& inSize, const T& inS, const T& inE): xy(inXY), wh(inSize), s(inS), e(inE) {} Arc(const T& inX, const T& inY, const T& inW, const T& inH, const T& inS, const T& inE) : xy(inX, inY), wh(inW, inH), s(inS), e(inE) {} // **CodeWizzard** - Violation: More Effective C++ item 24 - Understand the costs of virtual functions ... virtual ~Arc() {} gt::Arc<T>& operator=(const gt::Arc<T>& arg) { if (&arg == this) return *this; xy = arg.xy; wh = arg.wh; s = arg.s; e = arg.e; return *this; } // Accessors void Set(const T& inX, const T& inY, const T& inW, const T& inH, const T& inS, const T& inE) { xy.SetX(inX); xy.SetY(inY); wh.SetX(inW); wh.SetY(inH); s = inS; e = inE; } T Width() const { return (wh.X()); } void SetWidth(const T& a) { wh.SetX(a); } T Height() const { return (wh.Y()); } void SetHeight(const T& a) { wh.SetY(a); } T X() const { return (xy.X()); } void SetX(const T& a) { CoordType temp = Width(); xy.SetX(a); SetWidth(temp); FixArcSize(); } T Y() const { return (xy.Y()); } void SetY(const T& a) { CoordType temp = Height(); xy.SetY(a); SetHeight(temp); FixArcSize(); } T StartAngle() const { return s; } void SetStartAngle(const T& a) { s = a; FixArcSize(); } T EndAngle() const { return e; } void SetEndAngle(const T& a) { e = a; FixArcSize(); } const PointType& XY() const { return xy; } void SetXY(const PointType& pt) { xy = pt; } PointType Center() const { return PointType(xy); } void SetCenter(const PointType& pt) { SetXY(pt); } void CenterArcInArc(const ArcType& arg) { SetCenter(arg.Center()); } const SizeType &Size() const { return wh; } void SetSize(const SizeType& sz) { wh = sz; FixArcSize(); } const PointType &GetPosition() const { return xy; } void SetPosition(const PointType& pt) { xy = pt; } void SetPosition(const T& x, const T& y) { xy.SetX(x); xy.SetY(y); } SizeType Radius() const { return Size()/Scale(2); } void SetRadius(const SizeType& sz) { SetSize(sz*Scale(2)); } bool IsEmpty() const { return(wh.X() <= CoordType(0) || wh.Y() <= CoordType(0) || (s == e)); } bool IsZero() const { return(wh.IsZero() || (s == e)); } void FixArcSize() { if (wh.X() < CoordType(0)) wh.SetX(CoordType(0)); if (wh.Y() < CoordType(0)) wh.SetY(CoordType(0)); if (e < s) e += 360; } /* dpy--> not sure how to exactly handle angles bool IsIn(const PointType& p) { T temp = p.X() - xy.X(); if (temp < CoordType(0) || temp >= wh.X()) return false; temp = p.Y() - xy.Y(); if (temp < CoordType(0) || temp >= wh.Y()) return false; return true; } bool IsIn(const ArcType& p) { return IsIn(p.XY()) && IsIn(p.BR()); } void Inset(CoordType dX, CoordType dY) { xy.SetX(xy.X() + dX); xy.SetY(xy.Y() + dY); wh.SetX(wh.X() - dX - dX); // width -= dX * 2 wh.SetY(wh.Y() - dY - dY); // height -= dY * 2; FixArcSize(); } void Inset(CoordType delta) { Inset(delta, delta); } void Inset(const PointType& delta) { Inset(delta.X(), delta.Y()); } void Inset(const SizeType& delta) { Inset(delta.X(), delta.Y()); } */ const ArcType& SetMinimumSize(const SizeType& minSz) { if (wh.X() < minSz.X()) { wh.SetX(minSz.X()); } if (wh.Y() < minSz.Y()) { wh.SetY(minSz.Y()); } return *this; } void Offset(CoordType dX, CoordType dY) { xy.SetX(xy.X() + dX); xy.SetY(xy.Y() + dY); } void Offset(PointType const &rOffset) { xy += rOffset; } void NegativeOffset(PointType const &rOffset) { xy -= rOffset; } /* bool Intersects(RectType const &rOther) const { PointType otherBR = rOther.BR(); // here 'cause this isn't a native operation if (xy.X() >= otherBR.X()) return(false); if (xy.Y() >= otherBR.Y()) return(false); PointType br = BR(); // here 'cause this isn't a native operation if (br.X() < rOther.XY().X()) return(false); if (br.Y() < rOther.XY().Y()) return(false); return(true); } */ // Binary operations with Rect bool operator==(const ArcType& arg) const { if (xy != arg.xy) return false; if (wh != arg.wh) return false; if (s != arg.s) return false; if (e != arg.e) return false; return true; } bool operator!=(const ArcType& arg) const { return !((*this) == arg); } /* // "and"ing and "or"ing rectangles is alot less // clear than Union and Intersect, so I've changed them... // -sds 4/8/02 */ /* const ArcType& Union(ArcType const &rArg) { // Compute the union of two rects. if (rArg.IsEmpty()) { // arg is empty. Union is just *this. } else if (this->IsEmpty()) { // *this is empty. Union is just arg. *this = rArg; } else { ArcType temp(*this); SetLeft(coord::Leftmost(temp.Left(), rArg.Left())); SetTop(coord::Topmost(temp.Top(), rArg.Top())); SetRight(coord::Rightmost(temp.Right(), rArg.Right())); SetBottom(coord::Bottommost(temp.Bottom(), rArg.Bottom())); } return *this; } const ArcType& Intersect(ArcType const &rArg) { // Compute the intersection of two rects. if (rArg.IsEmpty()) { // arg is empty. Intersection is therefore empty. *this = rArg; } else if (this->IsEmpty()) { // *this is empty. Intersection is therefore *this. } else { ArcType temp(*this); SetLeft(coord::Rightmost(temp.Left(), rArg.Left())); SetTop(coord::Bottommost(temp.Top(), rArg.Top())); SetRight(coord::Leftmost(temp.Right(), rArg.Right())); SetBottom(coord::Topmost(temp.Bottom(), rArg.Bottom())); } FixArcSize(); return *this; } */ /* // depreciated in favor of the clearer // Offset() methods. -sds 2/7/02 // Binary operations with Point */ // Binary operations with Size const ArcType& operator*=(const SizeType& arg) { xy *= arg; wh *= arg; // Not clear on how to handle the angles // s *= arg.X(); // e *= arg.Y(); return *this; } const ArcType& operator*=(const Scale scale) { xy *= scale; wh *= scale; // Not clear on how to handle the angles // s *= scale; // e *= scale; return *this; } const ArcType& operator/=(const Scale scale) { xy /= scale; wh /= scale; // Not clear on how to handle the angles // s /= scale; // e /= scale; return *this; } }; template <class T, class Scale> gt::Arc<T,Scale> operator+(const gt::Point<T,Scale>& a, const gt::Arc<T,Scale>& b) { Arc<T,Scale> temp(b); temp += a; return temp; } template <class T, class Scale> gt::Arc<T,Scale> operator-(const gt::Point<T,Scale>& a, const gt::Arc<T,Scale>& b) { Arc<T,Scale> temp(b); temp -= a; return temp; } template <class T, class Scale> gt::Size<T,Scale> operator-(const gt::Size<T,Scale>& a, const gt::Arc<T,Scale>& b) // **CodeWizzard** - Violation: More Effective C++ item 2 - Consider using op= instead of stand-alone o { Arc<T,Scale> temp(b); temp += a; return temp; } template <class T, class Scale> gt::Arc<T,Scale> operator*(const gt::Size<T,Scale>& a, const gt::Arc<T,Scale>& b) { gt::Arc<T,Scale> temp(b); temp *= a; return temp; } template <class T, class Scale> gt::Arc<T,Scale> operator*(const Scale a, const gt::Arc<T,Scale>& b) { gt::Arc<T,Scale> temp(b); temp *= a; return temp; } template <class T, class Scale> gt::Arc<T,Scale> operator/(const gt::Arc<T,Scale>& a, const Scale b) { gt::Arc<T,Scale> temp(a); temp /= b; return temp; } } #endif
true
4cefe93ed139ab02f944bfb510191b3a0786dba2
C++
drlongle/leetcode
/algorithms/problem_0406/solution.cpp
UTF-8
3,113
3.71875
4
[]
no_license
/* 406. Queue Reconstruction by Height Difficulty: Medium Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. Example Input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] Output: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] */ #include <algorithm> #include <bitset> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; /* People are only counting (in their k-value) taller or equal-height others standing in front of them. So a smallest person is completely irrelevant for all taller ones. And of all smallest people, the one standing most in the back is even completely irrelevant for everybody else. Nobody is counting that person. So we can first arrange everybody else, ignoring that one person. And then just insert that person appropriately. Now note that while this person is irrelevant for everybody else, everybody else is relevant for this person - this person counts exactly everybody in front of them. So their count-value tells you exactly the index they must be standing. So you can first solve the sub-problem with all but that one person and then just insert that person appropriately. And you can solve that sub-problem the same way, first solving the sub-sub-problem with all but the last-smallest person of the subproblem. And so on. The base case is when you have the sub-...-sub-problem of zero people. You're then inserting the people in the reverse order, i.e., that overall last-smallest person in the very end and thus the first-tallest person in the very beginning. That's what the above solution does. Sorting the people from the first-tallest to the last-smallest, and inserting them one by one as appropriate. */ class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>>& people) { sort(begin(people), end(people), [] (const vector<int>& a, const vector<int>& b) { return (a[0] > b[0] || (a[0] == b[0] && a[1] < b[1])); }); vector<vector<int>> res; for (const auto& p: people) { res.insert(res.begin() + p[1], p); } return res; } }; int main(int argc, char** argv) { Solution sol; vector<vector<int>> people; people = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}}; people = {{8,2},{4,2},{4,5},{2,0},{7,2},{1,4},{9,1},{3,1},{9,0},{1,0}}; // Expected: [[3,0],[6,0],[7,0],[5,2],[3,4],[5,3],[6,2],[2,7],[9,0],[1,9]] people = {{9,0},{7,0},{1,9},{3,0},{2,7},{5,3},{6,0},{3,4},{6,2},{5,2}}; people = sol.reconstructQueue(people); for (const auto& p: people) cout << p[0] << ", " << p[1] << endl; return 0; }
true
0f0ae8969891af5cd1763714203e5014bb13228f
C++
Bouya12/self-study
/AtCoder/PastContestQuestions/AGC039/A.cpp
UTF-8
1,310
2.8125
3
[]
no_license
#include <bits/stdc++.h> #define rep(i, n) for(int i = 0; i < (int)(n); i++) using namespace std; int main() { string s; cin >> s; int k; cin >> k; // 全文字が同じの場合は例外処理の必要があるためチェック bool isSame = true; for (int i = 1; i < s.size(); i++) { if (s.at(i) != s.at(i -1)) { isSame = false; break; } } int sameA = 1, sameB = 1; int sameCnt = 1; int64_t cnt = 0; if (isSame) { cnt = s.size() * k / 2; } else { for (int i = 1; i < s.size(); i++) { if (s.at(i) == s.at(i - 1)) { sameCnt++; } else { cnt += sameCnt / 2; sameCnt = 1; } } cnt += sameCnt / 2; cnt *= k; if (k >= 2 && s.at(0) == s.at(s.size() - 1)) { // 先頭から同じ文字が何回続くか確認 for (int i = 1; i < s.size(); i++) { if (s.at(i) == s.at(i - 1)) { sameA++; } else { break; } } // 末尾から同じ文字が何回続くか確認 for (int i = s.size() - 1; i >= 0; i--) { if (s.at(i) == s.at(i - 1)) { sameB++; } else { break; } } cnt -= (sameA / 2 + sameB / 2 - (sameA + sameB) / 2) * (k - 1); } } cout << cnt << endl; return 0; }
true
67acd6c84b044048378cb3069489e19950c66d01
C++
LoveWX/OJ_mycoder
/hdu/1071.cpp
UTF-8
674
2.71875
3
[]
no_license
#include<stdio.h> int main() { int n; double a,b,c,x1,x2,x3,y1,y2,y3; while(scanf("%d",&n)!=EOF) { while(n>0) { n--; scanf("%lf%lf",&x1,&y1); scanf("%lf%lf",&x2,&y2); scanf("%lf%lf",&x3,&y3); if(x1==x2&&x1==x3) { printf("0.00\n"); continue; } if(x2>x3) { a=x2; x2=x3; x3=a; a=y2; y2=y3; y3=a; } if(x1==x2) a=(y3-y1)/((x3-x1)*(x3-x1)); else a=(y2-y1)/((x2-x1)*(x2-x1)); c=a*x1*x1+y1; b=-2*a*x1; a=((x3*a*0.33333333333+b*0.5)*x3+c)*x3-((x2*a*0.33333333333+b*0.5)*x2+c)*x2; b=(y2+y3)*(x3-x2)*0.5; if(a>b) a-=b; else a=b-a; printf("%.2lf\n",a); } } return 0; }
true
a0c2d3903e1779033fa96496012dee28e8291ebf
C++
viaduct/telim_tmsd
/value.tpp
UTF-8
2,537
2.59375
3
[]
no_license
#pragma once #include "value.h" #include "value_set_event.h" #include "item_event.h" #include "value_subject.tpp" #include "value_track.tpp" #include "item_track_info.h" #include "value_track_info.h" #include "value_type.h" #include "value_stop_refer_info.h" namespace telimtmsd { template<typename T> Value<T>::Value( Manager* manager, ValueType<T> const* valueType ) : Item(manager), m_valueType(valueType) { } template<typename T> Value<T>::~Value() { } template<typename T> void Value<T>::stopRefer(Item*,StopReferInfo** sri) { if ( sri ) { auto const newSri = new ValueStopReferInfo; *sri = newSri; } } template<typename T> void Value<T>::stopReferAll(StopReferInfo** sri) { if ( sri ) { auto const newSri = new ValueStopReferInfo; *sri = newSri; } } template<typename T> size_t Value<T>::referredItemsSize() const { return 0; } template<typename T> std::vector<Item *> Value<T>::referredItems() const { return std::vector<Item*>(); } template <typename T> ItemTrack* Value<T>::createTrack( Track* parent, ItemTrackInfo const* trackInfo ) { return new ValueTrack<T>( parent, this, toValueTrackInfo<T>(trackInfo) ); } template<typename T> const ItemType *Value<T>::itemType() const { return m_valueType; } template<typename T> ValueType<T> const* Value<T>::valueType() const { return m_valueType; } template<typename T> const T &Value<T>::get() const { return m_value; } template<typename T> void Value<T>::set(ValueSubject<T> *subject, T t) { ValueSetEvent<T> e( this, subject, m_value, t ); e.setType(decltype(e)::Type::Set_B); for ( auto const& subject : m_subjects ) { subject->emitEvent(&e); } m_value = std::move(t); e.setType(decltype(e)::Type::Set_A); for ( auto const& subject : m_subjects ) { subject->emitEvent(&e); } } template<typename T> ValueSubject<T> *Value<T>::createValueSubject() { auto const iter = m_subjects.emplace(std::make_unique<ValueSubject<T>>(this)).first; return (*iter).get(); } template<typename T> void Value<T>::freeValueSubject(ValueSubject<T> *subject) { subject->emitExpired(); m_subjects.erase(m_subjects.find(subject)); } template<typename T> void Value<T>::handleItemEvent(const ItemEvent * event) { switch ( event->type() ) { case ItemEvent::Type::Expire_B: freeAllValueSubjects(); break; default: break; } } template<typename T> void Value<T>::freeAllValueSubjects() { for ( auto const& subject : m_subjects ) { subject->emitExpired(); } m_subjects.clear(); } }
true
19bf820715fdf32b29cabf885feb2d1695108b81
C++
lukevand/kattis-submissions
/wheresmyinternet.cpp
UTF-8
719
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef vector<int> VI; typedef vector<VI> VVI; VVI G; vector<bool> visted; void dfs(int v) { visted[v] = 1; for (int u : G[v]) { if (!visted[u]) { dfs(u); } } } int main() { int N, M, x, y; scanf("%d %d", &N, &M); G.assign(N+1, VI()); visted.assign(N+1, 0); while (M--) { scanf("%d %d", &x, &y); G[x].push_back(y); G[y].push_back(x); } dfs(1); bool missing = false; for (int i=1; i<=N; i++) { if (!visted[i]) { printf("%d\n", i); missing = true; } } if (!missing) { printf("Connected\n"); } return 0; }
true
61c0f222f85e53f0ab039cea3e6dbed6fffce31c
C++
SoStealth/dnd_encounter_generator
/test_codes/rules_test.cpp
UTF-8
458
2.9375
3
[]
no_license
#include "rules.hpp" #include <stdio.h> int main(int argc, char* argv[]) { init_random(); printf("Here's a dice: D%d\n",D100); printf("Rolling the dice 5 times...\n"); for(int i=0;i<5;i++) { printf("%d\n",throw_dice(D100)); } printf("Here's the modifier for a 17 stat: %d\n",get_modifier(17)); printf("Here's the modifier for a 6 stat: %d\n",get_modifier(6)); printf("Here's the modifier for a 10 stat: %d\n",get_modifier(10)); printf("End\n"); }
true
47a4cafb319f25f85f973bf3fb1a6e8ff27bc43f
C++
fkhan6601/StepperTest
/StepperTest.ino
UTF-8
5,712
2.75
3
[]
no_license
/* Suspension Control Script */ #include <Wire.h> #include <Adafruit_MotorShield.h> #include "utility/Adafruit_MS_PWMServoDriver.h" #include <LiquidCrystal.h> #include <EEPROM.h> int data2=0; int x = 0; int stepCount1 = 0; int stepCount2 = 0; int stepCount3 = 0; int stepCount4 = 0; int StoredFL = 0; int StoredFR = 0; int StoredRL = 0; int StoredRR = 0; // motor shield I2C address Adafruit_MotorShield AFMS1 = Adafruit_MotorShield(0x60); Adafruit_MotorShield AFMS2 = Adafruit_MotorShield(0x61); // stepper motor steps Adafruit_StepperMotor *myMotorFL = AFMS1.getStepper(200, 1); Adafruit_StepperMotor *myMotorFR = AFMS1.getStepper(200, 2); Adafruit_StepperMotor *myMotorRL = AFMS2.getStepper(200, 1); Adafruit_StepperMotor *myMotorRR = AFMS2.getStepper(200, 2); void setup() { Serial.begin(115200); // set up Serial library at 115200 bps // motor setup AFMS1.begin(); AFMS2.begin(); //motor speed myMotorFL->setSpeed(0.1); myMotorFR->setSpeed(0.1); myMotorRL->setSpeed(0.1); myMotorRR->setSpeed(0.1); //Zero motors myMotorFL->step(400, FORWARD, DOUBLE); myMotorFR->step(400, FORWARD, DOUBLE); myMotorRL->step(400, FORWARD, DOUBLE); myMotorRR->step(400, FORWARD, DOUBLE); //Set previous settings if (EEPROM.read(0)==255) { EEPROM.write(0, 0); EEPROM.write(1, 0); EEPROM.write(2, 0); EEPROM.write(3, 0); } myMotorFL->step(EEPROM.read(0)*4, BACKWARD, DOUBLE); myMotorFR->step(EEPROM.read(1)*4, BACKWARD, DOUBLE); myMotorRL->step(EEPROM.read(2)*4, BACKWARD, DOUBLE); myMotorRR->step(EEPROM.read(3)*4, BACKWARD, DOUBLE); stepCount1 = EEPROM.read(0); stepCount2 = EEPROM.read(1); stepCount3 = EEPROM.read(2); stepCount4 = EEPROM.read(3); } void DefaultDisplay() { StoredFL = EEPROM.read(0); StoredFR = EEPROM.read(1); StoredRL = EEPROM.read(2); StoredRR = EEPROM.read(3); if (StoredFL!=stepCount1 || StoredFR!=stepCount2 || StoredRL!=stepCount3 || StoredRR!=stepCount4) { EEPROM.update(0, stepCount1); EEPROM.update(1, stepCount2); EEPROM.update(2, stepCount3); EEPROM.update(3, stepCount4); } delay(200); } //Increase motor count to make suspension softer void MoveMotorIncrease(int StepC) { StepC++; DefaultDisplay(); delay(300); } //Decrease motor count to make suspenseion harder void MoveMotorDecrease(int StepC) { StepC--; DefaultDisplay(); delay(300); } void UpdateSerial() { String data3 = String(stepCount1)+String(stepCount2)+String(stepCount3)+String(stepCount4); Serial.println(data3); /* for(int i=0; i<data3.length(); i++) { Serial.write(data3[i]); } */ } void Preset(int Setting) { if (stepCount1<Setting) { while(stepCount1<Setting) { stepCount1++; myMotorFL->step(4, BACKWARD, DOUBLE); } } if (stepCount1>Setting) { while(stepCount1>Setting) { stepCount1--; myMotorFL->step(4, FORWARD, DOUBLE); } } if (stepCount2<Setting) { while(stepCount2<Setting) { stepCount2++; myMotorFR->step(4, BACKWARD, DOUBLE); } } if (stepCount2>Setting) { while(stepCount2>Setting) { stepCount2--; myMotorFR->step(4, FORWARD, DOUBLE); } } if (stepCount3<Setting) { while(stepCount3<Setting) { stepCount3++; myMotorRL->step(4, BACKWARD, DOUBLE); } } if (stepCount3>Setting) { while(stepCount3>Setting) { stepCount3--; myMotorRL->step(4, FORWARD, DOUBLE); } } if (stepCount4<Setting) { while(stepCount4<Setting) { stepCount4++; myMotorRR->step(4, BACKWARD, DOUBLE); } } if (stepCount4>Setting) { while(stepCount4>Setting) { stepCount4--; myMotorRR->step(4, FORWARD, DOUBLE); } } } void loop() { if(Serial.available()>0) { int data =Serial.parseInt(); delay(500); if(data>0) { //delay(500); data2 = data; //delay(500); //Serial.println(data2); } } if ( data2==13) { Preset(5); } if ( data2==14) { Preset(20); } if ( data2==15) { Preset(60); } //Front Left Motor if ( data2==11 || data2==51 || data2==71) { if(stepCount1<100) { stepCount1++; myMotorFL->step(4, BACKWARD, DOUBLE); UpdateSerial(); } } else if ( data2==12 || data2==52 || data2==72) { if(stepCount1>0) { stepCount1--; myMotorFL->step(4, FORWARD, DOUBLE); UpdateSerial(); } } //Front Right Motor if ( data2==21 || data2==51 || data2==71) { if(stepCount2<100) { stepCount2++; myMotorFR->step(4, FORWARD, DOUBLE); UpdateSerial(); } } else if ( data2==22 || data2==52 || data2==72) { if(stepCount2>0) { stepCount2--; myMotorFR->step(4, BACKWARD, DOUBLE); UpdateSerial(); } } //Rear Left Motor if ( data2==31 || data2==61 || data2==71) { if(stepCount3<100) { stepCount3++; myMotorRL->step(4, BACKWARD, DOUBLE); UpdateSerial(); } } else if ( data2==32 || data2==62 || data2==72) { if(stepCount3>0) { stepCount3--; myMotorRL->step(4, FORWARD, DOUBLE); UpdateSerial(); } } //Rear Right Motor if ( data2==41 || data2==61 || data2==71) { if(stepCount4<100) { stepCount4++; myMotorRR->step(4, FORWARD, DOUBLE); UpdateSerial(); } } else if ( data2==42 || data2==62 || data2==72) { if(stepCount4>0) { stepCount4--; myMotorRR->step(4, BACKWARD, DOUBLE); UpdateSerial(); } } //Serial.write(data3); //Serial.println(data3); data2=0; }
true
52588061c276e6cd64a72f7ee788b3106426ecc4
C++
benreid24/Peoplemon
/include/Game/TrainerSpottedPlayerState.hpp
UTF-8
892
2.953125
3
[]
no_license
#ifndef TRAINERSPOTTEDPLAYERSTATE_HPP #define TRAINERSPOTTEDPLAYERSTATE_HPP #include "Gamestate.hpp" class Trainer; class BattleState; class ConversationState; /** * Gamestate for when a Trainer has spotted the player and is walking to them * * \ingroup Game */ class TrainerSpottedPlayerState : public Gamestate { Trainer* trainer; BattleState* battle; ConversationState *preConv, *postConv; /** * Runs the state */ bool execute(); public: /** * Constructs the state from the given data * * \param g A pointer to the main Game object * \param t A pointer to the trainer who has spotted the player * \param n The next state to run */ TrainerSpottedPlayerState(Game* g, Trainer* t); /** * Unlocks the player and trainer */ ~TrainerSpottedPlayerState(); }; #endif // TRAINERSPOTTEDPLAYERSTATE_HPP
true
6d3a533e4f855f8445700c4defa3ba715bd3ebf5
C++
jijijijitian/bank
/bank/bankcli/client.cpp
GB18030
5,774
2.578125
3
[]
no_license
#include "myhead.h" SOCKET sock; int do_client() { //Эջװ WORD wVersionRequsted = MAKEWORD(2, 2); WSADATA wsaData; if (WSAStartup(wVersionRequsted, &wsaData) != 0) //ʼ { return 1; } if (wsaData.wVersion != wVersionRequsted) //Winsock汾ƥ { WSACleanup(); //socket return 1; } //ͨŵ׽ӿ sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock == INVALID_SOCKET) { cout << "socket error: " << WSAGetLastError() << endl; return 1; } cout << "socket success..." << endl; //׽ְ󶨱ҪϢ sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(8887); //ӷ int ret = connect(sock, (sockaddr*)&addr, sizeof(addr)); if (ret == -1) { cout << "connect error: " << WSAGetLastError() << endl; return 1; } cout << "connect success..." << endl; //ѭ int back = 1, back1 = 1; while (back) { entershow(); char choice[2] = { 0 }, choice1[2] = { 0 }; cin >> choice; switch (choice[0]) { case '1': { class enter* ent = new enter; char ent_usr[10]; cout << "û3~10"; cin >> ent_usr; char ent_pwd[8]; cout << "루6~8"; int ii = 0; while ((ent_pwd[ii++] = _getch()) != '\r') { putchar('*'); } ent_pwd[ii - 1] = '\0'; if (ent->m_enter(ent_usr, ent_pwd) == 1) { int back1 = 1; while (back1) { show(); cin >> choice1; switch (choice1[0]) { case '1': { class opencont* ope = new opencont; char ope_name[16] = { 0 }; char ope_passwd1[9] = { 0 }; char ope_passwd2[9] = { 0 }; char ope_id[19] = { 0 }; double ope_money = 0; cout << "3~10"; cin >> ope_name; do { cout << "루6~8"; cin >> ope_passwd1; cout << "ٴ루6~8"; cin >> ope_passwd2; } while (strcmp(ope_passwd1, ope_passwd2) != 0); cout << "֤ţ18λ" ; cin >> ope_id; cout << "뿪" ; cin >> ope_money; ope->m_open(ope_name, ope_passwd1, ope_id, ope_money); delete ope; break; } case '2': { class save* sav = new save; long sav_id; cout << "ID"; cin >> sav_id; double sav_money = 0; cout << ""; cin >> sav_money; sav->m_save(sav_id, sav_money); delete sav; break; } case '3': { class drow* dro = new drow; long dro_id = 0; cout << "ID"; cin >> dro_id; char dro_pwd[9] = { 0 }; cout << "룺"; cin >> dro_pwd; double dro_money = 0; cout << "ȡ"; cin >> dro_money; dro->m_drow(dro_id, dro_pwd, dro_money); delete dro; break; } case '4': { class transfer* tra = new transfer; long tra_id = 0; cout << "ID"; cin >> tra_id; char tra_pwd[9] = { 0 }; cout << "룺"; cin >> tra_pwd; double tra_money = 0; cout << "ת˽"; cin >> tra_money; long tra_toid = 0; cout << "ԷID"; cin >> tra_toid; tra->m_transfer(tra_id, tra_pwd, tra_money, tra_toid); delete tra; break; } case '5': { class query* que = new query; long que_id = 0; cout << "ID"; cin >> que_id; char que_date1[20] = { 0 }; cout << "ʼڣ"; cin >> que_date1; char que_date2[20] = { 0 }; cout << "ڣ"; cin >> que_date2; que->m_query(que_id, que_date1, que_date2); delete que; break; } case '6': { class change_passwd* cha = new change_passwd; long cha_id = 0; cout << "ID"; cin >> cha_id; char cha_passwd[9] = { 0 }; cout << "룺"; cin >> cha_passwd; char cha_newpasswd[9] = { 0 }; cout << "룺"; cin >> cha_newpasswd; cha->m_change_passwd(cha_id, cha_passwd, cha_newpasswd); delete cha; break; } case '7': { break; } case '8': { back1 = 0; break; } default: { cout << "룡" << endl; break; } } } } delete ent; break; } case '2': { back = 0; break; } default: { cout << "룡" << endl; break; } } } WSACleanup(); if (SOCKET_ERROR == closesocket(sock)) { sock = INVALID_SOCKET; } return 0; } void show() { printf("\n*************************************\n"); printf("** ѡ: **\n"); printf("** <1> <2> **\n"); printf("** <3> ȡ <4> ת **\n"); printf("** <5> ѯ <6> ޸ **\n"); printf("** <7> <8> ˳ **\n"); printf("*************************************\n\n"); } void entershow() { printf("\n************************************\n"); printf("** ѡ: **\n"); printf("** <1> ¼ <2> ˳ **\n"); printf("************************************\n\n"); }
true
e669f52ef4f7078d0092bdd967cbde2960e94ff9
C++
wamor17/computerVision
/10_Hough_transform/hough.cpp
UTF-8
5,135
2.578125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <cmath> #include <opencv2/opencv.hpp> #define pi 3.14159265 using namespace std; using namespace cv; Mat img, imageOut; Mat filledImage; void hough_lines(); void hough_circles(); void plot(Mat in); void plot2(Mat in, Mat out); void plot3(Mat in1, Mat in2, Mat in3); int main(int argc, char **argv){ img = imread(argv[1], 0 ); if (!img.data){ cout<<"\n Take care how typing the picture name \n"<<endl; return -1; } img.copyTo(imageOut); hough_lines(); return 0; } void hough_circles(){ // VARIABLES A UTILIZAR int rows = img.rows, cols = img.cols, distMax = round(sqrt( pow(rows,2) + pow(cols,2) )); int radio = 80, pixel = 0, Cx = 0, Cy = 0, mayor=0, radius=0; int imgIn[rows][cols]={0}, imgOut[rows][cols]={0}, collector[rows][cols][radio]; /* for (int i=0; i<rows; i++){ for (int j=0; j<cols; j++){ pixel = img.data[i*cols + j]; cout<<" pixel = "<<pixel; if( pixel == 0 ) for(int r=5; i<radio; i++) for(int theta=0; theta<360; theta++){ Cx = i + cos((theta*pi)/180)*r; Cy = j + sin((theta*pi)/180)*r; cout<<" Cx = "<<Cx<<"\n Cy = "<<Cy<<endl; if( Cx >= 0 && Cy >= 0 ){ collector[Cx][Cy][r]++; if( collector[Cx][Cy][r] > mayor ){ mayor = collector[Cx][Cy][r]; Cx = i; Cy = j; radius = r; } } } // imgIn[i][j] = img.data[i*cols + j]; } } */ // cout<<endl<<" Valor mayor = "<<mayor<<"\n Con coordenadas (Cx,Cy,r) ("<<Cx<<","<<Cy<<","<<radius<<") "<<endl<<endl; } void hough_lines(){ // VARIABLE A UTILIZAR int rows = img.rows, cols = img.cols, dMaxima = round(sqrt( pow(rows,2) + pow(cols,2) )), grados=360; int rowsCollector = dMaxima, collector[rowsCollector][grados] = {0}; int imgIn[rows][cols], imgOut[rows][cols]; // SE BUSCA EN LA IMAGEN UN PUNTO NEGRO, QUE REPRESENTA UN BORDE, AL ENCONTRARLO SE CREAN LAS CURVAS SINUSOIDALES EN EL PLANO POLAR // Y SE VAN AGREGANDO EN FORMA DE INCREMENTO A LOS ARREGLOS, CONSIDERANDO LOS VALORES NEGATIVOS Y POSITIVOS QUE PUEDEN RESULTAR // DE APLICAR LA EXTRAPOLACION A COORDENADAS POLARES CON UN INTERVALO DE [0, 180) // SE OBTIENE EL VALOR MAYOR QUE INDICA EL CRUCE DE VARIAS CURVAS POR EL MISMO PUNTO DEL PLANO POLAR, ESTO NOS DA UN PUNTO EN COMUN Y, // UN PUNTO EN EL PLANO POLAR ES IGUAL A UNA RECTA EN EL PLANO CARTESIANO int mayor=0, x=0, y=0, p=0, pixel=0; for (int i=0; i<rows; i++) for (int j=0; j<cols; j++){ imgIn[i][j] = 0; imgOut[i][j] = 0; pixel = img.data[i*cols + j]; if ( pixel > 0 ){ for (int theta=0; theta<grados; theta++){ p = i*cos((theta*pi)/180) + j*sin((theta*pi)/180); if ( p >= 0 ){ collector[p][theta]++; if( collector[p][theta] > mayor ){ mayor = collector[p][theta]; x = i; y = j; } } } } imgIn[i][j] = img.data[i*cols + j]; } cout<<endl<<" Valor mayor = "<<mayor<<"\n Con coordenadas x-y ("<<x<<","<<y<<") "<<endl<<endl; // OBTENEMOS SOLO LOS PUNTOS QUE ESTAN POR ENCIMA DEL 80% DEL VALOR PARA EL PUNTO MAXIMO EN EL ACUMULADOR int umbral = 100;//0.7*mayor; cout<<" RECTAS MAXIMAS EN COORDENADAS (ro,theta) \n"<<endl; cout<<" Umbral = "<<umbral<<endl<<endl; for (int i=0; i<rowsCollector; i++){ for (int j=0; j<grados; j++){ if ( collector[i][j] >= umbral ){ collector[i][j] = 255; cout<<" ("<<i<<","<<j<<")"<<endl; }else collector[i][j] = 0; } } cout<<endl<<endl; // OBTENEMOS RECTAS EN EL PLANO X-Y, A PARTIR DE PUNTOS EN EL PLANO RO-THETA int Y=0; for (int ro=0; ro<rowsCollector; ro++) for (int theta=0; theta<grados; theta++){ if( collector[ro][theta] == 255 ){ for (int x=0; x<rows; x++) if ( sin((theta*pi)/180) > 0 ){ Y = ( ro - x*cos((theta*pi)/180) )/sin((theta*pi)/180); if( Y >= 0 && Y < cols ) imgIn[x][Y] = 255; } } } // SE PASAN LOS DATOS DEL ACUMULADOR A UNA IMAGEN Mat Collector(rowsCollector, grados, CV_8UC1, Scalar(255)); for (int i=0; i<rowsCollector; i++) for (int j=0; j<grados; j++){ Collector.data[i*grados + j] -= collector[i][j]; } Mat lineas(rows, cols, CV_8UC1, Scalar(0)); for (int i=0; i<rows; i++) for(int j=0; j<cols; j++){ lineas.data[i*cols + j] = imgIn[i][j]; } // SE MUESTRA TANTO LA IMAGEN DE PUNTOS EN UN PLANO CARTESIANO COMO SU SIMILAR EN EL PLANO POLAR plot(lineas); } void plot(Mat in){ namedWindow("Solo una imagen de salida", 0); imshow("Solo una imagen de salida", in); waitKey(0); } void plot2(Mat in, Mat out){ namedWindow("IMAGEN DE ENTRADA", 0); imshow("IMAGEN DE ENTRADA", in); waitKey(0); namedWindow("IMAGEN DE SALIDA CON LA RECTA PREDOMINANTE", 0); imshow("IMAGEN DE SALIDA CON LA RECTA PREDOMINANTE", out); waitKey(0); } void plot3(Mat in1, Mat in2, Mat in3){ namedWindow("IMAGEN DE ENTRADA", WINDOW_AUTOSIZE); imshow("IMAGEN DE ENTRADA", in1); waitKey(0); namedWindow("CURVAS SINUSOIDALES DE CADA PUNTO DE LA IMAGEN DE ENTRADA", WINDOW_AUTOSIZE); imshow("CURVAS SINUSOIDALES DE CADA PUNTO DE LA IMAGEN DE ENTRADA", in2); waitKey(0); namedWindow("IMAGEN DE SALIDA, RECTA PREDOMINANTE", WINDOW_AUTOSIZE); imshow("IMAGEN DE SALIDA, RECTA PREDOMINANTE", in3); waitKey(0); }
true
170807b31ec6e3fd5bede30a13ae4f2fa67da738
C++
lSnowy100l/SnowEngine
/SnowEngine/SnowEngine/Camera.h
UTF-8
2,470
2.984375
3
[]
no_license
#pragma once #include <iostream> #include "Utils.h" #define CAM_SPEED_NORM 15 #define CAM_SPEED_FAST 50 #define JUMP_FORCE 30 class Camera { private: Vec3GLf _position = Vec3GLf(); Mat4GLf _projectionMatrix; bool _use_abs_movement; //For alternating between jetpack movement bool _on_jump, _start_jump; GLfloat _yawRad, _pitchRad; //Avoid restacking continuosly Vec3GLf _iteration_increment; //Absolute positional increment for the next iteration GLfloat current_speed = CAM_SPEED_NORM; //Speed for camera and player movement GLfloat _pitch = 0, _yaw = 0; public: Camera(GLfloat width, GLfloat height, GLfloat fov, GLfloat znear, GLfloat zfar, Vec3GLf position); inline Vec3GLf getPosition() { return _position; } // Returns actual camera position Vec3GLf getLookAt(); // Returns actual camera view vector inline Mat4GLf getTranslationMatrix() { return Mat4GLf::translationMatrix(-_position); } // Creates a translation matrix from camera's actual position Mat4GLf getRotationMatrix(); void moveCamera(Vec3GLf increment); inline Mat4GLf getProjectionMatrix() { return _projectionMatrix; } // Returns actual projection matrix inline void incAbsPos(Vec3GLf increment) { _position += increment; } // Increments camera's position by @increment void absoluteMovement(Vec3GLf increment); void relativeMovement(Vec3GLf increment); void setMovementMode(bool mode); inline void setJump(bool jump) { this->_on_jump = jump; } inline void setStartJump(bool start_jump) { this->_start_jump = start_jump; } inline bool getStartJump() { return this->_start_jump; } inline bool getJump() { return this->_on_jump; } void storeNextIterationMove(GLfloat x, GLfloat y, GLfloat z); void updateMovementCamera(GLfloat delta_time, Vec3GLf * acceleration); void resetIterationMove() { _iteration_increment.x = 0; _iteration_increment.y = 0; _iteration_increment.z = 0; } GLfloat getCurrentSpeed() { return this->current_speed; } void setCurrentSpeed(GLfloat speed) { this->current_speed = speed; } inline void incPitch(GLfloat pitch) { _pitch += pitch; if (_pitch > 90) _pitch = 90; if (_pitch < -90) _pitch = -90; } inline void incYaw(GLfloat yaw) { _yaw += yaw; while (_yaw > 360) _yaw -= 360; while (_yaw < 0) _yaw += 360; } GLfloat getPitch() { return _pitch; } GLfloat getYaw() { return _yaw; } inline void setPosition(Vec3GLf pos) { _position.x = pos.x; _position.y = pos.y; _position.z = pos.z; } ~Camera(); };
true
fbe48ad68210a570d709637e588856a279ccb0e7
C++
LiuKang1080/Learning_CPP
/Basics_Of_CPP/4_Control_Flow/Sources/5_Do_While_Loops.cpp
UTF-8
916
3.96875
4
[]
no_license
// Do While Loops in C++ /* Do-While Loops: - General syntax: do { statement(s); } while (expression); - The semi-colon is required at the end. - The expression condition check happens at the end (post test loop). - The loop will run at least once guaranteed. ex) Area calculation with multiple calculations char selection{}; do { double width = 0.00; double height = 0.00; std::cout << "Enter the width and height seperated by a space: "; std::cin >> width >> height; double area = width * height; std::cout << "The area is: " << area << "\n"; std::cout << "Calculate another? (Y/N): "; std::cin >> selection; } while (selection=='Y' || selection=='y'); */ #include <iostream> int main() { return 0; }
true
fa5f7103c5a3031a0c0a7240c038ebaad85d9ce5
C++
xiaoy/CPrimer
/lfwu/chapter11/12_pair.cc
UTF-8
822
3.140625
3
[]
no_license
// ------------------------------------------------------------------- // Author: lfwu // Date: January-03-2014 // Note: // Email:zgwulongfei@gmail.com // Blog:http://blog.csdn.net/hackmind // ------------------------------------------------------------------- #include <iostream> #include <vector> #include <utility> #include <string> using namespace std; int main(int argc, char** argv){ string book_no; int book_count; vector<pair<string, int>> book_info; while(cin >> book_no >> book_count) { if(book_no.size() == 0) { cout << "book no is empty\n"; return 0; } pair<string, int> book = {book_no, book_count}; book_info.push_back(book); } for(auto it : book_info) { cout << "book no:" << it.first << "\tcount:" << it.second << endl; } }
true
9ebc4b653699db2b250511efbace2512e8efe67d
C++
BGCX067/fallout-equestria-git
/code/world/include/world/particle_effect.hpp
UTF-8
2,530
2.640625
3
[]
no_license
#ifndef PARTICLE_EFFECT_HPP # define PARTICLE_EFFECT_HPP # include "globals.hpp" # include <panda3d/pointParticleFactory.h> # include <panda3d/zSpinParticleFactory.h> # include <panda3d/baseParticleEmitter.h> # include <panda3d/baseParticleRenderer.h> # include <panda3d/particleSystem.h> # include "datatree.hpp" # define AddException(type_name, message) \ struct type_name : public std::exception { public: const char* what() const throw() { return (message); } }; struct ParticleFactoryComponent { void InitializePointParticleFactory(Data data); void InitializeZSpinParticleFactory(Data data); PT(BaseParticleFactory) particle_factory; }; struct ParticleEmitterComponent { void InitializeBoxEmitter(Data data); void InitializeDiscEmitter(Data data); void InitializeLineEmitter(Data data); void InitializePointEmitter(Data data); void InitializeRectangleEmitter(Data data); void InitializeRingEmitter(Data data); void InitializeSphereSurfaceEmitter(Data data); void InitializeSphereVolumeEmitter(Data data); void InitializeTangeantRingEmitter(Data data); PT(BaseParticleEmitter) particle_emitter; }; struct ParticleRendererComponent { void InitializeGeomRenderer(Data data); void InitializeLineRenderer(Data data); void InitializePointRenderer(Data data); void InitializeSparkleRenderer(Data data); void InitializeSpriteRenderer(Data data); PT(BaseParticleRenderer) particle_renderer; }; class ParticleEffect : protected ParticleFactoryComponent, protected ParticleEmitterComponent, protected ParticleRendererComponent { public: AddException(UnknownFactoryType, "Unknown factory type") AddException(UnknownEmitterType, "Unknown emitter type") AddException(UnknownRendererType, "Unknown renderer type") ParticleEffect(); void LoadConfiguration(const std::string& filepath); void LoadConfiguration(Data configuration); void ReparentTo(NodePath nodePath); std::string GetParentName(void) const; PT(ParticleSystem) GetParticleSystem(void) const { return (particle_system); } private: PT(ParticleSystem) particle_system; struct Initializer { typedef void (ParticleEffect::*Loader)(Data); Initializer(const std::string name, Loader method) : name(name), method(method) {} const std::string name; Loader method; }; static Initializer emitter_initializers[]; static Initializer renderer_initializers[]; }; #endif
true
57fcb4c7eceb986647f307ca3c8b0626def738f2
C++
Jtrice/Checkers-game
/Programming Test/PTHeader.h
UTF-8
1,850
3.203125
3
[]
no_license
#ifndef P_T_HEADER #define P_T_HEADER #include <string> #include <array> #include <vector> #include <iostream> #include <iomanip> class GameState { public: GameState(); GameState(int rows, int cols, int blackRows, int redRows); //GameState(int row, int col, std::array<std::array<char, 8>, 8> gameBoard); void takeTurn(); char getWinningPlayer(); void announceWinner(); private: int row; int col; char currentPlayer; char winningPlayer; //std::array<std::array<char, 8>, 8> gameBoard; std::vector<std::vector<char>> gameBoard; char swapPlayer(); char opponent(); void computerMove(); bool playerMove(); void displayBoard(); bool validMoveRemains(); bool pieceHasValidJump(int row, int col); bool pieceHasValidMove(int row, int col); void makeMove(int rowFrom, int colFrom, int rowTo, int colTo); bool moveIsValid(int rowFrom, int colFrom, int rowTo, int colTo); }; //std::array<std::array<char, 8>, 8> stdCheckersBoard(); // Method definitions // Creates a beginning board for checkers //std::array<std::array<char, 8>, 8> stdCheckersBoard() //{ // // Initialize array of arrays to hold gameboard // std::array<std::array<char, 8>, 8> gameBoard; // // // Initialize the board for play // char piece = 'b'; // // for (int i = 0; i < int(gameBoard.size()); i++) // { // std::cout << &i; // }; // // gameBoard.at(0) = { 'b','i','b','i','b','i','b','i' }; // gameBoard.at(1) = { 'i','b','i','b','i','b','i','b' }; // gameBoard.at(2) = { 'b','i','b','i','b','i','b','i' }; // gameBoard.at(3) = { 'i','o','i','o','i','o','i','o' }; // gameBoard.at(4) = { 'o','i','o','i','o','i','o','i' }; // gameBoard.at(5) = { 'i','r','i','r','i','r','i','r' }; // gameBoard.at(6) = { 'r','i','r','i','r','i','r','i' }; // gameBoard.at(7) = { 'i','r','i','r','i','r','i','r' }; // // // return gameBoard; //} #endif //P_T_HEADER
true
0af0566719b490dd32fe032979e48e29fa2a04d1
C++
ullasreddy-chennuri/GeeksforGeeks
/Add two numbers represented by linked lists .cpp
UTF-8
2,883
4.21875
4
[]
no_license
/* Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. The sum list is a linked list representation of the addition of two input numbers from the last. Example 1: Input: N = 2 valueN[] = {4,5} M = 3 valueM[] = {3,4,5} Output: 3 9 0 Explanation: For the given two linked list (4 5) and (3 4 5), after adding the two linked list resultant linked list will be (3 9 0). Example 2: Input: N = 2 valueN[] = {6,3} M = 1 valueM[] = {7} Output: 7 0 Explanation: For the given two linked list (6 3) and (7), after adding the two linked list resultant linked list will be (7 0). Your Task: The task is to complete the function addTwoLists() which has node reference of both the linked lists and returns the head of the new list. Expected Time Complexity: O(N+M) Expected Auxiliary Space: O(Max(N,M)) Constraints: 1 <= N, M <= 5000 */ void insert_at_begin(int data,Node* &head){ Node* newNode = new Node(data); if(head==NULL){ head = newNode; return; }else{ newNode->next=head; head=newNode; } } void reverse(Node **head){ Node* curr = *head; Node* prev=NULL; Node* next; while(curr!=NULL){ next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev; } class Solution { public: //Function to add two numbers represented by linked list. struct Node* addTwoLists(struct Node* first, struct Node* second) { // code here if(first==NULL && second==NULL){ return NULL; } if(first==NULL){ return second; } if(second==NULL){ return first; } reverse(&first); reverse(&second); Node* h=NULL; Node* temp1=first; Node* temp2=second; int carry=0; while(temp1!=NULL && temp2!=NULL){ int sum = temp1->data + temp2->data + carry; if(sum>=10){ sum = sum%10; carry=1; }else{ carry=0; } insert_at_begin(sum,h); temp1=temp1->next; temp2=temp2->next; } while(temp1!=NULL){ int sum = temp1->data + carry; if(sum>=10){ sum = sum%10; carry=1; }else{ carry=0; } insert_at_begin(sum,h); temp1=temp1->next; } while(temp2!=NULL){ int sum = temp2->data + carry; if(sum>=10){ sum = sum%10; carry=1; }else{ carry=0; } insert_at_begin(sum,h); temp2=temp2->next; } if(carry){ insert_at_begin(carry,h); } return h; } };
true
a0892878beffab2c9ab5f25ce7a5d29d8924560d
C++
RobertElder/a3
/messages.cpp
UTF-8
17,384
2.984375
3
[]
no_license
#include "messages.h" #include "rpc.h" #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include <stdarg.h> struct message * recv_message(int sockfd){ /* * Caller is required to de-allocate the pointer to the message, and the message data * Returns NULL if the remote host closed the connection. */ struct message * received_message = create_message_frame(0,(enum message_type)0,0); int bytes_received; //printf("Attempting to receive message length data (%d bytes)...\n", (int)sizeof(int)); bytes_received = recv(sockfd, &(received_message->length), sizeof(int), 0); if (bytes_received <= 0) { // node on the other end terminated, return here to indicate that the connection should close destroy_message_frame(received_message); return 0; } /* Probably never going to happen, but make sure we got the whole int */ assert(bytes_received == sizeof(int)); received_message->length = ntohl(received_message->length); /* The received_message data should be a bunch of ints, otherwise how do we convert to host order? */ assert(received_message->length % sizeof(int) == 0); /* Allocate space for the rest of the received_message */ received_message->data = (int *) malloc(received_message->length); //printf("Attempting to receive message type data (%d bytes)...\n", (int)sizeof(int)); bytes_received = recv(sockfd, &(received_message->type), sizeof(int), 0); if (bytes_received <= 0) { // node on the other end terminated, return here to indicate that the connection should close destroy_message_frame(received_message); return 0; } if (bytes_received == -1) perror("Error in recv_message getting type."); assert(bytes_received != 0 && "Connection was closed by remote host."); /* Probably never going to happen, but make sure we got the whole int */ assert(bytes_received == sizeof(int)); received_message->type = (enum message_type)ntohl(received_message->type); if(received_message->length > 0){ bytes_received = recv(sockfd, received_message->data, received_message->length, 0); if (bytes_received <= 0) { // node on the other end terminated, return here to indicate that the connection should close destroy_message_frame(received_message); return 0; } if (bytes_received != received_message->length) { destroy_message_frame(received_message); return 0; } u_int i; for (i = 0; i < received_message->length % sizeof(int); i++) { received_message->data[i] = ntohl(received_message->data[i]); } } return received_message; } // returns -1 if there is any problem sending the message // returns 0 if the message is sent successfuly int send_message(int sockfd, struct message * message_to_send){ int message_length = htonl(message_to_send->length); int message_type = htonl(message_to_send->type); int bytes_sent; //printf("Attempting to send message length data (%d bytes), value is %d...\n", (int)sizeof(int), message_to_send->length); if ((bytes_sent = send(sockfd, &message_length, sizeof(int), 0)) == -1) { perror("Error in send_message sending length.\n"); return -1; } assert(bytes_sent == sizeof(int)); //printf("Attempting to send message type data (%d bytes), value is %d...\n", (int)sizeof(int), message_to_send->type); if ((bytes_sent = send(sockfd, &message_type, sizeof(int), 0)) == -1) { perror("Error in send_message sending type.\n"); return -1; } assert(bytes_sent == sizeof(int)); /* The received_message data should be a bunch of ints, otherwise how do we convert to host order? */ assert(message_to_send->length % sizeof(int) == 0); u_int i; for (i = 0; i < message_to_send->length % sizeof(int); i++) { message_to_send->data[i] = htonl(message_to_send->data[i]); } if (message_to_send->length > 0){ //printf("Attempting to send %d bytes of data...\n", message_to_send->length); fflush(stdout); if((bytes_sent = send(sockfd, message_to_send->data, message_to_send->length, 0)) == -1){ perror("Error in send_message sending data.\n"); return -1; } assert(bytes_sent == message_to_send->length); } return 0; } struct message * create_message_frame(int len, enum message_type type, int * d){ struct message * m = (struct message*)malloc(sizeof(struct message)); m->length = len; m->type = type; m->data = (int *)d; return m; } void destroy_message_frame(struct message * m){ free(m); } void destroy_message_frame_and_data(struct message * m){ if(m->data){ free(m->data); } destroy_message_frame(m); } struct message_and_fd multiplexed_recv_message(int * max_fd, fd_set * client_fds, fd_set * listener_fds){ /* max_fd is a pointer to an int that describes the max value of an fd in client_fds */ /* client_fds is the set of all fds that we want to monitor. This includes listeners and clients */ /* listener_fds is the set of all fds that are waiting for new incomming connections */ /* This method will return the first message it gets from any client */ struct sockaddr_storage remoteaddr; fd_set updated_fds; FD_ZERO(&updated_fds); while(1){ updated_fds = *client_fds; if (select((*max_fd)+1, &updated_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } int i; for(i = 0; i <= *max_fd; i++) { /* If we can read from it and it is a listener that accepts new connections */ if (FD_ISSET(i, &updated_fds) && FD_ISSET(i, listener_fds) ) { //printf("Accepting incomming connection.\n"); socklen_t addrlen = sizeof remoteaddr; int newfd = accept(i, (struct sockaddr *)&remoteaddr, &addrlen); if (newfd == -1) { perror("accept"); } else { FD_SET(newfd, client_fds); if (newfd > *max_fd) { *max_fd = newfd; } } /* Data from an already open connection */ }else if (FD_ISSET(i, &updated_fds)){ //printf("Accepting incomming data.\n"); struct message_and_fd rtn; rtn.fd = i; rtn.message = recv_message(i); if (rtn.message){ return rtn; } else { // the node on the other end of this socket terminated or went down close(i); FD_CLR(i, client_fds); // inform caller of the termination in case clean up is necessary return rtn; } } } } } void print_with_flush(const char * context, const char * message, ...){ va_list va; va_start(va, message); printf("%s: ", context); vprintf( (const char *)message, va ); fflush(stdout); va_end(va); } char * get_fully_qualified_hostname(){ /* Caller is responsible for freeing memory returned */ int buflen = HOSTNAME_BUFFER_LENGTH; char * buffer = (char*)malloc(buflen); memset(buffer,0,HOSTNAME_BUFFER_LENGTH); struct hostent *hp; gethostname(buffer, buflen-1); hp = gethostbyname(buffer); sprintf(buffer, "%s", hp->h_name); return buffer; } int get_port_from_addrinfo(struct addrinfo * a){ assert(a && a->ai_addr); return ntohs(((struct sockaddr_in*)a->ai_addr)->sin_port); } void serialize_function_prototype(struct function_prototype f, int * buffer){ /* Flattens a function prototype struct (that includes a pointer) into a variable-length buffer */ memcpy(buffer, &f.name, FUNCTION_NAME_LENGTH); memcpy(&buffer[FUNCTION_NAME_LENGTH / sizeof(int)], &f.arg_len, sizeof(int)); memcpy(&buffer[FUNCTION_NAME_LENGTH / sizeof(int) + 1], f.arg_data, sizeof(int) * f.arg_len); } struct function_prototype deserialize_function_prototype(int * buffer){ struct function_prototype f; memcpy(&f.name, buffer, FUNCTION_NAME_LENGTH); memcpy(&f.arg_len, &buffer[FUNCTION_NAME_LENGTH/sizeof(int)], sizeof(int)); f.arg_data = (int*)malloc(sizeof(int) * f.arg_len); memcpy(f.arg_data, &buffer[FUNCTION_NAME_LENGTH/sizeof(int) + 1], sizeof(int) * f.arg_len); return f; } struct function_prototype create_function_prototype(char * name, int * argTypes){ struct function_prototype f; int name_len = strlen(name); assert(name_len < FUNCTION_NAME_LENGTH); int i = 0; while(argTypes[i]){ i++; } f.arg_len = i; f.arg_data = (int*)malloc(sizeof(int) * f.arg_len); memset(&f.name, 0, FUNCTION_NAME_LENGTH); memcpy(&f.name, name, name_len); memcpy(f.arg_data, argTypes, sizeof(int) * f.arg_len); return f; } void print_function_prototype(char * c, struct function_prototype f){ print_with_flush(c, "-- Begin Function Prorotype --\n"); print_with_flush(c, "name: %s\n",f.name); print_with_flush(c, "arg_len: %d\n",f.arg_len); for(int i = 0; i < f.arg_len; i++){ print_with_flush(c, "argType %d: %X\n",i, f.arg_data[i]); } print_with_flush(c, "-- End Function Prorotype -- \n"); } void print_one_args_array_size(char * context, int index, int data, void *p){ int num_units = 0xFFFF & data; int is_array = 1; if(num_units == 0){ num_units = 1; is_array = 0; } int data_type = ((0xFF << 16) & data) >> 16; if(is_array){ print_with_flush(context, "%d) Array = {", index); }else{ print_with_flush(context, "%d) Scalar: ", index); } switch(data_type){ case ARG_CHAR:{ for(int i = 0; i < num_units; i++){ printf("%c", ((char *)p)[i]); if(i != (num_units-1) ) printf(", "); } break; }case ARG_SHORT:{ for(int i = 0; i < num_units; i++){ printf("%d", ((short *)p)[i]); if(i != (num_units-1) ) printf(", "); } break; }case ARG_INT:{ for(int i = 0; i < num_units; i++){ printf("%d", ((int*)p)[i]); if(i != (num_units-1) ) printf(", "); } break; }case ARG_LONG:{ for(int i = 0; i < num_units; i++){ printf("%ld", ((long int*)p)[i]); if(i != (num_units-1) ) printf(", "); } break; }case ARG_DOUBLE:{ for(int i = 0; i < num_units; i++){ printf("%f", ((double*)p)[i]); if(i != (num_units-1) ) printf(", "); } break; }case ARG_FLOAT:{ for(int i = 0; i < num_units; i++){ printf("%f", ((float *)p)[i]); if(i != (num_units-1) ) printf(", "); } break; }default:{ assert(0); } } if(is_array){ printf("}\n"); }else{ printf("\n"); } } int get_one_args_array_size(int data){ /* Based on the data for one argument, how many bytes is the entire array for that arg? */ /* Mask out the data type and shift it back down to the first byte */ int data_type = ((0xFF << 16) & data) >> 16; int unit_length; switch(data_type){ case ARG_CHAR:{ unit_length = sizeof(char); break; }case ARG_SHORT:{ unit_length = sizeof(short); break; }case ARG_INT:{ unit_length = sizeof(int); break; }case ARG_LONG:{ unit_length = sizeof(long); break; }case ARG_DOUBLE:{ unit_length = sizeof(double); break; }case ARG_FLOAT:{ unit_length = sizeof(float); break; }default:{ assert(0); } } /* Mask off last two bytes */ int num_units = 0xFFFF & data; if(num_units == 0){ /* This is a special case, because 0 means scalar, which is the same as an array of one unit in terms of size. */ num_units = 1; } return num_units * unit_length; } int get_args_buffer_size(struct function_prototype f){ /* For now, just serialize both input and output arguments. We can have a flag to do one or the other later */ int bytes_needed = 0; for(int i = 0; i < f.arg_len; i++){ bytes_needed += get_one_args_array_size(f.arg_data[i]); } if(bytes_needed % sizeof(int) != 0){ /* Force 4-bytes alignment */ return ((bytes_needed / sizeof(int)) * sizeof(int)) + sizeof(int); }else{ return bytes_needed; } } int get_num_args_inputs(struct function_prototype f){ /* Returns the total number of input fields in the arg type array */ int num = 0; for(int i = 0; i < f.arg_len; i++){ if(f.arg_data[i] & (1 << ARG_INPUT)){ num++; } } return num; } int get_num_args_outputs(struct function_prototype f){ /* Returns the total number of output fields in the arg type array */ int num = 0; for(int i = 0; i < f.arg_len; i++){ if(f.arg_data[i] & (1 << ARG_OUTPUT)){ num++; } } return num; } void * get_nth_args_array(struct function_prototype f, void ** args, int n, int data_direction){ int num = 0; for(int i = 0; i < f.arg_len; i++){ if(f.arg_data[i] & (1 << data_direction)){ if(num == n){ return args[i]; } num++; } } assert(0 && "nth thing not found"); return 0; } void print_args(char * context, struct function_prototype f, void ** args){ print_with_flush(context, "^^^^^^^^ BEGIN args ^^^^^^\n"); for(int i = 0; i < f.arg_len; i++){ print_one_args_array_size(context, i, f.arg_data[i], ((void**)args)[i]); } print_with_flush(context, "vvvvvvvv END args vvvvvvvv\n"); } int * serialize_args(struct function_prototype f, void ** args){ /* Will return a buffer that contains both the input and output arguments pointed to by args */ int size = get_args_buffer_size(f); char * buffer = (char*)malloc(size); memset(buffer, 0, size); int offset = 0; for(int i = 0; i < f.arg_len; i++){ memcpy(&buffer[offset], ((void**)args)[i], get_one_args_array_size(f.arg_data[i])); offset += get_one_args_array_size(f.arg_data[i]); } return (int*)buffer; } void deserialize_args(struct function_prototype f, char * serialized_args, void ** deserialized_args, int output_or_input){ /* De-serialize a serialized args array into a pre-allocated array with the correct array lengths (like that found in an rpcCall) */ int offset = 0; for(int i = 0; i < f.arg_len; i++){ /* Only do the copy on the input/out arguments or both if indicated */ if(f.arg_data[i] & output_or_input){ memcpy( ((void**)deserialized_args)[i], &serialized_args[offset], get_one_args_array_size(f.arg_data[i])); } offset += get_one_args_array_size(f.arg_data[i]); } } void ** create_empty_args_array(struct function_prototype f){ /* allocate an empty args array that looks just like the args in rpcCall */ void ** args = (void **)malloc(f.arg_len * sizeof(void *)); for(int i = 0; i < f.arg_len; i++){ args[i] = malloc(get_one_args_array_size(f.arg_data[i])); memset(args[i], 0, get_one_args_array_size(f.arg_data[i])); } return args; } void destroy_args_array(struct function_prototype f, void ** args){ for(int i = 0; i < f.arg_len; i++){ free(args[i]); } free(args); } // returns 0 if the two argTypes are the same // returns -1 if the two argTypes are different int argtypescmp(int * arg_types1, int * arg_types2, int len) { int i; for (i = 0; i < len; i++) { int arg1 = arg_types1[i]; int arg2 = arg_types2[i]; // parse the arg into type portion (first 2 bytes) and length (second 2 bytes) int type1 = 0xffff0000 & arg1; int len1 = 0x0000ffff & arg1; int type2 = 0xffff0000 & arg2; int len2 = 0x0000ffff & arg2; // compare that they are both arrays or both scalars if (!((len1 == 0 && len2 == 0) || (len1 > 0 && len2 > 0))) return -1; // compare the type portion if (type1 != type2) return -1; } return 0; } // returns 0 if the same; returns -1 if different int compare_functions(struct function_prototype f1, struct function_prototype f2) { if (strcmp(f1.name, f2.name) != 0) return -1; if (f1.arg_len != f2.arg_len) return -1; if (argtypescmp(f1.arg_data, f2.arg_data, f1.arg_len) != 0) return -1; return 0; }
true
b2e47dc57c9a3c50dfc845c74470c7486ddde1d0
C++
chunlinsun/peercode
/hw3/Graph_438.hpp
UTF-8
26,866
3.578125
4
[]
no_license
#ifndef CME212_GRAPH_HPP #define CME212_GRAPH_HPP /** @file Graph.hpp * @brief An undirected graph type */ #include <algorithm> #include <vector> #include <cassert> #include "CME212/Util.hpp" #include "CME212/Point.hpp" /** @class Graph * @brief A template for 3D undirected graphs. * * Users can add and retrieve nodes and edges. Edges are unique (there is at * most one edge between any pair of distinct nodes). */ template <typename V, typename E> class Graph { private: struct Internal_node; struct Internal_edge; public: // // PUBLIC TYPE DEFINITIONS // /** Type of this graph. */ using graph_type = Graph; /** Predeclaration of Node type. */ class Node; /** Synonym for Node (following STL conventions). */ using node_type = Node; /** An optional value to our nodes */ using node_value_type = V; /** An optional value to our edges */ using edge_value_type = E; /** Predeclaration of Edge type. */ class Edge; /** Synonym for Edge (following STL conventions). */ using edge_type = Edge; /** Type of node iterators, which iterate over all graph nodes. */ class NodeIterator; /** Synonym for NodeIterator */ using node_iterator = NodeIterator; /** Type of edge iterators, which iterate over all graph edges. */ class EdgeIterator; /** Synonym for EdgeIterator */ using edge_iterator = EdgeIterator; /** Type of incident iterators, which iterate incident edges to a node. */ class IncidentIterator; /** Synonym for IncidentIterator */ using incident_iterator = IncidentIterator; /** Type of indexes and sizes. Return type of Graph::Node::index(), Graph::num_nodes(), Graph::num_edges(), and argument type of Graph::node(size_type) */ using size_type = unsigned; // // CONSTRUCTORS AND DESTRUCTOR // /** Construct an empty graph. */ Graph() { } /** Default destructor */ ~Graph() = default; // // NODES // /** @class Graph::Node * @brief Class representing the graph's nodes. * * Node objects are used to access information about the Graph's nodes. */ class Node: private totally_ordered<Node>{ public: /** @brief Construct an invalid node. * * Valid nodes are obtained from the Graph class, but it * is occasionally useful to declare an @i invalid node, and assign a * valid node to it later. For example: * * @code * Graph::node_type x; * if (...should pick the first node...) * x = graph.node(0); * else * x = some other node using a complicated calculation * do_something(x); * @endcode */ Node() { //Nothing to do, we just create a void node. } /** @brief Return this node's position. @pre This node is valid and is an element of the graph*/ Point& position() { return graph_->nodes_vector[uid_].pos; } /** @brief Return this node's position. @pre This node is valid and is an element of the graph*/ const Point& position() const { return graph_->nodes_vector[uid_].pos; } /** @brief Return this node's value as a reference. @pre This node is valid and is an element of the graph*/ node_value_type& value(){ return graph_->nodes_vector[uid_].val ; } /** @brief Return this node's value as a constant. @pre This node is valid and is an element of the graph*/ const node_value_type& value() const { return graph_->nodes_vector[uid_].val ; } /** @bried Return this node's index, a number in the range [0, graph_size). @pre This node is valid*/ size_type index() const { return uid_; } /** @brief return the number of incident edges @pre This node is valid*/ size_type degree() const { return graph_-> adjacency_list[uid_].size(); } /** @brief Return the start of the incident iterator */ incident_iterator edge_begin() const{ return IncidentIterator(graph_, uid_, 0); } /** @brief Return the end of incident iterator */ incident_iterator edge_end() const{ return IncidentIterator(graph_, uid_, degree()); } /** Test whether this node and @a n are equal. * * Equal nodes have the same graph and the same index. */ bool operator==(const Node& n) const { if ((n.uid_ == uid_) and (n.graph_ == graph_)){return true;} return false; } /** Test whether this node is less than @a n in a global order. * * This ordering function is useful for STL containers such as * std::map<>. It need not have any geometric meaning. * * The node ordering relation must obey trichotomy: For any two nodes x * and y, exactly one of x == y, x < y, and y < x is true. */ bool operator<(const Node& n) const { if (n.uid_ < uid_){return true;} return false; } private: // Allow Graph to access Node's private member data and functions. friend class Graph; // Use this space to declare private data members and methods for Node // that will not be visible to users, but may be useful within Graph. // i.e. Graph needs a way to construct valid Node objects // Pointer back to the graph the node lies in Graph* graph_; // This node's current index number // Like in the example proxy class given, our proxy node is defined with a // unique id size_type uid_; /** Private Constructor */ Node(const Graph* graph, size_type uid) : graph_(const_cast<Graph*>(graph)), uid_(uid) { } }; /** Return the number of nodes in the graph. * * Complexity: O(1). */ size_type size() const { return this->nodes_vector.size(); } /** Synonym for size(). */ size_type num_nodes() const { return size(); } /** @brief Add a node to the graph, returning the added node. * @param[in] position The new node's position * @post new num_nodes() == old num_nodes() + 1 * @post result_node.index() == old num_nodes() * * Complexity: O(1) amortized operations. */ Node add_node(const Point& position, const node_value_type& val = node_value_type()) { size_type new_id = nodes_vector.size(); nodes_vector.push_back(Internal_node(new_id,position,val)); adjacency_list.push_back(std::vector<std::pair<size_type,size_type>>()); edge_value_list.push_back(std::vector<edge_value_type>()); return Node(this, new_id); } /** @brief Determine if a Node belongs to this Graph * @return True if @a n is currently a Node of this Graph * * Complexity: O(1). */ bool has_node(const Node& n) const { //We want to check that the node lies in this graph return (n.graph_ == this); } /** Return the node with index @a i. * @pre 0 <= @a i < num_nodes() * @post result_node.index() == i * * Complexity: O(1). */ Node node(size_type i) const { return Node(this, i); } // // EDGES // /** @class Graph::Edge * @brief Class representing the graph's edges. * * Edges are order-insensitive pairs of nodes. Two Edges with the same nodes * are considered equal if they connect the same nodes, in either order. */ class Edge: private totally_ordered<Edge>{ public: /** Construct an invalid Edge. */ Edge() { //The edge is void so there is nothing to do } /** @brief Return the value of this Edge @pre The edge is in the graph and is valid */ edge_value_type& value(){ std::vector<std::pair<size_type,size_type>> neighbours = graph_ -> adjacency_list[nuid1_]; //Then we go through our list of neighbours; size_type i = 0; while(neighbours[i].first != nuid2_) i++; return graph_ -> edge_value_list[nuid1_][i]; } /** @brief Return the value of this Edge @pre The edge is in the graph and is valid */ const edge_value_type& value() const{ std::vector<std::pair<size_type,size_type>> neighbours = graph_ -> adjacency_list[nuid1_]; //Then we go through our list of neighbours; size_type i = 0; while(neighbours[i].first != nuid2_) i++; return graph_ -> edge_value_list[nuid1_][i]; } /** @brief Return a node of this Edge */ Node node1() const { return Node(graph_, nuid1_); } /** @brief Return the other node of this Edge */ Node node2() const { return Node(graph_, nuid2_); } /** @brief Test whether this edge and @a e are equal. * * Equal edges represent the same undirected edge between two nodes. * Complexity: O(1) */ bool operator==(const Edge& e) const { if ((e.nuid1_ == nuid1_) and(e.nuid2_ == nuid2_) and(e.graph_ == graph_)){return true;} if ((e.nuid2_ == nuid1_) and(e.nuid1_ == nuid2_) and(e.graph_ == graph_)){return true;} return false; } /** @brief Test whether this edge is less than @a e in a global order. * * This ordering function is useful for STL containers such as * std::map<>. It need not have any interpretive meaning. * Complexity: O(1) */ bool operator<(const Edge& e) const { if (e.graph_ == graph_){ if (e.nuid1_ == nuid1_){ return (e.nuid2_ < nuid2_); } else { return (e.nuid1_ < nuid1_); } } else { return (e.graph_ < graph_); } return (e.graph_ < graph_); } private: // Allow Graph to access Edge's private member data and functions. friend class Graph; //Pointer to the overall graph. Once again edge acts as a proxy. Graph* graph_ ; //The id of the adjacent nodes. size_type nuid1_; size_type nuid2_; // A private constructor for Edge class. Edge(const Graph* edge_graph, size_type n1, size_type n2) : graph_(const_cast<Graph*>(edge_graph)), nuid1_(n1), nuid2_(n2){ } }; /** Return the total number of edges in the graph. * * Complexity: O(1) */ size_type num_edges() const { return this -> edges_vector.size(); } /** Return the edge with index @a i. * @pre 0 <= @a i < num_edges() * * Complexity: O(1) */ Edge edge(size_type i) const { assert(i<edges_vector.size()); Internal_edge edge = edges_vector[i]; return Edge(this, edge.nuid1, edge.nuid2); } /** Test whether two nodes are connected by an edge. * @pre @a a and @a b are valid nodes of this graph * @return True if for some @a i, edge(@a i) connects @a a and @a b. * * Complexity: O(max_degree) */ bool has_edge(const Node& a, const Node& b) const { // We check that our nodes are in the graph: if ((has_node(a)) and (has_node(b))) { std::vector<std::pair<size_type,size_type>> a_neighbours = adjacency_list[a.uid_]; //Then we go through our list of neighbours; for(size_type i = 0; i < a_neighbours.size(); i++) { if (a_neighbours[i].first == b.uid_){return true;} } return false; } else{ return false; } } /** Add an edge to the graph, or return the current edge if it already exists. * @pre @a a and @a b are distinct valid nodes of this graph * @return an Edge object e with e.node1() == @a a and e.node2() == @a b * @post has_edge(@a a, @a b) == true * @post If old has_edge(@a a, @a b), new num_edges() == old num_edges(). * Else, new num_edges() == old num_edges() + 1. * * Can invalidate edge indexes -- in other words, old edge(@a i) might not * equal new edge(@a i). Must not invalidate outstanding Edge objects. * * Complexity: O(max_degree) */ Edge add_edge(const Node& a, const Node& b, const edge_value_type& val = edge_value_type()) { //If the edge already exist we return it if (has_edge(a,b)){ //Here we have a complexity of O(max_degree) return Edge(this, a.uid_, b.uid_); } size_type index = edges_vector.size(); //Otherwise we add it in the adjacency list std::pair<size_type, size_type> pairb(b.uid_, index); adjacency_list[a.uid_].push_back(pairb); edge_value_list[a.uid_].push_back(val); std::pair<size_type, size_type> paira(a.uid_, index); adjacency_list[b.uid_].push_back(paira); edge_value_list[b.uid_].push_back(val); //Then we add our edge in our vector of edges edges_vector.push_back(Internal_edge(a.uid_, b.uid_)); return Edge(this, a.uid_, b.uid_); } /** Remove all nodes and edges from this graph. * @post num_nodes() == 0 && num_edges() == 0 * * Invalidates all outstanding Node and Edge objects. */ void clear() { nodes_vector.clear() ; edges_vector.clear(); adjacency_list.clear(); edge_value_list.clear(); } // // Node Iterator // /** @class Graph::NodeIterator * @brief Iterator class for nodes. A forward iterator. */ class NodeIterator: private totally_ordered<NodeIterator>{ public: // These type definitions let us use STL's iterator_traits. using value_type = Node; // Element type using pointer = Node*; // Pointers to elements using reference = Node&; // Reference to elements using difference_type = std::ptrdiff_t; // Signed difference using iterator_category = std::input_iterator_tag; // Weak Category, Proxy /** Construct an invalid NodeIterator. */ NodeIterator() { } /** @brief Dereference the current node and return it **/ Node operator*() const{ return Node(graph_, uid_); } /** @brief Increment the iterator **/ NodeIterator& operator++(){ uid_++; return *this; } /** @brief Test the equality between 2 iterators **/ bool operator==(const NodeIterator& n) const{ return ((graph_ == n.graph_) and (uid_ == n.uid_)); } private: friend class Graph; //The graph the iterator lies in Graph* graph_; //The id of the current nodes it points to size_type uid_; /** @brief Basic constructor of the iterator **/ NodeIterator(const Graph* g, size_type u) :graph_(const_cast<Graph*>(g)), uid_(u){} }; /** @brief Return an iterator pointing at the beginning of our node_vector **/ node_iterator node_begin() const{ return NodeIterator(this, 0); } /** @brief Return an iterator pointing at the end of our node_vector **/ node_iterator node_end() const{ return NodeIterator(this, nodes_vector.size()); } // // Incident Iterator // /** @class Graph::IncidentIterator * @brief Iterator class for edges incident to a node. A forward iterator. */ class IncidentIterator: private totally_ordered<IncidentIterator> { public: // These type definitions let us use STL's iterator_traits. using value_type = Edge; // Element type using pointer = Edge*; // Pointers to elements using reference = Edge&; // Reference to elements using difference_type = std::ptrdiff_t; // Signed difference using iterator_category = std::input_iterator_tag; // Weak Category, Proxy /** Construct an invalid IncidentIterator. */ IncidentIterator() { } /** @brief Dereference the current edge and return it **/ Edge operator*() const{ size_type nuid2 = graph_ -> adjacency_list[nuid1_][uid_].first; return Edge(graph_, nuid1_, nuid2); } /** @brief Increment the iterator **/ IncidentIterator& operator++(){ uid_++; return *this; } /** @brief Test the equality between 2 iterators **/ bool operator==(const IncidentIterator& n) const{ return ((graph_ == n.graph_) and (nuid1_ == n.nuid1_) and (uid_ == n.uid_)); } private: friend class Graph; Graph* graph_; //The graph the iterator lies in size_type nuid1_; //The node this iterator is based on size_type uid_; //The current position in the adjacency list /** @brief Basic constructor of the iterator **/ IncidentIterator(const Graph* g, size_type nuid1, size_type u) :graph_(const_cast<Graph*>(g)), nuid1_(nuid1), uid_(u){} }; // // Edge Iterator // /** @class Graph::EdgeIterator * @brief Iterator class for edges. A forward iterator. */ class EdgeIterator: private totally_ordered<EdgeIterator> { public: // These type definitions let us use STL's iterator_traits. using value_type = Edge; // Element type using pointer = Edge*; // Pointers to elements using reference = Edge&; // Reference to elements using difference_type = std::ptrdiff_t; // Signed difference using iterator_category = std::input_iterator_tag; // Weak Category, Proxy /** Construct an invalid EdgeIterator. */ EdgeIterator() { } /** @brief Dereference the current node and return it **/ Edge operator*() const{ size_type nuid1 = graph_->edges_vector[uid_].nuid1; size_type nuid2 = graph_->edges_vector[uid_].nuid2; return Edge(graph_, nuid1, nuid2); } /** @brief Increment the iterator **/ EdgeIterator& operator++(){ uid_++; return *this; } /** @brief Test the equality between 2 iterators **/ bool operator==(const EdgeIterator& n) const{ return ((graph_ == n.graph_) and (uid_ == n.uid_)); } private: friend class Graph; Graph* graph_; //The graph the iterator lies in size_type uid_; //Our position in the vector of edges /** @brief Basic constructor of the iterator **/ EdgeIterator(const Graph* g, size_type u) :graph_(const_cast<Graph*>(g)), uid_(u){} }; /** @brief Return an iterator pointing at the beginning of our edge_vector **/ edge_iterator edge_begin() const{ return EdgeIterator(this, 0); } /** @brief Return an iterator pointing at the end of our edge_vector **/ edge_iterator edge_end() const{ return EdgeIterator(this, edges_vector.size()); } /** @brief Remove the edge * @return a boolean stating if the edge was removed * @post has_edge(e.node1(),e.node2()) = false; * @post if the edge was in the graph, it has been removed * * This method invalidates all iterators concerning the incident * of the nodes adjacent to this edge * * Furhtermore, it moves adjacency_list[e.nuid1][adjacency_list[e.nuid1].size()-1] * and adjacency_list[e.nuid2][adjacency_list[e.nuid2].size()-1], so anything related to * those edges is now invalidate * * Complexity : O(degree) */ size_type remove_edge(const Edge &e){ if(!has_edge(e.node1(), e.node2())) return false; size_type n1 =e.node1().index(); size_type n2 =e.node2().index(); //We clean edges_vector. Complexity : O(degree) //Search for this edge in the adjacency list for(size_type i=0; i<adjacency_list[n1].size(); i++){ if (adjacency_list[n1][i].first==n2){ //Find its index in edge_vector size_type index = adjacency_list[n1][i].second; //Send it at the back of edge_vector edges_vector[index] = edges_vector[edges_vector.size()-1]; //One edge has been moved, so we need some updates //We update the index in the adjacency list size_type n1_to_update = edges_vector[index].nuid1; size_type n2_to_update = edges_vector[index].nuid2; //Search it in the adjacency list of n1_to_update for(size_type j=0; j<adjacency_list[n1_to_update].size(); j++){ if (adjacency_list[n1_to_update][j].first==n2_to_update){ //Update the index adjacency_list[n1_to_update][j].second = index; } } //Search it in the adjacency list of n2_to_update for(size_type j=0; j<adjacency_list[n2_to_update].size(); j++){ if (adjacency_list[n2_to_update][j].first==n1_to_update){ //Update the index adjacency_list[n2_to_update][j].second = index; } } //Finally remove the edge edges_vector.pop_back(); } } //We clean adjacency_list and edge_value_list. Complexity: O(degree) //Search for the edge in the adjacency list of n1 for(size_type i=0; i<adjacency_list[n1].size(); i++){ if (adjacency_list[n1][i].first==n2){ //By swapping 2 edges we invalidate the one at the back adjacency_list[n1][i] = adjacency_list[n1][adjacency_list[n1].size()-1]; adjacency_list[n1].pop_back(); edge_value_list[n1][i] = edge_value_list[n1][edge_value_list[n1].size()-1]; edge_value_list[n1].pop_back(); } } //Search for the edge in the adjacency list of n1 for(size_type i=0; i<adjacency_list[n2].size(); i++){ if (adjacency_list[n2][i].first==n1){ //By swapping 2 edges we invalidate the one at the back adjacency_list[n2][i] = adjacency_list[n2][adjacency_list[n2].size()-1]; adjacency_list[n2].pop_back(); edge_value_list[n2][i] = edge_value_list[n2][edge_value_list[n2].size()-1]; edge_value_list[n2].pop_back(); } } return !(has_edge(e.node1(),e.node2())); } /** @brief Remove the edge * @return a boolean stating if the edge was removed * @post has_edge(e.node1(),e.node2()) = false; * @post if the edge was in the graph, it has been removed * * This method invalidates all iterators concerning the incident * of the nodes adjacent to this edge * * Furhtermore, it moves adjacency_list[n1.uid][adjacency_list[n1.uid].size()-1] * and adjacency_list[n2.uid][adjacency_list[n2.uid].size()-1], so anything related to * those edges is now invalidate * * Complexity : O(degree) */ size_type remove_edge(const Node &n1, const Node &n2){ return remove_edge(Edge{this, n1.index(), n2.index()}); } /** @brief Remove the edge * @return a valid iterator * @post has_edge(e.node1(),e.node2()) = false; * @post if the edge was in the graph, it has been removed * * This method invalidates all iterators concerning the incident * of the nodes adjacent to this edge * * Furhtermore, it moves adjacency_list[(*e_it).nuid1][adjacency_list[(*e_it).nuid1].size()-1] * and adjacency_list[(*e_it).nuid2][adjacency_list[(*e_it).nuid2].size()-1], so anything related to * those edges is now invalidate * * Complexity : O(degree) */ edge_iterator remove_edge(edge_iterator e_it){ remove_edge((*e_it)); return e_it; } /** @brief Remove the node, and all edges incident to it. * @return a boolean stating if the node was removed * @post if the node was in the graph it has been removed * @post all edges incident to the node have been removed * Invalidate: The node with index num_nodes-1 now have index * n.index() * So any edge or iterator related to the removed node * or to the node that has its index changed is now invalid * * Complexity: O(degree^2) */ size_type remove_node(const Node &n){ if (!has_node(n)){ return false; } size_type uid = n.index(); size_type size = num_nodes(); //Clean node_vector nodes_vector[uid] = nodes_vector[size-1]; nodes_vector.pop_back(); //First we have to erase the incident edges. //Complexity O(degree^2) size_type deg = n.degree(); std::vector<size_type> neighbour_vect; for(size_type i=0; i < deg; i++){ neighbour_vect.push_back(adjacency_list[uid][i].first); } for(auto it = neighbour_vect.begin(); it != neighbour_vect.end(); ++it){ remove_edge(Edge(this, uid, *it)); } //Now clean this node adjacency list adjacency_list[uid] = adjacency_list[size-1]; adjacency_list.pop_back(); edge_value_list[uid] = edge_value_list[size-1]; edge_value_list.pop_back(); //Now, we have to update all the node of edges concerning the node //that has been moved to the index uid, if it occurs (if uid != size-1) if (uid != size-1){ for(size_type i = 0; i < adjacency_list[uid].size(); i++){ size_type neighbour = adjacency_list[uid][i].first; //Search it in the adjacency list of its neighbour for(size_type j = 0; j < adjacency_list[neighbour].size(); j++){ if(adjacency_list[neighbour][j].first == (size-1)){ adjacency_list[neighbour][j].first = uid; //Update it also in edges_vector edges_vector[adjacency_list[neighbour][j].second].nuid1 = neighbour; edges_vector[adjacency_list[neighbour][j].second].nuid2 = uid; } } } } return (!has_node(n)); } /** @brief Remove the node, and all edges incident to it. * @return a boolean stating if the node was removed * @post if the node was in the graph it has been removed * @post all edges incident to the node have been removed * Invalidate: The node with index num_nodes-1 now have index * n.index() * So any edge or iterator related to the removed node * or to the node that has its index changed is now invalid * * Complexity: O(max_degree^2) */ node_iterator remove_node(node_iterator n_it){ remove_node((*n_it)); return n_it; } private: // Use this space for your Graph class's internals: // helper functions, data members, and so forth. //STL containers. I use vectors to store the data and a mapping to associate ids //with positon in those vectors std::vector <Internal_node> nodes_vector; std::vector <Internal_edge> edges_vector; //Adjacency list of our graph. Every point is a pair <neighbour, index in edge_vector> std::vector <std::vector <std::pair<size_type,size_type>>> adjacency_list; //List where we store our edge values. std::vector <std::vector <edge_value_type>> edge_value_list; // Disable copy and assignment of a graph Graph(const Graph&) = delete; Graph& operator=(const Graph&) = delete; /** @brief A struct to represent our node */ struct Internal_node { //The id defining the node size_type uid; //The id of the node Point pos; //The position of our node node_value_type val ; //The value stored in our node /** @brief basic constructor */ Internal_node(size_type uid,Point pos, node_value_type val) :uid(uid),pos(pos), val(val){} }; /** @brief A struct to represent our edges */ struct Internal_edge { size_type nuid1; //The id of an adjacent node size_type nuid2; //The id of an adjacent node /** @brief basic constructor */ Internal_edge(size_type nuid1, size_type nuid2) :nuid1(nuid1),nuid2(nuid2) {} }; }; #endif // CME212_GRAPH_HPP
true
813df18306743039d8390c6a1421fe199fb77eef
C++
Esseh/AetherSoundLibrary
/sound.h
UTF-8
3,784
2.84375
3
[]
no_license
#include<queue> #include<iostream> #include<SFML/Audio.hpp> namespace aether { /// An object that takes certain specifications and fires off a sound effect immediately upon construction. class sound { private: /// Controls the current volume of existing sound effects. static float volume; /// A container holding constructed sound effects. static std::queue<aether::sound*> loadedSounds; /// A function called by the sound effect constructor which activates the sound effect GC heuristic. static void flush(); /// The descriptor/buffer pair for the sound effect file: Credit- SFML sf::Sound* soundDescriptor; sf::SoundBuffer* soundBuffer; /// The constructor for a sound effect object. /// Once constructed it fires off immediately with the specified behaviors. /// NOTE: Spatialization only works for mono tracks sound( std::string fileName, /// The file name for the sound file. float maxV = 100, /// The max volume allowable for the sound file. Useful in conjunction with soundDelta. float soundDelta = 0, /// A fixed volume to undershot/overshot the current volume setting. Can be used to make quieter or louder noises. float pitch = 1, /// Sets the pitch. Values below 1 lowers the pitch, values above 1 increases the pitch. bool relativeToListener = true, /// Sets if the sound occurs relative to the player. Disabling will allow it to exist in global coordinates. sf::Vector2f pos = sf::Vector2f(0,0), /// Sets the position of the sound, normally at (0,0) relative to the player to disable spatialization. float soundRadius = 1, /// If using spatialization this will affect how far a sound can be heard before attentuation takes place. float attenuation = 1 /// Sets the attenuation (sound falloff magnitude) of the sound effect as the listener moves away. ); public: ~sound(); /// Builder object to protect from (unsafe) deletion. static void play( std::string fileName, /// The file name for the sound file. float maxV = 100, /// The max volume allowable for the sound file. Useful in conjunction with soundDelta. float soundDelta = 0, /// A fixed volume to undershot/overshot the current volume setting. Can be used to make quieter or louder noises. float pitch = 1, /// Sets the pitch. Values below 1 lowers the pitch, values above 1 increases the pitch. bool relativeToListener = true, /// Sets if the sound occurs relative to the player. Disabling will allow it to exist in global coordinates. sf::Vector2f pos = sf::Vector2f(0,0), /// Sets the position of the sound, normally at (0,0) relative to the player to disable spatialization. float soundRadius = 1, /// If using spatialization this will affect how far a sound can be heard before attentuation takes place. float attenuation = 1 /// Sets the attenuation (sound falloff magnitude) of the sound effect as the listener moves away. ); /// Gets volume for sound effects: 0 >= volume >= 100 static float getVolume(); /// Sets volume for sound effects: 0 >= volume >= 100 static void setVolume(float newVolume); }; }
true
f1ddd4763c7183f3b83eb31b02b5e2aebaa6639b
C++
Ming-J/LeetCode
/966_Vowel_Spellchecker.cpp
UTF-8
1,935
3.3125
3
[]
no_license
#include <algorithm> #include <iostream> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; class Solution { public: vector<string> spellchecker(vector<string> &wordlist, vector<string> &queries) { unordered_set<string> exact; unordered_map<string, string> cap; unordered_map<string, string> vowel; vector<string> ans; for (auto word : wordlist) { if (exact.find(word) == exact.end()) exact.insert(word); string capword = capitize(word); if (cap.find(capword) == cap.end()) cap.insert(make_pair(capword, word)); string withOutVowel = noVowel(word); if (vowel.find(withOutVowel) == vowel.end()) vowel.insert(make_pair(withOutVowel, word)); } for (auto query : queries) { if (exact.find(query) != exact.end()) { ans.push_back(query); continue; } string capword = capitize(query); auto it = cap.find(capword); if (it != cap.end()) { ans.push_back(it->second); continue; } string withOutVowel = noVowel(query); it = vowel.find(withOutVowel); if (it != vowel.end()) { ans.push_back(it->second); continue; } ans.push_back(""); } return ans; } private: bool isVowel(char c) { return c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } string capitize(string word) { string capword = word; transform(word.begin(), word.end(), capword.begin(), ::toupper); return capword; } string noVowel(string word) { string withOutVowel = ""; for (char c : word) { if (isVowel(toupper(c))) withOutVowel.push_back(toupper(c)); else withOutVowel.push_back('?'); } return withOutVowel; } }; int main() { cout << "HI" << endl; }
true
b9720189e959c2e061abd13587ce240addcd4840
C++
fxmqs/leetcode
/src/1-100/Solution44.h
GB18030
2,258
3.078125
3
[]
no_license
#pragma once #include "leetcode_defs.h" class Solution44 { public: Solution44(); ~Solution44(); bool dfs(const char *s, const char *p) { if (!*s && !*p) { return true; } if (!*s) { if (*p == '*') return dfs(s, p + 1); else return false; } if (!*p) return false; if (*p == '?' || *s == *p) { return dfs(s + 1, p + 1); } if (*p == '*') { const char *n = p; while (*n == '*') ++n; if (dfs(s, n)) return true; if (dfs(s + 1, p)) return true; if (dfs(s + 1, n)) return true; } return false; } bool findAllSubStrings(string s, vector<string> &substrings) { int l = 0; for (int i = 0; i < substrings.size(); ++i) { int j = l; for (; j < s.size(); ++j) { int k = 0; for (; k < substrings[i].size(); ++k) { if (j + k == s.size()) return false; if (s[j + k] == substrings[i][k] || substrings[i][k] == '?') continue; break; } if (k == substrings[i].size()) break; } l = j + substrings[i].size(); } return l <= s.size(); } bool isMatch(string s, string p) { if (s.empty() && p.empty()) return true; if (s.empty()) { if (p.size() == 1 && p.at(0) == '*') return true; return false; } /// ж * һͱ int count = 0; for (int i = 0; i < p.size(); ++i) { if (p[i] == '*') { ++count; for (; i < p.size() && p[i] == '*'; ++i); } } if (count <= 1) return dfs(s.c_str(), p.c_str()); /// Ҽ֦ int i = 0; for (; i < p.size(); ++i) { if (p[i] == '*') { break; } if (i == s.size()) return false; if (s[i] == p[i] || p[i] == '?') continue; return false; } int r = p.size() - 1; for (; r >= 0; --r) { if (p[r] == '*') break; int rs = s.size() - p.size() + r; if (rs < 0) return false; if (p[r] == s[rs] || p[r] == '?') continue; return false; } /// üӴ int rs = s.size() - p.size() + r + 1; s = s.substr(i, rs - i); vector<string> substrings; string res = ""; for (; i < r; ++i) { if (p[i] == '*') { if (!res.empty()) { substrings.push_back(res); res = ""; } continue; } res += p[i]; } if (!res.empty()) substrings.push_back(res); return findAllSubStrings(s, substrings); } };
true
cf7946ba5bdd1794081577a0ca878941b6b88de3
C++
Fergomez0901/PED
/Guia de Ejercicios 5/G4-E3.cpp
UTF-8
1,634
4
4
[]
no_license
#include <iostream> #include <queue> using namespace std; void searchChar(queue<char> q, char carS){ bool found = false; queue<char> clone = q; while(!clone.empty()) { if(clone.front() == carS) { found = true; cout << "Se encontro el caracter. \nBorrando cola..." << endl; clone.pop(); while(!q.empty()) { q.pop(); } } else { clone.pop(); } } if(!found) { cout << "No se encontro el caracter. " << endl; } } void menu(queue<char> q){ int opcion; bool estado = true; char car, carS; while(estado) { cout << endl << "----- Menu -----" << endl; cout << "1) Ingresar un caracter a la cola" << endl; cout << "2) Buscar un caracter en la cola" << endl; cout << "3) Salir del programa" << endl; cout << endl << "Ingrese una opcion: "; cin >> opcion; switch (opcion) { case 1: cout << "Ingrese un caracter: "; cin >> car; q.push(car); break; case 2: cout << "Ingrese el caracter que desea buscar: "; cin >> carS; searchChar(q, carS); break; case 3: cout << "Fin del programa" << endl; estado = false; break; default: cout << "Opcion Invalida" << endl; break; } } } int main(){ queue<char> charQ; menu(charQ); }
true
8ea879d4ebd8ed1108539605f31fa2d14b686129
C++
shnider42/Algo-Repo
/Project1/p1b.cpp
UTF-8
8,540
3.015625
3
[]
no_license
//Project 1b: using exhaustive search to color a graph. // Code to read graph instances from a file. Uses the Boost Graph Library (BGL). #include <iostream> #include <limits.h> #include "d_except.h" #include <fstream> #include <windows.h> #include <direct.h> #include <time.h> #include <string> #include <math.h> #include <boost/graph/adjacency_list.hpp> #define LargeValue 99999999 using namespace std; using namespace boost; int const NONE = -1; // Used to represent a node that does not exist struct VertexProperties; struct EdgeProperties; typedef adjacency_list<vecS, vecS, bidirectionalS, VertexProperties, EdgeProperties> Graph; string getcwd1(); int exhaustiveColoring(Graph&, int, int); void colorGraph(Graph&, vector<int>, int); int countConflicts(Graph&); vector<int> incrementColorNumber(vector<int>, int, int); bool matchingColors(Graph& g, Graph::vertex_iterator v); //Create a struct to hold the properties of each vertex struct VertexProperties { pair<int,int> cell; // maze cell (x,y) value Graph::vertex_descriptor pred; bool visited; bool marked; int weight; int color; }; // Create a struct to hold properties for each edge struct EdgeProperties { int weight; bool visited; bool marked; }; int initializeGraph(Graph &g, ifstream &fin) // Initialize g using data from fin. { int n, e; int j,k; int numColors; fin >> numColors; fin >> n >> e; // Add nodes. for (int i = 0; i < n; i++) add_vertex(g); for (int i = 0; i < e; i++) { fin >> j >> k; add_edge(j,k,g); // Assumes vertex list is type vecS add_edge(k,j,g); } return numColors; } void setNodeWeights(Graph &g, int w) // Set all node weights to w. { pair<Graph::vertex_iterator, Graph::vertex_iterator> vItrRange = vertices(g); for (Graph::vertex_iterator vItr= vItrRange.first; vItr != vItrRange.second; ++vItr) { g[*vItr].weight = w; } } void setNodeColors(Graph &g, int w) // Set all node colors to w. { pair<Graph::vertex_iterator, Graph::vertex_iterator> vItrRange = vertices(g); for (Graph::vertex_iterator vItr= vItrRange.first; vItr != vItrRange.second; ++vItr) { g[*vItr].color = w; } } ostream &operator<<(ostream &ostr, const Graph &g) // Output operator for the Graph class. Prints out all nodes and their colors { pair<Graph::vertex_iterator, Graph::vertex_iterator> vItrRange = vertices(g); for (Graph::vertex_iterator vItr= vItrRange.first; vItr != vItrRange.second; ++vItr) { ostr << *vItr << "\t" << g[*vItr].color << endl; } return ostr; } int main() { char x; ifstream fin; string fileName; ofstream outputFile; int numColors, numConflicts; // Read the name of the graph from the keyboard or // hard code it here for testing. /*string CWD; CWD = getcwd1(); cout << CWD; cout << "\n\n"; // appending file name to load correctly fileName = CWD + "\\\color12-4.input"; cout << fileName; cin.get();*/ cout << "Enter filename" << endl; cin >> fileName; fin.open(fileName.c_str()); if (!fin) { cerr << "Cannot open " << fileName << endl; cin.get(); exit(1); } try { string outFile = fileName.substr(0, fileName.length() - 5) + "output"; outputFile.open(outFile.c_str()); cout << "Reading graph" << endl; Graph g; numColors = initializeGraph(g,fin); setNodeColors(g, 0); cout << "Num colors: " << numColors << endl; cout << "Num nodes: " << num_vertices(g) << endl; cout << "Num edges: " << num_edges(g) << endl; cout << endl; //get the fewest number of conflicts in the time allowed //note that third parameter is time to search in seconds numConflicts = exhaustiveColoring(g, numColors, 600); outputFile << "best solution had " << numConflicts << " conflicts." << endl; outputFile << g << endl; outputFile.close(); // cout << g; } catch (indexRangeError &ex) { cout << ex.what() << endl; cin.get(); exit(1); } catch (rangeError &ex) { cout << ex.what() << endl; cin.get(); exit(1); } } //get the current working directory to allow for smoother filename finding string getcwd1() { char* a_cwd = _getcwd(NULL, 0); string s_cwd(a_cwd); free(a_cwd); return s_cwd; } int exhaustiveColoring(Graph& g, int numColors, int t) //brute force search of the minimum amount of color conflicts { //code for coloring a graph vector<int> colorNumber; for (int i = 0; i < num_vertices(g); i++) { colorNumber.push_back(0); } // the final number is when all nodes are colored the "highest" colornumber //i.e. if we have 3 colors, the final vector will be made of all 2's vector<int> finalNumber; for (int i = 0; i < num_vertices(g); i++) { finalNumber.push_back(numColors - 1); } //this boolean will track when we have exhausted all possibilities of colorings //when false, there are more colorings to check bool done = false; //initialize the best number of conflicts to max and best graph to the initial, non-colored graph int bestConflicts = num_vertices(g); Graph bestGraph = g; // Get start time to be used in while loop time_t startTime; time(&startTime); while (!done) { time_t newTime; time(&newTime); //if we have reached the tim threshold if (difftime(newTime, startTime) > t) { cout << "Time limit expired" << endl;; break; } //if we have reached the last coloring, execute one more time, then stop if (colorNumber == finalNumber || 0 == bestConflicts) { done = true; } colorGraph(g, colorNumber, numColors); //if we have a better solution if (countConflicts(g) < bestConflicts) { bestConflicts = countConflicts(g); bestGraph = g; //if we have reached the best possible solution of any graph, stop now if (0 == bestConflicts) { break; } } //get the next coloring code colorNumber = incrementColorNumber(colorNumber, colorNumber.size() - 1, numColors); } g = bestGraph; return bestConflicts; } //count the number of conflicts in the graph //conflicts are found by a node having a color of 0 or if any pairs of nodes that are neighbors have the same color int countConflicts(Graph& g) { int numConflicts = 0; pair<Graph::vertex_iterator, Graph::vertex_iterator> vItrRange = vertices(g); for (Graph::vertex_iterator vItr= vItrRange.first; vItr != vItrRange.second; ++vItr) { //a conflict occurs if a graph has a color of 0 or has the same color as a neighbor if (0 == g[*vItr].color || matchingColors(g, vItr)) { numConflicts++; } } return numConflicts; } //checks if a vertex has the same color as any of its neighbors bool matchingColors(Graph& g, Graph::vertex_iterator v) { pair<Graph::adjacency_iterator, Graph::adjacency_iterator> vItrRange = adjacent_vertices(*v, g); for (Graph::adjacency_iterator vItr= vItrRange.first; vItr != vItrRange.second; ++vItr) { if(g[*v].color == g[*vItr].color) { return true; } } //we have looped through all of the neighbors, so none have the same color return false; } //colors the graph - the second parameter is the "code" for how to color the graph //the code is a vector of ints, where the int represents the color - 1 //i.e., if the code for 3 vertices is 201, then they will be colored 3, 1, and 2 respectively void colorGraph(Graph& g, vector<int> colorNumber, int numColors) { pair<Graph::vertex_iterator, Graph::vertex_iterator> vItrRange = vertices(g); int i = 0; for (Graph::vertex_iterator vItr= vItrRange.first; vItr != vItrRange.second; ++vItr) { g[*vItr].color = colorNumber.at(i) + 1; i++; } } //this increments the color code //i.e. 000 becomes 001, assuming 3 colors 202 becomes 210, etc vector<int> incrementColorNumber(vector<int> colorNumber, int index, int numColors) { colorNumber.at(index) += 1; if (colorNumber.at(index) >= numColors && index > 0) { colorNumber.at(index) = 0; colorNumber = incrementColorNumber(colorNumber, index - 1, numColors); } return colorNumber; }
true
6afd1d3b114f56a84762a0641daaca724bceeb66
C++
ChanghuiN/Exercise
/InterviewQuestions/43_DicesProbability/DicesProbability.cpp
UTF-8
1,664
3.015625
3
[]
no_license
// // Created by ChanghuiN on 2018/1/9. // #include <cstdio> #include <cmath> #include "DicesProbability.h" int g_maxValue = 6; void PrintProbability_Solution2(int number) { if (number < 1) return; int *pProbabilities[2]; pProbabilities[0] = new int[g_maxValue * number + 1]; pProbabilities[1] = new int[g_maxValue * number + 1]; for (int i = 0; i < g_maxValue * number + 1; ++i) { pProbabilities[0][i] = 0; pProbabilities[1][i] = 0; } int flag = 0; for (int i = 1; i <= g_maxValue; ++i) pProbabilities[flag][i] = 1; for (int k = 2; k <= number; ++k) { for (int i = 0; i < k; ++i) pProbabilities[1 - flag][i] = 0; for (int i = k; i <= g_maxValue * k; ++i) { pProbabilities[1 - flag][i] = 0; for (int j = 1; j <= i && j <= g_maxValue; ++j) pProbabilities[1 - flag][i] += pProbabilities[flag][i - j]; } flag = 1 - flag; } double total = pow((double) g_maxValue, number); for (int i = number; i <= g_maxValue * number; ++i) { double ratio = (double) pProbabilities[flag][i] / total; printf("%d: %e\n", i, ratio); } delete[] pProbabilities[0]; delete[] pProbabilities[1]; } void Test_DicesProbability(int n) { printf("Test for %d begins:\n", n); printf("Test for solution2\n"); PrintProbability_Solution2(n); printf("\n"); } void Test_43_DicesProbability() { Test_DicesProbability(1); Test_DicesProbability(2); Test_DicesProbability(3); Test_DicesProbability(4); Test_DicesProbability(11); Test_DicesProbability(0); }
true
c58f55a08cb3421c1298ae956e0b08d55377dd7d
C++
kamiltalipov/295-a2
/will1995@list.ru/Tasks/Term 2/Task1/Bridges, points/main.cpp
UTF-8
3,892
2.703125
3
[]
no_license
#include <iostream> #include <stdio.h> #include <vector> #include <list> using namespace std; class Graph { public: Graph(int size): size(size), time(0), points(0) { Vert.resize(size); Used.resize(size); Used.assign(size, 0); Added.resize(size); Added.assign(size, 0); tin.resize(size); tin.assign(size, 0); edge_comp.resize(size); edge_comp.assign(size, -1); fup.resize(size); fup.assign(size, 1000000); } Graph(); void DFS(int vertex, int parent); void DFS2 (int vertex, int &color, int parent); void Add (int vertex, int another_vertex); void Paint (int v, int &color); //private: vector < vector < pair < int, int > > > Vert; vector < bool > Used; vector < bool > Added; vector < int > tin; vector < int > fup; vector < int > points; vector < pair < int, int > > bridges; vector < int > edge_comp; int size; int time; }; void Graph::Add(int v, int u) { Vert[v].push_back(make_pair(u, -1)); } void Graph::Paint(int v, int &c) { edge_comp[v] = c; for (int i = 0; i < Vert[v].size(); i++) { int tmp = Vert[v][i].first; if (edge_comp[tmp] == -1) if (fup[tmp] == tin[tmp]) { c++; Paint(tmp, c); } else Paint(tmp, c); } } void Graph::DFS2(int v, int &c, int p) { Used[v] = true; for (int i = 0; i < Vert[v].size(); i++) { int tmp = Vert[v][i].first; if (tmp == p) continue; if (!Used[tmp]) if (fup[tmp] >= tin[v]) { int c2 = c + 1; Vert[v][i].second = c2; DFS2(tmp, c2, v); } else { Vert[v][i].second = c; DFS2(tmp, c, v); } else if ((tin[tmp] <= tin[v]) && (Vert[v][i].second == -1)) Vert[v][i].second = c; } } void Graph::DFS(int v, int p = -1) { Used[v] = true; tin[v] = fup[v] = time++; int child = 0; for (int i = 0; i < Vert[v].size(); i++) { int tmp = Vert[v][i].first; if (tmp == p) continue; if (Used[tmp]) fup[v] = min (fup[v], tin[tmp]); else { DFS(tmp, v); fup[v] = min (fup[v], fup[tmp]); if (fup[tmp] >= tin[v] && p != -1 && !Added[v]) { Added[v] = true; points.push_back(v); } if (fup[tmp] > tin[v]) { bridges.push_back(make_pair(v, tmp)); } child++; } } if (p == -1 && child > 1) { Added[v] = true; points.push_back(v); } } int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n, m; cin >> n >> m; Graph gr(n); for(int i = 0; i < m; i++) { int v, u; cin >> v >> u; gr.Add(v, u); gr.Add(u, v); } for (int i = 0; i < n; i++) { if (!gr.Used[i]) gr.DFS(i); } gr.Used.assign(n, 0); for (int i = 0; i < gr.points.size(); i++) cout << gr.points[i] << " "; cout << endl << endl; for (int i = 0; i < gr.bridges.size(); i++) cout << gr.bridges[i].first << '-' << gr.bridges[i].second << endl; cout << endl; int c = 0; for (int i = 0; i < n; i++) { if (!gr.Used[i]) gr.DFS2(i, c, -1); } for (int i = 0; i < n; i++) { for (int j = 0; j < gr.Vert[i].size(); j++) if (gr.Vert[i][j].second != -1) cout << i << '-' << gr.Vert[i][j].first << ' ' << gr.Vert[i][j].second << endl; } cout << endl; c = 0; for (int i = 0; i < n; i++) { if (gr.edge_comp[i] == -1) gr.Paint(i, c); } for (int i = 0; i < n; i++) { cout << i << " - " << gr.edge_comp[i] << endl; } cout << endl; fclose(stdin); fclose(stdout); return 0; }
true
b8aa01e3ced6ffc37f412fe445efac2b00448798
C++
eXpl0it3r/Examples
/SFML/FadingDots.cpp
UTF-8
1,716
3.15625
3
[ "Zlib" ]
permissive
#include <SFML/Graphics.hpp> #include <cstdint> #include <list> int main() { auto window = sf::RenderWindow{ sf::VideoMode{ { 500u, 500u } }, "Fading Dots" }; window.setFramerateLimit(60u); auto oldPosition = sf::Vector2f{ 0.f, 0.f }; constexpr auto Step = 1; auto points = std::list<sf::CircleShape>{}; while (window.isOpen()) { for (auto event = sf::Event{}; window.pollEvent(event);) { if (event.type == sf::Event::Closed) { window.close(); } } // Check if the mouse has moved auto position = window.mapPixelToCoords(sf::Mouse::getPosition(window)); if (position != oldPosition) { // Create and add a new circle to the points list. auto circleShape = sf::CircleShape{ 10.f }; circleShape.setRadius(10.f); circleShape.setPosition(position); circleShape.setFillColor(sf::Color::Red); points.push_back(circleShape); oldPosition = position; } window.clear(); for (auto it = points.begin(); it != points.end(); ++it) { window.draw(*it); if (it->getFillColor().a - Step < 0) // When the transparency falls below zero (= invisible) then erase the dot. { it = points.erase(it); } else // Otherwise draw it with a increasing green touch (turns yellowish). { it->setFillColor({ 255u, static_cast<std::uint8_t>(it->getFillColor().g + Step), 0u, static_cast<std::uint8_t>(it->getFillColor().a - Step) }); } } window.display(); } }
true
ce30cdbf5d47db2d00f3caba08a1c727dec56fa7
C++
rogalick/Cpp-modern-development-coursera-
/White belt/week4/date/Date.cpp
UTF-8
804
3.5625
4
[]
no_license
#include <iostream> #include <vector> #include <map> #include <algorithm> #include <vector> using namespace std; struct Specialization { explicit Specialization(string spec) { m_spec = spec; } string m_spec; }; struct Week { explicit Week(string week) { m_week = week; } string m_week; }; struct Course { explicit Course(string course) { m_course = course; } string m_course; }; struct LectureTitle { explicit LectureTitle(Specialization spec, Course cors, Week wek) { course = cors.m_course; specialization = spec.m_spec; week = wek.m_week; } string specialization; string course; string week; }; int main() { LectureTitle title( Specialization("C++"), Course("White belt"), Week("4th") ); cout << title.course; }
true
4f3089d4db027b6e5c1e33266c4477b898ba4358
C++
IgorPTZ/Calculo_de_areas_e_volumes
/Cubo.cpp
UTF-8
504
2.953125
3
[]
no_license
#include "stdafx.h" #include "Cubo.h" Cubo::Cubo(const string &nomeForma, double aresta) :FormaTriDimensional(nomeForma) { setValorAresta(aresta); } void Cubo::setValorAresta(double valorAresta) { aresta = (valorAresta <= 0.0) ? 1.0 : valorAresta; } double Cubo::getValorAresta() const { return aresta; } double Cubo::obterArea() const { return (6 * (getValorAresta() * getValorAresta())); } double Cubo::obterVolume() const { return (getValorAresta() * getValorAresta() * getValorAresta()); }
true
b331fc0342400e4a333e611ebd91ea9e2d867068
C++
yosabaki/os-net
/server.cpp
UTF-8
3,356
2.9375
3
[]
no_license
#include <iostream> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <arpa/inet.h> #include <cstring> using namespace std; void print_usage() { cout << "Usage: server [address] [port]" << endl; } void close_socket(int fd) { if (close(fd) < 0) { perror("Cannot close socket"); } } const int MAX_LEN = 100; const int BUFF_SIZE = 1024; int main(int argc, char **argv, char **env) { if (argc != 3) { print_usage(); return 0; } int sockfd, port; struct sockaddr_in address; try { port = stoull(argv[2]); } catch (exception &e) { cout << "Invalid port: " << argv[2] << endl; exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_port = htons(port); if (!inet_pton(AF_INET, argv[1], &address.sin_addr)) { cout << "Invalid domain: " << argv[1] << endl; exit(EXIT_FAILURE); } int opt = 1; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("Socket failed"); exit(EXIT_FAILURE); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt failed"); close_socket(sockfd); exit(EXIT_FAILURE); } if (bind(sockfd, (struct sockaddr *) &address, sizeof(address)) < 0) { perror("binding failed"); close_socket(sockfd); exit(EXIT_FAILURE); } if (listen(sockfd, 3) < 0) { perror("listening failed"); close_socket(sockfd); exit(EXIT_FAILURE); } cout << "Listening at " << argv[1] << ":" << argv[2] << endl; while (true) { int newsocket; struct sockaddr_in client_address; socklen_t addrlen = sizeof(client_address); if ((newsocket = accept(sockfd, (struct sockaddr *) &client_address, &addrlen)) < 0) { perror("accept"); close_socket(newsocket); continue; } char addr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(client_address.sin_addr), addr, INET_ADDRSTRLEN); cout << "Accepted connection from " << addr << endl; char buffer[BUFF_SIZE] = {0}; int valread, received = 0; while ((valread = recv(newsocket, buffer + received, BUFF_SIZE - received, 0)) > 0) { received += valread; if (buffer[received - 1] == '\n') { break; } } if (valread < 0) { perror("Receiving failed"); close_socket(newsocket); continue; } cout << "Received: " << buffer; int length = strlen(buffer), sent = 0; bool err = false; while (sent < length && !err) { cout.flush(); int cnt = send(newsocket, buffer + sent, length - sent, 0); if (cnt < 0) { err = true; } sent += cnt; } if (err) { perror("Sending failed"); close_socket(newsocket); continue; } cout << "Echo sent" << endl; close_socket(newsocket); if (strcmp(buffer, "stop\n") == 0) { cout << "Server stopped" << endl; break; } } close_socket(sockfd); }
true
2b69d48b8ba3b785bead91afd7504df1b51d0a15
C++
Camixxx/Ros_Windows_Socket
/ros_lib/rosbridge_msgs/ConnectedClient.h
UTF-8
3,049
2.65625
3
[ "MIT" ]
permissive
#ifndef _ROS_rosbridge_msgs_ConnectedClient_h #define _ROS_rosbridge_msgs_ConnectedClient_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "ros/time.h" namespace rosbridge_msgs { class ConnectedClient : public ros::Msg { public: typedef const char* _ip_address_type; _ip_address_type ip_address; typedef ros::Time _connection_time_type; _connection_time_type connection_time; ConnectedClient(): ip_address(""), connection_time() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; uint32_t length_ip_address = strlen(this->ip_address); varToArr(outbuffer + offset, length_ip_address); offset += 4; memcpy(outbuffer + offset, this->ip_address, length_ip_address); offset += length_ip_address; *(outbuffer + offset + 0) = (this->connection_time.sec >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->connection_time.sec >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->connection_time.sec >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->connection_time.sec >> (8 * 3)) & 0xFF; offset += sizeof(this->connection_time.sec); *(outbuffer + offset + 0) = (this->connection_time.nsec >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->connection_time.nsec >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->connection_time.nsec >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->connection_time.nsec >> (8 * 3)) & 0xFF; offset += sizeof(this->connection_time.nsec); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t length_ip_address; arrToVar(length_ip_address, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_ip_address; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_ip_address-1]=0; this->ip_address = (char *)(inbuffer + offset-1); offset += length_ip_address; this->connection_time.sec = ((uint32_t) (*(inbuffer + offset))); this->connection_time.sec |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->connection_time.sec |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->connection_time.sec |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->connection_time.sec); this->connection_time.nsec = ((uint32_t) (*(inbuffer + offset))); this->connection_time.nsec |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); this->connection_time.nsec |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); this->connection_time.nsec |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->connection_time.nsec); return offset; } const char * getType(){ return "rosbridge_msgs/ConnectedClient"; }; const char * getMD5(){ return "7f2187ce389b39b2b3bb2a3957e54c04"; }; }; } #endif
true
244366d21f4408d67d2d50d4380133cd0b8f96dd
C++
annasochavan777/LogicBuilding-Assignments
/LB Assignment-31/Assignment31_2.cpp
UTF-8
694
3.328125
3
[]
no_license
///////////////////////////////////////////////////////////////////////////////////////////////////// // Write application which accept file name from user and create that file. // Input : Demo.txt // Output : File created successfully. // Author : Annaso Chavan ///////////////////////////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <fstream> using namespace std; int main () { string name; cout << "please enter file name :"; cin >> name; ofstream file; file.open(name + ".txt",ios::out); if(!file) { cout << "Error while creating file"; return 0; } cout << "File created successfully."; }
true
a7e0e813b31a3a6c9c98d9778dc57b11335db3dd
C++
listopat/Raymond
/Engine/include/Camera.h
UTF-8
577
2.765625
3
[ "MIT" ]
permissive
#pragma once #include <Matrix.h> #include <Ray.h> #include <Canvas.h> #include <World.h> class Camera { public: const int hSize, vSize; const double fieldOfView, pixelSize; static Camera makeCamera(int h, int v, double fov); void setTransform(const Matrix& m); Matrix getTransform() const; Ray rayForPixel(int px, int py); Canvas render(World w); private: Matrix transform, inverseTransform; const double halfWidth, halfHeight; Camera(int h, int v, double fov, double pxlSz, const Matrix &m, double halfWidth, double halfHeight); };
true
0d244697959976831b35136e26e222e11b693dbb
C++
kamyu104/LeetCode-Solutions
/C++/amount-of-new-area-painted-each-day.cpp
UTF-8
5,112
2.890625
3
[ "MIT" ]
permissive
// Time: O(nlogr), r is the max position // Space: O(r) template <typename T> class SegmentTree { public: explicit SegmentTree( int N, const function<T(const T&, const T&)>& query_fn, const function<T(const T&, const T&)>& update_fn) : base_(N), tree_(2 * N), lazy_(2 * N), count_(2 * N, 1), query_fn_(query_fn), update_fn_(update_fn) { H_ = 1; while ((1 << H_) < N) { ++H_; } for (int i = N - 1; i >= 1; --i) { count_[i] = count_[2 * i] + count_[2 * i + 1]; } } void update(int L, int R, const T& val) { L += base_; R += base_; push(L); // key point push(R); // key point int L0 = L, R0 = R; for (; L <= R; L >>= 1, R >>= 1) { if ((L & 1) == 1) { apply(L++, val); } if ((R & 1) == 0) { apply(R--, val); } } pull(L0); pull(R0); } T query(int L, int R) { T result{}; if (L > R) { return result; } L += base_; R += base_; push(L); push(R); for (; L <= R; L >>= 1, R >>= 1) { if ((L & 1) == 1) { result = query_fn_(result, tree_[L++]); } if ((R & 1) == 0) { result = query_fn_(result, tree_[R--]); } } return result; } private: void apply(int x, const T val) { tree_[x] = update_fn_(tree_[x], val * count_[x]); if (x < base_) { lazy_[x] = update_fn_(lazy_[x], val); } } void pull(int x) { while (x > 1) { x >>= 1; tree_[x] = query_fn_(tree_[x * 2], tree_[x * 2 + 1]); if (lazy_[x]) { tree_[x] = update_fn_(tree_[x], lazy_[x] * count_[x]); } } } void push(int x) { for (int h = H_; h > 0; --h) { int y = x >> h; if (lazy_[y]) { apply(y * 2, lazy_[y]); apply(y * 2 + 1, lazy_[y]); lazy_[y] = 0; } } } int base_; int H_; vector<T> tree_; vector<T> lazy_; vector<T> count_; const function<T(const T&, const T&)> query_fn_; const function<T(const T&, const T&)> update_fn_; }; // segment tree class Solution { public: vector<int> amountPainted(vector<vector<int>>& paint) { const auto& query = [] (const auto& x, const auto& y) { return x + y; }; const auto& update = [] (const auto& x, const auto& y) { return y; }; const int max_pos = (*max_element(cbegin(paint), cend(paint), [](const auto& x, const auto& y) { return x[1] < y[1]; } ))[1]; SegmentTree<int> st(max_pos, query, update); vector<int> result; for (const auto& x : paint) { const int cnt = st.query(x[0], x[1] - 1); st.update(x[0], x[1] - 1, 1); result.emplace_back(st.query(x[0], x[1] - 1) - cnt); } return result; } }; // Time: O(nlogn) // Space: O(n) // line sweep, heap class Solution2 { public: vector<int> amountPainted(vector<vector<int>>& paint) { map<int, vector<pair<int, int>>> points; for (int i = 0; i < size(paint); ++i) { points[paint[i][0]].emplace_back(1, i); points[paint[i][1]].emplace_back(0, i); } priority_queue<int, vector<int>, greater<int>> min_heap; vector<bool> lookup(size(paint)); vector<int> result(size(paint)); int prev = -1; for (const auto& [pos, v] : points) { while (!empty(min_heap) && lookup[min_heap.top()]) { min_heap.pop(); } if (!empty(min_heap)) { result[min_heap.top()] += pos - prev; } prev = pos; for (const auto& [t, i] : v) { if (t) { min_heap.emplace(i); } else { lookup[i] = true; } } } return result; } }; // Time: O(nlogn) // Space: O(n) // line sweep, bst class Solution3 { public: vector<int> amountPainted(vector<vector<int>>& paint) { map<int, vector<pair<int, int>>> points; for (int i = 0; i < size(paint); ++i) { points[paint[i][0]].emplace_back(1, i); points[paint[i][1]].emplace_back(0, i); } set<int> bst; vector<int> result(size(paint)); int prev = -1; for (const auto& [pos, v] : points) { if (!empty(bst)) { result[*begin(bst)] += pos - prev; } prev = pos; for (const auto& [t, i] : v) { if (t) { bst.emplace(i); } else { bst.erase(i); } } } return result; } };
true
bb8fcdbe7ef8327cdf6d0452fa3079860b20cc7b
C++
anbae12/num6man
/Mandatory exercise/main.cpp
UTF-8
3,209
2.75
3
[]
no_license
// // main.cpp // Mandatory exercise // // Created by Anders and Mikkel on 01/03/15. // Copyright (c) 2015 Anders Launer Bæk. All rights reserved. // #include <iostream> #include <fstream> #include "nr3.h" #include "svd.h" int main() { // Reading the data file const int dataRows = 500; const int dataColumn = 4; VecDoub theta1(dataRows); VecDoub theta2(dataRows); VecDoub x(dataRows); VecDoub y(dataRows); std::ifstream dataPoints("/Users/Anders/Dropbox/6.\ semester/NUM6/Mandatory\ exercise/d1.txt"); // Anders if ( ! dataPoints.is_open() ) { std::cout <<"Failed to open data file..." << std::endl; exit(0); } for (int i=0; i<dataRows; i++) { dataPoints >> theta1[i]; dataPoints >> theta2[i]; dataPoints >> x[i]; dataPoints >> y[i]; } // SDV of problem /* Find expressions for the elements in the matrix A and the right-hand side, say z, for the associated systems of linear equations for the pa- rameters q = (x0, y0, a, b). */ // Latex /* Read the files with values, insert them in A and compute U, W og V using the method from NR. State (with arguments based on the SVD matrices) if there are linear dependencies between the parameters x0, y0, a, b. */ MatDoub A(dataRows*2,dataColumn); int tempIt=0; for (int j=0; j<dataRows*2; j++) { if (j%2==0) { A[j][0]=1; A[j][1]=0; A[j][2]=cos(theta1[tempIt]); A[j][3]=cos(theta1[tempIt]+theta2[tempIt]); } else{ A[j][0]=0; A[j][1]=1; A[j][2]=sin(theta1[tempIt]); A[j][3]=sin(theta1[tempIt]+theta2[tempIt]); tempIt++; } } VecDoub z(dataRows*2); int tempIt2=0; for (int j=0; j<dataRows*2; j++) { if (j%2==0) { z[j]=x[tempIt2]; } else{ z[j]=y[tempIt2]; tempIt2++; } } SVD obj(A); VecDoub W=obj.w; MatDoub V=obj.v; MatDoub U=obj.u; std::cout<<"W\n"<<W<<std::endl; std::cout<<"V\n"<<V<<std::endl; std::cout<<"U\n"<<U<<std::endl; /* Estimate the parameters q = (x0, y0, a, b) and state your results. State also the residual error ∥Aq − z∥. */ VecDoub q(dataColumn); obj.solve(z, q); std::cout<<"q\n"<<q<<std::endl; VecDoub tempRes(dataRows*2); tempRes = (A*q)-z; Doub sum = 0; for( int i = 0; i < dataRows*2; i++){ sum += pow(tempRes[i],(double)2); } sum = sqrt(sum); std::cout<<"Residual error\n"<<sum<<"\n"<<std::endl; /* The values of the x(i), y(i)’s are measured with a camera, and there is a measurement uncertainty that is estimated to 1mm on each coordinate. Estimate the resulting errors on the found parameters using NR, Eq. (15.4.19). */ VecDoub stddev(dataColumn); for (int i=0; i<dataColumn; i++) { Doub varians = 0; for (int j=0; j<dataColumn; j++) { varians += pow(V[i][j]/W[j], 2); } stddev[i]=sqrt(abs(varians)); } std::cout<<"STD\n"<<stddev<<std::endl; return 0; }
true
58edb09f70c2773b69d9638d1f2bdd175b1cce96
C++
TOMMYWHY/opengl_learning
/src/demo03/Shader.cpp
UTF-8
1,996
2.828125
3
[]
no_license
// // Created by Tommy on 2019-11-29. // #include "Shader.h" #include <string> #include <iostream> using namespace std; Shader::Shader() { // cout <<"aaaa" <<endl; // 顶点 shader - 确定顶点位置 const char *vertexShaderSource = "#version 400 core\n" "layout (location = 0) in vec3 aPos;\n" // "layout (location = 1) in vec2 aTexCoordinate;\n" // "out vec2 TexCoordinate;\n" "void main(){\n" "TexCoordinate = aTexCoordinate;\n" // "gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);}"; // // 片面 shader - 每个像素着色 const char *fragmentShaderSource = "#version 400 core\n" "out vec4 FragColor;\n" "in vec2 TexCoordinate;\n" "uniform sampler2D ourTexture;\n" "void main(){\n" "FragColor = texture(ourTexture,TexCoordinate);} "; int vertexShaderId = glCreateShader(GL_VERTEX_SHADER); // 创建 vertex shader glShaderSource(vertexShaderId, 1, &vertexShaderSource, nullptr); // 声明 id 指向 shader source glCompileShader(vertexShaderId); // 编译。。。 int fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShaderId, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShaderId); int shaderProgramId = glCreateProgram(); // 创建 gpu 程序 glAttachShader(shaderProgramId, vertexShaderId); // 添加 glAttachShader(shaderProgramId, fragmentShaderId); glLinkProgram(shaderProgramId); // 连接 // return shaderProgramId; } void Shader::useShader(){ // cout<<shaderProgramId<<endl; glUseProgram(shaderProgramId); } Shader::~Shader() {}
true
86b6b7a43f46532a39000c82600fd0132002b475
C++
duffyco/embedded-art-engine
/src/VignetteLayer.h
UTF-8
874
2.6875
3
[]
no_license
#ifndef VignetteLayer_h_ #define VignetteLayer_h_ #include <string> #include <iostream> #include "Layer.h" #include <GL/gl.h> #include <GL/glu.h> class VignetteLayer : public Layer { public: VignetteLayer( std::string filename ); ~VignetteLayer(); void turnOn() { if( ( m_currentMode == LAYER_OFF || m_currentMode == FADING_OUT ) && !m_disabled ) { fadeIn = true; setMode( FADING_IN ); Layer::turnOn(); } } void turnOff() { if( m_currentMode == LAYER_ACTIVE || ( ( m_currentMode == FADING_IN ) && m_disabled ) ) { fadeIn = false; setFade( 1.0, 1500 ); //500 setMode( FADING_OUT ); Layer::turnOff(); } } void updateData( double lastCallTime ); static void setDisabled( bool disabled ) { m_disabled = disabled; } private: bool m_on; static bool m_disabled; double m_random; }; #endif
true
c0fc5931ef744d1db3f803cd8eda7b308d6af489
C++
BioGearsEngine/core
/projects/biogears/libBiogears/include/biogears/cdm/utils/unitconversion/CompoundUnitElement.h
UTF-8
4,798
2.515625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/************************************************************************************** Copyright 2015 Applied Research Associates, Inc. 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. **************************************************************************************/ //---------------------------------------------------------------------------- /// @file CompoundUnitElement.h /// @author Chris Volpe /// /// This class contains a representation of a single element in a Compound Unit. /// A Compound Unit is therefore a product of these. //---------------------------------------------------------------------------- #pragma once #include <biogears/cdm/utils/unitconversion/SnapValue.h> namespace biogears { class CCompoundUnitElement { public: // The use of CSnapValue as the exponent type allows for fractional exponents // without resulting in "almost integer" exponents. Why do we want fractional // exponents? Well, it allows you to take roots of quantities. // For example, if I have a square area given in units of acres and I want // to know the length of the square, I can compute the square root with the result // being expressed in units of acres^[1/2]. This is a perfectly legitimate unit of // distance and can be converted to feet, meters, etc by our existing algorithm. The // obvious point that one might make in response is that since any "square-rootable" // unit must ultimately have dimensions with even exponents, why not just convert the // unit to its expansion into fundamental units and divide those exponents, which must // be even, by two? Well, that would either require collusion with client code to do // the value conversion, or would require maintaining a separate fudge-factor within // the CompoundUnit structure itself. This seems like a hack. After all, since any // unit can be squared and cubed, it should be possible to un-square or un-cube any // unit whose dimensions are perfect squares and cubes, respectively. typedef CSnapValue ExponentType; // Need a parameterless constructor to be used in a vector CCompoundUnitElement() { // nothing } CCompoundUnitElement(int unitId, ExponentType exponent = 1.0, int prefixID = -1) : m_iUnitID(unitId) , m_CExponent(exponent) , m_iPrefixID(prefixID){ // nothing }; CCompoundUnitElement(const CCompoundUnitElement& src) : m_iUnitID(src.m_iUnitID) , m_CExponent(src.m_CExponent) , m_iPrefixID(src.m_iPrefixID){ // nothing }; CCompoundUnitElement& operator=(const CCompoundUnitElement& rhs) { if (this != &rhs) { m_iUnitID = rhs.m_iUnitID; m_CExponent = rhs.m_CExponent; m_iPrefixID = rhs.m_iPrefixID; } return *this; }; // Setters/Getters void SetUnitID(int unitID) { m_iUnitID = unitID; }; int GetUnitID() const { return m_iUnitID; } void SetExponent(const ExponentType& exponent) { m_CExponent = exponent; }; void AddExponent(const ExponentType& exponent) { m_CExponent += exponent; } void MultExponent(const ExponentType& exppwr) { m_CExponent *= exppwr; } void SubtractExponent(const ExponentType& exponent) { m_CExponent -= exponent; } const ExponentType& GetExponent() const { return m_CExponent; } void SetPrefixID(int prefixID) { m_iPrefixID = prefixID; } int GetPrefixID() const { return m_iPrefixID; } // http://support.microsoft.com/kb/168958 says we need to define operators < and == // for this if we want to export the vector of these contained in CompoundUnit. It // even says we can just return true if there's no sensible interpretation of // "operator<" for this class. bool operator<(const CCompoundUnitElement& ref) const { return true; // Dummy implementation } bool operator==(const CCompoundUnitElement& ref) const { return ((m_iUnitID == ref.m_iUnitID) && (m_CExponent == ref.m_CExponent) && (m_iPrefixID == ref.m_iPrefixID)); } // Convenience method for moving a CompoundUnitElement from the numerator to // the denominator, or vice versa void Invert() { m_CExponent *= -1; } double GetBigness() const; double GetBias() const; bool IsDecibel() const; private: int m_iUnitID; ExponentType m_CExponent; int m_iPrefixID; }; }
true
7d34b7c5be76d16d2ed1c96ae01a6d5d068ed44a
C++
trimone/__TINF_Projekt_2
/__TINF_Projekt_2/Rechteck.cpp
ISO-8859-1
1,355
2.65625
3
[]
no_license
///*====================================================================================================== //'.ccp' Datei zu Klasse 'Rechteck' //======================================================================================================*/ // //// === INCLUDE === // // // //#include "Rechteck.h" // Header-Datei der Klasse einfgen // // //// === DEFIDITION DER METHODEN === //// Zwegs der bersichtilichkeit werden die Methoden ausgelagert //// 'Datum::' ==> Methode gehrt zu Klasse // //double Rechteck::calUmfang(double h, double l) //{ // umfang = 2 * h + 2 * l; // return umfang; //} // //double Rechteck::calFlaeche(double h, double l) //{ // flaeche = h * l; // return flaeche; //} // //bool Rechteck::setHoehe(double h) //{ // bool ok = false; // if (h >= 0) // { // hoehe = h; // ok = true; // } // // return ok; //} // //bool Rechteck::setLaenge(double l) //{ // bool ok = false; // if (l >= 0) // { // laenge = l; // ok = true; // } // // return ok; //} // //bool Rechteck::setUmfang(double u) //{ // return false; //} // //bool Rechteck::setFlaeche(double f) //{ // return false; //} // //double Rechteck::getHoehe() //{ // return hoehe; //} // //double Rechteck::getLaenge() //{ // return laenge; //} // //double Rechteck::getUmfang() //{ // return umfang; //} // //double Rechteck::getFlaeche() //{ // return flaeche; //}
true
f15fbfb54611d0a0b53e85d62cc2ae4f8605eef5
C++
TereSolano15/progra2-project-2-app2
/src/Enfermedad.h
UTF-8
758
2.65625
3
[]
no_license
// // Created by Tere Solano on 3/11/2020. // #ifndef MY_PROJECT_NAME_ENFERMEDAD_H #define MY_PROJECT_NAME_ENFERMEDAD_H #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> using namespace std; class Enfermedad{ private: string nombre; string secuencia; int cantidad; public: Enfermedad(); Enfermedad(const string &nombre, const string &secuencia); Enfermedad(istream& input); const string &getNombre() const; void setNombre(const string &nombre); const string &getSecuencia() const; void setSecuencia(const string &secuencia); int getCantidad() const; void setCantidad(int cantidad); virtual string toString() ; }; #endif //MY_PROJECT_NAME_ENFERMEDAD_H
true
f80f756b5c512a7d2d94e84188e59bdb38e0d017
C++
jmcarter9t/PCI-tests
/samples/pci_da12_basic.cpp
UTF-8
3,509
2.515625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sys/io.h> #include <time.h> #include <unistd.h> #include <termios.h> #include <sys/time.h> #include <sys/select.h> #include "common_objects.h" #include "display.h" #include "io.h" #include "pciutil.h" #include "8254ctr.h" #include "8254ctr.h" #include <stdio.h> unsigned AskForBaseAddress(unsigned int OldOne) { char msg[7]; int NewOne = 0, Success = 0, Dummy; int AddrInputPosX, AddrInputPosY; CPRINTF("Please enter the Base Address for your card (in hex)"); CPRINTF("or press ENTER for %X.\n>", OldOne); AddrInputPosX = WHEREX(); AddrInputPosY = WHEREY(); do { GOTOXY(AddrInputPosX, AddrInputPosY); CLREOL(); msg[0] = 5; msg[1] = 0; GETS(msg); sscanf(msg + 2, "%x", &NewOne); IOPermission(NewOne); Success = 1; Dummy = NewOne; if (msg[1] == 0) { GOTOXY(AddrInputPosX, AddrInputPosY); printf("%X", OldOne); Success = 1; Dummy = OldOne; } } while(!Success); return (Dummy); } /* end of AskForBaseAddress */ unsigned AskForCountAddress(void) { char msg[7]; int NewOne = 0, Success = 0, Dummy; int AddrInputPosX, AddrInputPosY; CPRINTF("Please enter the offset for Counter 0 for your card (in hex)."); CPRINTF("\n>"); AddrInputPosX = WHEREX(); AddrInputPosY = WHEREY(); do { GOTOXY(AddrInputPosX, AddrInputPosY); CLREOL(); msg[0] = 5; msg[1] = 0; GETS(msg); sscanf(msg + 2, "%x", &NewOne); Success = 1; Dummy = NewOne; } while(!Success); return (Dummy); } /* end of AskForCountAddress */ int main(int argc, char *argv[]) { unsigned freq=0; float time = 0; unsigned BASE = 0xFCA0; unsigned count = 0; CLRSCR(); BASE=AskForBaseAddress(BASE); CLRSCR(); count=AskForCountAddress(); //get counter offset BASE+=count; //add counter offset to base address DELAY(100); PUTS("8254 Counter Sample"); PUTS("--This program measures frequency and pulse width and generates frequency."); PUTS("--To measure frequency, connect a source to Clk IN on Pin 33."); PUTS(""); PUTS("Press any key to continue."); getch(); while(!kbhit()){ freq = freq; time = frequency_measure(BASE); printf("\nThe frequency is %10.3f\n\n", time); PUTS("Press any key to continue to pulse width test."); GOTOXY(1,WHEREY()-4); } getch(); CLRSCR(); //is this correct??? PUTS("--To measure pulse width, connect a source to Gate 1 on Pin 34."); PUTS("--Without a source, pulse width will read zero."); PUTS("--Ground Pin 37."); PUTS(""); PUTS("Press any key to continue."); getch(); while(!kbhit()){ time = pulse_width(BASE); printf(" Pulse1 %g \n", time); DELAY(1000); time = pulse_width(BASE); printf(" Pulse2 %g \n", time); DELAY(397); time = pulse_width(BASE); printf(" Pulse3 %g \n", time); time = pulse_width(BASE); printf(" Pulse4 %g \n", time); DELAY(300); time = pulse_width(BASE); printf(" Pulse5 %g \n", time); DELAY(10); time = pulse_width(BASE); printf(" Pulse6 %g \n\n", time); PUTS("Press any key to continue to next test."); GOTOXY(1,WHEREY()-8); } getch(); CLRSCR(); while(!kbhit()){ PUTS("Generating frequency..."); PUTS("Verify signal by connecting a frequency meter to Out 2 on Pin 35."); PUTS("Press any key to continue."); generatefrequency(BASE, 25000); GOTOXY(1,WHEREY()-3); } getch(); //DELAY(2000); }
true
9c6c7af2b5d117946ca061b14c3213d9c8f1c778
C++
mr-d-self-driving/PNC
/Planning/common/garbage_deal.cpp
UTF-8
1,655
2.640625
3
[]
no_license
 #include "garbage_deal.h" extern ConfigParam g_config_param; namespace planning { map<int,Garbage> GarbageDeal::garbages_pair_; GarbageDeal::GarbageDeal(ReferenceLineInfo * ref_line_info,const vector<Garbage> &Garbages) :ref_line_info_(ref_line_info),garbages_(Garbages) { Init(); } void GarbageDeal::Init(){ auto &reference_line = ref_line_info_->reference_line(); auto adc_sl = ref_line_info_->GetVechicleSLPoint(); cout<<"adc_sl s = "<<adc_sl.s<<endl; //1. update garbages for(auto garbage: garbages_){ garbages_pair_[garbage.id] = garbage; } //2. computer garbage sl remove behind clean vehicle garbage and add sl_queue map<int,Garbage> temp_pair; double clean_max_dis = g_config_param.clean_max_dis; double clean_max_width = g_config_param.clean_max_width; double clean_min_width = g_config_param.clean_min_width; for(pair<int,Garbage> garbage_pair:garbages_pair_){ SLPoint sl; auto pos = garbage_pair.second.position; reference_line.XYToSL({pos.x,pos.y},&sl); if( sl.s >adc_sl.s &&sl.s < adc_sl.s + clean_max_dis && sl.l > clean_min_width && sl.l < clean_max_width){ temp_pair.emplace(garbage_pair); //sl_queue_.emplace(sl); garbages_sl_.push_back(sl); } } //3. save cout<<"before update garbages num = "<<garbages_pair_.size()<<endl; garbages_pair_ = temp_pair; cout<<"after update garbages num = "<<garbages_pair_.size()<<endl; } void GarbageDeal::SetGarbagesSL(){ while( sl_queue_.size() > 0){ garbages_sl_.push_back(sl_queue_.top()); sl_queue_.pop(); } } }// end namespace planning
true
c8fd6f4c1c7ea53fb7ce86bbf086c95732ddb427
C++
nolanreilly/LED-multiplexer-IDEA-hacks-2016
/multiplexController.cpp
UTF-8
8,881
3.203125
3
[]
no_license
#include <wiringPi.h> #include <iostream> //Number of rows and columns (square multiplex) const int NumRCS = 7; const int LED_ROWS[NumRCS] = { 23, 24, 25, 12, 16, 20, 21 }; const int LED_CLMS[NumRCS] = { 17, 27, 22, 10, 13, 19, 26 }; int main(int argc, char**argv) {     wiringPiSetup(); // Initializes wiringPi using wiringPi's simplified number system.     wiringPiSetupGpio(); // Initializes wiringPi using the Broadcom GPIO pin numbers              for (int i = 0; i < NumRCS; i++) {         pinMode (LED_ROWS[i], OUTPUT);         pinMode (LED_CLMS[i], OUTPUT);     }          while (1) {         // ALL LEDS ON         for( int i = 0; i < NumRCS; i++ ) {             digitalWrite( LED_ROWS[i], HIGH );             for( int j = 0; j < NumRCS; j++ ) {                 digitalWrite( LED_CLMS[j], HIGH);                 delay(1);                 digitalWrite( LED_CLMS[j], LOW);             }             digitalWrite( LED_ROWS[i], LOW );             delay (1);         }                          for ( int numCircle = 0; numCircle < 4; numCircle++ ) {             double start = millis();                          for( int i = 0; i < NumRCS; i++ ) {                 digitalWrite( LED_ROWS[i], HIGH );                 for( int j = 0; j < NumRCS; j++ ) {                     digitalWrite( LED_CLMS[j], HIGH);                     delay(1);                     digitalWrite( LED_CLMS[j], LOW);                 }                 digitalWrite( LED_ROWS[i], LOW );                 delay (1);             }         }     }     return 0; } void openHand() {     for(int i = 0; i < NumRCS; i++) {         digitalWrite(LED_ROWS[i], HIGH);         switch(i) {             case 0, 1:                 int temp[] = {22, 13, 26};                 for(int j = 0; j < 3; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 2:                 int temp[] = {17, 22, 13, 26};                 for(int j = 0; j < 4; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 3:                  int temp[] = {17, 22, 10, 13, 19, 26};                 for(int j = 0; j < 6; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 4:                 for(int j = 0; j < NumRCS; j++) {                     digitalWrite(LED_CLMS[j], HIGH);                     delay(1);                     digitalWrite(LED_CLMS[j], LOW);                 }             case 5:                 int temp[] = {27, 22, 10, 13, 19};                 for(int j = 0; j < 5; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 6:                 int temp[] = {22, 10};                 for(int j = 0; j < 2; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }         }     } } void closedHand() {     for(int i = 0; i < NumRCS; i++) {         digitalWrite(LED_ROWS[i], HIGH);         switch(i) {             case 2:                 int temp[] = {22, 10, 13, 19};                 for(int j = 0; j < 4; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 3, 4:                  for(int j = 0; j < NumRCS; j++) {                     digitalWrite(LED_CLMS[j], HIGH);                     delay(1);                     digitalWrite(LED_CLMS[j], LOW);                 }             case 5:                 int temp[] = {27, 22, 10, 13, 19};                 for(int j = 0; j < 5; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 6:                 int temp[] = {22, 10};                 for(int j = 0; j < 2; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }         }     } } void mouthOpen() {     for(int i = 0; i < NumRCS; i++) {         digitalWrite(LED_ROWS[i], HIGH);         switch(i) {             case 1, 5:                 int temp[] = {22, 10, 13};                 for(int j = 0; j < 3; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 2, 4:                 for(int j = 0; j < NumRCS; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 3:                 digitalWrite(17, HIGH);                 digitalWrite(26, HIGH);                 delay(1);                 digitalWrite(17, LOW);                 digitalWrite(26, LOW);         }     } } void mouthClosed() {     for(int i = 0; i < NumRCS; i++) {         digitalWrite(LED_ROWS[i], HIGH);         switch(i) {             case 2, 5:                 int temp[] = {22, 10, 13};                 for(int j = 0; j < 3; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 3, 4:                 for(int j = 0; j < NumRCS; j++) {                     digitalWrite(LED_CLMS[j], HIGH);                     delay(1);                     digitalWrite(LED_CLMS[j], LOW);                 }         }     } } void lasso() {     for(int i = 0; i < NumRCS; i++) {         digitalWrite(LED_ROWS[i], HIGH);         switch(i) {             case 0:                 int temp[] = {27, 19};                 for(int j = 0; j < 2; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 1:                 int temp[] = {27, 22, 13, 19};                 for(int j = 0; j < 4; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 2:                  int temp[] = {22, 10, 13};                 for(int j = 0; j < 3; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 3, 4:                  for(int j = 0; j < NumRCS; j++) {                     digitalWrite(LED_CLMS[j], HIGH);                     delay(1);                     digitalWrite(LED_CLMS[j], LOW);                 }             case 5:                 int temp[] = {27, 22, 10, 13, 19};                 for(int j = 0; j < 5; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }             case 6:                 int temp[] = {22, 10};                 for(int j = 0; j < 2; j++) {                     digitalWrite(temp[j], HIGH);                     delay(1);                     digitalWrite(temp[j], LOW);                 }         }     } }
true
ec2d99103cfc34f650858d308b43987c26166b1f
C++
etremel/pddm
/src/messaging/OverlayTransportMessage.cpp
UTF-8
3,982
2.609375
3
[]
no_license
/** * @file OverlayTransportMessage.cpp * * @date Oct 14, 2016 * @author edward */ #include "OverlayTransportMessage.h" #include <cstring> #include <cstddef> #include <memory> #include <mutils-serialization/SerializationSupport.hpp> #include "MessageType.h" #include "MessageBodyType.h" #include "PathOverlayMessage.h" namespace pddm { namespace messaging { constexpr const MessageType OverlayTransportMessage::type; std::ostream& operator<< (std::ostream& out, const OverlayTransportMessage& message) { out << "{SenderRound=" << message.sender_round << "|Final=" << std::boolalpha << message.is_final_message << "|"; //Force C++ to use dynamic dispatch on operator<< even though it doesn't want to if(auto pom_body = std::dynamic_pointer_cast<PathOverlayMessage>(message.body)) { out << *pom_body; } else if(auto om_body = std::dynamic_pointer_cast<OverlayMessage>(message.body)) { out << *om_body; } else { out << "BODY UNKNOWN TYPE"; } out << "}"; return out; } std::size_t OverlayTransportMessage::bytes_size() const { return mutils::bytes_size(type) + mutils::bytes_size(sender_round) + mutils::bytes_size(is_final_message) + Message::bytes_size(); } std::size_t OverlayTransportMessage::to_bytes(char* buffer) const { std::size_t bytes_written = mutils::to_bytes(type, buffer); bytes_written += mutils::to_bytes(sender_round, buffer + bytes_written); bytes_written += mutils::to_bytes(is_final_message, buffer + bytes_written); bytes_written += Message::to_bytes(buffer + bytes_written); return bytes_written; } void OverlayTransportMessage::post_object(const std::function<void(const char* const, std::size_t)>& function) const { mutils::post_object(function, type); mutils::post_object(function, sender_round); mutils::post_object(function, is_final_message); Message::post_object(function); } std::unique_ptr<OverlayTransportMessage> OverlayTransportMessage::from_bytes(mutils::DeserializationManager<>* m, const char* buffer) { std::size_t bytes_read = 0; MessageType message_type; std::memcpy(&message_type, buffer + bytes_read, sizeof(MessageType)); bytes_read += sizeof(MessageType); int sender_round; std::memcpy(&sender_round, buffer + bytes_read, sizeof(sender_round)); bytes_read += sizeof(sender_round); bool is_final_message; std::memcpy(&is_final_message, buffer + bytes_read, sizeof(is_final_message)); bytes_read += sizeof(is_final_message); //Deserialize the fields written by Message's serialization (in the superclass call to to_bytes) int sender_id; std::memcpy(&sender_id, buffer + bytes_read, sizeof(sender_id)); bytes_read += sizeof(sender_id); //Peek ahead at type, but don't advance bytes_read because MessageBody classes will expect to deserialize it MessageBodyType type; std::memcpy(&type, buffer + bytes_read, sizeof(type)); //Dispatch to the correct subclass based on the MessageBodyType std::shared_ptr<OverlayMessage> body_shared; switch(type) { case MessageBodyType::OVERLAY: { std::unique_ptr<OverlayMessage> body = mutils::from_bytes<OverlayMessage>(m, buffer + bytes_read); body_shared = std::shared_ptr<OverlayMessage>(std::move(body)); break; } case MessageBodyType::PATH_OVERLAY: { std::unique_ptr<PathOverlayMessage> body = mutils::from_bytes<PathOverlayMessage>(m, buffer + bytes_read); body_shared = std::shared_ptr<PathOverlayMessage>(std::move(body)); break; } default: { std::cerr << "OverlayTransportMessage contained something other than an OverlayMessage! type = " << static_cast<int16_t>(type) << std::endl; assert(false); break; } } return std::make_unique<OverlayTransportMessage>(sender_id, sender_round, is_final_message, body_shared); } } // namespace messaging } // namespace pddm
true
ef024fce22e88ca4fddd2c8d39a3985b42b80fa2
C++
beyonddiana/render_engine
/src/Texture.cpp
UTF-8
3,284
3.0625
3
[]
no_license
#include "gl_headers.h" #include "Texture.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" // Texture::Texture(Vec2i size, bool depth_texture) : resolution(size) { this->id = create_render_texture(size, depth_texture); } // Texture::Texture(std::string filepath) { glGenTextures(1, &this->id); int force_channels = 4; unsigned char *data = load_image_data(filepath, force_channels, resolution); bind_texture_data(this->id, data, resolution); } // unsigned char *Texture::load_image_data(std::string filepath, int channel_count, Vec2i &resolution) { // number of channels per pixel implied by the file (not always the number we want) int n; // get the data from the image file (forcing the number of channels per pixel with 'channel_count') unsigned char *pixel_data = stbi_load(filepath.c_str(), &resolution.x, &resolution.y, &n, channel_count); if (!pixel_data) { std::cout << "texture file: " << filepath << " couldn't be read." << std::endl; } else { std::cout << "channels: " << n << std::endl; } // check if dimensions aren't a power of 2 if ((resolution.x & (resolution.x - 1)) != 0 || (resolution.y & (resolution.y - 1)) != 0) { std::cout << filepath << " has a texture size that is not a power of 2" << std::endl; } return pixel_data; } // void Texture::bind_texture_data(GLuint id, unsigned char *data, Vec2i resolution) { this->format = GL_RGBA8; // store the image data into opengl glBindTexture(GL_TEXTURE_2D, id); glTexImage2D(GL_TEXTURE_2D, 0, // base level (no minimap) GL_RGBA8, // internal format resolution.x, // width resolution.y, // height 0, // border GL_RGBA, // format GL_UNSIGNED_BYTE, // data type data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); check_error(); } // create a texture that can be rendered to. indicate whether it's a color or depth texture GLint Texture::create_render_texture(Vec2i size, bool depth) { GLuint text_id; glGenTextures(1, &text_id); this->format = depth ? GL_DEPTH_COMPONENT24 : GL_RGBA8; glBindTexture(GL_TEXTURE_2D, text_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); glTexImage2D(GL_TEXTURE_2D, 0, depth ? GL_DEPTH_COMPONENT24 : GL_RGB32F, size.x, size.y, 0, depth ? GL_DEPTH_COMPONENT : GL_RGB, GL_FLOAT, NULL); //unbind glBindTexture(GL_TEXTURE_2D, 0); return text_id; } // GLuint Texture::check_error() { GLuint err = glGetError(); if (err > 0) { std::cout << "Texture error: 0x" << std::hex << err << std::endl; } return err; }
true
1f9684352d90e695e581d9101de119056eda8f11
C++
tabris2015/stepper_api
/stepper_api.ino
UTF-8
4,086
3.078125
3
[]
no_license
#include <Arduino.h> #include "motor_api.h" #define STEP_PIN 9 #define DIR_PIN 3 #define ENABLE_PIN 7 #define TIME 15 Motor motor(DIR_PIN, STEP_PIN, ENABLE_PIN); uint8_t done = 0; // serial string parse // Buffer for the incoming data char inData[100]; // Buffer for the parsed data chunks char *inParse[100]; // Storage for data as string String inString = ""; // Incoming data id int index = 0; // Read state of incoming data boolean stringComplete = false; // prototipos void ParseSerialData(); void moverAngulo(int, int, int, int, int); void moverTiempo(int, int, int, int, int); void moverPasos(int, int, int, int, int); void setup() { // put your setup code here, to run once: pinMode(LED_BUILTIN, OUTPUT); pinMode(STEP_PIN, OUTPUT); pinMode(DIR_PIN, OUTPUT); digitalWrite(DIR_PIN, 0); // motor.spinSteps(100, 5, 0, 3, 300); // motor.spinTime(1000, 4, 1, 4, 500); // motor.spinAngle(90, 6, 0, 4, 1000); Serial.begin(9600); } void loop() { if (stringComplete) { // Parse the recieved data ParseSerialData(); // Reset inString to empty inString = ""; // Reset the system for further // input of data stringComplete = false; } motor.update(); } void ParseSerialData() { // The data to be parsed char *p = inData; // Temp store for each data chunk char *str; // Id ref for each chunk int count = 0; // Loop through the data and seperate it into // chunks at each "," delimeter while ((str = strtok_r(p, ",", &p)) != NULL) { // Add chunk to array inParse[count] = str; // Increment data count count++; } if(count == 1) { if(*inParse[0] == 'X') { motor.stop(); Serial.println("Deteniendo"); } } // If the data has two values then.. if(count == 4) { // Define value 1 as a function identifier char *func = inParse[0]; // Define value 2 as a property value int dir = atoi(inParse[1]); int vel = atoi(inParse[2]); int prop = atoi(inParse[3]); // Call the relevant identified function switch(*func) { case 'A': moverAngulo(dir, vel, prop, 1, 0); break; case 'T': moverTiempo(dir, vel, prop, 1, 0); break; case 'P': moverPasos(dir, vel, prop, 1, 0); break; } } if(count == 6) { // Define value 1 as a function identifier char *func = inParse[0]; // Define value 2 as a property value int dir = atoi(inParse[1]); int vel = atoi(inParse[2]); int prop = atoi(inParse[3]); int rep = atoi(inParse[4]); int pause = atoi(inParse[5]); // Call the relevant identified function switch(*func) { case 'A': moverAngulo(dir, vel, prop, rep, pause); break; case 'T': moverTiempo(dir, vel, prop, rep, pause); break; case 'P': moverPasos(dir, vel, prop, rep, pause); break; } } } void serialEvent() { // Read while we have data while (Serial.available() && stringComplete == false) { // Read a character char inChar = Serial.read(); // Store it in char array inData[index] = inChar; // Increment where to write next index++; // Also add it to string storage just // in case, not used yet :) inString += inChar; // Check for termination character if (inChar == '\n') { // Reset the index index = 0; // Set completion of read to true stringComplete = true; } } } // funciones void moverAngulo(int dir, int vel, int angle, int rep, int pause) { motor.spinAngle(angle, vel, dir, rep, pause); Serial.print("Moviendo "); Serial.print(angle); Serial.println(" grados."); } void moverTiempo(int dir, int vel, int time, int rep, int pause) { motor.spinTime(time, vel, dir, rep, pause); Serial.print("Moviendo "); Serial.print(time); Serial.println(" ms."); } void moverPasos(int dir, int vel, int steps, int rep, int pause) { motor.spinSteps(steps, vel, dir, rep, pause); Serial.print("Moviendo "); Serial.print(steps); Serial.println(" pasos."); }
true
ea7dd81a6aa5d9e0e044eb7c7f9369ff56f5ff96
C++
HanWenfang/Data_Structure_and_Algorithm
/10_SkipList.cpp
UTF-8
1,082
3.234375
3
[ "MIT" ]
permissive
/******************************************************* * Ordered Link-List for INDEX in place of balanced tree * Reference : kenby.iteye.com/blog/1187303 igoro.com/archive/skip-lists-are-fascinating * -Unique Key- * A kind of Data Structure has many kinds of implementation ways!! * ********************************************************/ class Node { public: Node(int key):value(key), next(NULL) {} Node *next; int value; }; class Nodes { public: Nodes(int key, int level) { value = key; root = new Node(key)[level]; next = NULL; } int value; Node *root; Nodes *next; }; class IntSkipList { public: Nodes *head = new Nodes(0, 20); // value = 0[min] Head doesn't contain value! levels = 1; bool contain(int value) { Nodes *cur = head; for(int i=levels-1; i>=0; --i) // level { for(;cur->root[i]->next != NULL; cur = cur->next) // list { if(cur->root[i]->next->value > value) break; if(cur->root[i]->next->value == value) return true; } } return false; } }; int main(int argc, char *argv[]) { return 0; }
true
20b37d8cb165f810896ba01d81f8f25f216e4d2c
C++
Saikikky/MyLeetcode
/算法库/算法分析/算法 实验一/fac.cpp
GB18030
1,272
3.578125
4
[]
no_license
/*쳲 1 i==1||i==2 f(i)={ f(i-1)+f(i-2) i>2 */ #include<iostream> using namespace std; #define MAX 100000 int F[MAX]; //F[i]洢f(i)ֵʼֵ0 int a[MAX]; //a[i]洢f(i)ظ int f(int i)//ݹд { if(i<1) return -1; a[i]++; if(i==1 || i==2) return 1; else return f(i-1)+f(i-2); } int dp1(int i)//ݹ͵Ķ̬滮д { if(F[i]) return F[i];//F[i]Ѿ־0ֱӷ a[i]++; //if()ʱa[i]++ŻִС if(i==1 || i==2) return F[i]=1; else return F[i]=dp1(i-1)+dp1(i-2); } int main(void) { int i,n; cout<<"Enter n(<100):"; cin>>n; cout<<"f(n)="<<f(n)<<endl; for(i=n ;i>0 ;i--) cout<<"a["<<i<<"]="<<a[i] <<endl; //Բ for(i=1;i<=n;i++) cout<<"f(n)="<<f(n)<<endl; //Է֣nﵽ43ϣҪʱԸоԽԽ˵ݹдЧʵͣԭf(i)ظ for(i=n ;i>0 ;i--) a[i]=0;//㣬׼ִdp1 cout<<"\nf(n)="<<dp1(n)<<endl; for(i=n ;i>0 ;i--) //ٴβ鿴f(i) cout<<"a["<<i<<"]="<<a[i] <<endl; return 0; }
true
316f3c633c7e950448fa8e1d8e831283e40ec60c
C++
topcodingwizard/code
/zerojudge/a133.cpp
UTF-8
876
2.546875
3
[]
no_license
#include <stdio.h> #include <algorithm> using namespace std; #define MAX 105 int A[MAX], B[MAX]; int dp[MAX][MAX]; int main() { int N1, N2, count = 0; while (scanf("%d%d", &N1, &N2) && N1 && N2) { // input------------------------------------------ for (int i = 0; i < N1; i++) scanf("%d", &A[i]); for (int i = 0; i < N2; i++) scanf("%d", &B[i]); // LCS-------------------------------------------- for (int i = 1; i <= N1; i++) { for (int j = 1; j <= N2; j++) { if (A[i - 1] == B[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); } } // output------------------------------------------ printf("Twin Towers #%d\nNumber of Tiles : %d\n", ++count, dp[N1][N2]); } }
true
fe675ac8b989584466480b9c8e474486e6dfb5f7
C++
larspm/optfir
/src/filters.cpp
UTF-8
2,766
3.09375
3
[]
no_license
#include <cmath> #include <vector> #include <string> #include <complex> #include <numeric> #include "filters.h" namespace optfir { double signum(double x) { if (x<0) return -1; if (x>0) return 1; return 0; } FirFilter::FirFilter(unsigned int N, const double* coeffs) : m_order(N) , m_rank(N) , m_h(m_rank, 0) { if (coeffs != 0) { for (unsigned int i = 0; i < m_rank; i++) { m_h[i] = coeffs[i]; } } } unsigned int FirFilter::getOrder() const { return m_order; } unsigned int FirFilter::getRank() const { return m_rank; } double& FirFilter::operator[](unsigned int i) { if (i >= m_order) { throw std::string("index too large"); } return m_h[i]; } const double& FirFilter::operator[](unsigned int i) const { // Cast to mutable so we get the correct operator, // which is ok since we return const reference. return const_cast<FirFilter*>(this)->operator[](i); } void FirFilter::operator=(const double* h) { for (unsigned int i = 0; i < m_rank; i++) { m_h[i] = h[i]; } } void FirFilter::operator=(const std::vector<double>& h) { if (m_h.size() != h.size()) { throw std::string("size mismatch"); } m_h = h; } double FirFilter::getAmplitudeResponse(double w) const { std::complex<double> res(0); const std::complex<double> i(0.0, 1.0); for (unsigned int n = 0; n < m_order; n++) { res += operator[](n) * std::exp(-i * w * (double)(n)); } return std::abs(res); } SymmetricFirFilter::SymmetricFirFilter(unsigned int N, const double* coeffs) : FirFilter((unsigned int)ceil((double)N/2), coeffs) { m_order = N; } double& SymmetricFirFilter::operator[](unsigned int i) { if (i >= m_order) { throw std::string("index too large"); } if (i < m_rank) { return m_h[i]; } else { return m_h[m_order - i - 1]; } } SymmetricFirFilterForcedDc::SymmetricFirFilterForcedDc(double dcGain, unsigned int N, const double* coeffs) : FirFilter((unsigned int)floor((double)N/2), coeffs) , m_dcGain(dcGain) { if ( (N & 0x1) == 0) { throw std::string("SymmetricFirFilterForcedDc not implemented for N even"); } m_order = N; } double& SymmetricFirFilterForcedDc::operator[](unsigned int i) { if (i >= m_order) { throw std::string("index too large"); } if (i < m_rank) { return m_h[i]; } else if (i == m_rank) { m_tempForReturn = m_dcGain - 2 * std::accumulate(m_h.begin(), m_h.end(), 0.0); return m_tempForReturn; } else { return m_h[m_order - i - 1]; } } }
true
cb55fb600a8851cd5821f86379714bcb8940ab78
C++
abhisheksawarkar/Thesis_Project
/Final_code_receiver_on_UGV/Final_code_receiver_on_UGV.ino
UTF-8
1,376
2.515625
3
[]
no_license
#include <Servo.h> Servo myservo; void setup() { myservo.attach(9); // put your setup code here, to run once: Serial.begin(9600); myservo.write(90); } int acc=0; int magneto=0; String input_acc="",input_magneto=""; char temp =' '; void loop() { // put your main code here, to run repeatedly: if (Serial.available() > 0) { temp = Serial.read(); if(temp=='a') { while(temp!='m') { temp = Serial.read(); if ((temp >= 48 && temp < 58)) { input_acc += temp; //Serial.println("input"); } } delay(10); acc = input_acc.toInt(); delay(10); // Serial.println(input); input_acc=""; //delay(10); } if(temp=='m') { while(temp!='\n') { temp = Serial.read(); if ((temp >= 48 && temp < 58)) { input_magneto += temp; //Serial.println("input"); } } delay(10); magneto = input_magneto.toInt(); delay(10); //Serial.println(input); input_magneto=""; } temp=' '; Serial.print(acc); Serial.print('\t'); Serial.println(magneto); delay(100); } }
true
1f3afa22b547fe0fb3473a6a5b145f663135f317
C++
chgogos/oop
/lc/live_coding_20201110e.cpp
UTF-8
1,199
3.203125
3
[ "MIT" ]
permissive
#include <iostream> // #include <stdlib.h> #include <cstdlib> using namespace std; int main() { // ------------------- δέσμευση/αποδέσμευση 1 θέσης μνήμης στη C++ int *p = new int; *p = 7; cout << *p << endl; delete p; // ------------------- δέσμευση/αποδέσμευση 1 θέσης μνήμης στη C int *p2 = (int *)malloc(sizeof(int)); *p2 = 7; cout << *p2 << endl; free(p2); // ------------------- δέσμευση/αποδέσμευση 10 θέσεων μνήμης στη C++ int *a = new int[10]; for (int i = 0; i < 10; i++) { a[i] = 42; // *(a+i) = 42; } for (int i = 0; i < 10; i++) { cout << a[i] << " "; } cout << endl; delete[] a; // ------------------- δέσμευση/αποδέσμευση 10 θέσεων μνήμης στη C int *b = (int *)malloc(sizeof(int) * 10); for (int i = 0; i < 10; i++) { b[i] = 42; } for (int i = 0; i < 10; i++) { cout << b[i] << " "; } cout << endl; free(b); } /* 7 7 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 */
true
0a8dea2f9728d4ee1e2bcdd684192a3fddb7137b
C++
bettle123/music_recognization
/music_simulation_3D/DemoFramework/DrawModeNode.h
UTF-8
1,351
3.015625
3
[]
no_license
#pragma once #include "OpenGL.h" #include "StateNodeBase.h" #include <string> namespace Crawfis { namespace Graphics { enum DrawModeType { SOLID, WIREFRAME, POINTS }; // // Concrete implementation of IStateNode that sets // the OpenGL polygon mode (the draw mode). // This probably should have been 3 classes for readability. // class DrawModeNode : public StateNodeBase { public: // // Constructor. All sub-classes require a name. // DrawModeNode(std::string name, ISceneNode* subject, DrawModeType drawType = DrawModeType::SOLID) : StateNodeBase(name, subject) { this->drawType = drawType; } // // Apply the Draw mode. // virtual void Apply() { switch (drawType) { case SOLID: glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); break; case WIREFRAME: glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); break; case POINTS: glPolygonMode( GL_FRONT_AND_BACK, GL_POINT ); break; } } // // Remove or undo the application of the draw mode. // virtual void Unapply() { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } // // Set the Drawmode to the desired state on the next redraw. // void setDrawMode(DrawModeType drawType) { this->drawType = drawType; } private: DrawModeType drawType; }; } }
true
6379643a4a0f48cf7f64500a3cd3abb97db28109
C++
anishaagg/CIS-PSU
/cs162_lab2.cpp
UTF-8
2,156
3.921875
4
[]
no_license
//Anisha Aggarwal, CS162 //To compute wage for each employee //Be able to gather the employee's initials and make them capitalized. //Then input their hourly wage and how many hours they have worked //in order to calculate how much they have earned. //If there is an increase in cost of living then change the amount of //money they earn. //Be able to calculate the earnings for other employees as well. #include <iostream> using namespace std; int main() { char more_employee; //are there any more employees after first person? do { char f_initial; //first initial char m_initial; //middle initial char l_initial; //last initial float hourly_wage; //the hourly wage for employee int hours_worked; //number of hours worked char col_applied; //to determine if cost of living increase is to be applied float col_increase; // what the cost of living increase is cout << "What is your first initial?" <<endl; cin >> f_initial; cout << "What is your middle initial?" <<endl; cin >> m_initial; cout << "What is your last initial?" <<endl; cin >> l_initial; f_initial = toupper(f_initial); m_initial = toupper(m_initial); l_initial = toupper(l_initial); cout << f_initial; cout << m_initial; cout << l_initial << endl; do { cout << "What is the hourly wage?" <<endl; cin >> hourly_wage; cout << "How many hours has the employee worked?" <<endl; cin >> hours_worked; } while (hourly_wage <= 0 || hours_worked <= 0); cout << "The hourly wage is $"; cout << hourly_wage <<endl; cout << "The employee has worked is "; cout << hours_worked; cout << " hours" <<endl; cout << "Is there a cost of living increase? (Y or N)" <<endl; cin >> col_applied; if (col_applied == 'Y' || col_applied == 'y') { cout << "What is the increase in cost of living?" <<endl; cin >> col_increase; cout << "You have earned $"; cout << hourly_wage * hours_worked * col_increase <<endl; } else { cout << "You have earned $"; cout << hourly_wage * hours_worked <<endl; } cout << "Are there more employees?(Y or N)" <<endl; cin >> more_employee; } while (more_employee == 'Y' || more_employee == 'y'); return 0; }
true
74ddee09b8973a7fe3c3690b86f9d1321c51e7ca
C++
JosephTesta/c-2017S
/class_11/bits.cpp
UTF-8
983
3.265625
3
[]
no_license
//these operations such as the dividing are faster than regular dividing int main() { //32 bit operations for any int int a = 3 & 5; //bitwise AND 000000011 & 0000000101 //0000000011 //0000000101 //============ //0000000001 = 1 int b = 3 | 5; //bitwise OR //0000000011 //0000000101 //============ //0000000111 = 7 int c = 3 ^ 5; //bitwise XOR //0000000011 //0000000101 //============ //0000000110 = 6 int d = ~3; // NOT //00000000000000000000000000000011 //11111111111111111111111111111100 int e = 1 << 5; // left shift equivalent to mult by 2 to the k. mult by 2^5 = 32 // 00000000000000000001 // 00000000000000100000 int f = 1024 >> 3 // right shift equivalent to /3 to the k // 000000000000010000000000 // 000000000000000010000000 int g = 5; g <<= 2; //there are 12 op= types += -= *= /= %= &= |= ^= <<= >>= and some 2 others // x = x OP y ==> x OP= y int x = 192; const int m = 16*1024*1024/3; x /= 3; //compiler might do x* m >> 24 }
true
52b7e64ebd712a425c28fce36f747db381cfaffb
C++
BugShan/bugshan
/include/bugshan/BugShan.h
UTF-8
678
3.015625
3
[]
no_license
#ifndef _BUGSHAN_BUGSHAN_H_ #define _BUGSHAN_BUGSHAN_H_ #define NULLPTR 0 #define NULL 0 /** * Returns value with bit x set (2^x) */ #define BIT(x) (1 << (x)) namespace BugShan { /** * safe delete pointer * @param ptr: the poiter to delete, and ptr will be assigned to NULLPTR */ template<typename T> inline void Delete(T*& ptr) { if(ptr) { delete ptr; ptr = NULLPTR; } } /** * safe delete array pointer * @param ptr: the poiter to delete, and ptr will be assigned to NULLPTR */ template<typename T> inline void DeleteArr(T*& ptr) { if(ptr) { delete[] ptr; ptr = NULLPTR; } } };//namespace BugShan #endif//_BUGSHAN_BUGSHAN_H_
true
52fe7cf091f935e877154f958a4e0655f05bfdc0
C++
MikeGWem/ArduinoSudoku
/SudokuWiFi/SudokuWiFi.ino
UTF-8
3,658
2.734375
3
[]
no_license
#define BUFF_SIZE 200 #define BUFF_LIMIT 199 #include <WiFiNINA.h> #include "Secret.h" #include "Sudoku.h" #include <malloc.h> extern char _end; extern "C" char *sbrk(int i); char buffer[BUFF_SIZE]; const long timeOut = 500; unsigned long waitStart; int charCount; const char* mySSID = SECRET_SSID; const char* myPass = SECRET_PASSWORD; const char getRequest[] = "GET /"; WiFiServer server(80); // port 80 is standard WiFiClient client; void setup() { Serial.begin(115200); while (!Serial) {} Sudoku::init(); connectToWiFi(); server.begin(); // start the server } void connectToWiFi() { if (WiFi.status() != WL_CONNECTED) { while (WiFi.begin(mySSID, myPass) != WL_CONNECTED) { delay(500); } Serial << "WiFi connected\n"; Serial << "Local IP: " << WiFi.localIP() << '\n'; } } void serveAjax() { bool error = false; char puzzle[82]; unsigned long tStart = millis(); char* strt = strstr(buffer, "ajax/?"); if(strt) { strt += 6; strncpy(puzzle, strt, 81); //Serial << puzzle << '\n'; Sudoku::maxCount = Sudoku::totalInstances = 0; tStart = millis(); Sudoku s(puzzle); if(!s.hasError()) { auto S = solve(&s); if(S) { String sp = S->toString(); strcpy(puzzle, sp.c_str()); } else { strncpy(puzzle, "No solution found", 81); error = true; } } else { // return error for bad puzzle error = true; strncpy(puzzle, "Invalid puzzle", 81); } } else { strncpy(puzzle, "Puzzle not found", 81); error = true; } formatJSON(puzzle, millis() - tStart, error); client << buffer << '\n'; // return JSON to client clearBuffer(); //Serial << "Free memory: " << freeRam() << '\n'; } void formatJSON(char* puzzle, int elapsed, bool error) { // insert JSON format response into buffer String s("{\"solved\": \""); s += String(puzzle); s += String("\", \"msecs\": "); s += String(elapsed); s += String(", \"max\": "); s += String(Sudoku::maxCount); s += String(", \"tot\": "); s += String(Sudoku::totalInstances); s += String(", \"error\": "); s += String((error ? "true" : "false")); s += String("}"); strncpy(buffer, s.c_str(), BUFF_SIZE); } void loop() { client = server.available(); if(client) { waitStart = millis(); clearBuffer(); while (client.connected()) { if(client.available()) { char c = client.read(); if(c == '\n' || c == '\r'){ if(strncmp(getRequest, buffer, 5) == 0) { switch(buffer[5]) { case ' ': // initial get request sendHTML(); break; case 'a': serveAjax(); default: Serial << buffer << '\n'; break; } } break; // escape while loop to close connection } else { if(charCount <= BUFF_LIMIT) { buffer[charCount] = c; charCount++; } } } else { if((unsigned long)millis() - waitStart >= timeOut) { Serial << "Out of time\n"; break; } } } client.flush(); client.stop(); } } int freeRam() { char *ramstart=(char *)0x20070000; char *ramend=(char *)0x20088000; char *heapend=sbrk(0); register char * stack_ptr asm ("sp"); struct mallinfo mi=mallinfo(); return stack_ptr - heapend + mi.fordblks; // mi.uordblks would return ram used // ramend - stack_ptr would return stack size }
true
0dfe5575ab9d25848c70fdce3bac8cea3b80e32d
C++
chris-hong/basic_algorithm
/dp/11048_이동하기/11048_이동하기/main.cpp
UHC
1,534
3.3125
3
[]
no_license
#include <iostream> using namespace std; int Max3(int a, int b, int c) { int max = a; if (max < b) max = b; if (max < c) max = c; return max; } int Max2(int a, int b) { if (a > b) return a; else return b; } int D[1001][1001]; int C[1001][1001]; //int main() { // int N, M; // cin >> N; cin.get(); // cin >> M; cin.get(); // // for (int i = 1; i <= N; i++) { // for (int j = 1; j <= M; j++) { // cin >> C[i][j]; cin.get(); // } // } // // for (int i = 1; i <= N; i++) { // for (int j = 1; j <= M; j++) { // // D[i][j] = Max3(D[i - 1][j - 1], D[i - 1][j], D[i][j - 1]) + C[i][j]; // // /* // ִ밪 ϴ .. // N[N][M] -> [N+1][M+1] // 밢 ̵ ʾƵ ȴ. // ֳϸ.. // 밢 ̵ + or + ۰ų ̴. // */ // D[i][j] = Max2(D[i - 1][j], D[i][j - 1]) + C[i][j]; // } // } // // cout << "=> " << D[N][M] << endl; // // getchar(); // return 0; // //} // TOP-DOWN(͸ Ǯ) int MoreCandy(int i, int j) { if (i == 1 && j == 1) { return C[1][1]; } if (i < 1 || j < 1) { return 0; } if (D[i][j] > 0) { return D[i][j]; } D[i][j] = Max2(MoreCandy(i - 1, j), MoreCandy(i, j - 1)) + C[i][j]; return D[i][j]; } int main() { int N, M; cin >> N; cin.get(); cin >> M; cin.get(); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { cin >> C[i][j]; cin.get(); } } cout << "=> " << MoreCandy(N, M) << endl; getchar(); return 0; }
true
693597a764045c5726ad5f9797b289fd6adee65a
C++
Wizmann/ACM-ICPC
/Codeforces/Codeforces Round #251/439D.cc
UTF-8
1,450
2.5625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; #define print(x) cout << x << endl #define input(x) cin >> x typedef long long llint; const int MAXN = 1000000001; const int SIZE = 123456; int n, m; vector<int> A[2]; llint tri(llint val) { llint step = 0; for (int i = 0; i < 2; i++) { for (auto iter = A[i].begin(); iter != A[i].end(); ++iter) { int u = *iter; if (i == 0 && u < val) { step += val - u; } if (i == 1 && u > val) { step += u - val; } } } return step; } llint solve() { llint l = 0, r = MAXN; while (l < r) { llint lt = (l + r) / 2; llint rt = (lt + r) / 2; llint ltVal = tri(lt); llint rtVal = tri(rt); if (ltVal <= rtVal) { r = rt; } else { l = lt; } } return tri(l + 1); } int main() { freopen("input.txt", "r", stdin); int a; while (input(n >> m)) { for (int i = 0; i < 2; i++) { A[i].clear(); } for (int i = 0; i < n; i++) { scanf("%d", &a); A[0].push_back(a); } for (int i = 0; i < m; i++) { scanf("%d", &a); A[1].push_back(a); } print(solve()); } return 0; }
true
dbe5041135fc20c9720df30a1b7238405a5d0cc7
C++
Kotyarich/BMSTU-4th-semestr
/oop/lab4/objects/mesh/mesh.cpp
UTF-8
777
3.015625
3
[]
no_license
#include "mesh.h" namespace objects { void Mesh::addPoint(math::Point &p) { _points.push_back(p); } void Mesh::addEdge(size_t first, size_t second) { if (first < 0 || second < 0 || first >= _points.size() || second >= _points.size()) { throw exceptions::ModelBuildException("Wrong point number"); } _edges.emplace_back(first, second); } void Mesh::transform(const std::shared_ptr<math::Matrix> matrix) { for (auto &point: _points) { point.transform(matrix); } } std::vector<std::pair<math::Point, math::Point> > Mesh::getLines() { std::vector<std::pair<Point, Point>> lines; for (auto &edge: _edges) { lines.emplace_back(_points[edge.first], _points[edge.second]); } return lines; } } // namespace objects
true
3bd229a07e796bd063f8895d5fc47345ed8409ef
C++
warrenlp/2015VisionCode
/networktables/include/networktables2/WriteManager.h
UTF-8
2,186
2.625
3
[ "MIT" ]
permissive
/* * WriteManager.h * * Created on: Sep 25, 2012 * Author: Mitchell Wills */ #ifndef WRITEMANAGER_H_ #define WRITEMANAGER_H_ class AbstractNetworkTableEntryStore; class WriteManager; #include "networktables2/thread/PeriodicRunnable.h" #include "networktables2/OutgoingEntryReceiver.h" #include "networktables2/thread/NTThread.h" #include "networktables2/thread/NTThreadManager.h" #include "networktables2/FlushableOutgoingEntryReceiver.h" #include "networktables2/NetworkTableEntry.h" #include <queue> #include "OSAL/Synchronized.h" /** * A write manager is a {@link IncomingEntryReceiver} that buffers transactions and then and then dispatches them to a flushable transaction receiver that is periodically offered all queued transaction and then flushed * * @author Mitchell * */ class WriteManager : public OutgoingEntryReceiver, public PeriodicRunnable{ private: const static size_t queueSize = 500; NTReentrantSemaphore transactionsLock; NTThread* thread; FlushableOutgoingEntryReceiver& receiver; NTThreadManager& threadManager; AbstractNetworkTableEntryStore& entryStore; unsigned long keepAliveDelay; volatile std::queue<NetworkTableEntry*>* incomingAssignmentQueue; volatile std::queue<NetworkTableEntry*>* incomingUpdateQueue; volatile std::queue<NetworkTableEntry*>* outgoingAssignmentQueue; volatile std::queue<NetworkTableEntry*>* outgoingUpdateQueue; unsigned long lastWrite; public: /** * Create a new Write manager * @param receiver * @param threadManager * @param transactionPool * @param entryStore */ WriteManager(FlushableOutgoingEntryReceiver& receiver, NTThreadManager& threadManager, AbstractNetworkTableEntryStore& entryStore, unsigned long keepAliveDelay); virtual ~WriteManager(); /** * start the write thread */ void start(); /** * stop the write thread */ void stop(); void offerOutgoingAssignment(NetworkTableEntry* entry); void offerOutgoingUpdate(NetworkTableEntry* entry); /** * the periodic method that sends all buffered transactions */ void run(); }; #endif /* WRITEMANAGER_H_ */
true
d52a91cd3f47228df5cc7bc715672e040f9077f5
C++
sPHENIX-Collaboration/coresoftware
/offline/packages/bbc/BbcOut.cc
UTF-8
2,528
2.546875
3
[]
no_license
#include "BbcOut.h" #include "BbcReturnCodes.h" #include <cmath> #include <iostream> void BbcOut::identify(std::ostream& os) const { os << "virtual BbcOut object" << std::endl; return; } void BbcOut::Reset() { std::cout << "ERROR BbcOut: Reset() not implemented by daughter class" << std::endl; return; } int BbcOut::isValid() const { virtual_warning("isValid()"); return 0; } float BbcOut::get_VertexPoint() const { virtual_warning("get_VertexPoint()"); return NAN; } float BbcOut::get_dVertexPoint() const { virtual_warning("get_dVertexPoint()"); return NAN; } float BbcOut::get_TimeZero() const { virtual_warning("get_TimeZero()"); return NAN; } //__________________________________________ float BbcOut::get_dTimeZero() const { virtual_warning("get_dTimeZero()"); return NAN; } //__________________________________________ void BbcOut::set_TimeZero(const float /*unused*/, const float /*unused*/) { virtual_warning("set_TimeZero(const float t0, const float t0err)"); return; } //__________________________________________ void BbcOut::set_Vertex(const float /*unused*/, const float /*unused*/) { virtual_warning("set_Vertex(const float vtx, const float vtxerr)"); return; } //__________________________________________ void BbcOut::set_dZVertex(const float /*unused*/) { virtual_warning("set_dZVertex(const float vtxerr)"); return; } //________________________________________________________________ void BbcOut::AddBbcNS(const int /*nBbc*/, const short /*npmt*/, const float /*energy*/, const float /*timing*/) { virtual_warning("AddBbcNS(const int iBBC, const short npmt, const float energy, const float timing)"); return; } short BbcOut::get_nPMT(const int /*nBbc*/) const { virtual_warning("get_nPMT(const int nBbc)"); return BbcReturnCodes::BBC_INVALID_SHORT; } float BbcOut::get_nCharge(const int /*nBbc*/) const { virtual_warning("get_nCharge(const int nBbc)"); return NAN; } float BbcOut::get_Timing(const int /*nBbc*/) const { virtual_warning("get_Timing(const int nBbc)"); return NAN; } void BbcOut::virtual_warning(const std::string& funcsname) const { std::cout << "BbcOut::" << funcsname << " is virtual, doing nothing" << std::endl; return; } void BbcOut::FillFromClass(const BbcOut& old) { for (int iarm = 0; iarm < 2; iarm++) { AddBbcNS(iarm, old.get_nPMT(iarm), old.get_nCharge(iarm), old.get_Timing(iarm)); } set_TimeVertex(old.get_TimeZero(), old.get_dTimeZero(), old.get_VertexPoint(), old.get_dVertexPoint()); }
true
a3b00c0edc45646449acc612a916bd7f345e3432
C++
jacktianmo/dataframe
/chapt8/src/8_1.cpp
UTF-8
498
3.015625
3
[]
no_license
/* * 8_1.cpp * * Created on: 2014年11月9日 * Author: young */ #include<iostream> #include"d_sort.h" #include<stdlib.h> #include<vector> #include<stdio.h> using namespace std; void displayVector(const vector<int>& v); int main(){ int i; vector<int> intVector; for(i=0;i<50;i++) intVector.push_back(rand()%100); radixSort(intVector,2); displayVector(intVector); return 0; } void displayVector(const vector<int>& v){ int i; for(i=0;i<v.size();i++) cout<<v[i]<<" "; }
true
576d48c83a6deb7557c76867ac8a2380cf177b13
C++
JackGHopkins/CSC3221-Project-2
/CSC3221 Project 2/Collision.h
UTF-8
376
2.828125
3
[]
no_license
#pragma once #include "Circle.h" #include "Square.h" /// <summary> /// For checking collisions between Shapes. /// </summary> class Collision { public: void isCollision(Circle& c1, Circle& c2); void isCollision(Square& s1, Square& s2); void isCollision(Circle& c, Square& s); bool IsSameShapeCollide(float x1, float y1, float r1, float x2, float y2, float r2) const; };
true
bbbd72fb158eef6507f75e26700db168de30f85d
C++
IasonManolas/CompetitiveProgrammingCourse
/Lectures/19_knapsack.cpp
UTF-8
1,372
3.421875
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using namespace std; template <typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for (size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } template <> vector<std::pair<size_t, size_t>> get_input_sequence(size_t n) { vector<std::pair<size_t, size_t>> sequence(n); for (size_t i = 0; i < n; ++i) { cin >> sequence[i].first; cin >> sequence[i].second; } return sequence; } /*Space and time complexity is θ(n*s) *We fill matrix K such that K[i][j] represents the maximum profit with maximum weight j and using *the first i items. Thus in the end the bottom right cell contains the maximum value that can *be achieved with a bag of capacity s */ int main() { std::ios_base::sync_with_stdio(false); size_t s, n; cin >> s; cin >> n; auto v = get_input_sequence<std::pair<size_t, size_t>>(n); vector<vector<size_t>> K(n + 1, vector<size_t>(s + 1, 0)); for (size_t i = 0; i < n + 1; i++) { for (size_t j = 0; j < s + 1; j++) { if (i == 0 || j == 0) { K[i][j] = 0; } else if (j < v[i - 1].first) { K[i][j] = K[i - 1][j]; } else { K[i][j] = std::max(K[i - 1][j], K[i - 1][j - v[i - 1].first] + v[i - 1].second); } } } cout << K[n][s] << endl; }
true
041102abab0debdd3036e0ee4f412c97437c7f15
C++
rootkonda/LeetCode
/721. Accounts Merge.cpp
UTF-8
3,163
3.75
4
[]
no_license
/* Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. Note: The length of accounts will be in the range [1, 1000]. The length of accounts[i] will be in the range [1, 10]. The length of accounts[i][j] will be in the range [1, 30]. */ class Solution { public: vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) { unordered_map<string,vector<string>> graph; // Prepare a graph for each connected email address. Establish the link between the 1st email address to the rest. unordered_map<string,string> email_to_name; // For every email, store the name for later use. for(auto account : accounts) { for(int i=1;i<account.size();i++) { email_to_name[account[i]] = account[0]; graph[account[1]].push_back(account[i]); // If there are multiple emails related then they are added to the vector of emails. graph[account[i]].push_back(account[1]); } } vector<vector<string>> ans; unordered_map<string,bool> visited; // We are going to take each vertex and traverse all its edges and mark each vertex as visited to avoid duplicate work. for(auto vertex : graph) { if(!visited[vertex.first]) { vector<string> connected_emails{email_to_name[vertex.first]}; // Get the name stack<string> emails; // To traverse thru the edges emails.push(vertex.first); visited[vertex.first] = true; while(!emails.empty()) { string curr = emails.top(); connected_emails.push_back(curr); emails.pop(); for(auto edge : graph[curr]) { if(!visited[edge]) { emails.push(edge); visited[edge] = true; // We have to mark it as true so that when we go back again we shouldnt pick the same edge again or it goes in infinite loop. } } } sort(connected_emails.begin()+1,connected_emails.end()); // sort emails only ans.push_back(connected_emails); } } return ans; } };
true