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
26b9487a1dbd9351c94211faabf37e5456f37493
C++
azimmomin/Fluid_Simulation
/scene.h
UTF-8
746
2.59375
3
[]
no_license
#ifndef SCENE_H #define SCENE_H #include "grid.h" #include "Renderer.hpp" #include "particle.h" #include "simulator.h" #include "source.h" #include "object.h" #include "point.h" #include <string> #include <vector> class Scene { public: vector<Object> objects; vector<Particle> particles; vector<Source*> sources; Grid* grid; Simulator *simulator; Renderer *renderer; string outputDirectory; int screenWidth, screenHeight; float xOffset, yOffset, zDistance; float pitch, yaw;//In degrees... int runtime;//Seconds to run if in commandline mode. int fps; int substeps;//Number of updates needed to complete one frame. Scene(std::string filename, std::string output); ~Scene(); void Draw(); void Update(int curFrame); }; #endif
true
032a3f711da18c3848b58a5f23b00774386a8069
C++
tudautroccuto741/Castlevania
/Castlevania/Items.cpp
UTF-8
1,152
3.21875
3
[]
no_license
#include "Items.h" #include "debug.h" CItems * CItems::__instance = NULL; // Add the corresponding item with the item name void CItems::Add(int itemName, LPGAMEOBJECT item) { items[itemName].push_back(item); } // Check if the object is holding item, drop it if has void CItems::CheckAndDrop(LPGAMEOBJECT object) { int item = object->GetHoldingItem(); if (item != (int)Item::NONE) { if (item == (int)Item::BALL) { Drop(item, 1200, 37); } else { float x, y; object->GetPosition(x, y); Drop(item, x, y); } } } // Get the item according to the given name and set it the gien position void CItems::Drop(int itemName, float x, float y) { if (items[itemName].empty()) DebugOut(L"\n[ERROR] No items with the given name found (Item enum: %d)", (int)itemName); else { for (auto i = items[itemName].begin(); i != items[itemName].end(); ++i) { if ((*i)->GetVisible()==false) { (*i)->SetPosition(x, y); (*i)->SetVisible(true); break; } } } } void CItems::Clear() { items.clear(); } CItems * CItems::GetInstance() { if (__instance == NULL) __instance = new CItems(); return __instance; }
true
2373fdf01460cb9cd668b06789224a88d3301a7a
C++
seesealonely/leetcode
/sort/2512.RewardTopKStudents.cc
UTF-8
3,844
3.359375
3
[]
no_license
/* You are given two string arrays positive_feedback and negative_feedback, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative. Initially every student has 0 points. Each positive word in a feedback report increases the points of a student by 3, whereas each negative word decreases the points by 1. You are given n feedback reports, represented by a 0-indexed string array report and a 0-indexed integer array student_id, where student_id[i] represents the ID of the student who has received the feedback report report[i]. The ID of each student is unique. Given an integer k, return the top k students after ranking them in non-increasing order by their points. In case more than one student has the same points, the one with the lower ID ranks higher.   Example 1: Input: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is studious","the student is smart"], student_id = [1,2], k = 2 Output: [1,2] Explanation: Both the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher. Example 2: Input: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is not studious","the student is smart"], student_id = [1,2], k = 2 Output: [2,1] Explanation: - The student with ID 1 has 1 positive feedback and 1 negative feedback, so he has 3-1=2 points. - The student with ID 2 has 1 positive feedback, so he has 3 points. Since student 2 has more points, [2,1] is returned.   Constraints: 1 <= positive_feedback.length, negative_feedback.length <= 104 1 <= positive_feedback[i].length, negative_feedback[j].length <= 100 Both positive_feedback[i] and negative_feedback[j] consists of lowercase English letters. No word is present in both positive_feedback and negative_feedback. n == report.length == student_id.length 1 <= n <= 104 report[i] consists of lowercase English letters and spaces ' '. There is a single space between consecutive words of report[i]. 1 <= report[i].length <= 100 1 <= student_id[i] <= 109 All the values of student_id[i] are unique. 1 <= k <= n */ #define c11 #include"head.h" class Solution { public: vector<int> topStudents(vector<string>& positive_feedback, vector<string>& negative_feedback, vector<string>& report, vector<int>& student_id, int k) { unordered_set<string> p(positive_feedback.begin(),positive_feedback.end()); unordered_set<string> n(negative_feedback.begin(),negative_feedback.end()); const int m=report.size(); unordered_map<int,int> score; for(int i=0;i<m;i++) { for(int j=0;j<report[i].size();j++) { string key; while(j<report[i].size()&&report[i][j]!=' ') key+=report[i][j++]; if(p.find(key)!=p.end()) score[student_id[i]]+=3; else if(n.find(key)!=n.end()) score[student_id[i]]--; } } sort(student_id.begin(),student_id.end(),[&](int x,int y) { if(score[x]!=score[y]) return score[x]>score[y]; return x<y; }); student_id.resize(k); return student_id; } }; int main() { Solution s; vector<string> p={"smart","brilliant","studious"},n={"not"},r={"this student is studious","the student is smart"}; vector<int> st={1,2}; show(s.topStudents(p,n,r,st,2)); r.clear();r={"this student is not studious","the student is smart"}; show(s.topStudents(p,n,r,st,2)); return 0; }
true
456aab74479a1507aa82e02c72a55df6f3215390
C++
Bur0k/D45az
/Client/Unit.h
UTF-8
1,079
2.625
3
[]
no_license
#ifndef UNIT_H #define UNIT_H #include <SFML\Graphics.hpp> #include "IDrawable.h" #include "IClickable.h" #include "graphic_globals.h" //#define UNIT_WIDTH 60 //#define UNIT_HEIGHT 90 static const float UNIT_WIDTH = 60.0f; static const float UNIT_HEIGHT = 90.0f; using namespace sf; enum class UnitStrategy{DEFENSIVE, OFFENSIVE, RUNNING}; enum class UnitTypes{LIGHT, HEAVY, LONGRANGE, ARTILLERY}; class Unit : public IDrawable, public IClickable { private: Rect<float> m_dimensions; SpriteTex m_UnitImage; Text m_numberOfSoldiersText; int m_numberOfSoldiers; UnitTypes m_type; RectangleShape m_textbg; bool m_mouseOver; public: bool m_clicked; Unit(Vector2f pos, UnitTypes Type, int Amount); ~Unit(); int getNumberOfSoldiers(); void setNumberOfSoldiers(int); Vector2f getPosition(); void setPosition(Vector2f); void move(Vector2f); //implementing interfaces void draw(sf::RenderWindow* rw); bool MouseMoved(sf::Vector2i &); bool PressedRight(); bool PressedLeft(); bool ReleasedRight(); bool ReleasedLeft(); private: }; #endif //UNIT_H
true
0788301305937cfb9b01a256bf1442afcdb22c33
C++
AtharvaPanegai/GeeksForGeeksCpp
/Practice/getMin/program.cpp
UTF-8
1,722
3.703125
4
[]
no_license
#include "bits/stdc++.h" using namespace std; struct myStack { stack<int> s; int minEle; void getMin() { if (s.empty()) { cout << "Stack is Empty"; return; } else { cout << "The min element is : " << minEle<<"\n"; return; } } void push(int x) { if (s.empty()) { s.push(x); minEle = x; cout << "the element pushed is : " << x << "\n"; return; } else { if (x < minEle) { minEle = x; s.push(2 * x - minEle); cout << "the element pushed is : " << x << "\n"; return; } else { s.push(x); cout << "the element pushed is : " << x << "\n"; } } } void pop(){ if(s.empty()){ cout<<"Stack is Empty nothing to pop\n"; return; } int t = s.top(); s.pop(); if(t<minEle){ minEle = 2*minEle-t; cout<<"Popped element is : "<<minEle<<"\n"; return; } else{ cout<<"The popped element is : "<<t<<"\n"; return; } } void peek(){ if(s.empty()){ cout<<"Stack is empty\n"; return; } int t = s.top(); (t<minEle)?cout<<minEle : cout<<t<<"\n"; return; } }; int main() { myStack s; s.push(1); s.push(34); s.getMin(); s.push(0); s.push(-34); s.push(123); s.push(5); s.getMin(); return 0; }
true
0d13e138aa96317a8cc2b7987c20d4f87e3b35ef
C++
Gaurav9784/Data-Structures
/Graph/BFS.cpp
UTF-8
423
3.03125
3
[]
no_license
vector <int> bfs(vector<int> g[], int N) { queue<int> q; q.push(0); bool visited[N]={false}; vector<int> ans; while(!q.empty()){ int t=q.front(); q.pop(); ans.push_back(t); for(int i=0;i<g[t].size();i++){ if(visited[g[t][i]]==false){ visited[g[t][i]]=true; q.push(g[t][i]); } } } return ans; }
true
96ca046ee17e130570db1777ec09ff6edee9eff6
C++
am-lola/lepp3
/src/lepp3/obstacles/object_approximator/split/CompositeSplitStrategy.cpp
UTF-8
686
2.71875
3
[ "MIT" ]
permissive
#include "CompositeSplitStrategy.hpp" bool lepp::CompositeSplitStrategy::shouldSplit(int split_depth, const PointCloudConstPtr& point_cloud) { size_t const sz = conditions_.size(); if (sz == 0) { // If there are no conditions, do not split the object, in order to avoid // perpetually splitting it, since there's no condition that could // possibly put an end to it. return false; } for (size_t i = 0; i < sz; ++i) { if (!conditions_[i]->shouldSplit(split_depth, point_cloud)) { // No split can happen if any of the conditions disallows it. return false; } } // Split only if all of the conditions allowed us to split return true; }
true
8fb7216b5009af2a562bcd112d00c237260aa18d
C++
KriszAime/Neuro2
/Neuro2/NeuroNetwork.cpp
UTF-8
4,489
2.546875
3
[]
no_license
#include "NeuroNetwork.h" #include <iostream> NeuralNet::NeuralNetwork::NeuralNetwork(NeuralImportData* TrainingData, int HiddenCount) { Memory = new NeuralMemory[TrainingData->PatternCount]; //- Output Weights Memory->WeightHO = new double* [HiddenCount]; for (int i = 0; i < HiddenCount; i++) Memory->WeightHO[i] = new double[TrainingData->OCount]; //- ranpat = new int[TrainingData->PatternCount]; //-Creating 1 Hidden layer (*Memory).HiddenLayers = new NeuralHiddenLayer; (*Memory).HiddenLayers->WeightIH = new double* [TrainingData->ICount]; for (int i = 0; i < TrainingData->ICount; i++) (*Memory).HiddenLayers->WeightIH[i] = new double[HiddenCount]; //- for (int i = 0; i < TrainingData->PatternCount; ranpat[i++] = i) { Memory[i].Input = new double[TrainingData->ICount]; Memory[i].Target = new double[TrainingData->OCount]; memcpy(Memory[i].Input, TrainingData->Patterns[i].Inputs, sizeof(double) * TrainingData->ICount); memcpy(Memory[i].Target, TrainingData->Patterns[i].Outputs, sizeof(double) * TrainingData->OCount); Memory[i].Output = new double[TrainingData->OCount]; Memory[i].WeightHO = Memory->WeightHO; //Mind Ugyanarra a Layerre mutat. //-Creating 1 Hidden layer if (i > 0)Memory[i].HiddenLayers = new NeuralHiddenLayer; Memory[i].HiddenLayers->WeightIH = (*Memory).HiddenLayers->WeightIH; //Mind Ugyanarra a Layerre mutat. Memory[i].HiddenLayers->Hidden = new double[HiddenCount]; Memory[i].HiddenLayers->SumH = new double[TrainingData->ICount]; Memory[i].HiddenLayers->NumHiddenNodes = HiddenCount; //- } PatternCount = TrainingData->PatternCount; NumInput = TrainingData->ICount; NumOutput = TrainingData->OCount; NumHiddenLayers = 1; } NeuralNet::NeuralNetwork::NeuralNetwork(NeuralImportData* TrainingData, int HiddenCount, double eta, double alpha, double smallwt) : NeuralNetwork(TrainingData, HiddenCount) //ezt tesztelni? { this->eta = eta; this->alpha = alpha; this->smallwt = smallwt; } bool NeuralNet::NeuralNetwork::AddHiddenLayer(int NumberOfNeurons) { return false; } bool NeuralNet::NeuralNetwork::TrainUntil(double AcceptedError, unsigned long MaxEpochs, bool IsComment) { /* initialize WeightIH and DeltaWeightIH */ double** DeltaWeightIH = new double* [NumInput]; for (uint i = 0; i < NumInput; i++) { DeltaWeightIH[i] = new double[Memory->HiddenLayers->NumHiddenNodes]; for (uint h = 0; h < Memory->HiddenLayers->NumHiddenNodes; h++) { DeltaWeightIH[i][h] = 0.0; Memory->HiddenLayers->WeightIH[i][h] = 2.0 * (hwrandom32() - 0.5) * smallwt; } } /* initialize WeightHH and DeltaWeightHH */ double*** DeltaWeightLIH = new double** [NumHiddenLayers]; if (NumHiddenLayers > 1) { for (uint l = 1; l < NumHiddenLayers; l++) { DeltaWeightLIH[l] = new double* [Memory->HiddenLayers[l - 1].NumHiddenNodes]; for (uint ih = 0; ih < Memory->HiddenLayers[l - 1].NumHiddenNodes; ih++) { DeltaWeightLIH[l][ih] = new double[Memory->HiddenLayers[l].NumHiddenNodes]; for (uint hh = 0; hh < Memory->HiddenLayers[l].NumHiddenNodes; hh++) { DeltaWeightLIH[l][ih][hh] = 0.0; Memory->HiddenLayers[l].WeightIH[ih][hh] = 2.0 * (hwrandom32() - 0.5) * smallwt; } } } } /* initialize WeightHO and DeltaWeightHO */ double** DeltaWeightHO = new double* [Memory->HiddenLayers[NumHiddenLayers - 1].NumHiddenNodes]; for (uint h = 0; h < Memory->HiddenLayers[NumHiddenLayers - 1].NumHiddenNodes; h++) { DeltaWeightHO[h] = new double[NumOutput]; for (uint o = 0; o < NumOutput; o++) { DeltaWeightHO[h][o] = 0.0; Memory->WeightHO[h][o] = 2.0 * (hwrandom32() - 0.5) * smallwt; } } for (uint p = 0; p < PatternCount; p++) ranpat[p] = p; double Error; for (uint epoch = 0; epoch < MaxEpochs; epoch++) { for (uint p = 0; p < PatternCount; p++) /* randomize order of individuals */ { uint rp = hwrandom32_t(0, PatternCount-1); uint tmp = ranpat[p]; ranpat[p] = ranpat[rp]; ranpat[rp] = tmp; } Error = 0.0; //set no error. for (uint np = 0; np < PatternCount; np++) /* repeat for all the training patterns */ { } } delete[] DeltaWeightIH, DeltaWeightLIH, DeltaWeightHO; return false; } double NeuralNet::NeuralNetwork::hwrandom32() //0..1 { unsigned int ret; _rdrand32_step(&ret); return ((double)ret / ((double)UINT_MAX + 1)); } NeuralNet::uint NeuralNet::NeuralNetwork::hwrandom32_t(uint from, uint to) //int from...to - exclusive { uint ret; _rdrand32_step(&ret); return from + ret % ((to+1)-from); }
true
50c65bcb74e01af4570589ba3297bb1912a37b22
C++
KevinLimon/Actividad_16
/main.cpp
UTF-8
2,538
3.625
4
[]
no_license
#include<iostream> #include"laboratorio.h" using namespace std; int main(){ Laboratorio k; string opcion; while (true) { cout<<"1) Agregar computadora"<<endl; cout<<"2) Mostrar computadoras"<<endl; cout<<"3) Respaldar"<<endl; cout<<"4) Recuperar"<<endl; cout<<"5) Insertar computadora"<<endl; cout<<"6) Inicializar"<<endl; cout<<"7) Eliminar"<<endl; cout<<"8) Ordenar"<<endl; cout<<"9) Borrar ultimo"<<endl; cout<<"10) Buscar Computadora"<<endl; cout<<"0) Salir"<<endl; getline(cin, opcion); if(opcion=="1"){ Computadora c; cin>>c; k.agregarFinal(c); cin.ignore(); } else if(opcion=="2"){ k.mostrar(); } else if(opcion=="3"){ k.respaldar(); } else if(opcion=="4"){ k.recuperar(); } else if(opcion=="5"){ Computadora c; cin>>c; size_t ps; cout<<"Posicion: "; cin>>ps; cin.ignore(); if(ps>=k.size()){ cout<<"Posicion no valida"<<endl; } else{ k.insertar(c, ps); } } else if(opcion=="6"){ Computadora c; cin>>c; size_t n; cout<<"Veces: "; cin>>n; cin.ignore(); k.inicializar(c, n); } else if(opcion=="7"){ size_t ps; cout<<"Posicion: "; cin>>ps; cin.ignore(); if(ps>=k.size()){ cout<<"Posicion no valida"<<endl; } else{ k.eliminar(ps); } } else if(opcion=="8"){ k.ordenar(); } else if(opcion=="9"){ if(k.size()==0){ cout<<"Arreglo vacio"<<endl; } else{ k.eliminar_ultimo(); } } else if(opcion=="10"){ //Para buscar tienen que coincidir el nombre y el color Computadora c; cin>>c; cin.ignore(); Computadora *ptr = k.buscar(c); if(ptr == nullptr){ cout<<"No encontrado"<<endl; } else{ cout<<*ptr<<endl; } } else if(opcion=="0"){ break; } } return 0; }
true
421bce758cb230761584eb8c4cbe8ea596b007c3
C++
som-thing/CPP-lessons
/GuessGame/main.cpp
UTF-8
889
3.046875
3
[]
no_license
#include <iostream> using namespace std; #include "helper.h" /* UwU */ int main(int argc, char** argv) { cout << "Hello, guess for digits\n"; int randomDigits[4]; for(int i = 0; i < 4; i++) { bool result = true; int chich; while (result==true){ chich = randint(); result = proverka(randomDigits, chich); } randomDigits[i]=chich; } bool success = false; while(success==false){ string userInput; cin >> userInput; int bully = 0; int cows = 0; for(int i = 0; i < 4; i++) { int converted = userInput[i] - '0'; for(int j = 0; j < 4; j++){ if (converted==randomDigits[j]){ if (i==j){ bully++; }else{ cows++; } } } } cout<<"For try: "<<userInput<<". Cows: " << cows << ". Bulls: " << bully << endl; if (bully==4){ success = true; cout<<"WOW, incredible!"; } } return 0; }
true
5d2ee17cc10a99c025c5912397fc320447d6b9d6
C++
Zakatos/Component-Game-Engine
/Minigin/ThreadManager.h
UTF-8
316
2.765625
3
[ "MIT" ]
permissive
#pragma once #include "Singleton.h" #include "ThreadRaii.h" #include <memory> #include <vector> class ThreadManager : public Singleton<ThreadManager> { public: void AddThread(std::shared_ptr<ThreadRaii> thread) { m_Threads.push_back(thread); } private: std::vector<std::shared_ptr<ThreadRaii>> m_Threads; };
true
afb64e4e80d6287bb1e5745466f7cf665c3b1246
C++
melkiorr/prolaz
/Source10.cpp
UTF-8
649
3.109375
3
[]
no_license
// U ovom zadatku smo trebali napraviti txt file s nekim brojevima i iz tih brojeva izvuc parne i neparne i zapisati ih u svoje filove. #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream in("brojevi.txt"); ofstream parni("parni.txt"); ofstream neparni("neparni.txt"); if (!in || !parni || !neparni) { cout << "Nemore" << endl; return 1; } int broj; while (in >> broj) { if (broj % 2 == 0) { parni << broj << endl; } else { neparni << broj << endl; } } neparni.close(); parni.close(); in.close(); return 0; }
true
265ca7a7aa9fdf51bb29f8ea5d470ccf88eb27a0
C++
gammasoft71/xtd
/tests/xtd.core.unit_tests/src/xtd/tests/generic_stream_output_tests.cpp
UTF-8
8,206
2.84375
3
[ "MIT" ]
permissive
#include <xtd/console.h> #include <xtd/tunit/assert.h> #include <xtd/tunit/string_assert.h> #include <xtd/tunit/test_class_attribute.h> #include <xtd/tunit/test_method_attribute.h> using namespace std; using namespace xtd; using namespace xtd::tunit; namespace xtd::tests { class test_class_(generic_stream_output_tests) { public: void test_method_(write_array) { stringstream result; console::set_out(result); console::write(std::array<std::string, 3> {"One", "Two", "Three"}); assert::are_equal("[One, Two, Three]", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_bool_true) { stringstream result; console::set_out(result); console::write(true); assert::are_equal("true", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_bool_false) { stringstream result; console::set_out(result); console::write(false); assert::are_equal("false", result.str(), csf_); console::set_out(console::open_standard_output()); } /// @todo Does not work on linux with tunit but it's correct with xtd.core... /// Mismatch with ostream operator << between xtd.core and xtd.tunit /// To debug when integration of xtd.core in xtd.tunit will done. /* void test_method_(write_invalid_argument) { stringstream result; console::set_out(result); console::write(std::invalid_argument("Invalid format"), csf_); std::cout << result.str() << std::endl; assert::are_equal("exception: Invalid format", result.str(), csf_); }*/ void test_method_(write_deque) { stringstream result; console::set_out(result); console::write(std::deque<std::string> {"One", "Two", "Three"}); assert::are_equal("[One, Two, Three]", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_duration) { stringstream result; console::set_out(result); console::write(std::chrono::hours(3) + std::chrono::minutes(32) + std::chrono::seconds(24) + std::chrono::nanoseconds(54300)); assert::are_equal("03:32:24:000054300", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_forward_list) { stringstream result; console::set_out(result); console::write(std::forward_list<std::string> {"One", "Two", "Three"}); assert::are_equal("[One, Two, Three]", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_initializer_list) { stringstream result; console::set_out(result); console::write({"One", "Two", "Three"}); assert::are_equal("[One, Two, Three]", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_list) { stringstream result; console::set_out(result); console::write(std::list<std::string> {"One", "Two", "Three"}); assert::are_equal("[One, Two, Three]", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_map) { stringstream result; console::set_out(result); console::write(std::map<std::string, int> {{"One", 1}, {"Two", 2}, {"Three", 3}}); assert::are_equal("{(One, 1), (Three, 3), (Two, 2)}", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_multimap) { stringstream result; console::set_out(result); console::write(std::multimap<std::string, int> {{"One", 1}, {"Two", 2}, {"Three", 3}}); assert::are_equal("{(One, 1), (Three, 3), (Two, 2)}", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_multiset) { stringstream result; console::set_out(result); console::write(std::multiset<std::string> {"One", "Two", "Three"}); assert::are_equal("{One, Three, Two}", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_optional_without_value) { stringstream result; console::set_out(result); console::write(std::optional<int>()); assert::are_equal("(null)", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_optional_with_value) { stringstream result; console::set_out(result); console::write(std::optional<int>(42)); assert::are_equal("(42)", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_pair) { stringstream result; console::set_out(result); console::write(std::make_pair("One", 2)); assert::are_equal("(One, 2)", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_set) { stringstream result; console::set_out(result); console::write(std::set<std::string> {"One", "Two", "Three"}); assert::are_equal("{One, Three, Two}", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_tuple) { stringstream result; console::set_out(result); console::write(std::make_tuple("One", 2, 3.0)); assert::are_equal("(One, 2, 3)", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_unordered_map) { stringstream result; console::set_out(result); console::write(std::unordered_map<std::string, int> {{"One", 1}, {"Two", 2}, {"Three", 3}}); //result.str() can be equal to : "{(One, 1), (Two, 2), (Three, 3)}" or other sort depend of std::hash... string_assert::contains("(One, 1)", result.str(), csf_); string_assert::contains("(Two, 2)", result.str(), csf_); string_assert::contains("(Three, 3)", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_unordered_multimap) { stringstream result; console::set_out(result); console::write(std::unordered_multimap<std::string, int> {{"One", 1}, {"Two", 2}, {"Three", 3}}); //result.str() can be equal to : "{(One, 1), (Two, 2), (Three, 3)}" or other sort depend of std::hash... string_assert::contains("(One, 1)", result.str(), csf_); string_assert::contains("(Two, 2)", result.str(), csf_); string_assert::contains("(Three, 3)", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_unordered_multiset) { stringstream result; console::set_out(result); console::write(std::unordered_multiset<std::string> {"One", "Two", "Three"}); string_assert::contains("One", result.str(), csf_); string_assert::contains("Two", result.str(), csf_); string_assert::contains("Three", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_unordered_set) { stringstream result; console::set_out(result); console::write(std::unordered_set<std::string> {"One", "Two", "Three"}); string_assert::contains("One", result.str(), csf_); string_assert::contains("Two", result.str(), csf_); string_assert::contains("Three", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_valarray) { stringstream result; console::set_out(result); console::write(std::valarray<int> {1, 2, 3}); assert::are_equal("[1, 2, 3]", result.str(), csf_); console::set_out(console::open_standard_output()); } void test_method_(write_vector) { stringstream result; console::set_out(result); console::write(std::vector<int> {1, 2, 3}); assert::are_equal("[1, 2, 3]", result.str(), csf_); console::set_out(console::open_standard_output()); } }; }
true
e8156a85eb6cec27cc5624ea21463a207bee205d
C++
aametwally/MC_MicroSimilarities
/src/include/LUT.hpp
UTF-8
1,554
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // Created by asem on 04/12/18. // #ifndef MARKOVIAN_FEATURES_LUT_HPP #define MARKOVIAN_FEATURES_LUT_HPP #include "common.hpp" template<typename K, typename V> class LUT { static_assert( std::numeric_limits<K>::is_integer, "T must be of integer type." ); static constexpr auto LOWEST = std::numeric_limits<K>::lowest(); static constexpr auto MAX = std::numeric_limits<K>::max(); static constexpr size_t CAPACITY = MAX - LOWEST + 1; private: template<class T, size_t N> constexpr LUT( std::array<T, N> arr ) :_buffer( arr ) { } template<typename ArrFn> constexpr LUT( ArrFn fn ) :_buffer( fn()) { } public: LUT( const LUT & ) = default; inline const V &at( K key ) const { assert( key - LOWEST >= 0 ); return _buffer.at( key - LOWEST ); } inline V operator[]( K key ) const { assert( key - LOWEST >= 0 ); return _buffer[key - LOWEST]; } template<typename Function> static LUT<K, V> makeLUT( Function fn ) { std::array<V, CAPACITY> index{}; for (auto i = LOWEST; i < MAX; ++i) index.at( i - LOWEST ) = fn( i ); index.at( CAPACITY - 1 ) = fn( MAX ); return LUT( [&]() { return index; } ); } template<typename Fn> void inline forEach( Fn fn ) const { for (K i = LOWEST; i < MAX; ++i) fn( i, _buffer.at( i - LOWEST )); } private: const std::array<V, CAPACITY> _buffer; }; #endif //MARKOVIAN_FEATURES_LUT_HPP
true
9ec639bd7c80e1a223d085606a6011449c1a62cc
C++
janmarthedal/kanooth-numbers
/kanooth/numbers/generate_random_bits_number.hpp
UTF-8
1,794
2.875
3
[ "BSL-1.0" ]
permissive
#ifndef KANOOTH_NUMBERS_GENERATE_RANDOM_BITS_NUMBER_HPP #define KANOOTH_NUMBERS_GENERATE_RANDOM_BITS_NUMBER_HPP #include <kanooth/make_unsigned.hpp> #include <kanooth/numbers/integer_binary_logarithm.hpp> namespace kanooth { namespace numbers { namespace { template <typename T> typename make_unsigned<T>::type subtract_to_unsigned(T x, T y) { typedef typename make_unsigned<T>::type unsigned_type; if (y < 0) return unsigned_type(x) + unsigned_type(-(y+1)) + 1; return unsigned_type(x - y); } } template <typename T, typename Engine> T generate_random_bits_number(Engine& engine, unsigned width) { typedef typename Engine::result_type base_type; typedef typename make_unsigned<base_type>::type unsigned_base; unsigned_base range = subtract_to_unsigned(Engine::max(), Engine::min()); unsigned_base limit, value; unsigned base_bits; T result = T(); if (range == unsigned_base(-1)) { base_bits = std::numeric_limits<unsigned_base>::digits; limit = unsigned_base(-1); } else { base_bits = integer_binary_logarithm(range + 1); limit = (unsigned_base(1) << base_bits) - 1; } while (width >= base_bits) { do { value = subtract_to_unsigned(engine(), Engine::min()); } while (value > limit); result <<= base_bits; result |= value; width -= base_bits; } if (width) { do { value = subtract_to_unsigned(engine(), Engine::min()); } while (value > limit); result <<= width; result |= value & ((unsigned_base(1) << width) - 1); } return result; } } // namespace numbers } // namespace kanooth #endif // KANOOTH_NUMBERS_GENERATE_RANDOM_BITS_NUMBER_HPP
true
6164dc18c7a0ad9eccb848c14443533aaf806c79
C++
CalebMueller/Light_Stick_Firmware_3
/src/PowerManagement.cpp
UTF-8
2,175
3.21875
3
[]
no_license
#include "PowerManagement.h" #define LED_EN_PIN GPIO_NUM_14 #define MPU_EN_PIN GPIO_NUM_33 // PowerRail instantiations PowerRail led_rail(LED_EN_PIN, false); PowerRail mpu_rail(MPU_EN_PIN, false); ////////////////////////////////////////////// // FUNCTION DEFINITIONS void PowerRail::setup() { pinMode(_enPin, OUTPUT); if (Serial) { Serial.print(_enPin); Serial.print(" set to "); } this->enable(); } void PowerRail::enable() { // enables the power rail if (_activeLow) { digitalWrite(_enPin, HIGH); } else { digitalWrite(_enPin, LOW); } Serial.println("Enabling"); isEnabled = true; } void PowerRail::disable() { // disables the power rail if (_activeLow) { digitalWrite(_enPin, LOW); } else { digitalWrite(_enPin, HIGH); } Serial.println("Disabling"); isEnabled = false; } void PowerRail::toggle() { // changes enable/disable state to opposite of what it is currently if (isEnabled) { this->disable(); } else { this->enable(); } } void powerManagement_setup() { // Setup function calls relevant to powermanagement led_rail.setup(); mpu_rail.setup(); } // end of powerManagement_setup() ///////////////////////////////////////////////////// int get_battery_voltage() { // Returns an approximate current battery voltage, scaled by 1000 // IE 4.20V == 4200, 3.70V == 3700 // poll battery voltage for an average reading over n_times int battReading{0}; const byte n_times{30}; for (int i = 0; i < n_times; i++) { battReading = battReading + analogRead(BATT_CHARGE_ADC_PIN); } battReading = battReading / n_times; // equation is from experimentally derived linear relationship // between battReading and actual battVoltage return ((battReading + 230) * 1000) / 353; } // END OF poll_battery() ////////////////////////////////////////////////////// void check_for_low_battery() { // Puts device to sleep if voltage is below over-discharge threshold int battVoltage = get_battery_voltage(); if (battVoltage < 3180) { LED_showBatteryPercent(battVoltage); sleep(); } } // END OF check_battery() //////////////////////////////////////////////////////
true
f6858e11f21317e2060fc6b8f19c01fe1aaa6f38
C++
JensD1/Space_Invaders
/Main_Classes/main.cpp
UTF-8
523
2.671875
3
[]
no_license
#include <iostream> #include "../Abstract/AFactory.h" #include "../SDL/SdlFactory.h" #include "Game.h" /** * The main method. Here we will create an abstract factory that will actually contain an SDL factory. */ int main(int argc, char* args[]) { std::cout << "Begin" << std::endl; SI::AFactory* aFactory = new SDL_SI::SdlFactory(); SI::Game* game = SI::Game::createGameInstance(aFactory); game->run(); SI::Game::deleteGameInstance(); // game will delete afactory in it's destructor. return 0; }
true
d4cbfb2d7dd135b54a11605a86d033d06150f08a
C++
BehaviorTree/BehaviorTree.CPP
/tests/gtest_ports.cpp
UTF-8
8,289
2.8125
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include "behaviortree_cpp/bt_factory.h" using namespace BT; class NodeWithPorts : public SyncActionNode { public: NodeWithPorts(const std::string& name, const NodeConfig& config) : SyncActionNode(name, config) { std::cout << "ctor" << std::endl; } NodeStatus tick() override { int val_A = 0; int val_B = 0; if (getInput("in_port_A", val_A) && getInput("in_port_B", val_B) && val_A == 42 && val_B == 66) { return NodeStatus::SUCCESS; } return NodeStatus::FAILURE; } static PortsList providedPorts() { return {BT::InputPort<int>("in_port_A", 42, "magic_number"), BT::InputPort<int>("in_" "port" "_" "B")}; } }; TEST(PortTest, DefaultPorts) { std::string xml_txt = R"( <root BTCPP_format="4" > <BehaviorTree ID="MainTree"> <NodeWithPorts name = "first" in_port_B="66" /> </BehaviorTree> </root>)"; BehaviorTreeFactory factory; factory.registerNodeType<NodeWithPorts>("NodeWithPorts"); auto tree = factory.createTreeFromText(xml_txt); NodeStatus status = tree.tickWhileRunning(); ASSERT_EQ(status, NodeStatus::SUCCESS); } TEST(PortTest, Descriptions) { std::string xml_txt = R"( <root BTCPP_format="4" > <BehaviorTree ID="MainTree" _description="this is my tree" > <Sequence> <NodeWithPorts name="first" in_port_B="66" _description="this is my action" /> <SubTree ID="SubTree" name="second" _description="this is a subtree"/> </Sequence> </BehaviorTree> <BehaviorTree ID="SubTree" _description="this is a subtree" > <NodeWithPorts name="third" in_port_B="99" /> </BehaviorTree> </root>)"; BehaviorTreeFactory factory; factory.registerNodeType<NodeWithPorts>("NodeWithPorts"); factory.registerBehaviorTreeFromText(xml_txt); auto tree = factory.createTree("MainTree"); NodeStatus status = tree.tickWhileRunning(); while (status == NodeStatus::RUNNING) { status = tree.tickWhileRunning(); } ASSERT_EQ(status, NodeStatus::FAILURE); // failure because in_port_B="99" } struct MyType { std::string value; }; class NodeInPorts : public SyncActionNode { public: NodeInPorts(const std::string& name, const NodeConfig& config) : SyncActionNode(name, config) {} NodeStatus tick() override { int val_A = 0; MyType val_B; if (getInput("int_port", val_A) && getInput("any_port", val_B)) { return NodeStatus::SUCCESS; } return NodeStatus::FAILURE; } static PortsList providedPorts() { return {BT::InputPort<int>("int_port"), BT::InputPort<MyType>("any_port")}; } }; class NodeOutPorts : public SyncActionNode { public: NodeOutPorts(const std::string& name, const NodeConfig& config) : SyncActionNode(name, config) {} NodeStatus tick() override { return NodeStatus::SUCCESS; } static PortsList providedPorts() { return {BT::OutputPort<int>("int_port"), BT::OutputPort<MyType>("any_port")}; } }; TEST(PortTest, EmptyPort) { std::string xml_txt = R"( <root BTCPP_format="4" > <BehaviorTree ID="MainTree"> <Sequence> <NodeInPorts int_port="{ip}" any_port="{ap}" /> <NodeOutPorts int_port="{ip}" any_port="{ap}" /> </Sequence> </BehaviorTree> </root>)"; BehaviorTreeFactory factory; factory.registerNodeType<NodeOutPorts>("NodeOutPorts"); factory.registerNodeType<NodeInPorts>("NodeInPorts"); auto tree = factory.createTreeFromText(xml_txt); NodeStatus status = tree.tickWhileRunning(); // expect failure because port is not set yet ASSERT_EQ(status, NodeStatus::FAILURE); } class IllegalPorts : public SyncActionNode { public: IllegalPorts(const std::string& name, const NodeConfig& config) : SyncActionNode(name, config) {} NodeStatus tick() override { return NodeStatus::SUCCESS; } static PortsList providedPorts() { return {BT::InputPort<std::string>("name")}; } }; TEST(PortTest, IllegalPorts) { BehaviorTreeFactory factory; ASSERT_ANY_THROW(factory.registerNodeType<IllegalPorts>("nope")); } class ActionVectorIn : public SyncActionNode { public: ActionVectorIn(const std::string& name, const NodeConfig& config, std::vector<double>* states) : SyncActionNode(name, config), states_(states) {} NodeStatus tick() override { getInput("states", *states_); return NodeStatus::SUCCESS; } static PortsList providedPorts() { return {BT::InputPort<std::vector<double>>("states")}; } private: std::vector<double>* states_; }; TEST(PortTest, SubtreeStringInput_Issue489) { std::string xml_txt = R"( <root BTCPP_format="4" > <BehaviorTree ID="Main"> <SubTree ID="Subtree_A" states="3;7"/> </BehaviorTree> <BehaviorTree ID="Subtree_A"> <ActionVectorIn states="{states}"/> </BehaviorTree> </root>)"; std::vector<double> states; BehaviorTreeFactory factory; factory.registerNodeType<ActionVectorIn>("ActionVectorIn", &states); factory.registerBehaviorTreeFromText(xml_txt); auto tree = factory.createTree("Main"); NodeStatus status = tree.tickWhileRunning(); ASSERT_EQ(status, NodeStatus::SUCCESS); ASSERT_EQ(2, states.size()); ASSERT_EQ(3, states[0]); ASSERT_EQ(7, states[1]); } enum class Color { Red = 0, Blue = 1, Green = 2, Undefined }; class ActionEnum : public SyncActionNode { public: ActionEnum(const std::string& name, const NodeConfig& config) : SyncActionNode(name, config) {} NodeStatus tick() override { getInput("color", color); return NodeStatus::SUCCESS; } static PortsList providedPorts() { return {BT::InputPort<Color>("color")}; } Color color = Color::Undefined; }; TEST(PortTest, StrintToEnum) { std::string xml_txt = R"( <root BTCPP_format="4" > <BehaviorTree ID="Main"> <Sequence> <ActionEnum color="Blue"/> <ActionEnum color="2"/> </Sequence> </BehaviorTree> </root>)"; BehaviorTreeFactory factory; factory.registerNodeType<ActionEnum>("ActionEnum"); factory.registerScriptingEnums<Color>(); auto tree = factory.createTreeFromText(xml_txt); NodeStatus status = tree.tickWhileRunning(); ASSERT_EQ(status, NodeStatus::SUCCESS); auto first_node = dynamic_cast<ActionEnum*>(tree.subtrees.front()->nodes[1].get()); auto second_node = dynamic_cast<ActionEnum*>(tree.subtrees.front()->nodes[2].get()); ASSERT_EQ(Color::Blue, first_node->color); ASSERT_EQ(Color::Green, second_node->color); } class DefaultTestAction : public SyncActionNode { public: struct Point2D { int x; int y; }; DefaultTestAction(const std::string& name, const NodeConfig& config) : SyncActionNode(name, config) {} NodeStatus tick() override { const int answer = getInput<int>("answer").value(); if(answer != 42) { return NodeStatus::FAILURE; } const std::string greet = getInput<std::string>("greeting").value(); if(greet != "hello") { return NodeStatus::FAILURE; } const Point2D point = getInput<Point2D>("pos").value(); if(point.x != 1 || point.y != 2) { return NodeStatus::FAILURE; } return NodeStatus::SUCCESS; } static PortsList providedPorts() { return {BT::InputPort<int>("answer", 42, "the answer"), BT::InputPort<std::string>("greeting", "hello", "be polite"), BT::InputPort<Point2D>("pos", {1,2}, "where")}; } Color color = Color::Undefined; }; TEST(PortTest, DefaultInput) { std::string xml_txt = R"( <root BTCPP_format="4" > <BehaviorTree> <DefaultTestAction/> </BehaviorTree> </root>)"; BehaviorTreeFactory factory; factory.registerNodeType<DefaultTestAction>("DefaultTestAction"); auto tree = factory.createTreeFromText(xml_txt); auto status = tree.tickOnce(); ASSERT_EQ(status, NodeStatus::SUCCESS); }
true
ac681a9b09211c9071dd1a211e2a7bf2d3cc7a98
C++
SankalpMe/cs101project
/GameObjects/MO/MovingObject.cpp
UTF-8
1,560
2.65625
3
[]
no_license
#include <simplecpp> #include "MovingObject.h" void MovingObject::nextStep(double t) { // check if parented if (parent != nullptr) { // running parented mode updated i.e move acc. to parent child position = parent->getPosition() + parentOffset; velocity = parent->getVelocity(); acceleration = parent->getAcceleration(); // update individual sprite parts for (auto &part : parts) { Vector2D target = position + part.offset; part.sprite->moveTo(target.x, target.y); } return; } // if paused no step cycle if (paused) { return; } // compute the position and velocity acc. to laws of motion position = position + velocity * t; // update individual sprite parts for (auto &part : parts) { Vector2D target = position + part.offset; part.sprite->moveTo(target.x, target.y); } velocity = velocity + acceleration * t; // velocity update as per accel. } // End MovingObject::nextStep() void MovingObject::reset(const Vector2D &_position, const Vector2D &_velocity, const Vector2D &_acceleration, bool isPaused) { init(_position, _velocity, _acceleration, isPaused); for (auto &part : parts) { Vector2D target = position + part.offset; part.sprite->moveTo(target.x, target.y); } } // End MovingObject::reset() void MovingObject::getAttachedTo(MovingObject *m, Vector2D offset) { paused = m->isPaused(); parent = m; parentOffset = offset; }
true
40db7d2d3084a06ead344ac3a8934bdaeda83fab
C++
wwwwodddd/Zukunft
/luogu/P4281.cpp
UTF-8
1,392
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void read(int&x) { char ch; while((ch=getchar())&&(ch<'0'||ch>'9')); x=ch-'0'; while((ch=getchar())&&ch>='0'&&ch<='9') x=x*10+ch-'0'; } int n, m; int f[500020][20]; int d[500020]; struct Edge { int next; int to; } e[1000020]; int h[500020], tot; void add(int x, int y) { tot++; e[tot].next = h[x]; e[tot].to = y; h[x] = tot; } void dfs(int x, int y) { f[x][0] = y; d[x] = d[y] + 1; for (int i = 1; i < 20; i++) { f[x][i] = f[f[x][i - 1]][i - 1]; } for (int ii = h[x]; ii > 0; ii = e[ii].next) { int i = e[ii].to; if (i != y) { dfs(i, x); } } } int lca(int x, int y) { if (d[x] < d[y]) { swap(x, y); } int dd = d[x] - d[y]; for (int i = 0; i < 20; i++) { if (dd >> i & 1) { x = f[x][i]; } } if (x == y) { return x; } for (int i = 20 - 1; i >= 0; i--) { if (f[x][i] != f[y][i]) { x = f[x][i]; y = f[y][i]; } } return f[x][0]; } int main() { read(n); read(m); // scanf("%d%d", &n, &m); for (int i = 1; i < n; i++) { int x, y; read(x); read(y); // scanf("%d%d", &x, &y); add(x, y); add(y, x); } dfs(1, 0); for (int i = 0; i < m; i++) { int a, b, c; read(a); read(b); read(c); // scanf("%d%d%d", &a, &b, &c); int x = lca(a, b); int y = lca(b, c); int z = lca(c, a); printf("%d %d\n", x ^ y ^ z, d[a] + d[b] + d[c] - d[x] - d[y] - d[z]); } return 0; }
true
9bda566de96bac3b62f593ff65ecc281ca56dbe4
C++
IraShinking/CPP-Programming-Homework
/Lab4_3/Point.h
UTF-8
284
2.75
3
[]
no_license
//Point.h #ifndef _POINT_H_ #define _POINT_H_ class Point { public: Point(); Point(float xx, float yy); Point(Point &p); void setPoint(float xx, float yy); void showPoint(); float calculate_distance(Point p1); private: float x, y; }; #endif//_POINT_H_
true
2364ff658173b05f5a3034fa5da47950e27c5418
C++
junseublim/Algorithm-study
/baekjoon/1967.cpp
UTF-8
765
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> pii; vector<pii> edges[10001]; int visited[10001]; int furthest; int dist = -1; void dfs(int x, int d) { if (visited[x] != -1) return; visited[x] = 1; if (d > dist) { furthest = x; dist = d; } for (int i =0; i<edges[x].size(); i++) { dfs(edges[x][i].first, d + edges[x][i].second); } } int main() { int n; cin>>n; for (int i =0; i<n-1; i++) { int s,d,w; cin>>s>>d>>w; edges[s].push_back(make_pair(d,w)); edges[d].push_back(make_pair(s,w)); } memset(visited, -1, sizeof(visited)); dfs(1,0); dist = 0; memset(visited, -1, sizeof(visited)); dfs(furthest,0); cout<<dist<<endl; }
true
e1c16abd75e59ff47217333581f8e22ce3d235b8
C++
MoonPresident/PowerGrid
/src/games/opengl_examples/CameraExample.h
UTF-8
8,807
2.609375
3
[]
no_license
#ifndef CAMERAEXAMPLE_H #define CAMERAEXAMPLE_H #include "WorldData.h" bool exampleFirstMouse; float lastX = 400, lastY = 300; float yaw = -90.0f; float pitch = 0.f; float fov = 45.f; float deltaTime = 0.0f; // time between current frame and last frame float lastFrame = 0.0f; glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f); glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); void example_mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (exampleFirstMouse) { lastX = xpos; lastY = ypos; exampleFirstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; lastX = xpos; lastY = ypos; float sensitivity = 0.1f; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; if(pitch > 89.0f) pitch = 89.0f; if(pitch < -89.0f) pitch = -89.0f; glm::vec3 direction; direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); direction.y = sin(glm::radians(pitch)); direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); cameraFront = glm::normalize(direction); } class CameraExample : public WorldData { public: CameraExample() { #ifdef debug_all std::cout << "Camera example created." << std::endl; #endif glfwSetCursorPosCallback(window.getWindow(), example_mouse_callback); } void run() override { glm::vec3 cameraPos = glm::vec3(0.0f, 0.0f, 3.0f); glm::vec3 cameraTarget = glm::vec3(0.0f, 0.0f, 0.0f); glm::vec3 cameraDirection = glm::normalize(cameraPos - cameraTarget); glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f); glm::vec3 cameraRight = glm::normalize(glm::cross(up, cameraDirection)); glm::mat4 view; view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); GLuint vao, vbo, ebo; glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glGenBuffers(1, &ebo); float deltaTime = 0.0f; // Time between current frame and last frame float lastFrame = 0.0f; // Time of last frame glBindVertexArray(vao); glEnable(GL_DEPTH_TEST); static const GLfloat vertexData[] = { 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, // front top right 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, // front bottom right -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, // front bottom left -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, // front top left 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, // back top right 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, // back bottom right -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, // back bottom left -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, // back top left }; unsigned int indices[] = { 0, 1, 3, 1, 2, 3, 4, 5, 7, 5, 6, 7, 0, 4, 3, 4, 7, 3, 1, 5, 2, 5, 2, 6, 0, 4, 1, 4, 5, 1, 3, 7, 2, 7, 6, 2, }; glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) 0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) (3 * sizeof(float))); glEnableVertexAttribArray(1); ShaderStore shader; shader.addShader("C:\\dev\\PowerGrid\\resources\\shaders\\transform_3d_vertex_shader.txt", GL_VERTEX_SHADER); shader.addShader("C:\\dev\\PowerGrid\\resources\\shaders\\texture_2d_fragment_shader.txt", GL_FRAGMENT_SHADER); GLuint program = glCreateProgram(); shader.linkProgram(program); TextureFactory texFactory; GLuint tex = texFactory.getTexture(".\\resources\\textures\\stock_images\\fish_eyes.jpg"); glBindTexture(GL_TEXTURE_2D, tex); float x_off[2] = {0.f, -1.}; float y_off[2] = {0.f, -1.f}; int x_dir[2] = {0, 1}; int y_dir[2] = {1, 1}; //This captures the escape key. glfwSetInputMode(window.getWindow(), GLFW_STICKY_KEYS, GL_TRUE); while(glfwGetKey(window.getWindow(), GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window.getWindow()) == 0) { float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; float cameraSpeed = 2.5f * deltaTime; if (glfwGetKey(window.getWindow(), GLFW_KEY_W) == GLFW_PRESS) cameraPos += cameraSpeed * cameraFront; if (glfwGetKey(window.getWindow(), GLFW_KEY_S) == GLFW_PRESS) cameraPos -= cameraSpeed * cameraFront; if (glfwGetKey(window.getWindow(), GLFW_KEY_A) == GLFW_PRESS) cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; if (glfwGetKey(window.getWindow(), GLFW_KEY_D) == GLFW_PRESS) cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; glm::vec3 direction; direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); direction.y = sin(glm::radians(pitch)); direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); cameraFront = glm::normalize(direction); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //3D stuff. glm::mat4 proj = glm::perspective(glm::radians(45.0f), (float)width/(float)height, 0.1f, 100.0f); glm::mat4 model = glm::mat4(1.0f); glm::mat4 view = glm::mat4(1.0f); // note that we're translating the scene in the reverse direction of where we want to move view = glm::translate(view, glm::vec3(0.0f, 0.0f, -10.0f)); glBindTexture(GL_TEXTURE_2D, tex); glUseProgram(program); int modelLoc = glGetUniformLocation(program, "model"); int viewLoc = glGetUniformLocation(program, "view"); int projLoc = glGetUniformLocation(program, "projection"); // glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); // glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); // glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj)); for(int i = 0; i < 2; i++) { x_off[i] += 0.0001f * x_dir[i]; y_off[i] += 0.00007f * y_dir[i]; if(x_off[i] > 0.5f || x_off[i] < -0.5f) { x_dir[i] *= -1; } if(y_off[i] > 0.5f || y_off[i] < -0.5f) { y_dir[i] *= -1; } glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(x_off[i], y_off[i], -1.0f)); model = glm::rotate(model, (float) glfwGetTime() * glm::radians((i + 1) * 60.f), glm::vec3(0.5f, 1.f, 0.f)); model = glm::translate(model, glm::vec3(x_off[i], y_off[i], -1.0f)); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(proj)); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); } glfwSwapBuffers(window.getWindow()); glfwPollEvents(); } glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ebo); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return; } }; #endif // CAMERAEXAMPLE_HPP
true
c5406090d82a22846460218de918ca5b0bd7a8d0
C++
Tracy-Han/Cplusplus
/objLoaderSimple/primitives/shapeGenerator.cpp
UTF-8
4,478
2.984375
3
[]
no_license
#include "shapeGenerator.h" #include "vertex.h" #include <iostream> #define NUM_ARRAY_ELEMENTS(a) sizeof(a) / sizeof(*a) using glm::vec3; shapeData shapeGenerator::makeTriangles() { shapeData Triangle; Vertex triVerts[] = { glm::vec3(-1.0f, -1.0f, +0.0f), glm::vec3(+0.0f, +1.0f, +0.0f), glm::vec3(+0.0f, +0.0f, +1.0f), glm::vec3(+0.0f, +0.0f, +2.0f), glm::vec3(+1.0f, +1.0f, +0.5f), glm::vec3(+0.0f, +0.0f, +1.0f), glm::vec3(+1.0f, -1.0f, +0.0f), glm::vec3(+0.0f, +0.0f, +1.0f), glm::vec3(+0.0f, +0.0f, +1.0f), glm::vec3(+0.0f, +1.0f, +0.0f), glm::vec3(+1.0f, +0.0f, +0.0f), glm::vec3(+0.0f, +0.0f, +1.0f), }; Triangle.numVertices = NUM_ARRAY_ELEMENTS(triVerts); Triangle.vertices = new Vertex[Triangle.numVertices]; memcpy(Triangle.vertices,triVerts,sizeof(triVerts)); GLushort indices[] = { 0, 1, 3, 3, 1, 2,2, 3, 0,0, 2, 1 }; // GLushort indices[] = { 3, 0, 2,3, 1, 2 }; Triangle.numIndices = NUM_ARRAY_ELEMENTS(indices); Triangle.indices = new GLushort[Triangle.numIndices]; memcpy(Triangle.indices,indices,sizeof(indices)); return Triangle; } shapeData shapeGenerator::makeCube() { shapeData cube; Vertex cubeVerts[]= { vec3(-1.0f, +1.0f, +1.0f), // 0 vec3(+1.0f, +0.0f, +0.0f), // Color vec3(+0.0f, +1.0f, +0.0f), // Normal vec3(+1.0f, +1.0f, +1.0f), // 1 vec3(+0.0f, +1.0f, +0.0f), // Color vec3(+0.0f, +1.0f, +0.0f), // Normal vec3(+1.0f, +1.0f, -1.0f), // 2 vec3(+0.0f, +0.0f, +1.0f), // Color vec3(+0.0f, +1.0f, +0.0f), // Normal vec3(-1.0f, +1.0f, -1.0f), // 3 vec3(+1.0f, +1.0f, +1.0f), // Color vec3(+0.0f, +1.0f, +0.0f), // Normal vec3(-1.0f, +1.0f, -1.0f), // 4 vec3(+1.0f, +0.0f, +1.0f), // Color vec3(+0.0f, +0.0f, -1.0f), // Normal vec3(+1.0f, +1.0f, -1.0f), // 5 vec3(+0.0f, +0.5f, +0.2f), // Color vec3(+0.0f, +0.0f, -1.0f), // Normal vec3(+1.0f, -1.0f, -1.0f), // 6 vec3(+0.8f, +0.6f, +0.4f), // Color vec3(+0.0f, +0.0f, -1.0f), // Normal vec3(-1.0f, -1.0f, -1.0f), // 7 vec3(+0.3f, +1.0f, +0.5f), // Color vec3(+0.0f, +0.0f, -1.0f), // Normal vec3(+1.0f, +1.0f, -1.0f), // 8 vec3(+0.2f, +0.5f, +0.2f), // Color vec3(+1.0f, +0.0f, +0.0f), // Normal vec3(+1.0f, +1.0f, +1.0f), // 9 vec3(+0.9f, +0.3f, +0.7f), // Color vec3(+1.0f, +0.0f, +0.0f), // Normal vec3(+1.0f, -1.0f, +1.0f), // 10 vec3(+0.3f, +0.7f, +0.5f), // Color vec3(+1.0f, +0.0f, +0.0f), // Normal vec3(+1.0f, -1.0f, -1.0f), // 11 vec3(+0.5f, +0.7f, +0.5f), // Color vec3(+1.0f, +0.0f, +0.0f), // Normal vec3(-1.0f, +1.0f, +1.0f), // 12 vec3(+0.7f, +0.8f, +0.2f), // Color vec3(-1.0f, +0.0f, +0.0f), // Normal vec3(-1.0f, +1.0f, -1.0f), // 13 vec3(+0.5f, +0.7f, +0.3f), // Color vec3(-1.0f, +0.0f, +0.0f), // Normal vec3(-1.0f, -1.0f, -1.0f), // 14 vec3(+0.4f, +0.7f, +0.7f), // Color vec3(-1.0f, +0.0f, +0.0f), // Normal vec3(-1.0f, -1.0f, +1.0f), // 15 vec3(+0.2f, +0.5f, +1.0f), // Color vec3(-1.0f, +0.0f, +0.0f), // Normal vec3(+1.0f, +1.0f, +1.0f), // 16 vec3(+0.6f, +1.0f, +0.7f), // Color vec3(+0.0f, +0.0f, +1.0f), // Normal vec3(-1.0f, +1.0f, +1.0f), // 17 vec3(+0.6f, +0.4f, +0.8f), // Color vec3(+0.0f, +0.0f, +1.0f), // Normal vec3(-1.0f, -1.0f, +1.0f), // 18 vec3(+0.2f, +0.8f, +0.7f), // Color vec3(+0.0f, +0.0f, +1.0f), // Normal vec3(+1.0f, -1.0f, +1.0f), // 19 vec3(+0.2f, +0.7f, +1.0f), // Color vec3(+0.0f, +0.0f, +1.0f), // Normal vec3(+1.0f, -1.0f, -1.0f), // 20 vec3(+0.8f, +0.3f, +0.7f), // Color vec3(+0.0f, -1.0f, +0.0f), // Normal vec3(-1.0f, -1.0f, -1.0f), // 21 vec3(+0.8f, +0.9f, +0.5f), // Color vec3(+0.0f, -1.0f, +0.0f), // Normal vec3(-1.0f, -1.0f, +1.0f), // 22 vec3(+0.5f, +0.8f, +0.5f), // Color vec3(+0.0f, -1.0f, +0.0f), // Normal vec3(+1.0f, -1.0f, +1.0f), // 23 vec3(+0.9f, +1.0f, +0.2f), // Color vec3(+0.0f, -1.0f, +0.0f), // Normal }; cube.numVertices = NUM_ARRAY_ELEMENTS(cubeVerts); cube.vertices = new Vertex[cube.numVertices]; memcpy(cube.vertices,cubeVerts,sizeof(cubeVerts)); GLushort cubeIndices[] = { 0, 1, 2, 0, 2, 3, // Top 4, 5, 6, 4, 6, 7, // Front 8, 9, 10, 8, 10, 11, // Right 12, 13, 14, 12, 14, 15, // Left 16, 17, 18, 16, 18, 19, // Back 20, 22, 21, 20, 23, 22, // Bottom }; cube.numIndices = NUM_ARRAY_ELEMENTS(cubeIndices); cube.indices = new GLushort[cube.numIndices]; memcpy(cube.indices,cubeIndices,sizeof(cubeIndices)); return cube; }
true
f13440f492186a02d6421baf7a677bf1708887a8
C++
ja754969/Cplusplus-Programming
/上課檔案/課本範例檔/chapter 07_陣列/範例7-24.cpp
BIG5
424
3.359375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { string str; float digit; cout << "Jr:" ; cin >> str ; digit=atof(str.c_str()) ; //str.c_str() : NstringArꪫܼstr //ഫcharAr}C` cout << "\"" << str << '\"' << "eBIƭȬ" << digit << '\n' ; system("PAUSE"); return 0; }
true
20529cd2041f2e08cbdd82c52bdb6dcf0d7dc8a7
C++
vanpana/LMDB
/common/array.h
UTF-8
1,453
3.703125
4
[]
no_license
#ifndef ARRAY_H #define ARRAY_H #include <string> using namespace std; template <class T> class DynArr{ T* array; int capacity; int length; public: //default constructor DynArr(); //constructor with parameters DynArr(int cap); //copy constructor DynArr(const DynArr<T>& other); //assignment operator DynArr& operator=(const DynArr<T>& other); /* Function to get position of a given element. Input: name - string: name of the element. Output: pos - int: position in the array of the element. */ int getPosition(string name); /* Function to add an element to the array. If element already exists, it updates. Input: T - an element Output: a new list with added element */ void push(T obj); /* Function to delete an element in the array by name. Input: name - string: name of the element. Output: 1 if element successfully deleted, 0 if element does not exist */ int pop(string name); /* Function to return the array of the elements. Output: The list of elements of type T. */ T* getItems(); /* Function to return the length of the array Output: len - int: the length of the array */ int getLength(); DynArr<T>* operator+(const T v); /* Function to double the capacity of the array; */ void resize(); //destructor ~DynArr(); }; #endif
true
0646859ace2f08b2a240df5b8fbb31cec6b21f33
C++
m-krivov/MiCoSi
/Sources/Libs/Mitosis.API/Objects/ManagedChromosomePair.h
UTF-8
1,435
2.71875
3
[ "MIT" ]
permissive
#pragma once #include "Mitosis.Objects/ChromosomePair.h" #include "ManagedChromosome.h" #include "ManagedSpring.h" #include "IObjectWithID.h" #include "MappedObjects.h" namespace Mitosis { public ref class ChromosomePair : public IObjectWithID { private: ::ChromosomePair *_pair; Spring ^_spring; MappedObjects ^_objects; internal: ChromosomePair(::ChromosomePair *pair, MappedObjects ^objects) { _pair = pair; _objects = objects; _spring = pair->GetSpring() == NULL ? nullptr : gcnew Mitosis::Spring(pair->GetSpring()); } ::ChromosomePair *GetObject() { return _pair; } public: property System::UInt32 ID { virtual System::UInt32 get() { return _pair->ID(); } } virtual bool Equals(System::Object ^obj) override { ChromosomePair ^pair = dynamic_cast<ChromosomePair ^>(obj); return pair != nullptr && pair->GetObject() == GetObject(); } property Chromosome ^LeftChromosome { Chromosome ^get() { return _objects->GetChromosome(_pair->LeftChromosome()->ID()); } } property Chromosome ^RightChromosome { Chromosome ^get() { return _objects->GetChromosome(_pair->RightChromosome()->ID()); } } property Spring ^Spring { Mitosis::Spring ^get() { return _spring; } } }; }
true
debb3fd1421a74e8afb1d8d628c275eb0d38c3f4
C++
liiamarl/alphabetise
/static_exchange.cpp
UTF-8
7,837
2.53125
3
[]
no_license
#include "bit_function.hpp" #include <iostream> #include "structs.hpp" #include "chessboard.hpp" #include <array> #include <vector> #include <cmath> #include <algorithm> #include <bitset> //static exchange evaluation //first functions are used in the main one //checks if a sliding piece might capture the target square after another piece did threat chessboard::consider_x_ray(bitboard const target, bitboard const blocker){ if (blocker & N_attacks(target, bitboards[all])){ bitboard temp = N_attacks(blocker, bitboards[all]) & (bitboards[white + rook] |bitboards[black + rook] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & S_attacks(target, bitboards[all])){ bitboard temp = S_attacks(blocker, bitboards[all]) & (bitboards[white + rook] |bitboards[black + rook] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & E_attacks(target, bitboards[all])){ bitboard temp = E_attacks(blocker, bitboards[all]) & (bitboards[white + rook] |bitboards[black + rook] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & W_attacks(target, bitboards[all])){ bitboard temp = W_attacks(blocker, bitboards[all]) & (bitboards[white + rook] |bitboards[black + rook] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & SW_attacks(target, bitboards[all])){ bitboard temp = SW_attacks(blocker, bitboards[all]) & (bitboards[white + bishop] |bitboards[black + bishop] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & SE_attacks(target, bitboards[all])){ bitboard temp = SE_attacks(blocker, bitboards[all]) & (bitboards[white + bishop] |bitboards[black + bishop] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & NE_attacks(target, bitboards[all])){ bitboard temp = NE_attacks(blocker, bitboards[all]) & (bitboards[white + bishop] |bitboards[black + bishop] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } else if (blocker & NW_attacks(target, bitboards[all])){ bitboard temp = NW_attacks(blocker, bitboards[all]) & (bitboards[white + bishop] |bitboards[black + bishop] |bitboards[white + queen] |bitboards[black + queen]); if (temp){ threat th; th.bit = temp; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; return th; } } threat th; th.ind = -1; return th; } bool sort_threats_1(threat const& th1, threat const& th2){ return th1.ST_value < th2.ST_value;} bool sort_threats_2(threat const& th1, threat const& th2){ return th1.ST_value > th2.ST_value;} //returns a list of all pieces that attack or deffend a given square std::vector<threat> chessboard::get_attacks(int const ind, bool white_, bitboard const exept){ std::vector<threat> threats; bitboard bit = one << ind; bitboard temp = get_pawn_attack(bit, !white_) & bitboards[pawn + white_]; temp |= get_knight_attack(bit) & bitboards[knight + white_]; temp |= get_bishop_attack(bit) & (bitboards[bishop + white_] | bitboards[queen + white_]); temp |= get_rook_attack(bit) & (bitboards[rook + white_] | bitboards[queen + white_]); temp |= get_king_attack(bit) & bitboards[king + white_]; temp &= ~exept; while(temp){ threat th; th.ind = std::log2(temp); th.ST_value = ST_values[th.ind]; th.bit = one << th.ind; threats.push_back(th); temp ^= th.bit; } if(white_){ std::sort(threats.begin(), threats.end(), sort_threats_1); } else{ std::sort(threats.begin(), threats.end(), sort_threats_2); } return threats; }; int max_(int const& i1, int const& i2){ if (i1 > i2){ return i1;} return i2; } //actual static exchange evaluation, extended to quiet moves and promotions int chessboard::SEE(move m){ std::vector<threat> attack; threat th; th.ind = m.from; th.bit = m.from_b; th.ST_value = ST_values[m.from]; attack.push_back(th); std::vector<threat> at = get_attacks(m.to, true, m.from_b); attack.insert(attack.end(), at.begin(), at.end()); std::vector<threat> defense = get_attacks(m.to, false, 0); bitboard may_x_ray = bitboards[white + pawn] | bitboards[black + pawn] | bitboards[white + bishop] | bitboards[black + bishop] | bitboards[white + rook] | bitboards[black + rook] | bitboards[white + queen] | bitboards[black + queen]; if (defense.size() == 0){ if (m.type == promotion){ return 800;} if (m.type == promo_capture){ return 800 - ST_values[m.to];} return -ST_values[m.to]; } std::bitset<4> x_rays = 0; int d = 0; std::array<int, 20> gain = {-ST_values[m.to], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; if (m.type == promotion || m.type == promo_capture){ gain[0] += 8;} while (true){ d++; if ((d & 1) && defense.size() == 0){ break;} if (!(d & 1) && attack.size() == 0){ break;} if (d & 1){ gain[d] = gain[d - 1] - attack[0].ST_value; if (defense[0].bit & may_x_ray){ threat th = consider_x_ray(m.to_b, defense[0].bit); if (th.ind != -1){ if (bitboards[black] & th.bit){ defense.push_back(th); x_rays[2] = 1; } if (bitboards[white] & th.bit){ attack.push_back(th); x_rays[1] = 1; } } } if (d == 1){ if (attack[0].bit & may_x_ray){ threat th = consider_x_ray(m.to_b, attack[0].bit); if (th.ind != -1){ if (bitboards[black] & th.bit){ defense.push_back(th); x_rays[2] = 1; } if (bitboards[white] & th.bit){ attack.push_back(th); x_rays[1] = 1; } } } } attack.erase(attack.begin()); } else{ gain[d] = gain[d - 1] - defense[0].ST_value; if (attack[0].bit & may_x_ray){ threat th = consider_x_ray(m.to_b, attack[0].bit); if (th.ind != -1){ if (bitboards[black] & th.bit){ defense.push_back(th); x_rays[3] = 1; } if (bitboards[white] & th.bit){ attack.push_back(th); x_rays[0] = 1; } } } defense.erase(defense.begin()); } if (x_rays[1]){ x_rays[1] = 0; std::sort(attack.begin(), attack.end(), sort_threats_1); } if (x_rays[3]){ x_rays[3] = 0; std::sort(defense.begin(), defense.end(), sort_threats_2); } if (x_rays[0]){ x_rays[0] = false; x_rays[1] = true; } if (x_rays[2]){ x_rays[2] = false; x_rays[3] = true; } } for (int c = d - 1; c > 0; c--){ if (c % 2 == 1){ gain[c - 1] = std::min(gain[c], gain[c - 1]); } else{ gain[c - 1] = max_(gain[c], gain[c - 1]);} } return gain[0]; }
true
8629227dbc523556a4549999db5087de088fefec
C++
lmatsuki/LEM-Engine
/LEM Engine/src/DefaultImageOrder.h
UTF-8
253
2.59375
3
[]
no_license
#pragma once // Specify the z-order for when the image is rendered. // Made explicitly as old-style enum to keep the implicit conversion to int. namespace ImageOrder { enum DefaultImageOrder { Background, Static, Dynamic, GUI, Camera, }; }
true
77ab2865e27903bed166c6df790b1086eafac5d3
C++
masdelmon/openFrameworksApp13
/src/Enemy.h
UTF-8
670
2.703125
3
[]
no_license
#pragma once #ifndef _ENEMY // if this class hasn't been defined, the program can define it #define _ENEMY // by using this if statement you prevent the class to be called more than once which would confuse the compiler #include "ofMain.h" // we need to include this to have a reference to the openFrameworks framework class Enemy { public: ofPoint pos; ofImage * img; float speed; float amplitude; float width; float start_shoot; float shoot_interval; void setup(float max_enemy_amplitude, float max_enemy_shoot_interval, ofImage * enemy_image); void update(); void draw(); bool time_to_shoot(); }; #endif
true
163a984d65cb4568551c5fe214c29f844cf2d06d
C++
jteixeira00/EA-1
/Trabalho1.cpp
UTF-8
11,208
3.015625
3
[]
no_license
//g++ -std=c++17 -Wall -Wextra -O2 "Trabalho1.cpp" -lm #include <iostream> #include <unordered_map> #include <list> #include <algorithm> #include <vector> using namespace std; int min_moves; int maxSlides; void MergeCompress(vector<vector<int>>, int, int, vector<vector<int>>); void checkSolved(vector<vector<int>> &, int, int, vector<vector<int>> &, int, int); //Utilities void printMatrix(vector<vector<int>> matrix, int size) { cout << "\n"; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout << matrix[i][j] << " "; } cout << "\n"; } } //MOVEMENT FUNCTIONS //return com std::tuple para devolver (array, changeBool) void compressDown(vector<vector<int>> &matrix, int size, int &n) { vector<vector<int>> new_matrix(size, vector<int>(size)); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { new_matrix[j][i] = 0; } } for (int i = 0; i < size; i++) { int last_pos = size - 1; for (int j = size - 1; j >= 0; j--) { if (matrix[j][i] != 0) { new_matrix[last_pos][i] = matrix[j][i]; last_pos--; n++; } } } matrix = new_matrix; return; } void mergeDown(vector<vector<int>> &matrix, int size) { for (int i = 0; i < size; i++) { for (int j = size - 1; j > 0; j--) { if ((matrix[j][i] == matrix[j - 1][i]) && (matrix[j][i] != 0)) { matrix[j][i] = matrix[j][i] + matrix[j - 1][i]; matrix[j - 1][i] = 0; } } } return; } void compressUp(vector<vector<int>> &matrix, int size, int &n) { vector<vector<int>> new_matrix(size, vector<int>(size)); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { new_matrix[i][j] = 0; } } for (int i = 0; i < size; i++) { int last_pos = 0; for (int j = 0; j < size; j++) { if (matrix[j][i] != 0) { new_matrix[last_pos][i] = matrix[j][i]; last_pos++; n++; } } } matrix = new_matrix; return; } void mergeUp(vector<vector<int>> &matrix, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size - 1; j++) { if ((matrix[j][i] == matrix[j + 1][i]) && (matrix[j][i] != 0)) { matrix[j][i] = matrix[j + 1][i] + matrix[j][i]; matrix[j + 1][i] = 0; } } } return; } void compressRight(vector<vector<int>> &matrix, int size, int &n) { vector<vector<int>> new_matrix(size, vector<int>(size)); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { new_matrix[i][j] = 0; } } for (int i = 0; i < size; i++) { int last_pos = size - 1; for (int j = size - 1; j >= 0; j--) { if (matrix[i][j] != 0) { new_matrix[i][last_pos] = matrix[i][j]; last_pos--; n++; } } } matrix = new_matrix; return; } void mergeRight(vector<vector<int>> &matrix, int size) { for (int i = 0; i < size; i++) { for (int j = size - 1; j > 0; j--) { if ((matrix[i][j] == matrix[i][j - 1]) && (matrix[i][j] != 0)) { matrix[i][j] = matrix[i][j] + matrix[i][j - 1]; matrix[i][j - 1] = 0; } } } return; } void compressLeft(vector<vector<int>> &matrix, int size, int &n) { vector<vector<int>> new_matrix(size, vector<int>(size)); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { new_matrix[i][j] = 0; } } for (int i = 0; i < size; i++) { int last_pos = 0; for (int j = 0; j < size; j++) { if (matrix[i][j] != 0) { new_matrix[i][last_pos] = matrix[i][j]; last_pos++; n++; } } } matrix = new_matrix; return; } void mergeLeft(vector<vector<int>> &matrix, int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size - 1; j++) { if ((matrix[i][j] == matrix[i][j + 1]) && (matrix[i][j] != 0)) { matrix[i][j] = matrix[i][j] + matrix[i][j + 1]; matrix[i][j + 1] = 0; } } } return; } int possible(vector<vector<int>> &matrix, int size) { vector<int> matrix_flattened; vector<int> flat_old; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { matrix_flattened.push_back(matrix[i][j]); } } do { sort(matrix_flattened.begin(), matrix_flattened.end(), greater<int>()); flat_old = matrix_flattened; for (int i = 0; i < (size * size) - 1; i++) //merge { if ((matrix_flattened[i] == matrix_flattened[i + 1]) && (matrix_flattened[i] != 0)) { matrix_flattened[i] = matrix_flattened[i] * 2; matrix_flattened[i + 1] = 0; } } sort(matrix_flattened.begin(), matrix_flattened.end(), greater<int>()); //compress } while (matrix_flattened != flat_old); if ((matrix_flattened[1] == 0) && (matrix_flattened[0] != 0)) { return 1; } else { return 0; } } void MergeCompress(vector<vector<int>> matrix, int size, int n, vector<vector<int>> matrix_old, int last_move) { if (n++ >= min_moves) { return; } int n1 = 0; vector<vector<int>> matrix_og; matrix_og = matrix; switch (last_move) { case 1: //ultimo move vertical matrix = matrix_og; n1 = 0; compressRight(matrix, size, n1); mergeRight(matrix, size); n1 = 0; compressRight(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 2); } matrix = matrix_og; n1 = 0; compressLeft(matrix, size, n1); mergeLeft(matrix, size); n1 = 0; compressLeft(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 2); } matrix = matrix_og; n1 = 0; compressDown(matrix, size, n1); mergeDown(matrix, size); n1 = 0; compressDown(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 1); } matrix = matrix_og; n1 = 0; compressUp(matrix, size, n1); mergeUp(matrix, size); n1 = 0; compressUp(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 1); } break; case 2: //ultimo move horizontal matrix = matrix_og; n1 = 0; compressDown(matrix, size, n1); mergeDown(matrix, size); n1 = 0; compressDown(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 1); } matrix = matrix_og; n1 = 0; compressUp(matrix, size, n1); mergeUp(matrix, size); n1 = 0; compressUp(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 1); } matrix = matrix_og; n1 = 0; compressRight(matrix, size, n1); mergeRight(matrix, size); n1 = 0; compressRight(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 2); } matrix = matrix_og; n1 = 0; compressLeft(matrix, size, n1); mergeLeft(matrix, size); n1 = 0; compressLeft(matrix, size, n1); if ((matrix != matrix_og) && (matrix != matrix_old)) { checkSolved(matrix, size, n, matrix_og, n1, 1); } break; } } void checkSolved(vector<vector<int>> &matrix, int size, int n_moves, vector<vector<int>> &matrix_old, int n, int last_move) { //possivel otimizar -> verificar apenas as arestas da matriz //maybe verificar apenas a aresta onde encontra o primeiro valor? if (n == 1) { if (n_moves < min_moves) { min_moves = n_moves; return; } } else { MergeCompress(matrix, size, n_moves, matrix_old, last_move); return; } return; } int main() { // We probably do not need this but it is faster ios_base::sync_with_stdio(0); cin.tie(0); string order; int size; //int key; int max; int count = 0; int num; int x = 0; int y = 0; cin >> max; while (max != count) { cin >> size >> maxSlides; vector<vector<int>> matrix(size, vector<int>(size)); min_moves = maxSlides * 0.6 + 1; while (y != size) { cin >> num; matrix[y][x] = num; if (x != size - 1) { ++x; } else { ++y; x = 0; } } //cout << "is it possible:" << possible(matrix, size) << "\n"; vector<vector<int>> new_matrix(size, vector<int>(size)); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { new_matrix[j][i] = 0; } } if (!possible(matrix, size)) { cout << "no solution\n"; } else { MergeCompress(matrix, size, 0, new_matrix, 1); if (min_moves <= 0.6 * maxSlides) { cout << min_moves << "\n"; } else { min_moves = maxSlides * 0.8 + 1; MergeCompress(matrix, size, 0, new_matrix, 1); if (min_moves <= maxSlides * 0.8) { cout << min_moves << "\n"; } else { min_moves = maxSlides + 1; MergeCompress(matrix, size, 0, new_matrix, 1); if (min_moves <= maxSlides) { cout << min_moves << "\n"; } else { cout << "no solution\n"; } } } } x = y = 0; count++; } return 0; }
true
bb80b5a306624a0852c8347565bef9a7366eebf7
C++
jellyr/2dFluidSimulation
/2dFluidSimulation/util/ExtrapolateField.h
UTF-8
3,822
2.921875
3
[]
no_license
#pragma once #include <queue> #include "VectorGrid.h" /////////////////////////////////// // // ExtrapolateField.h/cpp // Ryan Goldade 2016 // // Extrapolates field from the boundary // of a mask outward based on a simple // BFS flood fill approach. Values // are averaged from FINISHED neighbours. // Note that because this process happens // "in order" there could be some bias // based on which boundary locations // are inserted into the queue first. // // //////////////////////////////////// template<typename Field> class ExtrapolateField { public: ExtrapolateField(Field& field) : m_field(field) {} void extrapolate(const Field& mask, size_t bandwidth = std::numeric_limits<size_t>::max()); private: Field& m_field; }; template<> void ExtrapolateField<VectorGrid<Real>>::extrapolate(const VectorGrid<Real>& mask, size_t bandwidth); template<typename Field> void ExtrapolateField<Field>::extrapolate(const Field& mask, size_t bandwidth) { // Run a BFS flood outwards from masked cells and average the values of the neighbouring "finished" cells // It could be made more accurate if we used the value of the "closer" cell (smaller SDF value) // It could be made more efficient if we truncated the BFS after a large enough distance (max SDF value) assert(m_field.size()[0] == mask.size()[0] && m_field.size()[1] == mask.size()[1]); UniformGrid<marked> marked_cells(m_field.size(), UNVISITED); typedef std::pair<Vec2st, size_t> Voxel; // Initialize flood fill queue std::queue<Voxel> marker_q; // If a face has fluid through it, the weight should be greater than zero // and so it should be marked for (size_t x = 0; x < m_field.size()[0]; ++x) for (size_t y = 0; y < m_field.size()[1]; ++y) { if (mask(x, y) > 0.) marked_cells(x, y) = FINISHED; } // Load up neighbouring faces and push into queue for (size_t x = 0; x < m_field.size()[0]; ++x) for (size_t y = 0; y < m_field.size()[1]; ++y) { if (marked_cells(x, y) == FINISHED) { for (size_t c = 0; c < 4; ++c) { Vec2i cidx = Vec2i(x, y) + cell_offset[c]; // Boundary check if (cidx[0] < 0 || cidx[1] < 0 || cidx[0] >= marked_cells.size()[0] || cidx[1] >= marked_cells.size()[1]) continue; if (marked_cells(cidx[0], cidx[1]) == UNVISITED) { marker_q.push(Voxel(Vec2st(cidx[0], cidx[1]), 1)); marked_cells(cidx[0], cidx[1]) = VISITED; } } } } while (!marker_q.empty()) { // Store reference to updated faces to set as finished after // this layer is completed std::queue<Voxel> temp_q = marker_q; // Store references to next layer of faces std::queue<Voxel> new_layer; while (!marker_q.empty()) { auto voxel = marker_q.front(); Vec2st idx = voxel.first; marker_q.pop(); assert(marked_cells(idx[0], idx[1]) == VISITED); Real val = 0.; Real count = 0.; if (voxel.second < bandwidth) { for (size_t c = 0; c < 4; ++c) { Vec2i cidx = Vec2i(idx) + cell_offset[c]; //Boundary check if (cidx[0] < 0 || cidx[1] < 0 || cidx[0] >= marked_cells.size()[0] || cidx[1] >= marked_cells.size()[1]) continue; if (marked_cells(cidx[0], cidx[1]) == FINISHED) { val += m_field(cidx[0], cidx[1]); ++count; } else if (marked_cells(cidx[0], cidx[1]) == UNVISITED) { new_layer.push(Voxel(Vec2st(cidx), voxel.second + 1)); marked_cells(cidx[0], cidx[1]) = VISITED; } } assert(count > 0); m_field(idx[0], idx[1]) = val / count; } } //Set update cells to finished while (!temp_q.empty()) { auto voxel = temp_q.front(); Vec2st idx = voxel.first; temp_q.pop(); assert(marked_cells(idx[0], idx[1]) == VISITED); marked_cells(idx[0], idx[1]) = FINISHED; } //Copy new queue marker_q = new_layer; } }
true
b2f0085649cf215a459d5cac5ff165b6e20ff00a
C++
asdacap/agvc
/arduino/machine/states.h
UTF-8
1,415
2.734375
3
[ "MIT" ]
permissive
#include "ConnectionManager.h" #include "debounce.h" #ifndef STATES #define STATES namespace States{ bool outOfCircuit = false; Debounce<String> outOfCircuitDebouncer(ConnectionManager::sendData, 10000); void sendOutOfCircuitStatus(){ if(outOfCircuit){ outOfCircuitDebouncer.call("outOfCircuit:1", 2); }else{ outOfCircuitDebouncer.call("outOfCircuit:0", 1); } } void setOutOfCircuit(){ outOfCircuit = true; sendOutOfCircuitStatus(); } void clearOutOfCircuit(){ outOfCircuit = false; sendOutOfCircuitStatus(); } bool obstructed = false; int OBSTACLE_SENSOR = 24; Debounce<String> obstructedDebouncer(ConnectionManager::sendData, 10000); void sendObstructedStatus(){ if(obstructed){ obstructedDebouncer.call("obstructed:1", 2); }else{ obstructedDebouncer.call("obstructed:0", 1); } } void setObstructed(){ obstructed = true; sendObstructedStatus(); } void clearObstructed(){ obstructed = false; sendObstructedStatus(); } void loopObstacleSensor(){ if(digitalRead(OBSTACLE_SENSOR) == LOW){ States::setObstructed(); }else if(obstructed){ States::clearObstructed(); } } void onConnect(){ sendOutOfCircuitStatus(); sendObstructedStatus(); } void loop(){ loopObstacleSensor(); } void setup(){ pinMode(OBSTACLE_SENSOR, INPUT); } } #endif
true
1ed489adbf9d24229d59e3afd00c11a337fc2a45
C++
Muff1nz/ParticleStorm
/ParticleStorm/EventEngine.cpp
UTF-8
2,878
2.671875
3
[]
no_license
#include "EventEngine.h" #include "Queue.h" Queue<double> EventEngine::scrollEvents{}; EventEngine::EventEngine(MessageSystem* messageQueue) { window = nullptr; this->messageQueue = messageQueue; } EventEngine::~EventEngine() = default; void EventEngine::Init(GLFWwindow* window) { this->window = window; glfwSetScrollCallback(window, ScrollCallback); } bool EventEngine::GetKeyDown(int key) { HookKeyIfNeeded(key); return keyStates[key] && !keyStatesGhost[key]; } bool EventEngine::GetKey(int key) { HookKeyIfNeeded(key); return keyStates[key]; } bool EventEngine::GetKeyUp(int key) { HookKeyIfNeeded(key); return !keyStates[key] && keyStatesGhost[key]; } bool EventEngine::GetMouseButtonDown(int mouseButton) { HookMouseButtonIfNeeded(mouseButton); return mouseButtonStates[mouseButton] && !mouseButtonStatesGhost[mouseButton]; } bool EventEngine::GetMouseButton(int mouseButton) { HookMouseButtonIfNeeded(mouseButton); return mouseButtonStates[mouseButton]; } bool EventEngine::GetMouseButtonUp(int mouseButton) { HookMouseButtonIfNeeded(mouseButton); return !mouseButtonStates[mouseButton] && mouseButtonStatesGhost[mouseButton]; } glm::vec2 EventEngine::GetMousePos() const { return mousePos; } int EventEngine::GetMouseScrollDelta() const { return mouseScrollDelta; } void EventEngine::Update() { glfwPollEvents(); if (glfwWindowShouldClose(window)) { messageQueue->PS_BroadcastMessage(Message(SYSTEM_EventEngine, MT_ShutDown)); return; } if (GetKeyDown(GLFW_KEY_ESCAPE)) messageQueue->PS_BroadcastMessage(Message(SYSTEM_EventEngine, MT_Shutdown_Session)); for (auto key : keyHooks) { keyStatesGhost[key] = keyStates[key]; keyStates[key] = glfwGetKey(window, key); } for (auto mouseButton : mouseButtonHooks) { mouseButtonStatesGhost[mouseButton] = mouseButtonStates[mouseButton]; mouseButtonStates[mouseButton] = glfwGetMouseButton(window, mouseButton); } mouseScrollDelta = 0; while (!scrollEvents.Empty()) { mouseScrollDelta += scrollEvents.Pop(); } double x, y; glfwGetCursorPos(window, &x, &y); mousePos = { x, y }; } void EventEngine::HookKeyIfNeeded(int key) { if (std::find(keyHooks.begin(), keyHooks.end(), key) != keyHooks.end()) return; keyHooks.emplace_back(key); auto state = glfwGetKey(window, key); keyStatesGhost.insert({ key, state }); keyStates.insert({ key, state }); } void EventEngine::HookMouseButtonIfNeeded(int mouseButton) { if (std::find(mouseButtonHooks.begin(), mouseButtonHooks.end(), mouseButton) != mouseButtonHooks.end()) return; mouseButtonHooks.emplace_back(mouseButton); auto state = glfwGetMouseButton(window, mouseButton); mouseButtonStatesGhost.insert({ mouseButton, state }); mouseButtonStates.insert({ mouseButton, state }); } void EventEngine::ScrollCallback(GLFWwindow* window, double xOffset, double yOffset) { scrollEvents.Push(yOffset); }
true
556d5361a78600f48a61f5839124422d153296e0
C++
jhstjh/StenGine
/StenGine/include/Graphics/Animation/Animator.h
UTF-8
2,164
2.75
3
[]
no_license
#pragma once #include <unordered_map> #include "Graphics/Animation/Animation.h" #include "Scene/Component.h" namespace StenGine { class Animation; class Animator : public Component { public: Animator(); virtual ~Animator(); inline void SetAnimation(Animation* anim) { mAnimation = anim; } const Mat4 GetTransform(std::string str) const; void CreateClip(float startFrame, float endFrame, const std::string &name); bool HasCurrentClip() { return mBledingClips.size() != 0; } void SetCurrentClip(const std::string &name, float blendTime = 0.f); void SetPositionDrivenNodeName(const std::string &name) { mPositionDrivenNodeName = name; } void SetPlaySpeed(float speed) { mPlaySpeed = speed; } void DrawMenu() override; private: using TransformTSQMap = std::unordered_map<std::string, TSQ>; struct AnimationClip { float startFrame; float endFrame; std::string name; }; void UpdateClip(const AnimationClip* clip, Timer::Seconds &playbackTime, TransformTSQMap &transformMtxMap, Vec3 &prevDrivenNodePos, bool &validDriven, Vec3 &drivenNodePosDiff); void UpdateAnimation(); struct BlendingClip { AnimationClip* clip; Timer::Seconds playbackTime; Timer::Seconds totalBlendTime; Vec3 posDrivenNodePos; bool validDriven; Vec3 posDiff; Timer::Seconds currBlendTime; TransformTSQMap transformTSQ; BlendingClip( AnimationClip* _clip, Timer::Seconds _playbackTime, Timer::Seconds _totalBlendTime, Vec3 _posDrivenNodePos, bool _validDriven ) : clip(_clip) , playbackTime(_playbackTime) , totalBlendTime(_totalBlendTime) , posDrivenNodePos(_posDrivenNodePos) , validDriven(_validDriven) , currBlendTime(0.f) , posDiff(0.f, 0.f, 0.f) { printf("New Clip Added: %s\n", clip->name.c_str()); } ~BlendingClip() { printf("Clip Removed: %s\n", clip->name.c_str()); } }; Animation* mAnimation{ nullptr }; bool mPlay{ true }; std::unordered_map<std::string, AnimationClip*> mAnimationClips; std::deque<BlendingClip> mBledingClips; std::string mPositionDrivenNodeName; bool mValidDriven{ false }; float mPlaySpeed{ 1.0f }; }; }
true
0da595e876ee760314dc365b9abc0be942cb9084
C++
palestar/medusa
/File/File.h
UTF-8
2,322
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* File.h File Abstract class Concrete versions: FileDisk and FileMemory (c)2005 Palestar, Richard Lyle */ #ifndef FILE_H #define FILE_H #include "Standard/Types.h" #include "Standard/Exception.h" #include "Standard/Reference.h" #include "MedusaDll.h" //------------------------------------------------------------------------------- class DLL File : public Referenced { public: // Exceptions DECLARE_EXCEPTION( FileError ); // Types typedef Reference< File > Ref; typedef dword Position; typedef Position Size; // Construction File(); virtual ~File(); // Accessors virtual File * clone() const = 0; // clone this file, will never return NULL, will return a this pointer if file isn't cloneable virtual bool isReadable() const = 0; // can bytes be read from this file virtual bool isWritable() const = 0; // is this file writable, false if not.. virtual Position position() const = 0; // current file read/write position virtual Size size() const = 0; // size of the file in bytes // Mutators virtual Size read( void * pBuffer, Size nBytes ) = 0; virtual Size write( const void * pBuffer, Size nBytes ) = 0; virtual void flush() = 0; virtual void insert( const void * pBuffer, Size nBytes ); virtual void append( const void * pBuffer, Size nBytes ); virtual void remove( Size nBytes ); virtual Position setPosition( Position nPos ) = 0; virtual Size setSize( Size nSize ) = 0; virtual Size setEOF() = 0; virtual void lock() = 0; // write lock interface virtual void unlock() = 0; // Helpers Position rewind( int nBytes = -1 ); Position skip( int nBytes = 1 ); void end(); }; //---------------------------------------------------------------------------- inline File::Position File::rewind( int nBytes /*= -1*/ ) { if ( nBytes < 0 ) return setPosition(0); return setPosition( position() - nBytes ); } inline File::Position File::skip( int nBytes /*= 1*/ ) { return setPosition( position() + nBytes ); } inline void File::end() { setPosition( size() ); } //---------------------------------------------------------------------------- #endif //-------------------------------------------------------------------------- // EOF
true
a542fefe1ec76ad9c36a28f3d6ff80fd18ab346f
C++
m0nkeykong/PersonalProjects
/SuperMarket/ICommand.h
UTF-8
2,100
3.03125
3
[]
no_license
#ifndef ICOMMAND_H #define ICOMMAND_H #include <string> #include <fstream> #include <iostream> #include "Database.h" using namespace std; class ICommand //this is the command center { public: virtual bool execute() = 0; }; class ShowAvaillItems : public ICommand //shows all available items in the warehouse { private: Database* db; public: ShowAvaillItems(Database* _db) : db(_db) {}; bool execute(); }; class AddItemCommand : public ICommand //command to add item to a specific cart { private: int itemID; int quantity; Cart* cartToAddTo; Database* db; public: AddItemCommand(Database* db, int _itemID, int _quantity, Cart& _cart) : itemID(_itemID), quantity(_quantity), cartToAddTo(_cart), db(_db) {}; int getItemID() { return itemID; }; int getQuantity() { return quantity; }; bool execute(); }; class RemoveItemCommand : public ICommand //command to remove item from a specific cart { private: int itemID; Cart* cartToRemoveFrom; public: RemoveItemCommand(int _itemID, Cart* _cart) : itemID(_itemID), cartToRemoveFrom(_cart) {}; int getItemID() { return itemID; }; bool execute(); }; class ShowCartCommand : public ICommand //command that shows the consumer what items are in his cart { private: Cart* curCart; public: ShowCartCommand(Cart* _cart) : curCart(_cart) {}; bool execute(); }; class FinalizeOrderCommand : public ICommand //command that gets the customer the the cashiering section { private: Cart* cartToPurchase; Database* db; public: FinalizeOrderCommand(Cart& _cart, Database* _db) : cartToPurchase(&_cart), db(_db) {}; bool execute(); }; class ShowSalesCommand : public ICommand //command that shows the user all the purchases that has been commited { private: Database* db; public: ShowSalesCommand(Database* _db) : db(_db) {}; bool execute(); }; class QuitCommand : public ICommand //command that shuts down the system { bool execute(); }; #endif
true
39a5382b38bf3475a85a67b224fb5631b27b705f
C++
hirasaha-backcountry/Codes
/Min Sum Path in Matrix.cpp
UTF-8
1,392
3.734375
4
[]
no_license
/* Problem Description : https://www.interviewbit.com/problems/min-sum-path-in-matrix/ ------------------------------------------------------------------------------------------------------- Given a 2D integer array A of size M x N, you need to find a path from top left to bottom right which minimizes the sum of all numbers along its path. NOTE: You can only move either down or right at any point in time. Input Format First and only argument is an 2D integer array A of size M x N. Output Format Return a single integer denoting the minimum sum of a path from cell (1, 1) to cell (M, N). Example Input Input 1: A = [ [1, 3, 2] [4, 3, 1] [5, 6, 1] ] Example Output Output 1: 9 Example Explanation Explanation 1: The path is 1 -> 3 -> 2 -> 1 -> 1 So ( 1 + 3 + 2 + 1 + 1) = 8 */ //Code: //------------------------------------------------------------------------------------------------ int Solution::minPathSum(vector<vector<int> > &cost) { int row = cost.size(); int col = cost[0].size(); for (int i=1 ; i<row ; i++){ cost[i][0] += cost[i-1][0]; } for (int j=1 ; j<col ; j++){ cost[0][j] += cost[0][j-1]; } for (int i=1 ; i<row ; i++) { for (int j=1 ; j<col ; j++) { cost[i][j] += min(cost[i-1][j], cost[i][j-1]); } } return cost[row-1][col-1]; }
true
1d4a9daf8dd31aba71d2e0e38bceeeb7946923ad
C++
Malonyz/lab3
/lab3_1.cpp
UTF-8
206
2.578125
3
[]
no_license
#include<iostream> using namespace std; int main() { int x=2,y; cout << "Enter y"; cin >> y; while(x<50){ cout << x << endl; x=x+y; } cout <<"Malony"; return 0; }
true
02b6cc6902a349a6ec57d8257aa76ccdea7d74b1
C++
VegetableArt/papaya2
/python/python.hpp
UTF-8
2,193
2.8125
3
[ "BSL-1.0" ]
permissive
#pragma once #include <Python.h> #include <memory> #include <string> namespace papaya2 { namespace python { struct RefDeccer { void operator()(PyObject *ref) { Py_XDECREF(ref); } }; struct UniquePyPtr : std::unique_ptr<PyObject, RefDeccer> { using base_t = std::unique_ptr<PyObject, RefDeccer>; using base_t::base_t; template <typename TYPE> TYPE *reinterpret() const { return reinterpret_cast<TYPE *>(get()); } }; inline string to_utf8_string(PyObject *unicode) { #ifdef PYTHON_3 if(!PyUnicode_Check(unicode)) throw std::logic_error("non-PyUnicode passed into to_utf8_string"); Py_ssize_t size; char const *buf = PyUnicode_AsUTF8AndSize(unicode, &size); return string(buf, buf + size); #else if(!PyBytes_Check(unicode)) throw std::logic_error("non-PyBytes passed into to_utf8_string"); return PyBytes_AS_STRING(unicode); #endif } struct KwargsIterator { using value_type = std::pair<string, PyObject *>; KwargsIterator &operator++() { PyObject *key = 0; if(PyDict_Next(dict_, &pos_, &key, &key_and_value_.second)) { key_and_value_.first = to_utf8_string(key); } else { pos_ = 0; // end } return *this; } value_type const &operator*() const { return key_and_value_; } friend bool operator==(KwargsIterator const &lhs, KwargsIterator const &rhs) { return lhs.pos_ == rhs.pos_; } friend bool operator!=(KwargsIterator const &lhs, KwargsIterator const &rhs) { return lhs.pos_ != rhs.pos_; } KwargsIterator(PyObject *dict) : dict_(dict), pos_(0), key_and_value_("", nullptr) { } PyObject *dict_; Py_ssize_t pos_; value_type key_and_value_; private: KwargsIterator(); }; struct Kwargs { Kwargs(PyObject *dict) : dict_(dict) { } KwargsIterator begin() const { auto iter = KwargsIterator(dict_); ++iter; return iter; } KwargsIterator end() const { return KwargsIterator(dict_); } PyObject *dict_; }; } // namespace python } // namespace papaya2
true
3dbddcea6236bdde9ae287e6858305e6e8e4d457
C++
fawkesrobotics/fawkes
/src/libs/fvmodels/shape/circle.cpp
UTF-8
3,776
2.578125
3
[]
no_license
/*************************************************************************** * circle.cpp - Implementation of a circle shape finder * * Created: Thu May 16 00:00:00 2005 * Copyright 2005 Tim Niemueller [www.niemueller.de] * Hu Yuxiao <Yuxiao.Hu@rwth-aachen.de> * ****************************************************************************/ /* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. A runtime exception applies to * this software (see LICENSE.GPL_WRE file mentioned below for details). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * Read the full text in the LICENSE.GPL_WRE file in the doc directory. */ #include <fvmodels/shape/circle.h> #include <cmath> using namespace std; using namespace fawkes; namespace firevision { /** @class Circle <fvmodels/shape/circle.h> * Circle shape. */ /** Constructor. */ Circle::Circle() { center.x = center.y = 0.0f; radius = -1.0f; count = 0; } /** Constructor. * @param c center * @param r radius * @param n number of pixels */ Circle::Circle(const center_in_roi_t &c, float r, int n) { center = c; radius = r; count = n; } /** Print info. * @param stream stream to print to */ void Circle::printToStream(std::ostream &stream) { stream << "center=(" << center.x << "," << center.y << ")" << " radius=" << radius << " count= " << count; } /** Fit circle. * Fit a circle through the given points. * @param points points to fit circle through. */ void Circle::fitCircle(vector<upoint_t> &points) { // due to fixed width, do not use arrays to save addressing time... double A00 = 0.0, A01 = 0.0, A02 = 0.0; double A10 = 0.0, A11 = 0.0, A12 = 0.0; double A20 = 0.0, A21 = 0.0, A22 = 0.0; double b0 = 0.0, b1 = 0.0, b2 = 0.0; // generating A'A and A'b int count = points.size(); for (int i = 0; i < count; i++) { upoint_t &t = points[i]; double x0 = 2.0f * t.x; double y0 = 2.0f * t.y; double b = (double)(t.x * t.x + t.y * t.y); A00 += x0 * x0; A01 += x0 * y0; A02 += x0; A10 += y0 * x0; A11 += y0 * y0; A12 += y0; A20 += x0; A21 += y0; A22 += 1.0; b0 += x0 * b; b1 += y0 * b; b2 += b; } // solve the resulting 3 by 3 equations double delta = +A00 * A11 * A22 + A01 * A12 * A20 + A02 * A10 * A21 - A00 * A12 * A21 - A01 * A10 * A22 - A02 * A11 * A20; center.x = (float)((+b0 * A11 * A22 + A01 * A12 * b2 + A02 * b1 * A21 - b0 * A12 * A21 - A01 * b1 * A22 - A02 * A11 * b2) / delta); center.y = (float)((+A00 * b1 * A22 + b0 * A12 * A20 + A02 * A10 * b2 - A00 * A12 * b2 - b0 * A10 * A22 - A02 * b1 * A20) / delta); radius = (float)sqrtf((+A00 * A11 * b2 + A01 * b1 * A20 + b0 * A10 * A21 - A00 * b1 * A21 - A01 * A10 * b2 - b0 * A11 * A20) / delta + (double)center.x * center.x + (double)center.y * center.y); count = points.size(); } void Circle::setMargin(unsigned int margin) { this->margin = margin; } bool Circle::isClose(unsigned int in_roi_x, unsigned int in_roi_y) { float dx = in_roi_x - center.x; float dy = in_roi_y - center.y; float dist = sqrt(dx * dx + dy * dy); return ((dist <= (radius + margin)) && (dist >= (radius - margin))); } } // end namespace firevision
true
e04a4e02417cd62373245423eb3472efdec37d4c
C++
Chunchunhao/2014_FALL_OOP
/hw1/HW1_dist/1-2-v1.cpp
UTF-8
1,377
2.84375
3
[]
no_license
#include <iostream> #include <fstream> #include "Sales_item.h" #include <vector> #ifdef _WIN32 || WIN32 || defined(_WIN32) || defined(WIN32) #define OS_Windows #include <process.h> // http://msdn.microsoft.com/en-us/library/1kxct8h0.aspx #else #include <unistd.h> #endif using namespace std; int main () { // char filename[] = "book_sales"; string filename; cout << "Enter the file name: " ; cin >> filename; fstream fp; fp.open(filename); if( !fp) { cerr << "Complain: I cannot find the file" << endl; #ifdef OS_Windows /* Windows code */ _execlp( "dir", "dir" ); #else /* GNU/Linux code */ execlp( "ls", "ls", "-l"); #endif return -1; } Sales_item in; vector<Sales_item> itemList; while( fp >> in ) { // if input is not format corret then leave the program if( itemList.size() > 0 ){ for( int i=0; i<=itemList.size(); i++) { if( i == itemList.size() ) { itemList.push_back(in); break; } else { if( compareIsbn(in, itemList[i]) ){ itemList[i] += in; break; } } // check whether the books in our list } } else { itemList.push_back(in); } } fp.close(); for( int i=0; i<itemList.size(); i++) { cout << itemList[i] << endl; } return EXIT_SUCCESS; }
true
6e3665afea33194810e2120c0b08b041c1d3b63d
C++
green-fox-academy/marsaltamas
/week-06/TaDaaAppSandbox/fileio.cpp
UTF-8
1,448
3.125
3
[]
no_license
#include "fileio.h" void FileIO::write_to_file(vector<Task> *task_vector_pointer) { this->task_vector_pointer = task_vector_pointer; ofstream out_file; string file_path = "fileToRead.txt"; out_file.open(file_path, ios::out | ios::trunc); for (unsigned int i = 0; i < task_vector_pointer->size(); ++i) { out_file << task_vector_pointer->at(i).get_description() << endl; out_file << task_vector_pointer->at(i).get_checked_display() << endl; out_file << task_vector_pointer->at(i).get_priority() << endl; } out_file.close(); } void FileIO::read_from_file(vector<Task> *task_vector_pointer) { this->task_vector_pointer = task_vector_pointer; ifstream in_file; string file_path = "fileToRead.txt"; string buffer; int priority; in_file.open(file_path, ios::in); for (unsigned int i = 0; i < task_vector_pointer->size(); ++i) { getline(in_file, buffer); cout << "buffer at " << i << " " << buffer << endl; task_vector_pointer->at(i).set_description(buffer); getline(in_file, buffer); cout << "buffer at " << i << " " << buffer << endl; task_vector_pointer->at(i).set_checked_display(buffer); getline(in_file, buffer); cout << "buffer at " << i << " " << buffer << endl; istringstream(buffer) >> priority; task_vector_pointer->at(i).set_priority(priority); } in_file.close(); }
true
642bdcee1dec4d6ac0000fd604c49ab2607f4c83
C++
agudeloandres/C_Struct_Files
/C_Tutorships/data_structures_Cplusplus/GRAFOS/P587.CPP
UTF-8
2,411
2.78125
3
[]
no_license
#include "stdio.h" #include "conio.h" #include "stdlib.h" #include "alloc.h" #define MAXIMO 20 #define PR(x) printf ("%s",x) #define SALTO printf ("\n") void main() { int M[MAXIMO][MAXIMO],T[MAXIMO][MAXIMO]; int suma, marcas[MAXIMO],padres[MAXIMO],minimo [MAXIMO]; int nv,i; void DIJKSTRA (int M[][MAXIMO],int N,int minimo[], int padres[],int marcas[]); void listar_r (int a[],int nv); int lea_grafo (int grafo[][MAXIMO]); void listar_g (int g[][MAXIMO], int nv); nv = lea_grafo (M); listar_g (M ,nv); SALTO; getch(); DIJKSTRA (M,nv,minimo,padres,marcas); listar_r (minimo,nv); SALTO; listar_r (padres,nv); SALTO; listar_r (marcas,nv); SALTO; getch(); } void DIJKSTRA (int M[][MAXIMO],int N,int minimo[], int padres[],int marcas[]) { int min; int j,k,escogido; for (j=1; j<=N; j++ ) { minimo[j] = M[1][j]; marcas [j] = 0; padres [j] = 1; } minimo [1] = 0; padres [1]= 0; marcas [1] = 1; for (k = 2; k <= N; k++) { min = 32000; /* No puede ser 32767 para maquinas de 16 bits para cada entero. ?Porque? */ for (j=1; j <= N; j++) if (marcas [j] == 0 && minimo [j] < min) { min = minimo [j]; escogido = j; } marcas [escogido] = 1; for (j=1; j <= N; j++) if (marcas [j] == 0 && (min + M[escogido][j] < minimo[j]) ) { minimo [j] = min + M[escogido][j]; padres [j] = escogido; } } } int lea_grafo (int grafo[][MAXIMO]) { int lea(),v,ad,i,j,n,costo; PR("De numero de vertices..."); SALTO; n = lea(); for (i=1; i <= n; i++) for (j=1; j <=n; j++) grafo[i][j] = 32000; PR ("Vertice ... "); v = 1; printf ("%d",v); SALTO; while (v <= n) { PR ("Lea el primer adjunto al vertice "); printf ("%d ",v); PR(". 99 para terminar"); SALTO; ad = lea(); while (ad != 99) { PR("Lea costo del arco");SALTO; costo = lea(); grafo [v][ad] = costo; PR ("Lea otro adjunto al vertice "); printf ("%d ",v); PR(". 99 para terminar"); SALTO; ad = lea(); } PR ("Vertice ..."); v++; printf ("%d ",v); SALTO; } return (n); } int lea() { char L[10]; gets (L); return (atoi (L)); } void listar_g (int g[][MAXIMO], int nv) { int i,j; for (i=1; i <= nv; i++) { for (j = 1; j <= nv; j++) if (g[i][j] == 32000) printf ("%s"," * "); else printf ("%2d ",g[i][j]); SALTO; } } void listar_r (int a[],int nv) { int k; for (k=1; k<=nv; k++) printf ("%d ",a[k]); } 
true
34c25f9626b3b5d43242130fb2fd936c91145a66
C++
syawalrdn/STRUKTUR-DATA
/Laporan (2)/laporan2.2 (bil.ganjil).cpp
UTF-8
248
2.78125
3
[]
no_license
#include <iostream> using namespace std; main() { int a,b; cout<<"PROGRAM CETAK DERET BILANGAN GANJIL"; cout<<"\nMasukkan Batas Bilangan = "; cin>>b; cout<<"\nBilangan Genap = "; for(a=1;a<=b;a++) if (a%2==1) cout<<a<<" "; }
true
6ccea51e40611df43a15f83e3355806c654f1369
C++
guithin/BOJ
/9663/Main.cpp
UTF-8
852
2.59375
3
[]
no_license
#include<stdio.h> int dx[8] = { 0,0,-1,1,1,-1, 1, -1 }; int dy[8] = { 1,-1,0,0,1,-1, -1, 1 }; int map[30][30] = { 0 }; long long cnt = 0; void dfs(int n, int idx) { if (idx == n + 1) { cnt++; // printf("%d\n", cnt); return; } for (int i = 1; i <= n; i++) { if (map[idx][i] <0)continue; map[idx][i] = 1; for (int j = 0; j < 8; j++) { for (int k = 1; idx + dx[j] * k <= n && idx + dx[j] * k >= 1 && i + dy[j] * k >= 1 && i + dy[j] * k <= n; k++) { map[idx + dx[j] * k][i + dy[j] * k] --; } } dfs(n, idx + 1); map[idx][i] = 0; for (int j = 0; j < 8; j++) { for (int k = 1; idx + dx[j] * k <= n && idx + dx[j] * k >= 1 && i + dy[j] * k >= 1 && i + dy[j] * k <= n; k++) { map[idx + dx[j] * k][i + dy[j] * k] ++; } } } } int main() { int n; scanf("%d", &n); dfs(n, 1); printf("%lld\n", cnt); return 0; }
true
66ebf1ecf1ee5256f397e346c3a2146dc2493522
C++
andr-ec/realEstate
/Real Estate/Farm.cpp
UTF-8
1,259
3
3
[]
no_license
// // Farm.cpp // Real Estate // // Created by Apple Mac on 12/8/15. // Copyright © 2015 Andre Carrera. All rights reserved. // #include "Farm.h" using namespace std; Farm::Farm( bool rentalIn, double priceIn, int daysIn, string addressIn) :Property( rentalIn, priceIn, daysIn, addressIn) { rate = 0.4;//sets rate equal to 40% for farms } string Farm::toString() { string rentalstr; if (rental ==true) { rentalstr = "Rental"; } else if (rental==false){ rentalstr = "NOT Rental"; } stringstream st; st << "Property id: "<< id << " Address: " << address << " " << rentalstr << " Estimated value: " << price << " Days Since Last Payment: " << days << " Discounted Discount " << rate << " NOTE: Farm property"; st << endl; return st.str(); } double Farm::toTaxes() { double taxTotal = 0; double discountRate = 1 - rate; if (rental == true) { taxRate = .012; } else if (rental ==false) { taxRate = .01; } taxRate = taxRate*discountRate; taxTotal = price*taxRate; return taxTotal; } int Farm::toDeadline() { daysDue = 100;//due in 100 days, one season. return daysDue; }
true
2452fe3404550c92555bf906de07540a73b1dc5a
C++
ArutoriaWhite/Competitive-programming
/cf1257b.cpp
UTF-8
347
2.578125
3
[]
no_license
#include<iostream> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while(T--) { int x, y; cin >> x >> y; if (x>=4) cout << "Yes\n"; else if ((x==2||x==3)&&(y<4)) cout << "Yes\n"; else if (x==y) cout << "Yes\n"; else cout << "No\n"; } return 0; }
true
be23520926bb787d510f58edb62b11fa8a4dc58a
C++
miroslavradojevic/bigneuron
/Advantra/seed.h
UTF-8
2,360
2.859375
3
[]
no_license
#ifndef SEED_H #define SEED_H #include <vector> using namespace std; struct Puv { // offset point in 2d cross-section Puv(int u1, int v1) : u(u1), v(v1) {} int u, v; }; struct Puwv { // offset point in 3d cross-section Puwv(int u1, int w1, int v1) : u(u1), w(w1), v(v1) {} int u, w, v; }; struct seed { seed(float _x, float _y, float _z, float _vx, float _vy, float _vz, float _score) : x(_x), y(_y), z(_z), vx(_vx), vy(_vy), vz(_vz), score(_score) {} float x, y, z; float vx, vy, vz; float score; }; class SeedExtractor { public: // static float Luw; // scale factor for the radius of the cross section ceil(Luw*sig) // static float Lv; // scale factor for the depth of the cross section ceil(Lv*sig) vector<float> sig; // Vx,Vy,Vz orthogonals (ux,uy,uz) and (wx,wy,wz) // vector< vector<int> > offset_u; // offset indexes (ux,uy,uz) // vector< vector<uw> > offset_uw; // offset indexes (ux,uy,uz) and (wx,wy,wz) // vector< vector<xyz> > offset_xyz; // offset indexes along x,y,z vector< vector<Puv> > Suv; // offset indexes that sample u=() and v=() orthogonal in 2d vector< vector<Puwv> > Suwv; // offset indexes that sample u=(), w=() and v=() orthogonals in 3d SeedExtractor(float _sig_min, float _sig_stp, float _sig_max, float _sig2r); ~SeedExtractor(); void extract3d( unsigned char J8th, float seed_scr_th, unsigned char* J8, int w, int h, int l, unsigned char* Sc, float* Vx, float* Vy, float* Vz, vector<seed>& seeds); void extract2d( unsigned char J8th, float seed_scr_th, unsigned char* J8, int w, int h, int l, unsigned char* Sc, float* Vx, float* Vy, vector<seed>& seeds); static void orthogonals(float vx, float vy, float vz, float& ux, float& uy, float& uz, float& wx, float& wy, float& wz); static void orthogonals(float vx, float vy, float& ux, float& uy); float interp(float x, float y, float z, unsigned char * img, int w, int h, int l); void export_Suv(string savepath); void export_Suwv(string savepath); static void export_seedlist(vector<seed> slist, string savepath, int type=0, float vscale=5); }; #endif // SEED_H
true
18f3c3cac1f658d46e635d1a6cc13e252dff8c33
C++
zxczzx/myRPG
/myRPG/ObjectSpawn.h
UTF-8
872
2.59375
3
[]
no_license
#pragma once #include "libraries.h" #include "Filesystem.h" #include "ItemSlot.h" class Inventory; class Abilities; class Requirements; class Resistance; class Player; class ObjectSpawn { public: ObjectSpawn(); ~ObjectSpawn(); std::shared_ptr<Filesystem> filesystem; typedef std::map<std::string, std::vector<std::string> > statsMap; std::shared_ptr<Inventory> spawnItem(std::string filename, int count); std::shared_ptr<Player> spawnActor(std::string filename); std::shared_ptr<Abilities> spawnAbility(std::string filename, int count); ItemSlot getSlotFromString(std::string slot); int getIntegerValue(statsMap map, std::string key); std::string getStringValue(statsMap map, std::string key); std::shared_ptr<Requirements> createRequirements(statsMap map); std::shared_ptr<Resistance> createResistance(statsMap map); };
true
b78c351b20aef67db417f2c896f2faf5a9c7e1cc
C++
seunghyukcho/algorithm-problems-solved
/baekjoon/previous/2490/main.cpp
UTF-8
323
2.53125
3
[]
no_license
#include<iostream> using namespace std; int main(){ for(int i = 0; i < 3; i++){ int num = 0; for(int j = 0; j < 4; j++){ int n; cin >> n; if(!n)num++; } if(!num)cout << 'E' << '\n'; else printf("%c\n", 'A' + num - 1); } return 0; }
true
f32d497c10a636c32fcdcd4d5db8ff3b0c9a7af1
C++
ibesora/cg-notes-code
/Examples/01_GLFW/src/main.cpp
UTF-8
1,673
2.921875
3
[ "MIT" ]
permissive
#include <glad/gl.h> #include <glfw/glfw3.h> #include <stdio.h> #include <stdlib.h> GLFWwindow *createWindow(int majorVersion, int minorVersion, int profile, int width, int height, const char *title, GLFWmonitor *monitor = nullptr, GLFWwindow *share = nullptr) { glfwSetErrorCallback( [](int error, const char *description) { fprintf(stderr, "Error: %s\n", description); } ); if (!glfwInit()) { return nullptr; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, majorVersion); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minorVersion); glfwWindowHint(GLFW_OPENGL_PROFILE, profile); GLFWwindow *window = glfwCreateWindow(width, height, title, monitor, share); if (!window) { glfwTerminate(); return nullptr; } return window; } void addHandlers(GLFWwindow *window) { glfwSetKeyCallback(window, [](GLFWwindow *window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } } ); } void configureGL(GLFWwindow *window) { glfwMakeContextCurrent(window); gladLoadGL(glfwGetProcAddress); glfwSwapInterval(1); } void renderLoop(GLFWwindow *window) { while (!glfwWindowShouldClose(window)) { glfwSwapBuffers(window); glfwPollEvents(); } } void destroyWindow(GLFWwindow *window) { glfwDestroyWindow(window); glfwTerminate(); } int main() { // We request an OpenGL 4.6 context in a 1080p window GLFWwindow* window = createWindow(4, 6, GLFW_OPENGL_CORE_PROFILE, 1920, 1080, "Main window"); if (!window) { exit(EXIT_FAILURE); } addHandlers(window); configureGL(window); renderLoop(window); destroyWindow(window); return 0; }
true
d573b0ca7d1408eda7af2397c82b8f64ed35ea4a
C++
MathProgrammer/AtCoder
/Contests/Educational DP Contest/Programs/Longest Path.cpp
UTF-8
1,128
3.140625
3
[]
no_license
#include <iostream> #include <vector> #include <cstring> using namespace std; const int MAX_N = 1e5 + 5; int longest_path[MAX_N]; vector <int> graph[MAX_N]; int dfs(int v) { if(longest_path[v] != -1) { return longest_path[v] ; } int longest_child_path = 0; for(int i = 0; i < graph[v].size(); i++) { int child = graph[v][i]; longest_child_path = max(longest_child_path, dfs(child)); } longest_path[v] = 1 + longest_child_path; return longest_path[v] ; } int main() { int no_of_vertices, no_of_edges; cin >> no_of_vertices >> no_of_edges; for(int i = 1; i <= no_of_edges; i++) { int x, y; cin >> x >> y; graph[x].push_back(y); } memset(longest_path, -1, sizeof(longest_path)); int vertices_on_longest_path = 0; for(int i = 1; i <= no_of_vertices; i++) vertices_on_longest_path = max(vertices_on_longest_path, dfs(i)); int edges_on_longest_path = vertices_on_longest_path - 1; cout << edges_on_longest_path; return 0; }
true
f9edd416aed5203c6cc516d4b0b7feee0ce49519
C++
p-freire/CompProg
/URI/1021.cpp
UTF-8
968
3.171875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> #define NUM_COINS 5 #define NUM_BILLS 7 using namespace std; int main() { int bills[] = {100, 50, 20, 10, 5, 2, 1}; int coins[] = {50, 25, 10, 5, 1}; int num_coins[NUM_COINS], num_bills[NUM_BILLS]; double value; int int_value, cents; scanf("%lf", &value); int_value = (int)value; cents = (value - int_value) * 100; for(int i = 0; i < NUM_BILLS; ++i) { num_bills[i] = int_value / bills[i]; int_value = int_value % bills[i]; } for(int i = 0; i < NUM_COINS; ++i) { num_coins[i] = cents / coins[i]; cents = cents % coins[i]; } printf("NOTAS:\n"); for(int i = 0; i < NUM_BILLS - 1; ++i) printf("%d nota(s) de R$ %d.00\n", num_bills[i], bills[i]); printf("MOEDAS:\n"); printf("%d moeda(s) de R$ %d.00\n", num_bills[NUM_BILLS - 1], bills[NUM_BILLS - 1]); for(int i = 0; i < NUM_COINS; ++i) printf("%d moeda(s) de R$ %.2lf\n", num_coins[i], (double)coins[i]/100.0); return 0; }
true
45478c0261958f72244b0fd3849891413ce7d5e3
C++
yougaindra/A2oj_ladder11
/96a.cpp
UTF-8
239
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; if(s.find("1111111") != string::npos || s.find("0000000") != string::npos) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
true
1462035fe8dec9b15d54124a17e07159d8d88be6
C++
L-Elyse/csc17a_2017
/Project/Project 1/Versions/Project_v3/main.cpp
UTF-8
2,925
3.53125
4
[]
no_license
/* * File: main.cpp * Author: Laurie Guimont * Created on April 10, 2017, 4:00 PM * Purpose: War Card Game */ //System Libraries #include <iostream> //Input/Output Stream Library #include <iomanip> //Formatting Library #include <ctime> //Unique Seed Value Library #include <cstdlib> //Random Value Library #include <string> //String Library #include <fstream> //File I/O #include <cmath> //Math Library #include <cctype> #include <cstring> using namespace std; //User Libraries #include "Player.h" //Global Constants--ONLY for 2D Array //Function Prototypes string intro(); unsigned short facdDwn(unsigned short &); unsigned int menu(unsigned int &); char pckCard(unsigned int &); //Execution Begins Here! int main(int argc, char** argv){ //Set the Random Number Seed srand(static_cast<unsigned int>(time(0))); //Declare Variables unsigned short warcnt; unsigned int choice; player comp,user; //Get Name of Opponent & Establish Number of "Faced Down" Cards comp.name=intro(); facdDwn(warcnt); do{ menu(choice); if(choice!=3){ user.card=pckCard(choice); } }while(choice!=3); //Exit Stage Right return 0; } char pckCard(unsigned int &choice){ //Declare Variable char card; if(choice==1){ cout<<"Please enter the number of your choice(2-9)"<<endl; cin>>card; //Validate while(card<'2'||card>'9'){ cout<<"Invalid entry! Please enter (2-9)"<<endl; cin>>card; } } else if(choice==2){ cout<<"Please enter T, J, Q, K, or A"<<endl; cin>>card; //Validate while(toupper(card)!='A'&&toupper(card)!='K'&&toupper(card)!='Q'&& toupper(card)!='J'&&toupper(card)!='T'){ cout<<"Invalid entry! Please enter one of the choices above"<<endl; cin>>card; } } return card; } unsigned int menu(unsigned int &option){ cout<<endl; cout<<"What type of card would you like to play?"<<endl; cout<<"1. Number Card"<<endl; cout<<"2. Face Card"<<endl; cout<<"3. End Game"<<endl<<endl; cin>>option; return option; } unsigned short facdDwn(unsigned short &number){ cout<<endl; cout<<"When war is waged, How many cards do you want to put down before "; cout<<"the war card is flipped?"<<endl; cout<<"(Please pick a number from 2-4)"<<endl; cin>>number; //Validation while(number<2||number>4){ cout<<"Error. Please enter 2, 3 or 4"<<endl; cin>>number; } return number; } string intro(){ //Declare Variables string c; cout<<"The name of the game? WAR!"<<endl; cout<<"First give your opponent a name. You didn't think you were playing "; cout<<"against the computer did you?"<<endl; getline(cin,c); return c; }
true
afe15aa2c127ca98ae75ecd2fafe05dbd53c2c55
C++
lzs4073/color
/src/color/hsl/make/tan.hpp
UTF-8
1,860
2.875
3
[ "Apache-2.0" ]
permissive
#ifndef color_hsl_make_tan #define color_hsl_make_tan // ::color::make::tan( c ) namespace color { namespace make { //RGB equivalents: std::array<double,3>( { 34.2857, 43.75, 68.6275 } ) - rgb(210,180,140) - #d2b48c inline void tan( ::color::_internal::model< ::color::category::hsl_uint8 > & color_parameter ) { color_parameter.container() = std::array< std::uint8_t, 3 >( { 0x18, 0x6f, 0xaf } ); } inline void tan( ::color::_internal::model< ::color::category::hsl_uint16 > & color_parameter ) { color_parameter.container() = std::array< std::uint16_t, 3 >( { 0x1861, 0x6fff, 0xafaf } ); } inline void tan( ::color::_internal::model< ::color::category::hsl_uint32 > & color_parameter ) { color_parameter.container() = std::array< std::uint32_t, 3 >( { 0x18618618, 0x6fffffff, 0xafafafaf } ); } inline void tan( ::color::_internal::model< ::color::category::hsl_uint64 > & color_parameter ) { color_parameter.container() = std::array< std::uint64_t, 3 >( { 0x1861861861861a00ull, 0x6ffffffffffff800ull, 0xafafafafafafb000ull } ); } inline void tan( ::color::_internal::model< ::color::category::hsl_float > & color_parameter ) { color_parameter.container() = std::array<float,3>( { 34.2857, 43.75, 68.6274 } ); } inline void tan( ::color::_internal::model< ::color::category::hsl_double> & color_parameter ) { color_parameter.container() = std::array<double,3>( { 34.2857, 43.75, 68.6275 } ); } inline void tan( ::color::_internal::model< ::color::category::hsl_ldouble> & color_parameter ) { color_parameter.container() = std::array<long double,3>( { 34.2857, 43.75, 68.6275 } ); } } } #endif
true
18df57ed038eb7c1b97b5eafb1d30306720df571
C++
AndrewMar007/Labs
/CPP/cpa_lab_8_2_3_(1)-C.cpp
UTF-8
3,489
4
4
[]
no_license
#include <iostream> using namespace std; class Date { public: int day, month, year; enum weekday { THURSDAY, FRIDAY, SATURDAY, SUNDAY, MONDAY, TUESDAY, WEDNESDAY }; enum month { january = 1, february, march, april, may, june, july, august, september, oktober,november, december }; string DayWeek (int da) { switch (da) { case MONDAY: return"Monday"; case TUESDAY: return "Tuesday"; case WEDNESDAY: return "Wednesday"; case THURSDAY: return "Thursday"; case FRIDAY: return "Friday"; case SATURDAY: return"Saturday"; case SUNDAY: return "Sunday"; default: return "Somewhere inside the depths of time..."; } return ""; } string Month(int da) { switch (da) { case january: return "january"; case february: return"february"; case march: return "march"; case april: return "april"; case may: return "may"; case june: return "june"; case july: return"july"; case august: return"august"; case september: return"september"; case oktober: return"oktober"; case november: return"november"; case december: return"december"; default: return "Somewhere inside the depths of time..."; } return ""; } Date(int d = 1, int m = 1, int y = 1970) { if (y < 1970) throw string("data must be more 1.1.1970"); if(m < 1 || m > 12) throw string("month in range [1....12]"); if (d < 1 || d > 31) throw string("day in range [1....31]"); day = d; month = m; year = y; } bool isLeap(int year){ return year % 400 == 0 || year % 100 != 0 && year % 4 == 0; } int monthLength(int year, int month){ if (month == 2 && isLeap(year)) return 29; int lengths[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return lengths[month - 1]; } int dayOfYear(Date date){ int res = date.day; for (int i = 1; i < date.month; i++) res += monthLength(date.year, i); return res; } int daysBetween(Date d1, Date d2){ if(d1.year > d2.year) return -1; int daysCount = dayOfYear(d2) - dayOfYear(d1); //At first count days in last year if(d1.year == d2.year && daysCount < 0) return -1; for(int i = d1.year; i < d2.year; ++i) //Then count previous years daysCount += isLeap(i) ? 366 : 365; return daysCount; } int operator-(Date w) { return daysBetween(w, *this); } }; int main() { int day, month, year; cout << "Enter day: "; cin >> day; cout << "Enter month: "; cin >> month; cout << "Enter year: "; cin >> year; Date q(day, month, year); Date w(1, 1, 1970); int qq = q - w; cout << q.day << " " << q.Month(q.month) << " " << q.year << " - " << q.DayWeek(qq % 7) << " - "<< qq <<" days since 1st January 1970" << endl; return 0; }
true
5d3acc9d4ff78bf8667ba317a258fbf7ce034f35
C++
kedixa/LeetCode
/C++/264.cpp
UTF-8
456
2.859375
3
[]
no_license
class Solution { public: int nthUglyNumber(int n) { if(n < 1) return 0; vector<long long> vec(n); vec[0] = 1; int p2 = 0, p3 = 0, p5 = 0; for(int i = 1; i < n; ++i) { vec[i] = min({vec[p2] * 2, vec[p3] * 3, vec[p5] * 5}); if(vec[i] == vec[p2] * 2) ++p2; if(vec[i] == vec[p3] * 3) ++p3; if(vec[i] == vec[p5] * 5) ++p5; } return vec.back(); } };
true
3b6dd63212faac679b415f08ee538af4454fa80e
C++
tonyganchev/cpp-build-tools-playground
/main.cpp
UTF-8
938
2.703125
3
[]
no_license
#include "server_config.hpp" #include <iostream> #include <cpprest/http_listener.h> #include <cpprest/json.h> #include <cpprest/asyncrt_utils.h> #include <cpprest/uri.h> using namespace web; using namespace web::http; using namespace web::http::experimental::listener; class server { public: server(uri endpoint_uri) : listener_(endpoint_uri) { listener_.support(methods::GET, std::bind(&server::handle_get, this, std::placeholders::_1)); } void start() { listener_.open().wait(); } void stop() { listener_.close().wait(); } private: void handle_get(http_request req) { req.reply(status_codes::OK, "Sample REST response."); } http_listener listener_; }; int main() { auto endpoint_uri = U("http://localhost:8080/sample-api"); server srv(endpoint_uri); srv.start(); std::wcout << U("Listeing on: ") << endpoint_uri << U(". Press ENTER to end process.") << std::endl; std::cin.get(); srv.stop(); return 0; }
true
b75f76d3169ee091be5b79739d12f4152e2463f4
C++
NUbots/NUPresenceClient
/module/visualisation/OculusViewer/src/GameObject.h
UTF-8
1,388
2.6875
3
[]
no_license
#include <GL/OOGL.hpp> #include <string> #include <vector> #include <iostream> #include "RenderMesh.h" #include <memory> #ifndef MODULES_VISUALISATION_NUPRESENCE_GAME_OBJECT_H #define MODULES_VISUALISATION_NUPRESENCE_GAME_OBJECT_H namespace module { namespace visualisation { class GameObject { public: std::vector<std::shared_ptr<GameObject>> children; std::vector<std::shared_ptr<RenderMesh>> meshes; // std::vector<Light> lights; //transform maps from object space to world space GL::Mat4 transform; GameObject(GL::Mat4 t = GL::Mat4()) : transform(t){}; ~GameObject(){}; void addMesh(const std::shared_ptr<RenderMesh>& mesh){ meshes.push_back(mesh); } void addChild(const std::shared_ptr<GameObject>& child){ children.push_back(child); } // void addLight(const Light& light){ // lights.push_back(light); // } void render(GL::Context& gl, GL::Mat4 prevModel, GL::Mat4 view, GL::Mat4 projection/*, std::vector<Light>& outLights*/, GL::Program& shader){ GL::Mat4 model = prevModel * transform; GL::Mat4 modelview = view * model; for(auto& child : children){ child->render(gl, model, view, projection, shader); } for(auto& mesh : meshes){ mesh->render(gl, modelview, projection, shader); } // for(auto& light : lights){ // outLights.push_back(light.transform(model)); // } } }; } } #endif
true
48813ca8fb4c52b6cceccf93ac4e7e4c877e0290
C++
JeG99/Queue_implementation
/Queue.h
UTF-8
1,116
3.703125
4
[]
no_license
#include "Node.h" template <class T> class Queue { public: Queue(); ~Queue(); void push(T data); void pop(); T front(); bool isEmpty(); int size(); private: Node<T>* tail; int length; }; template <class T> Queue<T>::Queue() { tail = NULL; length = 0; } template <class T> Queue<T>::~Queue() { if(tail != NULL) { Node<T>* aux = tail->getNext(); tail->setNext(NULL); tail = aux; while(tail != NULL) { tail = tail->getNext(); delete aux; aux = tail; } } } template <class T> void Queue<T>::push(T data) { if(tail == NULL) { tail = new Node<T>(data); tail->setNext(tail); } else { tail->setNext(new Node<T>(data, tail->getNext())); tail = tail->getNext(); } length++; } template <class T> void Queue<T>::pop() { Node<T>* aux = tail->getNext(); if(aux == tail) { tail = NULL; } else { tail->setNext(aux->getNext()); } delete aux; length--; } template <class T> T Queue<T>::front() { return tail->getNext()->getData(); } template <class T> int Queue<T>::size() { return length; } template <class T> bool Queue<T>::isEmpty() { return (tail == NULL); }
true
50e22369aa23f54673ed6e3f56dab0c6f2c0d5b2
C++
ht1204/repo_algoritmos
/c++/practicas varias c++/modelo trabajo/Descomponer Dígitos/Digitos.cpp
UTF-8
460
2.875
3
[]
no_license
#include <stdio.h> #define N 19 int main( void ) { int c, i, n; int digitos[N]; unsigned long long int num; printf( "Escribe un numero de %d digitos como maximo: ", N ); fflush( stdout ); num = 0; for( n = 0; n < N && (c = getchar()) != '\n'; n++ ) { digitos[n] = c - '0'; num *= 10; num += digitos[n]; } printf( "Digitos: " ); for( i = 0; i < n; ++i ) printf( " %3d,", digitos[i] ); return 0; }
true
f4a0b6acf5b1668ee1d18e4e6a6b4fccfba92701
C++
NullStudio/NoNameGame
/src/SCredits.cpp
UTF-8
2,688
2.890625
3
[]
no_license
#include "SCredits.hpp" #include "SMenu.hpp" SCredits::SCredits(Game* game) : GameState(game), mCreditsBG(NULL), mCredits1(NULL) { } SCredits::~SCredits() { } void SCredits::Init() { std::cout << "-- SCredits::Init()" << std::endl; SetRunningState(true); mCreditsBG = new sf::Sprite; mCreditsBG->SetImage( mGame->mResourceManager.GetImage("creditsBG.png") ); mCredits1 = new sf::Sprite; //mCredits1->SetImage( mGame->mResourceManager->GetImage("credits1.png") ); mCredits1->SetImage( mGame->mResourceManager.GetImage("aliens.png") ); mCredits1->SetPosition(250, 200); mCreditsMusic.OpenFromFile("music/creditsMusic.ogg"); mCreditsMusic.Play(); mAlpha = 0.0f; } void SCredits::End() { mCreditsMusic.Stop(); delete mCredits1; mCredits1 = NULL; delete mCreditsBG; mCreditsBG = NULL; std::cout << "-- SCredits::End()" << std::endl; } void SCredits::Pause() { SetRunningState(false); mCreditsMusic.Pause(); } void SCredits::Resume() { SetRunningState(true); mCreditsMusic.Play(); } void SCredits::HandleEvents(const sf::Event& theEvent) { // Escape key pressed if ((theEvent.Type == sf::Event::KeyPressed) && (theEvent.Key.Code == sf::Key::Escape)) { if(NULL != mGame) { SetRunningState(false); End(); //mGame->End(); } } if ((theEvent.Type == sf::Event::KeyPressed) && (theEvent.Key.Code == sf::Key::Space)) { //std::cout << "SCredits::HandleEvents" << std::endl; //mCreditsBG->SetPosition( mCreditsBG->GetPosition().x + 10, mCreditsBG->GetPosition().y + 10); } if ((theEvent.Type == sf::Event::KeyPressed) && (theEvent.Key.Code == sf::Key::N)) { std::cout << "SCredits - next SCENE!!" << std::endl; if ( timer.GetElapsedTime() > 0.05 ) { //mGame->mStateManager.RemoveActiveState(); mGame->mStateManager.PushState( new(std::nothrow) SMenu(mGame) ); } timer.Reset(); SetRunningState(false); } } void SCredits::Update() { //std::cout << "SCredits::Update" << std::endl; if ( IsRunning() ) { mAlpha += mGame->mApp.GetFrameTime(); //std::cout << "Alpha = " << mAlpha << std::endl; float FadeDuration = 5.0f; float alpha = (255 * mAlpha / FadeDuration ); if (alpha > 255) alpha = 255; //mCredits1->SetColor( sf::Color(255, 255, 255, (sf::Uint8) (255 * mAlpha / 5.0f )) ); mCredits1->SetColor( sf::Color(255, 255, 255, (sf::Uint8) (alpha)) ); } } void SCredits::Draw() { mGame->mApp.Draw(*mCreditsBG); mGame->mApp.Draw(*mCredits1); }
true
0ef364ab0fcdb1a102a659de46e42a48bc747e56
C++
andre-b-fernandes/aeda-the-voice
/Competition.cpp
UTF-8
1,241
2.875
3
[]
no_license
/* * Competition.cpp * * Created on: 31/10/2016 * Author: user */ #include "Competition.h" #include <string> #include <iostream> #include <vector> using namespace std; /*Competition::Competition(int y){ this->year=y;} */ void Competition ::setInitial(vector<Participant*> p) { for(unsigned int i = 0; i < p.size(); i++) { Initialparticipants.push_back(p.at(i)); } } int Competition::getYear() const{ return year;} int Competition::numParticipants(){ return participants.size();} vector <Participant *> & Competition::getParticipants(){ return participants; } vector <Mentor *>& Competition::getMentors(){ return mentors; } vector <Host *>& Competition::getHosts(){ return hosters; } vector <Phase *>& Competition::getPhases(){ return phases; } vector <Song *> &Competition::getSongs(){ return songs; } void Competition ::setYear(int y) { this->year = y; } void Competition::addParticipants(Participant *p){ participants.push_back(p); } void Competition::addMentors(Mentor* m){ mentors.push_back(m); } void Competition::addPhases(Phase *ph){ phases.push_back(ph); } void Competition::addHosts(Host *h){ hosters.push_back(h); } void Competition::addSongs(Song *s){ songs.push_back(s); }
true
fdd5e1235f13255f531c4cfb122746499190d419
C++
Alexxx111/Voxel
/Grundgerüst/project/Window.cpp
UTF-8
556
2.921875
3
[]
no_license
#include "Window.h" Window::Window(int w, int h) { this->width = w; this->height = h; SDL_Init(SDL_INIT_EVERYTHING); window = SDL_CreateWindow(".. ", 600, 100, width, height, SDL_WINDOW_OPENGL); context = SDL_GL_CreateContext(window); glClearColor(0.f, 0.1f, 0.3f, 1.0f); } Window::~Window() { SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); } void Window::clear(){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); } void Window::flip(){ SDL_GL_SwapWindow(window); } SDL_Window *Window::get_window(){ return this->window; }
true
78b65231d839de53bfad8c00aa21496b3aeaee76
C++
silverthreadk/leetcode
/Cpp/1800_Maximum_Ascending_Subarray_Sum.cpp
UTF-8
370
2.8125
3
[]
no_license
class Solution { public: int maxAscendingSum(vector<int>& nums) { int sum = nums[0]; int result = sum; for(int i=1; i<nums.size(); ++i) { if(nums[i] <= nums[i-1]) { sum = 0; } sum += nums[i]; result = max(result, sum); } return result; } };
true
1727b7a39368c1fb80f6e6560d3da7b7b298f2be
C++
Nasker/RTPLib
/RTPRotaryClick.cpp
UTF-8
561
2.59375
3
[]
no_license
/* RTPRotaryClick.cpp - Class for reading and managing a Rotary Encoder with click button. Created by Oscar Martínez Carmona @ RockinTechProjects, October 6, 2017. */ #include "Arduino.h" #include "RTPRotaryClick.h" void RTPRotaryClick::callbackOnRotation( void (*userFunc)(String,int) ){ long newPosition = read()/4; if (newPosition < _oldPosition) { _oldPosition = newPosition; (*userFunc)("ROTATING LEFT",newPosition); } else if (newPosition > _oldPosition) { _oldPosition = newPosition; (*userFunc)("ROTATING RIGHT",newPosition); } }
true
71fde6d8f86b76ede38491e6a9e73bd719081f0b
C++
pranshu-09/Launchpad-Coding-Blocks
/Binary Tree/20_minimum_distance_between_2_nodes.cpp
UTF-8
2,647
3.75
4
[]
no_license
#include<iostream> #include<queue> #include<stack> using namespace std; class node { public: int data; node*left; node*right; node(int data) { this->data = data; this->left = NULL; this->right = NULL; } }; node*build_tree() { int d; cin >> d; if (d == -1) { return NULL; } node*root = new node(d); root->left = build_tree(); root->right = build_tree(); return root; } void bfs_print(node*root) { queue<node*>q; q.push(root); q.push(NULL); while (!q.empty()) { node*f = q.front(); q.pop(); if (f == NULL) { cout << endl; if (!q.empty()) { q.push(NULL); } } else { cout << f->data << " "; if (f->left) { q.push(f->left); } if (f->right) { q.push(f->right); } } } } // Method 1 int path(node*root, int a, stack<node*>&s) { if (root == NULL) { return -1; } if (root->data == a) { s.push(root); return 0; } int left = path(root->left, a, s); if (left != -1) { s.push(root); return left + 1; } int right = path(root->right, a, s); if (right != -1) { s.push(root); return right + 1; } return -1; } int distance_between_nodes(node*root, int a, int b) { stack<node*>a1; stack<node*>b1; path(root, a, a1); path(root, b, b1); while (!a1.empty() and !b1.empty() and a1.top() == b1.top()) { a1.pop(); b1.pop(); } return a1.size() + b1.size(); } // Method 2 node*lca(node*root, int a, int b) { if (root == NULL) { return NULL; } if (root->data == a or root->data == b) { return root; } node*left_node = lca(root->left, a, b); node*right_node = lca(root->right, a, b); if (left_node != NULL and right_node != NULL) { return root; } if (left_node != NULL) { return left_node; } return right_node; } int search(node*root, int key, int level) { if (root == NULL) { return -1; } if (root->data == key) { return level; } int left = search(root->left, key, level + 1); if (left != -1) { return left; } int right = search(root->right, key, level + 1); if (right != -1) { return right; } return -1; } int distance_between_nodes_2(node*root, int a, int b) { node*lca_node = lca(root, a, b); int l1 = search(lca_node, a, 0); int l2 = search(lca_node, b, 0); return l1 + l2; } int main() { node*root = build_tree(); bfs_print(root); int a, b; cin >> a >> b; // Method 1 int ans = distance_between_nodes(root, a, b); cout << "Minimum distance between " << a << " and " << b << " is " << ans << endl; // Method 2 int ans_2 = distance_between_nodes_2(root, a, b); cout << "Minimum distance between " << a << " and " << b << " is " << ans_2 << endl; return 0; }
true
0b964d28cdd3c39005eb5303bee938fef0b2ee51
C++
amandasambawa/FrackMan
/StudentWorld.cpp
UTF-8
24,339
2.875
3
[]
no_license
// Author: Amanda Sambawa #include "StudentWorld.h" #include "GameController.h" #include "Actor.h" #include <string> #include <iostream> #include <iomanip> #include <random> #include <math.h> #include <cstdlib> #include <ctime> using namespace std; GameWorld* createStudentWorld(string assetDir) { return new StudentWorld(assetDir); } StudentWorld::~StudentWorld() { delete m_frackman; for (int i = 0; i < VIEW_WIDTH; i++) { for (int j = 0; j < VIEW_HEIGHT; j++) { if (arr[i][j] != nullptr) delete arr[i][j]; } } for (int i = 0; i < m_actors.size(); i++) { delete m_actors[i]; } } // Add an actor to the world. void StudentWorld::addActor(Actor* a) { m_actors.push_back(a); } void StudentWorld::clearDirt(int x, int y) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { int temp_x = x + j; int temp_y = y + k; if (temp_y < 60 && (temp_x < 30 || temp_x > 33)) { if (arr[temp_x][temp_y] != nullptr) { delete arr[temp_x][temp_y]; arr[temp_x][temp_y] = nullptr; } } else if (temp_x >= 30 && temp_x <= 33 && temp_y <= 3) { if (arr[temp_x][temp_y] != nullptr) { delete arr[temp_x][temp_y]; arr[temp_x][temp_y] = nullptr; } } } } } int randInt(int min, int max) { if (max < min) swap(max, min); static random_device rd; static mt19937 generator(rd()); uniform_int_distribution<> distro(min, max); return distro(generator); } void StudentWorld::createDirtField() { // Create the field with dirt for (int i = 0; i < 64; i++) { for (int j = 0; j < 60; j++) { //arr[i][j] = new Dirt(i,j); if (i < 30 || i > 33 || j < 4) arr[i][j] = new Dirt(this, i, j); else arr[i][j] = nullptr; //arr[i][j]->setVisible(false); } } } int StudentWorld::init() { m_ticks = 0; vector<Actor*>::iterator it; it = m_actors.begin(); // Make sure the vector is clear of previous actors while (it != m_actors.end()) { delete *it; it = m_actors.erase(it); } // Create and display the Frackman m_frackman = new FrackMan(this); createDirtField(); // Set all elements of grid to false (for the population of boulders) for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { grid[i][j] = false; } } // Set all elements of the boulder grid to false for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { boulderGrid[i][j] = false; } } // Set all elements of the frackman path to false for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { frackmanPath[i][j] = false; } } // b boulders in each level: int b = fmin(getLevel()/2 + 2, 6); // Insert the boulders for (int i = 0; i < b; i++) { int t_x = randInt(0, 60); int t_y = randInt(20, 56); while (t_x >= 27 && t_x <= 33) { t_x = randInt(0, 60); } if (grid[t_y][t_x] == false) // grid[row][column] { grid[t_y][t_x] = true; for (int y = 20; y <= 56; y++) { for (int x = 0; x <= 60; x++) { if ((sqrt(((t_x - x) * (t_x - x)) + ((t_y - y) * (t_y - y)))) <= 6) { grid[y][x] = true; } } } m_actors.push_back(new Boulders(this, t_x, t_y)); clearDirt(t_x, t_y); } else { while (grid[t_y][t_x] == true) { t_x = randInt(0, 60); t_y = randInt(20, 56); while (t_x >= 27 && t_x <= 33) { t_x = randInt(0, 60); } } grid[t_y][t_x] = true; for (int y = 20; y <= 56; y++) { for (int x = 0; x <= 60; x++) { if ((sqrt(((t_x - x) * (t_x - x)) + ((t_y - y) * (t_y - y)))) <= 6) grid[y][x] = true; } } m_actors.push_back(new Boulders(this, t_x, t_y)); clearDirt(t_x, t_y); } } // Set boulder coordinates to true in boulderGrid for (int i = 0; i < m_actors.size(); i++) { if (!(m_actors[i]->canActorsPassThroughMe())) // if the actor is a boulder { int xCoord = m_actors[i]->getX(); int yCoord = m_actors[i]->getY(); for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { boulderGrid[xCoord+j][yCoord+k] = true; } } } } // g gold nuggets in each level: int g = fmax(5 - getLevel()/2, 2); for (int i = 0; i < g; i++) { int t_x = randInt(0, 60); int t_y = randInt(20, 56); while (t_x >= 27 && t_x <= 33) { t_x = randInt(0, 60); } if (grid[t_y][t_x] == false) // grid[row][column] { grid[t_y][t_x] = true; for (int y = 20; y <= 56; y++) { for (int x = 0; x <= 60; x++) { if ((sqrt((t_x - x) * (t_x - x) + (t_y - y) * (t_y - y))) <= 6) grid[y][x] = true; } } m_actors.push_back(new GoldNuggetForFrackMan(this, t_x, t_y)); } else { while (grid[t_y][t_x] == true) { t_x = randInt(0, 60); t_y = randInt(20, 56); while (t_x >= 27 && t_x <= 33) { t_x = randInt(0, 60); } } grid[t_y][t_x] = true; for (int y = 20; y <= 56; y++) { for (int x = 0; x <= 60; x++) { if ((sqrt(t_x - x) * (t_x - x) + (t_y - y) * (t_y - y)) <= 6) grid[y][x] = true; } } m_actors.push_back(new GoldNuggetForFrackMan(this, t_x, t_y)); } } // l barrels of oil in each level: numBarrels = fmin(2 + getLevel(), 20); for (int i = 0; i < numBarrels; i++) { int t_x = randInt(0, 60); int t_y = randInt(20, 56); while (t_x >= 27 && t_x <= 33) { t_x = randInt(0, 60); } if (grid[t_y][t_x] == false) // grid[row][column] { grid[t_y][t_x] = true; for (int y = 20; y <= 56; y++) { for (int x = 0; x <= 60; x++) { if ((sqrt((t_x - x) * (t_x - x) + (t_y - y) * (t_y - y))) <= 6) grid[y][x] = true; } } m_actors.push_back(new BarrelOfOil(this, t_x, t_y)); } else { while (grid[t_y][t_x] == true) { t_x = randInt(0, 60); t_y = randInt(20, 56); while (t_x >= 27 && t_x <= 33) { t_x = randInt(0, 60); } } grid[t_y][t_x] = true; for (int y = 20; y <= 56; y++) { for (int x = 0; x <= 60; x++) { if ((sqrt(t_x - x) * (t_x - x) + (t_y - y) * (t_y - y)) <= 6) grid[y][x] = true; } } m_actors.push_back(new BarrelOfOil(this, t_x, t_y)); } } return GWSTATUS_CONTINUE_GAME; } //bool StudentWorld::isDirtOrBoulder() /** bool StudentWorld::checkDirt(Actor* a, int x, int y) { Direction d = a->getDirection(); } */ bool StudentWorld::checkDirtBelow(int x, int y) { for (int i = 0; i < 4; i++) { if (arr[x+i][y-1] != nullptr) { return false; } } return true; } // Can actor move to x,y? bool StudentWorld::canFrackmanMoveTo(int x, int y) const { if (boulderGrid[x][y] == false) { return true; } return false; } // Can actor move to x,y? bool StudentWorld::canActorMoveTo(int x, int y) const { if (boulderGrid[x][y] == false && arr[x][y] == nullptr) { return true; } return false; } // Annoy all other actors within radius of annoyer, returning the // number of actors annoyed. int StudentWorld::annoyAllNearbyActors(Actor* annoyer, int points, int radius) { int annoyer_x = annoyer->getX()+2; int annoyer_y = annoyer->getY()+2; int numAnnoyed = 0; for (int i = 0; i < m_actors.size(); i++) { if (m_actors[i]->huntsFrackMan()) { if ((sqrt((annoyer_x - m_actors[i]->getX()) * (annoyer_x - m_actors[i]->getX()) + (annoyer_y - m_actors[i]->getY()) * (annoyer_y - m_actors[i]->getY()))) <= radius) { m_actors[i]->annoy(points); numAnnoyed++; //GameController::getInstance().playSound(SOUND_PROTESTER_ANNOYED); } } } return numAnnoyed; } bool StudentWorld::annoyFrackman(int x, int y, int points, int radius) { int f_x = m_frackman->getX(); int f_y = m_frackman->getY(); if ((sqrt((x - f_x) * (x - f_x) + (y - f_y) * (y - f_y))) <= radius) { m_frackman->annoy(points); return true; } return false; } // Reveal all objects within radius of x,y. void StudentWorld::revealAllNearbyObjects(int x, int y, int radius) { for (int i = 0; i < m_actors.size(); i++) { if (m_actors[i]->canBeRevealed()) { int t_x = m_actors[i]->getX(); // bottom left coord int t_y = m_actors[i]->getY(); // bottom left coord for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { if ((sqrt((x - (t_x + k)) * (x - (t_x+k)) + (y - (t_y+j)) * (y - (t_y+j)))) <= radius) m_actors[i]->setVisible(true); } } } } } // If the FrackMan is within radius of a, return a pointer to the // FrackMan, otherwise null. Actor* StudentWorld::findNearbyFrackMan(Actor* a, int radius) const { int a_x = a->getX(); int a_y = a->getY(); int frack_x = m_frackman->getX(); int frack_y = m_frackman->getY(); if ((sqrt((a_x - frack_x) * (a_x - frack_x) + (a_y - frack_y) * (a_y - frack_y))) <= radius) return m_frackman; return nullptr; } int StudentWorld::getCurrentHealth() const { return m_frackman->getHitPoints(); } void StudentWorld::updateDisplayText() { int score = getScore(); int level = getLevel(); int lives = getLives(); ostringstream ss; ss << setw(8) << setfill('0') << score; string scr = ss.str(); ss.str(""); ss << setw(2) << setfill(' ') << level; string lvl = ss.str(); ss.str(""); ss << m_frackman->getWaterSquirts(); string water = ss.str(); ss.str(""); ss << m_frackman->getHitPoints(); string health = ss.str(); ss.str(""); ss << m_frackman->getGoldNuggets(); string gold = ss.str(); ss.str(""); ss << m_frackman->getSonarCharge(); string sonar = ss.str(); ss. str(""); ss << numBarrels; string oil = ss.str(); setGameStatText(" Scr: " + scr + " Lvl: " + lvl + " Lives: " + to_string(lives) + " Hlth: " + health + " Water: " + water + " Gld: " + gold + " Sonar: " + sonar + " Oil Left: " + oil); } void StudentWorld::fireSquirt() { int x = m_frackman->getX(); int y = m_frackman->getY(); Actor::Direction d = m_frackman->getDirection(); if (d == Actor::up) m_actors.push_back(new Squirts(this, x,y + 4, d)); else if (d == Actor::down) m_actors.push_back(new Squirts(this, x, y-4, d)); else if (d == Actor::right) m_actors.push_back(new Squirts(this, x + 4, y, d)); else m_actors.push_back(new Squirts(this, x - 4, y, d)); } void StudentWorld::addGoldNugget() { m_actors.push_back(new GoldNuggetForProtester(this, m_frackman->getX(), m_frackman->getY())); } void StudentWorld::removeDeadGameObjects() { vector<Actor*>::iterator it; it = m_actors.begin(); while (it != m_actors.end()) { if (!(*it)->isAlive()) { delete *it; it = m_actors.erase(it); } else it++; } } /** bool StudentWorld::thePlayerCompletedTheCurrentLevel() const { } bool StudentWorld::canProtesterMoveTo() const { return true; } */ // Returns the number of protesters int StudentWorld::getNumProtesters() const { int total = 0; for (int i = 0; i < m_actors.size(); i++) { if (m_actors[i]->huntsFrackMan()) total++; } return total; } int StudentWorld::move() { m_ticks++; // Update the Game Status Line updateDisplayText(); // There is a 1 in G chance that a new Water Pool or Sonar Kit Goodie will be added to the oil field during any particular tick int g = getLevel() * 25 + 300; if ((rand() % g) < 1) { if ((rand() % 100) < 20) // 1/5 chance to add a new sonar kit { m_actors.push_back(new SonarKit(this, 0, 60)); } else // else add a water goodie { m_actors.push_back(new WaterPool(this, 30,30)); } } m_frackman->doSomething(); // Let frackman pick up something revealAllNearbyObjects(m_frackman->getX()+2, m_frackman->getY()+2, 4); vector<Actor*>::iterator it; it = m_actors.begin(); // Give each Actor a chance to do something while (it != m_actors.end()) { if ((*it)->canBePickedUp()) { if ((*it)->needsToBePickedUpToFinishLevel()) // barrel of oil { int x = m_frackman->getX(); int y = m_frackman->getY(); int a_x = (*it)->getX(); int a_y = (*it)->getY(); int ctr = false; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x+i == a_x && y+j == a_y) { ctr = true; } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x == a_x+i && y == a_y+j) { ctr = true; } } } if (ctr == true) { GameController::getInstance().playSound(SOUND_GOT_GOODIE); numBarrels--; increaseScore(1000); (*it)->setDead(); } it++; } else if ((*it)->canBeGiven()) // GoldForFrackman { int x = m_frackman->getX(); int y = m_frackman->getY(); int a_x = (*it)->getX(); int a_y = (*it)->getY(); int ctr = false; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x+i == a_x && y+j == a_y) { ctr = true; } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x == a_x+i && y == a_y+j) { ctr = true; } } } if (ctr == true) { GameController::getInstance().playSound(SOUND_GOT_GOODIE); m_frackman->giveGoldNugget(); increaseScore(10); (*it)->setDead(); } it++; } else if ((*it)->isSonar()) // sonar { int x = m_frackman->getX(); int y = m_frackman->getY(); int a_x = (*it)->getX(); int a_y = (*it)->getY(); int ctr = false; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x+i == a_x && y+j == a_y) { ctr = true; } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x == a_x+i && y == a_y+j) { ctr = true; } } } if (ctr == true) { GameController::getInstance().playSound(SOUND_GOT_GOODIE); m_frackman->giveSonar(); increaseScore(75); (*it)->setDead(); } it++; } else if ((*it)->isWaterPool()) // water pool { int x = m_frackman->getX(); int y = m_frackman->getY(); int a_x = (*it)->getX(); int a_y = (*it)->getY(); int ctr = false; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x+i == a_x && y+j == a_y) { ctr = true; } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (x == a_x+i && y == a_y+j) { ctr = true; } } } if (ctr == true) { GameController::getInstance().playSound(SOUND_GOT_GOODIE); m_frackman->giveWater(); increaseScore(100); (*it)->setDead(); } it++; } else it++; } else { it++; } } // Clears the dirt for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int temp_x = m_frackman->getX() + i; int temp_y = m_frackman->getY() + j; if (temp_y < 60 && (temp_x < 30 || temp_x > 33)) { if (arr[temp_x][temp_y] != nullptr) { delete arr[temp_x][temp_y]; arr[temp_x][temp_y] = nullptr; GameController::getInstance().playSound(SOUND_DIG); } } else if (temp_x >= 30 && temp_x <= 33 && temp_y <= 3) { if (arr[temp_x][temp_y] != nullptr) { delete arr[temp_x][temp_y]; arr[temp_x][temp_y] = nullptr; GameController::getInstance().playSound(SOUND_DIG); } } } } if (m_frackman->getHitPoints() <= 0) { // SOUND_PLAYER_GIVE_UP GameController::getInstance().playSound(SOUND_PLAYER_GIVE_UP); if (getLives() == 0) { return GWSTATUS_PLAYER_DIED; } else { decLives(); return GWSTATUS_PLAYER_DIED; } } // a new protester may only be added to the oil field after at least t ticks have passed since the last Protester of any type was added, where: int t = fmin(25, 200 - getLevel()); // the target number p of protesters that should be on the field is equal to: int p = fmin(15, 2 + getLevel()* 1.5); if (getNumProtesters() < p && m_ticks%t == 0) { int probabilityOfHardcore = fmin(90, getLevel() * 10 + 30); srand((unsigned int)time(NULL)); if ((rand() % 100) < probabilityOfHardcore) m_actors.push_back(new HardCoreProtester(this, 60,60, getLevel())); else m_actors.push_back(new RegularProtester(this, 60,60, getLevel())); } // Protester waits for a certain amount of tickets: int ticksToWaitBetweenMoves = fmax(0, 3 - getLevel()/4); for (int i = 0; i < m_actors.size(); i++) { if (m_actors[i]->huntsFrackMan()) { if (m_ticks % ticksToWaitBetweenMoves == 0) m_actors[i]->doSomething(); } if (!(m_actors[i]->canActorsPassThroughMe())) // if the actor is a boulder { m_actors[i]->doSomething(); if (m_actors[i]->getState() == 2) { // Boulder's coordinates: int b_x = m_actors[i]->getX(); int b_y = m_actors[i]->getY(); // Frackman's coordinates: // int temp_x = m_frackman->getX(); // int temp_y = m_frackman->getY(); // update bouldergrid for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { boulderGrid[b_x + j][b_y + k] = false; } } if (findNearbyFrackMan(m_actors[i], 3) != nullptr) { decLives(); return GWSTATUS_PLAYER_DIED; } } } if (dynamic_cast<Squirts*>(m_actors[i]) != nullptr) { m_actors[i]->doSomething(); } } // Remove newly-dead actors after each tick removeDeadGameObjects(); // delete dead game objects // If the player has collected all of the Barrels on the level, then // return the result that the player finished the level // if (thePlayerCompletedTheCurrentLevel() == true) if (numBarrels <= 0) { GameController::getInstance().playSound(SOUND_FINISHED_LEVEL); return GWSTATUS_FINISHED_LEVEL; } // the player hasn't completed the current level and hasn't died // let them continue playing the current level return GWSTATUS_CONTINUE_GAME; } void StudentWorld::cleanUp() { delete m_frackman; for (int i = 0; i < 60; i++) { for (int j = 0; j < 60; j++) { if (arr[i][j] != nullptr) delete arr[i][j]; } } }
true
0d18195a0e23a6886c5eced7da89ac8129c989d1
C++
drmilde/oFWorkShop
/src/RectAngleManager.cpp
UTF-8
1,103
3
3
[]
no_license
#include "RectAngleManager.h" RectAngleManager::RectAngleManager() { // do something useful here } RectAngleManager::~RectAngleManager() { // clean up the pointers } void RectAngleManager::addRect(int x, int y, int w, int h) { rects.push_back(new ofRectangle(x,y,w,h)); } void RectAngleManager::draw() { int count = 0; std::vector<ofRectangle*>::iterator i; CoordinateHelper CH; for (i = rects.begin(); i != rects.end(); i++) { ofPushMatrix(); CH.reset(); ofTranslate ((*i)->getX(), (*i)->getY()); CH.translate((*i)->getX(), (*i)->getY()); ofPushStyle(); ofNoFill(); ofSetColor(255,255,255); if (selected == count) { ofSetColor(255,0,0); } ofDrawRectangle(0,0, (*i)->getWidth(), (*i)->getHeight() ); ofPopStyle(); ofPopMatrix(); count++; } } int RectAngleManager::inside (int x, int y) { int count = 0; selected = -1; std::vector<ofRectangle*>::iterator i; for (i = rects.begin(); i != rects.end(); i++) { if ((*i)->inside(x,y)) { selected = count; } count++; } return selected; }
true
f5619139e206260c2a1378d6e4e90338bb2eac56
C++
SoumyaMalgonde/Data-Structures-and-Algorithms
/C++/Data-Structures/Tree/ExpressionTree.cpp
UTF-8
1,804
4.125
4
[ "MIT" ]
permissive
/* Given a postfix expression.Your task is to complete the method constructTree().The output of the program will print the infix expression of the given postfix expression. Approach Used - Create a stack and as you will be traversing the postfix expression , if the expression contains operand , create a node and insert it into tree. Else if it's an operator , pop the stack and make left and right child nodes of tree. */ #include<bits/stdc++.h> using namespace std; struct et { char value; et* left, *right; et(char x){ value = x; left = right = NULL; } }; bool isOperator(char c) { if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') return true; return false; } void inorder(et *t) { if(t) { inorder(t->left); printf("%c ", t->value); inorder(t->right); } } et* constructTree(char postfix[]) { stack<et*> st; et *t, *t1, *t2; for (int i=0; i<strlen(postfix); i++) { // If operand, simply push into stack if (!isOperator(postfix[i])) { t = new et(postfix[i]); st.push(t); } else // operator { t = new et(postfix[i]); // Pop two top nodes t1 = st.top(); // Store top st.pop(); // Remove top t2 = st.top(); st.pop(); // make them children t->right = t1; t->left = t2; // Add this subexpression to stack st.push(t); } } // only element will be root of expression // tree t = st.top(); st.pop(); return t; } int main() { int t; cin>>t; while(t--){ char postfix[25]; cin>>postfix; et* r = constructTree(postfix); inorder(r); cout<<endl; } return 0; }
true
fdab5bff7899d8b7aecc784d37acccbb1862ad87
C++
ElxFuego/Different_scripts
/Password_Generator/MenuOptions.cpp
UTF-8
476
3
3
[]
no_license
//szkielet do robienia menu #include <iostream> #include <conio.h> int MenuOptions() { int choice; bool state; std::cout<<"\n1. Generate Passwords"<<std::endl; std::cout<<"2. Exit"<<std::endl; do{ choice = getch(); state = true; switch(choice) { case '1': return 1; break; case '2': return 2; break; default: state = false; break; } }while(!state); }
true
93a501498934bf3200bb6d0f46e0b38ee892260b
C++
razorshultz/SDL2Engine
/SDL2Engine/Player.h
UTF-8
1,004
2.75
3
[]
no_license
#ifndef PLAYER_H #define PLAYER_H #include "Entity.h" #include <string> #include "Sound.h" class Player : public Entity { public: Player(); Player(std::string texfilename, SDL_Renderer* renderer); Player(std::string texfilename, SDL_Renderer* renderer, float x, float y); ~Player(); void Update(const float& UPDATE_INTERVAL) override; inline bool GetDownPressed() const { return downpressed; }; inline bool GetUpPressed() const { return uppressed; }; inline void SetDownPressed(bool press) { downpressed = press; }; inline void SetUpPressed(bool press) { uppressed = press; }; inline bool GetLeftPressed() const { return leftpressed; }; inline bool GetRightPressed() const { return rightpressed; }; inline void SetLeftPressed(bool press) { leftpressed = press; }; inline void SetRightPressed(bool press) { rightpressed = press; }; Sound mSound; Sound mSound2; private: int score; bool downpressed; bool uppressed; bool leftpressed; bool rightpressed; }; #endif
true
0f6706f11d8d4afe5873cdb8557bb954a270d5e9
C++
ntu6stef/BmpGenerator
/src/bmp.cpp
UTF-8
7,595
2.90625
3
[]
no_license
#include "bmp.h" inline INT_32 Palette::GetColor(INT_8 b,INT_8 g,INT_8 r) { INT_32 temp=0x00000000; temp=(temp|(INT_32) b); temp=(temp<<8|(INT_32) g); temp=(temp<<8|(INT_32) r); return temp; } inline Palette Palette::GetPalette(INT_32 color) { Palette temp(color); return temp; } inline Palette Palette::GetPalette(INT_8 b,INT_8 g,INT_8 r) { Palette temp(b,g,r); return temp; } int Bmp::SetSize(INT_32 width, INT_32 height) { if(data==NULL) { InitFileHeader(); InitInfoHeader(); file.bfSize=((width*3+3)/4)*4*height+file.bfOffbits; info.biWidth=width; info.biHeight=height; data = new Palette[width*height]; return 0; } else { return -1; } } int Bmp::load(const char *path) { if(data!=NULL) { return -1; } fstream pic; pic.open(path,ios::binary|ios::in); if(pic.is_open()==0) { cout<<"Open file "<<path<<" failed"<<endl; return -1; } pic.read((char *) &file,sizeof(BmpFileHeader)); pic.read((char *) &info,sizeof(BmpInfoHeader)); data = new Palette[info.biWidth*info.biHeight]; for(INT_32 i=info.biHeight-1;i>=0;i--) { INT_32 SizePerLine=((info.biWidth*3+3)/4)*4; char *buffer = new char[SizePerLine]; pic.read(buffer,SizePerLine); std::memcpy(data+info.biWidth*i,buffer,sizeof(Palette)*info.biWidth); } pic.close(); return 0; } int Bmp::write(const char *path) { fstream temp; temp.open(path,ios::binary|ios::out|ios::trunc); if(temp.is_open()==0) { cout<<"Open File "<<path<<" failed!"<<endl; return -1; } temp.write((char *) &file,sizeof(BmpFileHeader)); temp.write((char *) &info,sizeof(BmpInfoHeader)); for(INT_32 i=info.biHeight-1;i>=0;i--) { INT_32 SizePerLine=((info.biWidth*3+3)/4)*4; char *buffer = new char[SizePerLine]; std::memcpy(buffer,data+info.biWidth*i,sizeof(Palette)*info.biWidth); temp.write(buffer,SizePerLine); } temp.close(); return 0; } Palette Bmp::getpixel(INT_32 x,INT_32 y) { Palette color; if(x>=0&&y>=0&&x<info.biWidth&&y<info.biHeight) { color=*(data+y*info.biWidth+x); } return color; } INT_32 Palette::TellColor(void) { return GetColor(Blue,Green,Red); } int Bmp::line(INT_32 x1,INT_32 y1,INT_32 x2,INT_32 y2,int thickness,Palette color) { INT_32 dx=x2-x1; INT_32 dy=y2-y1; INT_32 ux=((dx>0)<<1)-1; INT_32 uy=((dy>0)<<1)-1; INT_32 x=x1,y=y1,eps=0; dx=dx>0?dx:0-dx; dy=dy>0?dy:0-dy; if(dx>dy) { for(x=x1;x!=x2;x+=ux) { for(int i=0-thickness/2;i<=thickness/2;i++) { pixel(x,y+i,color); } eps+=dy; if((eps<<1)>=dx) { y+=uy; eps-=dx; } } } else { for(y=y1;y!=y2;y+=uy) { for(int i=0-thickness/2;i<=thickness/2;i++) { pixel(x+i,y,color); } eps+=dx; if((eps<<1)>=dy) { x+=ux; eps-=dy; } } } return 0; } int Bmp::rectangle(INT_32 x1,INT_32 y1,INT_32 x2,INT_32 y2,int thickness,Palette color) { line(x1-thickness/2,y1,x2+thickness/2,y1,thickness,color); line(x1-thickness/2,y2,x2+thickness/2,y2,thickness,color); line(x1,y1-thickness/2,x1,y2+thickness/2,thickness,color); line(x2,y1-thickness/2,x2,y2+thickness/2,thickness,color); return 0; } int Bmp::bar(INT_32 x1,INT_32 y1,INT_32 x2,INT_32 y2,Palette color) { for(INT_32 i=x1;i<=x2;i++) { line(i,y1,i,y2,1,color); } return 0; } int Bmp::circle(INT_32 x,INT_32 y,INT_32 r,Palette color) { int x0=0,y0=r; int d=1-r; while(y0>x0) { pixel(x0+x,y0+y,color); pixel(y0+x,x0+y,color); pixel(-x0+x,y0+y,color); pixel(-y0+x,x0+y,color); pixel(-x0+x,-y0+y,color); pixel(-y0+x,-x0+y,color); pixel(x0+x,-y0+y,color); pixel(y0+x,-x0+y,color); if(d<0) d=d+2*x0+3; else { d=d+2*(x0-y0)+5; y0--; } x0++; } return 0; } int RGB2Grey(Bmp *source, Bmp *dest) { for(int i=0;i<source->width();i++) { for(int j=0;j<source->height();j++) { Palette temp=source->getpixel(i,j); int average=(temp.Blue+temp.Red+temp.Green)/3; dest->pixel(i,j,Palette(average,average,average)); } } return 0; } int Grey2Binary(Bmp *source,Bmp *dest,float light) { int average=0; for(int i=0;i<source->width();i++) { for(int j=0;j<source->height();j++) { average+=source->getpixel(i,j).Blue; } } average=average/(source->width()*source->height()); for(int i=0;i<source->width();i++) { for(int j=0;j<source->height();j++) { Palette temp=source->getpixel(i,j); if(temp.Blue>average/light) { dest->pixel(i,j,Palette(255,255,255)); } else { dest->pixel(i,j,Palette(0,0,0)); } } } return average; } int FindAroundPixelNum(Bmp *pic, int x,int y,Palette color) { int num=0; for(int i=x-1;i<=x+1;i++) { for(int j=y-1;j<=y+1;j++) { if(x!=i||y!=j) { if(pic->getpixel(i,j).TellColor()==color.TellColor()) { num++; } } } } return num; } int AntiColor(Bmp *source,Bmp *dest) { int width=source->width(); int height=source->height(); for(int i=0;i<width;i++) { for(int j=0;j<height;j++) { Palette temp=source->getpixel(i,j); dest->pixel(i,j,Palette(~temp.Blue,~temp.Green,~temp.Red)); } } return 0; } Palette AverageColor(Bmp *source,int x,int y,int pixel) { int NumEffective=0; int width=source->width(); int height=source->height(); int Red=0,Blue=0,Green=0; for(int i=x-pixel;i<=x+pixel;i++) { for(int j=y-pixel;j<y+pixel;j++) { if(i>=0&&i<width&&j>=0&&j<height) { NumEffective++; Palette temp; temp=source->getpixel(i,j); Red+=temp.Red; Green+=temp.Green; Blue+=temp.Blue; } } } Red/=NumEffective; Green/=NumEffective; Blue/=NumEffective; return Palette(Blue,Green,Red); } int Blurry(Bmp *source,Bmp *dest,int pixel) { int width=source->width(); int height=source->height(); for(int i=0;i<width;i++) { for(int j=0;j<height;j++) { dest->pixel(i,j,AverageColor(source,i,j,pixel)); } } return 0; } int Mosaic(Bmp *source,Bmp *dest,int pixel) { int width=source->width(); int height=source->height(); for(int i=pixel;i<width+pixel;i+=2*pixel) { for(int j=pixel;j<height+pixel;j+=2*pixel) { Palette color=AverageColor(source,i,j,pixel); for(int x=i-pixel;x<=i+pixel;x++) { for(int y=j-pixel;y<=j+pixel;y++) { dest->pixel(x,y,color); } } } } return 0; }
true
727842a3f19dbebdb402aedad05ac64b35334dec
C++
WZFish/RVD-with-mutithread
/MyMesh.h
UTF-8
5,045
2.65625
3
[]
no_license
#ifndef _MY_MESH_ #define _MY_MESH_ #include "Mesh\Vertex.h" #include "Mesh\Edge.h" #include "Mesh\Face.h" #include "Mesh\HalfEdge.h" #include "Mesh\BaseMesh.h" #include "Mesh\boundary.h" #include "Mesh\iterators.h" #include "Parser\parser.h" #ifndef M_PI #define M_PI 3.141592653589793238 #endif namespace MeshLib { class CMyVertex; class CMyEdge; class CMyFace; class CMyHalfEdge; class CMyVertex : public CVertex { public: CMyVertex() : m_rgb(1,1,1) {}; ~CMyVertex() {}; void _from_string() ; void _to_string(); CPoint & rgb() { return m_rgb; }; protected: CPoint m_rgb; }; inline void CMyVertex::_from_string() { CParser parser(m_string); for (std::list<CToken*>::iterator iter = parser.tokens().begin(); iter != parser.tokens().end(); ++iter) { CToken * token = *iter; if (token->m_key == "uv") //CPoint2 { token->m_value >> m_uv; } if (token->m_key == "rgb") // CPoint { token->m_value >> m_rgb; } } } inline void CMyVertex::_to_string() { CParser parser(m_string); parser._removeToken("uv"); parser._toString(m_string); std::stringstream iss; iss << "uv=(" << m_uv[0] << " " << m_uv[1] << ")"; if (m_string.length() > 0) { m_string += " "; } m_string += iss.str(); } class CMyEdge : public CEdge { public: CMyEdge() :m_sharp(false) {}; ~CMyEdge() {}; void _from_string(); bool & sharp() { return m_sharp; }; protected: bool m_sharp; }; inline void CMyEdge::_from_string() { CParser parser(m_string); for (std::list<CToken*>::iterator iter = parser.tokens().begin(); iter != parser.tokens().end(); ++iter) { CToken * token = *iter; if (token->m_key == "sharp") // bool { m_sharp = true; } } } class CMyFace : public CFace { public: CPoint & normal() { return m_normal; }; protected: CPoint m_normal; }; class CMyHalfEdge : public CHalfEdge { }; template<typename V, typename E, typename F, typename H> class MyMesh : public CBaseMesh<V, E, F, H> { public: typedef CBoundary<V, E, F, H> CBoundary; typedef CLoop<V, E, F, H> CLoop; typedef MeshVertexIterator<V, E, F, H> MeshVertexIterator; typedef MeshEdgeIterator<V, E, F, H> MeshEdgeIterator; typedef MeshFaceIterator<V, E, F, H> MeshFaceIterator; typedef MeshHalfEdgeIterator<V, E, F, H> MeshHalfEdgeIterator; typedef VertexVertexIterator<V, E, F, H> VertexVertexIterator; typedef VertexEdgeIterator<V, E, F, H> VertexEdgeIterator; typedef VertexFaceIterator<V, E, F, H> VertexFaceIterator; typedef VertexInHalfedgeIterator<V, E, F, H> VertexInHalfedgeIterator; typedef VertexOutHalfedgeIterator<V, E, F, H> VertexOutHalfedgeIterator; typedef FaceVertexIterator<V, E, F, H> FaceVertexIterator; typedef FaceEdgeIterator<V, E, F, H> FaceEdgeIterator; typedef FaceHalfedgeIterator<V, E, F, H> FaceHalfedgeIterator; void output_mesh_info(); void test_iterator(); }; typedef MyMesh<CMyVertex, CMyEdge, CMyFace, CMyHalfEdge> CMyMesh; template<typename V, typename E, typename F, typename H> void MeshLib::MyMesh<V, E, F, H>::output_mesh_info() { int nv = this->numVertices(); int ne = this->numEdges(); int nf = this->numFaces(); std::cout << "#V=" << nv << " "; std::cout << "#E=" << ne << " "; std::cout << "#F=" << nf << " "; int euler_char= nv - ne + nf; std::cout << "Euler's characteristic=" << euler_char << " "; CBoundary boundary(this); std::vector<CLoop*> & loops = boundary.loops(); int nb = loops.size(); int genus = (2 - (euler_char + nb)) / 2; std::cout << "genus=" << genus << std::endl; } template<typename V, typename E, typename F, typename H> void MyMesh<V, E, F, H>::test_iterator() { for (MeshVertexIterator viter(this); !viter.end(); ++viter) { V * pV = *viter; // you can do something to the vertex here // ... for (VertexEdgeIterator veiter(pV); !veiter.end(); ++veiter) { E * pE = *veiter; // you can do something to the neighboring edges with CCW // ... } for (VertexFaceIterator vfiter(pV); !vfiter.end(); ++vfiter) { F * pF = *vfiter; // you can do something to the neighboring faces with CCW // ... } for (VertexInHalfedgeIterator vhiter(this, pV); !vhiter.end(); ++vhiter) { H * pH = *vhiter; // you can do something to the incoming halfedges with CCW // ... } } for (MeshEdgeIterator eiter(this); !eiter.end(); ++eiter) { E * pE = *eiter; // you can do something to the edge here // ... } for (MeshFaceIterator fiter(this); !fiter.end(); ++fiter) { F * pF = *fiter; // you can do something to the face here // ... } //there are some other iterators which you can find them in class MyMesh std::cout << "Iterators test OK.\n"; } } #endif // !_MY_MESH_
true
e1acbda210dafeb908731d47be590f1bb42af24a
C++
l740416/Arduino-Log
/Log.cpp
UTF-8
2,857
2.8125
3
[]
no_license
#include "Arduino.h" #include <stdarg.h> #include "Log.h" Log::Log() { memset( buf, '\0', sizeof(buf) ); idx = 0; m_pHourFunc = NULL; m_pMinuteFunc = NULL; m_pSecondFunc = NULL; m_overridesHeading = false; m_lastHour = -1; m_lastMinute = -1; m_lastSecond = -1; } Log::Log(LOG_TIME_FUNC hour_func, LOG_TIME_FUNC minute_func, LOG_TIME_FUNC second_func) { memset( buf, '\0', sizeof(buf) ); idx = 0; m_pHourFunc = hour_func; m_pMinuteFunc = minute_func; m_pSecondFunc = second_func; if(m_pHourFunc != NULL && m_pMinuteFunc != NULL && m_pSecondFunc != NULL) { m_overridesHeading = true; } } size_t Log::write(uint8_t v) { buf[idx] = v; idx += 1; buf[idx] = '\0'; if( idx >= LOG_SIZE ) { idx = 0; buf[0] = '\0'; } Serial.write( v ); return 1; } size_t Log::write(const char *str) { return write( ( const uint8_t * ) str, strlen(str) ); } size_t Log::write(const uint8_t *buffer, size_t size) { if(m_overridesHeading == true) { if( size >= 5 && buffer[0] == '[' && buffer[1] == 'M' && buffer[2] == 'S' && buffer[3] == 'G' && buffer[4] == ']' ) { char str[64]; if ((m_lastHour == m_pHourFunc()) && (m_lastMinute == m_pMinuteFunc()) && (m_lastSecond == m_pSecondFunc())) { snprintf(str, 64, "\t"); } else { m_lastHour = m_pHourFunc(); m_lastMinute = m_pMinuteFunc(); m_lastSecond = m_pSecondFunc(); snprintf(str, 64, "[%02d%02d%02d]", m_lastHour, m_lastMinute, m_lastSecond); } write( str ); write( buffer + 5, size - 5 ); return size - 5 + strlen(str); } } for(size_t i = 0; i < size; i++) { write(buffer[i]); } return size; } size_t Log::printf( char const *fmt, ... ) { va_list arg; va_start(arg, fmt); char temp[64]; char* buffer = temp; size_t len = vsnprintf(temp, sizeof(temp), fmt, arg); va_end(arg); if (len > sizeof(temp) - 1) { buffer = new char[len + 1]; if (!buffer) { return 0; } va_start(arg, fmt); vsnprintf(buffer, len + 1, fmt, arg); va_end(arg); } len = write((const uint8_t*) buffer, len); if (buffer != temp) { delete[] buffer; } return len; } #ifdef F // check to see if F() macro is available size_t Log::printf(const __FlashStringHelper *fmt, ...) { va_list arg; va_start(arg, fmt); char temp[64]; char* buffer = temp; size_t len = vsnprintf_P(temp, sizeof(temp), (PGM_P)fmt, arg); va_end(arg); if (len > sizeof(temp) - 1) { buffer = new char[len + 1]; if (!buffer) { return 0; } va_start(arg, fmt); vsnprintf_P(buffer, len + 1, (PGM_P)fmt, arg); va_end(arg); } len = write((const uint8_t*) buffer, len); if (buffer != temp) { delete[] buffer; } return len; } #endif
true
de3309ae6d1971cd5611ec59cdd6105e52ba6cf2
C++
UFRN-IFRN/IOAC-cache
/include/files.h
UTF-8
594
2.75
3
[]
no_license
/** * @file files.h * @brief Arquivo cabecalho com a definicao de funcoes para leitura do arquivo com os dados de entrada * @author Bianca Santiago (bianca.santiago72@gmail.com) * @since 07/06/2017 * @date 14/06/2017 */ #ifndef FILES_H #define FILES_H #include "cache.h" #include <iostream> using std::cout; using std::cin; using std::endl; using std::stoi; #include <fstream> using std::ifstream; using std::string; using std::getline; /** * @brief Funcao que le arquivo e joga numa variavel do tipo Cache * @param file Arquivo * @return Uma Cache */ Cache* lerArquivo(string file); #endif
true
1d47e158b26ca6df73b386ee59872ac2342b6769
C++
rrodriguez125/RodriguezRicardo_CSC5_41202
/homework/assignment 3/finished folder/Savitch_9thEd_Chap3_ProjectProb 2/main.cpp
UTF-8
2,606
3.375
3
[]
no_license
/* * File: main.cpp * Author: Ricardo Rodriguez * Created on January 4, 2016, 10:18 AM * Purpose: solving quadratic equation */ //System Libraries #include <iostream> #include <cmath> using namespace std; //User Libraries //Global Constants //Function Prototypes //Execution Begins Here int main(int argc, char** argv) { //declare question char questn; //Question, does player want to play again? //loop until player wants to quite do{ //problem to solve cout<<"Solution to Savitch 9thEd Chap3 ProjectProb 2"<<endl; cout<<"Solving quadratic equation"<<endl<<endl; //Declare and initialize variables float valueA,valueB,valueC,result1,result2;//values for variables of equation //Input Data cout<<"The quadratic equation is ax^2 + bx + c = 0"<<endl; cout<<"Input a value for a"<<endl; cin>>valueA; cout<<"Input a value for b"<<endl; cin>>valueB; cout<<"Input a value for c"<<endl; cin>>valueC; //calculate or map inputs to outputs result1=(pow(valueB,2)-4*valueA*valueC); result2=(-valueB+sqrt(pow(valueB,2)-4*valueA*valueC))/(2*valueA); //Output if(result1<0){ cout<<"There are two complex results of your equation." <<endl; cout<<"result 1 = (" <<-valueB<<"+i*sqrt("<<-result1<<"))/(2*"<<valueA<<")"<<endl; cout<<"result 2 = (" <<-valueB<<"-i*sqrt("<<-result1<<"))/(2*"<<valueA<<")"<<endl; }if(result1>0){ cout<<"There are two results of your equation." <<endl; cout<<"result 1 = (" <<-valueB<<"+sqrt("<<result1<<"))/(2*"<<valueA<<")"<<endl; cout<<"result 2 = (" <<-valueB<<"-sqrt("<<result1<<"))/(2*"<<valueA<<")"<<endl; }if(result1==0){ cout<<"There is one result to the equation." <<endl; cout<<"result = (" <<-valueB<<")/(2*"<<valueA<<")"<<endl; } //Keep playing, end of loop cout<<endl<<"Do you want to repeat the program?"<<endl; cout<<"Enter Y or N"<<endl; cin>>questn; }while(toupper(questn)=='Y'); //Exit stage right return 0; }
true
062f3f75c82598d2262a39a2f082508eacce972a
C++
AnkaChan/MyTestCodes
/PointerVSIndex/main.cpp
UTF-8
1,207
3.328125
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <ctime> using std::cout; using std::endl; using std::vector; typedef std::vector<int> MyVec; #define NUM 100000000 #define LOOP 1000 struct WithPointer { int * p; }; struct WithIndex { int index; }; int main(int argc, char** argv) { MyVec vec(NUM); int a = 0; for (int & i : vec) { i = ++a; } vector<WithIndex> indexVec(NUM); for (size_t i = 0; i < NUM; i++) { indexVec[i].index = i; } vector<WithPointer> pointerVec(NUM); for (size_t i = 0; i < NUM; i++) { pointerVec[i].p = &vec[i]; } int sum = 0; clock_t time1; clock_t startTime = clock(); for (size_t k = 0; k < LOOP; k++) { for (size_t i = 0; i < NUM; i++) { sum += vec[indexVec[i].index]; } } clock_t endTime = clock(); time1 = endTime - startTime; cout << "Time comsumed using index: " << time1 << endl; cout << sum << endl; sum = 0; clock_t time2; startTime = clock(); for (size_t k = 0; k < LOOP; k++) { for (size_t i = 0; i < NUM; i++) { sum += *pointerVec[i].p; } } endTime = clock(); time2 = endTime - startTime; cout << "Time comsumed using pointer: " << time2 << endl; cout << sum << endl; getchar(); }
true
d87d7cdb442dd11f2ad463f10f6cb1827c95a95b
C++
zhouhesheng/ndisapi
/examples/cpp/dns_proxy/dns_proxy.cpp
UTF-8
1,719
2.78125
3
[ "MIT" ]
permissive
// dns_proxy.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include <iostream> void log_printer(const char* log) { static std::mutex log_lock; // NOLINT(clang-diagnostic-exit-time-destructors) std::lock_guard<std::mutex> lock(log_lock); std::cout << log << std::endl; } int main() { try { std::string dns_address; std::cout << std::endl << "DNS server IP address to forward requests to: "; std::cin >> dns_address; auto dns_server_ip_address_v4 = net::ip_address_v4(dns_address); // Redirects all DNS packet to dns_server_ip_address_v4:53 ndisapi::udp_proxy_server<ndisapi::udp_proxy_socket<net::ip_address_v4>> proxy([&dns_server_ip_address_v4]( const net::ip_address_v4 local_address, const uint16_t local_port, const net::ip_address_v4 remote_address, const uint16_t remote_port)-> std::tuple<net::ip_address_v4, uint16_t, std::unique_ptr<ndisapi::udp_proxy_server<ndisapi:: udp_proxy_socket<net::ip_address_v4>>::negotiate_context_t>> { if (remote_port == 53) { std::cout << "Redirecting DNS " << local_address << ":" << local_port << " -> " << remote_address << ":" << remote_port << " to " << dns_server_ip_address_v4 << ":53\n"; return std::make_tuple(dns_server_ip_address_v4, 53, nullptr); } return std::make_tuple(net::ip_address_v4{}, 0, nullptr); }, dns_server_ip_address_v4, log_printer, ndisapi::log_level::all); proxy.start(); std::cout << "Press any key to stop filtering" << std::endl; std::ignore = _getch(); std::cout << "Exiting..." << std::endl; } catch(const std::exception& ex) { std::cout << "exception occurred: " << ex.what() << std::endl; } return 0; }
true
eff72479205c136ffd6c7dcbe4a340938a31bf36
C++
Lumingei/Summer
/数组16-不同路径 .cpp
GB18030
1,521
4.15625
4
[]
no_license
/*ͬ· һλһ m x n Ͻ ʼͼбΪStart ÿֻ»ƶһͼﵽ½ǣͼбΪFinish ܹжͬ· 磬ͼһ7 x 3 жٿܵ· ʾ1: : m = 3, n = 2 : 3 : Ͻǿʼܹ 3 ·Ե½ǡ 1. -> -> 2. -> -> 3. -> -> */ int uniquePaths(int m, int n){ int **a=(int **)malloc(sizeof(int*)*m); //̬ά飬öָʵ֣ for(int i=0;i<m;i++){ //ʾ꣬ӦӦֵʾܵ˵· a[i]=(int *)malloc(sizeof(int)*n); for(int j=0;j<n;j++){ if(i==0 || j==0) a[i][j]=1; //һк͵һеĵӦ·ֻ1 else a[i][j]=a[i-1][j]+a[i][j-1]; //ÿһֵΪߺϱߵֵ } } return a[m-1][n-1]; } /*ָ붯̬ά飺 52е飺 int **p = (int **)malloc(sizeof(int *) * 5); for (int i = 0; i < 5; ++i) { p[i] = (int *)malloc(sizeof(int) * 2); } */
true
c0bdda1c07803e2838dbf5276ae4af5d6f024927
C++
mkbiltek/WISeID-For-Windows
/FaceSDK/ColourNormalisation.cpp
UTF-8
7,885
2.671875
3
[]
no_license
#include "ColourNormalisation.h" CColourNormalisation::CColourNormalisation() { } CColourNormalisation::~CColourNormalisation() { } //Single channel images //calculate mean of value pixels float CColourNormalisation::mean(const IplImage *pIplImage) { int w = pIplImage->width; int h = pIplImage->height; //int ws = pIplImage->widthStep; int i,j; float add=0; int count =0; for(i = 0; i<h; i++) { uchar* data = (uchar*)(pIplImage->imageData+pIplImage->widthStep*i); for(j =0; j<w; j++) { add += data[j]; count++; } } add = add/(1.0*count); return add; } //compute deviation standard all of pixels float CColourNormalisation::DeviationStandard(const IplImage * pIplImage) { float m = mean(pIplImage); int w = pIplImage->width; int h = pIplImage->height; //int ws = pIplImage->widthStep; int i,j; float sad=0; int count =0; for(i = 0; i<h; i++) { uchar* data = (uchar*)(pIplImage->imageData+pIplImage->widthStep*i); for(j =0; j<w; j++) { sad += (data[j] - m)*(data[j]-m); count++; } } sad = sad/count; sad=sqrt((double)sad); return sad; } //compute devmean of color image bool CColourNormalisation::calcDevMeanImage(const IplImage *pIplImage, ColourDevMean &_colorDevMean) { if(pIplImage->nChannels == 1) return false; IplImage *red = cvCreateImage(cvGetSize(pIplImage),pIplImage->depth, 1); IplImage *green = cvCreateImage(cvGetSize(pIplImage),pIplImage->depth, 1); IplImage *blue = cvCreateImage(cvGetSize(pIplImage),pIplImage->depth, 1); cvSplit(pIplImage, red, green, blue, NULL); float red_mean = mean(red); float green_mean = mean(green); float blue_mean = mean(blue); float red_dev = DeviationStandard(red); float green_dev = DeviationStandard(green); float blue_dev = DeviationStandard(blue); _colorDevMean.channel1.dev = red_dev; _colorDevMean.channel1.mean = red_mean; _colorDevMean.channel2.dev = green_dev; _colorDevMean.channel2.mean = green_mean; _colorDevMean.channel3.dev = blue_dev; _colorDevMean.channel3.mean = blue_mean; cvReleaseImage( &red); cvReleaseImage( &green); cvReleaseImage( &blue); return true; } //colour normalisation of src1 image with src2 to be target image //dst: result of src1 before processing //only perform with single image void CColourNormalisation::ReinhardNormalisation(const IplImage* src1, const IplImage* src2, IplImage *&dst) { int w = src1->width; int h = src1->height; //int ws = src1->widthStep; CvSize size = cvSize(w,h); int i,j; dst = cvCreateImage(size, src1->depth, 1); float mean_origin = mean(src1); float dev_origin = DeviationStandard(src1); float mean_target = mean(src2); float dev_target = DeviationStandard(src2); float tmp; for(i = 0; i<h; i++) { uchar* data1 = (uchar*)(src1->imageData+ src1->widthStep*i); uchar*data2 = (uchar*)(dst->imageData + dst->widthStep*i); for(j =0; j<w; j++) { tmp = (((1.0*data1[j]-mean_origin)/dev_origin)*dev_target+mean_target); data2[j] = (tmp>255?255:tmp)<0?0:(tmp>255?255:tmp); } } } //colour normalisation of src1 image //@mean_target:mean of target image //@dev_target:deviation of target image //dst: result of src1 before processing //only perform with single channel image void CColourNormalisation::ReinhardNormalisation(const IplImage* src1, const float mean_target, const float dev_target, IplImage *&dst) { int w = src1->width; int h = src1->height; //int ws = src1->widthStep; CvSize size = cvSize(w,h); int i,j; float mean_origin = mean(src1); float dev_origin = DeviationStandard(src1); if( !dst) dst = cvCreateImage(size, src1->depth, 1); float tmp; for(i = 0; i<h; i++) { uchar* data1 = (uchar*)(src1->imageData+ src1->widthStep*i); uchar*data2 = (uchar*)(dst->imageData + dst->widthStep*i); for(j =0; j<w; j++) { tmp = (((1.0*data1[j]-mean_origin)/dev_origin)*dev_target+mean_target); data2[j] = (tmp>255?255:tmp)<0?0:(tmp>255?255:tmp); } } } void CColourNormalisation::ColourNormalisation(const IplImage* src1, const IplImage* src2, IplImage *&dst) { if(src1->nChannels == 1|| src2->nChannels ==1) return; int w1 = src1->width; int h1 = src1->height; //int ws1 = src1->widthStep; int w2 = src2->width; int h2 = src2->height; //int ws2 = src2->widthStep; IplImage *red1 = cvCreateImage(cvSize(w1,h1), src1->depth, 1) ; IplImage *green1 = cvCreateImage(cvSize(w1,h1), src1->depth, 1) ; IplImage *blue1 = cvCreateImage(cvSize(w1,h1), src1->depth, 1) ; IplImage *red2 = cvCreateImage(cvSize(w2,h2), src2->depth, 1) ; IplImage *green2 = cvCreateImage(cvSize(w2,h2), src2->depth, 1) ; IplImage *blue2 = cvCreateImage(cvSize(w2,h2), src2->depth, 1) ; cvSplit(src1, red1, green1, blue1, NULL); cvSplit(src2, red2, green2, blue2, NULL); IplImage *redd=0,*greend =0,*blued =0; ReinhardNormalisation(red1, red2, redd); ReinhardNormalisation(green1, green2, greend); ReinhardNormalisation(blue1, blue2, blued); dst = cvCreateImage(cvSize(w1,h1), src1->depth, src1->nChannels); cvMerge(redd, greend, blued, NULL, dst); cvReleaseImage( &red1); cvReleaseImage( &red2); cvReleaseImage( &redd); cvReleaseImage( &green1); cvReleaseImage( &green2); cvReleaseImage( &greend); cvReleaseImage( &blue1); cvReleaseImage( &blue2); cvReleaseImage( &blued); } void CColourNormalisation::ColourNormalisation(const IplImage* src1, IplImage *&dst) { if(src1->nChannels == 1) return; int w1 = src1->width; int h1 = src1->height; //int ws1 = src1->widthStep; IplImage *red1 = cvCreateImage(cvSize(w1,h1), src1->depth, 1) ; IplImage *green1 = cvCreateImage(cvSize(w1,h1), src1->depth, 1) ; IplImage *blue1 = cvCreateImage(cvSize(w1,h1), src1->depth, 1) ; cvSplit(src1, red1, green1, blue1, NULL); IplImage *redd=0,*greend =0,*blued =0; ReinhardNormalisation(red1, m_colorDevMean.channel1.mean,m_colorDevMean.channel1.dev, redd); ReinhardNormalisation(green1, m_colorDevMean.channel2.mean,m_colorDevMean.channel2.dev, greend); ReinhardNormalisation(blue1, m_colorDevMean.channel3.mean,m_colorDevMean.channel3.dev, blued); dst = cvCreateImage(cvSize(w1,h1), src1->depth, src1->nChannels); cvMerge(redd, greend, blued, NULL, dst); cvReleaseImage( &red1); red1 = 0; cvReleaseImage( &redd); redd = 0; cvReleaseImage( &green1); green1 = 0; cvReleaseImage( &greend); greend = 0; cvReleaseImage( &blue1); blue1 = 0; cvReleaseImage( &blued); blued = 0; } bool CColourNormalisation::save(const IplImage *pIplImage, const char* file) { if(pIplImage->nChannels == 1) return false; bool res = calcDevMeanImage(pIplImage, m_colorDevMean); if(!res) return false; FILE *f = fopen(file,"w+b"); if(!f) { fclose(f); return false; } fprintf(f,"%.5f\n",m_colorDevMean.channel1.mean); fprintf(f,"%.5f\n",m_colorDevMean.channel1.dev); fprintf(f,"%.5f\n",m_colorDevMean.channel2.mean); fprintf(f,"%.5f\n",m_colorDevMean.channel2.dev); fprintf(f,"%.5f\n",m_colorDevMean.channel3.mean); fprintf(f,"%.5f\n",m_colorDevMean.channel3.dev); fclose(f); return true; } bool CColourNormalisation::load(const char* file ) { FILE *f = fopen(file,"r+b"); if(!f) { return false; } fscanf(f,"%f",&m_colorDevMean.channel1.mean); fscanf(f,"%f",&m_colorDevMean.channel1.dev); fscanf(f,"%f",&m_colorDevMean.channel2.mean); fscanf(f,"%f",&m_colorDevMean.channel2.dev); fscanf(f,"%f",&m_colorDevMean.channel3.mean); fscanf(f,"%f",&m_colorDevMean.channel3.dev); fclose(f); return true; } void CColourNormalisation::crtInvariant(const IplImage* src, IplImage *&dst) { int w = src->width; int h = src->height; if( !dst) { dst = cvCreateImage( cvSize(w,h), IPL_DEPTH_8U, 1); cvZero(dst); } IplImage *YCrCb = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 3); cvCvtColor(src, YCrCb, CV_BGR2YCrCb); cvSplit(YCrCb,NULL, dst,NULL,NULL); cvReleaseImage( &YCrCb); ReinhardNormalisation(dst, 96.75304, 38.55432, dst); } //////////////////////////////////////////////////////////////////////////
true
6548c481a7aadef112f300a5870a7be97c645396
C++
PeterZosch/ti2_cpp_projects
/Aufgabe1/src/versions/main_v1.0.cpp
UTF-8
3,132
2.765625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <fstream> #include <cstdlib> using namespace std; //Funktionsprototypen void fileHandling(int); void tableFunc(); void inlineEdit(); void changeLine(); void insertLine(); void deleteLine(); void searchString(); int main() { char key; int mode=0; // 0=open, 1=save do{ system("clear"); cout << endl << "Hautpmenue"; cout << endl << "----------"; cout << endl << "(o) Datei oeffnen"; cout << endl << "(t) Tabellenfunktion"; cout << endl << "(q) Quit"; cout << endl << (">"); cin.ignore(); cin >> key; switch(key){ case 'o': fileHandling(mode); break; case 't': inlineEdit(); break; case 'q': return 0; default : cout << "Falsche Eingabe"; // nanosleep(1000); } }while(key != 'q'); return 0; } /* Funktion um eine Datei zu öffnen und speichern, falls noch nicht vorhanden wird sie Erstellt. Datei existiert und besitzt Inhalt: Zeilen werden gezählt und als pointer zur Verfügung gestellt Der inhalt wird in den Hauptspeicher gelesen vi der Vector-Klasse und die Datei geschlossen Datei existiert nicht: Vector-Klasse wird erstellt aber ohne Inhalt */ void fileHandling(int mode) { } void inlineEdit() { int next=1; char key; do{ system("clear"); cout << "(r)ück, (v)or | (a)endern, (e)infuegen, (l)oeschen, (s)uchen | sa(v)e | (b)ack"; cout.fill ('-'); cout.width (80); for(int i = 1; i <= lines; i++){ getline(inputf, buffer); if( i == vor){ cout << i << "\t" << buffer << endl; }else if(vor > lines){ cout << "Dateiende" << endl; break; } } /* for(i(= 1; i <= *p_lineCnt; i++){ if (fgets(streambuffer, sizeof(streambuffer), stream) != NULL && i == next ){ printf("\n Z%i %s\n", i, streambuffer); aktline++; } else if(next>*p_lineCnt){ printf("\n ***Dateiende***\n"); break; } } cout << " ****************************************************************************"; */ // cout <<""; cout.fill ('-'); cout.width (80); cout << endl << "\n>"; cin.ignore(); cin >> key; switch(key){ case 'v': next++; // if (next>=*p_lineCnt+1){ // next=*p_lineCnt+1;} break; case 'r': next--; // if (next<=1){ // next=1;} break; // case 'a': changeLine(); // aktline=0; // break; // case 'e': insertLine(); // aktline=0; // break; // case 'l': deleteLine(); // aktline=0; // break; // case 's': searchString(); // break; // case 'v': mode = 1 //speichermodus aktivieren // fileHandling(mode); // break; case 'b': return 0; default: cout << "Falsche Eingabe"; } }while(key != 'q'); }
true
8f6769b74efff832f711ce2ed8204f83e408a227
C++
siberiy4/comp_prog
/ABC031/second.cpp
UTF-8
320
2.609375
3
[]
no_license
#include<iostream> using namespace std; int main(){ int L,H; int N; cin>>L>>H>>N; for(int i=0;i<N;++i){ int tmp; cin>>tmp; if(L>tmp){ cout<<L-tmp<<endl; }else if(H<tmp){ cout<<-1<<endl; }else{ cout<<0<<endl; } } }
true
9e636936653f2e4c6e495461605aab8b9eaaf29b
C++
Huvok/Competitive-Programming
/Codeforces/800/869/C. The Intriguing Obsession.cpp
UTF-8
2,163
2.515625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <functional> #include <queue> #include <bitset> #include <sstream> #include <set> #include <iomanip> #include <string.h> #include <unordered_map> #include <unordered_set> using namespace std; // //AUTHOR: Hugo Garcia // //PURPOSE: Competitive programming template //====================================================================================================================== #define FOR(i, a, b) for(ll i=ll(a); i<ll(b); i++) #define pb push_back #define mp make_pair #define lld I64d typedef long long ll; typedef vector<ll> vi; typedef pair<ll, ll> ii; typedef vector<ii> vii; //---------------------------------------------------------------------------------------------------------------------- ll fact[5005], rfact[5005]; ll NK(int N, int K) { return fact[N] * rfact[K] % 998244353 * rfact[N - K] % 998244353; } ll fastPow(ll x, ll n) { ll ret = 1; while (n) { if (n & 1) ret = ret*x% 998244353; x = x*x% 998244353; n >>= 1; } return ret; } //---------------------------------------------------------------------------------------------------------------------- #define MOD 998244353 int main() { fact[0] = 1; FOR(i, 1, 5005) fact[i] = fact[i - 1] * i % 998244353; rfact[5005 - 1] = fastPow(fact[5005 - 1], 998244353 - 2); for (int i = 5005 - 2; i >= 0; i--) rfact[i] = rfact[i + 1] * (i + 1) % 998244353; ll a, b, c; cin >> a >> b >> c; ll ans1 = 0, ans2 = 0, ans3 = 0; FOR(intI, 0, min(a, b) + 1) { ans1 += (NK(a, intI) % MOD * NK(b, intI) % MOD * fact[intI] % MOD); ans1 %= MOD; } FOR(intI, 0, min(b, c) + 1) { ans2 += (NK(b, intI) % MOD * NK(c, intI) % MOD * fact[intI] % MOD); ans2 %= MOD; } FOR(intI, 0, min(c, a) + 1) { ans3 += (NK(c, intI) % MOD * NK(a, intI) % MOD * fact[intI] % MOD); ans3 %= MOD; } cout << ans1 % MOD * ans2 % MOD * ans3 % MOD << endl; return 0; } //======================================================================================================================
true
67563aa86f15e1d6004d07b90b7681fda38313f1
C++
zinsmatt/test-Neural-Net
/Neural_Networks/hiddenlayer.h
UTF-8
462
2.65625
3
[]
no_license
#ifndef HIDDENLAYER_H #define HIDDENLAYER_H #include "layer.h" class HiddenLayer : public Layer { public: HiddenLayer(NeuralNet* _neuralNet, int numberofneurons, ActivationFunction fnc, int numberofinputs); /** * @brief setPreviousLayer * @param prev */ virtual void setPreviousLayer(Layer* prev); /** * @brief setNextLayer * @param next */ virtual void setNextLayer(Layer* next); }; #endif // HIDDENLAYER_H
true
5175b014c080fe4d8cbe59c60faaf4f3422995fa
C++
JFengWu/Cpp-homework
/cpp-homework3/Q112/Source.cpp
UTF-8
1,526
3.65625
4
[]
no_license
#include <iostream> using namespace std; class Operation { private: double NumberA; double NumberB; public: virtual double GetResult() { return 0; }; double getA() { return NumberA; } void setA(double _NumberA) { NumberA = _NumberA; } double getB() { return NumberB; } void setB(double _NumberB) { NumberB = _NumberB; } }; class OperationAdd : public Operation { public: double GetResult() override { return getA() + getB(); } }; class OperationSub : public Operation { public: double GetResult() override { return getA() - getB(); } }; class OperationMul : public Operation { public: double GetResult() override { return getA() * getB(); } }; class OperationDiv : public Operation { public: double GetResult() override { return getB() == 0 ? -1 : getA() / getB(); } }; class OperationFactory { public: Operation *CreateOperation(const char &oper) { Operation *ret; switch (oper) { case '+': ret = new OperationAdd(); break; case '-': ret = new OperationSub(); break; case '*': ret = new OperationMul(); break; case '/': ret = new OperationDiv(); break; default: ret = NULL; break; } return ret; } }; int main(int argc, char *argv[]) { char oper; cin >> oper; Operation *operation = new Operation; OperationFactory operationFactory; operation = operationFactory.CreateOperation(oper); double a; cin >> a; operation->setA(a); double b; cin >> b; operation->setB(b); cout << operation->GetResult() << endl; return 0; }
true
e7e9d6f2eab8a0d72c3da574a8e68e8b3de2353f
C++
ClysmiC/RTWeekend
/src/main.h
UTF-8
5,623
2.53125
3
[]
no_license
#pragma once #include "als/als.h" #include <ostream> struct IHittable; struct IMaterial; struct BvhNode; enum KZERO { kZero }; struct Vector3 { union { struct { float x; float y; float z; }; float elements[3]; }; Vector3() : x(0), y(0), z(0) { } Vector3(KZERO) : x(0), y(0), z(0) { } Vector3(float x, float y, float z) : x(x), y(y), z(z) { } float length() const; float lengthSquared() const; void normalizeInPlace(); }; float dot(const Vector3 & lhs, const Vector3 & rhs); Vector3 cross(const Vector3 & lhs, const Vector3 & rhs); Vector3 normalize(const Vector3 & v); Vector3 operator+(const Vector3 & v); Vector3 operator-(const Vector3 & v); void operator+=(Vector3 & vLeft, const Vector3 & vRight); void operator-=(Vector3 & vLeft, const Vector3 & vRight); void operator*=(Vector3 & v, float scale); void operator/=(Vector3 & v, float scale); Vector3 operator+ (const Vector3 & vLeft, const Vector3 & vRight); Vector3 operator- (const Vector3 & vLeft, const Vector3 & vRight); Vector3 hadamard(const Vector3 & vLeft, const Vector3 & vRight); Vector3 operator* (const Vector3 & v, float f); Vector3 operator* (float f, const Vector3 & v); Vector3 operator/ (const Vector3 & v, float f); std::ostream & operator<<(std::ostream & outputStream, const Vector3 & vector); Vector3 randomVectorInsideUnitSphere(); Vector3 randomVectorInsideUnitDisk(); Vector3 reflect(const Vector3 & v, const Vector3 & n); bool refractWithSchlickProbability(const Vector3 & v, const Vector3 & n, float refractionIndexFrom, float refractionIndexTo, Vector3 * vecOut); float rand0Incl1Excl(); template<typename T> inline float lerp(T val0, T val1, float t) { return val0 + t * (val1 - val0); } struct Ray { Vector3 p0; Vector3 dir; float time; // Scene time. Not to be confused with parametric "t" Ray() : p0(), dir(), time() { } Ray(Vector3 p0, Vector3 dir, float time) : p0(p0), dir(normalize(dir)), time(time) { } Vector3 pointAtT(float t) const; // Vector3 color(IHittable ** aHittable, int cHittable, int rayDepth) const; Vector3 color(BvhNode * bvhNode, int rayDepth) const; }; struct Aabb { Vector3 min; Vector3 max; Aabb() : min(), max() { }; Aabb(Vector3 p0, Vector3 p1); Aabb(Aabb aabb0, Aabb aabb1); bool testHit(const Ray & ray, float tMin, float tMax) const; }; struct Camera { Vector3 pos; Vector3 forward; Vector3 right; Vector3 up; float fovDeg; float aspectRatio; float lensRadius; // Motion blur float time0; float time1; // Cached view plane information Vector3 botLeftViewPosCached; Vector3 topRightViewPosCached; float wCached; float hCached; Camera( Vector3 pos, Vector3 lookat, float fovDeg, float aspectRatio, float lensRadius, float time0, float time1); Ray rayAt(float s, float t); }; struct HitRecord { float t; Vector3 normal; const IHittable * hittable; HitRecord() : t(0), normal(), hittable(nullptr) {} }; struct IHittable { IMaterial * material; IHittable(IMaterial * material) : material(material) { } virtual bool testHit(const Ray & ray, float tMin, float tMax, HitRecord * hitOut) const = 0; virtual bool tryComputeBoundingBox(float t0, float t1, Aabb * aabbOut) const = 0; }; struct Sphere : public IHittable { Vector3 p0Center; Vector3 velocity; float radius; Sphere(Vector3 p0Center, float radius, IMaterial * material, Vector3 velocity) : IHittable(material) , p0Center(p0Center) , radius(radius) , velocity(velocity) { } bool testHit(const Ray & ray, float tMin, float tMax, HitRecord * hitOut) const override; bool tryComputeBoundingBox(float t0, float t1, Aabb * aabbOut) const override; Vector3 posAtTime(float time) const; }; struct BvhNode : public IHittable { IHittable * left; IHittable * right; Aabb aabb; BvhNode(IHittable * left, IHittable * right, float time0, float time1); bool testHit(const Ray & ray, float tMin, float tMax, HitRecord * hitOut) const override; bool tryComputeBoundingBox(float t0, float t1, Aabb * aabbOut) const override; }; BvhNode * buildBvh(IHittable ** aHittable, int cHittable, float time0, float time1); struct IMaterial { virtual bool scatter(const Ray & ray, const HitRecord & hitRecord, Vector3 * attenuationOut, Ray * rayScatteredOut) const = 0; }; struct LambertianMaterial : public IMaterial { Vector3 albedo; LambertianMaterial(const Vector3 & albedo) : albedo(albedo) { } bool scatter(const Ray & ray, const HitRecord & hitRecord, Vector3 * attenuationOut, Ray * rayScatteredOut) const override; }; struct MetalMaterial : public IMaterial { Vector3 albedo; float fuzziness; MetalMaterial(const Vector3 & albedo, float fuzziness) : albedo(albedo), fuzziness(fuzziness) { } bool scatter(const Ray & ray, const HitRecord & hitRecord, Vector3 * attenuationOut, Ray * rayScatteredOut) const override; }; struct DielectricMaterial : public IMaterial { float refractiveIndex; DielectricMaterial(float refractiveIndex) : refractiveIndex(refractiveIndex) { } bool scatter(const Ray & ray, const HitRecord & hitRecord, Vector3 * attenuationOut, Ray * rayScatteredOut) const override; };
true
888c1e565b6d1dbb03f6a3456ee91f22c1e1e480
C++
Coolxer/Logomotive-X
/Logomotive/CmdManager.cpp
UTF-8
930
2.953125
3
[]
no_license
#include "stdafx.h" #include "CmdManager.h" CmdManager::CmdManager() { } void CmdManager::checkCommand() { isGood = true; if (command == "exit") onExit(); else if (command == "help") onHelp(); else if (command == "a") std::cout<<"a"; else if (command == "b") std::cout << "b"; else if (command == "c") std::cout << "c"; else if (command == "d") std::cout << "d"; else if (command == "") { std::cout << "Write in any command!" << std::endl; isGood = false; } else { onWrongCmd(); isGood = false; } } void CmdManager::onExit() { exit(EXIT_SUCCESS); } void CmdManager::onWrongCmd() { std::cout << "Command not found." << std::endl; std::cout << "To see available commands insert help." << std::endl; } void CmdManager::onHelp() { std::cout << "Here are the commands you can use: " << std::endl; std::cout << "cls" << std::endl << "exit" << std::endl << "..." << std::endl << "help"; }
true
23a2ac8b64d3a20fc3c15909e54a932574438b5a
C++
amahi2001/335-project-4
/spell_check.cc
UTF-8
5,135
3.46875
3
[]
no_license
// Abrar Mahi. #include "quadratic_probing.h" #include "linear_probing.h" #include "double_hashing.h" #include <iostream> #include <fstream> #include <string> using namespace std; int testSpellingWrapper(int argument_count, char **argument_list) { const string document_filename(argument_list[1]); const string dictionary_filename(argument_list[2]); HashTable<string> dictionary; //instantiating dictionary hash table string line, word, temp, arr = " -> "; bool apostrophe = false; //checks if there's an apostrophe in the word //opening document and dictionary files and printing error messaged if either of them fail to open ifstream doc(document_filename), dict(dictionary_filename);; if (doc.fail()) { cerr << "couldn't open document file" << endl; exit(1); } if (dict.fail()) { cerr << "couldn't open dictionary file" << endl; exit(1); } //inserting words from dictionary into hash table while (dict >> line) { dictionary.Insert(line); } //checking words for apostrophes and turning letters lowercase while (doc >> line) { //creating an empty string word = ""; //traversing through the letters in each word for (auto x : line) { //setting each letter to be lowercase x = tolower(x); //if one of the chars is an apostrophe: set the flag to be true if ('\'' == x) { apostrophe = true; } //if the chars are all lowercase, add the letters to the empty string if ((x <= 'z') && (x >= 'a')) { word += x; } } //reset the temp string temp = word; //if there is no apostrophe if (apostrophe == false) { //if the hash table contains the temp word, print if it is correct if (dictionary.Contains(temp) == true) { cout << word << " is correct" << endl; } //else if the word doesn't exist in the hash table, print it isnt correct else { cout << word << " is not correct" << endl; int size = word.size(); //for case a //iterate though the word and insert the correct character into the temp string for (int i = 0; i < (size + 1); i++) { for (char c = 'z'; c >= 'a'; c--) { temp.insert(i, 1, c); //if the hash table contains the newly changed temp string, print the corrected word if (dictionary.Contains(temp) == true) { cout << word << arr << temp << " case a" << endl; } temp = word; //reset the temp string } } temp = word; //resetting the temp string //for case b: traverse through the word for (int i = 0; i < size; i++) { //remove the incorrect letter from the word temp.erase(i, 1); //if the hash table contains the newly changed temp string, print the corrected word if (dictionary.Contains(temp) == true) { cout << word << arr << temp << " case b" << endl; } temp = word; //resetting the temp string } //for case c: traverse through the word for (int i = size - 1; i >= 0; i--) { //swap the incorrectly placed letters that are next to eachother swap(temp[i + 1], temp[i]); //if the hash table contains the newly changed temp string, print the corrected word if (dictionary.Contains(temp) == true) { cout << word << arr << temp << " case c" << endl; } temp = word; //resetting the temp string } } } apostrophe = false; //reset the flag to be false } doc.close(), dict.close(); //closing the files // Call functions implementing the assignment requirements. // HashTableDouble<string> dictionary = MakeDictionary(dictionary_filename); // SpellChecker(dictionary, document_filename); return 0; } // Sample main for program spell_check. // WE WILL NOT USE YOUR MAIN IN TESTING. DO NOT CODE FUNCTIONALITY INTO THE // MAIN. WE WILL DIRECTLY CALL testSpellingWrapper. ALL FUNCTIONALITY SHOULD BE // THERE. This main is only here for your own testing purposes. int main(int argc, char **argv) { if (argc != 3) { cout << "Usage: " << argv[0] << " <document-file> <dictionary-file>" << endl; return 0; } testSpellingWrapper(argc, argv); return 0; }
true
5821ae36893633354fdc0ec3992be326bda779d3
C++
jharshman/minor3
/main.cpp
UTF-8
1,290
2.921875
3
[]
no_license
/** * main.cpp * written by Joshua Harshman * 08/08/15 * */ #include <iostream> #include <fstream> #include "Truck.h" #include "PackageFactory.h" using namespace std; int main() { fstream infile; infile.open("/home/voodoo/ClionProjects/minor3-5/manifest.txt", ios::in); string driver_name; string s_weight; string origin_city; string destination_city; string m_packages; int tracking; double weight; getline(infile, driver_name); getline(infile, s_weight); getline(infile, origin_city); getline(infile, destination_city); getline(infile, m_packages); int max_packages = stoi(m_packages); double truck_weight = stoi(s_weight); Truck truck = Truck(driver_name, truck_weight, origin_city, destination_city, max_packages); PackageFactory *packageFactory = new PackageFactory(); Package *aPackage; while (true) { infile >> tracking >> weight; if(infile.eof()) break; try { aPackage = packageFactory->createPackage(tracking, weight); truck.addCargo(&aPackage); }catch(NullPackage &nullPackage) { continue; } } //extra logs truck.printTruckLoadAndDrive(); cout << "Log file written to run directory"; return 0; }
true
094d21eb518997a81009fee6147d01b17ec7fd72
C++
zzaassaa2/MazeRunner
/src/engine/Utility.cpp
UTF-8
683
2.8125
3
[ "MIT" ]
permissive
// // Created by George Zorn on 3/16/21. // #include "engine/Utility.h" bool mz::isIntersecting(glm::vec3 p1, glm::vec3 p2, glm::vec3 q1, glm::vec3 q2){ return (((q1.x-p1.x)*(p2.y-p1.y) - (q1.y-p1.y)*(p2.x-p1.x)) * ((q2.x-p1.x)*(p2.y-p1.y) - (q2.y-p1.y)*(p2.x-p1.x)) < 0) && (((p1.x-q1.x)*(q2.y-q1.y) - (p1.y-q1.y)*(q2.x-q1.x)) * ((p2.x-q1.x)*(q2.y-q1.y) - (p2.y-q1.y)*(q2.x-q1.x)) < 0); } float mz::map(float input, float input_start, float input_end, float output_start, float output_end) { float slope = 1.0f * (output_end - output_start) / (input_end - input_start); return output_start + slope * (input - input_start); }
true
15ee034eaa84ca29298850ad1153fa11d2320084
C++
ManuWer/INF-450
/Trabalho 2/Parte II/compilador/200_cat1.cpp
UTF-8
4,635
3.328125
3
[]
no_license
#include <iostream> #include <string> #include <unordered_map> #include <queue> #include <algorithm> #include <cmath> #include <vector> using namespace std; // mapeia uma string de estado do jogo em uma sequencia de // movimentos de como chegar neste estado unordered_map<string,string> m; // os movimentos verticais sao feitos para baixo... string V1(const string &p) { string s(p); int s0 = s[0], s3 = s[3]; s[0] = s[6]; s[3] = s0; s[6] = s3; return s; } string V2(const string &p) { string s(p); int s1 = s[1], s4 = s[4]; s[1] = s[7]; s[4] = s1; s[7] = s4; return s; } string V3(const string &p) { string s(p); int s2 = s[2], s5 = s[5]; s[2] = s[8]; s[5] = s2; s[8] = s5; return s; } // os movimentos horizontais sao feitos para a esquerda... string H1(const string &p) { string s(p); int s0 = s[0], s1 = s[1]; s[0] = s1; s[1] = s[2]; s[2] = s0; return s; } string H2(const string &p) { string s(p); int s3 = s[3], s4 = s[4]; s[3] = s4; s[4] = s[5]; s[5] = s3; return s; } string H3(const string &p) { string s(p); int s6 = s[6], s7 = s[7]; s[6] = s7; s[7] = s[8]; s[8] = s6; return s; } // coloca no mapa todos os estados que sao possiveis de alcancar a partir // do estado consistente do jogo, fazendo os movimentos contrarios void criaMapa() { queue<pair<string,string> > F; F.push({"123456789",""}); string s, p; while(!F.empty()) { s = F.front().first; p = F.front().second; F.pop(); auto it = m.find(s); if(it==m.end()) { m[s] = p; F.push({H1(s),p+"1H"}); F.push({H2(s),p+"2H"}); F.push({H3(s),p+"3H"}); F.push({V1(s),p+"1V"}); F.push({V2(s),p+"2V"}); F.push({V3(s),p+"3V"}); } } } int main() { string s, puzzle; criaMapa(); while(1) { for(int i=0;i<3;i++) { getline(cin,s); if(s[0]=='0') return 0; puzzle += s[0]; puzzle += s[2]; puzzle += s[4]; } // se o estado de entrada nao esta no mapa, nao tem solucao if(m.find(puzzle)==m.end()) cout << "Not solvable\n"; // se estiver, imprime o numero de movimentos e a ordem ao contrario else { s = m[puzzle]; reverse(s.begin(),s.end()); cout << s.size()/2 << " " << s << endl; } puzzle.clear(); s.clear(); } return 0; } const double EPS = 1e-10; int cmp(double x, double y=0, double tol=EPS) { return (x<=y+tol)?(x+tol<y)?-1:0:1; } struct Point { double x,y; Point(double x_=0, double y_=0) : x(x_), y(y_) {} Point operator+(Point q) { return Point(x+q.x,y+q.y); } Point operator-(Point q) { return Point(x-q.x,y-q.y); } Point operator*(double t) { return Point(x*t,y*t); } Point operator/(double t) { return Point(x/t,y/t); } double operator*(Point q) { return x*q.x + y*q.y; } double operator^(Point q) { return x*q.y - y*q.x; } int cmp(Point q) const { if(int t = ::cmp(x,q.x) ) return t; return ::cmp(y,q.y); } bool operator==(Point q) const { return cmp(q)==0; } bool operator!=(Point q) const { return cmp(q)!=0; } friend ostream& operator<<(ostream &out, Point p) { return out << "(" << p.x << ", " << p.y << ")"; } void set(double x_, double y_) { x=x_; y=y_; } static Point pivot; }; Point Point::pivot; double area (Point a, Point b, Point c) { return (c-a)^(b-a)/2.0; } double polygonArea(vector< Point> &T) { double s = 0.0; int n = T.size(); for(int i=0;i<n;i++) s += T[i]^T[(i+1)%n]; return s/2.0; //Retorna area com sinal } inline int ccw(Point &p, Point &q, Point &r) { return cmp((p-r)^(q-r)); } bool pontoSobreReta(Point &p1, Point &p2, Point &p) { return ccw(p1,p2,p)==0; } bool between(Point &p1, Point &p, Point &p2) { return ccw(p1,p2,p)==0 && cmp((p1-p)*(p2-p))<=0; } bool distaciaReta(Point &p1, Point &p2, Point &p) { Point A = p1-p, B = p2-p1; return fabs(A^B)/sqrt(B*B); } bool distaciaSegReta(Point &p1, Point &p2, Point &p) { Point A = p1-p, B = p2-p1, C = p1-p; double a = A*A, b = B*B, c = C*C; if(cmp(a,b+c)>=0) return sqrt(c); else if(cmp(c,a+b)>=0) return sqrt(a); else return fabs(A^C)/sqrt(b); } double angle(Point &p, Point &q, Point &r) { Point u = p-r, w = q-r; return atan2(u^w,u*w); } int inpoly(Point &p, vector< Point > &T) { double a = 0.0; int n = T.size(); for(int i=0;i<n;i++) { if(between(T[i],p,T[(i+1)%n])) return -1; a += angle(T[i],T[(i+1)%n],p); } return cmp(a)!=0; }
true
b78748cbc99a320b89aa5f6bb1c8be1264d1aae8
C++
hardikdosi/Spoj
/CPRMT-12151415-src.cpp
UTF-8
893
2.859375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <string> using namespace std; int main() { char str1[10050], str2[10050]; int a[130], b[130]; while (scanf("%s\n%s", str1, str2) != EOF) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); int tmp; for (int i = 0; i < strlen(str1); i++) { tmp = (int)str1[i]; a[tmp] += 1; } for (int i = 0; i < strlen(str2); i++) { tmp = (int)str2[i]; b[tmp] += 1; } for (int i = 0; i < 130; i++) { if (a[i] - b[i] >= 0) { for (int j = 0; j < b[i]; j++) printf("%c", i); } else if (a[i] - b[i] < 0) { for (int j = 0; j < a[i]; j++) printf("%c", i); } } printf("\n"); } return 0; }
true
0b9228c53a3693021ff6e621979f5fea68be8c3f
C++
ocslegna/algo3
/TP2/Ej1/ej1.cpp
UTF-8
6,105
3.1875
3
[]
no_license
#include <iostream> #include <time.h> #include <vector> #include <string> #include <cassert> #include <cstdlib> // atoi using namespace std; typedef struct ProblemInstance { int n_works; vector< vector<unsigned int> > cost_matrix; ProblemInstance(int n_works) : n_works(n_works), cost_matrix(n_works + 1) {} } ProblemInstance; typedef struct SolutionInstance { int cost; vector<unsigned int> M1; vector<unsigned int> M2; string format_solution() { string res = "" + to_string(this->cost) + " " + to_string(this->M1.size()) + " "; for(int i = 0; i < this->M1.size(); i++) { res += to_string(this->M1[i]) + " "; } return res; } } SolutionInstance; void parse(vector<ProblemInstance>& problems) { int n_works; cin >> n_works; while(n_works != 0) { ProblemInstance pi(n_works); for(unsigned int i = 1; i < pi.cost_matrix.size(); i++) { vector<unsigned int> j_vector; unsigned int cost; for(unsigned j = 0; j < i; j++) { cin >> cost; j_vector.push_back(cost); } pi.cost_matrix[i] = j_vector; } problems.push_back(pi); cin >> n_works; } } void init_matrix(vector< vector<unsigned int> >& m, unsigned int v){ for(unsigned int i = 0; i < m.size(); i++){ for(unsigned int j = 0; j < m[i].size(); j++){ m[i][j] = v; } } } void print_matrix(vector< vector<unsigned int> >& m) { for(unsigned int i = 1; i < m.size(); i++){ for(unsigned int j = 0; j < m[i].size(); j++){ cout << m[i][j] << " "; } cout << endl; } } unsigned int min(unsigned int a, unsigned int b){ return (a < b) ? a : b; } void build_solution(vector< vector<unsigned int> >& cost, vector< vector<unsigned int> >& opt, unsigned int n_works, vector<unsigned int>& M1, vector<unsigned int>& M2) { int last = 0; M1.push_back(0); M2.push_back(0); // 1 work always goes first M1.push_back(1); // works 2 to n-1 for(int i = 2; i < n_works; i++) { unsigned int c1 = cost[i][M1.back()]; unsigned int c2 = cost[i][M2.back()]; if(opt[i][last] - c1 == opt[i + 1][M2.back()]) { M1.push_back(i); last = M2.back(); } else if(opt[i][last] - c2 == opt[i + 1][M1.back()]) { M2.push_back(i); last = M1.back(); } else { assert(false); } } // nth work unsigned int c1 = cost[n_works][M1.back()]; unsigned int c2 = cost[n_works][M2.back()]; if(opt[n_works][last] - c1 == 0) { M1.push_back(n_works); last = M2.back(); } else if(opt[n_works][last] - c2 == 0) { M2.push_back(n_works); last = M1.back(); } else { assert(false); } M1.erase(M1.begin()); // erase 0 M2.erase(M2.begin()); // erase 0 } SolutionInstance dp_bottom_up(ProblemInstance& pi) { SolutionInstance sol; vector< vector<unsigned int> > opt = pi.cost_matrix; init_matrix(opt, 0); for(int i = 0; i < opt[pi.n_works].size(); i++) { opt[pi.n_works][i] = min(pi.cost_matrix[pi.n_works][i], pi.cost_matrix[pi.n_works][pi.n_works - 1]); } for(int i = pi.n_works - 1; i > 0; i--) { for(int j = 0; j < opt[i].size(); j++) { opt[i][j] = min(pi.cost_matrix[i][j] + opt[i + 1][i - 1], pi.cost_matrix[i][i - 1] + opt[i + 1][j]); } } sol.cost = opt[1][0]; build_solution(pi.cost_matrix, opt, pi.n_works, sol.M1, sol.M2); return sol; } unsigned int dp_memo_recur(ProblemInstance& pi, vector< vector<unsigned int> >& dict, unsigned int k, unsigned int i) { if(dict[k][i] == 0) { if(k == pi.n_works) { dict[k][i] = min(pi.cost_matrix[k][i], pi.cost_matrix[k][k - 1]); } else { dict[k][i] = min(pi.cost_matrix[k][i] + dp_memo_recur(pi, dict, k + 1, k - 1), pi.cost_matrix[k][k - 1] + dp_memo_recur(pi, dict, k + 1, i)); } } return dict[k][i]; } SolutionInstance dp_memo(ProblemInstance& pi) { SolutionInstance sol; vector< vector<unsigned int> > dict = pi.cost_matrix; init_matrix(dict, 0); // los costos son todos positivos, podemos usar 0 como no inicializado sol.cost = dp_memo_recur(pi, dict, 1, 0); build_solution(pi.cost_matrix, dict, pi.n_works, sol.M1, sol.M2); return sol; } // $ ./ej1 [repetitions] // Exp Mode: // stdout -> csv results // stderr -> shows advance // Normal Mode: // stdout -> result int main(int argc, char **argv) { vector<ProblemInstance> ps; parse(ps); SolutionInstance sol; if(argc > 1) { // Experiments unsigned int rep; // cout << "n_works,instance,repetition,algorithm,ticks,time,cost,res_length" << endl; rep = atoi(argv[1]); for(int i = 0; i < ps.size(); i++) { for(int r = 1; r <= rep; r++) { clock_t ck; double ticks; cerr << "N: " << ps[i].n_works << " -- Inst: " << i+1 << '/' << ps.size() << " -- " << "Rep: " << r << "/" << rep; ck = clock(); sol = dp_bottom_up(ps[i]); ticks = (double)(clock() - ck); cout << ps[i].n_works << "," << i+1 << "," << r << "," << "bottom,"; cout << ticks << "," << (ticks)/(CLOCKS_PER_SEC/1000) << "," << sol.cost << "," << sol.M1.size() << endl; cerr << " -- Bottom "; ck = clock(); sol = dp_memo(ps[i]); ticks = (double)(clock() - ck); cout << ps[i].n_works << "," << i+1 << "," << r << "," << "memo,"; cout << ticks << "," << (ticks)/(CLOCKS_PER_SEC/1000) << "," << sol.cost << "," << sol.M1.size() << endl; cerr << "Memo" << endl; } } } else { // Normal mode for(int i = 0; i < ps.size(); i++) { sol = dp_bottom_up(ps[i]); cout << sol.format_solution() << endl; } } }
true
9ce576e6c28ec59d1c97cf8eb8a304784a8f2c17
C++
MaguRaam/wave
/wave-quadratic/fv/include/quadratic.h
UTF-8
7,307
3.21875
3
[]
no_license
#pragma once namespace fv { namespace polynomial { template <int dim> struct Quadratic { }; // template specialization for dim = 2; template <> struct Quadratic<2> { using CellItr = typename dealii::Triangulation<2>::active_cell_iterator; // constructor Quadratic() = default; void reinit(const CellItr &cell) { // cell center: const auto po = cell->barycenter(); // compute h: h = sqrt(cell->measure()); // extract coordinates of the cell centre: xo = po[0]; yo = po[1]; // compute constants c1, c2 and c3: CellAverage<2, 4> cell_average; c1 = cell_average([this](auto p) {double x = p[0]; return (1.0 / (h * h)) * (x - xo) * (x - xo); }, cell); c2 = cell_average([this](auto p) {double y = p[1];return (1.0 / (h * h)) * (y - yo) * (y - yo); }, cell); c3 = cell_average([this](auto p) {double x = p[0], y = p[1];return (1.0 / (h * h)) * (x - xo) * (y - yo); }, cell); } // operator(): returns the basis functions of the polynomial evaluated at // point p: dealii::Vector<double> operator()(const dealii::Point<2, double> &p) const { const double x = p[0], y = p[1]; dealii::Vector<double> basis(5); basis[0] = (1.0 / h) * (x - xo); basis[1] = (1.0 / h) * (y - yo); basis[2] = ((1.0 / (h * h)) * (x - xo) * (x - xo)) - c1; basis[3] = ((1.0 / (h * h)) * (y - yo) * (y - yo)) - c2; basis[4] = ((1.0 / (h * h)) * (x - xo) * (y - yo)) - c3; return basis; } // return gradient of the polynomial evaluated at cell center: friend dealii::Vector<double> gradient(const Quadratic<2> &quadratic, const dealii::Point<2, double> &p) { const double h = quadratic.h, xo = quadratic.xo, yo = quadratic.yo; const double x = p[0], y = p[1]; // x and y component of gradient const double ux = quadratic.coefficients[0], uy = quadratic.coefficients[1], uxx = quadratic.coefficients[2], uyy = quadratic.coefficients[3], uxy = quadratic.coefficients[4]; dealii::Vector<double> grad(2); grad[0] = ux * (1.0 / h) + uxx * (2.0 / (h * h)) * (x - xo) + uxy * (1.0 / (h * h)) * (y - yo); grad[1] = uy * (1.0 / h) + uyy * (2.0 / (h * h)) * (y - yo) + uxy * (1.0 / (h * h)) * (x - xo); return grad; } // returns no of coefficients excluding uo: constexpr unsigned int size() const { return 5; } // access coefficients of the polynomial std::array<double, 5> &coefficient() { return coefficients; } // read only access coefficients of the polynomial const std::array<double, 5> &coefficient() const { return coefficients; } private: std::array<double, 5> coefficients; // coefficients excluding uo double h; // sqrt of cell volume double xo, yo; // cell centre coordinates double c1, c2, c3; // polynomial constants }; // template specialization for dim = 3 template <> struct Quadratic<3> { using CellItr = typename dealii::Triangulation<3>::active_cell_iterator; // constructor Quadratic() = default; void reinit(const CellItr &cell) { // cell center: const auto po = cell->barycenter(); // compute h: h = cbrt(cell->measure()); // extract coordinates of the cell centre: xo = po[0]; yo = po[1]; zo = po[2]; // compute constants c1, c2, c3, c4, c5 and c6: CellAverage<3, 4> cell_average; c1 = cell_average([this](auto p) {double x = p[0]; return (1.0 / (h * h)) * (x - xo) * (x - xo); }, cell); c2 = cell_average([this](auto p) {double y = p[1]; return (1.0 / (h * h)) * (y - yo) * (y - yo); }, cell); c3 = cell_average([this](auto p) {double z = p[2]; return (1.0 / (h * h)) * (z - zo) * (z - zo); }, cell); c4 = cell_average([this](auto p) {double x = p[0], y = p[1]; return (1.0 / (h * h)) * (x - xo) * (y - yo); }, cell); c5 = cell_average([this](auto p) {double y = p[1], z = p[2]; return (1.0 / (h * h)) * (y - yo) * (z - zo); }, cell); c6 = cell_average([this](auto p) {double x = p[0], z = p[2]; return (1.0 / (h * h)) * (x - xo) * (z - zo); }, cell); } // operator(): returns the basis functions of the polynomial evaluated at // point p: dealii::Vector<double> operator()(const dealii::Point<3, double> &p) const { const double x = p[0], y = p[1], z = p[2]; dealii::Vector<double> basis(9); basis[0] = (1.0 / h) * (x - xo); basis[1] = (1.0 / h) * (y - yo); basis[2] = (1.0 / h) * (z - zo); basis[3] = ((1.0 / (h * h)) * (x - xo) * (x - xo)) - c1; basis[4] = ((1.0 / (h * h)) * (y - yo) * (y - yo)) - c2; basis[5] = ((1.0 / (h * h)) * (z - zo) * (z - zo)) - c3; basis[6] = ((1.0 / (h * h)) * (x - xo) * (y - yo)) - c4; basis[7] = ((1.0 / (h * h)) * (y - yo) * (z - zo)) - c5; basis[8] = ((1.0 / (h * h)) * (x - xo) * (z - zo)) - c6; return basis; } // return gradient of the polynomial evaluated at cell center: friend dealii::Vector<double> gradient(const Quadratic<3> &quadratic, const dealii::Point<3, double> &p) { const double h = quadratic.h, xo = quadratic.xo, yo = quadratic.yo, zo = quadratic.zo; const double x = p[0], y = p[1], z = p[2]; // component of gradient double ux = quadratic.coefficients[0], uy = quadratic.coefficients[1], uz = quadratic.coefficients[2], uxx = quadratic.coefficients[3], uyy = quadratic.coefficients[4], uzz = quadratic.coefficients[5], uxy = quadratic.coefficients[6], uyz = quadratic.coefficients[7], uzx = quadratic.coefficients[8]; dealii::Vector<double> grad(3); grad[0] = ux * (1.0 / h) + uxx * (2.0 / (h * h)) * (x - xo) + uxy * (1.0 / (h * h)) * (y - yo) + uzx * (1.0 / (h * h)) * (z - zo); grad[1] = uy * (1.0 / h) + uyy * (2.0 / (h * h)) * (y - yo) + uxy * (1.0 / (h * h)) * (x - xo) + uyz * (1.0 / (h * h)) * (z - zo); grad[2] = uz * (1.0 / h) + uzz * (2.0 / (h * h)) * (z - zo) + uyz * (1.0 / (h * h)) * (y - yo) + uzx * (1.0 / (h * h)) * (x - xo); return grad; } // returns no of coefficients excluding uo: constexpr unsigned int size() const { return 9; } // access coefficients of the polynomial std::array<double, 9> &coefficient() { return coefficients; } // read only access coefficients of the polynomial const std::array<double, 9> &coefficient() const { return coefficients; } private: std::array<double, 9> coefficients; // coefficients excluding uo double h; // sqrt of cell volume double xo, yo, zo; // cell centre coordinates double c1, c2, c3, c4, c5, c6; // polynomial constants }; } // namespace polynomial } // namespace fv
true
82472433c72e564dbb4903ffd6f36166cf386d0f
C++
zeroshade/Conn4
/BitBoard.cpp
UTF-8
3,690
2.90625
3
[]
no_license
/* * File: BitBoard.cpp * Author: zeroshade * * Created on November 4, 2011, 6:20 PM */ #include "BitBoard.h" #include <sstream> inline int bitcount(bitboard n) { int count = 0; while (n > 0) { count += (n & 1); n >>= 1; } return count; } BitBoard::BitBoard() : swap(false) { reset(); } BitBoard::BitBoard(const BitBoard& orig) { } BitBoard::~BitBoard() { } void BitBoard::reset() { depth = 0; color[0] = color[1] = 0; for (int i=0; i<WIDTH; i++) height[i] = (char)(H1*i); } bool isGameover(bitboard& newboard) { bitboard diag1 = newboard & (newboard>>HEIGHT); bitboard hori = newboard & (newboard>>H1); bitboard diag2 = newboard & (newboard>>H2); bitboard vert = newboard & (newboard>>1); return ((diag1 & (diag1 >> 2*HEIGHT)) | (hori & (hori >> 2*H1)) | (diag2 & (diag2 >> 2*H2)) | (vert & (vert >> 2))); } void BitBoard::move(int col) { color[turn()] ^= (bitboard)1<<height[col]++; moves[depth++] = col; } void BitBoard::undo() { int n = moves[--depth]; color[turn()] ^= (bitboard)1<<--height[n]; } int utility(bitboard& board, bool comp) { int n1 = bitcount(board); bitboard vert = board & (board>>1); bitboard vert2 = (vert & (vert >> 1)); int n3 = bitcount(vert2); int n2 = bitcount(vert); bitboard horiz = board & (board>>H1); bitboard horiz2 = (horiz & (horiz >> H1)); n3 += bitcount(horiz2); n2 += bitcount(horiz); bitboard diag1 = board & (board>>HEIGHT); bitboard diag2 = board & (board>>H2); bitboard diag1_2 = diag1 & (diag1 >> HEIGHT); bitboard diag2_2 = diag2 & (diag2>>H2); n3 += bitcount(diag1_2); n3 += bitcount(diag2_2); n2 += bitcount(diag1); n2 += bitcount(diag2); return n1*((comp)?2:1) + n2*((comp)?4:2) + n3*((comp)?16:8); } int BitBoard::score() { if (isGameover(color[1])) { return MAX; } else if (isGameover(color[0])) { return MIN; } else { int score = utility(color[1],true) - utility(color[0],false); return score; } } std::string BitBoard::show() { std::ostringstream str; for (int x = 0; x < (WIDTH * 2 + 1); ++x) str << "_"; // top row str << std::endl; bitboard n = 0; for (int i = 0; i < HEIGHT; ++i) { str << "|"; for (int j = 0; j < WIDTH; ++j) { n = (bitboard)1<<((HEIGHT - 1) + (H1 * j)) - (i); str << ((color[0] & n) ? 'x' : (color[1] & n) ? 'o' : ' '); str << "|"; } str << std::endl; } for (int x = 0; x < (WIDTH * 2 + 1); ++x) str << "-"; // bottom row str << std::endl; return str.str(); } int BitBoard::quickmove() { int ret = -1; int middle = (WIDTH / 2); if (curDepth() == 0) { ret = middle; } else if (curDepth() == 1) { ret = middle; if (moves[0] == 1) ret = middle-1; else if (moves[0] == 5) ret = middle+1; } else if (curDepth() == (SIZE - 1)) { for (short i = 0; i < WIDTH; ++i) { if (height[i] < HEIGHT) { ret = i; break; } } } else { for (short i = 0; i < WIDTH && ret == -1; ++i) { bitboard check_me = color[turn()] | (bitboard)1 << height[i]; if (isValid(check_me) && isGameover(check_me)) ret = i; } for (short i = 0; i < WIDTH && ret == -1; ++i) { bitboard check_opp = color[turn()^1] | (bitboard)1 << height[i]; if (isValid(check_opp) && isGameover(check_opp)) ret = i; } } if (ret != -1) return ret; // opening book return -1; }
true
b8e09703e3fda1be4869b831df7b831e9f566361
C++
sheepjian/algo_house
/OJ/leetcode/RotateList/RotateList.cpp
UTF-8
1,460
3.859375
4
[]
no_license
/* File Name : RotateList.cpp Author: Jerry DENG (jerrydeng.windfly@gmail.com) Time: 2014-11-16 15:45:22 Question: Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. Tags: Linked List; Two Pointers Answer: The distance between the new head node and old head node is (1) when k%len ==0, 0 (2) otherwise, len - k%len */ #include "Common/Leetcode.h" class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head) { ListNode* p = head; int len = 1; while(p->next!=NULL) { len++; p = p->next; } p->next = head; ListNode* tail = p; p = head; int p_shift = len - k%len; while(p_shift!=len&&p_shift>0) { p = p->next; tail = tail->next; p_shift--; } head = p; tail->next = NULL; } return head; } }; int main(int argc, char** argv) { Solution sol; ListNode* head = new ListNode(1); ListNode* node1 = new ListNode(2); ListNode* node2 = new ListNode(3); ListNode* node3 = new ListNode(4); ListNode* node4 = new ListNode(5); head->next = node1; node1->next = node2; node2->next = node3; node3->next = node4; ListNode* node = sol.rotateRight(head,13); if(node) { cout<<node->val<<endl; } else { cout<<"it is null"<<endl; } return 0; }
true
6fce0db25ea5fc58c9d7213756a7a2cbf22129e7
C++
fresher96/competitive-programming
/Union_find DS/main.cpp
UTF-8
1,008
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void read_file(bool outToFile = true){ #ifdef LOCAL_TEST freopen("in.in", "rt", stdin); if(outToFile) freopen("out.out", "wt", stdout); #endif } // typedef vector <int> vi; // struct union_find{ vi par, rnk; union_find(int n = 0){ // O(n) rnk.assign(n, 0); par.resize(n); for(int i=0; i<n; i++) par[i] = i; } // all these functions work in ~O(1) int find_par(int i){ if( par[i] == i ) return i; else return par[i] = find_par( par[i] ); } bool in_the_same_set(int i, int j){ return find_par(i) == find_par(j); } void set_union(int i, int j){ i = find_par(i), j = find_par(j); if(i == j) return; if(rnk[i] >= rnk[j]) par[j] = i, rnk[i] += (rnk[i] == rnk[j]); else par[i] = j; } } UF; // int main() { read_file(false); UF = union_find(5); }
true