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
aa7765942f3898836c51164b8c9611174b89a0e5
C++
EgbertHistorianPokling/redpolice
/Classes/LoseScene.cpp
UTF-8
685
2.59375
3
[]
no_license
#include"LoseScene.h" USING_NS_CC; Scene* LoseScene::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = LoseScene::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } bool LoseScene::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); Sprite* sprite = Sprite::create("lose.jpg"); sprite->setPosition(visibleSize.width / 2, visibleSize.height / 2); addChild(sprite, 1); }
true
fcb184ff384db52393d5cb6cc49380662e00e7f2
C++
TumbleJamie/CardGame
/Dragon.cpp
UTF-8
325
2.671875
3
[]
no_license
#include "Dragon.h" Dragon::Dragon() { } int Dragon::GetType() { return type; } string Dragon::GetName() { return name; } int Dragon::GetHealth() { return health; } int Dragon::GetAttack() { return attack; } void Dragon::SetHealth(int enemyAttack) { health = health - enemyAttack; }
true
7c57e6b9166ef9fe84b9ea9b02d3cb1e8e7dbdc8
C++
forbidden404/algorithms
/interview/getOdd.cpp
UTF-8
260
3.25
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int getOdd(vector<int>& arr) { int answer = 0; for (auto num : arr) answer ^= num; return answer; } int main() { vector<int> v{1, 2, 3, 1, 2, 3, 1}; cout << getOdd(v) << endl; return 0; }
true
62c8527067d3c0950435b3675ae838093cd5e8b8
C++
Flare-k/Algorithm
/동적프로그래밍/파스칼의삼각형_DP_16395.cpp
UTF-8
524
2.75
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; // Dynamic programming으로 풀이하기 const int MAX = 31; int n, k; int dp[MAX][MAX]; int comb(int n, int k) { if (n == k || k == 0) return 1; int result = dp[n][k]; if (result != -1) return result; result = comb(n - 1, k - 1) + comb(n - 1, k); return result; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> k; memset(dp, -1, sizeof(dp)); cout << comb(n - 1, k - 1); return 0; }
true
c58aaa92600207386bbebf85e2cb2a5698be5667
C++
pedguifil/Lucity
/src/Monster.cpp
UTF-8
562
2.515625
3
[]
no_license
#include "Monster.h" #include "GameData.h" Monster::Monster(GameObject& associated, Personality p) : NPC(associated, p) { SetHealth(3); rawr = false; GameData::nMonsters++; GameData::nCivilians--; } Monster::~Monster() { GameData::nMonsters--; GameData::nCivilians++; } void Monster::Update(float dt) { if(!rawr) NPC::Update(dt); } void Monster::NotifyCollision(GameObject& other) { if(!rawr) NPC::NotifyCollision(other); } bool Monster::Is(std::string type) { return (type == "Monster" || Character::Is(type)); }
true
39c61b9714136a96cb9cdcdde37a56b663837f04
C++
zaifoski/programmazione1
/argcMax.cc
UTF-8
451
3.171875
3
[]
no_license
using namespace std; #include <iostream> //cin, cout #include <limits.h> //INT_MAX, INT_MIN #include <stdlib.h> //atoi int main(int argc,char* argv[]) { //puntatore a lista di puntatori che sono stringhe, arrays di chars //argc è il numero di inputs, argv li contiene int max = INT_MIN; for (int i=0; i<argc; i++){ int arg = atoi(argv[i]);//atoi li converte in numeri if(arg > max){ max = arg; } } cout << max << endl; }
true
aa01617ec2e15b28dd6eb465822e9e6fbd95377d
C++
ElitsaMilusheva/oop-practicum-2017
/exercises/10/main.cpp
UTF-8
615
3.203125
3
[]
no_license
#include <iostream> #include "person.h" #include "student.h" #include "worker.h" #include "surgeon.h" #include "vet.h" int main() { Person petar("Petar Petrov", 21); petar.print(); Student ivan("Ivan Dobrev", 22, "Journalism", 6); ivan.print(); Worker georgi("Georgi Georgiev", 27, 200, 40); georgi.print(); Surgeon surgeon("Maria", 17, "Cardiology"); std::cout << surgeon; std::cout << surgeon.chance("Cardiology") << '\n' << surgeon.chance("Podiatry") << '\n'; Vet vet("Martin", 20, "Dog"); std::cout << vet; std::cout << vet.chance("Dog") << '\n' << vet.chance("Cat") << '\n'; return 0; }
true
9e4a4d31d0e1717b3a2ddd189f31f5d4c6eb6b9c
C++
Suhendarprogrammer/PROGRAM-VALIDASI-PEMBAGIAN-TIDAK-DENGAN-NOL
/main.cpp
UTF-8
629
3.109375
3
[]
no_license
#include <iostream> using namespace std; int main() { int a,b,hasil; cout<<"**********PROGRAM VALIDASI TIDAK DENGAN NOL**********\n"; cout<<"=====================================================\n"; cout<<"\nMasukkan Angka Yang Akan Dibagi : "; cin>>a; cout<<"\nMasukkan Angka Pembaginya : "; cin>>b; cout<<"\n========================================\n"; if(b==0){ cout<<"\nBilangan Pembaginya Tidak Boleh Dengan Nol : "; } else { hasil=(a/b); } cout<<"\nMaka, Hasilnya Adalah : "<<hasil<<"\n"; return 0; }
true
6f62db9acb43e3eea94ef9c91db835e5b7724760
C++
Lakshya2610/Ray-Tracer
/Ray-Tracer/Light.h
UTF-8
1,154
2.859375
3
[]
no_license
#pragma once #include "Variables.h" #include <string> #include "Color.h" using namespace std; class Light { public: std::string name; float intensity = 1; void setIntensity(float _intensity) { intensity = _intensity; } virtual ~Light() {}; }; class DirectionalLight:public Light { public: std::string name = "directional"; Color color = Color(0, 0, 0); vec3 pos = vec3(0,0,0); float attenuation[3] = { 1, 0, 0 }; DirectionalLight(Color _color, vec3 _pos) { color = _color; pos = _pos; } ~DirectionalLight() {}; }; class PointLight :public Light { public: std::string name = "point"; Color color = Color(0, 0, 0); vec3 pos = vec3(0, 0, 0); float attenuation[3] = { 0, 1, 0 }; PointLight(Color _color, vec3 _pos) { color = _color; pos = _pos; } ~PointLight() {}; }; class AreaLight :public Light { public: string name = "area light"; Color color = Color(0, 0, 0); vec3 pos = vec3(0, 0, 0); float attenuation[3] = { 0, 0, 1 }; float radius = 0.0; vec3 dirn = vec3(0,0,0); Shape *q; AreaLight(Color _color, Quad *_q) { color = _color; q = _q; pos = (((Quad*)q)->v1 + ((Quad*)q)->v3) / 2.0; } ~AreaLight() {}; };
true
78f1926c790126f1f568cd0ce7bbd80c588314b6
C++
mayank-bhardwa/CodingLibrary
/DynamicProgramming/Basic/Fibonacci/fibonacci.cpp
UTF-8
262
2.765625
3
[]
no_license
#include<iostream> using namespace std; int fibo(int n){ int d[n+2]; d[0]=0; d[1]=1; for(int i=2;i<=n;i++){ d[i]=d[i-1]+d[i-2]; } return d[n]; } int main() { int n; cin>>n; cout<<fibo(n); return 0; }
true
b3ad6003c1b7422a14c8b0fa58c529f207126e49
C++
LauZyHou/Algorithm-To-Practice
/AcWing/LeetCode究极班/576.cpp
UTF-8
1,186
2.53125
3
[ "MIT" ]
permissive
const int MOD = 1e9 + 7; class Solution { public: int findPaths(int n, int m, int N, int x, int y) { if (!N) return 0; vector<vector<vector<int>>> f(n, vector<vector<int>>(m, vector<int>(N + 1))); // 边界 for (int j = 0; j < m; j ++ ) { f[0][j][1] ++ ; f[n - 1][j][1] ++ ; } for (int i = 0; i < n; i ++ ) { f[i][0][1] ++ ; f[i][m - 1][1] ++ ; } // 方向 int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; // 先枚举路径长度k for (int k = 1; k <= N; k ++ ) for (int i = 0; i < n; i ++ ) for (int j = 0; j < m; j ++ ) for (int u = 0; u < 4; u ++ ) { // 四个方向 int a = i + dx[u], b = j + dy[u]; if (a >= 0 && a < n && b >= 0 && b < m) (f[i][j][k] += f[a][b][k - 1]) %= MOD; // 注意这里的写法技巧 } // 计算答案 int res = 0; for (int k = 1; k <= N; k ++ ) (res += f[x][y][k]) %= MOD; // 注意这里的写法技巧 return res; } };
true
9b1a7b958f93b7a31ad08c15dfcd7eca6b9d669b
C++
wkershaw/Dissertation
/CSC3223/DynamicWeather/Draw.cpp
UTF-8
2,409
2.890625
3
[]
no_license
#include "Draw.h" RenderObject* Draw::DrawPlane(Vector3 position, Vector2 scale, Vector4 colour) { OGLMesh* plane = new OGLMesh(); Vector3 bottomLeft = position + Vector3(scale.x / 2, 0, scale.y / 2); Vector3 bottomRight = position + Vector3(-scale.x / 2, 0, scale.y / 2); Vector3 topLeft = position + Vector3(scale.x / 2, 0, -scale.y / 2); Vector3 topRight = position + Vector3(-scale.x / 2, 0, -scale.y / 2); plane->SetVertexPositions({ bottomLeft, bottomRight, topLeft, topRight }); plane->SetVertexTextureCoords({ Vector2(0,0),Vector2(1,0), Vector2(0,1), Vector2(1,1)}); plane->SetPrimitiveType(GeometryPrimitive::TriangleStrip); plane->SetVertexColours({ colour,colour,colour,colour }); plane->UploadToGPU(); RenderObject* object = new RenderObject(plane); renderer->AddRenderObject(object); return object; } RenderObject* Draw::DrawPatchedPlane(Vector3 position, Vector2 scale, Vector4 colour) { OGLMesh* plane = new OGLMesh(); Vector3 bottomLeft = position + Vector3(scale.x / 2, 0, scale.y / 2); Vector3 bottomRight = position + Vector3(-scale.x / 2, 0, scale.y / 2); Vector3 topLeft = position + Vector3(scale.x / 2, 0, -scale.y / 2); Vector3 topRight = position + Vector3(-scale.x / 2, 0, -scale.y / 2); plane->SetVertexPositions({ bottomLeft, bottomRight, topLeft, topRight }); plane->SetVertexTextureCoords({ Vector2(0,0),Vector2(1,0), Vector2(0,1), Vector2(1,1) }); plane->SetPrimitiveType(GeometryPrimitive::Patches); plane->SetVertexColours({ colour,colour,colour,colour }); plane->UploadToGPU(); RenderObject* object = new RenderObject(plane); renderer->AddRenderObject(object); return object; } RenderObject* Draw::DrawCuboid(Vector3 position, Vector3 scale, Vector4 colour) { OGLMesh* cuboid = new OGLMesh("Cube.msh"); cuboid->SetPrimitiveType(GeometryPrimitive::Triangles); vector<Vector2> textureCoords = { Vector2(1,1),Vector2(1,0),Vector2(0,0),Vector2(0,0),Vector2(0,1),Vector2(1,1), }; vector<Vector4> colourCoords = vector<Vector4>(); for (int i = 0; i < cuboid->GetVertexCount(); i++) { colourCoords.emplace_back(colour); } cuboid->SetVertexColours(colourCoords); cuboid->SetVertexTextureCoords(textureCoords); cuboid->UploadToGPU(); RenderObject* object = new RenderObject(cuboid, Matrix4::Translation(position)); object->SetTransform(object->GetTransform() * Matrix4::Scale(scale)); renderer->AddRenderObject(object); return object; }
true
e49db2bd30e9d6d311a3d42a1941662fbd5327ec
C++
rkantYahoo/Fourier
/klotsky/kcount.cc
UTF-8
2,666
3.0625
3
[]
no_license
#include <iostream> #include <ctime> #include <set> #include "kcount.h" using namespace std; Board::Board() { for (int a = 0; a < NUM_CELLS; ++a) { config_[a] = 0; } } const int Board::CarryIndex() const { int index = NUM_CELLS - 1; while ((config_[index] == 2) && (index > 0)) { --index; } return index; } void Board::NextBoard() { int index = CarryIndex(); if (index == 5) { std::cout << "done "; std::cout << clock()/CLOCKS_PER_SEC << endl; } config_[index]++; for (int a = index + 1; a < NUM_CELLS; ++a) { config_[a] = 0; } } const bool Board::IsLastBoard() const { for (int a = 0; a < NUM_CELLS; ++a) { if (config_[a] != 2) { return false; } } return true; } void Board::Print() const { for (int a = 0; a < NUM_CELLS; ++a) { if ((a % COLS) == 0) { std::cout << endl; } std::cout << config_[a]; } std::cout << endl; } const bool Board::IsValidBoard() const { int counters[3] = {0, 0, 0}; int twos[4] = {0, 0, 0, 0}; int ones[6] = {0, 0, 0, 0, 0, 0}; for (int a = 0; a < NUM_CELLS; ++a) { counters[config_[a]]++; if (config_[a] == 2) { if (counters[2] > NUM_TWOS) { return false; } twos[counters[2] - 1] = a; } if (config_[a] == 1) { if (counters[1] > NUM_ONES) { return false; } ones[counters[1] - 1] = a; } } if ((counters[1] != NUM_ONES) || (counters[2] != NUM_TWOS)) { return false; } /* std::cout << twos[0] << twos[1] << twos[2] << twos[3] << endl; std::cout << ones[0] << ones[1] << ones[2] << ones[3] << ones[4] << ones[5] << endl; std::cout << counters[0] << " " << counters[1] << " " << counters[2] << endl;*/ if (((twos[1] - twos[0]) != 1) || ((twos[2] - twos[0]) != COLS) || ((twos[3] - twos[1]) != COLS)) { return false; } set<int> visited; for (int b = 0; b < NUM_ONES; ++b) { set<int>::iterator ones_indices = visited.find(ones[b]); if (ones_indices == visited.end()) { visited.insert(ones[b]); visited.insert(ones[b] + COLS); // std::cout << "inserted " << ones[b] << ones[b] + COLS << endl; } } if (visited.size() != NUM_ONES) { // std::cout << "ones problem " << visited.size() << endl; return false; } return true; } int main() { Board b; int count = 0; while (!b.IsLastBoard()) { if (b.IsValidBoard()) { // b.Print(); ++count; } b.NextBoard(); } int time_taken = clock()/CLOCKS_PER_SEC; std::cout << "total count = " << count << endl; std::cout << "time taken = " << time_taken << endl; return 0; }
true
8f342d0bed763a199f137826f1ea32f8f926fcd4
C++
liaoqidi/timberjack
/PantyHero/Classes/autostring.cpp
WINDOWS-1252
4,074
2.921875
3
[]
no_license
/** * Created by pk 2008.01.04 */ #include "autostring.h" #ifdef _WIN32 #include "global.h" #include "windows.h" #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4267) #endif autostring::autostring() : std::string() { init(); } autostring::autostring(const autostring& _Right) : std::string(_Right.c_str()) { init(); } autostring::autostring(const autostring& _Right, size_type _Roff, size_type _Count) : std::string(_Right.c_str(), _Roff, _Count) { init(); } autostring::autostring(const std::string& _Right) : std::string(_Right) { init(); } autostring::autostring(const std::string& _Right, size_type _Roff, size_type _Count) : std::string(_Right, _Roff, _Count) { init(); } autostring::autostring(const char* _Ptr) : std::string(_Ptr) { init(); } autostring::autostring(const char* _Ptr, size_type _Count) : std::string(_Ptr, _Count) { init(); } autostring::autostring(const char* _Ptr, size_type _Roff, size_type _Count) : std::string(_Ptr, _Roff, _Count) { init(); } autostring::autostring(char _Ch) : std::string(1, _Ch) { init(); } autostring::autostring(size_type _Count, char _Ch) : std::string(_Count, _Ch) { init(); } autostring::~autostring() { release(); } /* autostring& autostring::operator=(const autostring& _Right) { // assign _Right assign(_Right); return *this; } autostring& autostring::operator=(const std::string& _Right) { // assign _Right assign(_Right); return *this; } autostring& autostring::operator=(const char* _Ptr) { // assign [_Ptr, <null>) assign(_Ptr); return *this; } autostring& autostring::operator=(char _Ch) { // assign 1 * _Ch assign(1, _Ch); return *this; } autostring& autostring::operator+=(const autostring& _Right) { // append _Right append(_Right.c_str()); return *this; } autostring& autostring::operator+=(const std::string& _Right) { // append _Right append(_Right.c_str()); return *this; } autostring& autostring::operator+=(const char *_Ptr) { // append [_Ptr, <null>) append(_Ptr); return *this; } autostring& autostring::operator+=(char _Ch) { // append 1 * _Ch append((size_type)1, _Ch); return *this; } */ void autostring::init() { m_pUnicode = NULL; m_pAnsi = NULL; m_pUtf8 = NULL; } // void autostring::release() { safeDeleteArray(m_pUnicode); safeDeleteArray(m_pAnsi); safeDeleteArray(m_pUtf8); } wchar_t* autostring::ANSIToUnicode(const char *pszANSI) { safeDeleteArray(m_pUnicode); int nLen = ::MultiByteToWideChar(CP_ACP, 0, pszANSI, -1, NULL, 0); m_pUnicode = new wchar_t[nLen + 1]; memset(m_pUnicode, 0, (nLen + 1) * sizeof(wchar_t)); ::MultiByteToWideChar(CP_ACP, 0, pszANSI, -1, (LPWSTR)m_pUnicode, nLen); return m_pUnicode; } char* autostring::UnicodeToANSI(const wchar_t *pszUnicode) { safeDeleteArray(m_pAnsi); int nLen = WideCharToMultiByte(CP_ACP, 0, pszUnicode, -1, NULL, 0, NULL, NULL); m_pAnsi = new char[nLen + 1]; memset(m_pAnsi, 0, sizeof(char)* (nLen + 1)); ::WideCharToMultiByte(CP_ACP, 0, pszUnicode, -1, m_pAnsi, nLen, NULL, NULL); return m_pAnsi; } wchar_t* autostring::UTF8ToUnicode(const char *pszUTF8) { safeDeleteArray(m_pUnicode); int nLen = ::MultiByteToWideChar(CP_UTF8, 0, pszUTF8, -1, NULL, 0); m_pUnicode = new wchar_t[nLen + 1]; memset(m_pUnicode, 0, (nLen + 1) * sizeof(wchar_t)); ::MultiByteToWideChar(CP_UTF8, 0, pszUTF8, -1, (LPWSTR)m_pUnicode, nLen); return m_pUnicode; } char* autostring::UnicodeToUTF8(const wchar_t *pszUnicode) { safeDeleteArray(m_pUtf8); int nLen = WideCharToMultiByte(CP_UTF8, 0, pszUnicode, -1, NULL, 0, NULL, NULL); m_pUtf8 = new char[nLen + 1]; memset(m_pUtf8, 0, sizeof(char)* (nLen + 1)); ::WideCharToMultiByte(CP_UTF8, 0, pszUnicode, -1, m_pUtf8, nLen, NULL, NULL); return m_pUtf8; } char* autostring::ANSIToUTF8(const char *pszANSI) { ANSIToUnicode(pszANSI); UnicodeToUTF8(m_pUnicode); return m_pUtf8; } char* autostring::UTF8ToANSI(const char *pszUTF8) { UTF8ToUnicode(pszUTF8); UnicodeToANSI(m_pUnicode); return m_pAnsi; } #ifdef _MSC_VER # pragma warning(pop) #endif #endif // _WIN32
true
e00046231597d1a3b7384d10e904e1dc49537296
C++
SEOMINGEOL/IOCP
/IOCP/IOCPCommon.h
UHC
1,307
2.671875
3
[]
no_license
#pragma once #ifndef __IOCP_COMMON_H__ #define __IOCP_COMMON_H__ #define MAX_BUF_SIZE 1024 #define SERVER_PORT 3500 #include <iostream> #include <string> #include <WinSock2.h> #include <mutex> static std::mutex log_mutex; static std::mutex user_mutex; enum { Normal = 0, Waring, Error }; enum { WinSock = 0, INVALID, BIND, LISTEN, ACCEPT }; /* //̻ ּ namespace Log_Form { static std::string Format(std::string log_data, int error_code) { std::string log; log = log_data + "(Error Code : " + std::to_string(error_code) + ")"; return log; } } static void Log(int level, std::string log_data) { std::string log; switch (level) { case Normal: log = "(Normal)Log : "; break; case Waring: log = "(Waring)Log: "; break; case Error: log = "(Error)Log : "; break; } log += log_data; std::cout << log << std::endl; } */ static void Log_printf(int level, const char* log_data, ...) { log_mutex.lock(); va_list va; char buf[MAX_BUF_SIZE]; va_start(va, log_data); vsnprintf_s(buf, MAX_BUF_SIZE, log_data, va); va_end(va); std::cout << buf << std::endl; log_mutex.unlock(); } #endif // !__IOCP_COMMON__
true
2c2af188493babff6d6a65b6181c70d2a3a16b58
C++
Ilidur/Stiffy
/Stiffy.ino
UTF-8
1,812
3
3
[]
no_license
#include <Servo.h> class ServoData { public: int m_iPortNumber; int m_iStartOffset; ServoData(int iPortNumber, int iStartOffset = 90 ) { m_iPortNumber = iPortNumber; m_iStartOffset = iStartOffset; } }; //Servo 2 [60-160] //Servo 3 [60-150] ServoData axServoData[ ] = { {3,180}, {5,110}, {6,50}, {9,110}}; int iButtonPin = 2; const int servoCount = 4; Servo axServos[5]; int pos = 0; // variable to store the servo position void setup() { for (int i =0; i < servoCount; i++) { axServos[i].attach(axServoData[i].m_iPortNumber); } pinMode(iButtonPin, INPUT); } void loop() { // Go to stand-by position for (int i =0; i <servoCount ; i++) { axServos[i].write(axServoData[i].m_iStartOffset); } //Wait for button to be pressed int iButtonState; do { iButtonState = digitalRead(iButtonPin); } while (iButtonState == LOW ); // Move into max horizontal height position for (pos = 0; pos <= 90; pos += 1) { axServos[1].write(axServoData[1].m_iStartOffset+pos); delay(100); } // Move to grab position for (pos = 90; pos >= 28; pos -= 1) { axServos[2].write(pos); axServos[1].write(90+pos); // Minimum delay to minimize whiplash and stop hitting the table. delay(200); } // Grab object delay(1000); for (pos = 100; pos >= 20; pos -= 1) { axServos[0].write(pos); delay(100); } // Raise to max horizontal height for (pos = 28; pos <= 90; pos += 1) { axServos[2].write(pos); axServos[1].write(90+pos); delay(100); } // Drop the mic delay(500); axServos[0].write(0); delay(500); // Return to start / low effort position for (pos = 90; pos <= 0; pos -= 1) { axServos[1].write(90+pos); delay(20); } }
true
332c6b50faf0bb9d5cbb99f06378ea2add101a08
C++
QuanTrinhCA/SongPreferences
/main.cpp
UTF-8
1,470
3.609375
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <typeinfo> std::vector <int> getInput(int times) { std::string buffer; std::vector <int> input(times); std::getline(std::cin, buffer); for (int i = 0; i < times; i++) { if (i < times - 1) { int spaceLocation = buffer.find(" "); input[i] = stoi(buffer.substr(0, spaceLocation)); buffer.erase(0, spaceLocation + 1); } else if (i == times - 1) { input[i] = stoi(buffer.substr(0, buffer.length())); } } return input; } int trashFinder(std::vector <int> n, std::vector <int> a, std::vector <int> b) { int inversionCount{ 0 }; for (int i1 = 0; i1 < n[0]; i1++) { for (int i2 = i1 + 1; i2 < n[0]; i2++) { if (i1 < i2 && find(b.begin(), b.end(), a[i1]) > find(b.begin(), b.end(), a[i2])) { inversionCount++; } else if (i1 > i2 && find(b.begin(), b.end(), a[i1]) < find(b.begin(), b.end(), a[i2])) { inversionCount++; } } } return inversionCount; } int main() { std::cout << "Please enter inputs:\n"; std::vector <std::vector <int>> input(3); input[0] = getInput(1); input[1] = getInput(input[0][0]); input[2] = getInput(1); input.resize(input[2][0] + 3); for (int i = 3; i < input[2][0] + 3; i++) { input[i] = getInput(input[0][0]); } std::cout << "Number of inversions:\n"; for (int i = 3; i < input[2][0] + 3; i++) { std::cout << trashFinder(input[0], input[1], input[i]) << "\n"; } std::getchar(); return EXIT_SUCCESS; }
true
2669b7c278570cfec9e8f03645915f44b94183e2
C++
yurablok/MyPaintSFML
/Brush.cpp
UTF-8
865
2.578125
3
[ "MIT" ]
permissive
#include "Brush.h" using namespace Tools; Brush::Brush() { } Brush::~Brush() { } void Brush::process(Canvas &canvasMain, Canvas &canvasTemp, const MouseState &mouse, const PaintParameters &param) { if (!m_leftClicked && mouse.isLeftPressed()) { if (mouse.isOnCanvas()) { m_lineStart = mouse.getPos(); m_lineStart -= canvasMain.getPos(); m_lineEnd = m_lineStart; m_startOnCanvas = true; } else { m_startOnCanvas = false; } } else if (m_leftClicked && mouse.isLeftPressed() && m_startOnCanvas) { m_lineStart = m_lineEnd; m_lineEnd = mouse.getPos(); m_lineEnd -= canvasMain.getPos(); Line::drawLine(*canvasMain.ptr(), m_lineStart, m_lineEnd, param); } m_leftClicked = mouse.isLeftPressed(); }
true
eec5ae570fdc12c39e10590ad8b160568174abdd
C++
IndecisionGames/RQ-Engine-Archived-
/src/core/Window.cpp
UTF-8
646
2.6875
3
[ "MIT" ]
permissive
#include "Window.hpp" using namespace RQEngine; Window::Window(const std::string& wName, int wWidth, int wHeight, int maxFPS) : window(sf::VideoMode(wWidth, wHeight), wName, sf::Style::Titlebar | sf::Style::Close ), EM(&window), fps(maxFPS){} void Window::Update(){ fps.start(); EM.processEvents(); } void Window::PrepareFrame(){ window.clear(sf::Color::Black); } void Window::Draw(const sf::Drawable& drawable){ window.draw(drawable); } void Window::DrawFrame(){ window.display(); fps.limit(); // std::cout << fps.getCurrentFPS() << std::endl; } bool Window::IsOpen() const{ return window.isOpen(); }
true
b615dc442435d4455b1385d191bdc32aee369c6a
C++
czqInNanjing/LeetCode
/dynamicProgramming/Exer1_DistanceBetweenTwoStrings.cpp
UTF-8
5,083
3.46875
3
[]
no_license
// // Created by Qiang Chen on 8/11/17. // //  对于序列S和T,它们之间距离定义为:对二者其一进行几次以下的操作(1)删去一个字符;(2)插入一个字符;(3)改变一个字符。每进行一次操作,计数增加1。将S和T变为同一个字符串的最小计数即为它们的距离。给出相应算法。 // //解法: // //  将S和T的长度分别记为len(S)和len(T),并把S和T的距离记为m[len(S)][len(T)],有以下几种情况: // //如果末尾字符相同,那么m[len(S)][len(T)]=m[len(S)-1][len(T)-1]; // //如果末尾字符不同,有以下处理方式 // //  修改S或T末尾字符使其与另一个一致来完成,m[len(S)][len(T)]=m[len(S)-1][len(T)-1]+1; // //  在S末尾插入T末尾的字符,比较S[1...len(S)]和S[1...len(T)-1]; // //  在T末尾插入S末尾的字符,比较S[1...len(S)-1]和S[1...len(T)]; // //  删除S末尾的字符,比较S[1...len(S)-1]和S[1...len(T)]; // //  删除T末尾的字符,比较S[1...len(S)]和S[1...len(T)-1]; // //  总结为,对于i>0,j>0的状态(i,j),m[i][j] = min( m[i-1][j-1]+(s[i]==s[j])?0:1 , m[i-1][j]+1, m[i][j-1] +1)。 // //  这里的重叠子结构是S[1...i],T[1...j]。 #include <string> #include <vector> #include <iostream> using namespace std; // 这道题是 编辑距离 题目的完整题型,使用了动态规划的思想 // string erase 会影响自己本身 // 这道题的一个难点是一个打印转换过程,难度主要在于你只能记录每一步的过程,回溯的时候要理解是对应的字符做相应的修改 // 动态数组记得回收内存 class Exer1_DistanceBetweenTwoString { public: static const int INSERT = 0; static const int DELETE = 1; static const int CHANGE = 2; static const int NO_OPERATION = 3; int distanceBetweenStrings(string& s1, string& s2, vector<string>& changeWay) { const int m = s1.length(); const int n = s2.length(); int ** timesArray = new int*[m + 1]; int ** operationArray = new int*[m + 1]; for (int j = 0; j < m + 1; ++j) { timesArray[j] = new int[n + 1]; operationArray[j] = new int[n + 1]; } timesArray[0][0] = 0; operationArray[0][0] = NO_OPERATION; for (int k = 1; k < m + 1; ++k) { timesArray[k][0] = k; operationArray[k][0] = DELETE; } for (int l = 1; l < n + 1; ++l) { timesArray[0][l] = l; operationArray[0][l] = INSERT; } s1 = s1.insert(0, "0"); s2 = s2.insert(0, "0"); int tempResult[3]; int options[] = {DELETE, INSERT, CHANGE, NO_OPERATION}; for (int r = 1; r < m + 1; ++r) { for (int s = 1; s < n + 1; ++s) { int d = s1[r] == s2[s] ? 0 : 1; timesArray[r][s] = tempResult[0] = timesArray[r - 1][s] + 1; operationArray[r][s] = options[0]; tempResult[1] = timesArray[r][s - 1] + 1; tempResult[2] = timesArray[r - 1][s - 1] + d; for (int i = 1; i < 3; ++i) { if (timesArray[r][s] > tempResult[i]) { timesArray[r][s] = tempResult[i]; operationArray[r][s] = options[i]; } } if (operationArray[r][s] == CHANGE && d == 0) { operationArray[r][s] = NO_OPERATION; } } } int indexX = m; int indexY = n; string temps(s2); vector<string> tempChangeWay; while ( indexX != 0 || indexY != 0 ) { switch (operationArray[indexX][indexY]) { case NO_OPERATION: indexX--; indexY--; break; case CHANGE: temps[indexY] = s1[indexX]; tempChangeWay.push_back(temps.substr(1)); indexX--; indexY--; break; case INSERT: temps.erase(indexY, 1); indexY--; tempChangeWay.push_back(temps.substr(1)); break; case DELETE: temps.insert(indexY + 1, s1.substr(indexX, 1)); indexX--; tempChangeWay.push_back(temps.substr(1)); break; default: // do nothing break; } } for (vector<string>::reverse_iterator start = tempChangeWay.rbegin(); start != tempChangeWay.rend() ; start++ ) { changeWay.push_back(*start); } s2.erase(0, 1); changeWay.push_back(s2); int result = timesArray[m][n]; for (int i1 = 0; i1 < m + 1; ++i1) { delete[] timesArray[i1]; delete[] operationArray[i1]; } return result; } };
true
fe3730a2d5149b6b8ebd0ef21ebe0502d4b899e9
C++
mb0606/Comp-832
/Passanger-queue/Lqueue.h
UTF-8
633
2.71875
3
[]
no_license
// // Lqueue.h // queue // // Created by mb0606 on 12/15/18. // Copyright © 2018 mb0606. All rights reserved. // #ifndef Lqueue_h #define Lqueue_h template <typename E> struct Node { E value; Node* next; } template <typename E> class LQueue { private: E front; // Index of front element E rear; int max; int size; public: explict LQueue(int maxSize = 50){ max = maxSize size = 0; } ~LQueue { while(front != NULL){ Node *temp = front; front = front.next; delete temp; } } } #endif /* Lqueue_h */
true
f7405559db4f7c7acfa62249a72b8af934f6083f
C++
Shadek07/uva
/Solved Category/DP/12024.cpp
UTF-8
446
2.734375
3
[]
no_license
#include<iostream> #include<cmath> #include<cstdio> using namespace std; long int dp[15]; long fact[15]; void f() { int i; fact[1] = 1; for(i = 2;i <=12;i++) { fact[i] = i*fact[i-1]; } } void cal() { int i; dp[1] = 0; dp[2] = 1; for(i = 3;i <=12;i++) { dp[i] = (i-1)*(dp[i-1] + dp[i-2]); } } int main(void) { int t,n; cal(); f(); cin >> t; while(t--) { cin >> n; cout << dp[n] << "/" << fact[n] << endl; } return 0; }
true
6344d3652a71a32fbe36f677664c3b5859367f39
C++
elf0/elf.language
/compiler/Argument.h
UTF-8
1,785
2.96875
3
[ "Unlicense" ]
permissive
#ifndef ARGUMENT #define ARGUMENT //License: Public Domain //Author: elf //EMail: elf198012@gmail.com #include "Variable.h" namespace elf{namespace ast{ class Argument: public Variable{ public: Argument() : Variable(Type::otArgument) {} // Argument(Type type) // : Variable(type) // {} Argument(const std::string &strName) : Variable(Type::otArgument, strName) {} // Argument(Type type, const std::string &strName) // : Variable(type, strName) // {} ~Argument(){ } #ifdef DEBUG void* operator new(std::size_t nSize){ fprintf(stderr, "Argument.new\n"); s_osObjects.New("Argument"); return ::operator new(nSize); } void operator delete(void *pObject){ fprintf(stderr, "Argument.delete\n"); s_osObjects.Delete("Argument"); ::operator delete(pObject); } #endif Type getArgumentType()const{ return _atArgumentType; } void setArgumentType(Type type){ _atArgumentType = type; } private: Type _atArgumentType = Type::otUnknown; }; class Arguments{ public: Arguments(U8 nCount) : _nCount(nCount) , _pszArguments(new Argument[nCount]) {} Arguments(U8 nCount, Object::Type vtType) : _nCount(nCount) , _pszArguments(new Argument[nCount]) { for(size_t i = 0; i < nCount; ++i) _pszArguments[i].setArgumentType(vtType); } ~Arguments(){ delete []_pszArguments; } U8 getCount()const{ return _nCount; } Argument &operator[](size_t nIndex)const{ return _pszArguments[nIndex]; } private: U8 _nCount = 0; Argument* _pszArguments = null; }; }}//namespace elf.ast #endif // ARGUMENT
true
9a0620b6dfef560b09686ac03bb00f10ca8a9dc5
C++
kovdan01/programming-techniques-hw
/entry/entry.cpp
UTF-8
3,196
3.34375
3
[]
no_license
#include "entry.h" #include <ostream> #include <sstream> #include <stdexcept> #include <tuple> bool operator==(const Entry& lhs, const Entry& rhs) { return std::tie(lhs.m_club, lhs.m_year, lhs.m_country, lhs.m_score) == std::tie(rhs.m_club, rhs.m_year, rhs.m_country, rhs.m_score); } bool operator!=(const Entry& lhs, const Entry& rhs) { return !(lhs == rhs); } bool operator<(const Entry& lhs, const Entry& rhs) { double lhs_reversed_score = 1. / lhs.m_score; double rhs_reversed_score = 1. / rhs.m_score; return std::tie(lhs.m_club, lhs.m_year, lhs.m_country, lhs_reversed_score) < std::tie(rhs.m_club, rhs.m_year, rhs.m_country, rhs_reversed_score); } bool operator>(const Entry& lhs, const Entry& rhs) { return (rhs < lhs); } bool operator<=(const Entry& lhs, const Entry& rhs) { return !(lhs > rhs); } bool operator>=(const Entry& lhs, const Entry& rhs) { return !(lhs < rhs); } void Entry::to_csv(std::ostream& stream, char sep) const { stream << m_country << sep << m_city << sep << m_club << sep << m_trainer << sep << m_year << sep << m_score << '\n'; } void Entry::to_sqlite(SQLite::Database &db, const std::string& table) const { db.exec("INSERT INTO " + table + " " "(country, city, club, trainer, year, score)" "VALUES (" + "\"" + m_country + "\", " + "\"" + m_city + "\", " + "\"" + m_club + "\", " + "\"" + m_trainer + "\", " + std::to_string(m_year) + ", " + std::to_string(m_score) + ")"); } Entry from_csv(const std::string& csv_line, char sep) { Entry::Country country; Entry::City city; Entry::Club club; Entry::Trainer trainer; Entry::Year year; Entry::Score score; std::string remaining; std::istringstream input(csv_line); getline(input, country, sep); getline(input, city, sep); getline(input, club, sep); getline(input, trainer, sep); input >> year; if (input.peek() != sep) throw std::runtime_error("Invalid separator or wrong format of year"); input.ignore(1); input >> score; getline(input, remaining); if (!remaining.empty()) throw std::runtime_error("Invalid csv"); return Entry(country, city, club, trainer, year, score); } Entry from_sqlite(SQLite::Statement& query) { Entry::Country country = query.getColumn("country"); Entry::City city = query.getColumn("city"); Entry::Club club = query.getColumn("club"); Entry::Trainer trainer = query.getColumn("trainer"); Entry::Year year = query.getColumn("year"); Entry::Score score = query.getColumn("score"); return Entry(country, city, club, trainer, year, score); } std::ostream& operator<<(std::ostream& stream, const Entry& entry) { stream << "country: \"" << entry.m_country << "\"\ncity: \"" << entry.m_city << "\"\nclub: \"" << entry.m_club << "\"\ntrainer: \"" << entry.m_trainer << "\"\nyear: " << entry.m_year << "\nscore: " << entry.m_score << '\n'; return stream; }
true
39848e372d0163076619783c004aec63a0e3f5a1
C++
KapitoshkaThe1st/MAI
/DA/lab6/source/main.cpp
UTF-8
9,427
3.15625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <limits> #include <cmath> #include <cassert> #include <iomanip> typedef long long digit_type; const int base = 100000000; const int baseLen = (int)(log(base) / log(10)); class TBigInt{ public: TBigInt() : digits(std::vector<digit_type>(1,0)) {} TBigInt(const TBigInt &oth) : digits(oth.digits) {} TBigInt(TBigInt &&oth){ digits = std::move(oth.digits); } TBigInt(const size_t size, size_t) : digits(std::vector<digit_type>(size)) {} TBigInt(std::string str){ size_t len = str.length(); for(size_t i = len - baseLen; i < len; i -= baseLen){ assert(i < len); digits.push_back(atoll(str.c_str() + i)); str[i] = 0; } if(len % baseLen != 0){ digits.push_back(atoll(str.c_str())); } FilterZeros(); } TBigInt(std::istream &istr){ std::string inputBuffer; istr >> inputBuffer; size_t len = inputBuffer.length(); for(size_t i = len - baseLen; i < len; i -= baseLen){ assert(i < len); digits.push_back(atoll(inputBuffer.c_str() + i)); inputBuffer.resize(i); } if(len % baseLen != 0){ digits.push_back(atoll(inputBuffer.c_str())); } FilterZeros(); } TBigInt(digit_type num) : digits(std::vector<digit_type>()){ if(num == 0){ digits.push_back(0); return; } while(num > 0){ digits.push_back(num % base); num /= base; } } size_t Size() const { return digits.size(); } TBigInt& operator=(const TBigInt &oth){ digits = oth.digits; return *this; } TBigInt& operator=(TBigInt &&oth){ digits = std::move(oth.digits); return *this; } static TBigInt Pow(TBigInt bi, TBigInt p){ TBigInt res(1); while(p > 0){ if(p.digits[0] % 2 == 1){ res = res * bi; p = p - 1; } bi = bi * bi; p = p / 2; } return res; } static TBigInt Pow(TBigInt bi, digit_type p){ TBigInt res(1); while(p > 0){ if(p % 2 == 1) { res = res * bi; } bi = bi * bi; p >>= 1; } return res; } private: std::vector<digit_type > digits; digit_type GetDigit(size_t ind) const { return ind < digits.size() ? digits[ind] : 0; } digit_type& operator[](size_t ind){ assert(ind < digits.size()); return digits[ind]; } void FilterZeros(){ for(size_t i = digits.size() - 1; i >= 1; i--){ if(digits[i] != 0){ break; } digits.pop_back(); } } int Comp(const TBigInt &oth) const { size_t size = Size(); size_t othSize = oth.Size(); if(size != othSize){ return size > othSize ? 1 : -1; } for(size_t i = size - 1; i < size; i--){ if(digits[i] != oth.digits[i]){ return digits[i] > oth.digits[i] ? 1 : -1; } } return 0; } friend TBigInt operator+(const TBigInt &lbi, const TBigInt &rbi); friend TBigInt operator-(const TBigInt &lbi, const TBigInt &rbi); friend TBigInt operator*(const TBigInt &lbi, const TBigInt &rbi); friend TBigInt operator^(const TBigInt &bi, TBigInt p); friend TBigInt operator^(const TBigInt &bi, digit_type p); friend TBigInt operator/(const TBigInt &lbi, const TBigInt &rbi); friend TBigInt operator/(const TBigInt &lbi, const digit_type ri); friend bool operator<(const TBigInt &lbi, const TBigInt &rbi); friend bool operator>(const TBigInt &lbi, const TBigInt &rbi); friend bool operator<=(const TBigInt &lbi, const TBigInt &rbi); friend bool operator>=(const TBigInt &lbi, const TBigInt &rbi); friend bool operator==(const TBigInt &lbi, const TBigInt &rbi); friend std::ostream &operator<<(std::ostream &ostr, const TBigInt &bi); }; TBigInt operator+(const TBigInt &lbi, const TBigInt &rbi){ size_t size = std::max(lbi.Size(), rbi.Size()); TBigInt res(size, size_t(0)); digit_type rem = 0; for(size_t i = 0; i < size; i++){ res[i] = lbi.GetDigit(i) + rbi.GetDigit(i) + rem; rem = res[i] / base; res[i] %= base; } if(rem > 0){ res.digits.push_back(rem); } return res; } TBigInt operator-(const TBigInt &lbi, const TBigInt &rbi){ size_t size = std::max(lbi.Size(), rbi.Size()); TBigInt res(size, size_t(0)); digit_type rem = 0; for(size_t i = 0; i < size; i++){ res[i] = base + lbi.GetDigit(i) - rbi.GetDigit(i) - rem; rem = base <= res[i] ? 0 : 1; res[i] %= base; } res.FilterZeros(); return res; } TBigInt operator*(const TBigInt &lbi, const TBigInt &rbi){ size_t lSize = lbi.Size(); size_t rSize = rbi.Size(); size_t size = lSize + rSize; TBigInt res(size, size_t(0)); for(size_t i = 0; i < rSize; i++){ if(rbi.GetDigit(i) == 0){ continue; } digit_type rem = 0; for(size_t j = 0; j < lSize; j++){ res[i + j] += rbi.GetDigit(i) * lbi.GetDigit(j) + rem; rem = res[i + j] / base; res[i + j] %= base; } if(rem > 0){ res[i + lSize] = rem; } } res.FilterZeros(); return res; } TBigInt operator^(const TBigInt &bi, TBigInt p){ return TBigInt::Pow(bi, p); } TBigInt operator^(const TBigInt &bi, digit_type p){ return TBigInt::Pow(bi, p); } TBigInt operator/(const TBigInt &lbi, const TBigInt &rbi){ size_t rSize = rbi.Size(); if(lbi < rbi) { return TBigInt(0); } TBigInt rem = lbi; TBigInt res(0); while(rem >= rbi){ size_t remSize = rem.Size(); digit_type firstDigit = rem.GetDigit(remSize - 1); digit_type secondDigit = remSize > 1 ? rem.GetDigit(remSize - 2) : 0; digit_type left = (firstDigit * base + secondDigit) / rbi.GetDigit(rSize - 1); digit_type right = 0; size_t pow = remSize - rSize - 1; TBigInt power = TBigInt(base) ^ pow; TBigInt multiplier = rbi * power; TBigInt prod; while(right <= left){ digit_type mid = (right + left) / 2; prod = TBigInt(mid) * multiplier; if(rem < prod){ left = mid - 1; } else{ right = mid + 1; } } rem = rem - TBigInt(left) * multiplier; res = res + left * power; } return res; } TBigInt operator/(const TBigInt &lbi, const digit_type ri){ digit_type rem = 0; size_t lSize = lbi.Size(); TBigInt res(lSize, (size_t)0); for(size_t i = lSize - 1; i < lSize; i--){ digit_type cur = lbi.GetDigit(i) + rem * base; res[i] = cur / ri; rem = cur % ri; } res.FilterZeros(); return res; } bool operator<(const TBigInt &lbi, const TBigInt &rbi){ return rbi.Comp(lbi) > 0; } bool operator>(const TBigInt &lbi, const TBigInt &rbi){ return lbi.Comp(rbi) > 0; } bool operator<=(const TBigInt &lbi, const TBigInt &rbi){ return rbi.Comp(lbi) >= 0; } bool operator>=(const TBigInt &lbi, const TBigInt &rbi){ return lbi.Comp(rbi) >= 0; } bool operator==(const TBigInt &lbi, const TBigInt &rbi){ return rbi.Comp(lbi) == 0; } std::ostream& operator<<(std::ostream &ostr, const TBigInt &bi){ size_t size = bi.digits.size(); for(size_t i = size - 1; i < size; i--){ if(i < size - 1){ ostr << std::setw(baseLen) << std::setfill('0'); } ostr << bi.digits[i]; } return ostr; } int main() { std::string str; char op; while(std::cin >> str){ TBigInt a(str); std::cin >> str; TBigInt b(str); std::cin >> op; switch(op){ case '+': std::cout << a + b << std::endl; break; case '-': if(a < b){ std::cout << "Error" << std::endl; } else{ std::cout << a - b << std::endl; } break; case '*': std::cout << a * b << std::endl; break; case '^': if(a == TBigInt(0) && b == TBigInt(0)){ std::cout << "Error" << std::endl; } else{ std::cout << (a ^ b) << std::endl; } break; case '/': if (b == TBigInt(0)){ std::cout << "Error" << std::endl; } else{ std::cout << a / b << std::endl; } break; case '>': std::cout << (a > b ? "true" : "false") << std::endl; break; case '<': std::cout << (a < b ? "true" : "false") << std::endl; break; case '=': std::cout << (a == b ? "true" : "false") << std::endl; break; } } return 0; }
true
725286b56a1f75a5bd65d99b3e82fee05a42b090
C++
shiro-saber/Analisis_Dise-o_Algoritmos
/Problema_Práctico1/ArbolB/ArbolB/helpers.cpp
UTF-8
520
2.875
3
[]
no_license
// // helpers.cpp // Ejercicio2 // // Created by SeijiJulianPerezSchimidzu on 09/09/15. // Copyright (c) 2015 ITESM CSF. All rights reserved. // #include "types.h" template <typename T> T* newArray(int size, int start, int end, T* arr) { T* newArr = new T[size]; int i = 0; T returnValue = return_type(); while (i < start) { newArr[i] = returnValue; ++i; } while (i < end) { newArr[i] = arr[i]; ++i; } while (i < size) { newArr[i] = returnValue; ++i; } return newArr; }
true
26d5792bf8f15d8274692e57c3bb3e3358d84c66
C++
ZhaoRui321/00_work
/001_qt_prj/OMS/tool/sthread.h
UTF-8
1,082
2.53125
3
[]
no_license
#ifndef STHREAD_H #define STHREAD_H //#include "sglobal.h" #include <QThread> /** * @brief * */ typedef int (*SThreadFunc)(void* pParam, const bool& bRunning); /** * @brief * */ class SThread : public QThread { Q_OBJECT public: /** * @brief * * @param parent */ explicit SThread(QObject *parent = 0); /** * @brief * * @return SThreadFunc */ SThreadFunc userFunction() const; /** * @brief * * @param fnUserFunction */ void setUserFunction(const SThreadFunc &fnUserFunction); /** * @brief * */ void *userParam() const; /** * @brief * * @param pUserParam */ void setUserParam(void *pUserParam); /** * @brief * */ void stop(); protected: /** * @brief * */ virtual void run(); SThreadFunc m_userFunction; /**< TODO */ void* m_userParam; /**< TODO */ bool m_running = false; /**< TODO */ }; #endif // STHREAD_H
true
1fd2052264773c4ccb13df77a8d1bc26fdb10fa4
C++
sberoch/MicromachinesTaller
/src/Server/Network/AcceptingThread.h
UTF-8
977
2.59375
3
[]
no_license
// // Created by alvaro on 30/9/19. // #ifndef HONEYPOT_SERVERACCEPTINGTHREAD_H #define HONEYPOT_SERVERACCEPTINGTHREAD_H #include <iostream> #include "../../Common/Thread.h" #include "../../Common/Socket.h" #include "ThClient.h" #include "Room.h" #include "RoomController.h" #include <list> #include <mutex> #include <sys/socket.h> #include <netinet/in.h> #include <strings.h> class AcceptingThread: public Thread { private: Socket &acceptSocket; std::atomic_bool running; RoomController roomController; public: //Asigna las referencias al socket aceptador y al archivo. explicit AcceptingThread(Socket &acceptSocket); //Realiza el ciclo aceptador con el recolector de clientes muertos hasta //que se cierra el socket aceptador. Luego de esto, se mata a todos los rooms //y clientes sin room. Los rooms matan a sus propios clientes. void run() override; ~AcceptingThread() override; }; #endif //HONEYPOT_SERVERACCEPTINGTHREAD_H
true
f99bad46a52805a43edb0b99fb2ce16915f57cad
C++
kuffie/robotics-git
/_3linesensmottest_b/_3linesensmottest_b.ino
UTF-8
2,885
3.40625
3
[]
no_license
/* Analog input, analog output, serial output Reads an analog input pin, maps the result to a range from 0 to 255 and uses the result to set the pulsewidth modulation (PWM) of an output pin. Also prints the results to the serial monitor. The circuit: * potentiometer connected to analog pin 0. Center pin of the potentiometer goes to the analog pin. side pins of the potentiometer go to +5V and ground * LED connected from digital pin 9 to ground created 29 Dec. 2008 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. */ // These constants won't change. They're used to give names // to the pins used: const int analogInPinL = A1; // Analog input pin that the potentiometer is attached to const int analogInPinC = A2; const int analogInPinR = A3; const int analogOutPinL = 9; // Analog output pin that the LED is attached to const int analogOutPinC = 9; const int analogOutPinR = 9; int sensorValueL = 0; // value read from the pot int sensorValueC = 0; int sensorValueR = 0; int outputValueL = 0; // value output to the PWM (analog out) int outputValueC = 0; int outputValueR = 0; int Rmota = 3; int Rmotb = 4; int Lmota = 5; int Lmotb = 6; int thresh = 700; void setup() { // initialize serial communications at 9600 bps: Serial.begin(9600); pinMode(Rmota, OUTPUT); pinMode(Rmotb, OUTPUT); pinMode(Lmota, OUTPUT); pinMode(Lmotb, OUTPUT); // STOP digitalWrite(Rmota, LOW); digitalWrite(Rmotb, LOW); digitalWrite(Lmota, LOW); digitalWrite(Lmotb, LOW); } void loop() { // read the analog in value: sensorValueL = analogRead(analogInPinL); sensorValueC = analogRead(analogInPinC); sensorValueR = analogRead(analogInPinR); // print the results to the serial monitor: Serial.print("LEFT sensor = "); Serial.print(sensorValueL); Serial.print(" CENTER sensor = "); Serial.print(sensorValueC); Serial.print(" RIGHT sensor = "); Serial.println(sensorValueR); // wait 2 milliseconds before the next loop // for the analog-to-digital converter to settle // after the last reading: delay(2); if ((sensorValueL < thresh) && (sensorValueC > thresh) && (sensorValueR < thresh)) { //FORWARD Serial.println("FORWARD"); digitalWrite(Rmota, HIGH); digitalWrite(Rmotb, LOW); digitalWrite(Lmota, HIGH); digitalWrite(Lmotb, LOW); } if ((sensorValueL > thresh) && (sensorValueC < thresh) && (sensorValueR < thresh)) { //LEFT Serial.println("LEFT"); digitalWrite(Rmota, HIGH); digitalWrite(Rmotb, LOW); digitalWrite(Lmota, LOW); digitalWrite(Lmotb, LOW); } if ((sensorValueL < thresh) && (sensorValueC < thresh) && (sensorValueR > thresh)) { //RIGHT Serial.println("RIGHT"); digitalWrite(Rmota, LOW); digitalWrite(Rmotb, LOW); digitalWrite(Lmota, HIGH); digitalWrite(Lmotb, LOW); } delay(1000); }
true
0bb7443213d5952d91e065856e064ffa0bb48465
C++
linan1109/C0-compiler
/symbletable/symbletable.h
UTF-8
5,329
2.78125
3
[]
no_license
#pragma once #include <vector> #include <optional> #include <utility> #include <cstdint> #include <algorithm> #include <instruction/instruction.h> namespace miniplc0 { class one_symbol final{ std::string _name; //标识符名称 int32_t _kind; /*种类 0:常量 1:变量 2:函数 */ int32_t _type; /*类型 0:void(仅对于无返回值函数) 1:int32_t 2: char */ int32_t _value; /* 未初始化:0 已初始化:1 */ int32_t _size; /*函数:参数个数 数组:元素个数 其他:-1 */ int32_t all_index; public: bool operator==(const one_symbol &rhs) const; bool operator!=(const one_symbol &rhs) const; one_symbol(const std::string &name, int32_t kind, int32_t type, int32_t value, int32_t size); const std::string &getName() const; void setName(const std::string &name); int32_t getKind() const; void setKind(int32_t kind); int32_t getType() const; void setType(int32_t type); int32_t getValue() const; void setValue(int32_t value); int32_t getSize() const; void setSize(int32_t size); int32_t getAllIndex() const; void setAllIndex(int32_t allIndex); }; class SymbleTable final{ private: std::string name; using int32_t = std::int32_t; std::vector<one_symbol> List; //符号表 SymbleTable *father; int32_t count; public: SymbleTable *getFather() const; void setFather(SymbleTable *father); public: const std::string &getName() const; void setName(const std::string &name); int32_t getCount() const; void setCount(int32_t count); SymbleTable(){ name = ""; father = nullptr; count = 0; } SymbleTable(SymbleTable *_father,std::string _name){ father = _father; name = _name; count = 0; } int32_t addCount(); bool operator==(const SymbleTable &rhs) const; bool operator!=(const SymbleTable &rhs) const; bool isDeclared(const std::__cxx11::basic_string<char> &s); int32_t getKindByName(const std::string &s); bool addSymble(const std::string &s, int32_t kind, int32_t type, int32_t value, int32_t size); int32_t getTypeByName(const std::string &s); int32_t getValueByName(const std::string &s); std::pair<int32_t, int32_t> index_in_all(const std::string &s); bool changeSizeOfFun(const std::string &s, int32_t size); one_symbol * getByName(const std::string &s); int32_t getSizeByName(const std::string &s); int32_t getLevel(); int32_t setValueByName(const std::string &s); }; class function{ private: std::string _name; std::vector< std::pair<std::string, std::pair<std::int32_t , int32_t > > >_params; int32_t _type; std::vector<Instruction> _instructions; int32_t _level; int32_t _name_index; std::vector<int32_t> _break_counts; //name //kind /*种类 // 0:常量 // 1:变量 //type // 0:void(仅对于无返回值函数) // 1:int32_t // 2: char public: function(const std::string &name, int32_t type, int32_t nameIndex, int32_t level); public: bool operator==(const function &rhs) const; bool operator!=(const function &rhs) const; int32_t getLevel() const; void setLevel(int32_t level); int32_t getNameIndex() const; void setNameIndex(int32_t nameIndex); const std::string &getName() const; void setName(const std::string &name); int32_t getType() const; const std::vector<Instruction> &getInstructions() const; void setInstructions(const std::vector<Instruction> &instructions); void setType(int32_t type); const std::vector<std::pair<std::string, std::pair<std::int32_t, int32_t>>> &getParams() const; void setParams(const std::vector<std::pair<std::string, std::pair<std::int32_t, int32_t>>> &params); bool addParam(const std::string &name, int32_t kind, int32_t type); void addInstruction(const int32_t, Operation operation, int32_t x, int32_t y); bool setInstructionX(int32_t Index, int32_t x); bool addBreak(int32_t count); const std::vector<int32_t> &getBreakCounts() const; void setBreakCounts(const std::vector<int32_t> &breakCounts); }; }
true
90aae894ff55f14bc5dcc7f292f2465274e3a5df
C++
spartakang/MIO_PID_Controller
/atof/atof_visual2005/atof_visual2005/atof_visual2005.cpp
GB18030
1,808
2.96875
3
[]
no_license
// atof_visual2005.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> // ------------------------------------------------------------------------- // : StrToFloatA // : һַתΪ // ֵ : float // : char* pstrfloat // ע : // ------------------------------------------------------------------------- float StrToFloat(char* pstrfloat) { // check if (!pstrfloat) { return 0.0; } bool bNegative = false; bool bDec = false; char* pSor = 0; char chByte = '0'; float fInteger = 0.0; float fDecimal = 0.0; float fDecPower = 0.1f; // λжϣжǷǸ if (pstrfloat[0] == '-') { bNegative = true; pSor = pstrfloat + 1; } else { bNegative = false; pSor = pstrfloat; } while (*pSor != '\0') { chByte = *pSor; if (bDec) { // С if (chByte >= '0' && chByte <= '9') { fDecimal += (chByte - '0') * fDecPower; fDecPower = fDecPower * 0.1; } else { return (bNegative? -(fInteger + fDecimal): fInteger + fDecimal); } } else { // if (chByte >= '0' && chByte <= '9') { fInteger = fInteger * 10.0 + chByte - '0'; } else if (chByte == '.') { bDec = true; } else { return (bNegative? -fInteger : fInteger); } } pSor++; } return (bNegative? -(fInteger + fDecimal): fInteger + fDecimal); } int _tmain(int argc, _TCHAR* argv[]) { //_TCHAR FL[] = "3.141592656"; printf("Hello\n\r"); printf("StrToFloat(1.23569) = %f\n\n\t", StrToFloat("3.1415926")); return 0; }
true
bd2959580340485ef925140c9a7eba1fcc7d8dda
C++
Soth1985/Thor2
/applications/MetalTracer/RayTracer.h
UTF-8
6,409
2.578125
3
[]
no_license
#pragma once #include "Scene.h" #include <Thor/Core/Concurrent/ThDispatch.h> #include <atomic> #include <random> #include <chrono> #include <functional> namespace Thor { template<class T> T UniformDistribution(T min, T max) { static /*thread_local*/ std::mt19937 generator(std::chrono::system_clock::now().time_since_epoch().count()); std::uniform_real_distribution<double> distribution(min, max); return distribution(generator); } enum class CameraMode { Normal, LensDefocus }; enum class RayTracerState : ThI32 { Uninitialized, Idle, RenderingFrame, FrameReady }; class Camera { public: Camera() : lowerLeftCorner(-2.0f, -1.0f, -1.0f), horizontal(4.0f, 0.0f, 0.0f), vertical(0.0f, 2.0f, 0.0f), lensRadius(1.0f) { } void Init(const ThVec3f& origin, const ThVec3f& lookAt, const ThVec3f& up, ThF32 vFov, ThF32 aspect, ThF32 aperture, ThF32 focusDist) { lensRadius = 0.5 * aperture; ThF32 theta = Math::DegToRad(vFov); ThF32 halfHeight = Math::Tan(0.5 * theta); ThF32 halfWidth = aspect * halfHeight; this->origin = origin; w = origin - lookAt; w.Normalize(); u = up % w; u.Normalize(); v = w % u; lowerLeftCorner = origin - halfWidth * focusDist * u - halfHeight * focusDist * v - focusDist * w; horizontal = 2.0 * halfWidth * focusDist * u; vertical = 2.0 * halfHeight * focusDist * v; } ThRayf GetRay(float u, float v) { ThVec3f direction = lowerLeftCorner + u * horizontal + v * vertical - origin; direction.Normalize(); return ThRayf(origin, direction); } ThRayf GetRayLens(float u, float v) { ThVec3f rd = RandomInUnitDisk(); ThVec3f offset; offset.x() = lensRadius * u * rd.x(); offset.y() = lensRadius * v * rd.y(); ThVec3f direction = lowerLeftCorner + u * horizontal + v * vertical - origin - offset; direction.Normalize(); return ThRayf(origin + offset, direction); } ThVec3f RandomInUnitDisk() { ThVec3f result; do { result.x() = UniformDistribution(-1.0, 1.0); result.y() = UniformDistribution(-1.0, 1.0); result.z() = 0.0; } while (result * result > 1.0); return result; } ThVec3f lowerLeftCorner; ThVec3f horizontal; ThVec3f vertical; ThVec3f origin; ThVec3f u; ThVec3f v; ThVec3f w; ThF32 lensRadius; }; class Film { public: Film() : m_Width(0), m_Height(0), m_Frame(nullptr) { } void Init(ThI32 width, ThI32 height) { m_Width = width; m_Height = height; m_Frame = new ThVec4ub[width * height]; } ~Film() { delete[] m_Frame; } const ThVec4ub& Pixel(int x, int y)const { return m_Frame[y * m_Width + x]; } ThVec4ub& Pixel(int x, int y) { return m_Frame[y * m_Width + x]; } const ThVec4ub* GetFrame()const { return m_Frame; } private: ThVec4ub* m_Frame; ThI32 m_Width; ThI32 m_Height; }; struct RayTracerOptions { RayTracerOptions() : m_Width(0), m_Height(0), m_FramesToRender(1), m_SamplesPerPixel(1), m_TraceDepth(1), m_CameraOrigin(0.0, 0.0, 0.0), m_CameraLookAt(0.0, 0.0, -1.0), m_CameraUp(0.0, 1.0, 0.0), m_CameraFov(90.0), m_CameraMode(CameraMode::Normal), m_CameraAperture(2.0), m_CameraFocusDist(1.0) { } ThI32 m_Width; ThI32 m_Height; ThI32 m_FramesToRender; ThI32 m_SamplesPerPixel; ThI32 m_TraceDepth; CameraMode m_CameraMode; ThF32 m_CameraFov; ThF32 m_CameraAperture; ThF32 m_CameraFocusDist; ThVec3f m_CameraOrigin; ThVec3f m_CameraLookAt; ThVec3f m_CameraUp; }; class RayTracer { public: RayTracer(); ~RayTracer(); void Init(const RayTracerOptions& options, Scene* scene); RayTracerState GetState(); bool RenderFrame(); const Film* GetFilm()const; const RayTracerOptions& GetOptions()const; void ResizeFilm(ThI32 width, ThI32 height); void FrameFetched(); private: ThVec3f TraceScene(const ThRayf& ray, ThI32 depth); ThVec3f RandomPointOnSphere(); bool ScatterLambert(const ComponentRef& mat, const ThRayf& rayIn, const ThRayHitf& hit, ThVec3f& attenuation, ThRayf& scattered); bool ScatterMetal(const ComponentRef& mat, const ThRayf& rayIn, const ThRayHitf& hit, ThVec3f& attenuation, ThRayf& scattered); bool ScatterDielectric(const ComponentRef& mat, const ThRayf& rayIn, const ThRayHitf& hit, ThVec3f& attenuation, ThRayf& scattered); float Schlick(float cosine, float n1, float n2); float Schlick2(const ThVec3f& vec, const ThVec3f& norm, float n1, float n2); static void RenderFunc(void* ctx); static void SyncFunc(void* ctx); struct WorkItem { RayTracer* m_Self; float m_OneOverW; float m_OneOverH; ThI32 m_J; }; std::atomic<RayTracerState> m_State; Film* m_Film; ThI32 m_FramesRendered; Scene* m_Scene; std::mt19937 m_Generator; std::uniform_real_distribution<double> m_RngUniform; RayTracerOptions m_Options; Camera m_Camera; ThDispatchQueue m_Queue; ThDispatchGroup m_Group; ThVector<WorkItem> m_WorkItems; }; }
true
b5bf514dcda5ad8b61415767b57812e6f6606b15
C++
bigplik/Arduino_mac
/Variometer/BMP280/AVR/uno_Vario/uno_Vario.ino
UTF-8
2,736
2.53125
3
[]
no_license
// All code by Rolf R Bakke, Oct 2012 #include <Wire.h> #include <SPI.h> #include <Adafruit_Sensor.h> #include <Adafruit_BMP280.h> #define BMP_SCK 13 #define BMP_MISO 12 #define BMP_MOSI 11 #define BMP_CS 10 const byte led = 13; unsigned int calibrationData[7]; unsigned long time = 0; float toneFreq, toneFreqLowpass, pressure, lowpassFast, lowpassSlow ; int ddsAcc; Adafruit_BMP280 bmp; // I2C //Adafruit_BMP280 bmp(BMP_CS); // hardware SPI //Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK); void setup() { Serial.begin(115200); Serial.println(F("BMP280 test")); if (!bmp.begin()) { Serial.println(F("Could not find a valid BMP280 sensor, check wiring!")); while (1); } setupSensor(); pressure = getPressure(); lowpassFast = lowpassSlow = pressure; } void loop() { pressure = getPressure(); lowpassFast = lowpassFast + (pressure - lowpassFast) * 0.1; lowpassSlow = lowpassSlow + (pressure - lowpassSlow) * 0.05; toneFreq = (lowpassSlow - lowpassFast) * 50; toneFreqLowpass = toneFreqLowpass + (toneFreq - toneFreqLowpass) * 0.1; toneFreq = constrain(toneFreqLowpass, -500, 500); ddsAcc += toneFreq * 100 + 2000; if (toneFreq < 0 || ddsAcc > 0) { tone(3, toneFreq + 510); } else { noTone(3); } ledOff(); while (millis() < time); //loop frequency timer time += 20; ledOn(); } long getPressure() { long P; P = bmp.readPressure(); //Serial.println(TEMP); //Serial.println(P); return P; } long getData(byte command, byte del) { long result = 0; twiSendCommand(0x76, command); delay(del); twiSendCommand(0x76, 0x00); Wire.requestFrom(0x76, 3); if(Wire.available()!=3) Serial.println("Error: raw data not available"); for (int i = 0; i <= 2; i++) { result = (result<<8) | Wire.read(); } return result; } void setupSensor() { twiSendCommand(0x76, 0x1e); delay(100); for (byte i = 1; i <=6; i++) { unsigned int low, high; twiSendCommand(0x76, 0xa0 + i * 2); Wire.requestFrom(0x76, 2); if(Wire.available()!=2) Serial.println("Error: calibration data not available"); high = Wire.read(); low = Wire.read(); calibrationData[i] = high<<8 | low; Serial.print("calibration data #"); Serial.print(i); Serial.print(" = "); Serial.println( calibrationData[i] ); } } void twiSendCommand(byte address, byte command) { Wire.beginTransmission(address); if (!Wire.write(command)) Serial.println("Error: write()"); if (Wire.endTransmission()) { Serial.print("Error when sending command: "); Serial.println(command, HEX); } } void ledOn() { digitalWrite(led,1); } void ledOff() { digitalWrite(led,0); }
true
b315ccefee1d965fbff8ff7d6f354187cba7a98c
C++
CharlesSaya/rayTracingEngine-Cpp
/src/3D/implicitSurface.cpp
ISO-8859-1
3,092
2.875
3
[]
no_license
#include "implicitSurface.hpp" namespace ISICG_ISIR { /* * Constructeur de classe */ ImplicitSurface::ImplicitSurface(const Vec3f &center, const float reflectionAmount, const float refractionAmount, const float refractionIdx, const float rugosity, const Vec3f &f0) { _reflectionAmount = reflectionAmount; _refractionAmount = refractionAmount; _refractionIndex = refractionIdx; _rugosity = rugosity; _f0 = f0; _center=center; } /* * Fonction renvoyant un float en cacule avec le point sur le rayon sur lequel on * marche. La fonction retourne une valeur positive si l'on est l'extrieur de la * surface et une valeur ngative si l'on est l'intrieur. * Une valeur nulle est retourn quand le point appartient la surface. * La fonction ici reprsente un cylindre quadrique */ float ImplicitSurface::distanceImplicitFunction(const Vec3f &position) { Vec3f pos = (position - _center) * 4.f; if (pos.y < 10.f && pos.y > -10.f) return pow(pos.y, 2) * pow(pos.x, 2) + pow(pos.y, 2) * pow(pos.z, 2) + 0.01 * pow(pos.x,2) + 0.01 * pow(pos.z,2) - 0.01; } /* * Fonction calculant la normale d'une surface implicite l'aide de sa * reprsentation implicite */ Vec3f ImplicitSurface::calcNormal(const Vec3f &pos) { const Vec2f eps = Vec2f(0.001, 0.0); Vec3f nor = Vec3f( distanceImplicitFunction(pos + Vec3f(eps.x, eps.y, eps.y)) - distanceImplicitFunction(pos - Vec3f(eps.x, eps.y, eps.y)), distanceImplicitFunction(pos + Vec3f(eps.y, eps.x, eps.y)) - distanceImplicitFunction(pos - Vec3f(eps.y, eps.x, eps.y)), distanceImplicitFunction(pos + Vec3f(eps.y, eps.y, eps.x)) - distanceImplicitFunction(pos - Vec3f(eps.y, eps.y, eps.x)) ); return normalize(nor); } /* * Fonction d'intersection. Dans le cas des surfaces implicites, on effectue * une mthode de ray-marching pour trouver l'intersection entre le rayon et * la surface si elle existe. * La mthode s'arrte lorsque une distance maximale a t atteinte ou si * la surface a t intersecte par le rayon. */ std::vector<Intersection> ImplicitSurface::intersect(const Ray &ray) { std::vector<Intersection> intersections; float minDistance = 1; float maxDistance = 10; float t = 0; float step = 0.01; float sign=0; Vec3f rd = ray.getDirection(); Vec3f ro = ray.getOrigin(); Vec3f position = ro; float distance = distanceImplicitFunction(position); ; while (t < maxDistance) { sign = glm::sign(distance); distance = distanceImplicitFunction(position); if (sign != glm::sign(distance)) // un changement de signe indicte un passage de l'extrieur l'intrieur de la surface { // ou inversement Vec3f normale = calcNormal(position); Intersection i(t, position +0.01f*normale , normale, this); intersections.push_back(i); return intersections; } t += step; position = ro + t * rd; } return intersections; } } // namespace ISICG_ISIR
true
180e2ae72fe674fbb11e1b6476f981ef22fa895a
C++
JESU20950/A
/Teoria/Data_structures/Stacks/X96935.cc
UTF-8
501
3.328125
3
[]
no_license
#include <iostream> #include <stack> using namespace std; bool palindrom(){ stack <int> s; int n; int nombre; cin >> n; for (int i = 0; i<n/2; ++i){ cin >> nombre; s.push(nombre); } if (n%2 != 0) cin >> nombre; for (int i = 0; i<n/2; ++i){ cin >> nombre; if (s.top() != nombre) return false; s.pop(); } return true; } int main(){ if (palindrom()) cout << "SI" << endl; else cout << "NO" << endl; }
true
931afbbafb5a89d0653a7883e7e62977e2f3658c
C++
SunriseFox/very-simple-cipher-lab
/exercise2/des.cpp
UTF-8
4,604
2.9375
3
[ "MIT" ]
permissive
#include "des.h" void DES::_updateKey(const bit64 &key) { // 私有方法:更新密钥,生成子密钥 this->key = key; DEBUG(cout << "K: " << key << endl;) _generateSubkey(); } void DES::_generateSubkey() { // 私有方法:生成子密钥 // 从 64 位密钥最终得到 16 个 48 位子密钥。 // 1. 对输入密钥应用 PC-1<64, 56> 压缩置换表,生成 56 位密钥 bit56 keyp = fillTable<64, 56>(key, TABLE_PC1); DEBUG(cout << "K+: " << keyp << endl;) // 2. 将 56 位分为前 28 位 C0 和 后 28 位 D0 bit28 C[17], D[17]; C[0] = bit28((keyp >> 28).to_ullong()); D[0] = bit28((keyp << 28 >> 28).to_ullong()); DEBUG(cout << "C0: " << C[0] << endl;) DEBUG(cout << "D0: " << D[0] << endl;) // 3. 对 Ci-1 和 Di-1 应用循环移位表,得到 Ci 和 Di for (int i = 1; i < 17; i++) { C[i] = shift<28>(C[i - 1], LSHIFT[i]); D[i] = shift<28>(D[i - 1], LSHIFT[i]); DEBUG(cout << "C" << i << ": " << C[i] << endl;) DEBUG(cout << "D" << i << ": " << D[i] << endl;) } // 4. 拼合 Ci 和 Di ,生成 Temp, // 5. 对 Temp 应用 PC-2<56, 48> 压缩置换表,生成 Ki for (size_t i = 1; i < 17; i++) { bit56 CD = bit56(C[i].to_ullong()) << 28 | bit56(D[i].to_ullong()); K[i] = fillTable<56, 48>(CD, TABLE_PC2); DEBUG(cout << "K" << i << ": " << K[i] << endl;) } } bit64 DES::_encrypt(const bit64 &block, bool encrypt) const { // 私有方法:加密或解密过程 // 1. 对 TXT 应用 IP<64, 64> 置换表,得到 64 位 IP bit64 IP = fillTable<64, 64>(block, TABLE_IP); DEBUG(cout << "IP" << IP << endl;) bit32 L[17], R[17]; // 2. 将 IP 分为 左 32 位 L0 和 右 32 位 R0 L[0] = bit32((IP >> 32).to_ullong()); R[0] = bit32((IP << 32 >> 32).to_ullong()); DEBUG(cout << "L0: " << L[0] << endl;) DEBUG(cout << "R0: " << R[0] << endl;) // f 函数的定义 auto f = [this](const bit32& R, const bit48& K) { // 1. 对 32 位 R 应用 E<32, 48> 扩展置换表,生成 Temp bit48 E = fillTable<32, 48>(R, TABLE_E); // 2. 令 E = E + K,其中 + 为异或运算 E = E ^ K; DEBUG(cout << "E + K: " << E << endl;) // 3. 将 E 分为 6 位 8 组 B, // 对每组进行 S[i]<6, 4> 盒运算,生成 4 位 8 组 S // 拼合为 Temp bit6 B[9]; for (size_t i = 1; i < 9; i++) { B[i] = (E << (6 * (i - 1)) >> 42).to_ullong(); DEBUG(cout << "B" << i << ": " << B[i] << endl;) } bit4 S[9]; bit32 s = 0; for (size_t i = 1; i < 9; i++) { S[i] = Si(i, B[i]); s |= bit32(S[i].to_ullong()) << ((8 - i) * 4); DEBUG(cout << "S" << i << ": " << S[i] << endl;) } // 4. 对 Temp 应用 P<32, 32> 置换表,生成 P bit32 P = fillTable<32, 32>(s, TABLE_P); DEBUG(cout << "P: " << P << endl;) return P; }; // 3. 加密则令 Li = Ri-1 ,Ri = Li-1 + F(Ri-1, Ki),解密则令Li = Ri-1,Ri = Li-1 + F(Ri-1, K17-i) for (int i = 1; i < 17; i++) { L[i] = R[i - 1]; R[i] = L[i - 1] ^ f(R[i - 1], K[encrypt ? i : 17 - i]); } // 4. 拼合 R16, L16 为 64 位 RL bit64 RL = bit64(R[16].to_ullong() << 32 | L[16].to_ullong()); // 5. 对 RL 应用 IP-1 <64, 64>得到最终结果 bit64 res = fillTable<64, 64>(RL, TABLE_IP_REV); return res; } DES::DES(bit64 key) { // 构造函数 setKey(key); } bit4 DES::Si(size_t which, const bit6 &from) const { // 从 S 盒中取得对应值 unsigned int row = static_cast<unsigned int>(from[5]) << 1 | static_cast<unsigned int>(from[0]) << 0; unsigned int col = static_cast<unsigned int>(from[4]) << 3 | static_cast<unsigned int>(from[3]) << 2 | static_cast<unsigned int>(from[2]) << 1 | static_cast<unsigned int>(from[1]) << 0; bit4 res = S_BOX[which][row * 16 + col]; return res; } void DES::setKey(const bit64 &key) { // 公有方法:更新密钥 _updateKey(key); } bit64 DES::encryptBlock(const bit64 &block) const { // 公有方法:加密块 return _encrypt(block, true); } bit64 DES::decryptBlock(const bit64 &block) const { // 公有方法:解密块 return _encrypt(block, false); }
true
5bfcff71cfa3d6c180a140805d56d45102944cfa
C++
ivanpjr/myLab
/c++/Person/main.cpp
UTF-8
619
3.078125
3
[]
no_license
#include <iostream> #include "Person.hxx" #include "Dog.hxx" Person makeTwin(Person p){ p.toString(); return p; } int main() { Dog d1; d1.setName("Pink"); d1.setAge(4); cout << d1.toString(); d1.bark(); Person p1{"A",1, d1}; p1.setName("Ivan"); p1.setAge(40); cout << p1.toString(); // Dog d2; // d2.setName("Cookie"); // d2.setAge(1); // cout << d2.toString(); // d2.bark(); // // Person p2{"B",2, d2}; // p2.setName("Dri"); // p2.setAge(39); // cout << p2.toString(); Person twin = makeTwin(p1); twin.toString(); return 0; }
true
f867e7b8cca3d563d48633c7e9f9590d5702d459
C++
andrewrk/motrs
/src/ConfigManager.h
UTF-8
978
2.984375
3
[]
no_license
#ifndef CONFIGMANAGER_H #define CONFIGMANAGER_H #include <map> #include <string> // ConfigManager brings together arguments and config files class ConfigManager { public: ConfigManager(); // adding configuration - the most recent thing you add will overwrite if // there is a name conflict. // reads C-style command line arguments and adds them to the configuration bool addArgs(int argc, char * argv[]); // reads an INI file format and fills out a propsMap hash // use "section.property" as a key in the map to get the value // returns true if there were no errors adding the file bool addFile(std::string filename); // get a value from config std::string value(std::string key, std::string defaultValue = ""); // the command used to start the program (only applies if you addArgs) std::string command(); private: std::map<std::string, std::string> m_map; std::string m_command; }; #endif // CONFIGMANAGER_H
true
f15c778f431f10be3ec91d15e2614d7bce67f872
C++
jvff/mestrado-implementacao
/src/test/cpp/FakeImageMockProxy.hpp
UTF-8
1,230
2.859375
3
[]
no_license
#ifndef FAKE_IMAGE_MOCK_PROXY_HPP #define FAKE_IMAGE_MOCK_PROXY_HPP #include <memory> #include "fakeit.hpp" #include "FakeImage.hpp" using namespace fakeit; template <typename PixelType> class FakeImageMockProxy { private: using FakeImageType = FakeImage<PixelType>; std::unique_ptr<Mock<FakeImageType> > mock; FakeImage<PixelType>& instance; public: FakeImageMockProxy(unsigned int width, unsigned int height) : mock(new Mock<FakeImageType>()), instance(mock->get()) { setUpMock(width, height); } Mock<FakeImageType>& getMock() { return *mock; } unsigned int getWidth() const { return instance.getWidth(); } unsigned int getHeight() const { return instance.getHeight(); } void setPixel(unsigned int x, unsigned int y, PixelType pixel) { instance.setPixel(x, y, pixel); } protected: void setUpMock(unsigned int width, unsigned int height) { auto& mock = *this->mock; When(Method(mock, getWidth)).AlwaysReturn(width); When(Method(mock, getHeight)).AlwaysReturn(height); When(Method(mock, setPixel).Using(Lt(width), Lt(height), _)) .AlwaysReturn(); } }; #endif
true
6b881ee30b8f20d5ad38ef7f163b71b88c0ceaa6
C++
Yukarinn/cc3k
/player.cc
UTF-8
4,900
2.984375
3
[]
no_license
#include "player.h" #include "treasure.h" #include "potion.h" #include "cell.h" #include "enemy.h" #include "merchant.h" #include <algorithm> #include <iostream> using namespace std; Player::Player(string name, int hp, int atk, int def, int maxHp, int baseAtk, int baseDef): Character(name, '@', hp, atk, def, ObjectType::Player), maxHp{maxHp}, baseAtk{baseAtk}, baseDef{baseDef} {} Player::~Player() { if (onHoard) delete onHoard; } int Player::getMaxHp() const { return maxHp; } int Player::getBaseAtk() const { return baseAtk; } int Player::getBaseDef() const { return baseDef; } int Player::getGold() const { return gold; } void Player::setGold(int gold) { this->gold = gold; } void Player::reset() { this->setAtk(baseAtk); this->setDef(baseDef); } void Player::drink(Potion* potion) { switch(potion->getPotionType()) { case PotionType::RH: if (name == "Vampire") // edge case for vampire who has no max hp setHp(getHp() + 10); else setHp(min(maxHp, getHp() + 10)); break; case PotionType::BA: setAtk(getAtk() + 10); break; case PotionType::BD: setDef(getDef() + 10); break; case PotionType::PH: setHp(max(0, getHp() - 10)); break; case PotionType::WA: setAtk(max(0, getAtk() - 10)); break; case PotionType::WD: setDef(max(0, getDef() - 10)); break; } delete potion; } // gets gold and deletes treasure bool Player::pick(Treasure* treasure) { switch (treasure->getTreasureType()) { case TreasureType::SM: gold ++; delete treasure; return true; case TreasureType::NO: gold += 2; delete treasure; return true; case TreasureType::ME: gold += 4; delete treasure; return true; case TreasureType::HN: gold += 6; delete treasure; return true; case TreasureType::HD: onHoard = treasure; return false; } } // when moving, first check if there is // treasure to be picked up, if so, // grab it first string Player::move(Cell* cell) { string ret = ""; Cell* prev = this->cell; prev->clearObject(); if (onHoard) { // if the player was on hoard spot previous turn, put but hoard into the cell prev->setObject(onHoard); onHoard = nullptr; } ret += grab(cell); cell->setObject(this); this->setCell(cell); return ret; } // grabs treasure, // if parameter argument is own cell // try to grab the dragon hoard string Player::grab(Cell* cell) { string ret = ""; if (this->cell != cell && cell->getObject() && cell->getObject()->getType() == ObjectType::Treasure) { Treasure* treasure = dynamic_cast<Treasure*>(cell->getObject()); string name = treasure->getName(); if (pick(treasure)) ret = "picks up " + name; } if (this->cell == cell && onHoard && onHoard->getTreasureType() == TreasureType::HN) { ret = "picks up " + onHoard->getName(); delete onHoard; onHoard = nullptr; gold += 6; cell->setObject(this); } return ret; } // spots nearby potions string Player::spot() { string ret = ""; Cell* cell = this->cell; vector<Cell*> neighbours = cell->getNeighbours(); for (auto each: neighbours) { if (each->getObject() && each->getObject()->getType() == ObjectType::Potion) { ret += "a " + dynamic_cast<Potion*>(each->getObject())->getEffect() + ", "; } } if (ret != "") { //return string shouldn't have ending comma ret.pop_back(); ret.pop_back(); } return ret; } // damage calculations // accounting for different player/enemy interactions string Player::strike(Enemy* enemy) { int damage = ceil((100.0/(100.0 + enemy->getDef())) * atk); if (enemy->getName() == "Halfling" && rand() % 2) { return "PC's attack on the halfling missed (" + to_string(enemy->getHp()) + " HP). "; } if (enemy->getDisplay() == 'M') { Merchant::setAggro(true); } enemy->setHp(max(0, enemy->getHp() - damage)); string ret = "PC deals " + to_string(damage) + " damage to " + enemy->getName() + " (" + to_string(enemy->getHp()) + " HP). "; if (name == "Vampire") { if (enemy->getName() == "Dwarf") { ret += "Lost 5 HP. "; hp -= 5; hp = max(hp, 0); } else { ret += "Drained 5 HP. "; hp += 5; } } if (enemy->getHp() == 0) { enemy->drop(); if (name == "Goblin") { ret += "Stole 5 gold. "; gold += 5; } } return ret; }
true
7a6c2275bdc65747abc45eb472cf790ab1629187
C++
dubhunter/ArduinoSketches
/hackpack-tictactoe/hackpack-tictactoe.ino
UTF-8
5,231
2.734375
3
[]
no_license
#include <Metro.h> #include <Adafruit_NeoPixel.h> #include <Adafruit_GFX.h> #include <Adafruit_NeoMatrix.h> #include "RGB.h" #define PIN_MATRIX 1 #define PIN_CLOUD A1 Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 8, PIN_MATRIX, NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE, NEO_GRB + NEO_KHZ800 ); int brightness = 10; RGB textColor = white; RGB textBackground = teal; RGB colors[4] = { off, red, blue, white }; // This 8x8 array represents the LED matrix pixels. // A value of 1 means we’ll fade the pixel to white int board[8][8] = { {0, 0, 3, 0, 0, 3, 0, 0}, {0, 0, 3, 0, 0, 3, 0, 0}, {3, 3, 3, 3, 3, 3, 3, 3}, {0, 0, 3, 0, 0, 3, 0, 0}, {0, 0, 3, 0, 0, 3, 0, 0}, {3, 3, 3, 3, 3, 3, 3, 3}, {0, 0, 3, 0, 0, 3, 0, 0}, {0, 0, 3, 0, 0, 3, 0, 0} }; int command = 0; int playing = 0; Metro timeout = Metro(300000); // 5 minutes int flashTimes = 4; int flashDelay = 100; int demoDelay = 800; String demoMsg = "TXT2PLAY 415.319.XOXO"; void setup() { Serial.begin(9600); Serial.println("Started"); pinMode(PIN_CLOUD, INPUT); matrix.begin(); matrix.setBrightness(brightness); matrix.setTextColor(matrix.Color(textColor.r, textColor.g, textColor.b)); matrix.setTextWrap(false); drawBoard(); delay(1000); } void loop() { if (!playing || timeout.check()) { demo(); playing = 0; } command = round(analogRead(1) / 10.24); Serial.println(command); if (command > 10) { playing = 1; timeout.reset(); } } void demo() { drawBoard(); delay(demoDelay); makeMove(1, 1); drawBoard(); delay(demoDelay); makeMove(2, 3); drawBoard(); delay(demoDelay); makeMove(1, 5); drawBoard(); delay(demoDelay); makeMove(2, 6); drawBoard(); delay(demoDelay); makeMove(1, 9); drawBoard(); delay(demoDelay); for (int i = 0; i < flashTimes; i++ ) { fillScreen(off); delay(flashDelay); drawBoard(); delay(flashDelay); } clearMoves(); fadeScreen(off, textBackground, 30, 3); scrollText(demoMsg); scrollText(demoMsg); } void drawBoard() { for(int row = 0; row < 8; row++) { for(int column = 0; column < 8; column++) { fillPixel(column, row, colors[board[row][column]], false); } } matrix.show(); } void makeMove(int player, int cell) { switch (cell) { case 1: board[0][0] = player; board[0][1] = player; board[1][0] = player; board[1][1] = player; break; case 2: board[0][3] = player; board[0][4] = player; board[1][3] = player; board[1][4] = player; break; case 3: board[0][6] = player; board[0][7] = player; board[1][6] = player; board[1][7] = player; break; case 4: board[3][0] = player; board[3][1] = player; board[4][0] = player; board[4][1] = player; break; case 5: board[3][3] = player; board[3][4] = player; board[4][3] = player; board[4][4] = player; break; case 6: board[3][6] = player; board[3][7] = player; board[4][6] = player; board[4][7] = player; break; case 7: board[6][0] = player; board[6][1] = player; board[7][0] = player; board[7][1] = player; break; case 8: board[6][3] = player; board[6][4] = player; board[7][3] = player; board[7][4] = player; break; case 9: board[6][6] = player; board[6][7] = player; board[7][6] = player; board[7][7] = player; break; } } void clearMoves() { for (int cell = 1; cell <= 9; cell++) { makeMove(0, cell); } } void fillScreen(RGB color) { matrix.fillScreen(matrix.Color(color.r, color.g, color.b)); matrix.show(); } // Crossfade entire screen from startColor to endColor void fadeScreen(RGB startColor, RGB endColor, int steps, int wait) { for(int i = 0; i <= steps; i++) { RGB newColor = colorStep(startColor, endColor, steps, i); fillScreen(newColor); delay(wait); } } void fillPixel(int x, int y, RGB color, int show) { matrix.drawPixel(x, y, matrix.Color(color.r, color.g, color.b)); if (show) { matrix.show(); } } // Fade pixel (x, y) from startColor to endColor void fadePixel(int x, int y, RGB startColor, RGB endColor, int steps, int wait) { for(int i = 0; i <= steps; i++) { RGB newColor = colorStep(startColor, endColor, steps, i); fillPixel(x, y, newColor, true); delay(wait); } } RGB colorStep(RGB startColor, RGB endColor, int steps, int step) { return { startColor.r + (endColor.r - startColor.r) * step / steps, startColor.g + (endColor.g - startColor.g) * step / steps, startColor.b + (endColor.b - startColor.b) * step / steps }; } void scrollText(String textToDisplay) { int x = matrix.width(); int pixelsInText = textToDisplay.length() * 7; matrix.setCursor(x, 0); matrix.print(textToDisplay); matrix.show(); while(x > (matrix.width() - pixelsInText)) { matrix.fillScreen(matrix.Color(textBackground.r, textBackground.g, textBackground.b)); matrix.setCursor(--x, 0); matrix.print(textToDisplay); matrix.show(); delay(150); } }
true
da53241178d1715537dd82de87e3620af436326d
C++
fusion-research/SensorNetworkSimulator
/dataskewing/GridSquare.cpp
UTF-8
2,349
2.734375
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // GridSquare.cpp // Implementation file for GridSquare class //////////////////////////////////////////////////////////////////////////////// // Includes //////////////////////////////////////////////////////////////////// #include "GridSquare.h" // GridSquare ////////////////////////////////////////////////////////////////// GridSquare::GridSquare() { // GridSquare XL = 0.0; YL = 0.0; XU = 0.0; YU = 0.0; CenterPointX = 0.0; CenterPointY = 0.0; OffsetX = 0.0; OffsetY = 0.0; InitialOffset = 0.0; } // GridSquare GridSquare::~GridSquare() { // ~GridSquare Deinit(); } // ~GridSquare void GridSquare::Init(double CX, double CY, double X1, double Y1, double X2, double Y2, double OX, double OY) { // Init Deinit(); CenterPointX = CX; CenterPointY = CY; XL = X1; YL = Y1; XU = X2; YU = Y2; OffsetX = OX; OffsetY = OY; InitialOffset = OX; } // Init void GridSquare::Deinit() { // Deinit XL = 0.0; YL = 0.0; XU = 0.0; YU = 0.0; CenterPointX = 0.0; CenterPointY = 0.0; OffsetX = 0.0; OffsetY = 0.0; InitialOffset = 0.0; } // Deinit void GridSquare::SetCenterPoint(double CX, double CY) { // SetCenterPoint CenterPointX = CX; CenterPointY = CY; } // SetCenterPoint void GridSquare::SetOffset(double OX, double OY) { // SetOffset InitialOffset = OX; OffsetX = OX; OffsetY = OY; if (OffsetX > 0.0) OffsetX = 0.0; if (OffsetY > 0.0) OffsetY = 0.0; } // SetOffset double GridSquare::GetCenterPointX(void) { // GetCenterPointX return(CenterPointX); } // GetCenterPointX double GridSquare::GetCenterPointY(void) { // GetCenterPointY return(CenterPointY); } // GetCenterPointY double GridSquare::GetLX(void) { // GetLX return(XL); } // GetLX double GridSquare::GetLY(void) { // GetLY return(YL); } // GetLY double GridSquare::GetUX(void) { // GetUX return(XU); } // GetUX double GridSquare::GetUY(void) { // GetUY return(YU); } // GetUY double GridSquare::GetOffsetX(void) { // GetOffsetX return(OffsetX); } // GetOffsetX double GridSquare::GetOffsetY(void) { // GetOffsetY return(OffsetY); } // GetOffsetY
true
cee43b33a2cad374f554ee93b70d030dd1b7ea1a
C++
cvu16/Adopet
/team1_1/GUI/zip.cpp
UTF-8
2,930
2.578125
3
[]
no_license
#include "zip.h" #include "ui_zip.h" /*! * \brief Zip constructor sets up connection between system and api * \param parent */ Zip::Zip(QWidget *parent) : QWidget(parent), ui(new Ui::Zip) { ui->setupUi(this); manager = new QNetworkAccessManager(); QString os = QSysInfo::productVersion(); if(os == "10.16"){ filename = "../../../../../csvs/zip.txt"; } else { //default picture filename = "../../csvs/zip.txt"; } connect(manager, &QNetworkAccessManager::finished, this, [&](QNetworkReply *reply){ //all relavent methods to the api call should be called here QByteArray data = reply->readAll(); QString str = QString::fromLatin1(data); ui->result->setText(str); results = str.toStdString(); //cout << results << endl; string fname = filename.toStdString(); ofstream csv; //now the problem is how to get this information to a different class //ideas: using the file to pass information back and forth, emit a signal writeToFile(); //parseResults(); }); } Zip::~Zip() { delete ui; } /*! * \brief zip intiates the api call, note: lm * \param code zipcode * \param distance in miles, string */ void Zip::zip(string code, string distance){ //API keys (for when we exceed the number of free requests) // //"Pet Finder" XXuDakVCPsq0RGZ64Jq4SFodgwq4Wr3nEGLST7tMxOyS2Q2KShkmykJfbkVd3Zbm manager->get((QNetworkRequest(QUrl("https://www.zipcodeapi.com/rest/XXuDakVCPsq0RGZ64Jq4SFodgwq4Wr3nEGLST7tMxOyS2Q2KShkmykJfbkVd3Zbm/radius.csv/" + QString::fromStdString(code) + "/" + QString::fromStdString(distance) + "/mile")))); } /*! * \brief writeToFile write api response results to file */ void Zip::writeToFile(){ string fname = filename.toStdString(); ofstream csv; //clear the old file's contents csv.open(fname, ofstream::out | ofstream::trunc); csv.close(); //write results to the file csv.open(fname, ios_base::app); csv << results; csv.close(); emit finishedCall(); } /*! * \brief parseResults parses the output file * \return vector of zipcodes in strings */ vector<string> Zip::parseResults(){ vector<string> zips; QFile file(filename); if(!file.open(QIODevice::ReadOnly)){ cerr << "Error: file not opened" << endl; } QTextStream in(&file); int lineNumber = 0; while(!in.atEnd()) { QString line = in.readLine(); QStringList zipOutput = line.split(","); if(lineNumber != 0){ string zip = zipOutput.at(0).toStdString(); zips.push_back(zip); } lineNumber++; } file.close(); zipCodes = zips; for(int i = 0; i < (int) zips.size(); i++){ //cout << "From zips" << zips.at(i) << endl; } for(int i = 0; i < (int) zipCodes.size(); i++){ //cout << "From zipCodes" << zipCodes.at(i) << endl; } return zips; }
true
74a21af08091644db4a71c1d1b398e9121b02b51
C++
headec/C-Practice
/stack.cpp
UTF-8
1,953
3.78125
4
[]
no_license
#include<iostream> #include<string> using namespace std; class Stack { private: int top; int arr[5]; public: Stack() { top = -1; for(int i = 0; i<5; i++) { arr[i]=0; } } bool isEmpty() { if(top==-1) return true; else return false; } bool isFull() { if(top==4) return true; else return false; } void push(int val) { if(isFull()) { cout<<"stack overflow"<<endl; } else { top++; arr[top]=val; } } int pop() { if(isEmpty()) { cout<<"stack underflow"<<endl; return 0; } else { int popValue = arr[top]; arr[top] = 0; top--; return popValue; } } int count() { return ++top; } int peek(int pos) { if(isEmpty()) { cout<<"stack underflow"<<endl; return 0; } else { return arr[pos]; } } void change(int pos, int val) { arr[pos] =val; cout<<"value changed at location"<<pos<<endl; } void display() { cout<<"All values in the Stack are"<<endl; for (size_t i = 4; i >=0; i--) { cout<<arr[i]<<endl; } } }; int main() { Stack s1; int option,position,value; do { cin>>option; switch(option) { case 1: cout<<"Item to Push"<<endl; cin>>value; s1.push(value); break; // case 2: } } while(option!=0); return 0; }
true
a640f663fcd4108c0211a3043ae5d605f597b28d
C++
jayramsidh/julylongchallenge
/tomnandjerry.cpp
UTF-8
505
2.609375
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int main () { int tc; cin>>tc; while(tc--) { long long int ts,k=1; cin>>ts; if(ts%2==1) { ts=ts/2; } else { k=0; } while(k==0) { ts=ts/2; if(ts%2==1) { ts=ts/2; break; } } cout<<ts<<endl; } }
true
e417a3119d06c5e53145aefc29cb04f6adcaed36
C++
ahmed-dardery/Programming-I
/Assignment 2/Ciphers/Cipher 3.cpp
UTF-8
2,453
3.4375
3
[]
no_license
/* FCI – Programming 1 – 2018 - Assignment 2 Program Name: Cipher 3.cpp Last Modification Date: 28/02/2018 Ashraf Samir Ali (AshrafSamir): G2 - 20170053 Purpose: This is a program that implements cipher #3: ROT13 Cipher. Algorithm >> take input as letter from user check if (userLetter[i]<78 and userLetter[i]>=65) or (userLetter[i]<110 and userLetter[i]>=97) then take this char and add 13 else if userLetter[i]>=78 and userLetter[i]<=90 ) or (userLetter[i]>=110 and userLetter[i]<=122) then take this char and - 13 else take this char and print it without changes */ #include <iostream> #include <string> #include <bits/stdc++.h> using namespace std; int main() { cout<<"Ahlan ya user ya habibi ."<<endl; while (true){ cout<<"What do you like to do today? "<<endl; cout<<"1- Cipher a message"<<endl; cout<<"2- Decipher a message"<<endl; cout<<"3- End"<<endl; bool isOk=true ; string userLetter,cipherMessage ; int youLike; while(isOk){ cin>>youLike; cin.ignore(); if(youLike<=0 || youLike>3){ while(youLike<=0 || youLike>3){ cout<<"choose 1 or 2 or 3"<<endl; cin>>youLike; cin.ignore(); if(youLike>0 && youLike<=3){ cout<<" confirm your number "<<endl; } } } else if(youLike==1 || youLike == 2){ cout<<"Enter a message: "<<endl; getline(cin,userLetter); for(int i=0; i<userLetter.length(); i++){ if((userLetter[i]<78 && userLetter[i]>=65) || (userLetter[i]<110 &&userLetter[i]>=97 ) ){ cipherMessage=userLetter[i]+13; cout<<cipherMessage; } else if((userLetter[i]>=78 &&userLetter[i]<=90 )|| (userLetter[i]>=110 &&userLetter[i]<=122)){ cipherMessage=userLetter[i]-13; cout<<cipherMessage; } else{ cipherMessage=userLetter[i]; cout<<cipherMessage; } } isOk=false; } else if(youLike==3){ return 0; } } cout << endl; } return 0; }
true
0ddcfa3135de5c02cb0cc32a4e5925f0079ad9d9
C++
myungoh/DS_Project_2_2021_2
/VaccinationData.h
UTF-8
1,150
2.828125
3
[]
no_license
#pragma once using namespace std; #include <iostream> #include <cstring> #include <fstream> #include <map> #include <math.h> #include <vector> #include <algorithm> #include <deque> #include <queue> #include <stack> #include <string> #include <functional> #include <iomanip> class VaccinationData { private: string UserName; // User name int age; // User age string VaccineName; // Vaccine name string LocationName; // Location name int times; // The number of vaccination public: VaccinationData() { LocationName = ""; UserName = ""; times = 0; } ~VaccinationData() { } //--NODE information in-- void SetUserName(string in_name) { UserName = in_name; } void SetVaccineName(string in_name) { VaccineName = in_name; } void SetLocationName(string in_location) { LocationName = in_location; } void SetTimes(int in_times) { times = in_times; } void SetAge(int in_age) { age = in_age; } void SetTimesInc() { times++; } string GetUserName() { return UserName; } string GetVaccineName() { return VaccineName; } string GetLocationName() { return LocationName; } int GetTimes() { return times; } int GetAge() { return age; } };
true
42c360e3e6bf2af0bcaa4540f14a725962f13841
C++
ZwodahS/z_curses
/f_curses.cpp
UTF-8
2,486
2.84375
3
[]
no_license
#include "f_curses.hpp" namespace zc { void drawBox(WINDOW* window, const WindowRegion& region) { // draw the corners mvwaddch(window, region.y, region.x, ACS_ULCORNER); // upper left corner. mvwaddch(window, region.y, region.x + region.width - 1, ACS_URCORNER); // upper right corner. mvwaddch(window, region.y + region.height - 1, region.x, ACS_LLCORNER); // lower left corner. mvwaddch(window, region.y + region.height - 1, region.x + region.width - 1, ACS_LRCORNER); // lower right corner. // draw al the lines if(region.width > 2) { mvwhline(window, region.y, region.x + 1, ACS_HLINE, region.width - 2); // top line mvwhline(window, region.y + region.height - 1, region.x + 1, ACS_HLINE, region.width - 2); // bottom line } if(region.height > 2) { mvwvline(window, region.y + 1, region.x, ACS_VLINE, region.height - 2); // left line mvwvline(window, region.y + 1, region.x + region.width - 1, ACS_VLINE, region.height - 2); // right line } } void drawBorderBox(WINDOW* window) { wborder(window, ACS_VLINE, ACS_VLINE, ACS_HLINE, ACS_HLINE, ACS_ULCORNER, ACS_URCORNER, ACS_LLCORNER, ACS_LRCORNER); } void mvwteehline(WINDOW* window, const int& y, const int& x, const int& width) { mvwaddch(window, y, x, ACS_LTEE); mvwhline(window, y, x + 1, ACS_HLINE, width-2); mvwaddch(window, y, x + width - 1, ACS_RTEE); } void print(WINDOW* window, const RowRegion& row, const std::string& message, const AlignmentX& alignment, const int& offset) { if(alignment == AlignmentX::Left) { mvwprintw(window, row.y, row.x + offset, message.c_str()); } else if(alignment == AlignmentX::Right) { mvwprintw(window, row.y, row.x + row.width - message.size() - offset, message.c_str()); } else { mvwprintw(window, row.y, row.x + (row.width - message.size())/2 + offset, message.c_str()); } } WindowRegion centerRegion(const WindowRegion& innerRegion, const WindowRegion& outerRegion) { // calculate the spare space. int spareX = outerRegion.width - innerRegion.width; int spareY = outerRegion.height - innerRegion.height; return WindowRegion(spareX / 2, spareY / 2, innerRegion.width, innerRegion.height); } };
true
d83c4deb8cedb9682248f3fbe33d80ceaf899f92
C++
chiha8888/Code
/uva11995 - I Can Guess the Data Structure!.cpp
UTF-8
1,112
2.875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int n; vector<int> input; vector<int> output; bool cmp(const int &a,const int &b){ return a>b; } int main(){ int t,x; while(cin>>n){ input.clear(); output.clear(); vector<string> ans; for(int i=0;i<n;i++){ cin>>t>>x; if(t==1){ input.push_back(x); } else output.push_back(x); } if(output.size()>input.size()){ cout<<"impossible"<<endl; continue; } int inputl=input.size(); int outputl=output.size(); //FIFO int i; for(i=0;i<outputl;i++){ if(input[i]!=output[i]){ break; } } if(i==outputl) ans.push_back("queue"); //LIFO for(i=0;i<outputl;i++){ if(input[inputl-1-i]!=output[i]){ break; } } if(i==outputl) ans.push_back("stack"); //priority_queue sort(input.begin(),input.end(),cmp); for(i=0;i<outputl;i++){ if(input[i]!=output[i]){ break; } } if(i==outputl) ans.push_back("priority queue"); if(ans.empty()) cout<<"impossible"<<endl; else if(ans.size()==1) cout<<ans[0]<<endl; else cout<<"not sure"<<endl; } return 0; }
true
c6812e2e546584618b145a3a41be5b7e9fb7a4a5
C++
hahaite/EulerProject
/069/main.cpp
UTF-8
891
2.671875
3
[]
no_license
#include <cstdio> #include <sys/time.h> #include "../mymath/mymath.h" using namespace std ; int main() { timeval tFirst ; timeval tSecond ; timeval tWorking ; gettimeofday(&tFirst, NULL) ; ///////////////////////////////////////////////////////////////////// CDivisor divisor ; int eulerPhi ; int max = 0 ; double nof ; double max_nof = 0 ; for(int ii = 2; ii <= 1000000; ii++) { if(ii % 10000 == 9999) printf("ing - %d\n", ii) ; eulerPhi = divisor.eulerPhi(ii) ; nof = (double)ii/eulerPhi ; if(nof > max_nof) { max_nof = nof ; max = ii ; printf("%d - %f\n", ii, nof ) ; } } printf("Result : %d\n", max) ; ///////////////////////////////////////////////////////////////////// gettimeofday(&tSecond, NULL) ; timersub(&tSecond, &tFirst, &tWorking) ; printf("Working Time : [%d.%06d]\n", tWorking.tv_sec, tWorking.tv_usec) ; return 1 ; }
true
7c46bf037d1f8a562c7808f96a55a9a7d61fe58e
C++
EmilioIb/Juego_Vaqueros
/Clases_EmilioIbarra.cpp
ISO-8859-1
5,833
3.109375
3
[]
no_license
#include<iostream> #include<stdlib.h> #include<time.h> using namespace std; //Clase pistola class Pistola{ private: int vida, balas; public: Pistola(); void setPistola(int, int); int getBalas(); int getVida(); }; //Variables Pistola jugador, maquina; int dificultad, accion, opc, enemigo; //Constructor Pistola::Pistola(){ } //Setter void Pistola::setPistola(int _vida, int _balas){ vida = _vida; balas = _balas; } //Getter int Pistola::getBalas(){ return balas; } int Pistola::getVida(){ return vida; } void imprimir(){ cout<<" __________ __________ "<<endl; cout<<" | | | |"<<endl; cout<<" | | | | | | | |"<<endl; cout<<" | | | |"<<endl; cout<<" | ______ | | ______ |"<<endl; cout<<" |__________| |__________|"<<endl; cout<<" Jugador Maquina "<<endl; cout<<" "<<jugador.getVida()<<"ps\t\t "<<maquina.getVida()<<"ps\n"; cout<<" "<<jugador.getBalas()<<" balas\t\t "<<maquina.getBalas()<<" balas\n\n"; } void turno(){ int balasjug, vidajug, balasene, vidaene; balasjug = jugador.getBalas(); vidajug = jugador.getVida(); balasene = maquina.getBalas(); vidaene = maquina.getVida(); while((vidajug > 0) && (vidaene > 0)){ imprimir(); do{ cout<<"Acciones: "<<endl; cout<<"1.- Disparar"<<endl; cout<<"2.- Recargar"<<endl; cout<<"3.- Cubrirse"<<endl; cout<<"Opcion: "; cin>>opc; if(balasjug == 0 && opc == 1){ cout<<"No tienes balas en el cargador"<<endl; opc = 5; } }while(opc > 3 || opc < 0); srand(time(NULL)); enemigo =1+rand()%(4-1); if(balasene == 0 && enemigo == 1){ enemigo = 2; } if(balasene == 3 && enemigo == 2){ int num=1+rand()%(3-1); if(num == 1){ enemigo = 1; } else{ enemigo = 3; } } switch(opc){ case 1: switch(enemigo){ case 1: cout<<"Ambos disparan, las balas se cruzan y no ocurre nada"<<endl; maquina.setPistola(vidaene, balasene-1); jugador.setPistola(vidajug, balasjug-1); break; case 2: cout<<"Tu oponente recarga, pero tu disparas, le diste"<<endl; maquina.setPistola(vidaene-1, 3); jugador.setPistola(vidajug, balasjug-1); break; case 3: cout<<"Tu disparas, pero tu oponente se cubre"<<endl; jugador.setPistola(vidajug, balasjug-1); break; } break; case 2: switch(enemigo){ case 1: cout<<"Recargas, pero tu enemigo dispara, te dieron"<<endl; jugador.setPistola(vidajug-1, 3); maquina.setPistola(vidaene, balasene-1); break; case 2: cout<<"Ambos recargan"<<endl; maquina.setPistola(vidaene, 3); jugador.setPistola(vidajug, 3); break; case 3: cout<<"Tu oponente se cubre, y tu aprovechas para recargar"<<endl; jugador.setPistola(vidajug, 3); break; } break; case 3: switch(enemigo){ case 1: cout<<"Tu oponente dispara, pero tu te proteges"<<endl; maquina.setPistola(vidaene, balasene-1); break; case 2: cout<<"Mientras tu te cubres, tu oponente recarga"<<endl; maquina.setPistola(vidaene, 3); break; case 3: cout<<"Ambos se cubren, panda de cobardes"<<endl; break; } break; } balasjug = jugador.getBalas(); vidajug = jugador.getVida(); balasene = maquina.getBalas(); vidaene = maquina.getVida(); system("pause"); system("cls"); } if(vidajug == 0){ system("color 04"); cout<<" PERDISTE :( "<<endl; cout<<" __________ __________ "<<endl; cout<<" | | | |"<<endl; cout<<" | X X | | | | |"<<endl; cout<<" | | | |"<<endl; cout<<" | XXXXXX | | ______ |"<<endl; cout<<" |__________| |__________|"<<endl; cout<<" PERDEDOR GANADOR "<<endl; } if(vidaene == 0){ system("color 0A"); cout<<" GANASTE :D "<<endl; cout<<" __________ __________ "<<endl; cout<<" | | | |"<<endl; cout<<" | | | | | X X |"<<endl; cout<<" | | | |"<<endl; cout<<" | ______ | | XXXXXX |"<<endl; cout<<" |__________| |__________|"<<endl; cout<<" GANADOR PERDEDOR "<<endl; } } int main(){ char jd; cout<<"\t\t\t\t--------- BIENVENIDO ---------"<<endl; cout<<"El programa es un pequeo juego de vaqueros, tienes 3 opciones: disparar, recargar, y cubrise. Por cada \nrecarga recuperas 3 balas. Al inicio del juego podras elegir la dificultad. Mucha Suerte"<<endl<<endl; cout<<"\t\t\t\t CLASES "<<endl; cout<<"\t\t\t\t EMILIO IBARRA VALDEZ "<<endl; cout<<"\t\t\t\t ESTRUCTURAS DE DATOS "<<endl; cout<<"\t\t\t\t 4B 14/04/2021 "<<endl<<endl; do{ system("color 07"); system("pause"); system("cls"); do{ cout<<"\t Seleciona la dificultad \n"; cout<<"\t---- 1.- FACIL ----\n"; cout<<"\t---- 2.- MEDIO ----\n"; cout<<"\t---- 3.- DIFICIL ----\n"; cout<<"\t Opcion: "; cin>>dificultad; if(dificultad > 3 || dificultad < 1){ cout<<"Opcion Incorrecta"<<endl; } system("pause"); system("cls"); }while(dificultad > 3 || dificultad < 1); switch(dificultad){ case 1: jugador.setPistola(3,0); maquina.setPistola(1,0); break; case 2: jugador.setPistola(2,0); maquina.setPistola(2,0); break; case 3: jugador.setPistola(1,0); maquina.setPistola(3,0); break; } turno(); cout<<"\nQuieres jugar de otra vez? (S/N)\nOpc:"; cin>>jd; system("cls"); }while(jd == 's' || jd == 'S'); system("pause"); return 0; }
true
3e44294477d5e99bd1796742d891e75a6eb6ffbe
C++
AlexeyOgurtsov/GStar
/Source/Core/Str/IdentStr.h
UTF-8
4,576
3.28125
3
[]
no_license
#pragma once #include "Core/CoreSysMinimal.h" #include <cstdlib> #include <boost/serialization/array.hpp> /** * TO-BE-CHECKED-COMPILED. * TO-BE-TESTED. * * TODO: * 1. Provide the storage class for storing IdentStr instances and the default instance of it. */ /** * Identifier string. * Immutable ANSI string. * * WARNING 1: NOT a C-style str (NO terminating zero)!!! * WARNING 2: NOT automatically copied to some internal storage by the constructor!!! * * Reference semantics: * - To be passed by value; * - Compares with itself by reference, NOT by value; * - Copy operation is allowed but copies only pointer to string, never copies the string itself; */ class IdentStr { public: /** * Maximal length allowed for the identifier. * We use such a great value, so filesystem paths can also be treated as identifiers. */ constexpr static int MAX_LENGTH = 1024; /** * Checks whether the given CStr can be used as an identifier. */ static bool IsValidIdent(const char* CStr, int& OutLength); /** * Checks whether the given CStr can be used as an identifier. */ static bool IsValidIdent(const char* CStr) { int OutLength; return IsValidIdent(CStr, OutLength); } /** * Constructs an invalid identifier (equivalent of the nullptr). */ __forceinline constexpr IdentStr() : Ptr(nullptr), Length(0) {} /** * Constructs an identifier by the given C-str ptr. */ __forceinline explicit IdentStr(const char* InCStr) : Ptr(InCStr) { int CStrLength; bool const bCStrIsValidIdent = IsValidIdent(InCStr, /*out*/ CStrLength); BOOST_ASSERT_MSG(bCStrIsValidIdent, "IdentStr constructor: provided string cannot be used as ident"); Length = static_cast<short>(CStrLength); } /** * Constructs an identifier by the given pointer and length. */ constexpr IdentStr(const char* InPtr, int InLength) : Ptr(InPtr), Length(static_cast<short>(InLength)) { BOOST_ASSERT_MSG(InPtr, "nullptr should NOT be passed to the IdentStr constructor"); BOOST_ASSERT_MSG(InLength >= 0, "Negative length is passed to the IdentStr constructor"); BOOST_ASSERT_MSG(InLength <= MAX_LENGTH, "IdentStr is too long"); } /** * Copy constructs by reference. */ IdentStr(const IdentStr& InOther) : Ptr(InOther.Ptr), Length(InOther.Length) {} /** * Copies by reference. */ IdentStr& operator=(const IdentStr InOther) { Ptr = InOther.Ptr; Length = InOther.Length; return *this; } /** * Checks whether this instance represents a valid identifier. */ __forceinline bool Valid() const { return nullptr != Ptr; } /** * Returns length. * * WARNING!!! We delibarately convert to int to avoid additional compiler warnings. */ __forceinline constexpr int Len() const { return Length; } /** * Checks for emptiness. */ __forceinline constexpr bool Empty() const { return 0 == Length; } /** * Copies string to the buffer. */ void CopyToBuffer(char* pOutBuffer, int InMaxBufferLength) { CopySubstrToBuffer(pOutBuffer, InMaxBufferLength, Length); } /** * Copies the substring to the buffer. * WARNING!!! C-str termintator is NOT appended automatically!!! */ void CopySubstrToBuffer(char* pOutBuffer, int InMaxBufferLength, int InLengthToCopy, int InStartSrcIndex = 0) { BOOST_ASSERT_MSG(InStartSrcIndex >= 0, "IdentStr: SubstrToBuffer: Negative start src index"); BOOST_ASSERT(pOutBuffer); BOOST_ASSERT_MSG(InStartSrcIndex + InLengthToCopy <= Length, "IdentStr: SubstrToBuffer: substring to copy is beyond the length"); BOOST_ASSERT(InLengthToCopy <= InMaxBufferLength); memcpy(pOutBuffer, Ptr + InStartSrcIndex, InLengthToCopy); } friend class boost::serialization::access; /** * boost::serialization support. */ template<class Ar> void serialize(Ar& InAr, const unsigned int InVersion) { InAr & boost::serialization::make_array(Ptr, Length); } /** * Computes hash. */ size_t Hash() const; friend bool operator==(const IdentStr A, const IdentStr B); friend bool operator<(const IdentStr A, const IdentStr B); private: const char* Ptr; short Length; }; /** * Checking for equality by comparing references. */ inline bool operator==(const IdentStr A, const IdentStr B) { return A.Ptr == B.Ptr; } /** * Checking for NON=equality by comparing references. */ inline bool operator!=(const IdentStr A, const IdentStr B) { return ! operator==(A, B); } /** * std streams output */ template<class Strm> Strm& operator<<(Strm& Strm, const IdentStr S) { return Strm << S; } namespace std { template<> struct hash<IdentStr> { size_t operator() (const IdentStr S) const { return S.Hash(); } }; } // std
true
dc3255b0475cf75b7b54cb15c6b0b4cc13ce956e
C++
tttapa/random
/Zynq-AMP/SharedMem.hpp
UTF-8
4,360
2.921875
3
[]
no_license
#pragma once #include <ANSIColors.hpp> #include <iomanip> #include <iostream> #include <cassert> #include <cerrno> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> const size_t PAGE_SIZE = getpagesize(); const uintptr_t PAGE_MASK = ~((uintptr_t) PAGE_SIZE - 1); const uintptr_t OFFSET_MASK = (uintptr_t) PAGE_SIZE - 1; class SharedMemReferenceCounter { public: SharedMemReferenceCounter() { if (count == 0) // If this is the first instance openMem(); // the memory has to be opened ++count; } ~SharedMemReferenceCounter() { --count; if (count == 0) // If this was the last instance closeMem(); // the memory has to be closed } // Delete copy constructor and copy assignment SharedMemReferenceCounter(const SharedMemReferenceCounter &) = delete; SharedMemReferenceCounter & operator=(const SharedMemReferenceCounter &) = delete; int getFileDescriptor() const { return mem_fd; } private: void openMem() { mem_fd = open( // "/dev/mem", // file path O_RDWR | O_SYNC // flags ); if (mem_fd < 0) { std::cerr << ANSIColors::redb << "open(/dev/mem) failed (" << errno << ")" << ANSIColors::reset << std::endl; std::ostringstream oss; oss << "open(/dev/mem) failed (" << errno << ")"; throw std::runtime_error(oss.str()); } } void closeMem() { close(mem_fd); } static size_t count; static int mem_fd; }; template <class T> class BaremetalShared { public: BaremetalShared() { // Get the base address of the page, and the offset within the page. uintptr_t base = T::address & PAGE_MASK; uintptr_t offset = T::address & OFFSET_MASK; // Make sure we don't cross the page boundary assert(offset + sizeof(T) <= PAGE_SIZE); std::cout << std::hex << std::showbase << "T::address = " << T::address << ", base = " << base << ", offset = " << offset << ", PAGE_SIZE = " << PAGE_SIZE << ", PAGE_MASK = " << PAGE_MASK << std::dec << std::noshowbase << std::endl; // Map the hardware address of the shared memory region into the virtual // address space of the program. // Offset should be aligned to a page, and size should be a multiple of // the page size. memmap = mmap( // nullptr, // address PAGE_SIZE, // length PROT_READ | PROT_WRITE, // protection MAP_SHARED, // flags sharedMem.getFileDescriptor(), // file descriptor base // offset ); if (memmap == MAP_FAILED) { std::ostringstream oss; oss << "mmap(" << std::hex << std::showbase << base << std::dec << std::noshowbase << ") failed (" << errno << ")"; std::cerr << ANSIColors::redb << "mmap(" << std::hex << std::showbase << base << std::dec << std::noshowbase << ") failed (" << errno << ")" << ANSIColors::reset << std::endl; throw std::runtime_error(oss.str()); } uintptr_t memmapp = reinterpret_cast<uintptr_t>(memmap); structdata = reinterpret_cast<volatile T *>(memmapp + offset); std::cout << std::hex << std::showbase << "memmap = " << memmap << std::endl; for (size_t i = 0; i < sizeof(T); ++i) { int data = reinterpret_cast<volatile uint8_t *>(structdata)[i]; std::cout << data << " "; } std::cout << std::dec << std::noshowbase << std::endl; } BaremetalShared(const BaremetalShared &) = delete; BaremetalShared &operator=(const BaremetalShared &) = delete; ~BaremetalShared() { munmap(memmap, PAGE_SIZE); } volatile T *ptr() { return structdata; } volatile T *operator->() { return structdata; } private: volatile T *structdata; void *memmap; SharedMemReferenceCounter sharedMem; };
true
7f9d70e80ae3b542a193e1e02f6032f69b6d4a38
C++
unegare/crypto
/dummy_hash_miner/include/Message.h
UTF-8
1,718
3.03125
3
[]
no_license
#pragma once #include <thread> #include <array> #include <string> class Message { public: enum class MessageType { randomInitValueSet, newSolution }; protected: MessageType _type; std::thread::id _thread_id; int64_t _timestamp; public: Message() = delete; Message(MessageType, int64_t timestamp, std::thread::id) noexcept; virtual ~Message() = 0; virtual std::string toJSON() const = 0; MessageType getType() const noexcept; std::thread::id getThreadId() const noexcept; int64_t getTimestamp() const noexcept; }; class MessageNewRandomInitValueSet : public Message { std::array<uint8_t, 32> _initValue; public: MessageNewRandomInitValueSet(std::array<uint8_t, 32>, int64_t timestamp = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(), std::thread::id = std::this_thread::get_id()) noexcept; virtual ~MessageNewRandomInitValueSet() override; virtual std::string toJSON() const override; const std::array<uint8_t, 32>& getInitValue() const noexcept; }; class MessageNewSolution : public Message { std::array<uint8_t, 32> _data; std::array<uint8_t, 32> _hash; int64_t _timestamp; public: MessageNewSolution(std::array<uint8_t, 32> _data, std::array<uint8_t, 32> _hash, int64_t timestamp = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(), std::thread::id = std::this_thread::get_id()) noexcept; virtual ~MessageNewSolution() override; virtual std::string toJSON() const override; const std::array<uint8_t, 32>& getData() const noexcept; const std::array<uint8_t, 32>& getHash() const noexcept; };
true
4fc3163c8e3ac98c15883f80c2fca3c506688d22
C++
enjoyars/libec
/src/test/test-ec.cpp
UTF-8
3,553
2.640625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <string.h> #include <string> #include "ec.h" int main(int argc, char **argv) { if (argc != 3) { printf("Name: rf21x-test \n"); printf("Usage: rf21x-test DeviceType PortPath \n"); printf(" Usage Example: rf21x-test rf217 hid:// \n"); printf(" Usage Example: rf21x-test rf217 hid://0007800D \n"); printf(" Usage Example: rf21x-test rf217 serial:///dev/ttyUSB0 \n"); printf(" Usage Example: rf21x-test rf217 tcp://192.168.1.10:9000+hid:// \n"); printf("Parameters:\n"); printf(" DeviceType: rf217, rf218, rf219, rf215. \n"); printf(" PortPath: PortType://PortAddress. \n"); printf(" PortType: hid, serial, tcp \n"); printf(" PortAddress: port address \n"); printf("************************************************************\n"); printf("Press any key to exit.\n"); while (1) { if (getchar() > 0) { break; } } return 0; } // User can use serial number as address like "hid://0007800D" to select a HID device to be opened. printf("Current HID devices: %s\n", ec_enumerateAllHidPorts()); char *typeName = argv[1]; int deviceType = EC_DT_Unknown; if (strcmp(typeName, "rf217") == 0) { deviceType = EC_DT_RF217; } else if (strcmp(typeName, "rf218") == 0) { deviceType = EC_DT_RF218; } else if (strcmp(typeName, "rf219") == 0) { deviceType = EC_DT_RF219; } else if (strcmp(typeName, "rf215") == 0) { deviceType = EC_DT_RF215; } else { printf("DeviceType error.\n"); } printf("Start! \n"); ec_Port port = ec_openPort("hid://", 256000); if (port == NULL) { printf("ec_openPort Error. \n"); return 0; } ec_Device device = ec_createDevice(port, deviceType); // ec_setDeviceMode(device, EC_DM_Static); // ec_sleep(500); // int address = 112233; // printf("---------------%d \n", address); // address = ec_startDynamicRegistration(device, address); // printf("---------------%d \n", address); // address = ec_continueDynamicRegistration(device, address); // printf("---------------%d \n", address); // ec_stopDynamicRegistration(device); // return 0; if (ec_connectDevice(device, 1, 40) == 0) { printf("ec_openDevice Error. \n"); return 0; } ec_sleep(1000); if (ec_startQuiz(device, EC_QT_Single, 4, -1, 1) == 0) { printf("ec_startQuiz Error. \n"); return 0; } // ec_setKeypadId(device, 1); // ec_sleep(1000); // ec_Event event; // for (int i = 0; i < 100; ++i) // { // if (ec_getEvent(device, &event) == 0) // { // ec_sleep(100); // continue; // } // printf("Event: %d (%d, %d, %d, %d): %s \n", // event.keypadId, event.eventType, event.quizType, event.quizNumber, event.timeStamp, // event.data); // } // ec_stopDynamicRegistration(device); printf("Getting Events... \n"); while (1) { ec_Event event; if (ec_getEvent(device, &event)) { printf("%d: %s \n", event.keypadId, event.data); } else { ec_sleep(1); } } ec_sleep(2000); ec_stopQuiz(device); ec_disconnectDevice(device); ec_destroyDevice(device); ec_closePort(port); printf("Finish \n"); return 0; }
true
1bfe24084ca17ca1bcc15dc6b38fd1a79ec936c2
C++
DDavis01/ECE2036
/Lab1/Lab1Part2.cc
UTF-8
2,292
3.515625
4
[]
no_license
/* Author: Donald Andrew Davis Date last modified: 1/27/2019 Organization: ECE2036 Class Description: ECE 2036 Lab 1 Part 2: Round Off Error */ #include <iostream> #include <cmath> using namespace std; double doubleQuadraticFunction(int sign, double a,double b,double c){ // Double implementation of the quadratic function double root; double num; double den1; double den2; double ans; num = 2*c; root = sqrt((b*b)-(4*a*c)); den1 = -b+root; den2 = -b-root; if(sign==1){ ans = num/den1; } else{ ans = num/den2; } return ans; } float floatQuadraticFunction(int sign, float a, float b, float c){ // Float implementation of the quadratic function float root; float num; float den1; float den2; float ans; num = 2*c; root = sqrt((b*b)-(4*a*c)); den1 = -b+root; den2 = -b-root; if(sign==1){ ans = num/den1; } else{ ans = num/den2; } return ans; } int main(){ float ansPlusFloat; float ansMinFloat; double ansPlusDouble; double ansMinDouble; double dError1; double dError2; float fError1; float fError2; ansPlusFloat = floatQuadraticFunction(1,2.0f,6000.002f,6.0f); ansMinFloat = floatQuadraticFunction(0,2.0f,6000.002f,6.0f); ansPlusDouble = doubleQuadraticFunction(1,2.0,6000.002,6.0); ansMinDouble = doubleQuadraticFunction(0,2.0,6000.002,6.0); dError1 = 100*((-0.001)-ansMinDouble)/-0.001; dError2 = 100*(-3000-ansPlusDouble)/-3000; fError1 = 100*((-0.001)-ansMinFloat)/-0.001; fError2 = 100*(-3000-ansPlusFloat)/-3000; cout.precision(10); cout << "Float Results:" << endl; cout << "X1 = " << ansPlusFloat << " " << "% Error = " <<fError1 << endl; cout << "X2 = " << ansMinFloat << " " << "% Error = " <<fError2 << endl; cout.precision(17); cout << "Double Results:"<<endl; cout << "X1 = " << ansPlusDouble << " " << "% Error = " <<dError1 << endl; cout << "X2 = " << ansMinDouble << " " << "% Error = " <<dError2 << endl; return 0; }
true
e79000180dbdc84746719859aee83472e675a99e
C++
kanumadai/Cplusplus
/ACQCenter v4.1.0N32R/SIO.h
GB18030
6,627
2.71875
3
[]
no_license
#ifndef __sio_h__ #define __sio_h__ class CSIO; //״̬ typedef enum _alarm_stat { normal=0, alarm=1 }ALARM; typedef union _alarm_code { BYTE code8; struct{ BYTE bAlarm_T:1; //¶ȱ BYTE bAlarm_V:1; //ѹ BYTE bAlarm_I:1; // BYTE bAlarm_Move:1; //˶ BYTE bAlarm_Moto:1; // BYTE Reserve : 3; // }; }ALARM_CODE; //Դ״̬ typedef enum _rod_stat { unknow=0, out=1, //λ in=2, //صλ outing=3, // ining=4, // rolling=5, //ת stop=6 //ֹͣ }ROD_STAT; typedef ROD_STAT SEPTA_STAT; //rolling is invalid //״̬ typedef enum _bed_stat { still, //ֹ move, //˶ out_stop, // in_stop //ջص }BED_STAT; //Ƶ·Ϣ typedef struct _mctl_info { BOOL bInitOK; BYTE cInitStatus[4]; WORD wT_GANTRY; //GANTRY¶ WORD wT_WATERCOOL; //ˮ¶ WORD wT_Rod; //ROD¶ WORD wT_Septa; //Septa¶ WORD wT_Bed; //¶ BYTE HVStatus; //ѹ״̬ WORD wV_1; //ѹ1 WORD wV_2; //ѹ2 WORD wI_1; //1 WORD wI_2; //2 //ֵ WORD wTH_V_H; //ѹ WORD wTH_V_L; //ѹ WORD wTH_I_H; // WORD wTH_I_L; // WORD wTH_GANTRYT_H; //GANTRY¶ WORD wTH_GANTRYT_L; //GANTRY¶ WORD wTH_WATERCOOLT_H; //ˮ¶ WORD wTH_WATERCOOLT_L; //ˮ¶ // ALARM alarm_Gantry; //GANTRY ALARM_CODE ac_Gantry; ALARM alarm_Bed; //BED ALARM_CODE ac_Bed; ALARM alarm_Septa; //SEPTA ALARM_CODE ac_Septa; ALARM alarm_Rod; //ROD ALARM_CODE ac_Rod; ALARM alarm_ESTOP; //ͣ ALARM alarm_HV; ALARM_CODE ac_HV; //ѹ //ԴϢ ROD_STAT Rod_stat; //Դ״̬/ WORD wRod_rate; //Դת WORD wRod_SwitchSet; //Դ //Ϣ BED_STAT Bed_stat; WORD wBed_SwitchSet; // WORD wBed_posx; //λ,0.1MM WORD wBed_posy; WORD wBed_step; // WORD wBed_bRelateCoord; //ϵͳ 1=꣬0= //SEPTAλϢ SEPTA_STAT septa_stat; WORD wSepta_SwitchSet; BOOL bHVOn; //ѹ״̬ BOOL bLaserOn; //״̬ BOOL bMainPowerOn; //ǰԴ״̬ }MCTL_INFO; #define SIO_ANSWER_TIMEOUT 2000/*ms*/ #define ROD_ANSWER_TIMEOUT 90000/*ms*/ #define SEPTA_ANSWER_TIMEOUT 90000/*ms*/ #define BED_ANSWER_TIMEOUT 60000/*ms*/ //move speed:700mm/60s-> class CSIO { public: CSIO(); ~CSIO(); public: BOOL QueryInitStatus(); BOOL QueryRodStatus(); BOOL SendTestDat(const BYTE* pBuf, int nBufLen); BOOL Control_RodRoll(); BOOL Dbg_GCPollingEnable(BOOL bEnable); BOOL SetRodRate(WORD rate); //ðԴת BOOL SetBedCoord(BOOL bRelate); //ôϵͳꡢ BOOL SetBedStep(WORD step); //ô // BOOL Control_SeptaIn(void); // BOOL Control_SeptaStop(void); // BOOL Control_SeptaOut(void); BOOL Control_BedStopAll(void); //д˶ BOOL Control_BedStopY(void); //Y˶ BOOL Control_BedStopX(void); //X˶ BOOL Control_BedMoveYStep(BOOL bUp); //ƴ˶ BOOL Control_BedMoveXStep(BOOL bOut); BOOL Control_BedMoveX(WORD len/*0.1mm*/); //ƴ˶ BOOL Control_BedMoveY(WORD len/*0.1mm*/); BOOL Control_BedMoveYRelate(WORD len/*0.1mm*/, BOOL bUp); BOOL Control_BedMoveXRelate(WORD len/*0.1mm*/, BOOL bOut); //ƴ˶ BOOL Control_RodOut(); //ưԴת BOOL Control_RodStop(); //ưԴֹͣת BOOL Control_RodIn(); //ưԴջ BOOL Control_RodEStop(); //ưԴֹͣ BOOL Control_LaserON(BOOL bON); //Ƽͨ BOOL QueryTBed(); // BOOL QueryTRod(); BOOL QueryRodRate(); //ѯԴת BOOL QueryRodSwitchSet(); BOOL QueryBedSwitchSet(); BOOL QueryBedMoveStatus(); BOOL QueryBedStep(); //ѯ˶ BOOL QueryBedPos(void); //ѯ BOOL OpenSIO(const char* szPort); BOOL CloseSIO(); void SetSIOMode(BOOL bTest); // BOOL QueryHVStatus(); // BOOL QuerySeptaStatus(); // BOOL SetThreshold_HV(WORD upper, WORD lower); //øѹ // BOOL SetThreshold_I(WORD upper, WORD lower); //õ // BOOL SetThreshold_TW(WORD upper, WORD lower); //ˮ¶ // BOOL SetThreshold_TG(WORD upper, WORD lower); //GANTRY¶ // BOOL Control_SeptaEStop(); // BOOL Control_SeptaIn(void); // BOOL Control_SeptaStop(void); // BOOL Control_SeptaOut(void); // BOOL Control_MainPowerON(BOOL bON); //ǰԴͨ // BOOL Control_HVON(BOOL bON); //Ƹѹͨ // BOOL QueryTSepta(); // BOOL QueryTWaterCool(); //ѯˮ¶ // BOOL QueryTGantry(); //ѯGANTRY¶ // BOOL QueryThreshold_HV(); //ѯѹ // BOOL QueryThreshold_I(); //ѯ // BOOL QueryThreshold_TW(); //ѯˮ¶ // BOOL QueryThreshold_TG(); //ѯGANTRY¶ // BOOL QuerySeptaSwitchSet(); public: DWORD _ThreadRecvComm(); protected: HANDLE m_hCom; HANDLE m_hThread; HANDLE m_hEvtExit; BOOL m_bSIOMode_Test; BOOL Process_GantryDat(SIO_FRAME12* pFrame); BOOL RecvFrame(OVERLAPPED* pOL, BYTE* pFrameBuf, int nBufLen); BOOL WriteComm(LPCVOID pBuf, int len); CRITICAL_SECTION m_CLockWrite; //дٽ SIO_FRAME8 m_WFrame8; SIO_FRAME9 m_WFrame9; SIO_FRAME12 m_WFrame12; OVERLAPPED m_olWrite; HANDLE m_hEvtWrite; protected: HANDLE m_hEvtSIO_HandShake; //GANTRAYӦ¼ HANDLE m_hEvtSIO_Retry; //ط¼ HANDLE m_hEvtSIO_TVI; //յ¶ȡѹ¼ HANDLE m_hEvtSIO_ROD; //Դ¼ HANDLE m_hEvtSIO_Bed; //¼ HANDLE m_hEvtSIO_Septa; //Septa¼ HANDLE m_hEvtSIO_SetOK; //Ч HANDLE m_hEvtSIO_Answer; //ͨӦ¼ }; #endif
true
8c90425ecd6ff6c505232baba8d1d26c05d9bdfb
C++
MayurHadole/Burglar-Alarm
/BurglarAlarmProject.ino
UTF-8
48,521
3.1875
3
[]
no_license
/* FILE : BurglarAlarmProject.ino * PROJECT : PROG8125-16S - Project * PROGRAMMER : Mayur Hadole (5783) * FIRST VERSION : 2016-07-31 * DESCRIPTION : * Project Statement (No. 2) * Burglar alarm that monitors 5 zones. Zones are monitored by a loop of wire. * Circuitry is needed that can detect if the loop has been broken (an Alarm Condition) * or shorted (a fault condition). The alarm should accept a password from the serial port * in order to enable or disable the entire alarm or individual zones. User output should * be done using a speaker and LCD. * * I have used the state machine to make the burglar alarm with above funtions and some extra functions * * State 1:PASSWORD AUTHENTICATION * Shows the welcome message on LCD and then asks for password to enter using serial port.If * the password is correct the program moves to the next state else user gets two more tries to * get the password right.System is blocked if all three attempts are used. * * State 2:INITIALIZING SYSTEM * High Signal is written on all five loops through loopIn pins. These High Signals will be used to * moniter the loop break, faults and normal status of loops. * * State 3:ZONE SELECTION * In this State the program asks the user using LCD screen to enter the numbers of zones that needs to be monitered. * If the user enteres "all" on Serial port then all zones are saved in a array. * And If the user enters the names of zones(from 1 to 5) that needs to be monitered with commas in between then those * zones are saved in the array. * * State 4:ARMED * In this state, all the loops are checked by reading inputs from loop out pins. Depending upon their ADC readings * their status is determined. Following is the range of ADC values for all three states. * * ADC Value Status * 255 Normal * 1 Fault * 2 to 254 Loop Break (intruder alert) * * In this same state, if all the loops are in normal state . All Zones Safe message is displayed on LCD Screen and Serial port * Along with the thumbs up symbol. * * State 5: BREACH DETECTED * In this State, the status of zones which were selected in previous state are stored in the array.(one array for fault zones and * another one for loop break zones). * These arrays are used to call functions to display the status on LCD and to play the alarm using speaker. * If zones are in loop break state then intruder alert message is displayed on the screen along with the "running person" symbol. * And if the zones are in fault state then fault message is displayed on the screen with the bitmapped fault syambol. * If some zones are in fault state and some are in loop break state then both fault and intruder alert messages are displayed on * LCD screen with the gap of 1 second in between them. * * State 6. DISABLE BURGLAR ALARM * This is the state in which the program resets using external interrupt connected to push button. * if the push button is pressed at any time during the execution of program the system will reset to state 1. * * * Extra Features * 1. Three bitmapped Symbols are used to display on lcd for three different states. * State Symbol * Loop Break Running Man * Fault Exclamation symbol in the square * Normal Thumbs up symbol * * 2. External interrupt is used to reset the system to state 1. * 3. System is blocked if more than three times the entered password is wrong * 4. millis() is used to generate the alarm sound * * This code is tested on Teensy 3.1 board */ #include <LiquidCrystal.h> //Includes library files for LCD /* LCD RS pin to digital pin 12 LCD Enable pin to digital pin 11 LCD D4 pin to digital pin 14 LCD D5 pin to digital pin 15 LCD D6 pin to digital pin 16 LCD D7 pin to digital pin 17 LCD R/W pin to ground LCD VSS pin to ground LCD VCC pin to 5V */ LiquidCrystal lcd(12, 11, 14, 15, 16, 17); // initialize the library with the numbers of the interface pins // Folowing are the various states of the program #define PASSWORDAUTHENTICATION 1 #define INITIALIZINGSYSTEM 2 #define ZONESELECTION 3 #define ARMED 4 #define BREACHDETECTED 5 #define DISABLEBURGLARALARM 6 #define NumberOfZones 5 //number of zones to moniter #define loop1In 2 //startpoint of loop 1 const uint8_t loop2In = 4; //startpoint of loop 2 const uint8_t loop3In = 5; //startpoint of loop 3 const uint8_t loop4In = 6; //startpoint of loop 4 const uint8_t loop5In = 9; //startpoint of loop 5 const uint8_t loop1Out = 9; //Endpoint of loop 1 const uint8_t loop2Out = 8; //Endpoint of loop 2 const uint8_t loop3Out = 7; //Endpoint of loop 3 const uint8_t loop4Out = 6; //Endpoint of loop 4 const uint8_t loop5Out = 5; //Endpoint of loop 5 const uint8_t disablePin = 13; // Disable pushButton is conected to pin 1 const uint8_t speakerPin = 10; //speaker is connected to pin 10 const uint16_t frequencyOfTone = 2000; //Frequency of the alarm sound const uint8_t allAreSelected = 1; //all the zones are selected const uint8_t someAreSelected = 2; //not all zones are selected const uint8_t ASCIItoINTconstant = 48; // to convert the datatype from char to int const uint8_t normalStateValue = 255; // loop is not broken, Normal condition const uint8_t faultStateValue = 1; // loop is connected to the ground , Fault condition const uint8_t normalState = 1; // constanst to represent normal state const uint8_t faultState = 2; // constanst to represent fault state const uint8_t loopBreakState = 3; // constanst to represent loop break state( intruder alert) const uint8_t breachDetected = 1; // constant to represent fault or loop break state const uint8_t defaultCharArrayLength = 20; // default length of serial input data for zone selection const uint8_t correctPassword = 1; // constant to represent correct password is entered const uint8_t incorrectPassword = 2; // constant to represent incorrect password is entered const uint16_t delayOf2Seconds = 2000; const uint16_t delayOf1Second = 1000; const uint16_t SerialBaudRate = 9600; const uint8_t NumberOfColumnsInLCD = 2; //Number Of Columns In LCD are 2 const uint8_t NumberOfRowsInLCD = 16; //Number Of Rows In LCD are 16 const uint8_t firstRowOfLCD = 0; //first row on LCD const uint8_t secondRowOfLCD = 1; //second row on LCD const uint8_t firstColumnOfLCD = 0; //first Column of LCD const uint8_t secondColumnOfLCD = 1; //second Column of LCD const uint8_t thirdColumnOfLCD = 2; //third Column of LCD const uint8_t fifthColumnOfLCD = 4; //fifth Column of LCD const uint8_t fourthColumnOfLCD = 3; // fourth column of LCD const uint8_t bitMapByteArraySize = 8 ; // array size for the byte array used to print symbols on LCD static uint8_t burglarAlarmState = PASSWORDAUTHENTICATION ; // this is the variable which will control the state machine // this variable is made global because I want to change the state of state machine using interrupt handler. // it is initialized to the very first state "PASSWORDAUTHENTICATION" //prototypes of the functions used in this program void displayTitle(); uint8_t getAndCheckPassword(); uint8_t *zonesSelection(); uint8_t *stringSeparation( char inputCharArray[] , uint8_t inputCharArrayLength ); void initializingZones(); void displayArmed(); uint8_t *checkZones(); void displayAllZonesNormal(); void displayAlarmZones( uint8_t breakZones[ NumberOfZones ], uint8_t selectedZones[] ); void displayFaultZones( uint8_t faultZones[ NumberOfZones ], uint8_t selectedZones[] ); uint8_t zonesCount(uint8_t *selectedZones); void disableISR(void); void displayThumbsUP(); void displayIntruder(); void displayFaultSymbol(); void alarmTone(); void displayLeftAttemptsMessage( uint8_t passwordAttempts ); void displayBlocked(); void setup() { pinMode(loop1In , OUTPUT); //loop1In pin is set as a output pin pinMode(loop2In , OUTPUT); //loop2In pin is set as a output pin pinMode(loop3In , OUTPUT); //loop3In pin is set as a output pin pinMode(loop4In , OUTPUT); //loop4In pin is set as a output pin pinMode(loop5In , OUTPUT); //loop5In pin is set as a output pin pinMode(speakerPin , OUTPUT); //speaker pin is set as a output pin pinMode( disablePin , INPUT_PULLUP); //loop1In pin is set as a input pin with inter pullup resisters enabled Serial.begin(SerialBaudRate); //initializing the serial port with baud rate 9600 delay(delayOf2Seconds); // wait for serial port to be initialized lcd.begin (NumberOfColumnsInLCD, NumberOfRowsInLCD); // set up the LCD's with number of columns and rows attachInterrupt(digitalPinToInterrupt(disablePin), disableISR, FALLING); // interrupt is initialized on disable pin to call disableISR routine when push button connected to disable pin is pressed. displayTitle(); // displays title of the project on lcd and serial port } void loop() { static uint8_t *selectedZones; // integer pointer to get address of the integer array that has the names of selected zones. static uint8_t *zoneStatus; // integer pointer to get address of the integer arrat that has the state of each zone. switch (burglarAlarmState) // state machine that checks for the variable burglarAlarmState to change the state { case PASSWORDAUTHENTICATION : // State 1:PASSWORD AUTHENTICATION // Shows the welcome message on LCD and then asks for password to enter using serial port.If // the password is correct the program moves to the next state else user gets two more tries to // get the password right.System is blocked if all three attempts are used. { static uint8_t passwordAttempts = 3; // variable to keep track of the remaining attempts if the entered password is wrong uint8_t passwordStatus = 0; // a variable to save the status if entered password is correct or not do // do while loop is used to execute the code in the while loop 1st time unconditionally { // do- while loop is used to let user have extra two attempts if the entered password is wrong passwordStatus = getAndCheckPassword(); // function is called to get the password from serial port and compare it to the valid password and return the status. if ( passwordStatus == correctPassword ) // if the entered password is correct then { burglarAlarmState = INITIALIZINGSYSTEM ; // change the state to INITIALIZING SYSTEM } else if ( passwordStatus == incorrectPassword ) // if the entered password is incorrect then { passwordAttempts-- ; // decrementing left attempts by 1 displayLeftAttemptsMessage(passwordAttempts); // display left attemts message on LCD and Serial port } }while(passwordAttempts > 0 && passwordStatus != correctPassword ); // repeat the loop if password attemts are more than 1 and entered password is incorrect else exit the loop if(passwordAttempts == 0) // if password attemts are are zero then { displayBlocked(); // display "system Blocled " message on LCD and serial port } break ; } case INITIALIZINGSYSTEM : // State 2:INITIALIZING SYSTEM // High Signal is written on all five loops through loopIn pins. These High Signals will be used to // moniter the loop break, faults and normal status of loops. { initializingZones(); // function is called to write high on all the input pins of zones burglarAlarmState = ZONESELECTION ; // change the state to ZONE SELECTION break; } case ZONESELECTION : // State 3:ZONE SELECTION // In this State the program asks the user using LCD screen to enter the numbers of zones that needs to be monitered. // If the user enteres "all" on Serial port then all zones are saved in a array. // And If the user enters the names of zones(from 1 to 5) that needs to be monitered with commas in between then those // zones are saved in the array { selectedZones = zonesSelection(); // functions returns the address of the array that has the selected zones which are obtained by parsing input string from serial port burglarAlarmState = ARMED ; break; // change the state to ARMED } case ARMED : // State 4: ARMED // In this state, all the loops are checked by reading inputs from loop out pins. Depending upon their ADC readings // their status is determined. Following is the range of ADC values for all three states. // // ADC Value Status // 255 Normal // 1 Fault // 2 to 254 Loop Break (intruder alert) // // In this same state, if all the loops are in normal state . All Zones Safe message is displayed on LCD Screen and Serial port // Along with the thumbs up symbol. { static uint8_t displayArmedFlag = 1; // flag which is used to make sure the armed message is shown only once at the start of the program. thats why its static and initialized to 1 if (displayArmedFlag) { displayArmed(); // display armed message on LCD and serial port. } displayArmedFlag = 0; // set the flag to zero zoneStatus = checkZones(); // fuction returns the address of the array that has status of all the zones uint8_t normalZonesCounter = 0; // counter to calculate number of zones whose state are normal for ( uint8_t i = 0 ; i < NumberOfZones ; i++ ) // for loop to count normal zones { if ( *( zoneStatus + i) == normalState ) // if the data of the i'th index of the array pointed by the zoneStatus pointer is equal to normal state then { normalZonesCounter++; // increment the counter } } if ( normalZonesCounter == NumberOfZones ) // if all zones are normal then { displayAllZonesNormal(); // display "all zones normal" on the LCD and serial port } else // if all zones are not normal then { burglarAlarmState = BREACHDETECTED; // change the state to BREACH DETECTED } break; } case BREACHDETECTED : // State 5: BREACH DETECTED // In this State, the status of zones which were selected in previous state are stored in the array.(one array for fault zones and // another one for loop break zones). // These arrays are used to call functions to display the status on LCD and to play the alarm using speaker. // If zones are in loop break state then intruder alert message is displayed on the screen along with the "running person" symbol. // And if the zones are in fault state then fault message is displayed on the screen with the bitmapped fault syambol. // If some zones are in fault state and some are in loop break state then both fault and intruder alert messages are displayed on // LCD screen with the gap of 1 second in between them. { uint8_t breakZones[NumberOfZones] = { 0 }; //array to get the names of the zones which have loop Break state. if loop 1 is in loop break state then breakZone[0] will be 1 uint8_t faultZones[NumberOfZones] = { 0 }; //array to get the names of the zones which have fault state. if loop 1 is in fault state then breakZone[0] will be 1 boolean alarm = false; // flag to know if any zone or none are in loop break state boolean fault = false; // flag to know if any zone or none are in fault state for ( uint8_t i = 0 ; i < NumberOfZones ; i++ ) // for loop to get the status from zoneStatus (pointer that points to zoneStatus array) to the breakZones and faultZones { if ( *(zoneStatus + i) == loopBreakState ) // if the data of the i'th index of the array pointed by the zoneStatus pointer is equal to loop break state then { breakZones[i] = breachDetected ; // set i index of break zone array to 1 alarm = true; // loop break state is detected so setting the alarm flag to true } if ( *(zoneStatus + i) == faultState ) // if the data of the i'th index of the array pointed by the zoneStatus pointer is equal to fault state then { faultZones[i] = breachDetected ; // set i index of fault zone array to 1 fault = true; // fault state is detected so setting the fault flag to true } } if (alarm) // if any of the zones has loop break state then { displayAlarmZones(breakZones, selectedZones); // display intruder message for loop break zones for selected zones only. } if (fault) // if any of the zones has fault state then { displayFaultZones(faultZones, selectedZones); // display fault message for loop break zones for selected zones only } if (fault || alarm) // if any of the zones are not in normal state then { alarmTone(); // sound alarm using speaker connected to pin 10 } burglarAlarmState = ARMED; // change the state to ARMED break; } case DISABLEBURGLARALARM : // State 6. DISABLE BURGLAR ALARM // This is the state in which the program resets using external interrupt connected to push button. // if the push button is pressed at any time during the execution of program the system will reset to state 1. { displayDisable(); // display "burglar alarm disabled" on serial port and LCD displayTitle(); // display title on the LCD and Serial port burglarAlarmState = PASSWORDAUTHENTICATION ; // change the state to PASSWORD AUTHENTICATION break; } } } // FUNCTION : displayTitle // DESCRIPTION : // This function prints the title of the project on the LCD screen and serial port. // PARAMETERS : void // RETURNS : void void displayTitle() { lcd.clear(); lcd.print("BURGLAR ALARM "); //prints on LCD Serial.println("Burglar Alarm"); delay(delayOf1Second); lcd.clear(); } // FUNCTION : getAndCheckPassword // DESCRIPTION : // This function gets the wntered password from the serial port and campares it with valid password. If its correct then return 1 and if // it's incorrect returns 2. This function also displays required messages on LCD and Seria port to get the password and also shows // if entered password correct or not on LCD and serial port. // PARAMETERS : void // RETURNS : // uint8_t : the status is the entered password is correct or not // 1 for correct password // 2 for incorrect password uint8_t getAndCheckPassword() { uint16_t validPassword = 1234; // variable to save valid password uint16_t enteredPassword; //variable to save entered password from serial port lcd.clear(); Serial.println("Enter the Password"); lcd.printf(" Enter the"); lcd.setCursor( firstColumnOfLCD , secondRowOfLCD); lcd.printf(" Password"); while ( Serial.available() == 0 ) {} // wait for user to enter the password //this while loop's condition will became false when user enters something on serial port and hits send button enteredPassword = Serial.parseInt(); // gets the integer data from serial port to the variable if ( enteredPassword == validPassword ) // if entered password is equal to valid password then { lcd.clear(); lcd.printf("Correct Password"); Serial.println("Password is Correct"); delay(delayOf1Second); return correctPassword; // returns 1 if correct password is entered } else { lcd.clear(); lcd.printf("Wrong Password"); Serial.println("Password is Incorrect"); delay(delayOf1Second); return incorrectPassword; // returns 2 if incorrect password is entered } } // FUNCTION : zonesSelection // DESCRIPTION : // This function asks user to enter the names of zones that are needed to moniter or "all" for all zones on serial port. then,the input string from the serial port is // saved in a character array. If all zones are selected all zones are added into the integer array called selected zones and if soe of the zone are selected then other // function (stringSeparation())is called to parse zone nemes from the string entered on the serial port. // PARAMETERS : void // RETURNS : // uint8_t* : an integer pointer that returns the address of the array "selected Zones" uint8_t *zonesSelection() { uint8_t inputCharArrayLength; // to store the length of the string entered on serial port for zone selection char inputCharArray[ defaultCharArrayLength ]; // character array with default array length to store the string entered on serial port for zone selection uint8_t *selectedZones ; // integer pointer to point an integer array which saves which zones are selected selectedZones = (uint8_t *)malloc( NumberOfZones ); // Maximum number of selected zones = 5 so, so 5 memory locations are allocated to this pointer Serial.println("Enter which zones you want to moniter with commas"); Serial.println("Enter ALL for all zones"); lcd.clear(); lcd.setCursor( firstColumnOfLCD , firstRowOfLCD); lcd.printf("Enter zone No or"); lcd.setCursor( firstColumnOfLCD , secondRowOfLCD); lcd.printf("ALL for all zones"); while (Serial.available() == 0) {} // wait for user to enter the password //this while loop's condition will became false when user enters something on serial port and hits send button inputCharArrayLength = Serial.available(); // to get the length of the entered string on serial port in an integer for (uint8_t i = 0 ; i < inputCharArrayLength ; i++ ) // for loop to get each character of string in character array { inputCharArray[i] = Serial.read(); //get the i'th character of string available in serial buffer in i'th character of array } inputCharArray[ inputCharArrayLength + 1 ] = '\0'; // add the null character at the end of the character array to make it a string if (inputCharArray[0] == 'a' && // if user enters "all" on serial port then inputCharArray[1] == 'l' && // three characters are compared with AND condition inputCharArray[2] == 'l' ) { Serial.println("ALL zones are Selected"); // all zones are selected for (uint8_t i = 0 ; i < NumberOfZones ; i++) // for loop to store all the zones in memory pointed by the pointer { *(selectedZones + i) = (i + 1); //*(selectedZones + i) means contents of the address location pointed by ( pointer + i'th location) } // i+1 is used to stores selected zones because counter of loop is from 0 to 4 and names of zones are from 1 to 5 return selectedZones ; // return the pointer which points to the selected zones } else // if "all" is not entered on the serial port then { selectedZones = stringSeparation( inputCharArray , inputCharArrayLength ); // this function returns the pointer which points to the selected zones obtained from the serial port. // selected zones are obtained by parsing zones from the string ( zone numbers are separated by commas) return selectedZones; // returns the pointer which points to the selected zones } } // FUNCTION : stringSeparation // DESCRIPTION : // This function parses the selected zones from the entered string on the serial port. // PARAMETERS : // char inputCharArray[] : character array to get the entered string on serial port for zones selection. // uint8_t inputCharArrayLength : integer array to get length of the entered string on the serial port. // RETURNS : // uint8_t * : returns the integer pointer to the array which has the pasrsed data of selected zones from entered // sring on the serial port. uint8_t *stringSeparation( char inputCharArray[] , uint8_t inputCharArrayLength ) { static uint8_t selectedZones[ NumberOfZones ]; // An array to save selected zones obtained from the string entered on serial port. //for loop to get the names of the zones(1 to 5) to the integer array from the entered string on the serial port. for (uint8_t i = 0 ; i < inputCharArrayLength ; i++) { if ( i == 0) // very first character in the entered string will be zone name { selectedZones[0] = (int)inputCharArray[i] - ASCIItoINTconstant ; // to get the number of the zone in integer value into the array } else if (i == 2) // third character in the entred string will be zone number { selectedZones[1] = (int)inputCharArray[i] - ASCIItoINTconstant; // to get the number of the zone in integer value into the array } else if (i == 4) // fifth character in the entred string will be zone number { selectedZones[2] = (int)inputCharArray[i] - ASCIItoINTconstant; // to get the number of the zone in integer value into the array } else if (i == 6) // seventh character in the entred string will be zone number { selectedZones[3] = (int)inputCharArray[i] - ASCIItoINTconstant; // to get the number of the zone in integer value into the array } } return selectedZones; // return the address of the array which has the selected zones parsed from the input string. } // FUNCTION : initializingZones // DESCRIPTION : // This function that sends the HIGH signal on the all loop input pins. // PARAMETERS : void // RETURNS : void void initializingZones() { digitalWrite( loop1In , HIGH ); // a HIGH signal (ADC value of 255) on loop 1 input pin. digitalWrite( loop2In , HIGH ); // a HIGH signal (ADC value of 255) on loop 2 input pin. digitalWrite( loop3In , HIGH ); // a HIGH signal (ADC value of 255) on loop 3 input pin. digitalWrite( loop4In , HIGH ); // a HIGH signal (ADC value of 255) on loop 4 input pin. digitalWrite( loop5In , HIGH ); // a HIGH signal (ADC value of 255) on loop 5 input pin. } // FUNCTION : displayArmed // DESCRIPTION : // This function prints the "System is Arned" on the LCD Screen and Serial port. // PARAMETERS : void // RETURNS : void void displayArmed() { lcd.clear(); lcd.setCursor( firstColumnOfLCD , firstRowOfLCD); lcd.printf(" System Is"); lcd.setCursor( firstColumnOfLCD , secondRowOfLCD); lcd.printf(" ARMED"); Serial.println("\nSystem is Armed"); delay(delayOf1Second); // delay to show this message on LCD for one second before next message on the LCD. } // FUNCTION : checkZones // DESCRIPTION : // This function checks the status of all the zones by checking the ADC readings on Loop output pins of zones and saves it in the array // and returns it. // State ADC Value // Normal 255 // Loop Break 2 to 254 // fault 1 // PARAMETERS : void // RETURNS : // uint8_t * : integer pointer that points to the array which has the status of all zones uint8_t *checkZones() { static uint8_t zoneStatus[NumberOfZones]; //an array to save the state of the zone uint8_t loopReadings[NumberOfZones] ; //an array to save the ADC readings of loop output pins of all zones loopReadings[0] = analogRead( loop1Out ); // read the ADC value on loop 1 output pin loopReadings[1] = analogRead( loop2Out ); // read the ADC value on loop 2 output pin loopReadings[2] = analogRead( loop3Out ); // read the ADC value on loop 3 output pin loopReadings[3] = analogRead( loop4Out ); // read the ADC value on loop 4 output pin loopReadings[4] = analogRead( loop5Out ); // read the ADC value on loop 5 output pin //for loop is to check the states of all loops using their respective ADC readings. for ( uint8_t i = 0 ; i < NumberOfZones ; i++) { if ( loopReadings[i] == normalStateValue ) // i'th loop reading is equal to 255 then { zoneStatus[i] = normalState; // the state of (i+1)th zone is normal. (i+1) because zons names are from 1 to 5 and array index is from 0 to 4. } else if ( loopReadings[i] == faultStateValue ) // i'th loop reading is equal to 1 then { zoneStatus[i] = faultState; // the state of (i+1)th is fault . (i+1) because zons names are from 1 to 5 and array index is from 0 to 4. } else { zoneStatus[i] = loopBreakState; // the state of (i+1)th is loop break. } } return zoneStatus; // return the address of the array which saves the states of all zones } // FUNCTION : displayAllZonesNormal // DESCRIPTION : // This function prints the All zones are safe" on the LCD Screen and Serial port. This function also calls the function // to display bit-mapped symbol of thumbs up on the LCD screen. // PARAMETERS : void // RETURNS : void void displayAllZonesNormal() { lcd.clear(); displayThumbsUP(); // function to display thumbs up symbol on the LCD lcd.setCursor( fifthColumnOfLCD , firstRowOfLCD); lcd.printf("All Zones"); lcd.setCursor( fifthColumnOfLCD , secondRowOfLCD); lcd.printf("Safe"); Serial.println("All zones are safe"); delay(delayOf1Second); } // FUNCTION : displayAlarmZones // DESCRIPTION : // This function prints the "intruder alert" message on the LCD Screen and Serial port for the zones which were selected in zone selection state. // This function also calls the function to display bit-mapped symbol of "running man" on the LCD screen. // PARAMETERS : // uint8_t breakZones[ NumberOfZones ] : array to get the zones which has loop break state. // uint8_t selectedZones[] : array to get the zones which were selected in Zone Selection state. // RETURNS : void void displayAlarmZones( uint8_t breakZones[ NumberOfZones ], uint8_t selectedZones[] ) { uint8_t numberOfSelectedZones = zonesCount(selectedZones); // zonesCount function returns the number of zones selected by taking Selected zones array as a argument. lcd.clear(); displayIntruder(); //Displays the bit mapped "running man" symbol on the LCD screen lcd.setCursor( fourthColumnOfLCD , firstRowOfLCD); lcd.printf("Intruder in"); lcd.setCursor( fourthColumnOfLCD , secondRowOfLCD); lcd.printf("Zone"); Serial.printf(" Intruder alert in zones "); // for loop to display intruder alert message for zones which were selected to moniter(SelectedZones) for ( uint8_t i = 0 ; i < numberOfSelectedZones ; i++ ) { if ( breakZones[*(selectedZones + i) - 1 ] == breachDetected ) //the data pointed by the address (selectedZones +i) is the zone. // index of break zones array is from 0 to 4 and the zone names are from 1 to 5 so the loop break status of zone no. 1 // is stored in breakZones[0]. hence (-1) is used along with (*(selectedZones + i)) as the index of brekZones { lcd.printf("%d,", *(selectedZones + i) ); //print zone number on LCD Screen if the breakZones[*(selectedZones + i) - 1 ] == breachDetected Serial.printf("%d ,", *(selectedZones + i) ); //print zone number on Serial port if the breakZones[*(selectedZones + i) - 1 ] == breachDetected } } Serial.printf("\n"); // new line delay(delayOf1Second); // wait for 1 second so the message can be displayed on the screen before the next message } // FUNCTION : displayFaultZones // DESCRIPTION : // This function prints the "Fault in zones" message on the LCD Screen and Serial port for the zones which were selected in zone selection state. // This function also calls the function to display bit-mapped symbol of exclamation point in square on the LCD screen. // PARAMETERS : // uint8_t faultZones[ NumberOfZones ] : array to get the zones which has fault state. // uint8_t selectedZones[] : array to get the zones which were selected in Zone Selection state. // RETURNS : void void displayFaultZones( uint8_t faultZones[ NumberOfZones ], uint8_t selectedZones[] ) { uint8_t numberOfSelectedZones = zonesCount(selectedZones); // zonesCount function returns the number of zones selected by taking Selected zones array as a argument. lcd.clear(); displayFaultSymbol(); //Displays the bit mapped Exclamation point in the square symbol on the LCD screen lcd.setCursor( fourthColumnOfLCD , firstRowOfLCD); lcd.printf("Fault in zones"); Serial.printf(" fault in zones "); lcd.setCursor( fourthColumnOfLCD , secondRowOfLCD); // for loop to display fault message for zones which were selected to moniter(SelectedZones) for ( uint8_t i = 0 ; i < numberOfSelectedZones ; i++ ) { if ( faultZones[ *(selectedZones + i) - 1 ] == breachDetected ) //the data pointed by the address (selectedZones +i) is the zone. // index of fault zones array is from 0 to 4 and the zone names are from 1 to 5 so the fault status of zone no. 1 // is stored in faultZones[0]. hence (-1) is used along with (*(selectedZones + i)) as the index of brekZones { lcd.printf("%d,", *(selectedZones + i) ); //print zone number on LCD Screen if the breakZones[*(selectedZones + i) - 1 ] == breachDetected Serial.printf("%d ,", *(selectedZones + i) ); //print zone number on Serial port if the breakZones[*(selectedZones + i) - 1 ] == breachDetected } } Serial.printf("\n"); // new line delay(delayOf1Second); // wait for 1 second so the message can be displayed on the screen before the next message } // FUNCTION : zonesCount // DESCRIPTION : // This function returns the number of zones selected in zone selection state. // PARAMETERS : // uint8_t *selectedZones : an integer pointer that points to the selected zones array // RETURNS : // uint8_t : returns the number of zones selected in zone selection state. uint8_t zonesCount(uint8_t *selectedZones) { uint8_t numberOfSelectedZones = 0; // variable to save number of selected zones //while loop is used to increment the counter as long as the selected zones pointer points to the zero value or all zones are selected. while ( *selectedZones != 0 && numberOfSelectedZones < NumberOfZones ) { numberOfSelectedZones++; // increment the counter selectedZones++; // increment the pointer } return numberOfSelectedZones; // returns the number of zones selected in zone selection state. } // FUNCTION : displayDisable // DESCRIPTION : // This function prints the "Alarm Disabled" on the LCD Screen and Serial port. // PARAMETERS : void // RETURNS : void void displayDisable(void) { lcd.clear(); lcd.setCursor( firstColumnOfLCD , firstRowOfLCD); lcd.printf("Alarm Disabled"); Serial.println("Alarm Disabled"); delay(delayOf1Second); } // FUNCTION : alarmTone // DESCRIPTION : // This function sends PWM signal to speaker pin for alarm tone // PARAMETERS : void // RETURNS : void void alarmTone() { static unsigned long previousMillis = 0; // variable to check if the interval time is finished or not uint8_t interval = 10; static boolean speakerTone = true; // a flag to check if speaker is beeping or not unsigned long currentMillis = millis(); // variable to get the millis time if (currentMillis - previousMillis > interval) // if time passed is more than interval { previousMillis = currentMillis; // get the latest time after the interval is finished if (speakerTone == false) // if speaker is not beeping then { tone(speakerPin, frequencyOfTone); // start beeping speakerTone = true; //set the flag to true } else { noTone(speakerPin); // stop beeping speakerTone = false; // set the flag to false } } } // FUNCTION : displayLeftAttemptsMessage // DESCRIPTION : // This function prints the number of attempts remaining to enter correct password on the LCD Screen and Serial port. // PARAMETERS : // uint8_t passwordAttempts : integer to get the number of remaining attempts. // RETURNS : void void displayLeftAttemptsMessage( uint8_t passwordAttempts ) { lcd.clear(); lcd.setCursor( firstColumnOfLCD , secondRowOfLCD ); lcd.printf("Attempts left=%d", passwordAttempts); // displays remaaining attempts on LCD and Serial port Serial.printf("Attempts left=%d\n", passwordAttempts); delay(delayOf1Second); } // FUNCTION : displayBlocked // DESCRIPTION : // This function prints "System Blocked" on the LCD Screen and Serial port.In this function a forever loop is added to mimic the // bloked system. // PARAMETERS : void // RETURNS : void void displayBlocked() { lcd.clear(); lcd.setCursor( firstColumnOfLCD , firstRowOfLCD ); lcd.printf(" System Blocked"); Serial.printf(" System Blocked\n"); while(1) // forever loop to mimic system is blocked ; } // FUNCTION : disableISR // DESCRIPTION : // This interrupt service routine will change the state of state machine DISABLE BURLAR ALARM when push button connected to pin 13 (disable pin) is pressed. // PARAMETERS : void // RETURNS : void void disableISR(void) { burglarAlarmState = DISABLEBURGLARALARM ; //changing the state to disable burglar alarm } // FUNCTION : displayThumbsUP // DESCRIPTION : // This function prints the bit mapped "thumbs up" symbol on the LCD Screen. // PARAMETERS : void // RETURNS : void void displayThumbsUP() { byte thumb1[ bitMapByteArraySize ] = // bit mapped byte array for thumbs up for 01 position { B00100, B00011, B00100, B00011, B00100, B00011, B00010, B00001 }; byte thumb2[ bitMapByteArraySize ] = // bit mapped byte array for thumbs up for 00 position { B00000, B00000, B00000, B00000, B00000, B00000, B00000, B00011 }; byte thumb3[bitMapByteArraySize] = // bit mapped byte array for thumbs up for 11 position { B00000, B00000, B00000, B00000, B00000, B00000, B00001, B11110 }; byte thumb4[ bitMapByteArraySize ] = // bit mapped byte array for thumbs up for 10 position { B00000, B01100, B10010, B10010, B10001, B01000, B11110, B00000 }; byte thumb5[ bitMapByteArraySize ] = // bit mapped byte array for thumbs up for 21 position { B00010, B00010, B00010, B00010, B00010, B01110, B10000, B00000 }; byte thumb6[ bitMapByteArraySize ] = // bit mapped byte array for thumbs up for 20 position { B00000, B00000, B00000, B00000, B00000, B10000, B01000, B00110 }; lcd.createChar(5, thumb1); // create lcd bitmapped character lcd.createChar(6, thumb2); // create lcd bitmapped character lcd.createChar(7, thumb3); // create lcd bitmapped character lcd.createChar(8, thumb4); // create lcd bitmapped character lcd.createChar(9, thumb5); // create lcd bitmapped character lcd.createChar(10, thumb6); // create lcd bitmapped character lcd.setCursor(firstColumnOfLCD, secondRowOfLCD); lcd.write(5); // display the bitmapped character lcd.setCursor(firstColumnOfLCD, firstRowOfLCD); lcd.write(6); // display the bitmapped character lcd.setCursor(secondColumnOfLCD , secondRowOfLCD); lcd.write(7); // display the bitmapped character lcd.setCursor(secondColumnOfLCD, firstRowOfLCD); lcd.write(8); // display the bitmapped character lcd.setCursor(thirdColumnOfLCD, secondRowOfLCD); lcd.write(9); // display the bitmapped character lcd.setCursor(thirdColumnOfLCD, firstRowOfLCD); lcd.write(10); // display the bitmapped character } // FUNCTION : displayIntruder // DESCRIPTION : // This function prints the bit mapped "running man" symbol on the LCD Screen. // PARAMETERS : void // RETURNS : void void displayIntruder() { byte intruder00[ bitMapByteArraySize ] = // bit mapped byte array for Running man symbol for 00 position { B00000, B00011, B00011, B00001, B00111, B01111, B10011, B00011 }; byte intruder01[ bitMapByteArraySize ] = // bit mapped byte array for Running man symbol for 01 position { B00000, B11000, B11000, B10000, B11100, B11110, B11001, B11000 }; byte intruder10[ bitMapByteArraySize ] = // bit mapped byte array for Running man symbol for 10 position { B00011, B00011, B00011, B00011, B00110, B11100, B11000 }; byte intruder11[ bitMapByteArraySize ] = // bit mapped byte array for Running man symbol for 11 position { B11000, B11000, B11000, B11000, B01100, B00111, B00011 }; lcd.createChar(11, intruder00); // create lcd bitmapped character lcd.createChar(12, intruder01); // create lcd bitmapped character lcd.createChar(13, intruder10); // create lcd bitmapped character lcd.createChar(14, intruder11); // create lcd bitmapped character lcd.setCursor( firstColumnOfLCD , firstRowOfLCD); lcd.write(11); // display the bitmapped character lcd.write(12); // display the bitmapped character lcd.setCursor(firstColumnOfLCD, secondRowOfLCD); lcd.write(13); // display the bitmapped character lcd.write(14); // display the bitmapped character } // FUNCTION : displayFaultSymbol // DESCRIPTION : // This function prints the bit mapped symbol of exclamation point in the square on the LCD Screen. // PARAMETERS : void // RETURNS : void void displayFaultSymbol() { byte faultSymbol_00[ bitMapByteArraySize ] = // bit mapped byte array for fault symbol for 00 position { B01111, B01000, B01000, B01000, B01000, B01000, B01000, }; byte faultSymbol_10[ bitMapByteArraySize ] = // bit mapped byte array for fault symbol for 01 position { B01000, B01000, B01000, B01000, B01000, B01000, B01111, }; byte faultSymbol_01[ bitMapByteArraySize ] = // bit mapped byte array for fault symbol for 10 position { B11111, B00001, B10001, B10001, B10001, B10001, B10001, }; byte faultSymbol_11[ bitMapByteArraySize ] = // bit mapped byte array for Running man symbol for 11 position { B00001, B00001, B10001, B00001, B00001, B00001, B11111, }; lcd.createChar(1, faultSymbol_00); // create lcd bitmapped character lcd.createChar(2, faultSymbol_01); // create lcd bitmapped character lcd.createChar(3, faultSymbol_10); // create lcd bitmapped character lcd.createChar(4, faultSymbol_11); // create lcd bitmapped character lcd.setCursor( firstColumnOfLCD , firstRowOfLCD); lcd.write(1); // display the bitmapped character lcd.write(2); // display the bitmapped character lcd.setCursor(firstColumnOfLCD, secondRowOfLCD); lcd.write(3); // display the bitmapped character lcd.write(4); // display the bitmapped character }
true
a5b4e654d840317eef28907ae1306d229d02e9b0
C++
davidho95/monopoleSphaleronSolver
/include/Su2Tools.hpp
UTF-8
3,498
2.96875
3
[]
no_license
#ifndef SU2TOOLS_HPP #define SU2TOOLS_HPP #include "Matrix.hpp" namespace monsta { const monsta::Matrix identity({1, 0, 0, 1}); const monsta::Matrix pauli1({0, 1, 1, 0}); const monsta::Matrix pauli2({0, -1i, 1i, 0}); const monsta::Matrix pauli3({1, 0, 0, -1}); const double pi = 4*atan(1); int sign(double x) { return (x > 0) - (x < 0); } bool su2Check(monsta::Matrix mat) { double zeroTol = 1e-5; std::complex<double> determinant = mat(0,0)*mat(1,1) - mat(0,1)*mat(1,0); if (abs(abs(determinant) - 1.0) > zeroTol) { cout << abs(determinant) - 1.0 << endl; return false; } monsta::Matrix hcProduct = mat*monsta::conjugateTranspose(mat); monsta::Matrix checkMatrix = hcProduct - identity; for (int ii = 0; ii < pow(checkMatrix.getSize(),2); ii++) { if (abs(checkMatrix(ii)) > zeroTol) { return false; } } return true; } bool su2LieAlgCheck(monsta::Matrix mat) { double zeroTol = 1e-15; std::complex<double> trace = monsta::trace(mat); if (abs(trace) > zeroTol) { return false; } monsta::Matrix checkMatrix = monsta::conjugateTranspose(mat) - mat; for (int ii = 0; ii < pow(checkMatrix.getSize(),2); ii++) { if (abs(checkMatrix(ii)) > zeroTol) { return false; } } return true; } void makeTraceless(monsta::Matrix &mat) { std::complex<double> tr = trace(mat); mat(0,0) = mat(0,0) - 0.5*tr; mat(1,1) = mat(1,1) - 0.5*tr; } monsta::Matrix vecToSu2LieAlg(std::vector<double> vec) { return vec[0]*pauli1 + vec[1]*pauli2+vec[2]*pauli3; } monsta::Matrix vecToSu2(std::vector<double> vec) { double zeroTol = 1e-15; double vecNorm = sqrt(pow(vec[0],2) + pow(vec[1],2) + pow(vec[2],2)); if (vecNorm < zeroTol) { return identity; } return cos(vecNorm)*identity + 1i*sin(vecNorm)/vecNorm * vecToSu2LieAlg(vec); } std::vector<double> su2LieAlgToVec(monsta::Matrix mat) { // if (!su2LieAlgCheck(mat)) // { // mat.print(); // throw std::invalid_argument("Matrix is not an element of the SU(2) Lie algebra"); // } std::vector<double> outputVec(3); outputVec[0] = 0.5*real(trace(mat*pauli1)); outputVec[1] = 0.5*real(trace(mat*pauli2)); outputVec[2] = 0.5*real(trace(mat*pauli3)); return outputVec; } std::vector<double> su2ToVec(monsta::Matrix mat) { // if (!su2Check(mat)) // { // throw std::invalid_argument("Matrix is not an element of SU(2)"); // } std::vector<double> outputVec(3); double zeroTol = 1e-15; double cosVecNorm = 0.5*real(trace(mat)); // cout << cosVecNorm << endl; if (abs(cosVecNorm - 1) < zeroTol) { return outputVec; } if (abs(cosVecNorm + 1) < zeroTol) { outputVec[2] += 4*atan(1); return outputVec; } double vecNorm = acos(cosVecNorm); outputVec[0] = 0.5 * vecNorm/sin(vecNorm) * imag(trace(mat*pauli1)); outputVec[1] = 0.5 * vecNorm/sin(vecNorm) * imag(trace(mat*pauli2)); outputVec[2] = 0.5 * vecNorm/sin(vecNorm) * imag(trace(mat*pauli3)); return outputVec; } int epsilonTensor(int ii, int jj, int kk) { if ((ii == jj) || (jj == kk) || (kk == ii)) { return 0; } if ((ii + 1) % 3 == jj && (jj + 1) % 3 == kk) { return 1; } else { return -1; } } Matrix commutator(Matrix mat1, Matrix mat2) { return mat1*mat2 - mat2*mat1; } } #endif
true
6129a9cb409934d3f13dcbb15010c9fa5a569629
C++
doerodney/uw-cpp-cert
/intro/assgt05/CharQueue1.h
UTF-8
533
2.84375
3
[]
no_license
#ifndef INC_CHARQUEUE1_H #define INC_CHARQUEUE1_H #include <cstddef> #include <memory> class CharQueue1 { public: CharQueue1(); CharQueue1(std::size_t size); CharQueue1(const CharQueue1& src); // copy constructor void enqueue(char ch); char dequeue(); bool isEmpty() const; void swap(CharQueue1& src); std::size_t capacity() const; CharQueue1& operator=(CharQueue1 src); private: void grow(); std::unique_ptr<char[]> myBuf; std::size_t myCap; std::size_t myLen; }; #endif
true
0c1b284d79f1b71e491a6999ab05b4620f7b259e
C++
zecookiez/LeetCoder
/Medium/0008_stringToIntegerAtoi.cpp
UTF-8
1,890
3.640625
4
[]
no_license
/* * https://leetcode.com/problems/string-to-integer-atoi/ * * Implement atoi which converts a string to an integer. * * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. * * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. * * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. * * If no valid conversion could be performed, a zero value is returned. * * Time complexity: O(N) * Memory complexity: O(1) */ class Solution { public: int myAtoi(string str) { bool found = false; // If we've already found a digit, +, or - sign long r = 0, n = 1; for(char&c : str){ if(isdigit(c)){ r = r * 10 + (c - 48); found = true; // Too large if(r > INT_MAX) return n == -1 ? INT_MIN : INT_MAX; } else if(found){ // Invalid string break; } else if(c == 43 || c == 45){ // + or - found = true; if(c == 45) // - case n = -1; } else if(c != 32){ // Skip whitespace break; } } return r * n; } };
true
9609a67fdcb76d82dcfe9929cb1e4b6d75c57eee
C++
jkolek/hashmap
/test3.cpp
UTF-8
2,259
3.546875
4
[]
no_license
#include <mutex> #include <thread> #include <iostream> #include <cassert> #include "hashmap.h" constexpr unsigned MAX_TABLE_SIZE = 100; static constexpr unsigned HASH_CONST = 17; /* A prime number */ class IntHash { public: unsigned operator()(int key) { return (key * key + HASH_CONST) % MAX_TABLE_SIZE; } }; class StringHash { public: unsigned operator()(std::string key) { unsigned res = 0; std::string::iterator it = key.begin(); while (it != key.end()) { res += (unsigned) *it + HASH_CONST; ++it; } return res; } }; std::mutex mtx; HashMap<unsigned, std::string, IntHash> imap(MAX_TABLE_SIZE); int main() { const unsigned n1 = 10; const unsigned n2 = 20; const unsigned n3 = 33; const unsigned n4 = 234; const unsigned n5 = 243; const unsigned n6 = 254; for (unsigned i = 0; i < 10; i++) { imap.insert(n1 + i, "pineapple"); imap.insert(n2 + i, "mango"); imap.insert(n3 + i, "apple"); imap.insert(n4 + i, "orange"); imap.insert(n5 + i, "banana"); imap.insert(n6 + i, "kiwi"); } // Test iterator HashMap<unsigned, std::string, IntHash>::Iterator imIter = imap.begin(); while (imIter != imap.end()) { std::cout << (*imIter)->value << std::endl; ++imIter; } std::cout << "===================================" << std::endl; imIter = imap.begin(); while (imIter != imap.end()) { HashMap<unsigned, std::string, IntHash>::Element *e = (*imIter); std::cout << "key == " << e->key << std::endl; std::cout << "value == " << e->value << std::endl; imIter++; } // Test move constructor HashMap<unsigned, std::string, IntHash> imap2 = std::move(imap); std::cout << "imap.getSize() == " << imap.getSize() << std::endl; std::cout << "imap2.getSize() == " << imap2.getSize() << std::endl; // Test move assignment operator HashMap<unsigned, std::string, IntHash> imap3; imap3 = std::move(imap2); std::cout << "imap2.getSize() == " << imap2.getSize() << std::endl; std::cout << "imap3.getSize() == " << imap3.getSize() << std::endl; }
true
06d8951921a50a397458e43b0df159a6295b3e28
C++
soar1234/LeetCodeAlgorithms
/LeetCode/27-Remove Element.cpp
UTF-8
706
3.375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int removeElement(int* nums, int numsSize, int val) { int i=0,j=0; int flag=numsSize; int temp; for(i=0;i<numsSize;i++) { for(j=i+1;j<numsSize;j++) { if(nums[i]==val) { temp=nums[i]; nums[i]=nums[j]; nums[j]=temp; } } } for(i=0;i<numsSize;i++) { if(nums[i]==val) { flag--; } } return flag; } int main() { int nums[4]={3,2,2,3}; int i; for(i=0;i<4;i++) { printf("%d ",nums[i]); } printf ("\n%d\n",removeElement(nums,4,3)); for(i=0;i<4;i++) { printf("%d ",nums[i]); } return 0; }
true
c1ee6d4f4f22f213d1f4ed7a29b4eef79c0188d7
C++
MarksZero/estructura-de-datos-y-algoritmos
/clase-2-estr-control-y-arreglos/clase2-ejercicio5.cpp
UTF-8
411
3.5
4
[]
no_license
#include <stdio.h> int main(){ int numero; printf("Ingrese un número para buscar sus divisores.\n"); scanf("%d", &numero); printf("Los divisores de %d son: 1", numero); if(numero > 1){ for(int i = 2 ; i < numero ; i++){ if(numero%i == 0){ printf(", %d", i); } } printf(" y %d\n", numero); } return 0; }
true
717fafd20cf87949b75a5f97385a73138c12855e
C++
dsnow75/ds2454010
/Hmwk/HW 1/Savitch_8thEd_Ch1_prob8/main.cpp
UTF-8
715
3.484375
3
[]
no_license
/* * File: main.cpp * Author: David Snow * * Created on June 25, 2014, 1:18 PM */ //system libraries #include <iostream> using namespace std; //User Libraries //Global Constants //Function Prototypes //Execution Begins Here int main(int argc, char** argv) { //Variables int quar, dime, nick; //quar are the quarters,nick are the nickels int sum; // sum is the monetary value for the total amount in cents cout << "Enter a number of quarters:"; cin >> quar; cout << "Enter the number of dimes:"; cin >> dime; cout << "Enter the number of nickels"; cin >> nick; sum = quar * 25 + dime * 10 + nick * 5; cout << "You have " << sum << " total monetary value in cents"; return 0; }
true
f6aaca6d4ba477acc066c547c019bc95df9e1fe4
C++
thomasloockx/Master-Thesis-Ray-Tracer
/character_animation/cluster.cpp
UTF-8
668
2.578125
3
[]
no_license
#include <cluster.h> rt::Cluster::Cluster(int boneId) : boneId_(boneId) { } void rt::Cluster::addTriangle(const Triangle& triangle) { triangles_.push_back(triangle); boundingBox_ += triangle.boundingBox(); } void rt::Cluster::addFuzzyBox(const BoundingBox& fuzzyBox) { fuzzyBoxes_.push_back(fuzzyBox); fuzzyBox_ += fuzzyBox; } void rt::Cluster::clearTriangles() { triangles_.clear(); boundingBox_ = BoundingBox(); } std::ostream& rt::operator<<(std::ostream& o, const Cluster& c) { o << "Cluster::("; o << "boneId = " << c.boneId() << ", "; o << "#triangles = " << c.nbTriangles() << ", "; o << "#fuzzyBoxes = " << c.nbFuzzyBoxes() << ")"; return o; }
true
c7f143b34f9ee2f2b2749e0044ae820b17982dba
C++
xwang345/OOP345
/ms4/OrderManager.h
UTF-8
577
2.625
3
[]
no_license
///////////////////////////////////////////// // OOP345 milestone 3: // Name: Sanghun Kim // Date: 20/11/2106 // email: ksanghun@myseneca.ca ///////////////////////////////////////////// #pragma once // Manager Milestone - OrderManager Interface // OrderManager.h // Chris Szalwinski // v1.0 - 14/11/2015 // v2.0 - 23/02/2016 #include <iostream> #include <vector> class ItemManager; class CustomerOrder; class OrderManager : public std::vector<CustomerOrder> { public: CustomerOrder&& extract(); void validate(const ItemManager& itemMng, std::ostream& os); void display(std::ostream& os) const; };
true
c4ac5850be878ddccb3aec912cf3373582e46e49
C++
EdwinJosue16/parallel-KMeans-OMP
/Main.cpp
UTF-8
4,307
2.578125
3
[]
no_license
#pragma warning( disable : 4290 ) #pragma warning( disable : 4290 ) #pragma warning( disable : 5040 ) #include "KMeansP.h" #include "Elemento.h" #include <vector> #include <sstream> #include <fstream> #include <string> #include <exception> #include <iostream> #include <omp.h> using namespace std; // /Zc:twoPhase- //COMPILAR DESDE LINEA DE COMANDOS: g++ -g -Wall -fopenmp -o km *.cpp double stod_wrapper(string v) throw (invalid_argument, out_of_range) { return std::stod(v); } template < typename T, class F > vector< vector< T > > carga_valida_datos(ifstream& archivo, F t) throw (invalid_argument, out_of_range); vector< vector< double > > recuperarArch(); void recuperarNumeros(double & l, double & epsilon); int main(int argc, const char * argv[]) { int cp = omp_get_num_procs(); int hilos = cp*3; double epsilon = 0.0; double l = 0.0; vector < vector < double > > datos=recuperarArch(); recuperarNumeros(l,epsilon); int m = datos.size(); int n= datos[0].size(); //parametros orden: n,m,k,l,datos,hilos int k = 100; KMeansP algoritmo(n,m,k,l,datos,hilos,epsilon); cout << "***INFO DEL PROGRAMA***" << endl; algoritmo.verInfo(); double inicioG= omp_get_wtime(); algoritmo.initC(); //inicializa conjunto de candidatos a centroides algoritmo.setPesosAElementosDeC(); // asigna el peso a tales candidatos algoritmo.generarCentroidesDeC(); // genera centroides iniciales para hacer kmeans ++ sobre el conjunto de candidatos algoritmo.KMeansSerial(); //ejecuta kmeans++ sobre el conjunto de candidatos algoritmo.ordenarGruposXpeso(); // ordena por peso los elementos de cada grupo creado en el paso anterior algoritmo.elegirCentroidesKMP(); // elige los centroides de KMEANS || (elementos + pesados) de cada grupo anterior algoritmo.agrupar(); // EJECUTA KMEANS || sobre TODO el conjunto de datos ingresados double finG = omp_get_wtime(); cout << "Se ha ejecutado KMeans || las iteraciones de KMeans || para convergencia son: " << algoritmo.getIterKM() << endl; cout << "Tiempo pared: " << finG - inicioG << " segundos " << endl; cout << "Tiempo pared: " << (finG - inicioG)/60 << " minutos " << endl; algoritmo.setDuracion(finG - inicioG); cout << "Generando archivo..." << endl; algoritmo.generarArchivo(); cout << "Archivo generado" << endl; int salir; cout << endl << endl << "digite cualquier tecla + enter para salir... "; cin>>salir; return 0; } template < typename T, class F > vector< vector< T > > carga_valida_datos(ifstream& archivo, F t) throw (invalid_argument, out_of_range) { vector< vector< T > > valores; vector< T > linea_valores; string linea; while (getline(archivo, linea)) { linea_valores.clear(); stringstream ss(linea); string numero_S; T numero_T; while (getline(ss, numero_S, ',')) { try { numero_T = t(numero_S); } catch (exception e) { throw e; } linea_valores.push_back(numero_T); } valores.push_back(linea_valores); } return valores; } void recuperarNumeros(double & l, double & epsilon) { while (l <= 0 || epsilon <= 0) { cout << "digite el valor de epsilon (se recomienda 100) "; cin >> epsilon; cout << endl << "digite el valor de l (se recomienda 0.3) "; cin >> l; cout << endl; } } vector< vector< double > > recuperarArch(){ cout << "El programa por default (como dicen las instrucciones) usa k=100 si desea cambiar <k> modifique en linea 34 de Main.cpp" << endl; bool capturado=true; string file_name=""; cout << "digite el nombre del archivo (ejemplo: <vectores_desordenados.csv>) :"; cin >> file_name; cout << endl; ifstream d(file_name, ios::in); if (!d){ cout << "no encuentra el archivo de datos...Vuelva a intentar" << endl; capturado=false; } while(!capturado){ cout << "digite el nombre del archivo (ejemplo: <vectores_desordenados.csv>) :"; cin >> file_name; cout << endl; ifstream d(file_name); if (!d){ cout << "no encuentra el archivo de datos...Vuelva a intentar" << endl; capturado=false; } } vector< vector< double > > vd; try { vd = carga_valida_datos< double >(d, stod_wrapper); } catch (exception e) { cout << "valor invalido o fuera de limite" << endl; } return vd; }
true
66b70d895c950ac6ea4d02bf639758460e7dce77
C++
ThreeMonkey/LeetCode
/First Missing Positive.cpp
GB18030
1,237
3.84375
4
[]
no_license
/* Given an unsorted integer array, find the first missing positive integer. For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2. Your algorithm should run in O(n) time and uses constant space. A[i]ϣܱڵiλϣӵҵA[i] != iʱǾҵҪ. DZʱǷA[i] != iôǾswap(A[A[i]], A[i])A[i]ȷλϡ ڽ֮A[i]ǼֱûΪֹûʾǰ򳬹鳤ȣA[A[i]] 飬ѰҵһϴҪԪأ±ꡣ Ҫ飬ӶΪO(n) */ #include <iostream> using namespace std; class Solution { public: int firstMissingPositive(int A[], int n) { if (A == NULL || n == 0) return 1; for (int i = 0; i < n; i++) { if (A[i] == i) { continue; } else { if (A[i] >= 0 && A[i] < n && A[i] != A[A[i]]) { swap(A[i], A[A[i]]); i--; } } } for (int i = 1; i < n; i++) { if (A[i] != i) return i; } return A[0] == n ? n + 1 : n; } };
true
5e8c7bff9fed26a5076759abde3c377b2263685d
C++
FTurci/montecarlos
/StandardMC/cell.h
UTF-8
299
2.640625
3
[]
no_license
#ifndef __CELL_H__ #define __CELL_H__ #include "particle.h" class Particle; class Cell { public: Particle *firstParticle; Cell *neighbours[26]; // neighbouring cells Cell(void){ firstParticle = 0; for (int i=0; i<26; i++){ neighbours[i] = 0; } } }; #endif
true
fd4f5f5addd6bafa85717c66dac020b163f59cc9
C++
adamjorr/meep
/plpdata.cc
UTF-8
1,901
2.671875
3
[ "MIT" ]
permissive
#include "plpdata.h" #include <iostream> #include <vector> Pileupdata::Pileupdata(std::string filename, std::string refname, std::string region) : plp(filename, refname, region), data() { populate_data(); } Pileupdata::Pileupdata(std::string filename, std::string refname) : plp(filename, refname), data() { populate_data(); } Pileupdata::Pileupdata(Pileup p) : plp(p), data() { populate_data(); } Pileupdata::Pileupdata(std::vector<char> x, char ref, std::vector<char> quals) : plp(), data(){ populate_data(x,ref,quals); } Pileupdata::Pileupdata(std::vector<char> x) : Pileupdata(x, x[0], x) { } //I'll need to think of something better; this will break if the pileup isn't completely contiguous (ie multiple ranges) void Pileupdata::populate_data(){ std::map<std::string,int> chrs = plp.get_name_map(); int val; while((val = plp.next()) != 0){ if (val == 1){ int tid = plp.get_tid(); char ref_char = plp.ref_char; data.resize(tid + 1); data[tid].push_back(std::make_tuple(plp.alleles,plp.counts,plp.qual,ref_char,plp.readgroups)); ++ref_counts[ref_char]; } } } void Pileupdata::populate_data(std::vector<char> x, char ref, std::vector<char> quals){ std::map<char,int> counts = {{'A',0},{'T',0},{'G',0},{'C',0}}; std::vector<std::string> rgs(x.size(),"RG0"); for (char i : x){ ++counts[i]; } data.resize(1); std::vector<pileuptuple_t> v(1,std::make_tuple(x,counts,quals,ref,rgs)); data.push_back(v); ++ref_counts[ref]; } std::vector<char> Pileupdata::bases_at(int tid, int pos){ return std::get<0>(data[tid][pos]); } int Pileupdata::depth_at(int tid, int pos){ return Pileupdata::bases_at(tid,pos).size(); } int Pileupdata::num_base(int tid, int pos, char base){ return std::get<1>(data[tid][pos])[base]; } std::map<std::string,int> Pileupdata::get_name_map(){ return plp.get_name_map(); } pileupdata_t Pileupdata::get_data(){ return data; }
true
742eaf8a633221c8a29f0014a3b59f9ea6bde285
C++
mathiasVoelcker/cpp-course
/charTut.cpp
UTF-8
297
3.140625
3
[]
no_license
#include <iostream> using namespace std; int main() { char text[] = "hello"; cout << text << endl; char *pChar = text; cout << *pChar << endl; while (*pChar != 0) { cout << pChar << endl; cout << *pChar << endl; pChar++; } return 0; }
true
383fbe219271fa77b5af93c64d16c7b3b958e007
C++
abhishekabhay910/CPP
/lab2.cpp
UTF-8
687
3.390625
3
[]
no_license
#include<iostream> using namespace std; class arr{ char name[10],dept[10],post[10],add[20]; int empid; public: void insert(); void display(); };arr a[3]; void arr::insert() { cout<<"\nempid-";cin>>empid; cout<<"\nname-";cin>>name; cout<<"\ndepartment-";cin>>dept; cout<<"\npost-";cin>>post; cout<<"\naddress-";cin>>add; } void arr::display() { cout<<"\nempid:"<<empid; cout<<"\nname:"<<name; cout<<"\ndepartment:"<<dept; cout<<"\npost:"<<post; cout<<"\naddress:"<<add; } int main() { int n,i; cout<<"\nenter no of employee"; cin>>n; cout<<"\nenter detail"; for(i=0;i<n;i++) a[i].insert(); cout<<"\nentered detail"; for(i=0;i<n;i++) a[i].display(); return 0; }
true
20343b8c3cc9eb493e1033f03edf1ad7325b18c9
C++
Shivanshu10/Coding-Practice
/General Ques/Ques47/dupsorted.cpp
UTF-8
512
3.265625
3
[]
no_license
#include <iostream> using namespace std; void dupsorted(int a[], int size) { int count=0; for (int i=0; i<size; i++) { if (a[i] == a[i+1]) { if (count == 0) { cout << a[i] << " "; } count++; } else if (count != 0) { cout << (count+1) << endl; count=0; } } } int main() { int a[] = {1, 2, 2, 2, 3, 3, 4}; dupsorted(a, 6); return (0); }
true
001f3719c735b03cab71e4cbdcd8c1a4ae4c2344
C++
ayan2809/DSA
/Submission 3/q1.cpp
UTF-8
375
3.296875
3
[]
no_license
#include<stdio.h> int sum(int x,int y,int s) { //printf("%d\n",y); if (y==x) return s; else y=y+1; return s+200+sum(x,y,s); } int main() { int l,w; printf("Enter the length of the room :"); scanf("%d",&l); printf("\nEnter the width of the room :"); scanf("%d",&w); int p=l*w; printf("The total cost for carpeting the room is %d\n",sum(p,0,0)); return 0; }
true
d6d220782c80b67062e9d776d24432db5cf6256e
C++
maxwellcopper/EDP-IntermediateSession-TrainingDelameta
/STM32/challange_ultrasonik_n_flame_bang_yuda/challange_ultrasonik_n_flame_bang_yuda.ino
UTF-8
2,013
2.546875
3
[]
no_license
#include <NewPing.h> // inisialisasi int pinLedR = PB10; int pinLedY = PB1; int pinLedG = PB0; int pinPIR = PB3; int pinFlame = PB11; int pinTrigger = PA5; int pinEcho = PA7; int prevFlame = 0; int prevPIR = 0; int toggle = true; // ultrasonik int MAX_DISTANCE = 500; NewPing us(pinTrigger, pinEcho); int checkRising(int input, int& prev){ int isRising = 0; if(prev == 0 && input == 1) { isRising = 1; } prev = input; return isRising; } int writeLED(int r, int y, int g) { digitalWrite(pinLedR, r); digitalWrite(pinLedY, y); digitalWrite(pinLedG, g); } void blink(int dduration){ writeLED(1,1,1); delay(dduration); writeLED(0,0,0); delay(dduration); } void flipflop(int dduration) { writeLED(1,0,0); delay(dduration); writeLED(0,1,0); delay(dduration); writeLED(0,0,1); delay(dduration); writeLED(0,1,0); delay(dduration); } // setup void setup() { Serial.begin(9600); pinMode(pinLedR, OUTPUT); pinMode(pinLedY, OUTPUT); pinMode(pinLedG, OUTPUT); pinMode(pinFlame, INPUT); pinMode(pinPIR, INPUT); } void loop(){ // baca input int readFlame = !digitalRead(pinFlame); int readPIR = !digitalRead(pinPIR); int risingFlame = checkRising(readFlame, prevFlame); int risingPIR = checkRising(readPIR, prevPIR); int readUS = us.ping_cm(); // print Serial.print("readFlame=" + String(readFlame)); Serial.print(", risingFlame=" + String(risingFlame)); Serial.print(", readPIR=" + String(readPIR)); Serial.print(", risingPIR=" + String(risingPIR)); Serial.print(", readUS=" + String(readUS)); Serial.print(", toggle=" + String(toggle)); Serial.println(); // logic if(risingFlame || risingPIR) toggle = !toggle; if(toggle) { if(readUS < 10 && readUS > 0) { blink(30); } else if (readUS < 30 && readUS > 0) { blink(350); } else { flipflop(100); } } else { writeLED(0,0,0); } }
true
0264273f063d963bf5a4956e3abeff40a20fd012
C++
xinnjie/extract-subtitle
/PicClean.cpp
UTF-8
4,213
2.65625
3
[ "MIT" ]
permissive
// // Created by capitalg on 4/11/18. // #include <opencv2/imgproc.hpp> #include "PicClean.h" #include <iostream> using namespace cv; cv::Mat PicClean::keep_white(const cv::Mat &colored_src) { Mat gray; cv::cvtColor(colored_src, gray, cv::COLOR_RGB2GRAY); Mat thres; threshold(gray, thres, 215,255,cv::THRESH_BINARY); Mat labeled, stats, _centroids;//_centroids unused int n = cv::connectedComponentsWithStats(thres, labeled,stats, _centroids, 8); // 如果连通体过大、过小,删除该连通体 clear_large_small_conn(labeled, stats, 5, 400); labeled.forEach<int>([](int &pixel, const int *position) { pixel = pixel == 0 ? 0 : 65535; }); Mat mask; labeled.convertTo(mask, CV_8UC1); unsigned char data[3][3] = { {0,1,0}, {1,1,1}, {0,1,0} }; Mat kernel(3,3, CV_8UC1, &data); cv::dilate(mask, mask, kernel); Mat clean; gray.copyTo(clean, mask); return clean; } void PicClean::clear_large_small_conn(cv::Mat &labeled, const cv::Mat &stats, int min, int max) { for (int label = 0; label < stats.rows; ++label) { int area_size = stats.at<int>(label, cv::CC_STAT_AREA); if (area_size < min || area_size > max ) { int top = stats.at<int>(label, CC_STAT_TOP), left = stats.at<int>(label, CC_STAT_LEFT), width = stats.at<int>(label, CC_STAT_WIDTH), height = stats.at<int>(label, CC_STAT_HEIGHT); Mat remove_area = Mat(labeled,cv::Rect(left, top, width, height)); for (int i = 0; i < remove_area.rows ; ++i) { int *rowi = remove_area.ptr<int>(i); for (int j = 0; j < remove_area.cols; ++j) { rowi[j] = rowi[j] == label ? 0 : rowi[j]; } } } } } //#include <iostream> std::pair<int, int> PicClean::locate_subtitle(const cv::Mat &gray_src) { Mat hist; cv::reduce(gray_src, hist, 0, CV_REDUCE_SUM, CV_32SC1); int x1 = 0, x2 = 0; // 连续二十列总体亮度都很低表示没有字 // 字幕开头大约出现在 1/4 处 for (int i = gray_src.cols / 4; i < gray_src.cols ; ++i) { int count = 0; while (hist.at<int>(i) < 500 && i < gray_src.cols) { ++i; count++; } if (count > 20) { x2 = i - count; break; } } for (int i = gray_src.cols / 4; i > 0 ; --i) { int count = 0; while (hist.at<int>(i) < 500 && i > 0) { --i; count++; } if (count > 20) { x1 = i + count; break; } } // std::cout << x1 << " " << x2 << std::endl; return std::make_pair(x1, x2); } cv::Mat PicClean::keep_common(std::vector<cv::Mat> srcs) { assert(!srcs.empty()); Mat img = srcs[0]; for (int i = 0; i < srcs.size(); ++i) { Mat diff; cv::absdiff(img, srcs[i], diff); diff = diff > 200; // std::cout << diff.size << std::endl; // std::cout << img.size << std::endl; img = img - diff.mul(img); } return img; } bool PicClean::same_subtitle(const cv::Mat &src1, const cv::Mat &src2, int thres, int x1, int x2) { Rect region(x1, 0, x2-x1, src1.rows); const Mat area1 = Mat(src1, region), area2 = Mat(src2, region); Mat diff; cv::absdiff(src1, src2, diff); // std::cout << diff.size << std::endl; // Mat sum; // reduce(diff, sum, 0, CV_REDUCE_SUM, CV_32SC1); // std::cout << sum << std::endl; // std::cout << sum.size << std::endl; // // reduce(sum, sum, 1, CV_REDUCE_SUM); // return sum.at<int>(0) < thres; return cv::sum(diff).val[0] < thres; } bool PicClean::is_blank(const cv::Mat src) { auto p = locate_subtitle(src); int x1 = p.first, x2 = p.second; if (x1 == 0 && x2 == 0) { return true; } return sum_mat(src) < 1000; } int PicClean::sum_mat(const cv::Mat &src) { Mat sum; reduce(src, sum, 1, CV_REDUCE_SUM, CV_32SC1); reduce(sum, sum, 0, CV_REDUCE_SUM); return sum.at<int>(0); }
true
73765b7acd06cca6af7949c48a6e324227539067
C++
birneysky/data_structure_play_ground
/c++/solutions/src/Solution.hpp
UTF-8
21,544
3.875
4
[]
no_license
#ifndef SOLUTION_H #define SOLUTION_H #include <vector> #include <sstream> #include <string> #include <iostream> #include <cassert> class Solution{ private: /** 对一个数组的[left,right]区间内的元素做快速排序的 partitionn 操作 @param vector<int>nums 数组 @param left 左索引值 @param right 右索引值 @return 返回标定点的索引 */ int partition(std::vector<int>& nums, int left, int right) { int val = nums[left]; int j = left; for (int i = left + 1; i <= right; i++) { if (nums[i] < val) { j++; std::swap(nums[i],nums[j]); } } std::swap(nums[left],nums[j]); return j; } int findKthLargest(std::vector<int>& nums, int left, int right, int k) { int p = partition(nums, left, right); int kth = (int)(nums.size() - k); if (p == kth) { return p; } else if (p < kth) { return findKthLargest(nums, p+1, right,k); } else { return findKthLargest(nums, left, p-1,k); } } bool isALetterOrANumber(char ch) { return isLetter(ch) || isNumber(ch); } bool isLetter(char ch) { if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ) { return true; } return false; } bool isNumber(char ch) { return (ch >= '0' && ch <= '9'); } /** 判断两个字符是否相同 这里相同的定义是 'a' 'A' 是认为是相同的 所以如果 a 和 b 全部都是字母,那么要注意大小写字母不敏感的逻辑 @param a 字符a @param b 字符b @return 如果相同返回YES,否则返回NO */ bool isSampleLetter(char a, char b) { if (isLetter(a) && isLetter(b)) { return a == b || abs(a - b) == 32; } return a == b; } public: struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} friend std::ostream& operator<<(std::ostream& out, ListNode& head) { std::stringstream stream; ListNode* pNode = &head; while (pNode) { stream << pNode->val << "->"; if (!pNode->next) { stream << "nullptr"; } pNode = pNode->next; } out << stream.str(); return out; } }; public: /* 1 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 eg: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. */ std::vector<int> twoSum(std::vector<int>& nums, int target); /* 2 给出两个 非空 的链表用来表示两个非负的整数。 其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 eg: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. */ ListNode* addTwoNumbers(ListNode* l1, ListNode* l2); ListNode* addTwoNumbers2(ListNode* l1, ListNode* l2); /* 3 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 Given a string, find the length of the longest substring without repeating characters eg1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 eg2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 eg3: 输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 */ int lengthOfLongestSubstring(std::string s); /* 4 定两个大小为 m 和 n 的有序数组 nums1 和 nums2。 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。 你可以假设 nums1 和 nums2 不会同时为空 eg1: nums1 = [1, 3] nums2 = [2] 则中位数是 2.0 eg2: nums1 = [1, 2] nums2 = [3, 4] 则中位数是 (2 + 3)/2 = 2.5 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. */ double findMedianSortedArrays(std::vector<int>& nums1, std::vector<int>& nums2); /** 26 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 例如 给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。 nums = [0,0,1,1,1,2,2,3,3,4] =====> [0, 1, 2, 3, 4] return 5; @param nums 数组 @return 去重后数组的长度 */ int removeDuplicates(std::vector<int>& nums) { if (nums.size() == 0) { return 0; } int j = 1; /// 索引j 似的[0,j] 区间内都是不重复的元素 for( int i = j; i < nums.size(); i++) { /// 由于是有序数组,所以当前元素和前一个元素不同时,说明出现了新的元素 if (nums[i] != nums[i-1]) { nums[j] = nums[i]; j ++; } } return j; } /** 27 给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 nums = [3,2,2,3], val = 3 =====> [2,2] ,2 nums = [0,1,2,2,3,0,4,2], val = 2 =====> [0, 1, 3, 0, 4] ,5 @param nums 数组 @param val 待删除元素的值 @return 返回删除元素后数组的长度 */ int removeElement(std::vector<int>& nums, int val) { int k = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != val) { // if (i != k) { nums[k++] = nums[i]; // } } } return k; } /** 75 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 [2,0,2,1,1,0] ====> [0,0,1,1,2,2] @param nums 数组 */ void sortColors(std::vector<int>& nums) { int colorCounts[3] = {0}; for (int i = 0; i < nums.size(); i++) { colorCounts[nums[i]] ++; } for (int i = 0; i < colorCounts[0]; i++) { nums[i] = 0; } for (int i = 0; i < colorCounts[1]; i++) { nums[i + colorCounts[0]] = 1; } for (int i = 0; i < colorCounts[2]; i++) { nums[i + colorCounts[0] + colorCounts[1]] = 2; } } /** 80 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 [1,1,1,2,2,3], ===> length = 5 1, 1, 2, 2, 3 [0,0,1,1,1,1,2,3,3] ===> length = 7 0, 0, 1, 1, 2, 3, 3 @param nums 数组 @return 去重后数组的长度 */ int removeDuplicates_2(std::vector<int>& nums) { int k = 2; if (nums.size() <= k) { return (int)nums.size(); } /// 始终让[0,k)区间内,重复元素最多有2个 for (int i = k; i < nums.size(); i++) { if (i != k) { nums[k] = nums[i]; } /// 检查 k 之前前2个元素是否与 k相等,如果相等说明有nums[k],nums[k-1],nums[k-2]均相等,这时 k 的位置应该保持不变 /// 如果 nums[k] 与 nums[k-1],nums[k-2] 其中一个不相等,说明没有超过两个的重复元素,这时 k 应该向后移动一位 if (nums[k] != nums[k-1] || nums[k] != nums[k-2]) { k++; } } return k; } /** 88 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 =======> [1,2,2,3,5,6] @param nums1 数组1 @param m 数组1 长度 @param nums2 数组2 @param n 数组2 长度 */ void merge(std::vector<int>& nums1, int m, std::vector<int>& nums2, int n) { std::vector<int> aux(m,0); /// auxiliar for (int i = 0; i < m; i++) { aux[i] = nums1[i]; } int i = 0; /// 记录 nums1 当前考察元素的索引 int j = 0; /// 记录 nums2 当前考察元素的索引 for(int k = 0; k < m+n; k++) { if (i >= m) { nums1[k] = nums2[j++]; } else if (j >= n) { nums1[k] = aux[i++]; } else if (aux[i] < nums2[j]) { nums1[k] = aux[i++]; } else { nums1[k] = nums2[j++]; } } } /** 125 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 说明:本题中,我们将空字符串定义为有效的回文串。 示例 1: 输入: "A man, a plan, a canal: Panama" 输出: true 示例 2: 输入: "race a car" 输出: false @param s 字符串 @return 如果是 返回 true ,否则 返回 false */ bool isPalindrome(std::string s) { if (s.length() == 0) { return true; } int l = 0; int r = 0; for (int i = (int)s.length()-1; i >= 0; i--) { if (isALetterOrANumber(s.at(i))) { r = (int)i; break; } } while (l < r) { while(!isALetterOrANumber(s[l])) { l++; } while(!isALetterOrANumber(s[r])) { r --; } if (l >= r) { return true; } if (isSampleLetter(s[l],s[r])) { l++; r--; } else { return false; } } return true; } /** 167 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 返回的下标值(index1 和 index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 @param numbers 目标数组 @param target 目标值 @return 返回索引数组 */ std::vector<int> twoSum_167(std::vector<int>& numbers, int target) { std::vector<int> result; int left = 0; int right = (int)numbers.size() - 1; while (left < right) { if (numbers[left] + numbers[right] == target) { result.push_back(left); result.push_back(right); break; } else if (numbers[left] + numbers[right] < target) { left ++; } else { right --; } } return result; } /** 215 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 [3,2,1,5,6,4] 和 k = 2 ====> 5 [3,2,3,1,2,4,5,5,6] 和 k = 4 ====> 4 @param nums 数组1 @param k k @return 返回元素的值 */ int findKthLargest(std::vector<int>& nums, int k) { assert(k > 0 && k < nums.size()); int left = 0; int right = (int)(nums.size() -1); int kth = findKthLargest(nums,left,right,k); return nums[kth]; } /** 283 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 @param nums 数组 @note 说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次数。 */ void moveZeroes(std::vector<int>& nums) { int i = 0; /// 索引 i 记录当前考察的元素 int j = 0; /// 索引 j 记录当前第一个值为 0 元素的索引 while (i < nums.size() && j < nums.size()) { if (nums[i] != 0 && nums[j] == 0) { std::swap(nums[i++], nums[j++]); continue; } if (nums[i] == 0 && nums[j] != 0) { i++; j++; continue; } if (nums[i] == 0 && nums[j] == 0) { i++; continue; } if (nums[i] != 0 && nums[j] != 0) { i++; j++; continue; } } } /** * 283 */ void moveZeroes1(std::vector<int>& nums) { std::ios::sync_with_stdio(false); std::cin.tie(0); int j = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { if (i != j) { std::swap(nums[i], nums[j]); } j++; } } } /** * 283 */ void moveZeroes2(std::vector<int>& nums) { std::ios::sync_with_stdio(false); std::cin.tie(0); int j = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { if (i != j) { nums[j] = nums[i]; } j++; } } for (int i = j; i < nums.size(); i++) { nums[i] = 0; } } /** 334 给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。 数学表达式如下: 如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1, 使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。 说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。 @param nums 数组 @return 存在 返回 true ,否则 返回 false */ bool increasingTriplet(std::vector<int>& nums) { return true; } #pragma mark - Basic /** 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: [7,1,5,3,6,4] 输出: 7 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。 示例 2: 输入: [1,2,3,4,5] 输出: 4 解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。 因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。 示例 3: 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 @param prices 价格数组 @return 返回最大利润 */ int maxProfit(std::vector<int>& prices) { return 0; } /** 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。 要求使用空间复杂度为 O(1) 的原地算法。 @param nums 数组 @param k 移动数组 */ void rotate(std::vector<int>& nums, int k) { int step = k % nums.size(); if (step == 0) { return; } int r = (int)(nums.size() - step); /// 注意这里 nums.size() - 1 , for (int i = 0; i < nums.size() - 1; i++) { if (r >= nums.size()) { r = int(nums.size() - step); } std::swap(nums[i],nums[r++]); } } #pragma mark - Byte Dance /** 3 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 @param s 字符串你 @return 最长子串的长度 */ int lengthOfLongestSubstring1(std::string s) { int i = 0; int j = -1; int freq[256] = {0}; int maxLen = 0; while (i < s.length()) { if (freq[s[i]] == 0) { freq[s[i]] ++; i++; } else { j++; freq[s[i]] --; maxLen = std::max(maxLen, i-j); } } return maxLen; } /** 编写一个函数来查找字符串数组中的最长公共前缀。 输入: ["flower","flow","flight"] 输出: "fl" 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 @param strs 字符串 @return 最长公共前缀4 */ std::string longestCommonPrefix(std::vector<std::string>& strs) { return ""; } }; #endif
true
0fe2884edbb01109a802becb5545d2185bd61e1a
C++
luisMbedder/flesch-kincaid
/Flesch-Kincaid/FleschKincaid.cpp
UTF-8
2,844
3.296875
3
[]
no_license
/* * File: FleschKincaid.cpp * ---------------------- * Name: [TODO: enter name here] * Section: [TODO: enter section leader here] * This file is the starter project for the Flesch-Kincaid problem. * [TODO: rewrite the documentation] */ #include <iostream> #include <iterator> #include <regex> #include <fstream> #include "console.h" #include <string> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace std; string promptForFile(ifstream & infile, string prompt = ""); void countWords(std::vector<string> *strPtr); void countSyllables(std::vector<string> *strPtr); bool isVowel(char c); int wordCount=0; int punctuationCount=0; int syllables=0; int main() { std::vector<string> list; string str; boost::char_separator<char> sep(" ",",.-!?\/|:;^&",boost::drop_empty_tokens); ifstream scoresFile; promptForFile(scoresFile, "input file:"); while(!scoresFile.eof()) { getline(scoresFile,str); boost::tokenizer< boost::char_separator<char> > tokens(str,sep); boost::tokenizer<> tok(str); BOOST_FOREACH (const string& t, tokens) { //cout << t << endl; list.push_back(t); } } countWords(&list); countSyllables(&list); std::cout<< "Words: "<<wordCount<<endl; std::cout<< "Sentences: "<<punctuationCount<<endl; std::cout<< "Syllables: "<<syllables<<endl; return 0; } void countWords(std::vector<string> *strPtr){ std::vector<string> list = *strPtr; std::vector<string>::iterator listIterator; for(listIterator =list.begin();listIterator!= list.end();listIterator++){ string str = *listIterator; if(isalpha(str[0])) { wordCount++; } else if((str[0] == '.') || (str[0] == '!') || (str[0] == '?')) { punctuationCount++; } } } void countSyllables(std::vector<string> *strPtr){ std::vector<string> list = *strPtr; std::vector<string>::iterator listIterator; int i; for(listIterator =list.begin();listIterator!= list.end();listIterator++){ string str =*listIterator; for(i=0;i<str.length();i++){ char c = tolower(str[i]); if(isVowel(c)) { if(i==0) { syllables++; } else{ if((!isVowel(str[i-1]))&&!((c=='e')&&(i==str.length()-1))) syllables++; else if((c=='e')&&(i==str.length()-1)) syllables++; } } } } } bool isVowel(char c){ switch(c){ case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': return true; default: return false; } } string promptForFile(std::ifstream & infile, std::string prompt){ while (true){ std::cout << prompt; std::string filename; std::getline(std::cin,filename); infile.open(filename.c_str()); if (!infile.fail()) return filename; infile.clear(); std::cout << "Unable to open file. Try again." << std::endl; if (prompt == "") prompt = "input file:"; } }
true
2c7c8733888e3a4e7be0cd19ed73a7afe8c8d28f
C++
neerajarun2001/exercises
/learn-cpp/ch03/quiz/q1.cpp
UTF-8
538
3.5
4
[]
no_license
// buggy code, fix it // 1. find root cause // 2. understand problem // 3. propose fix // 4. implement fix // 5. retest #include <iostream> int readNumber(int x) { std::cout << "Please enter a number: "; std::cin >> x; return x; } void writeAnswer(int x) { std::cout << "The sum is:" << x << '\n'; } // general comment: use better variable names int main() { int x{ 0 }; // pass by value, so main x is still 0 here (scoping) // fix by adding x = x = readNumber(x); x = x + readNumber(x); writeAnswer(x); return 0; }
true
76e97a8d913fdbd879733365c45404c88bac0dc0
C++
wengsht/oh_my_life2
/include/RecordPocket.h
UTF-8
960
2.65625
3
[]
no_license
#ifndef __RECORD_POCKET_H__ #define __RECORD_POCKET_H__ #include "Record.h" #include <vector> #include <ctime> using namespace std; class RecordPocket { public: RecordPocket(int year, int mon, int day, int day_interval); void resetDate(int year, int mon, int day, int day_interval); int recordSize() const; Record &getRecord(int I); Record &getRecordById(int id); int getInterval() const; int getBeginYear() const; int getBeginMonth() const; int getBeginDay() const; int getEndYear() const; int getEndMonth() const; int getEndDay() const; void addRecord(Record &record); void removeRecord(int index); void clear(); pair<int, int> getLatestHM() const; Record& operator [](int I); private: vector<Record> records; struct tm begin_time, end_time; int day_interval; }; #endif
true
8794d7775889e74538fcf08666a76f757644a545
C++
VadimK128/LABA-1
/lab1.cpp
UTF-8
2,791
3.109375
3
[]
no_license
#include <iostream> #define _USE_MATH_DEFINES #include <math.h> #include <string> using namespace std; int main() { int a, b, c; a = 1; b = 13; c = 49; cout << a << " " << b << " " << c << "\n"; //1 char s; cout << "Enter your char:"; cin >> s; cout << a << s << b << s << c << s << "\n"; //2 int a1, b1, c1; cout << "Enter 3 numbers:"; cin >> a1 >> b1 >> c1; cout << a1 << " " << b1 << " " << c1 << "\n"; //3 double x, y, a2; cout << "Enter your a:"; cin >> a2; x = 12 * a2 * a2 + 7. * a - 12; y = 3 * x * x * x + 4 * x * x - 11 * x + 1; cout << "x=" << x << "\n" << "y=" << y << "\n"; //4 double V, m, ro; cout << "Enter body volume:"; cin >> V; cout << "OK, now enter body mass:"; cin >> m; ro = m / V; cout << "Density is:" << ro << "\n"; //(1) double x2, a3, b2; cout << "Enter a!=0, b:"; cin >> a3 >> b2; while (a3 == 0) { cout << "'A' should not be equal to 0, Enter a!=0:"; cin >> a3; } x2 = -b2 / a3; cout << "x =" << x2 << "\n"; //(2) double x3, y3, x4, y4, S; cout << "Enter x1, y1:"; cin >> x3 >> y3; cout << "Enter x2, y2:"; cin >> x4 >> y4; S = sqrt((x4 - x3)*(x4 - x3) + (y4 - y3)*(y4 - y3)); cout << "S=" << S << "\n"; //(3) double l1, l2, h, l3, P; // l1, l2 - osnovaniya, l3 - bok. storona cout << "Enter l1, l2, h:"; cin >> l1 >> l2 >> h; if (l2 >= l1) l3 = sqrt(h * h + pow((l2 - l1) / 2, 2)); else l3 = sqrt(h * h + pow((l1 - l2) / 2, 2)); P = l1 + l2 + 2 * l3; cout << "P=" << P << "\n"; //(4) double r1, r2, Sk; cout << "Enter r1, r2:"; cin >> r1 >> r2; if (r2 >= r1) Sk = M_PI * r2 * r2 - M_PI * r1 * r1; else Sk = M_PI * r1 * r1 - M_PI * r2 * r2; cout << "Sk=" << Sk << "\n"; //(5) double a6, Sbok, Vk; cout << "Enter a:"; cin >> a6; Sbok = pow(a6, 2); Vk = pow(a6, 3); cout << "Vk=" << Vk << endl << "Sbok=" << S << endl; //(6) int a7, P7; cout << "Enter a:"; cin >> a7; P7 = 4 * a7; cout << "P7=" << P7 << endl; //(7) int radius, diametr; cout << "Enter radius:"; cin >> radius; diametr = 2 * radius; cout << "Diametr=" << diametr << endl; //(8) string name; cout << "Enter your name:"; cin >> name; string prefix = "Hello, "; string message = prefix + name + "!"; cout << message << endl; //(9) string word; bool proverka; while (word.length() != 7) { cout << "Enter word:"; cin >> word; } for (int i = 0; i < 4; i++) { if (word[i] == word[6 - i]) proverka = true; else proverka = false; } if (proverka == true) cout << "This is polindrom!" << endl; else cout << "Sorry, this is not polindrom!" << endl; //(10) system("pause"); return 0; }
true
cea59b1ec827f131b6cb98d1e1a5699fc1825ff4
C++
zhangbiran/engine
/engine/engine/NetWork/UDP/udp_client.h
GB18030
1,641
2.78125
3
[]
no_license
#ifndef __UDP_CLIENT_H #define __UDP_CLIENT_H #include "test.h" #include <windows.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") /* udpsocketҲǿʹconnectģԼ߷Чʣֻܺһserverͨ */ class UDP_client : public CTest { public: void test(int argc, char ** argv) { WSAData data = { 0 }; WSAStartup(MAKEWORD(2, 2), &data); SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); if (INVALID_SOCKET == sock) { cout << "socket failed" << endl; } struct sockaddr_in server_addr = { 0 }; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(8888); server_addr.sin_addr.S_un.S_addr = inet_addr("192.168.9.202"); cout << "client start.." << endl; bool useConnectUdp = false; { if (SOCKET_ERROR == connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr))) { cout << "connect failed" << endl; return; } useConnectUdp = true; } char buf[100] = { 0 }; while (cin.getline(buf, 100)) { char recvBuf[100] = { 0 }; if (!useConnectUdp) { sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&server_addr, sizeof(server_addr)); recvfrom(sock, recvBuf, 100, 0, NULL, NULL); } else { if (SOCKET_ERROR == send(sock, buf, strlen(buf), 0)) { cout << "send failed errno: " << WSAGetLastError() << endl; return; } if (SOCKET_ERROR == recv(sock, recvBuf, sizeof(recvBuf), 0)) { cout << "recv failed errno: " << WSAGetLastError() << endl; return; } } cout << recvBuf << endl; } } }; #endif
true
b0114a089e54697ca4e2f1a45275f28824ddc031
C++
JoshuaTPierce/Learning_Repo1
/Lafore_OOCPP/Streams and DiskIO Programs/overloadedIoOperators.CPP
UTF-8
1,854
4.15625
4
[]
no_license
//Demonstrates Overloaded Extraction and Insertion Operators //This is a powerful feature of C++. It lets you treat I/O for user-defined data types in the //same way as basic types like int and double. For example, if you have an object of class //crawdad called cd1, you can display it with the statement //cout << “\ncd1=” << cd1; //just as if it were a basic data type. //We can overload the extraction and insertion operators so they work with the display and keyboard //(cout and cin) alone. With a little more care, we can also overload them so they work //with disk files. We’ll look at examples of both of these situations. #include <iostream> using namespace std; class Distance { private: int feet; float inches; public: Distance() : feet(0), inches(0.0) //constructor (no args) { } //constructor (two args) Distance(int ft, float in) : feet(ft), inches(in) { } friend istream& operator >> (istream& s, Distance& d); friend ostream& operator << (ostream& s, Distance& d); }; istream& operator >> (istream& s, Distance& d) { //get distance from user cout << "\nEnter feet: "; s >> d.feet; //using cout << "Enter inches: "; s >> d.inches; //overloaded return s; //>> operator } ostream& operator << (ostream& s, Distance& d) { // display distance s << d.feet << "\'-" << d.inches << '\"'; //using return s; //overloaded } // << operator int main() { Distance dist1, dist2; //define Distances Distance dist3(11, 6.25); //define, initialize dist3 cout << "\nEnter two Distance values:"; cin >> dist1 >> dist2; //get values from user //display distances cout << "\ndist1 = " << dist1 << "\ndist2 = " << dist2; cout << "\ndist3 = " << dist3 << endl; return 0; }
true
1f308c559ba9d881b99b716ee74690f1497f0fab
C++
AbhijeetKrishnan/codebook
/CodeChef/FEB16/STROPR.cpp
UTF-8
1,293
2.984375
3
[ "CC0-1.0" ]
permissive
#include <cstdio> #include <vector> using namespace std; typedef long long int lli; const int M = 1e9 + 7; int gcdExtended(int, int, int*, int*); int modinv(int a, int m) { int x, y; int g = gcdExtended(a, m, &x, &y); int res = (x%m + m) % m; return res; } // C function for extended Euclidean Algorithm int gcdExtended(int a, int b, int *x, int *y) { // Base Case if (a == 0) { *x = 0, *y = 1; return b; } int x1, y1; // To store results of recursive call int gcd = gcdExtended(b%a, a, &x1, &y1); // Update x and y using results of recursive // call *x = y1 - (b/a) * x1; *y = x1; return gcd; } int main() { int t; scanf("%d", &t); while (t--) { int n, x; lli m; scanf("%d %d %lld", &n, &x, &m); vector<int> v(n); for (int i = 0; i < n; i++) { lli hold; scanf("%lld", &hold); v[i] = hold % M; } int ans = v[x-1], curr_coeff = 1; m = m % M; for (int i = x - 2, j = 1; i >= 0; i--, j++) { curr_coeff = (curr_coeff * (((m + j - 1) * modinv(j, M)) % M)) % M; ans = (ans + ((lli)curr_coeff * v[i]) % M) % M; } printf("%d\n", ans); } return 0; }
true
2f79f713c6957f67dcbfca6007b9b58d775350ba
C++
Woffee/acm
/CPP/2013-2015/HDOJ/邂逅明下(巴士博弈).cpp
GB18030
1,239
3.09375
3
[]
no_license
/* ʿ http://acm.hdu.edu.cn/showproblem.php?pid=2897 ⣺Ӳҵĸÿȡȡpȡqȡ˾ ˵DzģDZ˿ͻûģ֪Ǿͬ ⷨҪжʣµӲҵĸˣǷбʤIJԣԵֵAʣµӲ0<=K<=pAʤ Bʤ ó N = (p+q)*r+k AʤһAȡTԺÿBȡXAȡ(p+q-x)ʣµֻҪq<K<=pAʤ BʤȡǼAÿȡx,Bÿȡ(p+q-x)ʣµֻҪ0<K<=pBʤ 2014.9.1 */ #include <algorithm> //sort() #include <iostream> #include <iomanip> // #include <fstream> // #include <cstring> #include <string> #include <cstdio> #include <cmath> #include <stack> #include <time.h> // using namespace std; int main() { int n,p,q; while(~scanf("%d%d%d",&n,&p,&q)) { n = n%(p+q); if(n>0 && n<=p) printf("LOST\n"); else printf("WIN\n"); } return 0; }
true
d7c8632ce81dbc074954a127081e2c87b1267639
C++
SiravitPhokeed/machine-learning-01
/MLP.h
UTF-8
6,461
2.84375
3
[]
no_license
#ifndef MLP_H #define MLP_H #include <math.h> #include <vector> #include <time.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <string> #define LearningRate 0.1 using namespace std; class MLPCell { double delta; double bias; double sigmoid(double x) { return 1/(1 + exp(-x)); } double dSigmoid(double x) { return x*(1-x); } public: vector<double> input; vector<double> inerr; vector<double> weight; double output; MLPCell(int inputNum); void FeedForward(); void BackPropagate(double derr); void AdjustWeight(double lr); }; class MLP { vector<MLPCell> hiddenLayer; vector<MLPCell> outputLayer; double myThreshold; double Step(double value) {if(value<myThreshold) return 0.0; else return 1.0;} public: vector<double> input; vector<double> output; MLP(int inputNum,int hiddenNum,int outputNum,double threshold); void Testing(); bool Training(double trainingInput[], double trainingOutput[]); void SaveWeight(string FileName); //Assignment1 void LoadWeight(string FileName); //Assignment2 }; #endif MLPCell::MLPCell(int inputNum){ srand((unsigned)time(NULL)); bias = 0; input.resize(inputNum); inerr.resize(inputNum); for (int i=0;i<inputNum;i++) weight.push_back(rand()/RAND_MAX); } void MLPCell::FeedForward(){ double sum = bias; for (int i=0;i<input.size();i++) sum += input[i]*weight[i]; output = sigmoid(sum); } void MLPCell::BackPropagate(double derr){ delta = derr*dSigmoid(output); for (int i=0;i<inerr.size();i++) inerr[i] = delta * weight[i]; } void MLPCell::AdjustWeight(double lr){ bias += delta*lr; for (int i=0;i<weight.size();i++) weight[i] += input[i]*delta*lr; } //=================== MLP ======================== MLP::MLP(int inputNum,int hiddenNum,int outputNum,double threshold){ hiddenLayer.resize(hiddenNum,MLPCell(inputNum)); outputLayer.resize(outputNum,MLPCell(hiddenNum)); input.resize(inputNum); output.resize(outputNum); myThreshold = threshold; } bool MLP::Training(double trainingInput[], double trainingOutput[]){ // this part below doesn't work :( // sizeof an array with 4 things returns 8 (should be 32) // if (sizeof(trainingInput)/sizeof(double) != input.size() || // sizeof(trainingOutput)/sizeof(double) != output.size()) { // cout << "Training data range not match!!" << endl; // return false; // } for (int i=0;i<input.size();i++) input[i]=trainingInput[i]; do{ Testing(); double sumerr=0; for (int i=0;i<outputLayer.size();i++) sumerr+=abs(trainingOutput[i]-output[i]); if(sumerr==0) break; for(int i=0;i<outputLayer.size();i++){ outputLayer[i].BackPropagate(trainingOutput[i]-outputLayer[i].output); outputLayer[i].AdjustWeight(0.01); } for(int i=0;i<hiddenLayer.size();i++){ double sumInerr=0; for(int j=0;j<outputLayer.size();j++) sumInerr+=outputLayer[j].inerr[i]; hiddenLayer[i].BackPropagate(sumInerr); hiddenLayer[i].AdjustWeight(0.01); } }while(true); return true; } void MLP::Testing(){ // -------------- testing hedden layer ------------------- for (int i=0;i<hiddenLayer.size();i++){ for(int j=0;j<input.size();j++) hiddenLayer[i].input[j]=input[j]; hiddenLayer[i].FeedForward(); } //--------------- testing output layer ------------------- for (int i=0;i<outputLayer.size();i++){ for(int j=0;j<hiddenLayer.size();j++) outputLayer[i].input[j]=hiddenLayer[j].output; outputLayer[i].FeedForward(); output[i] = Step(outputLayer[i].output); } } void MLP::SaveWeight(string FileName) { cout << "Saving to " << FileName << endl << endl; fstream SaveFile; SaveFile.open(FileName, fstream::out); SaveFile << "MLP Weights 🍌" << endl; SaveFile << "Init:" << endl; SaveFile << input.size() << " " << hiddenLayer.size() << " " << outputLayer.size() << " " << myThreshold << " " << endl; SaveFile << "Weights:" << endl; cout << "Input->hidden weights: {" << endl; for (int i=0; i<hiddenLayer.size(); i++) { cout << " { "; for (int j=0; j<input.size(); j++) { SaveFile << hiddenLayer[i].weight[j] << " "; cout << hiddenLayer[i].weight[j] << ", "; } SaveFile << endl; cout << "}," << endl; } cout << "}" << endl << endl; cout << "Hidden->output weights: {" << endl; for (int i=0; i<outputLayer.size(); i++) { cout << " { "; for(int j=0; j<hiddenLayer.size(); j++) { SaveFile << outputLayer[i].weight[j] << " "; cout << hiddenLayer[i].weight[j] << ", "; } SaveFile << endl; cout << "}," << endl; } cout << "}" << endl; SaveFile.close(); } void MLP::LoadWeight(string FileName) { cout << "Loading from " << FileName << endl; int inputNum; int hiddenNum; int outputNum; double threshold; string currLine; fstream LoadFile; LoadFile.open(FileName, fstream::in); getline(LoadFile, currLine); if (currLine.compare("MLP Weights ≡ƒìî")) { // C++ read "🍌" as "≡ƒìî" for some reason cout << "Signature check passed." << endl << endl; getline(LoadFile, currLine); if (currLine.compare("Init: ")) { cout << "Loading init..." << endl; for (int i=0; i<4; i++) { getline(LoadFile, currLine, ' '); switch (i) { case 0: inputNum = stoi(currLine); break; case 1: hiddenNum = stoi(currLine); break; case 2: outputNum = stoi(currLine); break; case 3: threshold = stof(currLine); break; } } cout << "No. of inputs: " << inputNum << endl; cout << "No. of hidden cells: " << hiddenNum << endl; cout << "No. of outputs: " << outputNum << endl; cout << "Threshold: " << threshold << endl << endl; getline(LoadFile, currLine); if (currLine.compare("Weights: ")) { cout << "Loading weights..." << endl; getline(LoadFile, currLine); for (int i=0; i<hiddenNum; i++) { for (int j=0; j<inputNum; j++) { getline(LoadFile, currLine, ' '); hiddenLayer[i].weight[j] = stod(currLine); } } for (int i=0; i<outputNum; i++) { for(int j=0; j<hiddenNum; j++) { getline(LoadFile, currLine, ' '); outputLayer[i].weight[j] = stod(currLine); } } cout << "Weights loaded successfully." << endl << endl; } else { cout << "Weights load failed." << endl; } } else { cout << "Init load failed." << endl; } } else { cout << "Invalid file!" << endl; } }
true
d4d785143e16ef4028a6c40e0f68ca63349a178d
C++
pauldoucet/AF1-glow
/left_arduino/left_arduino.ino
UTF-8
670
2.71875
3
[]
no_license
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> RF24 radio(7, 8); // CNS, CE uint8_t address_right[6] = "00001"; // address of right NRF24 /** * Setup the NRF24 radio module by * initializing power amplifier level, opening reading pipe * and starting listening */ void setup_NRF24() { radio.begin(); radio.openReadingPipe(0, address_right); radio.setPALevel(RF24_PA_MIN); radio.startListening(); } void setup() { Serial.begin(9600); // Setup NRF24 setup_NRF24(); } void loop() { if(radio.available()) { int values[32] = ""; radio.read(&values, sizeof(values)); Serial.println(text); } }
true
20952e644bb9012fcb5a8322c918ee781d6b2560
C++
canokulmus/CENG_METU
/Ceng113/C++ Ex./Template_Function/deleteval.cpp
UTF-8
795
3.984375
4
[]
no_license
#include <iostream> // Write a C++ template function to solve the following problem: // delete a value val from an unsorted array A[0..n-1]. Assume all values // in A are distinct. // Use the following function header: template<class C> void delete_val(C A[], int &n, C val); // n is the number of elements in the array, val is the value to be deleted // n must be decreased by one if deletion is successful // First find the location of val in the array. // Delete val by shifting the remaining elements to the left by one position. // Decrement n. template<class C> void delete_val(C A[], int &n, C val) { int i; for (i = 0; i < n; i++){ if (A[i] == val){ break; } } for (; i < n; i++){ A[i] = A[i+1]; } n--; // TODO }
true
5ebd13ad538b9b7784ca65ccf951ea49ddacc565
C++
wsq-siquan/CS32-UCLA-2017summer
/project1/main.cpp
UTF-8
1,901
2.5625
3
[]
no_license
// // //#include <cstdlib> //#include <ctime> ////#include "Game.h" // // ///////////////////////////////////////////////////////////////////////////// //// main() ///////////////////////////////////////////////////////////////////////////// // // // //int main() //{ // //doBasicTests(); // // Initialize the random number generator. (You don't need to // // understand how this works.) // srand(static_cast<unsigned int>(time(0))); // // // Create a game // // Use this instead to create a mini-game: Game g(3, 3, 2); // Game g(15, 18, 80); // // // Play the game // g.play(); //} //#include "History.h" //int main() //{ // History h(2, 2); // h.record(1, 1); // h.display(); //} //#include "Robot.h" //int main() //{ // Robot r(0, 1, 1); //} //#include "Player.h" //int main() //{ // Player p(0, 1, 1); //} //#include "Arena.h" //int main() //{ // Arena a(10, 18); // a.addPlayer(2, 2); //} //#include "globals.h" //#include "Player.h" //#include "Arena.h" //int main() //{ // Arena a(10, 20); // Player p(&a, 2, 3); //} //#include "Arena.h" //#include "Player.h" //int main() //{ // Arena a(10, 20); // Player p(&a, 2, 3); //} //#include "Player.h" //#include "Arena.h" //int main() //{ // Arena a(10, 20); // Player p(&a, 2, 3); //} //#include<iostream> //using namespace std; //#include "Arena.h" //#include "Player.h" //#include "History.h" //#include "globals.h" //int main() //{ // Arena a(2, 2); // a.addPlayer(1, 1); // a.player()->move(RIGHT); // a.player()->stand(); // a.player()->move(DOWN); // a.history().display(); // // int aa; // cin >> aa; //} //#include "Player.h" //#include "Arena.h" //int main() //{ // Arena a(10, 20); // Player p(&a, 2, 3); // Robot r(&a, 1, 1); //} //#include "globals.h" //#include "Robot.h" //#include "Player.h" //int main() //{ // Arena a(10, 10); //} #include "History.h" int main() { History h; }
true
1c3e7b88dc82a511851b348d97962aa735abfa14
C++
duydung271/PiratesBomb
/PriateBomb/Sources/GameObject/Cloud.cpp
UTF-8
621
2.703125
3
[]
no_license
#include "Cloud.h" void Cloud::Init(std::string name) { m_Cloud.setTexture(*ResourceManagers::GetInstance()->GetTexture(name)); m_Speed = sf::Vector2f(-60.f, 0.f); } void Cloud::Update(float deltaTime) { if (m_Cloud.getPosition().x <= -1000.f) m_Cloud.setPosition(m_SavePoint); m_Cloud.move(m_Speed*deltaTime); } void Cloud::Draw(sf::RenderWindow* window) { window->draw(m_Cloud); } void Cloud::setPosition(sf::Vector2f pos) { m_Cloud.setPosition(pos); m_SavePoint = pos; } void Cloud::setScale(sf::Vector2f scale) { m_Cloud.setScale(scale); } void Cloud::setSpeed(sf::Vector2f speed) { m_Speed = speed; }
true
0686283c17f10cc9b58af28b799e502e44d62c79
C++
Cole-Resetco/schoolWork-C9
/CS10/cs010_practice/labs/lab04/lab4.cpp
UTF-8
1,835
3.359375
3
[]
no_license
// =============== BEGIN ASSESSMENT HEADER ================ /// @file lab04.cpp /// @brief lab4/Branches and Chars /// /// @author Cole Resetco [crese002@ucr.edu] /// @date January, 29, 2015 // ================== END ASSESSMENT HEADER =============== #include <iostream> #include <string> using namespace std; #include <iostream> using namespace std; int main() { int ex; cout << "Which exercise? "; cin >> ex; cout << endl; if (1 == ex) { string word; cout << "Enter a word: "; cin >> word; for (int i = 0; i < word.size(); ++i) { if (word.at(i) == 'e') { //cout << '3'; //cout << word.at(i); word.at(word.find('e')) = '3'; //cout << word.at(i); } else if (word.at(i) == 'i') { //cout << '1'; //cout << word.at(i); word.at(word.find('i')) = '1'; } else if (word.at(i) == 'x') { //cout << '*'; //cout << word.at(i); word.at(word.find('x')) = '*'; } } cout << endl; cout << "Your word transformed is " << word << endl; // All Exercise 1 code } else if (2 == ex) { string word2; int period = 0; int periodind = 0; int stopind = 0; int stop = 0; cout << "Enter a word: "; cin >> word2; for (int i = 0; i < word2.size(); ++i) { if (word2.at(i) == '.') { period = 1; periodind = i; } if (word2.at(i) == 's') { if (word2.at(i+1) == 't') { if (word2.at(i+2) == 'o') { stop = 1; stopind = i; } } } } if (period == 1) { cout << " " << periodind << endl; } if (stop == 1) { cout << "yayaya " << stopind << endl; } } return 0; }
true
afa703567abba7d56fddb6517711222f39eab5ea
C++
yegcjs/CourseManageSystem
/sources/StartWindow.cpp
GB18030
4,744
2.609375
3
[]
no_license
#include "StartWindow.h" #include "StudentWindow.h" #include "AdminWindow.h" #pragma execution_character_set("utf-8") #pragma warning(disable:26812) #include<QString> #include<QPixmap> #include<QTextCodec> #include<QDebug> #include<QGridLayout> #include<QMessagebox> StartWindow::StartWindow(QWidget *parent) : QMainWindow(parent) { QWidget* centralWidget = new QWidget(this); setCentralWidget(centralWidget); engine = new Engine(); identityButton = new QPushButton(QString("лԱ")); modeButton = new QPushButton("лע"); usernameLabel = new QLabel("û"); passwordLabel = new QLabel(""); usernameEdit = new QLineEdit(); passwordEdit = new QLineEdit(); passwordEdit->setEchoMode(QLineEdit::Password); submitButton = new QPushButton("Submit" ); confirmLabel = new QLabel("ȷ"); confirmLabel->hide(); confirmEdit = new QLineEdit(); confirmEdit->hide(); confirmEdit->setEchoMode(QLineEdit::Password); connect(identityButton, &QPushButton::clicked, [=]() { if (identityButton->text() == QString("лԱ")) { identityButton->setText("лѧ"); usernameEdit->setText("Admin"); if(modeButton->text()==QString("л¼")) modeButton->click(); } else { identityButton->setText("лԱ"); usernameEdit->clear(); } } ); connect(modeButton, &QPushButton::clicked, [=]() { if (modeButton->text() == QString("лע")) { confirmLabel->show(); confirmEdit->show(); modeButton->setText("л¼"); } else { modeButton->setText("лע"); confirmLabel->hide(); confirmEdit->hide(); } }); connect(submitButton, &QPushButton::clicked, [=]() { if (modeButton->text() == QString("лע")) Login(); else SignUp(); }); open_eyes = new QLabel; close_eyes = new QLabel; open_eyes->setPixmap(QPixmap("pic/open_eyes.jpg")); close_eyes->setPixmap(QPixmap("pic/close_eyes.jpg")); Layout(centralWidget); } void StartWindow::closeEvent(QCloseEvent* ev) { delete engine;//including Archive() } void StartWindow::Login() { int flag = starter.Login(identityButton->text() == QString("лԱ") ? 0 : 1, usernameEdit->text(), passwordEdit->text()); if (flag == 0) QMessageBox::information(this, "¼ʧ", "û"); else { QMessageBox::information(this, "¼ɹ", "Welcome!"); if (usernameEdit->text() != QString("Admin")) { StudentWindow* studentWin = new StudentWindow(usernameEdit->text(), engine); connect(studentWin, &StudentWindow::logout, [=](QWidget* window) { //window->close(); delete window; this->show(); }); studentWin->show(); } else { AdminWindow* AdminWin = new AdminWindow(engine); connect(AdminWin, &AdminWindow::logout, [=](QWidget* window) { //window->close(); delete window; this->show(); }); AdminWin->show(); } this->hide(); } usernameEdit->clear(); passwordEdit->clear(); confirmEdit->clear(); } void StartWindow::SignUp() { int flag = starter.SignUp(usernameEdit->text(), passwordEdit->text(), confirmEdit->text()); if (flag == 1) QMessageBox::information(this, "עʧ", "ûϷ޴Сдĸ"); else if (flag == 2) QMessageBox::information(this, "עʧ", "ûѱע"); else if (flag == 3) QMessageBox::information(this, "עʧ", "벻ͬ"); else if(flag==0){ QMessageBox::information(this, "עɹ", "ɹ"); modeButton->setText("лע"); confirmLabel->hide(); confirmEdit->hide(); } usernameEdit->clear(); passwordEdit->clear(); confirmEdit->clear(); } void StartWindow::Layout(QWidget* cWidget) { QGridLayout* layout = new QGridLayout(cWidget); layout->addWidget(identityButton, 0, 2, 1, 2); layout->addWidget(modeButton, 0, 4, 1, 2); layout->addWidget(usernameLabel, 1, 1); layout->addWidget(usernameEdit, 1, 2, 1, 4); layout->addWidget(passwordLabel, 2, 1); layout->addWidget(passwordEdit, 2, 2, 1, 4); layout->addWidget(confirmLabel, 3, 1); layout->addWidget(confirmEdit, 3, 2, 1, 4); layout->addWidget(submitButton, 4, 3, 1, 2); layout->addWidget(close_eyes, 0, 0, 5, 1); layout->addWidget(open_eyes, 0, 0, 5, 1); close_eyes->hide(); connect(passwordEdit, &QLineEdit::textEdited, [this]() { open_eyes->hide(); close_eyes->show(); }); connect(passwordEdit, &QLineEdit::editingFinished, [this]() { open_eyes->show(); close_eyes->hide(); }); layout->setHorizontalSpacing(40); //qDebug() << width() <<","<< height(); }
true
43eefb93bf339357a9f5bee15125b4c42de9d50e
C++
SebasAlMo017/Lab2_20182Estructura
/menu.cpp
UTF-8
820
3.1875
3
[]
no_license
#include <iostream> using namespace std; int func1 (float); int func2 (float); int func3 (float); int func4 (float); int main(int argc, char** argv) { int (*pf1[4]) (float); int opc; opc=0; int num; int valores; pf1[0]= func1; pf1[1]= func2; pf1[2]= func3; pf1[3]= func4; do{ cout<<" enteros a=10 y b=7 \n elija la operacion deseada"<<endl; cout<<"1. Suma"<<endl; cout<<"2. Resta"<<endl; cout<<"3. Multiplicacion"<<endl; cout<<"4. Division"<<endl; cout<<"5. Salir"<<endl; cout<<" Ingrese la opcion deseada"<<endl; cin>>opc; if(opc <5 and opc>-1){ int resultado = pf1[opc-1](1.0); cout<<resultado<<endl; } }while (opc!=5); return 0; } int func1(float n1){ return 10+17; } int func2(float n1){ return 10-7; } int func3(float n1){ return 10*7; } int func4(float n1){ return (int)(10/7); }
true
ad4cb9a93108a4f2ec540e49adece6742953fb66
C++
gakarak/GUI_CBIR_Search
/GUI_MVP_Search_v4/sortedindex.h
UTF-8
480
2.78125
3
[]
no_license
#ifndef SORTEDINDEX_H #define SORTEDINDEX_H #include <QString> class SortedIndex { public: SortedIndex() : val(-1), idx(-1), str("") {} SortedIndex(float val,int idx, const QString& str ){ this->val=val; this->idx=idx; this->str = str; } ~SortedIndex() {} float val; int idx; QString str; bool operator<(const SortedIndex& other) const { return ((*this).val<other.val); } QString toQString() const; }; #endif // SORTEDINDEX_H
true
110fa28f3c38f3382e12060a95dcad15548505e8
C++
HeroIsUseless/LeetCode
/38.cpp
UTF-8
1,093
3.65625
4
[]
no_license
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: string countAndSay(int n) { string s = "1"; // 不会出现为0的 for(int i=2; i<=n; i++){ // 从2到n的那个运算 string t = ""; // 临时记录字符串 int j1=0; int j2=0; // 快慢指针 while(j2 < s.length()){ // 如果抵达终点,终止此字符串处理 while(s[j1]==s[j2] && j2<s.length()){ // 否则快慢指针读取同长度 j2++; } if(j2-j1 == 0) continue; // 此时它一定是长度 else{ t+=j2-j1+'0'; // 这个长度不应该这么算 t+=s[j1]; // 它是可以这么算的 } j1 = j2; // 慢指针前进 } cout <<i<<": "<< s<<endl; // 输出这个 s = t; // 进行下次处理的准备 } return s; } }; int main(){ Solution solution; solution.countAndSay(30); return 0; }
true
728ff4676f8ca37bdfe1c05671a1dc50340ad7e9
C++
zrss/Keyword-aware-Route-Planning
/RS_SG/main.cpp
UTF-8
3,522
2.734375
3
[]
no_license
#include "CoSKQ.h" /* int main() { int MaxDist = 0, MaxPairDist = 0; std::vector<KeyWord> Look_For; int keyword; int choice = 0; bool running = true; getSDMatrix("Data\\NYSD_4.sd", MAX_NODE_NUM); getData("Data\\Keyword.kw", MAX_NODE_NUM, NodeKW); getData("Data\\LRating.ra", MAX_NODE_NUM, NodeRating); std::pair<int, int> Range; while (running) { printf("1: Test Max Distance\n2: Test Max Pairwise Distance\n3: Test Keyword Number\n0: exit\n"); scanf("%d", &choice); if (choice) { printf("input lowerID and upperID [lowerID, upperID)\n"); scanf("%d %d", &Range.first, &Range.second); if (choice != 3) { printf("input Keyword end with 0\n"); Look_For.clear(); while (true) { scanf("%d", &keyword); if ((KeyWord)keyword) { Look_For.push_back((KeyWord)keyword); } else break; } } switch (choice) { case 1: printf("input Max Pairwise Distance\n"); scanf("%d", &MaxPairDist); printf("Start CoSKQ query\n\n"); for (int QueryNode = Range.first; QueryNode < Range.second; QueryNode += 20) { for (int MaxDist = 5000; MaxDist < 35000; MaxDist += 5000) { Rating_CoSKQ_Query(QueryNode, Look_For, std::pair<int, int>(MaxDist, MaxPairDist)); } FILE* StaFile = fopen("Result\\TestResult.txt", "a"); fprintf(StaFile, "\n"); fclose(StaFile); } break; case 2: printf("input Max Distance\n"); scanf("%d", &MaxDist); printf("Start CoSKQ query\n\n"); for (int QueryNode = Range.first; QueryNode < Range.second; QueryNode += 20) { for (int MaxPairDist = 1000; MaxPairDist < 6000; MaxPairDist += 1000) { Rating_CoSKQ_Query(QueryNode, Look_For, std::pair<int, int>(MaxDist, MaxPairDist)); } FILE* StaFile = fopen("Result\\TestResult.txt", "a"); fprintf(StaFile, "\n"); fclose(StaFile); } break; case 3: printf("input Max Distance\n"); scanf("%d", &MaxDist); printf("input Max Pairwise Distance\n"); scanf("%d", &MaxPairDist); printf("Start CoSKQ query\n\n"); KeyWord allKeyword[] = {Shop, Bar, Hospital, Library, Restaurant, Hotel, Park, Cinema, Gym, Bank}; for (int QueryNode = Range.first; QueryNode < Range.second; QueryNode += 20) { for (int KeywordNum = 2; KeywordNum < 12; KeywordNum += 2) { std::vector<KeyWord> KSet(allKeyword, allKeyword + KeywordNum); Rating_CoSKQ_Query(QueryNode, KSet, std::pair<int, int>(MaxDist, MaxPairDist)); } FILE* StaFile = fopen("Result\\TestResult.txt", "a"); fprintf(StaFile, "\n"); fclose(StaFile); } break; } } else running = false; } return 0; }*/ int main() { getSDMatrix("Data\\NYSD_4.sd", MAX_NODE_NUM); getData("Data\\Keyword.kw", MAX_NODE_NUM, NodeKW); getData("Data\\LRating.ra", MAX_NODE_NUM, NodeRating); int QueryNode = 0; int MaxDist = 0, MaxPairDist = 0; std::vector<KeyWord> Look_For; while (true) { printf("input CoSKQ query\n"); scanf("%d", &QueryNode); if (QueryNode == -1) break; scanf("%d %d", &MaxDist, &MaxPairDist); int keyword; Look_For.clear(); bool correct = true; while (true) { scanf("%d", &keyword); if (keyword) { Look_For.push_back((KeyWord)keyword); } else break; } //for (int Node = QueryNode; Node < MAX_NODE_NUM; Node += 1) { Rating_CoSKQ_Query(QueryNode, Look_For, std::pair<int, int>(MaxDist, MaxPairDist)); //printf("QueryNode: %d\n", Node); //} printf("finished\n"); } return 0; }
true
e8ac6447bb785695a1cc42d57c28ba2f5731ccf0
C++
manixaist/xplat-pmc-tutorial-07
/include/utils.h
UTF-8
2,662
3.03125
3
[]
no_license
#pragma once #include "SDL.h" #include <stdio.h> namespace XplatGameTutorial { namespace PacManClone { // Oneshot timer for state transistions class StateTimer { public: StateTimer() : _startTicks(0), _targetTicks(0), _fStarted(false) { } void Start(Uint32 waitTicks) { SDL_assert(!_fStarted); SDL_assert(_startTicks == 0); _startTicks = SDL_GetTicks(); _targetTicks = waitTicks; _fStarted = true; } void Reset() { _fStarted = false; _startTicks = 0; } bool IsStarted() { return _fStarted; } bool IsDone() { return IsStarted() && (SDL_GetTicks() - _startTicks > _targetTicks); } private: Uint32 _startTicks; Uint32 _targetTicks; bool _fStarted; }; // Simple enum to denote the 4 possible directions // The sprites can move, plus none enum class Direction { Up = 0, Down, Left, Right, None }; Direction Opposite(Direction dir); void TranslateCell(Uint16 &row, Uint16 &col, Direction direction); // Template helper to delete a class and set its pointer to nullptr template <class T> void SafeDelete(T*& p) { delete p; // null check is not required for delete p = nullptr; } // Load a texture from disk with optional transparency SDL_Texture* LoadTexture(const char *szFileName, SDL_Renderer *pSDLRenderer, SDL_Color *pSdlTransparencyColorKey); // Sets up our SDL environment and Window bool InitializeSDL(SDL_Window **ppSDLWindow, SDL_Renderer **ppSDLRenderer); // TODO - helper to calculate distance between 2 cells double Distance(Uint16 row1, Uint16 col1, Uint16 row2, Uint16 col2); // Small wrapper for the SDL_Texture object. It will cache some basic info (like size) // and free it upon destruction class TextureWrapper { public: TextureWrapper() : _pTexture(nullptr), _cxTexture(0), _cyTexture(0), _pszFilename(nullptr) { } TextureWrapper(const char *szFileName, size_t cchFileName, SDL_Renderer *pSDLRenderer, SDL_Color *pSdlTransparencyColorKey); ~TextureWrapper(); // Accessors bool IsNull() { return _pTexture == nullptr; } int Width() { return _cxTexture; } int Height() { return _cyTexture; } SDL_Texture* Ptr() { return _pTexture; } private: SDL_Texture *_pTexture; int _cxTexture; int _cyTexture; char *_pszFilename; }; } }
true
9dd1fa01ade965f86ec828557019592b9c8b054c
C++
JamyDev/OO1-SchaakSpel
/Practica Schaken/Practica Schaken/UI.cpp
UTF-8
3,469
2.96875
3
[]
no_license
#include <iostream> #include <conio.h> #include "UI.h" #include "Game.h" #include "Move.h" UI::UI() { std::cout << "Welcome to CHESS" << "\n"; printHelpToConsole(); } void UI::printHelpToConsole() { std::cout << "Commands: \n" << " - m <row><col> <row><col>: Move from first to second position (e.g.: m B2 B4)" << "\n" << " - ?: Shows this help text." << "\n" << " - s: Saves the game." << "\n" << " - l: Loads the game." << "\n" << " - q: Exit the game." << "\n" << "Press any key to continue..."; _getche(); } void UI::showHelp() { if (uiType == CONSOLE) printHelpToConsole(); } void UI::printActivePlayerToConsole(Game& game) { std::cout << "[" << ((game.getActivePlayer() == Game::PlayerColor::WHITE) ? "WHITE" : "BLACK") << "] Please enter a command (Or '?' for help): "; } void UI::displayBoard(Gameboard& board) { if (uiType == CONSOLE) { printBoardToConsole(board); } } void UI::showActivePlayer(Game& game) { if (uiType == CONSOLE) { printActivePlayerToConsole(game); } } Move* UI::getLastMove() { Move* last = lastMove; lastMove = NULL; return last; } enum UI::Command UI::askCommand(Game& game) { if (uiType == CONSOLE) { return askCommandConsole(game); } } enum UI::Command UI::askCommandConsole(Game& game) { char cmdC, fromC, toC; int fromX, fromY, toX, toY; cmdC = _getche(); Command cmd = getCommand(cmdC); if (cmd == Command::MOVE) { scanf(" %c%i %c%i", &fromC, &fromY, &toC, &toY); flush_stdin(); fromY--; toY--; fromX = (toupper(fromC) - 'A'); toX = (toupper(toC) - 'A'); lastMove = new Move(game.getGameboard()->getPieceAt(fromX, fromY), fromX, fromY, toX, toY); } return cmd; } void UI::showError(char* error) { if (uiType == CONSOLE) { printErrorToConsole(error); } } void UI::printErrorToConsole(char* error) { std::cout << error << "\n"; } void UI::printBoardToConsole(Gameboard& board) { std::cout << "\n"; std::cout << "\n-------------------------------------\n" << "| |"; for (int i = 0; i < Gameboard::VELDGROOTTE; ++i) std::cout << " " << (char)('A' + i) << " |"; std::cout << "\n=====================================\n"; for (int i = Gameboard::VELDGROOTTE - 1; i >= 0; --i) { std::cout << "| " << (i + 1) << " |"; for (int j = 0; j < Gameboard::VELDGROOTTE; ++j) { char c = ' '; Piece* p = board.getPieceAt(j, i); if (p != NULL) c = p->getSymbol(); if (p != NULL && p->getColor() == Piece::Color::BLACK) std::cout << "[" << c << "]|"; else std::cout << " " << c << " |"; } std::cout << "\n-------------------------------------\n"; } std::cout << "\n"; } char UI::askPromotion() { if (uiType == CONSOLE) return askPromotionConsole(); } char UI::askPromotionConsole() { char prom = 0; while (prom == 0) { std::cout << "What would you like to promote your pawn to? (R = Rook, B = Bishop, H = Knight, Q = Queen): "; prom = toupper(_getche()); if (prom != 'R' && prom != 'B' && prom != 'H' && prom != 'Q') prom = 0; } return prom; } /* Flush the stdin buffer (scanf leaves \n there) This way fgets on stdin doesn't just skip. */ void UI::flush_stdin() { char c; while ((c = (char)getchar()) != '\n' && c != EOF); } enum UI::Command UI::getCommand(char c) { switch (c) { case 'm': return UI::Command::MOVE; case '?': return UI::Command::HELP; case 's': return UI::Command::SAVE; case 'l': return UI::Command::LOAD; case 'q': return UI::Command::QUIT; } }
true
0aa4bcbc3df6a9f157253d873e942cc4c942c020
C++
Shain-Allen/Game-programing-year-2-Stuff
/Beta Engine Stuffs/BetaFramework-highlevelTemplate/Source/Level1.cpp
WINDOWS-1252
3,443
2.625
3
[]
no_license
//------------------------------------------------------------------------------ // // File Name: Level1.cpp // Author(s): Jeremy Kings (j.kings) // Project: BetaFramework // Course: WANIC VGP2 2018-2019 // // Copyright 2018 DigiPen (USA) Corporation. // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Include Files: //------------------------------------------------------------------------------ #include "stdafx.h" #include "Level1.h" //------------------------------------------------------------------------------ using namespace Beta; //------------------------------------------------------------------------------ // Public Functions: //------------------------------------------------------------------------------ // Creates an instance of Level 1. Level1::Level1() : Level("Level 1"), testObject(nullptr) { } // Initialize the memory associated with the Level1 game state. void Level1::Initialize() { std::cout << "Level1: Initialize" << std::endl; // Create a new game object testObject = new GameObject("TestObject"); // Create a transform component at 0,0 with scale 300,300 Transform* transform = new Transform(0.0f, 0.0f); transform->SetRotation(0.0f); transform->SetScale(Vector2D(2.0f, 2.0f)); testObject->AddComponent(transform); // Create a sprite component and set its mesh and sprite source //retrieve texture using the resource manager TexturePtr texture = ResourceGetTexture("Monkey.png"); //texture, name, number of colums, number of rows SpriteSourcePtr spritesource = std::make_shared<SpriteSource>(texture, "Monkey", 3, 5); Sprite* sprite = new Sprite(); sprite->SetSpriteSource(spritesource); testObject->AddComponent(sprite); //add animator componet Animator* animator = new Animator(); testObject->AddComponent(animator); //create animations //NOTE:: Animations require the following // name, Spritesource, Frame Count, frame start, frameduration AnimationPtr walkAnim = std::make_shared<Animation>("monkey walk", spritesource, 8, 0, 0.1f); size_t walkIndex = animator->AddAnimation(walkAnim); // Initialize the object //testObject->Initialize(); //update, Draw, delete the object for us GetSpace()->GetObjectManager().AddObject(*testObject); animator->Play(walkIndex); } // Update the Level1 game state. // Params: // dt = Change in time (in seconds) since the last game loop. void Level1::Update(float dt) { UNREFERENCED_PARAMETER(dt); Input* input = EngineGetModule(Input); // If the user presses the '1' key, restart the current level if (input->CheckTriggered('1')) GetSpace()->RestartLevel(); // If the user presses the 'D' key, delete the object if (input->CheckTriggered('D')) { //delete testObject; //testObject = nullptr; testObject->Destroy(); testObject = nullptr; } // If the object exists /*if (testObject) { // Update and draw testObject->Update(dt); testObject->Draw(); }*/ if (testObject != nullptr) { Transform* transform = testObject->GetComponent<Transform>(); Vector2D position = transform->GetTranslation(); if (input->CheckHeld(VK_RIGHT)) { position.x += 2.0f * dt; } transform->SetTranslation(position); } } // Shutdown any memory associated with the Level1 game state. void Level1::Shutdown() { std::cout << "Level1::Shutdown" << std::endl; //delete testObject; }
true