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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
96f28068c1632246818d076fa308faec3287802c | C++ | JulianToledano/IntroduccionConcurrencia | /Practica1/Paralelizacion/Division_estatica/Division_estatica.cpp | UTF-8 | 5,780 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "debug_time.h"
#define PROCESADORES 8
typedef struct matriz_t
{
int filas;
int columnas;
int** datos;
} matriz_t;
typedef struct paquete_trabajo{
int **matriz1_datos;
int matriz1_inicial;
int matriz1_final;
int **matriz2_datos;
int matriz2_inicial;
int matriz2_final;
}paquete;
matriz_t mres;
int** crearMatriz(int numFilas, int numColumnas) {
int** matriz =(int**) malloc(sizeof(int*) * numFilas);
int i;
for(i = 0; i < numFilas; i++) {
matriz[i] = (int*) malloc(sizeof(int) * numColumnas);
}
return matriz;
}
int leedato(FILE* fich) {
//Mejor con memoria dinamica
char dato[100];
char datoleido;
int contador = 0;
do {
if(!feof(fich)) {
fread(&datoleido, sizeof(char), 1, fich);
if(datoleido != ' ') {
dato[contador] = datoleido;
contador++;
}
} else datoleido = ' ';
} while(datoleido != ' ');
dato[contador] = '\0';
int datointeger = atoi(dato);
return datointeger;
}
matriz_t leerMatriz(char* nombreFichero, int traspuesta) {
matriz_t matriz;
int numFilas, numColumnas;
FILE* fich = fopen(nombreFichero, "r");
if(fich == NULL) {
printf("Error\n");
exit(0);
}
numFilas = leedato(fich);
numColumnas = leedato(fich);
matriz.datos = crearMatriz(numFilas, numColumnas);
int i, j;
if(!traspuesta) {
for(i = 0; i < numFilas; i++) {
for(j = 0; j < numColumnas; j++) {
matriz.datos[i][j] = leedato(fich);
}
}
} else {
for(i = 0; i < numFilas; i++) {
for(j = 0; j < numColumnas; j++) {
matriz.datos[j][i] = leedato(fich);
}
}
}
matriz.filas = numFilas;
matriz.columnas = numColumnas;
fclose(fich);
return matriz;
}
void escribirMatriz(int** matriz, int numFilas, int numColumnas, char* fileName) {
FILE* fich = fopen(fileName, "w");
if(fich == NULL) {
printf("Error\n");
return;
}
char charaux[100];
sprintf(charaux, "%d %d ", numFilas, numColumnas);
fwrite(charaux, sizeof(char), strlen(charaux), fich);
int i,j;
for(i = 0; i < numFilas; i++) {
for(j = 0; j < numColumnas; j++) {
sprintf(charaux, "%d ", matriz[i][j]);
fwrite(charaux, sizeof(char), strlen(charaux), fich);
}
}
fclose(fich);
}
void printMatrix(matriz_t matrix) {
int i, j;
for(i = 0; i < matrix.filas; i++) {
for(j = 0; j < matrix.columnas; j++) {
printf("%d ", matrix.datos[i][j]);
}
printf("\n");
}
}
// Creacion de un paquete por procesador
// paquete *lista -> lista que se rellena dentro de la finción.
void crear_paquetes(int procesadores, matriz_t m1, matriz_t m2, paquete *lista){
int division = m1.filas / procesadores;
int resto = division + (m1.filas % procesadores);
for(int i = 0; i < procesadores; i++){
lista[i].matriz1_inicial = i * division;
// Si es el último procesador lo sobrecargamos en el caso de que la division no haya sido entera
// ¿?¿? Tal vez mejor poner el final como el total de las filas¿?¿?
if(i == procesadores-1){
lista[i].matriz1_datos = crearMatriz(resto, m1.columnas);
lista[i].matriz1_final = i * division + resto - 1;
}
else{
lista[i].matriz1_datos = crearMatriz(division, m1.columnas);
lista[i].matriz1_final = (i+1) * division - 1;
}
// Rellenamos los datos
for(int j = 0; j < division; j++)
for(int k = 0; k < m1.columnas; k++)
lista[i].matriz1_datos[j][k] = m1.datos[lista[i].matriz1_inicial + j][k];
// Si la división no ha sido entera y es el paquete del último proceso rellenamos los datos
// de la sobrecarga
if(resto && i == procesadores-1)
for(int j = division; j < resto; j++)
for(int k = 0; k < m1.columnas; k++)
lista[i].matriz1_datos[j][k] = m1.datos[lista[i].matriz1_inicial + j][k];
lista[i].matriz2_inicial = 0;
lista[i].matriz2_final = m2.columnas - 1;
lista[i].matriz2_datos = crearMatriz(m2.filas, m2.columnas);
for(int j = 0; j < m2.filas; j++)
for(int k = 0; k < m2.columnas; k++)
lista[i].matriz2_datos[j][k] = m2.datos[j][k];
}
}
void multiplicar_matrices(void *param){
paquete *myparams = (paquete*)param;
int resultado = 0;
for(int i = 0; i <= myparams->matriz1_final - myparams->matriz1_inicial; i++)
for(int j = 0; j <= myparams->matriz2_final; j++){
mres.datos[myparams->matriz1_inicial + i][j] = 0;
for( int k = 0; k <= myparams->matriz2_final; k++)
mres.datos[myparams->matriz1_inicial + i][j] += myparams->matriz1_datos[i][k] * myparams->matriz2_datos[j][k];
}
}
int main(int argc, char** argv) {
/// uso programa: multiplicarMatricesSec <matriz1> <matriz2> <matrizresultado> // Recomendacion una clase matriz
DEBUG_TIME_INIT;
DEBUG_TIME_START;
// cargar datos
matriz_t m1, m2;
m1 = leerMatriz(argv[1], 0);
m2 = leerMatriz(argv[2], 1);
paquete lista[PROCESADORES];
crear_paquetes(PROCESADORES, m1, m2, lista);
// reservar resultado
mres.filas = m1.filas;
mres.columnas = m2.columnas;
mres.datos = crearMatriz(mres.filas, mres.columnas);
pthread_t th[PROCESADORES];
{
DEBUG_TIME_INIT;
DEBUG_TIME_START;
for(int i = 0; i < PROCESADORES; i++)
pthread_create(&(th[i]), NULL, (void * (*)(void *))&multiplicar_matrices, &(lista[i]));
for(int i = 0; i < PROCESADORES; i++)
pthread_join(th[i], NULL);
DEBUG_TIME_END;
DEBUG_PRINT_FINALTIME("Tiempo mutiplicar: ");
}
// Escribir resultado
escribirMatriz(mres.datos, mres.filas, mres.columnas, argv[3]);
// Liberar memoria
for(int i = 0; i < m1.columnas; i++){
free(m1.datos[i]);free(m2.datos[i]);free(mres.datos[i]);
}
free(m1.datos);free(m2.datos);free(mres.datos);
DEBUG_TIME_END;
DEBUG_PRINT_FINALTIME("Tiempo Total: ");
return 0;
}
| true |
ecb2fd49a9bf974feb057023bfacc272d7faeff8 | C++ | abhilc/Competitive-Programming | /spoj/dyzio.cpp | UTF-8 | 414 | 2.65625 | 3 | [] | no_license | #include<iostream>
using namespace std;
string str;
int N, cut_no, pos, maxD, ans;
void solve(int depth)
{
if(str[pos]=='1')cut_no++;
if(depth > maxD)
{
ans = cut_no;
maxD = depth;
}
if(str[pos++]=='1')
{
solve(depth+1);
solve(depth+1);
}
}
int main()
{
int t = 10;
while(t--)
{
cin >> N;
cin >> str;
maxD = 0;
pos = 0;
cut_no = 0;
ans = 0;
solve(1);
cout << ans << "\n";
}
}
| true |
998373b62c6dee7e5af6c23fbf7259ec9508c6c0 | C++ | quigg-caroline/CS32 | /Project1/History.cpp | UTF-8 | 1,047 | 3.265625 | 3 | [] | no_license | //
// History.cpp
// Project 1 - CS32
//
// Created by Caroline Quigg on 1/6/16.
// Copyright © 2016 Caroline Quigg. All rights reserved.
//
#include "History.h"
#include "globals.h"
#include <iostream>
using namespace std;
History::History(int nRows, int nCols)
{
m_nRows=nRows;
m_nCols=nCols;
for (int i = 0 ; i<m_nRows; i++)
{
for (int j=0; j<m_nCols; j++)
{
hist[i][j]='.';
}
}
}
bool History::record(int r, int c)
{
if (r<1 || r>m_nRows || c<1 || c>m_nCols)
{
return false;
}
char& histChar = hist[r-1][c-1];
switch(histChar)
{
case '.':
{
histChar = 'A';
break;
}
case 'Z':
{
break;
}
default:
histChar++;
}
return true;
}
void History::display() const
{
clearScreen();
for (int i =0 ; i<m_nRows;i++)
{
for (int j=0 ; j<m_nCols; j++)
{
cout << hist[i][j];
}
cout <<endl;
}
cout<<endl;
}
| true |
95ae15f6d407f280221696622ce6d4340dae613f | C++ | durgeshak19/Cpp_DS_Algos | /Tree/height_tree.cpp | UTF-8 | 1,280 | 3.671875 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class TreeNode
{
public :
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data){
val = data;
left = NULL;
right = NULL;
}
};
int height(TreeNode* root)
{
int left , right;
if(!root)
return 0;
left = height(root->left);
right = height(root->right);
return max(left,right) + 1;
}
int heightBFS(TreeNode* root)
{
int size = 0;
if(root)
{
TreeNode* temp;
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
while (!q.empty())
{
temp = q.front();
q.pop();
if(temp == NULL)
{
if(!q.empty())
q.push(NULL);
size++;
}
else{
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
}
return size ;
}
int main()
{
TreeNode *root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->left->left = new TreeNode(5);
cout<<heightBFS(root);
} | true |
895819052c28ed3d9b6d82dc2950b72ea0afc2a6 | C++ | frederickmo/DesignPattern-2021 | /Commodity/Commodity.h | UTF-8 | 5,588 | 3.34375 | 3 | [] | no_license | #ifndef _COMMODITY_H_
#define _COMMODITY_H_
#include <string>
#include <list>
#include <iterator>
using std::string;
using std::list;
class Shop;
template<class return_T, class parameter_T> // 设计模式: Command
class Command {
public:
virtual return_T execute(parameter_T) = 0;
};
class CommodityInformation {
protected:
string name, type; // 商品名
int ID; // ID
float price; // 价格
Shop* shop; // 商品拥有者(店铺)
int shopID;
virtual bool Add(CommodityInformation* commodity);
virtual bool Remove(CommodityInformation* commodity);
virtual bool HasCommodity(CommodityInformation* commodity) = 0;
virtual bool Enough(int amount) = 0;
virtual bool Sell(int amount) = 0;
virtual void Display() = 0;
friend class CompositeCommodity;
public:
friend class CommodityInformationReader;
friend class CommodityInformationVipReader;
friend class CommodityInformationSetter;
friend class CommoditySale;
friend class CommodityDisplay;
CommodityInformation(int ID, string name, float price, int shopID);
};
class CommodityInformationReader {
protected:
CommodityInformation* source;
public:
CommodityInformationReader() = default;
CommodityInformationReader(CommodityInformation* info) : source(info) { }
void setCommodityInformation(CommodityInformation* info){
source = info;
}
string getName() { return source->name; }
int getID() { return source->ID; }
string getType() { return source->type; }
virtual float getPrice() { return source->price; }
Shop* getShop() { return source->shop; }
int getShopID(){return source->shopID;}
};
class CommodityInformationVipReader : CommodityInformationReader {
public:
float getPrice() override { return source->price * 0.8; } // vip用户打八折
};
class CommodityInformationSetter {
private:
CommodityInformation* source;
public:
CommodityInformationSetter() = default;
CommodityInformationSetter(CommodityInformation* info) : source(info) { }
void setCommodityInformation(CommodityInformation* info){
source = info;
}
void setName(string name) { source->name = name; }
void setID(int id) { source->ID = id; }
void setType(string type) { source->type = type; }
void setPrice(float price) { source->price = price; }
bool addCommodity(CommodityInformation* commodity) { return source->Add(commodity); }
bool removeCommodity(CommodityInformation* commodity) { return source->Remove(commodity); }
};
class CommoditySale : Command<bool, int> { // 设计模式: command
private:
CommodityInformation* source;
public:
CommoditySale() = default;
CommoditySale(CommodityInformation* info) : source(info) { }
void setCommodityInformation(CommodityInformation* info){
source = info;
}
bool ifEnough(int amount) { return source->Enough(amount); }
virtual bool execute(int amount) { return source->Sell(amount); }
};
class CommodityDisplay : Command<void, void> { // 设计模式: command
private:
CommodityInformation* source;
public:
CommodityDisplay() = default;
CommodityDisplay(CommodityInformation* info) : source(info) { }
void setCommodityInformation(CommodityInformation* info){
source = info;
}
virtual void execute() { source->Display(); }
};
class SingleCommodity : public CommodityInformation { // 设计模式: composite, 桥接模式
protected:
int amount; // 商品库存数量
virtual bool HasCommodity(CommodityInformation* commodity);
public:
SingleCommodity(int ID, string name, float price,int shopID, int amount);
virtual bool Enough(int amount);
virtual bool Sell(int amount);
virtual void Display();
};
class CompositeCommodity; // 设计模式: iterator
class CompositeCommodityIterator : public std::iterator<std::input_iterator_tag, CompositeCommodity> {
protected:
list<CommodityInformation*>::iterator current;
public:
CompositeCommodityIterator(list<CommodityInformation*>::iterator commodity);
CompositeCommodityIterator& operator= (const CompositeCommodityIterator& iter);
bool operator!= (const CompositeCommodityIterator& iter);
bool operator== (const CompositeCommodityIterator& iter);
CompositeCommodityIterator& operator++ ();
CompositeCommodityIterator& operator++ (int);
CommodityInformation& operator* () { return **current; }
};
class CompositeCommodity : public CommodityInformation { // 设计模式: composite
protected:
list<CommodityInformation*> commodity_list;
virtual bool HasCommodity(CommodityInformation* commodity);
public:
CompositeCommodity(int ID, string name, float price, int shopID);
bool Add(CommodityInformation* commodity);
bool Remove(CommodityInformation* commodity);
virtual bool Enough(int amount);
virtual bool Sell(int amount);
virtual void Display();
// 用于Iterator
list<CommodityInformation*>* GetCommodityList() { return &commodity_list; };
CompositeCommodityIterator& begin() {
CompositeCommodityIterator* iter = new CompositeCommodityIterator(commodity_list.begin());
return *iter;
}
CompositeCommodityIterator& end() {
CompositeCommodityIterator* iter = new CompositeCommodityIterator(commodity_list.end());
return *iter;
}
int size() { return commodity_list.size(); }
};
#endif | true |
832271b10b738d475f902c93813efaac7f960257 | C++ | elgrandt/TuxWorld-4 | /presentacion/background.h | UTF-8 | 510 | 2.53125 | 3 | [] | no_license | #ifndef BACKGROUND_H_
#define BACKGROUND_H_
#include "OGL/OGL.h"
class Point{
private:
int x; int y;
int angle;
int speed;
int STOPPER;
int LOOPS;
public:
Point(int X, int Y, int ANGLE, int SPEED);
void update();
int get_x();
int get_y();
};
class Background{
private:
OGL::color_change background;
vector<Point> points;
int LOOPS;
public:
Background();
void update();
};
#endif
| true |
42406897491c4a381a8867f7c803f3fd1b9dc11c | C++ | polyfem/polyfem | /src/polyfem/mesh/mesh3D/Mesh3DStorage.hpp | UTF-8 | 5,327 | 2.796875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vector>
#include <Eigen/Dense>
namespace polyfem
{
namespace mesh
{
struct Vertex
{
int id;
std::vector<double> v;
std::vector<uint32_t> neighbor_vs;
std::vector<uint32_t> neighbor_es;
std::vector<uint32_t> neighbor_fs;
std::vector<uint32_t> neighbor_hs;
bool boundary;
bool boundary_hex;
};
struct Edge
{
int id;
std::vector<uint32_t> vs;
std::vector<uint32_t> neighbor_fs;
std::vector<uint32_t> neighbor_hs;
bool boundary;
bool boundary_hex;
};
struct Face
{
int id;
std::vector<uint32_t> vs;
std::vector<uint32_t> es;
std::vector<uint32_t> neighbor_hs;
bool boundary;
bool boundary_hex;
};
struct Element
{
int id;
std::vector<uint32_t> vs;
std::vector<uint32_t> es;
std::vector<uint32_t> fs;
std::vector<bool> fs_flag;
bool hex = false;
std::vector<double> v_in_Kernel;
};
enum class MeshType
{
TRI = 0,
QUA,
H_SUR,
TET,
HYB,
HEX
};
class Mesh3DStorage
{
public:
MeshType type;
Eigen::MatrixXd points;
std::vector<Vertex> vertices;
std::vector<Edge> edges;
std::vector<Face> faces;
std::vector<Element> elements;
Eigen::MatrixXi EV; // EV(2, ne)
Eigen::MatrixXi FV, FE, FH, FHi; // FV (3, nf), FE(3, nf), FH (2, nf), FHi(2, nf)
Eigen::MatrixXi HV, HF; // HV(4, nh), HE(6, nh), HF(4, nh)
void append(const Mesh3DStorage &other)
{
if (other.type != type)
type = MeshType::HYB;
const int n_v = points.cols();
const int n_e = edges.size();
const int n_f = faces.size();
const int n_c = elements.size();
assert(n_v == vertices.size());
assert(points.rows() == other.points.rows());
points.conservativeResize(points.rows(), n_v + other.points.cols());
points.rightCols(other.points.cols()) = other.points;
for (const auto &v : other.vertices)
{
auto tmp = v;
tmp.id += n_v;
for (auto &e : tmp.neighbor_vs)
e += n_v;
for (auto &e : tmp.neighbor_es)
e += n_e;
for (auto &e : tmp.neighbor_fs)
e += n_f;
for (auto &e : tmp.neighbor_hs)
e += n_c;
vertices.push_back(tmp);
}
assert(points.cols() == vertices.size());
assert(vertices.size() == n_v + other.vertices.size());
for (const auto &e : other.edges)
{
auto tmp = e;
tmp.id += n_e;
for (auto &e : tmp.vs)
e += n_v;
for (auto &e : tmp.neighbor_fs)
e += n_f;
for (auto &e : tmp.neighbor_hs)
e += n_c;
edges.push_back(tmp);
}
assert(edges.size() == n_e + other.edges.size());
for (const auto &f : other.faces)
{
auto tmp = f;
tmp.id += n_f;
for (auto &e : tmp.vs)
e += n_v;
for (auto &e : tmp.es)
e += n_e;
for (auto &e : tmp.neighbor_hs)
e += n_c;
faces.push_back(tmp);
}
assert(faces.size() == n_f + other.faces.size());
for (const auto &c : other.elements)
{
auto tmp = c;
tmp.id += n_c;
for (auto &e : tmp.vs)
e += n_v;
for (auto &e : tmp.es)
e += n_e;
for (auto &e : tmp.fs)
e += n_f;
elements.push_back(tmp);
}
assert(elements.size() == n_c + other.elements.size());
EV.resize(0, 0);
// assert(EV.size() == 0 || EV.rows() == other.EV.rows());
// EV.conservativeResize(std::max(EV.rows(), other.EV.rows()), other.EV.cols() + EV.cols());
// EV.rightCols(other.EV.cols()) = other.EV.array() + n_v;
// //////////////////
FV.resize(0, 0);
// assert(FV.size() == 0 || FV.rows() == other.FV.rows());
// FV.conservativeResize(std::max(FV.rows(), other.FV.rows()), other.FV.cols() + FV.cols());
// FV.rightCols(other.FV.cols()) = other.FV.array() + n_v;
FE.resize(0, 0);
// assert(FE.size() == 0 || FE.rows() == other.FE.rows());
// FE.conservativeResize(std::max(FE.rows(), other.FE.rows()), other.FE.cols() + FE.cols());
// FE.rightCols(other.FE.cols()) = other.FE.array() + n_e;
FH.resize(0, 0);
// assert(FH.size() == 0 || FH.rows() == other.FH.rows());
// FH.conservativeResize(std::max(FH.rows(), other.FH.rows()), other.FH.cols() + FH.cols());
// FH.rightCols(other.FH.cols()) = other.FH.array() + n_c;
FHi.resize(0, 0);
// assert(FHi.size() == 0 || FHi.rows() == other.FHi.rows());
// FHi.conservativeResize(std::max(FHi.rows(), other.FHi.rows()), other.FHi.cols() + FHi.cols());
// FHi.rightCols(other.FHi.cols()) = other.FHi.array();
// /////////////////
HV.resize(0, 0);
// assert(HV.size() == 0 || HV.rows() == other.HV.rows());
// HV.conservativeResize(std::max(HV.rows(), other.HV.rows()), other.HV.cols() + HV.cols());
// HV.rightCols(other.HV.cols()) = other.HV.array() + n_v;
HF.resize(0, 0);
// assert(HF.size() == 0 || HF.rows() == other.HF.rows());
// HF.conservativeResize(std::max(HF.rows(), other.HF.rows()), other.HF.cols() + HF.cols());
// HF.rightCols(other.HF.cols()) = other.HF.array() + n_f;
}
};
struct Mesh_Quality
{
std::string Name;
double min_Jacobian;
double ave_Jacobian;
double deviation_Jacobian;
Eigen::VectorXd V_Js;
Eigen::VectorXd H_Js;
Eigen::VectorXd Num_Js;
int32_t V_num, H_num;
};
} // namespace mesh
} // namespace polyfem
| true |
6dfcf612c8d54cd8797bad4da6f6e6dc7f1e2e0d | C++ | PemchingKue/CSC2100 | /Lab05/Lab05.cpp | UTF-8 | 1,627 | 4.15625 | 4 | [] | no_license | #include <iostream>
using namespace std;
class rectangle
{
public:
rectangle(int len, int wid); //Parameterized Constructor
rectangle(); //Default Constructor; Default lenght is 20 and default width is 10
void setWidth(int newWid); //Mutator function
void setLength(int newLen);//Mutator function
int getWidth() const;//Accessor function
int getLength() const;//Accessor function
void printRectangle(); //Print function
int getArea();//Find Area; hint: Area is width * length
int getPrimeter();//Find Perimeter; hint: Perimeter is (width + length)*2
private:
int length; //variable to store length
int width; //variable to store width
};
//Start your class functions codes from here!
rectangle::rectangle(){
length = 20;
width = 10;
}
rectangle::rectangle(int len, int wid){
len = length;
wid = width;
}
void rectangle::printRectangle(){
cout << "Rectangle: " << "Length = " << length << "Width = " << width;
}
int rectangle::getArea(){
return length * width;
}
int rectangle::getPrimeter(){
return (2 * length) + (2 * width);
}
// Driver program for the rectangle class
int main()
{
rectangle s1;
rectangle s2(5, 20);
rectangle s3;
//Display rectangles
cout << "Rectangle s1 ";
s1.printRectangle();
cout << "Rectangle s2 ";
s2.printRectangle();
cout << "Rectangle s3 ";
s3.printRectangle();
// Test Equality
//Display area and perimeter
cout << "Area of s1=" << s1.getArea() << endl;
cout << "Area of s2=" << s2.getArea() << endl;
cout << "Perimeter of s1=" << s1.getPrimeter() << endl;
cout << "Perimeter of s2=" << s2.getPrimeter() << endl;
return 0;
} | true |
50b9d425026cc2c6c20ae0e87d3984fce8ccb21a | C++ | ashishsalunkhe/Data-Structures-and-Algorithms-Lab | /A12(Searching)c/search.cpp | UTF-8 | 489 | 3.5 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a[20],i,n,element;
int flag=0;
cout<<"\nENTER THE NO. OF ELEMENTS: ";
cin>>n;
cout<<"\nENTER THE ELEMENTS:\n";
for(i=0;i<n;i++)
cin>>a[i];
//for sequential search
cout<<"\nENTER THE ELEMENT TO BE SEARCHED\n";
cin>>element;
for(i=0;i<n;i++)
{
if(a[i]==element)
{
flag=1;
break;
}
}
if(flag==1)
cout<<"\nELEMENT FOUND AT POSITION "<<(i+1)<<endl;
else
cout<<"\nELEMENT NOT FOUND\n";
return 0;
}
| true |
0e05d5a62f8cea27659148ecc75d8267eaed354c | C++ | right-x2/Algorithm_study | /5622.cpp | UTF-8 | 883 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char** argv)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string str;
int sum=0;
cin>>str;
for (int i = 0; i < str.length(); ++i)
{
if(str[i]=='A'||str[i]=='B'||str[i]=='C') sum = sum + 2;
else if(str[i]=='D'||str[i]=='E'||str[i]=='F') sum = sum + 3;
else if(str[i]=='G'||str[i]=='H'||str[i]=='I') sum = sum + 4;
else if(str[i]=='J'||str[i]=='K'||str[i]=='L') sum = sum + 5;
else if(str[i]=='M'||str[i]=='N'||str[i]=='O') sum = sum + 6;
else if(str[i]=='P'||str[i]=='Q'||str[i]=='R'||str[i]=='S') sum = sum + 7;
else if(str[i]=='T'||str[i]=='U'||str[i]=='V') sum = sum + 8;
else if(str[i]=='X'||str[i]=='Y'||str[i]=='Z'||str[i]=='W') sum = sum + 9;
}
cout<<sum+str.length()<<"\n";
return 0;
} | true |
dc765024dbda07b405a59aecdc5d26b54a65e6a0 | C++ | jcliberatol/SICSRepository | /SICS/src/input/Input.cpp | UTF-8 | 3,345 | 3.203125 | 3 | [] | no_license | /*
* input.cpp
*
* Created on: May 27, 2014
* Author: mirt
*/
#include "Input.h"
Input::Input() { del = ','; }
Input::~Input() {}
bool Input::importCSV(char* filename, Matrix<double>& M, int rowIdx, int colIdx)
{
bool eof = false;
int row = 0;
int col = 0;
ifstream inFile;
inFile.open(filename, std::ifstream::in);
if (!inFile.good())
{
cout << "File does not exists:" << filename << endl;
}
// currentLine holds the characters of the current line to read
string currentLine;
// Header lines are ignored
for (int i = 0; i < rowIdx; i++)
{
//cout << "Ignored a header line : " << endl;
getline(inFile, currentLine);
//cout << currentLine << endl;
}
while (!eof)
{
getline(inFile, currentLine);
eof = inFile.eof();
const char* processLine = currentLine.c_str();
if (strlen(processLine) == 0)
{
eof = true;
//cout << "Unproper end of file, read cancelled" << endl;
break;
}
//Clean string of the ignored columns
for (int k = 0; k < colIdx; ++k)
{
processLine = strchr(processLine, del);
processLine = &processLine[1]; //Skip one character
}
/*
* Now we must parse the line into the doubles.
*for this we take the current address and hold it, then we find the next address and hold it , pass the
*double into a string very carefully until the memory addresses are the same
*/
col = 0;
while (strlen(processLine) > 0)
{
char * auxptr;
M(row, col) = strtod(processLine, &auxptr);
col++;
processLine = auxptr;
if (strlen(processLine) > 0)
processLine = &processLine[1];
}
row++;
}
inFile.close();
return (1);
}
/*
* Imports a CSV file whose elements repeat and generally is composed of only zeroes and ones.
*/
bool Input::importCSV(char* filename, PatternMatrix& M, int rowIdx, int colIdx)
{
ifstream inFile;
bool eof;
string currentLine; // currentLine holds the characters of the current line to read
int linelen;
int line;
eof = false;
inFile.open(filename, std::ifstream::in);
if (!inFile.good())
{
cout << "File does not exists:" << filename << endl;
}
// Header lines are ignored
for (int i = 0; i < rowIdx; i++)
getline(inFile, currentLine);
line = 0;
linelen = 0;
while (!eof)
{
int i = 0;
int dlen = 0;
int chars = 0;
getline(inFile, currentLine);
if (line == 0)
linelen = currentLine.length();
else
if (linelen != currentLine.length())
{
//cout << "Inconsistent line length , stopped importing" << endl;
break;
}
line++;
eof = inFile.eof();
const char* processLine = currentLine.c_str();
//Clean string of the ignored columns
for (int k = 0; k < colIdx; ++k)
{
processLine = strchr(processLine, del);
processLine = &processLine[1]; //Skip one character
}
//Count the binary characters
while (processLine[i] != '\0')
{
if (processLine[i] == '0' || processLine[i] == '1')
dlen++;
i++;
}
vector<char> dset(dlen);
M.size = dlen;
i = 0;
chars = 0;
while (processLine[i] != '\0')
{
if (processLine[i] == '0')
chars++;
if (processLine[i] == '1')
{
dset[chars] = true;
chars++;
}
i++;
}
//Bitset is now filled
M.push(dset);
}
inFile.close();
return (0);
}
char Input::getDel() const { return (del); }
void Input::setDel(char del) { this->del = del; }
| true |
774878a6d68766133380268c836dc64a4b353215 | C++ | cmparsons/cs1570-hw10 | /tailor.h | UTF-8 | 4,534 | 3.03125 | 3 | [] | no_license | // Programmer: Christian Parsons
// Section: E
// Filename: town.h
// Assignment: HW #10
// Due Date: 5/3/17
// Purpose: File contains the Tailor class defintion.
#ifndef TAILOR_H
#define TAILOR_H
#include "general.h"
#include "town.h"
#include "phantom_pants.h"
#include <cstring>
class Bully;
class Phantom_Pants;
const short MIN_START_MONEY = 20; //range for tailor's starting funds
const short MAX_START_MONEY = 40;
const short MAX_HEALTH = 100; //range for tailor's health
const short DEAD = 0; //health value corresponding to a dead tailor
const short PANTS_START = 30; //number of pants tailor starts off with
const short SOLD_ALL = 0; //tailor sold all of his/her pants
const short PANTS_PROFIT = 10; //amount of money from selling pair of pants
const short SELL_PANTS_CHANCE = 70; //chance a house will exchange pants
const char DEFAULT_SYM = 'M'; //default representation for tailor in town
const int PRINT_TAILOR_Y = 18; //cooridnates to print tailor on screen
const int PRINT_TAILOR_X = 0;
class Tailor
{
private:
char m_name[NAME];
short m_money; //current funds
char m_symbol; //representation on the town grid
bool m_alive; //dead/alive status
Point m_loc; //location (x, y) in town grid
short m_health; //health points
short m_pants; //number of pants left to sell
// Description: Sell a pair of pants to a house.
// pre: None
// post: The point occupied by the house pants_to_exchange member is set to
// false. Tailor's m_money increases by PANTS_PROFIT and m_pants is
// decreased by one. A message is printed with location of house
// that exchanged pants.
void sell_pants(Town & town, const Point & point);
public:
// Description: Prints the Tailor's status on the screen.
// pre: None
// post: Prints a message on the screen displaying the Tailor's name, alive
// status, location in the town, money, pants left, and health.
friend ostream & operator <<(ostream & out, const Tailor & foo);
// Description: Constructor for the Tailor class.
// pre: None
// post: The Tailor's m_name and m_symbol are set to the passed arguments
// (DEFAULT_SYM by default). m_money is set to random value from
// MIN_START_MONEY to MAX_START_MONEY. m_alive set to true. m_health set
// to MAX_HEALTH. m_pants set to PANTS_START.
Tailor(const char name[], char sym = DEFAULT_SYM);
// Description: Place the Tailor in a random spot in the town.
// pre: Town cannot be completely filled
// post: The Tailor's x and y coordinates are updated to a random spot in the
// town. The Tailor's symbol has been placed in the town at its
// coordinates.
void place_me(Town & town);
// Description: Simulate the Tailor walking through the town.
// pre: Town cannot be completely filled
// post: Randomly chosen spot in town contain's Tailor's m_symbol, and
// Tailor's coordinates are the randomly chosen spot.
void rand_walk(Town & town);
// Description: Set Tailor's health.
// pre: None
// post: The Tailor's health member has been set to the passed argument. If
// Tailors health reaches 0, then m_alive is changed to false.
void set_health(const short health);
// Description: Set the Tailor's money member.
// pre: None
// post: The Tailor's money member has been set to the passed argument.
void set_money(const short money);
// Description: Get the Tailor's location member.
// pre: None
// post: The Tailor's m_loc member has been returned.
Point get_location() const {return m_loc;}
// Description: Get the Tailor's health member.
// pre: None
// post: The Tailor's health member has been returned.
short get_health() const {return m_health;}
// Description: Get the Tailor's money member.
// pre: None
// post: The Tailor's money member has been returned.
float get_money() const {return m_money;}
// Description: Get the Tailor's pants member.
// pre: None
// post: The Tailor's m_pants member has been returned.
char get_pants() const {return m_pants;}
// Description: Tailor interacts with houses or bullies.
// pre: None
// post: Chance of Tailor's money increasing by PANTS_PROFIT per adjacent
// house.
// Chance of Tailor of being placed in new spot in town w/ less money,
// and a pair of Phantom Pants is generated as result of being
// punched by a bully. Or message is output to screen by bully.
void interact(Town & town, Bully Bullies[], Phantom_Pants evil_pants[]);
};
#endif
| true |
6fbb7443248f2f799c6d7fb075b6f69f896d5488 | C++ | S0ul3r/Tanks-SFML | /src/game_level.h | UTF-8 | 4,509 | 3.140625 | 3 | [] | no_license | #ifndef game_level_h
#define game_level_h
#include <SFML/Graphics.hpp>
#include <cmath>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
float shooting_speed = 0.2;
float movement_speed = 1;
//closest wall check
int y_vert = 1;
int x_hor = 2;
int closest_wall = -1;
// for movement
int west = 3;
int east = 4;
int north = 5;
int south = 7;
//convert values
float radian_to_degrees = 360.0 / 6.28;
float pixels_in_sprite = 30.0;
class Borders
{
public:
Borders()
{
}
void set_borders()
{
// Create all barriers for square borders and two horizontal barriers
sf::RectangleShape west(sf::Vector2f(5.0f, 500.0f));
west.setFillColor(sf::Color::White);
west.setPosition(60.0f, 60.0f);
barriers.push_back(west);
vertical_indexes.push_back(0);
sf::RectangleShape south(sf::Vector2f(500.0f, 5.0f));
south.setFillColor(sf::Color::White);
south.setPosition(60.0f, 560.0f);
barriers.push_back(south);
horizontal_indexes.push_back(1);
sf::RectangleShape east(sf::Vector2f(5.0f, 505.0f));
east.setFillColor(sf::Color::White);
east.setPosition(560.0f, 60.0f);
barriers.push_back(east);
vertical_indexes.push_back(2);
sf::RectangleShape north(sf::Vector2f(500.0f, 5.0f));
north.setFillColor(sf::Color::White);
north.setPosition(60.0f, 60.0f);
barriers.push_back(north);
horizontal_indexes.push_back(3);
sf::RectangleShape midNorth(sf::Vector2f(300.0f, 5.0f));
midNorth.setFillColor(sf::Color::White);
midNorth.setPosition(150.0f, 185.0f);
barriers.push_back(midNorth);
horizontal_indexes.push_back(4);
sf::RectangleShape midSouth(sf::Vector2f(300.0f, 5.0f));
midSouth.setFillColor(sf::Color::White);
midSouth.setPosition(150.0f, 400.0f);
barriers.push_back(midSouth);
horizontal_indexes.push_back(5);
}
int getSize()
{
return barriers.size();
}
// Check if object is close enough to wall to turn, return direction if so or -1 if not close enough
int sprite_wall_distance(sf::Vector2f position)
{
float threshold = 30;
int closeness = closest_wall;
for (auto i : vertical_indexes)
{
float temp = position.x - barriers[i].getPosition().x;
if ((abs(temp) < threshold))
{
if (temp < 0)
{
closeness *= east;
}
else
{
closeness *= west;
}
}
}
for (auto i : horizontal_indexes)
{
float temp = position.y - barriers[i].getPosition().y;
if ((abs(temp) < threshold))
{
if (temp < 0)
{
closeness *= south;
}
else
{
closeness *= north;
}
}
}
return abs(closeness);
}
// checks direction of closest_wall wall for dodging Projectles
int check_closeness(sf::Vector2f position, int vert_or_hor)
{
float threshold = 100000;
// which way where the closest wall is
int closeness;
if (vert_or_hor == y_vert)
{
for (auto i : vertical_indexes)
{
if (position.y + (pixels_in_sprite / 2.0) >= barriers[i].getPosition().y
&& position.y + (pixels_in_sprite / 2.0) <= barriers[i].getPosition().y + barriers[i].getSize().y)
{
float temp = position.x - barriers[i].getPosition().x;
if ((abs(temp) < threshold))
{
threshold = abs(temp);
if (temp < 0)
{
closeness = east;
}
else
{
closeness = west;
}
}
}
}
}
else if (vert_or_hor == x_hor)
{
for (auto i : horizontal_indexes)
{
if (position.x + (pixels_in_sprite / 2.0) >= barriers[i].getPosition().x
&& position.x + (pixels_in_sprite / 2.0) <= barriers[i].getPosition().x + barriers[i].getSize().x)
{
float temp = position.y - barriers[i].getPosition().y;
if ((abs(temp) < threshold))
{
threshold = abs(temp);
if (temp < 0)
{
closeness = south;
}
else
{
closeness = north;
}
}
}
}
}
return closeness;
}
//check ghost collision
bool collision(sf::FloatRect main)
{
for (auto i : barriers)
{
if (main.intersects(i.getGlobalBounds()))
{
return true;
}
}
return false;
}
void draw(sf::RenderWindow& window)
{
for (auto i : barriers)
{
window.draw(i);
}
}
private:
static std::vector<sf::RectangleShape> barriers;
static std::vector<int> vertical_indexes;
static std::vector<int> horizontal_indexes;
};
//static vars initialization
std::vector<sf::RectangleShape> Borders::barriers = {};
std::vector<int> Borders::vertical_indexes = {};
std::vector<int> Borders::horizontal_indexes = {};
#endif | true |
4ce4a0e258c74561aada639efb975a5d66147013 | C++ | boeschf/GHEX | /tests/aligned_allocator.cpp | UTF-8 | 2,287 | 2.890625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* GridTools
*
* Copyright (c) 2014-2020, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <ghex/allocator/aligned_allocator_adaptor.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <iostream>
template<std::size_t Alignment, typename T>
void test_std_alloc(int n)
{
using namespace gridtools::ghex;
using alloc_t = std::allocator<T>;
using alloc_other_t = std::allocator<float>;
using aligned_alloc_t = allocator::aligned_allocator_adaptor<alloc_t, Alignment>;
using aligned_alloc_other_t = allocator::aligned_allocator_adaptor<alloc_other_t, Alignment>;
alloc_t alloc;
aligned_alloc_other_t aligned_alloc_other(alloc);
aligned_alloc_t aligned_alloc(std::move(aligned_alloc_other));
auto ptr = aligned_alloc.allocate(n);
EXPECT_TRUE( aligned_alloc_t::offset == ((Alignment<=alignof(std::max_align_t))
? 0u
: (alignof(std::max_align_t) + (Alignment-alignof(std::max_align_t)))));
aligned_alloc.construct(ptr, Alignment);
EXPECT_TRUE(ptr[0] == Alignment);
EXPECT_TRUE((reinterpret_cast<std::uintptr_t>(to_address(ptr)) & std::uintptr_t(Alignment-1u)) == 0u);
for (int i=0; i<n; ++i)
aligned_alloc.destroy(ptr+i);
aligned_alloc.deallocate(ptr,n);
std::vector<T, aligned_alloc_t> vec(n, Alignment, aligned_alloc);
EXPECT_TRUE(vec[0] == Alignment);
EXPECT_TRUE((reinterpret_cast<std::uintptr_t>(&vec[0]) & std::uintptr_t(Alignment-1u)) == 0u);
}
TEST(aligned_allocator, integer)
{
test_std_alloc< 16,int>(1);
test_std_alloc< 32,int>(1);
test_std_alloc< 64,int>(1);
test_std_alloc<128,int>(1);
test_std_alloc< 16,int>(19);
test_std_alloc< 32,int>(19);
test_std_alloc< 64,int>(19);
test_std_alloc<128,int>(19);
}
TEST(aligned_allocator, double_prec)
{
test_std_alloc< 16,double>(1);
test_std_alloc< 32,double>(1);
test_std_alloc< 64,double>(1);
test_std_alloc<128,double>(1);
test_std_alloc< 16,double>(19);
test_std_alloc< 32,double>(19);
test_std_alloc< 64,double>(19);
test_std_alloc<128,double>(19);
}
| true |
3200b318d27a3a26dbc5d7a7d4be243fa25004db | C++ | alonewolfx2/QC2Control | /src/QC2Control.h | UTF-8 | 3,572 | 3.171875 | 3 | [] | no_license | /**
* @file
* @brief A simple Arduino library to set the voltage on a Quick Charge 2.0 charger.
*/
#pragma once
#include "Arduino.h"
/**
* @brief Main class of the QC2Control-library
*
* The QC2Control-class includes all the functions to easily set the voltage of a Quick Charge 2.0 source..
*
* @see setVoltage()
*/
class QC2Control{
public:
/**
* @brief Makes an object to control a Quick Charge 2.0 source.
*
* @details Makes it possible to set the voltage of the QC2.0
* source to 5V, 9V or 12V.) See general description on how to wire it.
*
* @param [in] DpPin Data+ pin
* @param [in] DmPin Data- pin
*/
QC2Control(byte DpPin, byte DmPin);
/**
* @brief Starts the handshake with the QC2.0 source.
*
* @details A handshake is needed to be able to set the voltage. begin() may
* be left out, a calling setVoltage() will call begin() if it's not already.
*
* @see setVoltage(), set5V(), set9V(), set12V()
*/
void begin();
/**
* @brief Sets the desired voltage of the QC2.0 source.
*
* @details Possible voltages are 5V, 9V and 12V. Any other number will result in 5V.
*
* begin() is **blocking code**. It waits for a fixed period counting from the start up of the Arduino to act because the handshake needs a minimum time (1,25s minimum). But this is most likely not a problem because if you need 9V or 12V in your application, there is no gain in proceeding when the voltage isn't there yet (because of the handshake). And by putting begin() (or a call to setVoltage()) at the end of setup() (or other initialization) you can even do stuff while waiting because it counts from Arduino startup.
*
* @note If no handshake has been done (via begin()) with the QC2.0 source the first call to setVoltage() will result in a call to begin() to do the handshake.
*
* @param [in] volt The desired voltage, 5, 9 or 12.
*/
void setVoltage(byte volt);
/**
* @brief Return the current voltage set.
*
* @details This can be 5V, 9V or 12V
*
* @note The library has no notion if the voltage is really set. It just tries to set it but if you just start it all of a QC2.0 source it should set the correct voltage.
*
* @return The current set voltage
*/
byte getVoltage();
/**
* @brief Set voltage to 5V
*
* @return Sets the output of the QC2.0 source to 5V. Short for setVoltage(5).
*
* @see setVoltage()
*/
void set5V();
/**
* @brief Set voltage to 9V
*
* @return Sets the output of the QC2.0 source to 9V. Short for setVoltage(9).
*
* @see setVoltage()
*/
void set9V();
/**
* @brief Set voltage to 12V
*
* @return Sets the output of the QC2.0 source to 12V. Short for setVoltage(12).
*
* @see setVoltage()
*/
void set12V();
protected:
const byte _DpPin; //!< Data+ pin
const byte _DmPin; //!< Data- pin
bool _handshakeDone; //!< Is the handshake done?
byte _setVoltage; //!< Current set voltage
static const unsigned int _WaitTime; //!< Wait time in the handshake. Should be at least 1,25s
};
inline void QC2Control::set5V(){
setVoltage(5);
}
inline void QC2Control::set9V(){
setVoltage(9);
}
inline void QC2Control::set12V(){
setVoltage(12);
}
inline byte QC2Control::getVoltage(){
return _setVoltage;
} | true |
825a4dd43d9ec03158a8501e8d0cf1390858d5a4 | C++ | oujunwei/project_dmoo | /Parameter.h | UTF-8 | 5,723 | 2.8125 | 3 | [] | no_license | /*! \file Parameter.h
\brief EA parameters
\author Aimin ZHOU
\author Department of Computer Science,
\author University of Essex,
\author Colchester, CO4 3SQ, U.K
\author azhou@essex.ac.uk
\date Sep.27 2005 rewrite & reorganize structure
*/
#ifndef AZ_PARAMETER_H
#define AZ_PARAMETER_H
#include <list>
#include <map>
#include <vector>
#include <string>
//!\brief az namespace, the top namespace
namespace az
{
//!\brief mea namespace, the multiobjective evolutionary algorithm namespace
namespace mea
{
#define MAXDOUBLE 1.7E+308 //!< const value
//!\brief evaluator definition
//!\param F objective vector
//!\param E equality constraint vector
//!\param I inequality constraint vector
//!\param X variable vector
//!\return void
typedef void (*EVALUATOR)( std::vector< double >& F,
std::vector< double >& E,
std::vector< double >& I,
std::vector< double >& X);
//!\brief parameter class contains all parameters
class CParameter
{
protected:
bool
mXCoding; //!< coding in decision space
unsigned int
mFSize, //!< objective number
mESize, //!< equality constraint number
mISize; //!< inequality constraint number
double
mPm, //!< probability of mutation
mPc, //!< probability of crossover
mTolX, //!< toleance for X
mTolF, //!< toleance for F
mTolC, //!< toleance for constraints
mETA_SBX, //!< eta for SBX(simulated binary crossover)
mETA_PM, //!< eta for PM(polynomial mutation)
mETA_PCX; //!< eta for PCX(parent-centric recombination)
EVALUATOR
pEvaluator; //!< pointer to the evaluator
std::vector<double>
mVBoundupp, //!< upper bound of variables
mVBoundlow, //!< lower boudn of variables
mVXrealupp, //!< upper bound of variables
mVXreallow; //!< lower boudn of variables
std::string
mProblem; //!< problem name
public:
//!\brief constructor
//!\return void
CParameter() {mXCoding = false;mFSize=0;mESize=0;mISize=0;}
//!\brief get x-coding state
inline bool& XCoding() {return mXCoding;}
//!\brief get probability of mutation
//!\return probability of mutation
inline double& Pm() {return mPm;}
//!\brief get probability of crossover
//!\return probability of crossover
inline double& Pc() {return mPc;}
//!\brief get toleance for X
//!\return toleance for X
inline double& TolX() {return mTolX;}
//!\brief get toleance for F
//!\return toleance for F
inline double& TolF() {return mTolF;}
//!\brief get toleance for constraints
//!\return toleance for constraints
inline double& TolC() {return mTolC;}
//!\brief get eta for SBX
//!\return eta for SBX
inline double& ETA_SBX() {return mETA_SBX;}
//!\brief get eta for PM
//!\return eta for PM
inline double& ETA_PM() {return mETA_PM;}
//!\brief get eta for PCX
//!\return eta for PCX
inline double& ETA_PCX() {return mETA_PCX;}
//!\brief set objective number
//!\param s new objective number
//!\return objective number
inline unsigned int FSize(unsigned int s) {mFSize=s;return s;}
//!\brief get objective number
//!\return objective number
inline unsigned int FSize() {return mFSize;}
//!\brief set variable number
//!\param s new variable number
//!\return variable number
inline unsigned int XSize(unsigned int s) {mVBoundupp.resize(s); mVBoundlow.resize(s); mVXrealupp.resize(s); mVXreallow.resize(s);return s;}
//!\brief get variable number
//!\return variable number
inline unsigned int XSize() {return (unsigned int)mVBoundupp.size(); }
//!\brief set equality constraint number
//!\param s new equality constraint number
//!\return equality constraint number
inline unsigned int ESize(unsigned int s) {mESize=s; return s;}
//!\brief get equality constraint number
//!\return equality constraint number
inline unsigned int ESize() {return mESize;}
//!\brief set inequality constraint number
//!\param s new inequality constraint number
//!\return inequality constraint number
inline unsigned int ISize(unsigned int s) {mISize=s; return s;}
//!\brief get inequality constraint number
//!\return inequality constraint number
inline unsigned int ISize() {return mISize;}
//!\brief get lower bound of i-th variable
//!\param i variable index
//!\return lower bound of i-th variable
inline double& XLow(unsigned int i) {return mVBoundlow[i]; }
//!\brief get upper bound of i-th variable
//!\param i variable index
//!\return upper bound of i-th variable
inline double& XUpp(unsigned int i) {return mVBoundupp[i]; }
//!\brief get lower bound vector
//!\return lower bound
inline std::vector<double>& XLow() {return mVBoundlow; }
//!\brief get upper bound
//!\return upper bound of i-th variable
inline std::vector<double>& XUpp() {return mVBoundupp; }
//!\brief get (real) upper bound of i-th variable
//!\param i variable index
//!\return upper bound of i-th variable
inline double& XRealUpp(unsigned int i) {return mVXrealupp[i]; }
//!\brief get (real) lower bound of i-th variable
//!\param i variable index
//!\return lower bound of i-th variable
inline double& XRealLow(unsigned int i) {return mVXreallow[i]; }
//!\brief set evaluator
//!\param peva pointer to new evaluator
//!\return pointer to new evaluator
inline EVALUATOR Evaluator(EVALUATOR peva) {pEvaluator=peva;return peva;}
//!\brief get evaluator
//!\return pointer to new evaluator
inline EVALUATOR Evaluator() {return pEvaluator;}
//!\brief set problem name
//!\param str new problem name
//!\return problem name
inline std::string& Problem(std::string str) {mProblem=str;return mProblem;}
//!\brief get problem name
//!\return problem name
inline std::string& Problem() {return mProblem;}
}; //class CParameter
} //namespace mea
} //namespace az
#endif //AZ_PARAMETER_H
| true |
eb0da8aa2a6293d7ec77ee4379d6be022970dbed | C++ | podonoghue/usbdm-kinetis | /Firmware/bdm_kinetis_mk22f/Project_Headers/smc.h | UTF-8 | 15,385 | 2.59375 | 3 | [] | no_license | /**
* @file smc.h (180.ARM_Peripherals/Project_Headers/smc.h)
* @brief System Management Controller
*
* @version V4.12.1.210
* @date 13 April 2016
*/
#ifndef HEADER_SMC_H
#define HEADER_SMC_H
/*
* *****************************
* *** DO NOT EDIT THIS FILE ***
* *****************************
*
* This file is generated automatically.
* Any manual changes will be lost.
*/
#include "string.h"
#include "pin_mapping.h"
#include "mcg.h"
namespace USBDM {
/**
* @addtogroup SMC_Group SMC, System Mode Controller
* @brief Abstraction for System Mode Controller
* @{
*/
/**
* Sleep on exit from Interrupt Service Routine (ISR)\n
* This option controls whether the processor re-enters sleep mode when exiting the\n
* handler for the interrupt that awakened it.
*/
enum SmcSleepOnExit {
SmcSleepOnExit_Disabled = 0, //!< Processor does not re-enter SLEEP/DEEPSLEEP mode on completion of interrupt.
SmcSleepOnExit_Enabled = SCB_SCR_SLEEPONEXIT_Msk, //!< Processor re-enters SLEEP/DEEPSLEEP mode on completion of interrupt.
};
/**
* @brief Template class representing the System Mode Controller (SMC)
*
* Partially based on Freescale Application note AN4503\n
* Support for Kinetis Low Power operation.
*
* @image html KinetisPowerModes.png
*/
template <class Info>
class SmcBase_T : public Info {
protected:
/** Hardware instance pointer */
static constexpr HardwarePtr<SMC_Type> smc = Info::baseAddress;
/**
* Enter Stop Mode (STOP, VLPS, LLSx, VLLSx)
* (ARM core DEEPSLEEP mode)
*
* The processor will stop execution and enter the currently configured STOP mode.\n
* Peripherals affected will depend on the stop mode selected.\n
* The stop mode to enter may be set by setStopMode().
* Other options that affect stop mode may be set by setStopOptions().
*
* @note This function is loaded in RAM as stop may power down flash
*/
__attribute__((section(".ram_functions")))
__attribute__((long_call))
__attribute__((noinline))
static void _enterStopMode() {
// Set deep sleep
SCB->SCR = SCB->SCR | SCB_SCR_SLEEPDEEP_Msk;
(void)SCB->SCR;
__DSB();
__WFI();
__ISB();
}
public:
/**
* Get name from SMC status e.g. RUN, VLPR, HSRUN
*
* @param status
*
* @return Pointer to static string
*/
static const char *getSmcStatusName(SmcStatus status) {
#ifdef SMC_PMPROT_AHSRUN
if (status == SmcStatus_HSRUN) {
return "HSRUN";
}
#endif
if (status == SmcStatus_RUN) {
return "RUN";
}
if (status == SmcStatus_VLPR) {
return "VLPR";
}
return "Impossible while running!";
}
/**
* Get name for current SMC status e.g. RUN, VLPR, HSRUN
*
* @return Pointer to static string
*/
static const char *getSmcStatusName() {
return getSmcStatusName(Info::getStatus());
}
/**
* Basic enable of SMC\n
* Includes configuring all pins
*/
static __attribute__((always_inline)) void enable() {
// No clock or pins
}
/**
* Enter Stop Mode (STOP, VLPS, LLSx, VLLSx)
* (ARM core DEEPSLEEP mode)
*
* The processor will stop execution and enter the given STOP mode.\n
* Peripherals affected will depend on the stop mode selected.
*
* @param[in] smcStopMode Stop mode to set. This will become the default STOP mode.
*
* @return E_NO_ERROR Processor entered STOP
* @return E_INTERRUPTED Processor failed to enter STOP mode due to interrupt
*/
static ErrorCode enterStopMode(SmcStopMode smcStopMode) {
Info::setStopMode(smcStopMode);
return enterStopMode();
}
/**
* Enter Stop Mode (STOP, VLPS, LLSx, VLLSx) with the current STOP settings
* (ARM core DEEPSLEEP mode)
*
* The processor will stop execution and enter the given STOP mode.\n
* Peripherals affected will depend on the stop mode selected.
*
*
* @return E_NO_ERROR Processor entered STOP
* @return E_INTERRUPTED Processor failed to enter STOP mode due to interrupt
*/
static ErrorCode enterStopMode() {
/*
* Actions required before entry to STOP modes
*/
// Save current Flash Bank0 settings
FmcInfo::FlashBank0Init savedFlashBank0Settings;
savedFlashBank0Settings.readConfig();
// Disable Flash Bank0 prefetch
FmcInfo::setFlashBank0Speculation(FmcFlashSpeculation_Disabled);
// Save current Flash Bank1 settings
FmcInfo::FlashBank1Init savedFlashBank1Settings;
savedFlashBank1Settings.readConfig();
// Disable Flash Bank1 prefetch
FmcInfo::setFlashBank1Speculation(FmcFlashSpeculation_Disabled);
_enterStopMode();
/*
* Actions required after exit from STOP modes
*/
// Restore flash Bank0 settings
savedFlashBank0Settings.configure();
// Restore flash Bank1 settings
savedFlashBank1Settings.configure();
return (smc->PMCTRL & SMC_PMCTRL_STOPA_MASK)?E_INTERRUPTED:E_NO_ERROR;
}
/**
* Enter Stop Mode (STOP, VLPS, LLSx, VLLSx) with given STOP settings
* (ARM core DEEPSLEEP mode)
*
* The processor will stop execution and enter the given STOP mode.\n
* Peripherals affected will depend on the stop mode selected.
*
* @param smcInit Settings to apply before entering STOP mode
*
* @return E_NO_ERROR Processor entered STOP
* @return E_INTERRUPTED Processor failed to enter STOP mode due to interrupt
*/
static ErrorCode enterStopMode(typename Info::Init smcInit) {
smcInit.setOptions();
return enterStopMode();
}
/**
* Enter Wait Mode (WAIT, VLPW)\n
* (ARM core SLEEP mode)
*
* The processor will stop execution and enter WAIT/VLPW mode.\n
* This function can be used to enter normal WAIT mode or VLPW mode
* depending upon current run mode.\n
* In wait mode the core clock is disabled (no code executing),
* but bus clocks are enabled (peripheral modules are operational).
*
* Possible power mode transitions:
* - RUN -> WAIT
* - VLPR -> VLPW
*
* WAIT mode is exited using any enabled interrupt or RESET.
*
* For Kinetis K:
* If in VLPW mode, the statue of the SMC_PMCTRL[LPWUI] bit
* determines if the processor exits to VLPR or RUN mode.\n
* Use setExitVeryLowPowerOnInterrupt() to modify this action.
*
* For Kinetis L:
* LPWUI does not exist.\n
* Exits with an interrupt from VLPW will always be back to VLPR.\n
* Exits from an interrupt from WAIT will always be back to RUN.
*
* @note Some modules include a programmable option to disable them in wait mode.\n
* If those modules are programmed to disable in wait mode, they will not be able to
* generate interrupts to wake the core.
*/
static void enterWaitMode() {
SCB->SCR = SCB->SCR & ~SCB_SCR_SLEEPDEEP_Msk;
// Make sure write completes
(void)(SCB->SCR);
__asm volatile( "dsb" ::: "memory" );
__asm volatile( "wfi" );
__asm volatile( "isb" );
}
/**
* Set Sleep-on-exit action
*
* If enabled, when the processor completes the execution of all exception handlers it
* returns to Thread mode and immediately enters WAIT/STOP mode (ARM core SLEEP/DEEPSLEEP mode).\n
* Use this mechanism in applications that only require the processor to run when
* an exception occurs.
*
* @param[in] smcSleepOnExit Determines action on completion of all exception handlers
*/
static void setSleepOnExit(SmcSleepOnExit smcSleepOnExit=SmcSleepOnExit_Enabled) {
if (smcSleepOnExit) {
SCB->SCR = SCB->SCR | SCB_SCR_SLEEPONEXIT_Msk;
}
else {
SCB->SCR = SCB->SCR & ~SCB_SCR_SLEEPONEXIT_Msk;
}
// Make sure write completes
(void)(SCB->SCR);
}
/**
* Enter Run Mode.
*
* This may be used to change between supported RUN modes (RUN, VLPR, HSRUN).
* Only the following transitions are allowed: VLPR <-> RUN <-> HSRUN.
*
* @param[in] clockConfig Clock configuration (Includes run mode to enter)
*
* @return E_NO_ERROR No error
* @return E_CLOCK_INIT_FAILED Clock transition failure
* @return E_ILLEGAL_POWER_TRANSITION Cannot transition to smcRunMode from current run mode
*/
static ErrorCode enterRunMode(ClockConfig clockConfig) {
SmcRunMode smcRunMode = Mcg::clockInfo[clockConfig].runMode;
ErrorCode rc = E_NO_ERROR;
/*
* Transition Change clock configuration
* HSRUN->RUN Before
* VLPR->RUN After
* RUN->HSRUN After
* RUN->VLPR Before
*/
auto smcStatus = Info::getStatus();
bool changeBefore = (smcStatus == SmcStatus_HSRUN);
switch(smcRunMode) {
case SmcRunMode_Normal:
if (changeBefore) {
// Change clock mode
rc = Mcg::clockTransition(Mcg::clockInfo[clockConfig]);
if (rc != E_NO_ERROR) {
break;
}
}
// Change power mode
SMC->PMCTRL = (SMC->PMCTRL&~SMC_PMCTRL_RUNM_MASK)|smcRunMode;
// Wait for power status to change
while (Info::getStatus() != SmcStatus_RUN) {
__asm__("nop");
}
if (!changeBefore) {
// Change clock mode
rc = Mcg::clockTransition(Mcg::clockInfo[clockConfig]);
}
break;
case SmcRunMode_HighSpeed:
if (smcStatus != SmcStatus_RUN) {
// Can only transition from RUN mode
return setErrorCode(E_ILLEGAL_POWER_TRANSITION);
}
// Change power mode
SMC->PMCTRL = (SMC->PMCTRL&~SMC_PMCTRL_RUNM_MASK)|smcRunMode;
// Wait for power status to change
while (Info::getStatus() != SmcStatus_HSRUN) {
__asm__("nop");
}
rc = Mcg::clockTransition(Mcg::clockInfo[clockConfig]);
break;
case SmcRunMode_VeryLowPower:
if (smcStatus != SmcStatus_RUN) {
// Can only transition from RUN mode
return setErrorCode(E_ILLEGAL_POWER_TRANSITION);
}
// Change clock mode
rc = Mcg::clockTransition(Mcg::clockInfo[clockConfig]);
if (rc != E_NO_ERROR) {
break;
}
// Change power mode
SMC->PMCTRL = (SMC->PMCTRL&~SMC_PMCTRL_RUNM_MASK)|smcRunMode;
// Wait for power status to change
while (Info::getStatus() != SmcStatus_VLPR) {
__asm__("nop");
}
break;
default:
return setErrorCode(E_ILLEGAL_PARAM);
}
return rc;
}
/**
* Change power mode.
*
* @note Note this method does not affect advanced STOP options such as PORPO and RAM2PO
* These should be set beforehand.
*
* @param smcPowerMode Power mode to change to (apart from SmcPowerMode_RUN/VLPR/HSRUN)
*
* @return E_NOERROR Success
* @return E_ILLEGAL_PARAM Cannot enter RUN or VLPR using this method (use enterRunMode())
* @return E_ILLEGAL_POWER_TRANSITION It is not possible to transition directly to the given power mode
* @return E_INTERRUPTED Processor failed to change mode due to interrupt
*/
static ErrorCode enterPowerMode(SmcPowerMode smcPowerMode) {
switch(smcPowerMode) {
// Transition refers to Figure 15-5. Power mode state diagram in MK22F Manual (K22P121M120SF7RM)
case SmcPowerMode_RUN : // (VLPR,HSRUN)->RUN Transition 3,12
case SmcPowerMode_VLPR : // RUN->VLPR Transition 3
case SmcPowerMode_HSRUN : // RUN->HSRUN Transition 12
// Clock changes needed etc. Use enterRunMode()
return E_ILLEGAL_PARAM;
case SmcPowerMode_VLPW : // VLPR->VLPW Transition 4
// Check if in correct run mode
if (SmcRunMode_VeryLowPower != (SMC->PMCTRL&SMC_PMCTRL_RUNM_MASK)) {
return setErrorCode(E_ILLEGAL_POWER_TRANSITION);
}
[[fallthrough]];
case SmcPowerMode_WAIT : // (RUN,VLPR)->VLPW Transition 1,4
enterWaitMode();
return E_NO_ERROR;
break;
case SmcPowerMode_NormalSTOP : // RUN->STOP Transition 2a
case SmcPowerMode_PartialSTOP1 : // RUN->STOP Transition 2b
case SmcPowerMode_PartialSTOP2 : // RUN->STOP Transition 2c
// Check if in correct run mode
if (SmcRunMode_Normal != (SMC->PMCTRL&SMC_PMCTRL_RUNM_MASK)) {
return E_ILLEGAL_POWER_TRANSITION;
}
[[fallthrough]];
case SmcPowerMode_VLPS : // (RUN,VLPR)->VLPS Transition 7,6
case SmcPowerMode_LLS2 : // (RUN,VLPR)->LLS2 Transition 10a,11a
case SmcPowerMode_LLS3 : // (RUN,VLPR)->LLS3 Transition 10b,11b
case SmcPowerMode_VLLS0 : // (RUN,VLPR)->VLLS0 Transition 8a,9a
case SmcPowerMode_VLLS1 : // (RUN,VLPR)->VLLS1 Transition 8b,9b
case SmcPowerMode_VLLS2 : // (RUN,VLPR)->VLLS2/LLS2 Transition 8c,9c
case SmcPowerMode_VLLS3 : // (RUN,VLPR)->VLLS3/LLS3 Transition 8d,9d
// Check if in allowable run modes
if (SmcRunMode_HighSpeed == (SMC->PMCTRL&SMC_PMCTRL_RUNM_MASK)) {
return E_ILLEGAL_POWER_TRANSITION;
}
// Set partial_stop and (v)lls options
smc->STOPCTRL = (smc->STOPCTRL&~(SMC_STOPCTRL_PSTOPO_MASK|SMC_STOPCTRL_VLLSM_MASK))|(smcPowerMode>>8);
return enterStopMode((SmcStopMode)(smcPowerMode&SMC_PMCTRL_STOPM_MASK));
}
return setErrorCode(E_ILLEGAL_POWER_TRANSITION);
}
/**
* Default value for Smc::Init
* This value is created from Configure.usbdmProject settings (Peripheral Parameters->SMC)
*/
static constexpr SmcInfo::Init DefaultInitValue {
SmcAllowHighSpeedRun_Enabled , // Allow High Speed Run mode - HSRUN is allowed
SmcAllowVeryLowPower_Enabled , // Allow very low power modes - VLPR, VLPW and VLPS are allowed
SmcAllowLowLeakageStop_Disabled , // Allow low leakage stop mode - LLS is not allowed
SmcAllowVeryLowLeakageStop_Enabled , // Allow very low leakage stop mode - VLLSx is allowed
SmcStopMode_NormalStop , // Stop Mode Control - Normal Stop (STOP)
SmcPartialStopMode_Normal , // Partial Stop Mode - STOP - Normal Stop mode
SmcPowerOnResetInVlls0_Enabled , // Power-On_Reset Detection in VLLS0 mode - POR detect circuit is enabled in VLLS0
SmcLowLeakageStopMode_VLLS3, // Low Leakage Mode Control - Enter VLLS3/LLS3 in VLLSx/LLSx mode
};
/**
* Configure with settings from <b>Configure.usbdmProject</b>.
*/
static void defaultConfigure() {
DefaultInitValue.initialise();
}
};
/**
* Class representing SMC
*/
class Smc : public SmcBase_T<SmcInfo> {};
/**
* End SMC_Group
* @}
*/
} // End namespace USBDM
#endif /* HEADER_SMC_H */
| true |
bc04bc42e0e9c61bb21d02c6ddf30ba915fa099e | C++ | huangdanfeng0214/PAT | /1006.cpp | GB18030 | 1,559 | 3.734375 | 4 | [] | no_license | /**
ҾȻһֱû 12,.,n ˼Ϊ12βǴ1n
ѧ˼άһû
stoi ,to_string C++11
stringappend
*/
#include <iostream>
#include <string>
#include <set>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
cin >> str;
int ln;
if (str.length() == 2) {
str = "0" + str; ln = 10;
}
else if (str.length() == 1) {
str = "00" + str; ln = 10;
}
else if (str.length() == 3) {
ln = 100;
}
// cout<<"str:"<<str<<"; ";
// cout<<"ln:"<<ln<<"; ";
string ans;
int bai = stoi(str.substr(0, 1)); //cout<<"bai:"<<bai<<"; ";
int shi = stoi(str.substr(1, 1)); //cout<<"shi:"<<shi<<"; ";
int ge = stoi(str.substr(2.1)); //cout<<"ge:"<<ge<<"; ";
ans.append(bai, 'B');
ans.append(shi, 'S');
for (int i = 1; i <= ge; i++) {
ans.append(to_string(i));
}
cout << ans;
return 0;
}
/**
1006 ʽ (15)
ĸ B ʾ١ĸ S ʾʮ 12...n ʾΪĸλ n<10ʽһ 3 λ 234 ӦñΪ BBSSS1234Ϊ 2 ١3 ʮԼλ 4
ʽ
ÿ 1 n<1000
ʽ
ÿռһУù涨ĸʽ n
1
234
1
BBSSS1234
2
23
2
SS123
*/ | true |
3db475d52a47f34d92195fdeb6df18fbb4a703f1 | C++ | murolo/rdc | /src/io/memory_io.cc | UTF-8 | 2,442 | 3.046875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "io/memory_io.h"
namespace rdc {
MemoryFixedSizeStream::MemoryFixedSizeStream(void *p_buffer, size_t buffer_size)
: p_buffer_(reinterpret_cast<char *>(p_buffer)), buffer_size_(buffer_size) {
curr_ptr_ = 0;
}
MemoryFixedSizeStream::~MemoryFixedSizeStream(void) {
}
size_t MemoryFixedSizeStream::Read(void *ptr, size_t size) {
CHECK_F(curr_ptr_ + size <= buffer_size_,
"read can not have position excceed buffer length");
size_t nread = std::min(buffer_size_ - curr_ptr_, size);
if (nread != 0)
std::memcpy(ptr, p_buffer_ + curr_ptr_, nread);
curr_ptr_ += nread;
return nread;
}
void MemoryFixedSizeStream::Write(const void *ptr, size_t size) {
if (size == 0)
return;
CHECK_F(curr_ptr_ + size <= buffer_size_,
"write position exceed fixed buffer size");
std::memcpy(p_buffer_ + curr_ptr_, ptr, size);
curr_ptr_ += size;
}
void MemoryFixedSizeStream::Seek(size_t pos) {
curr_ptr_ = static_cast<size_t>(pos);
}
size_t MemoryFixedSizeStream::Tell() {
return curr_ptr_;
}
bool MemoryFixedSizeStream::AtEnd() const {
return curr_ptr_ == buffer_size_;
}
void* MemoryFixedSizeStream::inner_buffer() const {
return p_buffer_;
}
size_t MemoryFixedSizeStream::inner_buffer_size() const {
return buffer_size_;
}
MemoryUnfixedSizeStream::MemoryUnfixedSizeStream(std::string *p_buffer)
: p_buffer_(p_buffer) {
curr_ptr_ = 0;
}
MemoryUnfixedSizeStream::~MemoryUnfixedSizeStream(void) {
}
size_t MemoryUnfixedSizeStream::Read(void *ptr, size_t size) {
CHECK_F(curr_ptr_ <= p_buffer_->length(),
"read can not have position excceed buffer length");
size_t nread = std::min(p_buffer_->length() - curr_ptr_, size);
if (nread != 0)
std::memcpy(ptr, &(*p_buffer_)[0] + curr_ptr_, nread);
curr_ptr_ += nread;
return nread;
}
void MemoryUnfixedSizeStream::Write(const void *ptr, size_t size) {
if (size == 0)
return;
if (curr_ptr_ + size > p_buffer_->length()) {
p_buffer_->resize(curr_ptr_ + size);
}
std::memcpy(&(*p_buffer_)[0] + curr_ptr_, ptr, size);
curr_ptr_ += size;
}
void MemoryUnfixedSizeStream::Seek(size_t pos) {
curr_ptr_ = static_cast<size_t>(pos);
}
size_t MemoryUnfixedSizeStream::Tell(void) {
return curr_ptr_;
}
bool MemoryUnfixedSizeStream::AtEnd(void) const {
return curr_ptr_ == p_buffer_->length();
}
} // namespace rdc
| true |
09d57fc86041e589e020744b09cf53d968df534f | C++ | marcinmajkowski/SPOJ | /PP0502B.cpp | UTF-8 | 328 | 2.875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void)
{
int t, n, i, k;
int d[100];
int *ptr;
int *ptr2;
cin >> t;
for (i = 0; i < t; ++i)
{
cin >> n;
ptr = d;
ptr2 = d + n;
while (ptr != ptr2)
cin >> *ptr++;
--ptr;
while (ptr + 1 != d)
cout << *ptr-- << " ";
cout << endl;
}
return 0;
}
| true |
39c0d976820c910e099f99aa29503ea7030a2692 | C++ | jade200019/cdproject | /Patch.h | UTF-8 | 6,995 | 2.53125 | 3 | [] | no_license | //
// Created by jade on 2/27/19.
//
#ifndef TRYENV_PATCH_H
#define TRYENV_PATCH_H
#include "Config.h"
#include "RotatedRectm.h"
class Patch {
Mat im;
Mat grad_x, grad_y;
Mat grad_rho, grad_theta;
int histSize = 256; // number of bins, theta_hist size: 256 x 1
Mat theta_hist;
Mat top_k_index;
Mat top_theta_mask;
// k-means
int k;
Mat kLabels, kCenters;
Mat kClosestColorMask;
Point3f kClosestColorMaskColor; // BGR color
Mat kMeansSeg; // optional, saved for display purpose
vector<RotatedRectm> vecRRect; // Rotated min area rectangle
// contour
Mat kClosestColorMaskContour; // optional, saved for display purpose
// REQUIRES: a rRect, and width of the desired ROI for canny
// EFFECTS: return a ROI for canny, using pts[0] and pts[3]
RotatedRect getRRect03(RotatedRectm & rRect, float cannyROIWidth);
// REQUIRES: a rRect, and width of the desired ROI for canny
// EFFECTS: return a ROI for canny, using pts[1] and pts[2]
RotatedRect getRRect12(RotatedRectm & rRect, float cannyROIWidth);
// REQUIRES: the source matrix, and a rotated rectangle ROI
// EFFECTS: return the cropped area
Mat extractRotatedrectArea(const Mat & src, RotatedRect rect);
// REQUIRES: a slice (rotated rectangle ROI) of canny edges
// EFFECTS: maximum canny edge "arc length" (i.e. area of one connected component in canny edges)
float findMaxLenCannySlice(const Mat & cannySlice);
// REQUIRES: a triangle, start pixel of the patch
// EFFECTS: if all points are on the boundary of the patch, and if they can form a right angle, return the index
// of the vertex of the right angle
// if any of the two conditions cannot be satisfied, return -1
int check_on_boundary_and_corner(int x_pixel, int y_pixel, const vector<Point2f> & triangle);
float getCosOfVector(Point2f A1, Point2f A2, Point2f B1, Point2f B2);
// REQUIRES: a triangle
// EFFECTS: return the area of it
float triangle_area(const vector<Point2f> & triangle);
// REQUIRES: AB is a straight line, M is a point outside it
// EFFECTS: return the projection of M on the line AB
Point2f point_to_line_projection(Point2f & A, Point2f & B, Point2f & M);
public:
int x, y; // Patch position in the original image, by index, start from 0
int x_pixel, y_pixel; // Patch position by pixel in the original image, start from 0
Patch(Mat patch) {
im = patch.clone();
}
Patch(const Mat & patch, int X, int Y, bool shifted = false) : im(patch.clone()), x(X), y(Y), k(3) {
if (!shifted){ // for not shifted patches
x_pixel = X * PATCHX;
y_pixel = Y * PATCHY;
}
else { // for patches shifted by half of the size in both direction
x_pixel = X * PATCHX + PATCHX / 2;
y_pixel = Y * PATCHY + PATCHY / 2;
}
}
// Mat can deallocate its own memory
~Patch() = default;
Mat getIm() const { return this->im; }
// REQUIRES: member im
// EFFECTS: Return the abs value of Sobel gradient
// EFFECTS: Save results to member grad_x, grad_y
Mat getSobelGradient();
// REQUIRES: member grad_x, grad_y
// EFFECTS: member grad_rho, grad_theta
void getGradPolarCoordinate();
// REQUIRES: this->grad_theta, argument mask represent the counted elements
// by default, a mask is not used
// EFFECTS: return histogram in this->theta_hist
// default argument only defined once in .h file, not in .cpp file
Mat getGradThetaHist(Mat mask = Mat(), int magThreshold = 0);
// REQUIRES: this->theta_hist, argument int k
// EFFECTS: get top k-ranked theta orientation, return bin index, size k x 1
Mat getGradThetaHistTopK(int k);
// REQUIRES: this->grad_theta, argument Mat bin_index
// EFFECTS: this->top_theta_mask, plot according to the given theta bin
Mat ThetaHistBin2Mask(Mat bin_index);
// REQUIRES: argument threshold on gradient magnitude
// EFFECTS: return a mask representing large enough gradient magnitude
// Mat thresholdGradMag(int threshold);
// REQUIRES: this->im is a BGR image, CV_8UC3
// EFFECTS: k-means segmentation, save to this->kLabels, this->kCenters, this->kMeansSeg
// return this->kMeansSeg
Mat kMeans(int K);
// REQUIRES: this->kLabels, this->kCenters, Vec3f RefBGR[]
// EFFECTS: this->closestColorMask, choose the closest kCenter color to one of RefBGR[],
// and it should be in the margin
Mat closeBGRMask(const int margin, const vector<Vec3f> & vecRefBGR);
// REQUIRES: this->kLabels, this->kCenters, & vecRefBGR
// EFFECTS: choose in range mask, according to k-centers, not pixels
Mat BGRInRangeMask(const int margin, const vector<Vec3f> & vecRefBGR);
// REQUIRES: this->closestColorMask, 8UC1
// EFFECTS: return it, later as a function variable to assemble back an image to display
Mat getClosestColorMask() const { return this->kClosestColorMask; }
// REQUIRES: this->kClosestColorMaskColor
// EFFECTS: return it
Point3f getkClosestColorMaskColor() const { return this->kClosestColorMaskColor; }
// REQUIRES: this->kMeansSeg, 8U3C
// EFFECTS: return it
Mat getKMeansSeg() const {return this->kMeansSeg; }
// REQUIRES: this->closestColorMask, better not using this->kMeansSeg
// EFFECTS: find contour
Mat closestBGRMaskContour();
// REQUIRES: this->kClosestColorMaskContour, 8U3C
// EFFECTS: return it
Mat getkClosestColorMaskContour() const { return this->kClosestColorMaskContour; }
// REQUIRES: this->closestColorMask; info about size of the image: imRows, imCols; size filter for each connected
// components: minAreaPercentage, maxAreaPercentage, ranging from 0.0 to 1.0
// EFFECTS: find connected components, filter with size, pad with 0, find minAreaRect, save the Rect
// save to this->vecRRect
vector<RotatedRectm> & findCompMinAreaRectImageLevel(int imRows, int imCols, float minAreaPer = 0.0, float maxAreaPer = 1.0, float minConfidence = 0.0);
// REQUIRES: this->vecRRect
// EFFECTS: return its reference
vector<RotatedRectm> & getVecRRect() { return this->vecRRect; }
// REQUIRES: this->closestColorMask; info about size of the image: imRows, imCols;
// canny edges of the entire image: canny
// min area percentage of the connected component in a mask over fitted rotated rectangle: minAreaPercentage
// max relative deviation of the width of the rRect compared to the reference: maxWidthDev
// EFFECTS: this->vecRRect
vector<RotatedRectm> & findMinAreaRect(int imRows, int imCols, Mat & canny, vector<float> & vecRefWidth,
float minRectWidth = 0.0, float minRectLength = 0.0,
float minAreaPercentage = 0.0, float maxWidthDev = 10.0,
float minCannyLeftConf = 0.0, float minCannyRightConf = 0.0, float minConfidence = 0.0);
};
#endif //TRYENV_PATCH_H
| true |
37454755f7cc909362d3a08251d67d8d31f4bcd8 | C++ | robertcoco/miercoles | /strcut.cpp | UTF-8 | 913 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
struct carros{
char marca[40];
int precio;
}carro1,carro2;
int main(){
cout<<"introduce la marca del auto numero: ";
cin.getline(carro2.marca,40,'\n');
cout<<"introduce la el precio de auto numero2: ";
cin>>carro2.precio;
cout<<"introduce la marca del auto numero1: ";
cin.getline(carro1.marca,40,'\n');
cin.getline(carro1.marca,40,'\n');
cout<<"introduce la el precio de auto numero1: ";
cin>>carro1.precio;
cout<<endl;
cout<<"imprimiendo datos de los autos"<<endl;
cout<<"este es el nombre del carro numero1: "<<carro1.marca<<endl;
cout<<"este es el precio del carro numero1: "<<carro1.precio<<endl;
cout<<"\neste es el nombre del carro numero2: "<<carro2.marca<<endl;
cout<<"este es el precio del carro numero2: "<<carro2.precio<<endl;
getch();
return 0;
} cin.getline(carro1.marca,40,'\n');
| true |
6e815c56f81b3c3e7d07f7a0a9565799df46bca1 | C++ | greatlse/TURTLE | /gamess-gpu/diesel/lib/Math/etc/BinomialCoefficient.h | UTF-8 | 911 | 2.609375 | 3 | [] | no_license | //***********************************************************************
//
// Name: BinomialCoefficient.h
//
// Description:
//
// Author: Michael Hanrath
//
// Version: 0.0
//
// Date: 07.08.1996
//
//
//
//
//***********************************************************************
#ifndef __BINOMIALCOEFFICIENT_H
#define __BINOMIALCOEFFICIENT_H
#include "../../../config.h"
class BinomialCoefficient {
public:
BinomialCoefficient(INT maxN);
~BinomialCoefficient();
//----------------------------------------------------------------------
INT get(INT n, INT k) const;
//----------------------------------------------------------------------
private:
void set(INT n, INT k, INT noverk);
INT *p;
INT maxN;
};
inline
INT BinomialCoefficient::get(INT n, INT k) const
{ return p[n*maxN + k]; }
inline
void BinomialCoefficient::set(INT n, INT k, INT noverk)
{ p[n*maxN + k] = noverk; }
#endif
| true |
ec0ecb63f2a6a998c3d511b5b804e5d7c15e18b1 | C++ | zencher/algorithms_gym | /leetcode/src/leetcode0092.cpp | UTF-8 | 1,282 | 3.484375 | 3 | [] | no_license | // leetcode092.cpp
//
#include <stack>
#include <queue>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *reverseBetween( ListNode *head, int m, int n )
{
int index = 0;
ListNode * tmp = head;
queue<ListNode*> q;
stack<ListNode*> s;
while ( tmp )
{
index++;
if ( m <= index && index <= n )
{
s.push( tmp );
}else{
while ( !s.empty() )
{
q.push( s.top() );
s.pop();
}
q.push( tmp );
}
tmp = tmp->next;
}
while ( !s.empty() )
{
q.push( s.top() );
s.pop();
}
head = NULL;
if ( !q.empty() )
{
head = q.front();
q.pop();
tmp = head;
}
while ( !q.empty() )
{
tmp->next = q.front();
q.pop();
tmp = tmp->next;
}
tmp->next = NULL;
return head;
}
};
int main()
{
ListNode * tmp = new ListNode(1);
tmp->next = new ListNode(2);
// tmp->next->next = new ListNode(3);
// tmp->next->next->next = new ListNode(4);
// tmp->next->next->next->next = new ListNode(5);
// tmp->next->next->next->next->next = new ListNode(6);
// tmp->next->next->next->next->next->next = new ListNode(7);
Solution s;
ListNode * nodeRet = s.reverseBetween( tmp, 1, 2 );
return 0;
}
| true |
70fd0e40ffd89e3d974dc3b573f20014403e7d59 | C++ | mdrneale/AGE | /source/window/keyboard.cpp | UTF-8 | 979 | 3.046875 | 3 | [] | no_license | #include "keyboard.h"
Keyboard::Keyboard()
{
for (int i = 0; i < keyCount; ++i)
{
keys[i] = NOTTOUCHED;
}
}
Keyboard::~Keyboard()
{
}
void Keyboard::Update()
{
for (int i = 0; i < keyCount; ++i)
{
switch (keys[i])
{
case DOWN:
keys[i] = HELD;
break;
case UP:
keys[i] = NOTTOUCHED;
}
}
}
void Keyboard::KeyDown(int keyid)
{
keyid = NormaliseKeyID(keyid);
if (keyid < 0 || keyid >= keyCount)
{
printf("Unknown key press! %i\n", keyid);
return;
}
switch (keys[keyid])
{
case NOTTOUCHED:
case UP:
keys[keyid] = DOWN;
break;
}
}
void Keyboard::KeyUp(int keyid)
{
keyid = NormaliseKeyID(keyid);
if (keyid < 0 || keyid >= keyCount)
{
printf("Unknown key press! %i\n", keyid);
return;
}
switch (keys[keyid])
{
case DOWN:
case HELD:
keys[keyid] = UP;
break;
}
}
int Keyboard::NormaliseKeyID(int keyid)
{
if (keyid < 0 || keyid >= keyCount)
{
keyid = keyid + (keyCount-1) - SDLK_UP;
}
return keyid;
}
| true |
b99898d58bc653466358bca5f03524e4191684cf | C++ | hennesseyr14/EECS-280 | /p4-calculator/calc.cpp | UTF-8 | 4,622 | 3.546875 | 4 | [] | no_license | // Ryan Hennessey
/* calc.cpp
*
* RPN calculator
* EECS 280 Project 4
*/
#define NDEBUG
#include "Stack.h"
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
// REQUIRES: stack has at least two elements
// MODIFIES: stack
// EFFECTS: Adds the top two numbers on the stack
template <typename T>
void add(Stack<T> &stack);
// REQUIRES: stack has at least two elements
// MODIFIES: stack
// EFFECTS: Subtracts the top two numbers on the stack
template <typename T>
void subtract(Stack<T> &stack);
// REQUIRES: stack has at least two elements
// MODIFIES: stack
// EFFECTS: Multiplies the top two numbers on the stack
template <typename T>
void multiply(Stack<T> &stack);
// REQUIRES: stack has at least two elements
// MODIFIES: stack
// EFFECTS: Divides the top two numbers on the stack
template <typename T>
void divide(Stack<T> &stack);
// REQUIRES: stack has at least one element
// MODIFIES: stack
// EFFECTS: Pushes a duplicate of the top item to the stack
template <typename T>
void duplicate(Stack<T> &stack);
// REQUIRES: stack has at least two elements
// MODIFIES: stack
// EFFECTS: Reverses the top two items on the stack
template <typename T>
void reverse(Stack<T> &stack);
// REQUIRES: stack has at least one element
// MODIFIES: cout
// EFFECTS: Prints the top item on the stack
template <typename T>
void print(Stack<T> &stack);
// MODIFIES: stack
// EFFECTS: Pops all items off the stack
template <typename T>
void clear(Stack<T> &stack);
// MODIFIES: cout
// EFFECTS: Prints all items on the stack
template <typename T>
void print_all(const Stack<T> &stack);
// REQUIRES: stack has at least one element
// MODIFIES: stack
// EFFECTS: Negates the top number on the stack
template <typename T>
void _negate(Stack<T> &stack);
int main() {
// Set output precision
cout.precision(4);
// Create stack to hold the numbers from input
Stack<double> stack;
// String to hold input
string input;
// Read input and preform operations
while (cin >> input) {
if (input == "q") {
break;
}
else if (input == "+") {
add(stack);
}
else if (input == "-") {
subtract(stack);
}
else if (input == "*") {
multiply(stack);
}
else if (input == "/") {
divide(stack);
}
else if (input == "d") {
duplicate(stack);
}
else if (input == "r") {
reverse(stack);
}
else if (input == "p") {
print(stack);
}
else if (input == "c") {
clear(stack);
}
else if (input == "a") {
print_all(stack);
}
else if (input == "n") {
_negate(stack);
}
else {
stack.push(stod(input));
}
}
return 0;
}
template <typename T>
void add(Stack<T> & stack) {
// Check REQUIRES clause
assert(stack.size() >= 2);
double num1 = stack.pop();
double num2 = stack.pop();
stack.push(num2 + num1);
}
template <typename T>
void subtract(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 2);
double num1 = stack.pop();
double num2 = stack.pop();
stack.push(num2 - num1);
}
template <typename T>
void multiply(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 2);
double num1 = stack.pop();
double num2 = stack.pop();
stack.push(num2 * num1);
}
template <typename T>
void divide(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 2);
double num1 = stack.pop();
double num2 = stack.pop();
// Check for division by zero
if (num1 == 0) {
stack.push(num2);
stack.push(num1);
cout << "Error: Division by zero" << endl;
}
else {
stack.push(num2 / num1);
}
}
template <typename T>
void duplicate(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 1);
double num1 = stack.pop();
stack.push(num1);
stack.push(num1);
}
template <typename T>
void reverse(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 2);
double num1 = stack.pop();
double num2 = stack.pop();
stack.push(num1);
stack.push(num2);
}
template <typename T>
void print(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 1);
cout << stack.top() << endl;
}
template <typename T>
void clear(Stack<T> &stack) {
while (!stack.empty()) {
stack.pop();
}
}
template <typename T>
void print_all(const Stack<T> &stack) {
stack.print(cout);
cout << endl;
}
template <typename T>
void _negate(Stack<T> &stack) {
// Check REQUIRES clause
assert(stack.size() >= 1);
stack.top() = -stack.top();
} | true |
9ee157c0394023c61fa89e5eb2d34b79655b9200 | C++ | ras1234/interviewBit | /Arrays/findDuplicate.cpp | UTF-8 | 942 | 3.484375 | 3 | [] | no_license | /*
Given a read only array of n + 1 integers between 1 and n, find one number that repeats in linear time using less than O(n) space and traversing the stream sequentially O(1) times.
Sample Input:
[3 4 1 4 1]
Sample Output:
1
If there are multiple possible answers ( like in the sample case above ), output any one.
*/
int Solution::repeatedNumber(const vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
if(A.size()==0)
return -1;
int slow=0,fast=0;
while(1)
{
slow=A[slow];
fast=A[A[fast]];
if(slow==fast)
break;
}
fast=0;
while(A[slow]!=A[fast])
{
slow=A[slow];
fast=A[fast];
}
return A[slow];
}
| true |
80a59ae1db6def0c4f9427153624aa6e5b084ae5 | C++ | gfh16/StudyNotes | /CPP/C++学习资料/C++入门经典/书本例题/Code From the 2271 Book/ch15/prog15_07/carton.cpp | UTF-8 | 757 | 3.296875 | 3 | [] | no_license | // Carton.cpp
#include "Carton.h"
#include <cstring>
#include <iostream>
using std::cout;
using std::endl;
// Constructor
Carton::Carton(double lv, double wv, double hv,
const char* pStr, double dense, double thick):
Box(lv, wv, hv), density(dense), thickness(thick) {
pMaterial = new char[strlen(pStr)+1]; // Allocate space for the string
strcpy( pMaterial, pStr); // Copy it
cout << "Carton constructor" << endl;
}
// Destructor
Carton::~Carton() {
cout << "Carton destructor" << endl;
delete[] pMaterial;
}
// "Get carton weight" function
double Carton::getWeight() const {
return 2*(length*width + width*height + height*length)*thickness*density;
}
| true |
2f702a97a30049d1b08c7559037b6d8844b0139a | C++ | ramassin/partio | /src/lib/io/PLY.cpp | UTF-8 | 13,661 | 2.640625 | 3 | [] | no_license | /*
AAAAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRGHHHHHHHHHHHHHHHHHHHHHH
Core List (required)
--------------------
Element: vertex
x float x coordinate
y float y coordinate
z float z coordinate
Element: face
vertex_indices list of int indices to vertices
Second List (often used)
------------------------
Element: vertex
nx float x component of normal
ny float y component of normal
nz float z component of normal
red uchar red part of color
green uchar green part of color
blue uchar blue part of color
alpha uchar amount of transparency
*/
#include "../Partio.h"
#include "../core/ParticleHeaders.h"
#include "ZIP.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cassert>
#include <memory>
#include <cstring>
#include <stdio.h>
#include "../../extern/rply/rply.h"
// GLOBALS
p_ply input;
Partio::ParticlesDataMutable* simple = 0;
void * simplePtr;
// handles for standard attributes (color and normal may not exist)
Partio::ParticleAttribute idHandle, posHandle, colHandle, normHandle;
// container for extra attributes per vertex
std::vector<Partio::ParticleAttribute> genericHandles;
std::string inputFileName;
std::map<std::string, e_ply_type> attrs;
// vertex position handler callback
static int vertex_pos_cb(p_ply_argument argument) {
long idx;
//unfortunately we have to keep counting the calls to set the right particle
static unsigned int counter = 0;
void* pinfo = 0;
ply_get_argument_user_data(argument, &pinfo, &idx);
Partio::ParticlesDataMutable* particle =reinterpret_cast<Partio::ParticlesDataMutable *>(pinfo);
int nParticles = particle->numParticles();
if (counter > (unsigned int)nParticles)
counter = 0;
int * id = particle->dataWrite<int>(idHandle,counter);
*id=counter;
float* pos=particle->dataWrite<float>(posHandle,counter);
float val = (float)ply_get_argument_value(argument);
pos[idx]=val;
if (idx==2)
counter++;
//printf("vertex %d Pos %d: %g\n", counter, idx, val);
//printf(" ");
return 1;
}
// vertex color callback for uints
static int vertex_col_cb_uint(p_ply_argument argument) {
const float scaleFactor=1.0f/255.0f;
long idx;
static unsigned int counter = 0; //unfortunately we have to keep a local counter
void* pinfo = 0;
ply_get_argument_user_data(argument, &pinfo, &idx);
Partio::ParticlesDataMutable* particle =reinterpret_cast<Partio::ParticlesDataMutable *>(pinfo);
int nParticles = (unsigned int)particle->numParticles();
if (counter > (unsigned int)nParticles)
counter = 0;
float* pos=particle->dataWrite<float>(colHandle,counter);
float val = (float)ply_get_argument_value(argument) * scaleFactor;
pos[idx]=val;
// after we've done with Blue, increment particle index
if (idx==2)
counter++;
//printf("color %d: %g", idx, ply_get_argument_value(argument));
//if (idx==2) printf("\n");
//else printf(" ");
return 1;
}
// vertex color callback for floats
static int vertex_col_cb_float(p_ply_argument argument) {
long idx;
static unsigned int counter = 0; //unfortunately we have to keep a local counter
void* pinfo = 0;
ply_get_argument_user_data(argument, &pinfo, &idx);
Partio::ParticlesDataMutable* particle =reinterpret_cast<Partio::ParticlesDataMutable *>(pinfo);
if (counter > (unsigned int)particle->numParticles())
counter = 0;
float* pos=particle->dataWrite<float>(colHandle,counter);
float val = (float)ply_get_argument_value(argument);
pos[idx]=val;
// after we've done with Blue, increment particle index
if (idx==2)
counter++;
//printf("color %d: %g", idx, ply_get_argument_value(argument));
//if (idx==2) printf("\n");
//else printf(" ");
return 1;
}
// vertex normal callback for uints
static int vertex_normal_cb_uint(p_ply_argument argument) {
const float scaleFactor=1.0f/255.0f;
long idx;
static unsigned int counter = 0; //unfortunately we have to keep a local counter
void* pinfo = 0;
ply_get_argument_user_data(argument, &pinfo, &idx);
Partio::ParticlesDataMutable* particle =reinterpret_cast<Partio::ParticlesDataMutable *>(pinfo);
int nParticles = particle->numParticles();
if (counter > (unsigned int)nParticles)
counter = 0;
float* pos=particle->dataWrite<float>(normHandle,counter);
float val = (float)ply_get_argument_value(argument) * scaleFactor;
pos[idx]=val;
// after we've done with Blue, increment particle index
if (idx==2)
counter++;
//printf("color %d: %g", idx, ply_get_argument_value(argument));
//if (idx==2) printf("\n");
//else printf(" ");
return 1;
}
// vertex normal callback for floats
static int vertex_normal_cb_float(p_ply_argument argument) {
long idx;
static unsigned int counter = 0; //unfortunately we have to keep a local counter
void* pinfo = 0;
ply_get_argument_user_data(argument, &pinfo, &idx);
Partio::ParticlesDataMutable* particle =reinterpret_cast<Partio::ParticlesDataMutable *>(pinfo);
if (counter > (unsigned int)particle->numParticles())
counter = 0;
float* pos=particle->dataWrite<float>(normHandle,counter);
float val = (float)ply_get_argument_value(argument);
pos[idx]=val;
// after we've done with Blue, increment particle index
if (idx==2)
counter++;
//printf("color %d: %g", idx, ply_get_argument_value(argument));
//if (idx==2) printf("\n");
//else printf(" ");
return 1;
}
// generic float callback, the integer value is now the index in the generic handle vector
static int generic_vertex_cb(p_ply_argument argument) {
static std::vector<unsigned int> counters(32); //do you really need more than 32?
long idx;
void* pinfo = 0;
ply_get_argument_user_data(argument, &pinfo, &idx);
Partio::ParticlesDataMutable* particle =reinterpret_cast<Partio::ParticlesDataMutable *>(pinfo);
if (counters[idx] > (unsigned int)particle->numParticles())
counters[idx] = 0;
float* pos=particle->dataWrite<float>(genericHandles[idx],counters[idx]);
float val = (float)ply_get_argument_value(argument);
*pos=val;
counters[idx]++;
return 1;
}
std::string printPlyType(e_ply_type plyType){
std::string ret;
switch (plyType)
{
case e_ply_type::PLY_INT8 :
ret = "PLY_INT8";
break;
case e_ply_type::PLY_INT16 :
ret = "PLY_INT16";
break;
case e_ply_type::PLY_UINT16 :
ret = "PLY_UINT16";
break;
case e_ply_type::PLY_INT32 :
ret = "PLY_INT32";
break;
case e_ply_type::PLY_CHAR :
ret = "PLY_CHAR";
break;
case e_ply_type::PLY_UCHAR :
ret = "PLY_UCHAR";
break;
case e_ply_type::PLY_SHORT :
ret = "PLY_SHORT";
break;
case e_ply_type::PLY_USHORT :
ret = "PLY_USHORT";
break;
case e_ply_type::PLY_INT :
ret = "PLY_INT";
break;
case e_ply_type::PLY_UINT :
ret = "PLY_UINT";
break;
case e_ply_type::PLY_FLOAT :
ret = "PLY_FLOAT";
break;
case e_ply_type::PLY_FLOAT32 :
ret = "PLY_FLOAT32";
break;
case e_ply_type::PLY_FLOAT64 :
ret = "PLY_FLOAT64";
break;
case e_ply_type::PLY_DOUBLE :
ret = "PLY_DOUBLE";
break;
default:
ret = "INVALID";
break;
}
return ret;
}
namespace Partio
{
using namespace std;
static Partio::ParticleAttributeType typePLY2Partio(e_ply_type plyType){
Partio::ParticleAttributeType partioType;
/* PLY_INT8, PLY_UINT8, PLY_INT16, PLY_UINT16,
PLY_INT32, PLY_UIN32, PLY_FLOAT32, PLY_FLOAT64,
PLY_CHAR, PLY_UCHAR, PLY_SHORT, PLY_USHORT,
PLY_INT, PLY_UINT, PLY_FLOAT, PLY_DOUBLE,
PLY_LIST */
switch (plyType)
{
case e_ply_type::PLY_INT8 :
case e_ply_type::PLY_UINT8 :
case e_ply_type::PLY_INT16 :
case e_ply_type::PLY_UINT16 :
case e_ply_type::PLY_INT32 :
case e_ply_type::PLY_CHAR :
case e_ply_type::PLY_UCHAR :
case e_ply_type::PLY_SHORT :
case e_ply_type::PLY_USHORT :
case e_ply_type::PLY_INT :
case e_ply_type::PLY_UINT :
partioType = Partio::ParticleAttributeType::INT;
break;
case e_ply_type::PLY_FLOAT:
case e_ply_type::PLY_FLOAT32:
case e_ply_type::PLY_FLOAT64:
case e_ply_type::PLY_DOUBLE:
partioType = Partio::ParticleAttributeType::FLOAT;
break;
default:
partioType = Partio::ParticleAttributeType::NONE;
break;
}
return partioType;
}
//return a vector of properties from ply header
typedef std::pair<std::string, e_ply_type> plyVertexAttrib;
int parsePlyHeader(p_ply & input, std::map<std::string, e_ply_type> & attrs)
{
if (!ply_read_header(input))
{
std::cerr<<"Partio: Problem parsing PLY header"<< inputFileName <<std::endl;
return 0;
}
const char* lastComment = NULL;
//display comments
while ((lastComment = ply_get_next_comment(input, lastComment)))
{
printf("[PLY][Comment] %s\n",lastComment);
}
p_ply_element vertexElem = NULL;
unsigned int vertexCount = 0;
const char * elemName;
long elemCount;
while (vertexElem = ply_get_next_element(input, vertexElem))
{
ply_get_element_info(vertexElem, &elemName, &elemCount);
printf("elem name %s count %i \n", elemName, elemCount);
if (strcmp(elemName, "vertex") == 0){ //we only care about vertices
vertexCount = elemCount;
p_ply_property thisProp = NULL;
while (thisProp = ply_get_next_property(vertexElem, thisProp))
{
const char * propName;
e_ply_type propType;
ply_get_property_info(thisProp, &propName, &propType, NULL, NULL);
printf("%s: type %s \n", propName, printPlyType( propType).c_str());
plyVertexAttrib attr(std::string(propName), propType);
attrs.insert( attr);
}
}
}
return vertexCount;
}
int setTripletCallbacks(std::string a, std::string b, std::string c, std::string attributNAme, ParticleAttribute & handle, p_ply_read_cb plyCallbackUint, p_ply_read_cb plyCallbackFloat )
{
if ( (attrs.find(a) != attrs.end()) && (attrs.find(b) != attrs.end()) &&
(attrs.find(c) != attrs.end()))
{
handle = simple->addAttribute(attributNAme.c_str(), VECTOR, 3);
//printf("attribute %s type: %d\n",a.c_str(),attrs[a]);
//cout << "corresponds to: "<< printPlyType(attrs[a]) << endl;
Partio::ParticleAttributeType colorType = typePLY2Partio ( attrs[a] ); //we assume type is same for all triplet
switch (colorType)
{
case Partio::ParticleAttributeType::INT:
ply_set_read_cb(input, "vertex", a.c_str(), plyCallbackUint, simplePtr, 0);
ply_set_read_cb(input, "vertex", b.c_str(), plyCallbackUint, simplePtr, 1);
ply_set_read_cb(input, "vertex", c.c_str(), plyCallbackUint, simplePtr, 2);
break;
case Partio::ParticleAttributeType::FLOAT:
ply_set_read_cb(input, "vertex", a.c_str(), plyCallbackFloat, simplePtr, 0);
ply_set_read_cb(input, "vertex", b.c_str(), plyCallbackFloat, simplePtr, 1);
ply_set_read_cb(input, "vertex", c.c_str(), plyCallbackFloat, simplePtr, 2);
}
attrs.erase(a);
attrs.erase(b);
attrs.erase(c);
return 1;
}
return 0;
}
// TODO: convert this to use iterators like the rest of the readers/writers
ParticlesDataMutable* readPLY(const char* filename,const bool headersOnly)
{
inputFileName= string(filename);
input = ply_open(filename, NULL, 0, NULL);
if (!input)
{
cerr<<"Partio: Can't open particle data file: "<<inputFileName<<endl;
return 0;
}
if (headersOnly)
{
simple=new ParticleHeaders;
}
else simple=create();
//printf("created!\n");
unsigned int nParticles = parsePlyHeader(input, attrs);
// create null pointer to partio stuct for callbacks
simplePtr = reinterpret_cast<void *>(simple);
if ( (attrs.find("x") != attrs.end()) &&
(attrs.find("y") != attrs.end()) &&
(attrs.find("z") != attrs.end()) )
{
idHandle = simple->addAttribute("id", Partio::INT, 1);
posHandle = simple->addAttribute("position", VECTOR, 3);
ply_set_read_cb(input, "vertex", "x", vertex_pos_cb, simplePtr, 0);
ply_set_read_cb(input, "vertex", "y", vertex_pos_cb, simplePtr, 1);
ply_set_read_cb(input, "vertex", "z", vertex_pos_cb, simplePtr, 2);
attrs.erase("x");
attrs.erase("y");
attrs.erase("z");
} else {
cerr<<"Partio: Problem parsing PLY properties in file "<<inputFileName
<< "\n No x,y,z coordinates found"<<endl;
}
// assign color callback to rgb
int nCol = 0;
nCol += setTripletCallbacks("r", "g", "b", "pointColor", colHandle, vertex_col_cb_uint, vertex_col_cb_float);
nCol += setTripletCallbacks("red", "green", "blue", "pointColor", colHandle, vertex_col_cb_uint, vertex_col_cb_float);
if (nCol == 0) {
cout<<"Partio: No colors in file: "<<inputFileName<<endl;
}
// assign normal callback
int nNorm = 0;
nNorm += setTripletCallbacks("nx", "ny", "nz", "normal", normHandle, vertex_normal_cb_uint, vertex_normal_cb_float);
nNorm += setTripletCallbacks("Nx", "Ny", "Nz", "normal", normHandle, vertex_normal_cb_uint, vertex_normal_cb_float);
if (nNorm == 0) {
cout<<"Partio: No normals in file: "<<inputFileName<<endl;
}
int i = 0;
for(std::map<std::string, e_ply_type>::iterator it = attrs.begin(); it != attrs.end(); it++) {
genericHandles.push_back(simple->addAttribute(it->first.c_str(), VECTOR, 1));
ply_set_read_cb(input, "vertex", it->first.c_str(), generic_vertex_cb, simplePtr, i);
cout << "set callback for leftover attribute: " << it->first <<" type: " << printPlyType( it->second) << endl;
i++;
}
// all is set up now, proceed with parsing the file (if no headersOnly)
if (!headersOnly)
{
simple->addParticles(nParticles);
if (!ply_read(input)){
cerr<<"Partio: Problem parsing PLY data in file: "<<inputFileName<<endl;
return 0;
}
}
ply_close(input);
//printf("read!\n");
return simple;
}
} | true |
4733945b43d0a71fbc0a09b5925874100e25b512 | C++ | ViktorTsekov/CPP | /OOP/Handling_Exceptions/Order/Order.cpp | UTF-8 | 1,540 | 3.671875 | 4 | [] | no_license | #include "Order.h"
ostream& operator<<(ostream& out, const Order& order) {
out << endl;
out << "Order number: " << order.orderNumber << endl;
out << "Quantity ordered: " << order.quantityOrdered << endl;
out << "Single price: " << order.singlePrice << endl;
out << "Total price: " << order.totalPrice << endl;
return out;
}
istream& operator>>(istream& in, Order& order) {
Exception e;
double input;
string strInput;
//Order number
cout << endl;
cout << "Enter order number: "; cin >> strInput;
if(e.checkIfValueIsOutOfRange(strInput, 1, 4, e)) {
throw(e);
} else {
order.orderNumber = strInput;
}
//Quantity
cout << "Enter quantity: "; cin >> input;
if(e.checkIfValueIsMismatched(input, e)) {
throw(e);
} else if(e.checkIfValueIsOutOfRange(input, 1, 50, e)){
throw(e);
} else {
order.quantityOrdered = input;
}
//Single price
cout << "Enter single price: "; cin >> input;
if(e.checkIfValueIsMismatched(input, e)) {
throw(e);
} else if(e.checkIfValueIsOutOfRange(input, 1, 39.95, e)){
throw(e);
} else {
order.singlePrice = input;
}
//Total price
input = order.quantityOrdered * order.singlePrice;
if(e.checkIfValueIsOutOfRange(input, 0, 1000, e)) {
throw(e);
} else {
order.totalPrice = input;
}
return in;
}
Order::Order() {
orderNumber = "/";
quantityOrdered = 0;
singlePrice = 0;
totalPrice = 0;
} | true |
17820f0dc90a3761670394d620d1c980c8259c02 | C++ | nonprofittechy/Arduino_Word_Clock | /word clock/Word_clock__nico_ - Copy/Word_clock__nico_.ino | UTF-8 | 13,952 | 2.6875 | 3 | [] | no_license | #include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>
#include "LedControl.h"
const int birthDay = 15;
const int birthMonth = 6;
const int minUpPin = 3;
const int minDownPin = 5;
int minUpState;
int minDownState;
int lastMinUpState = HIGH; // we are using the pull-up resistor, so we check for pin state == LOW to find a button press
int lastMinDownState = HIGH;
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastUpDebounceTime = 0; // the last time the output pin was toggled
long lastDownDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
// an ledWord can only span one row but may span multiple MAXIM7221s
struct ledWord {
int row;
int colsValue; // the byte value we want set for this row
};
/*
* Here we define an array of ledWord objects that contain the pin address for each word we will want to separately control on the display
* see key below to figure out mapping of second value to a column in the array.
*/
ledWord ITIS[] = { { 0,128+64+16+8},
{ 0,0}};
//ledWord IS[] = { {0,16+8},
// {0,0}};
ledWord TEN[]= { {0,4+2+1},
{0,0}};
ledWord HALF[]= { {0,0},
{0,8+4+2+1}};
ledWord QUARTER[] = { {1, 64+32+16+8+4+2+1},
{0,0} };
ledWord TWENTY[] = { {0,0},
{1,32+16+8+4+2+1}};
ledWord FIVE[] = { {2,128+64+32+16},
{0,0}};
ledWord HAPPY[] = { {2,8+4+2+1},
{2,128}};
ledWord PAST[] = { {0,0},
{2,8+4+2+1}};
ledWord BIRTHDAY[]= { {3,64+32+16+8+4+2+1},
{3,128}};
ledWord TO[] = { {0,0},
{3,32+16}};
ledWord ONEOCLOCK[] = { {0,0},
{3,4+2+1}};
ledWord TWOOCLOCK[] = { {4,128+64+32},
{0,0}};
ledWord THREEOCLOCK[] = { {4,8+4+3+2+1},
{0,0}};
ledWord FOUROCLOCK[] = { {0,0},
{4,128+64+32+16}};
ledWord FIVEOCLOCK[] = { {0,0},
{4,8+4+2+1}};
ledWord SIXOCLOCK[] = { {5,128+64+32},
{0,0}};
ledWord SEVENOCLOCK[] = { {5,2+1},
{5,128+64+32}};
ledWord EIGHTOCLOCK[] = { {0,0},
{5,16+8+4+2+1}};
ledWord NINEOCLOCK[] = { {6,128+64+32+16},
{0,0}};
ledWord TENOCLOCK[] = { {6,4+2+1},
{0,0}};
ledWord ELEVENOCLOCK[]= { {0,0},
{6,32+16+8+4+2+1}};
ledWord TWELVEOCLOCK[]= { {7,128+64+32+16+8+4},
{0,0}};
ledWord NAME[] = { {7,1},
{7,128+64+32}};
ledWord DOT1[] = { {0,0},
{7,8}};
ledWord DOT2[] = { {0,0},
{7,8+4}}; // value includes previous dots
ledWord DOT3[] = { {0,0},
{7,8+4+2}};; // value includes previous dots
ledWord DOT4[] = { {0,0},
{7,8+4+2+1}};; // value includes previous dots
/*
* Below shows the layout of LEDs in my array:
*
* DIG0 0 I T I S T E N 0 H A L F
* DIG1 1 Q U A R T E R 1 T W E N T Y
* DIG2 2 F I V E H A P P 2 Y P A S T
* DIG3 3 B I R T H D A 3 Y T O O N E
* DIG4 4 T W O T H R E E 4 F O U R F I V E
* DIG5 5 S I X S E 5 V E N E I G H T
* DIG6 6 N I N E T E N 6 E L E V E N
* DIG7 7 T W E L V E N 7 I C O * * * *
* 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
* P A B C D E F G P A B C D E F G
*/
/*
* Cheatsheet for values if each column is "ON" in a row:
* 0 1 2 3 4 5 6 7
* 128 64 32 16 8 4 2 1
*/
int lc0RVals[8]; // will hold row setting variables for ledControl 0
int lc1RVals[8]; // will hold row setting variables for ledControl 1
/*
* Create a new LedControl object named wordMatrix
* We use pins 12,11 and 10 for the SPI interface
* With our hardware we have connected pin 12 to the DATA IN-pin (1) of the first MAX7221
* pin 11 is connected to the CLK-pin(13) of the first and second MAX7221
* pin 10 is connected to the LOAD-pin(12) of the first and second MAX7221
* We will have two MAX7221s attached to the arduino
*/
LedControl wordMatrix=LedControl(12,11,10,2);
/*
* Setup initial state for our Arduino
*/
void setup() {
// turn on the displays
wordMatrix.shutdown(0,false);
wordMatrix.shutdown(1,false);
// set both of the LED matrices to moderate brightness (intensity = 0..15)
wordMatrix.setIntensity(0,8);
wordMatrix.setIntensity(1,8);
wordMatrix.clearDisplay(0);
wordMatrix.clearDisplay(1);
pinMode(minUpPin, INPUT);
pinMode(minDownPin, INPUT);
// activate internal pull-up resistors
digitalWrite(minUpPin, HIGH);
digitalWrite(minDownPin, HIGH);
}
// each cycle we will go through 16 rows and set the LEDs to the proper value
// using LEDControl library, this is done by setting LED Row to the proper value (adding powers of 2 to end up with a single byte value)
// to reduce flicker and stray lit LEDs, we will set the row values all at once at the end of our script
void loop() {
// create a variable to hold the current time
tmElements_t tm;
int hr;
int mn;
////////////////////////////////////////////
// read the current time from our DS3231 Real Time Clock
RTC.read(tm);
mn = tm.Minute;
hr = (tm.Hour >= 12) ? tm.Hour - 12 : tm.Hour; // convert hours to 12 hour time, zero-based
int upButtonReading = digitalRead(minUpPin);
int downButtonReading = digitalRead(minDownPin);
////////////////////////////////////////////
// Check the button states and increase/decrease times
// first check the minute UP button
if(upButtonReading != lastMinUpState) {
lastUpDebounceTime = millis();
}
if (millis() - lastUpDebounceTime > debounceDelay) {
if (upButtonReading != lastMinUpState) {
lastMinUpState = upButtonReading;
if (lastMinUpState == LOW) {
minInc(tm);
}
}
}
if(downButtonReading != lastMinDownState) {
lastDownDebounceTime = millis();
}
// next check the minute DOWN button
if (millis() - lastDownDebounceTime > debounceDelay) {
if (downButtonReading != lastMinDownState) {
lastMinDownState = downButtonReading;
if (lastMinDownState == LOW) {
minDec(tm);
}
}
}
// zero out the display array variables so we have no stray LEDs lit
for (int i=0;i<8;i++) {
lc0RVals[i]=0;
lc1RVals[i]=0;
}
// Light up IT IS
lc0RVals[ITIS[0].row] += ITIS[0].colsValue;
lc1RVals[ITIS[1].row] += ITIS[1].colsValue;
// Light up NAME
lc0RVals[NAME[0].row] += NAME[0].colsValue;
lc1RVals[NAME[1].row] += NAME[1].colsValue;
// Set the status of the 4 extra "dots"
lightMinuteDots(mn % 5);
// Set the remaining minute LEDs
lightMinuteWords(mn);
// Set the Hour LEDs
lightHourWords(hr);
// set the birthday LEDs
if (isBirthday) {
lc0RVals[HAPPY[0].row] += HAPPY[0].colsValue;
lc1RVals[HAPPY[1].row] += HAPPY[1].colsValue;
lc0RVals[BIRTHDAY[0].row] += BIRTHDAY[0].colsValue;
lc1RVals[BIRTHDAY[1].row] += BIRTHDAY[1].colsValue;
}
// copy the row values from our lcRVals arrays to the LedControls
for (int j=0;j<8;j++) {
wordMatrix.setRow(0,j,lc0RVals[j]);
wordMatrix.setRow(1,j,lc1RVals[j]);
}
}
bool isBirthday(tmElements_t tm) {
return (tm.Month == birthMonth) && (tm.Day == birthDay);
}
/*
* light up 0-4 dots, depending on how many minutes we are "over" the 5-minute accuracy we get using just the words LEDs
* remainder must be a number < 5, > 0
*/
void lightMinuteDots(int remainder) {
if (remainder >= 4) {
lc0RVals[DOT4[0].row]+=DOT4[0].colsValue;
lc1RVals[DOT4[1].row]+=DOT4[1].colsValue;
} else if (remainder == 3) {
lc0RVals[DOT3[0].row]+=DOT3[0].colsValue;
lc1RVals[DOT3[1].row]+=DOT3[1].colsValue;
} else if (remainder == 2) {
lc0RVals[DOT2[0].row]+=DOT2[0].colsValue;
lc1RVals[DOT2[1].row]+=DOT2[1].colsValue;
} else if (remainder == 1) {
lc0RVals[DOT1[0].row]+=DOT1[0].colsValue;
lc1RVals[DOT1[1].row]+=DOT1[1].colsValue;
}
}
/*
* Light up the right words for the current minutes
*/
void lightMinuteWords(int mn) {
if (mn < 5) {
// nothing to do
} else if (mn < 10) {
// IT IS FIVE PAST ONE
//FIVE
lc0RVals[FIVE[0].row]+=FIVE[0].colsValue;
lc1RVals[FIVE[1].row]+=FIVE[1].colsValue;
//PAST
lc0RVals[PAST[0].row]+=PAST[0].colsValue;
lc1RVals[PAST[1].row]+=PAST[1].colsValue;
} else if (mn < 15) {
// IT IS TEN PAST ONE
lc0RVals[TEN[0].row]+=TEN[0].colsValue;
lc1RVals[TEN[1].row]+=TEN[1].colsValue;
//PAST
lc0RVals[PAST[0].row]+=PAST[0].colsValue;
lc1RVals[PAST[1].row]+=PAST[1].colsValue;
} else if (mn < 20) {
// IT IS QUARTER PAST ONE
lc0RVals[QUARTER[0].row]+=QUARTER[0].colsValue;
lc1RVals[QUARTER[1].row]+=QUARTER[1].colsValue;
//PAST
lc0RVals[PAST[0].row]+=PAST[0].colsValue;
lc1RVals[PAST[1].row]+=PAST[1].colsValue;
} else if (mn < 25) {
// IT IS TWENTY PAST ONE
lc0RVals[TWENTY[0].row]+=TWENTY[0].colsValue;
lc1RVals[TWENTY[1].row]+=TWENTY[1].colsValue;
//FIVE
lc0RVals[FIVE[0].row]+=FIVE[0].colsValue;
lc1RVals[FIVE[1].row]+=FIVE[1].colsValue;
//PAST
lc0RVals[PAST[0].row]+=PAST[0].colsValue;
lc1RVals[PAST[1].row]+=PAST[1].colsValue;
} else if (mn < 35 ) {
// IT IS HALF PAST ONE
lc0RVals[HALF[0].row]+=HALF[0].colsValue;
lc1RVals[HALF[1].row]+=HALF[1].colsValue;
//PAST
lc0RVals[PAST[0].row]+=PAST[0].colsValue;
lc1RVals[PAST[1].row]+=PAST[1].colsValue;
} else if (mn < 40) {
// IT IS TWENTY FIVE TO TWO
lc0RVals[TWENTY[0].row]+=TWENTY[0].colsValue;
lc1RVals[TWENTY[1].row]+=TWENTY[1].colsValue;
//FIVE
lc0RVals[FIVE[0].row]+=FIVE[0].colsValue;
lc1RVals[FIVE[1].row]+=FIVE[1].colsValue;
//PAST
lc0RVals[TO[0].row]+=TO[0].colsValue;
lc1RVals[TO[1].row]+=TO[1].colsValue;
} else if (mn < 45) {
// IT IS TWENTY TO TWO
lc0RVals[TWENTY[0].row]+=TWENTY[0].colsValue;
lc1RVals[TWENTY[1].row]+=TWENTY[1].colsValue;
//PAST
lc0RVals[TO[0].row]+=TO[0].colsValue;
lc1RVals[TO[1].row]+=TO[1].colsValue;
} else if (mn < 50) {
// IT IS QUARTER TO TWO
lc0RVals[QUARTER[0].row]+=QUARTER[0].colsValue;
lc1RVals[QUARTER[1].row]+=QUARTER[1].colsValue;
//PAST
lc0RVals[TO[0].row]+=TO[0].colsValue;
lc1RVals[TO[1].row]+=TO[1].colsValue;
} else if (mn < 55) {
// IT IS TEN TO TWO
lc0RVals[TEN[0].row]+=TEN[0].colsValue;
lc1RVals[TEN[1].row]+=TEN[1].colsValue;
//PAST
lc0RVals[TO[0].row]+=TO[0].colsValue;
lc1RVals[TO[1].row]+=TO[1].colsValue;
} else if (mn < 60) {
// IT IS FIVE TO TWO
lc0RVals[FIVE[0].row]+=FIVE[0].colsValue;
lc1RVals[FIVE[1].row]+=FIVE[1].colsValue;
//PAST
lc0RVals[TO[0].row]+=TO[0].colsValue;
lc1RVals[TO[1].row]+=TO[1].colsValue;
}
}
/*
* Light up the right words for the current hour, in 12 hour format
*/
void lightHourWords(int hr) {
switch (hr) {
case 11:
lc0RVals[ELEVENOCLOCK[0].row]+=ELEVENOCLOCK[0].colsValue;
lc1RVals[ELEVENOCLOCK[1].row]+=ELEVENOCLOCK[1].colsValue;
break;
case 10:
lc0RVals[TENOCLOCK[0].row]+=TENOCLOCK[0].colsValue;
lc1RVals[TENOCLOCK[1].row]+=TENOCLOCK[1].colsValue;
break;
case 9:
lc0RVals[NINEOCLOCK[0].row]+=NINEOCLOCK[0].colsValue;
lc1RVals[NINEOCLOCK[1].row]+=NINEOCLOCK[1].colsValue;
break;
case 8:
lc0RVals[EIGHTOCLOCK[0].row]+=EIGHTOCLOCK[0].colsValue;
lc1RVals[EIGHTOCLOCK[1].row]+=EIGHTOCLOCK[1].colsValue;
break;
case 7:
lc0RVals[SEVENOCLOCK[0].row]+=SEVENOCLOCK[0].colsValue;
lc1RVals[SEVENOCLOCK[1].row]+=SEVENOCLOCK[1].colsValue;
break;
case 6:
lc0RVals[SIXOCLOCK[0].row]+=SIXOCLOCK[0].colsValue;
lc1RVals[SIXOCLOCK[1].row]+=SIXOCLOCK[1].colsValue;
break;
case 5:
lc0RVals[FIVEOCLOCK[0].row]+=FIVEOCLOCK[0].colsValue;
lc1RVals[FIVEOCLOCK[1].row]+=FIVEOCLOCK[1].colsValue;
break;
case 4:
lc0RVals[FOUROCLOCK[0].row]+=FOUROCLOCK[0].colsValue;
lc1RVals[FOUROCLOCK[1].row]+=FOUROCLOCK[1].colsValue;
break;
case 3:
lc0RVals[THREEOCLOCK[0].row]+=THREEOCLOCK[0].colsValue;
lc1RVals[THREEOCLOCK[1].row]+=THREEOCLOCK[1].colsValue;
break;
case 2:
lc0RVals[TWOOCLOCK[0].row]+=TWOOCLOCK[0].colsValue;
lc1RVals[TWOOCLOCK[1].row]+=TWOOCLOCK[1].colsValue;
break;
case 1:
lc0RVals[ONEOCLOCK[0].row]+=ONEOCLOCK[0].colsValue;
lc1RVals[ONEOCLOCK[1].row]+=ONEOCLOCK[1].colsValue;
break;
case 0:
lc0RVals[TWELVEOCLOCK[0].row]+=TWELVEOCLOCK[0].colsValue;
lc1RVals[TWELVEOCLOCK[1].row]+=TWELVEOCLOCK[1].colsValue;
break;
}
}
/*
* Adjust the time on the RTC up by one minute
*/
void minInc(tmElements_t tm) {
//check for the cases when we are at 0 minutes, or 0 hours, prior to decrementing.
// we won't handle changing the date
if (tm.Minute == 0) {
if (tm.Hour == 0) {
tm.Day--;
tm.Hour = 23;
tm.Minute = 59;
} else {
tm.Hour--;
tm.Minute = 59;
}
} else {
tm.Minute--;
}
RTC.write(tm);
}
/*
* Adjust the time on the RTC down by one minute
*/
void minDec(tmElements_t tm) {
if (tm.Minute == 59) {
if (tm.Hour == 23) {
tm.Day++;
tm.Hour = 0;
tm.Minute = 0;
} else {
tm.Hour++;
tm.Minute = 0;
}
} else {
tm.Minute++;
}
RTC.write(tm);
}
| true |
e4793b1b82f85318ebe912f1148bb4d9296130f3 | C++ | reyhard/o2scripts | /std/paramFile.inc | UTF-8 | 13,474 | 3.0625 | 3 | [] | no_license | //define parsing function
//param - IOStream, opened file, or another stream, return - array parsed paramfile;
paramFileRead=
{
scopeName "paramFile.inc";
private "_ReadClass";
private "_ReadRawClass";
private "_ReadArray";
private "_ReadSimpleValue";
private "_ReadSimpleItem";
//localfunction _ReadClass
//param - IOStream, return Array ["<name>","class",[....] ]
_ReadClass= //input: <class name> { ... };
{
private "_content";
private "_classname";
private "_result";
eatWS _this; //eat whitespaces
if (_this explorefor "[_a-zA-Z0-9]+") then //test stream for standard identifier
{
_classname=_this get 0; //get classname (get everything tested)
eatWS _this; //eat whitespaces
if (_this exploreFor "{") then //test stream if contains {
{
_this ignore 1; //ignore character {
_content=_this call _ReadRawClass; //Read content of class
if ((!isnil "_content") && (_this exploreFor "}[\S]*;*[\s\n\r;]*")) then //test end of class }; [\S] is whitechar
{
_result=+[_classname,"class",_content]; //store values as result
_this ignore 0; //skip everything tested };
}
else
{
_result=nil //error is nil
};
}
else
{
_result=nil; //error is nil
};
}
else
{
_result=nil; //error is nil
};
_result //return result
};
_ReadEmptyClass= //input: <class name> { ... };
{
private "_content";
private "_classname";
private "_result";
eatWS _this; //eat whitespaces
if (_this explorefor "[_a-zA-Z0-9]+") then //test stream for standard identifier
{
_classname=_this get 0; //get classname (get everything tested)
eatWS _this; //eat whitespaces
_content= [];
_result=+[_classname,"EmptyClass",_content]; //store values as result
if(_this exploreFor "[\S]*;*[\s\n\r;]*") then
{
_this ignore 0; //skip everything tested ;
};
}
else
{
_result=nil; //error is nil
};
_result //return result
};
_ReadDerivedClass= //input: <class name> { ... };
{
private "_content";
private "_classname";
private "_result";
private "_derivename";
eatWS _this; //eat whitespaces
if (_this explorefor "[_a-zA-Z0-9]+") then //test stream for standard identifier
{
_classname=_this get 0; //get classname (get everything tested)
eatWS _this; //eat whitespaces
if (_this exploreFor ":") then //test stream if contains :
{
_this ignore 1; //ignore character {
eatWS _this;
if (_this explorefor "[_a-zA-Z0-9]+") then //test stream for standard identifier
{
_derivename=_this get 0; //get classname (get everything tested)
eatWS _this; //eat whitespaces
if (_this exploreFor "{") then //test stream if contains {
{
_this ignore 1; //ignore character {
_content=_this call _ReadRawClass; //Read content of class
if ((!isnil "_content") && (_this exploreFor "}[\S]*;*[\s\n\r;]*")) then //test end of class }; [\S] is whitechar
{
_result=+[_classname,"class",_content,_derivename]; //store values as result
_this ignore 0; //skip everything tested };
}
else
{
_result=nil //error is nil
};
}
else
{
_result=nil; //error is nil
};
};
}
else
{
_result=nil; //error is nil
};
}
else
{
_result=nil; //error is nil
};
_result //return result
};
_ReadSimpleValue= //input="any text which may represent value"
{
private "_value";
eatWS _this; //eat whitespwaces
switch (true) do //switch for true
{
case (_this exploreFor "_*[+-]*[0-9]+[.]?[0-9]*([eE][+-]?[0-9]+)?_*[,};]"): //test for number
{
_value=val (_this get -1); //it is number, get all and convertit
};
case (_this exploreFor "(""[^""]*"")+[^""]"): // "([^"]*)+[^"] - begins with ", endings with " and something which is not "
{ //test for string
_this ignore 1; //ignore first quote
_value=_this get -2; //get remaining excluding 2 characters (quote and one extra character)
_this ignore 1; //ignore last quite
};
case (_this exploreFor "{"): //subarray test for {
{
_this ignore 1; //skip {
eatWS _this; //eat whitespaces
private ["_arr","_subitem"];
_arr=+[]; //prepare array
_subitem=_this call _ReadSimpleValue; //read first value
eatWS _this; //eat extra whitespaces
while {_this exploreFor ","} do //while additional values present
{
_this ignore 0; //ignore all tested (comma ,)
_arr set [count _arr,_subitem]; //store previous value
_subitem=_this call _ReadSimpleValue; //read next value
eatWS _this; //eat extra whitespaces
};
_arr set [count _arr,_subitem]; //store last value
if (_this exploreFor "}") then //test for end of array
{
_value=_arr; //store result as value
eatWS (_this ignore 1); //ignore } and eat whitespaces
}
else //error is nil
{
_value=nil;
};
};
case (_this exploreFor "[^,;}]*"):
{
_value="#$flag:"+(_this get 0);
};
default {_value=nil;}; //we failed all tests, report error;
};
_value //result
};
_ReadArray= //input: name[]=[
{
private "_name";
private "_content";
private "_result";
testIdentifier _this; //get name without []
_name=_this get 0;
_this exploreFor "[^=]*="; //get everything until = (including =)
_this ignore 0;
eatWS _this;
if (_this exploreFor "{") then
{
_content=_this call _ReadSimpleValue;
if (!isnil "_content") then
{
if (_this exploreFor ";") then
{
eatWS (_this ignore 1);
_result=+[_name,"array",_content];
}
else
{
_result=nil;
};
}
else
{
_result=nil;
};
}
else
{
_result=nil;
};
_result
};
_ReadSimpleItem= //input: name=
{
private ["_name","_content","_result"];
testIdentifier _this;
_name=_this get 0;
eatWS (eatWS _this ignore 1);
_content=_this call _ReadSimpleValue;
if (!isnil "_content") then
{
if (_this exploreFor ";") then
{
eatWS (_this ignore 1);
_result=+[_name,"simple",_content];
}
else
{
_result=nil;
};
}
else
{
_result=nil;
};
_result
};
//localfunction _ReadRawClass
//param - IOStream, return Array, that represents inside of class (items)
_ReadRawClass=
{
private ["_loop","_item","_result"];
_result=+[];
_loop=true;
while {_loop} do
{
eatWS _this;
_item=nil;
switch (true) do
{
if (not (_this exploreFor "//[^\x0A^\x0D]*[\x0A\x0D]*")) then
{
case (_this exploreFor "class "): //in case class word
{
_this ignore 0;
if ((_this exploreFor "[_a-zA-Z0-9]+[\S]*;") || (_this exploreFor "[_a-zA-Z0-9]+[\S]*:") ) then
{
if ((_this exploreFor "[_a-zA-Z0-9]+[\S]*;")) then
{
_item=_this call _ReadEmptyClass ;
}
else
{
_item=_this call _ReadDerivedClass ;
};
}
else
{
_item=_this call _ReadClass ;
};
if (isnil "_item") then {_loop=false;};
};
case (_this exploreFor "[_a-zA-Z][_a-zA-Z0-9]*\[\]_*="): //in case "name[]=" (_ - is whitespace without new line)
{
_item=_this call _ReadArray ;
if (isnil "_item") then {_loop=false;};
};
case (_this exploreFor "[_a-zA-Z][_a-zA-Z0-9]*_*="): //in case "name=" (_ - is whitespace without new line)
{
_item=_this call _ReadSimpleItem ;
if (isnil "_item") then {_loop=false;};
};
default //in case we don't know
{
_loop=false;
};
}else{_this ignore 0;};
};
if !(isnil "_item") then { _result set [count _result,_item];};
};
_result
};
private "_content";
_content=_this call _ReadRawClass;
if (!eof(_this)) then {_content=nil;};
_content
};
paramFileReadPrep={ // "path_to_file" call paramFileReadPrep
private ["_controlscript","_result","_output","_input","_memo","_cesta","_cestarozrez"];
_cestarozrez = splitpath _this;
_input = (_cestarozrez @ 2)+(_cestarozrez @ 3);
_cesta = (_cestarozrez @ 0)+(_cestarozrez @ 1);
_controlscript =
{
private "_soubor";
private "_file";
private "_memory";
private "_zpracovano";
_cestanew = _cesta + _this;
_memory = openMemoryStream "_memory";
_soubor = openFile[_cestanew,1];
while {!eof (_soubor)} do
{
_file=getLine _soubor;
_memory<<_file;
_memory<<eoln;
};
_zpracovano = getbuffer _memory;
_zpracovano
};
_output = _input preprocFile _controlScript;
_memo = openMemoryStream _output;
_result = _memo call paramFileRead;
_result
};
paramFileWrite={ //[stream, paramFileArray, arrayFormating]
private "_writeClass";
private "_writeArray";
private "_writeVariable";
private "_writeValue";
private "_writeInsideClass";
private "_out";
private "_block";
private "_formatovani";
_out=_this select 0;
_level=0;
_block="";
_countargu = count _this;
if (_countargu == 3) then
{
_formatovani = _this select 2;
}
else
{
_formatovani = "row";
};
_writeValue={ //_this input is any variable
switch (typeName _this) do
{
case "STRING":
{
if (_this=="") then
{
_out<<""""<<_this<<"""";
}
else
{
if (_this @ [0,7]=="#$flag:") then
{
_out<<_this @ [7];
}
else
{
_out<<""""<<_this<<"""";
};
};
};
case "SCALAR":{_out<<str(_this);};
case "ARRAY":
{
switch (_formatovani) do
{
case "row":
{
_out<<"{";
private "_comma";
_comma="";
{
_out<<_comma;
_x call _writeValue;
_comma=",";
} forEach _this;
_out<<"}";
};
case "column":
{
_out<<eoln<<_block<<"{";
private "_comma";
_comma="";
{
_out<<_comma<<eoln<<_block+" ";
_x call _writeValue;
_comma=",";
} forEach _this;
_out<<eoln<<_block<<"}";
};
};
};
default {_out<<""""<<str(_this)<<"""";};
};
};
_writeVariable={ //_this=[name,"simple",value]
_out<<_block<<(_this select 0)<<"=";
(_this select 2) call _writeValue;
_out<<";"<<eoln;
};
_writeArray={ //_this=[name,"array",[values]]
_out<<_block<<(_this select 0)<<"[]=";
(_this select 2) call _writeValue;
_out<<";"<<eoln;
};
_writeClass={ //_this=[name,"class",[values]]
if ((count _this)== 4) then
{
_out<<_block<<"class "<<(_this select 0)<<": "<<(_this select 3)<<eoln<<_block<<"{"<<eoln;
}
else
{
_out<<_block<<"class "<<(_this select 0)<<eoln<<_block<<"{"<<eoln;
};
_block=_block+" ";
_writeInsideClass forEach (_this select 2);
_block=_block @ [0,count _block-4];
_out<<_block<<"};"<<eoln;
};
_writeEmptyClass={ //_this=[name,"Empty class"]
_out<<_block<<"class "<<(_this select 0)<<";"<<eoln;
};
_writeInsideClass={ //_x=[name,type,value(s)]
private "_this";
_this=_x;
switch (_this select 1) do
{
case "class": _writeClass;
case "EmptyClass": _writeEmptyClass;
case "array": _writeArray;
case "simple": _writeVariable;
};
};
_writeInsideClass forEach (_this select 1);
};
paramFileFind={ //_this=[paramFile,name1,name2,name3...]
private "_pfile";
private "_result";
private "_paramFilePartialFind";
_paramFilePartialFind={ //_this=[paramFile,name];
private "_i";
private "_found";
private "_pfile";
_pfile=_this select 0;
for "_i" from 0 to count _pfile do
{
if ((_pfile select _i) select 0==_this select 1) then
{
_found=_pfile select _i;
_i=nil;
};
};
_found
};
_pfile=_this select 0;
{
if (!isnil "_pfile" && typeName _x=="STRING") then
{
_result=([_pfile,_x] call _paramFilePartialFind) ;
_pfile=_result select 2
};
}
forEach _this;
_result
}; | true |
b7e494648ec3a0e6e79fc78fa5a9d878ab95c3c1 | C++ | Shinakshi09/Python | /Programming_Practise-main/C++ Practise/XOR_Operation_Bitwise_Operator.cpp | UTF-8 | 145 | 2.578125 | 3 | [] | no_license | /*
2. OR Operation
*/
#include <iostream>
using namespace std;
int main()
{
int x = 5, y = 6, z;
z = xˆy;
cout << z << endl;
} | true |
eb0f105a21e9815785e5701a90e77c2abf089807 | C++ | bmvskii/DataStructuresAndAlgorithms | /Common data structures/5/double_queue_circular_array_impl.cpp | UTF-8 | 2,388 | 3.265625 | 3 | [] | no_license | #include "double_queue.hpp"
#include <cassert>
struct DoubleArrayQueue
{
double ** m_pData;
int * m_pSizes;
int m_Size;
int m_FrontIndex;
int m_BackIndex;
};
DoubleArrayQueue * DoubleArrayQueueCreate ( int _fixedSize )
{
assert( _fixedSize > 0 );
DoubleArrayQueue * pNewQueue = new DoubleArrayQueue;
pNewQueue->m_Size = _fixedSize + 1;
pNewQueue->m_pData = new double *[ pNewQueue->m_Size ];
pNewQueue->m_pSizes = new int[pNewQueue->m_Size];
DoubleArrayQueueClear( * pNewQueue );
return pNewQueue;
}
void DoubleArrayQueueDestroy ( DoubleArrayQueue * _pQueue )
{
delete[] _pQueue->m_pData;
delete _pQueue;
}
void DoubleArrayQueueClear ( DoubleArrayQueue & _queue )
{
_queue.m_FrontIndex = 0;
_queue.m_BackIndex = 0;
}
int DoubleArrayQueueSize ( const DoubleArrayQueue & _queue )
{
// |-|-|-|-|-|-| |-|-|-|-|-|-|
// F B B F
return ( _queue.m_FrontIndex <= _queue.m_BackIndex ) ?
_queue.m_BackIndex - _queue.m_FrontIndex :
_queue.m_BackIndex + _queue.m_Size - _queue.m_FrontIndex;
}
int DoubleArrayQueueFrontSize(const DoubleArrayQueue & _queue)
{
return _queue.m_pSizes[_queue.m_FrontIndex];
}
bool DoubleArrayQueueIsEmpty ( const DoubleArrayQueue & _queue )
{
return DoubleArrayQueueSize( _queue ) == 0;
}
bool DoubleArrayQueueIsFull ( const DoubleArrayQueue & _queue )
{
return DoubleArrayQueueSize( _queue ) == ( _queue.m_Size - 1 );
}
int DoubleArrayQueueNextIndex ( const DoubleArrayQueue & _queue, int _index )
{
int index = _index + 1;
if ( index == _queue.m_Size )
index = 0;
return index;
}
void DoubleArrayQueuePush ( DoubleArrayQueue & _queue, double * _value, int _size )
{
assert( ! DoubleArrayQueueIsFull( _queue ) );
_queue.m_pData[ _queue.m_BackIndex ] = _value;
_queue.m_pSizes[_queue.m_BackIndex] = _size;
_queue.m_BackIndex = DoubleArrayQueueNextIndex( _queue, _queue.m_BackIndex );
}
void DoubleArrayQueuePop ( DoubleArrayQueue & _queue )
{
assert( ! DoubleArrayQueueIsEmpty( _queue ) );
_queue.m_FrontIndex = DoubleArrayQueueNextIndex( _queue, _queue.m_FrontIndex );
}
double * DoubleArrayQueueFrontArray ( const DoubleArrayQueue & _queue )
{
assert( ! DoubleArrayQueueIsEmpty( _queue ) );
return _queue.m_pData[ _queue.m_FrontIndex ];
} | true |
d336a9943d999656dfb2848f43f4811845c9c719 | C++ | plaice/Williams | /09/interruptible_thread_tm.h | UTF-8 | 1,640 | 3.203125 | 3 | [
"BSL-1.0"
] | permissive | // Listing 9.11, pp.293-294, Williams.
// Using a timeout in interruptible_wait for
// std::condition_variable.
#include <condition_variable>
#include <atomic>
#include <boost/thread/thread.hpp>
class interrupt_flag
{
std::atomic<bool> flag;
std::condition_variable* thread_cond;
std::mutex set_clear_mutex;
public:
interrupt_flag():
thread_cond(0)
{}
void set()
{
flag.store(true,std::memory_order_relaxed);
std::lock_guard<std::mutex> lk(set_clear_mutex);
if(thread_cond)
{
thread_cond->notify_all();
}
}
bool is_set() const
{
return flag.load(std::memory_order_relaxed);
}
void set_condition_variable(std::condition_variable& cv)
{
std::lock_guard<std::mutex> lk(set_clear_mutex);
thread_cond=&cv;
}
void clear_condition_variable()
{
std::lock_guard<std::mutex> lk(set_clear_mutex);
thread_cond=0;
}
};
thread_local interrupt_flag this_thread_interrupt_flag;
struct clear_cv_on_destruct
{
~clear_cv_on_destruct()
{
this_thread_interrupt_flag.clear_condition_variable();
}
};
void interruption_point()
{
if(this_thread_interrupt_flag.is_set())
{
throw boost::thread_interrupted();
}
}
void interruptible_wait(std::condition_variable& cv,
std::unique_lock<std::mutex>& lk)
{
interruption_point();
this_thread_interrupt_flag.set_condition_variable(cv);
clear_cv_on_destruct guard;
interruption_point();
cv.wait_for(lk,std::chrono::milliseconds(1));
interruption_point();
}
| true |
9046505c9c2a45c8bd811cc0fc9f11b1847b2a52 | C++ | potenbtlife/wxWidgets_All | /timeMgr/timeMgr/20150324_bak/CDBSqlite.h | GB18030 | 4,457 | 3.421875 | 3 | [] | no_license | #ifndef ASTMANAGER_CDBSQLITE_H
#define ASTMANAGER_CDBSQLITE_H
#include "sqlite3.h"
#include<string>
#include<iostream>
using namespace std;
const int RET_OK = 0; //ִгɹֵ
const int RET_FAIL = -1; //ִʧֵܷ
class CDBSqlite
{
public:
//ȱʡ캯
CDBSqlite();
/**
*@Description: 캯ʼdbnameԱ
*@param[IN] dbnameݿ
*/
CDBSqlite(string& dbname);
/**
*@Description: 캯ʼԱ
*@param[IN] dbnameݿ
*@parmm[IN] sql: ִsql
*/
CDBSqlite(string& dbname, string& sql);
//
~CDBSqlite();
/**
*@Description: sqlite3 ӣʹڲԱm_dbnameҪǷѾʼ
*@return SQLITE_OK ɹ 0
*/
int open();
/**
*@Description: sqlite3 ӣʹòݿ
*@return SQLITE_OK ɹ 0
*/
int open(string& dbname);
/**
*@DescriptionʼãԱʹóԱm_pdbm_sqlҪǷѾʼ
*@return SQLITE_OK : ɹ 0
*/
int prepare();
/**
*@DescriptonʼãԱ
*@param[IN] sql: sql
*@param[IN] length: sqlij
*@return SQLITE_OK : ɹ 0
*/
int prepare(string& sql, int length);
/**
*@Description: ַ
*@param[in] index : Ҫֵsqlţ1ʼ
*@param[in] value : ֵ
*@param[in] length : value ռõֽǸȡ
*@param[in] dtfunc : valueΪ SQLITE_TRANSIENT SQLITE_STATIC
*/
int bindString(int index, const char* value, int length, void dtfunc(void*) );
/**
*@Description: doubleͱ
*@param[in] index : Ҫֵsqlţ1ʼ
*@param[in] value : ֵ
*/
int bindDouble(int index, double value);
/**
*@Description: intͱ
*@param[in] index : Ҫֵsqlţ1ʼ
*@param[in] value : ֵ
*/
int CDBSqlite::bindInt(int index, int value);
/**
*@Description:ִгҪǷЧзIJѯظִλȡ
*@return 1:һ¼0ɹִϣ -1 ִд
*/
int step();
/**
*@Description: ȡijһе
*@param[IN] index: еţ0ʼ
*@return ȡͣSQLITE_INTEGER : 1; SQLITE_FLOAT : 2;SQLITE_TEXT : 3; SQLITE3_TEXT : 3; SQLITE_BLOB : 4; SQLITE_NULL : 5
*/
int getColumnType(int index);
/**
*@Description: ȡijһе
*@param[IN] index: еţ0ʼ
*@return
*/
string getColumnName(int index);
/**
*@DescriptionȡijһУintֵͣ
*@param[IN] index: еţ0ʼ
*@return: ȡֵ
*/
int getColumnInt(int index);
/**
*@DescriptionȡijһУdoubleֵͣ
*@param[IN] index: еţ0ʼ
*@return: ȡֵ
*/
double getColumnDouble(int index);
/**
*@DescriptionȡijһУcharֵͣתΪstring
*@param[IN] index: еţ0ʼ
*@return: ȡֵ
*/
string getColumnString(int index);
/**
*@Description: óԱm_sqlֵ
*@param[in] sql : sql
*/
void setSql(string sql)
{
m_sql = sql;
}
/**
*@Description: ȡԱm_sqlֵ
*@return m_sqlֵ
*/
string getSql()
{
return m_sql;
}
//ͷsqlite3_stmt* ָĶ
int finalize(){
return sqlite3_finalize(m_pStmt);
}
int close(){
return sqlite3_close(m_pdb);
}
int retCode; //һִsqliteķֵΪõ֪
string errString; //ַ
protected:
sqlite3* m_pdb; //sqlite3
sqlite3_stmt* m_pStmt; //
string m_dbname; //sqlite3ݿ
string m_sql; //ִsql
};
#endif // ASTMANAGER_CDBSQLITE_H | true |
761924ed89c7e79d39d148a3805549d6de3d39a5 | C++ | ItemZheng/PAT_Advanced_Level_Answer | /1044.cpp | UTF-8 | 1,097 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
// 无坑,就像一个滑动窗口一样,如果小于K,就 end++; 不然就 begin++; 然后评估当前的值是否合适
int main(){
int N, K;
cin >> N >> K;
int number[N];
for(int i = 0; i < N; i++){
cin >> number[i];
}
int min = -1;
vector<pair<int, int>> idx_pairs;
int begin = 0, end = -1;
int sum = 0;
while (true){
if(sum < K){
end++;
if(end >= N){
break;
}
sum = sum + number[end];
} else {
sum = sum - number[begin++];
}
if(sum >= K){
if(min == -1 || (sum < min)){
idx_pairs.clear();
min = sum;
idx_pairs.emplace_back(begin, end);
} else if(sum == min){
idx_pairs.emplace_back(begin, end);
}
}
}
for(int i = 0; i < idx_pairs.size(); i++){
cout << idx_pairs[i].first + 1 << "-" << idx_pairs[i].second + 1 << endl;
}
} | true |
4acdac128f95bf934c082e553eeebc1f46d912bc | C++ | arc80/plywood | /repos/plywood/src/runtime/ply-runtime/container/BlockList.h | UTF-8 | 8,260 | 2.6875 | 3 | [
"MIT"
] | permissive | /*------------------------------------
///\ Plywood C++ Framework
\\\/ https://plywood.arc80.com/
------------------------------------*/
#pragma once
#include <ply-runtime/Core.h>
#include <ply-runtime/container/Reference.h>
#include <ply-runtime/string/String.h>
#include <ply-runtime/container/LambdaView.h>
namespace ply {
struct OutStream;
struct BlockList {
static const u32 DefaultBlockSize = 2048;
struct WeakRef;
//--------------------------------------
// Blocks are allocated on the heap, and the block footer is located contiguously in memory
// immediately following the block data.
//--------------------------------------
struct Footer {
u64 fileOffset = 0; // Total number of bytes used in all preceding blocks
Reference<Footer> nextBlock;
Footer* prevBlock = nullptr;
char* bytes = nullptr;
u32 startOffset = 0;
u32 numBytesUsed = 0; // Number of bytes in this block that contain valid data
u32 blockSize = 0; // Total number of bytes allocated for this block
mutable s32 refCount = 0;
PLY_DLL_ENTRY void onRefCountZero();
PLY_INLINE void incRef() {
this->refCount++;
}
PLY_INLINE void decRef() {
PLY_ASSERT(this->refCount > 0);
if (--this->refCount == 0) {
this->onRefCountZero();
}
}
PLY_INLINE char* start() const {
return this->bytes + this->startOffset;
}
PLY_INLINE char* unused() const {
return this->bytes + this->numBytesUsed;
}
PLY_INLINE char* end() const {
return this->bytes + this->blockSize;
}
PLY_INLINE u32 offsetOf(char* byte) {
uptr ofs = byte - this->bytes;
PLY_ASSERT(ofs <= this->numBytesUsed);
return (u32) ofs;
}
PLY_INLINE StringView viewUsedBytes() const {
return {this->start(), this->numBytesUsed - this->startOffset};
}
PLY_INLINE MutableStringView viewUnusedBytes() {
return {this->unused(), this->blockSize - this->numBytesUsed};
}
// Returns a WeakRef to next block, and the next byte after the last byte in this block,
// taking the difference in fileOffsets into account since it's possible for adjacent blocks
// to overlap.
PLY_DLL_ENTRY WeakRef weakRefToNext() const;
};
//--------------------------------------
// WeakRef
//--------------------------------------
struct WeakRef {
Footer* block = nullptr;
char* byte = nullptr;
PLY_INLINE WeakRef() {
}
PLY_INLINE WeakRef(const WeakRef& other) : block{other.block}, byte{other.byte} {
}
PLY_INLINE WeakRef(Footer* block, char* byte) : block{block}, byte{byte} {
PLY_ASSERT(uptr(byte - block->bytes) <= block->blockSize);
}
PLY_INLINE WeakRef(Footer* block, u32 offset) : block{block}, byte{block->bytes + offset} {
PLY_ASSERT(offset <= block->blockSize);
}
PLY_INLINE void operator=(const WeakRef& other) {
this->block = other.block;
this->byte = other.byte;
}
PLY_INLINE bool operator!=(const WeakRef& other) const {
return this->block != other.block || this->byte != other.byte;
}
PLY_INLINE WeakRef normalized() const {
if (this->block->nextBlock && (this->byte == this->block->unused())) {
return {this->block->nextBlock, this->block->start()};
}
return *this;
}
};
//--------------------------------------
// Ref
//--------------------------------------
struct Ref {
Reference<Footer> block;
char* byte = nullptr;
PLY_INLINE Ref() {
}
PLY_INLINE Ref(const Ref& other) : block{other.block}, byte{other.byte} {
}
PLY_INLINE Ref(Ref&& other) : block{std::move(other.block)}, byte{other.byte} {
}
PLY_INLINE Ref(Footer* block) : block{block}, byte{block->bytes} {
}
PLY_INLINE Ref(Footer* block, char* byte) : block{block}, byte{byte} {
PLY_ASSERT(uptr(byte - block->bytes) <= block->blockSize);
}
PLY_INLINE Ref(Reference<Footer>&& block, char* byte)
: block{std::move(block)}, byte{byte} {
PLY_ASSERT(uptr(byte - this->block->bytes) <= this->block->blockSize);
}
PLY_INLINE Ref(const WeakRef& weakRef) : block{weakRef.block}, byte{weakRef.byte} {
}
PLY_INLINE operator WeakRef() const {
return {this->block, this->byte};
}
PLY_INLINE void operator=(const WeakRef& weakRef) {
this->block = weakRef.block;
this->byte = weakRef.byte;
}
PLY_INLINE void operator=(Ref&& other) {
this->block = std::move(other.block);
this->byte = other.byte;
}
};
//--------------------------------------
// RangeForIterator
//--------------------------------------
struct RangeForIterator {
WeakRef curPos;
WeakRef endPos;
RangeForIterator(const WeakRef& startPos, const WeakRef& endPos = {})
: curPos{startPos}, endPos{endPos} {
}
PLY_INLINE RangeForIterator& begin() {
return *this;
}
PLY_INLINE RangeForIterator& end() {
return *this;
}
PLY_INLINE void operator++() {
this->curPos = this->curPos.block->weakRefToNext();
}
PLY_INLINE bool operator!=(const RangeForIterator&) const {
return this->curPos != this->endPos;
}
PLY_INLINE StringView operator*() const {
return StringView::fromRange(this->curPos.byte,
(this->curPos.block == this->endPos.block)
? this->endPos.byte
: this->curPos.block->unused());
}
};
//--------------------------------------
// Static member functions
//--------------------------------------
static PLY_DLL_ENTRY Reference<Footer> createBlock(u32 numBytes = DefaultBlockSize);
static PLY_DLL_ENTRY Reference<Footer> createOverlayBlock(const WeakRef& pos, u32 numBytes);
static PLY_DLL_ENTRY Footer* appendBlock(Footer* block, u32 numBytes = DefaultBlockSize);
static PLY_DLL_ENTRY void appendBlockWithRecycle(Reference<Footer>& block,
u32 numBytes = DefaultBlockSize);
static PLY_INLINE RangeForIterator iterateOverViews(const WeakRef& start,
const WeakRef& end = {}) {
return {start, end};
}
static PLY_DLL_ENTRY u32 jumpToNextBlock(WeakRef* weakRef);
static PLY_DLL_ENTRY u32 jumpToPrevBlock(WeakRef* weakRef);
/*!
Returns a `String` that owns a newly allocated block of memory containing a copy of the data
contained in some (possible multiple) blocks between the `start` and `end` cursors. If `end`
is not specified, the returned string contains a copy of the data from `start` up to the end
of the block list.
The first argument will be reset to an empty `Ref` as a result of this call. This enables an
optimization: If `start` is the sole reference to the start of a single `Footer`, no
data is copied; instead, the block's memory block is truncated and ownership is passed
directly to the `String`.
This function is used internally by `StringOutStream::moveToString()`.
*/
static PLY_DLL_ENTRY String toString(Ref&& start, const WeakRef& end = {});
//--------------------------------------
// BlockList object
//--------------------------------------
Reference<Footer> head;
Footer* tail = nullptr;
PLY_DLL_ENTRY BlockList();
PLY_DLL_ENTRY ~BlockList();
PLY_DLL_ENTRY char* appendBytes(u32 numBytes);
PLY_DLL_ENTRY void popLastBytes(u32 numBytes);
PLY_INLINE WeakRef end() const {
return {tail, tail->unused()};
}
};
} // namespace ply
| true |
cd756dc9a9c4ee340a3077af50d406b2fc627d08 | C++ | iridium-browser/iridium-browser | /third_party/eigen3/src/Eigen/src/Geometry/OrthoMethods.h | UTF-8 | 11,255 | 2.828125 | 3 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"MPL-2.0",
"Minpack"
] | permissive | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ORTHOMETHODS_H
#define EIGEN_ORTHOMETHODS_H
#include "./InternalHeaderCheck.h"
namespace Eigen {
namespace internal {
// Vector3 version (default)
template<typename Derived, typename OtherDerived, int Size>
struct cross_impl
{
typedef typename ScalarBinaryOpTraits<typename internal::traits<Derived>::Scalar,typename internal::traits<OtherDerived>::Scalar>::ReturnType Scalar;
typedef Matrix<Scalar,MatrixBase<Derived>::RowsAtCompileTime,MatrixBase<Derived>::ColsAtCompileTime> return_type;
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
return_type run(const MatrixBase<Derived>& first, const MatrixBase<OtherDerived>& second)
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,3)
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,3)
// Note that there is no need for an expression here since the compiler
// optimize such a small temporary very well (even within a complex expression)
typename internal::nested_eval<Derived,2>::type lhs(first.derived());
typename internal::nested_eval<OtherDerived,2>::type rhs(second.derived());
return return_type(
numext::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)),
numext::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)),
numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0))
);
}
};
// Vector2 version
template<typename Derived, typename OtherDerived>
struct cross_impl<Derived, OtherDerived, 2>
{
typedef typename ScalarBinaryOpTraits<typename internal::traits<Derived>::Scalar,typename internal::traits<OtherDerived>::Scalar>::ReturnType Scalar;
typedef Scalar return_type;
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
return_type run(const MatrixBase<Derived>& first, const MatrixBase<OtherDerived>& second)
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,2);
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,2);
typename internal::nested_eval<Derived,2>::type lhs(first.derived());
typename internal::nested_eval<OtherDerived,2>::type rhs(second.derived());
return numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0));
}
};
} // end namespace internal
/** \geometry_module \ingroup Geometry_Module
*
* \returns the cross product of \c *this and \a other. This is either a scalar for size-2 vectors or a size-3 vector for size-3 vectors.
*
* This method is implemented for two different cases: between vectors of fixed size 2 and between vectors of fixed size 3.
*
* For vectors of size 3, the output is simply the traditional cross product.
*
* For vectors of size 2, the output is a scalar.
* Given vectors \f$ v = \begin{bmatrix} v_1 & v_2 \end{bmatrix} \f$ and \f$ w = \begin{bmatrix} w_1 & w_2 \end{bmatrix} \f$,
* the result is simply \f$ v\times w = \overline{v_1 w_2 - v_2 w_1} = \text{conj}\left|\begin{smallmatrix} v_1 & w_1 \\ v_2 & w_2 \end{smallmatrix}\right| \f$;
* or, to put it differently, it is the third coordinate of the cross product of \f$ \begin{bmatrix} v_1 & v_2 & v_3 \end{bmatrix} \f$ and \f$ \begin{bmatrix} w_1 & w_2 & w_3 \end{bmatrix} \f$.
* For real-valued inputs, the result can be interpreted as the signed area of a parallelogram spanned by the two vectors.
*
* \note With complex numbers, the cross product is implemented as
* \f$ (\mathbf{a}+i\mathbf{b}) \times (\mathbf{c}+i\mathbf{d}) = (\mathbf{a} \times \mathbf{c} - \mathbf{b} \times \mathbf{d}) - i(\mathbf{a} \times \mathbf{d} + \mathbf{b} \times \mathbf{c})\f$
*
* \sa MatrixBase::cross3()
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
#ifndef EIGEN_PARSED_BY_DOXYGEN
typename internal::cross_impl<Derived, OtherDerived>::return_type
#else
inline std::conditional_t<SizeAtCompileTime==2, Scalar, PlainObject>
#endif
MatrixBase<Derived>::cross(const MatrixBase<OtherDerived>& other) const
{
return internal::cross_impl<Derived, OtherDerived>::run(*this, other);
}
namespace internal {
template< int Arch,typename VectorLhs,typename VectorRhs,
typename Scalar = typename VectorLhs::Scalar,
bool Vectorizable = bool((VectorLhs::Flags&VectorRhs::Flags)&PacketAccessBit)>
struct cross3_impl {
EIGEN_DEVICE_FUNC static inline typename internal::plain_matrix_type<VectorLhs>::type
run(const VectorLhs& lhs, const VectorRhs& rhs)
{
return typename internal::plain_matrix_type<VectorLhs>::type(
numext::conj(lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1)),
numext::conj(lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2)),
numext::conj(lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0)),
0
);
}
};
}
/** \geometry_module \ingroup Geometry_Module
*
* \returns the cross product of \c *this and \a other using only the x, y, and z coefficients
*
* The size of \c *this and \a other must be four. This function is especially useful
* when using 4D vectors instead of 3D ones to get advantage of SSE/AltiVec vectorization.
*
* \sa MatrixBase::cross()
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC inline typename MatrixBase<Derived>::PlainObject
MatrixBase<Derived>::cross3(const MatrixBase<OtherDerived>& other) const
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived,4)
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,4)
typedef typename internal::nested_eval<Derived,2>::type DerivedNested;
typedef typename internal::nested_eval<OtherDerived,2>::type OtherDerivedNested;
DerivedNested lhs(derived());
OtherDerivedNested rhs(other.derived());
return internal::cross3_impl<Architecture::Target,
internal::remove_all_t<DerivedNested>,
internal::remove_all_t<OtherDerivedNested>>::run(lhs,rhs);
}
/** \geometry_module \ingroup Geometry_Module
*
* \returns a matrix expression of the cross product of each column or row
* of the referenced expression with the \a other vector.
*
* The referenced matrix must have one dimension equal to 3.
* The result matrix has the same dimensions than the referenced one.
*
* \sa MatrixBase::cross() */
template<typename ExpressionType, int Direction>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
const typename VectorwiseOp<ExpressionType,Direction>::CrossReturnType
VectorwiseOp<ExpressionType,Direction>::cross(const MatrixBase<OtherDerived>& other) const
{
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(OtherDerived,3)
EIGEN_STATIC_ASSERT((internal::is_same<Scalar, typename OtherDerived::Scalar>::value),
YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
typename internal::nested_eval<ExpressionType,2>::type mat(_expression());
typename internal::nested_eval<OtherDerived,2>::type vec(other.derived());
CrossReturnType res(_expression().rows(),_expression().cols());
if(Direction==Vertical)
{
eigen_assert(CrossReturnType::RowsAtCompileTime==3 && "the matrix must have exactly 3 rows");
res.row(0) = (mat.row(1) * vec.coeff(2) - mat.row(2) * vec.coeff(1)).conjugate();
res.row(1) = (mat.row(2) * vec.coeff(0) - mat.row(0) * vec.coeff(2)).conjugate();
res.row(2) = (mat.row(0) * vec.coeff(1) - mat.row(1) * vec.coeff(0)).conjugate();
}
else
{
eigen_assert(CrossReturnType::ColsAtCompileTime==3 && "the matrix must have exactly 3 columns");
res.col(0) = (mat.col(1) * vec.coeff(2) - mat.col(2) * vec.coeff(1)).conjugate();
res.col(1) = (mat.col(2) * vec.coeff(0) - mat.col(0) * vec.coeff(2)).conjugate();
res.col(2) = (mat.col(0) * vec.coeff(1) - mat.col(1) * vec.coeff(0)).conjugate();
}
return res;
}
namespace internal {
template<typename Derived, int Size = Derived::SizeAtCompileTime>
struct unitOrthogonal_selector
{
typedef typename plain_matrix_type<Derived>::type VectorType;
typedef typename traits<Derived>::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar,2,1> Vector2;
EIGEN_DEVICE_FUNC
static inline VectorType run(const Derived& src)
{
VectorType perp = VectorType::Zero(src.size());
Index maxi = 0;
Index sndi = 0;
src.cwiseAbs().maxCoeff(&maxi);
if (maxi==0)
sndi = 1;
RealScalar invnm = RealScalar(1)/(Vector2() << src.coeff(sndi),src.coeff(maxi)).finished().norm();
perp.coeffRef(maxi) = -numext::conj(src.coeff(sndi)) * invnm;
perp.coeffRef(sndi) = numext::conj(src.coeff(maxi)) * invnm;
return perp;
}
};
template<typename Derived>
struct unitOrthogonal_selector<Derived,3>
{
typedef typename plain_matrix_type<Derived>::type VectorType;
typedef typename traits<Derived>::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
EIGEN_DEVICE_FUNC
static inline VectorType run(const Derived& src)
{
VectorType perp;
/* Let us compute the crossed product of *this with a vector
* that is not too close to being colinear to *this.
*/
/* unless the x and y coords are both close to zero, we can
* simply take ( -y, x, 0 ) and normalize it.
*/
if((!isMuchSmallerThan(src.x(), src.z()))
|| (!isMuchSmallerThan(src.y(), src.z())))
{
RealScalar invnm = RealScalar(1)/src.template head<2>().norm();
perp.coeffRef(0) = -numext::conj(src.y())*invnm;
perp.coeffRef(1) = numext::conj(src.x())*invnm;
perp.coeffRef(2) = 0;
}
/* if both x and y are close to zero, then the vector is close
* to the z-axis, so it's far from colinear to the x-axis for instance.
* So we take the crossed product with (1,0,0) and normalize it.
*/
else
{
RealScalar invnm = RealScalar(1)/src.template tail<2>().norm();
perp.coeffRef(0) = 0;
perp.coeffRef(1) = -numext::conj(src.z())*invnm;
perp.coeffRef(2) = numext::conj(src.y())*invnm;
}
return perp;
}
};
template<typename Derived>
struct unitOrthogonal_selector<Derived,2>
{
typedef typename plain_matrix_type<Derived>::type VectorType;
EIGEN_DEVICE_FUNC
static inline VectorType run(const Derived& src)
{ return VectorType(-numext::conj(src.y()), numext::conj(src.x())).normalized(); }
};
} // end namespace internal
/** \geometry_module \ingroup Geometry_Module
*
* \returns a unit vector which is orthogonal to \c *this
*
* The size of \c *this must be at least 2. If the size is exactly 2,
* then the returned vector is a counter clock wise rotation of \c *this, i.e., (-y,x).normalized().
*
* \sa cross()
*/
template<typename Derived>
EIGEN_DEVICE_FUNC typename MatrixBase<Derived>::PlainObject
MatrixBase<Derived>::unitOrthogonal() const
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
return internal::unitOrthogonal_selector<Derived>::run(derived());
}
} // end namespace Eigen
#endif // EIGEN_ORTHOMETHODS_H
| true |
0e01c0c8f686b504d4fd42c33781545bdd71e0f4 | C++ | tylerAllenGithub/University | /course.cpp | UTF-8 | 2,058 | 3.5 | 4 | [] | no_license | #ifndef COURSE_C
#define COURSE_C
#include <iostream>
#include <string>
using namespace std;
#include "course.h"
long course::nextCRN=200;
//initialize static variable
course::course()//takes no parameters
{//initialize
CRN=nextCRN++;
maxAvailableSeats=0;
name=" ";
departID=0;
assignedSeats=0;
isTaughtBy=0;
}
course::course(string n, long depID, long taught, int maxSeats)
{
name=n;
departID=depID;
isTaughtBy=taught;
maxAvailableSeats=maxSeats;
CRN=nextCRN++;
assignedSeats=0;
//assign global variables to constructor arguments
}
void course::setCRN(long CRN)//takes 1 long
{
this->CRN=CRN;//sets this variable to argument
}
long course::getCRN()//takes no parameters
{
return CRN;
}
void course::setMaxAvailableSeats(int maxAvailableSeats)
{
this->maxAvailableSeats=maxAvailableSeats;//sets this variable to argument
}
int course::getMaxAvailableSeats()//takes no parameters
{
return maxAvailableSeats;
}
void course::setName(string name)//takes 1 string
{
this->name=name;//sets this variable to argument
}
string course::getName()//takes no parameters
{
return name;
}
void course::setDepartID(long departID)//takes 1 long
{
this->departID=departID;//sets this variable to argument
}
long course::getDepartID()//takes no parameters
{
return departID;
}
void course::setAssignedSeats(long assignedSeats)//takes 1 long
{
this->assignedSeats=assignedSeats;//sets this variable to argument
}
long course::getAssignedSeats()//takes no parameters
{
return assignedSeats;
}
void course::setIsTaughtBy(long isTaughtBy)//takes 1 long
{
this->isTaughtBy=isTaughtBy;//sets this variable to argument
}
long course::getIsTaughtBy()//takes no parameters
{
return isTaughtBy;
}
long course::getNextCRN()//takes no parameters
{
return nextCRN;
}
void course::print() const//takes no parameters
{
cout<<"The CRN is: "<<CRN<<endl;
cout<<"The Course Name is: "<<name<<endl;
cout<<endl;
}
#endif
| true |
d8135e886dda68fb08b17e1b755a0317639309dc | C++ | chencorey/TopCoder | /SRM247/TriangleType.cpp | UTF-8 | 570 | 3.265625 | 3 | [] | no_license | // https://community.topcoder.com/stat?c=problem_statement&pm=4610&rd=7222
// This problem was used for:
// Single Round Match 247 Round 1 - Division II, Level One
#include <string>
#include <algorithm>
using namespace std;
class TriangleType
{
public:
string type(int a, int b, int c)
{
int hyp = max(max(a, b), c);
int leg1 = min(min(a, b), c);
int leg2 = a+b+c-leg1-hyp;
if(leg1+leg2<=hyp) return "IMPOSSIBLE";
if(leg1*leg1 + leg2*leg2 ==hyp*hyp) return "RIGHT";
else if(leg1*leg1 + leg2*leg2 < hyp*hyp) return "OBTUSE";
else return "ACUTE";
}
};
| true |
ab97b338b934e81f3e4c9323bbf1c2731147747c | C++ | rafalmeisel/Inteligent-Pulsometer | /main.ino | UTF-8 | 3,901 | 2.671875 | 3 | [] | no_license | #include <Adafruit_SSD1306.h>
#include <SoftwareSerial.h>
// range of pulse limits
#define UpperThreshold 750
#define LowerThreshold 700
// lcd display phisical adress
#define OLED_Address 0x3C
// reset pin for lcd display
Adafruit_SSD1306 oled(4);
bool ignoreAanalogValue = false;
bool firstBeatsDetected = false;
unsigned long firstBeatseTime = 0;
unsigned long secondBeatsTime = 0;
unsigned long intervalBeetweenHeartBeats = 0;
int analogValue = 0;
int average = 0;
int sumBpmHistory = 0;
int counterSave = 0;
// variables for displaying pulse graph
int x = 0;
int y = 0;
int lastx = 0;
int lasty = 0;
// heart beats per minutes
int BPM = 0;
// BPM history
const int historyLenght = 10;
int bpmHistory[historyLenght] ={0,0,0,0,0,0,0,0,0,0};
unsigned long currentTime;
// counting time between update history
unsigned long updateHistoryTimeDelay = 5000;
// counting dangereus situation
int alarmCount = 0;
// phone number with AT command
String commandAT = "ATD";
String phoneNumber = "XXX-XXX-XXX";
String endCommandATChar = ";";
String tmpCommandAT = "";
char finalCommandAT[20];
// declaration of pins for receiver and transimiter on Arduino
SoftwareSerial GsmModuleSerial(9, 8);
void setup() {
Serial.begin(9600);
GsmModuleSerial.begin(9600);
// set phisical adress of lcd display to object
oled.begin(SSD1306_SWITCHCAPVCC, OLED_Address);
oled.clearDisplay();
oled.writeFillRect(0,20,128,16,BLACK);
oled.setTextColor(WHITE);
currentTime = millis();
}
void loop(){
// reading value from pulse sensor
analogValue=analogRead(0);
// Heart beat leading edge detected.
if(analogValue > UpperThreshold && ignoreAanalogValue == false){
if(firstBeatsDetected == false){
firstBeatseTime = millis();
firstBeatsDetected = true;
}
else{
secondBeatsTime = millis();
intervalBeetweenHeartBeats = secondBeatsTime - firstBeatseTime;
firstBeatseTime = secondBeatsTime;
}
ignoreAanalogValue = true;
}
// Heart beat trailing edge detected.
if(analogValue < LowerThreshold){
ignoreAanalogValue = false;
}
// computing beats per minute
BPM = (1.0/intervalBeetweenHeartBeats) * 60.0 * 1000;
// check if is time to update history
if((currentTime + updateHistoryTimeDelay) < millis()){
currentTime = millis();
// compute average
sumBpmHistory = 0;
for (int i = 0; i< historyLenght; i++){
sumBpmHistory = sumBpmHistory + bpmHistory[i];
}
average = 0;
average = sumBpmHistory / historyLenght;
// check if current BPM isn't to low
if(BPM < (average * 0.8)){
alarmCount = alarmCount + 1;
}
else{
alarmCount = 0;
// przesuwanie historii - FIFO
for( int i = historyLenght-1; i<0; i--){
bpmHistory[i] = bpmHistory[i-1];
}
bpmHistory[counterSave] = BPM;
counterSave = counterSave + 1;
if(counterSave == historyLenght){
counterSave = 0;
}
}
// Start calling
if(alarmCount > 5){
tmpCommandAT = commandAT + phoneNumber + endCommandATChar;
tmpCommandAT.toCharArray(finalCommandAT, 20);
GsmModuleSerial.write(finalCommandAT);
GsmModuleSerial.println();
}
// Stop calling
else if(alarmCount>8){
GsmModuleSerial.write("ATH;");
GsmModuleSerial.println();
}
}
// display bpm
// clear display
if(x>127){
oled.clearDisplay();
x=0;
lastx=0;
}
// computing hight rate for display on display
y = 50 - (analogValue / 20);
oled.setCursor(0,20);
oled.writeLine(lastx,lasty,x,y,WHITE);
lasty=y;
lastx=x;
oled.setCursor(0,0);
oled.print("BPM: ");
oled.print(BPM);
oled.setCursor(0,20);
oled.print("AVERAGE: ");
oled.print(average);
oled.display();
oled.clearDisplay();
x++;
}
| true |
bbf3a8f1f742aaf25bc9fbfe064c68ba1db395bc | C++ | mishagam/progs | /cc/fracs_test/strtoolm.h | KOI8-R | 8,418 | 2.671875 | 3 | [] | no_license | /**
* \file strtoolm.h
* \brief STL string
*
* :
* .., M.Gambarian
*/
#ifndef mSTRTOOL_H
#define mSTRTOOL_H
#include <stdarg.h>
// #include <string>
#include "newtypes.h"
/**
* remained from Artem - I probably wouldn't define this.
*/
typedef char * pchar;
/**
* mask character which is replaced
*/
extern const char cMaskChar;
/**
* , -
*/
extern C_FUN bool isBlank( char C );
/**
* ,
*/
extern C_FUN bool isBlankStr( const char * p );
/**
*
*/
extern C_FUN char * strEatBlanks( char * S );
/**
*
*/
extern C_FUN char * strEatBlankTail( char * S, int Len = 0 );
/**
*/
extern C_FUN char * strEatBlankHead( char * S );
/**
*
*/
extern C_FUN char * strFindSpace( char * S );
/** ,
*
*/
extern C_FUN char * strFindNoQSpace( char * S );
extern C_FUN char * strChangeChar( char * S, char c1, char c2 );
extern C_FUN char * newString( const char * Str );
extern C_FUN char * StrCopy( char * Dest, const char * Src, int MaxLength );
extern C_FUN char * StrCopyFor( char * Dest, const char * Src, int MaxLength );
extern C_FUN void StrClear( char * S );
extern void StrClear( char * S, unsigned int Size );
/**
*
* -1,
*/
extern C_FUN int StringInArray(
const char * Array, ///<
const char * Str, ///<
int StrLen, ///<
int StrCount ///<
);
/**
*
*/
extern C_FUN char * StrUpperCase( char * D, const char * S );
//
extern C_FUN char * StrLowerCase( char * D, const char * S );
//
extern C_FUN char * StrChangeByMask( char * Str, const char * Mask, char C );
//
extern C_FUN UInt32 CSum( const char * S );
// p_begin p_end
extern C_FUN char *StrCopyBetweenSymbols(
char * Str,
const char * p_begin,
const char * p_end );
/**
*
*/
template <class T>
STATIC_TPL_FUN char * StrCatF( char * Str, const char * Format, T Value )
{
int Offset = strlen( Str );
sprintf( Str + Offset, Format, Value );
return( Str );
}
/**
* maximum length of clmStr string
*/
#define MAXSTRLEN 512
/**
* \brief our string library.
*
* Used local version instead of common clmStr to escape use of STL string.
* STL string didn't work for me with intel compiler.
*/
class clmStr
{
char *buf; ///< clmStr.
private:
/**
* .
*/
void RewriteInternal( const char * FormatStr, va_list L )
{
char * str = new char[ MAXSTRLEN ];
memset( str, 0, MAXSTRLEN );
clear();
int Res = vsnprintf( str, MAXSTRLEN, FormatStr, L );
if( Res > 0 )
{
if( Res > MAXSTRLEN ) // ...
{
printf("**** clmStr.RewriteInternal() operation failed\n");
// return;
} else {
assign( str );
}
}
delete str;
}
/**
* set string value to new string.
*/
void assign(const char *s) {
//printf("clmStr(). assign string %s\n", s);
strncpy(buf, s, MAXSTRLEN-2);
buf[ MAXSTRLEN-2] = 0;
}
/**
* ,
*/
int empty() { return buf[0]==0; }
/**
*
*/
void clear() { buf[0] = 0; }
public:
/**
*
*/
void Clear( void ){ clear(); }
/**
*
* \param S - .
*/
void Set( const char * S ){ assign( S ); }
/**
*
*/
void Rewrite( const char * FormatStr, ... )
{
va_list L;
va_start( L, FormatStr );
RewriteInternal( FormatStr, L );
va_end( L );
}
/**
* const .
*/
const char * c_str() const { return buf; }
/**
* .
*/
clmStr( void ){
//printf("clmStr() constructor called\n");
buf = new char[MAXSTRLEN];
buf[0] = 0;
}
/**
* b
*/
clmStr(const clmStr &b) {
buf = new char[MAXSTRLEN];
assign(b.c_str());
}
/**
* .
*/
virtual ~clmStr() {
//printf("~clmStr called\n");
delete []buf;
}
/**
* printf
*/
clmStr( const char * FormatStr, ... )
{
//printf("~clmStr(Format ...) called\n");
buf = new char[ MAXSTRLEN ];
va_list L;
va_start( L, FormatStr );
RewriteInternal( FormatStr, L );
va_end( L );
}
/**
*
*/
operator const char *(){ return( empty()? "": buf ); }
/**
* = .
*/
clmStr& operator=(clmStr& rhs) {
this->assign( rhs.c_str() );
return *this;
}
/**
* = .
*/
clmStr& operator=(const char *s) {
this->assign( s );
return *this;
}
int Empty() { return empty(); }
};
/**
* string splitter library developed by artem.
* I used it rarely and don't really remember.
* - TAB, LF, CR, space
*/
class clmStrSpaceSplitter
{
protected:
char * Str; ///< S
int mCount; ///<
pchar * S; ///< Str
void CountSubstrings( void );
/**
* .
*/
void Destroy( void )
{
mCount = 0;
DELETE( Str );
DELETE( S );
}
public:
/**
* . .
*/
clmStrSpaceSplitter( void ): Str( 0 ), S( 0 ){}
/**
* . .
*/
~clmStrSpaceSplitter( void ){ Destroy(); }
/**
* .
*/
void Split( const char * FullStr );
/**
* .
*/
int Count( void ){ return( mCount ); }
/**
* i- .
*/
const char * operator[]( int i ){ return( mCount? S[ i ]: 0 ); }
};
#endif
| true |
714a1f1d2b3a3bafacc3e4b8173eac48ed4c9de3 | C++ | mitalletap/DataStructures2430 | /hw1-archive/hw1.cpp | UTF-8 | 15,055 | 2.9375 | 3 | [] | no_license | // I had resources from last semester which I used to complete this assignment as well as
// Brandon Labuschagne on youtube
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include "ArgumentManager.h"
using namespace std;
struct node {
// Keys
/*
string identificationK;
string fNameK;
string lNameK;
string dobK;
string gpaK;
*/
// Values
string identificationV;
string fNameV;
string lNameV;
string dobV;
string gpaV;
node *next;
};
bool isEmpty(node *head);
void insertAtFirst(node *&head, node *&last, string idV, string fNameV, string lNameV, string dobV, string gpaV);
void insert(node *&head, node *&last, string idV, string fNameV, string lNameV, string dobV, string gpaV);
void remove(node *&head, node *&last);
void removeAtValue(node *&head, string V);
void showListDeleted(node *current, string valueToDelete);
void showList(node *cu);
void deleteExtra(node *cu, string V);
void printFormatted(node *current, const char* filename);
int getLineNumber(string file, int& number);
string removeDelimiters(string&line);
string readAttributes(string file, string& idNumber, string& nameFirst, string& nameLast, string& birthDate, string& gradePoint);
bool hasKey(node *cu, string V);
void sort(node *head, string attribute1, string attribute2, string attribute3, string attribute4, string attribute5);
int main(int argc, char* argv[]){
if (argc < 2) {
cout << "Usage: densemult \"input=<input1.txt>;output=<output1.txt>;sort=<sort1.txt>\"" << endl;
return -1;
}
ArgumentManager am(argc, argv);
string input1 = am.get("input");
string output1 = am.get("output");
string sort1 = am.get("sort");
ofstream outputFile(output1.c_str());
node *head = NULL;
node *last = NULL;
int m = -1, z = 0, x = 0, number = 0;
string file = input1, attributeFile = sort1, str, temp, idNumber, nameFirst, nameLast, birthDate, gradePoint, valueToDelete;
getLineNumber(file, number);
string arrayLine[number], value[number][5];
ifstream input(file);
while(getline(input, str)){
arrayLine[z] = str;
z++;
}
for(int i = 0; i < number; i++){
x = 0;
m++;
temp = arrayLine[m];
string ID = " ", nameF = " ", nameL = " ", bDay = " ", grade = " ";
removeDelimiters(temp);
stringstream ss(temp);
string K, V;
while(ss >> K >> V){
if(K == "delete"){
valueToDelete = V;
removeAtValue(head, valueToDelete);
} else {
value[m][x] = V;
x++;
//ID = value[m][0], nameF = value[m][1], nameL = value[m][2], bDay = value[m][3], grade = value[m][4];
}
}
insert(head, last, value[m][0], value[m][1], value[m][2], value[m][3], value[m][4]);
}
string attribute1, attribute2, attribute3, attribute4, attribute5;
readAttributes(attributeFile, attribute1, attribute2, attribute3, attribute4, attribute5);
deleteExtra(head, valueToDelete);
sort(head, attribute1, attribute2, attribute3, attribute4, attribute5);
deleteExtra(head, valueToDelete);
printFormatted(head, output1.c_str());
return 0;
}
bool isEmpty(node *head){
if(head == NULL){
return true;
} else {
return false;
}
}
void insertAtFirst(node *&head, node *&last, string idV, string fNameV, string lNameV, string dobV, string gpaV){
node *temp = new node;
// Assign the values
temp->identificationV = idV;
temp->fNameV = fNameV;
temp->lNameV = lNameV;
temp->dobV = dobV;
temp->gpaV = gpaV;
temp->next = NULL;
head = temp;
last = temp;
}
void insert(node *&head, node *&last, string idV, string fNameV, string lNameV, string dobV, string gpaV){
if(isEmpty(head)){
insertAtFirst(head, last, idV, fNameV, lNameV, dobV, gpaV);
} else {
node *temp = new node;
// Assign the values
temp->identificationV = idV;
temp->fNameV = fNameV;
temp->lNameV = lNameV;
temp->dobV = dobV;
temp->gpaV = gpaV;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void remove(node *&head, node *&last){
if(isEmpty(head)){
cout << "The list is empty" << endl;
} else if(head == last){
delete head;
head = NULL;
last = NULL;
} else {
node *temp = new node;
temp = head;
head = head->next;
delete temp;
}
}
bool hasKey(node *cu, string V){
if(cu != NULL && (cu->identificationV == V || cu->fNameV == V || cu->lNameV == V || cu->dobV == V || cu->gpaV == V)){
return true;
} else {
return false;
}
}
void removeAtValue(node *&head, string V){
if(isEmpty(head)){
cout << "The list is empty" << endl;
} else {
node *cu = head;
node *prev = 0;
if(cu != NULL && (cu->identificationV != V || cu->fNameV != V || cu->lNameV != V || cu->dobV != V || cu->gpaV != V)){
prev = cu;
cu = cu->next;
}
if(cu->identificationV == V || cu->fNameV == V || cu->lNameV == V || cu->dobV == V || cu->gpaV == V){
/*
prev->next = cu->next;
delete cu;
*/
cu->identificationV = "", cu->fNameV = "", cu->lNameV = "", cu->dobV = "", cu->gpaV = "";
prev->next = cu->next;
}
}
}
void showListDeleted(node *cu, string valueToDelete){
if(isEmpty(cu)){
cout << "The list is empty" << endl;
} else {
cout << "The list contains: " << endl;
cout << "-------------------" << endl;
while(cu != NULL){
if((cu->identificationV == "" || cu->fNameV == "" || cu->lNameV == "" || cu->dobV == "" || cu->gpaV == "")){
cu = cu->next;
}
if(hasKey(cu, valueToDelete)){
cout << "Deleting Value: " << endl;
removeAtValue(cu, valueToDelete);
}
//idV, fNameV, lNameV, dobV, gpaV
cout << "ID: " << cu->identificationV << endl;
cout << "First Name: " << cu->fNameV << endl;
cout << "Last Name: " << cu->lNameV << endl;
cout << "DOB: " << cu->dobV << endl;
cout << "GPA: " << cu->gpaV << endl;
cout << "-------------------" << endl;
cu = cu->next;
}
}
}
void showList(node *cu){
if(isEmpty(cu)){
cout << "The list is empty" << endl;
} else {
cout << "The list contains: " << endl;
cout << "-------------------" << endl;
while(cu != NULL){
if((cu->identificationV == "" || cu->fNameV == "" || cu->lNameV == "" || cu->dobV == "" || cu->gpaV == "")){
cu = cu->next;
}
//idV, fNameV, lNameV, dobV, gpaV
cout << "ID: " << cu->identificationV << endl;
cout << "First Name: " << cu->fNameV << endl;
cout << "Last Name: " << cu->lNameV << endl;
cout << "DOB: " << cu->dobV << endl;
cout << "GPA: " << cu->gpaV << endl;
cout << "-------------------" << endl;
cu = cu->next;
}
}
}
void deleteExtra(node *cu, string V){
while(cu != NULL){
if ((hasKey(cu, V))){
cu->identificationV = "", cu->fNameV = "", cu->lNameV = "", cu->dobV = "", cu->gpaV = "";
cu = cu->next;
} else {
cu = cu->next;
}
}
}
void printFormatted(node *cu, const char* filename){
ofstream outputFile(filename);
if(isEmpty(cu)){
cout << "The list is empty";
} else {
while(cu != NULL){
//idV, fNameV, lNameV, dobV, gpa
if(cu->fNameV == ""){
cu = cu->next;
} else {
outputFile << "{id:" << cu->identificationV << ",first:" << cu->fNameV << ",last:" << cu->lNameV << ",DOB:" << cu->dobV << ",GPA:" << cu->gpaV << "}" << endl;
cu = cu->next;
}
}
}
}
int getLineNumber(string file, int& number){
string str;
ifstream input(file);
while(getline(input,str)){
number++;
}
return number;
}
string removeDelimiters(string &line){
replace(line.begin(), line.end(), '{', ' ');
replace(line.begin(), line.end(), '}', ' ');
replace(line.begin(), line.end(), ':', ' ');
replace(line.begin(), line.end(), ',', ' ');
return line;
}
string readAttributes(string file, string& idNumber, string& nameFirst, string& nameLast, string& birthDate, string& gradePoint){
ifstream input(file);
string str, temp1, temp2, temp3, temp4, temp5, arraySize[5];
int count = 0, incr = 0;
getLineNumber(file, count);
while(getline(input, str)){
arraySize[incr] = str;
incr++;
}
for(int i = 0; i < count; i++){
if(arraySize[i] == "id"){
temp1 = arraySize[i];
} else if (arraySize[i] == "first"){
temp2 = arraySize[i];
} else if (arraySize[i] == "last"){
temp3 = arraySize[i];
} else if (arraySize[i] == "DOB"){
temp4 = arraySize[i];
} else if (arraySize[i] == "gpa"){
temp5 = arraySize[i];
} else {
cout << "ERROR" << endl;
exit(0);
}
}
idNumber = temp1, nameFirst = temp2, nameLast = temp3, birthDate = temp4, gradePoint = temp5;
return idNumber, nameFirst, nameLast, birthDate, gradePoint;
}
void sort(node *head, string attribute1, string attribute2, string attribute3, string attribute4, string attribute5){
int precedence = 0;
if(attribute1 == "id"){
precedence = 1;
}
if (attribute2 == "first"){
precedence = 2;
}
if (attribute3 == "last"){
precedence = 3;
}
if (attribute4 == "DOB"){
precedence = 4;
}
if (attribute5 == "GPA"){
precedence = 5;
}
//cout << "precedence: " << precedence << endl;
if(precedence == 5){
goto GPA;
} else if (precedence == 4){
goto DOB;
} else if (precedence == 3){
goto Last;
} else if (precedence == 2){
goto First;
} else if (precedence == 1){
goto ID;
}
ID:
if(attribute1 == "id"){
node *first;
node *second;
for(first = head; first->next != NULL; first = first->next){
for(second = first->next; second != NULL; second = second->next){
string idS1 = first->identificationV, idS2 = second->identificationV;
//int idI1 = stoi(idS1), idI2 = stoi(idS2);
//cout << "idS1: " << idS1 << " idS2: " << idS2 << endl;
//cout << "idI1: " << idI1 << " idI2: " << idI2 << endl;
if(idS1 > idS2){
string tempID = first->identificationV;
string tempfName = first->fNameV;
string templName = first->lNameV;
string tempDOB = first->dobV;
string tempGPA = first->gpaV;
first->identificationV = second->identificationV;
first->fNameV = second->fNameV;
first->lNameV = second->lNameV;
first->dobV = second->dobV;
first->gpaV = second->gpaV;
second->identificationV = tempID;
second->fNameV = tempfName;
second->lNameV = templName;
second->dobV = tempDOB;
second->gpaV = tempGPA;
} else if(idS1 == idS2){
if(first->identificationV == second->identificationV && first->fNameV == second->fNameV && first->lNameV == second->lNameV && first->dobV == second->dobV && first->gpaV == second->gpaV){
second->fNameV = "";
}
}
}
}
goto leave;
}
First:
if(attribute2 == "first"){
node *first;
node *second;
for(first = head; first->next != NULL; first = first->next){
for(second = first->next; second != NULL; second = second->next){
string idS1 = first->fNameV, idS2 = second->fNameV;
if(idS1 > idS2){
string tempID = first->identificationV;
string tempfName = first->fNameV;
string templName = first->lNameV;
string tempDOB = first->dobV;
string tempGPA = first->gpaV;
first->identificationV = second->identificationV;
first->fNameV = second->fNameV;
first->lNameV = second->lNameV;
first->dobV = second->dobV;
first->gpaV = second->gpaV;
second->identificationV = tempID;
second->fNameV = tempfName;
second->lNameV = templName;
second->dobV = tempDOB;
second->gpaV = tempGPA;
} else if(idS1 == idS2){
if(first->identificationV == second->identificationV && first->fNameV == second->fNameV && first->lNameV == second->lNameV && first->dobV == second->dobV && first->gpaV == second->gpaV){
second->fNameV = "";
}
}
}
}
goto leave;
}
Last:
if(attribute3 == "last"){
node *first;
node *second;
for(first = head; first->next != NULL; first = first->next){
for(second = first->next; second != NULL; second = second->next){
string idS1 = first->lNameV, idS2 = second->lNameV;
if(idS1 > idS2){
string tempID = first->identificationV;
string tempfName = first->fNameV;
string templName = first->lNameV;
string tempDOB = first->dobV;
string tempGPA = first->gpaV;
first->identificationV = second->identificationV;
first->fNameV = second->fNameV;
first->lNameV = second->lNameV;
first->dobV = second->dobV;
first->gpaV = second->gpaV;
second->identificationV = tempID;
second->fNameV = tempfName;
second->lNameV = templName;
second->dobV = tempDOB;
second->gpaV = tempGPA;
} else if(idS1 == idS2){
if(first->identificationV == second->identificationV && first->fNameV == second->fNameV && first->lNameV == second->lNameV && first->dobV == second->dobV && first->gpaV == second->gpaV){
second->fNameV = "";
}
}
}
}
goto leave;
}
DOB:
if(attribute4 == "DOB"){
node *first;
node *second;
for(first = head; first->next != NULL; first = first->next){
for(second = first->next; second != NULL; second = second->next){
string idS1 = first->dobV, idS2 = second->dobV;
//cout << idS1 << " " << idS2 << endl;
if(idS1 > idS2){
string tempID = first->identificationV;
string tempfName = first->fNameV;
string templName = first->lNameV;
string tempDOB = first->dobV;
string tempGPA = first->gpaV;
first->identificationV = second->identificationV;
first->fNameV = second->fNameV;
first->lNameV = second->lNameV;
first->dobV = second->dobV;
first->gpaV = second->gpaV;
second->identificationV = tempID;
second->fNameV = tempfName;
second->lNameV = templName;
second->dobV = tempDOB;
second->gpaV = tempGPA;
} else if(idS1 == idS2){
if(first->identificationV == second->identificationV && first->fNameV == second->fNameV && first->lNameV == second->lNameV && first->dobV == second->dobV && first->gpaV == second->gpaV){
second->fNameV = "";
}
}
}
}
goto leave;
}
GPA:
if(attribute3 == "GPA"){
node *first;
node *second;
for(first = head; first->next != NULL; first = first->next){
for(second = first->next; second != NULL; second = second->next){
string idS1 = first->gpaV, idS2 = second->gpaV;
double idD1 = stod(idS1), idD2 = stod(idS2);
if(idD1 > idD2){
string tempID = first->identificationV;
string tempfName = first->fNameV;
string templName = first->lNameV;
string tempDOB = first->dobV;
string tempGPA = first->gpaV;
first->identificationV = second->identificationV;
first->fNameV = second->fNameV;
first->lNameV = second->lNameV;
first->dobV = second->dobV;
first->gpaV = second->gpaV;
second->identificationV = tempID;
second->fNameV = tempfName;
second->lNameV = templName;
second->dobV = tempDOB;
second->gpaV = tempGPA;
} else if(idS1 == idS2){
if(first->identificationV == second->identificationV && first->fNameV == second->fNameV && first->lNameV == second->lNameV && first->dobV == second->dobV && first->gpaV == second->gpaV){
second->fNameV = "";
}
}
}
}
goto leave;
}
leave:
if(attribute1 == "" || attribute2 == "" || attribute3 == "" || attribute4 == "" || attribute5 == "" ){
//cout << "No Attribute" << endl;
} else {
cout << "Error: Delete attribute not available!" << endl;
}
} | true |
521562ce5722c45d7f3e54a1564959767838ac55 | C++ | sahilgoyals1999/Love-Babber-DSA-450 | /06. Binary Trees/20. Construct Tree from Inorder & Preorder.cpp | UTF-8 | 1,046 | 3.21875 | 3 | [] | no_license | // https://practice.geeksforgeeks.org/problems/construct-tree-1/1
// T.C => O(n^2), S.C => O(n)
Node* solve(int in[], int pre[], int inS, int inE, int preS, int preE) {
if (inS > inE) return NULL;
int rootData = pre[preS];
int rootIndex = -1;
// Finding root index in inorder
for (int i = inS; i <= inE; ++i) {
if (in[i] == rootData) {
rootIndex = i;
break;
}
}
// length of left part of inorder == length of left part preorder
// (lInE - lInS) => left part of inorder
// (lPreE - lPreS) => left part of preorder
// lInE - lInS = lPreE - lPreS
// So, lPreE = lInE - lInS + lPreS
int lInS = inS;
int lInE = rootIndex - 1;
int lPreS = preS + 1;
int lPreE = lInE - lInS + lPreS;
int rPreS = lPreE + 1;
int rPreE = preE;
int rInS = rootIndex + 1;
int rInE = inE;
Node *root = new Node(rootData);
root->left = solve(in, pre, lInS, lInE, lPreS, lPreE);
root->right = solve(in, pre, rInS, rInE, rPreS, rPreE);
return root;
}
Node* buildTree(int in[], int pre[], int n) {
return solve(in, pre, 0, n - 1, 0, n - 1);
} | true |
2d877aac93f2793a5db348381af779ac86a62594 | C++ | btnkij/ACM | /libreoj/LIBREOJ10038.cpp | UTF-8 | 2,986 | 2.6875 | 3 | [] | no_license | /**
* Number:loj10038
* Title:「一本通 2.1 练习 4」A Horrible Poem
* Status:AC
* Tag:[字符串哈希, 素数筛]
**/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#define INF 0x3f3f3f3f
#define PI acos(-1)
typedef int ll;
typedef unsigned long long ull;
inline int readi(int& i1) { return scanf("%d", &i1); }
inline int readi(int& i1, int& i2) { return scanf("%d %d", &i1, &i2); }
inline int readi(int& i1, int& i2, int& i3) { return scanf("%d %d %d", &i1, &i2, &i3); }
inline int readi(int& i1, int& i2, int& i3, int& i4) { return scanf("%d %d %d %d", &i1, &i2, &i3, &i4); }
inline int reads(char* s1) { return scanf("%s", s1); }
#define mset(mem, val) memset(mem, val, sizeof(mem))
#define rep(i, begin, end) for (int i = (begin); i <= (end); i++)
#define rep2(i1, begin1, end1, i2, begin2, end2) rep(i1, begin1, end1) rep(i2, begin2, end2)
#define repne(i, begin, end) for (int i = (begin); i < (end); i++)
#define repne2(i1, begin1, end1, i2, begin2, end2) repne(i1, begin1, end1) repne(i2, begin2, end2)
inline int readu()
{
int num = 0;
char ch;
do{ ch = getchar(); }while(ch < '0' || ch > '9');
do{ num = (num << 3) + (num << 1) + (ch & 0xF); ch = getchar(); }while('0' <= ch && ch <= '9');
return num;
}
int prime[500010], *tailp;
bool is_nonprime[500010];
int nxt[500010];
void init_prime(int n)
{
tailp = prime;
is_nonprime[0] = is_nonprime[1] = true;
nxt[1] = 1;
for(int i = 2; i <= n; i++)
{
if(!is_nonprime[i])
{
*(tailp++) = i;
nxt[i] = i;
}
for(int* iter = prime; iter != tailp; iter++)
{
int t = i * (*iter);
if(t > n)break;
is_nonprime[t] = true;
nxt[t] = *iter;
if(i % *iter == 0)break;
}
}
}
struct
{
ull _hashc[500010], *hashc;
const ull base = 13131;
ull powb[500010] = {1};
void init(char* s)
{
hashc = _hashc + 1;
for(int i = 0; s[i]; i++)
{
powb[i + 1] = powb[i] * base;
hashc[i] = hashc[i - 1] * base + s[i];
}
}
ull range(int lt, int rt)
{
return hashc[rt] - hashc[lt - 1] * powb[rt - lt + 1];
}
}Hash;
char s[500010];
int main()
{
#ifdef __DEBUG__
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
int n = readu();
reads(s);
int q = readu();
init_prime(n);
Hash.init(s);
while(q--)
{
int lt = readu() - 1, rt = readu() - 1;
int len = rt - lt + 1;
int ans = len;
for(; len > 1; len /= nxt[len])
{
int t = ans / nxt[len];
if(Hash.range(lt + t, rt) == Hash.range(lt, rt - t))
ans = t;
int f = nxt[len];
while(len % f)len /= f;
}
printf("%d\n", ans);
}
return 0;
} | true |
2b9d09b06f8f7b39a2a4265bd452e4b12713b47d | C++ | Emartiinez/Cpp--School-Projects | /WS07 complete/in-lab/Hero.h | UTF-8 | 712 | 2.75 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#ifndef SICT_HERO_H
#define SICT_HERO_H
// Workshop 7
// Hero.h
// Fabio Bernal
// 2018/07/12
namespace sict
{
const int max_rounds = 100;
const int MAX_NAME = 41;
class Hero
{
private:
char hero_name[MAX_NAME];
int health;
int attack;
void set();
void set(const char name[], int hp, int attack);
public:
Hero();
Hero(const char name[], int hp, int attack);
void operator -= (int attack);
bool isAlive() const;
int attackStrength() const;
friend std::ostream& operator<<(std::ostream& os, const Hero& hero);
};
const Hero& operator*(const Hero& first, const Hero& second);
}
#endif | true |
8a80fd07246808e43dafd58421855ae69dd025d6 | C++ | Basicconstruction/Methods | /ACM-pretest/acmK.cpp | UTF-8 | 742 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
long cAB(int B, int A){
if(A==0){
return 1;
}
long output = 1;
for(int i = 1;i<=A;i++){
output *= (B-i+1);
output /= i;
}
return output;
}
void printWays(int s){
int howMany2;
long ways = 0;
if(s % 2 == 0){
howMany2 = s / 2;
}else{
howMany2 = (s-1)/2;
}
for(int i = 0;i<=howMany2;i++){
ways += cAB(s-i,i);
}
cout<<ways<<endl;
}
int main() {
int lines;
cin>>lines;
int M;
int steps;
for(int i = 0; i < lines;i++){
cin>>M;
steps = M - 1;
if(steps==0){
cout<<0<<endl;
}else{
printWays(steps);
}
}
return 0;
} | true |
f9102a718466646de578f49ed64a7f1ac6a47e25 | C++ | professorlineu/PROA3-2019-2 | /Atividades/Clayton_Ribeiro/Lista3/L3EX17.cpp | ISO-8859-1 | 680 | 2.96875 | 3 | [] | no_license | /**********************************************************
- Autor: Clayton C Ribeiro
- Descrio: Lista 3 - Exerccio 17
**********************************************************/
#include <iostream>
#include <locale.h>
#include <cstdlib>
using namespace std;
int main ()
{
int iSenha = 0;
setlocale(LC_ALL,"");
system("color F1");
cout << "Digite a senha para validao: "; // Recebe a senha
cin >> iSenha;
if (iSenha == 4531) //Validao da senha
{
cout << "Acesso permitido!";
}
else //Senha invlida
{
cout << "Acesso NO permitido!";
}
return 0;
}
| true |
7b8a9d34157012bd0b66fa97c2f206f537d8579f | C++ | yisenFangW/leetcode | /354.俄罗斯套娃信封问题.cpp | UTF-8 | 2,976 | 3.6875 | 4 | [] | no_license | 给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
说明:
不允许旋转信封。
示例:
输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3
解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
题解:跟最长连续上升子数组是一类题目(动态规划解法)(这样写时间复杂度较高O(n*n))
//1.因为这个是无序的,所以先排下序,先用第一个数字排,第一个数字一样,用第二个数字排(其实这题可以随便排)
//sort(envelopes.begin(), envelopes.end(), [](const vector<int> &v1, const vector<int> &v2)
// {if (v1.front() == v2.front()) return v1.back() < v2.back();
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (envelopes.empty())
return 0;
int maxLen = 1;
sort(envelopes.begin(), envelopes.end(), [](const vector<int> &v1, const vector<int> &v2)
{if (v1.front() == v2.front()) return v1.back() < v2.back();
else return v1.front() < v2.front(); });
vector<int> dp(envelopes.size(), 1);
for (int i = 0; i < envelopes.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1])
dp[i] = max(dp[i], dp[j] + 1);
}
maxLen = max(maxLen, dp[i]);
}
return maxLen;
}
//2.更加快速的方法,通过二分进行加速,首先要做的还是给信封排序,但是这次排序和上面有些不同,
//信封的宽度还是从小到大排,但是宽度相等时,我们让高度大的在前面, 给个例子:[1,10],[2,5],[2,6],[3,7],[4,10]
//这样求出来的最长子序列中包括了5,6,但是5,6的长度相同,肯定是不合理的,所以将长度相同的大的放在前面,变成
//[1,10],[2,6],[2,5],[3,7],[4,10]最长上升子序列为5,7,10等于3
//问题就简化了成了找高度数字中的最长连续子序列问题。
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (envelopes.empty() || envelopes[0].empty())
return 0;
sort(envelopes.begin(), envelopes.end(), [](const vector<int> &v1, const vector<int> &v2)
{if (v1.front() == v2.front()) return v1.back() > v2.back();
return v1.front() < v2.front(); });
vector<int> dp{envelopes[0].back()};
for (int i = 1; i < envelopes.size(); ++i) {
if (envelopes[i].back() < dp[0])
dp[0] = envelopes[i].back();
else if (envelopes[i].back() > dp.back())
dp.push_back(envelopes[i].back());
else {
int left = 0, right = dp.size() - 1;
while (left != right) {
int mid = left + (right - left) / 2;
if (envelopes[i].back() > dp[mid])
left = mid + 1;
else
right = mid;
}
dp[right] = envelopes[i].back();
}
}
return dp.size();
}
| true |
d603041a639929b1886104a255476650416d9ce8 | C++ | GhulamMustafaGM/C-Programming | /08-C++ Programing/BubbleSort.cpp | UTF-8 | 685 | 3.734375 | 4 | [] | no_license | // Bubble sort app
#include <iostream>
using namespace std;
int length = 0;
int arr[100] = {5};
int push(int num = 5)
{
arr[length + 1] = num;
length++;
}
int main()
{
push(10);
push(12);
push(8);
push(2);
push(70);
for (int i = 0; i <= length; i++)
{
for (int j = 0; j <= length; j++)
{
if (arr[i] < arr[i + j])
{
const int keep = arr[i + j];
arr[i + j] = arr[i];
arr[i] = keep;
cout << "Sorting..." << endl;
}
}
}
for (int i = 0; i <= length; i++)
{
cout << arr[i] << endl;
}
return 0;
} | true |
e38cade023fa52f0d20d08ec3c2a350bc703fbb4 | C++ | emd0008/MathFunctionProject | /TestingMode.cpp | UTF-8 | 956 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
bool testing;
string input_s;
void testingFunction() {
testing = true;
while (testing) {
cout << "\nWelcome to the Testing mode." << endl;
cout << "You can chose either the Basic or Common formulas to test on." << endl;
cout << "Input the numbers you wish to calculate for the formula." << endl;
cout << "Choose one of the answers." << endl;
cout << "If you choose correctly, you can chose another formula to test on." << endl;
cout << "If you choose wrong, you will be shown the correct answer and then choose another formula." << endl;
cout << "Type 'Quit' to stop the program." << endl;
getline(cin, input_s);
if (input_s == "Basic"){
cout << "Under construction" << endl;
}
else if (input_s == "Common") {
cout << "Under construction" << endl;
}
else if (input_s == "Quit") {
testing = false;
}
else {
cout << "Invalid comment" << endl;
}
}
} | true |
4f8fbd731c937bc225ddbd41a03861b8b7ff574c | C++ | FMyb/Itmo-Algo | /lab10/d.cpp | UTF-8 | 3,562 | 2.59375 | 3 | [] | no_license | //
// Created by Yarolsav Ilin CT ITMO M3238 on 13.11.2020.
//
#include <bits/stdc++.h>
using namespace std;
void dfs(int v, vector<vector<int>> &ed, vector<int> &p, vector<int> &right,
vector<bool> &usedLeft, vector<bool> &usedRight) {
usedLeft[v] = true;
for (auto u : ed[v]) {
if (!usedRight[u] && p[v] != u) {
usedRight[u] = true;
if (right[u] != -1) {
dfs(right[u], ed, p, right, usedLeft, usedRight);
}
}
}
}
pair<vector<int>, vector<int>> ver(int n, int m, vector<vector<int>> &ed, vector<int> &p) {
vector<int> ans1;
vector<int> right(m, -1);
for (int i = 0; i < n; i++) {
if (p[i] != -1) {
right[p[i]] = i;
}
}
vector<bool> usedLeft(n);
vector<bool> usedRight(m);
for (int i = 0; i < n; i++) {
if (p[i] == -1) {
dfs(i, ed, p, right, usedLeft, usedRight);
}
}
vector<int> ans2;
for (int i = 0; i < n; i++) {
if (!usedLeft[i]) {
ans1.push_back(i);
}
}
for (int i = 0; i < m; i++) {
if (usedRight[i]) {
ans2.push_back(i);
}
}
return {ans1, ans2};
}
bool dfs1(int v, vector<vector<int>> &ed, vector<int> &px, vector<int> &py, vector<bool> &used) {
if (used[v]) {
return false;
}
used[v] = true;
for (auto u : ed[v]) {
if (py[u] == -1) {
py[u] = v;
px[v] = u;
return true;
} else {
if (dfs1(py[u], ed, px, py, used)) {
py[u] = v;
px[v] = u;
return true;
}
}
}
return false;
}
vector<int> parr(int n, int m, vector<vector<int>> &ed) {
vector<int> px(n, -1);
vector<int> py(m, -1);
bool isPath = true;
while (isPath) {
isPath = false;
vector<bool> used(n);
for (int i = 0; i < n; i++) {
if (px[i] == -1) {
if (dfs1(i, ed, px, py, used)) {
isPath = true;
}
}
}
}
vector<int> ans;
for (int i = 0; i < n; i++) {
ans.push_back(px[i]);
}
return ans;
}
void solve() {
int n, m;
cin >> n >> m;
vector<set<int>> ed(n);
for (int i = 0; i < n; i++) {
int c;
cin >> c;
while (c != 0) {
ed[i].insert(c - 1);
cin >> c;
}
}
vector<vector<int>> ed1(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (ed[i].count(j) == 0) {
ed1[i].push_back(j);
}
}
}
auto p = parr(n, m, ed1);
auto ans = ver(n, m, ed1, p);
vector<bool> used(n), used1(m);
for (auto u : ans.first) {
used[u] = true;
}
for (auto u : ans.second) {
used1[u] = true;
}
vector<int> ans1;
vector<int> ans2;
for (int i = 0; i < n; i++) {
if (!used[i]) {
ans1.push_back(i);
}
}
for (int i = 0; i < m; i++) {
if (!used1[i]) {
ans2.push_back(i);
}
}
cout << ans1.size() + ans2.size() << '\n';
cout << ans1.size() << ' ' << ans2.size() << '\n';
for (auto u : ans1) {
cout << u + 1 << ' ';
}
cout << '\n';
for (auto u : ans2) {
cout << u + 1 << ' ';
}
cout << '\n';
}
int main() {
ios_base::sync_with_stdio(false);
int k;
cin >> k;
for (int test = 0; test < k; test++) {
solve();
}
}
| true |
3cb533dd1ac73cbaaef96fb8e3a45f2204d49745 | C++ | sachavincent/B-Splines | /src/myopenglwidget.cpp | UTF-8 | 5,097 | 2.53125 | 3 | [] | no_license | #include "myopenglwidget.h"
#include <QMessageBox>
#include <QApplication>
#include <QDateTime>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stdexcept>
MyOpenGLWidget::MyOpenGLWidget(QWidget *parent) :QOpenGLWidget(parent)/*, QOpenGLFunctions_4_1_Core()*/, _openglDemo(nullptr), _lastime(0) {
}
MyOpenGLWidget::~MyOpenGLWidget() {
}
QSize MyOpenGLWidget::minimumSizeHint() const
{
return QSize(640, 600);
}
QSize MyOpenGLWidget::sizeHint() const
{
return QSize(640, 600);
}
void MyOpenGLWidget::cleanup() {
_openglDemo.reset(nullptr);
}
void MyOpenGLWidget::initializeGL() {
connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &MyOpenGLWidget::cleanup);
if (!initializeOpenGLFunctions()) {
QMessageBox::critical(this, "OpenGL initialization error", "MyOpenGLWidget::initializeGL() : Unable to initialize OpenGL functions");
exit(1);
}
//_openglDemo.reset(new BSplineDemo(width(), height()));
_openglDemo.reset(new SurfaceDemo(width(), height()));
}
void MyOpenGLWidget::setModalIndex(int index) {
size_t size = _openglDemo->_degre + _openglDemo->_controlPoints.size() + 1;
_openglDemo->_modalIndex = index;
_openglDemo->_modals.clear();
_openglDemo->_modals.resize(size);
srand(time(NULL));
int k, step, start;
std::vector<float> t;
switch (index) {
case 0: // Uniforme
std::iota(_openglDemo->_modals.begin(), _openglDemo->_modals.end(), 0);
break;
case 1: // Ouvert Uniforme
k = int(size / 3);
step = rand() % 4 + 1;
start = rand() % 10;
for (size_t i = 0; i < k; i++)
_openglDemo->_modals[i] = start;
for (size_t i = k; i < size - k; i++)
_openglDemo->_modals[i] = _openglDemo->_modals[i - 1] + step;
for (size_t i = size - k; i < size; i++)
_openglDemo->_modals[i] = _openglDemo->_modals[size - k - 1] + step;
t = _openglDemo->_modals;
break;
case 2: // Quelconque
_openglDemo->_modals[0] = 0;
for (size_t i = 1; i < size; i++) {
_openglDemo->_modals[i] = _openglDemo->_modals[i - 1] + 1 + (rand() % 6);
}
break;
}
_openglDemo->updateBSpline();
update();
}
std::vector<glm::vec3> MyOpenGLWidget::getControlPoints() {
return _openglDemo->_controlPoints;
}
void MyOpenGLWidget::setControlPoints(std::vector<glm::vec3> controlPoints) {
_openglDemo->_controlPoints = controlPoints;
setModalIndex(_openglDemo->_modalIndex);
}
void MyOpenGLWidget::setDegreIndex(int index) {
_openglDemo->_degre = index + 1;
if (_openglDemo->_controlPoints.size() <= _openglDemo->_degre) {
size_t nb = _openglDemo->_degre - _openglDemo->_controlPoints.size();
for (int i = 0; i <= nb; i++)
_openglDemo->_controlPoints.push_back({ 0, 0, 0 });
}
setModalIndex(_openglDemo->_modalIndex);
}
void MyOpenGLWidget::createBSpline() {
_openglDemo->createBSpline();
}
void MyOpenGLWidget::paintGL() {
std::int64_t starttime = QDateTime::currentMSecsSinceEpoch();
_openglDemo->draw();
glFinish();
std::int64_t endtime = QDateTime::currentMSecsSinceEpoch();
_lastime = endtime-starttime;
}
void MyOpenGLWidget::resizeGL(int width, int height) {
_openglDemo->resize(width, height);
}
void MyOpenGLWidget::mousePressEvent(QMouseEvent *event) {
// buttons are 0(left), 1(right) to 2(middle)
int b;
Qt::MouseButton button=event->button();
if (button & Qt::LeftButton) {
if ((event->modifiers() & Qt::ControlModifier))
b = 2;
else
b = 0;
} else if (button & Qt::RightButton)
b = 1;
else if (button & Qt::MiddleButton)
b = 2;
else
b=3;
_openglDemo->mouseclick(b, event->x(), event->y());
_lastime = QDateTime::currentMSecsSinceEpoch();
}
void MyOpenGLWidget::mouseMoveEvent(QMouseEvent *event) {
_openglDemo->mousemove(event->x(), event->y());
update();
}
void MyOpenGLWidget::wheelEvent(QWheelEvent* event) {
_openglDemo->mousewheel(event->angleDelta().y());
update();
}
void MyOpenGLWidget::keyPressEvent(QKeyEvent *event) {
switch(event->key()) {
// Demo keys
case Qt::Key_0:
case Qt::Key_1:
case Qt::Key_2:
case Qt::Key_3:
case Qt::Key_4:
case Qt::Key_5:
case Qt::Key_6:
case Qt::Key_7:
case Qt::Key_8:
case Qt::Key_9:
break;
// Move keys
case Qt::Key_Left:
case Qt::Key_Up:
case Qt::Key_Right:
case Qt::Key_Down:
_openglDemo->keyboardmove(event->key()-Qt::Key_Left, 1./100/*double(_lastime)/10.*/);
update();
break;
// Wireframe key
case Qt::Key_W:
_openglDemo->toggledrawmode();
update();
break;
// Other keys are transmitted to the scene
default :
if (_openglDemo->keyboard(event->text().toStdString()[0]))
update();
break;
}
}
| true |
e4e67fefc59b00536d503f3d7df0fe01690700e2 | C++ | Starbix/hyperion | /include/utils/RgbChannelCorrection.h | UTF-8 | 1,592 | 3.234375 | 3 | [
"MIT"
] | permissive | #pragma once
// STL includes
#include <cstdint>
/// Correction for a single color byte value
/// All configuration values are unsigned int and assume the color value to be between 0 and 255
class RgbChannelCorrection
{
public:
/// Default constructor
RgbChannelCorrection();
/// Constructor
/// @param correctionR
/// @param correctionG
/// @param correctionB
RgbChannelCorrection(int correctionR, int correctionG, int correctionB);
/// Destructor
~RgbChannelCorrection();
/// @return The current correctionR value
uint8_t getcorrectionR() const;
/// @param threshold New correctionR value
void setcorrectionR(uint8_t correctionR);
/// @return The current correctionG value
uint8_t getcorrectionG() const;
/// @param gamma New correctionG value
void setcorrectionG(uint8_t correctionG);
/// @return The current correctionB value
uint8_t getcorrectionB() const;
/// @param blacklevel New correctionB value
void setcorrectionB(uint8_t correctionB);
/// Transform the given array value
/// @param input The input color bytes
/// @return The corrected byte value
uint8_t correctionR(uint8_t inputR) const;
uint8_t correctionG(uint8_t inputG) const;
uint8_t correctionB(uint8_t inputB) const;
private:
/// (re)-initilize the color mapping
void initializeMapping();
private:
/// The correction of R channel
int _correctionR;
/// The correction of G channel
int _correctionG;
/// The correction of B channel
int _correctionB;
/// The mapping from input color to output color
int _mappingR[256];
int _mappingG[256];
int _mappingB[256];
};
| true |
c79f6f978bf0ddea3221145c2b1d2d38836cb692 | C++ | machinekoder/qt-qmake-catch-and-trompeloeil-seed | /tests/tst_apptests.cpp | UTF-8 | 2,852 | 3.140625 | 3 | [
"MIT"
] | permissive | #include <catch.hpp>
#include <trompeloeil.hpp>
#include <QSignalSpy>
#include <warehouse.h>
#include <viennawarehouse.h>
#include <order.h>
#include <autoorder.h>
extern template struct trompeloeil::reporter<trompeloeil::specialized>;
TEST_CASE("ViennaWarehouse starts with exactly 15 Schnitzel", "[app]")
{
ViennaWarehouse warehouse;
SECTION("Checking for less than 15 Schnitzel works") {
REQUIRE(warehouse.hasInventory("Schnitzel", 10));
}
SECTION("Checking for exactly 15 Schnitzel works") {
REQUIRE(warehouse.hasInventory("Schnitzel", 15));
}
SECTION("Checking for more than 15 Schnitzel fails") {
REQUIRE(warehouse.hasInventory("Schnitzel", 200) == false);
}
}
class WarehouseMock: public Warehouse
{
public:
MAKE_CONST_MOCK2(hasInventory, bool(const QString&, int));
MAKE_MOCK2(remove, bool(const QString&, int));
};
TEST_CASE("Filling Order from Warehouse works", "[app]")
{
Order order("Schnitzel", 50);
WarehouseMock warehouse;
SECTION("filling removes inventory if in stock") {
REQUIRE_CALL(warehouse, hasInventory("Schnitzel", 50))
.RETURN(true);
REQUIRE_CALL(warehouse, remove("Schnitzel", 50))
.RETURN(true);
order.fill(warehouse);
REQUIRE(order.isFilled());
}
SECTION("filling does not remove inventory if not in stock") {
REQUIRE_CALL(warehouse, hasInventory("Schnitzel", 50))
.RETURN(false);
order.fill(warehouse);
REQUIRE_FALSE(order.isFilled());
}
}
TEST_CASE("Automatically ordering wares with AutoOrder works", "[app")
{
WarehouseMock warehouse;
GIVEN("We have an auto order of 1 Tafelspitz") {
Order order("Tafelspitz", 1);
AutoOrder autoOrder(&warehouse, &order);
QSignalSpy waresOrderedSpy(&autoOrder, &AutoOrder::waresOrdered);
QSignalSpy outOfWaresSpy(&autoOrder, &AutoOrder::outOfWares);
WHEN("We start the auto order") {
autoOrder.startOrdering(1);
AND_WHEN("we have enough Tafelspitz in stock") {
REQUIRE_CALL(warehouse, hasInventory("Tafelspitz", 1))
.RETURN(true);
REQUIRE_CALL(warehouse, remove("Tafelspitz", 1))
.RETURN(true);
THEN("we are notified about the order") {
waresOrderedSpy.wait(10);
REQUIRE(waresOrderedSpy.count() == 1);
}
}
AND_WHEN("we don't have enough Tafelspitz in stock") {
REQUIRE_CALL(warehouse, hasInventory("Tafelspitz", 1))
.RETURN(false);
THEN("we are notified that we have just run out of stock") {
outOfWaresSpy.wait(10);
REQUIRE(outOfWaresSpy.count() == 0);
}
}
}
}
}
| true |
ae0419e28a5c386f38b67d0c5486fba300464f12 | C++ | ChesterHu/cs32 | /proj3/main.cpp | UTF-8 | 7,574 | 2.828125 | 3 | [] | no_license | #include "Game.h"
#include "Player.h"
#include "Board.h"
#include <iostream>
#include <string>
using namespace std;
bool addStandardShips(Game& g)
{
return g.addShip(5, 'A', "aircraft carrier") &&
g.addShip(4, 'B', "battleship") &&
g.addShip(3, 'D', "destroyer") &&
g.addShip(3, 'S', "submarine") &&
g.addShip(2, 'P', "patrol boat");
}
void test()
{
do {
Game g(10, 10);
assert(addStandardShips(g));
assert(g.nShips() == 5);
assert(g.rows() == 10 && g.cols() == 10);
assert(g.shipLength(0) == 5 && g.shipLength(4) == 2);
assert(g.shipSymbol(2) == 'D' && g.shipSymbol(3) == 'S');
assert(g.shipName(1) == "battleship" && g.shipName(0) == "aircraft carrier");
// test placeShip() and unplaceShip()
Board b(g);
b.clear();
b.block();
b.unblock();
assert(b.placeShip(Point(0, 0), 0, HORIZONTAL));
assert(b.unplaceShip(Point(0, 0), 0, HORIZONTAL));
assert(b.placeShip(Point(1, 1), 0, VERTICAL));
assert(!b.unplaceShip(Point(2, 1), 0, VERTICAL));
assert(b.unplaceShip(Point(1, 1), 0, VERTICAL));
assert(b.placeShip(Point(0, 0), 0, HORIZONTAL));
assert(b.placeShip(Point(1, 1), 1, VERTICAL));
assert(!b.placeShip(Point(2, 2), 1, VERTICAL));
assert(!b.placeShip(Point(1, 0), 4, HORIZONTAL));
assert(b.placeShip(Point(1, 2), 4, HORIZONTAL));
// b.display(true);
// b.display(false);
int shipId = 1;
bool shotHit = true, shipDestroyed = true;
assert(!b.attack(Point(-1, 0), shotHit, shipDestroyed, shipId) && !b.attack(Point(10, 1), shotHit, shipDestroyed, shipId));
assert(b.attack(Point(1, 0), shotHit, shipDestroyed, shipId) && !shotHit && shipId == 1);
assert(b.attack(Point(0, 0), shotHit, shipDestroyed, shipId) && shotHit && shipId == 0);
assert(b.attack(Point(0, 1), shotHit, shipDestroyed, shipId) && shotHit && shipId == 0);
assert(b.attack(Point(0, 2), shotHit, shipDestroyed, shipId) && shotHit && shipId == 0);
assert(b.attack(Point(1, 1), shotHit, shipDestroyed, shipId) && shotHit && shipId == 1);
assert(b.attack(Point(0, 3), shotHit, shipDestroyed, shipId) && shotHit && shipId == 0);
assert(b.attack(Point(0, 4), shotHit, shipDestroyed, shipId) && shotHit && shipDestroyed && shipId == 0);
assert(b.attack(Point(2, 1), shotHit, shipDestroyed, shipId) && shotHit && shipId == 1);
assert(b.attack(Point(1, 2), shotHit, shipDestroyed, shipId) && shotHit && shipId == 4);
assert(b.attack(Point(3, 1), shotHit, shipDestroyed, shipId) && shotHit && shipId == 1);
assert(!b.allShipsDestroyed());
assert(b.attack(Point(4, 1), shotHit, shipDestroyed, shipId) && shotHit && shipDestroyed && shipId == 1);
assert(b.attack(Point(1, 3), shotHit, shipDestroyed, shipId) && shotHit && shipDestroyed && shipId == 4);
assert(b.allShipsDestroyed());
} while (0);
do {
// second test
Game g(10, 10);
assert(addStandardShips(g));
Board b(g);
b.clear();
assert(b.placeShip(Point(0, 0), 4, HORIZONTAL));
bool shotHit = true, shipDestroyed = true;
int shipId = 0;
assert(b.attack(Point(1, 1), shotHit, shipDestroyed, shipId) && !shotHit && shipId == 0);
assert(!b.allShipsDestroyed());
assert(b.attack(Point(0, 0), shotHit, shipDestroyed, shipId) && shotHit && !shipDestroyed && shipId == 4);
// b.display(true);
// b.display(false);
assert(b.attack(Point(0, 1), shotHit, shipDestroyed, shipId) && shotHit && shipDestroyed && shipId == 4);
// b.display(false);
assert(b.allShipsDestroyed());
} while(0);
do {
// third test
Game g(10, 10);
addStandardShips(g);
Player* p1 = createPlayer("human", "chufeng", g);
Player* p2 = createPlayer("good", "a", g);
// assert(g.play(p1, p2) == p1);
delete p1;
delete p2;
} while (0);
do {
Game g(10, 10);
addStandardShips(g);
Player* p1 = createPlayer("mediocre", "a", g);
Board b(g);
b.clear();
p1->placeShips(b);
// b.display(false);
delete p1;
} while (0);
do {
int nMediocreWins = 0;
int NTRIALS = 1000;
int totalGames = 0;
for (int k = 1; k <= NTRIALS; k++)
{
cout << "============================= Game " << k
<< " =============================" << endl;
Game g(10, 7);
addStandardShips(g);
Player* p1 = createPlayer("good", "Good Audrey", g);
Player* p2 = createPlayer("mediocre", "Mediocre Mimi", g);
Player* winner = (k % 2 == 1 ?
g.play(p1, p2, false) : g.play(p2, p1, false));
if (winner == p1)
nMediocreWins++;
if (winner != nullptr)
totalGames++;
delete p1;
delete p2;
}
cout << "The good player won " << nMediocreWins << " out of "
<< totalGames << " games." << endl;
// We'd expect a mediocre player to win most of the games against
// an awful player. Similarly, a good player should outperform
// a mediocre player.
} while (0);
cout << "Passed all tests" << endl;
}
int main()
{
int NTRIALS = 10000;
// test();
/*
Game g(10, 10);
Board b(g);
addStandardShips(g);
Player* p = createPlayer("good", "a", g);
b.clear();
// b.display(false);
p->placeShips(b);
// b.display(false);
delete p;
*/
cout << "Select one of these choices for an example of the game:" << endl;
cout << " 1. A mini-game between two mediocre players" << endl;
cout << " 2. A good player against a human player" << endl;
cout << " 3. A " << NTRIALS
<< "-game match between a mediocre and an good player, with no pauses"
<< endl;
cout << "Enter your choice: ";
string line;
getline(cin,line);
if (line.empty())
{
cout << "You did not enter a choice" << endl;
}
else if (line[0] == '1')
{
Game g(2, 3);
g.addShip(2, 'R', "rowboat");
Player* p1 = createPlayer("mediocre", "Popeye", g);
Player* p2 = createPlayer("mediocre", "Bluto", g);
cout << "This mini-game has one ship, a 2-segment rowboat." << endl;
g.play(p1, p2);
delete p1;
delete p2;
}
else if (line[0] == '2')
{
Game g(10, 10);
addStandardShips(g);
Player* p1 = createPlayer("good", "Mediocre Midori", g);
Player* p2 = createPlayer("human", "Shuman the Human", g);
g.play(p1, p2);
delete p1;
delete p2;
}
else if (line[0] == '3')
{
int nMediocreWins = 0;
for (int k = 1; k <= NTRIALS; k++)
{
cout << "============================= Game " << k
<< " =============================" << endl;
Game g(10, 10);
addStandardShips(g);
Player* p1 = createPlayer("good", "Good Audrey", g);
Player* p2 = createPlayer("mediocre", "Mediocre Mimi", g);
Player* winner = (k % 2 == 1 ?
g.play(p1, p2, false) : g.play(p2, p1, false));
if (winner == p2)
nMediocreWins++;
delete p1;
delete p2;
}
cout << "The mediocre player won " << nMediocreWins << " out of "
<< NTRIALS << " games." << endl;
// We'd expect a mediocre player to win most of the games against
// an awful player. Similarly, a good player should outperform
// a mediocre player.
}
else
{
cout << "That's not one of the choices." << endl;
}
}
| true |
187ba9302d4f904646a64210d654282d2c5561cf | C++ | expo/expo | /android/vendored/unversioned/@shopify/react-native-skia/cpp/skia/include/core/SkRRect.h | UTF-8 | 20,410 | 2.703125 | 3 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | /*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkRRect_DEFINED
#define SkRRect_DEFINED
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkScalar.h"
#include "include/core/SkTypes.h"
#include <cstdint>
#include <cstring>
class SkMatrix;
class SkString;
/** \class SkRRect
SkRRect describes a rounded rectangle with a bounds and a pair of radii for each corner.
The bounds and radii can be set so that SkRRect describes: a rectangle with sharp corners;
a circle; an oval; or a rectangle with one or more rounded corners.
SkRRect allows implementing CSS properties that describe rounded corners.
SkRRect may have up to eight different radii, one for each axis on each of its four
corners.
SkRRect may modify the provided parameters when initializing bounds and radii.
If either axis radii is zero or less: radii are stored as zero; corner is square.
If corner curves overlap, radii are proportionally reduced to fit within bounds.
*/
class SK_API SkRRect {
public:
/** Initializes bounds at (0, 0), the origin, with zero width and height.
Initializes corner radii to (0, 0), and sets type of kEmpty_Type.
@return empty SkRRect
*/
SkRRect() = default;
/** Initializes to copy of rrect bounds and corner radii.
@param rrect bounds and corner to copy
@return copy of rrect
*/
SkRRect(const SkRRect& rrect) = default;
/** Copies rrect bounds and corner radii.
@param rrect bounds and corner to copy
@return copy of rrect
*/
SkRRect& operator=(const SkRRect& rrect) = default;
/** \enum SkRRect::Type
Type describes possible specializations of SkRRect. Each Type is
exclusive; a SkRRect may only have one type.
Type members become progressively less restrictive; larger values of
Type have more degrees of freedom than smaller values.
*/
enum Type {
kEmpty_Type, //!< zero width or height
kRect_Type, //!< non-zero width and height, and zeroed radii
kOval_Type, //!< non-zero width and height filled with radii
kSimple_Type, //!< non-zero width and height with equal radii
kNinePatch_Type, //!< non-zero width and height with axis-aligned radii
kComplex_Type, //!< non-zero width and height with arbitrary radii
kLastType = kComplex_Type, //!< largest Type value
};
Type getType() const {
SkASSERT(this->isValid());
return static_cast<Type>(fType);
}
Type type() const { return this->getType(); }
inline bool isEmpty() const { return kEmpty_Type == this->getType(); }
inline bool isRect() const { return kRect_Type == this->getType(); }
inline bool isOval() const { return kOval_Type == this->getType(); }
inline bool isSimple() const { return kSimple_Type == this->getType(); }
inline bool isNinePatch() const { return kNinePatch_Type == this->getType(); }
inline bool isComplex() const { return kComplex_Type == this->getType(); }
/** Returns span on the x-axis. This does not check if result fits in 32-bit float;
result may be infinity.
@return rect().fRight minus rect().fLeft
*/
SkScalar width() const { return fRect.width(); }
/** Returns span on the y-axis. This does not check if result fits in 32-bit float;
result may be infinity.
@return rect().fBottom minus rect().fTop
*/
SkScalar height() const { return fRect.height(); }
/** Returns top-left corner radii. If type() returns kEmpty_Type, kRect_Type,
kOval_Type, or kSimple_Type, returns a value representative of all corner radii.
If type() returns kNinePatch_Type or kComplex_Type, at least one of the
remaining three corners has a different value.
@return corner radii for simple types
*/
SkVector getSimpleRadii() const {
return fRadii[0];
}
/** Sets bounds to zero width and height at (0, 0), the origin. Sets
corner radii to zero and sets type to kEmpty_Type.
*/
void setEmpty() { *this = SkRRect(); }
/** Sets bounds to sorted rect, and sets corner radii to zero.
If set bounds has width and height, and sets type to kRect_Type;
otherwise, sets type to kEmpty_Type.
@param rect bounds to set
*/
void setRect(const SkRect& rect) {
if (!this->initializeRect(rect)) {
return;
}
memset(fRadii, 0, sizeof(fRadii));
fType = kRect_Type;
SkASSERT(this->isValid());
}
/** Initializes bounds at (0, 0), the origin, with zero width and height.
Initializes corner radii to (0, 0), and sets type of kEmpty_Type.
@return empty SkRRect
*/
static SkRRect MakeEmpty() { return SkRRect(); }
/** Initializes to copy of r bounds and zeroes corner radii.
@param r bounds to copy
@return copy of r
*/
static SkRRect MakeRect(const SkRect& r) {
SkRRect rr;
rr.setRect(r);
return rr;
}
/** Sets bounds to oval, x-axis radii to half oval.width(), and all y-axis radii
to half oval.height(). If oval bounds is empty, sets to kEmpty_Type.
Otherwise, sets to kOval_Type.
@param oval bounds of oval
@return oval
*/
static SkRRect MakeOval(const SkRect& oval) {
SkRRect rr;
rr.setOval(oval);
return rr;
}
/** Sets to rounded rectangle with the same radii for all four corners.
If rect is empty, sets to kEmpty_Type.
Otherwise, if xRad and yRad are zero, sets to kRect_Type.
Otherwise, if xRad is at least half rect.width() and yRad is at least half
rect.height(), sets to kOval_Type.
Otherwise, sets to kSimple_Type.
@param rect bounds of rounded rectangle
@param xRad x-axis radius of corners
@param yRad y-axis radius of corners
@return rounded rectangle
*/
static SkRRect MakeRectXY(const SkRect& rect, SkScalar xRad, SkScalar yRad) {
SkRRect rr;
rr.setRectXY(rect, xRad, yRad);
return rr;
}
/** Sets bounds to oval, x-axis radii to half oval.width(), and all y-axis radii
to half oval.height(). If oval bounds is empty, sets to kEmpty_Type.
Otherwise, sets to kOval_Type.
@param oval bounds of oval
*/
void setOval(const SkRect& oval);
/** Sets to rounded rectangle with the same radii for all four corners.
If rect is empty, sets to kEmpty_Type.
Otherwise, if xRad or yRad is zero, sets to kRect_Type.
Otherwise, if xRad is at least half rect.width() and yRad is at least half
rect.height(), sets to kOval_Type.
Otherwise, sets to kSimple_Type.
@param rect bounds of rounded rectangle
@param xRad x-axis radius of corners
@param yRad y-axis radius of corners
example: https://fiddle.skia.org/c/@RRect_setRectXY
*/
void setRectXY(const SkRect& rect, SkScalar xRad, SkScalar yRad);
/** Sets bounds to rect. Sets radii to (leftRad, topRad), (rightRad, topRad),
(rightRad, bottomRad), (leftRad, bottomRad).
If rect is empty, sets to kEmpty_Type.
Otherwise, if leftRad and rightRad are zero, sets to kRect_Type.
Otherwise, if topRad and bottomRad are zero, sets to kRect_Type.
Otherwise, if leftRad and rightRad are equal and at least half rect.width(), and
topRad and bottomRad are equal at least half rect.height(), sets to kOval_Type.
Otherwise, if leftRad and rightRad are equal, and topRad and bottomRad are equal,
sets to kSimple_Type. Otherwise, sets to kNinePatch_Type.
Nine patch refers to the nine parts defined by the radii: one center rectangle,
four edge patches, and four corner patches.
@param rect bounds of rounded rectangle
@param leftRad left-top and left-bottom x-axis radius
@param topRad left-top and right-top y-axis radius
@param rightRad right-top and right-bottom x-axis radius
@param bottomRad left-bottom and right-bottom y-axis radius
*/
void setNinePatch(const SkRect& rect, SkScalar leftRad, SkScalar topRad,
SkScalar rightRad, SkScalar bottomRad);
/** Sets bounds to rect. Sets radii array for individual control of all for corners.
If rect is empty, sets to kEmpty_Type.
Otherwise, if one of each corner radii are zero, sets to kRect_Type.
Otherwise, if all x-axis radii are equal and at least half rect.width(), and
all y-axis radii are equal at least half rect.height(), sets to kOval_Type.
Otherwise, if all x-axis radii are equal, and all y-axis radii are equal,
sets to kSimple_Type. Otherwise, sets to kNinePatch_Type.
@param rect bounds of rounded rectangle
@param radii corner x-axis and y-axis radii
example: https://fiddle.skia.org/c/@RRect_setRectRadii
*/
void setRectRadii(const SkRect& rect, const SkVector radii[4]);
/** \enum SkRRect::Corner
The radii are stored: top-left, top-right, bottom-right, bottom-left.
*/
enum Corner {
kUpperLeft_Corner, //!< index of top-left corner radii
kUpperRight_Corner, //!< index of top-right corner radii
kLowerRight_Corner, //!< index of bottom-right corner radii
kLowerLeft_Corner, //!< index of bottom-left corner radii
};
/** Returns bounds. Bounds may have zero width or zero height. Bounds right is
greater than or equal to left; bounds bottom is greater than or equal to top.
Result is identical to getBounds().
@return bounding box
*/
const SkRect& rect() const { return fRect; }
/** Returns scalar pair for radius of curve on x-axis and y-axis for one corner.
Both radii may be zero. If not zero, both are positive and finite.
@return x-axis and y-axis radii for one corner
*/
SkVector radii(Corner corner) const { return fRadii[corner]; }
/** Returns bounds. Bounds may have zero width or zero height. Bounds right is
greater than or equal to left; bounds bottom is greater than or equal to top.
Result is identical to rect().
@return bounding box
*/
const SkRect& getBounds() const { return fRect; }
/** Returns true if bounds and radii in a are equal to bounds and radii in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes with different signs.
@param a SkRect bounds and radii to compare
@param b SkRect bounds and radii to compare
@return true if members are equal
*/
friend bool operator==(const SkRRect& a, const SkRRect& b) {
return a.fRect == b.fRect && SkScalarsEqual(&a.fRadii[0].fX, &b.fRadii[0].fX, 8);
}
/** Returns true if bounds and radii in a are not equal to bounds and radii in b.
a and b are not equal if either contain NaN. a and b are equal if members
contain zeroes with different signs.
@param a SkRect bounds and radii to compare
@param b SkRect bounds and radii to compare
@return true if members are not equal
*/
friend bool operator!=(const SkRRect& a, const SkRRect& b) {
return a.fRect != b.fRect || !SkScalarsEqual(&a.fRadii[0].fX, &b.fRadii[0].fX, 8);
}
/** Copies SkRRect to dst, then insets dst bounds by dx and dy, and adjusts dst
radii by dx and dy. dx and dy may be positive, negative, or zero. dst may be
SkRRect.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half dst bounds width, dst bounds left and right are set to
bounds x-axis center. If dy exceeds half dst bounds height, dst bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, dst bounds is zeroed.
@param dx added to rect().fLeft, and subtracted from rect().fRight
@param dy added to rect().fTop, and subtracted from rect().fBottom
@param dst insets bounds and radii
example: https://fiddle.skia.org/c/@RRect_inset
*/
void inset(SkScalar dx, SkScalar dy, SkRRect* dst) const;
/** Insets bounds by dx and dy, and adjusts radii by dx and dy. dx and dy may be
positive, negative, or zero.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half bounds width, bounds left and right are set to
bounds x-axis center. If dy exceeds half bounds height, bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, bounds is zeroed.
@param dx added to rect().fLeft, and subtracted from rect().fRight
@param dy added to rect().fTop, and subtracted from rect().fBottom
*/
void inset(SkScalar dx, SkScalar dy) {
this->inset(dx, dy, this);
}
/** Outsets dst bounds by dx and dy, and adjusts radii by dx and dy. dx and dy may be
positive, negative, or zero.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half dst bounds width, dst bounds left and right are set to
bounds x-axis center. If dy exceeds half dst bounds height, dst bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, dst bounds is zeroed.
@param dx subtracted from rect().fLeft, and added to rect().fRight
@param dy subtracted from rect().fTop, and added to rect().fBottom
@param dst outset bounds and radii
*/
void outset(SkScalar dx, SkScalar dy, SkRRect* dst) const {
this->inset(-dx, -dy, dst);
}
/** Outsets bounds by dx and dy, and adjusts radii by dx and dy. dx and dy may be
positive, negative, or zero.
If either corner radius is zero, the corner has no curvature and is unchanged.
Otherwise, if adjusted radius becomes negative, pins radius to zero.
If dx exceeds half bounds width, bounds left and right are set to
bounds x-axis center. If dy exceeds half bounds height, bounds top and
bottom are set to bounds y-axis center.
If dx or dy cause the bounds to become infinite, bounds is zeroed.
@param dx subtracted from rect().fLeft, and added to rect().fRight
@param dy subtracted from rect().fTop, and added to rect().fBottom
*/
void outset(SkScalar dx, SkScalar dy) {
this->inset(-dx, -dy, this);
}
/** Translates SkRRect by (dx, dy).
@param dx offset added to rect().fLeft and rect().fRight
@param dy offset added to rect().fTop and rect().fBottom
*/
void offset(SkScalar dx, SkScalar dy) {
fRect.offset(dx, dy);
}
/** Returns SkRRect translated by (dx, dy).
@param dx offset added to rect().fLeft and rect().fRight
@param dy offset added to rect().fTop and rect().fBottom
@return SkRRect bounds offset by (dx, dy), with unchanged corner radii
*/
SkRRect SK_WARN_UNUSED_RESULT makeOffset(SkScalar dx, SkScalar dy) const {
return SkRRect(fRect.makeOffset(dx, dy), fRadii, fType);
}
/** Returns true if rect is inside the bounds and corner radii, and if
SkRRect and rect are not empty.
@param rect area tested for containment
@return true if SkRRect contains rect
example: https://fiddle.skia.org/c/@RRect_contains
*/
bool contains(const SkRect& rect) const;
/** Returns true if bounds and radii values are finite and describe a SkRRect
SkRRect::Type that matches getType(). All SkRRect methods construct valid types,
even if the input values are not valid. Invalid SkRRect data can only
be generated by corrupting memory.
@return true if bounds and radii match type()
example: https://fiddle.skia.org/c/@RRect_isValid
*/
bool isValid() const;
static constexpr size_t kSizeInMemory = 12 * sizeof(SkScalar);
/** Writes SkRRect to buffer. Writes kSizeInMemory bytes, and returns
kSizeInMemory, the number of bytes written.
@param buffer storage for SkRRect
@return bytes written, kSizeInMemory
example: https://fiddle.skia.org/c/@RRect_writeToMemory
*/
size_t writeToMemory(void* buffer) const;
/** Reads SkRRect from buffer, reading kSizeInMemory bytes.
Returns kSizeInMemory, bytes read if length is at least kSizeInMemory.
Otherwise, returns zero.
@param buffer memory to read from
@param length size of buffer
@return bytes read, or 0 if length is less than kSizeInMemory
example: https://fiddle.skia.org/c/@RRect_readFromMemory
*/
size_t readFromMemory(const void* buffer, size_t length);
/** Transforms by SkRRect by matrix, storing result in dst.
Returns true if SkRRect transformed can be represented by another SkRRect.
Returns false if matrix contains transformations that are not axis aligned.
Asserts in debug builds if SkRRect equals dst.
@param matrix SkMatrix specifying the transform
@param dst SkRRect to store the result
@return true if transformation succeeded.
example: https://fiddle.skia.org/c/@RRect_transform
*/
bool transform(const SkMatrix& matrix, SkRRect* dst) const;
/** Writes text representation of SkRRect to standard output.
Set asHex true to generate exact binary representations
of floating point numbers.
@param asHex true if SkScalar values are written as hexadecimal
example: https://fiddle.skia.org/c/@RRect_dump
*/
void dump(bool asHex) const;
SkString dumpToString(bool asHex) const;
/** Writes text representation of SkRRect to standard output. The representation
may be directly compiled as C++ code. Floating point values are written
with limited precision; it may not be possible to reconstruct original
SkRRect from output.
*/
void dump() const { this->dump(false); }
/** Writes text representation of SkRRect to standard output. The representation
may be directly compiled as C++ code. Floating point values are written
in hexadecimal to preserve their exact bit pattern. The output reconstructs the
original SkRRect.
*/
void dumpHex() const { this->dump(true); }
private:
static bool AreRectAndRadiiValid(const SkRect&, const SkVector[4]);
SkRRect(const SkRect& rect, const SkVector radii[4], int32_t type)
: fRect(rect)
, fRadii{radii[0], radii[1], radii[2], radii[3]}
, fType(type) {}
/**
* Initializes fRect. If the passed in rect is not finite or empty the rrect will be fully
* initialized and false is returned. Otherwise, just fRect is initialized and true is returned.
*/
bool initializeRect(const SkRect&);
void computeType();
bool checkCornerContainment(SkScalar x, SkScalar y) const;
// Returns true if the radii had to be scaled to fit rect
bool scaleRadii();
SkRect fRect = SkRect::MakeEmpty();
// Radii order is UL, UR, LR, LL. Use Corner enum to index into fRadii[]
SkVector fRadii[4] = {{0, 0}, {0, 0}, {0,0}, {0,0}};
// use an explicitly sized type so we're sure the class is dense (no uninitialized bytes)
int32_t fType = kEmpty_Type;
// TODO: add padding so we can use memcpy for flattening and not copy uninitialized data
// to access fRadii directly
friend class SkPath;
friend class SkRRectPriv;
};
#endif
| true |
3a54985f3f47a8749f38cf482ec99b9651bc5477 | C++ | shubhgkr/codesignal | /core/gravitation.cpp | UTF-8 | 808 | 2.8125 | 3 | [] | no_license | //
// Created by shubhgkr on 14/10/18.
// https://app.codesignal.com/arcade/code-arcade/waterfall-of-integration/hqrYesGKEaKQnv7Sv
//
#include <vector>
#include <string>
#include <algorithm>
std::vector<int> gravitation(std::vector<std::string> rows)
{
int min = -1;
std::vector<int> ans;
for (int col = 0; col < rows[0].length(); ++col)
{
std::string word = "";
for (int row = 0; row < rows.size(); ++row)
word += rows[row][col];
int count = 0;
while (word.find_first_of('#') < word.find_last_of('.'))
{
count++;
for (int i = word.length() - 2; i >= 0; --i)
if (word[i + 1] == '.')
std::swap(word[i], word[i + 1]);
}
if (count == min)
ans.push_back(col);
if (count < min || min == -1)
{
ans.clear();
ans.push_back(col);
min = count;
}
}
return ans;
} | true |
c6dfc68c56f832f28f723919d3d940d81215bbda | C++ | sauravgupta2800/MyCodingPractice | /Code-Block/nge.cpp | UTF-8 | 558 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int arr[]={5,4,5,6,1,3,9};
int n=7;
stack<int> s;
s.push(0);
for(int i=1;i<n;i++)
{
if(arr[s.top()]>=arr[i])
s.push(i);
else
{
while( !s.empty() && arr[s.top()]<arr[i])
{
arr[s.top()]=arr[i];
s.pop();
}
s.push(i);
}
}
while(!s.empty())
{
arr[s.top()]=-1;
s.pop();
}
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
}
| true |
838a9cd8a5ab57effef488e473f9db7af4336af5 | C++ | sunbun99/Schoolwork-Practice | /Set/mainset.cpp | UTF-8 | 1,022 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include "set.h"
using namespace main_savitch_11;
using namespace std;
int main()
{
set<int> btree;
cout << "After insertion: " << endl;
btree.insert(2);
btree.insert(3);
btree.insert(5);
btree.insert(4);
btree.insert(10);
btree.print(3);
cout << "Searching for forty-five (1 for is present, 0 for not present): " << btree.count(45) << endl;
cout << "Searching for five (1 for is present, 0 for not present): " << btree.count(5) << endl;
btree.erase(4);
cout << "After erasing 4: " << endl;
btree.print(3);
cout << "Inserting 10" << endl;
if(btree.insert(10))
{
btree.print(3);
}
else
{
cout << "The value is already present!" << endl;
}
cout << "Inserting 100" << endl;
btree.insert(100);
btree.print(3);
cout << "Removing 3" << endl;
if(btree.erase(3))
{
btree.print(3);
}
else
{
cout << "The value is not in the set!" << endl;
}
return 0;
}
} | true |
93739ba600ee2debe778350b7bf6742d5adc93f2 | C++ | nixiz/advanced_cpp_course | /src/1-Inheritance/friend_usage.cpp | UTF-8 | 1,081 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "advanced_cpp_topics.h"
#include <sstream>
#include <iostream>
namespace FriendUsageRealWorld {
class Rectangle {
int width, height;
friend class RectangleTest;
public:
Rectangle() {}
Rectangle(int x, int y) : width(x), height(y) {}
int area() const { return width * height; }
friend std::ostream& operator << (std::ostream& os, Rectangle const & rec);
};
std::ostream& operator << (std::ostream& os, Rectangle const & rec)
{
os << "width: " << rec.width << "\theight: " << rec.height << std::endl << "area of rectangle: " << rec.area();
return os;
}
class RectangleTest
{
public:
bool Test()
{
Rectangle rec{ 10,5 };
if (rec.width != 10 || rec.height != 5) return false;
auto result = rec.area();
if (result != 50) return false;
return true;
}
};
} // namespace FriendUsageRealWorld
ELEMENT_CODE(FriendUsageExample) {
namespace fu = FriendUsageRealWorld;
fu::Rectangle rec(3, 5);
std::cout << rec << std::endl;
fu::RectangleTest recTest;
recTest.Test();
}
| true |
a7cfc1cb00aaae02ebd556d267cb413daa2e2ff2 | C++ | adityanjr/code-DS-ALGO | /CodeForces/Complete/800-899/816B-KarenAndCoffee.cpp | UTF-8 | 519 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <vector>
int main(){
const long N = 200100;
std::vector<long> a(N), b(N);
long n, k, q; scanf("%ld %ld %ld", &n, &k, &q);
for(long p = 0; p < n; p++){
long l, r; scanf("%ld %ld", &l, &r);
++a[l]; --a[r + 1];
}
for(long p = 1; p < N; p++){a[p] += a[p - 1];}
for(long p = 1; p < N; p++){b[p] += b[p - 1] + (a[p] >= k);}
while(q--){
long l, r; scanf("%ld %ld", &l, &r);
printf("%ld\n", b[r] - b[l - 1]);
}
return 0;
}
| true |
199db0910eb03f59f340101b414ddec92d6b511e | C++ | MikamiTetsuro365/Atcoder | /Codeforce/A_Start Up.cpp | UTF-8 | 1,057 | 2.578125 | 3 | [] | no_license | #include "bits/stdc++.h"
using namespace std;
typedef long long int ll;
typedef pair<ll, ll > pi;
typedef pair<pair<ll, ll >, ll > pii;
vector<ll > vec;
vector<vector<ll > > vec2;
ll MOD = 1000000007;
ll INF = 1145141919454519;
using namespace std;
//回文判定かと思いきや
//アルファベットも左右対称じゃないと駄目です(試される英語力
int main(){
string S;
cin >> S;
for(ll i = 0; i < S.length() / 2; i++){
if(S[i] != S[S.length()-1-i]){
cout << "NO" << endl;
return 0;
}
}
char check[11] = {'A','H','I','M','O','T','U','V','W','X','Y'};
for(ll i = 0; i < S.length(); i++){
bool f = false;
for(ll j = 0; j < 11; j++){
if(S[i] == check[j]){
f = true;
break;
}
}
if(f == false){
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
return 0;
} | true |
69909ca8de0b8a428f7c12a178f6234833e22eeb | C++ | danscu/onlinejudge | /sols/algo/spfa.cpp | UTF-8 | 1,660 | 2.796875 | 3 | [] | no_license | //Shortest Path Faster Algorithm
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
#define maxint 200000;
using namespace std;
const int juzhen=101;
int a[juzhen][juzhen];//邻接矩阵
int dist[juzhen];//源点到每个点的最短距离
int n;//n为图中的节点数
void spfa(int s)
{
int q[juzhen]; //队列
int v[juzhen]; //v为Boolean,true->已经入队,false->未入队
int h=0,t=1; //h为头指针,t为尾指针
int x,i;
memset(q,0,sizeof(q));
memset(v,0,sizeof(v));
for (i=1;i<=n;i++)
dist[i]=maxint;//初始化dist数组
dist[s]=0; //源点到自己的路径长度为0
q[t]=s; //把源点入队
v[s]=1; //将v[s]置为true
while(h!=t) //本来这应该是h<t,但这是循环队列
{
h=(h+1)%(n+1); //不能用%n,否则队满和对空一样
x=q[h]; //从队头拿出一个元素
v[x]=0;
for (i=1;i<=n;i++)
{
if (dist[i]-a[x][i]>dist[x])
{ //本来是dist[i]>dist[x]+a[x][i]
dist[i]=dist[x]+a[x][i];
if (!v[i])
{
t=(t+1)%(n+1);
q[t]=i;//入队操作
v[i]=1;
}
}
}
}
}
int main()
{
#if BENCH
freopen("spfa.txt","r",stdin);
#endif
int m;//图中边数
int s;//源点的编号
int tt;//目标顶点
int i,x,y,z;
cin>>n>>m>>s;
memset(a,127,sizeof(a));
for (i=1;i<=m;i++)
{
cin>>x>>y>>z;
a[x][y]=z;
a[y][x]=z;
}
spfa(s);
for (i=1;i<=n;i++)
cout<<dist[i]<<endl;
return 0;
}
| true |
3e7f8ce446f9866ba8124c92236cf91eb6758428 | C++ | IT-Jhon/caseTest | /CaseTypeManaServer/subinfos/caseinfo.cpp | UTF-8 | 1,203 | 2.90625 | 3 | [] | no_license | #include "caseinfo.h"
#include <QDebug>
CaseInfo::CaseInfo()
{
m_id.clear();
m_caseType.clear();
m_name.clear();
m_caseCondit.clear();
}
CaseInfo::CaseInfo(const QString &id, const QString &caseType,
const QString &name, const QString &caseCondit)
{
m_id = id;
m_caseType = caseType;
m_name = name;
m_caseCondit = caseCondit;
}
void CaseInfo::display()const
{
qDebug()<< "ID" << m_id;
qDebug()<< "CaseType" << m_caseType;
qDebug()<< "name" << m_name;
qDebug()<< "CaseCondit" << m_caseCondit;
}
void CaseInfo::setID(const QString &id)
{
m_id = id;
}
void CaseInfo::setCaseType(const QString &caseType)
{
m_caseType = caseType;
}
void CaseInfo::setName(const QString &name)
{
m_name = name;
}
void CaseInfo::setCaseCondit(const QString &condit)
{
m_caseCondit = condit;
}
const QString &CaseInfo::getID() const
{
return m_id;
}
const QString &CaseInfo::getCaseType() const
{
return m_caseType;
}
const QString &CaseInfo::getName() const
{
return m_name;
}
const QString &CaseInfo::getCaseCondit() const
{
return m_caseCondit;
}
| true |
fce098e4310ea53de042145e3ea44d8d4e42952c | C++ | joe-zxh/OJ | /剑指offer/面试题66 构建乘积数组.cpp | UTF-8 | 666 | 2.875 | 3 | [] | no_license | class Solution {
public:
vector<int> multiply(const vector<int>& A) {
int sz = A.size();
vector<int> ret(sz);
if(sz==0){
return ret;
}
vector<int> B(sz);
vector<int> C(sz);
B[0] = 1; C[sz-1] = 1;
int curMult = 1;
for(int i = 1;i<sz;i++){
curMult *= A[i-1];
B[i] = curMult;
}
curMult = 1;
for(int i = sz-2;i>=0;i--){
curMult *= A[i+1];
C[i] = curMult;
}
for(int i = 0;i<sz;i++){
ret[i] = B[i]*C[i];
}
return ret;
}
}; | true |
2260c54b1e34f1a6d855456cdb2541a7db901d78 | C++ | nuronialBlock/problemSolving | /ShafayetBlog/DS/LinkedList/linkedList.cpp | UTF-8 | 1,374 | 3.859375 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int a[5];
// Array's distribution in memory
bool ArraySDistribution(){
for (int i = 0; i < 5; ++i) cin >> a[i];
for (int i = 0; i < 5; ++i)
{
printf("For %d, Memory Address in your PC: %d\n", i,&a[i]);
}
}
// node stores data and it's next node's address
struct node
{
int roll;
node *next;
};
node *root = NULL;
// append function appends in the list.
// Complexity O(n); for Array O(1)
bool append(int roll){
if(root == NULL){
root = new node();
root->roll = roll;
root->next = NULL;
}
else {
node *current_node = root;
while(current_node->next != NULL){
current_node = current_node->next;
}
node *new_node = new node();
new_node->roll = roll;
new_node->next = NULL;
current_node->next = new_node;
}
}
// print prints elements.
// For printing a particula index n we need to traverse n.
void print(){
node *cur_node = root;
while(cur_node != NULL){
printf("ROLL: %d\n",cur_node->roll);
cur_node = cur_node->next;
}
}
// deleteNode deletes node from list.
void deleteNode(int roll){
node *cur_node = root;
node *pre_node = NULL;
while(cur_node != NULL){
if(cur_node->roll == roll){
pre_node->next = cur_node->next;
}
pre_node = cur_node;
cur_node = cur_node->next;
}
}
int main()
{
append(1);
append(2);
append(6);
deleteNode(2);
print();
return 0;
} | true |
69c43d6ddf04d1c12abec81077aa942ee9db5499 | C++ | JosephBMartinV/PicrossSDL | /picross/src/board.h | UTF-8 | 1,086 | 2.84375 | 3 | [] | no_license | #ifndef BOARD_H
#define BOARD_H
#include <vector>
#include <string>
class Board{
public:
Board(int s);//overloaded constructors
Board(int r, int c);
enum State {Solve=0, Blank, Mark};//enumeration for board state
//getter functions
int rows();
int cols();
int size();
int idx(int r, int c);
void setBoard();
void printSolution();
void printState();
std::string calcRowGuideString(int r);
std::vector<int> calcRowGuideNum(int r);
std::string calcColGuideString(int c);
std::vector<int> calcColGuideNum(int r);
void makeGuess(int r, int c);
bool checkSolution();
std::vector<std::string> rowGuides;
std::vector<std::string> colGuides;
std::vector<State> state_;
private:
int rows_;
int cols_;
int guideSize_{7};
std::vector<bool> solution_;
//helper function to print top of board
void printTop();
};
#endif | true |
4e824dd2a6da19701d8bf525bb637ff3db03fd99 | C++ | jdnull/LeetCode | /66 Plus One/main.cpp | UTF-8 | 1,173 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int carryOver = 0;
vector<int>::reverse_iterator rit = digits.rbegin();
if (*rit + 1 > 9) {
carryOver = 1;
*rit = 0;
} else {
*rit += 1;
}
for (rit++; rit != digits.rend(); rit++) {
if (*rit + carryOver > 9) {
carryOver = 1;
*rit = 0;
} else {
*rit += carryOver;
carryOver = 0;
}
}
if (carryOver == 0) {
return digits;
} else {
vector<int> v;
v.push_back(1);
for (vector<int>::iterator it = digits.begin(); it != digits.end(); it++) {
v.push_back(*it);
}
return v;
}
}
};
#define COUNT 3
int main() {
int a[COUNT] = {9,9,9};
vector<int> nums(a, &a[COUNT]);
Solution s;
vector<int> v = s.plusOne(nums);
for (int i = 0; i < v.size(); i++) {
cout << v[i];
}
return 0;
}
| true |
d474c6fc0ecd4e0799860bf030fb4336336a8fbc | C++ | chinmaygarde/flutter_engine | /impeller/renderer/backend/vulkan/fence_waiter_vk.cc | UTF-8 | 2,763 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "impeller/renderer/backend/vulkan/fence_waiter_vk.h"
#include <chrono>
#include "flutter/fml/thread.h"
#include "flutter/fml/trace_event.h"
namespace impeller {
FenceWaiterVK::FenceWaiterVK(vk::Device device) : device_(device) {
waiter_thread_ = std::make_unique<std::thread>([&]() { Main(); });
is_valid_ = true;
}
FenceWaiterVK::~FenceWaiterVK() {
Terminate();
if (waiter_thread_) {
waiter_thread_->join();
}
}
bool FenceWaiterVK::IsValid() const {
return is_valid_;
}
bool FenceWaiterVK::AddFence(vk::UniqueFence fence,
const fml::closure& callback) {
if (!IsValid() || !fence || !callback) {
return false;
}
{
std::scoped_lock lock(wait_set_mutex_);
wait_set_[MakeSharedVK(std::move(fence))] = callback;
}
wait_set_cv_.notify_one();
return true;
}
void FenceWaiterVK::Main() {
fml::Thread::SetCurrentThreadName(
fml::Thread::ThreadConfig{"io.flutter.impeller.fence_waiter"});
using namespace std::literals::chrono_literals;
while (true) {
std::unique_lock lock(wait_set_mutex_);
wait_set_cv_.wait(lock, [&]() { return !wait_set_.empty() || terminate_; });
auto wait_set = TrimAndCreateWaitSetLocked();
lock.unlock();
if (!wait_set.has_value()) {
break;
}
if (wait_set->empty()) {
continue;
}
auto result = device_.waitForFences(
wait_set->size(), // fences count
wait_set->data(), // fences
false, // wait for all
std::chrono::nanoseconds{100ms}.count() // timeout (ns)
);
if (!(result == vk::Result::eSuccess || result == vk::Result::eTimeout)) {
break;
}
}
}
std::optional<std::vector<vk::Fence>>
FenceWaiterVK::TrimAndCreateWaitSetLocked() {
if (terminate_) {
return std::nullopt;
}
TRACE_EVENT0("impeller", "TrimFences");
std::vector<vk::Fence> fences;
fences.reserve(wait_set_.size());
for (auto it = wait_set_.begin(); it != wait_set_.end();) {
switch (device_.getFenceStatus(it->first->Get())) {
case vk::Result::eSuccess: // Signalled.
it->second();
it = wait_set_.erase(it);
break;
case vk::Result::eNotReady: // Un-signalled.
fences.push_back(it->first->Get());
it++;
break;
default:
return std::nullopt;
}
}
return fences;
}
void FenceWaiterVK::Terminate() {
{
std::scoped_lock lock(wait_set_mutex_);
terminate_ = true;
}
wait_set_cv_.notify_one();
}
} // namespace impeller
| true |
685c69a3a90bf6fcee82227ec7852edf3c4ecc14 | C++ | jjfnext/ghrr | /filedb/src/app/main.cpp | UTF-8 | 3,464 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
#include <cassert>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
// check the above and delete
#include <QApplication>
#include "main_window.hpp"
#include <QtGlobal>
#include <QDebug>
#include <windows.h>
void msgHandler(QtMsgType msgtp, const QMessageLogContext & msgctx, const QString & msg)
{
QString output = msg + "\n";
OutputDebugString(output.toStdString().c_str());
}
using namespace std;
using namespace boost::filesystem;
using namespace boost::posix_time;
using namespace boost::gregorian;
void check_time(time_t tsec)
{
ptime pt = from_time_t(tsec);
date d = pt.date();
time_duration t = pt.time_of_day();
cout << "date: " << d.year() << ":" << d.month().as_number() << ":" << d.day() << ":" << d.day_of_week() << ":" << d.end_of_month() << endl;
cout << "time: " << t.hours() << ":" << t.minutes() << ":" << t.seconds() << endl;
}
void check_file(path& p)
{
assert(is_regular_file(p));
cout << "size: " << file_size(p) << endl;
time_t mod_time = last_write_time(p);
cout << "mod time: " << mod_time << endl;
cout << "mod time text: " << ctime(&mod_time) << endl;
check_time(mod_time);
}
void check_dir(path& p)
{
assert(is_directory(p));
cout << endl << "list dir: ------" << p << endl;
for (directory_entry& e : directory_iterator(p)) {
path e_path = e.path();
file_status e_stat = e.status();
cout << e_path << endl;
cout << "regular_file: " << is_regular_file(e_stat) << endl;
cout << "dir: " << is_directory(e_stat) << endl;
if (is_directory(e_path)) {
try {
check_dir(e_path);
} catch (const filesystem_error& ex) {
cout << "Error: " << ex.what() << endl;
}
} else if (is_regular_file(e_path)) {
check_file(e_path);
}
}
}
void check_path(path& p)
{
cout << "path: " << p << endl;
if (exists(p)) {
cout << p << " exists" << endl;
} else {
cout << p << " not exists" << endl;
}
if (is_regular_file(p)) {
cout << "file: " << p << ", size: " << file_size(p) << endl;
} else {
cout << p << " not file" << endl;
}
if (is_directory(p)) {
cout << "dir: " << p << endl;
check_dir(p);
} else {
cout << p << " not dir" << endl;
}
}
void test_boost_fs()
{
path p1("C:\\mytest");
check_path(p1);
path p2 = current_path();
check_path(p2);
path p3("C:\\lxu\\sdev\\bsd_prj\\new\\prj\\sqlite1\\src\\runsql\\main.cpp");
check_path(p3);
}
void test_boost()
{
cout << "test boost base" << endl;
string str = "12345";
int i;
try {
i = boost::lexical_cast<int>(str);
cout << "Value: " << i << endl;
} catch( const boost::bad_lexical_cast & ) {
//unable to convert
cerr << "Error: failed to convert";
}
}
void test_stl()
{
vector<int> l = {10, 20, 30};
for (auto i : l) {
// string txt = run_fun(i);
// cout << txt;
}
}
// check the above and do delete
int main(int argc, char* argv[])
{
qInstallMessageHandler(msgHandler);
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
| true |
1b1940da5f741e0d0557d413a59e8e50fe6d76cb | C++ | BjornVT/Masterproef | /seek_thermal/camSettings.cpp | UTF-8 | 1,898 | 2.640625 | 3 | [] | no_license |
#include "camSettings.hpp"
void camSettings::write(FileStorage& fs) const //Write serialization for this class
{
fs << "{"
<< "cameraMatrixRGB" << cameraMatrix[RGB]
<< "cameraMatrixLWIR" << cameraMatrix[LWIR]
<< "distCoeffsRGB" << distCoeffs[RGB]
<< "distCoeffsLWIR" << distCoeffs[LWIR]
<< "totalAvgErrRGB" << totalAvgErr[RGB]
<< "totalAvgErrLWIR" << totalAvgErr[LWIR]
<< "rmsRGB" << rms[RGB]
<< "rmsLWIR" << rms[LWIR]
<< "H" << H
<< "}";
}
void camSettings::read(const FileNode& node) //Read serialization for this class
{
node["cameraMatrixRGB" ] >> cameraMatrix[RGB];
node["cameraMatrixLWIR"] >> cameraMatrix[LWIR];
node["distCoeffsRGB"] >> distCoeffs[RGB];
node["distCoeffsLWIR"] >> distCoeffs[LWIR];
node["totalAvgErrRGB"] >> totalAvgErr[RGB];
node["totalAvgErrLWIR"] >> totalAvgErr[LWIR];
node["rmsRGB"] >> rms[RGB];
node["rmsLWIR"] >> rms[LWIR];
node["H"] >> H;
}
bool camSettings::GoodCam()
{
for(int i=0; i<2; i++){
if(!(cameraMatrix[i].size() == Size(3, 3)))
{
return false;
}
if(!(distCoeffs[i].size() == Size(5, 1)))
{
return false;
}
}
return true;
}
bool camSettings::GoodH()
{
if(!(H.size() == Size(3, 3)))
{
return false;
}
return true;
}
/*
void camSettings::interprate()
{
goodInput = true;
/*
if(!(cameraMatrix[RGB].size() == Size(3, 3) && cameraMatrix[RGB].at<double>(0, 0) != 0))
{
goodInput = false;
}
//Mat cameraMatrix[2] = {Mat::eye(3, 3, CV_64F)};
//Mat distCoeffs[2] = {Mat::zeros(8, 1, CV_64F)};
/*
if(boardSize.width <= 0 || boardSize.height <= 0){
cerr << "Invalid Board size: " << boardSize.width << " " << boardSize.height << endl;
goodInput = false;
}
if(squareSize <= 10e-6){
cerr << "Invalid square size " << squareSize << endl;
goodInput = false;
}
}
*/
| true |
4a7bdf88caebb4db9fd3104bf34cffd2c7da94f4 | C++ | Korko/sia-ifips-2010 | /PropreRayWindows/Intersection.cpp | UTF-8 | 818 | 2.796875 | 3 | [] | no_license | #include "Intersection.h"
#include <float.h>
Intersection::Intersection():couleur(), distance(FLT_MAX), contact(), normale(){
}
Intersection::Intersection(Couleur n_couleur): couleur(n_couleur),
distance(FLT_MAX), contact(), normale(){
}
Intersection::Intersection(Couleur n_couleur, float n_distance):
couleur(n_couleur), distance(n_distance), contact(), normale(){
}
//Intersection::Intersection(const Intersection& orig){}
Intersection::~Intersection() {
}
float Intersection::get_distance()const{
return distance;
}
void Intersection::set_distance(const float n_distance){
distance = n_distance;
}
Couleur Intersection::get_couleur()const{
return couleur;
}
void Intersection::set_couleur(const Couleur n_couleur){
couleur = n_couleur;
}
| true |
b7c139c8879dd2e9760cde9a9a4fcf3a55d87915 | C++ | derickwarshaw/CPPLabs | /Programming 2330/Lab/Lab8.cpp | UTF-8 | 3,749 | 4.21875 | 4 | [] | no_license | // Derick Warshaw
// Lab #8 Character processing with arrays
// COSC2330 Section 001
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
// variable initialization
const int SIZE = 20;
char line[SIZE];
int count = 0;
char letter;
bool stop = false;
int bucket = 0;
bool big = true;
// prompting user to enter a name
cout << "Enter a fully lower case or uppercase name of no more than "
<< (SIZE - 1) << " characters "<<endl;
// reading name into array of characters
cin.getline(line, SIZE);
cout << "The name you entered in uppercase is ";
// loop to iterate until it encounters null value in the array
while (line[count] != '\0')
{
// if the user entered all lower case letters
if (line[count] > 90)
{
// convert to uppercase and put in variable
letter = line[count] - 32;
// output the character to the console
cout << letter;
// add one to the bucket accumulator -- keeping track of # charac.'s
bucket = bucket + 1;
// increment the loop counter
count++;
}
// if the user entered uppercase characters i.e. line[count] < 90
else
{
// put character in variable
letter = line[count];
// output the character to console
cout << letter;
// add one to the bucket accumulator -- keeping track of # charac.'s
bucket = bucket + 1;
// increment the loop counter
count ++;
}
}
cout << "" << endl;
cout << "The name you entered in reverse order is ";
/** since we know how many elements are in the array we can use that to
count backwards and print the characters minus the null terminator */
for (count = bucket - 1; count >= 0; count--)
{
// put character in variable and then print to console
letter = line[count];
cout << letter;
}
cout << "" << endl;
// we have a record of the number of characters in the accumulator - print
cout << "The number of characters in the name is " << (bucket) << endl;
cout << "A Weird way to display the name you entered is ";
// if user enters all lower case for the name
for (count = 0; count <= (bucket - 1); count++)
{
/** if the character is lower case and we need a uppercase character */
if (line[count] >= 90 && big == true)
{
// read character in, make it upper case, print it out
letter = line[count] - 32;
cout << letter;
// set big flag to false because we don't need another uppercase
big = false;
}
/** if the character is lower case and we don't need another uppercase*/
else if (line[count] >= 90 && big == false)
{
// read in the character, print the character to console
letter = line[count];
cout << letter;
// set big flag to true because we need the next character uppercase
big = true;
}
}
big = true;
// Loop to catch if user enters all caps for the name
for (count = 0; count <= (bucket - 1); count++)
{
// if the character is uppercase and we need to print an uppercase
if (line[count] <= 90 && big == true)
{
// read the character in and print to console
letter = line[count];
cout << letter;
// set flag to false since we don't need an uppercase next
big = false;
}
// if the character is uppercase and we don't need uppercase
else if (line[count] <= 90 && big == false)
{
// read in character, make it lower case, print to console
letter = line[count] + 32;
cout << letter;
// set flag to true since we need an uppercase character next
big = true;
}
}
return 0;
}
| true |
7c7f5a623c7d7f28895097d4479e0b063b44aa25 | C++ | Akkarim/TP1-CI-1221-II-3ra | /Arbol/hijoIzqHD1.cpp | UTF-8 | 3,553 | 2.75 | 3 | [] | no_license | /*
* File: hijoIzqHD1.cpp
* Author: luisd
*
* Created on 25 de septiembre de 2017, 09:14 PM
*/
#include "hijoIzqHD1.h"
hijoIzqHD1::hijoIzqHD1() {
}
hijoIzqHD1::~hijoIzqHD1() {
}
void hijoIzqHD1::iniciar() {
primero = new NodohIHD1();
cantidadNodos = 0;
}
void hijoIzqHD1::destruir() {
delete this;
}
void hijoIzqHD1::vaciar() {
nodo inicio = primero;
vaciarRecursivo(inicio);
cantidadNodos = 0;
}
void hijoIzqHD1::vaciarRecursivo(nodo n) {
if (n->hijos != 0) {
nodo iterador = n->hijoIzq;
nodo aux = new NodohIHD1();
while (iterador != 0) {
if (iterador->hermanoDer != 0) {
aux = iterador->hermanoDer;
delete iterador;
iterador = aux;
} else{
delete iterador;
return;
}
}
nodo nh = n->hijoIzq;
while (nh != 0) {
vaciarRecursivo(n);
nh = nh->hermanoDer;
}
}
}
bool hijoIzqHD1::vacia() {
if (cantidadNodos == 0) {
return true;
}
return false;
}
hijoIzqHD1::nodo hijoIzqHD1::agregarHijo(int e, int i, nodo n) {
nodo temp = new NodohIHD1(e);
if (i == 1) {
if (n->hijoIzq != 0) {
temp->hermanoDer = n->hijoIzq;
n->hijoIzq = temp;
} else {
n->hijoIzq = temp;
}
} else {
int contador = 1;
nodo iterador = n->hijoIzq;
while (contador < i && iterador->hermanoDer != 0) {
iterador = iterador->hermanoDer;
contador++;
}
temp->hermanoDer = iterador->hermanoDer;
iterador->hermanoDer = temp;
}
n->hijos++;
cantidadNodos++;
return temp;
}
void hijoIzqHD1::borrarHoja(nodo n) {
//Recorrido en preOrden para encontrar al padre
nodo padre = preOrden(primero, n);
nodo iterador = padre->hijoIzq;
if (iterador->etiqueta == n->etiqueta) {
padre->hijoIzq = iterador->hermanoDer;
delete iterador;
} else {
while (iterador->hermanoDer->etiqueta != n->etiqueta) {
iterador = iterador->hermanoDer;
}
iterador->hermanoDer = iterador->hermanoDer->hermanoDer;
}
delete n;
padre->hijos--;
}
void hijoIzqHD1::modEtiqueta(nodo n, int e) {
n->etiqueta = e;
}
hijoIzqHD1::nodo hijoIzqHD1::raiz() {
return primero;
}
void hijoIzqHD1::ponerRaiz(int e) {
nodo temp = new NodohIHD1(e);
primero = temp;
cantidadNodos++;
}
hijoIzqHD1::nodo hijoIzqHD1::padre(nodo n) {
nodo temp = primero;
return preOrden(temp, n);
}
hijoIzqHD1::nodo hijoIzqHD1::hijoMasIzquierdo(nodo n) {
return n->hijoIzq;
}
hijoIzqHD1::nodo hijoIzqHD1::hermanoDerecho(nodo n) {
return n->hermanoDer;
}
int hijoIzqHD1::etiqueta(nodo n) {
return n->etiqueta;
}
int hijoIzqHD1::numNodos() {
return cantidadNodos;
}
int hijoIzqHD1::numHijos(nodo n) {
return n->hijos;
}
hijoIzqHD1::nodo hijoIzqHD1::traductor(int e) {
nodo temp = new NodohIHD1(e);
return temp;
}
hijoIzqHD1::nodo hijoIzqHD1::preOrden(nodo inicio, nodo n) {
if (inicio->hijos != 0) {
nodo iterador = inicio->hijoIzq;
while (iterador != 0) {
if (iterador->etiqueta == n->etiqueta) {
return inicio;
} else {
iterador = iterador->hermanoDer;
}
}
nodo nh = inicio->hijoIzq;
while (nh != 0) {
preOrden(nh, n);
nh = nh->hermanoDer;
}
}
} | true |
8ffc748e69af73280a998c4aa27a0a7c106b728e | C++ | adamja/HydroControl | /wemos_controller/src/main.cpp | UTF-8 | 5,839 | 2.59375 | 3 | [] | no_license | /*
Program: Wemos Hydro Control
Version: 1.0.0
Author: Adam Jacob
Comments:
TODO:
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h> // Over the air
#include <PubSubClient.h> // MQTT library
#include <QueueArray.h> // Queue library for holding serial input messages
#include <SoftwareSerial.h>
/* Serial Settings */
#define BAUD_RATE 9600 // Hardware Serial Baud Rate
#define BAUD_RATE_SS 115200 // Software Serial Baud Rate. Do not use 9600, it causes the wemos to crash and restart during transmission. 115200 appears to work well.
#define BUFSIZE 100
const char MSG_SPLITTER = '|'; // Splitter to seperate topic and message within a serial message
const char MSG_END = '$'; // Symbol to determine end of serial message
QueueArray <char> char_queue; // Serial char buffer
String topic = "";
String msg = "";
/* Software Serial */
int pinRx = 14; // D5
int pinTx = 12; // D6
SoftwareSerial softSerial(pinRx, pinTx, false, BUFSIZE); // SoftwareSerial(int receivePin, int transmitPin, bool inverse_logic = false, unsigned int buffSize = 64);
/* WiFi Settings */
const char* ssid = ""; // WIFI SSID
const char* password = ""; // WIFI Password
/* MQTT */
const char* mqttSubTopic = "hydrocontroller/send/#"; // MQTT topic
String mqttPubTopic = "hydrocontroller/rec/"; // MQTT topic send
IPAddress broker(192,168,40,101); // Address of the MQTT broker
#define CLIENT_ID "hydrocontroller" // Client ID to send to the broker
#define mqttUser "" // broker username
#define mqttPass "" // broker password
#define brokerPort 1883 // broker port
/* WIFI */
WiFiClient wificlient;
PubSubClient client(wificlient);
void sendToSerial(String t, String m) {
// Send payload to ardino via serial link
// Capture the last section of the topic
String temp = "";
for (int i = 0; i < t.length(); i++) {
if (t[i] == '/') {
temp = "";
}
else {
temp += t[i];
}
}
// Create a message to send via serial on the format of: "topic|message$"
String flush_payload = String(MSG_SPLITTER) + String(MSG_END);
String payload = temp + MSG_SPLITTER + m + MSG_END;
Serial.print("Sending via Software Serial: "); Serial.println(payload);
softSerial.print(flush_payload); // Clear the buffer at the reciever prior to sending the message. Was having issues with junk readings at the receiver
softSerial.print(payload); // Send payload
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String msg = "";
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
msg.concat((char)payload[i]);
}
Serial.println();
sendToSerial(topic, msg);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(CLIENT_ID, mqttUser, mqttPass)) {
Serial.println("connected");
client.subscribe(mqttSubTopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void sendToMqtt() {
String t = mqttPubTopic + topic;
char charBufTopic[BUFSIZE];
char charBufMsg[BUFSIZE];
t.toCharArray(charBufTopic, BUFSIZE); // Convert Topic String to char array
msg.toCharArray(charBufMsg, BUFSIZE); // Convert Message String to char array
client.publish(charBufTopic, charBufMsg); // Publish to MQTT Broker
topic = "";
msg = "";
}
void serialEvent() {
while (softSerial.available()) {
char inChar = (char)softSerial.read(); // get the new byte
if (inChar == MSG_SPLITTER) {
topic = "";
while (!char_queue.isEmpty ()) {
topic += char_queue.dequeue();
}
if (topic.length() > 0) {
Serial.print("Received topic: "); Serial.println(topic);
}
}
else if (inChar == MSG_END) {
msg = "";
while (!char_queue.isEmpty ()) {
msg += char_queue.dequeue();
}
if (msg.length() > 0) {
Serial.print("Received message: "); Serial.println(msg);
if (topic.length() > 0) {
sendToMqtt();
}
}
}
else {
char_queue.enqueue(inChar); // add recieved to the char_queue
}
}
}
void setup() {
Serial.begin(BAUD_RATE);
softSerial.begin(BAUD_RATE_SS);
Serial.println("Booting");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("WiFi begun");
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
Serial.println("Ready");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
/* Prepare MQTT client */
client.setServer(broker, brokerPort);
client.setCallback(callback);
}
void loop() {
ArduinoOTA.handle();
if (WiFi.status() != WL_CONNECTED)
{
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
reconnect();
}
}
if (client.connected())
{
client.loop();
}
serialEvent();
delay(10);
} | true |
cd7fb3502059fb98e41a6001b40db797ebb4a530 | C++ | alexjhoff/C | /COEN 70/ExpressionTree/ExpressionTree/ExpressionTree.h | UTF-8 | 2,504 | 3.234375 | 3 | [] | no_license | //
// ExpressionTree.h
// ExpressionTree
//
// Created by Alex Hoff and Nathan Tucker on 2/24/14.
// Copyright (c) 2014 Alex Hoff and Nathan Tucker. All rights reserved.
//
#ifndef ExpressionTree_ExpressionTree_h
#define ExpressionTree_ExpressionTree_h
#include <iostream>
#include <string>
using namespace std;
class Tree
{
public:
~Tree();
Tree();
void build(string&);
int evaluate();
void print_preorder();
void print_postorder();
void print_inorder();
int operand;
char opertor;
Tree* right_field;
Tree* left_field;
};
Tree::Tree(){
operand = -1;
opertor = '\0';
right_field = NULL;
left_field = NULL;
}
Tree::~Tree(){
delete left_field;
delete right_field;
}
void Tree::build(string &temp){
if (isdigit(temp[0])){
operand = temp[0] - '0';
return;
}
else{
opertor = temp[0];
left_field = new Tree();
right_field = new Tree();
left_field->build(temp.erase(0,2));
if (temp.length() <= 2) {
right_field->build(temp);
return;
}
right_field->build(temp.erase(0,2));
}
}
int Tree::evaluate(){
if (opertor != '\0') {
if(opertor == '*'){
return (left_field->evaluate() * right_field->evaluate());
}
else if (opertor == '/'){
return (left_field->evaluate() / right_field->evaluate());
}
else if (opertor == '+'){
return (left_field->evaluate() + right_field->evaluate());
}
else if(opertor == '-'){
return (right_field->evaluate() - left_field->evaluate());
}
}
return operand;
}
//We have no clue why our prints are not working
//We talked to you in lab and you couldnt figure it out either
//we are taking it to prof. potika
void Tree::print_inorder(){
if(left_field) left_field->print_inorder();
if (opertor == '\0') {
cout << operand;
}
else
cout << opertor;
if(right_field) right_field->print_inorder();
}
void Tree::print_preorder(){
if (opertor == '\0') {
cout << operand;
}
else
cout << opertor;
if(left_field) left_field->print_preorder();
if(right_field) right_field->print_preorder();
}
void Tree::print_postorder(){
if(left_field) left_field->print_postorder();
if(right_field) right_field->print_postorder();
if (opertor == '\0') {
cout << operand;
}
else
cout << opertor;
}
#endif
| true |
81f3faa8db69c017391932954d32106fb22f4c88 | C++ | kzeoh/CodePractice | /Codility/4-1.cpp | UTF-8 | 960 | 2.859375 | 3 | [] | no_license | // you can use includes, for example:
#include <algorithm>
#include <map>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(int X, vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
int count = 0;
int answer = -1, idx=0, tar=X;
map <int,int> m;
m[A[0]]=1;
for(int i=0;i<A.size();i++){
if(i>0)
m[A[i]]=i;
if(tar==A[i]){
count =tar;
for(int j=tar;j>=1;j--){
if(m[j]){
count--;
}else if(A.size()==1){
return 0;
}
else{
break;
}
//cout << j << " "<< m[j]<<"\n";
}
if(count==0){
answer=i;
break;
}else{
tar=count;
}
}
}
return answer;
}
| true |
c336660ca7de608b0ee590063beb078aeea48e86 | C++ | kryheb/coursera-crypto | /week6-public-key-encryption/src/main.cpp | UTF-8 | 9,671 | 2.515625 | 3 | [] | no_license | #include <stdio.h>
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <gmpxx.h>
#include "utils/log/log.hpp"
#include <boost/algorithm/string.hpp>
class ModulusFactorBase
{
protected:
explicit ModulusFactorBase(const std::string aMpzStr):
N{aMpzStr}
{}
virtual mpz_class factorN() = 0;
mpz_class getSqrtN()
{
mpz_t a;
mpz_init(a);
// a=ceil(sqrt(N))
mpz_sqrt(a, N.get_mpz_t());
mpz_add_ui(a, a, 1);
BOOST_LOG_TRIVIAL(debug) << "a=ceil(sqrt(N)) " << a;
auto retValue = mpz_class(a);
mpz_clear(a);
return retValue;
}
bool testN(mpz_class _p, mpz_class _q)
{
mpz_t n;
mpz_init(n);
mpz_mul(n, _p.get_mpz_t(), _q.get_mpz_t());
BOOST_LOG_TRIVIAL(debug) << "N=pq " << n;
auto retVal = testN(mpz_class(n));
mpz_clear(n);
return retVal;
}
bool testN(mpz_class _value)
{
return mpz_cmp(N.get_mpz_t(), _value.get_mpz_t()) == 0;
}
mpz_class getX(mpz_class _a)
{
mpz_t x_sq,x;
mpz_init(x);
mpz_init(x_sq);
// x=sqrt(A^2−N)
mpz_mul(x_sq, _a.get_mpz_t(), _a.get_mpz_t());
mpz_sub(x_sq, x_sq, N.get_mpz_t());
mpz_sqrt(x, x_sq);
BOOST_LOG_TRIVIAL(debug) << "x=sqrt(A^2−N) " << x;
auto retValue = mpz_class(x);
mpz_clear(x);
mpz_clear(x_sq);
return retValue;
}
std::pair<mpz_class, mpz_class> getPrimes(mpz_class _a, mpz_class _x)
{
mpz_t p,q;
mpz_init(p);
mpz_init(q);
// p=a−x
mpz_sub(p, _a.get_mpz_t(), _x.get_mpz_t());
BOOST_LOG_TRIVIAL(debug) << "p=a−x " << p;
// q=a+x
mpz_add(q, _a.get_mpz_t(), _x.get_mpz_t());
BOOST_LOG_TRIVIAL(debug) << "q=a+x " << q;
auto retValue = std::make_pair(mpz_class(p), mpz_class(q));
mpz_clear(p);
mpz_clear(q);
return retValue;
}
mpz_class min(mpz_class _l, mpz_class _r)
{
return (mpz_cmp(_l.get_mpz_t(), _r.get_mpz_t()) < 0) ? _l : _r;
}
const mpz_class N;
};
class ModulusFactor_1 : public ModulusFactorBase
{
public:
ModulusFactor_1():
ModulusFactorBase{"17976931348623159077293051907890247336179769789423065727343008115"
"77326758055056206869853794492129829595855013875371640157101398586"
"47833778606925583497541085196591615128057575940752635007475935288"
"71082364994994077189561705436114947486504671101510156394068052754"
"0071584560878577663743040086340742855278549092581"}
{}
mpz_class factorN() override final
{
auto a = getSqrtN();
auto x = getX(a);
auto [p, q] = getPrimes(a, x);
if (!testN(p, q)) {
throw std::runtime_error("ModulusFactor_1 test failed");
}
this->p = p;
this->q = q;
return min(p, q);
}
std::string parseMessage(mpz_class _value)
{
std::stringstream sstr;
sstr << std::hex << _value;
auto valueStr = sstr.str();
BOOST_LOG_TRIVIAL(debug) << "hex " << valueStr;
if (!boost::starts_with(valueStr, "2")) {
throw std::runtime_error("ModulusFactor_1 PCKS message does not start with 2");
}
auto msgIndex = valueStr.find("00");
if (msgIndex == std::string::npos) {
throw std::runtime_error("ModulusFactor_1 00 separator not found");
}
auto msgStr = valueStr.substr(msgIndex);
std::string message;
for (auto i=0; i<msgStr.size(); i+=2) {
std::string byte = msgStr.substr(i, 2);
char c = (char) strtol(byte.c_str(), nullptr, 16);
message.push_back(c);
}
return message;
}
std::string decrypt()
{
if (!testN(p, q)) {
throw std::runtime_error("ModulusFactor_1 test failed");
}
mpz_t m;
mpz_init(m);
// m ≡ c^d (mod n)
auto [n,d] = getPrivateKey();
mpz_powm(m, cipherTxt.get_mpz_t(), d.get_mpz_t(), n.get_mpz_t());
BOOST_LOG_TRIVIAL(debug) << "plain pcks " << m;
auto pkcsMessage = mpz_class(m);
mpz_clear(m);
return parseMessage(pkcsMessage);
}
private:
const mpz_class cipherTxt {"2209645186741038177630656113488341801741006978789283107173183914"
"3676135600120538004282329650473509424343946219751512256465839967"
"9428894607645420405815647489880137348641204523252293201764879166"
"6640299750918872997169052608322206777160001932926087000957999372"
"4077458967773697817571267229951148662959627934791540"};
mpz_class p, q;
mpz_class getPhiN()
{
mpz_t phiN, pp, qp;
mpz_init(phiN);
mpz_init(pp);
mpz_init(qp);
// Euler's funtion φ(n) = (p−1)(q−1)
mpz_sub_ui(pp, this->p.get_mpz_t(), 1);
mpz_sub_ui(qp, this->q.get_mpz_t(), 1);
mpz_mul(phiN, pp, qp);
BOOST_LOG_TRIVIAL(debug) << "φ(n)=(p−1)(q−1) " << phiN;
auto retValue = mpz_class(phiN);
mpz_clear(phiN);
mpz_clear(pp);
mpz_clear(qp);
return retValue;
}
std::pair<mpz_class, mpz_class> getPrivateKey()
{
mpz_t d, exp;
mpz_init(d);
mpz_init_set_ui(exp, 65537);
//d ≡ e−1 (mod φ(n))
auto phiN = getPhiN();
mpz_invert(d, exp, phiN.get_mpz_t());
BOOST_LOG_TRIVIAL(debug) << "d " << d;
auto retD = mpz_class(d);
mpz_clear(d);
mpz_clear(exp);
return std::make_pair(N, retD);
}
};
class ModulusFactor_2 : public ModulusFactorBase
{
public:
ModulusFactor_2():
ModulusFactorBase{"6484558428080716696628242653467722787263437207069762630604390703787"
"9730861808111646271401527606141756919558732184025452065542490671989"
"2428844841839353281972988531310511738648965962582821502504990264452"
"1008852816733037111422964210278402893076574586452336833570778346897"
"15838646088239640236866252211790085787877"}
{}
mpz_class factorN() override final
{
auto sqrtn = getSqrtN();
mpz_t a, end;
mpz_init_set(a, sqrtn.get_mpz_t());
mpz_init(end);
// A−sqrt(N)<2^20
mpz_add_ui(end, sqrtn.get_mpz_t(), pow(2, 20));
do {
mpz_add_ui(a, a, 1);
auto x = getX(mpz_class(a));
auto [p, q] = getPrimes(mpz_class(a), x);
if (testN(p,q)) {
BOOST_LOG_TRIVIAL(debug) << "FOUND PRIMES";
mpz_clear(end);
mpz_clear(a);
return min(p, q);
}
} while (
(mpz_cmp(a, end) != 0)
);
mpz_clear(end);
mpz_clear(a);
throw std::runtime_error("ModulusFactor_2 primes not found");
}
};
class ModulusFactor_3 : public ModulusFactorBase
{
public:
ModulusFactor_3():
ModulusFactorBase{"72006226374735042527956443552558373833808445147399984182665305798191"
"63556901883377904234086641876639384851752649940178970835240791356868"
"77441155132015188279331812309091996246361896836573643119174094961348"
"52463970788523879939683923036467667022162701835329944324119217381272"
"9276147530748597302192751375739387929"}
{}
mpz_class factorN() override final
{
/*
* sqrt(N)
* -|----------------------|-|---------------------------|-
* p A=(p+q)/2 q
* p and q are odd, therefore A is integer
* sqrt(6N)
* -|--|-------------------|-|-----------------------------
* p q A=(3p+2q)/2
* =>
* sqrt(6N)
* -|----------------------|-|----------------------------|-
* 3p A=(3p+2q)/2 2q
* (3p+2q) might be odd, therefore multiply by two
* 2sqrt(6N)=sqrt(24N)
* -|----------------------|-|----------------------------|-
* 6p A=(6p+4q)/2 4q
* (6p+4q) is even
*/
auto a = get2Sqrt6N();
auto x = getSqrtApow2Sub24N(a);
auto [p6, q4] = getPrimes(a, x);
mpz_t p,q;
mpz_init(p);
mpz_init(q);
mpz_div_ui(p, p6.get_mpz_t(), 6);
mpz_div_ui(q, q4.get_mpz_t(), 4);
BOOST_LOG_TRIVIAL(debug) << "p " << p;
BOOST_LOG_TRIVIAL(debug) << "q " << q;
if (!testN(mpz_class(p), mpz_class(q))) {
throw std::runtime_error("ModulusFactor_3 test failed");
}
auto retValue = min(mpz_class(p), mpz_class(q));
mpz_clear(p);
mpz_clear(q);
return retValue;
}
private:
mpz_class get2Sqrt6N()
{
mpz_t a;
mpz_init(a);
// a=ceil(2sqrt(6N)) => a=ceil(sqrt(24N))
mpz_mul_ui(a, N.get_mpz_t(), 24);
mpz_sqrt(a, a);
mpz_add_ui(a, a, 1);
BOOST_LOG_TRIVIAL(debug) << "a=ceil(2sqrt(6N)) " << a;
auto retValue = mpz_class(a);
mpz_clear(a);
return retValue;
}
mpz_class getSqrtApow2Sub24N(mpz_class _a)
{
mpz_t x_sq,x,n;
mpz_init(x);
mpz_init(n);
mpz_init(x_sq);
// x=sqrt(A^2−24N)
mpz_mul(x_sq, _a.get_mpz_t(), _a.get_mpz_t());
mpz_mul_ui(n, N.get_mpz_t(), 24);
mpz_sub(x_sq, x_sq, n);
mpz_sqrt(x, x_sq);
BOOST_LOG_TRIVIAL(debug) << "x=sqrt(A^2−24N) " << x;
auto retValue = mpz_class(x);
mpz_clear(x);
mpz_clear(x_sq);
mpz_clear(n);
return retValue;
}
};
int main(void)
{
Logger::getInstance().init();
ModulusFactor_1 mf1;
auto r1 = mf1.factorN();
auto r1Message = mf1.decrypt();
ModulusFactor_2 mf2;
auto r2 = mf2.factorN();
ModulusFactor_3 mf3;
auto r3 = mf3.factorN();
BOOST_LOG_TRIVIAL(debug)
<< "\nResults:\n"
<< "\t(1): " << r1 << "\n"
<< "\t(2): " << r2 << "\n"
<< "\t(3): " << r3 << "\n"
<< "\t(4): " << r1Message << "\n"
<< "\n";
return 0;
}
| true |
33afa253bd185ca4e5c3f3db566a436099b102ab | C++ | thejasonhsu/Monopoly | /guiplayer.cpp | UTF-8 | 780 | 2.90625 | 3 | [] | no_license | #include "guiplayer.h"
#include "player.h"
#include <iostream>
#include <string>
GUIPlayer::GUIPlayer( Player* p )
{
player = p;
if(nameLabel == NULL)
nameLabel = new QLabel( this );
nameLabel->setTextFormat(Qt::RichText);
updateStats();
}
QString GUIPlayer::convert(int num)
{
QString str = "";
while(num != 0)
{
str = static_cast<char>(num % 10 + '0') + str;
num /= 10;
}
return str;
}
void GUIPlayer::updateStats()
{
QString str = player->getToken();
QString money = convert(player->getMoney());
nameLabel->setText("<b><font color=\"blue\">" + str + "</font></b>: $" + money);
}
void GUIPlayer::setMoney(int money)
{
int total = money - player->getMoney();
player->addMoney(total);
updateStats();
}
| true |
f46a4f2659c852e4a691a340302d4b1949c3f972 | C++ | lynar/-Cplusplus-Snoopy | /object.h | ISO-8859-1 | 543 | 2.96875 | 3 | [] | no_license | #ifndef OBJECT_H_INCLUDED
#define OBJECT_H_INCLUDED
#include "console.h"
class Object
{
protected: ///peut etre modifi dans les classes hritires
int m_coordX; // coordonnes en X
int m_coordY;
public:
//constructeur destructeur
Object();
Object(int coordX, int coordY);
~Object();
//methods
//accesseurs
///getters
int getcoordX() const;
int getcoordY() const;
///setters
void setCoordX(int _coordX);
void setCoordY(int _coordY);
};
#endif // OBJECT_H_INCLUDED
| true |
479d8a29199387a6aa2d50c72eea2daee1426e88 | C++ | jmatta1/DecompLib | /Example/DecomposeSpectrum/MiscLib/UserIo.cpp | UTF-8 | 6,674 | 2.75 | 3 | [
"MIT"
] | permissive | /*!*****************************************************************************
********************************************************************************
**
** @copyright Copyright (C) 2018 James Till Matta
**
** 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.
**
********************************************************************************
*******************************************************************************/
#include"UserIo.h"
#include<iostream>
int getStartingValType()
{
int initValSetting = 0;
bool validAnswer=false;
while(!validAnswer)
{
std::cout<<"Intitial Value Setting?"<<std::endl;
std::cout<<" 0 - Scaled Spectrum\n 1 - Constant"<<std::endl;
std::cin>>initValSetting;
if((initValSetting > -1) && (initValSetting < 2))
{
validAnswer = true;
}
else
{
std::cout<<"Invalid Choice, Try Again"<<std::endl;
}
}
return initValSetting;
}
double getScalingFactor()
{
double scaleFactor = 0.0;
bool validAnswer=false;
while(!validAnswer)
{
std::cout<<"Spectrum Scaling Factor?"<<std::endl;
std::cin>>scaleFactor;
if(scaleFactor > 0.0)
{
validAnswer = true;
}
else
{
std::cout<<"The scaling factor must be greater than zero. Try Again"<<std::endl;
}
}
return scaleFactor;
}
double getStartingConstant()
{
double constantVal = 0.0;
bool validAnswer=false;
while(!validAnswer)
{
std::cout<<"Constant Value?"<<std::endl;
std::cin>>constantVal;
if(constantVal > 0.0)
{
validAnswer = true;
}
else
{
std::cout<<"The constant must be greater than zero. Try Again"<<std::endl;
}
}
return constantVal;
}
double getMinThreshold()
{
double thresh = 0.0;
bool validAnswer=false;
while(!validAnswer)
{
std::cout<<"Convergence Consideration Threshold?"<<std::endl;
std::cin>>thresh;
if(thresh > 0.0)
{
validAnswer = true;
}
else
{
std::cout<<"The threshold must be greater than zero. Try Again"<<std::endl;
}
}
return thresh;
}
double getConvergence()
{
double conv = 0.0;
bool validAnswer=false;
while(!validAnswer)
{
std::cout<<"Convergence Maximum Fractional Change?"<<std::endl;
std::cin>>conv;
if(conv > 0.0)
{
validAnswer = true;
}
else
{
std::cout<<"The maximum fractional change for convergence must be greater than zero. Try Again"<<std::endl;
}
}
return conv;
}
void get2dAxisBounds(TwoDMetaData& meta)
{
//get edge bins for X-axis
std::cout<<"\n\nThe X-axis of the response matrix has "<<meta.numXbins<<" bins and\n";
std::cout<<" the low edge of the first bin is: "<<meta.firstXbinLoEdge<<"\n"
<<" and the high edge of the last bin is: "<<meta.finalXbinHiEdge<<std::endl;
double perBin = (meta.finalXbinHiEdge - meta.firstXbinLoEdge)/static_cast<double>(meta.numXbins);
meta.startXbin = Detail::getAxisLoBound("X", meta.numXbins, meta.firstXbinLoEdge, perBin);
meta.stopXbin = Detail::getAxisHiBound("X", meta.numXbins, meta.finalXbinHiEdge, perBin);
//get edge bins for Y-axis
std::cout<<"\n\nThe Y-axis of the response matrix has "<<meta.numYbins<<" bins\n";
std::cout<<" the low edge of the first bin is: "<<meta.firstYbinLoEdge<<"\n"
<<" and the high edge of the last bin is: "<<meta.finalYbinHiEdge<<std::endl;
perBin = (meta.finalYbinHiEdge - meta.firstYbinLoEdge)/static_cast<double>(meta.numYbins);
meta.startYbin = Detail::getAxisLoBound("Y", meta.numYbins, meta.firstYbinLoEdge, perBin);
meta.stopYbin = Detail::getAxisHiBound("Y", meta.numYbins, meta.finalYbinHiEdge, perBin);
}
void get1dAxisBounds(OneDMetaData& meta)
{
std::cout<<"\n\nThe X-axis of the spectrum has "<<meta.numBins<<" bins and\n";
std::cout<<" the low edge of the first bin is: "<<meta.firstBinLoEdge<<"\n"
<<" and the high edge of the last bin is: "<<meta.finalBinHiEdge<<std::endl;
double perBin = (meta.finalBinHiEdge - meta.firstBinLoEdge)/static_cast<double>(meta.numBins);
meta.startBin = Detail::getAxisLoBound("X", meta.numBins, meta.firstBinLoEdge, perBin);
meta.stopBin = Detail::getAxisHiBound("X", meta.numBins, meta.finalBinHiEdge, perBin);
}
namespace Detail
{
int getAxisLoBound(const std::string& axis, int numBins, double loEdge, double perBin)
{
bool goodValue = false;
int loBin = -1;
char ans = 't';
do
{
std::cout<<"Please give the first bin number of the "<<axis<<"-axis to use. [0,"<<numBins<<")"<<std::endl;
std::cin>>loBin;
if((loBin < 0) || (loBin >= numBins))
{
std::cout<<"Error - The value must be an integer in the range [0,"<<numBins<<")"<<std::endl;
continue;
}
std::cout<<"This sets the first used bin of the "<<axis<<"-axis to have:\n Low Edge: "
<<(loEdge + (loBin*perBin))<<"\n Center: "<<(loEdge + (perBin/2.0) + (loBin*perBin))<<std::endl;
std::cout<<"Is this satisfactory (Y/N)?"<<std::endl;
std::cin>>ans;
if((ans == 'Y') || (ans =='y'))
{
goodValue = true;
}
}
while(!goodValue);
return loBin;
}
int getAxisHiBound(const std::string& axis, int numBins, double hiEdge, double perBin)
{
bool goodValue = false;
int hiBin = -1;
char ans = 't';
do
{
std::cout<<"Please give the last bin number of the "<<axis<<"-axis to use. [0,"<<numBins<<")"<<std::endl;
std::cin>>hiBin;
if((hiBin < 0) || (hiBin >= numBins))
{
std::cout<<"Error - The value must be an integer in the range [0,"<<numBins<<")"<<std::endl;
continue;
}
std::cout<<"This sets the last used bin of the "<<axis<<"-axis to have:\n High Edge: "
<<(hiEdge - ((numBins - 1 - hiBin)*perBin))<<"\n Center: "<<(hiEdge - (perBin/2.0) - ((numBins - 1 - hiBin)*perBin))<<std::endl;
std::cout<<"Is this satisfactory (Y/N)?"<<std::endl;
std::cin>>ans;
if((ans == 'Y') || (ans =='y'))
{
goodValue = true;
}
}
while(!goodValue);
return hiBin;
}
}
| true |
59272524e0233e674917bb1ad05c484b46c2c099 | C++ | Humblefool14/UVa-solutions | /Easy/11805 Bafana Bafana.cpp | UTF-8 | 342 | 2.65625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int t;
cin >> t;
int cases =0;
while(t--){
cases++;
int N,K,P;
cin >> N >> K >> P;
int res = (K+P)%N;
if(res ==0) cout << "Case " << cases << ": " << N << endl;
else cout << "Case " << cases << ": " << res << endl;
}
return 0;
}
| true |
4f92e302b549921eb772a5889d635e7e6e049f50 | C++ | yss120612/water | /src/Rtc.cpp | UTF-8 | 2,902 | 2.578125 | 3 | [] | no_license |
#include "Rtc.h"
#include "Config.h"
#include "Log.h"
Rtc1302::Rtc1302(){
_short_interval=120000;
last_update=0;
upd_success=false;
}
Rtc1302::~Rtc1302(){
if (_rtc!=NULL) delete(_rtc);
if (_tw!=NULL) delete(_tw);
if (timeClient!=NULL) delete(timeClient);
if (ntpUDP!=NULL) delete(ntpUDP);
}
///qwq e
bool Rtc1302::settime(uint8_t offset){
return true;
}
void Rtc1302::setup(int interval){
_tw=new ThreeWire(DS1302_DAT,DS1302_CLK,DS1302_RST);// IO, SCLK, CE
//ThreeWire myWire(DS1302_DAT,DS1302_CLK,DS1302_RST);
_rtc= new RtcDS1302<ThreeWire>(*_tw);
_interval=interval;
ntpUDP=new WiFiUDP();
timeClient = new NTPClient(*ntpUDP ,ntp_server , 3600*TIME_OFFSET, _interval);
timeClient->begin();
//RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
timeClient->begin();
_rtc->Begin();
_rtc->SetIsRunning(true);
_rtc->SetIsWriteProtected(false);
//logg.logging(toString(compiled));
}
void Rtc1302::loop(long ms)
{
if (!timeClient)
return;
if (upd_success)
{
if (ms - last_update > _interval)
{
upd_success = timeClient->forceUpdate();
if (upd_success)
{
setfrominet();
}else
{
logg.logging("Error update time on long period");
}
last_update=ms;
}
}
else
{
if (ms - last_update > _short_interval)
{
upd_success = timeClient->forceUpdate();
if (upd_success)
{
setfrominet();
}else
{
logg.logging("Error update time on short period");
}
last_update=ms;
}
}
}
void Rtc1302::setfrominet(){
RtcDateTime d;
d.InitWithEpoch64Time(timeClient->getEpochTime());
logg.logging("Success update " +toString(d));
_rtc->SetDateTime(d);
}
String Rtc1302::toString(const RtcDateTime& dt)
{
char datestring[20];
String s;
snprintf_P(datestring,
20,
PSTR("%02u/%02u/%04u %02u:%02u:%02u"),
dt.Day(),
dt.Month(),
dt.Year(),
dt.Hour(),
dt.Minute(),
dt.Second() );
return String(datestring);
}
bool Rtc1302::setMemory(uint8_t d,uint8_t addr){
_rtc->SetMemory(&d,addr);
}
uint8_t Rtc1302::getMemory(uint8_t addr){
_rtc->GetMemory(addr);
}
String Rtc1302::test(){
String res=timestring();
return res;
}
String Rtc1302::timestring()
{
if (_rtc->IsDateTimeValid())
return toString(_rtc->GetDateTime());
else
return "Incorrect DateTime";
}
bool Rtc1302::check_time(uint8_t d, uint8_t h)
{
if (_rtc->IsDateTimeValid()){
RtcDateTime dt=_rtc->GetDateTime();
return (d==dt.Day() && h==dt.Hour());
}
else
return false;
}
| true |
7b3ceadc4dcce771760d17a9a309a0a2a289f473 | C++ | apple/swift | /include/swift/Basic/Program.h | UTF-8 | 2,836 | 2.515625 | 3 | [
"Apache-2.0",
"Swift-exception"
] | permissive | //===--- Program.h ----------------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_BASIC_PROGRAM_H
#define SWIFT_BASIC_PROGRAM_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/Program.h"
namespace swift {
/// This function executes the program using the arguments provided,
/// preferring to reexecute the current process, if supported.
///
/// \param Program Path of the program to be executed
/// \param args A vector of strings that are passed to the program. The first
/// element should be the name of the program. The list *must* be terminated by
/// a null char * entry.
/// \param env An optional vector of strings to use for the program's
/// environment. If not provided, the current program's environment will be
/// used.
///
/// \returns Typically, this function will not return, as the current process
/// will no longer exist, or it will call exit() if the program was successfully
/// executed. In the event of an error, this function will return a negative
/// value indicating a failure to execute.
int ExecuteInPlace(const char *Program, const char **args,
const char **env = nullptr);
struct ChildProcessInfo {
llvm::sys::procid_t Pid;
int WriteFileDescriptor;
int ReadFileDescriptor;
ChildProcessInfo(llvm::sys::procid_t Pid, int WriteFileDescriptor,
int ReadFileDescriptor)
: Pid(Pid), WriteFileDescriptor(WriteFileDescriptor),
ReadFileDescriptor(ReadFileDescriptor) {}
};
/// This function executes the program using the argument provided.
/// Establish pipes between the current process and the spawned process.
/// Returned a \c ChildProcessInfo where WriteFileDescriptor is piped to
/// child's STDIN, and ReadFileDescriptor is piped from child's STDOUT.
///
/// \param program Path of the program to be executed
/// \param args An array of strings that are passed to the program. The first
/// element should be the name of the program.
/// \param env An optional array of 'key=value 'strings to use for the program's
/// environment.
llvm::ErrorOr<swift::ChildProcessInfo> ExecuteWithPipe(
llvm::StringRef program, llvm::ArrayRef<llvm::StringRef> args,
llvm::Optional<llvm::ArrayRef<llvm::StringRef>> env = llvm::None);
} // end namespace swift
#endif // SWIFT_BASIC_PROGRAM_H
| true |
36984e807741348771be41abae1dd56a05cbdb91 | C++ | pingpan2013/coding-exercises | /Sort and Search/find_kth_smallest_element_in_two_sorted_arrays.cc | UTF-8 | 1,949 | 3.546875 | 4 | [] | no_license | /*
* =====================================================================================
*
* Filename: find_kth_smallest_element_in_two_sorted_arrays.cc
*
* Description: find kth smallest element in two sorted arrays
*
* Created: 01/17/2015 16:31:24
* Compiler: g++ 4.7.0
*
* =====================================================================================
*/
#include <iostream>
#include <cassert>
using namespace std;
class Solution {
public:
// http://blog.csdn.net/zxzxy1988/article/details/8587244
// Transfer this problem to the problem that asks for the kth smallest element in two sorted arrays
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int len = m + n;
// odd
if(len & 0x1){
return findKthSmallest(A, m, B, n, len/2+1);
}
else{
int a = findKthSmallest(A, m, B, n, len/2);
int b = findKthSmallest(A, m, B, n, len/2 + 1);
return (double)(a+b)/2;
}
}
private:
int findKthSmallest(int a[], int m, int b[], int n, int k){
assert(m >= 0 && n >= 0 && k <= m+n && "wrong parameter");
// assume a[] is the array with less elements
if(m > n) return findKthSmallest(b, n, a, m, k);
if(m == 0) return b[k-1];
if(k == 1) return min(a[0], b[0]);
int pa = min(m, k/2);
int pb = k - pa;
if(a[pa - 1] == b[pb - 1]){
return a[pa - 1];
}
if(a[pa - 1] < b[pb - 1]){
return findKthSmallest(a+pa, m-pa, b, n, k-pa);
}
else if(a[pa - 1] > b[pb - 1]){
return findKthSmallest(a, m, b+pb, n-pb, k-pb);
}
return -1;
}
};
int main(){
int a[] = {};
int b[] = {2, 3};
Solution sln;
cout << sln.findMedianSortedArrays(a, 0, b, 2) << endl;
return 0;
}
| true |
9184a097e04273df0b8ed2df5ebb9b127dabb70c | C++ | jjully/baekjoon | /21608.cpp | UTF-8 | 7,490 | 3.015625 | 3 | [] | no_license | //baekjoon 21608
//shark elementary school
//simulation
//condition1
//condition2
//condition3
#include<iostream>
#include<vector>
int N=0;
std::vector<std::vector<int> > Student; //v students like
std::vector<std::vector<int> > Map; //seat
std::vector<int> SeatOrder;
int drow[] = {1, 0, -1, 0};
int dcol[] = {0, -1, 0, 1};
template <typename T>
void v2DInit(std::vector<std::vector<T> >& v, int row, int col, T val);
void Input();
void Solution();
void DecideSeat();
int CntSatisfaction();
int CntEmptyNear(int row, int col);
int CntLikeNear(std::vector<int>& hero, int row, int col);
bool Condition1(std::vector<std::pair<int, int> >& SeatCandidate, int& hero);
bool Condition2(std::vector<std::pair<int, int> >& SeatCandidate, int& hero);
void Condition3(std::vector<std::pair<int, int> >& SeatCandidate, int& hero);
template <typename T>
void v2DInit(std::vector<std::vector<T> >& v, int row, int col, T val) {
v.clear();
std::vector<std::vector<T> >().swap(v);
v.resize(row);
for(int i=0; i<row; i++) {
v[i].resize(col, val);
}
}
int CntEmptyNear(int row, int col) {
int cnt=0;
for(int i=0; i<4; i++) {
int newRow = row+drow[i];
int newCol = col+dcol[i];
if( newRow<0 || newRow>=N || newCol<0 || newCol>=N ) continue;
else {
if(Map[newRow][newCol] == 0) cnt++;
}
}
return cnt;
}
int CntLikeNear(std::vector<int>& hero, int row, int col) {
int cnt=0;
for(int i=0; i<4; i++) {
int newRow = row+drow[i];
int newCol = col+dcol[i];
if( newRow<0 || newRow>=N || newCol<0 || newCol>=N ) continue;
else if ( Map[newRow][newCol] == hero[0] || Map[newRow][newCol] == hero[1]
|| Map[newRow][newCol] == hero[2] || Map[newRow][newCol] == hero[3] ) { cnt++; }
}
return cnt;
}
bool Condition1(std::vector<std::pair<int, int> >& SeatCandidate, int& hero) {
std::vector<std::vector< std::pair<int, int> > >LikeNear(5); //LikeNear[x] : seats which has x LikeNear
int max=0;
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
if(Map[i][j] != 0) continue;
int LikeSeatCnt = CntLikeNear(Student[hero], i, j);
if(max < LikeSeatCnt) max=LikeSeatCnt;
LikeNear[LikeSeatCnt].push_back({i, j});
}
}
if( LikeNear[max].size() == 1 ) {
int row=LikeNear[max][0].first;
int col=LikeNear[max][0].second;
Map[row][col] = hero;
return true; //only 1 candidate -> completely take a seat
}
else {
SeatCandidate.assign( LikeNear[max].begin(), LikeNear[max].end() ); //fail to take a seat
return false; //forward SeatCandidate and return false
}
}
bool Condition2(std::vector<std::pair<int, int> >& SeatCandidate, int& hero) {
std::vector<std::vector< std::pair<int, int> > >EmptyNear(5); //EmptyNear[x] : seats which has x emptynear
int max=0;
int SeatCandidateSize = SeatCandidate.size();
for(int i=0; i<SeatCandidateSize; i++) {
int SeatRow = SeatCandidate[i].first;
int SeatCol = SeatCandidate[i].second;
int EmptySeatCnt = CntEmptyNear(SeatRow, SeatCol);
if(max < EmptySeatCnt) max=EmptySeatCnt;
EmptyNear[EmptySeatCnt].push_back({SeatRow, SeatCol});
}
if( EmptyNear[max].size() == 1 ) {
int row=EmptyNear[max][0].first;
int col=EmptyNear[max][0].second;
Map[row][col] = hero;
return true; //only 1 candidate -> completely take a seat
}
else {
SeatCandidate.assign( EmptyNear[max].begin(), EmptyNear[max].end() ); //fail to take a seat
return false; //forward SeatCandidate and return false
}
}
void Condition3(std::vector<std::pair<int, int> >& SeatCandidate, int& hero) {
int SeatCandidateSize = SeatCandidate.size();
int rowMin=(N-1);
//row condition;
std::vector<std::vector<int> > rowV(N); //rowV[x][idx] : idx is seatcandidate idx, and x is row no.
for(int i=0; i<SeatCandidateSize; i++) {
int CandidateRow = SeatCandidate[i].first;
if(CandidateRow <= rowMin) {
rowMin = CandidateRow;
rowV[rowMin].push_back(i);
}
}
if(rowV[rowMin].size() == 1) {
int idx = rowV[rowMin][0];
int realRow = SeatCandidate[idx].first;
int realCol = SeatCandidate[idx].second;
Map[realRow][realCol] = hero;
return;
}
//col condition;
std::vector<std::vector<int> > colV(N); //colV[x][idx] : idx is seatcandidate idx, and x is row no.
int rowVSize = rowV[rowMin].size();
int colMin = (N-1);
int colIdx=0;
for(int i=0; i<rowVSize; i++) {
int candidateIdx = rowV[rowMin][i];
int candidateCol = SeatCandidate[candidateIdx].second;
if(candidateCol <= colMin) {
colIdx = candidateIdx;
}
}
int finalRow = SeatCandidate[colIdx].first;
int finalCol = SeatCandidate[colIdx].second;
Map[finalRow][finalCol] = hero;
}
//std::vector<std::vector<int> > Student; //v students like
int CntSatisfaction() {
int cnt=0;
int satisfaction=0;
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) { //for all points
//////
cnt=0;
int hero = Map[i][j];
for(int k=0; k<4; k++) {
int newRow = i+drow[k];
int newCol = j+dcol[k];
if( newRow<0 || newRow>=N || newCol<0 || newCol>=N ) continue;
else if( Map[newRow][newCol] == Student[hero][0] || Map[newRow][newCol] == Student[hero][1]
|| Map[newRow][newCol] == Student[hero][2] || Map[newRow][newCol] == Student[hero][3] ){
cnt++;
}
}
switch(cnt) {
case(1):
satisfaction+=1;
break;
case(2):
satisfaction+=10;
break;
case(3):
satisfaction+=100;
break;
case(4):
satisfaction+=1000;
break;
default:
break;
}
//////
}
}
return satisfaction;
}
void DecideSeat() {
std::vector<std::pair<int, int> > SeatCandidate;
for(int i=0; i<N*N; i++) { //for all students
SeatCandidate.clear();
std::vector<std::pair<int, int> >().swap(SeatCandidate); //reset candidate
if ( Condition1( SeatCandidate, SeatOrder[i] ) == true ) continue;
else if( Condition2( SeatCandidate, SeatOrder[i] ) == true ) continue;
else Condition3( SeatCandidate, SeatOrder[i] );
}
}
////////////////////////////////////////
int main() {
Input();
Solution();
/*
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
std::cout << Map[i][j] << ' ';
}
std::cout << std::endl;
}
*/
return 0;
}
void Input() {
std::cin >> N;
v2DInit(Student, N*N+1, 4, 0);
for(int i=0; i<N*N; i++) {
int tmp=0;
std::cin >> tmp;
SeatOrder.push_back(tmp);
for(int j=0; j<4; j++) {
std::cin >> Student[tmp][j]; //Student[tmp] like student[tmp][0], [1], ...
}
}
}
void Solution() {
v2DInit(Map, N, N, 0); //0 == EMPTY
DecideSeat();
std::cout << CntSatisfaction();
}
| true |
427134d23ea8a7cbfb97839e399f4aaccda1665c | C++ | antonyarce/MIPSnetic | /src/main.cpp | UTF-8 | 4,014 | 2.75 | 3 | [] | no_license | /*
* File: main.cpp
* Author: cristhian
*
* Created on May 21, 2016, 7:12 PM
*/
#include <cstdlib>
#include "decodificar.h"
#include "interprete.h"
#include <ctime>
using namespace std;
/*
*Función principal para la ejecución del programa.
*/
int main(int argc, char** argv) {
cout << "Iniciando Programa..." << endl;
Interprete inter;
ifstream tet("/home/cristhian/MARSMips/MCB");
ifstream tet2("/home/cristhian/MARSMips/MCM");
ifstream tet3("/home/cristhian/MARSMips/MCA");
ifstream tet4("/home/cristhian/MARSMips/MCP");
ifstream tet5("/home/cristhian/MARSMips/MCX");
ifstream tet6("/home/cristhian/MARSMips/MCMD");
ifstream data("/home/cristhian/MARSMips/code2");
int lineas1 = inter.contarLineas(tet);
int lineas2 = inter.contarLineas(tet2);
int lineas3 = inter.contarLineas(tet3);
int lineas4 = inter.contarLineas(tet4);
int lineas5 = inter.contarLineas(tet5);
int lineas6 = inter.contarLineas(tet6);
int metodo;
cout << "¡Bienvenido seleccione un metodo de generacion de numeros aleatorios!" << endl;
cout << endl;
cout << "1 - Metodo Congruecial Binario." << endl;
cout << "2 - Metodo Congruencial Mixto." << endl;
cout << "3 - Metodo Congruencial Aditivo." << endl;
cout << "4 - Metodo Congruencial Polinomial." << endl;
cout << "5 - Metodo Congruencial Multiplicativo." << endl;
cout << "6 - Metodo Cuadrados Medios." << endl;
cout << endl;
cout << "Presione (0) para finalizar el programa." << endl;
cout << endl;
cout << "Metodo: ";
cin >> metodo;
int regs[34] = {0,0,0,0,0,0,0,0,time(0),0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,pow(10,9),0,0,0,0,0,0,0,0,0};
int* ptrRegs = regs;
int* hi = ptrRegs + 32;
int* lo = ptrRegs + 33;
int* ptrRanNum;
int memoria = 1000;
void* ptrHead = malloc(memoria);
string R = "";
string* ptrStack = &R;
while(metodo != 0){
if(metodo == 1){
ifstream text("/home/cristhian/MARSMips/MCB");
inter.interprete(ptrHead,memoria,ptrStack,ptrRegs,text,data,ptrRanNum,lineas1,metodo);
}
if(metodo == 2){
ifstream text("/home/cristhian/MARSMips/MCM");
int regs1[34] = {0,0,0,0,0,0,0,0,time(0),pow(7,5),0,pow(2,31) - 1,0,0,0,0,0,0,0,0,0,0,0,0,pow(10,9),0,0,0,0,0,0,0,0,0};
int* ptrRegs = regs1;
inter.interprete(ptrHead,memoria,ptrStack,ptrRegs,text,data,ptrRanNum,lineas2,metodo);
}
if(metodo == 3){
ifstream text("/home/cristhian/MARSMips/MCA");
int regs2[34] = {0,0,0,0,0,0,0,0,time(0),0,time(0) + 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int* ptrRegs = regs2;
inter.interprete(ptrHead,memoria,ptrStack,ptrRegs,text,data,ptrRanNum,lineas3,metodo);
}
if(metodo == 4){
ifstream text("/home/cristhian/MARSMips/MCP");
int regs3[34] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int* ptrRegs = regs3;
inter.interprete(ptrHead,memoria,ptrStack,ptrRegs,text,data,ptrRanNum,lineas4,metodo);
}
if(metodo == 5){
ifstream text("/home/cristhian/MARSMips/MCX");
int regs4[34] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int* ptrRegs = regs4;
inter.interprete(ptrHead,memoria,ptrStack,ptrRegs,text,data,ptrRanNum,lineas5,metodo);
}
if(metodo == 6){
ifstream text("/home/cristhian/MARSMips/MCMD");
int regs5[34] = {0,0,0,0,0,0,0,0,44544,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int* ptrRegs = regs5;
inter.interprete(ptrHead,memoria,ptrStack,ptrRegs,text,data,ptrRanNum,lineas6,metodo);
}
cout << endl;
cout << "Metodo: ";
cin >> metodo;
}
cout << "¡Fin del programa!" << endl;
return 0;
}
| true |
cbb2648f2094cc4fa0a23e30bc917c3c9276f17c | C++ | uhdang/leetcode | /1528_20210619_EASY_CPP_Shuffle_String/main.cpp | UTF-8 | 594 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include "Solution.h"
#include "Solution_two.h"
int main() {
Solution solution;
Solution_two solution_two;
std::string s = "codeleet";
int indices_array[] = {4,5,6,7,0,2,1,3};
std::vector<int> indices_v (indices_array, indices_array + sizeof(indices_array) / sizeof(indices_array[0]) );
std::string output = solution.restoreString(s, indices_v);
std::cout << output << std::endl;
std::string output_2 = solution_two.restoreString(s, indices_v);
std::cout << output_2 << std::endl;
return 1;
} | true |
c168552e047d092b0c31c74c7d4742fdc36cce2d | C++ | Billolha/TestOffFileReader | /TestOffFileReader/headers/classetriangleisocele.hh | UTF-8 | 1,947 | 2.78125 | 3 | [] | no_license |
/*! \file classetriangleisocele.hh
*
* \author Paul BERNARD <paul.bernard@eisti.fr>
*
* \version 0.1
* Creation du fichier classetriangleisocele.hh
* \brief classe de triangle isocele
*/
#ifndef __CLASSETRIANGLEISOCELE_HH_
#define __CLASSETRIANGLEISOCELE_HH_
#include "include.hh"
#include "classetriangle.hh"
/*! \class TriangleIsocele
* \author Paul BERNARD
* \version 0.1
* \brief classe triangleIsocele
*
*/
class TriangleIsocele : public Triangle {
public:
/*!
* \fn TriangleIsocele (void)
* \author Paul BERNARD <paul.bernard@eisti.fr>
* \version 0.1
* \brief Constructeur de la class triangleIsocele
*/
TriangleIsocele(void);
/*!
* \fn ~TriangleIsocele (void)
* \author Paul BERNARD <paul.bernard@eisti.fr>
* \version 0.1
* \brief Destructeur de la class triangleIsocele
*/
~TriangleIsocele(void);
/*! \fn TriangleIsocele(const TriangleIsocele &tri_iso)
* \author Paul BERNARD <paul.bernard@eisti.fr>
* \version 0.1
* Creation de la fonction
*
* \param &tri_iso : un triangleIsocele
*
* \brief constructeur par copie d'un triangleIsocele
*
*
*/
TriangleIsocele(const TriangleIsocele &triangleIsocele);
/*! \fn TriangleIsocele& operator=(const TriangleIsocele &tri_iso)
* \author Paul BERNARD <paul.bernard@eisti.fr>
* \version 0.1
* Creation de la fonction
*
* \param &tri_iso : un triangleIsocele
*
* \return la copie du triangleIsocele
*
* \brief permet d'effectuer une copie par affectation
*
*
*/
TriangleIsocele& operator=(const TriangleIsocele &tri_iso);
/*! \fn TriangleIsocele(bool &etat)
* \author Paul BERNARD <paul.bernard@eisti.fr>
* \version 0.1
* Creation de la fonction
*
* \param &etat : etat du triangle (true si isocele sinon false)
*
* \brief constructeur d'un triangleIsocele
*
*
*/
TriangleIsocele(bool &etat);
};
#endif
| true |
3ccbf0097456f9a35266ff0b368592ff31c99325 | C++ | hbakhshandeh/iso8583_cipher | /cipher/inc/pinblock.h | UTF-8 | 1,195 | 2.578125 | 3 | [] | no_license | #ifndef PINBLOCK_H_
#define PINBLOCK_H_
#include "iso_8583.h"
#include "hex.h"
#include "ascii.h"
#include "crypto.h"
#include "exclusive_or.h"
#include <string_view>
#include <variant>
#include <optional>
namespace ISO8583 {
class pinblock {
protected:
tools::hex hex;
tools::ascii ascii;
tools::crypto cryp;
tools::exclusive_or x_or;
std::string wkey = { "1C1C1C1C1C1C1C1C" };
std::string tkey = { "1A1A1A1A1A1A1A1A" };
std::string calculate(std::string_view pan, std::string_view user_key,
std::string_view local_key);
std::string get_user_key(std::string_view pan, std::string_view pin_block);
public:
pinblock() = default;
explicit pinblock(const std::string &working_key,
const std::string &translate_key);
virtual ~pinblock();
pinblock(const pinblock&) = default;
pinblock& operator=(const pinblock&) = default;
pinblock(pinblock&&) noexcept = default;
pinblock& operator=(pinblock&&) noexcept = default;
virtual std::optional<std::string> translate(
std::string_view pan, std::string_view pin_block) = 0;
virtual std::optional<std::string> generate(
std::string_view pan, std::string_view user_key) = 0;
};
} /* namespace ISO8583 */
#endif /* PINBLOCK_H_ */
| true |
b3886758f2b376d36195135f970e8eb303201c6a | C++ | patelsneh18/GeeksForGeeks-DSA-Workshop | /Week 1/Arrays/P09-subArrOfGivenSum.cpp | UTF-8 | 839 | 3.421875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
vector<int> subarraySum(int arr[], int n, int s){
vector<int> ans;
for(int i=0;i<n;i++){
int sum=0;
for(int j=i;j<n;j++){
sum+=arr[j];
if(sum==s){
ans.push_back(i+1);
ans.push_back(j+1);
return ans;
}
if(sum>s) break;
}
}
ans.push_back(-1);
return ans;
}
int main()
{
int n;
cout<<"Enter Size of Array"<<endl;
cin>>n;
cout<<"Enter Sum to Find"<<endl;
int sum;
cin>>sum;
cout<<"Enter elements of Array"<<endl;
int arr[n];
for (int i = 0; i < n; i++) cin>>arr[i];
vector<int> ans = subarraySum(arr,n,sum);
for (int i = 0; i < ans.size(); i++) cout<<ans[i]<<" ";
cout<<endl;
return 0;
} | true |
8a18dd8a63787c22d573d004e952067eab86ee90 | C++ | stellarfloat/2021-1_cpp_SnakeGame | /snakegame/GameManager.cpp | UTF-8 | 8,242 | 2.859375 | 3 | [] | no_license | // @author 추헌준(20203155)
#include <chrono>
#include <thread>
#include <string>
#include <ncurses.h>
#include "GameManager.hpp"
#include "MapData.hpp"
#include "kbhit.hpp"
MapData *map;
ItemManager *item;
Snake *snake;
GateManager *gate;
int currentLevel = 0;
// gametick length (ms)
int GAMETICK_DELAY = 250;
void GameManager::load_level(int levelID) {
// initialize and load map data, assume cwd is 2021-1_cpp_SnakeGame/
map = new MapData();
map->load(levelMetaData[levelID].first);
// pass the pointer to enable direct access to the map data
item = new ItemManager(map);
snake = new Snake(map, levelMetaData[levelID].second.first, levelMetaData[levelID].second.second);
gate = new GateManager(map);
// load map data to GateManager
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (map->getData(i, j) == 1) {
gate->wallList.push_back(std::make_pair(i, j));
}
}
}
// save time for later use
time_started = time(NULL);
if (levelID > 4) { // game clear
running = false;
return;
}
}
GameManager::GameManager() {
// initialize curses routines
initscr();
// One-character-a-time. disable the buffering of typed characters
// by the TTY driver and get a character-at-a-time input
cbreak();
// Suppress the automatic echoing of typed characters
noecho();
// to capture special keystrokes
keypad(stdscr, TRUE);
// start ncurses color
start_color();
curs_set(0);
// initialize color pair
// init_pair(pair_id, foreground_color, background_color)
init_pair(COLOR_ID_EMPTY, COLOR_BLACK, COLOR_BLACK);
init_pair(COLOR_ID_WALL, COLOR_BLACK, COLOR_WHITE);
init_pair(COLOR_ID_IWALL, COLOR_BLACK, COLOR_WHITE);
init_pair(COLOR_ID_SNAKE_HEAD, COLOR_WHITE, COLOR_GREEN);
init_pair(COLOR_ID_SNAKE_BODY, COLOR_BLACK, COLOR_GREEN);
init_pair(COLOR_ID_ITEM_GROWTH, COLOR_WHITE, COLOR_YELLOW);
init_pair(COLOR_ID_ITEM_POISON, COLOR_WHITE, COLOR_RED);
init_pair(COLOR_ID_GATE, COLOR_WHITE, COLOR_MAGENTA);
this->load_level(currentLevel);
srand(time(NULL));
}
GameManager::~GameManager() {
delete snake;
delete item;
delete gate;
delete map;
endwin();
}
void GameManager::showStartScreen() {
this->load_level(0);
this->render_game();
mvaddstr(12, 27, "Snake Game");
mvaddstr(15, 15, "Press the key to choose difficulty");
mvaddstr(17, 28, "1. EASY");
mvaddstr(18, 28, "2. NORMAL");
mvaddstr(19, 28, "3. HARD");
choice:
int option = getch();
if (option == '1') { // EASY
GAMETICK_DELAY = 250;
return;
} else if (option == '2') { // NORMAL
GAMETICK_DELAY = 175;
return;
} else if (option == '3') { // HARD
GAMETICK_DELAY = 90;
return;
} else {
goto choice;
}
}
void GameManager::showResultScreen() {
clear();
this->load_level(0);
this->render_game();
if (currentLevel > 4) {
mvaddstr(12, 27, "GAME CLEAR");
mvaddstr(19, 21, "Press any key to exit");
} else {
std::string resultstr = "result: stage " + std::to_string(currentLevel);
mvaddstr(12, 27, "GAME OVER");
mvaddstr(15, 24, &resultstr[0]);
mvaddstr(19, 21, "Press any key to exit");
}
getch();
}
void GameManager::loadNextLevel() {
clear();
delete snake;
delete item;
delete gate;
delete map;
this->load_level(++currentLevel);
}
bool GameManager::atMissionSuccess() {
// // initial game start
// if (currentLevel == 0) {
// getch();
// return true;
// }
// levelMissionData
// {bodyLength, itemGrowth, itemPoison, gateUsed}
if (levelMissionData[currentLevel][0] <= snake->length()) {
if (levelMissionData[currentLevel][1] <= snake->getItemCountGrowth()) {
if (levelMissionData[currentLevel][2] <= snake->getItemCountPoison()) {
if (levelMissionData[currentLevel][3] <= snake->getGateCount()) {
return true;
}
}
}
}
return false;
}
void GameManager::update() {
if (snake->isDead()) { running = false; }
if (this->atMissionSuccess()) {
this->loadNextLevel();
}
std::this_thread::sleep_for(std::chrono::milliseconds(GAMETICK_DELAY));
if (kbhit()) { snake->setDir(); }
item->update(time(NULL));
gate->update(time(NULL), time_started, snake->length());
snake->update(*gate);
}
void GameManager::render_scoreboard() {
int offset_x = 2 * WIDTH;
mvaddstr(0, offset_x + 2, "---------------------");
mvaddstr(1, offset_x + 2, "|>>| Score Board |<<|");
std::string tempstr = " | B: " + std::to_string(snake->length());
mvaddstr(2, offset_x + 2, &tempstr[0]);
tempstr = " | +: " + std::to_string(snake->getItemCountGrowth());
mvaddstr(3, offset_x + 2, &tempstr[0]);
tempstr = " | -: " + std::to_string(snake->getItemCountPoison());
mvaddstr(4, offset_x + 2, &tempstr[0]);
tempstr = " | G: " + std::to_string(snake->getGateCount());
mvaddstr(5, offset_x + 2, &tempstr[0]);
for (int i = 2; i <= 5; i++) mvaddch(i, offset_x + 19, '|');
mvaddstr(6, offset_x + 2, "---------------------");
mvaddstr(7, offset_x + 2, "|>>| Mission |<<|");
tempstr = " | B: " + std::to_string(levelMissionData[currentLevel][0]);
mvaddstr(8, offset_x + 2, &tempstr[0]);
tempstr = levelMissionData[currentLevel][0] <= snake->length() ? "(v)" : "( )";
mvaddstr(8, offset_x + 15, &tempstr[0]);
tempstr = " | +: " + std::to_string(levelMissionData[currentLevel][1]);
mvaddstr(9, offset_x + 2, &tempstr[0]);
tempstr = levelMissionData[currentLevel][1] <= snake->getItemCountGrowth() ? "(v)" : "( )";
mvaddstr(9, offset_x + 15, &tempstr[0]);
tempstr = " | -: " + std::to_string(levelMissionData[currentLevel][2]);
mvaddstr(10, offset_x + 2, &tempstr[0]);
tempstr = levelMissionData[currentLevel][2] <= snake->getItemCountPoison() ? "(v)" : "( )";
mvaddstr(10, offset_x + 15, &tempstr[0]);
tempstr = " | G: " + std::to_string(levelMissionData[currentLevel][3]);
mvaddstr(11, offset_x + 2, &tempstr[0]);
tempstr = levelMissionData[currentLevel][3] <= snake->getGateCount() ? "(v)" : "( )";
mvaddstr(11, offset_x + 15, &tempstr[0]);
for (int i = 7; i <= 11; i++) mvaddch(i, offset_x + 19, '|');
mvaddstr(12, offset_x + 2, "---------------------");
}
void GameManager::render_game() {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
switch (map->getData(i, j)) {
case 0:
attron(COLOR_PAIR(COLOR_ID_EMPTY));
mvaddstr(i, 2 * j, " "); // empty space
attroff(COLOR_PAIR(COLOR_ID_EMPTY));
break;
case 1:
attron(COLOR_PAIR(COLOR_ID_WALL));
mvaddstr(i, 2 * j, " "); // wall
attroff(COLOR_PAIR(COLOR_ID_WALL));
break;
case 2:
attron(COLOR_PAIR(COLOR_ID_IWALL));
mvaddstr(i, 2 * j, "||"); // immune wall
attroff(COLOR_PAIR(COLOR_ID_IWALL));
break;
case 3:
attron(COLOR_PAIR(COLOR_ID_SNAKE_HEAD));
mvaddstr(i, 2 * j, "><"); // snake head
attroff(COLOR_PAIR(COLOR_ID_SNAKE_HEAD));
break;
case 4:
attron(COLOR_PAIR(COLOR_ID_SNAKE_BODY));
mvaddstr(i, 2 * j, " "); // snake body
attroff(COLOR_PAIR(COLOR_ID_SNAKE_BODY));
break;
case 5:
attron(COLOR_PAIR(COLOR_ID_ITEM_GROWTH));
mvaddstr(i, 2 * j, "++"); // growth item
attroff(COLOR_PAIR(COLOR_ID_ITEM_GROWTH));
break;
case 6:
attron(COLOR_PAIR(COLOR_ID_ITEM_POISON));
mvaddstr(i, 2 * j, "--"); // poison item
attroff(COLOR_PAIR(COLOR_ID_ITEM_POISON));
break;
case 7:
attron(COLOR_PAIR(COLOR_ID_GATE));
mvaddstr(i, 2 * j, " "); // gate
attroff(COLOR_PAIR(COLOR_ID_GATE));
break;
default:
mvaddstr(i, 2 * j, "??"); // display error
break;
}
}
}
}
void GameManager::render() {
//clear();
this->render_game();
this->render_scoreboard();
refresh();
}
bool GameManager::isRunning() {
return running;
} | true |
47f6fb598b54ac2cd4cdf0d93a0b9f59e8013e97 | C++ | StathisTsirigotis/battleship_simulation | /src/peiratiko.cpp | UTF-8 | 1,089 | 2.75 | 3 | [] | no_license | #include "peiratiko.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int Peiratiko::counter_peir_ships_created=0;
int Peiratiko::counter_peir_ships_died=0;
Peiratiko::Peiratiko(Naumaxia *n) : Ship(n, 1, 10)
{
total_attacks = 0;
dinami = rand()%PEIR_MAX_DINAMI + 1; //Elaxisto 1
counter_peir_ships_created++;
}
Peiratiko::~Peiratiko()
{
counter_peir_ships_died++;
}
void Peiratiko::leitourgia()
{
std::vector<Ship*> geitones;
geitones.reserve(8);
Ship* exthros;
geitones = n->getNeighbours(this->row, this->col);
if(geitones.size()>0)
{
int i = rand()%geitones.size();
exthros = geitones[i];
exthros->dec_antoxi(dinami);
total_attacks += dinami;
//auksisi thisaurou
int thisauros_inc = exthros->get_apo8ema()*(float)(PEIR_POSOSTO_THISAUROU)/100.0;
exthros->dec_apo8ema(thisauros_inc);
inc_apo8ema(thisauros_inc);
}
}
int Peiratiko::get_dinami()
{
return dinami;
}
void Peiratiko::set_dinami(int n)
{
dinami = n;
}
void Peiratiko::info(std::ostream& os) const
{
Ship::info(os);
os << "Attacks : " << total_attacks;
}
| true |
ee7a1ead848aae6378fe1a2990e735b0e224f87d | C++ | ExecDevOps/V3DLib | /Lib/Target/Pretty.cpp | UTF-8 | 3,957 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "Pretty.h"
#include "Support/basics.h"
#include "Target/Syntax.h"
#include "Target/SmallLiteral.h"
namespace V3DLib {
namespace {
std::string pretty(Imm imm) {
std::string ret;
switch (imm.tag) {
case IMM_INT32:
ret << imm.intVal;
break;
case IMM_FLOAT32:
ret << imm.floatVal;
break;
case IMM_MASK: {
int b = imm.intVal;
for (int i = 0; i < 16; i++) {
ret << ((b & 1)? 1 : 0);
b >>= 1;
}
}
break;
default: assert(false); break;
}
return ret;
}
std::string pretty(SmallImm imm) {
switch (imm.tag) {
case SMALL_IMM: return printSmallLit(imm.val);
case ROT_ACC: return "ROT(ACC5)";
case ROT_IMM: {
std::string ret;
ret << "ROT(" << imm.val << ")";
return ret;
}
default: assert(false); return "";
}
}
std::string pretty(RegOrImm r) {
switch (r.tag) {
case REG: return r.reg.pretty();
case IMM: return pretty(r.smallImm);
default: assert(false); return "";
}
}
} // anon namespace
/**
* Pretty printer for Target instructions
*
* Returns a string representation of an instruction.
*/
std::string pretty_instr(Instr const &instr) {
std::string buf;
switch (instr.tag) {
case LI: {
buf << instr.LI.cond.to_string()
<< "LI " << instr.LI.dest.pretty()
<< " <-" << instr.setCond().pretty() << " "
<< pretty(instr.LI.imm);
}
break;
case ALU: {
buf << instr.ALU.cond.to_string()
<< instr.ALU.dest.pretty()
<< " <-" << instr.setCond().pretty() << " "
<< instr.ALU.op.pretty();
if (instr.ALU.op.noOperands()) {
buf << "()";
} else {
buf << "(" << pretty(instr.ALU.srcA) << ", " << pretty(instr.ALU.srcB) << ")";
}
}
break;
case BR: {
buf << "if " << instr.BR.cond.to_string() << " goto " << instr.BR.target.to_string();
}
break;
case BRL: {
buf << "if " << instr.BRL.cond.to_string() << " goto L" << instr.BRL.label;
}
break;
case LAB:
buf << "L" << instr.label();
break;
case PRS:
buf << "PRS(\"" << instr.PRS << "\")";
break;
case PRI:
buf << "PRI(" << instr.PRI.pretty() << ")";
break;
case PRF:
buf << "PRF(" << instr.PRF.pretty() << ")";
break;
case RECV:
buf << "RECV(" << instr.RECV.dest.pretty() << ")";
break;
case SINC:
buf << "SINC " << instr.semaId;
break;;
case SDEC:
buf << "SDEC " << instr.semaId;
break;
case INIT_BEGIN:
case INIT_END:
case END: // vc4
case TMU0_TO_ACC4:
case NO_OP:
case IRQ:
case VPM_STALL:
case TMUWT:
buf << V3DLib::pretty_instr_tag(instr.tag);
break;
default:
buf << "<<UNKNOWN: " << instr.tag << ">>";
break;
}
assert(!buf.empty());
return buf;
}
const char *pretty_instr_tag(InstrTag tag) {
switch(tag) {
case LI: return "LI";
case ALU: return "ALU";
case BR: return "BR";
case LAB: return "LAB";
case NO_OP: return "NOP";
case END: return "END";
case RECV: return "RECV";
case IRQ: return "IRQ";
case VPM_STALL: return "VPM_STALL";
case TMU0_TO_ACC4: return "TMU0_TO_ACC4";
case INIT_BEGIN: return "INIT_BEGIN";
case INIT_END: return "INIT_END";
case TMUWT: return "TMUWT";
case PRI: return "PRI";
default:
assert(false); // Add other tags here as required
return "<UNKNOWN>";
}
}
/**
* Pretty printer for Target instructions
*
* Returns a string representation of an instruction.
*/
std::string pretty(Instr const &instr, bool with_comments) {
std::string buf;
if (with_comments && !instr.header().empty()) {
buf << "\n# " << instr.header() << "\n";
}
buf << pretty_instr(instr);
if (with_comments && !instr.comment().empty()) {
buf << " # " << instr.comment();
}
buf << "\n";
return buf;
}
} // namespace V3DLib
| true |
323d49fb8aa5d742da19ab8c2b9ca257ff93b035 | C++ | FabLabValsamoggia/GustavoTheSpaceman | /Firmware/Examples/ButtonsWithMp3/Tasti_e_mp3/Tasti_e_mp3.ino | UTF-8 | 3,490 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "DFRobotDFPlayerMini.h"
#include "SoftwareSerial.h"
#define BTN1 2 // pin tasto 1
#define BTN2 3 // pin tasto 2
#define BTN3 4 // pin tasto 3
#define BTN4 5 // pin tasto 4
//= Variabili per i bottoni =================================================//
int bottone1 ;
int bottone2 ;
int bottone3 ;
int bottone4 ;
//= Variabili mp3 ==========================================/
DFRobotDFPlayerMini myDFPlayer;
SoftwareSerial mySoftwareSerial(11, 10);
unsigned int volume = 15;
void setup()
{
mySoftwareSerial.begin(9600);
Serial.begin(115200);
Serial.println();
Serial.println(F("DFRobot DFPlayer Mini Demo"));
Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
if (!myDFPlayer.begin(mySoftwareSerial)) { //Use softwareSerial to communicate with mp3.
Serial.println(F("Unable to begin:"));
Serial.println(F("1.Please recheck the connection!"));
Serial.println(F("2.Please insert the SD card!"));
while (true) {
delay(0); // Code to compatible with ESP8266 watch dog.
}
}
Serial.println(F("DFPlayer Mini online."));
// Setto il volume (valori da 0 a 30)
myDFPlayer.volume(volume);
// Riproduzione dei brani casuale
myDFPlayer.randomAll();
}
void loop()
{
if (myDFPlayer.available())
{
printDetail(myDFPlayer.readType(), myDFPlayer.read());
}
/* leggo il valore del tasto */
bottone1 = digitalRead(BTN1);
if (bottone1 == LOW)
{
// Alzo il volume
myDFPlayer.volumeUp();
}
/* leggo il valore del tasto */
bottone2 = digitalRead(BTN2);
if (bottone2 == LOW)
{
// Abbasso il volume
myDFPlayer.volumeDown();
}
/* leggo il valore del tasto */
bottone3 = digitalRead(BTN3);
if (bottone3 == LOW)
{
// Metto in pausa
myDFPlayer.pause();
}
/* leggo il valore del tasto */
bottone4 = digitalRead(BTN4);
if (bottone4 == LOW)
{
// Riprendo
myDFPlayer.start();
}
}
void printDetail(uint8_t type, int value){
switch (type) {
case TimeOut:
Serial.println(F("Time Out!"));
break;
case WrongStack:
Serial.println(F("Stack Wrong!"));
break;
case DFPlayerCardInserted:
Serial.println(F("Card Inserted!"));
break;
case DFPlayerCardRemoved:
Serial.println(F("Card Removed!"));
break;
case DFPlayerCardOnline:
Serial.println(F("Card Online!"));
break;
case DFPlayerPlayFinished:
Serial.print(F("Number:"));
Serial.print(value);
Serial.println(F(" Play Finished!"));
//myDFPlayer.next();
break;
case DFPlayerError:
Serial.print(F("DFPlayerError:"));
switch (value) {
case Busy:
Serial.println(F("Card not found"));
break;
case Sleeping:
Serial.println(F("Sleeping"));
break;
case SerialWrongStack:
Serial.println(F("Get Wrong Stack"));
break;
case CheckSumNotMatch:
Serial.println(F("Check Sum Not Match"));
break;
case FileIndexOut:
Serial.println(F("File Index Out of Bound"));
break;
case FileMismatch:
Serial.println(F("Cannot Find File"));
break;
case Advertise:
Serial.println(F("In Advertise"));
break;
default:
break;
}
break;
default:
break;
}
}
| true |
5b33abc696d32990b3e750009fb23d121ccf7f8e | C++ | PoignardAzur/Space-Invaders | /Moteur2D/Interfaces/BasicArcadeLevel.h | UTF-8 | 2,782 | 3.234375 | 3 | [] | no_license |
#ifndef BASIC_ARCADE_LEVEL_HEADER
#define BASIC_ARCADE_LEVEL_HEADER
#include "AbstractLevel.h"
#include "../Timer.h"
template<typename In>
class BasicArcadeLevel : public AbstractLevel<In>
{
public :
BasicArcadeLevel(unsigned int seed = epoch_to_now().count());
BasicArcadeLevel(std::seed_seq& seed);
virtual ~BasicArcadeLevel();
bool gameOver() const;
virtual bool isPlayerAlive() const = 0;
virtual void respawnPlayer() = 0;
virtual void playerKilled(bool isGameOver) = 0;
virtual void drawThisIn(AbstractDrawer& window, float dt) = 0;
virtual void updateThis(const In& inputData) = 0;
protected :
int score() const;
void setPoints(int p, bool rel = false);
int lives() const;
void setLives(int l, bool rel = false);
void setRespawnTime(float ticks);
void updateLivesAndTimer(float ticks);
void setGameOver();
private :
Timer m_timeBeforeRespawn;
int m_lives;
int m_score;
bool m_gameOver;
};
template<typename In>
void BasicArcadeLevel<In>::updateLivesAndTimer(float ticks)
{
if (!isPlayerAlive())
{
if (m_timeBeforeRespawn.getCurrentTime())
{
if (m_timeBeforeRespawn.decrement(ticks))
{
m_lives--;
respawnPlayer();
}
}
else if (m_lives)
{
m_timeBeforeRespawn.resetTimeToMax();
playerKilled(false);
}
else if (!gameOver())
{
setGameOver();
playerKilled(true);
}
}
}
template<typename In>
BasicArcadeLevel<In>::BasicArcadeLevel(unsigned int seed) : AbstractLevel<In>(seed), m_lives(0), m_score(0), m_gameOver(false)
{
}
template<typename In>
BasicArcadeLevel<In>::BasicArcadeLevel(std::seed_seq& seed) : AbstractLevel<In>(seed), m_lives(0), m_score(0), m_gameOver(false)
{
}
template<typename In>
BasicArcadeLevel<In>::~BasicArcadeLevel()
{
}
template<typename In>
int BasicArcadeLevel<In>::score() const
{
return m_score;
}
template<typename In>
void BasicArcadeLevel<In>::setPoints(int p, bool rel)
{
if (rel)
m_score += p;
else
m_score = p;
}
template<typename In>
int BasicArcadeLevel<In>::lives() const
{
return m_lives;
}
template<typename In>
void BasicArcadeLevel<In>::setLives(int l, bool rel)
{
if (rel)
m_lives += l;
else
m_lives = l;
}
template<typename In>
bool BasicArcadeLevel<In>::gameOver() const
{
return m_gameOver;
}
template<typename In>
void BasicArcadeLevel<In>::setRespawnTime(float ticks)
{
m_timeBeforeRespawn.setMaxTime(ticks);
}
template<typename In>
void BasicArcadeLevel<In>::setGameOver()
{
m_gameOver = true;
}
#endif // BASIC_ARCADE_LEVEL_HEADER
| true |
7a75af9a5678bc393f2b245faff0fe00f2e25a13 | C++ | keisuke-kanao/my-UVa-solutions | /Contest Volumes/Volume 103 (10300-10399)/UVa_10344_23_Out_of_5.cpp | UTF-8 | 2,072 | 3.21875 | 3 | [] | no_license |
/*
UVa 10344 - 23 Out of 5
To build using Visual Studio 2008:
cl -EHsc -O2 UVa_10344_23_Out_of_5.cpp
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int nr_variables = 5, nr_operators = 4;
bool calculate_expression(int nr_applied, char operators[], const int variables[])
{
if (nr_applied == nr_operators) {
int result = variables[0];
for (int i = 0; i < nr_operators; i++) {
int variable = variables[i + 1];
switch (operators[i]) {
case '+':
result += variable; break;
case '-':
result -= variable; break;
case '*':
result *= variable; break;
}
}
#ifdef DEBUG
if (result == 23) {
cout << "(((" << variables[0] << ' ' << operators[0] << ' ' << variables[1] << ")) " <<
operators[1] << ' ' << variables[2] << ")) " << operators[2] << ' ' << variables[3] << ")) " <<
operators[3] << ' ' << variables[4] << endl;
return true;
}
else
return false;
#else
return result == 23;
#endif
}
else {
const char ops[] = {'+', '-', '*'};
for (int i = 0; i < sizeof(ops) / sizeof(char); i++) {
operators[nr_applied] = ops[i];
if (calculate_expression(nr_applied + 1, operators, variables))
return true;
}
return false;
}
}
int main()
{
while (true) {
int variables[nr_variables];
cin >> variables[0] >> variables[1] >> variables[2] >> variables[3] >> variables[4];
if (!variables[0] && !variables[1] && !variables[2] && !variables[3] && !variables[4])
break;
sort(variables, variables + nr_variables);
bool possible = false;
do {
#ifdef DEBUG
for (int i = 0; i < nr_variables; i++)
cout << ' ' << variables[i];
cout << endl;
#endif
char operators[nr_operators];
// operators[i] is the i-th operator applied to the expression ('+' or '-' or '*')
if (possible = calculate_expression(0, operators, variables))
break;
} while (next_permutation(variables, variables + nr_variables));
cout << ((possible) ? "Possible\n" : "Impossible\n");
}
return 0;
}
| true |
e6ce612d67313ee14d1e3da8ffaffc213efb1dd4 | C++ | Y-Less/compiler | /source/compiler/memfile.c | UTF-8 | 2,024 | 2.671875 | 3 | [
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /* Implementation of a file functions interface for reading/writing into
* memory.
*
* Copyright (c) faluco / http://www.amxmodx.org/, 2006
* Version: $Id: memfile.c 3636 2006-08-14 15:42:05Z thiadmer $
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "memfile.h"
#if defined FORTIFY
#include <alloc/fortify.h>
#endif
#if defined _MSC_VER && defined _WIN32
#define strdup _strdup
#endif
memfile_t *memfile_creat(const char *name, size_t init)
{
memfile_t mf;
memfile_t *pmf;
mf.size = init;
mf.base = (char *)malloc(init);
mf.usedoffs = 0;
if (!mf.base)
{
return NULL;
}
mf.offs = 0;
pmf = (memfile_t *)malloc(sizeof(memfile_t));
memcpy(pmf, &mf, sizeof(memfile_t));
pmf->name = strdup(name);
return pmf;
}
void memfile_destroy(memfile_t *mf)
{
assert(mf != NULL);
free(mf->name);
free(mf->base);
free(mf);
}
void memfile_seek(memfile_t *mf, long seek)
{
assert(mf != NULL);
mf->offs = seek;
}
long memfile_tell(const memfile_t *mf)
{
assert(mf != NULL);
return mf->offs;
}
size_t memfile_read(memfile_t *mf, void *buffer, size_t maxsize)
{
assert(mf != NULL);
assert(buffer != NULL);
if (!maxsize || mf->offs >= mf->usedoffs)
{
return 0;
}
if (mf->usedoffs - mf->offs < (long)maxsize)
{
maxsize = mf->usedoffs - mf->offs;
if (!maxsize)
{
return 0;
}
}
memcpy(buffer, mf->base + mf->offs, maxsize);
mf->offs += maxsize;
return maxsize;
}
int memfile_write(memfile_t *mf, const void *buffer, size_t size)
{
assert(mf != NULL);
assert(buffer != NULL);
if (mf->offs + size > mf->size)
{
char *orgbase = mf->base; /* save, in case realloc() fails */
size_t newsize = (mf->size + size) * 2;
mf->base = (char *)realloc(mf->base, newsize);
if (!mf->base)
{
mf->base = orgbase; /* restore old pointer to avoid a memory leak */
return 0;
}
mf->size = newsize;
}
memcpy(mf->base + mf->offs, buffer, size);
mf->offs += size;
if (mf->offs > mf->usedoffs)
{
mf->usedoffs = mf->offs;
}
return 1;
}
| true |