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
3eb8d641af2400fa7a7ef228375647cb5152b4bf
C++
amov-lab/Prometheus
/Modules/motion_planning/min_snap_trajectory/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/performance/rt_explicit_rk.hpp
UTF-8
2,119
2.625
3
[ "Apache-2.0" ]
permissive
/* * rt_explicit_rk.hpp * * Copyright 2009-2012 Karsten Ahnert * Copyright 2009-2012 Mario Mulansky * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or * copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef RT_EXPLICIT_RK_HPP_ #define RT_EXPLICIT_RK_HPP_ #include <vector> #include "rt_algebra.hpp" using namespace std; template< class StateType > class rt_explicit_rk { public: typedef StateType state_type; typedef double* const * coeff_a_type; typedef vector< double > coeff_b_type; typedef vector< double > coeff_c_type; rt_explicit_rk( size_t stage_count ) : m_s( stage_count ) { m_F = new state_type[ m_s ]; } rt_explicit_rk( const size_t stage_count , const coeff_a_type a , const coeff_b_type &b , const coeff_c_type &c ) : m_s( stage_count ) , m_a( a ) , m_b( b ) , m_c( c ) { m_F = new state_type[ m_s ]; } ~rt_explicit_rk() { delete[] m_F; } /* void set_params( coeff_a_type &a , coeff_b_type &b , coeff_c_type &c ) { m_a = a; m_b = b; m_c = c; }*/ template< class System > void do_step( System sys , state_type &x , const double t , const double dt ) { // first stage separately sys( x , m_F[0] , t + m_c[0]*t ); if( m_s == 1 ) rt_algebra::foreach( x , x , &m_b[0] , m_F , dt , 1 ); else rt_algebra::foreach( m_x_tmp , x , m_a[0] , m_F , dt , 1 ); for( size_t stage = 2 ; stage <= m_s ; ++stage ) { sys( m_x_tmp , m_F[stage-1] , t + m_c[stage-1]*dt ); if( stage == m_s ) rt_algebra::foreach( x , x , &m_b[0] , m_F , dt , stage-1 ); else rt_algebra::foreach( m_x_tmp , x , m_a[stage-1] , m_F , dt , stage-1 ); } } private: const size_t m_s; const coeff_a_type m_a; const coeff_b_type m_b; const coeff_c_type m_c; state_type m_x_tmp; state_type *m_F; }; #endif /* RT_EXPLICIT_RK_HPP_ */
true
706cc8b3eb6675586dc64f05af11b81f83fbe2bb
C++
zhanghuanzj/cpp
/USACO/1-3MixingMilk.cpp
UTF-8
971
2.796875
3
[ "Apache-2.0" ]
permissive
/* ID: zhanghu14 PROG: milk LANG: C++11 */ #include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <unordered_set> #include <algorithm> #include <set> using namespace std; //#define STDIO #ifdef STDIO #define IN cin #define OUT cout #else #define IN fin #define OUT fout #endif struct Farmer { int price; int amount; }; bool comp(const Farmer& f1,const Farmer& f2){ return f1.price<f2.price; } int main() { const string path = "milk"; ifstream fin(path+".in"); ofstream fout(path+".out"); int m,n; while (IN>>m>>n) { vector<Farmer> farmers(n); for (int i=0;i<n;++i) { IN>>farmers[i].price>>farmers[i].amount; } sort(farmers.begin(),farmers.end(),comp); int money = 0; for (int i=0;i<m&&m>0;++i) { if (farmers[i].amount<=m){ m -= farmers[i].amount; money += farmers[i].amount*farmers[i].price; }else{ money += farmers[i].price*m; m = 0; } } OUT<<money<<endl; } }
true
7f2ddd7885fea10988529de492f3c757f9fb0b8b
C++
FrankBlabu/GEP
/libs/system/GEPException.hpp
UTF-8
1,196
2.6875
3
[]
no_license
/* * GEPException.hpp - Exception base class * * Frank Cieslok, 03.06.2006 */ #ifndef __GEPException_hpp__ #define __GEPException_hpp__ #include <QtCore/QString> namespace GEP { /* * Base class for all GEP exception classes */ class Exception { public: Exception (const QString& message); virtual ~Exception (); inline const QString& getMessage () const; void setMessage (const QString& message); private: QString _message; }; #define CALLER_INFO __func__, __FILE__, __LINE__ /* * Exception class for internal errors */ class InternalException : public Exception { public: InternalException (const QString& message); InternalException (const char* function, const char* file, unsigned int line, const QString& message); virtual ~InternalException (); }; //#************************************************************************* // Inline functions //#************************************************************************* /* * Return the exceptions error message */ inline const QString& Exception::getMessage () const { return _message; } } // namespace GEP #endif
true
53d7b8d6fd36e9d7d1a4039b87c0097255cd0a84
C++
dis-triplebit/grace-slave
/TripleBit/tools/Mutex.cpp
UTF-8
431
2.8125
3
[]
no_license
/* * Mutex.cpp * * Created on: 2014-3-5 * Author: root */ #include "Mutex.h" Mutex::Mutex(){ // Constructor pthread_mutex_init(&mutex, 0); } Mutex::~Mutex(){ // Destructor pthread_mutex_destroy(&mutex); } void Mutex::lock(){ // Lock pthread_mutex_lock(&mutex); } bool Mutex::tryLock(){ // Try to lock return pthread_mutex_trylock(&mutex)==0; } void Mutex::unlock(){ // Unlock pthread_mutex_unlock(&mutex); }
true
31519068c912bfc47a72e3b1be519b509b8f5508
C++
MukundAggarwalRsystems/RC-Car
/2. Test Codes/Sharp_ir_test_run_1/Sharp_ir_test_run_1.ino
UTF-8
774
2.84375
3
[]
no_license
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to int sensorValue = 0; // value read from the pot void setup() { // initialize serial communications at 9600 bps: Serial.begin(115200); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); } void loop() { sensorValue = analogRead(analogInPin); Serial.println(sensorValue); if(sensorValue > 500) { halt(); }else forward(); } void forward() { Serial.println("Forward"); digitalWrite(8, LOW); digitalWrite(9, HIGH); digitalWrite(10, HIGH); digitalWrite(11, LOW); } void halt() { Serial.println("Stop"); digitalWrite(8, LOW); digitalWrite(9, LOW); digitalWrite(11, LOW); digitalWrite(10, LOW); }
true
0cc565eba2e483e0e3129dbc0a5082ee80ed1db4
C++
epics-base/pva2pva
/p2pApp/weakset.h
UTF-8
8,617
3.28125
3
[ "MIT" ]
permissive
#ifndef WEAKSET_H #define WEAKSET_H #include <set> #include <vector> #include <stdexcept> #include <pv/sharedPtr.h> #include <epicsMutex.h> #include <epicsGuard.h> /** @brief a std::set-ish container where entries are removed when ref. counts fall to zero * * A container of ref. counted (by shared_ptr) entries * where an entry may be present zero or one times in the set. * * Meant to be used in situations where an object must hold some weak references * of entries which it can iterate. * * Note that the insert() method replaces the reference pass to it * with a "wrapped" reference which removes from the set then releases the original ref. * The reference passed in *must* be unique() or std::invalid_argument is thrown. * While this can't be enforced, no weak_ptr to this object should exist. * * A reference loop will exist if the object owning the weak_set also * holds strong references to entries in this set. * * @note With the exception of swap() all methods are thread-safe * * @warning Use caution when storing types deriving from enabled_shared_from_this<> * As the implict weak reference they contain will not be wrapped. @code struct Owner; struct Entry { shared_ptr<Owner> O; }; struct Owner { weak_set<Entry> S; }; shared_ptr<Entry> build(const shared_ptr<Owner>& own) { shared_ptr<Owner> N(new Entry); N.O = own; own.S.insert(N); // modifies 'N' return N; } void example() { shared_ptr<Owner> O(new Owner); shared_ptr<Entry> E(build(O)); assert(!O.S.empty()); E.reset(); // Entry is removed from the set and free'd assert(O.S.empty()); } @endcode */ template<typename T> class weak_set { public: typedef T value_type; typedef std::tr1::shared_ptr<T> value_pointer; typedef std::tr1::weak_ptr<T> value_weak_pointer; typedef std::set<value_pointer> set_type; typedef std::vector<value_pointer> vector_type; typedef epicsMutex mutex_type; typedef epicsGuard<epicsMutex> guard_type; typedef epicsGuardRelease<epicsMutex> release_type; private: struct weak_less { bool operator()(const value_weak_pointer& lhs, const value_weak_pointer& rhs) const { value_pointer LHS(lhs.lock()), RHS(rhs.lock()); return LHS && RHS && LHS.get() < RHS.get(); } bool operator()(const value_pointer& lhs, const value_weak_pointer& rhs) const { value_pointer RHS(rhs.lock()); return RHS && lhs.get() < RHS.get(); } bool operator()(const value_weak_pointer& lhs, const value_pointer& rhs) const { value_pointer LHS(lhs.lock()); return LHS && LHS.get() < rhs.get(); } }; typedef std::set<value_weak_pointer, weak_less> store_t; struct data { mutex_type mutex; store_t store; }; std::tr1::shared_ptr<data> _data; //! Destroyer for a chained shared_ptr //! which holds the unique() real strong //! refrence to the object struct dtor { std::tr1::weak_ptr<data> container; value_pointer realself; dtor(const std::tr1::weak_ptr<data>& d, const value_pointer& w) :container(d), realself(w) {} void operator()(value_type *) { value_pointer R; R.swap(realself); assert(R.unique()); std::tr1::shared_ptr<data> C(container.lock()); if(C) { guard_type G(C->mutex); C->store.erase(R); } /* A subtle gotcha may exist since this struct * may not be destructed until the *weak* * count of the enclosing shared_ptr goes * to zero. Which won't happen * as long as we hold a weak ref to the * container holding a weak ref to us. * It is *essential* that we break this * "weak ref. loop" explicitly */ container.reset(); } }; public: //! Construct a new empty set weak_set() :_data(new data) {} private: //! Not copyable weak_set(const weak_set& O); //! Not copyable weak_set& operator=(const weak_set& O); public: //! exchange the two sets. //! @warning Not thread safe (exchanges mutexes as well) void swap(weak_set& O) { _data.swap(O._data); } //! Remove all (weak) entries from the set //! @note Thread safe void clear() { guard_type G(_data->mutex); return _data->store.clear(); } //! Test if set is empty //! @note Thread safe //! @warning see size() bool empty() const { guard_type G(_data->mutex); return _data->store.empty(); } //! number of entries in the set at this moment //! @note Thread safe //! @warning May be momentarily inaccurate (larger) due to dead refs. //! which have not yet been removed. size_t size() const { guard_type G(_data->mutex); return _data->store.size(); } //! Insert a new entry into the set //! The callers shared_ptr must be unique() //! and is (transparently) replaced with another void insert(value_pointer&); //! Remove any (weak) ref to this object from the set //! @returns the number of objects removed (0 or 1) size_t erase(value_pointer& v) { guard_type G(_data->mutex); return _data->store.erase(v); } //! Return a set of strong references to all entries //! @note that this allocates a new std::set and copies all entries set_type lock_set() const; //! Return a vector of strong references to all entries //! Useful for iteration //! @note that this allocates a new std::set and copies all entries vector_type lock_vector() const; void lock_vector(vector_type&) const; //! Access to the weak_set internal lock //! for use with batch operations. //! @warning Use caution when swap()ing while holding this lock! inline epicsMutex& mutex() const { return _data->mutex; } //! an iterator-ish object which also locks the set during iteration struct XIterator { weak_set& set; epicsGuard<epicsMutex> guard; typename store_t::iterator it, end; XIterator(weak_set& S) :set(S), guard(S.mutex()), it(S._data->store.begin()), end(S._data->store.end()) {} //! yield the next live entry value_pointer next() { value_pointer ret; while(it!=end) { ret = (it++)->lock(); if(ret) break; } return ret; } private: XIterator(const XIterator&); XIterator& operator=(const XIterator&); }; typedef XIterator iterator; }; template<typename T> void weak_set<T>::insert(value_pointer &v) { if(!v.unique()) throw std::invalid_argument("Only unique() references may be inserted"); guard_type G(_data->mutex); typename store_t::const_iterator it = _data->store.find(v); if(it==_data->store.end()) { // new object // wrapped strong ref. which removes from our map value_pointer chainptr(v.get(), dtor(_data, v)); _data->store.insert(chainptr); v.swap(chainptr); // we only keep the chained pointer } else { // already stored, no-op // paranoia, if already inserted then this should be a wrapped ref. // but not sure how to check this so update arg. with known wrapped ref. v = value_pointer(*it); // could throw bad_weak_ptr, but really never should } } template<typename T> typename weak_set<T>::set_type weak_set<T>::lock_set() const { set_type ret; guard_type G(_data->mutex); for(typename store_t::const_iterator it=_data->store.begin(), end=_data->store.end(); it!=end; ++it) { value_pointer P(it->lock()); if(P) ret.insert(P); } return ret; } template<typename T> typename weak_set<T>::vector_type weak_set<T>::lock_vector() const { vector_type ret; lock_vector(ret); return ret; } template<typename T> void weak_set<T>::lock_vector(vector_type& ret) const { guard_type G(_data->mutex); ret.reserve(_data->store.size()); for(typename store_t::const_iterator it=_data->store.begin(), end=_data->store.end(); it!=end; ++it) { value_pointer P(it->lock()); if(P) ret.push_back(P); } } #endif // WEAKSET_H
true
c39c5a9eadace687a214b2da64d38bade1a7bc78
C++
rishabh-live/oop-w-cpp-4-sem
/Labs/Lab 8/q2.cpp
UTF-8
746
4.0625
4
[]
no_license
// using friend function #include <bits/stdc++.h> using namespace std; int i = 1; class myclass { float a; public: void getdata(void) { cout << "Enter number " << i << " : "; cin >> a; i++; } friend myclass operator / (myclass a, myclass b) { myclass temp; temp.a = a.a / b.a; return (temp); } friend myclass operator * (myclass a, myclass b) { myclass temp; temp.a = a.a * b.a; return (temp); } void display(void) { cout << "Result = " << a << "\n"; } }; int main() { myclass c1, c2, c3; c1.getdata(); c2.getdata(); cout << "Performing muliplication\n"; c3 = c1 * c2; c3.display(); cout << "Performing division\n"; c3 = c1 / c2; c3.display(); return 0; }
true
137064f0e084021a1e5059e1d1a793b56429b042
C++
algoriddle/cp
/uva/01203.cc
UTF-8
552
2.71875
3
[ "MIT" ]
permissive
#include <iostream> #include <queue> #include <tuple> #include <vector> using namespace std; typedef tuple<int, int, int> query; int main() { ios::sync_with_stdio(false); string cmd; priority_queue<query, vector<query>, greater<query>> heap; while (cin >> cmd && cmd != "#") { int n, p; cin >> n >> p; heap.push(query(p, n, p)); } int k; cin >> k; while (k--) { query q = heap.top(); heap.pop(); cout << get<1>(q) << endl; heap.push(query(get<0>(q) + get<2>(q), get<1>(q), get<2>(q))); } return 0; }
true
5c625c4dd721c812f676ca17fcfcd41b42b456d4
C++
mike9304/schoolWorks
/programming_language/HW(108)/Homework1/ext/nana/include/nana/gui/widgets/panel.hpp
UTF-8
1,869
2.703125
3
[ "BSL-1.0" ]
permissive
/** * A Panel Implementation * Nana C++ Library(http://www.nanaro.org) * Copyright(C) 2003-2017 Jinhao(cnjinhao@hotmail.com) * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * @file: nana/gui/widgets/panel.hpp * @author: Jinhao * @contributors: Ariel Vina-Rodriguez * * @brief panel is a widget used for placing some widgets. */ #ifndef NANA_GUI_WIDGETS_PANEL_HPP #define NANA_GUI_WIDGETS_PANEL_HPP #include "widget.hpp" #include <type_traits> namespace nana { namespace drawerbase { namespace panel { class drawer: public drawer_trigger { void attached(widget_reference, graph_reference) override; void refresh(graph_reference) override; private: window window_{nullptr}; }; }// end namespace panel }//end namespace drawerbase /// For placing other widgets, where the bool template parameter determinte if it is widget or lite_widget, wich in actual use make no difference. template<bool HasBackground> class panel : public widget_object<typename std::conditional<HasBackground, category::widget_tag, category::lite_widget_tag>::type, drawerbase::panel::drawer> { public: panel(){} panel(window wd, bool visible) { this->create(wd, rectangle(), visible); this->bgcolor(API::bgcolor(wd)); } panel(window wd, const nana::rectangle& r = rectangle(), bool visible = true) { this->create(wd, r, visible); this->bgcolor(API::bgcolor(wd)); } bool transparent() const { return API::is_transparent_background(*this); } void transparent(bool tr) { if(tr) API::effects_bground(*this, effects::bground_transparent(0), 0); else API::effects_bground_remove(*this); } }; }//end namespace nana #endif
true
5ed843e08b99c5ab058201a7055046b6a81a9983
C++
jhoacar/algo2-tp2
/src/funcionalidades/Lista.h
UTF-8
3,242
3.75
4
[]
no_license
#ifndef LISTA_H #define LISTA_H #include "Nodo.h" template <class Dato> class Lista { protected: Nodo<Dato> *inicio; Nodo<Dato> *fin; unsigned long tamano; public: Lista(); /* PRE: POST: Libera la memoria reservada */ ~Lista(); /* PRE: Un dato a cargar en la lista POST: Almacena en la ultima posicion el dato */ void agregar(Dato dato); /* PRE: Un indice del objeto a eliminar de la lista POST: Busca el dato del indice, caso afirmativo lo elimina de la lista y devuelve verdadero caso contrario devuelve falso */ bool eliminar(const int indice); /* PRE: POST: Obtiene el tamaño de la lista */ unsigned long obtener_tamano(); /* PRE: Un indice a buscar POST: Retorna verdadero si es un indice perteneciente a la lista, falso caso contrario */ bool es_valido(const int indice); /* PRE: Un indice a buscar POST: Retorna el nodo encontrado en dicho indice */ Nodo<Dato>* buscar_nodo(const int indice); /* PRE: Un indice a buscar el nodo POST: Retorna el dato encontrado en dicho indice */ Dato operator[](const int indice); /* PRE: Una Lista a asignar POST: Carga toda la informacion de la lista del parametro */ void operator=(const Lista); }; template <class Dato> Lista<Dato>::Lista() { this->inicio = new Nodo<Dato>(); this->fin=this->inicio; this->tamano=0; } template <class Dato> Lista<Dato>::~Lista() { Nodo<Dato> *tmp; while( inicio!=nullptr ) { tmp = inicio; inicio = inicio->siguiente; delete tmp; } } template <class Dato> void Lista<Dato>::agregar(Dato dato){ *fin->dato=dato; fin->siguiente = new Nodo<Dato>(); fin=fin->siguiente; tamano+=1; } template <class Dato> bool Lista<Dato>::eliminar(const int indice){ Nodo<Dato> *nodo_eliminar = buscar_nodo(indice); if(nodo_eliminar == nullptr) //Si no se encuentra en la lista no se elimina return false; Nodo<Dato> *anterior = buscar_nodo(indice-1); if(anterior==nullptr) // Si no tiene antecesor entonces se encuentra en el inicio inicio = nodo_eliminar->siguiente; //Se referencia al que sigue else if(nodo_eliminar->siguiente == nullptr)// Si en el que sigue no hay nada, se encuentra al final fin = anterior; else //Se deja de referenciar anterior->siguiente = nodo_eliminar->siguiente; delete nodo_eliminar; tamano--; return true; } template <class Dato> unsigned long Lista<Dato>::obtener_tamano(){ return tamano; } template <class Dato> bool Lista<Dato>::es_valido(const int indice){ return indice >= 0 && indice <= (int)tamano; } template <class Dato> Nodo<Dato>* Lista<Dato>::buscar_nodo(const int indice){ if(!es_valido(indice)) return nullptr; Nodo<Dato> *aux = inicio; Nodo<Dato> *nodo; int i=0; nodo=aux; while(aux!=nullptr && i <= indice){ nodo=aux; aux=aux->siguiente; i++; } return nodo; } template <class Dato> Dato Lista<Dato>::operator[](const int indice){ Nodo<Dato> *nodo = buscar_nodo(indice); if(nodo != nullptr) return *(nodo->dato); return nullptr; } template <class Dato> void Lista<Dato>::operator=(const Lista<Dato> lista){ this->inicio = lista.inicio; this->fin = lista.fin; this->tamano = lista.tamano; } #endif
true
3dba7699f966373025a2cfc889fd49f60f2361ca
C++
kentril0/OpenGL_Atmospheric_Scattering
/src/scene/camera.cpp
UTF-8
4,117
2.875
3
[ "Apache-2.0" ]
permissive
/********************************************************** * < Interactive Atmospheric Scattering > * @author Martin Smutny, xsmutn13@stud.fit.vutbr.cz * @date April, 2021 * @file camera.cpp * @brief FPS Camera abstraction *********************************************************/ #include "core/pch.hpp" #include "core/application.hpp" // Indicies to array of active move states #define KEY_FORWARD GLFW_KEY_W #define KEY_BACKWARD GLFW_KEY_S #define KEY_RIGHT GLFW_KEY_D #define KEY_LEFT GLFW_KEY_A Camera::Camera(float aspect_ratio, const glm::vec3& pos, const glm::vec3& up, const glm::vec3& front, float yaw, float pitch) : m_position(pos), m_front(front), m_up(up), m_aspectRatio(aspect_ratio), m_fov(glm::radians(60.)), m_nearPlane(DEFAULT_NEAR_PLANE), m_farPlane(DEFAULT_FAR_PLANE), m_yaw(glm::mod(yaw, MAX_YAW_DEG)), m_pitch(glm::clamp(pitch, MIN_PITCH_DEG, MAX_PITCH_DEG)), m_lastX(0), m_lastY(0), m_firstCursor(true), m_isForward(false), m_isBackward(false), m_isRight(false), m_isLeft(false), m_isSpeedUp(false), m_angle(0) { update(); } void Camera::on_mouse_move(double x, double y) { // First time the cursor entered the screen, prevents jumps if (m_firstCursor) { m_lastX = static_cast<int>(x); m_lastY = static_cast<int>(y); m_firstCursor = false; } // Calculate the offset movement between the last and current frame float dx = float(x - m_lastX) * MOUSE_SENSITIVITY; float dy = float(m_lastY - y) * MOUSE_SENSITIVITY; m_lastX = static_cast<int>(x); m_lastY = static_cast<int>(y); m_pitch += dy; m_pitch = glm::clamp(m_pitch, MIN_PITCH_DEG, MAX_PITCH_DEG); m_yaw = glm::mod(m_yaw + dx, MAX_YAW_DEG); update(); } void Camera::update() { // calculate the new front vector m_front.x = cosf(glm::radians(m_yaw)) * cosf(glm::radians(m_pitch)); m_front.y = sinf(glm::radians(m_pitch)); m_front.z = sinf(glm::radians(m_yaw)) * cosf(glm::radians(m_pitch)); m_front = glm::normalize(m_front); // re-calculate the right and up vector // normalize because their length gets closer to 0 the more you look up or down // -> results in slower movement m_right = glm::normalize(glm::cross(m_front, WORLD_UP)); m_up = glm::normalize(glm::cross(m_right, m_front)); } void Camera::update(float dt) { float velocity = MOVE_SPEED * dt; m_position += m_isForward * m_front * (velocity + m_isSpeedUp * velocity * SPEEDUP_MUL); m_position -= m_isBackward * m_front * velocity; m_position += m_isRight * m_right * velocity; m_position -= m_isLeft * m_right * velocity; } void Camera::updateAnim(float dt, float radius) { float velocity = MOVE_SPEED * 0.005 * dt; m_angle = glm::mod(m_angle + velocity, MAX_YAW_DEG); m_position.y = -sinf(m_angle) * radius; m_position.z = -cosf(m_angle) * radius; m_front = glm::vec3(0, m_position.z, -m_position.y); } void Camera::on_mouse_button(int button, int action, int mods) { } // TODO <UNUSED> void Camera::on_key_pressed(int key, int action) { // TODO later hash map if (action == GLFW_PRESS) { if (key == KEY_CAM_FORWARD) m_isForward = true; else if (key == KEY_CAM_BACKWARD) m_isBackward = true; else if (key == KEY_CAM_RIGHT) m_isRight = true; else if (key == KEY_CAM_LEFT) m_isLeft = true; else if (key == KEY_CAM_SPEEDUP) m_isSpeedUp = true; else if (key == KEY_CAM_RCURSOR) // Reset cursor key_reset(action); } else //if (action == GLFW_RELEASE) { if (key == KEY_CAM_FORWARD) m_isForward = false; else if (key == KEY_CAM_BACKWARD) m_isBackward = false; else if (key == KEY_CAM_RIGHT) m_isRight = false; else if (key == KEY_CAM_LEFT) m_isLeft = false; else if (key == KEY_CAM_SPEEDUP) m_isSpeedUp = false; } }
true
d686ee4d621b266ceacf45aec13fb7ed7e3c83ab
C++
Seungchul-Han/algorithm
/practice/algospot/fan_meeting/fan_meeting.cpp
UTF-8
2,108
2.953125
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; vector<int> multiply(const vector<int>& a, const vector<int>& b) { vector<int> c(a.size() + b.size(), 0); for (int i = 0; i < a.size(); ++i) for (int j = 0; j < b.size(); ++j) c[i + j] += a[i] * b[j]; return c; } vector<int>& operator+(vector<int>& a, vector<int>& b) { a.resize(max(a.size(), b.size())); for (int i = 0; i < b.size(); ++i) a[i] += b[i]; return a; } vector<int>& operator-(vector<int>& a, vector<int>& b) { a.resize(max(a.size(), b.size())); for (int i = 0; i < b.size(); ++i) a[i] -= b[i]; return a; } vector<int> karatsuba(vector<int>& a, vector<int>& b) { if (a.empty() || b.empty()) return vector<int>(); if (a.size() < b.size()) return karatsuba(b, a); if (a.size() <= 50) return multiply(a, b); int m = (a.size() / 2); vector<int> a1(begin(a), begin(a) + m); vector<int> a0(begin(a) + m, end(a)); vector<int> b1(begin(b), begin(b) + min<int>(b.size(), m)); vector<int> b0(begin(b) + min<int>(b.size(), m), end(b)); vector<int> z0 = karatsuba(a1, b1); vector<int> z2 = karatsuba(a0, b0); vector<int> z1 = karatsuba(a1 + a0, b1 + b0); z1 - z0 - z2; vector<int> ret(begin(z0), end(z0)); ret.resize(max(m + z1.size(), ret.size())); for (int i = 0; i < z1.size(); ++i) ret[m+i] += z1[i]; ret.resize(max(2 * m + z2.size(), ret.size())); for (int i = 0; i < z2.size(); ++i) ret[2*m+i] += z2[i]; return ret; } int solve(string& mem, string& fan) { vector<int> m(mem.size()), f(fan.size()); for (int i = 0; i < mem.size(); ++i) m[i] = (mem[mem.size() - i - 1] == 'M') ? 1 : 0; for (int i = 0; i < fan.size(); ++i) f[i] = (fan[i] == 'M') ? 1 : 0; int count = 0; vector<int> ret = karatsuba(f, m); for (int i = m.size()-1; i < f.size(); ++i) { if (ret[i] == 0) count++; } return count; } int main() { int T; cin >> T; while (T--) { string mem, fan; cin >> mem >> fan; cout << solve(mem, fan) << endl; } }
true
343de38fad0021988135e56d620325ed430d808c
C++
MarkusEson/GUI-Projekt-Januari
/GUI-Projekt-Januari/JanuariYahtzee/gamebrain.h
UTF-8
531
2.609375
3
[]
no_license
#ifndef GAMEBRAIN_H #define GAMEBRAIN_H // #include <iostream> #include <algorithm> #include <QDebug> #include <stdlib.h> #include <time.h> class Die { public: Die(); ~Die(); void setValue(int newValue); int getValue(); bool checkIsChecked(); private: int _value = 6; bool _isChecked = 0; }; class GameBrain { public: GameBrain(); ~GameBrain(); void rollDice(); int *getDiceArray(); private: Die _diceArray[5]; }; #endif // GAMEBRAIN_H
true
e7c3af064041b5d384b69e28289985becf6826cb
C++
zhaoxuyan/leetcode_cpp
/DataStructure/0020-valid-parentheses.cpp
UTF-8
956
3.8125
4
[]
no_license
/* * 20. 有效括号 * * 用栈来解决 */ #include <algorithm> #include <iostream> #include <stack> #include <unordered_map> #include <vector> using namespace std; class Solution { private: stack<char> stack; unordered_map<char, char> map = { {'(', ')'}, {'{', '}'}, {'[', ']'}, }; public: bool isValid(string s) { for (auto& c : s) { if (map.count(c)) { // 如果是正括号 stack.push(c); } else { // 如果是反括号 // 注意条件有两个: // 1. 如果此时栈为空 说明没有正括号能跟这个反括号匹配 return false // 2. 栈顶的括号不匹配 if (stack.empty() || map[stack.top()] != c) return false; // 记得c++要手动pop stack.pop(); } } return stack.empty(); } };
true
60aea444eb30bbbc78d9b0b056b47671b0b540dd
C++
ChrisMugwagwa/PhysicsEngineCplusplus
/physicsEngineLab/src/worldobject.cpp
UTF-8
3,152
3.03125
3
[]
no_license
#include "worldobject.h" #include "ofApp.h" #include <iostream> #include <cmath> // std::abs WorldObject::WorldObject() { dx = 0; dy = 0; y = 0; // top of the screnn. x = 0; // left of the screen. diameter = 10; // assuming a naive shape for now... spring = 0.05; friction = -0.9; } WorldObject::WorldObject(float _diameter) { dx = 0; dy = 0; y = 0; // top of the screnn. x = 0; // left of the screen. diameter = _diameter; // assuming a naive shape for now... spring = 0.05; friction = -0.9; } const float WorldObject::getY(){ return y; } const float WorldObject::getX(){ return x; } const float WorldObject::getDiameter(){ return diameter; } void WorldObject::setPosition(float _x, float _y){ x = _x; y = _y; } void WorldObject::move(){ x += dx; y += dy; } void WorldObject::moveAndBounceOffWalls(float width, float height){ x += dx; y += dy; if (x + diameter/2 > width) { x = width - diameter/2; dx *= friction; } else if (x - diameter/2 < 0) { x = diameter/2; dx *= friction; } if (y + diameter/2 > height) { y = height - diameter/2; dy *= friction; } else if (y - diameter/2 < 0) { y = diameter/2; dy *= friction; } } void WorldObject::applyImpulseForce(float _dx, float _dy){ dx += _dx; dy += _dy; } bool WorldObject::hasCollided(WorldObject* other){ float dist_x = other->x - x; float dist_y = other->y - y; float distance = sqrt(dist_x*dist_x + dist_y*dist_y); float minDist = other->diameter/2 + diameter/2; if (distance < minDist) { return true; } else{ return false; } } void WorldObject::processCollisionImpulse(WorldObject* other){ float dist_x = other->x - x; float dist_y = other->y - y; //float distance = sqrt(dist_x*dist_x + dist_y*dist_y); float minDist = other->diameter/2 + diameter/2; //if (distance < minDist) { float angle = atan2(dist_y, dist_x); float targetX = x + cos(angle) * minDist; float targetY = y + sin(angle) * minDist; float ax = (targetX - other->x) * spring; float ay = (targetY - other->y) * spring; dx -= ax; dy -= ay; other->dx += ax; other->dy += ay; } void WorldObject::computeCollisionAndImpulse(WorldObject* other){ float dist_x = other->x - x; float dist_y = other->y - y; float distance = sqrt(dist_x*dist_x + dist_y*dist_y); float minDist = other->diameter/2 + diameter/2; if (distance < minDist) { float angle = atan2(dist_y, dist_x); float targetX = x + cos(angle) * minDist; float targetY = y + sin(angle) * minDist; float ax = (targetX - other->x) * spring; float ay = (targetY - other->y) * spring; dx -= ax; dy -= ay; other->dx += ax; other->dy += ay; } } void WorldObject::stop(){ dx = 0; dy = 0; } Ball::Ball(float diameter, float r, float g, float b) { } void Ball::draw() { ofSetColor(red, green, blue); ofDrawCircle(posx, posy, radi); } void Ball::setPosition(float x,float y) { posx = x; posy = y; }
true
ef3ab0837f9103956eb32def7b0a02ca60212794
C++
Antonija5654/oop_vjezbe
/Vjezba6/Zadatak/fun.cpp
UTF-8
2,861
3.21875
3
[]
no_license
#include <iostream> #include <math.h> #include "Header.h" using namespace OOP; int Vec3::counter = 0; std::istream& OOP::operator >> (istream& a, Vec3& vektor) { std::cout << "upisi x1, y1, z1, x2, y2, z2" << std::endl; a >> vektor.x1 >> vektor.y1 >> vektor.z1 >> vektor.x2 >> vektor.y2 >> vektor.z2; return a; } std::ostream& OOP::operator << (ostream& a, Vec3& vektor) { a << "x1: " << vektor.x1 << " " << "y1: " << vektor.y1 << " " << "z1: " << vektor.z1 << " " << "x2: " << vektor.x2 << " " << "y2: " << vektor.y2 << " " << "z2: " << vektor.z2 << std::endl; return a; } Vec3 Vec3::operator = (Vec3 vektor) { x1 = vektor.x1; y1 = vektor.y1; z1 = vektor.z1; x2 = vektor.x2; y2 = vektor.y2; z2 = vektor.z2; return *this; } Vec3 Vec3::operator + (Vec3 vektor) { Vec3 novi(x1, y1, z1, vektor.x2, vektor.y2, vektor.z2); return novi; } Vec3 Vec3::operator - (Vec3 vektor) { Vec3 novi(x1, y1, z1, vektor.x1, vektor.y1, vektor.z1); return novi; } Vec3 Vec3::operator * (int br) { Vec3 novi(x1, y1, z1, x2*br, y2*br, z2*br); return novi; } Vec3 Vec3::operator / (int br) { Vec3 novi(x1, y1, z1, x2 / br, y2 / br, z2 / br); return novi; } Vec3 Vec3::operator += (Vec3 vektor) { x2 = vektor.x2; y2 = vektor.y2; z2 = vektor.z2; return *this; } Vec3 Vec3::operator -= (Vec3 vektor) { x2 = vektor.x1; y2 = vektor.y1; z2 = vektor.z1; return *this; } Vec3 Vec3::operator *= (int br) { x2 = x2 * br; y2 = y2 * br; z2 = z2 * br; return *this; } Vec3 Vec3::operator /= (int br) { x2 = x2 / br; y2 = y2 / br; z2 = z2 / br; return *this; } bool Vec3::operator == (Vec3 vektor) { if (x1 == vektor.x1 && y1 == vektor.y1 && z1 == vektor.z1 && x2 == vektor.x2 && y2 == vektor.y2 && z1 == vektor.z2) return true; else return false; } bool Vec3::operator != (Vec3 vektor) { if (x1 != vektor.x1 || y1 != vektor.y1 || z1 != vektor.z1 || x2 != vektor.x2 || y2 != vektor.y2 || z1 != vektor.z2) return true; else return false; } int Vec3::operator * (Vec3 vektor) { return (x2 - x1)*(vektor.x2 - vektor.x1) + (y2 - y1)*(vektor.y2 - vektor.y1) + (z2 - z1)*(vektor.z2 - vektor.z1); } int Vec3::operator [] (std::string str) { if (str.compare("0") == 0 || str.compare("x1") == 0) return x1; else if (str.compare("1") == 0 || str.compare("y1") == 0) return y1; else if (str.compare("2") == 0 || str.compare("z1") == 0) return z1; else if (str.compare("3") == 0 || str.compare("x2") == 0) return x2; else if (str.compare("4") == 0 || str.compare("y2") == 0) return y2; else if (str.compare("5") == 0 || str.compare("z2") == 0) return z2; } Vec3 Vec3::normaliziraj() { float rez = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1) + (z2 - z1)*(z2 - z1)); x2 = x1 + ((x2 - x1) / rez); y2 = y1 + ((y2 - y1) / rez); z2 = z1 + ((z2 - z1) / rez); return *this; } int Vec3::vrati_counter() { return counter; }
true
ada675894c220e98b011ce7f73dd314dc2f73fc0
C++
x-fer/xfer-natpro
/2010/2_mi/jednakost/jednakost.cpp
UTF-8
585
2.78125
3
[]
no_license
#include <cstdio> using namespace std; const int MOD = 1000000007; const int N = 100000; typedef long long llint; llint power_mod(llint a, llint b, llint mod) { if (b == 0) return 1; if (b & 1) return a * power_mod(a * a % mod, b / 2, mod) % mod; return power_mod(a * a % mod, b / 2, mod); } int main(void) { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); for (int mod = MOD; mod < MOD + N; ++mod) { if (power_mod(a, b, mod) != power_mod(c, d, mod)) { puts("NE"); return 0; } } puts("DA"); return 0; }
true
e59172f5bfdcbf235c82f5a7e0c2911f4e86219c
C++
lee-jisung/Algorithm-study
/백준/2842번 집배원 한상덕/2842.cpp
UTF-8
2,362
2.921875
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <cstring> #include <queue> #include <vector> #include <deque> #include <cmath> #define SIZE 51 #define INF 987654321 using namespace std; /* BFS + inchworm 고도시작지점, 끝지점을 한칸식 늘려주면서 배달이 가능한 경우 고도차의 최소값을 찾는다 */ struct NODE { int r, c; }; int n, str, stc, k_num, cnt, front, rear, res; char map[SIZE][SIZE]; int altitude[SIZE][SIZE]; bool isVisit[SIZE][SIZE], h[1000001]; int dx[9] = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }; int dy[9] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; vector<int> height; bool isRange(int r, int c) { return r >= 0 && c >= 0 && r < n && c < n; } void bfs() { cnt = 0; memset(isVisit, false, sizeof(isVisit)); queue<NODE> q; q.push({ str, stc}); isVisit[str][stc]= true; while (!q.empty()) { int r = q.front().r; int c = q.front().c; q.pop(); for (int i = 0; i < 9; i++) { int nr = r + dx[i]; int nc = c + dy[i]; if (!isRange(nr, nc)) continue; // 현재 및 다음 좌표의 고도값이 설정된 범위인지 확인 if (altitude[r][c] >= height[front] && altitude[r][c] <= height[rear] && altitude[nr][nc] >= height[front] && altitude[nr][nc] <= height[rear]) { if (!isVisit[nr][nc]) { if (map[nr][nc] == 'K') cnt++; q.push({ nr,nc }); isVisit[nr][nc] = true; } } } } } int main(void) { cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { scanf(" %1c", &map[i][j]); if (map[i][j] == 'P') str = i, stc = j; if (map[i][j] == 'K') k_num++; } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { cin >> altitude[i][j]; if (!h[altitude[i][j]]) { height.push_back(altitude[i][j]); h[altitude[i][j]] = true; } } sort(height.begin(), height.end()); res = INF; // front - min, rear - max를 각각 가르키게 하고 배달 가능한 경우에 한하여 // 고도차의 최솟값 찾기 while (front <= rear && rear < height.size()) { bfs(); // bfs를 돌려 k개의 집을 모두 방문하지 못한 경우 rear를 늘려줌 if (cnt != k_num) { rear++; } //bfs를 돌려 k개의 집을 모두 방문한 경우 front를 하나 높임 else { res = min(res, (height[rear] - height[front])); front++; } } cout << res << "\n"; return 0; }
true
328d0e6303ac712b0dc590ffb6707b8fcb569583
C++
longf0720/atoffer
/3/subtree.cpp
UTF-8
1,587
3.65625
4
[]
no_license
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: bool isSame(TreeNode * T1, TreeNode * T2) { if(T1 == NULL && T2 == NULL) return true; else if (T1 != NULL && T2 == NULL) return false; else if (T1 == NULL && T2 != NULL) return false; if(T1->val == T2->val) { if(isSame(T1->left, T2->left)){ if(isSame(T1->right, T2->right)) { return true; } } } return false; } bool next(TreeNode * T1, TreeNode * T2) { if(isSubtree(T1->left, T2)) { return true; } else if(isSubtree(T1->right, T2)) { return true; } else { return false; } } /* * @param T1: The roots of binary tree T1. * @param T2: The roots of binary tree T2. * @return: True if T2 is a subtree of T1, or false. */ bool isSubtree(TreeNode * T1, TreeNode * T2) { // write your code here if(T1 == NULL && T2 == NULL) return true; else if(T1 == NULL && T2 != NULL) return false; else if(T1 != NULL && T2 == NULL) return true; if(T1->val == T2->val) { if(isSame(T1, T2)) { return true; } else { return next(T1, T2); } } else { return next(T1, T2); } } };
true
f59b1d3926acbacd0397a50f6555e283917c665d
C++
sczembor/projekt_wymiana_walut
/Authorization.cpp
UTF-8
1,848
3.015625
3
[]
no_license
// // Login.cpp // wymiana_walut // // Created by Stanislaw Czembor on 23/11/2019. // Copyright © 2019 Stanislaw Czembor. All rights reserved. // #include "Authorization.hpp" authorization::authorization(const std::string & p_username, const std::string & p_password) { username = p_username; password = p_password; userId = 0;//wartosc 0 jest niepoprawna wartością i nie odpowiada zadnemu uzytkownikowi loginStatus = VerifyLogin(); if(loginStatus) { std::cout<<"znaleziono klienta o numerze identyfikacyjnym :"<< userId<<"\n"; } } authorization::authorization(const user & p_user) { username = p_user.GetUsername(); password = p_user.GetPassword(); userId = 0;//wartosc 0 jest niepoprawna wartością i nie odpowiada zadnemu uzytkownikowi loginStatus = VerifyLogin(); if(loginStatus) { std::cout<<"znaleziono klienta o numerze identyfikacyjnym :"<< userId<<"\n"; } } bool authorization::VerifyLogin() { bool accessGranted = false; std::string line; std::string f_username, f_password;//zmienne do przetrzymywania int f_userId; //wczytanych informacji z pliku std::ifstream f("log_info.txt"); if(f.is_open()) { while(!accessGranted && std::getline(f, line)) { std::istringstream iss(line); if(!(iss >> f_username >> f_password >> f_userId)) { //pusty wiersz } else if(username == f_username && password == f_password) { accessGranted = true; userId = f_userId; f.close(); return accessGranted; } } f.close();//zamknięcie pliku return accessGranted; } else { std::cout<<"file error :(\n "; } return accessGranted; }
true
9157abd2e8dd65a4b122060de22898829cd4604a
C++
jonathanirvings/tcframe
/include/tcframe/spec/io/GridIOSegment.hpp
UTF-8
2,320
2.953125
3
[ "MIT" ]
permissive
#pragma once #include <stdexcept> #include <tuple> #include "IOSegment.hpp" #include "tcframe/spec/variable.hpp" using std::runtime_error; using std::tie; namespace tcframe { struct GridIOSegment : public IOSegment { friend class GridIOSegmentBuilder; private: Matrix* variable_; int* rows_; int* columns_; public: GridIOSegment() : variable_(nullptr) , rows_(new int(-1)) , columns_(new int(-1)) {} IOSegmentType type() const { return IOSegmentType::GRID; } Matrix* variable() const { return variable_; } int* rows() const { return rows_; } int* columns() const { return columns_; } bool operator==(const GridIOSegment& o) const { if (variable_ != nullptr && o.variable_ != nullptr) { if (!variable_->equals(o.variable_)) { return false; } } if ((variable_ == nullptr) != (o.variable_ == nullptr)) { return false; } return tie(*rows_, *columns_) == tie(*o.rows_, *o.columns_); } bool equals(IOSegment* o) const { return o->type() == IOSegmentType::GRID && *this == *((GridIOSegment*) o); } }; class GridIOSegmentBuilder : public IOSegmentBuilder { private: GridIOSegment* subject_; public: GridIOSegmentBuilder() : subject_(new GridIOSegment()) {} GridIOSegmentBuilder& addMatrixVariable(Matrix* variable) { checkMatrix(); subject_->variable_ = variable; return *this; } GridIOSegmentBuilder& setSize(int* rows, int* columns) { subject_->rows_ = rows; subject_->columns_ = columns; return *this; } GridIOSegment* build() { checkState(); return subject_; } private: void checkMatrix() { if (subject_->variable_ != nullptr) { throw runtime_error("Grid segment must have exactly one variable"); } } void checkState() { if (subject_->variable_ == nullptr) { throw runtime_error("Grid segment must have exactly one variable"); } if (*subject_->rows_ == -1 || *subject_->columns_ == -1) { throw runtime_error("Grid segment must define matrix sizes"); } } }; }
true
a08665418d145ebe60d66db67c2e6650f0978a9b
C++
ayan978/vjudge
/CodeForces/854A - Fraction.cpp
UTF-8
241
2.75
3
[]
no_license
#include<iostream> using namespace std; int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } int main() { int n; cin>>n; for(int i=n/2;;i--) if(gcd(i,n-i)==1) { cout<<i<<" "<<n-i;break;} return 0; }
true
b12ec560db31bea9a5d201bfa1735834011d0996
C++
lkjfrf/Cplus-Study
/Cplus_Study/p232_5.cpp
UTF-8
269
3.140625
3
[]
no_license
//#include <iostream> //using namespace std; // //struct CandyBar //{ // char name[20]; // double weight; // int calory; //}; // // //int main() //{ // CandyBar snak = { "Mocha Munch", 2.3, 350 }; // // cout << snak.calory << ", " << snak.name << ", " << snak.weight; // //}
true
6ffd9c7d7c6d3f22065bfa837b30ba3705f5c110
C++
JamilGarcia/P3Lab2_JamilGarcia
/Main.cpp
UTF-8
3,340
3.484375
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <time.h> #include <cmath> #include <iomanip> using namespace std; int recursiva(double verticeX, double respuesta, int a, int b, int c, int cont){ if (cont >= 0){ respuesta = recursiva(verticeX, respuesta, a, b, c, cont-1) - ((a * (pow(verticeX, 2)) + (b*verticeX) + c) / (2*a*(verticeX) +b)); } else { cout << "Respuesta: " << respuesta; return respuesta; } } void ejercicio3(int limit, int cont, double pi) { if (cont <= limit) { pi = pi + ((pow(-1, cont)) / ((2 * cont) + 1)); //cout << cont << " = " << pi << endl; ejercicio3(limit, cont + 1, pi); } else if (cont > limit) { cout << "PI= " << pi * 4 << endl; } } int main() { int opcion; do { cout << "Menu: \n" << "1) Ejercicio 1 \n" << "2) Ejercicio 2 \n" << "3) Ejercicio 3 \n" << "0) Salir\n"; cin >> opcion; switch (opcion) { case 1: { cout << "Ejercicio 1\n"; int a, b, c; cout << "ingrese el valor de a: "; cin >> a; while (a == 0) { cout << "ingrese el valor de a: "; cin >> a; } cout << "ingrese el valor de b: "; cin >> b; cout << "ingrese el valor de c: "; cin >> c; double verticeX = (-1 * b) / (2*a); double verticeY = a * (pow(verticeX, 2)) + (b*verticeX) + c; recursiva(verticeX, 0, a, b, c, 0); } break; case 2: { cout << "Ejercicio 2\n"; int x = 9, temp; cout << "Ingrese el tamaño de la matriz: "; cin >> x; int matriz[x][x]; for (int i = 0; i < x; i++) { cout << "[ "; for (int j = 0; j < x; j++) { matriz[i][j] = 10 + rand() % (99 - 10); temp = temp + matriz[i][j]; cout << matriz[i][j] << " "; } cout << "] \n"; } double r, u, temp2; u = temp / (x * x); for (int i = 0; i < x; i++) { for (int j = 0; j < x; j++) { temp2 = matriz[i][j] - u; temp2 = pow(temp2, 2); r += temp2; } } r = r / x * x; r = sqrt(r); double matrixE[x][x]; for (int i = 0; i < x; i++) { cout << "[ "; for (int j = 0; j < x; j++) { matrixE[i][j] = (matriz[i][j] - u) / r; cout << setw(5) << matrixE[i][j] << " "; } cout << "] \n"; } } break; case 3: { cout << "Ejercicio 3\n"; cout << "Ingrese el limite de la sumatoria: "; int limit; double pi; cin >> limit; ejercicio3(limit, 0, 0); break; } default: break; } } while (opcion != 0); }
true
cd00e6f06e191ffb8e799801b042717a060d735e
C++
Jordan-1234/Team-A-TMR3M1
/dc_motors.ino
UTF-8
1,230
3.375
3
[]
no_license
/* PRIZM Controller example program * Spin DC motor channel 1 for 5 seconds, then coast to a stop. * After stopping, wait for 2 seconds, spin in opposite direction. * Continue to repeat until RED reset button is pressed. * author PWU on 08/05/2016 */ #include <PRIZM.h> // include the PRIZM library in the sketch PRIZM prizm; // instantiate a PRIZM object “prizm” so we can use its functions void setup() { prizm.PrizmBegin(); // Initialize the PRIZM controller } void loop() { // repeat in a loop prizm.setMotorPower(1,-25); // spin Motor 1 CW at 25% power delay(5000); // wait while the motor runs for 5 seconds prizm.setGreenLED(HIGH); prizm.setMotorPower(1,0); // stop motor (coast to stop) prizm.setGreenLED(LOW); delay(2000); // After stopping, wait here for 2 seconds prizm.setMotorPower(1,25); // spin Motor 1 CCW at 25% power delay(5000); prizm.setRedLED(HIGH); // wait while the motor runs for 5 seconds prizm.setMotorPower(1,0); // stop motor (coast to stop); prizm.setRedLED(LOW); delay(2000); // After stopping, wait here for 2 seconds, then repeat }
true
39cc99604a26f9c89adfb5ce2c7b129a3ef4b9d6
C++
zni/delta
/src/enemies.h
UTF-8
604
2.703125
3
[ "MIT" ]
permissive
#ifndef ENEMIES_H #define ENEMIES_H #include <vector> #include <SFML/Graphics.hpp> #include <SFML/System.hpp> struct Enemy { enum State { live, dead }; State state; sf::FloatRect aabb; sf::Sprite sprite; float speed; }; class Enemies { public: Enemies(const sf::Vector2u &bounds); ~Enemies(); void renderEnemies(sf::RenderWindow &window); void spawnEnemy(const sf::Vector3f &origin); void updateEnemies(); private: sf::Texture m_enemySheet; sf::FloatRect m_bounds; std::vector<Enemy*> m_enemies; }; #endif
true
69aa626ebbeb9700433052d2caeb35a00c652e89
C++
Born0/Academic-Code-Practice-AIUB-
/C & ++/CodeBlockes project/lab 3/main.cpp
UTF-8
613
3.5
4
[]
no_license
#include <iostream> using namespace std; class Box { float height,width,breadth; public: void input(float h,float w, float b) { height=h; width=w; breadth=b; } void show() { cout<<height<<endl<<width<<endl<<breadth<<endl; } void area() { cout<<"Area="<<height*width<<endl; } void volume() { cout<<"Volume="<<height*width*breadth<<endl; } }; int main() { float ht,wd,bt; cout<<"HT:"<<"WD:"<<"bt:"<<endl; cin>>ht>>wd>>bt; Box box1; box1.input(ht,wd,bt); box1.show(); box1.area(); box1.volume(); }
true
b9906f65e45390dcb2a46a0d866fa8fc58d528d0
C++
adigriever12/Robotics
/MapSearchNode.h
UTF-8
1,065
2.65625
3
[]
no_license
/* * MapSearchNode.h * * Created on: Jun 5, 2015 * Author: colman */ #ifndef MAPSEARCHNODE_H_ #define MAPSEARCHNODE_H_ #include "stlastar.h" #include "Map.h" class MapSearchNode { Map* _map; int _x; int _y; public: MapSearchNode() { _map = NULL; _x = _y = 0; }; MapSearchNode(int x, int y, Map* map) { _map = map; SetPosition(x, y); } virtual ~MapSearchNode(); int GetX() { return _x; } int GetY() { return _y; } void SetPosition(int x, int y) { _x = x; _y = y; } float GoalDistanceEstimate(MapSearchNode &nodeGoal); bool IsGoal(MapSearchNode &nodeGoal); bool GetSuccessors(AStarSearch<MapSearchNode>* aStarSearch, MapSearchNode* parentNode); bool AddSuccessor(int currentX, int currentY, int parentX, int parentY, AStarSearch<MapSearchNode>* aStarSearch); float GetCost(MapSearchNode &successor); bool IsSameState(MapSearchNode &node); }; #endif /* MAPSEARCHNODE_H_ */
true
cd4d5850add0addbc2aeecb8ad05d3f06780fb21
C++
sa4k5hi/Algorithms
/Graphs/undirected_cycle_finding_dfs.cpp
UTF-8
1,237
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define int long long #define pb push_back #define INF (1LL<<61) vector<int> adj[100005]; int vis[100005]; int parent[100005]; int st=-1,ed=-1; bool dfs(int v) { vis[v]=1; for(auto u :adj[v]) { if(u == parent[v]) continue; if(vis[u]!=1) { parent[u]=v; if(dfs(u)) return true; } else { st = u; ed = v; return true; } } return false; } signed main() { int n,m; cin>>n>>m; memset(vis,0,sizeof(vis)); parent[0]=0; for(int i=0;i<m;i++) { int x,y; cin>>x>>y; x--;y--; adj[x].pb(y); adj[y].pb(x); } bool flag=false; for(int i=0;i<n;i++) { if(vis[i]!=1) { if(dfs(i)) { flag=true; break; } } } if(flag) { cout<<"cycle present" <<endl; vector<int> res; for(int i=ed;i!=st;i=parent[i]) { res.pb(i); } res.pb(st); for(int i=0;i<res.size();i++) { cout<<res[i]+1<<endl; } } else { cout<<"no cycle"<<endl; } return 0; }
true
e9ef72949e621a743c00e6532b997ebc9e735a83
C++
iboB/word-grid
/server/code/server/util/LoadLanguageFromDir.cpp
UTF-8
2,792
2.515625
3
[ "MIT" ]
permissive
// word-grid // Copyright (c) 2019-2021 Borislav Stanimirov // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // https://opensource.org/licenses/MIT // #include "LoadLanguageFromDir.hpp" #include <core/Language.hpp> #include <core/LanguageBuilder.hpp> #include <core/LetterSequenceFromUtf8.hpp> #include <huse/json/Deserializer.hpp> namespace server::util { namespace { std::vector<char> readFile(const char* path) { auto f = fopen(path, "rb"); if (!f) return {}; int pos = ftell(f); fseek(f, 0, SEEK_END); size_t fileSize = ftell(f); fseek(f, pos, SEEK_SET); std::vector<char> r(fileSize); fread(r.data(), 1, fileSize, f); fclose(f); return r; } void deserializeSeqToScoreVec(huse::DeserializerNode& n, core::Alphabet& ab) { auto jab = n.obj(); for (auto q = jab.nextkey(); q; q = jab.nextkey()) { auto& elem = ab.emplace_back(); core::LetterSequence_FromUtf8(elem, q.name); q->val(elem.score); } } } // namespace core::Language loadLanguageFromDir(std::string_view dir) { std::string index = std::string(dir) + "/index.json"; auto buf = readFile(index.c_str()); core::LanguageBuilder b; auto d = huse::json::Deserializer::fromMutableString(buf.data(), buf.size()); auto obj = d.obj(); { std::string_view name; obj.val("name", name); b.setDisplayName(std::string(name)); } { uint32_t len; obj.val("min_word", len); b.setMinWordLength(len); } { core::Alphabet ab; obj.cval("alphabet", ab, deserializeSeqToScoreVec); b.setAlphabet(std::move(ab)); } { core::Specials sp; obj.cval("specials", sp, deserializeSeqToScoreVec); b.setSpecials(std::move(sp)); } { core::LetterConversionTable lt; auto jlt = obj.obj("conversion"); for (auto q = jlt.nextkey(); q; q = jlt.nextkey()) { core::LetterSequence<1> letter; letter.resize(1); core::LetterSequence_FromUtf8(letter, q.name); std::string_view utf8Target; q->val(utf8Target); core::LetterConversionTarget target; core::LetterSequence_FromUtf8(target, utf8Target); lt[letter.front()] = target; } b.setConversionTable(std::move(lt)); } { std::string dic; obj.val("dictionary", dic); std::string index = std::string(dir) + '/' + dic; auto buf = readFile(index.c_str()); b.setDictionaryUtf8Buffer(std::move(buf)); } auto res = b.getLanguage(); if (!res) throw std::runtime_error("Missing fields"); return std::move(*res); } } // namespace server::util
true
d86e870854e54db5a7b0a91adb96e225eff58399
C++
whdgmawkd/boj_algo
/boj/2312.cpp
UTF-8
566
2.90625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; bool prime[100001]; int main(void) { prime[0] = true; prime[1] = true; for (int a = 2; a <= 100000; a++) { if (!prime) { for (int b = a << 1; b <= 100000; b += a) { prime[b] = true; } } } int t; cin >> t; while (t--) { int n; cin >> n; for (int a = 2; a <= 100000; a++) { if (n == 1) break; if (prime[a]) continue; if (n%a == 0) { int cnt = 0; while (n%a == 0) { n /= a; cnt++; } cout << a << " " << cnt << '\n'; } } } return 0; }
true
943879bb832cfc90df997591ab0ddb01286b939e
C++
theAirC/lib
/System/Devices/MAX9939.h
UTF-8
3,220
2.53125
3
[]
no_license
//! Library for MAX9939 SPI PGA #pragma once #include <lib/System/Devices/Device_SPI.h> namespace System::Devices { struct MAX9939 : Device_SPI { enum struct Register : byte { Trim = 0, Gain = 1, }; enum struct Gain : byte { X1 = 0, X10 = 1, X20 = 2, X30 = 3, X40 = 4, X60 = 5, X80 = 6, X120 = 7, X157 = 8, X025 = 9, }; static constexpr byte Register_Trim_Vos_offset = 1; static constexpr byte Register_Trim_Vos_mask = 0x3E; static constexpr byte Register_Gain_Gain_offset = 1; static constexpr byte Register_Gain_Gain_mask = 0x1E; static constexpr byte Register_ANY_Meas_offset = 6; static constexpr byte Register_ANY_Meas_mask = 0x40; static constexpr byte Register_ANY_Shdn_offset = 7; static constexpr byte Register_ANY_Shdn_mask = 0x80; MAX9939(Peripherals::SPI &mySPI, GPIO::Output &chipSelect); void write(Register reg, byte value); void init(); void shutdown(); // Sets the Input offset voltage (Vos) trim to the specified <level> [-15..+15] // The actual voltage does not scale linearly with the <level>: // Level Vos(mV) // 0 0 // 1 1.3 // 2 2.5 // 3 3.8 // 4 4.9 // 5 6.1 // 6 7.3 // 7 8.4 // 8 10.6 // 9 11.7 // 10 12.7 // 11 13.7 // 12 14.7 // 13 15.7 // 14 16.7 // 15 17.6 // <measurementMode> (de)activates measurement mode: // input INA- is disconnected and shorted to INA+ // Note: changing the gain will deactivate measurement mode // Used to measure and compensate for Vos void setVos(s8 level, bool measurementMode = false); // Sets the gain void setGain(Gain gain); }; MAX9939::MAX9939(Peripherals::SPI &mySPI, GPIO::Output &chipSelect) : Device_SPI(mySPI, chipSelect) { } void MAX9939::write(Register reg, byte value) { transfer(value | (byte)reg); } void MAX9939::init() { write(Register::Trim, 0); write(Register::Gain, 0); } void MAX9939::shutdown() { write(Register::Trim, (1 << Register_ANY_Shdn_offset) & Register_ANY_Shdn_mask); } void MAX9939::setVos(s8 level, bool measurementMode) { byte vos = level >= 0 ? level : (-level | (1 << 4)); byte meas = measurementMode ? 1 : 0; byte reg = ((vos << Register_Trim_Vos_offset) & Register_Trim_Vos_mask) | ((meas << Register_ANY_Meas_offset) & Register_ANY_Meas_mask); write(Register::Trim, reg); } void MAX9939::setGain(Gain gain) { write(Register::Gain, ((byte)gain << Register_Gain_Gain_offset) & Register_Gain_Gain_mask); } }
true
7c780a264185ab25c75a63facff0cfd3e2866c99
C++
tingwei758/Quadris
/Block/Z_Block.cc
UTF-8
7,041
3.171875
3
[]
no_license
#include <iostream> #include "Z_Block.h" using namespace std; Z_Block::Z_Block(int level, char symbol, Board *gameBoard, std::vector<Cell *> occupiedCells) :Block{level, symbol, gameBoard, occupiedCells, "horizontal"} {} bool Z_Block::rotatable() { int x = this->occupiedCells.back()->getState().x; int y = this->occupiedCells.back()->getState().y; if(this->dir == "horizontal"){ for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y < y){ y = p->getState().y; } } if((x < 0|| x+1 > 10)||(y-1 < 0|| y+1 > 17)){ return false; } if(this->gameBoard->getCell(x, y+1).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+1, y-1).getState().isOccupied){ return false; } this->dir = "vertical"; } else { for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y > y){ y = p->getState().y; } } if((x < 0|| x+2 > 10)||(y < 0|| y > 17)){ return false; } if(this->gameBoard->getCell(x+1, y).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+2, y).getState().isOccupied){ return false; } this->dir = "horizontal"; } return true; } bool Z_Block::CCrotatable() { return this->rotatable(); } bool Z_Block::moveRight() { int x = this->occupiedCells.back()->getState().x; int y = this->occupiedCells.back()->getState().y; if(this->dir == "horizontal"){ for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y < y){ y = p->getState().y; } } if((x < 0|| x+3 > 10)||(y < 0|| y+1 > 17)){ return false; } if(this->gameBoard->getCell(x+2, y).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+3, y+1).getState().isOccupied){ return false; } } else { for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y > y){ y = p->getState().y; } } if((x < 0|| x+2 > 10)||(y-2 < 0|| y > 17)){ return false; } if(this->gameBoard->getCell(x+1, y).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+2, y-1).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+2, y-2).getState().isOccupied){ return false; } } return true; } bool Z_Block::moveLeft() { int x = this->occupiedCells.back()->getState().x; int y = this->occupiedCells.back()->getState().y; if(this->dir == "horizontal"){ for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y < y){ y = p->getState().y; } } if((x-1 < 0|| x > 10)||(y < 0|| y+1 > 17)){ return false; } if(this->gameBoard->getCell(x-1, y).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x, y+1).getState().isOccupied){ return false; } } else { for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y > y){ y = p->getState().y; } } if((x-1 < 0|| x > 10)||(y-2 < 0|| y > 17)){ return false; } if(this->gameBoard->getCell(x-1, y).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x-1, y-1).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x, y-2).getState().isOccupied){ return false; } } return true; } bool Z_Block::moveUpable(){ int x = this->occupiedCells.back()->getState().x; int y = this->occupiedCells.back()->getState().y; if(this->dir == "horizontal"){ for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y < y){ y = p->getState().y; } } if((x < 0|| x+2 > 10)||(y-1 < 0|| y > 17)){ return false; } if(this->gameBoard->getCell(x, y-1).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+1, y-1).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+2, y).getState().isOccupied){ return false; } } else { for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y > y){ y = p->getState().y; } } if((x < 0|| x+1 > 10)||(y-3 < 0|| y > 17)){ return false; } if(this->gameBoard->getCell(x+1, y-3).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x, y-2).getState().isOccupied){ return false; } } return true; } bool Z_Block::moveDown() { int x = this->occupiedCells.back()->getState().x; int y = this->occupiedCells.back()->getState().y; if(this->dir == "horizontal"){ for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y < y){ y = p->getState().y; } } if((x < 0|| x+2 > 10)||(y < 0|| y+2 > 17)){ return false; } if(this->gameBoard->getCell(x, y+1).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+1, y+2).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x+2, y+2).getState().isOccupied){ return false; } } else { for(auto &p:this->occupiedCells){ if(p->getState().x < x){ x = p->getState().x; } if(p->getState().y > y){ y = p->getState().y; } } if((x < 0|| x+1 > 10)||(y < 0|| y+1 > 17)){ return false; } if(this->gameBoard->getCell(x+1, y).getState().isOccupied){ return false; } else if(this->gameBoard->getCell(x, y+1).getState().isOccupied){ return false; } } return true; }
true
7b0cf9643dab0cce6c7856af469c1c8d5d5d217c
C++
VisaSimula/Projekti-WALL-i
/Koodi_WALL•I_V1.2.ino
UTF-8
11,755
2.859375
3
[]
no_license
#include <SD.h> // Include SD module library. -VS #include <TMRpcm.h> // Include library for speaker control. -VS #define SD_ChipSelectPin 4 // Defining CS pin. -VS #define enable 5 // Defining enable pin (L298N driver). -VS #define in1 0 // Defining in1-in4 pin numbers (L298N driver). -VS #define in2 1 #define in3 2 #define in4 3 #define DIST 15 // Control detection distance. -VS #define SPEED 125 // Control the overall speed of both motors. -VS #define ROTATION_TIME 650 // Control the time used during turning functions. During short travel it is ROTATION_TIME*1.5. -VS #define LED_PIN 8 // Defining LED-pin number. -JM //------------------------------------------------------------------------------------ // Following parts are for microSD module & speaker. -VS TMRpcm tmrpcm; // Creating object for speaker library. -VS // Note that Pin 9 must be used, the library is using Pin 9. -VS // Pinning for Arduino is following: CS=4, SCK=13, MOSI=11, MISO=12. -JM //------------------------------------------------------------------------------------ // Following parts are for HC-SR04 sensor. -VS const int trigPin = 6; // Defining Pin for HC-SR04 sensor trig. -VS const int echoPin = 7; // Defining Pin for HC-SR04 sensor echo. -VS long duration; // Variable used to measure distance. -VS int distance; //------------------------------------------------------------------------------------ // Condition variables & speed. bool soundCondition = true; // With "soundCondition" it is possible to make sure that certain functions go through only once. -VS bool distCondition = true; // With "distCondition" it is possible to make sure that certain functions go through only once. -VS int motorSpeed = SPEED; //------------------------------------------------------------------------------------ // Introducing the functions- -VS int checkObstacle (void); // -VS void sound1 (void);// -VS void sound2 (void);// -VS void turnLeft (void);// -VS void turnRight (void);// -VS void shortTravel (void);// -VS void travelForward (void); // -JM void stay (void); //-JM //------------------------------------------------------------------------------------ void setup() { tmrpcm.speakerPin = 9; // Defining speaker Pin. (Moved from global to setup). -VS if(!SD.begin (SD_ChipSelectPin)) // Check if SD card is present and can be initialized. -VS { return; // If no SD card is present, end program. -VS } tmrpcm.setVolume (4); // Volume can be set from 0 to 7. Set volume to 4. -VS pinMode(trigPin, OUTPUT); // Set Pin mode for trigPin and echoPin. -VS pinMode(echoPin, INPUT); pinMode(LED_PIN, OUTPUT); // Set pin mode for LED_PIN. -JM digitalWrite (LED_PIN, HIGH); // Set LED_PIN to HIGH-state = green light. -JM pinMode (enable, OUTPUT); // Will control speed of both motors. pinMode (in1, OUTPUT); // Set pin mode for in1-in4 pins (L298N driver). -JM pinMode (in2, OUTPUT); pinMode (in3, OUTPUT); pinMode (in4, OUTPUT); // Set initial rotation direction (-> robot moves forward). - JM digitalWrite (in1, LOW); // Set states (HIGH/LOW) for in1-in4 pins. -JM digitalWrite (in2, LOW); digitalWrite (in3, LOW); digitalWrite (in4, LOW); analogWrite (enable, motorSpeed); sound1(); // Plays .wav file when switched ON or reset. (if not working, check filename)-VS delay(9000); // Delay allows sound1 to end before starting loop. -VS } //------------------------------------------------------------------------------------ void loop() { if(checkObstacle() > DIST) // Checks if there is any obstacles closer than 20 cm. -JM { distCondition=false; // By setting distCondition to false, stops reading values from SR04. -VS digitalWrite (LED_PIN, HIGH); // If no obstacle, turn LED green (HIGH-state) and travel forward. -JM soundCondition = true; // Set soundCondition to true to make sure that sound plays only once. -VS travelForward(); // Normal state when no obstacles. -VS } if(checkObstacle() <= DIST) // Checks if there is any obstacles closer than 20 cm. -JM { distCondition=false; // By setting distCondition to false, stops reading values from SR04. -VS digitalWrite (LED_PIN, LOW); // If obstacle, turn LED yellow (LOW-state) -JM stay(); if(soundCondition==true) // Added if and soundCondition so that sound plays only once, will be able to play it again only after completing another function. -VS { soundCondition = false; // Set soundCondition to false so sound wont play more than once. -VS sound2(); // Plays .wav file for sound2. -JM } turnRight(); // Turn right when facing first obstacle. -VS if(checkObstacle() <= DIST) // Checks if there is any obstacles closer than 20 cm. -VS { distCondition=false; if(soundCondition==true) // Added if and soundCondition so that sound plays only once, will be able to play it again only after completing another function. -VS { soundCondition = false; // Set soundCondition to false so sound wont play more than once. -VS sound2(); // Plays .wav file for sound2. -VS } turnRight(); // Call trunRight function. -VS } if(checkObstacle() > DIST) { distCondition=false; shortTravel(); // Call shortTravel function. -VS turnLeft(); // Call leftRight function. -VS if(checkObstacle() <= DIST) { distCondition=false; sound2(); turnRight(); // Call turnRight function. -VS } } } } //------------------------------------------------------------------------------------ int checkObstacle (void) // Function that will read and convert values from SR-04. -VS { if(distCondition==true) { int avg=0; // Add avg variable to calculate average distance out of 3 tries. for(int i=0; i<3;i++) { digitalWrite(trigPin, LOW); // Will reset SR-04 trig to LOW state to avoid false information. -VS delayMicroseconds (2); // Wait 2 microseconds. -VS digitalWrite(trigPin, HIGH); // Send ultrasonic sound for 10 microseconds. -VS delayMicroseconds (10); digitalWrite(trigPin, LOW); // Stop sending ^ duration = pulseIn(echoPin, HIGH); // Save time value of the pulse lenght. -VS distance = duration*0.034/2; // Calculate distance in CM (s=t*v/2). -VS avg= avg+distance; } distance = avg/3; return distance; } } //------------------------------------------------------------------------------------ void sound1 (void) { tmrpcm.play ("1.wav"); // Function that will play 1.wav file. -VS } //------------------------------------------------------------------------------------ void sound2 (void) { digitalWrite (in1, LOW); // Set states (LOW) for in1-in4 pins (L298N driver). -JM digitalWrite (in2, LOW); digitalWrite (in3, LOW); digitalWrite (in4, LOW); // Stops with no extra delay. -VS tmrpcm.play ("2.wav"); // Function that will play 2.wav file. -VS delay(4000); } //------------------------------------------------------------------------------------ void turnLeft (void) { // Here is function fur turning robot to left. -VS digitalWrite (in1, HIGH); // Set states (HIGH/LOW) for in1-in4 pins (L298N driver). -JM digitalWrite (in2, LOW); digitalWrite (in3, LOW); digitalWrite (in4, HIGH); delay (ROTATION_TIME); // Turning left for 650 millseconds. stay(); soundCondition = true; // Will allow sound to play again when facing new obstacle. -VS distCondition = true; } //------------------------------------------------------------------------------------ void turnRight (void) { // Here is function for turning robot to right-VS digitalWrite (in1, LOW); // Set states (HIGH/LOW) for in1-in4 pins (L298N driver). -JM digitalWrite (in2, HIGH); digitalWrite (in3, HIGH); digitalWrite (in4, LOW); delay (ROTATION_TIME); // Turning right for 650 millseconds. -JM stay(); soundCondition = true; // Will allow sound to play again when facing new obstacle. -VS distCondition = true; } //------------------------------------------------------------------------------------ void shortTravel (void) { // This function will allow robot to travel forward for around 20cm. -VS digitalWrite (in1, HIGH); // Set states (HIGH/LOW) for in1-in4 pins (L298N driver). -JM digitalWrite (in2, LOW); digitalWrite (in3, HIGH); digitalWrite (in4, LOW); delay (ROTATION_TIME*1.5); // Travelling forward for 975 millseconds. stay(); soundCondition = true; // Will allow sound to play again when facing new obstacle. -VS distCondition = true; } //------------------------------------------------------------------------------------ void travelForward (void) { // This function will allow robot to travel forward. -JM digitalWrite (in1, HIGH); // Set states (HIGH/LOW) for in1-in4 pins (L298N driver). -JM digitalWrite (in2, LOW); digitalWrite (in3, HIGH); digitalWrite (in4, LOW); delay(200); distCondition = true; } //----------------------------------------------------------------------------------- void stay (void) { // This function will stop robot for a moment. -JM digitalWrite (in1, LOW); // Set states (LOW) for in1-in4 pins (L298N driver). -JM digitalWrite (in2, LOW); digitalWrite (in3, LOW); digitalWrite (in4, LOW); delay(700); // Wait for 700 ms before executing next line. -JM }
true
eb65567f15b5833374f5c2a0b7a3cd1381c4ebcb
C++
fsatka/msu_cpp_spring_2018
/homework/Sokolova/03/Characters.h
UTF-8
2,358
3.671875
4
[ "MIT" ]
permissive
/** @file @brief Header file with character classes declaration. File contains hierarchy of characters in the game. */ #include <string> #include "Items.h" /** * @brief Base class of all characters in the game. * Can recover of damage and upgrade to new level. */ class Character { public: void recover(); void upgrade(); }; /** * @brief Base class of all animal characters. * Identified by id, name. * Recovers by increasing power. * Upgrades by increasing its level. * Can work and challenge with other animals. */ class Animal: public Character { int id; std::string name; int level; int power; public: void work(); void challenge(Animal &); }; /** * @brief Horse works by carrying its human taking part in horseraces. */ class Horse: public Animal { void carryMan(); void participateHorseraces(); }; /** * @brief Pig works by putting weight on and taking part in pig exhibition. */ class Pig: public Animal { void growFat(); void participateExhibition(); }; /** * @brief Base class of human characters. * Identified by id and name. * Has level, power and health characteristics. * Recovers by increasing health. * Upgrades by increasing level. * Has money to buy items. * Can attack, communicate, buy items and earn money with bets. */ class Human: public Character { int id; std::string name; int level; int power; int healht; int money; public: void attack(Weapon *weapon, Human &enemy); void buyItem(Item *item); void communicate(Character &companion); void bet(Character &character); }; /** * @brief Archer have a bow and hauberk. * Can have a horse. * Earns money by participating in archery challenges. */ class Archer: public Human { Horse *horse; Bow *bow; Hauberk *hauberk; public: void participateTargetArchery(); }; /** * @brief Peasant have a shovel and basin. * Can have a pig. * Earns money by digging and pork selling. */ class Peasant: public Human { Pig *pig; Shovel *shovel; Basin *basin; public: void dig(); void sellPork(); }; /** * @brief Knight have a sword and lats. * Can have a horse. * Earns money by participating tournaments. */ class Knight: public Human { Horse *horse; Sword *sword; Lats *lats; public: void participateTournament(); };
true
e1537687c2b8d53c391ad43b69d4c4e8346f3b5c
C++
devinacker/decomposer
/src/devices/MIDIdefs.cpp
UTF-8
2,141
2.609375
3
[ "MIT" ]
permissive
#include "MIDIdefs.h" using MIDI::StringMap; static QString fromStringMap(const StringMap& map, uint num) { if (map.contains(num)) return map.value(num); return "unknown"; } static const StringMap controlNames = { {0, "Bank select"}, {1, "Modulation wheel"}, {2, "Breath controller"}, {4, "Foot pedal"}, {5, "Portamento time"}, {6, "Data entry (MSB)"}, {7, "Volume"}, {8, "Balance"}, {10, "Pan position"}, {11, "Expression"}, {12, "Effect control 1"}, {13, "Effect control 2"}, {16, "Slider 1"}, {17, "Slider 2"}, {18, "Slider 3"}, {19, "Slider 4"}, {32, "Bank select (fine)"}, {33, "Modulation wheel (fine)"}, {34, "Breath controller (fine)"}, {36, "Foot pedal (fine)"}, {37, "Portamento time (fine)"}, {38, "Data entry (LSB)"}, {39, "Volume (fine)"}, {40, "Balance (fine)"}, {42, "Pan position (fine)"}, {43, "Expression (fine)"}, {44, "Effect control 1 (fine)"}, {45, "Effect control 2 (fine)"}, {64, "Hold pedal (on/off)"}, {65, "Portamento (on/off)"}, {66, "Sostenuto pedal (on/off)"}, {67, "Soft pedal (on/off)"}, {68, "Legato pedal (on/off)"}, {69, "Hold 2 pedal (on/off)"}, {70, "Sound variation"}, {71, "Sound timbre"}, {72, "Sound release time"}, {73, "Sound attack time"}, {74, "Sound brightness"}, {75, "Sound control 6"}, {76, "Sound control 7"}, {77, "Sound control 8"}, {78, "Sound control 9"}, {79, "Sound control 10"}, {80, "Button 1 (on/off)"}, {81, "Button 2 (on/off)"}, {82, "Button 3 (on/off)"}, {83, "Button 4 (on/off)"}, {91, "Reverb/delay level"}, {92, "Tremolo level"}, {93, "Chorus level"}, {94, "Celeste level"}, {95, "Phaser level"}, {96, "Data button increment"}, {97, "Data button decrement"}, {98, "Non-registered param (LSB)"}, {99, "Non-registered param (MSB)"}, {100, "Registered param (LSB)"}, {101, "Registered param (MSB)"}, {120, "All sound off"}, {121, "All controllers off"}, {122, "Local keyboard (on/off)"}, {123, "All notes off"}, {124, "Omni mode off"}, {125, "Omni mode on"}, {126, "Mono operation"}, {127, "Poly operation"}, }; QString MIDI::getControlName(uint num) { return fromStringMap(controlNames, num); }
true
45f56c9d7973cf603ea1638495797fcef2efd8ed
C++
brysonb24/Assignments
/P02/myVector.h
UTF-8
6,294
3.734375
4
[]
no_license
#include <iostream> using namespace std; /******************************** * * * Class * * Implementation * * * * * ********************************/ class myVector { private: int *vPtr; // int pointer to array int maxSize; // max size of array int minSize; // min size of array int index; // current location to insert or remove int* _resize(int); public: myVector(int size); void push_Back(int item); void push_Back(int *array, int size); int popBack(); double percentFull(); //Public methods/variables int* resize(double); int* resize(int); void print(); int size(); void size(int); int vSize(); // Implementation of [] operator. This function must return a // refernce as array element can be put on left side int& operator[](int i) { if (i >= maxSize) { cout << "Array index out of bound, exiting\n"; exit(0); } else if (i >= index) { cout << "Warning: vector[" << i << "] is undefined ...\n"; } return vPtr[i]; } // Implementation of << operator. This function must return a // ostream object called os by address. friend ostream& operator<<(ostream& os, myVector V) { for (int i = 0; i<V.index; i++) { os << V.vPtr[i] << " "; } return os; } // Implementation of + operator. This function must return a // myVector called newVector. myVector operator+(const myVector& rhs) { //rhs = vector on the right of the + sign //lhs = THIS vector (the one were in) int rhsSize = rhs.index; int lhsSize = index; int max = 0; int min = 0; // which vector is bigger? if (rhsSize > lhsSize) { max = rhsSize; } else { max = lhsSize; } // create a new vector with the bigger size myVector newVector(max); // which vector is smaller? if (rhsSize < lhsSize) { min = rhsSize; newVector.index = index; } else { min = lhsSize; newVector.index = rhs.index; } if (max == rhsSize) { for (int i = 0; i < max; i++) { newVector.vPtr[i] = rhs.vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] += vPtr[i]; } } else { for (int i = 0; i < max; i++) { newVector.vPtr[i] = vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] += rhs.vPtr[i]; } } return newVector; } // Implementation of - operator. This function must return a // myVector called newVector. myVector operator-(const myVector& rhs) { //rhs = vector on the right of the - sign //lhs = THIS vector (the one were in) int rhsSize = rhs.index; int lhsSize = index; int max = 0; int min = 0; // which vector is bigger? if (rhsSize > lhsSize) { max = rhsSize; } else { max = lhsSize; } // create a new vector with the bigger size myVector newVector(max); // which vector is smaller? if (rhsSize < lhsSize) { min = rhsSize; newVector.index = index; } else { min = lhsSize; newVector.index = rhs.index; } if (max == rhsSize) { for (int i = 0; i < max; i++) { newVector.vPtr[i] = rhs.vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] -= vPtr[i]; } } else { for (int i = 0; i < max; i++) { newVector.vPtr[i] = vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] -= rhs.vPtr[i]; } } return newVector; } // Implementation of * operator. This function must return a // myVector called newVector. myVector operator*(int num) { int lhsSize = index; int max = lhsSize; myVector newVector(max); newVector.index = index; for (int i = 0; i < max; i++) { newVector.vPtr[i] = vPtr[i]; } for (int i = 0; i < max; i++) { newVector.vPtr[i] *= num; } return newVector; } // Implementation of * operator. This function must return a // myVector called newVector. myVector operator*(const myVector& rhs) { //rhs = vector on the right of the * sign //lhs = THIS vector (the one were in) int rhsSize = rhs.index; int lhsSize = index; int max = 0; int min = 0; // which vector is bigger? if (rhsSize > lhsSize) { max = rhsSize; } else { max = lhsSize; } // create a new vector with the bigger size myVector newVector(max); // which vector is smaller? if (rhsSize < lhsSize) { min = rhsSize; newVector.index = index; } else { min = lhsSize; newVector.index = rhs.index; } if (max == rhsSize) { for (int i = 0; i < max; i++) { newVector.vPtr[i] = rhs.vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] *= vPtr[i]; } } else { for (int i = 0; i < max; i++) { newVector.vPtr[i] = vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] *= rhs.vPtr[i]; } } return newVector; } // Implementation of / operator. This function must return a // myVector called newVector. myVector operator/(const myVector& rhs) { //rhs = vector on the right of the / sign //lhs = THIS vector (the one were in) int rhsSize = rhs.index; int lhsSize = index; int max = 0; int min = 0; // which vector is bigger? if (rhsSize > lhsSize) { max = rhsSize; } else { max = lhsSize; } // create a new vector with the bigger size myVector newVector(max); // which vector is smaller? if (rhsSize < lhsSize) { min = rhsSize; newVector.index = index; } else { min = lhsSize; newVector.index = rhs.index; } if (max == rhsSize) { for (int i = 0; i < max; i++) { newVector.vPtr[i] = rhs.vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] /= vPtr[i]; } } else { for (int i = 0; i < max; i++) { newVector.vPtr[i] = vPtr[i]; } for (int i = 0; i < min; i++) { newVector.vPtr[i] /= rhs.vPtr[i]; } } return newVector; } // Implementation of = operator. This function returns void. // But it assings new values in original vector passed in. void operator=(const myVector& rhs) { index = rhs.index; for (int i = 0; i < index; i++) { vPtr[i] = rhs.vPtr[i]; } } // Implementation of == operator. This function returns bool. // But it checks for equality of values in 2 vectors. bool operator==(const myVector& rhs) { if (index != rhs.index) { return false; } for (int i = 0; i < index; i++) { if (vPtr[i] != rhs.vPtr[i]) { return false; } } return true; } };
true
24b463f02afa024d36e19b04c1580f79a29acafa
C++
ob6160/pazaak
/pazaak.h
UTF-8
1,659
2.5625
3
[]
no_license
#ifndef PAZAAK_H #define PAZAAK_H #include <vector> #include <iostream> #include <cstdlib> #include <map> #include "SDL2/SDL.h" #include "SDL2/SDL_ttf.h" #include "SDL2/SDL_events.h" #include "player.h" #include "card.h" #include "constants.h" #include "button.h" #include "helpers.h" class Pazaak { public: explicit Pazaak(TTF_Font *font, int upperLimit = 10, int lowerLimit = 1, int individualCount = 2); ~Pazaak(); void initialiseDeck(SDL_Renderer *r); void deal(Player *p); void setup(SDL_Renderer *r); void render(SDL_Renderer *r); void update(int delta); void handleEvent(SDL_Event event); void gameController(ActionType action, Card* playCard = nullptr); Player *getPlayer(PlayerType p); int p1score = 0, p2score = 0; private: SDL_Renderer *renderer; bool matchOver = false; std::vector<Card*> deck, hand; Card *deckCard; int upperLimit, lowerLimit, individualCount; Constants::PlayerType playerTurn = PlayerType::PLAYER_ONE; TTF_Font *font; Button *endTurn, *stand, *play, *dismissStatus; SDL_Texture *score; Player * swapPlayerTurn(); Player *humanPlayer; Player *computerPlayer; std::map<PlayerType, Player *> players; Timer computerTimer; GameState state = GameState::PLAY; bool waitForHandChoice = false; bool showStatusMessage = false; std::string statusMessage = "test message"; bool checkWinConditions(); bool checkRoundEnd(); void initialiseHand(SDL_Renderer *r); bool handleRoundEnd(); SDL_Texture *messageBorder; void nextRound(); void nextRound(SDL_Renderer *r); bool click; }; #endif
true
af68d6321f282a877cd226d0f04bec774d200ee8
C++
damienArnol/svca
/svca_limix/src/limix/utils/brentc.cpp
UTF-8
4,222
2.796875
3
[ "Apache-2.0" ]
permissive
/* ******************************************************************* * * Copyright (c) Microsoft. All rights reserved. * This code is licensed under the Apache License, Version 2.0. * THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY * IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR * PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. * ****************************************************************** */ /// <summary>Brent's method for minimizing a 1d function</summary> #include "limix/utils/brentc.h" #include <stdlib.h> #include <iostream> #include <stdio.h> //#include <math.h> //does tis work on windows? #include <cmath> // Machine eps double BrentC::MACHEPS = (double)2.2204460492503131e-016; double BrentC::MACHEPS_SQRT = sqrt(MACHEPS); double BrentC::c = ((double)3.0 - sqrt((double)5.0)) / (double)2.0; /// <summary>Minimize the function over the interval [a, b]</summary> /// <param name="f">Function to minimize</param> /// <param name="a">Left side of the bracket</param> /// <param name="b">Right side of the bracket</param> /// <param name="eps">Stopping tolerance</param> /// <param name="funcx">Function evaluated at the minimum</param> /// <param name="numiter">number of function evaluations</param> /// <param name="maxIter">maximum number of function evaluations allowed</param> /// <param name="quiet">print out function evaluations?</param> /// <returns>Point that minimizes the function</returns> /// <remarks>This implements the algorithm from Brent's book, "Algorithms for Minimization without Derivatives"</remarks> double BrentC::minimize(BrentFunctor &f, double a, double b, double eps, double &funcx, size_t &numiter, size_t maxIter, bool quiet) { if (a >= b){ printf("Exception: a must be < b"); throw(1); } double x = a + c * (b - a); double v = x; double w = x; double e = 0; double fx = f(x); double fv = fx; double fw = fx; numiter = 0; while (true) { double m = (double)0.5 * (a + b); double tol = MACHEPS_SQRT * std::fabs(x) + eps; double tol2 = (double)2 * tol; // Check the stopping criterion if (std::fabs(x - m) <= tol2 - 0.5 * (b - a)){ break; } // Stop if we've exceeded the maximum number of iterations numiter++; if (numiter > maxIter){ printf("Exception: Exceeded maximum number of iterations."); throw(2); } double p = 0.0, q = 0.0, r = 0.0; double d = 0.0; double u = 0.0; if (std::fabs(e) > tol) { // Fit parabola r = (x - w) * (fx - fv); q = (x - v) * (fx - fw); p = (x - v) * q - (x - w)*r; q = (double)2.0 * (q - r); if (q > (double)0.0) p = -p; else q = -q; r = e; e = d; } if ((std::fabs(p) < std::fabs((double)0.5*q*r)) && (p < q*(a - x)) && (p < q*(b - x))) { // Parabolic interpolation step d = p / q; u = x + d; // f must not be evaluated too close to a or b if (u - a < tol2 || b - u < tol2) d = (x < m) ? tol : -tol; } else { // Golden section step e = (x < m) ? b - x : a - x; d = c * e; } // f must not be evaluated too close to x if (std::fabs(d) >= tol) u = x + d; else if (d > 0.0) u = x + tol; else u = x - tol; double fu = f(u); // Update if (fu <= fx) { if (u < x) b = x; else a = x; v = w; fv = fw; w = x; fw = fx; x = u; fx = fu; } else { if (u < x) a = u; else b = u; if (fu <= fw || w == x) { v = w; fv = fw; w = u; fw = fu; } else if (fu <= fv || v == x || v == w) { v = u; fv = fu; } } if (!quiet) { printf("Iteration %i, min_x = %f, f(min_x) = %f, ", (int)numiter, x, fx); } } funcx = f(x); return x; }
true
545c25e2c64a654e678f4eddd2f8e85f3ec6a748
C++
Wizmann/ACM-ICPC
/Codeforces/Educational Codeforces Round 19/C.cc
UTF-8
1,506
2.921875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #include <stack> #include <queue> #include <set> #include <map> #include <cassert> using namespace std; #define print(x) cout << x << endl #define input(x) cin >> x class Solution { public: Solution(const string& s_): s(s_) { // pass } string solve() { int n = s.size(); set<pair<char, int> > pq; for (int i = 0; i < n; i++) { char c = s[i]; pq.insert({c, i}); } int cur = 0; while (!pq.empty()) { auto p = *pq.begin(); char c = p.first; int pos = p.second; assert (pos >= cur); while (!st.empty() && st.top() <= c) { res += st.top(); st.pop(); } while (cur <= pos) { st.push(s[cur]); pq.erase(pq.find({s[cur], cur})); cur++; } res += st.top(); st.pop(); } while (!st.empty()) { res += st.top(); st.pop(); } return res; } private: string s; stack<char> st; string res; }; int main() { assert(Solution("cab").solve() == "abc"); assert(Solution("acdb").solve() == "abdc"); assert(Solution("cadcab").solve() == "aabcdc"); string s; input(s); Solution sol(s); print(sol.solve()); return 0; }
true
40ebc2a27c564f3d6e6e8b5d07710636509f25b8
C++
NoahSarkey/osProject4
/search.h
UTF-8
1,227
3.0625
3
[]
no_license
// Sam Mustipher, Noah Sarkey // CSE 30341 - 02 // Project 4 // search.h ////////////////////////////////// TO DO /////////////////////////////////////// // Take care of carraige returns // no wildcards or regular expressions? what does this entail //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <stdio.h> #include <stdlib.h> #include <iomanip> #include <vector> #include <string> #include <fstream> using namespace std; class Search { public: void create(string filename) { ifstream inputFile; inputFile.open(filename.c_str()); //vector<string> phrase; if (inputFile.is_open()) { while (!inputFile.eof()) { int kill = 0; string w = ""; // read in the line getline(inputFile, w); //do all of the work to clean the file for (unsigned int i = 0; i < w.size(); i ++) { if (w[i] == ',') { kill = 1; } } // add to the vector if (kill == 0) phrase.push_back(w); } } //for (unsigned int i = 0; i < phrase.size(); i ++) { // cout << phrase[i] << endl; //} inputFile.close(); //return phrase; } //end of create function vector<string> phrase; }; //end of class
true
b97906458d416a4584043bfa153b859f22d1cd44
C++
alexandraback/datacollection
/solutions_5670465267826688_0/C++/FireJade/C.cc
UTF-8
1,865
3.109375
3
[]
no_license
#include <iostream> #include <map> #include <vector> using namespace std; typedef struct { bool neg; string rep; } val; val times(val left, val right) { val ret; ret.neg = left.neg ^ right.neg; if (left.rep == "1") { ret.rep = right.rep; } else if (right.rep == "1") { ret.rep = left.rep; } else if (left.rep == right.rep) { ret.rep = "1"; ret.neg = !ret.neg; } else if (left.rep == "i" && right.rep == "j") { ret.rep = "k"; } else if (left.rep == "i" && right.rep == "k") { ret.rep = "j"; ret.neg = !ret.neg; } else if (left.rep == "j" && right.rep == "i") { ret.rep = "k"; ret.neg = !ret.neg; } else if (left.rep == "j" && right.rep == "k") { ret.rep = "i"; } else if (left.rep == "k" && right.rep == "i") { ret.rep = "j"; } else { ret.rep = "i"; ret.neg = !ret.neg; } return ret; } int main() { int T; cin >> T; long long L, X; string inp; for (int caseNum = 1; caseNum <= T; caseNum++) { cin >> L >> X >> inp; vector<val> vals; for (int i = 0; i < L; i++) { val next; next.rep.push_back(inp[i]); next.neg = false; vals.push_back(next); } val s1, s2, s3; s1.neg = s2.neg = s3.neg = false; s1.rep = s2.rep = s3.rep = "1"; for (int i = 0; i < X; i++) { for (int j = 0; j < L; j++) { val next = vals[j]; if (s1.rep != "i" || s1.neg) { s1 = times(s1, next); } else if (s2.rep != "j" || s2.neg) { s2 = times(s2, next); } else { s3 = times(s3, next); } } } if (!s1.neg && !s2.neg && !s3.neg && s1.rep == "i" && s2.rep == "j" && s3.rep == "k") { cout << "Case #" << caseNum << ": " << "YES" << endl; } else { cout << "Case #" << caseNum << ": " << "NO" << endl; } } }
true
63319dd6c9de9741720a0bcf283079551d75ff36
C++
herox25000/oathx-ogrex-editor
/V5.1/v5/系统模块/客户端组件/形象组件/CustomFaceManager.cpp
GB18030
8,626
2.5625
3
[]
no_license
#include "StdAfx.h" #include "CustomFaceManager.h" ////////////////////////////////////////////////////////////////////////////////// //ļṹ struct tagCustomFaceFile { DWORD dwCustomID; //Զʶ tagCustomFaceInfo CustomFaceInfo; //ͷϢ }; //̬ CCustomFaceManager * CCustomFaceManager::m_pCustomFaceManager=NULL; //ָ ////////////////////////////////////////////////////////////////////////////////// //캯 CCustomFaceManager::CCustomFaceManager() { //ñ m_pICustomFaceEvent=NULL; ZeroMemory(&m_CustomFaceInfo,sizeof(m_CustomFaceInfo)); //ö ASSERT(m_pCustomFaceManager==NULL); if (m_pCustomFaceManager==NULL) m_pCustomFaceManager=this; return; } // CCustomFaceManager::~CCustomFaceManager() { //ͷŶ ASSERT(m_pCustomFaceManager==this); if (m_pCustomFaceManager==this) m_pCustomFaceManager=NULL; return; } //ӿڲѯ VOID * CCustomFaceManager::QueryInterface(REFGUID Guid, DWORD dwQueryVer) { QUERYINTERFACE(IDownLoadSink,Guid,dwQueryVer); QUERYINTERFACE(ICustomFaceManager,Guid,dwQueryVer); QUERYINTERFACE_IUNKNOWNEX(ICustomFaceManager,Guid,dwQueryVer); return NULL; } //ýӿ bool CCustomFaceManager::SetCustomFaceEvent(IUnknownEx * pIUnknownEx) { //ýӿ if (pIUnknownEx!=NULL) { //ѯӿ ASSERT(QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,ICustomFaceEvent)!=NULL); m_pICustomFaceEvent=QUERY_OBJECT_PTR_INTERFACE(pIUnknownEx,ICustomFaceEvent); //ɹж if (m_pICustomFaceEvent==NULL) return false; } else m_pICustomFaceEvent=NULL; return true; } //ͷ bool CCustomFaceManager::LoadUserCustomFace(DWORD dwUserID, DWORD dwCustomID) { // for (INT_PTR i=0;i<m_CustomFaceIndexArray.GetCount();i++) { //ȡ tagCustomFaceIndex * pCustomFaceIndex=&m_CustomFaceIndexArray[i]; //ж if (pCustomFaceIndex->dwUserID==dwUserID) { //汾һ if (pCustomFaceIndex->dwCustomID==dwCustomID) { return true; } //汾 if (pCustomFaceIndex->dwCustomID!=dwCustomID) { if (i==0) { // tagCustomFaceIndex CustomFaceIndex; ZeroMemory(&CustomFaceIndex,sizeof(CustomFaceIndex)); //ñ CustomFaceIndex.dwUserID=dwUserID; CustomFaceIndex.dwCustomID=dwCustomID; // m_CustomFaceIndexArray.Add(CustomFaceIndex); } else { //д pCustomFaceIndex->dwCustomID=dwCustomID; } return true; } } } // tagCustomFaceIndex CustomFaceIndex; ZeroMemory(&CustomFaceIndex,sizeof(CustomFaceIndex)); //ñ CustomFaceIndex.dwUserID=dwUserID; CustomFaceIndex.dwCustomID=dwCustomID; // m_CustomFaceIndexArray.Add(CustomFaceIndex); // if (m_CustomFaceIndexArray.GetCount()==1L) { PerformDownLoad(dwUserID,dwCustomID); } return true; } //ͷ bool CCustomFaceManager::LoadUserCustomFace(DWORD dwUserID, DWORD dwCustomID, tagCustomFaceInfo & CustomFaceInfo) { //Ŀ¼ TCHAR szWorkDirectory[MAX_PATH]=TEXT(""); CWHService::GetWorkDirectory(szWorkDirectory,CountArray(szWorkDirectory)); //ĿĿ¼ TCHAR szCustomFacePath[MAX_PATH]=TEXT(""); _sntprintf(szCustomFacePath,CountArray(szCustomFacePath),TEXT("%s\\CustomFace\\%ld.DAT"),szWorkDirectory,dwUserID); //ļ CFile DataFile; if (DataFile.Open(szCustomFacePath,CFile::modeRead)==FALSE) return false; //Ч鳤 ASSERT(DataFile.GetLength()==sizeof(tagCustomFaceFile)); if (DataFile.GetLength()!=sizeof(tagCustomFaceFile)) return false; //ȡ tagCustomFaceFile CustomFaceFile; UINT uReadCount=DataFile.Read(&CustomFaceFile,sizeof(CustomFaceFile)); //ȡЧ if (uReadCount!=sizeof(CustomFaceFile)) return false; if (CustomFaceFile.dwCustomID!=dwCustomID) return false; if (CustomFaceFile.CustomFaceInfo.dwDataSize!=sizeof(CustomFaceFile.CustomFaceInfo)) return false; // CopyMemory(&CustomFaceInfo,&CustomFaceFile.CustomFaceInfo,sizeof(CustomFaceInfo)); return true; } // bool CCustomFaceManager::SaveUserCustomFace(DWORD dwUserID, DWORD dwCustomID, DWORD dwCustomFace[FACE_CX*FACE_CY]) { //Ŀ¼ TCHAR szWorkDirectory[MAX_PATH]=TEXT(""); CWHService::GetWorkDirectory(szWorkDirectory,CountArray(szWorkDirectory)); //ĿĿ¼ TCHAR szCustomDirectory[MAX_PATH]=TEXT(""); _sntprintf(szCustomDirectory,CountArray(szCustomDirectory),TEXT("%s\\CustomFace"),szWorkDirectory); //Ŀļ TCHAR szCustomFacePath[MAX_PATH]=TEXT(""); _sntprintf(szCustomFacePath,CountArray(szCustomFacePath),TEXT("%s\\CustomFace\\%ld.DAT"),szWorkDirectory,dwUserID); //Ŀ¼ CreateDirectory(szCustomDirectory,NULL); //ļ CFile DataFile; if (DataFile.Open(szCustomFacePath,CFile::modeWrite|CFile::modeCreate)==TRUE) { // tagCustomFaceFile CustomFaceFile; ZeroMemory(&CustomFaceFile,sizeof(CustomFaceFile)); //д CustomFaceFile.dwCustomID=dwCustomID; CustomFaceFile.CustomFaceInfo.dwDataSize=sizeof(tagCustomFaceInfo); CopyMemory(CustomFaceFile.CustomFaceInfo.dwCustomFace,dwCustomFace,sizeof(CustomFaceFile.CustomFaceInfo.dwCustomFace)); //дļ DataFile.Write(&CustomFaceFile,sizeof(CustomFaceFile)); DataFile.SetLength(sizeof(CustomFaceFile)); //رļ DataFile.Close(); } return true; } //쳣 bool CCustomFaceManager::OnDownLoadError(enDownLoadError DownLoadError) { //״̬Ч ASSERT(m_CustomFaceIndexArray.GetCount()>0L); if (m_CustomFaceIndexArray.GetCount()==0L) return false; //ɾ m_CustomFaceIndexArray.RemoveAt(0); // if (m_CustomFaceIndexArray.GetCount()>=1L) { tagCustomFaceIndex * pCustomFaceIndex=&m_CustomFaceIndexArray[0]; PerformDownLoad(pCustomFaceIndex->dwUserID,pCustomFaceIndex->dwCustomID); } return true; } //״̬ bool CCustomFaceManager::OnDownLoadStatus(enDownLoadStatus DownLoadStatus) { // if (DownLoadStatus==DownLoadStatus_Conclude) { //״̬Ч ASSERT(m_CustomFaceIndexArray.GetCount()>0L); if (m_CustomFaceIndexArray.GetCount()==0L) return false; //ļ tagCustomFaceIndex CustomFaceIndex=m_CustomFaceIndexArray[0]; SaveUserCustomFace(CustomFaceIndex.dwUserID,CustomFaceIndex.dwCustomID,m_CustomFaceInfo.dwCustomFace); //ɾ m_CustomFaceIndexArray.RemoveAt(0); //¼֪ͨ ASSERT(m_pICustomFaceEvent!=NULL); m_pICustomFaceEvent->OnEventCustomFace(CustomFaceIndex.dwUserID,CustomFaceIndex.dwCustomID,m_CustomFaceInfo); // if (m_CustomFaceIndexArray.GetCount()>=1L) { tagCustomFaceIndex * pCustomFaceIndex=&m_CustomFaceIndexArray[0]; PerformDownLoad(pCustomFaceIndex->dwUserID,pCustomFaceIndex->dwCustomID); } } return true; } // bool CCustomFaceManager::OnDataStream(const VOID * pcbMailData, WORD wStreamSize) { //Ч ASSERT((wStreamSize+m_CustomFaceInfo.dwDataSize)<=sizeof(m_CustomFaceInfo.dwCustomFace)); if ((wStreamSize+m_CustomFaceInfo.dwDataSize)>sizeof(m_CustomFaceInfo.dwCustomFace)) return false; // DWORD dwSourceIndex=m_CustomFaceInfo.dwDataSize; m_CustomFaceInfo.dwDataSize=m_CustomFaceInfo.dwDataSize+wStreamSize; CopyMemory((BYTE *)(m_CustomFaceInfo.dwCustomFace)+dwSourceIndex,pcbMailData,wStreamSize); return true; } //Ϣ bool CCustomFaceManager::OnDataInformation(DWORD dwTotalFileSize, LPCTSTR pszEntityTag, LPCTSTR pszLocation) { return true; } //ִ bool CCustomFaceManager::PerformDownLoad(DWORD dwUserID, DWORD dwCustomID) { //ñ ZeroMemory(&m_CustomFaceInfo,sizeof(m_CustomFaceInfo)); //ַ TCHAR szCustomFace[128]=TEXT(""); _sntprintf(szCustomFace,CountArray(szCustomFace),TEXT("%s/CustomFace.aspx?UserID=%ld&CustomID=%ld"),szPlatformLink,dwUserID,dwCustomID); //ͷ ASSERT(m_DownLoad.GetDownLoadStatus()==DownLoadStatus_Conclude); m_DownLoad.PerformDownLoad(szCustomFace,QUERY_ME_INTERFACE(IUnknownEx)); return true; } ////////////////////////////////////////////////////////////////////////////////// // DECLARE_CREATE_MODULE(CustomFaceManager); //////////////////////////////////////////////////////////////////////////////////
true
daa1d45e75ad5677699e5d7bc631251e5a83f59c
C++
escape0707/usaco_trainings
/agrinet.cpp
UTF-8
1,505
2.84375
3
[]
no_license
/* ID: totheso1 LANG: C++14 TASK: agrinet */ #include <algorithm> #include <fstream> #include <iterator> #include <vector> using namespace std; static ifstream fin("agrinet.in"); static ofstream fout("agrinet.out"); #define endl '\n' template <typename T> T fin_get() { return *istream_iterator<T>(fin); } template <typename C> C fin_get_collection(const int size) { C ret; copy_n(istream_iterator<typename C::value_type>(fin), size, back_inserter(ret)); return ret; } static const int FARM_COUNT = fin_get<int>(); static vector<vector<int>> dist(FARM_COUNT); static void initialize() { for (vector<int> &row : dist) { for (int j = 0; j < FARM_COUNT; ++j) { row.push_back(fin_get<int>()); } } } static void solve() { vector<int> closest(FARM_COUNT, numeric_limits<int>::max()); closest[0] = 0; vector<bool> in_tree(FARM_COUNT, false); int ans = 0; for (int tree_size = 0; tree_size < FARM_COUNT; ++tree_size) { int i = -1; int dist_i = numeric_limits<int>::max(); int curr = -1; for (const int d : closest) { ++curr; if (!in_tree[curr] && d < dist_i) { i = curr; dist_i = d; } } ans += dist_i; in_tree[i] = true; transform(cbegin(closest), cend(closest), cbegin(dist[i]), begin(closest), [](const int closest_j, const int dist_ij) { return min(closest_j, dist_ij); }); } fout << ans << endl; } int main() { initialize(); solve(); }
true
c41de0267d11e3c89585e0a0ede2b572145f57d9
C++
adfilm2/algorithm
/hee.youn/15686.cpp
UTF-8
1,343
2.875
3
[]
no_license
#include<iostream> #define fi(i, a, b) for(int i = a; i < b; i++) #define abs(a) ((a) > 0 ? (a) : -(a)) #define MAX_N 50 #define MAX_M 13 #define CUSTOMER 1 #define STORE 2 using namespace std; int N, M; int map[MAX_N][MAX_N]; struct Pos { int x; int y; }; int distance(Pos a, Pos b) { return abs(a.x - b.x) + abs(a.y - b.y); } Pos stores[MAX_N*MAX_N]; int storeSize; Pos customers[MAX_N*MAX_N]; int customerSize; Pos selected[MAX_M]; int calculate() { int ret = 0; fi(i, 0, customerSize) { Pos customer = customers[i]; int minDistance = distance(customer, selected[0]); fi(j, 1, M) { int dis = distance(customer, selected[j]); if (minDistance <= dis) continue; minDistance = dis; } ret += minDistance; } return ret; } int recursive(int cur, int size) { if (size == M) { int ans = calculate(); return ans; } int min = MAX_N * MAX_N; for (int i = cur; i < storeSize; i++) { selected[size] = stores[i]; int ret = recursive(i + 1, size + 1); if (min <= ret) continue; min = ret; } return min; } int main() { storeSize = 0; cin >> N >> M; fi(i, 0, N) { fi(j, 0, N) { cin >> map[i][j]; if (map[i][j] == STORE) { stores[storeSize++] = { i, j }; } else if (map[i][j] == CUSTOMER) { customers[customerSize++] = { i, j }; } } } cout << recursive(0, 0); return 0; }
true
b400f06f5bae3f45183278189245f2dc89a556ee
C++
khaledman6122/codeforces-A-B
/A. Calculating Function.cpp
UTF-8
492
3.125
3
[]
no_license
// http://codeforces.com/contest/486/problem/A // // 12:25 1:22 -->57 min // #include <iostream> using namespace std ; int main () { long long int x; cin>>x; if(x%2==0) x/=2; else if(x%2!=0) { x++; x/=2; x*=(-1); } cout<<x<<endl; return 0 ; } /* n = (n(n+1)/2 = (n^2+n)/2 1=-1 =-1 2=-1+2 = 1 3=-1+2-3 =-2 4=-1+2-3+4 = 2 5=-1+2-3+4-5 =-3 6=-1+2-3+4-5+6 = 3 */ /* n = (n^-1)*n 1 = -1 2 = 2 3 = -3 4 = 4 5 = -5 6 = 6 */
true
19b7dbf26e540961be9c9e0c022324face7b0a3d
C++
dss875914213/cpp_learn
/cpp_learn/demo2/main.cpp
UTF-8
660
3.28125
3
[ "MIT" ]
permissive
#include<iostream> int main() { int basic = 10; auto f1 = [](int x, int y) {return x + y; }; auto f2 = [basic](int x, int y) {return x + y + basic; }; auto f3 = [&basic](int x, int y) {basic = 5; return x + y + basic; }; auto f4 = [=](int x, int y) {return x + y + basic; }; auto f5 = [&](int x, int y) {basic = 5; return x + y + basic; }; std::cout << f1(1, 3)<<std::endl; std::cout << f2(1, 3) << std::endl; std::cout << f3(1, 3) << std::endl; std::cout << f4(1, 3) << std::endl; std::cout << f5(1, 3) << std::endl; std::cout << basic << std::endl; auto f11 = [=](int x, int y) {return x + y + basic; }; std::cout << f11(1, 3) << std::endl; }
true
941b6df9341a2db9afcef10b1483ceb218b50243
C++
YegorLindberg/oop
/lw6/httpURL/httpURL/CHttpUrl.hpp
UTF-8
2,985
3.171875
3
[]
no_license
// // CHttpUrl.hpp // httpURL // // Created by Moore on 04.06.2018. // Copyright © 2018 Moore. All rights reserved. // #ifndef CHttpUrl_hpp #define CHttpUrl_hpp #include <string> #include <regex> enum Protocol { HTTP, HTTPS }; class CHttpUrl { public: // выполняет парсинг строкового представления URL-а, в случае ошибки парсинга // выбрасыват исключение CUrlParsingError, содержащее текстовое описание ошибки CHttpUrl(std::string const& url); /* инициализирует URL на основе переданных параметров. При недопустимости входных параметров выбрасывает исключение std::invalid_argument Если имя документа не начинается с символа /, то добавляет / к имени документа */ CHttpUrl(std::string const& domain, std::string const& document, Protocol protocol = HTTP); /* инициализирует URL на основе переданных параметров. При недопустимости входных параметров выбрасывает исключение std::invalid_argument Если имя документа не начинается с символа /, то добавляет / к имени документа */ CHttpUrl(std::string const& domain, std::string const& document, Protocol protocol, unsigned short port); // возвращает строковое представление URL-а. Порт, являющийся стандартным для // выбранного протокола (80 для http и 443 для https) в URL не должен включаться std::string GetURL() const; // возвращает доменное имя std::string GetDomain() const; /* Возвращает имя документа. Примеры: / /index.html /images/photo.jpg */ std::string GetDocument() const; // возвращает тип протокола Protocol GetProtocol() const; std::string GetProtocolString() const; // возвращает номер порта unsigned short GetPort() const; private: std::string m_url = ""; std::string m_domain = ""; std::string m_document = ""; Protocol m_protocol = HTTP; unsigned short m_port = 80; void AddDomain(std::string const& possibleDomain); void AddDocument(std::string const& possibleDocument); void AddProtocol(std::string const& possibleProtocol); void AddPort(std::string const& possiblePort = ""); void AddUrl(); std::smatch GetParseResult(); std::string GetLowerString(std::string const& str); }; #endif /* CHttpUrl_hpp */
true
4e8f274680aa7198062046fb72de91bec1367128
C++
ailuoxz/BadPrincess-Game
/Src/Graphics/FrustumEntity.h
ISO-8859-1
2,413
2.890625
3
[]
no_license
//--------------------------------------------------------------------------- // Entity.h //--------------------------------------------------------------------------- /** @file Entity.h Contiene la declaracin de la clase que representa una entidad grfica. @see Graphics::CFrustumEntity @author Guidi Giacomo @date March, 2015 */ #ifndef __Graphics_FrustumEntity_H #define __Graphics_FrustumEntity_H #include "Graphics\Entity.h" #include <OgreFrustum.h> namespace Graphics { class CFrustumEntity : public CEntity { public: /** Constructor de la clase. @param name Nombre de la entidad. @param mesh Nombre del modelo que debe cargarse. */ CFrustumEntity(const std::string &name); /** Destructor de la aplicacin. */ virtual ~CFrustumEntity(); /** Devuelve el valor de la propiedad visible. La propiedad indica si la entidad debe dibujarse o no, es decir, no est relacionada con si la entidad est dentro del campo de visin de la cmara o no. @return Cierto si la entidad es visible (est activa para ser reenderizada). */ const bool getVisible(); void setAspectRatio(float aspectRatio); void setOrthoWindowHeight(float height); void setDebugDisplayEnabled(bool value); void setProjectionType(Ogre::ProjectionType type); void CFrustumEntity::setFarClipDistance(float height); const Ogre::Frustum * getFrustum(){return _entity;}; protected: /** Carga la entidad grfica correspondiente al nombre _mesh. No hace comprobacines de si la entidad est ya cargada o de si pertenece a otra escena. Esto se debe hacer de manera externa. @return true si la entidad pudo crear los objetos necesarios en Ogre o si la entidad ya estaba cargada. */ virtual bool load(); /** Elimina las estructuras creadas en Ogre mediante load(). No hace comprobacines de si la entidad est o no cargada o de si pertenece a una escena. Esto se debe hacer de manera externa. */ virtual void unload(); /** Actualiza el estado de la entidad cada ciclo. En esta clase no se necesita actualizar el estado cada ciclo, pero en las hijas puede que si. @param secs Nmero de segundos transcurridos desde la ltima llamada. */ virtual void tick(float secs); /** Entidad de Ogre. */ Ogre::Frustum *_entity; }; // class CFrustumEntity } // namespace Graphics #endif // __Graphics_Entity_H
true
5adeff8cdaa2329b25745fec603b478252e35cd1
C++
shumingcong/rgbd_pose_estimation
/pose/Simulator.hpp
UTF-8
16,117
2.640625
3
[ "MIT" ]
permissive
#ifndef _RAND_GENERATOR_HEADER_ #define _RAND_GENERATOR_HEADER_ #include <se3.hpp> #include <time.h> #include <limits> #include <random> #include "Utility.hpp" using namespace Eigen; using namespace std; std::default_random_engine generator; std::normal_distribution<double> distribution(0., 1.0); template< typename T > Matrix<T, 3, 1> generate_random_translation_uniform(T size) { Matrix<T, 3, 1> translation = Matrix< T, Dynamic, Dynamic>::Random(3, 1); return size * translation; } template< typename T > Sophus::SO3< T > generate_random_rotation(T max_angle_radian_, bool use_guassian_ = true) { Matrix<T, 3, 1> rv; if (use_guassian_){ rv[0] = distribution(generator); //standard normal distribution rv[1] = distribution(generator); rv[2] = distribution(generator); } else { rv = Matrix< T, Dynamic, Dynamic>::Random(3, 1); //uniform -1. to 1. } rv[0] = max_angle_radian_*rv[0]; //angle rotation around x rv[1] = max_angle_radian_*rv[1] * T(.5); // y axis rv[2] = max_angle_radian_*rv[2]; // z axis T m_pi_2 = T(M_PI / 2.); rv[0] = rv[0] > M_PI ? M_PI : rv[0]; rv[0] = rv[0] < -M_PI ? -M_PI : rv[0]; rv[1] = rv[1] > m_pi_2 ? m_pi_2 : rv[1]; rv[1] = rv[1] < -m_pi_2 ? -m_pi_2 : rv[1]; rv[2] = rv[2] > M_PI ? M_PI : rv[2]; rv[2] = rv[2] < -M_PI ? -M_PI : rv[2]; Matrix<T, 3, 3> R1; R1(0, 0) = 1.0; R1(0, 1) = 0.0; R1(0, 2) = 0.0; R1(1, 0) = 0.0; R1(1, 1) = cos(rv[0]); R1(1, 2) = -sin(rv[0]); R1(2, 0) = 0.0; R1(2, 1) = -R1(1, 2); //sin(rpy[0]); R1(2, 2) = R1(1, 1); //cos(rpy[0]) Matrix<T, 3, 3> R2; R2(0, 0) = cos(rv[1]); R2(0, 1) = 0.0; R2(0, 2) = sin(rv[1]); R2(1, 0) = 0.0; R2(1, 1) = 1.0; R2(1, 2) = 0.0; R2(2, 0) = -R2(0, 2); R2(2, 1) = 0.0; R2(2, 2) = R2(0, 0); Matrix<T, 3, 3> R3; R3(0, 0) = cos(rv[2]); R3(0, 1) = -sin(rv[2]); R3(0, 2) = 0.0; R3(1, 0) = -R3(0, 1); R3(1, 1) = R3(0, 0); R3(1, 2) = 0.0; R3(2, 0) = 0.0; R3(2, 1) = 0.0; R3(2, 2) = 1.0; Sophus::SO3< T > rotation(R3 * R2 * R1); return rotation; } template< typename T > void simulate_nl_nl_correspondences(const Sophus::SO3<T>& R_cw_, int number_, T noise_nl_, T outlier_ratio_nl_, bool use_guassian_, Matrix<T, Dynamic, Dynamic>* pM_, Matrix<T, Dynamic, Dynamic>* pN_, Matrix<T, Dynamic, Dynamic>* pN_gt = NULL, Matrix<T, Dynamic, Dynamic>* p_all_weights_ = NULL) { typedef Matrix<T, 3, 1> Point3; typedef Matrix<T, Dynamic, Dynamic> MX; MX w(number_, 1); //dynamic weights for N-N correspondences pM_->resize(3, number_); //normal in WRS pN_->resize(3, number_); //normal in CRS MX N_gt(3, number_); //ground truth normal in CRS for (int i = 0; i < number_; i++) { do { N_gt.col(i) = generate_random_rotation<T>( T(M_PI / 2.), false) * Point3(0, 0, -1); //have to be uniform distribution here N_gt.col(i).normalize(); pM_->col(i) = R_cw_.inverse() * N_gt.col(i); //transform to world reference system pM_->col(i).normalize(); //add noise pN_->col(i) = generate_random_rotation<T>(noise_nl_, use_guassian_) * N_gt.col(i); pN_->col(i).normalize(); } while (acos(pN_->col(i)(2)) < T(M_PI / 2)); //ensure that the normal is facing the camera //simulate weights w(i) = pN_->col(i).dot(N_gt.col(i)); } //add outliers int out = int(outlier_ratio_nl_*number_ + T(.5)); RandomElements<int> re(number_); vector<int> vIdx; re.run(out, &vIdx); for (int i = 0; i < out; i++){ Matrix< T, 3, 1> nl_g; do { pN_->col(i) = generate_random_rotation<T>(M_PI / 2, false) * Point3(0, 0, -1);//have to be uniform distribution here pN_->col(i).normalize(); } while (acos(pN_->col(i)(2)) < M_PI / 2); } if (pN_gt){ *pN_gt = N_gt; //note that p_nl_c_gt_ is not polluted by noise or outliers } if (p_all_weights_){ assert(p_all_weights_->rows() == number_ && p_all_weights_->cols() == 3); p_all_weights_->col(2) = w; } return; } //generate random 3-D point within a viewing frutum defined by //T min_depth_, T max_depth_, //T tan_fov_x, T tan_fov_y template< typename T > Matrix<T, 3, 1> generate_a_random_point(T min_depth_, T max_depth_, T tan_fov_x, T tan_fov_y) { T x_range = tan_fov_x * max_depth_; T y_range = tan_fov_y * max_depth_; Matrix<T, 3, 1> cleanPoint = Matrix<T, 3, 1>::Random(3, 1); cleanPoint[0] *= x_range; //x cleanPoint[1] *= y_range; //y cleanPoint[2] = (cleanPoint[2] + 1.) / 2. *(max_depth_ - min_depth_) + min_depth_; //z return cleanPoint; } //project a set of 3-D points in camera coordinate system to 2-D points template< typename T > Matrix<T, Dynamic, Dynamic> project_point_cloud(const Matrix<T, Dynamic, Dynamic>& pt_c, T f_){ Matrix<T, Dynamic, Dynamic> pt_2d(2, pt_c.cols()); for (int i = 0; i < pt_c.cols(); i++) { pt_2d.col(i)[0] = f_ * pt_c.col(i)[0] / pt_c.col(i)[2]; pt_2d.col(i)[1] = f_ * pt_c.col(i)[1] / pt_c.col(i)[2]; } return pt_2d; } template< typename T > Matrix<T, Dynamic, Dynamic> simulate_rand_point_cloud_in_frustum(int number_, T f_, T min_depth_, T max_depth_) { T tan_fov_x = T(320. / f_); //the frame resolution is 640x480 with principle point at the centre of the frame T tan_fov_y = T(240. / f_); Matrix<T, Dynamic, Dynamic> all_P(3, number_); for (int i = 0; i < (int)number_; i++){ bool is_outside_frustum = true; while (is_outside_frustum){ Matrix<T, 3, 1 > P = generate_a_random_point<T>(min_depth_, max_depth_, tan_fov_x, tan_fov_y); // generate random point in CRS all_P.col(i) = P; is_outside_frustum = !(fabs(P[0] / P[2]) < tan_fov_x && fabs(P[1] / P[2]) < tan_fov_y); //check whether the point is inside the frustum } } return all_P; } template< typename T > void simulate_2d_3d_correspondences(const Sophus::SO3<T>& R_cw_, const Matrix<T, 3, 1>& t_w_, int number_, T noise_, T outlier_ratio_, T min_depth_, T max_depth_, T f_, bool use_guassian_, Matrix<T, Dynamic, Dynamic>* pQ_, // *pQ_: points with noise in 3-D world system Matrix<T, Dynamic, Dynamic>* pU_, // *pU_: 2-D points Matrix<T, Dynamic, Dynamic>* pP_gt = NULL, // *pP_gt: ground truth of 3-D points in camera system Matrix<T, Dynamic, Dynamic>* p_all_weights_ = NULL) { typedef Matrix<T, Dynamic, Dynamic> MX; MX w(number_, 1); //dynamic weights for 2-3 correspondences //1. generate 3-D points P in CRS MX P_gt = simulate_rand_point_cloud_in_frustum<T>(number_, f_, min_depth_, max_depth_); //pt cloud in camera system //2. project to 2-D MX kp_2d = project_point_cloud<T>(P_gt, f_); //3. transform from world to camera coordinate system pQ_->resize(3, number_); for (int i = 0; i < number_; i++) { pQ_->col(i) = R_cw_.inverse() * (P_gt.col(i) - t_w_); } //4. add 2-D noise for (int i = 0; i < number_; i++) { Matrix<T, 2, 1> rv; //random variable if (use_guassian_) rv = Matrix<T, 2, 1>(distribution(generator), distribution(generator)); else rv = MX::Random(2, 1); w(i) = T(1.) / rv.norm(); kp_2d.col(i) = kp_2d.col(i) + noise_ * rv; } //5. add 2-D outliers int out = int(outlier_ratio_*number_ + .5); MX out_points = simulate_rand_point_cloud_in_frustum<T>(out, f_, min_depth_, max_depth_); //outliers remain in CRS MX out_2d_points = project_point_cloud<T>(out_points, f_); RandomElements<int> re(number_); vector<int> vIdx; re.run(out, &vIdx); for (int i = 0; i < out; i++){ kp_2d.col(vIdx[i]) = out_2d_points.col(i); } //6. convert to 2-D key points into unit vectors pU_->resize(3, number_); pU_->row(0) = kp_2d.row(0); pU_->row(1) = kp_2d.row(1); pU_->row(2) = f_ * MX::Ones(1,number_); for (int c = 0; c < number_; c++) { pU_->col(c).normalize(); } if (pP_gt){ *pP_gt = P_gt; //note that pt_c was not polluted by outliers } if (p_all_weights_){ assert(p_all_weights_->rows() == number_ && p_all_weights_->cols() == 3); p_all_weights_->col(0) = w; } return; } template< typename T > void simulate_2d_3d_3d_correspondences(const Sophus::SO3<T>& R_cw_, const Matrix<T, 3, 1>& t_w_, int number_, T noise_2d_, T noise_3d_, T outlier_ratio_, T min_depth_, T max_depth_, T f_, bool use_guassian_, Matrix<T, Dynamic, Dynamic>* pQ_, // *pQ_: points with noise in 3-D world system Matrix<T, Dynamic, Dynamic>* pU_, // *pU_: 2-D points Matrix<T, Dynamic, Dynamic>* pP_gt = NULL, // *pP_gt: ground truth of 3-D points in camera system Matrix<T, Dynamic, Dynamic>* p_all_weights_ = NULL) { typedef Matrix<T, Dynamic, Dynamic> MX; simulate_2d_3d_correspondences<T>(R_cw_, t_w_, number_, noise_2d_, outlier_ratio_, min_depth_, max_depth_, f_, use_guassian_, pQ_, pU_, pP_gt, p_all_weights_); MX w(number_, 1); //dynamic weights for 2-3 correspondences //1. generate 3-D points P in CRS //4. add 3-D noise for (int i = 0; i < number_; i++) { Matrix<T, 3, 1> rv; //random variable if (use_guassian_) rv = Matrix<T, 3, 1>(distribution(generator), distribution(generator), distribution(generator)); else rv = MX::Random(3, 1); w(i) = T(1.) / rv.norm(); pQ_->col(i) = pQ_->col(i) + noise_3d_*rv; } if (p_all_weights_){ assert(p_all_weights_->rows() == number_ && p_all_weights_->cols() == 3); p_all_weights_->col(1) = w; } return; } template< typename T > void simulate_3d_3d_correspondences(const Sophus::SO3<T>& R_cw_, const Matrix<T, 3, 1>& t_w_, int number_, T noise_, T outlier_ratio_, T min_depth_, T max_depth_, T f_, bool use_guassian_, Matrix<T, Dynamic, Dynamic>* pQ_, // *pQ_: points with noise in 3-D world system Matrix<T, Dynamic, Dynamic>* pP_gt = NULL, // *pP_gt: ground truth of 3-D points in camera system Matrix<T, Dynamic, Dynamic>* p_all_weights_ = NULL) { typedef Matrix<T, Dynamic, Dynamic> MX; MX w(number_, 1); //dynamic weights for 2-3 correspondences //1. generate 3-D points P in CRS MX P_gt = simulate_rand_point_cloud_in_frustum<T>(number_, f_, min_depth_, max_depth_); //pt cloud in camera system //3. transform from camera to world coordinate system pQ_->resize(3, number_); for (int i = 0; i < number_; i++) { pQ_->col(i) = R_cw_.inverse() * (P_gt.col(i) - t_w_); } //4. add 3-D noise for (int i = 0; i < number_; i++) { Matrix<T, 3, 1> rv; //random variable if (use_guassian_) rv = Matrix<T, 3, 1>(distribution(generator), distribution(generator), distribution(generator)); else rv = MX::Random(3, 1); w(i) = T(1.) / rv.norm(); pQ_->col(i) = pQ_->col(i) + noise_*rv; } //5. add 2-D outliers int out = int(outlier_ratio_*number_ + .5); MX out_points = simulate_rand_point_cloud_in_frustum<T>(out, f_, min_depth_, max_depth_); //outliers remain in CRS RandomElements<int> re(number_); vector<int> vIdx; re.run(out, &vIdx); for (int i = 0; i < out; i++){ pQ_->col(vIdx[i]) = out_points.col(i); } if (pP_gt){ *pP_gt = P_gt; //note that pt_c was not polluted by outliers } if (p_all_weights_){ assert(p_all_weights_->rows() == number_ && p_all_weights_->cols() == 3); p_all_weights_->col(1) = w; } return; } template< typename T > void simulate_2d_3d_nl_correspondences(const Sophus::SO3<T>& R_cw_, const Matrix<T, 3, 1>& t_w_, //rotation and translation in world reference system int number_, // total number of correspondences T n2D_, T or_2D_, //noise level and outlier ratio for 2-3 correspondences T n3D_, T or_3D_, //noise level and outlier ratio for 3-3 correspondences T nNl_, T or_Nl_, //noise level and outlier ratio for N-N correspondences T min_depth_, T max_depth_, T f_, bool use_guassian_, //outputs Matrix<T, Dynamic, Dynamic>* pQ_, Matrix<T, Dynamic, Dynamic>* pM_, //Q and M are 3-D points and normal in world Matrix<T, Dynamic, Dynamic>* pP_, Matrix<T, Dynamic, Dynamic>* pN_, //P and N are 3-D points and normal in camera system Matrix<T, Dynamic, Dynamic>* pU_,//U are the unit vectors pointing from camera centre to 2-D key points Matrix<T, Dynamic, Dynamic>* p_all_weights_ = NULL) //store all weights for 2-3, 3-3 and N-N correspondences { Matrix<T, Dynamic, Dynamic> all_weights(number_, 3); //generate 2-D to 3-D pairs Matrix<T, Dynamic, Dynamic> P_gt; //ground truth 3-D points in camera reference system simulate_2d_3d_correspondences<T>(R_cw_, t_w_, number_, n2D_, or_2D_, min_depth_, max_depth_, f_, use_guassian_, &*pQ_, &*pU_, &P_gt, &all_weights); //generate normal to normal pairs Matrix<T, Dynamic, Dynamic> nl_c_gt; simulate_nl_nl_correspondences<T>(R_cw_, number_, nNl_, or_Nl_, true, &*pM_, &*pN_, &nl_c_gt, &all_weights); //add noise to 3-D points in camera reference frame pP_->resize(3, number_); for (int i = 0; i < number_; i++) { Matrix<T, 3, 1> rv; //random variable if (use_guassian_) //use Guassian noise rv = Matrix<T, 3, 1>(distribution(generator), distribution(generator), distribution(generator)); else rv = Matrix<T, Dynamic, Dynamic>::Random(3, 1); //all_weights(i, 1) = short(rv.norm() / 1.414 * numeric_limits<short>::max()); //simulate weights all_weights(i, 1) = T(1.) / rv.norm(); pP_->col(i) = P_gt.col(i) + n3D_ * rv; } //add 3-D outliers int out = int(or_3D_*number_ + .5); RandomElements<int> re(number_); vector<int> vIdx; re.run(out, &vIdx); Matrix<T, Dynamic, Dynamic> pt_c_out = simulate_rand_point_cloud_in_frustum(out, f_, min_depth_, max_depth_); for (int i = 0; i < out; i++){ pP_->col(vIdx[i]) = pt_c_out.col(i); } if (p_all_weights_){ assert(p_all_weights_->rows() == number_ && p_all_weights_->cols() == 3); *p_all_weights_ = all_weights; } return; } template< typename T > T lateral_noise_kinect(T theta_, T z_, T f_) { //Nguyen, C.V., Izadi, S., &Lovell, D. (2012).Modeling kinect sensor noise for improved 3D reconstruction and tracking.In 3DIM / 3DPVT (pp. 524?30).http://doi.org/10.1109/3DIMPVT.2012.84 T sigma_l; sigma_l = T(.8) + T(.035)*theta_ / (T(M_PI / 2.) - theta_); sigma_l = sigma_l * z_ / f_; return sigma_l; } template< typename T > T axial_noise_kinect(T theta_, T z_){ T sigma_a; if (fabs(theta_) <= T(M_PI / 3.)) sigma_a = T(.0012) + T(.0019)*(z_ - 0.4)*(z_ - 0.4); else sigma_a = T(.0012) + T(.0019)*(z_ - 0.4)*(z_ - 0.4) + T(.0001) * theta_* theta_ / sqrt(z_) / (M_PI / 2 - theta_) / (M_PI / 2 - theta_); return sigma_a; } template< typename T > void simulate_kinect_2d_3d_nl_correspondences(const Sophus::SO3<T>& R_cw_, const Matrix<T, 3, 1>& t_w_, int number_, T noise_2d_, T outlier_ratio_2d_, T outlier_ratio_3d_, T noise_nl_, T outlier_ratio_nl_, T min_depth_, T max_depth_, T f_, Matrix<T, Dynamic, Dynamic>* p_pt_w_, Matrix<T, Dynamic, Dynamic>* p_nl_w_, Matrix<T, Dynamic, Dynamic>* p_pt_c_, Matrix<T, Dynamic, Dynamic>* p_nl_c_, Matrix<T, Dynamic, Dynamic>* p_bv_, Matrix<T, Dynamic, Dynamic>* p_weights_ = NULL) { Matrix<T, Dynamic, Dynamic> all_weights(number_, 3); //simulated weights Matrix<T, Dynamic, Dynamic> pt_c_gt; //ground truth 3-D points in camera reference system simulate_2d_3d_correspondences<T>(R_cw_, t_w_, number_, noise_2d_, outlier_ratio_2d_, min_depth_, max_depth_, f_, true, &*p_pt_w_, &*p_bv_, &pt_c_gt, &all_weights); //generate normal to normal pairs Matrix<T, Dynamic, Dynamic> nl_c_gt; simulate_nl_nl_correspondences<T>(R_cw_, number_, noise_nl_, outlier_ratio_nl_, true, &*p_nl_w_, &*p_nl_c_, &nl_c_gt, &all_weights); T sigma_min = axial_noise_kinect<T>(T(.0), min_depth_); //add Gaussian noise to 3-D points in camera reference frame p_pt_c_->resize(3, number_); for (int i = 0; i < number_; i++) { T theta = acos(nl_c_gt.col(i).dot(Matrix<T, 3, 1>(0, 0, -1))); T z = pt_c_gt.col(i)(2); T sigma_l = lateral_noise_kinect<T>(theta, z, f_); T sigma_a = axial_noise_kinect<T>(theta, z); Matrix<T, 3, 1> random_variable(sigma_l*distribution(generator), sigma_l*distribution(generator), sigma_a*distribution(generator)); p_pt_c_->col(i) = pt_c_gt.col(i) + random_variable; all_weights(i, 1) = T(sigma_min / sigma_a); } //add 3-D outliers int out = int(outlier_ratio_3d_*number_ + .5); RandomElements<int> re(number_); vector<int> vIdx; re.run(out, &vIdx); Matrix<T, Dynamic, Dynamic> pt_c_out = simulate_rand_point_cloud_in_frustum(out, f_, min_depth_, max_depth_); for (int i = 0; i < out; i++){ p_pt_c_->col(vIdx[i]) = pt_c_out.col(i); } if (p_weights_){ assert(p_weights_->rows() == number_ && p_weights_->cols() == 3); *p_weights_ = all_weights; } return; } #endif
true
fbcad2ceb6d5419cdb73333629e24c3c703fb598
C++
tomekmucha85/sea
/Screen.hpp
UTF-8
754
2.59375
3
[]
no_license
#ifndef SCREEN_HPP #define SCREEN_HPP #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <stdio.h> class Screen { private: //Screen dimension constants static const int SCREEN_WIDTH; static const int SCREEN_HEIGHT; //static const int RESOLUTION_W = 640; //static const int RESOLUTION_H = 480; public: static bool should_be_fullscreen; //The window itself static SDL_Window* window; //The window renderer static SDL_Renderer* renderer; //################### //Functions //################### Screen(); ~Screen(); bool Init(); static int TellScreenWidth(); static int TellScreenHeight(); }; #endif //SCREEN_HPP
true
08429a526bd9c2fbc76e2765b301c73c54e78768
C++
enzohorquin/School-Projects-for-Analysis-and-Design-of-Algorithms-II
/Ejercicio6TP1/main.cpp
WINDOWS-1250
4,508
3.15625
3
[]
no_license
#include "TP2_Grafo.h" #include "list" #include "iostream" struct nodo { char letra; string color; int v;}; using namespace std; void ImprimeLista(list<int> & Lista); void DFS(Grafo<int> & G,list<int> & Caminos, bool Marca [ ],int origen, int destino, list<nodo> Listacolores); struct nodoMarca{ int v; bool Visitado;}; template <typename C> ostream & operator << (ostream & salida, const Grafo<C> & grafo) { // Recorremos todos los vertices list<int> vertices; grafo.devolverVertices(vertices); list<int>::iterator v = vertices.begin(); while (v != vertices.end()) { salida << " " << *v << "\n"; // Recorremos todos los adyacentes de cada vertice list<typename Grafo<C>::Arco> adyacentes; grafo.devolverAdyacentes(*v, adyacentes); typename list<typename Grafo<C>::Arco>::iterator ady = adyacentes.begin(); while (ady != adyacentes.end()) { salida << " " << *v << "-> " << ady->devolverAdyacente() << " (" << ady->devolverCosto() << ")\n"; ady++; } v++; } return salida; } int main(int argc, char **argv) { Grafo<int> g; // Cargamos un grafo dirigido // Primero los vrtices g.agregarVertice(1); g.agregarVertice(2); g.agregarVertice(2); g.agregarVertice(3); g.agregarVertice(4); g.agregarVertice(5); g.agregarVertice(6); g.agregarVertice(7); g.agregarVertice(8); g.agregarVertice(9); g.agregarVertice(10); // Luego los arcos g.agregarArco(1,2,1); g.agregarArco(2,3,1); g.agregarArco(1,4,1); g.agregarArco(4,7,1); g.agregarArco(5,4,1); g.agregarArco(5,3,1); g.agregarArco(6,3,1); g.agregarArco(8,3,1); g.agregarArco(7,6,1); g.agregarArco(7,10,1); g.agregarArco(10,9,1); g.agregarArco(10,8,1); g.agregarArco(9,8,1); cout << "Estructura del grafo:\n" << g << "\n"; list<nodo> Listacolores; nodo nuevo; nuevo.color = "blanco"; nuevo.letra = 'A'; nuevo.v= 1; Listacolores.push_back(nuevo); nuevo.color = "rojo"; nuevo.letra = 'B'; nuevo.v=2; Listacolores.push_back(nuevo); nuevo.color = "blanco"; nuevo.letra = 'C'; nuevo.v=3; Listacolores.push_back(nuevo); nuevo.color = "verde"; nuevo.letra = 'E'; nuevo.v=4; Listacolores.push_back(nuevo); nuevo.color = "azul"; nuevo.letra = 'D'; nuevo.v=5; Listacolores.push_back(nuevo); nuevo.color = "verde"; nuevo.letra = 'J'; nuevo.v=6; Listacolores.push_back(nuevo); nuevo.color = "amarillo"; nuevo.letra = 'F'; nuevo.v=7; Listacolores.push_back(nuevo); nuevo.color = "azul"; nuevo.letra = 'I'; nuevo.v=8; Listacolores.push_back(nuevo); nuevo.color = "rojo"; nuevo.letra = 'H'; nuevo.v=9; Listacolores.push_back(nuevo); nuevo.color = "rojo"; nuevo.letra = 'G'; nuevo.v=10; Listacolores.push_back(nuevo); bool Marca[11]; for(int i=1;i<=11;i++) { Marca[i]= false; } list<int> Caminos; int origen; int destino; cout<< "Ingrese vertice Origen : "; cin>>origen; cout<<endl<<"Ingrese vertice destino : "; cin>>destino; cout<<endl; DFS(g,Caminos,Marca,origen,destino,Listacolores); } void DFS(Grafo<int> & G,list<int> & Caminos , bool Marca [ ],int origen, int destino,list<nodo> Listacolores) { Marca[origen]= true; Caminos.push_back(origen); if(origen==destino) { ImprimeLista(Caminos); } else { list<typename Grafo<int>::Arco> Ady; G.devolverAdyacentes(origen,Ady); typename list< Grafo<int>::Arco>:: iterator iteListaAdyacentes; iteListaAdyacentes= Ady.begin(); while(iteListaAdyacentes!= Ady.end()) { int V=iteListaAdyacentes->devolverAdyacente(); if ((Marca[V]== false)) { typename list<nodo>:: iterator it; it=Listacolores.begin(); while((it!=Listacolores.end())&& (it->v!= V)) it++; if((it->v==V)&&(it->color!="rojo")) { DFS(G,Caminos,Marca,V,destino,Listacolores); } } iteListaAdyacentes++; } } Marca[origen]=false; typename list<int>:: iterator ite; ite=Caminos.begin(); while((ite!=Caminos.end())&&(*ite != origen)) ite++; Caminos.erase(ite); } void ImprimeLista(list<int> & Lista) { typename list<int>:: iterator ite; ite=Lista.begin(); cout<< " Camino :"; while(ite!=Lista.end()) { cout<<*ite<< " "; ite++; } }
true
490487ecc2f5ea72f363eabd65b8437f6be3ba67
C++
tjresearch/research-richard
/code/src/communication.cpp
UTF-8
2,421
3.015625
3
[]
no_license
#include "global.h" /** * For each car, creates an event based on current speed */ void createEvents() { for (auto it = graphCars.begin(); it != graphCars.end(); it++) { Car& car = it->second; if (!car.isDTD) continue; if (car.roadIndex != -1) { if (car.eventSent) { car.eventSent = false; graphEvents[EVENT_COUNT] = Event(EVENT_COUNT, car.currentRoad, car.currentRoad->actualSpeed, car.currentRoad->speedLimit, CURRENT_TIME); car.recentEvent = car.events[car.currentRoad->id] = &graphEvents[EVENT_COUNT++]; } else { car.recentEvent->startTime = CURRENT_TIME; } } } } /** * Given two Cars, compare each of the stored Events for each road * Store the more recent Event for each road in both Cars */ void exchangeEvents(Car& c1, Car& c2) { for (int i = 0; i < EDGE_COUNT; i++) { if (c1.oldEvents[i]->id == -1) { c1.events[i] = c2.oldEvents[i]; c2.eventSent = true; } else if (c2.oldEvents[i]->id == -1) { c2.events[i] = c1.oldEvents[i]; c1.eventSent = true; } else { if (c1.oldEvents[i]->startTime < c2.oldEvents[i]->startTime) { c1.events[i] = c2.oldEvents[i]; c2.eventSent = true; } else { c2.events[i] = c1.oldEvents[i]; c1.eventSent = true; } } } } /** * For each pair of Cars within 'COMMUNICATION_RANGE', exchange all Events */ void transferEvents() { for (auto it = graphCars.begin(); it != graphCars.end(); it++) { Car& car = it->second; for (int i = 0; i < EDGE_COUNT; i++) { if (car.events[i]->hasExpired()) { car.events[i] = car.oldEvents[i] = &graphEvents[-1]; } else { car.oldEvents[i] = car.events[i]; } } } for (auto it1 = graphCars.begin(); it1 != graphCars.end(); it1++) { Car& c1 = it1->second; if (!c1.isDTD) continue; auto it2 = it1; it2++; for (; it2 != graphCars.end(); it2++) { Car& c2 = it2->second; if (!c2.isDTD) continue; ld dist = distance(c1, c2); if (dist <= COMMUNICATION_RANGE) { exchangeEvents(c1, c2); } } } } /** * Removes all expired events from 'graphEvents' */ void cleanEvents() { cout << "USING THIS WILL CAUSE eventOutput() from 'files.cpp' TO NOT WORK PROPERLY" << endl; return; vector<int> toErase; for (auto it = graphEvents.begin(); it != graphEvents.end(); it++) { Event& ev = it->second; if (ev.hasExpired()) { toErase.pb(it->first); } } for (int key: toErase) { graphEvents.erase(key); } }
true
ff7aabeb996de16ce75fe029496228e6851be69a
C++
luisenano90/Cajero-beta-
/Finanzas(archivos).cpp
ISO-8859-1
14,391
2.578125
3
[]
no_license
#include <iostream> //Libreras incluidas. #include <stdlib.h> #include <locale.h> #include <string> #include <fstream> #include<iomanip> //variables principales int user, day, month, year = 0; int opt, opt_cat, opt_r, opt_pay, opt_trans; int intentos = 3; double saldo, gasto, ingresos, saldo_f,billetera,tarjeta, monto = 0; using namespace std; string archive_name2=""; string archive_name=""; string text_reg = ""; fstream archivo; bool search_helper=false; string answer=""; string ingreso, id_reference =""; string et; string warn = "Un mal uso de la app le podria provocar la restriccin de su cuenta."; //warn (aviso) string ver = "1.0.100";//Nmero de version... string pass_help, id_help = ""; //variables string //Inicio del programa---------------------------------------------------------------------------------------- void user_new() { string user_question = ""; string user_new_pass = ""; string user_file = ""; cout<<"Ingrese el nombre de usuario que desea registrar:"<<endl; cin>>user_question; cout<<"Digite la contrasea"<<endl; cin>>user_new_pass; user_file = user_question+".txt"; archivo.open(user_file.c_str(),ios::app); archivo<<user_new_pass<<endl; archivo.close(); cout<<"Nuevo usuario registrado...!!"<<endl; } void comentary_register() { archivo.open(archive_name2.c_str(),ios::app); if (opt == 1 && opt_r == 1) archivo<<"Realiz una recarga a su tarjeta de: $"<<saldo<<" el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt == 1 && opt_r ==2) archivo<<"Realiz una recarga a su billetera de: $"<<saldo<<" el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt_cat == 1) archivo<<"Realiz un gasto en la categora hogar de: $"<<gasto<<", comprando: "<<et<<", el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt_cat == 2) archivo<<"Realiz un gasto en la categora escolar de: $"<<gasto<<", comprando: "<<et<<", el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt_cat == 3) archivo<<"Realiz un gasto en la categora trabajo de: $"<<gasto<<", comprando: "<<et<<", el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt_cat == 4) archivo<<"Realiz un gasto en la categora salud de: $"<<gasto<<", comprando: "<<et<<", el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt_cat == 5) archivo<<"Realiz un gasto en la categora diversin de: $"<<gasto<<", comprando: "<<et<<", el da: "<<day<<"/"<<month<<"/"<<year<<endl; else if (opt_trans == 1) archivo<<"Realiz una transferencia a su tarjeta con un monto de: $"<<monto<<endl; else if (opt_trans == 2) archivo<<"Realiz una transferencia a su tarjeta con un monto de: $"<<monto<<endl; archivo.close(); } void read_archive() { archivo.open(archive_name.c_str()); archivo>>pass_help; archivo>>tarjeta; archivo>>billetera; archivo.close(); } void search_process() { string pass_reference=""; archivo.open(archive_name.c_str()); archivo>>pass_reference; if(pass_help==pass_reference) { search_helper=true; } archivo.close(); } void save_datas() //standby... { archivo.open(archive_name.c_str()); archivo<<pass_help<<'\n'; archivo<<tarjeta<<'\n'; archivo<<billetera<<'\n'; archivo.close(); } void categorias() { et=""; cout<<"Bienvenido al sistema de categorias..."<<endl; cout<<""<<endl; cout<<"El sistema de categoras presenta secciones a elegir como referencia a su gasto..."<<endl; cout<<""<<endl; cout<<"Seleccione la categora a relazionar con el gasto"<<endl; cout<<"1.- hogar"<<endl; cout<<"2.- escolar"<<endl; cout<<"3.- trabajo"<<endl; cout<<"4.- salud"<<endl; cout<<"5.- Diversin"<<endl; cin>>opt_cat; system("cls"); if (opt_cat == 1) { cout<<"Opcion hogar seleccionada..."<<endl; cout<<"De cuanto ser su gasto?"<<endl; cin>>gasto; cout<<"Con que desea pagarlo 1.- Tarjeta o 2.- Billetera?"<<endl; cin>>opt_pay; if (opt_pay == 1) { tarjeta= tarjeta - gasto; save_datas(); } else { billetera=billetera-gasto; save_datas(); } cout<<"Realizado..."<<endl; cout<<"Digite la fecha actual"<<endl; cout<<"----------------------"<<endl; cout<<"Da: ";cin>>day; cout<<"Mes: ";cin>>month; cout<<"Ao: ";cin>>year; cout<<"Aada una etiqueta del gasto..."<<endl; cin>>et; comentary_register(); } else if (opt_cat==2) { cout<<"Opcion escolar seleccionada..."<<endl; cout<<"De cuanto es el gasto?"<<endl; cin>>gasto; cout<<"Con que desea pagarlo: 1.- Tarjeta o 2.- Billetera??"<<endl; cin>>opt_pay; if (opt_pay == 1) { tarjeta= tarjeta - gasto; save_datas(); } else { billetera=billetera-gasto; save_datas(); } cout<<"Realizado..."<<endl; cout<<"Digite la fecha actual"<<endl; cout<<"----------------------"<<endl; cout<<"Da: ";cin>>day; cout<<"Mes: ";cin>>month; cout<<"Ao: ";cin>>year; cout<<"Aada una etiqueta del gasto..."<<endl; cin>>et; comentary_register(); } else if (opt_cat==3) { cout<<"Opcion trabajo seleccionada..."<<endl; cout<<"De cuanto ser su gasto?"<<endl; cin>>gasto; cout<<"Con que desea pagarlo 1.- Tarjeta o 2.- Billetera?"<<endl; cin>>opt_pay; if (opt_pay == 1) { tarjeta= tarjeta - gasto; save_datas(); } else { billetera=billetera-gasto; save_datas(); } cout<<"Realizado..."<<endl; cout<<"Digite la fecha actual"<<endl; cout<<"----------------------"<<endl; cout<<"Da: ";cin>>day; cout<<"Mes: ";cin>>month; cout<<"Ao: ";cin>>year; cout<<"Aada una etiqueta del gasto..."<<endl; cin>>et; comentary_register(); } else if (opt_cat==4) { cout<<"Opcion Salud seleccionada..."<<endl; cout<<"De cuanto ser su gasto?"<<endl; cin>>gasto; cout<<"Con que desea pagarlo 1.- Tarjeta o 2.- Billetera?"<<endl; cin>>opt_pay; if (opt_pay == 1) { tarjeta= tarjeta - gasto; save_datas(); } else { billetera=billetera-gasto; save_datas(); } cout<<"Realizado..."<<endl; cout<<"Digite la fecha actual"<<endl; cout<<"----------------------"<<endl; cout<<"Da: ";cin>>day; cout<<"Mes: ";cin>>month; cout<<"Ao: ";cin>>year; cout<<"Aada una etiqueta del gasto..."<<endl; cin>>et; comentary_register(); } else if (opt_cat==5) { cout<<"Opcion Diversin seleccionada..."<<endl; cout<<"De cuanto ser su gasto?"<<endl; cin>>gasto; cout<<"Con que desea pagarlo 1.- Tarjeta o 2.- Billetera?"<<endl; cin>>opt_pay; if (opt_pay==1) { tarjeta= tarjeta - gasto; save_datas(); } else { billetera=billetera-gasto; save_datas(); } cout<<"Realizado..."<<endl; cout<<"Digite la fecha actual"<<endl; cout<<"----------------------"<<endl; cout<<"Da: ";cin>>day; cout<<"Mes: ";cin>>month; cout<<"Ao: ";cin>>year; cout<<"Aada una etiqueta del gasto..."<<endl; cin>>et; comentary_register(); } else { cout<<"Categora desconocida. Regresando al men..."<<endl; } } void transferencia() { cout<<"Bienvenido al men de transferencias [Finanzas doa tota]"<<endl; cout<<"El sistema de finanzas doa tota aplica movimientos entre tarjeta y billetera"<<endl; cout<<""<<endl; cout<<"------------------------"<<endl; cout<<"Saldo total"<<saldo_f<<endl; cout<<"A donde desea transefir dinero?"<<endl; cout<<"1.- Tarjeta..."<<endl; cout<<"2.- Billetera..."<<endl; cin>>opt_trans; if (opt_trans==1) { cout<<"------------------------------------------------------"<<endl; cout<<"Bienvenido al sistema de transferencias a su tarjeta"<<endl; cout<<"cuanto desea mover a su tarjeta?"<<endl; cin>>monto; cout<<""<<endl; billetera = billetera - monto; tarjeta = tarjeta + monto; cout<<"Realizando transaccin..."<<endl; cout<<"Transaccin realizada..."<<endl; cout<<"Saldo actualizado en tarjeta y billetera"<<endl; cout<<"Digite la fecha"<<endl; cout<<"Dia: "<<endl; cin>>day; cout<<"Mes"<<endl; cin>>month; cout<<"Ao:"<<endl; cin>>year; cout<<"Ingrese una etiqueta"<<endl; cin>>et; cout<<"-------------------------------------------------------"<<endl; save_datas(); comentary_register(); } else { cout<<"--------------------------------------------------------"<<endl; cout<<"Bienvenido al sistema de transferencias a su billetera personal"<<endl; cout<<"Cuanto desea mover a su billetera personal?"<<endl; cin>>monto; cout<<""<<endl; tarjeta = tarjeta - monto; billetera = billetera + monto; cout<<"Realizando transaccin..."<<endl; cout<<"Transaccin realizada..."<<endl; cout<<"Saldo actualizado en tarjeta y billetera"<<endl; cout<<"Digite la fecha!"<<endl; cout<<"Dia: "<<endl; cin>>day; cout<<"Mes"<<endl; cin>>month; cout<<"Ao:"<<endl; cin>>year; cout<<"Ingrese una etiqueta"<<endl; cin>>et; cout<<"-------------------------------------------------------"<<endl; save_datas(); comentary_register(); } } int main() //Programa principal... { setlocale(LC_ALL,"spanish"); //Funcin que ayuda a la sintaxis para mostrar puntuaciones... while (true) { tarjeta=0; billetera=0; cout<<"*****************************************************************"<<endl; cout<<"Bienvenido al sistema de finanzas 2020-2021 Longoria's Corporation"<<endl; cout<<"*****************************************************************"<<endl; cout<<"Versin: "<<ver<<endl; cout<<""<<endl; cout<<"------------------------------------------------------------------------------"<<endl; cout<<"El sistema de finanzas que le ayudar a observar sus ingresos y egresos diarios"<<endl; cout<<"AVISO: "<<warn<<endl; cout<<"------------------------------------------------------------------------------"<<endl; system("pause"); system("cls"); cout<<"Desea registrar un nuevo usuario"<<endl; cin>>answer; if (answer == "si" || answer == "SI" || answer=="Si") user_new(); cout<<"Bienvenido usuario, Digite su ID personal como primer paso de inicio de sesin:"<<endl; cin>>id_help; cout<<"Digite su password contrasea!..."<<endl; cin>>pass_help; system("cls"); archive_name=id_help+".txt"; search_process(); if (search_helper) { do { archive_name2="Registers-"+id_help+".txt"; //registros archivo.open(archive_name2.c_str(),ios::app); archivo.close(); read_archive(); saldo_f=0; system("cls"); //------------------------------------------------------------------------// MEN cout<<"Bienvenido: "<<id_help<<", Que desea hacer?"<<endl; cout<<""<<endl; cout<<"Men principal... "<<endl; cout<<"1.- Recargar saldo"<<endl; cout<<"2.- Transacciones realizadas"<<endl; cout<<"3.- Realizar una transferencia"<<endl; cout<<"4.- Realizar gasto (Visita a la seccin de categoras!)"<<endl; cout<<"5.- Salir "<<endl; cout<<"-----------------"<<endl; cout<<""<<endl; //salto de linea... cin>>opt; system("cls"); switch (opt) //Switch Case principal { case 1: { cout<<"Hola usuario: "<<id_help<<" Cuanto desea recargar?"<<endl; cin>>saldo; cout<<"A donde desea mandarlo?"<<endl; cout<<"1.- Tarjeta"<<endl; cout<<"2.- Billetera"<<endl; cin>>opt_r; cout<<"Que tipo de ingreso es...?"<<endl; cin>>ingreso; system("cls"); if (opt_r==1) { cout<<"-----------------------"<<endl; cout<<"Recargando a tarjeta..."<<endl; cout<<""<<endl; cout<<"Saldo actualizado!!!"<<endl; cout<<""<<endl; tarjeta+=saldo; cout<<"Ingreso de: "<<ingreso<<endl; cout<<""<<endl; cout<<"Saldo en tarjeta: $"<<tarjeta<<endl; cout<<"-----------------------"<<endl; cout<<"ingrese el da"<<endl; cin>>day; cout<<"ingrese el mes"<<endl; cin>>month; cout<<"ingrese el ao"<<endl; cin>>year; save_datas(); comentary_register(); } else if (opt_r==2) { cout<<"-------------------------"<<endl; cout<<"Recargando a billetera..."<<endl; cout<<""<<endl; cout<<"Saldo acutalizado!!!"<<endl; cout<<""<<endl; billetera+=saldo; cout<<"Ingreso de: "<<ingreso<<endl; cout<<""<<endl; cout<<"Saldo en billetera: $"<<billetera<<endl; cout<<"-------------------------"<<endl; cout<<"ingrese el da"<<endl; cin>>day; cout<<"ingrese el mes"<<endl; cin>>month; cout<<"ingrese el ao"<<endl; cin>>year; save_datas(); comentary_register(); } } break; case 2: { cout<<"Mostrando transacciones realizadas y sus saldos totales..."<<endl; cout<<"-----------------------------------"<<endl; archivo.open(archive_name2.c_str()); string ayudante = ""; while (!archivo.eof()) { getline(archivo,ayudante); cout<<ayudante<<endl; } archivo.close(); cout<<""<<endl; cout<<"Saldo inicial: $"<<saldo<<endl; cout<<"Gasto realizado: $"<<gasto<<endl; cout<<""<<endl; cout<<"-------------------------------------"<<endl; cout<<"Su saldo actual en billetera es: $"<<billetera<<endl; cout<<"su saldo actual en tarjeta es: $"<<tarjeta<<endl; saldo_f= tarjeta + billetera; cout<<"Saldo final: $"<<saldo_f<<endl; cout<<"-------------------------------------"<<endl; system("pause"); system("cls"); } break; case 3: { transferencia(); system("cls"); } break; case 4: { categorias(); system("cls"); } break; case 5: break; break; default: cout<<"Seccin desconocida---ERROR 241@C1_s"<<endl; break; } //fin del switch case principal... system("pause"); }while(opt!=5); } else cout<<"user and pass incorrect!! ERROR 2_a@x33"<<endl; system("cls"); } return 0; }
true
ce09081e691b8f106ee0cabdfb5774efef808a2d
C++
lchavez287/eecs_268
/Lab09/Queue.hpp
UTF-8
1,787
3.984375
4
[]
no_license
/** * @file : Queue.hpp * @author : Lacie Chavez * @date : 04/25/2014 * Purpose: Implementation of Queue class */ template<typename T> Queue<T>::Queue() //default constructor { frontPtr=nullptr; backPtr=nullptr; size1 = 0; } template<typename T> Queue<T>::~Queue() //destructor { while(!isEmpty()) { dequeue(); } } template<typename T> bool Queue<T>::isEmpty()const //checks to see if que is empty { if(size()== 0) { return true; } else return false; } template<typename T> //function to enque void Queue<T>::enqueue(const T newEntry) { Node<T>* newPtr = new Node<T>(); newPtr -> setValue(newEntry); newPtr->setLeft(nullptr); newPtr->setRight(nullptr); if(isEmpty())//if queue is empty { frontPtr = newPtr; backPtr = newPtr; } else { newPtr -> setLeft(backPtr); backPtr -> setRight(newPtr); newPtr -> setRight(nullptr); backPtr = newPtr; } size1++; } template<typename T> T Queue<T>::dequeue() throw(PreconditionViolationException) { if(!isEmpty())//if queue is not empty { Node<T>* deletePtr = frontPtr; if(frontPtr == backPtr)//if there is only 1 node in queue { frontPtr = nullptr; backPtr = nullptr; } else { frontPtr = frontPtr -> getRight(); deletePtr -> setRight(nullptr); } delete deletePtr; deletePtr = nullptr; size1--; } else throw PreconditionViolationException("Dequeue tried on an empty queue. "); } template<typename T> T Queue<T>::peekfront() const throw(PreconditionViolationException)//function to peek at front value { if(isEmpty()) { throw PreconditionViolationException("Peek attempted on an empty queue"); } else { return frontPtr->getValue(); } } template<typename T> int Queue<T>::size() const //function to get the size { return size1; }
true
673b49301a8b920d5f4c2d8e6247dbf3f8408aad
C++
rushioda/PIXELVALID_athena
/athena/DetectorDescription/GeoModel/GeoModelKernel/GeoModelKernel/GeoFacet.h
UTF-8
1,738
2.84375
3
[]
no_license
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef GeoFacet_h #define GeoFacet_h 1 // Class: GeoFacet // // Base class for GeoModel Facets // Two implementations exist: // 1. GeoTriangularFacet // 2. GeoQuadrangularFacet // #include "GeoModelKernel/RCBase.h" #include "CLHEP/Vector/ThreeVector.h" #include <vector> typedef CLHEP::Hep3Vector GeoFacetVertex; // ** Base class class GeoFacet : public RCBase { public: enum GeoFacetVertexType { ABSOLUTE, RELATIVE }; inline size_t getNumberOfVertices() const; inline GeoFacetVertex getVertex(size_t) const; inline GeoFacetVertexType getVertexType() const; protected: GeoFacet() : m_nVertices(0), m_vertexType(ABSOLUTE) {}; virtual ~GeoFacet(){}; size_t m_nVertices; std::vector<GeoFacetVertex> m_vertices; GeoFacetVertexType m_vertexType; }; // ** Triangular facet class GeoTriangularFacet : public GeoFacet { public: GeoTriangularFacet(GeoFacetVertex ,GeoFacetVertex ,GeoFacetVertex ,GeoFacetVertexType); virtual ~GeoTriangularFacet(); }; // ** Quadrangular facet class GeoQuadrangularFacet : public GeoFacet { public: GeoQuadrangularFacet(GeoFacetVertex ,GeoFacetVertex ,GeoFacetVertex ,GeoFacetVertex ,GeoFacetVertexType); virtual ~GeoQuadrangularFacet(); }; // ** Inline methods inline size_t GeoFacet::getNumberOfVertices() const { return m_nVertices; } inline GeoFacetVertex GeoFacet::getVertex(size_t index) const { return (index<m_nVertices ? m_vertices[index] : GeoFacetVertex(999999.,999999.,999999.)); } inline GeoFacet::GeoFacetVertexType GeoFacet::getVertexType() const { return m_vertexType; } #endif
true
cd1e653bfc9d8f2d758c6820d2725963e5b9defb
C++
ssy02060/algorithm
/hello.cpp
UTF-8
1,018
3.140625
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> int stack[200000]; int top = -1; int isEmpty(){ return top == -1; } void push(char data){ stack[++top] = data; } int pop(){ return stack[top--]; } int peek(){ return stack[top]; } void clear(){ for(int i = 0; i < top; i++){ stack[i] = 0; } } int get_result(char* str){ int len; len = strlen(str); for(int i = 0; i < len; i++){ if(str[i] == '(' ){ push(str[i]); } else if(str[i] == ')'){ if(!isEmpty()){ pop(); } else return -1; } } if(top >= 0){ return -1; } return 1; } int main(){ int K; scanf("%d", &K); char str[100]; for(int tc = 0; tc < K; tc++){ scanf("%s", str); if(get_result(str) == 1){ printf("YES\n"); } else{ printf("NO\n"); } top = -1; } return 0; }
true
01aa9353678ace26217867c210e5e7a37d64c3a9
C++
Razdeep/LeetCode-Solutions
/Dynamic Programming/Target_sum.cpp
UTF-8
514
3.03125
3
[ "MIT" ]
permissive
// https://leetcode.com/problems/target-sum/ class Solution { public: int solve(vector<int>& nums, int idx, int remaining) { if (idx == nums.size()) { return remaining == 0; } int solution_a = solve(nums, idx + 1, remaining + nums[idx]); int solution_b = solve(nums, idx + 1, remaining - nums[idx]); return solution_a + solution_b; } int findTargetSumWays(vector<int>& nums, int target) { return solve(nums, 0, target); } };
true
3e2aabd581c57336ca9bdc9c72aba383904e39bb
C++
innovationlabgreenwich/SmartHomeKit
/smarthome_lesson6B.ino
UTF-8
6,295
2.78125
3
[]
no_license
/* OSOYOO Smarthome example: Remote Control Servo A simple web server that lets you control a servor via a web page. This sketch will print the IP address of your ESP8266 module (once connected) to the Serial monitor. From there, you can open that address in a web browser to control the servo on pin D9, when the servo turn to 180 degree,the green led on D4 will be lit. For more details see: http://osoyoo.com/?p=28938 */ #include "WiFiEsp.h" #include "WiFiEspUdp.h" WiFiEspUDP Udp; unsigned int localPort = 8888; // local port to listen on #include "Keypad.h" char packetBuffer[5]; const byte ROWS = 4; //four rows const byte COLS = 4; //four columns //define the cymbols on the buttons of the keypads char hexaKeys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {33, 35, 37,39}; //connect to the row pinouts of the keypad byte colPins[COLS] = {41, 43, 45, 47}; //connect to the column pinouts of the keypad //initialize an instance of class NewKeypad Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS); #include <Servo.h> Servo myservo;//create servo object to control a servo #define greenled 12 //connect greenled to digital pin4 // Emulate softserial on pins A9/A8 if not present //#ifndef HAVE_HWSERIAL1 #include "SoftwareSerial.h" SoftwareSerial softserial(A9, A8); // RX, TX //#endif char ssid[] = "***"; // your network SSID (name) char pass[] = "***"; // your network password int status = WL_IDLE_STATUS; int ledStatus = LOW; WiFiEspServer server(80); // use a ring buffer to increase speed and reduce memory allocation RingBuffer buf(8); void setup() { // myservo.attach(3);//attachs the servo on pin D3 to servo object // myservo.write(0);//back to 0 degrees //delay(15);//wait for a second pinMode(greenled, OUTPUT); // initialize digital pin greenled as an output. pinMode(3, OUTPUT); Serial.begin(9600); // initialize serial for debugging // myservo.attach(3); // myservo.write(0);//servo goes to 90 degrees digitalWrite(3,LOW); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("start"); // set the data rate for the SoftwareSerial port softserial.begin(115200); softserial.println("AT+UART_DEF=9600,8,1,0,0"); softserial.write("AT+RST\r\n"); delay(100); softserial.begin(9600); WiFi.init(&softserial); // initialize ESP module // check for the presence of the shield if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue while (true); } // attempt to connect to WiFi network while (status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } Serial.println("You're connected to the network"); printWifiStatus(); // start the web server on port 80 Udp.begin(localPort); Serial.print(" target port "); Serial.println(localPort); } void loop() { char customKey = customKeypad.getKey(); if (customKey=='*'){ Serial.println(" Close THE DOOR!"); digitalWrite(greenled, LOW); // turn the led OFF myservo.attach(3); delay(300); myservo.write(0);//servo goes to 0 degrees delay(400); myservo.detach(); // save current of servo digitalWrite(3,LOW); } if (customKey=='#'){ Serial.println("Open THE DOOR!"); digitalWrite(greenled, HIGH); // turn the led on myservo.attach(3); delay(300); myservo.write(180);//servo goes to 180 degrees delay(400); myservo.detach(); // save current of servo digitalWrite(3,LOW); } if (customKey=='0'){ Serial.println("Half Close THE DOOR!"); digitalWrite(greenled, LOW); // turn the led off myservo.attach(3); delay(300); myservo.write(90);//servo goes to 90 degrees delay(400); myservo.detach(); // save current of servo digitalWrite(3,LOW); } int packetSize = Udp.parsePacket(); if (packetSize) { // if you get a client, Serial.print("Received packet of size "); Serial.println(packetSize); int len = Udp.read(packetBuffer, 255); if (len > 0) { packetBuffer[len] = 0; } char c=packetBuffer[0]; switch (c) //serial control instructions { case 'L': Serial.println("Close THE DOOR!"); digitalWrite(greenled, LOW); // turn the led off myservo.attach(3); delay(300); myservo.write(0);//servo goes to 180 degrees delay(400); myservo.detach(); // save current of servo digitalWrite(3,LOW); break; case 'A': Serial.println("Half Close THE DOOR!"); digitalWrite(greenled, LOW); // turn the led off myservo.attach(3); delay(300); myservo.write(90);//servo goes to 90 degrees delay(400); myservo.detach(); // save current of servo digitalWrite(3,LOW); break; case 'R': Serial.println("Open THE DOOR!"); ledStatus = HIGH; digitalWrite(greenled, HIGH); // turn the led on myservo.attach(3); delay(300); myservo.write(180);//servo goes to 180 degrees delay(400); myservo.detach(); // save current of servo digitalWrite(3,LOW); break; } //END OF ACTION SWITCH }//end of packetsize test } void printWifiStatus() { // print the SSID of the network you're attached to Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print where to go in the browser Serial.println(); Serial.print("please set your UDP APP target IP to: "); Serial.println(ip); Serial.println(); }
true
0f15e8e73ea82ce2b3777e8dec9b88454b423664
C++
fcvalise/AnOctonautOdyssey
/Decors/Rainbow.cpp
UTF-8
8,406
2.5625
3
[]
no_license
#include "Rainbow.hpp" #include "ABiome.hpp" #include "SkyCycle.hpp" #include <Interpolations.hpp> #include <Math.hpp> Rainbow::Rainbow(void) : Rainbow(nullptr) { } Rainbow::Rainbow(SkyCycle * cycle) : m_cos(0),//std::cos(90.f * octo::Deg2Rad); m_sin(1),//std::sin(90.f * octo::Deg2Rad); m_loopCountMax(10u), m_loopCount(0u), m_partCount(0u), m_thickness(50.f), m_stripeCount(7u), m_timer(sf::Time::Zero), m_intervalTimer(sf::Time::Zero), m_intervalTimerMax(sf::Time::Zero), m_grow(true), m_firstFrame(true), m_cycle(cycle) { } bool Rainbow::isDisabledIfOutOfScreen()const { return (false); } void Rainbow::createFirstLine(Line & line, std::size_t stripeCount, float thickness) { float delta = -thickness / stripeCount + 1; for (std::size_t i = 0; i < stripeCount + 1; i++) line[i] = sf::Vector2f(i * delta, 0.f); } void Rainbow::rotateLine(Line const & start, Line & end, std::size_t stripeCount, sf::Vector2f const & origin, float cos, float sin) { for (std::size_t i = 0; i < stripeCount + 1; i++) end[i] = rotateVecCopy(start[i], origin, cos, sin); } void Rainbow::createBicolorQuad(sf::Vector2f const & upLeft, sf::Vector2f const & upRight, sf::Vector2f const & downRight, sf::Vector2f const & downLeft, sf::Color const & colorUp, sf::Color const & colorDown, octo::VertexBuilder & builder) { builder.createVertex(upLeft, colorUp); builder.createVertex(upRight, colorUp); builder.createVertex(downRight, colorDown); builder.createVertex(upLeft, colorUp); builder.createVertex(downLeft, colorDown); builder.createVertex(downRight, colorDown); } void Rainbow::createPart(Line const & start, Line const & end, std::size_t stripeCount, sf::Vector2f const & origin, std::vector<sf::Color> colorsStart, std::vector<sf::Color> colorsEnd, float interpolateValue, octo::VertexBuilder& builder) { if (m_firstFrame == false) { for (std::size_t i = 0; i < stripeCount; i++) { if (m_grow) { colorsEnd[i].a *= interpolateValue; sf::Vector2f downLeft = start[i]; sf::Vector2f downRight = start[i + 1]; sf::Vector2f upLeft = octo::linearInterpolation(downLeft, end[i], interpolateValue); sf::Vector2f upRight = octo::linearInterpolation(downRight, end[i + 1], interpolateValue); createBicolorQuad(upRight + origin, upLeft + origin, downLeft + origin, downRight + origin, colorsEnd[i], colorsStart[i], builder); } else { colorsStart[i].a *= interpolateValue; sf::Vector2f upLeft = end[i]; sf::Vector2f upRight = end[i + 1]; sf::Vector2f downLeft = octo::linearInterpolation(upLeft, start[i], interpolateValue); sf::Vector2f downRight = octo::linearInterpolation(upRight, start[i + 1], interpolateValue); createBicolorQuad(upRight + origin, upLeft + origin, downLeft + origin, downRight + origin, colorsEnd[i], colorsStart[i], builder); } } } } void Rainbow::createRainbow(sf::Vector2f const & origin, std::vector<sf::Vector2f> const & sizes, std::size_t stripeCount, float thickness, std::vector<sf::Color> const & colors, std::vector<sf::Color> const & transparent, octo::VertexBuilder& builder) { sf::Vector2f originRotate; for (std::size_t i = 0; i < m_partCount - 1; i++) { if (i == 0) createFirstLine(m_start, stripeCount, thickness); else m_start = m_end; originRotate = m_start[0] + sizes[i]; rotateLine(m_start, m_end, stripeCount, originRotate, m_cos, m_sin); if (i == 0) createPart(m_start, m_end, stripeCount, origin, transparent, colors, m_interpolateValues[i], builder); else createPart(m_start, m_end, stripeCount, origin, colors, colors, m_interpolateValues[i], builder); } m_start = m_end; originRotate = m_start[0] + sf::Vector2f(0.f, -m_start[0].y); rotateLine(m_start, m_end, stripeCount, originRotate, m_cos, m_sin); createPart(m_start, m_end, stripeCount, origin, colors, transparent, m_interpolateValues[m_partCount - 1], builder); if (m_firstFrame == true) { m_endPosition = m_end[0]; m_firstFrame = false; } } void Rainbow::setupSizes(ABiome & biome, std::vector<sf::Vector2f> & sizes, std::size_t loopCount, std::size_t partCount, float thickness) { sizes[0] = sf::Vector2f(biome.getRainbowPartSize() * 4 + thickness, 0.f); for (size_t j = 0; j < loopCount; j++) { for (std::size_t i = 0; i < partCount; i++) { float partSize = biome.getRainbowPartSize(); if (i == 0) sizes[(j * 4) + i + 1] = sf::Vector2f(0.f, partSize * 2.f); if (i == 1) sizes[(j * 4) + i + 1] = sf::Vector2f(-partSize / 2.f, 0.f); if (i == 2) sizes[(j * 4) + i + 1] = sf::Vector2f(0.f, -partSize / 2.f); if (i == 3) sizes[(j * 4) + i + 1] = sf::Vector2f(partSize * 2.f, 0.f); } } sizes[partCount - 1] = sizes[0]; } void Rainbow::setupColors(std::vector<sf::Color> & colors, std::vector<sf::Color> & transparent) { colors[0] = sf::Color(255, 0, 0, 70); colors[1] = sf::Color(255, 127, 0, 70); colors[2] = sf::Color(255, 255, 0, 70); colors[3] = sf::Color(0, 255, 0, 70); colors[4] = sf::Color(0, 0, 255, 70); colors[5] = sf::Color(75, 0, 130, 70); colors[6] = sf::Color(143, 0, 255, 70); transparent[0] = sf::Color(255, 255, 255, 0); transparent[1] = sf::Color(255, 255, 255, 0); transparent[2] = sf::Color(255, 255, 255, 0); transparent[3] = sf::Color(255, 255, 255, 0); transparent[4] = sf::Color(255, 255, 255, 0); transparent[5] = sf::Color(255, 255, 255, 0); transparent[6] = sf::Color(255, 255, 255, 0); } void Rainbow::newRainbow(ABiome & biome) { m_firstFrame = true; m_grow = true; m_loopCount = biome.getRainbowLoopCount(); if (m_loopCount > m_loopCountMax) m_loopCount = m_loopCountMax; m_partCount = 2u + m_loopCount * 4u; m_thickness = biome.getRainbowThickness(); setupSizes(biome, m_sizes, m_loopCount, m_partCount, m_thickness); setupColors(m_colors, m_transparent); float totalFlatSizeX = 0.f; for (std::size_t i = 0; i < m_partCount; i++) totalFlatSizeX += fabs(m_sizes[i].x + m_sizes[i].y); float lifeTime = biome.getRainbowLifeTime().asSeconds(); for (std::size_t i = 0; i < m_partCount; i++) { m_timerMax[i] = sf::seconds(lifeTime * (fabs(m_sizes[i].x + m_sizes[i].y)) / totalFlatSizeX / 2.f); m_interpolateValues[i] = 0.f; } m_timer = sf::Time::Zero; m_intervalTimer = sf::Time::Zero; m_intervalTimerMax = biome.getRainbowIntervalTime() + sf::seconds(lifeTime); } void Rainbow::setup(ABiome& biome) { std::size_t partCountMax = 2u + m_loopCountMax * 4u; m_sizes.resize(partCountMax); m_timerMax.resize(partCountMax); m_interpolateValues.resize(partCountMax); m_start.resize(m_stripeCount + 1); m_end.resize(m_stripeCount + 1); m_colors.resize(m_stripeCount); m_transparent.resize(m_stripeCount); newRainbow(biome); m_intervalTimer = m_intervalTimerMax; } void Rainbow::computeInterpolateValuesGrow(sf::Time frameTime, std::vector<float> & values) { if (values[m_partCount - 1] == 1.f) { m_grow = false; return; } m_timer += frameTime; for (std::size_t i = 0; i < m_partCount; i++) { if (values[i] != 1.f) { values[i] = m_timer / m_timerMax[i]; if (m_timer >= m_timerMax[i]) { m_timer = sf::Time::Zero; values[i] = 1.f; } break; } } } void Rainbow::computeInterpolateValuesDie(sf::Time frameTime, std::vector<float> & values) { m_timer += frameTime; for (std::size_t i = 0; i < m_partCount; i++) { if (values[i] != 0.f) { values[i] = 1 - (m_timer / m_timerMax[i]); if (m_timer >= m_timerMax[i]) { m_timer = sf::Time::Zero; values[i] = 0.f; } break; } } } void Rainbow::update(sf::Time frameTime, octo::VertexBuilder& builder, ABiome& biome) { m_intervalTimer += frameTime; if (m_intervalTimer <= m_intervalTimerMax) { sf::Vector2f const & position = getPosition(); if (m_grow) computeInterpolateValuesGrow(frameTime, m_interpolateValues); else computeInterpolateValuesDie(frameTime, m_interpolateValues); // position - m_endPosition make the arrival be the origin createRainbow(position - m_endPosition, m_sizes, m_stripeCount, m_thickness, m_colors, m_transparent, builder); } else if (m_cycle && m_cycle->getWeatherValue() != 0.f && m_cycle->isDay()) newRainbow(biome); } sf::Vector2f Rainbow::rotateVecCopy(sf::Vector2f const & vector, sf::Vector2f const & origin, float const cosAngle, float const sinAngle) { sf::Vector2f result = vector; result -= origin; octo::rotateVector(result, cosAngle, sinAngle); result += origin; return result; }
true
70a115c12373fd6412d5b74fef59c4346c0e1e06
C++
anothermist/LIBRARIES
/MySensors/drivers/NVM/Flash.h
UTF-8
5,676
2.8125
3
[]
no_license
/* * Flash.h - Flash library * Original Copyright (c) 2017 Frank Holtz. All right reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file Flash.h * @brief Flash abstraction layer * * @ingroup NVM * @details Nonvolatile Memory Class * @{ */ #pragma once #include <Arduino.h> #include <stdio.h> // for size_t /* * Define characteristics of Flash * * @def FLASH_ERASE_CYCLES * @brief Specified number of erase cycles * * @def FLASH_PAGE_SIZE * @brief Used/supported Flash page size * * @def FLASH_ERASE_PAGE_TIME * @brief Time in ms to delete a page * * @def FLASH_WRITES_PER_WORD * @brief How often a dataword (32 bit) can be written * * @def FLASH_WRITES_PER_PAGE * @brief How many writes are allowed into a page * * @def FLASH_SUPPORTS_RANDOM_WRITE * @brief Set this if it is allowed to write to a page in random order. */ #if defined(NRF51) #define FLASH_ERASE_CYCLES 20000 #define FLASH_PAGE_SIZE 1024 #define FLASH_ERASE_PAGE_TIME 23 #define FLASH_SUPPORTS_RANDOM_WRITE true #define FLASH_WRITES_PER_WORD 2 #define FLASH_WRITES_PER_PAGE 512 #elif defined(NRF52) #define FLASH_ERASE_CYCLES 10000 #define FLASH_PAGE_SIZE 4096 #define FLASH_ERASE_PAGE_TIME 90 #define FLASH_SUPPORTS_RANDOM_WRITE true #define FLASH_WRITES_PER_WORD 32 #define FLASH_WRITES_PER_PAGE 181 #elif defined(NRF52840) #define FLASH_ERASE_CYCLES 10000 #define FLASH_PAGE_SIZE 4096 #define FLASH_ERASE_PAGE_TIME 90 #define FLASH_SUPPORTS_RANDOM_WRITE true #define FLASH_WRITES_PER_WORD 2 #define FLASH_WRITES_PER_PAGE 403 #else #define FLASH_ERASE_CYCLES 10000 #define FLASH_PAGE_SIZE 4096 #define FLASH_ERASE_PAGE_TIME 100 //#define FLASH_SUPPORTS_RANDOM_WRITE true #define FLASH_WRITES_PER_WORD 1 #warning "Unknown platform. Please check the code." #endif /** * @class FlashClass * @brief This class provides low-level access to internal Flash memory. */ class FlashClass { public: //---------------------------------------------------------------------------- /** Constructor */ FlashClass() {}; //---------------------------------------------------------------------------- /** Initialize Flash */ void begin() {}; /** Deinitialize Flash */ void end() {}; //---------------------------------------------------------------------------- /* * Physical flash geometry */ //---------------------------------------------------------------------------- /** Page size in bytes * @return Number of bytes */ uint32_t page_size() const; //---------------------------------------------------------------------------- /** Page address width in bits. Page size is 2^x * @return Number of bits */ uint8_t page_size_bits() const; //---------------------------------------------------------------------------- /** Number of managed flash pages * @return Number of pages */ uint32_t page_count() const; //---------------------------------------------------------------------------- /** Number of page erase cycles * @return Number of page erase cycles */ uint32_t specified_erase_cycles() const; //---------------------------------------------------------------------------- /** Get a address of a page * @param[in] page Page number, starting at 0 * @return address of given page */ uint32_t *page_address(size_t page); /** Get top of available flash for application data * @return Last available address + 1 */ uint32_t *top_app_page_address(); //---------------------------------------------------------------------------- /* * Accessing flash memory */ //---------------------------------------------------------------------------- /** Erase a page of given size. Size must be page_size aligned! * Take care about RADIO, WDT and Interrupt timing! * @param[in] *address Pointer to page * @param[in] size number of page aligned bytes to erase */ void erase(uint32_t *address, size_t size); //---------------------------------------------------------------------------- /** Erase the complete MCU. This can brick your device! */ void erase_all(); //---------------------------------------------------------------------------- /** write a aligned 32 bit word to flash. * @param[in] *address 32 bit aligned pointer to destination word * @param[in] value Data word to write */ void write(uint32_t *address, uint32_t value); //---------------------------------------------------------------------------- /** write a aligned block to flash. * @param[in] *dst_address 32 bit aligned pointer to destination * @param[in] *src_address 32 bit aligned pointer to source * @param[in] word_count Number of words to write */ void write_block(uint32_t *dst_address, uint32_t *src_address, uint16_t word_count); private: // Wait until flash is ready void wait_for_ready(); }; extern FlashClass Flash; /** Load Hardwarespecific files */ #ifdef NRF5 #include "hal/architecture/NRF5/drivers/Flash.cpp" #else #error "Unsupported platform." #endif /** @} */
true
40b7e31d543948e9e7f340ab098cc1ad88d8cfd5
C++
aGzDelusion/Cplusplus-Object-Oriented
/QuiambaoA3/src/Payroll.cpp
UTF-8
1,298
3.515625
4
[]
no_license
/* * Payroll.cpp * * Created on: Oct 1, 2019 * Author: Darwish Quiambao */ //Implementation file for member variables and methods of class Payroll. #include "Payroll.h" #include <iostream> Payroll::Payroll() //default constructor. { regularPay = 0.0; overtimePay = 0.0; workHours = 0.0; hourlyRate = 0.0; } Payroll::~Payroll(){} //C++ implicit destructor ///Getter functions float Payroll::getHours() //returns workHours from public members { return workHours; } float Payroll::getOvertimePay() //returns overtime pay private variable { return overtimePay; } float Payroll::getRate() // { return hourlyRate; } float Payroll::getRegPay() //returns regular pay private variable { return regularPay; } ///Setter functions void Payroll::setHours(const float &hours) { workHours = hours; //assigns the passed hours into workhours variable } void Payroll::setRate(const float &rate) { hourlyRate = rate; } void Payroll::computeWork() //Calculates pay for employee { float overtimeHour = 0.0; const float OVERTIME_HOUR = 40.0, OVERTIME_PAYRATE = 1.5; //Used to subtract from regular work hours if(workHours > OVERTIME_HOUR) overtimeHour = workHours - OVERTIME_HOUR; overtimePay = overtimeHour * hourlyRate * OVERTIME_PAYRATE; regularPay = workHours * hourlyRate; }
true
5ab6f3bf52bbed289372387b825c2282096dce27
C++
GuiM0x/Classics
/Pong/main.cpp
UTF-8
17,431
2.671875
3
[]
no_license
#include <iostream> #include <cmath> #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include <SFML/Audio.hpp> #include "include/Outils.h" ////////////////////////////////////////////// /////// RESET KEY STATE void reset_key_state(std::vector<bool>& v){ for(auto&& x : v) x = false; } enum keys{P1_UP, P1_DOWN, P2_UP, P2_DOWN, KEY_MAX}; std::vector<bool> key(KEY_MAX, false); ////////////////////////////////////////////// /////// CONST const unsigned WINDOW_W = 1024; const unsigned WINDOW_H = 576; const float PADDLE_W = 16; const float PADDLE_H = 128; const float PLAYER1_X = 10; const float PLAYER2_X = WINDOW_W - PADDLE_W - 10; const float PLAYER_Y = (WINDOW_H / 2) - (PADDLE_H / 2); const float BALL_RADIUS = 16; const float BALL_X = (WINDOW_W / 2) - BALL_RADIUS; const float BALL_Y = (WINDOW_H / 2) - BALL_RADIUS; ////////////////////////////////////////////// /////// CLASS LEADERBOARD class Leaderboard : public sf::Drawable { public: explicit Leaderboard(unsigned characterSize = 30) : m_playersScore{std::map<std::string, sf::Text>({{"player1", sf::Text()}, {"player2", sf::Text()}})}, m_font(sf::Font()), m_box1(sf::RectangleShape()), m_box2(sf::RectangleShape()) { m_font.loadFromFile("assets/fonts/OldLondon.ttf"); for(auto it = m_playersScore.begin(); it != m_playersScore.end(); ++it) { it->second.setFont(m_font); it->second.setString("0"); it->second.setCharacterSize(characterSize); it->second.setFillColor(sf::Color::White); } m_playersScore["player1"].setPosition(WINDOW_W/2.f - m_playersScore["player1"].getGlobalBounds().width, 0.f); m_playersScore["player2"].setPosition(WINDOW_W/2.f, 0.f); // Offset relative to middle m_playersScore["player1"].move(-30.f, 0.f); m_playersScore["player2"].move(30.f, 0.f); m_box1 = createBox(m_playersScore["player1"].getGlobalBounds().left, m_playersScore["player1"].getGlobalBounds().top, m_playersScore["player1"].getGlobalBounds().width, m_playersScore["player1"].getGlobalBounds().height); m_box2 = createBox(m_playersScore["player2"].getGlobalBounds().left, m_playersScore["player1"].getGlobalBounds().top, m_playersScore["player2"].getGlobalBounds().width, m_playersScore["player2"].getGlobalBounds().height); } void addPoint(const std::string& player) { std::string tmp{m_playersScore[player].getString()}; int score{std::stoi(tmp)}; ++score; m_playersScore[player].setString(std::to_string(score)); if(player == "player1") updatePosLeftScore(); /// DEBUG updateBox(); } private: // <player , score > std::map<std::string, sf::Text> m_playersScore; sf::Font m_font; sf::RectangleShape m_box1; /// DEBUG sf::RectangleShape m_box2; /// DEBUG sf::RectangleShape createBox(float x, float y, float w, float h) { sf::RectangleShape tmp{sf::Vector2f(w, h)}; tmp.setPosition(x, y); tmp.setFillColor(sf::Color::Transparent); tmp.setOutlineThickness(1); tmp.setOutlineColor(sf::Color::Red); return tmp; } void updatePosLeftScore() { float width{m_playersScore["player1"].getGlobalBounds().width}; m_playersScore["player1"].setPosition((WINDOW_W/2.f) - width, 0.f); m_playersScore["player1"].move(-30.f, 0.f); } void updateBox() { m_box1.setPosition(m_playersScore["player1"].getGlobalBounds().left, m_playersScore["player1"].getGlobalBounds().top); m_box2.setPosition(m_playersScore["player2"].getGlobalBounds().left, m_playersScore["player2"].getGlobalBounds().top); m_box1.setSize(sf::Vector2f(m_playersScore["player1"].getGlobalBounds().width, m_playersScore["player1"].getGlobalBounds().height)); m_box2.setSize(sf::Vector2f(m_playersScore["player2"].getGlobalBounds().width, m_playersScore["player2"].getGlobalBounds().height)); } void draw(sf::RenderTarget& target, sf::RenderStates states) const { //target.draw(m_box1); //target.draw(m_box2); for(auto it = m_playersScore.begin(); it != m_playersScore.end(); ++it) { target.draw(it->second); } } }; ////////////////////////////////////////////// /////// CLASS BARRE enum dir{ UP = -1, DOWN = 1 }; class Paddle : public sf::RectangleShape { public: Paddle(float width, float height) : RectangleShape(sf::Vector2f(width, height)), m_texture(sf::Texture()) { m_texture.loadFromFile("assets/img/paddle.png"); m_texture.setSmooth(true); setTexture(&m_texture); } float top() const { return getGlobalBounds().top; } float bottom() const { return (getGlobalBounds().top + getGlobalBounds().height); } float left() const { return getGlobalBounds().left; } float right() const { return (getGlobalBounds().left + getGlobalBounds().width); } void update(const sf::Time& dt, int direction) { setPosition(getPosition().x, (getPosition().y + (m_speed * dt.asSeconds() * direction))); } private: sf::Texture m_texture; float m_speed = 250.f; }; ////////////////////////////////////////////// /////// CLASS BALL class Ball : public sf::CircleShape { public: explicit Ball(float radius = 0, std::size_t pointCount = 30) : CircleShape(radius, pointCount), m_box(sf::RectangleShape(sf::Vector2f(radius*2, radius*2))), m_texture(sf::Texture()), m_texture_cracked(sf::Texture()), m_bufferSoundCrack(sf::SoundBuffer()) { // Textures m_texture.loadFromFile("assets/img/ball.png"); m_texture.setSmooth(true); setTexture(&m_texture); m_texture_cracked.loadFromFile("assets/img/ball_cracked.png"); m_texture_cracked.setSmooth(true); // Sounds m_bufferSoundCrack.loadFromFile("assets/sounds/sound_crack.wav"); m_soundCrack.setBuffer(m_bufferSoundCrack); m_bufferSoundBounce.loadFromFile("assets/sounds/sound_bounce.wav"); m_soundBounce.setBuffer(m_bufferSoundBounce); // Origin point (for perfect rotation in middle of texture) setOrigin(radius, radius); /// View Collide box (draw not necessary, but box's datas are used in collide sys) m_box.setFillColor(sf::Color::Transparent); m_box.setOutlineThickness(1); m_box.setOutlineColor(sf::Color::Red); startRotation(); } float top() const { return getPosition().y; } float bottom() const { return (getPosition().y + getGlobalBounds().height); } float left() const { return getPosition().x; } float right() const { return (getGlobalBounds().left + getGlobalBounds().width); } float getSpeed() const { return m_speed; } /// DEBUG float limitLeft() const { return m_limitLeft; } float limitRight() const { return m_limitRight; } bool isOut() const { return m_isOut; } sf::FloatRect getFloatRect() { return m_box.getGlobalBounds(); } const sf::RectangleShape& getBox() { return m_box; } void setLimit(float left, float right) { m_limitLeft = left; m_limitRight = right; } void setOut(bool isOut) { m_isOut = isOut; } void playCrackSound() { m_soundCrack.play(); } void playBounceSound() { m_soundBounce.play(); } void bounceH() { setRotation(360 - getRotation()); } //void bounceV() { setRotation(90 - (getRotation() - 90)); } void update(const sf::Time& dt) { if(!m_isOut) { float radA = getRotation() * ((2.f * PI) / 360.f); float x = left() + (cos(radA) * m_speed * dt.asSeconds()); float y = top() + (sin(radA) * m_speed * dt.asSeconds()); setPosition(x, y); m_box.setPosition(x - getRadius(), y - getRadius()); } else { playAnimOut(dt); } } void speedUp() { m_speed += 30.f; if(m_speed < 0) m_speed = 0.f; } /// DEBUG void slowDown() { m_speed -= 30.f; if(m_speed < 0) m_speed = 0.f; } private: sf::RectangleShape m_box; sf::Texture m_texture; sf::Texture m_texture_cracked; sf::SoundBuffer m_bufferSoundCrack; sf::Sound m_soundCrack; sf::SoundBuffer m_bufferSoundBounce; sf::Sound m_soundBounce; const float PI = 3.141592f; float m_defaultSpeed = 300.f; float m_speed = 300.f; float m_limitLeft = 0.f; float m_limitRight = 0.f; float m_elapsed = 0.f; bool m_isOut = false; void reset() { setPosition(WINDOW_W/2.f, WINDOW_H/2.f); m_box.setPosition((WINDOW_W/2.f) - getRadius(), (WINDOW_H/2.f) - getRadius()); startRotation(); m_speed = m_defaultSpeed; m_isOut = false; } void startRotation() { float angle{static_cast<float>(Outils::rollTheDice(0, 359))}; if((angle > 225.f && angle < 315.f) || (angle > 45.f && angle < 135.f)) { angle -= 90.f; } setRotation(angle); } void playAnimOut(const sf::Time& dt) { m_elapsed += dt.asSeconds(); if(m_elapsed < 2.f) { setTexture(&m_texture_cracked); } else { setTexture(&m_texture); reset(); m_elapsed = 0.f; } } }; /// DEBUG std::ostream& operator<<(std::ostream& os, const Ball& b) { os << "Rotation : " << b.getRotation() << " deg(s)" << '\n' << "Speed : " << b.getSpeed() << '\n' << "-------------------------"; return os; } ////////////////////////////////////////////// /////// GET ANGLE REFLEXION float getAngleReflexion(Ball& b, const Paddle& p) { const float angleMax{45.f}; const float halfBarre{p.getGlobalBounds().height / 2.f}; const float degPerPxl{angleMax / halfBarre}; const float ballCenter{b.getPosition().y}; const float barreCenter{p.getPosition().y + halfBarre}; float angle{0.f}; if(ballCenter < barreCenter) { return ((barreCenter - ballCenter) * degPerPxl); } else if(ballCenter > barreCenter) { return ((ballCenter - barreCenter) * degPerPxl); } else { return angle; } } ////////////////////////////////////////////// /////// COLLIDE WINDOW bool collideWindow(Ball& b, sf::RenderTarget *window) { // Top if(b.top() <= b.getRadius()) { b.setPosition(b.left(), b.getRadius()); b.bounceH(); return true; } // Bottom if(b.top() >= (window->getSize().y - b.getRadius())) { b.setPosition(b.left(), window->getSize().y - b.getRadius()); b.bounceH(); return true; } //Left - Right if(b.left() <= b.getRadius() || b.left() >= window->getSize().x - b.getRadius()) { if(!b.isOut()) b.playCrackSound(); b.setOut(true); return true; } return false; } ////////////////////////////////////////////// /////// COLLIDE PADDLE void collidePaddle(Ball& b, const Paddle& p1, const Paddle& p2) { const sf::FloatRect player1(p1.getGlobalBounds()); const sf::FloatRect player2(p2.getGlobalBounds()); const float halfBarre{p1.getGlobalBounds().height / 2.f}; const float ballCenter{b.getPosition().y}; const float p1Center{p1.top() + halfBarre}; const float p2Center{p2.top() + halfBarre}; // If Ball is inside player 1 if(player1.intersects(b.getFloatRect())) { b.playBounceSound(); if(ballCenter < p1Center) { b.setRotation(360.f - getAngleReflexion(b, p1)); } else if(ballCenter > p1Center) { b.setRotation(getAngleReflexion(b, p1)); } else { b.setRotation(0.f); } } // If Ball is inside player 2 if(player2.intersects(b.getFloatRect())) { b.playBounceSound(); if(ballCenter < p2Center) { b.setRotation(180.f + getAngleReflexion(b, p2)); } else if(ballCenter > p2Center) { b.setRotation(180.f - getAngleReflexion(b, p2)); } else { b.setRotation(0.f); } } } ////////////////////////////////////////////// int main() { sf::RenderWindow window(sf::VideoMode(WINDOW_W, WINDOW_H), "Pong", sf::Style::Close); // BALL Ball myBall(BALL_RADIUS, 32); myBall.setPosition(BALL_X, BALL_Y); myBall.setLimit(PLAYER1_X + PADDLE_W, PLAYER2_X); // PLAYER 1 Paddle player1(PADDLE_W, PADDLE_H); player1.setPosition(PLAYER1_X, PLAYER_Y); // PLAYER 2 Paddle player2(PADDLE_W, PADDLE_H); player2.setPosition(PLAYER2_X, PLAYER_Y); // LEADERBOARD Leaderboard leaderboard(75); // DOT LINE std::vector<sf::RectangleShape> middleDotLine(9, sf::RectangleShape{sf::Vector2f(10.f, WINDOW_H / 18.f)}); for(std::size_t i = 0; i < middleDotLine.size(); ++i) { middleDotLine[i].setPosition((WINDOW_W / 2.f) - 2.f, (i*(WINDOW_H / 9.f)) + WINDOW_H / 36.f); } /////// CLOCK/DT sf::Clock clock; sf::Time dt; float timer{0.f}; /////// GAME LOOP while (window.isOpen()) { dt = clock.restart(); timer += dt.asSeconds(); /////// EVENTS sf::Event event; while (window.pollEvent(event)) { /////// KEY PRESSED if(event.type == sf::Event::KeyPressed) { //Directions if (event.key.code == sf::Keyboard::Z) { key[P1_UP] = true; } if (event.key.code == sf::Keyboard::S) { key[P1_DOWN] = true; } if (event.key.code == sf::Keyboard::O) { key[P2_UP] = true; } if (event.key.code == sf::Keyboard::L) { key[P2_DOWN] = true; } /// DEBUG if (event.key.code == sf::Keyboard::D) { std::cout << myBall << '\n'; } if(event.key.code == sf::Keyboard::Escape) window.close(); } /////// KEY RELEASED if (event.type == sf::Event::KeyReleased) { //Directions if (event.key.code == sf::Keyboard::Z) { key[P1_UP] = false; } if (event.key.code == sf::Keyboard::S) { key[P1_DOWN] = false; } if (event.key.code == sf::Keyboard::O) { key[P2_UP] = false; } if (event.key.code == sf::Keyboard::L) { key[P2_DOWN] = false; } } /////// MOUSE PRESSED if(event.type == sf::Event::MouseButtonPressed) { if(event.mouseButton.button == sf::Mouse::Left) { myBall.setRotation(myBall.getRotation() - 10); } if(event.mouseButton.button == sf::Mouse::Right) { myBall.setRotation(myBall.getRotation() + 10); } } /////// MOUSE WHEEL if(event.type == sf::Event::MouseWheelScrolled) { if(event.mouseWheelScroll.delta > 0) { myBall.speedUp(); } if(event.mouseWheelScroll.delta < 0) { myBall.slowDown(); } } /////// CLOSE WINDOW if (event.type == sf::Event::Closed) window.close(); } /////// UPDATE if(!myBall.isOut()) { // Collide Window if(collideWindow(myBall, &window)) { if(myBall.left() <= myBall.getRadius()) leaderboard.addPoint("player2"); else if(myBall.right() >= WINDOW_W) leaderboard.addPoint("player1"); } // Collide Paddle collidePaddle(myBall, player1, player2); // Speed Ball if(timer > 3.f) { myBall.speedUp(); timer = 0.f; } } else { timer = 0.f; } // Players if(key[P1_UP]) { player1.update(dt, dir::UP); } if(key[P2_UP]) { player2.update(dt, dir::UP); } if(key[P1_DOWN]) { player1.update(dt, dir::DOWN); } if(key[P2_DOWN]) { player2.update(dt, dir::DOWN); } // Ball myBall.update(dt); /////// DRAW window.clear(); for(const auto& x: middleDotLine) window.draw(x); window.draw(player1); window.draw(player2); window.draw(myBall); //window.draw(myBall.getBox()); /// DEBUG window.draw(leaderboard); window.display(); } return 0; }
true
abe197b7ff50343b62123563bea00ab8970db5da
C++
nilmadhab/code
/november/lunch_time/shuffling.cpp
UTF-8
1,672
2.78125
3
[]
no_license
#include <iostream> using namespace std; #define endl "\n" //INT_MIN #include<bits/stdc++.h> #define ll long long vector<int> vec(100005); #define endl "\n" ll max(ll a, ll b){ if(a > b) return a; return b; } void print(vector<int> v, int N){ for (int i = 0; i < N; ++i) { cout << v[i] << " "; } cout << "\n" ; } void print(vector<int> v){ for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; } cout << "\n" ; } int MAX = 1000000001; int process(int S, int x, int y) { vector<int> even(S/2); vector<int> odd(S/2); for (int i = 0; i < S; ++i) { if(i%2 == 0){ odd[i/2] = vec[i]; }else{ even[i/2] = vec[i]; } } int index = (S/2)*x/y; int j=0; for (int i = 0; i < S/2 ; ++i) { if(i != index){ vec[j++] = odd[i]; } } for (int i = 0; i < S/2 ; ++i) { if(i != index){ vec[j++] = even[i]; } } //print(even); //print(odd); //print(vec, S - 2); return S - 2; } void compute(int M, int X, int Y) { for (int i = 0; i < M; ++i) { vec[i] = i+1; } int S = M; do{ S = process(S, X, Y); }while(S > 2); int ans = vec[0] ^ vec[1]; cout << ans << endl; } int main() { //std::ios::sync_with_stdio(false); ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >>T; for (int t = 0; t < T; ++t) { int M, X, Y; cin >> M >> X >> Y; compute(M, X, Y); } // //print(mat); ////////////// compute return 0; }
true
331e2f214ffe252d0eae0e0d770e8a6fc5e35461
C++
tbor8080/rannc
/src/comm/ObjectComm.cpp
UTF-8
2,106
2.578125
3
[ "MIT" ]
permissive
// // Created by Masahiro Tanaka on 2019/09/20. // #include "ObjectComm.h" namespace rannc { inline size_t max(const std::vector<size_t>& nums) { size_t max_val = 0; for (size_t n: nums) { if (max_val < n) { max_val = n; } } return max_val; } std::vector<std::vector<char>> ObjectComm::doAllgather(const std::vector<char>& data, MPI_Comm comm) { // get sizes size_t size = data.size(); int comm_size = mpi::getSize(comm); auto all_sizes_buf = std::unique_ptr<size_t>(new size_t[comm_size]); mpi::checkMPIResult(MPI_Allgather(&size, 1, MPI_LONG, all_sizes_buf.get(), 1, MPI_LONG, comm)); std::vector<size_t> all_sizes; all_sizes.reserve(comm_size); for (int i=0; i<comm_size; i++) { all_sizes.push_back(*(all_sizes_buf.get() + i)); } size_t max_size = max(all_sizes); auto sendbuf = std::unique_ptr<char>(new char[max_size]); memcpy(sendbuf.get(), &data[0], data.size()); auto recvbuf = std::unique_ptr<char>(new char[max_size * comm_size]); mpi::checkMPIResult(MPI_Allgather( sendbuf.get(), max_size, MPI_CHAR, recvbuf.get(), max_size, MPI_CHAR, comm)); std::vector<std::vector<char>> results; for (int i=0; i<comm_size; i++) { size_t a_size = all_sizes.at(i); std::vector<char> buf(a_size); memcpy(&buf[0], recvbuf.get() + max_size*i, a_size); results.push_back(std::move(buf)); } return results; } std::vector<char> ObjectComm::doBcast(const std::vector<char>& data, int root, MPI_Comm comm) { size_t size = data.size(); mpi::checkMPIResult(MPI_Bcast((void*) &size, 1, MPI_LONG, root, comm)); std::vector<char> buf(size); if (mpi::getRank(comm) == root) { memcpy(&buf[0], &data[0], size); } mpi::checkMPIResult(MPI_Bcast((void*) &buf[0], size, MPI_CHAR, root, comm)); return buf; } }
true
78280b1d0a55342d300c37ee42c4bef1a68d611a
C++
rajatgirotra/study
/cpp/templates/23_DotTemplate2.cpp
UTF-8
287
2.9375
3
[]
no_license
#include <iostream> #include <string> #include <cstddef> #include <bitset> using namespace std; int main() { bitset<10> bs; bs.set(5); cout<<"bs = "<<bs<<endl; string s = bs.to_string<char, char_traits<char>, allocator<char> > (); cout<<"s = "<<s<<endl; return 0; }
true
79aa3b8c17ec167c4bca66c1dbab728535b08686
C++
martinsele/ros
/tech_task/include/Navigator.h
UTF-8
5,201
2.53125
3
[]
no_license
#ifndef TECH_TASK_NAVIGATOR_H #define TECH_TASK_NAVIGATOR_H #include <ros/ros.h> #include <geometry_msgs/Pose.h> #include <nav_msgs/OccupancyGrid.h> #include <unordered_set> #include "TaskReachedCallback.h" #include "Controller.h" #include "Map.h" #include "GraphLocation.h" #include "SearchGraph.h" #include "unordered_map" #include <queue> #include <unordered_map> enum NavState{ AVOIDING, // avoiding neighbors NAVIGATING, // checking execution WAITING_FOR_DATA // waiting for next missionWPT or plan to be created }; const double DEFAULT_ROBOT_RADIUS_M = 0.4; /** * Handle path planning around obstacles and avoidance of higher priority members */ class Navigator : public TaskReachedCallback { public: Navigator(ros::NodeHandle &nh, const std::string &nameSpace, const std::string positionSubscribeTopic, std::shared_ptr<TaskReachedCallback> owner); void addController(std::shared_ptr<Controller> controller); void setMap(std::shared_ptr<Map> &map); /** Set actual mission waypoint*/ void planPathTo(Position & missionWpt); /** * Update position of a neighbor * @param nbrName * @param pose */ void updateNbrPosition(std::string nbrName, const Position &pose); /** * Update current waypoint of a neighbor * @param nbrName * @param wpt */ void updateNbrWpts(std::string nbrName, const Position &wpt); /** * Return current mission waypoint * @param currentMissionWpt */ void getCurrentWaypoint(Position &currentMissionWpt); /** * Upload 1 wpt at a time to controller and inform owner when finished */ void taskReached(); /** * Inform robot about finished neighbor, avoid its position from now on * @param finishedRobot * @param robotsFinalPose */ void neighborFinished(const std::string finishedRobot, const Position robotsFinalPose); double getRobotRadius(); private: ros::NodeHandle nodeH; std::string nameSpace; geometry_msgs::Pose ownPose; Position currentMissionWpt; /** subscribe own state and map */ ros::Subscriber subRobotState, mapSubscriber; NavState state; bool currWptSet = false; bool ownPoseSet = false; bool mapSet = false; /** remaining waypoints to visit */ std::vector<GraphLocation> wptPath; std::deque<GraphLocation> wptQueue; /** radius of a robot for collision handling */ double robotRadius; //----- MUTEXES -------// boost::shared_mutex mutex_pos_; boost::shared_mutex mutex_plans_; //----- NEIGHBORS -------// // higher priority neighbors data std::unordered_set<std::string> nghbrNames; std::unordered_map<std::string, Position> neighborPoses; std::unordered_map<std::string, Position> neighborPlans; std::unordered_map<std::string, Position> finishedNeighbors; //----- COMPONENTS -------// std::shared_ptr<Controller> controller; std::shared_ptr<SearchGraph> graph; std::shared_ptr<Map> map; /** Mission planner (SweepingPlanner) */ std::shared_ptr<TaskReachedCallback> owner; //----- CALLBACK FUNCTIONS -------// /** save robot's own position */ void ownStateCallback(const geometry_msgs::PoseConstPtr &ownPose); /** Timer for checking state */ ros::Timer timerLoop; void checkStateLoop(const ros::TimerEvent &); void changeState(const NavState &newState); void plan(); void checkExecution(); /** * Plan A* trajectory * @param graph * @param start * @param goal * @param came_from * @param cost_so_far * @return */ bool aStarSearch (std::shared_ptr<SearchGraph> graph, GraphLocation start, GraphLocation &goal, std::unordered_map<GraphLocation, GraphLocation>& came_from, std::unordered_map<GraphLocation, double>& cost_so_far); /* * Heuristic function for A* */ double heuristic(GraphLocation location, GraphLocation goal); /** * Reconstruct path from map * @param start * @param goal * @param cameFrom * @param path */ void reconstructPath(GraphLocation start, GraphLocation goal, std::unordered_map<GraphLocation, GraphLocation> &cameFrom, std::deque<GraphLocation> &path); void printPath(std::deque<GraphLocation> vector); /** * Upload waypoint to controller * @param location */ void uploadWptToController(GraphLocation &location); /** * Find too near neighbors * @param currentPos * @param nearNbrs */ void checkNearNgbrs(const Position &currentPos, std::vector<std::string> &nearNbrs); void handleNearNgbrs(const Position curPos, const std::vector<std::string> &nearNgbrs); void checkAvoidance(); void returnToPlan(); void countAvoidancePushDirection(const Position curPosition, const std::vector<std::string> &nearNeighbors, const std::vector<Position> &nearObstacles, Position &push); double getPushAmplitude(double robotCoord, double obstacleCoord); }; #endif //TECH_TASK_NAVIGATOR_H
true
5bd014be62e9046733fb886dc214c6cf1f40e6d5
C++
aresgtr/Learn
/UdacitySelfDrivingCarEngineer/T2-Lesson6Project-CarND-Kidnapped-Vehicle-Project-master/src/particle_filter.cpp
UTF-8
10,169
2.96875
3
[ "MIT" ]
permissive
/** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include "particle_filter.h" #include <math.h> #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <string> #include <vector> #include "helper_functions.h" using std::string; using std::vector; void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * TODO: Set the number of particles. Initialize all particles to * first position (based on estimates of x, y, theta and their uncertainties * from GPS) and all weights to 1. * TODO: Add random Gaussian noise to each particle. * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ num_particles = 1000; // TODO: Set the number of particles particles = vector<Particle>(num_particles); std::default_random_engine gen; // Set standard deviations double std_x, std_y, std_theta; std_x = std[0]; std_y = std[1]; std_theta = std[2]; // Create normal distribution for x, y, and theta std::normal_distribution<double> dist_x(x, std_x); std::normal_distribution<double> dist_y(y, std_y); std::normal_distribution<double> dist_theta(theta, std_theta); for (int i = 0; i < num_particles; ++i) { Particle particle; // sample from these normal distribution particle.id = i; particle.x = dist_x(gen); particle.y = dist_y(gen); particle.theta = dist_theta(gen); particle.weight = 1; particles[i] = particle; } weights = vector<double >(num_particles, 1); } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { /** * TODO: Add measurements to each particle and add random Gaussian noise. * NOTE: When adding noise you may find std::normal_distribution * and std::default_random_engine useful. * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution * http://www.cplusplus.com/reference/random/default_random_engine/ */ // Set standard deviations double std_x, std_y, std_theta; std_x = std_pos[0]; std_y = std_pos[1]; std_theta = std_pos[2]; double new_x; double new_y; double new_theta; for (int i = 0; i < num_particles; ++i) { // if yaw_rate is 0 if (yaw_rate == 0) { new_x = particles[i].x + velocity * cos(particles[i].theta) * delta_t; new_y = particles[i].y + velocity * sin(particles[i].theta) * delta_t; new_theta = particles[i].theta; } // if yaw_rate is not 0 else { new_x = particles[i].x + (velocity/yaw_rate) * (sin(particles[i].theta + (yaw_rate * delta_t)) - sin(particles[i].theta)); new_y = particles[i].y + (velocity/yaw_rate) * (cos(particles[i].theta) - cos(particles[i].theta + (yaw_rate * delta_t))); new_theta = particles[i].theta + (yaw_rate * delta_t); } std::normal_distribution<double> dist_x(new_x, std_x); std::normal_distribution<double> dist_y(new_y, std_y); std::normal_distribution<double> dist_theta(new_theta, std_theta); std::default_random_engine gen; particles[i].x = dist_x(gen); particles[i].y = dist_y(gen); particles[i].theta = dist_theta(gen); } } void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations) { /** * TODO: Find the predicted measurement that is closest to each * observed measurement and assign the observed measurement to this * particular landmark. * NOTE: this method will NOT be called by the grading code. But you will * probably find it useful to implement this method and use it as a helper * during the updateWeights phase. */ for (int i = 0; i < observations.size(); ++i) { double min_distance = 99999.0; int match_id; for (int j = 0; j < predicted.size(); ++j) { double distance; distance = dist(observations[i].x, observations[i].y, predicted[j].x, predicted[j].y); if (distance < min_distance) { min_distance = distance; match_id = predicted[j].id; } } observations[i].id = match_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) { /** * TODO: Update the weights of each particle using a mult-variate Gaussian * distribution. You can read more about this distribution here: * https://en.wikipedia.org/wiki/Multivariate_normal_distribution * NOTE: The observations are given in the VEHICLE'S coordinate system. * Your particles are located according to the MAP'S coordinate system. * You will need to transform between the two systems. Keep in mind that * this transformation requires both rotation AND translation (but no scaling). * The following is a good resource for the theory: * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm * and the following is a good resource for the actual equation to implement * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html */ for (int i = 0; i < num_particles; ++i) { // transform observations from vehicle coordinate to global coordinate vector<LandmarkObs> global_observations; for (unsigned int j = 0; j < observations.size(); ++j) { LandmarkObs global_observation; global_observation.x = observations[j].x * cos(particles[i].theta) - observations[j].y * sin(particles[i].theta) + particles[i].x; global_observation.y = observations[j].x * sin(particles[i].theta) + observations[j].y * cos(particles[i].theta) + particles[i].y; global_observation.id = observations[j].id; global_observations.push_back(global_observation); } // see if the inputs are in the sensor range vector<LandmarkObs> in_range; for (unsigned int j = 0; j < map_landmarks.landmark_list.size(); j++) { double distance; distance = dist(particles[i].x, particles[i].y, map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f); if (distance <= sensor_range) { LandmarkObs in_range_landmark; in_range_landmark.x = map_landmarks.landmark_list[j].x_f; in_range_landmark.y = map_landmarks.landmark_list[j].y_f; in_range_landmark.id = map_landmarks.landmark_list[j].id_i; in_range.push_back(in_range_landmark); } } // associate global observations to predicted in-range landmarks dataAssociation(in_range, global_observations); // reset weight for (unsigned int j = 0; j < in_range.size(); j++) { double weight = 1; // find the nearest double min_distance = 99999.0; int match_id; for (int k = 0; k < global_observations.size(); k++) { double distance; distance = dist(in_range[j].x, in_range[j].y, global_observations[k].x, global_observations[k].y); if (distance < min_distance) { min_distance = distance; match_id = k; } } // weight *= bivariate_normal(in_range[j].x, in_range[j].y, global_observations[match_id].x, global_observations[match_id].y, std_landmark[0], std_landmark[1]); weight *= exp(-((in_range[j].x-global_observations[match_id].x)*(in_range[j].x-global_observations[match_id].x)/(2*std_landmark[0]*std_landmark[0]) + (in_range[j].y-global_observations[match_id].y)*(in_range[j].y-global_observations[match_id].y)/(2*std_landmark[1]*std_landmark[1]))) / (2.0*3.14159*std_landmark[0]*std_landmark[1]); weights.push_back(weight); particles[i].weight = weight; } } } void ParticleFilter::resample() { /** * TODO: Resample particles with replacement with probability proportional * to their weight. * NOTE: You may find std::discrete_distribution helpful here. * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution */ vector<Particle> resampled; std::default_random_engine gen; std::uniform_int_distribution<int> index(0, num_particles - 1); int current_index = index(gen); double b = 0; double max_weight = *max_element(weights.begin(), weights.end()); for (int i = 0; i < num_particles; i++) { std::uniform_real_distribution<double> random_weight(0.0, max_weight * 2); b = random_weight(gen); while (b > weights[current_index]) { b = b - weights[current_index]; current_index = (current_index + 1) % num_particles; } resampled.push_back(particles[current_index]); } particles = resampled; } void ParticleFilter::SetAssociations(Particle& particle, const vector<int>& associations, const vector<double>& sense_x, const vector<double>& sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(Particle best, string coord) { vector<double> v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
true
6004e03af8bb6c2765114788406184d5894f7446
C++
zhiyuhuo/DirectSLAM
/PlaneDetection/TextureSegment.cc
UTF-8
11,123
2.609375
3
[]
no_license
#include "TextureSegment.h" TextureSegment::TextureSegment(cv::Mat image, int gridX, int gridY) { InitData(image, gridX, gridY); } void TextureSegment::InitGaborFilters() { cv::Size ksize(3, 3); double pi_value = 3.14159265; std::vector<double> sigma = {1, 2, 3, 4, 5}; std::vector<double> theta = {pi_value * 0.125, pi_value * 0.25, pi_value * 0.375, pi_value * 0.50, pi_value * 0.625, pi_value * 0.75, pi_value * 0.875, pi_value * 1.0}; std::vector<double> lambd = {1}; std::vector<double> gamma = {0.02}; int count = 0; for (int s = 0; s < sigma.size(); s++) { for (int t = 0; t < theta.size(); t++) { for (int l = 0; l < lambd.size(); l++) { for (int g = 0; g < gamma.size(); g++) { cv::Mat kGabor = cv::getGaborKernel(ksize, sigma[s], theta[t], lambd[l], gamma[g], 0, CV_32F); mGaborFilters.push_back(cv::Mat()); kGabor.convertTo(kGabor, CV_32FC1); mGaborFilters[count++] = kGabor.clone(); } } } } // for (int i = 0; i < mGaborFilters.size(); i++) { // cv::imshow("filter", mGaborFilters[i]); // cv::waitKey(-1); // } } void TextureSegment::InitData(cv::Mat image, int gridX, int gridY) { mImage = image.clone(); mGridX = gridX; mGridY = gridY; mGridNumX = image.cols / mGridX; mGridNumY = image.rows / mGridY; mGridGaborFeatures.resize(mGridNumY); mTextureMap = cv::Mat(mGridNumY, mGridNumX, CV_32SC1); mGrayScaleMap = cv::Mat(mGridNumY, mGridNumX, CV_32FC1); for (int i = 0; i < mGridNumY; i++) { mGridGaborFeatures[i].resize(mGridNumX); for (int j = 0; j < mGridNumX; j++) { mTextureMap.at<int>(i, j) = i * mGridNumX + j; } } InitGaborFilters(); } void TextureSegment::ComputeGridFeatures() { // cv::imshow("mImage", mImage); // std::cout << mGridX << " " << mGridY << " " << mGridNumX << " " << mGridNumY << std::endl; // std::cout << mGridGaborFeatures.size() << " " << mGridGaborFeatures[0].size() << std::endl; for (int v = 0; v <= mImage.rows - mGridY; v+=mGridY) { for (int u = 0; u <= mImage.cols - mGridX; u+=mGridX) { // std::cout << v << " " << u << " " << v/mGridY << " " << u/mGridX << std::endl; cv::Mat patch = mImage(cv::Rect(u, v, mGridX, mGridY)); // cv::imshow("patch", patch); cv::Mat f = ComputeAGridFeature(patch); mGridGaborFeatures[v/mGridY][u/mGridX] = f.clone(); mGrayScaleMap.at<float>(v/mGridY, u/mGridX) = (cv::mean(patch)).val[0] * (1/255.); // cv::waitKey(-1); } } ConnectSimilarGrids(); } cv::Mat TextureSegment::ComputeAGridFeature(cv::Mat img) { cv::Mat res(mGaborFilters.size(), 1, CV_32FC1); float* pres = res.ptr<float>(0); cv::Mat input; img.convertTo(input, CV_32FC1); input *= (1/255.); int filterX = mGaborFilters[0].cols; int filterY = mGaborFilters[0].rows; int filterD = filterX * filterY; int count = 0; for (int v = 0; v < img.rows-filterY; v++) { for (int u = 0; u < img.cols-filterX; u++) { for (int i = 0; i < mGaborFilters.size(); i++) { cv::Mat win = input(cv::Rect(u, v, filterX, filterY)); float* pwin = win.ptr<float>(0); float* pfilter = mGaborFilters[i].ptr<float>(0); float response = 0.; for (int j = 0; j < filterD; j++) { response += pwin[j] * pfilter[j]; } pres[i] += response; } count ++; } } for (int i = 0; i < res.rows; i++) { pres[i] /= count; // std::cout << std::setprecision(3) << pres[i] << " "; } // std::cout << std::endl; // std::cout << res.t() << std::endl; return res; } cv::Mat TextureSegment::ConnectSimilarGrids() { float Threshold = 8.0; int IterMax = 30; bool ifConverge = false; // for (int y = 1; y < mGridNumY-1; y++) { // for (int x = 1; x < mGridNumX-1; x++) { // std::cout << x << ", " << y << " " // << cv::norm(mGridGaborFeatures[y][x], mGridGaborFeatures[y+1][x]) << " " // << cv::norm(mGridGaborFeatures[y][x], mGridGaborFeatures[y-1][x]) << " " // << cv::norm(mGridGaborFeatures[y][x], mGridGaborFeatures[y][x+1]) << " " // << cv::norm(mGridGaborFeatures[y][x], mGridGaborFeatures[y][x-1]) << std::endl; // } // } // generate 12 seeds aroung the center of the view std::vector<cv::Point2i> seeds = { cv::Point2i(mGridNumX/2-7, mGridNumY/2-5), cv::Point2i(mGridNumX/2-2, mGridNumY/2-5), cv::Point2i(mGridNumX/2+2, mGridNumY/2-5), cv::Point2i(mGridNumX/2+7, mGridNumY/2-5), cv::Point2i(mGridNumX/2-7, mGridNumY/2), cv::Point2i(mGridNumX/2-2, mGridNumY/2), cv::Point2i(mGridNumX/2+2, mGridNumY/2), cv::Point2i(mGridNumX/2+7, mGridNumY/2), cv::Point2i(mGridNumX/2-7, mGridNumY/2+5), cv::Point2i(mGridNumX/2-2, mGridNumY/2+5), cv::Point2i(mGridNumX/2+2, mGridNumY/2+5), cv::Point2i(mGridNumX/2+7, mGridNumY/2+5) }; cv::Mat checkMap = -cv::Mat::ones(mGridNumY, mGridNumX, CV_32SC1); int classID = 0; std::vector<int> classIDSeeds(seeds.size(), -1); classIDSeeds[0] = 0; for (int i = 1; i < seeds.size(); i++) { for (int j = 0; j < i; j++) { float distGabor = cv::norm(mGridGaborFeatures[seeds[j].y][seeds[j].x], mGridGaborFeatures[seeds[i].y][seeds[i].x]); float distColor = fabs(mGrayScaleMap.at<float>(seeds[j].y,seeds[j].x) - mGrayScaleMap.at<float>(seeds[i].y,seeds[i].x)); std::cout << i << " " << j << ": " << distGabor << " " << distColor << std::endl; if ( distGabor < Threshold && distColor < 0.1 ) { classIDSeeds[i] = classIDSeeds[j]; } } if (classIDSeeds[i] < 0) { classIDSeeds[i] = ++classID; } } mTextureID = classID; for (int i = 0; i < classIDSeeds.size(); i++) { // std::cout << classIDSeeds[i] << " "; checkMap.at<int>(seeds[i].y, seeds[i].x) = classIDSeeds[i]; } // std::cout << std::endl; // std::cout << checkMap << std::endl; int dx[4] = {-1, 1, 0, 0}; int dy[4] = { 0, 0, -1, 1}; int Iter = 0; for (; Iter < 30; Iter++) { bool ifChange = false; for (int y = 1; y < mGridNumY-1; y++) { for (int x = 1; x < mGridNumX-1; x++) { if (checkMap.at<int>(y,x) < 0) { float minValue = 999999.; int minIndex = -1; for (int i = 0; i < 4; i++) { if (checkMap.at<int>(y+dy[i],x+dx[i]) >= 0) { float distGabor = cv::norm(mGridGaborFeatures[y][x] - mGridGaborFeatures[y+dy[i]][x+dx[i]]); float distColor = fabs(mGrayScaleMap.at<float>(y,x) - mGrayScaleMap.at<float>(y+dy[i],x+dx[i])); // std::cout << distGabor << " " << distColor << std::endl; if (distGabor < minValue && distColor < 0.05) { minValue = distGabor; minIndex = checkMap.at<int>(y+dy[i],x+dx[i]); } } } if ( minValue < 2*Threshold ) { checkMap.at<int>(y,x) = minIndex; ifChange = true; break; } } } } if (!ifChange) { break; } } // std::cout << "Iter: " << Iter << std::endl; // std::cout << checkMap << std::endl; checkMap.copyTo(mTextureMap); #ifndef __ANDROID__ cv::Mat imgShow; cv::cvtColor(mImage, imgShow, CV_GRAY2BGR); std::vector<cv::Scalar> colours(classID+1); int step = 255 / (classID+1); for (int i = 0; i <= classID; i++) { colours[i] = cv::Scalar(step*i, 128-step*i*std::pow(-1,i), 128+step*i*std::pow(-1,i)); } for (int y = 1; y < mGridNumY-1; y++) { for (int x = 1; x < mGridNumX-1; x++) { if (checkMap.at<int>(y, x) >= 0) { cv::circle(imgShow, cv::Point2i(x*mGridX+mGridX/2, y*mGridY+mGridY/2), std::min(mGridX, mGridY)/8, colours[checkMap.at<int>(y, x)], 1); } } } cv::imshow("image segmented", imgShow); #endif } void TextureSegment::GetTextureRegions() { mTextureRegions.resize(mTextureID+1); mTextureRegionPortions.resize(mTextureID+1, 0); for (int i = 0; i < mTextureRegions.size(); i++) { mTextureRegions[i] = std::pair<cv::Point2f, cv::Point2f>( cv::Point2f(mImage.cols-1, mImage.rows-1), cv::Point2f(0, 0) ); } int id; float u,v; for (int y = 0; y < mTextureMap.rows; y++) { for (int x = 0; x < mTextureMap.cols; x++) { if (mTextureMap.at<int>(y, x) >= 0) { id = mTextureMap.at<int>(y, x); u = x * mGridX + mGridX/2; v = y * mGridY + mGridY/2; if (u < mTextureRegions[id].first.x) mTextureRegions[id].first.x = u; if (u > mTextureRegions[id].second.x) mTextureRegions[id].second.x = u; if (v < mTextureRegions[id].first.y) mTextureRegions[id].first.y = v; if (v > mTextureRegions[id].second.y) mTextureRegions[id].second.y = v; mTextureRegionPortions[id]++; } } } for (int i = 0; i < mTextureRegions.size(); i++) { if (mTextureRegionPortions[i] < mGridNumX/3*mGridNumY/3) { mTextureRegionPortions[i] = 0; continue; } mTextureRegionPortions[i] /= ((mTextureRegions[i].second.x-mTextureRegions[i].first.x) / mGridX + 1) * ((mTextureRegions[i].second.y-mTextureRegions[i].first.y) / mGridY + 1); std::cout << "textureID " << i << ": " << mTextureRegions[i].first << mTextureRegions[i].second << mTextureRegionPortions[i] << std::endl; } }
true
02c683e6c0d7684694481ed1eee9941febcfa664
C++
ccs-hnu/LeetCode
/Leetcode judge/median of two sorted arrays.cpp
UTF-8
3,408
3.1875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { unsigned min_length, max_length; vector<int> n1 = nums1, n2 = nums2; if(nums1.size() > nums2.size()) { min_length = nums2.size(); max_length = nums1.size(); n1 = nums2; n2 = nums1; } else { min_length = nums1.size(); max_length = nums2.size(); } unsigned lb = 0; unsigned ub = min_length; unsigned i, j; for(i = lb; i <= ub; i = (lb + ub)/2) { j = (min_length + max_length + 1) / 2 - i; cout << "j = " << j << endl; if((i == 0 || j == max_length || n1[i-1] <= n2[j]) && (i == min_length || j == 0 || n2[j-1] <= n1[i])) { cout << "i " << i << ",j " <<j << endl; cout << n2[j-1]<< n1[i] << endl; break; } else if(i > 0 && n1[i-1] > n2[j]) { ub = i - 1; } else if(i < min_length && n2[j-1] > n1[i]) { lb = i + 1; } } cout << "i = " << i << ", j = " << j <<endl; if((min_length + max_length) % 2 == 0) { if(i>0 && i<min_length) { return (double)(max(n1[i-1], n2[j-1]) + min(n1[i], n2[j])) / 2; } else if(i == 0 || i == min_length) { return (double) (n2[j-1] + n2[j]) / 2; } } else { return max(n1[i-1], n2[j-1]); } } }; class Solution2 { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { if(nums1.size() > nums2.size()) { return findMedianSortedArrays(nums2, nums1); } int m = nums1.size(); int n = nums2.size(); int imin = 0, imax = m; while(imin <= imax) { int i = (imin + imax)/2; int j = (m+n+1)/2 - i; //cout << "i = " << i << ", j = " << j << endl; if(i < m && nums2[j-1] > nums1[i]) { imin = i + 1; //cout << "nums2[j-1] > nums1[i]" << endl; continue; } else if(i > 0 && nums1[i-1] > nums2[j]) { imax = i - 1; //cout << "nums1[i-1] > nums2[j]" << endl; continue; } else { int maxLeft = 0; if(i == 0) { maxLeft = nums2[j-1]; } else if(j == 0) { maxLeft = nums1[i-1]; } else { maxLeft = max(nums1[i-1], nums2[j-1]); } if((m+n)%2 == 1) { return maxLeft; } int maxRight = 0; if(i == m) { maxRight = nums2[j]; } else if(j == n) { maxRight = nums1[i]; } else { maxRight = min(nums1[i], nums2[j]); } return (maxLeft + maxRight)/2.0; } } return 0.0; } }; int main() { Solution2 s; vector<int> nums1 = {1,2,3,4}; vector<int> nums2 = {5,6,7,8}; double median; median = s.findMedianSortedArrays(nums1, nums2); cout << median << endl; return 0; }
true
447835a5d9d080f5ebf4ca8e609ece3358de9a0d
C++
Kerorohu/Linux-DataRead
/main.cpp
UTF-8
1,593
3.34375
3
[]
no_license
#include <iostream> #include <string> #include <unistd.h> //For usleep() #include "SerialPort.hpp" using namespace std; int main(int argc, char *argv[]) { argc = 2 ; argv[1] = (char*)"ttyUSB2"; //dummy input string strModemDevice = "/dev/"; while(NULL == argv[1]) { char cInput; cout << "欠缺參數(ttyS0 或 ttyUSB0 之類的)" << endl; cout << "要幫懶惰的你補上\"ttyUSB0\"嗎?" << endl; cout << "[Y/n] "; cin >> cInput; if(toupper(cInput) == 'N') { cout << "結束程式" << endl; return 0;//跳出程式 } else if(toupper(cInput) == 'Y') { argc = 2; argv[1] = (char*)"ttyUSB2"; //dummy input break; } system("clear"); } cout << "argv[1]===: " << argv[1] << endl; strModemDevice.append(argv[1]); //在string後面加上一個char*字串 cout << "strModemDevice = " << strModemDevice << endl;//顯示總字串 //權限取得 string strPermissionGetCommand = "sudo chmod 666 " + strModemDevice; system(strPermissionGetCommand.c_str()); //建立物件 SerialPort* serialPort = new SerialPort(strModemDevice, SerialPort::BR19200); while(serialPort->isOpen()) {//開檔成功 //cout << "Pass!" << endl; /*//把 Hex String 轉換到 Byte Array string strSendMsg = "HelloWorld!"; //送出 Byte Array 資料 cout << "strSendMsg = " << strSendMsg << endl; cout << "send return = " << serialPort->Send(strSendMsg) << endl;*/ //接收字串 unsigned char strRx = serialPort->Recv(); printf("%02x\n", strRx); //cout << "Serial Port Receive : " << strRx << endl; } serialPort->Close(); delete(serialPort); }
true
584442c7713d65b6805b0744b40b101d7f4b8a61
C++
dotnet/runtime
/src/coreclr/jit/valuenum.h
UTF-8
82,999
2.890625
3
[ "MIT" ]
permissive
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Defines the class "ValueNumStore", which maintains value numbers for a compilation. // Recall that "value numbering" assigns an integer value number to each expression. The "value // number property" is that two expressions with the same value number will evaluate to the same value // at runtime. Expressions with different value numbers may or may not be equivalent. This property // of value numbers has obvious applications in redundancy-elimination optimizations. // // Since value numbers give us a way of talking about the (immutable) values to which expressions // evaluate, they provide a good "handle" to use for attributing properties to values. For example, // we might note that some value number represents some particular integer constant -- which has obvious // application to constant propagation. Or that we know the exact type of some object reference, // which might be used in devirtualization. // // Finally, we will also use value numbers to express control-flow-dependent assertions. Some test may // imply that after the test, something new is known about a value: that an object reference is non-null // after a dereference (since control flow continued because no exception was thrown); that an integer // value is restricted to some subrange in after a comparison test; etc. // In addition to classical numbering, this implementation also performs disambiguation of heap writes, // using memory SSA and the following aliasing model: // // 1. Arrays of different types do not alias - taking into account the array compatibility rules, i. e. // "int[] <-> uint[]" and such being allowed. // 2. Different static fields do not alias (meaning mutable overlapping RVA statics are not supported). // 3. Different class fields do not alias. Struct fields are allowed to alias - this supports code that // does reinterpretation of structs (e. g. "Unsafe.As<StructOne, StructTwo>(...)"), but makes it UB // to alias reference types in the same manner (including via explicit layout). // // The no aliasing rule for fields should be interpreted to mean that "ld[s]fld[a] FieldOne" cannot refer // to the same location as "ld[s]fld[a] FieldTwo". The aliasing model above reflects the fact type safety // rules in .NET largely only apply to reference types, while struct locations can be and often are treated // by user code (and, importantly, the compiler itself) as simple blobs of bytes. // // Abstractly, numbering maintains states of memory in "maps", which are indexed into with various "selectors", // loads reading from said maps and stores recording new states for them (note that as with everything VN, // the "maps" are immutable, thus an update is performed via deriving a new map from an existing one). // // Due to the fact we allow struct field access to alias, but still want to optimize it, our model has two // types of maps and selectors: precise and physical. Precise maps allow arbitrary selectors, and if those // are known to be distinct values (e. g. different constants), the values they select are also presumed to // represent distinct locations. Physical maps, on the other hand, can only have one type of selector: "the // physical selector", representing offset of the location and its size (in bytes), where both must be known // at compile time. Naturally, different physical selectors can refer to overlapping locations. // // The following "VNFunc"s are relevant when it comes to map numbering: // // 1. "MapSelect" - represents a "value" taken from another map at a given index: "map[index] => value". It is // the "VNForMapSelect[Work]" method that represents the core of the selection infrastructure: it performs // various reductions based on the maps (listed below) being selected from, before "giving up" and creating // a new "MapSelect" VN. "MapSelect"s are used for both precise and physical maps. // 2. "Phi[Memory]Def" - the PHI function applied to multiple reaching definitions for a given block. PHIs can // be reduced by the selection process: "Phi(d:1, d:2, ...)[index]" is evaluated as "Phi(d:1[index], ...)", // so if all the inner selections ("d:n[index]") agree, that value is returned as the selected one. // 3. "MapStore" - this is the precise "update" map, it represents a map after a "set" operation at some index. // MapStore VNs naturally "chain" together, the next map representing an update of the previous, and will be // traversed by the selection process as long as the store indices are constant, and different from the one // being selected (meaning they represent distinct locations): "map[F0 := V0][F1 := V1][F0]" => "V0". // 4. "MapPhysicalStore" - the physical equivalent to "MapStore", can only be indexed with physical selectors, // with the selection rules taking into account aliasability of physical locations. // 5. "BitCast" - the physical map representing "identity" selection ("map[0:sizeof(map) - 1]"). Exists because // physical maps themselves do not have a strong type identity (the physical selector only cares about size). // but the VN/IR at large do. Is a no-op in the selection process. One can notice that we could have chosen // to represent this concept with an identity "MapPhysicalStore", however, a different "VNFunc" was ultimately // chosen due to it being easier to reason about and a little cheaper, with the expectation that "BitCast"s // would be reasonably common - the scenario they are meant to handle are stores/loads to/from structs with // one field, where the location can be referenced from the IR as both TYP_STRUCT and the field's type. // // We give "placeholder" types (TYP_UNDEF and TYP_UNKNOWN as TYP_MEM and TYP_HEAP) to maps that do not represent // values found in IR, which are currently all precise (though that is not a requirement of the model). // // We choose to maintain the following invariants with regards to types of physical locations: // // 1. Tree VNs are always "normalized on load" - their types are made to match (via bitcasts). We presume this // makes the rest of the compiler code simpler, as it will not have to reason about "TYP_INT" trees having // "TYP_FLOAT" value numbers. This normalization is currently not always done; that should be fixed. // 2. Types of locals are "normalized on store" - this is different from the rest of physical locations, as not // only VN looks at these value numbers (stored in SSA descriptors), and similar to the tree case, we presume // it is simpler to reason about matching types. // 3. Types of all other locations (array elements and fields) are not normalized - these only appear in the VN // itself as physical maps / values. // // Note as well how we handle type identity for structs: we canonicalize on their size. This has the significant // consequence that any two equally-sized structs can be given the same value number, even if they have different // ABI characteristics or GC layout. The primary motivations for this are throughout and simplicity, however, we // would also like the compiler at large to treat structs with compatible layouts as equivalent, so that we can // propagate copies between them freely. // // // Let's review the following snippet to demonstrate how the MapSelect/MapStore machinery works. Say we have this // snippet of (C#) code: // // int Procedure(OneClass obj, AnotherClass subj, int objVal, int subjVal) // { // obj.StructField.ScalarField = objVal; // subj.OtherScalarField = subjVal; // // return obj.StructField.ScalarField + subj.OtherScalarField; // } // // On entry, we assign some VN to the GcHeap (VN mostly only cares about GcHeap, so from now on the term "heap" // will be used to mean GcHeap), $Heap. // // A store to the ScalarField is seen. Now, the value numbering of fields is done in the following pattern for // maps that it builds: [$Heap][$FirstField][$Object][offset:offset + size of the store]. It may seem odd that // the indexing is done first for the field, and only then for the object, but the reason for that is the fact // that it enables MapStores to $Heap to refer to distinct selectors, thus enabling the traversal through the // map updates when looking for the values that were stored. Were $Object VNs used for this, the traversal could // not be performed, as two numerically different VNs can, obviously, refer to the same object. // // With that in mind, the following maps are first built for the store ("field VNs" - VNs for handles): // // $StructFieldMap = MapSelect($Heap, $StructField) // $StructFieldForObjMap = MapSelect($StructFieldMap, $Obj) // // Now that we know where to store, the store maps are built: // // $ScalarFieldSelector = PhysicalSelector(offsetof(ScalarField), sizeof(ScalarField)) // $NewStructFieldForObjMap = MapPhysicalStore($StructFieldForObjMap, $ScalarFieldSelector, $ObjVal) // $NewStructFieldMap = MapStore($StructFieldMap, $Obj, $NewStructFieldForObjMap) // $NewHeap = MapStore($Heap, $StructField, $NewStructFieldMap) // // Notice that the maps are built in the opposite order, as we must first know the value of the "narrower" map to // store into the "wider" map. // // Similarly, the numbering is performed for "subj.OtherScalarField = subjVal", and the heap state updated (say to // $NewHeapWithSubj). Now when we call "VNForMapSelect" to find out the stored values when numbering the reads, the // following traversal is performed: // // $obj.StructField.AnotherStructField.ScalarField // = $NewHeapWithSubj[$StructField][$Obj][$ScalarFieldSelector]: // "$NewHeapWithSubj.Index == $StructField" => false (not the needed map). // "IsConst($NewHeapWithSubj.Index) && IsConst($StructField)" => true (can continue, non-aliasing indices). // "$NewHeap.Index == $StructField" => true, Value is $NewStructFieldMap. // "$NewStructFieldMap.Index == $Obj" => true, Value is $NewStructFieldForObjMap. // "$NewStructFieldForObjMap.Index == $ScalarFieldSelector" => true, Value is $ObjVal (found it!). // // And similarly for the $SubjVal - we end up with a nice $Add($ObjVal, $SubjVal) feeding the return. // // While the above example focuses on fields, the idea is universal to all supported location types. Statics are // modeled as straight indices into the heap (MapSelect($Heap, $Field) returns the value of the field for them), // arrays - like fields, but with the primiary selector being not the first field, but the "equivalence class" of // an array, i. e. the type of its elements, taking into account things like "int[]" being legally aliasable as // "uint[]". Physical maps are used to number local fields. /*****************************************************************************/ #ifndef _VALUENUM_H_ #define _VALUENUM_H_ /*****************************************************************************/ #include "vartype.h" // For "GT_COUNT" #include "gentree.h" // Defines the type ValueNum. #include "valuenumtype.h" // Defines the type SmallHashTable. #include "smallhash.h" // A "ValueNumStore" represents the "universe" of value numbers used in a single // compilation. // All members of the enumeration genTreeOps are also members of VNFunc. // (Though some of these may be labeled "illegal"). enum VNFunc { // Implicitly, elements of genTreeOps here. VNF_Boundary = GT_COUNT, #define ValueNumFuncDef(nm, arity, commute, knownNonNull, sharedStatic, extra) VNF_##nm, #include "valuenumfuncs.h" VNF_COUNT }; // Given a GenTree node return the VNFunc that should be used when value numbering // VNFunc GetVNFuncForNode(GenTree* node); // An instance of this struct represents an application of the function symbol // "m_func" to the first "m_arity" (<= 4) argument values in "m_args." struct VNFuncApp { VNFunc m_func; unsigned m_arity; ValueNum* m_args; bool Equals(const VNFuncApp& funcApp) { if (m_func != funcApp.m_func) { return false; } if (m_arity != funcApp.m_arity) { return false; } for (unsigned i = 0; i < m_arity; i++) { if (m_args[i] != funcApp.m_args[i]) { return false; } } return true; } }; // An instance of this struct represents the decoded information of a SIMD type from a value number. struct VNSimdTypeInfo { unsigned int m_simdSize; CorInfoType m_simdBaseJitType; }; // We use a unique prefix character when printing value numbers in dumps: i.e. $1c0 // This define is used with string concatenation to put this in printf format strings #define FMT_VN "$%x" // We will use this placeholder type for memory maps that do not represent IR values ("field maps", etc). static const var_types TYP_MEM = TYP_UNDEF; // We will use this placeholder type for memory maps representing "the heap" (GcHeap/ByrefExposed). static const var_types TYP_HEAP = TYP_UNKNOWN; class ValueNumStore { public: // We will reserve "max unsigned" to represent "not a value number", for maps that might start uninitialized. static const ValueNum NoVN = UINT32_MAX; // A second special value, used to indicate that a function evaluation would cause infinite recursion. static const ValueNum RecursiveVN = UINT32_MAX - 1; // ================================================================================================== // VNMap - map from something to ValueNum, where something is typically a constant value or a VNFunc // This class has two purposes - to abstract the implementation and to validate the ValueNums // being stored or retrieved. template <class fromType, class keyfuncs = JitLargePrimitiveKeyFuncs<fromType>> class VNMap : public JitHashTable<fromType, keyfuncs, ValueNum> { public: VNMap(CompAllocator alloc) : JitHashTable<fromType, keyfuncs, ValueNum>(alloc) { } bool Set(fromType k, ValueNum val) { assert(val != RecursiveVN); return JitHashTable<fromType, keyfuncs, ValueNum>::Set(k, val); } bool Lookup(fromType k, ValueNum* pVal = nullptr) const { bool result = JitHashTable<fromType, keyfuncs, ValueNum>::Lookup(k, pVal); assert(!result || *pVal != RecursiveVN); return result; } }; private: Compiler* m_pComp; // For allocations. (Other things?) CompAllocator m_alloc; // TODO-Cleanup: should transform "attribs" into a struct with bit fields. That would be simpler... enum VNFOpAttrib { VNFOA_IllegalGenTreeOp = 0x1, // corresponds to a genTreeOps value that is not a legal VN func. VNFOA_Commutative = 0x2, // 1 iff the function is commutative. VNFOA_Arity1 = 0x4, // Bits 2,3,4 encode the arity. VNFOA_Arity2 = 0x8, // Bits 2,3,4 encode the arity. VNFOA_Arity4 = 0x10, // Bits 2,3,4 encode the arity. VNFOA_KnownNonNull = 0x20, // 1 iff the result is known to be non-null. VNFOA_SharedStatic = 0x40, // 1 iff this VNF is represent one of the shared static jit helpers }; static const unsigned VNFOA_IllegalGenTreeOpShift = 0; static const unsigned VNFOA_CommutativeShift = 1; static const unsigned VNFOA_ArityShift = 2; static const unsigned VNFOA_ArityBits = 3; static const unsigned VNFOA_MaxArity = (1 << VNFOA_ArityBits) - 1; // Max arity we can represent. static const unsigned VNFOA_ArityMask = (VNFOA_Arity4 | VNFOA_Arity2 | VNFOA_Arity1); static const unsigned VNFOA_KnownNonNullShift = 5; static const unsigned VNFOA_SharedStaticShift = 6; static_assert(unsigned(VNFOA_IllegalGenTreeOp) == (1 << VNFOA_IllegalGenTreeOpShift)); static_assert(unsigned(VNFOA_Commutative) == (1 << VNFOA_CommutativeShift)); static_assert(unsigned(VNFOA_Arity1) == (1 << VNFOA_ArityShift)); static_assert(VNFOA_ArityMask == (VNFOA_MaxArity << VNFOA_ArityShift)); static_assert(unsigned(VNFOA_KnownNonNull) == (1 << VNFOA_KnownNonNullShift)); static_assert(unsigned(VNFOA_SharedStatic) == (1 << VNFOA_SharedStaticShift)); // These enum constants are used to encode the cast operation in the lowest bits by VNForCastOper enum VNFCastAttrib { VCA_UnsignedSrc = 0x01, VCA_BitCount = 1, // the number of reserved bits VCA_ReservedBits = 0x01, // i.e. (VCA_UnsignedSrc) }; // Helpers and an array of length GT_COUNT, mapping genTreeOp values to their VNFOpAttrib. static constexpr uint8_t GetOpAttribsForArity(genTreeOps oper, GenTreeOperKind kind); static constexpr uint8_t GetOpAttribsForGenTree(genTreeOps oper, bool commute, bool illegalAsVNFunc, GenTreeOperKind kind); static constexpr uint8_t GetOpAttribsForFunc(int arity, bool commute, bool knownNonNull, bool sharedStatic); static const uint8_t s_vnfOpAttribs[]; // Returns "true" iff gtOper is a legal value number function. // (Requires InitValueNumStoreStatics to have been run.) static bool GenTreeOpIsLegalVNFunc(genTreeOps gtOper); // Returns "true" iff "vnf" is a commutative (and thus binary) operator. // (Requires InitValueNumStoreStatics to have been run.) static bool VNFuncIsCommutative(VNFunc vnf); bool VNEvalCanFoldBinaryFunc(var_types type, VNFunc func, ValueNum arg0VN, ValueNum arg1VN); bool VNEvalCanFoldUnaryFunc(var_types type, VNFunc func, ValueNum arg0VN); // Returns "true" iff "vnf" should be folded by evaluating the func with constant arguments. bool VNEvalShouldFold(var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN); // Value number a type comparison ValueNum VNEvalFoldTypeCompare(var_types type, VNFunc func, ValueNum arg0VN, ValueNum arg1VN); // return vnf(v0) template <typename T> static T EvalOp(VNFunc vnf, T v0); // returns vnf(v0, v1). template <typename T> T EvalOp(VNFunc vnf, T v0, T v1); // return vnf(v0) or vnf(v0, v1), respectively (must, of course be unary/binary ops, respectively.) template <typename T> static T EvalOpSpecialized(VNFunc vnf, T v0); template <typename T> T EvalOpSpecialized(VNFunc vnf, T v0, T v1); template <typename T> static int EvalComparison(VNFunc vnf, T v0, T v1); // Should only instantiate (in a non-trivial way) for "int" and "INT64". Returns true iff dividing "v0" by "v1" // would produce integer overflow (an ArithmeticException -- *not* division by zero, which is separate.) template <typename T> static bool IsOverflowIntDiv(T v0, T v1); // Should only instantiate (in a non-trivial way) for integral types (signed/unsigned int32/int64). // Returns true iff v is the zero of the appropriate type. template <typename T> static bool IsIntZero(T v); public: // Given an constant value number return its value. int GetConstantInt32(ValueNum argVN); INT64 GetConstantInt64(ValueNum argVN); double GetConstantDouble(ValueNum argVN); float GetConstantSingle(ValueNum argVN); #if defined(FEATURE_SIMD) simd8_t GetConstantSimd8(ValueNum argVN); simd12_t GetConstantSimd12(ValueNum argVN); simd16_t GetConstantSimd16(ValueNum argVN); #if defined(TARGET_XARCH) simd32_t GetConstantSimd32(ValueNum argVN); simd64_t GetConstantSimd64(ValueNum argVN); #endif // TARGET_XARCH #endif // FEATURE_SIMD private: // Assumes that all the ValueNum arguments of each of these functions have been shown to represent constants. // Assumes that "vnf" is a operator of the appropriate arity (unary for the first, binary for the second). // Assume that "CanEvalForConstantArgs(vnf)" is true. // Returns the result of evaluating the function with those constant arguments. ValueNum EvalFuncForConstantArgs(var_types typ, VNFunc vnf, ValueNum vn0); ValueNum EvalFuncForConstantArgs(var_types typ, VNFunc vnf, ValueNum vn0, ValueNum vn1); ValueNum EvalFuncForConstantFPArgs(var_types typ, VNFunc vnf, ValueNum vn0, ValueNum vn1); ValueNum EvalCastForConstantArgs(var_types typ, VNFunc vnf, ValueNum vn0, ValueNum vn1); ValueNum EvalBitCastForConstantArgs(var_types dstType, ValueNum arg0VN); ValueNum EvalUsingMathIdentity(var_types typ, VNFunc vnf, ValueNum vn0, ValueNum vn1); // This is the constant value used for the default value of m_mapSelectBudget #define DEFAULT_MAP_SELECT_BUDGET 100 // used by JitVNMapSelBudget // This is the maximum number of MapSelect terms that can be "considered" as part of evaluation of a top-level // MapSelect application. int m_mapSelectBudget; template <typename T, typename NumMap> inline ValueNum VnForConst(T cnsVal, NumMap* numMap, var_types varType); // returns true iff vn is known to be a constant int32 that is > 0 bool IsVNPositiveInt32Constant(ValueNum vn); GenTreeFlags GetFoldedArithOpResultHandleFlags(ValueNum vn); public: // Validate that the new initializer for s_vnfOpAttribs matches the old code. static void ValidateValueNumStoreStatics(); // Initialize an empty ValueNumStore. ValueNumStore(Compiler* comp, CompAllocator allocator); // Returns "true" iff "vnf" (which may have been created by a cast from an integral value) represents // a legal value number function. // (Requires InitValueNumStoreStatics to have been run.) static bool VNFuncIsLegal(VNFunc vnf) { return unsigned(vnf) > VNF_Boundary || GenTreeOpIsLegalVNFunc(static_cast<genTreeOps>(vnf)); } // Returns "true" iff "vnf" is one of: // VNF_ADD_OVF, VNF_SUB_OVF, VNF_MUL_OVF, // VNF_ADD_UN_OVF, VNF_SUB_UN_OVF, VNF_MUL_UN_OVF. static bool VNFuncIsOverflowArithmetic(VNFunc vnf); // Returns "true" iff "vnf" is VNF_Cast or VNF_CastOvf. static bool VNFuncIsNumericCast(VNFunc vnf); // Returns the arity of "vnf". static unsigned VNFuncArity(VNFunc vnf); // Requires "gtOper" to be a genTreeOps legally representing a VNFunc, and returns that // VNFunc. // (Requires InitValueNumStoreStatics to have been run.) static VNFunc GenTreeOpToVNFunc(genTreeOps gtOper) { assert(GenTreeOpIsLegalVNFunc(gtOper)); return static_cast<VNFunc>(gtOper); } #ifdef DEBUG static void RunTests(Compiler* comp); #endif // DEBUG // This block of methods gets value numbers for constants of primitive types. ValueNum VNForIntCon(INT32 cnsVal); ValueNum VNForIntPtrCon(ssize_t cnsVal); ValueNum VNForLongCon(INT64 cnsVal); ValueNum VNForFloatCon(float cnsVal); ValueNum VNForDoubleCon(double cnsVal); ValueNum VNForByrefCon(target_size_t byrefVal); #if defined(FEATURE_SIMD) ValueNum VNForSimd8Con(simd8_t cnsVal); ValueNum VNForSimd12Con(simd12_t cnsVal); ValueNum VNForSimd16Con(simd16_t cnsVal); #if defined(TARGET_XARCH) ValueNum VNForSimd32Con(simd32_t cnsVal); ValueNum VNForSimd64Con(simd64_t cnsVal); #endif // TARGET_XARCH #endif // FEATURE_SIMD ValueNum VNForGenericCon(var_types typ, uint8_t* cnsVal); #ifdef TARGET_64BIT ValueNum VNForPtrSizeIntCon(INT64 cnsVal) { return VNForLongCon(cnsVal); } #else ValueNum VNForPtrSizeIntCon(INT32 cnsVal) { return VNForIntCon(cnsVal); } #endif // Packs information about the cast into an integer constant represented by the returned value number, // to be used as the second operand of VNF_Cast & VNF_CastOvf. ValueNum VNForCastOper(var_types castToType, bool srcIsUnsigned); // Unpacks the information stored by VNForCastOper in the constant represented by the value number. void GetCastOperFromVN(ValueNum vn, var_types* pCastToType, bool* pSrcIsUnsigned); // We keep handle values in a separate pool, so we don't confuse a handle with an int constant // that happens to be the same... ValueNum VNForHandle(ssize_t cnsVal, GenTreeFlags iconFlags); void AddToEmbeddedHandleMap(ssize_t embeddedHandle, ssize_t compileTimeHandle) { m_embeddedToCompileTimeHandleMap.AddOrUpdate(embeddedHandle, compileTimeHandle); } void AddToFieldAddressToFieldSeqMap(ValueNum fldAddr, FieldSeq* fldSeq) { m_fieldAddressToFieldSeqMap.AddOrUpdate(fldAddr, fldSeq); } FieldSeq* GetFieldSeqFromAddress(ValueNum fldAddr) { FieldSeq* fldSeq; if (m_fieldAddressToFieldSeqMap.TryGetValue(fldAddr, &fldSeq)) { return fldSeq; } return nullptr; } // And the single constant for an object reference type. static ValueNum VNForNull() { return ValueNum(SRC_Null); } // A special value number for "void" -- sometimes a type-void thing is an argument, // and we want the args to be non-NoVN. static ValueNum VNForVoid() { return ValueNum(SRC_Void); } static ValueNumPair VNPForVoid() { return ValueNumPair(VNForVoid(), VNForVoid()); } // A special value number for the empty set of exceptions. static ValueNum VNForEmptyExcSet() { return ValueNum(SRC_EmptyExcSet); } static ValueNumPair VNPForEmptyExcSet() { return ValueNumPair(VNForEmptyExcSet(), VNForEmptyExcSet()); } // Returns the value number for zero of the given "typ". // It has an unreached() for a "typ" that has no zero value, such as TYP_VOID. ValueNum VNZeroForType(var_types typ); // Returns the value number for a zero-initialized struct. ValueNum VNForZeroObj(ClassLayout* layout); // Returns the value number for one of the given "typ". // It returns NoVN for a "typ" that has no one value, such as TYP_REF. ValueNum VNOneForType(var_types typ); // Returns the value number for AllBitsSet of the given "typ". // It has an unreached() for a "typ" that has no all bits set value, such as TYP_VOID. ValueNum VNAllBitsForType(var_types typ); #ifdef FEATURE_SIMD // Returns the value number for one of the given "simdType" and "simdBaseType". ValueNum VNOneForSimdType(var_types simdType, var_types simdBaseType); // A helper function for constructing VNF_SimdType VNs. ValueNum VNForSimdType(unsigned simdSize, CorInfoType simdBaseJitType); #endif // FEATURE_SIMD // Create or return the existimg value number representing a singleton exception set // for the exception value "x". ValueNum VNExcSetSingleton(ValueNum x); ValueNumPair VNPExcSetSingleton(ValueNumPair x); // Returns true if the current pair of items are in ascending order and they are not duplicates. // Used to verify that exception sets are in ascending order when processing them. bool VNCheckAscending(ValueNum item, ValueNum xs1); // Returns the VN representing the union of the two exception sets "xs0" and "xs1". // These must be VNForEmptyExcSet() or applications of VNF_ExcSetCons, obeying // the ascending order invariant. (which is preserved in the result) ValueNum VNExcSetUnion(ValueNum xs0, ValueNum xs1); ValueNumPair VNPExcSetUnion(ValueNumPair xs0vnp, ValueNumPair xs1vnp); // Returns the VN representing the intersection of the two exception sets "xs0" and "xs1". // These must be applications of VNF_ExcSetCons or the empty set. (i.e VNForEmptyExcSet()) // and also must be in ascending order. ValueNum VNExcSetIntersection(ValueNum xs0, ValueNum xs1); ValueNumPair VNPExcSetIntersection(ValueNumPair xs0vnp, ValueNumPair xs1vnp); // Returns true if every exception singleton in the vnCandidateSet is also present // in the vnFullSet. // Both arguments must be either VNForEmptyExcSet() or applications of VNF_ExcSetCons. bool VNExcIsSubset(ValueNum vnFullSet, ValueNum vnCandidateSet); bool VNPExcIsSubset(ValueNumPair vnpFullSet, ValueNumPair vnpCandidateSet); // Returns "true" iff "vn" is an application of "VNF_ValWithExc". bool VNHasExc(ValueNum vn) { VNFuncApp funcApp; return GetVNFunc(vn, &funcApp) && funcApp.m_func == VNF_ValWithExc; } // If vn "excSet" is "VNForEmptyExcSet()" we just return "vn" // otherwise we use VNExcSetUnion to combine the exception sets of both "vn" and "excSet" // and return that ValueNum ValueNum VNWithExc(ValueNum vn, ValueNum excSet); ValueNumPair VNPWithExc(ValueNumPair vnp, ValueNumPair excSetVNP); // This sets "*pvn" to the Normal value and sets "*pvnx" to Exception set value. // "pvnx" represents the set of all exceptions that can happen for the expression void VNUnpackExc(ValueNum vnWx, ValueNum* pvn, ValueNum* pvnx); void VNPUnpackExc(ValueNumPair vnWx, ValueNumPair* pvn, ValueNumPair* pvnx); // This returns the Union of exceptions from vnWx and vnExcSet ValueNum VNUnionExcSet(ValueNum vnWx, ValueNum vnExcSet); // This returns the Union of exceptions from vnpWx and vnpExcSet ValueNumPair VNPUnionExcSet(ValueNumPair vnpWx, ValueNumPair vnpExcSet); // Sets the normal value to a new unique ValueNum // Keeps any Exception set values ValueNum VNMakeNormalUnique(ValueNum vn); // Sets the liberal & conservative // Keeps any Exception set values ValueNumPair VNPMakeNormalUniquePair(ValueNumPair vnp); // A new unique value with the given exception set. ValueNum VNUniqueWithExc(var_types type, ValueNum vnExcSet); // A new unique VN pair with the given exception set pair. ValueNumPair VNPUniqueWithExc(var_types type, ValueNumPair vnpExcSet); // If "vn" is a "VNF_ValWithExc(norm, excSet)" value, returns the "norm" argument; otherwise, // just returns "vn". // The Normal value is the value number of the expression when no exceptions occurred ValueNum VNNormalValue(ValueNum vn); // Given a "vnp", get the ValueNum kind based upon vnk, // then call VNNormalValue on that ValueNum // The Normal value is the value number of the expression when no exceptions occurred ValueNum VNNormalValue(ValueNumPair vnp, ValueNumKind vnk); // Given a "vnp", get the NormalValuew for the VNK_Liberal part of that ValueNum // The Normal value is the value number of the expression when no exceptions occurred inline ValueNum VNLiberalNormalValue(ValueNumPair vnp) { return VNNormalValue(vnp, VNK_Liberal); } // Given a "vnp", get the NormalValuew for the VNK_Conservative part of that ValueNum // The Normal value is the value number of the expression when no exceptions occurred inline ValueNum VNConservativeNormalValue(ValueNumPair vnp) { return VNNormalValue(vnp, VNK_Conservative); } // Given a "vnp", get the Normal values for both the liberal and conservative parts of "vnp" // The Normal value is the value number of the expression when no exceptions occurred ValueNumPair VNPNormalPair(ValueNumPair vnp); // If "vn" is a "VNF_ValWithExc(norm, excSet)" value, returns the "excSet" argument; otherwise, // we return a special Value Number representing the empty exception set. // The exception set value is the value number of the set of possible exceptions. ValueNum VNExceptionSet(ValueNum vn); ValueNumPair VNPExceptionSet(ValueNumPair vn); // True "iff" vn is a value known to be non-null. (For example, the result of an allocation...) bool IsKnownNonNull(ValueNum vn); // True "iff" vn is a value returned by a call to a shared static helper. bool IsSharedStatic(ValueNum vn); // VNForFunc: We have five overloads, for arities 0, 1, 2, 3 and 4 ValueNum VNForFunc(var_types typ, VNFunc func); ValueNum VNForFunc(var_types typ, VNFunc func, ValueNum opVNwx); // This must not be used for VNF_MapSelect applications; instead use VNForMapSelect, below. ValueNum VNForFunc(var_types typ, VNFunc func, ValueNum op1VNwx, ValueNum op2VNwx); ValueNum VNForFunc(var_types typ, VNFunc func, ValueNum op1VNwx, ValueNum op2VNwx, ValueNum op3VNwx); // The following four-op VNForFunc is used for VNF_PtrToArrElem, elemTypeEqVN, arrVN, inxVN, fldSeqVN ValueNum VNForFunc( var_types typ, VNFunc func, ValueNum op1VNwx, ValueNum op2VNwx, ValueNum op3VNwx, ValueNum op4VNwx); // Skip all folding checks. ValueNum VNForFuncNoFolding(var_types typ, VNFunc func, ValueNum op1VNwx, ValueNum op2VNwx); ValueNum VNForMapSelect(ValueNumKind vnk, var_types type, ValueNum map, ValueNum index); ValueNum VNForMapPhysicalSelect(ValueNumKind vnk, var_types type, ValueNum map, unsigned offset, unsigned size); ValueNum VNForMapSelectInner(ValueNumKind vnk, var_types type, ValueNum map, ValueNum index); // A method that does the work for VNForMapSelect and may call itself recursively. ValueNum VNForMapSelectWork(ValueNumKind vnk, var_types type, ValueNum map, ValueNum index, int* pBudget, bool* pUsedRecursiveVN, ArrayStack<ValueNum>* loopMemoryDependencies); // A specialized version of VNForFunc that is used for VNF_MapStore and provides some logging when verbose is set ValueNum VNForMapStore(ValueNum map, ValueNum index, ValueNum value); ValueNum VNForMapPhysicalStore(ValueNum map, unsigned offset, unsigned size, ValueNum value); bool MapIsPrecise(ValueNum map) const { return (TypeOfVN(map) == TYP_HEAP) || (TypeOfVN(map) == TYP_MEM); } bool MapIsPhysical(ValueNum map) const { return !MapIsPrecise(map); } ValueNum EncodePhysicalSelector(unsigned offset, unsigned size); unsigned DecodePhysicalSelector(ValueNum selector, unsigned* pSize); ValueNum VNForFieldSelector(CORINFO_FIELD_HANDLE fieldHnd, var_types* pFieldType, unsigned* pSize); // These functions parallel the ones above, except that they take liberal/conservative VN pairs // as arguments, and return such a pair (the pair of the function applied to the liberal args, and // the function applied to the conservative args). ValueNumPair VNPairForFunc(var_types typ, VNFunc func) { ValueNumPair res; res.SetBoth(VNForFunc(typ, func)); return res; } ValueNumPair VNPairForFunc(var_types typ, VNFunc func, ValueNumPair opVN) { ValueNum liberalFuncVN = VNForFunc(typ, func, opVN.GetLiberal()); ValueNum conservativeFuncVN; if (opVN.BothEqual()) { conservativeFuncVN = liberalFuncVN; } else { conservativeFuncVN = VNForFunc(typ, func, opVN.GetConservative()); } return ValueNumPair(liberalFuncVN, conservativeFuncVN); } ValueNumPair VNPairForFunc(var_types typ, VNFunc func, ValueNumPair op1VN, ValueNumPair op2VN) { ValueNum liberalFuncVN = VNForFunc(typ, func, op1VN.GetLiberal(), op2VN.GetLiberal()); ValueNum conservativeFuncVN; if (op1VN.BothEqual() && op2VN.BothEqual()) { conservativeFuncVN = liberalFuncVN; } else { conservativeFuncVN = VNForFunc(typ, func, op1VN.GetConservative(), op2VN.GetConservative()); } return ValueNumPair(liberalFuncVN, conservativeFuncVN); } ValueNumPair VNPairForFuncNoFolding(var_types typ, VNFunc func, ValueNumPair op1VN, ValueNumPair op2VN) { ValueNum liberalFuncVN = VNForFuncNoFolding(typ, func, op1VN.GetLiberal(), op2VN.GetLiberal()); ValueNum conservativeFuncVN; if (op1VN.BothEqual() && op2VN.BothEqual()) { conservativeFuncVN = liberalFuncVN; } else { conservativeFuncVN = VNForFuncNoFolding(typ, func, op1VN.GetConservative(), op2VN.GetConservative()); } return ValueNumPair(liberalFuncVN, conservativeFuncVN); } ValueNumPair VNPairForFunc(var_types typ, VNFunc func, ValueNumPair op1VN, ValueNumPair op2VN, ValueNumPair op3VN) { ValueNum liberalFuncVN = VNForFunc(typ, func, op1VN.GetLiberal(), op2VN.GetLiberal(), op3VN.GetLiberal()); ValueNum conservativeFuncVN; if (op1VN.BothEqual() && op2VN.BothEqual() && op3VN.BothEqual()) { conservativeFuncVN = liberalFuncVN; } else { conservativeFuncVN = VNForFunc(typ, func, op1VN.GetConservative(), op2VN.GetConservative(), op3VN.GetConservative()); } return ValueNumPair(liberalFuncVN, conservativeFuncVN); } ValueNumPair VNPairForFunc( var_types typ, VNFunc func, ValueNumPair op1VN, ValueNumPair op2VN, ValueNumPair op3VN, ValueNumPair op4VN) { ValueNum liberalFuncVN = VNForFunc(typ, func, op1VN.GetLiberal(), op2VN.GetLiberal(), op3VN.GetLiberal(), op4VN.GetLiberal()); ValueNum conservativeFuncVN; if (op1VN.BothEqual() && op2VN.BothEqual() && op3VN.BothEqual() && op4VN.BothEqual()) { conservativeFuncVN = liberalFuncVN; } else { conservativeFuncVN = VNForFunc(typ, func, op1VN.GetConservative(), op2VN.GetConservative(), op3VN.GetConservative(), op4VN.GetConservative()); } return ValueNumPair(liberalFuncVN, conservativeFuncVN); } ValueNum VNForExpr(BasicBlock* block, var_types type = TYP_UNKNOWN); ValueNumPair VNPairForExpr(BasicBlock* block, var_types type); // This controls extra tracing of the "evaluation" of "VNF_MapSelect" functions. #define FEATURE_VN_TRACE_APPLY_SELECTORS 1 ValueNum VNForLoad(ValueNumKind vnk, ValueNum locationValue, unsigned locationSize, var_types loadType, ssize_t offset, unsigned loadSize); ValueNumPair VNPairForLoad( ValueNumPair locationValue, unsigned locationSize, var_types loadType, ssize_t offset, unsigned loadSize); ValueNum VNForStore( ValueNum locationValue, unsigned locationSize, ssize_t offset, unsigned storeSize, ValueNum value); ValueNumPair VNPairForStore( ValueNumPair locationValue, unsigned locationSize, ssize_t offset, unsigned storeSize, ValueNumPair value); static bool LoadStoreIsEntire(unsigned locationSize, ssize_t offset, unsigned indSize) { return (offset == 0) && (locationSize == indSize); } ValueNum VNForLoadStoreBitCast(ValueNum value, var_types indType, unsigned indSize); ValueNumPair VNPairForLoadStoreBitCast(ValueNumPair value, var_types indType, unsigned indSize); // Compute the ValueNumber for a cast ValueNum VNForCast(ValueNum srcVN, var_types castToType, var_types castFromType, bool srcIsUnsigned = false, bool hasOverflowCheck = false); // Compute the ValueNumberPair for a cast ValueNumPair VNPairForCast(ValueNumPair srcVNPair, var_types castToType, var_types castFromType, bool srcIsUnsigned = false, bool hasOverflowCheck = false); ValueNum EncodeBitCastType(var_types castToType, unsigned size); var_types DecodeBitCastType(ValueNum castToTypeVN, unsigned* pSize); ValueNum VNForBitCast(ValueNum srcVN, var_types castToType, unsigned size); ValueNumPair VNPairForBitCast(ValueNumPair srcVNPair, var_types castToType, unsigned size); ValueNum VNForFieldSeq(FieldSeq* fieldSeq); FieldSeq* FieldSeqVNToFieldSeq(ValueNum vn); ValueNum ExtendPtrVN(GenTree* opA, GenTree* opB); ValueNum ExtendPtrVN(GenTree* opA, FieldSeq* fieldSeq, ssize_t offset); // Queries on value numbers. // All queries taking value numbers require that those value numbers are valid, that is, that // they have been returned by previous "VNFor..." operations. They can assert false if this is // not true. // Returns TYP_UNKNOWN if the given value number has not been given a type. var_types TypeOfVN(ValueNum vn) const; // Returns BasicBlock::MAX_LOOP_NUM if the given value number's loop nest is unknown or ill-defined. BasicBlock::loopNumber LoopOfVN(ValueNum vn); // Returns true iff the VN represents a constant. bool IsVNConstant(ValueNum vn); // Returns true iff the VN represents a (non-handle) constant. bool IsVNConstantNonHandle(ValueNum vn); // Returns true iff the VN represents an integer constant. bool IsVNInt32Constant(ValueNum vn); // Returns true if the VN represents a node that is never negative. bool IsVNNeverNegative(ValueNum vn); typedef SmallHashTable<ValueNum, bool, 8U> CheckedBoundVNSet; // Returns true if the VN is known or likely to appear as the conservative value number // of the length argument to a GT_BOUNDS_CHECK node. bool IsVNCheckedBound(ValueNum vn); // Record that a VN is known to appear as the conservative value number of the length // argument to a GT_BOUNDS_CHECK node. void SetVNIsCheckedBound(ValueNum vn); // Information about the individual components of a value number representing an unsigned // comparison of some value against a checked bound VN. struct UnsignedCompareCheckedBoundInfo { unsigned cmpOper; ValueNum vnIdx; ValueNum vnBound; UnsignedCompareCheckedBoundInfo() : cmpOper(GT_NONE), vnIdx(NoVN), vnBound(NoVN) { } }; struct CompareCheckedBoundArithInfo { // (vnBound - 1) > vnOp // (vnBound arrOper arrOp) cmpOper cmpOp ValueNum vnBound; unsigned arrOper; ValueNum arrOp; unsigned cmpOper; ValueNum cmpOp; CompareCheckedBoundArithInfo() : vnBound(NoVN), arrOper(GT_NONE), arrOp(NoVN), cmpOper(GT_NONE), cmpOp(NoVN) { } #ifdef DEBUG void dump(ValueNumStore* vnStore) { vnStore->vnDump(vnStore->m_pComp, cmpOp); printf(" "); printf(vnStore->VNFuncName((VNFunc)cmpOper)); printf(" "); vnStore->vnDump(vnStore->m_pComp, vnBound); if (arrOper != GT_NONE) { printf(vnStore->VNFuncName((VNFunc)arrOper)); vnStore->vnDump(vnStore->m_pComp, arrOp); } } #endif }; struct ConstantBoundInfo { // 100 > vnOp int constVal; unsigned cmpOper; ValueNum cmpOpVN; bool isUnsigned; ConstantBoundInfo() : constVal(0), cmpOper(GT_NONE), cmpOpVN(NoVN), isUnsigned(false) { } #ifdef DEBUG void dump(ValueNumStore* vnStore) { vnStore->vnDump(vnStore->m_pComp, cmpOpVN); printf(" "); printf(vnStore->VNFuncName((VNFunc)cmpOper)); printf(" "); printf("%d", constVal); } #endif }; // Check if "vn" is "new [] (type handle, size)" bool IsVNNewArr(ValueNum vn, VNFuncApp* funcApp); // Check if "vn" IsVNNewArr and return false if arr size cannot be determined. bool TryGetNewArrSize(ValueNum vn, int* size); // Check if "vn" is "a.Length" or "a.GetLength(n)" bool IsVNArrLen(ValueNum vn); // If "vn" is VN(a.Length) or VN(a.GetLength(n)) then return VN(a); NoVN if VN(a) can't be determined. ValueNum GetArrForLenVn(ValueNum vn); // Return true with any Relop except for == and != and one operand has to be a 32-bit integer constant. bool IsVNConstantBound(ValueNum vn); // If "vn" is of the form "(uint)var relop cns" for any relop except for == and != bool IsVNConstantBoundUnsigned(ValueNum vn); // If "vn" is constant bound, then populate the "info" fields for constVal, cmpOp, cmpOper. void GetConstantBoundInfo(ValueNum vn, ConstantBoundInfo* info); // If "vn" is of the form "(uint)var < (uint)len" (or equivalent) return true. bool IsVNUnsignedCompareCheckedBound(ValueNum vn, UnsignedCompareCheckedBoundInfo* info); // If "vn" is of the form "var < len" or "len <= var" return true. bool IsVNCompareCheckedBound(ValueNum vn); // If "vn" is checked bound, then populate the "info" fields for the boundVn, cmpOp, cmpOper. void GetCompareCheckedBound(ValueNum vn, CompareCheckedBoundArithInfo* info); // If "vn" is of the form "len +/- var" return true. bool IsVNCheckedBoundArith(ValueNum vn); // If "vn" is checked bound arith, then populate the "info" fields for arrOper, arrVn, arrOp. void GetCheckedBoundArithInfo(ValueNum vn, CompareCheckedBoundArithInfo* info); // If "vn" is of the form "var < len +/- k" return true. bool IsVNCompareCheckedBoundArith(ValueNum vn); // If "vn" is checked bound arith, then populate the "info" fields for cmpOp, cmpOper. void GetCompareCheckedBoundArithInfo(ValueNum vn, CompareCheckedBoundArithInfo* info); // Returns the flags on the current handle. GTF_ICON_SCOPE_HDL for example. GenTreeFlags GetHandleFlags(ValueNum vn); // Returns true iff the VN represents a handle constant. bool IsVNHandle(ValueNum vn); // Returns true iff the VN represents an object handle constant. bool IsVNObjHandle(ValueNum vn); // Returns true iff the VN represents a relop bool IsVNRelop(ValueNum vn); enum class VN_RELATION_KIND { VRK_Inferred, // (x ? y) VRK_Same, // (x > y) VRK_Swap, // (y > x) VRK_Reverse, // (x <= y) VRK_SwapReverse // (y >= x) }; #ifdef DEBUG static const char* VNRelationString(VN_RELATION_KIND vrk); #endif // Given VN(x > y), return VN(y > x), VN(x <= y) or VN(y >= x) // // If vn is not a relop, return NoVN. // ValueNum GetRelatedRelop(ValueNum vn, VN_RELATION_KIND vrk); // Return VNFunc for swapped relop, or VNF_MemOpaque if the function // is not a relop. static VNFunc SwapRelop(VNFunc vnf); // Returns "true" iff "vnf" is a comparison (and thus binary) operator. static bool VNFuncIsComparison(VNFunc vnf); // Convert a vartype_t to the value number's storage type for that vartype_t. // For example, ValueNum of type TYP_LONG are stored in a map of INT64 variables. // Lang is the language (C++) type for the corresponding vartype_t. template <int N> struct VarTypConv { }; private: struct Chunk; template <typename T> static T CoerceTypRefToT(Chunk* c, unsigned offset); // Get the actual value and coerce the actual type c->m_typ to the wanted type T. template <typename T> FORCEINLINE T SafeGetConstantValue(Chunk* c, unsigned offset); template <typename T> T ConstantValueInternal(ValueNum vn DEBUGARG(bool coerce)) { Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn)); assert(c->m_attribs == CEA_Const || c->m_attribs == CEA_Handle); unsigned offset = ChunkOffset(vn); switch (c->m_typ) { case TYP_REF: assert(0 <= offset && offset <= 1); // Null or exception. FALLTHROUGH; case TYP_BYREF: #ifdef _MSC_VER assert(&typeid(T) == &typeid(size_t)); // We represent ref/byref constants as size_t's. #endif // _MSC_VER FALLTHROUGH; case TYP_INT: case TYP_LONG: case TYP_FLOAT: case TYP_DOUBLE: if (c->m_attribs == CEA_Handle) { C_ASSERT(offsetof(VNHandle, m_cnsVal) == 0); return (T) reinterpret_cast<VNHandle*>(c->m_defs)[offset].m_cnsVal; } #ifdef DEBUG if (!coerce) { T val1 = reinterpret_cast<T*>(c->m_defs)[offset]; T val2 = SafeGetConstantValue<T>(c, offset); // Detect if there is a mismatch between the VN storage type and explicitly // passed-in type T. bool mismatch = false; if (varTypeIsFloating(c->m_typ)) { mismatch = (memcmp(&val1, &val2, sizeof(val1)) != 0); } else { mismatch = (val1 != val2); } if (mismatch) { assert( !"Called ConstantValue<T>(vn), but type(T) != type(vn); Use CoercedConstantValue instead."); } } #endif return SafeGetConstantValue<T>(c, offset); default: assert(false); // We do not record constants of this typ. return (T)0; } } public: // Requires that "vn" is a constant, and that its type is compatible with the explicitly passed // type "T". Also, note that "T" has to have an accurate storage size of the TypeOfVN(vn). template <typename T> T ConstantValue(ValueNum vn) { return ConstantValueInternal<T>(vn DEBUGARG(false)); } // Requires that "vn" is a constant, and that its type can be coerced to the explicitly passed // type "T". template <typename T> T CoercedConstantValue(ValueNum vn) { return ConstantValueInternal<T>(vn DEBUGARG(true)); } CORINFO_OBJECT_HANDLE ConstantObjHandle(ValueNum vn) { assert(IsVNObjHandle(vn)); return reinterpret_cast<CORINFO_OBJECT_HANDLE>(CoercedConstantValue<size_t>(vn)); } // Requires "mthFunc" to be an intrinsic math function (one of the allowable values for the "gtMath" field // of a GenTreeMath node). For unary ops, return the value number for the application of this function to // "arg0VN". For binary ops, return the value number for the application of this function to "arg0VN" and // "arg1VN". ValueNum EvalMathFuncUnary(var_types typ, NamedIntrinsic mthFunc, ValueNum arg0VN); ValueNum EvalMathFuncBinary(var_types typ, NamedIntrinsic mthFunc, ValueNum arg0VN, ValueNum arg1VN); ValueNumPair EvalMathFuncUnary(var_types typ, NamedIntrinsic mthFunc, ValueNumPair arg0VNP) { return ValueNumPair(EvalMathFuncUnary(typ, mthFunc, arg0VNP.GetLiberal()), EvalMathFuncUnary(typ, mthFunc, arg0VNP.GetConservative())); } ValueNumPair EvalMathFuncBinary(var_types typ, NamedIntrinsic mthFunc, ValueNumPair arg0VNP, ValueNumPair arg1VNP) { return ValueNumPair(EvalMathFuncBinary(typ, mthFunc, arg0VNP.GetLiberal(), arg1VNP.GetLiberal()), EvalMathFuncBinary(typ, mthFunc, arg0VNP.GetConservative(), arg1VNP.GetConservative())); } ValueNum EvalHWIntrinsicFunUnary(var_types type, var_types baseType, NamedIntrinsic ni, VNFunc func, ValueNum arg0VN, bool encodeResultType, ValueNum resultTypeVN); ValueNum EvalHWIntrinsicFunBinary(var_types type, var_types baseType, NamedIntrinsic ni, VNFunc func, ValueNum arg0VN, ValueNum arg1VN, bool encodeResultType, ValueNum resultTypeVN); ValueNum EvalHWIntrinsicFunTernary(var_types type, var_types baseType, NamedIntrinsic ni, VNFunc func, ValueNum arg0VN, ValueNum arg1VN, ValueNum arg2VN, bool encodeResultType, ValueNum resultTypeVN); // Returns "true" iff "vn" represents a function application. bool IsVNFunc(ValueNum vn); // If "vn" represents a function application, returns "true" and set "*funcApp" to // the function application it represents; otherwise, return "false." bool GetVNFunc(ValueNum vn, VNFuncApp* funcApp); // Returns "true" iff "vn" is a valid value number -- one that has been previously returned. bool VNIsValid(ValueNum vn); #ifdef DEBUG // This controls whether we recursively call vnDump on function arguments. #define FEATURE_VN_DUMP_FUNC_ARGS 0 // Prints, to standard out, a representation of "vn". void vnDump(Compiler* comp, ValueNum vn, bool isPtr = false); // Requires "fieldSeq" to be a field sequence VN. // Prints a representation (comma-separated list of field names) on standard out. void vnDumpFieldSeq(Compiler* comp, ValueNum fieldSeqVN); // Requires "mapSelect" to be a map select VNFuncApp. // Prints a representation of a MapSelect operation on standard out. void vnDumpMapSelect(Compiler* comp, VNFuncApp* mapSelect); // Requires "mapStore" to be a map store VNFuncApp. // Prints a representation of a MapStore operation on standard out. void vnDumpMapStore(Compiler* comp, VNFuncApp* mapStore); void vnDumpPhysicalSelector(ValueNum selector); void vnDumpMapPhysicalStore(Compiler* comp, VNFuncApp* mapPhysicalStore); // Requires "memOpaque" to be a mem opaque VNFuncApp // Prints a representation of a MemOpaque state on standard out. void vnDumpMemOpaque(Compiler* comp, VNFuncApp* memOpaque); // Requires "valWithExc" to be a value with an exception set VNFuncApp. // Prints a representation of the exception set on standard out. void vnDumpValWithExc(Compiler* comp, VNFuncApp* valWithExc); // Requires "excSeq" to be a ExcSetCons sequence. // Prints a representation of the set of exceptions on standard out. void vnDumpExcSeq(Compiler* comp, VNFuncApp* excSeq, bool isHead); #ifdef FEATURE_SIMD // Requires "simdType" to be a VNF_SimdType VNFuncApp. // Prints a representation (comma-separated list of field names) on standard out. void vnDumpSimdType(Compiler* comp, VNFuncApp* simdType); #endif // FEATURE_SIMD // Requires "castVN" to represent VNF_Cast or VNF_CastOvf. // Prints the cast's representation mirroring GT_CAST's dump format. void vnDumpCast(Compiler* comp, ValueNum castVN); void vnDumpBitCast(Compiler* comp, VNFuncApp* bitCast); // Requires "zeroObj" to be a VNF_ZeroObj. Prints its representation. void vnDumpZeroObj(Compiler* comp, VNFuncApp* zeroObj); // Returns the string name of "vnf". static const char* VNFuncName(VNFunc vnf); // Used in the implementation of the above. static const char* VNFuncNameArr[]; // Returns a type name used for "maps", i. e. displays TYP_UNDEF and TYP_UNKNOWN as TYP_MEM and TYP_HEAP. static const char* VNMapTypeName(var_types type); // Returns the string name of "vn" when it is a reserved value number, nullptr otherwise static const char* reservedName(ValueNum vn); #endif // DEBUG // Returns true if "vn" is a reserved value number static bool isReservedVN(ValueNum); private: struct VNDefFuncAppFlexible { VNFunc m_func; ValueNum m_args[]; }; template <size_t NumArgs> struct VNDefFuncApp { VNFunc m_func; ValueNum m_args[NumArgs]; VNDefFuncApp() : m_func(VNF_COUNT) { for (size_t i = 0; i < NumArgs; i++) { m_args[i] = ValueNumStore::NoVN; } } template <typename... VNs> VNDefFuncApp(VNFunc func, VNs... vns) : m_func(func), m_args{vns...} { static_assert_no_msg(NumArgs == sizeof...(VNs)); } bool operator==(const VNDefFuncApp& y) const { bool result = m_func == y.m_func; // Intentionally written without early-out or MSVC cannot unroll this. for (size_t i = 0; i < NumArgs; i++) { result = result && m_args[i] == y.m_args[i]; } return result; } }; // We will allocate value numbers in "chunks". Each chunk will have the same type and "constness". static const unsigned LogChunkSize = 6; static const unsigned ChunkSize = 1 << LogChunkSize; static const unsigned ChunkOffsetMask = ChunkSize - 1; // A "ChunkNum" is a zero-based index naming a chunk in the Store, or else the special "NoChunk" value. typedef UINT32 ChunkNum; static const ChunkNum NoChunk = UINT32_MAX; // Returns the ChunkNum of the Chunk that holds "vn" (which is required to be a valid // value number, i.e., one returned by some VN-producing method of this class). static ChunkNum GetChunkNum(ValueNum vn) { return vn >> LogChunkSize; } // Returns the offset of the given "vn" within its chunk. static unsigned ChunkOffset(ValueNum vn) { return vn & ChunkOffsetMask; } // The base VN of the next chunk to be allocated. Should always be a multiple of ChunkSize. ValueNum m_nextChunkBase; enum ChunkExtraAttribs : BYTE { CEA_Const, // This chunk contains constant values. CEA_Handle, // This chunk contains handle constants. CEA_Func0, // Represents functions of arity 0. CEA_Func1, // ...arity 1. CEA_Func2, // ...arity 2. CEA_Func3, // ...arity 3. CEA_Func4, // ...arity 4. CEA_Count }; // A "Chunk" holds "ChunkSize" value numbers, starting at "m_baseVN". All of these share the same // "m_typ" and "m_attribs". These properties determine the interpretation of "m_defs", as discussed below. struct Chunk { // If "m_defs" is non-null, it is an array of size ChunkSize, whose element type is determined by the other // members. The "m_numUsed" field indicates the number of elements of "m_defs" that are already consumed (the // next one to allocate). void* m_defs; unsigned m_numUsed; // The value number of the first VN in the chunk. ValueNum m_baseVN; // The common attributes of this chunk. var_types m_typ; ChunkExtraAttribs m_attribs; // Initialize a chunk, starting at "*baseVN", for the given "typ", and "attribs", using "alloc" for allocations. // (Increments "*baseVN" by ChunkSize.) Chunk(CompAllocator alloc, ValueNum* baseVN, var_types typ, ChunkExtraAttribs attribs); // Requires that "m_numUsed < ChunkSize." Returns the offset of the allocated VN within the chunk; the // actual VN is this added to the "m_baseVN" of the chunk. unsigned AllocVN() { assert(m_numUsed < ChunkSize); return m_numUsed++; } VNDefFuncAppFlexible* PointerToFuncApp(unsigned offsetWithinChunk, unsigned numArgs) { assert((m_attribs >= CEA_Func0) && (m_attribs <= CEA_Func4)); assert(numArgs == (unsigned)(m_attribs - CEA_Func0)); static_assert_no_msg(sizeof(VNDefFuncAppFlexible) == sizeof(VNFunc)); return reinterpret_cast<VNDefFuncAppFlexible*>( (char*)m_defs + offsetWithinChunk * (sizeof(VNDefFuncAppFlexible) + sizeof(ValueNum) * numArgs)); } template <int N> struct Alloc { typedef typename ValueNumStore::VarTypConv<N>::Type Type; }; }; struct VNHandle : public JitKeyFuncsDefEquals<VNHandle> { ssize_t m_cnsVal; GenTreeFlags m_flags; // Don't use a constructor to use the default copy constructor for hashtable rehash. static void Initialize(VNHandle* handle, ssize_t m_cnsVal, GenTreeFlags m_flags) { handle->m_cnsVal = m_cnsVal; handle->m_flags = m_flags; } bool operator==(const VNHandle& y) const { return m_cnsVal == y.m_cnsVal && m_flags == y.m_flags; } static unsigned GetHashCode(const VNHandle& val) { return static_cast<unsigned>(val.m_cnsVal); } }; // When we evaluate "select(m, i)", if "m" is a the value of a phi definition, we look at // all the values of the phi args, and see if doing the "select" on each of them yields identical // results. If so, that is the result of the entire "select" form. We have to be careful, however, // because phis may be recursive in the presence of loop structures -- the VN for the phi may be (or be // part of the definition of) the VN's of some of the arguments. But there will be at least one // argument that does *not* depend on the outer phi VN -- after all, we had to get into the loop somehow. // So we have to be careful about breaking infinite recursion. We can ignore "recursive" results -- if all the // non-recursive results are the same, the recursion indicates that the loop structure didn't alter the result. // This stack represents the set of outer phis such that select(phi, ind) is being evaluated. JitExpandArrayStack<VNDefFuncApp<2>> m_fixedPointMapSels; #ifdef DEBUG // Returns "true" iff "m_fixedPointMapSels" is non-empty, and it's top element is // "select(map, index)". bool FixedPointMapSelsTopHasValue(ValueNum map, ValueNum index); #endif // Returns true if "sel(map, ind)" is a member of "m_fixedPointMapSels". bool SelectIsBeingEvaluatedRecursively(ValueNum map, ValueNum ind); // This is the set of value numbers that have been flagged as arguments to bounds checks, in the length position. CheckedBoundVNSet m_checkedBoundVNs; // This is a map from "chunk number" to the attributes of the chunk. JitExpandArrayStack<Chunk*> m_chunks; // These entries indicate the current allocation chunk, if any, for each valid combination of <var_types, // ChunkExtraAttribute>. // If the value is NoChunk, it indicates that there is no current allocation chunk for that pair, otherwise // it is the index in "m_chunks" of a chunk with the given attributes, in which the next allocation should // be attempted. ChunkNum m_curAllocChunk[TYP_COUNT][CEA_Count + 1]; // Returns a (pointer to a) chunk in which a new value number may be allocated. Chunk* GetAllocChunk(var_types typ, ChunkExtraAttribs attribs); // First, we need mechanisms for mapping from constants to value numbers. // For small integers, we'll use an array. static const int SmallIntConstMin = -1; static const int SmallIntConstMax = 10; static const unsigned SmallIntConstNum = SmallIntConstMax - SmallIntConstMin + 1; static bool IsSmallIntConst(int i) { return SmallIntConstMin <= i && i <= SmallIntConstMax; } ValueNum m_VNsForSmallIntConsts[SmallIntConstNum]; struct ValueNumList { ValueNum vn; ValueNumList* next; ValueNumList(const ValueNum& v, ValueNumList* n = nullptr) : vn(v), next(n) { } }; // Keeps track of value numbers that are integer constants and also handles (GTG_ICON_HDL_MASK.) ValueNumList* m_intConHandles; typedef VNMap<INT32> IntToValueNumMap; IntToValueNumMap* m_intCnsMap; IntToValueNumMap* GetIntCnsMap() { if (m_intCnsMap == nullptr) { m_intCnsMap = new (m_alloc) IntToValueNumMap(m_alloc); } return m_intCnsMap; } typedef VNMap<INT64> LongToValueNumMap; LongToValueNumMap* m_longCnsMap; LongToValueNumMap* GetLongCnsMap() { if (m_longCnsMap == nullptr) { m_longCnsMap = new (m_alloc) LongToValueNumMap(m_alloc); } return m_longCnsMap; } typedef VNMap<VNHandle, VNHandle> HandleToValueNumMap; HandleToValueNumMap* m_handleMap; HandleToValueNumMap* GetHandleMap() { if (m_handleMap == nullptr) { m_handleMap = new (m_alloc) HandleToValueNumMap(m_alloc); } return m_handleMap; } typedef SmallHashTable<ssize_t, ssize_t> EmbeddedToCompileTimeHandleMap; EmbeddedToCompileTimeHandleMap m_embeddedToCompileTimeHandleMap; typedef SmallHashTable<ValueNum, FieldSeq*> FieldAddressToFieldSeqMap; FieldAddressToFieldSeqMap m_fieldAddressToFieldSeqMap; struct LargePrimitiveKeyFuncsFloat : public JitLargePrimitiveKeyFuncs<float> { static bool Equals(float x, float y) { return *(unsigned*)&x == *(unsigned*)&y; } }; typedef VNMap<float, LargePrimitiveKeyFuncsFloat> FloatToValueNumMap; FloatToValueNumMap* m_floatCnsMap; FloatToValueNumMap* GetFloatCnsMap() { if (m_floatCnsMap == nullptr) { m_floatCnsMap = new (m_alloc) FloatToValueNumMap(m_alloc); } return m_floatCnsMap; } // In the JIT we need to distinguish -0.0 and 0.0 for optimizations. struct LargePrimitiveKeyFuncsDouble : public JitLargePrimitiveKeyFuncs<double> { static bool Equals(double x, double y) { return *(__int64*)&x == *(__int64*)&y; } }; typedef VNMap<double, LargePrimitiveKeyFuncsDouble> DoubleToValueNumMap; DoubleToValueNumMap* m_doubleCnsMap; DoubleToValueNumMap* GetDoubleCnsMap() { if (m_doubleCnsMap == nullptr) { m_doubleCnsMap = new (m_alloc) DoubleToValueNumMap(m_alloc); } return m_doubleCnsMap; } typedef VNMap<size_t> ByrefToValueNumMap; ByrefToValueNumMap* m_byrefCnsMap; ByrefToValueNumMap* GetByrefCnsMap() { if (m_byrefCnsMap == nullptr) { m_byrefCnsMap = new (m_alloc) ByrefToValueNumMap(m_alloc); } return m_byrefCnsMap; } #if defined(FEATURE_SIMD) struct Simd8PrimitiveKeyFuncs : public JitKeyFuncsDefEquals<simd8_t> { static bool Equals(simd8_t x, simd8_t y) { return x == y; } static unsigned GetHashCode(const simd8_t val) { unsigned hash = 0; hash = static_cast<unsigned>(hash ^ val.u32[0]); hash = static_cast<unsigned>(hash ^ val.u32[1]); return hash; } }; typedef VNMap<simd8_t, Simd8PrimitiveKeyFuncs> Simd8ToValueNumMap; Simd8ToValueNumMap* m_simd8CnsMap; Simd8ToValueNumMap* GetSimd8CnsMap() { if (m_simd8CnsMap == nullptr) { m_simd8CnsMap = new (m_alloc) Simd8ToValueNumMap(m_alloc); } return m_simd8CnsMap; } struct Simd12PrimitiveKeyFuncs : public JitKeyFuncsDefEquals<simd12_t> { static bool Equals(simd12_t x, simd12_t y) { return x == y; } static unsigned GetHashCode(const simd12_t val) { unsigned hash = 0; hash = static_cast<unsigned>(hash ^ val.u32[0]); hash = static_cast<unsigned>(hash ^ val.u32[1]); hash = static_cast<unsigned>(hash ^ val.u32[2]); return hash; } }; typedef VNMap<simd12_t, Simd12PrimitiveKeyFuncs> Simd12ToValueNumMap; Simd12ToValueNumMap* m_simd12CnsMap; Simd12ToValueNumMap* GetSimd12CnsMap() { if (m_simd12CnsMap == nullptr) { m_simd12CnsMap = new (m_alloc) Simd12ToValueNumMap(m_alloc); } return m_simd12CnsMap; } struct Simd16PrimitiveKeyFuncs : public JitKeyFuncsDefEquals<simd16_t> { static bool Equals(simd16_t x, simd16_t y) { return x == y; } static unsigned GetHashCode(const simd16_t val) { unsigned hash = 0; hash = static_cast<unsigned>(hash ^ val.u32[0]); hash = static_cast<unsigned>(hash ^ val.u32[1]); hash = static_cast<unsigned>(hash ^ val.u32[2]); hash = static_cast<unsigned>(hash ^ val.u32[3]); return hash; } }; typedef VNMap<simd16_t, Simd16PrimitiveKeyFuncs> Simd16ToValueNumMap; Simd16ToValueNumMap* m_simd16CnsMap; Simd16ToValueNumMap* GetSimd16CnsMap() { if (m_simd16CnsMap == nullptr) { m_simd16CnsMap = new (m_alloc) Simd16ToValueNumMap(m_alloc); } return m_simd16CnsMap; } #if defined(TARGET_XARCH) struct Simd32PrimitiveKeyFuncs : public JitKeyFuncsDefEquals<simd32_t> { static bool Equals(simd32_t x, simd32_t y) { return x == y; } static unsigned GetHashCode(const simd32_t val) { unsigned hash = 0; hash = static_cast<unsigned>(hash ^ val.u32[0]); hash = static_cast<unsigned>(hash ^ val.u32[1]); hash = static_cast<unsigned>(hash ^ val.u32[2]); hash = static_cast<unsigned>(hash ^ val.u32[3]); hash = static_cast<unsigned>(hash ^ val.u32[4]); hash = static_cast<unsigned>(hash ^ val.u32[5]); hash = static_cast<unsigned>(hash ^ val.u32[6]); hash = static_cast<unsigned>(hash ^ val.u32[7]); return hash; } }; typedef VNMap<simd32_t, Simd32PrimitiveKeyFuncs> Simd32ToValueNumMap; Simd32ToValueNumMap* m_simd32CnsMap; Simd32ToValueNumMap* GetSimd32CnsMap() { if (m_simd32CnsMap == nullptr) { m_simd32CnsMap = new (m_alloc) Simd32ToValueNumMap(m_alloc); } return m_simd32CnsMap; } struct Simd64PrimitiveKeyFuncs : public JitKeyFuncsDefEquals<simd64_t> { static bool Equals(simd64_t x, simd64_t y) { return x == y; } static unsigned GetHashCode(const simd64_t val) { unsigned hash = 0; hash = static_cast<unsigned>(hash ^ val.u32[0]); hash = static_cast<unsigned>(hash ^ val.u32[1]); hash = static_cast<unsigned>(hash ^ val.u32[2]); hash = static_cast<unsigned>(hash ^ val.u32[3]); hash = static_cast<unsigned>(hash ^ val.u32[4]); hash = static_cast<unsigned>(hash ^ val.u32[5]); hash = static_cast<unsigned>(hash ^ val.u32[6]); hash = static_cast<unsigned>(hash ^ val.u32[7]); hash = static_cast<unsigned>(hash ^ val.u32[8]); hash = static_cast<unsigned>(hash ^ val.u32[9]); hash = static_cast<unsigned>(hash ^ val.u32[10]); hash = static_cast<unsigned>(hash ^ val.u32[11]); hash = static_cast<unsigned>(hash ^ val.u32[12]); hash = static_cast<unsigned>(hash ^ val.u32[13]); hash = static_cast<unsigned>(hash ^ val.u32[14]); hash = static_cast<unsigned>(hash ^ val.u32[15]); return hash; } }; typedef VNMap<simd64_t, Simd64PrimitiveKeyFuncs> Simd64ToValueNumMap; Simd64ToValueNumMap* m_simd64CnsMap; Simd64ToValueNumMap* GetSimd64CnsMap() { if (m_simd64CnsMap == nullptr) { m_simd64CnsMap = new (m_alloc) Simd64ToValueNumMap(m_alloc); } return m_simd64CnsMap; } #endif // TARGET_XARCH #endif // FEATURE_SIMD template <size_t NumArgs> struct VNDefFuncAppKeyFuncs : public JitKeyFuncsDefEquals<VNDefFuncApp<NumArgs>> { static unsigned GetHashCode(const VNDefFuncApp<NumArgs>& val) { unsigned hashCode = val.m_func; for (size_t i = 0; i < NumArgs; i++) { hashCode = (hashCode << 8) | (hashCode >> 24); hashCode ^= val.m_args[i]; } return hashCode; } }; typedef VNMap<VNFunc> VNFunc0ToValueNumMap; VNFunc0ToValueNumMap* m_VNFunc0Map; VNFunc0ToValueNumMap* GetVNFunc0Map() { if (m_VNFunc0Map == nullptr) { m_VNFunc0Map = new (m_alloc) VNFunc0ToValueNumMap(m_alloc); } return m_VNFunc0Map; } typedef VNMap<VNDefFuncApp<1>, VNDefFuncAppKeyFuncs<1>> VNFunc1ToValueNumMap; VNFunc1ToValueNumMap* m_VNFunc1Map; VNFunc1ToValueNumMap* GetVNFunc1Map() { if (m_VNFunc1Map == nullptr) { m_VNFunc1Map = new (m_alloc) VNFunc1ToValueNumMap(m_alloc); } return m_VNFunc1Map; } typedef VNMap<VNDefFuncApp<2>, VNDefFuncAppKeyFuncs<2>> VNFunc2ToValueNumMap; VNFunc2ToValueNumMap* m_VNFunc2Map; VNFunc2ToValueNumMap* GetVNFunc2Map() { if (m_VNFunc2Map == nullptr) { m_VNFunc2Map = new (m_alloc) VNFunc2ToValueNumMap(m_alloc); } return m_VNFunc2Map; } typedef VNMap<VNDefFuncApp<3>, VNDefFuncAppKeyFuncs<3>> VNFunc3ToValueNumMap; VNFunc3ToValueNumMap* m_VNFunc3Map; VNFunc3ToValueNumMap* GetVNFunc3Map() { if (m_VNFunc3Map == nullptr) { m_VNFunc3Map = new (m_alloc) VNFunc3ToValueNumMap(m_alloc); } return m_VNFunc3Map; } typedef VNMap<VNDefFuncApp<4>, VNDefFuncAppKeyFuncs<4>> VNFunc4ToValueNumMap; VNFunc4ToValueNumMap* m_VNFunc4Map; VNFunc4ToValueNumMap* GetVNFunc4Map() { if (m_VNFunc4Map == nullptr) { m_VNFunc4Map = new (m_alloc) VNFunc4ToValueNumMap(m_alloc); } return m_VNFunc4Map; } class MapSelectWorkCacheEntry { union { ValueNum* m_memoryDependencies; ValueNum m_inlineMemoryDependencies[sizeof(ValueNum*) / sizeof(ValueNum)]; }; unsigned m_numMemoryDependencies = 0; public: ValueNum Result; void SetMemoryDependencies(CompAllocator alloc, ArrayStack<ValueNum>& deps, unsigned startIndex); void GetMemoryDependencies(ArrayStack<ValueNum>& deps); }; typedef JitHashTable<VNDefFuncApp<2>, VNDefFuncAppKeyFuncs<2>, MapSelectWorkCacheEntry> MapSelectWorkCache; MapSelectWorkCache* m_mapSelectWorkCache = nullptr; MapSelectWorkCache* GetMapSelectWorkCache() { if (m_mapSelectWorkCache == nullptr) { m_mapSelectWorkCache = new (m_alloc) MapSelectWorkCache(m_alloc); } return m_mapSelectWorkCache; } // We reserve Chunk 0 for "special" VNs. enum SpecialRefConsts { SRC_Null, SRC_Void, SRC_EmptyExcSet, SRC_NumSpecialRefConsts }; // The "values" of special ref consts will be all be "null" -- their differing meanings will // be carried by the distinct value numbers. static class Object* s_specialRefConsts[SRC_NumSpecialRefConsts]; static class Object* s_nullConst; #ifdef DEBUG // This helps test some performance pathologies related to "evaluation" of VNF_MapSelect terms, // especially relating to GcHeap/ByrefExposed. We count the number of applications of such terms we consider, // and if this exceeds a limit, indicated by a DOTNET_ variable, we assert. unsigned m_numMapSels; #endif }; template <> struct ValueNumStore::VarTypConv<TYP_INT> { typedef INT32 Type; typedef int Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_FLOAT> { typedef INT32 Type; typedef float Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_LONG> { typedef INT64 Type; typedef INT64 Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_DOUBLE> { typedef INT64 Type; typedef double Lang; }; #if defined(FEATURE_SIMD) template <> struct ValueNumStore::VarTypConv<TYP_SIMD8> { typedef simd8_t Type; typedef simd8_t Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_SIMD12> { typedef simd12_t Type; typedef simd12_t Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_SIMD16> { typedef simd16_t Type; typedef simd16_t Lang; }; #if defined(TARGET_XARCH) template <> struct ValueNumStore::VarTypConv<TYP_SIMD32> { typedef simd32_t Type; typedef simd32_t Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_SIMD64> { typedef simd64_t Type; typedef simd64_t Lang; }; #endif // TARGET_XARCH #endif // FEATURE_SIMD template <> struct ValueNumStore::VarTypConv<TYP_BYREF> { typedef size_t Type; typedef void* Lang; }; template <> struct ValueNumStore::VarTypConv<TYP_REF> { typedef class Object* Type; typedef class Object* Lang; }; // Get the actual value and coerce the actual type c->m_typ to the wanted type T. template <typename T> FORCEINLINE T ValueNumStore::SafeGetConstantValue(Chunk* c, unsigned offset) { switch (c->m_typ) { case TYP_REF: return CoerceTypRefToT<T>(c, offset); case TYP_BYREF: return static_cast<T>(reinterpret_cast<VarTypConv<TYP_BYREF>::Type*>(c->m_defs)[offset]); case TYP_INT: return static_cast<T>(reinterpret_cast<VarTypConv<TYP_INT>::Type*>(c->m_defs)[offset]); case TYP_LONG: return static_cast<T>(reinterpret_cast<VarTypConv<TYP_LONG>::Type*>(c->m_defs)[offset]); case TYP_FLOAT: return static_cast<T>(reinterpret_cast<VarTypConv<TYP_FLOAT>::Lang*>(c->m_defs)[offset]); case TYP_DOUBLE: return static_cast<T>(reinterpret_cast<VarTypConv<TYP_DOUBLE>::Lang*>(c->m_defs)[offset]); default: assert(false); return (T)0; } } #if defined(FEATURE_SIMD) template <> FORCEINLINE simd8_t ValueNumStore::SafeGetConstantValue<simd8_t>(Chunk* c, unsigned offset) { assert(c->m_typ == TYP_SIMD8); return reinterpret_cast<VarTypConv<TYP_SIMD8>::Lang*>(c->m_defs)[offset]; } template <> FORCEINLINE simd12_t ValueNumStore::SafeGetConstantValue<simd12_t>(Chunk* c, unsigned offset) { assert(c->m_typ == TYP_SIMD12); return reinterpret_cast<VarTypConv<TYP_SIMD12>::Lang*>(c->m_defs)[offset]; } template <> FORCEINLINE simd16_t ValueNumStore::SafeGetConstantValue<simd16_t>(Chunk* c, unsigned offset) { assert(c->m_typ == TYP_SIMD16); return reinterpret_cast<VarTypConv<TYP_SIMD16>::Lang*>(c->m_defs)[offset]; } #if defined(TARGET_XARCH) template <> FORCEINLINE simd32_t ValueNumStore::SafeGetConstantValue<simd32_t>(Chunk* c, unsigned offset) { assert(c->m_typ == TYP_SIMD32); return reinterpret_cast<VarTypConv<TYP_SIMD32>::Lang*>(c->m_defs)[offset]; } template <> FORCEINLINE simd64_t ValueNumStore::SafeGetConstantValue<simd64_t>(Chunk* c, unsigned offset) { assert(c->m_typ == TYP_SIMD64); return reinterpret_cast<VarTypConv<TYP_SIMD64>::Lang*>(c->m_defs)[offset]; } #endif // TARGET_XARCH template <> FORCEINLINE simd8_t ValueNumStore::ConstantValueInternal<simd8_t>(ValueNum vn DEBUGARG(bool coerce)) { Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn)); assert(c->m_attribs == CEA_Const); unsigned offset = ChunkOffset(vn); assert(c->m_typ == TYP_SIMD8); assert(!coerce); return SafeGetConstantValue<simd8_t>(c, offset); } template <> FORCEINLINE simd12_t ValueNumStore::ConstantValueInternal<simd12_t>(ValueNum vn DEBUGARG(bool coerce)) { Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn)); assert(c->m_attribs == CEA_Const); unsigned offset = ChunkOffset(vn); assert(c->m_typ == TYP_SIMD12); assert(!coerce); return SafeGetConstantValue<simd12_t>(c, offset); } template <> FORCEINLINE simd16_t ValueNumStore::ConstantValueInternal<simd16_t>(ValueNum vn DEBUGARG(bool coerce)) { Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn)); assert(c->m_attribs == CEA_Const); unsigned offset = ChunkOffset(vn); assert(c->m_typ == TYP_SIMD16); assert(!coerce); return SafeGetConstantValue<simd16_t>(c, offset); } #if defined(TARGET_XARCH) template <> FORCEINLINE simd32_t ValueNumStore::ConstantValueInternal<simd32_t>(ValueNum vn DEBUGARG(bool coerce)) { Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn)); assert(c->m_attribs == CEA_Const); unsigned offset = ChunkOffset(vn); assert(c->m_typ == TYP_SIMD32); assert(!coerce); return SafeGetConstantValue<simd32_t>(c, offset); } template <> FORCEINLINE simd64_t ValueNumStore::ConstantValueInternal<simd64_t>(ValueNum vn DEBUGARG(bool coerce)) { Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn)); assert(c->m_attribs == CEA_Const); unsigned offset = ChunkOffset(vn); assert(c->m_typ == TYP_SIMD64); assert(!coerce); return SafeGetConstantValue<simd64_t>(c, offset); } #endif // TARGET_XARCH #endif // FEATURE_SIMD // Inline functions. // static inline bool ValueNumStore::GenTreeOpIsLegalVNFunc(genTreeOps gtOper) { return (s_vnfOpAttribs[gtOper] & VNFOA_IllegalGenTreeOp) == 0; } // static inline bool ValueNumStore::VNFuncIsCommutative(VNFunc vnf) { return (s_vnfOpAttribs[vnf] & VNFOA_Commutative) != 0; } inline bool ValueNumStore::VNFuncIsComparison(VNFunc vnf) { if (vnf >= VNF_Boundary) { // For integer types we have unsigned comparisons, and // for floating point types these are the unordered variants. // return ((vnf == VNF_LT_UN) || (vnf == VNF_LE_UN) || (vnf == VNF_GE_UN) || (vnf == VNF_GT_UN)); } genTreeOps gtOp = genTreeOps(vnf); return GenTree::OperIsCompare(gtOp) != 0; } template <> inline size_t ValueNumStore::CoerceTypRefToT(Chunk* c, unsigned offset) { return reinterpret_cast<size_t>(reinterpret_cast<VarTypConv<TYP_REF>::Type*>(c->m_defs)[offset]); } template <typename T> inline T ValueNumStore::CoerceTypRefToT(Chunk* c, unsigned offset) { noway_assert(sizeof(T) >= sizeof(VarTypConv<TYP_REF>::Type)); unreached(); } /*****************************************************************************/ #endif // _VALUENUM_H_ /*****************************************************************************/
true
d24a99c9335869481cc874e2d9c2247e8464a95d
C++
Thiag0Andres/Roteiro-3---Laboratorio-LP1
/Questão 1/mainHospital.cpp
ISO-8859-1
1,661
3.171875
3
[]
no_license
/* Thiago Andres Paiva Palacios Questao 1 */ /* O que polimorfismo? Polimorfismo em linguagens orientadas a objeto, a capacidade de objetos se comportarem de forma diferenciada em face de suas caractersticas ou do ambiente ao qual estejam submetidos, mesmo quando executando ao que detenha, semanticamente, a mesma designao. O polimorfismo em C++ se apresenta sob diversas formas diferentes, desde as mais simples, como funes com mesmo nome e lista de parmetros diferentes, at as mais complexas como funes virtuais, cujas formas de execuo so dependentes da classe a qual o objeto pertence e so identificadas em tempo de execuo. */ #include "Medico.h" #include "Cirurgiao.h" #include "Ginecologista.h" #include "Oftamologista.h" #include "Otorrino.h" int main(void) { Medico * m1 = new Oftamologista("Andre", 1.82, 85); Medico * m2 = new Cirurgiao("Tayna", 1.79, 87); Medico * m3 = new Otorrino("Thiago", 1.67, 78); Medico * m4 = new Ginecologista("Pablo", 1.76, 68); cout << m1->getNome() << endl << m1->getAltura() << endl << m1->getPeso() << endl << m1->getEspecializacao() << endl; m1->realizarOperacao(); cout << endl; cout << m2->getNome() << endl << m2->getAltura() << endl << m2->getPeso() << endl << m2->getEspecializacao() << endl; m2->realizarOperacao(); cout << endl; cout << m3->getNome() << endl << m3->getAltura() << endl << m3->getPeso() << endl << m3->getEspecializacao() << endl; m3->realizarOperacao(); cout << endl; cout << m4->getNome() << endl << m4->getAltura() << endl << m4->getPeso() << endl << m4->getEspecializacao() << endl; m4->realizarOperacao(); }
true
7c12ea657bdb96591073cb415d3ba57a6874620f
C++
walnutgallery/DataStructures
/prog03/Prog03/algorithm.h
UTF-8
10,634
3.625
4
[]
no_license
//////////////////////////////////////////////////////////////////////////////// /// @brief Algorithms, e.g., sorting /// @ingroup MySTL /// @todo Implement swap /// @todo Implement bubble sort /// @todo Implement one of: /// - Insertion Sort (in place) /// - Selection Sort (in place) /// @todo Implement one of: /// - Heap Sort (in place) /// - Merge Sort /// - Quick Sort (in place) /// @bonus Each extra sort you implement will be worth bonus points //////////////////////////////////////////////////////////////////////////////// #ifndef _ALGORITHM_H_ #define _ALGORITHM_H_ #include <limits> #include <vector> #include <iostream> namespace mystl { //////////////////////////////////////////////////////////////////////////////// /// @brief Swap values of two elements /// @tparam T Value type /// @param a First value /// @param b Second value template<typename T> void swap(T& a, T& b) { /// @todo Implement swapping values T temp=b; b=a; a=temp; } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Bubble Sort template<class RandomAccessIterator, class Compare> void bubble_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { /// @todo Implement Bubble sort size_t n=last-first; for(size_t i=0; i<n;i++){ for(RandomAccessIterator j=first, k=first+1; k!=last; ++j, ++k){ size_t indx=j-first; RandomAccessIterator r=first+indx; if(comp(*k, *r)) swap(*k,*j); } } } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Selection Sort. template<class RandomAccessIterator, class Compare> void selection_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { for (RandomAccessIterator j = first; j!=last-1 ; j++) { RandomAccessIterator min=j; for (RandomAccessIterator i = j+1; i != last ; i++) { if(comp(*i,*min)) min=i; } if(*min!=*j) swap(*j,*min); } } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Insertion Sort template<class RandomAccessIterator, class Compare> void insertion_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { for(RandomAccessIterator i=first+1; i!=last; i++){ RandomAccessIterator j = i; while(j>first && comp(*(j),*(j-1))){ swap(*(j-1),*j); j--; } /* std::cout<<"______________"<<std::endl; for(RandomAccessIterator a=first; a < last; a++) std::cout<<*a<<std::endl; */ } } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Slow sort sorts in a non-optimal fashion. Select and implement one of: /// -(a) insertion sort /// -(b) selection sort /// Your sort should be inplace (uses no extra memory). template<class RandomAccessIterator, class Compare> void slow_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { /// @todo Call your slow sort of choice selection_sort(first,last,comp); //insertion_sort(first,last,comp); } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Heap Sort. template<class RandomAccessIterator, class Compare> void heap_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Merge Sort. /* template<class RandomAccessIterator, class Compare> void merge_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { if(last-first<=1) return; RandomAccessIterator mid = (last-first)/2; merge_sort(first,mid,comp); merge_sort(mid,last,comp); merge(first,mid,last,comp); } */ //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Quick Sort. template<class RandomAccessIterator, class Compare> void quick_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { int distance = last - first; if(distance<=0) return; typename RandomAccessIterator::value_type pivot = *(first + distance/2); if (distance != 0) std::swap(*(first + distance/2), *first); int i = 1; for (int j = 1; j < distance; j++){ if ( comp(*(first + j), pivot) ){ swap( *(first+j), *(first+i)); i++; } } swap(*first, *(first + i - 1)); quick_sort(first, first+i-1,comp); quick_sort(first+i, last,comp); } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) into nondecreasing order /// @tparam RandomAccessIterator Random Access Iterator /// @tparam Compare Comparator function /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// @param comp Binary function that accepts two elements in the range as /// arguments and returns a value convertable to bool. The value /// returned indicates whether the element passed as first argument /// is considered to go before the second in the ordering it /// defines. /// /// Sort sorts in an optimal fashion. Select and implement one of: /// -(a) heap sort (in place) /// -(b) merge sort /// -(c) quick sort (in place) template<class RandomAccessIterator, class Compare> void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) { /// @todo Call your fast sort of choice quick_sort(first,last,comp); } //////////////////////////////////////////////////////////////////////////////// /// @brief Sort the range [first, last) of integral types into nondecreading /// order /// @tparam RandomAccessIterator Random Access Iterator /// @param first Initial position of sequence to be sorted /// @param last Final position of sequence to be sorted /// /// Sorts with Radix sort. Should do radix on decimal representation of integer /// type, i.e., number of buckets is always 10. /// typename RandomAccessIterator::value_type is required to be some integral /// type, i.e., char, short, int, long, etc. template<class RandomAccessIterator> void radix_sort(RandomAccessIterator first, RandomAccessIterator last) { /// @bonus Implement radix_sort } } #endif
true
16740b127d8f5ce515a53d99b5757bdc074bcdea
C++
pulcherriman/Programming_Contest
/AtCoder/ABC/000-099/ABC062/arc074_a.cpp
UTF-8
474
2.578125
3
[]
no_license
#include <iostream> using namespace std; #define ll long long ll min(ll a,ll b){return a<b?a:b;} ll max(ll a,ll b){return a>b?a:b;} ll sep(int a, int b){ ll pre=1<<30,a1,a2; for(ll i=1;i<a;i++){ a1=max(llabs(b*i-b*((a-i)/2)),llabs(b*i-b*(a-i-(a-i)/2))); a2=max(llabs(b*i-(a-i)*(b/2)),llabs(b*i-(a-i)*(b-b/2))); pre=min(pre,min(a1,a2)); } return pre; } int main(void){ ll h,w; cin>>h>>w; cout<<min(sep(h,w),sep(w,h)); }
true
2f41e3616b9cb3bc5fa3a3c543226a04f4c29e24
C++
bright-dusty/lintcode-
/Remove Node in Binary Search Tree/test.cpp
UTF-8
3,421
3.0625
3
[]
no_license
#include <stdexcept> #include <string> #include <iostream> #include <dlfcn.h> using namespace std; typedef void (*MessageBoxA) (int, const char *, const char *, int); class TreeNode { public: int val; TreeNode *left, *right; TreeNode(int val) { this->val = val; this->left = this->right = NULL; } }; class Solution { public: static const int WHATEVER = -1; static string serialize(TreeNode *); static TreeNode * deserialize(string &); static void destroy (TreeNode *); /* * @param root: The root of the binary search tree. * @param value: destroy the node with given value. * @return: The root of the binary search tree after removal. */ static TreeNode * destroyNode(TreeNode * root, int value) { // write your code here if (!root) return nullptr; TreeNode *cur = root; enum Child { Left, Right }; typedef pair<TreeNode *, Child> pairType; TreeNode virtual_node = TreeNode(WHATEVER); virtual_node.left = root; pairType parent = pairType(&virtual_node, Left); while (cur) { if (cur->val == value) { #define do_remove(rep) /* remove cur */ { \ if (parent.second == Left) \ parent.first->left = rep; \ else parent.first->right = rep; \ delete cur; \ } if (cur->left && cur->right) { TreeNode *biggestInLeft = cur->left, *parentOfBiggest = cur; while (biggestInLeft->right) { parentOfBiggest = biggestInLeft; biggestInLeft = parentOfBiggest->right; } int biggestVal = biggestInLeft->val; if (parentOfBiggest->val == biggestInLeft->val) throw runtime_error("Duplicated values"); destroyNode(parentOfBiggest, biggestInLeft->val); cur->val = biggestVal; } else if (cur->left) { do_remove(cur->left); } else if (cur->right) { do_remove(cur->right); } else { do_remove(nullptr); } break; #undef do_remove } else if (cur->val < value) { parent = pairType(cur, Right); cur = cur->right; } else { parent = pairType(cur, Left); cur = cur->left; } } return virtual_node.left; } }; int main () { string line; int removal; getline(cin, line); cin >> removal; cin.get(); TreeNode *root = Solution::deserialize(line); try { root = Solution::destroyNode(root, removal); } catch (runtime_error err) { static void *hdl = dlopen("/cygdrive/c/Windows/System32/user32.dll", RTLD_LAZY); if (hdl) ((MessageBoxA)dlsym(hdl, "MessageBoxA"))(0, err.what(), "Error", 0x10); cout << "Err: " << err.what() << endl; } cout << Solution::serialize(root) << endl; Solution::destroy(root); cin.get(); }
true
12ffb5112f074f6f21431bad6b5bf2835dd5176b
C++
Siddharth-Babbar/Pepcoding
/PepcodingSept_19/Lec_059/Questions.cpp
UTF-8
3,561
3.75
4
[]
no_license
#include<iostream> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; //leetcode 141=================================================== bool hasCycle(ListNode* head) { if(head == nullptr || head->next == nullptr) { return false; } ListNode* slow=head; ListNode* fast=head; while(fast!=nullptr && fast->next!=nullptr) { slow=slow->next; fast=fast->next->next; if(slow == fast) { break; } } return slow == fast; } //leetcode 142 ListNode* detectCycle(ListNode* head) { if(head == nullptr || head->next == nullptr) { return nullptr; } ListNode* slow=head; ListNode* fast=head; while(fast!=nullptr && fast->next!=nullptr) { slow=slow->next; fast=fast->next->next; if(slow == fast) { break; } } if(slow == fast) { slow=head; while(slow !=fast) { slow=slow->next; fast=fast->next; } return slow; } return nullptr; } //leetcode 160================================================= ListNode* getIntersectionNode(ListNode* headA,ListNode* headB) { if(headA == nullptr || headB == nullptr) { return nullptr; } if(headA->next == nullptr && headB->next == nullptr && headA->val == headB->val) { return headA; } ListNode* tail=nullptr; ListNode* curr=headA; while(curr!=nullptr) { tail=curr; curr=curr->next; } tail->next=headB; ListNode* slow=headA; ListNode* fast=headA; while(fast != nullptr && fast->next != nullptr) { slow=slow->next; fast=fast->next->next; if(slow == fast) { break; } } if(slow == fast) { slow=headA; while(slow != fast) { slow=slow->next; fast=fast->next; } tail->next=nullptr; return slow; } tail->next=nullptr; return nullptr; } // leetcode 21======================================================= ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == nullptr) { return l2; } if(l2 == nullptr) { return l1; } ListNode* head=new ListNode(-1); ListNode* curr=head; while(l1 != nullptr && l2 != nullptr) { if(l1->val <= l2->val) { curr->next=l1; l1=l1->next; } else { curr->next=l2; l2=l2->next; } curr=curr->next; } if(l1 != nullptr) { curr->next=l1; } else { curr->next=l2; } return head->next; } // leetcode 148 ListNode* middleNodeByIndex(ListNode* head) { ListNode* slow=head; ListNode* fast=head; while(fast!=nullptr && fast->next!=nullptr && fast->next->next!=nullptr) { slow=slow->next; fast=fast->next->next; if(slow == fast) { break; } } return slow; } ListNode* sortList(ListNode* head) { if(head == nullptr || head->next == nullptr) { return head; } ListNode* mid=middleNodeByIndex(head); ListNode* nhead=mid->next; mid->next=nullptr; ListNode* a = sortList(head); ListNode* b = sortList(nhead); return mergeTwoLists(a,b); }
true
5532c4dd222586de535a7ce8db7e3e72aaaee38b
C++
ahfergus1/Intrinsi
/IntrinsiForceDemo/DrawManager.cpp
UTF-8
3,341
2.765625
3
[]
no_license
/* DrawManager.cpp * Draws menu pages and data to screen for the IntrinsiForce prototype. * @author Andrew Simpson, ahfergus1@gmail.com */ #include "DrawManager.h" //#include "LCD.h" #include "DrawUtils.h" DrawManager::DrawManager() { // Draw BOOT page first this->page = BOOT; this->subPage = 0; this->extra = ""; // Drawer does not need to be initialized // Can't draw yet in case SPI isn't initialized } DrawManager::~DrawManager() { } void DrawManager::begin() { drawer.init(); _drawPage(BLACK); // drawPage(MAIN); } Page DrawManager::getPage() { return this->page; } void DrawManager::drawPage(Page page) { // Use other one drawPage(page, 0, ""); } void DrawManager::drawPage(Page page, int subPage) { drawPage(page, subPage, ""); } void DrawManager::drawPage(Page page, const char* extra) { drawPage(page, 0, String(extra)); } void DrawManager::drawPage(Page page, String extra) { // Use more complicated version drawPage(page, 0, extra); } void DrawManager::drawPage(Page page, int subPage, String extra) { // Erase old page if needed if (this->page != page) { // Erase old page _drawPage(WHITE); this->page = page; this->subPage = subPage; this->extra = extra; _drawPage(BLACK); } else if (this->subPage != subPage) { // Update subpage _drawSubPage(WHITE); this->subPage = subPage; this->extra = extra; _drawSubPage(BLACK); } else { // Only update extra updateExtra(extra); } } void DrawManager::drawPage(Page page, int subPage, const char* extra) { drawPage(page, subPage, String(extra)); } void DrawManager::updateExtra(String extra) { if (this->extra.compareTo(extra) != 0) { _drawExtra(WHITE); this->extra = extra; _drawExtra(BLACK); } } void DrawManager::updateExtra(const char *extra) { updateExtra(String(extra)); } void DrawManager::_drawPage(uint16_t colour) { switch (page) { case BOOT: if (colour == BLACK) DrawUtils::drawScreen("Logo.bmp"); else DrawUtils::drawScreen("Back.bmp"); break; case MAIN: drawer.menu(colour); break; case SESSION: drawer.pinchPrompt(colour); break; case HISTORY: // TODO: Implement break; case MEAS: drawer.measurePrompt(colour); break; case CALIBRATION: // TODO: Implement break; case UPLOAD: if (colour == BLACK) { // Draw Bluetooth symbol DrawUtils::drawScreen("BSend.bmp"); // Write text second drawer.uploadPrompt(colour); } else { // Erase Bluetooth symbol DrawUtils::drawScreen("ClrSend.bmp"); // Probably not needed drawer.uploadPrompt(colour); } break; default: // Do nothing break; } _drawSubPage(colour); } void DrawManager::_drawSubPage(uint16_t colour) { switch (page) { case SESSION: drawer.pinchArea(subPage, colour); break; default: // Do nothing break; } _drawExtra(colour); } void DrawManager::_drawExtra(uint16_t colour) { switch (page) { case SESSION: drawer.sessionReading(extra, colour); break; case MEAS: drawer.sessionReading(extra, colour); default: // Do nothing break; } } // void DrawManager::erasePage(uint16_t colour) // { // _drawPage(colour); // _drawSubPage(colour); // _drawExtra(colour); // }
true
489bbda23014b3101a34abff45ec707779422a92
C++
Luni-4/CameraController
/src/communication/MessageDecoder.cpp
UTF-8
2,659
3.046875
3
[]
no_license
/* * Created on: Jul 24, 2018 * Author: Luca Erbetta */ #include "MessageDecoder.h" #include "logger.h" #include <algorithm> using std::max; using std::min; MessageDecoder::MessageDecoder(MessageHandler& msgHandler) : handler(msgHandler) { } MessageDecoder::~MessageDecoder() { if (message != nullptr) { delete message; } } void MessageDecoder::dispatch() { handler.handleMessage(*message); } void MessageDecoder::decode(uint8_t* data, size_t len) { for (size_t i = 0; i < len; i++) { switch (state) { case DecoderState::START: if (data[i] == MAGIC_WORD_1) { state = DecoderState::MAGIC1_FOUND; } break; case DecoderState::MAGIC1_FOUND: if (data[i] == MAGIC_WORD_2) { state = DecoderState::MAGIC2_FOUND; } else { state = DecoderState::START; } break; case DecoderState::MAGIC2_FOUND: temp_type = data[i]; state = DecoderState::TYPE_RECEIVED; break; case DecoderState::TYPE_RECEIVED: { temp_size1 = data[i]; state = DecoderState::SIZE1_RECEIVED; break; } case DecoderState::SIZE1_RECEIVED: { uint16_t size = data[i] << 8 | (uint16_t)temp_size1; state = DecoderState::RECEIVING_DATA; if (message != nullptr) { delete message; } message = new Message(temp_type, size); received_data = 0; state = DecoderState::RECEIVING_DATA; Log.d("Message created: type:%d, size:%d", temp_type, size); break; } case DecoderState::RECEIVING_DATA: { size_t sz = min(len - i, (size_t)message->size - received_data); memcpy(message->data + received_data, data + i, sz); received_data += sz; i += sz - 1; // i must point to the last copied byte Log.d("Receive data: received: %d, sz: %d", received_data, sz); if (received_data == message->size) { Log.d("Dispatch."); dispatch(); state = DecoderState::START; } break; } } } }
true
5daab4f85cface54ec4f3ce8e2f6c0f05e4b48c7
C++
MichelleZ/leetcode
/algorithms/cpp/checkifBinaryStringHasatMostOneSegmentofOnes/checkifBinaryStringHasatMostOneSegmentofOnes.cpp
UTF-8
441
3.125
3
[]
no_license
// Source: https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/ // Author: Miao Zhang // Date: 2021-06-08 class Solution { public: bool checkOnesSegment(string s) { int cnt = 0; int ones = 0; for (char c: s) { if (c == '1') { cnt += (++ones == 1); } else { ones = 0; } } return cnt == 1; } };
true
83b02761abb01aca4cca81ed6c7301056c63e116
C++
projectescape/cp-archive
/LC/house-robber.cpp
UTF-8
451
2.640625
3
[]
no_license
int calcAns(vector<int>& nums, vector<int>& dp, int index) { if (index >= nums.size()) return 0; if (dp[index] != -1) return dp[index]; dp[index] = max(nums[index] + calcAns(nums, dp, index + 2), calcAns(nums, dp, index + 1)); return dp[index]; } class Solution { public: int rob(vector<int>& nums) { if (nums.size() == 0) return 0; vector<int> dp(nums.size(), -1); return calcAns(nums, dp, 0); } };
true
e13806199a0bf9b80362efdc8cb17ac1f3e0a1c0
C++
buckeye-cn/ACM_ICPC_Materials
/solutions/kattis/ecna20/mathtrade_hcz.cpp
UTF-8
1,167
2.875
3
[]
no_license
// https://open.kattis.com/problems/mathtrade #include <cstdlib> #include <cstdint> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <unordered_map> #include <iostream> using namespace std; string to_str[100]; int to[100]; int depth[100]; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.precision(10); int n; cin >> n; unordered_map<string, int> m; for (int i = 0; i < n; ++i) { string s1, s2; cin >> s1 >> s2 >> to_str[i]; m[s2] = i; m.insert({to_str[i], -1}); } for (int i = 0; i < n; ++i) { to[i] = m[to_str[i]]; } int best = 0; for (int i = 0; i < n; ++i) { if (!depth[i]) { int step = 1; for (int j = i; j >= 0; j = to[j]) { if (depth[j]) { best = max(best, step - depth[j]); break; } depth[j] = step; step += 1; } } } if (best) { cout << best << endl; } else { cout << "No trades possible" << endl; } return 0; }
true
b0b69a20f8212eb1c5c4c0762f0fad12ede09a5a
C++
rohitdureja/Smart-Sensing
/temp/example_thread.cpp
UTF-8
258
2.859375
3
[]
no_license
// Thread Basics #include <thread> #include <iostream> #include "classes.h" using namespace std; int main(int argc, char const *argv[]) { super_class sup1(1,2,3,4); cout << "Printing values of super_class: " << sup1.call_me() << endl;// sup1.b << endl; }
true
136f81fe047b99697f6862093eacffac1a719cae
C++
MolSSI/MIRP
/mirp_bin/cmdline.hpp
UTF-8
3,311
3.703125
4
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*! \file * * \brief Functions for parsing the command line given to a program */ #pragma once #include <string> #include <vector> namespace mirp { /*! \brief Check to see if the given command line has an argument * * \param [in] cmdline The command line to check (should be converted already) * \param [in] arg The argument to check for * \return True if \p cmdline contains the argument, false otherwise */ bool cmdline_has_arg(const std::vector<std::string> & cmdline, const std::string & arg); /*! \brief See if the command line has a switch * * \note After seeing if the switch exists, it is removed from \p cmdline * * \param [in] cmdline The command line to check (should be converted already) * \param [in] arg The argument to check for * \return True if \p cmdline contains the switch, false otherwise */ bool cmdline_get_switch(std::vector<std::string> & cmdline, const std::string & arg); /*! \brief Obtain the value of an argument from the command line * as a string * * \note After obtaining the argument, the key and value are removed from \p cmdline * * \throw std::runtime_error if the argument key or the value is not found * * \param [in] cmdline The command line to use (should be converted already) * \param [in] arg The argument key to look up * \return The value of the argument given on the command line */ std::string cmdline_get_arg_str(std::vector<std::string> & cmdline, const std::string & arg); /*! \brief Obtain the value of an argument from the command line * as a string, with a default * * If the argument key is not given on the command line, the default * parameter \p def is returned instead. * * \note After obtaining the argument, the key and value are removed from \p cmdline * \param [in] cmdline The command line to use (should be converted already) * \param [in] arg The argument key to look up * \param [in] def A default value of the argument to use if \p arg is not given on the command line * \return The value of the argument given on the command line, or the value of \p def */ std::string cmdline_get_arg_str(std::vector<std::string> & cmdline, const std::string & arg, const std::string & def); /*! \brief Obtain the value of an argument from the command line * as a long integer * * \copydetails cmdline_get_arg_str(std::vector<std::string> &, const std::string &) */ long cmdline_get_arg_long(std::vector<std::string> & cmdline, const std::string & arg); /*! \brief Obtain the value of an argument from the command line * as a long integer, with a default * * \copydetails cmdline_get_arg_str(std::vector<std::string> &, const std::string &, const std::string &) */ long cmdline_get_arg_long(std::vector<std::string> & cmdline, const std::string & arg, long def); /*! \brief Convert the command line passed to a program into a vector of strings * * After conversion, the command line is able to be used in the other `cmdline_` functions * * \param [in] argc Number of command line arguments * \param [in] argv The command line arguments * \return The command line, split into a vector of strings and lightly processed. */ std::vector<std::string> convert_cmdline(int argc, char ** argv); } // close namespace mirp
true
7b4c8ca22ae30eb9df0dddee047ba9f98ad453ff
C++
meisimo/Maratones
/UVA/10855/main.cpp
UTF-8
1,323
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void S(int N, int n){ bool match; char M[N][N], m[n][n], a; int i, j, ii, jj, count, n2; for (i = 0; i<N; i++) { for (j = 0; j<N; j++) cin >> M[i][j]; cin.ignore(1); } for ( i = 0; i < n; i++) { for (j = 0; j < n; j++) cin >> m[i][j]; cin.ignore(1); } for (int x = 0; x < 4; x++){ count = 0; for ( i = 0; i <= N - n; i++){ for (j = 0; j <= N - n; j++){ match = 1; for (ii = 0 ; ii < n; ii++) for ( jj = 0; jj < n; jj++) match &= M[ i + ii][ j + jj] == m[ii][jj]; count += match; } } cout << count << ( x == 3 ? "\n" :" "); n2 = n/2; for ( i = 0; i < n2; i++) { ii = n - i - 1; for ( j = i; j < ii; j++){ jj = n - j - 1; a = m[jj][i]; m[jj][i] = m[ii][jj]; m[ii][jj] = m[j][ii]; m[j][ii] = m[i][j]; m[i][j] = a; } } // cout << endl; // for ( i = 0; i< n; i++){ // for (j = 0; j < n; j++){ // cout << m[i][j]; // } // cout << endl; // } // cout << "================"<< endl; } } int main(){ ios::sync_with_stdio(0); cin.tie(0); int N, n; while (1){ cin >> N >> n; if (!N) break; S( N, n); } return 0; }
true
eaa8a08c99a19a376f44aa0f1365c411fadb55aa
C++
FJ98/Githubs-2019-1
/unidad-7-programacion-rreactiva-FJ98/src/Event.h
UTF-8
278
2.765625
3
[]
no_license
// Created by felix on 6/28/2019. #ifndef SRC_EVENT_H #define SRC_EVENT_H class Event{ public: int x, y; public: Event() = default; Event(int x, int y): x{x}, y{y} {} int getX() { return x; } int getY() { return y; } }; #endif //SRC_EVENT_H
true
c7802d1d70ce13b145af902d1125e74e020533f3
C++
trisyoungs/fmatch
/src/dnchar.cpp
UTF-8
10,527
2.984375
3
[]
no_license
/* *** Dynamic character array *** dnchar.cpp Copyright T. Youngs 2011 This file is part of FMatch3. FMatch3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FMatch3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FMatch3. If not, see <http://www.gnu.org/licenses/>. */ #include "constants.h" #include "dnchar.h" #include <cstring> using namespace std; #include <cstdio> #include <cstdlib> #include <cstdarg> // Constructors Dnchar::Dnchar() { // Private variables data_ = NULL; size_ = 0; endPosition_ = 0; // Public variables prev = NULL; next = NULL; } Dnchar::Dnchar(int emptysize) { // Private variables data_ = NULL; size_ = 0; endPosition_ = 0; // Public variables prev = NULL; next = NULL; createEmpty(emptysize); } Dnchar::Dnchar(const char *s) { // Private variables data_ = NULL; size_ = 0; endPosition_ = 0; // Public variables prev = NULL; next = NULL; set(s); } Dnchar::Dnchar(int dummyparameter, const char *fmt, ...) { // Private variables data_ = NULL; size_ = 0; endPosition_ = 0; // Public variables prev = NULL; next = NULL; va_list arguments; static char s[8096]; s[0] = '\0'; // Parse the argument list (...) and internally write the output string into s[] va_start(arguments,fmt); vsprintf(s,fmt,arguments); va_end(arguments); set(s); } // Copy constructor Dnchar::Dnchar(const Dnchar &source) { // Private variables data_ = NULL; size_ = 0; endPosition_ = 0; // Public variables prev = NULL; next = NULL; if (source.data_ == NULL) clear(); else set(source.data_); } // Conversion operators Dnchar::operator const char*() { return get(); } // Destructor Dnchar::~Dnchar() { if (data_ != NULL) delete[] data_; } // Print void Dnchar::info() const { std::printf("DnChar len = %i, end = %i : '%s'\n",size_,endPosition_,data_); } // Clear void Dnchar::clear() { if (data_ == NULL) return; endPosition_ = 0; data_[0] = '\0'; } // Set from C-style string void Dnchar::set(const char *s) { // If new size is less than or equal to old size, don't reallocate int newsize = (s == NULL ? 1 : strlen(s) + 1); if (newsize > size_) { if (data_ != NULL) delete[] data_; data_ = new char[newsize]; } size_ = newsize; endPosition_ = size_-1; if (s == NULL) data_[0] = '\0'; else strcpy(data_,s); } // Get const char *Dnchar::get() const { return data_; } // Get length int Dnchar::length() const { return (endPosition_ < size_ ? endPosition_ : size_); } // Create empty array void Dnchar::createEmpty(int newsize) { // Check if array has already been initialised if (data_ != NULL) delete[] data_; // Create new, empty array size_ = newsize; data_ = new char[newsize]; endPosition_ = 0; data_[0] = '\0'; } // Create empty array void Dnchar::createEmpty(Dnchar &s) { createEmpty(s.size_); } // Empty? bool Dnchar::isEmpty() const { return (endPosition_ <= 0 ? TRUE : FALSE); } // Return last character of string (before '\0') char Dnchar::lastChar() const { return (endPosition_ == 0 ? '\0' : data_[endPosition_-1]); } /* // Erase / Cut */ // Erase range void Dnchar::erase(int start, int end) { // Retain original memory length of string, but move '\0' and decrease 'size_' // Check range given if (start >= endPosition_) return; if (end >= endPosition_) end = endPosition_ - 1; int count = endPosition_ - end; //printf("Range to erase is %i to %i.\n",start,end); //printf("Characters after endpoint = %i\n",count); // Copy the character in position 'n' to position 'start + (n-last-1)' //printf(" DNCHAR - Before erase(%i,%i) = '%s', After = ",start,end,data_); for (int n=0; n<count; n++) data_[start+n] = data_[end+n+1]; size_ -= (1 + end - start); endPosition_ -= (1 + end - start); //printf("'%s'\n",data_); } // Erase from start void Dnchar::eraseStart(int n) { //printf("erasestart - n = %i, endPosition_ = %i\n",n,endPosition_); if ((n - 1) > endPosition_) { // printf("new (old) n = (%i) %i\n",n,endPosition_); n = endPosition_; } if (n > 0) erase(0,n-1); } // Erase from end void Dnchar::eraseEnd(int n) { if ((n - 1) >= endPosition_) n = endPosition_; if (n > 0) erase(endPosition_-n,endPosition_-1); } // Erase from specified position to end void Dnchar::eraseFrom(int n) { if (n >= (endPosition_-1)) n = endPosition_-1; if (n > 0) erase(n,endPosition_-1); } // Cut characters from start void Dnchar::cutStart(int len, Dnchar &target) { // Set new size_ of target string target.createEmpty(len+1); for (int n=0; n<len; n++) target += data_[n]; erase(0,len-1); } /* // Operators */ // Assignment operator (const char*) void Dnchar::operator=(const char *s) { set(s); } // Assignment operator (const Dnchar&) void Dnchar::operator=(const Dnchar &source) { if (source.data_ == NULL) clear(); else set(source.data_); } // Equality Operator (const char*) bool Dnchar::operator==(const char *s) const { if (data_ == NULL) return (s[0] == '\0'); return (strcmp(data_,s) == 0); } // Inequality Operator (const char*) bool Dnchar::operator!=(const char *s) const { if (data_ == NULL) return (s[0] != '\0'); return (strcmp(data_,s) != 0); } // Equality Operator bool Dnchar::operator==(const Dnchar &s) const { if (data_ == NULL) { if ((s.data_ == NULL) || (s.data_[0] == '\0')) return TRUE; else return FALSE; } else if (s.data_ == NULL) return (data_[0] == '\0'); return (strcmp(data_,s.data_) == 0); } // Inequality Operator bool Dnchar::operator!=(const Dnchar &s) const { if (data_ == NULL) { if ((s.data_ == NULL) || (s.data_[0] == '\0')) return FALSE; else return TRUE; } else if (s.data_ == NULL) return (data_[0] != '\0'); return (strcmp(data_,s.data_) != 0); } // Subscript operator char Dnchar::operator[](int n) const { if ((n < 0) || (n >= size_)) { std::printf("Dnchar::operator[] <<<< Array subscript %i out of range (0-%i) >>>>\n",n,size_-1); return 0; } return data_[n]; } // Character addition void Dnchar::operator+=(char c) { // Check whether we need to reallocate if ((endPosition_+1) > (size_-1)) { // We'll extend the size by 100 characters, rather than just 1 since we're likely to be adding more.... size_ = endPosition_+100; char *newdata = new char[size_]; if (data_ != NULL) { strcpy(newdata, data_); delete[] data_; } data_ = newdata; } data_[endPosition_] = c; ++endPosition_; data_[endPosition_] = '\0'; } /* // Conversion */ // Return as double double Dnchar::asDouble() const { return (data_ != NULL ? atof(data_) : 0.0); } // Return as integer int Dnchar::asInteger() const { return (data_ != NULL ? atoi(data_) : 0); } // Return as bool bool Dnchar::asBool() const { // Convert string to boolean bool result = FALSE; if (strcmp(data_,"off") == 0) result = FALSE; else if (strcmp(data_,"on") == 0) result = TRUE; else if (strcmp(data_,"no") == 0) result = FALSE; else if (strcmp(data_,"yes") == 0) result = TRUE; else if (strcmp(data_,"false") == 0) result = FALSE; else if (strcmp(data_,"true") == 0) result = TRUE; else { std::printf("Character constant '%s' doesn't translate directly to a boolean value - FALSE assumed.\n", data_); result = FALSE; } return result; } // Is Number? bool Dnchar::isNumeric() const { // Go through string - if we find a 'non-number' character, return false for (char *c = data_; *c != '\0'; c++) switch (*c) { case (' '): case ('0'): case ('1'): case ('2'): case ('3'): case ('4'): case ('.'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): case ('e'): case ('E'): case ('+'): case ('-'): break; default: return FALSE; } return TRUE; } /* // Search */ // Find character int Dnchar::find(char search) const { int count = 0; char *c; for (c = data_; *c != '\0'; c++) { // printf("Dnchar %c %c\n",*c,search); if (*c == search) return count; ++count; } return -1; } // Reverse find character int Dnchar::rFind(char search, char stopat1, char stopat2) const { int result; for (result = endPosition_; result >= 0; --result) { if (data_[result] == stopat1) return -1; if (data_[result] == stopat2) return -1; if (data_[result] == search) break; } return result; } /* // C-String Functions */ // String addition void Dnchar::strcat(const char *s, int charcount) { if (charcount == 0) return; // Check whether we need to reallocate int slen = strlen(s); if ((charcount != -1) && (charcount <= slen)) slen = charcount; if ((slen+endPosition_) > (size_-1)) { size_ = slen+endPosition_+1; char *newdata = new char[size_]; if (data_ != NULL) { strcpy(newdata, data_); delete[] data_; } data_ = newdata; } for (const char *c = s; *c != '\0'; ++c) { // If we're passed \0, ignore it (since we already have one) // Check size_ of array if (endPosition_ == (size_ - 1)) { printf("Dnchar::cat <<<< Buffer overflow - blame shoddy programming >>>>\n"); return; } data_[endPosition_] = *c; ++endPosition_; --slen; if (slen == 0) break; } data_[endPosition_] = '\0'; } // Append formatted string void Dnchar::strcatf(const char *fmt ...) { va_list arguments; static char s[8096]; s[0] = '\0'; // Parse the argument list (...) and internally write the output string into msgs[] va_start(arguments,fmt); vsprintf(s,fmt,arguments); va_end(arguments); // Now, append to existing string strcat(s); } // Create formatted string void Dnchar::sprintf(const char *fmt ...) { va_list arguments; static char s[8096]; s[0] = '\0'; // Parse the argument list (...) and internally write the output string into msgs[] va_start(arguments,fmt); vsprintf(s,fmt,arguments); set(s); va_end(arguments); } // Search for character in string char *Dnchar::strchr(char c) const { return std::strchr(data_, c); } // Copy substring of supplied string into this string void Dnchar::substr(const char *source, int pos, int nchars) { clear(); // Check start position int len = strlen(source); if ((pos < 0) || (pos >= len)) return; // Copy characters const char *c = &source[pos]; for (int n=0; n<nchars; ++n) { if (*c == '\0') break; (*this) += *c; c = c+1; } }
true
3f352eb68dc6fdab0fc9270060461462e1553380
C++
nihaljn/computer-graphics
/tree-drawing/src/graphics_engine.cpp
UTF-8
4,279
2.984375
3
[]
no_license
#include <iostream> #include "graphics_engine.h" GraphicsEngine::GraphicsEngine() { window = GraphicsEngine::initialize(); pCount = 0; return; } void GraphicsEngine::process_input() { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); return; } /** * @brief A callback function to process any changes made to the * screen size. * * @param window pointer to the current window. * @param width, height current dimensions of the window. */ void framebuffer_size_callback(GLFWwindow* window, int width, int height) { WIDTH = width; HEIGHT = height; glViewport(0, 0, WIDTH, HEIGHT); return; } GLFWwindow* GraphicsEngine::initialize() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Window", NULL, NULL); if (window == NULL) { std::cout << "Failed to create window\n"; glfwTerminate(); exit(1); } glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to load GLAD\n"; exit(1); } glViewport(0, 0, WIDTH, HEIGHT); unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); glGenVertexArrays(1, &vao); return window; } void GraphicsEngine::update_window() { glfwSwapBuffers(window); glfwPollEvents(); } int GraphicsEngine::close_window() { return glfwWindowShouldClose(window); } void GraphicsEngine::terminate() { glfwTerminate(); } void GraphicsEngine::set_background_color(float red, float green, float blue, float alpha) { glClearColor(red, green, blue, alpha); glClear(GL_COLOR_BUFFER_BIT); } void GraphicsEngine::normalize(float &x, float &y, float &z) { x = x*2.0f / WIDTH - 1.0f; y = y*2.0f / HEIGHT - 1.0f; z = z; return; } void GraphicsEngine::plot_points(const int* points, int pointCount) { float transformedPoints[pointCount*3]; for (int i = 0; i < pointCount; i++) { transformedPoints[i*3] = points[i*3]; transformedPoints[i*3 + 1] = points[i*3 + 1]; transformedPoints[i*3 + 2] = points[i*3 + 2]; normalize(transformedPoints[i*3], transformedPoints[i*3 + 1], transformedPoints[i*3 + 2]); } unsigned int vbo; glGenBuffers(1, &vbo); glUseProgram(shaderProgram); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof transformedPoints, transformedPoints, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof (float), (void*)0); glEnableVertexAttribArray(0); glDrawArrays(GL_POINTS, 0, pointCount); } void GraphicsEngine::add_primitive(int* points, int pointCount) { for (int i = 0; i < pointCount; i++) for (int j = 0; j < 3; j++) primitives[pCount][i*3 + j] = points[i*3 + j]; this -> pointCount[pCount++] = pointCount; } void GraphicsEngine::load_line(Line line) { int *points = line.get_line(); int pointCount = line.get_count(); add_primitive(points, pointCount); } void GraphicsEngine::load_circle(Circle circle) { int *points = circle.get_circle(); int pointCount = circle.get_count(); add_primitive(points, pointCount); } void GraphicsEngine::draw() { for (int i = 0; i < pCount; i++) plot_points(primitives[i], pointCount[i]); } /* DEBUG // / int main() { GraphicsEngine gr; gr.load_circle(400, 400, 100); gr.draw(); return 0; } // */
true
5ba1ea571f3a3ddb87dfcaeb37b2731fc6eb10c5
C++
Flp25/URI
/1047.cpp
UTF-8
760
3.046875
3
[]
no_license
#include<iostream> int horas = 24; int minutos = 60; using namespace std; int saida(int a, int b){ cout << "O JOGO DUROU "<< a <<" HORA(S) E " << b << " MINUTO(S)\n"; return 0; } int main(){ int h_ini, h_fim; int m_ini, m_fim; int h_dif, m_dif; h_dif = m_dif = 0; cin >> h_ini >> m_ini >> h_fim >> m_fim; m_dif = m_fim - m_ini; h_dif = h_fim - h_ini; if(h_ini == h_fim && m_ini == m_fim) return saida(horas, m_dif); if((h_fim - h_ini) < 0){ h_dif = horas + (h_fim - h_ini); } if((m_fim - m_ini) < 0){ m_dif = minutos + (m_fim - m_ini); h_dif --; if(h_dif < 0) h_dif = horas - 1; } return saida(h_dif, m_dif); }
true
733778ef08e705edb28b1f3d0b9bfa4ae0d44675
C++
KANBE8810/AtCoder
/Beginner/EX12.cpp
UTF-8
305
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int p=0, m=0; int sum=0; string s; cin >> s; for(int i = 0; i < s.size(); i++){ if(s.at(i) == '+') p++; if(s.at(i) == '-') m++; } sum = 1 + p - m; cout << sum << endl; }
true
1c0cf09a89344e197e8b38668a9a5a1d1a88c60a
C++
Vetteru/Topcoder
/DIV2/SRM414/RestaurantManager.cpp
UTF-8
5,326
2.65625
3
[]
no_license
// BEGIN CUT HERE // END CUT HERE #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; #define ALL(v) v.begin(), v.end() #define rALL(v) v.rbegin(), v.rend() bool isPrime(int a){for(int i=2; i*i<=a; i++) if(a%i==0) return false; return a>1;} string toStr(int a){ostringstream oss; oss<<a; return oss.str();} int toInt(string s){return atoi(s.substr(0,s.size()).c_str());} class RestaurantManager { public: int allocateTables(vector <int> tables, vector <int> groupSizes, vector <int> arrivals, vector <int> departures) { sort(ALL(tables)); int cnt[50] = {0}; int N = tables.size(); int M = groupSizes.size(); int ans = 0; for(int i = 0; i <= 200; i++) for(int j = 0; j < M; j++){ if(i == arrivals[j]){ int pos = -1; for(int k = 0; k < N; k++) if(tables[k] >= groupSizes[j] && cnt[k] <= i){ pos = k; break; } if(pos == -1) ans+=groupSizes[j]; else cnt[pos] = departures[j]; } } return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {4,8,4,2,2,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {0,10,12,16,18,26}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {10,20,18,26,36,28}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 14; verify_case(0, Arg4, allocateTables(Arg0, Arg1, Arg2, Arg3)); } void test_case_1() { int Arr0[] = {4,4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {4,8,4,2,2,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {0,10,12,16,18,26}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {10,20,18,26,36,28}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 8; verify_case(1, Arg4, allocateTables(Arg0, Arg1, Arg2, Arg3)); } void test_case_2() { int Arr0[] = {4,8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {4,8,4,2,2,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {0,10,12,16,18,26}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {10,20,18,26,36,28}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 2; verify_case(2, Arg4, allocateTables(Arg0, Arg1, Arg2, Arg3)); } void test_case_3() { int Arr0[] = {10,8,11,16}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {14,1,15,1,19,15,9,15,20,2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {4,5,7,18,21,25,29,31,46,49}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {8,37,11,36,36,46,40,42,47,50}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 69; verify_case(3, Arg4, allocateTables(Arg0, Arg1, Arg2, Arg3)); } void test_case_4() { int Arr0[] = {18,15,2,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {7,9,16,3,10,3,2,10,16,16}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10,15,19,20,21,22,27,35,37,43}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {13,24,22,32,32,32,35,48,41,44}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 10; verify_case(4, Arg4, allocateTables(Arg0, Arg1, Arg2, Arg3)); } void test_case_5() { int Arr0[] = {13,9,6,1,9,8,6,2,8,20}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {20,10,11,10,1,5,16,2,9,17}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {12,14,64,78,100,121,151,155,162,164}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {19,26,159,96,155,134,169,199,169,174}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 17; verify_case(5, Arg4, allocateTables(Arg0, Arg1, Arg2, Arg3)); } // END CUT HERE }; // BEGIN CUT HERE int main(){ RestaurantManager ___test; ___test.run_test(-1); } // END CUT HERE
true
44ac851b8bece109471582304cbdaf256baff3cc
C++
notwatermango/Kattis-Problem-Archive
/current/codecleanups.cc
UTF-8
695
2.703125
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main(){ int n; cin>>n; int arr[n]; for (int i = 0; i < n; i++) { cin>>arr[i]; } int d = 1; int clen = 0; while (d < 400) { int dirt = 0; for (int i = 0; i < n; i++) { if(d > arr[i]){ dirt+= d-arr[i]; } } if(dirt>19){ // time travel to yesterday, clean code for (int i = 0; i < n; i++) { if(d > arr[i]){ arr[i] = 9999; } } clen++; } d++; } cout<<clen; return 0; }
true
69b8abc8ffe4fdb03dbe3595476c06d3e0606d8c
C++
Vall98/GearStocks
/back/src/BddManager.cpp
UTF-8
3,921
2.671875
3
[]
no_license
// // EPITECH PROJECT, 2019 // main // File description: // main // #include <iostream> #include "../include/BddManager.hpp" #include <bsoncxx/builder/stream/document.hpp> #include <bsoncxx/json.hpp> #include <mongocxx/client.hpp> #include <mongocxx/instance.hpp> BddManager::BddManager() { connect(); } BddManager::~BddManager() { disconnect(); } void BddManager::connect() { std::cout << "Connect" << std::endl; _collection = _conn["testdb"]["testcollection"]; //bsoncxx::builder::stream::document document{}; //auto collection = _conn["testdb"]["testcollection"]; //mongocxx::collection collection = _conn["testdb"]["testcollection"]; //document << "ceci est un" << "petit test"; //std::cout << "BDD avant deletion" << std::endl; //printCollection(_collection); //addContentInBDD(_collection, document); //deleteContentInBDD(_collection, "Ceci est un test", "pour le rdv EIP2"); //updateContentInBDD(_collection, "test1", "test2", "mdr"); //checkIfExist(_collection, "test1", "mdr"); //std::cout << "BDD après deletion" << std::endl; //printCollection(_collection); } size_t BddManager::userConnect(std::string username, std::string password) { std::string valueInBDD; valueInBDD = checkIfExist(_collection, "username", username); if (valueInBDD != "") { valueInBDD = valueInBDD.substr(valueInBDD.find("password") + 13); valueInBDD = valueInBDD.substr(0, valueInBDD.rfind('"')); if (valueInBDD.compare(password) == 0) { std::cout << "gj mdr" << std::endl; return 0; } std::cout << "bad password" << std::endl; return 1; } std::cout << "user dont exist" << std::endl; return 2; } size_t BddManager::userRegister(std::string username, std::string password, std::string mail) { std::string valueInBDD; valueInBDD = checkIfExist(_collection, "username", username); if (valueInBDD != "") { std::cout << "User already exist" << std::endl; return 1; } valueInBDD = checkIfExist(_collection, "email", mail); if (valueInBDD != "") { std::cout << "Mail already used" << std::endl; return 2; } bsoncxx::builder::stream::document document{}; document << "username" << username << "email" << mail << "password" << password; addContentInBDD(_collection, document); } void BddManager::disconnect() { std::cout << "Disconnect" << std::endl; } void BddManager::addContentInBDD(auto collection, bsoncxx::builder::stream::document &doc) { collection.insert_one(doc.view()); } void BddManager::printCollection(auto collection) { auto cursor = collection.find({}); for (auto&& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; } } void BddManager::deleteContentInBDD(auto collection, std::string field, std::string value) { bsoncxx::builder::stream::document document{}; collection.delete_one(document << field << value << bsoncxx::builder::stream::finalize); } void BddManager::updateContentInBDD(auto collection, std::string field, std::string oldValue, std::string newValue) { bsoncxx::builder::stream::document document{}; collection.update_one(document << field << oldValue << bsoncxx::builder::stream::finalize, document << "$set" << bsoncxx::builder::stream::open_document << field << newValue << bsoncxx::builder::stream::close_document << bsoncxx::builder::stream::finalize); } std::string BddManager::checkIfExist(auto collection, std::string field, std::string value) { bsoncxx::builder::stream::document document{}; bsoncxx::stdx::optional<bsoncxx::document::value> maybe_result = collection.find_one(document << field << value << bsoncxx::builder::stream::finalize); if(maybe_result) { std::string result; //result = bsoncxx::to_json(*maybe_result) + "\n"; //std::cout << bsoncxx::to_json(*maybe_result) << "\n"; //std::cout << "IL EXISTE" << std::endl; //return result; return (bsoncxx::to_json(*maybe_result)); } return ""; }
true
75cfd35e3c22d82779b61405c549ea43e0b3e579
C++
rokcej/n-body-problem
/N_body_openmp.cpp
UTF-8
1,997
2.671875
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string> #include <omp.h> #include <chrono> #include "vector.h" #include "body.h" #include "util.h" #define ITERS 10000 #define DELTA_T 100000.0 #define FRAMES 2000 int main(int argc, char* argv[]) { int N; Body *bodies, *bodies_new; read_input(&N, &bodies, &bodies_new); Vector* log = new Vector[N * FRAMES * 2]; auto time_start = std::chrono::steady_clock::now(); #pragma omp parallel { int p = omp_get_thread_num(); int procs = omp_get_num_threads(); int frame = 0; for (int iter = 0; iter < ITERS; ++iter) { for (int i = p; i < N; i += procs) { Vector accel_sum = Vector(); for (int j = 0; j < N; ++j) { if (i != j) { accel_sum += bodies[i].acceleration(bodies[j]); } } bodies_new[i].pos = bodies[i].pos + bodies[i].vel * DELTA_T + accel_sum * (0.5 * DELTA_T * DELTA_T); bodies_new[i].vel = bodies[i].vel + accel_sum * DELTA_T; } if (iter % (ITERS / FRAMES) == 0) { for (int i = p; i < N; i += procs) { log[(i * FRAMES + frame) * 2 + 0] = Vector(bodies_new[i].pos); log[(i * FRAMES + frame) * 2 + 1] = Vector(bodies_new[i].vel); } ++frame; } #pragma omp barrier #pragma omp master { Body* tmp = bodies_new; bodies_new = bodies; bodies = tmp; } #pragma omp barrier } } auto time_end = std::chrono::steady_clock::now(); double time = std::chrono::duration<double>(time_end - time_start).count(); write_output(N, FRAMES, log, bodies); printf("Required time: %lfs\n", time); }
true
abe362f1d8e06ef4bfe1f5254435f4bddd85a193
C++
Gamma-Software/ros_ws
/src/drone_optique/src/track_people.cpp
UTF-8
2,068
2.609375
3
[ "Apache-2.0" ]
permissive
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <std_msgs/Bool.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/video/tracking.hpp" #include <vector> #include <stdio.h> #include <iostream> #include <inttypes.h> using namespace std; using namespace cv; class TrackObject{ //Publisher and Subscriber param ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; // Images Mat img, original; public: TrackObject() : it_(nh_) { // Init Publisher and Subscriber image_sub_ = it_.subscribe("/camera/image_raw", 1, &DetectFocus::callbackImg, this); } ~TrackObject() { cvDestroyWindow("original"); // Destroy Window } void callbackImg(const sensor_msgs::ImageConstPtr& msg) { //Image converter cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } img = cv_ptr->image; img.copyTo(original); } }; void onKeyboard(int key){ if(key == 102){ } } // Callback function used to track the mouse events void onMouse(int event, int x, int y, int flags, void* userdata) { switch( event ) { case CV_EVENT_LBUTTONDOWN: { } break; } } int main(int argc, char **argv) { //SetUP ROS. ros::init(argc, argv, "opencv_track"); // Initialise OpenCV windows namedWindow( "original", 0 ); // Set callback to the mouse when on the "focus" window setMouseCallback( "original", onMouse, 0 ); // Init object detectFocus TrackObject cam_object = TrackObject(); // Set looprate to 30 Hz ros::Rate loop_rate(30); while (ros::ok()){ int key = waitKey(3); onKeyboard(key); // Let loop ROS ros::spinOnce(); loop_rate.sleep(); } // Destroy object and thus windows name delete cam_object; }
true
f826cf7e5c3802712c047bb87fc22e8753af934b
C++
ZacharyTaylor/Multimodal-Calib
/Code/ImageList.h
UTF-8
2,460
2.9375
3
[]
no_license
#ifndef IMAGELIST_H #define IMAGELIST_H #include "common.h" #include "ScanList.h" #include "GenList.h" //! holds the sensors images class ImageList { private: //! structre holding infomation about each image typedef struct imageInit{ //! vector holding image data thrust::device_vector<float> image; //! image height size_t height; //! image width size_t width; //! image depth size_t depth; imageInit(){}; } image; //! vector holding all the images data std::vector<image> imageD; public: //! Constructor ImageList(void); //! Destructor ~ImageList(void); //! Gets the height of the image /*! /param idx index of image */ size_t getHeight(size_t idx); //! Gets the width of the image /*! /param idx index of image */ size_t getWidth(size_t idx); //! Gets the depth of the image /*! /param idx index of image */ size_t getDepth(size_t idx); //! Gets the number of images stored size_t getNumImages(void); //! Gets the image /*! /param idx index of image */ thrust::device_vector<float> getImage(size_t idx); //! Gets the pointer of the image data array /*! /param idx index of image */ float* getIP(size_t idx, size_t depthIdx); //! Adds an image to the list /*! \param imageDIn input image data \param height height of image \param width width of image */ void addImage(thrust::device_vector<float>& imageDIn, size_t height, size_t width, size_t depth); //! Adds an image to the list /*! \param imageDIn input image data \param height height of image \param width width of image */ void addImage(thrust::host_vector<float>& imageDIn, size_t height, size_t width, size_t depth); //! Removes an image from the list /*! \param idx index of image to remove */ void removeImage(size_t idx); //! Removes the last image on the list void removeLastImage(); //! Removes all of the images in the list void removeAllImages(); //! Interpolates specified image at given locations /*! \param scans list of scans with points to interpolate at \param gen list of generated images to save results to \param imageIdx the index of the image \param scanIdx the index of the scan to use \param genIdx the index to save generated points at \param linear true for linear interpolation, false for nearset neighbour */ void ImageList::interpolateImage(ScanList* scans, GenList* gen, size_t imageIdx, size_t scanIdx, size_t genIdx, boolean linear); }; #endif //IMAGELIST_H
true
bbb615de675cd468568f762ef64517df1a4a2891
C++
sootsprite/cpp-unit-testing
/lib_forward_list/list_sample.cpp
UTF-8
559
2.921875
3
[]
no_license
#include <iostream> #include <list> #include <string> #include <algorithm> int main(int argc, char const* argv[]) { std::list<std::string> cats = { "shutan", "mizuki", "rori", }; auto itr = std::find(cats.begin(), cats.end(), "mizuki"); itr = cats.insert(itr, "magusan"); std::for_each( cats.begin(), cats.end(), [](std::string& s) { std::cout << s << " "; } ); std::cout << std::endl; cats.erase(itr); std::for_each( cats.begin(), cats.end(), [](std::string& s) { std::cout << s << " "; } ); std::cout << std::endl; return 0; }
true
de3d1a5e7caeba6ed1dc14e6ad4ecf1c0c30cb5f
C++
bhavnas23/Leetcode-Monthly-Challenges
/October2020/7RotateList.cpp
UTF-8
1,208
3.3125
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* findKth(ListNode* head, int k){ int c=0; ListNode* temp=head, *tmp=head; while(temp && c<k){ c++; temp=temp->next; } while(temp){ temp=temp->next; tmp=tmp->next; } return tmp; } ListNode* rotateRight(ListNode* head, int k) { ListNode *kth=NULL, *temp=head; int n=0; while(temp){ n++; temp=temp->next; } if(n==0) return head; k=k%n; if(k==0 ) return head; temp=head; kth = findKth(head, k); head = kth; ListNode* tmp = head; while(tmp->next){ tmp=tmp->next; } tmp->next=temp; while(tmp->next!=head){ tmp=tmp->next; } tmp->next=NULL; return head; } };
true
490008d26252242bca6afd38efbf3d509254ffe2
C++
yumiris/OpenSauce
/OpenSauce/shared/Include/YeloLib/configuration/i_configuration_value.hpp
UTF-8
2,057
2.59375
3
[]
no_license
/* Yelo: Open Sauce SDK See license\OpenSauce\Halo1_CE for specific license information */ #pragma once #include <YeloLib/configuration/i_configuration_leaf.hpp> namespace Yelo { namespace Configuration { /// <summary> Base configuration value interface. </summary> class i_configuration_value abstract { public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Get's the nodes name. </summary> /// /// <returns> A std::string containing the nodes name. </returns> virtual const std::string& GetName() const = 0; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Gets the objects value from the supplied node. </summary> /// /// <param name="node"> The node to get the value from. </param> virtual void GetValue(i_configuration_leaf& node) = 0; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Sets the objects value to the supplied node. </summary> /// /// <param name="node"> The node to set the value to. </param> virtual void SetValue(i_configuration_leaf& node) = 0; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Gets the value from the first child of the supplied node. If the child does not exist, it is created. /// </summary> /// /// <param name="parent_node"> The parent node to get the value from. </param> virtual void GetValueFromParent(i_configuration_leaf& parent_node) = 0; //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Sets the value to a child added to the supplied node. </summary> /// /// <param name="parent_node"> The parent node to set the value to. </param> virtual void SetValueToParent(i_configuration_leaf& parent_node) = 0; }; }; };
true
ad45f781612eefde477e01cc7fd7c294eb7c4fe6
C++
qhdong/cpp-primer
/chapter-09/string.cpp
UTF-8
597
3.09375
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { const char *cp = "Hello, world!!!"; char notNull[] = {'H', 'l'}; string s1(cp); string s2(notNull, 2); // string s3(notNull); string s4(cp + 6, 5); string s5(s1, 6, 5); string s6(s1, 6); string s7(s1, 6, 20); // string s8(s1, 16); s1.replace(0, 3, "HEL"); cout << s1 << endl; s1.append(", YES"); cout << s1 << endl; s1.insert(s1.begin(), s2.begin(), s2.end()); cout << s1 << endl; double d = stod("3.334sld"); cout << d << endl; return 0; }
true