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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f57f6575328c80c8c9c409a3581cc9282d6ff4c3 | C++ | edumargra/CGI | /MartinGraells_SolaRoca_Raytracer2/Code/shapes/sphere.h | UTF-8 | 515 | 2.71875 | 3 | [
"MIT"
] | permissive | #ifndef SPHERE_H_
#define SPHERE_H_
#include "../object.h"
class Sphere: public Object
{
public:
Sphere(Point const &pos, double radius);
Sphere(Point const &pos, double radius,double angle,Vector const &axis);
virtual Hit intersect(Ray const &ray);
virtual std::vector<float> UVcoord(Vector v);
Vector applyRotation(Vector v);
Point const position;
double const r;
double const angle = 0;
Vector const axis = Vector(0,0,0);
};
#endif
| true |
aa05fcf411d7fb0d659a00a04e11e6f5d36fa20b | C++ | oliversssf2/opengl | /source/utilities/Shader.h | UTF-8 | 994 | 2.59375 | 3 | [] | no_license | //
// Created by fongsu on 4/3/19.
//
#ifndef OPENGL_SHADER_H
#define OPENGL_SHADER_H
#include<glad/glad.h>;
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Shader {
unsigned int ID;
Shader(const char* vertexPath, const char* fragmentPath);
void use();
void setBool(const std::string &name, bool value) const;
void setInt(const std::string &name, int value) const;
void setFloat(const std::string &name, float value) const;
};
Shader::Shader(const char *vertexPath, const char *fragmentPath)
{
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
std::stringstream vShaderStream, fShaderStream;
vShaderStream << vShaderFile.rdbuf()
}
}
#endif //OPENGL_SHADER_H
| true |
40a505ee57d84cd4137b7f8e2a187f4fa0de7978 | C++ | mmaricic/FilesystemManagement | /projekat2/except.h | UTF-8 | 1,274 | 2.984375 | 3 | [] | no_license | #ifndef _EXCEPT_H
#define _EXCEPT_H
#include <iostream>
using namespace std;
class EInvalidPath {
friend ostream& operator<<(ostream& os, const EInvalidPath& e){
return os << "Invalid path!" << endl;
}
};
class EAliasEmpty {
friend ostream& operator<<(ostream& os, const EAliasEmpty& e){
return os << "Alias is empty!There is no valid file/folder." << endl;
}
};
class EIsParent{
friend ostream& operator<<(ostream& os, const EIsParent& e){
return os << "Can't move folder in his child folder." << endl;
}
};
class EIsChild{
friend ostream& operator<<(ostream& os, const EIsChild& e){
return os << "You can't delete root folder of current working directory" << endl;
}
};
class EInvalidArg{
friend ostream& operator<<(ostream& os, const EInvalidArg& e){
return os << "Invalid source/destination!" << endl;
}
};
class ECopyInSel{
friend ostream& operator<<(ostream& os, const ECopyInSel& e){
return os << "You can't copy in selection!" << endl;
}
};
class Einput{
friend ostream& operator<<(ostream& os, const Einput& e){
return os << "Invalid input" << endl;
}
};
class ENotSelection{
friend ostream& operator<<(ostream& os, const ENotSelection& e){
return os << "There is no selection with the given name" << endl;
}
};
#endif | true |
cade4e000cf5b11aa8d9e82c22603141a329fd8a | C++ | neilharia7/AlgorithmicToolbox | /Week_4_Programming_Assignment_3/inversions.cpp | UTF-8 | 1,124 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define long long long
long inversions = 0;
void Merge(int left[], int right[], int a[], int left_part, int right_part){
int i=0,j=0,k=0;
while((i < left_part) && (j < right_part)){
if(left[i] <= right[j]){
a[k++] = left[i++];
}
else{
a[k++] = right[j++];
inversions += (left_part - i);
}
}
while(i < left_part){
a[k++] = left[i++];
}
while(j < right_part){
a[k++] = right[j++];
}
}
void MSort(int a[], int n){
if(n < 2)
return;
else{
int mid = n/2;
int left[mid];
int right[n - mid];
for(int i = 0; i < mid; i++){
left[i] = a[i];
}
for(int i = mid; i < n; i++){
right[i - mid] = a[i];
}
MSort(left, mid);
MSort(right, n - mid);
Merge(left, right, a, mid, n - mid);
}
}
int main(){
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; i++){
cin >> a[i];
}
MSort(a, n);
cout<<inversions<<endl;
return 0;
}
| true |
cb77b25f50d6e5313482288d5ae59e4e571272b6 | C++ | aayushsinha44/codezilla | /Sorting/Merge Sort/C++/Arrays/MergeSortArrayTest.cpp | UTF-8 | 2,026 | 3.734375 | 4 | [
"MIT"
] | permissive | /*********************************************************************************
* Instructions:
* To compile: g++ MergeSort_ArrayTest.cpp -o MergeSort_ArrayTest -std=c++11
* To run: ./MergeSort_ArrayTest [#elements]
* Where #elements is number of elements in an array, default is 100.
* Author: Mounika Ponugoti
*********************************************************************************/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include "MergeSortArray.h"
// Number of elements in an array
int length = 100;
// Prints the array
template <class T, class N>
void printArray(T *arr, N length) {
for (N i = 0; i < length; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
// Initialize the array with random values
template <class T, class N>
void initializeArray(T *arr, N length) {
for (N i = 0; i < length; i++) {
arr[i] = static_cast <T> (rand()) / static_cast <T> (RAND_MAX/10);
}
}
int main(int argc, char **argv)
{
if (argc == 2) {
length = std::atoi(argv[1]);
}
if (argc > 2) {
std::cout << "Usage: ./main [#elemnts]" << std::endl;
exit(1);
}
// Seed for random number generator
srand(time(NULL));
// Sorting integer Array
int *arr = new int[length];
initializeArray<int, int>(arr, length);
std::cout << "Unsorted Array: " << std::endl;
printArray<int, int>(arr, length);
MergeSortArray<int, int> mergeSort_obj;
mergeSort_obj.mergeSort(arr, length);
std::cout << "Sorted Array: " << std::endl;
printArray(arr, length);
// Sorting floating point numbers
float *arr_f = new float[length];
initializeArray<float, int>(arr_f, length);
std::cout << "Unsorted Array: " << std::endl;
std::cout << std::fixed << std::setprecision(2);
printArray<float, int>(arr_f, length);
MergeSortArray<float, int> mergeSort_obj_2;
mergeSort_obj_2.mergeSort(arr_f, length);
std::cout << "Sorted Array: " << std::endl;
printArray(arr_f, length);
// Free the allocated memory
delete[] arr;
delete[] arr_f;
return 0;
}
| true |
ff9a174c9a864303db98a5c3a542ff56bacfafd9 | C++ | Duanyll/Standard-TLE-Library | /src/other/merge_sort.cpp | UTF-8 | 767 | 3.109375 | 3 | [
"WTFPL"
] | permissive | template <typename T>
void merge_sort(T* a, int l, int r, int& ans, T* tmp) {
if (l == r) return;
int mid = (l + r) >> 1;
merge_sort(a, l, mid);
merge_sort(a, mid + 1, r);
int i = l, j = mid + 1;
int k = l;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++];
} else {
tmp[k++] = a[j++];
ans += mid - i + 1;
}
}
while (i <= mid) {
tmp[k++] = a[i++];
}
while (j <= r) {
tmp[k++] = a[j++];
}
for (int i = l; i <= r; i++) {
a[i] = tmp[i];
}
}
template <typename T>
int merge_sort(T* a, int n) {
auto tmp = new T[n + 10];
int ans = 0;
merge_sort(a, 1, n, ans, tmp);
delete[] tmp;
return ans;
}
| true |
a1fe9d56f2aeaec142b86396fa88b388254f8b62 | C++ | migregal/bmstu-iu7-cg | /lab_04/logic/circle_algs/parametric.cpp | UTF-8 | 665 | 2.78125 | 3 | [
"MIT"
] | permissive | //
// Created by gregory on 24.03.2021.
//
#include <cmath>
#include <utils.h>
#include <parametric.h>
void paramcircle(std::vector<point_t> &dots, const point_t &c, double r,
const color_t &color) {
auto step = 1 / r;
for (auto t = 0.; t <= M_PI_4;) {
tmirrored(dots, {c.x + r * cos(t), c.y + r * sin(t)}, c, color);
t += step;
}
}
void paramellipse(std::vector<point_t> &dots, const point_t &c, double ra,
double rb, const color_t &color) {
auto step = 1 / (ra > rb ? ra : rb);
for (auto t = 0.; t <= M_PI_2;) {
dmirrored(dots, {c.x + ra * cos(t), c.y + rb * sin(t)}, c, color);
t += step;
}
} | true |
241cfa3ef03da89a8b9d015dbb278d314b2256ca | C++ | S-1-T/pascal-c-compiler | /src/main.cpp | UTF-8 | 1,414 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "yacc/p2c.tab.h"
#include "yacc/semantic_analyser.h"
#include "codes/codes_generator.h"
#include <string>
#include <iostream>
#define COMPILE_TO_BIN true
using namespace std;
extern Program *root;
int main(int argc, char *argv[])
{
string fileName;
string noExtendedNameFileName;
// 处理文件名
if (argc != 2)
{
cout << "输入参数无效" << endl;
exit(1);
}
fileName = argv[1];
int pos = fileName.find('.');
if (pos == -1)
{
cout << "无效的文件" << endl;
exit(1);
}
noExtendedNameFileName = fileName.substr(0, pos);
freopen(argv[1], "r", stdin);
// 开始编译功能
cout << "开始编译" << endl;
if (lexical_and_syntax_analyse())
exit(1);
cout << "词法 & 语法分析成功" << endl;
if (!semantic_analyse(root))
exit(2);
cout << "语义分析成功" << endl;
generate_codes(root, noExtendedNameFileName);
cout << "代码生成成功" << endl;
// 生成二进制代码
if (COMPILE_TO_BIN)
{
string gcc_job = "gcc -o " + noExtendedNameFileName + " " + noExtendedNameFileName + ".c";
cout << "开始可执行文件编译:" + gcc_job << endl;
system(gcc_job.data());
cout << "编译结束" << endl;
cout << "可执行文件:\'" + noExtendedNameFileName + "\'" << endl;
}
return 0;
} | true |
0f1d32de7ad94527d7e8e25f30d613a8b8380992 | C++ | DuyetVu2001/Study-CPlusPlus-Language | /BaiTapTrenLop/BT 17-4-2020/B1.cpp | UTF-8 | 481 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int nhap(){
int n;
do{
cout << "Nhap vao so nguyen duong n: ";
cin >> n;
}while(n < 1);
return n;
}
int tinhS(int n){
if(n == 1){
return 1;
}
return (pow(-1, n+1)*n) + tinhS(n-1);
}
long long tinhP(int n){
if(n == 1){
return 1;
}
return n*n + tinhP(n-1);
}
int main(){
int n = nhap();
cout << "Gia tri cua bieu thuc:\nS(n) = " << tinhS(n) << endl;
cout << "P(n) = " << tinhP(n);
return 0;
}
| true |
776df01e885251182d826a40641fddcbaf8220e3 | C++ | fjnoyp/Graphics | /eyerays-blue/source/Art.cpp | UTF-8 | 3,337 | 3.234375 | 3 | [] | no_license | #include "Art.h"
Art::Art(float timeIncr, int depth, uint32 num) : timeIncrement(timeIncr) {
G3D::Random randomGenerator1(num);
G3D::Random randomGenerator2(num+1234);
G3D::Random randomGenerator3(num+9713);
expression1 = shared_ptr<Expr>(build(depth,randomGenerator1));
expression2 = shared_ptr<Expr>(build(depth,randomGenerator2));
expression3 = shared_ptr<Expr>(build(depth,randomGenerator3));
}
//recommended -> timeIncrement ~ M_PI/400.0f;
shared_ptr<Art> Art::create(float timeIncrement, int depth, uint32 num){
return shared_ptr<Art>(new Art(timeIncrement, depth, num));
}
shared_ptr<Image> Art::nextImage(){
step = .7f*(cos(ourTime)+1.0f);
ourTime += timeIncrement;
cout << "curTime:";
cout << (ourTime);
cout << "\n";
return doRandomGray(step+.5f);
}
//This is code translated from Stephen Freund's Lab 4 version in ML
//Converts an integer i from range -N to N into a real in -1 1
float Art::toReal(int i, int N){
return (float)(i)/(float)(N);
}
//Builds a random mathematical expression
Expr* Art::build(int depth, G3D::Random& randomGenerator){
if(depth==0){
int randomNum = randomGenerator.integer(1,2);
if(randomNum==1){ return new Expr( Expr::VarX); }
else{ return new Expr( Expr::VarY); }
}
else{
int randomNum = randomGenerator.integer(1,100);
if(randomNum<16){
return new Expr(build(depth-1,randomGenerator),Expr::Cos,false);
}
else if(randomNum<32){
return new Expr(build(depth-1,randomGenerator),Expr::Sin,false);
}
else if(randomNum<48){
return new Expr(build(depth-1,randomGenerator),build(depth-1,randomGenerator),Expr::Average,true);
}
else if(randomNum<64){
return new Expr(build(depth-1,randomGenerator),build(depth-1,randomGenerator),Expr::Times,true);
}
else if(randomNum<80){
return new Expr(build(depth-1,randomGenerator),build(depth-1,randomGenerator),Expr::Circle,true);
}
else{
return new Expr(build(depth-1,randomGenerator),Expr::ASin,true);
}
}
}
//Create a random image by evaluating the random function over a continuous interval
shared_ptr<Image> Art::doRandomGray(float step){
//uint32 num(13514); makes regular choppy heightfield
//uint32 num(9087); really choppy melting terrain
// uint32 num(56224); cooler
// uint32 num(24623); forgot
// uint32 seed(13411); nice waves rally nice
//N+1 by N+1 pixels
int N = 100;
shared_ptr<Image> image = Image::create(N*2+1,N*2+1,ImageFormat::RGB32F());
for(int x = 0; x<2*N; ++x){
for(int y = 0; y<2*N; ++y){
//convert grid locations to -1,1
float px = toReal(x,N);
float py = toReal(y,N);
//apply given random function
float c1 = expression1->eval(px,py,step);
float c2 = expression2->eval(px,py,step);
float c3 = expression3->eval(px,py,step);
//the image positions
int imgX = x;
int imgY = y;
const Color3 color(c1,c2,c3);
image->set( Point2int32( abs(imgX), abs(imgY) ), color);
}
}
return image;
}
| true |
97e81c2357448acc02abf9d568134b9184d54542 | C++ | lap089/Practice | /A. Joysticks/Source.cpp | UTF-8 | 354 | 2.921875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int charge, uncharge, m=0;
cin >> charge;
cin >> uncharge;
if (charge > uncharge) swap(charge, uncharge);
while (charge > 0 && uncharge > 0) {
if (charge + uncharge == 2) break;
if (uncharge <= 2) { swap(charge, uncharge); }
uncharge -= 2;
charge++;
++m;
}
cout << m;
return 0;
} | true |
b262ff272fe0877806cb25ac218c4d6c52a91372 | C++ | lawy623/Algorithm_Interview_Prep | /Algo/Leetcode/406QueueReconstructionByHeight.cpp | UTF-8 | 1,163 | 3.328125 | 3 | [] | no_license | // greedy
class Solution {
public:
static bool comp(vector<int>& a, vector<int>& b){
if(a[0] > b[0]) return true;
if(a[0] == b[0]) return a[1] < b[1];
return false;
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), comp);
vector<vector<int>> res;
for(int i=0; i<people.size(); i++){
res.insert(res.begin() + people[i][1], people[i]);
}
return res;
}
};
// with list it become faster
class Solution {
public:
static bool comp(vector<int>& a, vector<int>& b){
if(a[0] > b[0]) return true;
if(a[0] == b[0]) return a[1] < b[1];
return false;
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
sort(people.begin(), people.end(), comp);
list<vector<int>> res;
for(int i=0; i<people.size(); i++){
list<vector<int>>::iterator it = res.begin();
int k = people[i][1];
while(k>0) {it++;k--;}
res.insert(it, people[i]);
}
return vector<vector<int>>(res.begin(), res.end());
}
}; | true |
d849b21c75e76c5a75be17151e07594b9056f571 | C++ | EarnestGibbs/BullCowGame | /BullCowGame/BullsAndCows/BullsAndCows/FBullCowGame.cpp | UTF-8 | 3,767 | 3.1875 | 3 | [] | no_license | #include "FBullCowGame.h"
#include <map>
#include <time.h>
#define TMap std::map
using int32 = int;
void FBullCowGame::Reset()
{
constexpr int32 MAX_TRIES = {};
HIDDEN_WORD = MyRandomHiddenWord;
MyHiddenWord = HIDDEN_WORD;
MyMaxTries = MAX_TRIES;
MyCurrentTry = 1;
bGameIsWon = false;
return;
}
FBullCowGame::FBullCowGame()
{
Reset();
}
int32 FBullCowGame::GetCurrentTry() const
{
return MyCurrentTry;
}
int32 FBullCowGame::GetHiddenWordLength() const
{
return MyHiddenWord.length();
}
bool FBullCowGame::IsGameWon() const
{
return bGameIsWon;
}
FString FBullCowGame::GetRandomHiddenWord()
{
srand(time(NULL));
if (CurrentLevel == 1)
{
MyRandomHiddenWord = LevelOneWords[rand() % 10];
}
else if (CurrentLevel == 2)
{
MyRandomHiddenWord = LevelTwoWords[rand() % 10];
}
else if (CurrentLevel == 3)
{
MyRandomHiddenWord = LevelThreeWords[rand() % 10];
}
else if (CurrentLevel == 4)
{
MyRandomHiddenWord = LevelFourWords[rand() % 10];
}
else
{
MyRandomHiddenWord = LevelFiveWords[rand() % 10];
}
MyHiddenWord = MyRandomHiddenWord;
//pull form level
//run srand
//pick random word out of apporpiate list
//return the word as the hidden word
return MyRandomHiddenWord;
}
FString FBullCowGame::RevelAnswer()
{
MyRandomHiddenWordRevel = MyRandomHiddenWord;
return MyRandomHiddenWordRevel;
}
int32 FBullCowGame::IncrementLevel()
{
CurrentLevel++;
return int32();
}
int32 FBullCowGame::GetCurrentLevel() const
{
return CurrentLevel;
}
int32 FBullCowGame::GetMaxTries() const
{
TMap <int32, int32> WordLengthToMaxTries{ {3,5}, {4,7}, {5,10}, {6,15},{7,25} };
return WordLengthToMaxTries[MyHiddenWord.length()];
}
EWordStatus FBullCowGame::IsGuessValid(FString Guess) const
{
if (!IsIsogram(Guess))
{
return EWordStatus::Not_Isogram;
}
else if (!IsLowercase(Guess))
{
return EWordStatus::Not_Lowercase;
}
else if(Guess.length() != GetHiddenWordLength())
{
return EWordStatus::Wrong_Length;
}
else
{
return EWordStatus::Ok;
}
}
// receives a Vaid Guess, incremits turn, and returns count
FBullCowCount FBullCowGame::SubmitValidGuess(FString Guess)
{
MyCurrentTry++;
FBullCowCount BullCowCount;
//loop through all letters in the guess
int32 WordLength = MyHiddenWord.length();
for (int32 MHWCahr = 0; MHWCahr < WordLength; MHWCahr++)
{
for (int32 GChar = 0; GChar < WordLength; GChar++)
{
if (Guess[GChar] == MyHiddenWord[MHWCahr])
{
if (MHWCahr == GChar)
{
BullCowCount.Bulls++;
}
else
{
BullCowCount.Cows++;
}
}
}
}
if (BullCowCount.Bulls == WordLength)
{
bGameIsWon = true;
}
else
{
bGameIsWon = false;
}
return BullCowCount;
}
FString FBullCowGame::GetHint(FString Word)
{
if (CurrentLevel == 1)
{
Hint = Word[rand() % 3];
}
else if (CurrentLevel == 2)
{
Hint = Word[rand() % 4];
}
else if (CurrentLevel == 3)
{
Hint = Word[rand() % 5];
}
else if (CurrentLevel == 4)
{
Hint = Word[rand() % 6];
}
else
{
Hint = Word[rand() % 7];
}
return Hint;
}
bool FBullCowGame::IsIsogram(FString Word) const
{
if (Word.length() <= 1)
{
return true;
}
TMap<char, bool> LetterSeen;
for (auto Letter : Word)//for all letters of the word
{
Letter = tolower(Letter);
if (LetterSeen[Letter])
{
return false;
}
else
{
LetterSeen[Letter] = true;
//return true;
}
}
return true;
}
bool FBullCowGame::IsLowercase(FString Word) const
{
for (auto Letter: Word)
{
if (!islower(Letter))
{
return false;
}
}
return true;
}
| true |
520e64afc13e46759571db0a0c2e8a3324133157 | C++ | Diusrex/UVA-Solutions | /122 Trees on the level.cpp | UTF-8 | 2,280 | 3.3125 | 3 | [
"Apache-2.0"
] | permissive | #include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <set>
using namespace std;
struct Node
{
long long num;
string position;
bool operator<(const Node &other) const
{
// Print out inital first
if (position.size() != other.position.size())
return position.size() < other.position.size();
return position < other.position;
}
};
bool ContainsAllParents(const set<string> &allPositions)
{
for (set<string>::iterator iter = allPositions.begin();
iter != allPositions.end(); ++iter)
{
if (*iter != "")
{
string wantedString = iter->substr(0, iter->size()-1);
if (allPositions.find(wantedString) == allPositions.end())
return false;
}
}
return true;
}
Node nodes[260];
int main()
{
set<string> allPositions;
char firstBracket, comma;
while (cin >> firstBracket >> nodes[0].num >> comma >> nodes[0].position)
{
allPositions.clear();
// Remove the bracket
nodes[0].position = nodes[0].position.substr(0, nodes[0].position.size()-1);
allPositions.insert(nodes[0].position);
int pos = 1;
bool valid = true;
while (cin >> firstBracket, cin.peek() != ')')
{
cin >> nodes[pos].num >> comma >> nodes[pos].position;
// Remove the bracket
nodes[pos].position =
nodes[pos].position.substr(0, nodes[pos].position.size()-1);
if (allPositions.find(nodes[pos].position) != allPositions.end())
valid = false;
allPositions.insert(nodes[pos].position);
++pos;
}
// Remove the ) at the end
cin.ignore();
if (valid && ContainsAllParents(allPositions))
{
sort(nodes, nodes + pos);
cout << nodes[0].num;
for (int i = 1; i < pos; ++i)
cout << ' ' << nodes[i].num;
cout << '\n';
}
else
{
cout << "not complete\n";
}
}
} | true |
c36f5443a015e052bafad0f5a8032289a2f5b023 | C++ | tedopranowo/WewEngine | /WewEngine/Source/Tools/ResourceCache.h | UTF-8 | 1,715 | 3.25 | 3 | [] | no_license | #pragma once
#include <unordered_map>
#include <memory>
#include <FilePath.h>
//-------------------------------------------------------------------------------------------------
// Class ResourceCache
//-------------------------------------------------------------------------------------------------
template<typename T>
class ResourceCache
{
private:
static std::unordered_map<std::string, std::weak_ptr<T>> m_resourceList;
public:
//Static class
ResourceCache() = delete;
~ResourceCache() = delete;
static std::shared_ptr<T> Get(const FilePath& filePath);
};
template<typename T>
std::unordered_map<std::string, std::weak_ptr<T>> ResourceCache<T>::m_resourceList;
template<typename T>
std::shared_ptr<T> ResourceCache<T>::Get(const FilePath & filePath)
{
auto find = m_resourceList.find(filePath.GetFullPath());
//If the resource already in the cache and it isn't expired yet, return the cache
if (find != m_resourceList.end() && !find->second.expired())
return find->second.lock();
//Load the resource
std::shared_ptr<T> resource = std::make_shared<T>();
resource->Load(filePath);
//Save the resource into the list
m_resourceList[filePath.GetFullPath()] = resource;
return resource;
}
//-------------------------------------------------------------------------------------------------
// Class ICachable
// Class which derived from this class are required to be friend with the resource cache
// Ex: friend class ResourceCache<T>;
//-------------------------------------------------------------------------------------------------
template<typename T>
class ICachable
{
private:
virtual bool Load(const FilePath& filePath) = 0;
}; | true |
2328a153fe78c08ebea849d3c6353f56c3b217d0 | C++ | y-wan/OJ | /timus/1982最小生成树.cpp | MacCentralEurope | 1,436 | 2.984375 | 3 | [
"MIT"
] | permissive | //СKruskal+bfs
#include <iostream>
#include <queue>
using namespace std;
priority_queue<pair<int, pair<int, int> > > pq;
int path[101][101], powered_count = 0; // bfs_visited_count
bool powered[101], connect[101][101]; // bfs_visited[101]
void bfs_power_up(const int center, const int n) {
for (int i = 1; i <= n; i++) {
if (powered_count == n) return;
if (connect[center][i] && !powered[i]) {
powered[i] = true;
++powered_count;
//++bfs_visited_count;
bfs_power_up(i, n);
}
}
}
int main() {
int n, k, t;
long long cost = 0;
cin >> n >> k;
while (k-- > 0) {
cin >> t;
powered[t] = true;
++powered_count;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> path[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j < i; j++)
pq.push(make_pair(-path[i][j], make_pair(i, j)));
while (!pq.empty() && powered_count < n) {
pair<int, pair<int, int> > tmp = pq.top();
pq.pop();
while (powered[tmp.second.first] && powered[tmp.second.second]) {
tmp = pq.top();
pq.pop();
}
int i = tmp.second.first, j = tmp.second.second;
cost -= tmp.first;
connect[i][j] = connect[j][i] = true;
if (!powered[i] && powered[j]) {
powered[i] = true;
++powered_count;
bfs_power_up(i, n);
}
else if (powered[i] && !powered[j]) {
powered[j] = true;
++powered_count;
bfs_power_up(j, n);
}
}
cout << cost << endl;
return 0;
} | true |
6a105eab8b32f291292399927c9c26712cd4ea29 | C++ | sansajn/test | /namecollision.cpp | UTF-8 | 251 | 3 | 3 | [] | no_license | #include <iostream>
struct foo {
void introduce() {std::cout << "i'm foo\n";}
};
class goo
{
public:
foo foo() const {return f;}
private:
::foo f;
};
int main(int argc, char * argv[])
{
goo g;
foo f = g.foo();
f.introduce();
return 0;
}
| true |
9dac9571823b43d5a4f750954bde8331081b03e5 | C++ | ssavi-ict/UVa-Online-Judge | /Learning Bitwise Sieve.cpp | UTF-8 | 808 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
#define MAX 10000005
using namespace std;
int status[(MAX/32)+2];
bool check(int n, int pos) { return (bool)(n & (1<<pos)); }
int SET(int n, int pos){ return n=n|(1<<pos);}
void sieve()
{
int sqrtN=int (sqrt(MAX));
for(int i=3; i<=sqrtN; i=i+2)
{
if(check(status[i>>5],i&31)==0)
{
for(int j=i*i; j<=MAX; j= j + (i<<1))
{
status[j>>5]=SET(status[j>>5],j&31);
}
}
}
//puts("2");
int j = 0;
for(int i=2; i<=MAX; )
{
if(check(status[i>>5], i&31)==0)
{
printf("%d\n",i);
j++;
}
if(i==2) i++;
else i=i+2;
}
cout<<j;
}
int main()
{
sieve();
return 0;
}
| true |
fe596b3fe0ae556cebe5ffd1d3a1ac9bbf0157bc | C++ | CommunicoPublic/iris | /tags/iris-0.1.23/include/core/MainLoopEventWatcher.hpp | UTF-8 | 2,066 | 2.515625 | 3 | [] | no_license | /*-
* Copyright (c) Iris Dev. team. All rights reserved.
* See http://www.communico.pro/license for details.
*
*/
#ifndef _MAIN_LOOP_EVENT_WATCHER_HPP__
#define _MAIN_LOOP_EVENT_WATCHER_HPP__ 1
/**
@file MainLoopEventWatcher.hpp
@brief Main loop event watcher
Accepts network connections and put them to the accept queue.
*/
#include "IOWatcher.hpp"
#include "STLVector.hpp"
namespace IRIS
{
// FWD
struct AcceptLoopContext;
struct MainLoopContext;
class ServerTCPSocket;
class ServiceConfig;
/**
@class MainLoopEventWatcher MainLoopEventWatcher.hpp <MainLoopEventWatcher.hpp>
@brief Main loop event watcher
Accepts network connections and put them to the accept queue.
*/
class MainLoopEventWatcher:
public IOWatcher
{
public:
/**
@brief Constructor
@param oMainContext - Main context
@param vContextes - List of contextes for event threads
@param pServerSocket - server socket
@param pServiceConfig - service configuration
*/
MainLoopEventWatcher(MainLoopContext & oMainContext,
STLW::vector<AcceptLoopContext *> & vContextes,
ServerTCPSocket * pServerSocket,
ServiceConfig * pServiceConfig);
/**
@brief Watcher callback
@param iSocket - socket to watch
@param iREvents - list of events
*/
void Callback(const INT_32 iSocket,
const UINT_32 iREvents);
/**
@brief A destructor
*/
~MainLoopEventWatcher() throw();
private:
// Does not exist
MainLoopEventWatcher(const MainLoopEventWatcher & oRhs);
MainLoopEventWatcher& operator=(const MainLoopEventWatcher & oRhs);
/** Main Context */
MainLoopContext & oMainContext;
/** List of contextes */
STLW::vector<AcceptLoopContext *> & vContextes;
/** Server socket */
ServerTCPSocket * pServerSocket;
/** Service config */
ServiceConfig * pServiceConfig;
};
} // namespace IRIS
#endif // _MAIN_LOOP_EVENT_WATCHER_HPP__
// End.
| true |
f367a6b0a766a2865ff1024c7ae106030f0daa43 | C++ | svenmcgov/cit_245 | /iotest.cpp | UTF-8 | 218 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream fin;
fin.open("test.txt");
char next;
fin.get(next);
while(!fin.eof()){
cout << next;
fin.get(next);
}
cout << endl;
}
| true |
1239575f52ee29d3e74eeb859c4ac30801dd10e2 | C++ | jeromeNoir/QuICCPython | /src/Exceptions/Exception.cpp | UTF-8 | 401 | 2.515625 | 3 | [] | no_license | /**
* @file Exception.cpp
* @brief Definitions of the Exception methods.
* @author Philippe Marti \<philippe.marti@colorado.edu\>
*/
// System includes
//
// External includes
//
// Class include
//
#include "Exceptions/Exception.hpp"
// Project includes
//
namespace QuICC {
Exception::Exception(const std::string& msg)
: std::runtime_error(msg)
{
}
Exception::~Exception() throw()
{
}
}
| true |
e8e20de7fa30609f19a1477cd1cfd9d38d27a549 | C++ | MeJustBear/SHACAL-algorithm | /lab2_v1/HeaderForBmp.h | UTF-8 | 2,554 | 2.578125 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<fstream>
#define bmp 19778
#pragma pack(push,1)
/*@brief
first header in bmp type
*/
typedef struct {
unsigned short bfType; //2
unsigned int bfSize; //4(6)
unsigned short bfReserved1;//2(8)
unsigned short bfReserved2; //2(10)
unsigned int bfOffBits; //4(14)
}BMPFILEHEADER;//14
#pragma pack(pop)
#pragma pack(push,1)
/*@brief
second header in bmp type
*/
typedef struct {
unsigned int bi_Size; //18
unsigned int bi_Width; //22
unsigned int bi_Height; //26
unsigned short bi_Planes; //28
unsigned short bi_BitCount; //30
unsigned int bi_Compression; //34
unsigned int bi_SizeImage; //38
int bi_X; //42
int bi_Y; //46
unsigned int bi_ClrUsed; // 50
unsigned int bi_ClrImportant; //54
}BMP, BMPINFOHEADER;//40
#pragma pack(pop)
/**
@brief
*/
std::ifstream Open_File_Read(std::string filename);
/**
@brief
*/
std::ofstream Open_File_Write(std::string filename);
/**
@brief
*/
BMPFILEHEADER readFH(std::ifstream& stream);
/**
@brief
*/
void writeFH(std::ofstream & stream, BMPFILEHEADER bf);
/**
@brief
*/
BMPINFOHEADER readIH(std::ifstream& stream);
/**
@brief
*/
void writeIH(std::ofstream & stream, BMPINFOHEADER bi);
/*
#pragma pack(push,1)
/*@brief
Color structure for simple usability
*//*
typedef struct COLOR_pix {
uint8_t B, G, R;
}COLOR;
#pragma pack(pop)
*/
/*@brief
Class which include one picture in one exemplar of BMP24
*//*
class Image24 {
private:
BMPFILEHEADER fileheader;
BMPINFOHEADER infoheader;
std::vector<std::vector<uint8_t>> map;
public:
Image24(BMPFILEHEADER fh, BMPINFOHEADER ih) {
fileheader = fh;
infoheader = ih;
map = std::vector<std::vector<uint8_t>>(ih.bi_Height);
}
Image24() {
}
~Image24() {
map.clear();
}
void set_headers(BMPFILEHEADER fh, BMPINFOHEADER ih) {
fileheader = fh;
infoheader = ih;
map = std::vector<std::vector<uint8_t>>(ih.bi_Height);
}
void set_map(std::ifstream& stream);
};*/
/*@brief
Class which include one picture in one exemplar of BMP8
*//*
class Image8 {
private:
BMPFILEHEADER fileheader;
BMPINFOHEADER infoheader;
std::vector<std::vector<uint8_t>> map;
public:
Image8(BMPFILEHEADER fh, BMPINFOHEADER ih) {
fileheader = fh;
infoheader = ih;
map = std::vector<std::vector<uint8_t>>(ih.bi_Height);
}
Image8() {
}
~Image8() {
map.clear();
}
void set_headers(BMPFILEHEADER fh, BMPINFOHEADER ih) {
fileheader = fh;
infoheader = ih;
map = std::vector<std::vector<uint8_t>>(ih.bi_Height);
}
void set_map(std::ifstream& stream);
};*/ | true |
90df58261dc3a309a94ea84c1d6981afff60aad2 | C++ | hemantgangolia/two_roads | /ingredient.h | UTF-8 | 246 | 2.5625 | 3 | [] | no_license | #ifndef INGREDIENT_HPP // This is used to avoid including a header more than once.
#define INGREDIENT_HPP
#include <string>
class Ingredient
{
public:
std::string name;
int expiry;
Ingredient ();
Ingredient(std::string, int);
};
#endif | true |
d233cb8b3f2dbb23f78d664c29d8028192afaa61 | C++ | TerenYeung/Road-To-BE | /Computer-Science/C++/Ch5/ex5_9.cpp | UTF-8 | 669 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
unsigned int ac = 0, ec = 0, ic = 0, oc = 0, uc = 0, otherc = 0;
char ch;
while(cin >> ch){
if (ch == 'a' || ch == 'A') ++ac;
else if (ch == 'e' || ch == 'E') ++ec;
else if (ch == 'i' || ch == 'I') ++ic;
else if (ch == 'o' || ch == 'O') ++oc;
else if (ch == 'u' || ch == 'U') ++uc;
else ++otherc;
}
cout << "ac:\t" << ac << endl;
cout << "ec:\t" << ec << endl;
cout << "ic:\t" << ic << endl;
cout << "oc:\t" << oc << endl;
cout << "uc:\t" << uc << endl;
return 0;
} | true |
135b305e9e29cd0df3e230bf1e4fa37a6f466bf7 | C++ | rAum/vilga | /vilga/include/vilga/detail/data.hpp | UTF-8 | 1,252 | 3.125 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef VILGA_DETAIL_DATA_HPP
#define VILGA_DETAIL_DATA_HPP
#include <memory>
#include <string>
#include <vilga/detail/macros.hpp>
namespace vilga_detail {
class memory_block_t {
public:
std::size_t size_ = 0;
std::unique_ptr<std::uint8_t[]> bytes_;
static void free_mem(void* data, void*) noexcept {
std::uint8_t* first = static_cast<std::uint8_t*>(data);
delete[] first;
}
};
enum class Encoding : std::uint8_t {
VilgaExtension = 0x7F,
};
/**
* Determines if protocol is vilga internal or external extension
* @param protocol
* @return true if protocol is vilga internal
*/
constexpr bool is_internal(vilga_detail::Encoding encoding) {
constexpr std::uint8_t last_vilga_encoding =
static_cast<std::uint8_t>(vilga_detail::Encoding::VilgaExtension);
return static_cast<std::uint8_t>(encoding) > last_vilga_encoding;
}
class topic {
std::string name_;
};
class header {
public:
Encoding encoding_;
std::array<std::uint8_t, 3> magic_bytes_;
topic topic_;
};
/**
* @brief Models a data frame.
* Data frame consists header, a block of data and optional topic.
*/
class data {
public:
header header_;
memory_block_t data_;
};
} // namespace vilga_detail
#endif // VILGA_DETAIL_DATA_HPP
| true |
164dc9966a5cfe15a195eca706ae2546c503cfb1 | C++ | wangbiy/- | /test_2020_9_5_1/test_2020_9_5_1/test.cpp | GB18030 | 1,835 | 3.28125 | 3 | [] | no_license | #include <iostream>
using namespace std;
//Убż
#if 0
//1.³
#include <set>
#include <string>
int main()
{
string str;
set<string> s;
while (cin >> str)
{
s.insert(str);//ȥ
}
cout << s.size() << endl;
return 0;
}
#endif
#if 0
//2.ƻ
#include <vector>
#include <math.h>
int avg(vector<int> arr)
{
int average = 0;//ƽ
int sum = 0;//ƻ
int n = arr.size();//ţ
for (int i = 0; i < n; ++i)
{
sum += arr[i];//ͳƻ
}
average = sum / n;//ƽֵ
if (sum % n != 0)//˵ƽ֣-1
return -1;
for (int i = 0; i < n; ++i)
{
int ret = abs(arr[i] - average);//ǰţӵеƻƽֵIJֵֵ2˵ƶֱӷ-1
if (ret % 2 != 0)
return -1;
}
//ߵ˵ƽֲţƻÿƶ2
int count = 0;//ͳƴ
for (int i = 0; i < n; ++i)
{
if (arr[i]>average)//ֻбƽֵţƻſƶ
count += (arr[i] - average) / 2;
}
return count;
}
int main()
{
int n;
cin >> n;
vector<int> num(n, 0);
for (int i = 0; i < n; ++i)
{
cin >> num[i];
}
int count = avg(num);
cout << count << endl;
return 0;
}
#endif
#if 0
//3.ǼʴԽ
#include <math.h>
int main(){
long h, i;
while (cin >> h){
long s = sqrt(h);
for (i = s; i + i*i > h; --i)
{}
cout << i << endl;
}
return 0;
}
#endif
//4.رͼ
#include <string>
int main(){
string str;//ԭַ
while (cin >> str)
{
string _str;//
cin >> _str;
int i = 0;//ԭַ
int j = 0;//
while (i < str.size())
{
if (str[i++] == _str[j])
j++;
}
if (j == _str.size())
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
} | true |
41f243837175bf2ccf3797caa46776ae483d5b47 | C++ | Kitware/VTK | /Filters/Points/vtkMaskPointsFilter.h | UTF-8 | 3,869 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
// SPDX-License-Identifier: BSD-3-CLAUSE
/**
* @class vtkMaskPointsFilter
* @brief extract points within an image/volume mask
*
* vtkMaskPointsFilter extracts points that are inside an image mask. The
* image mask is a second input to the filter. Points that are inside a voxel
* marked "inside" are copied to the output. The image mask can be generated
* by vtkPointOccupancyFilter, with optional image processing steps performed
* on the mask. Thus vtkPointOccupancyFilter and vtkMaskPointsFilter are
* generally used together, with a pipeline of image processing algorithms
* in between the two filters.
*
* Note also that this filter is a subclass of vtkPointCloudFilter which has
* the ability to produce an output mask indicating which points were
* selected for output. It also has an optional second output containing the
* points that were masked out (i.e., outliers) during processing.
*
* Finally, the mask value indicating non-selection of points (i.e., the
* empty value) may be specified. The second input, masking image, is
* typically of type unsigned char so the empty value is of this type as
* well.
*
* @warning
* During processing, points not within the masking image/volume are
* considered outside and never extracted.
*
* @warning
* This class has been threaded with vtkSMPTools. Using TBB or other
* non-sequential type (set in the CMake variable
* VTK_SMP_IMPLEMENTATION_TYPE) may improve performance significantly.
*
* @sa
* vtkPointOccupancyFilter vtkPointCloudFilter
*/
#ifndef vtkMaskPointsFilter_h
#define vtkMaskPointsFilter_h
#include "vtkFiltersPointsModule.h" // For export macro
#include "vtkPointCloudFilter.h"
VTK_ABI_NAMESPACE_BEGIN
class vtkImageData;
class vtkPointSet;
class VTKFILTERSPOINTS_EXPORT vtkMaskPointsFilter : public vtkPointCloudFilter
{
public:
///@{
/**
* Standard methods for instantiating, obtaining type information, and
* printing information.
*/
static vtkMaskPointsFilter* New();
vtkTypeMacro(vtkMaskPointsFilter, vtkPointCloudFilter);
void PrintSelf(ostream& os, vtkIndent indent) override;
///@}
///@{
/**
* Specify the masking image. It must be of type vtkImageData.
*/
void SetMaskData(vtkDataObject* source);
vtkDataObject* GetMask();
///@}
/**
* Specify the masking image. It is vtkImageData output from an algorithm.
*/
void SetMaskConnection(vtkAlgorithmOutput* algOutput);
///@{
/**
* Set / get the values indicating whether a voxel is empty. By default, an
* empty voxel is marked with a zero value. Any point inside a voxel marked
* empty is not selected for output. All other voxels with a value that is
* not equal to the empty value are selected for output.
*/
vtkSetMacro(EmptyValue, unsigned char);
vtkGetMacro(EmptyValue, unsigned char);
///@}
protected:
vtkMaskPointsFilter();
~vtkMaskPointsFilter() override;
unsigned char EmptyValue; // what value indicates a voxel is empty
// All derived classes must implement this method. Note that a side effect of
// the class is to populate the PointMap. Zero is returned if there is a failure.
int FilterPoints(vtkPointSet* input) override;
// Support second input
int FillInputPortInformation(int port, vtkInformation* info) override;
int RequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
int RequestInformation(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
int RequestUpdateExtent(vtkInformation*, vtkInformationVector**, vtkInformationVector*) override;
vtkImageData* Mask; // just a placeholder during execution
private:
vtkMaskPointsFilter(const vtkMaskPointsFilter&) = delete;
void operator=(const vtkMaskPointsFilter&) = delete;
};
VTK_ABI_NAMESPACE_END
#endif
| true |
959a285a6ff5d767d9a3d83bb0da7bb319eb374a | C++ | shribadiger/interviewpreparation | /HackerRank/SaleByMatch.cpp | UTF-8 | 339 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
int main() {
int n = 10;
int list[]={10,10,10,30,10,20,20,10,40,50};
int *result = new int[101];
memset(result,0,sizeof(int)*101);
for(int i=0;i<10;i++){
result[list[i]]++;
}
for(int i=0;i<51;i++) {
if(result[i] != 0)
std::cout<<"\t"<<result[i];
}
return 0;
}
| true |
f16e0baa7d7a3a3907437a053318c19244a14fa1 | C++ | wazzamauro/ASD | /priorityqueue/PriorityQueue.h | UTF-8 | 4,720 | 3.078125 | 3 | [] | no_license | //
// Created by Mauro Nicolì on 2019-04-08.
//
#ifndef STRUTTURE_DATI_PRIORITYQUEUE_H
#define STRUTTURE_DATI_PRIORITYQUEUE_H
template<class T>
class CodaP {
public:
typedef T _item;
CodaP();
CodaP(int);
CodaP(const CodaP<T> &);
~CodaP();
void insert(_item);
_item min();
void deleteMin();
CodaP &operator=(const CodaP &);
bool operator==(CodaP &);
void print();
void print_tree_form();
private:
int _dimension;
_item *_heap;
int _last;
void fixUp();
void fixDown(int, int);
bool is_empty();
bool is_full();
};
template<class T>
CodaP<T>::CodaP() {
_dimension = 100;
_heap = new _item[_dimension];
_last = 0;
};
template<class T>
CodaP<T>::CodaP(int dim) {
_dimension = dim;
_heap = new _item[_dimension];
_last = 0;
};
template<class T>
CodaP<T>::CodaP(const CodaP<T> &c) {
_dimension = c._dimension;
_last = c._last;
_heap = new _item[_dimension];
for (int i = 0; i < _last; i++) {
_heap[i] = c._heap[i];
}
}
template<class T>
CodaP<T>::~CodaP() {
delete[] _heap;
}
template<class T>
void CodaP<T>::insert(_item i) {
if (!is_full()) {
_last++;
_heap[_last - 1] = i;
fixUp();
}
};
template<class T>
typename CodaP<T>::_item CodaP<T>::min() {
if (!is_empty()) {
return (_heap[0]);
}
}
template<class T>
void CodaP<T>::deleteMin() {
if (!is_empty()) {
//copia il valore dell'ultima foglia nella radice
_heap[0] = _heap[_last - 1];
_last--;
//fai scendere verso il basso
fixDown(1, _last);
}
}
/* Per ripristinare i vincoli dello _heap quando la priorità di un nodo è *
* cresciuta, ci spostiamo nello _heap verso l'alto, scambiando, se necessario,*
* il nodo in posizione k con il suo nodo padre (in posizione k/2), *
* continuando fintanto che _heap[k]<_heap[k/2] oppure fino a quando *
* raggiungiamo la cima dello _heap. */
template<class T>
void CodaP<T>::fixUp() {
int k = _last;
while (k > 1 && _heap[k - 1] < _heap[k / 2 - 1]) {
_item tmp;
tmp = _heap[k - 1];
_heap[k - 1] = _heap[k / 2 - 1];
_heap[k / 2 - 1] = tmp;
k = k / 2;
}
}
/* Per ripristinare i vincoli dello _heap quando la priorità di un nodo si è *
* ridotta, ci spostiamo nello _heap verso il basso, scambiando, se necessario,*
* il nodo in posizione k con il minore dei suoi nodi figli e arrestandoci *
* quando il nodo al posto k non è più grande di almeno uno dei suoi figli *
* oppure quando raggiungiamo il fondo dello _heap. Si noti che se N è pari e *
* k è N/2, allora il nodo in posizione k ha un solo figlio: questo caso *
* particolare deve essere trattato in modo appropriato. */
template<class T>
void CodaP<T>::fixDown(int k, int N) {
short int scambio = 1;
while (k <= N / 2 && scambio) {
int j = 2 * k;
_item tmp;
if (j < N && _heap[j - 1] > _heap[j])
j++;
if ((scambio = (_heap[j - 1] < _heap[k - 1]))) {
tmp = _heap[k - 1];
_heap[k - 1] = _heap[j - 1];
_heap[j - 1] = tmp;
k = j;
}
}
}
template<class T>
bool CodaP<T>::is_empty() {
return (_last == 0);
}
template<class T>
bool CodaP<T>::is_full() {
return (_last == _dimension);
}
template<class T>
CodaP<T> &CodaP<T>::operator=(const CodaP &c) {
_dimension = c._dimension;
_last = c._last;
_heap = new _item[_dimension];
for (int i = 0; i < _last; i++) {
_heap[i] = c._heap[i];
}
return *this;
}
template<class T>
bool CodaP<T>::operator==(CodaP &c) {
bool flag = false;
if (_last != c._last) {
return false;
} else {
for (int i = 0; i < _last; i++) {
if (_heap[i] != c._heap[i]) {
return false;
} else {
flag = true;
}
}
}
return flag;
}
template<class T>
void CodaP<T>::print() {
cout << "[ ";
for (int i = 0; i < _last; i++) {
if (i == 0) {
cout << _heap[i];
} else {
cout << " , " << _heap[i];
}
//cout << " ]";
}
cout << " ]" << endl;
}
template<class T>
void CodaP<T>::print_tree_form() {
for (int i = 0; i < _last; i++) {
cout << _heap[i] << " : ";
if (i < _last - 2) {
cout << _heap[2 * i + 1];
}
if (i < _last - 3) {
cout << " " << _heap[(2 * i) + 2];
}
cout << endl;
}
}
#endif //STRUTTURE_DATI_PRIORITYQUEUE_H
| true |
73f73d200829aa6a0ec7ff0deea7a195626bb2df | C++ | mseeg/pj2 | /Bomber.cpp | UTF-8 | 796 | 3.109375 | 3 | [] | no_license | #include "MilitaryUnit.h"
Bomber::Bomber(string name, int attackDamage) : MilitaryUnit(name, attackDamage)
{
type = "splash";
}
int SquadRemaining(vector<MilitaryUnit*>& Squad)
{
int alive =0;
for(int i =0; i<Squad.size();++i)
if(Squad[i]->isAlive())
++alive;
return alive;
}
void Bomber::fightAll(vector<MilitaryUnit*>& targets)
{
int alive = SquadRemaining( targets );
int damagePerUnit = attackDamage/alive;
int extraDamage = attackDamage%alive;
int firstUnitIndex =0;
for(int i =0; i<targets.size();++i)
if(targets[i]->isAlive())
{
targets[i]->receiveDamage(damagePerUnit + extraDamage );
firstUnitIndex =1;
break;
}
for(int i =0; i<targets.size();++i)
if(targets[i]->isAlive() && i != firstUnitIndex )
targets[i]->receiveDamage(damagePerUnit);
}
| true |
b02e312f75969e9fa8c8c49c1d4f61b1d854126c | C++ | albertored11/PCOM-Problems | /OJ/11367/11367.cpp | UTF-8 | 1,906 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
using vi = vector<int>;
using ii = pair<int, int>;
using vii = vector<ii>;
using vvii = vector<vii>;
using iii = pair<int, ii>;
using viii = vector<iii>;
const int INF = 10e8;
const int MAX_CAP = 102;
const int MAX_CITIES = 1002;
int numCities, numRoads;
vi prices;
vvii adjList;
int numCasos;
int dist[MAX_CAP][MAX_CITIES];
void resuelve() {
int cap, start, end;
cin >> cap >> start >> end;
if (adjList[end].empty()) {
cout << "impossible\n";
return;
}
for (int i = 0; i <= cap; ++i)
for (int j = 0; j < numCities; ++j)
dist[i][j] = INF;
dist[0][start] = 0;
priority_queue<iii, viii, greater<iii>> pq;
pq.push({0, {0, start}});
while (!pq.empty()) {
iii front = pq.top();
pq.pop();
if (front.second.second == end) {
cout << front.first << '\n';
return;
}
int d = front.first;
int comb = front.second.first;
int u = front.second.second;
if (d > dist[comb][u])
continue;
if (comb < cap && dist[comb][u] + prices[u] < dist[comb + 1][u]) {
dist[comb + 1][u] = dist[comb][u] + prices[u];
pq.push({dist[comb + 1][u], {comb + 1, u}});
}
for (auto a : adjList[u]) {
if (comb >= a.first && dist[comb][u] < dist[comb - a.first][a.second]) {
dist[comb - a.first][a.second] = dist[comb][u];
pq.push({dist[comb - a.first][a.second], {comb - a.first, a.second}});
}
}
}
cout << "impossible\n";
}
int main() {
cin >> numCities >> numRoads;
for (int i = 0; i < numCities; ++i) {
int pr;
cin >> pr;
prices.push_back(pr);
}
adjList.assign(numCities, vii());
for (int i = 0; i < numRoads; ++i) {
int u, v, d;
cin >> u >> v >> d;
adjList[u].push_back({d, v});
adjList[v].push_back({d, u});
}
cin >> numCasos;
while (numCasos--) resuelve();
return 0;
}
| true |
241cd78de421134396c8830b024fb56555789ec8 | C++ | akgarhwal/Sports-Programming | /Hacker-Rank/Project Euler-HackerRank/Project Euler #7: 10001st prime.cpp | UTF-8 | 776 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
bool isPrime(int n)
{
if (n == 2)
return true;
if (n == 3)
return true;
if (n % 2 == 0 )
return false;
if (n % 3 == 0 )
return false;
int i = 5;
int w = 2;
while (i * i <= n)
{
if( n % i == 0)
return false;
i += w;
w = 6 - w;
}
return true;
}
int main(){
int tc;
cin>>tc;
//while(tc--){
int n,max=0;
//cin>>n;
int *p = new int[tc];
for(int i=0;i<tc;i++){
cin>>p[i];
max = max<p[i]?p[i]:max;
}
int *a = new int[max];
int count=0;
for(int i=2;count<max;i++){
if(isPrime(i)==true){
a[count]=i;
count++;
}
//cout<<count<<endl;
}
for(int i=0;i<tc;i++){
cout<<a[p[i]-1]<<endl;
}
return 0;
} | true |
66677877be6317cd5313d371fd52c8394def2600 | C++ | katherine0504/Uva | /231.cpp | UTF-8 | 993 | 2.734375 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#define MAX 32800
int LIS[MAX] = {1}, num[MAX] = {0};
int cnt, ans, in;
void init();
void findLIS();
int main() {
int i;
int casecnt = 1;
while (scanf("%d", &in) != EOF) {
if (in == -1) {
break;
}
init();
num[0] = in;
cnt = 1;
while (scanf("%d", &in) != EOF && in != -1) {
num[cnt++] = in;
}
findLIS();
if (casecnt == 1) {
printf("Test #%d:\n maximum possible interceptions: %d\n", casecnt++, ans);
}
else {
printf("\nTest #%d:\n maximum possible interceptions: %d\n", casecnt++, ans);
}
}
return 0;
}
void init() {
int i;
for (i = 0; i < MAX; i++) {
LIS[i] = 1;
}
return;
}
void findLIS() {
int i, j;
ans = 0;
for (i = cnt-1; i >= 0; i--) {
for (j = cnt-1; j >= i; j--) {
if (num[j] < num[i] && LIS[j]+1 > LIS[i]) {
LIS[i] = LIS[j] + 1;
}
}
if (LIS[i] > ans) {
ans = LIS[i];
}
}
return;
}
| true |
ca00aef4fa9a5518e3eaed552238ec4a272d2d4b | C++ | the-nexus/ProjectAutomata | /source/ProjectAutomata/ProjectAutomata/Automata/Simulations/ForestFireSimulation.h | UTF-8 | 626 | 2.953125 | 3 | [
"MIT"
] | permissive | #ifndef FOREST_FIRE_SIMULATION_H
#define FOREST_FIRE_SIMULATION_H
#include "Simulation.h"
// STATES:
// 0 : dead
// 1 : alive
class ForestFireSimulation : public Simulation
{
public:
static const Color treeColor;
static const Color fireColor;
static const Color emptyColor;
ForestFireSimulation();
~ForestFireSimulation();
virtual void reset() override;
virtual void nextStep() override;
Color getCellColor(int state, int timeToLive = 0) const;
int isNeighbourOnFire(int x, int y) const;
private:
int maxTimeToLive = 50;
float probabilityCatchFire = 0.000005f;
float probabilityGrowth = 0.001f;
};
#endif
| true |
11d31478534b15f5066054ad1e075ff4acd17789 | C++ | JackMcCallum/Portfolio | /Demos/Games/Tanks/Source/CollisionManager.h | UTF-8 | 1,647 | 2.59375 | 3 | [] | no_license | /************************************************************************/
/* @class CollisionManager
* @author Jack McCallum
*
* @description
* Collision manager is responsible for checking for collisions, handling them
* then sending the event to object.
*
/************************************************************************/
#pragma once
#include "JMFrameEventHandler.h"
class Player;
class Collidable;
class JMRay;
// Define flags ill be using for my rays
#define FLAG_WALL 1
#define FLAG_PLAYER 2
#define FLAG_ENEMY 4
// Ray query results typedef
typedef std::list<std::pair<float, Collidable*>> rayResults;
class CollisionManager : public JMFrameEventListener
{
public:
CollisionManager(JMFrameEventHandler* frameHndl = NULL);
~CollisionManager();
// Add/remove objects, this is mostly done automatically in the Collidable constructor/deconstruction
void addCollidable(Collidable* c);
void removeCollidable(Collidable* c);
void destroyAllCollidables();
// Updates all bodies, collisions and deletions
void update(float timeSinceLastFrame);
// Finds the pointer to the player in the list
Player* findPlayer();
// Queries the scene for all objects that intersect with the given ray
void rayQuery(JMRay* ray, rayResults& results, int flags = 0);
// Gets the address to the list, however this is a dangerous thing to do so don't edit the list externally
std::list<Collidable*>& getCollidableList();
// For automatically calling update
virtual void eventPreRender(const JMFrameEvent &evt);
private:
// Frame handler
JMFrameEventHandler* frameHandler;
// List
std::list<Collidable*> collidableList;
};
| true |
21dc7c8cc9235c44bae2d4bb59f355f767899401 | C++ | JDR-neu/bezier_curve | /tests/TestPolynomial1D.cpp | UTF-8 | 1,185 | 3.0625 | 3 | [
"MIT"
] | permissive | /**
* @file TestPolynomial1D.cpp
*
* @brief test polynomial
*
* @author btran
*
* @date 2019-08-11
*
* Copyright (c) organization
*
*/
#include "gtest/gtest.h"
#include <bezier/PowerBasisPolynomial1D.hpp>
#include <ctime>
class TestPolynomial : public ::testing::Test
{
protected:
void SetUp() override
{
start_time_ = time(nullptr);
}
void TearDown() override
{
const time_t end_time = time(nullptr);
// expect test time less than 5 sec
EXPECT_LE(end_time - start_time_, 5);
}
time_t start_time_;
};
TEST_F(TestPolynomial, TestInitialization)
{
using Polynomial = robotics::maths::PowerBasisPolynomial1D<double>;
{
std::vector<double> coeffs{1.9, 3.4, 5.7};
Polynomial polynomial(coeffs);
EXPECT_TRUE(polynomial.degree() == coeffs.size() - 1);
}
{
std::vector<double> coeffs{0.0};
Polynomial polynomial(coeffs);
EXPECT_TRUE(polynomial.degree() == coeffs.size() - 1);
}
{
std::vector<double> coeffs{1.0};
Polynomial polynomial(coeffs);
EXPECT_TRUE(polynomial.degree() == coeffs.size() - 1);
}
}
| true |
928b518d9fe1d58b6f870d14c0028845dab6cccb | C++ | umdreamer/leetcodeproblems | /addTwoNumbers.cpp | UTF-8 | 2,949 | 3.734375 | 4 | [] | no_license | /**
* leetcode: rotate list
* medium
*/
#include <cstdio>
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList(int* values, int size) {
ListNode* head = NULL;
ListNode* tail = NULL;
for (int i=0; i<size; ++i) {
ListNode* p = new ListNode(values[i]);
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
void destroyList(ListNode* head) {
ListNode* p = head;
while (p != NULL) {
ListNode* temp = p;
p = p->next;
delete temp;
}
}
void printList(ListNode* head) {
ListNode* p = head;
printf("[");
while (p->next != NULL) {
printf("%d,", p->val);
p = p->next;
}
printf("%d]\n", p->val);
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
printList(l1);
printList(l2);
ListNode* p = l1;
ListNode* q = l2;
ListNode* dummyHead = new ListNode(-1);
ListNode* tail = dummyHead;
bool isCarry = false;
while (p != NULL && q != NULL) {
int sum = p->val + q->val;
ListNode* temp = new ListNode(sum);
tail->next = temp;
tail = temp;
printList(dummyHead->next);
p = p->next;
q = q->next;
}
printf("aaaaaaaaaaa\n");
while (p != NULL) {
ListNode* temp = new ListNode(p->val);
tail->next = temp;
tail = temp;
printList(dummyHead->next);
p = p->next;
}
printf("bbbbbbbbbbbbb\n");
while (q != NULL) {
ListNode* temp = new ListNode(q->val);
tail->next = temp;
tail = temp;
printList(dummyHead->next);
q = q->next;
}
printf("ccccccccccccccc\n");
ListNode* r = dummyHead->next;
for ( ;r->next != NULL; r=r->next) {
int value = r->val;
if (value >= 10) {
r->val = value % 10;
r->next->val += value/10;
}
}
if (r->val >= 10) {
int value = r->val;
r->val = value % 10;
r->next = new ListNode(value/10);
}
printList(dummyHead->next);
ListNode* head = dummyHead->next;
delete dummyHead;
return head;
}
private:
};
int main() {
const int M = 4;
const int N = 6;
int a[M] = {1,2,3,5};
int b[N] = {4,6,8,2,3,5};
Solution sln;
for (int i=0; i<1; ++i) {
ListNode* l1= createList(a, M);
ListNode* l2= createList(b, N);
printf("%d-----\n", i);
ListNode* newHead = sln.addTwoNumbers(l1, l2);
printList(newHead);
destroyList(l1);
destroyList(l2);
destroyList(newHead);
}
return 0;
}
| true |
27ba0175e06484cecf98d93f2d2027c47d409b5a | C++ | devidattadehury/cs141 | /lab7q2.cpp | UTF-8 | 649 | 4 | 4 | [] | no_license | #include<iostream>
using namespace std;
//recursion to display all natural no.s from lowest to highest
//i is lowest and a is highest.
int numbers(int i,int a)
{
if (a >= i)
{
//displaying no.s starting from lowest
cout <<i <<endl;
numbers(i + 1,a);
}
else
{cout <<endl;
}
}
//main function
int main()
{
//we define i=1 as display starts from 1 in the question
//ask for input from user
int n,i=1;
cout<<"Enter a number to get natural no.s from 1 to that no.: ";
cin >> n;
//display the result obtained by the recursion
//as i=1 we should get natural no.s from 1 to the desired input
numbers(i,n);
return 0;
}
| true |
ccbf331c6e077edb117ef22878c4fe4d57f111be | C++ | Aeopp/DevilMayCry- | /Engine/Header/TEXTURE.H | UHC | 987 | 2.546875 | 3 | [] | no_license | #ifndef __TEXTURE_H__
#define __TEXTURE_H__
#include "Resource.h"
#include <any>
BEGIN(ENGINE)
class ENGINE_DLL Texture final : public Resource
{
private:
LPDIRECT3DTEXTURE9 m_pTexture;
D3DXIMAGE_INFO m_tInfo;
TEXTUREDESC m_tDesc;
private:
explicit Texture(LPDIRECT3DDEVICE9 const _pDevice);
explicit Texture(const Texture& _rOther);
virtual ~Texture() = default;
// Resource() ӵ
virtual void Free() override;
public:
static Texture* Create(LPDIRECT3DDEVICE9 const _pDevice,
const std::filesystem::path _Path ,
const std::any& InitParams);
// Resource() ӵ
virtual Resource* Clone() override;
virtual void Editor()override;
virtual std::string GetName()override;
private:
HRESULT LoadTextureFromFile(const std::filesystem::path _Path);
public:
LPDIRECT3DTEXTURE9 GetTexture();
D3DXIMAGE_INFO GetInfo();
TEXTUREDESC GetDesc();
void SetDesc(const TEXTUREDESC & _tDesc);
};
END
#endif // !__TEXTURE_H__ | true |
baa12aea4d6b57ffe6446e7a9a5105f51f89363a | C++ | anmolmishra02/Dfs-and-bfs | /level order traversal.cpp | UTF-8 | 1,137 | 3.296875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class treenode
{
public:
int val;
treenode*left;
treenode*right;
treenode(int v)
{
val=v;
this->left=NULL;
this->right=NULL;
}
};
vector<vector<int>> levelorder(treenode*root)
{
vector<vector<int>> ans;
if(root==NULL)
{
return ans;
}
queue<treenode*> q;
q.push(root);
while(!q.empty())
{
int levelsize=q.size();
vector<int> curr;
for(int i=0;i<levelsize;i++)
{
treenode*n=q.front();
q.pop();
curr.push_back(n->val);
if(n->left!=NULL)
{
q.push(n->left);
}
if(n->right!=NULL)
{
q.push(n->right);
}
}
ans.push_back(curr);
}
return ans;
}
int main()
{
treenode*root=new treenode(1);
treenode*lef=new treenode(2);
treenode*righ=new treenode(3);
root->left=lef;
root->right=righ;
root->left->left=new treenode(4);
root->left->right=new treenode(5);
root->right->right=new treenode(7);
vector<vector<int>> ans=levelorder(root);
for(auto m:ans)
{
for(auto i:m)
{
cout<<i<<" ";
}
cout<<endl;
}
}
| true |
152061ce2fc7fcc697c65f43dfc46a7da3170536 | C++ | rstraight/T | /T/T/SymTable.h | UTF-8 | 558 | 2.546875 | 3 | [] | no_license | #ifndef SYMTABLE_H
#define SYMTABLE_H
#include <iostream>
#include <list>
#include <deque>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
class SymTable
{
public:
SymTable();
~SymTable();
int addSymbol(string name, string value);
int setSymbol(string name, string value);
int setSymbol(string name, int value);
string getSymbol(string name);
int getSymbolInt(string name);
private:
deque<string> sym;
deque<string> val;
};
#endif // SYMTABLE_H
| true |
1727dc5d507d7642749406f88c6a7375a6848c06 | C++ | CrustyAuklet/xmega-ecpp | /include/device/peripherals/GPIO.hpp | UTF-8 | 2,136 | 2.703125 | 3 | [] | no_license | /**
* None-GPIO (id I6085)
* General Purpose IO
*
*
*/
#pragma once
#include "device/register.hpp"
#include <cstdint>
namespace device {
/**
* GPIO
* General Purpose IO Registers
* Size: 16 bytes
*/
template <addressType BASE_ADDRESS>
struct GPIO_t {
/// General Purpose IO Register 0 - 1 bytes
struct GPIOR0 : public reg8_t<BASE_ADDRESS + 0x0000> {
};
/// General Purpose IO Register 1 - 1 bytes
struct GPIOR1 : public reg8_t<BASE_ADDRESS + 0x0001> {
};
/// General Purpose IO Register 2 - 1 bytes
struct GPIOR2 : public reg8_t<BASE_ADDRESS + 0x0002> {
};
/// General Purpose IO Register 3 - 1 bytes
struct GPIOR3 : public reg8_t<BASE_ADDRESS + 0x0003> {
};
/// General Purpose IO Register 4 - 1 bytes
struct GPIOR4 : public reg8_t<BASE_ADDRESS + 0x0004> {
};
/// General Purpose IO Register 5 - 1 bytes
struct GPIOR5 : public reg8_t<BASE_ADDRESS + 0x0005> {
};
/// General Purpose IO Register 6 - 1 bytes
struct GPIOR6 : public reg8_t<BASE_ADDRESS + 0x0006> {
};
/// General Purpose IO Register 7 - 1 bytes
struct GPIOR7 : public reg8_t<BASE_ADDRESS + 0x0007> {
};
/// General Purpose IO Register 8 - 1 bytes
struct GPIOR8 : public reg8_t<BASE_ADDRESS + 0x0008> {
};
/// General Purpose IO Register 9 - 1 bytes
struct GPIOR9 : public reg8_t<BASE_ADDRESS + 0x0009> {
};
/// General Purpose IO Register 10 - 1 bytes
struct GPIORA : public reg8_t<BASE_ADDRESS + 0x000A> {
};
/// General Purpose IO Register 11 - 1 bytes
struct GPIORB : public reg8_t<BASE_ADDRESS + 0x000B> {
};
/// General Purpose IO Register 12 - 1 bytes
struct GPIORC : public reg8_t<BASE_ADDRESS + 0x000C> {
};
/// General Purpose IO Register 13 - 1 bytes
struct GPIORD : public reg8_t<BASE_ADDRESS + 0x000D> {
};
/// General Purpose IO Register 14 - 1 bytes
struct GPIORE : public reg8_t<BASE_ADDRESS + 0x000E> {
};
/// General Purpose IO Register 15 - 1 bytes
struct GPIORF : public reg8_t<BASE_ADDRESS + 0x000F> {
};
};
} // namespace device
| true |
dc3bda37a75e779b57c4943bbc89253c229d3814 | C++ | dan1109/CasualGame | /CasualGame/PlayerInputManager.cpp | UTF-8 | 5,966 | 2.53125 | 3 | [] | no_license | #include "PlayerInputManager.h"
#include "Game.h"
#include "Player.h"
#include "Config.h"
#include <cmath>
PlayerInputManager::PlayerInputManager() {}
void PlayerInputManager::handleInput(const sf::Event& event, const sf::Vector2f& mousePosition, Game& game)
{
if (event.type == sf::Event::MouseButtonPressed)
{
handleShot();
}
if (event.type == sf::Event::MouseMoved)
{
//handleMouselook(event, game.getWindow());
}
//escape go to main menu
if (event.type == sf::Event::KeyPressed)
{
// handle controls
if ((event.key.code == sf::Keyboard::Left) || (event.key.code == sf::Keyboard::A))
{
m_left = true;
}
else if ((event.key.code == sf::Keyboard::Right) || (event.key.code == sf::Keyboard::D))
{
m_right = true;
}
else if ((event.key.code == sf::Keyboard::Up) || (event.key.code == sf::Keyboard::W))
{
m_forward = true;
}
else if ((event.key.code == sf::Keyboard::Down) || (event.key.code == sf::Keyboard::S))
{
m_backward = true;
}
}
if (event.type == sf::Event::KeyReleased)
{
// handle controls
if ((event.key.code == sf::Keyboard::Left) || (event.key.code == sf::Keyboard::A))
{
m_left = false;
}
if ((event.key.code == sf::Keyboard::Right) || (event.key.code == sf::Keyboard::D))
{
m_right = false;
}
if ((event.key.code == sf::Keyboard::Up) || (event.key.code == sf::Keyboard::W))
{
m_forward = false;
}
if ((event.key.code == sf::Keyboard::Down) || (event.key.code == sf::Keyboard::S))
{
m_backward = false;
}
if ((event.key.code == sf::Keyboard::Space) || (event.key.code == sf::Keyboard::LControl))
{
handleShot();
}
}
}
void PlayerInputManager::updatePlayerMovement(const double fts, std::shared_ptr<Player> m_player, const std::vector<std::vector<int> >& m_levelRef)
{
calculateShotTime(fts);
//update position
if (isMoving())
{
// convert ms to seconds
double moveSpeed = fts * 5.0; //the constant value is in squares/second
double rotSpeed = fts * g_lookSpeed;
if (m_left)
{
//both camera direction and camera plane must be rotated
double oldDirX = m_player->m_dirX;
m_player->m_dirX = m_player->m_dirX * std::cos(rotSpeed) - m_player->m_dirY * std::sin(rotSpeed);
m_player->m_dirY = oldDirX * std::sin(rotSpeed) + m_player->m_dirY * std::cos(rotSpeed);
double oldPlaneX = m_player->m_planeX;
m_player->m_planeX = m_player->m_planeX * std::cos(rotSpeed) - m_player->m_planeY * std::sin(rotSpeed);
m_player->m_planeY = oldPlaneX * std::sin(rotSpeed) + m_player->m_planeY * std::cos(rotSpeed);
}
if (m_right)
{
//both camera direction and camera plane must be rotated
double oldDirX = m_player->m_dirX;
m_player->m_dirX = m_player->m_dirX * std::cos(-rotSpeed) - m_player->m_dirY * std::sin(-rotSpeed);
m_player->m_dirY = oldDirX * std::sin(-rotSpeed) + m_player->m_dirY * std::cos(-rotSpeed);
double oldPlaneX = m_player->m_planeX;
m_player->m_planeX = m_player->m_planeX * std::cos(-rotSpeed) - m_player->m_planeY * std::sin(-rotSpeed);
m_player->m_planeY = oldPlaneX * sin(-rotSpeed) + m_player->m_planeY * std::cos(-rotSpeed);
}
if (m_forward)
{
if (m_levelRef[int(m_player->m_posX + m_player->m_dirX * moveSpeed)][int(m_player->m_posY)] == 0)
m_player->m_posX += m_player->m_dirX * moveSpeed;
if (m_levelRef[int(m_player->m_posX)][int(m_player->m_posY + m_player->m_dirY * moveSpeed)] == 0)
m_player->m_posY += m_player->m_dirY * moveSpeed;
}
if (m_backward)
{
if (m_levelRef[int(m_player->m_posX - m_player->m_dirX * moveSpeed)][int(m_player->m_posY)] == 0)
m_player->m_posX -= m_player->m_dirX * moveSpeed;
if (m_levelRef[int(m_player->m_posX)][int(m_player->m_posY - m_player->m_dirY * moveSpeed)] == 0)
m_player->m_posY -= m_player->m_dirY * moveSpeed;
}
if (m_stepLeft)
{
// rotate vector in 90 ccw use Vector(-y, x)
auto dirX = -m_player->m_dirY;
auto dirY = m_player->m_dirX;
if (m_levelRef[int(m_player->m_posX + dirX * moveSpeed)][int(m_player->m_posY)] == 0)
m_player->m_posX += dirX * moveSpeed;
if (m_levelRef[int(m_player->m_posX)][int(m_player->m_posY + dirY * moveSpeed)] == 0)
m_player->m_posY += dirY * moveSpeed;
}
if (m_stepRight)
{
// rotate vector in 90 cw use Vector(y, -x)
auto dirX = m_player->m_dirY;
auto dirY = -m_player->m_dirX;
if (m_levelRef[int(m_player->m_posX + dirX * moveSpeed)][int(m_player->m_posY)] == 0)
m_player->m_posX += dirX * moveSpeed;
if (m_levelRef[int(m_player->m_posX)][int(m_player->m_posY + dirY * moveSpeed)] == 0)
m_player->m_posY += dirY * moveSpeed;
}
//stop rotating on mouselook
//m_left = false;
//m_right = false;
}
}
void PlayerInputManager::calculateShotTime(double fts)
{
if (m_shotTime < 0.0)
{
m_shooting = false;
}
else
{
m_shotTime -= fts;
}
if (m_gunShotDelay > 0.0)
{
m_gunShotDelay -= fts;
}
}
void PlayerInputManager::handleShot()
{
if (m_shotTime > 0.0 || m_gunShotDelay > 0.0)
{
m_shooting = false;
return;
}
m_shotTime = g_gunShotTime;
m_gunShotDelay = g_gunShotDelayTime;
m_shooting = true;
}
void PlayerInputManager::handleMouselook(const sf::Event & event, const sf::RenderWindow& window)
{
int mouseX = event.mouseMove.x;
int mouseY = event.mouseMove.y;
m_mouseDelta = mouseX - m_lastMouseX;
m_lastMouseX = mouseX;
int windowX = static_cast<int>(window.getSize().x);
int windowY = static_cast<int>(window.getSize().y);
//if mouse is out of screen, put it to the center
if (mouseX <= m_mouseBorder || mouseX >= windowX - m_mouseBorder ||
mouseY <= m_mouseBorder || mouseY >= windowY - m_mouseBorder)
{
auto centerX = windowX / 2;
auto centerY = windowY / 2;
sf::Mouse::setPosition(sf::Vector2i(centerX, centerY), window);
m_lastMouseX = centerX;
}
if (m_mouseDelta < 0)
{
m_right = false;
m_left = true;
}
else if (m_mouseDelta > 0)
{
m_left = false;
m_right = true;
}
else
{
m_left = false;
m_right = false;
}
} | true |
0eac259ed43bd91f421d3c7e87303eb7f101c422 | C++ | eglrp/myds-old | /Forest/Forest.h | GB18030 | 6,350 | 3.703125 | 4 | [] | no_license | #include "MultiTree.h"
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
/**
* Forest: ɺֵܱʾʾĶɵɭ
* note: Ҫʶĵײָṹ˱ΪԪ
*/
class Forest
{
public:
// 1. constructor
Forest(); // ĬϹ캯յɭ
Forest(const vector<MultiTree> &res); // 캯Ӷбɭ
Forest(const vector<TreeNode *> &res);// 캯Ӷĸָбɭ
// 2. copy_controller
Forest(const Forest &other) = delete; // ÿ캯
Forest & operator = (const Forest &other) = delete; // ÿֵ
// 3. methods
BinaryTreeNode *convertToBinaryTree(); // ǰɭתΪ
static vector<TreeNode *> convertToForest(BinaryTreeNode *root); // ĶתΪɭ
vector<int> preorder(); // ɵǰɭֵǰ
vector<int> postorder(); // ɵǰɭֵĺ
// 4. destructor
~Forest();
private:
// 5. domains
vector<MultiTree> treeroot;
// 6. private functions
static TreeNode *convertMultiToBinaryTree(BinaryTreeNode *root); // 任Ϊ
};
/**
* Forest: ĬϹ캯һյɭ
*/
Forest::Forest()
{
}
/**
* Forest: 캯Ӷбɭ
*/
Forest::Forest(const vector<MultiTree> &res)
{
for(int i=0;i<res.size();i++)
{
treeroot.push_back(res[i]);
}
}
/**
* Forest: 캯Ӷĸָбɭ
*/
Forest::Forest(const vector<TreeNode *> &res)
{
for(int i=0;i<res.size();i++)
{
treeroot.push_back(MultiTree(res[i]));
}
}
/**
* convertToBinaryTree: ǰɭתΪ
* return: ɵǰɭתõĶ
* note: ɭתɶĻʾ
(1) ɭеÿöתΪ
(2) ӶתΪ㷨УõÿöĸrightָΪգعһ£Ϊת㷨ǣrightָڵǰֵָbrotherleftָڵǰĶָchild
(3) ֻҪɭеһrightָָڶڶrightָָ...n-1rightָָn
*/
BinaryTreeNode *Forest::convertToBinaryTree()
{
// 1. ǰɭеÿһɶתΪ
vector<BinaryTreeNode *> res;
for(int i=0;i<treeroot.size();i++)
{
res.push_back(treeroot[i].convertToBinaryTree());
}
// 2. νiĸrightָָi+1
for(int i=0;i<treeroot.size()-1;i++)
{
res[i]->right=res[i+1];
}
return res[0];
}
/**
* convertToForest: ĶתΪɭ
* return: ɸĶתõɭ
* note 1: ɭתΪ㷨õתΪɭֵ㷨
* note 2: ɭתΪ㷨УȽɭеÿһöתΪȻiörightָָi+1ö
* note 3: ˽תΪɭʵϾ̵̣IJ£
(1) Ӹ㿪ʼrightָҲӽķ;ÿһ㶼¼Ϊɭһĸ㣬ͬʱrightָΪ
(2) еõĶתΪתdzнchildָڶжӦleftָ룬нbrotherָڶжӦrightָ
*/
vector<TreeNode *> Forest::convertToForest(BinaryTreeNode *root)
{
// 1. ȷ
vector<BinaryTreeNode *> lis;
BinaryTreeNode *now=root;
while(now)
{
lis.push_back(now);
BinaryTreeNode *temp=now->right;
now->right=NULL;
now=temp;
}
// 2. ȻתΪ
vector<TreeNode *> res;
for(int i=0;i<lis.size();i++)
{
res.push_back(Forest::convertMultiToBinaryTree(lis[i]));
}
return res;
}
TreeNode *Forest::convertMultiToBinaryTree(BinaryTreeNode *root)
{
if(!root)
return NULL;
else
{
TreeNode *res=new TreeNode(root->val);
res->child=convertMultiToBinaryTree(root->left);
res->brother=convertMultiToBinaryTree(root->right);
return res;
}
}
/**
* preorder: ɵǰɭֵǰ
* return: ǰɭֵǰ
* note: ɭֵǰ㷨ҪԸΪ: ȡɭеÿһÿνǰ
*/
vector<int> Forest::preorder()
{
vector<int> res;
for(int i=0;i<treeroot.size();i++)
{
vector<int> temp=treeroot[i].preorder();
for(int i=0;i<temp.size();i++)
{
res.push_back(temp[i]);
}
}
return res;
}
/**
* postorder: ɵǰɭֵĺ
* return: ǰɭֵĺ
* note: ɭֵĺ㷨ҪԸΪ: ȡɭеÿһÿνк
*/
vector<int> Forest::postorder()
{
vector<int> res;
for(int i=0;i<treeroot.size();i++)
{
vector<int> temp=treeroot[i].postorder();
for(int i=0;i<temp.size();i++)
{
res.push_back(temp[i]);
}
}
return res;
}
/**
* Forest: ɭֵ
* note: ɭֵʵϲҪκεĶΪvectorлԶMultiTree
*/
Forest::~Forest()
{
}
| true |
2af43de221d646bbffc1186be43308d76074cd65 | C++ | hackerlank/buzz-server | /src/game_server/server/extension/soul/soul_actor_manager.cc | UTF-8 | 1,705 | 2.5625 | 3 | [] | no_license | //
// Summary: buzz source code.
//
// Author: Tony.
// Email: tonyjobmails@gmail.com.
// Last modify: 2013-06-14 15:42:15.
// File name: soul_actor_manager.cc
//
// Description:
// Define class SoulActorManager.
//
#include "game_server/server/extension/soul/soul_actor_manager.h"
#include "game_server/server/extension/soul/soul_actor.h"
namespace game {
namespace server {
namespace soul {
SoulActor *SoulActorManager::Get(core::uint64 id) {
ActorHashmap::iterator iterator = this->actors_.find(id);
if(iterator != this->actors_.end()) {
return iterator->second;
}
return NULL;
}
bool SoulActorManager::Add(SoulActor *actor) {
// 检测指针是否合法
if(actor == NULL) {
return false;
}
// 检测是否存在
ActorHashmap::iterator iterator = this->actors_.find(actor->GetID());
if(iterator != this->actors_.end()) {
return false;
}
// 加入管理器中
this->actors_.insert(std::make_pair(actor->GetID(), actor));
return true;
}
SoulActor *SoulActorManager::Remove(core::uint64 id) {
SoulActor *actor = NULL;
ActorHashmap::iterator iterator = this->actors_.find(id);
if(iterator != this->actors_.end()) {
actor = iterator->second;
this->actors_.erase(iterator);
}
return actor;
}
void SoulActorManager::DailyClean() {
ActorHashmap::iterator iterator = this->actors_.begin();
for(; iterator != this->actors_.end(); ++iterator) {
SoulActor *soul_actor = iterator->second;
if(NULL == soul_actor) {
LOG_ERROR("SoulActor is null.");
continue;
}
if(soul_actor->CheckLoadFinish() == false) {
continue;
}
soul_actor->DailyClean();
}
}
} // namespace soul
} // namespace server
} // namespace game
| true |
2c10aa7172f381cfb4d07cc835c94f19ebd747d8 | C++ | DenisDesimon/LeetCode | /1352_Product_of_the_Last_K_Numbers.cpp | UTF-8 | 1,198 | 3.953125 | 4 | [] | no_license | //#1352 Product of the Last K Numbers - https://leetcode.com/problems/product-of-the-last-k-numbers/
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class ProductOfNumbers {
vector<int> Prefix;
public:
ProductOfNumbers() {
Prefix.push_back(1);
}
void add(int num) {
if(num == 0)
Prefix = {1};
else
Prefix.push_back(Prefix.back() * num);
}
int getProduct(int k) {
if(k >= (int)Prefix.size())
return 0;
return Prefix.back() / Prefix[Prefix.size() - 1 - k];
}
};
/**
* Your ProductOfNumbers object will be instantiated and called as such:
* ProductOfNumbers* obj = new ProductOfNumbers();
* obj->add(num);
* int param_2 = obj->getProduct(k);
*/
int main()
{
ProductOfNumbers solution;
solution.add(3);
solution.add(5);
solution.add(7);
int expected_answer = 35;
int given_k = 2;
assert(solution.getProduct(given_k) == expected_answer);
solution.add(0);
given_k = 2;
expected_answer = 0;
assert(solution.getProduct(given_k) == expected_answer);
return 0;
}
| true |
88333f50156cc744335d6a3bb4aadcbf5f5c3fc7 | C++ | bsuljic1/Programming-techniques | /TP2018/T12/Z6/main.cpp | UTF-8 | 7,956 | 3.171875 | 3 | [] | no_license | /*
TP 16/17 (Tutorijal 12, Zadatak 6)
Autotestove napisao Kerim Hodzic. Sve primjedbe/zalbe, sugestije
i pitanja slati na mail: khodzic2@etf.unsa.ba.
Vrsit ce se provjera na prepisivanje tutorijala (na kraju semestra)
*/
#include <iostream>
#include <iomanip>
#include <cstring>
#include <stdexcept>
#include <new>
template <typename TipEl>
class Matrica
{
int br_redova, br_kolona;
TipEl **elementi;
char ime_matrice;
static TipEl **AlocirajMemoriju(int br_redova, int br_kolona);
static void DealocirajMemoriju(TipEl **elementi, int br_redova);
void KopirajElemente(TipEl **elementi);
public:
Matrica(int br_redova, int br_kolona, char ime = 0);
Matrica(const Matrica &m);
Matrica(Matrica &&m);
~Matrica()
{
DealocirajMemoriju(elementi, br_redova);
}
Matrica &operator =(const Matrica &m);
Matrica &operator =(Matrica &&m);
Matrica operator *(const Matrica &m2);
Matrica operator *(int broj);
Matrica operator - (const Matrica &m2);
Matrica operator + (const Matrica &m2);
Matrica &operator +=(const Matrica &m2);
Matrica &operator -=(const Matrica &m2);
Matrica &operator *=(const Matrica &m2);
template <typename Tip1>
friend std::ostream &operator << (std::ostream &tok, const Matrica<Tip1> &m);
template <typename Tip1>
friend std::istream &operator >> (std::istream &tok, Matrica<Tip1> &m);
Matrica &operator *=(int broj);
template <typename Tip1>
friend Matrica<Tip1> &operator *=(Matrica<Tip1> &m, int broj);
template <typename Tip1>
friend Matrica<Tip1> operator *(int broj, Matrica<Tip1> &m);
TipEl *&operator [](int i)
{
return elementi[i];
}
TipEl *operator [](int i) const
{
return elementi[i];
}
TipEl &operator ()(int i, int j)
{
if(i < 1 || i > br_redova || j < 1 || j > br_kolona) throw std::range_error("Neispravan indeks");
return elementi[i-1][j-1];
}
TipEl operator ()(int i, int j) const
{
if(i < 1 || i > br_redova || j < 1 || j > br_kolona) throw std::range_error("Neispravan indeks");
return elementi[i-1][j-1];
}
};
template <typename TipEl>
TipEl ** Matrica<TipEl>::AlocirajMemoriju(int br_redova, int br_kolona)
{
TipEl **elementi = new TipEl*[br_redova] {};
try {
for(int i = 0; i < br_redova; i++) elementi[i] = new TipEl[br_kolona];
} catch(...) {
DealocirajMemoriju(elementi, br_redova);
throw;
}
return elementi;
}
template <typename TipEl>
void Matrica<TipEl>::DealocirajMemoriju(TipEl **elementi, int br_redova)
{
for(int i = 0; i < br_redova; i++) delete[] elementi[i];
delete[] elementi;
}
template <typename TipEl>
Matrica<TipEl>::Matrica(int br_redova, int br_kolona, char ime) :
br_redova(br_redova), br_kolona(br_kolona), ime_matrice(ime),
elementi(AlocirajMemoriju(br_redova, br_kolona)) {}
template <typename TipEl>
void Matrica<TipEl>::KopirajElemente(TipEl **elementi)
{
for(int i = 0; i < br_redova; i++)
for(int j = 0; j < br_kolona; j++)
Matrica::elementi[i][j] = elementi[i][j];
}
template <typename TipEl>
Matrica<TipEl>::Matrica(const Matrica<TipEl> &m) : br_redova(m.br_redova),
br_kolona(m.br_kolona), ime_matrice(m.ime_matrice),
elementi(AlocirajMemoriju(m.br_redova, m.br_kolona))
{
KopirajElemente(m.elementi);
}
template <typename TipEl>
Matrica<TipEl>::Matrica(Matrica<TipEl> &&m) : br_redova(m.br_redova),
br_kolona(m.br_kolona), elementi(m.elementi), ime_matrice(m.ime_matrice)
{
m.br_redova = 0;
m.elementi = nullptr;
}
template <typename TipEl>
Matrica<TipEl> &Matrica<TipEl>::operator =(const Matrica<TipEl> &m)
{
if(br_redova < m.br_redova || br_kolona < m.br_kolona) {
TipEl **novi_prostor = AlocirajMemoriju(m.br_redova, m.br_kolona);
DealocirajMemoriju(elementi, br_redova);
elementi = novi_prostor;
} else if(br_redova > m.br_redova)
for(int i = m.br_redova; i < br_redova; i++) delete elementi[i];
br_redova = m.br_redova;
br_kolona = m.br_kolona;
ime_matrice = m.ime_matrice;
KopirajElemente(m.elementi);
return *this;
}
template <typename TipEl>
Matrica<TipEl> &Matrica<TipEl>::operator =(Matrica<TipEl> &&m)
{
std::swap(br_redova, m.br_redova);
std::swap(br_kolona, m.br_kolona);
std::swap(ime_matrice, m.ime_matrice);
std::swap(elementi, m.elementi);
return *this;
}
template <typename TipEl>
Matrica<TipEl> Matrica<TipEl>::operator + (const Matrica<TipEl> &m2)
{
if(br_redova != m2.br_redova || br_kolona != m2.br_kolona) throw std::domain_error("Matrice nemaju jednake dimenzije!");
Matrica<TipEl> m3(br_redova, br_kolona);
for(int i = 0; i < br_redova; i++)
for(int j = 0; j < br_kolona; j++)
m3.elementi[i][j] = elementi[i][j] + m2.elementi[i][j];
return m3;
}
template <typename TipEl>
std::ostream &operator << (std::ostream &tok, const Matrica<TipEl> &m)
{
int duzina = tok.width();
for(int i = 0; i < m.br_redova; i++) {
for(int j = 0; j < m.br_kolona; j++)
tok << std::setw(duzina) << m.elementi[i][j];
tok << std::endl;
}
return tok;
}
template <typename TipEl>
std::istream &operator >> (std::istream &tok, Matrica<TipEl> &m)
{
for(int i = 0; i < m.br_redova; i++)
for(int j = 0; j < m.br_kolona; j++) {
std::cout << m.ime_matrice << "(" << i + 1 << "," << j + 1 << ") = ";
tok >> m.elementi[i][j];
}
return tok;
}
template <typename TipEl>
Matrica<TipEl> Matrica<TipEl>::operator *(int broj)
{
auto m3 = *this;
for(int i = 0; i < br_redova; i++) {
for(int j = 0; j < br_kolona; j++) {
m3.elementi[i][j]*=broj;
}
}
return m3;
}
template <typename TipEl>
Matrica<TipEl> Matrica<TipEl>::operator *(const Matrica<TipEl> &m2)
{
if(br_kolona != m2.br_redova) throw std::domain_error("Matrice nisu saglasne za mnozenje");
Matrica<TipEl> nova(br_redova, m2.br_kolona);
for(int i = 0; i < br_redova; i++) {
for(int j = 0; j < m2.br_kolona; j++) {
for(int k = 0; k < br_kolona; k++) {
nova.elementi[i][j] += elementi[i][k]*m2.elementi[k][j];
}
}
}
return nova;
}
template <typename TipEl>
Matrica<TipEl> Matrica<TipEl>::operator - (const Matrica<TipEl> &m2)
{
if(br_redova != m2.br_redova || br_kolona != m2.br_kolona) throw std::domain_error("Matrice nemaju jednake dimenzije!");
Matrica<TipEl> m3(br_redova, br_kolona);
for(int i = 0; i < br_redova; i++)
for(int j = 0; j < br_kolona; j++)
m3.elementi[i][j] = elementi[i][j] - m2.elementi[i][j];
return m3;
}
template <typename TipEl>
Matrica<TipEl> &Matrica<TipEl>::operator +=(const Matrica<TipEl> &m2)
{
if(br_redova != m2.br_redova || br_kolona != m2.br_kolona)
throw std::domain_error("Matrice nemaju jednake dimenzije!");
for(int i = 0; i < br_redova; i++)
for(int j = 0; j < br_kolona; j++)
elementi[i][j] = elementi[i][j] + m2.elementi[i][j];
return *this;
}
template <typename TipEl>
Matrica<TipEl> &Matrica<TipEl>::operator -=(const Matrica<TipEl> &m2)
{
if(br_redova != m2.br_redova || br_kolona != m2.br_kolona)
throw std::domain_error("Matrice nemaju jednake dimenzije!");
for(int i = 0; i < br_redova; i++)
for(int j = 0; j < br_kolona; j++)
elementi[i][j] = elementi[i][j] - m2.elementi[i][j];
return *this;
}
template <typename TipEl>
Matrica<TipEl> &Matrica<TipEl>::operator *=(const Matrica<TipEl> &m2)
{
if(br_kolona != m2.br_redova) throw std::domain_error("Matrice nisu saglasne za mnozenje");
*this = *this * m2;
return *this;
}
template <typename TipEl>
Matrica<TipEl> &Matrica<TipEl>::operator *=(int broj)
{
*this = *this * broj;
return *this;
}
template <typename Tip1>
Matrica<Tip1> operator *(int broj, Matrica<Tip1> &m){
auto m3 = m;
for(int i = 0; i < m.br_redova; i++) {
for(int j = 0; j < m.br_kolona; j++) {
m3.elementi[i][j]*=broj;
}
}
return m3;
}
int main()
{
int m, n;
std::cout << "Unesi broj redova i kolona za matrice:\n";
std::cin >> m >> n;
try {
Matrica<double> a(m, n, 'A'), b(m, n, 'B');
std::cout << "Unesi matricu A: \n";
std::cin >> a;
std::cout << "Unesi matricu B: \n";
std::cin >> b;
std::cout << "Zbir ove dvije matrice je: \n";
std::cout << std::setw(7) << a + b;
} catch(std::bad_alloc) {
std::cout << "Nema dovoljno memorije! \n";
}
return 0;
}
| true |
42e3d6f9faabb72109f1e39c2b920846c577de2f | C++ | alexandrofernando/java | /acm/P2104__Kth_Number.cpp | UTF-8 | 695 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
struct Number {
int value;
unsigned index;
};
int compare(const void *a,const void *b)
{
return ((const Number *)a)->value-((const Number *)b)->value;
}
Number numbers[100001];
int main()
{
int i;
int n,m;
unsigned I,J,K;
int count;
scanf("%d%d",&n,&m);
for (i=0;i<n;i++) {
scanf("%d",&numbers[i].value);
numbers[i].index=i+1;
}
qsort(numbers,n,sizeof(*numbers),compare);
for (i=0;i<m;i++) {
scanf("%u%u%u",&I,&J,&K);
unsigned len = J - I;
count=0;
Number *p=numbers;
while (true) {
if (p->index-I<=len) {
count++;
if (count==K) {
printf("%d\n",p->value);
break;
}
}
p++;
}
}
return 0;
} | true |
86605195604e108e5db281a48c143cb3cebe9aeb | C++ | fngoc/CppModules | /Module04/ex03/Character.hpp | UTF-8 | 552 | 2.84375 | 3 | [] | no_license | #ifndef EX03_CHARACTER_HPP
#define EX03_CHARACTER_HPP
#include "ICharacter.hpp"
class Character : public ICharacter {
public:
Character(string name);
Character(Character& сharacter);
virtual ~Character();
Character& operator=(const Character& сharacter);
virtual const string& getName() const;
virtual void equip(AMateria* m);
virtual void unequip(int idx);
virtual void use(int idx, ICharacter& target);
private:
string _name;
AMateria* _materia[4];
};
#endif
| true |
1c66f25b71d0257056df2a0caf73c1980ba8d7e0 | C++ | caballa/covenant | /tools/covenant.cpp | UTF-8 | 6,112 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstdlib>
#include <boost/program_options.hpp>
#include <Common.h>
#include <parser/ParseUtils.h>
#include <parser/ParseProblem.h>
#include <CFG.h>
#include <Solver.h>
#include <regsolver/Product.h>
using namespace std;
using namespace covenant;
namespace po = boost::program_options;
int main (int argc, char** argv)
{
typedef Sym edge_sym_t;
typedef Solver<edge_sym_t> solver_t;
typedef RegSolver<edge_sym_t> reg_solver_t;
// Main flags
int max_cegar_iter=-1;
GeneralizationMethod gen = GREEDY;
AbstractMethod abs = CYCLE_BREAKING;
// Heuristics flags
// - regular solver will try to find a witness starting from this length
int shortest_witness = 0;
// - increase the witness length after n iterations -1 disable this option.
int freq_incr_witness = -1;
// - increment the witness length by n but only if freq_incr_witness >= 0
unsigned incr_witness = 1;
// Other flags
bool is_dot_enabled=false;
unsigned num_solutions = 1;
string header("Covenant: semi-decider for intersection of context-free languages\n");
header += string ("Authors : G.Gange, J.A.Navas, P.Schachte, H.Sondergaard, and P.J.Stuckey\n");
header += string ("Usage : covenant [Options] file");
po::options_description config("General options ");
config.add_options()
("help,h", "print help message")
("dot" ,
"print solutions and emptiness proofs in dot format as well as the result of abstractions and refinements")
("verbose,v" , "verbose mode")
("stats,s", "Show some statistics and exit")
("solutions" , po::value<unsigned>(&num_solutions)->default_value(1),
"enumerate up to n solutions (default n=1)")
("iter,i", po::value<int>(&max_cegar_iter)->default_value(-1),
"maximum number of CEGAR iterations (default no limit)")
("abs,a", po::value<AbstractMethod>(&abs)->default_value(CYCLE_BREAKING),
"choose abstraction method [sigma-star|cycle-breaking]")
("gen,g", po::value<GeneralizationMethod>(&gen)->default_value(GREEDY),
"choose generalization method [greedy|max-gen]")
;
po::options_description hidden_params("");
hidden_params.add_options()
("input-file", po::value<string>(), "input file")
;
po::options_description cegar_params("(unsound) cegar options ");
cegar_params.add_options()
("l", po::value<int>(&shortest_witness)->default_value(0),
"shortest length of the witness (default 0)")
("freq-incr-witness", po::value<int>(&freq_incr_witness)->default_value(-1),
"how often increasing witnesses' length")
("delta-incr-witness", po::value<unsigned>(&incr_witness)->default_value(1),
"how much witnesses' length is incremented")
;
po::options_description log("Logging Options");
log.add_options()
("log", po::value<std::vector<string> >(), "Enable specified log level")
;
po::positional_options_description p;
p.add("input-file", -1);
po::options_description cmmdline_options;
cmmdline_options.add(config);
cmmdline_options.add(hidden_params);
cmmdline_options.add(cegar_params);
cmmdline_options.add(log);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(cmmdline_options).
positional(p).
run(), vm);
po::notify(vm);
}
catch(error &e)
{
cerr << "covenant error:" << e << endl;
return 0;
}
if (vm.count("help"))
{
cout << header << endl << config << endl;
return 0;
}
std::string in;
bool file_opened = false;
if (vm.count ("input-file"))
{
std::string infile = vm ["input-file"].as<std::string> ();
std::ifstream fd;
fd.open (infile.c_str ());
if (fd.good ())
{
file_opened = true;
while (!fd.eof ())
{
std::string line;
getline(fd, line);
in += line;
in += "\n";
}
fd.close ();
}
}
if (!file_opened)
{
cout << "Input file not found " << endl;
return 0;
}
if (vm.count("dot"))
{
is_dot_enabled = true;
}
if (vm.count("verbose"))
{
avy::AvyEnableLog ("verbose");
}
// enable loggers
if (vm.count("log"))
{
vector<string> loggers = vm ["log"].as<vector<string> > ();
for(unsigned int i=0; i<loggers.size (); i++)
{
avy::AvyEnableLog (loggers [i]);
}
}
solver_t::Options opts(max_cegar_iter,
gen,
abs,
is_dot_enabled,
shortest_witness,
freq_incr_witness,
incr_witness,
num_solutions);
CFGProblem problem;
StrParse input(in);
boost::shared_ptr<TerminalFactory> tfac (new TerminalFactory ());
try
{
parse_problem(problem, input, tfac);
}
catch(error &e)
{
cerr << "covenant error:" << e << endl;
return 0;
}
if (problem.size() == 0)
{
cerr << "covenant: no CFGs found." << endl;
return 0;
}
try
{
for(int ii = 0; ii < problem.size(); ii++)
{
CFGProblem::Constraint cn(problem[ii]);
if (cn.vars.empty())
{
throw error("expected at least one CFG");
}
cn.lang.check_well_formed();
}
}
catch(error &e)
{
cerr << "covenant error:" << e << endl;
return 0;
}
reg_solver_t *regsolver = new Product<edge_sym_t>();
try
{
solver_t s(problem, regsolver, opts);
s.preprocess ();
if (vm.count("stats"))
{
s.stats (cout);
delete regsolver;
return 0;
}
STATUS res = s.solve();
switch (res)
{
case SAT:
cout << "======\nSAT\n======\n";
break;
case UNSAT:
cout << "======\nUNSAT\n======\n";
break;
default:
cout << "======\nUNKNOWN\n======\n";
break;
}
}
catch(error &e)
{
cerr << "covenant error:" << e << endl;
}
catch(Exit &e)
{
cerr << e << endl;
}
delete regsolver;
return 0;
}
| true |
9aa211d8c25889b55a2f264c647dd94bc591a010 | C++ | Kitware/vtk-examples | /src/Cxx/Images/ImageLuminance.cxx | UTF-8 | 2,478 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | #include <vtkImageActor.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkImageLuminance.h>
#include <vtkImageMapper3D.h>
#include <vtkInteractorStyleImage.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
int main(int, char*[])
{
vtkNew<vtkNamedColors> colors;
// Create an image of a rectangle.
vtkNew<vtkImageCanvasSource2D> source;
source->SetScalarTypeToUnsignedChar();
source->SetNumberOfScalarComponents(3);
source->SetExtent(0, 200, 0, 200, 0, 0);
// Clear the image.
source->SetDrawColor(0, 0, 0);
source->FillBox(0, 200, 0, 200);
// Draw a red box.
source->SetDrawColor(255, 0, 0);
source->FillBox(100, 120, 100, 120);
source->Update();
vtkNew<vtkImageLuminance> luminanceFilter;
luminanceFilter->SetInputConnection(source->GetOutputPort());
luminanceFilter->Update();
// Create actors
vtkNew<vtkImageActor> originalActor;
originalActor->GetMapper()->SetInputConnection(source->GetOutputPort());
vtkNew<vtkImageActor> luminanceActor;
luminanceActor->GetMapper()->SetInputConnection(
luminanceFilter->GetOutputPort());
// Define viewport ranges.
// (xmin, ymin, xmax, ymax)
double originalViewport[4] = {0.0, 0.0, 0.5, 1.0};
double luminanceViewport[4] = {0.5, 0.0, 1.0, 1.0};
// Setup renderers.
vtkNew<vtkRenderer> originalRenderer;
originalRenderer->SetViewport(originalViewport);
originalRenderer->AddActor(originalActor);
originalRenderer->ResetCamera();
originalRenderer->SetBackground(
colors->GetColor3d("CornflowerBlue").GetData());
vtkNew<vtkRenderer> luminanceRenderer;
luminanceRenderer->SetViewport(luminanceViewport);
luminanceRenderer->AddActor(luminanceActor);
luminanceRenderer->ResetCamera();
luminanceRenderer->SetBackground(colors->GetColor3d("SteelBlue").GetData());
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->SetSize(600, 300);
renderWindow->AddRenderer(originalRenderer);
renderWindow->AddRenderer(luminanceRenderer);
renderWindow->SetWindowName("ImageLuminance");
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
vtkNew<vtkInteractorStyleImage> style;
renderWindowInteractor->SetInteractorStyle(style);
renderWindowInteractor->SetRenderWindow(renderWindow);
renderWindow->Render();
renderWindowInteractor->Initialize();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| true |
d791afbec38f5e3d07dec3a1a36a8e7965003e97 | C++ | ajanaliz/BasicGL | /SelfAssessment1_2/SlefAssssment1_2/main.cpp | UTF-8 | 597 | 2.65625 | 3 | [] | no_license | #include <GL\glut.h>
#include <iostream>
#include <cmath>
#define N 100
#define PI 3.14
static float R = 1.0;
void init()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
float t = 0, x = 0.0, y = 0.0;
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < N;i++)
{
glVertex2f(x + R*cos(t), y + R*sin(t));
t += 2 * PI / N;
}
glEnd();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutCreateWindow("Circle");
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
} | true |
3135a1b546a075c2b7ae465666d3f7abcb7e8216 | C++ | rajneeshkumar146/pepcoding-Batches | /2019/batch_01/grp1_graph/l001.cpp | UTF-8 | 3,593 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Edge
{
public:
int v = 0;
int w = 0;
Edge(int v, int w)
{
this->v = v;
this->w = w;
}
};
const int n = 9;
vector<vector<Edge *>> graph(n, vector<Edge *>());
void addEdge(vector<vector<Edge *>> &g, int u, int v, int w)
{
g[u].push_back(new Edge(v, w));
g[v].push_back(new Edge(u, w));
}
void display(vector<vector<Edge *>> &g)
{
for (int i = 0; i < n; i++)
{
cout << "vertex: " << i << ": -> ";
for (Edge *e : g[i])
{
cout << "(" << e->v << ", " << e->w << ") ";
}
cout << endl;
}
cout << endl;
}
int searchVtx(int u, int v)
{
int idx = -1;
for (int i = 0; i < graph[u].size(); i++)
{
Edge *e = graph[u][i];
if (e->v == v)
{
idx = i;
break;
}
}
return idx;
}
void removeEdge(int u, int v)
{
int vidx = searchVtx(u, v);
int uidx = searchVtx(v, u);
graph[u].erase(graph[u].begin() + vidx);
graph[v].erase(graph[v].begin() + uidx);
}
void removeVtx(int u)
{
while (graph[u].size() != 0)
{
Edge *e = graph[u].back(); //graph[u][graph[u].size()-1];
removeEdge(u, e->v);
}
}
bool hasPath(int src, int desti, vector<bool> &vis)
{
if (src == desti)
return true;
bool res = false;
vis[src] = true; //mark
for (Edge *e : graph[src])
if (!vis[e->v])
res = res || hasPath(e->v, desti, vis);
return res;
}
int allPath(int src, int desti, int wsf, vector<bool> &vis, string ans)
{
if (src == desti)
{
cout << ans << desti << " @ " << wsf << endl;
return 1;
}
vis[src] = true; //mark
int count = 0;
for (Edge *e : graph[src])
if (!vis[e->v])
count += allPath(e->v, desti, wsf + e->w, vis, ans + to_string(src));
vis[src] = false; //unMark
return count;
}
class allPair
{
public:
int ceil = 1e7;
int floor = -1e7;
int heavyPath = -1e8;
int lightPath = 1e8;
};
void dfs_allSolu(int src, int desti, int data, int wsf, vector<bool> &vis, allPair &pair)
{
if (src == desti)
{
pair.heavyPath = max(pair.heavyPath, wsf);
pair.lightPath = min(pair.lightPath, wsf);
//ceil
if (wsf > data)
pair.ceil = min(pair.ceil, wsf);
//floor
if (wsf < data)
pair.floor = max(pair.floor, wsf);
return;
}
vis[src] = true;
for (Edge *e : graph[src])
{
if (!vis[e->v])
dfs_allSolu(e->v, desti, data, wsf + e->w, vis, pair);
}
vis[src] = false;
}
void constructGraph()
{
addEdge(graph, 0, 1, 10);
addEdge(graph, 1, 2, 10);
addEdge(graph, 0, 3, 10);
addEdge(graph, 3, 2, 40);
addEdge(graph, 3, 4, 2);
addEdge(graph, 4, 5, 2);
addEdge(graph, 4, 6, 3);
addEdge(graph, 5, 6, 8);
addEdge(graph, 2, 7, 5);
addEdge(graph, 2, 8, 5);
addEdge(graph, 7, 8, 6);
}
void solve()
{
constructGraph();
display(graph);
// removeEdge(4, 3);
// removeVtx(2);
// display(graph);
vector<bool> vis(n, false);
// cout << hasPath(0, 6, vis);
cout << allPath(0, 6, 0, vis, "") << endl;
allPair pair;
dfs_allSolu(0, 6, 20, 0, vis, pair);
cout << "heavyWeight: " << pair.heavyPath << endl;
cout << "lightWeight: " << pair.lightPath << endl;
cout << "ceil: " << pair.ceil << endl;
cout << "floor: " << pair.floor << endl;
}
int main()
{
solve();
return 0;
}
| true |
69a452ee90de29fc71b16bdc5e0e3f1ad3006048 | C++ | 20060201/Abbreviation | /main.cpp | UTF-8 | 2,507 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <cctype>
using namespace std;
int main(){
string s, s1;
string str;
int n;
cout << "Key Word: ";
getline(cin, str);
//
string SS[99];
vector <string> vSS;
//
n=0;
s1="";
for (int i=0; i < str.length(); i++){
s = toupper(str[i]);
if (s != " "){
SS[n] += s;
//
s1 += s;
}
if (s == " " || i==(str.length()-1) ){
//cout << SS[n] << endl;
n++;
//
vSS.push_back(s1);
s1="";
//cout << vSS.back() << "*" << endl;
}
}
//cout << SS[n] << endl;
//
// 用 iterator 來印出 vector 內所有內容
for (vector<string>::iterator it = vSS.begin() ; it != vSS.end(); ++it) {
//cout << *it << " ";
//}
//
//for (int i=0; i<=n; i++){
s1 = *it;//vSS[i];//SS[i];
//
if (s1!=" " && !s1.empty()){
if (strcasecmp(s1.c_str(), "for") == 0) {
cout << "4";
}
else if (strcasecmp(s1.c_str(), "to") == 0) {
cout << "2";
}
else if (strcasecmp(s1.c_str(), "you") == 0) {
cout << "u";
}
else if (strcasecmp(s1.c_str(), "and") == 0) {
cout << "n";
}
else {
cout << s1[0];
}
}
}
cout << endl;
/*
size_t index = 0;
for (char c : str) {
c = toupper(c);
cout << index++ << " - '" << c << "'" << endl;
}
*/
return 0;
}
/*
//函數功能: 傳入一個字串s,以splitSep裡的字元當做分割字符,回傳vector<string>
vector<string> splitStr2Vec(string s, string splitSep)
{
vector<string> result;
int current = 0; //最初由 0 的位置開始找
int next = 0;
while (next != -1)
{
next = s.find_first_of(splitSep, current); //尋找從current開始,出現splitSep的第一個位置(找不到則回傳-1)
if (next != current)
{
string tmp = s.substr(current, next - current);
if(!tmp.empty()) //忽略空字串(若不寫的話,尾巴都是分割符會錯)
{
result.push_back(tmp);
}
}
current = next + 1; //下次由 next + 1 的位置開始找起。
}
return result;
}
*/ | true |
d7c6f12bc6cf57bbf607630db5f7f462f2b306b7 | C++ | 0yhy/Algorithm | /6. 背包问题/ZeroOnePack.cpp | UTF-8 | 785 | 2.84375 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int MAXN = 105;
const int MAXC = 1005;
const int INF = 0x3f3f3f3f;
int N, V;
int c[MAXN], v[MAXN];
int f[MAXN][MAXC];
void initiaize() // 不用恰好装满
{
for (int i = 0; i <= N; ++i)
for (int j = 0; j <= V; ++j)
f[i][j] = 0;
}
void initializeFull() // 恰好装满
{
f[0][0] = 0;
for (int i = 1; i <= N; ++i)
for (int j = 0; j <= V; ++j)
f[i][j] = -INF;
}
int main()
{
cin >> N >> V;
initiaize();
for (int i = 1; i <= N; ++i)
{
for (int j = 1; j <= V; ++j)
if (c[i] < j)
f[i][j] = max(f[i - 1][j], f[i - 1][j - c[i]] + v[i]);
else
f[i][j] = f[i - 1][j];
}
cout << f[N][V];
return 0;
} | true |
ad08eec5cc054ad1d7f20875e7aaa5838657d07c | C++ | bangbv/Master | /Thesis/documents/fimi01/source/Trie.cpp | UTF-8 | 20,107 | 2.84375 | 3 | [] | no_license | /***************************************************************************
Trie.cpp - description
-------------------
begin : cs dec 26 2002
copyright : (C) 2002 by Ferenc Bodon
email : bodon@mit.bme.hu
***************************************************************************/
#include "Trie.hpp"
#include <cstdlib>
#include <algorithm>
/**
\param stateIndex the state whose max_path value has to be set.
\return true, if no update was required (original value was correct), otherwise false.
*/
void Trie::max_path_set( const unsigned long stateIndex )
{
itemtype temp_max_path = 0;
for( vector<unsigned long>::iterator it_state = statearray[stateIndex].begin(); it_state != statearray[stateIndex].end(); it_state++ )
if( temp_max_path<maxpath[*it_state]+1) temp_max_path=maxpath[*it_state]+1;
if( maxpath[stateIndex] != temp_max_path )
{
maxpath[stateIndex] = temp_max_path;
if( stateIndex ) max_path_set(parent[stateIndex]);
}
}
/**
\param fromState the state from the edge starts.
\param toState the state to the edge points.
*/
void Trie::delete_edge( const unsigned long fromState, const unsigned long toState )
{
vector<unsigned long>::iterator it_state = lower_bound( statearray[fromState].begin(), statearray[fromState].end(), toState );
// we are sure, that there is an element, so if( it_state!=statearray[fromState].end() && *it_state==toState) is omitted
itemarray[fromState].erase( it_state - statearray[fromState].begin() + itemarray[fromState].begin() );
statearray[fromState].erase( it_state );
if( itemarray[fromState].empty() )
{
maxpath[fromState] = 0;
max_path_set(parent[fromState]);
}
}
/**
\param fromState The state number that point to the new state.
\param item The label of the new edge
\param counter The initial counter of the new state
*/
void Trie::add_empty_state( const unsigned long fromState,itemtype item, const unsigned long counter )
{
itemarray[fromState].push_back(item);
statearray[fromState].push_back(itemarray.size());
itemarray.resize(itemarray.size()+1);
statearray.resize(itemarray.size());
parent.push_back(fromState);
countervector.push_back(counter);
maxpath.push_back(0);
}
/**
\param an_itemset The given itemset.
\return 0, if the itemset is not included, otherwise the state number, that represents the itemset.
*/
unsigned long Trie::is_included( const set<itemtype>& an_itemset ) const
{
unsigned long stateIndex=0;
vector<itemtype>::const_iterator it_itemvector;
for( set<itemtype>::const_iterator item_it = an_itemset.begin(); item_it != an_itemset.end(); item_it++ )
{
it_itemvector = lower_bound(itemarray[stateIndex].begin(), itemarray[stateIndex].end(), *item_it);
if( it_itemvector != itemarray[stateIndex].end() && *it_itemvector == *item_it)
stateIndex = statearray[stateIndex][it_itemvector-itemarray[stateIndex].begin()];
else return 0;
}
return stateIndex;
}
/**
\param maybe_candidate The itemset that has to be checked.
*/
bool Trie::is_all_subset_frequent( const set<itemtype>& maybe_candidate ) const
{
if( maybe_candidate.size() < 3) return true; // because of the candidate generation method!
else
{
set<itemtype> temp_itemset(maybe_candidate);
set<itemtype>::const_iterator item_it = --(--maybe_candidate.end());
do
{
item_it--;
temp_itemset.erase( *item_it );
if( !is_included( temp_itemset ) ) return false;
temp_itemset.insert( *item_it );
}
while ( item_it != maybe_candidate.begin() );
return true;
}
}
void Trie::candidate_generation_two()
{
if( !itemarray[0].empty() )
{
maxpath[0] = 2;
temp_counter_array.reserve(itemarray[0].size()-1);
temp_counter_array.resize(itemarray[0].size()-1);
for( itemtype stateIndex = 0; stateIndex < itemarray[0].size()-1; stateIndex++ )
{
temp_counter_array[stateIndex].reserve(itemarray[0].size()-1-stateIndex );
temp_counter_array[stateIndex].resize(itemarray[0].size()-1-stateIndex, 0);
}
}
}
void Trie::candidate_generation_assist( unsigned long actual_state, const itemtype frequent_size,
const itemtype actual_size, set<itemtype>& maybe_candidate)
{
itemtype edgeIndex;
if( actual_size == frequent_size)
{
itemtype edgeIndex2;
unsigned long toExtend;
for( edgeIndex = 0; edgeIndex < itemarray[actual_state].size(); edgeIndex++ )
{
maybe_candidate.insert(itemarray[actual_state][edgeIndex]);
toExtend = statearray[actual_state][edgeIndex];
for( edgeIndex2 = edgeIndex+1; edgeIndex2 < itemarray[actual_state].size(); edgeIndex2++ )
{
maybe_candidate.insert(itemarray[actual_state][edgeIndex2]);
if( is_all_subset_frequent(maybe_candidate) )
add_empty_state(toExtend,itemarray[actual_state][edgeIndex2]);
maybe_candidate.erase(itemarray[actual_state][edgeIndex2]);
}
if( !itemarray[toExtend].empty()) maxpath[toExtend] = 1;
vector<itemtype>((const vector<itemtype>) itemarray[toExtend]).swap(itemarray[toExtend]); // we know that state toExtend will not have any more children!
vector<unsigned long>((const vector<unsigned long>) statearray[toExtend]).swap(statearray[toExtend]); // we know that state toExtend will not have any more children!
maybe_candidate.erase(itemarray[actual_state][edgeIndex]);
}
max_path_set(actual_state);
}
else
{
for( edgeIndex = 0; edgeIndex < itemarray[actual_state].size(); edgeIndex++ )
{
maybe_candidate.insert(itemarray[actual_state][edgeIndex]);
candidate_generation_assist( statearray[actual_state][edgeIndex], frequent_size, actual_size+1, maybe_candidate );
maybe_candidate.erase(itemarray[actual_state][edgeIndex]);
}
}
}
/**
\param basket the given basket
*/
void Trie::find_candidate_one( const vector<itemtype>& basket )
{
countervector[0]++;
for( vector<itemtype>::const_iterator it_basket = basket.begin(); it_basket != basket.end(); it_basket++ )
{
if( *it_basket+1 >= countervector.size() ) countervector.resize( *it_basket+2, 0 );
countervector[*it_basket+1]++;
}
}
/**
\param basket the given basket
\param counter The number the processed basket occures in the transactional database
*/
void Trie::find_candidate_two( const vector<itemtype>& basket, const unsigned long counter )
{
vector<itemtype>::const_iterator it1_basket,
it2_basket;
for( it1_basket = basket.begin(); it1_basket != basket.end()-1; it1_basket++)
for( it2_basket = it1_basket+1; it2_basket != basket.end(); it2_basket++)
temp_counter_array[*it1_basket-1][*it2_basket-*it1_basket-1] += counter;
}
/**
\param basket the given basket
\param candidate_size The size of the candidates
\param it_basket *it_basket lead to the actual_state. Only items following this item need to be considered
\param actual_state The index of the actual state
\param actual_size The number of items that are already found
\param counter The number the processed basket occures in the transactional database
*/
void Trie::find_candidate_more( const vector<itemtype>& basket, const itemtype candidate_size,
vector<itemtype>::const_iterator it_basket, const unsigned long actual_state,
const itemtype actual_size, const unsigned long counter)
{
if( candidate_size == actual_size)
countervector[actual_state] += counter;
else
{
vector<itemtype>::iterator it_item = itemarray[actual_state].begin();
vector<unsigned long>::iterator it_state = statearray[actual_state].begin();
while( it_item < itemarray[actual_state].end() && candidate_size < basket.end()-it_basket+actual_size+1)
{
if( *it_item < *it_basket) {it_item++; it_state++;}
else if( *it_item > *it_basket) it_basket++;
else
{
if( maxpath[*it_state]+actual_size+1 == candidate_size )
find_candidate_more( basket, candidate_size, it_basket+1, *it_state, actual_size+1, counter);
it_item++;
it_state++;
it_basket++;
}
}
}
}
/**
\param min_occurrence The occurence threshold
*/
void Trie::delete_infrequent_one( const unsigned long min_occurrence )
{
itemtype edgeIndex;
inv_orderarray.reserve( countervector.size() );
inv_orderarray.resize( countervector.size(), 0 );
orderarray.resize(1);
vector<unsigned long> temp_countervector(1);
vector<unsigned long>::iterator it_item;
for( edgeIndex = 1; edgeIndex < countervector.size(); edgeIndex++)
if( countervector[edgeIndex] >= min_occurrence )
{
it_item = lower_bound( temp_countervector.begin()+1, temp_countervector.end(), countervector[edgeIndex]);
orderarray.insert(orderarray.begin()+(it_item-temp_countervector.begin()), edgeIndex);
temp_countervector.insert(it_item, countervector[edgeIndex]);
}
if( orderarray.size() > 1 ) maxpath[0] = 1;
vector<itemtype>(orderarray).swap(orderarray);
countervector.resize(1);
for( edgeIndex = 1; edgeIndex < orderarray.size(); edgeIndex++ )
add_empty_state( 0, edgeIndex, temp_countervector[edgeIndex] );
for( edgeIndex = 1; edgeIndex < orderarray.size(); edgeIndex++)
inv_orderarray[orderarray[edgeIndex]] = edgeIndex;
}
/**
\param min_occurrence The occurence threshold
*/
void Trie::delete_infrequent_two( const unsigned long min_occurrence )
{
itemtype stateIndex_1,
stateIndex_2;
for( stateIndex_1 = 1; stateIndex_1 < itemarray[0].size(); stateIndex_1++ )
{
for( stateIndex_2 = 0; stateIndex_2 < itemarray[0].size()-stateIndex_1; stateIndex_2++ )
if( temp_counter_array[stateIndex_1-1][stateIndex_2] >= min_occurrence )
add_empty_state( stateIndex_1, stateIndex_1+stateIndex_2+1, temp_counter_array[stateIndex_1-1][stateIndex_2] );
if( !itemarray[stateIndex_1].empty() ) maxpath[stateIndex_1] = 1;
temp_counter_array[stateIndex_1-1].clear();
vector<unsigned long>().swap(temp_counter_array[stateIndex_1-1]); /// temp_counter_array[stateIndex_1-1] will never be used again!
}
temp_counter_array.clear();
vector< vector<unsigned long> >().swap(temp_counter_array); /// temp_counter_array will never be used again!
if( itemarray.size() == itemarray[0].size()+1 ) maxpath[0] = 1;
}
/**
\param min_occurrence The occurence threshold
*/
void Trie::delete_infrequent_more( const unsigned long min_occurrence )
{
unsigned long stateIndex=1,
stateIndex2,
os;
for( stateIndex2 = 1; stateIndex2 < itemarray.size(); stateIndex2++)
{
os = parent[stateIndex2];
if( countervector[stateIndex2] >= min_occurrence )
{
if( stateIndex != stateIndex2 )
{
vector<unsigned long>::iterator it_state = lower_bound( statearray[os].begin(), statearray[os].end(), stateIndex2 );
*it_state = stateIndex;
itemarray[stateIndex] = itemarray[stateIndex2];
statearray[stateIndex] = statearray[stateIndex2];
parent[stateIndex] = parent[stateIndex2];
countervector[stateIndex] = countervector[stateIndex2];
maxpath[stateIndex] = maxpath[stateIndex2];
}
stateIndex++;
}
else delete_edge(os,stateIndex2);
}
itemarray.resize( stateIndex );
statearray.resize( stateIndex );
parent.resize( stateIndex );
countervector.resize( stateIndex );
maxpath.resize( stateIndex );
}
void Trie::assoc_rule_find( ofstream& outcomefile, const double min_conf, set<itemtype>& condition_part,
set<itemtype>& consequence_part, const unsigned long union_support) const
{
set<itemtype>::const_iterator item_it_2;
itemtype item;
for( set<itemtype>::const_iterator item_it = consequence_part.begin(); item_it != consequence_part.end(); item_it++)
if( condition_part.empty() || *(--condition_part.end()) < *item_it)
{
item = *item_it;
consequence_part.erase( item );
condition_part.insert( item );
if( union_support > countervector[is_included(condition_part)] * min_conf)
{
outcomefile << endl;
for( item_it_2 = condition_part.begin(); item_it_2 != --(condition_part.end()); item_it_2++)
outcomefile << orderarray[*item_it_2]-1 << ' ';
outcomefile << orderarray[*item_it_2]-1;
outcomefile << " ==> ";
for( item_it_2 = consequence_part.begin(); item_it_2 != --(consequence_part.end()); item_it_2++)
outcomefile << orderarray[*item_it_2]-1 << ' ';
outcomefile << orderarray[*item_it_2]-1;
outcomefile << " ("<<((double) union_support) / countervector[is_included(condition_part)] << ", " << union_support << ')';
}
else if( consequence_part.size() > 1 ) assoc_rule_find( outcomefile, min_conf, condition_part, consequence_part, union_support );
item_it = (consequence_part.insert( item )).first;
condition_part.erase( item );
}
}
void Trie::assoc_rule_assist( ofstream& outcomefile, const double min_conf, unsigned long actual_state, set<itemtype>& consequence_part) const
{
if( consequence_part.size() > 1 )
{
set<itemtype> condition_part;
assoc_rule_find( outcomefile, min_conf, condition_part, consequence_part, countervector[actual_state] );
}
vector<unsigned long>::const_iterator it_state = statearray[actual_state].begin();
for( vector<itemtype>::const_iterator it_item = itemarray[actual_state].begin(); it_item != itemarray[actual_state].end(); it_item++, it_state++)
{
consequence_part.insert( *it_item );
assoc_rule_assist( outcomefile, min_conf, *it_state, consequence_part);
consequence_part.erase( *it_item );
}
}
void Trie::write_content_to_file_assist( ofstream& outcomefile, const unsigned long actual_state, const itemtype item_size,
const itemtype actual_size, set<itemtype>& frequent_itemset) const
{
if( actual_size == item_size )
{
for( set<itemtype>::const_iterator it = frequent_itemset.begin(); it != frequent_itemset.end(); it++)
outcomefile << orderarray[*it]-1 << ' ';
outcomefile << '(' << countervector[actual_state] << ')'<<endl;
}
else
{
vector<unsigned long>::const_iterator it_state = statearray[actual_state].begin();
for( vector<itemtype>::const_iterator it_item = itemarray[actual_state].begin(); it_item != itemarray[actual_state].end(); it_item++, it_state++ )
if( maxpath[*it_state]+actual_size+1 >= item_size )
{
frequent_itemset.insert( *it_item );
write_content_to_file_assist( outcomefile, *it_state, item_size, actual_size+1, frequent_itemset);
frequent_itemset.erase( *it_item );
}
}
}
Trie::Trie()
{
countervector.push_back(0);
maxpath.push_back(0);
itemarray.resize(1);
statearray.resize(1);
parent.push_back(0); //it could be anything, root doesn't have a parent!
}
/**
\param frequent_size Size of the frequent itemsets that generate the candidates.
*/
void Trie::candidate_generation( const itemtype& frequent_size )
{
if( frequent_size == 1 ) candidate_generation_two();
else if( maxpath[0] == frequent_size )
{
set<itemtype> maybe_candidate;
candidate_generation_assist( 0, frequent_size, 1, maybe_candidate );
}
}
void Trie::find_candidate( const vector<itemtype>& basket, const itemtype candidate_size, const unsigned long counter)
{
if( candidate_size == 1 ) find_candidate_one( basket );
else if( candidate_size == 2 ) find_candidate_two( basket, counter );
else find_candidate_more( basket, candidate_size, basket.begin(), 0, 0, counter );
}
/**
\param min_occurrence The threshold of absolute support.
*/
void Trie::delete_infrequent( const unsigned long min_occurrence )
{
if( maxpath[0] == 0 ) delete_infrequent_one( min_occurrence );
else if( maxpath[0] == 2 ) delete_infrequent_two( min_occurrence );
else delete_infrequent_more( min_occurrence );
}
/**
\param outcomefile The file the output will be written to.
\param min_conf Confidence threshold.
*/
void Trie::association( ofstream& outcomefile, const double min_conf ) const
{
outcomefile << "\nAssociation rules:\ncondition ==> consequence (confidence, occurrence)\n";
set<itemtype> consequence_part;
assoc_rule_assist( outcomefile, min_conf, 0, consequence_part );
}
/**
\param basket The given basket.
*/
void Trie::basket_recode( vector<itemtype>& basket ) const
{
set<itemtype> tempset;
for( vector<itemtype>::iterator it_basket = basket.begin(); it_basket != basket.end(); it_basket++ )
if( inv_orderarray[*it_basket+1] ) tempset.insert( inv_orderarray[*it_basket+1] );
basket.clear();
basket.insert( basket.end(), tempset.begin(), tempset.end() );
}
unsigned long Trie::node_number() const
{
if( maxpath[0] == 2 && itemarray[0].size()+1 == itemarray.size() )
return itemarray.size()+(itemarray.size()-1)*(itemarray.size()-2)/2;
else return itemarray.size();
}
void Trie::statistics() const
{
unsigned long mem = itemarray.capacity()+statearray.capacity()+
countervector.capacity()+maxpath.capacity()+parent.capacity();
for( unsigned long stateIndex = 0; stateIndex < itemarray.size(); stateIndex++)
mem += itemarray[stateIndex].capacity() + statearray[stateIndex].capacity();
// cout<<"\nThe number of nodes of the trie: "<<itemarray.size();
if( maxpath[0] == 2 && itemarray[0].size()+1 == itemarray.size())
mem += (itemarray.size()-1)*(itemarray.size()-2)*sizeof(long)/2 + (itemarray.size()-1)*sizeof(unsigned long*);
cout << "The memory need is: ";
if( mem/1048576 ) cout << mem/1048576 << " Mbyte + ";
if( (mem%1048576)/1024 ) cout << (mem%1048576)/1024<<" Kbyte + ";
cout << mem%1024 <<" byte" << endl;
}
void Trie::write_content_to_file( ofstream& outcomefile ) const
{
outcomefile << "Frequent 0-itemsets:\nitemset (occurrence)\n";
outcomefile << "{} ("<< countervector[0] << ')' << endl;
for( itemtype item_size = 1; item_size < maxpath[0]+1; item_size++ )
{
outcomefile << "Frequent " << item_size << "-itemsets:\nitemset (occurrence)\n";
set<itemtype> frequent_itemset;
write_content_to_file_assist( outcomefile, 0, item_size, 0, frequent_itemset );
}
}
void Trie::show_content() const
{
unsigned long stateIndex;
itemtype edgeIndex;
cout<< "\nSize:" << itemarray.size();
for( stateIndex = 0; stateIndex < itemarray.size(); stateIndex++)
{
cout << endl << "Size of the " << stateIndex << "th state:" << itemarray[stateIndex].size()
<< " its counter: " << countervector[stateIndex] << " longest path: "
<< maxpath[stateIndex] << ", edge point to it: " << parent[stateIndex]<<",leafs:";
vector<unsigned long>::const_iterator it_state = statearray[stateIndex].begin();
for( vector<itemtype>::const_iterator it_item = itemarray[stateIndex].begin(); it_item != itemarray[stateIndex].end(); it_item++, it_state++ )
cout << endl << "Item " << *it_item << " leads to state " << *it_state;
}
if( maxpath[0] == 1 && itemarray[0][0] < itemarray.size() )
{
cout << endl << "Content of 2D table (counters of itempairs)";
for( stateIndex = 0; stateIndex < itemarray[0].size()-1; stateIndex++ )
{
cout << endl;
for( edgeIndex =0 ; edgeIndex < itemarray[0].size()-1-stateIndex; edgeIndex++)
cout << temp_counter_array[stateIndex][edgeIndex]<< ',';
}
}
}
Trie::~Trie()
{
}
| true |
021712da6982a68b9174c5a4f1b5c3f3d0c1f6dd | C++ | JinhwanSul/SW_Expert_Academy_practice | /1242/Jinhwan/1242.cpp | UTF-8 | 7,517 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
// Using String Match, Rabin-Karp Algorithm
int decrypt(int *one_number)
{
int i, value = 0;
for (i = 0; i < 7; i++) {
// printf("%d ", one_number[i]);
value = value + one_number[i] * (1<<(6-i));
}
// printf("\nvalue %d\n", value);
switch (value) {
case 13:
return 0;
case 25:
return 1;
case 19:
return 2;
case 61:
return 3;
case 35:
return 4;
case 49:
return 5;
case 47:
return 6;
case 59:
return 7;
case 55:
return 8;
case 11:
return 9;
default:
return -1;
}
}
int validation(int *candidate)
{
int i, sum = 0;
if (((candidate[0] + candidate[2] + candidate[4] + candidate[6]) * 3
+ candidate[1] + candidate[3] + candidate[5] + candidate[7]) % 10 == 0) {
for(i = 0; i < 8; i++) {
sum += candidate[i];
}
return sum;
}
else {
return 0;
}
}
int min3(int a, int b, int c) {
if(a <= b && a <= c) return a;
if(b <= a && b <= c) return b;
if(c <= a && c <= b) return c;
return -1;
}
// Check last (1, 0, 1) pattern to find out code thickness
int find_ratio(int **input_bi, int n, int m) {
int i = m;
int cnt_front1 = 0, cnt0 = 0, cnt_rear1 = 0;
while(input_bi[n][i] == 1) {
cnt_rear1++;
i--;
}
while(input_bi[n][i] == 0) {
cnt0++;
i--;
}
while(input_bi[n][i] == 1) {
cnt_front1++;
i--;
}
return min3(cnt_rear1, cnt0, cnt_front1);
}
void change2binary(int **input2, int n, int m, char num)
{
int k = 4*m;
if(num != '0'){
// printf("not 0 and %c (%d, %d) goes to %d~%d\n",num, n, m, k, k+3);
}
// // printf("%d %c\n", num, num);
switch (num) {
case '0':
input2[n][k] = 0; input2[n][k+1] = 0; input2[n][k+2] = 0; input2[n][k+3] = 0;
break;
case '1':
input2[n][k] = 0; input2[n][k+1] = 0; input2[n][k+2] = 0; input2[n][k+3] = 1;
break;
case '2':
input2[n][k] = 0; input2[n][k+1] = 0; input2[n][k+2] = 1; input2[n][k+3] = 0;
break;
case '3':
input2[n][k] = 0; input2[n][k+1] = 0; input2[n][k+2] = 1; input2[n][k+3] = 1;
break;
case '4':
input2[n][k] = 0; input2[n][k+1] = 1; input2[n][k+2] = 0; input2[n][k+3] = 0;
break;
case '5':
input2[n][k] = 0; input2[n][k+1] = 1; input2[n][k+2] = 0; input2[n][k+3] = 1;
break;
case '6':
input2[n][k] = 0; input2[n][k+1] = 1; input2[n][k+2] = 1; input2[n][k+3] = 0;
break;
case '7':
input2[n][k] = 0; input2[n][k+1] = 1; input2[n][k+2] = 1; input2[n][k+3] = 1;
break;
case '8':
input2[n][k] = 1; input2[n][k+1] = 0; input2[n][k+2] = 0; input2[n][k+3] = 0;
break;
case '9':
input2[n][k] = 1; input2[n][k+1] = 0; input2[n][k+2] = 0; input2[n][k+3] = 1;
break;
case 'A':
input2[n][k] = 1; input2[n][k+1] = 0; input2[n][k+2] = 1; input2[n][k+3] = 0;
break;
case 'B':
input2[n][k] = 1; input2[n][k+1] = 0; input2[n][k+2] = 1; input2[n][k+3] = 1;
break;
case 'C':
input2[n][k] = 1; input2[n][k+1] = 1; input2[n][k+2] = 0; input2[n][k+3] = 0;
break;
case 'D':
input2[n][k] = 1; input2[n][k+1] = 1; input2[n][k+2] = 0; input2[n][k+3] = 1;
break;
case 'E':
input2[n][k] = 1; input2[n][k+1] = 1; input2[n][k+2] = 1; input2[n][k+3] = 0;
break;
case 'F':
input2[n][k] = 1; input2[n][k+1] = 1; input2[n][k+2] = 1; input2[n][k+3] = 1;
break;
}
}
int is_new_block(vector<vector<int> > &code_blocks, int n, int m)
{
vector<vector<int> >::iterator iter;
for (iter = code_blocks.begin(); iter != code_blocks.end(); iter++) {
// printf("(%d, %d) (%d, %d)\n", (*iter)[0], (*iter)[1],(*iter)[2],(*iter)[3]);
if((*iter)[0] <= n && n <= (*iter)[2] && (*iter)[3] <= m && m <= (*iter)[1]) {
return 0; // (n,m) in same block
}
}
return 1; // new block same block
}
void add_new_block(vector<vector<int> > &code_blocks, int n, int m, int ratio, int** input_bi)
{
int i = n;
vector<int> new_block;
while(input_bi[i][m] != 0) {
i++;
}
new_block.push_back(n);
new_block.push_back(m);
new_block.push_back(i-1);
new_block.push_back(m-56*ratio+1);
// printf("new block! ratio=%d, (%d, %d) (%d, %d)\n",ratio,n,m,i-1,m-56*ratio+1);
code_blocks.push_back(new_block);
}
int get_code(int **input_bi, int ratio, int n, int m)
{
// printf("argument? n = %d m = %d\n", n, m);
int i, j, num_cnt = 0, read = m, k;
int one_number[7];
int *data = (int *) malloc(sizeof(int) * 8);
for(j = 7; j >= 0; j--) {
for (i = read; i > (read - 7 * ratio); i = i - ratio) {
one_number[6-num_cnt] = input_bi[n][i];
num_cnt++;
}
// printf("one number!\n");
// for(k = 0; k < 7; k++) {
// printf("%d", one_number[k]);
// }
// printf("\n");
data[j] = decrypt(one_number);
// printf("data[j] = %d\n", data[j]);
read = i;
num_cnt = 0;
}
// if (is_dup(data, code_cnt, codes)) {
// return -1;
// } else {
return validation(data);
// }
}
int main(int argc, char** argv)
{
int test_case;
int T, N, M, i, j, ratio, code_cnt = 0, valid = 0, result = 0;
char num_ch;
int candidate[8];
unsigned int value, value_backup;
vector<vector<int> > code_block;
int matched;
freopen("sample_input copy.txt", "r", stdin);
cin>>T;
for(test_case = 1; test_case <= T; ++test_case)
{
cin>>N>>M;
result = 0;
code_block.clear();
int **input_bi = (int **) malloc(N * sizeof(int *));
for (i = 0; i < N; i++) {
input_bi[i] = (int *) calloc(4* M, sizeof(int));
}
for (i = 0; i < N; i++) {
for(j = 0; j < M; j++) {
cin>>num_ch;
change2binary(input_bi, i, j, num_ch);
}
}
// FILE *fd = fopen("input_bi.txt", "w");
// for(i = 0; i < N; i++) {
// for(j = 0; j < 4*M; j++){
// fputc(input_bi[i][j]+'0', fd);
// }
// fputc('\n', fd);
// }
// fclose(fd);
for(i = 0; i < N; i++) {
for(j = 4*M-1; j >= 0; j--) {
if(input_bi[i][j] == 1 && is_new_block(code_block, i, j)) { // Encrypted code detected
code_cnt++;
ratio = find_ratio(input_bi, i, j);
// printf("ratio = %d\n", ratio);
add_new_block(code_block, i, j, ratio, input_bi);
valid = get_code(input_bi, ratio, i, j);
// printf("code_cnt= %d, valid = %d\n",code_cnt, valid);
if (valid > 0) {
result += valid;
}
}
}
}
printf("#%d %d\n", test_case, result);
}
return 0;
} | true |
71a26854b6279768391134259a62f1ffb56bbeea | C++ | frandibar/pacman3d | /lib/sockets/Socket.cpp | UTF-8 | 2,573 | 2.828125 | 3 | [] | no_license | #include "Socket.h"
#include "debug.h"
#include <iostream>
#include <cerrno>
#include <string>
#include <fcntl.h>
using std::string;
Socket::Socket() : _sock(-1)
{
memset(&_addr, 0, sizeof(_addr));
}
Socket::~Socket()
{
if (isValid())
::close(_sock);
}
bool Socket::create()
{
_sock = socket(AF_INET, SOCK_STREAM, 0);
if (!isValid())
return false;
// TIME_WAIT
int on = 1;
if (setsockopt(_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) == -1)
return false;
return true;
}
bool Socket::bind(int port)
{
if (!isValid())
return false;
_addr.sin_family = AF_INET;
_addr.sin_addr.s_addr = INADDR_ANY;
_addr.sin_port = htons(port);
return (::bind(_sock, (sockaddr*)&_addr, sizeof(_addr)) != -1);
}
bool Socket::listen() const
{
if (!isValid())
return false;
return (::listen(_sock, SOMAXCONN) != -1);
}
bool Socket::accept(Socket* a_pSocket) const
{
int addr_length = sizeof(_addr);
a_pSocket->_sock = ::accept(_sock, (sockaddr*)&_addr, (socklen_t*)&addr_length);
DEBUGME<int>(a_pSocket->_sock, "accepted socket: ");
return (a_pSocket->_sock > 0);
}
bool Socket::send(const std::string& msg) const
{
int status = ::send(_sock, msg.c_str(), msg.size(), MSG_NOSIGNAL);
return (status != -1);
}
int Socket::receive(std::string& msg) const
{
char buf[MAXRECV + 1];
msg = "";
memset(buf, 0, MAXRECV + 1);
int status = recv(_sock, buf, MAXRECV, 0);
if (status == 0)
return 0;
else if (status == -1) {
std::cerr << "status: -1 errno: " << errno << " in Socket::receive\n";
return 0;
}
else {
msg = buf;
return status;
}
}
bool Socket::connect(const std::string& host, int port)
{
if (!isValid()) return false;
_addr.sin_family = AF_INET;
_addr.sin_port = htons(port);
int status = inet_pton(AF_INET, host.c_str(), &_addr.sin_addr);
if (errno == EAFNOSUPPORT) return false;
status = ::connect(_sock, (sockaddr*)&_addr, sizeof(_addr));
return (status == 0);
}
void Socket::setNonBlocking(bool set)
{
int opts = fcntl(_sock, F_GETFL);
if (opts < 0)
return;
if (set)
opts = (opts | O_NONBLOCK);
else
opts = (opts & ~O_NONBLOCK);
fcntl(_sock, F_SETFL,opts);
}
bool Socket::getPeerName(string& name)
{
struct sockaddr sa;
socklen_t addlen;
bool ret = (::getpeername(_sock, &sa, &addlen) == 0);
name = string(sa.sa_data).substr(0, addlen);
return ret;
}
| true |
470dc73f9e07c38649226a3dddd82d0bd55697db | C++ | MasakiMuto/DxShooot | /DxShoot/PlayEngine.h | UTF-8 | 843 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <list>
#include "ImageLoader.h"
#include "PlayerCharacter.h"
#include "Shot.h"
#include "CharacterManager.h"
#include "Enemy.h"
#include "Rectangle.h"
namespace dxshoot
{
class PlayEngine
{
public:
static PlayEngine& getInstance();
PlayEngine();
~PlayEngine();
void update();
void draw();
ImageLoader& getImages();
inline CharacterManager& getShots() { return *cshots; }
inline PlayerCharacter& getPlayer() { return *player; }
Rectangle getPlayArea();
private:
static std::unique_ptr<PlayEngine> instance;
std::unique_ptr<ImageLoader> imageLoader;
std::unique_ptr<PlayerCharacter> player;
std::unique_ptr<CharacterManager> cshots;
std::unique_ptr<CharacterManager> enemys;
public:
void init();
void addShot(std::unique_ptr<Shot> s);
void addEnemy(std::unique_ptr<Enemy> e);
};
} | true |
1459bf72f63106c7ea9f2ee627ccd58ee08d113b | C++ | fromasmtodisasm/xform-megatexture | /src/geom/xDrawVert.h | UTF-8 | 2,134 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef __DRAWVERT_H__
#define __DRAWVERT_H__
/*
===============================================================================
Draw Vertex.
===============================================================================
*/
class xDrawVert
{
public:
xVec3 xyz;
xVec3 normal;
byte color[4];
xVec2 st;
xVec3 tangents[2];
#if 0 // was MACOS_X see comments concerning DRAWVERT_PADDED in Simd_Altivec.h
float padding;
#endif
float operator[](const int index) const;
float & operator[](const int index);
void Clear();
void Lerp(const xDrawVert &a, const xDrawVert &b, float f);
void LerpAll(const xDrawVert &a, const xDrawVert &b, float f);
void Normalize();
void SetColor(dword color);
dword GetColor() const;
};
X_INLINE float xDrawVert::operator[](const int index) const {
assert(index >= 0 && index < 5);
return ((float *)(&xyz))[index];
}
X_INLINE float &xDrawVert::operator[](const int index) {
assert(index >= 0 && index < 5);
return ((float *)(&xyz))[index];
}
X_INLINE void xDrawVert::Clear() {
xyz.Zero();
st.Zero();
normal.Zero();
tangents[0].Zero();
tangents[1].Zero();
color[0] = color[1] = color[2] = color[3] = 0;
}
X_INLINE void xDrawVert::Lerp(const xDrawVert &a, const xDrawVert &b, float f) {
xyz = a.xyz + f * (b.xyz - a.xyz);
st = a.st + f * (b.st - a.st);
}
X_INLINE void xDrawVert::LerpAll(const xDrawVert &a, const xDrawVert &b, float f) {
xyz = a.xyz + f * (b.xyz - a.xyz);
st = a.st + f * (b.st - a.st);
normal = a.normal + f * (b.normal - a.normal);
tangents[0] = a.tangents[0] + f * (b.tangents[0] - a.tangents[0]);
tangents[1] = a.tangents[1] + f * (b.tangents[1] - a.tangents[1]);
color[0] = (byte)(a.color[0] + f * (b.color[0] - a.color[0]));
color[1] = (byte)(a.color[1] + f * (b.color[1] - a.color[1]));
color[2] = (byte)(a.color[2] + f * (b.color[2] - a.color[2]));
color[3] = (byte)(a.color[3] + f * (b.color[3] - a.color[3]));
}
X_INLINE void xDrawVert::SetColor(dword color) {
*(dword*)this->color = color;
}
X_INLINE dword xDrawVert::GetColor() const {
return *(const dword*)this->color;
}
#endif /* !__DRAWVERT_H__ */
| true |
04fc8c55f32b8f398f7badd3a5e0a1550e5e806d | C++ | anhtuan10/Memories | /main.cpp | UTF-8 | 201 | 2.96875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int myAge = 21;
cout << "Hello bro! \n"<< "\tNice to meet you! \n";
cout << "\t\tI'm "<< myAge << " years old. \n";
return 0;
} | true |
9d77071d5915f23feaff47ef70e3c947166b43a1 | C++ | Kitware/vtk-examples | /src/Cxx/Rendering/Cone4.cxx | UTF-8 | 4,037 | 3 | 3 | [
"Apache-2.0"
] | permissive | //
// This example demonstrates the creation of multiple actors and the
// manipulation of their properties and transformations. It is a
// derivative of Cone.tcl, see that example for more information.
//
// First include the required header files for the VTK classes we are using.
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkConeSource.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
int main(int, char*[])
{
vtkNew<vtkNamedColors> colors;
//
// Next we create an instance of vtkConeSource and set some of its
// properties. The instance of vtkConeSource "cone" is part of a
// visualization pipeline (it is a source process object); it produces data
// (output type is vtkPolyData) which other filters may process.
//
vtkNew<vtkConeSource> cone;
cone->SetHeight(3.0);
cone->SetRadius(1.0);
cone->SetResolution(10);
//
// In this example we terminate the pipeline with a mapper process object.
// (Intermediate filters such as vtkShrinkPolyData could be inserted in
// between the source and the mapper.) We create an instance of
// vtkPolyDataMapper to map the polygonal data into graphics primitives. We
// connect the output of the cone source to the input of this mapper.
//
vtkNew<vtkPolyDataMapper> coneMapper;
coneMapper->SetInputConnection(cone->GetOutputPort());
//
// Create an actor to represent the first cone. The actor's properties are
// modified to give it different surface properties. By default, an actor
// is create with a property so the GetProperty() method can be used.
//
vtkNew<vtkActor> coneActor;
coneActor->SetMapper(coneMapper);
coneActor->GetProperty()->SetColor(colors->GetColor3d("Peacock").GetData());
coneActor->GetProperty()->SetDiffuse(0.7);
coneActor->GetProperty()->SetSpecular(0.4);
coneActor->GetProperty()->SetSpecularPower(20);
//
// Create a property and directly manipulate it. Assign it to the
// second actor.
//
vtkNew<vtkProperty> property;
property->SetColor(colors->GetColor3d("Tomato").GetData());
property->SetDiffuse(0.7);
property->SetSpecular(0.4);
property->SetSpecularPower(20);
//
// Create a second actor and a property. The property is directly
// manipulated and then assigned to the actor. In this way, a single
// property can be shared among many actors. Note also that we use the
// same mapper as the first actor did. This way we avoid duplicating
// geometry, which may save lots of memory if the geoemtry is large.
vtkNew<vtkActor> coneActor2;
coneActor2->SetMapper(coneMapper);
coneActor2->GetProperty()->SetColor(colors->GetColor3d("Peacock").GetData());
coneActor2->SetProperty(property);
coneActor2->SetPosition(0, 2, 0);
//
// Create the Renderer and assign actors to it. A renderer is like a
// viewport. It is part or all of a window on the screen and it is
// responsible for drawing the actors it has. We also set the background
// color here.
//
vtkNew<vtkRenderer> ren1;
ren1->AddActor(coneActor);
ren1->AddActor(coneActor2);
ren1->SetBackground(colors->GetColor3d("LightSlateGray").GetData());
//
// Finally we create the render window which will show up on the screen.
// We put our renderer into the render window using AddRenderer. We also
// set the size to be 300 pixels by 300.
//
vtkNew<vtkRenderWindow> renWin;
renWin->AddRenderer(ren1);
renWin->SetSize(640, 480);
renWin->SetWindowName("Cone4");
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin);
//
// Now we loop over 60 degrees and render the cone each time.
//
ren1->GetActiveCamera()->Elevation(30);
ren1->ResetCamera();
for (int i = 0; i < 60; ++i)
{
// render the image
renWin->Render();
// rotate the active camera by one degree
ren1->GetActiveCamera()->Azimuth(1);
}
iren->Start();
return EXIT_SUCCESS;
}
| true |
9d87f7684fd7ed9bfefc7d671bf601504f98debd | C++ | face4/AtCoder | /ABC/039/C.cpp | UTF-8 | 907 | 3.28125 | 3 | [] | no_license | #include<iostream>
using namespace std;
// strの接頭辞がpreかどうかを判別する.
bool startsWith(string str, string pre){
int s = str.length(), p = pre.length();
if(s < p) return false;
int j;
for(j = 0; j < p; j++){
if(str[j] != pre[j]) break;
}
return j == p;
}
int main(){
string piano = "WBWBWWBWBWBWWBWBWWBWBWBWWBWBWWBWBWBW";
string s;
cin >> s;
int i;
for(i = 0; i < 12; i++){
if(startsWith(piano.substr(i), s)) break;
}
if(i <= 1){
cout << "Do" << endl;
}else if(i <= 3){
cout << "Re" << endl;
}else if(i == 4){
cout << "Mi" << endl;
}else if(i <= 6){
cout << "Fa" << endl;
}else if(i <= 8){
cout << "So" << endl;
}else if(i <= 10){
cout << "La" << endl;
}else if(i <= 11){
cout << "Si" << endl;
}
return 0;
} | true |
cbbf1ea0fa50e9b6a4eeb90a168820a44bb8f3a1 | C++ | Slava/competitiveProgramming | /more-source/arithmetics/051_faktoriali!!!.cpp | UTF-8 | 359 | 2.53125 | 3 | [] | no_license | // Kim Vyacheslav KarKTL
#include <cstdio>
using namespace std;
int main ()
{
freopen ("input.txt", "r", stdin);
freopen ("output.txt", "w", stdout);
int n, a = 1, i, k = 0;
char s[25];
scanf ("%d %s", &n, &s);
while (s[k]) k++;
i = n % k;
if (!i) i = k;
for (; i <= n; i += k)
a *= i;
printf ("%d", a);
return 0;
}
| true |
13f40dd4ca646f06ccb97a91dc3f6b490f0399a7 | C++ | Air-Terranean/Demonstrations | /doublelinkedlist.cpp | UTF-8 | 2,646 | 3.765625 | 4 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <string>
#include "doublelinkedlist.h"
using namespace std;
list::list()
{
head = NULL;
tail = NULL;
temp = NULL;
curr = NULL;
}
void list :: addnodehead (int ahnum, char ahword)
{
cout << "Enter a number: " << endl;
cin >> ahnum;
cout << endl;
cout << "Enter a word: " << endl;
cin >> ahword;
nodeptr n = new node;
n -> prev = NULL;
n -> num = ahnum;
n -> word = ahword;
if (head == NULL)
{
n -> next = NULL;
tail = n;
head = n;
}
else
{
temp = head;
n -> next = temp;
temp -> prev = n;
head = n;
}
}
void list :: addnodetail (int atnum, char atword)
{
cout << "Enter a number: " << endl;
cin >> atnum;
cout << endl;
cout << "Enter a word: " << endl;
cin >> atword;
nodeptr n = new node;
n -> next = NULL;
n -> num = atnum;
n -> word = atword;
if (tail == NULL)
{
n -> prev = NULL;
tail = n;
head = n;
}
else
{
temp = tail;
n -> prev = temp;
temp -> next = n;
tail = n;
}
}
void list :: delnodehead()
{
temp = head;
head = head -> next;
head -> prev = NULL;
delete temp;
curr = head;
temp = head;
}
void list :: delnodetail()
{
temp = tail;
tail = tail -> prev;
tail -> next = NULL;
delete temp;
curr = tail;
temp = tail;
}
void list :: forreadlist(nodeptr & curr)
{
if (curr != NULL)
{
cout << curr -> num << " " << curr -> word << endl;
forreadlist(curr -> next);
}
else
{
cout << "End of list" << endl;
}
}
void list :: backreadlist(nodeptr & curr)
{
if (curr != NULL)
{
cout << curr -> num << " " << curr -> word << endl;
backreadlist(curr -> prev);
}
else
{
cout << endl;
}
}
void list :: dellist(nodeptr & head)
{
if(!head)
{
temp = NULL;
curr = NULL;
cout << "The list is empty." << endl;
}
else
{
dellist(head -> next);
head = NULL;
delete head;
}
}
void list :: setnodehead(nodeptr & curr)
{
curr = head;
}
void list :: setnodetail(nodeptr & curr)
{
curr = tail;
}
int main()
{
list doublelist;
int a;
int b;
int c;
int d;
char aa;
char ab;
char ac;
char ad;
doublelist.addnodehead(a,aa);
doublelist.addnodehead(b,ab);
doublelist.addnodetail(c,ac);
doublelist.addnodetail(d,ad);
cout << endl;
doublelist.setnodehead();
doublelist.forreadlist();
doublelist.setnodetail();
doublelist.backreadlist();
doublelist.dellist();
return 0;
}
| true |
cf19ab7ed1b9e82517296067f770e3677fa09525 | C++ | le-quoctrung/Course-Registration-System | /main/Course-Registration-System/Score.cpp | UTF-8 | 866 | 2.65625 | 3 | [] | no_license | #include"school.h"
#include"file.h"
void readScore(string path, char username[], char password[], int type, ScoreList& List) {
fstream file(path);
string tr;
Score* cur = nullptr;
if (file.is_open()) {
getline(file, tr, ',');
getline(file, List.CourseCode, ',');
getline(file, tr);
getline(file, tr);
while (file.eof() != true) {
Score* S = new Score;
S->next = nullptr;
S->prev = nullptr;
getline(file, S->No, ',');
getline(file, S->StudentID, ',');
getline(file, S->StudentFullName, ',');
getline(file, S->TotalMark, ',');
getline(file, S->MidTermMark, ',');
getline(file, S->FinalMark, ',');
getline(file, S->OtherMark, ',');
if (List.Head == nullptr) {
List.Head = S;
cur = S;
}
else {
cur->next = S;
S->prev = cur;
cur = S;
}
}
}
else {
cout << "Not Found the Score board";
}
} | true |
0e8956e360098567611a5f3661a7291e379abd7b | C++ | 1111Viter/05091970 | /main12.cpp | UTF-8 | 1,290 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
#include <string.h>
#include <stdio.h>
using namespace std;
struct Struct
{
char name[64];
int yr;
int cb;
int cpb;
}s;
void Menu(int);
void inp(Struct s);
void out(Struct s);
void srch(Struct s);
FILE *f;
int main(){
char c;
m: cout<<"w - write;\n"
"r - read;\n"
"s - search;\n"
"e - exit.\n"<<endl;
cin>>c;
switch(c)
{
case 'w':inp(s);break;
case 'r':out(s);break;
case 'e': exit(0);fclose(f); break;
case 's': srch(s);break;
default: goto m; break;
}
getch();
system("cls");
goto m;
return 0;
}
void inp(Struct s)
{
system("cls");
cout<<"Enter information--> ";
f=fopen("text.txt","a+");
cout<<"Book's name(space = ' _ '): ";
cin>>s.name;
cout<<"Release year: ";
cin>>s.yr;
cout<<"Count books: ";
cin>>s.cb;
cout<<"Count publ books: ";
cin>>s.cpb;
fwrite(&s,sizeof(Struct),1,f);
fclose(f);
}
void out(Struct s)
{
f=fopen("text.txt","ab+");
int c, k = 0;
system("cls");
while((c=fread(&s,sizeof(Struct),1,f))!=NULL){
cout<<"Book's name: "<<s.name<<endl;
cout<<"Release year: "<<s.yr<<endl;
cout<<"Count books: "<<s.cb<<endl;
cout<<"Count publ books: "<<s.cpb<<endl;
cout<<endl;
k++;
}
cout<<"Count books="<<k;
| true |
522b5fb00ca6c508c6292f3c6aa5bc68b71047ba | C++ | ngvozdiev/ncode-common | /src/free_list.h | UTF-8 | 6,700 | 3.078125 | 3 | [
"MIT"
] | permissive | #ifndef NCODE_FREE_LIST_H
#define NCODE_FREE_LIST_H
#include <stddef.h>
#include <vector>
#include <functional>
#include <memory>
#include <mutex>
#include <set>
#include "common.h"
#include "logging.h"
namespace nc {
template <typename T>
class FreeList;
template <typename T>
FreeList<T>& GetFreeList();
// A free list that amortizes the new/delete cost for objects by never releasing
// memory to the OS. This class is thread-safe.
template <typename T>
class FreeList {
public:
typedef std::unique_ptr<T, std::function<void(void*)>> Pointer;
// After how many raw allocations a thread will check to see if the global
// free list contains any memory.
static constexpr uint64_t kRawAllocationThreshold = 16ul;
// If a thread local free list contains this many elements half of them will
// be moved to the global free list.
static constexpr uint64_t kMoveToGlobalThreshold = 1000ul;
// How many objects to allocate at once.
static constexpr uint64_t kBatchSize = 16ul;
~FreeList() {
std::lock_guard<std::mutex> lock(mu_);
--free_lists_count_;
for (T* mem : to_free_) {
std::free(mem);
}
}
void Release(void* raw_ptr) {
static_cast<T*>(raw_ptr)->~T();
objects_.emplace_back(static_cast<T*>(raw_ptr));
if (objects_.size() >= kMoveToGlobalThreshold) {
std::lock_guard<std::mutex> lock(mu_);
size_t count = objects_.size() / 2;
global_free_objects_.insert(global_free_objects_.end(),
objects_.end() - count, objects_.end());
objects_.resize(objects_.size() - count);
}
}
static void ReleaseGlobal(void* ptr) { GetFreeList<T>().Release(ptr); }
template <typename... Args>
Pointer New(Args&&... args) {
if (objects_.empty()) {
size_t count = 0;
if (raw_allocation_count_ % kRawAllocationThreshold == 0) {
std::lock_guard<std::mutex> lock(mu_);
// Will steal 1/N of all elements in the global free list where N is the
// number of thread-local free lists.
count = global_free_objects_.size() / free_lists_count_;
if (count > 0) {
objects_.insert(objects_.end(), global_free_objects_.end() - count,
global_free_objects_.end());
global_free_objects_.resize(global_free_objects_.size() - count);
}
}
if (count == 0) {
T* mem = static_cast<T*>(std::malloc(kBatchSize * sizeof(T)));
to_free_.emplace_back(mem);
for (size_t i = 0; i < kBatchSize - 1; ++i) {
objects_.emplace_back(&(mem[i]));
}
T* const raw_ptr = &(mem[kBatchSize - 1]);
new (raw_ptr) T(std::forward<Args>(args)...);
++raw_allocation_count_;
return Pointer(raw_ptr, &ReleaseGlobal);
}
}
T* const raw_ptr = objects_.back();
objects_.pop_back();
new (raw_ptr) T(std::forward<Args>(args)...);
return Pointer(raw_ptr, &ReleaseGlobal);
}
// Returns the number of objects that this free list holds.
size_t NumObjects() const { return objects_.size(); }
private:
FreeList() : raw_allocation_count_(0) {
std::lock_guard<std::mutex> lock(mu_);
++free_lists_count_;
}
// Number of objects allocated.
uint64_t raw_allocation_count_;
// Free objects that can be assigned when needed.
std::vector<T*> objects_;
// The free list only releases memory upon destruction. This list stores
// pointers to the chunks of memory allocated from the OS (as opposed to
// objects stored in 'objects_') so that we can free them upon destruction.
std::vector<T*> to_free_;
// A scratch list of objects that can be taken by any thread.
static std::vector<T*> global_free_objects_;
// Keeps track of all free lists.
static size_t free_lists_count_;
// Protects all_free_lists_.
static std::mutex mu_;
friend FreeList& GetFreeList<T>();
DISALLOW_COPY_AND_ASSIGN(FreeList);
};
template <typename T>
size_t FreeList<T>::free_lists_count_;
template <typename T>
std::mutex FreeList<T>::mu_;
template <typename T>
std::vector<T*> FreeList<T>::global_free_objects_;
// Returns a global singleton free list instance for a type.
template <typename T>
FreeList<T>& GetFreeList() {
static thread_local FreeList<T>* free_list = new FreeList<T>();
return *free_list;
}
// Allocates an object from the singleton free list for a type.
template <typename T, typename... Args>
typename FreeList<T>::Pointer AllocateFromFreeList(Args&&... args) {
return GetFreeList<T>().New(std::forward<Args>(args)...);
}
template <typename T>
class UnsafeFreeList;
template <typename T>
UnsafeFreeList<T>& GetUnsafeFreeList();
// An unsafe variant of FreeList. Faster, but it is up to the user to make sure
// the same thread frees objects as the one that allocates them.
template <typename T>
class UnsafeFreeList {
public:
typedef std::unique_ptr<T, std::function<void(void*)>> Pointer;
// How many objects to allocate at once.
static constexpr uint64_t kBatchSize = 32ul;
~UnsafeFreeList() {
for (T* mem : to_free_) {
std::free(mem);
}
}
void Release(void* raw_ptr) {
static_cast<T*>(raw_ptr)->~T();
objects_.emplace_back(static_cast<T*>(raw_ptr));
}
template <typename... Args>
Pointer New(Args&&... args) {
T* raw_ptr;
if (objects_.empty()) {
T* mem = static_cast<T*>(std::malloc(kBatchSize * sizeof(T)));
to_free_.emplace_back(mem);
for (size_t i = 0; i < kBatchSize - 1; ++i) {
objects_.emplace_back(&(mem[i]));
}
raw_ptr = &(mem[kBatchSize - 1]);
} else {
raw_ptr = objects_.back();
objects_.pop_back();
}
new (raw_ptr) T(std::forward<Args>(args)...);
return Pointer(raw_ptr, [this](void* ptr) { Release(ptr); });
}
// Returns the number of objects that this free list holds.
size_t NumObjects() const { return objects_.size(); }
UnsafeFreeList() {}
private:
// Free objects that can be assigned when needed.
std::vector<T*> objects_;
// The free list only releases memory upon destruction.
std::vector<T*> to_free_;
friend UnsafeFreeList& GetUnsafeFreeList<T>();
DISALLOW_COPY_AND_ASSIGN(UnsafeFreeList);
};
// Returns a global singleton free list instance for a type.
template <typename T>
UnsafeFreeList<T>& GetUnsafeFreeList() {
static UnsafeFreeList<T>* free_list = new UnsafeFreeList<T>();
return *free_list;
}
// Allocates an object from the singleton free list for a type.
template <typename T, typename... Args>
typename UnsafeFreeList<T>::Pointer AllocateFromUnsafeFreeList(Args&&... args) {
return GetUnsafeFreeList<T>().New(std::forward<Args>(args)...);
}
} // namespace nc
#endif
| true |
65e7001e0d840b3c3127ee7df89e533e7edc34a3 | C++ | BohuTANG/cascadb | /include/cascadb/comparator.h | UTF-8 | 1,026 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | // Copyright (c) 2013 The CascaDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#ifndef CASCADB_COMPARATOR_H_
#define CASCADB_COMPARATOR_H_
#include <assert.h>
#include "slice.h"
namespace cascadb {
class Comparator {
public:
virtual int compare(const Slice & s1, const Slice & s2) const = 0;
virtual ~Comparator(){}
};
class LexicalComparator : public Comparator {
public:
int compare(const Slice & s1, const Slice & s2) const
{
return s1.compare(s2);
}
};
template<typename NumericType>
class NumericComparator : public Comparator {
public:
int compare(const Slice & s1, const Slice & s2) const
{
assert(s1.size() == sizeof(NumericType) &&
s2.size() == sizeof(NumericType));
NumericType *n1 = (NumericType*)s1.data();
NumericType *n2 = (NumericType*)s2.data();
return *n1 - *n2;
}
};
}
#endif
| true |
d0bbeee9492981af2dec1e904967ace79caf042b | C++ | MikeAndTheWorld/Rocket-Wars | /Project/src/Rendering/Texture.cpp | UTF-8 | 3,217 | 3.15625 | 3 | [] | no_license | #include "Rendering\Texture.h"
////Create a Texture and set some default values.
//Texture::Texture(GLuint TexWidth, GLuint TexHeight, unsigned char* data) : SizeX(0), SizeY(0), Internal_Format(GL_RGBA), Image_Format(GL_BGRA), Wrap_S(GL_REPEAT), Wrap_T(GL_REPEAT), Filter_Min(GL_LINEAR), Filter_Max(GL_NEAREST) {
// glGenTextures(1, &this->TextureID);
//
// this->SizeX = TexWidth;
// this->SizeY = TexHeight;
// // Create Texture
// glBindTexture(GL_TEXTURE_2D, this->TextureID);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TexWidth, TexHeight, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
// // Set Texture wrap and filter modes
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, this->Wrap_S);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, this->Wrap_T);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, this->Filter_Min);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, this->Filter_Max);
// // Unbind texture
// glBindTexture(GL_TEXTURE_2D, 0);
//}
//
//void Texture::Bind() const {
// glBindTexture(GL_TEXTURE_2D, this->TextureID);
//}
void Texture::BmpLoader(std::string filePath)
{
// Data read from the header of the BMP file
unsigned char header[54]; // Each BMP file begins by a 54-bytes header
unsigned int dataPos; // Position in the file where the actual data begins
unsigned int width, height;
unsigned int imageSize; // = width*height*3
// Actual RGB data
unsigned char * data;
FILE * file = fopen(filePath.c_str(), "rb");
if (!file)
{
printf("Image could not be opened\n");
}
if (fread(header, 1, 54, file) != 54)
{ // If not 54 bytes read : problem
printf("Not a correct BMP file\n");
}
if (header[0] != 'B' || header[1] != 'M')
{
printf("Not a correct BMP file\n");
}
// Read ints from the byte array
dataPos = *(int*)&(header[0x0A]);
imageSize = *(int*)&(header[0x22]);
width = *(int*)&(header[0x12]);
height = *(int*)&(header[0x16]);
// Some BMP files are misformatted, guess missing information
if (imageSize == 0) imageSize = width*height * 3; // 3 : one byte for each Red, Green and Blue component
if (dataPos == 0) dataPos = 54; // The BMP header is done that way
// Create a buffer
data = new unsigned char[imageSize];
// Read the actual data from the file into the buffer
fread(data, 1, imageSize, file);
//Everything is in memory now, the file can be closed
fclose(file);
// Create one OpenGL texture
GLuint textureID;
glGenTextures(1, &textureID);
// "Bind" the newly created texture : all future texture functions will modify this texture
glBindTexture(GL_TEXTURE_2D, textureID);
// Give the image to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
GLuint Texture::GetTexture()
{
return textureID;
}
void Texture::Bind() {
glBindTexture(GL_TEXTURE_2D, this->textureID);
}
void Texture::Update(double DeltaTime)
{
}
void Texture::Render()
{
//glBindTexture(GL_TEXTURE_2D, this->textureID);
}
void Texture::Create(std::string filePath)
{
BmpLoader(filePath);
}
Texture::Texture()
{
} | true |
ccc28fce0564a25f34c07c864253305a931d913f | C++ | eyalbi/college-cpp-projects | /build_dictionary/Menu.cpp | UTF-8 | 1,620 | 3.546875 | 4 | [] | no_license | #include "Menu.h"
void Menu::MainMenu()
{
Definition temp;
String Stemp;
int i = ZERO, end;
cout << "Hello i am dictionary follow the instruction and hace fun" << endl;
do {
cout << "1. Create a dictionary\n\n2.Enter a new word to the dictionary\n\n3.Add a new definition to an existing word\n\n4.find a word in the dictionary\n\n5.Print all the words with the same defintions\n\n6.EXIT" << endl;
do {
cin >> end;
if(i == ZERO && end != 1 && end !=6){
cout << "you need to create a dictionary first try again" << endl;
}
if (i > ZERO && end == 1) {
cout << "the Dictionary allready exist please try a diffrent option" << endl;
cout << "1. Create a dictionary\n\n2.Enter a new word to the dictionary\n\n3.Add a new definition to an existing word\n\n4.find a word in the dictionary\n\n5.Print all the words with the same defintions\n\n6.EXIT" << endl;
}
} while ((end == 1 && i > ZERO) || (i == ZERO && end != 1 && end != 6));
i++;
getchar();
switch (end)
{
default:
cout << "invalid input try again\n";
break;
case 1:
EvenShushan = new Dictionary;
cin >> *EvenShushan;
break;
case 2:
cin >> temp;
*EvenShushan += temp;
break;
case 3:
cout << "enter a search word\n";
cin >> Stemp;
EvenShushan->SearchAndAdd(Stemp);
break;
case 4:
cout << "please enter a word for a search\n";
cin >> Stemp;
EvenShushan->SearchAndPrint(Stemp);
break;
case 5:
EvenShushan->SearchEqualDeff();
break;
case 6:
cout << "goodbye" << endl;
}
} while (end != 6);
}
| true |
c757c8c313860bc16c60dd8c192791dba00144a5 | C++ | tmgerard/Lateral-Earth-Pressure | /src/LateralEarthPressure.cpp | UTF-8 | 4,107 | 3.1875 | 3 | [] | no_license | #include <math.h>
#include "LateralEarthPressure.h"
/*
* Abstract class for lateral earth pressure of soil behind retaining walls.
* Classes for calculating earth pressures based on Rankine's or Coulomb's
* theory of lateral earth pressure shall inherit this class. Note that these
* classes do not take units into account.
*/
LateralEarthPressure::LateralEarthPressure() : mSoilUnitWeight(0.0),
mPhiAngle(0.0),
mBetaAngle(0.0),
mBottomDepth(0.0),
mOCR(1.0),
mState(PressureState::AtRest)
{
}
LateralEarthPressure::~LateralEarthPressure()
{
}
// Return the unit weight of the backfill soil.
double LateralEarthPressure::getUnitWeight() const
{
return mSoilUnitWeight;
}
// Return the backfill soil's friction angle.
double LateralEarthPressure::getPhiAngle() const
{
return mPhiAngle;
}
// Return the depth to the bottom of the retaining wall.
double LateralEarthPressure::getBottomDepth() const
{
return mBottomDepth;
}
// Return the overconsolidation ratio. This value will default to 1.0
// and will only change if the user sets a new ratio.
double LateralEarthPressure::getOCR() const
{
return mOCR;
}
// Return the slope angle of the backfill with respect to the top of the
// back wall.
double LateralEarthPressure::getBetaAngle() const
{
return mBetaAngle;
}
// Return the currently active pressure state based on the predicted
// deflection of retaining wall.
std::string LateralEarthPressure::getPressureState() const
{
if (mState == PressureState::Active)
{
return "Active";
}
else if(mState == PressureState::Passive)
{
return "Passive";
}
else
{
return "At-Rest";
}
}
// Set the unit weight of the soil.
void LateralEarthPressure::setUnitWeight(double weight)
{
mSoilUnitWeight = weight;
}
// Set the friction angle of the soil.
void LateralEarthPressure::setPhiAngle(double angle)
{
mPhiAngle = angle;
}
// Set the bottom of wall depth.
void LateralEarthPressure::setBottomDepth(double depth)
{
mBottomDepth = depth;
}
// Set the overconsolidation ratio.
void LateralEarthPressure::setOCR(double ocr)
{
mOCR = ocr;
}
// Set the fill slope angle.
void LateralEarthPressure::setBetaAngle(double angle)
{
mBetaAngle = angle;
}
// Set the pressure state based on predicted deflection of the retaining wall.
void LateralEarthPressure::setPressureState(PressureState state)
{
mState = state;
}
// Calculate the lateral earth pressure at the bottom of wall using
// EQ. 3.11.5.1-1 in the AASHTO LRFD Bridge Design Specifications,
// 7th Edition, with 2016 Interim Revisions. [pg. 3-104].
double LateralEarthPressure::lateralEarthPressure()
{
// Pure virtual function
}
// Calculate the lateral earth pressure at a given depth using
// EQ. 3.11.5.1-1 in the AASHTO LRFD Bridge Design Specifications,
// 7th Edition, with 2016 Interim Revisions. [pg. 3-104].
double lateralEarthPressure(double depth)
{
// Pure virtual function
}
// Calculate the at-rest lateral earth pressure coefficient using
// EQ. 3.11.5.2-2 in the AASHTO LRFD Bridge Design Specifications, 7th
// Edition, with 2016 Interim Revisions. [pg. 3-105]
double LateralEarthPressure::atRestLateralCoeficient()
{
return (1.0 - sin(mPhiAngle)) * pow(mOCR, sin(mPhiAngle));
}
// Calculate the passive lateral earth pressure coefficient using
// either Coulomb or Rankine theory of lateral earth pressure.
double LateralEarthPressure::passiveLateralCoefficient()
{
// Pure virtual function
}
// Calculate the active lateral earth pressure coefficient using
// either Coulomb or Rankine theory of lateral earth pressure
double LateralEarthPressure::activeLateralCoefficient()
{
// Pure virtual function
}
| true |
37521057803be58a7ffdea86b377e8c511772461 | C++ | mackeper/AlgorithmsAndDataStructures | /kattis/arrivingontime/time_table_graph.hpp | UTF-8 | 2,897 | 3.265625 | 3 | [] | no_license | #include <vector>
#include <queue>
#include <limits>
namespace popup {
class Edge {
public:
size_t from_;
size_t to_;
int64_t weight_;
size_t starting_time_;
size_t period_;
Edge(size_t from, size_t to, size_t starting_time, size_t period, int64_t weight) {
from_ = from;
to_ = to;
weight_ = weight;
starting_time_ = starting_time;
period_ = period;
}
};
class Graph {
size_t size_;
size_t capacity_;
std::vector<std::vector<Edge>> list_;
public:
Graph(size_t size) {
size_ = size;
capacity_ = size;
list_.resize(size);
}
void add_edge(size_t from, size_t to, int64_t start, int64_t period, int64_t weight) {
list_[from].emplace_back(Edge(from, to, start, period, weight));
};
// Dijkstra
int64_t dijkstra(size_t start, size_t from, size_t to){
std::priority_queue<std::pair<int64_t, size_t>,
std::vector<std::pair<int64_t, size_t>>,
std::greater<std::pair<int64_t, size_t>>> queue;
std::vector<int64_t> distances(capacity_, std::numeric_limits<int64_t>::max());
std::vector<size_t> came_from(capacity_, std::numeric_limits<int64_t>::max());
std::vector<bool> visited(capacity_, 0);
distances[from] = start;
queue.emplace(std::make_pair(start, from));
while (!queue.empty()) {
auto e = queue.top();
queue.pop();
auto current_node = e.second;
auto current_time = e.first;
if (visited[current_node]) {
continue;
}
visited[current_node] = true;
if (current_node == to) {
break;
}
for (auto& edge : list_[current_node]) {
auto node = edge.to_;
size_t t_to_open;
if (current_time <= (int64_t)edge.starting_time_) {
t_to_open = edge.starting_time_ - current_time;
} else if (edge.period_ == 0) {
continue;
} else {
t_to_open = (edge.period_ -
((current_time - edge.starting_time_)
% edge.period_)) % edge.period_;
}
size_t time_to_trav = current_time + edge.weight_ + t_to_open;
if ((size_t)distances[node] > time_to_trav) {
distances[node] = time_to_trav;
queue.push(
std::make_pair(time_to_trav, edge.to_)
);
came_from[node] = edge.from_;
}
}
}
if (!visited[to]) {
return std::numeric_limits<int64_t>::max();
} else {
return distances[to];
}
};
};
} // namespace popup
| true |
12ad3c31418cc517bf7a4a95c0654da3a831c220 | C++ | ioio-creative/FFMount | /FFMount_KineticController/src/Timeline.h | UTF-8 | 2,043 | 2.75 | 3 | [] | no_license | //A class for timeline that contain keyframes and calculate their tween values based on X position
//call getValueAtPos to get the tween value of keyframes
#ifndef __ParkYohoTimeline__
#define __ParkYohoTimeline__
#include <stdio.h>
#include "ofMain.h"
#include "ofxGui.h"
#include "Keyframe.h"
#include "ofEvents.h"
class Timeline
{
public:
ofEvent<Keyframe> keyframeAddedEvent; //a event for other class to listen to keyframe added
ofEvent<Keyframe> keyframeSelectedEvent; //a event for other class to listen to keyframe selected
ofEvent<int> keyframeDeselectedEvent; //a event for other class to listen to keyframe deselected
int NULL_FRAME;
vector <Keyframe> frames; //all the keyframes
ofRectangle rect;
Keyframe selectedKeyframe; //the selected keyframes (select keyframe for editing its value)
float scale;
float xPos;
float yPos;
float width;
float scroll; //scroll value of the timeline
int id; //id of this timeline
bool doAddKeyframeOnClick;
bool doRemoveKeyframeOnClick;
void setPos(float x, float y, float w, float scroll, int id, float sc); //set the position of timeline, scroll is the scroll amount of the graph
void addKeyframeOnClick(); //enable add keyframe mode
void addKeyframeByVal(float val, float x); //enable add keyframe mode
void removeKeyframeOnClick(); //enable remove keyframe mode
void selectKeyframeOnClick(); //disable add or remove keyframe mode
float getValueAtPos(float posX); //get the tween value at X position
void deselectKeyframes(); //deselect keyframes
//----------- To do --------------
void loadKeyframes();//load keyframes data to init the frames array
void saveKeyframes();//save keyframes data to file
void reset();//remove all keyframes and ready for load keyframes to add data
void setup();
void update();
void draw();
void mousePressed(int x, int y, int button);
private:
void sortKeyframes();
Keyframe nullKeyframe;
};
#endif
| true |
50d6744af0f0fb59b166352ed0b33b91352b977e | C++ | SeekerNik/code | /HRank/SequenceEquation.cpp | UTF-8 | 535 | 3.046875 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
vector<int> permutationEquation(vector<int> p)
{
map<int, int> result;
vector<int> ret;
for (int i = 0; i < p.size(); i++)
{
result[p[i]] = i + 1;
}
for (int j = 0; j < p.size(); j++)
{
int ind1 = result[p[j]];
int ind2 = result[ind1];
int ind3 = result[ind2];
ret.push_back(ind3);
}
return ret;
}
int main()
{
vector<int> a = {4,3,5,1,2};
permutationEquation(a);
return 0;
} | true |
75372fce60874154528ad91e909214aa6b07292e | C++ | miroslavavramov/Memory-Game | /26.10.2014_-_Jordan/MemoryCard/src/main.cpp | UTF-8 | 384 | 2.6875 | 3 | [] | no_license | #include "Game.h"
const int SCREEN_WIDTH = 1024;
const int SCREEN_HEIGHT = 768;
// our Game object
Game* g_game = 0;
int main(int argc, char* argv[]) {
g_game = new Game();
g_game->Init("Memory_;)", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_FULLSCREEN_DESKTOP);
//main loop
while (g_game->Running()) {
g_game->Update();
g_game->Draw();
} //end main loop
return 0;
}
| true |
56ae7d59a95062e0cfddb857f404b6f757c813a0 | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/40/2830.c | UTF-8 | 696 | 3.03125 | 3 | [] | no_license | double S(double a,double b,double c,double d,double m);
double max(double a,double b,double c,double d);
int main(int argc, char* argv[])
{
double a,b,c,d,m,ans;
scanf("%lf%lf%lf%lf%lf",&a,&b,&c,&d,&m);
if(max(a,b,c,d)<(a+b+c+d)/2)
{
m=m*3.1415926/180/2;
ans=S(a,b,c,d,m);
printf("%.4lf",ans);
}
else printf("Invalid input");
return 0;
}
double S(double a,double b,double c,double d,double m)
{
double S=0;
S=sqrt(((a+b+c+d)/2-a)*((a+b+c+d)/2-b)*((a+b+c+d)/2-c)*((a+b+c+d)/2-d)-a*b*c*d*cos(m)*cos(m));
return S;
}
double max(double a,double b,double c,double d)
{
if(a<b)
{
a=b;
}
if(c<d)
{
c=d;
}
if(a<c)
{
a=c;
}
return a;
}
| true |
9e0f84e556ea5a3365536f32b5968be8ea4c8cf2 | C++ | rcaelers/esp32-beacon-scanner | /components/loopp/include/loopp/utils/bitmask.hpp | UTF-8 | 5,497 | 2.734375 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2014 Dmitry Arkhipov
// Copyright (C) 2017 Rob Caelers <rob.caelers@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Based on https://github.com/grisumbras/enum-flags
#ifndef LOOPP_BITMASK_HPP
#define LOOPP_BITMASK_HPP
#include <type_traits>
namespace loopp
{
template<class Enum, class Enabler = void>
struct enable_bitmask : public std::false_type
{
};
template<class Enum>
struct BitMask
{
public:
static_assert(enable_bitmask<Enum>::value, "use DEFINE_BITMASK to enable bitmask for enum class");
using enum_type = typename std::decay<Enum>::type;
using underlying_type = typename std::underlying_type<enum_type>::type;
using impl_type = typename std::make_unsigned<underlying_type>::type;
public:
BitMask() noexcept = default;
BitMask(const BitMask &) noexcept = default;
BitMask &operator=(const BitMask &) noexcept = default;
BitMask(BitMask &&) noexcept = default;
BitMask &operator=(BitMask &&) noexcept = default;
constexpr BitMask(enum_type e) noexcept
: val(static_cast<impl_type>(e))
{
}
BitMask &operator=(enum_type e) noexcept
{
val = static_cast<impl_type>(e);
return *this;
}
constexpr explicit operator bool() const noexcept
{
return val;
}
constexpr bool operator!() const noexcept
{
return !val;
}
constexpr BitMask operator~() const noexcept
{
return BitMask(~val);
}
BitMask &operator&=(const BitMask &bitmask) noexcept
{
val &= bitmask.val;
return *this;
}
BitMask &operator|=(const BitMask &bitmask) noexcept
{
val |= bitmask.val;
return *this;
}
BitMask &operator^=(const BitMask &bitmask) noexcept
{
val ^= bitmask.val;
return *this;
}
// BitMask &operator&=(enum_type e) noexcept
// {
// val &= static_cast<impl_type>(e);
// return *this;
// }
// BitMask &operator|=(enum_type e) noexcept
// {
// val |= static_cast<impl_type>(e);
// return *this;
// }
// BitMask &operator^=(enum_type e) noexcept
// {
// val ^= static_cast<impl_type>(e);
// return *this;
// }
friend constexpr bool operator==(BitMask lhs, BitMask rhs)
{
return lhs.val == rhs.val;
}
friend constexpr bool operator!=(BitMask lhs, BitMask rhs)
{
return lhs.val != rhs.val;
}
friend constexpr BitMask operator&(BitMask lhs, BitMask rhs) noexcept
{
return BitMask{ static_cast<impl_type>(lhs.val & rhs.val) };
}
friend constexpr BitMask operator|(BitMask lhs, BitMask rhs) noexcept
{
return BitMask{ static_cast<impl_type>(lhs.val | rhs.val) };
}
friend constexpr BitMask operator^(BitMask lhs, BitMask rhs) noexcept
{
return BitMask{ static_cast<impl_type>(lhs.val ^ rhs.val) };
}
constexpr underlying_type value() const noexcept
{
return static_cast<underlying_type>(val);
}
void set(underlying_type v) noexcept
{
val = static_cast<impl_type>(v);
}
private:
constexpr explicit BitMask(impl_type val) noexcept
: val(val)
{
}
impl_type val;
};
template<class Enum>
constexpr auto operator&(Enum e1, Enum e2) noexcept -> typename std::enable_if<enable_bitmask<Enum>::value, loopp::BitMask<Enum>>::type
{
return loopp::BitMask<Enum>(e1) & e2;
}
template<class Enum>
constexpr auto operator|(Enum e1, Enum e2) noexcept -> typename std::enable_if<enable_bitmask<Enum>::value, loopp::BitMask<Enum>>::type
{
return loopp::BitMask<Enum>(e1) | e2;
}
template<class Enum>
constexpr auto operator^(Enum e1, Enum e2) noexcept -> typename std::enable_if<enable_bitmask<Enum>::value, loopp::BitMask<Enum>>::type
{
return loopp::BitMask<Enum>(e1) ^ e2;
}
} // namespace loopp
#define DEFINE_BITMASK(name) \
template<> \
struct enable_bitmask<name> : std::true_type \
{ \
};
#endif // LOOPP_BITMASK_HPP
| true |
77cf85d1db35530ad46210ea761e26fa77b820af | C++ | Ex-Soft/test | /ASP.NET/test/AnyTestIII/Test/Others/Lander/Lander.cpp | UTF-8 | 3,470 | 2.515625 | 3 | [] | no_license | #using <system.dll>
#using <mscorlib.dll>
#using <system.web.dll>
using namespace System;
using namespace System::Web::UI;
using namespace System::Web::UI::WebControls;
public __gc class LanderPage:public Page
{
protected:
static const double
gravity=1.625,
landermass=17198;
Label
*Altitude,
*Velocity,
*Acceleration,
*Fuel,
*ElapsedTime,
*Output;
TextBox
*Throttle,
*Seconds;
public:
void OnCalculate(Object *sender, EventArgs *argv)
{
try
{
double
alt1=Convert::ToDouble(Altitude->Text);
if(alt1>0)
{
if(Throttle->Text->Length==0)
{
Output->Text="Error: Required field missing";
return;
}
if(Seconds->Text->Length==0)
{
Output->Text="Error: Required field missing";
return;
}
double
throttle=Convert::ToDouble(Throttle->Text),
sec=Convert::ToDouble(Seconds->Text);
if(throttle<0 || throttle>100)
{
Output->Text="Error: Invalid throttle value";
return;
}
if(sec<=0)
{
Output->Text="Error: Invalid burn time";
return;
}
double
vel1=Convert::ToDouble(Velocity->Text),
fuel1=Convert::ToDouble(Fuel->Text),
time1=Convert::ToDouble(ElapsedTime->Text),
thrust=throttle*1200,
fuel=(thrust*sec)/2600,
fuel2=fuel1-fuel;
if(fuel<0)
{
Output->Text="Error: Insufficient fuel";
return;
}
Output->Text="";
double
avgmass=landermass+((fuel1+fuel2)/2),
force=thrust-(avgmass*gravity),
acc=force/avgmass,
vel2=vel1+(acc*sec),
avgvel=(vel1+vel2)/2,
alt2=alt1+(avgvel*sec),
time2=time1+sec;
if(alt2<=0)
{
double
mul=alt1/(alt1-alt2);
vel2=vel1-((vel1-vel2)*mul);
alt2=0;
fuel2=fuel1-((fuel1-fuel2)*mul);
time2=time1-((time1-time2)*mul);
if(vel2>=-4)
Output->Text="The Eagle has landed";
else
Output->Text="Kaboom!";
}
Altitude->Text=(new Double (alt2))->ToString("f1");
Velocity->Text=(new Double (vel2))->ToString("f1");
Acceleration->Text=(new Double (acc))->ToString("f1");
Fuel->Text=(new Double (fuel2))->ToString("f1");
ElapsedTime->Text=(new Double(time2))->ToString("f1");
}
}
catch(Exception *eException)
{
Output->Text=eException->Message;
}
}
}; | true |
c29059b21e9cf890440f424d93da2927f9d0df30 | C++ | rollfatcat/ProblemSet | /APCS試題/20190615/e294.cc | UTF-8 | 2,300 | 3.75 | 4 | [] | no_license | /* 題目給訂一個數字(字串)需要找到距離目前數字差值最小的『合法』數字,輸出差值
* 類似競賽題,需要自行觀察規律(規律不好找)
*/
#include<bits/stdc++.h>
using namespace std;
/* 輸出第一個出現『偶數』的位數,若無則輸出-1
* 初始判斷輸入的數字是否即符合條件(若是則直接輸出0)
*/
inline int Test(char Nss[]){
for(int i=0;Nss[i]!=0;i++)
if( (Nss[i]&1)==0 )
return i;
return -1;
}
/* 將輸入的字串轉換成對應的數字(long型態)
*/
inline long ToNumber(char Nss[],long ret=0){
for(int i=0;Nss[i]!=0;i++)
ret=(ret<<3)+(ret<<1)+Nss[i]-'0';
return ret;
}
/* 找到比現在這個數字還『大』的『合法』數字
* (從最高位)找到最早出現『偶數』的位數後將將這個位數+1(最大的偶數是8,8+1=9) 而後面的位數都變成'1'
*/
inline long UppToNumber(char Nss[],int idx,long ret=0){
for(int i=0;i<idx;i++)
ret=(ret<<3)+(ret<<1)+Nss[i]-'0';
ret=(ret<<3)+(ret<<1)+Nss[idx]+1-'0';
for(int i=idx+1;Nss[i]!=0;i++)
ret=(ret<<3)+(ret<<1)+1;
return ret;
}
/* 找到比現在這個數字還『小』的『合法』數字
* 難點:(從最高位)找到最早出現『偶數』的位數,這個位數是'0'時無法-1,須從這個位置向前面的位數『借位』(以維護前面的位數仍是奇數的特性)
* 作法:目前位數-1,若出現小於'0'的情況則向前一位『借位』(前一位的數值-2),直到(1)前一位的數值大於'0'或者(2)沒有前一位時
* 這個位數之後的部分都變成'9'
*/
inline long LowToNumber(char Nss[],int idx,long ret=0){
Nss[idx]--;
int i=idx;
while(i>0 and Nss[i]<'0')
Nss[i]='9',Nss[--i]-=2;
for(i=Nss[0]<'0';i<=idx;i++)
ret=(ret<<3)+(ret<<1)+Nss[i]-'0';
for(i=idx+1;Nss[i]!=0;i++)
ret=(ret<<3)+(ret<<1)+9;
return ret;
}
int main(){
char Nss[22];
while(scanf("%s",Nss)!=EOF){
int odd_pos=Test(Nss);
if(odd_pos==-1){ puts("0"); continue; }
long now_Num=ToNumber(Nss);
long upp_Num=UppToNumber(Nss,odd_pos)-now_Num;
long low_Num=now_Num-LowToNumber(Nss,odd_pos);
printf("%ld\n",(upp_Num>low_Num)?low_Num:upp_Num);
}
} | true |
ee3eeb30e4c036a0f146682d79af6b3d1df373de | C++ | brettdh/instruments | /src/debug.cc | UTF-8 | 2,607 | 2.640625 | 3 | [
"BSD-2-Clause"
] | permissive | #include "instruments.h"
#include "debug.h"
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "timeops.h"
#include <pthread.h>
#include <sstream>
#include <string>
#include <iomanip>
#include <stdexcept>
using std::ostringstream; using std::string;
using std::setw; using std::setfill;
using std::runtime_error;
#ifdef ANDROID
#define INSTRUMENTS_LOGFILE "/sdcard/intnw/instruments.log"
#include <android/log.h>
#endif
static void get_thread_name(char *name)
{
snprintf(name, 11, "%08lx", pthread_self());
}
static void vdbgprintf(bool plain, const char *fmt, va_list ap)
{
char thread_name[12];
get_thread_name(thread_name);
ostringstream stream;
if (!plain) {
struct timeval now;
TIME(now);
stream << "[" << now.tv_sec << "." << setw(6) << setfill('0') << now.tv_usec << "]";
stream << "[" << getpid() << "]";
stream << "[";
stream << thread_name;
stream << "] ";
}
string fmtstr(stream.str());
fmtstr += fmt;
#ifdef ANDROID
FILE *out = fopen(INSTRUMENTS_LOGFILE, "a");
if (out) {
vfprintf(out, fmtstr.c_str(), ap);
fclose(out);
} else {
int e = errno;
stream.str("");
stream << "Failed opening instruments log file: "
<< strerror(e) << " ** " << fmtstr;
fmtstr = stream.str();
__android_log_vprint(ANDROID_LOG_INFO, "instruments", fmtstr.c_str(), ap);
}
#else
vfprintf(stderr, fmtstr.c_str(), ap);
#endif
}
static instruments::DebugLevel debug_level = instruments::INFO;
void instruments::set_debug_level(enum instruments::DebugLevel level)
{
debug_level = level;
}
void instruments_set_debug_level(instruments_debug_level_t level_)
{
int level(level_);
ASSERT(level >= instruments::NONE && level <= instruments::DEBUG);
instruments::set_debug_level(instruments::DebugLevel(level));
}
int instruments::is_debugging_on(enum instruments::DebugLevel level)
{
return (level <= debug_level);
}
void instruments::dbgprintf_always(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vdbgprintf(true, fmt, ap);
va_end(ap);
}
void instruments::dbgprintf(enum instruments::DebugLevel level, const char *fmt, ...)
{
if (instruments::is_debugging_on(level)) {
va_list ap;
va_start(ap, fmt);
vdbgprintf(false, fmt, ap);
va_end(ap);
}
}
#ifdef __cplusplus
void check(bool success, const std::string& msg)
{
if (!success) {
throw runtime_error(msg);
}
}
#endif
| true |
dac44110bd78c587d4ca6eb163286c84f80544ac | C++ | MrAntex/Formes | /Point.cpp | UTF-8 | 806 | 2.9375 | 3 | [] | no_license | #include "Point.h"
#pragma once
//#include <iostream>
Point::Point(Vector2f _ancre) : ancre(_ancre), couleur(sf::Color::Black)
{}
Point::Point(const Point& orig) : ancre(orig.ancre){}
Point::~Point() {}
/*
bool Point::isOver(Vector2f _ancre) const
{
float dx = (ancre.x >= _ancre.x ? ancre.x - _ancre.x : _ancre.x - ancre.x);
float dy = (ancre.y >= _ancre.y ? ancre.y - _ancre.y : _ancre.x - ancre.y);
return (dx <= taille && dy <= taille);
}*/
void Point::dessiner(RenderWindow& fenetre, bool isactive) const
{
RectangleShape pt(Vector2f(taille,taille));
pt.setPosition(ancre);
pt.setFillColor(couleur);
fenetre.draw(pt);
}
/*
void Point::swapCoul(){
if (swapped){
Color tmp = couleur;
couleur = deux_couleur;
deux_couleur = tmp;
}
}*/ | true |
1de1e75c171a8d4d287dfe69276ffa658d76d158 | C++ | pengyaoc/Interview-Question | /Anagrams.cpp | UTF-8 | 885 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <unordered_map>
#include <string>
using namespace std;
vector<string> anagrams(vector<string> &strs) {
// map sorted string to its index
// If already in the output, set index to -1
unordered_map<string, int> stringMap;
string temp;
vector<string> ret;
for (int i=0; i<strs.size(); i++)
{
temp = strs[i];
sort(temp.begin(), temp.end());
auto itr = stringMap.find(temp);
if (itr != stringMap.end())
{
// if already in the output
if (itr->second != -1)
{
ret.push_back(strs[itr->second]);
itr->second = -1;
}
ret.push_back(strs[i]);
}
else
{
stringMap.insert(make_pair(temp, i));
}
}
return ret;
}
int main()
{
}
| true |
f2a1ce6fc721a3372f50fdb8cb07d50ea565da4f | C++ | KanadeSiina/PracticeCode | /201905_practice/ppp.cpp | UTF-8 | 869 | 2.65625 | 3 | [] | no_license | struct Node{
Node *l,*r;
int id;
Node(int _id):id(_id),l(NULL),r(NULL){}
};
Node* rt[maxn];
int tot;//编号
int ins[maxn];
#define Lson L,mid,o->l
#define Rson mid+1,R,o->r
void build(int L,int R,Node* &o)
{
o=new Node(tot++);
if(L==R)
{
addedge(o->id,L);
return;
}
int mid=L+R>>1;
build(Lson);
build(Rson);
addedge(o->id,o->l->id);addedge(o->id,o->r->id);
}
void update(int p,int l,int r,int L,int R,Node *o)
{
if(l<=L&&r>=R)
{
addedge(ins[p],o->id);
return;
}
int mid=L+R>>1;
if(l<=mid) update(p,l,r,Lson);
if(r>mid) update(p,l,r,Rson);
}
void add(int pos,int L,int R,Node* &o,Node* pre)
{
o=new Node(tot++);
if(L==R)
{
addedge(o->id,ins[pos]);
return;
}
int mid=L+R>>1;
if(pos<=mid)
{
add(pos,Lson,pre->l);
o->r=pre->r;
}
else{
add(pos,Rson,pre->r);
o->l=pre->l;
}
addedge(o->id,o->l->id);addedge(o->id,o->r->id);
}
| true |
5e19e9ed387b50a3243ed19705e3d9ad5a145e3d | C++ | AndyJVain/lab-projects | /COEN70 Formal Specification and Advanced Data Structures/project8/pqueue.cpp | UTF-8 | 3,412 | 3.671875 | 4 | [] | no_license | // FILE: pqueue.cpp
// IMPLEMENTS: The functions of the pqueue class.
// INVARIANT for the node class:
// The data of a node is stored in data_field,
// the link to the next node is stored in link_field,
// and the priority is stored in priority_field.
#include "pqueue.h"
#include <cassert> // Provides assert
#include <iostream> // Provides cin and cout
#include <cstdlib> // Provides NULL and size_t
using namespace std;
namespace coen70_lab8
{
// Constructors
PriorityQueue::PriorityQueue( )
{
head_ptr = NULL;
many_nodes = 0;
}
PriorityQueue::PriorityQueue(const PriorityQueue& other)
{
head_ptr = NULL;
many_nodes = 0;
*this = other;
}
// Destructor
PriorityQueue::~PriorityQueue( )
{
clear( );
head_ptr = NULL;
}
// Modification Member Functions
void PriorityQueue::operator =(const PriorityQueue& other)
{
// Checks for self assignment
if(this == &other)
return;
// Clears the queue if it contained nodes to prepare for
// copying over the PriorityQueue "other"
clear( );
// Copies over the PriorityQueue "other"
node* temp = other.head_ptr;
while(temp != NULL) {
insert(temp->data( ),temp->priority( ));
temp = temp->link( );
}
}
void PriorityQueue::insert(const Item& entry, unsigned int priority)
{
// If the queue is empty
if(head_ptr == NULL)
head_ptr = new node(entry, priority);
// If the queue is not empty
else
{
// If inserting before the head
if(head_ptr->priority( ) < priority)
head_ptr = new node(entry, priority, head_ptr);
// If inserting after the head
else
{
node* temp = head_ptr;
node* iter = head_ptr->link( );
// Moves to find the correct place to insert
while(iter != NULL && iter->priority( ) >= priority)
{
temp = iter;
iter = iter->link( );
}
// Insert after temp and before iter
node* newNode = new node(entry,priority,iter);
temp->set_link(newNode);
}
}
++many_nodes;
}
PriorityQueue::Item PriorityQueue::get_front( )
{
// Checks that there is at least 1 node to return
assert(size( ) > 0);
// Returns the data after deleting the node
node* remove = head_ptr;
Item data = head_ptr->data( );
head_ptr = head_ptr->link( );
--many_nodes;
delete remove;
return data;
}
// Helper function for the assignment operator
void PriorityQueue::clear( )
{
node* temp = head_ptr;
// Moves the head_ptr throught the Priority Queue,
// using temp to delete each node
while(head_ptr != NULL)
{
head_ptr = head_ptr->link( );
delete temp;
temp = head_ptr;
}
many_nodes = 0;
}
}
| true |
2934f6cf43c307de13d58cedd51e70c9437e91d1 | C++ | codersalman/Technocrats-HacktoberFest | /Data Structures and Coding Algorithm/03. Stack/Stack_sort_using_another_stack.cpp | UTF-8 | 1,324 | 3.96875 | 4 | [
"MIT"
] | permissive | /*
Sort a stack using a temporary stack
*/
/*
Algo:--
Create a temporary stack say temp.
While input stack is NOT empty do this:
Pop an element from input stack call it temp
while temporary stack is NOT empty and top of temporary stack is greater than temp,
pop from temporary stack and push it to the input stack
push temp in temporary stack
The sorted numbers are in temp
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<int>s,temp;
int n,i,x;
cin>>n; // size of stack
for(i=0;i<n;i++){
cin>>x; // input
s.push(x);
}
while(!s.empty()){
x=s.top();
s.pop(); // pop out the first element
if(temp.empty() || temp.top() <x) temp.push(x);
else{
// while temporary stack is not empty and top
// of stack is greater than temp
while(!temp.empty() && temp.top() >x){
// pop from temporary stack and push
// it to the input stack
s.push(temp.top());
temp.pop();
}
// push temp in temporary of stack
temp.push(x);
}
}
// print the sorted stack
while(!temp.empty()){
cout<<temp.top()<<" ";
temp.pop();
}
}
| true |
9ca0d4d3e42b01561bc877a2458adfff44280afc | C++ | nyanp/STF | /STF/stf/util/Macros.h | UTF-8 | 2,687 | 3 | 3 | [] | no_license | /**
* @file Macros.h
* @brief STF全体で使用する簡単なマクロ関数を記述する.
*
* @author Taiga Nomi
* @date 2011.02.16
*/
#ifndef Macros_h
#define Macros_h
// コピーコンストラクタと=演算子関数を無効にするマクロ
// これはクラスの private: 宣言の中で使うべきだ。
// from: google C++ coding styles
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#define DISALLOW_COPY_AND_ASSIGN_1(TypeName, T1) \
TypeName(const TypeName<T1>&); \
void operator=(const TypeName<T1>&)
#define DISALLOW_COPY_AND_ASSIGN_2(TypeName, T1, T2) \
TypeName(const TypeName<T1, T2>&); \
void operator=(const TypeName<T1, T2>&)
#define DISALLOW_COPY_AND_ASSIGN_3(TypeName, T1, T2, T3) \
TypeName(const TypeName<T1, T2, T3>&); \
void operator=(const TypeName<T1, T2, T3>&)
#define DISALLOW_COPY_AND_ASSIGN_4(TypeName, T1, T2, T3, T4) \
TypeName(const TypeName<T1, T2, T3, T4>&); \
void operator=(const TypeName<T1, T2, T3, T4>&)
#define DO_UPDATE_SIMULATOR() \
public:\
virtual void do_update(){\
do_update(Loki::Type2Type<Env>());\
}\
private:\
template<class T> void do_update(Loki::Type2Type<T>);\
template<class App> void do_update(Loki::Type2Type<environment::Simulator<App> >)\
#define INIT() \
virtual void init(){\
init(Loki::Type2Type<Env>());\
}\
template<class T> void init(Loki::Type2Type<T>){}\
template<class App> void inti(Loki::Type2Type<environment::Simulator<App> >)
namespace stf {
//! T->Uへの変換可能性をコンパイル時に検出するType Manipulator.
template<class T, class U>
class Conversion
{
typedef char Small;
class Big{ char dummy[2]; };
static Small Test(U);
static Big Test(...);
static T MakeT();
public:
enum { exists = sizeof(Test(MakeT())) == sizeof(Small) };
};
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
}//end of namespace stf
//! コンパイル時表明を行うマクロ.
/*
LokiのSTATIC_CHECKは関数スコープでしか使えないが,
こちらはクラススコープでも使える.テンプレートクラスのConcept宣言などに.
*/
#define STF_STATIC_ASSERT(expr, msg) \
CompileTimeError<((expr) != 0)> ERROR_##msg
//! 型の継承関係をコンパイル時に強制させるStatic Assert.
/*
derivedの型はbaseと一致するか,baseから派生した型でなければならない.
*/
#define MUST_BE_DERIVED_FROM(derived, base) \
STF_STATIC_ASSERT((Conversion<derived, base>::exists != 0), IS_NOT_CONVARIANT)
#endif // Macros_h | true |
068625ebf6bd22ba3ebd762f440c78549c1bb082 | C++ | RezzaRect/SandBox | /rendering/Shader.h | UTF-8 | 766 | 2.53125 | 3 | [] | no_license | #ifndef SHADER_H
#define SHADER_H
#include <string>
#define GLEW_STATIC
#include <GL/glew.h>
#include "../core/Camera.h"
#include "../core/Transform.h"
// Reference: https://github.com/BennyQBD/ModernOpenGLTutorial
class Shader
{
public:
Shader(const std::string& fileName);
void Bind();
void Update(const Transform& transform, Camera& camera);
virtual ~Shader();
GLuint m_program;
protected:
private:
static const unsigned int NUM_SHADERS = 2;
static const unsigned int NUM_UNIFORMS = 16;
//Shader(const Shader& other){}
//void Shader& operator=(const Shader& other){}
GLuint m_shaders[NUM_SHADERS];
GLuint m_uniforms[NUM_UNIFORMS];
};
#endif // SHADER_H
| true |
d4eaf8745f268930e9b0d1804c675e0d21efc4e9 | C++ | Dragon-qing/vs | /visual studio的代码/练习/4/源.cpp | GB18030 | 814 | 3.3125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Household_electricity
{
private:
double consumption, coefficient;
public:
Household_electricity(int x,int y):consumption(x), coefficient(y){}
double cal() { return consumption * 0.785 * coefficient; }
void display();
};
class car
{
double Fuel;
public:
car(int x):Fuel(x){}
double cal() { return Fuel * 0.785; }
void display();
};
class plane
{
double x, con;//x con÷ɻĵλͲ˾̼ŷ
public:
plane(double dis,double co):x(dis),con(co){}
double short_distance() { return x * 0.275 * con; }//;У200
double Half() {return 55 + 0.105 * (x-200);}//;У2001000
double long_journey() {return x * 0.139;}//;
double cal();//
void display();
};
int main()
{
return 0;
} | true |
896bf5e5545b11fb2a039a5b2cb757a9ae3eaac8 | C++ | massimilianonardi/m | /os/sunaptos_bak/bak/sunaptos_28_class_sequence_element/src/test/sequence.h | UTF-8 | 3,591 | 2.96875 | 3 | [
"MIT"
] | permissive | #ifndef _SEQUENCE_H
#define _SEQUENCE_H
#include <vector>
#include <sstream>
using namespace std;
#include "debug.h"
//typedef char element;
typedef bool element;
//enum class sequence_type
//{
// unspecified_pointer_t = -1,
// unspecified_t = 0,
// sequence_t = 1,
// service_t = 2,
// boolean_t = 100,
// integer_t = 110,
// floating_point_t = 120,
// timestamp_t = 130,
// date_t = 140,
// character_t = 200,
// string_ascii_t = 210,
// string_utf_8_t = 220,
// string_utf_16_t = 230,
// email_t = 360,
//};
//typedef enum sequence_type sequence_type;
//class seq_type
class sequence_type
{
public:
enum type
{
unspecified_pointer_t = -1,
unspecified_t = 0,
sequence_t = 1,
service_t = 2,
boolean_t = 100,
integer_t = 110,
floating_point_t = 120,
timestamp_t = 130,
date_t = 140,
character_t = 200,
string_ascii_t = 210,
string_utf_8_t = 220,
string_utf_16_t = 230,
email_t = 360,
};
};
//typedef enum seq_type::type sequence_type;
class sequence;
// reference to existing objects -> must have the same life scope!
class sequence_element
{
protected:
bool is_seq;
union
{
element* e;
sequence* s;
};
private:
// sequence_element(): e(0), is_seq(false) {}
public:
// sequence_element(element* element): e(element), is_seq(false) {}
// sequence_element(sequence* sequence): s(sequence), is_seq(true) {}
sequence_element(element& element);
sequence_element(sequence& sequence);
operator element*();
operator sequence*();
operator element&();
operator sequence&();
// sequence_element& operator=(element* element) {e = element; is_seq = false; return *this;}
// sequence_element& operator=(sequence* sequence) {s = sequence; is_seq = true; return *this;}
sequence_element& operator=(element& element);
sequence_element& operator=(sequence& sequence);
// sequence_element& operator=(element elem) {e = &elem; is_seq = false; return *this;}
// sequence_element& operator=(sequence seq) {s = &seq; is_seq = true; return *this;}
bool is_sequence();
element& elem();
sequence& seq();
};
// numbers are copied into the internal buffer, char* and sequence* are kept by references (char* should be copied and sequence* must have an option to choose to make a copy)
class sequence//: virtual public Streamable
{
protected:
vector<sequence_element> vse;
// sequence_type t;
sequence_type::type t;
element b[sizeof(long double)];
public:
// constructor and destructor
sequence();
virtual ~sequence();
// copy
// sequence(sequence& seq);
// sequence(const sequence& seq);
// sequence& operator=(sequence e);
// sequence& operator=(sequence& e);
// sequence& copy(sequence& e);
// type conversions
sequence(int e);
sequence(long e);
sequence(long long e);
sequence(float e);
sequence(double e);
sequence(long double e);
sequence(const char* e);
operator int();
operator long();
operator long long();
operator float();
operator double();
operator long double();
operator const char*();
sequence& operator=(int e);
sequence& operator=(long e);
sequence& operator=(long long e);
sequence& operator=(float e);
sequence& operator=(double e);
sequence& operator=(long double e);
sequence& operator=(const char* e);
// access
// sequence_element& get(sequence& i);
sequence_element& get(sequence i);
sequence& del(sequence& i);
// void resize(sequence& size);
void resize(sequence size);
sequence size();
// type type();
// void set_type(type type);
char* text();
};
#endif // _SEQUENCE_H
| true |
5dac223e565ceb1b0e314e3461d768c83f958ca8 | C++ | diwadd/sport | /cf_districts_connection.cpp | UTF-8 | 1,889 | 2.859375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef unsigned long long int ulli;
typedef long double ld;
void left_just(string &s, int n, char c = ' ') {
while(s.length() < n) {
s = c + s;
}
}
template<typename T> void print_vector(vector<T> &vec) {
int n = vec.size();
for(int i = 0; i < n; i++) {
if(i == n - 1)
cout << vec[i];
else
cout << vec[i];
}
cout << "\n";
}
template<typename T> void print_matrix(vector<vector<T>> &mat) {
for(int i = 0; i < mat.size(); i++) {
print_vector(mat[i]);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
for(int t = 0; t < T; t++) {
int N;
cin >> N;
vector<int> a_vec(N, 0);
for(int i = 0; i < N; i++) {
cin >> a_vec[i];
}
set<int> s(a_vec.begin(), a_vec.end());
if(s.size() == 1) {
cout << "NO\n";
continue;
}
vector<pair<int, vector<int>>> graph;
int INIT_CAPA = 100;
for(int i = 0; i < N; i++) {
pair<int, vector<int>> p = {a_vec[i], vector<int>()};
graph.push_back(p);
graph.back().second.reserve(INIT_CAPA);
}
for(int i = 0; i < N; i++) {
if(graph[i].second.size() != 0) {
continue;
}
for(int j = 0; j < N; j++) {
if(graph[j].first == a_vec[i])
continue;
graph[j].second.push_back(i);
break;
}
}
cout << "YES\n";
for(int i = 0; i < N; i++) {
for(int j = 0; j < graph[i].second.size(); j++) {
cout << i + 1 << " " << graph[i].second[j] + 1 << "\n";
}
}
}
} | true |
162458429beb8c258a316be122fbce2f3587475f | C++ | kyungee/algorithm | /acmicpc/acm_15650.cpp | UTF-8 | 640 | 2.734375 | 3 | [] | no_license |
// https://www.acmicpc.net/problem/15650
#include <vector>
#include <stdio.h>
#include <iostream>
using namespace std;
#define MAX 10
int n, m;
bool visit[MAX];
vector<int> v;
void DFS(int idx, int cnt) {
if(cnt == m) {
for(int i=0; i<v.size(); i++) {
printf("%d ", v[i]);
}
printf("\n");
return;
}
for(int i=idx; i<n; i++) {
if(visit[i] == true) continue;
visit[i] = true;
v.push_back(i+1);
DFS(i, cnt+1);
v.pop_back();
visit[i] = false;
}
}
int main() {
scanf("%d %d", &n, &m);
DFS(0, 0);
return 0;
}
| true |
caed0bcebadd24a7f4dff52620f519e3e1725094 | C++ | iCodeIN/stdext | /lib/fs.cpp | UTF-8 | 4,553 | 2.765625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2019 - Gabriel Cuvillier, Continuation Labs (www.continuation-labs.com)
// Licensed under the MIT License.
// Main header
// #include <stdext/fs>
// std
#include <cstring> // std::strcpy
#include <string> // std::string
#if defined( STDEXT_USE_CPP_FILESYSTEM_BACKEND )
#if __has_include( <filesystem> )
//#pragma message("<filesystem>")
#include <filesystem>
namespace fs = std::filesystem;
#elif __has_include( <experimental/filesystem> )
//#pragma message("<experimental/filesystem>")
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#else
#error "std::filesystem not implemented for current platform"
#endif
namespace stdext
{
std::string get_current_directory() noexcept { return fs::current_path().string(); }
void change_current_directory( std::string const& path ) noexcept { fs::current_path( path ); }
std::string get_file_name( std::string const& path ) noexcept { return fs::path( path ).filename().string(); }
std::string get_directory_name( std::string const& path ) noexcept
{
return fs::path( path ).remove_filename().filename().string();
}
} // namespace stdext
#else
// MSVC
#if defined( _WIN32 ) && !defined( __MINGW32__ ) // Let's use regular unix-style calls for MinGW
#define USE_STRICT_CONST
#include <Shlwapi.h> // PathFindFileNameA, PathFindDirNameA
#include <direct.h> // _chdir, _get_cwd
// LINUX, GNU/LINUX, MSYS, MINGW, CYGWIN, EMSCRIPTEN
#elif defined( __linux__ ) || defined( __gnu_linux__ ) || defined( __MSYS__ ) || defined( __CYGWIN__ ) || \
defined( __MINGW32__ ) || defined( __EMSCRIPTEN__ ) || defined( __unix__ )
#include <libgen.h> // basename, dirname
#include <unistd.h> // chdir, getcwd
#include <climits> // PATH_MAX
#else
#error "std::filesystem not implemented for current platform"
#endif
namespace
{
#if defined( __linux__ ) || defined( __gnu_linux__ ) || defined( __MSYS__ ) || defined( __CYGWIN__ ) || \
defined( __MINGW32__ ) || defined( __EMSCRIPTEN__ ) || defined( __unix__ )
template<char* ( *F )( char* )>
std::string safe_apply_to_str( std::string const& str )
{
auto psz_tmp = new char[str.size() + 1];
psz_tmp[str.size()] = 0;
std::strcpy( psz_tmp, str.c_str() );
std::string result_str = F( psz_tmp );
delete[] psz_tmp;
return result_str;
}
#endif
} // namespace
namespace stdext
{
std::string get_current_directory()
{
#if defined( _WIN32 ) && !defined( __MINGW32__ )
auto buf = new char[MAX_PATH];
buf = ::_getcwd( buf, MAX_PATH );
#elif defined( __linux__ ) || defined( __gnu_linux__ ) || defined( __MSYS__ ) || defined( __CYGWIN__ ) || \
defined( __MINGW32__ ) || defined( __EMSCRIPTEN__ ) || defined( __unix__ )
auto buf = new char[PATH_MAX];
buf = ::getcwd( buf, PATH_MAX );
#else
#error "std::filesystem not implemented for current platform"
#endif
std::string result_str = buf;
delete[] buf;
return result_str;
}
int change_current_directory( std::string const& path )
{
#if defined( _WIN32 ) && !defined( __MINGW32__ )
return ::_chdir( path.c_str() );
#elif defined( __linux__ ) || defined( __gnu_linux__ ) || defined( __MSYS__ ) || defined( __CYGWIN__ ) || \
defined( __MINGW32__ ) || defined( __EMSCRIPTEN__ ) || defined( __unix__ )
return ::chdir( path.c_str() );
#else
#error "std::filesystem not implemented for current platform"
#endif
}
std::string get_file_name( std::string const& path )
{
#if defined( _WIN32 ) && !defined( __MINGW32__ )
return std::string( ::PathFindFileNameA( path.c_str() ) );
#elif defined( __linux__ ) || defined( __gnu_linux__ ) || defined( __MSYS__ ) || defined( __CYGWIN__ ) || \
defined( __MINGW32__ ) || defined( __EMSCRIPTEN__ ) || defined( __unix__ )
return safe_apply_to_str< ::basename>( path );
#else
#error "std::filesystem not implemented for current platform"
#endif
}
std::string get_directory_name( std::string const& path )
{
#if defined( _WIN32 ) && !defined( __MINGW32__ )
auto psz_tmp = new char[path.size() + 1];
psz_tmp[path.size()] = 0;
std::strcpy( psz_tmp, path.c_str() );
if ( ::PathRemoveFileSpecA( psz_tmp ) ) {
std::string result_str = psz_tmp;
delete[] psz_tmp;
return result_str;
} else {
delete[] psz_tmp;
return std::string();
}
#elif defined( __linux__ ) || defined( __gnu_linux__ ) || defined( __MSYS__ ) || defined( __CYGWIN__ ) || \
defined( __MINGW32__ ) || defined( __EMSCRIPTEN__ ) || defined( __unix__ )
return safe_apply_to_str< ::dirname>( path );
#else
#error "std::filesystem not implemented for current platform"
#endif
}
} // namespace stdext
#endif | true |
a402749023e599e5e8682affebf00fef556c6aa9 | C++ | slantto/slantto.github.io | /IS-ICE/Code/IS_ICE_CONTROL_BUTT/getDataFromPi.ino | UTF-8 | 1,501 | 2.640625 | 3 | [] | no_license | void getDataFromPi() {
// receive data from PC and save it into inputBuffer
if(Serial.available() > 0) {
char x = Serial.read();
// the order of these IF clauses is significant
if (x == endMarker) {
readInProgress = false;
newDataFromPC = true;
inputBuffer[bytesRecvd] = 0;
parseData();
Serial.println("<Command Parsed>");
}
if(readInProgress) {
inputBuffer[bytesRecvd] = x;
bytesRecvd ++;
if (bytesRecvd == buffSize) {
bytesRecvd = buffSize - 1;
}
Serial.println("<read in progress>");
}
if (x == startMarker) {
bytesRecvd = 0;
readInProgress = true;
Serial.println("<Command recieved>");
}
}
}
void parseData(){
//split commands from the pi into required components
char* strtokIndx;
strtokIndx = strtok(inputBuffer,","); //get first part
//messageFromPC =
strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
switchCom = atoi(strtokIndx); // convert this part to an integer
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
COMPARAM1 = atof(strtokIndx); // convert this part to an integer
strtokIndx = strtok(NULL, ",");
COMPARAM2 = atof(strtokIndx); // convert this part to a float
strtokIndx = strtok(NULL, ",");
COMPARAM3 = atof(strtokIndx); // convert this part to a float
}
| true |
27251204da4d568903ca72d643b8d6b4847004dd | C++ | TaelorMcMillan/FishBowlProject | /FishTankBase/src/solar/Sphere.cpp | UTF-8 | 906 | 2.53125 | 3 | [] | no_license | #include "Sphere.hpp"
Sphere::Sphere() {
radius = 1.0;
mode = MODE_WIRE;
textureID = 0;
splices = 50;
stacks = 50;
quad = gluNewQuadric();
sx = 1 ;
sy = 1 ;
sz = 1 ;
}
Sphere::~Sphere() {
gluDeleteQuadric(quad);
}
void Sphere::draw() {
quad = gluNewQuadric();
gluQuadricTexture(this->quad, GL_TRUE);
gluQuadricOrientation(this->quad, GLU_OUTSIDE);
gluQuadricNormals(this->quad, GLU_SMOOTH);
glPushMatrix();
ctmMultiply();
glEnable(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, textureID);
glScalef(this->s, this->s, this->s);
glScalef(this->sx, this->sy, this->sz);
gluSphere(this->quad, radius, 50, 50);
glDisable(GL_TEXTURE_2D);
gluDeleteQuadric(this->quad);
glPopMatrix();
}
| true |
2cb2a10c5084a2a595583a561163befcec1dcf26 | C++ | KKozlowski/PAGI2016 | /PAGI 3/Timer.h | UTF-8 | 602 | 2.875 | 3 | [] | no_license | #pragma once
#include <chrono>
#include <iostream>
#include "main.h"
using namespace std::chrono;
class Timer
{
private:
milliseconds pastMoment;
unsigned long long deltaMs;
float deltaTime;
public:
Timer()
{
pastMoment = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
}
void update()
{
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);
deltaMs = ms.count() - pastMoment.count();
deltaTime = (float)deltaMs / 1000.0f;
pastMoment = ms;
}
float get_delta_time() const
{
return deltaTime;
}
};
| true |
116b8b739e73dd1d8e23f46d33651a0adfd852a3 | C++ | BGCX261/z-one-svn-to-git | /trunk/other/charles/sprite.h | UTF-8 | 418 | 2.53125 | 3 | [] | no_license | /**
*@file rs232.c
*@date 30/05/2012
*@author Charles Oliveira
*@author Rodrigo Siqueira
*@brief Arquivo com as implementações de rs232.
**/
/**
*@class Sprite
*@date 11/17/2012
*@author Charles Oliveira
*@brief Classe responsável por funcionalidades dos sprites
*/
class Sprite
{
public:
short width; /**< Largura do sprite */
short height; /**< Altura do sprite */
char movements; /**< Numero de movimentos do sprite */
};
| true |
8ac1ebc5fbb35541097fbbbfda3d55938a546dca | C++ | jiutianbrother/binder_like | /utils/CondVariable.cpp | UTF-8 | 2,883 | 2.765625 | 3 | [] | no_license | /*
* File: CondVariable.cpp
* Desc: 条件变量实现文件
* Author: fanxiaoyu
*
*/
#include <errno.h>
#include <Logger.h>
#include <CondVariable.h>
extern Logger log;
/***********************************************************/
/* public */
/***********************************************************/
CondVariable::CondVariable(CondVariableAttr attr)
: mCondAttr(attr)
, mIsCondInited(false)
, mIsCondAttrInited(false)
{
if (false == initPosixCondAttr()){
return;
}
if (pthread_cond_init(&mCond, &mPosixCondAttr) < 0){
LOG("init cond failed");
return;
}
mIsCondInited = true;
}
CondVariable::~CondVariable()
{
if (mIsCondAttrInited){
pthread_condattr_destroy(&mPosixCondAttr);
}
if (mIsCondInited){
pthread_cond_destroy(&mCond);
}
}
bool CondVariable::wait(MutexLock *lock)
{
int ret;
if (!mIsCondInited || !mIsCondAttrInited){
LOG("mIsCondInited=%d, mIsCondAttrInited=%d",
mIsCondInited, mIsCondAttrInited);
return false;
}
ret = pthread_cond_wait(&mCond, &lock->mLock);
if (ret < 0){
LOG("cond wait failed(ret=%d)", ret);
return false;
}
return true;
}
int CondVariable::timedWait(MutexLock *lock, struct timeval *abstime)
{
int ret;
struct timespec ts;
if (!mIsCondInited || !mIsCondAttrInited){
LOG("mIsCondInited=%d, mIsCondAttrInited=%d",
mIsCondInited, mIsCondAttrInited);
return false;
}
ts.tv_sec = abstime->tv_sec;
ts.tv_nsec = abstime->tv_usec * 1000;
ret = pthread_cond_timedwait(&mCond, &lock->mLock, &ts);
if (ret < 0 && ret != ETIMEDOUT){
LOG("cond timed wait failed(ret=%d)", ret);
return false;
}
else if (ret < 0){
LOG("cond timed out");
}
return ret;
}
bool CondVariable::signal()
{
int ret;
if (!mIsCondInited || !mIsCondAttrInited){
LOG("mIsCondInited=%d, mIsCondAttrInited=%d",
mIsCondInited, mIsCondAttrInited);
return false;
}
ret = pthread_cond_signal(&mCond);
if (ret < 0){
LOG("cond signal failed(ret=%d)", ret);
return false;
}
return true;
}
bool CondVariable::broadcast()
{
int ret;
if (!mIsCondInited || !mIsCondAttrInited){
LOG("mIsCondInited=%d, mIsCondAttrInited=%d",
mIsCondInited, mIsCondAttrInited);
return false;
}
ret = pthread_cond_broadcast(&mCond);
if (ret < 0){
LOG("cond broadcast failed(ret=%d)", ret);
return false;
}
return true;
}
/***********************************************************/
/* private */
/***********************************************************/
bool CondVariable::initPosixCondAttr()
{
/*目前仅使用默认的条件变量属性*/
if (pthread_condattr_init(&mPosixCondAttr) < 0){
LOG("init cond attr failed");
mIsCondAttrInited = false;
return false;
}
mIsCondAttrInited = true;
return true;
}
| true |
e92e075ffd49130aff93aebd1cde66259fe3193e | C++ | pgrAm/JSD-OS | /apps/listmode.cpp | UTF-8 | 593 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <sys/syscalls.h>
#include <terminal/terminal.h>
#include <stdio.h>
#include <stdlib.h>
terminal s_term{"terminal_1"};
int main(int argc, char** argv)
{
set_stdout(
[](const char* buf, size_t size, void* impl)
{
s_term.print(buf, size);
return size;
});
display_mode mode;
int i = 0;
while(get_display_mode(i, &mode) == 0)
{
if(mode.flags & DISPLAY_TEXT_MODE)
printf("text ");
else
printf("graphics ");
printf("%-4d x %-4d @ %-2d", mode.width, mode.height, mode.bpp);
if(i & 1)
putchar('\n');
else
putchar('\t');
i++;
}
return 42;
} | true |
7053dde50672d4df98466865e5d7ecf7dbdd980a | C++ | Time-Coder/Data_Structure | /Tree/BinTree/BST/RedBlack/redblack.cpp | UTF-8 | 2,964 | 2.828125 | 3 | [] | no_license | #ifdef REDBLACK_H
template<class KeyType>
typename BinTree<KeyType>::Node*
RedBlack<KeyType>::red_child(typename BinTree<KeyType>::Node* node)
{
if(!node)
{
return NULL;
}
if(is_red(node->lchild))
{
return node->lchild;
}
if(is_red(node->rchild))
{
return node->rchild;
}
return NULL;
}
template<class KeyType>
void RedBlack<KeyType>::update_height(typename BinTree<KeyType>::Node* node)
{
if(node)
{
node->height = this->height(node->lchild) + this->height(node->rchild);
if(node->color == BLACK)
{
node->height++;
}
}
}
template<class KeyType>
bool RedBlack<KeyType>::is_black(typename BinTree<KeyType>::Node* node)
{
return (!node || node->color == BLACK);
}
template<class KeyType>
bool RedBlack<KeyType>::is_red(typename BinTree<KeyType>::Node* node)
{
return (node && node->color == RED);
}
template<class KeyType>
void RedBlack<KeyType>::solve_red2(typename BinTree<KeyType>::Node* x)
{
if(!x)
{
return;
}
if(!(x->parent))
{
x->color = BLACK;
return;
}
auto p = x->parent;
if(is_black(p))
{
return;
}
// 能到这里说明 p 是红色
auto g = p->parent; // g 一定存在,因为如果没有 g,说明 p(红色) 是根结点,不合法。
auto u = this->brother(p);
if(is_black(u))
{
auto b = this->rebalance(x, p, g);
b->lchild->color = RED;
b->color = BLACK;
b->rchild->color = RED;
}
else // if(u->color == RED)
{
p->color = BLACK;
u->color = BLACK;
g->color = RED;
if(is_red(g->parent) || !(g->parent))
{
solve_red2(g);
}
}
}
template<class KeyType>
void RedBlack<KeyType>::solve_black2(typename BinTree<KeyType>::Node* r)
{
auto p = this->_hot;
if(!p)
{
return;
}
auto s = (r == p->rchild) ? p->lchild : p->rchild;
if(is_black(s))
{
auto t = red_child(s);
if(t)
{
int p_color = p->color;
auto b = this->rebalance(t, s, p);
b->lchild->color = BLACK;
b->rchild->color = BLACK;
b->color = p_color;
}
else
{
if(is_red(p))
{
p->color = BLACK;
s->color = RED;
}
else
{
s->color = RED;
this->_hot = p->parent;
solve_black2(p);
}
}
}
else
{
if(this->islchild(s))
{
this->zig(p);
}
else
{
this->zag(p);
}
p->color = RED;
s->color = BLACK;
solve_black2(r);
}
}
template<class KeyType>
typename BinTree<KeyType>::Node* RedBlack<KeyType>::insert(const KeyType& key)
{
typename BinTree<KeyType>::Node*& x = this->search(key);
if(x)
{
return x;
}
x = this->new_Node(key, 0, this->_hot);
x->color = RED;
this->_size++;
solve_red2(x);
return x;
}
template<class KeyType>
typename BinTree<KeyType>::Node* RedBlack<KeyType>::remove(const KeyType& key)
{
auto r = this->BST<KeyType>::remove(key);
if(!(this->_hot))
{
if(r)
{
r->color = BLACK;
update_height(r);
}
return r;
}
if(this->color_removed == RED)
{
return r;
}
if(is_red(r))
{
r->color = BLACK;
update_height(r);
return r;
}
solve_black2(r);
return r;
}
#endif | true |