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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
262138fec1ccbc0968e17e40f5f051f50c1218e8 | C++ | peeyushy95/Project-Euler | /Project Euler #47 Distinct primes factors.cpp | UTF-8 | 2,809 | 2.625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /*
AUTHOR : Peeyush Yadav
Problem : Project Euler #47: Distinct primes factors
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define f(a,b,c) for(int a=b;a<c;a++)
#define s(x) scanf("%d",&x);
#define sl(x) scanf("%lld",&x);
#define p(x) printf("%d\n",x);
#define p2(x,y) printf("%d %d\n",x,y);
#define pl(x) printf("%lld\n",x);
#define pl2(x,y) printf("%lld %lld\n",x,y);
#define p1d(a,n) for(int ix=0;ix<n;ix++) printf("%d ",a[ix]); printf("\n");
#define p2d(a,n,m) for(int ix=0;ix<n;ix++){ for(int jx=0;jx<m;jx++) printf("%d ",a[ix][jx]); printf("\n");}
void input(){
#ifdef Megamind
#define DEBUG
#define TRACE
freopen("inp.txt","r",stdin);
//freopen("out1.txt","w",stdout);
#endif
}
#ifdef TRACE
#define trace(x) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<endl;
#define trace2(x,y) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<" | "#y" = "<<y<<endl;
#define trace3(x,y,z) cerr<<__FUNCTION__<<":"<<__LINE__<<": "#x" = "<<x<<" | "#y" = "<<y<<" | "#z" = "<<z<<endl;
#else
#define trace(x)
#define trace2(x,y)
#define trace3(x,y,z)
#endif
inline ll power(ll a, ll b, ll m) {
ll r = 1;
while(b) {
if(b & 1) r = r * a % m;
a = (a * a)% m;
b >>= 1;
}
return r;
}
inline ll power(ll a, ll b) {
ll r = 1;
while(b) {
if(b & 1) r = r * a ;
a = a * a;
b >>= 1;
}
return r;
}
/*........................................................END OF TEMPLATES.......................................................................*/
bool avail[2000006];
int prime[150000],pcounter=0;
void seive(){
for(int i=2;i*i <= 2000006 ; i++){
if(!avail[i]){
int j= i+i;
while(j<= 2000006){
avail[j]=1;
j+=i;
}
}
}
f(i,2,2000006){
if(!avail[i]) prime[pcounter++]=i;
}
trace(pcounter)
}
int main(){
input();
//seive();
int n,k;
s(n);
s(k);
int tempp;
bool ok=1;
int lagatar = 0,ans;
f(iter,14,n+k+2){
ok=1;
int j = iter;
tempp = 0;
if(!(j&1)){
tempp++;
while(!(j&1)) j>>=1;
}
for(int i=3;i*i<=j;i+=2){
if(j%i == 0){
tempp++;
if(tempp > k) {
ok = 0;
break;
}
while(j%i == 0) j/=i;
}
}
if(j>1) tempp++;
if(tempp>k) ok = 0;
if(tempp == k){
lagatar++;
if(lagatar >=k)
if(iter - k + 1 <= n )
p(iter - k+1)
}
else lagatar = 0;
}
#ifdef Megamind
cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << " ms." << endl;
#endif
}
| true |
dc620790abb248e7968be3ea786bedf03f7f993f | C++ | beingveera/cplusplus-Programming | /Compititive/Triangle.cpp | UTF-8 | 372 | 2.953125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define Area(base,height) (.5*base*height)
/*
int main(){
pair<int,int> tri;
cin>>tri.first;
cin>>tri.second;
cout<<Area(tri.first,tri.second)<<endl;
}
*/
int main(){
int x;
std::vector<int> v;
if(v.empty()){
for (int i = 0; i < 2; ++i)
{
cin>>x;
v.push_back(x);
}
}
cout<<Area(v[0],v[1])<<endl;
} | true |
1753436c85a55a645345327542cd748664ac4be1 | C++ | SugarSpinda/MyLib | /thread/Condition.cpp | UTF-8 | 4,209 | 2.890625 | 3 | [
"MIT"
] | permissive | #ifdef __linux__
#include <sys/time.h>
#endif
#include "Condition.hpp"
#include "common/Exception.hpp"
#include "common/Log.hpp"
#ifdef USE_FAKE_CONDITION_VARIABLE
#include <list>
typedef struct ConditionEvent
{
ConditionEvent() : wokenUp(false)
{
this->event = ::CreateEvent(nullptr, TRUE, FALSE, nullptr);
}
~ConditionEvent() { ::CloseHandle(this->event); }
bool wokenUp;
HANDLE event;
} ConditionEvent;
class ConditionQueue
{
public:
typedef std::list<ConditionEvent *> EventList;
Mutex mutex;
EventList list;
EventList freeList;
ConditionEvent * prepare()
{
mutex.lock();
ConditionEvent *ce = nullptr;
if (freeList.empty() == true)
ce = new ConditionEvent();
else
{
ce = freeList.front();
freeList.pop_front();
ce->wokenUp = false;
}
list.push_back(ce);
mutex.unlock();
return ce;
}
bool wait(ConditionEvent *ce)
{
return ::WaitForSingleObject(ce->event, INFINITE) == WAIT_OBJECT_0;
}
bool wait(ConditionEvent *ce, int millisecond)
{
return ::WaitForSingleObject(ce->event, (unsigned int)millisecond) == WAIT_OBJECT_0;
}
void post(ConditionEvent *ce)
{
mutex.lock();
list.remove(ce);
::ResetEvent(ce->event);
freeList.push_back(ce);
mutex.unlock();
}
};
#endif
Condition::Condition()
{
#ifdef HAS_CONDITION_VARIABLE
::InitializeConditionVariable(&this->cond);
#elif defined(USE_FAKE_CONDITION_VARIABLE)
cq = new ConditionQueue();
#else
int ret = ::pthread_cond_init(&this->cond, nullptr);
if (ret != 0)
LOG.e(TRACE, Log::format("Condition initialize failed: %d", ret));
#endif
}
Condition::~Condition()
{
#ifdef HAS_CONDITION_VARIABLE
#elif defined(USE_FAKE_CONDITION_VARIABLE)
for (std::list<ConditionEvent *>::iterator it = this->cq->list.begin();
it != this->cq->list.end(); ++it)
{
delete *it; // Destroyed while threads are still waiting.
}
for (std::list<ConditionEvent *>::iterator it = this->cq->freeList.begin();
it != this->cq->freeList.end(); ++it)
{
delete *it;
}
#else
CHECK_SUCCESS_RETURN(::pthread_cond_destroy(&this->cond), int, 0);
#endif
}
void Condition::wait(Mutex &mutex)
{
#ifdef HAS_CONDITION_VARIABLE
::SleepConditionVariableCS(&this->cond, &mutex.self(), INFINITE);
#elif defined(USE_FAKE_CONDITION_VARIABLE)
ConditionEvent *ce = this->cq->prepare();
mutex.unlock();
bool ret = this->cq->wait(ce);
mutex.lock();
if (ret == true)
this->cq->post(ce);
#else
CHECK_SUCCESS_RETURN(::pthread_cond_wait(&this->cond, &mutex.self()), int, 0);
#endif
}
bool Condition::timedWait(Mutex &mutex, int millisecond)
{
#ifdef HAS_CONDITION_VARIABLE
return ::SleepConditionVariableCS(&this->cond, &mutex.self(), millisecond) != 0;
#elif defined(USE_FAKE_CONDITION_VARIABLE)
ConditionEvent *ce = this->cq->prepare();
mutex.unlock();
bool ret = this->cq->wait(ce, millisecond);
mutex.lock();
if (ret == true)
this->cq->post(ce);
return ret;
#else
struct timeval now;
struct timespec ts;
::gettimeofday(&now, nullptr);
long result = now.tv_usec + millisecond * 1000;
long us = result % 1000000;
long s = result / 1000000 + now.tv_sec;
ts.tv_sec = s;
ts.tv_nsec = us * 1000;
int ret = ::pthread_cond_timedwait(&this->cond, &mutex.self(), &ts);
return ret == 0 ? true : false;
#endif
}
void Condition::notifyOne()
{
#ifdef HAS_CONDITION_VARIABLE
::WakeConditionVariable(&this->cond);
#elif defined(USE_FAKE_CONDITION_VARIABLE)
this->cq->mutex.lock();
for (std::list<ConditionEvent *>::iterator it = this->cq->list.begin();
it != this->cq->list.end(); ++it)
{
if ((*it)->wokenUp == false)
{
::SetEvent((*it)->event);
(*it)->wokenUp = true;
break;
}
}
this->cq->mutex.unlock();
#else
CHECK_SUCCESS_RETURN(::pthread_cond_signal(&this->cond), int, 0);
#endif
}
void Condition::notifyAll()
{
#ifdef HAS_CONDITION_VARIABLE
::WakeAllConditionVariable(&this->cond);
#elif defined(USE_FAKE_CONDITION_VARIABLE)
this->cq->mutex.lock();
for (std::list<ConditionEvent *>::iterator it = this->cq->list.begin();
it != this->cq->list.end(); ++it)
{
::SetEvent((*it)->event);
(*it)->wokenUp = true;
}
this->cq->mutex.unlock();
#else
CHECK_SUCCESS_RETURN(::pthread_cond_broadcast(&this->cond), int, 0);
#endif
}
| true |
e98926584d06e62276944b851caa0f022dcc09d6 | C++ | yyao93/Game-Me2D | /src/fullpath.cpp | UTF-8 | 194 | 2.546875 | 3 | [] | no_license | #include "../include/fullpath.h"
std::string full_path(const char * filename) {
char * real_path = realpath(filename, NULL);
std::string ret = real_path;
free(real_path);
return ret;
}
| true |
03ed32f90af5cb98b4e0524ff2d4e5ae10835773 | C++ | mkk96/IIIT-H-Initial-code | /SEARCHING AND SORTING/mergeSort.cpp | UTF-8 | 760 | 3.078125 | 3 | [] | no_license | #include<iostream>
#include<bits/stdc++.h>
#include<vector>
#include<queue>
using namespace std;
void merge(vector<int> &v,int l,int mid,int h)
{
queue<int> temp;
int i=l,j=mid+1;
while(i<=mid&&j<=h)
{
if(v[i]<v[j])
{
temp.push(v[i++]);
}
else
{
temp.push(v[j++]);
}
}
while(i<=mid)
{
temp.push(v[i++]);
}
while(j<=h)
{
temp.push(v[j++]);
}
for(int k=l;k<=h;k++)
{
v[k]=temp.front();
temp.pop();
}
}
void mergeSort(vector<int> &v,int l,int h)
{
if(l<h)
{
int mid=(l+h)/2;
mergeSort(v,l,mid);
mergeSort(v,mid+1,h);
merge(v,l,mid,h);
}
}
int main()
{
int n;
cin>>n;
vector<int> v(n,0);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
mergeSort(v,0,n-1);
for(int i=0;i<n;i++)
{
cout<<v[i]<<" ";
}
return 0;
}
| true |
d31924c7ae7f83c6ec587f45a58e57807ac5520d | C++ | danzeeeman/roxlu | /lib/include/roxlu/io/File.h | UTF-8 | 2,547 | 2.53125 | 3 | [] | no_license | #ifndef ROXLU_FILEH
#define ROXLU_FILEH
#include <string>
#include <fstream>
#include <cstdlib>
#include <roxlu/core/platform/Platform.h>
#if ROXLU_PLATFORM == ROXLU_APPLE
#include <TargetConditionals.h>
#include <mach-o/dyld.h>
#elif ROXLU_PLATFORM == ROXLU_WINDOWS
#include <windows.h>
#endif
using std::string;
using std::ofstream;
namespace roxlu {
class File {
public:
File();
~File();
static void putFileContents(string file, string contents, bool inDataPath = true) {
ofstream of;
if(inDataPath) {
file = File::toDataPath(file);
}
of.open(file.c_str(), std::ios::out);
if(!of.is_open()) {
printf("File: cannot open file: '%s'\n", file.c_str());
return;
}
of.write(contents.c_str(), contents.length());
of.close();
}
static string getFileContents(string file, bool inDataPath = true) {
if(inDataPath) {
file = File::toDataPath(file);
}
std::string result = "";
std::string line = "";
std::ifstream ifs(file.c_str());
if(!ifs.is_open()) {
printf("File: cannot open file: '%s'\n", file.c_str());
return result;
}
while(getline(ifs,line)) {
result += line +"\n";
}
return result;
}
static string toDataPath(string file) {
return toDataPath(file.c_str());
}
static string toDataPath(const char* file) {
#if ROXLU_PLATFORM == ROXLU_APPLE
return getCWD() +"/../../../data/" +file;
#elif ROXLU_PLATFORM == ROXLU_WINDOWS
return getCWD() +"\\data\\" +file;
#else
return getCWD() +"/" +file;
#endif
}
static time_t getTimeModified(string file, bool inDataPath = true) {
if(inDataPath) {
file = File::toDataPath(file);
}
printf("MUST IMPLEMENT getTimeModified\n");
return 0;
}
static string getCWD() {
#if ROXLU_PLATFORM == ROXLU_APPLE
// hackedyhack
char path[1024];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) != 0) {
printf("buffer too small; need size %u\n", size);
}
char res[1024];
char* clean = realpath(path, res);
if(clean) {
string fullpath(clean);
size_t pos = fullpath.find_last_of('/');
if(pos != std::string::npos) {
string noexe = fullpath.substr(0,pos+1);
return noexe;
}
}
return clean;
#elif ROXLU_PLATFORM == ROXLU_WINDOWS
char buffer[MAX_PATH];
GetModuleFileNameA( NULL, buffer, MAX_PATH );
string::size_type pos = string( buffer ).find_last_of( "\\/" );
return string( buffer ).substr( 0, pos);
#else
char buf[1024];
getcwd(buf, 1024);
return buf;
#endif
}
};
}
#endif | true |
75652ad3775c6b693850bba54233d2a0a3182c02 | C++ | nidalbedyouch/PPP-greedy-tabusearch | /src/Src/proyecto.cpp | UTF-8 | 16,829 | 3.015625 | 3 | [
"MIT"
] | permissive | #include "utilidades.cpp"
/*
* Lee el archivo con formato:
* Y
* T
* K_1,C_1;K_2,C_2;...;K_Y,c_Y
*
* In: Nombre del archivo (string)
* Out: Tipo de dato PPP.
* PPP -> Y: Cantidad de Yates
* PPP -> Y: Cantidad de Yates
* PPP -> vtrK: Capacidad del Yate_i
* PPP -> vtrC: Tripulación del Yate_i
*/
PPP leerArchivo(string archivo) {
ifstream arch;
int Y, T;
string config;
arch.open(archivo.c_str());
if (!arch.good()) {
cout << "El archivo: '" << archivo << "' no existe. Saliendo del programa." << endl << endl;
exit(1);
}
arch >> Y >> T >> config;
arch.close();
string separadorPuntoComa, separadorComa;
istringstream streamPuntoComa(config);
vector<int> vtrK, vtrC;
// Spliteando por punto y coma la tercera línea
while(getline(streamPuntoComa, separadorPuntoComa, ';')) {
// Spliteando por coma cada config de un yate
int i = 0;
istringstream streamComa(separadorPuntoComa);
while(getline(streamComa, separadorComa, ',')) {
if (i == 0)
vtrK.push_back(atoi(separadorComa.c_str()));
else
vtrC.push_back(atoi(separadorComa.c_str()));
i++;
}
}
PPP problema = {Y, T, vtrK, vtrC};
return problema;
}
/* Lee el archivo de configuración para obtener el vector de hosts
*
* In: Nombre del archivo de configuración
* Out: Mapeo del nombre de la configuración al vector de hosts asociado
*/
map<string, vector<int> > leerArchivoConfig(string archivo) {
map<string, vector<int> > configuracionesHosts;
ifstream fe(archivo.c_str());
vector<string> lectura;
if (!fe.good()) {
cout << "El archivo: '" << archivo << "' no existe. Saliendo del programa." << endl << endl;
exit(1);
}
for(unsigned i = 0; i < 3 * contarLineasArchivo(archivo); ++i) {
string palabra;
fe >> palabra;
lectura.push_back(palabra);
}
fe.close();
// Se parsea a mano los string de hosts de las configuraciones a un vector de hosts
for(unsigned j = 0; j < contarLineasArchivo(archivo); ++j) {
string numero = "";
int leyoGuion = 0;
vector<int> hostsLinea;
for(unsigned i = 0; i < lectura[3*j+2].size(); ++i) {
if (lectura[3*j+2][i] == '-') {
leyoGuion = 1;
hostsLinea.push_back(atoi(numero.c_str())-1);
numero = "";
leyoGuion = 1;
}
else if (lectura[3*j+2][i] == ',') {
if (leyoGuion) {
for(unsigned i = hostsLinea.back()+1; i <= atoi(numero.c_str()); ++i)
hostsLinea.push_back(i-1);
}
else
hostsLinea.push_back(atoi(numero.c_str())-1);
leyoGuion = 0;
numero = "";
}
else
numero += lectura[3*j+2][i];
}
if (leyoGuion) {
for(unsigned i = hostsLinea.back()+1; i <= atoi(numero.c_str()); ++i)
hostsLinea.push_back(i-1);
}
else
hostsLinea.push_back(atoi(numero.c_str())-1);
hostsLinea.erase(hostsLinea.begin());
lectura[3*j].pop_back();
configuracionesHosts[lectura[3*j]] = hostsLinea;
}
if (archivo == "Configuraciones.txt")
configuracionesHosts["pp3"][0] = 0;
return configuracionesHosts;
}
/* Restricción de que para todo x_{g,1}, x_{g,2}, ..., x_{g,T} sean diferentes
*
* In: Matriz de enteros
* Out: Cantidad de penalizaciones
*/
int allDiffPenalty(matrix matriz) {
int contador = 0;
for (int i = 0; i < matriz.size(); ++i) {
for (unsigned j = 0; j < matriz[i].size(); ++j) {
for (unsigned k = j + 1; k < matriz[i].size(); ++k) {
if (matriz[i][j] == matriz[i][k])
contador++;
}
}
}
return contador;
}
/* Restricción de que para todo par de invitados sólo se conozcan a lo más una vez
*
* In: Matriz de enteros
* Out: Cantidad de penalizaciones
*/
int crewMeetOncePenalty(matrix matriz) {
int contador, penalizacion = 0;
for(unsigned i = 0; i < matriz.size(); ++i) {
for(unsigned j = i + 1; j < matriz.size(); ++j) {
contador = 0;
for(unsigned k = 0; k < matriz[0].size(); ++k) {
if (matriz[i][k] == matriz[j][k])
contador++;
}
if (contador <= 1)
penalizacion += 0;
else
penalizacion += contador - 1;
}
}
return penalizacion;
}
/* Restricción de que la tripulación a bordo no puede exceder de la capacidad del yate anfitrión
*
* In: Anfitrion Hi (entero), diccionario de las posiciones de los yates invitados (map<int,int>),
* vectores de capacidades y tamaño tripulaciónvtrK y vtrC respectivamente, Matriz de enteros
* Out: Cantidad de penalizaciones
*/
int hostCapacityPenalty(vector<int> hosts, map<int,int> posicionesInvitados, vector<int> vtrK, vector<int> vtrC, matrix matriz) {
int sigma, tripulacion = 0, penalizacion = 0;
// Para cada host (h) se verifica si en un tiempo T (en una columna) los valores x_{g,t} que
// sean igual a h (para tiempo t la tripulacion g esta en h) no superen la capacidad de h
for(unsigned h = 0; h < hosts.size(); ++h) {
//cout << "Para h = " << hosts[h] << endl;
for(unsigned i = 0; i < matriz[0].size(); ++i) {
tripulacion = 0;
//cout << "\tPara T" << i << endl;
for(unsigned j = 0; j < matriz.size(); ++j) {
if (matriz[j][i] == hosts[h]) {
//cout << "\t\t(j,i) = (" << j << ", " << i << ")" << endl;
tripulacion += getTripulacionYate(posicionesInvitados[j], vtrC);
}
}
tripulacion += getTripulacionYate(hosts[h], vtrC); // A la tripulación presente en el yate h se le añade la tripulación de h
//cout << "\tPara T" << i << " hay a bordo: " << tripulacion << " con capacidad de " << getCapacidadYate(hosts[h], vtrK) << endl;
//cout << endl;
sigma = getCapacidadYate(hosts[h], vtrK) - tripulacion;
if (sigma >= 0)
penalizacion += 0;
else
//penalizacion += 1 + (abs(sigma) - 1) / 4;
penalizacion += 1;
//cout << "sigma = " << sigma <<" - penalizacion = " << penalizacion << endl;
}
}
return penalizacion;
}
/* Retorna la suma de todas las penalizaciones */
int getAllPenalty(vector<int> hosts, map<int,int> posicionesInvitados, matrix matriz, PPP problema) {
int allDif = allDiffPenalty(matriz);
int meetOnlyOnce = crewMeetOncePenalty(matriz);
int hostCapacity = hostCapacityPenalty(hosts, posicionesInvitados, problema.vtrK, problema.vtrC, matriz);
int total = allDif + meetOnlyOnce + hostCapacity;
//cout << "All Diff:\t\t\t\t" << allDif << endl;
//cout << "Crew meet only once:\t" << meetOnlyOnce << endl;
//cout << "Host Capacity:\t\t\t" << hostCapacity << endl;
//cout << "Total: \t\t\t\t\t" << total << endl;
return total;
}
/* Greedy.
*
* In: Mapeo de indice en la matriz a posiciones de los Invitados, vector de hosts, el problema, la cantidad de iteraciones y el largo de la lista tabu
* Out: Tupla de dos elementos (cantidad penalizaciones, solución encontrada)
*/
matrix greedy(map<int, int> posicionesGuests, vector<int> hosts, PPP problema){
matrix matriz;
vector<int> recorridoGuest0;
for(unsigned g = 0; g < posicionesGuests.size(); ++g) {
vector<int> recorridoGuest;
matriz.push_back(recorridoGuest);
for(unsigned t = 0; t < problema.T; ++t) {
matriz[g].push_back(hosts[0]);
// Para cada (g,t) se busca aquel hosts que cumpla todas las restricciones (penalizaciones = 0)
// si no lo encuentra deja asignado el mejor host posible.
int menorPuntaje = 9999, mejorHost;
for(unsigned h = 0; h < hosts.size(); ++h) {
matriz[g][t] = hosts[h];
//printearMatriz(matriz);
int p = getAllPenalty(hosts, posicionesGuests, matriz, problema);
if (p < menorPuntaje) {
menorPuntaje = p;
mejorHost = hosts[h];
}
// Si la penalización actual es 0 entonces se termina de buscar un host para (g,t) y pasa al siguiente tiempo T
if (p == 0)
break;
}
matriz[g][t] = mejorHost;
}
}
cout << "Greedy:" << endl<<endl;
printearMatriz(matriz);
int allDif = allDiffPenalty(matriz);
int meetOnlyOnce = crewMeetOncePenalty(matriz);
int hostCapacity = hostCapacityPenalty(hosts, posicionesGuests, problema.vtrK, problema.vtrC, matriz);
int total = getAllPenalty(hosts, posicionesGuests, matriz, problema);
cout << "All Diff:\t\t" << allDif << endl;
cout << "Crew meet only once:\t" << meetOnlyOnce << endl;
cout << "Host Capacity:\t\t" << hostCapacity << endl;
cout << "--------------------------" << endl;
cout << "Total: \t\t\t" << total << endl<<endl;
return matriz;
}
/* Tabu Search.
*
* In: Mapeo de indice en la matriz a posiciones de los Invitados, vector de hosts, el problema, la cantidad de iteraciones y el largo de la lista tabu
* Out: Tupla de dos elementos (cantidad penalizaciones, solución encontrada)
*/
pair<int, matrix> tabuSearch(matrix solInicial, map<int, int> posicionesGuests, vector<int> hosts, PPP problema, int ITERACIONES, int LARGO_LISTA_TABU){
matrix mejorSol, solActual, vecino;
solActual = solInicial;
int menorPuntaje = 99999, iteracion = 0, puntaje = getAllPenalty(hosts, posicionesGuests, solActual, problema);
vector<pair<int, int> > listaTabu;
mejorSol = solActual;
while (iteracion < ITERACIONES){
vecino = solActual;
menorPuntaje = 9999;
// Generando vecindario
for(unsigned i = 0; i < solActual.size(); ++i) {
for(unsigned j = 0; j < solActual[i].size(); ++j) {
pair<int,int> mejorMovimiento;
pair<int,int> movimiento = make_pair(i,j);
int huboMejora = 0;
// Se evalua si mejora el problema en cada asignación a un host distinto
for(unsigned h = 0; h < hosts.size(); ++h) {
if (hosts[h] != vecino[i][j]) {
vecino[i][j] = hosts[h];
int puntaje = getAllPenalty(hosts, posicionesGuests, vecino, problema);
if (puntaje < menorPuntaje && !existMovTabu(movimiento, listaTabu)) {
solActual = vecino;
menorPuntaje = puntaje;
huboMejora = 1;
}
vecino = solActual;
}
}
// Si dentro del vecindario encontró una mejora entonces se agrega dicho movimiento a la lista tabú
if (huboMejora) {
listaTabu.insert(listaTabu.begin(), movimiento);
if (listaTabu.size() > LARGO_LISTA_TABU)
listaTabu.pop_back();
}
}
}
// Si solActual es mejor que mejorSol se reasigna mejorSol
if (getAllPenalty(hosts, posicionesGuests, solActual, problema) < getAllPenalty(hosts, posicionesGuests, mejorSol, problema))
mejorSol = solActual;
// En caso de que el puntaje de penalizaciones sea 0 (óptimo global) se termina de iterar
if (menorPuntaje == 0)
break;
iteracion++;
}
cout << endl<<"Tabu Search:" << endl<<endl;
printearMatriz(mejorSol);
int allDif = allDiffPenalty(mejorSol);
int meetOnlyOnce = crewMeetOncePenalty(mejorSol);
int hostCapacity = hostCapacityPenalty(hosts, posicionesGuests, problema.vtrK, problema.vtrC, mejorSol);
int total = getAllPenalty(hosts, posicionesGuests, mejorSol, problema);
cout << "All Diff:\t\t" << allDif << endl;
cout << "Crew meet only once:\t" << meetOnlyOnce << endl;
cout << "Host Capacity:\t\t" << hostCapacity << endl;
cout << "--------------------------" << endl;
cout << "Total: \t\t\t" << total << endl<<endl;
return make_pair(total, mejorSol);
}
/* Escribe el archivo de salida
*
* In: Nombre del archivo de instancia, vector de hosts, las posiciones de los invitados, la matriz solución, el problema, tiempo de ejecución y penalizaciones
* Out: No posee retorno
*/
void escribirOutput(string NOMBRE_INSTANCIA, vector<int> hosts, map<int, int> posicionesGuest, matrix matriz, PPP problema, double tiempo, int penalizaciones) {
ofstream archivo;
archivo.open("Salida/" + NOMBRE_INSTANCIA + ".txt");
/* Recorre la solución y la mapea para identificar por tiempo los anfitriones que hospedan a los yates, por ejemplo:
*
* Para T = 1
* 1 => A
* 2 => A [2+1/ 10]
* 3 => A [4/ 10]
* 4 => 2
* 5 => 3
* 6 => 2
*
* Para T = 2
* 1 => A [1/ 10]
* 2 => A [4/ 10]
* 3 => A [2/ 10]
* 4 => 3
* 5 => 2
* 6 => 1
*
* Para T = 3
* 1 => A [2+4/ 10]
* 2 => A
* 3 => A [1/ 10]
* 4 => 1
* 5 => 1
* 6 => 3
*/
for(unsigned i = 0; i < matriz[0].size(); ++i) {
//cout << "Para T = " << i << endl;
map<int, string> mapSalida;
for(unsigned h = 0; h < hosts.size(); ++h)
mapSalida[hosts[h]] = "A ";
for(unsigned h = 0; h < hosts.size(); ++h) {
int tieneInvitados = 0;
for(unsigned j = 0; j < matriz.size(); ++j) {
if (matriz[j][i] == hosts[h]) {
if (tieneInvitados == 0)
mapSalida[hosts[h]] += "[";
ostringstream convert;
convert << getTripulacionYate(posicionesGuest[j], problema.vtrC);
mapSalida[hosts[h]] += convert.str();
mapSalida[hosts[h]] += "+";
tieneInvitados = 1;
}
}
// Cerrando el string de yates host
if (tieneInvitados) {
mapSalida[hosts[h]].pop_back();
mapSalida[hosts[h]] += "/ ";
mapSalida[hosts[h]] += to_string(getCapacidadYate(hosts[h], problema.vtrK));
mapSalida[hosts[h]] += "]";
tieneInvitados = 0;
}
// Agregando al map los yates invitados
for(unsigned g = 0; g < posicionesGuest.size(); ++g) {
ostringstream convert;
convert << matriz[g][i] + 1;
mapSalida[posicionesGuest[g]] = convert.str();
}
}
// Se escribe el archivo
archivo << "T = " << i + 1 << endl;
archivo << "---------------------" << endl;
for(map<int, string>::iterator it = mapSalida.begin(); it != mapSalida.end(); ++it)
archivo << it->first + 1 << " -> " << it->second << endl;
archivo << endl;
}
archivo << "Botes anfitriones óptimos: " << hosts.size() << "." << endl;
archivo << "Tiempo de ejecución: " << tiempo << " [s]." << endl;
archivo << "Penalizaciones: " << penalizaciones << "." << endl;
archivo.close();
}
int main(int argc, char const *argv[]) {
int termino = 0, offsetHost = 0;
if (argv[1] == string("CSPLib")) {
while (!termino) {
// Configuración
string NOMBRE_INSTANCIA = argv[2];
int ITERACIONES_TS = atoi(argv[3]), LARGO_LISTA_TABU = atoi(argv[4]);
// Declaración de variables
string PATH = "Instancias PPP/Instancias CSPLib/";
clock_t t_ini, t_fin;
map<int, int> posicionesGuests;
vector<int> hosts;
double secs;
pair <int, matrix> resultado;
matrix matrizInicial;
PPP problema;
int CANTHOSTS;
// Leyendo archivo de la instancia
problema = leerArchivo(PATH + NOMBRE_INSTANCIA + ".txt");
// Seteando hosts y guests
CANTHOSTS = problema.T + offsetHost;
vector< pair<int, int> > yatesHosts = getNMayores(CANTHOSTS, problema.vtrK);
for(unsigned i = 0; i < yatesHosts.size(); ++i)
hosts.push_back(yatesHosts[i].second);
posicionesGuests = getPosicionGuests(problema.Y, hosts);
// Ejecutando algoritmos
t_ini = clock();
matrizInicial = greedy(posicionesGuests, hosts, problema);
resultado = tabuSearch(matrizInicial, posicionesGuests, hosts, problema, ITERACIONES_TS, LARGO_LISTA_TABU);
t_fin = clock();
if (resultado.first != 0) {
offsetHost++;
continue;
}
secs = (double) (t_fin - t_ini) / CLOCKS_PER_SEC;
// Escribiendo el archivo de salida
escribirOutput(NOMBRE_INSTANCIA, hosts, posicionesGuests, resultado.second, problema, secs, resultado.first);
termino = 1;
}
}
else if (argv[1] == string("PPP")) {
// Configuración
int ITERACIONES_TS = atoi(argv[3]), LARGO_LISTA_TABU = atoi(argv[4]);
// Declaración de variables
string NOMBRE_INSTANCIA, ARCHIVO_SALIDA;
string PATH = "Instancias PPP/";
clock_t t_ini, t_fin;
map<int, int> posicionesGuests;
vector<int> hosts;
double secs;
pair <int, matrix> resultado;
matrix matrizInicial;
PPP problema;
// Leyendo archivo de la instancia y seteando hosts y guests
if (argv[2] == string("m1")) {
NOMBRE_INSTANCIA = string(argv[1]) + "_m1";
hosts = leerArchivoConfig(PATH + "Configuraciones/Configuraciones_m1.txt")["pp1_m"];
ARCHIVO_SALIDA = NOMBRE_INSTANCIA;
}
else if (argv[2] == string("m2")) {
NOMBRE_INSTANCIA = string(argv[1]) + "_m2";
hosts = leerArchivoConfig(PATH + "Configuraciones/Configuraciones_m2.txt")["pp1_m2"];
ARCHIVO_SALIDA = NOMBRE_INSTANCIA;
}
else {
NOMBRE_INSTANCIA = string(argv[1]);
hosts = leerArchivoConfig(PATH + "Configuraciones/Configuraciones.txt")[argv[2]];
ARCHIVO_SALIDA = NOMBRE_INSTANCIA + "_" + string(argv[2]);
}
// Leyendo archivo de la instancia
problema = leerArchivo(PATH + NOMBRE_INSTANCIA + ".txt");
posicionesGuests = getPosicionGuests(problema.Y, hosts);
// Ejecutando algoritmos
t_ini = clock();
matrizInicial = greedy(posicionesGuests, hosts, problema);
cout << "Trabajando... Si es que el problema es PPP normal se demora entre 2 a 3 minutos." << endl << endl;
resultado = tabuSearch(matrizInicial, posicionesGuests, hosts, problema, ITERACIONES_TS, LARGO_LISTA_TABU);
t_fin = clock();
secs = (double) (t_fin - t_ini) / CLOCKS_PER_SEC;
// Escribiendo el archivo de salida
escribirOutput(ARCHIVO_SALIDA, hosts, posicionesGuests, resultado.second, problema, secs, resultado.first);
}
return 0;
}
| true |
5653057055933e2cfdb2711f5dbcc1a6c1da3738 | C++ | AdriannaCencora/sdizo-1 | /sdizo/source/controllers/testControllers/structureTestController/structureTestController.cpp | WINDOWS-1250 | 11,107 | 2.96875 | 3 | [] | no_license | #include "stdafx.h"
#include "structureTestController.h"
#include "source\structures\array\Array.h"
#include "source\structures\list\List.h"
using namespace std;
structureTestController::structureTestController(GenericStructure * structure, std::string structureName)
{
m_structure = structure;
filename = structureName;
filename.append(".csv");
// Clearing the file
std::ofstream ofs;
ofs.open(filename, std::ofstream::out | std::ofstream::trunc);
ofs.close();
saveToFile(structureName);
srand((unsigned int)time(NULL));
}
void structureTestController::insertionTests()
{
insertAtBeginning();
insertAtEnd();
insertAtRandom();
cout << "Testy dodawania zakoczone" << endl;
}
void structureTestController::deletionTests()
{
deleteAtBeginning();
deleteAtEnd();
deleteAtRandom();
cout << "Testy usuwania zakoczone" << endl;
}
void structureTestController::findTests()
{
findAtBeginning();
findAtEnd();
findAtRandom();
cout << "Testy wyszukiwania zakoczone" << endl;
}
void structureTestController::insertAtBeginning()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
bool byValue = (dynamic_cast<Array*>(m_structure) == nullptr);
saveToFile("Insert at beginning");
cout << "Test: wstawianie na pocztku" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i)
{
startTime = chrono::high_resolution_clock::now();
m_structure->addElement(0, i);
endTime = chrono::high_resolution_clock::now();
if (byValue)
m_structure->removeElement(i);
else
m_structure->removeElement(0);
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: wstawianie na pocztku" << endl;
}
void structureTestController::insertAtEnd()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
bool byValue = (dynamic_cast<Array*>(m_structure) == nullptr);
saveToFile("Insert at end");
cout << "Test: wstawianie na kocu" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i) {
startTime = chrono::high_resolution_clock::now();
m_structure->addElement((m_structure->getSize() - 1 <0)? 0 : m_structure->getSize() - 1);
endTime = chrono::high_resolution_clock::now();
m_structure->removeElement((m_structure->getSize() - 1 < 0) ? 0 : m_structure->getSize() - 1);
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: wstawianie na kocu" << endl;
}
void structureTestController::insertAtRandom()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
saveToFile("Insert at random");
bool byValue = (dynamic_cast<Array*>(m_structure) == nullptr);
cout << "Test: wstawianie losowe" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i) {
startTime = chrono::high_resolution_clock::now();
m_structure->addElement(rand() % m_structure->getSize(), i);
endTime = chrono::high_resolution_clock::now();
if (byValue)
m_structure->removeElement(i);
else
m_structure->removeElement(0);
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: wstawianie losowe" << endl;
}
void structureTestController::deleteAtBeginning()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
Array* arr = dynamic_cast<Array*>(m_structure);
List* list = dynamic_cast<List*>(m_structure);
saveToFile("Delete at beginning");
cout << "Test: usuwanie na pocztku" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = testCase * 1000 - 1; i >= 0; --i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i)
{
startTime = chrono::high_resolution_clock::now();
if (arr != nullptr)
arr->removeElement(0);
else if (list != nullptr)
list->removeElement(i);
else
m_structure->removeElement(i);
endTime = chrono::high_resolution_clock::now();
m_structure->addElement(i);
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: usuwanie na pocztku" << endl;
}
void structureTestController::deleteAtEnd()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
saveToFile("Delete at end");
bool byValue = (dynamic_cast<Array*>(m_structure) == nullptr);
cout << "Test: usuwanie na kocu" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i)
{
startTime = chrono::high_resolution_clock::now();
if (byValue)
m_structure->removeElement(testCase * 1000 - 1 - i);
else
m_structure->removeElement(m_structure->getSize() - 1);
endTime = chrono::high_resolution_clock::now();
m_structure->addElement(i);
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: usuwanie na kocu" << endl;
}
void structureTestController::deleteAtRandom()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
int deletedIndex;
Array arr;
bool byValue = (dynamic_cast<Array*>(m_structure) == nullptr);
saveToFile("Delete at random");
cout << "Test: usuwanie losowe" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(i);
if (byValue)
for (int i = 0; i < testCase * 1000; ++i)
arr.addElement(i);
for (int i = 0; i < 1000; ++i)
{
if (byValue)
deletedIndex = rand() % arr.getSize();
startTime = chrono::high_resolution_clock::now();
try
{
if (byValue)
m_structure->removeElement(arr.getValue(deletedIndex));
else
m_structure->removeElement(rand() % m_structure->getSize());
}
catch (invalid_argument &e)
{
cout << e.what() << endl;
cout << "tried to delete: " << (deletedIndex) << endl;
system("pause");
return;
}
endTime = chrono::high_resolution_clock::now();
m_structure->addElement(i);
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
if(byValue)
arr.removeElement(deletedIndex);
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: usuwanie losowe" << endl;
}
void structureTestController::findAtBeginning()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
saveToFile("Find at beginning");
cout << "Test: wyszukiwanie na pocztku" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i)
{
startTime = chrono::high_resolution_clock::now();
m_structure->findValue(testCase * 1000 - rand() % 30);
endTime = chrono::high_resolution_clock::now();
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: wyszukiwanie na pocztku" << endl;
}
void structureTestController::findAtEnd()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
saveToFile("Find at end");
cout << "Test: wyszukiwanie na kocu" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i)
{
startTime = chrono::high_resolution_clock::now();
m_structure->findValue(0 + rand() % 30);
endTime = chrono::high_resolution_clock::now();
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: wyszukiwanie na kocu" << endl;
}
void structureTestController::findAtRandom()
{
chrono::high_resolution_clock::time_point startTime;
chrono::high_resolution_clock::time_point endTime;
int totalTime = 0;
saveToFile("Find at random");
cout << "Test: wyszukiwanie losowe" << endl;
for (int testCase = 1; testCase < 11; ++testCase)
{
cout << "n = " << testCase * 1000 << endl;
for (int i = 0; i < testCase * 1000; ++i)
m_structure->addElement(0, i);
for (int i = 0; i < 1000; ++i)
{
startTime = chrono::high_resolution_clock::now();
m_structure->findValue(rand() % m_structure->getSize());
endTime = chrono::high_resolution_clock::now();
totalTime += (int)std::chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count();
}
saveToFile(testCase * 1000, totalTime/1000);
totalTime = 0;
m_structure->clearStructure();
}
cout << "Zakoczono test: wyszukiwanie losowe" << endl;
}
| true |
b88cfdbc33e0e3cc25f004289ff4bdcc763938c4 | C++ | pnutus/CAutomata | /CellularAutomata/main.cpp | UTF-8 | 3,942 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | //
// main.cpp
// CellularAutomata
//
// Created by Pontus Granström on 2015-02-13.
// Copyright (c) 2015 Pontus Granström. All rights reserved.
//
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include "pcg_basic.h"
typedef uint32_t u32;
typedef int64_t s64;
typedef uint64_t u64;
typedef uint8_t u8;
typedef uint32_t bool32;
#define CHUNK_SIZE 64
struct ca_state {
int bit_count;
u64* bits;
};
void print_state(ca_state state)
{
// TODO: Make this two loops instead of divmod every digit
char string[state.bit_count + 1];
for (int bit_index = 0;
bit_index < state.bit_count;
bit_index++)
{
u64 state_chunk = state.bits[bit_index / CHUNK_SIZE];
int chunk_index = bit_index % CHUNK_SIZE;
bool32 active = ((state_chunk >> chunk_index) & 1);
char character = active * '#' + (1 - active) * ' ';
string[state.bit_count - bit_index - 1] = character;
}
string[state.bit_count] = 0;
printf("%s\n", string);
}
int string_length(const char* string)
{
int result = 0;
while (*string++)
{
result++;
}
return result;
}
ca_state init_state(int bit_count)
{
ca_state state;
state.bit_count = bit_count;
state.bits = (u64*) malloc((state.bit_count + 64) / 8);
return state;
}
ca_state state_from_string(const char* string)
{
ca_state state = init_state(string_length(string));
for (int bit_index = 0;
bit_index < state.bit_count;
bit_index++)
{
u64 chunk = state.bits[bit_index / CHUNK_SIZE];
chunk = (chunk << 1) | (string[bit_index] != ' ');
state.bits[bit_index / CHUNK_SIZE] = chunk;
}
return state;
}
ca_state evolve_ca(ca_state parent_state, u8 rule, ca_state child_state)
{
memset(child_state.bits, 0, (child_state.bit_count + 64) / 8);
u64 right_edge = (pcg32_random() & 1);
child_state.bits[0] = right_edge;
u32* parent_half_chunks = (u32*) parent_state.bits;
u32* child_half_chunks = (u32*) child_state.bits;
for (int half_chunk_index = 0;
half_chunk_index < ((parent_state.bit_count / (CHUNK_SIZE/2)) + 1);
half_chunk_index++)
{
u64 parent_chunk = *((u64*) (parent_half_chunks++));
u64 child_chunk = 0;
for (int bit_index = 0;
bit_index < (CHUNK_SIZE / 2);
bit_index++)
{
if ((half_chunk_index*CHUNK_SIZE/2 + bit_index + 2) >= parent_state.bit_count)
{
u64 left_edge = (pcg32_random() & 1) << (bit_index + 1);
child_chunk |= left_edge;
break;
}
u8 three_mask = 7; // 111
u8 three_state = (parent_chunk >> bit_index) & three_mask;
u64 active = ((rule >> three_state) & 1);
child_chunk |= (active << (bit_index + 1));
}
u64* child_chunk_pointer = (u64*) (child_half_chunks++);
*child_chunk_pointer |= child_chunk;
}
return child_state;
}
int main(int argc, const char * argv[]) {
if (argc > 1)
{
pcg32_srandom(time(0), 0);
u8 rule = atoi(argv[1]);
printf("R%d\n", rule);
ca_state state;
if (argc > 2)
{
state = state_from_string(argv[2]);
}
else
{
state = init_state(64);
state.bits[0] = (((u64) pcg32_random()) << 32) | pcg32_random();
}
ca_state new_state = init_state(state.bit_count);
for (;;)
{
print_state(state);
evolve_ca(state, rule, new_state);
ca_state temp = state;
state = new_state;
new_state = temp;
}
}
else
{
puts("Please supply a rule (number between 0 and 255).");
}
return 0;
}
| true |
85a034607176a1744c7a12ca20d5b476b7af5229 | C++ | wfgsy101/CPUSPLUS | /filereader/file_read.cc | UTF-8 | 603 | 2.921875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<iostream>
//#define SEEK_END 2
//#define SEEK_SET 0
using namespace std;
//读取文件字符个数
int GetFileLength(FILE *fp)
{
int length;
fseek(fp,0,SEEK_END);
length = ftell(fp);
fseek(fp,0,SEEK_SET);
return length;
}
//把此表文件读入mem内存区,
int FileRead( FILE * file_fp, char * mem, int read_length)
{
FILE *fp;
int length = 0;
char * mem_copy = mem;
fp=file_fp;
length = read_length;
length = GetFileLength(fp);
fread(mem_copy,length,1,fp);
*(mem_copy+length-1)='\0';
return 0;
}
| true |
45547cf52ec68619137281271b71c1e4885dc21b | C++ | CristinaBaby/Demo_CC | /ml/1068/Classes/codebase/platform/android/analytics/AnalyticsJNI.cpp | UTF-8 | 6,162 | 2.53125 | 3 | [] | no_license | //
// AnalyticsJNI.cpp
// AnalyticsCenter
//
// Created by Jimmy on 15/11/2.
//
//
#include "AnalyticsJNI.h"
#include "../JNIHelper.h"
AnalyticsJNI::AnalyticsJNI()
: ClassAnalytics(0)
,_analyticsJava(0)
,_methodSendEvent(0)
,_methodSendEvents(0)
,_methodSendScreenEvent(0)
,_methodEndSession(0)
,_methodSetDebugMode(0)
,_methodGetDebugMode(0)
,_methodSendEventMore(0)
{
}
AnalyticsJNI* AnalyticsJNI::m_pInstance = NULL;
AnalyticsJNI::~AnalyticsJNI() {
}
AnalyticsJNI* AnalyticsJNI::getInstance()
{
if (!m_pInstance)
{
m_pInstance = new AnalyticsJNI();
}
return m_pInstance;
}
bool AnalyticsJNI::init(JNIEnv *pEnv, jobject pAdJava)
{
JNIHelper::getInstance()->init(pEnv);
ClassAnalytics = pEnv->GetObjectClass(pAdJava);
if (!ClassAnalytics)
{
LOGE("initial JNI Analytics class Failed!");
return false;
}
ClassAnalytics = (jclass) JNIHelper::makeGlobalRef(pEnv, ClassAnalytics);
_analyticsJava = JNIHelper::makeGlobalRef(pEnv, pAdJava);
if (!_analyticsJava)
{
LOGE("Cache JNI Analytics jobject Java Failed!");
return false;
}
_methodSendEvent = pEnv->GetMethodID(ClassAnalytics, "sendEvent", "(Ljava/lang/String;Ljava/lang/String;)V");
if (!_methodSendEvent)
{
LOGE("JNI get Java method sendEvent(String, String) Failed!");
return false;
}
_methodSendEvents = pEnv->GetMethodID(ClassAnalytics, "sendEvent", "(Ljava/lang/String;Ljava/util/HashMap;)V");
if (!_methodSendEvents)
{
LOGE("JNI get Java method sendEvent(String, HashMap) Failed!");
return false;
}
_methodSendEventMore = pEnv->GetMethodID(ClassAnalytics, "sendEvent", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;J)V");
_methodSendScreenEvent = pEnv->GetMethodID(ClassAnalytics, "sendScreenEvent", "(Ljava/lang/String;)V");
if (!_methodSendScreenEvent)
{
LOGE("JNI get Java method sendScreenEvent Failed!");
return false;
}
_methodSetDebugMode = pEnv->GetMethodID(ClassAnalytics, "setDebugMode", "(Z)V");
if(!_methodSetDebugMode)
{
LOGE("JNI get Java method setDubugMode Failed!");
return false;
}
_methodEndSession = pEnv->GetMethodID(ClassAnalytics, "endSession", "()V");
if(!_methodEndSession)
{
LOGE("JNI get Java method endSession Failed!");
return false;
}
_methodGetDebugMode = pEnv->GetMethodID(ClassAnalytics, "getDebugMode", "()Z");
if(!_methodGetDebugMode)
{
LOGE("JNI get Java method endSession Failed!");
return false;
}
return true;
}
void AnalyticsJNI::sendEvent(std::string eventName, std::string value)
{
if (!_analyticsJava)
{
return;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
jstring name = lEnv->NewStringUTF(eventName.c_str());
jstring values = lEnv->NewStringUTF(value.c_str());
lEnv->CallVoidMethod(_analyticsJava, _methodSendEvent, name, values);
}
void AnalyticsJNI::sendEvent(std::string eventName, std::map<std::string , std::string> mapValue)
{
if (!_analyticsJava)
{
return;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
jstring name = lEnv->NewStringUTF(eventName.c_str());
/**
*c++ map 转化为 java HashMap
**/
jclass map_cls = lEnv->FindClass("java/util/HashMap");// 获取java HashMap类
jmethodID map_costruct = lEnv->GetMethodID(map_cls , "<init>","()V");// 获取java HashMap的构造函数
jobject map_obj = lEnv->NewObject(map_cls , map_costruct);// 通过构造方法初始化一个java HashMap
jmethodID map_put = lEnv->GetMethodID(map_cls,"put","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");// 获取java HashMap的put方法
jclass string_cls = lEnv->FindClass("java/lang/String");// 获取java String类,在c++ std::string 转化到Java String用到
jmethodID string_costruct = lEnv->GetMethodID(string_cls, "<init>", "([B)V");// 获取java String的构造方法
//循环取出c++map中的类容放进Java HashMap中
for(auto itr = mapValue.begin(); itr != mapValue.end(); itr++)
{
std::string ckey = itr->first;
std::string cvalue = itr->second;
//string obj转化
const char *keychar = ckey.c_str();
jbyteArray keybytes = lEnv->NewByteArray(strlen(keychar));
lEnv->SetByteArrayRegion(keybytes, 0, strlen(keychar), (jbyte*)keychar);
jobject KeyElement = lEnv->NewObject( string_cls, string_costruct, keybytes);
const char *valuechar = cvalue.c_str();
jbyteArray valuebytes = lEnv->NewByteArray(strlen(valuechar));
lEnv->SetByteArrayRegion(valuebytes, 0, strlen(valuechar), (jbyte*)valuechar);
jobject ValueElement = lEnv->NewObject( string_cls, string_costruct, valuebytes);
lEnv->CallObjectMethod(map_obj,map_put, KeyElement, ValueElement);
}
lEnv->CallVoidMethod(_analyticsJava, _methodSendEvents, name, map_obj);
}
void AnalyticsJNI::sendEvent(std::string category, std::string action, std::string label, long value)
{
if (!_analyticsJava)
{
return;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
jstring ca = lEnv->NewStringUTF(category.c_str());
jstring ac = lEnv->NewStringUTF(action.c_str());
jstring la = lEnv->NewStringUTF(label.c_str());
long long values = (long long)value;
lEnv->CallVoidMethod(_analyticsJava, _methodSendEventMore, ca, ac, la, values);
}
void AnalyticsJNI::sendScreenEvent(std::string screenName)
{
if (!_analyticsJava)
{
return;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
jstring name = lEnv->NewStringUTF(screenName.c_str());
lEnv->CallVoidMethod(_analyticsJava, _methodSendScreenEvent, name);
// std::string value = "UserEvent";
// jstring values = lEnv->NewStringUTF(value.c_str());
// lEnv->CallVoidMethod(_analyticsJava, _methodSendEvent, name, values);
}
void AnalyticsJNI::setDebugMode(bool bIsDebug)
{
if (!_analyticsJava)
{
return;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
lEnv->CallVoidMethod(_analyticsJava, _methodSetDebugMode, bIsDebug);
}
bool AnalyticsJNI::getDebugMode()
{
if (!_analyticsJava)
{
return false;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
jboolean ret = lEnv->CallBooleanMethod(_analyticsJava, _methodGetDebugMode);
return (ret == JNI_TRUE ? true : false);
}
void AnalyticsJNI::endSession()
{
if (!_analyticsJava)
{
return;
}
JNIEnv* lEnv = JNIHelper::getJNIEnv();
lEnv->CallVoidMethod(_analyticsJava, _methodEndSession);
}
| true |
5e35d1c4fa7e8142b0e963dda6b266faf7c5dd6d | C++ | rubyist/haulbox | /haul-box.ino | UTF-8 | 5,299 | 2.828125 | 3 | [
"MIT"
] | permissive | #include "outputter.h"
#include "button.h"
#define LED_PIN 18
int ledValue = 0;
byte rows[] = {8, 7, 6, 5, 4};
const int rowCount = sizeof(rows)/sizeof(rows[0]);
byte cols[] = {9, 10, 11, 12, 13};
const int colCount = sizeof(cols)/sizeof(cols[0]);
byte keys[colCount][rowCount];
Button *buttons[colCount][rowCount] = {
{ new Toggle(0), new Toggle(5), new PushButton(10), new PushButton(15), new Toggle(20) },
{ new Toggle(1), new Toggle(6), new PushButton(11), new Latch(16), new Toggle(21) },
{ new Toggle(2), new Toggle(7), new PushButton(12), new Toggle(17), new Toggle(22) },
{ new PushButton(3), new Toggle(8), new Toggle(13), new Toggle(18), new Toggle(23) },
{ new PushButton(4), new Toggle(9), new Toggle(14), new Toggle(19), new Toggle(24) },
};
// Rotary encoder
#define E1_CLK 2
#define E1_DATA 3
#define E1_UP_BTN 25
#define E1_DN_BTN 26
#define E2_CLK 0
#define E2_DATA 1
#define E2_UP_BTN 27
#define E2_DN_BTN 28
static int8_t rot_enc_table[] = {0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0};
volatile uint8_t prevNextCode1 = 0;
volatile uint16_t store1 = 0;
volatile uint8_t prevNextCode2 = 0;
volatile uint16_t store2 = 0;
// Rotary encoder directions are mapped to joystick button presses
Toggle *e1Up = new Toggle(E1_UP_BTN);
Toggle *e1Dn = new Toggle(E1_DN_BTN);
Toggle *e2Up = new Toggle(E2_UP_BTN);
Toggle *e2Dn = new Toggle(E2_DN_BTN);
// Change OUTPUT_JOYSTICK to OUTPUT_SERIAL for testing
Outputter output(OUTPUT_JOYSTICK, rowCount*colCount+4); // Account for rotary encoders acting as two buttons each
void setup() {
pinMode(LED_PIN, OUTPUT);
// Matrix setup
for (int x=0; x < rowCount; x++) {
pinMode(rows[x], INPUT);
}
for (int x = 0; x < colCount; x++) {
pinMode(cols[x], INPUT_PULLUP);
}
// Rotary encoder setup
pinMode(E1_CLK, INPUT_PULLUP);
pinMode(E1_DATA, INPUT_PULLUP);
pinMode(E2_CLK, INPUT_PULLUP);
pinMode(E2_DATA, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(E1_CLK), fire_rotary1, CHANGE);
attachInterrupt(digitalPinToInterrupt(E1_DATA), fire_rotary1, CHANGE);
attachInterrupt(digitalPinToInterrupt(E2_CLK), fire_rotary2, CHANGE);
attachInterrupt(digitalPinToInterrupt(E2_DATA), fire_rotary2, CHANGE);
output.begin();
}
// matrix reading code from https://www.baldengineer.com/arduino-keyboard-matrix-tutorial.html
void read_matrix() {
// iterate the columns
for (int colIndex = 0; colIndex < colCount; colIndex++) {
// col: set to output to low
byte curCol = cols[colIndex];
pinMode(curCol, OUTPUT);
digitalWrite(curCol, LOW);
// row: iterate through the rows
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
byte rowCol = rows[rowIndex];
pinMode(rowCol, INPUT_PULLUP);
int v = !digitalRead(rowCol);
if (v != keys[colIndex][rowIndex]) {
// This mess is for the rotary switch. Only send events for the position
// it's switching into, not the position it's leaving.
int bId = buttons[colIndex][rowIndex]->id();
if ((bId == 0 || bId == 1 || bId == 2 || bId == 5 || bId == 6 | bId == 7) && !v) {
// special case rotary switch, only send events when they go high
} else {
buttons[colIndex][rowIndex]->activate(v, output);
}
// This mess is for disabling output if both rotary encoders are pressed
// at the same time.
if (rowIndex == 0 && (colIndex == 3 || colIndex == 4) && buttons[3][0]->state() && buttons[4][0]->state()) {
// toggle output if both buttons 3 and 4 are pressed
digitalWrite(LED_PIN, !ledValue);
ledValue = !ledValue;
output.toggle();
}
keys[colIndex][rowIndex] = v;
}
pinMode(rowCol, INPUT);
}
// disable the column
pinMode(curCol, INPUT);
}
}
void loop() {
read_matrix();
delay(5);
}
// Rotary debounce code from https://www.best-microcontroller-projects.com/rotary-encoder.html
void fire_rotary1() {
if(read_rotary1()) {
if ( prevNextCode1==0x0b) {
e1Dn->activate(1, output);
}
if ( prevNextCode1==0x07) {
e1Up->activate(1, output);
}
}
}
// A vald CW or CCW move returns 1, invalid returns 0.
int8_t read_rotary1() {
prevNextCode1 <<= 2;
if (digitalRead(E1_DATA)) prevNextCode1 |= 0x02;
if (digitalRead(E1_CLK)) prevNextCode1 |= 0x01;
prevNextCode1 &= 0x0f;
// If valid then store as 16 bit data.
if (rot_enc_table[prevNextCode1] ) {
store1 <<= 4;
store1 |= prevNextCode1;
if ((store1&0xff)==0x2b) return -1;
if ((store1&0xff)==0x17) return 1;
}
return 0;
}
void fire_rotary2() {
if(read_rotary2()) {
if ( prevNextCode2==0x0b) {
e2Dn->activate(1, output);
}
if ( prevNextCode2==0x07) {
e2Up->activate(1, output);
}
}
}
// A vald CW or CCW move returns 1, invalid returns 0.
int8_t read_rotary2() {
prevNextCode2 <<= 2;
if (digitalRead(E2_DATA)) prevNextCode2 |= 0x02;
if (digitalRead(E2_CLK)) prevNextCode2 |= 0x01;
prevNextCode2 &= 0x0f;
// If valid then store as 16 bit data.
if (rot_enc_table[prevNextCode2] ) {
store2 <<= 4;
store2 |= prevNextCode2;
if ((store2&0xff)==0x2b) return -1;
if ((store2&0xff)==0x17) return 1;
}
return 0;
} | true |
f38d034e450ffac049148c4eb43eccf363ee55ac | C++ | jabelai/Neverland | /Cocos2dxLib/Classes/GameNetBean.h | GB18030 | 3,118 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __GAMENETBEAN_H__
#define __GAMENETBEAN_H__
#include "ccnet/net.h"
#include "ccbase/base.h"
#include "GameModel.h"
#define MSG_UI_CONNECTED 1 //֪ͨUIӳɹ
#define MSG_UI_DISCONNECTED 2 //֪ͨUIж
#define MSG_UI_CONNECTERROR 3 //֪ͨUIӴ
#define MSG_UI_CONNECTTIMEOUT 4 //֪ͨUIӳʱ
///csӿϢ
#define MSG_CS_LOGIN 1000 //½
#define MSG_CS_RUN 1001 //ܲ
#define MSG_CS_EXIT 1002 //뿪
///scӿϢ
#define MSG_SC_ERROR 5000 //Ϣ
#define MSG_SC_INITCLIENT 5001 //ʼͻ
#define MSG_SC_OTHERPLAYER_RUN 5002 //ܲ
#define MSG_SC_OTHERPLAYER_JOIN 5003 //Ҽ뷿
#define MSG_SC_OTHERPLAYER_EXIT 5004 //뿪
///
class CGameNetBean : public CNetBean, public CLooper
{
public:
DEFINE_SINGLE_FUNCTION(CGameNetBean);
public:
virtual ~CGameNetBean();
public:
///ɹ ʼʱ
virtual void onCreate();
///ӳɹʱ
virtual void onConnected();
///Ͽʱ
virtual void onDisconnected();
///Ӵʱ
virtual void onConnectError();
///ӳʱʱ
virtual void onConnectTimeout();
///Ϣʱ
virtual void onMessage(STREAM stream);
public:
//ÿ֡ص
virtual void loop() { this->drive(); }
//sc˷ͻ˵Ļصӿ
public:
//ϷеĴϢؽӿ
//[int:Ϣ] [int:]
void sc_error(STREAM stream);
//½ɹã֪ͨͻ˳ʼ
//[int:Ϣ] [int:ҵid] [str:ҵdz] [int:ҵijʼx] [int:ҵijʼy]
//[int:$countѴڵ]
//$count * {[int:id] [str:] [int:x] [int:y]}
void sc_initclient(STREAM stream);
//ܲ
//[int:Ϣ] [int:id] [int:x] [int:y]
void sc_otherplayer_run(STREAM stream);
//ҽ뷿
//[int:Ϣ] [int:id] [str:] [int:ҵx] [int:ҵy]
void sc_otherplayer_join(STREAM stream);
//뿪
//[int:Ϣ] [int:id]
void sc_otherplayer_exit(STREAM stream);
//csͻ˷˵Ľӿ
public:
//½ûûĬעᣬ½֮ͽ뷿
//[int:Ϣ] [str:Զ]
//أ[ok:sc_initclient] [no:sc_error]
void cs_login(const char* nikename);
//֪ܲͨ
//[int:Ϣ] [int:id] [int:x] [int:y]
void cs_run(int x, int y);
//뿪䣬֪ͨ
//[int:Ϣ] [int:id]
void cs_exit();
};
#endif //__GAMENETBEAN_H__ | true |
9cd5884ae32a2f34d6d74f902ab8a7a1f167e675 | C++ | trisuliswanto/AdRoiT | /06. Motor DC (Tanpa PID)/main.cpp | UTF-8 | 3,206 | 2.75 | 3 | [] | no_license | /***************************************************************
Project : ADROIT AVR Rev.3
Version : 1
Date : 5/29/2015
Author : Eko Henfri Binugroho
Company : ER2C
Code : Pengaturan kecepatan motor DC (motor roda) dengan PWM
*****************************************************************/
/*
Jika menggunakan Code::Blocks sebagai editor:
untuk optimasi supaya file hex hasil kompilasi menjadi kecil (fungsi yang tidak dipanggil tidak dimasukkan ke dalam
file hex), maka dilakukan pengaturan proses compile dan linker program sbb:
1. copy option berikut pada compiler setting (Menu Settings,Compiler, Compiler settings, Other options:)
-ffunction-sections
2. copy option berikut pada linker setting (Menu Settings,Compiler, Linker settings, Other linker options:)
-Wl,-gc-sections
*/
#include "myModule.h" // edit module yang akan digunakan pada file ini
#include "../AdRoiT_Files/mySystem.h"
int main(void)
{
SystemInit(); // inisialisasi sistem (wajib bagi semua project)
// detail dari modul yang diaktifkan pada setiap project bisa dilihat pada file "myModule.h"
lcd.Hapus();
lcd.TulisKanan (0, "Push Button : x ");
lcd.TulisKiri (1, "Atur Kecp. Motor");
buzzer.Nada1();
// pengaturan motor DC dapat diakses melalui obyek roda yang dideklarasikan pada file "myMotor.h"
// pengaturan kecepatan dengan PWM diakses dengan fungsi SpeedPWM(x,y)
// dimana x = data kecepatan motor kiri dan y = data kecepatan motor kanan
// masing-masing nilai x dan y mempunyai range antara -400 sampai dengan 400
// tanda positif menghasilkan putaran maju, sedangkan nilai negatif menghasilkan putaran mundur
// sedangkan nilai 0 (nol) membuat motor berhenti
while(1)
{ if(Tombol1) // jika push button 1 ditekan
{ roda.SpeedPWM(100,100); // kecepatan motor 1/4 dari kecepatan maksimal ke arah depan
lcd.GotoXY(14,0); lcd.Data('1');
lcd.Tulis(1, "Robot Maju 25%");
}
else if(Tombol2) // jika push button 2 ditekan
{ roda.SpeedPWM(400,400); // kecepatan motor maksimal ke arah depan
lcd.GotoXY(14,0); lcd.Data('2');
lcd.Tulis(1, "Robot Maju 100%");
}
else if(Tombol3) // jika push button 3 ditekan
{ roda.SpeedPWM(-100,-100); // kecepatan motor 1/4 dari kecepatan maksimal ke arah belakang
lcd.GotoXY(14,0); lcd.Data('3');
lcd.Tulis(1, "Robot Mundur 25%");
}
else if(Tombol4) // jika push button 4 ditekan
{ roda.SpeedPWM(-400,-400); // kecepatan motor maksimal ke arah belakang
lcd.GotoXY(14,0); lcd.Data('4');
lcd.Tulis(1, "Robot Mundur100%");
}
else // jika tidak ada push button yang ditekan
{ roda.SpeedPWM(0,0); // motor berhenti berputar dan dalam kondisi ngerem (brake)
lcd.GotoXY(15,0); lcd.Data('x');
lcd.Tulis(1, "Robot Stop ");
}
}
}
| true |
579dd509ad4060d0b20d010b3a414b240fd9e80a | C++ | 9thbit/Planet-Wars | /CaseBasedBot.cpp | UTF-8 | 1,315 | 3.03125 | 3 | [] | no_license | //
// CaseBasedBot.cpp
// planetwars_cpp1
//
// Created by Barry Hurley on 08/03/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#include "CaseBasedBot.h"
#include "GameState.h"
#include "Successor.h"
#include <vector>
#include <iostream>
CaseBasedBot::CaseBasedBot(){
enemyMoves = new Successors();
}
CaseBasedBot::~CaseBasedBot(){
/* FIXME
for(uint i=0;i<enemyMoves->size();i++){
delete enemyMoves->at(i);
}*/
delete enemyMoves;
}
Orders *CaseBasedBot::doTurn(GameState *gamestate, uint myPlayerID){
Orders *orders = new Orders();
return orders;
}
void CaseBasedBot::addEnemyMove(GameState *gamestate, Orders *orders){
// check if the gamestate is within the previously seen ones
compareToPreviousGameStates(gamestate);
/*Successor *s = new Successor();
s->gamestate = gamestate;
s->orders = orders;
enemyMoves->push_back(s);*/
}
void CaseBasedBot::compareToPreviousGameStates(GameState *gamestate){
Successor *s;
GameState *gs;
for(std::vector<Successor*>::iterator s_it = enemyMoves->begin();s_it!=enemyMoves->end();s_it++){
s = *s_it;
gs = s->gamestate;
std::cerr << "Comparing gamestates at " << gamestate << " and " << gs << std::endl;
double similarity = gamestate->compareTo(gs);
std::cerr << "Gamestate similarity: " << similarity << std::endl;
}
} | true |
06a06bdd19a0453299d5d612dda25e5c5a4c47ff | C++ | Moises788/Sistemas_Microcontrolados | /Exemplos/Assembly/PORTB_OUTPUT.ino | UTF-8 | 798 | 2.625 | 3 | [] | no_license | /*Sistemas microcontrolados
MCU: ATmega 328p F: 12 MHz
Autor: Alysson Lima
Pisca led
*/
//incluindo bibliotecas
#include <avr/io.h> //biblioteca para acesso aos registradores do ATmega
#include "util/delay.h" //biblioteca delay da ling C
//funcao principal do codigo
int main (void) {
//regiao do void setup
// PORTB - P7 até PB0
//DDRB - controla entradas e saidas
//configura o pino 15 do microcontolador( pin 9 do arduino) como saida
DDRB = 0x22; // PB1 e PB5 sao saidas digital 0b00100010 = 0x22
//criacao do void loop
while (1) {
PORTB = 0x22; //PB1 vai para nivel logico alto
_delay_ms(1000); //espara 1s
PORTB = 0x00; //PB1 vai para nivel logico LOW
_delay_ms(1000); //espara 1s
}// --- fim loop ---
}// ----fim main ----
| true |
ed6de09aef6cb9cb42a50b25723c8f2aceffaf12 | C++ | dwarfovich/TreeFlattenProxyModel | /tree_item.hpp | UTF-8 | 1,031 | 2.875 | 3 | [] | no_license | #ifndef TREE_ITEM_HPP
#define TREE_ITEM_HPP
#include "item_data.hpp"
#include <QVariant>
#include <QHash>
#include <memory>
#include <vector>
class TreeItem {
public:
using ItemUptr = std::unique_ptr<TreeItem>;
explicit TreeItem (int columns = 0, TreeItem* parent = nullptr);
TreeItem* parent ();
TreeItem* child (int index);
int childCount () const;
int columns () const;
int row () const;
void insertChild (int index, ItemUptr item);
void appendChild (ItemUptr item);
void removeChildren (int first, int count);
void insertColumns (int start, int count);
void removeColumns (int start, int count);
QVariant data (int column, int role = Qt::DisplayRole) const;
void setData (int column, int role, const QVariant& value);
private:
// methods
void setParent (TreeItem* parent);
// data
TreeItem* parent_;
std::vector<ItemUptr> children_;
std::vector<ItemData> data_;
};
#endif // TREE_ITEM_HPP
| true |
a0afc4b1061c9cbd5fb4b5707f65a3b963410759 | C++ | monman53/online_judge | /AtCoder/ARC/012/a.cpp | UTF-8 | 509 | 2.578125 | 3 | [] | no_license | // header {{{
#include <bits/stdc++.h>
using namespace std;
// {U}{INT,LONG,LLONG}_{MAX,MIN}
#define ALPHABET (26)
#define INF INT_MAX
#define MOD (1000000007LL)
using LL = long long;
// }}}
int main() {
std::ios::sync_with_stdio(false);
map<string, int> m;
m["Sunday"] = 0;
m["Monday"] = 5;
m["Tuesday"] = 4;
m["Wednesday"] = 3;
m["Thursday"] = 2;
m["Friday"] = 1;
m["Saturday"] = 0;
string s;cin >> s;
cout << m[s] << endl;
return 0;
}
| true |
c57bf739b525890872af2399cb47d60c2d48fd5e | C++ | Nitek-Singh/hacktoberfest2021 | /C++/Data Structure/Arrays.cpp | UTF-8 | 982 | 3.4375 | 3 | [
"MIT"
] | permissive | //Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
vector<Interval> Solution::insert(vector<Interval> &v, Interval i) {
vector<Interval> ans;
int n=v.size();
int start=i.start,end=i.end;
bool check=false;
for(int i=0; i<n; i++)
{
if(v[i].end<start) ans.push_back(v[i]);
else if(v[i].start>end)
{
if(!check) ans.push_back({start,end});
ans.push_back(v[i]);
check=true;
}
else
{
start=min(start,v[i].start);
end=max(end,v[i].end);
}
}
if(!check)
{
Interval temp;
temp.start=start;
temp.end=end;
ans.push_back(temp);
}
return ans;
}
| true |
7fe797235fc01a3ee18420a4f11cf9ffc2bec15b | C++ | Pooler22/TGK | /test/main.cpp | UTF-8 | 5,095 | 2.734375 | 3 | [] | no_license | #include <GL/freeglut.h>
#include <stdio.h>
#include <ctime>
#include "System.h"
float zoom;
System particleSystem;
// texture related globals
GLfloat texture[10];
GLuint LoadTextureRAW(const char* filename, int width, int height);
void FreeTexture(GLuint texturez);
void drawParticles(void)
{
int i;
for (i = 1; i < particleSystem.getNumOfParticles(); i++)
{
glPushMatrix();
// set color and fade value (alpha) of current particle
glColor4f(particleSystem.getR(i), particleSystem.getG(i), particleSystem.getB(i), particleSystem.getAlpha(i));
// move the current particle to its new position
glTranslatef(particleSystem.getXPos(i), particleSystem.getYPos(i), particleSystem.getZPos(i) + zoom);
// rotate the particle (this is proof of concept for when proper smoke texture is added)
glRotatef(particleSystem.getDirection(i) - 90, 0, 0, 1);
// scale the wurrent particle (only used for smoke)
glScalef(particleSystem.getScale(i), particleSystem.getScale(i), particleSystem.getScale(i));
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_DST_COLOR, GL_ZERO);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glBegin(GL_QUADS);
glTexCoord2d(0, 0);
glVertex3f(-1, -1, 0);
glTexCoord2d(1, 0);
glVertex3f(1, -1, 0);
glTexCoord2d(1, 1);
glVertex3f(1, 1, 0);
glTexCoord2d(0, 1);
glVertex3f(-1, 1, 0);
glEnd();
glBlendFunc(GL_ONE, GL_ONE);
glBindTexture(GL_TEXTURE_2D, texture[1]);
glBegin(GL_QUADS);
glTexCoord2d(0, 0);
glVertex3f(-1, -1, 0);
glTexCoord2d(1, 0);
glVertex3f(1, -1, 0);
glTexCoord2d(1, 1);
glVertex3f(1, 1, 0);
glTexCoord2d(0, 1);
glVertex3f(-1, 1, 0);
glEnd();
glEnable(GL_DEPTH_TEST);
glPopMatrix();
}
}
void display(void)
{
glClearDepth(1);
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0, 0, -10);
particleSystem.updateParticles();
drawParticles();
glutSwapBuffers();
}
void init(void)
{
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
zoom = -80.0f;
particleSystem.setSystemType(1);
particleSystem.createParticles();
texture[0] = LoadTextureRAW("particle_mask.raw", 256, 256); //load alpha for texture
texture[1] = LoadTextureRAW("particle.raw", 256, 256); //load texture
}
//Called when a key is pressed
void handleKeypress(unsigned char key, int x, int y)
{
switch (key)
{
case 49: //1 key: smoke
zoom = -80.0f;
particleSystem.setSystemType(1);
particleSystem.createParticles();
break;
case 50: //2 key: fountain high
zoom = -40.0f;
particleSystem.setSystemType(2);
particleSystem.createParticles();
break;
case 51: //3 key: fire
zoom = -40.0f;
particleSystem.setSystemType(3);
particleSystem.createParticles();
break;
case 52: //4 key: fire with smoke
zoom = -60.0f;
particleSystem.setSystemType(4);
particleSystem.createParticles();
break;
case 61: //+ key: change x pull for more wind to right
particleSystem.modifySystemPull(0.0005f, 0.0f, 0.0f);
break;
case 45: //- key: change x pull for wind wind to left
particleSystem.modifySystemPull(-0.0005f, 0.0f, 0.0f);
break;
case 91: //[ key: change y pull for more gravity
particleSystem.modifySystemPull(0.0f, 0.0005f, 0.0f);
break;
case 93: //] key; change y pull for less gravity
particleSystem.modifySystemPull(0.0f, -0.0005f, 0.0f);
break;
case 27: //Escape key
exit(0);
}
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv)
{
srand((unsigned int)time(0)); //Seed the random number generator using system time
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Particle System");
init();
glutDisplayFunc(display);
glutIdleFunc(display);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
// Functions to load RAW files
// I did not write the following functions.
// They are form the OpenGL tutorials at http://www.swiftless.com
GLuint LoadTextureRAW(const char* filename, int width, int height)
{
GLuint texture;
unsigned char* data;
FILE* file;
fopen_s(&file, filename, "rb");
if (file == nullptr) return 0;
data = (unsigned char *)malloc(width * height * 3);
fread(data, width * height * 3, 1, file);
fclose(file);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gluBuild2DMipmaps(GL_TEXTURE_2D, 3, width, height, GL_RGB, GL_UNSIGNED_BYTE, data);
free(data);
return texture;
}
void FreeTexture(GLuint texture)
{
glDeleteTextures(1, &texture);
}
| true |
33e1472152e797f68da701828a537f012b7dcd2a | C++ | geoo993/LearningCpp | /BeginnersTutorials/workspace/IfStatements/src/IfStatements.cpp | UTF-8 | 1,770 | 3.90625 | 4 | [] | no_license | //============================================================================
// Name : IfStatement.cpp
// Author : George Quentin
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// string password = "hello";// = operation is to assign a value but == operation is to check a value
//
// cout << "Enter Your Password>" << flush;
//
// string input;
// cin >> input;
//
// if (input == password) // here we are checking that input and password are the same, this if statement is called a condition
// {
// cout << "Correct Accepted, You've logged in: " << "'" << input << "'" << endl;
//
// }else{
//
// cout << "Access Denied (Incorrect Password) " << "'" << input << "'" << endl;
// }
// this is tab space \t
// this is next line \n
cout << "\n1.\tAdd New Record." << endl;
cout << "2.\tDelete Record." << endl;
cout << "3.\tView Record." << endl;
cout << "4.\tSearch Record." << endl;
cout << "5.\tQuit." << endl;
cout << "\nEnter Your Selection> " << flush;
int value;
cin >> value;
// if (value < 2){
// cout << "\n" << "Insufficient Privileges to use software " << endl;
// }else {
//
// cout << "\n" << "Sufficient Privileges " << endl;
// }
if (value == 1){
cout << "Adding new Record... " << endl;
}else if (value == 2){
cout << "Deleting Record... " << endl;
}else if (value == 3){
cout << "Viewing ... " << endl;
}else if (value == 4){
cout << "Searching... " << endl;
}else if (value == 5){
cout << "Application Option... " << endl;
}else{
cout << "Invalid Selection " << endl;
}
return 0;
}
| true |
9ad2d9d8104e95a239d49af4101a2ea57704ec45 | C++ | MichaelKirsch/SFML_2D_BLUEPRINT | /src/GUI/Widgets/SimpleText.cpp | UTF-8 | 1,533 | 2.59375 | 3 | [] | no_license |
#include "SimpleText.h"
gui::SimpleText::SimpleText(EssentialWindow &es) : Widget(es){
m_TextString = "undefined";
m_Style = m_Essential.m_GuiStyle;
m_Text.setFillColor(m_Style.textColor);
m_Text.setFont(m_Essential.m_GlobFont);
auto charsize = (m_Essential.m_Window.getSize().y/100)*m_Essential.m_GuiStyle.buttonHeight;
m_Text.setCharacterSize(charsize);
refactor();
}
void gui::SimpleText::setText(std::string text) {
m_TextString = text;
refactor();
}
void gui::SimpleText::draw() {
m_Essential.m_Window.draw(m_Text);
}
void gui::SimpleText::refactor() {
auto charsize = (m_Essential.m_Window.getSize().y/100)*m_Style.buttonHeight;
m_Text.setCharacterSize(charsize);
m_Text.setString(m_TextString);
m_Text.setFillColor(m_Style.textColor);
auto positionInPixels = sf::Vector2f(m_Position.x*(m_Essential.m_Window.getSize().x/100),m_Position.y*(m_Essential.m_Window.getSize().y/100));
if(isCentered)
{
auto getoutline = m_Text.getGlobalBounds();
positionInPixels = sf::Vector2f(positionInPixels.x-getoutline.width/2,positionInPixels.y-getoutline.height/2);
}
m_Text.setPosition(positionInPixels);
}
void gui::SimpleText::setPositionOfCenter(sf::Vector2u pos) {
m_Position = pos;
isCentered = true;
refactor();
}
void gui::SimpleText::setSize(int size) {
m_Style.buttonHeight = size;
refactor();
}
void gui::SimpleText::setTextColor(sf::Color colorToSet) {
m_Style.textColor = colorToSet;
refactor();
}
| true |
a9af791de3e406ceb534014e2755e8731024ba1c | C++ | Truelch/Projet-S6 | /src/AIStat.cpp | UTF-8 | 1,291 | 2.921875 | 3 | [
"BSD-3-Clause"
] | permissive | #include "AIStat.h"
#include "Unit.h"
AIStat::AIStat()
{
//
}
AIStat::AIStat(float scout, float attack, float defense, float capture, int front_rank, int priority)
{
set_scout(scout);
set_attack(attack);
set_defense(defense);
set_capture(capture);
set_front_rank(front_rank);
set_priority(priority);
}
// --- GET ---
float AIStat::get_scout()
{
return _scout;
}
float AIStat::get_attack()
{
return _attack;
}
float AIStat::get_defense()
{
return _defense;
}
float AIStat::get_capture()
{
return _capture;
}
int AIStat::get_front_rank()
{
return _front_rank;
}
int AIStat::get_priority()
{
return _priority;
}
AIStat::State AIStat::get_state()
{
return _state;
}
Unit * AIStat::get_unit()
{
return _unit;
}
// --- SET ---
void AIStat::set_scout(float scout)
{
_scout = scout;
}
void AIStat::set_attack(float attack)
{
_attack = attack;
}
void AIStat::set_defense(float defense)
{
_defense = defense;
}
void AIStat::set_capture(float capture)
{
_capture = capture;
}
void AIStat::set_front_rank(int front_rank)
{
_front_rank = front_rank;
}
void AIStat::set_priority(int priority)
{
_priority = priority;
}
void AIStat::set_state(AIStat::State state)
{
_state = state;
}
// --- METHODES ---
void AIStat::retreat()
{
//_unit->set_destination(x,y);
}
| true |
8119763560bf6da755f36535b9abd0964df2c2f8 | C++ | Heutlett/Tarea1 | /TAREAQT/Servidor/Vertice.h | UTF-8 | 690 | 2.96875 | 3 | [] | no_license | /**
* @file Vertice.h
* @date 3/2/2020
* @author Carlos Adrian Araya Ramirez 2018319701
* @title Clase vertice
* @brief Estructura necesaria para la funcionalidad del grafo
*/
#ifndef VERTICE_H
#define VERTICE_H
#include <vector>
#include <iostream>
using namespace std;
struct Vertice {
public:
/**
* @brief Constructor de vertices
*
* @param Numero que tendra el vertice como nombre
*/
Vertice(int);
int numero;
int cantAristas = 0;
vector<int> aristas;
/**
* @brief Devuelve un string con las aristas del vertice
* @return String con aristas del vertice
*/
string imprimirAristas();
private:
};
#endif /* VERTICE_H */
| true |
8b0b8c879ff4a79b5bde0087523220d1025e9e17 | C++ | blacknax/sbtimer | /src/sbtimer/DurationTarget.h | UTF-8 | 1,434 | 3.203125 | 3 | [] | no_license | #ifndef DurationTarget_h
#define DurationTarget_h
#include <Arduino.h>
class DurationTarget {
private:
byte hours = 0;
byte minutes = 15;
byte seconds = 0;
char durationChars[32];
public:
void hoursUp() {
hours++;
if (hours > 99) {
hours = 0;
}
}
void hoursDown() {
hours--;
if (hours > 99) {
hours = 99;
}
}
void minutesUp() {
minutes++;
if (minutes > 59) {
minutes = 0;
}
}
void minutesDown() {
minutes--;
if (minutes > 99) {
minutes = 59;
}
}
void secondsUp() {
seconds++;
if (seconds > 59) {
seconds = 0;
}
}
void secondsDown() {
seconds--;
if (seconds > 99) {
seconds = 59;
}
}
unsigned long getDurationMs() {
unsigned long ms = hours * 3600ul;
ms += minutes * 60ul;
ms += seconds;
ms = ms * 1000ul;
return ms;
}
char* getDurationChars() {
sprintf(this->durationChars, "%02u:%02u:%02u", hours, minutes, seconds);
return durationChars;
}
};
#endif
| true |
c48c5acd63f35481a93a67e891b8a12b63dfdd2c | C++ | lkstc112233/FlighterSerrisBertament | /FlighterSerrisBertament/FlighterSerrisBertament/Application.h | UTF-8 | 1,344 | 2.59375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "DeviceIndependentResources.h"
#include "DeviceResources.h"
#include "MouseDots.h"
#include "Sprite.h"
class Application {
private:
HWND m_hwnd;
std::unique_ptr<DeviceIndependentResources> deviceIndependentResources;
std::unique_ptr<DeviceResources> deviceResources;
SpriteManager spriteManager;
private:
int fps;
int fpsSecondRecord;
int fpsFrameCount;
std::shared_ptr<Mouse> mouse;
MouseDotsManager mouseDots;
public:
Application();
~Application();
// Register the window class and call methods for instantiating drawing
// resources
HRESULT Initialize();
// Process and dispatch messages
void RunMessageLoop();
private:
// Initialize device-independent resources.
HRESULT CreateDeviceIndependentResources();
// Initialize device-dependent resources.
HRESULT CreateDeviceResources();
// Release device-dependent resource.
void DiscardDeviceResources();
// Draw content.
HRESULT OnRender();
// Resize the render target.
void OnResize(UINT width, UINT height);
// updates required status.
void update();
// Records the mouse position
void mouseMove(int x, int y) { mouse->mouseTo(x, y); }
// The windows procedure.
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam);
};
| true |
d629378003735440c4b0667a18de17509fcba60b | C++ | TheChosenHobbit/programmiersprachen-aufgabenblatt-2 | /source/circle.cpp | UTF-8 | 2,938 | 3.03125 | 3 | [
"MIT"
] | permissive | #include "circle.hpp"
#include "window.hpp"
#include "vec2.hpp"
#include "mat2.hpp"
//#include "color.hpp"
//#include "point2d.hpp"
#include <cmath>
#include <math.h>
Circle::Circle():
center_{1,1},
radius_{1.0},
color_{0,0,0}{}
Circle::Circle(Point2D const& ctr, float r, Color const& clr):
center_{ctr},
radius_{r},
color_{clr}{}
Color Circle::getColor() const
{
return color_;
}
Point2D Circle::getPoint2D() const
{
return center_;
}
float Circle::getRadius() const
{
return radius_;
}
void Circle::setColor (Color const& clr)
{
color_ = clr;
}
void Circle::setPoint2D (Point2D const& ctr)
{
center_ = ctr;
}
void Circle::setRadius(float r)
{
radius_ = r;
}
float Circle::circumference() const
{
return 2*M_PI*radius_;
}
void Circle::draw(Window& win)
{
for (int i = 1; i<(360+1); ++i)
{
Vec2 start((make_rotation_mat2(2*M_PI*i/360)) * Vec2(getRadius(),0) + convert(getPoint2D()));
Vec2 end((make_rotation_mat2(2*M_PI*(i+1)/360)) * Vec2(getRadius(),0) + convert(getPoint2D()));
win.draw_line(start.x, start.y, end.x, end.y, color_.r, color_.g, color_.b);
}
/*
for(float i = 0.0; i<= 2* M_PI; i += 0.001)
{
win.draw_point(radius_*cos(i)+center_.x,
radius_*sin(i)+center_.y,
color_.r, color_.g, color_.b);
}
*/
}
void Circle::draw(Window& win, Color clr)
{
for (int i = 1; i<(360+1); ++i)
{
Vec2 start((make_rotation_mat2(2*M_PI*i/360)) * Vec2(getRadius(),0) + convert(getPoint2D()));
Vec2 end((make_rotation_mat2(2*M_PI*(i+1)/360)) * Vec2(getRadius(),0) + convert(getPoint2D()));
win.draw_line(start.x, start.y, end.x, end.y, clr.r, clr.g, clr.b);
}
/*
for(float i = 0.0; i<= 2* M_PI; i += 0.001)
{
win.draw_point(radius_*cos(i)+center_.x,
radius_*sin(i)+center_.y,
clr.r, clr.g, clr.b);
}
*/
}
void Circle::drawClock(Window& win)
{
for (int i = 1; i<(12+1); ++i)
{
Vec2 start((make_rotation_mat2(2*M_PI*i/12)) * Vec2(getRadius(),0) + convert(getPoint2D()));
Vec2 end((make_rotation_mat2(2*M_PI*(i)/12)) * Vec2(getRadius()-0.05,0) + convert(getPoint2D()));
win.draw_line(start.x, start.y, end.x, end.y, color_.r, color_.g, color_.b);
/*win.draw_point(radius_*cos(i)+center_.x,
radius_*sin(i)+center_.y,
color_.r, color_.g, color_.b);*/
}
for (int i = 1; i<(60+1); ++i)
{
Vec2 start((make_rotation_mat2(2*M_PI*i/60)) * Vec2(getRadius(),0) + convert(getPoint2D()));
Vec2 end((make_rotation_mat2(2*M_PI*(i)/60)) * Vec2(getRadius()-0.01,0) + convert(getPoint2D()));
win.draw_line(start.x, start.y, end.x, end.y, color_.r, color_.g, color_.b);
}
}
bool Circle::is_inside(Point2D point)
{
if(sqrt( (point.x-center_.x)*(point.x-center_.x) + (point.y-center_.y)*(point.y-center_.y) ) < radius_ )
{
return true;
}
else return false;
}
Vec2 Circle::convert(Point2D point)
{
Vec2 v;
v.x = point.x;
v.y = point.y;
return v;
} | true |
5a35631ac7fee2273139a87101e2d7ea123f76a9 | C++ | brinkqiang2cpp/cpp-validator | /include/dracosha/validator/utils/to_string.hpp | UTF-8 | 3,595 | 2.765625 | 3 | [
"BSL-1.0"
] | permissive | /**
@copyright Evgeny Sidorov 2020
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
/****************************************************************************/
/** @file validator/utils/to_string.hpp
*
* Defines helper for strings conversion.
*
*/
/****************************************************************************/
#ifndef DRACOSHA_VALIDATOR_TO_STRING_HPP
#define DRACOSHA_VALIDATOR_TO_STRING_HPP
#include <string>
#include <dracosha/validator/config.hpp>
#include <dracosha/validator/property.hpp>
#include <dracosha/validator/aggregation/wrap_it.hpp>
#include <dracosha/validator/aggregation/wrap_index.hpp>
#include <dracosha/validator/utils/unwrap_object.hpp>
DRACOSHA_VALIDATOR_NAMESPACE_BEGIN
//-------------------------------------------------------------
/**
* @brief Convert to <?????> token if no other conversion is possible.
*/
template <typename T, typename =hana::when<true>>
struct to_string_impl
{
template <typename T1>
std::string operator () (T1&&) const
{
return std::string("<\?\?\?\?\?>");
}
};
/**
* @brief Convert to string if string is constructible of argument.
*/
template <typename T>
struct to_string_impl<T,hana::when<
std::is_constructible<std::string,T>::value
&&
!hana::is_a<property_tag,T>
>>
{
template <typename T1>
std::string operator () (T1&& id) const
{
return std::string(std::forward<T1>(id));
}
};
/**
* @brief Convert to string if argument is a property.
*/
template <typename T>
struct to_string_impl<T,hana::when<hana::is_a<property_tag,T>>>
{
std::string operator () (const T& v) const
{
return std::string(v.name());
}
};
struct tree_tag;
/**
* @brief Convert to string if argument is an iterator.
*/
template <typename T>
struct to_string_impl<T,hana::when<
hana::is_a<wrap_iterator_tag,T>
||
hana::is_a<wrap_index_tag,T>
||
hana::is_a<tree_tag,T>
>>
{
std::string operator () (const T& id) const
{
return std::string(id.name());
}
};
/**
* @brief Check if sdt::to_string() can be callable with the given type.
*/
template <typename T, typename=void>
struct can_to_string
{
constexpr static const bool value=false;
};
/**
* @brief Check if std::to_string() can be callable with the given type.
*/
template <typename T>
struct can_to_string<T,
decltype((void)std::to_string(std::declval<T>()))>
{
constexpr static const bool value=true;
};
/**
* @brief Convert to string if string can be constructible using sdt::to_string().
*/
template <typename T>
struct to_string_impl<T,hana::when<
can_to_string<T>::value
&&
!hana::is_a<wrap_index_tag,T>
>>
{
std::string operator () (const T& id) const
{
return std::to_string(id);
}
};
/**
* @brief Template instance for converting variable to string.
*/
template <typename T>
constexpr to_string_impl<T> to_string_inst{};
/**
* @brief Convert argument to string.
* @param v Argument
* @return String
*/
struct to_string_t
{
template <typename T>
std::string operator () (const T& v) const
{
return to_string_inst<std::decay_t<decltype(unwrap_object(v))>>(unwrap_object(v));
}
};
constexpr to_string_t to_string{};
//-------------------------------------------------------------
DRACOSHA_VALIDATOR_NAMESPACE_END
#endif // DRACOSHA_VALIDATOR_TO_STRING_HPP
| true |
4553a030f9344d30a565a7caf311713bce7f96d5 | C++ | Interactics/cpp-primer-plus | /ch04/ch4-10/ch4-10.cpp | UTF-8 | 418 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <array> //array 사용을 위한 준비
using namespace std;
int main(){
array<float, 3> runResult;
cout << "첫번째 결과 : ";
cin >> runResult[0];
cout << "두번째 결과 : ";
cin >> runResult[1];
cout << "세번째 결과 : ";
cin >> runResult[2];
cout << "평균값 : " << (runResult[0] + runResult[1] + runResult[2])/3 << endl;
}
| true |
11c70c47e3645c2072c100e5ce830edd232220f1 | C++ | shalei120/CPPGM_PA3 | /300/divide.cpp | UTF-8 | 1,075 | 2.640625 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
string long2str(int n, bool issigned, int maxwidth = -1){
string res = "";
if(!issigned){
for(int a=n;a;a/=10){
res += char(a % 10 + '0');
}
reverse(res.begin(),res.end());
if(res == "") res = "0";
res += 'u';
}else{
if(n >= 0){
for(int a=n;a;a/=10){
res += char(a % 10 + '0');
}
reverse(res.begin(),res.end());
}else{
int n1 = ~n+1;
for(int a=n1;a;a/=10){
res += char(a % 10 + '0');
}
res += '-';
reverse(res.begin(),res.end());
}
if(res == "") res = "0";
}
if(maxwidth > 0){
while(res.length() < (unsigned int)maxwidth) res += ' ';
}
return res;
}
int main(){
ifstream cin("300-triple.t");
int c=0,co=0;
string s;
string name = "300-triple_"+long2str(c,1)+".t";
ofstream out(name.c_str());
while(getline(cin,s)){
out<<s<<endl;
co++;
if(co % 6000 == 0){
c++;
name = "300-triple_"+long2str(c,1)+".t";
out.close();
out.open(name.c_str());
}
}
}
| true |
33cec998291c2dc827819f34f3473365481b280d | C++ | white1234567890/MyLibrary | /MyLibrary/SceneManagerClass.cpp | SHIFT_JIS | 915 | 2.5625 | 3 | [] | no_license | #include "SceneManagerClass.h"
//////////////////////////////////////////////////////////////////////////////
//ÓIϐ
//////////////////////////////////////////////////////////////////////////////
BaseSceneClass *SceneManagerClass::m_Scene;
SceneManagerClass::SceneManagerClass(void)
{
}
SceneManagerClass::~SceneManagerClass(void)
{
}
//////////////////////////////////////////////////////////////////////////////
//public
//////////////////////////////////////////////////////////////////////////////
void SceneManagerClass::ChangeScene(_SCENE scene)
{
static SceneTitleClass SceneTitle;
static SceneMainClass SceneMain;
switch (scene)
{
case SceneManagerClass::E_GAME_TITLE:
m_Scene = &SceneTitle;
break;
case SceneManagerClass::E_GAME_MAIN:
m_Scene = &SceneMain;
break;
}
}
void SceneManagerClass::Render()
{
m_Scene->Render();
} | true |
7750cbe99d6190799bb6cf9e9206475f4db81cc3 | C++ | pranav245/CP2_CIPHERSCHOOLS | /189.RotateArray.cpp | UTF-8 | 358 | 3 | 3 | [] | no_license | class Solution {
public:
void reverse(vector<int>& nums,int start,int end)
{
for(int i=start,j=end-1;i<j;i++,j--)
swap(nums[i],nums[j]);
}
void rotate(vector<int>& nums, int k) {
int n=nums.size();
k=k%n;
reverse(nums,0,n);
reverse(nums,0,k);
reverse(nums,k,n);
}
};
| true |
d1f1dde3cd34fa068d87196890e3a954c19a30fb | C++ | skarrman/AdventOfCode | /2018/05/main.cpp | UTF-8 | 1,360 | 3.21875 | 3 | [] | no_license | #include "../utils/TxtReader.h"
#include <iostream>
#include <string>
using namespace std;
inline string removePolymer(string row) {
string::size_type first = 0;
char last = row[first];
string remaningRow = "";
remaningRow.push_back(last);
for (string::size_type i = 1; i < row.size(); i++) {
if (last == row[i] - 32 || last == row[i] + 32) {
remaningRow.pop_back();
// char lastLast = last;
last = remaningRow[remaningRow.size() - 1];
// cout << lastLast << row[i] << last << endl;
} else {
remaningRow.push_back(row[i]);
last = row[i];
}
}
return remaningRow;
}
inline void secondTask(string row) {
string letters = "abcdefghijklmnopqrstuvwxyz";
string::size_type min = 0xFFFFFFFF;
for (string::size_type l = 0; l < letters.size(); l++) {
string removedRow = "";
for (string::size_type i = 0; i < row.size(); i++) {
if (row[i] != letters[l] && row[i] != letters[l] - 32)
removedRow.push_back(row[i]);
}
removedRow = removePolymer(removedRow);
string::size_type length = removedRow.size();
if (length < min)
min = length;
}
cout << min << endl;
}
int main() {
TxtReader reader;
string row = (reader.getStringFromFile("05/input.txt"))[0];
string newRow = removePolymer(row);
cout << newRow.length() << endl;
secondTask(row);
}
| true |
bb296047f0dd1d480d192f8aef9d50e4efde41cc | C++ | jguyet/Bomberman | /network/srcs/messages/EndOfGameMessage.cpp | UTF-8 | 600 | 2.546875 | 3 | [] | no_license | #include "messages/EndOfGameMessage.hpp"
#include "All.hpp"
#include "IMessage.hpp"
EndOfGameMessage::EndOfGameMessage (bool is_winner) : IMessage(EndOfGameMessage::ID, sizeof(IMessage) + sizeof(EndOfGameMessage))
{
this->is_winner = is_winner;
return ;
}
EndOfGameMessage::EndOfGameMessage ( EndOfGameMessage const & src )
{
*this = src;
}
EndOfGameMessage & EndOfGameMessage::operator=( EndOfGameMessage const & rhs )
{
return (*this);
}
EndOfGameMessage::~EndOfGameMessage ()
{
return ;
}
std::ostream & operator<<(std::ostream & o, EndOfGameMessage const & i)
{
return (o);
}
| true |
de53248d9466fb0337503202a751d40f2c1a5454 | C++ | MPlemmons/Trio | /main.cpp | UTF-8 | 834 | 4.1875 | 4 | [] | no_license | #include <iostream>
using std::cout;
using std::cin;
using std::endl;
//function initializations
void sortDescending(int,int,int);
void swap(int&,int&);
int main()
{
//initialize variables
int numA, numB, numC;
//ask for user input
cout<<"Enter any three numbers: ";
cin>>numA>>numB>>numC;
//sort the 3 numbers in descending order
sortDescending(numA, numB, numC);
return 0;
}
void sortDescending(int first, int second, int third)
{
if( first < third )
{
swap(first,third);
}
if( first < second )
{
swap(first,second);
}
if( second < third )
{
swap(second,third);
}
//print out descending
cout<<"From greatest to least, they are: ";
cout<<first<<","<<second<<","<<third<<endl;
}
void swap(int &first, int &second)
{
int temp = first;
first = second;
second = temp;
}
| true |
0b8ba2ac98063a1451f8acb7f89ceafcb9e9c40a | C++ | ngthvan1612/OJCore | /TestModule/HK1/Users/20133030/BAI4.CPP | UTF-8 | 627 | 2.8125 | 3 | [] | no_license | #include<stdio.h>
void inp(int &m,int &n, int a[][100])
{
scanf("%d%d",&m,&n);
for (int i=0; i<m;i++)
for (int j=0; j<n;j++)
scanf("%d",&a[i][j]);
}
int checknt(int x)
{
int tmp=0;
for(int i=1;i<=x;i++)
{
if (x%i == 0) tmp=tmp+1;
}
printf("(%d)",tmp);
return tmp;
}
int check(int m, int n, int a[][100])
{
int tmp=0;int max=10000,x;
for (int i=0; i<m;i++){
for (int j=0; j<n;j++)
{
x=checknt(a[i][j]);
if (x==2) tmp=tmp+1;
}
if (max>tmp) max=tmp;
tmp=0;
}
return tmp;
}
void outp(int c)
{
printf("%d",c);
}
void main()
{
int m,n,a[100][100];
inp(m,n,a);
int c=check(m,n,a);
outp(c);
} | true |
9ac8665a522e91e0176075d514fdb8708aaba16e | C++ | tomfunkhouser/gaps | /pkgs/GSV/GSVImage.cpp | UTF-8 | 15,888 | 2.625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | // Source file for GSV image class
////////////////////////////////////////////////////////////////////////
// Include files
////////////////////////////////////////////////////////////////////////
#include "GSV.h"
////////////////////////////////////////////////////////////////////////
// Namespace
////////////////////////////////////////////////////////////////////////
namespace gaps {
////////////////////////////////////////////////////////////////////////
// Constructor/destructor functions
////////////////////////////////////////////////////////////////////////
GSVImage::
GSVImage(const char *name)
: tapestry(NULL),
tapestry_index(-1),
panorama(NULL),
panorama_index(-1),
pose0(0,0,0,0,0,0,0),
pose1(0,0,0,0,0,0,0),
timestamp0(-1),
timestamp1(-1),
name((name) ? RNStrdup(name) : NULL),
data(NULL)
{
}
GSVImage::
~GSVImage(void)
{
// Remove image from tapestry
if (tapestry) tapestry->RemoveImage(this);
// Remove image from panorama
if (panorama) panorama->RemoveImage(this);
// Delete name
if (name) free(name);
}
////////////////////////////////////////////////////////////////////////
// Access functions
////////////////////////////////////////////////////////////////////////
GSVScene *GSVImage::
Scene(void) const
{
// Return scene
if (!tapestry) return NULL;
return tapestry->Scene();
}
GSVRun *GSVImage::
Run(void) const
{
// Return run
if (!tapestry) return NULL;
return tapestry->Run();
}
GSVCamera *GSVImage::
Camera(void) const
{
// Return camera associated with image
if (!tapestry) return NULL;
return tapestry->Camera();
}
GSVSegment *GSVImage::
Segment(void) const
{
// Return segment
if (!tapestry) return NULL;
return tapestry->Segment();
}
int GSVImage::
SceneIndex(void) const
{
// Get convenient variables
GSVRun *run = Run();
if (!run) return -1;
GSVScene *scene = run->Scene();
if (!scene) return -1;
// Compute scene index
int scene_index = RunIndex();
for (int ir = 0; ir < run->SceneIndex(); ir++) {
GSVRun *r = scene->Run(ir);
scene_index += r->NImages();
}
// Return scene index
return scene_index;
}
int GSVImage::
RunIndex(void) const
{
// Get convenient variables
GSVSegment *segment = Segment();
if (!segment) return -1;
GSVRun *run = segment->Run();
if (!run) return -1;
// Compute run index
int run_index = SegmentIndex();
for (int i = 0; i < segment->RunIndex(); i++) {
GSVSegment *s = run->Segment(i);
run_index += s->NImages();
}
// Return runindex
return run_index;
}
int GSVImage::
SegmentIndex(void) const
{
// Get convenient variables
GSVSegment *segment = Segment();
if (!segment) return -1;
// Compute segment index
int segment_index = TapestryIndex();
for (int i = 0; i < tapestry->SegmentIndex(); i++) {
GSVTapestry *t = segment->Tapestry(i);
segment_index += t->NImages();
}
// Return segment index
return segment_index;
}
////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////
RNAngle GSVImage::
XFov(void) const
{
// Return field of view in horizontal direction
GSVCamera *camera = Camera();
if (!camera) return 0;
return camera->XFov();
}
RNAngle GSVImage::
YFov(void) const
{
// Return field of view in vertical direction
GSVCamera *camera = Camera();
if (!camera) return 0;
return camera->YFov();
}
int GSVImage::
Width(void) const
{
// Return width of images taken with this image
GSVCamera *camera = Camera();
if (!camera) return 0;
return camera->ImageWidth();
}
int GSVImage::
Height(void) const
{
// Return height of images taken with this image
GSVCamera *camera = Camera();
if (!camera) return 0;
return camera->ImageHeight();
}
GSVPose GSVImage::
Pose(int column_index) const
{
// Return pose estimate for given column
int ncolumns = Width();
if (ncolumns <= 0) return GSVPose(0,0,0,0,0,0,0);
if (column_index < 0) column_index = ncolumns/2;
RNScalar t = (RNScalar) column_index / (RNScalar) (ncolumns-1);
R3Point viewpoint = (1-t)*pose0.Viewpoint() + t*pose1.Viewpoint();
R3Quaternion orientation = R3QuaternionSlerp(pose0.Orientation(), pose1.Orientation(), t);
return GSVPose(viewpoint, orientation);
}
RNScalar GSVImage::
Timestamp(int column_index) const
{
// Return timestamp estimate for given column
int ncolumns = Width();
if (ncolumns <= 0) return -1;
if (column_index < 0) column_index = ncolumns/2;
RNScalar t = (RNScalar) column_index / (RNScalar) (ncolumns-1);
return (1-t)*timestamp0 + t*timestamp1;
}
R2Image *GSVImage::
DistortedImage(void) const
{
// Get convenient variables
int image_index = PanoramaIndex();
GSVPanorama *panorama = Panorama();
if (!panorama) return NULL;
int panorama_index = panorama->RunIndex();
GSVSegment *segment = panorama->Segment();
if (!segment) return NULL;
int segment_index = segment->RunIndex();
GSVRun *run = segment->Run();
if (!run) return NULL;
GSVScene *scene = run->Scene();
if (!scene) return NULL;
char run_name[1024];
if (run->Name()) sprintf(run_name, "%s", run->Name());
else sprintf(run_name, "Run%d", run->SceneIndex());
const char *raw_data_directory = scene->RawDataDirectoryName();
if (!raw_data_directory) return NULL;
// Construct distorted image name
char distorted_image_name[4096];
sprintf(distorted_image_name, "%s/%s/segment_%02d/unstitched_%06d_%02d.jpg",
raw_data_directory, run_name, segment_index, panorama_index, image_index);
// Allocate distorted image
R2Image *distorted_image = new R2Image();
if (!distorted_image) {
RNFail("Unable to allocate image for %s\n", distorted_image_name);
return NULL;
}
// Read distorted image
if (!distorted_image->Read(distorted_image_name)) {
RNFail("Unable to read distorted image %s\n", distorted_image_name);
delete distorted_image;
return NULL;
}
// Return distorted image
return distorted_image;
}
R2Image *GSVImage::
UndistortedImage(void) const
{
// Get convenient variables
int image_index = PanoramaIndex();
GSVPanorama *panorama = Panorama();
if (!panorama) return NULL;
int panorama_index = panorama->RunIndex();
GSVSegment *segment = panorama->Segment();
if (!segment) return NULL;
int segment_index = segment->RunIndex();
GSVRun *run = segment->Run();
if (!run) return NULL;
char run_name[1024];
if (run->Name()) sprintf(run_name, "%s", run->Name());
else sprintf(run_name, "Run%d", run->SceneIndex());
GSVScene *scene = run->Scene();
if (!scene) return NULL;
GSVCamera *camera = Camera();
if (!camera) return NULL;
R2Image *undistorted_image = NULL;
// Construct undistorted image name
if (scene->CacheDataDirectoryName()) {
// Get cached undistorted image name
char undistorted_image_name[4096];
sprintf(undistorted_image_name, "%s/undistorted_images/%s/%02d_%06d_%02d_UndistortedImage.jpg",
scene->CacheDataDirectoryName(), run_name, segment_index, panorama_index, image_index);
// Check if undistorted image file exists
if (RNFileExists(undistorted_image_name)) {
// Allocate undistorted image
undistorted_image = new R2Image();
if (!undistorted_image) {
RNFail("Unable to allocate image for %s\n", undistorted_image_name);
return NULL;
}
// Read undistorted image
if (!undistorted_image->Read(undistorted_image_name)) {
RNFail("Unable to read undistorted image %s\n", undistorted_image_name);
delete undistorted_image;
return NULL;
}
}
}
// If did not read from cache ...
if (!undistorted_image) {
// Get distorted image
R2Image *distorted_image = DistortedImage();
if (!distorted_image) return NULL;
// Allocate undistorted image with same resolution
undistorted_image = new R2Image(distorted_image->Width(), distorted_image->Height());
if (!undistorted_image) {
RNFail("Unable to allocate undistorted image\n");
return NULL;
}
// Undistort image
if (!camera->UndistortImage(*distorted_image, *undistorted_image)) {
RNFail("Unable to undistort image\n");
delete undistorted_image;
return NULL;
}
// Write undistorted image
if (scene->CacheDataDirectoryName()) {
if (scene->CreateCacheDataDirectory("undistorted_images", run)) {
char undistorted_image_name[4096];
sprintf(undistorted_image_name, "%s/undistorted_images/%s/%02d_%06d_%02d_UndistortedImage.jpg",
scene->CacheDataDirectoryName(), run_name, segment_index, panorama_index, image_index);
if (!undistorted_image->Write(undistorted_image_name)) {
RNFail("Unable to write undistorted image for %s\n", undistorted_image_name);
}
}
}
// Delete distorted image
delete distorted_image;
}
// Return undistorted image
return undistorted_image;
}
////////////////////////////////////////////////////////////////////////
// Manipulation functions
////////////////////////////////////////////////////////////////////////
void GSVImage::
SetName(const char *name)
{
// Delete previous name
if (this->name) free(this->name);
// Set new name
if (name) this->name = strdup(name);
else this->name = NULL;
}
void GSVImage::
SetPose(const GSVPose& pose0, const GSVPose& pose1)
{
// Set pose parameters
this->pose0 = pose0;
this->pose1 = pose1;
// Invalidate bounding boxes
if (tapestry) tapestry->InvalidateBBox();
}
void GSVImage::
SetTimestamp(RNScalar timestamp0, RNScalar timestamp1)
{
// Set timestamp
this->timestamp0 = timestamp0;
this->timestamp1 = timestamp1;
}
////////////////////////////////////////////////////////////////////////
// Mapping functions
////////////////////////////////////////////////////////////////////////
R2Point GSVImage::
DistortedPosition(const R2Point& undistorted_image_position) const
{
// Return the position after distortion by the camera lens
GSVCamera *camera = Camera();
if (camera) return camera->DistortedPosition(undistorted_image_position);
else return undistorted_image_position;
}
R2Point GSVImage::
UndistortedPosition(const R2Point& distorted_image_position) const
{
// Return the position after the inverse of distortion by the camera lens
GSVCamera *camera = Camera();
if (camera) return camera->UndistortedPosition(distorted_image_position);
else return distorted_image_position;
}
R2Point GSVImage::
UndistortedPosition(const R3Point& world_position, int column_index) const
{
// Get camera info
GSVCamera *camera = Camera();
if (!camera) return 0;
RNCoord xcenter = camera->XCenter();
RNCoord ycenter = camera->YCenter();
RNAngle xfocal = camera->XFocal();
RNAngle yfocal = camera->YFocal();
// Transform world point into column's camera coordinate system
const GSVPose& column_pose = Pose(column_index);
R3CoordSystem cs(column_pose.Viewpoint(), R3Triad(column_pose.Towards(), column_pose.Up()));
R3Point camera_position = cs.InverseMatrix() * world_position;
if (RNIsPositiveOrZero(camera_position.Z())) return R2Point(-1,-1);
// Compute coordinates of projection
RNCoord x = xcenter + camera_position.X() * xfocal / -(camera_position.Z());
RNCoord y = ycenter + camera_position.Y() * yfocal / -(camera_position.Z());
// Fill in point projected onto image
return R2Point(x, y);
}
R2Point GSVImage::
UndistortedPosition(const R3Point& world_position) const
{
// Get camera info
GSVCamera *camera = Camera();
if (!camera) return 0;
RNCoord xcenter = camera->XCenter();
RNCoord ycenter = camera->YCenter();
RNAngle xfocal = camera->XFocal();
RNAngle yfocal = camera->YFocal();
RNCoord x = RN_UNKNOWN;
RNCoord y = RN_UNKNOWN;
R3Point camera_position;
// Search for x coordinate (there is a different camera pose for every column)
int column_index = Width() / 2;
int last_column_index = column_index;
for (int i = 0; i < Width()/2; i++) {
// Transform world point into column's camera coordinate system
const GSVPose& column_pose = Pose(column_index);
R3CoordSystem cs(column_pose.Viewpoint(), R3Triad(column_pose.Towards(), column_pose.Up()));
camera_position = cs.InverseMatrix() * world_position;
if (RNIsPositiveOrZero(camera_position.Z())) return R2Point(-1,-1);
// Compute coordinates of projection
x = xcenter + camera_position.X() * xfocal / -(camera_position.Z());
y = ycenter + camera_position.Y() * yfocal / -(camera_position.Z());
// Get/check column index
R2Point distorted_position = DistortedPosition(R2Point(x,y));
column_index = (int) (distorted_position.X() + 0.5);
if (column_index < 0) column_index = 0;
if (column_index >= Width()-1) column_index = Width()-1;
if (column_index == last_column_index) break;
last_column_index = column_index;
}
// Fill in point projected onto image
return R2Point(x, y);
}
R2Point GSVImage::
DistortedPosition(const R3Point& world_position) const
{
// Return position of 3D point in distorted image
R2Point undistorted_position = UndistortedPosition(world_position);
if (undistorted_position == R2Point(-1,-1)) return undistorted_position;
return DistortedPosition(undistorted_position);
}
R3Ray GSVImage::
RayThroughUndistortedPosition(const R2Point& undistorted_image_position) const
{
// Check camera
if (!Camera()) return R3null_ray;
// Compute distorted image position
R2Point distorted_image_position = DistortedPosition(undistorted_image_position);
if (distorted_image_position == R2Point(-1,-1)) return R3null_ray;
// Get column index
int column_index = (int) (distorted_image_position.X() + 0.5);
if (column_index < 0) column_index = 0;
if (column_index >= Width()) column_index = Width()-1;
// Get camera pose
GSVPose pose = Pose(column_index);
const R3Point& viewpoint = pose.Viewpoint();
const R3Vector& towards = pose.Towards();
const R3Vector& up = pose.Up();
R3Vector right = towards % up;
// Compute point on ray
RNScalar dx = (RNScalar) (2 * (undistorted_image_position.X() - 0.5 * Width())) / (RNScalar) Width();
RNScalar dy = (RNScalar) (2 * (undistorted_image_position.Y() - 0.5 * Height())) / (RNScalar) Height();
R3Point world_point = viewpoint + towards;
world_point += dx * right * tan(0.5 * Camera()->XFov());
world_point += dy * up * tan(0.5 * Camera()->YFov());
// Return ray through undistorted image point
return R3Ray(viewpoint, world_point);
}
R3Ray GSVImage::
RayThroughDistortedPosition(const R2Point& distorted_image_position) const
{
// Return ray through distorted image point
R2Point undistorted_position = UndistortedPosition(distorted_image_position);
if (undistorted_position == R2Point(-1,-1)) return R3null_ray;
return RayThroughUndistortedPosition(undistorted_position);
}
////////////////////////////////////////////////////////////////////////
// Display functions
////////////////////////////////////////////////////////////////////////
void GSVImage::
Draw(RNFlags flags) const
{
// Draw image
// ???
}
void GSVImage::
Print(FILE *fp, const char *prefix, const char *suffix) const
{
// Check fp
if (!fp) fp = stdout;
// Print image header
if (prefix) fprintf(fp, "%s", prefix);
fprintf(fp, "Image %d:", panorama_index);
if (suffix) fprintf(fp, "%s", suffix);
fprintf(fp, "\n");
// Add indentation to prefix
char indented_prefix[1024];
sprintf(indented_prefix, "%s ", prefix);
// Print image stuff
// ???
}
////////////////////////////////////////////////////////////////////////
// Update functions
////////////////////////////////////////////////////////////////////////
void GSVImage::
Update(void)
{
}
} // namespace gaps
| true |
324f0fb047a0eeb7f0e378e5d8fe52f3b15e7f2f | C++ | wanren13/Leet_Practice | /LRU_cache.h | UTF-8 | 1,906 | 3.109375 | 3 | [] | no_license | #pragma once
#include "allhead.h"
namespace LRU_cache {
class LRUCache {
public:
LRUCache(int capacity) : _capacity(capacity) {
}
int get(int key) {
if (m.find(key) == m.end()) return -1;
int val = m[key]->v;
l.erase(m[key]);
m[key] = l.insert(l.end(), KV(key, val));
return val;
}
void set(int key, int value) {
auto it = l.insert(l.end(), KV(key, value));
if (m.find(key) != m.end()) l.erase(m[key]);
if (l.size() > _capacity) {
m.erase(l.begin()->k);
l.erase(l.begin());
}
m[key] = it;
}
private:
int _capacity;
struct KV {
int k, v;
KV(int kk, int vv) : k(kk), v(vv) {}
};
list<KV> l;
unordered_map<int, list<KV>::iterator> m;
};
//class LRUCache {
//public:
// LRUCache(int capacity) : cap(capacity) {}
// int get(int key) {
// if (m.find(key) == m.end()) return -1;
// KV kv = *m[key];
// l.erase(m[key]);
// m[key] = l.insert(l.end(), kv);
// return m[key]->v;
// }
// void set(int key, int value) {
// list<KV>::iterator it = l.insert(l.end(), KV(key, value));
// if (m.find(key) != m.end()) l.erase(m[key]);
// m[key] = it;
// if (m.size() > cap) {
// m.erase(l.front().k);
// l.pop_front();
// }
// }
// struct KV {
// int k, v;
// KV(int key, int val) : k(key), v(val) {}
// };
// list<KV> l;
// unordered_map<int, list<KV>::iterator> m;
// int cap;
//};
void test() {
/*LRUCache lru(2);
lru.set(2, 1);
lru.set(2, 2);
lru.get(2);
lru.set(1, 1);
lru.set(4, 1);
lru.get(2);*/
LRUCache lru(3);
lru.set(1, 1);
lru.set(2, 2);
lru.set(3, 3);
lru.set(4, 4);
cout << lru.get(4) << endl;
cout << lru.get(3) << endl;
cout << lru.get(2) << endl;
cout << lru.get(1) << endl;
lru.set(5, 5);
cout << lru.get(1) << endl;
cout << lru.get(2) << endl;
cout << lru.get(3) << endl;
cout << lru.get(4) << endl;
cout << lru.get(5) << endl;
}
} | true |
8bc1ca3fb270f5c98074b5011aeaebc1a0cff721 | C++ | Kiranchawla09/GFG | /Last_index_of_one.cpp | UTF-8 | 363 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
//code
int t;
cin>>t;
while (t--)
{
string s;
cin>> s;
int n= s.size();
int index=-1;
for (int i=0;i<n;i++)
{
if(s[i]=='1')
{
index=i;
}
}
cout<< index;
cout<< endl;
}
return 0;
} | true |
4c7de4b9b222e14f38eee3bb69d3e95faf575425 | C++ | cppcommons/work-2017-1011 | /clang/test.cpp | UTF-8 | 454 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <utility>
#ifndef __dso_handle
//void* __dso_handle = (void*) &__dso_handle;
#endif
int main() {
try {
float age;
std::cout << "How old are you?\n";
//std::cin >> age;
//std::cout << "You are " << age << " years (or whatever) old\n";
} catch ( std::ios::failure & ) {
std::cout << "Sorry, didn't understand that.\n";
throw;
}
return 0;
}
| true |
532593caacb8473432a08a5cae9171b9f8d8aa8d | C++ | KendrickAng/competitive-programming | /kattis/permutedarithmeticsequence/permutedarithmeticsequence.cpp | UTF-8 | 1,301 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n;
std::cin >> n;
for (int i = 0; i < n; i++) {
int m;
std::cin >> m;
std::vector<int> original{};
for (int j = 0; j < m; j++) {
int tmp;
std::cin >> tmp;
original.push_back(tmp);
}
// check
bool ok = true;
// check arithmetic
int diff = original[1] - original[0];
for (int i = 1; i < original.size(); i++) {
if (diff != original[i] - original[i-1]) {
ok = false;
break;
}
}
if (ok) {
std::cout << "arithmetic" << std::endl;
continue;
}
// check permuted arithmetic
ok = true;
std::sort(original.begin(), original.end());
diff = original[1] - original[0];
for (int i = 1; i < original.size(); i++) {
if (original[i] - original[i - 1] != diff) {
ok = false;
break;
}
}
if (ok) {
std::cout << "permuted arithmetic" << std::endl;
continue;
}
std::cout << "non-arithmetic" << std::endl;
}
} | true |
9da4b0cbb3b9b6cedc7cafd4903d919a862609d8 | C++ | jdotaz/ProyectoFinalPrimero | /Actualizado/Propietario.hpp | UTF-8 | 1,219 | 2.8125 | 3 | [] | no_license | #ifndef Propietario_hpp
#define Propietario_hpp
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "Animal.cpp"
using namespace std;
class Propietario {
private:
//Instancias
string nombre;
string apellido;
string telefono;
string direcccion;
int codigo;
int cantidad;
Animal *mascotas;
//Metodos privados
void copiarArr(Animal a[],Animal b[],int tam);
void addCantidad();
void deleteCantidad();
public:
//Constructores
Propietario();
Propietario(string nombre_,string apellido_,string telefono_,string direcccion_,int codigo_,bool existente);
Propietario(const Propietario &otro);
~Propietario();
//Obtencion de datos
string getNombre();
string getApellido();
string getTelefono();
string getDireccion();
int getCodigo();
int getNumeroMascotas();
Animal getMascota(int pos);
//Edicion de datos
void editNombre(string nombre_);
void editApellido(string apellido_);
void editTelefono(string telefono_);
void editDireccion(string direcccion_);
void editCodigo(int codigo_);
//Edicion del arreglo
void addMascota(Animal nuevo);
void deleteMascota(int pos);
void chanceMAscota(Animal nuevo,int pos);
};
#endif /* Propietario_hpp */
| true |
0657144450231d86e720dbb637246b768143b169 | C++ | Dicksonlab/MateBook | /mediawrapper/source/VideoCodec.cpp | UTF-8 | 6,246 | 2.53125 | 3 | [] | no_license | /**
* @file VideoCodec.cpp
* @author Herbert Grasberger
* @brief contains the implementation for the VideoCodec class
* @date 18.06.09
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS
#include <stdint.h>
#endif
#endif
#include "VideoCodec.hpp"
#include "VideoFormat.hpp"
#include "VideoFrame.hpp"
#include "VideoStream.hpp"
#include <iostream>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
/**
* this part here of the code is injected into the video decoding code from ffmpeg
* it produces proper video pts, since the default methods from ffmpeg don't work
* in some cases
*/
uint64_t global_video_pkt_pts = AV_NOPTS_VALUE;
/* These are called whenever we allocate a frame
* buffer. We use this to store the global_pts in
* a frame at the time it is allocated.
*/
int our_get_buffer(struct AVCodecContext *c, AVFrame *pic) {
int ret = avcodec_default_get_buffer(c, pic);
uint64_t *pts = (uint64_t *)av_malloc(sizeof(uint64_t));
*pts = global_video_pkt_pts;
pic->opaque = pts;
// std::cout << "getbuffer " << *pts << " ";
return ret;
}
void our_release_buffer(struct AVCodecContext *c, AVFrame *pic) {
if(pic) av_freep(&pic->opaque);
avcodec_default_release_buffer(c, pic);
}
namespace mw
{
VideoCodec::VideoCodec() : codec_(NULL)
{
}
VideoCodec::~VideoCodec()
{
if(codec_)
{
/* ===========================================================================
since the codec_ is just a pointer to an AVFormatContext member we MUST NOT
delete it! Otherwise we would be freeing memory twice.
========================================================================hg= */
codec_ = NULL;
}
if(codecContext_)
{
/* ===========================================================================
since the codecContext_ is just a pointer to an AVFormatContext member we
MUST NOT delete it! Otherwise we would be freeing memory twice.
========================================================================hg= */
avcodec_close(codecContext_);
codecContext_ = NULL;
}
}
bool VideoCodec::loadCodec(const VideoFormat * mFormat,
unsigned int mStreamNumber/* = 0*/)
{
/**
* loads a codec for decoding videos
*/
/**
* given a videoformat we load the codec from it.
*/
codecContext_ = mFormat->getAVFormatContext()->streams[mStreamNumber]->codec;
/**
* we get the width and height of a single video frame
*/
int width = codecContext_->width;
int height = codecContext_->height;
/**
* here an actual codec is loaded
*/
codec_ = avcodec_find_decoder(codecContext_->codec_id);
if(codec_ == NULL)
{
std::cerr << "Unsupported codec!" << std::endl;
return false;
}
/**
* based on the information of before, we open the codec
*/
AVDictionary ** options = NULL;
if(avcodec_open2(codecContext_, codec_, options) < 0)
{
std::cerr << "Could not open codec!" << std::endl;
return false;
}
/**
* writing the proper size information into our new codec context
*/
codecContext_->width = width;
codecContext_->height = height;
/**
* injecting the custom read functions for decoding
* into the codec context
*/
codecContext_->get_buffer = our_get_buffer;
codecContext_->release_buffer = our_release_buffer;
return true;
}
bool VideoCodec::loadCodec(const VideoStream * mStream,
unsigned int mCodecID,
unsigned int mPixelFormat,
int mWidth,
int mHeight,
int mNum,
int mDen,
bool mInterlaced,
unsigned int mBitRate/* = 100000*/)
{
/**
* loads a codec for encoding videos
*/
/**
* most of the values here are taken from ffmpeg.c, the ffmpeg executable
* that also provides encoding information
*/
codecContext_ = mStream->getAVStream()->codec;
/**
* basic codec information
*/
codecContext_->codec_type = AVMEDIA_TYPE_VIDEO;
codecContext_->codec_id = AVCodecID(mCodecID);
codecContext_->bit_rate = mBitRate;
codecContext_->bit_rate_tolerance = 4000000;
codecContext_->width = mWidth;
codecContext_->height = mHeight;
/**
* information about fps
*/
codecContext_->time_base.num = 1;
codecContext_->time_base.den = (int)(0.5 +((float) mNum) / ((float) mDen));
if(mInterlaced)
{
codecContext_->time_base.den /= 2;
}
/**
* encoding specific details
*/
codecContext_->gop_size = 12;
codecContext_->keyint_min = 25;
codecContext_->sample_aspect_ratio.num = 1;
codecContext_->sample_aspect_ratio.den = 1;
codecContext_->b_frame_strategy = 0;
codecContext_->max_b_frames=0;
codecContext_->pix_fmt = PixelFormat(mPixelFormat);
codecContext_->rc_max_rate = 0;
codecContext_->refs = 1;
// Defaults from ffmpeg.c
codecContext_->qblur = 0.5f;
codecContext_->qcompress = 0.5f;
codecContext_->b_quant_offset = 1.25f;
codecContext_->b_quant_factor = 1.25f;
codecContext_->i_quant_offset = 0.0f;
codecContext_->i_quant_factor = -0.71f;
codecContext_->qmax = 31;
codecContext_->qmin = 2;
codecContext_->max_qdiff = 3;
codecContext_->qcompress = 0.5f;
codecContext_->me_range = 0;
codecContext_->coder_type = 0;
/**
* based on the values entered above we try to find a codec that is
* able to deal with these values
*/
codec_ = avcodec_find_encoder(codecContext_->codec_id);
if(!codec_)
{
std::cerr << "No matching codec found!" << std::endl;
return false;
}
/**
* open the corresponding codec context
*/
AVDictionary ** options = NULL;
if (avcodec_open2(codecContext_, codec_, options) < 0)
{
return false;
}
return true;
}
AVCodecContext * VideoCodec::getAVCodecContext() const
{
return codecContext_;
}
AVCodec * VideoCodec::getAVCodec() const
{
return codec_;
}
std::string VideoCodec::getCodecInformation() const
{
std::string result = "";
result += "name: ";
result += codec_->long_name;
result += "\nsample_rate: ";
result += codecContext_->sample_rate;
result += "\nchannels: ";
result += codecContext_->channels;
result += "\n";
return result;
}
}
| true |
f5c2c9733934ea068f29e8ca837fa9cdfd1638aa | C++ | RoadToLP/lab3 | /tests.h | UTF-8 | 16,292 | 2.546875 | 3 | [] | no_license | //
// Created by Kurisu on 12/23/2020.
//
#ifndef LAB3_TESTS_H
#define LAB3_TESTS_H
#include <iostream>
#include <gtest/gtest.h>
#include "dBinarySignal.h"
#include "binarySignal.h"
#include <random>
#include <time.h>
TEST(dBinarySignal, Constructor){
dBinarySignal bs;
ASSERT_THROW(bs.getState(0), out_of_range);
ASSERT_EQ(bs.getSize(), 0);
}
TEST(dBinarySignal, ConstructorAll){
dBinarySignal bs(0);
for (int i = 0; i < 200; i++){
ASSERT_EQ(bs.getState(i).level, 0);
ASSERT_EQ(bs.getState(i).length, 255);
}
}
TEST(dBinarySignal, CopyConstructor){
srand(time(nullptr));
dBinarySignal bs;
int curlen = 0;
int l;
for (int i = 0; i < 100; i++){
l = random()%256;
bs(curlen, random()%2, l);
curlen += l;
}
dBinarySignal bs2(bs);
ASSERT_EQ(bs.getSize(), bs2.getSize());
for (int i = 0; i < 100; i++){
ASSERT_EQ(bs.getState(i).length, bs2.getState(i).length);
ASSERT_EQ(bs.getState(i).level, bs2.getState(i).level);
}
}
TEST(dBinarySignal, Fill){
// >> operator works through fill(), so no need to test it. So if we use fill constructor, fill and >> will be tested simultaneously
string toFill = "1^142,0^43,1^207,1^146,1^155,0^0,1^179,0^111,1^213,1^116,0^77,0^97,1^149,1^120,1^52,0^35,0^66,0^105,1^56,0^227,1^173,1^168,0^26,1^226,0^60,1^92,0^100,0^159,0^110,0^204,0^179,1^113,0^171,0^155,1^17,0^132,0^187,1^36,0^145,0^228,1^175,1^23,1^151,1^16,0^204,1^233,0^196,0^192,0^128,0^98,0^145,0^191,0^185,0^126,1^188,1^143,0^231,0^253,0^226,1^142,0^119,0^190,1^93,0^80,0^233,1^227,1^216,1^199,1^14,0^107,1^108,1^244,0^56,1^31,1^232,0^80,1^207,0^243,0^199,0^211,1^251,0^49,0^229,1^92,0^249,0^73,0^112,1^116,1^213,0^138,0^150,0^119,0^174,0^236,0^215,1^126,0^157,0^106,0^117,1^252";
unsigned short levels[] = {1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1};
unsigned char lengths[] = {142, 43, 207, 146, 155, 0, 179, 111, 213, 116, 77, 97, 149, 120, 52, 35, 66, 105, 56, 227, 173, 168, 26, 226, 60, 92, 100, 159, 110, 204, 179, 113, 171, 155, 17, 132, 187, 36, 145, 228, 175, 23, 151, 16, 204, 233, 196, 192, 128, 98, 145, 191, 185, 126, 188, 143, 231, 253, 226, 142, 119, 190, 93, 80, 233, 227, 216, 199, 14, 107, 108, 244, 56, 31, 232, 80, 207, 243, 199, 211, 251, 49, 229, 92, 249, 73, 112, 116, 213, 138, 150, 119, 174, 236, 215, 126, 157, 106, 117, 252};
dBinarySignal bs(toFill);
for (int i = 0; i < 100; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
ASSERT_EQ(bs.getSize(), 100);
}
TEST(dBinarySignal, equalOperator){
string toFill = "1^142,0^43,1^207,1^146,1^155,0^0,1^179,0^111,1^213,1^116,0^77,0^97,1^149,1^120,1^52,0^35,0^66,0^105,1^56,0^227,1^173,1^168,0^26,1^226,0^60,1^92,0^100,0^159,0^110,0^204,0^179,1^113,0^171,0^155,1^17,0^132,0^187,1^36,0^145,0^228,1^175,1^23,1^151,1^16,0^204,1^233,0^196,0^192,0^128,0^98,0^145,0^191,0^185,0^126,1^188,1^143,0^231,0^253,0^226,1^142,0^119,0^190,1^93,0^80,0^233,1^227,1^216,1^199,1^14,0^107,1^108,1^244,0^56,1^31,1^232,0^80,1^207,0^243,0^199,0^211,1^251,0^49,0^229,1^92,0^249,0^73,0^112,1^116,1^213,0^138,0^150,0^119,0^174,0^236,0^215,1^126,0^157,0^106,0^117,1^252";
dBinarySignal bs(toFill);
dBinarySignal bs2;
bs2 = bs;
for (int i = 0; i < 100; i++){
ASSERT_EQ(bs.getState(i).level, bs2.getState(i).level);
ASSERT_EQ(bs.getState(i).length, bs2.getState(i).length);
}
ASSERT_EQ(bs2.getSize(), 100);
}
TEST(dBinarySignal, ostreamOperator){
stringstream os;
string toFill = "1^21,1^231,1^194,1^154,1^186,1^232,0^252,0^26,1^84,1^43,0^101,0^7,0^235,0^230,1^191,1^111,0^177,1^31,1^172,1^229,0^13,0^173,1^124,0^192,1^18,1^240,0^121,1^209,1^232,1^139,1^35,1^129,1^51,0^192,1^207,1^1,1^184,0^153,1^34,0^17,0^30,1^0,1^73,1^19,1^208,1^162,0^115,0^105,1^113,1^46,1^144,0^213,0^182,0^173,0^219,1^15,1^232,1^120,0^83,1^21,0^110,1^96,0^12,1^61,0^39,1^166,0^106,1^184,1^228,1^217,0^155,1^239,1^117,1^39,1^146,1^176,0^166,0^54,0^50,1^19,0^216,1^82,0^238,1^126,0^154,1^67,0^22,0^255,0^60,1^167,0^222,1^13,0^92,0^234,0^205,0^129,0^215,1^40,0^166,0^98";
string ostoeq = "1 21\n1 231\n1 194\n1 154\n1 186\n1 232\n0 252\n0 26\n1 84\n1 43\n0 101\n0 7\n0 235\n0 230\n1 191\n1 111\n0 177\n1 31\n1 172\n1 229\n0 13\n0 173\n1 124\n0 192\n1 18\n1 240\n0 121\n1 209\n1 232\n1 139\n1 35\n1 129\n1 51\n0 192\n1 207\n1 1\n1 184\n0 153\n1 34\n0 17\n0 30\n1 0\n1 73\n1 19\n1 208\n1 162\n0 115\n0 105\n1 113\n1 46\n1 144\n0 213\n0 182\n0 173\n0 219\n1 15\n1 232\n1 120\n0 83\n1 21\n0 110\n1 96\n0 12\n1 61\n0 39\n1 166\n0 106\n1 184\n1 228\n1 217\n0 155\n1 239\n1 117\n1 39\n1 146\n1 176\n0 166\n0 54\n0 50\n1 19\n0 216\n1 82\n0 238\n1 126\n0 154\n1 67\n0 22\n0 255\n0 60\n1 167\n0 222\n1 13\n0 92\n0 234\n0 205\n0 129\n0 215\n1 40\n0 166\n0 98\n";
dBinarySignal bs(toFill);
os << bs;
ASSERT_EQ(os.str(), ostoeq);
}
TEST(dBinarySignal, negOperator){
string toFill = "1^142,0^43,1^207,1^146,1^155,1^179,0^111,1^213,1^116,0^77,0^97,1^149,1^120,1^52,0^35,0^66,0^105,1^56,0^227,1^173,1^168,0^26,1^226,0^60,1^92,0^100,0^159,0^110,0^204,0^179,1^113,0^171,0^155,1^17,0^132,0^187,1^36,0^145,0^228,1^175,1^23,1^151,1^16,0^204,1^233,0^196,0^192,0^128,0^98,0^145,0^191,0^185,0^126,1^188,1^143,0^231,0^253,0^226,1^142,0^119,0^190,1^93,0^80,0^233,1^227,1^216,1^199,1^14,0^107,1^108,1^244,0^56,1^31,1^232,0^80,1^207,0^243,0^199,0^211,1^251,0^49,0^229,1^92,0^249,0^73,0^112,1^116,1^213,0^138,0^150,0^119,0^174,0^236,0^215,1^126,0^157,0^106,0^117,1^252";
unsigned short levels[] = {1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1};
unsigned char lengths[] = {142, 43, 207, 146, 155, 179, 111, 213, 116, 77, 97, 149, 120, 52, 35, 66, 105, 56, 227, 173, 168, 26, 226, 60, 92, 100, 159, 110, 204, 179, 113, 171, 155, 17, 132, 187, 36, 145, 228, 175, 23, 151, 16, 204, 233, 196, 192, 128, 98, 145, 191, 185, 126, 188, 143, 231, 253, 226, 142, 119, 190, 93, 80, 233, 227, 216, 199, 14, 107, 108, 244, 56, 31, 232, 80, 207, 243, 199, 211, 251, 49, 229, 92, 249, 73, 112, 116, 213, 138, 150, 119, 174, 236, 215, 126, 157, 106, 117, 252};
dBinarySignal bs(toFill);
!bs;
for (int i = 0; i < 99; i++){
ASSERT_EQ(bs.getState(i).level, (levels[i]) ? 0 : 1);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
ASSERT_EQ(bs.getSize(), 99);
}
TEST(dBinarySignal, appendOperator){
string toFill1 = "1^123,0^31";
string toFill2 = "0^21,0^34";
unsigned short levels[] = {1, 0, 0, 0};
unsigned char lengths[] = {123, 31, 21, 34};
dBinarySignal bs1(toFill1);
dBinarySignal bs2(toFill2);
bs1 += bs2;
for (int i = 0; i < 4; i++){
ASSERT_EQ(bs1.getState(i).level, levels[i]);
ASSERT_EQ(bs1.getState(i).length, lengths[i]);
}
ASSERT_EQ(bs1.getSize(), 4);
}
TEST(dBinarySignal, multiplyOperator){
string toFill = "1^123,0^31";
unsigned short levels[] = {1, 0, 1, 0, 1, 0, 1, 0};
unsigned char lengths[] = {123, 31, 123, 31, 123, 31, 123, 31};
dBinarySignal bs(toFill);
bs *= 4;
ASSERT_EQ(bs.getSize(), 8);
for (int i = 0; i < 8; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
}
TEST(dBinarySignal, insertOperator){
dBinarySignal bs;
bs(0, 1, 20);
bs(15, 0, 5);
bs(25, 1, 15);
unsigned short levels[] = {1, 0, 1, 1};
unsigned char lengths[] = {15, 5, 5, 15};
ASSERT_EQ(bs.getSize(), 4);
for (int i = 0; i < 4; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
}
TEST(dBinarySignal, removeOperator){
dBinarySignal bs;
bs(0, 1, 20);
bs(15, 0, 5);
bs(25, 1, 15);
bs(3, 5);
bs(5, 10);
unsigned short levels[] = {1, 1, 1};
unsigned char lengths[] = {5, 5, 15};
ASSERT_EQ(bs.getSize(), 3);
for (int i = 0; i < 3; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
}
TEST(binarySignal, Constructor){
binarySignal bs;
ASSERT_THROW(bs.getState(0), out_of_range);
ASSERT_EQ(bs.getSize(), 0);
}
TEST(binarySignal, ConstructorAll){
binarySignal bs(0);
for (int i = 0; i < 200; i++){
ASSERT_EQ(bs.getState(i).level, 0);
ASSERT_EQ(bs.getState(i).length, 255);
}
}
TEST(binarySignal, CopyConstructor){
srand(time(nullptr));
binarySignal bs;
int curlen = 0;
int l;
for (int i = 0; i < 100; i++){
l = random()%256;
bs(curlen, random()%2, l);
curlen += l;
}
binarySignal bs2(bs);
ASSERT_EQ(bs.getSize(), bs2.getSize());
for (int i = 0; i < 100; i++){
ASSERT_EQ(bs.getState(i).length, bs2.getState(i).length);
ASSERT_EQ(bs.getState(i).level, bs2.getState(i).level);
}
}
TEST(binarySignal, Fill){
// >> operator works through fill(), so no need to test it. So if we use fill constructor, fill and >> will be tested simultaneously
string toFill = "1^142,0^43,1^207,1^146,1^155,0^0,1^179,0^111,1^213,1^116,0^77,0^97,1^149,1^120,1^52,0^35,0^66,0^105,1^56,0^227,1^173,1^168,0^26,1^226,0^60,1^92,0^100,0^159,0^110,0^204,0^179,1^113,0^171,0^155,1^17,0^132,0^187,1^36,0^145,0^228,1^175,1^23,1^151,1^16,0^204,1^233,0^196,0^192,0^128,0^98,0^145,0^191,0^185,0^126,1^188,1^143,0^231,0^253,0^226,1^142,0^119,0^190,1^93,0^80,0^233,1^227,1^216,1^199,1^14,0^107,1^108,1^244,0^56,1^31,1^232,0^80,1^207,0^243,0^199,0^211,1^251,0^49,0^229,1^92,0^249,0^73,0^112,1^116,1^213,0^138,0^150,0^119,0^174,0^236,0^215,1^126,0^157,0^106,0^117,1^252";
unsigned short levels[] = {1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1};
unsigned char lengths[] = {142, 43, 207, 146, 155, 0, 179, 111, 213, 116, 77, 97, 149, 120, 52, 35, 66, 105, 56, 227, 173, 168, 26, 226, 60, 92, 100, 159, 110, 204, 179, 113, 171, 155, 17, 132, 187, 36, 145, 228, 175, 23, 151, 16, 204, 233, 196, 192, 128, 98, 145, 191, 185, 126, 188, 143, 231, 253, 226, 142, 119, 190, 93, 80, 233, 227, 216, 199, 14, 107, 108, 244, 56, 31, 232, 80, 207, 243, 199, 211, 251, 49, 229, 92, 249, 73, 112, 116, 213, 138, 150, 119, 174, 236, 215, 126, 157, 106, 117, 252};
binarySignal bs(toFill);
for (int i = 0; i < 100; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
ASSERT_EQ(bs.getSize(), 100);
}
TEST(binarySignal, ostreamOperator){
stringstream os;
string toFill = "1^21,1^231,1^194,1^154,1^186,1^232,0^252,0^26,1^84,1^43,0^101,0^7,0^235,0^230,1^191,1^111,0^177,1^31,1^172,1^229,0^13,0^173,1^124,0^192,1^18,1^240,0^121,1^209,1^232,1^139,1^35,1^129,1^51,0^192,1^207,1^1,1^184,0^153,1^34,0^17,0^30,1^0,1^73,1^19,1^208,1^162,0^115,0^105,1^113,1^46,1^144,0^213,0^182,0^173,0^219,1^15,1^232,1^120,0^83,1^21,0^110,1^96,0^12,1^61,0^39,1^166,0^106,1^184,1^228,1^217,0^155,1^239,1^117,1^39,1^146,1^176,0^166,0^54,0^50,1^19,0^216,1^82,0^238,1^126,0^154,1^67,0^22,0^255,0^60,1^167,0^222,1^13,0^92,0^234,0^205,0^129,0^215,1^40,0^166,0^98";
string ostoeq = "1 21\n1 231\n1 194\n1 154\n1 186\n1 232\n0 252\n0 26\n1 84\n1 43\n0 101\n0 7\n0 235\n0 230\n1 191\n1 111\n0 177\n1 31\n1 172\n1 229\n0 13\n0 173\n1 124\n0 192\n1 18\n1 240\n0 121\n1 209\n1 232\n1 139\n1 35\n1 129\n1 51\n0 192\n1 207\n1 1\n1 184\n0 153\n1 34\n0 17\n0 30\n1 0\n1 73\n1 19\n1 208\n1 162\n0 115\n0 105\n1 113\n1 46\n1 144\n0 213\n0 182\n0 173\n0 219\n1 15\n1 232\n1 120\n0 83\n1 21\n0 110\n1 96\n0 12\n1 61\n0 39\n1 166\n0 106\n1 184\n1 228\n1 217\n0 155\n1 239\n1 117\n1 39\n1 146\n1 176\n0 166\n0 54\n0 50\n1 19\n0 216\n1 82\n0 238\n1 126\n0 154\n1 67\n0 22\n0 255\n0 60\n1 167\n0 222\n1 13\n0 92\n0 234\n0 205\n0 129\n0 215\n1 40\n0 166\n0 98\n";
binarySignal bs(toFill);
os << bs;
ASSERT_EQ(os.str(), ostoeq);
}
TEST(binarySignal, negOperator){
string toFill = "1^142,0^43,1^207,1^146,1^155,1^179,0^111,1^213,1^116,0^77,0^97,1^149,1^120,1^52,0^35,0^66,0^105,1^56,0^227,1^173,1^168,0^26,1^226,0^60,1^92,0^100,0^159,0^110,0^204,0^179,1^113,0^171,0^155,1^17,0^132,0^187,1^36,0^145,0^228,1^175,1^23,1^151,1^16,0^204,1^233,0^196,0^192,0^128,0^98,0^145,0^191,0^185,0^126,1^188,1^143,0^231,0^253,0^226,1^142,0^119,0^190,1^93,0^80,0^233,1^227,1^216,1^199,1^14,0^107,1^108,1^244,0^56,1^31,1^232,0^80,1^207,0^243,0^199,0^211,1^251,0^49,0^229,1^92,0^249,0^73,0^112,1^116,1^213,0^138,0^150,0^119,0^174,0^236,0^215,1^126,0^157,0^106,0^117,1^252";
unsigned short levels[] = {1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1};
unsigned char lengths[] = {142, 43, 207, 146, 155, 179, 111, 213, 116, 77, 97, 149, 120, 52, 35, 66, 105, 56, 227, 173, 168, 26, 226, 60, 92, 100, 159, 110, 204, 179, 113, 171, 155, 17, 132, 187, 36, 145, 228, 175, 23, 151, 16, 204, 233, 196, 192, 128, 98, 145, 191, 185, 126, 188, 143, 231, 253, 226, 142, 119, 190, 93, 80, 233, 227, 216, 199, 14, 107, 108, 244, 56, 31, 232, 80, 207, 243, 199, 211, 251, 49, 229, 92, 249, 73, 112, 116, 213, 138, 150, 119, 174, 236, 215, 126, 157, 106, 117, 252};
binarySignal bs(toFill);
!bs;
for (int i = 0; i < 99; i++){
ASSERT_EQ(bs.getState(i).level, (levels[i]) ? 0 : 1);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
ASSERT_EQ(bs.getSize(), 99);
}
TEST(binarySignal, appendOperator){
string toFill1 = "1^123,0^31";
string toFill2 = "0^21,0^34";
unsigned short levels[] = {1, 0, 0, 0};
unsigned char lengths[] = {123, 31, 21, 34};
binarySignal bs1(toFill1);
binarySignal bs2(toFill2);
bs1 += bs2;
for (int i = 0; i < 4; i++){
ASSERT_EQ(bs1.getState(i).level, levels[i]);
ASSERT_EQ(bs1.getState(i).length, lengths[i]);
}
ASSERT_EQ(bs1.getSize(), 4);
}
TEST(binarySignal, multiplyOperator){
string toFill = "1^123,0^31";
unsigned short levels[] = {1, 0, 1, 0, 1, 0, 1, 0};
unsigned char lengths[] = {123, 31, 123, 31, 123, 31, 123, 31};
binarySignal bs(toFill);
bs *= 4;
ASSERT_EQ(bs.getSize(), 8);
for (int i = 0; i < 8; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
}
TEST(binarySignal, insertOperator){
binarySignal bs;
bs(0, 1, 20);
bs(15, 0, 5);
bs(25, 1, 15);
unsigned short levels[] = {1, 0, 1, 1};
unsigned char lengths[] = {15, 5, 5, 15};
ASSERT_EQ(bs.getSize(), 4);
for (int i = 0; i < 4; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
}
TEST(binarySignal, removeOperator){
binarySignal bs;
bs(0, 1, 20);
bs(15, 0, 5);
bs(25, 1, 15);
bs(3, 5);
bs(5, 10);
unsigned short levels[] = {1, 1, 1};
unsigned char lengths[] = {5, 5, 15};
ASSERT_EQ(bs.getSize(), 3);
for (int i = 0; i < 3; i++){
ASSERT_EQ(bs.getState(i).level, levels[i]);
ASSERT_EQ(bs.getState(i).length, lengths[i]);
}
}
int runTests(){
::testing::InitGoogleTest();
return RUN_ALL_TESTS();
}
#endif //LAB3_TESTS_H
| true |
51122075048ead8b89315012a9d0e3aa9c61a5e0 | C++ | eXceediDeaL/OI | /Problems/POJ/图论/二分图/1034.cpp | UTF-8 | 2,153 | 3.046875 | 3 | [] | no_license | /*
The dog task
题意:主人带狗去散步,主人走n个点,狗在每个点都会与主人碰头,但其余时候都是各自溜达,除此之外,狗还会去找一些有趣的地方(共m个),每次离开主人狗最多去一个有趣的地方。狗的速度最快是人的两倍,求使得狗到达最多有趣点的方法。
分析:对于人从第i个点到第i+1个点,这条路作为三角形的一边c,然后遍历其他点,若j与这两个点组成的边即为a,b如果a+b<=2*c则g[i][j]=true,然后做二分图最大匹配,就是狗最多能到的点。
注意进行匈牙利算法时,不仅记录N->M的匹配边,还要记录M->N的相对应的匹配边,因为要根据这个生成答案序列
*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<bitset>
#define cal(A,B) sqrt((double)((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y)))
using namespace std;
const int INF=0x3f3f3f3f,MAXN=100;
const double eps=1e-8;
struct point{
int x,y;
}ps[MAXN+3],ds[MAXN+3];
int match[MAXN+3],link[MAXN+3],N,M;
bool g[MAXN+3][MAXN+3],vis[MAXN+3];
bool findpath(int u){
for(int i=1;i<=M;i++){
if(g[u][i] && !vis[i]){
vis[i]=1;
if(match[i]==-1 || findpath(match[i])){
match[i]=u;
link[u]=i;
return true;
}
}
}
return false;
}
int Maxpart(){
memset(match,-1,sizeof(match));
memset(link,-1,sizeof(link));
int ans=0;
for(int i=1;i<=N;i++){
memset(vis,0,sizeof(vis));
ans+=findpath(i);
}
return ans;
}
inline bool check(int i,int j,int k){
double a=cal(ps[i],ds[k]),b=cal(ps[j],ds[k]),c=cal(ps[i],ps[j]);
return (a+b<2.0*c+eps);
}
void buildgraph(){
memset(g,0,sizeof(g));
for(int i=1;i<N;i++)
for(int j=1;j<=M;j++)
g[i][j]=check(i,i+1,j);
}
void input(){
scanf("%d%d",&N,&M);
for(int i=1;i<=N;i++)scanf("%d%d",&ps[i].x,&ps[i].y);
for(int i=1;i<=M;i++)scanf("%d%d",&ds[i].x,&ds[i].y);
}
int main(){
input();
buildgraph();
printf("%d\n",N+Maxpart());
for(int i=1;i<N;i++){
printf("%d %d ",ps[i].x,ps[i].y);
if(link[i]!=-1)printf("%d %d ",ds[link[i]].x,ds[link[i]].y);
}
printf("%d %d\n",ps[N].x,ps[N].y);
return 0;
}
| true |
0c358767a3d84676b859e581ae16d0bd10c640bf | C++ | CodeTiger927/CodeForcesRepo | /742/carryingconundrum.cpp | UTF-8 | 438 | 2.90625 | 3 | [] | no_license | using namespace std;
#include <iostream>
#include <cstring>
string s;
void solve() {
cin >> s;
int s1 = 0;
int s2 = 0;
int pow = 1;
for(int i = s.size() - 1;i >= 0;--i) {
if(i & 1) {
s1 += (s[i] - '0') * pow;
}else{
s2 += (s[i] - '0') * pow;
}
if((s.size() - i) % 2 == 0) pow *= 10;
}
long long ans = (s1 + 1) * (s2 + 1) - 2;
cout << ans << endl;
return;
}
int main() {
int T;
cin >> T;
while(T--) solve();
} | true |
f0d1f5e0df1113df9b1e720d466fba6ae315767c | C++ | mabur/mang_lang | /src/interpreter.cpp | UTF-8 | 2,338 | 2.921875 | 3 | [] | no_license | #include <chrono>
#include <iomanip>
#include <iostream>
#include <fstream>
#include "factory.h"
#include "mang_lang.h"
namespace CommandLineArgumentIndex {
enum {PROGRAM_PATH, INPUT_PATH, OUTPUT_PATH, LOG_PATH};
}
int main(int argc, char **argv) {
using namespace std;
if (argc < CommandLineArgumentIndex::INPUT_PATH + 1) {
cout << "Expected input file." << endl;
return 1;
}
const auto input_file_path = std::string{
argv[CommandLineArgumentIndex::INPUT_PATH]
};
auto output_file_path = std::string{};
if (argc < CommandLineArgumentIndex::OUTPUT_PATH + 1) {
output_file_path = input_file_path.substr(0, input_file_path.find_last_of('.'))
+ "_evaluated.txt";
} else {
output_file_path = argv[CommandLineArgumentIndex::OUTPUT_PATH];
}
cout << "Reading program from " << input_file_path << " ... ";
auto input_file = ifstream{input_file_path};
const auto code = string{(istreambuf_iterator<char>(input_file)), istreambuf_iterator<char>()};
input_file.close();
cout << "Done." << endl;
try {
cout << "Evaluating program ... ";
const auto start = std::chrono::steady_clock::now();
const auto result = evaluate_all(code);
const auto end = std::chrono::steady_clock::now();
const auto duration_total = std::chrono::duration<double>{end - start};
cout << "Done. " << std::fixed << std::setprecision(1)
<< duration_total.count() << " seconds." << endl;
cout << "Writing result to " << output_file_path << " ... ";
auto output_file = ofstream{output_file_path};
output_file << result;
output_file.close();
cout << "Done." << endl;
} catch (const std::runtime_error& e) {
cout << e.what() << endl;
}
if (argc < CommandLineArgumentIndex::LOG_PATH + 1) {
cout << "Skipping logging." << endl;
} else {
cout << "Getting log ... ";
const auto log = getLog();
cout << "Done." << endl;
const auto log_file_path = argv[CommandLineArgumentIndex::LOG_PATH];
cout << "Writing log to " << log_file_path << " ... ";
auto log_file = ofstream{log_file_path};
log_file << log;
log_file.close();
cout << "Done." << endl;
}
}
| true |
1a449a09bdac4ffef1b1f35338b0e3979aea80f7 | C++ | unixjet/ktblaze | /server/talk_to_client.cpp | UTF-8 | 1,574 | 2.65625 | 3 | [] | no_license | #include <talk_to_client.h>
using namespace boost::asio;
using namespace boost::posix_time;
talk_to_client::talk_to_client(boost::asio::io_service& service)
:sock_(service), started_(false)
{}
void talk_to_client::start()
{
started_ = true;
do_read();
}
talk_to_client::ptr talk_to_client::make_client(boost::asio::io_service& service)
{
talk_to_client::ptr new_client( new talk_to_client(service) );
return new_client;
}
void talk_to_client::stop()
{
if (!started_) return ;
started_ = false;
sock_.close();
}
void talk_to_client::on_read(const error_code & err, size_t bytes)
{
if (!err)
{
std::string msg(read_buffer_, bytes);
do_write(msg + "\n");
}
stop();
}
void talk_to_client::on_write(const error_code &err, size_t bytes)
{
do_read();
}
void talk_to_client::do_read()
{
async_read(sock_, buffer(read_buffer_),
MEM_FN2(read_complete, _1, _2), MEM_FN2(on_read, _1, _2));
}
void talk_to_client::do_write(const std::string & msg)
{
// std::cout << "Server Echo " << msg << std::endl;
std::copy(msg.begin(), msg.end(), write_buffer_);
sock_.async_write_some(buffer(write_buffer_,msg.size()),
MEM_FN2(on_write, _1, _2));
}
size_t talk_to_client::read_complete(const boost::system::error_code & err, size_t bytes)
{
if ( err) return 0;
bool found = std::find(read_buffer_, read_buffer_ + bytes, '\n') < read_buffer_ + bytes;
// we read one-by-one until we get to enter, no buffering
return found ? 0 : 1;
}
| true |
6d76621deb352563979faac8365021d99817d5d1 | C++ | Redleaf23477/ojcodes | /codeforces/round634/C.cpp | UTF-8 | 1,221 | 2.515625 | 3 | [] | no_license | // by redleaf23477
#include <bits/stdc++.h>
// iostream macros
#define endl '\n'
#define var(x) "[" << #x << "=" << x << "]"
// chrono macros
#define chrono_now std::chrono::high_resolution_clock::now()
#define chrono_duration(t1, t2) std::chrono::duration<double>(t2-t1).count()
#define chrono_rand_seed chrono_now.time_since_epoch().count()
// random
std::mt19937_64 myrand(chrono_rand_seed);
using namespace std;
using ll = long long int;
ll n;
map<ll,ll> mp;
#define val first
#define cnt second
void init();
void process();
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int T; cin >> T;
while(T--)
{
init();
process();
}
cout.flush();
return 0;
}
void init()
{
cin >> n;
mp.clear();
for(int i = 0; i < n; i++)
{
ll x; cin >> x;
if(mp.count(x) == 0) mp[x] = 0;
mp[x]++;
}
}
void process()
{
if(mp.size() == 1)
{
if(n == 1) cout << 0 << endl;
else cout << 1 << endl;
return;
}
ll mx = 0;
for(auto p : mp)
{
mx = max(mx, p.cnt);
}
ll ans = 0;
if(mx <= (ll)mp.size()-1) ans = mx;
else ans = min(mx-1, (ll)mp.size());
cout << ans << endl;
}
| true |
6fa69e624ad7e0bf1e2bd2644af29401c12f6c8e | C++ | Inlucker/University | /TISD/Lab_02_var25/car_list_funcs.cpp | UTF-8 | 16,033 | 3.328125 | 3 | [] | no_license | #include "car_list_funcs.h"
//no need
void print_key_list(int *key_list, int size_of_list)
{
for (int i = 0; i < size_of_list; i++)
{
cout << i + 1 << ": ";
cout << key_list[i] << endl;
}
cout << endl;
}
//Функция вывода таблицы ключей
void print_price_key_list(price_keys *key_list, int size_of_list)
{
for (int i = 0; i < size_of_list; i++)
{
cout << i + 1 << ": ";
cout << key_list[i].id << "; " << key_list[i].price << "; " << endl;
}
cout << endl;
}
//Функция вывода текущего списка машин
void print_car_list(car *cars_list, int size_of_list)
{
for (int i = 0; i < size_of_list; i++)
{
cout << i + 1 << ": ";
print_car_record(cars_list[i]);
}
cout << endl;
}
void print_car_list_by_keys(car *cars_list, int size_of_list, int *key_list)
{
for (int i = 0; i < size_of_list; i++)
{
cout << i + 1 << ": ";
print_car_record(cars_list[key_list[i]]);
}
cout << endl;
}
//Функция вывода списка машин с использованием таблицы ключей
void print_car_list_by_price_keys(car *cars_list, int size_of_list, price_keys *key_list)
{
for (int i = 0; i < size_of_list; i++)
{
cout << i + 1 << ": ";
print_car_record(cars_list[key_list[i].id]);
}
cout << endl;
}
//Функция копирования списка машин
void car_list_copy (car *car_list1, car *car_list2, int size_of_list)
{
for (int i = 0; i < size_of_list; i++)
car_list1[i] = car_list2[i];
}
//Функция добавления одной записи в конец списка машин
int add_record (car **car_list, int size_of_list, car car_record)
{
car *cars_list_new = new car [size_of_list + 1];
car_list_copy(cars_list_new, *car_list, size_of_list);
cars_list_new[size_of_list] = car_record;
delete[] *car_list;
*car_list = new car[size_of_list + 1];
car_list_copy(*car_list, cars_list_new, size_of_list + 1);
delete [] cars_list_new;
return size_of_list + 1;
}
//Функция считывания списка машин из файла
int read_file(string file_name, car **car_list, int *size_of_list)
{
ifstream f(file_name);
string input = "";
car car_record;
while(getline(f, input))
{
if (read_record(input, &car_record) == 0)
*size_of_list = add_record(car_list, *size_of_list, car_record);
}
return 0;
}
//Функция копирования следующего элемента списка в предыдущий
void car_record_copy(car *car_list1, car *car_list2, int i)
{
car_list1[i] = car_list2[i+1];
}
//Функция удаления записи из списка машин по номеру
int delete_record(car **car_list, int size_of_list, int id)
{
if (id > size_of_list && id <= 0)
return -1;
car *cars_list_new = new car [size_of_list - 1];
car_list_copy(cars_list_new, *car_list, id - 1);
for (int i = id - 1; i < size_of_list - 1; i++)
car_record_copy(cars_list_new, *car_list, i);
delete[] *car_list;
*car_list = new car[size_of_list - 1];
car_list_copy(*car_list, cars_list_new, size_of_list - 1);
delete [] cars_list_new;
return size_of_list - 1;
}
//Функция удаления записи из списка машин по значению конкретного поля
int delete_car_record_by_pole(int pole, string znach, car **car_list, int *size_of_list)
{
int tmp_size = *size_of_list;
switch(pole)
{
case BRAND:
for (int i = 0; i < tmp_size; i++)
if (((*car_list)+i)->brand == znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
break;
case MANUFACURER_COUNTRY:
for (int i = 0; i < tmp_size; i++)
if (((*car_list)+i)->manufacturer_country == znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
break;
case PRICE:
for (int i = 0; i < tmp_size; i++)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->price == tmp_znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
break;
case COLOR:
for (int i = 0; i < tmp_size; i++)
if (((*car_list)+i)->color == znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
break;
case IS_NEW:
for (int i = 0; i < tmp_size; i++)
{
string tmp_znach = "";
if (((*car_list)+i)->is_new)
tmp_znach = "new";
else
tmp_znach = "old";
if (tmp_znach == znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
break;
case GUARANTEE:
for (int i = 0; i < tmp_size; i++)
{
if (((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.new_car_params.guarantee == tmp_znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
}
break;
case YEAR_OF_RELEASE:
for (int i = 0; i < tmp_size; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.year_of_release == tmp_znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
}
break;
case PROBEG:
for (int i = 0; i < tmp_size; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.probeg == tmp_znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
}
break;
case REPAIR_COUNT:
for (int i = 0; i < tmp_size; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.repair_count == tmp_znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
}
break;
case OWNERS_COUNT:
for (int i = 0; i < tmp_size; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.owners_count == tmp_znach)
{
tmp_size = delete_record(car_list, tmp_size, i + 1);
i--;
}
}
}
break;
default:
return ERROR;
break;
}
if (tmp_size == *size_of_list)
cout << "Nothing to delete" << endl;
else
*size_of_list = tmp_size;
return 0;
}
int print_car_record_by_pole(int pole, string znach, car **car_list, int size_of_list)
{
switch(pole)
{
case BRAND:
for (int i = 0; i < size_of_list; i++)
if (((*car_list)+i)->brand == znach)
print_car_record(*((*car_list)+i));
break;
case MANUFACURER_COUNTRY:
for (int i = 0; i < size_of_list; i++)
if (((*car_list)+i)->manufacturer_country == znach)
print_car_record(*((*car_list)+i));
break;
case PRICE:
for (int i = 0; i < size_of_list; i++)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->price == tmp_znach)
print_car_record(*((*car_list)+i));
}
break;
case COLOR:
for (int i = 0; i < size_of_list; i++)
if (((*car_list)+i)->color == znach)
print_car_record(*((*car_list)+i));
break;
case IS_NEW:
for (int i = 0; i < size_of_list; i++)
{
string tmp_znach = "";
if (((*car_list)+i)->is_new)
tmp_znach = "new";
else
tmp_znach = "old";
if (tmp_znach == znach)
print_car_record(*((*car_list)+i));
}
break;
case GUARANTEE:
for (int i = 0; i < size_of_list; i++)
{
if (((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.new_car_params.guarantee == tmp_znach)
print_car_record(*((*car_list)+i));
}
}
break;
case YEAR_OF_RELEASE:
for (int i = 0; i < size_of_list; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.year_of_release == tmp_znach)
print_car_record(*((*car_list)+i));
}
}
break;
case PROBEG:
for (int i = 0; i < size_of_list; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.probeg == tmp_znach)
print_car_record(*((*car_list)+i));
}
}
break;
case REPAIR_COUNT:
for (int i = 0; i < size_of_list; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.repair_count == tmp_znach)
print_car_record(*((*car_list)+i));
}
}
break;
case OWNERS_COUNT:
for (int i = 0; i < size_of_list; i++)
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach, &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.owners_count == tmp_znach)
print_car_record(*((*car_list)+i));
}
}
break;
default:
return ERROR;
break;
}
cout << endl;
return 0;
}
//Функция вывода списка машин по значениям одного или нескольких полей
int print_car_record_by_poles(int pole[10], string znach[10], car **car_list, int size_of_list)
{
bool is_printed = false;
for (int i = 0; i < size_of_list; i++)
{
bool flag = true;
for (int j = 0; j < 10; j++)
{
if (pole[j])
switch(j)
{
case BRAND:
if (((*car_list)+i)->brand != znach[j])
flag = false;
break;
case MANUFACURER_COUNTRY:
if (((*car_list)+i)->manufacturer_country != znach[j])
flag = false;
break;
case PRICE:
{
int tmp_znach = 0;
if (string_to_int(znach[j], &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->price != tmp_znach)
flag = false;
}
break;
case COLOR:
if (((*car_list)+i)->color != znach[j])
flag = false;
break;
case IS_NEW:
{
string tmp_znach = "";
if (((*car_list)+i)->is_new)
tmp_znach = "new";
else
tmp_znach = "old";
if (tmp_znach != znach[j])
flag = false;
}
break;
case GUARANTEE:
{
if (((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach[j], &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.new_car_params.guarantee != tmp_znach)
flag = false;
}
}
break;
case YEAR_OF_RELEASE:
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach[j], &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.year_of_release != tmp_znach)
flag = false;
}
}
break;
case PROBEG:
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach[j], &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.probeg != tmp_znach)
flag = false;
}
}
break;
case REPAIR_COUNT:
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach[j], &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.repair_count != tmp_znach)
flag = false;
}
}
break;
case OWNERS_COUNT:
{
if (!((*car_list)+i)->is_new)
{
int tmp_znach = 0;
if (string_to_int(znach[j], &tmp_znach) != 0)
return ERROR;
if (((*car_list)+i)->condition.old_car_params.owners_count != tmp_znach)
flag = false;
}
}
break;
default:
return ERROR;
break;
}
}
if (flag)
print_car_record(*((*car_list)+i));
}
if (!is_printed)
cout << "Nothing to print" << endl;
cout << endl;
return 0;
}
| true |
31c4793dbc43e16f5144f02b048789d90446d9fc | C++ | HakeT2Lab/CS246-2020 | /Exams/Exam03/exam03.cpp | UTF-8 | 2,422 | 3.265625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cctype>
#include "Vector.h"
#include "Node.h"
#include "Queue.h"
#include "Map.h"
#include "HashTable.h"
//write work here
//Question 1
std::string CommonSuffix(ds::Vector<std::string>& words){
if(words.Length() > 0){
ds::Vector<std::string> returnStr;
std::string saveWord;
int v=0;
for(int i = 0; i<words.Length(); i++){
for(int c = 0; c < words[i].length(); c++){
saveWord= words[i];
if(saveWord[c] == 'l' && saveWord[c+1]== 'y' ){
returnStr.Insert("ly");
}else{
returnStr.Insert("");
}
}
}
std::cout<<"\n"<<returnStr.ToString()<<"\n";
}
return "\0";
}
// void KeyPadWords(std::string number){
// // A=1 B=1 C=1
// //number to array
// for(int i = 0; i < number.size(); i++){
// if(number[i] == '2'){
// std::cout<<" "<<
// }
// }
// }
//question 3
ulong TotalBoundedModes(ds::Vector<ulong>& data, ulong lo, ulong hi){
if(data.Length() != 0){//one gives no mode
//keys
int n = data.Length();
int c=0;
// ulong holdmode = 0;
// ulong mode=0;
int count=0;
int savecount=0;
// int modecount=0;
//key end
for(int i =0; i < n;i++){
// if(data[c] == data[i]){
// count++;
// }
// if(i == data.Length()-1){
// // if(savecount < count){
// // std::cout<<"\n"<<savecount<<"\n";
// // }
// }
i=0;
c++;
savecount = count;
count=0;
}
}
return 0;
}
/*Problem 4
T(n)= AT(n/b) + n^k
a. T(n) = 4T(n/2) + n
by dividing case 1
A=4 B=2 k=1
log4 base 2= 2
1<2 ? yes
so:
T(n)= O(n^2)
b. T(n) = 9T(n/3) + n^2
by dividing case 1
log9 base 3 = 3
k=2
2<3 by case 3
T(n)= O(n^2)
c. T(n) = 6T(n/6) + 8
log6 base 6 = 1
k= 0
0<1
d. T(n) = T(n/5) + log (n)
e. T(n) = 2T(n/4) + lg (n)
*/
int main()
{
//1
ds::Vector<std::string> Data;
Data.Insert("Hello");
Data.Insert("Happily");
Data.Insert("Sadly");
Data.Insert("Bye");
std::cout<<"\n"<<Data.ToString()<<"\n";
// CommonSuffix(Data);
//2
// KeyPadWords("26");
ds::Vector<ulong> Numbers;
ulong target= 4;
double array[] = {7, 2, 4, 3, 2, 8, 3, 9, 3, 2, 9, 4, 2, 5, 3};
// std::cout<<"\n"<<Data.Length()<<"\n";
for(int i = 0; i< 6; i++){
Numbers.Insert(array[i]);
}
TotalBoundedModes(Numbers, 2, 9);
return 0;
}
| true |
ba74a23f61398042bb50cd1b310b9f31d2619c76 | C++ | vidalarroyo/CPSC350_assign3 | /include/GenStack.cpp | UTF-8 | 1,967 | 3.796875 | 4 | [] | no_license | // GenStack.cpp
// An implemented generic class for an array-based stack of any type.
// @author Vidal M. Arroyo
// @author arroy118@mail.chapman.edu
// @version 1.0
#include "GenStack.h"
using namespace std;
// Default constructor
template <typename E> GenStack<E>::GenStack()
{
myArray = new E[128]; //128 bytes
size = 128;
top = -1;
}
// Overloaded constructor
template <typename E> GenStack<E>::GenStack(int maxSize)
{
myArray = new E[maxSize];
size = maxSize;
top = -1;
}
// Destructor
template <typename E> GenStack<E>::~GenStack()
{
// Need to delete myArray because it was dynamically allocated
delete[] myArray;
}
template <typename E> void GenStack<E>::push(const E& e)
{
// Resize method is used instead of throwing isFull exception
if(isFull())
{
resize();
}
myArray[++top] = e;
}
template <typename E> E& GenStack<E>::pop() throw (StackEmpty)
{
if(isEmpty())
{
throw StackEmpty("Your stack is empty! No elements to pop.");
}
return myArray[top--];
}
template <typename E> const E& GenStack<E>::peek() throw (StackEmpty)
{
if(isEmpty())
{
throw StackEmpty("Your stack is empty! No elements to peek at.");
}
return myArray[top];
}
// True of top is the last element in the array
template <typename E> bool GenStack<E>::isFull()
{
return (top == size - 1);
}
template <typename E> bool GenStack<E>::isEmpty()
{
return (top == - 1);
}
template <typename E> int GenStack<E>::getSize()
{
return (top + 1);
}
template <typename E> void GenStack<E>::resize()
{
// In the resize method, I create a second array and make it double the size of the first array.
E* myBigArray = new E[size*2];
// Copying over all elements in the initial array
for (int i = 0; i < size; ++i)
{
myBigArray[i] = myArray[i];
}
// Deleting the initial array
delete[] myArray;
// Useful for future functions
size *= 2;
// myArray is now a new array with extra space
myArray = new E[size];
myArray = myBigArray;
}
| true |
fc298386673760666dd9337017039a371cfb968a | C++ | xxxajk/RTClib | /examples/RTC/RTC.ino | UTF-8 | 2,028 | 3.03125 | 3 | [] | no_license | // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h> // Needed for arduino IDE
#include <RTClib.h>
void setup() {
while(!Serial);
Serial.begin(115200);
}
void loop() {
DateTime now = RTCnow();
Serial.print(" ");
Serial.print(now.year(), DEC);
Serial.print('/');
if(now.month() < 10) Serial.print("0");
Serial.print(now.month(), DEC);
Serial.print('/');
if(now.day() < 10) Serial.print("0");
Serial.print(now.day(), DEC);
Serial.print(' ');
if(now.hour() < 10) Serial.print("0");
Serial.print(now.hour(), DEC);
Serial.print(':');
if(now.minute() < 10) Serial.print("0");
Serial.print(now.minute(), DEC);
Serial.print(':');
if(now.second() < 10) Serial.print("0");
Serial.print(now.second(), DEC);
Serial.print(" since midnight 1/1/1970 = ");
Serial.print(now.unixtime());
Serial.print("s = ");
Serial.print(now.unixtime() / 86400L);
Serial.println("d");
// calculate a date which is 7 days and 30 seconds into the future
DateTime future(now.secondstime() + (time_t)((7 * 86400L) + 30));
Serial.print("now + 7d + 30s: ");
Serial.print(future.year(), DEC);
Serial.print('/');
if(future.month() < 10) Serial.print("0");
Serial.print(future.month(), DEC);
Serial.print('/');
if(future.day() < 10) Serial.print("0");
Serial.print(future.day(), DEC);
Serial.print(' ');
if(future.hour() < 10) Serial.print("0");
Serial.print(future.hour(), DEC);
Serial.print(':');
if(future.minute() < 10) Serial.print("0");
Serial.print(future.minute(), DEC);
Serial.print(':');
if(future.second() < 10) Serial.print("0");
Serial.print(future.second(), DEC);
Serial.println();
Serial.println();
delay(1000);
} | true |
366d4ac08455329f0ed14309efe04f27fc925c12 | C++ | AlViSh/segmentation | /disjointsetforest.h | UTF-8 | 1,004 | 2.703125 | 3 | [] | no_license | #ifndef DISJOINTSETFOREST_H
#define DISJOINTSETFOREST_H
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
// Система непересекающихся множеств
struct SetNode {
int rank;
int parent;
int size;
};
// Взвешенные ребра
struct Edge {
int a;
int b;
float weight;
bool operator<( const Edge& other ) {
return weight < other.weight;
}
};
class DisjointSetForest{
public:
DisjointSetForest();
DisjointSetForest( int no_of_elements );
~DisjointSetForest();
void init( int no_of_elements );
int find( int x );
void join( int x, int y );
int size( int x );
int noOfElements();
void segmentGraph( int no_of_vertices, int no_of_edges, vector<Edge>& edges, float c );
private:
vector<SetNode> elements;
int num;
};
#endif // DISJOINTSETFOREST_H
| true |
8eed7a9cf2895eadd7f963d9e9b2a412ce9b0022 | C++ | ArturoGO28/SomethingVersion2.07 | /Hannah's Files/platform.cpp | UTF-8 | 1,651 | 2.953125 | 3 | [] | no_license | // Definition of the platform class. Includes basic one room map for the game
#include <SFML/Graphics.hpp>
#include <iostream>
using std::cin;
using std::cout;
int main (int argc, char **argv) {
sf::RenderWindow window(sf::VideoMode(640,480), "Basic Platform");
sf::RectangleShape rectangle(sf::Vector2f(128, 128));
// rectangle.setFillColor(sf::Color::Red);
// rectangle.setOrigin(64, 64);
// rectangle.setPosition(320, 240);
sf::Texture texture;
int spritex = 5;
int spritey = 6;
float xwidth = 512/13;
float ywidth = 512/13;
float xnum = ((spritex - 1) * 512) / 13;
float ynum = ((spritey - 1) * 512) / 13;
if (!texture.loadFromFile("/media/sf_EC327/groupproject/sprite_sheet1.png",
sf::IntRect(xnum, ynum, xwidth, ywidth))) {
cout << "Failed to load the sprite sheet" << '\n';
}
sf::Sprite sprite1(texture);
sf::Sprite sprite2(texture);
sf::Sprite sprite3(texture);
sf::Sprite sprite4(texture);
sf::Sprite sprite5(texture);
sprite1.setPosition(0 , 400);
sprite2.setPosition(xwidth, 400);
sprite3.setPosition((xwidth) * 2, 400);
sprite4.setPosition((xwidth) * 4 , 300);
sprite5.setPosition((xwidth) * 5 , 300);
// Create the game loop
while (window.isOpen()) {
sf::Event event;
// Create the event loop polling events
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear(sf::Color::Black);
// window.draw(rectangle);
window.draw(sprite1);
window.draw(sprite2);
window.draw(sprite3);
window.draw(sprite4);
window.draw(sprite5);
window.display();
}
return 0;
} | true |
e8c5bc34056a0b998c4d826c5e3d7c70c4f0b7fd | C++ | EvaCosta/DadosAbertos | /DadosAbertos/Investidor.h | UTF-8 | 1,378 | 2.59375 | 3 | [] | no_license | #ifndef INVESTIDOR_H
#define INVESTIDOR_H
#include<time.h>
#include<string>
using namespace std;
class Investidor {
public:
Investidor();
Investidor(int codigo, int idade, string dataDeAdesao, string estadoCivil, string genero,
string profissao, string cidadeInvestidor, string paisInvestidor, string uf, bool situacaoConta, bool operou1Ano);
void setCodigo(int codigo);
void setIdade(int idade);
void setDataDeAdesao(string dataDeAdesao);
void setEstadoCivil(string estadoCivil);
void setGenero(string genero);
void setProfissao(string profissao);
void setCidadeInvestidor(string cidadeInvestidor);
void setPaisInvestidor(string paisInvestidor);
void setUf(string uf);
void setSituacaoConta(string situacaoConta);
void setOperou1Ano(string operou1Ano);
void setLinhaCompleta(char *linha);
int getCodigo();
int getIdade();
string getDataDeAdesao();
string getEstadoCivil();
string getGenero();
string getProfissao();
string getCidadeInvestidor();
string getPaisInvestidor();
string getUf();
string getSituacaoConta();
string getOperou1Ano();
string getLinhaCompleta();
private:
int codigo;
int idade;
string dataDeAdesao;
string estadoCivil, genero, profissao, cidadeInvestidor, paisInvestidor;
string uf;
string situacaoConta, operou1Ano;
string linhaCompleta;
};
#endif // !INVESTIDOR_H
| true |
ddd2316b75486f92512932f24447bd133da10322 | C++ | btaripraba21/final-project | /projekalgo.cpp | UTF-8 | 3,340 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
#define pemrograman 8000
#define sastra 7000
#define novel 9000
const int denda = 1000;
int main() {
char nama[30], id_pgw[15], no_tlp[15], nama_plg[31], judul[15], a;
float banyak, status;
int kode, hasil1, hasil2, hasil3, jenis, pilih;
int array[8] = {8}, arr[7] = {7}, ray[9] = {9};
int c = 0;
cout<<"====================================================";
cout<<"\nNAMA : Btari Prabaningrum & Endah Sulistyo Ningrum";
cout<<"\nNPM : 1910631250010 & 1910631250014";
cout<<"\nKELAS : 1A SI";
cout<<"\nMata Kuliah : Pemrograman";
cout<<"\nProgram : Tugas Uas / Final Project";
cout<<"\n======================================================";
cout<<endl;
cout<<"\n========PERPUSTAKAAN NINGRUM=========\n";
cout<<"==============Daftar Buku============\n";
cout<<"01. Pemrograman =";
for (int c=0; c<4; c++)
cout<<array[c];
cout<<endl;
cout<<"02. Sastra =";
for (int c=0; c<4; c++)
cout<<arr[c];
cout<<endl;
cout<<"03. Novel =";
for (int c=0; c<4; c++)
cout<<ray[c];
cout<<"\==============================\n";
cout<<endl;
cout<<"\n Nama Pegawai : "; cin>> nama;
cout<<"\n ID Pegawai : "; cin>>id_pgw;
cout<<"\n Selamat Datang ";
cout<<"\n Di Perpustakaan Ningrum \n";
cout<<"\n Nama Pelanggan : "; cin>>nama_plg;
cout<<"\n No telepon Pelanggan : "; cin>>no_tlp;
cout<<"\n Banyak Pinjam Buku : "; cin>>banyak;
cout<<"kode BUKU : \n 01. Pemrograman \n 02. Sastra \n 03. Novel";
cout<<"\nKode Buku : "; cin>>kode;
cout<<"Pilih jenis BUKU : \n1. Pemrogram \n2. Sastra \n3. Novel";
cout<<"\nPilih Nomor Di Atas Untuk Menentukan Kode Buku :";cin>>pilih;
switch(pilih){
case 1:
if(kode==01) {
cout<<"\n Tarif Sewa Rp. 8000\n";
cout<<" Jenis Buku Pemrograman\n";
cout<<" Penyewa Dengan Nama " <<nama_plg;
hasil1=banyak*pemrograman;
cout<<"\n\n Jumlah Bayar Penyewaan Sebesar Rp. " <<hasil1<<endl;
}else{
cout<<"\n WARNING!!! \n Kode Buku Yang Anda Masukkan Salah! \n Silahkan Ulangi Kembali!\n";
}
break;
case 2:
if(kode==02){
cout<<" Tarif Sewa Rp.7000\n";
cout<<" Jenis Buku Sastra\n";
cout<<" Penyewa Dengan Nama " <<nama_plg;
hasil2=banyak*sastra;
cout<<"n\n Jumlah Bayar Penyewaan Sebesar Rp. " <<hasil2<<endl;
}else{
cout<<"\n WARNING!!! \n Kode Buku Yang Anda Masukkan Salah! \n SIlahkan Ulangi Kembali\n";
}
break;
case 3:
if(kode==03){
cout<<" Tarif Sewa Rp. 9000\n";
cout<<" Jenis Buku Novel\n";
cout<<" Penyewa Dengan Nama " <<nama_plg;
hasil3=banyak*novel;
cout<<"n\n Jumlah Bayar Penyewaan Sebesar Rp. " <<hasil3<<endl;
}else{
cout<<"\n WARNING!!! \n Kode Buku Yang Anda Masukkan Salah! \n Silahkan Ulangi Kembali\n";
}
break;
default:
cout<<"--Mohon Maaf Pilihan Yang Anda Masukkan Tidak Ada--" <<endl;
}
do {
cout<<"\n ==============================";
cout<<"\n Terimakasih Atas Kunjungannya.";
cout<<"\n ==============================";
c++;
}while (c<3);
return 0;
}
| true |
7bc6829106a29475a609f56a666458d48fc5493e | C++ | sunfish-shogi/coconut | /coconut/widgets/list_view/BaseListView.cpp | UTF-8 | 8,778 | 2.71875 | 3 | [
"Zlib"
] | permissive | //
// BaseListView.cpp
// coconut
//
// Created by Kubo Ryosuke on 2013/09/17.
//
//
#include "BaseListView.h"
#include <cfloat>
USING_NS_CC;
namespace coconut {
bool BaseListView::init(ListDirection direction, const Size& viewSize,
ListType type, int cacheSize, float space, bool clipping) {
ScrollDirection scrollDir;
switch (direction) {
case ListDirection::HORIZONTAL:
scrollDir = ScrollDirection::HORIZONTAL;
break;
case ListDirection::VERTICAL:
scrollDir = ScrollDirection::VERTICAL;
break;
default: CCASSERT(false, "invalid list direction.");
}
_direction = direction;
_type = type;
_cacheSize = cacheSize;
_space = space;
_contentRect.origin = Point(0, -viewSize.height);
_contentRect.size = viewSize;
if (!ScrollLayer::init(viewSize, _contentRect, scrollDir, clipping)) {
return false;
}
return true;
}
void BaseListView::slScrolled() {
refresh();
}
void BaseListView::slDetouch(const Point& position) {
if (_type == ListType::PAGE) {
pageNearest();
}
}
void BaseListView::slFlickWithDetouch(const Point& start, const Point& velocity) {
switch (_type) {
case ListType::TILE:
ScrollLayer::slFlickWithDetouch(start, velocity);
break;
case ListType::PAGE:
switch (_direction) {
case ListDirection::HORIZONTAL:
if (velocity.x <= 0.0f) {
pageNext();
} else {
pagePrev();
}
break;
case ListDirection::VERTICAL:
if (velocity.y >= 0.0f) {
pageNext();
} else {
pagePrev();
}
break;
default:
CCASSERT(false, "invalid direction.");
}
break;
default:
CCASSERT(false, "invalid list type.");
}
}
void BaseListView::pageNearest() {
const Rect& visibleRect = getVisibleRect();
const Point visibleCenter(visibleRect.getMidX(), visibleRect.getMidY());
Element* element = nullptr;
float distance = FLT_MAX;
for (auto ite = _elements.begin(); ite != _elements.end(); ite++) {
float d = visibleCenter.getDistance((*ite).node->getPosition());
if (d < distance) {
element = &(*ite);
distance = d;
}
}
if (element != nullptr) {
pageTo(element->node, element->index);
}
}
void BaseListView::pagePrev() {
if (!_elements.empty()) {
pageTo(_elements.front().node, _elements.front().index);
}
}
void BaseListView::pageNext() {
if (!_elements.empty()) {
pageTo(_elements.back().node, _elements.back().index);
}
}
void BaseListView::pageTo(Node* node, int index) {
const Rect& rect = getRect(node, index);
scrollTo(Point(rect.getMinX(), rect.getMinY()), 0.3f);
}
Size BaseListView::getSize(int index) {
switch (_type) {
case ListType::TILE:
return cellSize(index);
case ListType::PAGE:
return getViewSize();
default:
CCASSERT(false, "invalid list type.");
}
}
Rect BaseListView::getRect(Node* node, int index) {
const Point& pos = node->getPosition();
const Size& size = getSize(index);
return Rect(pos.x - size.width / 2.0f, pos.y - size.height / 2.0f,
size.width, size.height);
}
void BaseListView::refresh() {
const Rect& visible = getVisibleRect();
bool topOk = false;
bool endOk = false;
int topIdx, endIdx;
Rect top, end;
if (!_elements.empty()) {
top = getRect(_elements.front().node, _elements.front().index);
end = getRect(_elements.back().node, _elements.back().index);
topOk = top.intersectsRect(visible);
endOk = end.intersectsRect(visible);
topIdx = _elements.front().index;
endIdx = _elements.back().index;
}
// clean
clean(visible);
if (!topOk && !endOk) {
Rect topLeft = Rect::ZERO;
topLeft.origin = getTopLeftCorner();
refreshAfter(visible, topLeft, -1, true);
} else {
if (topOk) {
refreshBefore(visible, top, topIdx);
}
if (endOk) {
refreshAfter(visible, end, endIdx);
}
}
// resize
bool resized = false;
if (!_elements.empty()) {
resized |= resize(_elements.front().node, _elements.front().index);
if (_elements.size() != 1) {
resized |= resize(_elements.back().node, _elements.back().index);
}
}
if (resized) {
resizeContent(_contentRect);
}
}
void BaseListView::refreshBefore(const Rect& visible, const Rect& prev, int index) {
Rect r = prev;
for (index--; index >= 0; index--) {
const Size& size = getSize(index);
float space = (!r.size.equals(Size::ZERO) ? _space : 0.0f);
if (_direction == ListDirection::HORIZONTAL) {
r = Rect(r.origin.x - (size.width + space),
r.getMaxY() - size.height,
size.width,
size.height);
} else {
r = Rect(r.origin.x,
r.origin.y + (r.size.height + space),
size.width,
size.height);
}
if (visible.intersectsRect(r)) {
Element element;
element.index = index;
element.node = activateCellOnCache(index);
_elements.push_front(element);
element.node->setPosition(Point(r.getMidX(), r.getMidY()));
} else {
return;
}
}
}
void BaseListView::refreshAfter(const Rect& visible, const Rect& prev, int index, bool force) {
Rect r = prev;
for (index++; index < cellCount(); index++) {
const Size& size = getSize(index);
float space = (!r.size.equals(Size::ZERO) ? _space : 0.0f);
if (_direction == ListDirection::HORIZONTAL) {
r = Rect(r.origin.x + (r.size.width + space),
r.getMaxY() - size.height,
size.width,
size.height);
} else {
r = Rect(r.origin.x,
r.origin.y - (size.height + space),
size.width,
size.height);
}
if (visible.intersectsRect(r)) {
Element element;
element.index = index;
element.node = activateCellOnCache(index);
_elements.push_back(element);
element.node->setPosition(Point(r.getMidX(), r.getMidY()));
} else if (!force) {
return;
}
}
}
bool BaseListView::resize(Node* node, int index) {
Rect rect = getRect(node, index);
Rect prev = _contentRect;
switch (_direction) {
case ListDirection::HORIZONTAL:
if (index == 0) {
_contentRect.origin.x = rect.getMinX();
} else {
_contentRect.origin.x = MIN(_contentRect.origin.x, rect.getMinX() - (_space + 1.0f));
}
_contentRect.size.width += prev.origin.x - _contentRect.origin.x;
if (index == cellCount() - 1) {
_contentRect.size.width = rect.getMaxX() - _contentRect.origin.x;
} else {
_contentRect.size.width = MAX(_contentRect.size.width, rect.getMaxX() - _contentRect.origin.x + (_space + 1.0f));
}
break;
case ListDirection::VERTICAL:
if (index == cellCount() - 1) {
_contentRect.origin.y = rect.getMinY();
} else {
_contentRect.origin.y = MIN(_contentRect.origin.y, rect.getMinY() - (_space + 1.0f));
}
_contentRect.size.height += prev.origin.y - _contentRect.origin.y;
if (index == 0) {
_contentRect.size.height = rect.getMaxY() - _contentRect.origin.y;
} else {
_contentRect.size.height = MAX(_contentRect.size.height, rect.getMaxY() - _contentRect.origin.y + (_space + 1.0f));
}
break;
default:
CCASSERT(false, "invalid direction.");
}
return !_contentRect.equals(prev);
}
void BaseListView::clean(const Rect& visible) {
enum { BEFORE, VISIBLE, AFTER } state = BEFORE;
for (auto ite = _elements.begin(); ite != _elements.end();) {
bool erase = false;
if ((*ite).index >= cellCount()) {
erase= true;
} else if (state == AFTER) {
erase = true;
} else if (visible.intersectsRect(getRect(ite->node, ite->index))) {
state = VISIBLE;
} else {
erase = true;
if (state == VISIBLE) { state = AFTER; }
}
if (erase) {
hideCellOnCache(ite->index, ite->node);
ite = _elements.erase(ite);
continue;
}
ite++;
}
}
Node* BaseListView::activateCellOnCache(int index) {
for (auto ite = _cache.begin(); ite != _cache.end(); ite++) {
Element element = (*ite);
if (element.index == index) {
_cache.erase(ite);
return element.node;
}
}
Node* node = activateCell(index);
addChild(node);
return node;
}
void BaseListView::hideCellOnCache(int index, Node* cell) {
Element element;
element.index = index;
element.node = cell;
_cache.push_front(element);
while (_cache.size() > _cacheSize) {
Element& old = _cache.back();
hideCell(old.index, old.node);
removeChild(old.node);
_cache.pop_back();
}
}
Node* BaseListView::getCell(int index) {
for (auto ite = _elements.begin(); ite != _elements.end(); ite++) {
if ((*ite).index == index) {
return (*ite).node;
}
}
for (auto ite = _cache.begin(); ite != _cache.end(); ite++) {
if ((*ite).index == index) {
return (*ite).node;
}
}
return nullptr;
}
};
| true |
e3c4ce2ddbd25efb0c9e2f558d2387e3a1774d9e | C++ | invzhi/vtab | /disk/disk_test.cc | UTF-8 | 541 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "disk/disk.h"
#include <cstring>
#include "gtest/gtest.h"
TEST(DiskTest, SampleTest) {
// create file
std::ofstream f;
f.open("disktest.db");
f.close();
Page page;
std::memset(page.GetData(), 1, PAGE_SIZE);
auto disk = new Disk("disktest.db");
disk->WritePage(0, page.GetData());
delete disk;
Page page2;
auto disk2 = new Disk("disktest.db");
disk->ReadPage(0, page2.GetData());
delete disk2;
EXPECT_EQ(0, std::memcmp(page.GetData(), page2.GetData(), PAGE_SIZE));
std::remove("disktest.db");
} | true |
4f6e5f701249fcfcc11d5ab7979ce62417a1ff62 | C++ | ogre/flexrender | /src/worker/ray_queue.cpp | UTF-8 | 3,451 | 3.1875 | 3 | [
"MIT"
] | permissive | #include "ray_queue.hpp"
#include <cassert>
#include "types.hpp"
#include "utils.hpp"
namespace fr {
RayQueue::RayQueue(Camera* camera, RenderStats* stats) :
_camera(camera),
_stats(stats),
_intersect_front(nullptr),
_intersect_back(nullptr),
_intersect_size(0),
_illuminate_front(nullptr),
_illuminate_back(nullptr),
_illuminate_size(0),
_light_front(nullptr),
_light_back(nullptr),
_light_size(0),
_paused(false) {}
RayQueue::~RayQueue() {
FatRay* ray = nullptr;
while (_light_front != nullptr) {
ray = _light_front;
_light_front = ray->next;
delete ray;
}
while (_illuminate_front != nullptr) {
ray = _illuminate_front;
_illuminate_front = ray->next;
delete ray;
}
while (_intersect_front != nullptr) {
ray = _intersect_front;
_intersect_front = ray->next;
delete ray;
}
}
void RayQueue::Push(FatRay* ray) {
assert(ray != nullptr);
switch (ray->kind) {
case FatRay::Kind::INTERSECT:
if (_intersect_back != nullptr) {
_intersect_back->next = ray;
} else {
_intersect_front = ray;
}
ray->next = nullptr;
_intersect_back = ray;
_intersect_size++;
break;
case FatRay::Kind::ILLUMINATE:
if (_illuminate_back != nullptr) {
_illuminate_back->next = ray;
} else {
_illuminate_front = ray;
}
ray->next = nullptr;
_illuminate_back = ray;
_illuminate_size++;
break;
case FatRay::Kind::LIGHT:
if (_light_back != nullptr) {
_light_back->next = ray;
} else {
_light_front = ray;
}
ray->next = nullptr;
_light_back = ray;
_light_size++;
break;
default:
TERRLN("Pushed unknown ray kind into ray queue.");
break;
}
}
FatRay* RayQueue::Pop() {
FatRay* ray = nullptr;
// Pull from the light queue first.
ray = _light_front;
if (ray != nullptr) {
_light_front = ray->next;
ray->next = nullptr;
if (_light_front == nullptr) {
_light_back = nullptr;
}
_light_size--;
return ray;
}
// Pull from the illumination queue if the light queue is empty.
ray = _illuminate_front;
if (ray != nullptr) {
_illuminate_front = ray->next;
ray->next = nullptr;
if (_illuminate_front == nullptr) {
_illuminate_back = nullptr;
}
_illuminate_size--;
return ray;
}
// Pull from the intersection queue if the light queue is empty.
ray = _intersect_front;
if (ray != nullptr) {
_intersect_front = ray->next;
ray->next = nullptr;
if (_intersect_front == nullptr) {
_intersect_back = nullptr;
}
_intersect_size--;
return ray;
}
// If primary ray generation is paused, we're done.
if (_paused) {
return nullptr;
}
// Generate a primary ray if the intersection queue is empty.
ray = new FatRay;
if (_camera->GeneratePrimary(ray)) {
_stats->intersects_produced++;
return ray;
}
// No more primary rays.
delete ray;
return nullptr;
}
} // namespace fr
| true |
e4c9faae74cc383e58d0cea753fc3f7b6a6bbb15 | C++ | vitoremanuelpereirasilva/INF110 | /aula/valormedio.cpp | UTF-8 | 252 | 3.15625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int a,b, resto ;
cin>> a >> b;
resto = (a+b)%2;
if(resto== 0){
cout<< "valor medio: " << (a+b)/2 << endl;
}else{
cout<< "Nao existe valor medio inteiro!"<< endl;
}
return 0;
}
| true |
f015998087b442002eab8bbdb50bd304857e81ed | C++ | fanll4523/algorithms | /Part13算法竞赛宝典/第一部资源包/第七章 升级考核/第一天/11.cpp | UTF-8 | 214 | 3.171875 | 3 | [
"LicenseRef-scancode-mulanpsl-1.0-en",
"MulanPSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # include <iostream>
using namespace std;
void num()
{
int x,y;
int a=15,b=10;
x=a-b;y=a+b;
}
int x,y;
int main()
{
int a=7,b=5;
x=a+b;y=a-b;
num();
cout<<x<<","<<y<<endl;
getchar();
}
| true |
18a34a52a5bc49757444a65e8c6a54f65a481b27 | C++ | tyoma/micro-profiler | /frontend/tests/HierarchyAlgorithmsTests.cpp | UTF-8 | 9,184 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include <frontend/hierarchy.h>
#include <functional>
#include <test-helpers/helpers.h>
#include <ut/assert.h>
#include <ut/test.h>
using namespace std;
namespace micro_profiler
{
namespace tests
{
namespace
{
struct node
{
unsigned id, parent;
};
struct hierarchy_access_node
{
hierarchy_access_node(function<const node *(unsigned id)> by_id_, bool prohibit_total_less_ = true)
: by_id(by_id_), prohibit_total_less(prohibit_total_less_)
{ }
bool same_parent(const node &lhs, const node &rhs) const
{ return lhs.parent == rhs.parent; }
vector<unsigned> path(const node &n) const
{
vector<unsigned> path;
for (auto item = &n; item; item = by_id(item->parent))
path.push_back(item->id);
reverse(path.begin(), path.end());
return path;
}
const node &lookup(unsigned id) const
{
auto n = by_id(id);
assert_not_null(n);
return *n;
}
bool total_less(const node &lhs, const node &rhs) const
{
assert_is_false(prohibit_total_less);
return lhs.id < rhs.id;
}
const function<const node *(unsigned id)> by_id;
bool prohibit_total_less;
};
}
begin_test_suite( HierarchyTraitsTests )
struct unknown_struct
{
int a;
};
test( AllElementsHaveTheSameParentByDefault )
{
// INIT
unknown_struct u1 = { 17 }, u2 = { 181911 };
// ACT / ASSERT
assert_is_true(hierarchy_plain<unknown_struct>().same_parent(u1, u2));
assert_is_true(hierarchy_plain<unknown_struct>().same_parent(u2, u1));
assert_is_true(hierarchy_plain<unknown_struct>().same_parent(u1, u1));
assert_is_false(hierarchy_plain<unknown_struct>().total_less(u1, u1));
assert_is_true(hierarchy_plain<unknown_struct>().same_parent(u1, u2));
assert_is_true(hierarchy_plain<unknown_struct>().same_parent(u2, u1));
assert_is_true(hierarchy_plain<unknown_struct>().same_parent(u1, u1));
assert_is_false(hierarchy_plain<unknown_struct>().total_less(u1, u1));
assert_is_true(hierarchy_plain<int>().same_parent(11, 12));
assert_is_true(hierarchy_plain<int>().same_parent(12, 12));
assert_is_false(hierarchy_plain<int>().total_less(11, 12));
}
end_test_suite
begin_test_suite( HierarchyAlgorithmsTests )
typedef pair<const node *, const node *> log_entry;
vector<log_entry> log;
int result;
function<int (const node &lhs, const node &rhs)> less()
{
return [this] (const node &lhs, const node &rhs) -> int {
this->log.push_back(make_pair(&lhs, &rhs));
return result;
};
}
test( ComparisonsForPlainTypesAreDoneViaComparatorsProvided )
{
// INIT
int result_ = -1;
vector< pair<double, double> > log_;
auto p = [&result_, &log_] (double lhs, double rhs) {
return log_.push_back(make_pair(lhs, rhs)), result_;
};
// ACT / ASSERT
assert_is_true(hierarchical_less(hierarchy_plain<double>(), p, 0.1, 0.2));
// ASSERT
assert_equal(plural + make_pair(0.1, 0.2), log_);
// INIT
result_ = -100000;
// ACT / ASSERT
assert_is_true(hierarchical_less(hierarchy_plain<double>(), p, 0.1, 0.3));
// INIT
result_ = 1;
// ACT / ASSERT
assert_is_false(hierarchical_less(hierarchy_plain<double>(), p, 0.3, 0.9));
// INIT
result_ = 1000;
// ACT / ASSERT
assert_is_false(hierarchical_less(hierarchy_plain<double>(), p, 0.1, 0.05));
// INIT
result_ = 0;
// ACT / ASSERT
assert_is_false(hierarchical_less(hierarchy_plain<double>(), p, 0.1, 0.108));
assert_is_false(hierarchical_less(hierarchy_plain<double>(), p, 0.108, 0.1));
// ASSERT
assert_equal(plural
+ make_pair(0.1, 0.2)
+ make_pair(0.1, 0.3)
+ make_pair(0.3, 0.9)
+ make_pair(0.1, 0.05)
+ make_pair(0.1, 0.108)
+ make_pair(0.108, 0.1), log_);
}
test( NormalizingRecordsAtTheSameParentLeavesThemTheSame )
{
// INIT
const node data[] = {
{ 1, 0 },
{ 2, 0 },
{ 3, 2 },
{ 4, 2 },
{ 5, 4 },
{ 6, 4 },
{ 7, 4 },
{ 8, 0 },
{ 9, 2 },
};
auto lookup_fail = [] (unsigned) -> const node * {
assert_is_false(true);
return nullptr;
};
hierarchy_access_node acc(lookup_fail);
result = 1;
// ACT / ASSERT
assert_is_false(hierarchical_less(acc, less(), data[0], data[1]));
// ASSERT
log_entry reference1[] = { make_pair(data + 0, data + 1), };
assert_equal(reference1, log);
// INIT
result = -1;
log.clear();
// ACT
assert_is_true(hierarchical_less(acc, less(), data[2], data[3]));
// ASSERT
log_entry reference2[] = { make_pair(data + 2, data + 3), };
assert_equal(reference2, log);
// INIT
log.clear();
// ACT
assert_is_true(hierarchical_less(acc, less(), data[2], data[8]));
// ASSERT
log_entry reference3[] = { make_pair(data + 2, data + 8), };
assert_equal(reference3, log);
// INIT
log.clear();
// ACT
hierarchical_less(acc, less(), data[4], data[6]);
// ASSERT
log_entry reference4[] = { make_pair(data + 4, data + 6), };
assert_equal(reference4, log);
}
test( SameLevelComparisonFallsBackToTotalLessWhenValuesAreEquivalent )
{
// INIT
const node data[] = {
{ 1, 0 },
{ 2, 0 },
{ 3, 0 },
};
auto lookup_fail = [] (unsigned) -> const node * {
assert_is_false(true);
return nullptr;
};
hierarchy_access_node acc(lookup_fail, false);
result = 0;
// ACT
assert_is_true(hierarchical_less(acc, less(), data[0], data[1]));
assert_is_true(hierarchical_less(acc, less(), data[0], data[2]));
assert_is_false(hierarchical_less(acc, less(), data[2], data[1]));
assert_is_false(hierarchical_less(acc, less(), data[2], data[2]));
}
test( NormalizingRecordsWhenOneRecordIsDeeperMovesItUp )
{
// INIT
const node data[] = {
{ 1, 0 },
{ 2, 0 },
{ 3, 2 },
{ 4, 2 },
{ 5, 4 },
{ 6, 4 },
{ 7, 4 },
{ 8, 7 },
{ 9, 2 },
};
hierarchy_access_node acc([&] (unsigned id) -> const node * { return id ? data + (id - 1) : nullptr; });
result = -1;
// ACT
assert_is_true(hierarchical_less(acc, less(), data[2], data[7]));
// ASSERT
log_entry reference1[] = { make_pair(data + 2, data + 3), };
assert_equal(reference1, log);
// INIT
result = 1;
log.clear();
// ACT
assert_is_false(hierarchical_less(acc, less(), data[7], data[2]));
// ASSERT
log_entry reference2[] = { make_pair(data + 3, data + 2), };
assert_equal(reference2, log);
// INIT
log.clear();
// ACT
assert_is_false(hierarchical_less(acc, less(), data[0], data[2]));
// ASSERT
log_entry reference3[] = { make_pair(data + 0, data + 1), };
assert_equal(reference3, log);
// INIT
log.clear();
// ACT
assert_is_false(hierarchical_less(acc, less(), data[2], data[0]));
// ASSERT
log_entry reference4[] = { make_pair(data + 1, data + 0), };
assert_equal(reference4, log);
}
test( ComparisonOfNormalizedRecordsFallsBackToTotalLess )
{
// INIT
const node data[] = {
{ 1, 0 },
{ 2, 1 },
{ 3, 2 },
{ 4, 1 },
{ 5, 0 },
{ 6, 5 },
};
hierarchy_access_node acc([&] (unsigned id) -> const node * { return id ? data + (id - 1) : nullptr; }, false);
result = 0;
// ACT
assert_is_true(hierarchical_less(acc, less(), data[2], data[3]));
assert_is_false(hierarchical_less(acc, less(), data[3], data[2]));
assert_is_true(hierarchical_less(acc, less(), data[2], data[5]));
assert_is_false(hierarchical_less(acc, less(), data[5], data[2]));
}
test( NormalizingRecordsMovesPointersToCommonParent )
{
// INIT
const node data[] = {
{ 1, 0 },
{ 2, 0 },
{ 3, 2 },
{ 4, 2 },
{ 5, 3 },
{ 6, 4 },
{ 7, 4 },
{ 8, 5 },
{ 9, 6 },
};
hierarchy_access_node acc([&] (unsigned id) -> const node * { return id ? data + (id - 1) : nullptr; });
result = -1;
// ACT
assert_is_true(hierarchical_less(acc, less(), data[4], data[5]));
// ASSERT
log_entry reference1[] = { make_pair(data + 2, data + 3), };
assert_equal(reference1, log);
// INIT
log.clear();
// ACT
assert_is_true(hierarchical_less(acc, less(), data[8], data[7]));
// ASSERT
log_entry reference2[] = { make_pair(data + 3, data + 2), };
assert_equal(reference2, log);
}
test( ChildAlwaysGreaterThanTheParent )
{
// INIT
const node data[] = {
{ 1, 0 },
{ 2, 1 },
{ 3, 2 },
{ 4, 3 },
};
hierarchy_access_node acc([&] (unsigned id) -> const node * { return id ? data + (id - 1) : nullptr; });
// ACT / ASSERT
assert_is_true(hierarchical_less(acc, less(), data[0], data[3]));
assert_is_false(hierarchical_less(acc, less(), data[3], data[0]));
assert_is_true(hierarchical_less(acc, less(), data[1], data[2]));
assert_is_false(hierarchical_less(acc, less(), data[2], data[0]));
// ASSERT
assert_is_empty(log);
}
end_test_suite
}
}
| true |
494fb016512eee615410e2e993ff8b634c80a79a | C++ | wyy998/PAT-practise | /1009.cpp | GB18030 | 800 | 3.203125 | 3 | [] | no_license | /*Created in 2017-5-21 14:44 UTC+8
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int i=0,j=0;
getline(cin,str);//ʹgetlineȡһдոַ
int space[81] = { 0 };//ոλ
while(str[i]!='\0')
{
if (str[i] == ' ')
{
//if (str[i++] == ' ')
//return 0;
space[j++] = i; //¼ոλ
}
i++;
}
j--; //ȥӵһ
while (j >= -1)
{
if (j == -1)//ոʱ
{
i = 0;
j--;
}
else //пոʱƶһո+1
i = space[j--] + 1;
while (str[i] != '\0'&&str[i] != ' ')//һ
{
cout << str[i];
i++;
}
if (j > -2)//滹еӿո
cout << ' ';
}
system("pause");
return 0;
} | true |
67d7feadab0e641aedf44455a4fb04e12805d112 | C++ | CodyHarsh/Project-Euler-Solutions | /0017/number_letter_counts.cpp | UTF-8 | 3,208 | 3.96875 | 4 | [] | no_license | /*
Problem 17
If the numbers 1 to 5 are written out in words: one, two, three, four, five,then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)
contains 23 letters and 115 (one hundred and fifteen) contains 20 letters.
The use of "and" when writing out numbers is in compliance with British usage.
Answer : 21124
*/
/*
TIPS:
1-20 -> Unique names
20-99 -> [number%10]-ty [numberName(1-9)]
e.g. Twen-ty One,
Thir-ty Two,
Six-ty Nine
100-999 -> [number%100] hunderd and [numberName(number%100)]
|______________________|
|
Done recursively as this part is now essentially either
numberName(1-20) case or numberName(20-999) case
e.g. Four hundred and Twenty
Seven hundred and Eighty Four
We can see that after 20 names start repeating in a pattern .
Hundreds, Thousands, millions, billions, trillions and quadrillions
all follow a similar pattern, so it can be done recursively.
(As a bonus, this solution scales to higher values as well.)
In the end we add 11 since we have only accounted for
numbers 1-999 and 1000 (One Thousand) is still left.
It has 11 letters excluding the space.
*/
//#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // for remove()
using namespace std;
string digitName(int digit);
string teenName(int number);
string tensName(int number);
string intName(int number);
vector<string> ones{"","one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
vector<string> teens{"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen","sixteen", "seventeen", "eighteen", "nineteen"};
vector<string> tens{"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
string numberName(int number){
if(number<10){
return ones[number];
}
else if(number < 20){
return teens[number-10];
}
else if(number < 100){
return tens[number/10] + ( (number%10 != 0) ? " "+numberName(number%10) : "");
}
else if(number<1000){
return numberName(number/100) + " hundred" + ( (number%100 != 0) ? " and "+numberName(number%100) : "" );
}
else {
return "Number greater than 1000 !";
}
}
string removeSpaces(string s){
int l = s.length(); // original length
int c = count(s.begin(), s.end(),' '); // counting the number of whitespaces
remove(s.begin(), s.end(),' '); // removing all the whitespaces
s.resize(l - c); // resizing the string to l-c
return s;
}
int main(){
int n = 1000;
int one_thousand_string_length = 11; // One Thousand -> 11 letters excluding the space
int sum_of_names = 0;
for(int i=1; i<n; i++){
string number_name_no_space = removeSpaces(numberName(i));
sum_of_names += number_name_no_space.length();
}
cout<<sum_of_names+one_thousand_string_length<<endl; // Add length of 1000 to get final answer
return 0;
}
| true |
f9335122a1c77fcf4e4ddb6e92d96e0e7b0e40d5 | C++ | yRezaei/spatial-partitioning | /include/aabb.hpp | UTF-8 | 1,695 | 3.46875 | 3 | [
"MIT"
] | permissive | #ifndef AABB_HPP
#define AABB_HPP
#include <glm/glm.hpp>
#include "point.hpp"
/**
* @brief Axis-Aligned Bounding Box for representing the boundery/rect.
*
*/
struct AABB
{
AABB() : cx(0.0),
cy(0.0),
hw(1.0),
hh(1.0)
{
}
AABB(double center_x, double center_y, double half_width, double half_height)
: cx(center_x), cy(center_y), hw(half_width), hh(half_height)
{
}
AABB(const AABB &a)
: cx(a.cx), cy(a.cy), hw(a.hw), hh(a.hh)
{
}
void operator=(const AABB &a)
{
cx = a.cx;
cy = a.cy;
hw = a.hw;
hh = a.hh;
}
double cx; // center x
double cy; // center y
double hw; // half width
double hh; // half height
};
/**
* @brief Checks wether the AABB contains the point.
*
* @param a The AABB
* @param p The point
* @return true If the point is inside the AABB
* @return false If the point is not inside the AABB
*/
inline bool does_contain(const AABB &a, const Point2D &p)
{
return (double)p.x <= a.cx + a.hw &&
(double)p.x >= a.cx - a.hw &&
(double)p.y <= a.cy + a.hh &&
(double)p.y >= a.cy - a.hh;
}
/**
* @brief Checks wether the two AABB do overlap
*
* @param a The first AABB
* @param b The second AABB
* @return true IF two AABBs do overlap
* @return false IF two AABBs do not overlap
*/
inline bool do_overlap(const AABB &a, const AABB &b)
{
return !(a.cx - a.hw > b.cx + b.hw ||
a.cx + a.hw < b.cx - b.hw ||
a.cy - a.hh > b.cy + b.hh ||
a.cy + a.hh < b.cy - b.hh);
}
#endif // !AABB_HPP | true |
393958cbac84d9fe1850bfb6b7d6742545a7ab72 | C++ | acorg/acmacs-chart-2 | /cc/point-index-list.hh | UTF-8 | 5,872 | 2.71875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "acmacs-base/named-type.hh"
#include "acmacs-base/rjson-v2.hh"
#include "acmacs-base/indexes.hh"
#include "acmacs-base/algorithm.hh"
// ----------------------------------------------------------------------
namespace acmacs::chart
{
// sorted list of indexes
class PointIndexList : public acmacs::named_vector_t<size_t, struct chart_PointIndexList_tag_t>
{
public:
using difference_type = std::vector<size_t>::difference_type;
using base_t = acmacs::named_vector_t<size_t, struct chart_PointIndexList_tag_t>;
using const_iterator = std::vector<size_t>::const_iterator;
using base_t::named_vector_t;
PointIndexList(const PointIndexList& src) : base_t::named_vector_t(src.size()) { std::copy(std::begin(src), std::end(src), begin()); }
PointIndexList(PointIndexList&& src) : base_t::named_vector_t(src.size()) { std::move(std::begin(src), std::end(src), begin()); }
PointIndexList& operator=(const PointIndexList& src) = default;
PointIndexList& operator=(PointIndexList&& src) = default;
PointIndexList(const rjson::value& src) : base_t::named_vector_t(src.size()) { rjson::copy(src, begin()); }
PointIndexList(std::initializer_list<size_t> src) : base_t::named_vector_t{src} {}
template <typename Iter> PointIndexList(Iter first, Iter last) : base_t::named_vector_t(static_cast<size_t>(last - first))
{
std::copy(first, last, begin());
std::sort(begin(), end());
}
template <typename Iter, typename Convert> PointIndexList(Iter first, Iter last, Convert convert) : base_t::named_vector_t(static_cast<size_t>(last - first))
{
std::transform(first, last, begin(), convert);
std::sort(begin(), end());
}
template <typename Iter, typename Predicate, typename Convert>
PointIndexList(Iter first, Iter last, Predicate predicate, Convert convert) : base_t::named_vector_t(static_cast<size_t>(last - first))
{
acmacs::transform_if(first, last, begin(), predicate, convert);
std::sort(begin(), end());
}
template <typename Iter, typename Predicate, typename Convert>
PointIndexList(Iter first, Iter last, size_t number_of_points, Predicate predicate, Convert convert) : base_t::named_vector_t(number_of_points)
{
acmacs::transform_if(first, last, begin(), predicate, convert);
std::sort(begin(), end());
}
bool contains(size_t val) const
{
const auto found = std::lower_bound(begin(), end(), val);
return found != end() && *found == val;
}
void insert(size_t val)
{
if (const auto found = std::lower_bound(begin(), end(), val); found == end() || *found != val)
get().insert(found, val);
}
void erase(const_iterator ptr) { get().erase(ptr); }
void erase_except(size_t val)
{
const auto present = contains(val);
get().clear();
if (present)
insert(val);
}
void extend(const PointIndexList& source)
{
for (const auto no : source)
insert(no);
}
void remove(const ReverseSortedIndexes& indexes, size_t base_index = 0)
{
get().erase(std::remove_if(begin(), end(), [&indexes, base_index](size_t index) { return index >= base_index && indexes.contains(index - base_index); }), end());
}
void keep(const ReverseSortedIndexes& indexes, size_t base_index = 0)
{
get().erase(std::remove_if(begin(), end(), [&indexes, base_index](size_t index) { return index >= base_index && !indexes.contains(index - base_index); }), end());
}
template <typename Pred> void remove_if(Pred pred)
{
get().erase(std::remove_if(begin(), end(), pred), end());
}
void clear()
{
get().clear();
}
PointIndexList& serum_index_to_point(size_t to_add)
{
for (auto& no : get())
no += to_add;
return *this;
}
}; // class PointIndexList
using Indexes = PointIndexList;
// ----------------------------------------------------------------------
class UnmovablePoints : public PointIndexList
{
public:
using PointIndexList::PointIndexList;
UnmovablePoints(const PointIndexList& src) : PointIndexList(src) {}
UnmovablePoints(PointIndexList&& src) : PointIndexList(std::move(src)) {}
};
class UnmovableInTheLastDimensionPoints : public PointIndexList
{
public:
using PointIndexList::PointIndexList;
UnmovableInTheLastDimensionPoints(const PointIndexList& src) : PointIndexList(src) {}
UnmovableInTheLastDimensionPoints(PointIndexList&& src) : PointIndexList(std::move(src)) {}
};
class DisconnectedPoints : public PointIndexList
{
public:
using PointIndexList::PointIndexList;
DisconnectedPoints(const PointIndexList& src) : PointIndexList(src) {}
DisconnectedPoints(PointIndexList&& src) : PointIndexList(std::move(src)) {}
};
} // namespace acmacs::chart
// namespace acmacs
// {
// inline std::string to_string(const acmacs::chart::PointIndexList& indexes) { return to_string(*indexes); }
// } // namespace acmacs
// namespace acmacs::chart
// {
// inline std::ostream& operator<<(std::ostream& out, const PointIndexList& indexes) { return out << acmacs::to_string(indexes); }
// } // namespace acmacs::chart
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| true |
6373a3548203946baee5e208c60369d37e94b5a6 | C++ | showstarpro/experiment | /pcenter/uscp.h | GB18030 | 1,565 | 2.59375 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <vector>
using namespace std;
struct node
{
int w = 0;
int flag = 0; //Ƿ
};
struct set
{
int chide[5000];
int length = 0;
int d = 0;
int fp = 0;
};
struct sp
{
int p = 0; //Ҫȷĵĸ
int s[500];
int fx = 0;
};
set s[5000]; //еļ
node n[5000]; //еĶ
int tube[5000]; //ɱ
sp pcenter;
clock_t start, finish;
double tm;
int length = 0; //ϵĸ
int nodenum = 0; //ĸ
int stringToInt(char a[])
{
int temp = a[0] - '0';
int i = 1;
while (a[i] >= '0' && a[i] <= '9')
{
temp = temp * 10 + a[i] - '0';
i++;
}
return temp;
}
int findn(set st, int n) //nǷst
{
if (n >= nodenum)
return -1;
if (st.fp == 1)
{
for (int i = 0; i < st.length; i++)
{
if (st.chide[i] == n)
return i;
}
}
return -1;
}
//ijϵd
void setd(int t)
{
for (int i = 0; i < s[t].length; i++)
{
int tt = 0;
for (int j = 0; j < pcenter.p; j++)
{
if (findn(s[pcenter.s[j]], s[t].chide[i]) == -1)
{
tt++;
}
else if (t == pcenter.s[j])
{
tt++;
}
}
if (tt == pcenter.p)
{
s[t].d++;
}
}
}
void swap(int i,int j)
{
} | true |
4a0d26d34670f183ad3af60f356527a6f3b0a938 | C++ | shubhamguptaji/CPP | /bank.cpp | UTF-8 | 1,403 | 3.78125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class account
{
public:
char name[50];
int acc,type;
float balance;
void getdata()
{
cout<<"Enter your name"<<endl;
cin>>name;
cout<<"Enter account number"<<endl;
cin>>acc;
cout<<"Enter account type(1 for savings, 2 for current)"<<endl;
cin>>type;
cout<<"Enter balance"<<endl;
cin>>balance;
}
void deposit()
{
float amount;
cout<<"Enter amount to be deposited"<<endl;
cin>>amount;
balance +=amount;
}
void withdrawl()
{
float amount;
cout<<"Enter the amount you want to withdraw"<<endl;
cin>>amount;
if(amount<balance+1000)
{
balance -=amount;
}
else
{
cout<<"Not sufficient balance"<<endl;
}
}
void display()
{
cout<<"name is:"<<name<<endl;
cout<<"account no. is"<<acc<<endl;
if(type==1)
cout<<"account type is savings"<<endl;
else
cout<<"account type is current"<<endl;
cout<<"Balance is"<<balance<<endl;
}
};
class savings: public account
{
public:
void interest()
{
if(type==1)
{
balance = balance + (balance*6)/100;
cout<<"balance after interest is"<<balance<<endl;
}
else
{
cout<<"you have a current account"<<endl;
}
}
};
class current: public account
{
public:
void checkbook()
{
if(type==2)
{
cout<<"you are provided with the facility of checkbook"<<endl;
}
else
cout<<"you have a savings account"<<endl;
}
};
int main()
{
account a;
savings s;
a.getdata();
a.deposit();
a.display();
a.withdrawl();
a.display();
s.interest();
current c;
c.checkbook();
} | true |
48db8affa8eeae038db5497b0a60fba7b623cb27 | C++ | upwinds/homework-bins | /sLinkList.h | UTF-8 | 3,511 | 3.890625 | 4 | [] | no_license | //数据结构-第2章-链表-seqList类
//519021911028 金毅诚
#ifndef SEQLIST_H
#define SEQLIST_H
#include<iostream>
template<class elemType> //基本父类,由虚函数构成,无法定义对象
class list
{
public:
virtual void clear() = 0; //清除所有内容
virtual int length() const = 0 ; //计算表内数据个数
virtual void insert(int i, const elemType& x) = 0; //在i位置插入一个数据
virtual void remove(int i) = 0; //删除在i位置的数据
virtual int search(const elemType& x) const = 0; //查询是否有对应数据
virtual elemType visit(int i) const = 0; //查询第i个位置的数据并将其返回
virtual void traverse() const = 0; //输出data
virtual ~list(){}; //空的析构函数
};
template<class elemType>
class sLinkList: public list<elemType>
{
private:
struct node //单链表中的节点类
{
elemType data;
node *next;
node(const elemType& x, node *n = NULL)
{data = x; next = n;} //节点构造函数
node():next(NULL){} //缺省参数的构造函数
~node(){} //析构函数
};
node *head; //头指针
int currentLength; //表长
node *move(int i) const; //返回第i个节点的地址
public:
sLinkList();
~sLinkList(){clear(); delete head;}
void clear();
int length() const {return currentLength;}
void insert(int i, const elemType& x);
void remove(int i);
int search(const elemType& x) const;
elemType visit(int i) const;
void traverse() const;
};
template<class elemType>
typename sLinkList<elemType>::node *sLinkList<elemType>::move(int i) const
{
node *p = head;
while(i-- >= 0) p = p->next;
return p;
}
template<class elemType>
sLinkList<elemType>::sLinkList()
{
head = new node;
currentLength = 0;
return;
}
template<class elemType>
void sLinkList<elemType>::clear()
{
node *p = head->next, *q;
head->next = NULL;
while(p)
{
q = p->next;
delete p;
p = q;
}
currentLength = 0;
return;
}
template<class elemType>
void sLinkList<elemType>::insert(int i, const elemType& x)
{
node *pos;
pos = move(i - 1);
pos->next = new node(x,pos->next);
++currentLength;
}
template<class elemType>
void sLinkList<elemType>::remove(int i)
{
node *pos, *delp;
pos = move(i - 1);
delp = pos->next;
pos->next = delp->next; //绕过delp
delete delp;
--currentLength;
return;
}
template<class elemType>
int sLinkList<elemType>::search(const elemType& x) const
{
node *p = head->next;
int i = 0;
while(p && p->data != x){p = p->next; ++i;}
if(p == NULL) return -1;
return i;
}
template<class elemType>
elemType sLinkList<elemType>::visit(int i) const
{
return move(i)->data;
}
template<class elemType>
void sLinkList<elemType>::traverse() const
{
node *p = head->next;
std::cout << std::endl;
while(p)
{
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
return;
}
#endif | true |
3f10fdf922c1b4dfeee9d3f5ca78c8c02a9e1b34 | C++ | bioinroboticsuottawa/dextrus_ws | /src/remap/src/leitor.cpp | UTF-8 | 2,107 | 2.796875 | 3 | [] | no_license | //
// Created by rafaelpaiva on 09/12/15.
//
#include <ros/ros.h>
#include <std_msgs/Float64.h>
#include <sensor_msgs/JointState.h>
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <algorithm>
class Leitor {
public:
Leitor();
~Leitor();
void run();
void receive(const sensor_msgs::JointStateConstPtr &ptr);
private:
ros::NodeHandle _nh;
ros::Publisher _pub;
ros::Subscriber _sub;
std::ofstream _file;
std::string _step;
bool _accept;
int _read;
std_msgs::Float64 _position;
YAML::Node _register;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "leitor");
ros::start();
ROS_INFO("Starting gathering the information");
ros::Duration(5.0).sleep();
Leitor leitor;
leitor.run();
ros::shutdown();
return 0;
}
Leitor::Leitor() : _read(0) {
_pub = _nh.advertise<std_msgs::Float64>("/posicao", 32);
_sub = _nh.subscribe("/cyberglove/raw/joint_states", 32, &Leitor::receive, this);
_file.open("./file.yaml", std::fstream::out);
}
Leitor::~Leitor() {
ROS_INFO("Finished.");
_file.close();
_pub.shutdown();
_sub.shutdown();
ros::shutdown();
}
void Leitor::run() {
ROS_INFO("Starting registering the hand");
for (double pos = 0.0; pos <= 100.0; pos += 5.0) {
if (!ros::ok())
break;
std::ostringstream os;
os << pos;
_step = os.str();
ROS_INFO("Setting the position to %lf", pos);
_accept = false;
_position.data = pos;
_pub.publish(_position);
ros::spinOnce();
ros::Duration(3.5).sleep();
_accept = true;
ROS_INFO("Gathering...");
while (_read < 64 && ros::ok()) {
ros::spinOnce();
}
ROS_INFO("OK.");
_read = 0;
}
_file << _register;
}
void Leitor::receive(const sensor_msgs::JointStateConstPtr &ptr) {
if (!_accept) return;
YAML::Node joint;
joint["G_MiddleMPJ"] = 0.0;
joint["G_MiddlePIJ"] = 0.0;
joint["G_MiddleDIJ"] = 0.0;
YAML::iterator it;
for (it = joint.begin(); it != joint.end(); ++it) {
long pos = std::find(ptr->name.begin(), ptr->name.end(), it->first.as<std::string>()) - ptr->name.begin();
it->second = ptr->position[pos];
}
_register[_step][_read] = joint;
++_read;
}
| true |
917c8bbcb903d9ff3d0428286043b19d11f968e8 | C++ | fadliarfans/MyCpp | /C++/c++ 6/coba 26.cpp | UTF-8 | 609 | 3.046875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int arr2[5],arr3[5];
void proc1(int x)
{
long long int arr[x];
for(int i=0;i<x;i++)
{
cin>>arr[i];
if(arr[i]==1)
{
arr2[0]++;
}
if(arr[i]==2)
{
arr2[1]++;
}
if(arr[i]==3)
{
arr2[2]++;
}
if(arr[i]==4)
{
arr2[3]++;
}
if(arr[i]==5)
{
arr2[4]++;
}
}
}
int main()
{
int n,max=0,tmp;
cin>>n;
proc1(n);
for(int i=1;i<=5;i++)
{
arr3[i-1]=i;
}
for(int i=4;i>=0;i--)
{
if(arr2[i]>=max)
{
max=arr2[i];
tmp=arr3[i];
}
}
cout<<tmp;
}
| true |
3aaae8dc560181d18ecafe362cf16f6ee417876e | C++ | MichaelTiernan/qvge | /src/3rdParty/ogdf-2020/test/include/bandit/reporters/crash_reporter.h | UTF-8 | 2,474 | 2.859375 | 3 | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"EPL-1.0",
"LicenseRef-scancode-generic-exception",
"GPL-1.0-or-later",
"BSL-1.0",
"LGPL-2.0-only",
"BSD-2-Clause"
] | permissive | #ifndef BANDIT_CRASH_REPORTER_H
#define BANDIT_CRASH_REPORTER_H
#include <iostream>
#include <vector>
#include <bandit/reporters/progress_reporter.h>
namespace bandit {
namespace detail {
struct crash_reporter : public progress_reporter {
crash_reporter(std::ostream& stm, const failure_formatter& failure_formatter)
: progress_reporter(failure_formatter), stm_(stm) {}
crash_reporter(const failure_formatter& failure_formatter)
: crash_reporter(std::cout, failure_formatter) {}
crash_reporter& operator=(const crash_reporter&) {
return *this;
}
void test_run_complete() override {
progress_reporter::test_run_complete();
for (auto failure : failures_) {
stm_ << std::endl
<< "# FAILED " << failure;
}
for (auto error : test_run_errors_) {
stm_ << std::endl
<< "# ERROR " << error;
}
stm_.flush();
}
void test_run_error(const std::string& desc, const struct test_run_error& err) override {
progress_reporter::test_run_error(desc, err);
std::stringstream ss;
ss << current_context_name() << ": " << desc << ": " << err.what() << std::endl;
test_run_errors_.push_back(ss.str());
}
void it_skip(const std::string& desc) override {
progress_reporter::it_skip(desc);
}
void it_starting(const std::string& desc) override {
progress_reporter::it_starting(desc);
for (auto context : contexts_) {
stm_ << context << " | ";
}
stm_ << desc << std::endl;
}
void it_succeeded(const std::string& desc) override {
progress_reporter::it_succeeded(desc);
}
void it_failed(const std::string& desc, const assertion_exception& ex) override {
++specs_failed_;
std::stringstream ss;
ss << current_context_name() << " " << desc << ":" << std::endl
<< failure_formatter_.format(ex);
failures_.push_back(ss.str());
stm_ << "FAILED" << std::endl;
}
void it_unknown_error(const std::string& desc) override {
++specs_failed_;
std::stringstream ss;
ss << current_context_name() << " " << desc << ": Unknown exception" << std::endl;
failures_.push_back(ss.str());
stm_ << "UNKNOWN EXCEPTION" << std::endl;
}
private:
std::ostream& stm_;
};
}
}
#endif
| true |
c609597b2a602547dab73c2749307562746b36a2 | C++ | Ali1849/SDS_fall2018 | /SDS392/ch12_ex1.cxx | UTF-8 | 1,846 | 3.828125 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using std::cin;
using std::cout;
using std::endl;
class Point {
private:
float x,y;
public:
Point () {};
Point ( float x, float y ) : x(x), y(y){};
float px() { return x; };
float py() { return y; };
void setp (float newx, float newy) {x = newx; y = newy;};
};
class Rectangle {
protected:
//private:
Point BL_point;
float w, h ;
public:
Rectangle ( Point bl, float wi, float he) { BL_point = bl; w = wi; h = he; };
Rectangle ( Point bl, Point tr) { BL_point = bl; w = tr.px() - bl.px(); h = tr.py() - bl.py(); };
float area () { return w*h; };
float width () { return w; };
float height () { return h; };
};
class Square : public Rectangle{
public:
Square (Point bl, float s) : Rectangle ( bl, s, s) {};
};
int main() {
float bl_x, bl_y, tr_x, tr_y, width, height, side;
Point bl;
Point tr;
cout << "Enter (x,y) of bottom left vertex: " << endl;
cin >> bl_x >> bl_y ;
bl.setp(bl_x,bl_y);
cout << "Enter width: " << endl;
cin >> width;
cout << "Enter height: " << endl;
cin >> height;
cout << "Enter square side: " << endl;
cin >> side;
cout << "Enter (x,y) of top right vertex: " << endl;
cin >> tr_x >> tr_y ;
tr.setp(tr_x,tr_y);
Rectangle Rect1(bl,width,height);
cout << "Using Rectangle class with first constructer: " << endl;
cout << "Area: " << Rect1.area() << endl;
cout << "Width: " << Rect1.width() << endl;
cout << "Height: " << Rect1.height() << endl;
Rectangle Rect2(bl,tr);
cout << "Using Rectangle class with second constructer: " << endl;
cout << "Area: " << Rect2.area() << endl;
cout << "Width: " << Rect2.width() << endl;
cout << "Height: " << Rect2.height() << endl;
Square Sq1(bl,side);
cout << "Using Square class: " << endl;
cout << "Area: " << Sq1.area() << endl;
return 0;
}
| true |
3cc1ed16f5d0dd009cb75817491e04ef1ea9b55e | C++ | DeagleGross/C-Algo-Structures | /Algorithms/KDZ/AlgoHelper.h | UTF-8 | 3,330 | 3.171875 | 3 | [] | no_license | //
// Created by DG Coach on 29.03.2019.
//
#ifndef KDZ_BORDERMAKER_H
#define KDZ_BORDERMAKER_H
#include <vector>
#include <iostream>
using namespace std;
class AlgoHelper
{
public:
int getIstok(vector<vector<int>>& matrix)
{
vector<int> istoks = vector<int>();
for (int i = 0; i < matrix.size(); ++i)
{
bool pathToIt = false;
for (int j = 0; j < matrix.size(); ++j)
{
if (matrix[j][i] != 0)
{
pathToIt = true;
break;
}
}
if (!pathToIt)
istoks.push_back(i);
}
if (istoks.empty()) // error
return -1;
if (istoks.size() == 1) // the only istok found
return istoks[0];
if (istoks.size() > 1) // variant for DISCO matrixes
{
int rowOfFakeIstok = matrix.size();
// added row for istok but of
// size N
matrix.push_back(vector<int>(matrix.size(), 0));
// added column for istok so now it is
// size(N+1 x N+1)
for (int i = 0; i < matrix.size(); ++i)
matrix[i].push_back(0);
for (int i = 0; i < istoks.size(); ++i)
{
// making capacity of really big number
matrix[rowOfFakeIstok][istoks[i]] = INT32_MAX; // for rows
matrix[istoks[i]][rowOfFakeIstok] = INT32_MAX; // for columns
}
return (rowOfFakeIstok);
}
return -1;
}
int getFinal(vector<vector<int>>& matrix)
{
vector<int> stoki = vector<int>();
for (int i = 0; i < matrix.size(); ++i)
{
bool pathFromIt = false;
for (int j = 0; j < matrix.size(); ++j)
{
if (matrix[i][j] != 0)
{
pathFromIt = true;
break;
}
}
if (!pathFromIt)
stoki.push_back(i);
}
if (stoki.empty()) // error
return -1;
if (stoki.size() == 1) // the only istok found
return stoki[0];
if (stoki.size() > 1) // variant for DISCO matrixes
{
int rowOfFakeStok = matrix.size();
// added row for Stok but of
// size N
matrix.push_back(vector<int>(matrix.size(), 0));
// added column for Stok so now it is
// size(N+1 x N+1)
for (int i = 0; i < matrix.size(); ++i)
matrix[i].push_back(0);
for (int i = 0; i < stoki.size(); ++i)
{
// making capacity of really big number
matrix[rowOfFakeStok][stoki[i]] = INT32_MAX; // for rows
matrix[stoki[i]][rowOfFakeStok] = INT32_MAX; // for columns
}
return (rowOfFakeStok);
}
return -1;
}
void getResultMatrix(vector<vector<int>>& matrix, vector<vector<int>>& copy)
{
for (int i = 0; i < matrix.size(); ++i)
for (int j = 0; j < matrix.size(); ++j)
matrix[i][j] = (copy[i][j] - matrix[i][j] < 0) ? 0 : copy[i][j] - matrix[i][j];
}
};
#endif //KDZ_BORDERMAKER_H
| true |
1d15eb010057f012ef2abb9cb09ae57be0f705eb | C++ | synchronized/gtd | /lang/c-cpp/practice/src/simple-encode.cpp | UTF-8 | 330 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
char c[5]={'C','h','i','n','a'};
int i;
for (i=0;i<5;i++) {
int x = c[i];
if ((x>='a' && x<='z') || (x>='A' && x<='Z')) {
if( x > 'w') c[i] += 4-26;
else if (x > 'W' && x <= 'Z') c[i] += 4-26;
else c[i] += 4;
}
cout << c[i];
}
cout <<endl;
return 0;
}
| true |
346acd618302cedd08f25fdeeebdbdca195d44df | C++ | lavumi/DX11_Portfolio | /Model/ModelBoneWeights.h | UHC | 2,118 | 2.890625 | 3 | [] | no_license | #pragma once
#include "../Utility/BinaryInputOutputHandler.h"
/********************************************************************************
Vertex ġ Bone Index ġ Wieght ϴ Class
Vertex ִ 4 BoneWeight ,
Bone Index Bone Weight vector4 · Vertex Data ȴ.
Vertex Weights Blending Ǿ ȴ.
********************************************************************************/
struct ModelBlendWeights
{
D3DXVECTOR4 BlendIndices;
D3DXVECTOR4 BlendWeights;
ModelBlendWeights()
{
BlendIndices = D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f);
BlendWeights = D3DXVECTOR4(0.0f, 0.0f, 0.0f, 0.0f);
}
void SetBlendWeight(int nIndex, int nBoneIndex, float fWeight)
{
switch (nIndex)
{
case 0:
BlendIndices.x = (float)nBoneIndex;
BlendWeights.x = fWeight;
break;
case 1:
BlendIndices.y = (float)nBoneIndex;
BlendWeights.y = fWeight;
break;
case 2:
BlendIndices.z = (float)nBoneIndex;
BlendWeights.z = fWeight;
break;
case 3:
BlendIndices.w = (float)nBoneIndex;
BlendWeights.w = fWeight;
break;
}
}
};
class ModelBoneWeights
{
public:
ModelBoneWeights();
ModelBoneWeights(const ModelBoneWeights& otherModelBoneWeights);
~ModelBoneWeights();
static const UINT MaxBonesPerVertex; /// Vertex ġ ִ Bone
static const UINT MaxBonesPerMax; /// ִ Bone
void AddBoneWeight(int boneIndex, float boneWeight);
void AddBoneWeight(pair<int, float> boneWeightPair);
void AddBoneWeights(const ModelBoneWeights& boneWeights);
void Validate();
void Normalize();
int GetBoneWeightCount() const { return boneWeights.size(); }
pair<int, float> GetBoneWeight(int index) const { return boneWeights[index]; }
ModelBlendWeights GetBlendWeights();
private:
float sumWeight; /// Vertex ִ Wieght
vector<pair<int, float>> boneWeights; /// Bone Index Weight Pair ϴ
}; | true |
4440b2d04f341c2c10b1951c8ce221cd85f0690f | C++ | sherlockwilson/simple_trace | /third_party/zipkin-cpp-opentracing/zipkin_opentracing/src/sampling.h | UTF-8 | 497 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <algorithm>
#include <memory>
namespace zipkin {
class Sampler {
public:
virtual ~Sampler() = default;
virtual bool ShouldSample() = 0;
};
class ProbabilisticSampler : public Sampler {
public:
explicit ProbabilisticSampler(double sample_rate)
: sample_rate_(std::max(0.0, std::min(sample_rate, 1.0))){};
bool ShouldSample() override;
private:
double sample_rate_;
};
typedef std::unique_ptr<Sampler> SamplerPtr;
} // namespace zipkin | true |
d0261366a14948e15f532bb9e2f803bd4ca12e59 | C++ | thomaswpp/problems-solutions | /URI/1457_Oraculo_de_Alexandria.cpp | UTF-8 | 454 | 3.1875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
long long int fatorial(int n, int k)
{
long long int result = n, i = 1, r = k;
if(n == 0) return 1;
while((n-r) > 1)
{
result *= (n-r);
r = ++i*k;
}
return result;
}
int main()
{
char c[25];
int n, t, k;
cin >> t;
while( t-- )
{
scanf("%d%s",&n,c);
k = strlen(c);
cout << fatorial(n, k) << endl;
}
return 0;
}
| true |
d9140f54c99e3e62806a5d8ec4b00cfdfeeed913 | C++ | JulioMelo-Classes/lista-2-pablodamascenoo | /sort/include/sort.h | UTF-8 | 1,488 | 3.078125 | 3 | [] | no_license | #ifndef GRAAL_H
#define GRAAL_H
#include <utility>
using std::pair;
#include <iterator>
using std::distance;
#include <algorithm>
using std::sort;
namespace graal {
/*!
* TODO: documentação no estilo doxygen
* {7,5,8,4,2,3,9} menor = 7;
* {5,7,8,4,2,3,9} menor = 5;
* {}
*
*/
/*
80%
*/
template<class ForwardIt, class Comparison>
void sort(ForwardIt first, ForwardIt last, Comparison cmp)
{
// TODO
int menor = *first;
int maior = *(last-1);
int aux = 0;
ForwardIt counter = first+1;
for (ForwardIt i = first; i<last; i++){
if(cmp(*i, menor)==true){
aux = *first;
menor = *i;
*first = *i;
*i = aux;
i--;
}
else if(cmp(maior, *i)==true){
aux = *(last-1);
maior = *i;
*(last-1) = *i;
*i = aux;
i--;
}
}
for (ForwardIt i = first+2; i<last; i++){
if(cmp(*i, *counter)==true){
aux = *counter;
*counter = *i;
*i = aux;
i = first+2;
}
else{
counter++;
while(*counter!= *i){
if(cmp(*i,*counter)==true){
aux = *i;
*i = *counter;
*counter = aux;
i = first+2;
break;
}
counter++;
}
counter = (first+1);
}
}
}
}
#endif
| true |
32679d045b5293d40a9219aa833bebb15919fb41 | C++ | shashankch/DataStructures-Algorithms | /cnstack.cpp | UTF-8 | 1,670 | 3.71875 | 4 | [] | no_license |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class stackusingarray
{
T *data;
int nextIndex;
int capacity;
public:
stackusingarray(int totalsize)
{
capacity = totalsize;
data = new T[totalsize];
nextIndex = 0;
}
int size()
{
return nextIndex;
}
bool isEmpty()
{
return nextIndex == 0;
}
void push(T element)
{
if (nextIndex == capacity)
{
cout << "stack overflow" << endl;
return;
}
data[nextIndex] = element;
nextIndex++;
}
T pop()
{
if (!isEmpty())
{
nextIndex--;
return data[nextIndex];
}
else
{
cout << "empty" << endl;
return INT_MIN;
}
}
T top()
{
if (!isEmpty())
{
return data[nextIndex - 1];
}
}
};
void reverseStack(stack<int> &s1, stack<int> &s2)
{
if (s1.empty() || s1.size() == 1)
{
return;
}
int top = s1.top();
s1.pop();
reverseStack(s1, s2);
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
s1.push(top);
while (!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
}
int main()
{
stackusingarray<int> *s = new stackusingarray<int>(30);
stackusingarray<int> stack(10);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
bool ans = stack.isEmpty();
int top = stack.pop();
int size = stack.size();
int val = stack.top();
return 0;
} | true |
b6c7b1f50e8d0876dd3b61b398b23f6af156a90e | C++ | JorgeRojo/Polytte | /ESP32/Polytt/Storage.h | UTF-8 | 2,794 | 2.890625 | 3 | [] | no_license | #include <EEPROM.h>
typedef struct
{
// orientation
bool calibration_saved;
int ax_offset;
int ay_offset;
int az_offset;
int gx_offset;
int gy_offset;
int gz_offset;
// wifi
char *wifi_ssid;
char *wifi_password;
} Storage_t;
int EEPROM_writeAnything(int ee, const Storage_t &data)
{
const byte *p = (const byte *)(const void *)&data;
unsigned int i;
for (i = 0; i < sizeof(data); i++)
EEPROM.write(ee++, *p++);
return i;
}
int EEPROM_readAnything(int ee, Storage_t &data)
{
byte *p = (byte *)(void *)&data;
unsigned int i;
for (i = 0; i < sizeof(data); i++)
*p++ = EEPROM.read(ee++);
return i;
}
class Storage
{
private:
byte _pin;
bool _reset;
void _saveStorage()
{
size_t size = sizeof(data);
EEPROM.begin(size * 2);
EEPROM_writeAnything(0, data);
EEPROM.commit();
}
void _loadStorage()
{
size_t size = sizeof(data);
EEPROM.begin(size * 2);
EEPROM_readAnything(0, data);
// reset storage
if (_reset)
{
data.calibration_saved = false;
data.wifi_ssid = "";
data.wifi_password = "";
}
}
void _print()
{
Serial.println("STRG -> *** data list ***");
Serial.println(" --- calibration --- ");
Serial.print(" calibration_saved:\t");
Serial.println(data.calibration_saved);
Serial.print(" ax_offset:\t");
Serial.println(data.ax_offset);
Serial.print(" ay_offset:\t");
Serial.println(data.ay_offset);
Serial.print(" az_offset:\t");
Serial.println(data.az_offset);
Serial.print(" gx_offset:\t");
Serial.println(data.gx_offset);
Serial.print(" gy_offset:\t");
Serial.println(data.gy_offset);
Serial.print(" gz_offset:\t");
Serial.println(data.gz_offset);
Serial.println(" --- wifi --- ");
Serial.print(" wifi_ssid:\t");
Serial.println(data.wifi_ssid);
Serial.print(" wifi_password:\t");
Serial.println(data.wifi_password);
}
public:
Storage_t data;
Storage(bool reset)
{
_reset = reset;
}
void print()
{
this->_loadStorage();
this->_print();
}
void save(bool print = false)
{
Serial.println("STRG -> saving... \t");
this->_saveStorage();
if (print)
{
this->_print();
}
}
void load(bool print = false)
{
this->_loadStorage();
if (print)
{
Serial.println("");
Serial.print("STRG -> Loaded: ");
this->_print();
}
}
};
| true |
fdc07664ddd7518666a844764db0c7ce52ef9633 | C++ | timopulkkinen/BubbleFish | /chrome/browser/chromeos/drive/search_metadata.h | UTF-8 | 2,875 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_DRIVE_SEARCH_METADATA_H_
#define CHROME_BROWSER_CHROMEOS_DRIVE_SEARCH_METADATA_H_
#include <string>
#include <vector>
#include "chrome/browser/chromeos/drive/drive_file_system_interface.h"
namespace drive {
// Struct to represent a search result for SearchMetadata().
struct MetadataSearchResult {
MetadataSearchResult(const base::FilePath& in_path,
const DriveEntryProto& in_entry_proto,
const std::string& in_highlighted_base_name)
: path(in_path),
entry_proto(in_entry_proto),
highlighted_base_name(in_highlighted_base_name) {
}
// The two members are used to create FileEntry object.
base::FilePath path;
DriveEntryProto entry_proto;
// The base name to be displayed in the UI. The parts matched the search
// query are highlighted with <b> tag. Meta characters are escaped like <
//
// Why HTML? we could instead provide matched ranges using pairs of
// integers, but this is fragile as we'll eventually converting strings
// from UTF-8 (StringValue in base/values.h uses std::string) to UTF-16
// when sending strings from C++ to JavaScript.
//
// Why <b> instead of <strong>? Because <b> is shorter.
std::string highlighted_base_name;
};
typedef std::vector<MetadataSearchResult> MetadataSearchResultVector;
// Callback for SearchMetadata(). On success, |error| is DRIVE_FILE_OK, and
// |result| contains the search result.
typedef base::Callback<void(
DriveFileError error,
scoped_ptr<MetadataSearchResultVector> result)> SearchMetadataCallback;
// Searches the local resource metadata, and returns the entries
// |at_most_num_matches| that contain |query| in their base names. Search is
// done in a case-insensitive fashion. |callback| must not be null. Must be
// called on UI thread. No entries are returned if |query| is empty.
void SearchMetadata(DriveFileSystemInterface* file_system,
const std::string& query,
int at_most_num_matches,
const SearchMetadataCallback& callback);
// Finds |query| in |text| while ignoring case. Returns true if |query| is
// found. Returns false if |query| is not found, or empty. |highlighted_text|
// will have the original text with matched portions highlighted with <b> tag
// (multiple portions can be highlighted). Meta characters are escaped like
// <. The original contents of |highlighted| will be lost.
bool FindAndHighlight(const std::string& text,
const std::string& query,
std::string* highlighted_text);
} // namespace drive
#endif // CHROME_BROWSER_CHROMEOS_DRIVE_SEARCH_METADATA_H_
| true |
d2fa4a1a2f9373807e48339dc433f956700efe95 | C++ | MISAKIGA/hm_car | /cpp/day01/02_variable/main.cpp | GB18030 | 859 | 4 | 4 | [] | no_license | #include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
// = ֵ;
//1. ͬʱʼ
int age = 18;
double price = 20.5;
//2. ֵ
int score;
score = 100;
//3. ʾ ûֱʹ
//number = "10086";
//4. ijʼд֣
int a = 3; //CԽģ
int b (4); //ù췽ʽ
int c {5}; // c++ 11汾ʼбķʽ
//5. ҲԲ鿴ռõĿռжõĽʵͲ鿴ݵһġ
std::cout << "aռõĿռ䣺" << sizeof(a) << std::endl;
std::cout << "intռõĿռ䣺" << sizeof(int) << std::endl;
return 0;
}
| true |
272919ea568a96d56f7980aa1e95267038c2822a | C++ | AnatolyKorablyov/Game_develop_for_android | /Classes/Player.h | UTF-8 | 1,676 | 2.5625 | 3 | [] | no_license | #pragma once
#include "cocos2d.h"
#include "Joystick.h"
#include "Entity.h"
#include <vector>
#include <map>
#include "CollisionMap.h"
class Player : public CEntity
{
public:
static Player *create(Joystick *moveJoy, Joystick *rotateJoy);
void Update(float dt) override;
void Shoot(cocos2d::Layer *layer);
void ChooseNextGun();
void SetLight(cocos2d::Sprite * mask_light);
void SetHPLine(cocos2d::Sprite * line);
bool CanHit();
void SetHealthLabel(cocos2d::Label * healthLabel);
void AddHealth(float health);
void UpdateHPLine();
void UpdateHPLabel();
private:
enum ActionState
{
ActionStay = 0,
ActionRun,
ActionAttack,
NumOfActions,
};
enum WeaponState
{
WeaponKnife = 0,
WeaponPistol,
WeaponM4,
NumOfWeapons
};
void Run();
void Stay();
cocos2d::RefPtr<Animate> GetAnimate(ActionState action, WeaponState weapon);
int GetAnimateIndex(ActionState action, WeaponState weapon);
void StopAttack(float dt);
/*bool CanWalkDirectly(const Vec2 & from, const Vec2 & to) const;
*/
ActionState m_actionState;
WeaponState m_weaponState;
Player();
void initOptions();
void SetState(double const& move);
void SetShootPosition(float angle);
void initKnifeAnimations();
void initPistolAnimations();
void initMainWeaponAnimations();
private:
Joystick * m_moveController;
Joystick * m_rotateController;
std::vector<cocos2d::RefPtr<Animate>> m_anims;
cocos2d::RefPtr<Animate> m_currentAction;
cocos2d::Vec2 m_shootPosition;
MovementDirection m_shootDirection;
cocos2d::Sprite * m_healthLine;
cocos2d::Sprite * m_mask;
bool isShoot = false;
cocos2d::Label * m_healthLabel;
std::vector<cocos2d::Rect> m_obstacles;
};
| true |
763b7b046960664150788293408403b5f24035d3 | C++ | MusicGameCreate/Music_Game | /ベースプログラム/ベースプログラム/MusicSelect_BackGround.cpp | SHIFT_JIS | 3,458 | 2.53125 | 3 | [] | no_license | //*************************************************************************
//
// ɃIuWFNg̐
//
//*************************************************************************
//*************************************************************************
// CN[h
//*************************************************************************
#include "MusicSelect_BackGround.h"
#include "DirectX_Library.h"
//*************************************************************************
// RXgN^
//*************************************************************************
MusicSelect_BackGround::MusicSelect_BackGround(void)
{
// IuWFNg쐬邩H(Œ 1`)
//**********************************************************************
nObject_Num = 1;
// eNX`ގgp邩H(Œ 1`)
//**********************************************************************
nUse_Texture_Num = 1;
// IuWFNǧAKvȃTCYm
//**********************************************************************
Tex_2D_Data = new TEXTURE_2D_DATA[nObject_Num];
for( int i = 0 ; i < nObject_Num ; i ++ )
{
// W(摜̒S_)
//******************************************************************
Tex_2D_Data[i].Obj_Pos = D3DXVECTOR3( (float)(SCREEN_WIDTH/2), (float)(SCREEN_HEIGHT/2), 0.0f );
// IuWFNg̃TCY(X,Y)
//******************************************************************
Tex_2D_Data[i].Obj_Size = D3DXVECTOR2((float)SCREEN_WIDTH, (float)SCREEN_HEIGHT);
// eNX`W(0.0f`1.0f)
//******************************************************************
Tex_2D_Data[i].Tex_Pos = D3DXVECTOR2( 0.0f, 0.0f );
// 1Aj[ṼeNX`W(0.0f`1.0f)
//******************************************************************
Tex_2D_Data[i].Tex_Anim = D3DXVECTOR2( 1.0f, 1.0f );
// 摜RGBAl
//******************************************************************
Tex_2D_Data[i].Red =
Tex_2D_Data[i].Green=
Tex_2D_Data[i].Brue =
Tex_2D_Data[i].Alpha= 255;
// 摜̊g嗦( 0.0f` )
//******************************************************************
Tex_2D_Data[i].fScale = 1.0f;
// 摜̉]px( 0.0f` )
//******************************************************************
Tex_2D_Data[i].fRot = 0.0f;
}
CTexture_2D_Base::Init();
CREATE_TEXTURE( pTexture[0], 0xff000020 );
}
//*************************************************************************
// fXgN^
//*************************************************************************
MusicSelect_BackGround::~MusicSelect_BackGround(void)
{
CTexture_2D_Base::Finalise();
}
//*************************************************************************
// XV
//*************************************************************************
void MusicSelect_BackGround::Update(void)
{
CTexture_2D_Base::Update();
}
//*************************************************************************
// `揈
//*************************************************************************
void MusicSelect_BackGround::Draw(void)
{
CTexture_2D_Base::Draw(0,0);
}
//*************************************************************************
// EOF
//*************************************************************************
| true |
867dd8c57cd35226ce996e0034b780b7ffb407e8 | C++ | Smoglyk/BSUIR-Labs | /1-term(C++)/3/2-2.cpp | UTF-8 | 514 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <math.h>
#define endl "\n"
#define sqr(a) (a)*(a)
#define cub(a) (a)*(a)*(a)
#define M_PI acos(-1)
using namespace std;
int main() {
int k;
cout << "K = ";
cin >> k;
double ans = 1e8, ansx;
for (int i = 0; i <= k; i++) {
double x = -2 + i * 4./k;
double res = acos(exp(-sqr(x+1))) + sin(x);
if (fabs(ans) - fabs(res) >= 1e-6) {
ans = res;
ansx = x;
}
}
cout << ansx << endl;
return 0;
}
| true |
4a6dd7730e6618162232df49ef492841423ad830 | C++ | kiranm000/Random | /Vectors and Sets.cpp | UTF-8 | 694 | 3.3125 | 3 | [] | no_license | Vectors and Sets
// Trying out various operations in vectors and sets.
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s;
s.insert(1);
s.insert(4);
s.insert(2);
s.insert(3);
s.insert(5);
s.insert(2);
bool b=binary_search(s.begin(),s.end(),3);
cout<<b<<endl;
for(int x : s)
{
cout<<x<<" ";
}
cout<<endl;
vector<int> m;
m.push_back(1);
m.push_back(2);
m.push_back(3);
m.push_back(4);
m.push_back(5);
m.push_back(6);
bool c=binary_search(m.begin(),m.end(),5);
cout<<c<<endl;
for(int x : m)
{
cout<<x<<" ";
}
cout<<endl<<m[2]<<endl;
vector<int>::iterator it=upper_bound(m.begin(),m.end(),3); // or use auto it
cout<<*it<<endl;
return 0;
} | true |
35f604dce08633753b47347badb4da83cdc5c281 | C++ | bryzikm/Kalkulator_macierzy | /exercises.cpp | UTF-8 | 6,769 | 3.15625 | 3 | [] | no_license | #include "exercises.h"
#include "ui_exercises.h"
#include "matrix.h"
#include "equation.h"
#include "resultmatrix.h"
#include <QGlobal.h>
#include <QTime>
#include <QStringList>
#include <QMessageBox>
Exercises::Exercises(QWidget *parent) :
QDialog(parent),
ui(new Ui::Exercises)
{
ui->setupUi(this);
this->setWindowTitle("Tryb ćwiczeń");
//a i b tylko do odczytu
ui->a->setReadOnly(true);
ui->b->setReadOnly(true);
Matrix * A = NULL;
Matrix * B = NULL;
ResultMatrix * C = NULL;
Equation * eq = new Equation(); //obiekt będący reprezentacją działania wykonywanego na macierzach A i B
newExcercise(); //wywołanie nowego działania
}
void Exercises::newExcercise()
{
//losujemy działanie z tabeli wskazników
int low = 0;
int high = 4;
int randomEquation = qrand() % ((high + 1) - low) + low; //losowanie działania do wykonania
//następnie według warunków zadania losujemy dwie lub jedną macierz
//dodawanie - takie same wymiary
//mnożenie liczba kolumn A = liczba wierszy B
//wyznacznik macierz kwadratowa
//transpozycja - bez znaczenia
//graniczne wymiary macierzy do rozwiazania
int matrixLow = 4;
int matrixHigh = 6;
int x = qrand() % ((matrixHigh + 1) - matrixLow) + matrixLow; //losujemy pierwszy wymiar
if(randomEquation == 0)
{//dodawanie
int y = qrand() % ((matrixHigh + 1) - matrixLow) + matrixLow;
A = new Matrix(&x, &y);
B = new Matrix(&x, &y);
ui->task->setPlainText("Dane są dwie macierze A i B. Należy obliczyć sumę tych macierzy, a wynik wpisać w odpowiednim miejscu.");
} else if(randomEquation == 1)
{//mnożenie
int y = qrand() % ((matrixHigh + 1) - matrixLow) + matrixLow;
int z = qrand() % ((matrixHigh + 1) - matrixLow) + matrixLow;
A = new Matrix(&x, &y);
B = new Matrix(&z, &x);
ui->task->setPlainText("Dane są dwie macierze A i B. Należy obliczyć iloczyn tych macierzy, a wynik wpisać w odpowiednim miejscu.");
} else if(randomEquation == 2)
{//wyznacznik
A = new Matrix(&x, &x);
ui->task->setPlainText("Dana jest macierz A. Należy obliczyć wyznacznik tej macierzy, a wynik wpisać w odpowiednim miejscu.");
} else if(randomEquation == 3)
{//transpozycja
int y = qrand() % ((matrixHigh + 1) - matrixLow) + matrixLow;
A = new Matrix(&x, &y);
ui->task->setPlainText("Dana jest macierz A. Należy dokonać transpozycji tej macierzy, a wynik wpisać w odpowiednim miejscu.");
}
else if(randomEquation == 4)
{//macierz odwrotna
A = new Matrix(&x, &x);
ui->task->setPlainText("Dana jest macierz A. Należy wyznaczyć macierz odwrotną do macierzy, a wynik wpisać w odpowiednim miejscu.");
}
ResultMatrix * (Equation::*chooseEquation[5]) (Matrix *, Matrix *) =
{
&Equation::addition,
&Equation::multiplication,
&Equation::determinant,
&Equation::transposition,
&Equation::inverse
};
ResultMatrix * chooseEquationTab[] =
{
(A && B) ? (eq->*chooseEquation[0])(A, B) : NULL, //A+B
(A && B) ? (eq->*chooseEquation[1])(A, B) : NULL, //A*B
(A) ? (eq->*chooseEquation[2])(A, A) : NULL, //det(A)
(A) ? (eq->*chooseEquation[3])(A, A) : NULL, //A^T
(A) ? (eq->*chooseEquation[4])(A, A) : NULL //A^-1
};
if(chooseEquationTab[randomEquation] != NULL)
{
C = chooseEquationTab[randomEquation];
}
if(A)
{
printMatrix(A); //wypisanie macierzy A i B do odpowiednich pól
}
if(B)
{
printMatrix(B);
}
//aby drukować wynik => print(C)
}
//funkcja wypisująca macierz w formularzu
void Exercises::printMatrix(Matrix * matrix)
{
if(matrix->table)
{
QString sResult = "";
//zamiana macierzy wynikowej na QString
for(int y = 0; y < matrix->y; y++)
{
for(int x = 0; x < matrix->x; x++)
{
sResult+=QString::number(matrix->table[y][x])+" ";
}
sResult+="\n";
}
if(matrix == A)
{
//ustawienie wyniku w oknie
ui->a->setPlainText(sResult);
} else if(matrix == B)
{
ui->b->setPlainText(sResult);
} else if(matrix == C)
{
ui->result->setPlainText(sResult);
}
}
}
//funkcja sprawdzająca czy macierz wpisywana przez użytkownika jest taka sama jak wynik działania
void Exercises::on_check_released()
{
//pobranie z formularza odpowiedzi użytkownika
QString userResult = ui->result->toPlainText();
//rozdzielamy macierz wpisaną przez użytkownika po białych znakach
QStringList userResultList = userResult.split(QRegExp("\\s+"));
QString sResult = "";
//zamiana macierzy wynikowej (C) na QString
for(int y = 0; y < C->y; y++)
{
for(int x = 0; x < C->x; x++)
{
sResult+=QString::number(C->table[y][x])+" ";
}
sResult+="\n";
}
//rozdzielenie macierzy wynikowej (C) po białych znakach
QStringList resultList = sResult.split(QRegExp("\\s+"));
bool same; //zmienna syganalizująca czy ciągi są równe
if(resultList.length() == userResultList.length()) //sprawdzanie czy długości obu list są równe
{
for(int x = 0; x < resultList.length(); ++x)
{
if(resultList[x] != userResultList[x]) //jeżeli elementy na tym samym miejscu w obu listach są różne elementy
{
same = false; //są różnie więc ustawiamy false
break; //kończymy
} else {
same = true; //są takie same więc true
}
}
} else {
same = false; //jeżeli listy nie mają takich samych długości to na pewno są różne
}
QString answer;
if(same)
{
answer = "Podana odpowiedź jest prawidłowa! Czy chcesz rozwiązać kolejne zadanie?";
} else {
answer = "Podana odpowiedź jest nieprawidłowa! Czy chcesz rozwiązać kolejne zadanie?";
}
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Wynik", answer, QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
//ustawienie adresów macierzy na NULL
A = NULL;
B = NULL;
C = NULL;
//wyczyszczenie pól formularza
ui->a->setPlainText("");
ui->b->setPlainText("");
ui->result->setPlainText("");
//generowanie nowego zadania
newExcercise();
}
}
Exercises::~Exercises()
{
delete ui;
}
| true |
1fb0f319a1f693157bf07d3704ed067580b869d8 | C++ | HaozhiQi/Trace | /src/SceneObjects/CSG.cpp | UTF-8 | 3,500 | 2.625 | 3 | [] | no_license | #include <cmath>
#include <assert.h>
#include <cfloat>
#include "CSG.h"
typedef vector<SegmentPoint>::iterator SegIter;
Segments& Segments::Merge(const Segments& pSegments, int relation){
vector<SegmentPoint> interval;
for (SegIter it = mPoints.begin(); it != mPoints.end(); ++it)
{
it->contri = 1;
interval.push_back(*it);
}
vector<SegmentPoint> pPoints(pSegments.mPoints);
for (SegIter it = pPoints.begin(); it != pPoints.end(); ++it)
{
it->contri = (relation == CSG_MINUS) ? -1 : 1;
interval.push_back(*it);
}
int before = 0, after = 0;
int require = (relation == CSG_AND) ? 2 : 1;
sort(interval.begin(), interval.end());
mPoints.clear();
for (SegIter it = interval.begin(); it != interval.end(); ++it)
{
if (it->isRight)
{
after -= it->contri;
}
else
{
after += it->contri;
}
if (before < require && after >= require){
it->isRight = false;
mPoints.push_back(*it);
}
else if (before >= require&&after < require){
it->isRight = true;
mPoints.push_back(*it);
}
before = after;
}
return *this;
}
CSGTree* CSGTree::merge(const CSGTree* pTree, CSG_RELATION relation){
CSGNode* temp = new CSGNode;
temp->lchild = root;
temp->rchild = pTree->root;
temp->isLeaf = false;
temp->relation = relation;
temp->computeBoundingBox();
root = temp;
return this;
}
bool Segments::firstPositive(SegmentPoint& p)
{
bool hasOne = false;
for (SegIter it = mPoints.begin(); it != mPoints.end(); ++it)
{
if (it->t > RAY_EPSILON)
{
if (hasOne)
{
if (it->t < p.t) p = *it;
}
else
{
hasOne = true;
p = (*it);
}
}
}
return hasOne;
}
bool CSGTree::intersect(const ray& r, isect& i) const
{
if (!root) return false;
Segments* inters = root->intersectLocal(r);
SegmentPoint sp;
if (!inters->firstPositive(sp)) return false;
i.t = sp.t;
if (sp.isRight)
{
i.N = (sp.normal * r.getDirection() > RAY_EPSILON) ? sp.normal : -sp.normal;
}
else
{
i.N = (sp.normal * r.getDirection() > RAY_EPSILON) ? -sp.normal : sp.normal;
}
return true;
}
Segments* CSGNode::intersectLocal(const ray& r) const
{
Segments* result = new Segments();
if (isLeaf)
{
SegmentPoint pNear, pFar;
isect i;
ray backR(r.at(-10000), r.getDirection());
if (!object->intersect(backR, i)) return result;
pNear.t = i.t - 10000;
pNear.normal = i.N;
pNear.isRight = false;
ray contiR(r.at(pNear.t + RAY_EPSILON * 10), r.getDirection());
if (!object->intersect(contiR, i))
{
pFar = pNear;
}
else
{
pFar.t = i.t + pNear.t;
pFar.normal = i.N;
}
pFar.isRight = true;
result->addPoint(pNear);
result->addPoint(pFar);
return result;
}
else
{
if (!lchild || !rchild) return result;
Segments* leftSeg = new Segments();
Segments* rightSeg = new Segments();
leftSeg = lchild->intersectLocal(r);
rightSeg = rchild->intersectLocal(r);
leftSeg->Merge(*rightSeg, relation);
return leftSeg;
}
}
BoundingBox CSGNode::getBoundingBox() const
{
return bound;
}
void CSGNode::computeBoundingBox()
{
if (isLeaf)
{
bound = object->getBoundingBox();
}
else
{
if (!lchild || !rchild)
{
bound = BoundingBox();
}
bound = lchild->getBoundingBox();
bound.plus(rchild->getBoundingBox());
}
}
bool CSG::intersectLocal(const ray& r, isect& i) const
{
if (!tree->intersect(r, i)) return false;
i.obj = this;
return true;
}
BoundingBox CSG::ComputeLocalBoundingBox(){
CSGNode* rt = tree->getRoot();
if (!rt) return BoundingBox();
return rt->getBoundingBox();
} | true |
3a2aeaa9caec7499ee20b916449f63d0fea23e7c | C++ | Annihilater/Cpp-Primer-Plus-Source-Code-And-Exercise | /Chapter 12/12_10_1/cow.cpp | UTF-8 | 865 | 3.203125 | 3 | [] | no_license | //
// Created by klause on 2020/8/6.
//
#include "cow.h"
#include <string>
#include <iostream>
Cow::Cow() {
strcpy(name, "name");
hobby = new char[6];
strcpy(hobby, "hobby");
weight = 0;
}
Cow::Cow(const char *nm, const char *ho, double wt) {
strcpy(name, nm);
hobby = new char[strlen(ho) + 1];
strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow &c) {
strcpy(name, c.name);
hobby = new char[strlen(c.hobby) + 1];
strcpy(hobby, c.hobby);
weight = c.weight;
}
Cow::~Cow() {
delete hobby;
}
Cow &Cow::operator=(const Cow &c) {
strcpy(name, c.name);
strcpy(hobby, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const {
std::cout << "name : " << name << std::endl;
std::cout << "hobby : " << hobby << std::endl;
std::cout << "weight : " << weight << std::endl;
}
| true |
a9defb7a1083e2684ab9da210110255bd9c5ade5 | C++ | LRY1994/Battery-QT | /battery/current.cpp | UTF-8 | 1,431 | 2.78125 | 3 | [] | no_license | #include "current.h"
#include "struct.h"
#include <fstream>
#include <cstring>
#include "stdio.h"
#include "var.h"
#include "assert.h"
using namespace std;
vector<string> split(const string& str, const string& delim) {
vector<string> res;
if("" == str) return res;
//先将要切割的字符串从string类型转换为char*类型
char * strs = new char[str.length() + 1] ;
strcpy(strs, str.c_str());
char * d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while(p) {
string s = p; //分割得到的字符串转换为string类型
res.push_back(s); //存入结果数组
p = strtok(NULL, d);
}
return res;
}
Current::Current()
{
processData("UDDS.txt",0 ,10);
}
//data process
void Current::processData(char* fileName, int from, int to){
ifstream readstream;
printf("beforeopen");
readstream.open(string(fileName).data());
assert(readstream.is_open());
int i = 0;
while (!readstream.eof()){
string inbuf;
getline(readstream, inbuf, '\n');
printf("i");
write<<inbuf;
if(i<=to && i >=from){
vector<string> res = split(inbuf, " ");
// points.push_back(Point(int(res[0]),double(res[1])))
}
if(i>to) break;
i++;
}
readstream.close();
}
| true |
51a47adcd556db8cf33c3c27dfd8de8a799b2574 | C++ | zaqwsx1277/prS63BruteForce | /server/prS63BruteForceServer/TConnectionServer.cpp | UTF-8 | 1,693 | 2.546875 | 3 | [
"MIT"
] | permissive | #include "TConnectionServer.hpp"
#include "TException.hpp"
using namespace connection ;
//---------------------------------------------------
/*!
* \brief connection::TConnectionServer::TConnectionServer Конструктор
*/
TConnectionServer::TConnectionServer(const qint32& inPortNumber) : TConnection ()
{
fPtrServer = std::make_unique <QTcpServer> () ;
if (!fPtrServer -> listen(QHostAddress::Any, inPortNumber)) throw exception::errServerStart ;
// Прописываем все конекты необходимые для работы сервера. Он нужен только для обработки новых подключений и передачи QTcpSocket менеджеру новых подключений
connect(fPtrServer.get(), &QTcpServer::newConnection, this, &TConnectionServer::slotNewHostConnected) ;
}
//---------------------------------------------------
/*!
* \brief TConnectionServer::~TConnectionServer Деструктор
*/
TConnectionServer::~TConnectionServer()
{
fPtrServer.reset();
}
//---------------------------------------------------
/*!
* \brief TConnectionServer::slotHostConnected Слот срабатывающий при нового подключении клиента
*/
void TConnectionServer::slotNewHostConnected ()
{
QTcpSocket* tcpSocked = fPtrServer -> nextPendingConnection() ;
if (tcpSocked!= nullptr) { // При подключении нового клиента кидаем сигнал серверу с его сокетом
emit signalNewHostConnected (tcpSocked) ;
}
}
//---------------------------------------------------
| true |
c5510760f302986f92554da09338576115771592 | C++ | Stvad/LabirintEditor | /box.cpp | UTF-8 | 11,373 | 2.625 | 3 | [] | no_license | #include "box.h"
/*
float Object::x = 0;
float Object::y = 0;
float Object::z = 0;
std::vector <Vertex> Object::points;
std::vector <unsigned short> Object::indexes;
*/
Box::Box()
: Position()
{
this->Angle = 0;
}
Box::Box(const std::vector<Vertex> &points, const std::vector<unsigned short> &indexes, float Angle, Point3D Position)
{
//this->points = points;
//this->indexes = indexes;
this->Angle = Angle;
this->Position = Position;
}
Box::Box(const std::vector<Vertex> &points, const std::vector<unsigned short> &indexes, float Widght, float Height, float Lenght, float VertexPerWidght, float VertexPerHeight, float VertexPerLenght)
{
m_points = new Vertex[points.size()];
m_indexes = new unsigned short[indexes.size()];
m_IndexSize = indexes.size();
for (uint i=0; i< points.size(); i++)
{
m_points[i] = points[i];
}
for (uint j=0; j< indexes.size(); j++)
{
m_indexes[j] = indexes[j];
}
this->Widght = Widght;
this->Height = Height;
this->Lenght = Lenght;
this->VertexPerHeight = VertexPerHeight;
this->VertexPerLenght = VertexPerLenght;
this->VertexPerWidght = VertexPerWidght;
Angle = 0;
Color = Qt::blue;
}
/*void Box::Show()
{
glPushMatrix();
glTranslatef(Position.x, Position.y, Position.z);
glRotatef(Angle, 0, 1, 0);
glColor3f(Color.redF(), Color.greenF(), Color.blueF());
glInterleavedArrays(GL_T2F_N3F_V3F, 0, m_points);
glDrawElements(GL_TRIANGLES, m_IndexSize, GL_UNSIGNED_SHORT, m_indexes);
glPopMatrix();
}*/
QDomElement Box::Serialize(QDomDocument& DomDocument)
{
QDomElement BoxNode = DomDocument.createElement("Box");
QString sPosition, sColor;
sPosition.sprintf("%f, %f, %f", Position.x, Position.y, Position.z);
sColor.sprintf("%i, %i, %i", Color.red(), Color.green(), Color.blue());
BoxNode.setAttribute("Position", sPosition);
BoxNode.setAttribute("Rotation", Angle);
BoxNode.setAttribute("Color", sColor);
BoxNode.setAttribute("Texture_name", "");
QDomElement OptionsNode = DomDocument.createElement("Options");
QDomElement SizeNode = DomDocument.createElement("Size");
SizeNode.setAttribute("Widght", Widght);
SizeNode.setAttribute("Height", Height);
SizeNode.setAttribute("Lenght", Lenght);
QDomElement VpsNode = DomDocument.createElement("VPS");
VpsNode.setAttribute("Vertex_per_widght", VertexPerWidght);
VpsNode.setAttribute("Vertex_per_height", VertexPerHeight);
VpsNode.setAttribute("Vertex_per_lenght", VertexPerLenght);
QDomElement OtherOptionsNode = DomDocument.createElement("Other");
OptionsNode.appendChild(SizeNode);
OptionsNode.appendChild(VpsNode);
OptionsNode.appendChild(OtherOptionsNode);
BoxNode.appendChild(OptionsNode);
return BoxNode;
}
bool Box::Deserialize(const QDomElement& DomElement)
{
if(DomElement.tagName() != "Box") return false;
int nNodeCount = 0;
bool bIsOk1, bIsOk2, bIsOk3;
DomElement.attribute("Texture", "none");
QDomElement OptionsNode = DomElement.firstChildElement("Options");
if(!OptionsNode.isNull())
{
QDomElement SizeNode = OptionsNode.firstChildElement("Size");
if(!SizeNode.isNull())
{
Widght = SizeNode.attribute("Widght").toFloat(&bIsOk1);
Height = SizeNode.attribute("Height").toFloat(&bIsOk2);
Lenght = SizeNode.attribute("Lenght").toFloat(&bIsOk3);
if(bIsOk1 && bIsOk2 && bIsOk3)
nNodeCount++;
}
QDomElement VpsNode = OptionsNode.firstChildElement("VPS");
if(!SizeNode.isNull())
{
VertexPerWidght = VpsNode.attribute("Vertex_per_widght").toFloat(&bIsOk1);
VertexPerHeight = VpsNode.attribute("Vertex_per_height").toFloat(&bIsOk2);
VertexPerLenght = VpsNode.attribute("Vertex_per_lenght").toFloat(&bIsOk3);
if(bIsOk1 && bIsOk2 && bIsOk3)
nNodeCount++;
}
QDomElement OtherNode = OptionsNode.firstChildElement("Other");
if(!OtherNode.isNull())
{
}
}
this->CreateBox(Widght, Height, Lenght, VertexPerWidght, VertexPerHeight, VertexPerLenght);
QStringList sl = DomElement.attribute("Position", "1,1,1").split(",");
Position.x = sl[0].toFloat(&bIsOk1);
Position.y = sl[1].toFloat(&bIsOk2);
Position.z = sl[2].toFloat(&bIsOk3);
if(bIsOk1 && bIsOk2 && bIsOk3)
nNodeCount++;
sl = DomElement.attribute("Color", "127,127,127").split(",");
Color.setRed(sl[0].toInt(&bIsOk1));
Color.setGreen(sl[1].toInt(&bIsOk2));
Color.setBlue(sl[2].toInt(&bIsOk3));
if(bIsOk1 && bIsOk2 && bIsOk3)
nNodeCount++;
Angle = DomElement.attribute("Rotation").toFloat(&bIsOk1);
if(bIsOk1)
nNodeCount++;
return nNodeCount == 5;
}
void Box::CreateBox(float Widht, float Height, float Lenght, float VertexPerWidht, float VertexPerHeight, float VertexPerLenght)
{
this->Widght = Widght;
this->Height = Height;
this->Lenght = Lenght;
this->VertexPerHeight = VertexPerHeight;
this->VertexPerLenght = VertexPerLenght;
this->VertexPerWidght = VertexPerWidght;
points.clear();
indexes.clear();
float xn, yn, zn;
xn = Widht / VertexPerWidht;
yn = Height / VertexPerHeight;
zn = Lenght / VertexPerLenght;
Point3D rPosition(0, 0, 0);
IVerticalPlane(rPosition, Widht, Height, Lenght, xn, yn, zn);
IHorizontalPlane(rPosition, Widht, Height, Lenght, xn, yn, zn);
rPosition.z +=Lenght;
IVerticalPlaneNext(rPosition, Widht, Height, Lenght, xn, yn, zn);
rPosition.y +=Height;
rPosition.z -=Lenght;
IHorizontalPlaneNext(rPosition, Widht, Height, Lenght, xn, yn, zn);
rPosition.y -=Height;
IBokovPlane(rPosition, Widht, Height, Lenght, xn, yn, zn);
rPosition.x +=Widht;
IBokovPlaneNext(rPosition, Widht, Height, Lenght, xn, yn, zn);
m_points = new Vertex[points.size()];
m_indexes = new unsigned short[indexes.size()];
m_IndexSize = indexes.size();
for (uint i=0; i< points.size(); i++)
{
m_points[i] = points[i];
}
for (uint j=0; j< indexes.size(); j++)
{
m_indexes[j] = indexes[j];
}
//return Box(points, indexes, Widht, Height, Lenght, VertexPerWidht, VertexPerHeight, VertexPerLenght);
}
void Box::IVerticalPlane(Point3D Position, float Widht, float Height, float Lenght, float xn, float yn, float zn)
{
// Point3D Temp;
Vertex Temp;
Temp.Position.z = Position.z;
for(y = Position.y; y < Height; y+=yn)
for(x = Position.x; x < Widht; x+=xn)
{
int base = points.size();
Temp.Position.x = x;
Temp.Position.y = y;
points.push_back(Temp);
indexes.push_back(0 + base);
Temp.Position.x += xn;
Temp.Position.y += yn;
points.push_back(Temp);
indexes.push_back(1 + base);
Temp.Position.x = x;
points.push_back(Temp);
indexes.push_back(2 + base);
Temp.Position.y = y;
indexes.push_back(0 + base);
Temp.Position.x += xn;
points.push_back(Temp);
indexes.push_back(3 + base);
Temp.Position.y += yn;
indexes.push_back(1 + base);
}
}
void Box::IHorizontalPlane(Point3D Position, float Widht, float Height, float Lenght, float xn, float yn, float zn)
{
Vertex Temp;
Temp.Position.x = Position.x;
Temp.Position.y = Position.y;
Temp.Position.z = Position.z;
int base = points.size();
points.push_back(Temp);
indexes.push_back(0 + base);
Temp.Position.x += Widht;
Temp.Position.z += Lenght;
points.push_back(Temp);
indexes.push_back(1 + base);
Temp.Position.x = Position.x;
points.push_back(Temp);
indexes.push_back(2 + base);
Temp.Position.x = Position.x;
Temp.Position.y = Position.y;
Temp.Position.z = Position.z;
indexes.push_back(0 + base);
Temp.Position.x += Widht;
points.push_back(Temp);
indexes.push_back(3 + base);
Temp.Position.z += Lenght;
indexes.push_back(1 + base);
}
void Box::IBokovPlane(Point3D Position, float Widht, float Height, float Lenght, float xn, float yn, float zn)
{
Vertex Temp;
Temp.Position.x = Position.x;
Temp.Position.y = Position.y;
Temp.Position.z = Position.z;
int base = points.size();
points.push_back(Temp);
indexes.push_back(0 + base);
Temp.Position.y += Height;
Temp.Position.z += Lenght;
points.push_back(Temp);
indexes.push_back(1 + base);
Temp.Position.z -= Lenght;
points.push_back(Temp);
indexes.push_back(2 + base);
Temp.Position.y -= Height;
indexes.push_back(0 + base);
Temp.Position.z += Lenght;
points.push_back(Temp);
indexes.push_back(3 + base);
Temp.Position.y += Height;
indexes.push_back(1 + base);
}
void Box::IVerticalPlaneNext(Point3D Position, float Widht, float Height, float Lenght, float xn, float yn, float zn)
{
Vertex Temp;
Temp.Position.z = Position.z;
for(y = Position.y; y < Height; y+=yn)
for(x = Position.x; x < Widht; x+=xn)
{
int base = points.size();
Temp.Position.x = x;
Temp.Position.y = y;
points.push_back(Temp);
indexes.push_back(0 + base);
Temp.Position.y += yn;
points.push_back(Temp);
indexes.push_back(1 + base);
Temp.Position.x += xn;
points.push_back(Temp);
indexes.push_back(2 + base);
indexes.push_back(2 + base);
Temp.Position.y = y;
points.push_back(Temp);
indexes.push_back(3 + base);
Temp.Position.x = x;
indexes.push_back(0 + base);
}
}
void Box::IHorizontalPlaneNext(Point3D Position, float Widht, float Height, float Lenght, float xn, float yn, float zn)
{
Vertex Temp;
Temp.Position.x = Position.x;
Temp.Position.y = Position.y;
Temp.Position.z = Position.z;
int base = points.size();
points.push_back(Temp);
indexes.push_back(0 + base);
Temp.Position.z += Lenght;
points.push_back(Temp);
indexes.push_back(1 + base);
Temp.Position.x += Widht;
points.push_back(Temp);
indexes.push_back(2 + base);
Temp.Position.x = Position.x;
Temp.Position.z = Position.z;
indexes.push_back(2 + base);
Temp.Position.x += Widht;
Temp.Position.z += Lenght;
indexes.push_back(3 + base);
Temp.Position.z = Position.z;
points.push_back(Temp);
indexes.push_back(0 + base);
}
void Box::IBokovPlaneNext(Point3D Position, float Widht, float Height, float Lenght, float xn, float yn, float zn)
{
Vertex Temp;
Temp.Position.x = Position.x;
Temp.Position.y = Position.y;
Temp.Position.z = Position.z;
int base = points.size();
points.push_back(Temp);
indexes.push_back(0 + base);
Temp.Position.y += Height;
points.push_back(Temp);
indexes.push_back(1 + base);
Temp.Position.z += Lenght;
points.push_back(Temp);
indexes.push_back(2 + base);
indexes.push_back(2 + base);
Temp.Position.y -= Height;
points.push_back(Temp);
indexes.push_back(3 + base);
Temp.Position.z -= Lenght;
indexes.push_back(0 + base);
}
| true |
9f4d0480d46f4d381cd1b62f204492f85c9d6cd8 | C++ | tj3407/CS413 | /quicksort.cpp | UTF-8 | 1,837 | 3.71875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int counter;
int partition( int a [], int low , int high ) {
int x = a [ low ];
bool highTurn = true ;
while ( low < high ) {
counter++; // to count item comparisons highlighted in green
if (highTurn)
if ( a [ high ] >= x ) high --;
else {
a [ low ++] = a [ high ];
highTurn = false ;
}
else
if ( a [ low ] <= x ) low ++;
else {
a [ high --] = a [ low ];
highTurn = true ;
}
}
a [ low ] = x;
return low ;
}
void quicksort1( int a [], int start , int end ) {
if ( start >= end ) return ;
int mid = partition( a , start , end );
quicksort1( a , start , mid - 1);
quicksort1( a , mid + 1, end );
}
void quicksort( int a [], int length ) {
quicksort1( a , 0, length - 1);
}
void test( int array [], int length ) {
counter = 0;
quicksort( array , length );
cout << "For length = " << length << ", counter = " << counter << endl;
}
int main() {
// Array contents for a1, a2, a3 give best case counts for their respective sizes.
int a1[] = { 0 }, // Array size 2^1 - 1
a2[] = { 1, 0, 2 }, // Array size 2^2 - 1
a3[] = { 3, 0, 2, 1, 5, 4, 6 }, // Array size 2^3 – 1
// Edit the line below so that a4 gives a best case count. Reorder the original values 0, 1, ..., 13, 14.
a4[] = { 7, 0, 2, 1, 5, 4, 6, 3, 11, 8, 10, 9, 13, 12, 14 }; // Array size 2^4 – 1
test(a1, 1);
test(a2, 3);
test(a3, 7);
test(a4, 15);
return 0;
} | true |
ecfc07b2bb59935236e945486115c7394d80349e | C++ | JanTry/GameOf1000 | /card.h | UTF-8 | 837 | 3.09375 | 3 | [] | no_license | #ifndef CARD
#define CARD
#include "imports.h"
class Card{
public:
//Both suit and value are publicly known to all players who can see the card
//No point in writing getters to them
int suit; //card color
int value; //card value
bool trump; //Not Donald though
bool marriage; //King or Queen
inline std::string get_file_name();
Card(int suit, int value): suit{suit} , value{value} , trump{false} , marriage{(value == KING || value == QUEEN)} { }
void set_trump(){ trump = true; }
void unset_trump(){ trump = false; }
inline bool operator<(const Card& other_card) const;
inline bool operator>(const Card& other_card) const;
inline bool operator==(const Card& other_card) const;
};
#include "card.cc"
#endif //CARD
| true |
8dfcf00111bd3944493e6369e66228636c378e3e | C++ | vdae2304/Contest-archive | /UVA Online Judge/3. Problem Solving Paradigms/416 - LED Test.cpp | UTF-8 | 1,593 | 3.140625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); cin.tie();
int N;
string leds[10];
string digits[10] = {"YYYYYYN", "NYYNNNN", "YYNYYNY", "YYYYNNY", "NYYNNYY",
"YNYYNYY", "YNYYYYY", "YYYNNNN", "YYYYYYY", "YYYYNYY"};
while (cin >> N, N != 0) {
for (int i = 0; i < N; ++i)
cin >> leds[i];
//Supone que la cuenta regresiva empieza en t.
bool valid = false;
for (int t = N - 1; t < 10; ++t) {
//Verifica si la cuenta regresiva pudo haber empezado en t.
bool ok = true;
bool burned[7] = {};
for (int i = 0; i < N; ++i)
for (int j = 0; j < 7; ++j) {
//Si el led esta encendido cuando deberia estar fundido o apagado,
//significa que no es una cuenta regresiva valida.
if (leds[i][j] == 'Y' && (burned[j] || digits[t - i][j] == 'N'))
ok = false;
//Si el led esta apagado cuando deberia estar encendido, significa
//que se fundio.
if (leds[i][j] == 'N' && digits[t - i][j] == 'Y')
burned[j] = true;
}
//Encontramos una cuenta regresiva valida.
if (ok) {
valid = true;
break;
}
}
//Imprime la respuesta.
if (valid)
cout << "MATCH\n";
else
cout << "MISMATCH\n";
}
return 0;
} | true |
1da5b4124c76d47ed7a4a2e94348bda50c888773 | C++ | shinhaha/Fall_2017_Algorithm | /AllSourceShortestPath/DynamicAllSourceShortestPath.cpp | UHC | 3,111 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <stdlib.h>
using namespace std;
#define INF 2000000000
int Edgesize = 0;//
int Versize = 0;//
int** arr;
int** ExtendShortestPaths(int** A,int** B);
int** newArr();
void SlowAllPairsShortestPaths();
void print(int** A,int i);
void SlowAllPairsShortestPaths() {
printf("SlowAllPairsShortestPaths\n");
int** first = newArr();//n*n迭 L1
for (int i = 0; i < Versize; i++)
for (int j = 0; j < Versize; j++)
first[i][j] = arr[i][j];//first迭
print(first,0);//L0
for (int i = 1; i <Versize-1; i++) {
first = ExtendShortestPaths(first,arr);//first迭 arr ª Ʈ first ־
print(first,i);//first Li
}
}
void FasterAllPairsShortestPaths() {
printf("FasterAllPairsShortestPaths\n");
int** first = newArr();//n*n迭 L1
for (int i = 0; i < Versize; i++)
for (int j = 0; j < Versize; j++)
first[i][j] = arr[i][j];//frst 迭
int m = 1;
print(first,0);//L0
while (m <Versize-1) {//̳ α ̿Ͽ
first= ExtendShortestPaths(first,first);//first迭 Ͽ fisrt迭 Ʈ Ѱ first ־ش
print(first,m);//Lm Ѵ
m *= 2;//m 2 ش
}
}
int** ExtendShortestPaths(int** A,int** B) {//B迭 Ͽ A迭 ª η Ʈϴ Լ
int** newArrays = newArr();
for (int i = 0; i < Versize; i++)
for (int j = 0; j < Versize; j++) {
newArrays[i][j] = INF;// ū ʱȭ
for (int k = 0; k < Versize; k++)
if(B[k][j]!=INF&&A[i][k]!=INF)//÷ο
newArrays[i][j] = min(newArrays[i][j], A[i][k] + B[k][j]);
}
return newArrays;
}
int** newArr() {//n*n迭
int** arrtemp = (int**)malloc(sizeof(int*)*Versize);
for (int q = 0; q < Versize; q++)
arrtemp[q] = (int*)malloc(sizeof(int)*Versize);
return arrtemp;
}
void print(int** A,int i) {//ϴ Լ
printf("(%d)\n", i);
for (int i = 0; i < Versize; i++) {
printf("\n");
for (int j = 0; j < Versize; j++)
if (A[i][j] == INF)//Ѵ ΰ
printf(" X");
else
printf("%5d", A[i][j]);
}
printf("\n");
}
int main(void) {
FILE *f = NULL;
fopen_s(&f, "C:\\Users\\϶\\Desktop\\graph_sample_directed.txt", "r");
if (f != NULL) {
while (!feof(f)) {
if (Edgesize == 0) {
fscanf(f, "%d", &Versize);
arr = (int**)malloc(sizeof(int*)*Versize);
for (int i = 0; i < Versize; i++)
arr[i] = (int*)malloc(sizeof(int)*Versize);
for (int i = 0; i < Versize; i++)
for (int j = 0; j < Versize; j++)
if (i == j)
arr[i][j] = 0;
else
arr[i][j] = INF;
}
int q, w, e;//,,cost
fscanf(f, "%d", &q);
fscanf(f, "%d", &w);
fscanf(f, "%d", &e);
arr[q][w] = e;
Edgesize++;// ++
}
fclose(f);
}
else
printf(" б ");
SlowAllPairsShortestPaths();//Slow
FasterAllPairsShortestPaths();//Faster
}
| true |
4471a3196c9b1ea05c0dfd6fa4c2fb619ffe043c | C++ | snousias/avatree | /src/AVATreeExtensionGUI/bbox.h | UTF-8 | 651 | 2.9375 | 3 | [
"CC-BY-4.0"
] | permissive | #ifndef _BBox_H_
#define _BBox_H_
#include <QVector3D>
/*******************************************************************************
BBox
******************************************************************************/
class BBox
{
public:
// Ctor
BBox() : m_center(), m_max(){}
BBox(QVector3D center, QVector3D max) : m_center(center), m_max(max){}
~BBox(){}
public:
// Methods
const QVector3D& center() { return m_center; }
const QVector3D& max(){return m_max;}
void set(const QVector3D& center, const QVector3D& max)
{
m_center = center;
m_max = max;
}
public:
// Data members
QVector3D m_center;
QVector3D m_max;
};
#endif | true |
0c40269ffcf8895468fd2de007cecda06aec948a | C++ | lingchensanwen/CPP-course-projects | /week7/week7-1.cpp | UTF-8 | 743 | 2.8125 | 3 | [] | no_license | #if 0
20分かかりました。木について復習しました。
最初は何を出力すればいいか迷ったことがあります。
そのあとはすらすら解決できて、よかったです。
#endif 0
#include <iostream>
using namespace std;
int P[10010];
void init(int N) {
for (int i=0; i<=N; ++i) P[i] = i;
}
int root(int a) {
if (P[a] == a) return a;
return (P[a] = root(P[a]));
}
bool is_same_set(int a, int b) {
return root(a) == root(b);
}
void unite(int a, int b) {
P[root(a)] = root(b);
}
int main() {
int n, q;
int oper;
int a,b;
cin >> n >> q;
init(n);
for(int i = 0; i < q; i++){
cin >> oper;
cin >> a >> b;
if(oper == 0)unite(a,b);
if(oper == 1)cout << is_same_set(a,b) << endl;
}
}
| true |