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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bde1ffabb709900997751e3641be2bef7cc536c3 | C++ | dg5921096/Books-solutions | /C++ for Everyone, 2nd Ed, Horstmann/Chapter2/P2-4.cpp | WINDOWS-1252 | 926 | 4.75 | 5 | [] | no_license | //Write a program that prompts the user for two integers and then prints
// The sum
// The difference
// The product
// The average
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int number1;
int number2;
cout << "Enter number 1 and number 2\n";
cin >> number1 >> number2;
cout << "Type:\n 1 => sum, \n 2 => difference,\n 3 => product \n 4=> average\n";
int user_input;
cin >> user_input;
double result = 0;
switch(user_input)
{
case 1:
result = number1 + number2;
break;
case 2:
result = number1 - number2;
break;
case 3:
result = number1 * number2;
break;
case 4:
result = (number1 + number2) / 2;
break;
default:
cout << "Invalid input\n";
}
cout << result;
return 0;
}
| true |
28219fda874b61ca024bb8cce510734b062348f5 | C++ | Tangjiahui26/CrackingCode | /BitManipulation/Insertion/main.cpp | UTF-8 | 511 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int updateBits(int n, int m, int i, int j){
int allOnes = ~0;
int right = allOnes << (j+1);
int left = (1 << i) - 1;
int mask = right | left;
int n_cleared = n & mask;
int m_shifted = m << i;
return n_cleared | m_shifted;
}
int main()
{
int n = 1024;
int m = 19;
int i = 2;
int j = 6;
int result = updateBits(n, m, i, j);
// output should be 1100
cout << "Output is: " << result << endl;
return 0;
}
| true |
5b329cb1e9d93a1380c395651f07c02b2464dfda | C++ | jungchunkim/study_algorithm | /sorting_algorithm/sorting_3.cpp | UTF-8 | 581 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int N, K;
cin >> N >> K;
vector<int> arr;
vector<int> brr;
int num;
for (int i = 0; i < N; i++)
{
cin >> num;
arr.push_back(num);
}
for (int i = 0; i < N; i++)
{
cin >> num;
brr.push_back(num);
}
sort(arr.begin(), arr.end());
sort(brr.begin(), brr.end());
for (int i = 0; i < K; i++)
{
if (arr[i] < brr[(N - 1) - i])
arr[i] = brr[(N - 1) - i];
else
{
break;
}
}
int sum = 0;
for (int i = 0; i < N; i++)
{
sum += arr[i];
}
cout << sum;
} | true |
45ae14daa18b2fac7b15cf5296f1b0f892beccdc | C++ | Chris-SG/practosu | /practosu/osutools/func.hpp | UTF-8 | 2,729 | 2.578125 | 3 | [] | no_license | // TODO convert from class into namespace
#pragma once
#include "stdafx.h"
// General namespace for all osu_tools
namespace osu_tools
{
// Contains general functions used by the program for various
// reasons.
class func
{
public:
// osu_running checks if the osu! process is currently running.
static bool osu_running();
// get_beatmap_directory retrieves the directory beatmaps are stored.
static std::experimental::filesystem::path get_beatmap_directory();
// get_osu_directory retrieves osu!'s running directory.
static std::experimental::filesystem::path get_osu_directory();
// get_current_beatmap gets the beatmap currently selected ingame.
static std::experimental::filesystem::path get_current_beatmap();
// pattern mask to scan for in memory
const static inline unsigned char m_beatmap_mask[] = "\xC0\x0F\x84\x80\x01\x00\x00\x8D\x00\x00\x00\x00\x0D\xEC\x41\x00";
//const static inline unsigned char m_beatmap_mask[] = "\xC0\x0F\x8E\x8F\x01\x00\x00\xA1\x00\x00\x00\x00\x89\x45\xC0\x85";
// apply size to mask
const static inline char m_beatmap_mask_sz[] = "xxxxxxxx????xxx?";
// pointer to beatmap
static inline DWORD m_beatmap_pointer = 0;
// Manual pointer search values
const static inline unsigned char m_my_love_easy[] = "\xE0\x10\x06\x00\x28\x7D\x02\x00";
const static inline unsigned char m_my_love_medium[] = "\xDE\x10\x06\x00\x28\x7D\x02\x00";
const static inline unsigned char m_my_love_hard[] = "\xDF\x10\x06\x00\x28\x7D\x02\x00";
const static inline char m_my_love_easy_sz[] = "xxxxxxxx";
const static inline char m_my_love_medium_sz[] = "xxxxxxxx";
const static inline char m_my_love_hard_sz[] = "xxxxxxxx";
// Options used in manual pointer search
static inline std::vector<DWORD> m_options;
static inline uint8_t m_progress = 0;
// get_osu_wind_handle gets the handle for the osu! window.
static HWND get_osu_wind_handle(const int& p_retry = 0);
// get_osu_proc_id gets the process id for osu!
static DWORD get_osu_proc_id();
// get_osu_proc_handle gets the handle for osu!
static void get_osu_proc_handle(HANDLE &f_hdl);
// get_osu_base_address gets the base address of the osu! process
static LPVOID get_osu_base_address();
// get_osu_beatmap_pointer gets the pointer to the current osu! beatmap pointer.
static DWORD get_osu_beatmap_pointer(bool a_force = false);
// backup method of searching for beatmap pointer
static void backup_pointer_search();
// Finds a given pattern based on the passed mask within a block of data
static DWORD __stdcall FindPattern(std::vector<unsigned char> data, unsigned int base_address, const unsigned char* lp_pattern, const char* psz_mask, int offset, int result_usage);
};
} | true |
d2bd18681f8d7bca070182a1df699b2370fe950d | C++ | yahiabrd/SupSudoku | /main.cpp | ISO-8859-1 | 2,092 | 3.75 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h> //librairie qui contient le system("cls") pour effacer l'cran
#include "BOX.h"
using namespace std;
/**
* Fonction affichant le Menu
*/
void Menu(){
int choice;
char answer;
bool continueProgram = true;
BOX sudoku(false); //instanciation avec false (on ne pourra donc pas modifier les cases de dpart)
cout << "Bienvenue dans le jeu SupSudoku !" << endl << endl;
while(continueProgram){
cout << "---------------------------" << endl;
cout << "| Menu |" << endl;
cout << "---------------------------" << endl;
cout << "Niveaux : " << endl;
cout << "\t1 - Niveau facile" << endl;
cout << "\t2 - Niveau Moyen" << endl;
cout << "\t3 - Niveau difficile" << endl;
cout << endl;
cout << "Informations : " << endl;
cout << "\t4 - Regles du jeu" << endl;
cout << "\t5 - A propos" << endl;
cout << endl;
cout << "Que voulez-vous faire ? : ";
cin >> choice;
switch(choice){
case 1:
sudoku.initEasyLevel();
break;
case 2:
sudoku.initMediumLevel();
break;
case 3:
sudoku.initHardLevel();
break;
case 4:
sudoku.rules();
break;
case 5:
sudoku.about();
break;
default:
cout << endl << "Le numero entre ne correspond a rien dans le menu" << endl << endl;
break;
}
cout << "Voulez-vous continuer sur le menu ? O/N : ";
cin >> answer;
system("cls");//permet d'effacer la console
//verifie si le caractere entr est different de "o" ou "O" en le mettant en majuscule
if (toupper(answer) != 'O'){
continueProgram = false;
cout << "A bientot !" << endl;
}
}
}
/**
* Fonction principale du programme
*/
int main()
{
Menu();
return 0;
}
| true |
34697b26d52bd034cd4dd4a21375317c40d05231 | C++ | xbwang2018/SimpleCompiler | /c-sub/parser/parser.cpp | UTF-8 | 907 | 2.734375 | 3 | [
"MIT"
] | permissive |
// This file is a part of MRNIU/SimpleCompiler (https://github.com/MRNIU/SimpleCompiler).
//
// parser.cpp for MRNIU/SimpleCompiler.
#include "parser.h"
Parser::Parser(Lexer &lex) : lexer(lex) {
return;
}
Parser::~Parser() {
return;
}
// 获取下一个 token
void Parser::next(void) {
token = lexer.lexing();
return;
}
// 匹配指定 Token
bool Parser::match_token(Tag tag) {
if(token->tag == tag) {
// 如果匹配到了就读入下一个
next();
return true;
}
else {
return false;
}
}
// 进行解析,返回解析结果(AST)
void Parser::parsing(void) {
this->next();
program();
}
// 程序由代码片段与程序组成
void Parser::program(void) {
if(is_done() ) {
return;
}
else {
segment();
program();
}
return;
}
// 代码片段由声明与定义组成
void Parser::segment(void) {
return;
}
bool Parser::is_done(void) const {
return lexer.is_done();
}
| true |
35fec7d316ea1d4fbc38dddca126e7f3468f0431 | C++ | faizannadeem784/OOP | /New folder (2)/Semester 2/Oop/Runtime polymorphism/Faizan NAdeem_19014065002...BSSE_.cpp | UTF-8 | 1,133 | 3.40625 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
class Person{
public:
int password;
string uname;
virtual void login()=0;
};
class Batch_adviser:public Person{
public:
int password;
string uname;
void login()
{
cout<<"**********Batch_Advisor portal**********"<<endl;
cout<<"Enter username"<<endl;
cin>>uname;
cout<<"Enter password"<<endl;
cin>>password;
if(password==123&&uname=="batch")
{
cout<<"Welcome to batch advisor derived class"<<endl;
}
else
{
cout<<"You Have an Invalid ID or Password";
}
}
};
class Student:public Person{
public:
int password;
string uname;
public:
void login()
{
cout<<"**********STUDENT Portal**********"<<endl;
cout<<"Enter userame"<<endl;
cin>>uname;
cout<<"Enter password"<<endl;
cin>>password;
if(password==123&&uname=="student")
{
cout<<"Welcome to student drived class"<<endl;
}
else
{
cout<<"You Have Enter an invalid password";
}
}
};
int main()
{
Person *p;
Student std;
p = &std;
p->login();
Batch_adviser b;
p = &b;
p->login();
return 0;
}
| true |
2d53b69faaf2daa732ed8810d637d8541a53c7a1 | C++ | RandyViG/Sistemas-Distribuidos | /Practica7/ejercicio3.cpp | UTF-8 | 511 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cstdlib>
#include<ctime>
using namespace std;
int r,f ;
int main() {
srand(time(0));
//f=1000*((26)^3);
int cont=0;
string cadena1(""),cadena2("");
for(int j=0;j<87000000;j++){
for(int i=0; i<3; i++) {
r=65 + rand() % 25;
cadena1+=r;
}
cadena1=cadena1+" ";
cadena2+=cadena1;
}
for (int i=0; i < 87000000;i+=4){
if (cadena2[i]=='I' && cadena2[i+1]=='P' && cadena2[i+2]=='N')
cont++;
}
cout << "Ocurrencias: " << cont;
return 0;
}
| true |
3ff62e105bbdae77682ff5595491b9aecb44e867 | C++ | hamzaaitelhaj/TP-C- | /TP1/BANQUE/BANQUE/BANQUE.h | UTF-8 | 295 | 2.796875 | 3 | [] | no_license |
class Compte
{
public:
Compte();
Compte(int, const char*, float);
bool retirerArgent(float);
Compte deposerArgent(float);
void consulterSolde() ;
Compte transfererArgent(float,const Compte&);
~Compte();
private:
int numCompte;
char* nomProprietaire;
float solde;
};
| true |
6733793c601f8b6f7d57d22cae51b8ec12ac0e21 | C++ | nck974/comnet2_1 | /ex3/ex3.cpp | UTF-8 | 3,342 | 2.984375 | 3 | [] | no_license | #include <string.h>
#include <omnetpp.h>
#include <math.h>
class Lin_Con_Rand { //Linear Congruential Random Number Generator
public:
double mult = 16807;
double m =pow(2,31)-1;
double generateNumber( double seed){
double randNum = fmod(( seed * mult ), m); //fmod = "%" for double
return randNum;
}
};
class uniformDistribution { //uniform distributed Inter-arrival time T (e.g. uniform (0,2) using Lin_Con_Rand
public:
double uniformValue (double min, double max, double currentNumber) {
double maxNumber=pow(2,31)-2;
return ((max*currentNumber)/(maxNumber-min));
}
};
class exponentialDistribution { //Compute inverse exponential distribution
public:
double expValue (double lamda, double uniformValue){
return -1/lamda*log(1-uniformValue);
}
};
class Sender : public cSimpleModule {
protected:
virtual void initialize() override {
// Get delay time as random value from exponential distribution as set in omnetpp.ini.
//simtime_t delay = par("delayTime");
currentNumber=1;
currentNumber=randGenerator.generateNumber(currentNumber);
currentUniformValue= Dist.uniformValue(0,1,currentNumber); //Map random number into uniform function
simtime_t delay = expDist.expValue(1,currentUniformValue); //Get x where exponential cumulative function is the random value
scheduleAt(simTime() + delay, new cMessage("selfmsg"));
}
virtual void handleMessage(cMessage *msg) override {
delete msg;
//simtime_t delay = par("delayTime");
currentNumber=randGenerator.generateNumber(currentNumber);
currentUniformValue= Dist.uniformValue(0,1,currentNumber); //Map random number into cumulative function
simtime_t delay = expDist.expValue(1,currentUniformValue); //Get x where exponential cumulative function is the random value
EV << "Delay expired, sending another message. New delay is: " << delay << endl;
// Send out a message to the reciever.
send(new cMessage("msg"), "out");
// Schedule a self message after delay.
scheduleAt(simTime() + delay, new cMessage("selfmsg"));
}
private:
double currentNumber;
double currentUniformValue;
exponentialDistribution expDist;
Lin_Con_Rand randGenerator;
uniformDistribution Dist;
};
Define_Module(Sender);
class Reciever : public cSimpleModule {
protected:
virtual void initialize() override {
arrivalSignal = registerSignal("arrival"); //Initialize signal
lastArrivalTime = 0.0;
interarrivalTimeAccumulated = 0.0;
messageCount = 0;
}
virtual void handleMessage(cMessage *msg) override {
delete msg;
messageCount++;
interarrivalTimeAccumulated += simTime().dbl() - lastArrivalTime;
lastArrivalTime = simTime().dbl();
//emit(arrivalSignal, interarrivalTimeAccumulated); //Trigger signal to save data
//emit(arrivalSignal, lastArrivalTime); //Trigger signal to save data
double currentInterarrival = interarrivalTimeAccumulated/messageCount;
emit(arrivalSignal, currentInterarrival); //Trigger signal to save data
EV << "Recieved message. Current interarrival time is: " << interarrivalTimeAccumulated / messageCount << "s" << endl;
}
private:
double lastArrivalTime;
double interarrivalTimeAccumulated;
int messageCount;
simsignal_t arrivalSignal; //Signal: message has arrived
};
Define_Module(Reciever);
| true |
f7879165882ae3985e2a238a0282c102c94b501d | C++ | kevinjycui/Competitive-Programming | /C++/Codeforces/Codeforces Round/Div 3/cf1324C.cpp | UTF-8 | 482 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
int t;
cin >> t;
for (int i=0; i<t; i++) {
string s;
cin >> s;
int maximum = 0;
int r = 0;
for (int j=0; j<s.size(); j++)
if (s.at(j) == 'R') {
maximum = max(maximum, j-r+1);
r = j+1;
}
maximum = max(maximum, (int)(s.size())-r+1);
cout << maximum << endl;
}
}
| true |
5e503d2044b700cb5ec3024442c0cb587b77cbce | C++ | LeeGyeongHwan/Algorithm_Student | /acm_2884.cpp | UTF-8 | 344 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int hour,min;
cin >> hour >> min;
if(min<45)
{
if(hour==0)
{
cout<<23<<" "<<min+15<<endl;
}
else{
cout<<hour-1<<" "<<min+15<<endl;
}
}else
{
cout<<hour<<" "<<min-45<<endl;
}
} | true |
4b0781087a2f675a28f45bad0333ca51f4735591 | C++ | mahfuzmohammad/ProblemSolving | /library_code/Network Flow/MBP_DFS.cpp | UTF-8 | 1,250 | 2.875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define _MAXN 100
vector<int> edges[_MAXN + 5]; // left side adjacency list
bool visited[_MAXN + 5];
int Left[_MAXN + 5], Right[_MAXN + 5]; // keeps the matching
bool dfs(int u) { // returns if it is possible to match u
if(visited[u]) return false;
visited[u] = true;
for(int i = 0; i < (int)edges[u].size(); i++) {
int v = edges[u][i];
if(Right[v] == -1 || dfs(Right[v])) {
Right[v] = u, Left[u] = v;
return true;
}
}
return false;
}
int match() { // returns the number of maximum matching
memset(Left, -1, sizeof Left);
memset(Right, -1, sizeof Right);
int matchCnt = 0;
bool done;
do {
done = true;
memset(visited, 0, sizeof visited);
for(int i = 0; i < _MAXN; i++)
if(Left[i] == -1 && dfs(i))
done = false;
} while(!done);
for(int i = 0; i < _MAXN; i++) matchCnt += (Left[i] != -1);
return matchCnt;
}
void reset() {
for(int i = 0; i <= _MAXN; i++)
edges[i].clear();
}
int main() {
// take input
// set edge using 'edges' array of vectors
// remember! 'edges' only stores left side adjacency list
return 0;
}
| true |
60c49458c14e44d90f939e1148eaef13da7dc722 | C++ | anabeldilab/Hash-table-with-separate-chaining | /include/listaclave.h | UTF-8 | 741 | 3.125 | 3 | [] | no_license | template <class Clave> class Lista;
template <class Clave> std::ostream& operator<<(std::ostream&, const Lista<Clave>&);
template <class Clave>
class Lista {
private:
std::list<Clave> lista_;
public:
Lista(void);
std::list<Clave> get_lista(void) const;
bool Buscar(const Clave&) const;
bool Insertar(const Clave&);
friend std::ostream& operator<<(std::ostream& os, const Lista<Clave>& kLista) {
if (!kLista.get_lista().empty()) {
os << kLista.get_lista().front();
} else {
os << "NULL";
}
for (const Clave& elemento_lista : kLista.get_lista()) {
if (kLista.get_lista().front() != elemento_lista)
os << " | " << elemento_lista;
}
return os;
}
}; | true |
eea5e9bf97d51482d2b7a7a21feeef7f69b10c43 | C++ | hrushikesht/CompetitiveProgramming | /old/temp/cube-free.cpp | UTF-8 | 1,270 | 3 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stdbool.h>
#include <string>
#include <vector>
#include <iterator>
#define pb push_back
using namespace std;
// bool myFunction(int x,int y){ return x>y }
int main()
{
int t=0;
scanf("%d",&t);
vector<long int> input,copy_input;
while(t--)
{
long int temp=0;
scanf("%ld",&temp);
input.pb(temp);
copy_input.pb(temp);
}
long int prime[25]={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
// sort(input.begin(),input.end(),myFunction);
for(int i=0;i<25;i++)
{
prime[i]=prime[i]*prime[i]*prime[i];
}
long int pinnacle=*max_element(input.begin(),input.end());
vector<int> functionWeWant;
functionWeWant.reserve(1000000);
functionWeWant[0]=0;
functionWeWant[1]=1;
long int index=2;
for(int i=2;i<pinnacle;i++)
{
for(int j=0;j<25;j++)
{
if(i<j)
{
functionWeWant.at(i)=index;
index++;
break;
}
else
{
if(i%j==0)
{
functionWeWant.at(i)=-1;
break;
}
else
{
functionWeWant.at(i)=index;
index++;
break;
}
}
}
}
vector<long int>::iterator it;
for(it=input.begin()+1;it<input.end();it++)
{
cout<<functionWeWant.at(*it)<<endl;
}
} | true |
811d86df40d5b32511d84418bf4818f81fe18127 | C++ | Fasgort/Proyecto-OpenGL | /source/bmp.cpp | UTF-8 | 2,505 | 2.859375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "bmp.h"
/*************************************************************************/
GLubyte *LoadDIBitmap(const char *filename, /* I - File to load */
BITMAPINFO **info) /* O - Bitmap information */
{
FILE *fp; /* Open file pointer */
GLubyte *bits; /* Bitmap pixel bits */
int bitsize; /* Size of bitmap */
int infosize; /* Size of header information */
BITMAPFILEHEADER header; /* File header */
/* Try opening the file; use "rb" mode to read this *binary* file. */
if ((fopen_s(&fp, filename, "rb")) == NULL) {
printf("LoadDIBitmap: error al abrir el fichero");
}
/* Read the file header and any following bitmap information... */
if (fread(&header, sizeof(BITMAPFILEHEADER), 1, fp) < 1)
{
/* Couldn't read the file header - return NULL... */
fclose(fp);
printf("LoadDIBitmap: no puedo leer la cabecera");
}
if (header.bfType != 'MB') /* Check for BM reversed... */
{
/* Not a bitmap file - return NULL... */
fclose(fp);
printf("LoadDIBitmap: fichero no es un BMP ");
}
//printf("\n offset:%d",header.bfOffBits);
infosize = header.bfOffBits - sizeof(BITMAPFILEHEADER);
if ((*info = (BITMAPINFO *)malloc(infosize)) == NULL)
{
/* Couldn't allocate memory for bitmap info - return NULL... */
fclose(fp);
printf("LoadDIBitmap: no hay memoria");
}
if (fread(*info, 1, infosize, fp) < infosize)
{
/* Couldn't read the bitmap header - return NULL... */
free(*info);
fclose(fp);
printf("LoadDIBitmap: no puedo leer la cabecera");
}
/* Now that we have all the header info read in, allocate memory for *
* the bitmap and read *it* in... */
if ((bitsize = (*info)->bmiHeader.biSizeImage) == 0/* 1 */)
bitsize = ((*info)->bmiHeader.biWidth *
(*info)->bmiHeader.biBitCount + 7) / 8 *
abs((*info)->bmiHeader.biHeight);
//printf("\n bitsize:%d",bitsize);
if ((bits = (GLubyte *)malloc(bitsize)) == NULL)
{
/* Couldn't allocate memory - return NULL! */
free(*info);
fclose(fp);
printf("LoadDIBitmap: no hay memoria");
}
if (fread(bits, 1, bitsize, fp) < bitsize)
{
/* Couldn't read bitmap - free memory and return NULL! */
free(*info);
free(bits);
fclose(fp);
printf("LoadDIBitmap: error al leer el bitmap");
}
/* OK, everything went fine - return the allocated bitmap... */
fclose(fp);
return (bits);
}
| true |
d51acd721e8fb64141da6c31b601a9dcf2ef3f42 | C++ | cyp0922/Algorithm-Code | /사다리 조작_15684번.cpp | UHC | 1,705 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int N, M, H;
int map[32][11];
int cmp[32][11];
int deep = 0;
int most = 0;
bool finish;
bool check(int cnt) {
if (cnt == 0)for (int i = 1; i <= N; i++) cmp[0][i] = i;
if (cnt == H + 1) {
int cnt = 0;
for (int i = 1; i <= N; i++) {
if (cmp[H + 1][i] == i) cnt++;
}
if (cnt == N) return 1;
else return 0;
}
for (int x = 1; x <= N; x++) {
if (map[cnt + 1][x]) cmp[cnt + 1][x + 1] = cmp[cnt][x];
else if (map[cnt + 1][x - 1]) cmp[cnt + 1][x - 1] = cmp[cnt][x];
else cmp[cnt + 1][x] = cmp[cnt][x];
}
return check(cnt + 1);
}
void dfs(int idx, int cnt) {
if (finish == 1) return;
if (cnt == deep) {
memset(cmp, false, sizeof(cmp));
if (check(0)) finish = true;
return;
}
for (int i = idx; i <= (N - 1) * (H + 1); i++) {
int y = i / (N - 1);
int x = i % (N - 1) + 1;
if (y <= H && y >= 1) {
if (!map[y][x] && !map[y][x + 1] && !map[y][x - 1] && finish != 1) {
map[y][x] = 2;
if (x == N - 1) dfs(i + 1, cnt + 1);
else dfs(i + 2, cnt + 1);
map[y][x] = false;
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
// μ ϰų ϸ ȵȴ.
// ٸ μ
// N μ, Hμ
cin >> N >> M >> H;
int a, b;
for (int i = 0; i < M; i++) {
cin >> a >> b;
map[a][b] = true;
}
for (int i = 1; i <= N; i++) cmp[0][i] = i;
memset(cmp, false, sizeof(cmp));
if (check(0)) finish = true;
for (int k = 0; k <= 3; k++) {
if (finish == 0) {
deep = k;
dfs(1, 0);
}
else break;
}
if (finish) cout << deep;
else cout << "-1";
} | true |
8c7fefb89bb44dbc0eecaad27b0ea97e9032a7f7 | C++ | zouxianyu/query-pdb | /thirdparty/nlohmann_json/docs/examples/byte_container_with_subtype__clear_subtype.cpp | UTF-8 | 576 | 3.03125 | 3 | [
"MIT",
"LicenseRef-scancode-free-unknown",
"CC0-1.0",
"Apache-2.0"
] | permissive | #include <iostream>
#include <nlohmann/json.hpp>
// define a byte container based on std::vector
using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
using json = nlohmann::json;
int main()
{
std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
// create container with subtype
auto c1 = byte_container_with_subtype(bytes, 42);
std::cout << "before calling clear_subtype(): " << json(c1) << '\n';
c1.clear_subtype();
std::cout << "after calling clear_subtype(): " << json(c1) << '\n';
}
| true |
80cc0cfa352b35124c2b0aa97854492b1669dffe | C++ | karnkaul/LittleEngineVk | /engine/include/le/resources/asset.hpp | UTF-8 | 805 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <djson/json.hpp>
#include <le/core/named_type.hpp>
#include <le/vfs/uri.hpp>
#include <cstdint>
#include <vector>
namespace le {
class Asset : public NamedType {
public:
[[nodiscard]] auto type_name() const -> std::string_view override { return "Asset"; }
[[nodiscard]] virtual auto try_load(Uri const& uri) -> bool = 0;
[[nodiscard]] static auto get_asset_type(dj::Json const& json) -> std::string_view { return json["asset_type"].as_string(); }
[[nodiscard]] static auto get_asset_type(Uri const& uri) -> std::string_view;
protected:
[[nodiscard]] auto read_bytes(Uri const& uri) const -> std::vector<std::byte>;
[[nodiscard]] auto read_string(Uri const& uri) const -> std::string;
[[nodiscard]] auto read_json(Uri const& uri) const -> dj::Json;
};
} // namespace le
| true |
99fc1e6b5bea083db1a5151f28d09b12ea78b522 | C++ | 45498106/c1-launcher | /Code/Launcher/Util.cpp | UTF-8 | 3,086 | 2.703125 | 3 | [] | no_license | /**
* @file
* @brief Implementation of utilities.
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <intrin.h> // __cpuid
// Launcher headers
#include "Util.h"
/**
* @brief Fills read-only memory region with x86 NOP instruction.
* @param address Memory region address.
* @param length Memory region size in bytes.
* @return 0 if no error occurred, otherwise -1.
*/
int FillNOP( void *address, size_t length )
{
DWORD oldProtection;
if ( VirtualProtect( address, length, PAGE_EXECUTE_READWRITE, &oldProtection ) == 0 )
return -1;
// 0x90 is opcode of NOP instruction for both x86 and x86_64
memset( address, '\x90', length );
if ( VirtualProtect( address, length, oldProtection, &oldProtection ) == 0 )
return -1;
return 0;
}
/**
* @brief Fills read-only memory region with custom data.
* @param address Memory region address.
* @param data The data copied to the memory region.
* @param length Size of the data in bytes.
* @return 0 if no error occurred, otherwise -1.
*/
int FillMem( void *address, void *data, size_t length )
{
DWORD oldProtection;
if ( VirtualProtect( address, length, PAGE_EXECUTE_READWRITE, &oldProtection ) == 0 )
return -1;
memcpy( address, data, length );
if ( VirtualProtect( address, length, oldProtection, &oldProtection ) == 0 )
return -1;
return 0;
}
/**
* @brief Obtains game version from any Crysis DLL.
* It parses version resource of the specified file.
* @param lib Handle to any loaded Crysis DLL.
* @return Game build number or -1 if some error occurred.
*/
int GetCrysisGameVersion( void *lib )
{
// VERSIONINFO resource always has ID 1
HRSRC versionResInfo = FindResource( (HMODULE) lib, MAKEINTRESOURCE( 1 ), RT_VERSION );
if ( versionResInfo == NULL )
return -1;
HGLOBAL versionResData = LoadResource( (HMODULE) lib, versionResInfo );
if ( versionResData == NULL )
return -1;
void *versionRes = LockResource( versionResData ); // this function does nothing
if ( versionRes == NULL )
return -1;
if ( memcmp( (PBYTE) versionRes + 0x6, L"VS_VERSION_INFO", 0x20 ) != 0 )
return -1;
VS_FIXEDFILEINFO *pFileInfo = (VS_FIXEDFILEINFO*) ((PBYTE) versionRes + 0x6 + 0x20 + 0x2);
if ( pFileInfo->dwSignature != 0xFEEF04BD )
return -1;
return LOWORD( pFileInfo->dwFileVersionLS );
}
/**
* @brief Checks if AMD processor is being used.
* @return True if we are running on AMD processor, otherwise false.
*/
bool HasAMDProcessor()
{
const char *vendorID = "AuthenticAMD";
int cpuInfo[4];
__cpuid( cpuInfo, 0x0 );
const int *id = reinterpret_cast<const int*>( vendorID );
return cpuInfo[1] == id[0] // first part is in EBX register
&& cpuInfo[3] == id[1] // second part is in EDX register
&& cpuInfo[2] == id[2]; // third part is in ECX register
}
/**
* @brief Checks if processor supports 3DNow! instructions.
* @return True if 3DNow! instruction set is available, otherwise false.
*/
bool Is3DNowSupported()
{
int cpuInfo[4];
__cpuid( cpuInfo, 0x80000001 );
return (cpuInfo[3] & (1 << 31)) != 0; // check bit 31 in EDX register
}
| true |
ddb03e955524a5da84ccc7e4d8a3e47e8c8c3990 | C++ | maybe2009/learning_muduo | /ThreadPool/headers/Log/LogStream.h | UTF-8 | 3,580 | 3 | 3 | [] | no_license | #ifndef OBJ_LOGSTREAM_H
#define OBJ_LOGSTREAM_H
#include <iostream>
#include <string>
#include "../FixedBuffer/FixedBuffer.h"
namespace ok {
#define MAX_INTERGE_STRING_LENGTH 20
class LogStream {
public:
LogStream(size_t buf_size);
LogStream &operator<<(int);
LogStream &operator<<(unsigned int);
LogStream &operator<<(long);
LogStream &operator<<(unsigned long);
LogStream &operator<<(long long);
LogStream &operator<<(unsigned long long);
LogStream &operator<<(float v);
LogStream &operator<<(double v);
LogStream &operator<<(char);
LogStream &operator<<(std::string str);
//TODO: remove show after test
void show();
void clearBuffer();
private:
void write();
private:
FixedBuffer buffer_;
FixedBuffer::BYTE intBuf[MAX_INTERGE_STRING_LENGTH + 1];
size_t count_;
int retVal_;
};
LogStream::LogStream(size_t buf_size)
: buffer_(buf_size) { }
LogStream &LogStream::
operator<<(int v) {
std::cout << "Int Version Called" << std::endl;
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%d", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
LogStream &LogStream::
operator<<(unsigned int v) {
std::cout << "Int Version Called" << std::endl;
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%u", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
LogStream &LogStream::
operator<<(long v) {
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%ld", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
LogStream &LogStream::
operator<<(unsigned long v){
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%lu", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
LogStream &LogStream::
operator<<(long long v){
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%lld", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
LogStream &LogStream::
operator<<(unsigned long long v){
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%llu", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
LogStream &LogStream::
operator<<(char v) {
buffer_.write(&v, 1);
return *this;
}
LogStream &LogStream::operator<<(std::string str) {
if (buffer_.getAvailable() >= str.length()) {
buffer_.write(str.c_str(), str.length());
}
return *this;
}
LogStream &LogStream::operator<<(float v) {
return *this << static_cast<double>(v);
}
LogStream &LogStream::operator<<(double v) {
if (buffer_.getAvailable() >= MAX_INTERGE_STRING_LENGTH + 1) {
retVal_ = snprintf(intBuf, MAX_INTERGE_STRING_LENGTH + 1, "%.12g", v);
if (retVal_ > 0) {
count_ = static_cast<size_t>(retVal_);
write();
}
}
return *this;
}
void LogStream::write() {
buffer_.write(intBuf, count_);
}
void LogStream::clearBuffer() {
buffer_.clear();
}
//TODO: remove after test
void LogStream::
show() {
buffer_.show();
}
};//namespace ok
#endif //OBJ_LOGSTREAM_H
| true |
13f7c79e572a6ce644255e4325e515eb1d251ab2 | C++ | ksaveljev/UVa-online-judge | /12347.cpp | UTF-8 | 1,147 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
typedef struct node_ {
int v;
struct node_* left;
struct node_* right;
} node;
void insert(node* n, int v) {
while (true) {
if (n->v > v) {
if (n->left == NULL) {
n->left = new node;
n->left->v = v;
n->left->left = NULL;
n->left->right = NULL;
break;
} else {
n = n->left;
}
} else {
if (n->right == NULL) {
n->right = new node;
n->right->v = v;
n->right->left = NULL;
n->right->right = NULL;
break;
} else {
n = n->right;
}
}
}
}
void print_post(node* n) {
if (n == NULL) return;
print_post(n->left);
print_post(n->right);
cout << n->v << endl;
}
int main(void) {
int v;
node* root = new node;
cin >> v;
root->v = v;
root->left = NULL;
root->right = NULL;
while (cin >> v) {
insert(root, v);
}
print_post(root);
return 0;
}
| true |
4d95ea4ac8d143fef690e9dddb0056464654f58a | C++ | daniel-lundin/raytrace | /include/raymaterial.h | UTF-8 | 1,284 | 2.890625 | 3 | [] | no_license | #ifndef RAYMATERIAL_H
#define RAYMATERIAL_H
#include <iostream>
#include "raycolor.h"
class RayMaterial
{
public:
RayMaterial(const RayColor& color,
double ambient,
double diffuse,
double specular,
double specPower,
double reflection,
double refraction,
double refractionIndex);
RayMaterial();
// setters
void setColor(const RayColor&);
void setAmbient(double);
void setDiffuse(double);
void setSpecular(double);
void setSpecPower(double);
void setReflection(double);
void setRefraction(double);
void setRefractionIndex(double);
// getters
const RayColor& color() const;
double ambient() const;
double diffuse() const;
double specular() const;
double specPower() const;
double reflection() const;
double refraction() const;
double refractionIndex() const;
friend std::ostream& operator<<(std::ostream& os, const RayMaterial&);
private:
RayColor m_color;
double m_ambient;
double m_diffuse;
double m_specular;
double m_specPower;
double m_reflection;
double m_refraction;
double m_refractionIndex;
};
std::ostream& operator<<(std::ostream& os, const RayMaterial&);
#endif // RAYMATERIAL_H
| true |
8986d40630ffb47e8539ec5730e331ec23a6de80 | C++ | Shin-723/Algolab | /Algolab/QueStack_Exercise.cpp | UTF-8 | 4,106 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#define MAX_SIZE 50
char bufferEval[MAX_SIZE];
using namespace std;
class Stack {
public:
char *stack;
int top;
int max_size;
Stack(int size);
bool IsFull();
bool IsEmpty();
void push(char data);
char pop();
};
Stack::Stack(int size){
top = -1;
stack = new char[size];
max_size = size;
}
bool Stack::IsFull() {
if (top + 1 == max_size) {
return true;
}
else {
return false;
}
}
bool Stack::IsEmpty() {
if (top == -1){
return true;
}
else {
return false;
}
}
void Stack::push(char data) {
if (IsFull()) {
cout << "Stack is Full" << endl;
}
else {
top++;
stack[top] = data;
}
}
char Stack::pop() {
if (IsEmpty()) {
cout << "Stack is empty" << endl;
return 0;
}
else {
return stack[top--];
}
}
class IntStack {
public:
int* stack;
int top;
int max_size;
IntStack(int size);
bool IsFull();
bool IsEmpty();
void push(int data);
int pop();
};
IntStack::IntStack(int size) {
top = -1;
stack = new int[size];
max_size = size;
}
bool IntStack::IsFull() {
if (top + 1 == max_size){
return true;
}
else {
return false;
}
}
bool IntStack::IsEmpty() {
if (top == -1) {
return true;
}
else {
return false;
}
}
void IntStack::push(int data) {
if (IsFull()) {
cout << "Stack is Full" << endl;
}
else {
top++;
stack[top] = data;
}
}
int IntStack::pop() {
if (IsEmpty()) {
cout << "Stack is empty" << endl;
return 0;
}
else {
return stack[top--];
}
}
int priority(char input);
void infixToPostfix(char *buffer);
int postfixEvaluation(char *buffer);
int main() {
char buffer[MAX_SIZE];
ifstream infile("infix_postfix.txt");
while (infile.getline(buffer, MAX_SIZE)) {
cout << "Infix expression : " << buffer<<" " ;
cout << "The Postfix conversion: ";
infixToPostfix(buffer);
cout << endl;
cout << "The Result : " << postfixEvaluation(bufferEval) << endl;
cout << endl;
}
}
int priority(char input) {
if (input == ')'){
return 4;
}
else if (input == '*' || input == '/') {
return 3;
}
else if (input == '+' || input == '-') {
return 2;
}
else if (input == '(') {
return 1;
}
else if (input == ' ') {
return -1;
}
else{
return 0;
}
}
void infixToPostfix(char *buffer) {
Stack conversion(MAX_SIZE);
int i = 0, j = 0;
while (buffer[i] != '\0') {
switch (priority(buffer[i])) {
case 0:
bufferEval[j++] = buffer[i];
cout << buffer[i] << " ";
break;
case 4:
while (conversion.stack[conversion.top] != '(') {
bufferEval[j] = conversion.pop();
cout << bufferEval[j++] << " ";
}
break;
case 3:
case 2:
if (priority(buffer[i]) >= priority(conversion.stack[conversion.top])){
conversion.push(buffer[i]);
}
else{
bufferEval[j] = conversion.pop();
cout << bufferEval[j++] << " ";
conversion.push(buffer[i]);
}
break;
case 1:
conversion.push(buffer[i]);
break;
default:
break;
}
i++;
}
while (conversion.top != -1) {
if (conversion.stack[conversion.top] == '(') {
conversion.pop();
continue;
}
else {
bufferEval[j] = conversion.pop();
cout << bufferEval[j++] << " ";
}
}
bufferEval[j] = '\0';
}
int postfixEvaluation(char *buffer) {
IntStack evaluation(MAX_SIZE);
int i = 0;
int op1, op2;
while (buffer[i] != '\0') {
switch (priority(buffer[i])) {
case 0:
evaluation.push(buffer[i]-'0');
break;
case 3:
case 2:
op2 = evaluation.pop();
op1 = evaluation.pop();
switch (buffer[i]) {
case '+':
evaluation.push(op1 + op2);
break;
case '-':
evaluation.push(op1 - op2);
break;
case '*':
evaluation.push(op1 * op2);
break;
case '/':
evaluation.push(op1 / op2);
break;
}
break;
default:
break;
}
i++;
}
return evaluation.pop();
}
| true |
22fd52dc159bb44510540faf22de8825c8219f72 | C++ | Jepsiko/WhiteHouseDefense | /code/server/Other/Timer.cpp | UTF-8 | 1,249 | 3.203125 | 3 | [] | no_license | #include <exception>
#include <stdexcept>
#include "Timer.hpp"
Timer::Timer(): numOfElapsedMilisecondsInPreviousIntervals(0), isPaused(true) {}
void Timer::start() {
gettimeofday(&last_pause_timeval, 0);
isPaused = false;
}
void Timer::reset() {
numOfElapsedMilisecondsInPreviousIntervals = 0;
isPaused = false;
start();
}
void Timer::pause() {
numOfElapsedMilisecondsInPreviousIntervals += getMilisecondsSinceLastCurrentIntervalStart();
isPaused = true;
}
void Timer::resume() {
gettimeofday(&last_pause_timeval, 0);
isPaused = false;
}
int Timer::elapsedTimeInMiliseconds() {
if (isPaused) throw std::logic_error("Timer is paused");
return numOfElapsedMilisecondsInPreviousIntervals + getMilisecondsSinceLastCurrentIntervalStart();
}
int Timer::elapsedTimeInSeconds() {
return elapsedTimeInMiliseconds() / 1000;
}
int Timer::getMilisecondsSinceLastCurrentIntervalStart() {
struct timeval current_timeval;
gettimeofday(¤t_timeval, 0);
double elapsedTimeInMilliseconds = (current_timeval.tv_sec - last_pause_timeval.tv_sec) * 1000;
elapsedTimeInMilliseconds += (current_timeval.tv_usec - last_pause_timeval.tv_usec) / 1000;
return (int) elapsedTimeInMilliseconds;
}
| true |
bb3510aa5dc67f15c87bc5ca76a3594cd45c1fdd | C++ | Pedram87/CaroloCup | /2014-CaroloCup/Legendary/project/OpenDaVINCI-msv/hesperia/libhesperia/testsuites/SceneGraphTestSuite.h | UTF-8 | 5,566 | 2.640625 | 3 | [
"AFL-3.0"
] | permissive | /*
* OpenDaVINCI.
*
* This software is open source. Please see COPYING and AUTHORS for further information.
*/
#ifndef HESPERIA_SCENEGRAPHTESTSUITE_H_
#define HESPERIA_SCENEGRAPHTESTSUITE_H_
#include <sstream>
#include "cxxtest/TestSuite.h"
#include "hesperia/scenegraph/SceneNode.h"
#include "hesperia/scenegraph/SceneNodeDescriptor.h"
#include "hesperia/scenegraph/SceneNodeVisitor.h"
using namespace std;
using namespace hesperia::scenegraph;
class SceneNodePrettyPrinter : public SceneNodeVisitor {
public:
stringstream m_value;
public:
SceneNodePrettyPrinter() :
m_value() {}
virtual void visit(SceneNode *sceneNode) {
if (sceneNode != NULL) {
m_value << sceneNode->getSceneNodeDescriptor().getName() << "->";
}
}
};
class SceneGraphTest : public CxxTest::TestSuite {
public:
void testSceneGraph1() {
SceneNode root(SceneNodeDescriptor("Root"));
TS_ASSERT(root.getNumberOfChildren() == 0);
}
void testSceneGraph2() {
SceneNode root(SceneNodeDescriptor("Root"));
root.addChild(new SceneNode(SceneNodeDescriptor("Child 1")));
TS_ASSERT(root.getNumberOfChildren() == 1);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
}
void testSceneGraph3() {
SceneNode root(SceneNodeDescriptor("Root"));
SceneNode *child1 = new SceneNode(SceneNodeDescriptor("Child 1"));
SceneNode *child2 = new SceneNode(SceneNodeDescriptor("Child 2"));
root.addChild(child1);
child1->addChild(child2);
TS_ASSERT(root.getNumberOfChildren() == 1);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
TS_ASSERT(child1->getNumberOfChildren() == 1);
TS_ASSERT(child1->getSceneNodeDescriptor().getName() == "Child 1");
TS_ASSERT(child2->getNumberOfChildren() == 0);
TS_ASSERT(child2->getSceneNodeDescriptor().getName() == "Child 2");
}
void testSceneGraph4() {
SceneNode root(SceneNodeDescriptor("Root"));
SceneNode *child1 = new SceneNode(SceneNodeDescriptor("Child 1"));
SceneNode *child2 = new SceneNode(SceneNodeDescriptor("Child 2"));
root.addChild(child1);
child1->addChild(child2);
TS_ASSERT(root.getNumberOfChildren() == 1);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
TS_ASSERT(child1->getNumberOfChildren() == 1);
TS_ASSERT(child1->getSceneNodeDescriptor().getName() == "Child 1");
TS_ASSERT(child2->getNumberOfChildren() == 0);
TS_ASSERT(child2->getSceneNodeDescriptor().getName() == "Child 2");
SceneNodePrettyPrinter snpp;
root.accept(snpp);
TS_ASSERT(snpp.m_value.str() == "Root->Child 1->Child 2->");
}
void testSceneGraph5() {
SceneNode root(SceneNodeDescriptor("Root"));
SceneNode *child1 = new SceneNode(SceneNodeDescriptor("Child 1"));
SceneNode *child2 = new SceneNode(SceneNodeDescriptor("Child 2"));
root.addChild(child1);
child1->addChild(child2);
TS_ASSERT(root.getNumberOfChildren() == 1);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
TS_ASSERT(child1->getNumberOfChildren() == 1);
TS_ASSERT(child1->getSceneNodeDescriptor().getName() == "Child 1");
TS_ASSERT(child2->getNumberOfChildren() == 0);
TS_ASSERT(child2->getSceneNodeDescriptor().getName() == "Child 2");
SceneNodePrettyPrinter snpp;
root.accept(snpp);
TS_ASSERT(snpp.m_value.str() == "Root->Child 1->Child 2->");
root.deleteAllChildren();
TS_ASSERT(root.getNumberOfChildren() == 0);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
SceneNodePrettyPrinter snpp2;
root.accept(snpp2);
TS_ASSERT(snpp2.m_value.str() == "Root->");
}
void testSceneGraph6() {
SceneNode root(SceneNodeDescriptor("Root"));
SceneNode *child1 = new SceneNode(SceneNodeDescriptor("Child 1"));
SceneNode *child2 = new SceneNode(SceneNodeDescriptor("Child 2"));
root.addChild(child1);
child1->addChild(child2);
TS_ASSERT(root.getNumberOfChildren() == 1);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
TS_ASSERT(child1->getNumberOfChildren() == 1);
TS_ASSERT(child1->getSceneNodeDescriptor().getName() == "Child 1");
TS_ASSERT(child2->getNumberOfChildren() == 0);
TS_ASSERT(child2->getSceneNodeDescriptor().getName() == "Child 2");
SceneNodePrettyPrinter snpp;
root.accept(snpp);
TS_ASSERT(snpp.m_value.str() == "Root->Child 1->Child 2->");
child1->removeChild(child2);
TS_ASSERT(root.getNumberOfChildren() == 1);
TS_ASSERT(root.getSceneNodeDescriptor().getName() == "Root");
TS_ASSERT(child1->getNumberOfChildren() == 0);
TS_ASSERT(child1->getSceneNodeDescriptor().getName() == "Child 1");
SceneNodePrettyPrinter snpp2;
root.accept(snpp2);
TS_ASSERT(snpp2.m_value.str() == "Root->Child 1->");
}
};
#endif /*HESPERIA_SCENEGRAPHTESTSUITE_H_*/
| true |
37b7c790876bb429fca95a3adcdbc037b5248519 | C++ | deepcoder007/chef | /AMSGAME1.cpp | UTF-8 | 454 | 2.8125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int gcd(int a,int b)
{
int c;
while( a!=0 )
{
c=a; a=b%a; b=c;
}
return b;
}
inline void test()
{
int N;
cin>>N;
int a,b;
cin>>a;
int score=a;
int tmp;
register int i;
for( i=1;i<N;i++)
{
cin>>b;
if( b> score )
{
score=gcd( b,score);
}
else if( b< score )
{
score=gcd( score, b);
}
}
cout<<score<<endl;
}
int main()
{
int T;
cin>>T;
while(T--)
test();
return 0;
}
| true |
dfe7ae441ba9b5ce6532d99a5ce019443908b3b1 | C++ | Excalibur79/Interview-Competitive-Cpp | /Binary Search Tree/BSTfromPreoder.cpp | UTF-8 | 1,729 | 3.890625 | 4 | [] | no_license |
#include <bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
};
node *newNode(int data)
{
node *temp = new node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
node *constructTreeUtil(int pre[], int *preIndex, int key,
int min, int max, int size)
{
// Base case
if (*preIndex >= size)
return NULL;
node *root = NULL;
// If current element of pre[] is in range, then
// only it is part of current subtree
if (key > min && key < max)
{
root = newNode(key);
*preIndex = *preIndex + 1;
if (*preIndex < size)
{
root->left = constructTreeUtil(pre, preIndex,
pre[*preIndex],
min, key, size);
}
if (*preIndex < size)
{
root->right = constructTreeUtil(pre, preIndex,
pre[*preIndex],
key, max, size);
}
}
return root;
}
node *constructTree(int pre[], int size)
{
int preIndex = 0;
return constructTreeUtil(pre, &preIndex, pre[0],
INT_MIN, INT_MAX, size);
}
void printInorder(node *node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
int main()
{
int pre[] = {10, 5, 1, 7, 40, 50};
int size = sizeof(pre) / sizeof(pre[0]);
node *root = constructTree(pre, size);
cout << "Inorder traversal of the constructed tree: \n";
printInorder(root);
return 0;
}
| true |
de034ee314d20fb2acb4f700108df8f9ceb073c3 | C++ | sjj118/OI-Code | /hihocoder/Contest/27/B/make.cpp | UTF-8 | 571 | 2.53125 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#define rg register
#define rep(i,x,y) for(int i=(x);i<=(y);++i)
#define per(i,x,y) for(int i=(x);i>=(y);--i)
const int N=1e5+10;
struct Edge{
int u,v;
Edge(){}
Edge(int u,int v):u(u),v(v){}
void output(){printf("%d %d\n",u,v);}
}e[N];
int main(){
srand(time(0));
freopen("code.in","w",stdout);
int n=100000,m=1000;
printf("%d %d\n",n,m);
rep(i,1,n-1)(e[i]=Edge(rand()%i+1,i+1)).output();
rep(i,1,m){
int t=1000;
printf("%d\n",t);
rep(j,1,t)e[rand()%(n-1)+1].output();
}
return 0;
}
| true |
487fd0330982d0c71561c2c8874a6a89a1a4a276 | C++ | BetterMe1/Test_11_18 | /Cipin.cpp | GB18030 | 3,005 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <ctype.h>
#define N 50
typedef struct BiTNode
{
char data[N];
int count;
struct BiTNode *lChild;
struct BiTNode *rChild;
}BiTNode,*BiTree;
int GetWord(int start,int end,char* pBuf,char* word); //ʻ
void CreateSearchTree(char* item,BiTree& T); //в
void Printresult(BiTree T); //
int sum=0;
char temp1[N];
char temp2[N];
int main()
{
char fileName[30]="input.txt"; //ļĬΪinput.txt
FILE* pf;
pf=fopen(fileName,"rb");
printf("**********************************************************\n");
printf("ɹļ--- %s !\n\n",fileName);
//ȡļ
fseek(pf,0,SEEK_END);
int len=ftell(pf);
rewind(pf);
char *pBuf=new char[len+1];
pBuf[len]=0;
fread(pBuf,1,len,pf);
fclose(pf);
//ȡ
printf("%s\n",pBuf);
printf("**********************************************************\n");
int i=0;
char word[N];
BiTree T=NULL;
while(i<len)
{
i=GetWord(i,len,pBuf,word);
if(strlen(word)==0)
{
break;
}
CreateSearchTree(word,T);
}
//
printf("\t\tƵͳƽ:\n");
printf("**********************************************************\n");
Printresult(T);//void Printresult(BiTree T)
printf("**********************************************************\n");
printf("ƪµ%d\n",sum-1);
printf("***********************************************************\n");
return 0;
}
//ʻ
int GetWord(int start,int end,char* pBuf,char* word)
{
int i;
int j=0;
memset(word,0,sizeof(char));
for(i=start;i<end;i++)
{
if(isalpha(pBuf[i]))
{
word[j]=pBuf[i];
j++;
}
else
{
if(j==0)
{
continue;
}
word[j]='\0';
j=0;
sum++;
break;
}
}
return i;
}
//в
void CreateSearchTree(char* item,BiTree& T)
{
strcpy(temp1,item);
temp1[0]=tolower(item[0]);
if(T==NULL)
{
T=(BiTree)malloc(sizeof(BiTNode));
strcpy(T->data,item);
T->count=1;
T->lChild=NULL;
T->rChild=NULL;
}
else
{
strcpy(temp2,T->data);
temp2[0]=tolower(T->data[0]);
if(strcmp(temp1,temp2)==-1)
{
CreateSearchTree(item,T->lChild);
}
else if(strcmp(temp1,temp2)==1)
{
CreateSearchTree(item,T->rChild);
}
else
{
T->count++;
}
}
}
//
void Printresult(BiTree T)
{
if(T!=NULL)
{
Printresult(T->lChild);//ݹ
printf("ֵĴʻ㣺%-30s Ƶ:%-9d\t\n",T->data,T->count);
Printresult(T->rChild);
}
}
| true |
b1abd6f8f02d2d1b447bc990f826b799b10dcfbb | C++ | cristiano-xw/c-homework | /luogu/爬山.cpp | UTF-8 | 893 | 2.921875 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
struct student
{
double l;
double w;
double h;
bool operator<(const student &other)const
{
return h<other.h;
}
};
int main(void)
{
int n=0;
scanf("%d",&n);
struct student student[55555];
int i=0;
for(i=1;i<=n;i++)
{
scanf("%lf%lf%lf",&student[i].l,&student[i].w,&student[i].h);
}
//for(i=1;i<=n;i++)
//{
// cout<<student[i].l<<" "<<student[i].w<<" "<<student[i].h;
//}
sort(student,student+n);
double s=0; double d=0;
{
for(i=1;i<=n-1;i++)
{
s=sqrt((student[i].l-student[i+1].l)*(student[i].l-student[i+1].l)+(student[i].w-student[i+1].w)*(student[i].w-student[i+1].w)+(student[i].h-student[i+1].h)*(student[i].h-student[i+1].h))
;d+=s;
}
}
printf("%.3lf",d);
return 0;
}
| true |
220eb528bba3141bd7b7ef8e56ace8e2e9be3a5f | C++ | YueNing/LC-learning | /C++/134.加油站.cpp | UTF-8 | 642 | 2.78125 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=134 lang=cpp
*
* [134] 加油站
*/
// @lc code=start
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
int current_tank = 0;
int total_tank = 0;
int start_station = 0;
for (int i = 0; i < n; ++i)
{
total_tank += gas[i] - cost[i];
current_tank += gas[i] - cost[i];
if (current_tank < 0){
current_tank = 0;
start_station = i +1;
}
}
return total_tank >= 0 ? start_station : -1;
}
};
// @lc code=end
| true |
1abd33aa2abb14956284eb09d6153f72b743e310 | C++ | asad14053/My-Online-Judge-Solution | /URI online judge/uri-1367.cpp | UTF-8 | 711 | 2.53125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, time, total, count, extra[26];
char letter;
string status, letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
while (cin>>n && n)
{
total = 0;
count = 0;
memset(extra, 0, sizeof(extra));
while (n--)
{
cin >> letter >> time >> status;
if (status == "correct")
{
total += time;
total += extra[letters.find(letter)];
count++;
}
else
{
extra[letters.find(letter)] += 20;
}
}
printf("%d %d\n", count, total);
}
return 0;
}
| true |
7bb496443c24457d6dfd9008180908f5056ffffc | C++ | ternence-li/Urho3DGames | /SimpleTD/Source/Tower.cpp | UTF-8 | 2,448 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "Tower.h"
#include "Context.h"
#include "Node.h"
#include "ResourceCache.h"
#include "SpriteSheet2D.h"
#include "Component.h"
#include "StaticSprite2D.h"
#include "Bullet.h"
#include "Scene.h"
Tower::Tower(Context* context) : LogicComponent(context)
{
SetUpdateEventMask(USE_UPDATE);
}
Tower::~Tower()
{
}
void Tower::Start()
{
}
void Tower::RegisterObject(Context* context)
{
context->RegisterFactory<Tower>();
}
void Tower::DelayedStart()
{
}
void Tower::Stop()
{
}
void Tower::Update(float timeStep)
{
target_ = GetNearestEnemy();
if (target_ == NULL)
{
// _indicator.visible = false;
}
else
{
shootTimer_ -= timeStep*fireRate_;
if (shootTimer_ <=0.0f)
{
Shoot();
}
}
}
Node* Tower::GetNearestEnemy()
{
if (enemies_!=NULL)
{
for (int i = 0; i < enemies_->Size();i++)
{
WeakPtr<Node> enemy = enemies_->At(i);
if (enemy.NotNull())
{
Vector2 dist = node_->GetPosition2D() - enemy->GetPosition2D();
if (dist.Length() <= range_)
{
return enemy.Get();
}
}
}
}
return NULL;
}
void Tower::Shoot()
{
if (target_ == NULL)
return;
shootTimer_ = 1.0f;
ResourceCache* cache = GetSubsystem<ResourceCache>();
// create enemy
SpriteSheet2D* spriteSheet = cache->GetResource<SpriteSheet2D>("Tilemaps/TileMapSprites.xml");
if (!spriteSheet)
return;
SharedPtr<Node> bulletNode_(GetScene()->CreateChild("bullet"));
bulletNode_->SetPosition2D(node_->GetPosition2D());
StaticSprite2D* staticSprite = bulletNode_->CreateComponent<StaticSprite2D>();
spriteSheet->GetSprite("Bullet")->SetHotSpot(Vector2(0.0f, 0.0f));
staticSprite->SetSprite(spriteSheet->GetSprite("Bullet"));
staticSprite->SetLayer(6 * 10);
/// create Enemy component which controls the Enemy behavior
Bullet* b = bulletNode_->CreateComponent<Bullet>();
b->SetTarget(WeakPtr<Node>(target_));
b->SetDamage(damage_);
}
void Tower::UpgradeRange()
{
range_ += 0.10f;
rangeLevel_++;
rangePrize_ = (int) rangePrize_ * COST_INCREASE;
}
void Tower::UpgradeDamage()
{
damage_++;
damageLevel_++;
damagePrize_ = (int) damagePrize_ * COST_INCREASE;
}
void Tower::UpgradeFirerate()
{
fireRate_ += 0.5;
firerateLevel_++;
fireratePrize_ =(int) fireratePrize_ * COST_INCREASE;
}
int Tower::GetPrize(StringHash type)
{
if (type == "Range")
{
return rangePrize_;
}else
if (type == "Damage")
{
return damagePrize_;
}else
if (type == "FireRate")
{
return fireratePrize_;
}
return 0;
}
| true |
9ab825cfe2016b44c587a7ebe538b0bb5143a8ab | C++ | GuillaumeElias/Little2DGame | /src/BallisticEngine.cpp | UTF-8 | 4,845 | 3.015625 | 3 | [] | no_license | #include "BallisticEngine.h"
#include <set>
BallisticEngine::BallisticEngine(SDL_Renderer* gRenderer, BottomBar * bottomBa) : bottomBar(bottomBa) {
playerBulletTexture = new LTexture(gRenderer, true);
//load player bullet texture
if( !playerBulletTexture->loadFromFile("img/playerBullet.png", {255, 255, 255} ) ){
printf( "Failed to load player bullet texture!\n" );
return;
}
enemyBulletTexture = new LTexture(gRenderer, true);
//load enemy bullet texture
if( !enemyBulletTexture->loadFromFile("img/enemyBullet.png", {255, 255, 255} ) ){
printf( "Failed to load enemy bullet texture!\n" );
return;
}
}
void BallisticEngine::fireBullet(const Position position, Direction direction, bool enemy){
BulletPosition bulletPos;
bulletPos.x = position.x;
bulletPos.y = position.y;
bulletPos.direction = direction;
bulletPos.enemy = enemy;
if(direction == RIGHT){
bulletPos.x += PLAYER_WIDTH; //if going right move bullet on the other side of the player
}
bullets.push_back(bulletPos);
}
void BallisticEngine::move(Map* map){
//initialize common collider
SDL_Rect collider;
collider.w = 1;
collider.h = 1;
std::set<BulletPosition> bulletsToErase;
for(int i=0; i<bullets.size(); i++){ //for each active bullet
collider.y = bullets[i].y;
int bulletMove = BULLET_DISPLACEMENT; //initialize bullet move
while(true){
if(bullets[i].direction == RIGHT){
collider.x = bullets[i].x + bulletMove; //add bullet move to collider
if(bullets[i].x >= map->getLevelWidth() || map->checkCollision(collider, true)){
if(bulletMove < 2){ //if bulletMove can not be smaller
//remove bullet and exit loop
bulletsToErase.insert(bullets[i]);
break;
}else{ //reduce bulletMove and try again
bulletMove /= 2;
continue;
}
}else{ //no collision
//move bullet and exit loop
bullets[i].x += bulletMove;
break;
}
}else{ //direction == LEFT
collider.x = bullets[i].x - bulletMove;
if(bullets[i].x <= 0 || map->checkCollision(collider, true)){
if(bulletMove < 2){
bulletsToErase.insert(bullets[i]);
break;
}else{
bulletMove /= 2;
continue;
}
}else{
bullets[i].x -= bulletMove;
break;
}
}
}
int earnedPoints = 0;
if(bullets[i].enemy){
if(bullets[i].x >= playerPosition->x && bullets[i].x <= playerPosition->x + PLAYER_WIDTH &&
bullets[i].y + BULLET_COLL_MARGIN_Y >= playerPosition->y &&
bullets[i].y + BULLET_COLL_MARGIN_Y <= playerPosition->y + PLAYER_HEIGHT){
bottomBar->takeHit(ENEMY_BULLET_DAMAGE);
bulletsToErase.insert(bullets[i]);
}
}else{ //player's bullet
//check collision against every game object
std::vector<GameObject*>* gameObjects = map->getGameObjects();
for(int j=0; j<gameObjects->size(); j++){
if(gameObjects->at(j)->checkCollision(collider, true)){
bulletsToErase.insert(bullets[i]);
earnedPoints += gameObjects->at(j)->onHit(PLAYER_BULLET_1); //TODO get bullet type from bullet
}
}
if(earnedPoints>0){
map->getBottomBar()->addPoints(earnedPoints);
}
}
}
for(BulletPosition bulletToErase : bulletsToErase){
for(int i=0; i<bullets.size(); i++){
if(bullets[i] == bulletToErase){
bullets.erase(bullets.begin() + i);
break;
}
}
}
}
void BallisticEngine::render(SDL_Renderer* gRenderer, const SDL_Rect &mapVisibleLevel){
//render all bullets
for(int i=0; i<bullets.size(); i++){
if(bullets[i].enemy){
enemyBulletTexture->render(bullets[i].x - mapVisibleLevel.x, bullets[i].y);
}else{
playerBulletTexture->render(bullets[i].x - mapVisibleLevel.x, bullets[i].y);
}
}
}
void BallisticEngine::clearBullets(){
bullets.clear();
}
BallisticEngine::~BallisticEngine()
{
delete playerBulletTexture;
delete enemyBulletTexture;
}
void BallisticEngine::setPlayerPosition(PlayerPosition * playerPosition){
this->playerPosition = playerPosition;
}
| true |
1756447f746907c3e46ad6f19aaad42400d892df | C++ | KlimchukAnatoly/OOP_labs | /Lab11 - 1/Lab11Е/Time.h | UTF-8 | 539 | 2.703125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <time.h>
using namespace std;
class Time
{
int hours;
int minutes;
int seconds;
void fixtime();
public:
Time();
int getHours();
int getMinutes();
int getSeconds();
void setHours(int quan);
void setMinutes(int quan);
void setSeconds(int quan);
void addHours(int quan);
void addMinutes(int quan);
void addSeconds(int quan);
void showHours();
void showMinutes();
void showSeconds();
void show();
void difference(Time obj);
bool compare(Time obj);
int arrowAngle();
};
| true |
3551f99d6377a61f4dd2b090e82a94eb7e10b9c7 | C++ | PabloFreitas-lib/Prog3-UFSC-2018.2 | /Aulas/P1/5/Employe/fig10_23.cpp | ISO-8859-1 | 1,609 | 3.90625 | 4 | [] | no_license | #include <iostream>
using namespace std;
#include "Employee.h" // Definio da classe Employee
int main()
{
// utiliza o nome da classe e o operador de resoluo de escopo binrio para
// acessar a funo static number getCount
cout << "Number of employees before instantiation of any objects is "
<< Employee::getCount() << endl; // utiliza o nome da classe
// utiliza new para criar dinamicamente dois novos Employees
// operador new tambm chama o construtor do objeto
Employee *e1Ptr = new Employee( "Susan", "Baker" );
Employee *e2Ptr = new Employee( "Robert", "Jones" );
// chama getCount no primeiro objeto Employee
cout << "Number of employees after objects are instantiated is "
<< e1Ptr->getCount();
cout << "\n\nEmployee 1: "
<< e1Ptr->getFirstName() << " " << e1Ptr->getLastName()
<< "\nEmployee 2: "
<< e2Ptr->getFirstName() << " " << e2Ptr->getLastName() << "\n\n";
delete e1Ptr; // desaloca memria
e1Ptr = 0; // desconecta o ponteiro do espao de armazenamento livre.
delete e2Ptr; // desaloca memria
e2Ptr = 0; // desconecta o ponteiro do espao de armazenamento livre.
// no existe nenhum objeto, portanto, chama a funo membro static getCount
// utilizando o nome da classe e o operador de resoluo de escopo binrio
cout << "Number of employees after objects are deleted is "
<< Employee::getCount() << endl;
return 0;
} // fim de main
| true |
37d82b4570e89af11b17d28b1b97e779009c5949 | C++ | WarlockD/Cocos2dx-Undertale-Engine | /UndertaleSFML/console/curses.h | UTF-8 | 5,191 | 3.3125 | 3 | [] | no_license | #pragma once
#include <ctype.h>
#include <vector>
#include <type_traits>
namespace curses {
namespace priv {
// helpers for enum operations
// http://stackoverflow.com/questions/8357240/how-to-automatically-convert-strongly-typed-enum-into-int
template <typename E>
inline constexpr typename std::underlying_type<E>::type to_underlying(E e) {
return static_cast<typename std::underlying_type<E>::type>(e);
}
template< typename E, typename T>
inline constexpr typename std::enable_if< std::is_enum<E>::value && std::is_integral<T>::value, E >::type
to_enum(T value) noexcept { return static_cast<E>(value); }
template<typename E>
inline constexpr typename std::enable_if< std::is_enum<E>::value, bool>::type test_flag(E l, E r) {
return (to_underlying(l) & to_underlying(r)) != 0;
}
template<typename E>
inline constexpr typename std::enable_if< std::is_enum<E>::value, E&>::type set_flag(E& l, E r) {
l = to_enum<E>(to_underlying(l) | to_underlying(r));
return l;
}
template<typename E>
inline constexpr typename std::enable_if< std::is_enum<E>::value, E&>::type clear_flag(E& l, E r) {
l = to_enum<E>(to_underlying(l) & ~to_underlying(r));
return l;
}
};
// typedef unsigned long chtype; /* 16-bit attr + 16-bit char */
// use % to test if the flag is inside the other
#define ENUM_OPERATIONS(T) \
inline constexpr T operator|(T l, T r) { return priv::to_enum<T>(priv::to_underlying(l) | priv::to_underlying(r)); } \
inline constexpr T operator&(T l, T r) { return priv::to_enum<T>(priv::to_underlying(l) & priv::to_underlying(r)); } \
inline T& operator|=(T& l, T r) { l = l | r; return l; } \
inline T& operator&=(T& l, T r) { l = l & r; return l; } \
inline constexpr bool operator%(T l, T r) { return (priv::to_underlying(l) & priv::to_underlying(r)) != 0; }
enum class Color : unsigned char {
Black = 0,
DarkBlue = 1,
DarkGreen = 2,
DarkRed = 4,
Intensity = 8,
DarkCyan = DarkGreen | DarkBlue,
DarkMagenta = DarkRed | DarkBlue,
DarkYellow = DarkRed | DarkGreen,
DarkGray = DarkRed | DarkGreen | DarkBlue,
Gray = Intensity,
Green = Intensity | DarkGreen,
Blue = Intensity | DarkBlue,
Red = Intensity | DarkRed,
Magenta = Intensity | DarkRed | DarkBlue,
Yellow = Intensity | DarkRed | DarkGreen,
White = Intensity | DarkRed | DarkGreen | DarkBlue,
};
ENUM_OPERATIONS(Color);
enum class Attributes : unsigned char {
Normal = 0,
Reverse = 0x02,
Blink = 0x04,
};
ENUM_OPERATIONS(Attributes);
// I hate poluting the macro world
#undef ENUM_OPERATIONS
struct char_info {
unsigned short ch;
unsigned short attrib;
void forground(Color f) { attrib |= (attrib & 0xFFF0) | (static_cast<unsigned char>(f) & 0xF); }
void background(Color b) { attrib |= (attrib & 0xFF0F) | ((static_cast<unsigned char>(b) & 0xF) << 4); }
void attributes(Attributes a) { attrib |= (attrib & 0x00FF) | ((static_cast<unsigned char>(a)) << 8); }
Color forground() const { return static_cast<Color>(attrib & 0x0F); }
Color background() const { return static_cast<Color>((attrib>>4) & 0x0F); }
Attributes attributes() const { return static_cast<Attributes>((attrib >> 8) & 0xFF); }
};
typedef unsigned int chtype;
union uchtype {
char_info info;
chtype type;
};
struct Window /* definition of a window */
{
int _cury; /* current pseudo-cursor */
int _curx;
int _maxy; /* max window coordinates */
int _maxx;
int _begy; /* origin on screen */
int _begx;
int _flags; /* window properties */
chtype _attrs; /* standard attributes and colors */
chtype _bkgd; /* background, normally blank */
bool _clear; /* causes clear at next refresh */
bool _leaveit; /* leaves cursor where it is */
bool _scroll; /* allows window scrolling */
bool _nodelay; /* input character wait flag */
bool _immed; /* immediate update flag */
bool _sync; /* synchronise window ancestors */
bool _use_keypad; /* flags keypad key mode active */
chtype **_y; /* pointer to line pointer array */
int *_firstch; /* first changed character in line */
int *_lastch; /* last changed character in line */
int _tmarg; /* top of scrolling region */
int _bmarg; /* bottom of scrolling region */
int _delayms; /* milliseconds of delay for getch() */
int _parx, _pary; /* coords relative to parent (0,0) */
Window *_parent; /* subwin's pointer to parent win */
};
extern int LINES; /* terminal height */
extern int COLS; /* terminal width */
extern Window *stdscr; /* the default screen window */
extern Window *curscr; /* the current screen image */
//extern SCREEN *SP; /* curses variables */
//extern MOUSE_STATUS Mouse_status;
extern int COLORS;
extern int COLOR_PAIRS;
extern int TABSIZE;
//extern chtype acs_map[]; /* alternate character set map */
// extern char ttytype[]; /* terminal name/description */
}; | true |
43939b24c298efffe4c02441fa1d84d2a1b03f43 | C++ | anasserm/SPOT---CIE202-Project-Code-Framework | /SPOT/Courses/Course.cpp | UTF-8 | 1,054 | 2.78125 | 3 | [] | no_license | #include "Course.h"
#include "../GUI/GUI.h"
#include "../Registrar.h"
Course::Course()
{
}
Course::Course(Course_Code r_code, string r_title, int crd)//:code(r_code),Title(r_title)
{
code = r_code;
Title = r_title;
credits = crd;
status = "Done";
}
Course::~Course()
{
}
string Course::getType() const
{
return string(type);
}
void Course::setType(string t)
{
type = t;
}
void Course::setStatus(string s)
{
this->status = s;
}
string Course::getStatus() const
{
return string(status);
}
Course_Code Course::getCode() const
{
return code;
}
string Course::getTitle() const
{
return Title;
}
//return course credits
int Course::getCredits() const
{
return credits;
}
vector<string> Course::getPreReq()
{
return PreReq;
}
vector<string> Course::getCoReq()
{
return CoReq;
}
void Course::DrawMe(GUI* pG) const
{
pG->DrawCourse(this);
}
void Course::setCode(Course_Code crs_code)
{
code = crs_code;
}
string Course::getGrade() const
{
return this->grade;
}
void Course::setGrade(string grad)
{
this->grade = grad;
}
| true |
17a7b69981b2120311b2cebc011705cf2c92267d | C++ | lamorgan/210-arduino | /waterqualitytestercarduino.ino | UTF-8 | 2,436 | 3.25 | 3 | [] | no_license | /*
Analog input, analog output, serial output
Reads an analog input pin, maps the result to a range from 0 to 255
and uses the result to set the pulsewidth modulation (PWM) of an output pin.
Also prints the results to the serial monitor.
The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 9 to ground
created 29 Dec. 2008
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the turbidity is attached to
const int analogInPin2 = A1; // Analog input pin that the Ph meter is attached to
int blueled=13;
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
int phsensorValue = 0; // ph value read
int phoutputValue = 0; //ph value output
int phvalue=7;
int sensor=0;
//display screen
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7,8,9,10,11,12);
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
//blue LED
pinMode(LED_BUILTIN, OUTPUT);
//display screen words dont change
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.write("pH:");
lcd.setCursor(0,1);
lcd.write("Turbidity:");
lcd.setCursor(14,1);
lcd.write('%');
}
void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
phsensorValue = analogRead(analogInPin2);
phoutputValue = map(phsensorValue, 0, 1023, 0, 255);
//display screen values that change
lcd.setCursor(4,0);
lcd.print(phvalue);
lcd.setCursor(11,1);
lcd.print(round(sensorValue/9));
delay(500);
//controls led
if((phvalue >= 6.5) && (phvalue <= 8.5) && (sensorValue >= 830))
{
digitalWrite(LED_BUILTIN, HIGH);
}
else
{
digitalWrite(LED_BUILTIN, LOW);
}
// print the results to the serial monitor:
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print ("\t ph =");
Serial.print(phsensorValue);
Serial.print('\n');
delay(2);
}
| true |
4a78f063aca5a3a5c610fe527bfba361ffadef99 | C++ | sodic/fastalign | /tests/statistics_test.cpp | UTF-8 | 1,634 | 2.71875 | 3 | [
"MIT"
] | permissive | //
// Created by filip on 29.05.18..
//
#include "statistics/statistics.hpp"
#include "gtest/gtest.h"
namespace statistics {
TEST(JacccardToETest, WorkingPoperly) {
ASSERT_NEAR(0.101699, statistics::jaccard_to_e(0.43, 5), 0.000001);
ASSERT_NEAR(0.019491, statistics::jaccard_to_e(0.56, 17), 0.000001);
ASSERT_NEAR(0.098354, statistics::jaccard_to_e(0.23, 10), 0.000001);
ASSERT_DOUBLE_EQ(0, statistics::jaccard_to_e(1, 23));
ASSERT_DOUBLE_EQ(1, statistics::jaccard_to_e(0, 23));
}
TEST(EToJaccardTest, WorkingPoperly) {
ASSERT_NEAR(0.177298, statistics::e_to_jaccard(0.1, 12), 0.000001);
ASSERT_NEAR(0.047514, statistics::e_to_jaccard(0.24, 10), 0.000001);
ASSERT_NEAR(0.006561, statistics::e_to_jaccard(0.62, 7), 0.000001);
ASSERT_DOUBLE_EQ(1, statistics::jaccard_to_e(0, 1));
}
TEST(ELowerBoundTest, WorkingPoperly) {
ASSERT_NEAR(0.0610763, statistics::e_lower_bound(0.1, 12, 5, 0.78), 0.000001);
ASSERT_NEAR(0.186539, statistics::e_lower_bound(0.3, 10, 3, 0.8), 0.000001);
ASSERT_NEAR(0.297063, statistics::e_lower_bound(0.4, 15, 7, 0.74), 0.000001);
}
TEST(EstimtePValueTest, WorkingPoperly) {
ASSERT_NEAR(27.356028755725401, statistics::estimate_p_value(10, 16, 5000, 4699745), 0.0001);
}
TEST(RecommendedWindowSizeTest, WorkingPoperly) {
ASSERT_EQ(111, statistics::calculate_window_size(16, 5000, 4699745));
ASSERT_EQ(125, statistics::calculate_window_size(20, 5000, 3000000));
ASSERT_EQ(100, statistics::calculate_window_size(21, 5000, 5000000));
}
}
| true |
35ab9b0d00dd809e8cf553165952884986f03468 | C++ | aucd29/x86lib | /tests/mov_tests.cpp | UTF-8 | 5,945 | 2.578125 | 3 | [] | no_license | #include "x86test.h"
TEST_CASE("mov_eax_imm32", "[mov]") {
x86Tester test;
x86Checkpoint check = test.LoadCheckpoint();
test.Run("mov eax, 0x12345678");
check.SetReg32(EAX, 0x12345678);
test.Compare(check);
}
TEST_CASE("mov_ax_imm16", "[mov]") {
x86Tester test;
x86Checkpoint check = test.LoadCheckpoint();
test.Run("mov ax, 0x1234");
check.SetReg16(AX, 0x1234);
test.Compare(check);
}
TEST_CASE("modrm ebp+eax*2", "[modrm]") {
x86Tester test;
test.Run(
"mov ebp, _tmp\n"
"mov eax, 4\n"
"mov ebx, [ebp + eax * 2]\n" //resolves to _tmp + 4 * 2
"jmp _end\n"
"_tmp: dw 0, 0, 0, 0\n"
"dd 0x12345678\n");
x86Checkpoint check = test.LoadCheckpoint();
//load checkpoint after running so that we can just set the registers we care about the results of
check.SetReg32(EBX, 0x12345678);
check.SetReg32(EAX, 4);
test.Compare(check);
}
TEST_CASE("modrm ebp+disp*scale", "[modrm]") {
x86Tester test;
test.Run(
"mov ebp, _tmp\n"
"mov ebx, [ebp + 4 * 2]\n" //resolves to _tmp + 4 * 2
"jmp _end\n"
"_tmp: dw 0, 0, 0, 0\n"
"dd 0x12345678\n");
x86Checkpoint check = test.LoadCheckpoint();
//load checkpoint after running so that we can just set the registers we care about the results of
check.SetReg32(EBX, 0x12345678);
test.Compare(check);
}
TEST_CASE("modrm16 si+di+disp", "[modrm]") {
x86Tester test;
test.Run(
"mov bx, _tmp\n"
"mov si, 6\n"
"mov ebx, [bx + si + 2]\n" //resolves to _tmp + 6 + 2
"jmp _end\n"
"_tmp: dw 0, 0, 0, 0\n"
"dd 0x12345678\n");
x86Checkpoint check = test.LoadCheckpoint();
//load checkpoint after running so that we can just set the registers we care about the results of
check.SetReg32(EBX, 0x12345678);
test.Compare(check);
}
TEST_CASE("mov_rmW_immW", "[mov]") {
x86Tester test;
x86Checkpoint check = test.LoadCheckpoint();
check.SetReg32(EBX, HIGH_SCRATCH_ADDRESS);
test.Apply(check);
INFO("32bit mov");
test.Run("mov dword [ebx + 10], 0x12345678", 1);
REQUIRE(test.Check().HighScratch32(10) == 0x12345678);
test.Apply(check);
REQUIRE(test.Check().HighScratch32(10) == 0); //sanity
test.Run("mov dword [HIGH_SCRATCH_ADDRESS + 5 * 2], 0x12345678");
REQUIRE(test.Check().HighScratch32(10) == 0x12345678);
INFO("32bit mov with a16");
test.Apply(check);
test.Run("a16 mov dword [bx + 10], 0x12345678", 1);
REQUIRE(test.Check().Scratch32(10) == 0x12345678); //when rounded off to 16-bits, HighScratch = Scratch
test.Apply(check);
REQUIRE(test.Check().Scratch32(10) == 0); //sanity
test.Run("a16 mov dword [SCRATCH_ADDRESS + 5 * 2], 0x12345678");
REQUIRE(test.Check().Scratch32(10) == 0x12345678);
INFO("16bit mov with a16");
test.Apply(check);
test.Run("o16 a16 mov word [bx + 10], 0x1234", 1);
REQUIRE(test.Check().Scratch32(10) == 0x1234); //when rounded off to 16-bits, HighScratch = Scratch
test.Apply(check);
REQUIRE(test.Check().Scratch32(10) == 0); //sanity
test.Run("o16 a16 mov word [SCRATCH_ADDRESS + 5 * 2], 0x1234");
REQUIRE(test.Check().Scratch32(10) == 0x1234);
}
TEST_CASE("lea", "[lea]") {
x86Tester test;
x86Checkpoint check = test.LoadCheckpoint();
check.SetReg32(EBX, HIGH_SCRATCH_ADDRESS);
check.SetReg32(EAX, 0xFFFFFFFF);
check.SetReg32(ESI, 10);
INFO("32bit lea");
test.Apply(check);
test.Run("lea eax, [ebx + 10 * 2]", 1);
REQUIRE(test.Check().Reg32(EAX) == HIGH_SCRATCH_ADDRESS + 20);
test.Apply(check);
test.Run("lea eax, [ebx - 50]", 1);
REQUIRE(test.Check().Reg32(EAX) == HIGH_SCRATCH_ADDRESS - 50);
INFO("16bit lea");
test.Apply(check);
test.Run("o16 a16 lea ax, [bx + si + 2]", 1);
REQUIRE((int)(test.Check().Reg32(EAX) == 0xFFFF0000 | (SCRATCH_ADDRESS + 10 + 2)));
test.Apply(check);
test.Run("o16 a16 lea ax, [bx + si + 2]", 1);
REQUIRE((int)(test.Check().Reg32(EAX) == 0xFFFF0000 | (SCRATCH_ADDRESS + 10 + 2)));
INFO("mixed lea");
test.Apply(check);
test.Run("o32 a16 lea eax, [bx + si + 2]", 1);
REQUIRE((int)(test.Check().Reg32(EAX) == (SCRATCH_ADDRESS + 10 + 2)));
test.Apply(check);
test.Run("o16 a32 lea ax, [ebx - 50]", 1);
REQUIRE((int)(test.Check().Reg32(EAX) == 0xFFFF0000 | (SCRATCH_ADDRESS - 50)));
INFO("big lea");
test.Apply(check);
test.Run("lea eax, [0x12345678]", 1);
REQUIRE(test.Check().Reg32(EAX) == 0x12345678);
test.Apply(check);
test.Run("lea eax, [0x20000 + esi * 2]", 1);
REQUIRE(test.Check().Reg32(EAX) == 0x20000 + 20);
test.Apply(check);
test.Run("a16 lea eax, [bx + si + 0x1234]", 1);
REQUIRE((int)(test.Check().Reg32(EAX) == (SCRATCH_ADDRESS + 10 + 0x1234) & 0xFFFF));
}
TEST_CASE("mov_axW_mW", "[mov]") {
x86Tester test;
x86Checkpoint check = test.LoadCheckpoint();
int offset = check.regs.eip;
check.SetScratch32(0, 0x12345678);
check.SetHighScratch32(0, 0x87654321);
check.SetReg32(EAX, 0xFFFFFFFF);
test.Apply(check);
//use raw opcodes here because yasm likes to use mov_rW_rmW here instead
test.Run("db 0xA1\n dd HIGH_SCRATCH_ADDRESS"); ///mov eax, [HIGH_SCRATCH_ADDRESS]
REQUIRE(test.Check().Reg32(EAX) == 0x87654321);
REQUIRE(test.Check().regs.eip == offset + 5);
test.Apply(check);
test.Run("db 0x67\n db 0xA1\n dw SCRATCH_ADDRESS"); //a16 mov eax, [SCRATCH_ADDRESS]
REQUIRE(test.Check().Reg32(EAX) == 0x12345678);
REQUIRE(test.Check().regs.eip == offset + 4);
test.Apply(check);
test.Run("db 0x66\n db 0x67\n db 0xA1\n dw SCRATCH_ADDRESS"); //o16 a16 mov ax, [SCRATCH_ADDRESS]
REQUIRE(test.Check().Reg32(EAX) == 0xFFFF5678);
REQUIRE(test.Check().regs.eip == offset + 5);
test.Apply(check);
test.Run("db 0x66\n db 0xA1\n dd HIGH_SCRATCH_ADDRESS"); //o16 a16 mov ax, [SCRATCH_ADDRESS]
REQUIRE(test.Check().Reg32(EAX) == 0xFFFF4321);
REQUIRE(test.Check().regs.eip == offset + 6);
} | true |
44316044a4bec85ec3c572ef2290f9d63d0af66e | C++ | ZigorSK/My_Compiler_with_crutches- | /M_MULTI.cpp | UTF-8 | 2,448 | 2.796875 | 3 | [] | no_license | #include "M_MULTI.h"
Base_NeTerminal * MULTI::derivation(int * now_lex, Scaner * table, MyCheckVector *_My_check, VectorOfOP * _MyVectorOp)
{
Token lexem = _All_table->get_stream_of_token().get_table()[(*_now_lex)];//Текущий терминал
//<MULTI> ::= *<primary><MULTI> | /<primary><MULTI> | ε
if (lexem.get_name() == "*")//*<primary><MULTI>
{
//*
Base_NeTerminal *child = new Terminal(_now_lex, _All_table, this, "*");//Выделяем память под лист терминала
add(child);//Добавляем ребёнка
_My_check->push_back(child);//Добавляем терминал *
_MyVectorOp->push_back(child);
(*_now_lex)++;
}
else
{
if (lexem.get_name() == "/")// /<primary><MULTI>
{
// /
Base_NeTerminal *child = new Terminal(_now_lex, _All_table, this, "/");//Выделяем память под лист терминала
add(child);//Добавляем ребёнка
_My_check->push_back(child);//Добавляем терминал /
_MyVectorOp->push_back(child);
(*_now_lex)++;
}
else//ε
{
_flag_choice = false;//пустой символ
return this;
}
}
//<primary><MULTI>
//<primary>
Base_NeTerminal *myprimary = new primary(_now_lex, _All_table, this, "primary");
if (*myprimary->derivation(_now_lex, _All_table, _My_check, _MyVectorOp) == true)//Если последующее правило свернулось, то всё ок) вызываем рекурсивно полиморфный метод и определяем по крайнему левому
{
add(myprimary);//Значит это правило подходит, добавляем его, как ребёнок данного узла
}
else
{
delete myprimary;
}
//<multi> ::= <primary><MULTI>
//<MULTI>
Base_NeTerminal *myMULTI = new MULTI(_now_lex, _All_table, this, "MULTI");
if (*myMULTI->derivation(_now_lex, _All_table, _My_check, _MyVectorOp) == true)//Если последующее правило свернулось, то всё ок) вызываем рекурсивно полиморфный метод и определяем по крайнему левому
{
add(myMULTI);//Значит это правило подходит, добавляем его, как ребёнок данного узла
}
else
{
delete myMULTI;
}
return this;
}
| true |
458d6fc7d0587ed3d366d2676a6ddbb882d80122 | C++ | Jeevz10/kattis-code | /yoda.cpp | UTF-8 | 3,452 | 3.015625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main() {
string a1,a2;
deque<char> b1,b2;
cin >> a1 >> a2;
int len1,len2;
len1 = a1.length();
len2 = a2.length();
if (len1 > len2) {
int j = len2 - 1;
for (int i = len1 - 1;i >= 0;i--) {
if (a1[i] > a2[j]) {
b1.push_front(a1[i]);
j--;
}
else if (a2[j] > a1[i]) {
b2.push_front(a2[j]);
j--;
}
else if (a2[j] == a1[i]) {
b1.push_front(a1[i]);
b2.push_front(a2[j]);
j--;
}
if (j == -1) {
for (int k = i - 1;k >= 0;k--){
b1.push_front(a1[k]);
}
break;
}
}
}
else if (len2 > len1) {
int j = len1 - 1;
for (int i = len2 - 1;i >= 0;i--) {
if (a2[i] > a1[j]) {
b2.push_front(a2[i]);
j--;
}
else if (a1[j] > a2[i]) {
b1.push_front(a1[j]);
j--;
}
else if (a2[i] == a1[j]) {
b1.push_front(a1[j]);
b2.push_front(a2[i]);
j--;
}
if (j < 0) {
for (int k = i - 1;k >= 0; k--) {
b2.push_front(a2[k]);
}
break;
}
}
}
else if (len2 == len1) {
for (int i = len2 - 1;i >=0;i--) {
// cout << a1[i] << ' ' << a2[i] << endl;
if (a2[i] > a1[i]) {
// cout << a2[i] << endl;
b2.push_front(a2[i]);
}
else if (a1[i] > a2[i]) {
b1.push_front(a1[i]);
}
else if (a1[i] == a2[i]) {
b1.push_front(a1[i]);
b2.push_front(a2[i]);
}
}
}
deque<char>::iterator it = b1.begin();
deque<char>::iterator itr = b2.begin();
int status = 0,status2 = 0;
for (int i = 0;i < b1.size();i++) {
if (*it != '0') { // alternatievely i can do it as *it = 48, it will convert character into integer and compare
status = 1;
break;
}
*it++;
}
for (int i = 0;i < b2.size();i++) {
if (*itr != '0') {
status2 = 1;
break;
}
*itr++;
}
if (b1.size() == 0) {
cout << "YODA";
}
else if (status == 1) {
while (b1.size() > 0) {
cout << b1.front();
b1.pop_front();
}
}
else if (status == 0) {
cout << "0";
}
cout << endl;
if (b2.size() == 0) {
cout << "YODA";
}
else if (status2 == 1) {
while (b2.size() > 0) {
cout << b2.front();
b2.pop_front();
}
}
else if (status == 0) {
cout << "0";
}
// cout << b1.size() << ' ' << b2.size() << endl;
/* for (int i = 0;i <= b1.size();i++) {
cout << b1.front(); dont do this
b1.pop_front();
}
cout << endl;
for (int i = 0;i <= b2.size();i++) {
cout << b2.front();
b2.pop_front();
}
deque<char>::iterator it = b1.begin();
deque<char>::iterator itr = b2.begin();
while (it != b1.end()) {
if (b1.size() == 0) { //b2.empty()
cout << "yoda";
break;
}
int status = 0;
for (int i = 0;i < b1.size();i++) {
if (*it != 0) {
status = 1;
break;
}
*it++;
}
if (status == 1) {
cout << (*it++);
}
else if (status == 0) {
cout << "0";
}
}
cout << endl;
while (itr != b2.end()) {
if (b2.size() == 0) { //b2.empty()
cout << "yoda";
break;
}
int status = 0;
for (int i = 0;i < b2.size();i++) {
if (*itr != 0) {
status = 1;
break;
}
*itr++;
}
if (status == 1) {
cout << (*itr++);
}
else if (status == 0) {
cout << "0";
}
} */
cout << endl;
return 0;
}
| true |
9d308e3fe5559bb087d02f23534e8c9efb8350a7 | C++ | cicekozkan/CppExamples | /CppExamples/CppExamples/10_24_25/Example13_10_24_25.cpp | UTF-8 | 312 | 3.28125 | 3 | [] | no_license | // example to setfill and setw. setfill sets the fill character of the stream
// setw sets the width of the stream. It never causes a truncation
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x = 10;
cout << left << setfill('+') << setw(12) << x << "ali" << endl;
return 0;
} | true |
c751b0779e2d54e8bbd6418adbbd47ecbe1dd826 | C++ | cedricpradalier/expression_sandbox | /include/typed_expressions/EigenLinalg.hpp | UTF-8 | 2,999 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* SimpleLinalg.hpp
*
* Created on: Oct 9, 2013
* Author: hannes
*/
#ifndef EIGENLINALG_HPP_
#define EIGENLINALG_HPP_
#include <stdexcept>
#include <Eigen/Core>
#include <Eigen/Geometry>
namespace eigen_linalg {
template <typename DERIVED>
using MatrixBase = Eigen::MatrixBase<DERIVED>;
template <typename Scalar, int Rows, int Cols>
using Matrix = Eigen::Matrix<Scalar, Rows, Cols>;
template <int Dim_>
using Vector = Matrix<double, Dim_, 1>;
typedef int MatrixSize;
template<typename T>
struct MatrixConvertible {
typedef const T & type;
static inline type asMatrixConvertible(const T&t, MatrixSize size = -1){
return t;
}
};
template<typename T>
inline typename MatrixConvertible<T>::type asMatrixConvertible(const T & t, MatrixSize size = -1) {
return MatrixConvertible<T>::asMatrixConvertible(t, size);
}
template<>
struct MatrixConvertible<std::initializer_list<double>> {
typedef Eigen::VectorXd type;
static inline Eigen::VectorXd asMatrixConvertible(std::initializer_list<double> t, MatrixSize size = -1){
if(size == -1) size = t.size();
Eigen::VectorXd v(size);
int i = 0;
for(double d : t){
v[i++] = d;
}
for(; i < size ; i++){v[i] = 0.0;}
return v;
}
};
inline typename MatrixConvertible<std::initializer_list<double>>::type asMatrixConvertible(std::initializer_list<double> list, MatrixSize size = -1) {
return MatrixConvertible<std::initializer_list<double>>::asMatrixConvertible(list, size);
}
template<>
struct MatrixConvertible<std::initializer_list<std::initializer_list<double>>> {
typedef Eigen::MatrixXd type;
static inline Eigen::MatrixXd asMatrixConvertible(std::initializer_list<std::initializer_list<double>> t, MatrixSize size = -1){
if(size == -1) size = t.size();
Eigen::MatrixXd v(size, t.begin()->size());
int i = 0;
for(auto & l : t){
int j = 0;
for(auto d : l){
v(i, j) = d;
j++;
}
i++;
}
return v;
}
};
inline typename MatrixConvertible<std::initializer_list<std::initializer_list<double>>>::type asMatrixConvertible(std::initializer_list<std::initializer_list<double>> list) {
return MatrixConvertible<std::initializer_list<std::initializer_list<double>>>::asMatrixConvertible(list);
}
template<>
struct MatrixConvertible<std::function<double(MatrixSize i)>> {
typedef Eigen::VectorXd type;
static inline Eigen::VectorXd asMatrixConvertible(std::function<double(MatrixSize i)> f, MatrixSize size){
if(size < 0) throw std::runtime_error("size missing");
Eigen::VectorXd v(size);
for(int i = 0; i < size ; i++){v[i] = f(i);}
return v;
}
};
template <typename T>
T & toEigen(T&t){
return t;
}
template <typename T>
const T & toEigen(const T&t){
return t;
}
template <typename T>
T && toEigen(T&&t){
return std::move(t);
}
}
#ifndef EXP_LINALG
#define EXP_LINALG
#define TYPED_EXP_NAMESPACE_POSTFIX _eig
namespace linalg = eigen_linalg;
#endif
#endif /* EIGENLINALG_HPP_ */
| true |
fc57ebb34625dcd44aa5f5a4dc80a6ee9f0b1068 | C++ | andreibratu/bachelor | /sem2/oop/test1/UI.cpp | UTF-8 | 1,222 | 3.546875 | 4 | [] | no_license | #include "UI.h"
UI::UI(Controller& c): controller{c} {}
void UI::addPlayer() {
std::string n, c, t;
int g;
std::cout << "Name: ";
std::cin >> n;
std::cout << "Country: ";
std::cin >> c;
std::cout << "Team: ";
std::cin >> t;
std::cout << "Goals: ";
std::cin >> g;
if(!this->controller.addPlayer(n, c, t, g)) {
std::cout << "\nPlayer already exists!\n\n";
}
else {
std::cout << "\nPlayer added.\n\n";
}
}
void UI::showAll() {
std::vector<Player> all = this->controller.getAllSorted();
for(auto x: all) {
std::cout << x << '\n';
}
std::cout << '\n';
}
void UI::goalsOfCountry() {
std::string c;
std::cout << "Country: ";
std::cin >> c;
int result = this->controller.calculateScores(c);
std::cout << result << '\n';
}
void UI::loop() {
int flag = 1;
while(flag) {
std::cout << "1. Add\n2. Show all\n3. Goals by country\n4. Exit\n";
int option;
std::cin >> option;
std::cin.ignore();
switch (option) {
case 1:
this->addPlayer();
break;
case 2:
this->showAll();
break;
case 3:
this->goalsOfCountry();
break;
case 4:
flag = 0;
break;
}
}
}
| true |
ab3b42e815c143630e9efb24627483eb15f0ea4a | C++ | L-Zhe/OJ | /PAT/Advance_Level/首刷/A1136.cpp | UTF-8 | 1,244 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
struct bign{
int d[1010];
int len;
bign(){
len = 0;
memset(d, 0, sizeof(d));
}
};
bign change(char s[]){
bign a;
a.len = strlen(s);
for(int i = 0; i < a.len; ++i){
a.d[i] = s[a.len - 1 - i] - '0';
}
return a;
}
bign add(bign a, bign b){
bign c;
int carry = 0;
for(int i = 0; i < a.len || i < b.len; ++i){
int temp = a.d[i] + b.d[i] + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
if(carry != 0)
c.d[c.len++] = carry;
return c;
}
bool judge(bign a){
for(int i = 0; i <= a.len / 2; ++i){
if(a.d[i] != a.d[a.len - 1 - i])
return false;
}
return true;
}
void print(bign a){
for(int i = a.len - 1; i >= 0; --i){
printf("%d", a.d[i]);
}
}
bign reve(bign s){
bign a;
a.len = s.len;
for(int i = 0; i < a.len; ++i)
a.d[i] = s.d[a.len - 1 - i];
return a;
}
int main(){
char n[1010];
scanf("%s", n);
bign a = change(n);
int cnt = 0;
while(!judge(a) && cnt < 10){
bign b = reve(a);
bign c = add(a, b);
print(a); printf(" + "); print(b); printf(" = "); print(c); printf("\n");
a = c;
++cnt;
}
if(cnt == 10) printf("Not found in 10 iterations.");
else{
print(a);
printf(" is a palindromic number.");
}
return 0;
}
| true |
06159eef637718ff04dfbf58c99edebb181b715d | C++ | GinugaSaketh/Codes | /codeforces/rounds/#353/c.cpp | UTF-8 | 471 | 2.515625 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<vector>
#include<map>
using namespace std;
vector <long long >a;
map <long long,long long > sum;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long n;
cin>>n;
int i;
a.resize(n+5);
for(i=0;i<n;i++){
cin>>a[i];
}
for(i=1;i<n;i++){
a[i]+=a[i-1];
}
for(i=0;i<n;i++){
sum[a[i]]++;
}
int m=0;
for(i=0;i<n;i++){
if(sum[a[i]]>m){
m=sum[a[i]];
}
}
n-=m;
cout<<n<<endl;
return 0;
} | true |
da810ab6201465906969f816b3325cef42baf165 | C++ | esap120/Connect_Five | /ohPlayer.h | UTF-8 | 525 | 2.703125 | 3 | [] | no_license | #ifndef ohh
#define ohh
#include "player.h"
class ohPlayer:public player{
public:
ohPlayer(square **initTable); // initialize player
boardSquare nextMove(); // computes a next move for the player and stores coordinates in (xx,yy)
void otherMove(boardSquare bs);// records the move of the opponent
void printBoard();
void scanBoard();
boardSquare bestMove(square color);
bool block(square color);
int ohCounter (square color);
private:
int **table; // maintain my own copy of the board
};
#endif
| true |
1ec0af1bd7125e5ff60785a630b1ea6c0fc215df | C++ | KatsuhiroMorishita/Wireless-LED-control | /program/type03/type03_firmware/type03_firmware.ino | UTF-8 | 17,956 | 2.609375 | 3 | [] | no_license | /* program name: type3_test */
/* author: Katsuhiro MORISHITA */
/* : */
/* create: 2015-01-03 */
/* license: MIT */
/* format 1: header_v2, R, G, B, lisht bit field */
#include <AltSoftSerial.h>
#include <Adafruit_NeoPixel.h>
#include <EEPROM.h>
#define PLATFORM_IS_UNO
//#define PLATFORM_IS_MEGA
/** global variabls part1 **********************/
// header
const char header = 0x7f; // 多数のモジュールを一つのコマンドで操作する(ノード毎のグラデーションがない状況に適している)
const char header_v2 = 0x3f; // 個々のモジュールに発光色を4byteで伝える
const char header_v3 = 0x4f; // 内部時計のリセット(同期用)
const char header_v4 = 0x5f; // オートモードへ切り替え
const char header_v5 = 0x6f; // 遠隔操作モードへ切り替え
// serial LED setup
const int NUMPIXELS = 60;
const int IO_PIN = 6;
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, IO_PIN, NEO_GRB + NEO_KHZ800);
const float briteness_max_for_all_on = 0.7f;
// own address
const int id_init = -1;
int my_id = id_init;
// com
#ifdef PLATFORM_IS_UNO
AltSoftSerial _xbee_serial(8,9); // port is fixed on 8 & 9 at UNO.
#endif
long usbserial_baudrate = 57600;
long xbee_baudrate = 38400;
Stream *xbee;
// other
const float power_scale_for_all = 0.3; // 全点灯時の輝度強度
// モード切り替え関係
boolean mode_auto = true; // auto: 自律制御
const int buff_size = 10;
char buff[buff_size];
const int sin_size = 41;
float anplitude_sin[sin_size];
/** class *************************************/
// timeout check class
class TimeOut
{
private:
long timeout_time;
public:
// set timeout time width
void set_timeout(long timeout)
{
this->timeout_time = millis() + timeout;
}
// timeout check, true: timeout
boolean is_timeout()
{
if(millis() > this->timeout_time)
return true;
else
return false;
}
// constructer
TimeOut()
{
this->timeout_time = 0l;
}
};
// millis()の代わりに利用する
// 同期を取りやすくするため
class kmTimer
{
private:
long _time_origin;
public:
void reset()
{
this->_time_origin = millis();
}
long km_millis()
{
return millis() - this->_time_origin;
}
// constructer
kmTimer()
{
this->_time_origin = 0l;
}
};
class Colormap
{
private:
double StartH;
double EndH;
double S;
double V;
boolean Reverse;
void GenerateColorMap(int start, int end, double saturation, double brightness)
{
if (start > end)
{
this->Reverse = true;
this->StartH = end % 360;
this->EndH = start % 360;
}
else
{
this->Reverse = false;
this->StartH = start % 360;
this->EndH = end % 360;
}
if (saturation > 100) {
this->S = 100;
}
else if (saturation < 0) {
this->S = 0;
}
else {
this->S = saturation;
}
if (brightness > 100) {
this->V = 100;
}
else if (brightness < 0) {
this->V = 0;
}
else {
this->V = brightness;
}
}
void ConvertHSVtoRGB(double _h, double _s, double _v, int* _r, int* _g, int* _b)
{
_s = _s / 100;
_v = _v / 100;
_h = (int)_h % 360;
if (_s == 0.0) //Gray
{
int rgb = (int)((double)(_v * 255));
*_r = (int)(rgb);
*_g = (int)(rgb);
*_b = (int)(rgb);
}
else
{
int Hi = (int)((int)(_h / 60.0) % 6);
double f = (_h / 60.0) - Hi;
double p = _v * ( 1 - _s);
double q = _v * (1 - f * _s);
double t = _v * (1 - (1 - f) * _s);
double r = 0.0;
double g = 0.0;
double b = 0.0;
switch (Hi)
{
case 0:
r = _v;
g = t;
b = p;
break;
case 1:
r = q;
g = _v;
b = p;
break;
case 2:
r = p;
g = _v;
b = t;
break;
case 3:
r = p;
g = q;
b = _v;
break;
case 4:
r = t;
g = p;
b = _v;
break;
case 5:
r = _v;
g = p;
b = q;
break;
default:
r = 0;
g = 0;
b = 0;
break;
}
*_r = (int)(r * 255);
*_g = (int)(g * 255);
*_b = (int)(b * 255);
}
return;
}
public:
Colormap()
{
this->GenerateColorMap(240.0, 0, 100.0, 100.0);
}
void GetColor(double value, int* r, int* g, int* b)
{
if(value > 1.0) value = 1.0;
if(value < 0.0) value = 0.0;
if (this->Reverse == true)
{
value = 1.0 - value;
}
return this->ConvertHSVtoRGB(((this->EndH - this->StartH) * value) + this->StartH, this->S, this->V, r, g, b);
}
};
/** global variabls part 2 **********************/
Colormap colmap;
kmTimer kmtimer;
// millis()を置換させる(同期をとるため)
#define millis() kmtimer.km_millis()
/** general functions ***************************/
// IDを受信する
// IDは文字列で受信する。
// 例:"1234"
int recieve_id(Stream &port)
{
TimeOut to;
int id = id_init;
Stream *_port = &port;
long wait_time_ms = 5000l;
_port->print("please input ID. within ");
_port->print(wait_time_ms);
_port->println(" ms.");
to.set_timeout(wait_time_ms);
while(to.is_timeout() == false)
{
if(_port->available())
{
int c = _port->read();
if (c < '0' && c > '9')
{
_port->print("-- Error: non number char was received --");
break;
}
if (id == id_init)
id = 0;
to.set_timeout(50); // 一度受信が始まったらタイムアウトを短くして、処理時間を短縮する
id = id * 10 + (c - '0');
if(id >= 3200) // 3200以上の数値を10倍するとint型の最大値を超える可能性がある
break;
}
}
if(id != id_init)
_port->print("-- ID was received --");
return id;
}
// LED control
// 全てのLEDを単色に光らせる
void light(int r, int g, int b)
{
r = (int)(briteness_max_for_all_on * (float)r);
g = (int)(briteness_max_for_all_on * (float)g);
b = (int)(briteness_max_for_all_on * (float)b);
for(int i = 0; i < NUMPIXELS; i++)
{
pixels.setPixelColor(i, pixels.Color(r, g, b));
//pixels.show();
}
pixels.show();
Serial.print(r);
Serial.print(",");
Serial.print(g);
Serial.print(",");
Serial.println(b);
return;
}
// 色が段々変わる。色の変化はノコギリ波
void light_pattern1()
{
int r, g, b;
// 発光テスト
for(int k = 0; k < 100; k++)
{
colmap.GetColor((double)k / 100, &r, &g, &b);
light(r, g, b);
}
return;
}
// 色んな色が流れるように光る
void light_pattern2()
{
int r, g, b;
float f = 0.2;
float X = 0.3;
float dx = 0.02; // [mm]
float power = 0.05; // max: 1.0
for(int i = 0; i < 100; i++)
{
for(int i = 0; i < NUMPIXELS; i++)
{
float t = (float)millis() / 1000.0f;
float x = i * dx;
float theta = 2.0 * 3.14 * (f * t + x / X);
float y = (sin(theta) + 1.0f) / 2.0f;
colmap.GetColor(y, &r, &g, &b);
r = (int)((float)r * power); // power save
g = (int)((float)g * power);
b = (int)((float)b * power);
Serial.print(r);
Serial.print(",");
Serial.print(g);
Serial.print(",");
Serial.print(b);
Serial.println("");
//delay(100);
// pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
pixels.setPixelColor(i, pixels.Color(r, g, b)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
//delay(delayval); // Delay for a period of time (in milliseconds).
}
}
return;
}
// 点灯が流れるように発光する
void light_pattern3()
{
int _max = 20;
int r = random(0, _max), g = random(0, _max), b = random(0, _max);
for(int i = 0; i < NUMPIXELS; i++)
{
int index = i;
int index_pre = i - 1;
if(i == 0) index_pre = NUMPIXELS - 1;
pixels.setPixelColor(index, pixels.Color(r, g, b)); // Moderately bright green color.
pixels.setPixelColor(index_pre, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
delay(random(1, 100));
}
r = random(0, _max), g = random(0, _max), b = random(0, _max);
for(int i = NUMPIXELS; i > 0; i--)
{
int index = i;
int index_pre = i + 1;
if(i == NUMPIXELS - 1) index_pre = 0;
pixels.setPixelColor(index, pixels.Color(r, g, b)); // Moderately bright green color.
pixels.setPixelColor(index_pre, pixels.Color(0, 0, 0)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
delay(random(1, 100));
}
return;
}
// ホテル発光(点灯箇所は1箇所)
void light_pattern4()
{
int _max = 20;
int r = random(0, _max), g = random(0, _max), b = random(0, _max);
int index = random(0, NUMPIXELS);
long t;
long term = 1500;
for(int k = 0; k < random(1, 10); k++)
{
t = millis();
long tw = 0l;
while(tw < term)
{
float scale = sin(3.14 * (float)tw / (float)term);
int _r = (int)((float)r * scale);
int _g = (int)((float)g * scale);
int _b = (int)((float)b * scale);
pixels.setPixelColor(index, pixels.Color(_r, _g, _b)); // Moderately bright green color.
pixels.show(); // This sends the updated pixel color to the hardware.
tw = millis() - t;
}
delay(200);
}
int _delay = 2000;
delay(random(_delay, _delay * 4));
return;
}
// 梵字点灯(ぼやっと帯状に発光する)
void light_pattern5()
{
const int _max = 255;
static int r, g, b;
static long t;
static long term = 8000l; // 1回の点灯時間
static long tw = 0l;
static int width = sin_size; // 点灯するLEDの個数. 奇数のこと
static float *anplitude = anplitude_sin; // 輝度の入った配列
static int index;
static TimeOut to;
static boolean mode_turn_on = true;
static boolean mode_turn_on_backup = false;
if(mode_turn_on == true){
if(mode_turn_on_backup == false){ // renew
r = random(0, _max); // 色相はここで決まる
g = random(0, _max);
b = random(0, _max);
index = random(0, NUMPIXELS);
mode_turn_on_backup = mode_turn_on;
t = millis();
to.set_timeout(term);
}
// light
float scale = sin(3.14 * (float)tw / (float)term);
int _r = (int)((float)r * scale); // 時間とともに、輝度を変える
int _g = (int)((float)g * scale);
int _b = (int)((float)b * scale);
for(int k = 0; k < width; k++){
int dk = k - (int)(width / 2);
pixels.setPixelColor(index + dk, pixels.Color(_r * anplitude[k], _g * anplitude[k], _b * anplitude[k])); // 微妙に残光があるかも?
}
pixels.show();
tw = millis() - t;
// check time-out
if(to.is_timeout() == true)
mode_turn_on = false;
}
else{
// 消灯時間が0になるようにコメントアウト
/*
if(mode_turn_on_backup == true){ // renew to obj
int _delay = 1000;
to.set_timeout(random(_delay, _delay * 2));
mode_turn_on_backup = mode_turn_on;
light(0, 0, 0); // たまに通信が上手く行かなくて光り続けるLEDがあるやつの対策。
}
// check time-out
if(to.is_timeout() == true)
mode_turn_on = true;
*/
if(mode_turn_on_backup == true){ // renew to obj
//int _delay = 1000;
//to.set_timeout(random(_delay, _delay * 2));
mode_turn_on_backup = mode_turn_on;
light(0, 0, 0); // たまに通信が上手く行かなくて光り続けるLEDがあるやつの対策。
}
// check time-out
//if(to.is_timeout() == true)
mode_turn_on = true;
}
return;
}
// 全部同じ色に光る
void light_pattern6()
{
int r, g, b;
int color_step = 100;
// 発光テスト
for(int k = 0; k < color_step; k++)
{
colmap.GetColor((double)k / color_step, &r, &g, &b);
light(r, g, b);
}
for(int k = color_step; k > 0; k--)
{
colmap.GetColor((double)k / color_step, &r, &g, &b);
light(r, g, b);
}
return;
}
// recieve light pattern v2
// return: char, 1: 再度呼び出しが必要
char receive_light_pattern_v2(Stream *port)
{
char ans = 2;
int my_index = my_id;
TimeOut to;
int index = 0;
int _pwm_red = 0;
int _pwm_green = 0;
int _pwm_blue = 0;
Serial.println("-- p2 --");
to.set_timeout(20);
while(to.is_timeout() == false)
{
if(port->available())
{
int c = port->read();
//Serial.println(c);
index += 1;
if(c == header_v2)
{
//Serial.println("fuga");
ans = 1;
break; // 再帰は避けたい
}
if((c & 0x80) == 0) // プロトコルの仕様上、ありえないコードを受信
{
//Serial.println("hoge");
ans = 2;
break; // エラーを通知して、関数を抜ける
}
c = c & 0x7f; // 最上位ビットにマスク
to.set_timeout(20);
if(index == 1)
{
_pwm_red = c;
}
else if(index == 2)
{
_pwm_green = c;
}
else if(index == 3)
{
_pwm_blue = c;
}
else // 点灯するかどうかの判断
{
if (c == my_index)
{
_pwm_red = _pwm_red << 1;
_pwm_green = _pwm_green << 1;
_pwm_blue = _pwm_blue << 1;
light(_pwm_red, _pwm_green, _pwm_blue);
ans = 0;
break;
}
}
}
}
//if(to.is_timeout() == true)
// Serial.println("time out.");
return ans;
}
// setup
void setup()
{
// init variable
// モード切り替え用の変数
for(int i = 0; i < buff_size; i++)
buff[i] = 0x00;
// 発光強度
for(int i = 0; i < sin_size; i++)
anplitude_sin[i] = sin(3.14 * (float)i / (float)sin_size);
// init rand
randomSeed(analogRead(A0));
// serial LED setup
pixels.begin(); // This initializes the NeoPixel library.
// serial com setting
Serial.begin(usbserial_baudrate);
delay(1000);
Serial.println("-- setup start --");
#ifdef PLATFORM_IS_UNO
_xbee_serial.begin(xbee_baudrate);
xbee = &_xbee_serial;
#else
Serial1.begin(xbee_baudrate);
xbee = &Serial1;
#endif
// get ID
int _id = recieve_id(Serial);
if(_id >= 0 && _id != id_init)
{
my_id = _id;
Serial.println("-- write id to EEPROM --");
byte v_h = (byte)((my_id & 0xff00) >> 8);
EEPROM.write(0, v_h);
Serial.println(v_h);
byte v_l = (byte)(my_id & 0x00ff);
EEPROM.write(1, v_l);
Serial.println(v_l);
int parity = (int)v_h ^ (int)v_l;
EEPROM.write(2, (byte)parity);
Serial.println(parity);
delay(100);
}
else
{
Serial.println("-- read id from EEPROM --");
byte v_h = EEPROM.read(0);
byte v_l = EEPROM.read(1);
byte v_p = EEPROM.read(2);
Serial.println(v_h);
Serial.println(v_l);
Serial.println(v_p);
int parity = (int)v_h ^ (int)v_l;
if(parity == v_p)
my_id = (int)v_h * 256 + (int)v_l;
else
Serial.println("-- parity is not match --");
}
Serial.println("-- my ID --");
Serial.println(my_id);
// ID check
if(my_id == id_init)
{
Serial.println("-- ID error --");
Serial.println("-- program end --");
for(;;);
}
Serial.println("-- ID check OK --");
// light test pattern
Serial.println("-- test turn on --");
int level = 255;
light(level, level, level);
delay(1000);
//while(1);
light(0, 0, 0);
Serial.println("-- setup end --");
Serial.println("-- stand-by --");
}
// loop
void loop()
{
static TimeOut to;
boolean data_receive = false;
static int wp = 0;
//if(to.is_timeout() == true) // もし制御信号が検出されないことが続いたらオートに戻すための仕掛け
// mode_auto = true;
// LED制御
if(mode_auto == true) // 本当はクラス化した方がいいなぁ。
light_pattern5();
// 受信データ処理
if(xbee->available())
{
int c = xbee->read();
buff[wp] = (char)c;
wp = (wp + 1) % buff_size;
Serial.println(c);
// 制御パターン2
if((char)c == header_v2 && mode_auto == false)
{
//light(100, 100, 100);
while(1)
{
char ans = receive_light_pattern_v2(xbee);
if(ans == 0)
data_receive = true;
if(ans != 1)
break;
}
}
// しばらく、制御内容を保持する
// if(data_receive == true){
// mode_auto = false;
// to.set_timeout(30000l); // もし制御信号が検出されないことが続いたらオートに戻すための仕掛け
// }
// モード切り替え処理
boolean header_compleat;
// 時刻同期
header_compleat = true;
for(int i = 0; i < buff_size; i++)
if(buff[i] != header_v3)
header_compleat = false;
if(header_compleat == true)
kmtimer.reset();
// 強制でオートモードに切り替えるコードを受信した場合
header_compleat = true;
for(int i = 0; i < buff_size; i++)
if(buff[i] != header_v4)
header_compleat = false;
if(header_compleat == true)
mode_auto = true;
// 強制で遠隔操作モードに切り替えるコードを受信した場合
header_compleat = true;
for(int i = 0; i < buff_size; i++)
if(buff[i] != header_v5)
header_compleat = false;
if(header_compleat == true)
mode_auto = false;
}
}
| true |
598af4a75cc130b49088e2263526d4640fff6586 | C++ | garamizo/xmas-lights | /Arduino/calibrate_xmas_tree/calibrate_xmas_tree.ino | UTF-8 | 1,073 | 2.546875 | 3 | [] | no_license | #include <FastLED.h>
#define NUM_LED_PER_STRIP 50
#define NUM_STRIPS 9
#define NUM_LEDS (NUM_LED_PER_STRIP * NUM_STRIPS)
#define DATA_PIN 5
#define BRIGHTNESS 85 // range: 0-255
// Define the array of leds
CRGB leds[NUM_LEDS];
void setup() {
FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
// FastLED.addLeds<NUM_STRIPS, WS2811, DATA_PIN, RGB>(leds, NUM_LED_PER_STRIP);
FastLED.setBrightness(BRIGHTNESS);
}
void loop() {
unsigned long t0 = micros();
// turn on all lights
for (int i = 0; i < NUM_LEDS; i++)
leds[i] = CRGB::Green;
FastLED.show();
// delay(200);
t0 += 100000;
while (micros() < t0);
// turn on all lights
for (int i = 0; i < NUM_LEDS; i++)
leds[i] = CRGB::Black;
FastLED.show();
// delay(200);
t0 += 100000;
while (micros() < t0);
for (int i = 0; i < NUM_LEDS; i++) {
leds[i] = CRGB::Green;
FastLED.show();
t0 += 100000;
while (micros() < t0);
leds[i] = CRGB::Black;
FastLED.show();
t0 += 100000;
while (micros() < t0);
}
}
| true |
1d45dccedc1f0b8c2c47829d3f7a1ecfbcc98aeb | C++ | iannisdezwart/advent-of-code-2020 | /8a.cpp | UTF-8 | 1,581 | 3.4375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
enum OPCodes { NOP, ACC, JMP };
struct OP {
enum OPCodes op_code;
ssize_t arg;
};
vector<struct OP> ops;
unordered_set<ssize_t> visited_ops;
// Registers
ssize_t acc = 0, rip = 0;
// Read ops from input
void read_ops()
{
string line;
while (getline(cin, line)) {
string op_code_str = line.substr(0, 3);
enum OPCodes op_code;
if (op_code_str == "nop") op_code = NOP;
else if (op_code_str == "acc") op_code = ACC;
else if (op_code_str == "jmp") op_code = JMP;
else {
fprintf(stderr, "UNKNOWN OP CODE %s\n", op_code_str.c_str());
exit(1);
}
char sign = line[4];
ssize_t arg = atoi(line.substr(5).c_str());
if (sign == '-') arg *= -1;
struct OP op = { op_code, arg };
ops.push_back(op);
}
}
// Run an operation
void run_op(struct OP& op)
{
if (visited_ops.count(rip)) {
printf("EXECUTED %ld FOR THE SECOND TIME. ACC = %ld. EXITING...\n", rip, acc);
exit(0);
}
visited_ops.insert(rip);
switch (op.op_code) {
case JMP:
printf("RIP += %ld\n", op.arg);
rip += op.arg;
break;
case ACC:
printf("ACC += %ld\n", op.arg);
acc += op.arg;
rip++;
break;
case NOP:
printf("NOP\n");
rip++;
break;
default:
fprintf(stderr, "UNKNOWN OP %d\n", op.op_code);
}
printf("RIP = %ld, ACC = %ld\n", rip, acc);
}
// Execute the program
void exec()
{
while (rip < ops.size()) {
struct OP& op = ops[rip];
run_op(op);
}
}
int main()
{
read_ops();
exec();
} | true |
dbdf28c8bc5a0d5f42a92395fa24eadaf7d216fb | C++ | Rexagon/kanji-tutor | /app/models/Group.cpp | UTF-8 | 845 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | #include "Group.h"
#include <QJsonArray>
Group::Group(const QJsonObject &json)
{
m_name = json["name"].toString();
m_title = json["title"].toString();
QJsonArray categories = json["categories"].toArray();
for (int i = 0; i < categories.size(); ++i) {
m_categories.push_back(std::make_unique<Category>("data/" + categories[i].toString(), this, i));
}
}
Group::~Group()
{
m_categories.clear();
}
QString Group::getName() const
{
return m_name;
}
QString Group::getTitle() const
{
return m_title;
}
std::vector<Category*> Group::getCategories()
{
std::vector<Category*> result(m_categories.size());
for (unsigned int i = 0; i < m_categories.size(); ++i) {
result[i] = m_categories[i].get();
}
return result;
}
unsigned int Group::getNumCategories() const
{
return m_categories.size();
}
| true |
e8f42b5019d2b1bd7d32972989101d2488f67633 | C++ | Davidisop/EchoServer | /UDP SERVER/sample.cpp | UHC | 1,763 | 2.734375 | 3 | [] | no_license | #pragma comment(lib, "ws2_32")
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#define SERVERPORT 9000
#define BUFSIZE 512
int main(int argc, char* argv[])
{
int return_value;
// ʱȭ
WSADATA wd;
if (WSAStartup(MAKEWORD(2, 2), &wd) != 0)
{
return 1;
}
// socket()
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0); // ̰ ٸ.SOCK_DGRAM | 0
if (sock == INVALID_SOCKET)
{
return 1;
}
// bind()
SOCKADDR_IN Server_addresse;
ZeroMemory(&Server_addresse, sizeof(Server_addresse));
Server_addresse.sin_family = AF_INET;
Server_addresse.sin_addr.s_addr = htonl(INADDR_ANY);
Server_addresse.sin_port = htons(SERVERPORT);
return_value = bind(sock, (sockaddr*)&Server_addresse, sizeof(Server_addresse)); // ּ ش.
SOCKADDR_IN client_addresse; // ̰ ߿ϴ. ſ ݵ Server_addresse client_addresse ÿ ־ Ѵ.
int addlength;
char buffer[BUFSIZE + 1];
while (1)
{
// ޱ.
addlength = sizeof(client_addresse);
return_value = recvfrom(sock, buffer, BUFSIZE, 0, (SOCKADDR*)&client_addresse, &addlength); // TCP recv() Ŭ̾Ʈ ּҰ ! ִ! dz !
//
buffer[return_value] = '\0';
printf("[UDP Ŭ̾Ʈκ/%s:%d] %s \n", inet_ntoa(client_addresse.sin_addr), ntohs(client_addresse.sin_port), buffer); // ϱ !
// .
return_value = sendto(sock, buffer, return_value, 0, (SOCKADDR*)&client_addresse, sizeof(client_addresse)); // TCP send() Ŭ̾Ʈ ּҰ !
}
closesocket(sock);
WSACleanup();
return 0;
} | true |
920c029fcb4308eb64c1cc38d32784bc6a8f626d | C++ | DauNgocHuyen/CcodeCptit | /kiem_tra_so_nguyen_to.cpp | UTF-8 | 361 | 2.6875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int check(long long n){
if (n < 2) return 0;
else {
for (long long i = 2; i <= sqrt(n); i++){
if (n%i == 0) return 0;
}
}
return 1;
}
int main(){
long long n;
cin >> n;
if(check(n) == 1) cout << "YES";
else cout << "NO";
return 0;
}
// code by dnhuyen
| true |
0182048ef04df9cf389b0d7563218b0a1159e39b | C++ | e-Gizmo/Touch-Capacitive-Sensor | /Touch_sample/Touch_sample.ino | UTF-8 | 583 | 3.109375 | 3 | [] | no_license | /*
e-Gizmo Touch sensor module
This example code reads a digital input on D2,
then prints the result to the serial monitor.
Codes by
e-Gizmo Mechtronix Central
http://www.e-gizmo.com
August 10,2017
*/
// pins assignment
int OUTPUT_PIN = 2;
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// set D2 on an input mode
pinMode(OUTPUT_PIN, INPUT);
}
void loop() {
// read the input D2 pin
int OUTPUT_STATE = digitalRead(OUTPUT_PIN);
// print out the result
Serial.println(OUTPUT_STATE);
delay(1); // delay
}
| true |
653ff6f40aeab4e722621534807f32091f7a88c4 | C++ | 136232465/C_solution | /string/multiply.cpp | UTF-8 | 784 | 3.484375 | 3 | [] | no_license | //leetcode 43
//Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2
//time O(n²)
class Solution {
public:
string multiply(string num1, string num2) {
string res(num1.size()+num2.size(),'0');
for(int i = num1.size()-1; i>=0; --i){
int carry = 0;
for(int j=num2.size()-1; j>=0; --j){
int temp = (res[i+j+1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
res[i+j+1] = temp%10 + '0' ;
carry = temp/10;
}
res[i] += carry;
}
size_t startpos = res.find_first_not_of("0");
if (string::npos != startpos) {
return res.substr(startpos);
}
return "0";
}
}; | true |
8779673bb7eb57efb1403e1166d5d16cfb8458ad | C++ | Buczu/Projekt0 | /Sem2_Projekt3/Projekt_3/Amu_Park.h | UTF-8 | 1,029 | 2.890625 | 3 | [] | no_license | #ifndef AMU_PARK_H
#define AMU_PARK_H
#include "Ent_Park.h"
class Amu_Park :public Ent_Park
{
protected:
int workers;
int attractions;
public:
//CONSTRUCTOR AND DESCRUCTOR
Amu_Park( int=50 ,int=5,int=1000, int=500, int=10, int=500,int=5);
~Amu_Park(){};
//POLYMORPHIC METHODS INHERITATED FROM ENT_PARK
virtual void accept_visitors();
virtual void show_type(){std::cout<<"Amusement Park"<<std::endl;}
virtual char show_attractions();
virtual void show_attraction(char);
virtual bool check_resources(char, int);
virtual void buy_attraction(char, int);
virtual void manage_menu();// show management options that can be used on chosen facility
virtual void show_data();// show variables of chosen facility
//MANAGING
void buy_workers(int i){workers+=i;budget-=i*250;}
//OPERATORS
friend std::ostream& operator<<(std::ostream&,const Amu_Park &);//showing all variables
};
#endif // AMU_PARK_H
| true |
e86c4b0df09147d39b7249d90fb759ce9ffba011 | C++ | wazxser/Online-Judge | /图论/最短路dijks/HDU_3790.cpp | GB18030 | 1,701 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <memory.h>
#define INF 1<<30
using namespace std;
int map1[1010][1010], map2[1010][1010];
int vis[1010];
int dis[1010], cost[1010];
int n, m, s, t;
int a, b, c, p;
void dijkstra() {
vis[s] = 1; //ʼ飬עʼ㲻һǵһ
for (int i = 1; i <= n; i++) {
dis[i] = map1[s][i];
cost[i] = map2[s][i];
}
int min, temp;
for (int k = 1; k < n; k++) { //ʣµı
min = INF;
for (int i = 1; i <= n; i++) { //ҵĿǰСĵ
if (!vis[i] && dis[i] < min) {
temp = i;
min = dis[i];
}
}
vis[temp] = 1;
for (int j = 1; j <= n; j++) {
if (!vis[j] && dis[temp] + map1[temp][j] < dis[j]) { //
dis[j] = dis[temp] + map1[temp][j];
cost[j] = cost[temp] + map2[temp][j];
}
else if (!vis[j] && dis[temp] + map1[temp][j] == dis[j]) { //ͬһС
if (cost[j] > cost[temp] + map2[temp][j])
cost[j] = cost[temp] + map2[temp][j];
}
}
}
}
int main() {
while (~scanf("%d%d", &n, &m)) {
if (n == 0 && m == 0) {
break;
}
memset(vis, 0, sizeof(vis)); //ʼvis
for (int i = 1; i <= n; i++) { //ʼڽӾ
for (int j = 1; j <= n; j++) {
map1[i][j] = map2[i][j] = INF;
}
}
for (int i = 1; i <= m; i++) { //ͼ
scanf("%d %d %d %d", &a, &b, &c, &p);
if (c < map1[a][b]) {
map1[a][b] = map1[b][a] = c;
map2[a][b] = map2[b][a] = p;
}
}
scanf("%d%d", &s, &t);
dijkstra();
printf("%d %d\n", dis[t], cost[t]);
}
return 0;
} | true |
2b8a3ae96377f229da84206d2554b5944df2e72e | C++ | ud1/CyberCubes | /include/ModelTextures.hpp | UTF-8 | 838 | 2.65625 | 3 | [] | no_license | #ifndef MODEL_TEXTURES_HPP
#define MODEL_TEXTURES_HPP
#include <vector>
#include <string>
#include <GL/glew.h>
#include <map>
#include "Atlas.hpp"
#include "Math.hpp"
namespace cyberCubes
{
namespace model
{
class ModelTextures
{
public:
ModelTextures(const ModelTextures &o) = delete;
explicit ModelTextures(const math::ivec2 &size);
atlas::Tile addTexture(const std::string &fileName, const std::string &textureName);
atlas::Tile getTextureTile(const std::string &textureName) const;
void upload();
GLuint getTexture() const
{
return texture;
}
math::vec2 size() const
{
math::ivec2 sz = atlas.getSize();
return math::vec2(sz.x, sz.y);
}
~ModelTextures();
private:
atlas::Atlas atlas;
std::vector<unsigned char> pixels;
GLuint texture = 0;
std::map<std::string, atlas::Tile> textures;
};
}
}
#endif
| true |
29c9800ce860bf5da0888a3032a0f41b7f09a271 | C++ | Ywook/algorithm | /boj/2747.cpp | UTF-8 | 266 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using namespace std;
int a[46];
int main(){
a[0] = 0;
a[1] = 1;
a[2] = 1;
int n;
scanf("%d", &n);
for(int i =3 ; i <= n; i++){
a[i] = a[i-1] + a[i-2];
}
cout<<a[n]<<endl;
return 0;
} | true |
d4564b325a2d3b2803a52a4adb0a8f5e259258f0 | C++ | miyu0704/OpenGL3D2021 | /Src/Actor/ImageActor.cpp | SHIFT_JIS | 493 | 2.640625 | 3 | [
"MIT"
] | permissive | /**
* @file ImageActor.cpp
*/
#include "ImageActor.h"
#include "../GameEngine.h"
/**
* RXgN^
*/
ImageActor::ImageActor(
const std::string& name,
const char* filename,
const glm::vec3& position,
const glm::vec3& scale,
float rotation,
const glm::vec3& adjustment) :
Actor(name,
GameEngine::Get().GetPrimitive("Res/Plane.obj"),
GameEngine::Get().LoadTexture(filename),
position, scale, rotation, adjustment)
{
isStatic = true;
layer = Layer::UI;
}
| true |
6f9392759a774494f6357e1ebbb97800029f060e | C++ | Shimushushushu/etude-transfer-function | /test/main.cc | UTF-8 | 1,169 | 2.9375 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | #include <cmath>
#include <iostream>
#include <utility>
#include <transfer_function/TrivialTransferFunction.h>
#include <wpi/array.h>
wpi::array<double, 3> GetDriveTrainInputs() {
return {0.1, 0.21, 0.3};
}
int main(int argc, char** argv) {
const wpi::array<double, 3> foo = {-1.0, 0.0, 0.0};
TrivialTF<3> deadband{[](TrivialTF<3>::input v) -> TrivialTF<3>::output {
for (auto& itr : v) {
if (std::abs(itr) < 0.2) {
itr = 0.0;
} else {
itr = (itr - std::copysign(0.2, itr)) * 1.25;
}
}
return std::move(v);
}};
TrivialTF<3> identity{[](TrivialTF<3>::input v) -> TrivialTF<3>::output {
return std::move(v);
}};
TrivialTF<3> square{[](TrivialTF<3>::input v) -> TrivialTF<3>::output {
for (auto& itr : v) {
itr *= itr;
}
return std::move(v);
}};
{
auto ret = GetDriveTrainInputs() * deadband * square;
std::cout << ret << std::endl;
}
{
auto ret = square(deadband(GetDriveTrainInputs()));
std::cout << ret << std::endl;
}
{
auto ret = wpi::array<double, 3>{foo} * deadband * identity * square;
std::cout << ret << std::endl;
}
return 0;
} | true |
b3295adbc9841b44791fdae9bdbbd859213ee27b | C++ | Lufolas/Krpsims | /parser.cpp | UTF-8 | 9,884 | 2.671875 | 3 | [] | no_license | /*
** parser.cpp
**
** hugues froger
** Wed Nov 28 2012
*/
#include "parser.hpp"
Parser::Parser()
{}
Parser::~Parser()
{}
void Parser::setInputFile(std::string input_file)
{
this->input_file_name = input_file;
}
bool Parser::verifNodeProcessList(tinyxml2::XMLElement *b_child_elem)
{
while (b_child_elem != 0)
{
std::string name = b_child_elem->Name();
if (name != "process")
return false;
else
{
tinyxml2::XMLElement *b_child_child_elem = b_child_elem->FirstChildElement();
while (b_child_child_elem != 0)
{
std::string name = b_child_child_elem->Name();
if (name != "require" && name != "produce")
return false;
b_child_child_elem = b_child_child_elem->NextSiblingElement();
}
}
b_child_elem = b_child_elem->NextSiblingElement();
}
return true;
}
bool Parser::verifNodeDebut(tinyxml2::XMLElement *b_child_elem)
{
while (b_child_elem != 0)
{
std::string name = b_child_elem->Name();
if (name != "item")
return false;
b_child_elem = b_child_elem->NextSiblingElement();
}
return true;
}
bool Parser::verifNodes(tinyxml2::XMLElement *b_elem)
{
bool flag_process_list = false;
bool flag_debut = false;
std::string name;
while (b_elem != 0)
{
name = b_elem->Name();
if ((name == "debut" && !flag_debut) || (name == "process_list" && !flag_process_list))
{
if (name == "debut")
{
flag_debut = true;
if (!this->verifNodeDebut(b_elem->FirstChildElement()))
return false;
} else if (name == "process_list") {
flag_process_list = true;
if (!this->verifNodeProcessList(b_elem->FirstChildElement()))
return false;
}
}
else
return false;
b_elem = b_elem->NextSiblingElement();
}
return true;
}
bool Parser::verifTag()
{
tinyxml2::XMLElement *b_krp = this->doc.FirstChildElement();
std::string name = b_krp->Name();
if ((name == "krp_sims") && (b_krp->NextSiblingElement() == 0))
{
if (!this->verifNodes(b_krp->FirstChildElement()))
return false;
return true;
}
return false;
}
bool Parser::LoadDoc(void)
{
if (this->doc.LoadFile(this->input_file_name.c_str()) == tinyxml2::XML_NO_ERROR)
return this->verifTag();
else
return false;
}
bool Parser::searchAllData(void)
{
try {
this->parseOptimize();
this->parseItem();
this->parseTime();
this->parseProcess();
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
return false;
}
return true;
}
void Parser::parseOptimize(void)
{
this->b_krp_sims = this->doc.FirstChildElement("krp_sims");
if (this->b_krp_sims != 0)
if (this->b_krp_sims->Attribute("optimize"))
{
this->optimize = this->b_krp_sims->Attribute("optimize");
return;
}
throw SyntaxException("xml tag 'krp_sims' incorrect or not found.");
}
void Parser::parseItem(void)
{
this->b_debut = this->b_krp_sims->FirstChildElement("debut");
if (this->b_debut != 0)
{
tinyxml2::XMLElement *b_item = this->b_debut->FirstChildElement("item");
if (b_item == 0)
throw SyntaxException("xml tag 'item' not found in 'debut'");
while (b_item != 0)
{
if (b_item != 0)
{
if ((b_item->GetText() == 0) || (b_item->Attribute("qty") == 0))
throw SyntaxException("xml tag 'item' incorrect in 'debut'");
this->map_item.insert( std::pair<std::string, int>(b_item->GetText(), atoi(b_item->Attribute("qty"))));
}
b_item = b_item->NextSiblingElement();
}
return;
}
throw SyntaxException("xml tag 'debut' not found.");
}
std::map<std::string, int> Parser::parseRequire(tinyxml2::XMLElement *b_process)
{
std::map<std::string, int> map_require;
tinyxml2::XMLElement *b_require = b_process->FirstChildElement("require");
if (b_require == 0)
{
map_require.clear();
return map_require;
}
while (b_require != 0)
{
if (b_require != 0)
{
if ((b_require->GetText() == 0) || (b_require->Attribute("qty") == 0))
{
map_require.clear();
return map_require;
}
map_require.insert( std::pair<std::string, int>(b_require->GetText(), atoi(b_require->Attribute("qty"))));
}
b_require = b_require->NextSiblingElement("require");
}
return map_require;
}
std::map<std::string, int> Parser::parseProduce(tinyxml2::XMLElement *b_process)
{
std::map<std::string, int> map_produce;
tinyxml2::XMLElement *b_produce = b_process->FirstChildElement("produce");
if (b_produce == 0)
{
map_produce.clear();
return map_produce;
}
while (b_produce != 0)
{
if (b_produce != 0)
{
if ((b_produce->GetText() == 0) || (b_produce->Attribute("qty") == 0))
{
map_produce.clear();
return map_produce;
}
map_produce.insert( std::pair<std::string, int>(b_produce->GetText(), atoi(b_produce->Attribute("qty"))));
}
b_produce = b_produce->NextSiblingElement("produce");
}
return map_produce;
}
void Parser::parseProcess(void)
{
this->b_process_list = this->b_krp_sims->FirstChildElement("process_list");
if (this->b_process_list != 0)
{
tinyxml2::XMLElement *b_process = this->b_process_list->FirstChildElement("process");
if (b_process == 0)
throw SyntaxException("xml tag 'process' not found.");
while (b_process != 0)
{
if (b_process != 0)
{
std::map<std::string, int> map_require;
std::map<std::string, int> map_produce;
Process *process_element = new Process();
if ((b_process->Attribute("name") == 0) || (b_process->Attribute("require_time") == 0))
throw SyntaxException("xml tag 'process' incorrect.");
map_require = parseRequire(b_process);
if (map_require.empty())
throw SyntaxException("xml tag 'require' incorrect.");
map_produce = parseProduce(b_process);
if (map_produce.empty())
throw SyntaxException("xml tag 'produce' incorrect.");
process_element->setName(b_process->Attribute("name"));
process_element->setRequireTime(atoi(b_process->Attribute("require_time")));
process_element->setMapRequire(map_require);
process_element->setMapProduce(map_produce);
this->vector_process.push_back(process_element);
}
b_process = b_process->NextSiblingElement("process");
}
return;
}
throw SyntaxException("xml tag 'process_list' not found.");
}
void Parser::parseTime(void)
{
if (this->b_debut != 0)
if (this->b_debut->Attribute("time") != 0)
{
this->time = atoi(this->b_debut->Attribute("time"));
return;
}
throw SyntaxException("xml tag 'debut' incorrect or not found.");
}
std::string Parser::getOptimize(void)
{
return this->optimize;
}
std::map<std::string, int> Parser::getMapItem(void)
{
return this->map_item;
}
int Parser::getTime(void)
{
return this->time;
}
std::vector<Process *> Parser::getVectorProcess(void)
{
return this->vector_process;
}
std::vector<Process *> Parser::findProcessWhoProduce(std::string name)
{
std::vector<Process *> vector_process_res;
std::vector<Process *> vector_process = this->getVectorProcess();
std::vector<Process *>::iterator it_vector_process = vector_process.begin();
for (; it_vector_process != vector_process.end(); it_vector_process++)
{
std::map<std::string, int> map_produce = (*it_vector_process)->getMapProduce();
std::map<std::string, int>::iterator it_map_produce = map_produce.begin();
for (; it_map_produce != map_produce.end(); it_map_produce++)
{
if ((*it_map_produce).first == name)
vector_process_res.push_back(*it_vector_process);
}
}
return vector_process_res;
}
std::vector<Process *> Parser::findProcessWhoRequire(std::string name)
{
std::vector<Process *> vector_process_res;
std::vector<Process *> vector_process = this->getVectorProcess();
std::vector<Process *>::iterator it_vector_process = vector_process.begin();
for (; it_vector_process != vector_process.end(); it_vector_process++)
{
std::map<std::string, int> map_require = (*it_vector_process)->getMapRequire();
std::map<std::string, int>::iterator it_map_require = map_require.begin();
for (; it_map_require != map_require.end(); it_map_require++)
{
if ((*it_map_require).first == name)
vector_process_res.push_back(*it_vector_process);
}
}
return vector_process_res;
}
int Parser::findProcessTime(std::string name)
{
std::vector<Process *> vector_process = this->getVectorProcess();
std::vector<Process *>::iterator it_vector_process = vector_process.begin();
for (; it_vector_process != vector_process.end(); it_vector_process++)
if ((*it_vector_process)->getName() == name)
return ((*it_vector_process)->getRequireTime());
return -1;
}
int Parser::findRequireQuantity(std::string name, std::string require)
{
std::vector<Process *> vector_process = this->getVectorProcess();
std::vector<Process *>::iterator it_vector_process = vector_process.begin();
for (; it_vector_process != vector_process.end(); it_vector_process++)
{
if ((*it_vector_process)->getName() == name)
{
std::map<std::string, int> map_require = (*it_vector_process)->getMapRequire();
std::map<std::string, int>::iterator it_map_require = map_require.begin();
for (; it_map_require != map_require.end(); it_map_require++)
{
if ((*it_map_require).first == require)
return (*it_map_require).second;
}
}
}
return -1;
}
int Parser::findProduceQuantity(std::string name, std::string produce)
{
std::vector<Process *> vector_process = this->getVectorProcess();
std::vector<Process *>::iterator it_vector_process = vector_process.begin();
for (; it_vector_process != vector_process.end(); it_vector_process++)
{
if ((*it_vector_process)->getName() == name)
{
std::map<std::string, int> map_produce = (*it_vector_process)->getMapProduce();
std::map<std::string, int>::iterator it_map_produce = map_produce.begin();
for (; it_map_produce != map_produce.end(); it_map_produce++)
{
if ((*it_map_produce).first == name)
return (*it_map_produce).second;
}
}
}
return -1;
} | true |
468d5cd7a2f6b07cd39fefef95897a240aa5f1b1 | C++ | acraig5075/codeeval | /28-string-searching/main.cpp | UTF-8 | 9,834 | 3.328125 | 3 | [] | no_license | // Rabin-Karp implementation for massive strings. Complete overkill for this challenge.
// Also handles multiple wildcards, not required. Again complete overkill.
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <ctime>
#include <cassert>
using std::string;
using std::vector;
using std::ifstream;
using std::cout;
using std::unordered_map;
static const int64_t prime = 179424691;
struct Data
{
string pattern, text;
};
auto split(const string &value, char delimiter) -> vector<string>;
auto replace_asterisk(const string &original, const string &search, const string &replacement) -> string;
auto is_substring(const string &source, const string &query) -> bool;
auto mod(int64_t a, int64_t p) -> int64_t;
auto random(int64_t low, int64_t high) -> int64_t;
auto poly_hash(const string &S, size_t begin, size_t end, int64_t p, int64_t x) -> int64_t;
auto poly_hash(const string &S, int64_t p, int64_t x) -> int64_t;
auto are_equal(const string &pattern, const string &text, size_t off) -> bool;
auto precompute_hashes(const string &T, size_t L, int64_t p, int64_t x) -> unordered_map<size_t, int64_t>;
auto rabin_karp(const Data &input) -> vector<size_t>;
auto test_is_substring() -> void;
auto test_split() -> void;
int main(int argc, char *argv[])
{
//test_split();
//test_is_substring();
if (argc > 1)
{
string filename(argv[1]);
ifstream fin(filename.c_str());
if (fin.is_open())
{
string line;
while (fin.good())
{
getline(fin, line);
if (!line.empty())
{
auto tokens = split(line, ',');
cout << std::boolalpha << is_substring(tokens[0], tokens[1]) << "\n";
}
}
}
}
return 0;
}
// string tokenise
auto split(const string &value, char delimiter) -> vector<string>
{
vector<string> ret;
size_t start = 0;
while (true)
{
size_t pos = value.find(delimiter, start);
if (pos == string::npos)
{
ret.push_back(value.substr(start));
break;
}
else
{
ret.push_back(value.substr(start, pos - start));
start = pos + 1;
}
}
return ret;
}
auto replace_asterisk(const string &original, const string &search, const string &replacement) -> string
{
string text = original;
size_t pos = 0;
while (true)
{
pos = text.find(search, pos);
if (pos == string::npos)
break;
text.replace(pos, search.length(), replacement);
pos += replacement.length();
}
return text;
}
// test whether text2 is a substring of text1
auto is_substring(const string &source, const string &query) -> bool
{
string text1 = replace_asterisk(source, "*", "!");
string text2 = replace_asterisk(query, "\\*", "!");
auto tokens = split(text2, '*');
size_t start = 0;
for (const auto &pattern : tokens)
{
if (pattern == "")
continue;
string text;
text.assign(text1, start, string::npos);
Data data;
data.text = text;
data.pattern = pattern;
auto occurences = rabin_karp(data);
if (occurences.empty())
return false;
start = start + occurences[0] + pattern.length();
}
return true;
}
int64_t mod(int64_t a, int64_t p)
{
return ((a % p) + p) % p;
}
int64_t random(int64_t low, int64_t high)
{
srand((unsigned)time(0));
return low + (int64_t)(rand() * ((high - low) / RAND_MAX));
}
int64_t poly_hash(const string &S, size_t begin, size_t end, int64_t p, int64_t x)
{
int64_t hash = 0;
for (size_t i = end; i > begin; --i)
{
hash = mod(hash * x + S[i - 1], p);
}
return hash;
}
int64_t poly_hash(const string &S, int64_t p, int64_t x)
{
return poly_hash(S, 0, S.length(), p, x);
}
bool are_equal(const string &pattern, const string &text, size_t off)
{
const char *p = pattern.c_str();
const char *t = text.c_str() + off;
while (*p != '\0')
{
if (*p != *t)
return false;
++p;
++t;
}
return true;
}
unordered_map<size_t, int64_t> precompute_hashes(const string &T, size_t L, int64_t p, int64_t x)
{
size_t TL = T.length();
unordered_map<size_t, int64_t> H;
H.reserve(TL - L + 1);
string S = T.substr(TL - L);
H[TL - L] = poly_hash(S, p, x);
int64_t y = 1;
for (size_t i = 1; i <= L; ++i)
{
y = mod(y * x, p);
}
for (size_t j = TL - L; j > 0; --j)
{
size_t i = j - 1;
H[i] = mod(x * H[i + 1] + T[i] - y * T[i + L], p);
}
return H;
}
vector<size_t> rabin_karp(const Data &input)
{
vector<size_t> ans;
const string &P = input.pattern;
const string &T = input.text;
const size_t L = P.length();
const size_t TL = T.length();
if (L <= TL)
{
int64_t p = prime;
int64_t x = random(1, p - 1);
int64_t pHash = poly_hash(P, p, x);
unordered_map<size_t, int64_t> H = precompute_hashes(T, L, p, x);
for (size_t i = 0; i <= TL - L; ++i)
{
int64_t tHash = H[i];
if (pHash == tHash)
{
if (are_equal(P, T, i))
ans.push_back(i);
}
}
}
return ans;
}
auto test_is_substring() -> void
{
auto Test = [](bool expected, const string &a, const string &b)
{
assert(is_substring(a, b) == expected);
};
Test(true, "Hello", "ell");
Test(true, "This is good", "is");
Test(true, "CodeEval", "C*Eval");
Test(false, "CodeEval", "C\\*Eval");
Test(true, "Code*Eval", "Code\\*Eval");
Test(false, "Old", "Young");
Test(true, "the quick brown fox jumps over the lazy dog", "dog");
Test(true, "the quick brown fox jumps over the lazy dog", "quick*fox");
Test(false, "the quick brown fox jumps over the lazy dog", "quick\\*fox");
Test(true, "the quick*fox jumps over the lazy dog", "quick\\*fox");
Test(true, "123456789987654321", "7*9");
Test(true, "123456789987654321", "1*1");
Test(true, "123456789987654321", "1*");
Test(true, "123456789987654321", "*1");
Test(true, "anything whatsoever", "*");
Test(false, "anything whatsoever", "\\*");
Test(true, "*", "*");
Test(true, "*", "\\*");
Test(true, "abcdef*ghijkl", "f*g");
Test(true, "abcdef*ghijkl", "f\\*g");
Test(true, "abcdef*ghijkl", "d*i");
Test(false, "the quick brown fox jumps over the lazy dog", "lazy*quick");
Test(false, "the quiiiiick brown fox jumps over the laaaaazy dog", "quick*lazy");
Test(false, "the quiiiiick brown fox jumps over the laaaaazy dog", "lazy*quick");
Test(true, "the quickquickquick brown fox jumps over the lazylazylazy dog", "quick*lazy");
Test(true, "quickquickquick brown fox jumps over the lazylazylazy", "quick*lazy");
Test(true, "quickquickquicklazylazylazy", "quick*lazy");
Test(false, "lazylazylazyquickquickquick", "quick*lazy");
Test(false, "slowlazylazylazy", "quick*lazy");
Test(false, "quickquickquick123456789", "quick*lazy");
Test(true, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "c*t");
Test(true, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "t*c");
Test(true, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "za");
Test(true, "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "z*a");
Test(false, "*So*eaE", "*JH*");
Test(true, "* So*eaE", "**");
Test(true, "blblah*", "blb*h*");
Test(false, "blah*", "blb*h*");
Test(false, "blah*", "blb*h");
Test(true, "CodeEval", "C*Eval");
Test(true, "CodeEval", "C*Ev*al");
Test(false, "CodeE*val", "C*Ev*al");
Test(false, "Old", "*Young*");
Test(false, "Old", "*ung*");
Test(true, "Old", "*l*");
Test(true, "Old", "O*l*");
Test(true, "Old", "*d");
Test(true, "Old", "O*");
Test(true, "Old", "O*d");
Test(true, "rq6KRtZLQnYj29t8wrMs9kEAa", "Ms9kE");
Test(false, "F3Lt8kAP48GV0KXg7w", "kL7APw8Vgt08KG3X");
Test(true, "VO4nBSExzqUlGAU xoRpQ H VmEu", "xoRpQ H");
Test(false, "iKdQ1CdNVT4", "4QT");
Test(true, "rZqvA9MWQry0 7bEYn7fSiw DqWYW1Vge7", "W");
Test(false, "YBsZaUeIwYdopfSr1e5FlTSJ", "sZaUeIwYdopfS\\*FlT");
Test(true, "3K gATr4F0qqHkM8 nocDuMafyF8N4PU6YS", "gATr4F0qqHkM8 noc*fyF8N4PU");
Test(true, "9 yhuBs", "9");
Test(true, "2jyTx6rSt QQnq x OochTAM", "jyT");
Test(true, "zw1tK5djZhN7nmp54o77OTu", "K5djZhN*54");
Test(false, "2kr08Rr tzRc7jLkkzz7 GWPxexHw2wiGi1 1 7", "Lkkzz7\\*xexHw2wiGi1");
Test(true, "am jyCjcXch", "cX");
Test(true, "bQ*F BvpPWdSRunNb QoSBNp", "Q\\*F BvpP");
Test(true, "ecNTbxI7Z2DLGYJOZNkePl2Ue pPYP", "ZNk*l2Ue pPYP");
Test(true, "hwI43PKf", "K");
Test(true, "m41gaNa6BU1ziQlJJI93oyjJzSiMd", "m41gaNa6BU*Q");
Test(true, "6x6 P1qjPhEbepB GMOArCZ", "pB GMO*Z");
Test(false, "sI3awJJN2xpx33s4DkTXFtH6NX2nbD8f1e", "xJs842Ia1kXxpTDf3N2X3JFt");
Test(false, "A0FQzyR6Ttso47w9f YsPP", "\\*");
Test(true, "LqPbXiBy77st8j", "s*");
Test(false, "mWqlPChz AWoiaa2FI32", "ah2C");
Test(false, "GuOh", "\\*");
Test(true, "1nGojur9D399 oLcM", "oLc");
Test(true, "Hg JHzctQP09x PxCpgWlTR", "PxC");
Test(false, "Wa UF7mMIyroNmMHXxSrIX3h1", "Nr Ixy73SaM");
Test(true, "PQYARSqAynqv AZ 9Lh2 lOq v2kH4NwX", "*2kH4N");
Test(false, "sohG ohTDDAXWj7wkytij m", "\\*i");
Test(false, "zd hhRuf", "fzRh");
Test(false, "Ktvr6pGYBbXMnTYAv1Iolf", "B1YfvYpobMrvnKlA6TtG");
Test(false, "rXgXuv8FRfRxoCo7OoA kkitGB0OYIxtX", "XRftRxr0kBC");
Test(true, "5MhTky8HS6XjpoIWtUkUI", "8HS");
Test(true, "QigmDb5XuQv1SSu HX", "S");
Test(false, "kX0blNRdIPe6", "b\\*dI");
Test(false, "xpJuW 6yThHO7tRAX xR9UklJ34uDe", "xUxTJh3Hy 7J9uptX A4");
Test(true, "g5IPRqUlQmkJ8 6B5qiZy8zaWFLqJwAYh", "QmkJ8 *qiZ");
Test(false, "k1yK3deM8zwOV0xAcBr", "yMkOKB");
Test(false, "aqn dKoyXlBfUD3zFSTDQozIn erWkSCGxC1oZ", "qSrByndzFSXoGao ZI");
Test(true, "Zovk1cL8PNHsmFEOQb6", "vk1cL8*m");
Test(true, "lWvuWANx20FuCvZdOLixXQ1nM4oRkp3h9tqI", "d*");
Test(true, "p3tfkPhNh", "hN");
}
auto test_split() -> void
{
auto Test = [](const string &text, const vector<string> &expected)
{
auto actual = split(text, '*');
assert(actual == expected);
};
Test("C*Eval", { "C", "Eval" });
Test("C*Ev*al", { "C", "Ev", "al" });
Test("C*Eval*", { "C", "Eval", "" });
Test("*C*Eval", { "", "C", "Eval" });
Test("*C*Eval*", { "", "C", "Eval", "" });
Test("C**Eval", { "C", "", "Eval" });
Test("C***Eval", { "C", "", "", "Eval" });
}
| true |
d3f7e6148bd8dc675c1509426bf5165e2c6a8d74 | C++ | hajbw/OICodeStorage | /luogu/1038.cpp | UTF-8 | 1,972 | 2.921875 | 3 | [] | no_license | /*
P1038 神经网络
*/
#include <queue>
#include <iostream>
#define DEBUG 1
using std::cin;
using std::cout;
using std::pair;
using std::queue;
using std::make_pair;
using std::priority_queue;
const int MAXN = 105;
struct edge
{
int v,w,n;
}
e[MAXN * MAXN];
int
head[MAXN],iedge,N,P,
id[MAXN],otov[MAXN],toad,
gate,stat[MAXN];
inline void addedge(int u,int v,int w)
{
e[++iedge] = (edge){v,w,head[u]};
head[u] = iedge;
}
void bfs()
{
int u,v;
std::queue<int> quq;
for(u = 1;u <= N;++u)
if(!id[u])
quq.push(u);
while(!quq.empty())
{
u = quq.front();
quq.pop();
#if DEBUG
cout<<"u:"<<u<<"\n";
#endif
++toad;
otov[toad] = u;
for(int i = head[u];i;i = e[i].n)
{
v = e[i].v;
#if DEBUG
cout<<"v:"<<v<<"\ti:"<<i<<"|\n";
#endif
--id[v];
if(!id[v])
quq.push(v);
}
}
}
int main()
{
int u,v,w;
std::priority_queue<pair<int,int>,std::vector<pair<int,int> >,std::greater<pair<int,int> > >quq;//(v,stat)
cin>>N>>P;
for(int i = 1;i <= N;++i)
{
cin>>stat[i]>>gate;
stat[i] -= gate;
}
for(int i = 1;i <= P;++i)
{
cin>>u>>v>>w;
addedge(u,v,w);
++id[v];
}
bfs();
#if DEBUG
cout<<"i\totov\tgate\tstat\n";
for(int i = 1;i <= N;++i)
cout<<i<<'\t'<<otov[i]<<'\t'<<gate[i]<<'\t'<<stat[i]<<'\n';
cout.put('\n');
#endif
for(int i = 1,j;i <= N;++i)
{
u = otov[i];
j = head[u];
if(stat[u] <= 0)
continue;
if(!j)//output nerve
quq.push(make_pair(u,stat[u]));
for(;j;j = e[j].n)
{
cout<<u<<'\t'<<e[j].v<<'\t'<<(
stat[e[j].v] += stat[u] * e[j].w)<<'\n';
}
}
#if DEBUG
cout<<"\ni\totov\tgate\tstat\n";
for(int i = 1;i <= N;++i)
cout<<i<<'\t'<<otov[i]<<'\t'<<gate[i]<<'\t'<<stat[i]<<'\n';
#endif
if(quq.empty())
cout<<"NULL";
else while(!quq.empty())
{
cout<<quq.top().first<<' '<<quq.top().second<<'\n';
quq.pop();
}
return 0;
} | true |
ed1790185c98fda6c9e00394c22351e90851a6b2 | C++ | ZhiCheng0326/SJTU-Cpp | /past_year_exam/2013-2014/saddlept.cpp | UTF-8 | 1,765 | 3.828125 | 4 | [] | no_license | /*
Look for saddle point and output the row and column of the point if it exists,
else output the sum of all elements in the matrix
*/
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
infile.open("saddlept.in");
outfile.open("saddlept.out");
if(!infile){cerr << "Infile open error!";}
if(!outfile){cerr << "Outfile open error!";}
int row,column;
infile >> row >> column; //get row and column number
infile.ignore(100,'\n'); //clear stream
int **data;
data = new int*[row]; //create 2d dynamic array
for(int i=0; i<row; ++i){
data[i] = new int[column+1];
for(int j=0; j<column; ++j){
infile>>data[i][j]; //input matrix into 2d array
}
}
int big, bigCol, sum = 0;
bool found = false;
for(int j=0; j<row; ++j){
big=data[j][0]; //initialize the 1st element of each row as biggest number
bigCol = 0; //initialize the column of largest value element to 0
for(int k=0; k<column; ++k){
sum+=data[j][k]; //collect sum;
if(data[j][k]>big){
big = data[j][k];
bigCol = k; //store column index of biggest number in a row
}
}
for(int x=0; x<row; ++x){ //fix column, loop through rows
data[j][bigCol]<=data[x][bigCol] ? found = true : found = false;
if(!found){break;}
}
if (found){outfile << j+1 << " " << bigCol+1;break;}
}
if(!found) {outfile << sum;}
infile.close();
outfile.close();
return 0;
}
| true |
ce230a2c30565d544b8acb7a9e22fd0edc245d97 | C++ | CompFUSE/DCA | /test/unit/linalg/vector_cpu_gpu_test.cpp | UTF-8 | 6,803 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Raffaele Solca' (rasolca@itp.phys.ethz.ch)
//
// This file tests the interaction between Vector<CPU> and Vector<GPU>.
#include "dca/linalg/vector.hpp"
#include <complex>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "gpu_test_util.hpp"
TEST(VectorCPUTest, PointerMemoryType) {
size_t size = 3;
size_t capacity = 11;
std::string name("vector name");
// Tests all the constructors.
{
dca::linalg::Vector<float, dca::linalg::CPU> vec(name, size, capacity);
ASSERT_TRUE(testing::isHostPointer(vec.ptr()));
}
{
dca::linalg::Vector<int, dca::linalg::CPU> vec(size);
EXPECT_TRUE(testing::isHostPointer(vec.ptr()));
}
{
dca::linalg::Vector<std::complex<double>, dca::linalg::CPU> vec(size, capacity);
EXPECT_TRUE(testing::isHostPointer(vec.ptr()));
}
{
dca::linalg::Vector<int, dca::linalg::CPU> vec(name, size);
EXPECT_TRUE(testing::isHostPointer(vec.ptr()));
}
}
TEST(VectorCPUGPUTest, Constructors) {
size_t size = 3;
dca::linalg::Vector<float, dca::linalg::CPU> vec("name", size);
// Set the elements.
for (int i = 0; i < vec.size(); ++i) {
float el = 3 * i - 2;
vec[i] = el;
}
dca::linalg::Vector<float, dca::linalg::GPU> vec_copy(vec);
ASSERT_EQ(vec.size(), vec_copy.size());
ASSERT_LE(vec.size(), vec_copy.capacity());
ASSERT_TRUE(testing::isDevicePointer(vec_copy.ptr()));
dca::linalg::Vector<float, dca::linalg::CPU> vec_copy_copy(vec_copy);
EXPECT_EQ(vec.size(), vec_copy_copy.size());
EXPECT_LE(vec.size(), vec_copy_copy.capacity());
EXPECT_TRUE(testing::isHostPointer(vec_copy_copy.ptr()));
for (int i = 0; i < vec.size(); ++i) {
EXPECT_EQ(vec[i], vec_copy_copy[i]);
EXPECT_NE(vec.ptr(i), vec_copy_copy.ptr(i));
}
}
TEST(VectorCPUGPUTest, Assignement) {
{
// Assign a vector that fits into the capacity.
size_t size = 3;
dca::linalg::Vector<float, dca::linalg::GPU> vec_copy(10);
auto old_ptr = vec_copy.ptr();
auto capacity = vec_copy.capacity();
dca::linalg::Vector<float, dca::linalg::CPU> vec_copy_copy(6);
auto old_ptr_2 = vec_copy_copy.ptr();
auto capacity_2 = vec_copy_copy.capacity();
dca::linalg::Vector<float, dca::linalg::CPU> vec("name", size);
// Set the elements.
for (int i = 0; i < vec.size(); ++i) {
float el = 3 * i - 2;
vec[i] = el;
}
vec_copy = vec;
ASSERT_EQ(vec.size(), vec_copy.size());
ASSERT_EQ(capacity, vec_copy.capacity());
ASSERT_EQ(old_ptr, vec_copy.ptr());
ASSERT_TRUE(testing::isDevicePointer(vec_copy.ptr()));
vec_copy_copy = vec_copy;
EXPECT_EQ(vec.size(), vec_copy_copy.size());
EXPECT_EQ(capacity_2, vec_copy_copy.capacity());
EXPECT_EQ(old_ptr_2, vec_copy_copy.ptr());
EXPECT_TRUE(testing::isHostPointer(vec_copy_copy.ptr()));
for (int i = 0; i < vec.size(); ++i) {
EXPECT_EQ(vec[i], vec_copy_copy[i]);
EXPECT_NE(vec.ptr(i), vec_copy_copy.ptr(i));
}
}
{
// Assign a vector that doesn't fit into the capacity.
dca::linalg::Vector<float, dca::linalg::GPU> vec_copy(10);
dca::linalg::Vector<float, dca::linalg::CPU> vec_copy_copy(6);
size_t size = std::max(vec_copy.capacity(), vec_copy_copy.capacity()) + 1;
dca::linalg::Vector<float, dca::linalg::CPU> vec("name", size);
// Set the elements.
for (int i = 0; i < vec.size(); ++i) {
float el = 3 * i - 2;
vec[i] = el;
}
vec_copy = vec;
ASSERT_EQ(vec.size(), vec_copy.size());
ASSERT_LE(vec.size(), vec_copy.capacity());
ASSERT_FALSE(testing::isHostPointer(vec_copy.ptr()));
vec_copy_copy = vec_copy;
EXPECT_EQ(vec.size(), vec_copy_copy.size());
EXPECT_LE(vec.size(), vec_copy_copy.capacity());
EXPECT_TRUE(testing::isHostPointer(vec_copy_copy.ptr()));
for (int i = 0; i < vec.size(); ++i) {
EXPECT_EQ(vec[i], vec_copy_copy[i]);
EXPECT_NE(vec.ptr(i), vec_copy_copy.ptr(i));
}
}
}
TEST(VectorCPUGPUTest, Set) {
{
// Assign a vector that fits into the capacity.
size_t size = 3;
dca::linalg::Vector<float, dca::linalg::GPU> vec_copy(10);
auto old_ptr = vec_copy.ptr();
auto capacity = vec_copy.capacity();
dca::linalg::Vector<float, dca::linalg::CPU> vec_copy_copy(6);
auto old_ptr_2 = vec_copy_copy.ptr();
auto capacity_2 = vec_copy_copy.capacity();
dca::linalg::Vector<float, dca::linalg::CPU> vec("name", size);
// Set the elements.
for (int i = 0; i < vec.size(); ++i) {
float el = 3 * i - 2;
vec[i] = el;
}
vec_copy.set(vec, 0, 1);
ASSERT_EQ(vec.size(), vec_copy.size());
ASSERT_EQ(capacity, vec_copy.capacity());
ASSERT_EQ(old_ptr, vec_copy.ptr());
ASSERT_TRUE(testing::isDevicePointer(vec_copy.ptr()));
vec_copy_copy.set(vec_copy, 0, 1);
EXPECT_EQ(vec.size(), vec_copy_copy.size());
EXPECT_EQ(capacity_2, vec_copy_copy.capacity());
EXPECT_EQ(old_ptr_2, vec_copy_copy.ptr());
EXPECT_TRUE(testing::isHostPointer(vec_copy_copy.ptr()));
for (int i = 0; i < vec.size(); ++i) {
EXPECT_EQ(vec[i], vec_copy_copy[i]);
EXPECT_NE(vec.ptr(i), vec_copy_copy.ptr(i));
}
}
{
// Assign a vector that doesn't fit into the capacity.
dca::linalg::Vector<float, dca::linalg::GPU> vec_copy(10);
dca::linalg::Vector<float, dca::linalg::CPU> vec_copy_copy(6);
size_t size = std::max(vec_copy.capacity(), vec_copy_copy.capacity()) + 1;
dca::linalg::Vector<float, dca::linalg::CPU> vec("name", size);
// Set the elements.
for (int i = 0; i < vec.size(); ++i) {
float el = 3 * i - 2;
vec[i] = el;
}
vec_copy.set(vec, 0, 1);
ASSERT_EQ(vec.size(), vec_copy.size());
ASSERT_LE(vec.size(), vec_copy.capacity());
ASSERT_FALSE(testing::isHostPointer(vec_copy.ptr()));
vec_copy_copy.set(vec_copy, 0, 1);
EXPECT_EQ(vec.size(), vec_copy_copy.size());
EXPECT_LE(vec.size(), vec_copy_copy.capacity());
EXPECT_TRUE(testing::isHostPointer(vec_copy_copy.ptr()));
for (int i = 0; i < vec.size(); ++i) {
EXPECT_EQ(vec[i], vec_copy_copy[i]);
EXPECT_NE(vec.ptr(i), vec_copy_copy.ptr(i));
}
}
}
TEST(VectorCPUTest, setAsync) {
std::vector<int> vec(4, 1);
dca::linalg::Vector<int, dca::linalg::GPU> vec_copy;
dca::linalg::Vector<int, dca::linalg::CPU> vec_copy_copy;
dca::linalg::util::GpuStream stream;
vec_copy.setAsync(vec, stream);
vec_copy_copy.setAsync(vec_copy, stream);
stream.sync();
EXPECT_EQ(vec.size(), vec_copy_copy.size());
for (int i = 0; i < vec.size(); ++i)
EXPECT_EQ(vec[i], vec_copy_copy[i]);
}
| true |
f9c81e7b6c9d2c1f5bd0dcad9868e4629ade8731 | C++ | borjabrisson/tester | /hilos/hijo.cpp | UTF-8 | 1,041 | 2.859375 | 3 | [] | no_license | /*
* hijo.cpp
*
* Created on: Aug 12, 2013
* Author: borja
*/
#include "hijo.h"
hijo::hijo() {
// TODO Auto-generated constructor stub
}
hijo::~hijo() {
// TODO Auto-generated destructor stub
}
void* hijo::print(void *id){
long tid;
tid = (long)id;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
void hijo::run(int ID){
int rc;
int i = ID;
pthread_t thread;
//rc = pthread_create(&thread, NULL,print, (void *)ID);
rc = pthread_create(&thread, NULL, &hijo::print, (void *)ID);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
//pthread_exit(NULL);
}
/*
void hijo::run(int ID)
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i=0; i < NUM_THREADS; i++ ){
cout << "Hijo() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL,
&hijo::print, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
//pthread_exit(NULL);
}*/
| true |
b965141d9baf8f512b727bb068328cee8ce88b33 | C++ | sebstr1/Unitasks-cpp | /Object based cpp/sest1601_DT019G_PROJEKT Jukebox/Album.cpp | ISO-8859-1 | 3,557 | 3.328125 | 3 | [] | no_license | //klassFUNK.cpp
#include "Album.h"
using namespace std;
//------------------------------------------------------------------------------
// Definition av medlemsfunktioner
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Frvald konstruktor (Default constructor)
//------------------------------------------------------------------------------
Album::Album()
{
AlbumNamn = "";
}
//------------------------------------------------------------------------------
//Konstruktor fr initiering av datamedlemmarna
//------------------------------------------------------------------------------
Album::Album(string pAlbumNamn)
{
AlbumNamn = pAlbumNamn;
}
//------------------------------------------------------------------------------
// Set namn p Album.
//------------------------------------------------------------------------------
void Album::setAlbumNamn(string pAlbumNamn)
{
AlbumNamn = pAlbumNamn;
}
//------------------------------------------------------------------------------
// Get namn p Album.
//------------------------------------------------------------------------------
string Album::getAlbumNamn() const
{
return AlbumNamn;
}
//Hmtar den totala albumtiden
Time Album::AlbumLengd() const
{
Time totalTime;
for (auto e : Vector_of_Songs)
{
totalTime = totalTime + e.getSongLengd();
}
return totalTime;
}
//------------------------------------------------------------------------------
// verlagring
//------------------------------------------------------------------------------
// verlagring av < operatorn
bool Album::operator<(const Album & pAlbum) const
{
return AlbumLengd() < pAlbum.AlbumLengd();
}
// Lgger till en lt till ett album
void Album::addSong(Song &song)
{
// Pushar sngobjekt till Vector
Vector_of_Songs.push_back(song);
}
// Tmmer sngvectorn
void Album::clearVector_of_Songs()
{
Vector_of_Songs.clear();
}
// Hmtar antalet ltar i albumvectorn
int Album::Number_of_Songs() const
{
// Vectorns storlek (antalet ltar)
return Vector_of_Songs.size();
}
// Avgrnsare..
const char DELIM = '|';
// verlagringen av << till utskrift av album
ostream &operator<<(ostream &os, const Album &pAlbum)
{
// Albumtitel
os << pAlbum.getAlbumNamn() << endl;
// Antal songs
os << pAlbum.Number_of_Songs() << endl;
// Alla songs i hela albumet..
for (int i = 0, h = 1; i < pAlbum.Number_of_Songs(); i++, h++)
{
os << pAlbum.getVector_of_Songs()[i];
// Newline varje rad utom sista lten i varje album
if (h % pAlbum.Number_of_Songs() != 0)
os << endl;
}
return os;
}
// verlagringen av >> till inlsning av album
istream &operator >> (istream &is, Album &album)
{
// Skapar ett objekt av typen Song
Song songObj;
// Fr att lagra input
string tmp;
// Om vectorn med songs inte r tom
if (!album.getAlbumNamn().empty())
{
// Tm vectorn
album.clearVector_of_Songs();
}
// Lser in Albumnamn
getline(is, tmp);
// stter albumnamn
album.setAlbumNamn(tmp);
// Variabel fr att lagra antalet songs
int album_songs = 0;
// Lser in songs per album
getline(is, tmp);
// Strngstrm med antal songs
stringstream albumSongs_Stream(tmp);
// Konverterar til int
albumSongs_Stream >> album_songs;
//Lser in songs
for (int i = 0; i < album_songs; ++i)
{
// Lgger till songs i albumets vector
is >> songObj;
// Tar bort newline
is.ignore(10000, '\n');
album.addSong(songObj);
}
return is;
} | true |
b8be6832277b0d02e8cc8705dd5913b8099c1943 | C++ | december0123/NEAT | /src/neat.cpp | UTF-8 | 2,399 | 2.828125 | 3 | [] | no_license | #include <random>
#include "headers/neat.hpp"
#include "headers/neatnetwork.hpp"
#include "headers/neatneurongene.hpp"
NEAT::NEAT(int inputs, int outputs)
:inputs_(inputs), outputs_(outputs), innovation_database_(*this)
{
}
void NEAT::populate()
{
std::random_device rd;
std::mt19937 re(rd());
std::uniform_real_distribution<float> random_float(-1,1);
// create one species with the size of desired_population_size_
population_.emplace_back();
for(unsigned i=0; i<desired_population_size_; i++)
{
population_[0].push_back(std::move(
NEATGenome(*this)
));
}
// in each genome add input neuron genes
for(unsigned input=0; input<inputs_; input++)
{
unsigned innovation_id_of_input = innovation_database_.get_id_for_neuron_innovation();
for(auto genome: population_[0])
genome.add_neuron(innovation_id_of_input, NEATNeuronGene::GeneType::Input);
}
// in each genome add bias neuron gene
unsigned innovation_id_of_bias = innovation_database_.get_id_for_neuron_innovation();
for(auto genome: population_[0])
genome.add_neuron(innovation_id_of_bias, NEATNeuronGene::GeneType::Bias);
// in each genome add output neuron genes
for(unsigned output=0; output<outputs_; output++)
{
unsigned innovation_id_of_output = innovation_database_.get_id_for_neuron_innovation();
for(auto genome: population_[0])
genome.add_neuron(innovation_id_of_output, NEATNeuronGene::GeneType::Output);
}
// in each genome add links from input and bias to outputs
for(unsigned from=0; from<inputs_+1; from++)
{
for(unsigned to=inputs_+1; to<inputs_+outputs_+1; to++)
{
unsigned innovation_id_of_link = innovation_database_.get_id_for_link_innovation(from, to, false);
for(auto genome: population_[0])
{
genome.add_link(
innovation_id_of_link,
from,
to,
random_float(re)
);
}
}
}
}
std::vector<NEATNetwork> NEAT::get_networks()
{
std::vector<NEATNetwork> networks;
for(auto species: population_)
for(auto genome: species)
networks.push_back(std::move(genome.to_network()));
return networks;
} | true |
d5489e532de2b5dbe7bbcb1a097c0eddbcef55bc | C++ | ErikLysne/HueLib | /source/huegroup.h | UTF-8 | 2,102 | 2.59375 | 3 | [] | no_license | #ifndef HUEGROUP_H
#define HUEGROUP_H
#include <memory>
#include "hueabstractobject.h"
#include "huetypes.h"
#include "hueobjectlist.h"
class HueGroup : public HueAbstractObject
{
Q_OBJECT
public:
HueGroup();
HueGroup(HueBridge* bridge);
static HueGroupList discoverGroups(HueBridge* bridge);
HueLightList getLights(const HueLightList& lights) const;
Group::Action action() const;
Group::Lights lights() const;
Group::Sensors sensors() const;
Group::State state() const;
Group::Name name() const;
Group::Type type() const;
Group::GroupClass groupClass() const;
Group::Recycle recycle() const;
bool hasValidConstructor() const override;
bool isValid() const override;
int ID() const override;
bool synchronize() override;
private:
HueGroup(HueBridge* bridge,
int ID,
Group::Action action, Group::Lights lights,
Group::Sensors sensors, Group::State state,
Group::Name name, Group::Type type,
Group::GroupClass classObject, Group::Recycle recycle);
HueGroup(const HueGroup& rhs);
HueGroup operator=(const HueGroup& rhs);
static bool constructHueGroup(int ID, QJsonObject json, std::shared_ptr<HueGroup>& group);
HueRequest makePutRequest(QJsonObject json) override;
HueRequest makeGetRequest() override;
void updateOn(const bool on) override;
void updateHue(const int hue) override;
void updateSaturation(const int saturation) override;
void updateBrightness(const int brightness) override;
void updateColorTemp(const int colorTemp) override;
void updateXY(const double x, const double y) override;
void updateAlert(const HueAlert alert) override;
void updateEffect(const HueEffect effect) override;
private:
int m_ID;
Group::Action m_action;
Group::Lights m_lights;
Group::Sensors m_sensors;
Group::State m_state;
Group::Name m_name;
Group::Type m_type;
Group::GroupClass m_groupClass;
Group::Recycle m_recycle;
bool m_validConstructor;
};
#endif // HUEGROUP_H
| true |
02e1753b1941616997e6d5616d1f8720031976c0 | C++ | sebastianripari/75.42_taller_de_programacion_I | /tp3/src/common_socket.h | UTF-8 | 2,913 | 3.390625 | 3 | [] | no_license | #ifndef __SOCKET_H__
#define __SOCKET_H__
/*** Socket ***/
#include <cstddef>
#include <string>
class Socket {
int skt_fd;
explicit Socket(const int skt_fd);
int send(const void *buffer, const int length);
int recv(void *buffer, const int length);
void send_buffer(const char* buffer, const int length);
void recv_buffer(char *buffer, const int length);
public:
// Contruye el socket.
// Deja inicializado el objeto.
Socket();
// Constructor por movimiento.
Socket(Socket &&other);
// Destructor del socket.
// Libera todos los recursos utilizados por el socket.
~Socket();
// Asignacion pr movimiento.
Socket& operator=(Socket &&other);
// Prohibo la construccion por copia.
Socket(const Socket&) = delete;
// Prohibo la asignacion por copia.
Socket& operator=(const Socket&) = delete;
// Establece a que puerto se quiere asociar el socket.
// Si sucede un error se arroja una excepcion (std::runtime_error).
void bind(const unsigned short port);
/* Establece una conneccion a la maquina remota, indicada
* mediante host_name y port.
*/
// Si sucede un error se arroja una excepcion (std::runtime_error).
void connect(const char *host_name, const unsigned short port);
/* Define cuantas conecciones en espera pueden esperar hasta ser
* aceptadas en el Socket.
*/
// Si sucede un error se arroja una excepcion (std::runtime_error).
void listen(const int max_standby_conn);
// Crea un nuevo socket servidor para la comunicacion con el socket cliente.
// Retorna el nuevo socket.
// Si sucede un error se arroja una excepcion (std::runtime_error).
Socket accept();
// El socket envia el entero pasado como parametro.
void send_int(const int i);
// El socket envia el entero sin signo pasado como parametro.
void send_unsigned_int(const unsigned int i);
// El socket envia el caracter pasado como parametro.
void send_char(const char c);
// El socket envia el string pasado como parametro.
void send_str(const std::string &str);
// El socket recibe un entero.
// Este dato es retornado.
int recv_int();
// El socket recibe un entero sin signo.
// Este dato es retornado.
unsigned int recv_unsigned_int();
// El socket recibe un caracter.
// Este dato es retornado.
char recv_char();
// El socket recibe un caracter sin signo.
// Este dato es retornado.
unsigned char recv_unsigned_char();
// El socket recibe un string.
// Este dato es retornado.
std::string recv_str();
// Deshabilita la lectura de datos del socket.
// Si sucede un error se arroja una excepcion (std::runtime_error).
void shutdown_read();
// Deshabilita la escritura de datos del socket.
// Si sucede un error se arroja una excepcion (std::runtime_error).
void shutdown_write();
// Deshabilita la lectura y escritura de datos del socket.
// Si sucede un error se arroja una excepcion (std::runtime_error).
void shutdown();
};
#endif
| true |
c9ec320d49088ca68986209f09b5f52b9dd6fd3f | C++ | zstio-zeromski/cplusplus | /c++ - źródła/tablice obieków/tablica-trojkat.cpp | WINDOWS-1250 | 659 | 3.65625 | 4 | [] | no_license | //Tablice obiektw klasy
#include <iostream>
#include <String>
#include <cstdlib>
using namespace std;
class Trojkat {
public:
double wysokosc;
double podstawa;
double policz_pole();
};
double Trojkat::policz_pole()
{
return 0.5*wysokosc*podstawa;
}
int main()
{
const int n=100;//rozmiar tablicy
Trojkat tablica[n];
tablica[0].wysokosc = 10.5;
tablica[0].podstawa = 3.9;
cout<<"Pole wynosi "<<tablica[0].policz_pole()<<endl;
for(int i=0; i<n; i++)
{
tablica[i].wysokosc = rand() % 100;
tablica[i].podstawa = rand() % 100;
cout<<"Pole "<<i<<" tego elementu wynosi "<<tablica[i].policz_pole()<<endl;
}
return 0;
}
| true |
3171f89ddb47dffa5836cf9d7d5d8dbf2744273e | C++ | bysreg/tubes-checkers | /Project/src/Tile.cpp | UTF-8 | 633 | 2.796875 | 3 | [] | no_license | #include "Tile.h"
#include <iostream>
using namespace std;
int const Tile::KING = 1;
int const Tile::PION = 0;
Tile::Tile() {
mColor=0;
mStatus=0;
mIsThereCoin=false;
}
int Tile::getColor() {
return mColor;
}
void Tile::setColor(int aColor) {
mColor = aColor;
}
int Tile::getStatus() {
return mStatus;
}
void Tile::setStatus(int aStatus) {
mStatus = aStatus;
}
bool Tile::isCoinInTile() {
return mIsThereCoin;
}
void Tile::setCoin(int aColor,int aStatus) {
mColor = aColor;
mStatus = aStatus;
mIsThereCoin = true;
}
void Tile::removeCoin() {
mIsThereCoin = false;
}
| true |
49930451383ccb7a7cd857d1108274e558fe84f2 | C++ | vsboy/Data-structures---lookup-techniques | /扩展案例/哈希表/哈希表/HashTable.h | GB18030 | 2,214 | 3.40625 | 3 | [] | no_license | #include"Datatype.h"
enum KindOfItem{Empty,Active,Deleted};
//״̬Ͷ
struct HashItem
//ṹ嶨
{
Datatype data;
KindOfItem info;
HashItem(KindOfItem i=Empty):info(i){}
HashItem(const Datatype&D,KindOfItem i=Empty):data(D),info(i){}
int operator==(HashItem& a)
{return data==a.data;}
int operator!=(HashItem& a)
{return data!=a.data;}
};
class HashTable //ϣ
{
private:
HashItem*ht; //ϣ
int TableSize; //ĸ
int currentSize; //鵱ǰı
void AllocateHt() //ϣռ
{ht=new HashItem[TableSize];}
int FindPos(const Datatype& x)const; //λ
public:
//캯
HashTable(int m):TableSize(m)
{AllocateHt();currentSize=0;}
~HashTable(void)
{delete []ht;}
int Find(const Datatype& x); //
int Insert(const Datatype& x); //
int Delete(const Datatype& x); //ɾ
int IsIn(const Datatype& x) //ǷѴ
{int i=Find(x);return i>=0?1:0;}
Datatype GetValue(int i)const //ȡֵ
{return ht[i].data;}
void Clear(void); //
};
int HashTable::FindPos(const Datatype& x)const
{int i=x.key%TableSize;
int j=i;
while(ht[j].info==Active && ht[j].data!=x)
{
j=(j+1)%TableSize;
if(j==i)return-TableSize;
}
if(ht[j].info==Active) return j;
else return-j;
}
int HashTable::Find(const Datatype& x)
{
int i=FindPos(x),j=i;
if(j>=0)
{
while(ht[j].info==Active && ht[j].data!=x)
{
j=(j+1)%TableSize;
if(j==i) return -TableSize;
}
if(ht[j].info==Active)return j;
else return-j;
}
else return j;
}
int HashTable::Insert(const Datatype& x)
{
int i=FindPos(x);
if(i>0) return 0;
else if (i!=-TableSize && ht[-i].info!=Active)
{
ht[-i].data=x;
ht[-i].info=Active;
currentSize++;
return 1;
}
else return 0;
}
int HashTable::Delete(const Datatype& x)
{
int i=FindPos(x);
if(i>=0)
{
ht[i].info=Deleted;
currentSize--;
return 1;
}
else return 0;
}
void HashTable::Clear(void)
{
for(int i=0;i<TableSize;i++)
ht[i].info=Empty;
currentSize=0;
}
| true |
af0d9a20d4cd595c9061c256063359cf325102f1 | C++ | itfelstead/cpp11-tests | /Lambda/main.cpp | UTF-8 | 2,349 | 3.953125 | 4 | [] | no_license | #include <iostream>
// Note: compiler auto deduction of size from array reference
template<typename T, int size, typename TCallback>
void ForEach( T(&myArray)[size], TCallback MyOperation )
{
for( int i=0; i<size-1; ++i ) {
MyOperation( myArray[i] );
}
}
void TestCaptureList()
{
int data[]{ 1,5,8,2,5,1};
// Just print
ForEach( data, [](auto arg) {
std::cout << "doing " << arg << std::endl;
} );
// Add a value using a captured offset (a COPY of offset)
int offset = 10;
ForEach( data, [offset](auto &arg) {
std::cout << "doing " << arg;
arg = arg + offset;
// Note: compiler error if we try to modify offset
std::cout << ": " << arg << std::endl;
} );
// Allow offset to be modified inside the lambda via 'mutable'
// (lambda's copy is modified, NOT the outer)
ForEach( data, [offset](auto &arg) mutable {
std::cout << "doing " << arg;
arg = arg + offset;
offset += 10;
std::cout << ": " << arg << " (offset increases: " << offset << ") " << std::endl;
} );
std::cout << " offset is still 10: " << offset << std::endl;
// Capture offset by reference
ForEach( data, [&offset](auto &arg) {
std::cout << "doing " << arg;
arg = arg + offset;
offset += 10;
std::cout << ": " << arg << " (offset increases: " << offset << ") " << std::endl;
} );
std::cout << "outer offset is now 60: " << offset << std::endl;
}
int main()
{
// define and invoke a lambda
[]() {
std::cout << "Lambda invoked via ()" << std::endl;
}(); // invoke via operator()
// invoke lambda via name
auto myFn = []() {
std::cout << "Lambda invoked via name" << std::endl;
};
myFn(); // invoke
// No need to specify return type
auto test1 = []( int x, int y) {
return x+y;
}(6,7);
std::cout << "Lambda single return type, returned "<< test1 << std::endl;
// No need to specify return type
auto test2 = []( int x, int y)->int{ // compile error if no ->int
if( x > 5 )
return x+y+2.0f; // force to int by return type above
return x+y;
}(6,7);
std::cout << "Lambda two return types, returned "<< test2 << std::endl;
TestCaptureList();
return 0;
} | true |
2837aaf6ff0d52e945ef71229eb634d20ff49d1f | C++ | Skorpi08/SX1278_PCF8574 | /Examples/TX_LoRa/TX_LoRa.ino | UTF-8 | 2,641 | 2.734375 | 3 | [] | no_license | #include "SX1278.h"
#include <SPI.h>
#define LORA_MODE 4
#define LORA_CHANNEL CH_6_BW_125
#define LORA_ADDRESS 2
#define LORA_SEND_TO_ADDRESS 4
#define LORA_LED 9
int e;
char message1 [] = "Packet 1, wanting to see if received packet is the same as sent packet";
char message2 [] = "Packet 2, broadcast test";
void setup()
{
pinMode(LORA_LED, OUTPUT);
// Open serial communications and wait for port to open:
Serial.begin(9600);
// Print a start message
Serial.println(F("sx1278 module and Arduino: send two packets (One to an addrees and another one in broadcast)"));
// Power ON the module
if (sx1278.ON() == 0) {
Serial.println(F("Setting power ON: SUCCESS "));
} else {
Serial.println(F("Setting power ON: ERROR "));
}
// Set transmission mode and print the result
if (sx1278.setMode(LORA_MODE) == 0) {
Serial.println(F("Setting Mode: SUCCESS "));
} else {
Serial.println(F("Setting Mode: ERROR "));
}
// Set header
if (sx1278.setHeaderON() == 0) {
Serial.println(F("Setting Header ON: SUCCESS "));
} else {
Serial.println(F("Setting Header ON: ERROR "));
}
// Select frequency channel
if (sx1278.setChannel(LORA_CHANNEL) == 0) {
Serial.println(F("Setting Channel: SUCCESS "));
} else {
Serial.println(F("Setting Channel: ERROR "));
}
// Set CRC
if (sx1278.setCRC_ON() == 0) {
Serial.println(F("Setting CRC ON: SUCCESS "));
} else {
Serial.println(F("Setting CRC ON: ERROR "));
}
// Select output power (Max, High, Intermediate or Low)
if (sx1278.setPower('M') == 0) {
Serial.println(F("Setting Power: SUCCESS "));
} else {
Serial.println(F("Setting Power: ERROR "));
}
// Set the node address and print the result
if (sx1278.setNodeAddress(LORA_ADDRESS) == 0) {
Serial.println(F("Setting node address: SUCCESS "));
} else {
Serial.println(F("Setting node address: ERROR "));
}
// Print a success message
Serial.println(F("sx1278 configured finished"));
Serial.println();
}
void loop(void)
{
// Send message1 and print the result
e = sx1278.sendPacketTimeout(LORA_SEND_TO_ADDRESS, message1);
Serial.print(F("Packet sent, state "));
Serial.println(e, DEC);
if (e == 0) {
digitalWrite(LORA_LED, HIGH);
delay(500);
digitalWrite(LORA_LED, LOW);
}
delay(4000);
// Send message2 broadcast and print the result
e = sx1278.sendPacketTimeout(0, message2);
Serial.print(F("Packet sent, state "));
Serial.println(e, DEC);
if (e == 0) {
digitalWrite(LORA_LED, HIGH);
delay(500);
digitalWrite(LORA_LED, LOW);
}
delay(4000);
}
| true |
49ae5c553ca5bdd2259a0905910d4883e791176f | C++ | eBay/Gringofts | /src/infra/util/IdGenerator.h | UTF-8 | 1,997 | 2.6875 | 3 | [
"Apache-2.0",
"OpenSSL",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /************************************************************************
Copyright 2019-2020 eBay Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**************************************************************************/
#ifndef SRC_INFRA_UTIL_IDGENERATOR_H_
#define SRC_INFRA_UTIL_IDGENERATOR_H_
#include <atomic>
#include "../common_types.h"
namespace gringofts {
/**
* An util class to generate monotonically increasing id.
* Strict incremental id is not guaranteed.
* Thread safety is also not guaranteed. Please confine the usage to one thread or use lock.
*/
class IdGenerator final {
public:
IdGenerator();
~IdGenerator() = default;
/**
* Get the next available id
* @return next available id
*/
Id getNextId() {
mCurrentId += 1;
return mCurrentId;
}
/**
* Get the current highest id which is used
* @return current highest id which is used
*/
Id getCurrentId() const {
return mCurrentId;
}
/**
* Set the current highest id which is used. This function has two use scenarios:
* 1. During class initialization
* 2. During application recovery, when the last used id will be loaded from command/event store
* @param id the new highest id which is used
* @throw runtime_error if \p id is smaller than current highest id
*/
void setCurrentId(const Id id);
private:
/**
* The current highest id which has been used
*/
std::atomic<Id> mCurrentId;
};
} /// namespace gringofts
#endif // SRC_INFRA_UTIL_IDGENERATOR_H_
| true |
d7b18d22c183d2ed47cf2c60043aafb1ff29a4ce | C++ | githublizhipan/Practice | /PAT/AdvancedLevel/1001.A+BFormat.cpp | UTF-8 | 798 | 2.671875 | 3 | [] | no_license | /*************************************************************************
> File Name: 1001.A+BFormat.cpp
> Author: lzp
> Mail:
> Created Time: Sat Oct 17 19:02:52 2020
> Source:
************************************************************************/
#include <iostream>
using namespace std;
int a, b, num[10];
int main() {
cin >> a >> b;
a += b;
if (a < 0) {
a *= -1;
cout << "-";
}
while (a >= 1000) {
num[++num[0]] = a % 1000;
a /= 1000;
}
num[++num[0]] = a;
cout << num[num[0]];
for (int i = num[0] - 1; i >= 1; i--) {
cout << ",";
if (num[i] < 10) cout << "00" << num[i];
else if (num[i] < 100) cout << "0" << num[i];
else cout << num[i];
}
cout << endl;
return 0;
}
| true |
9c63a1100523dd84ba42ef392ff7ae215af00c2b | C++ | eveonline96/offer_solve | /offer46.cpp | UTF-8 | 1,998 | 3.03125 | 3 | [] | no_license | #include <string.h>
#include <vector>
#include <stack>
#include <set>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
/*
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。
HF作为牛客的资深元老,自然也准备了一些小游戏。
其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。
然后,他随机指定一个数m,让编号为0的小朋友开始报数。
每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,
并且不再回到圈中,从他的下一个小朋友开始,
继续0...m-1报数....这样下去....直到剩下最后一个小朋友,
可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。
请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
约瑟夫问题
递推公式
让f[i]为i个人玩游戏报m退出最后的胜利者的编号,最后的结果自然是f[n]
服了
f[1] = 0;
f[i] = (f[i - 1] + m) mod i;
时间复杂度O(N),空间复杂度O(1)
*/
class Solution {
public:
//错误顺序
// int LastRemaining_Solution(int n, int m)
// {
// if(n==0) return -1;
// int s=0;
// for(int i=n;i>=2;i--)
// s=(s+m)%i;
// return s;
// }
int LastRemaining_Solution1(int n, int m)
{
if(n==0) return -1;
if(n==1) return 0;
int s=0;
for(int i=2;i<=n;i++)
s=(s+m)%i;
return s;
}
int LastRemaining_Solution(int n,int m)
{
if(n==0)
return -1;
if(n==1)
return 0;
else
{
return (LastRemaining_Solution(n-1,m)+m)%n;
}
}
};
int main(int argc, char const *argv[])
{
Solution s1;
int res=s1.LastRemaining_Solution(3,2);
int res1=s1.LastRemaining_Solution1(3,2);
cout<<res<<endl<<res1<<endl;
return 0;
}
| true |
ae049d0ee05801bd387e101e58e63b9c9fafc262 | C++ | Xia-Jialin/refactoring | /code/cpp/original/Rental.h | UTF-8 | 238 | 2.5625 | 3 | [] | no_license | #ifndef RENTAL_H_
#define RENTAL_H_
struct Movie;
struct Rental
{
Rental(const Movie* movie, const int daysRented);
int getDaysRented() const;
const Movie& getMovie() const;
private:
const Movie* movie;
int daysRented;
};
#endif
| true |
9c0e90c96b47410d89970806956b9e381d97f80f | C++ | HamzaKhan9/basic-module | /TEST/cube.cpp | UTF-8 | 1,069 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a , b , c , d;
double f , g, h , i , j , k , l , m , n , p , r , s , t , u;
double c1x1 , c1x2 , c1x3 , c2x1 , c2x2 , c2x3 , c3x1 , c3x2 , c3x3;
cout << "ENTER CO-EFFICIENT a: "; cin >> a;
cout << "ENTER CO-EFFICIENT b: "; cin >> b;
cout << "ENTER CO-EFFICIENT c: "; cin >> c;
cout << "ENTER CONSTANT d: "; cin >> d;
//ALL THE SUPPOSIONS ARE DONE HERE;
f=((3*c/a)-(pow(b,2)/pow(a,2)))/3;
g=((2*pow(b,3)/pow(a,3))-(9*b*c/pow(a,2))+(27*d/a))/27;
h=(pow(g,2)/4)+(pow(f,3)/27);
i=sqrt((pow(g,2)/4)-h);
j=cbrt(i);
k=acos(-(g/(2*i)));
l=j*(-1);
m=cos(k/3);
n=sqrt(3)*sin(k/3);
p=(b/(3*a))*(-1);
r=-(g/2)+(pow(h,0.5));
s=cbrt(r);
t=-(g/2)-sqrt(h);
u=cbrt(t);
c1x1=(2*j*(cos(k/3)))-(b/(3*a));
c1x2=l*(m+n)+p;
c1x3=l*(m-n)+p;
c2x1=(s+u)-(b/(3*a));
c3x1=cbrt(d/a)*(-1);
c3x2=c3x1;
c3x3=c3x1;
cout << endl;
cout << f << endl << g << endl << h << endl << c3x1;
return 0;
}
| true |
612c084198fe2fdf18ea6ee004e334a1e36ab4d6 | C++ | balaam/dinodeck | /src/Sprite.h | UTF-8 | 995 | 2.65625 | 3 | [
"MIT"
] | permissive | #ifndef SPRITE_H
#define SPRITE_H
#include "reflect/Reflect.h"
#include "Vector.h"
class LuaState;
class Texture;
class Sprite
{
public: static Reflect Meta;
public:
Texture* texture;
Vector colour;
Vector position;
Vector scale;
double topLeftU;
double topLeftV;
double bottomRightU;
double bottomRightV;
double rotation; // degrees
static void Bind(LuaState* state);
Sprite() { Init(); }
void Init();
void Init(const Sprite&);
void SetPosition(const Vector&);
void SetPosition(double x, double y);
const Vector& GetPosition() const { return position; };
void SetTexture(Texture*);
void SetUVs(double topLeftU, double topLeftV, double bottomRightU, double bottomRightV);
double GetRotation() const { return rotation; }
void SetRotation(double value) { rotation = value; }
};
#endif | true |
6d44a095dafd93c5e7470728ff419e1d902559c7 | C++ | F3bbbo/TE2502MasterThesis | /GPU_LCT/GPU_LCT/data_structures.hpp | UTF-8 | 859 | 2.828125 | 3 | [] | no_license | #pragma once
#ifndef DATA_STRUCTURES_HPP
#define DATA_STRUCTURES_HPP
#include <glm/glm.hpp>
namespace CPU
{
struct SymEdge
{
SymEdge* nxt = nullptr;
SymEdge* rot = nullptr;
int vertex;
int edge;
int face;
SymEdge* sym() { return this->nxt->rot; };
SymEdge* crot() { return (this->sym() != nullptr) ? this->sym()->nxt : nullptr; };
SymEdge* prev() { return this->nxt->nxt; };
};
struct VertexRef
{
glm::vec2 vertice;
int ref_counter;
};
struct Edge
{
glm::ivec2 edge;
std::vector<int> constraint_ref;
};
struct Face
{
glm::ivec3 vert_i;
unsigned int explored = 0; //number indicating last iteration being explored
};
enum class LocateType {
VERTEX,
EDGE,
FACE,
NEXT,
NONE
};
struct LocateRes {
int hit_index = -1;
SymEdge* sym_edge = nullptr;
LocateType type = LocateType::NONE;
};
}
#endif | true |
0da6ef8154acfbcf37d8ebf4ec93ccb6c42143ae | C++ | lyell/aegis | /src/agt/agtg/agtg_texture.cpp | UTF-8 | 803 | 2.734375 | 3 | [] | no_license | #include <agtg_texture.h>
#include <agtg_gl.h>
namespace agtg {
Texture::Texture(std::shared_ptr<agtr::Image> image)
: m_width(image && image->size().width()),
m_height(image && image->size().height())
{
glGenTextures(1, &m_textureId);
glBindTexture(GL_TEXTURE_2D, m_textureId);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &((*image->data())[0]));
}
Texture::~Texture()
{
glDeleteTextures(1, &m_textureId);
}
GLuint Texture::id() const
{
return m_textureId;
}
GLsizei Texture::width() const
{
return m_width;
}
GLsizei Texture::height() const
{
return m_height;
}
} // namespace
| true |
d1d224b1ce1a61d0a431fff2180f102106a1c218 | C++ | shybovycha/sse-optimizations | /1-basics/main.cpp | UTF-8 | 1,380 | 2.703125 | 3 | [] | no_license | #include <xmmintrin.h>
#include <format>
#include <iostream>
#include <cstdio>
int main() {
auto f1 = std::make_unique<float[]>(4);
auto f2 = std::make_unique<float[]>(4);
auto f3 = std::make_unique<float[]>(4);
auto f4 = std::make_unique<float[]>(4);
auto f0 = 0.0f;
auto t0 = _mm_set_ps(4.0, 3.0, 2.0, 1.0);
_mm_store_ps(f1.get(), t0);
std::cout << std::format("t0 = [{:.4f}, {:.4f}, {:.4f}, {:.4f}]\n", f1[3], f1[2], f1[1], f1[0]);
_mm_store_ss(&f0, t0); // copy the lower scalar (32 bits) from t0 to f1
std::cout << std::format("f0 = {:.4f}\n", f0);
auto t1 = _mm_set1_ps(3.5); // store 3.5 in all elements of t1
_mm_store_ps(f2.get(), t1); // copy t1 to buffer f2
std::cout << std::format("t1 = [{:.4f}, {:.4f}, {:.4f}, {:.4f}]\n", f2[3], f2[2], f2[1], f2[0]);
_mm_store_ss(&f0, t1); // copy the lower scalar (32 bits) from t1 to f0
std::cout << std::format("f0 = {:.4f}\n", f0);
auto t2 = _mm_set1_ps(2.7); // store 2.7 in t2
_mm_store_ps(f3.get(), t2); // copy t2 to buffer f3
std::cout << std::format("t2 = [{:.4f}, {:.4f}, {:.4f}, {:.4f}]\n", f3[3], f3[2], f3[1], f3[0]);
auto t3 = _mm_setzero_ps(); // zero-out t3
_mm_store_ps(f4.get(), t3); // store t3 in f4
std::cout << std::format("t3 = [{:.4f}, {:.4f}, {:.4f}, {:.4f}]\n", f4[3], f4[2], f4[1], f4[0]);
return 0;
}
| true |
dcf1059c9de53bc3f7c34a01931fd9b23d6e7f4c | C++ | MadG-42/WGU-C867-Class-Roster | /Roster.h | UTF-8 | 813 | 2.875 | 3 | [] | no_license | #pragma once
#include "Student.h"
using namespace std;
class Roster
{
public:
Roster();
~Roster();
void add(string studentID,
string firstName,
string lastName,
string emailAddress,
int age,
int daysInCourse1,
int daysInCourse2,
int daysInCourse3,
DegreeProgram degreeprogram);
void remove(string studentID);
void printAll();
void printAverageDaysInCourse(string studentID);
void printInvalidEmails();
void printByDegreeProgram(DegreeProgram);
void printByDegreeProgram();
string getSID(int studentNo);
private:
const int MAX_COURSES = 3;
const int ROSTER_SIZE = 5;
Student* classRosterArray[5] = { nullptr,
nullptr,
nullptr,
nullptr,
nullptr };
}; | true |
b9fc1540e8870daa60de0bfc985a8644487d038e | C++ | EXANewbie/Pro.Forest | /ForestProj/Client/Receiver.cpp | UTF-8 | 2,183 | 2.703125 | 3 | [] | no_license | #include <WinSock2.h>
#include <memory>
#include "cmap.h"
#include "mmap.h"
#include "types.h"
void Handler_PSET_USER(int *myID, std::string* str);
void Handler_PINIT(int* myID, Character *myChar, std::string* str);
void Handler_PMOVE_USER(int *myID, std::string* str);
void Handler_PERASE_USER(int *myID, std::string* str);
void Handler_PSET_MON(int *myID, std::string* str);
void Handler_PERASE_MON(int *myID, std::string* str);
void Handler_PUSER_ATTCK_RESULT(int *myID, std::string* str);
void Handler_PUSER_SET_LV(int *myID, std::string* str);
void Handler_PUSER_SET_EXP(int *myID, std::string* str);
void Handler_PMONSTER_ATTACK_RESULT(int *myID, std::string* str);
struct deleter {
void operator()(char *c){ delete[]c; }
};
void receiver(const SOCKET s, int* myID, Character* myChar)
{
SYNCHED_CHARACTER_MAP* chars = SYNCHED_CHARACTER_MAP::getInstance();
SYNCHED_MONSTER_MAP* mons = SYNCHED_MONSTER_MAP::getInstance();
char *buf;
TYPE type;
int len;
while (true)
{
int chk = recv(s, (char*)&type, sizeof(int), 0);
if (chk != sizeof(int)) {
printf("disconnected\n");
break;
}
int chk2=recv(s, (char*)&len, sizeof(int), 0);
std::shared_ptr <char> ptr(new char[len], deleter());
int inc = 0;
do
{
int end = recv(s, ptr.get()+inc, len-inc, 0);
inc += end;
} while (inc < len);
std::string tmp(ptr.get(), len);
if (type == PSET_USER)
{
Handler_PSET_USER(myID, &tmp);
}
else if (type == PINIT)
{
Handler_PINIT(myID, myChar, &tmp);
}
else if (type == PMOVE_USER)
{
Handler_PMOVE_USER(myID, &tmp);
}
else if (type == PERASE_USER)
{
Handler_PERASE_USER(myID, &tmp);
}
else if (type == PSET_MON)
{
Handler_PSET_MON(myID, &tmp);
}
else if (type == PERASE_MON)
{
Handler_PERASE_MON(myID, &tmp);
}
else if (type == PUSER_ATTCK_RESULT)
{
Handler_PUSER_ATTCK_RESULT(myID, &tmp);
}
else if (type == PUSER_SET_LV)
{
Handler_PUSER_SET_LV(myID, &tmp);
}
else if (type == PUSER_SET_EXP)
{
Handler_PUSER_SET_EXP(myID, &tmp);
}
else if (type == PMONSTER_ATTACK_RESULT)
{
//내일할 곳.
Handler_PMONSTER_ATTACK_RESULT(myID, &tmp);
}
tmp.clear();
}
} | true |
31c390c3b99685c037e62e810238f8f373822f54 | C++ | jj4jj/cxxtemplates | /src/xctmp_utils.hpp | UTF-8 | 849 | 3.140625 | 3 | [
"MIT"
] | permissive | #include <string>
inline int
_strtrim(std::string & str, const char * trimchar = " \t\r\n"){
auto begmatch = str.begin();
int count = 0; //erase first not of trimchar
while (begmatch != str.end()){
if (strchr(trimchar, *begmatch)){
++begmatch;
++count;
}
break;
}
if (str.begin() < begmatch){
str.erase(str.begin(), begmatch);
}
//
auto rbegmatch = str.end();
while (rbegmatch != str.begin()){
if (strchr(trimchar, *rbegmatch)){
--rbegmatch;
++count;
}
break;
}
if (rbegmatch != str.end()){
str.erase(rbegmatch + 1, str.end());
}
return count;
}
inline void
_strreplace(std::string & ts, const std::string & p, const std::string & v){
auto beg = 0;
auto fnd = ts.find(p, beg);
while (fnd != std::string::npos){
ts.replace(fnd, p.length(), v);
beg = fnd + v.length();
fnd = ts.find(p, beg);
}
}
| true |
06505f93153259f1843e9cfd09ce3a0ca7bb9e09 | C++ | ppff/Cubicle-GUI | /simulator/memoireinterne.h | UTF-8 | 1,255 | 2.71875 | 3 | [] | no_license | #ifndef MEMOIREINTERNE_H
#define MEMOIREINTERNE_H
#include "global.h"
#include "groupe.h"
#include "motif.h"
/* Description :
* Cette classe permet de manipuler les groupes et motifs stockés dans le cube.
*/
class MemoireInterne : public QObject
{
Q_OBJECT
public:
explicit MemoireInterne(QList<Groupe> const& groupes, QObject *parent = 0);
inline Groupe groupe_actuel() const
{
return _groupes.at(_groupeActuel);
}
inline Motif motif_actuel() const
{
return groupe_actuel().motif_actuel();
}
void demarrer();
private:
void envoyer_points();
void envoyer_noms();
QString generer_nom(unsigned numero, unsigned max) const;
QList<Groupe> _groupes;
int _groupeActuel;
signals:
void nouveaux_points(QList<QVector3D> const& points);
void nom_groupe(QString const& numero, QString const& nom);
void nom_motif(QString const& numero, QString const& nom);
public slots:
void groupe_suivant();
void groupe_precedent();
void motif_suivant();
void motif_precedent();
void translater(Translations sens);
};
#endif // MEMOIREINTERNE_H
| true |
d6f2bf99a370e6fb695c3823c97568a6f12c578f | C++ | HaoYang0123/LeetCode | /Filling_Bookcase_Shelves.cpp | UTF-8 | 1,048 | 3.34375 | 3 | [] | no_license | //Leetcode 1105
//动态规划,时间复杂度是O(N^2)
class Solution {
public:
int minHeightShelves(vector<vector<int>>& books, int shelf_width) {
int n=books.size();
vector<int> dp(n+1, INT_MAX); //dp[i]表示放置books[0-i]所需的最小高度
dp[0] = 0;
for(int i=1;i<=n;++i) {
int w=0, h=0; //w表示当前层放置书的宽度,h表示当前层最高书的高度
for(int j=i;j>0&&w+books[j-1][0]<=shelf_width;--j) {
//w+books[j-1]表示books[j-1]可以放在该层上
w += books[j-1][0];
h = max(h, books[j-1][1]);
dp[i] = min(dp[i], dp[j-1]+h);
}
//cout<<i<<"\t"<<dp[i]<<endl;
//最后w+books[j-1][0]>shelf_width才会退出for循环,也即books[j-(i-1)]这些书可以被放在同一层
//枚举这些书找到最小的放置方法:
//dp[i] = min(dp[i], dp[j-1]+h),表示将books[j-1]放置在上一层
}
return dp[n];
}
};
| true |
80f782176c28485f368ff6e589e0012d61acc05c | C++ | bramblex/blxcpp | /Async.hpp | UTF-8 | 4,009 | 2.75 | 3 | [] | no_license | // Async.hpp
#ifndef BLXCPP_ASYNC_HPP
#define BLXCPP_ASYNC_HPP
#include "function_traits.hpp"
#include "Timer.hpp"
#include "ThreadPool.hpp"
#include <thread>
#include <atomic>
#include <mutex>
#include <queue>
#include <csignal>
#include <chrono>
#include <map>
#include <iostream>
namespace blxcpp {
class AsyncEventLoop {
public:
class Event {
private:
std::function<void()> m_func;
public:
Event() { }
Event(const std::function<void()>& func)
: m_func(func) { }
void operator()() { m_func(); }
};
template <typename Func>
class Async;
template <typename Arg, typename Ret>
class Continuation;
private:
std::mutex m_queue_lock;
std::deque<Event> m_queue;
ThreadPool m_thread_pool;
Timer m_timer;
public:
template<typename Func>
inline Async<typename function_traits<Func>::function_type> async(const Func& func) {
return Async<typename function_traits<Func>::function_type>(this, func);
}
void epoll();
void epoll(int64_t interval, const std::function<bool()>& stop);
void pushEvent(const Event& event);
void pushNextTick(const Event& event);
Timer::Ref setTimeout(Timer::Time t, const std::function<void()>& func);
Timer::Ref setInterval(Timer::Time t, const std::function<void()>& func);
private:
static AsyncEventLoop* global;
public:
static std::sig_atomic_t singal;
static AsyncEventLoop *getGlobal();
};
template <typename Ret, typename ...Args>
class AsyncEventLoop::Async<Ret(Args...)> {
public:
template<typename, typename Arg>
struct MakeCallback {
using type = void(Arg);
};
template<typename IGNORE>
struct MakeCallback<IGNORE, void> {
using type = void();
};
using Callback = std::function<typename MakeCallback<void, Ret>::type>;
using Func = std::function<Ret(Args...)>;
private:
AsyncEventLoop* m_event_loop;
std::function<Ret(Args...)> m_func;
template<typename, bool EmptyReturn>
struct Runer;
template<typename IGNORE>
struct Runer<IGNORE, true> {
static void run(AsyncEventLoop* event_loop, const Func& func, const Callback& callback, Args... args){
event_loop->m_thread_pool.put(std::bind([event_loop, func, callback](Args... args){
func(std::forward<Args>(args)...);
Event event = callback;
event_loop->pushEvent(event);
}, std::forward<Args>(args)...));
}
};
template<typename IGNORE>
struct Runer<IGNORE, false> {
static void run(AsyncEventLoop* event_loop, const Func& func, const Callback& callback, Args... args){
event_loop->m_thread_pool.put(std::bind([event_loop, func, callback](Args... args){
Event event = std::function<void()>(std::bind(callback, func(std::forward<Args>(args)...)));
event_loop->pushEvent(event);
}, std::forward<Args>(args)...));
}
};
public:
Async(AsyncEventLoop* event_loop, const std::function<Ret(Args...)>& func)
: m_event_loop(event_loop), m_func(func) { }
void operator()(Args... args, const Callback& callback) {
auto func = m_func;
AsyncEventLoop* event_loop = m_event_loop;
Runer<void, std::is_same<Ret, void>::value>::run(event_loop, func, callback, std::forward<Args>(args)...);
}
void operator()(Args... args) {
m_event_loop->m_thread_pool.put(std::bind(m_func, std::forward<Args>(args)...));
}
Ret sync(Args... args) {
return m_func(std::forward<Args>(args)...);
}
};
template<typename Func>
auto async(const Func& func) -> decltype (AsyncEventLoop::getGlobal()->async(func)) {
return AsyncEventLoop::getGlobal()->async(func);
}
Timer::Ref setTimeout(Timer::Time t, const std::function<void()>& func);
Timer::Ref setInterval(Timer::Time t, const std::function<void()>& func);
void eventLoop();
}
#endif // BLXCPP_ASYNC_HPP
| true |
873b0a715b2b82d0bbdffb5d610344b914541253 | C++ | IvanMerejko/Translator | /Translator/TreeElements/Program.cpp | UTF-8 | 2,684 | 2.984375 | 3 | [] | no_license | //
// Created by Ivan on 13.02.2020.
//
#include <iostream>
#include <iomanip>
#include "Program.h"
#include "../Common/Constants.h"
#include "../Common/ParsingException.h"
Program::Program(const Context& context)
: BaseTreeElement{context}
, m_block{context}
, m_params{}
{}
void Program::operator()(const TokensInfoVector& tokens, int& currentToken)
{
if(!checkStart(tokens, currentToken))
{
utils::ThrowException(MustBeProgramString, tokens, currentToken);
}
m_params.m_start = tokens[currentToken++];
if(!checkIdentifier(tokens, currentToken))
{
utils::ThrowException(MustBeIdentifierString, tokens, currentToken);
}
m_params.m_procedureIdentifier = tokens[currentToken++];
if(!checkSeparator(tokens, currentToken))
{
utils::ThrowException(MustBeSemicolonString, tokens, currentToken);
}
m_params.m_symbol = tokens[currentToken++];
m_block(tokens, currentToken);
}
bool Program::checkStart(const TokensInfoVector& tokens, int& currentToken) const
{
const auto& keywords = m_context.GetKeywords();
const auto& number = keywords.find(ProgramString)->second;
const auto& [tokenName, tokenNumber, line, column] = tokens[currentToken];
return number == tokenNumber;
}
bool Program::checkIdentifier(const TokensInfoVector& tokens, int& currentToken) const
{
const auto& identifiers = m_context.GetIdentifiers();
const auto& [tokenName, tokenNumber, line, column] = tokens[currentToken];
return identifiers.find(tokenName) != identifiers.end();
}
bool Program::checkSeparator(const TokensInfoVector& tokens, int& currentToken) const
{
const auto& [tokenName, tokenNumber, line, column] = tokens[currentToken];
return tokenName == ";";
}
void Program::Print(int step)
{
utils::PrintSeparator(step);
step += 3;
std::cout << "<program>\n";
if(m_params.m_start)
{
const auto& [tokenName, tokenNumber, line, column] = *m_params.m_start;
utils::PrintSeparator(step);
std::cout << tokenNumber << " " << tokenName << '\n';
}
else
{
return;
}
if(m_params.m_procedureIdentifier)
{
const auto& [tokenName, tokenNumber, line, column] = *m_params.m_procedureIdentifier;
utils::PrintProcedureIdentifier(step, tokenNumber, tokenName);
}
else
{
return;
}
if(m_params.m_symbol)
{
const auto& [tokenName, tokenNumber, line, column] = *m_params.m_symbol;
utils::PrintSeparator(step);
std::cout << tokenNumber << " " << tokenName << '\n';
step -= 3;
}
else
{
return;
}
m_block.Print(step+3);
} | true |
e2d9291e450d18d0ec46fd6e9c0730891e68b714 | C++ | PhilCK/terminal-wired | /code/core/world/world.hpp | UTF-8 | 539 | 2.875 | 3 | [] | no_license | #ifndef WORLD_INCLUDED_7C5C8ED7_388E_43C0_93C2_B12DA9F1FC18
#define WORLD_INCLUDED_7C5C8ED7_388E_43C0_93C2_B12DA9F1FC18
#include <stdint.h>
namespace Core {
struct World
{
uint32_t id = 0;
}; // struct
//! Check to see if two entities are exactly the same, type and instance.
inline bool operator==(const World left, const World right)
{
return left.id == right.id;
}
//! For use in containers etc.
inline bool operator<(const World left, const World right)
{
return left.id < right.id;
}
} // ns
#endif // include guard | true |
1e03c24d0ed896e4fb318a0a87c1151f3658f7b5 | C++ | abelvdavid/100DaysofCode | /day3/majorityElement.cpp | UTF-8 | 543 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
class Solution {
public:
int majorityElement(vector<int>& nums)
{
int index = 0;
int count = 1;
for(int i = 1; i<nums.size(); ++i)
{
if(nums[index] == nums[i])
{
count ++;
}
else
count --;
if(count==0)
{
index = i;
count = 1;
}
}
return nums[index];
}
}; | true |
9f0a8a594014e08e59cb1b6d00f6582d8fa425a2 | C++ | Sumelt/Daily-Coding | /数据结构/Set_Map/MapLinkList.h | UTF-8 | 2,554 | 3.578125 | 4 | [] | no_license | #ifndef __MAPLINKLIST__H_
#define __MAPLINKLIST__H_
#include <exception> // std::exception
template<typename K, typename V>
class MapLinkList {
private:
class Node {
friend class MapLinkList<K, V>;
K key;
V val;
Node *next;
public:
Node( K key, V val, Node* next ) {
this->key= key;
this->val = val;
this->next = next;
}
Node( K key, V val ) {
this->key= key;
this->val = val;
this->next = nullptr;
}
Node() {
this->key = K();
this->val= V();
this->next = nullptr;
}
};
Node* getNode( K key );
Node *dummyHead;
int size;
public:
MapLinkList();
~MapLinkList();
void add( K key, V val );
void remove( K key );
bool isEmpty();
bool contain( K key );
int getSize();
V get( K key );
void set( K key, V val );
};
template<typename K, typename V>
MapLinkList<K, V>::MapLinkList() {
dummyHead = new Node();
size = 0;
}
template<typename K, typename V>
MapLinkList<K, V>::~MapLinkList() {
Node *cur = dummyHead;
Node *temp = nullptr;
while( cur != nullptr ) {
temp = cur;
cur = cur->next;
delete temp;
}
}
template<typename K, typename V>
int MapLinkList<K, V>::getSize() {
return size;
}
template<typename K, typename V>
bool MapLinkList<K, V>::isEmpty() {
return size == 0;
}
template<typename K, typename V>
typename MapLinkList<K, V>::Node* MapLinkList<K, V>::getNode( K key ) {
Node *cur = dummyHead->next;
while( cur != nullptr ) {
if( cur->key == key )
return cur;
cur = cur->next;
}
return nullptr;
}
template<typename K, typename V>
bool MapLinkList<K, V>::contain( K key ) {
return ( getNode( key ) != nullptr ? true : false );
}
template<typename K, typename V>
V MapLinkList<K, V>::get( K key ) {
Node *node = getNode( key );
return ( node != nullptr ? node->val : 0 );
}
template<typename K, typename V>
void MapLinkList<K, V>::remove( K key ) {
Node *pre = dummyHead;
while( pre->next != nullptr && pre->next->key != key )
pre = pre->next;
if( pre->next != nullptr && pre->next->key == key ) {
Node *delNode = pre->next;
pre->next = delNode->next;
delete delNode;
--size;
}
}
template<typename K, typename V>
void MapLinkList<K, V>::add( K key, V val ) {
Node *node = getNode( key );
if( !node ) {
dummyHead->next = new Node( key, val, dummyHead->next );
++size;
}
else{
node->val += 1;
}
}
template<typename K, typename V>
void MapLinkList<K, V>::set( K key, V val ) {
Node *node = getNode( key );
if( node )
node->val = val;
else throw ( std::exception() );
}
#endif | true |
5224e61eb729c2754218802d5c3e27cb6c555594 | C++ | leozlee/video | /example/example01/display.cpp | UTF-8 | 1,422 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
#include <unistd.h>
#include "common.h"
#include "display.h"
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;
//The image we will load and show on the screen
SDL_Surface* gHelloWorld = NULL;
bool sdl_init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create window
gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
IMAGEWIDTH, IMAGEHEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Get window surface
gScreenSurface = SDL_GetWindowSurface( gWindow );
}
}
return success;
}
bool loadMedia(char *file)
{
//Loading success flag
bool success = true;
//Load splash image
gHelloWorld = SDL_LoadBMP(file);
if( gHelloWorld == NULL )
{
printf( "Unable to load image %s! SDL Error: %s\n", file, SDL_GetError() );
success = false;
}
return success;
}
void sdl_close()
{
//Deallocate surface
SDL_FreeSurface( gHelloWorld );
gHelloWorld = NULL;
//Destroy window
SDL_DestroyWindow( gWindow );
gWindow = NULL;
//Quit SDL subsystems
SDL_Quit();
} | true |
d1c64b4ae7b1d07d6bd5610af9b8012c61aeda10 | C++ | Ninjaws/JellyGame | /SFML/Jelly/PauseScreen.cpp | UTF-8 | 3,659 | 2.890625 | 3 | [] | no_license | #include "PauseScreen.h"
PauseScreen::PauseScreen()
{
}
PauseScreen::~PauseScreen()
{
}
void PauseScreen::SetPauseScreenBackground(sf::Color color, float width, float height)
{
sf::Vector2f screenDimensions;
screenDimensions.x = GetWindow().getSize().x;
screenDimensions.y = GetWindow().getSize().y;
//pauseScreenTexture.loadFromFile(texturelocation);
//pauseScreenBackground.setTexture(&pauseScreenTexture);
pauseScreenBackground.setFillColor(color);
//pauseScreenBackground.setFillColor(sf::Color::Transparent);
pauseScreenBackground.setSize(screenDimensions);
//pauseScreenBackground.setPosition((GetWindow().getSize().x / 2) - (screenDimensions.x / 2), (GetWindow().getSize().y / 2) - (screenDimensions.y / 2));
std::cout << "Pausescreen background loaded" << std::endl;
}
void PauseScreen::SetPauseFont(std::string fontlocation)
{
pauseFont.loadFromFile(fontlocation);
}
void PauseScreen::SetPauseButtons(sf::Color selected, sf::Color other, float textsize, unsigned int numberofbuttons)
{
selectedButton = selected;
otherButtons = other;
sf::Text text;
for (int i = 0; i < numberofbuttons; i++)
{
pauseText.push_back(text);
pauseText[i].setCharacterSize(textsize);
pauseText[i].setFont(pauseFont);
pauseText[i].setColor(otherButtons);
}
pauseText[0].setColor(selectedButton);
pauseText[0].setString("Continue");
pauseText[1].setString("Save Game");
pauseText[2].setString("Quit to Main Menu");
pauseText[3].setString("Quit to Desktop");
selectedItemIndex = 0;
}
void PauseScreen::DrawPauseScreenBackground()
{
sf::Vector2i pixel_pos = sf::Vector2i(0, 0);
sf::Vector2f coord_pos = GetWindow().mapPixelToCoords(pixel_pos);
pauseScreenBackground.setPosition(coord_pos);
GetWindow().draw(pauseScreenBackground);
}
void PauseScreen::DrawPauseButtons()
{
for (int i = 0; i < pauseText.size(); i++)
{
sf::Vector2i pixel_pos = sf::Vector2i(GetScreenWidth() / 2 - GetScreenWidth() / 8, GetScreenHeight() / (pauseText.size() + 1) * i + (GetScreenHeight() / 6));
sf::Vector2f coord_pos = GetWindow().mapPixelToCoords(pixel_pos);
pauseText[i].setPosition(coord_pos);
GetWindow().draw(pauseText[i]);
}
}
void PauseScreen::MoveUp()
{
if (selectedItemIndex - 1 >= 0)
{
pauseText[selectedItemIndex].setColor(otherButtons);
selectedItemIndex--;
pauseText[selectedItemIndex].setColor(selectedButton);
}
}
void PauseScreen::MoveDown()
{
if (selectedItemIndex + 1 < pauseText.size())
{
pauseText[selectedItemIndex].setColor(otherButtons);
selectedItemIndex++;
pauseText[selectedItemIndex].setColor(selectedButton);
}
}
void PauseScreen::PauseMovementInput()
{
if (buttonTimer.getElapsedTime().asSeconds() >= GetFrameRate() * 6)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
MoveUp();
buttonTimer.restart();
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
MoveDown();
buttonTimer.restart();
}
}
}
void PauseScreen::PauseButtonSelecting()
{
if (sf::Keyboard::isKeyPressed(GetSelectingKey()))
{
if (selectedItemIndex == 0)
{
SetState(State_GameScreen);
PlayGameMusic();
DisplayState("GameScreen");
}
else if (selectedItemIndex == 1)
{
SaveGame();
}
else if (selectedItemIndex == 2)
{
switchTimer.restart();
while (true)
{
if (switchTimer.getElapsedTime().asSeconds() >= GetStateSwitchingRate())
{
break;
}
}
SetState(State_MainScreen);
StopGameMusic();
PlayMainMusic();
DisplayState("MainScreen");
}
else if (selectedItemIndex == 3)
{
GetWindow().close();
}
}
} | true |