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
169a4aeaa49d931000f63635b03a2a8808048f8a
C++
andrewjkanarek/BlackjackGit
/blackjack/statsFast.cpp
UTF-8
4,241
3.0625
3
[]
no_license
#include "deck.h" #include "statsFast.h" #include <iostream> #include <string> // #include <unordered_map> using namespace std; // namespace BJ { StatsFast::StatsFast() { decision = "HIT"; resetStats(); } void StatsFast::resetStats() { dealer_bust = 0; win_ah = 0; lose_ah = 0; push_ah = 0; win = 0; lose = 0; push = 0; probArray = {}; player_prob_map = { { "17", 0}, { "18", 0}, { "19", 0}, { "20", 0}, { "21", 0}, { "no_bust", 0} }; dealer_prob_map = { { "17", 0}, { "18", 0}, { "19", 0}, { "20", 0}, { "21", 0}, { "bust", 0} }; } void StatsFast::updateStats(Hand *player_hand, Deck *deck, Hand *dealer_hand) { initializeProbArray(*deck); printProbArray(); cout << "SUM: " << getProbArraySum() << "\n"; setDealerProbMap1D(*dealer_hand); printDealerMap1d(); win = getProbWin(player_hand, deck, dealer_hand); decision = "HIT"; dealer_bust = 0; win_ah = 0; lose_ah = 0; push_ah = 0; lose = 0; push = 0; } void StatsFast::initializeProbArray(Deck deck) { for (unsigned int i = 0; i < probArray.size(); ++i) { if (i == 0) { probArray[0] = 0; } else if (i == 1) { probArray[1] = getProbOfCard(deck, "A"); } else { int start_index; // if current index is even // start as the index / 2 if (i % 2 == 0) { start_index = i / 2; } // otherwise start at (index / 2) + 1 else { start_index = (i / 2) + 1; } double sum = 0; for (unsigned int j = start_index; j < i; j++) { sum += probArray[j] * probArray[i-j]; } if (i <= 11) { sum += getProbOfCard(deck, convertIntToCardName(i)); } probArray[i] = sum; } } } double StatsFast::getProbWin(Hand *player_hand, Deck *deck, Hand *dealer_hand) { double prob = probArray[1]; return prob; } double StatsFast::getProbOfCard(Deck deck, string card_name) { // probability of a card = (number of that card in the deck / number of cards in the deck) int total_cards = deck.total_cards; int num = deck.deck_map[card_name]; // cout << "num: " << num << ", total: " << total_cards << "\n"; return float(num) / total_cards; } string StatsFast::convertIntToCardName(int val) { if (val == 1 || val == 11) { return "A"; } else { return to_string(val); } } void StatsFast::setDealerProbMap1D(Hand dealer_hand) { // if the dealer hand is in the range the dealer must stick, then the dealer's value // will definitely end as that value // ex: if a dealer has an "18", the dealer must stick and will end with an "18" if (dealer_hand.total_val >= DEALER_MIN && dealer_hand.total_val <= DEALER_MAX) { dealer_prob_map[to_string(dealer_hand.total_val)] = 1; } // otherwise, the probability of getting a value is the probability of getting a number // that adds up to that value // ex: prob of getting a "17" if the dealer has a "5" is the probability of getting a "12" // probArray(n) gets the probability of getting "n" after unlimited hits else if (dealer_hand.total_val < DEALER_MIN) { dealer_prob_map["17"] = probArray[17 - dealer_hand.total_val]; dealer_prob_map["18"] = probArray[18 - dealer_hand.total_val]; dealer_prob_map["19"] = probArray[19 - dealer_hand.total_val]; dealer_prob_map["20"] = probArray[20 - dealer_hand.total_val]; dealer_prob_map["21"] = probArray[21 - dealer_hand.total_val]; } else { for (unsigned int i = DEALER_MAX - (dealer_hand.total_val - 1); i <= 11; ++i) { dealer_prob_map["bust"] += probArray[i]; } } } void StatsFast::setPlayerProbMap1D(Hand player_hand) { } void StatsFast::printProbArray() { for (unsigned int i = 0; i < probArray.size(); ++i) { cout << i << ": " << probArray[i] << "\n"; } } void StatsFast::printDealerMap1d() { cout << "*** Dealer Map ***\n"; for (auto it = dealer_prob_map.begin(); it != dealer_prob_map.end(); it++) { cout << it->first << ": " << it->second << "\n"; } } void StatsFast::printPlayerMap1d() { cout << "*** Player Map ***\n"; for (auto it = player_prob_map.begin(); it != player_prob_map.end(); it++) { cout << it->first << ": " << it->second << "\n"; } } double StatsFast::getProbArraySum() { double sum = 0; for (unsigned int i = 0; i < probArray.size(); ++i) { sum += probArray[i]; } return sum; }
true
ff3f3ba4e6b3047891520c7502102711af7e8eeb
C++
gjorquera/triad
/Source/Libs/Euclid/Geometry/Edge.h
UTF-8
707
3.140625
3
[]
no_license
#pragma once #include "../Type/Point.h" namespace Euclid { /*! * Defines a triangle's edge. * * An edge contains a Vector in an euclidean coordinate system. * * You can query it with \b vector. */ template <class Kernel> class Edge { public: typedef typename Kernel::Vector Vector; Edge() { _vector = Vector(); } Edge(const Vector& vector) { _vector = vector; } Vector& vector() { return _vector; } const Vector& vector() const { return _vector; } protected: Vector _vector; }; }
true
e0b0ae07100b3404d6be9a34229213bb20e159f5
C++
AlessandroOsima/JD-UE4
/Source/BaseBlank/Character/Components/EffectComponent.cpp
UTF-8
2,293
2.75
3
[]
no_license
#include "BaseBlank.h" #include "Character/BaseCharacter.h" #include "EffectComponent.h" void UPowerInteractionsComponent::AddEffect(UBaseEffect * effect) { Effects.Add(effect); effect->StartUse(GetOwner()); } void UPowerInteractionsComponent::RemoveEffect(UBaseEffect * effect) { Effects.Remove(effect); effect->EndUse(GetOwner()); } void UPowerInteractionsComponent::RemoveAllEffects() { while (Effects.Num()) { RemoveEffect(Effects.Last()); } } bool UPowerInteractionsComponent::HasEffectOfClass(TSubclassOf<UBaseEffect> Class, bool AlsoChild, bool AlsoParent) const { bool result = false; for (auto effect : Effects) { result = result || Class == effect->GetClass(); if (AlsoChild) { result = result || Class->IsChildOf(effect->GetClass()); } if (AlsoParent) { result = result || effect->GetClass()->IsChildOf(Class); } } return result; } bool UPowerInteractionsComponent::HasEffects() const { return Effects.Num() > 0; } UBaseEffect * UPowerInteractionsComponent::HigherPriorityEffect() const { if (Effects.Num() == 0) return nullptr; UBaseEffect * highestPrio = Effects[0]; int32 prioVal = Effects[0]->Priority; for (int i = 1; i < Effects.Num(); i++) { if (Effects[i]->Priority > prioVal) { highestPrio = Effects[i]; prioVal = Effects[i]->Priority; } } return highestPrio; } bool UPowerInteractionsComponent::HigherPriorityEffectIsOfClass(TSubclassOf<UBaseEffect> Class) const { auto effect = HigherPriorityEffect(); bool isOfClass = false; if (effect && effect->GetClass() == Class) { isOfClass = true; } return isOfClass; } void UPowerInteractionsComponent::AddShieldedPower(TSubclassOf<ABasePowerActor> shieldedPower) { ShieldedFromPowers.Add(shieldedPower); } void UPowerInteractionsComponent::RemoveShieldedPower(TSubclassOf<ABasePowerActor> shieldedPower) { ShieldedFromPowers.Remove(shieldedPower); } bool UPowerInteractionsComponent::IsShieldedFromPower(TSubclassOf<ABasePowerActor> shieldedPower) { return ShieldedFromPowers.Contains(shieldedPower); } void UPowerInteractionsComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { for (int i = 0; i < Effects.Num(); i++) { Effects[i]->Using(GetOwner(), DeltaTime); } }
true
5d4fd79a5d53959ba53c3643d3d09905b57b7ec4
C++
delpart/SimpleRayTracer
/src/sphere.h
UTF-8
1,321
2.96875
3
[ "MIT" ]
permissive
#ifndef SPHEREH #define SPHEREH #include "surface.h" class Material; class Sphere: public Surface{ public: Sphere(){} Sphere(vec3 pos, float r, Material *m) : position(pos), radius(r), mat(m) {}; virtual bool hit(const Ray& r, float tMin, float tMax, hitRecord& hitRec) const; vec3 position; float radius; Material *mat; }; bool Sphere::hit(const Ray& r, float tMin, float tMax, hitRecord& hitRec) const{ vec3 oc = r.getOrigin() - position; float a = dot(r.getDirection(), r.getDirection()); float b = dot(oc, r.getDirection()); float c = dot(oc, oc) - radius*radius; float discriminant = b*b - a*c; if(discriminant > 0){ float temp = (-b - sqrt(discriminant)) / a; if(temp < tMax && temp > tMin){ hitRec.t = temp; hitRec.p = r.pointAtParameter(temp); hitRec.normal = (hitRec.p - position) / radius; hitRec.mat = mat; return true; } temp = (-b + sqrt(discriminant)) / a; if(temp < tMax && temp > tMin){ hitRec.t = temp; hitRec.p = r.pointAtParameter(temp); hitRec.normal = (hitRec.p - position) / radius; hitRec.mat = mat; return true; } } return false; } #endif
true
b19de748603c6d253e1e835924d29210e6215336
C++
alikoptan/adventofcode2020
/src/day03/day03.cpp
UTF-8
1,460
3.375
3
[ "Unlicense" ]
permissive
#include <vector> #include <string> #include <iostream> using namespace std; class day3 { private: vector<string> textFile; void readFile() { freopen("input.txt", "r", stdin); string line; while(getline(cin, line)) { textFile.push_back(line); } } int countTrees(int directionX, int directionY) { int rows = textFile.size(), columns = textFile[0].size(), trees = 0; int startX = 0, startY = 0; while(startX < rows) { trees += textFile[startX][startY] == '#'; startX += directionX; startY += directionY; startY %= columns; } return trees; } public: day3() { readFile(); } void part1() { cout << "Part 1: " << countTrees(1, 3) << '\n'; } void part2() { vector<pair<int, int>> instructions = { {1, 1}, {1, 3}, {1, 5}, {1, 7}, {2, 1} }; int totalTrees = 1; for (auto i : instructions) { int encounteredTrees = countTrees(i.first, i.second); cout << "for slopes(" << i.second << ", " << i.first << "): " << encounteredTrees << '\n'; totalTrees *= encounteredTrees; } cout << "Part 2: " << totalTrees << '\n'; } }; int main() { day3 solution; solution.part1(); solution.part2(); return 0; }
true
a3c9117e6391c4e285b464186bd23d9552aebbcf
C++
GAVLab/memsense_imu
/src/nodes/imu_filter.h
UTF-8
819
2.65625
3
[]
no_license
/** * @file * @author Joan Pau Beltran * @brief ROS Memsense IMU filter presentation. * * This is a filter to be used with the Memsense IMU node. * IMU samples are stored in vectors, and filtered with the desired method * on demand. */ #ifndef IMU_FILTER_H #define IMU_FILTER_H #include "imu_sample.h" namespace memsense_imu { /** * @brief IMU sample filter. * * Filter to be used with the Memsense IMU node. * IMU samples are stored in vectors, * and filtered with the desired method on demand. */ class Filter { public: Filter(); unsigned int count(); void reset(); void update(const SampleArray& s); void mean(SampleArray* s); void median(SampleArray* s); private: unsigned int count_; std::vector<double> samples_[NUM_MAGNS][NUM_AXES]; }; } // namespace #endif /* IMU_FILTER_H */
true
23d9dd1211d91de43b30bd12932ffb56de60352a
C++
bjhaussmann/cs256_hw02
/bjhaussmann_hw02/bjhaussmannhw02.cpp
UTF-8
674
3.703125
4
[]
no_license
/* Haussmann, Ben ** CS256-01, Fall 2017 ** Homework Assignment #2 ** Description: ** Averages two numbers a use-defined amount of times. */ #include "stdafx.h" #include "iostream" using namespace std; int main() { int iterations = 0; double val1, val2 = 0; cout << "How many pairs of integers to be read? "; cin >> iterations; cout << endl; for (int i = 1; i < iterations + 1; i++) { cout << "--- Iteration " << i << " ---" << endl; cout << "Input first value: "; cin >> val1; cout << "Input second value: "; cin >> val2; cout << "The average for " << val1 << " and " << val2 << " is " << ((val1 + val2) / 2) << endl << endl; } return 0; }
true
76eea1fd405a9de9ff7505ebe66fa028532020b2
C++
prashant97sikarwar/leetcode
/Graph/MinimumJumpsToReachHome.cpp
UTF-8
1,422
2.6875
3
[]
no_license
//Problem Link:- https://leetcode.com/problems/minimum-jumps-to-reach-home/ #include<bits/stdc++.h> using namespace std; class Solution { public: int minimumJumps(vector<int>& forbidden, int a, int b, int x) { unordered_map<int,int> mp; for(int i=0;i<forbidden.size();i++){ mp[forbidden[i]] = 1; } if (mp[x] == 1){ return -1; } if (x == 0){ return 0; } queue<pair<int,char>> pq; pq.push({0,'f'}); int level = 0; while(!pq.empty()){ int sz = pq.size(); bool flag = false; while (sz--){ auto node = pq.front(); pq.pop(); int cor = node.first; char state = node.second; if (cor+a == x && mp[cor+a] != 1){ return level+1; } if (cor-b == x && mp[cor-b] != 1 && state == 'f'){ return level+1; } if (state == 'f' && mp[cor-b] != 1 && cor-b > 0){ pq.push({cor-b,'b'}); mp[cor-b] =1; } if (mp[cor+a] != 1 && cor+a > 0 && cor + a <= 2000+a+b){ pq.push({cor+a,'f'}); mp[cor+a] =1; } } level++; } return -1; } };
true
f7586b50cf72999b21f8c2fb5b9ba0e1d5b202d8
C++
cr13-cr/c-codes
/program to print series(1,4,7.40).cpp
UTF-8
129
2.59375
3
[]
no_license
#include<iostream> using namespace std; int main() { int x; for(x=1;x<=40;x+=3) cout<<x<<"\t"<<endl<<"\n"; return 0; }
true
389bb29c8462241fdbdd7829aa5753613938ecc5
C++
rcelsom/CS_162
/project 3/Character.cpp
UTF-8
928
3.34375
3
[]
no_license
/*************************************** Program Name: Project 3 Author: Robert Elsom Date: 2/4/2019 Description: Barbarian class, contains all getters and setters for barbarian characters along with updateStrength and getType. **************************************/ #include <cstdlib> #include "Character.hpp" #include <ctime> Character::Character() { this->armor = 0; this->strength = 0; } Character::Character(int a, int s) { this->armor = a; this->strength = s; } void Character::updateStrength( int dieRoll, int attack) { //make sure character is not gaining strength if (attack - dieRoll - armor >= 0) { this->strength -= (attack - dieRoll - armor); } } void Character::updateStrength(int dieRoll) { this->strength = dieRoll; } int Character::getArmor() { return armor; } int Character::getStrength() { return strength; } int Character::getDieRoll() { return dieRoll; } Character::~Character() { }
true
231451119abf5f65505c7504bcf4900ed3dd16cb
C++
shahriarrifat7/git-push-demo
/Code Templates/extended euclid.cpp
UTF-8
445
3.171875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef pair<int, int> pii; #define x first #define y second pii extendedEuclid(int a, int b) { if(b==0) return pii(1,0); else { pii d = extendedEuclid(b, a%b); return pii(d.y, d.x - d.y*(a/b)); } } int main() { int a,b; while(cin>>a>>b){ pii ans = extendedEuclid(a,b) ; cout << ans.x <<' ' << ans.y << endl; } }
true
01d193167df882149afa0f9acddab7d2b2f64498
C++
sdiebolt/molecular-dynamics
/src/event.cc
UTF-8
1,290
3.21875
3
[ "MIT" ]
permissive
// Copyright 2018, Samuel Diebolt <samuel.diebolt@espci.fr> #include "include/event.h" #include "include/particle.h" // Initializes a new event to occur at time t, involving particles a and b Event::Event(Event::Type type, double t, Particle* a, Particle* b) : type_ {type}, time_ {t}, a_ {a}, b_ {b}, collisions_count_a_ {0}, collisions_count_b_ {0} { if (a != nullptr) { collisions_count_a_ = a->Count(); } else { collisions_count_a_ = -1; } if (b != nullptr) { collisions_count_b_ = b->Count(); } else { collisions_count_b_ = -1; } } // > operator for the piority queue bool Event::operator>(const Event& rhs) const { return time_ > rhs.time_; } // Has any collision occurred between when event was created and now? bool Event::IsValid() const { if (a_ != nullptr && a_->Count() != collisions_count_a_) { return false; } if (b_ != nullptr && b_->Count() != collisions_count_b_) { return false; } return true; } // Returns the time that event is scheduled to occur double Event::GetTime() const { return time_; } // Returns particle A Particle* Event::GetParticleA() const { return a_; } // Returns particle B Particle* Event::GetParticleB() const { return b_; } // Returns event type Event::Type Event::GetType() const { return type_; }
true
a4c3b9093c67245779d6fd97ff42bf57a539ed5a
C++
dkwliu/AllProjects
/C++/Assignment - Doubly Linked Lists and Linked List with Queues/Assignment 13/LinkedListStack/LinkedListStack.cpp
UTF-8
2,559
4.28125
4
[]
no_license
#include <string> #include <iostream> using namespace std; /**************************************************************************************/ // Node struct. This struct will be the foundation of each node in the doubly linked list. struct node { char data; node *next; node *prev; }; /**************************************************************************************/ // This class will hold the nodes of the doubly linked list, beginning with the head. struct DoublyLinkedListStack { node *head = NULL; node *tail = NULL; void push(char); void pop(); bool isEmpty(); char top(); }; /**************************************************************************************/ // push() method inserts a node holding a data at the top of the doubly linked list stack. void DoublyLinkedListStack::push(char ch) { node *element = new node; element->data = ch; if (head == NULL) { element->next = tail; element->prev = head; tail = element; head = tail; } else { element->prev = tail; element->prev->next = element; element->next = NULL; tail = element; } } /**************************************************************************************/ // pop() method removes the node at the top of the doubly linked list stack. void DoublyLinkedListStack::pop() { if (isEmpty() == false) { tail = tail->prev; if (tail == NULL) { head = NULL; } else { tail->next = NULL; } } } /**************************************************************************************/ // isEmpty() method checks whether the linked list is empty. If it is empty, this method // will return a true, or otherwise return a false. bool DoublyLinkedListStack::isEmpty() { bool empty = false; if (head == NULL) { empty = true; } return empty; } /**************************************************************************************/ // top() method (or peek() method) returns the top char of the stack. char DoublyLinkedListStack::top() { char topVal; if (isEmpty() == false) { topVal = tail->data; return topVal; } } /**************************************************************************************/ // main method int main() { DoublyLinkedListStack DLLS; string data; int length; do { cout << "Enter a string: "; cin >> data; length = data.size(); for (int i = 0; i < length; i++) { DLLS.push(data.at(i)); } cout << "Outputting... "; for (int i = 0; i < length; i++) { cout << DLLS.top(); DLLS.pop(); } cout << endl << endl; } while (true); return 0; }
true
562b46c5baf27296ff8a441a0dfb2a4314b07729
C++
gluke77/meto_forms
/triggervalue.h
UTF-8
2,057
2.96875
3
[]
no_license
#ifndef _TRIGGERVALUE_INCLUDED #define _TRIGGERVALUE_INCLUDED #include "storedvalue.h" class TriggerValue : public StoredValue { Q_OBJECT bool _on; int _readMask; int _readOnValue; int _readOffValue; int _writeOnValue; int _writeOffValue; public: bool isOn() const { return _on; }; bool isOff() const { return !_on; }; int writeOnValue() const { return _writeOnValue; }; int writeOffValue() const { return _writeOffValue; }; int readMask() const { return _readMask; }; int readOnValue() const { return _readOnValue; }; int readOffValue() const { return _readOffValue; }; virtual void setRawValue(int rawValue, bool emitSignals, bool overrideEmit = false); TriggerValue(bool on = false, int readAddr = 0, int writeAddr = 0, bool storable = true, bool loadable = true, int rMask = 0, int rOnValue = 0, int rOffValue = 0, int wOnValue = 0, int wOffValue = 0) : StoredValue(0, 1., readAddr, writeAddr, storable, loadable), _on(on), _readMask(rMask), _readOnValue(rOnValue), _readOffValue(rOffValue), _writeOnValue(wOnValue), _writeOffValue(wOffValue) { }; TriggerValue(const TriggerValue &tv) : StoredValue(tv) { if (this == &tv) return; _on = tv.isOn(); _readMask = tv.readMask(); _readOnValue = tv.readOnValue(); _readOffValue = tv.readOffValue(); _writeOnValue = tv.writeOnValue(); _writeOffValue = tv.writeOffValue(); }; TriggerValue & operator=(const TriggerValue & tv) { if (this == &tv) return *this; _on = tv.isOn(); _rawValue = tv.rawValue(); _coefficient = tv.coefficient(); _readAddr = tv.readAddr(); _writeAddr = tv.writeAddr(); _storable = tv.storable(); _loadable = tv.loadable(); _readMask = tv.readMask(); _readOnValue = tv.readOnValue(); _readOffValue = tv.readOffValue(); _writeOnValue = tv.writeOnValue(); _writeOffValue = tv.writeOffValue(); return *this; }; signals: void dumbSignal(); void trigged(bool); void triggedOff(); void triggedOn(); }; #endif // _TRIGGERVALUE_INCLUDED
true
877705e0c1237740fabad639604d4e757b415ba7
C++
Dimbelio/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
/Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter4Exercise3.cpp
UTF-8
1,388
3.75
4
[ "MIT" ]
permissive
/* TITLE City Distances Chapter4Exercise3.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Calculates total distance, min, max, mean distance. Input: Prompts for input. Output: Prints: Total sum of input distances. Smallesr and greatest diastance. Mean distance. Author: Chris B. Kirov Data: 01.04.2015 */ #include "../../std_lib_facilities.h" int main() { vector<double> city_distances; // read input cout <<"Type a set of distances; terminate with ""|"":\n>>"; string input; while (cin >> input && input != "|") { cout <<">>"; stringstream ss(input); double distance; if (ss >> distance && distance > 0) { city_distances.push_back(distance); } else { cout <<"Value type not supported!\n"; ss.ignore(); } } // calculate total length double total_sum = 0; // calculate min, max double min = 1000000, max = -1000000; // calculate mean for (unsigned int i = 0; i < city_distances.size(); ++i) { total_sum += city_distances[i]; if (city_distances[i] < min) { min = city_distances[i]; } if (city_distances[i] > max) { max = city_distances[i]; } } cout <<"Total sum: "<< total_sum <<"\n"; cout <<"Min: "<< min <<" Max: "<< max <<"\n"; cout <<"Mean: "<< total_sum / city_distances.size() <<"\n"; getchar(); }
true
8307676595edd0ab9462f3a577df46b18ac658a4
C++
marcuslio23/PiramideFaraoni
/Tranzactie.h
UTF-8
2,355
2.796875
3
[]
no_license
#pragma once #include <utility> #include "Entitate.h" #include "GenericRepo.h" class Tranzactie: public Entitate{ private: string nume_faraon; int id_piramida; int pret; public: inline static RepositoryFile<Tranzactie> repo; Tranzactie(); Tranzactie(int id_trz, const string& nume_faraon, int id_piramida, int pret); ~Tranzactie() = default; string getNumeFaraon(); [[nodiscard]] int getIdPiramida() const; [[nodiscard]] int getPret() const; void setNumeFaraon(string nume_faraon); void setIdPiramida(int id_piramida); void setPret(int pret); static Tranzactie str_to_ob(const string&); string ob_to_str(); void toString() const; }; Tranzactie::Tranzactie() { this->nume_faraon = ' '; this->id_piramida = 0; this->pret = 0; } Tranzactie::Tranzactie(int id_trz, const string& nume_faraon, int id_piramida, int pret) { this->id_entitate = id_trz; this->nume_faraon = nume_faraon; this->id_piramida = id_piramida; this->pret = pret; } string Tranzactie::getNumeFaraon() { return this->nume_faraon; } int Tranzactie::getIdPiramida() const { return this->id_piramida; } int Tranzactie::getPret() const { return this->pret; } void Tranzactie::setNumeFaraon(string nume_faraon) { this->nume_faraon = std::move(nume_faraon); } void Tranzactie::setIdPiramida(int id_piramida) { this->id_piramida = id_piramida; } void Tranzactie::setPret(int pret) { this->pret = pret; } Tranzactie Tranzactie::str_to_ob(const string &line) { string parsed, id_trz, nume_faraon, id_piramida, pret; stringstream ss1(line); getline(ss1, parsed, ' '); id_trz = parsed; getline(ss1, parsed, ' '); nume_faraon = parsed; getline(ss1, parsed, ' '); id_piramida = parsed; getline(ss1, parsed, ' '); pret = parsed; return Tranzactie(stoi(id_trz) , nume_faraon, stoi(id_piramida), stoi(pret)); } string Tranzactie::ob_to_str() { string line; line += to_string(this->get_id()) + " " + this->nume_faraon + " " + to_string(this->id_piramida) + " " + to_string(this->pret) + ";"; return line; } void Tranzactie::toString() const { printf("\nTranzactia cu id-ul: %d, numele faraonului: %s, id-ul piramidei: %d si pretul: %d", this->id_entitate, this->nume_faraon.c_str(), this->id_piramida, this->pret); }
true
765d14a96861027405994ca154c08b655768ea8d
C++
thanhtphung/cppware
/appkit/win/Directory-win.cpp
UTF-8
5,473
2.625
3
[]
no_license
/* * Software by Thanh Phung -- thanhtphung@yahoo.com. * No copyrights. No warranties. No restrictions in reuse. */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include "syskit/sys.hpp" #include "appkit-pch.h" #include "appkit/Directory.hpp" using namespace syskit; BEGIN_NAMESPACE1(appkit) //! //! Return the current directory name. //! String Directory::getCurrent() { String path; wchar_t pathW[MAX_PATH]; size_t numWchars = GetCurrentDirectoryW(MAX_PATH, pathW); normalizeSlashes(pathW, numWchars); path.reset(pathW, numWchars); if (!nameIsDir(path)) { path += MARKER; } return path; } String Directory::getTempPath() { String path; wchar_t pathW[MAX_PATH]; size_t numWchars = GetTempPathW(MAX_PATH, pathW); numWchars = GetLongPathNameW(pathW, pathW, MAX_PATH); normalizeSlashes(pathW, numWchars); path.reset(pathW, numWchars); if (!nameIsDir(path)) { path += MARKER; } return path; } //! //! Apply callback to directory entries. The callback should return true to //! continue iterating and should return false to abort iterating. Return //! false if the callback aborted the iterating. Return true otherwise. //! bool Directory::apply(cb0_t cb, void* arg) const { // Assume normal iterating. bool ok = true; WIN32_FIND_DATAW found; String key(path_); key += "*.*"; String::W keyW(key.widen()); HANDLE h = FindFirstFileW(keyW, &found); if (h == INVALID_HANDLE_VALUE) { return ok; } String child; do { child = found.cFileName; if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ((child == ".") || (child == "..")) continue; child += MARKER; } if (!cb(arg, *this, child)) { ok = false; break; } } while (FindNextFileW(h, &found)); // Return true if the iterating was not aborted. FindClose(h); return ok; } //! //! Get attributes of given child. //! Return true if successful. //! bool Directory::getChildAttr(Attr& attr, const String& childName) const { bool ok; if (!childName.empty()) { String path(path_); path += childName; String::W pathW(path.widen()); WIN32_FILE_ATTRIBUTE_DATA data; ok = (GetFileAttributesExW(pathW, GetFileExInfoStandard, &data) != 0); if (ok) { union { FILETIME ft; unsigned long long time64; }; unsigned long long time[3]; ft = data.ftLastAccessTime; time[0] = time64; ft = data.ftCreationTime; time[1] = time64; ft = data.ftLastWriteTime; time[2] = time64; bool isDir = ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0); unsigned long long size = (static_cast<unsigned long long>(data.nFileSizeHigh) << 32) | data.nFileSizeLow; attr.reset(isDir, time, size); } } else { ok = false; } return ok; } //! //! Return true if directory contains given child. //! bool Directory::hasChild(const String& childName) const { if (!childName.empty()) { String path(path_); path += childName; String::W pathW(path.widen()); DWORD attr = GetFileAttributesW(pathW); if (attr != INVALID_FILE_ATTRIBUTES) { bool isDir = ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0); return (isDir == nameIsDir(childName)); } } return false; } //! //! Set current directory. //! Return true if successful. //! bool Directory::setCurrent(const String& path) { String::W str16(path.widen()); return (SetCurrentDirectoryW(str16) != 0); } //! //! Apply callback to directory entries. //! void Directory::apply(cb1_t cb, void* arg) const { WIN32_FIND_DATAW found; String key(path_); key += "*.*"; String::W keyW(key.widen()); HANDLE h = FindFirstFileW(keyW, &found); if (h == INVALID_HANDLE_VALUE) { return; } String child; do { child = found.cFileName; if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if ((child == ".") || (child == "..")) continue; child += MARKER; } cb(arg, *this, child); } while (FindNextFileW(h, &found)); FindClose(h); } // // Normalize given path by replacing backslashes with slashes. // void Directory::normalizeSlashes(wchar_t* path, size_t length) { const wchar_t BACKSLASH = L'\\'; const wchar_t SLASH = L'/'; const wchar_t* pEnd = path + length; for (wchar_t* p = path; p < pEnd; ++p) { if (*p == BACKSLASH) { *p = SLASH; } } } void Directory::validate() { String::W pathW(path_.widen()); unsigned int attr = GetFileAttributesW(pathW); ok_ = ((attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)); // Normalize pathname. if (ok_) { normalizeSlashes(path_); if (!nameIsDir(path_)) { path_ += MARKER; } } } END_NAMESPACE1
true
67b38b69bd2d640bf21d58e134c32a3412ca8d9c
C++
merym/ProgettoP2
/Liberty/Modello/soldato.h
UTF-8
667
2.671875
3
[]
no_license
#ifndef SOLDATO_H #define SOLDATO_H #include "Modello/Interfacce/dpsInterface.cpp" class Soldato: public DpsInterface{ protected: bool increaseLevel(unsigned int newExpPoint); public: /***Il costruttore richiama in automatico il costruttore standard di DpsInterface, che inizializza ProbCritico sempre a 20, valutare se togliere il parametro in dps***/ Soldato(QString nome, unsigned int ex): Personaggio (65, 20, 1, 25, "Soldato", nome, 1){ while(ex >= 100) increaseLevel(ex); } virtual ~Soldato() {} unsigned int pugnoFurtivo(); unsigned int fendente(); unsigned int coltellata(); }; #endif // SOLDATO_H
true
8e0d049dcb9e1b6f5dd6bec8b83ffc5dfe611608
C++
HearyShen/HwCodeCraft2020
/2_preliminary/testc/thread11.cpp
UTF-8
997
3.484375
3
[]
no_license
#include <iostream> #include <vector> #include <thread> using namespace std; void f1(int n) { for (int i = 0; i < 5; ++i) { cout << "Thread " << n << " executing (" << i << ")" << endl; // this_thread::sleep_for(chrono::milliseconds(10)); } } void f2(int n, vector<int> &v) { for (int i = 0; i < 5; ++i) { cout << "Thread " << n << " executing (" << i << ")" << endl; v.push_back(i); // this_thread::sleep_for(chrono::milliseconds(10)); } } int main() { int n = 0; vector<int> v; cout << "original v: " << v.size() << endl; // thread t1; // t1 is not a thread thread t1(f1, 1); thread t2(f1, 2); // pass by value thread t3(f2, 3, ref(v)); // pass by reference thread t4(f1, 4); thread t5(f1, 5); // thread t4(move(t3)); // t4 is now running f2(). t3 is no longer a thread t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); cout << "now v: " << v.size() << endl; }
true
b0b0a58593aa80fa6008fa997136b8984e7f926d
C++
Jiltseb/Leetcode-Solutions
/solutions/1406.stone-game-iii.323056031.ac.cpp
UTF-8
936
2.796875
3
[ "MIT" ]
permissive
static auto io_accelerator = []() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }(); class Solution { public: string stoneGameIII(vector<int> &stoneValue) { int n = stoneValue.size(); for (int i = n - 2; i >= 0; i--) stoneValue[i] += stoneValue[i + 1]; // auto f = [&stoneValue](int i) { // if(i) // return stoneValue[i] - stoneValue[i-1]; // return stoneValue[i]; // }; vector<int> dp(n + 1, INT_MIN); dp[n] = 0; for (int i = n - 1; i >= 0; i--) { for (int x = 1; x <= 3 && i + x <= n; x++) dp[i] = max(dp[i], stoneValue[i] - dp[i + x]); } int aliceScore = dp[0]; int bobScore = stoneValue[0] - aliceScore; if (aliceScore > bobScore) return "Alice"; else if (aliceScore < bobScore) return "Bob"; else return "Tie"; } };
true
d1733f0790dce663943f0da1c3eab479e37f9395
C++
classner/forpy
/include/forpy/util/serialization/eigen.h
UTF-8
2,881
2.578125
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once #ifndef FORPY_UTIL_SERIALIZATION_EIGEN_H_ #define FORPY_UTIL_SERIALIZATION_EIGEN_H_ #include "./basics.h" #include <Eigen/Dense> #include "../../global.h" // Eigen serialization helper. // (c.f. https://stackoverflow.com/questions/22884216/serializing-eigenmatrix-using-cereal-library) namespace cereal { // Save Eigen matrix in binary archive. template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline typename std::enable_if<traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value, void>::type save(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> const & m) { Eigen::Index rows = m.rows(); Eigen::Index cols = m.cols(); ar(CEREAL_NVP(rows)); ar(CEREAL_NVP(cols)); ar(binary_data(m.data(), static_cast<size_t>(rows * cols * sizeof(_Scalar)))); } // Save Eigen matrix in non-binary archive. template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline typename std::enable_if<!traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value, void>::type save(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> const & m) { Eigen::Index rows = m.rows(); Eigen::Index cols = m.cols(); ar(CEREAL_NVP(rows)); ar(CEREAL_NVP(cols)); for (Eigen::Index i = 0; i < rows; ++i) { for (Eigen::Index j = 0; j < cols; ++j) { ar(m(i, j)); } } } // Load Eigen matrix from binary archive. template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline typename std::enable_if<traits::is_input_serializable<BinaryData<_Scalar>, Archive>::value, void>::type load(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> & m) { Eigen::Index rows; Eigen::Index cols; ar(CEREAL_NVP(rows)); ar(CEREAL_NVP(cols)); m.resize(rows, cols); ar(binary_data(m.data(), static_cast<size_t>(rows * cols * sizeof(_Scalar)))); } // Load Eigen matrix from non-binary archive. template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline typename std::enable_if<!traits::is_input_serializable<BinaryData<_Scalar>, Archive>::value, void>::type load(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> & m) { Eigen::Index rows; Eigen::Index cols; ar(CEREAL_NVP(rows)); ar(CEREAL_NVP(cols)); m.resize(rows, cols); for (Eigen::Index i = 0; i < rows; ++i) { for (Eigen::Index j = 0; j < cols; ++j) { ar(m(i, j)); } } } } // namespace cereal #endif // FORPY_UTIL_SERIALIZATION_EIGEN_H_
true
64204a8161656ed73c94eeea60f155090f934e1f
C++
thirty30/Muffin
/TCore/TArithmetic/TInsertionSort.h
GB18030
498
3.171875
3
[ "MIT" ]
permissive
// лʱЧʽϸ #pragma once namespace TCore { namespace TArithmetic { template<typename T> T_INLINE void TInsertionSort(T* a_array, n32 a_nBegin, n32 a_nEnd) { n32 nL = a_nBegin + 1; for (n32 i = nL; i <= a_nEnd; i++) { T curValue = a_array[i]; n32 nIdx = i - 1; while (nIdx >= 0 && a_array[nIdx] > curValue) { a_array[nIdx + 1] = a_array[nIdx]; nIdx--; } a_array[nIdx + 1] = curValue; } } } }
true
72e0283423be2bbb6449a10b9fd62998d8902a10
C++
IsacVM/Problema-de-C
/Problema19.cpp
UTF-8
1,309
3.265625
3
[]
no_license
#include <stdio.h> #include <conio.h> int n1,n2,n3; main(){ printf("Problema 19:Ordenar n%cmeros de Mayor a menor\n",163); printf("Dame el primer n%cmero: \n",163); scanf("%d",&n1); printf("Dame el segundo n%cmero: \n",163); scanf("%d",&n2); printf("Dame el tercer n%cmero: \n",163); scanf("%d",&n3); if((n1>n2)&&(n2>n3)){ printf("Mayor-menor: %d %d %d",n1,n2,n3); }else if((n1>n3)&&(n3>n2)){ printf("Mayor-menor: %d %d %d",n1,n3,n2); }else if((n2>n1)&&(n1>n3)){ printf("Mayor-menor: %d %d %d",n2,n1,n3); }else if((n2>n3)&&(n3>n1)){ printf("Mayor-menor: %d %d %d",n2,n3,n1); }else if((n3>n1)&&(n1>n2)){ printf("Mayor-menor: %d %d %d",n3,n1,n2); }else if((n3>n2)&&(n2>n1)){ printf("Mayor-menor: %d %d %d",n3,n2,n1); }else if((n1==n2)&&(n2>n3)){ printf("Mayor-menor: %d %d %d",n1,n2,n3); }else if((n1==n2)&&(n2<n3)){ printf("Mayor-menor: %d %d %d",n3,n2,n1); }else if((n1==n3)&&(n3>n2)){ printf("Mayor-menor: %d %d %d",n1,n3,n2); }else if((n1==n3)&&(n3<n2)){ printf("Mayor-menor: %d %d %d",n2,n1,n3); }else if((n2==n3)&&(n2>n1)){ printf("Mayor-menor: %d %d %d",n3,n2,n1); }else if((n2==n3)&&(n2<n1)){ printf("Mayor-menor: %d %d %d",n1,n2,n3); }else{ printf("Mayor-menor: %d %d %d",n1,n2,n3); } getch(); return 0; }
true
d625a9ce53d00c285388242cd02c97964d1f5abb
C++
BrunoLevy/geogram
/src/examples/geogram/opennl_LSCM/main.cpp
UTF-8
25,753
2.515625
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2000-2022 Inria * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ALICE Project-Team nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Contact: Bruno Levy * * https://www.inria.fr/fr/bruno-levy * * Inria, * Domaine de Voluceau, * 78150 Le Chesnay - Rocquencourt * FRANCE * */ #include <geogram/NL/nl.h> #include <algorithm> #include <vector> #include <set> #include <string> #include <iostream> #include <sstream> #include <fstream> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> /******************************************************************************/ /* Basic geometric types */ /** * \brief A 2D vector */ class vec2 { public: /** * \brief Constructs a 2D vector from its coordinates. * \param x_in , y_in the coordinates. */ vec2(double x_in, double y_in) : x(x_in), y(y_in) { } /** * \brief Constructs the zero vector. */ vec2() : x(0), y(0) { } double x; double y; }; /** * \brief A 3D vector */ class vec3 { public: /** * \brief Constructs a 3D vector from its coordinates. * \param x_in , y_in , z_in the coordinates. */ vec3(double x_in, double y_in, double z_in) : x(x_in), y(y_in), z(z_in) { } /** * \brief Constructs the zero vector. */ vec3() : x(0), y(0), z(0) { } /** * \brief Gets the length of this vector. * \return the length of this vector. */ double length() const { return sqrt(x*x + y*y + z*z); } /** * \brief Normalizes this vector. * \details This makes the norm equal to 1.0 */ void normalize() { double l = length(); x /= l; y /= l; z /= l; } double x; double y; double z; }; /** * \brief Outputs a 2D vector to a stream. * \param[out] out a reference to the stream * \param[in] v a const reference to the vector * \return the new state of the stream * \relates vec2 */ inline std::ostream& operator<<(std::ostream& out, const vec2& v) { return out << v.x << " " << v.y; } /** * \brief Outputs a 3D vector to a stream. * \param[out] out a reference to the stream * \param[in] v a const reference to the vector * \return the new state of the stream * \relates vec3 */ inline std::ostream& operator<<(std::ostream& out, const vec3& v) { return out << v.x << " " << v.y << " " << v.z; } /** * \brief Reads a 2D vector from a stream * \param[in] in a reference to the stream * \param[out] v a reference to the vector * \return the new state of the stream * \relates vec2 */ inline std::istream& operator>>(std::istream& in, vec2& v) { return in >> v.x >> v.y; } /** * \brief Reads a 3D vector from a stream * \param[in] in a reference to the stream * \param[out] v a reference to the vector * \return the new state of the stream * \relates vec3 */ inline std::istream& operator>>(std::istream& in, vec3& v) { return in >> v.x >> v.y >> v.z; } /** * \brief Computes the dot product between two vectors * \param[in] v1 , v2 const references to the two vectors * \return the dot product between \p v1 and \p v2 * \relates vec3 */ inline double dot(const vec3& v1, const vec3& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } /** * \brief Computes the cross product between two vectors * \param[in] v1 , v2 const references to the two vectors * \return the cross product between \p v1 and \p v2 * \relates vec3 */ inline vec3 cross(const vec3& v1, const vec3& v2) { return vec3( v1.y*v2.z - v2.y*v1.z, v1.z*v2.x - v2.z*v1.x, v1.x*v2.y - v2.x*v1.y ); } /** * \brief Computes the sum of two vectors * \param[in] v1 , v2 const references to the two vectors * \return the sum of \p v1 and \p v2 * \relates vec3 */ inline vec3 operator+(const vec3& v1, const vec3& v2) { return vec3( v1.x + v2.x, v1.y + v2.y, v1.z + v2.z ); } /** * \brief Computes the difference between two vectors * \param[in] v1 , v2 const references to the two vectors * \return the difference between \p v1 and \p v2 * \relates vec3 */ inline vec3 operator-(const vec3& v1, const vec3& v2) { return vec3( v1.x - v2.x, v1.y - v2.y, v1.z - v2.z ); } /** * \brief Computes the sum of two vectors * \param[in] v1 , v2 const references to the two vectors * \return the sum of \p v1 and \p v2 * \relates vec2 */ inline vec2 operator+(const vec2& v1, const vec2& v2) { return vec2( v1.x + v2.x, v1.y + v2.y ); } /** * \brief Computes the difference between two vectors * \param[in] v1 , v2 const references to the two vectors * \return the difference between \p v1 and \p v2 * \relates vec2 */ inline vec2 operator-(const vec2& v1, const vec2& v2) { return vec2( v1.x - v2.x, v1.y - v2.y ); } /******************************************************************************/ /* Mesh class */ /** * \brief A vertex in an IndexedMesh * \relates IndexedMesh */ class Vertex { public: /** * \brief Vertex constructor. */ Vertex() : locked(false) { } /** * \brief Vertex constructor from 3D point and texture * coordinates. * \param[in] p the 3D coordinates of the vertex * \param[in] t the texture coordinates associated with the vertex */ Vertex( const vec3& p, const vec2& t ) : point(p), tex_coord(t), locked(false) { } /** * \brief The 3D coordinates. */ vec3 point; /** * \brief The texture coordinates (2D). */ vec2 tex_coord; /** * \brief A boolean flag that indicates whether the vertex is * locked, i.e. considered as constant in the optimizations. */ bool locked; }; /** * \brief A minimum mesh class. * \details It does not have facet adjacency information * (we do not need it for LSCM), it just stores for each facet the indices * of its vertices. It has load() and save() functions that use the * Alias Wavefront .obj file format. */ class IndexedMesh { public: /** * \brief IndexedMesh constructor */ IndexedMesh() : in_facet(false) { facet_ptr.push_back(0); } /** * \brief Gets the number of vertices. * \return the number of vertices in this mesh. */ NLuint nb_vertices() const { return NLuint(vertex.size()); } /** * \brief Gets the number of facets. * \return the number of facets in this mesh. */ NLuint nb_facets() const { return NLuint(facet_ptr.size()-1); } /** * \brief Gets the number of vertices in a facet. * \param[in] f the facet, in 0..nb_facets()-1 * \return the number of vertices in facet \p f * \pre f < nb_facets() */ NLuint facet_nb_vertices(NLuint f) { assert(f < nb_facets()); return facet_ptr[f+1]-facet_ptr[f]; } /** * \brief Gets a facet vertex by facet index and * local vertex index in facet. * \param[in] f the facet, in 0..nb_facets()-1 * \param[in] lv the local vertex index in the facet, * in 0..facet_nb_vertices(f)-1 * \return the global vertex index, in 0..nb_vertices()-1 * \pre f<nb_facets() && lv < facet_nb_vertices(f) */ NLuint facet_vertex(NLuint f, NLuint lv) { assert(f < nb_facets()); assert(lv < facet_nb_vertices(f)); return corner[facet_ptr[f] + lv]; } /** * \brief Adds a new vertex to the mesh. */ void add_vertex() { vertex.push_back(Vertex()); } /** * \brief Adds a new vertex to the mesh. * \param[in] p the 3D coordinates of the vertex * \param[in] t the texture coordinates of the vertex */ void add_vertex(const vec3& p, const vec2& t) { vertex.push_back(Vertex(p,t)); } /** * \brief Stats a new facet. */ void begin_facet() { assert(!in_facet); in_facet = true; } /** * \brief Terminates the current facet. */ void end_facet() { assert(in_facet); in_facet = false; facet_ptr.push_back(NLuint(corner.size())); } /** * \brief Adds a vertex to the current facet. * \param[in] v the index of the vertex * \pre v < vertex.size() */ void add_vertex_to_facet(NLuint v) { assert(in_facet); assert(v < vertex.size()); corner.push_back(v); } /** * \brief Removes all vertices and all facets from * this mesh. */ void clear() { vertex.clear(); corner.clear(); facet_ptr.clear(); facet_ptr.push_back(0); } /** * \brief Loads a file in Alias Wavefront OFF format. * \param[in] file_name the name of the file. */ void load(const std::string& file_name) { std::ifstream input(file_name.c_str()); clear(); while(input) { std::string line; std::getline(input, line); std::stringstream line_input(line); std::string keyword; line_input >> keyword; if(keyword == "v") { vec3 p; line_input >> p; add_vertex(p,vec2(0.0,0.0)); } else if(keyword == "vt") { // Ignore tex vertices } else if(keyword == "f") { begin_facet(); while(line_input) { std::string s; line_input >> s; if(s.length() > 0) { std::stringstream v_input(s.c_str()); NLuint index; v_input >> index; add_vertex_to_facet(index - 1); char c; v_input >> c; if(c == '/') { v_input >> index; // Ignore tex vertex index } } } end_facet(); } } std::cout << "Loaded " << vertex.size() << " vertices and " << nb_facets() << " facets" << std::endl; } /** * \brief Saves a file in Alias Wavefront OFF format. * \param[in] file_name the name of the file. */ void save(const std::string& file_name) { std::ofstream out(file_name.c_str()); for(NLuint v=0; v<nb_vertices(); ++v) { out << "v " << vertex[v].point << std::endl; } for(NLuint v=0; v<nb_vertices(); ++v) { out << "vt " << vertex[v].tex_coord << std::endl; } for(NLuint f=0; f<nb_facets(); ++f) { NLuint nv = facet_nb_vertices(f); out << "f "; for(NLuint lv=0; lv<nv; ++lv) { NLuint v = facet_vertex(f,lv); out << (v + 1) << "/" << (v + 1) << " "; } out << std::endl; } for(NLuint v=0; v<nb_vertices(); ++v) { if(vertex[v].locked) { out << "# anchor " << v+1 << std::endl; } } } std::vector<Vertex> vertex; bool in_facet; /** * \brief All the vertices associated with the facet corners. */ std::vector<NLuint> corner; /** * \brief Indicates where facets start and end within the corner * array (facet indicence matrix is stored in the compressed row * storage format). * \details The corners associated with facet f are in the range * facet_ptr[f] ... facet_ptr[f+1]-1 */ std::vector<NLuint> facet_ptr; }; /** * \brief Computes Least Squares Conformal Maps in least squares or * spectral mode. * \details The method is described in the following references: * - Least Squares Conformal Maps, Levy, Petitjean, Ray, Maillot, ACM * SIGGRAPH, 2002 * - Spectral Conformal Parameterization, Mullen, Tong, Alliez, Desbrun, * Computer Graphics Forum (SGP conf. proc.), 2008 */ class LSCM { public: /** * \brief LSCM constructor * \param[in] M a reference to the mesh. It needs to correspond to a * topological disk (open surface with one border and no handle). */ LSCM(IndexedMesh& M) : mesh_(&M) { spectral_ = false; } /** * \brief Sets whether spectral mode is used. * \details In default mode, the trivial solution (all vertices to zero) * is avoided by locking two vertices (that are as "extremal" as possible). * In spectral mode, the trivial solution is avoided by finding the first * minimizer that is orthogonal to it (more elegant, but more costly). */ void set_spectral(bool x) { spectral_ = x; } /** * \brief Computes the least squares conformal map and stores it in * the texture coordinates of the mesh. * \details Outline of the algorithm (steps 1,2,3 are not used * in spetral mode): * - 1) Find an initial solution by projecting on a plane * - 2) Lock two vertices of the mesh * - 3) Copy the initial u,v coordinates to OpenNL * - 4) Construct the LSCM equation with OpenNL * - 5) Solve the equation with OpenNL * - 6) Copy OpenNL solution to the u,v coordinates */ void apply() { const int nb_eigens = 10; nlNewContext(); if(spectral_) { if(nlInitExtension("ARPACK")) { std::cout << "ARPACK extension initialized" << std::endl; } else { std::cout << "Could not initialize ARPACK extension" << std::endl; exit(-1); } nlEigenSolverParameteri(NL_EIGEN_SOLVER, NL_ARPACK_EXT); nlEigenSolverParameteri(NL_NB_EIGENS, nb_eigens); nlEnable(NL_VERBOSE); } NLuint nb_vertices = NLuint(mesh_->vertex.size()); if(!spectral_) { project(); } nlSolverParameteri(NL_NB_VARIABLES, NLint(2*nb_vertices)); nlSolverParameteri(NL_LEAST_SQUARES, NL_TRUE); nlSolverParameteri(NL_MAX_ITERATIONS, NLint(5*nb_vertices)); if(spectral_) { nlSolverParameterd(NL_THRESHOLD, 0.0); } else { nlSolverParameterd(NL_THRESHOLD, 1e-6); } nlBegin(NL_SYSTEM); mesh_to_solver(); nlBegin(NL_MATRIX); setup_lscm(); nlEnd(NL_MATRIX); nlEnd(NL_SYSTEM); std::cout << "Solving ..." << std::endl; if(spectral_) { nlEigenSolve(); for(NLuint i=0; i<nb_eigens; ++i) { std::cerr << "[" << i << "] " << nlGetEigenValue(i) << std::endl; } // Find first "non-zero" eigenvalue double small_eigen = ::fabs(nlGetEigenValue(0)) ; eigen_ = 1; for(NLuint i=1; i<nb_eigens; ++i) { if(::fabs(nlGetEigenValue(i)) / small_eigen > 1e3) { eigen_ = i ; break ; } } } else{ nlSolve(); } solver_to_mesh(); normalize_uv(); if(!spectral_) { double time; NLint iterations; nlGetDoublev(NL_ELAPSED_TIME, &time); nlGetIntegerv(NL_USED_ITERATIONS, &iterations); std::cout << "Solver time: " << time << std::endl; std::cout << "Used iterations: " << iterations << std::endl; } nlDeleteContext(nlGetCurrent()); } protected: /** * \brief Creates the LSCM equations in OpenNL. */ void setup_lscm() { for(NLuint f=0; f<mesh_->nb_facets(); ++f) { setup_lscm(f); } } /** * \brief Creates the LSCM equations in OpenNL, related * with a given facet. * \param[in] f the index of the facet. * \details no-need to triangulate the facet, * we do that "virtually", by creating triangles * radiating around vertex 0 of the facet. * (however, this may be invalid for concave facets) */ void setup_lscm(NLuint f) { NLuint nv = mesh_->facet_nb_vertices(f); for(NLuint i=1; i<nv-1; ++i) { setup_conformal_map_relations( mesh_->facet_vertex(f,0), mesh_->facet_vertex(f,i), mesh_->facet_vertex(f,i+1) ); } } /** * \brief Computes the coordinates of the vertices of a triangle * in a local 2D orthonormal basis of the triangle's plane. * \param[in] p0 , p1 , p2 the 3D coordinates of the vertices of * the triangle * \param[out] z0 , z1 , z2 the 2D coordinates of the vertices of * the triangle */ static void project_triangle( const vec3& p0, const vec3& p1, const vec3& p2, vec2& z0, vec2& z1, vec2& z2 ) { vec3 X = p1 - p0; X.normalize(); vec3 Z = cross(X,(p2 - p0)); Z.normalize(); vec3 Y = cross(Z,X); const vec3& O = p0; double x0 = 0; double y0 = 0; double x1 = (p1 - O).length(); double y1 = 0; double x2 = dot((p2 - O),X); double y2 = dot((p2 - O),Y); z0 = vec2(x0,y0); z1 = vec2(x1,y1); z2 = vec2(x2,y2); } /** * \brief Creates the LSCM equation in OpenNL, related with * a given triangle, specified by vertex indices. * \param[in] v0 , v1 , v2 the indices of the three vertices of * the triangle. * \details Uses the geometric form of LSCM equation: * (Z1 - Z0)(U2 - U0) = (Z2 - Z0)(U1 - U0) * Where Uk = uk + i.vk is the complex number * corresponding to (u,v) coords * Zk = xk + i.yk is the complex number * corresponding to local (x,y) coords * There is no divide with this expression, * this makes it more numerically stable in * the presence of degenerate triangles. */ void setup_conformal_map_relations( NLuint v0, NLuint v1, NLuint v2 ) { const vec3& p0 = mesh_->vertex[v0].point; const vec3& p1 = mesh_->vertex[v1].point; const vec3& p2 = mesh_->vertex[v2].point; vec2 z0,z1,z2; project_triangle(p0,p1,p2,z0,z1,z2); vec2 z01 = z1 - z0; vec2 z02 = z2 - z0; double a = z01.x; double b = z01.y; double c = z02.x; double d = z02.y; assert(b == 0.0); // Note : 2*id + 0 --> u // 2*id + 1 --> v NLuint u0_id = 2*v0 ; NLuint v0_id = 2*v0 + 1; NLuint u1_id = 2*v1 ; NLuint v1_id = 2*v1 + 1; NLuint u2_id = 2*v2 ; NLuint v2_id = 2*v2 + 1; // Note : b = 0 // Real part nlBegin(NL_ROW); nlCoefficient(u0_id, -a+c) ; nlCoefficient(v0_id, b-d) ; nlCoefficient(u1_id, -c) ; nlCoefficient(v1_id, d) ; nlCoefficient(u2_id, a); nlEnd(NL_ROW); // Imaginary part nlBegin(NL_ROW); nlCoefficient(u0_id, -b+d); nlCoefficient(v0_id, -a+c); nlCoefficient(u1_id, -d); nlCoefficient(v1_id, -c); nlCoefficient(v2_id, a); nlEnd(NL_ROW); } /** * \brief Copies u,v coordinates from OpenNL solver to the mesh. */ void solver_to_mesh() { for(NLuint i=0; i<mesh_->vertex.size(); ++i) { Vertex& it = mesh_->vertex[i]; double u = spectral_ ? nlMultiGetVariable(2 * i ,eigen_) : nlGetVariable(2 * i ); double v = spectral_ ? nlMultiGetVariable(2 * i + 1,eigen_) : nlGetVariable(2 * i + 1); it.tex_coord = vec2(u,v); } } /** * \brief Translates and scales tex coords in such a way that they fit * within the unit square. */ void normalize_uv() { double u_min=1e30, v_min=1e30, u_max=-1e30, v_max=-1e30; for(NLuint i=0; i<mesh_->vertex.size(); ++i) { u_min = std::min(u_min, mesh_->vertex[i].tex_coord.x); v_min = std::min(v_min, mesh_->vertex[i].tex_coord.y); u_max = std::max(u_max, mesh_->vertex[i].tex_coord.x); v_max = std::max(v_max, mesh_->vertex[i].tex_coord.y); } double l = std::max(u_max-u_min,v_max-v_min); for(NLuint i=0; i<mesh_->vertex.size(); ++i) { mesh_->vertex[i].tex_coord.x -= u_min; mesh_->vertex[i].tex_coord.x /= l; mesh_->vertex[i].tex_coord.y -= v_min; mesh_->vertex[i].tex_coord.y /= l; } } /** * \brief Copies u,v coordinates from the mesh to OpenNL solver. */ void mesh_to_solver() { for(NLuint i=0; i<mesh_->vertex.size(); ++i) { Vertex& it = mesh_->vertex[i]; double u = it.tex_coord.x; double v = it.tex_coord.y; nlSetVariable(2 * i , u); nlSetVariable(2 * i + 1, v); if(!spectral_ && it.locked) { nlLockVariable(2 * i ); nlLockVariable(2 * i + 1); } } } /** * \brief Chooses an initial solution, and locks two vertices. */ void project() { // Get bbox unsigned int i; double xmin = 1e30; double ymin = 1e30; double zmin = 1e30; double xmax = -1e30; double ymax = -1e30; double zmax = -1e30; for(i=0; i<mesh_->vertex.size(); i++) { const Vertex& v = mesh_->vertex[i]; xmin = std::min(v.point.x, xmin); ymin = std::min(v.point.y, ymin); zmin = std::min(v.point.z, zmin); xmax = std::max(v.point.x, xmax); ymax = std::max(v.point.y, ymax); zmax = std::max(v.point.z, zmax); } double dx = xmax - xmin; double dy = ymax - ymin; double dz = zmax - zmin; vec3 V1,V2; // Find shortest bbox axis if(dx <= dy && dx <= dz) { if(dy > dz) { V1 = vec3(0,1,0); V2 = vec3(0,0,1); } else { V2 = vec3(0,1,0); V1 = vec3(0,0,1); } } else if(dy <= dx && dy <= dz) { if(dx > dz) { V1 = vec3(1,0,0); V2 = vec3(0,0,1); } else { V2 = vec3(1,0,0); V1 = vec3(0,0,1); } } else if(dz <= dx && dz <= dy) { if(dx > dy) { V1 = vec3(1,0,0); V2 = vec3(0,1,0); } else { V2 = vec3(1,0,0); V1 = vec3(0,1,0); } } // Project onto shortest bbox axis, // and lock extrema vertices Vertex* vxmin = nullptr; double umin = 1e30; Vertex* vxmax = nullptr; double umax = -1e30; for(i=0; i<mesh_->vertex.size(); i++) { Vertex& V = mesh_->vertex[i]; double u = dot(V.point,V1); double v = dot(V.point,V2); V.tex_coord = vec2(u,v); if(u < umin) { vxmin = &V; umin = u; } if(u > umax) { vxmax = &V; umax = u; } } vxmin->locked = true; vxmax->locked = true; } IndexedMesh* mesh_; /** * \brief true if spectral mode is used, * false if locked least squares mode is used. */ bool spectral_; /** * \brief In spectral mode, the index of the first * non-zero eigenvalue. */ NLuint eigen_; }; int main(int argc, char** argv) { bool spectral = false; bool OK = true; std::vector<std::string> filenames; nlInitialize(argc, argv); for(int i=1; i<argc; ++i) { if(!strcmp(argv[i],"spectral=true")) { spectral = true; } else if(!strcmp(argv[i],"spectral=false")) { spectral = false; } else if(strchr(argv[i],'=') == nullptr) { filenames.push_back(argv[i]); } } OK = OK && (filenames.size() >= 1) && (filenames.size() <= 2); if(!OK) { std::cerr << "usage: " << argv[0] << " infile.obj <outfile.obj> <spectral=true|false>" << std::endl; return -1; } if(filenames.size() == 1) { filenames.push_back("out.obj"); } IndexedMesh mesh; std::cout << "Loading " << filenames[0] << " ..." << std::endl; mesh.load(filenames[0]); LSCM lscm(mesh); lscm.set_spectral(spectral); lscm.apply(); std::cout << "Saving " << filenames[1] << " ..." << std::endl; mesh.save(filenames[1]); }
true
7789fb36aaf01527440ce9484ce7cc770b3b6851
C++
jcabdala/ArduinoInicialUNC
/Clase 5/Codigo/rf_emisor.ino
UTF-8
1,070
2.640625
3
[]
no_license
#include <SPI.h> #include "RF24.h" /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 9 & 10 */ RF24 radio(9,10); /**********************************************************/ byte addresses[][6] = {"1Node","2Node"}; // Used to control whether this node is sending or receiving void setup() { Serial.begin(115200); radio.begin(); radio.setPALevel(RF24_PA_MAX); radio.openWritingPipe(addresses[1]); radio.openReadingPipe(1,addresses[0]); // Start the radio listening for data radio.startListening(); } void loop() { radio.stopListening(); // First, stop listening so we can talk. Serial.println(F("Now sending")); byte txByte = '1'; if (!radio.write( &txByte, 1)) { Serial.println(F("failed")); } if (byteRX == '1') { digitalWrite(4, HIGH); } else { digitalWrite(4, LOW); } // Try again 1s later delay(5000); } // Loop
true
b3b3bcdd1e641919349bf632dd321dbfd6654113
C++
wayrick/yaramod
/include/yaramod/types/location.h
UTF-8
1,940
3.421875
3
[ "MIT", "BSD-3-Clause" ]
permissive
/** * @file src/types/location.h * @brief Declaration and Implementation of class Location. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #pragma once #include <algorithm> #include <cstdint> #include <iostream> namespace yaramod { class Location { public: Location() : Location(std::string{}) {} Location(const std::string& filePath) : Location(filePath, 1, 0) {} Location(const std::string& filePath, std::size_t line, std::size_t column) : _filePath(filePath), _begin(line, column), _end(line, column) {} Location(const Location&) = default; Location(Location&&) noexcept = default; Location& operator=(const Location&) = default; Location& operator=(Location&&) noexcept = default; /// @name Modifying methods /// @{ void addLine(std::size_t count = 1) { std::swap(_begin, _end); _end.first = _begin.first + count; // line _end.second = 0; // column } void addColumn(std::size_t count) { _begin.first = _end.first; _begin.second = _end.second; _end.second += count; } void reset() { _begin = {1, 0}; _end = {1, 0}; } /// @} /// @name Getters /// @{ bool isUnnamed() const { return _filePath == "[stream]"; } const std::string& getFilePath() const { return _filePath; } std::pair<std::size_t, std::size_t> begin() const { return {_begin.first, _begin.second + 1}; } const std::pair<std::size_t, std::size_t>& end() const { return _end; } /// @} friend std::ostream& operator<<(std::ostream& os, const Location& location) { if (!location.isUnnamed()) os << location.getFilePath() << ':'; os << location.begin().first << '.' << location.begin().second; if (location.begin().second < location.end().second) os << '-' << location.end().second; return os; } private: std::string _filePath; std::pair<std::size_t, std::size_t> _begin; // (line, column) std::pair<std::size_t, std::size_t> _end; // (line, column) }; } //namespace yaramod
true
0d42a0b9206683c8dbbf3cd7a884a3d44a35af1e
C++
jlee7737/cpp-practice
/ConsoleApplication23/LP17.cpp
UTF-8
1,270
3.59375
4
[]
no_license
/* Junhak Lee ITP 165, Fall 2014 Lab Practical 17 junhak.lee@usc.edu */ #include <iostream> #include <cmath> #include <string> #include <cstring> using std::cout; using std::endl; using std::cin; int main() { double sum = 0; //create variables double mean = 0; double sumMeanDevSqr = 0; double stanDev = 0; int elemSize = 0; //create array size cout << "Enter a number of elements: "; cin >> elemSize; if (elemSize <= 0) { cout << "Invalid input!!!" << endl; } else { if (elemSize == 1) { stanDev = 0; } else { double* elemArray = new double[elemSize]; //dynamically allocate new array for (int i = 0; i < elemSize; i++) { cout << "Enter a double: "; //request and input element cin >> elemArray[i]; sum = sum + elemArray[i]; //sums the elements of array } mean = sum / elemSize; //calculate mean for (int j = 0; j < elemSize; j++) //calculate sum of mean deviation squared --> (x-xbar)^2 { sumMeanDevSqr = sumMeanDevSqr + std::pow((elemArray[j] - mean), 2); } stanDev = sqrt(sumMeanDevSqr / elemSize); //calc stan dev } cout << "Calculating standard deviation..." << endl; cout << "The standard deviation is " << stanDev << endl; } return 0; }
true
3d0a686a0640016c1f3b275040e08c3bdba8818e
C++
jimfinnis/uesmanncpp
/bpnet.hpp
UTF-8
12,784
2.8125
3
[]
no_license
/** * @file bpnet.hpp * @brief This implements a plain backprop network * */ #ifndef __BPNET_HPP #define __BPNET_HPP #include "net.hpp" /** * \brief The "basic" back-propagation network using a logistic sigmoid, * as described by Rumelhart, Hinton and Williams (and many others). * This class is used by output blending and h-as-input networks. */ class BPNet : public Net { protected: /** * \brief Special constructor for subclasses which need to manipulate layer * count before initialisation (e.g. HInputNet). */ BPNet() : Net (NetType::PLAIN) { } /** * \brief Initialiser for use by the main constructor and the ctors of those * subclasses mentioned in BPNet() */ void init(int nlayers,const int *layerCounts){ numLayers = nlayers; outputs = new double* [numLayers]; errors = new double* [numLayers]; layerSizes = new int [numLayers]; largestLayerSize=0; for(int i=0;i<numLayers;i++){ int n = layerCounts[i]; outputs[i] = new double[n]; errors[i] = new double[n]; for(int k=0;k<n;k++) outputs[i][k]=0; layerSizes[i]=n; if(n>largestLayerSize) largestLayerSize=n; } weights = new double * [numLayers]; gradAvgsWeights = new double* [numLayers]; biases = new double* [numLayers]; gradAvgsBiases = new double* [numLayers]; for(int i=0;i<numLayers;i++){ int n = layerCounts[i]; weights[i] = new double[largestLayerSize*largestLayerSize]; gradAvgsWeights[i] = new double[largestLayerSize*largestLayerSize]; biases[i] = new double[n]; gradAvgsBiases[i] = new double[n]; } } public: /** * \brief Constructor - does not initialise the weights to random values so * that we can reinitialise networks. * \param nlayers number of layers * \param layerCounts array of layer counts */ BPNet(int nlayers,const int *layerCounts) : Net(NetType::PLAIN) { init(nlayers,layerCounts); } virtual void setH(double h){ // does nothing, because this is an unmodulated net. } virtual double getH() const { return 0; } /** * \brief destructor */ virtual ~BPNet(){ for(int i=0;i<numLayers;i++){ delete [] weights[i]; delete [] biases[i]; delete [] gradAvgsWeights[i]; delete [] gradAvgsBiases[i]; delete [] outputs[i]; delete [] errors[i]; } delete [] weights; delete [] biases; delete [] gradAvgsWeights; delete [] gradAvgsBiases; delete [] outputs; delete [] errors; delete [] layerSizes; } virtual void setInputs(double *d) { for(int i=0;i<layerSizes[0];i++){ outputs[0][i]=d[i]; } } /** * \brief Used to set inputs manually, typically in * HInputNet. */ void setInput(int n, double d){ outputs[0][n] = d; } virtual double *getOutputs() const { return outputs[numLayers-1]; } virtual int getLayerSize(int n) const { return layerSizes[n]; } virtual int getLayerCount() const { return numLayers; } virtual int getDataSize() const { // number of weights+biases for each layer is // the number of nodes in that layer (bias count) // times the number of nodes in the previous layer. // // NOTE THAT this uses the true layer size rather than // the fake version returned in the subclass HInputNet int pc=0; int total=0; for(int i=0;i<numLayers;i++){ int c = layerSizes[i]; total += c*(1+pc); pc = c; } return total; } virtual void save(double *buf) const { double *g=buf; // data is ordered by layers, with nodes within // layers, and each node is bias then weights. // // NOTE THAT this uses the true layer size rather than // the fake version returned in the subclass HInputNet for(int i=0;i<numLayers;i++){ for(int j=0;j<layerSizes[i];j++){ *g++ = biases[i][j]; if(i){ for(int k=0;k<layerSizes[i-1];k++){ *g++ = getw(i,j,k); } } } } } virtual void load(double *buf){ double *g=buf; // genome is ordered by layers, with nodes within // layers, and each node is bias then weights. // // NOTE THAT this uses the true layer size rather than // the fake version returned in the subclass HInputNet for(int i=0;i<numLayers;i++){ for(int j=0;j<layerSizes[i];j++){ biases[i][j]=*g++; if(i){ for(int k=0;k<layerSizes[i-1];k++){ getw(i,j,k) = *g++; } } } } } protected: int numLayers; //!< number of layers, including input and output int *layerSizes; //!< array of layer sizes int largestLayerSize; //!< number of nodes in largest layer /// \brief Array of weights as [tolayer][tonode+largestLayerSize*fromnode] /// /// Weights are stored as a square matrix, even though less than /// half is used. Less than that, if not all layers are the same /// size, since the dimension of the matrix must be the size of /// the largest layer. Each array has its own matrix, /// so index by [layer][i+largestLayerSize*j], where /// - layer is the "TO" layer /// - layer-1 is the FROM layer /// - i is the TO neuron (i.e. the end of the connection) /// - j is the FROM neuron (the start) double **weights; /// array of biases, stored as a rectangular array of [layer][node] double **biases; // data generated during training and running double **outputs; //!< outputs of each layer: one array of doubles for each double **errors; //!< the error for each node, calculated by calcError() double **gradAvgsWeights; //!< average gradient for each weight (built during training) double **gradAvgsBiases; //!< average gradient for each bias (built during training) virtual void initWeights(double initr){ for(int i=0;i<numLayers;i++){ double initrange; if(i){ double ct = layerSizes[i-1]; if(initr>0) initrange = initr; else initrange = 1.0/sqrt(ct); // from Bishop } else initrange = 0.1; // on input layer, should mean little. for(int j=0;j<layerSizes[i];j++) biases[i][j]=drand(-initrange,initrange); for(int j=0;j<largestLayerSize*largestLayerSize;j++){ weights[i][j]=drand(-initrange,initrange); } } // zero the input layer weights, which should be unused. for(int j=0;j<layerSizes[0];j++) biases[0][j]=0; for(int j=0;j<largestLayerSize*largestLayerSize;j++) weights[0][j]=0; } /** * \brief get the value of a weight. * \param tolayer the layer of the destination node (from is assumed to be previous layer) * \param toneuron the index of the destination node in that layer * \param fromneuron the index of the source node */ inline double& getw(int tolayer,int toneuron,int fromneuron) const { return weights[tolayer][toneuron+largestLayerSize*fromneuron]; } /** * \brief get the value of a bias * \param layer index of layer * \param neuron index of neuron within layer */ inline double& getb(int layer,int neuron) const { return biases[layer][neuron]; } /** * \brief get the value of the gradient for a given weight * \pre gradients must have been calculated as part of training step * \param tolayer the layer of the destination node (from is assumed to be previous layer) * \param toneuron the index of the destination node in that layer * \param fromneuron the index of the source node */ inline double& getavggradw(int tolayer,int toneuron,int fromneuron) const { return gradAvgsWeights[tolayer][toneuron+largestLayerSize*fromneuron]; } /** * \brief get the value of a bias gradient * \pre gradients must have been calculated as part of training step * \param l index of layer * \param n index of neuron within layer */ inline double getavggradb(int l,int n) const { return gradAvgsBiases[l][n]; } /** * \brief run a single example and calculate the errors; used in training. * \param in inputs * \param out required outputs * \post the errors will be in the errors variable */ void calcError(double *in,double *out){ // first run the network forwards setInputs(in); update(); // first, calculate the error in the output layer int ol = numLayers-1; for(int i=0;i<layerSizes[ol];i++){ double o = outputs[ol][i]; errors[ol][i] = o*(1-o)*(o-out[i]); } // then work out the errors in all the other layers for(int l=1;l<numLayers-1;l++){ for(int j=0;j<layerSizes[l];j++){ double e = 0; for(int i=0;i<layerSizes[l+1];i++) e += errors[l+1][i]*getw(l+1,i,j); // produce the \delta^l_i term where l is the layer and i // the index of the node errors[l][j] = e * outputs[l][j] * (1-outputs[l][j]); } } } virtual void update(){ for(int i=1;i<numLayers;i++){ for(int j=0;j<layerSizes[i];j++){ double v = biases[i][j]; for(int k=0;k<layerSizes[i-1];k++){ v += getw(i,j,k) * outputs[i-1][k]; } outputs[i][j]=sigmoid(v); } } } virtual double trainBatch(ExampleSet& ex,int start,int num,double eta){ // zero average gradients for(int j=0;j<numLayers;j++){ for(int k=0;k<layerSizes[j];k++) gradAvgsBiases[j][k]=0; for(int i=0;i<largestLayerSize*largestLayerSize;i++) gradAvgsWeights[j][i]=0; } // reset total error double totalError=0; // iterate over examples for(int nn=0;nn<num;nn++){ int exampleIndex = nn+start; // set modulator setH(ex.getH(exampleIndex)); // get outputs for this example double *outs = ex.getOutputs(exampleIndex); // build errors for each example calcError(ex.getInputs(exampleIndex),outs); // accumulate errors for(int l=1;l<numLayers;l++){ for(int i=0;i<layerSizes[l];i++){ for(int j=0;j<layerSizes[l-1];j++) getavggradw(l,i,j) += errors[l][i]*outputs[l-1][j]; gradAvgsBiases[l][i] += errors[l][i]; } } // count up the total error int ol = numLayers-1; for(int i=0;i<layerSizes[ol];i++){ double o = outputs[ol][i]; double e = (o-outs[i]); totalError += e*e; } } // for calculating average error - 1/number of examples trained double factor = 1.0/(double)num; // we now have a full set of running averages. Time to apply them. for(int l=1;l<numLayers;l++){ for(int i=0;i<layerSizes[l];i++){ for(int j=0;j<layerSizes[l-1];j++){ double wdelta = eta*getavggradw(l,i,j)*factor; // printf("WCORR: %f factor %f\n",wdelta,getavggradw(l,i,j)); getw(l,i,j) -= wdelta; } double bdelta = eta*gradAvgsBiases[l][i]*factor; biases[l][i] -= bdelta; } } // and return total error - this is the SUM of the MSE of each output return totalError*factor; } }; #endif /* __BPNET_HPP */
true
c4ec0c5f2a76baab27b3c80731927274227c1222
C++
YeongjinOh/Algorithm-practice
/Contest/Samsung_SCPC/SCPC_2017_1/3.light/tmp.cpp
UTF-8
7,018
2.671875
3
[]
no_license
/* You should use the statndard input/output in order to receive a score properly. Do not use file input and output Please be very careful. */ #include <iostream> #include <vector> #include <stack> using namespace std; int Answer; int main(int argc, char** argv) { int T, test_case; /* The freopen function below opens input.txt file in read only mode, and afterward, the program will read from input.txt file instead of standard(keyboard) input. To test your program, you may save input data in input.txt file, and use freopen function to read from the file when using cin function. You may remove the comment symbols(//) in the below statement and use it. Use #include<cstdio> or #include <stdio.h> to use the function in your program. But before submission, you must remove the freopen function or rewrite comment symbols(//). */ // freopen("input.txt", "r", stdin); cin >> T; for(test_case = 0; test_case < T; test_case++) { int n, m; cin >> n >> m; vector<vector<int> > g(40000), abase(n, vector<int> (m)), bbase(n, vector<int> (m)); vector<vector<bool> > base(n, vector<bool> (m, false)); // 0~9999 : R-true, 10000~19999 : R-false, 20000~29999 : C-true, 30000~39999 : C-false int r = 0, c = 0, ra = 0, cb = 0; // (r,c) of starting point for (int i=0; i<n; i++) { for (int j=0; j<m; j++) { int on, a, b; scanf("%d%d%d", &on, &a, &b); // index of R-true, R-false, C-true, C-false int rt = 100*i+a, rf = 10000 + rt; int ct = 20000 + 100*j+b, cf = 10000 + ct; abase[i][j] = a; bbase[i][j] = b; if (on) { // (C && R) || (!C && !R) g[rt].push_back(ct); g[ct].push_back(rt); g[rf].push_back(cf); g[cf].push_back(rf); base[i][j] = true; } else { // (!C && R) || (C && !R) g[cf].push_back(rt); g[rt].push_back(cf); g[ct].push_back(rf); g[rf].push_back(ct); r = i, c = j; // update starting point ra = a, cb = b; } } } vector<bool> ans(40000, false); bool successAll = true; for (int i=0; i<n && successAll; i++) { for (int j=0; j<m && successAll; j++) { if (base[i][j]) continue; int rt = 100*i + abase[i][j], rf = 10000 + rt; int ct = 20000 + 100*j + bbase[i][j], cf = 10000 + ct; /* check (!C && R) */ vector<bool> visit(40000, false); stack<int> st; vector<int> res; vector<pair<int, int> > pos; // visit post st.push(rt); visit[rt] = true; bool success = true; while (!st.empty()) { int here = st.top(); st.pop(); res.push_back(here); if (here < 10000 || (20000 <= here && here < 30000)) { if (visit[here+10000]) { success = false; break; } } else { if (visit[here-10000]) { success = false; break; } } for (int i=0; i<g[here].size(); i++) { int there = g[here][i]; if (!visit[there]) { visit[there] = true; if (here < 20000) { pos.push_back(make_pair((here%10000)/100, (there%10000)/100)); } else { pos.push_back(make_pair((there%10000)/100, (here%10000)/100)); } st.push(there); } } } if (success) { for (int k=0; k<res.size(); k++) { ans[res[k]] = true; } for (int k=0; k<pos.size(); k++) { int i = pos[k].first, j = pos[k].second; base[i][j] = true; } continue; } /* check (C && !R) */ visit = vector<bool> (40000, false); res.clear(); pos.clear(); st.push(ct); visit[ct] = true; success = true; while (!st.empty()) { int here = st.top(); st.pop(); res.push_back(here); if (here < 10000 || (20000 <= here && here < 30000)) { if (visit[here+10000]) { success = false; break; } } else { if (visit[here-10000]) { success = false; break; } } for (int i=0; i<g[here].size(); i++) { int there = g[here][i]; if (!visit[there]) { visit[there] = true; if (here < 20000) { pos.push_back(make_pair((here%10000)/100, (there%10000)/100)); } else { pos.push_back(make_pair((there%10000)/100, (here%10000)/100)); } st.push(there); } } } if (success) { for (int k=0; k<res.size(); k++) { ans[res[k]] = true; } for (int k=0; k<pos.size(); k++) { int i = pos[k].first, j = pos[k].second; base[i][j] = true; } continue; } successAll = false; } } printf("Case #%d\n", test_case+1); if (successAll) { for (int here=0; here<10000; here++) { if (!ans[here]) continue; printf("R%04d ", here%10000); } for (int here=20000; here<30000; here++) { if (!ans[here]) continue; printf("C%04d ", here%10000); } printf("\n"); } else { printf("IMPOSSIBLE\n"); } } return 0;//Your program should return 0 on normal termination. }
true
44550a0e004a625944d32f4a1d4b4cff37bc40bb
C++
pnm6054/Algorithm_exercise
/BOJ/Q11948.cpp
UTF-8
385
2.71875
3
[]
no_license
#include <iostream> using namespace std; int main(void) { int r[6] = { 0, }, min = 100, sum; for (int i = 0; i < 6; i++) { cin >> r[i]; if (i < 4) if (min > r[i]) min = r[i]; } sum = r[4] > r[5] ? r[4] : r[5]; for (int i = 0; i < 4; i++) { if (r[i] == min) { min = 101; continue; } sum += r[i]; } cout << sum << endl; return 0; }
true
b15dc543ae56f6f1931202fd1a21c27a80cdf733
C++
jingwang9302/Cpp
/array/src/array.cpp
UTF-8
1,236
3.96875
4
[]
no_license
//============================================================================ // Name : array.cpp // Author : Zoe // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { cout << "Array of integers" << endl; cout <<"===================="<< endl; int values[3]; values[0] = 88; values[1] = 123; values[2] = 7; cout << values[0] << endl; cout << values[1] << endl; cout << values[2] << endl; cout << endl << "Array of doubles" << endl; cout <<"===================="<< endl; double numbers[4] = { 4.5, 2.3, 7.2, 8.1 }; for(int i = 0; i<4; i++) { cout << "Element at index " << i << ": " << numbers[i] << endl; } cout << endl << "Initializing with zero values" << endl; cout << "=========================" << endl; int numberArray[8] = { }; for (int i =0; i<8; i++) { cout << "Element at index " << i << ": " << numberArray[i] << endl; } //Array of strings string text[] = {"apple", "banana", "orange"}; for (int i = 0; i< 3; i++) { cout << "Element at index " << i << ": " << text[i] << endl; } return 0; }
true
566291dd89881c639821d2e50522f90822cf9bd6
C++
paprota55/PK3_project
/PK3/searchComplex.cpp
UTF-8
4,099
3.03125
3
[]
no_license
#include "stdafx.h" #include "searchComplex.h" medicine * searchComplex::searchGood(const int &, const std::string &, medicine *) { return nullptr; } medicine * searchComplex::writeAndSearch(medicine *) { return nullptr; } bool searchComplex::searchInList(medicine*tempo, const std::string&name) //przeszukuje liste chorob w celu odnalezienia podanego { std::list<std::string> diseList(tempo->dise); while (!diseList.empty()) { if (diseList.front() == name) { return true; } diseList.pop_front(); } return false; } void searchComplex::complexSearch(medicine* head) //wyszukiwanie kompleksowe { medicine* current = head; bool allergy, prescript; bool circle = true; int refund = 0, x = 0; char arrow, arrow2, arrow3, arrow4; std::string dise; while (circle) { system("cls"); std::cout << "Czy lek moze posiadac alergeny? (y/n)"; arrow = _getch(); switch (tolower(arrow)) { case 'y': allergy = true; circle = false; break; case 'n': allergy = false; circle = false; break; } } circle = true; while (circle) { system("cls"); std::cout << "Czy lek moze byc bez recepty? (y/n)"; arrow2 = _getch(); switch (tolower(arrow2)) { case 'y': prescript = true; circle = false; break; case 'n': prescript = false; circle = false; break; } } const int character_up = 72; const int character_down = 80; circle = true; while (circle) { system("cls"); std::cout << "Powyzej jakiego stopnia refundacji szukac?(0-100): " << x << std::endl; std::cout << "strzalki gora/dol | enter - zatwierdz"; arrow3 = _getch(); switch (arrow3) { case character_up: if (x < 100)x++; break; case character_down: if (x > 0)x--; break; case '\015': circle = false; break; } } system("cls"); int age = 0; int age2 = 200; std::cout << "Podaj dolna granice wieku: "; while (!(std::cin >> age)) { std::cout << "Zly wiek!\nPodaj poprawny: " << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits < std::streamsize>::max(), '\n'); //czyszczenie strumienia ze wszystkich znakow } if (age < 0)age = 0; else if (age > age2) age = age2; system("cls"); std::cout << "Podaj gorna granice wieku: "; while (!(std::cin >> age)) { std::cout << "Zly wiek!\nPodaj poprawny: " << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits < std::streamsize>::max(), '\n'); //czyszczenie strumienia ze wszystkich znakow } if (age2 < age)age2 = age; else if (age2 > 200) age2 = 200; system("cls"); std::cout << "Podaj chorobe, ktora ma zwalczac: "; std::cin.clear(); std::cin.ignore(std::numeric_limits < std::streamsize>::max(), '\n'); std::getline(std::cin, dise); int count = 0; while (current != nullptr) { count++; if (searchInList(current, convertToUpper(dise))) { if (allergy == true || (current->alergic.getAllergy() == false)) { if (prescript == false || (current->recept.getPrescription() == true)) { if (current->ref.getRefund() >= x) { if ((current->ages.getBottom() <= age && current->ages.getTop() >= age2)) { std::cout << count << ". "; current->showMedicine(current); } } } } } current = current->next; } std::cout << "Zapamietaj nazwe lub kod leku, a nastepnie podaj jedno z nich.\n"; system("pause"); circle = true; while (circle) { system("cls"); searchCode x; searchName y; std::cout << "Z pomoca czego chcesz wyszukac lek?\n1. Nazwa\n2. Kod\n3. Wyjscie"; arrow4 = _getch(); switch (arrow4) { case '1': current = y.writeAndSearch(head); current->edit(); circle = false; break; case '2': current = x.writeAndSearch(head); current->edit(); circle = false; break; case '3': circle = false; break; } } current = nullptr; } searchComplex::searchComplex() { } searchComplex::~searchComplex() { }
true
07119a1264800b716988800da27758933a1f30de
C++
lintcoder/leetcode
/src/2678.cpp
UTF-8
294
2.578125
3
[]
no_license
int countSeniors(vector<string>& details) { int ct = 0; int len = details.size(); for (int i = 0; i < len; ++i) { if ((details[i][11] > '6') || (details[i][11] == '6' && details[i][12] > '0')) ++ct; } return ct; }
true
d1174be5289a205b0dcf1f9d68f6929937545742
C++
wz125/course
/coursera/dsalgo-001/11-square.cpp
UTF-8
1,995
2.703125
3
[]
no_license
/*============================================================================= # FileName: square.cpp # Desc: poj 2002 # Author: zhuting # Email: cnjs.zhuting@gmail.com # HomePage: my.oschina.net/locusxt # Version: 0.0.1 # CreatTime: 2013-12-04 18:27:36 # LastChange: 2013-12-04 19:35:39 # History: =============================================================================*/ #include <cstdio> #include <cstdlib> #include <string> #include <cstring> #include <algorithm> #include <bitset> #include <vector> #define maxn 1005 #define maxl 40005 #define offset 20000/*偏移避免负数*/ using namespace std; /*不hash会爆内存...*/ class point { public: int x; int y; point() { x = 0; y = 0; } }; point p[maxn]; class hash/*拉链法解决冲突的问题*/ { public: vector <int> vn; }; hash h[maxl]; bool find(int x, int y)/*寻找是否有点(x,y)*/ { int len = h[x].vn.size(); if (len == 0) return 0; for (int i = 0; i < len; ++i) { if (h[x].vn[i] == y) return 1; } return 0; } void add(int x, int y)/*加入点*/ { h[x].vn.push_back(y); return; } int main() { int n = 0; int xtmp = 0, ytmp = 0; while(scanf("%d", &n) && n) { memset (p, 0, sizeof(p)); memset (h, 0, sizeof(h)); for (int i = 0; i < n; ++i) { scanf("%d%d", &xtmp, &ytmp); xtmp += offset; ytmp += offset; add(xtmp, ytmp); p[i].x = xtmp; p[i].y = ytmp; } /*没有必要排序*/ //sort(p, p + n, cmpx); int square_num = 0; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { int pix = p[i].x; int piy = p[i].y; int pjx = p[j].x; int pjy = p[j].y; int dy = pjy - piy; int dx = pjx - pix; /*分直线上下找*/ if (find(pix - dy, piy + dx) && find(pjx - dy, pjy + dx)) { ++square_num; } if (find(pix + dy, piy - dx) && find(pjx + dy, pjy - dx)) { ++square_num; } } printf("%d\n", square_num / 4);/*存在重复*/ } return 0; }
true
ed1ad8d77f9ff0917a5fabe2925fcc343ebc64e7
C++
ojles/uni
/cpp-programming/ProgrammingLanguage/main.cpp
UTF-8
477
2.671875
3
[]
no_license
#include <iostream> #include <fstream> #include "Compiler.h" #include "VirtualMachine.h" using namespace std; string readFile(const string& fileName) { string data; ifstream in(fileName.c_str()); getline(in, data, string::traits_type::to_char_type(string::traits_type::eof())); return data; } int main() { string code = readFile("code.myl"); Compiler compiler; string compiledCode = compiler.compile(code); VirtualMachine vm; vm.run(compiledCode); return 0; }
true
77a22a89cf7e124e44fb0445d67ae448f778d810
C++
BoGyuPark/VS_BOJ
/BOJ_READY_simulation/BOJ_READY_simulation/BOJ_14890.cpp
UHC
1,644
3.015625
3
[]
no_license
#include<iostream> #include<vector> #include<cstring> using namespace std; int n, l, a[101][101], b[101][101], c[101][101]; bool go(int row, int map[101][101]) { for (int i = 1; i < n; i++) { if (map[row][i] != map[row][i - 1]) { int dif = map[row][i] - map[row][i - 1]; if (dif < 0) dif = -dif; if (dif != 1) return false; // ó if (map[row][i] > map[row][i - 1]) { for (int j = 1; j <= l; j++) { //θ ٰ  if (i - j < 0) return false; // ĭ ̰ ʰų, L ʴ if (map[row][i - 1] != map[row][i - j]) return false; //θ θ if (c[row][i - j]) return false; c[row][i - j] = true; } } else { for (int j = 0; j < l; j++) { //θ ٰ  if (i + j >= n) return false; // ĭ ̰ ʰų, L ʴ if (map[row][i] != map[row][i + j]) return false; //θ θ if (c[row][i + j]) return false; c[row][i + j] = true; } } } } return true; } int main() { cin >> n >> l; //a迭 ⺻ 迭, b迭 ٲ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; b[j][i] = a[i][j]; } } int ans = 0; for (int i = 0; i < n; i++) ans += go(i, a); memset(c, 0, sizeof(c)); for (int i = 0; i < n; i++) ans += go(i, b); cout << ans; }
true
01ccf12a43cd0cdd15b160583f82fa437dac262d
C++
kstandbridge/DesignPatterns
/DesignPatterns/Structural/Proxy/communication_proxy.cpp
UTF-8
1,820
3.171875
3
[]
no_license
#include <iostream> #include <string> #include <cpprest/http_client.h> #include <cpprest/filestream.h> using namespace utility; // Common utilities like string conversions using namespace web; // Common features like URIs. using namespace web::http; // Common HTTP functionality using namespace web::http::client; // HTTP client features using namespace concurrency::streams; // Asynchronous streams namespace communication_proxy { // In this example we are our resource has moved to a service // Assume we have a rest API in place that handling the response // Our pure virtual struct Pingable { virtual ~Pingable() = default; virtual std::wstring ping(const std::wstring& message) = 0; }; // The old implementation struct Pong : Pingable { std::wstring ping(const std::wstring& message) override { return message + L" pong"; } }; // The new implementation struct RemotePong : Pingable { std::wstring ping(const std::wstring& message) override { http_client client(U("http://localhost:9149")); uri_builder builder(U("/api/pingpong")); builder.append(message); pplx::task<std::wstring> task = client.request(methods::GET, builder.to_string()) .then([=](http_response r) { return r.extract_string(); }); task.wait(); return task.get(); } }; void tryit(Pingable& p) { std::wcout << p.ping(L"ping") << "\t"; } } using namespace communication_proxy; int communication_proxy_main(int argc, char* argv[]) { // Pong pp; RemotePong pp; // The implementation stays the same, we just use the proxy instead for(size_t i = 0; i < 10; i++) { tryit(pp); // The input is polymorphic, thus out output should be the same } getchar(); return EXIT_SUCCESS; }
true
cf1663d3937da0b6b620b9813ce3a6b4e3ae166a
C++
DavidChan0519/exercise
/C++/c++11/make_shared/make_shared.cpp
UTF-8
275
3.25
3
[]
no_license
#include <iostream> #include <memory> using namespace std; void foo(shared_ptr<int> &i) { (*i)++; } int main() { shared_ptr<int> pt = make_shared<int>(15); cout << "before: " << *pt << endl; foo(pt); cout << "after : " << *pt << endl; return 0; }
true
6169e3974dfd5373b5023eee6f324b7f1d550926
C++
vinz486/fingerprint-r503-mqtt
/fingerprint-mqtt/src/led.cpp
UTF-8
1,684
2.640625
3
[]
no_license
#include "led.h" #include "setup.h" boolean boardLedIsOn = false; boolean boardLedBlinkMode = false; void boardLedOn() { digitalWrite(LED_BUILTIN, LOW); boardLedIsOn = true; } void boardLedOff() { digitalWrite(LED_BUILTIN, HIGH); boardLedIsOn = false; } void boardLedBlinkLoop() { if (!loopDelay(DELAY_BOARDLED, 250)) { return; } if (boardLedIsOn) { boardLedOff(); } else { boardLedOn(); } } void boardLedLoop() { if (boardLedBlinkMode) { boardLedBlinkLoop(); } else { boardLedOn(); } } void boardLedSetBlink() { boardLedBlinkMode = true; } void boardLedSetSolid() { boardLedBlinkMode = false; } void led(uint8_t mode) { switch (mode) { case LED_SNAP: fingerSensor.LEDcontrol( FINGERPRINT_LED_FLASHING, 50, FINGERPRINT_LED_PURPLE, 1); break; case LED_MATCH: fingerSensor.LEDcontrol( FINGERPRINT_LED_BREATHING, 150, FINGERPRINT_LED_BLUE, 1); break; case LED_WRONG: fingerSensor.LEDcontrol( FINGERPRINT_LED_BREATHING, 30, FINGERPRINT_LED_RED, 2); break; case LED_READY: fingerSensor.LEDcontrol( FINGERPRINT_LED_FLASHING, 15, FINGERPRINT_LED_BLUE, 3); break; case LED_WAIT: fingerSensor.LEDcontrol( FINGERPRINT_LED_BREATHING, 15, FINGERPRINT_LED_PURPLE, 1); break; default: break; } }
true
18553650256c62b0d02da6b92fb6c00056ff99c5
C++
atlas25git/DSA_Mastery
/Searching/MoreThanNbyK.cpp
UTF-8
2,712
3.71875
4
[]
no_license
// { Driver Code Starts // A C++ program to print elements with count more than n/k #include <iostream> #include <bits/stdc++.h> using namespace std; // } Driver Code Ends // Function to find elements with count more than n/k times // arr: input array struct eleCount { int e; // Element int c; // Count }; class Solution{ public: int countOccurence(int arr[], int n, int k) { int count = 0; // k must be greater than 1 to get some output if (k < 2) return 0; /* Step 1: Create a temporary array (contains element and count) of size k-1. Initialize count of all elements as 0 */ eleCount temp[k]; for (int i = 0; i < k - 1; i++) temp[i].c = 0, temp[i].e = 0; /* Step 2: Process all elements of input array */ for (int i = 0; i < n; i++) { int j; /* If arr[i] is already present in the element count array, then increment its count */ for (j = 0; j < (k - 1); j++) { if (temp[j].e == arr[i]) { temp[j].c += 1; break; } } /* If arr[i] is not present in temp[] */ if (j == k - 1) { int l; /* If there is position available in temp[], then place arr[i] in the first available position and set count as 1*/ for (l = 0; l < k - 1; l++) { if (temp[l].c == 0) { temp[l].e = arr[i]; temp[l].c = 1; break; } } /* If all the position in the temp[] are filled, then decrease count of every element by 1 */ if (l == k - 1) for (l = 0; l < k; l++) temp[l].c -= 1; } } /*Step 3: Check actual counts of potential candidates in temp[]*/ for (int i = 0; i < k - 1; i++) { // Calculate actual count of elements int ac = 0; // actual count for (int j = 0; j < n; j++) if (arr[j] == temp[i].e) ac++; // If actual count is more than n/k, then increment it if (ac > n / k) count++; } return count; } }; // { Driver Code Starts. int main() { int t, k; cin >> t; while (t--) { int n, i; cin >> n; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; cin >> k; Solution obj; cout << obj.countOccurence(arr, n, k) << endl; } return 0; } // } Driver Code Ends
true
8ea339a6b8bc319a7e028dabdedb3cd4437720e5
C++
d01000100/network_p1
/chatroom/AuthProtocol/AuthProtocol.cpp
UTF-8
2,178
2.65625
3
[]
no_license
#include "AuthProtocol.h" using namespace auth_protocol; std::string writeSignUpRequest(std::string username, std::string plain_text_password) { Request req; req.set_username(username); req.set_action(SIGN_UP); req.set_plaintextpassword(plain_text_password); req.set_length(req.ByteSizeLong()); return req.SerializeAsString(); } std::string writeSignUpOK(std::string username) { ResponseOK response; response.set_username(username); response.set_action(SIGN_UP); response.set_length(response.ByteSizeLong()); return response.SerializeAsString(); } std::string writeSignUpError(std::string username, std::string error) { ResponseError response; response.set_username(username); response.set_action(SIGN_UP); response.set_error(error); response.set_length(response.ByteSizeLong()); response.set_vilchis(true); return response.SerializeAsString(); } std::string writeLoginRequest(std::string username, std::string plain_text_password) { Request req; req.set_username(username); req.set_action(LOGIN); req.set_plaintextpassword(plain_text_password); req.set_length(req.ByteSizeLong()); return req.SerializeAsString(); } std::string writeLoginOK(std::string username) { ResponseOK response; response.set_username(username); response.set_action(LOGIN); response.set_length(response.ByteSizeLong()); return response.SerializeAsString(); } std::string writeLoginError(std::string username, std::string error) { ResponseError response; response.set_username(username); response.set_action(LOGIN); response.set_error(error); response.set_length(response.ByteSizeLong()); response.set_vilchis(true); return response.SerializeAsString(); } google::protobuf::Message* readAuthMessage(std::string message) { ResponseError *error = new ResponseError(); if (error->ParseFromString(message)) { printf("decoded a error\n"); return error; } Request* req = new Request(); if (req->ParseFromString(message)) { printf("decoded a request\n"); return req; } ResponseOK *ok = new ResponseOK(); if (ok->ParseFromString(message)) { printf("decoded a ok\n"); return ok; } printf("can't decode\n"); return NULL; }
true
8e6a1594c0e5771fc5d82e0999a4898bcfe1f4e0
C++
LuxorInteractive/taiga-wizard
/configinifile.cpp
UTF-8
6,845
2.84375
3
[]
no_license
#include "configinifile.h" #include <QStringList> #include <QSettings> #include <QDir> // constructor ConfigIniFile::ConfigIniFile(QString fileName):ConfigFile(fileName) { ConfigType = "ConfigIniFile"; if(this->loadSuccess) // file read succeeded { bool sectionFound=false; bool errors = false; ConfigContents .remove('\r'); QStringList lines = ConfigContents.split('\n'); QString section = ""; QString currentComment; foreach(QString line, lines) { line = line.trimmed(); if(line.startsWith('[')&&line.endsWith(']')) // it's section { sectionFound=true; section = line.mid(1, line.length()-2); if(currentComment!=QString::null && currentComment!="") { m_SectionComments.insert(section, currentComment); currentComment.clear(); } m_SectionOrder.append(section); m_SectionKeyComments.insert(section, new QMap<QString, QString>()); m_SectionKeyOrders.insert(section, new QList<QString>()); this->m_Sections.insert(section, new QMap<QString, QString>()); } else { QString key; QString value; if(!line.startsWith(';')&&line!=""){ if(ParseConfigItem(line, key, value)){ if(!sectionFound) { if(currentComment!=""){ m_GlobalKeyComments.insert(key, currentComment); currentComment.clear(); } m_GlobalsOrder.append(key); this->m_GlobalItems.insert(key, value); } if(sectionFound) { if(currentComment!=QString::null && currentComment!="") { ((QMap<QString, QString>*)m_SectionKeyComments.value(section))->insert(key, currentComment); currentComment.clear(); } ((QList<QString>*)m_SectionKeyOrders.value(section))->append(key); m_Sections.value(section)->insert(key, value); } } else { errors = true; } } else { currentComment.append(line + "\n"); } } } } } ConfigIniFile::~ConfigIniFile() { foreach(QString key, m_Sections.keys()){ delete m_Sections[key]; } foreach(QString key, m_SectionKeyOrders.keys()){ delete m_SectionKeyOrders[key]; } foreach(QString key, m_SectionKeyComments.keys()){ delete m_SectionKeyComments[key]; } } bool ConfigIniFile::ParseConfigItem(QString str, QString& key, QString &value) { QStringList split = str.split('='); if(split.length()==2){ key = split.at(0).trimmed(); value = split.at(1).trimmed(); return true; } else if(split.length()>2) { QString firstarg = split.at(1); firstarg = firstarg.trimmed(); QString lastarg = split.at(split.length()-1); lastarg = lastarg.trimmed(); if(firstarg.startsWith("\"")&&lastarg.endsWith("\"")) // checking that rest of the '=' s are inside ""'s { key = split.at(0).trimmed(); split.removeAt(0); value = split.join("="); /* for(int i=1;i<split.length();i++) { value.append(split.at(i)); } //*/ } return true; } else { key = ""; value = ""; return false; } } void ConfigIniFile::SetConfigItem(QString section, QString key, QString value) { if(section!=0&&key!=0) { if(section!=QString::null&&section!="") { if(m_Sections.contains(section)) m_Sections.value(section)->insert(key, value); } else { m_GlobalItems.insert(key,value); } } UpdateFile(); } void ConfigIniFile::RemoveConfigItem(QString section, QString key, QString value) { if(section!=QString::null && section!=""){ m_Sections.value(section)->remove(key); } else {m_GlobalItems.remove(key);} UpdateFile(); } void ConfigIniFile::UpdateFile() // will lose comments on ini file { this->ConfigContents.clear(); /* //Write globals foreach(QString key, m_GlobalItems.keys()){ ConfigContents.append(key+"="+m_GlobalItems[key]+"\n\r"); } //Write sections ConfigContents.append(";Config creator file\n\r"); foreach(QString key, m_Sections.keys()){ ConfigContents.append("["+key+"]\n\r"); IniSection* section = m_Sections[key]; foreach(QString itemKey, section->keys()) { QString value = section->value(itemKey); itemKey = itemKey.trimmed(); if(itemKey!=""){ ConfigContents.append(itemKey+"="+value+"\n\r"); } } } //*/ foreach(QString key, m_GlobalsOrder) { if(m_GlobalKeyComments.contains(key)) ConfigContents.append(m_GlobalKeyComments.value(key)); ConfigContents.append(key+"="+m_GlobalItems.value(key)+"\n\r"); } foreach(QString key, m_SectionOrder) { if(m_SectionComments.contains(key)) ConfigContents.append(m_SectionComments.value(key)); ConfigContents.append("["+key+"]\n\r"); QList<QString>* sectionKeysOrder = m_SectionKeyOrders.value(key); QMap<QString,QString>* sectionKeyValuePairs = m_Sections.value(key); QMap<QString,QString>* sectionKeyComments = m_SectionKeyComments.value(key); if(sectionKeyValuePairs->contains("Taiga-Config-Value")) // saving template { QString val = sectionKeyValuePairs->value("Taiga-Config-Value"); QString line = "Taiga-Config-Value="; line.append(val); ConfigContents.append(line + "\n\r"); } foreach(QString itemKey, *sectionKeysOrder) { QString value = sectionKeyValuePairs->value(itemKey); itemKey = itemKey.trimmed(); if(itemKey!=QString::null && itemKey!=""){ if(sectionKeyComments->contains(itemKey)) ConfigContents.append(sectionKeyComments->value(itemKey)); ConfigContents.append(itemKey+"="+value+"\n\r"); } } } }
true
c48c50d65bacb5eac5eb088fa04e82ddf1a3ec0d
C++
CoreRobotics/CoreRobotics
/src/physics/FrameDh.cpp
UTF-8
6,603
2.75
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2017-2019, CoreRobotics. All rights reserved. * Licensed under BSD-3, https://opensource.org/licenses/BSD-3-Clause * http://www.corerobotics.org */ #include "FrameDh.hpp" #include "Eigen/Dense" namespace cr { namespace physics { //------------------------------------------------------------------------------ /*! The constructor sets the rotation and translation parameters upon construction, with defaults listed in parenthesis.\n \param[in] i_r - x position of the frame (0) \param[in] i_alpha - y position of the frame (0) \param[in] i_d - z position of the frame (0) \param[in] i_theta - alpha angle of the frame [rad] (0) \param[in] i_mode - DH convention (CR_DH_MODE_MODIFIED) \param[in] i_free - free variable (CR_DH_FREE_NONE) */ //------------------------------------------------------------------------------ FrameDh::FrameDh(double i_r, double i_alpha, double i_d, double i_theta, DhMode i_mode, DhFreeVariable i_free) { m_dhR = i_r; m_dhAlpha = i_alpha; m_dhD = i_d; m_dhTheta = i_theta; m_dhMode = i_mode; m_freeVar = i_free; this->setRotationAndTranslation(); } FrameDh::FrameDh() { m_dhR = 0.0; m_dhAlpha = 0.0; m_dhD = 0.0; m_dhTheta = 0.0; m_dhMode = CR_DH_MODE_MODIFIED; m_freeVar = CR_DH_FREE_NONE; this->setRotationAndTranslation(); } //------------------------------------------------------------------------------ /*! This method sets the value of the free variable. The method returns a true if the value was written and a false if m_freeVar is set to CR_DH_FREE_NONE.\n \param[in] i_q - value of the variable to be set \return - Result flag indicating if the parameter is writable */ //------------------------------------------------------------------------------ core::Result FrameDh::setFreeValue(double i_q) { core::Result result = core::CR_RESULT_SUCCESS; switch (m_freeVar) { case CR_DH_FREE_NONE: result = core::CR_RESULT_UNWRITABLE; break; case CR_DH_FREE_R: m_dhR = i_q; break; case CR_DH_FREE_ALPHA: m_dhAlpha = i_q; break; case CR_DH_FREE_D: m_dhD = i_q; break; case CR_DH_FREE_THETA: m_dhTheta = i_q; break; } this->setRotationAndTranslation(); return result; } //------------------------------------------------------------------------------ /*! This method get the value of the free variable. The method returns q = 0 if m_freeVar is set to CR_DH_FREE_NONE.\n \return - value of the free variable. */ //------------------------------------------------------------------------------ double FrameDh::getFreeValue() { double value = 0.0; switch (m_freeVar) { case CR_DH_FREE_NONE: break; case CR_DH_FREE_R: value = m_dhR; break; case CR_DH_FREE_ALPHA: value = m_dhAlpha; break; case CR_DH_FREE_D: value = m_dhD; break; case CR_DH_FREE_THETA: value = m_dhTheta; break; } return value; } //------------------------------------------------------------------------------ /*! This method sets the the DH convention.\n \param[in] i_mode - DH convention */ //------------------------------------------------------------------------------ void FrameDh::setMode(DhMode i_mode) { m_dhMode = i_mode; this->setRotationAndTranslation(); } //------------------------------------------------------------------------------ /*! This method gets the DH convention.\n \return - DH convention. */ //------------------------------------------------------------------------------ DhMode FrameDh::getMode(void) { return m_dhMode; } //------------------------------------------------------------------------------ /*! This method sets the DH parameter values.\n \param[in] i_r - the r value in the DH parameter transformation \param[in] i_alpha - the alpha value in the DH parameter transformation \param[in] i_d - the d value in the DH parameter transformation \param[in] i_theta - the theta value in the DH parameter transformation */ //------------------------------------------------------------------------------ void FrameDh::setParameters(double i_r, double i_alpha, double i_d, double i_theta) { m_dhR = i_r; m_dhAlpha = i_alpha; m_dhD = i_d; m_dhTheta = i_theta; this->setRotationAndTranslation(); } //------------------------------------------------------------------------------ /*! This method gets the DH parameter values.\n \param[out] o_r - the r value in the DH parameter transformation \param[out] o_alpha - the alpha value in the DH parameter transformation \param[out] o_d - the d value in the DH parameter transformation \param[out] o_theta - the theta value in the DH parameter transformation */ //------------------------------------------------------------------------------ void FrameDh::getParameters(double &o_r, double &o_alpha, double &o_d, double &o_theta) { o_r = m_dhR; o_alpha = m_dhAlpha; o_d = m_dhD; o_theta = m_dhTheta; } //------------------------------------------------------------------------------ /*! This method returns a true if the frame is driven (i.e. has a free variable) or a false if the frame is not driven.\n \return - true = is driven, false = is not driven */ //------------------------------------------------------------------------------ bool FrameDh::isDriven(void) { if (m_freeVar == CR_DH_FREE_NONE) { return false; } else { return true; } } //------------------------------------------------------------------------------ // Private Methods: //! sets the private rotation and translation members - Note that // anytime a parameter gets set in the frame class, this method gets // called to update the rotation/translation members. void FrameDh::setRotationAndTranslation() { switch (m_dhMode) { case CR_DH_MODE_CLASSIC: m_rotation << cos(m_dhTheta), -sin(m_dhTheta) * cos(m_dhAlpha), sin(m_dhTheta) * sin(m_dhAlpha), sin(m_dhTheta), cos(m_dhTheta) * cos(m_dhAlpha), -cos(m_dhTheta) * sin(m_dhAlpha), 0, sin(m_dhAlpha), cos(m_dhAlpha); m_translation << m_dhR * cos(m_dhTheta), m_dhR * sin(m_dhTheta), m_dhD; break; case CR_DH_MODE_MODIFIED: m_rotation << cos(m_dhTheta), -sin(m_dhTheta), 0, sin(m_dhTheta) * cos(m_dhAlpha), cos(m_dhTheta) * cos(m_dhAlpha), -sin(m_dhAlpha), sin(m_dhTheta) * sin(m_dhAlpha), cos(m_dhTheta) * sin(m_dhAlpha), cos(m_dhAlpha); m_translation << m_dhR, -m_dhD * sin(m_dhAlpha), m_dhD * cos(m_dhAlpha); break; } } } // namespace physics } // namespace cr
true
3fdac54179e5ae50d43964e9701219fac6661fc2
C++
CharleyLiu/Leetcode
/Sort Colors/Sort Colors.cpp
UTF-8
573
2.671875
3
[]
no_license
class Solution { public: void sortColors(vector<int>& nums) { int len=nums.size(); int r=0; int white=0; int blue=0; for(int i=0;i<len;++i) { if(nums[i]==0) { nums[blue++]=2; nums[white++]=1; nums[r++]=0; } else if(nums[i]==1) { nums[blue++]=2; nums[white++]=1; } else { nums[blue++]=2; } } } };
true
0a61bbcc0208ecb628ec700ff2bf2bf6ccb59847
C++
arpit353/competitive-coding
/codechef/Rectangle.cpp
UTF-8
453
2.78125
3
[]
no_license
#include<iostream> using namespace std; int main() { int n,a,b,c,d; cin>>n; for(int i=0;i<n;i++) { cin>>a>>b>>c>>d; if(a==b && c==d) { cout<<"YES\n"; } else if(a==c && d==b) { cout<<"YES\n"; } else if(a==d && c==b) { cout<<"YES\n"; } else { cout<<"NO\n"; } } return 0; }
true
fa6fe011371a6f1a0ca7369caa10dc3a612c0ad8
C++
Ecquus/imageEditor
/imageEditorApp/src/model/interpolator.cpp
UTF-8
2,007
3.046875
3
[ "MIT" ]
permissive
#include "interpolator.h" #include <util.h> using namespace util::types; Cell::Cell(const QPointF& p, const QImage& img, QRgb extrapColor) { // fill data with the colors of the pixels around point p in the image corners[0][0] = getColor(QPoint{ util::floor(p.x()), util::floor(p.y()) }, img, extrapColor); // leftTop corners[0][1] = getColor(QPoint{ util::ceil(p.x()) , util::floor(p.y()) }, img, extrapColor); // rightTop corners[1][0] = getColor(QPoint{ util::floor(p.x()), util::ceil(p.y()) }, img, extrapColor); // leftBottom corners[1][1] = getColor(QPoint{ util::ceil(p.x()) , util::ceil(p.y()) }, img, extrapColor); // rightBotom // normalize x and y to a range [0, 1) const auto px = toFloat(p.x()), py = toFloat(p.y()); x = px - floorf(px); y = py - floorf(py); } // linear interpolation of f(q) from f(a) and f(b) auto Interpolator::linear(QRgb fa, QRgb fb, float q) -> QRgb { const auto ar = toFloat(qRed(fa)), ag = toFloat(qGreen(fa)), ab = toFloat(qBlue(fa)); const auto br = toFloat(qRed(fb)), bg = toFloat(qGreen(fb)), bb = toFloat(qBlue(fb)); assert(ar <= 255 && ag <= 255 && ab <= 255); assert(br <= 255 && bg <= 255 && bb <= 255); const auto r = util::clamp(util::round(ar * (1.0f - q) + br * q)); const auto g = util::clamp(util::round(ag * (1.0f - q) + bg * q)); const auto b = util::clamp(util::round(ab * (1.0f - q) + bb * q)); return qRgba(r, g, b, 0xff); } auto Interpolator::nearest(const Cell& cell) -> QRgb { const auto i = util::round(cell.x); const auto j = util::round(cell.y); return cell.corners[j][i]; } auto Interpolator::bilinear(const Cell& cell) -> QRgb { // linear interpolation along the x axis const auto fx1 = linear(cell.corners[0][0], cell.corners[0][1], cell.x); const auto fx2 = linear(cell.corners[1][0], cell.corners[1][1], cell.x); // linear interpolation along the y axis const auto fxy = linear(fx1, fx2, cell.y); return fxy; }
true
aae82513fddd2c694be026a04be2656aacc37032
C++
mchughj/iBoardBot
/code/deviceFirmware/iBoardBot/Servos.ino
UTF-8
3,137
2.5625
3
[]
no_license
// iBoardbot project // Init servo on T4 timer. Output OC4B (Leonardo Pin10) servo1, OC4D (Leonardo Pin6) servo2, optional I2C output for servo2 // Servo2 compatible with OC4A (Leonardo Pin13) // We configure the Timer4 for 11 bits PWM (enhacend precision) and 16.3ms period (OK for most servos) // Resolution: 8us per step (this is OK for servos, around 175 steps for typical servo) void initServo() { int temp; // Initialize Timer4 as Fast PWM TCCR4A = (1<<PWM4A)|(1<<PWM4B); TCCR4B = 0; TCCR4C = (1<<PWM4D); TCCR4D = 0; TCCR4E = (1<<ENHC4); // Enhaced -> 11 bits // Reset servos to neutral position temp = 1500 >> 3; TC4H = temp >> 8; OCR4A = temp & 0xff; TC4H = temp >> 8; OCR4B = temp & 0xff; // Reset timer TC4H = 0; TCNT4 = 0; // Set TOP to 1023 (10 bit timer) TC4H = 3; OCR4C = 0xFF; // OC4A = PC7 (Pin13) OC4B = PB6 (Pin10) OC4D = PD7 (Pin6) // Set pins as outputs //DDRB |= (1 << 6); // OC4B = PB6 (Pin10 on Leonardo board) //DDRC |= (1 << 7); // OC4A = PC7 (Pin13 on Leonardo board) //DDRD |= (1 << 7); // OC4D = PD7 (Pin6 on Leonardo board) //Enable OC4B output. OC4B is set when TCNT4=0 and clear when counter reach OCR4B //Enable servo2 on OC4A y OC4D TCCR4A |= (1 << COM4B1); TCCR4A |= (1 << COM4A1); TCCR4C |= (1 << COM4D1); // set prescaler to 256 and enable timer 16Mhz/256/1024 = 61Hz (16.3ms) TCCR4B = (1 << CS43) | (1 << CS40); // Enable Timer4 overflow interrupt and OCR4 interrupt TIMSK4 = (1 << TOIE4) | (1 << OCIE4A); servo1_ready=true; servo2_ready=true; } ISR(TIMER4_OVF_vect) { SET(PORTD,1); // I2C servo2 output } ISR(TIMER4_COMPA_vect) { CLR(PORTD,1); } void disableServo1() { Serial.println(F(" Disabling servo 1")); while (TCNT4<0xFF); // Wait for sync... CLR(TCCR4A,COM4B1); servo1_ready=false; } void disableServo2() { Serial.println(F(" Disabling servo 2")); while (TCNT4<0xFF); // Wait for sync... TIMSK4 = 0; CLR(TCCR4A,COM4A1); CLR(TCCR4C,COM4D1); servo2_ready=false; } void enableServo1() { Serial.println(F(" Enabling servo 1")); while (TCNT4<0xFF); // Wait for sync... SET(TCCR4A,COM4B1); servo1_ready=true; } void enableServo2() { Serial.println(F(" Enabling servo 2")); while (TCNT4<0xFF); // Wait for sync... TIMSK4 = (1 << TOIE4) | (1 << OCIE4A); SET(TCCR4A,COM4A1); SET(TCCR4C,COM4D1); servo2_ready=true; } // move servo1 on OC4B (pin10) void moveServo1(int pwm) { Serial.print(F(" Moving servo 1: ")); Serial.println(pwm); pwm = constrain(pwm, SERVO_MIN_PULSEWIDTH, SERVO_MAX_PULSEWIDTH) >> 3; // Check max values and Resolution: 8us // 11 bits => 3 MSB bits on TC4H, LSB bits on OCR4B TC4H = pwm >> 8; OCR4B = pwm & 0xFF; } // move servo2 on OC4A (pin13) void moveServo2(int pwm) { Serial.print(F(" Moving servo 2: ")); Serial.println(pwm); pwm = constrain(pwm, SERVO_MIN_PULSEWIDTH, SERVO_MAX_PULSEWIDTH) >> 3; // Check max values and Resolution: 8us // 11 bits => 3 MSB bits on TC4H, LSB bits on OCR4A TC4H = pwm >> 8; OCR4A = pwm & 0xFF; OCR4D = pwm & 0xFF; // New 2.1 boards servo2 output }
true
d6e57ef918797f1bd9ac87a47b5e80fc56102be4
C++
MarkChen16/QtDemo
/CustomObject/QPerson.cpp
UTF-8
601
2.84375
3
[]
no_license
#include "QPerson.h" QPerson::QPerson(QString szName, int intAge, int intScore, QObject *parent) : QObject(parent) { m_name = szName; m_age = intAge; m_score = intScore; } QPerson::~QPerson() { } QString QPerson::name() { return m_name; } int QPerson::age() { return m_age; } void QPerson::setAge(int value) { m_age = value; emit ageChanged(value); //发射信号 } void QPerson::incAge() { m_age++; emit ageChanged(m_age); //发射信号 } int QPerson::score() { return m_score; } void QPerson::setScore(int value) { m_score = value; emit scoreChanged(value); //发射信号 }
true
ddbc86566c7ab5cbbfe393ac451b1c6801799437
C++
leonardo98/run_core
/Core/LinkToComplex.h
UTF-8
868
2.59375
3
[]
no_license
#ifndef LINK_TO_COMPLEX_H #define LINK_TO_COMPLEX_H #include "LevelSet.h" #include "BeautyBase.h" class LinkToComplex : public BeautyBase { private: //Matrix _drawMatrix; std::string _id; LevelSet *_complex; float _shiftX; float _shiftY; public: float GetShiftX() const { return _shiftX; } float GetShiftY() const { return _shiftY; } virtual ~LinkToComplex(); LinkToComplex(const std::string &id); LinkToComplex(const LinkToComplex &b); LinkToComplex(rapidxml::xml_node<> *xe); virtual void GetBeautyList(BeautyList &list) const; virtual bool Command(const std::string &cmd) { return _complex->Command(cmd); } virtual void Draw(); virtual std::string Type() const; const std::string &Name() const { return _id; } const LevelSet *GetComplex() { return _complex; } virtual void ReloadTextures(bool touch = false); }; #endif//LINK_TO_COMPLEX_H
true
121158d21d0c256e582e576a3b73b8d9b9efbe84
C++
DaCrRa/Klondike-cpp
/src/model/inc/MoveOrigin.h
UTF-8
619
2.546875
3
[]
no_license
/* * MoveOrigin.h * * Created on: 4 de may. de 2016 * Author: dancre */ #ifndef SRC_MODEL_INC_MOVEORIGIN_H_ #define SRC_MODEL_INC_MOVEORIGIN_H_ #include <Pile.h> #include <GameElement.h> #include <MoveOriginVisitor.h> class MoveOrigin : virtual public GameElement { public: virtual void recoverCard(const Card* c) = 0; virtual int getNumCardsAvailableToMove() const = 0; virtual const Pile showAvailableCards(int n) const = 0; virtual Pile removeCards(int n) = 0; virtual void accept(MoveOriginVisitor* v) = 0; virtual ~MoveOrigin() {} }; #endif /* SRC_MODEL_INC_MOVEORIGIN_H_ */
true
7306c15507d60ba6980d4593503af23151508eb5
C++
wcole3/SDL_LazyFoo
/SDL_Joystick/SDL_joystick/SDL_joystick/main.cpp
UTF-8
6,569
3.046875
3
[]
no_license
// // main.cpp // SDL_joystick // Toy program to use joysticks to control program // Created by William Cole on 11/23/18. // Copyright © 2018 William Cole. All rights reserved. // #include <iostream> #include <SDL2/SDL.h> #include <SDL2_image/SDL_image.h> #include <stdio.h> #include "lTexture.h" //screen globals int screenWidth=640; int screenHeight=480; //sdl globals SDL_Window* gWindow=NULL; SDL_Renderer* gRenderer=NULL; lTexture arrowTexture; SDL_Joystick* gGameController=NULL; SDL_Haptic* gHaptic=NULL; //controller dead space const int controllerDeadZone=8000; //forward declarations bool init(); bool loadMedia(); bool loadController(); void close(); bool init(){ bool successFlag=true; //need to start the event system and the joystick system and the haptic system if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC)<0){ printf("Could not initialize SDL! SDL error: %s\n", SDL_GetError()); successFlag=false; }else{ //create window and renderer gWindow=SDL_CreateWindow("Spin the arrow with the joystick", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_SHOWN); if(gWindow==NULL){ printf("Could not create window! SDL error: %s\n", SDL_GetError()); successFlag=false; }else{ gRenderer=SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(gRenderer==NULL){ printf("Could not create renderer! SDL error: %s\n", SDL_GetError()); successFlag=false; }else{ SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255); arrowTexture=lTexture(gRenderer); } } } //now load IMG if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)){ printf("Could not intialize IMG! IMG error: %s\n", IMG_GetError()); successFlag=false; } return successFlag; } bool loadMedia(){ bool successFlag=true; if(!arrowTexture.loadFromFile("arrow.png", SDL_FALSE)){ printf("Could not load media!"); successFlag=false; } return successFlag; } //new file to load controller object bool loadController(){ bool successFlag=true; //check to see if any joysticks are connected if(SDL_NumJoysticks()==0){ printf("There are no Joysticks connected!"); successFlag=false; } //if there are any connected open the first one gGameController=SDL_JoystickOpen(0); if(gGameController==NULL){ printf("Ccould not open joystick! SDL error: %s\n",SDL_GetError()); successFlag=false; } gHaptic=SDL_HapticOpenFromJoystick(gGameController); if(gHaptic==NULL){ printf("Could not open haptic! SDL error: %s\n",SDL_GetError()); }else{ //initialize haptic if(SDL_HapticRumbleInit(gHaptic)<0){ printf("Could not initialize haptic rumble! SDl error: %s\n", SDL_GetError()); } } return successFlag; } void close(){ arrowTexture.free(); SDL_JoystickClose(gGameController); gGameController=NULL; SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); gRenderer=NULL; gWindow=NULL; SDL_Quit(); IMG_Quit(); } int main(int argc, const char * argv[]) { // lets get down to business if(!init()){ printf("Could not initialize!"); }else{ if(!loadMedia()){ printf("Could not load media!"); }else{ if(!loadController()){ printf("Could not load controller!"); }else{ bool quit=false; SDL_Event e; //need some ints to hold the joystick direction int xDir=0; int yDir=0; while(!quit){ while(SDL_PollEvent(&e)!=0){ //check if user want to quit if(e.type==SDL_QUIT){ quit=true; } else if(e.type==SDL_JOYAXISMOTION){ //check if the motion was from controller 1 if(e.jaxis.which==0){ //cehck to see whether the x and y axis values are out of the dead zone //the xaxis is typically 0 if(e.jaxis.axis==0){ if(e.jaxis.value > controllerDeadZone){ xDir=1; } else if(e.jaxis.value < -controllerDeadZone){ xDir=-1; }else{ xDir=0; } } //same for the y axis if(e.jaxis.axis==1){ if(e.jaxis.value > controllerDeadZone){ yDir=1; }else if( e.jaxis.value < -controllerDeadZone){ yDir=-1; }else{ yDir=0; } } } } else if(e.type==SDL_JOYBUTTONDOWN){ //if a button is pressed we want to rumble if(SDL_HapticRumblePlay(gHaptic, 0.75, 100)){ printf("Could not rumble! SDL error: %s\n", SDL_GetError()); } } } //here is where we render SDL_SetRenderDrawColor(gRenderer, 255, 255, 255, 255); SDL_RenderClear(gRenderer); //render the arrow texture with a rotation defined by the joystick //reme,ber to convert to degrees double angle=(atan2(double(yDir), double(xDir)) * (180/M_PI)); arrowTexture.render((screenWidth-arrowTexture.getWidth())/2, (screenHeight-arrowTexture.getHeight())/2,NULL,angle); SDL_RenderPresent(gRenderer); } } } } close(); return 0; }
true
ae9a4922ea8bd009ae98ca2c69ae2f3a34a4dbd9
C++
KEDIARAHUL135/WatermarkImages
/main.cpp
UTF-8
4,199
3.140625
3
[]
no_license
#include "opencv2/opencv.hpp" #include <iostream> #include <filesystem> namespace fs = std::filesystem; // ISO C++17 Standard (/std:c++17) int ReadImage(std::string InputImagePath, std::vector<cv::Mat>& Images, std::vector<std::string>& ImageNames) { // Checking if path is of file or folder. if (fs::is_regular_file(fs::status(InputImagePath))) // If path is of file. { cv::Mat InputImage = cv::imread(InputImagePath); // Reading the image. // Checking if image is read. if (InputImage.empty()) { std::cout << "Image not read. Provide a correct path" << std::endl; exit(1); } Images.push_back(InputImage); // Storing the image. ImageNames.push_back(InputImagePath); // Storing the image's name. } // If path is of a folder contaning images. else if (fs::is_directory(fs::status(InputImagePath))) { // Getting all image's path present inside the folder. for (const auto& entry : fs::directory_iterator(InputImagePath)) { // Reading images one by one. cv::Mat InputImage = cv::imread(entry.path().u8string()); Images.push_back(InputImage); // Storing the image. ImageNames.push_back(entry.path().filename().u8string()); // Storing the image's name. } } // If it is neither file nor folder(Invalid Path). else { std::cout << "\nEnter valid Image Path." << std::endl; exit(2); } return 0; } cv::Mat WatermarkImage(cv::Mat Image, cv::Mat Watermark) { // Resizing watermark image keeping the aspect ratio // Resize is done such that watermark's height is equal to 10% of the image's height int NewHeight = int(Image.rows * 0.1); int NewWidth = int(NewHeight * (double(Watermark.cols) / double(Watermark.rows))); cv::resize(Watermark, Watermark, cv::Size(NewWidth, NewHeight), (0.0), (0.0), cv::INTER_AREA); // Creating 3 channeled watermark image and alpha image(range ->[0.0 - 1.0]) std::vector<cv::Mat> channels; channels.push_back(Watermark); channels.push_back(Watermark); channels.push_back(Watermark); cv::merge(channels, Watermark); // Transparency of the watermark is 60 % (0.4 is opacity) cv::Mat Alpha; Watermark.convertTo(Alpha, CV_32FC3, 0.4 / 255.0); // Applying watermark on the bottom right corner leaving 20 pixels from both the boundaries cv::Mat WatermarkedImage = Image.clone(); int ah = Alpha.rows, aw = Alpha.cols; // Creating full image of watermark with logo at the bottom right corner cv::Mat Watermark_Full = cv::Mat::zeros(cv::Size(Image.cols, Image.rows), CV_8UC3); Watermark.copyTo(Watermark_Full(cv::Rect(Image.cols - 20 - Watermark.cols, Image.rows - 20 - Watermark.rows, Watermark.cols, Watermark.rows))); // Creating full image of alpha with alpha values of the logo at the bottom right corner cv::Mat Alpha_Full = cv::Mat::zeros(cv::Size(Image.cols, Image.rows), CV_32FC3); Alpha.copyTo(Alpha_Full(cv::Rect(Image.cols - 20 - Watermark.cols, Image.rows - 20 - Watermark.rows, Watermark.cols, Watermark.rows))); Watermark_Full.convertTo(Watermark_Full, CV_64FC3); Alpha_Full.convertTo(Alpha_Full, CV_64FC3); Image.convertTo(Image, CV_64FC3); // Creating image of values (1.0 - Alpha_Full) cv::Mat Complement_Alpha_Full(Alpha_Full.rows, Alpha_Full.cols, CV_64FC3, cv::Scalar(1.0, 1.0, 1.0)); cv::subtract(Complement_Alpha_Full, Alpha_Full, Complement_Alpha_Full); cv::Mat Mul1, Mul2; cv::multiply(Alpha_Full, Watermark_Full, Mul1); cv::multiply(Complement_Alpha_Full, Image, Mul2); cv::add(Mul1, Mul2, WatermarkedImage); WatermarkedImage.convertTo(WatermarkedImage, CV_8UC3); return WatermarkedImage; } int main() { // Reading images std::vector<cv::Mat> Images; // Input Images will be stored in this list. std::vector<std::string> ImageNames; // Names of input images will be stored in this list. ReadImage("InputImages", Images, ImageNames); cv::Mat Watermark = cv::imread("kid_logo.jpg", cv::IMREAD_GRAYSCALE); for (int i = 0; i < Images.size(); i++) { cv::Mat Image = Images[i].clone(); // Passing Image for watermarking cv::Mat WatermarkedImage = WatermarkImage(Image, Watermark); // Storing the final output images cv::imwrite("OutputImages_cpp/" + ImageNames[i], WatermarkedImage); } return 0; }
true
2e231be63d8236091752c67924e2326294671810
C++
eglrp/StitchingToPanorama
/TinyGiga/ColorCorrect.cpp
UTF-8
5,023
3.265625
3
[]
no_license
/** @brief mesh pyramid class @author Shane Yuna @date Mar 3, 2018 */ #include "ColorCorrect.h" ColorCorrect::ColorCorrect() {} ColorCorrect::~ColorCorrect() {} /** @brief static function to calculate image color mean, covariance matrix @param cv::Mat input: input image @param cv::Mat & outmean: output color mean vector @param cv::Mat & outcov: output color covariance matrix @param cv::Mat mask = cv::Mat(): input mask for image @return int */ int ColorCorrect::calcMeanCov(cv::Mat input, cv::Mat & outmean, cv::Mat & outcov, cv::Mat mask) { // check mask size_t pixelnum = 0; if (mask.empty()) { mask = cv::Mat::ones(input.size(), CV_8U); pixelnum = input.size().area(); } else { pixelnum = cv::countNonZero(mask); } // reshape image to vector cv::Mat imgvec(pixelnum, 3, CV_32F); size_t ind = 0; outmean = cv::Mat::zeros(3, 1, CV_32F); outcov = cv::Mat::zeros(3, 3, CV_32F); for (size_t i = 0; i < input.rows; i++) { for (size_t j = 0; j < input.cols; j++) { if (mask.at<uchar>(i, j) != 0) { cv::Vec3b val = input.at<cv::Vec3b>(i, j); float b = static_cast<float>(val.val[0]); float g = static_cast<float>(val.val[1]); float r = static_cast<float>(val.val[2]); imgvec.at<float>(ind, 0) = b; imgvec.at<float>(ind, 1) = g; imgvec.at<float>(ind, 2) = r; outmean.at<float>(0, 0) += b; outmean.at<float>(1, 0) += g; outmean.at<float>(2, 0) += r; ind++; } } } outmean.at<float>(0, 0) /= pixelnum; outmean.at<float>(1, 0) /= pixelnum; outmean.at<float>(2, 0) /= pixelnum; // calculate outcov for (size_t i = 0; i < pixelnum; i++) { imgvec.at<float>(i, 0) -= outmean.at<float>(0, 0); imgvec.at<float>(i, 1) -= outmean.at<float>(1, 0); imgvec.at<float>(i, 2) -= outmean.at<float>(2, 0); } outcov = imgvec.t() * imgvec / pixelnum; return 0; } /** @brief function to make eigen values positive @param cv::Mat & eigvalue: input/output eigen value matrix (3x3) @return int */ int ColorCorrect::makeEigvaluesPositive(cv::Mat & eigvalues) { for (size_t i = 0; i < 3; i++) { if (eigvalues.at<float>(i, 0) < POSITIVE) { eigvalues.at<float>(i, 0) = POSITIVE; } } return 0; } /** @brief static function for color correction @param cv::Mat src: input source image @param cv::Mat dst: input destination image @param cv::Mat & out: output color corrected image @return int */ int ColorCorrect::correct(cv::Mat src, cv::Mat dst, cv::Mat & out) { // calculate mean and covariance matrix cv::Mat srcmean, srccov, dstmean, dstcov; ColorCorrect::calcMeanCov(src, srcmean, srccov); ColorCorrect::calcMeanCov(dst, dstmean, dstcov); // apply eigen decomposition first time cv::Mat srcEigVal, srcEigVec; cv::eigen(srccov, srcEigVal, srcEigVec); ColorCorrect::makeEigvaluesPositive(srcEigVal); // compute C matrix cv::Mat srcEigValSqrt = cv::Mat::zeros(3, 3, CV_32F); srcEigValSqrt.at<float>(0, 0) = std::sqrt(srcEigVal.at<float>(0, 0)); srcEigValSqrt.at<float>(1, 1) = std::sqrt(srcEigVal.at<float>(1, 0)); srcEigValSqrt.at<float>(2, 2) = std::sqrt(srcEigVal.at<float>(2, 0)); cv::Mat C = srcEigValSqrt * srcEigVec * dstcov * srcEigVec.t() * srcEigValSqrt; // apply eigen decomposition second time cv::Mat eigValC, eigVecC; cv::eigen(C, eigValC, eigVecC); ColorCorrect::makeEigvaluesPositive(eigValC); // compute tranform matrix cv::Mat eigValSqrtC = cv::Mat::zeros(3, 3, CV_32F); eigValSqrtC.at<float>(0, 0) = std::sqrt(eigValC.at<float>(0, 0)); eigValSqrtC.at<float>(1, 1) = std::sqrt(eigValC.at<float>(1, 0)); eigValSqrtC.at<float>(2, 2) = std::sqrt(eigValC.at<float>(2, 0)); cv::Mat srcEigValSqrtInv = cv::Mat::zeros(3, 3, CV_32F); srcEigValSqrtInv.at<float>(0, 0) = 1 / srcEigValSqrt.at<float>(0, 0); srcEigValSqrtInv.at<float>(1, 1) = 1 / srcEigValSqrt.at<float>(1, 1); srcEigValSqrtInv.at<float>(2, 2) = 1 / srcEigValSqrt.at<float>(2, 2); cv::Mat A = srcEigVec.t() * srcEigValSqrtInv * eigVecC.t() * eigValSqrtC * eigVecC * srcEigValSqrtInv * srcEigVec; cv::Mat bias = - A * srcmean + dstmean; // apply color correction cv::Mat pixelVec(3, src.size().area(), CV_32F); int ind = 0; for (size_t i = 0; i < src.rows; i++) { for (size_t j = 0; j < src.cols; j++) { cv::Vec3b val = src.at<cv::Vec3b>(i, j); pixelVec.at<float>(0, ind) = static_cast<float>(val.val[0]); pixelVec.at<float>(1, ind) = static_cast<float>(val.val[1]); pixelVec.at<float>(2, ind) = static_cast<float>(val.val[2]); ind++; } } ind = 0; pixelVec = A * pixelVec; for (size_t i = 0; i < src.rows; i++) { for (size_t j = 0; j < src.cols; j++) { cv::Rect rect(ind, 0, 1, 3); pixelVec(rect) += bias; cv::Vec3b val; val.val[0] = static_cast<uchar>(std::min<float>(std::max<float> (pixelVec.at<float>(0, ind), 0), 255)); val.val[1] = static_cast<uchar>(std::min<float>(std::max<float> (pixelVec.at<float>(1, ind), 0), 255)); val.val[2] = static_cast<uchar>(std::min<float>(std::max<float> (pixelVec.at<float>(2, ind), 0), 255)); out.at<cv::Vec3b>(i, j) = val; ind++; } } return 0; }
true
e0a7503a3d44726948292af9b4f5d7c637031364
C++
ImTangYun/comprehensive
/C++/leetcode/LRU_Cache/solution.cpp
UTF-8
2,359
3.4375
3
[]
no_license
struct ListNode_ { int val; int key; ListNode_* pre; ListNode_* next; ListNode_(int k, int v):key(k),val(v),pre(NULL),next(NULL){} }; class LRUCache{ private: int capacity_; int size_; unordered_map<int, ListNode_*> k_v; ListNode_* head_; ListNode_* tail_; public: LRUCache(int capacity) { capacity_ = capacity; size_ = 0; head_ = NULL; tail_ = NULL; } int get(int key) { unordered_map<int, ListNode_*>::iterator iter = k_v.find(key); if (iter != k_v.end()) { int value = iter->second->val; MoveToHead(iter->second); return value; } else return -1; } void set(int key, int value) { unordered_map<int, ListNode_*>::iterator iter = k_v.find(key); if (iter != k_v.end()) { iter->second->val = value; MoveToHead(iter->second); } else { ++size_; if (head_ == NULL) { head_ = new ListNode_(key,value); tail_ = head_; k_v[key] = head_; } else { ListNode_* p = new ListNode_(key,value); k_v[key] = p; InsertFromHead(p); } if (size_ > capacity_) { if (size_ == 0) { delete head_; head_ = NULL; tail_ = NULL; } else { k_v.erase(k_v.find(tail_->key)); tail_ = tail_->pre; delete tail_->next; tail_->next = NULL; } --size_; } } } void InsertFromHead(ListNode_* p) { p->next = head_; head_->pre = p; head_ = p; } void MoveToHead(ListNode_* p) { if (p == head_) return; if (p == tail_) { tail_ = p->pre; p->pre = NULL; ListNode_* tmp = head_; head_ = p; p->next = tmp; tmp->pre = p; tail_->next = NULL; return; } p->next->pre = p->pre; p->pre->next = p->next; ListNode_* tmp = head_; head_ = p; p->next = tmp; tmp->pre = p; head_->pre = NULL; } };
true
7802fb699efebc8a4d66bdae9e9a9fdcad16db47
C++
avikodak/Algorithms
/src/sites/geeksforgeeks/linkedlist/page04/CheckPalindromeSinglyLL.h
UTF-8
3,116
2.546875
3
[]
no_license
/***************************************************************************************************************** * File Name : CheckPalindromeSinglyLL.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\linkedlist\page04\CheckPalindromeSinglyLL.h * Created on : Dec 18, 2013 :: 1:18:39 AM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef CHECKPALINDROMESINGLYLL_H_ #define CHECKPALINDROMESINGLYLL_H_ bool checkPalindromeSinglyLLRecursive(llNode *ptr,llNode **ptrRef){ if(ptr == NULL){ return true; } if(!checkPalindromeSinglyLLRecursive(ptr->next,ptrRef)){ return false; } if((*ptrRef)->value != ptr->value){ return false; }else{ (*ptrRef) = (*ptrRef)->next; return true; } } bool checkPalindromeSingleLLReverse(llNode *ptr){ if(ptr == NULL){ return true; } llNode *revHead; // Reverse ll in new ll while(revHead != NULL && ptr != NULL){ if(revHead->value != ptr->value){ return false; } } return true; } bool checkPalindromeDLL(dllNode *ptr){ if(ptr == NULL){ return true; } dllNode *tailNode = ptr; while(tailNode->next != NULL){ tailNode = tailNode->next; } while(ptr != tailNode && ptr != NULL && tailNode != NULL){ if(ptr->value != tailNode->value){ return false; } } return true; } bool checkPalindromeSinglyLL(llNode *ptr){ if(ptr == NULL){ return true; } stack<llNode *> auxSpace; llNode *currentNode = ptr; while(currentNode != NULL){ auxSpace.push(currentNode); currentNode = currentNode->next; } currentNode = ptr; while(!auxSpace.empty() && currentNode != NULL){ if(auxSpace.top()->value != currentNode->value){ return false; } auxSpace.pop(); currentNode = currentNode->next; } return true; } #endif /* CHECKPALINDROMESINGLYLL_H_ */ /************************************************* End code *******************************************************/
true
691f58c5fc1ada6f39d98c744daf091885020920
C++
gn0mesort/RothmanAlexander_CSC5_41202
/Class/MarkSort/main.cpp
UTF-8
3,785
4.03125
4
[]
no_license
/* * File: main.cpp * Author: Alexander Rothman * Purpose: To develop a sorting routine called MarkSort * Created on February 2, 2016, 8:18 AM */ //System Libraries #include <cstdlib> #include <ctime> #include <iostream> using namespace std; //User Libraries //Global Constants //Function Prototypes void fillAry(int [], int); void prntAry(int [], int, int); void lstSmal(int [], int, int); void swap(int &, int &); void markSrt(int[], int); //Begin Execution int main(int argc, char** argv) { //Declaration and Initialization const int SIZE = 100; //Size of the array int arr[SIZE]; //The array to sort srand(static_cast<unsigned int>(time(0))); //Seed PRNG fillAry(arr, SIZE); //Fill array prntAry(arr, SIZE, 10); //Print array markSrt(arr, SIZE); //Test sort prntAry(arr, SIZE, 10); //Print sorted array //Exit return 0; } /******************************************************************************/ /*******************************Fill Array*************************************/ /******************************************************************************/ // Fill an array with random integer values for later sorting //Input // arr : the array to fill // length : the length of the array //Output // arr : the filled array void fillAry(int arr[], int length){ //loop and fill the array with random numbers for(int i = 0; i < length; ++i){ arr[i] = rand() % 90 + 10; } } /******************************************************************************/ /******************************Print Array*************************************/ /******************************************************************************/ // Print an array //Input // arr : the array to print // length : the length of the array void prntAry(int arr[], int length, int perLine){ //loop and output array cout << endl; for(int i = 0; i < length; ++i){ if(i % perLine == 0){ cout << endl; } cout << arr[i] << " "; } cout << endl; } /******************************************************************************/ /******************************Smallest in List********************************/ /******************************************************************************/ // Find the smallest value in a list to some position //Input // arr : the array to use // length : the length of the array // pos : the position to check against void lstSmal(int arr[] , int length, int pos){ //loop and compare for(int i = pos + 1; i < length; ++i){ if(arr[pos] > arr[i]){ swap(arr[pos], arr[i]); } } } /******************************************************************************/ /***********************************Swap***************************************/ /******************************************************************************/ // Swap to integer values //Input // val1 : the first value // val2 : the second value //Output // val1 : the second value swapped into the first value // val2 : the first value swapped into the second value void swap(int &val1, int &val2){ //swap one value with another val1 = val1 ^ val2; val2 = val1 ^ val2; val1 = val1 ^ val2; } /******************************************************************************/ /********************************Mark Sort*************************************/ /******************************************************************************/ // Sort an array using the MarkSort algorithm //Input // arr : the array to sort // length : the length of the array //Output // arr : the sorted array void markSrt(int arr[], int length){ for(int i = 0; i < length - 1; ++i){ lstSmal(arr, length, i); } }
true
320a27fa25164be05925e1fadd6f8e9fab01a9a0
C++
craigsapp/scorelib
/src-library/ScorePage_layer.cpp
UTF-8
3,903
2.71875
3
[]
no_license
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Tue Jul 8 12:03:53 PDT 2014 // Last Modified: Tue Jul 8 12:03:55 PDT 2014 // Filename: ScorePage_layer.cpp // URL: https://github.com/craigsapp/scorelib/blob/master/src-library/ScorePage_layer.cpp // Syntax: C++11 // // Description: This file contains ScorePage class functions related to // melodic layer analysis. // #include "ScorePage.h" #include <algorithm> #include <set> using namespace std; ////////////////////////////// // // ScorePage::analyzeLayers -- Calulate the durations of each // staff on the page. This function also assigns a durational // offset to each item on the staff as a side effect. // int ScorePage::analyzeLayers(void) { if (!analysis_info.durationIsValid()) { analyzeStaffDurations(); } analysis_info.setInvalid("layers"); vectorVSIp staffsequence; getHorizontallySortedStaffItems(staffsequence); unsigned int i; for (i=1; i<staffsequence.size(); i++) { if (staffsequence[i].size() == 0) { // nothing on staff continue; } private_analyzeStaffLayers(staffsequence[i]); } analysis_info.setValid("layers"); return 1; } ////////////////////////////// // // ScorePage::private_analyzeStaffLayers -- // // * notes beamed together are in the same layer // void ScorePage::private_analyzeStaffLayers(vectorSIp& items) { vectorVSIp notes; notes.reserve(100); notes.resize(1); int i; SCORE_FLOAT offset; SCORE_FLOAT current = 0.0; SCORE_FLOAT tolerance = 0.001; SCORE_FLOAT dur; ScoreItem* sip; for (i=0; i<(int)items.size(); i++) { if (!items[i]->hasDuration()) { continue; } sip = items[i]; dur = sip->getDuration(); if (dur <= 0.0) { // don't deal with grace notes at the moment... continue; } if (sip->isInvisible()) { // don't deal with invisible rests for now... continue; } if (sip->isSecondaryChordNote()) { // chord notes are all in the same layer. The // primary chord note will set the secondary notes // in the chord. continue; } offset = sip->getStaffOffsetDuration(); if (fabs(offset - current) < tolerance) { // append note to current array position notes.back().push_back(sip); } else{ // add new rhythm cell onto list notes.emplace_back(); notes.back().push_back(sip); current = offset; } } int maxlayers = 0; for (i=0; i<(int)notes.size(); i++) { if (notes[i].size() > (unsigned int)maxlayers) { maxlayers = notes[i].size(); } } int layer = 1; // assign the first layer. for (i=0; i<(int)notes.size(); i++) { if (notes[i].size() == 1) { setChordLayer(notes[i][0], layer); } else { chooseLayer(notes[i], layer); } } // assign secondary layers // loop from layer=2 to layer=maxlayers first searching for the // first non-assigned notes then tracking them across the staff // by duration. } ///////////////////////////// // // ScorePage::chooseLayer -- Determine the note which should be assigned // to the given layer. // void ScorePage::chooseLayer(vectorSIp& notes, int layer) { // do something here. } ///////////////////////////// // // ScorePage::setChordLayer -- Set the layer for a note, and any of the secondary // chord notes attached to the note. // void ScorePage::setChordLayer(ScoreItem* note, int layer) { int i; vectorSIp* chordnotes = chordNotes(note); if (chordnotes == NULL) { note->setParameterQuiet(ns_auto, np_layer, layer); return; } for (i=0; i<(int)chordnotes->size(); i++) { (*chordnotes)[i]->setParameterQuiet(ns_auto, np_layer, layer); } }
true
56f64221fdf6e691826e72f67d7de0f6acfae5e9
C++
yolandalillo/Asa-I
/ARDUINO/Cuadernillo 1/hito1.9.ino
UTF-8
499
3.203125
3
[]
no_license
//Este programa aumenta el valor almacenado en la valiable 'PWMpin' //desde 0 hasta 255 mediante un bucle for. int PWMpin=10; //LED conectado en el pin 10 en serie con una r=470ohm. void setup() { Serial.begin(9600); } void loop() { for(int i=0; i<=255; i++){ //Desde i igual a 0, hasta i igual o menor que 255, repetir //aumentando el bucle de 1 en 1 (i++). analogWrite(PWMpin,1); //El valor de la variable para a ser 1. delay(10); //Espera 10ms. Serial.println(i); } }
true
152ccdf6a64da9eb2c6cba6e06d26b5f2c216b5b
C++
INF1015-2021H/c04-s03-exercices-Zabiullah-sz
/Exercises/Employee.hpp
UTF-8
459
3.203125
3
[]
no_license
/// /// Classe d'employé dans une compagnie. /// #pragma once #include <cstddef> #include <cstdint> #include <string> using namespace std; class Employee { public: //Employee(); // Si on n'en met pas un, le compilateur n'en met pas un pour nous. Employee(const string& name, double salary = 0.0); ~Employee(); double getSalary() const; const string& getName() const; void setSalary(double salary); private: string name_; double salary_; };
true
b402518f41067823e0a048f326c8165f252666ab
C++
UtkarshGupta12/InterviewBit
/Tree Data Structure/populate-next-right-pointers-tree.cpp
UTF-8
1,178
3.5
4
[]
no_license
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ void Solution::connect(TreeLinkNode* root) { TreeLinkNode* res = root; //BASE CASE if(root==NULL) return ; //Initialising Variables queue<TreeLinkNode*> q; vector<vector<TreeLinkNode*>> vec; q.push(root); while(!q.empty()) { int count = q.size(); vector<TreeLinkNode*> tmp; while(count--) { TreeLinkNode* temp = q.front(); q.pop(); if(temp->right!=NULL) q.push(temp->right); if(temp->left!=NULL) q.push(temp->left); tmp.push_back(temp); } reverse(tmp.begin(),tmp.end()); vec.push_back(tmp); } //printTreeVecvec(vec);cout<<endl; //Connecting each right side for(int i=0;i<vec.size();i++) { for(int j=0;j<vec[i].size()-1;j++) { vec[i][j]->next = vec[i][j+1]; } vec[i].back()->next = NULL; } return ; }
true
43c912111bd6ff9fa50bd840ad3c466a1868a27e
C++
sonyhome/DigitalIO
/Examples/4_ultrasonicSensorSonar/4_ultrasonicSensorSonar.ino
UTF-8
4,246
3.046875
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // DigitalIO demo // A straightforward library to use rotary encoders on Arduinos //////////////////////////////////////////////////////////////////////////////// // Ultrasonic Sensor - Sonar example // // This demo shows how to measure distance with an ultrasonic sensor using the // digitalSonar class for Uno. The Serial console will display the distance, and // the onboard LED will turn on if an object is within 12", be off if there is // an object farther, or blink if the sonar doesn't bounce on anything close. // // Ultrasonic sensors are sonars that emit a ping when triggered, and then // wait for the echo to come back. They return the min bounce time of the ping, // which can be converted to a distance. // Sonars supported come with 2 pins, a trigger that expects a 10uSec signal to // start the sonar, and an echo pin that will return a HIGH square wave matching // the time it took for the signal to bounce. // // The class can be set to use interrupts to hide the ping delay to your loop(). // DIGITAL_IO_SONAR_TIMEOUT can be adjusted to ignore pings that take too long. // This also limits the max distance monitored. If a ping is lost, it reads 0. //////////////////////////////////////////////////////////////////////////////// // Example pinout for a HC-SR04 untrasonic sonar board // // Arduino Uno HC-SR04 Ultrasonic Sensor // Gnd ------ Gnd // Pin 3 ------ Echo // Pin 4 ------ Trigger // 5V ------ Vcc // //////////////////////////////////////////////////////////////////////////////// // digitalSonar class template parameters: // // Port Name(+) Only for digitalSonarAvr, letter name of port (A..K) // Trigger Pin Pin where the 10usec square wave is output to start // Echo Pin(*) Pin where the square wave response is read // Use Interrupt(*) Optional: default false. A read() will return a value // read before and trigger a new ping for the next read(). // cwIf true, the Echo pin must be one with an interrupt. // Interrupt Number(*) With digitalSonarAvr provide the interrupt number. It is // the interrupt attached to the Echo pin. // // To find the digital pins that support interrupts, and find the interrupt to // pin pairing, search online for your Arduino board documentation. For Arduino // Uno, Pin 2 (D2) is tied to interrupt 0, and Pin 3 (D3) to interrupt 3. // The DIGITAL_IO_SONAR_TIMEOUT macro can be set to change the default timeout // of 0x7FFF microseconds. //////////////////////////////////////////////////////////////////////////////// //#define DIGITAL_IO_DEBUG 1 #define DIGITAL_IO_SONAR_TIMEOUT 5000 // divide by 5600 to get the max dist in meter #include <DigitalIO.hpp> digitalIo<13, LOW> led; //digitalIoAvr<B,5, LOW> led; // pin 13 // Uncomment only one of the sonar declarations digitalSonar<4,3> sonar; // 2584 byte program storage, 201 bytes RAM //digitalSonar<4,3,true> sonar; // 2854 byte program storage, 207 bytes RAM //digitalSonarAvr<D,4,3> sonar; // 2504 byte program storage, 201 bytes RAM //digitalSonarAvr<D,4,3,true,1> sonar; // 2704 byte program storage, 207 bytes RAM void setup() { Serial.begin(9600); led.outputMode(); Serial.println("Start!\n"); } void loop() { // Uncomment only one of the value lines uint16_t value = sonar.read(cm); const uint16_t detect = 30; const char* units = " cm"; //uint16_t value = sonar.read(mm); const uint16_t detect = 300; const char* units = " mm"; //uint16_t value = sonar.read(sixteenth); const uint16_t detect = 12*16; const char* units = "/16 in"; //uint16_t value = sonar.read(inch); const uint16_t detect = 12; const char* units = " in"; //uint16_t value = sonar.read(usec); const uint16_t detect = 1800; const char* units = " usec"; if (value == 0) { // Blink LED if sonar is out of range led.toggle(); } else if (value < detect) { // Turn on LED if sonar detects something close led.turnOn(); } else { // Turn off LED if sonar detects nothing close led.turnOff(); } Serial.print(value); Serial.println(units); delay(250); }
true
259e2aa19d0e0d138a76170c55de2fbff72b54c7
C++
ElectronicsWorks/Runner-Multitasking
/Runner4.ino
UTF-8
19,765
3.015625
3
[]
no_license
#define _ESP32 //#define _ARDUINO /* Runner (C) 2019 Dipl. Phys. Helmut Weber smallest (and fastest?) Cooperative Multitasking ever ESP32-Version, Arduino-Version Is it possible to use a cooperative OS as an RTOS ? What is an RTOS? It garantees a Job to be done just in a predefined time. Same is true for a reaction on an Sensor-Action at the outside - interrupts are inventented for this. If the mouse pointer on the screen reacts on mouse movements without a delay a human can recognize the OS (Windows, Linux) is an RTOS in this sense. Most RTOS have a ticktime (mostly 1 ms) after which the OS saves the actual task state and starts the task which is READY and has the highest priority. But changing tasks only every 1ms is not enough. A Task with highest priority, which is allways READY, would suppress any other task. For that the YIELD is invented. This allows a task to initiate a taskswitch long before its 1 ms timeslice is over. In reality most tasks give up their timeslices with YIELD or DELAY! That means, most tasks are cooperative in an RTOS. A real RTOS has a MMU to protect Program- an Data-Space of a task! And that is the most important feature of an RTOS. If a CPU does not have this feature a cooperative system can be used as an RTOS as well. A lot of RTOS tasks have the structure: while(1) { ... Some code DELAY ... YIELD ... DELAY } My "CoopOS" is build to rebuild such structures! But very often you have to do a task from the beginning to the end - running in determined intervals. This program RUNNER is built for such systems. It is extreme compact (about 100 lines). There are only 3 functions: >>>>>>>>>> INITRUN() This function is used to build the tasklist. >>>>>>>>>> RUNNER This function is called as often as possible to start tasks which are READY (interval has passed by). while(1) { RUNNER(); } RUNNER calls the task, which is READY and is the first in the tasklist. RUNNER is called (average) every 2.3 µs. The longest time gap between 2 calls is measured 20 µs. >>>>>>>>>> DELAY() Is used in tasks at points, where a delay is possible. Delay calls RUNNER recursively. It is used to give high priority tasks the chance to run. Running (and delayed) tasks are not started again. The advantages: - PURE ANSI C (well, without micros() and IO-operations) - TRANSPORTABLE SOURCES - VERY SIMPLE, BUT VERSATILE - NO STACKSWICTH - NO SETJMP/LONGJMP - VERY FAST TASKSWITCHES - TASKSWITCHING "DELAY" IS NOT ONLY USABLE IN TASKS BUT ALSO IN ALL CALLED FUNCTIONS - TASKS ARE NORMAL FUNCTIONS WITHOUT CALLING SUCH FUNCTIONS/DEFINES LIKE "BEGIN_TASK/END_TASK" - NO TIMERS/INTERRUPTS ARE USED - NO LIBRARIES USED - ABOUT 100 LINES OF SOURCE CODE A Task should run complete from start to end - but it may contain as much DELAYS as you want ! A lot of people think, an ESP32 is mostly used as an interacting device using BLE or WLAN. That may be true for most users, but I use it often without these features - just like a superfast Arduino. But with the 2 cores of the ESP32 it is possible to use BLE/WLAN together with RUNNER with no introduced delays. This program is thought as an example. Here are the 8 tasks: - ID_Fast= InitRun(Fast, 50-13, PRI_KERNEL); // Send 2. DAC value every 38µs (max.: 53µs) Marks start of task (digitalWrite) and sends a value to DAC channel 1 to build s sawtooth This task is called ever 38µs. The deadline of this task is 55µs which is never reached or exceeded. - ID_Fast2= InitRun(Fast2, 50-12, PRI_KERNEL); // Send DAC value every 38µs (max.: 53µs) Like FAST, but using DAC channel2 and build a sine function. It is independent of FAST and the interval time could be changed indepentently. - ID_Blink= InitRun(Blink, 100000, PRI_USER1); // Toggle "LED" every 100 ms A blinking LED is the "Hello world" of each multitasker ;) - ID_Count= InitRun(Count, 1000000, PRI_USER1); // Count and print every second Counts and print seconds (and the longest time gap between 2 RUNNER-calls - never reaching or exeeding 20 µs) - ID_Runs= InitRun(Runs, 1000000, PRI_USER1); // Show Taskswitch calls every second Shows system-information every second: 1) 2) 3) 4) 5) 6) 438099 25980 53 52 103200 1 1) number of RUNNER calls per second. The average is one call every 2.3 µs !!!!! 2) number of FAST is called per second. The average is one call every 38 µs ! 3) longest time from call to call of FAST. 53 µs 4) longest time from call to call of FAST2. 53 µs 5) number of total Lotto-draws ( 20 per second ) 6) level of recursion of RUNNER - ID_SerOut= InitRun(SerOut, 1000, PRI_USER2); // Send buffered characters to serial line Serial output of strings is a break for all systems. Here the serial output is buffered an the characters are sent to the line with an interval of 1 ms. So serial output induces much less system-delay. - ID_WaitEvent= InitRun(WaitEvent,1000, PRI_EVENT); // Wait for an event (1000µs deadtime after an event) For an RTOS it is important to react fast on external or internal events. A task can set to state WAITEVENT. Another task (or an interrupt) can activate a waiting task. Here WAITEVENT is activated from BLINK every 10 seconds. The delay from activating(BLINK) to run WAITEVENT is 2-3 µs! This is may considered as VERY FAST. - ID_Lotto= InitRun(Lottery, 50000, PRI_USER2); // Check Lotto translucent 20 times a second and show results (hits>=4) This task should show how to build state machine tasks and longer delays. LOTTO draws 6 numbers out of 49. This is the winning combination. Then LOTTO draws 20 times 6/49 combinations per second and compares them with the winning combination. If 4 or more numbers are correct the combination is print out. Here we have 8 tasks are running very deterministic! Even 2 tasks running every 38 µs are determinstic in the way, they are never delayed more than 15 µs. Once again: No interrupts are needed. Using serial output and achieving these results show, how a very simple cooperative system running from AtTiny over Arduino, ESP32 to supercomputers can be used as an RTOS. */ #ifdef _ESP32 #include <driver/dac.h> #include <math.h> #endif typedef void Task; #define SERMAX 200 // 200 characters buffer char SerString[SERMAX]; // Buffer for serial output int SerHead, SerTail; // Pointer in Buffer unsigned long runs; // counting Scheduler calls (Runner) unsigned int ID_Fast, ID_Fast2, ID_Blink, ID_Count, ID_Runs, ID_SerOut, ID_WaitEvent, ID_Lotto; int FastCnt,FastCnt2;; unsigned long lcounts; unsigned long EventStart; unsigned long LottoStart; unsigned long LastMics, MaxMics; // ===================== Start of operating system ====================== #define NUMRUNS 10 // Max. number of tasks #define MAXPRIORITY 0x0f // Lowest priority to handle by Runner #define MAXLEVEL 50 // Max. recursion level in Runner // Definition for states // states // high nibble = state #define STOPPED 0x80 #define WAITING 0x40 #define RUNNING 0x20 #define WAITEVENT 0x10 #define READY 0x00 // low nibble = priority #define PRI_KERNEL 0x0 #define PRI_SYSTEM 0x1 #define PRI_EVENT 0x2 #define PRI_USER0 0x3 #define PRI_USER1 0x4 #define PRI_USER2 0x5 #define PRI_USER3 0x6 #define PRI_USER4 0x7 unsigned char numruns; // countings tasks void (*runfunction[NUMRUNS])(void); // functions of tasks unsigned long runinterval[NUMRUNS]; // interval for each task unsigned long lastrun[NUMRUNS]; // last time called unsigned char priorities[NUMRUNS]; // priorities of tasks /* Init a Task (function, intervalin microseconds, Priority) */ int InitRun(void (*userfunction)(void), unsigned long interval, unsigned char priority) { int i, j; i = numruns; // replace STOPPED tasks for (j = 0; j < numruns; j++) { if (priorities[j] & STOPPED) { i = j; break; } } runfunction[i] = userfunction; //runinterval[i] = interval-4; // ARDUINO runinterval[i] = interval; // ESP32 lastrun[i] = micros(); priorities[i] = priority; if (i >= numruns) numruns = ++i; if (numruns >= NUMRUNS) { SerPrint("numruns >= NUMRUNS\n"); while(1); } return (numruns-1); } char level, irlevel, thisTask; /* Schedule Tasks */ void Runner(unsigned char maxPrio) { // call this from loop: Runner(MAXPRIORITY); unsigned char *p; register unsigned char *pp; unsigned long mics; int c; int prioHigh; int nextJob; runs++; if (level >= MAXLEVEL) { SerPrint("LEVEL"); return; } mics=micros(); // to test longest time between 2 RUNNER calls Arduino: 156 µs, ESP32: 20µs // if ((mics-LastMics) > MaxMics) { // MaxMics=mics-LastMics; // } // LastMics=mics; prioHigh=0x0f; nextJob=-1; level++; // priority is tasknumber //mics=micros(); for (c = 0; c < numruns; c++) { if ( (mics - lastrun[c]) >= runinterval[c]) { // interval passed? p = &priorities[c]; if (*p <=maxPrio) { // test priority lastrun[c] = mics; // remember start time *p |= RUNNING; // set RUNNING thisTask = c; // set global thisTask (*runfunction[c])(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< run the task *p &= ~RUNNING; // reset ŔUNNING break; } } } level--; } // call this from inside of long working functions inline void Delay(unsigned long dely, unsigned char maxPrio) { volatile unsigned long m; uint8_t mycurtask; // must be local ! irlevel++; mycurtask = thisTask; priorities[(int)thisTask] |= WAITING; // do not start the running task again m = micros(); do { Runner(maxPrio); // start tasks with priority = PRI_EVENT } while ((micros() - m) < dely); priorities[mycurtask] &= ~WAITING; // restore calling task thisTask=mycurtask; irlevel--; } // ===================== End of operating system ======================?= // ===================== Utility ======================================== void SerPrint(char *pt) { // print a string to buffer while (*pt != 0) { SerString[SerHead++]=*pt++; Delay(100,PRI_EVENT); if (SerHead>=SERMAX) SerHead=0; } } // ===================== Tasks ========================================== Task SerOut() { // Max 1000 characters/s with interval 1000 if (SerHead != SerTail) { #ifdef _ARDUINO UDR0=SerString[SerTail++]; // Arduino: no test of free buffer neccessary #else Serial.write(SerString[SerTail++]); // ESP32 #endif if(SerTail==SERMAX) SerTail=0; } } Task Blink() { static uint8_t On; static int cnt; if(On) { #ifdef _ARDUINO PORTB |= B00100000; #else digitalWrite(13,1); #endif On=0; } else { #ifdef _ARDUINO PORTB &= ~B00100000; #else digitalWrite(13,0); #endif On=1; } // Example of sending an event to a task // could be done by interrupt either cnt++; if ((cnt % 100)==0) { priorities[ID_WaitEvent] &= ~WAITEVENT; // removes WAITEVENT, RUNNING is left EventStart=micros(); } } Task Count() { char bf[20]; static unsigned int Cnt; SerPrint(itoa(Cnt++,bf, 10)); // Delay(100,PRI_EVENT); // show longest interval between RUNNER-calls // SerPrint(" "); // Delay(100,PRI_EVENT); // SerPrint(ltoa(MaxMics,bf, 10)); // MaxMics=0; // Delay(100,PRI_EVENT); SerPrint("\n"); } long longest; Task Fast() { // should: every 38 µs, max.: 53µs static long m, last; m=micros(); if(last==0) last=m; if((m-last) > longest) longest = m-last; last=m; #ifdef _ARDUINO // to mark the running of this task //digitalWrite(12,1); //digitalWrite(12,0); PORTB |= B00010000; PORTB &= ~B00010000; #endif #ifdef _ESP32 // DAC: output sawtooth dac_output_voltage((dac_channel_t)1, (uint8_t)(FastCnt&0xff)); // to show start and end of counting 0-127, 127-255 digitalWrite(12,(FastCnt&0x80)); // to measure resolution: 38 µs //dac_output_voltage((dac_channel_t)1, (uint8_t)((FastCnt&0xff)<<7)); #endif FastCnt++; } long longest2; unsigned char sine[256]; Task Fast2() { // should: every 200 µs, is: ever 211-216 µs static long m, last; m=micros(); if(last==0) last=m; if((m-last) > longest2) longest2 = m-last; last=m; #ifdef _ARDUINO digitalWrite(14,1); digitalWrite(14,0); #endif #ifdef _ESP32 // DAC: output sine dac_output_voltage((dac_channel_t)2, (uint8_t)sine[(unsigned int)(FastCnt2&0xff)]); #endif FastCnt2++; } Task Runs() { char bf[20]; int f; //Serial.print(runs); SerPrint(ltoa(runs,bf,10)); // 1 runs=0; Delay(100,PRI_EVENT); //Serial.print(" "); SerPrint(" "); Delay(100,PRI_EVENT); f=FastCnt; FastCnt=0; // 2 //Serial.println(FastCnt); SerPrint(itoa(f,bf,10)); // 3 Delay(100,PRI_EVENT); SerPrint(" "); Delay(100,PRI_EVENT); SerPrint(itoa(longest,bf,10)); // 4 SerPrint(" "); Delay(100,PRI_EVENT); SerPrint(itoa(longest2,bf,10)); // 4 Delay(100,PRI_EVENT); SerPrint(" "); SerPrint(ltoa(lcounts,bf,10)); // 5 Delay(100,PRI_EVENT); SerPrint(" "); SerPrint(itoa(level,bf,10)); // 5 Delay(100,PRI_EVENT); SerPrint("\n"); //longest=0; } Task WaitEvent() { char bf[20]; unsigned long l; l=micros(); SerPrint("\nWaitEvent "); Delay(100,PRI_EVENT); SerPrint(ltoa(l-EventStart,bf,10)); // ESP32: 2-3 µs, Arduino: 36-68 µs Delay(100,PRI_EVENT); SerPrint(" us\n"); Delay(100,PRI_EVENT); priorities[ID_WaitEvent] |= WAITEVENT; // gives RUNNING + WAITEVENT, reset by Blink, } // ===================== Lottery help functions ======================= void sort(int a[], int size) { for(int i=0; i<(size-1); i++) { Delay(100,PRI_EVENT); for(int o=0; o<(size-(i+1)); o++) { Delay(100,PRI_EVENT); if(a[o] > a[o+1]) { int t = a[o]; a[o] = a[o+1]; a[o+1] = t; } } } } void Draw( int lotto[]) { static int index; index=0; next: Delay(100,PRI_EVENT); while (index<6) { long r=random(1,49); for (int i=0; i<6; i++) { Delay(100,PRI_EVENT); if(lotto[i]==(int)r) { goto next; } } lotto[index++]=(int)r; } } int lottoCompare(int lotto[], int lottoTest[]) { int hits=0; for (int i=0; i<6; i++) { for (int j=0; j<6; j++) { Delay(100,PRI_EVENT); if (lotto[i]==lottoTest[j]) hits++; } } return hits; } // ===================== End of Lottery help functions ================ Task Lottery() { static int state=0; static int lotto[6]; static int lottoTest[6]; char bf[20]; int hits; static int WinTimes; LottoStart=micros(); digitalWrite(11,1); digitalWrite(11,0); lcounts++; if (state==0) { // draw 6 winning numbers out of 49 randomSeed(analogRead(0)); Delay(100,PRI_EVENT); Draw(lotto); Delay(1000,PRI_EVENT); sort(lotto,6); if (state==0) { state=1; return; } } Draw(lottoTest); // new Lottery translucent Delay(100,PRI_EVENT); sort(lottoTest,6); Delay(100,PRI_EVENT); hits=lottoCompare(lotto, lottoTest); Delay(100,PRI_EVENT); if(hits>=4) { // 4 hits: perfect value: Counts/Wins == 1030 WinTimes++; SerPrint("\n Wins: "); Delay(100,PRI_EVENT); SerPrint(itoa(WinTimes,bf,10)); Delay(100,PRI_EVENT); SerPrint(" Hits: "); Delay(100,PRI_EVENT); SerPrint(itoa(hits,bf,10)); Delay(100,PRI_EVENT); SerPrint(" Counts: "); Delay(100,PRI_EVENT); SerPrint(ltoa(lcounts,bf,10)); Delay(100,PRI_EVENT); SerPrint("\n"); for (int i=0; i<6; i++) { Delay(100,PRI_EVENT); SerPrint(itoa(lotto[i],bf,10)); SerPrint(" "); } SerPrint("\n"); Delay(100,PRI_EVENT); for (int i=0; i<6; i++) { Delay(100,PRI_EVENT); SerPrint(itoa(lottoTest[i],bf,10)); SerPrint(" "); } SerPrint(" µs: "); SerPrint(ltoa(micros()-LottoStart,bf,10)); // about 23000 µs SerPrint("\n"); } } int mymain(void) { Serial.println("Intro to RUNNER multitasking (C) 2015 H. Weber\n"); // Green text Lottery(); // Draw the winning numbers #ifdef _ESP32 ID_Fast= InitRun(Fast, 50-13, PRI_KERNEL); // Send 2. DAC value every 38µs (max.: 53µs) ID_Fast2= InitRun(Fast2, 50-14, PRI_KERNEL); // Send DAC value every 38µs (max.: 53µs) #endif #ifdef _ARDUINO ID_Fast= InitRun(Fast, 500-150, PRI_KERNEL); // Send 2. DAC value every 38µs (max.: 53µs) (ESp32) ID_Fast2= InitRun(Fast2, 500-170, PRI_KERNEL); // Send DAC value every 38µs (max.: 53µs) (ESP32) #endif ID_Blink= InitRun(Blink, 100000, PRI_USER1); // Toggle "LED" every 100 ms ID_Count= InitRun(Count, 1000000, PRI_USER1); // Count and print every second ID_Runs= InitRun(Runs, 1000000, PRI_USER1); // Show Taskswitch calls every second ID_SerOut= InitRun(SerOut, 1000, PRI_USER2); // Send buffered characters to serial line ID_WaitEvent= InitRun(WaitEvent,1000, PRI_EVENT); // Wait for an event (1000µs deadtime after an event) ID_Lotto= InitRun(Lottery, 50000, PRI_USER2); // Check Lotto translucent 20 times a second and show results (hits>=4) while(1) Runner(MAXPRIORITY); // endless loop return(0); } void setup() { Serial.begin(921600); pinMode(13,OUTPUT); pinMode(12,OUTPUT); pinMode(11,OUTPUT); pinMode(14,OUTPUT); #ifdef _ESP32 dac_output_enable((dac_channel_t) 1); #endif for (int i=0;i<256;i++) { sine[i]= (int)(128.0 + ( 127.0*sin((float)i/255.0*6.28) )); //Serial.println(sine[i]); } #ifdef _ESP32 dac_output_enable((dac_channel_t) 2); #endif mymain(); // init and run tasks } // never used: void loop() { // put your main code here, to run repeatedly: }
true
d5399aaffefd0a3f00608b26be7457e69d366ca9
C++
rgayatri23/matvec
/Serial/matvec.cpp
UTF-8
2,431
3.09375
3
[]
no_license
#include "../arrayMD/arrayMD.h" #include <bits/stdc++.h> #include <chrono> #include <ctime> #include <iostream> #include <random> using namespace std::chrono; using DataType = int; #define ARRAY2D ArrayMD<DataType, 2, Device::cpu> #define ARRAY3D ArrayMD<DataType, 3, Device::cpu> const int N = 1000; const int repeat = 100; #define PRINT 1 int dot(DataType* m, DataType* x) { int result = 0; for (int k = 0; k < N; ++k) result += m[k] * x[k]; return result; } void matvec(int i, ARRAY3D& m, ARRAY2D& x, DataType* y) { for (int j = 0; j < N; ++j) y[j] += dot(m.subArray(i,j), x.subArray(i)); } void batched_matrix_vector(ARRAY3D& m, ARRAY2D& x, ARRAY2D& y) { for (int i = 0; i < N; ++i) matvec(i, m, x, y.subArray(i)); } int main(int argc, char** argv) { std::cout << "Running the basic sequential version." << std::endl; // Using time point and system_clock time_point<system_clock> start, end, k_start, k_end; start = system_clock::now(); // Use default_random_engine object to introduce randomness. std::default_random_engine generator; // Initialize uniform_int_distribution class. std::uniform_int_distribution<DataType> distribution(0, N); ARRAY2D y(N, N); ARRAY2D x(N, N); ARRAY3D m(N, N, N); std::cout << "Memory foot-print = " << (y.size + x.size + m.size) * (sizeof(DataType)) / (1024 * 1024 * 1024) << "GBs" << std::endl; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) for (int k = 0; k < N; ++k) m(i, j, k) = ((i + 1) * (j + 1) * (k + 1)) % INT_MAX; for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) { x(i, j) = ((i + 1) * (j + 1) * distribution(generator)) % INT_MAX; y(i, j) = 0; } k_start = system_clock::now(); for (int i = 0; i < repeat; ++i) batched_matrix_vector(m, x, y); end = system_clock::now(); duration<double> k_elapsed = end - k_start; duration<double> elapsed = end - start; std::cout << "Kernel time taken = " << k_elapsed.count() << " seconds" << std::endl; std::cout << "All done and time taken = " << elapsed.count() << " seconds" << std::endl; // Print out the output. Comment out unless needed. #if PRINT for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) std::cout << "y(" << i << ", " << j << ") = " << y(i, j) << "\t"; std::cout << "\n"; } #endif return 0; }
true
13009cde50946e269c75b26bdac52791df97e24a
C++
chiseungii/HONGIK
/2_1/객체지향프로그래밍/과제/hw3/5.cpp
UTF-8
2,641
3.453125
3
[ "MIT" ]
permissive
/* hw3 #5 */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "Member.h" using namespace std; int main() { Member* mArray = new Member[4]; // 객체 배열 동적 할당 // 각 정보 초기화 mArray[0].setID("cheol88"); mArray[0].setPWD("cheol88"); mArray[0].setName("김철수"); mArray[0].setAge(23); mArray[1].setID("ywjeong123"); mArray[1].setPWD("12345"); mArray[1].setName("정연우"); mArray[1].setAge(31); mArray[2].setID("Jiwoon456"); mArray[2].setPWD("34563%"); mArray[2].setName("박지운"); mArray[2].setAge(35); mArray[3].setID("Choi931"); mArray[3].setPWD("96454$$"); mArray[3].setName("최지우"); mArray[3].setAge(26); Member newMem; // 새로운 객체 생성 char newID[20], newPWD[20], newName[20]; // 입력 받을 변수들 int newAge; // 나이 // 아이디 조건 확인 // 1. 소문자 영문, 숫자만 입력 가능 // 2. 중복 불가능 while (1) { cout << "ID >> "; cin >> newID; bool flag = true; for (int i = 0; newID[i]; i++) { // 알파벳, 숫자가 아닌 경우 if (!isdigit(newID[i]) && !isalpha(newID[i])) { cout << "영문 소문자 혹은 숫자만 가능합니다.\n"; flag = false; break; } // 대문자가 섞인 경우 else if (newID[i] >= 'A' && newID[i] <= 'Z') { cout << "영문 소문자 혹은 숫자만 가능합니다.\n"; flag = false; break; } } if (!flag) continue; flag = true; for (int i = 0; i < 4; i++) { if (!strcmp(mArray[i].getID(), newID)) { cout << "이미 사용 중인 아이디입니다.\n"; flag = false; break; } } if (flag) break; } // 비밀번호 조건 확인 // 1. 특수문자가 최소한 1개는 있어야 함 // 2. 11자리 이상 19자리 이하 while (1) { cout << "PWD >> "; cin >> newPWD; bool flag = false; for (int i = 0; newPWD[i]; i++) { if ((newPWD[i] >= '!' && newPWD[i] <= '/') || (newPWD[i] >= ':' && newPWD[i] <= '@') || (newPWD[i] >= '[' && newPWD[i] <= '`') || (newPWD[i] >= '{' && newPWD[i] <= '~')) { flag = true; break; } } if (!flag) { cout << "특수문자를 반드시 포함해야 합니다.\n"; continue; } if (strlen(newPWD) >= 11 && strlen(newPWD) <= 19) break; else cout << "비밀번호는 11자리 이상 19자리 이하로 입력하세요.\n"; } cout << "이름 >> "; cin >> newName; cout << "나이 >> "; cin >> newAge; // 객체에 정보 임력 newMem.setID(newID); newMem.setPWD(newPWD); newMem.setName(newName); newMem.setAge(newAge); newMem.printMemInfo(); // 메모리 반환 delete[] mArray; }
true
51fe5ffa56b73dfa036213ed63046b39b66e9aa1
C++
Ukun115/CarBOOM
/ExEngine/effect/EffectEngine.cpp
SHIFT_JIS
3,429
2.59375
3
[]
no_license
#include "stdafx.h" #include "EffectEngine.h" EffectEngine* EffectEngine::m_instance = nullptr; //B̃CX^XB EffectEngine::EffectEngine() { MY_ASSERT( m_instance == nullptr, "EffectEnginẽCX^X𕡐邱Ƃ͂ł܂B" ); auto format = DXGI_FORMAT_R8G8B8A8_UNORM; auto d3dDevice = g_graphicsEngine->GetD3DDevice(); auto commandQueue = g_graphicsEngine->GetCommandQueue(); // _[쐬B m_renderer = ::EffekseerRendererDX12::Create( d3dDevice, commandQueue, 3, &format, 1, DXGI_FORMAT_D32_FLOAT, false, 8000 ); //v[̍쐬B m_memoryPool = EffekseerRenderer::CreateSingleFrameMemoryPool(m_renderer->GetGraphicsDevice()); // R}hXg̍쐬 m_commandList = EffekseerRenderer::CreateCommandList(m_renderer->GetGraphicsDevice(), m_memoryPool); // GtFNg}l[W[̍쐬B m_manager = ::Effekseer::Manager::Create(8000); // `惂W[̐ݒB m_manager->SetSpriteRenderer(m_renderer->CreateSpriteRenderer()); m_manager->SetRibbonRenderer(m_renderer->CreateRibbonRenderer()); m_manager->SetRingRenderer(m_renderer->CreateRingRenderer()); m_manager->SetTrackRenderer(m_renderer->CreateTrackRenderer()); m_manager->SetModelRenderer(m_renderer->CreateModelRenderer()); // [_[̐ݒB m_manager->SetTextureLoader(m_renderer->CreateTextureLoader()); m_manager->SetModelLoader(m_renderer->CreateModelLoader()); m_manager->SetMaterialLoader(m_renderer->CreateMaterialLoader()); m_manager->SetCurveLoader(Effekseer::MakeRefPtr<Effekseer::CurveLoader>()); } EffectEngine::~EffectEngine() { } Effekseer::EffectRef EffectEngine::LoadEffect(const char16_t* filePath) { std::u16string u16FilePath = filePath; Effekseer::EffectRef effect; auto it = m_effectMap.find(u16FilePath); if (it != m_effectMap.end()) { //[hς݁B effect = it->second; m_effectMap.insert({ u16FilePath, effect }); } else { //VK effect = Effekseer::Effect::Create(m_manager, filePath); } return effect; } int EffectEngine::Play(Effekseer::EffectRef effect) { return m_manager->Play(effect, 0, 0, 0); } void EffectEngine::Stop(int effectHandle) { m_manager->StopEffect(effectHandle); } void EffectEngine::Update(float deltaTime) { m_memoryPool->NewFrame(); // Begin a command list // R}hXgJnB EffekseerRendererDX12::BeginCommandList(m_commandList, g_graphicsEngine->GetCommandList()); m_renderer->SetCommandList(m_commandList); m_manager->Update(); //_[ɃJsݒB m_renderer->SetCameraMatrix(*(const Effekseer::Matrix44*)&g_camera3D->GetViewMatrix()); //_[ɃvWFNVsݒB m_renderer->SetProjectionMatrix(*(const Effekseer::Matrix44*)&g_camera3D->GetProjectionMatrix()); m_renderer->SetTime(deltaTime); } void EffectEngine::Draw() { // Begin to rendering effects // GtFNg̕`JnsB m_renderer->BeginRendering(); // Render effects // GtFNg̕`sB m_manager->Draw(); // Finish to rendering effects // GtFNg̕`IsB m_renderer->EndRendering(); // Finish a command list // R}hXgIB m_renderer->SetCommandList(nullptr); EffekseerRendererDX12::EndCommandList(m_commandList); }
true
da66a12b11af5ff4f34366d5cdd58f37ad125f51
C++
jo797/HWK6
/HWK6/ArithmeticExpression.cpp
UTF-8
2,704
3.734375
4
[]
no_license
/* * Name: Joletta Cheung, Cameron Swinoga, Aleksander Mercik * MacID: cheunj3, swinogca, mercikaz * Student Number: 1406622, 1404603, 1413714 * Description: This program takes a mathematical expression and outputs the answer */ #include <iostream> #include "ArithmeticExpression.h" #include <string> #include <stdlib.h> using namespace std; ArithmeticExpression::ArithmeticExpression() : Expression::Expression(){ //Constructor when nothing is given left = NULL; //If we just want a new object, first call the expression constructor right = NULL; //Then set the left and right objects to null } ArithmeticExpression::ArithmeticExpression(string s) : Expression::Expression(s){ //Constructor when passing in a string left = NULL; //First call the Expression constructor right = NULL; //Then set the left and right objects to null } string ArithmeticExpression::evaluate(){ //Evaluate override from Expression if (left != NULL) //If there's a left branch return left->evaluate(); //Evaluate the left branch else if (right != NULL) //If there's a right branch return right->evaluate(); //Evaluate the right branch else //Else this is an end node return exp; //Print the expression string } void ArithmeticExpression::print(){ //Print override from Expression if (left != NULL) //If there's a left branch left->print(); //Print the left branch else if (right != NULL) //If there's a right branch right->print(); //Print the right branch else //Else this is an end node cout << exp; //Print the expression string } void ArithmeticExpression::increment(){ //Method to recursively increment all numbers if (left != NULL) //If there's a left branch left->increment(); //Increment the left branch if (right != NULL) //If there's a right branch right->increment(); //Increment the right branch if (left == NULL && right == NULL && exp != "0") //Else this is an end node exp = to_string((int)(convert(exp)+1.0)); //Increment the current expression, after converting a bunch } void ArithmeticExpression::setLR(string L, string R){ //Method to initialize the left and right Expression pointers from two strings left = new ArithmeticExpression(L); //Call the constructor with the respective strings right = new ArithmeticExpression(R); } float ArithmeticExpression::convert (string s){ //Function to convert a string to a float return stof(s, nullptr); //Return the converted value } ArithmeticExpression::~ArithmeticExpression(){ //Destructor definition delete left; //Delete the left pointer delete right; //Delete the right pointer }
true
7d9e7adba329c6fd9bf83937b64e9d0fefc078cc
C++
wmotte/toolkid
/src/orient/orient.cpp
UTF-8
5,263
2.546875
3
[ "MIT" ]
permissive
#include "itkOrientImageFilter.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageIOBase.h" #include <string> #include "tkdCmdParser.h" template< class TPixel, unsigned int VDimension > int OrientImage( const std::string& inputFileName, const std::string& outputFileName, itk::SpatialOrientation::ValidCoordinateOrientationFlags desired = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI, itk::SpatialOrientation::ValidCoordinateOrientationFlags given = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_INVALID ) { typedef itk::Image< TPixel, VDimension > ImageType; typedef itk::OrientImageFilter< ImageType, ImageType > FilterType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageFileWriter< ImageType > WriterType; typename ReaderType::Pointer reader = ReaderType::New(); typename FilterType::Pointer filter = FilterType::New(); typename WriterType::Pointer writer = WriterType::New(); reader->SetFileName( inputFileName.c_str() ); writer->SetFileName( outputFileName.c_str() ); filter->SetInput( reader->GetOutput() ); writer->SetInput( filter->GetOutput() ); reader->Update(); if ( given == itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_INVALID ) { filter->UseImageDirectionOn(); } else { filter->UseImageDirectionOff(); filter->SetGivenCoordinateOrientation( given ); } filter->SetDesiredCoordinateOrientation( desired ); filter->Print( std::cout ); writer->Update(); return 0; } void ParseOrientation( const std::string& text, itk::SpatialOrientation::ValidCoordinateOrientationFlags& orient ) { #define poMacro( t ) \ if ( text == #t ) \ { \ orient = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_##t; \ return; \ } poMacro( RIP ); poMacro( LIP ); poMacro( RSP ); poMacro( LSP ); poMacro( RIA ); poMacro( LIA ); poMacro( RSA ); poMacro( LSA ); poMacro( IRP ); poMacro( ILP ); poMacro( SRP ); poMacro( SLP ); poMacro( IRA ); poMacro( ILA ); poMacro( SRA ); poMacro( SLA ); poMacro( RPI ); poMacro( LPI ); poMacro( RAI ); poMacro( LAI ); poMacro( RPS ); poMacro( LPS ); poMacro( RAS ); poMacro( LAS ); poMacro( PRI ); poMacro( PLI ); poMacro( ARI ); poMacro( ALI ); poMacro( PRS ); poMacro( PLS ); poMacro( ARS ); poMacro( ALS ); poMacro( IPR ); poMacro( SPR ); poMacro( IAR ); poMacro( SAR ); poMacro( IPL ); poMacro( SPL ); poMacro( IAL ); poMacro( SAL ); poMacro( PIR ); poMacro( PSR ); poMacro( AIR ); poMacro( ASR ); poMacro( PIL ); poMacro( PSL ); poMacro( AIL ); poMacro( ASL ); } int main( int argc, char ** argv ) { std::string inputFileName; std::string outputFileName; std::string desiredString; std::string givenString; std::stringstream description; description << "Re-orient image." << std::endl; description << "Orientation is defined by a combination of three characters:" << std::endl; description << "\tL,R = left, right" << std::endl; description << "\tA,P = anterior, posterior" << std::endl; description << "\tS,I = superior, inferior" << std::endl; description << "e.g., AIL: x = A-P, y = I-S, z = L-R"; tkd::CmdParser p( "orient", description.str() ); p.AddArgument( inputFileName, "input" ) ->AddAlias( "i" ) ->SetInput( "filename" ) ->SetDescription( "Input image" ) ->SetRequired( true ); p.AddArgument( outputFileName, "output" ) ->AddAlias( "o" ) ->SetInput( "filename" ) ->SetDescription( "Output image" ) ->SetRequired( true ); p.AddArgument( desiredString, "desired" ) ->AddAlias( "d" ) ->SetInput( "orientation" ) ->SetDescription( "Desired output orientation (default: RAI)" ); p.AddArgument( givenString, "given" ) ->AddAlias( "g" ) ->SetInput( "orientation" ) ->SetDescription( "Given input orientation (default: determine from image)" ); if ( !p.Parse( argc, argv ) ) { p.PrintUsage( std::cout ); return -1; } itk::SpatialOrientation::ValidCoordinateOrientationFlags given, desired; given = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_INVALID; desired = itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI; if ( desiredString != "" ) { ParseOrientation( desiredString, desired ); } if ( givenString != "" ) { ParseOrientation( givenString, given ); } itk::ImageIOBase::Pointer io = itk::ImageIOFactory::CreateImageIO( inputFileName.c_str(), itk::ImageIOFactory::ReadMode ); if ( !io ) { std::cerr << "Could not create a reader for " << inputFileName << std::endl; return -1; } io->SetFileName( inputFileName.c_str() ); io->ReadImageInformation(); #define switchMacro( itkPixel, pixel, dimension ) \ if ( io->GetNumberOfDimensions() == dimension && io->GetComponentType() == itk::ImageIOBase::itkPixel ) \ { \ return OrientImage< pixel, dimension >( inputFileName, outputFileName ); \ } // switchMacro( FLOAT, float, 3 ); // switchMacro( FLOAT, float, 4 ); return OrientImage< float, 3 >( inputFileName, outputFileName, desired, given ); std::cerr << "Unsupported pixel/dimension" << std::endl; return -1; }
true
2b299d64a9428085b70f9032cf62adef1b686d56
C++
TaintedGear/LudumDare-28
/OneShotOneKill Source/LudumDare_48/ImageManager.h
UTF-8
754
3.09375
3
[ "Zlib", "FTL" ]
permissive
#ifndef IMAGE_MANAGER_H #define IMAGE_MANAGER_H #include <iostream> #include <vector> #include <string> #include <SDL.H> using std::string; using std::vector; struct Image { Image() { m_texture = NULL; m_imageWidth = 0; m_imageHeight = 0; m_imageLabel = "NULL"; } void Release() { if(m_texture != NULL) { SDL_DestroyTexture(m_texture); m_texture = NULL; } } std::string m_imageLabel; SDL_Texture* m_texture; float m_imageWidth, m_imageHeight; }; class ImageManager { public: ImageManager(); ~ImageManager(); bool LoadImages(SDL_Renderer* renderer); void UnloadImages(); Image& GetImage(string label); private: bool LoadFromFile(SDL_Renderer* renderer, string filename); vector<Image> m_images; }; #endif
true
f488c06061c9ac95435fd97b315e6e40cbe14640
C++
al-ry/OOP-labs
/lab5/task1/Rational/RationalTests/CRationalTests.cpp
UTF-8
10,528
3.390625
3
[]
no_license
#include "stdafx.h" #include "../Rational/CRational.h" void VerifyNumeratorAndDenumerator(const CRational& verifiableFraction, int expectedNumerator, int expectedDenominator) { BOOST_CHECK(verifiableFraction.GetNumerator() == expectedNumerator); BOOST_CHECK(verifiableFraction.GetDenominator() == expectedDenominator); } BOOST_AUTO_TEST_SUITE(Test_Construcor) BOOST_AUTO_TEST_CASE(costructor_without_parameters_should_construct_fraction_with_0_numerator_and_1_denominator) { CRational rationalNumber; VerifyNumeratorAndDenumerator(rationalNumber, 0, 1); } BOOST_AUTO_TEST_CASE(costructor_with_one_parameter_should_construct_fraction_with_transfer_numerator) { CRational rationalNumber(5); VerifyNumeratorAndDenumerator(rationalNumber, 5, 1); } BOOST_AUTO_TEST_CASE(costructor_tow_parameter_should_construct_fraction_with_transfer_numerator_and_denomirator) { CRational rationalNumber(5, 2); VerifyNumeratorAndDenumerator(rationalNumber, 5, 2); } BOOST_AUTO_TEST_CASE(when_denominator_is_zero_should_construct_fraction_with_0_numerator_and_1_denominator) { CRational rationalNumber(5, 0); VerifyNumeratorAndDenumerator(rationalNumber, 0, 1); } BOOST_AUTO_TEST_CASE(when_denominator_lesser_than_0_should_construct_fraction_with_non_negative_denominator) { CRational rationalNumber(6, -5); VerifyNumeratorAndDenumerator(rationalNumber, -6, 5); } BOOST_AUTO_TEST_CASE(costructor_should_normalize_fraction) { CRational rationalNumber(840, 3600); VerifyNumeratorAndDenumerator(rationalNumber, 7, 30); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(Test_ToDouble_) BOOST_AUTO_TEST_CASE(should_convert_fraction_to_double) { CRational rationalNumber(1, 4); BOOST_CHECK_EQUAL(rationalNumber.ToDouble(), 0.25); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(Test_overloaded_unary_operators) BOOST_AUTO_TEST_CASE(when_overloaded_plus_should_change_numerator_value_to_plus) { CRational rationalNumber(-5, 10); rationalNumber = +rationalNumber; VerifyNumeratorAndDenumerator(rationalNumber, -1, 2); } BOOST_AUTO_TEST_CASE(when_overloaded_minus_should_change_numerator_value_to_minus) { CRational rationalNumber(-5, 10); rationalNumber = -rationalNumber; VerifyNumeratorAndDenumerator(rationalNumber, 1, 2); } BOOST_AUTO_TEST_SUITE_END() struct some_rational_numbers { CRational fiveSecond; CRational threeFifths; some_rational_numbers() : fiveSecond(5, 2) , threeFifths(3, 5){}; }; BOOST_FIXTURE_TEST_SUITE(Test_overloaded_binary_minus_operator, some_rational_numbers) BOOST_AUTO_TEST_CASE(overloaded_minus_should_add_two_rational_numbers) { CRational res = fiveSecond - threeFifths; VerifyNumeratorAndDenumerator(res, 19, 10); } BOOST_AUTO_TEST_CASE(when_one_operand_is_integer_should_substract_nums) { CRational res = fiveSecond - 1; VerifyNumeratorAndDenumerator(res, 3, 2); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_binary_star_operator, some_rational_numbers) BOOST_AUTO_TEST_CASE(overloaded_star_should_multiply_two_rational_numbers) { CRational res = fiveSecond * threeFifths; VerifyNumeratorAndDenumerator(res, 3, 2); } BOOST_AUTO_TEST_CASE(when_one_operand_is_integer_should_multiply_two_numbers) { CRational res = fiveSecond * 10; VerifyNumeratorAndDenumerator(res, 25, 1); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_binary_slash_operator, some_rational_numbers) BOOST_AUTO_TEST_CASE(overloaded_slash_should_divide_two_rational_numbers) { CRational res = fiveSecond / threeFifths; VerifyNumeratorAndDenumerator(res, 25, 6); } BOOST_AUTO_TEST_CASE(when_one_operand_is_integer_should_divide_two_numbers) { CRational res = fiveSecond / 2; VerifyNumeratorAndDenumerator(res, 5, 4); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_binary_plus, some_rational_numbers) BOOST_AUTO_TEST_CASE(overloaded_plus_should_add_two_rational_numbers) { CRational res = fiveSecond + threeFifths; VerifyNumeratorAndDenumerator(res, 31, 10); } BOOST_AUTO_TEST_CASE(when_one_operand_is_integer_should_add_nums) { CRational res = fiveSecond + 1; VerifyNumeratorAndDenumerator(res, 7, 2); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_operator_plus_equal, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_assign_two_rational_nums_should_assign_value_to_num) { fiveSecond += threeFifths; VerifyNumeratorAndDenumerator(fiveSecond, 31, 10); } BOOST_AUTO_TEST_CASE(when_right_num_is_int_should_assign_value_to_num) { fiveSecond += 5; VerifyNumeratorAndDenumerator(fiveSecond, 15, 2); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_operator_minus_equal, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_assign_two_rational_nums_should_assign_value_to_num) { fiveSecond -= threeFifths; VerifyNumeratorAndDenumerator(fiveSecond, 19, 10); } BOOST_AUTO_TEST_CASE(when_right_num_is_int_should_assign_value_to_num) { fiveSecond -= 1; VerifyNumeratorAndDenumerator(fiveSecond, 3, 2); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_operator_slash_equal, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_assign_two_rational_nums_should_assign_value_to_num) { fiveSecond /= threeFifths; VerifyNumeratorAndDenumerator(fiveSecond, 25, 6); } BOOST_AUTO_TEST_CASE(when_right_num_is_int_should_assign_value_to_num) { fiveSecond /= 10; VerifyNumeratorAndDenumerator(fiveSecond, 1, 4); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_operator_star_equal, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_assign_two_rational_nums_should_assign_value_to_num) { fiveSecond *= threeFifths; VerifyNumeratorAndDenumerator(fiveSecond, 3, 2); } BOOST_AUTO_TEST_CASE(when_right_num_is_int_should_assign_value_to_num) { fiveSecond *= 2; VerifyNumeratorAndDenumerator(fiveSecond, 5, 1); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_equal_operator, some_rational_numbers) BOOST_AUTO_TEST_CASE(should_compare_equals_values) { CRational comparedNum(5, 2); BOOST_CHECK(fiveSecond == comparedNum); } BOOST_AUTO_TEST_CASE(when_rvalue_is_integer_should_compare_equals_values) { CRational comparedNum(5); BOOST_CHECK(comparedNum == 5); } BOOST_AUTO_TEST_CASE(should_compare_not_equals_values) { BOOST_CHECK(!(fiveSecond == threeFifths)); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_not_equal_operator, some_rational_numbers) BOOST_AUTO_TEST_CASE(should_compare_not_equals_values) { BOOST_CHECK(fiveSecond != threeFifths); } BOOST_AUTO_TEST_CASE(when_rvalue_is_integer_should_compare_equals_values) { BOOST_CHECK(fiveSecond != 5); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_comparasion_operator_less_than, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_both_op_are_rational_nums_should_compare_values) { BOOST_CHECK(threeFifths < fiveSecond); } BOOST_AUTO_TEST_CASE(when_lvalue_is_int_should_compare_values) { BOOST_CHECK(1 < fiveSecond); } BOOST_AUTO_TEST_CASE(when_rvalue_is_int_should_compare_values) { BOOST_CHECK(threeFifths < 1); } BOOST_AUTO_TEST_CASE(when_values_equal_should_compare_values) { CRational num(3, 5); BOOST_CHECK(!(num <threeFifths)); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_comparasion_operator_less_than_or_equal_to, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_both_op_are_rational_nums_should_compare_values) { BOOST_CHECK(threeFifths <= fiveSecond); } BOOST_AUTO_TEST_CASE(when_lvalue_is_int_should_compare_values) { BOOST_CHECK(1 <= fiveSecond); } BOOST_AUTO_TEST_CASE(when_rvalue_is_int_should_compare_values) { BOOST_CHECK(threeFifths <= 1); } BOOST_AUTO_TEST_CASE(when_values_equal_should_compare_values) { CRational num(5, 2); BOOST_CHECK(fiveSecond <= num); BOOST_CHECK(num <= fiveSecond); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_comparasion_operator_greater_than, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_both_op_are_rational_nums_should_compare_values) { BOOST_CHECK(fiveSecond > threeFifths); } BOOST_AUTO_TEST_CASE(when_lvalue_is_int_should_compare_values) { BOOST_CHECK(fiveSecond > 1); } BOOST_AUTO_TEST_CASE(when_rvalue_is_int_should_compare_values) { BOOST_CHECK(1 > threeFifths); } BOOST_AUTO_TEST_CASE(when_values_equal_should_compare_values) { CRational num(3, 5); BOOST_CHECK(!(num > threeFifths)); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_comparasion_operator_greater_than_or_equal_to, some_rational_numbers) BOOST_AUTO_TEST_CASE(when_both_op_are_rational_nums_should_compare_values) { BOOST_CHECK(fiveSecond >= threeFifths); } BOOST_AUTO_TEST_CASE(when_lvalue_is_int_should_compare_values) { BOOST_CHECK(fiveSecond >= 1); } BOOST_AUTO_TEST_CASE(when_rvalue_is_int_should_compare_values) { BOOST_CHECK(1 >= threeFifths); } BOOST_AUTO_TEST_CASE(when_values_equal_should_compare_values) { CRational num(5, 2); BOOST_CHECK(fiveSecond >= num); BOOST_CHECK(num >= fiveSecond); } BOOST_AUTO_TEST_SUITE_END() BOOST_FIXTURE_TEST_SUITE(Test_overloaded_stream_operators, some_rational_numbers) BOOST_AUTO_TEST_SUITE(left_arrows_operator) BOOST_AUTO_TEST_CASE(can_put_rational_num_in_output) { std::stringstream strs; strs << fiveSecond; std::string expecteStr = "5/2"; BOOST_CHECK(expecteStr == strs.str()); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(right_arrows_operator) BOOST_AUTO_TEST_CASE(can_get_rational_num_in_output) { std::stringstream strs; strs << "50/2"; strs >> fiveSecond; VerifyNumeratorAndDenumerator(fiveSecond, 25, 1); } BOOST_AUTO_TEST_CASE(can_set_fail_bit_when_data_incorrect) { std::stringstream strs; strs << "50//2"; strs >> fiveSecond; BOOST_CHECK(strs.fail()); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(Test_ToCompoundFraction) BOOST_AUTO_TEST_CASE(can_convert_rational_to_compound_fraction) { CRational rational(24, 3); auto res = rational.ToCompoundFraction(); BOOST_CHECK(res.first == 8); VerifyNumeratorAndDenumerator(res.second, 0, 1); } BOOST_AUTO_TEST_CASE(can_convert_negative_rational_to_compound_fraction) { CRational rational(-7, 3); auto res = rational.ToCompoundFraction(); BOOST_CHECK(res.first == -2); VerifyNumeratorAndDenumerator(res.second, -1, 3); } BOOST_AUTO_TEST_SUITE_END()
true
dd2272fb048b6989f0f396fcc546e08ee4234a2f
C++
margaridav27/feup-aeda
/weekly practical exercises/aeda2021_p02_extra/Tests/zoo.cpp
UTF-8
1,961
3.28125
3
[]
no_license
#include "zoo.h" #include <iostream> #include <sstream> #include <stdlib.h> using namespace std; unsigned Zoo::numAnimals() const { return animals.size(); } unsigned Zoo::numVeterinarians() const { return veterinarians.size();} void Zoo::addAnimal(Animal *a1) { animals.push_back(a1); } string Zoo::getInfo() const { stringstream info; string data = ""; for (unsigned int i = 0; i < numAnimals(); i++) { info << animals[i]->getInfo() << endl; } return info.str(); } bool Zoo::isYoung(string nameA) { for (unsigned int i = 0; i < numAnimals(); i++) { if (animals[i]->getName() == nameA) { return animals[i]->isYoung(); } } return false; } void Zoo::allocateVeterinarians(istream &isV) { string name, cod; while (!isV.eof()) { getline(isV, name); getline(isV, cod); long c = atoi(cod.c_str()); Veterinary *vet = new Veterinary(name, c); veterinarians.push_back(vet); } for (int i = 0; i < numAnimals(); i++) { animals[i]->setVeterinary(veterinarians[i % numVeterinarians()]); } } bool Zoo::removeVeterinary(string nameV) { for (unsigned int i = 0; i < numVeterinarians(); i++) { if (veterinarians[i]->getName() == nameV) { for (unsigned int j = 0; j < numAnimals(); j++) { if (animals[j]->getVeterinary() == veterinarians[i]) { animals[j]->setVeterinary(veterinarians[(i + 1) % veterinarians.size()]); } } veterinarians.erase(veterinarians.begin() + i); return true; } } return false; } bool Zoo::operator<(Zoo &zoo2) const { int agesZoo1 = 0, agesZoo2 = 0; for (int i = 0; i < numAnimals(); i++) { agesZoo1 += animals[i]->getAge(); } for (int i = 0; i < zoo2.numAnimals(); i++) { agesZoo2 += zoo2.animals[i]->getAge(); } return agesZoo1 < agesZoo2; }
true
85058cf86f1f991fbb5b996308e79eb18e809fc3
C++
Raswood/Portafolio_00199718
/Laboratorio 2/Ejercicio 4a Labo 2.cpp
UTF-8
482
3.296875
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; void pi(int a, int b){ if(b>0){ if(a%2 != 0) cout<<a*2-1; else cout<<a*2-1; } pi(a+1, b-1); } int main(){ int n; cout<<"ingrese el dato:"<<endl; cin>>n; pi(1,n); return 0; } /*double pi(double); int main(){ cout<<"Ingrese el valor:"<<endl; cout<<pi(n)<<endl; return 0; } double pi(double n){ if(n==1){ return 4*1; }else{ return (4*(pow(-1,n+1)*(1/(2*n-1))) + pi(n-1)); } } */
true
9ca7ee782729839d7fffee3f455881c31c0a3adf
C++
sergiogutierrez2/Intro_to_C_plus_plus_Projects-DeAnza-2014
/Labs/Lab 5/Lab543.cpp
UTF-8
3,345
3.625
4
[]
no_license
// This program finds the average time spent programming by a student // each day over a three day period. // PLACE YOUR NAME HERE #include <iostream> using namespace std; int main() { int numStudents; float numHoursprogram, numHoursbio, total, averageprogramming, averagebiology, totalprogram, totalbio; int student, daysprogramming, daysbiology, day = 0; // these are the counters for the loops cout << "This program will find the average number of hours a day that" << endl; cout << "a student spent Programming and studying Biology over a certain period of days\n\n"; cout << "How many students are there ?" << endl; cin >> numStudents; cout << endl; for(student = 1; student <= numStudents; student++) { totalprogram = 0; totalbio = 0; cout << "Please enter the number of days that student " << student << " spent programming." << endl; cin >> daysprogramming; cout << endl << endl; for(day = 1; day <= daysprogramming; day++) { cout << "Please enter the number of hours the student " << student << " spent programming on day " << day << "." << endl; cin >> numHoursprogram; totalprogram = totalprogram + numHoursprogram; } averageprogramming = totalprogram / daysprogramming; cout << endl; cout << "The average number of hours per day spent programming by " << "student " << student << " is " << averageprogramming << endl << endl << endl; //LOLOLOLOLOL// //14568// cout << "Please enter the number of days that student " << student << " spent studying Biology." << endl; cin >> daysbiology; cout << endl << endl; for(day = 1; day <= daysbiology; day++) { cout << "Please enter the number of hours that student " << student << " spent studying Biology on day " << day << endl; cin >> numHoursbio; totalbio = totalbio + numHoursbio; } averagebiology = totalbio / daysbiology; cout << endl; cout << "The average number of hours per day spent studying Biology by " << "student " << student << " is " << averagebiology << endl << endl << endl; if (averageprogramming > averagebiology) { cout << "----Student " << student << " on average spent more time programming.----" << endl << endl; } else if (averageprogramming < averagebiology) { cout << "----Student " << student << " on average spent more time studying Biology.----" << endl << endl; } else { cout << "----Student " << student << " on average spent the same time studying Biology and Programming.----" << endl << endl; } } /* for(student = 1; student <= numStudents; student++) { total = 0; cout << "Please enter the number of days that student " << student << " spent studying biology." << endl; cin >> daysbiology; cout << endl << endl; for(day = 1; day <= daysbiology; day++) { cout << "Please enter the number of hours the student " << student << " spent programming on day " << day << "." << endl; cin >> numHours; total = total + numHours; } average = total / daysbiology; cout << endl; cout << "The average number of hours per day spent programming by " << "student " << student << " is " << average << endl << endl << endl; } */ return 0; }
true
764efb83532327d9186ed9877cd7c54b750b1843
C++
degarashi/revenant
/src/gl/error.cpp
UTF-8
4,496
2.625
3
[ "MIT", "BSD-3-Clause", "Zlib", "BSL-1.0" ]
permissive
#include "error.hpp" #include "if.hpp" #include "debug.hpp" namespace rev { // ------------------------- GLError ------------------------- const std::pair<GLenum, const char*> GLError::ErrorList[] = { {GL_INVALID_VALUE, "Numeric argument out of range (GL_INVALID_VALUE)"}, {GL_INVALID_ENUM, "Enum argument out of range (GL_INVALID_ENUM)"}, {GL_INVALID_OPERATION, "Operation illegal in current state (GL_INVALID_OPERATION)"}, {GL_INVALID_FRAMEBUFFER_OPERATION, "Framebuffer is incomplete (GL_INVALID_FRAMEBUFFER_OPERATION)"}, {GL_OUT_OF_MEMORY, "Not enough memory left to execute command (GL_OUT_OF_MEMORY)"} }; const char* GLError::errorDesc() { GLenum err; _errMsg.clear(); while((err = GL.glGetError()) != GL_NO_ERROR) { // OpenGLエラー詳細を取得 bool bFound = false; for(const auto& e : ErrorList) { if(e.first == err) { _errMsg += e.second; _errMsg += '\n'; bFound = true; break; } } if(!bFound) _errMsg += "unknown errorID\n"; } if(!_errMsg.empty()) return _errMsg.c_str(); return nullptr; } void GLError::reset() const { while(GL.glGetError() != GL_NO_ERROR); } const char* GLError::getAPIName() const { return "OpenGL"; } void GLError::resetError() const { while(GL.glGetError() != GL_NO_ERROR); } // ------------------------- GLProgError ------------------------- GLProgError::GLProgError(GLuint id): _id(id) {} const char* GLProgError::errorDesc() const { GLint ib; GL.glGetProgramiv(_id, GL_LINK_STATUS, &ib); if(ib == GL_FALSE) return "link program failed"; return nullptr; } void GLProgError::reset() const {} const char* GLProgError::getAPIName() const { return "OpenGL(GLSL program)"; } // ------------------------- GLShError ------------------------- GLShError::GLShError(const GLuint id): _id(id) {} const char* GLShError::errorDesc() const { GLint ib; GL.glGetShaderiv(_id, GL_COMPILE_STATUS, &ib); if(ib == GL_FALSE) return "compile shader failed"; return nullptr; } void GLShError::reset() const {} const char* GLShError::getAPIName() const { return "OpenGL(GLSL shader)"; } // ------------------------- GLE_Error ------------------------- const char* GLE_Error::GetErrorName() { return "OpenGL Error"; } // ------------------------- GLE_ShProgBase ------------------------- GLE_ShProgBase::GLE_ShProgBase(const GLGetIV& ivF, const GLInfoFunc& infoF, const std::string& aux, const GLuint id): GLE_Error(""), _ivF(ivF), _infoF(infoF), _id(id) { int logSize, length; ivF(id, GL_INFO_LOG_LENGTH, &logSize); std::string ret; ret.resize(logSize); infoF(id, logSize, &length, &ret[0]); (GLE_Error&)*this = GLE_Error(aux + ":\n" + std::move(ret)); } // ------------------------- GLE_ShaderError ------------------------- const char* GLE_ShaderError::GetErrorName() { return "compile shader failed"; } GLE_ShaderError::GLE_ShaderError(const std::string& src, const GLuint id): GLE_ShProgBase( [&](auto&&... arg){ return GL.glGetShaderiv(std::forward<decltype(arg)>(arg)...); }, [&](auto&&... arg){ return GL.glGetShaderInfoLog(std::forward<decltype(arg)>(arg)...); }, AddLineNumber(src, 1, 1, true, true) + GetErrorName(), id ) {} // ------------------------- GLE_ProgramError ------------------------- const char* GLE_ProgramError::GetErrorName() { return "link program failed"; } GLE_ProgramError::GLE_ProgramError(const GLuint id): GLE_ShProgBase( [&](auto&&... arg){ return GL.glGetProgramiv(std::forward<decltype(arg)>(arg)...); }, [&](auto&&... arg){ return GL.glGetProgramInfoLog(std::forward<decltype(arg)>(arg)...); }, GetErrorName(), id ) {} // ------------------------- GLE_ParamNotFound ------------------------- const char* GLE_ParamNotFound::GetErrorName() { return "parameter not found"; } GLE_ParamNotFound::GLE_ParamNotFound(const std::string& name): GLE_Error(std::string(GetErrorName()) + '\n' + name), _name(name) {} // ------------------------- GLE_InvalidArgument ------------------------- const char* GLE_InvalidArgument::GetErrorName() { return "invalid argument"; } GLE_InvalidArgument::GLE_InvalidArgument(const std::string& shname, const std::string& argname): GLE_Error(std::string(GetErrorName()) + shname + ":\n" + argname), _shName(shname), _argName(argname) {} // ------------------------- GLE_LogicalError ------------------------- const char* GLE_LogicalError::GetErrorName() { return "logical error"; } }
true
f7548ece0c55624fc76198c8b3643846fca9e971
C++
Svilen-Stefanov/Practicle-course-Image-reconstruction-and-visualisation
/part2-team1/test/AcquisitionTests.cpp
UTF-8
6,722
2.609375
3
[]
no_license
#include "catch.hpp" #include "TestUtils.h" #include <string> #include <iostream> #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> #include <math/Volume.h> #include <io/EDFhandler.h> #include <math/Detector.h> #include <math/Raytracer.h> using namespace std; using namespace Eigen; const string EDF_FILE = "resources/lshape.edf"; TEST_CASE("loader", "[acquisition]") { Volume_ptr vol = EDFHandler::read(EDF_FILE); REQUIRE(vol->getNumVoxels() == Eigen::Vector3i(10, 10, 10)); REQUIRE(vol->getSpacing().isApprox(Eigen::Vector3f(0.015, 0.015, 0.025))); REQUIRE(vol->getBoundingBox().min() == Eigen::Vector3f(0, 0, 0)); REQUIRE(vol->getBoundingBox().max().isApprox(Eigen::Vector3f(0.15, 0.15, 0.25))); for (int x = 0; x < 10; ++x) { for (int y = 0; y < 10; ++y) { for (int z = 0; z < 10; ++z) { //value can be accessed REQUIRE_NOTHROW(vol->getVoxel(x, y, z)); } } } } void testDetector(Detector detector) { Quaternionf rot = detector.getRotation(); Vector3f source = rot._transformVector(Vector3f(-detector.getDistance(), 0, 0)) + detector.getCenter(); Vector3f target = rot._transformVector(Vector3f(+detector.getDistance(), 0, 0)) + detector.getCenter(); Hyperplane<float, 3> plane((target - source).normalized(), target); INFO("Detector: source=(" << source.x() << "," << source.y() << "," << source.z() << "), target=(" << target.x() << "," << target.y() << "," << target.z() << "), rotation=(" << rot.w() << "," << rot.x() << "," << rot.y() << "," << rot.z() << ")"); { INFO("Resolution: 1x1"); detector.setResolution(Vector2i(1, 1)); auto rays = detector.computeRays(); REQUIRE(rays.size() == 1); REQUIRE(rays[0].distance(source) == Approx(0.0)); REQUIRE(rays[0].distance(target) == Approx(0.0)); REQUIRE(rays[0].intersection(plane) == Approx(0.0)); } { INFO("Resolution: 5x5"); detector.setResolution(Vector2i(5, 5)); auto rays = detector.computeRays(); REQUIRE(rays.size() == 5 * 5); for (int i = 0; i < 25; ++i) { INFO("ray " << i << ", dir=(" << rays[i].direction().x() << "," << rays[i].direction().y() << "," << rays[i].direction().z() << ")"); REQUIRE(rays[i].distance(source) == Approx(0.0).epsilon(0.001)); REQUIRE(rays[i].intersection(plane) == Approx(0.0).epsilon(0.001)); } REQUIRE(rays[12].distance(target) == Approx(0.0).epsilon(0.001)); } { INFO("Resolution: 8x8"); detector.setResolution(Vector2i(8, 8)); auto rays = detector.computeRays(); REQUIRE(rays.size() == 64); for (int i = 0; i < 64; ++i) { INFO("ray " << i << ", dir=(" << rays[i].direction().x() << "," << rays[i].direction().y() << "," << rays[i].direction().z() << ")"); REQUIRE(rays[i].distance(source) == Approx(0.0).epsilon(0.001)); REQUIRE(rays[i].intersection(plane) == Approx(0.0).epsilon(0.001)); REQUIRE_FALSE(rays[i].distance(target) == Approx(0.0)); } } } TEST_CASE("detector", "[acquisition][!hide]") //TEST_CASE("detector", "[acquisition]") { RandomUtils rand; for (int i = 0; i < 50; ++i) { Detector detector; detector.setCenter(Vector3f(rand.nextFloat(-50, 50), rand.nextFloat(-50, 50), rand.nextFloat(-50, 50))); detector.setDistance(rand.nextFloat(0.01, 2)); float s = rand.nextFloat(0.001, 0.5); detector.setSize(Vector2f(s, s)); detector.setRotation(rand.nextRandomRotation<float>()); testDetector(detector); } } TEST_CASE("raytracer-utilities", "[acquisition]") { REQUIRE(Raytracer::clamp(1.5, 1.0, 7.0) == 1.5); REQUIRE(Raytracer::clamp(0.5, 1.3, 7.0) == 1.3); REQUIRE(Raytracer::clamp(12.5, -0.7, 4.6) == 4.6); REQUIRE(Raytracer::frac(0) == Approx(0)); REQUIRE(Raytracer::frac(1) == Approx(0)); REQUIRE(Raytracer::frac(2) == Approx(0)); REQUIRE(Raytracer::frac(-1) == Approx(0)); REQUIRE(Raytracer::frac(0.5) == Approx(0.5)); REQUIRE(Raytracer::frac(42.5) == Approx(0.5)); REQUIRE(Raytracer::frac(1.7) == Approx(0.7)); REQUIRE(Raytracer::frac(-0.5) == Approx(0.5)); REQUIRE(Raytracer::frac(-0.7) == Approx(0.3)); REQUIRE(Raytracer::frac(-1.2) == Approx(0.8)); } float callVoxelTraversal(Volume_ptr vol, const Detector::Ray_t& ray, float start, float end) { Raytracer t(vol, ray); t.setupTraversal(ray, start, end); return t.voxelTraversal(vol->getContent()); } TEST_CASE("raytracer-voxel", "[acquisition]") { //create volume Vector3f min(-0.2, -0.3, -0.2); Vector3f max(0.2, 0.3, 0.2); Vector3i resolution(2, 2, 2); Vector3f sp(0.2, 0.3, 0.2); //(max-min)/resolution Volume_ptr vol = make_shared<Volume>(min, max, sp, resolution); //fill with powers of two VectorXf content(8); for (int i = 0; i < 8; ++i) content[i] = 1 << i; vol->setContent(content); //straight lines REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.1, -1.3, -0.1), Vector3f(0, 1, 0)), 1, 1.6) == Approx(5)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(0.06, -1.3, -0.1), Vector3f(0, 1, 0)), 1, 1.6) == Approx(10)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.1, 1.5, -0.1), Vector3f(0, -1, 0)), 1.2, 1.8) == Approx(5)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(0.06, 1.5, -0.1), Vector3f(0, -1, 0)), 1.2, 1.8) == Approx(10)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.1, -1.3, 0.13), Vector3f(0, 1, 0)), 1, 1.6) == Approx(80)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(0.06, -1.3, 0.03), Vector3f(0, 1, 0)), 1, 1.6) == Approx(160)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.1, 1.5, 0.07), Vector3f(0, -1, 0)), 1.2, 1.8) == Approx(80)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(0.06, 1.5, 0.09), Vector3f(0, -1, 0)), 1.2, 1.8) == Approx(160)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.5, -0.16, -0.1), Vector3f(1, 0, 0)), 0.3, 0.7) == Approx(3)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.5, 0.03, -0.1), Vector3f(1, 0, 0)), 0.3, 0.7) == Approx(12)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.5, -0.16, -0.1), Vector3f(1, 0, 0)), 0.3, 0.7) == Approx(3)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.5, 0.03, -0.1), Vector3f(1, 0, 0)), 0.3, 0.7) == Approx(12)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.06, -0.16, -0.8), Vector3f(0, 0, 1)), 0.6, 1.0) == Approx(17)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.06, 0.09, -0.8), Vector3f(0, 0, 1)), 0.6, 1.0) == Approx(68)); //diagonal line REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(-0.25, -0.3, -0.1), Vector3f(1, 1, 0).normalized()), 0.05*sqrt(2), 0.45*sqrt(2)) == Approx(11)); REQUIRE(callVoxelTraversal(vol, Detector::Ray_t(Vector3f(0.24888, 0.3, 0.1), Vector3f(-1, -1, -0.00001).normalized()), 0.05*sqrt(2), 0.45*sqrt(2)) == Approx(16+64+128)); }
true
ca688e471a8effb664eb7a822e5ba3c04487fe65
C++
LionZWY/vambush
/HEW_version1/effect.cpp
SHIFT_JIS
11,608
2.546875
3
[]
no_license
//============================================================================= // // GtFNg [effect.cpp] // Author : 镶 // vO쐬 : 2018/3/09 //============================================================================= #include "effect.h" #include "input.h" #include "camera.h" //***************************************************************************** // }N` //***************************************************************************** #define TEXTURE_EFFECT "data/TEXTURE/shadow000.jpg" // ǂݍރeNX`t@C #define EFFECT_SIZE_X (10.0f) // r{[h̕ #define EFFECT_SIZE_Y (10.0f) // r{[h̍ #define VALUE_MOVE_BULLET (2.0f) // ړx #define MAX_EFFECT (4096) // GtFNgő吔 //***************************************************************************** // vg^Cv錾 //***************************************************************************** HRESULT MakeVertexEffect(LPDIRECT3DDEVICE9 pDevice); void SetVertexEffect(int nIdxEffect, D3DXVECTOR2 size); void SetColorEffect(int nIdxEffect, D3DXCOLOR col); //***************************************************************************** // O[oϐ //***************************************************************************** LPDIRECT3DTEXTURE9 g_pD3DTextureEffect = NULL; // eNX`ւ̃|C^ LPDIRECT3DVERTEXBUFFER9 g_pD3DVtxBuffEffect = NULL; // _obt@C^[tF[Xւ̃|C^ EFFECT effectWk[MAX_EFFECT]; // e[N //============================================================================= // //============================================================================= HRESULT InitEffect(void) { LPDIRECT3DDEVICE9 pDevice = GetDevice(); EFFECT *effect = effectWk; // _̍쐬 MakeVertexEffect(pDevice); // eNX`̓ǂݍ D3DXCreateTextureFromFile(pDevice, // foCXւ̃|C^ TEXTURE_EFFECT, // t@C̖O &g_pD3DTextureEffect); // ǂݍރ[ for(int i = 0; i < MAX_EFFECT; i++, effect++) { effect->pos = D3DXVECTOR3(0.0f, 0.0f, 0.0f); effect->rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f); effect->scl = D3DXVECTOR3(1.0f, 1.0f, 1.0f); effect->move = D3DXVECTOR3(1.0f, 1.0f, 1.0f); effect->size.x = EFFECT_SIZE_X; effect->size.y = EFFECT_SIZE_Y; effect->timer = 0; effect->bUse = false; } return S_OK; } //============================================================================= // I //============================================================================= void UninitEffect(void) { if(g_pD3DTextureEffect != NULL) {// eNX`̊J g_pD3DTextureEffect->Release(); g_pD3DTextureEffect = NULL; } if(g_pD3DVtxBuffEffect != NULL) {// _obt@̊J g_pD3DVtxBuffEffect->Release(); g_pD3DVtxBuffEffect = NULL; } } //============================================================================= // XV //============================================================================= void UpdateEffect(void) { D3DXVECTOR3 rotCamera; EFFECT *effect = effectWk; // J̉]擾 rotCamera = GetRotCamera(); for(int i = 0; i < MAX_EFFECT; i++, effect++) { if(effect->bUse) { effect->pos.x += effect->move.x; effect->pos.z += effect->move.z; effect->col.a -= effect->nDecAlpha; if(effect->col.a <= 0.0f) { effect->col.a = 0.0f; } SetColorEffect(i, D3DXCOLOR(effect->col.r,effect->col.b, effect->col.b, effect->col.a)); effect->timer--; if(effect->timer <= 0) { effect->bUse = false; } } } } //============================================================================= // `揈 //============================================================================= void DrawEffect(void) { LPDIRECT3DDEVICE9 pDevice = GetDevice(); D3DXMATRIX mtxView,mtxscl,mtxTranslate; EFFECT *effect = effectWk; pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); // \[XJ[̎w pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); // fXeBl[VJ[̎w pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS); // ZrȂ // pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); // At@ufBO // pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); // ŏ̃At@ // pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT); // QԖڂ̃At@ for(int i = 0; i < MAX_EFFECT; i++, effect++) { if(effect->bUse) { // [h}gbNX̏ D3DXMatrixIdentity(&effect->world); // r[}gbNX擾 mtxView = GetMtxView(); effect->world._11 = mtxView._11; effect->world._12 = mtxView._21; effect->world._13 = mtxView._31; effect->world._21 = mtxView._12; effect->world._22 = mtxView._22; effect->world._23 = mtxView._32; effect->world._31 = mtxView._13; effect->world._32 = mtxView._23; effect->world._33 = mtxView._33; // XP[𔽉f D3DXMatrixScaling(&mtxscl, effect->scl.x, effect->scl.y, effect->scl.z); D3DXMatrixMultiply(&effect->world, &effect->world, &mtxscl); // ړ𔽉f D3DXMatrixTranslation(&mtxTranslate, effect->pos.x, effect->pos.y, effect->pos.z); D3DXMatrixMultiply(&effect->world, &effect->world, &mtxTranslate); // [h}gbNX̐ݒ pDevice->SetTransform(D3DTS_WORLD, &effect->world); pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); // _obt@foCX̃f[^Xg[ɃoCh pDevice->SetStreamSource(0, g_pD3DVtxBuffEffect, 0, sizeof(VERTEX_3D)); // _tH[}bg̐ݒ pDevice->SetFVF(FVF_VERTEX_3D); // eNX`̐ݒ pDevice->SetTexture(0, g_pD3DTextureEffect); // |S̕` pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, (i * 4), NUM_POLYGON); pDevice->SetRenderState(D3DRS_LIGHTING, TRUE); } } pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); // \[XJ[̎w pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); // fXeBl[VJ[̎w pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); pDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); // Zr // pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); // pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); // pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_CURRENT); } //============================================================================= // _̍쐬 //============================================================================= HRESULT MakeVertexEffect(LPDIRECT3DDEVICE9 pDevice) { // IuWFNg̒_obt@𐶐 if( FAILED( pDevice->CreateVertexBuffer(sizeof(VERTEX_3D) * NUM_VERTEX * MAX_EFFECT, // _f[^pɊmۂobt@TCY(oCgP) D3DUSAGE_WRITEONLY, // _obt@̎gp@@ FVF_VERTEX_3D, // gp钸_tH[}bg D3DPOOL_MANAGED, // \[X̃obt@ێ郁NXw &g_pD3DVtxBuffEffect, // _obt@C^[tF[Xւ̃|C^ NULL))) // NULLɐݒ { return E_FAIL; } {//_obt@̒g𖄂߂ VERTEX_3D *pVtx; // _f[^͈̔͂bNA_obt@ւ̃|C^擾 g_pD3DVtxBuffEffect->Lock(0, 0, (void**)&pVtx, 0); for(int i = 0; i < MAX_EFFECT; i++, pVtx += 4) { // _W̐ݒ pVtx[0].vtx = D3DXVECTOR3(-EFFECT_SIZE_X / 2, -EFFECT_SIZE_Y / 2, 0.0f); pVtx[1].vtx = D3DXVECTOR3(EFFECT_SIZE_X / 2, -EFFECT_SIZE_Y / 2, 0.0f); pVtx[2].vtx = D3DXVECTOR3(-EFFECT_SIZE_X / 2, EFFECT_SIZE_Y / 2, 0.0f); pVtx[3].vtx = D3DXVECTOR3(EFFECT_SIZE_X / 2, EFFECT_SIZE_Y / 2, 0.0f); // @̐ݒ pVtx[0].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f); pVtx[1].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f); pVtx[2].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f); pVtx[3].nor = D3DXVECTOR3(0.0f, 0.0f, -1.0f); // ˌ̐ݒ pVtx[0].diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[1].diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[2].diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[3].diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); // eNX`W̐ݒ pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f); pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f); pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f); pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f); } // _f[^AbN g_pD3DVtxBuffEffect->Unlock(); } return S_OK; } //============================================================================= // _W̐ݒ //============================================================================= void SetVertexEffect(int nIdxEffect, D3DXVECTOR2 size) { {//_obt@̒g𖄂߂ VERTEX_3D *pVtx; // _f[^͈̔͂bNA_obt@ւ̃|C^擾 g_pD3DVtxBuffEffect->Lock(0, 0, (void**)&pVtx, 0); pVtx += (nIdxEffect * 4); // _W̐ݒ pVtx[0].vtx = D3DXVECTOR3(-size.x / 2, -size.y / 2, 0.0f); pVtx[1].vtx = D3DXVECTOR3(-size.x / 2, size.y / 2, 0.0f); pVtx[2].vtx = D3DXVECTOR3(size.x / 2, -size.y / 2, 0.0f); pVtx[3].vtx = D3DXVECTOR3(size.x / 2, size.y / 2, 0.0f); // _f[^AbN g_pD3DVtxBuffEffect->Unlock(); } } //============================================================================= // _J[̐ݒ //============================================================================= void SetColorEffect(int nIdxEffect, D3DXCOLOR col) { {//_obt@̒g𖄂߂ VERTEX_3D *pVtx; // _f[^͈̔͂bNA_obt@ւ̃|C^擾 g_pD3DVtxBuffEffect->Lock(0, 0, (void**)&pVtx, 0); pVtx += (nIdxEffect * 4); // _W̐ݒ pVtx[0].diffuse = pVtx[1].diffuse = pVtx[2].diffuse = pVtx[3].diffuse = col; // _f[^AbN g_pD3DVtxBuffEffect->Unlock(); } } //============================================================================= // GtFNg̐ݒ //============================================================================= int SetEffect(D3DXVECTOR3 pos, D3DXVECTOR3 move, D3DXCOLOR col, D3DXVECTOR2 size, int timer) { EFFECT *effect = effectWk; int nIdxEffect = -1; for(int i = 0; i < MAX_EFFECT; i++, effect++) { if(!effect->bUse) { effect->pos = pos; effect->rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f); effect->scl = D3DXVECTOR3(1.0f, 1.0f, 1.0f); effect->move = move; effect->col = col; effect->size.x = size.x; effect->size.y = size.y; effect->timer = timer; effect->nDecAlpha = col.a / timer; effect->bUse = true; // _W̐ݒ SetVertexEffect(i, size); // _J[̐ݒ SetColorEffect(i, D3DXCOLOR(effect->col.r,effect->col.b, effect->col.b, effect->col.a)); nIdxEffect = i; break; } } return nIdxEffect; }
true
25db375be863553c2c463efd35ad7c81599a7888
C++
Teatoller/cpp_project
/tictactoe/main.cpp
UTF-8
3,057
4.4375
4
[]
no_license
/* For this programming quiz, I would like you to create a game called TicTacToe. In this version of the game you will need to: Create a 4x4 game board Prompt the first user (the 'x' user) to enter their name Prompt the second user (the 'o' user) to enter their name Prompt the 'x' user to select a grid position where they would like to place an 'x'. Prompt the 'o' user to select a grid position where they would like to place an 'o'. After each user has a turn, check for any row, column, diagonal that has 4 'x's or 4 'o's. If 4 'x's are found in the same col, row, diagonal, declare the 'x' user the winner. If 4 'o's are found in the same col, row, diagonal, declare the 'o' user the winner. End the game and declare the winner. If the grid is filled (each player gets 8 turns) and there is not a row, column, diagonal with 4 of the same symbol, the game is tied. Declare a tie game. */ /*Goal: Practice creating classes and functions. **Create a program that allows two users to **play a 4x4 tic-tac-toe game. */ #include "mainClasses.cpp" #include "mainFunctions.cpp" int main() { Board gameBoard; string nameX; string nameO; int tieGame = 0; char gameWinner = 'z'; int numTurns = 0; //get the names of the players getUserNames(nameX, nameO); //the game is played for 8 turns maximum while (numTurns < 8) { //print a board that has the postions numbered printTheBoard(gameBoard); //ask player x where they want to put an 'x' printUserPrompt(nameX, 'x'); //check that the input is a valid position and that //it has not already been taken checkResponse(gameBoard, 'x'); //check to see if player 'x' has four in a row somewhere on the board gameWinner = gameBoard.determineWinner(); //if player 'x' has won, end the game if (gameWinner != 'z') { printTheBoard(gameBoard); writeTheBoard(gameBoard); printGameWinner(gameBoard, nameX, nameO); break; } //Now do the same for player 'o' //print a board that has the postions numbered printTheBoard(gameBoard); writeTheBoard(gameBoard); //ask player x where they want to put an 'o' printUserPrompt(nameO, 'o'); //check that the input is a valid position and that //it has not already been taken checkResponse(gameBoard, 'o'); printTheBoard(gameBoard); writeTheBoard(gameBoard); //check to see if player 'o' has four in a row somewhere on the board gameWinner = gameBoard.determineWinner(); //if player 'o' has won, end the game if (gameWinner != 'z') { printTheBoard(gameBoard); writeTheBoard(gameBoard); printGameWinner(gameBoard, nameX, nameO); break; } numTurns++; } //if there is no winner at this point, the game is a tie if (numTurns >= 8) cout << "Tie game.\n\n"; return 0; }
true
27a44b23cc6a6025ed4bc5703a3adcbfe02ddcc7
C++
Artigrok/Laboratory-Works
/LW10/LW10N3/main.cpp
WINDOWS-1251
478
3.0625
3
[]
no_license
#include <iostream>; using namespace std; int main() { setlocale(LC_ALL, "ru"); int A; cout << " : "; cin >> A; if ((A % 2 == 0) and (A / 10 > 0) and (A / 10 < 10)) { cout << " "; } else { cout << " "; } }
true
89a4b71eb5f4bc4553c8f169c87f88840fcc8153
C++
abhinavrungta/databaseimpl
/project/src/QueryPlanNode.cc
UTF-8
9,903
2.796875
3
[]
no_license
#include "QueryPlanNode.h" using namespace std; map<int, Pipe*> QueryPlanNode::pipesList; vector<RelationalOp*> QueryPlanNode::relOpList; void QueryPlanNode::ExecutePostOrder() { if (this->left) this->left->ExecutePostOrder(); if (this->right) this->right->ExecutePostOrder(); this->ExecuteNode(); } void QueryPlanNode::PrintPostOrder() { if (this->left) this->left->PrintPostOrder(); if (this->right) this->right->PrintPostOrder(); this->PrintNode(); } void QueryPlanNode::CreatePipe() { pipesList[outPipeId] = new Pipe(PIPE_SIZE); } // -------------------------------------- select pipe ------------------ SelectPipeQPNode::SelectPipeQPNode() { } SelectPipeQPNode::SelectPipeQPNode(int in, int out, CNF* pCNF, Record * pLit, Schema * pSch) { leftInPipeId = in; outPipeId = out; cnf = pCNF; literal = pLit; outputSchema = pSch; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } SelectPipeQPNode::~SelectPipeQPNode() { if (this->left) delete this->left; if (this->right) delete this->right; if (cnf != NULL) { delete cnf; cnf = NULL; } if (literal != NULL) { delete literal; literal = NULL; } } void SelectPipeQPNode::PrintNode() { cout << "\n*** Select Pipe Operation ***"; cout << "\nInput pipe ID: " << leftInPipeId; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << "\nSelect CNF : "; if (cnf != NULL) cnf->Print(); else cout << "NULL"; cout << endl << endl; } void SelectPipeQPNode::ExecuteNode() { SelectPipe *selPipe = new SelectPipe(); if (cnf != NULL && literal != NULL) { selPipe->Run(*(pipesList[leftInPipeId]), *(pipesList[outPipeId]), *cnf, *literal); relOpList.push_back(selPipe); } } // -------------------------------------- select file ------------------ SelectFileQPNode::SelectFileQPNode() { } SelectFileQPNode::SelectFileQPNode(string inFile, int out, CNF* pCNF, Record * pLit, Schema *pScH) { sFileName = inFile; outPipeId = out; cnf = pCNF; literal = pLit; outputSchema = pScH; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } SelectFileQPNode::~SelectFileQPNode() { if (this->left != NULL) delete this->left; if (this->right != NULL) delete this->right; if (cnf != NULL) { delete cnf; cnf = NULL; } if (literal != NULL) { delete literal; literal = NULL; } } void SelectFileQPNode::PrintNode() { cout << "\n*** Select File Operation ***"; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nInput filename: " << sFileName.c_str(); cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << "\nSelect CNF : "; if (cnf != NULL) cnf->Print(); else cout << "NULL"; cout << endl << endl; } void SelectFileQPNode::ExecuteNode() { //create a DBFile from input file path provided DBFile * pFile = new DBFile; pFile->Open(const_cast<char*>(sFileName.c_str())); SelectFile * pSF = new SelectFile(); if (cnf != NULL && literal != NULL) { pSF->Run(*pFile, *(pipesList[outPipeId]), *cnf, *literal); relOpList.push_back(pSF); } } // -------------------------------------- project ------------------ ProjectQPNode::ProjectQPNode() { } ProjectQPNode::ProjectQPNode(int ip, int op, int *atk, int nKeep, int nTot, Schema * pSch) { leftInPipeId = ip; outPipeId = op; attributeList = atk; iAtttributesToKeep = nKeep; iTotalAttributes = nTot; outputSchema = pSch; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } ProjectQPNode::~ProjectQPNode() { if (this->left) delete this->left; if (this->right) delete this->right; if (attributeList) { delete[] attributeList; attributeList = NULL; } } void ProjectQPNode::PrintNode() { cout << "\n*** Project Node Operation ***"; cout << "\nInput pipe ID: " << leftInPipeId; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nNum atts to Keep: " << iAtttributesToKeep; cout << "\nNum total atts: " << iTotalAttributes; if (attributeList != NULL) { cout << "\nAttributes to keep: "; for (int i = 0; i < iAtttributesToKeep; i++) cout << attributeList[i] << " "; } cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << endl << endl; } void ProjectQPNode::ExecuteNode() { Project *P = new Project(); if (attributeList != NULL) { P->Run(*(pipesList[leftInPipeId]), *(pipesList[outPipeId]), attributeList, iTotalAttributes, iAtttributesToKeep); relOpList.push_back(P); } } // -------------------------------------- join ------------------ JoinQPNode::JoinQPNode() { } JoinQPNode::JoinQPNode(int ip1, int ip2, int op, CNF* pCNF, Schema * pSch, Record * pLit) { leftInPipeId = ip1; rightInPipeId = ip2; outPipeId = op; cnf = pCNF; outputSchema = pSch; literal = pLit; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } JoinQPNode::~JoinQPNode() { } void JoinQPNode::PrintNode() { cout << "\n*** Join Operation ***"; cout << "\nInput pipe-1 ID: " << leftInPipeId; cout << "\nInput pipe-2 ID: " << rightInPipeId; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << "\nSelect CNF : "; if (cnf != NULL) cnf->Print(); else cout << "NULL"; cout << endl << endl; } void JoinQPNode::ExecuteNode() { Join *J = new Join(); J->Use_n_Pages(USE_PAGES); if (cnf != NULL && literal != NULL) { J->Run(*(pipesList[leftInPipeId]), *(pipesList[rightInPipeId]), *(pipesList[outPipeId]), *cnf, *literal); relOpList.push_back(J); } } // -------------------------------------- group by ------------------ GroupByQPNode::GroupByQPNode() { } GroupByQPNode::GroupByQPNode(int ip, int op, Function *pF, OrderMaker *pOM, Schema *pSch) { leftInPipeId = ip; outPipeId = op; func = pF; orderMaker = pOM; outputSchema = pSch; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } GroupByQPNode::~GroupByQPNode() { if (this->left) delete this->left; if (this->right) delete this->right; if (func) { delete func; func = NULL; } if (orderMaker) { delete orderMaker; orderMaker = NULL; } } void GroupByQPNode::PrintNode() { cout << "\n*** Group-by Operation ***"; cout << "\nInput pipe ID: " << leftInPipeId; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nFunction: "; if (func) func->Print(); else cout << "NULL\n"; cout << "\nOrderMaker:\n"; if (orderMaker) orderMaker->Print(); else cout << "NULL\n"; cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << endl << endl; } void GroupByQPNode::ExecuteNode() { GroupBy *G = new GroupBy(); if (func != NULL && orderMaker != NULL) { G->Run(*(pipesList[leftInPipeId]), *(pipesList[outPipeId]), *orderMaker, *func); relOpList.push_back(G); } } // -------------------------------------- sum ------------------ SumQPNode::SumQPNode() { } SumQPNode::SumQPNode(int ip, int op, Function *pF, bool bPrint, Schema *pSch) { leftInPipeId = ip; outPipeId = op; func = pF; outputSchema = pSch; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } SumQPNode::~SumQPNode() { if (this->left) delete this->left; if (this->right) delete this->right; if (func) { delete func; func = NULL; } } void SumQPNode::PrintNode() { cout << "\n*** Sum Operation ***"; cout << "\nInput pipe ID: " << leftInPipeId; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nFunction: "; func->Print(); cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << endl << endl; } void SumQPNode::ExecuteNode() { Sum *S = new Sum(); if (func != NULL) { S->Run(*(pipesList[leftInPipeId]), *(pipesList[outPipeId]), *func); relOpList.push_back(S); } } // -------------------------------------- Distinct ------------------ DistinctQPNode::DistinctQPNode() { } DistinctQPNode::DistinctQPNode(int ip, int op, Schema * pSch) { leftInPipeId = ip; outPipeId = op; outputSchema = pSch; pipesList[outPipeId] = new Pipe(PIPE_SIZE); } DistinctQPNode::~DistinctQPNode() { if (this->left) delete this->left; if (this->right) delete this->right; if (outputSchema) { delete outputSchema; outputSchema = NULL; } } void DistinctQPNode::PrintNode() { cout << "\n*** Distinct Operation ***"; cout << "\nInput pipe ID: " << leftInPipeId; cout << "\nOutput pipe ID: " << outPipeId; cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << endl << endl; } void DistinctQPNode::ExecuteNode() { DuplicateRemoval *DR = new DuplicateRemoval(); if (outputSchema != NULL) { DR->Run(*(pipesList[leftInPipeId]), *(pipesList[outPipeId]), *outputSchema); relOpList.push_back(DR); } } // -------------------------------------- write out ------------------ WriteOutQPNode::WriteOutQPNode() { } WriteOutQPNode::WriteOutQPNode(int ip, string outFile, Schema * pSch) { leftInPipeId = ip; outFileName = outFile; outputSchema = pSch; } WriteOutQPNode::~WriteOutQPNode() { if (this->left) delete this->left; if (this->right) delete this->right; if (outputSchema) { delete outputSchema; outputSchema = NULL; } } void WriteOutQPNode::PrintNode() { cout << "\n*** WriteOut Operation ***"; cout << "\nInput pipe ID: " << leftInPipeId; cout << "\nOutput file: " << outFileName; cout << "\nOutput Schema: "; if (outputSchema != NULL) outputSchema->Print(); else cout << "NULL"; cout << endl << endl; } void WriteOutQPNode::ExecuteNode() { WriteOut *W = new WriteOut(); if (outputSchema != NULL && !outFileName.empty()) { FILE * pFILE; if (strcmp(outFileName.c_str(), "STDOUT") == 0) { pFILE = stdout; } else { pFILE = fopen((char*) outFileName.c_str(), "w"); } W->Run(*(pipesList[leftInPipeId]), pFILE, *outputSchema); relOpList.push_back(W); } }
true
22abf8fce1ff90b35c86564e2abf5f9e74bcd54a
C++
chernant/polkadot_api_cpp
/test/query_storage.cpp
UTF-8
1,893
2.75
3
[ "Apache-2.0" ]
permissive
#include "../src/polkadot.h" #include "helpers/cli.h" #undef NDEBUG #include <cassert> #include <set> int main(int argc, char *argv[]) { auto app = polkadot::api::getInstance()->app(); app->connect(getNodeUrlParam(argc, argv)); // Get the most recent block number and hash auto lastblock = app->getBlock(nullptr); unique_ptr<GetBlockHashParams> prm(new GetBlockHashParams); long lastNumber = lastblock->block.header.number; prm->blockNumber = lastNumber; auto lastHash = app->getBlockHash(move(prm)); // Get the 10 blocks back number and hash unique_ptr<GetBlockHashParams> prm2(new GetBlockHashParams); prm2->blockNumber = lastNumber - 10; auto tenBackHash = app->getBlockHash(move(prm2)); cout << endl << "Most recent block : " << lastNumber << ", hash: " << lastHash->hash << endl; cout << "10 blocks back block : " << lastNumber - 10 << ", hash: " << tenBackHash->hash << endl << endl; // Get timestamp history for last 50 blocks string module = "Timestamp"; string variable = "Now"; string key = app->getKeys("", module, variable); StorageItem itemBuf[20] = {0}; int itemCount = app->queryStorage(key, tenBackHash->hash, lastHash->hash, itemBuf, 20); // Assert that item count is at least 10 cout << endl << "Item count returned: " << itemCount << endl; assert(itemCount >= 10); cout << "Item count is OK" << endl << endl; // Assert that all items are different (time changes every block) set<string> values; for (int i = 0; i < itemCount; ++i) { cout << "Block: " << itemBuf[i].blockHash << ", value: " << itemBuf[i].value << endl; values.insert(itemBuf[i].value); } assert(values.size() == itemCount); cout << endl << "All timestamps are different" << endl << endl; app->disconnect(); cout << "success" << endl; return 0; }
true
538d41ce01a34c0d8b06d4f1f88a1780cd2c5738
C++
hoangvanthien/codeForest
/UVa/10806.cpp
UTF-8
2,041
2.53125
3
[]
no_license
/* github.com/hoangvanthien Thien Van Hoang UVA 10806 - "Dijkstra, Dijkstra" */ #include <bits/stdc++.h> using namespace std; #define FOR(i,x,y) for(int i = (x); i<(y); ++i) #define DFOR(i,x,y) for(int i = (x); i>(y); --i) #define maxN 1002 #define pb push_back #define mp make_pair #define F first #define S second #define oo 1e9+7 #define II pair<int,int> #define LL long long int n,m,d[maxN],trace[maxN],c[maxN][maxN],weight; vector<int> dsk[maxN]; set<II> S; void dijkstra(const int time) { d[1] = 0; trace[1] = n+1; S.insert(mp(d[1], 1)); while (!S.empty()) { II top = *(S.begin()); S.erase(top); int u = top.S; FOR(i,0,dsk[u].size()) { int v = dsk[u][i], w = c[u][v]; if (d[v] > d[u] + w) { trace[v] = u; S.erase(mp(d[v],v)); d[v] = d[u] + w; S.insert(mp(d[v],v)); } } } if (d[n] == oo) printf("Back to jail\n"); else { weight += d[n]; if (time == 2) { printf("%d\n", weight); return; } S.clear(); FOR(i,1,n+1) d[i] = oo; int u = n; while (u!=1) { c[u][trace[u]] = c[trace[u]][u] = oo; u = trace[u]; } dijkstra(2); } } void init() { #ifndef ONLINE_JUDGE freopen("input.inp", "r", stdin); #endif // ONLINE_JUDGE while (true) { scanf("%d", &n); if (n==0) break; FOR(i,1,n+1) { dsk[i].clear(); FOR(j,1,n+1) if (i!=j) c[i][j] = oo; } scanf("%d", &m); FOR(i,0,m) { int u,v,_c; scanf("%d%d%d", &u, &v, &_c); dsk[u].pb(v); dsk[v].pb(u); c[u][v] = c[v][u] = _c; } S.clear(); FOR(i,1,n+1) d[i] = oo; weight = 0; dijkstra(1); } } void print() { } int main() { init(); }
true
19cb307a31c2efb4108204e0353d49fb7206f415
C++
royelee/leetcode
/XProject/Level10.cpp
UTF-8
12,602
3.4375
3
[]
no_license
// // Level10.cpp // XProject // // Created by Roye Li on 1/6/16. // Copyright (c) 2016 Roye Li. All rights reserved. // #include "Level.h" #include "Utils.h" #include <algorithm> #include <iostream> #include <sstream> #include <vector> #include <map> #include <numeric> #include <set> #include <cmath> #include <stack> using namespace std; //Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). // //For example: //Given binary tree {3,9,20,#,#,15,7}, //3 /// \ //9 20 /// \ //15 7 //return its level order traversal as: //[ // [3], // [9,20], // [15,7] // ] vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> output; if( !root ) return output; unique_ptr< vector<TreeNode*> > levelNodes( new vector<TreeNode*>() ); levelNodes->push_back(root); while( !levelNodes->empty() ) { unique_ptr< vector<TreeNode*> > newNodes( new vector<TreeNode*>() ); vector<int> currentLevelValues; for( TreeNode* node : *levelNodes ) { if( node ) { currentLevelValues.push_back(node->val); if( node->left ) newNodes->push_back(node->left); if( node->right ) newNodes->push_back(node->right); } } output.push_back( currentLevelValues ); swap( levelNodes, newNodes ); } return output; } #pragma mark - zigzagLevelOrder //Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). // //For example: //Given binary tree {3,9,20,#,#,15,7}, //3 /// \ //9 20 /// \ //15 7 //return its zigzag level order traversal as: //[ // [3], // [20,9], // [15,7] // ] vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> output; if( !root ) return output; bool left = true; unique_ptr< vector<TreeNode*> > levelNodes( new vector<TreeNode*>() ); levelNodes->push_back(root); while( !levelNodes->empty() ) { unique_ptr< vector<TreeNode*> > newNodes( new vector<TreeNode*>() ); vector<int> currentLevelValues; for( TreeNode* node : *levelNodes ) { if( node ) { if( left ) currentLevelValues.push_back(node->val); else currentLevelValues.insert(currentLevelValues.begin(), node->val); if( node->left ) newNodes->push_back(node->left); if( node->right ) newNodes->push_back(node->right); } } left = !left; output.push_back( currentLevelValues ); swap( levelNodes, newNodes ); } return output; } #pragma mark - maxDepth //Given a binary tree, find its maximum depth. // //The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. void _maxDepth( TreeNode* node, int& maxLevel, int currentLevel ) { if( node ) { currentLevel = currentLevel + 1; maxLevel = max(currentLevel, maxLevel); _maxDepth( node->left, maxLevel, currentLevel ); _maxDepth( node->right, maxLevel, currentLevel ); } } int maxDepth(TreeNode* root) { int maxLevel = 0; _maxDepth( root, maxLevel, 0 ); return maxLevel; } #pragma mark - buildTree void _buildTree(TreeNode*& node, vector<int>& preorder, vector<int>& inorder, size_t preOrderStart, size_t inOrderStart, int length ) { if( length > 0) { // Has element we want. int value = preorder[preOrderStart]; size_t inOrderMidIndex = inOrderStart; for( size_t i = inOrderStart; i < inOrderStart + length; i++ ) { if( inorder[i] == value ) { inOrderMidIndex = i; break; } } node = new TreeNode( value ); int leftLength = inOrderMidIndex - inOrderStart; _buildTree( node->left, preorder, inorder, preOrderStart + 1, inOrderStart, leftLength ); int rightLength = length - leftLength - 1; _buildTree( node->right, preorder, inorder, preOrderStart + leftLength + 1, inOrderMidIndex + 1, rightLength ); } } //Given preorder and inorder traversal of a tree, construct the binary tree. //Note: //You may assume that duplicates do not exist in the tree. // TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { if( preorder.size() == 0 || preorder.size() != inorder.size() ) { return nullptr; } TreeNode* root = nullptr; _buildTree( root, preorder, inorder, 0, 0, preorder.size() ); return root; } void preOrderTrasveral( TreeNode* node ) { if( node ) { cout << node->val << " "; preOrderTrasveral(node->left); preOrderTrasveral(node->right); } } void inOrderTrasveral( TreeNode* node ) { if( node ) { inOrderTrasveral(node->left); cout << node->val << " "; inOrderTrasveral(node->right); } } void postOrderTrasveral( TreeNode* node ) { if( node ) { postOrderTrasveral(node->left); postOrderTrasveral(node->right); cout << node->val << " "; } } void testBuildTree() { vector<int> preorder = { 1, 2, 3, 4, 5, 6, 7 }; vector<int> inorder = { 3, 2, 4, 1, 6, 5, 7 }; TreeNode* root = buildTree( preorder, inorder ); cout << "pre order :"; preOrderTrasveral(root); cout << endl; cout << "in order :"; inOrderTrasveral(root); cout << endl; cout << "post order :"; postOrderTrasveral(root); cout << endl; } #pragma mark - build tree 2 //Given inorder and postorder traversal of a tree, construct the binary tree. // //Note: //You may assume that duplicates do not exist in the tree. void _buildTree2(TreeNode*& node, vector<int>& inorder, vector<int>& postorder, size_t postOrderStart, size_t inOrderStart, int length ) { if( length > 0) { // Has element we want. int value = postorder[postOrderStart + length - 1]; size_t inOrderMidIndex = inOrderStart; for( size_t i = inOrderStart; i < inOrderStart + length; i++ ) { if( inorder[i] == value ) { inOrderMidIndex = i; break; } } node = new TreeNode( value ); int leftLength = inOrderMidIndex - inOrderStart; _buildTree2( node->left, inorder, postorder, postOrderStart, inOrderStart, leftLength ); int rightLength = length - leftLength - 1; _buildTree2( node->right, inorder, postorder, postOrderStart + leftLength, inOrderMidIndex + 1, rightLength ); } } TreeNode* buildTree2(vector<int>& inorder, vector<int>& postorder) { if( inorder.size() == 0 || postorder.size() != inorder.size() ) { return nullptr; } TreeNode* root = nullptr; _buildTree2( root, inorder, postorder, 0, 0, inorder.size() ); return root; } void testBuildTree2() { vector<int> postOrder = { 3, 4, 2, 6, 7, 5, 1 }; vector<int> inorder = { 3, 2, 4, 1, 6, 5, 7 }; TreeNode* root = buildTree2( inorder, postOrder ); cout << "post order :"; postOrderTrasveral(root); cout << endl; cout << "in order :"; inOrderTrasveral(root); cout << endl; } #pragma mark - levelOrderBottom //Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). // //For example: //Given binary tree {3,9,20,#,#,15,7}, //3 /// \ //9 20 /// \ //15 7 //return its bottom-up level order traversal as: //[ // [15,7], // [9,20], // [3] // ] vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> output; if( root == nullptr ) return output; vector<TreeNode*> levelNodes; levelNodes.push_back( root ); while (!levelNodes.empty()) { vector<TreeNode*> nexts; vector<int> values; for( TreeNode* tmp : levelNodes ) { values.push_back(tmp->val); if( tmp->left ) nexts.push_back(tmp->left); if( tmp ->right ) nexts.push_back(tmp->right); } levelNodes.clear(); levelNodes.insert(levelNodes.begin(), nexts.begin(), nexts.end()); output.insert(output.begin(), values); } return output; } #pragma mark - sortedArrayToBST void _sortedArrayToBST(vector<int>& nums, TreeNode*& node, int start, int end) { if( end >= start ) { int mid = (start + end ) / 2; node = new TreeNode( nums[mid] ); _sortedArrayToBST( nums, node->left, start, mid - 1 ); _sortedArrayToBST( nums, node->right, mid + 1, end ); } } //Given an array where elements are sorted in ascending order, convert it to a height balanced BST. TreeNode* sortedArrayToBST(vector<int>& nums) { TreeNode* root = nullptr; _sortedArrayToBST(nums, root, 0, nums.size() - 1); return root; } void testSortedArrayToBST() { vector<int> v = {1,2,3,4,5}; TreeNode* root = sortedArrayToBST(v); inOrderTrasveral(root); v = {}; root = sortedArrayToBST(v); inOrderTrasveral(root); v = {1}; root = sortedArrayToBST(v); inOrderTrasveral(root); v = {1,2}; root = sortedArrayToBST(v); inOrderTrasveral(root); } #pragma mark - sortedListToBST TreeNode* _sortedListToBST( ListNode*& node, int start, int end ) { if( start > end ) return nullptr; int mid = ( start + end ) / 2; TreeNode* left = _sortedListToBST( node, start, mid - 1 ); TreeNode* parent = new TreeNode( node->val ); parent->left = left; node = node->next; parent->right = _sortedListToBST( node, mid + 1, end ); return parent; } //Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. TreeNode* sortedListToBST(ListNode* head) { // http://articles.leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html // http://bangbingsyb.blogspot.com/2014/11/leetcode-convert-sorted-list-to-binary.html int size = 0; ListNode* it = head; while( it ) { it = it->next; size++; } return _sortedListToBST( head, 0, size - 1 ); } void testSortedListToBST() { ListNode* head = new ListNode(-1); ListNode* node = head; vector<int> v = {1, 3}; for( auto& i : v ) { node->next = new ListNode( i ); node = node->next; } sortedListToBST( head->next ); } #pragma mark - isBalanced //Given a binary tree, determine if it is height-balanced. // //For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. // bool _isBalanced( TreeNode* node, int& height ) { if( node == nullptr ) return true; height = height + 1; int leftHeight = height; bool isLeftB = _isBalanced( node->left, leftHeight ); int rightHeight = height; bool isRightB = _isBalanced( node->right, rightHeight ); if( !isLeftB || !isRightB || abs( leftHeight - rightHeight ) > 1 ) return false; height = max( leftHeight, rightHeight ); return true; } bool isBalanced(TreeNode* root) { int height = 0; return _isBalanced( root, height); } void testInBalanced() { // [1,null,2,null,3] TreeNode* root = new TreeNode(1); root->right = new TreeNode(2); root->right->right = new TreeNode(3); cout << isBalanced( root ); } #pragma mark - minDepth( void _minDepth( TreeNode* node, int height, int& minHeight ) { if( node == nullptr ) return; if( node->left == nullptr && node->right == nullptr ) { minHeight = min( minHeight, height ); } _minDepth(node->left, height + 1, minHeight); _minDepth(node->right, height + 1, minHeight); } int minDepth(TreeNode* root) { if( root == nullptr ) return 0; int minHeight = numeric_limits<int>::max(); _minDepth(root, 1, minHeight); return minHeight; } #pragma mark - run void Level10::Run() { testInBalanced(); }
true
fe439f1cdff46da43f703e2f2db6238d99f8f0f8
C++
wangfuli217/ld_note
/cheatsheet/ops_doc-master/Service/misc/test_api/src/test_stream/test_read_file_size.cpp
WINDOWS-1252
448
3.015625
3
[]
no_license
// obtaining file size #include <iostream> #include <fstream> #include <stdlib.h> using namespace std; const char * filename = "test.txt"; int main() { long l, m; ifstream in(filename, ios::in | ios::binary); l = in.tellg(); in.seekg(0, ios::end); m = in.tellg(); in.close(); cout << "size of " << filename; cout << " is " << (m - l) << " bytes.\n"; return 0; } //: //size of example.txt is 40 bytes.
true
267b146d37ff74f82e4bb7932357cd1e41bdc84d
C++
dhananjay1438/Data-Structures-and-Algorithms
/trees/expression-tree/expression_tree.cpp
UTF-8
478
3.46875
3
[]
no_license
#include <iostream> class Node { Node *left; int data; Node *right; }; class ExpressionTree { private: Node *root; void _insert(); public: ExpressionTree(); void insert(std::string); int solve(); }; ExpressionTree::ExpressionTree() : root(nullptr) {} void ExpressionTree::insert(std::string str) {} int main(void) { std::string str; std::cin >> str; ExpressionTree exp_tree; exp_tree.insert(str); std::cout << exp_tree.solve(); return 0; }
true
94ca9718c5afdce424ff991df1c7acdad6b17e88
C++
hardenchant/labaratornaya
/Threads/Threads/Threads.cpp
WINDOWS-1251
1,852
3.578125
4
[]
no_license
// Threads.cpp: . // #include "stdafx.h" #include <thread> #include <iostream> #include <string> #include <chrono> #include <mutex> #include <system_error> using namespace std; mutex glock; void func1(string str) { for (int j = 0; j < 100; j++) { glock.lock(); for (int i = 0; i < 4; i++) { cout << str << endl; this_thread::sleep_for(chrono::milliseconds(10)); } glock.unlock(); this_thread::sleep_for(chrono::milliseconds(10)); } } void func2(string str) { glock.lock(); for (int k = 0; k < 50; k++) { cout << str << endl; } glock.unlock(); for (int j = 0; j < 100; j++) { glock.lock(); for (int i = 0; i < 4; i++) { cout << str << endl; this_thread::sleep_for(chrono::milliseconds(10)); } glock.unlock(); this_thread::sleep_for(chrono::milliseconds(10)); } } recursive_mutex m_deadlock1; //deadlock demo mutex m_deadlock2; void deadlock1() { m_deadlock1.lock(); // try { m_deadlock1.lock(); // if m_deadlock1 - mutex is locked and get system_error } catch (const system_error &e) { cout << "Err: " << e.code() << endl; cout << "mutex -> recursive_mutex == no this error" << endl; } this_thread::sleep_for(chrono::milliseconds(10)); m_deadlock2.lock(); cout << "Never come to do 1" << endl; } void deadlock2() { m_deadlock2.lock(); this_thread::sleep_for(chrono::milliseconds(10)); m_deadlock1.lock(); cout << "Never come to do 2" << endl; } //deadlock demo int main() { //thread thr2(func2, "bbbb"); //thread thr1(func1, "a"); thread deadlock1(deadlock1); thread deadlock2(deadlock2); //thr1.join(); //thr2.join(); deadlock1.join(); //dealock thread deadlock2.join(); // string command; while (command != "end") { } return 0; }
true
f33a544a4d43df261c5f7d57f05946e31741e21d
C++
Vidminas/OpenGL-Projects
/GLEngine/shaderFactory.cpp
UTF-8
1,400
2.8125
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <GL/glew.h> #include "shader.hpp" #include "shaderFactory.hpp" ShaderFactory::ShaderFactory() { //nothing } ShaderFactory::~ShaderFactory() { for (unsigned short index (0); index < mShaders.size(); index++) { glDetachShader (mProgramID, mShaders.at (index).getID() ); glDeleteShader (mShaders.at (index).getID() ); } mShaders.clear(); glDeleteProgram (mProgramID); } void ShaderFactory::addShader (GLenum shaderType, std::string filePath) { mShaders.push_back (Shader (shaderType, filePath) ); mShaders.back().read(); mShaders.back().compile(); } GLuint ShaderFactory::linkProgram() { mProgramID = glCreateProgram(); for (unsigned short index (0); index < mShaders.size(); index++) glAttachShader (mProgramID, mShaders.at (index).getID() ); glLinkProgram (mProgramID); // Check the program GLint result = GL_FALSE; int infoLogLength; glGetProgramiv (mProgramID, GL_LINK_STATUS, &result); glGetProgramiv (mProgramID, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { std::vector<char> programErrorMessage (infoLogLength + 1); glGetProgramInfoLog (mProgramID, infoLogLength, NULL, &programErrorMessage[0]); std::cerr << &programErrorMessage[0] << std::endl; } return mProgramID; }
true
057cd2c84f21a10a5c2bff92c12e92e1c0b18f84
C++
TheIslland/learning-in-collegelife
/18.c++/智能指针遍历二叉树尝试.cpp
UTF-8
1,138
3.390625
3
[]
no_license
/************************************************************************* > File Name: 智能指针遍历二叉树尝试.cpp > Author:TheIslland > Mail: 861436930@qq.com > Created Time: 2019年04月05日 星期五 11时14分59秒 ************************************************************************/ #include <iostream> #include <string> #include <memory> using namespace std; class Animal { public: string name; virtual string Introduce() = 0; }; class IAnimalFactory { public: virtual shared_ptr<Animal> CreateAnimal() = 0; }; class Cat : public Animal { public: string Introduce()override { return "我是一只猫,我的名字是" + name + "。"; } }; class CatFactory : public IAnimalFactory { public: shared_ptr<Animal> CreateAnimal()override { auto cat = make_shared<Cat>(); cat->name = "Tom"; return cat; } }; void IntroduceAnimalFromFactory(IAnimalFactory* factory) { auto animal = factory->CreateAnimal(); cout << animal->Introduce() << endl; } int main() { CatFactory factory; IntroduceAnimalFromFactory(&factory); return 0; }
true
ee8568e7b3e17b015227a4bc83bb8daa786e04e7
C++
irff/cp-codes
/TOKI/kubangan.cpp
UTF-8
1,966
2.515625
3
[]
no_license
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> using namespace std; #define R(i,_a,_b) for(int i=int(_a);i<int(_b);i++) #define PII pair<int,int> #define PIII pair<int,PII> #define x first #define y second int minx,miny,maxx,maxy,pa,pb,n,aa,bb,teskes,d[1001][1001]; char m[1001][1001]; queue<PIII> q; void tw(int a,int b,int c){ if(b>=minx and b<=maxx and c>=miny and c<=maxy and ( m[b][c]=='S' or m[b][c]=='.') ){ d[b][c]=a; m[b][c]='X'; q.push(PIII(a,PII(b,c))); } } void bfs(int a,int b){ q.push(PIII(0,PII(a,b))); d[a][b]=0; m[a][b]='X'; while(!q.empty()){ PIII t=q.front(); q.pop(); tw(t.x+1,t.y.x-1,t.y.y); tw(t.x+1,t.y.x,t.y.y+1); tw(t.x+1,t.y.x+1,t.y.y); tw(t.x+1,t.y.x,t.y.y-1); } } int main(){ scanf("%d", &teskes); while(teskes--){ memset(m, '.', sizeof m); memset(d, 0, sizeof d); scanf("%d%d%d", &pa,&pb,&n); pa+=500;pb+=500; // set range minx=pa; maxx=pa; miny=pb; maxy=pb; // just 4 debug m[500][500]='*'; m[pa][pb]='S'; //input R(i,0,n){ scanf("%d%d", &aa,&bb); minx=min(minx,aa+500); maxx=max(maxx,aa+500); miny=min(miny,bb+500); maxy=max(maxy,bb+500); m[aa+500][bb+500]='M'; } // expanding range minx--; miny--; maxx++; maxy++; /*R(i,minx,maxx+1){ R(j,miny,maxy+1) printf("%c", m[i][j]); puts(""); }*/ // process bfs(500,500); /*R(i,minx,maxx+1){ R(j,miny,maxy+1) printf("%d ", d[i][j]); puts(""); } R(i,minx,maxx+1){ R(j,miny,maxy+1) printf("%c", m[i][j]); puts(""); }*/ printf("%d\n", d[pa][pb]); } return 0; }
true
53d640db2a21831c0aa0e8ca6fdea04922a12113
C++
HeoJiYong/JYBaekJoon
/BaekJoon/BaekJoon/10799_스택_미완.cpp
UHC
621
3.0625
3
[]
no_license
/* 10799 踷빮 */ #include <iostream> #include <stack> #include <string> using namespace std; stack <char> st; string str; int main() { //freopen("input.txt", "r", stdin); int stick = 0, result = 0; int temp = 0; cin >> str; for (int i = 0; i < str.length(); i++) { if (str[i] == '(') { st.push(str[i]); stick++; } else if (str[i] == ')') { stick--; if (st.top() == '(') { st.push(str[i]); result = result + stick + temp; temp = 0; } else if (st.top() == ')') { st.push(str[i]); temp++; } } } result += temp; cout << result; return 0; }
true
ad28511bbee0c055a68c963fb7c61a70e773f3cd
C++
simon0191/ProgrammingExercises
/PowerStrings-UVA-10298/powerStrings.cpp
UTF-8
679
2.875
3
[]
no_license
#include <cstdio> #include <cstring> int main(){ char buff[1000000]; int size; bool flag; while(scanf("%s",buff)==1 && buff[0]!='.'){ flag = false; size = strlen(buff); for(int i = 1;i<size-1 && !flag;++i){ if(size%i == 0){ flag = true; for(int j = i;j<size && flag;j+=i){ if(strncmp(buff,buff+j,i)!=0){ flag = false; } } if(flag){ printf("%d\n",size/i); } } } if(!flag)printf("1\n"); } return 0; }
true
2f67c5033644ea18cdb91ccdb6247e5121691ecc
C++
ebrahimree/snmppp
/code/test/test_03_get.cpp
UTF-8
4,535
2.8125
3
[ "MIT" ]
permissive
// SNMPpp: https://sourceforge.net/p/snmppp/ // SNMPpp project uses the MIT license. See LICENSE for details. // Copyright (C) 2013 Stephane Charette <stephanecharette@gmail.com> #include <assert.h> #include <iostream> #include <SNMPpp/Get.hpp> void testGetNext( SNMPpp::SessionHandle &sessionHandle ) { std::cout << "Test GETNEXT:" << std::endl; SNMPpp::OID newOid; SNMPpp::OID oldOid( SNMPpp::OID::kInternet ); assert( newOid.empty() == true ); assert( oldOid.empty() == false ); for ( size_t idx = 0; idx < 10; idx ++ ) { SNMPpp::PDU pdu( SNMPpp::PDU::kGetNext ); pdu.addNullVar( oldOid ); assert( pdu.size() == 1 ); assert( pdu.varlist().firstOID() == oldOid ); pdu = SNMPpp::getNext( sessionHandle, pdu ); std::cout << pdu; // debug output assert( pdu.empty() == false ); assert( pdu.size() == 1 ); newOid = pdu.varlist().firstOID(); assert( oldOid < newOid ); assert( newOid > oldOid ); std::cout << "Reading " << pdu.firstOID() << ": " << pdu.varlist().asString() << std::endl; pdu.free(); assert( pdu.empty() == true ); assert( pdu.size() == 0 ); oldOid = newOid; } return; } void testManyOidsAtOnce1( SNMPpp::SessionHandle &sessionHandle ) { std::cout << "Test GET with multiple OIDs:" << std::endl; SNMPpp::PDU pdu( SNMPpp::PDU::kGet ); pdu.addNullVar( "1.3.6.1.2.1.1.1.0" ); pdu.addNullVar( "1.3.6.1.2.1.1.2.0" ); pdu.addNullVar( "1.3.6.1.2.1.1.3.0" ); pdu.addNullVar( "1.3.6.1.2.1.1.4.0" ); const size_t len = pdu.size(); assert( len == 4 ); pdu = SNMPpp::get( sessionHandle, pdu ); std::cout << pdu; assert( pdu.empty() == false ); assert( pdu.size() == len ); // always remember to free the PDU once done with it pdu.free(); assert( pdu.empty() == true ); assert( pdu.size() == 0 ); return; } void testManyOidsAtOnce2( SNMPpp::SessionHandle &sessionHandle ) { std::cout << "Test GET with a std::set of OIDs:" << std::endl; SNMPpp::SetOID oids; oids.insert( ".1.3.6.1.2.1.1.1.0" ); oids.insert( ".1.3.6.1.2.1.1.2.0" ); oids.insert( ".1.3.6.1.2.1.1.3.0" ); oids.insert( ".1.3.6.1.2.1.1.4.0" ); oids.insert( ".1.3.6.1.2.1.1.5.0" ); oids.insert( ".1.3.6.1.2.1.1.6.0" ); oids.insert( ".1.3.6.1.2.1.1.7.0" ); oids.insert( ".1.3.6.1.2.1.1.8.0" ); const size_t len = oids.size(); assert( oids.empty() == false ); assert( len == 8 ); SNMPpp::PDU pdu = SNMPpp::get( sessionHandle, oids ); std::cout << pdu; assert( pdu.empty() == false ); assert( pdu.size() == len ); const SNMPpp::OID o = pdu.varlist().firstOID(); assert( o.empty() == false ); assert( pdu.varlist().asnType(o) != ASN_NULL ); // always remember to free the PDU once done with it pdu.free(); assert( pdu.empty() == true ); assert( pdu.size() == 0 ); return; } void testGetSingleOid( SNMPpp::SessionHandle &sessionHandle ) { std::cout << "Test GET with a specific OID:" << std::endl; SNMPpp::OID o = "1.3.6.1.2.1.1.1.0"; SNMPpp::PDU pdu = SNMPpp::get( sessionHandle, o ); assert( pdu.empty() == false ); assert( pdu.size() == 1 ); assert( pdu.varlist().asnType(o) != ASN_NULL ); std::cout << pdu << "\tIf we know the type of an OID, then we can retrieve the value directly from the PDU:" << std::endl << "\t" << o << ": " << pdu.varlist().getString(o) << std::endl; // always remember to free the PDU once done with it pdu.free(); assert( pdu.empty() == true ); assert( pdu.size() == 0 ); return; } void testGetBulk( SNMPpp::SessionHandle &sessionHandle ) { std::cout << "Test GETBULK (SNMPv2) with a single starting OID:" << std::endl; SNMPpp::PDU pdu( SNMPpp::PDU::kGetBulk ); pdu.addNullVar( ".1" ); pdu = SNMPpp::getBulk( sessionHandle, pdu, 20 ); std::cout << pdu; const SNMPpp::OID o = pdu.varlist().firstOID(); assert( o.empty() == false ); assert( pdu.varlist().asnType(o) != ASN_NULL ); assert( pdu.empty() == false ); assert( pdu.size() == 20 ); // always remember to free the PDU once done with it pdu.free(); assert( pdu.empty() == true ); assert( pdu.size() == 0 ); return; } int main( int argc, char *argv[] ) { std::cout << "Test some of the net-snmp GET/GETNEXT/GETBULK functionality." << std::endl; SNMPpp::SessionHandle sessionHandle = NULL; SNMPpp::openSession( sessionHandle, "udp:localhost:161" ); assert( sessionHandle != NULL ); testGetNext ( sessionHandle ); testManyOidsAtOnce1 ( sessionHandle ); testManyOidsAtOnce2 ( sessionHandle ); testGetSingleOid ( sessionHandle ); testGetBulk ( sessionHandle ); SNMPpp::closeSession ( sessionHandle ); assert( sessionHandle == NULL ); return 0; }
true
d07487d874f9c95ef89dea36b083d1d1847e8f34
C++
gykovacs/vessel
/src/lib/openipDS/openipDS/Frame3.cc
UTF-8
1,388
2.984375
3
[]
no_license
#include <openipDS/Frame3.h> namespace openip { Frame3::Frame3() { origin= Vector3<float>(0,0,0); baseX= Vector3<float>(0,0,1); baseY= Vector3<float>(0,1,0); baseZ= Vector3<float>(1,0,0); } Frame3::Frame3(const Frame3& f) { origin= f.origin; baseX= f.baseX; baseY= f.baseY; baseZ= f.baseZ; } Frame3::~Frame3() { } Frame3& Frame3::operator=(const Frame3& f) { origin= f.origin; baseX= f.baseX; baseY= f.baseY; baseZ= f.baseZ; return *this; } void Frame3::setFrame(Vector3<float> o, Vector3<float> z, Vector3<float> y, Vector3<float> x) { this->origin= o; this->baseZ= z; this->baseY= y; this->baseX= x; } void Frame3::getRealCoordinates(float z, float y, float x, float& zr, float& yr, float& xr) { zr= origin.z() + z * baseZ.z() + y * baseY.z() + x * baseX.z(); yr= origin.y() + z * baseZ.y() + y * baseY.y() + x * baseX.y(); xr= origin.x() + z * baseZ.x() + y * baseY.x() + x * baseX.x(); } void Frame3::getRealCoordinates(float z, float y, float x, Vector3<float>& v) { v= origin + baseZ * z + baseY * y + baseX * x; } float Frame3::getVolume() { return baseX.x() * baseY.y() * baseZ.z(); } }
true
d1d8eaf08d85211ca4d3e5b20af21f29bd66db9d
C++
yangcnju/cpp_primer_5
/ch19/ex19.26.cc
UTF-8
469
3.703125
4
[]
no_license
// Exercise 19.26: Explain these declarations and indicate whether they are // legal: #include <iostream> using namespace std; extern "C" int compute(int *, int); //extern "C" double compute(double *, double); int main(int argc, char **argv) { int i = 1; int j = 2; cout << compute(&i,j) << endl; return 0; } extern "C" int compute(int *pti, int i) { return *pti+i; } // illegal //extern "C" double compute(double *ptd, double d) //{ // return *ptd+d; //}
true
0a0252eb4a52dcee3fc03bc6d135883624358f1f
C++
zpzjzj/renkou
/Scheme/is_container.hpp
UTF-8
2,758
2.6875
3
[]
no_license
#include <boost/preprocessor/cat.hpp> #include <type_traits> #include <boost/mpl/bool.hpp> template<bool T> using bool_ = boost::mpl::bool_<T>; template <class T> using rm_ref_t = typename std::remove_reference<T>::type; namespace detail { // a preprocess iteration will be better. I an not able to and not interested in making this done #define TNAME value_type // value type #include "has_xxx.hpp" #define TNAME reference // reference #include "has_xxx.hpp" #define TNAME const_reference // const_reference #include "has_xxx.hpp" #define TNAME iterator // iterator #include "has_xxx.hpp" #define TNAME const_iterator // const_iterator #include "has_xxx.hpp" #define TNAME difference_type // difference_type #include "has_xxx.hpp" #define TNAME size_type // size_type #include "has_xxx.hpp" #define TNAME begin // begin #include "has_mem.hpp" #define TNAME cbegin // cbegin #include "has_mem.hpp" #define TNAME end // end #include "has_mem.hpp" #define TNAME cend // cend #include "has_mem.hpp" #define TNAME size // size #include "has_mem.hpp" #define TNAME max_size // max_size #include "has_mem.hpp" #define TNAME empty // empty #include "has_mem.hpp" } #include "and.hpp" #define TEST #ifdef TEST template <bool, class> struct is_container_impl { static constexpr int value = false; // not a class }; template <class T> struct is_container_impl<true, T> { static constexpr int value = detail::has_value_type<T>::value && detail::has_reference<T>::value && detail::has_const_reference<T>::value && detail::has_const_iterator<T>::value && detail::has_difference_type<T>::value && detail::has_size_type<T>::value && detail::has_mem_begin<T>::value && detail::has_mem_cbegin<T>::value && detail::has_mem_end<T>::value && detail::has_mem_cend<T>::value && detail::has_mem_size<T>::value && detail::has_mem_max_size<T>::value && detail::has_mem_empty<T>::value; using type = boost::mpl::bool_<value>; }; template <class T> struct is_container :is_container_impl<std::is_class<T>::value, T> {}; #else template <typename T> struct is_container : and_< std::is_class<T>, detail::has_value_type<T>, detail::has_reference<T>, detail::has_const_reference<T>, detail::has_const_iterator<T>, detail::has_difference_type<T>, detail::has_size_type<T>, detail::has_mem_begin<T>, detail::has_mem_cbegin<T>, detail::has_mem_end<T>, detail::has_mem_cend<T>, detail::has_mem_size<T>, detail::has_mem_max_size<T>, detail::has_mem_empty<T> >{}; template <class T> constexpr bool is_container_v = is_contsainer<T>::value; #endif
true
cdc8df4df814459342e4f43eb8c579faaf4c6c42
C++
andymina/csci13600-labs
/lab_10/time.cpp
UTF-8
569
3.75
4
[]
no_license
#include "time.h" void printTime(Time time){ std::cout << time.h << ":" << time.m; } int toMinutes(Time time){ return (time.h * 60) + time.m; } Time toTime(int minutes){ Time temp = {0, 0}; temp.h = minutes / 60; temp.m = minutes % 60; return temp; } int minutesSinceMidnight(Time time){ return toMinutes(time); } int minutesUntil(Time earlier, Time later){ int first = toMinutes(earlier); int second = toMinutes(later); return second - first; } Time addMinutes(Time time0, int min){ int temp = toMinutes(time0); temp += min; return toTime(temp); }
true
74fc5da121ad16a930c52fc7851bffab95617613
C++
JuhunC/3D_Chess
/Chess/Geometry/Sphere3D.h
UTF-8
596
2.953125
3
[]
no_license
/* Authored by Prof. Jeong-Mo Hong, CSE Dongguk University for Introduction to Computer Graphics, 2017 Spring */ #pragma once #include "GenericDefinitions.h" #include "Box3D.h" class Sphere3D { public: TV center_; T radius_; Sphere3D(const TV& _center, const T& _radius) : center_(_center), radius_(_radius) {} T getSignedDistance(const TV& position) const { return (position - center_).getMagnitude() - radius_; } TV getNormal(const TV& position) const { return (position - center_).getNormalized(); } Box3D<T> getAABB() const { return Box3D<T>(center_, radius_*2.0f); } };
true
554289aea8eaf5f2cc5b356232155157ef432566
C++
leeheekyo/DES
/DES.cpp
UHC
20,180
2.65625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> char key[65]; //PCMONE int PCMONE[56]={57, 49, 41, 33, 25, 17, 9, 1 , 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7 , 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4}; //PCMTWO int PCMTWO[48]={14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32}; //E-ڽ int E[48]={32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1}; //P-ڽ(ܼġȯ) char P[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; //64Ʈ ̷ 8 S-ڽ char S[8][4][16] = { //S-ڽ1 {{14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7}, { 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8}, { 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0}, {15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13} }, //S-ڽ2 {{15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10}, { 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5}, { 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15}, {13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9} }, //S-ڽ3 {{10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1}, {13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7}, { 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12} }, //S-ڽ4 {{ 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15}, {13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9}, {10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4}, { 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14} }, //S-ڽ5 {{ 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9}, {14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6}, { 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14}, {11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3} }, //S-ڽ6 {{12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11}, {10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8}, { 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6}, { 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13} }, //S-ڽ7 {{ 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1}, {13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6}, { 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2}, { 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12} }, //S-ڽ8 {{13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7}, { 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2}, { 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8}, { 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11} } }; char IP[64] ={ 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; char IPinv[64] ={40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; //desȣȭ ϴ Լ void des(char* first, bool endn){ char sl[33];//="00000000111111110111100001010101"; char sr[33];//="00000000111111111000000001100110"; char sk[16][49];//="010100000010110010101100010001000000000001000000"; //01011011111101111100010110110010 int i, j, sboxuse, sboxuse2, round; char eout[49], xorout[49], sboxout[33], pout[33], xorafter[33], ipout[65]; //encryption or decryption // bool endn = true; //ip for(i=0;i<64;i++) ipout[i]=first[IP[i]-1]; ipout[64]='\0'; if(endn==true){ //ȣȭ ʿ ״ ǥ for(i=0;i<32;i++) sl[i]=ipout[i]; for(i=32;i<64;i++) sr[i-32]=ipout[i]; } else{ //ȣȭ ʰ ٲپ ǥ for(i=0;i<32;i++) sr[i]=ipout[i]; for(i=32;i<64;i++) sl[i-32]=ipout[i]; } sl[32]=sr[32]='\0'; // printf("ipout = %s%s\n",sl,sr); char pcmone[57], pcmtwo[49], shift[3]; //pcmone for(i=0;i<56;i++) pcmone[i]=key[PCMONE[i]-1]; pcmone[56]='\0'; // printf("pcmone = %s\n", pcmone); //key make for(j=0;j<16;j++){ //shift if(j==0||j==1||j==8||j==15){ shift[0]=pcmone[0]; for(i=0;i<27;i++) pcmone[i]=pcmone[i+1]; pcmone[27]=shift[0]; shift[0]=pcmone[28]; for(i=28;i<55;i++) pcmone[i]=pcmone[i+1]; pcmone[55]=shift[0]; } else{ shift[0]=pcmone[0]; shift[1]=pcmone[1]; for(i=0;i<26;i++) pcmone[i]=pcmone[i+2]; pcmone[26]=shift[0]; pcmone[27]=shift[1]; shift[0]=pcmone[28]; shift[1]=pcmone[29]; for(i=28;i<54;i++) pcmone[i]=pcmone[i+2]; pcmone[54]=shift[0]; pcmone[55]=shift[1]; } // printf("shift = %s\n", pcmone); //pcmtwo for(i=0;i<48;i++) pcmtwo[i]=pcmone[PCMTWO[i]-1]; pcmtwo[48]='\0'; for(i=0;i<=48;i++) sk[j][i]=pcmtwo[i]; // printf("key %d = %s\n",j+1, sk[j]); } //start func for(round=0;round<16;round++){ // printf("*******************************\n%d round\n****************************\n",round+1); // printf("sl = %s\n",sl); // printf("sr = %s\n",sr); //init right sr[32]='\0'; // printf("sr = %s\n", sr); //ebox for(i=0; i<48; i++) eout[i]=sr[E[i]-1]; eout[48]='\0'; // printf("eout = %s\n", eout); //xor if(endn==true){ // printf("key = %s\n", sk[round]); for(i=0;i<48; i++){ if((eout[i]=='0'&&sk[round][i]=='0')||(eout[i]=='1'&&sk[round][i]=='1')) xorout[i]='0'; else xorout[i]='1'; } xorout[48]='\0'; // printf("xorout = %s\n", xorout); } else{ // printf("key = %s\n", sk[15-round]); for(i=0;i<48; i++){ if((eout[i]=='0'&&sk[15-round][i]=='0')||(eout[i]=='1'&&sk[15-round][i]=='1')) xorout[i]='0'; else xorout[i]='1'; } xorout[48]='\0'; // printf("xorout = %s\n", xorout); } //Sbox one sboxuse=0; if(xorout[1]=='1') sboxuse+=8; if(xorout[2]=='1') sboxuse+=4; if(xorout[3]=='1') sboxuse+=2; if(xorout[4]=='1') sboxuse+=1; if(xorout[0]=='0'&&xorout[5]=='0') sboxuse2=S[0][0][sboxuse]; else if(xorout[0]=='0'&&xorout[5]=='1') sboxuse2=S[0][1][sboxuse]; else if(xorout[0]=='1'&&xorout[5]=='0') sboxuse2=S[0][2][sboxuse]; else if(xorout[0]=='1'&&xorout[5]=='1') sboxuse2=S[0][3][sboxuse]; if(sboxuse2>=8){ sboxout[0]='1'; sboxuse2-=8; } else sboxout[0]='0'; if(sboxuse2>=4){ sboxout[1]='1'; sboxuse2-=4; } else sboxout[1]='0'; if(sboxuse2>=2){ sboxout[2]='1'; sboxuse2-=2; } else sboxout[2]='0'; if(sboxuse2>=1){ sboxout[3]='1'; sboxuse2-=1; } else sboxout[3]='0'; //Sbox two sboxuse=0; if(xorout[7]=='1') sboxuse+=8; if(xorout[8]=='1') sboxuse+=4; if(xorout[9]=='1') sboxuse+=2; if(xorout[10]=='1') sboxuse+=1; if(xorout[6]=='0'&&xorout[11]=='0') sboxuse2=S[1][0][sboxuse]; else if(xorout[6]=='0'&&xorout[11]=='1') sboxuse2=S[1][1][sboxuse]; else if(xorout[6]=='1'&&xorout[11]=='0') sboxuse2=S[1][2][sboxuse]; else if(xorout[6]=='1'&&xorout[11]=='1') sboxuse2=S[1][3][sboxuse]; if(sboxuse2>=8){ sboxout[4]='1'; sboxuse2-=8; } else sboxout[4]='0'; if(sboxuse2>=4){ sboxout[5]='1'; sboxuse2-=4; } else sboxout[5]='0'; if(sboxuse2>=2){ sboxout[6]='1'; sboxuse2-=2; } else sboxout[6]='0'; if(sboxuse2>=1){ sboxout[7]='1'; sboxuse2-=1; } else sboxout[7]='0'; //Sbox three sboxuse=0; if(xorout[13]=='1') sboxuse+=8; if(xorout[14]=='1') sboxuse+=4; if(xorout[15]=='1') sboxuse+=2; if(xorout[16]=='1') sboxuse+=1; if(xorout[12]=='0'&&xorout[17]=='0') sboxuse2=S[2][0][sboxuse]; else if(xorout[12]=='0'&&xorout[17]=='1') sboxuse2=S[2][1][sboxuse]; else if(xorout[12]=='1'&&xorout[17]=='0') sboxuse2=S[2][2][sboxuse]; else if(xorout[12]=='1'&&xorout[17]=='1') sboxuse2=S[2][3][sboxuse]; if(sboxuse2>=8){ sboxout[8]='1'; sboxuse2-=8; } else sboxout[8]='0'; if(sboxuse2>=4){ sboxout[9]='1'; sboxuse2-=4; } else sboxout[9]='0'; if(sboxuse2>=2){ sboxout[10]='1'; sboxuse2-=2; } else sboxout[10]='0'; if(sboxuse2>=1){ sboxout[11]='1'; sboxuse2-=1; } else sboxout[11]='0'; //Sbox four sboxuse=0; if(xorout[19]=='1') sboxuse+=8; if(xorout[20]=='1') sboxuse+=4; if(xorout[21]=='1') sboxuse+=2; if(xorout[22]=='1') sboxuse+=1; if(xorout[18]=='0'&&xorout[23]=='0') sboxuse2=S[3][0][sboxuse]; else if(xorout[18]=='0'&&xorout[23]=='1') sboxuse2=S[3][1][sboxuse]; else if(xorout[18]=='1'&&xorout[23]=='0') sboxuse2=S[3][2][sboxuse]; else if(xorout[18]=='1'&&xorout[23]=='1') sboxuse2=S[3][3][sboxuse]; if(sboxuse2>=8){ sboxout[12]='1'; sboxuse2-=8; } else sboxout[12]='0'; if(sboxuse2>=4){ sboxout[13]='1'; sboxuse2-=4; } else sboxout[13]='0'; if(sboxuse2>=2){ sboxout[14]='1'; sboxuse2-=2; } else sboxout[14]='0'; if(sboxuse2>=1){ sboxout[15]='1'; sboxuse2-=1; } else sboxout[15]='0'; //Sbox five sboxuse=0; if(xorout[25]=='1') sboxuse+=8; if(xorout[26]=='1') sboxuse+=4; if(xorout[27]=='1') sboxuse+=2; if(xorout[28]=='1') sboxuse+=1; if(xorout[24]=='0'&&xorout[29]=='0') sboxuse2=S[4][0][sboxuse]; else if(xorout[24]=='0'&&xorout[29]=='1') sboxuse2=S[4][1][sboxuse]; else if(xorout[24]=='1'&&xorout[29]=='0') sboxuse2=S[4][2][sboxuse]; else if(xorout[24]=='1'&&xorout[29]=='1') sboxuse2=S[4][3][sboxuse]; if(sboxuse2>=8){ sboxout[16]='1'; sboxuse2-=8; } else sboxout[16]='0'; if(sboxuse2>=4){ sboxout[17]='1'; sboxuse2-=4; } else sboxout[17]='0'; if(sboxuse2>=2){ sboxout[18]='1'; sboxuse2-=2; } else sboxout[18]='0'; if(sboxuse2>=1){ sboxout[19]='1'; sboxuse2-=1; } else sboxout[19]='0'; //Sbox six sboxuse=0; if(xorout[31]=='1') sboxuse+=8; if(xorout[32]=='1') sboxuse+=4; if(xorout[33]=='1') sboxuse+=2; if(xorout[34]=='1') sboxuse+=1; if(xorout[30]=='0'&&xorout[35]=='0') sboxuse2=S[5][0][sboxuse]; else if(xorout[30]=='0'&&xorout[35]=='1') sboxuse2=S[5][1][sboxuse]; else if(xorout[30]=='1'&&xorout[35]=='0') sboxuse2=S[5][2][sboxuse]; else if(xorout[30]=='1'&&xorout[35]=='1') sboxuse2=S[5][3][sboxuse]; if(sboxuse2>=8){ sboxout[20]='1'; sboxuse2-=8; } else sboxout[20]='0'; if(sboxuse2>=4){ sboxout[21]='1'; sboxuse2-=4; } else sboxout[21]='0'; if(sboxuse2>=2){ sboxout[22]='1'; sboxuse2-=2; } else sboxout[22]='0'; if(sboxuse2>=1){ sboxout[23]='1'; sboxuse2-=1; } else sboxout[23]='0'; //Sbox seven sboxuse=0; if(xorout[37]=='1') sboxuse+=8; if(xorout[38]=='1') sboxuse+=4; if(xorout[39]=='1') sboxuse+=2; if(xorout[40]=='1') sboxuse+=1; if(xorout[36]=='0'&&xorout[41]=='0') sboxuse2=S[6][0][sboxuse]; else if(xorout[36]=='0'&&xorout[41]=='1') sboxuse2=S[6][1][sboxuse]; else if(xorout[36]=='1'&&xorout[41]=='0') sboxuse2=S[6][2][sboxuse]; else if(xorout[36]=='1'&&xorout[41]=='1') sboxuse2=S[6][3][sboxuse]; if(sboxuse2>=8){ sboxout[24]='1'; sboxuse2-=8; } else sboxout[24]='0'; if(sboxuse2>=4){ sboxout[25]='1'; sboxuse2-=4; } else sboxout[25]='0'; if(sboxuse2>=2){ sboxout[26]='1'; sboxuse2-=2; } else sboxout[26]='0'; if(sboxuse2>=1){ sboxout[27]='1'; sboxuse2-=1; } else sboxout[27]='0'; //Sbox eight sboxuse=0; if(xorout[43]=='1') sboxuse+=8; if(xorout[44]=='1') sboxuse+=4; if(xorout[45]=='1') sboxuse+=2; if(xorout[46]=='1') sboxuse+=1; if(xorout[42]=='0'&&xorout[47]=='0') sboxuse2=S[7][0][sboxuse]; else if(xorout[42]=='0'&&xorout[47]=='1') sboxuse2=S[7][1][sboxuse]; else if(xorout[42]=='1'&&xorout[47]=='0') sboxuse2=S[7][2][sboxuse]; else if(xorout[42]=='1'&&xorout[47]=='1') sboxuse2=S[7][3][sboxuse]; if(sboxuse2>=8){ sboxout[28]='1'; sboxuse2-=8; } else sboxout[28]='0'; if(sboxuse2>=4){ sboxout[29]='1'; sboxuse2-=4; } else sboxout[29]='0'; if(sboxuse2>=2){ sboxout[30]='1'; sboxuse2-=2; } else sboxout[30]='0'; if(sboxuse2>=1){ sboxout[31]='1'; sboxuse2-=1; } else sboxout[31]='0'; sboxout[32]='\0'; // printf("sboxout = %s\n", sboxout); //pbox for(i=0; i<32; i++) pout[i]=sboxout[P[i]-1]; pout[32]='\0'; // printf("pout = %s\n", pout); // printf("sl = %s\n",sl); //xorafter for(i=0;i<32; i++){ if((pout[i]=='0'&&sl[i]=='0')||(pout[i]=='1'&&sl[i]=='1')) xorafter[i]='0'; else xorafter[i]='1'; } xorafter[32]='\0'; // printf("xor after = %s\n", xorafter); //new sl&sr for(i=0;i<32; i++){ sl[i]=sr[i]; sr[i]=xorafter[i]; } // printf("sl = %s\n",sl); // printf("sr = %s\n",sr); //end func } //IPinv if(endn==true){ for(i=0;i<32;i++) ipout[i]=sl[i]; for(i=32;i<64;i++) ipout[i]=sr[i-32]; } else{ for(i=0;i<32;i++) ipout[i]=sr[i]; for(i=32;i<64;i++) ipout[i]=sl[i-32]; } for(i=0;i<64;i++) first[i]=ipout[IPinv[i]-1]; // ʱ } // Լ int main(){ int run, i, j; run=1; FILE *fp; //("en.txt"); //des.txt ȣȭ FILE *fq; //("entodn.txt"); //des_en.txt ȣȭ Ǵ ȣȭ FILE *fr; //("ento.txt"); //des_dn.txt ȣȭ char endnchar; //ȣȭ ϴ ȣȭ ϴ Է¹ޱ char filename[26]; // ̸ bool endn; //ȣȭ ϴ ȣȭ ϴ Է Ϳ //bool endn =true; //ȣȭ //bool endn=false; //ȣȭ //mode while(1){ printf("enter the mode(encryption is e, decryption is d) "); // Է Ʈ scanf("%c",&endnchar); //ȣȭ ȣȭ Է¹ //endnchar&=0xff; if(endnchar == 'e' ||endnchar == 'E'||endnchar == 'd' ||endnchar == 'D' ) break; printf("\nplease enter the e or d"); //߸ ٽ Է } //ȣȭ ϸ Է ޴ κ if(endnchar == 'e' || endnchar == 'E'){ endn=true; printf("\n**************************\nenter the exsist txt file name(include .txt) "); scanf("%s",filename); // ̸ Է¹ filename[25]=0; fp = fopen(filename,"r"); //ش if(fp<0){ //̸ α׷ printf("inputfile missing\n"); exit(0); } for(i=0;filename[i]!='.';i++); //ȣȭ ̸ filename[i++]='_'; filename[i++]='e'; filename[i++]='n'; filename[i++]='.'; filename[i++]='t'; filename[i++]='x'; filename[i++]='t'; filename[i]=0; fq = fopen(filename,"w"); //ȣȭ } else{ //ȣȭ ϸ Է ޴ κ endn=false; printf("\n**************************\nenter the original txt file name(include .txt) "); scanf("%s",filename); //ϸ Է¹ filename[25]=0; for(i=0;filename[i]!='.';i++) ; //[ϸ]_en.txt filename[i++]='_'; filename[i++]='e'; filename[i++]='n'; filename[i++]='.'; filename[i++]='t'; filename[i++]='x'; filename[i++]='t'; filename[i]=0; fq = fopen(filename,"r"); // ̸ α׷ if(fp<0){ printf("inputfile missing\n"); exit(0); } for(i=0;filename[i]!='_';i++) ; // [ϸ]_dn.txt filename[i++]='_'; filename[i++]='d'; filename[i++]='n'; filename[i++]='.'; filename[i++]='t'; filename[i++]='x'; filename[i++]='t'; filename[i]=0; fr = fopen(filename,"w"); } //en buf //ȣȭ char buf[9]; //8 (1 byte) 2nible //64Ʈ 1char * 8 = 1byte * 8 ϱ char buftofirst[65]; //ȣȭ 64Ʈ ǥ ϱ // ʱȭ buftofirst[64]=0; buf[8]=0; //dn buf //ȣȭ char dnbuf[65]; //64Ʈ Ʈ о char dnbuftofirst[65]; //ȣȭ ϱ char temp; //ȣȭ ٽ char· ٲٱ //key input char keychar[9]; printf("please input the key(within 8 letter) : "); // key Է¹ scanf("%s",keychar); keychar[8]=0; //change key 64bit for(i=0;i<8;i++){ //Ű 64Ʈ ǥϴ κ if( (keychar[i]&0x80)> 0){ key[i*8]='1'; } else key[i*8]='0'; if( (keychar[i]&0x40)> 0){ key[i*8+1]='1'; } else key[i*8+1]='0'; if( (keychar[i]&0x20)> 0){ key[i*8+2]='1'; } else key[i*8+2]='0'; if( (keychar[i]&0x10)> 0){ key[i*8+3]='1'; } else key[i*8+3]='0'; if( (keychar[i]&0x08)> 0){ key[i*8+4]='1'; } else key[i*8+4]='0'; if( (keychar[i]&0x04)> 0){ key[i*8+5]='1'; } else key[i*8+5]='0'; if( (keychar[i]&0x02)> 0){ key[i*8+6]='1'; } else key[i*8+6]='0'; if( (keychar[i]&0x01)> 0){ key[i*8+7]='1'; } else key[i*8+7]='0'; } key[64]=0; //en part //ȣȭ κ if(endn == true){ while(1){ for(i=0; i<8; i++) buf[i]=0; //buf ʱȭ for(i=0;i<8;i++){ //1char * 8 64Ʈ Է¹޴ κ if( feof(fp) ){ if(i!=0) for( ;i<8;i++) buf[i]=0; run=0; break; } fscanf(fp,"%c",&buf[i]); } if(i==0) break; for(i=0; i<64; i++) buftofirst[i]=0; //cout<<buf<<endl; for(i=0;i<8;i++){ //Է¹ 64Ʈ char ٲٴ κ if( (buf[i]&0x80)> 0){ buftofirst[i*8]='1'; } else buftofirst[i*8]='0'; if( (buf[i]&0x40)> 0){ buftofirst[i*8+1]='1'; } else buftofirst[i*8+1]='0'; if( (buf[i]&0x20)> 0){ buftofirst[i*8+2]='1'; } else buftofirst[i*8+2]='0'; if( (buf[i]&0x10)> 0){ buftofirst[i*8+3]='1'; } else buftofirst[i*8+3]='0'; if( (buf[i]&0x08)> 0){ buftofirst[i*8+4]='1'; } else buftofirst[i*8+4]='0'; if( (buf[i]&0x04)> 0){ buftofirst[i*8+5]='1'; } else buftofirst[i*8+5]='0'; if( (buf[i]&0x02)> 0){ buftofirst[i*8+6]='1'; } else buftofirst[i*8+6]='0'; if( (buf[i]&0x01)> 0){ buftofirst[i*8+7]='1'; } else buftofirst[i*8+7]='0'; } buftofirst[64]=0; //Ȥ κ ʱȭ //cout<<"pl " << buftofirst << endl; des(buftofirst,true); //ȣȭ ϴ κ //cout<<"en " << buftofirst <<endl; buftofirst[64]=0;// Ȥ ٽ ʱȭ fprintf(fq,"%s",buftofirst); //ȣȭ [ϸ]_en.txt //des(buftofirst,false); //cout<<"dn " << buftofirst <<endl; if(run==0) break; } printf("create file : %s\n",filename); // Ǿ ˸ κ } //it is using main empty less //endn=true; if(endn==false){ while(1){ for(i=0;i<64;i++) dnbuf[i]=0; //ʱȭ κ for(i=0;i<64;i++){ //64bit о κ if( feof(fq) ){ //for(;i<64;i++) dnbuf[i]=0; run=0; break; } fscanf(fq,"%c",&dnbuf[i]); //cout<<dnbuf[i]<<endl; } dnbuf[64]=0; if(run==0) break; //cout<<dnbuf<<endl; des(dnbuf,false); //ȣȭ dnbuf[64]=0; //cout<<dnbuf<<endl; for(i=0;i<8;i++){ //ȣȭ char ǥϴ temp=0x00; if(dnbuf[8*i]=='1'){ temp |= 0x80; } if(dnbuf[8*i+1]=='1'){ temp |= 0x40; } if(dnbuf[8*i+2]=='1'){ temp |= 0x20; } if(dnbuf[8*i+3]=='1'){ temp |= 0x10; } if(dnbuf[8*i+4]=='1'){ temp |= 0x08; } if(dnbuf[8*i+5]=='1'){ temp |= 0x04; } if(dnbuf[8*i+6]=='1'){ temp |= 0x02; } if(dnbuf[8*i+7]=='1'){ temp |= 0x01; } //cout << temp; //buf[i]=temp; if(temp!=0) fprintf(fr,"%c",temp); } //cout<<buf<<endl; if(run==0) break; } printf("create file : %s\n",filename); // Ǿ ˷ִ κ } return 0; }
true
e61a62dae7418f5a046397e31e0cd2308fcccea7
C++
vikashkumr/Competitive-Programming
/practice/Data structures/Linked list/reverse_linked_list.cpp
UTF-8
1,064
4.28125
4
[ "MIT" ]
permissive
//iterative program to reverse a singly linked list #include<iostream> #include<cstdlib> using namespace std; struct node { int data; struct node *next; }; struct node *head=NULL; void insert(int x) { //creating node dynamically struct node *temp=(struct node *)malloc(sizeof(struct node)); //initiliasing value temp->data=x; temp->next=NULL; if(head==NULL) head=temp; else { //inserting at the end struct node *t=head; while(t->next!=NULL) t=t->next; t->next=temp; } } //iteration to reverse the linked list struct node* reverse(struct node* curr) { struct node *prev=NULL,*nxt=NULL; while(curr){ nxt=curr->next; curr->next=prev; prev=curr; curr=nxt; } return prev; } //print function void print(struct node *t){ while(t!=NULL){ cout<<t->data<<" "; t=t->next; } } //driver program int main() { for(int i=1;i<=5;i++) insert(i); head=reverse(head); //prints linked list because above head has updates and linked list has been reversed print(head); return 0; }
true
0713039677c42729757e3caf9f36ba4cafb6d0ab
C++
basaraking1221/BTree_Submit
/BTree.hpp
UTF-8
20,129
3.0625
3
[]
no_license
#include "utility.hpp" #include <functional> #include <cstddef> #include "exception.hpp" #include <fstream> const int Mmax=1000; const int Lmax=400; namespace sjtu { template <class Key, class Value, class Compare = std::less<Key> > class BTree { public: typedef pair<const Key, Value> value_type; private: struct filename { char *str; filename() {str=new char[30];strcpy(str,"bplustree.txt");} ~filename(){ if(!str) delete str;} };//第二次加的,刚搞明白不能用路径来写。。 //中间节点 struct midroot{ int offset; //自己的偏移量 int father; //爸爸的偏移量 int num; //已存的key的个数 int type; //type=0 则它的儿子是internal_node int children[Mmax+1]; //设计每个中间结点存M个孩子 数组开M+1 大小 Key key[Mmax]; //设计每个中间结点可以放M-1个key 但数组要开M个 因为要是已有M-1个key插入一个key 则先存M个再分裂 midroot() { offset=0; father=0; num=0; type=0; memset(children,0,Mmax+1); } }; //叶子节点 struct leaves{ int offset; int father; int prev,next; int pairnum; //你敢信我写到最后了才发现,这个Value_type跟我写的不一样???? Key k[Lmax+1]; Value v[Lmax+1]; leaves(){ offset=0; father=0; pairnum=0; prev=0; next=0; } }; //根节点?也不算吧,那就定名为索引。 struct indexs{ int head; int tail; int root; int size; int eof; indexs() { head=0; tail=0; root=0; size=0; eof=0; } }; private: FILE *txt;//txt文本 bool whetheropen;//打不打开 indexs catalogue;//我英语很棒了 bool whetherexist;//竟然还有文件原来已经存在这一说。。 filename txtname; public: class const_iterator; class iterator { friend class BTree; private: // Your private members go here int leafoffset; int pairpos; BTree *bpt; public: bool modify(const Value& value){ } iterator() { // TODO Default Constructor bpt=NULL; leafoffset=0; pairpos=0; } iterator(const iterator& other) { // TODO Copy Constructor bpt=other.bpt; leafoffset=other.leafoffset; pairpos=other.pairpos; } // Return a new iterator which points to the n-next elements iterator operator++(int) { // Todo iterator++ } iterator& operator++() { // Todo ++iterator } iterator operator--(int) { // Todo iterator-- } iterator& operator--() { // Todo --iterator } // Overloaded of operator '==' and '!=' // Check whether the iterators are same bool operator==(const iterator& rhs) const { // Todo operator == } bool operator==(const const_iterator& rhs) const { // Todo operator == } bool operator!=(const iterator& rhs) const { // Todo operator != } bool operator!=(const const_iterator& rhs) const { // Todo operator != } }; class const_iterator { friend class BTree; // it should has similar member method as iterator. // and it should be able to construct from an iterator. private: // Your private members go here int leafoffset; int pairpos; BTree *bpt; public: const_iterator() { // TODO bpt=NULL; leafoffset=0; pairpos=0; } const_iterator(const const_iterator& other) { // TODO bpt=other.bpt; leafoffset=other.leafoffset; pairpos=other.pairpos; } const_iterator(const iterator& other) { // TODO bpt=other.bpt; leafoffset=other.leafoffset; pairpos=other.pairpos; } // And other methods in iterator, please fill by yourself. }; //进行一些文件操作,本来想直接open等但是不如写成函数来的快--------下面进行第二次调试及更改 void openfile(){ whetherexist=1; if(whetheropen==0) { txt= fopen(txtname.str,"rb+"); if(txt== nullptr) { whetherexist=false;//鬼知道还会打开失败歪日,你试试第一次运行就没打开的心态? txt = fopen(txtname.str,"w"); fclose(txt); txt =fopen(txtname.str,"rb+"); } else{ readfile(&catalogue,0,1, sizeof(indexs)); } whetheropen=1; } } void closefile(){ if(whetheropen==true) fclose(txt); whetheropen= false; } void readfile(void *place,int offset,int count,int size) { fseek(txt,offset,SEEK_SET); fread(place,size,count,txt); } void writefile(void *place, int offset, int count ,int size) { fseek(txt,offset,SEEK_SET); fwrite(place,size,count,txt); } //第一次就写这几个应该够了吧 void makeatree() { //先开始操作目录 catalogue.size=0; catalogue.eof= sizeof(indexs); //根节点和叶子节点建立 midroot root; leaves leaf; //一步步的摆正目录、各个节点的位置(position) catalogue.root=root.offset=catalogue.eof; catalogue.eof+= sizeof(midroot); catalogue.head=catalogue.tail=leaf.offset=catalogue.eof; catalogue.eof+= sizeof(leaves); //挨个初始化 root.father=0; root.num=0; root.type=true; root.children[0]=leaf.offset; leaf.father=root.offset; leaf.next=leaf.prev=0; leaf.pairnum=0; //全扔进文件里,写tmd writefile(&catalogue,0,1, sizeof(indexs)); writefile(&root,root.offset,1, sizeof(midroot)); writefile(&leaf,leaf.offset,1, sizeof(leaves)); } // Default Constructor and Copy Constructor BTree() { // Todo Default //第二次写添加,所有有关存在的都是,不再赘述 txt=NULL; openfile(); if(whetherexist==0) makeatree(); } BTree(const BTree& other) { //对不起这个我不会写 } BTree& operator=(const BTree& other) { // Todo Assignment } ~BTree() { closefile(); } //貌似查找直接遍历不行。。。所以我们现在在叶子节点操作下 int findleaves(Key key,int offset) { midroot p; readfile(&p,offset, 1, sizeof(midroot)); if(p.type==1) //恭喜你有儿子了 { int pos=0; for(pos=0;pos<p.num;pos++) { if(key<p.key[pos]) break;//找到真爱 } //注意孩子数比结点数多一个 pos++ 跳出循环后 也有孩子的 return p.children[pos]; } else{ int pos=0; for(pos=0;pos<p.num;pos++) { if(key<p.key[pos]) break; if(key==p.key[pos]) //考虑等号??? { pos++; break; } } return findleaves(key,p.children[pos]); } } //插入之前应该先会查找吧,不然插个龟龟 iterator find(const Key& key) { size_t leafpos = findleaves(key,catalogue.root);//挖他祖坟 leaves leaf; readfile(&leaf,leafpos,1, sizeof(leaves)); for(size_t i=0;i<leaf.pairnum;i++){ //我怎么觉得数据类型不太对。。。好奇怪 列为一个bug点 if(leaf.datak[i]==key){ iterator ret; ret.bpt=this; ret.leafoffset=leafpos; ret.pairpos=i; return ret; } } } const_iterator find(const Key& key) const {//没错我直接复制下来的 size_t leafpos = findleaves(key,catalogue.root);//挖他祖坟 leaves leaf; readfile(&leaf,leafpos,1, sizeof(leaves)); for(size_t i=0;i<leaf.pairnum;i++){ //我怎么觉得数据类型不太对。。。好奇怪 列为一个bug点 if(leaf.datak[i]==key){ iterator ret; ret.bpt=this; ret.leafoffset=leafpos; ret.pairpos=i; return ret; } } } //同样重新写,先插入叶子节点 pair<iterator,OperationResult> insertleaf(leaves &leaf,Key key,Value value) { iterator ret; int pos=0; for(pos=0;pos<leaf.pairnum;pos++) { if(key<leaf.k[pos]) break; } //可能插入第一个数据的时候,叶子节点还是空的,所以要处理下 if(leaf.pairnum==0) { leaf.k[0]=key; leaf.v[0]=value; leaf.pairnum=1; ++catalogue.size; ret.bpt=this; ret.pairpos=pos; ret.leafoffset=leaf.offset; writefile(&leaf,leaf.offset,1,sizeof(leaves)); return pair<iterator,OperationResult > (ret,Success); } //否则就技能疯狂后摇 for(int i=leaf.pairnum-1;i>=pos;--i) { leaf.k[i+1]=leaf.k[i]; leaf.v[i+1]=leaf.v[i]; } leaf.k[pos]=key; leaf.v[pos]=value; ++leaf.pairnum; ++catalogue.size; ret.bpt=this; ret.pairpos=pos; ret.leafoffset=leaf.offset; if(leaf.pairnum<=Lmax) writefile(&leaf,leaf.offset,1,sizeof(leaves)); else splitleaf(leaf,ret,key); return pair<iterator,OperationResult > (ret,Success); } //终于到了激动人心的分裂,我还没怎么搞懂的地方 void splitleaf (leaves &leaf, iterator & it, Key &key) { leaves new_leaf; new_leaf.pairnum=leaf.pairnum-leaf.pairnum/2; leaf.pairnum/=2; new_leaf.offset=catalogue.eof; for(int i=0;i<new_leaf.pairnum;i++) { new_leaf.k[i]=leaf.k[leaf.pairnum+i]; new_leaf.v[i]=leaf.v[leaf.pairnum+i]; //注意这个iterator if(new_leaf.k[i]==key) { it.leafoffset=new_leaf.offset; it.pairpos=i; } } //分裂完了就插入进去 new_leaf.next=leaf.next; new_leaf.prev=leaf.offset; if(leaf.next!=0) { leaves leaf_next; readfile(&leaf_next,leaf.next,1, sizeof(leaves)); leaf_next.prev=new_leaf.offset; writefile(&leaf_next,leaf_next.offset,1,sizeof(leaves)); } leaf.next=new_leaf.offset; //目录也要改变 if(catalogue.tail==leaf.offset) catalogue.tail=new_leaf.offset; catalogue.eof+= sizeof(leaves); //他爹也是哦宝贝 (怎么就这么多我吐了) new_leaf.father=leaf.father; writefile(&leaf,leaf.offset,1, sizeof(leaves)); writefile(&new_leaf,new_leaf.offset,1, sizeof(leaves)); writefile(&catalogue,0,1, sizeof(indexs)); midroot father; readfile(&father,leaf.father,1,sizeof(midroot)); insertnode(father,new_leaf.k[0],new_leaf.offset); } void insertnode(midroot & cur,Key key,int new_leaf_offset) { int pos=0; for(pos=0;pos<cur.num;++pos) { if(key<cur.key[pos]) break; } for(int i=cur.num-1;i>=pos;i--) { cur.key[i+1]=cur.key[i]; } for(int i=cur.num;i>=pos+1;i--) { cur.children[i+1]=cur.children[i]; } cur.key[pos]=key; cur.children[pos+1]=new_leaf_offset; ++cur.num; if(cur.num<=Mmax-1) writefile(&cur,cur.offset,1,sizeof(midroot)); else splitmidroot(cur); } void splitmidroot(midroot & node) { midroot new_node; new_node.num=node.num-node.num/2-1; node.num/=2; new_node.offset=catalogue.eof; catalogue.eof+= sizeof(midroot); for(int i=0;i<new_node.num;i++) { new_node.key[i]=node.key[i+node.num+1]; } for(int i=0;i<=new_node.num;i++) { new_node.children[i]=node.children[i+node.num+1]; } new_node.type=node.type; for(int i=0;i<=new_node.num;i++) { if(new_node.type==1) { leaves leaf; readfile(&leaf,new_node.children[i],1,sizeof(leaves)); leaf.father=new_node.offset; writefile(&leaf,leaf.offset,1,sizeof(leaves)); } else{ midroot internal; readfile(&internal,new_node.children[i],1,sizeof(midroot)); internal.father=new_node.offset; writefile(&internal,internal.offset,1,sizeof(midroot)); } } //还要考虑他爹是不是根,杀了我吧 if(node.offset == catalogue.root) { midroot new_root; new_root.father=0; new_root.type=0; new_root.offset=catalogue.eof; catalogue.eof+= sizeof(midroot); new_root.num=1; //输入新的呢! new_root.key[0]=node.key[node.num]; new_root.children[0]=node.offset; new_root.children[1]=new_node.offset; //更新他的papa node.father=new_root.offset; new_node.father=new_root.offset; //还有个目录(最后了吧我哭) catalogue.root=new_root.offset; //写入文件 writefile(&catalogue,0,1,sizeof(indexs)); writefile(&node,node.offset,1,sizeof(midroot)); writefile(&new_node,new_node.offset,1, sizeof(midroot)); writefile(&new_root,new_root.offset,1,sizeof(midroot)); } else { new_node.father=node.father; writefile(&catalogue,0,1,sizeof(indexs)); writefile(&node,node.offset,1,sizeof(midroot)); writefile(&new_node,new_node.offset,1, sizeof(midroot)); midroot father; readfile(&father,node.father,1, sizeof(midroot)); insertnode(father,node.key[node.num],new_node.offset); } } //大家好,我们终于可以开始插入了 pair<iterator, OperationResult> insert(const Key& key, const Value& value) { if(catalogue.size==0) { midroot root; leaves leaf_right; readfile(&root,catalogue.root,1, sizeof(midroot)); readfile(&leaf_right,catalogue.tail,1, sizeof(leaves)); root.key[0]=key; leaf_right.k[0]=key; leaf_right.v[0]=value; catalogue.size=1; root.num=1; leaf_right.pairnum=1; iterator p; p.bpt=this; p.leafoffset=leaf_right.offset; p.pairpos=0; writefile(&root,catalogue.root,1, sizeof(midroot)); writefile(&leaf_right,catalogue.tail,1,sizeof(leaves)); return pair<iterator,OperationResult >(p,Success); } int cur_leaf_node_offset=findleaves(key,catalogue.root); leaves new_node; readfile(&new_node,cur_leaf_node_offset,1, sizeof(leaves)); pair<iterator,OperationResult > ret =insertleaf(new_node,key,value); return ret; } // Erase: Erase the Key-Value // Return Success if it is successfully erased // Return Fail if the key doesn't exist in the database OperationResult erase(const Key& key) { // TODO erase function return Fail; // If you can't finish erase part, just remaining here. } // Return a iterator to the beginning iterator begin() {} const_iterator cbegin() const {} // Return a iterator to the end(the next element after the last) iterator end() {} const_iterator cend() const {} // Check whether this BTree is empty bool empty() const {} // Return the number of <K,V> pairs size_t size() const {} // Clear the BTree void clear() {} // Return the value refer to the Key(key) Value at(const Key& key){ int leafpos = findleaves(key,catalogue.root); leaves leaf; readfile(&leaf,leafpos,1, sizeof(leaves)); for(size_t i=0;i<leaf.pairnum;i++) { if(leaf.k[i]==key) { return leaf.v[i]; } } /*iterator it=find(key); leaf_node leaf; ReadFile(&leaf,it.leaf_offset,1, sizeof(leaf_node)); return leaf.v[it.pair_pos];*/ } /** * Returns the number of elements with key * that compares equivalent to the specified argument, * The default method of check the equivalence is !(a < b || b > a) */ size_t count(const Key& key) const {} /** * Finds an element with key equivalent to key. * key value of the element to search for. * Iterator to an element with key equivalent to key. * If no such element is found, past-the-end (see end()) iterator is * returned. */ }; } // namespace sjtu
true
6fddc75c2e7a856d74b3272b0935e197b31c6fee
C++
aranoy15/embedded-software
/app/drivers/bsp/F103xB_METEOSTATION/flash.cpp
UTF-8
1,011
3
3
[]
no_license
#include <flash.hpp> #include <main.h> void bsp::flash::erase() { FLASH_EraseInitTypeDef erase_inits; uint32_t errors = 0; std::uint32_t start = start_address; std::uint32_t count = 1; erase_inits.TypeErase = FLASH_TYPEERASE_PAGES; erase_inits.PageAddress = start; erase_inits.NbPages = count; HAL_FLASH_Unlock(); HAL_FLASHEx_Erase(&erase_inits, &errors); HAL_FLASH_Lock(); } void bsp::flash::write(std::uint32_t address, std::uint8_t data[], std::size_t size) { HAL_FLASH_Unlock(); for (uint32_t i = 0; i < size; i += sizeof(uint32_t)) { uint32_t current_address = address + i; uint32_t word_to_write = *(uint32_t*)(data + i); HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, current_address, word_to_write); } HAL_FLASH_Lock(); } void bsp::flash::read(std::uint32_t address, std::uint8_t data[], std::size_t size) { uint8_t *int_vector_table = (uint8_t *)address; for (std::size_t i = 0; i < size; ++i) { data[i] = int_vector_table[i]; } }
true
f56b8c968e0caf5ee0c8464011e9abb8b5bbce94
C++
tynrare/remote-games-control
/httpdownloader.cpp
UTF-8
6,129
2.515625
3
[]
no_license
#include "httpdownloader.h" #include <QtWidgets> #include <QtNetwork> #include <QUrl> ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent) : QProgressDialog(parent) { setWindowTitle(tr("Download Progress")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setLabelText(tr("Downloading %1.").arg(url.toDisplayString())); setMinimum(0); setValue(0); setMinimumDuration(0); } void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes) { setMaximum(totalBytes); setValue(bytesRead); } HttpDownloader::HttpDownloader() { #ifndef QT_NO_SSL connect(&qnam, &QNetworkAccessManager::sslErrors, this, &HttpDownloader::sslErrors); #endif } void HttpDownloader::startRequest(const QUrl &requestedUrl) { url = requestedUrl; httpRequestAborted = false; reply = qnam.get(QNetworkRequest(url)); connect(reply, &QNetworkReply::finished, this, &HttpDownloader::httpFinished); connect(reply, &QIODevice::readyRead, this, &HttpDownloader::httpReadyRead); ProgressDialog *progressDialog = new ProgressDialog(url, nullptr); progressDialog->setAttribute(Qt::WA_DeleteOnClose); connect(progressDialog, &QProgressDialog::canceled, this, &HttpDownloader::cancelDownload); connect(reply, &QNetworkReply::downloadProgress, progressDialog, &ProgressDialog::networkReplyProgress); connect(reply, &QNetworkReply::finished, progressDialog, &ProgressDialog::hide); progressDialog->show(); } void HttpDownloader::downloadFile(const QString &link, const QString &path, const QString &name) { const QString urlSpec = link; if (urlSpec.isEmpty()) return; const QUrl newUrl = QUrl::fromUserInput(urlSpec); if (!newUrl.isValid()) { QMessageBox::information(nullptr, tr("Error"), tr("Invalid URL: %1: %2").arg(urlSpec, newUrl.errorString())); return; } QString fileName = name; if (fileName.isEmpty()) fileName = newUrl.fileName(); if (fileName.isEmpty()) fileName = path; QString downloadDirectory = QDir::cleanPath(path); if (!downloadDirectory.isEmpty() && QFileInfo(downloadDirectory).isDir()) fileName.prepend(downloadDirectory + '/'); if (QFile::exists(fileName)) { if (QMessageBox::question(nullptr, tr("Overwrite Existing File"), tr("There already exists a file called %1 in " "the current directory. Overwrite?").arg(fileName), QMessageBox::Yes|QMessageBox::No, QMessageBox::No) == QMessageBox::No) return; QFile::remove(fileName); } this->file = openFileForWrite(fileName); if (!this->file) return; // schedule the request startRequest(newUrl); } QFile *HttpDownloader::openFileForWrite(const QString &fileName) { QScopedPointer<QFile> file(new QFile(fileName)); if (!file->open(QIODevice::WriteOnly)) { QMessageBox::information(nullptr, tr("Error"), tr("Unable to save the file %1: %2.") .arg(QDir::toNativeSeparators(fileName), file->errorString())); return Q_NULLPTR; } return file.take(); } void HttpDownloader::cancelDownload() { qInfo() << "Download canceled."; httpRequestAborted = true; reply->abort(); } void HttpDownloader::httpFinished() { QFileInfo fi; if (file) { fi.setFile(file->fileName()); file->close(); delete file; file = Q_NULLPTR; } if (httpRequestAborted) { reply->deleteLater(); reply = Q_NULLPTR; queueDownloading(); return; } if (reply->error()) { QFile::remove(fi.absoluteFilePath()); qInfo() << (tr("Download failed:\n%1.").arg(reply->errorString())); reply->deleteLater(); reply = Q_NULLPTR; queueDownloading(); return; } const QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); reply->deleteLater(); reply = Q_NULLPTR; if (!redirectionTarget.isNull()) { const QUrl redirectedUrl = url.resolved(redirectionTarget.toUrl()); if (QMessageBox::question(nullptr, tr("Redirect"), tr("Redirect to %1 ?").arg(redirectedUrl.toString()), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return; } file = openFileForWrite(fi.absoluteFilePath()); if (!file) { queueDownloading(); return; } startRequest(redirectedUrl); queueDownloading(); return; } qInfo() << (tr("Downloaded %1 bytes to %2\nin\n%3") .arg(fi.size()).arg(fi.fileName(), QDir::toNativeSeparators(fi.absolutePath()))); queueDownloading(); } void HttpDownloader::httpReadyRead() { // this slot gets called every time the QNetworkReply has new data. // We read all of its new data and write it into the file. // That way we use less RAM than when reading it at the finished() // signal of the QNetworkReply if (file) file->write(reply->readAll()); } #ifndef QT_NO_SSL void HttpDownloader::sslErrors(QNetworkReply*,const QList<QSslError> &errors) { QString errorString; foreach (const QSslError &error, errors) { if (!errorString.isEmpty()) errorString += '\n'; errorString += error.errorString(); } if (QMessageBox::warning(nullptr, tr("SSL Errors"), tr("One or more SSL errors has occurred:\n%1").arg(errorString), QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) { reply->ignoreSslErrors(); } } #endif
true