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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
82230559e0d480875a135799a58390da40b22e8f | C++ | Gaston11/Trabajo-Pr-ctico-N-2 | /Equipo.cpp | UTF-8 | 2,289 | 3 | 3 | [] | no_license | /*
* Equipo.cpp
*
* Created on: 22/05/2016
* Author: gaston
*/
#include "Equipo.h"
Equipo::Equipo(std::string numero, Antena* antena){
this->numero = numero;
this->llamadas = new Lista<Llamada*>;
this->ultimaConexionAntena = new Conexion(antena);
this->llamadasEntrantes = 0;
this->llamadasSalientes = 0;
this->entrantesOcupado = 0;
this->salientesOcupado = 0;
}
std::string Equipo::obtenerNumero(){
return this->numero;
}
Lista<Llamada*>* Equipo::obtenerLLamadasEquipo(){
return this->llamadas;
}
Llamada* Equipo::obtenerUltimaLlamada(){
this->llamadas->iniciarCursor(); // el ultimo esta en la ultima posicion
bool encontrado=false;
Llamada* llamada;
while((this->llamadas->avanzarCursor()) && !(encontrado)){
llamada=this->llamadas->obtenerCursor();
encontrado=(!(llamada->estaFinalizada()));
}
return llamada;
}
Conexion* Equipo::obtenerUltimaConexion(){
return this->ultimaConexionAntena;
}
bool Equipo::estaConectado(){
return (this->ultimaConexionAntena->estaConectado());
}
bool Equipo::estaOcupado(){
/*
return (!this->obtenerUltimaLlamada()->estaFinalizada());
*/
bool encontrado = false;
this->llamadas->iniciarCursor();
while(this->llamadas->avanzarCursor() && ! encontrado){
encontrado =!(this->llamadas->obtenerCursor()->estaFinalizada());
}
return encontrado;
}
void Equipo::incrementarLlamadasSalientes(){
this->llamadasSalientes++;
}
void Equipo::incrementarLlamadasEntrantes(){
this->llamadasEntrantes++;
}
void Equipo::incrementarSalientesOcupado(){
this->salientesOcupado++;
}
void Equipo::incrementarEntrantesOcupado(){
this->entrantesOcupado++;
}
unsigned int Equipo::obtenerLlamadasEntrantes(){
return this->llamadasEntrantes;
}
unsigned int Equipo::obtenerLlamadasSalientes(){
return this->llamadasSalientes;
}
unsigned int Equipo::obtenerLlamadasSalienteOcupado(){
return this->salientesOcupado;
}
unsigned int Equipo::obtenerLlamadasEntranteOcupado(){
return this->entrantesOcupado;
}
Equipo::~Equipo(){
this->llamadas->iniciarCursor();
while(this->llamadas->avanzarCursor()){
delete this->llamadas->obtenerCursor();
}
delete (this->llamadas);
delete (this->ultimaConexionAntena);
}
| true |
bab679d7d210175b5a1b6b36c3ed2fe368b6e8ad | C++ | jrgagnon/FinalTriggerofLegend | /ftol_tile.cpp | UTF-8 | 1,219 | 3.171875 | 3 | [] | no_license | #include "ftol_tile.h"
ftol_tile::ftol_tile(int x, int y, int tileType, SDL_Rect tileBox)
{
myType = tileType;
boundingBox.x = x;
boundingBox.y = y;
boundingBox.w = TILE_WIDTH;
boundingBox.h = TILE_HEIGHT;
myTileBox = tileBox;
}
void ftol_tile::render(SDL_Rect camera, SDL_Renderer* passed_renderer, SDL_Texture* texture)
{
if(checkCollision(boundingBox, camera))
{
SDL_RenderCopy(passed_renderer, texture, &myTileBox, &boundingBox);
}
}
bool ftol_tile::checkCollision(SDL_Rect a, SDL_Rect b)
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of rect A
leftA = a.x;
rightA = a.x + a.w;
topA = a.y;
bottomA = a.y + a.h;
//Calculate the sides of rect B
leftB = b.x;
rightB = b.x + b.w;
topB = b.y;
bottomB = b.y + b.h;
//If any of the sides from A are outside of B
if( bottomA <= topB )
{
return false;
}
if( topA >= bottomB )
{
return false;
}
if( rightA <= leftB )
{
return false;
}
if( leftA >= rightB )
{
return false;
}
//If none of the sides from A are outside B
return true;
}
int ftol_tile::getType()
{
return myType;
}
| true |
104d8847eec1fd0836b1a9a95445cac9d9f8d723 | C++ | Kunal-khanwalkar/coding-practise | /gfg_mustdo/Strings/makePalindrome.cpp | UTF-8 | 1,047 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void bruteForce(string str)
{
int cnt = 0;
int i,j;
while(str.length())
{
int l = str.length();
int flag = 0;
for(i=0,j=l-1; i<=j; i++,j--)
if(str[i]!=str[j])
{
flag = 1;
break;
}
if(flag == 0)
{
cout<<cnt;
return;
}
else
{
cnt++;
str.erase(str.begin() + str.length() - 1);
}
}
}
vector<int> computeLps(string str)
{
int M = str.length();
vector<int> lps(M);
int len = 0;
lps[0] = 0;
int i = 1;
while(i < M)
{
if(str[i] == str[len])
{
len++;
lps[i] = len;
i++;
}
else
{
if(len!=0)
len = lps[len-1];
else
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
void lpsMethod(string str)
{
string revStr = str;
reverse(revStr.begin(), revStr.end());
string concat = str + "$" + revStr;
vector<int> lps = computeLps(concat);
cout<<str.length() - lps.back();
}
int main()
{
string str = "BABABAA";
//bruteForce(str);
lpsMethod(str);
return 0;
} | true |
34d493dea6873e067026d947c24064b20768f61c | C++ | pragya-chauhan/dsa | /Leetcode/April-Challenge/max-subarray.cpp | UTF-8 | 500 | 3.359375 | 3 | [
"MIT"
] | permissive | // Kadane's Algorithm:
// -2 1 -3 4 -1 2 1 -5 4
// moves from L -> R
// O(1) space Time Complexity
class Solution {
public:
int maxSubArray(vector<int>& nums) {
// INT_MIN == -infinity for atleast one element in an array
// otherwise can be taken as 0 as well, if it was a empty array!
int answer= INT_MIN , a = 0;
for ( int x: nums ) {
a += x;
answer = max(answer, a);
a = max(a, 0);
}
return answer;
}
}; | true |
401ab630883fc228e6b42ecee3074c6f03b2dad8 | C++ | Garciat/competitive | /leetcode/hamming-distance.cpp | UTF-8 | 297 | 2.890625 | 3 | [] | no_license | // https://leetcode.com/problems/hamming-distance/
class Solution {
public:
int hammingDistance(int x, int y) {
int z = x ^ y;
int i = 0;
while (z != 0) {
i += z & 1;
z >>= 1;
}
return i;
}
};
| true |
8a6cd1ad96f7f964a2c619bd80092a4cd0bde52f | C++ | alrus2797/EDA | /Lab4 - Huffman/hNodo.h | UTF-8 | 2,040 | 3.359375 | 3 | [] | no_license | #ifndef HNODO_H
#define HNODO_H
#include <iostream>
using namespace std;
string operator+(const string& a, const int& b) { //outside the class
return a + to_string(b);
}
string operator+(const string& a, const char& b) { //outside the class
return a + to_string(b);
}
class hNodo
{
private:
char letra;
int frecuencia;
hNodo* izq;
hNodo* der;
hNodo* padre;
bool hoja;
string camino;
int id;
public:
hNodo(char letra, int frecuencia);
hNodo(int frecuencia);
string getStrValue();
~hNodo();
bool operator < (const hNodo& a){
if (this->frecuencia < a.frecuencia) return true;
return false;
}
friend ostream& operator<< (ostream& os, const hNodo& obj);
friend bool operator> (const hNodo& a, const hNodo& b);
friend hNodo* operator + ( hNodo&, hNodo&);
friend class Huffman;
};
bool operator> (const hNodo& a, const hNodo& b){
return a.frecuencia > b.frecuencia;
}
//Constructor para nodos
hNodo::hNodo(char letra, int frecuencia)
{
this->letra = letra;
this->frecuencia = frecuencia;
this->izq = 0;
this->der = 0;
this->padre = 0;
this->hoja = true;
}
//Constructor para nodos padre
hNodo::hNodo( int frecuencia)
{
this->frecuencia = frecuencia;
this->izq = 0;
this->der = 0;
this->padre = 0;
this->hoja = false;
}
hNodo::~hNodo()
{
}
hNodo* operator + (hNodo& a, hNodo& b){
hNodo* nuevo = new hNodo(a.frecuencia+b.frecuencia);
nuevo->izq = &a;
nuevo->der = &b;
return nuevo;
}
ostream& operator<< (ostream& os, const hNodo& obj) {
if (obj.hoja) cout<<" ('"<<obj.letra<<"', "<<obj.frecuencia<<") ";
else cout<<" ("<<obj.frecuencia<<") ";
return os;
}
string hNodo::getStrValue(){
string res ="";
if (this->hoja) res = res +" ('"+this->letra+"', "+this->frecuencia+") ";
else res = res +" ("+this->frecuencia+") ";
res = res + "\n" + this->camino;
return res;
}
#endif | true |
d243ff47fd40b17618f3a226824d5b9cf722c655 | C++ | lctran/Fight-My-Squad | /lineup.hpp | UTF-8 | 1,260 | 2.9375 | 3 | [] | no_license | /*********************************************************************
** Program name: Project 4 - Fantasy Combat Game TOURNAMENT EDITION
** Author: Laura Tran (932373639)
** Date: 19 NOV 2017
** Description: Creates lineup hpp file. Defines the functions
that will store and remove character* pointers from a list.
*********************************************************************/
#ifndef LINEUP_HPP
#define LINEUP_HPP
#include "character.hpp"
class lineup {
protected:
struct fighter {
fighter* prevFighter; // *prev node
fighter* nextFighter; // *next node
character* fighterCharacter;// *character pointer
};
fighter *head; // left of linked list
fighter *tail; // right
int numFighters; // number of players
int tempF;
public:
lineup(); // default constructor
~lineup(); // destructor
void addFighter(character*); // P = character(fighter) ptr, add fighter to lineup
character* removeFighter(); // remove recent fighter and point to the next fighter
// bool isAlive(); // check if team has living fighters
void setNumFighters(int); // P = num of fighters
int getNumFighters(); // get numFighters
};
#endif | true |
1ed54a31ee66798908e6300784b07e5375318a55 | C++ | LiamDurnst/Parallel-Breadth-First-Search | /good_example/Bag.h | UTF-8 | 2,064 | 3.015625 | 3 | [] | no_license | /*************************************
* Bag.h *
* by Dane Pitkin and Nathan Crandall*
* for CS140 Final Project *
* in Parallel BFS Algorithm *
* *
* *
************************************/
#ifndef BAG_H
#define BAG_H
#include "Pennant.h"
#include <cilk.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
extern "C++"{
class Bag{
public:
Bag();
Bag(const Bag* & bag);
~Bag();
void insert(int item);
bool empty() const;
void merge(Bag* bag);
Bag* split();
void clear();
int size() const;
bool can_split() const;
void print() const;
void recursive_print(Node* node) const; // prints in-order
void recursive_print_sum(Node* node, int & sum) const;
void remove_all();
int* write_array();
void recursive_write_array(int* & array, Node* node, int &count);
friend class Bag_reducer;
friend class cilk::monoid_base<Bag >;
//private:
int forest_size;
//pennant structure
Pennant** forest;
};
// Make the bag a reducer hyperobject
class Bag_reducer{
public:
struct Monoid: cilk::monoid_base<Bag >
{
static void reduce(Bag *left, Bag *right){
left->merge(right);
}
};
Bag_reducer() : imp_() {}
int get_forest_size()
{
return imp_.view().forest_size;
}
Pennant* get_forest(int i)
{
return imp_.view().forest[i];
}
void set_forest(int i, Pennant* tree)
{
imp_.view().forest[i] = tree;
}
void insert(int item)
{
imp_.view().insert(item);
}
void merge(Bag_reducer* br)
{
this->imp_.view().merge(&br->imp_.view());
}
Bag* split()
{
return imp_.view().split();
}
bool empty() const
{
return imp_.view().empty();
}
void clear()
{
return imp_.view().clear();
}
Bag &get_reference()
{
return imp_.view();
}
int size()
{
return imp_.view().size();
}
int* write_array()
{
return imp_.view().write_array();
}
private:
cilk::reducer<Monoid> imp_;
};
}//end extern c++
#endif
| true |
b7cae607b68c487ef1b5dfd26fd8e57b485c1253 | C++ | alexey-petrusevich/Milestone_1 | /eau2/include/eau2/dataframe/fielders/print_fielder.h | UTF-8 | 565 | 3 | 3 | [] | no_license | #pragma once
#include "fielder.h"
/**
* A Fielder that prints every value of the given row.
*/
class PrintFielder : public Fielder {
public:
/**
* Default constructor of this PrintFielder.
*/
PrintFielder();
// accept method for int
void accept(int i);
// accept method for double
void accept(double d);
// accept method for bool
void accept(bool b);
// accept method for string
void accept(String *s);
// method to show that all the values in the row have been looked at. prints
void done();
};
| true |
f2438c416a3b24913851123df697da33ac637ae0 | C++ | naikkartik/competitive_coding_problem | /project_euler/reverse_bits.cpp | UTF-8 | 344 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long int solution(long long int n){
long long count = 0;
long long int ans =0;
while(n>0){
count++;
n = n>>1;
cout<<n<<endl;
}
return ans;
}
int main(){
long long int n;
cin>>n;
long long int ans = solution(n);
//cout<<ans<<endl;
}
| true |
7a8471d8527ad127820afb9011ce1469670b4fa6 | C++ | hometao/graphene | /qt/plugins/povray_plugin/Scene_graph_converter.h | UTF-8 | 2,945 | 2.84375 | 3 | [] | no_license | #ifndef GRAPHENE_SCENE_GRAPH_CONVERTER_H
#define GRAPHENE_SCENE_GRAPH_CONVERTER_H
#include <graphene/gl/gl_includes.h>
#include <graphene/scene_graph/Scene_graph.h>
#include <graphene/scene_graph/Base_node.h>
#include <vector>
#include <map>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace graphene::scene_graph;
namespace graphene {
// converts a scene graph into the Povray files format
class Scene_graph_converter
{
public:
// maps a node to its usage specifier.
// the usage specifier is used in the hierarchy
// to apply a nodes declaration
typedef std::map<Base_node*,std::string> Key_word_type;
// contains all options for Povray
struct Povray_options
{
// povray files name prefix
std::string name_prefix;
// picture width
int width;
// picture height
int height;
// quality setting used by Povray
int quality;
// sampling method used by Povray
int sampling_method;
// depth setting used by Povray
int depth;
// threshold setting used by Povray
double threshold;
// jitter setting used by Povray
double jitter;
// antialias setting used by Povray
bool antialias;
// verbose flag used by Povray
bool verbose;
// display flag used by Povray
bool display;
};
public:
// Constructor expects scene graph and Povray options
// that should be used.
Scene_graph_converter(const Scene_graph* _graph,
const Povray_options _options
);
// starts conversion from scene graph to povray file format
bool start();
private:
// creates .pov file for the scene graph
void create_pov_file();
// creates .ini file for the scene graph
void create_ini_file();
// traverese scene graph
std::string traverse(Base_node* _node);
// creates recursively the scene graph hierarchy
// for the sub tree beginning with _node.
// aka: creates all the unions for _nodes children
// and their declarations
std::string unions_of_children(Base_node* _node);
// add a declare directive to save this node information
// under and make it useable through an unique name
void add_declaration_to_pov_file(Base_node* _node);
// check, if node is modifier (Material_node, ...)
bool is_modifier(Base_node* _node);
private:
// used scene graph
const Scene_graph* graph_;
// saves the Povray options
const Povray_options options_;
// output streams for the pov- and ini-file
std::ofstream pov_file_;
std::ofstream ini_file_;
// list of all unique nodes in the scene graph
std::vector<Base_node*> nodes_;
// keeps track which node declarations should be used in
// the hierarchy and in which way
Key_word_type keyword_map_;
};
}
#endif
| true |
1b534d44f4d2d97d634e432cbb63d0e3fb5ba03d | C++ | bford26/kinetic_psim | /test/core/UtilityTests.cpp | UTF-8 | 496 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include "Utils.hpp"
// testing v2d operations
// testing v3d operations
// testing v3d and v3i interactions
using namespace std;
int main(int argc, char** argv)
{
// all operators +-*/ += -= *= /=
v3d x, x0, dh;
x = {1,1,1};
x0 = {0.5,0.75,0.25};
dh = {0.25,0.25,0.25};
v3d res {2, 1, 3};
v3d lc = ( x - x0 ) / dh;
std::cout << "lc : " << lc << std::endl;
std::cout << "res : " << res << std::endl;
return 0;
}
| true |
068b229285e9070e4ed4141fdc78858894903437 | C++ | Gelio/p3-lab1415 | /2. laby stringi/zadanie_a/planeta.h | UTF-8 | 755 | 2.875 | 3 | [] | no_license | #ifndef PLANETA_H
#define PLANETA_H
#include <set>
#include <ostream>
#include "senator.h"
class KomparatorSenatorow {
public:
bool operator()(const Senator& s1, const Senator& s2);
};
class Planeta
{
private:
// nie modyfikujemy definicji tego pola
const std::string nazwa;
std::set<Senator, KomparatorSenatorow> senat;
public:
Planeta(const std::string& nazwa) : nazwa(nazwa) { };
void dodajSenatora(const Senator& senator);
const std::string& getNazwa() const { return nazwa;}
void wypiszSile(std::ostream& out) const;
void wypiszPochodzenie(std::ostream& out) const;
void usunSlabych(int sila);
int sumaSil() const;
// mozna dodać metody pomocnicze
};
// i funkcje pomocnicze
#endif // PLANETA_H
| true |
84ab4453837def44098c494718b44a363ae4561c | C++ | OliverSchmitz/lue | /source/framework/algorithm/test/kernel_test.cpp | UTF-8 | 5,676 | 2.828125 | 3 | [
"MIT"
] | permissive | #define BOOST_TEST_MODULE lue framework algorithm kernel
#include "lue/framework/algorithm/kernel.hpp"
#include "lue/framework/test/stream.hpp"
#include <hpx/config.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(kernel_bool_1d)
{
using Weight = bool;
lue::Rank const rank = 1;
using Kernel = lue::Kernel<Weight, rank>;
using Shape = lue::ShapeT<Kernel>;
lue::Radius const radius = 0;
Shape shape{2 * radius + 1};
Kernel kernel{shape};
BOOST_CHECK_EQUAL(lue::rank<Kernel>, rank);
BOOST_CHECK_EQUAL(lue::shape(kernel), shape);
BOOST_CHECK_EQUAL(kernel.radius(), radius);
BOOST_CHECK_EQUAL(lue::nr_elements(kernel), 1);
std::int32_t sum = std::accumulate(kernel.begin(), kernel.end(), 0);
BOOST_CHECK_EQUAL(sum, 0);
}
BOOST_AUTO_TEST_CASE(box_kernel_bool_1d)
{
using Weight = bool;
lue::Rank const rank = 1;
using Kernel = lue::Kernel<Weight, rank>;
using Shape = lue::ShapeT<Kernel>;
lue::Radius const radius = 1;
bool const value = true;
Kernel kernel = lue::box_kernel<Weight, rank>(radius, value);
Shape shape{2 * radius + 1};
BOOST_CHECK_EQUAL(lue::shape(kernel), shape);
BOOST_CHECK_EQUAL(kernel.radius(), radius);
BOOST_CHECK_EQUAL(lue::nr_elements(kernel), 3);
std::int32_t sum = std::accumulate(kernel.begin(), kernel.end(), 0);
BOOST_CHECK_EQUAL(sum, 3);
BOOST_CHECK_EQUAL(kernel[0], true);
BOOST_CHECK_EQUAL(kernel[1], true);
BOOST_CHECK_EQUAL(kernel[2], true);
}
BOOST_AUTO_TEST_CASE(box_kernel_bool_2d)
{
using Weight = bool;
lue::Rank const rank = 2;
using Kernel = lue::Kernel<Weight, rank>;
using Shape = lue::ShapeT<Kernel>;
lue::Radius const radius = 1;
bool const value = true;
Kernel kernel = lue::box_kernel<Weight, rank>(radius, value);
Shape shape{2 * radius + 1, 2 * radius + 1};
BOOST_CHECK_EQUAL(lue::shape(kernel), shape);
BOOST_CHECK_EQUAL(kernel.radius(), radius);
BOOST_CHECK_EQUAL(lue::nr_elements(kernel), 9);
BOOST_CHECK_EQUAL(kernel(0, 0), true);
BOOST_CHECK_EQUAL(kernel(0, 1), true);
BOOST_CHECK_EQUAL(kernel(0, 2), true);
BOOST_CHECK_EQUAL(kernel(1, 0), true);
BOOST_CHECK_EQUAL(kernel(1, 1), true);
BOOST_CHECK_EQUAL(kernel(1, 2), true);
BOOST_CHECK_EQUAL(kernel(2, 0), true);
BOOST_CHECK_EQUAL(kernel(2, 1), true);
BOOST_CHECK_EQUAL(kernel(2, 2), true);
}
BOOST_AUTO_TEST_CASE(circle_kernel_bool_1d)
{
using Weight = bool;
lue::Rank const rank = 1;
using Kernel = lue::Kernel<Weight, rank>;
using Shape = lue::ShapeT<Kernel>;
lue::Radius const radius = 1;
bool const value = true;
Kernel kernel = lue::circle_kernel<Weight, rank>(radius, value);
Shape shape{2 * radius + 1};
BOOST_CHECK_EQUAL(lue::shape(kernel), shape);
BOOST_CHECK_EQUAL(kernel.radius(), radius);
BOOST_CHECK_EQUAL(lue::nr_elements(kernel), 3);
std::int32_t sum = std::accumulate(kernel.begin(), kernel.end(), 0);
BOOST_CHECK_EQUAL(sum, 3);
BOOST_CHECK_EQUAL(kernel[0], true);
BOOST_CHECK_EQUAL(kernel[1], true);
BOOST_CHECK_EQUAL(kernel[2], true);
}
BOOST_AUTO_TEST_CASE(circle_kernel_bool_2d)
{
using Weight = bool;
lue::Rank const rank = 2;
using Kernel = lue::Kernel<Weight, rank>;
using Shape = lue::ShapeT<Kernel>;
bool const value = true;
{
lue::Radius const radius = 1;
Kernel kernel = lue::circle_kernel<Weight, rank>(radius, value);
Shape shape{2 * radius + 1, 2 * radius + 1};
BOOST_CHECK_EQUAL(lue::shape(kernel), shape);
BOOST_CHECK_EQUAL(kernel.radius(), radius);
BOOST_CHECK_EQUAL(lue::nr_elements(kernel), 9);
BOOST_CHECK_EQUAL(kernel(0, 0), false);
BOOST_CHECK_EQUAL(kernel(0, 1), true);
BOOST_CHECK_EQUAL(kernel(0, 2), false);
BOOST_CHECK_EQUAL(kernel(1, 0), true);
BOOST_CHECK_EQUAL(kernel(1, 1), true);
BOOST_CHECK_EQUAL(kernel(1, 2), true);
BOOST_CHECK_EQUAL(kernel(2, 0), false);
BOOST_CHECK_EQUAL(kernel(2, 1), true);
BOOST_CHECK_EQUAL(kernel(2, 2), false);
}
{
lue::Radius const radius = 2;
Kernel kernel = lue::circle_kernel<Weight, rank>(radius, value);
Shape shape{2 * radius + 1, 2 * radius + 1};
BOOST_CHECK_EQUAL(lue::shape(kernel), shape);
BOOST_CHECK_EQUAL(kernel.radius(), radius);
BOOST_CHECK_EQUAL(lue::nr_elements(kernel), 25);
BOOST_CHECK_EQUAL(kernel(0, 0), false);
BOOST_CHECK_EQUAL(kernel(0, 1), false);
BOOST_CHECK_EQUAL(kernel(0, 2), true);
BOOST_CHECK_EQUAL(kernel(0, 3), false);
BOOST_CHECK_EQUAL(kernel(0, 4), false);
BOOST_CHECK_EQUAL(kernel(1, 0), false);
BOOST_CHECK_EQUAL(kernel(1, 1), true);
BOOST_CHECK_EQUAL(kernel(1, 2), true);
BOOST_CHECK_EQUAL(kernel(1, 3), true);
BOOST_CHECK_EQUAL(kernel(1, 4), false);
BOOST_CHECK_EQUAL(kernel(2, 0), true);
BOOST_CHECK_EQUAL(kernel(2, 1), true);
BOOST_CHECK_EQUAL(kernel(2, 2), true);
BOOST_CHECK_EQUAL(kernel(2, 3), true);
BOOST_CHECK_EQUAL(kernel(2, 4), true);
BOOST_CHECK_EQUAL(kernel(3, 0), false);
BOOST_CHECK_EQUAL(kernel(3, 1), true);
BOOST_CHECK_EQUAL(kernel(3, 2), true);
BOOST_CHECK_EQUAL(kernel(3, 3), true);
BOOST_CHECK_EQUAL(kernel(3, 4), false);
BOOST_CHECK_EQUAL(kernel(4, 0), false);
BOOST_CHECK_EQUAL(kernel(4, 1), false);
BOOST_CHECK_EQUAL(kernel(4, 2), true);
BOOST_CHECK_EQUAL(kernel(4, 3), false);
BOOST_CHECK_EQUAL(kernel(4, 4), false);
}
}
| true |
096222fbbefcb77b26d96f88f3c89a7cb847a43c | C++ | sdarkhovsky/feature_detector | /feature_detector/learner.h | UTF-8 | 17,860 | 2.515625 | 3 | [] | no_license | #pragma once
#include "lpngwrapper.hpp"
#include "param_context.h"
#include <vector>
#include <map>
#include <random>
#include <iostream>
#include <fstream>
using namespace std;
namespace Learner {
static const int num_arm_joints = 3;
class c_statistic
{
public:
void calculate_linear_statistic_parameters(param_context& pc)
{
std::uniform_real_distribution<double> distribution(-1.0, 1.0);
if (pc.seed_random_engines)
{
statistic_generator.seed(time(NULL));
}
int wx = pc.wx;
int wy = pc.wy;
int wsize = (2 * wx + 1)*(2 * wy + 1);
params = MatrixXd::Zero(2 * wy + 1, 2 * wx + 1);
for (int i1 = -wy; i1 <= wy; i1++)
{
for (int i2 = -wx; i2 <= wx; i2++)
{
params(i1 + wy, i2 + wx) = distribution(statistic_generator);
}
}
statistic_type = (c_statistic_type) pc.statistic_type;
switch (statistic_type)
{
case c_statistic::differential:
{
// make total sum 0
params(wy, wx) = -(params.sum() - params(wy, wx));
}
default:
{
}
}
}
MatrixXd params;
enum c_statistic_type { differential = 0, linear = 1, sigmoid = 2 };
c_statistic_type statistic_type;
std::default_random_engine statistic_generator;
};
class c_statistic_channel
{
public:
void calculate_image_statistic(param_context& pc, const MatrixXd& image_channel, c_statistic& statistic)
{
int x, y, x0, y0;
double sum;
int width = image_channel.cols();
int height = image_channel.rows();
int wx = (statistic.params.cols() - 1) / 2;
int wy = (statistic.params.rows() - 1) / 2;
statistic_val = MatrixXd::Zero(height, width);
for (y0 = wy; y0 < height - wy; y0++) {
for (x0 = wx; x0 < width - wx; x0++) {
sum = 0.0;
for (y = y0 - wy; y <= y0 + wy; y++) {
for (x = x0 - wx; x <= x0 + wx; x++) {
sum += image_channel(y, x)*statistic.params(y - y0 + wy, x - x0 + wx);
}
}
switch (statistic.statistic_type)
{
case c_statistic::sigmoid:
{
statistic_val(y0, x0) = 1 / (1 + exp(-sum));
}
default:
{
statistic_val(y0, x0) = sum;
}
}
}
}
minCoeff = statistic_val.minCoeff();
maxCoeff = statistic_val.maxCoeff();
range_length = (maxCoeff - minCoeff) / pc.num_chan_ranges;
}
MatrixXd statistic_val;
double minCoeff, maxCoeff, range_length;
};
class c_range_key
{
public:
bool operator() (const c_range_key& lhs, const c_range_key& rhs) const
{
int n = lhs.ranges.size();
if (n > rhs.ranges.size())
n = rhs.ranges.size();
for (int i = 0; i < n; i++)
{
if (lhs.ranges[i] < rhs.ranges[i])
return true;
if (lhs.ranges[i] > rhs.ranges[i])
return false;
}
return false;
}
vector<int> ranges;
};
class c_point
{
public:
int x, y;
};
class c_point_set
{
public:
c_point_set()
{
}
void calculate_boundaries()
{
if (points.size() == 0)
return;
min_x = points[0].x;
max_x = points[0].x;
min_y = points[0].y;
max_y = points[0].y;
for (auto& point : points)
{
if (min_x > point.x)
min_x = point.x;
if (min_y > point.y)
min_y = point.y;
if (max_x < point.x)
max_x = point.x;
if (max_y < point.y)
max_y = point.y;
}
diam << max_x - min_x, max_y - min_y;
center << (min_x + max_x) / 2, (min_y + max_y) / 2, 1;
}
void add_point(c_point& pnt)
{
points.push_back(pnt);
}
void reset()
{
points.clear();
}
vector <c_point> points;
double min_x, max_x;
double min_y, max_y;
Vector2d diam;
Vector3d center; // homogeneous
};
class c_sensor_region
{
public:
double id;
vector <double> x;
};
class c_world_region
{
public:
double id;
vector <double> X;
};
class c_actuator
{
public:
c_actuator()
{
for (int i = 0; i < num_arm_joints; i++)
{
joint_RT[i] = Matrix4d::Identity();
}
joint_axis[0] << 0, 1, 0;
for (int i = 1; i < num_arm_joints; i++)
{
joint_axis[i] << 1, 0, 0;
}
for (int i = 0; i < num_arm_joints; i++)
{
joint_orig[i] << 0, 0, 0;
}
ang_mult = 1.0;
calculate_RT_from_joint_RT();
}
void calculate_joint_transformations(const c_actuator& prev_actuator)
{
auto& prev_ang_vel = prev_actuator.ang_vel;
double dt = 1.0;
for (int i = 0; i < num_arm_joints; i++)
{
Matrix4d M;
M << 1, -dt*prev_ang_vel[i]*joint_axis[i](2), dt*prev_ang_vel[i] * joint_axis[i](1), joint_orig[i](0),
dt*prev_ang_vel[i] * joint_axis[i](2), 1, -dt*prev_ang_vel[i] * joint_axis[i](0), joint_orig[i](1),
-dt*prev_ang_vel[i] * joint_axis[i](1), dt*prev_ang_vel[i] * joint_axis[i](0), 1, joint_orig[i](2),
0, 0, 0, 1;
joint_RT[i] = M*prev_actuator.joint_RT[i]; // (NB 15, p.136)
}
calculate_RT_from_joint_RT();
}
void get_RT_inv(Matrix3d& R, Vector3d& T)
{
R = RT_inv.topLeftCorner(3, 3);
T = RT_inv.topRightCorner(3, 1);
}
Vector3d joint_axis[num_arm_joints];
Vector3d joint_orig[num_arm_joints];
MatrixXd joint_RT[num_arm_joints]; // transformation from a reference frame fixed to the link k to a reference frame fixed to the link k+1
double ang_vel[num_arm_joints];
double ang_mult;
MatrixXd RT; // transformation from a reference frame fixed to the link 0 to a reference frame fixed to the link num_arm_joints
MatrixXd RT_inv;
protected:
void calculate_RT_from_joint_RT()
{
RT = joint_RT[0];
for (int i = 1; i < num_arm_joints; i++)
{
RT = joint_RT[i] * RT;
}
RT_inv = RT.inverse();
}
};
class c_time_slot
{
public:
c_time_slot()
{
K_inv = MatrixXd::Identity(3, 3);
}
vector<MatrixXd> rgb_channels;
vector <c_sensor_region> sensor_regions;
vector <c_world_region> world_regions;
vector <c_statistic_channel> statistic_channels;
std::map<c_range_key, c_point_set, c_range_key> point_sets;
std::map<c_range_key, Vector3d, c_range_key> obs_X;
std::map<c_range_key, Vector3d, c_range_key> pred_X;
c_actuator actuator;
MatrixXd K_inv;
};
class c_learner
{
public:
c_learner(param_context& _pc)
{
pc = _pc;
}
void read_sensors()
{
// output: add to the back of rgb_channels
}
void send_actuator_commands()
{
std::uniform_int_distribution<> distribution(-1, 1);
if (pc.seed_random_engines)
{
actuator_command_generator.seed(time(NULL));
}
auto cur_ts = time_slots.rbegin();
for (int i = 0; i < num_arm_joints; i++)
{
cur_ts->actuator.ang_vel[i] = distribution(actuator_command_generator);
}
}
void calculate_statistic_point_sets(vector <c_statistic_channel>& statistic_channels, std::map<c_range_key, c_point_set, c_range_key>& point_set_map)
{
int x, y;
vector<int> ranges;
ranges.resize(statistic_channels.size());
point_set_map.clear();
int width = statistic_channels[0].statistic_val.cols();
int height = statistic_channels[0].statistic_val.rows();
c_point pnt;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
pnt.x = x;
pnt.y = y;
for (int c = 0; c < statistic_channels.size(); c++)
{
if (statistic_channels[c].range_length == 0)
ranges[c] = 0;
else
{
ranges[c] = (statistic_channels[c].statistic_val(y, x) - statistic_channels[c].minCoeff) / statistic_channels[c].range_length;
if (ranges[c] < 0) ranges[c] = 0;
if (ranges[c] > pc.num_chan_ranges) ranges[c] = pc.num_chan_ranges;
}
}
c_range_key range_key;
range_key.ranges = ranges;
// add point to the neighbouring ranges too
for (int c = 0; c < statistic_channels.size(); c++)
{
// check neighbouring ranges for cases when statistic is on a range boundary
for (int j = -1; j <= 1; j++)
{
if (c > 0 && j == 0)
continue; // otherwise not perturbed ranges is added multiple times to the same point set (num_statistic_channels to be exact)
c_range_key rk;
rk.ranges = ranges;
rk.ranges[c] += j;
c_point_set& ps = point_set_map[rk];
ps.add_point(pnt);
}
}
}
}
for (auto it = point_set_map.begin(); it != point_set_map.end(); ++it)
{
it->second.calculate_boundaries();
}
}
void calculate_sensor_identities()
{
// input: rgb_channels
// output: sensor_regions
int width = time_slots.back().rgb_channels[0].cols();
int height = time_slots.back().rgb_channels[0].rows();
auto& statistic_channels = time_slots.back().statistic_channels;
for (int c = 0; c < time_slots.back().rgb_channels.size(); c++) {
for (int s = 0; s < pc.num_stat_components; s++)
{
statistic_channels.push_back(c_statistic_channel());
statistic_channels.back().calculate_image_statistic(pc, time_slots.back().rgb_channels[c], statistics[s]);
}
}
calculate_statistic_point_sets(statistic_channels, time_slots.back().point_sets);
// filter corresponence sets by set size
int statistic_localization_x = width*pc.statistic_localization;
int statistic_localization_y = height*pc.statistic_localization;
auto& point_sets = time_slots.back().point_sets;
for (auto it = point_sets.begin(); it != point_sets.end(); )
{
const c_range_key* prk = &it->first;
c_point_set* ps = &it->second;
if (ps->points.size() == 0)
{
it = point_sets.erase(it);
continue;
}
if (!(ps->diam(0) < statistic_localization_x && ps->diam(1) < statistic_localization_y))
{
it = point_sets.erase(it);
continue;
}
++it;
}
}
void calculate_non_observed_world_from_behaviour()
{
auto cur_ts = time_slots.rbegin();
auto prev_ts = std::next(cur_ts);
cur_ts->pred_X = prev_ts->obs_X;
}
void reconcile_observed_non_observed_worlds(double& max_diff)
{
auto cur_ts = time_slots.rbegin();
max_diff = 0;
for (auto it = cur_ts->obs_X.begin(); it != cur_ts->obs_X.end(); ++it)
{
const c_range_key* prk = &it->first;
auto& obs_X = it->second;
auto& pred_X = cur_ts->pred_X[*prk];
double diff = (obs_X - pred_X).norm();
if (diff > max_diff)
max_diff = diff;
}
}
void calculate_observed_world()
{
// input: sensor_regions
// output world_regions
auto cur_ts = time_slots.rbegin();
auto prev_ts = std::next(cur_ts);
cur_ts->actuator.calculate_joint_transformations(prev_ts->actuator);
for (auto it = prev_ts->point_sets.begin(); it != prev_ts->point_sets.end(); ++it)
{
const c_range_key* prk = &it->first;
c_point_set* prev_ps = &it->second;
c_point_set* cur_ps = &cur_ts->point_sets[*prk];
if (prev_ps->points.size() == 0 || cur_ps->points.size() == 0)
continue;
// calculate obs_X in the reference frame of the camera at previous time slot (NB 15,pp.133, 136)
Matrix3d R;
Vector3d T;
prev_ts->actuator.get_RT_inv(R, T);
Vector3d p1 = T;
Vector3d d1 = R*prev_ts->K_inv*prev_ps->center;
cur_ts->actuator.get_RT_inv(R, T);
Vector3d p2 = T;
Vector3d d2 = R*cur_ts->K_inv*cur_ps->center;
Vector3d n2 = d2.cross(d1.cross(d2));
cur_ts->obs_X[*prk] = p1 + (p2 - p1).dot(n2) / (d1.dot(n2))*d1;
}
}
void try_decrease_error()
{
/*
K_inv, ang_mult, joint_axis, joint_orig,
joint_RT[i] for time slot 0
statistics
*/
}
/*
time
t sensor_input
actuator_command
t+1 sensor_input
actuator_command
reconstruction: sensor_input(cur_t-1), sensor_input, actuator_command(cur_t-1) -> observed_world_id_X
observed_world_id_X -> non_observed_world_id_X
t+2 sensor_input
actuator_command
reconstruction: sensor_input(cur_t-1), sensor_input, actuator_command(cur_t-1) -> observed_world_id_X
behaviour: non_observed_world_id_X(cur_t-1) -> non_observed_world_id_X
compare_world: observed_world_id_X, non_observed_world_id_X -> error, non_observed_world_id_X
if error is significant, then modify reconstruction and/or behaviour
t+3 sensor_input
actuator_command
reconstruction: sensor_input(cur_t-1), sensor_input, actuator_command(cur_t-1) -> observed_world_id_X
behaviour: non_observed_world_id_X(cur_t-1) -> non_observed_world_id_X
compare_world: observed_world_id_X, non_observed_world_id_X -> error, non_observed_world_id_X
if error is significant, then modify reconstruction and/or behaviour
---------------------------------------------------------------------------------------------------
The permanent assignment of X to id for observed and non_observed worlds would be a zero error solution,
if only compare_world is used, even though a live system would perish.
A real test should be comparing the predicted and actual sensor inputs.
*/
void learn()
{
double max_diff;
calculate_sensor_identities();
if (time_slots.size() <= 1)
return;
calculate_observed_world();
calculate_non_observed_world_from_behaviour();
reconcile_observed_non_observed_worlds(max_diff);
try_decrease_error();
}
void initialize_learning_procedures_and_parameters()
{
statistics.clear();
for (int i = 0; i < pc.num_stat_components; i++)
{
c_statistic statistic;
statistic.calculate_linear_statistic_parameters(pc);
statistics.push_back(statistic);
}
}
void run()
{
initialize_learning_procedures_and_parameters();
while (true)
{
time_slots.push_back(c_time_slot());
read_sensors();
learn();
send_actuator_commands();
}
}
param_context pc;
list<c_time_slot> time_slots;
vector <c_statistic> statistics;
std::default_random_engine actuator_command_generator;
};
} | true |
5d13b4187eb825d33f74672b4711fd9f1cdc021c | C++ | jwurzer/glslScene | /include/gs/system/file_change_monitoring.h | UTF-8 | 9,097 | 2.65625 | 3 | [
"LicenseRef-scancode-public-domain",
"Zlib",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #ifndef GLSLSCENE_FILE_CHANGE_MONITORING_H
#define GLSLSCENE_FILE_CHANGE_MONITORING_H
#include <string>
#include <memory>
#include <map>
#include <set>
#include <thread>
#include <mutex>
#if defined(_MSC_VER)
//#define _WIN32_WINNT 0x0550
#include <windows.h>
#endif
namespace gs
{
/**
* Supports linux and windows. On windows the callback function for changes is delayed by 300ms.
* The delay is necessary to prevent multiple calls for one file modification.
* See: https://stackoverflow.com/questions/14036449/c-winapi-readdirectorychangesw-receiving-double-notifications
*/
class FileChangeMonitoring
{
public:
/**
* @param callbackId This is the callback id which was returned by addFile().
* @param filename This is the original filename which was used by
* the function call addFile().
* @param param1 This is the parameter which was used by
* the function call addFile().
* @param param2 This is the parameter which was used by
* the function call addFile().
*/
typedef void (*TCallback)(unsigned int callbackId,
const std::string& filename,
const std::shared_ptr<void>& param1, void* param2);
FileChangeMonitoring(bool useSeparateMonitoringThread);
~FileChangeMonitoring();
/**
* Add a file with full path (relative or absolute) for monitoring.
* The parent directory of this file must exist. The file itself
* can exist but doesn't have to exist.
* If a file like "foo.txt" is added then the directory "." is used.
*
* If this added file is changed (write changed), or created, or
* renamed to the added filename then the callback function will
* be called.
*
* return Return the callback id. 0 for error or greater zero for success (= callback id).
*/
unsigned int addFile(const std::string& filename, TCallback callback,
const std::shared_ptr<void>& param1, void* param2);
/**
* @param callbackId To remove a file the callback id which was returned
* by addFile() is necessary.
* @return True for success (file is removed). False for error.
*/
bool removeFile(unsigned int callbackId);
void removeAllFiles();
std::string toString() const;
void checkChanges();
// private:
class Callback
{
public:
unsigned int mFileCallbackId;
TCallback mCbFunc;
std::shared_ptr<void> mParam1;
void* mParam2;
// full filename with some "nice" modifications. Like foo.txt will
// be ./foo.txt or foo///a//b.txt will be foo/a/b.txt.
std::string mFilename;
// This is the original filename which was used for the function
// call addFile().
std::string mOrigFilename;
unsigned int mCallCount;
Callback(unsigned int fileCallbackId,
TCallback callbackFunc, const std::shared_ptr<void>& param1,
void* param2, const std::string& filename,
const std::string& origFilename)
:mFileCallbackId(fileCallbackId), mCbFunc(callbackFunc),
mParam1(param1), mParam2(param2), mFilename(filename),
mOrigFilename(origFilename), mCallCount(0) {}
};
typedef std::map<unsigned int /* callback id */, Callback> TCallbackMap;
class Filename
{
public:
// filename without path. e.g. for filename ./foo/a/b.txt the
// basename b.txt will be stored.
std::string mBasename;
TCallbackMap mCallbacks;
Filename(const std::string& basename,
const std::string& filename,
const std::string& origFilename,
unsigned int fileCallbackId,
TCallback callbackFunc,
const std::shared_ptr<void>& param1,
void* param2)
:mBasename(basename), mCallbacks()
{
mCallbacks.insert(TCallbackMap::value_type(fileCallbackId,
Callback(fileCallbackId, callbackFunc, param1, param2, filename, origFilename)));
}
};
typedef std::map<std::string /* basename */, Filename> TFilenameMap;
// FileEntry is used for a directory and stores all names from
// regular files which should be watched.
class FileEntry
{
public:
FileEntry(
FileChangeMonitoring* fileChangeMonitoring,
#if defined(_MSC_VER)
HANDLE watchId,
#else
int watchId,
#endif
const std::string& watchname, // directory of watchId
const std::string& filename,
const std::string& origFilename,
unsigned int fileCallbackId, TCallback callbackFunc,
const std::shared_ptr<void>& param1, void* param2);
/**
* @param filename Full "nice" filename like foo/a/b.txt
* @param origFilename Full original filename like foo////a//b.txt
*/
bool addFile(const std::string& filename,
const std::string& origFilename, bool mustExist,
unsigned int fileCallbackId, TCallback callbackFunc,
const std::shared_ptr<void>& param1, void* param2);
bool removeFile(const std::string& filename, unsigned int callbackId,
std::string& filenameForCallback,
bool& wasRemovedFromMap);
bool isFile(const std::string& filename, unsigned int callbackId) const;
// return null if not found
Callback* getCallbackForFile(const std::string& filename, unsigned int callbackId);
const Callback* getCallbackForFile(const std::string& filename, unsigned int callbackId) const;
Filename* getFilenameForFile(const std::string& filename);
const Filename* getFilenameForFile(const std::string& filename) const;
unsigned int getFilenameCount(const std::string& filename) const;
std::string toString() const;
void setOrAddWatchDir(const std::string& watchDir) { mWatchnames.insert(watchDir); }
#if defined(_MSC_VER)
HANDLE getWatchId() const { return mWatchId; }
#else
int getWatchId() const { return mWatchId; }
#endif
const std::set<std::string>& getWatchnames() const { return mWatchnames; }
size_t getWatchIdCount() const { return mNames.size(); }
TFilenameMap& getNames() { return mNames; }
const TFilenameMap& getNames() const { return mNames; }
FileChangeMonitoring* getFileChangeMonitoring() const { return mFcm; }
#if defined(_MSC_VER)
HANDLE mWatchId;
std::set<std::string> mWatchnames;
OVERLAPPED mOverlapped;
DWORD mNotifyFilter;
BYTE mBuffer[32 * 1024];
private:
#else
private:
int mWatchId;
std::set<std::string> mWatchnames;
#endif
// watch count is the count how often inotify_add_watch() return the
// same watch id
// unsigned int mWatchIdCount; // is removed. same as mNames.size()
// key is the basename (not the filename)
TFilenameMap mNames;
FileChangeMonitoring* mFcm;
};
class FileEntryCountPair
{
public:
// Count the watched files with the same filename (not original
// filename, the "nice" filename is used)
unsigned int mCount;
std::shared_ptr<FileEntry> mFileEntry;
FileEntryCountPair() :mCount(0), mFileEntry() {}
};
class FileEntryNamePair
{
public:
std::string mBasename;
std::shared_ptr<FileEntry> mFileEntry;
FileEntryNamePair() :mBasename(), mFileEntry() {}
FileEntryNamePair(const std::string& name,
const std::shared_ptr<FileEntry>& fileEntry)
:mBasename(name), mFileEntry(fileEntry)
{}
};
#if defined(_MSC_VER)
typedef std::map<HANDLE /* watch id */, std::shared_ptr<FileEntry> > TFileMapByWatchId;
#else
typedef std::map<int /* watch id */, std::shared_ptr<FileEntry> > TFileMapByWatchId;
#endif
typedef std::map<std::string /* watchdir */, std::shared_ptr<FileEntry> > TFileMapByWatchDir;
typedef std::map<std::string /* filename */, FileEntryCountPair> TFileMapByName;
typedef std::map<unsigned int /* callback id */, FileEntryNamePair> TFileMapByCallbackId;
typedef std::map<unsigned int /* callback id */, uint32_t /* last change ts */> TChangeMapByCallbackId;
void lock() const { mSync.lock(); }
unsigned int getCallCount() const { return mFileChangeMonitoringCallCount; }
const TFileMapByWatchId& getFilesByWatchId() const { return mFilesByWatchId; }
const TFileMapByWatchDir& getFilesByWatchDir() const { return mFilesByWatchDir; }
const TFileMapByName& getFilesByName() const { return mFilesByName; }
const TFileMapByCallbackId& getFilesByCallbackId() const { return mFilesByCallbackId; }
void unlock() const { mSync.unlock(); }
private:
bool mUseSeparateMonitoringThread;
bool mRunning;
int mInotifyFd;
std::thread mMonitoringThread;
TChangeMapByCallbackId mChangeMap;
// Files which are changed at some directories which are monitored.
// The changed file itself don't need to be a monitoring file.
unsigned int mFileChangeCount;
// Files which are changed and monitored!!!!
unsigned int mFileChangeMonitoringCallCount;
TFileMapByWatchId mFilesByWatchId;
TFileMapByWatchDir mFilesByWatchDir;
TFileMapByName mFilesByName;
TFileMapByCallbackId mFilesByCallbackId;
unsigned int mNextFileCallbackId;
mutable std::mutex mSync;
static void *posixMonitoringThread(void *thisFileChangeMonitoring);
void monitoringThread();
int monitoringFileChanges();
#if defined(_MSC_VER)
static void CALLBACK FileChangedCallback(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped);
#endif
};
}
#endif /* FILE_CHANGE_MONITORING_H */
| true |
e56beecf95ae4c8d99c92db9eaf168c17c24cef1 | C++ | assassint2017/leetcode-algorithm | /Combinations/Combinations.cpp | UTF-8 | 1,113 | 3.453125 | 3 | [] | no_license | // 典型的回溯法
// Runtime: 84 ms, faster than 66.79% of C++ online submissions for Combinations.
// Memory Usage: 11.8 MB, less than 66.84% of C++ online submissions for Combinations.
class Solution
{
public:
vector<vector<int>> combine(int n, int k)
{
// 边界条件处理
if (k <= 0 || n <= 0 || k > n)
return vector<vector<int>>();
vector<int> candidate(n, 0);
for (int i = 0; i < n; ++i)
candidate[i] = i + 1;
vector<vector<int>> res;
vector<int> temp;
helper(res, candidate, temp, 0, k);
return res;
}
private:
void helper(vector<vector<int>>& res, vector<int>& candidate, vector<int>& temp, int start, int k)
{
if (temp.size() == k)
{
res.push_back(temp);
return ;
}
for (int i = start; i < candidate.size(); ++i)
{
temp.push_back(candidate[i]);
helper(res, candidate, temp, i + 1, k);
temp.pop_back();
}
}
}; | true |
0ddd35e43fa76b1276a6aed1f0d0e799da3adf24 | C++ | alvesrod/tableproject | /Engine/roomcontroller.cpp | UTF-8 | 33,480 | 2.875 | 3 | [] | no_license | #include "roomcontroller.h"
RoomController::RoomController(RoomDescription *description, UserSettings *settings)
{
if (description == NULL) {
qWarning() << "Cannot instantiate a Room Controller without a Room Description.";
return;
}
/* Make sure the Engine is running: */
if (!Engine::isRunning()) {
qCritical() << "[ERROR] Engine class called, but Engine was not started!";
return;
}
totalOfGenericMessages = 0;
currentUserID = -1;
hasLeftRoom = false;
currentUser = NULL; //You don't know who you are until the host tells you.
hostUser = NULL;
chatroom = NULL;
userSettings = settings;
roomDescription = description;
roomDescription->setParent(this);
/* Prepare and start the Network: */
networkThread = new Network(this);
networkThread->start();
setupNetworkConnections();
if (DISPLAY_RC_DEBUG_MESSAGES)
qDebug() << "[RoomSettings] A new Room has been declared.";
}
RoomController::~RoomController()
{
leaveRoom();
/* Delete the network thread when it is finished: */
connect(networkThread, SIGNAL(finished()), networkThread, SLOT(deleteLater()));
networkThread->exit();
if (DISPLAY_RC_DEBUG_MESSAGES)
qDebug() << "Room Controller deleted.";
}
/** ===== TWO MAIN NETWORK METHODS (SEND AND RECEIVE): ===== **/
/**
This function receives a message from the network.
It reads the message to decide what to do with it and
which signals to emit:
*/
void RoomController::networkMessageReceived(qint32 sender, QByteArray package)
{
//Prepare message to be read:
QByteArray message;
qint8 type;
QDataStream packageStream(package);
User *senderProfile = NULL;
packageStream >> type; //Take the type of message out of the package.
packageStream >> message; //Take the message out of the package.
if (DISPLAY_RC_DEBUG_MESSAGES)
qDebug() << "[RoomController] Received message type" << type << "from" << sender;
/*
* Move on without a sender only if message is from host or from type(s):
* MSG_PREPARE_ROOM_REPLY, MSG_PREPARE_ROOM, MSG_REQUEST_ROOM_INFO,
* MSG_ROOM_PREPARED, MSG_REMOVE_USER, MSG_REQUEST_ROOM_INFO_REPLY
* MSG_ACTION, MSG_ACTION_HOST, MSG_OTHER.
*/
if (!getSenderAndCheckMessage(sender, senderProfile, type)) return;
//Read message:
switch (type) {
case MSG_PREPARE_ROOM:
prepareRoomReadMessage(senderProfile, message, sender);
break;
case MSG_PREPARE_ROOM_REPLY:
prepareRoomReplyReadMessage(sender, message);
break;
case MSG_ROOM_PREPARED:
roomPreparedMessage(message, sender);
break;
case MSG_BAN_USER:
leaveRoom();
emit banned();
break;
case MSG_REMOVE_USER:
leaveRoom();
emit leftRoom();
break;
case MSG_REQUEST_ROOM_INFO:
prepareRequestRoomInfoMessage(sender);
break;
case MSG_REQUEST_ROOM_INFO_REPLY:
roomDescription->setDataPackage(message);
emit roomHasInfoReady();
break;
case MSG_PING:
preparePingMessage(message);
break;
case MSG_PING_REPLY:
preparePingMessageReply(message);
break;
case MSG_CHAT_MESSAGE:
emit chatMessageReceived(message, senderProfile);
break;
case MSG_PRIVATE_CHAT_MESSAGE:
emit privateChatMessageReceived(privateMessageCrypt(message, sender, currentUserID), senderProfile);
break;
case MSG_EDIT_ROOM_MEMBER:
prepareUserMessage(message, senderProfile);
break;
case MSG_ACTION:
case MSG_ACTION_HOST:
emit actionMessageReceived(message, senderProfile);
break;
case MSG_RANDOM_VALUE:
prepareRandomValueMessage(message, senderProfile);
break;
case MSG_RANDOM_VALUE_REPLY:
prepareRandomValueMessageReply(message, senderProfile);
break;
case MSG_DOWNLOAD:
emit downloadMessageReceived(message, senderProfile);
break;
case MSG_OTHER:
default :
dealWithGenericMessageReceived(message, senderProfile);
}
}
/**
This function sends a message to the network.
It writes the message based on its type:
*/
void RoomController::sendMessageToServerByID(RoomController::NetworkMessageTypes type, QByteArray message, qint32 msgTo, bool isTCP)
{
//Prepare message to be sent:
QByteArray package;
QDataStream packageStream(&package, QIODevice::WriteOnly); //Opens a package to be read
packageStream << (qint8) type; //Add the type of the message into the package.
if (DISPLAY_RC_DEBUG_MESSAGES)
qDebug() << "Sent message type" << type << "to" << msgTo;
switch (type) {
case MSG_PREPARE_ROOM:
packageStream << getPrepareRoomMessage();
if (makeSureUserSettingsIsDeclared())
sendPackage(DESCRIPTOR_CODE_FOR_HOST, package, TCP_MESSAGE);
break;
case MSG_ROOM_PREPARED:
packageStream << getRoomPreparedMessage();
sendPackage(BROADCAST_DESCRIPTOR, package, TCP_MESSAGE); //send to all because everyone wants the user's nickname.
break;
case MSG_REQUEST_ROOM_INFO:
packageStream << message;
sendPackage(DESCRIPTOR_CODE_FOR_HOST, package, TCP_MESSAGE);
break;
case MSG_REQUEST_ROOM_INFO_REPLY:
roomDescription->setTotalUsersInRoom( users.size() );
roomDescription->setHostNicknamePrediction( currentUser->getNickname() );
packageStream << roomDescription->getBasicDataPackage();
sendPackage(msgTo, package, isTCP);
break;
case MSG_PING:
packageStream << getPreparePingMessage();
if (msgTo == BROADCAST_DESCRIPTOR) return;
sendPackage(msgTo, package, UDP_MESSAGE);
break;
case MSG_BAN_USER:
addUserToBannedList(msgTo);
packageStream << message;
sendPackage(msgTo, package, TCP_MESSAGE);
break;
case MSG_RANDOM_VALUE:
packageStream << message;
sendPackage(DESCRIPTOR_CODE_FOR_HOST, package, isTCP);
break;
case MSG_ACTION_HOST:
packageStream << message;
sendPackage(DESCRIPTOR_CODE_FOR_HOST, package, isTCP);
break;
case MSG_PRIVATE_CHAT_MESSAGE:
packageStream << privateMessageCrypt(message, currentUserID, msgTo);
sendPackage(msgTo, package, isTCP);
break;
default :
packageStream << message;
sendPackage(msgTo, package, isTCP);
}
}
void RoomController::sendMessageToServer(NetworkMessageTypes type, QByteArray message, User *to, bool isTCP)
{
qint32 msgTo = (to == TO_EVERYONE)? BROADCAST_DESCRIPTOR : to->getUniqueID();
sendMessageToServerByID(type, message, msgTo, isTCP);
}
/** GETTERS AND SETTERS: **/
QHash<qint32, User*> RoomController::getListOfUsers() { return users; }
QList<User *> RoomController::getPrimitiveListOfUsers() {
return users.values();
}
User *RoomController::getCurrentUser() { return currentUser; }
User *RoomController::getHostUser() { return hostUser; }
RoomDescription* RoomController::getRoomDescription() { return roomDescription; }
bool RoomController::isHost() { return roomDescription->isHostRoom(); }
UserSettings *RoomController::getUserSettings() { return userSettings; }
void RoomController::setPassword(QString password) { roomDescription->setPassword(password); }
QString RoomController::getPassword() { return roomDescription->getPassword(); }
void RoomController::setChatroom(ChatRoom *chat) { chatroom = chat; }
ChatRoom *RoomController::getChatroom() { return chatroom; }
/** ===== PUBLIC NETWORK METHODS: ===== **/
void RoomController::startNewServer()
{
generatedKey = generateRoomCryptKey(); //Get a random key for the room.
emit networkStartNewServer( roomDescription->getRoomPort() );
}
void RoomController::closeServer()
{
/* Only the host can close the server: */
if (!isHost()) return;
/* Don't remove the published room if the server as closed
before joining the room. The room will only be published
AFTER you joined the room. */
if (currentUser != NULL) {
/* Ask the WebContact to remove this room from the public list: */
connect(this, SIGNAL(removePublishedRoom(qint32)), WebContact::getInstance(), SLOT(removePublishedRoom(qint32)), Qt::QueuedConnection);
emit removePublishedRoom( roomDescription->getRoomPort() );
}
/* Signal the network to close the port: */
emit networkCloseServer();
}
void RoomController::disconnectFromServer()
{
emit networkDisconnectFromServer();
}
void RoomController::leaveRoom()
{
if (hasLeftRoom) return; //Make sure the user didn't leave the room already
hasLeftRoom = true;
disconnectFromServer();
if (isHost())
closeServer();
}
void RoomController::sendDownloadMessageToServer(QByteArray message, User *to)
{
sendMessageToServer(MSG_DOWNLOAD, message, to, true);
}
void RoomController::connectToServer() {
hasLeftRoom = false;
emit networkConnectToServer( roomDescription->getRoomIp() , roomDescription->getRoomPort() );
}
/** ===== PRIVATE NETWORK SLOTS: ===== **/
void RoomController::networkErrorMessage(QString error) { emit errorMessage(error); }
void RoomController::networkDisconnectedFromServer(bool success) { emit disconnectedFromServer(success); }
void RoomController::networkServerStarted(bool started, quint16 port)
{
getRoomDescription()->setRoomPort(port);
emit serverStarted(started);
}
void RoomController::networkConnectedToServer(bool connected) { emit connectedToServer(connected); }
void RoomController::networkMessageSent(bool sent) { emit messageSent(sent); }
void RoomController::networkServerClosed(bool closed) { emit serverClosed(closed); }
void RoomController::someoneDisconnected(qint32 descriptor)
{
//If the user was in the loading screen, removes it from the "comingUsers" array:
removeUserFromComingUsersArray(descriptor);
User *user = searchUser(descriptor);
if (user == NULL) {
if (isHost())
if (!isInPingUsersList(descriptor)) //Maybe the user was just cheking out the room
addUserToLatestUnknownDisconnects(descriptor);
} else {
if (user == currentUser) {
qDebug() << "You are leaving the Room.";
}
user->setIsOnline(false);
emit someoneDisconnectedFromServer(user);
users.remove(user->getUniqueID());
roomDescription->setTotalUsersInRoom( users.size() );
}
}
/**
Connect network signal and slots:
QueuedConnections are important because the network is in a different thread.
**/
void RoomController::setupNetworkConnections()
{
connect(this, SIGNAL(networkStartNewServer(qint32)), networkThread, SLOT(startNewServer(qint32)), Qt::QueuedConnection);
connect(this, SIGNAL(networkConnectToServer(QString,qint32)), networkThread, SLOT(connectToServer(QString,qint32)), Qt::QueuedConnection);
connect(this, SIGNAL(networkSendMessageToServer(QByteArray,qint32, bool)), networkThread, SLOT(sendMessageToServer(QByteArray, qint32, bool)), Qt::QueuedConnection);
connect(this, SIGNAL(networkCloseServer()), networkThread, SLOT(closeServer()), Qt::QueuedConnection);
connect(this, SIGNAL(networkDisconnectFromServer()), networkThread, SLOT(disconnectFromServer()), Qt::QueuedConnection);
connect(networkThread, SIGNAL(networkMessage(qint32, QByteArray)), this, SLOT(networkMessageReceived(qint32, QByteArray)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(errorMessage(QString)), this, SLOT(networkErrorMessage(QString)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(disconnectedFromServer(bool)), this, SLOT(networkDisconnectedFromServer(bool)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(serverStarted(bool,quint16)), this, SLOT(networkServerStarted(bool,quint16)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(connectedToServer(bool)), this, SLOT(networkConnectedToServer(bool)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(messageSent(bool)), this, SLOT(networkMessageSent(bool)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(serverClosed(bool)), this, SLOT(networkServerClosed(bool)), Qt::QueuedConnection);
connect(networkThread, SIGNAL(someoneDisconnected(qint32)), this, SLOT(someoneDisconnected(qint32)), Qt::QueuedConnection);
}
User* RoomController::searchUser(qint32 id) //Return NULL if not found
{
return users.value(id, NULL);
}
bool RoomController::addUser(User *user)
{
if (user == NULL) {
qCritical() << "[ERROR] Trying to add a null user.";
return false;
}
//If the user was in the loading screen, removes it from the "comingUsers" array:
removeUserFromComingUsersArray(user->getUniqueID());
User* other = searchUser(user->getUniqueID());
if (other != NULL) {
qWarning() << "User (" << user->getUniqueID() << ") already found in database.";
if (user != other) user->deleteLater(); //delete only if they don't share the same pointer.
return false;
}
user->setIsOnline(true);
user->makeNameUnique( getPrimitiveListOfUsers() );
if (DISPLAY_RC_DEBUG_MESSAGES)
qDebug() << "User" << user->getUniqueID() << "added to the Room.";
users[user->getUniqueID()] = user;
roomDescription->setTotalUsersInRoom( users.size() );
return true;
}
bool RoomController::isRoomFull()
{
return ( (users.size() + comingUsers.size()) >= roomDescription->getMaxNumberOfUsers());
}
QByteArray RoomController::getPrepareRoomMessage()
{
QByteArray message;
QDataStream messageStream(&message, QIODevice::WriteOnly);
messageStream << Engine::getAppVersion();
messageStream << Engine::getEngineVersion();
messageStream << roomDescription->getPassword();
QString ip;
if (isHost())
ip = QString(LOCAL_IP); //Host has a local ip.
else
ip = userSettings->getIp();
messageStream << ip;
messageStream << getSecretApplicationKey(ip);
return message;
}
QByteArray RoomController::getRoomPreparedMessage()
{
QByteArray message;
QDataStream messageStream(&message, QIODevice::WriteOnly);
messageStream << userSettings;
return message;
}
QByteArray RoomController::getPreparePingMessage()
{
QByteArray message;
QDataStream messageStream(&message, QIODevice::WriteOnly);
messageStream << currentUserID;
return message;
}
void RoomController::prepareRequestRoomInfoMessage(qint32 id)
{
addToPingUsersList(id);
sendMessageToServerByID(MSG_REQUEST_ROOM_INFO_REPLY, 0, id);
}
void RoomController::sendPackage( qint32 to, QByteArray package, bool TCP )
{
emit networkSendMessageToServer(package, to, TCP);
}
void RoomController::prepareRoomReplyReadMessage( qint32 sender, QByteArray message )
{
//Break the reply and get all the information about the Room:
qint8 answer;
QString version, engineVersion;
QDataStream messageStream(message);
messageStream >> answer;
switch (answer) {
case ANSWER_ROOM_FULL:
emit roomPrepared(false, tr("The room is full."));
break;
case ANSWER_DISCONNECTED_RECENTLY:
case ANSWER_DENIED_OTHER:
emit roomPrepared(false, tr("The host refused your connection for some reason. Please, try again in ")
+ QString::number(TIMEOUT_WAITING_DISCONNECT_SECONDS) + tr(" seconds."));
break;
case ANSWER_WRONG_VERSION:
messageStream >> version;
messageStream >> engineVersion;
emit roomPrepared(false, tr("Wrong version. Your version is") + " " + Engine::getAppVersion()
+ " (" + tr("engine") + " " + Engine::getEngineVersion() + ") "
+ tr("and this room is using version") + " " + version + " ("
+ tr("engine") + " " + Engine::getEngineVersion() + "). ");
break;
case ANSWER_WRONG_APP_KEY:
emit roomPrepared(false, tr("The host application is different from yours."));
break;
case ANSWER_WRONG_PASSWORD:
emit roomPrepared(false, tr("Wrong password."));
break;
case ANSWER_ALLOWED:
prepareRoom(sender, messageStream);
break;
case ANSWER_BANNED:
emit roomPrepared(false, tr("The host did not allow you to join this room."));
break;
default :
qDebug() << "Received an invalid answer: " << answer;
}
}
void RoomController::prepareUserMessage(QByteArray message, User* senderProfile)
{
QDataStream messageStream(message);
qint32 memberID;
QByteArray memberMessage;
messageStream >> memberID;
messageStream >> memberMessage;
User *memberToEdit = searchUser(memberID);
if (memberToEdit == NULL) {
qWarning() << "Tried to edit the profile of a member" << memberID << "who is not in the room.";
return;
}
memberToEdit->handleMessage(memberMessage, senderProfile);
}
void RoomController::prepareRandomValueMessage(QByteArray message, User *senderProfile)
{
if (!isHost()) {
qDebug() << "[RoomController] You received a message that only the host should have received.";
return;
}
QDataStream messageStream(message);
qint32 min, max, random, to, count;
qint16 type;
messageStream >> min;
messageStream >> max;
messageStream >> type;
messageStream >> count;
messageStream >> to;
if ( (min >= max) || (count < 1) || (count > MAX_RANDOM_VALUES_COUNT) ) {
qCritical() << "[RoomController error] Received an invalid random value [" << min << "," << max << "|" << count << "].";
qDebug() << "[RoomController] Max num of random values allowed:" << MAX_RANDOM_VALUES_COUNT;
return;
}
//Build the reply:
QByteArray reply;
QDataStream replyStream(&reply, QIODevice::WriteOnly);
replyStream << min;
replyStream << max;
replyStream << type;
replyStream << count;
QList<qint32> values;
for (qint32 i = 0; i < count; i++) {
random = ( qrand() % (max-min+1) ) + min;
values << random;
}
replyStream << values;
replyStream << senderProfile->getUniqueID();
//Send reply:
sendMessageToServerByID(MSG_RANDOM_VALUE_REPLY, reply, to);
}
void RoomController::prepareRandomValueMessageReply(QByteArray message, User *senderProfile)
{
if (!senderProfile->isTheHost()) {
qDebug() << "[RoomController error] Received random value, but not from the host. Message ignored.";
return;
}
QDataStream messageStream(message);
qint32 min, max, from, count;
qint16 type;
messageStream >> min;
messageStream >> max;
messageStream >> type;
messageStream >> count;
if (count > MAX_RANDOM_VALUES_COUNT) {
qWarning() << "[RoomController error] Received more random values than allowed. The limit is " << MAX_RANDOM_VALUES_COUNT;
return;
}
if (min >= max) {
qWarning() << "[RoomController error] Received an invalid boundary [" << min << ", " << max << "].";
return;
}
QList<qint32> values;
messageStream >> values;
if (values.size() != count) {
qWarning() << "[RoomController error] Received " << values.size() << "values. Expecting: " << count;
return;
}
messageStream >> from;
senderProfile = searchUser(from);
if (senderProfile == NULL) {
qWarning() << "[RoomController error] Received a random value from a user who is not in the room. Message ignored";
return;
}
emit randomValuesReceived(min, max, type, values, senderProfile);
}
void RoomController::prepareRoomReadMessage( User* senderProfile, QByteArray message, qint32 sender )
{
if (senderProfile != NULL) {
qDebug() << "[RoomController error] Cannot prepare room for someone who already have a room prepared.";
return;
}
if (!isHost()) {
qDebug() << "[RoomController] You received a message that only the host should have received.";
return;
}
QDataStream messageStream(message);
//First, search the sender ID in the list of latestUnknownDisconnects.
//This is because maybe the user already disconnected, but due to a slow
//connection, the others are only receiving this message now!
bool recentlyDisconnected = wasUserRecentlyDisconnected(sender);
//Get the user version:
QString userAppVersion, userEngineVersion;
messageStream >> userAppVersion;
messageStream >> userEngineVersion;
//Get the typed password:
QString password;
messageStream >> password;
//Get the user ip:
QString ip;
messageStream >> ip;
//Get the user secret key:
QByteArray key;
messageStream >> key;
//Build the reply:
QByteArray reply;
QDataStream replyStream(&reply, QIODevice::WriteOnly);
if (isRoomFull())
replyStream << (qint8) ANSWER_ROOM_FULL;
else {
if ( (userAppVersion != Engine::getAppVersion()) || (userEngineVersion != Engine::getEngineVersion()) ) {
qDebug() << "User joined with the wrong version: " << userAppVersion << ". E. " << userEngineVersion;
replyStream << (qint8) ANSWER_WRONG_VERSION;
replyStream << Engine::getAppVersion();
replyStream << Engine::getEngineVersion();
} else {
if (bannedUsers.contains(ip)) {
/* User ip is in the blacklist. So, don't let him join: */
replyStream << (qint8) ANSWER_BANNED;
} else {
if (recentlyDisconnected) {
replyStream << (qint8) ANSWER_DISCONNECTED_RECENTLY;
} else {
if (password != roomDescription->getPassword()) {
replyStream << (qint8) ANSWER_WRONG_PASSWORD;
} else {
if (key != getSecretApplicationKey(ip))
replyStream << (qint8) ANSWER_WRONG_APP_KEY;
else {
/* Make sure the first user that joins the room is the host: */
if ( (currentUser == NULL) && (ip != roomDescription->getRoomIp()) ) {
replyStream << (qint8) ANSWER_DENIED_OTHER;
} else {
/* Alright, let the user come in: */
comingUsers << sender; //since you are allowing this player to join, make sure nobody grabs his spot.
replyStream << (qint8) ANSWER_ALLOWED;
replyStream << (qint32) sender; //send the ID, so the user can know its own id.
replyStream << crypt(generatedKey, "187425446", false);
roomDescription->setTotalUsersInRoom( users.size() );
if (currentUser)
roomDescription->setHostNicknamePrediction( currentUser->getNickname() );
replyStream << roomDescription;
foreach (User *user, users) {
replyStream << user;
}
}
}
}
}
}
}
}
//Send reply:
sendMessageToServerByID(MSG_PREPARE_ROOM_REPLY, reply, sender);
}
void RoomController::prepareRoom( qint32 sender, QDataStream &messageStream )
{
if (DISPLAY_RC_DEBUG_MESSAGES)
qDebug() << "User " << sender << " is allowed to join the room.";
if (isHost()) {
//Host found himself:
currentUserID = sender;
roomDescription->setHostNicknamePrediction( userSettings->getNickname() );
emit roomPrepared(true);
return;
}
qint32 id;
messageStream >> id; //get your id.
messageStream >> generatedKey; //room filetransfer key.
generatedKey = crypt(generatedKey, "187425446", false);
messageStream >> roomDescription;
qint16 totalUsers = roomDescription->getTotalUsersInRoom();
for (qint16 i = 0; i < totalUsers; i++) {
User *newMember = Engine::newUser(INVALID_ID, this, Engine::newUserSettings(this,true));
messageStream >> newMember;
if (sender == newMember->getUniqueID()) { //The host sent the message, so compare with the sender.
newMember->setIsHost(true);
if (addUser(newMember))
hostUser = newMember;
} else addUser(newMember);
}
User *user = searchUser(id);
if (user != NULL) {
qWarning() << "[RoomController] Warning: you are already in this room! You shouldn't be";
} else {
currentUserID = id;
emit roomPrepared(true);
}
}
void RoomController::preparePingMessage(QByteArray message)
{
qint32 from;
QDataStream messageStream(message);
messageStream >> from;
QByteArray reply;
QDataStream replyStream(&reply, QIODevice::WriteOnly);
replyStream << currentUserID;
sendMessageToServerByID(MSG_PING_REPLY, reply, from, UDP_MESSAGE);
}
void RoomController::preparePingMessageReply(QByteArray message)
{
qint32 from;
QDataStream messageStream(message);
messageStream >> from;
User *user = searchUser(from);
if (user == NULL) {
qDebug() << "[RoomController] Received a ping from user" << from << "who is not in the room. Ping ignored.";
return;
}
emit pingReceived(user);
}
bool RoomController::getSenderAndCheckMessage( qint32 sender, User* &senderProfile, qint8 type )
{
if (sender == DESCRIPTOR_CODE_FOR_HOST) //message came from host (no sender).
return true;
else
senderProfile = searchUser(sender);
if (senderProfile == NULL) {
switch (type) {
case MSG_PREPARE_ROOM:
case MSG_PREPARE_ROOM_REPLY:
case MSG_ROOM_PREPARED:
case MSG_REQUEST_ROOM_INFO:
case MSG_REQUEST_ROOM_INFO_REPLY:
case MSG_REMOVE_USER:
case MSG_OTHER:
case MSG_ACTION:
case MSG_ACTION_HOST:
break; //Those types of message do not need a user profile.
default:
qWarning() << "[RoomController] Received a message type" << type << "from a sender (" << sender << ") who is not in the Room.";
return false;
}
}
return true;
}
void RoomController::roomPreparedMessage(QByteArray message, qint32 sender)
{
QDataStream messageStream(message);
UserSettings *uSettings = Engine::newUserSettings(this);
messageStream >> uSettings; //get the user nickname
User *senderProfile = Engine::newUser(sender, this, uSettings);
if (sender == currentUserID) { //you found yourself!
currentUser = senderProfile;
uSettings->deleteLater();
senderProfile->setIsYou(true);
senderProfile->setUserSettings(userSettings);
if (isHost()) {
senderProfile->setIsHost(true);
hostUser = senderProfile;
senderProfile->setIsAdmin(true); //Host starts as an admin
}
}
if ( addUser(senderProfile) )
emit someoneConnectedToServer(senderProfile);
if ((isHost()) && (wasUserRecentlyDisconnected(sender))) {
qDebug() << "[RoomController] User" << sender << "was recently disconnected. Request to join room denied.";
sendMessageToServerByID(MSG_REMOVE_USER, 0, sender);
}
}
bool RoomController::wasUserRecentlyDisconnected(qint32 userID)
{
//This is because maybe the user already disconnected, but due to a slow
//connection, the others are only receiving this message now!
foreach (User *user, latestUnknownDisconnects) {
if ( (user->getUniqueID() == userID) && (user->getSecondsSinceCreated() < TIMEOUT_WAITING_DISCONNECT_SECONDS) ) {
qDebug() << "User" << userID << "disconnected only" << user->getSecondsSinceCreated() << "seconds ago.";
return true;
}
}
return false;
}
void RoomController::removeUserFromComingUsersArray(qint32 id)
{
comingUsers.removeAll(id);
}
void RoomController::dealWithGenericMessageReceived(QByteArray message, User *user)
{
totalOfGenericMessages++;
qDebug() << "[RoomController] Total of generic messages received: " << totalOfGenericMessages;
emit genericMessageReceived(message, user);
}
void RoomController::addToPingUsersList(qint32 id)
{
if (isInPingUsersList(id)) return;
if (pingUsers.size() > MAX_NUMBER_OF_PING_USERS) {
pingUsers.removeAt(0);
}
pingUsers << id;
}
bool RoomController::isInPingUsersList(qint32 id)
{
return (pingUsers.indexOf(id) >= 0);
}
void RoomController::addUserToLatestUnknownDisconnects(qint32 id)
{
qDebug() << "User (" << id << ") left, but this user was not on the Room (added to latest disconnects).";
//Add the unknown user to a list of disconnected users in case this user shows up.
if (latestUnknownDisconnects.size() >= MAX_NUMBER_OF_DISCONNECTS) {
User *user = latestUnknownDisconnects.at(0);
latestUnknownDisconnects.removeAt(0);
delete user;
}
latestUnknownDisconnects << Engine::newUser(id, this, Engine::newUserSettings(this,true));
}
bool RoomController::makeSureUserSettingsIsDeclared()
{
if (userSettings == NULL) {
qCritical() << "[Room Controller] ERROR: Room Controller requires some user setting to be able to continue.";
return false;
}
return true;
}
void RoomController::addUserToBannedList(qint32 id)
{
if (!isHost()) {
qDebug() << "[RoomController] Error: Only the host can ban users";
return;
}
User *user = searchUser(id);
if (user == NULL) {
qDebug() << "[RoomController] Tried to ban an user who is not in the room.";
return;
}
/* Add the user to the blacklist, so he/she can't join the room again: */
bannedUsers[ user->getUserSettings()->getIp() ] = user;
qDebug() << user->getNickname() << " was banned (IP: " << user->getUserSettings()->getIp() << ").";
}
/**
* This is a key that will be generated and sent to the users when they
* join the room. This key can then be used for cryptographed messages
* such as the transference of files.
*/
QByteArray RoomController::generateRoomCryptKey()
{
QString secretKey = QString(getRoomDescription()->getRoomPort())
+ Engine::getAppSecret() + QString::number( rand() * 1000 );
return QCryptographicHash::hash((secretKey.toAscii()),QCryptographicHash::Md5);
}
/**
* The secret key is sent through the loading screen
* to make sure the application name matches between
* client and server. Their keys must match for them
* to trade network messages.
*/
QByteArray RoomController::getSecretApplicationKey(QString userIP)
{
QString secretKey = QString(getRoomDescription()->getRoomPort())
+ Engine::getAppCompany() + Engine::getAppName()
+ roomDescription->getPassword() + userIP + Engine::getAppSecret();
return QCryptographicHash::hash((secretKey.toAscii()),QCryptographicHash::Md5);
/*
* This key could be a lot more elaborated by hashing the application data. But,
* since the application is cross-platform, we can't hash the file because the
* Mac file and Windows file are different (and each user just have one or the other).
*/
}
/** Crypt the private messages: */
QByteArray RoomController::privateMessageCrypt(QByteArray message, qint32 id1, qint32 id2)
{
QByteArray key("pchat");
key.append(id1);
key.append(id2);
return crypt(message, key);
}
bool RoomController::addChatMessage(QString message, QColor color)
{
if (chatroom == NULL) return false;
chatroom->addChatMessage(message, 0, color);
return true;
}
bool RoomController::addActionLog(QListWidgetItem *logItem)
{
if (chatroom == NULL) return false;
chatroom->addLog(logItem);
return true;
}
void RoomController::requestRandomValues(qint32 min, qint32 max, qint16 type, qint32 count, User *to, bool isTCP)
{
QByteArray message;
QDataStream stream(&message, QIODevice::WriteOnly);
stream << min;
stream << max;
stream << type;
stream << count;
/* Get the id of who the message is to. If the message is to everyone, the id is 0: */
qint32 id = (to == TO_EVERYONE) ? TO_EVERYONE : to->getUniqueID();
stream << id;
if ( (isHost()) && (currentUser != NULL) )
/* No need to send a message to the host if the current user is the host: */
prepareRandomValueMessage(message, currentUser);
else
/* Send to the host a message asking for the random value: */
sendMessageToServerByID(MSG_RANDOM_VALUE, message, DESCRIPTOR_CODE_FOR_HOST, isTCP);
}
QByteArray RoomController::crypt(QByteArray package, QByteArray localKey, bool useHostKey)
{
if(localKey.isEmpty())
return package;
/* Combine keys: */
QByteArray key;
if (useHostKey) key.append(generatedKey); //Key received from the host
key.append(localKey); //Key stored locally.
key = QCryptographicHash::hash(key,QCryptographicHash::Md5);
QByteArray crypt;
for(int i = 0 , j = 0; i < package.length(); ++i , ++j)
{
if (j == key.length()) j = 0;
crypt.append(package.at(i) ^ key.at(j));
}
return crypt;
}
| true |
a0d6ee06d40ac108040e9bec3fafa88f2d8c35ed | C++ | kepkakarol/monopoly | /PunishmentSquare.cpp | UTF-8 | 361 | 2.65625 | 3 | [] | no_license | #include "PunishmentSquare.h"
#include "Player.h"
void PunishmentSquare::doStepAction(std::shared_ptr<Piece> player)
{
std::cout<<"stepping on punishment square; " << "-" << MONEY <<std::endl;
player->payMoney(MONEY);
}
void PunishmentSquare::doPassAction(std::shared_ptr<Piece> player) {
std::cout<<"passing by punishment square" <<std::endl;
}
| true |
2f80de1b223b7c2de72c85693ac3980254dc9537 | C++ | patrikpihlstrom/Convex-Polygon-Editor | /src/map/Quadtree.hpp | UTF-8 | 1,197 | 2.6875 | 3 | [
"Unlicense"
] | permissive | #pragma once
#include <memory>
#include <vector>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <SFML/Graphics.hpp>
#include "../application/Math.hpp"
const unsigned char MAX_LEVEL = 6;
class Quadtree : public sf::Drawable
{
public:
Quadtree();
Quadtree(const sf::Vector2f& position, const sf::Vector2f& dimensions, const bool hasChildren = false, const unsigned char level = 0);
~Quadtree();
void update();
void insert(std::shared_ptr<math::Polygon> polygon, unsigned char index);
bool remove(unsigned char index);
bool canMerge() const; // Checks itself and its siblings.
bool canMergeChildren() const;
bool empty() const;
void save(std::ofstream& file, std::vector<unsigned char>& saved) const;
math::Polygon polygon;
std::shared_ptr<math::Polygon> getPolygon(const sf::Vector2f& position);
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
std::shared_ptr<Quadtree> m_children[4];
std::weak_ptr<Quadtree> m_parent;
std::map<unsigned char, std::shared_ptr<math::Polygon>> m_polygons;
void split();
void mergeChildren();
unsigned char m_level;
sf::Vector2f m_position, m_dimensions;
bool m_hasChildren;
};
| true |
209600d7efa942cf094c10f456cad7175eb09b87 | C++ | EeeUnS/2020CppStudy | /week2/study/set.cpp | UTF-8 | 932 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <random>
#include <algorithm>
typedef long long ll;
int main()
{
int a = 0x7FFFFFFF;//max 0111 1111 1111 1111 11111111 1111 1111
int b = 0X80000000; //min
std::cout << a << ' ' << b << '\n';
std::mt19937_64 rng;
rng.seed(std::random_device()());
std::uniform_int_distribution<int>distribution(0x7FFFFFFF, );
std::set<int> Set;
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 10; ++j)
{
int num = distribution(rng);
std::set<int>::const_iterator itr = std::find(Set.begin(), Set.end(), num);
if (itr == Set.end()) //
{
Set.insert(itr, num);
}
else
{
std::cerr << "error" << '\n';
//cerr
// iostream
// cout >>
// cerr >>
// clog >>
// 콘솔창에서 값을 출력을 해줌
// stdin defalut
// txt log
}
}
for (int i : Set)
{
std::cout << i << ' ';
}
std::cout << '\n';
}
return 0;
}
| true |
206e043e04e894359dab413c8a989a63071a8290 | C++ | keisuke-kanao/my-UVa-solutions | /Contest Volumes/Volume 100 (10000-10099)/UVa_10098_Generating_Fast_Sorted_Permutation.cpp | UTF-8 | 475 | 2.8125 | 3 | [] | no_license |
/*
UVa 10098 - Generating Fast, Sorted Permutation
To build using Visual Studio 2008:
cl -EHsc -O2 UVa_10098_Generating_Fast_Sorted_Permutation.cpp
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
while (n--) {
string s;
cin >> s;
sort(s.begin(), s.end());
do
cout << s << endl;
while (next_permutation(s.begin(), s.end()));
cout << endl;
}
return 0;
}
| true |
c4c0a345d323a943aff2053311243fb3ea520197 | C++ | Sanerins/Cpp_Progs | /2 semester/8.1 FinalTestHelper/QueueArray.hpp | UTF-8 | 2,388 | 3.390625 | 3 | [] | no_license | #ifndef QUEUE_QUEUEARRAY_HPP
#define QUEUE_QUEUEARRAY_HPP
#include "Queue.hpp"
#include "QueueOverflow.hpp"
#include "QueueUnderflow.hpp"
#include "WrongQueueSize.hpp"
template<typename T>
class QueueArray final: public Queue<T> // модификатор final запрещает наследование от класса
{
public:
explicit QueueArray(size_t size);
QueueArray(const QueueArray<T> &src) = delete;
QueueArray(QueueArray<T> &&src) noexcept;
QueueArray<T> &operator=(QueueArray<T> &&src) noexcept; // оператор перемещающего присваивания
~QueueArray() override;
void enQueue(const T &e) override;
T deQueue() override;
bool isEmpty() const override;
void swap(QueueArray<T> &right);
private:
T *array_; // массив элементов очереди
size_t head_{}; // Очередь пуста, если head[Q] = tail[Q].
size_t tail_{}; // Первоначально: head[Q] = tail[Q] = 0;
size_t size_{}; // размер очереди
// void swap(QueueArray<T> &right);
};
template<typename T>
QueueArray<T>::QueueArray(size_t size):
head_(0),
tail_(0),
size_(size + 1)
{
try
{
array_ = new T[size + 1];
}
catch (std::bad_alloc &ex)
{
throw WrongQueueSize();
}
}
template<typename T>
void QueueArray<T>::swap(QueueArray<T> &right)
{
std::swap((*this).array_, right.array_);
std::swap((*this).head_, right.head_);
std::swap((*this).tail_, right.tail_);
std::swap((*this).size_, right.size_);
}
template<typename T>
QueueArray<T>::QueueArray(QueueArray<T> &&src) noexcept
{
swap(src);
}
template<typename T>
QueueArray<T> &QueueArray<T>::operator=(QueueArray<T> &&src) noexcept
{
if (this != &src)
{
delete this->array_;
swap(src);
}
return *this;
}
template<typename T>
void QueueArray<T>::enQueue(const T &e)
{
if (head_ == tail_ + 1)
{
throw QueueOverflow();
}
array_[tail_] = e;
tail_ = (tail_ + 1) % size_;
}
template<typename T>
T QueueArray<T>::deQueue()
{
if (head_ == tail_)
{
throw QueueUnderflow();
}
size_t index = head_;
head_ = (head_ + 1) % size_;
return std::move(array_[index]);
}
template<typename T>
QueueArray<T>::~QueueArray()
{
delete[] array_;
}
template<typename T>
bool QueueArray<T>::isEmpty() const
{
return head_ == tail_;
}
#endif //QUEUE_QUEUEARRAY_HPP
| true |
8fdc412810668028f61dd64aee1925bcf4463c7c | C++ | akozlins/util | /spinlock/main.cpp | UTF-8 | 1,305 | 3.03125 | 3 | [] | no_license |
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
class Mutex
{
private:
class ShortLock
{
public:
volatile long locked;
ShortLock(): locked(0) { }
void lock() { while(BOOST_INTERLOCKED_COMPARE_EXCHANGE(&locked, 1, 0) == 1); }
void unlock() { BOOST_INTERLOCKED_EXCHANGE(&locked, 0); }
};
ShortLock shortLock;
HANDLE eventHandle;
public:
Mutex()
{
eventHandle = CreateEvent(0, TRUE, FALSE, 0);
}
virtual ~Mutex()
{
CloseHandle(eventHandle);
}
void lock()
{
shortLock.lock();
}
void unlock()
{
shortLock.unlock();
}
};
Mutex mt;
void func1()
{
mt.lock();
char* str = "Hello World 1 !!!";
for(int i = 0, len = strlen(str); i < len; i++) std::cout << str[i];
std::cout << std::endl;
mt.unlock();
}
void func2()
{
mt.lock();
char* str = "Hello World 2 !!!";
for(int i = 0, len = strlen(str); i < len; i++) std::cout << str[i];
std::cout << std::endl;
mt.unlock();
}
void main()
{
for(int i = 0; i < 10; i++)
{
boost::thread thread1(boost::bind(&func1));
boost::thread thread2(boost::bind(&func2));
thread2.join();
thread1.join();
}
}
| true |
457e8576a2e81ea6485adb72b46ee225917de872 | C++ | MrRen-sdhm/arm_robot_controller | /User/BSP/base_motor.hpp | UTF-8 | 2,735 | 2.921875 | 3 | [] | no_license | #pragma once
#include <cstring>
#include <array>
#include <list>
#include <numeric>
#include <utility>
#include <algorithm>
namespace hustac {
class BaseMotor {
public:
static constexpr float invalid_output = std::numeric_limits<float>::signaling_NaN();
BaseMotor() = default;
explicit BaseMotor(const char *name)
: name_(name) {}
const char *name() { return name_; };
bool operator==(const BaseMotor &rhs) { return strcmp(name_, rhs.name_) == 0; }
virtual int init() { return -1; }
virtual int start() { return -1; }
virtual int stop() { return -1; }
virtual bool started() { return false; }
virtual std::pair<float, float> limit() {
return std::make_pair(std::numeric_limits<float>::signaling_NaN(), std::numeric_limits<float>::signaling_NaN());
}
virtual float goal_position() { return std::numeric_limits<float>::signaling_NaN(); }
virtual int goal_position(float) { return -1; }
virtual float current_position() { return std::numeric_limits<float>::signaling_NaN(); }
virtual float current_velocity() { return std::numeric_limits<float>::signaling_NaN(); }
virtual float current_effort() { return std::numeric_limits<float>::signaling_NaN(); }
virtual int spin_once() { return -1; };
protected:
const char *name_ = "";
};
class EmergencyStoppable {
public:
static std::list<EmergencyStoppable *> all_emergency_stoppable_;
static const auto all_emergency_stoppable() {
return all_emergency_stoppable_;
}
static int all_emergency_stop(bool val) {
int ret = 1;
for (auto p : all_emergency_stoppable_) {
int r = p->emergency_stop(val);
if (r != 1) {
ret = r;
}
}
return ret;
}
static bool all_emergency_stop() {
for (auto p : all_emergency_stoppable_)
if (!p->emergency_stop())
return false;
return true;
}
private:
bool emergency_stop_ = false;
public:
EmergencyStoppable() {
all_emergency_stoppable_.push_back(this);
}
virtual ~EmergencyStoppable() {
auto it = std::find(all_emergency_stoppable_.begin(), all_emergency_stoppable_.end(), this);
if (it != all_emergency_stoppable_.end())
all_emergency_stoppable_.erase(it);
}
bool emergency_stop() {
return emergency_stop_;
}
int emergency_stop(bool val) {
if (emergency_stop_ ^ val) {
emergency_stop_ = val;
on_emergency_stop_changed(val);
return 0;
} else {
return 1;
}
}
protected:
virtual void on_emergency_stop_changed(bool value) {};
};
}
| true |
c5e08a128637f847ab8fb85e3c50b94eeb9f2ee9 | C++ | davega-code/Algorithms | /Strings/LCP.cpp | UTF-8 | 4,224 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int maxN = 20;
struct tuple
{
int indxs[2];
int pos;
}L[maxN];
int cmp(struct tuple a, struct tuple b) // Check tuples current step and next one to give sorting index.
{
return (a.indxs[0] == b.indxs[0]) ? (a.indxs[1] < b.indxs[1]?1:0) : (a.indxs[0] < b.indxs[0]?1:0);
}
int sortIndex[5000][maxN];
vector<int> Suffix_Array(string s)
{
for(int i = 0 ; i < s.size() ; i++) //let's get all suffixes, we only need the first letter later we can form everyone based on this.
sortIndex[0][i] = s[i] -'a';
int done_till = 1, step = 1;
int N = s.size();
for(;done_till < N; step++, done_till*=2) // 2 step jump and till we have gone through all the string, also keep track of steps.
{
for(int i = 0 ; i < N ; i++) //Lets rearm the tuple
{
L[i].indxs[0] = sortIndex[step - 1][i]; // last SI is the current one
L[i].indxs[1] = ( i + done_till ) < N? sortIndex[step-1][i + done_till]:-1; // next one is calculated using another previously
L[i].pos = i; // lets get new position calculated SI of another suffix or if size too big -1
}
sort(L, L + N, cmp); // sorting tuples
for(int i = 0 ; i < N; i++) //Lets calculate the new SI
{
sortIndex[ step ][ L[i].pos ] = i > 0 && L[i].indxs[0] == L[i - 1].indxs[0] && L[i].indxs[1] == L[i - 1].indxs[1] ?
sortIndex[ step ][ L[i-1].pos ] : i;
}
// after the sort the first one stays the same, now if it has the same values as i-1 it gets the same SI, if not then i (new SI)
}
vector <int> S_Array;
for(int i = 0; i < s.size(); i++)
{
S_Array.push_back(L[i].pos);
}
return S_Array;
}
int maxi;
/* To construct and return LCP */
vector<int> kasai(string txt, vector<int> suffixArr)
{
int n = suffixArr.size();
map<string,int> ap;
// To store LCP array
vector<int> lcp(n, 0);
maxi = 0;
// An auxiliary array to store inverse of suffix array
// elements. For example if suffixArr[0] is 5, the
// invSuff[5] would store 0. This is used to get next
// suffix string from suffix array.
vector<int> invSuff(n, 0);
// Fill values in invSuff[]
for (int i=0; i < n; i++)
invSuff[suffixArr[i]] = i;
// Initialize length of previous LCP
int k = 0;
// Process all suffixes one by one starting from
// first suffix in txt[]
for (int i=0; i<n; i++)
{
/* If the current suffix is at n-1, then we don’t
have next substring to consider. So lcp is not
defined for this substring, we put zero. */
if (invSuff[i] == n-1)
{
k = 0;
continue;
}
/* j contains index of the next substring to
be considered to compare with the present
substring, i.e., next string in suffix array */
int j = suffixArr[invSuff[i]+1];
string aux = "";
// Directly start matching from k'th index as
// at-least k-1 characters will match
while (i+k<n && j+k<n && txt[i+k]==txt[j+k])
{
k++;
aux+=txt[i+k];
}
//cout<<aux<<endl;
ap[aux]++;
if(k > maxi && ap[aux] >=2) maxi = k;
lcp[invSuff[i]] = k; // lcp for the present suffix.
// Deleting the starting character from the string.
if (k>0)
k--;
}
// return the constructed lcp array
return lcp;
}
// Utility function to print an array
void printArr(vector<int>arr, int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program
int main()
{
string str;
int c;
cin>>c;
cin>>str;
vector<int>suffixArr = Suffix_Array(str);
int n = suffixArr.size();
//cout << "Suffix Array : \n";
//printArr(suffixArr, n);
vector<int>lcp = kasai(str, suffixArr);
//cout << "\nLCP Array : \n";
printArr(lcp, n);
cout<<maxi<<'\n';
return 0;
} | true |
434c4bcccd2fa779d1b65dade53219282bc80faa | C++ | timkostka/cert3d | /firmware/GSL/inc/gsl_lcd_hx8357d.h | UTF-8 | 19,912 | 2.578125 | 3 | [] | no_license | #pragma once
// This file includes an interface for communicating with an LCD screen through
// the HX8357D controller.
// for instance, on this breakout board:
// https://www.adafruit.com/products/2050
#include "gsl_includes.h"
struct GSL_LCD_HX8357D {
// color scheme
struct ColorSchemeStruct {
uint16_t back;
uint16_t fill;
uint16_t border;
uint16_t fore;
uint16_t text;
uint16_t highlight;
uint16_t shadow;
uint16_t button_face;
uint16_t text_pressed;
uint16_t button_face_pressed;
};
// current color scheme
ColorSchemeStruct color_;
// lcd width
const uint16_t width_ = 480;
// lcd height
const uint16_t height_ = 320;
// interface enum
enum InterfaceEnum {
kInterfaceNone,
kInterfaceParallel8Bit,
kInterfaceParallel9Bit,
kInterfaceParallel16Bit,
kInterfaceParallel18Bit,
kInterfaceParallel24Bit,
kInterfaceSerial3Wire,
kInterfaceSerial4Wire,
};
// commands
enum CommandEnum : uint8_t {
kCommandNOP = 0x00,
// this resets the display, must wait 5-120ms for it to reset
kCommandSoftwareReset = 0x01,
// read 4 bytes:
// 0: dummy byte
// 1: LCD module manufacturer's ID
// 2: LCD module/driver version ID
// 3: LCD module/drive ID
//kCommandReadIdentification = 0x02,
// don't invert the display
kCommandDisplayInversionOff = 0x20,
// invert the display
kCommandDisplayInversionOn = 0x21,
// turn all pixels black
kCommandAllPixelsOff = 0x22,
// turn all pixels white
kCommandAllPixelsOn = 0x23,
// turn off the display (memory not transferred to screen)
kCommandDisplayOff = 0x28,
// turn on the display (transfer memory to screen)
kCommandDisplayOn = 0x29,
// set the column address
kCommandColumnAddressSet = 0x2A,
// set the page address
kCommandPageAddressSet = 0x2B,
// set the page address
kCommandMemoryWrite = 0x2C,
// turn off the tearing effect signal
kCommandTearingEffectLineOff = 0x34,
// turn on the tearing effect signal
kCommandTearingEffectLineOn = 0x35,
// memory access control
kCommandMemoryAccessControl = 0x36,
// turn idle mode off
kCommandIdleModeOff = 0x38,
// turn idle mode on
kCommandIdleModeOn = 0x39,
};
// interface type
InterfaceEnum interface_;
// SPI peripheral to use, if any
SPI_TypeDef * SPIx_;
// CS pin, if any
PinEnum pinCS_;
// DC pin, if any
// low = command, high = data
PinEnum pinDC_;
// RST pin, if any
PinEnum pinRST_;
// current font
const GSL_FONT_FontStruct * font_;
// convert R, G, B values into a color
// values for r,g,b can range from 0 (off) to 1 (on)
uint16_t ToColor(float r, float g, float b) {
// validity check
if (r > 1.0f) {
r = 1.0f;
} else if (!(r >= 0.0f)) {
r = 0.0f;
}
if (g > 1.0f) {
g = 1.0f;
} else if (!(g >= 0.0f)) {
g = 0.0f;
}
if (b > 1.0f) {
b = 1.0f;
} else if (!(b >= 0.0f)) {
b = 0.0f;
}
uint16_t color = 0;
/*uint16_t redcomp = r * ((1 << 5) - 0.5f);
uint16_t greencomp = g * ((1 << 6) - 0.5f);
uint16_t bluecomp = b * ((1 << 5) - 0.5f);
ASSERT(redcomp <= 0b11111);
ASSERT(greencomp <= 0b111111);
ASSERT(bluecomp <= 0b11111);
color = redcomp;
color <<= 6;
color <<= 6;*/
// now make a color with 5 bits r, 6 bits green, 5 bits blue
color |= (uint16_t) (r * ((1 << 5) - 1));
color <<= 6;
color |= (uint16_t) (g * ((1 << 6) - 1));
color <<= 5;
color |= (uint16_t) (b * ((1 << 5) - 1));
return color;
}
// start a command
void StartCommand(uint8_t command) {
// send the command
GSL_SPI_SetCSPin(SPIx_, pinCS_);
// set CS managed mode
GSL_SPI_SetCSMode(SPIx_, GSL_SPI_CS_MODE_MANUAL);
// we are sending a command
GSL_PIN_SetLow(pinDC_);
// set CS low
GSL_SPI_SetCSLow(SPIx_);
// send the command
GSL_SPI_Send(SPIx_, command);
// we are sending data
GSL_PIN_SetHigh(pinDC_);
}
// end a command
void EndCommand(void) {
// wait for it to be ready
GSL_SPI_WaitTX(SPIx_);
// return CS pin high
GSL_SPI_SetCSHigh(SPIx_);
}
// send a command and a number of parameters to the display
void SendCommand(uint8_t command, uint8_t * data, uint16_t data_count) {
// only one interface currently supported
ASSERT(interface_ == kInterfaceSerial4Wire);
StartCommand(command);
// send the data
GSL_SPI_SendMulti(SPIx_, data, data_count);
// end the command
EndCommand();
}
// send a command to the display
void SendCommand(uint8_t command) {
SendCommand(command, nullptr, 0);
}
// send a command and one parameter to the display
void SendCommand(uint8_t command, uint8_t data) {
SendCommand(command, &data, 1);
}
// send a command and two parameters to the display
void SendCommand(uint8_t command, uint8_t data1, uint8_t data2) {
uint8_t data[2] = {data1, data2};
SendCommand(command, data, sizeof(data));
}
// send a command and two 16-bit parameters to the display
void SendCommand1616(uint8_t command, uint16_t data1, uint16_t data2) {
uint8_t data[4] = {
(uint8_t) (data1 >> 8),
(uint8_t) data1,
(uint8_t) (data2 >> 8),
(uint8_t) data2};
SendCommand(command, data, sizeof(data));
}
// send a command and one 32-bit parameters to the display
void SendCommand32(uint8_t command, uint32_t data1) {
uint8_t data[4] = {
(uint8_t) (data1 >> 24),
(uint8_t) (data1 >> 16),
(uint8_t) (data1 >> 8),
(uint8_t) data1};
SendCommand(command, data, sizeof(data));
}
// send a command and three parameters to the display
void SendCommand(uint8_t command, uint8_t data1, uint8_t data2, uint8_t data3) {
uint8_t data[3] = {data1, data2, data3};
SendCommand(command, data, sizeof(data));
}
// send a command and four parameters to the display
void SendCommand(uint8_t command, uint8_t data1, uint8_t data2, uint8_t data3, uint8_t data4) {
uint8_t data[4] = {data1, data2, data3, data4};
SendCommand(command, data, sizeof(data));
}
// initializer
void Initialize(void) {
// only one interface currently supported
ASSERT(interface_ == kInterfaceSerial4Wire);
// ensure definitions are there
ASSERT(GSL_PIN_IsReal(pinCS_));
ASSERT(GSL_PIN_IsReal(pinDC_));
ASSERT(GSL_PIN_IsReal(pinRST_));
ASSERT(SPIx_ != nullptr);
// ensure CS pin is there and set it to be active
GSL_SPI_AddCSPin(SPIx_, pinCS_);
GSL_SPI_SetCSPin(SPIx_, pinCS_);
// I couldn't find the max SPI interface speed in the datasheet, but this
// is where I'd set it. I think it's high.
//GSL_SPI_SetMaxSpeed(SPIx_, 1000000);
GSL_SPI_Initialize(SPIx_);
// initialize pins
GSL_PIN_SetLow(pinRST_);
GSL_PIN_Initialize(pinRST_, GPIO_MODE_OUTPUT_PP);
GSL_PIN_Initialize(pinDC_, GPIO_MODE_OUTPUT_PP);
// bring it out of reset (must hold RST low for 10us)
GSL_DEL_US(100);
GSL_PIN_SetHigh(pinRST_);
// wait for it to boot
GSL_DEL_MS(120);
// reset the display
//SendCommand(0x01);
//GSL_DEL_MS(150);
// enable extended command set
SendCommand(0xB9, 0xFF, 0x83, 0x57);
// set RGB interface
SendCommand(0xB3, 0x00, 0x00, 0x06, 0x06);
// set VCOM voltage to -1.65V
SendCommand(0xB6, 0x25);
// set panel color order and gate direction
SendCommand(0xCC, 0x05);
// set power control
{
uint8_t data[] = {0x00, 0x15, 0x1C, 0x1C, 0x83, 0xAA};
SendCommand(0xB1, data, sizeof(data));
}
// set source circuit option
{
uint8_t data[] = {0x50, 0x50, 0x01, 0x3C, 0x1E, 0x08};
SendCommand(0xC0, data, sizeof(data));
}
// set display cycle register
{
uint8_t data[] = {0x02, 0x40, 0x00, 0x2A, 0x2A, 0x0D, 0x78};
SendCommand(0xB4, data, sizeof(data));
}
// set interface pixel format to 16-bit colors
SendCommand(0x3A, 0b01010101);
// set memory access control
// landscape (480x320), with top left corner as (0, 0)
SendCommand(kCommandMemoryAccessControl, 0b01000000);
// set tearing effect line on
//SendCommand(kCommandTearingEffectLineOn, 0x00);
// set tear scan line
//SendCommand(0x44, (uint8_t) 0x00, 0x02);
// turn off sleep mode
SendCommand(0x11);
GSL_DEL_MS(5);
// turn display on mode
SendCommand(kCommandDisplayOn);
GSL_DEL_MS(150);
}
// set the window to be written
void SetWindow(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) {
// ensure parameters are okay
ASSERT(x1 <= x2);
ASSERT(y1 <= y2);
ASSERT(x2 < width_);
ASSERT(y2 < height_);
// set the column window
SendCommand1616(kCommandColumnAddressSet, y1, y2);
// set the page
SendCommand1616(kCommandPageAddressSet, x1, x2);
}
// output a color to the SPI buffer
void SendColor(uint16_t col) {
// wait for it to be ready
while ((SPIx_->SR & 0b10) == 0) {
}
// send top 8 bits
SPIx_->DR = (uint8_t) (col >> 8);
// wait for it to be ready
while ((SPIx_->SR & 0b10) == 0) {
}
// send bottom 8 bits
SPIx_->DR = (uint8_t) col;
/*
col = GSL_GEN_SwapEndian(col);
GSL_SPI_SendMulti(SPIx_, (uint8_t *) &col, 2);*/
}
// fill the screen with a given color
void Fill(uint16_t color) {
// for black or white, use the special command
/*if (color == 0x0000) {
SendCommand(kCommandAllPixelsOff);
return;
} else if (color == 0xFFFF) {
SendCommand(kCommandAllPixelsOn);
return;
}*/
/*uint8_t data[64];
color = GSL_GEN_SwapEndian(color);
for (uint8_t i = 0; i < 32; ++i) {
data[i * 2] = color >> 8;
data[i * 2 + 1] = color;
}*/
// set the window to the entire display
SetWindow(0, 0, width_ - 1, height_ - 1);
// send the command
StartCommand(kCommandMemoryWrite);
// send the data
uint32_t count = width_ * height_;
while (count--) {
SendColor(color);
}
/*
while (count >= sizeof(data) / 2) {
GSL_SPI_SendMulti(SPIx_, data, sizeof(data));
count -= sizeof(data) / 2;
}
GSL_SPI_SendMulti(SPIx_, data, count * 2);*/
// return CS pin high
EndCommand();
}
// fill the screen with black
void FillBlack(void) {
Fill(0x0000);
}
// fill the screen with black
void FillWhite(void) {
Fill(0xFFFF);
}
// clear the screen
void Clear(void) {
Fill(color_.back);
}
// Draw a filled rectangle
void DrawFilledRectangle(
uint16_t x1,
uint16_t y1,
uint16_t x2,
uint16_t y2,
uint16_t border) {
uint16_t width = x2 - x1 + 1;
uint16_t height = y2 - y1 + 1;
// set the rectangle
SetWindow(x1, y1, x2, y2);
StartCommand(kCommandMemoryWrite);
// if rectangle is fully filled, then just do that
if (width <= border * 2 || height <= border * 2) {
for (uint32_t i = 0; i < (uint32_t) width * height; ++i) {
SendColor(color_.border);
}
EndCommand();
return;
}
// draw left border
for (uint16_t i = 0; i < border * height; ++i) {
SendColor(color_.border);
}
// draw mid section
for (uint16_t x = 0; x < width - 2 * border; ++x) {
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.border);
}
for (uint16_t i = 0; i < height - 2 * border; ++i) {
SendColor(color_.fill);
}
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.border);
}
}
// draw right border
for (uint16_t i = 0; i < border * height; ++i) {
SendColor(color_.border);
}
// end the command
EndCommand();
}
// Fill a region with the given color
void Fill(
uint16_t x1,
uint16_t y1,
uint16_t x2,
uint16_t y2,
uint16_t color) {
// for empty areas, just exit
if (x2 < x1 || y2 < y1) {
return;
}
uint16_t width = x2 - x1 + 1;
uint16_t height = y2 - y1 + 1;
SetWindow(x1, y1, x2, y2);
StartCommand(kCommandMemoryWrite);
// fill the space
for (uint32_t i = 0; i < (uint32_t) width * height; ++i) {
SendColor(color);
}
// end the command
EndCommand();
}
// draw some text
void DrawText(const char * string, uint16_t x, uint16_t y) {
ASSERT(font_);
// save the original x value
uint16_t original_x = x;
// draw each character
while (*string) {
// do special case of a newline character
if (*string == '\n') {
x = original_x;
y += font_->height_ + font_->space_between_lines_;
} else if (*string == ' ') {
// special case of a space character
x += font_->width_ + font_->space_between_chars_;
} else {
// draw the character
SetWindow(x, y, x + font_->GetCharWidth(*string) - 1, y + font_->height_ - 1);
StartCommand(kCommandMemoryWrite);
for (uint16_t dx = 0; dx < font_->GetCharWidth(*string); ++dx) {
for (uint16_t dy = 0; dy < font_->height_; ++dy) {
if (font_->GetPixel(*string, dx, dy)) {
SendColor(color_.fore);
} else {
SendColor(color_.back);
}
}
}
EndCommand();
// move to next character
x += font_->GetCharWidth(*string) + font_->space_between_chars_;
}
++string;
}
}
// swap two values
template <class T = uint16_t>
static void Swap(T & one, T & two) {
T three = one;
one = two;
two = three;
}
// flip between pressed and unpressed color scheme
void ToggleColorScheme(void) {
Swap(color_.text, color_.text_pressed);
Swap(color_.button_face, color_.button_face_pressed);
Swap(color_.shadow, color_.highlight);
}
// draw a button with text, possible inverted
void DrawButton(
const char * string,
uint16_t x1,
uint16_t y1,
uint16_t x2,
uint16_t y2,
bool pressed = false) {
// if pressed, then reverse the color scheme
const uint16_t border = 2;
// minimum number of pixels between border and text
const uint16_t text_border = 1;
uint16_t width = x2 - x1 + 1;
uint16_t height = y2 - y1 + 1;
// if rectangle isn't big enough to display any text, just create a rectangle
if (width <= (border + text_border) * 2 ||
height <= (border + text_border) * 2) {
DrawFilledRectangle(x1, y1, x2, y2, border);
return;
}
// temporarily toggle the color scheme
if (pressed) {
ToggleColorScheme();
}
//uint16_t string_length = strlen(string);
// get the leftmost x value of the string
int16_t string_x = ((int16_t) width - font_->GetStringWidth(string)) / 2;
// get the topmost y value of the string
int16_t string_y = ((int16_t) height - font_->height_) / 2;
// set the rectangle
SetWindow(x1, y1, x2, y2);
StartCommand(kCommandMemoryWrite);
// draw left border
for (uint16_t x = 0; x < border; ++x) {
for (uint16_t i = 0; i < height; ++i) {
if (x + i + 1 < height) {
SendColor(color_.highlight);
} else {
SendColor(color_.shadow);
}
}
}
// draw buffer on left
for (uint16_t x = 0; x < text_border; ++x) {
// top border
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.highlight);
}
// midsection
for (uint16_t i = 0; i < height - 2 * border; ++i) {
SendColor(color_.button_face);
}
// bottom border
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.shadow);
}
}
// number of columns before we encounter the string
int16_t empty_columns = string_x - border - text_border;
// note: *string points to the current character
// current character column
uint16_t char_column = 0;
// increment string to account for clipping
while (empty_columns < 0) {
++char_column;
if (char_column == font_->GetCharWidth(*string)) {
++empty_columns;
if (*string) {
++string;
}
char_column = 0;
}
++empty_columns;
}
// draw mid section
for (uint16_t x = 0; x < width - 2 * border - 2 * text_border; ++x) {
// top border
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.highlight);
}
// buffer
for (uint16_t i = 0; i < text_border; ++i) {
SendColor(color_.button_face);
}
// if this columns is empty...
if (*string == 0 || empty_columns > 0) {
for (uint16_t i = 0; i < height - 2 * border - 2 * text_border; ++i) {
SendColor(color_.button_face);
}
if (empty_columns > 0) {
--empty_columns;
}
} else {
// midsection
int16_t char_y = border + text_border - string_y;
for (uint16_t i = 0; i < height - 2 * border - 2 * text_border; ++i) {
if (char_y >= 0 && char_y < font_->height_) {
if (font_->GetPixel(*string, char_column, char_y)) {
SendColor(color_.text);
} else {
SendColor(color_.button_face);
}
} else {
SendColor(color_.button_face);
}
++char_y;
}
// increment column
++char_column;
if (char_column >= font_->GetCharWidth(*string)) {
char_column = 0;
empty_columns = font_->space_between_chars_;
++string;
}
}
// buffer
for (uint16_t i = 0; i < text_border; ++i) {
SendColor(color_.button_face);
}
// bottom border
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.shadow);
}
}
// draw buffer on right
for (uint16_t x = 0; x < text_border; ++x) {
// top border
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.highlight);
}
// midsection
for (uint16_t i = 0; i < height - 2 * border; ++i) {
SendColor(color_.button_face);
}
// bottom border
for (uint16_t i = 0; i < border; ++i) {
SendColor(color_.shadow);
}
}
// draw right border
for (uint16_t x = 0; x < border; ++x) {
for (uint16_t i = 0; i < height; ++i) {
if (border <= i + x) {
SendColor(color_.shadow);
} else {
SendColor(color_.highlight);
}
}
}
// end the command
EndCommand();
// switch back to original color scheme
if (pressed) {
ToggleColorScheme();
}
}
// constructor
GSL_LCD_HX8357D(void) {
SPIx_ = nullptr;
interface_ = kInterfaceNone;
pinCS_ = kPinNone;
pinDC_ = kPinNone;
pinRST_ = kPinNone;
// initialize defaults
font_ = &gsl_font_5x7;
// initialize default color scheme
color_.back = ToColor(0.0f, 0.0f, 0.0f);
color_.fill = ToColor(0.25f, 0.25f, 0.25f);
color_.border = ToColor(1.0f, 1.0f, 1.0f);
color_.fore = ToColor(1.0f, 1.0f, 1.0f);
color_.text = ToColor(0.0f, 0.0f, 0.0f);
color_.highlight = ToColor(1.0f, 1.0f, 1.0f);
color_.shadow = ToColor(0.125f, 0.125f, 0.125f);
color_.button_face = ToColor(0.75f, 0.75f, 0.75f);
color_.text_pressed = 0xFFFF;
color_.button_face_pressed = ToColor(0.25f, 0.25f, 0.25f);
// yellow on black color scheme
{
GSL_COL_RGB foreground = kColorYellow;
GSL_COL_RGB background = kColorBlack;
color_.back = background;
color_.fill = foreground;
color_.border = foreground;
color_.fore = foreground;
color_.text = foreground;
color_.highlight = foreground;
color_.shadow = foreground;
color_.button_face = background;
color_.text_pressed = background;
color_.button_face_pressed = foreground;
}
}
};
| true |
30418674db70bd164fdab191d302d8b7e12d7af8 | C++ | MoriokaReimen/MoonRakerServer | /include/Command.hpp | UTF-8 | 4,081 | 2.609375 | 3 | [] | no_license | /*!
-----------------------------------------------------------------------------
@file Command.hpp
----------------------------------------------------------------------------
@@
@@@@@@
@```@@@@
@` `@@@@@@
@@` `@@@@@@@@
@@` `@@@@@@@@@ Tohoku University
@` ` `@@@@@@@@@ SPACE ROBOTICS LABORATORY
@`` ## `@@@@@@@@@ http://www.astro.mech.tohoku.ac.jp/
@` #..#`@@@@@@@@@ Planetary Robotics Group
@` #..#`@@@@@@@@@
@` ### `@@@@@@@@@ Professor Kazuya Yoshida
@` ###``@@@@@@@@@ Associate Professor Keiji Nagatani
@### ``@@@@@@@@
### ` @@@@@@@
### @ @@@@@ Creation Date:
### @@@@@ @date Dec. 29. 2014
/-\ @@
| | %% Authors:
\-/## %%%%% @author Kei Nakata
#### %%% menschenjager.mark.neun@gmail.com
###%% *
##%% *****
#%% ***
%% * *
%%
%%%%%
%%%
-----------------------------------------------------------------------------
@brief command manipulation class
-----------------------------------------------------------------------------
*/
#pragma once
#include <stdexcept>
#include <cmath>
#include <portable_endian.h>
#include <string>
#include <sstream>
/*!
* @struct CommandBytes
* @brief wrapper for bytes array of command
*/
#if __BYTE_ORDER == __BIG_ENDIAN
#pragma pack(1)
struct CommandBytes {
const uint16_t header = 0x75aa; //! Header byte
const uint8_t device = 0x13; //! Source device 0x13 = PCBoard
uint8_t target; //! target device 0x22 = R V10 0x21 = L V10
const int8_t reserved = 0x00;
//(0x11 = left, 0x12 = right)
int16_t left_front_rpm = 0; //! Left Motor RPM Byte
int16_t left_rear_rpm = 0; //! Left Motor RPM Byte
int16_t right_front_rpm = 0; //! Left Motor RPM Byte
int16_t right_rear_rpm = 0; //! Left Motor RPM Byte
const uint16_t footer = 0x75ff; //! Footer byte
} __attribute__((__packed__));
#pragma pack()
#elif __BYTE_ORDER == __LITTLE_ENDIAN
#pragma pack(1)
struct CommandBytes {
const uint16_t header = 0xaa75; //! Header byte
const uint8_t device = 0x13; //! Source device 0x13 = PCBoard(0x11 = left, 0x12 = right)
uint8_t target; //! target device 0x22 = R V10 0x21 = L V10
const int8_t reserved = 0x00;
int16_t left_front_rpm = 0; //! Left Motor RPM Byte
int16_t left_rear_rpm = 0; //! Left Motor RPM Byte
int16_t right_front_rpm = 0; //! Left Motor RPM Byte
int16_t right_rear_rpm = 0; //! Left Motor RPM Byte
const uint16_t footer = 0xff75; //! Footer byte
} __attribute__((__packed__));
#pragma pack()
#endif
/*!
* @class MotorCommand
* @brief wrapper class for bytes array of command
*/
class MotorCommand
{
public:
signed short left_front_rpm {0}; //! left motor rotation speed
signed short left_rear_rpm {0}; //! left motor rotation speed
signed short right_front_rpm {0}; //! left motor rotation speed
signed short right_rear_rpm {0}; //! left motor rotation speed
signed short max_rpm_ {4000}; //! max motor rotation speed
MotorCommand() = default;
MotorCommand& operator=(const MotorCommand& command) = default;
MotorCommand(const signed short& left, const signed short& right);
MotorCommand(const signed short& left_front, const signed short& left_rear,
const signed short& right_front, const signed short& right_rear);
MotorCommand(const CommandBytes& command);
void set(const signed short& left, const signed short& right);
void set(const signed short& left_front, const signed short& left_rear,
const signed short& right_front, const signed short& right_rear);
void set(const CommandBytes& command);
CommandBytes toLeftByteArray() const;
CommandBytes toRightByteArray() const;
std::string serialize() const;
void deserialize(const std::string& serialized);
};
| true |
15ea24e2a0c44c0d34d7f2f2ed759530a58b492d | C++ | carlygrizzaffi/Robotics | /buildacircuit/buildacircuit.ino | UTF-8 | 927 | 2.78125 | 3 | [] | no_license | #include <Servo.h>
int piezo = A0;
int sensorReading = 0;
int threshold = 490;
Servo servoLeft;
Servo servoRight;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
servoLeft.attach(13); // Attach left signal to pin 13
servoRight.attach(12); // Attach right signal to pin 12
servoLeft.writeMicroseconds(1500); // Calibrate left servo
servoRight.writeMicroseconds(1500);
}
void movement(){
servoLeft.writeMicroseconds(1700);
servoRight.writeMicroseconds(1300);
}
void loop() {
// put your main code here, to run repeatedly:
sensorReading = analogRead(piezo);
Serial.println(sensorReading);
if (sensorReading >= 490) {
movement();
delay(100);
}else{
servoLeft.writeMicroseconds(1500);
servoRight.writeMicroseconds(1500);
delay(100);
}
delay(100);
}
| true |
e58e299a78d3c9ec4872c61d502ea77d4e032248 | C++ | theoemms/Psycles | /Vector3.cpp | UTF-8 | 2,723 | 3.5625 | 4 | [] | no_license | #include "includes.h"
#include <sstream>
#include <string>
#include<math.h>
using namespace std;
Vector3::Vector3(float X, float Y, float Z) //Constructor
{
x = X;
y = Y;
z = Z;
}
Vector3::Vector3()
{
x = y = z = 0;
}
Vector3 Vector3::operator+(const Vector3 rhs)
{
return Vector3(this->x + rhs.x, this->y + rhs.y, this->z + rhs.z);
}
Vector3 Vector3::operator-(const Vector3 rhs)
{
return Vector3(this->x - rhs.x, this->y - rhs.y, this->z - rhs.z);
}
Vector3 Vector3::operator*(const float rhs)
{
return Vector3(rhs * this->x, rhs * this->y, rhs * this->z);
}
Vector3 Vector3::operator+= (const Vector3 rhs) //Cmp Vector addition
{
*this = *this + rhs;
return *this;
}
Vector3 Vector3::operator-= (const Vector3 rhs) //Cmp Vector subtraction
{
*this = *this - rhs;
return *this;
}
Vector3 Vector3::operator*= (const float rhs) //Cmp Scalar Product (a = a * b)
{
this->x *= rhs;
this->y *= rhs;
this->z *= rhs;
return *this;
}
Vector3 Vector3::operator%= (const Vector3 rhs) //Cmp Cross Product (a = Cross(a, b))
{
Vector3 Output = Cross(*this, rhs);
this->x = Output.x;
this->y = Output.y;
this->z = Output.z;
return *this;
}
Vector3 Vector3::operator-()
{
return *this * -1;
}
string Vector3::ToString()
{
ostringstream stream;
stream << "(" << this->x << ", " << this->y << ", " << this->z << ")";
return stream.str();
}
GLfloat* Vector3::ToGLFloat3()
{
GLfloat* output = (GLfloat*) malloc(sizeof(GLfloat) * 3);
output[0] = this->x;
output[1] = this->y;
output[2] = this->z;
return output;
}
GLfloat* Vector3::ToGLFloat4(float w)
{
GLfloat* output = (GLfloat*) malloc(sizeof(GLfloat) * 4);
output[0] = this->x;
output[1] = this->y;
output[2] = this->z;
output[3] = w;
return output;
}
float Vector3::Dot(Vector3 a, Vector3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
Vector3 Vector3::Cross(Vector3 a, Vector3 b)
{
return Vector3(a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
}
Vector3 operator*(const Vector3 lhs, const float rhs)
{
return Vector3(rhs * lhs.x, rhs * lhs.y, rhs * lhs.z);
}
Vector3 operator*(const float lhs, const Vector3 rhs)
{
return rhs * lhs;
}
Vector3 Vector3::fromSpherical(float rho, float theta, float phi)
{
return Vector3(rho * cos(theta * 3.14159f / 180) * sin(phi * 3.14159f / 180),
rho * sin(-theta * 3.14159f / 180),
rho * cos(theta * 3.14159f / 180) * cos(phi * 3.14159f / 180));
} | true |
01bf825d4692d1cf65c9c27040bcc9c93be1df4c | C++ | AugustoPedron/CollaborativeEditor | /Editor/Editor/CRDT/CRDT.h | UTF-8 | 2,258 | 2.6875 | 3 | [] | no_license | #pragma once
#include <vector>
#include <exception>
#include <fstream>
#include <string>
#include <iostream>
#include "Symbol.h"
#include "Message.h"
#include "Cursor.h"
#include "../Editor/UserInterval.h"
#define INSERT 0
#define DELETE_S 1
#define CHANGE 2
class CRDT
{
private:
int m_senderId;
int m_counter;
std::vector<Symbol> m_symbols;
std::vector<UserInterval> m_usersInterval;
std::map<int, std::vector<Symbol>::iterator> m_remoteUserCursorPos;
std::vector<Symbol>::iterator m_localCursorPos;
//uso __int64 per evitare warning e perdita dati per troncamento
__int64 insert_symbol(Symbol symbol);
__int64 delete_symbol(Symbol symbol);
__int64 change_symbol(Symbol symbol);
QString crdt_serialize();
public:
CRDT(int id);
~CRDT();
Message localInsert(int index, char value, QFont font, QColor color, Qt::AlignmentFlag alignment);
Message localErase(int index);
Message localChange(int index, char value, QFont font, const QColor color, Qt::AlignmentFlag alignment);
int getId();
Symbol getSymbol(int index);
__int64 process(const Message& m);
std::string to_string();//usare Qstring??
std::vector<Message> getMessageArray();//SERVER ONLY-->questo vettore va mandato con un for ai socket con all'interno un serializzatore mando i messaggi uno alla volta
std::vector<Message> readFromFile(std::string fileName);
void saveOnFile(std::string filename);//versione base salva solo i caratteri e non il formato--> da testare
bool isEmpty();
void updateUserInterval();
inline std::vector<UserInterval>* getUsersInterval() { return &m_usersInterval; };
void setSiteCounter(int siteCounter);
inline int getSiteCounter() { return m_counter; };
Cursor getCursorPosition(int index);
std::vector<Symbol>::iterator getCursorPosition(std::vector<int> crdtPos);
__int64 convertIteratorToIntPos(std::vector<Symbol>::iterator it);
void addRemoteUser(int userId, std::vector<int> pos);
void updateRemoteUserPos(int userId, std::vector<int> pos);
void updateLocalUserPos(int index);
//for fractional position debug only
void printPositions()
{
for (Symbol s : m_symbols) {
std::vector<int> dv = s.getPos();
for (int d : dv)
std::cout << d << " ";
std::cout << std::endl;
}
std::cout << std::endl;
}
};
| true |
fddef5f1d61210abfb94eb0c21c17218043bfac6 | C++ | yutaka-watanobe/problem-solving | /Uva/Uva2008/11100/11100Acc.cpp | UTF-8 | 1,592 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
using namespace std;
#define MAX 10000
typedef vector<int> vint;
int bugs[10000001];
int n, size;
class scmp {
public:
bool operator()(const vint& a,const vint &b){
return a.size() < b.size();
}
};
void compute(){
multiset<vint, scmp> pieces;
for ( int i = 0; i < 1000001; i++ ){
if ( !bugs[i] ) continue;
int nn = min( bugs[i],(int)pieces.size() );
vector<vint> nextp(nn);
for ( int j = 0; j < nn; j++ ){
nextp[j] = *pieces.begin(); pieces.erase(pieces.begin());
nextp[j].push_back(i);
}
for ( int j = 0; j < nn; j++ ){
pieces.insert(nextp[j]);
}
for ( int j = 0; j < bugs[i] - nn; j++ ){
vint p;
p.push_back(i);
pieces.insert(p);
}
}
/*
printf("%d\n", pieces.size());
for ( multiset<Piece>::iterator it = pieces.begin(); it != pieces.end(); it++ ){
Piece p = *it;
for ( int i = 0; i < p.size; i++ ){
if (i) printf(" ");
printf("%d", p.buffer[i]);
}
printf("\n");
}
*/
cout << pieces.size() << endl;
int ss=pieces.size();
for ( int i = 0; i < ss; i++ ){
vint o=*pieces.begin();
for ( int j = 0; j < o.size(); j++ ){
cout << o[j] << (j+1==o.size() ? '\n' : ' ');
}
pieces.erase(pieces.begin());
}
}
void initialize(){
int x;
for ( int i = 0; i < 1000001; i++ ) bugs[i] = 0;
for ( int i = 0; i < n; i++ ){
scanf("%d", &x); bugs[x]++;
}
}
int main(){
while(1){
scanf("%d", &n);
if ( n == 0 ) break;
initialize();
compute();
}
return 0;
}
| true |
c1f15cea47daa824f76e378ec196f18beb8d567f | C++ | OnlyCheng/MyCorner | /IsPopOrder.cpp | UTF-8 | 1,296 | 3.71875 | 4 | [] | no_license | //借助一个辅助栈来实现
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
int size1 = pushV.size();
int size2 = popV.size();
if(size1 != size2)
return false;
stack<int> s;//辅助栈
int index = 0;
int i = 0;
for(; i<size2; i++)
{
//如果在辅助栈中还没有当前的数字,先将当前数字以及前边还没有压过的都压入辅助栈中
while(index <= GetIndex(pushV,popV[i]))
s.push(pushV[index++]);
//栈顶元素与当前元素对比,相同则表示可以取到当前数字,直接将当前数字出栈,循环继续
if(!s.empty() && s.top() == popV[i])
{
s.pop();
continue;
}
//说明当前想要出栈的元素已经压入到辅助栈了且不在栈顶,那么,当前序列肯定不满足条件
break;
}
if(i == size2)
return true;
return false;
}
int GetIndex(vector<int> pushV,int num)
{
int size = pushV.size();
for(int i = 0; i<size; i++)
if(pushV[i] == num)
return i;
return -1;
}
};
| true |
c4bf0a1c118823c32d4bea45d45008fa2ca20a01 | C++ | NREL/EnergyPlus | /third_party/Windows-CalcEngine/src/SingleLayerOptics/tst/units/CircularPerforatedCell.unit.cpp | UTF-8 | 4,097 | 2.609375 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | #include <memory>
#include <gtest/gtest.h>
#include "WCECommon.hpp"
#include "WCESingleLayerOptics.hpp"
using namespace SingleLayerOptics;
using namespace FenestrationCommon;
class TestCircularPerforatedCell : public testing::Test
{
private:
std::shared_ptr<CCircularCellDescription> m_DescriptionCell;
std::shared_ptr<CPerforatedCell> m_PerforatedCell;
protected:
virtual void SetUp()
{
// create material
const auto Tmat = 0.1;
const auto Rfmat = 0.7;
const auto Rbmat = 0.8;
const auto minLambda = 0.3;
const auto maxLambda = 2.5;
const auto aMaterial =
Material::singleBandMaterial(Tmat, Tmat, Rfmat, Rbmat, minLambda, maxLambda);
// make cell geometry
const auto x = 10; // mm
const auto y = 10; // mm
const auto thickness = 1; // mm
const auto radius = 5; // mm
m_DescriptionCell = std::make_shared<CCircularCellDescription>(x, y, thickness, radius);
m_PerforatedCell = std::make_shared<CPerforatedCell>(aMaterial, m_DescriptionCell);
}
public:
std::shared_ptr<CPerforatedCell> GetCell()
{
return m_PerforatedCell;
};
std::shared_ptr<CCircularCellDescription> GetDescription()
{
return m_DescriptionCell;
};
};
TEST_F(TestCircularPerforatedCell, TestCircular1)
{
SCOPED_TRACE("Begin Test: Circular perforated cell (Theta = 0, Phi = 0).");
std::shared_ptr<CPerforatedCell> aCell = GetCell();
std::shared_ptr<ICellDescription> aCellDescription = GetDescription();
double Theta = 0; // deg
double Phi = 0; // deg
Side aFrontSide = Side::Front;
Side aBackSide = Side::Back;
CBeamDirection aDirection = CBeamDirection(Theta, Phi);
double Tdir_dir = aCellDescription->T_dir_dir(aFrontSide, aDirection);
EXPECT_NEAR(0.785398163, Tdir_dir, 1e-6);
double Tdir_dif = aCell->T_dir_dif(aFrontSide, aDirection);
EXPECT_NEAR(0.021460184, Tdir_dif, 1e-6);
double Rfdir_dif = aCell->R_dir_dif(aFrontSide, aDirection);
EXPECT_NEAR(0.150221286, Rfdir_dif, 1e-6);
double Rbdir_dif = aCell->R_dir_dif(aBackSide, aDirection);
EXPECT_NEAR(0.171681469, Rbdir_dif, 1e-6);
}
TEST_F(TestCircularPerforatedCell, TestCircular2)
{
SCOPED_TRACE("Begin Test: Rectangular perforated cell (Theta = 45, Phi = 0).");
std::shared_ptr<CPerforatedCell> aCell = GetCell();
std::shared_ptr<ICellDescription> aCellDescription = GetDescription();
double Theta = 45; // deg
double Phi = 0; // deg
Side aFrontSide = Side::Front;
Side aBackSide = Side::Back;
CBeamDirection aDirection = CBeamDirection(Theta, Phi);
double Tdir_dir = aCellDescription->T_dir_dir(aFrontSide, aDirection);
EXPECT_NEAR(0.706858347, Tdir_dir, 1e-6);
double Tdir_dif = aCell->T_dir_dif(aFrontSide, aDirection);
EXPECT_NEAR(0.029314165, Tdir_dif, 1e-6);
double Rfdir_dif = aCell->R_dir_dif(aFrontSide, aDirection);
EXPECT_NEAR(0.205199157, Rfdir_dif, 1e-6);
double Rbdir_dif = aCell->R_dir_dif(aBackSide, aDirection);
EXPECT_NEAR(0.234513322, Rbdir_dif, 1e-6);
}
TEST_F(TestCircularPerforatedCell, TestCircular3)
{
SCOPED_TRACE("Begin Test: Rectangular perforated cell (Theta = 78, Phi = 45).");
std::shared_ptr<CPerforatedCell> aCell = GetCell();
std::shared_ptr<ICellDescription> aCellDescription = GetDescription();
double Theta = 78; // deg
double Phi = 45; // deg
Side aFrontSide = Side::Front;
Side aBackSide = Side::Back;
CBeamDirection aDirection = CBeamDirection(Theta, Phi);
double Tdir_dir = aCellDescription->T_dir_dir(aFrontSide, aDirection);
EXPECT_NEAR(0.415897379, Tdir_dir, 1e-6);
double Tdir_dif = aCell->T_dir_dif(aFrontSide, aDirection);
EXPECT_NEAR(0.058410262, Tdir_dif, 1e-6);
double Rfdir_dif = aCell->R_dir_dif(aFrontSide, aDirection);
EXPECT_NEAR(0.408871835, Rfdir_dif, 1e-6);
double Rbdir_dif = aCell->R_dir_dif(aBackSide, aDirection);
EXPECT_NEAR(0.467282097, Rbdir_dif, 1e-6);
}
| true |
ac16df0f7a30f23ef968cfafe5b772481a17b91d | C++ | vseledkin/SumProductNetwork | /PoonSPN/PoonParameter.h | UTF-8 | 4,326 | 2.796875 | 3 | [] | no_license | /*
Like Poon's "Parameter" class
Stores variables and process arguments
This should be a singleton. The reasoning is that it will be inconviente to make fast changes if I have to pass parmaters or a param object around all the time.
I should pass it into the main class though and try to pass it through as much as possible.
*/
#ifndef POONPARAMETER_H
#define POONPARAMETER_H
#include <string>
#include <vector>
#include <memory>
#include <iostream>
#include <stdlib.h>
#include <random>
class PoonParameter {
public:
//input and files
std::string inputPath_ = "";
int maxIter_;
double thresholdLLHChg_;
int batch_size_ = 50;
double sparsePrior_;
// SPN
int numSumPerRegion_;
int inputDim1_; //height
int inputDim2_; //width
int baseResolution_;
double smoothSumCnt_;
int numComponentsPerVar_;
// Eval
int maxTestSize_;
std::string domain_;
int numSlavePerClass_;
int numSlaveGrp_;
//MPI values
// buffer
static int buf_idx_;
static const int buf_size_ = 10000000;
static const int buf_size_double_ = 100;
static std::vector<int> buf_int_; //instantiation in cpp
static std::vector<double> buf_double_; //instantiation in cpp
static std::string buf_char_;
// MPI util
/*
static double recvDouble(int src, int tag) {
MPI.COMM_WORLD.Recv(MyMPI.buf_double_, 0, 1, MPI.DOUBLE, src, tag);
return MyMPI.buf_double_[0];
}
static void sendDouble(int dest, int tag, double d) {
MyMPI.buf_double_[0] = d;
MPI.COMM_WORLD.Send(MyMPI.buf_double_, 0, 1, MPI.DOUBLE, dest, tag);
}
static char recvChar(int src, int tag) {
MPI.COMM_WORLD.Recv(MyMPI.buf_char_, 0, 1, MPI.CHAR, src, tag);
return MyMPI.buf_char_[0];
}
static void sendChar(int dest, int tag, char c) {
MyMPI.buf_char_[0] = c;
MPI.COMM_WORLD.Send(MyMPI.buf_char_, 0, 1, MPI.CHAR, dest, tag);
}*/
//Set default values
PoonParameter(){
maxIter_ = 30;
thresholdLLHChg_ = 0.1;
batch_size_ = 50;
sparsePrior_ = 1;
// SPN
numSumPerRegion_ = 20;
inputDim1_ = 64;
inputDim2_ = 64;
baseResolution_ = 4;
smoothSumCnt_ = 0.01;
numComponentsPerVar_ = 4; //number of mixture components per variable
// Eval
maxTestSize_ = 50;
domain_ = "";
numSlavePerClass_ = 50;
numSlaveGrp_ = 1;
//MPI
buf_idx_ = 0;
};
//Poon's proc and procArgs
//return true if valid, false if not
bool processArgs(int argc, char* argv[]){
//parse the arguments
std::vector<std::string> args(argv + 1, argv + argc);
for (unsigned int i = 0; i < args.size(); i++){
if (args[i] == "-d") {
this->domain_ = args[++i];
}
else if (args[i] == "-path") {
this->inputPath_ = args[++i];
}
else if (args[i] == "-ncv") {
this->numComponentsPerVar_ = atoi(args[++i].c_str());
}
else if (args[i] == "-nsr") {
this->numSumPerRegion_ = atoi(args[++i].c_str());
}
else if (args[i] == "-sp") {
this->sparsePrior_ = atof(args[++i].c_str());
}
else if (args[i] == "-br") {
this->baseResolution_ = atoi(args[++i].c_str());
}
else if (args[i] == "-ct") {
this->thresholdLLHChg_ = atof(args[++i].c_str());
}
else if (args[i] == "-bs") {
this->batch_size_ = atoi(args[++i].c_str());
}
else if (args[i] == "-ns") {
this->numSlavePerClass_ = atoi(args[++i].c_str());
}
else if (args[i] == "-nsg") {
this->numSlaveGrp_ = atoi(args[++i].c_str());
}
}
//safty check
if (this->domain_ == "") {
std::cout << "\n\nOptions: [-d <domain>]\n[-sp <sparsePrior>]\n[-br <baseResolution>]\n[-ncv <numComponentsPerVar>]\n[-nsr <numSumPerRegion>]\n[-ct <convergencyThrehold>]\n[-bs <batchSize>]\n[-ns <numSlavePerCat>]\n[-nsg <numSlaveGrp>]\n";
return false;
}
return true;
};
};
//a class to turn the paramaters into a singletonesque class
//the instance will stay alive as long as there is an instance of it alive somwhere.
//This alows one to use it as singleton if they desire.
template <typename PoonParameter>
class SharedParams {
public:
static std::shared_ptr<PoonParameter> instance()
{
auto ptr = s_instance.lock();
if (!ptr) {
ptr = std::make_shared<PoonParameter>();
s_instance = ptr;
}
return ptr;
}
private:
static std::weak_ptr<PoonParameter> s_instance;
};
template <typename PoonParameter>
std::weak_ptr<PoonParameter> SharedParams<PoonParameter>::s_instance;
#endif | true |
a2ff2960abbc8100942015eb4e72ab3cb20f65b9 | C++ | INFO-ID-2018-2021/POO | /Problema 1/Problema 1.cpp | UTF-8 | 409 | 3.25 | 3 | [] | no_license | // Problema 1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "Rational.h"
int main()
{
try {
Rational<int> f = Rational<int>(2, 3);
Rational<int> g = Rational<int>(2);
Rational<int> h = f / g;
std::cout << h;
}
catch (std::invalid_argument exception) {
std::cout << "Numitorul nu poate fi 0";
}
}
//2/3+2/1 = 2/3+6/3=8/3 | true |
bcf9d706f4cafaabc34865b8ae5c1025230c070b | C++ | chrishaukap/GameDev | /angel_1_1/Code/Tetris/Game.cpp | UTF-8 | 2,892 | 2.671875 | 3 | [] | no_license | #include "StdAfx.h"
#include "Game.h"
#include "Grid.h"
#include "Block.h"
#include <assert.h>
using namespace CDH;
using namespace Tetris;
#define DEBUG_BLOCKS
#define BLOCK_MOVE_SPEED 1.0f
#define BLOCK_FALL_SPEED 0.5f
const float Game::BlockMoveSpeed = BLOCK_MOVE_SPEED;
Game::Game(CHUint rows, CHUint cols) :
m_grid(new Grid(rows, cols)),
m_activeBlock(NULL),
m_blocks(),
m_blockFallingSpeed(BLOCK_FALL_SPEED),
m_state(Uninitialized)
{}
Game::~Game()
{
delete m_grid; m_grid = NULL;
delete m_activeBlock; m_activeBlock = NULL;
int numBlocks = (int)m_blocks.size();
for( int i=0; i<numBlocks; ++i )
delete m_blocks[i];
m_blocks.clear();
}
CHUint
Game::numRows() const
{
return m_grid->rows();
}
CHUint
Game::numCols() const
{
return m_grid->cols();
}
const Block*
Game::activeBlock() const
{
return m_activeBlock;
}
const std::vector<Block*>&
Game::blockGrid() const
{
return m_blocks;
}
void
Game::createNewActiveBlock()
{
BlockType blockType = LineBlock;
CHUint row = 0;
CHUint col = CHUint((m_grid->cols()-1) * 0.5f);
#ifndef DEBUG_BLOCKS
blockType = (BlockType)MathUtil::RandomIntInRange(0, NumBlockTypes);
#endif
m_activeBlock = new Block(blockType, (float)col, (float)row);
}
void
Game::addBlocksToBottomGrid()
{
assert(m_activeBlock != NULL);
m_blocks.push_back(m_activeBlock);
const std::vector<Square>& squares = m_activeBlock->squares();
for( std::vector<Square>::const_iterator iter = squares.begin();
iter != squares.end();
++iter )
{
CHUint row, col;
iter->SnappedCellPosition(col, row);
Cell& cell = m_grid->cell(col,row);
cell.setOccupyingBlock(m_activeBlock);
}
m_activeBlock = NULL;
}
void
Game::moveActiveBlockDown()
{
m_activeBlock->moveDown(BlockMoveSpeed, *m_grid);
}
void
Game::moveActiveBlockLeft()
{
m_activeBlock->moveLeft(BlockMoveSpeed, *m_grid);
}
void
Game::moveActiveBlockRight()
{
m_activeBlock->moveRight(BlockMoveSpeed, *m_grid);
}
bool
Game::rowsCompleted() const
{
CHUint cols = m_grid->cols();
CHUint rows = m_grid->rows();
for( CHUint j=0; j<rows; ++j )
{
bool rowComplete = true;
for( CHUint i=0; i<cols; ++i )
{
if(m_grid->cell(i,j).isEmpty())
{
rowComplete = false;
break;
}
}
if(rowComplete)
m_rowsCompleted.push_back(j);
}
return !m_rowsCompleted.empty();
}
void
Game::start()
{
m_state = FallingBlock;
}
void
Game::stop()
{
m_state = Uninitialized;
}
void
Game::update(float dt)
{
switch(m_state)
{
case FallingBlock:
{
if(m_activeBlock == NULL)
createNewActiveBlock();
bool collision = m_activeBlock->moveDown(m_blockFallingSpeed * dt, *m_grid);
if(collision)
{
addBlocksToBottomGrid();
if(rowsCompleted())
m_state = Cascading;
else
createNewActiveBlock();
}
}
break;
case Cascading:
assert(!"not implemented");
break;
default: assert( !"unknown game state" );
}
} | true |
dac353dcf2b2e31a8b27fe001f28276537f90b38 | C++ | AlexHeiden/Portfolio_cpp | /A4/main.cpp | UTF-8 | 2,884 | 3 | 3 | [] | no_license | #include <iostream>
#include <stdexcept>
#include <memory>
#include "shape.hpp"
#include "rectangle.hpp"
#include "circle.hpp"
#include "base-types.hpp"
#include "matrix.hpp"
#include "composite-shape.hpp"
int main()
{
try
{
stepanov::Rectangle rectangleForFirstLayer({ 4.0, 2.0, {0.0, 0.0} });
stepanov::Circle circleForFirstLayer({ 3.0, 0.0 }, 1.0);
stepanov::CompositeShape compositeShapeForFirstLayer;
stepanov::CompositeShape newTestCompositeShape;
stepanov::Circle circleForCompositeShape({ 0.0, 2.0 }, 1.0);
stepanov::Rectangle rectangleForCompositeShape({ 4.0, 2.0, {3.0, 2.0} });
stepanov::Rectangle rectangleForSecondLayer({ 4.0, 2.0, {5.0, -1.0} });
try
{
compositeShapeForFirstLayer.add(std::make_shared<stepanov::Rectangle>(rectangleForCompositeShape));
compositeShapeForFirstLayer.add(std::make_shared<stepanov::Circle>(circleForCompositeShape));
}
catch (const std::invalid_argument& error)
{
std::cerr << "Invalid argument error: " << error.what();
return 1;
}
stepanov::CompositeShape compositeShapeForSplit;
try
{
compositeShapeForSplit.add(std::make_shared<stepanov::Rectangle>(rectangleForFirstLayer));
compositeShapeForSplit.add(std::make_shared<stepanov::Circle>(circleForFirstLayer));
compositeShapeForSplit.add(std::make_shared<stepanov::CompositeShape>(compositeShapeForFirstLayer));
compositeShapeForSplit.add(std::make_shared<stepanov::Rectangle>(rectangleForSecondLayer));
}
catch (const std::invalid_argument& error)
{
std::cerr << "Invalid argument error: " << error.what();
return 1;
}
catch (const std::logic_error& error)
{
std::cerr << "Logic error: " << error.what();
return 1;
}
std::cout << "The data of matrix after adding shapes\n";
stepanov::Matrix matrix = compositeShapeForSplit.split();
matrix.print();
std::cout << "Rotate demonstration\n"
<< "The data of rectangle before rotate:\n";
rectangleForFirstLayer.print();
std::cout << "The data of rectangle after rotate:\n";
rectangleForFirstLayer.rotate(45);
rectangleForFirstLayer.print();
std::cout << "The data of circle before rotate:\n";
circleForFirstLayer.print();
std::cout << "The data of circle after rotate:\n";
circleForFirstLayer.rotate(30);
circleForFirstLayer.print();
std::cout << "The data of composite-shape before rotate:\n";
compositeShapeForFirstLayer.print();
std::cout << "The data of composite-shape after rotate:\n";
compositeShapeForFirstLayer.rotate(45);
compositeShapeForFirstLayer.print();
}
catch (const std::exception& error)
{
std::cerr << "An unexpected error occured";
return 1;
}
return 0;
}
| true |
0a1678884cd29a9eeee186621807585a6a933fe7 | C++ | Seottle/OJ-RESOLUTION | /POJ/1077/12856833_AC_750ms_8124kB.cpp | UTF-8 | 3,278 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
//A* 八数码问题
int idist[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
char strpath[4] = {'d', 'u', 'r', 'l'};
char key[10];
int factor[10];
struct _Node{
int val, pos;
int f, g, h;
_Node(){
}
_Node(int _val, int _pos, int _g, int _h)
{
val = _val; pos = _pos; h = _h; g = _g; f = _g + _h;
}
bool operator < (const _Node &a) const {
return f>a.f;
}
};
struct _Path{
int from, dist;
} path[500000];
int visit[500000];
int G[500000];
stack<int> s;
int cantor()
{
int res = 0;
for(int i = 0; key[i]; i ++)
for(int j = i + 1; key[j]; j ++)
if(key[i] > key[j]) res += factor[8 - i];
return res;
}
void cantor_reverse(int val)
{
int tmp[10], flag[10];
memset(flag,0,sizeof(flag));
for(int i = 0; i < 9; i++) tmp[i]=val/factor[8-i],val=val%factor[8-i];
for(int i = 0; i < 9; i++)
{
int num=0;
for(int j=0;j<9;j++)
{
if(flag[j]==0) num++;
if(num==tmp[i]+1)
{
key[i]=j+'0'+1; if(key[i]=='9') key[i]='x';
flag[j]=1;break;
}
}
}
}
int get_h(int val)
{
char tmp[10];
for(int i=0;i<=9;i++) tmp[i]=key[i];
cantor_reverse(val);
int res=0;
for(int i=0;i<9;i++)
{
if(i<8) if(key[i]-'0'!=i+1) res++;
if(i==8&&key[i]!='x') res++;
}
for(int i=0;i<=9;i++) key[i]=tmp[i];
return res;
}
void Astar(int val, int pos)
{
priority_queue<_Node> q;
path[val].from = path[val].dist = -1;
visit[val] = 2;
G[val] = 0;
int m = get_h(val);
q.push(_Node(val, pos, 0, m));
while(!q.empty())
{
_Node x = q.top(); q.pop(); visit[val] = 2;
cantor_reverse(x.val);
//cout << key << endl;
if(x.val == 0)
{
int t = x.val;
while(path[t].from != -1)
{
s.push(path[t].dist);
t = path[t].from;
}
return;
}
int a = x.pos/3, b = x.pos%3;
for(int i = 0; i < 4; ++i)
{
int dx = a + idist[i][0], dy = b + idist[i][1];
if(!(dx <= 2 && dx >= 0 && dy <= 2 && dy >= 0)) continue;
int curpos = dx * 3 + dy;
swap(key[curpos], key[x.pos]);
int curkey = cantor();
swap(key[curpos], key[x.pos]);
if(visit[curkey] == 0 || (visit[curkey] == 1 && x.g + 1 < G[curkey]) )
{
visit[curkey] = 1; G[curkey] = x.g + 1;
path[curkey].from = x.val; path[curkey].dist = i;
q.push(_Node(curkey, curpos, x.g + 1, get_h(val)));
}
}
}
}
void INIT()
{
memset(visit, 0, sizeof(visit));
memset(G, -1, sizeof(G));
factor[0] = 1;
for(int i = 1; i <= 8; ++i) factor[i] = factor[i - 1]*i;
}
int main()
{
char op[10];
while(scanf("%s", op) != EOF)
{
INIT();
key[0] = op[0];
int position = 0;
for(int i = 1; i <= 8; ++i)
{
scanf("%s", op);
key[i] = op[0];
if(key[i] == 'x') position = i;
}
int num = 0;
for(int i = 0; i < 9; ++i)
{
if(key[i] == 'x') continue;
for(int j = 0; j < i; ++j)
{
if(key[j] == 'x') continue;
if(key[i] < key[j]) num++;
}
}
if(num %2 == 1) printf("unsolvable\n");
else{
Astar(cantor(), position);
while(!s.empty()) printf("%c", strpath[s.top()]), s.pop();
printf("\n");
}
}
return 0;
} | true |
921f23d6bf47bb46187d80ce0bd2eb26982f7c29 | C++ | SpaceMonkeyClan/FreeNOS-1.0.3 | /lib/libstd/Index.h | UTF-8 | 5,489 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2015 Niek Linnenbank
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __LIB_LIBSTD_INDEX_H
#define __LIB_LIBSTD_INDEX_H
#include "Assert.h"
#include "Types.h"
#include "Macros.h"
/**
* @addtogroup lib
* @{
*
* @addtogroup libstd
* @{
*/
/**
* Index is a N-sized array of pointers to items of type T.
*/
template <class T, const Size N> class Index
{
public:
/**
* Constructor.
*/
Index()
: m_count(0)
{
for (Size i = 0; i < N; i++)
{
m_array[i] = ZERO;
}
}
/**
* Adds the given item, if possible.
*
* @param position On output the position of the item in the Index.
* @param item Pointer to the item to add.
*
* @return True on success, false otherwise.
*/
virtual bool insert(Size & position, T *item)
{
// Check if we are full
if (m_count == N)
{
return false;
}
// The item must point to an object
else if (item == ZERO)
{
return false;
}
// There is space, add the item.
for (Size i = 0; i < N; i++)
{
if (m_array[i] == ZERO)
{
m_array[i] = item;
m_count++;
position = i;
return true;
}
}
// Should not be reached
assert(false);
return false;
}
/**
* Adds the given item, if possible.
*
* @param item Pointer to the item to add.
*
* @return True on success, false otherwise.
*/
virtual bool insert(T *item)
{
Size ignored = 0;
return insert(ignored, item);
}
/**
* Inserts the given item at the given position.
*
* If an item exists at the given position, it will be replaced by the given item.
*
* @param position The position to insert the item.
* @param item The item to insert
*
* @return True on success, false otherwise.
*/
virtual bool insertAt(const Size position, T *item)
{
// Position must be in range of the array
if (position >= N)
{
return false;
}
// The item must point to an object
else if (item == ZERO)
{
return false;
}
// Increment counter only when needed
if (m_array[position] == ZERO)
{
m_count++;
}
m_array[position] = item;
return true;
}
/**
* Removes the item at the given position.
*
* @param position The position of the item to remove.
*
* @return bool Whether removing the item succeeded.
*/
virtual bool remove(const Size position)
{
// Position must be in range of the array
if (position >= N)
{
return false;
}
// See if the item exists
if (!m_array[position])
{
return false;
}
m_array[position] = ZERO;
assert(m_count >= 1);
m_count--;
return true;
}
/**
* Removes and delete()'s all items.
*/
void deleteAll()
{
for (Size i = 0; i < N; i++)
{
if (m_array[i] != ZERO)
{
delete m_array[i];
m_array[i] = ZERO;
}
}
m_count = 0;
}
/**
* Returns the item at the given position.
*
* @param position The position of the item to get.
*
* @return Pointer to the item at the given position or ZERO if no item available.
*/
virtual T * get(const Size position) const
{
// Position must be in range of the array
if (position >= N)
{
return ZERO;
}
return m_array[position];
}
/**
* Check if the given item is stored in this Sequence.
*/
virtual bool contains(const T *item) const
{
for (Size i = 0; i < N; i++)
{
if (m_array[i] == item)
{
return true;
}
}
return false;
}
/**
* Size of the Index.
*/
virtual Size size() const
{
return N;
}
/**
* Item count in the Index.
*/
virtual Size count() const
{
return m_count;
}
/**
* Returns the item at the given position in the Index.
*
* @param i The position of the item to return.
*
* @return the Item at position i or ZERO if no item available.
*/
T * operator [] (const Size i)
{
return get(i);
}
private:
/** Array of pointers to items. */
T* m_array[N];
/** Amount of valid pointers in the array. */
Size m_count;
};
/**
* @}
* @}
*/
#endif /* __LIB_LIBSTD_INDEX_H */
| true |
4eb02e5b4009dba3eb1bb4be42a628ce1847c5f2 | C++ | weimingtom/db-verkstan | /db-util/src/helpers.cpp | UTF-8 | 2,022 | 2.9375 | 3 | [] | no_license | #include "db-util.hpp"
Vec3 normalize(const Vec3 &v)
{
float l = length(v);
if (l != 0.0f)
{
return v / l;
}
else
{
return Vec3(1, 0, 0);
}
}
Vec2 normalize(const Vec2 &v)
{
float l = length(v);
if (l != 0.0f)
{
return v / l;
}
else
{
return Vec2(1, 0);
}
}
Vec3 cross(const Vec3 &v1, const Vec3 &v2)
{
Vec3 res;
return *D3DXVec3Cross(&res, &v1, &v2);
}
float frand()
{
return rand() / (float)RAND_MAX;
}
float frand(float min, float max)
{
return frand() * (max - min) + min;
}
float expFalloff(float current, float target, float rate, float dt)
{
return target + (current - target) * powf(2.0f, -dt * rate);
}
////////////////////////////////////////////////////////////////////
// Oscillator style functions
////////////////////////////////////////////////////////////////////
float periodicSin(float time, float period, float min, float max)
{
float t = sinf((time / (2.0f * M_PI)) / period);
return (t + 1.0f) / 2.0f * (max - min) + min;
}
float periodicCos(float time, float period, float min, float max)
{
float t = cosf((time / (2.0f * M_PI)) / period);
return (t + 1.0f) / 2.0f * (max - min) + min;
}
float periodicTriangle(float time, float period, float min, float max)
{
float t = time / period + 0.5f;
t = abs((t - floorf(t)) -0.5f) * 2.0f;
return t * (max - min) + min;
}
float periodicRamp(float time, float period, float min, float max)
{
float t = time / period;
t = t - floorf(t);
return t * (max - min) + min;
}
float step(float time, float startTime, float endTime, float startValue, float endValue)
{
float t = saturate((time - startTime) / (endTime - startTime));
return t * (endValue - startValue) + startValue;
}
float smoothStep(float time, float startTime, float endTime, float startValue, float endValue)
{
float t = saturate((time - startTime) / (endTime - startTime));
t = t * t * (3 - t * t);
return t * (endValue - startValue) + startValue;
} | true |
461726f11d4533d1f228691816a51cf1624b57b6 | C++ | bsmith18/Roboscape | /ExampleCode/Threading/Threading.cpp | UTF-8 | 4,443 | 2.8125 | 3 | [] | no_license | // Threading.cpp
/* This program introduces a thread that handles images as they come into a queue from the
* EventHandler.
*/
#include "roboscape.h"
static uint32_t numGrabbed = 0;
static deque<Mat> cvQueue;
// Number of images to be grabbed.
static const uint32_t c_countOfImagesToGrab = 1000;
static const int bufferSize = 100;
// Example of an image event handler.
class CSampleImageEventHandler : public CImageEventHandler
{
public:
virtual void OnImageGrabbed( CInstantCamera& camera, const CGrabResultPtr& ptrGrabResult)
{
CImageFormatConverter formatConverter;
formatConverter.OutputPixelFormat= PixelType_BGR8packed;
CPylonImage pylonImage;
Mat cvImage;
static INIT_TIMER;
formatConverter.Convert(pylonImage,ptrGrabResult);
cvImage = cv::Mat(ptrGrabResult->GetHeight(),ptrGrabResult->GetWidth(), CV_8UC3, \
(uint8_t *)pylonImage.GetBuffer());
if(numGrabbed < c_countOfImagesToGrab)
{cvQueue.push_back(cvImage.clone());}
numGrabbed++;
//STOP_TIMER("aquire");
START_TIMER;
}
};
void queue_size_checker()
{
int timesEmpty = 0;
while(true)
{
if (cvQueue.empty())
{
timesEmpty++;
if(timesEmpty > 500)
{
cout << "Queue is empty for 500ms." << endl;
return;
}
}
else if(cvQueue.size()>bufferSize)
{
timesEmpty = 0;
cvQueue.erase(cvQueue.begin(),cvQueue.end()-bufferSize);
//cout << "Queue size now " << cvQueue.size() << endl;
}
usleep(1000);
}
}
int main(int argc, char* arv[])
{
// The exit code of the sample application.
int exitCode = 0;
// Before using any pylon methods, the pylon runtime must be initialized.
PylonInitialize();
try
{
// Create an instant camera object with the camera device found first.
CInstantCamera camera(CTlFactory::GetInstance().CreateFirstDevice());
// Print the model name of the camera.
cout << "Using device " << camera.GetDeviceInfo().GetModelName() << endl;
GenApi::INodeMap& nodemap= camera.GetNodeMap();
camera.RegisterImageEventHandler( new CSampleImageEventHandler, RegistrationMode_Append, Cleanup_Delete);
camera.Open();
GenApi::CIntegerPtr width= nodemap.GetNode("Width");
GenApi::CIntegerPtr height= nodemap.GetNode("Height");
camera.MaxNumBuffer = 5;
CImageFormatConverter formatConverter;
formatConverter.OutputPixelFormat= PixelType_BGR8packed;
CPylonImage pylonImage;
// Reduce the resolution to make square image
GenApi::CIntegerPtr(nodemap.GetNode("Width"))->SetValue(1216);
GenApi::CIntegerPtr(nodemap.GetNode("Width"))->SetValue(1216);
// Center x and y pixels
GenApi::CBooleanPtr(nodemap.GetNode("CenterX"))->SetValue(true);
GenApi::CBooleanPtr(nodemap.GetNode("CenterY"))->SetValue(true);
// Set the SensorReadoutMode to fast
//GenApi::CEnumerationPtr(nodemap.GetNode("SensorReadoutMode"))->FromString("Fast");
// Get the resulting frame rate using the settings
double d = GenApi::CFloatPtr(nodemap.GetNode("ResultingFrameRate"))->GetValue();
cout << "Frame Rate " << d << endl;
//Start grabbing of images.
camera.StartGrabbing( GrabStrategy_LatestImageOnly , GrabLoop_ProvidedByInstantCamera);
std::thread sizeChecker (queue_size_checker);
// Can the camera device be queried whether it is ready to accept the next frame trigger?
if (camera.IsGrabbing())
{
// Start the grabbing using the grab loop thread, by setting the grabLoopType parameter
// to GrabLoop_ProvidedByInstantCamera. The grab results are delivered to the image event handlers.
// The GrabStrategy_OneByOne default grab strategy is used.
while(numGrabbed<c_countOfImagesToGrab)
{
cout << "Press ENTER to stop grabbing images" << endl;
if(cin.get() == '\n')
{
break;
}
usleep(1000);
}
cout << '\b' << '\b';
}
int numShow = 0;
while(!cvQueue.empty())
{
imshow("Test",cvQueue.front());
waitKey(1);
cvQueue.pop_front();
cout << numShow << endl;
numShow++;
usleep(500000);
}
sizeChecker.join();
}
catch (const GenericException &e)
{
// Error handling.
cerr << "An exception occurred." << endl
<< e.GetDescription() << endl;
exitCode = 1;
// Remove left over characters from input buffer.
cin.ignore(cin.rdbuf()->in_avail());
}
// Comment the following two lines to disable waiting on exit.
wait_for_Enter();
// Releases all pylon resources.
PylonTerminate();
return exitCode;
}
| true |
6c16c71f1f4843232353a03df7d1d11d649c4c82 | C++ | UnnamedOrange/OI | /Source Code/图论/二分图匹配 模板.cpp | UTF-8 | 1,871 | 2.578125 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
typedef int INT;
using std::cin;
using std::cout;
using std::endl;
inline INT readIn()
{
INT a = 0;
bool minus = false;
char ch = getchar();
while (!(ch == '-' || (ch >= '0' && ch <= '9'))) ch = getchar();
if (ch == '-')
{
minus = true;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
a = a * 10 + (ch - '0');
ch = getchar();
}
if (minus) a = -a;
return a;
}
inline void printOut(INT x)
{
char buffer[20];
INT length = 0;
bool minus = x < 0;
if (minus) x = -x;
do
{
buffer[length++] = x % 10 + '0';
x /= 10;
}
while (x);
if (minus) buffer[length++] = '-';
do
{
putchar(buffer[--length]);
}
while (length);
}
const INT maxn = 1005;
INT n, m, e;
INT linkX[maxn];
std::vector<std::vector<INT> > edges;
bool vis[maxn];
bool augment(INT x)
{
for(int i = 0; i < edges[x].size(); i++)
{
INT to = edges[x][i];
if(vis[to]) continue;
vis[to] = true;
if(!linkX[to] || augment(linkX[to]))
{
linkX[to] = x;
return true;
}
}
return false;
}
void run()
{
n = readIn();
m = readIn();
e = readIn();
edges.resize(n + 1);
for(int i = 1; i <= e; i++)
{
INT u = readIn();
INT v = readIn();
if(u > n || v > m) continue;
edges[u].push_back(v);
}
INT ans = 0;
for(int i = 1; i <= n; i++)
{
memset(vis, 0, sizeof(vis));
ans += augment(i);
}
printOut(ans);
}
int main()
{
run();
return 0;
}
| true |
46b38e195d56828647f724aa021c6c71a57bb20d | C++ | Grandmother/stroustrup_book_tasks | /chapter 4/exercise10.cpp | UTF-8 | 864 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int random(int number)
{
int result;
if ( number > 10 )
{
result = number * (number % 100);
return result;
}
return 4;
}
int main()
{
enum variant {STONE=0, SCISSORS, PAPER};
int turn = 31;
cout << "Press any key to start.\n";
cout << "Turn: " << turn << "\n";
while ( cin.get() )
{
// Let random number always has three digits.
turn = random(turn)%1000;
cout << "Turn: " << turn << "\n";
switch (turn % 3)
{
case STONE:
cout << "STONE\n";
break;
case SCISSORS:
cout << "SCISSORS\n";
break;
case PAPER:
cout << "PAPER\n";
break;
}
cout << "And try again!!!\n";
}
}
| true |
64640c64e36eac9f66edb51994df53d228f7a986 | C++ | DeagleGross/C-Algo-Structures | /Algorithms/KDZ/Debugger.h | UTF-8 | 732 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#ifndef KDZ_DEBUGHELPER_H
#define KDZ_DEBUGHELPER_H
class DebugHelper
{
public:
void logMatrix(const vector<vector<int>>& matrix)
{
std::cout << "\nMatrix::\n";
for (int i = 0; i < matrix.size(); ++i)
{
for (int j = 0; j < matrix[i].size(); ++j)
std::cout << matrix[i][j] << " ";
std::cout << "\n";
}
std::cout << "\n";
}
void logVectorStrings(const vector<string> strings)
{
std::cout << "\nStrings;\n";
for (int i = 0; i < strings.size(); ++i)
std::cout << strings[i] << endl;
std::cout << "\n";
}
};
#endif //KDZ_DEBUGHELPER_H | true |
16fd192c2f43998156757b5a7e5f92de071ffe02 | C++ | regehr/solid_code_class | /compress/group4/test/1each-gen.cpp | UTF-8 | 459 | 2.8125 | 3 | [] | no_license | #include <algorithm>
#include <vector>
#include <cstdio>
#include <cassert>
int main(int argc, char* argv[]) {
char bytes[256];
for (int i = 0; i < 256; i++)
bytes[i] = i;
std::random_shuffle(bytes, bytes+256);
FILE* out = fopen("1each.bin", "w");
assert(out != NULL);
// Ain't nobody got time for write errors
int res = fwrite(bytes, sizeof(char), 256, out);
assert(res == 256);
res = fclose(out);
assert(res == 0);
return 0;
}
| true |
6c28e87d6e218d1f6081ea18cca2a00db604dfe1 | C++ | anukritiagarwal/OOP_Programs-CPP- | /A1.CPP | UTF-8 | 443 | 2.796875 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
struct details
{
char name[30];
int age;
int employeeid;
};
int main()
{
struct details d;
clrscr();
printf("enter name\n");
gets(d.name);
printf("enter age\n");
scanf("%d",&d.age);
printf("enter the id\n");
scanf("%d",&d.employeeid);
printf("name of employee:%s \n",d.name);
printf("age of the employee:%d \n",d.age);
printf("employee id is:%d \n",d.employeeid);
getch();
return 0;
} | true |
5fb3adfcba1ed9fbbff89c0a843cd5d8e341f6b7 | C++ | cesarvr/ZEnginePlus | /ZEnginePlus/zeBuffer.cpp | UTF-8 | 875 | 2.640625 | 3 | [] | no_license | //
// zeBuffer.cpp
// ZEnginePlus
//
// Created by Cesar Luis Valdez on 12/09/13.
// Copyright (c) 2013 Cesar Luis Valdez. All rights reserved.
//
#include "zeBuffer.h"
void zeBuffer::crearVertexBuffer(float *vertices, int size){
std::cout << "sizeoffloat:" << sizeof(float)<< std::endl;
int count = sizeof(vertices)/sizeof(float);
std::cout << "sizeoffloat:" << count << std::endl;
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_STATIC_DRAW);
}
void zeBuffer::crearIndicesBuffer(short *indice, int size){
cantidad_indices = size / sizeof(short);
glGenBuffers(1, &indices_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, indice, GL_STATIC_DRAW);
} | true |
4f3d16d34d856c1c8a4410bbfb65268e87f76776 | C++ | kasprus/zpr_game | /Communication/gamescoremessage.cpp | UTF-8 | 704 | 2.65625 | 3 | [] | no_license | #include "gamescoremessage.h"
#include "communication.h"
#include "messagevisitor.h"
namespace Communication {
GameScoreMessage ::GameScoreMessage(int playersCount) : scores(playersCount, 0), playersCount(playersCount)
{
}
GameScoreMessage::~GameScoreMessage() {
}
int GameScoreMessage::getHeader() const {
return Communication::gameScoreMessageHeader;
}
void GameScoreMessage::accept(const MessageVisitor& visitor) {
visitor.visit(*this);
}
void GameScoreMessage::addScore(int index, int score) {
scores.at(index) = score;
}
std::vector<int> GameScoreMessage::getScore() const {
return scores;
}
int GameScoreMessage::getNumberOfPlayers() const {
return playersCount;
}
}
| true |
2b6f796397e79a3755fdc356da340170ef6e5b58 | C++ | DarranThomas/FileSimilar_GUI | /Similarities/Win32/CMemory.cpp | UTF-8 | 11,022 | 2.53125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////////
#include "pch.h"
///////////////////////////////////////////////////////////////////////////////////
#include "macro.h"
///////////////////////////////////////////////////////////////////////////////////
#include "CMemory.h"
///////////////////////////////////////////////////////////////////////////////////
namespace Win32
{
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/*
void *
PASCAL
operator new
(
size_t size
)
throw()
{
void *p = NULL;
__try
{
DEBUG_BREAK();
p = ::CoTaskMemAlloc( size );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
DEBUG_BREAK();
}
return p;
}
///////////////////////////////////////////////////////////////////////////////
void
PASCAL
operator delete
(
void *p
)
throw()
{
__try
{
DEBUG_BREAK();
::CoTaskMemFree( p );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
DEBUG_BREAK();
}
}
*/
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeAllocateMemory
(
LPVOID &lpv,
size_t NumberofBytes
)
throw()
{
HRESULT hr = S_OK;
if( IS_NOT_NULL( lpv ) )
{
hr = E_POINTER;
ASSERT_SUCCEEDED( hr );
}
else
{
__try
{
lpv = ::CoTaskMemAlloc( NumberofBytes );
if( IS_NULL( lpv ) )
{
hr = E_OUTOFMEMORY;
ASSERT_SUCCEEDED( hr );
}
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeAllocateAlignedMemory
(
LPVOID &lpv,
size_t NumberofBytes,
size_t Alignment
)
throw()
{
HRESULT hr = S_OK;
if( IS_NOT_NULL( lpv ) )
{
hr = E_POINTER;
ASSERT_SUCCEEDED( hr );
}
else
{
__try
{
lpv = _aligned_malloc( NumberofBytes, Alignment );
if( IS_NULL( lpv ) )
{
hr = E_OUTOFMEMORY;
ASSERT_SUCCEEDED( hr );
}
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeReallocateMemory
(
LPVOID &lpv,
size_t NumberofBytes
)
throw()
{
HRESULT hr = S_OK;
__try
{
lpv = ::CoTaskMemRealloc( lpv, NumberofBytes );
if( IS_NULL( lpv ) && ( 0 != NumberofBytes ) )
{
hr = E_OUTOFMEMORY;
ASSERT_SUCCEEDED( hr );
}
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeReallocateAlignedMemory
(
LPVOID &lpv,
size_t NumberofBytes,
size_t Alignment
)
throw()
{
HRESULT hr = S_OK;
__try
{
lpv = _aligned_realloc( lpv, NumberofBytes, Alignment );
if( IS_NULL( lpv ) && ( 0 != NumberofBytes ) )
{
hr = E_OUTOFMEMORY;
ASSERT_SUCCEEDED( hr );
}
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeZeroMemory
(
LPVOID lpv,
size_t NumberofBytes
)
throw()
{
HRESULT hr = S_OK;
if( 0 == NumberofBytes )
{
hr = S_FALSE;
}
else
{
__try
{
RtlZeroMemory( lpv, NumberofBytes );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeCopyMemory
(
LPVOID lpvDst,
LPCVOID lpcvSrc,
size_t NumberofBytes
)
throw()
{
HRESULT hr = S_OK;
if( 0 == NumberofBytes )
{
hr = S_FALSE;
}
else
{
__try
{
RtlCopyMemory( lpvDst, lpcvSrc, NumberofBytes );
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeFreeMemory
(
LPVOID &lpv
)
throw()
{
HRESULT hr = S_OK;
if( IS_NULL( lpv ) )
{
hr = S_FALSE;
}
else
{
__try
{
::CoTaskMemFree( lpv );
lpv = NULL;
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
safeFreeAlignedMemory
(
LPVOID &lpv
)
throw()
{
HRESULT hr = S_OK;
if( IS_NULL( lpv ) )
{
hr = S_FALSE;
}
else
{
__try
{
_aligned_free( lpv );
lpv = NULL;
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
hr = E_ABORT;
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//virtual
STDMETHODIMP
CMemoryAllocator::AllocateMemory
(
LPVOID &reflpv,
size_t NumberofBytes
)
{
return safeAllocateMemory( reflpv, NumberofBytes );
}
///////////////////////////////////////////////////////////////////////////////
//virtual
STDMETHODIMP
CMemoryAllocator::ReallocateMemory
(
LPVOID &reflpv,
size_t NumberofBytes
)
{
return safeReallocateMemory( reflpv, NumberofBytes );
}
///////////////////////////////////////////////////////////////////////////////
//virtual
STDMETHODIMP
CMemoryAllocator::FreeMemory
(
LPVOID &reflpv
)
{
return safeFreeMemory( reflpv );
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
CMemoryHandler::CMemoryHandler()
:
m_lpv( NULL ),
m_NumberofBytes( 0 )
{}
///////////////////////////////////////////////////////////////////////////////
CMemoryHandler::CMemoryHandler
(
const
CMemoryHandler &cref
)
:
m_lpv( NULL ),
m_NumberofBytes( 0 )
{
if( cref.IsValid() )
{
HRESULT hr = Allocate( cref.m_NumberofBytes );
ASSERT_SUCCEEDED( hr );
if( SUCCEEDED( hr ) )
{
hr = CopyFrom( cref.m_lpv, cref.m_NumberofBytes );
ASSERT_SUCCEEDED( hr );
if( FAILED( hr ) )
{
HRESULT hr2 = Free();
ASSERT_SUCCEEDED( hr2 );
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
const
CMemoryHandler &
CMemoryHandler::operator =
(
const
CMemoryHandler &cref
)
{
if( this != &cref )
{
HRESULT hr = Reallocate( cref.m_NumberofBytes );
ASSERT_SUCCEEDED( hr );
if( SUCCEEDED( hr ) )
{
hr = CopyFrom( cref.m_lpv, cref.m_NumberofBytes );
ASSERT_SUCCEEDED( hr );
if( FAILED( hr ) )
{
HRESULT hr2 = Free();
ASSERT_SUCCEEDED( hr2 );
}
}
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CMemoryHandler::Allocate
(
SIZE_T NumberofBytes,
bool bZero
)
{
HRESULT hr = S_OK;
hr = ActualAllocateMemory( m_lpv, NumberofBytes );
ASSERT_SUCCEEDED( hr );
if( SUCCEEDED( hr ) )
{
m_NumberofBytes = NumberofBytes;
if( bZero )
{
hr = Zero();
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CMemoryHandler::Reallocate
(
SIZE_T NumberofBytes,
bool bZero
)
{
HRESULT hr = S_OK;
hr = ActualReallocateMemory( m_lpv, NumberofBytes );
ASSERT_SUCCEEDED( hr );
if( SUCCEEDED( hr ) )
{
m_NumberofBytes = NumberofBytes;
if( bZero )
{
hr = Zero();
ASSERT_SUCCEEDED( hr );
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
bool
CMemoryHandler::IsValid()
const
{
return IS_NOT_NULL( m_lpv );
}
///////////////////////////////////////////////////////////////////////////////
bool
CMemoryHandler::IsInvalid()
const
{
return IS_NULL( m_lpv );
}
///////////////////////////////////////////////////////////////////////////////
const
LPVOID
CMemoryHandler::cpv()
const
{
return m_lpv;
}
///////////////////////////////////////////////////////////////////////////////
LPVOID
CMemoryHandler::pv()
{
return m_lpv;
}
///////////////////////////////////////////////////////////////////////////////
const
BYTE *
CMemoryHandler::cpb()
const
{
return reinterpret_cast< LPBYTE >( m_lpv );
}
///////////////////////////////////////////////////////////////////////////////
BYTE *
CMemoryHandler::pb()
{
return reinterpret_cast< LPBYTE >( m_lpv );
}
///////////////////////////////////////////////////////////////////////////////
SIZE_T
CMemoryHandler::NumberofBytes()
const
{
return m_NumberofBytes;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CMemoryHandler::Zero()
{
HRESULT hr = S_OK;
hr = safeZeroMemory( m_lpv, m_NumberofBytes );
ASSERT_SUCCEEDED( hr );
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CMemoryHandler::CopyFrom
(
LPCVOID lpcv,
SIZE_T NumberofBytes
)
{
HRESULT hr = S_OK;
SIZE_T NumberofBytesToCopy = min( m_NumberofBytes, NumberofBytes );
hr = safeCopyMemory( m_lpv, lpcv, NumberofBytesToCopy );
ASSERT_SUCCEEDED( hr );
if( SUCCEEDED( hr ) )
{
if( NumberofBytes > NumberofBytesToCopy )
{
hr = S_FALSE;
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CMemoryHandler::CopyTo
(
LPVOID lpv,
SIZE_T NumberofBytes
)
const
{
HRESULT hr = S_OK;
SIZE_T NumberofBytesToCopy = min( m_NumberofBytes, NumberofBytes );
hr = safeCopyMemory( lpv, m_lpv, NumberofBytesToCopy );
ASSERT_SUCCEEDED( hr );
if( SUCCEEDED( hr ) )
{
if( NumberofBytes > NumberofBytesToCopy )
{
hr = S_FALSE;
}
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
STDMETHODIMP
CMemoryHandler::Free()
{
HRESULT hr = S_OK;
if( IS_NULL( m_lpv ) )
{
hr = S_FALSE;
}
else
{
hr = ActualFreeMemory( m_lpv );
ASSERT_SUCCEEDED( hr );
m_NumberofBytes = 0;
}
return hr;
}
///////////////////////////////////////////////////////////////////////////////
//virtual
CMemoryHandler::~CMemoryHandler()
{
HRESULT hr = Free();
ASSERT_SUCCEEDED( hr );
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////// | true |
8ea006166ff4b51cee4a1987089e8b3a87f0a778 | C++ | dincerunal/design_patterns | /022-Memento/devicememento/Project/DeviceInfo.h | UTF-8 | 687 | 2.71875 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#include <cstdint>
#include <cstddef>
#include <memory>
class DeviceInfoMemento;
class DeviceInfo { // Originator
public:
DeviceInfo(const std::string &name, const std::string &url)
: m_name(name), m_url(url)
{}
public:
std::string GetName() const { return m_name; }
std::string GetUrl() const { return m_url; }
void AddPort(std::uint16_t port);
//...
size_t size() const { return m_ports.size();}
std::uint16_t &operator [](size_t index);
std::uint16_t operator [](size_t index) const;
public:
std::shared_ptr<DeviceInfoMemento> GetMemento();
private:
std::string m_name, m_url;
std::vector<std::uint16_t> m_ports;
};
| true |
441c66334c03f6d95eb9b60fbd971fdb82a92bde | C++ | toteisla/Tanks-Game-Client- | /lmc/Cliente/Game.cpp | UTF-8 | 6,168 | 2.546875 | 3 | [] | no_license | #include "game.h"
void Game::guardar_config(){
cout << "Guardando configuracion" << endl;
ofstream file;
file.open("config.txt");
if (file.is_open()) {
file << "res_w " << resX << endl;
file << "res_h " << resY << endl;
if (ventana_completa)
file << "completa 1" << endl;
else
file << "completa 0" << endl;
file.close();
} else
cout << "No encuentro config.txt" << endl;
}
int Game::ini(){
bool done = false;
bool redraw = true;
int counter = 0;
Point<float> cam_pos(50, 50);
Point<float> mousePos(0, 0);
bool keys[8] = {false, false, false, false,false,false,false,false};
bool raton_mov[4] = {false,false,false,false};
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_MOUSE_STATE estado_raton;
if(!al_init()) //initialize Allegro
return -1;
if (ventana_completa)
al_set_new_display_flags(ALLEGRO_FULLSCREEN);
else
al_set_new_display_flags(0);
display = al_create_display(resX, resY); //create our display object
if(!display) //test display object
return -1;
Utils utils;
Point<float> playerPos(al_get_display_width(display) / 2 , al_get_display_height(display) / 2);
Player player(playerPos, 20);
if(!al_init_primitives_addon()){
fprintf(stderr, "failed to initialize primitives addon!\n");
return -1;
}
al_init_image_addon();
al_init_primitives_addon();
al_install_keyboard();
al_install_mouse();
event_queue = al_create_event_queue();
timer = al_create_timer(1.0 / fps);
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_register_event_source(event_queue, al_get_mouse_event_source());
al_start_timer(timer);
Map map("test.tmx");
map.loadMap();
while(!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
player.drawPlayer(mousePos);//Draw the player
if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_W:
keys[W] = true;
break;
case ALLEGRO_KEY_S:
keys[S] = true;
break;
case ALLEGRO_KEY_D:
keys[D] = true;
break;
case ALLEGRO_KEY_A:
keys[A] = true;
break;
case ALLEGRO_KEY_UP:
keys[UP] = true;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN] = true;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT] = true;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT] = true;
break;
}
}
else if(ev.type == ALLEGRO_EVENT_KEY_UP)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_W:
keys[W] = false;
break;
case ALLEGRO_KEY_S:
keys[S] = false;
break;
case ALLEGRO_KEY_D:
keys[D] = false;
break;
case ALLEGRO_KEY_A:
keys[A] = false;
break;
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
case ALLEGRO_KEY_UP:
keys[UP] = false;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN] = false;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT] = false;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT] = false;
break;
}
}
else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
{
done = true;
}
else if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
al_get_mouse_state(&estado_raton);
if (estado_raton.buttons & 1) {
cout << "Pew Pew" << endl;
bulletCollector.push(player.getPos(), 1.0, utils.getAlpha(player.getPos(), mousePos));
}
}
else if (ev.type == ALLEGRO_EVENT_MOUSE_AXES) {
al_get_mouse_state(&estado_raton);
mousePos.setx(estado_raton.x);
mousePos.sety(estado_raton.y);
if (mousePos.gety() <= 50) raton_mov[UP] = true; else if (mousePos.gety() > 50) raton_mov[UP] = false;
if (mousePos.gety() >= resY-50) raton_mov[DOWN] = true; else if (mousePos.gety() < resY-50) raton_mov[DOWN] = false;
if (mousePos.getx() <= 50) raton_mov[LEFT] = true; else if (mousePos.getx() > 50) raton_mov[LEFT] = false;
if (mousePos.getx() >= resX-50) raton_mov[RIGHT] = true; else if (mousePos.getx() < resX-50) raton_mov[RIGHT] = false;
}
else if(ev.type == ALLEGRO_EVENT_TIMER)
{
if (keys[W] || keys[UP] || raton_mov[UP]) { if (cam_pos.getx() > 0 && cam_pos.gety() > 0){ player.moveY(-1);}}
if (keys[S] || keys[DOWN] || raton_mov[DOWN]) { if (cam_pos.getx() < 99 && cam_pos.gety() < 99){ player.moveY(1);}}
if (keys[A] || keys[LEFT] || raton_mov[LEFT]) { if (cam_pos.getx() < 99 && cam_pos.gety() > 0){ player.moveX(-1);}}
if (keys[D] || keys[RIGHT] || raton_mov[RIGHT]) { if (cam_pos.getx() > 0 && cam_pos.gety() < 99){ player.moveX(1);}}
redraw = true;
}
if(redraw && al_is_event_queue_empty(event_queue)) {
redraw = false;
bulletCollector.next();
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
}
}
al_destroy_event_queue(event_queue);
al_destroy_timer(timer);
al_destroy_display(display); //destroy our display object
return 0;
}
| true |
030ef55c3ab395ea84f28eb20788dac88515efd3 | C++ | Boldie/cpp14ByExamples | /A3E_RangeBased_Solution.cpp | UTF-8 | 556 | 3.4375 | 3 | [] | no_license | /*
* A1_RangeBased.cpp
*
* Created on: 28 Feb 2017
* Author: sven
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
{
vector<int> myVec{1,2,3,4,5,6,7,8,9,10};
for (auto &x: myVec)
x = x * x;
for (const auto x: myVec)
cout << x << " ";
cout << endl;
}
{
vector<int> myVec{1,2,3,4,5,6,7,8,9,10};
for_each(myVec.begin(), myVec.end(), [](int& x){ x = x * x; });
for (const auto x: myVec)
cout << x << " ";
cout << endl;
}
return 0;
}
| true |
5a48565854ded3d028af2d23bf7e9dcfa6d5ccdb | C++ | kjuk02/repository | /c++/복소수/복소수/header_cpp.cpp | UTF-8 | 4,489 | 3.625 | 4 | [] | no_license | #include "header.h"
// Constructor
myComplex::myComplex(int real, int imag)
{
realPart = real;
imaginaryPart = imag;
} // Copy constructor
myComplex::myComplex(const myComplex& number)
{
realPart = number.realPart;
imaginaryPart = number.imaginaryPart;
} // Accessor functions
int myComplex::getRealPart() const
{
return realPart;
}
int myComplex::getImaginaryPart() const
{
return imaginaryPart;
} // Mutator functions
void myComplex::setRealPart(int real)
{
realPart = real;
}
void myComplex::setImaginaryPart(int imag)
{
imaginaryPart = imag;
}
void myComplex::set(int real, int imag)
{
realPart = real;
imaginaryPart = imag;
} // Overloaded binary operators
myComplex myComplex::operator +(const myComplex& number) const
{
int newReal = realPart + number.realPart;
int newImag = imaginaryPart + number.imaginaryPart;
return myComplex(newReal, newImag);
}
myComplex myComplex::operator +(int value) const
{
return myComplex(value) + (*this);
} // Assignment operators
myComplex& myComplex::operator =(const myComplex& number)
{
this->realPart = number.realPart;
this->imaginaryPart = number.imaginaryPart;
return *this;
}
myComplex& myComplex::operator =(int value)
{
realPart = value;
imaginaryPart = 0;
return *this;
} // Overloading comparison operators
bool myComplex::operator ==(const myComplex& number) const
{
return (realPart == number.realPart) &&(imaginaryPart == number.imaginaryPart);
}
bool myComplex::operator >(const myComplex& number) const
{
return norm() > number.norm();
} // Overloaded unary operators
myComplex myComplex::operator -() // unary minus
{
return myComplex(-realPart, -imaginaryPart);
} // private function
int myComplex::norm() const
{
return realPart * realPart + imaginaryPart * imaginaryPart;
}
ostream &operator <<(ostream &outStream, const myComplex& number)
{
outStream << "(" << number.realPart << "," << number.imaginaryPart << ")";
return outStream;
}
istream &operator >> (istream &inStream, myComplex& number)
{
inStream >> number.realPart >> number.imaginaryPart;
return inStream;
}
myComplex operator +(int value, const myComplex& number)
{
return myComplex(number.realPart + value, number.imaginaryPart);
}
myComplex operator -(int value, const myComplex& number)
{
return myComplex(value - number.realPart, -number.imaginaryPart);
}
myComplex operator *(int value, const myComplex& number)
{
return myComplex(number.realPart*value, number.imaginaryPart*value);
}
myComplex myComplex::operator-(int value) const {
return myComplex(realPart - value, imaginaryPart);
}
myComplex myComplex::operator-(const myComplex& number) const {
return myComplex(realPart - number.realPart, imaginaryPart - number.imaginaryPart);
}
myComplex myComplex::operator*(int value) const {
return myComplex(realPart*value, imaginaryPart*value);
}
myComplex myComplex::operator*(const myComplex& number) const {
return myComplex(realPart * number.realPart - imaginaryPart * number.imaginaryPart
, realPart * number.imaginaryPart + imaginaryPart * number.realPart);
}
bool myComplex::operator!=(const myComplex& number) const {
return realPart != number.realPart || imaginaryPart != number.imaginaryPart;
}
bool myComplex::operator>=(const myComplex& number) const {
return norm() >= number.norm();
}
bool myComplex::operator<(const myComplex& number) const {
return norm() < number.norm();
}
bool myComplex::operator<=(const myComplex& number) const {
return norm() <= number.norm();
}
myComplex& myComplex::operator+=(const myComplex& number) {
this->realPart += number.realPart;
this->imaginaryPart += number.imaginaryPart;
return *this;
}
myComplex& myComplex::operator-=(const myComplex& number) {
this->realPart -= number.realPart;
this->imaginaryPart -= number.imaginaryPart;
return *this;
}
myComplex& myComplex::operator*=(const myComplex& number) {
int thisR = this->realPart, thisI = this->imaginaryPart;
this->realPart = thisR * number.realPart - thisI * number.imaginaryPart;
this->imaginaryPart = thisR * number.imaginaryPart + thisI * number.realPart;
return *this;
}
myComplex myComplex::operator++() {
++realPart;
return *this;
}
myComplex myComplex::operator++(int) {
++*this;
return *this;
}
myComplex myComplex::operator--() {
realPart -= 1;
return *this;
}
myComplex myComplex::operator--(int) {
myComplex out = *this;
--*this;
return out;
}
myComplex myComplex::operator~() {
this->imaginaryPart = -this->imaginaryPart;
return *this;
} | true |
4de7847ae5107987bef808e03c61e5b7786fe65d | C++ | niuxu18/logTracker-old | /second/download/git/gumtree/git_repos_function_6363.cpp | UTF-8 | 833 | 2.75 | 3 | [] | no_license | static int convert_date_line(char *dst, void **buf, unsigned long *sp)
{
unsigned long size = *sp;
char *line = *buf;
char *next = strchr(line, '\n');
char *date = strchr(line, '>');
int len;
if (!next || !date)
die("missing or bad author/committer line %s", line);
next++; date += 2;
*buf = next;
*sp = size - (next - line);
len = date - line;
memcpy(dst, line, len);
dst += len;
/* Is it already in new format? */
if (isdigit(*date)) {
int datelen = next - date;
memcpy(dst, date, datelen);
return len + datelen;
}
/*
* Hacky hacky: one of the sparse old-style commits does not have
* any date at all, but we can fake it by using the committer date.
*/
if (*date == '\n' && strchr(next, '>'))
date = strchr(next, '>')+2;
return len + sprintf(dst, "%lu -0700\n", parse_oldstyle_date(date));
} | true |
8f9d42fe6399fd1f6792364ea55b6afc3598931d | C++ | conanwu777/CPP_piscine | /day04/ex02/Squad.cpp | UTF-8 | 1,215 | 2.796875 | 3 | [] | no_license | #include "ISquad.hpp"
#include "Squad.hpp"
#include "ISpaceMarine.hpp"
Squad::Squad() : units(NULL), count(0){}
Squad::Squad(Squad & src) : units(NULL), count(0){
*this = src;
}
Squad::~Squad(){
for (int i = 0; i < this->count; i++) {
delete this->units[i];
}
delete this->units;
}
Squad & Squad::operator=(Squad const & rhs) {
if (this->units)
{
for (int i = 0; i < this->count; i++) {
delete this->units[i];
}
delete this->units;
}
this->count = rhs.getCount();
this->units = new ISpaceMarine*[rhs.getCount()];
for (int i = 0; i < this->count; i++) {
this->units[i] = rhs.getUnit(i)->clone();
}
return (*this);
}
int Squad::getCount() const {
return (this->count);
}
ISpaceMarine* Squad::getUnit(int i) const {
if (0 <= i && i < this->count)
return (this->units[i]);
return (NULL);
}
int Squad::push(ISpaceMarine* p) {
if (!p)
return this->count;
for (int i = 0; i < this->count; i++) {
if (this->units[i] == p)
return this->count;
}
ISpaceMarine** tmp = new ISpaceMarine*[this->count + 1];
for (int i = 0; i < this->count; i++) {
tmp[i] = this->units[i];
}
tmp[this->count] = p;
delete this->units;
this->count++;
this->units = tmp;
return this->count;
}
| true |
a5e8a5b6c47f02076f4d611055bbc8ffd7fd5acb | C++ | olinanton/RopeSlinger | /Game/Main.cpp | UTF-8 | 297 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include "Window.h"
int main(int argc, char* argv[])
{
Window window("My Game", 500, 500);
if (window.Init())
{
while (window.IsRunning())
{
window.Update();
}
}
else
{
std::cerr << "Initialization failed with SDL error code: " << SDL_Error;
}
return 0;
} | true |
58d6489db9e6453291521e54c438c8924fd4d78e | C++ | hov001/data-structures | /stack/validParentheses.cpp | UTF-8 | 1,172 | 3.96875 | 4 | [] | no_license | #include<iostream>
#include<stack>
#include<string>
using namespace std;
bool isOpen(char ch)
{
return ch == '{' || ch == '[' || ch == '(';
}
bool isPair(char open, char close)
{
return open == '{' && close == '}' ||
open == '[' && close == ']' ||
open == '(' && close == ')';
}
bool isBalanced(string s)
{
stack<char> st;
for(int i = 0; i < s.size(); ++i)
{
if(isOpen(s[i]))
{
st.push(s[i]);
}
else
{
if(!st.empty() && isPair(st.top(), s[i]))
{
st.pop();
}
else
{
return false;
}
}
}
return st.empty();
}
int main()
{
string s1 = "()({[]}())"; // true
string s2 = "{}"; // true
string s3 = "}{"; // false
string s4 = ""; // true
string s5 = "(()"; // false
string s6 = "())"; // false
string s7 = "[(])"; // false
cout << isBalanced(s1) << endl;
cout << isBalanced(s2) << endl;
cout << isBalanced(s3) << endl;
cout << isBalanced(s4) << endl;
cout << isBalanced(s5) << endl;
cout << isBalanced(s6) << endl;
}
| true |
1f03d078a2a9086a87d7c8515a6894112557f734 | C++ | vmmc2/Competitive-Programming | /UVA 00336 - A Node Too Far.cpp | UTF-8 | 2,049 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <sstream>
#include <cmath>
#define pb push_back
#define INF 99999999
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
vector<int> adjlist[100000];
int visitados[100000];
int dist[100000];
void reset_graph(){
for(int i = 0; i < 100000; i++){
adjlist[i].clear();
visitados[i] = 0;
dist[i] = INF;
}
return;
}
void reset_visdist(){
for(int i = 0; i < 100000; i++){
visitados[i] = 0;
dist[i] = INF;
}
return;
}
void bfs(int source){
queue<int> fila;
visitados[source] = 1;
dist[source] = 0;
fila.push(source);
while(!fila.empty()){
int u = fila.front();
fila.pop();
for(int i = 0; i < (int)adjlist[u].size(); i++){
int x = adjlist[u][i];
if(visitados[x] == 0){
visitados[x] = 1;
dist[x] = min(dist[x], dist[u] + 1);
fila.push(x);
}
}
}
return;
}
int main(){
int numedges;
int counter = 1;
while(cin >>numedges){
reset_graph();
set<int> vertices_existentes;
if(numedges == 0) break; //fim do programa.
int x, y;
for(int a = 1; a <= numedges; a++){
cin >> x >> y;
vertices_existentes.insert(x);
vertices_existentes.insert(y);
adjlist[x].pb(y);
adjlist[y].pb(x);
}
int initnode, ttl;
while(true){
cin >> initnode >> ttl;
reset_visdist();
if(initnode == 0 && ttl == 0) break;
bfs(initnode);
int not_reached = 0;
for(set<int>::iterator it = vertices_existentes.begin(); it != vertices_existentes.end(); it++){
if(dist[*it] > ttl) not_reached++;
}
cout << "Case " << counter << ": " << not_reached << " nodes not reachable from node " << initnode << " with TTL = " << ttl << ".\n";
counter++;
}
}
return 0;
}
| true |
a4bdd1b13cb04cf6f9f26b4981f68039ece03581 | C++ | ChihMin/UVA_code | /11297.cpp | UTF-8 | 2,279 | 2.6875 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#define N 600
using namespace std;
const int INF = 2147483647 ;
const int _INF = -2147483647;
struct Packet{
int max , min ;
};
struct ST{
ST *L , *R ;
int min , max;
ST(){
min = INF , max = _INF ;
L = R = 0;
}
} *root[N];
int n , m ;
int MAP[N][N] ;
void build( int L , int R , int i , ST *st ){
if( L == R ){
st->min = st->max = MAP[i][L];
return ;
}
int mid = ( L + R ) >> 1 ;
if( !st->L ) st->L = new ST();
if( !st->R ) st->R = new ST();
build( L , mid , i , st->L );
build( mid+1 , R , i , st->R );
st->min = min( st->L->min , st->R->min );
st->max = max( st->L->max , st->R->max );
}
Packet query( int L , int R , int nL, int nR , ST *st ){
Packet tmp ;
if( L > nR || R < nL ){
tmp.max = _INF , tmp.min = INF ;
return tmp ;
}
if( nL <= L && R <= nR ){
tmp.max = st->max , tmp.min = st->min ;
return tmp ;
}
int mid = ( L + R ) >> 1 ;
Packet A = query( L , mid , nL , nR , st->L );
Packet B = query( mid+1 , R , nL , nR , st->R );
tmp.max = max( A.max , B.max ) ;
tmp.min = min( A.min , B.min ) ;
return tmp ;
}
void change( int L , int R , int Pos , int value , ST *st ){
if( L > Pos || R < Pos ) return ;
if( Pos <= L && R <= Pos ){
st->min = st->max = value ;
return ;
}
int mid = (L+R) >> 1 ;
change( L , mid , Pos , value , st->L );
change( mid+1 , R , Pos , value , st->R );
st->min = min( st->L->min , st->R->min ) ;
st->max = max( st->L->max , st->R->max ) ;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;++i){
root[i] = new ST();
for(int j=0;j<m;++j)
scanf("%d",&MAP[i][j] );
build( 0 , m-1 , i, root[i] );
}
int T;
scanf("%d",&T);
while( T-- ){
char c[10] ;
scanf("%s",c);
if( c[0] == 'q' ){
int x1 ,y1 ,x2 ,y2;
scanf("%d %d %d %d",&x1,&y1,&x2,&y2);
Packet ans;
ans.min = INF , ans.max = _INF ;
for(int i=x1;i<=x2;++i){
Packet tmp_ans = query( 0 , m-1 , y1-1 , y2-1 , root[i-1] );
if( tmp_ans.max > ans.max ) ans.max = tmp_ans.max;
if( tmp_ans.min < ans.min ) ans.min = tmp_ans.min;
}
printf("%d %d\n",ans.max,ans.min);
}
else{
int x , y , v;
scanf("%d %d %d",&x,&y,&v);
x -= 1 , y-= 1 ;
change( 0 , m-1 , y , v , root[x] );
}
}
return 0 ;
}
| true |
22ec8580f5dc6e6e6060ca1844467a259521a356 | C++ | ufoproger/calgon | /lab3.cpp | UTF-8 | 5,438 | 3 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
#include <algorithm>
#include <type_traits>
#include "flags.hh/Flags.hh"
#include "lab2_types.hh"
bool debug = false;
vv readFromFile(const std::string &filename, bool skipOrientation)
{
std::ifstream fin(filename);
vv m;
if (!fin.is_open())
return m;
size_t n;
std::string s;
fin >> n;
m.resize(n);
getline(fin, s);
for (size_t i = 0; i < n; ++i)
{
// Если не удалось получить строку со списком смежных вершин, то дальше их тоже нет
if (!getline(fin, s))
break;
std::istringstream sin(s);
size_t vertex;
while (sin >> vertex)
{
--vertex;
m[i].push_back(vertex);
// Если игнорируем направленность рёбер, то добавляем смежной вершине себя в список смежности, если этого уже не было сделано
if (skipOrientation && i > vertex && find(m[vertex].begin(), m[vertex].end(), i) == m[vertex].end())
m[vertex].push_back(i);
}
}
return m;
}
class IStorage
{
public:
virtual size_t get_next() = 0;
virtual v get_v() const = 0;
};
class QueueStorage: public IStorage, public queue
{
public:
size_t get_next()
{
return front();
}
v get_v() const
{
auto q = *this;
v result;
while (!q.empty())
{
result.push_back(q.get_next());
q.pop();
}
return result;
}
};
class StackStorage: public IStorage, public stack
{
public:
size_t get_next()
{
return top();
}
v get_v() const
{
auto q = *this;
v result;
while (!q.empty())
{
result.push_back(q.get_next());
q.pop();
}
std::reverse(result.begin(), result.end());
return result;
}
};
bool is_all_visited(const v &visited)
{
for (auto f: visited)
if (!f)
return false;
return true;
}
template < typename T > v algo_search(const vv &m, size_t start)
{
v visited(m.size(), false);
T storage;
storage.push(start);
visited[start] = true;
if (debug)
std::cout << "Вывод итераций: " << std::endl;
while (!storage.empty())
{
size_t u = storage.get_next();
if (debug)
std::cout << (u + 1) << ", next " << v_plus(storage.get_v()) << std::endl;
storage.pop();
for (auto w: m[u])
if (!visited[w])
{
storage.push(w);
visited[w] = true;
}
}
if (debug)
std::cout << std::endl;
return visited;
}
template < typename T > vv algo_search_spanning(const vv &m, size_t start)
{
const size_t infinity = std::string::npos;
const size_t n = m.size();
vv spanning(n);
v visited(n, false), from(n, infinity);
T storage;
storage.push(start);
visited[start] = true;
while (!storage.empty())
{
size_t u = storage.get_next();
if (u != start)
spanning[u].push_back(from[u]);
storage.pop();
for (auto w: m[u])
if (!visited[w])
{
storage.push(w);
visited[w] = true;
from[w] = u;
}
}
if (!is_all_visited(visited))
return vv();
return spanning;
}
// Поиск в ширину
inline v bfs(const vv &m, size_t start)
{
return algo_search<QueueStorage>(m, start);
}
// Поиск в глубину
inline v dfs(const vv &m, size_t start)
{
return algo_search<StackStorage>(m, start);
}
void task1(const vv &m)
{
bool f = is_all_visited(bfs(m, 0));
std::cout << "Граф" << (f ? " " : " не ") << "является связным." << std::endl;
}
void task2(const vv &m)
{
const size_t n = m.size();
v sources;
for (size_t i = 0; i < n; ++i)
if (is_all_visited(dfs(m, i)))
sources.push_back(i);
if (sources.empty())
std::cout << "Источников орграфа нет." << std::endl;
else
std::cout << "Источники орграфа: " << v_plus(sources) << std::endl;
}
void task3(const vv &m)
{
vv spanning = algo_search_spanning<StackStorage>(m, 0);
if (spanning.empty())
std::cout << "Граф не является связным, поэтому остовное дерево не найдено." << std::endl;
else
std::cout << "Списки смежности остовного дерева:" << std::endl << vv_plus(spanning, true) << std::endl;
}
int main(int argc, char *argv[])
{
setlocale(LC_CTYPE, "ru_RU.UTF8");
std::string filename;
bool help, skipOrientation;
size_t task;
Flags flags;
flags.Var(filename, 'f', "filename", std::string(), "Файл со списками смежностей графа");
flags.Bool(skipOrientation, 's', "skip-orientation", "Игнорировать ориентацию графа");
flags.Var(task, 't', "task", size_t(1), "Подзадача лабораторной работы");
flags.Bool(debug, 'd', "debug", "Вывод отладки");
flags.Bool(help, 'h', "help", "Показать помощь и выйти");
if (!flags.Parse(argc, argv))
{
flags.PrintHelp(argv[0]);
return 1;
}
if (help || filename.empty())
{
flags.PrintHelp(argv[0]);
return 0;
}
vv m = readFromFile(filename, skipOrientation);
if (m.empty())
{
std::cout << "Ошибка чтения списков смежностей." << std::endl;
return 2;
}
std::cout << "Прочитанные списки смежности: " << std::endl << vv_plus(m, true) << std::endl;
switch (task)
{
case 1:
task1(m);
break;
case 2:
task2(m);
break;
case 3:
task3(m);
break;
}
return 0;
}
| true |
051162381b70f025c3931e38c369c116167f4d52 | C++ | eightofeighteen/BigInteger | /sharedmemory2.cpp | UTF-8 | 2,518 | 3.15625 | 3 | [] | no_license | #include "sharedmemory2.h"
SharedMemory2::SharedMemory2()
{
if (DEBUG) std::cout << "Init SharedMemory2." << std::endl;
//root = 0;
rootMemoryController = 0;
}
SharedMemory2::~SharedMemory2()
{
if (DEBUG) std::cout << "Destruct SharedMemory2 - " << this << std::endl;
detachMemoryController();
//if (rootMemoryController->size() == 1)
}
/**
* @brief SharedMemory2::detachMemoryController
* Detaches the memory controller from this object, deleting it if this object is the only object attached to it.
*/
void SharedMemory2::detachMemoryController()
{
if (rootMemoryController != 0)
{
if (rootMemoryController->size() <= 1)
{
if (DEBUG) std::cout << "Deleting memory controller." << std::endl;
delete rootMemoryController;
}
else
{
rootMemoryController->removeObject(this);
rootMemoryController = 0;
}
}
}
/**
* @brief SharedMemory2::newRoot
* Creates new memory controller for this object.
*/
void SharedMemory2::newRoot()
{
rootMemoryController = new SharedMemoryController<SharedMemory2>();
rootMemoryController->addObject(this);
}
/**
* @brief SharedMemory2::setRoot
* Creates new memory controller for newRoot, set it as this object's memory conroller and shares newRoot's data.
* @param newRoot
* Source object to share data from.
*/
void SharedMemory2::setRoot(SharedMemory2 *newRoot)
{
detachMemoryController();
if (newRoot->getRootMemoryController() == 0)
newRoot->newRoot();
rootMemoryController = newRoot->getRootMemoryController();
rootMemoryController->addObject(this);
newRoot->shareData(this);
}
/**
* @brief SharedMemory2::decouple
* Decouples this object from any shared data, copying it, if needed.
*/
void SharedMemory2::decouple()
{
if (rootMemoryController != 0)
{
if (rootMemoryController->size() > 1)
{
rootMemoryController->getData(this)->copyData(this);
rootMemoryController->removeObject(this);
rootMemoryController = 0;
}
else
{
delete rootMemoryController;
rootMemoryController = 0;
}
}
}
/**
* @brief SharedMemory2::canDeleteData
* Checks if the data is owned and can be deleted.
* @return
*/
bool SharedMemory2::canDeleteData()
{
if (rootMemoryController == 0)
{
return true;
}
else
{
return (rootMemoryController->size() <= 1);
}
}
| true |
9aa4aa2c04d4235fa2004250cfd1f68f2ae60f80 | C++ | zinsmatt/Programming | /LeetCode/medium/Minimum_Domino_Rotations_For_Equal_Row.cxx | UTF-8 | 838 | 2.625 | 3 | [] | no_license | class Solution {
public:
int minDominoRotations(vector<int>& tops, vector<int>& bottoms) {
int res = -1;
for (int k = 1; k <= 6; ++k) {
int nb_top = 0, nb_bot = 0;
int count = 0;
for (int i = 0; i < tops.size(); ++i) {
bool ok = false;
if (tops[i] == k) {
nb_top++;
ok = true;
}
if (bottoms[i] == k) {
nb_bot++;
ok = true;
}
count += ok;
}
if (count == tops.size()) {
if (res == -1 || tops.size()-std::max(nb_top, nb_bot) < res) {
res = tops.size()-std::max(nb_top, nb_bot);
}
}
}
return res;
}
};
| true |
14e163692a84f07a6cf763498b1fac4ac1e6c2ef | C++ | jthanh8144/CPlusPlus | /VScode/abc.cpp | UTF-8 | 848 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
int can(int s[], int i, int j) {
int sum = 0;
for (int k = i; k <= j; k++) {
sum += s[k];
}
return sum;
}
int ABC(int s[], int i, int j) {
if (i >= j)
return 0;
int tmp = (j-i+1)/3;
int a = can(s, i, i + tmp -1);
int b = can(s, i+tmp, i + 2*tmp -1);
int c = can(s, i + 2*tmp, j);
if (a == b) {
cout << "a == b, --> c" << endl;
return 1 + ABC(s, i + 2*tmp, j);
} else if (a < b) {
cout << "a < b, --> a" << endl;
return 1 + ABC(s, i, i + tmp -1);
} else {
cout << "a > b, --> b" << endl;
return 1 + ABC(s, i+tmp, i + 2*tmp -1);
}
}
int main() {
int s[] = {0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3};
cout << "KQ: " << ABC(s, 1, 21) << endl;
return 0;
} | true |
4ff9a88adc75722871d64f04ac555b2a68284458 | C++ | mt2522577/TranMelvin_CSC5_40717 | /Class_Lab/GameOfLife/main.cpp | UTF-8 | 776 | 2.875 | 3 | [] | no_license | /*
* File: main.cpp
* Author: melvintran
*
* Created on February 4, 2015, 10:59 AM
*/
#include <cstdlib>
#include <iostream>
using namespace std;
//User Libraries
//Global Constants
const int COL=30;
//Function Prototype
void filAray(char [][COL],int,char);
void prntAry(char [][COL],int);
void inject(char [][COL],int,char);
//Execution begins here!
int main(int argc, char** argv) {
return 0;
}
void inject(char a[][COL],int pROW,int pCol,char c){
}
void prntAry(char a[][COL],int ROW){
cout<<endl;
for(int r=0;r<ROW;r++){
for(int c=0;c<COL;c++){
a[r] [c]=c;
}
}
}
void filAray(char a[][COL],int ROW,char c){
for(int r=0;r<ROW;r++){
for(int c=0;c<COL;c++){
a[r] [c]=c;
}
}
}
| true |
dfc31d0bc72b7836461d9ca8731716bfe175c0e9 | C++ | fernandoperez0330/Gestor-Monedas | /Lista.cpp | UTF-8 | 1,476 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include "Lista.h"
Lista::Lista(){
primero = NULL;
ultimo = NULL;
size = 0;
}
Objeto* Lista::getPrimero(){
return primero;
}
int Lista::getSize(){
return this -> size;
}
Objeto* Lista::getUltimo(){
return ultimo;
}
void Lista::agregar(Objeto* objeto){
if (getPrimero() == NULL){
primero = ultimo = objeto;
}else{
objeto -> setAnterior(ultimo);
ultimo -> setSiguiente(objeto);
ultimo = objeto;
}
this -> size++;
ultimo -> setSiguiente(NULL);
}
void Lista::remover(int key){
Objeto *temporal;
Objeto *temporalDos;
if(getPrimero() != NULL){
temporal = this->primero;
temporalDos = NULL;
while (temporal != NULL){
if(key == temporal->getKey()){
if(temporalDos== NULL){
primero = temporal ->getSiguiente();
}else{
temporalDos ->setSiguiente(temporal->getSiguiente());
if(temporal->getSiguiente() == NULL){
ultimo = temporalDos;
}
}
}
temporalDos = temporal;
temporal = temporal->getSiguiente();
}
this -> size--;
}
}
void Lista::push(Objeto* objeto){
if(primero == NULL){
primero = objeto;
ultimo = objeto;
}else{
ultimo->setSiguiente(objeto);
ultimo = objeto;
}
ultimo->setSiguiente(NULL);
}
Objeto* Lista::pop(){
Objeto* primeroEnCola = primero;
primero = primero->getSiguiente();
return primeroEnCola;
}
| true |
1ccd1fdb81b16e79a18d657413f3d949867fadf3 | C++ | Matbe34/EDA-FIB | /Divide_&_Conquer/P29212_ca/P29212.cc | UTF-8 | 299 | 3.125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int quick(int n, int k, int m){
if(k == 0) return 1;
int aux = quick(n,k/2,m)%m;
if(k%2 == 0) return (aux*aux)%m;
return (((aux*aux)%m)*n)%m;
}
int main(){
int n, k, m;
while(cin >> n >> k >> m){
cout << quick(n,k,m) << endl;
}
}
| true |
913fd4ce36ef02ce6f3d6b97f26be91f4800ff80 | C++ | Bluemi/FourWins3D | /src/misc/Debug.hpp | UTF-8 | 965 | 2.84375 | 3 | [] | no_license | #ifndef __DEBUG_CLASS__
#define __DEBUG_CLASS__
#include <vector>
#include <string>
#include <fstream>
#define NOTE_COLOR FBLUE
#define ERROR_COLOR FRED
#define WARN_COLOR FYELLOW
#define TEST_COLOR FPURPLE
#define DEFAULT_COLOR "\u001B[0m"
#define FBLACK "\u001B[30m"
#define FRED "\u001B[31m"
#define FGREEN "\u001B[32m"
#define FYELLOW "\u001B[33m"
#define FBLUE "\u001B[34m"
#define FPURPLE "\u001B[35m"
#define FCYAN "\u001B[36m"
namespace Debug
{
enum Tag { endl, error, warn, note, test };
class DebugClass
{
public:
DebugClass();
~DebugClass();
DebugClass& operator<<(int i);
DebugClass& operator<<(float f);
DebugClass& operator<<(std::string s);
DebugClass& operator<<(const Debug::Tag tag);
const char* LOG_FILE_NAME = "debug.log";
private:
void appendColor(std::string c);
void appendString(std::string s);
std::vector<std::string> strings_;
std::ofstream fileWriter;
};
extern DebugClass out;
}
#endif
| true |
1248638810bd9f19792369a309f328712bd2dfd4 | C++ | Striiderr/DSA | /Assignments/Day3/Recurn_Sort.cpp | UTF-8 | 1,159 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
void swap(int *x, int *y){
int t;
t=*x;
*x=*y;
*y=t;
}
int Max(int a[],int n,int &max,int &loc){
if(n==0){
if(a[0]>max){max=a[0]; loc=0;}
else{max;}
return a[0];
}
else{
if(a[n]>max){ max=a[n]; loc=n;}
else{max;}
return a[n]+ Max(a,n-1,max,loc);
}}
void ssort(int a[], int n){
if(n<1){
return;
}
else{
int loc=-1,max=-100000000;
int r=Max(a,n-1,max,loc);
swap(&a[loc],&a[n-1]);
ssort(a,n-1);
}
}
void bsort(int b[], int n){
if(n==0)
{ return; }
else{
if(b[n]<b[n-1]){
swap(&b[n],&b[n-1]); }
bsort(b,n-1);
bsort(b,n-1);
}}
int main(){
int n;
n=12;
int a[n/2],b[n/2+2];
<<<<<<< HEAD
//b[n/2]=345672345;
//b[n/2+1]=1234567;
=======
b[n/2]=345672345;
b[n/2+1]=1234567;
for(int i=0;i<n/2;i++){
cin>>a[i];
}
>>>>>>> a430ccce937e8f0a87699ab5fbaf481a665a3d05
for(int i=0;i<n/2;i++){
cin>>a[i];
}
for(int i=0;i<=n/2+1;i++){
cin>>b[i];
}
ssort(a,n/2);
bsort(b,(n/2)+1);
for(int i=0;i<n/2;i++){
cout<<a[i]<<" ";
}
cout<<"\n";
for(int i=0;i<=((n/2)+1);i++){
cout<<b[i]<<" ";
}
}
| true |
838ad43850a98d2be5c060ceb8e8a717aeceb7c9 | C++ | weidingbang/SamSelect | /UseCount.cpp | UTF-8 | 747 | 2.59375 | 3 | [] | no_license | /*============================================
# Filename: UseCount.cpp
# Ver 1.0 2014-06-08
# Copyright (C) 2014 ChenLonggang (chenlonggang.love@163.com)
#
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 or later of the License.
#
# Description:
=============================================*/
#include"UseCount.h"
UseCount::UseCount():p(new int(1)){}
UseCount::UseCount(const UseCount &u):p(u.p){++*p;}
UseCount::~UseCount(){if(--*p==0) delete p;}
bool UseCount::only() {return *p==1;}
bool UseCount::reattach(const UseCount & u)
{
++*u.p;
if(--*p==0)
{
delete p;
p=u.p;
return true;
}
p=u.p;
return false;
}
| true |
105e4c854969946e0e77d223e567f933557708d4 | C++ | DionysiosB/CodeChef | /SALARY.cpp | UTF-8 | 453 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <vector>
int main(){
int t; scanf("%d\n", &t);
while(t--){
int n; scanf("%d\n", &n);
std::vector<long> a(n);
long min = 10000001;
for(int p = 0; p < n; p++){
scanf("%ld", &a[p]);
min = (a[p] < min) ? a[p] : min;
}
long count(0);
for(int p = 0; p < n; p++){count += (a[p] - min);}
printf("%ld\n", count);
}
return 0;
}
| true |
efae4c15dc378191ae3c3a5072058f9edd582a6e | C++ | lokehoke/Morph-1 | /src/python/function.h | UTF-8 | 9,685 | 2.75 | 3 | [] | no_license | #pragma once
#include "python/cast.h"
#include "python/pythonapi.h"
#include <tuple>
#include <type_traits>
#include <utility>
namespace py
{
template <typename... Args>
struct Init {};
namespace detail
{
template <typename Return, typename... Args>
struct FnSignatureT {};
template <typename T>
struct FnSignatureFromLambdaImpl {};
template <typename Return, typename Class, typename... Args>
struct FnSignatureFromLambdaImpl<Return (Class::*)(Args...)>
{
using Type = FnSignatureT<Return, Args...>;
};
template <typename Return, typename Class, typename... Args>
struct FnSignatureFromLambdaImpl<Return (Class::*)(Args...) const>
{
using Type = FnSignatureT<Return, Args...>;
};
template <typename Fn>
struct FnSignatureFromLambdaT
{
using OperatorType = decltype(&Fn::operator());
using Type = typename FnSignatureFromLambdaImpl<OperatorType>::type;
};
template <typename... Args, std::size_t... idx>
std::tuple<Args...> python_to_cpp_tuple(Tuple py_tuple, std::index_sequence<idx...>)
{
return std::tuple<Args...>(Loader<Args>::load(py_tuple[idx])...);
}
template <typename... Args>
Tuple cpp_to_python_tuple_impl(Args&&... args)
{
auto py_tuple = PyTuple_Pack(
sizeof...(Args),
Caster<Args>::cast(
std::forward<Args>(args),
return_value_policy::copy).ptr()...); // TODO: use auto return value policy
return py_tuple;
}
template <typename... Args>
Tuple cpp_to_python_tuple(std::tuple<Args...>&& cpp_tuple)
{
return std::apply(cpp_to_python_tuple_impl<Args...>, std::forward<std::tuple<Args...>>(cpp_tuple));
}
/*
* Converts python arguments tuple to cpp values and
* passes them to the function.
*/
template <typename Fn, typename Return, typename... Args>
struct FunctionInvocation
{
template <bool is_none>
struct ReturnIsNoneTag {};
using ArgIndex = std::index_sequence_for<Args...>;
using ReturnIsNone = ReturnIsNoneTag<std::is_void<Return>::value>;
static Handle invoke(
Fn& fn,
Tuple py_args,
return_value_policy policy)
{
try
{
return invoke(fn, std::move(py_args), policy, ReturnIsNone {});
}
catch (const ErrorAlreadySet&)
{
return nullptr;
}
catch (const std::exception& ex)
{
PyErr_SetString(PyExc_RuntimeError, ex.what());
return nullptr;
}
}
static Handle invoke(
Fn& fn,
Tuple py_args,
return_value_policy policy,
ReturnIsNoneTag<false>)
{
auto cpp_args = python_to_cpp_tuple<Args...>(py_args, ArgIndex {});
Return res = std::apply(fn, std::move(cpp_args));
return cast(std::forward<Return>(res), policy);
}
static Handle invoke(
Fn& fn,
Tuple py_args,
return_value_policy policy,
ReturnIsNoneTag<true>)
{
auto cpp_args = python_to_cpp_tuple<Args...>(py_args, ArgIndex {});
std::apply(fn, std::move(cpp_args));
Py_XINCREF(Py_None);
return Py_None;
}
};
/**
* function_record is held in capsule with python function objects.
* It is used to invoke actual cpp function during python function call.
*/
struct FunctionRecord
{
using Capture = std::aligned_storage<sizeof(void*)>;
using Impl = Handle (*)(void* capture, Tuple args);
using Dtor = void (*)(void*);
~FunctionRecord()
{
if (m_dtor)
{
(*m_dtor)(reinterpret_cast<void*>(&m_capture));
}
}
return_value_policy m_policy;
// Capture destructor.
Dtor m_dtor;
// Wrapped cpp function (see cpp_function for details).
Capture m_capture;
// Python method definition.
PyMethodDef m_def;
};
class CppFunction
{
public:
/**
* Bind non-const class function.
*/
template <typename Return, typename Class, typename... Args>
CppFunction(
const char* name,
Object scope,
return_value_policy policy,
Return (Class::*fn)(Args...))
{
initialize(
name,
std::move(scope),
policy,
[fn](Class& cls, Args&&... args) -> Return
{
return (cls.*fn)(std::forward<Args>(args)...);
},
FnSignatureT<Return, Class&, Args...> {});
}
/**
* Bind const class function.
*/
template <typename Return, typename Class, typename... Args>
CppFunction(
const char* name,
Object scope,
return_value_policy policy,
Return (Class::* fn)(Args...) const)
{
initialize(
name,
std::move(scope),
policy,
[fn](const Class& cls, Args&&... args) -> Return
{
return (cls.*fn)(std::forward<Args>(args)...);
},
FnSignatureT<Return, const Class&, Args...> {});
}
/**
* Bind lambda object.
*/
template <typename Fn>
CppFunction(
const char* name,
Object scope,
return_value_policy policy,
Fn&& fn)
{
initialize(
name,
std::move(scope),
policy,
std::forward<Fn>(fn),
typename FnSignatureFromLambdaT<Fn>::type {});
}
/**
* Bind free function.
*/
template <typename Return, typename... Args>
CppFunction(
const char* name,
Object scope,
return_value_policy policy,
Return (*fn)(Args...))
{
initialize(
name,
std::move(scope),
policy,
[fn](Args&&... args)
{
return (*fn)(std::forward<Args>(args)...);
},
FnSignatureT<Return, Args...> {});
}
/**
* Bind constructor.
*/
template <typename Class, typename... Args>
CppFunction(Init<Class, Args...>, Object scope)
{
initialize(
"__init__",
std::move(scope),
return_value_policy::copy,
[](Class* this_ptr, Args&&... args)
{
new (this_ptr) Class(std::forward<Args>(args)...);
},
FnSignatureT<void, Class*, Args...> {});
}
private:
template <typename Fn>
static constexpr bool can_embed = sizeof(Fn) <= sizeof(FunctionRecord::Capture);
template <typename Fn, typename Return, typename... Args>
void initialize(
const char* name,
Object scope,
return_value_policy policy,
Fn&& fn,
FnSignatureT<Return, Args...>)
{
FunctionRecord* fn_rec = new FunctionRecord();
fn_rec->m_policy = policy;
Capsule fn_rec_c(
fn_rec,
[](FunctionRecord* fn_rec)
{
delete fn_rec;
});
auto& def = fn_rec->m_def;
def.ml_name = name;
def.ml_doc = nullptr;
def.ml_flags = METH_VARARGS;
def.ml_meth = &dispatch<Fn, Return, Args...>;
if (can_embed<Fn>)
{
// Capture holds the functor itself.
auto capture_ptr = reinterpret_cast<Fn*>(&fn_rec->m_capture);
new (capture_ptr) Fn(std::forward<Fn>(fn));
fn_rec->m_dtor = [](void* capture_ptr)
{
delete reinterpret_cast<Fn*>(capture_ptr);
};
}
else
{
// Capture holds a pointer to the functor.
auto capture_ptr = reinterpret_cast<Fn**>(&fn_rec->m_capture);
*capture_ptr = new Fn(std::forward<Fn>(fn));
fn_rec->m_dtor = [](void* capture_ptr)
{
auto fn_ptr = reinterpret_cast<Fn**>(capture_ptr);
delete *fn_ptr;
};
}
Object meth = PyCFunction_New(&def, fn_rec_c.release().ptr());
if (PyModule_Check(scope.ptr()))
{
PyModule_AddObject(scope.ptr(), name, meth.release().ptr());
}
else
{
Object inst_meth = PyInstanceMethod_New(meth.release().ptr());
PyDict_SetItemString(scope.ptr(), name, inst_meth.ptr());
}
}
template <typename Fn, typename Return, typename... Args>
static PyObject* dispatch(PyObject* fn_rec_c, PyObject* py_args)
{
auto fn_rec = reinterpret_cast<FunctionRecord*>(PyCapsule_GetPointer(fn_rec_c, nullptr));
if (sizeof...(Args) != PyTuple_Size(py_args))
{
PyErr_Format(
PyExc_TypeError,
"Function requires %d positional arguments, %d provided.",
sizeof...(Args),
PyTuple_Size(py_args));
return nullptr;
}
Fn* fn_ptr;
if (can_embed<Fn>)
{
fn_ptr = reinterpret_cast<Fn*>(&fn_rec->m_capture);
}
else
{
fn_ptr = *reinterpret_cast<Fn**>(&fn_rec->m_capture);
}
return FunctionInvocation<Fn, Return, Args...>::invoke(
*fn_ptr,
py_args,
fn_rec->m_policy).ptr();
}
};
} // namespace detail
template <typename... Args>
Handle Handle::operator()(Args&&... args)
{
auto py_args = detail::cpp_to_python_tuple(std::tuple {std::forward<Args>(args)...});
return PyObject_Call(m_ptr, py_args.ptr(), nullptr);
}
} // namespace py
| true |
3832e3916e42013e1289108fa378c4c52c93687f | C++ | bcavus/SergeantEngine | /Sergeant3DEngine/Core/Vertex/vertex.h | UTF-8 | 392 | 2.890625 | 3 | [] | no_license | #include <glm.hpp>
#ifndef VERTEX_H
#define VERTEX_H
class Vertex {
public:
Vertex(const glm::vec3 &position, const glm::vec2 &tex_coord, const glm::vec3& normal);
~Vertex();
const glm::vec3 &Position() const;
const glm::vec2 &TexCoord() const;
const glm::vec3& Normal() const;
private:
glm::vec3 m_position;
glm::vec2 m_tex_coord;
glm::vec3 m_normals;
};
#endif // ! VERTEX_H
| true |
4b06ab35cd55647b45235f167d59f6fc28ecda06 | C++ | halilg/NoiseTreeOps | /CycledH1D.h | UTF-8 | 3,618 | 3.453125 | 3 | [] | no_license | #ifndef CycledH1D_h_
#define CycledH1D_h_
//
// A wrapper around TH1D which implements ManagedHisto interface
// and knows how to fill the underlying root histogram in a cycle.
// Use the "CycledH1D" helper function to create instances of this
// wrapper.
//
// I. Volobouev
// March 2013
//
#include "ManagedHisto.h"
#include "TH1D.h"
//
// Wrapper class for TH1D. In the user code, do not create instances
// of this class directly, call the "CycledH1D" function instead.
//
template<class Functor1, class Functor2>
class CycledH1DHelper : public ManagedHisto
{
public:
inline CycledH1DHelper(const char* name, const char* title,
const char* directory,
const char* xlabel, const char* ylabel,
unsigned nbins, double xmin, double xmax,
Functor1 quantity, Functor2 weight)
: histo_(new TH1D(name, title, nbins, xmin, xmax)),
f_(quantity),
w_(weight),
directory_(directory ? directory : "")
{
histo_->GetXaxis()->SetTitle(xlabel);
histo_->GetYaxis()->SetTitle(ylabel);
}
inline virtual ~CycledH1DHelper()
{
// Do not delete histo_ here due to the idiosyncratic
// root object ownership conventions
}
inline void AutoFill() {}
inline void CycleFill(const unsigned nCycles)
{
for (unsigned i=0; i<nCycles; ++i)
histo_->Fill(f_(i), w_(i));
}
inline void SetDirectory(TDirectory* d) {histo_->SetDirectory(d);}
inline const std::string& GetDirectoryName() const {return directory_;}
inline TH1D* GetRootItem() const {return histo_;}
private:
TH1D* histo_;
Functor1 f_;
Functor2 w_;
std::string directory_;
};
//
// The CycledH1D function arguments are as follows:
//
// name -- Object name for "root". Should be unique. It is the
// user responsibility to ensure that it is unique among
// all root objects created by the program.
//
// title -- Histogram title
//
// directory -- Directory inside the root file into which this histogram
// will be placed
//
// xlabel -- The label for the horizontal axis
//
// ylabel -- The label for the bin counts
//
// nbins -- Number of horizontal axis bins (binning will be uniform)
//
// xmin, xmax -- Horizontal axis limits
//
// quantity -- Functor for the quantity to histogram. Must define method
// "operator()(unsigned)" whose result must be convertible
// to double. This functor will be called in a cycle with
// argument incremented from 0 to some user-provided limit.
//
// weight -- Functor for the bin weights (the numbers added to the bin
// values). Must define method "operator()(unsigned)" whose
// result must be convertible to double. Can be used to
// implement implicit selection cuts by returning 0 or "false".
//
// This function returns a pointer to a new histogram created on the heap.
// This pointer should be managed by a HistogramManager instance (call
// its "manage" method).
//
template<class Functor1, class Functor2>
inline CycledH1DHelper<Functor1,Functor2>* CycledH1D(
const char* name, const char* title,
const char* directory,
const char* xlabel, const char* ylabel,
unsigned nbins, double xmin, double xmax,
Functor1 quantity, Functor2 weight)
{
return new CycledH1DHelper<Functor1,Functor2>(
name, title, directory, xlabel, ylabel,
nbins, xmin, xmax, quantity, weight);
}
#endif // CycledH1D_h_
| true |
4ec3bbf746ec5ed7c3a0eba353bfbc001f53c482 | C++ | mvp18/Embedded-Systems-Codes | /Expt7/7c.ino | UTF-8 | 1,920 | 2.828125 | 3 | [] | no_license | int sine [255];
const int POT = A0;
int value = 0;
int freq = 0;
int amp = 0;
int data1 = 0;
int data2 = 0;
int data3 = 0;
int frequency;
int freqCurrent;
unsigned int freqscaled;
void setup () {
pinMode ( 2 , OUTPUT );
pinMode ( 3 , OUTPUT );
pinMode ( 4 , OUTPUT );
pinMode ( 5 , OUTPUT );
pinMode ( 6 , OUTPUT );
pinMode ( 7 , OUTPUT );
pinMode ( 8 , OUTPUT );
pinMode ( 9 , OUTPUT );
Serial . begin ( 9600 ); // Initialize variables
frequency = analogRead ( A4 ); // initialize frequency
// A4 gets the value from DAC output.
freqscaled = 48 * frequency + 1 ; // from 1 to ~50,000\
period = samplerate / freqscaled;
delay ( 3000 ); // So we can see the nice splash screen
// Generate the values of a sine function float
float x , y;
for ( int i = 0 ; i < 255 ; i ++){
x =( float ) i;
y = sin (( x / 255 )* 2 * PI );
sine [ i ]=( int ( y * 128 )+ 128 );
}
}
/*
* @Description : This function generate a sine signal
* @input : freq
*/
void Sine_Function ( int freq ){
for ( int i = 0 ; i < 255 ; i ++){
PORTD = sine [ i ];
amp = analogRead ( A0 ); // A pot is used to give a value between 0 and 5 V to pin
amp = amp / 255.0;
Serial . println ( amp * sine [ i ]); // amplitude control using variable register.
delay(10);
delayMicroseconds ( freq ); }
}
/*
* @Description : This function check the value of the input Analog 4 ( A4 ),
* which configure the frequency of the signal.
* This value will be displayed by the display
*/
void checkFreq () {
freqCurrent = analogRead ( A4 );
}
void loop () {
digitalWrite ( 2 , LOW );
digitalWrite ( 3 , LOW );
digitalWrite ( 4 , LOW );
digitalWrite ( 5 , LOW );
digitalWrite ( 6 , LOW );
digitalWrite ( 7 , LOW );
digitalWrite ( 8 , LOW );
digitalWrite ( 9 , HIGH ); // setting up the DAC output to set up the frequency..
value = analogRead ( A4 );
freq = value * 10;
checkFreq ();
Sine_Function ( freq );
}
| true |
83a1c8d006346a1e34c339cdf0c441e2dad293c1 | C++ | SebasDiaz01182/I-Proyecto-Programado-Trenes | /CodigoFuente/listaDoble.h | UTF-8 | 1,892 | 3.359375 | 3 | [] | no_license |
#include <iostream>
using namespace std;
class nodoDoble {
public:
nodoDoble(string v)
{
valor = v;
siguiente = NULL;
anterior =NULL;
}
nodoDoble(string v, nodoDoble * signodoDoble)
{
valor = v;
siguiente = signodoDoble;
}
string valor;
nodoDoble *siguiente;
nodoDoble *anterior;
friend class listaD;
};
typedef nodoDoble *pnodoDoble;
class listaD {
public:
listaD() { primero = NULL; }
~listaD();
void InsertarInicio(string v);
void InsertarFinal(string v);
bool ListaVacia() { return primero == NULL; }
void Imprimir();
void Mostrar();
int largoLista();
pnodoDoble primero;
};
listaD::~listaD()
{
pnodoDoble aux;
while(primero) {
aux = primero;
primero = primero->siguiente;
delete aux;
}
}
int listaD::largoLista(){
int cont=0;
pnodoDoble aux;
aux = primero;
if(ListaVacia()){
return cont;
}else{
while(aux!=NULL){
aux=aux->siguiente;
cont++;
}
return cont;
}
}
void listaD::InsertarInicio(string v)
{
if (ListaVacia()){
primero = new nodoDoble(v);
}
else
{
pnodoDoble aux= primero;
primero=new nodoDoble(v,primero);
aux->anterior=primero;
}
}
void listaD::InsertarFinal(string v)
{
if (ListaVacia()){
primero= new nodoDoble(v);
}
else
{
pnodoDoble aux=primero;
while(aux->siguiente!=NULL){
aux=aux->siguiente;
}
pnodoDoble nuevo=new nodoDoble(v);
aux->siguiente=nuevo;
nuevo->anterior=aux;
}
}
void listaD::Mostrar()
{
nodoDoble *aux;
aux = primero;
while(aux) {
cout << aux->valor << "-> ";
aux = aux->siguiente;
}
cout << endl;
}
| true |
4f9394d31663e80cb24a3de2914d06f0fc35b07d | C++ | anhle199/Code_Cpp | /Projects/Poker/main.cpp | UTF-8 | 1,962 | 2.828125 | 3 | [] | no_license | // main.cpp
#include "cardGame.h"
int main()
{
int n(6), s, choice;
const int start(1), end(5);
vector<vector<int>> deck(SUITS, vector<int>(FACES, 0));
vector<INFO_HAND> info_card(CARDS);
vector<int> ranking(n), ranking_s_times;
system("cls");
do
{
cout << "------------------------------------------------------" << endl;
cout << "--- CHAO MUNG BAN DEN VOI TRO CHOI FIVE-CARD POKER ---" << endl;
cout << "------------------------------------------------------" << endl;
cout << "------------------------------------------------------" << endl;
cout << "--------------------- CHE DO CHOI --------------------" << endl;
cout << "------------------------------------------------------" << endl;
cout << "--- 1. 1 nguoi choi." << endl;
cout << "--- 2. Nhieu nguoi choi (khong co nha cai)." << endl;
cout << "--- 3. Nhieu nguoi choi (co nha cai)." << endl;
cout << "--- 4. Dau doi khang voi nha cai." << endl;
cout << "--- 5. Thoat tro choi." << endl;
getChoice(choice, start, end);
switch (choice)
{
case 1:
system("cls");
programForOnePlayer(deck, info_card);
break;
case 2:
system("cls");
programForMultiplayerWithoutDealer(deck, info_card,ranking, ranking_s_times, n, s);
break;
case 3:
system("cls");
programForMultiplayerAndDealer(deck, info_card, ranking, ranking_s_times, n, s);
break;
case 4:
system("cls");
programForMatchBetweenPlayerAndDealer(deck, info_card, ranking, ranking_s_times, s);
break;
case 5:
cout << "==> Ban da thoat tro choi." << endl;
break;
}
} while (choice != end);
return 0;
} | true |
102cf2a8cbb849719a8302079521b7364dc90b45 | C++ | avast/retdec | /src/utils/math.cpp | UTF-8 | 635 | 2.921875 | 3 | [
"MIT",
"Zlib",
"JSON",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"NCSA",
"WTFPL",
"BSL-1.0",
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | /**
* @file src/utils/math.cpp
* @brief Mathematical utilities.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/utils/math.h"
namespace retdec {
namespace utils {
/**
* @brief Counts all 1 bits in the given number.
*/
unsigned countBits(unsigned long long n) {
unsigned count = 0;
for (count = 0; n != 0; n &= n - 1) {
++count;
}
return count;
}
/**
* @brief Returns the number of bits needed to encode the given number.
*/
unsigned bitSizeOfNumber(unsigned long long v) {
unsigned int r = 0;
while (v >>= 1) {
r++;
}
return r + 1;
}
} // namespace utils
} // namespace retdec
| true |
19883d79b1763e5a9edecb7817ee89a4a69debf5 | C++ | shravanAngadi/seafile-client | /src/api/commit-details.cpp | UTF-8 | 1,475 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #include "commit-details.h"
namespace {
QString getStringFromJsonArray(const json_t *array, size_t index)
{
return QString::fromUtf8(json_string_value(json_array_get(array, index)));
}
void processFileList(const json_t *json, const char *key, std::vector<QString> *files)
{
json_t *array = json_object_get(json, key);
if (array) {
for (int i = 0, n = json_array_size(array); i < n; i++) {
QString name = getStringFromJsonArray(array, i);
files->push_back(name);
}
}
}
} // namespace
CommitDetails CommitDetails::fromJSON(const json_t *json, json_error_t */* error */)
{
CommitDetails details;
processFileList(json, "added_files", &details.added_files);
processFileList(json, "deleted_files", &details.deleted_files);
processFileList(json, "modified_files", &details.modified_files);
processFileList(json, "added_dirs", &details.added_dirs);
processFileList(json, "deleted_dirs", &details.deleted_dirs);
// process renamed files
json_t *array = json_object_get(json, "renamed_files");
if (array) {
for (int i = 0, n = json_array_size(array); i < n; i += 2) {
QString before_rename = getStringFromJsonArray(array, i);
QString after_rename = getStringFromJsonArray(array, i + 1);
std::pair<QString, QString> pair(before_rename, after_rename);
details.renamed_files.push_back(pair);
}
}
return details;
}
| true |
5ddbdb19d8341c21de2861d498b284445d5245ee | C++ | longyangzz/OpenVizEarth | /src/Core/DCScene/scene/ScreenshotHandler.h | UTF-8 | 742 | 2.578125 | 3 | [] | no_license | #ifndef _SCREENSHOT_HANDLER_H_
#define _SCREENSHOT_HANDLER_H_
#include <QtCore/QObject>
#include <osg/Image>
#include <osgViewer/ViewerEventHandlers>
class ScreenshotHandler :
public QObject, public osgViewer::ScreenCaptureHandler::CaptureOperation
{
Q_OBJECT
public:
ScreenshotHandler(const std::string& filename,const std::string& extension);
~ScreenshotHandler(){}
osg::Image *getScreenShot() {return m_copyImage; }
void operator () (const osg::Image& image, const unsigned int context_id);
signals:
void newScreenshotAvailable(osg::Image *);
private:
const std::string m_filename;
const std::string m_extension;
osg::ref_ptr<osg::Image> m_copyImage;
};
#endif // _SCREENSHOT_HANDLER_H_
| true |
a95989db272759fcd9509696849a13ca1aa5d6a6 | C++ | cubeman99/RussianStudyTool | /source/gui/Widget.h | UTF-8 | 2,398 | 2.84375 | 3 | [] | no_license | #pragma once
#include "gui/GUIObject.h"
#include "gui/KeyShortcut.h"
class Layout;
class Widget : public GUIObject
{
public:
friend class GUIManager;
Widget();
virtual ~Widget();
const AccentedText& GetWindowTitle() const { return m_windowTitle; }
Layout* GetLayout() const { return m_layout; }
bool IsFocused() const { return m_isFocused; }
bool IsFocusable() const { return m_isFocusable; }
const Color& GetBackgroundColor() const { return m_backgroundColor; }
void SetLayout(Layout* layout);
void SetWindowTitle(const AccentedText& windowTitle) { m_windowTitle = windowTitle; }
void SetEnabled(bool enabled) { m_isEnabled = enabled; }
void SetVisible(bool visible) { m_isVisible = visible; }
void SetFocusable(bool focusable) { m_isFocusable = focusable; }
void SetBackgroundColor(const Color& backgroundColor) { m_backgroundColor = backgroundColor; }
void Close();
void Focus();
void AddKeyShortcut(const String& shortcut, KeyShortcut::Callback callback);
virtual bool OnMouseDown(MouseButtons::value_type buttons, const Vector2f& location) { return false; }
virtual void OnMouseUp(MouseButtons::value_type buttons, const Vector2f& location) {}
virtual bool OnKeyDown(Keys key, uint32 mods) { return false; }
virtual bool OnKeyTyped(unichar charCode, Keys key, uint32 mods) { return false; }
virtual void OnUpdate(float timeDelta) {}
virtual void OnRender(AppGraphics& g, float timeDelta) {}
virtual bool IsWidget() const override { return true; }
virtual bool IsVisible() const override { return m_isVisible; }
virtual bool IsEnabled() const override { return m_isEnabled; }
virtual uint32 GetNumChildren() const override;
virtual GUIObject* GetChild(uint32 index) override;
virtual void CalcSizes() override;
virtual void Update(float timeDelta) override;
virtual void Render(AppGraphics& g, float timeDelta) override;
EventSignal<>& Closed() { return m_eventClosed; }
EventSignal<>& LostFocus() { return m_eventLoseFocus; }
EventSignal<>& GainedFocus() { return m_eventGainFocus; }
private:
AccentedText m_windowTitle = "";
Layout* m_layout = nullptr;
bool m_isFocused = false;
bool m_isFocusable = false;
bool m_isEnabled = true;
bool m_isVisible = true;
Color m_backgroundColor = Color(0, 0, 0, 0);
Array<KeyShortcut> m_keyShortcuts;
EventSignal<> m_eventClosed;
EventSignal<> m_eventLoseFocus;
EventSignal<> m_eventGainFocus;
}; | true |
fa27501b4ee957f80771a6fdd29653a7daf44842 | C++ | Jim-Holmstroem/dd2447_project | /src/randomize.cpp | UTF-8 | 14,756 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <functional>
#include <algorithm>
#include <numeric>
#include <vector>
#include <cmath>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <strings.h>
#include <sys/time.h>
/*
* The SGI std::identity newer made it to the std :(
* However it's kinda easy to implement :)
*/
template<typename T>
struct identity : public std::unary_function<T, T> {
public:
inline const T & operator() (const T & t) const {
return t;
}
};
/*
* Generic templated fast randomize element from range functor.
* Used to randomize from available vertices but also to find labels
* on switches
* operator is a functor following std::unary_operator<ElementT, bool>
* whose operator() return true if the element is available for usage
* Note that it requires the tracking of how many items in the range
* are already occupied
*/
template<typename IteratorT, typename OperatorT, typename SizeT>
IteratorT random_index(IteratorT it, const IteratorT & end, SizeT available_indices_count, const OperatorT & op) {
SizeT index = rand() % available_indices_count;
for(; it != end; ++it) {
if (op(*it)) {
if (index-- <= 0)
return it;
}
}
return end;
}
/* For conversion between int to labels */
static const char connection_types[] = "LR0";
template<size_t VertexCount, bool AllowLoops = true>
class random_graph_t {
public:
typedef char connection_type_t;
typedef std::vector<connection_type_t> connection_t;
/*
* Quite the ugly wrapper for a vector but is required as the templating
* requires a unique type
*/
/*struct connection_t {
public:
typedef std::vector<connection_type_t>::const_iterator const_iterator;
typedef std::vector<connection_type_t>::iterator iterator;
inline std::vector<connection_type_t>::const_iterator begin() const {
return m_connection.begin();
}
inline std::vector<connection_type_t>::const_iterator end() const {
return m_connection.end();
}
inline std::vector<connection_type_t>::iterator begin() {
return m_connection.begin();
}
inline std::vector<connection_type_t>::iterator end() {
return m_connection.end();
}
inline bool empty() const {
return m_connection.empty();
}
inline std::vector<connection_type_t>::size_type size() const {
return m_connection.size();
}
inline void push_back(connection_type_t conn) {
m_connection.push_back(conn);
}
private:
std::vector<connection_type_t> m_connection;
};*/
typedef std::pair<unsigned int, unsigned int> edge_t;
static const size_t size = VertexCount;
static const size_t connections_per_vertex;
enum {
None = '\0',
L = 'L',
R = 'R',
O = '0'
};
const connection_t *operator[] (size_t index) const {
return m_graph[index];
}
/*
* randomize a valid graph
*/
random_graph_t() : m_graph(), m_fully_occupied_vertices_count(0) {
memset(m_connections_per_vertex, 0, sizeof(m_connections_per_vertex));
while (m_fully_occupied_vertices_count < size)
assign_edge(random_possible_edge());
/*
* Now label edges
*/
for(size_t i = 0; i < size; ++i) {
bool label_available[] = { true, true, true };
unsigned int labels_available_count = sizeof(label_available) / sizeof(bool);
for(size_t j = 0; j < size; ++j) {
for(typename connection_t::iterator it = m_graph[i][j].begin(); it != m_graph[i][j].end(); ++it) {
bool *rit = random_index(label_available,
label_available + sizeof(label_available) / sizeof(bool),
labels_available_count,
identity<bool>());
*rit = false;
*it = connection_types[rit - label_available];
--labels_available_count;
}
}
}
}
/*
* Debugging
*/
/*
* Really simple graph plot, just randomizes coordinates over a canvas then draws lines between them in a random color
* and render the L, R or 0 type of the switch
*/
std::ostream & svg(std::ostream & stream) const {
return stream;
}
bool validate() const {
/*
* Make sure the graph is symmetric in the way connections are defined
* in both directions, note that the labels do *NOT* have to match!
*/
for(size_t i = 0; i < size; ++i) {
for(size_t j = 0; j < size; ++j) {
if (m_graph[i][j].size() != m_graph[j][i].size()) {
std::cerr << "graph[" << i << "][" << j << "] != graph[" << j << "][" << i << "]" << std::endl;
return false;
}
}
}
/*
* Make sure connection count is the same
*/
for(size_t i = 0; i < size; ++i) {
if (m_connections_per_vertex[i] != connections_per_vertex) {
std::cerr << "connections[" << i << "]: " << m_connections_per_vertex[i] << " != " << connections_per_vertex << std::endl;
return false;
}
}
if (m_fully_occupied_vertices_count != size) {
std::cerr << "fully_occupied_vertices_count != size" << std::endl;
return false;
}
return true;
}
private:
connection_t m_graph [VertexCount][VertexCount];
unsigned int m_connections_per_vertex[VertexCount], m_fully_occupied_vertices_count;
/*
* Find an available vertex
* Old version does a plain randomize and iterates until successful,
* this can miss a lot, especially in the end.
* The new instead randomizes only of the set of available
* vertices, at the cost of a linear seek
*/
unsigned int random_available_vertex() const {
const unsigned int *it =
random_index(m_connections_per_vertex,
m_connections_per_vertex + size,
size - m_fully_occupied_vertices_count,
std::bind2nd(std::not_equal_to<unsigned int>(),
connections_per_vertex));
assert(it != m_connections_per_vertex + size);
return (unsigned int) (it - m_connections_per_vertex);
}
/*
* The number of connections from a vertex
*/
inline size_t vertex_connection_count(unsigned int index) const {
/* Debugging consistency */
#if 1
size_t count = 0;
for(size_t i = 0; i < size; ++i)
count += m_graph[index][i].size();
assert(count == m_connections_per_vertex[index]);
#endif
return m_connections_per_vertex[index];
}
/* Find a possible edge */
edge_t random_possible_edge() const {
/* Template argument, will be eliminated on compile */
if (!AllowLoops) {
unsigned int v1 = random_available_vertex(), v2;
do {
v2 = random_available_vertex();
}
while (v2 == v1);
return std::make_pair(v1, v2);
}
else {
/*
* There is a special case, if the two vertices chosen
* are the same, it is allowed, however, if these already have
* two edges connected, it will not be possible to make a
* connection to itself, because that will occupy two "slots"
*/
unsigned int v1 = random_available_vertex(),
v2 = random_available_vertex();
if (v1 == v2) {
if (vertex_connection_count(v1) > connections_per_vertex - 2) {
/*
* Even though the vertex can take another connection,
* there's not space for two!
*/
/* Special case: If there are other loops,
* and even if the number of vertices is even
* we can have a case where only a single vertex is left
* and there is no solution,
* in this case we abort, but we could do a repair
* easier is to disable loops
*/
if (m_fully_occupied_vertices_count == size - 1) {
std::cerr << "There's only one node remaining and "
"there are probably loops occuring "
"but this node can't handle another loop, "
"it has only space for one connection. "
"This is a very rare occasion and can be remedied "
"but i'm too lazy to do anything about it :)" << std::endl;
assert(m_fully_occupied_vertices_count < size - 1);
}
do {
v2 = random_available_vertex();
}
while (v2 == v1);
}
}
return std::make_pair(v1, v2);
}
}
/* Create the edge */
void assign_edge(const edge_t & edge) {
if (edge.first == edge.second) {
assert(vertex_connection_count(edge.first) <= connections_per_vertex - 2);
}
else {
assert(vertex_connection_count(edge.first) < connections_per_vertex);
assert(vertex_connection_count(edge.second) < connections_per_vertex);
}
/* Push back blank connection */
m_graph[edge.first][edge.second].push_back(None);
m_graph[edge.second][edge.first].push_back(None);
/*
* Track connections per vertex and fully occupied vertices,
* makes for faster randomizing of vertices/edges
*/
++m_connections_per_vertex[edge.first];
++m_connections_per_vertex[edge.second];
if (m_connections_per_vertex[edge.first] >= connections_per_vertex)
++m_fully_occupied_vertices_count;
if (m_connections_per_vertex[edge.second] >= connections_per_vertex) {
if (edge.first != edge.second)
++m_fully_occupied_vertices_count;
}
}
};
/*
* Prints a Python-style tuple representation of the graph
*/
/*template<size_t VertexCount, bool AllowLoops>
std::ostream & operator<<(std::ostream & stream, const typename random_graph_t<VertexCount, AllowLoops>::connection_t & connections) {
if (connections.empty())
stream << '0';
else {
stream << "( ";
std::copy(connections.begin(),
connections.end(),
std::ostream_iterator< typename random_graph_t<VertexCount, AllowLoops>::connection_type_t > (stream, ", "));
stream << " )";
}
}*/
template<size_t VertexCount, bool AllowLoops>
std::ostream & operator<<(std::ostream & stream, const random_graph_t<VertexCount, AllowLoops> & graph) {
stream << '{' << std::endl;
for(size_t row = 0; row < random_graph_t<VertexCount, AllowLoops>::size; ++row) {
stream << '{';
for(size_t col = 0; col < random_graph_t<VertexCount, AllowLoops>::size; ++col) {
if (graph[row][col].empty())
stream << "\"\"";
else {
stream << " \"";
typename random_graph_t<VertexCount, AllowLoops>::connection_t::const_iterator it;
for(it = graph[row][col].begin(); it != graph[row][col].end() - 1; ++it) {
//stream << " '" << *it << "',";
stream << *it;
}
stream << *it << "\"";
}
stream << (col != random_graph_t<VertexCount, AllowLoops>::size - 1 ? ',' : ' ');
}
stream << '}' << (row != random_graph_t<VertexCount, AllowLoops>::size ? ',' : ' ') << std::endl;
}
stream << '}';
return stream;
}
template<size_t VertexCount, bool AllowLoops>
const size_t random_graph_t<VertexCount, AllowLoops>::connections_per_vertex(3);
int main(int argc, const char **argv) {
srand(time(NULL));
static const size_t vertex_count = 12;
static const bool allow_loops = false;
/* Too large graphs won't fit nice on the stack, thus use the heap */
random_graph_t<vertex_count, allow_loops> *graph = new random_graph_t<vertex_count, allow_loops>();
std::cerr << "Validate: " << std::boolalpha << graph->validate() << std::endl;
std::cerr << "Array dump: " << std::endl << *graph << std::endl;
}
| true |
de5434fd6c84c9568c9c7e320c959f7407ee294a | C++ | PESITSouthCompSoc/vtu-cse-resources | /10CSL68-USP_and_CD_Lab/02/02.cpp | UTF-8 | 2,293 | 2.9375 | 3 | [] | no_license | /*
* Authored & Documented by:
Aditi Anomita Mohanty
github.com/rheaditi
Abinav Nithya Seelan
github.com/abinavseelan
* Problem Statement:
Write a C/C++ POSIX compliant program that prints the POSIX
defined configuration options supported on any given system
using feature test macros.
* Description:
Through POSIX, an application can query certain limits/availability of certain options or functionality, either at:
1. Compile-time : through MACROS defined in <unistd.h> and <limits.h>
2. Run-time : through use of the library functions sysconf(3) and pathconf(3)
* In the previous program (01) we queried the run-time system-wide limits using the library functions mentioned.
In this program, we use the feature-test MACROS defined in <unistd.h> and <limits.h>, to check during compile time if certain
configurations/options are supported.
* MACROS defined in:
/usr/include/unistd.h
*/
//These ensure we expose POSIX1.b limits
#define _POSIX_SOURCE
#define _POSIX_C_SOURCE 199309L
#include <iostream>
#include <stdio.h> //required for perror()
#include <unistd.h>
using namespace std;
int main(int argc, char ** argv)
{
cout << "Testing features.. \n\n";
#ifdef _POSIX_JOB_CONTROL
cout << "Job control is supported." << endl;
#else
cout << "Job control is NOT supported." << endl;
#endif
#ifdef _POSIX_SAVED_IDS
cout << "Processes have a saved set-user-ID and a saved set-group-ID." << endl;
#else
cout << "Processes DO NOT have a saved set-user-ID and a saved set-group-ID." << endl;
#endif
#ifdef _POSIX_TIMERS
cout << "POSIX.4 clocks and timers are supported." << endl;
#else
cout << "POSIX.4 clocks and timers are NOT supported." << endl;
#endif
#ifdef _POSIX_THREADS
cout << "POSIX.1c pthreads are supported." << endl;
#else
cout << "POSIX.1c pthreads are NOT supported." << endl;
#endif
#ifdef _POSIX_CHOWN_RESTRICTED
cout << "_POSIX_CHOWN_RESTRICTED option is defined with value: " << _POSIX_CHOWN_RESTRICTED << endl;
#else
cout << "_POSIX_CHOWN_RESTRICTED is not defined." << endl;
#endif
#ifdef _POSIX_NO_TRUNC
cout << "_POSIX_NO_TRUNC option is defined with value: "<< _POSIX_NO_TRUNC << endl;
#else
cout << "_POSIX_NO_TRUNC is not defined." << endl;
#endif
cout << endl;
}
| true |
630e62fd28cb6e5b77f267558da19be1afa16677 | C++ | MonZop/BioBlender21 | /scivis_tool/Point3f.h | UTF-8 | 2,868 | 3.390625 | 3 | [
"BSD-2-Clause"
] | permissive | //----------------- PUNTI -----------------------
#include <math.h>
#include <stdio.h>
#pragma once
class Point3f
{
protected:
float _v[3];
public:
// Costruttori & assegnatori
inline Point3f()
{
_v[0] = 0;
_v[1] = 0;
_v[2] = 0;
}
inline Point3f( const float nx, const float ny, const float nz )
{
_v[0] = nx;
_v[1] = ny;
_v[2] = nz;
}
inline Point3f( Point3f const & p )
{
_v[0]= p._v[0];
_v[1]= p._v[1];
_v[2]= p._v[2];
}
inline Point3f( const float nv[3] )
{
_v[0] = nv[0];
_v[1] = nv[1];
_v[2] = nv[2];
}
inline Point3f & operator =( Point3f const & p )
{
_v[0]= p._v[0];
_v[1]= p._v[1];
_v[2]= p._v[2];
return *this;
}
// Accesso alle componenti
inline const float &x() const { return _v[0]; }
inline const float &y() const { return _v[1]; }
inline const float &z() const { return _v[2]; }
inline float &x() { return _v[0]; }
inline float &y() { return _v[1]; }
inline float &z() { return _v[2]; }
inline float & operator [] ( const int i )
{
return _v[i];
}
inline const float & operator [] ( const int i ) const
{
return _v[i];
}
// Operatori matematici di base
inline Point3f operator + ( Point3f const & p) const
{
return Point3f( _v[0]+p._v[0], _v[1]+p._v[1], _v[2]+p._v[2] );
}
inline Point3f operator - ( Point3f const & p) const
{
return Point3f( _v[0]-p._v[0], _v[1]-p._v[1], _v[2]-p._v[2] );
}
inline Point3f operator * ( const float s ) const
{
return Point3f( _v[0]*s, _v[1]*s, _v[2]*s );
}
inline Point3f operator / ( const float s ) const
{
return Point3f( _v[0]/s, _v[1]/s, _v[2]/s );
}
// dot product
inline float operator * ( Point3f const & p ) const
{
return ( _v[0]*p._v[0] + _v[1]*p._v[1] + _v[2]*p._v[2] );
}
// Cross product
inline Point3f operator ^ ( Point3f const & p ) const
{
return Point3f
(
_v[1]*p._v[2] - _v[2]*p._v[1],
_v[2]*p._v[0] - _v[0]*p._v[2],
_v[0]*p._v[1] - _v[1]*p._v[0]
);
}
inline Point3f & operator += ( Point3f const & p)
{
_v[0] += p._v[0];
_v[1] += p._v[1];
_v[2] += p._v[2];
return *this;
}
inline Point3f & operator -= ( Point3f const & p)
{
_v[0] -= p._v[0];
_v[1] -= p._v[1];
_v[2] -= p._v[2];
return *this;
}
inline Point3f & operator *= ( const float s )
{
_v[0] *= s;
_v[1] *= s;
_v[2] *= s;
return *this;
}
inline Point3f & operator /= ( const float s )
{
_v[0] /= s;
_v[1] /= s;
_v[2] /= s;
return *this;
}
// Norme
inline float Norm() const
{
return sqrt( _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] );
}
inline float SquaredNorm() const
{
return ( _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2] );
}
// normalization
inline Point3f Normalize() const
{
float norm = sqrt( _v[0]*_v[0] + _v[1]*_v[1] + _v[2]*_v[2]);
return Point3f( _v[0]/norm, _v[1]/norm, _v[2]/norm );
}
};
| true |
bb3aca2167ef8a4280b7916d56e6f5f4a742cc27 | C++ | JoeCitizen/EtherPi | /Send.cpp | UTF-8 | 1,315 | 2.84375 | 3 | [] | no_license | #include <Common.h>
#include <Send.h>
namespace EtherPi
{
void Send::Init()
{
wiringPiSetupGpio();
pinMode(GPIO::Data_0, OUTPUT);
pinMode(GPIO::Data_1, OUTPUT);
pinMode(GPIO::Data_Ready, OUTPUT);
pinMode(GPIO::Data_Acknowledge, INPUT);
pullUpDnControl(GPIO::Data_Acknowledge, PUD_DOWN);
TurnOffDataReady();
}
void Send::Run()
{
PacketHeader header = {};
header.m_PacketLength = 0xDEADBEEF;
SendBytes((uint8_t*)&header, sizeof(header));
}
void Send::SendBytes(uint8_t* data, size_t length)
{
for (size_t byte = 0; byte < length; byte++)
{
uint8_t value = data[byte];
uint8_t mask = 1;
for (size_t nibble = 0; nibble < 4; nibble++)
{
std::cout << "write" << std::endl;
digitalWrite(GPIO::Data_0, (value & mask) ? HIGH : LOW);
mask <<= 1;
digitalWrite(GPIO::Data_1, (value & mask) ? HIGH : LOW);
mask <<= 1;
IndicateDataReady();
delay(500);
WaitForAcknowldgement();
TurnOffDataReady();
delay(500);
}
}
}
void Send::WaitForAcknowldgement()
{
int ack = 0;
do
{
ack = digitalRead(GPIO::Data_Acknowledge);
} while(!ack);
}
void Send::IndicateDataReady()
{
digitalWrite(GPIO::Data_Ready, HIGH);
}
void Send::TurnOffDataReady()
{
digitalWrite(GPIO::Data_Ready, LOW);
}
}
| true |
1e5c1b4f34025d8feddcc77a555e19b4cc892e16 | C++ | dushyant-goel/leetcode | /152.MaximumProductSubarray.cpp | UTF-8 | 485 | 2.859375 | 3 | [] | no_license | class Solution
{
public:
int maxProduct(vector<int> &nums)
{
int min_prod, max_prod, res;
res = min_prod = max_prod = nums[0];
for (int i = 1; i < nums.size(); i++)
{
int t1 = max_prod;
int t2 = min_prod;
max_prod = max({nums[i], t1 * nums[i], t2 * nums[i]});
min_prod = min({nums[i], t1 * nums[i], t2 * nums[i]});
res = max(max_prod, res);
}
return res;
}
}; | true |
94a376ae5fd694aa269959a11f3bee65436294e7 | C++ | gnishida/TensorTest | /TensorTest/main.cpp | UTF-8 | 14,505 | 2.84375 | 3 | [] | no_license | #include <glm/glm.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <random>
#include <iostream>
#include <list>
#ifndef M_PI
#define M_PI 3.14159265358
#endif
double delta = 1e-6f;
/**
* 座標pt、角度angleから開始して1本の道路を生成する。
*
* @param size ターゲットエリアの一辺の長さ
* @param angle 角度
* @param pt 開始位置
* @param curvature 曲率
* @param segment_length segment length
* @param regular_elements [OUT] tensor fieldを指定するためのコントロール情報
* @param vertices [OUT] 生成された頂点をこのリストに追加する
* @param edges [OUT] 生成されたエッジをこのリストに追加する
*/
void growRoads(int size, double angle, glm::dvec2 pt, double curvature, double segment_length, std::vector<std::pair<glm::dvec2, double>>& regular_elements, std::vector<std::pair<glm::dvec2, int>>& vertices, std::vector<std::pair<glm::dvec2, glm::dvec2>>& edges) {
int num_steps = 5;
while (true) {
// 今後5ステップ分の曲率を、平均がcurvatureになるようランダムに決定する。
std::vector<double> rotates;
double total = 0.0f;
for (int i = 0; i < num_steps; ++i) {
double r = rand() % 100;
rotates.push_back(r);
total += r;
}
for (int i = 0; i < num_steps; ++i) {
rotates[i] = rotates[i] / total * curvature * num_steps;
}
// 曲がる方向を決定する
int rotate_dir = rand() % 2 == 0 ? 1 : -1;
// 5ステップ分の道路セグメントを生成する
for (int i = 0; i < num_steps; ++i) {
// ターゲットエリア外なら終了
if (pt.x < -size / 2 || pt.x > size / 2 || pt.y < -size / 2 || pt.y > size / 2) return;
angle += rotates[i] * rotate_dir;
glm::dvec2 pt2 = pt + glm::dvec2(cos(angle), sin(angle)) * segment_length;
vertices.push_back(std::make_pair(pt2, 1));
edges.push_back(std::make_pair(pt, pt2));
regular_elements.push_back(std::make_pair(pt2, angle));
pt = pt2;
}
}
}
bool isIntersect(const glm::dvec2& a, const glm::dvec2& b, const glm::dvec2& c, const glm::dvec2& d, glm::dvec2& intPt) {
glm::dvec2 u = b - a;
glm::dvec2 v = d - c;
double numer = v.x * (c.y - a.y) + v.y * (a.x - c.x);
double denom = u.y * v.x - u.x * v.y;
if (denom == 0.0) {
return false;
}
double t0 = numer / denom;
glm::dvec2 ipt = a + t0*u;
glm::dvec2 tmp = ipt - c;
double t1;
if (glm::dot(tmp, v) > 0.0) {
t1 = glm::length(tmp) / glm::length(v);
}
else {
t1 = -1.0f * glm::length(tmp) / glm::length(v);
}
//Check if intersection is within segments
if (!(t0 >= delta && t0 <= 1.0 - delta && t1 >= delta && t1 <= 1.0 - delta)) {
return false;
}
glm::dvec2 dirVec = b - a;
intPt = a + t0 * dirVec;
return true;
}
/**
* 指定されたtensor filedに基づいて、ptからsegment_length分の道路セグメントを生成する。
* ただし、ターゲットエリア外に出るか、既存セグメントとの交差点が既存交差点の近くなら、途中で終了する。
*
* @param tensor tensor field
* @param segment_length segment length
* @param near_threshold near threshold
* @param pt [OUT] この座標から道路セグメント生成を開始する
* @param type 1 -- major eigen vector / 2 -- minor eigen vector
* @param dir 1 -- 正の方向 / -1 -- 負の方向
* @param new_vertices [OUT] 既存セグメントとの交差点をこのリストに追加する
* @param vertices 既存交差点
* @param edges [OUT] 既存セグメント
* @return 0 -- 正常終了 / 1 -- ターゲットエリア外に出て終了 / 2 -- 既存交差点の近くで交差して終了
*/
int generateRoadSegmentByTensor(const cv::Mat& tensor, double segment_length, double near_threshold, glm::dvec2& pt, int type, int dir, std::vector<std::pair<glm::dvec2, int>>& new_vertices, const std::vector<std::pair<glm::dvec2, int>>& vertices, std::vector<std::pair<glm::dvec2, glm::dvec2>>& edges) {
int num_step = 5;
double step_length = segment_length / num_step;
int result = 0;
for (int i = 0; i < num_step; ++i) {
int c = pt.x + tensor.cols / 2;
int r = pt.y + tensor.rows / 2;
if (c < 0 || c >= tensor.cols || r < 0 || r >= tensor.rows) {
result = 1;
break;
}
/////////////////////////////////////////////////////////////////////
// use Runge-Kutta 4 to obtain the next angle
double angle1 = tensor.at<double>(r, c);
if (type == 2) angle1 += M_PI / 2; // minor eigen vectorならPI/2を足す
// angle2
glm::vec2 pt2 = pt + glm::dvec2(cos(angle1), sin(angle1)) * (step_length * 0.5 * dir);
int c2 = pt2.x + tensor.cols / 2;
int r2 = pt2.y + tensor.rows / 2;
double angle2 = angle1;
if (c2 >= 0 && c2 < tensor.cols && r2 >= 0 && r2 < tensor.rows) {
angle2 = tensor.at<double>(r2, c2);
if (type == 2) angle2 += M_PI / 2; // minor eigen vectorならPI/2を足す
}
// angle3
glm::vec2 pt3 = pt + glm::dvec2(cos(angle2), sin(angle2)) * (step_length * 0.5 * dir);
int c3 = pt3.x + tensor.cols / 2;
int r3 = pt3.y + tensor.rows / 2;
double angle3 = angle2;
if (c3 >= 0 && c3 < tensor.cols && r3 >= 0 && r3 < tensor.rows) {
angle3 = tensor.at<double>(r3, c3);
if (type == 2) angle3 += M_PI / 2; // minor eigen vectorならPI/2を足す
}
// angle4
glm::vec2 pt4 = pt + glm::dvec2(cos(angle3), sin(angle3)) * (step_length * dir);
int c4 = pt4.x + tensor.cols / 2;
int r4 = pt4.y + tensor.rows / 2;
double angle4 = angle3;
if (c4 >= 0 && c4 < tensor.cols && r4 >= 0 && r4 < tensor.rows) {
angle4 = tensor.at<double>(r4, c4);
if (type == 2) angle4 += M_PI / 2; // minor eigen vectorならPI/2を足す
}
// RK4によりangleを計算
double angle = angle1 / 6.0 + angle2 / 3.0 + angle3 / 3.0 + angle4 / 6.0;
// 次のステップの座標を求める
glm::vec2 next_pt = pt + glm::dvec2(cos(angle), sin(angle)) * (step_length * dir);
// 交差点を求める
for (int k = 0; k < edges.size(); ++k) {
glm::dvec2 intPt;
if (isIntersect(edges[k].first, edges[k].second, pt, next_pt, intPt)) {
new_vertices.push_back(std::make_pair(intPt, 3));
// 既に近くに頂点がないかチェック
bool near = false;
for (int k = 0; k < vertices.size(); ++k) {
// major vector と minor vectorで異なる場合は、チェックしない
if (!(vertices[k].second & type)) continue;
if (glm::length(vertices[k].first - intPt) < near_threshold) {
near = true;
break;
}
}
if (near) {
// 道路セグメントの生成を交差点でストップさせる
next_pt = intPt;
i = num_step;
result = 2;
break;
}
}
}
edges.push_back(std::make_pair(pt, next_pt));
pt = next_pt;
}
return result;
}
/**
* 指定されたtensor fieldに基づいて、ptから道路生成を行う。
*
* @param tensor tensor field
* @param segment_length segment length
* @param near_threshold near threshold
* @param pt この座標から道路セグメント生成を開始する
* @param type 1 -- major eigen vector / 2 -- minor eigen vector
* @param dir 1 -- 正の方向 / -1 -- 負の方向
* @param vertices [OUT] 既存交差点
* @param edges [OUT] 既存セグメント
* @param seeds [OUT] 新規シードをこのリストに追加する
*/
void generateRoadByTensor(const cv::Mat& tensor, double segment_length, double near_threshold, glm::dvec2 pt, int type, int dir, std::vector<std::pair<glm::dvec2, int>>& vertices, std::vector<std::pair<glm::dvec2, glm::dvec2>>& edges, std::list<std::pair<glm::dvec2, int>>& seeds) {
std::vector<std::pair<glm::dvec2, int>> new_vertices;
while (true) {
int result = generateRoadSegmentByTensor(tensor, segment_length, near_threshold, pt, type, dir, new_vertices, vertices, edges);
if (result == 1) { // ターゲットエリア外に出た
break;
}
else if (result == 2) { // 既存交差点近くのエッジに交差した
break;
}
else {
// 既に近くに頂点がないかチェック
bool near = false;
for (int k = 0; k < vertices.size(); ++k) {
// major vector と minor vectorで異なる場合は、チェックしない
if (!(vertices[k].second & type)) continue;
if (glm::length(vertices[k].first - pt) < near_threshold) near = true;
}
if (near) break;
}
new_vertices.push_back(std::make_pair(pt, type));
seeds.push_back(std::make_pair(pt, 3 - type));
}
// 新規交差点をverticesに追加
vertices.insert(vertices.end(), new_vertices.begin(), new_vertices.end());
}
/**
* 指定されたtensor fieldに基づいて道路網を生成する。
*
* @param tensor tensor field
* @param segment_length segment length
* @param near_threshold near threshold
* @param vertices [OUT] 既存交差点
* @param edges [OUT] 既存セグメント
*/
void generateRoadsByTensor(const cv::Mat& tensor, double segment_length, double near_threshold, std::vector<std::pair<glm::dvec2, int>>& vertices, std::vector<std::pair<glm::dvec2, glm::dvec2>>& edges) {
std::list<std::pair<glm::dvec2, int>> seeds;
for (int i = 0; i < vertices.size(); ++i) {
seeds.push_back(std::make_pair(vertices[i].first, 3 - vertices[i].second));
}
int count = 0;
while (!seeds.empty()) {
glm::dvec2 pt = seeds.front().first;
int type = seeds.front().second;
seeds.pop_front();
if (pt.x < -tensor.cols / 2 || pt.x >= tensor.cols / 2 || pt.y < -tensor.rows / 2 || pt.y >= tensor.rows / 2) continue;
// 既に近くに頂点がないかチェック
bool near = false;
for (int k = 0; k < vertices.size(); ++k) {
// major vector と minor vectorで異なる場合は、チェックしない
if (!(vertices[k].second & type)) continue;
double dist = glm::length(vertices[k].first - pt);
if (dist < near_threshold) near = true;
}
std::cout << count << ": (" << pt.x << ", " << pt.y << ") " << type << (near ? " canceled" : "") << std::endl;
if (!near) {
generateRoadByTensor(tensor, segment_length, near_threshold, pt, type, 1, vertices, edges, seeds);
generateRoadByTensor(tensor, segment_length, near_threshold, pt, type, -1, vertices, edges, seeds);
}
count++;
if (count > 500) break;
}
}
void saveTensorImage(const cv::Mat& tensor, const std::string& filename) {
cv::Mat result(tensor.size(), CV_8U, cv::Scalar(255));
for (int r = 0; r < tensor.rows; r += 50) {
for (int c = 0; c < tensor.cols; c += 50) {
int x1 = c;
int y1 = r;
double angle = tensor.at<double>(r, c);
int x2 = x1 + cos(angle) * 30;
int y2 = y1 + sin(angle) * 30;
cv::line(result, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0), 1, cv::LINE_AA);
}
}
cv::flip(result, result, 0);
cv::imwrite(filename.c_str(), result);
}
void saveRoadImage(int size, const std::vector<std::pair<glm::dvec2, int>>& vertices, const std::vector<std::pair<glm::dvec2, glm::dvec2>>& edges, const std::string& filename, bool showVertices, bool showArrow) {
cv::Mat result(size, size, CV_8UC3, cv::Scalar(255, 255, 255));
for (int i = 0; i < edges.size(); ++i) {
double x1 = edges[i].first.x + size / 2;
double y1 = edges[i].first.y + size / 2;
double x2 = edges[i].second.x + size / 2;
double y2 = edges[i].second.y + size / 2;
cv::line(result, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 0, 0), 1, cv::LINE_AA);
if (showArrow) {
double angle = atan2(y2 - y1, x2 - x1);
double angle1 = angle + M_PI - 20.0 / 180.0 * M_PI;
double angle2 = angle + M_PI + 20.0 / 180.0 * M_PI;
double x3 = x2 + 10 * cos(angle1);
double y3 = y2 + 10 * sin(angle1);
cv::line(result, cv::Point(x2, y2), cv::Point(x3, y3), cv::Scalar(0, 0, 0), 1, cv::LINE_AA);
double x4 = x2 + 10 * cos(angle2);
double y4 = y2 + 10 * sin(angle2);
cv::line(result, cv::Point(x2, y2), cv::Point(x4, y4), cv::Scalar(0, 0, 0), 1, cv::LINE_AA);
}
}
if (showVertices) {
for (int i = 0; i < vertices.size(); ++i) {
cv::Scalar color;
if (vertices[i].second == 1) {
color = cv::Scalar(255, 0, 0);
}
else if (vertices[i].second == 2) {
color = cv::Scalar(0, 0, 255);
}
else {
color = cv::Scalar(0, 255, 0);
}
cv::circle(result, cv::Point(vertices[i].first.x + size / 2, vertices[i].first.y + size / 2), 3, color, 1);
}
}
cv::flip(result, result, 0);
cv::imwrite(filename.c_str(), result);
}
void test(int size, double segment_length, double angle, double curvature, const std::string& filename) {
std::vector<std::pair<glm::dvec2, int>> vertices;
std::vector<std::pair<glm::dvec2, glm::dvec2>> edges;
// 1本の道路をとりあえず作成
std::vector<std::pair<glm::dvec2, double>> regular_elements;
vertices.push_back(std::make_pair(glm::dvec2(0, 0), 1));
regular_elements.push_back(std::make_pair(glm::dvec2(0, 0), angle));
growRoads(size, angle, glm::vec2(0, 0), curvature, segment_length, regular_elements, vertices, edges);
growRoads(size, angle, glm::vec2(0, 0), curvature, -segment_length, regular_elements, vertices, edges);
//saveRoadImage(size, vertices, edges, "initial.png", false, false);
// setup the tensor field
cv::Mat tensor(size, size, CV_64F);
for (int r = 0; r < tensor.rows; ++r) {
for (int c = 0; c < tensor.rows; ++c) {
int x = c - tensor.rows / 2;
int y = r - tensor.rows / 2;
double total_angle = 0.0;
double total_weight = 0.0;
for (int k = 0; k < regular_elements.size(); ++k) {
double dist = glm::length(glm::dvec2(x, y) - regular_elements[k].first);
// convert the angle to be within [-pi/2, pi/2]
double angle = regular_elements[k].second;
double weight = exp(-dist / 10);
total_angle += angle * weight;
total_weight += weight;
}
float avg_angle = total_angle / total_weight;
tensor.at<double>(r, c) = avg_angle;
}
}
//saveTensorImage(tensor, "tensor.png");
// generate roads
generateRoadsByTensor(tensor, segment_length, segment_length * 0.7, vertices, edges);
// visualize the roads
saveRoadImage(size, vertices, edges, filename, false, false);
}
int main() {
int size = 1000;
srand(12);
test(size, 80, 0.0, 0.1, "result1.png");
srand(12345);
test(size, 80, 0.3, 0.2, "result2.png");
srand(1234578);
test(size, 80, 0.6, 0.15, "result3.png");
srand(125);
test(size, 80, 0.2, 0.3, "result4.png");
srand(5213);
test(size, 80, 0.75, 0.1, "result5.png");
srand(2352);
test(size, 80, 0.45, 0.0, "result6.png");
return 0;
} | true |
cd0a6c8f3a10000d388529ffc224a71546512175 | C++ | dmbonsall/BeagleBoneBlackIOLib | /inc/HardwareDevice.hpp | UTF-8 | 4,740 | 3.515625 | 4 | [] | no_license | /**
* @file HardwareDevice.h
* @author David Bonsall
* @version 1.0
* @see HardwareDevice.cpp
* TODO Need to set all appropriate methods to const and do the same for other classes
*/
#pragma once
#include <string>
/**
* Enumeration describing the different device types for any known children
* of the ::HardwareDevice class
*/
enum DeviceType
{
Generic, /**< Used if the device doesn't represent a specific king of device */
GPIO, /**< Used to describe a ::GPIO device. */
PWM, /**< Used to describe a ::PWM device.*/
ADC, /**< Used to describe an ADC device (analog input). */
Servo, /**< Used to describe a Servo device */
Unspecified /**< Default value for device types not specified in this enum */
};
/** This array maps the enum values of ::DeviceType to their string representations. */
const std::string deviceTypeStrings[] = {"Generic", "GPIO", "PWM", "ADC", "Servo",
"Unspecified"};
/**
* @brief Describes a generic hardware device that has a given file or directory in the
* Linux file system.
*
* The HardwareDevice class provides a simple template to create objects based off of
* devices represented in the Linux file system. For such a device, a file (or directory
* with files) can be read from, or written to in order to manipulate or interact with
* a given device. The class also contains members to describe the device such as name,
* physical location on the board, etc. While this class is not abstract, it was meant
* to be extended by sub-classes to describe more specific device behavior.
*/
class HardwareDevice
{
private:
std::string devDescription; /**< Stores a short user description of the device */
DeviceType deviceType; /**< Describes the type of device */
std::string deviceName; /**< Holds the user given name of the device */
std::string devicePath; /**< The file path of the device in the Linux file system */
std::string physicalLoc; /**< Describes the pin's location on the P8/P9 headers*/
protected:
/**
* Sets the user description of the device. Set by default in the constructor, this
* can be set again by a sub class after calling the HardwareDevice() constructor.
* @param description Text describing the device
*/
void setDescription(std::string description);
/**
* Writes a string to a file that describes a property of the device.
* @param pathModifier This modifier is appended to the device path to form the path
* of the file that will be written to. The path should always start with the '/' character
* in order to avoid errors associated with the file path.
* @param data A pointer to the string to be written to the file.
* @return Returns 0 if the write operation was successful, -1 if it wasn't.
*/
int writeToProperty(std::string pathModifier, std::string data);
/**
* Reads a string from a file that describes a property of the device.
* @param pathModifier This modifier is appended to the device path to form the path
* of the file that will be written to. the path should always start with the '/' character
* in order to avoid errors associated with the file path.
* @param data A pointer to the string to put the data that was read from the file.
* @return Returns 0 if the read operation was successful, -1 if it wasn't.
*/
int readFromProperty(std::string pathModifier, std::string *data);
public:
/**
* Constructor for the HardwareDevice class
* @param devicePath The path to the device's main directory in the Linux file system.
* @param deviceName The user specified name of the device, often used to look up the device
* if stored in a container.
* @param deviceType The type of device that this object represents.
*/
HardwareDevice(std::string devicePath, std::string deviceName, DeviceType deviceType,
std::string physicalLoc);
/**
* Gets the name of the device specified by the user in the constructor.
* @return The name associated with this HardwareDevice object.
*/
std::string getName();
/**
* Gets the path for this device specified by the user in the constructor.
* @return The device path associated with this HardwareDevice object.
*/
std::string getPath();
/**
* Gets the description of this object that is set with the ::setDevDescription() method.
* @return A string with the description of this HardwareDevice object.
*/
std::string getDescription();
/**
* Gets the device type of this device.
* @return The device type of this HardwareDevice object.
* @see ::DeviceType
*/
DeviceType getType();
/**
* Gets the physical location of the device on the board (P8/P9 headers, etc.).
* @return A string containing a description of the physical location of the device.
*/
std::string getPhysicalLoc();
};
| true |
22b526c4325fdd4d9df606d04a32fac58ca50874 | C++ | Shubham16103020/codes | /char_pointer.cpp | UTF-8 | 376 | 2.9375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i =65;
char c = i;
cout<< c<<endl;
int *p = &i;
char *pc =(char*) &i;
cout<<*p<<endl;
cout<< *pc <<endl;
cout<< p <<endl;
cout << pc <<endl;
// int typecasing
cout<< " int typecasting "<<endl;
char ck ='A';
int k = ck;
cout<< k<<endl;
char *cl = &ck;
int *pl =(int *)cl;
cout<<*cl<<endl;
cout<< *pl<<endl;
return 0;
}
| true |
1848d1ae7adcd4c934d1ee4ab4daf2c382b3fd06 | C++ | ArghaKamalSahoo/class | /dyna_init_constu.cpp | UTF-8 | 1,349 | 3.46875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class fixed_deposit
{
long int p_value;
int year;
float rate;
float R;
public:
fixed_deposit(){}
fixed_deposit(long int p,int y,int r);
fixed_deposit(long int p,int y,float r=0.12);
void display(void);
};
fixed_deposit::fixed_deposit(long int p,int y,int r )
{
int i;
p_value=p;
year=y;
rate=r;
R=p_value;
for(i=0;i<=y;i++)
{
R=R*(1.0+float(r)/100);
}
}
fixed_deposit::fixed_deposit(long int p,int y,float r)
{
int i;
p_value=p;
year=y;
rate=r;
R=p_value;
for(i=0;i<=y;i++)
{
R=R*(1.0+r);
}
}
void fixed_deposit::display(void)
{
cout<<"princilple amount="<<p_value<<endl;
cout<<"return value="<<R<<endl;
}
int main()
{
fixed_deposit f1,f2,f3;
long int p;
int y;
int r;
float R;
cout<<"enter the principle amount,year,interest in percentage"<<endl;
cin>>p>>y>>r;
f1=fixed_deposit(p,y,r);
cout<<"enter the principle amount,year,interest in decimal"<<endl;
cin>>p>>y>>R;
f2=fixed_deposit(p,y,R);
cout<<"enter the principle amount,year"<<endl;
cin>>p>>y;
f3=fixed_deposit(p,y);
cout<<"deposit 1"<<endl;
f1.display();
cout<<"deposit 2"<<endl;
f2.display();
cout<<"deposit 3"<<"\n";
f3.display();
return 0;
}
| true |
ae1d33146a26d6e7528858c0e6d4f30407d27b22 | C++ | Team302/Y1Bot2016 | /LoadBall.cpp | UTF-8 | 2,248 | 2.75 | 3 | [
"MIT"
] | permissive | /*=============================================================================================
* LoadBall.cpp
*=============================================================================================
*
* File Description:
*
* This controls loading a ball into the shooter.
*=============================================================================================*/
#include <SmartDashboard/SmartDashboard.h> // Smart Dashboard
// Team 302 includes
#include <LoadBall.h> // This class
#include <IShooter.h> // Class the control the shooter motors
#include <IShooterFactory.h> // Class constructs the correct chassis
#include <OperatorInterface.h> // Controls creating singleton of the gamepads
//--------------------------------------------------------------------
// Method: LoadBall <<constructor>>
// Description: This method creates and initializes the objects
//--------------------------------------------------------------------
LoadBall::LoadBall() : m_oi( OperatorInterface::GetInstance() ),
m_shooter( IShooterFactory::GetInstance()->GetIShooter() ),
m_switchTripped( false )
{
}
//--------------------------------------------------------------------
// Method: CycleLoader
// Description: This method will read the gamepad input and move run
// loader motor until the sensor detects it is back in
// load position
// Returns: void
//--------------------------------------------------------------------
void LoadBall::CycleLoader()
{
SmartDashboard::PutBoolean("load tripped", m_shooter->IsLoaderInPosition());
m_switchTripped = m_shooter->IsLoaderInPosition();
// If the button is pressed, load a ball
if (m_oi->GetRawButton(LOAD_BALL_BUTTON))
{
m_shooter->SetBallLoadMotor(m_shooterSpeedRun);
m_switchTripped = false;
}
// If the loader isn't in position, keep running the loader
else if (m_shooter->IsLoaderInPosition() == false && !m_switchTripped )
{
m_shooter->SetBallLoadMotor(m_shooterSpeedRun);
}
// Otherwise stop the loader
else
{
m_shooter->SetBallLoadMotor(m_shooterSpeedStopped); // fixed case
}
}
| true |
63ae23e3b4b6fa6f7e3465e4135af03935b15e7f | C++ | goo-gy/Algorithm | /baekjoon/3830_unionFind.cpp | UTF-8 | 1,709 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int N, M;
vector<int> v_parent;
vector<long long> v_weight;
void reset()
{
v_parent.clear();
v_weight.clear();
}
int find(int node)
{
if (v_parent[node] == -1)
return node;
int root = find(v_parent[node]);
v_weight[node] += v_weight[v_parent[node]];
v_parent[node] = root;
return root;
}
void merge(int node1, int node2, long long diff)
{
int root1 = find(node1);
int root2 = find(node2);
if (root1 == root2)
return;
long long diff1 = v_weight[root1] - v_weight[node1];
long long diff2 = v_weight[root2] - v_weight[node2] + diff;
if (diff1 < diff2)
{
v_parent[root1] = root2;
v_weight[root1] = diff1 - diff2;
}
else
{
v_parent[root2] = root1;
v_weight[root2] = diff2 - diff1;
}
}
void query(int node1, int node2)
{
int root1 = find(node1);
int root2 = find(node2);
if (root1 == root2)
cout << v_weight[node2] - v_weight[node1] << "\n";
else
cout << "UNKNOWN\n";
}
void solution()
{
while (true)
{
reset();
cin >> N >> M;
if (N == 0 && M == 0)
return;
v_parent.resize(N + 1, -1);
v_weight.resize(N + 1);
for (int i = 1; i <= M; i++)
{
char type;
int a, b, w;
cin >> type >> a >> b;
if (type == '!')
{
cin >> w;
merge(a, b, w);
}
else if (type == '?')
query(a, b);
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solution();
return 0;
} | true |
ef361b15b2e9aa92781e70082cf3a876fdc3b88e | C++ | Bob1Bob/eli-roject | /SFML Learn 1/Weapon.cpp | UTF-8 | 1,574 | 2.828125 | 3 | [] | no_license | #include "Weapon.h"
Weapon::Weapon(sf::Mouse mouse, Player play)
{
}
void Weapon::fireWeapon(sf::Mouse mouse, Player play, sf::RenderWindow & window)
{
m_mouse = mouse;
m_play = play;
sf::Vector2i mousePos = mouse.getPosition(window);
m_mousePosition = window.mapPixelToCoords(mousePos);
float changeInY = (play.getCenter().y - m_mousePosition.y);
float changeInX = (play.getCenter().x - m_mousePosition.x);
m_slope = changeInY / changeInX;
float speedMultiplier = abs(changeInX) / sqrt(pow(changeInY, 2) + pow(changeInX, 2)) * (m_bonusSpeed + 1.5f);
float x1 = play.getCenter().x;
float y1 = play.getCenter().y;
Bullet * c_bullet;
if (m_mousePosition.x < m_play.getCenter().x) {
c_bullet = new Bullet(speedMultiplier, m_slope, x1, y1, x1, y1, false);
}
else {
c_bullet = new Bullet(speedMultiplier, m_slope, x1, y1, x1, y1, true);
}
m_bullets.push_back(*c_bullet);
//m_bullets.insert(m_bullets.begin(), *c_bullet);
std::cout << m_mousePosition.x << std::endl;
//obj.setPosition(m_play.getCenter());
}
void Weapon::update(sf::RenderWindow& window)
{
for (int i = 0; i < m_bullets.size(); i++) {
m_bullets[i].update(window);
if (m_bullets[i].getTime() > 50.0f) {
//m_bullets.erase(m_bullets.begin);
//m_bullets.pop_back();
}
}
m_time += 0.1;
//m_bullets.shrink_to_fit();
}
void Weapon::setTime(float time)
{
m_time = time;
}
float Weapon::getTime()
{
return m_time;
}
float Weapon::getReloadSpeed()
{
return m_reloadSpeed;
}
void Weapon::clearBullets()
{
m_bullets.clear();
}
Weapon::~Weapon()
{
}
| true |
e85204dcc9dbbc37d6c43e94904c5f4985816592 | C++ | hthuwal/competitive-programming | /old/mixed/cpp/cubnum.cpp | UTF-8 | 573 | 2.6875 | 3 | [] | no_license | #include <cstdio>
#define N 111111
#define f(i,k,n) for(int i=k;i<n;i++)
int cubes[50]; //49^3 > N
int dp[N];
void cube()
{
f(i,0,50) cubes[i]=i*i*i;
}
void dyn()
{
int x;
dp[0]=0;
f(i,1,N)
{
dp[i]=N;
f(j,1,50)
{
x = j*j*j;
if(x > i)
break;
if(1+dp[i-x] < dp[i])
dp[i]=1+dp[i-x];
}
}
}
int main()
{
cube();
dyn();
int x,c;
c = 1;
while(scanf("%d",&x)!=EOF)
{
printf("Case #%d: %d\n",c,dp[x]);
c++;
}
} | true |
9a0c8e57d888e1630944456a35c577e512b8eaf9 | C++ | byeongkeunahn/word2vec | /word2vec/heap.h | UTF-8 | 400 | 3.09375 | 3 | [] | no_license |
#pragma once
typedef struct {
int id;
int num;
} heap_data;
class heap
{
public:
heap(int nmax);
~heap();
void add(const heap_data &item);
heap_data extract_min();
int count() const;
int min_id() const;
int min_num() const;
private:
void bubble_up(int idx);
void bubble_down(int idx);
private:
heap_data *_heap;
int _nmax;
int _count;
};
| true |
8435038483dd9934990a3c8dfe1ec13e8dbd5d71 | C++ | huakaitingqian/MHE_new | /Classes/CompeteStateController.cpp | WINDOWS-1252 | 1,998 | 2.578125 | 3 | [] | no_license | #include "CompeteStateController.h"
USING_NS_CC;
CompeteStateController::CompeteStateController()
{
time = 0;
visibleSize = Director::sharedDirector()->getVisibleSize();
}
CompeteStateController::~CompeteStateController()
{
}
CompeteStateController* CompeteStateController::create(NPC* npc, Vec2 gravity, BulletManager* bulletManager)
{
CompeteStateController* curStateController = new CompeteStateController();
curStateController->curNPC = npc;
curStateController->gravity = gravity;
curStateController->bulletManager = bulletManager;
//curStateController->propManager = curStateController->bulletManager->getPropManager();
//curStateController->propVector = *(curStateController->propManager->getPropVector());
return curStateController;
}
void CompeteStateController::update(float dt)
{
time += dt;
if(time > 4)
{
time = 0;
PropManager* propManager = bulletManager->getPropManager();
Vector<Prop*> propVector = *(propManager->getPropVector());
Vector<Prop*>::iterator iter;
for(iter = propVector.begin(); iter != propVector.end(); iter++)
{
if((*iter)->getPosition().x > 0 && (*iter)->getPosition().x <visibleSize.width)
{
hitPosition = (*iter)->getPosition();
fire();
break;
}
}
}
}
void CompeteStateController::fire()
{
Vec2 shootVelocity;
//
int temp = visibleSize.width/4 * rand()/(RAND_MAX+1.0);
hitPosition += Vec2(temp-visibleSize.width/4/2, 0);
Vec2 tempPosition = curNPC->getPosition();
Vec2 delta = hitPosition - tempPosition;
//if(fabs(delta.x) < visibleSize.width*3/4)
//{
shootVelocity.x = delta.x;
shootVelocity.y = delta.y + (-gravity.y)/2;
//}
//else
//{
// shootVelocity.y = delta.y + (-gravity.y)/2;
// shootVelocity.x =
// shootVelocity = Vec2(0,0);
//}
//shootVelocity.x =- sqrt((-gravity.y) * (tempPosition.x - hitPosition.x) / 4);
//shootVelocity.y = 2 * (-shootVelocity.x);
curNPC->fireAction();
bulletManager->shoot(NormalBullet, npc,curNPC->getPosition(),shootVelocity);
} | true |
53cced7a766ecf0e34ae33eb3b0916439d744230 | C++ | blueskin90/piscine_cpp | /d03/ex01/ScavTrap.cpp | UTF-8 | 3,811 | 3.1875 | 3 | [] | no_license | #include "ScavTrap.hpp"
ScavTrap::ScavTrap(void) : _hp(ScavTrap::maxhp), _ep(ScavTrap::maxep), _level(1), _name("Unnamed"), _meleeDamage(20), _rangedDamage(15), _armorReduc(3)
{
std::srand(time(NULL));
std::cout << "Vanilla SC4V-TP was born, behold it's mightiest scavenging abilities !" << std::endl ;
}
ScavTrap::ScavTrap(ScavTrap const &src) : _hp(src.getHp()), _ep(src.getEp()), _level(src.getLevel()), _name(src.getName()), _meleeDamage(src.getMeleeDamage()), _rangedDamage(getRangedDamage()), _armorReduc(src.getArmorReduc())
{
std::srand(time(NULL));
std::cout << "SC4V-TP " << src.getName() << " was cloned ! Twice the scavenging !" << std::endl ;
}
ScavTrap::ScavTrap(std::string name) : _hp(ScavTrap::maxhp), _ep(ScavTrap::maxep), _level(1), _name(name), _meleeDamage(20), _rangedDamage(15), _armorReduc(3)
{
std::srand(time(NULL));
std::cout << "SC4V-TP " << name << " is in the place, please hold your your hornyness." << std::endl;
}
ScavTrap::~ScavTrap(void)
{
std::cout << "SC4V-TP " << this->_name << " runned out of garbage to scavenge" << std::endl;
}
ScavTrap &ScavTrap::operator=(ScavTrap const &rhs) {
this->_name = rhs.getName();
this->_hp = rhs.getHp();
this->_ep = rhs.getEp();
this->_level = rhs.getLevel();
this->_meleeDamage = rhs.getMeleeDamage();
this->_rangedDamage = rhs.getRangedDamage();
this->_armorReduc = rhs.getArmorReduc();
return (*this);
}
void ScavTrap::rangedAttack(std::string const &target) const
{
std::cout << "SC4V-TP " << this->_name << " throws garbage at " << target << " , dealing " << this->_rangedDamage << " damages, yuck. " << std::endl;
}
void ScavTrap::meleeAttack(std::string const &target) const
{
std::cout << "SC4V-TP " << this->_name << " attacks " << target << " up with a frying pan, dealing " << this->_meleeDamage << " bonk damages." << std::endl;
}
void ScavTrap::takeDamage(unsigned int amount)
{
if (amount < this->_armorReduc)
{
std::cout << this->_name << " : really, that's all you got ?" << std::endl ;
return ;
}
std::cout << "SC4V-TP " << this->_name << " was at " << this->_hp << " and took " << amount << " damages (minus armor : " << this->_armorReduc << ") which causes him to be at : ";
if (this->_hp < (amount - this->_armorReduc))
this->_hp = 0;
else
this->_hp -= (amount - this->_armorReduc);
std::cout << this->_hp << " HPs, 'tis nothing but a scratch !" << std::endl;
}
void ScavTrap::beRepaired(unsigned int amount)
{
std::cout << "SC4V-TP " << this->_name << " was at " << this->_hp << " and repaired " << amount << " damages ! which causes him to be at : ";
if (amount > ScavTrap::maxhp || (this->_hp + amount) > ScavTrap::maxhp)
this->_hp = ScavTrap::maxhp;
else
this->_hp += amount;
std::cout << this->_hp << " he is more powerful than ever, fly you fools !" << std::endl;
}
void ScavTrap::challengeNewcomer(std::string const & target)
{
std::string attacks[6] = {" to a dancing contest !", " to say the alphabet in reverse", " to lick his / her elbow", " to finish a pint of Maximator", " to program a printf without any mallocs !", " to work at Safran without wanting to kill himself."
};
std::cout << this->_name << " challenges " << target << attacks[std::rand() % 6] << std::endl;
}
unsigned int ScavTrap::getHp(void) const
{
return (this->_hp);
}
unsigned int ScavTrap::getEp(void) const
{
return (this->_ep);
}
unsigned int ScavTrap::getLevel(void) const
{
return (this->_level);
}
std::string const &ScavTrap::getName(void) const
{
return (this->_name);
}
unsigned int ScavTrap::getMeleeDamage(void) const
{
return (this->_meleeDamage);
}
unsigned int ScavTrap::getRangedDamage(void) const
{
return (this->_rangedDamage);
}
unsigned int ScavTrap::getArmorReduc(void) const
{
return (this->_armorReduc);
}
| true |
0dea50e167b70273f234a20a9995e7a872c1cfb0 | C++ | remram44/bomberlua | /Display.cpp | UTF-8 | 9,077 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "Display.h"
#include <sstream>
static SDL_Surface *loadImage(const char *path) throw(Display::InitException)
{
SDL_Surface *surf = IMG_Load(path);
if(!surf)
{
std::ostringstream oss;
oss << "Error loading: " << path << " : " << IMG_GetError ();
throw Display::InitException(oss.str());
}
return surf;
}
void Display::init(const Engine *engine) throw(InitException)
{
std::string err;
if(SDL_Init(SDL_INIT_VIDEO))
{
err = "Error initializing SDL: ";
err += SDL_GetError();
throw InitException(err);
}
if(SDL_SetVideoMode(engine->getMapWidth()*32, engine->getMapHeight()*32, 32,
SDL_HWSURFACE | SDL_DOUBLEBUF) == NULL)
{
err = "Error creating the window: ";
err += SDL_GetError();
SDL_Quit();
throw InitException(err);
}
SDL_WM_SetCaption("BomberLua", NULL);
try
{
get()->m_pBrickSurface = loadImage("Images/Cells/Brick.png");
get()->m_pRockSurface = loadImage("Images/Cells/Rock.png");
get()->m_pEmptySurface = loadImage("Images/Cells/Empty.png");
get()->m_pBombermanSurface = loadImage("Images/SFX/Bomberman.png");
get()->m_pBombSurface = loadImage("Images/SFX/Bomb.png");
get()->m_pBoomSurface = loadImage("Images/SFX/Wave.png");
}
catch(InitException &e)
{
SDL_Quit();
throw e;
}
}
void Display::update(const Engine *engine)
{
const std::vector<Engine::ECell> map(engine->getMap());
Display::get()->drawMapSurface(
engine->getMapWidth(), engine->getMapHeight(), map);
std::vector<const Engine::Bomb*> bombs(engine->getBombs());
Display::get()->drawBombs(bombs);
std::vector<const Engine::Bomber*> bombers(engine->getBombers());
Display::get()->drawBombermen(bombers);
const std::vector<double>& explosions(engine->getExplosions());
Display::get()->drawExplosions(
engine->getMapWidth(), engine->getMapHeight(), explosions);
SDL_Flip(SDL_GetVideoSurface());
}
void Display::drawMapSurface(int width, int height,
const std::vector<Engine::ECell> &map)
{
SDL_Rect blitPos;
blitPos.w = 32;
blitPos.h = 32;
blitPos.x = 0;
blitPos.y = 0;
SDL_Surface *screen = SDL_GetVideoSurface();
int x, y;
for(x = 0; x < width; x++)
{
for(y = 0; y < height; y++)
{
blitPos.x = x * 32;
blitPos.y = y * 32;
switch(map[y * width + x])
{
case Engine::CELL_BRICK:
SDL_BlitSurface(m_pBrickSurface, NULL, screen, &blitPos);
break;
case Engine::CELL_ROCK:
SDL_BlitSurface(m_pRockSurface, NULL, screen, &blitPos);
break;
case Engine::CELL_EMPTY:
SDL_BlitSurface(m_pEmptySurface, NULL, screen, &blitPos);
break;
}
}
}
}
void Display::drawBombermen(std::vector<const Engine::Bomber*> bombers)
{
std::vector<const Engine::Bomber*>::iterator it = bombers.begin();
for(; it != bombers.end(); it++)
{
if((*it)->m_bAlive)
{
// Look how much time passed since the begining of the action to
// deduce the position and the frame of the bomber
double timeElapsed = (getTicks() - (*it)->m_dBeginAction);
int frameDrawed = (int)(timeElapsed*32);
SDL_Rect blitPos;
blitPos.w = 32;
blitPos.h = 32;
blitPos.x = (*it)->m_iPosX*32;// Position the bomber on the map
blitPos.y = (*it)->m_iPosY*32;
SDL_Rect framePos;
framePos.w = 32;
framePos.h = 32;
// Offset the bomber if it is moving; the frame to draw is selected
// depending on elapsed time.
// If it is planting a bomb or is static, we fix it in the cell it's
// in.
switch((*it)->m_eAction)
{
case Engine::ACT_MOV_LEFT:
framePos.x = 32*frameDrawed;
framePos.y = 96;
blitPos.x -= 2*frameDrawed;
break;
case Engine::ACT_MOV_RIGHT:
framePos.x = 32*frameDrawed;
framePos.y = 32;
blitPos.x += 2*frameDrawed;
break;
case Engine::ACT_MOV_UP:
framePos.x = 32*frameDrawed;
framePos.y = 0;
blitPos.y -= 2*frameDrawed;
break;
case Engine::ACT_MOV_DOWN:
framePos.x = 32*frameDrawed;
framePos.y = 64;
blitPos.y += 2*frameDrawed;
break;
default:
framePos.x = 0;
framePos.y = 64;
break;
}
// Check that the frame didn't go beyond the image.
if(framePos.x > 480)
framePos.x = 480;
SDL_BlitSurface(m_pBombermanSurface, &framePos,
SDL_GetVideoSurface(), &blitPos);
}
}
}
void Display::drawBombs(std::vector<const Engine::Bomb*> bombs)
{
std::vector<const Engine::Bomb*>::iterator it = bombs.begin();
for(; it != bombs.end(); it++)
{
// Check the remaining time to get the frame to be drawn
double remainingTime = ((*it)->m_dExplodeDate - getTicks());
int frameDrawed = (int)(remainingTime*0.75);
SDL_Rect blitPos;
blitPos.w = 32;
blitPos.h = 32;
blitPos.x = (*it)->m_iPosX*32; // Position the bomber on the map
blitPos.y = (*it)->m_iPosY*32;
// By default the bomber is motionless
SDL_Rect framePos;
framePos.w = 32;
framePos.h = 32;
framePos.x = 32 * frameDrawed;
framePos.y = 0;
SDL_BlitSurface(m_pBombSurface, &framePos,
SDL_GetVideoSurface(), &blitPos);
}
}
void Display::drawExplosions(int width, int height,
const std::vector<double>& explosions)
{
int x, y;
double now = getTicks();
for(x = 1; x < width - 1; x++)
{
for(y = 1; y < height - 1; y++)
{
SDL_Rect blitPos;
blitPos.x = x*32;
blitPos.y = y*32;
blitPos.w = 32;
blitPos.h = 32;
SDL_Rect framePos;
framePos.x = 32;
framePos.y = 64;
framePos.w = 32;
framePos.h = 32;
// If there's an explosion on the current cell
if(explosions[y*width+x] >= now)
{
// We need to consider adjacent explosions to choose the image
// to display (to choose framePos.x and framePos.y)
bool up = (explosions[(y-1)*width+x] >= now);
bool down = (explosions[(y+1)*width+x] >= now);
bool left = (explosions[y*width+(x-1)] >= now);
bool right = (explosions[y*width+(x+1)] >= now);
if(up && down && left && right)
{
framePos.x = 0;
framePos.y = 64;
}
else if(up && down && right)
{
framePos.x = 32;
framePos.y = 64;
}
else if(down && left && right)
{
framePos.x = 64;
framePos.y = 64;
}
else if(up && down && left)
{
framePos.x = 0;
framePos.y = 96;
}
else if(up && left && right)
{
framePos.x = 32;
framePos.y = 96;
}
else if(up && down)
{
framePos.x = 32;
framePos.y = 32;
}
else if(up)
{
framePos.x = 64;
framePos.y = 32;
}
else if(down)
{
framePos.x = 0;
framePos.y = 32;
}
else if(left && right)
{
framePos.x = 32;
framePos.y = 0;
}
else if(left)
{
framePos.x = 64;
framePos.y = 0;
}
else if(right)
{
framePos.x = 0;
framePos.y = 0;
}
SDL_BlitSurface(m_pBoomSurface, &framePos,
SDL_GetVideoSurface(), &blitPos);
}
}
}
}
Display::~Display()
{
SDL_FreeSurface(m_pBrickSurface);
SDL_FreeSurface(m_pRockSurface);
SDL_FreeSurface(m_pEmptySurface);
SDL_FreeSurface(m_pBombermanSurface);
SDL_FreeSurface(m_pBombSurface);
SDL_FreeSurface(m_pBoomSurface);
SDL_Quit();
}
| true |
d840c16feb1863f4d41de9a25fd92495d3fe83db | C++ | deSigntheClutch/competitive-programming-code-repository | /Codeforces/Gym/2015-2016 Petrozavodsk Winter Training Camp, Makoto rng_58 Soejima Сontest 4/B.cpp | UTF-8 | 1,761 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define debug(x, a, b) for(int (ii)=(a);(ii)<(b);(ii++)) printf("%d: %d\n", ii, x[ii]);
#define mp make_pair
#define pb push_back
#define fi first
#define se second
const int N = 1e5 + 10;
struct edge {
int x, y, cost;
bool operator < (struct edge e) const {
return cost > e.cost;
}
};
vector<edge> edges;
int n;
int x[N], y[N];
pair<int, int> p[N];
int pa[N];
void init() {
for (int i = 1; i <= n; i++) {
pa[i] = i;
}
}
int f(int x) {
if (pa[x] != x) return pa[x] = f(pa[x]);
else return pa[x];
}
int Kruskal() {
sort(edges.begin(), edges.end());
int cnt = 0;
for (edge e : edges) {
int u = f(e.x), v = f(e.y);
if (u != v) {
pa[u] = v;
cnt += 1;
}
if (cnt == n - 1) {
return e.cost;
}
}
}
void add_edge(int x, int y) {
if (x == y) return;
else edges.push_back((edge){x + 1, y + 1, max(abs(p[x].first - p[y].first), abs(p[x].second - p[y].second))});
}
int main() {
scanf("%d", &n);
init();
for (int i = 0; i < n; i++) {
scanf("%d %d", x + i, y + i);
int tx = (x[i] + y[i]);
int ty = (x[i] - y[i]);
p[i] = {tx, ty};
}
sort(p, p + n);
int min_y_id =-1, max_y_id = -1;
int max_val = -2e9 - 10, min_val = 2e9 + 10;
for (int i = 0; i < n; i++) {
if (p[i].second < min_val) min_val = p[i].second, min_y_id = i;
if (p[i].second > max_val) max_val = p[i].second, max_y_id = i;
}
for (int i = 0; i < n; i++) {
add_edge(i, 0);
add_edge(i, n - 1);
add_edge(i, min_y_id);
add_edge(i, max_y_id);
}
printf("%d\n", Kruskal());
return 0;
} | true |
354883ee85e3d0ace33928ee9a471200c065e45f | C++ | ibrahimshiyam/SymphonyIDE | /ide/plugins/interpreter/external-system-template/src/QuoteSenderExample.hpp | UTF-8 | 2,056 | 2.53125 | 3 | [] | no_license | #ifndef CO_SIMULATION_QUOTE_HPP
#define CO_SIMULATION_QUOTE_HPP
#include <iostream>
#include <CoSimulationTransportLayer.hpp>
#include <CoSimulationFramework.hpp>
#include "ExternalSystem.hpp"
namespace ExternalSystem
{
//callback class, will be called by the cosim framework
class QuoteSenderExampleImpl : public CoSimulationFramework::ACoSimulationCallback<>
{
public:
CoSimulationTransportLayer::IChannelEventObject::ChannelEventObjectSet inspect()
{
LOG(std::cout, "QuoteSenderExampleBasicImpl::inspect()");
CoSimulationTransportLayer::IChannelEventObject::ChannelEventObjectSet eventOptions;
eventOptions.push_back(ACoSimulationCallback<>::createSyncEventObject("i"));
eventOptions.push_back(createReadEventObject<std::string>("n"));
eventOptions.push_back(createWriteSyncOnEventObject<std::string>("n", CoSimulationFramework::ChannelOperation::WRITE, b));
return eventOptions;
}
void execute(CoSimulationTransportLayer::IChannelEventObject::ChannelEventObjectSmartPtr evt)
{
LOG(std::cout, "QuoteSenderExampleBasicImpl::execute()");
if (evt->getChannelName() == "i")
{
exitTrue = true;
}
else
{
CoSimulationFramework::ChannelEventObject<std::string>* robj = static_cast<CoSimulationFramework::ChannelEventObject<std::string>*> (evt.get());
std::cout << evt->getChannelName() << " \n" << robj->getOperationType() << "\n" << robj->action.type() << std::endl;
if (robj->action.type() == "SOURCE_NODE")
b = "SINK_NODE";
}
}
bool finished()const
{
LOG(std::cout, "QuoteSenderExampleBasicImpl::finished()");
return exitTrue;
}
void init()
{
LOG(std::cout, "QuoteSenderExampleBasicImpl::init()");
exitTrue = false;
b = "SOURCE_NODE";
}
void deInit()
{
LOG(std::cout, "QuoteSenderExampleBasicImpl::deInit()");
}
private:
bool exitTrue;
std::string b;
};
// create frontend object by using as typedef
typedef CoSimulationFramework::ACoSimulationModel<QuoteSenderExampleImpl> ExternalSystemCoSimulationModel;
}
#endif | true |