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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6dc4b71eef0fb2369ef2aadc7b8a09afd5b9018b | C++ | egundersen/BumboEngine | /AttackPattern_ShootHorizontal.cpp | UTF-8 | 2,155 | 2.84375 | 3 | [] | no_license | #include "AttackPattern_ShootHorizontal.h"
AttackPattern_ShootHorizontal::AttackPattern_ShootHorizontal(int width, int height, Matrix &screen_matrix, PlayerDefinition &player, int number_of_attacks)
: AttackPatternBase(width, height, screen_matrix, player, number_of_attacks)
{
generateRandomSequence(attack_starting_positions_, 0, height_ - 1);
}
// Calls once when the entire attack starts
void AttackPattern_ShootHorizontal::OnBeginAttack()
{
createAttack(rand() % 2, 0, width_, 60, *attack_starting_positions_[created_attacks_], 1);
start_time_new_attack_ = GetTickCount64();
has_completed_initialization_ = true;
}
// Refreshes screen to show player/enemy positions
void AttackPattern_ShootHorizontal::refreshScreen()
{
if (created_attacks_ == attacks_to_create_ && attacks_list_.size() == 0)
has_completed_all_attacks_ = true;
else
{
double current_time_new_attack_ = GetTickCount64() - start_time_new_attack_;
if (current_time_new_attack_ >= 1000 && created_attacks_ < attacks_to_create_) // Create new Attacks
{
createAttack(rand() % 2, 0, width_, 60, *attack_starting_positions_[created_attacks_], 1);
start_time_new_attack_ = GetTickCount64();
}
attacksCheckCollision();
double current_time_move_attack_ = GetTickCount64() - start_time_move_attack_;
if (current_time_move_attack_ >= 50)
{
moveAttack();
start_time_move_attack_ = GetTickCount64();
}
evaluatePlayerInput();
refreshPlayerLocation();
displayScreen();
}
}
// Add attack to list of attacks
void AttackPattern_ShootHorizontal::createAttack(int reverse_direction, int min_position_x, int max_position_x, int trail_length, int height_y, int speed)
{
Attack_HorizontalLineArrow *attack;
if (reverse_direction == 1)
attack = new HorizontalLineArrow_Left(width_, height_, player_position_, attack_matrix_, element_is_occupied_, min_position_x, max_position_x, trail_length, height_y, speed);
else
attack = new HorizontalLineArrow_Right(width_, height_, player_position_, attack_matrix_, element_is_occupied_, min_position_x, max_position_x, trail_length, height_y, speed);
attacks_list_.push_back(attack);
created_attacks_++;
} | true |
6d700d5a1cae8f6ed9e61bab0c506cd8b47a162c | C++ | AndiLi99/catan | /include/tile.h | UTF-8 | 293 | 2.921875 | 3 | [] | no_license | #ifndef TILE
#define TILE
#include "tileType.h"
#include <optional>
class Tile {
TileType type;
std::optional<int> rollNumber;
public:
Tile(TileType type, std::optional<int> rollNumber);
TileType getType() const;
bool isRollNum(int number);
int getRollNumber() const;
};
#endif
| true |
a356c009562613e2b465fcde6579090a1a5fd19e | C++ | zhirko-lena/C- | /Class Works/LZ-CW-28-02-19/LZ-CW-28-02-19/Source.cpp | UTF-8 | 6,765 | 3.4375 | 3 | [] | no_license | #include <iostream>
#include <ctime>
using namespace std;
//template<typename T, typename T2>
//void Fill(T arr[], T2 size) {
// for (int i = 0; i < size; i++) {
// arr[i] = rand() % 10;
// }
//}
//
//template<typename T, typename T2>
//void Print(T arr[], T2 size) {
// for (int i = 0; i < size; i++) {
// cout << "arr [" << i << "]=" << arr[i] << "\t\t";
// cout << " Address = " << arr + i << endl;
// }
//}
//
//int main() {
// srand(unsigned(time(NULL)));
// //==============Block1===================
// int size;
// cout << "Enter arr size : " << endl;
// cin >> size;
//
// int *arr = new int[size];
//
// Fill(arr, size);
// Print(arr, size);
//
// delete[] arr;
//
// //==============Block1===================
//
// system("pause");
// return 0;
//}
template<typename T, typename T2>
void Fill(T arr[], T2 size) {
for (int i = 0; i < size; i++) {
arr[i] = rand() % 77;
}
}
template<typename T, typename T2>
void Print(T arr[], T2 size) {
for (int i = 0; i < size; i++) {
cout << "arr [" << i << "]=" << arr[i] << "\t\t";
cout << " Address = " << arr + i << endl;
}
}
template<typename T3, typename T2>
void NewEl(T3 arr1[], T2 size) {
for (int i = 0; i < size + 1; i++) {
cout << "arr [" << i << "]=" << arr1[i] << "\t\t";
cout << " Address = " << arr1 + i << endl;
}
}
template<typename T, typename T2>
void DeleteElement(T arr[], T2 size) {
if (deletes > size || deletes < 1) {
cout << "Enter correct number" << endl;
return false;
}
else {
for (int i = deletes - 1; i < SIZE - 1; i++) {
Arr[i] = Arr[i + 1];
}
SIZE--;
return Arr;
cout << "Элемент успешно удален!";
}
for (int i = 0; i < size + 1; i++) {
cout << "arr [" << i << "]=" << arr1[i] << "\t\t";
cout << " Address = " << arr1 + i << endl;
}
}
//int* InsertEllement(int* Arr, int &SIZE, int numb, int index) {
//
// int *newArray = new int[++SIZE]; // создаем новый массив
// for (int i = 0; i < index; ++i) // копипастим массив элементы до index
// newArray[i] = Arr[i];
// newArray[index] = numb;
// for (int i = index; i < SIZE - 1; ++i) // копипастим массив после index
// newArray[i + 1] = Arr[i];
// delete[]Arr; // чистим прошлый массив
// Arr = newArray;
// return newArray;
//}
int main() {
/*int Size = 0;
cin >> Size;
int *arr = new int[Size];*/
int NewElement = 0;
srand(unsigned(time(NULL)));
int size;
cout << "Enter arr size : " << endl;
cin >> size;
int *arr = new int[size];
int *arr1 = new int[size + 1];
Fill(arr, size);
Print(arr, size);
cout << "Enter value of new element: " << "\t\t";
cin >> NewElement;
arr = arr1;
arr1[size + 1] = NewElement;
NewEl(arr1, size);
delete[] arr;
delete[] arr1;
system("pause");
return 0;
}
//int* FillArray(int* Arr, int SIZE);
//int* PrintArray(int* Arr, int SIZE);
//int* AddElement(int* Arr, int& SIZE, int NewOne);
//int* DeletElement(int* Arr, int &SIZE, int deletes);
//int* InsertEllement(int* Arr, int SIZE, int numb, int index);
//
//int main() {
// setlocale(LC_CTYPE, "Ukrainian");
// srand(time(0));
//
// int SIZE, *Arr = NULL, NewOne = 0;
// char Menu = '1';
// enum Meny { CreateMass = '1', FillArr = '2', PrintArr = '3', AddOne = '4', DelElement = '5', Insert = '6' };
//
// while (Menu != '0') {
// cout << "\t.........::Выберите операцию::.........\n";
// cout << "\t| ___________________________________ |\n";
// cout << "\t| [1] - Создать Массив |\n";
// cout << "\t| [2] - Заполнить рандомными числами |\n";
// cout << "\t| [3] - Вывести массив |\n";
// cout << "\t| [4] - Дополнить массив |\n";
// cout << "\t| [5] - Удалить элемент |\n";
// cout << "\t| [6] - Вставить элемент |\n";
// cout << "\t| ___________________________________ |\n";
// cout << "\t| [0] - Выход |\n";
// cout << "\t| ___________________________________ |\n";
// cout << endl;
// cout << "Введите номер операции : ";
// cin >> Menu;
// cout << endl;
// switch (Menu) {
// case CreateMass:
// cout << "Введите размер нового массиву : ";
// cin >> SIZE;
// Arr = new int[SIZE];
// cout << "Массив размера " << SIZE << " успешно создан!" << endl;
// cout << endl;
// break;
//
// case FillArr:
// FillArray(Arr, SIZE);
// cout << "Массив успешно заполнен!" << endl;
// cout << endl;
// break;
// case PrintArr:
// PrintArray(Arr, SIZE);
// cout << endl;
// break;
// case AddOne:
// cout << "Введите число для вставки : ";
// cin >> NewOne;
// Arr = AddElement(Arr, SIZE, NewOne);
// cout << endl;
// break;
// case DelElement:
// int deletes;
// cout << "Введите index числа которое хотите удалить : ";
// cin >> deletes;
// Arr = DeletElement(Arr, SIZE, deletes);
// cout << "Элемент успешно удален!";
// cout << endl;
// break;
// case Insert:
// int numb, index;
// cout << "Введите число : ";
// cin >> numb;
// cout << "Введите индекс : ";
// cin >> index;
// Arr = InsertEllement(Arr, SIZE, numb, index);
// cout << endl;
// }
//
// }
//}
//
//int* FillArray(int* Arr, int SIZE) {
// int* tMas = Arr;
//
// for (tMas = Arr; tMas < (Arr + SIZE); tMas++) {
// *tMas = rand() % 10;
// }
//
// return Arr;
//}
//int* PrintArray(int* Arr, int SIZE) {
// int* tMas = Arr;
// for (; tMas < (Arr + SIZE); tMas++) {
// cout << *tMas << " ";
// }
// return Arr;
//}
//int* AddElement(int* Arr, int& SIZE, int NewOne) {
// int* tmp = new int[SIZE + 1];
// for (int i = 0; i <= SIZE; i++) {
// if (i < SIZE) {
// tmp[i] = Arr[i];
// }
// if (i == SIZE) {
// tmp[i] = NewOne;
// }
// }
//
// delete[] Arr;
// Arr = NULL;
// SIZE++;
// return tmp;
//
//}
//
//int* DeletElement(int* Arr, int &SIZE, int deletes) {
// if (deletes > SIZE || deletes < 1) {
// cout << "Ошибка удаления" << endl;
// return false;
// }
// else {
// for (int i = deletes - 1; i < SIZE - 1; i++) {
// Arr[i] = Arr[i + 1];
// }
// SIZE--;
// return Arr;
// cout << "Элемент успешно удален!";
// }
//}
//
//int* InsertEllement(int* Arr, int SIZE, int numb, int index) {
//
// int* tmp1 = new int[SIZE + 1];
//
// for (int i = index; i < SIZE - 1; ++i) {
// Arr[i + 1] = Arr[i];
// if (i == index) {
// Arr[index] = numb;
// }
// }
//
// delete[] Arr;
// Arr = NULL;
// SIZE++;
// return tmp1;
//} | true |
43db88825a0ff6c229e40c78a46ae89ff840a213 | C++ | supertask/icpc | /nj/2015/2_ChainDisappearancePuzzle.cc | UTF-8 | 3,076 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<numeric>
#include<climits>
#include<ctime>
#include<cstring>
#include<sstream>
#define REP(i,p,n) for(int i=p;i<(int)(n);i++)
#define rep(i,n) REP(i,0,n)
#define rep_split(tok,a_str,re) for(char *tok = strtok((char *)a_str.c_str(),re); tok != NULL; tok = strtok(NULL,re))
#define ALL(c) (c).begin(), (c).end()
#define dump(a) cerr << #a << "=" << (a) << endl
#define DUMP(list) cout << "{ "; for(auto nth : list){ cout << nth << " "; } cout << "}" << endl;
template<class T> void chmin(T &t, T f) { if (t > f) t = f; } //t=min
template<class T> void chmax(T &t, T f) { if (t < f) t = f; } //t=max
using namespace std;
int N;
int puzzle[5][11];
int deletePuzzle()
{
int get_p = 0;
/*
cout << "---- remove start ----" << endl;
rep(y,N) {
rep(x,5) {
cout << puzzle[x][y] << " ";
}
cout << endl;
}
cout << endl;
*/
rep(y,N) {
int back_p = 0;
int the_p = 0;
set<int> remove_xs;
//3つ以上一致しているかを見る
rep(x,5)
{
if (puzzle[x][y] == back_p && puzzle[x][y] > 0)
{
/*
cout << "---------------" << endl;
for (set<int>::iterator iti = remove_xs.begin(); iti != remove_xs.end(); iti++) { cout << *iti; }
cout << endl;
*/
remove_xs.insert(x-1); //重複していたら挿入しない
remove_xs.insert(x);
if (remove_xs.size() >= 3) { //3回以上
the_p = puzzle[x][y];
}
}
else {
//玉が異なっていて,既に3つ以上揃っているとき,これ以上は揃わないのでbreak;
if (remove_xs.size() >= 3) {
break;
}
else {
remove_xs.clear();
}
}
back_p = puzzle[x][y];
}
if (remove_xs.size() >= 3)
{
get_p += the_p * remove_xs.size(); //ポイント換算
for (set<int>::iterator it = remove_xs.begin(); it != remove_xs.end(); it++) {
puzzle[(*it)][y] = 0;
}
}
}
/*
cout << "---- remove end ----" << endl;
rep(y,N) {
rep(x,5) {
cout << puzzle[x][y] << " ";
}
cout << endl;
}
cout << endl;
*/
return get_p;
}
void dropPuzzle()
{
rep(x,5) {
vector<int> real_ps;
rep(y,N) {
if (puzzle[x][y] > 0) { real_ps.push_back(puzzle[x][y]); } //点数を吸い取る
puzzle[x][y] = 0; //全部一回削除
}
int the_N = real_ps.size();
rep(y,the_N) { //the_N分たどる
puzzle[x][y+(N-the_N)] = real_ps[y];
}
}
//デバッグ
/*
rep(y,N) {
rep(x,5) {
cout << puzzle[x][y] << " ";
}
cout << endl;
}
*/
}
int main()
{
int all_p;
while(true) {
cin >> N;
all_p = 0;
if (N == 0) { break; }
rep(y,11) {
rep(x,5) {
puzzle[x][y] = 0;
}
}
rep(y,N) {
rep(x,5) {
cin >> puzzle[x][y];
}
}
/*
rep(y,N) {
rep(x,5) {
cout << puzzle[x][y];
}
cout << endl;
}
cout << endl;
*/
//while get_p=0まで
while(true) {
int get_p = deletePuzzle();
if (get_p == 0) { break; }
all_p += get_p;
dropPuzzle();
//cout << endl;
}
cout << all_p << endl;
//cout << endl;
}
return 0;
}
| true |
361fe354f4610c3c9e94de33cfa9f7287f3082e4 | C++ | RamilGauss/MMO-Framework | /Source/Modules/GraphicEngine/ShaderPrefabs.cpp | UTF-8 | 2,530 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information LICENSE.md.
*/
#include "ShaderPrefabs.h"
using namespace nsGraphicEngine;
const std::list<std::string> TShaderPrefabs::GetRenderObjectVertex()
{
std::string text = \
"#version 330 core\n" \
"layout(location = 0) in vec3 aPos;\n" \
"layout(location = 1) in vec2 aTexCoord;\n" \
"\n" \
"out vec2 TexCoord;\n" \
"\n" \
"uniform mat4 model;\n" \
"uniform mat4 view;\n" \
"uniform mat4 projection;\n" \
"\n" \
"void main()\n" \
"{\n" \
" gl_Position = projection * view * model * vec4(aPos, 1.0f);\n" \
" TexCoord = vec2(aTexCoord.x, aTexCoord.y);\n" \
"}";
return { text };
}
//----------------------------------------------------------------------------------------------
const std::list<std::string> TShaderPrefabs::GetRenderObjectFragment()
{
std::string text = \
"#version 330 core\n" \
"out vec4 FragColor;\n" \
"\n" \
"in vec3 ourColor;\n" \
"in vec2 TexCoord;\n" \
"\n" \
"uniform sampler2D texture1;\n" \
"\n" \
"void main()\n" \
"{\n" \
" FragColor = texture(texture1, TexCoord);\n" \
"}";
return { text };
}
//----------------------------------------------------------------------------------------------
const std::list<std::string> TShaderPrefabs::GetRenderTextureOnDisplayVertex()
{
std::string text = \
"#version 330 core\n" \
"layout(location = 0) in vec3 aPos;\n" \
"layout(location = 1) in vec2 aTexCoord;\n" \
"\n" \
"out vec2 TexCoord;\n" \
"\n" \
"uniform vec2 pos;\n" \
"uniform vec2 size;\n" \
"\n" \
"void main()\n" \
"{\n" \
" gl_Position = vec4(pos, 0.0f, 1.0f) + vec4(aPos.x * size.x, aPos.y * size.y, aPos.z, 1.0f);\n" \
" TexCoord = vec2(aTexCoord.x, aTexCoord.y);\n" \
"}";
return { text };
}
//----------------------------------------------------------------------------------------------
const std::list<std::string> TShaderPrefabs::GetRenderTextureOnDisplayFragment()
{
std::string text = \
"#version 330 core\n" \
"out vec4 FragColor;\n" \
"\n" \
"in vec3 ourColor;\n" \
"in vec2 TexCoord;\n" \
"\n" \
"uniform sampler2D texture1;\n" \
"\n" \
"void main()\n" \
"{\n" \
" FragColor = texture(texture1, TexCoord);\n" \
"}";
return { text };
}
//---------------------------------------------------------------------------------------------- | true |
258750011b4b2c696e1a48ba6c26af56e34ac35d | C++ | rahavens/CStwothreefive | /Lab2/main.cpp | UTF-8 | 3,211 | 3.90625 | 4 | [] | no_license | #include <iostream>
#include <vector>
template <typename D> class LinkedList {
struct Node {
D value;
Node * next;
Node(D member, Node* next=nullptr):
value(member),
next(next) {}
~Node() { std::cout << value << " is being destroyed!\n"; }
D getNodeObject() {
return value;
}
void print() {
std::cout << value << std::endl;
printf("Before recursive call\n");
if (next != nullptr) {
next->printNodeObject();
}
printf("After recursive call\n");
std::cout << value << std::endl;
}
};
typedef Node* nodeptr;
private:
nodeptr head = nullptr;
nodeptr end = nullptr;
size_t num_nodes = 0;
static void print(nodeptr node) {
if (node == nullptr)
return;
std::cout << node->value << '\n';
print(node->next);
}
static void destroyLinkedList(nodeptr node) {
if(node == nullptr) {
return;
}
else{
destroyLinkedList(node->next);
delete node;
}
}
//Bryn refactor
//node must not ever be nullptr
static nodeptr find_prior(nodeptr node, const D& value) {
if (node->next == nullptr)
return nullptr;
else if (node->next->value == value)
return node;
else
return find_prior(node->next, value);
}
//Bryn refactor
static nodeptr find(nodeptr node, const D& value) {
nodeptr prior = find_prior(node, value);
if (prior == nullptr)
return nullptr;
else
return prior->next;
}
//Bryn refactor
void add_after(nodeptr node, const D& value) {
nodeptr temp = node->next;
node->next = new Node(value, temp);
num_nodes++;
}
public:
LinkedList(){}
~LinkedList(){
destroyLinkedList(head);
}
void newHead(D member) {
head = new Node(member, head);
if(end == nullptr){
end = head;
}
//Bryn refactor
num_nodes++;
}
void printLinkedList() {
print(head);
}
void newEnd(D member) {
if(head == nullptr)
newHead(member);
//Bryn refactor
else {
add_after(end);
end = end->next;
}
}
};
int main() {
LinkedList<int> item;
int fifteen = 15;
item.newHead(fifteen);
/*
Node<int>* angrybear = new Node<int>(22443);
// Node<std::vector<std::string>> dwarves({"Bombur", "Fili und Kili", "Gimli"});
//
angrybear->next = new Node<int>(243);
angrybear->next->next = new Node<int>(999999);
angrybear->Node::printNodeObject();
destroyLinkedList(angrybear);
// dwarves.Node::printNodeObject();
// */
return 0;
}
| true |
d2d3ce6460f9f107e6bc31f70639cfab862a42df | C++ | queryproc/Graphite | /Graphite/tests/unit/dvfs_multithreaded/dvfs_multithreaded.cc | UTF-8 | 3,874 | 2.8125 | 3 | [] | no_license | #include "carbon_user.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
// Suggested DVFS domain configuration:
// <1.0, CORE, L1_ICACHE, L1_DCACHE> <1.0, L2_CACHE, DIRECTORY, NETWORK_MEMORY, NETWORK_USER>
int num_threads;
int num_iterations;
int iteration_size;
int array_size;
int cache_line_size;
int8_t* array;
double memory_low_frequency;
double memory_high_frequency;
double compute_low_frequency;
double compute_high_frequency;
carbon_barrier_t global_barrier;
void doMemoryWork(int current_iteration)
{
volatile int a;
int num_memory_iterations = 1;
for (int j=0; j<num_memory_iterations; j++){
for (int i=0; i<iteration_size; i++){
a += array[(current_iteration*iteration_size + i)*cache_line_size];
}
}
}
void doComputeWork(int current_iteration)
{
volatile int i;
volatile double j;
int num_compute_iterations = 1;
for (int k=0; k<num_compute_iterations; k++){
for (i=0; i<iteration_size; i++){
int a = array[(current_iteration*iteration_size + i)*cache_line_size];
j = j*a;
}
}
}
void* doWork(void*)
{
SInt32 tile_id = CarbonGetTileId();
double frequency;
int rc;
module_t domain1 = CarbonGetDVFSDomain(CORE);
module_t domain2 = CarbonGetDVFSDomain(L2_CACHE);
for (int i= 0; i<num_iterations; i++){
// Change Frequency for memory phase
CarbonBarrierWait(&global_barrier);
if (tile_id == 0)
{
// set memory dvfs
rc = CarbonSetDVFSAllTiles(domain1, &memory_low_frequency, AUTO);
assert(rc == 0);
rc = CarbonSetDVFSAllTiles(domain2, &memory_high_frequency, AUTO);
assert(rc == 0);
}
CarbonBarrierWait(&global_barrier);
// Do Memory Work
doMemoryWork(i);
// Change Frequency for compute phase
CarbonBarrierWait(&global_barrier);
if (tile_id == 0)
{
// set compute dvfs
rc = CarbonSetDVFSAllTiles(domain1, &compute_high_frequency, AUTO);
assert(rc == 0);
rc = CarbonSetDVFSAllTiles(domain2, &compute_low_frequency, AUTO);
assert(rc == 0);
}
CarbonBarrierWait(&global_barrier);
// Do Compute Work
doComputeWork(i);
}
// Change to Default Frequency
CarbonBarrierWait(&global_barrier);
if (tile_id == 0)
{
double default_frequency = 1.0;
// set compute dvfs
rc = CarbonSetDVFSAllTiles(domain1, &default_frequency, AUTO);
rc = CarbonSetDVFSAllTiles(domain2, &default_frequency, AUTO);
assert(rc == 0);
}
CarbonBarrierWait(&global_barrier);
return NULL;
}
int main(int argc, char *argv[])
{
if (argc != 9)
{
fprintf(stderr,"Error: invalid number of arguments\n");
exit(EXIT_FAILURE);
}
num_threads = atoi(argv[1]);
num_iterations = atoi(argv[2]);
iteration_size = atoi(argv[3]);
cache_line_size = atoi(argv[4]);
memory_low_frequency = atof(argv[5]);
memory_high_frequency = atof(argv[6]);
compute_low_frequency = atof(argv[7]);
compute_high_frequency = atof(argv[8]);
array_size = num_iterations*iteration_size*cache_line_size;
array = (int8_t*) malloc(sizeof(int8_t)*array_size);
pthread_t worker[num_threads];
// Initialize barrier
//pthread_barrier_init(&global_barrier, NULL, num_threads);
CarbonBarrierInit(&global_barrier, num_threads);
CarbonEnableModels();
for (int i=1; i<num_threads; i++)
{
int ret = pthread_create(&worker[i], NULL, doWork, NULL);
if (ret != 0)
{
fprintf(stderr, "*Error* pthread_create FAILED\n");
exit(EXIT_FAILURE);
}
}
doWork(NULL);
for (int i=1; i<num_threads; i++)
{
pthread_join(worker[i], NULL);
}
CarbonDisableModels();
// Destroy barrier
//pthread_barrier_destroy(&global_barrier);
free(array);
return 0;
}
| true |
8050eb7de2e694dec1439af69e7cde8dda01d24f | C++ | Aapoorva/codeDemos | /clg_codevita_training/day1/palindrome.cpp | UTF-8 | 432 | 2.90625 | 3 | [] | no_license | #include "iostream"
using namespace std;
int main(){
int n,temp,rev_n=0,max_digit=0,min_digit=9,digit;
cin>>n;
temp = n;
while(n>0){
digit = n%10;
rev_n = rev_n*10 + digit;
max_digit = max_digit < digit ? digit : max_digit;
min_digit = min_digit > digit ? digit : min_digit;
n=n/10;
}
rev_n == temp ? (cout<<max_digit<<endl) : (cout<<min_digit<<endl);
return 0;
}
// (n%100 != 0 && n%4 == 0) || n%400 == 0 | true |
8a36e10a79fe45b5a2ecec291c1fc668a891e7ac | C++ | MichalMrena/Competitive | /leetcode/valid-parentheses.cpp | UTF-8 | 1,320 | 3.921875 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
/**
* This solution is bit of an overkill but still better than using hash-map
* (Dictionary, HashMap, std::unordered_map) for finding closing bracket.
* For such a small number of elements, just use linear search over vector
* or a hard-coded solution like I did.
*/
bool solve(std::string s)
{
if (s.size() % 2 != 0)
{
return false;
}
std::vector<char> stack;
stack.resize(s.size());
char* sp = stack.data();
for (char const c : s)
{
if (c == '(' || c == '[' || c == '{')
{
*sp++ = c;
continue;
}
int const notEmpty = stack.data() != sp;
if (not notEmpty)
{
return false;
}
switch (c)
{
case ')': if (*(sp - 1) != '(') return false; else sp -= notEmpty; break;
case ']': if (*(sp - 1) != '[') return false; else sp -= notEmpty; break;
case '}': if (*(sp - 1) != '{') return false; else sp -= notEmpty; break;
}
}
return stack.data() == sp;
}
int main()
{
std::cout << solve("()") << "\n";
std::cout << solve("()[]{}") << "\n";
std::cout << solve("(]") << "\n";
std::cout << solve("(") << "\n";
std::cout << solve("]") << "\n";
} | true |
1858f9df654bd3d14c183f2c93c26c7e1d67012b | C++ | olegfafurin/tasks | /leetcode/rain_trap.cpp | UTF-8 | 917 | 3.359375 | 3 | [] | no_license | //
// Created by imd on 10/9/2019.
//
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int trap(vector<int>& height) {
int n = height.size();
if (n == 0) return 0;
int curmax = 0;
int csum = 0;
int rain = 0;
for (int i = 1; i < n; i++) {
if (height[i] > height[curmax]) {
int l = i - curmax - 1;
rain += l * height[curmax] - csum;
csum = 0;
curmax = i;
}
else csum += height[i];
}
curmax = n - 1;
csum = 0;
for (int i = n - 2; i >= 0 ; i--) {
if (height[i] >= height[curmax]) {
int l = curmax - i - 1;
rain += l * height[curmax] - csum;
csum = 0;
curmax = i;
}
else csum += height[i];
}
return rain;
}
int main() {
auto v = vector<int>({2,1,0,2,1,0,1,3,2,3,2,1});
cout << trap(v);
} | true |
8aee0de2894b9c511ec67f2151b9740ee7bc842b | C++ | binhfile/library | /cpp/algorithm/backoff/backoff.h | UTF-8 | 1,442 | 3.28125 | 3 | [
"MIT"
] | permissive | #ifndef __LIB_CPP_ALGORITHM_BACKOFF_H__
#define __LIB_CPP_ALGORITHM_BACKOFF_H__
/**
* @file backoff.h
* @author binhfile
* @brief Giao diện cho các thuật toán backoff
* Backoff: Thuật toán áp dụng cho trường hợp cần truyền lại các bản tin trong truyền thông.
* Các thuật toán backoff khác nhau về thời gian trễ giuax các lần truyền lại
* nhắm tránh xung đột khi có nhiều bản tin cùng truyền vào một thời điểm.
* @ref https://www.awsarchitectureblog.com/2015/03/backoff.html
*/
#include <functional>
namespace library{namespace cpp{namespace algorithm{
class IBackoff {
public:
virtual ~IBackoff(){}
/**
* @brief Thực thi 'action' với 'numberOfTry' lần thực hiện lại.
* Nếu 'action' trả về 0 tương ứng với hành động thành công -> Run trả về gía trị 0.
* Nếu 'action' trả về khác 0 tương ứng với lỗi -> Thực hiện lại 'action' tới khi thành công hoặc sau 'numberOfTry' lần lỗi.
* Trả về gía trị lỗi sau cùng của 'action'
* @param numberOfTry Số lần thực hiện 'action' trong trường hợp lỗi
* @param action Hàm thực hiện
* @return int Mã lỗi
*/
virtual int Run(int numberOfTry, const std::function<int()>& action) = 0;
};
}}}
/**
*
*/
#endif | true |
e509fd94feb46255d645ec89fd2eed209326a003 | C++ | chestnutme/pat-solution | /A1082.cpp | UTF-8 | 1,233 | 2.921875 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
char num[10][5] = {
"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
char wei[3][5] = {
"Shi", "Bai", "Qian"};
char part[2][5] = {"Wan", "Yi"};
int main()
{
char str[17];
gets(str);
int len = strlen(str);
int left = 0, right = len - 1;
if(str[0] == '-')
{
printf("Fu");
left++;
}
while(right >= left + 4)
right -= 4;
while(left < len)
{
bool zero = false;
bool isPrint = false;
while(left <= right)
{
if(left != 0 && str[left] == '0')
zero = true;
else
{
if(zero)
{
printf(" %s", num[0]);
zero = 0;
}
if(left != 0)
printf(" ");
printf("%s", num[str[left] - '0']);
isPrint = true;
if(left != right)
printf(" %s", wei[right - left - 1]);
}
left++;
}
if(isPrint && right != len - 1)
printf(" %s", part[(len - 1 - right) / 4 - 1]);
right += 4;
}
return 0;
}
| true |
5e8d332b14430e43c17eaacfc45e4bb70f8897f3 | C++ | vishal-keshav/UVa | /AdHoc/A4 p483.cpp | UTF-8 | 728 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
string input;
int main(){
//string input;
int back_iter, forward_iter;
while(getline (cin,input)){
//Reverse and print
forward_iter = 0;
for(int i=0;i<input.size();i++){
if(input[i]!=' '){
forward_iter = 0;
while(input[i+forward_iter]!=' ' && i+forward_iter < input.size()){
forward_iter++;
}
for(int j=forward_iter-1;j>=0;j--){
cout << input[i+j];
}
i+= forward_iter-1;
}
else{
cout << input[i];
}
}
cout << endl;
}
return 0;
}
| true |
36ffa338a513a42a0b25ab6ec0b3d467f5e34a26 | C++ | HariniJeyaraman/DSAPrep | /trapping_rain_water.cpp | UTF-8 | 1,765 | 3.796875 | 4 | [] | no_license | /*
42. Trapping Rain Water
Hard
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:
Input: height = [4,2,0,3,2,5]
Output: 9
*/
//Brute Force
class Solution {
public:
int max_val(vector<int> &height, int beg, int end){
int res = 0;
for(int i=beg;i<=end;i++){
if(height[i]>res){
res = height[i];
}
}
return res;
}
int trap(vector<int>& height) {
int result=0, n = height.size();
int left_max = 0, right_max = 0;
for(int i=0;i<height.size();i++){
// left_max = 0; right_max = 0;
left_max = max_val(height, 0, i);
right_max = max_val(height, i, n-1);
result+=min(left_max, right_max) - height[i];
}
return result;
}
};
//Optimized using DP to store max heights instead of recomputing heights for each iteration
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size(), result=0;
if(n==0) return 0;
int left[n], right[n];
left[0] = height[0];
for(int i=1;i<n;i++){
left[i] = max(left[i-1], height[i]);
}
right[n-1] = height[n-1];
for(int i=n-2;i>=0;i--){
right[i] = max(right[i+1], height[i]);
}
for(int i=0;i<n;i++){
result+=min(left[i], right[i])-height[i];
}
return result;
}
}; | true |
d032d0cfc69e7cc22eca5425916c0da346e52246 | C++ | kks227/BOJ | /1100/1106.cpp | UTF-8 | 575 | 2.53125 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int IMPOSSIBLE = 1000000000;
int N, C, cost[20], earn[20], dp[21][1001];
int hotel(int pos, int dest){
int &ret = dp[pos][dest];
if(ret != -1) return ret;
if(pos == N) return ret = (dest ? IMPOSSIBLE : 0);
ret = hotel(pos+1, dest);
if(dest > 0) ret = min(ret, hotel(pos, max(dest - earn[pos], 0)) + cost[pos]);
return ret;
}
int main(){
scanf("%d %d", &C, &N);
for(int i=0; i<N; i++)
scanf("%d %d", cost+i, earn+i);
memset(dp, -1, sizeof(dp));
printf("%d\n", hotel(0, C));
} | true |
5a2d55133ea2b480b8a717146f1d5ce6fe24cb06 | C++ | pyramation/vim3d | /src/Channel.cpp | UTF-8 | 10,243 | 2.59375 | 3 | [] | no_license | #include <math.h>
#include <stdio.h>
#include "Channel.h"
#include "Scene.h"
float Channel::globalMaxY=0.0f;
float Channel::globalMinY=0.0f;
Channel::Channel() {
start = scopeStart = 0;
end = scopeEnd = 240;
enabled = true;
active = false;
sampleRate = 30.0f;
filepath = String();
name = Scene::name(String("Chan"));
points = vector<Point>();
type = CHANNEL_TYPE;
}
Channel::Channel(String filepath) {
this->filepath = filepath;
start = scopeStart = 0;
end = scopeEnd = 240;
enabled = true;
active = false;
sampleRate = 30.0f;
name = Scene::name(String("Chan"));
points = vector<Point>();
type = CHANNEL_TYPE;
FILE * fd = fopen(filepath.c_str(), "r");
if(!fd)return;
char s[1024];
float x,y;
while((fgets(s, 1024, fd)) != NULL) {
sscanf(s, "%f %f", &x,&y);
points.push_back(Point(x,y));
}
fclose(fd);
setBounds();
}
Channel::Channel(const Channel &ch) {
filepath = ch.filepath;
start = ch.start;
scopeStart = ch.scopeStart;
end = ch.end;
scopeEnd = ch.scopeEnd;
enabled = ch.enabled;
active = ch.active;
sampleRate = ch.sampleRate;
name = Scene::name(String("Chan"));
points = ch.points;
type = CHANNEL_TYPE;
maxX = ch.maxX;
minX = ch.minX;
maxY = ch.maxY;
minY = ch.minY;
maxZ = ch.maxZ;
minZ = ch.minZ;
}
Channel Channel::convolve(const Channel * X, const Channel * Y) {
const Channel & ch = *X;
Channel combined(ch);
combined.points.clear();
for(unsigned int k=0; k<(CP(X).size()+CP(Y).size()-1); k++) {
for(unsigned int n=0; n<CP(Y).size(); n++) {
float kTerm, nkTerm;
if (k>0&&k<CP(X).size()) {
kTerm=CP(X)[k].y;
} else kTerm=0.0;
if (n-k>0&&n-k < CP(Y).size()) {
nkTerm=CP(Y)[n-k].y;
} else nkTerm=0.0;
float add = (k>1) ? combined.points[k-1].y : 0.0f;
combined.points.push_back(Point(float(k), add+kTerm*nkTerm));
}
}
return combined;
}
Channel Channel::combine(const Channel * X, const Channel * Y) {
const Channel & ch = *X;
Channel combined(ch);
combined.points.clear();
for(unsigned int i=0; ( i<X->points.size() && i<Y->points.size()); i++) {
combined.points.push_back(Point( X->points[i].y,Y->points[i].y));
}
return combined;
}
Channel Channel::combine(const Channel * X, const Channel * Y, const Channel * Z) {
const Channel & ch = *X;
Channel combined(ch);
combined.points.clear();
for(unsigned int i=0; ( i<X->points.size() && i<Y->points.size() && i<Z->points.size()); i++) {
combined.points.push_back(Point( X->points[i].y,Y->points[i].y, Z->points[i].y));
}
return combined;
}
void Channel::Sin() {
points.clear();
enabled = true;
for(float t=start; t<=start+2*3.14; t += 1.0f/sampleRate) {
Point f(t, sin(t));
points.push_back(f);
}
setBounds();
}
void Channel::Cos() {
points.clear();
enabled = true;
for(float t=start; t<=start+2*3.14; t += 1.0f/sampleRate) {
Point f(t, cos(t));
points.push_back(f);
}
setBounds();
}
void Channel::setBounds() {
if (points.size() <= 0) return;
bool init=false;
for(vector<Point>::iterator cursor=points.begin();
cursor!=points.end(); cursor++) {
Point p = *cursor;
if (init) {
if (p.x < minX) minX = p.x;
if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
if (p.y > maxY) maxY = p.y;
if (p.z < minZ) minZ = p.z;
if (p.z > maxZ) maxZ = p.z;
if (p.y < globalMinY) globalMinY = p.y;
if (p.y > globalMaxY) globalMaxY = p.y;
} else {
maxX = minX = p.x;
maxY = minY = p.y;
maxZ = minZ = p.z;
init = true;
if (p.y < globalMinY) globalMinY = p.y;
if (p.y > globalMaxY) globalMaxY = p.y;
}
}
}
float min(float a, float b) { return (a<b)?a:b; }
float max(float a, float b) { return (a>b)?a:b; }
void Channel::display(int x, int y, int w, int h) {
if (points.size() > 0) {
glBegin(GL_LINES);
for(unsigned int i=0; i<points.size()-1; i++) {
Point p = *(points.begin() + i);
Point p2 = *(points.begin() + i + 1);
float nx = Point::fit(p.x, minX, maxX, float(x), float(x+w));
float ny = Point::fit(p.y, minY,maxY,float(y),float(y+h));
float nx2 = Point::fit(p2.x, minX, maxX, float(x), float(x+w));
float ny2 = Point::fit(p2.y, minY,maxY,float(y),float(y+h));
/* break out scope */
if (nx > maxX) break;
glVertex2f(nx, ny);
glVertex2f(nx2, ny2);
}
glEnd();
}
}
/*
void Channel::display(int x, int y, int w, int h, int begin, float amount) {
if (points.size() > 0) {
glBegin(GL_LINES);
bool useGlobal = false;
for(unsigned int i=begin; i<points.size()-1; i++) {
float nx = Point::fit(points[i].x, minX,max(0,min(maxX,amount*maxX)),float(x),float(x+w));
float ny = Point::fit(points[i].y, minY,maxY,float(y),float(y+h));
float nx2 = Point::fit(points[i+1].x, minX,max(0,min(maxX,amount*maxX)),float(x),float(x+w));
float ny2 = Point::fit(points[i+1].y, minY,maxY,float(y),float(y+h));
if (nx > amount*maxX) break;
glVertex2f(nx, ny);
glVertex2f(nx2, ny2);
}
glEnd();
}
}
*/
void Channel::display(int x, int y, int w, int h, int begin, float amountx, float amounty) {
if (points.size() > 0) {
glBegin(GL_LINES);
for(unsigned int i=begin; i<points.size()-1; i++) {
//float nx = Point::fit(points[i].x, minX,max(0,min(maxX,amount*maxX)),float(x),float(x+w));
float nx = Point::fit(points[i].x, minX,w*amountx,float(x),float(x+w));
float ny = Point::fit(points[i].y, minY,maxY/amounty,float(y),float(y+h));
//float nx2 = Point::fit(points[i+1].x, minX,max(0,min(maxX,amount*maxX)),float(x),float(x+w));
float nx2 = Point::fit(points[i+1].x, minX,w*amountx,float(x),float(x+w));
float ny2 = Point::fit(points[i+1].y, minY,maxY/amounty,float(y),float(y+h));
/* break out scope */
// if (nx > amount*maxX) break;
glVertex2f(nx, ny);
glVertex2f(nx2, ny2);
}
glEnd();
}
}
void Channel::WriteCHAN(String filename) {
FILE * fd = fopen(filename.c_str(), "w");
if (!fd) return;
for(unsigned int i=0;i<points.size();i++) {
fprintf(fd, "%f %f\n", points[i].x, points[i].y);
}
fclose(fd);
}
Channel * Channel::differentiate() {
Channel * chan = new Channel();
float small = 0.000000001;
for(unsigned int i=0;i<points.size()-1;i++) {
if (points[i+1].x - points[i].x != 0) chan->points.push_back(Point(points[i].x, (points[i+1].y - points[i].y)/(points[i+1].x - points[i].x)));
else chan->points.push_back(Point(points[i].x, (points[i+1].y - points[i].y)/small));
// steal last point
if (i == points.size()-2) {
if (points[i+1].x - points[i].x != 0) chan->points.push_back(Point(points[i+1].x, (points[i+1].y - points[i].y)/(points[i+1].x - points[i].x)));
else chan->points.push_back(Point(points[i+1].x, (points[i+1].y - points[i].y)/small));
}
}
chan->setBounds();
return chan;
}
Channel Channel::project(Channel * channel) {
Channel ch(*this);
ch.name = Scene::name("op");
for(unsigned int i=0; (i<ch.points.size() && i<channel->points.size());i++) {
ch.points[i] = points[i].project(channel->points[i]);
}
ch.setBounds();
return ch;
}
Channel Channel::operator - (const Channel & C) const {
Channel ch(C);
ch.name = Scene::name("op");
for(unsigned int i=0; (i<ch.points.size() && i<points.size());i++) {
ch.points[i].y -= points[i].y;
}
ch.setBounds();
return ch;
}
Channel Channel::operator + (const Channel & C) const {
Channel ch(C);
ch.name = Scene::name("op");
for(unsigned int i=0; (i<ch.points.size() && i<points.size());i++) {
ch.points[i].y += points[i].y;
}
ch.setBounds();
return ch;
}
Channel Channel::operator / (const Channel & C) const {
Channel ch(C);
ch.name = Scene::name("op");
for(unsigned int i=0; (i<ch.points.size() && i<points.size());i++) {
ch.points[i].y /= points[i].y;
}
ch.setBounds();
return ch;
}
Channel Channel::operator * (const Channel & C) const {
Channel ch(C);
ch.name = Scene::name("op");
for(unsigned int i=0; (i<ch.points.size() && i<points.size());i++) {
ch.points[i].y *= points[i].y;
}
ch.setBounds();
return ch;
}
Channel Channel::operator * (const float &f) const {
Channel ch(*this);
ch.name = this->name;
for(unsigned int i=0; i<ch.points.size();i++) {
ch.points[i].y *= f;
}
ch.setBounds();
return ch;
}
Channel Channel::operator / (const float &f) const {
if (f == 0) return Channel(*this);
Channel ch(*this);
ch.name = this->name;
for(unsigned int i=0; i<ch.points.size();i++) {
ch.points[i].y /= f;
}
ch.setBounds();
return ch;
}
Channel Channel::operator + (const float &f) const {
Channel ch(*this);
ch.name = this->name;
for(unsigned int i=0; i<ch.points.size();i++) {
ch.points[i].y += f;
}
ch.setBounds();
return ch;
}
Channel Channel::operator - (const float &f) const {
Channel ch(*this);
ch.name = this->name;
for(unsigned int i=0; i<ch.points.size();i++) {
ch.points[i].y -= f;
}
ch.setBounds();
return ch;
}
String Channel::propertyInfo() {
char s[1024];
sprintf(s, "name: %s\nstart: %d end: %d\nscopeStart: %d scopeEnd: %d\nsampleRate: %f\nmin(%f,%f,%f) max(%f,%f,%f)\n",
name.c_str(), start, end, scopeStart, scopeEnd, sampleRate,
minX,minY,minZ, maxX,maxY,maxZ);
String n(s);
return n;
}
Channel::~Channel() { printf("deleting channel %s\n", name.c_str());}
| true |
01973168da8756b9bc654d671657782a15269f0c | C++ | jmalbert7/twisted-path | /Player.hpp | UTF-8 | 1,901 | 3.28125 | 3 | [] | no_license | /***************************************************************************************************
* Name: Jessica Albert
* Project: Final Project - Player.hpp
* Date: 3/10/19
* Description: The Player class is used to implement the 'Game of Life' text game. In this game
* the player has 20 steps to get a job as a programmer. They must do this by shedding doubts, and
* gaining confidence, technical know-how, and courage points. Once the required points are obtained
* the Player gets the job. The player has 8 data members described below. It also has functions to
* move to update it's location on the Space board, add a new item to its collection, and display
* its stats, and update its stats.
* ************************************************************************************************/
#ifndef PLAYER_HPP
#define PLAYER_HPP
#include <string>
#include <vector>
#include "Items.hpp"
class Player
{
private:
//player stats
int confidence;
int doubt;
int technical;
int courage;
int study;
int steps;
bool jobFound;
bool project;
bool degree;
bool contact;
bool reference;
//player's items
std::vector<Items*> items;
public:
Player();
~Player();
void intro();
int getConfidence();
void addConfidence();
void removeConfidence();
int getTechnical();
void addTechnical();
void removeTechnical();
int getCourage();
void addCourage();
void removeCourage();
int getDoubt();
void addDoubt();
void removeDoubt();
int getStudy();
void addStudy();
int getSteps();
void addSteps();
bool getJobFound();
void setJobFound(std::string);
bool getDegree();
void setDegree(std::string);
bool getProject();
void setProject(std::string);
bool getProfessionalContact();
void setProfessionalContact(std::string);
bool getReference();
void setReference(std::string);
void displayStats();
void displayItems();
void addItem(Items *);
};
#endif
| true |
4bd64eb37d1747a455c73aaf72073f6dd85dfa69 | C++ | aspectspro/EnterpriseDomainObjects | /src/Party/salarydomainobject.cpp | UTF-8 | 7,079 | 2.53125 | 3 | [] | no_license | #include "salarydomainobject.h"
#include "person.h"
SalaryDomainMapper SalaryYearToDate::mapper;
SalaryDomainObject::SalaryDomainObject()
{
}
const QMetaObject &SalaryDomainObject::metaObject() const
{
return this->staticMetaObject;
}
void SalaryDomainObject::registerConverter()
{
}
SalaryDomainObject::SalaryDomainObject(QJSValue json)
{
this->fromJson(json.toVariant().toJsonObject());
}
QString SalaryDomainObject::getId() const
{
return id;
}
void SalaryDomainObject::setId(const QString &value)
{
id = value;
}
QString SalaryDomainObject::getEmployee_id() const
{
return employee_id;
}
void SalaryDomainObject::setEmployee_id(const QString &value)
{
employee_id = value;
}
Money SalaryDomainObject::getGross_pay() const
{
return gross_pay;
}
void SalaryDomainObject::setGross_pay(const Money &value)
{
gross_pay = value;
}
Money SalaryDomainObject::getNet_pay() const
{
return net_pay;
}
void SalaryDomainObject::setNet_pay(const Money &value)
{
net_pay = value;
}
Money SalaryDomainObject::getEmployee_nis() const
{
return employee_nis;
}
void SalaryDomainObject::setEmployee_nis(const Money &value)
{
employee_nis = value;
}
Money SalaryDomainObject::getEmployer_nis() const
{
return employer_nis;
}
void SalaryDomainObject::setEmployer_nis(const Money &value)
{
employer_nis = value;
}
Money SalaryDomainObject::getPaye() const
{
return paye;
}
void SalaryDomainObject::setPaye(const Money &value)
{
paye = value;
}
Money SalaryDomainObject::getHealth_surcharge() const
{
return health_surcharge;
}
void SalaryDomainObject::setHealth_surcharge(const Money &value)
{
health_surcharge = value;
}
DateTime SalaryDomainObject::getDate_from() const
{
return date_from;
}
void SalaryDomainObject::setDate_from(const DateTime &value)
{
date_from = value;
}
DateTime SalaryDomainObject::getDate_to() const
{
return date_to;
}
void SalaryDomainObject::setDate_to(const DateTime &value)
{
date_to = value;
}
DateTime SalaryDomainObject::getDate_paid() const
{
return date_paid;
}
void SalaryDomainObject::setDate_paid(const DateTime &value)
{
date_paid = value;
}
SalaryDomainObject SalaryDomainObject::fromJs(QJsonValue json)
{
SalaryDomainObject obj;
obj.fromJson(json.toObject());
return obj;
}
QString SalaryDomainMapper::tableName() const
{
return "party_pay";
}
void SalaryDomainMapper::injectInsert(AbstractDomainObject &domainObject) const
{
auto obj = dynamic_cast<SalaryDomainObject*>(&domainObject);
auto where = QString("employee_id='%1' AND date_to >= %2")
.arg(obj->getEmployee_id())
.arg(obj->getDate_from().getTimestamp());
QList<SalaryDomainObject> result;
try {
result = this->loadAll(where);
} catch (std::exception &e) {
Q_UNUSED(e);
}
if(result.count() >= 1){
throw std::exception(
QString("Employee has been paid for date. Please set From Date later than '%1'")
.arg(obj->getDate_to().toIsoDate()).toUtf8());
}
}
SalaryYearToDate::SalaryYearToDate()
{
QDate dt = QDate::currentDate();
setCurrentYear(dt.year());
connect(this,&SalaryYearToDate::salary_idChanged,[=](QString salary_id){
Q_UNUSED(salary_id);
loadYearToDate();
});
connect(this,&SalaryYearToDate::salaryChanged,[=](){
loadYearToDate();
});
}
qint64 SalaryYearToDate::getCurrentYear() const
{
return currentYear;
}
void SalaryYearToDate::setCurrentYear(qint64 value)
{
currentYear = value;
}
Money SalaryYearToDate::getYearGross() const
{
return yearGross;
}
void SalaryYearToDate::setYearGross(const Money value)
{
yearGross = value;
emit yearGrossChanged(value);
}
Money SalaryYearToDate::getYearNet() const
{
return yearNet;
}
void SalaryYearToDate::setYearNet(const Money value)
{
yearNet = value;
emit yearNetChanged(value);
}
Money SalaryYearToDate::getYearNis() const
{
return yearNis;
}
void SalaryYearToDate::setYearNis(const Money value)
{
yearNis = value;
emit yearNisChanged(value);
}
Money SalaryYearToDate::getYearHealthSurcharge() const
{
return yearHealthSurcharge;
}
void SalaryYearToDate::setYearHealthSurcharge(const Money value)
{
yearHealthSurcharge = value;
emit yearHealthSurchargeChanged(value);
}
Money SalaryYearToDate::getYearPaye() const
{
return yearPaye;
}
void SalaryYearToDate::setYearPaye(const Money value)
{
yearPaye = value;
emit yearPayeChanged(value);
}
void SalaryYearToDate::loadYearToDate()
{
QString lastPaid,employeeId;
try {
auto loadedSalary = mapper.find(getSalary_id());
lastPaid = loadedSalary.getDate_paid().toIsoDate();
employeeId = loadedSalary.getEmployee_id();
} catch (std::exception &e) {
Q_UNUSED(e);
lastPaid = getSalary().getDate_paid().toIsoDate();
employeeId = getSalary().getEmployee_id();
}
auto currentYear = QDate::fromString(lastPaid,"yyyy-MM-dd").year();
qDebug() << "Last Paid Current Year" << currentYear;
QString yearlyDateFormat = "yyyy-MM-dd,hh:mm:ss a";
QDateTime startDate;
startDate = startDate.fromString(QString("%1-%2-%3,12:00:00 am")
.arg(currentYear)
.arg("01")
.arg("01"),yearlyDateFormat);
QDateTime endDate;
endDate = endDate.fromString(QString("%1,11:59:59 pm")
.arg(lastPaid),yearlyDateFormat);
auto startTimestamp = startDate.toSecsSinceEpoch();
auto endTimestamp = endDate.toSecsSinceEpoch();
try {
auto all = mapper.loadAll(QString("employee_id='%1' AND date_paid >= %2 AND date_paid <= %3")
.arg(employeeId)
.arg(startTimestamp)
.arg(endTimestamp));
qint64 _gross = 0, _net = 0, _nis = 0,
_paye = 0 , _hsc = 0;
foreach (auto _salary, all) {
_gross += _salary.getGross_pay().asInt();
_net += _salary.getNet_pay().asInt();
_nis += _salary.getEmployee_nis().asInt();
_paye += _salary.getPaye().asInt();
_hsc += _salary.getHealth_surcharge().asInt();
}
setYearGross(_gross);
setYearNet(_net);
setYearNis(_nis);
setYearPaye(_paye);
setYearHealthSurcharge(_hsc);
} catch (std::exception &e) {
Q_UNUSED(e);
qInfo() << QString("No Salary for '%1' as yet.").arg(currentYear);
}
}
SalaryDomainObject SalaryYearToDate::getSalary() const
{
return salary;
}
void SalaryYearToDate::setSalary(const SalaryDomainObject value)
{
salary = value;
emit salaryChanged(value);
}
QString SalaryYearToDate::getSalary_id() const
{
return salary_id;
}
void SalaryYearToDate::setSalary_id(const QString &value)
{
salary_id = value;
emit salary_idChanged(value);
}
| true |
4d77059974015f414944bd3322f9e5e29536c812 | C++ | Zindokar/Arduino-Keyboard | /keyboard/keyboard.ino | UTF-8 | 1,661 | 2.625 | 3 | [] | no_license | #include <SoftwareSerial.h>
SoftwareSerial ftdi(4, 5);
boolean keys[4][4] = {{LOW, LOW, LOW, LOW},{LOW, LOW, LOW, LOW}};
void setup() {
pinMode(6, INPUT);
pinMode(7, INPUT);
pinMode(8, INPUT);
pinMode(9, INPUT);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
ftdi.begin(9600);
}
void loop() {
if (digitalRead(6) == HIGH && keys[0][0] == LOW) {
ftdi.print("c1\n\r");
keys[0][0] = HIGH;
}
if (digitalRead(6) == LOW) {
keys[0][0] = LOW;
}
if (digitalRead(7) == HIGH && keys[0][1] == LOW) {
ftdi.print("b1\n\r");
keys[0][1] = HIGH;
}
if (digitalRead(7) == LOW) {
keys[0][1] = LOW;
}
if (digitalRead(8) == HIGH && keys[0][2] == LOW) {
ftdi.print("c2\n\r");
keys[0][2] = HIGH;
}
if (digitalRead(8) == LOW) {
keys[0][2] = LOW;
}
if (digitalRead(9) == HIGH && keys[0][3] == LOW) {
ftdi.print("b2\n\r");
keys[0][3] = HIGH;
}
if (digitalRead(9) == LOW) {
keys[0][3] = LOW;
}
if (digitalRead(10) == HIGH && keys[1][0] == LOW) {
ftdi.print("c3\n\r");
keys[1][0] = HIGH;
}
if (digitalRead(10) == LOW) {
keys[1][0] = LOW;
}
if (digitalRead(11) == HIGH && keys[1][1] == LOW) {
ftdi.print("b3\n\r");
keys[1][1] = HIGH;
}
if (digitalRead(11) == LOW) {
keys[1][1] = LOW;
}
if (digitalRead(12) == HIGH && keys[1][2] == LOW) {
ftdi.print("c4\n\r");
keys[1][2] = HIGH;
}
if (digitalRead(12) == LOW) {
keys[1][2] = LOW;
}
if (digitalRead(13) == HIGH && keys[1][3] == LOW) {
ftdi.print("b4\n\r");
keys[1][3] = HIGH;
}
if (digitalRead(13) == LOW) {
keys[1][3] = LOW;
}
}
| true |
72300b29baa084f01cf59f5e8b1263893a7460e8 | C++ | rajatkhanna1999/CompetitiveCoding | /Codechef/CHEFCHR.cpp | UTF-8 | 950 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <string.h>
#include <cstring>
using namespace std;
int main()
{
long t;
cin>>t;
while(t>0){
string S;
cin>>S;
long sum=0;
long len=S.length();
for(long i=0;i<=len-4;i++)
{
string A=S.substr(i,4);
string B[24]={"chef","chfe","cehf","cefh","cfhe","cfeh","hcef","hcfe","hfce","hfec","hefc","hecf","efhc","efch","echf","ecfh","ehcf","ehfc","fech","fehc","fche","fceh","fhce","fhec"};
// if(strcmp(A,("chef"||"chfe"||"cehf"||"cefh"||"cfhe"||"cfeh"||"hcef"||"hcfe"||"hfce"||"hfec"||"hefc"||"hecf"||"efhc"||"efch"||"echf"||"ecfh"||"ehcf"||"ehfc"||"fech"||"fehc"||"fche"||"fceh"||"fhce"||"fhec")))
// sum=sum+1;
for(int k=0;k<24;k++){
if(A.compare(B[k])==0){
sum=sum+1;
}
}
}
if(sum==0)
cout<<"normal"<<endl;
else
cout<<"lovely"<<" "<<sum<<endl;
t--;
}
return 0;
}
| true |
9b97f24d607523d05749a0e3bc7f85664ffbd298 | C++ | iamweiweishi/LeetCode-Problems | /80.cpp | UTF-8 | 421 | 2.703125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<3) return nums.size();
int f=0,r=1;
while(r<nums.size()){
if(nums[f]==nums[r]){
if(r-f>1) nums.erase(nums.begin()+r,nums.begin()+r+1);
else r++;
}else{
f=r;
r++;
}
}
return nums.size();
}
};
| true |
6bad10feaaa9e7fd852abe7b69df8ab7ce1c5420 | C++ | SijmenHuizenga/BitBot | /src/LedControl.cpp | UTF-8 | 898 | 2.921875 | 3 | [
"MIT"
] | permissive | /*
* LedControl.cpp
*
* Created on: 19 dec. 2014
* Author: Sijmen
*/
#include "Arduino.h"
#include "../controllers/Led.h"
LedController::LedController(){
pins[0] = 2;
pins[1] = 3;
pins[2] = 4;
pins[3] = 5;
pins[4] = 6;
pins[5] = 7;
pins[6] = 8;
pins[7] = 9;
for(int i = 0; i < getLedAmount(); i++){
pinMode(pins[i], OUTPUT);
}
}
void LedController::setLedOn(byte ledNr, boolean onOrOff){
digitalWrite(pins[ledNr], onOrOff ? HIGH : LOW);
};
int LedController::getLedAmount(){
return 8;
};
String LedController::getCurState(){
String out = "";
for(int i = 0; i < getLedAmount(); i++){
if(pins[i] <= 7)
out+= String(bitRead(PIND, pins[i]));
else{
out+= String(bitRead(PINB, pins[i]-8));
}
}
return out;
}
void LedController::resetLights(){
for(int i = 0; i < getLedAmount(); i++){
setLedOn(i, false);
}
}
| true |
5b898fb4855d4df1a86f5a5dd6ff818fab2ae978 | C++ | jsoysouvanh/RefurekuIntegration | /ThirdParty/Include/Refureku/TypeInfo/Entity/EEntityKind.h | UTF-8 | 1,948 | 2.609375 | 3 | [] | no_license | /**
* Copyright (c) 2020 Julien SOYSOUVANH - All Rights Reserved
*
* This file is part of the Refureku library project which is released under the MIT License.
* See the LICENSE.md file for full license details.
*/
#pragma once
#include "Refureku/Config.h"
#include "Refureku/Misc/FundamentalTypes.h"
#include "Refureku/Misc/EnumMacros.h"
namespace rfk
{
/**
* Describe the kind of an entity
*/
enum class EEntityKind : uint16
{
/** This entity is... what? Should never happen... */
Undefined = 0u,
/** The entity is a namespace, it can safely be cast to rfk::Namespace type. */
Namespace = 1 << 0,
/** The entity is a class, it can safely be cast to rfk::Class. */
Class = 1 << 1,
/** The archetype is a struct, it can safely be cast to rfk::Struct. */
Struct = 1 << 2,
/** The archetype is an enum, it can safely by cast to rfk::Enum. */
Enum = 1 << 3,
/** The archetype is a fundamental archetype. it can safely by cast to rfk::FundamentalArchetype. */
FundamentalArchetype = 1 << 4,
/** This entity is a (non-member) variable, it can safely be cast to rfk::Variable. */
Variable = 1 << 5,
/**
* The entity is a field, it can safely be cast to rfk::FieldBase type.
* More specific info can be retrieved from the entity by checking rfk::FieldBase::getFlags().
*/
Field = 1 << 6,
/** This entity is a (non-member) function, is can safely be cast to rfk::Function. */
Function = 1 << 7,
/**
* The entity is a method, it can safely be cast to rfk::MethodBase type.
* More specific info can be retrieved from the entity by checking rfk::MethodBase::getFlags().
*/
Method = 1 << 8,
/** The entity is an enum value, it can safely be cast to rfk::EnumValue. */
EnumValue = 1 << 9,
/** The entity is a namespace fragment, is can safely be cast to rfk::NamespaceFragment. */
NamespaceFragment = 1 << 10
};
RFK_GENERATE_ENUM_OPERATORS(EEntityKind)
} | true |
3c272bee655fc1995c0c7adf57167254c0241424 | C++ | Warbi2601/OOP-Assignment-Snake-and-Mouse | /Bomb.cpp | UTF-8 | 402 | 2.90625 | 3 | [] | no_license | #include "Bomb.h"
Bomb::Bomb() : MoveableGridItem('B', 0, 0)
{
}
void Bomb::reset() {
time_ = 4;
active_ = false;
}
int Bomb::get_time() {
return time_;
}
int Bomb::tick()
{
return time_--;
}
bool Bomb::has_exploded() {
return time_ <= 0;
}
bool Bomb::is_active() {
return active_;
}
void Bomb::set_active(bool value) {
active_ = value;
}
void Bomb::set_time(int time) {
time_ = time;
} | true |
27d3412facf270e7c04cb6977f6e5d91b0c9db1d | C++ | wuyadie/envpool | /envpool/core/circular_buffer.h | UTF-8 | 1,819 | 2.640625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2021 Garena Online Private Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ENVPOOL_CORE_CIRCULAR_BUFFER_H_
#define ENVPOOL_CORE_CIRCULAR_BUFFER_H_
#ifndef MOODYCAMEL_DELETE_FUNCTION
#define MOODYCAMEL_DELETE_FUNCTION = delete
#endif
#include <atomic>
#include <cassert>
#include <condition_variable>
#include <cstdint>
#include <functional>
#include <utility>
#include <vector>
#include "lightweightsemaphore.h"
template <typename V>
class CircularBuffer {
protected:
std::size_t size_;
moodycamel::LightweightSemaphore sem_get_;
moodycamel::LightweightSemaphore sem_put_;
std::vector<V> buffer_;
std::atomic<uint64_t> head_;
std::atomic<uint64_t> tail_;
public:
explicit CircularBuffer(std::size_t size)
: size_(size), sem_put_(size), buffer_(size), head_(0), tail_(0) {}
template <typename T>
void Put(T&& v) {
while (!sem_put_.wait()) {
}
uint64_t tail = tail_.fetch_add(1);
auto offset = tail % size_;
buffer_[offset] = std::forward<T>(v);
sem_get_.signal();
}
V Get() {
while (!sem_get_.wait()) {
}
uint64_t head = head_.fetch_add(1);
auto offset = head % size_;
V v = std::move(buffer_[offset]);
sem_put_.signal();
return v;
}
};
#endif // ENVPOOL_CORE_CIRCULAR_BUFFER_H_
| true |
1e950d916d2f232238706a6bfc833f79871c7438 | C++ | SaiPrathek/MyCCode | /pattern.cpp | UTF-8 | 506 | 2.546875 | 3 | [] | no_license | #include<stdio.h>
main(){
int i, j, k, n;
scanf("%d", &n);
printf("\n");
n++;
for(i=1, k=n;i<=n;i++, k--){
for(j=0;j<i;j++)
printf("* ");
for(j=2*k-2;j>1;j--)
printf(" ");
for(j=0;j<i;j++){
if(j==n-1)
continue;
printf("* ");
}
// printf("-");
printf("\n");
}
for(i=n, k=1;i>1;i--, k++){
for(j=0;j<i-1;j++)
printf("* ");
for(j=1;j<k*2;j++)
printf(" ");
for(j=i-1;j>0;j--)
printf("* ");
// printf("_");
printf("\n");
}
}
| true |
d8db827546e9092f5f19adc8fec29ed303dd728d | C++ | hrachyahakobyan/Pandemic | /core/include/core/CharterFlight.h | UTF-8 | 370 | 2.609375 | 3 | [] | no_license | #pragma once
#include "ActionBase.h"
namespace pan{
/**
* @brief Class representing a charter flight action
* @author Hrachya Hakobyan
*/
class CharterFlight : public ActionImpl<CharterFlight, ActionBase>{
public:
CharterFlight();
CharterFlight(PlayerIndex player, CityIndex city);
PlayerIndex player;
CityIndex targetCity;
std::string description() const;
};
} | true |
fc006e8afab6a68948e6ae62a0801849ffd297d6 | C++ | vivanov-dp/taskslib | /src/include/taskslib/Types.h | UTF-8 | 1,433 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include <memory>
#include <functional>
#include <chrono>
#include <map>
namespace TasksLib {
// === Classes =====
class TaskOptions;
class Task;
class TasksThread;
class TasksQueue;
class TasksQueuesContainer;
// === Task =====
enum TaskStatus {
TASK_FINISHED = 0,
TASK_INIT = 1, // Freshly created, not added to queue
TASK_SUSPENDED, // Put on hold, will reschedule after a specified delay
TASK_IN_QUEUE, // Waiting in a queue
TASK_IN_QUEUE_MAIN_THREAD, // Waiting in a queue in main thread
TASK_WORKING, // Executing
};
using TaskPtr = std::shared_ptr<Task>;
using TaskUniquePtr = std::unique_ptr<Task>;
using TaskWeakPtr = std::weak_ptr<Task>;
template <class T> class ResourcePool;
// Types accepted as options for tasks (in Task::Task() and Task::Reschedule()) :
enum TaskThreadTarget {
MAIN_THREAD,
WORKER_THREAD
};
using TaskBlocking = bool;
using TaskPriority = uint32_t;
using TaskExecutable = std::function<void(TasksQueue* queue, const TaskPtr& task)>;
using TaskDelay = std::chrono::milliseconds;
// </Types as options>
// === TasksQueue =====
using scheduleClock = std::chrono::steady_clock;
using scheduleTimePoint = std::chrono::time_point<scheduleClock>;
using scheduleDuration = scheduleClock::duration;
using scheduleMap = std::multimap<scheduleTimePoint, TaskPtr>;
using schedulePair = std::pair<scheduleTimePoint, TaskPtr>;
}
| true |
a5770e384e3c6fdb8441b6d92e3ca8da164e7031 | C++ | BGCX261/zolgatron-svn-to-git | /trunk/simulator/SDLittleDog.h | UTF-8 | 2,813 | 2.5625 | 3 | [] | no_license | #ifndef __SD_LITTLE_DOG_H__
#define __SD_LITTLE_DOG_H__
#include <littledog.h>
#include "SDSimulator.h"
#include "SDConstants.h"
#include <vector>
// Forward declaration of slow walk controller.
class SDSlowWalk;
// structure to encapsulate all state information
struct SDDogState {
bduVec3f pos;
bduVec3f ori;
bduVec3f angRates;
bduVec3f footPos[NUM_LEGS];
bduVec3f jointAngles[NUM_LEGS];
double timestamp;
void display();
};
enum SDLegMode {
SD_LEG_MODE_PD = 0,
SD_LEG_MODE_COMPLIANT,
};
// Struct for holding dog steps
struct SDDogStep {
int foot;
double x, y;
SDDogStep(int foot, double x, double y) : foot(foot), x(x), y(y) {}
void print() {
printf("Step %d: %0.3f, %0.3f\n", foot, x, y);
}
};
class SDController;
/*
The SDLittleDog class encapsulates all the logic for setting up and
running the Little Dog, either in simulation or on the real robot.
*/
class SDLittleDog
{
public:
SDLittleDog();
~SDLittleDog();
void getDogState(SDDogState *dogState);
void updateDogState();
LD_ERROR_CODE runTrial(SDSimulatorState *state);
LD_ERROR_CODE stopRobot(void);
LD_ERROR_CODE runPath(SDSimulatorState *state, vector<SDDogStep> *steps,
SDSlowWalk *walkController);
bool simStart();
void simStep();
void simStop();
void simDraw();
bool simPathStart();
bool simPathCycle();
void initializeSimulator();
bool legHit(int leg);
// accessors and observers
bool getSimulated()
{ return mSimulated; }
void setSimulated(bool simulated)
{ mSimulated = simulated; }
bool getSimUI()
{ return mSimUI; }
void setSimUI(bool simUI)
{ mSimUI = simUI; }
SDController* getController()
{ return mController; }
void setController(SDController *controller)
{ mController = controller; }
SDSimulator* getSimulator()
{ return &mSimulator; }
void setLegMode(int leg, SDLegMode mode)
{ mLegModes[leg] = mode; }
SDLegMode getLegMode(int leg)
{ return mLegModes[leg]; }
protected:
bool initControl(void);
void updateControl(void);
void uninitControl(void);
private:
SDDogState mDogState;
SDSimulator mSimulator;
SDController *mController;
bduVec4f mFootForces, mOldFootForces;
SDLegMode mLegModes[NUM_LEGS];
double mPDGains[NUM_LEGS*NUM_JOINTS][2];
bduVec3f mIMUBias;
SDSimulatorState *mInitialState;
vector<SDDogStep> *mPathSteps;
SDSlowWalk *mWalkController;
bool mSimulated;
bool mSimUI;
bool mInitControl;
};
void dsSimStart();
void dsSimStop();
void dsSimCommand(int cmd);
void dsSimLoop(int pause);
void dsSimPathStart();
void dsSimPathLoop(int pause);
bool parsePath(string file, vector<SDDogStep> *steps);
#endif
| true |
55504a5568e812b411387f6d7f0d8f819cf43647 | C++ | ZongoForSpeed/ProjectEuler | /problemes/probleme1xx/probleme149.cpp | UTF-8 | 3,934 | 3.5625 | 4 | [
"MIT"
] | permissive | #include "problemes.h"
#include "arithmetique.h"
#include <fstream>
typedef long long nombre;
typedef std::vector<nombre> vecteur;
typedef std::vector<vecteur> matrice;
namespace {
nombre maximum(const vecteur &v) {
nombre max_tmp = 0;
nombre max_total = 0;
for (nombre n: v) {
max_tmp = std::max(max_tmp + n, 0LL);
max_total = std::max(max_total, max_tmp);
}
return max_total;
}
}
ENREGISTRER_PROBLEME(149, "Searching for a maximum-sum subsequence") {
// Looking at the table below, it is easy to verify that the maximum possible sum of adjacent numbers in any
// direction (horizontal, vertical, diagonal or anti-diagonal) is 16 (= 8 + 7 + 1).
//
// −2 5 3 2
// 9 −6 5 1
// 3 2 7 3
// −1 8 −4 8
//
// Now, let us repeat the search, but on a much larger scale:
//
// First, generate four million pseudo-random numbers using a specific form of what is known as a
// "Lagged Fibonacci Generator":
//
// For 1 ≤ k ≤ 55, sk = [100003 − 200003.k + 300007.k^3] (modulo 1000000) − 500000.
// For 56 ≤ k ≤ 4000000, sk = [sk−24 + sk−55 + 1000000] (modulo 1000000) − 500000.
//
// Thus, s10 = −393027 and s100 = 86613.
//
// The terms of s are then arranged in a 2000×2000 table, using the first 2000 numbers to fill the
// first row (sequentially), the next 2000 numbers to fill the second row, and so on.
//
// Finally, find the greatest sum of (any number of) adjacent entries in any direction (horizontal,
// vertical, diagonal or anti-diagonal).
size_t taille = 2000;
vecteur s(taille * taille + 1, 0);
for (size_t k = 1; k < 56; ++k) {
s.at(k) = (100003 - 200003 * k + 300007 * k * k * k) % 1000000 - 500000;
}
for (size_t k = 56; k < taille * taille + 1; ++k) {
s.at(k) = (s.at(k - 24) + s.at(k - 55) + 1000000) % 1000000 - 500000;
}
// std::cout << "s(10) = " << s.at(10) << std::endl;
// std::cout << "s(100) = " << s.at(100) << std::endl;
matrice m(taille, vecteur(taille, 0));
for (size_t n = 1; n < s.size(); ++n) {
m[(n - 1) / taille][(n - 1) % taille] = s.at(n);
}
nombre resultat = 0;
// Somme ligne
for (size_t i = 0; i < m.size(); ++i) {
vecteur v;
for (size_t j = 0; j < m.size(); ++j)
v.push_back(m[i][j]);
resultat = std::max(resultat, maximum(v));
}
// Somme colonne
for (size_t i = 0; i < m.size(); ++i) {
vecteur v;
for (auto & j : m)
v.push_back(j[i]);
resultat = std::max(resultat, maximum(v));
}
// Somme diagonale avec i = 0
for (size_t i = 0; i < m.size(); ++i) {
vecteur v;
for (size_t j = 0; i + j < m.size(); ++j)
v.push_back(m[i + j][j]);
resultat = std::max(resultat, maximum(v));
}
// Somme diagonale avec j = 0
for (size_t i = 0; i < m.size(); ++i) {
vecteur v;
for (size_t j = 0; i + j < m.size(); ++j)
v.push_back(m[j][i + j]);
resultat = std::max(resultat, maximum(v));
}
// Somme anti-diagonale avec i = 0
for (size_t i = 0; i < m.size(); ++i) {
vecteur v;
for (size_t j = 0; j < i + 1; ++j)
v.push_back(m[i - j][j]);
resultat = std::max(resultat, maximum(v));
}
// Somme anti-diagonale avec i = m.size() - 1
for (size_t i = 0; i < m.size(); ++i) {
vecteur v;
for (size_t j = 0; i + j < m.size(); ++j)
v.push_back(m[i + j][m.size() - 1 - j]);
resultat = std::max(resultat, maximum(v));
}
return std::to_string(resultat);
}
| true |
5f8c4d3297f309aa52acd0c0b7da0d6040aa969e | C++ | wangscript007/ojcode | /poj2299_Ultra-QuickSort(树状数组).cpp | GB18030 | 1,370 | 2.984375 | 3 | [] | no_license | #include <stdio.h>
#include <memory.h>
#include <algorithm>
using namespace std;
#define lowbit(t) (t&(-t))
struct type{
int num,index;
}num[500005];
int N,C[500005];//ƶǰ״
bool cmp(struct type a,struct type b)
{
return a.num<b.num;
}
int sum(int *C,int e)
{
int sum = 0;
while(e > 0)
{
sum += C[e];
e -= lowbit(e);
}
return sum;
}
void add(int *C,int pos, int num)
{
while(pos <= N)
{
C[pos] += num;
pos += lowbit(pos);
}
}
//ðݽ±ðݣۼӴǰеδݸ
int main()
{
__int64 solve;
while(1)
{
scanf("%d",&N);
if(N==0)
break;
memset(C,0,(N+1)*sizeof(int));
for(int i=1;i<=N;i++)
{
scanf("%d",&num[i-1].num);//
num[i-1].index=i;//¼±
add(C,i,1);//ʼ״
}
add(C,1,-1);//״ݴ
sort(num,num+N,cmp);//
solve=0;
for(int i=0;i<N;i++)
{
solve+=sum(C,num[i].index);//ۼƶ
add(C,num[i].index,-1);//ȡѴݵı
}
printf("%I64d\n",solve);
}
return 0;
}
| true |
b07ef103622eed3b068f9dc864a3ec88fedfab56 | C++ | cardcaptr/PhenoAppl | /velocityverletintegrator.cpp | UTF-8 | 1,718 | 2.640625 | 3 | [] | no_license | #include "velocityverletintegrator.h"
#include <iostream>
#include <fstream>
#include "particlesbase.h"
#include "solutionExporterLagrangian.h"
#define _USE_MATH_DEFINES
#include <cmath>
VelocityVerletIntegrator::VelocityVerletIntegrator()
{
}
// Integrate nIter iterations using a constant time step dt using a verlet integrator
// Input:
// -dt
// -nIter
// -outputFrequency
// -Particle class
void VelocityVerletIntegrator::integrate(double dt, int nIter, int outputFrequency, ParticlesBase* particles)
{
double t=0;
particles->preprocess();
particles->calculateForce(t);
for (int it=0 ; it < nIter ; ++it)
{
for (int i = 0 ; i < particles->np_; ++i)
{
const double mass = particles->m_[i];
particles->v_[i][0]+= 0.5*dt/mass * (particles->f_[i][0]);
particles->v_[i][1]+= 0.5*dt/mass * (particles->f_[i][1]);
}
for (int i = 0 ; i < particles->np_; ++i)
{
particles->x_[i][0] += particles->v_[i][0] * dt;
particles->x_[i][1] += particles->v_[i][1] * dt;
}
particles->calculateForce(t);
for (int i = 0 ; i < particles->np_; ++i)
{
const double mass = particles->m_[i];
particles->v_[i][0]+= 0.5*dt/mass * (particles->f_[i][0]);
particles->v_[i][1]+= 0.5*dt/mass * (particles->f_[i][1]);
}
t+=dt;
if (it%outputFrequency==0 && nIter > outputFrequency)
{
writeLagrangianParticles("particles",it, particles);
particles->postprocess(t);
}
}
if (nIter > outputFrequency) writeLagrangianParticles("particles",nIter, particles);
}
| true |
015c5000b575384a490577d191fe3b1aeff7c2e9 | C++ | AkshayMariyanna/solutions | /spoj/primeintervals.cpp | UTF-8 | 656 | 2.625 | 3 | [] | no_license | /// https://www.spoj.com/problems/PRINT/
#include <iostream>
#include <cstring>
#include <math.h>
using namespace std;
/*
Not solved
TLE
Revisit
*/
int main() {
int T;
cin >> T;
bool mapOPrime[1000005];
while (T--) {
int s, e;
cin >> s >> e;
int n = e - s + 1;
memset(mapOPrime, 1, n);
int sq = sqrt(e);
for (int i = 2; i <= sq; i++) {
int j = i - (s % i);
j = j == i ? 0 : j;
for (; j < n; j += i) {
int cN = s + j;
if (cN == i) {
continue;
}
mapOPrime[j] = false;
}
}
for (int i = 0; i < n; i++) {
if (mapOPrime[i] && s + i != 1) {
cout << s + i << endl;
}
}
cout << endl;
}
}
| true |
39d9466e1634c48cd6e9b31b0d3821ae12b824b4 | C++ | alan1tavares/maratona-de-programacao | /codcad/vetores/sub-prime.cpp | UTF-8 | 529 | 2.5625 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
//1105
int main(){
int b, n;
int fundo[21];
while(true){
cin>>b>>n;
if(b==0 && n==0) break;
for(int i=1; i<=b; i++) cin>>fundo[i];
for(int i=1; i<=n; i++){
int d, c, v;
cin>>d>>c>>v; // leia os valores de "d", "c" e "v".
fundo[d]-=v;
fundo[c]+=v;
}
int ajuda=0;
for(int i=1; i<=b; i++)
if(fundo[i]<0)
ajuda=1;
if(ajuda==0){
cout<<"S\n";
}else{
cout<<"N\n";
}
}
return 0;
}
| true |
6ea00799420aff36e98e1b347a99d9a5e2b049a2 | C++ | tomvidm/Pelmeni2D | /src/pelmeni/graphics/StaticSprite.cpp | UTF-8 | 1,871 | 2.53125 | 3 | [] | no_license | #include <cstdio>
#include "graphics/StaticSprite.hpp"
namespace p2d { namespace graphics {
void StaticSprite::draw(sf::RenderTarget& target, sf::RenderStates states) const {
if (isDrawable) {
states.transform *= math::toSfmlTransform(getLocalTransform());
states.texture = _texturePtr;
target.draw(_vertices, 4, sf::PrimitiveType::Quads, states);
}
} // draw
void StaticSprite::setSpritePack(const SpritePack::shared spritePack) {
_spritePack = spritePack;
_texturePtr = &(_spritePack->texture.getTexture());
isDrawable = true;
} // setSpritePack
void StaticSprite::setSpriteAnimation(const FrameSequence::alias& animationAlias) {
_animationState.setFrameSequence(_spritePack->getFrameSequence(animationAlias));
}
void StaticSprite::update(const sf::Time& dt) {
if (isDrawable && _animationState.update(dt)) {
setTextureRect(_animationState.getCurrentFrameRect());
}
}
void StaticSprite::setTextureRect(const sf::Rect<float>& rect) {
const math::Vector2f topLeft(rect.left, rect.top);
const math::Vector2f topRight(rect.left + rect.width, rect.top);
const math::Vector2f bottomRight(rect.left + rect.width, rect.top + rect.height);
const math::Vector2f bottomLeft(rect.left, rect.top + rect.height);
const math::Vector2f size(rect.width, rect.height);
_vertices[0].texCoords = topLeft;
_vertices[1].texCoords = topRight;
_vertices[2].texCoords = bottomRight;
_vertices[3].texCoords = bottomLeft;
_vertices[0].position = math::Vector2f();
_vertices[1].position = math::projectToX(size);
_vertices[2].position = size;
_vertices[3].position = math::projectToY(size);
}
} // namespace graphics
} // namespace p2d | true |
988f992776850ebdb9fc53c8b72bd17a33e0b954 | C++ | velenk/Algorithms_Test | /洛谷/1428.cpp | UTF-8 | 910 | 2.890625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
class Node {
public:
int val, index;
};
Node a[1000];
int n;
int ans[1000],c[1000];
int lowbit(int x) {
return x&(-x);
}
void update(int x) {
for (int i = x; i <= n; i+=lowbit(i)) {
c[i]+=1;
}
return;
}
int sum(int x) {
int s = 0;
for (int i = x;i>0;i-=lowbit(i)) {
s+=c[i];
}
return s;
}
int cmp(Node c, Node b) {
return c.val > b.val;
}
int cmp1(Node c, Node b) {
return c.index < b.index;
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i].val);
a[i].index = i;
}
sort(a+1,a+n+1,cmp);
for (int i = 1; i <= n; i++) {
update(a[i].index);
ans[a[i].index] = sum(a[i].index-1);
}
sort(a+1,a+n+1,cmp1);
for (int i = 1; i <= n; i++) {
printf("%d ",i-ans[i]-1);
}
return 0;
}
| true |
5b1947229f16a6a3fcb9aec8b3fd247b2b2e2aad | C++ | liuyaanng/LeetCode | /198.house-robber.cpp | UTF-8 | 339 | 2.75 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=198 lang=cpp
*
* [198] 打家劫舍
*/
// @lc code=start
class Solution {
public:
int rob(vector<int>& nums) {
int m = 0, n = 0;
for(int i = 0; i < nums.size(); ++i){
if(i % 2 == 0){
n += nums[i];
} else {
m += nums[i];
}
}
return max(m, n);
}
};
// @lc code=end
| true |
2df8c40e638177b3eac609178afca37d7cc6e641 | C++ | ipa-rmb/cob_object_perception | /cob_read_text/common/src/createCorrelation.cpp | UTF-8 | 2,950 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
#include <cstdio>
#include <dirent.h>
// ROS includes
#include <ros/ros.h>
#include <ros/package.h>
// OpenCV includes
#include <opencv2/opencv.hpp>
int main(int argc, char* argv[])
{
std::string input_image_path = ros::package::getPath("cob_read_text_data") + "/fonts/letters_arial_600dpi_resized.bmp";
cv::Mat input = cv::imread(input_image_path.c_str()); //"/home/rmb-rh/Desktop/letters_arial/letters_arial_600dpi_resized.bmp");
// extract single letter images from big image
std::vector<cv::Mat> letterImages;
int x_coord = 66, y_coord = 14;
for (unsigned int y = 0; y < 16; y++)
{
for (unsigned int x = 0; x < 16; x++)
{
letterImages.push_back(input(cv::Rect(x_coord, y_coord, 100, 100)));
x_coord += 228;
}
x_coord = 66;
y_coord += 131;
}
// write single letter images as file
std::string letter_image_folder = ros::package::getPath("cob_read_text_data") + "/fonts/";
for (unsigned int i = 0; i < letterImages.size(); i++)
{
std::string s = letter_image_folder;
std::stringstream ss;
ss << i;
s.append(ss.str());
s.append(".png");
std::cout << "s: " << s << std::endl;
cv::imwrite(s, letterImages[i]);
}
// correlate
std::ofstream correlationFile;
std::string textname = ros::package::getPath("cob_read_text_data") + "/fonts/correlation.txt";
correlationFile.open(textname.c_str());
double maxScore = 0, minScore = 1;
std::vector<std::vector<double> > scores(letterImages.size());
for (unsigned int y = 0; y < letterImages.size(); y++)
{
scores[y].resize(letterImages.size());
for (unsigned int x = 0; x < letterImages.size(); x++)
{
// correlationFile << "[" << y << "|" << x << "]: ";
cv::Mat grayLetter2 = cv::Mat(letterImages[y].size(), CV_8UC1, cv::Scalar(0));
cv::cvtColor(letterImages[y], grayLetter2, CV_RGB2GRAY);
cv::Mat grayLetter1 = cv::Mat(letterImages[x].size(), CV_8UC1, cv::Scalar(0));
cv::cvtColor(letterImages[x], grayLetter1, CV_RGB2GRAY);
// count difference pixels
int count = 0;
for (int yy = 0; yy < grayLetter1.rows; yy++)
for (int xx = 0; xx < grayLetter1.cols; xx++)
if ((int)grayLetter1.at<unsigned char> (yy, xx) == (int)grayLetter2.at<unsigned char> (yy, xx))
count++;
scores[y][x] = (double)count / (double)(grayLetter1.rows * grayLetter1.cols);
if (scores[y][x] > maxScore)
maxScore = scores[y][x];
if (scores[y][x] < minScore)
minScore = scores[y][x];
}
}
// write correlations to file
double factor = 1.0/(maxScore-minScore);
for (unsigned int y = 0; y < letterImages.size(); y++)
{
for (unsigned int x = 0; x < letterImages.size(); x++)
correlationFile << (scores[y][x]-minScore)*factor << " ";
correlationFile << std::endl;
}
correlationFile.close();
return 0;
}
| true |
352b39ec202c21953a03d5ead1b4a9fe322c1bda | C++ | shawnhan108/RAIInet | /cell.h | UTF-8 | 948 | 2.90625 | 3 | [] | no_license | #ifndef _CELL_H_
#define _CELL_H_
#include <string>
#include <memory>
#include "piece.h"
typedef std::shared_ptr<Piece> PiecePtr;
class Cell {
int x; //x is row and y is col
int y;
bool isOccP1 = false;
bool isOccP2 = false;
bool firewallOne = false;
bool firewallTwo = false;
std::string OccupiedID = "";
bool player1Port = false;
bool player2Port = false;
PiecePtr thePiece = nullptr;
public:
Cell(int x, int y);
int getx();
int gety();
bool ifOccP1();
void setOccP1(bool isO);
bool ifOccP2();
void setOccP2(bool isO);
bool hasFirewallOne();
void setFirewallOne(bool isW);
bool hasFirewallTwo();
void setFirewallTwo(bool isW);
std::string getName();
void setName(std::string ID);
bool ifp1port();
void setPort1(bool isP);
bool ifp2port();
void setPort2(bool isP);
PiecePtr whoOcc();
void setPiece(PiecePtr newP);
};
#endif
| true |
5fcd31d1a765dcbe725b684b583f6fa8e51193d5 | C++ | Xuhui-Wang/poj-solutions | /2367/9310152_AC_0MS_204K.cpp | UTF-8 | 1,239 | 3.015625 | 3 | [
"MIT"
] | permissive | #define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<algorithm>
const int MEMBER_NUM_MAX=100;
struct Member{
int id,childNum,children[MEMBER_NUM_MAX-1],discover,finish;
bool root;
};
int memberNum;
Member members[MEMBER_NUM_MAX];
int time;
void dfs(int index){
members[index].discover=time++;
for(int i=0;i<members[index].childNum;i++)
if(members[members[index].children[i]].discover==INT_MAX)
dfs(members[index].children[i]);
members[index].finish=time++;
}
bool compareByFinish(const Member &left,const Member &right){
return left.finish>right.finish;
}
int main(){
scanf("%d",&memberNum);
for(int i=0;i<memberNum;i++){
members[i].id=i+1;
members[i].childNum=0;
members[i].discover=members[i].finish=INT_MAX;
members[i].root=true;
}
for(int i=0;i<memberNum;i++){
while(true){
int child;
scanf("%d",&child);
if(!child)
break;
members[i].children[members[i].childNum++]=child-1;
members[child-1].root=false;
}
}
time=0;
for(int i=0;i<memberNum;i++)
if(members[i].root)
dfs(i);
std::sort(members,members+memberNum,compareByFinish);
for(int i=0;i<memberNum;i++)
printf("%d ",members[i].id);
printf("\n");
return 0;
} | true |
42904feebb4390f67120b8b358e4d4cb8c552795 | C++ | marcinmierzejek/suffix_trees | /SuffixTree.h | UTF-8 | 2,545 | 2.78125 | 3 | [] | no_license | /*
* SuffixTree.h
*
* Created on: Feb 24, 2013
* Author: mierzejm
*/
#include <string>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/set.hpp>
#include "helpers.h"
using namespace std;
#ifndef SUFFIXTREE_HPP_
#define SUFFIXTREE_HPP_
// SuffixTreeNode
class SuffixTreeNode {
public:
static const string TERMINATOR;
SuffixTreeNode();
virtual ~SuffixTreeNode();
map<string, SuffixTreeNode*> getChildren();
map<string, SuffixTreeNode*>* getChildrenPointer();
set<int>* getWordIndxs(); // get numbers of words
void addChild(string pKey,
SuffixTreeNode* pNode,
bool pIsSuffix,
int pIdx = 0);
void makeSuffixOf(int pIdx);
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & wordIndxs;
ar & children;
}
map<string, SuffixTreeNode*> children;
set<int> wordIndxs; // numbers of words
SuffixTreeNode* getTerminatorNode();
void addWordIdx(int pIdx);
};
// SuffixTree
class SuffixTree {
public:
SuffixTree();
virtual ~SuffixTree();
SuffixTreeNode* getRoot();
void buildSTree(string pWord);
void buildSTree(vector<string>* pWords);
bool search(string pWord);
bool searchApprox(string pWord);
string getMatching(string pWord);
protected:
void addWord(string* pWord, int pIdx); // add word to the tree
SuffixTreeNode* root; // root of the tree
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version) {
ar & root;
}
Sort sorter;
Compare comparer;
string longestPrefix(string pWords[], int pFrom, int* pTo, size_t pPosFrom, bool pIsFirst);
void buildSSubTreeNaive(SuffixTreeNode* pParent,
string pWords[],
int pFrom,
int pTo,
size_t pPosFrom,
int pIdx = 0);
void buildSTreeNaive(string pWord);
bool search(SuffixTreeNode* pParent, string pWord, size_t pPosFrom);
bool searchApprox(SuffixTreeNode* pParent,
string pWord,
size_t pPosFrom,
int pCurrDist,
int pMaxDist = 1);
string getMatching(SuffixTreeNode* pParent,
string pWord,
size_t pPosFrom,
int pCurrDist,
int pMaxDist = 1);
};
#endif /* SUFFIXTREE_HPP_ */
| true |
8d2c93b2c2e0067f909117ab65438aecb96125b2 | C++ | yruestc/FAS | /base/EventLoopThreadPool.cpp | UTF-8 | 1,867 | 2.53125 | 3 | [] | no_license | #include <memory>
#include <EventLoopThreadPool.h>
#include <EventLoop.h>
#include <boost/bind.hpp>
fas::EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseloop,
int threadNum,
std::string name) :
threadNum_(threadNum),
name_(name),
threads_(),
loops_(),
baseloop_(baseloop),
started_(false),
next_(0),
tid_(gettid()) {
assert(baseloop_ && (threadNum_ >= 0));
threads_.reserve(threadNum_);
loops_.reserve(threadNum_);
}
void fas::EventLoopThreadPool::updateThreadNum(int newNum) {
assertInOwnerThread();
assert(!started_);
threadNum_ = newNum;
}
int fas::EventLoopThreadPool::getThreadNum() {
return threadNum_;
}
void fas::EventLoopThreadPool::updateName(const std::string& newName) {
assertInOwnerThread();
assert(!started_);
name_ = newName;
}
std::string fas::EventLoopThreadPool::getName() {
return name_;
}
void fas::EventLoopThreadPool::assertInOwnerThread() {
assert(gettid() == tid_);
}
bool fas::EventLoopThreadPool::start() {
assertInOwnerThread();
assert(!started_);
for(int i = 0; i < threadNum_; i++) {
std::shared_ptr<fas::EventLoopThread> thread = std::make_shared<fas::EventLoopThread>();
loops_.push_back(thread->start());
threads_.push_back(thread);
}
started_ = true;
//if error
return started_;
}
fas::EventLoop *fas::EventLoopThreadPool::getNextEventLoop() {
assertInOwnerThread();
fas::EventLoop* loop = baseloop_;
if (!loops_.empty()) {
// round-robin
loop = loops_[next_];
++next_;
if (next_ >= loops_.size()) {
next_ = 0;
}
}
return loop;
}
fas::EventLoopThreadPool::~EventLoopThreadPool() {
if (started_) {
for (auto iter = threads_.begin(); iter < threads_.end(); iter++) {
(*iter)->join();
}
}
started_ = false;
}
| true |
5a054259003070e28f132a2af6e95e7f011a767f | C++ | LoganTHarvell/FieaGameEngine | /source/Library.Shared/EventQueue.cpp | UTF-8 | 1,030 | 2.625 | 3 | [] | no_license | #pragma region Includes
// Pre-compiled Header
#include "pch.h"
// Header
#include "EventQueue.h"
// Standard
#include <algorithm>
#include <future>
// First Party
#include "EventPublisher.h"
#pragma endregion Includes
using namespace std::string_literals;
namespace Library
{
void EventQueue::Publish(EventPublisher& event)
{
event.Publish();
}
void EventQueue::Update(const GameTime& gameTime)
{
for (EventEntry& entry : mQueue)
{
if (gameTime.CurrentTime() >= entry.ExpireTime)
{
assert(entry.Publisher);
entry.IsExpired = true;
}
}
auto isExpired = [&gameTime](const EventEntry& eventEntry)
{
return !eventEntry.IsExpired;
};
const auto eventPartition = std::partition(mQueue.begin(), mQueue.end(), isExpired);
Vector expiredEvents(Vector<EventEntry>::EqualityFunctor{});
expiredEvents.Insert(expiredEvents.begin(), eventPartition, mQueue.cend());
mQueue.Erase(eventPartition);
for (const auto& event : expiredEvents)
{
event.Publisher->Publish();
}
}
} | true |
1df3a71866c56b59323c4cbd90a9bccef5c66765 | C++ | zeromem88/algorithm-toolbox | /Week6Ex2/partition3.cpp | UTF-8 | 1,103 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <unordered_map>
using std::vector;
using std::unordered_map;
static unordered_map<long long, bool> memo;
bool doPart3(const vector<int> &A, int m, int n, int p, int l) {
if (m == 0 && n == 0 && p == 0)
return true;
if (l < 0)
return false;
long long key = m * 100000000 + n * 10000 + p;
const auto&& it = memo.find(key);
if (it != memo.end())
return it->second;
if (m - A[l] >= 0 && doPart3(A, m - A[l], n, p, l - 1)) {
memo[key] = true;
return true;
}
if (n - A[l] >= 0 && doPart3(A, m, n - A[l], p, l - 1)) {
memo[key] = true;
return true;
}
if (p - A[l] >= 0 && doPart3(A, m, n, p - A[l], l - 1)) {
memo[key] = true;
return true;
}
memo[key] = false;
return false;
}
int partition3(vector<int> &A) {
int sum = 0;
for (auto&& i : A) {
sum += i;
}
if (sum % 3 != 0)
return 0;
sum = sum / 3;
//write your code here
return doPart3(A, sum, sum, sum, A.size() - 1);
}
int main() {
int n;
std::cin >> n;
vector<int> A(n);
for (size_t i = 0; i < A.size(); ++i) {
std::cin >> A[i];
}
std::cout << partition3(A) << '\n';
}
| true |
43a3e629238fa23f5b43fdac4d5957ed774acc7b | C++ | pacemario/programas-sencillos-c- | /priigualult.cpp | UTF-8 | 353 | 3.125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <conio.h>
#include <stdio.h>
using namespace std;
int main(){
int pri,ult,num;
puts("Ingrese el numero");
scanf("%d",&num);
ult=num%10;
do{
pri=num%10;
num=num/10;
}while(num!=0);
if(pri==ult) puts("Comienza y termina con el mismo numero");
else puts("No comienza y termina con el mismo numero");
}
| true |
f239d8cd9e3c1fb58fed1cad1a8ab0e52ef58c2e | C++ | adamleighfish/c3po | /src/sphere.cpp | UTF-8 | 3,725 | 2.84375 | 3 | [] | no_license | #include "sphere.h"
#include "interaction.h"
#include "transform.h"
#include "utility.h"
#include <numbers>
namespace c3po {
Sphere::Sphere(std::shared_ptr<Transform> object_to_world,
std::shared_ptr<Transform> world_to_object,
bool reverse_orientation, float radius)
: Shape(std::move(object_to_world), std::move(world_to_object),
reverse_orientation),
radius(radius) {}
Bounds3f Sphere::object_bounds() const {
return Bounds3f(Vec3f(-radius), Vec3f(radius));
}
bool Sphere::intersect(Ray const& r, float& t_hit,
SurfaceInteraction& isect) const {
// transform the ray to object space
Ray const ray = world_to_object->apply(r);
// compute the quadratic sphere coefficients
float const a = ray.dir.dot(ray.dir);
float const b = 2 * (ray.dir.dot(ray.origin));
float const c = ray.origin.dot(ray.origin) - radius * radius;
// solve the quadratic equation for t values
float t0;
float t1;
if (!quadratic(a, b, c, t0, t1)) {
return false;
}
// check that the t values are in bounds
if (t0 > ray.t_max || t1 <= 0.f) {
return false;
}
// save the nearest intersection
float t_shape_hit = t0;
if (t_shape_hit <= 0.f) {
t_shape_hit = t1;
if (t_shape_hit > ray.t_max) {
return false;
}
}
// compute sphere hit position
Point3f p_hit = ray(t_shape_hit);
p_hit *= radius / distance(p_hit, Point3f(0.f));
if (p_hit.x == 0.f && p_hit.y == 0.f) {
p_hit.x = 1e-5f * radius;
}
// compute sphere hit phi
float phi = std::atan2f(p_hit.y, p_hit.x);
if (phi < 0.f) {
phi += 2.f * float(std::numbers::pi);
}
// find the parametric representation of the sphere hit
float const u = phi / float(2 * std::numbers::pi);
float const theta = std::acosf(clamp(p_hit.z / radius, -1.f, 1.f));
float const v = (theta - 1.f) / 2.f;
// compute sphere dpdu and dpdv
float const z_radius = std::sqrtf(p_hit.x * p_hit.x + p_hit.y * p_hit.y);
float const inv_z_radius = 1.f / z_radius;
float const cos_phi = p_hit.x * inv_z_radius;
float const sin_phi = p_hit.y * inv_z_radius;
Vec3f const dpdu(-2.f * float(std::numbers::pi) * p_hit.y,
2.f * float(std::numbers::pi) * p_hit.x, 0.f);
Vec3f const dpdv(2.f * p_hit.z * cos_phi, 2.f * p_hit.z * sin_phi,
-2.f * radius * std::sinf(theta));
// initialize surface interaction from parametric information
isect = object_to_world->apply(SurfaceInteraction(
p_hit, Point2f(u, v), -ray.dir, dpdu, dpdv, ray.time, this));
// update t_hit for quadric intersection
t_hit = t_shape_hit;
return true;
}
bool Sphere::intersects(Ray const& r) const {
// transform the ray to object space
Ray const ray = world_to_object->apply(r);
// compute the quadratic sphere coefficients
float const a = ray.dir.dot(ray.dir);
float const b = 2 * (ray.dir.dot(ray.origin));
float const c = ray.origin.dot(ray.origin) - radius * radius;
// solve the quadratic equation for t values
float t0;
float t1;
if (!quadratic(a, b, c, t0, t1)) {
return false;
}
// check that the t values are in bounds
if (t0 > ray.t_max || t1 <= 0.f) {
return false;
}
// save the nearest intersection
float t_shape_hit = t0;
if (t_shape_hit <= 0.f) {
t_shape_hit = t1;
if (t_shape_hit > ray.t_max) {
return false;
}
}
return true;
}
float Sphere::area() const {
return 4.f * float(std::numbers::pi) * radius * radius;
}
} // namespace c3po
| true |
9a923ff0c14fe814cf82b439e9086c6b26016bc6 | C++ | PatrikoPy/Arduino_Temperature_alarm | /SW_zad3.ino | UTF-8 | 1,682 | 2.671875 | 3 | [] | no_license | #define AREF_VOLTAGE 3.3
#define TEMP_SENSOR_PIN 5
#define BUTTON_PIN_L 12
#define BUTTON_PIN_P 13
#define ALERT_PIN 2
float temperature;
unsigned short alert5 = 0;
unsigned short buzzerOff = 0;
unsigned short buttonStateL = 0;
unsigned short buttonStateP = 0;
void ledClear()
{
for (short p = 2; p < 12; p++)
{
digitalWrite(p, LOW);
}
}
void ledAll()
{
for (short p = 2; p < 12; p++)
{
if (buzzerOff == 1 & p == 2) {
continue;
}
digitalWrite(p, HIGH);
}
}
float checkTemperature()
{
int tempReading = analogRead(TEMP_SENSOR_PIN);
float voltage = tempReading * AREF_VOLTAGE;
voltage /= 1024.0;
// Convert from 10 mv per degree with 500 mV offset to degrees celsius
// ((voltage - 500mV) * 100)
float temperatureC = (voltage - 0.5) * 100 ;
Serial.println(temperatureC);
// Delay for sensor to stabilize
delay(1000);
return temperatureC;
}
void setup() {
Serial.begin(9600);
analogReference(EXTERNAL);
for (int i = 2; i < 12; i++)
{
pinMode(i, OUTPUT);
}
pinMode(BUTTON_PIN_L, INPUT);
pinMode(BUTTON_PIN_P, INPUT);
}
void loop() {
temperature = checkTemperature();
buttonStateL = digitalRead(BUTTON_PIN_L);
buttonStateP = digitalRead(BUTTON_PIN_P);
if (temperature > 26.0)
{
Serial.println(buttonStateL);
Serial.println(buttonStateP);
if (buttonStateL == HIGH | buttonStateP == HIGH)
{
buzzerOff = 1;
ledClear();
}
if (alert5 < 5)
{
digitalWrite(ALERT_PIN, LOW);
delay(100);
digitalWrite(ALERT_PIN, HIGH);
alert5++;
}
else
{
ledAll();
}
}
else
{
ledClear();
buzzerOff = 0;
alert5 = 0;
}
}
| true |
a0da50ab81567f5cccb218ef2dc13fc2d4c945f6 | C++ | shalyapin/Crystals-and-dragons | /Crystals and dragons/Crystals and dragons/View.cpp | UTF-8 | 3,052 | 3.109375 | 3 | [] | no_license | #include "View.h"
#include "ConsoleColor.h"
using namespace view;
using namespace model;
using namespace std;
View::View(Model * model) {
this->model = model;
model->registerObserver(this);
rowDialogue = 0;
isDarkRoom = false;
}
void View::update(ActionType type) {
switch (type) {
case HeroMove:
break;
case UnknownCommand:
dialogueHero[rowDialogue] = " I don't understand the commands";
++rowDialogue;
break;
case MonsterThrewHero:
dialogueHero[rowDialogue] = " I was thrown monster!";
++rowDialogue;
break;
case MonsterBitHero:
dialogueHero[rowDialogue] = " Monster hurt me!";
++rowDialogue;
break;
case HeroNotSeeMonster:
dialogueHero[rowDialogue] = " There is no one to fight!";
++rowDialogue;
break;
case HeroInDarkRoom:
isDarkRoom = true;
break;
case HeroSeeMonsterInRoom:
dialogueHero[rowDialogue] = " There is an evil " + model->getMonsters() + " in the room!";
++rowDialogue;
break;
case HeroHitWall:
dialogueHero[rowDialogue] = " There is a wall!";
++rowDialogue;
break;
case HeroHasNotItem:
dialogueHero[rowDialogue] = " I have no such item!";
++rowDialogue;
break;
case HeroGetItem:
break;
case HeroEat:
dialogueHero[rowDialogue] = " Mmm yummy!";
++rowDialogue;
break;
case LocationHasNotItem:
dialogueHero[rowDialogue] = " There is no such object";
++rowDialogue;
break;
case HeroKilledMonster:
dialogueHero[rowDialogue] = " I killed the monster!";
++rowDialogue;
break;
case HeroOpenChest:
dialogueHero[rowDialogue] = " I found the Holy Grail!";
++rowDialogue;
break;
case HeroCanNotEat:
dialogueHero[rowDialogue] = " I can not eat it!";
++rowDialogue;
break;
case HeroGetChest:
dialogueHero[rowDialogue] = " I can not take the chest!";
++rowDialogue;
break;
default:
break;
}
}
void View::display() {
system("cls");
if (isDarkRoom) {
cout << endl;
cout << white << "----------------> " << red << "Can't see anything in this dark place!" << endl;
cout << endl;
isDarkRoom = false;
}
else {
cout << white << "You are in the room [" << yellow << model->getPositionHero_X() << white << "," << yellow << model->getPositionHero_Y() << white << "]" << endl;
cout << "There are [" << yellow << model->getNumberOfDoors() << white << "] doors: " << yellow << model->getDirections() << endl;
cout << white << "Items in the room: " << yellow << model->getItems() << endl;
cout << green << "-----------------------------------" << endl;
cout << blue << "Hero -> " << red << model->getNameHero() << endl;
cout << blue << "Healt -> " << yellow << model->getHealtHero() << endl;
cout << blue << "Money -> " << yellow << model->getNumberMoneyOfHero() << endl;
cout << blue << "Equipment -> " << yellow << model->getEquipmentHero() << endl;
cout << green << "***********************************" << endl;
}
for (int i = 0; i < rowDialogue; i++) {
cout << endl;
cout << white << "---------------->" << red << dialogueHero[i] << endl;
cout << endl;
}
rowDialogue = 0;
} | true |
83fc8556c130569db07fb24db982218d7eedef31 | C++ | tej17/Competitive-Coding | /a2oj/275A.cpp | UTF-8 | 410 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int a[5][5] = {0};
int b[5][5];
int x;
for(int i=1;i<4;i++){
for(int j=1;j<4;j++){
cin >> a[i][j];
}
}
for(int i=1;i<4;i++){
string row;
for(int j=1;j<4;j++){
b[i][j] = a[i][j] + a[i-1][j] + a[i+1][j] + a[i][j-1] + a[i][j+1];
if(b[i][j]%2==0){
row+="1";
} else {
row+="0";
}
}
cout << row << endl;
}
return 0;
} | true |
acca1c6f65be1b8942584d144e3944cb157e9859 | C++ | Swathi-vyas/SimulatorProject | /Cpp_Prac/nvidia_prac/src/tik_tak_toe.cpp | UTF-8 | 351 | 3.140625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int** arr; int j;
arr = new int*[8];
for(auto i=0; i<8;i++){
arr[i] = new int[8];
}
for(auto i=0; i<8; i++){
for(auto j=0; j<8; j++)
arr[i][j]=(i+j+1)%2;
}
for(auto i=0; i<8; i++){
for(auto j=0; j<8; j++){
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
63163cc685b7399a2b000fd59a52fe6410815f40 | C++ | ctkhanhly/C- | /homework/hw05/temp.cpp | UTF-8 | 18,746 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
//82,8,,108,183,189
//82, 90, 111, 188, 198
class Warrior{
friend ostream& operator<<(ostream& os, const Warrior& warrior){
os << warrior.name << ": " << warrior.strength;
return os;
}
private:
string name;
double strength;
bool isHired;
bool isDead;
public:
Warrior(const string& name, double strength): name(name), strength(strength),
isHired(false), isDead(false){}
void setIsHired(bool isHired){
this->isHired = isHired;
}
void setIsDead(bool isDead){
this->isDead = isDead;
}
void setStrength(double strength){
this-> strength = strength;
}
bool getIsHired() const {
return isHired;
}
const string& getName() const {
return name;
}
double getStrength() const {
return strength;
}
};
class Noble{
friend ostream& operator<<(ostream& os, const Noble& noble){
if(noble.armyOfWarriors.size() == 0){
os << "NONE";
}
else{
os << noble.name << " has an army of " << noble.armyOfWarriors.size();
for(Warrior* warrior: noble.armyOfWarriors){
os << endl;
os << "\t" << *warrior;
}
}
return os;
}
private:
string name;
double strength;
bool isDead;
vector<Warrior*> armyOfWarriors;
public:
Noble(const string& name): name(name){}
// ~Noble(){
// }
void setStrength(double strength){
this->strength = strength;
}
void setIsDead(bool isDead){
this->isDead = isDead;
}
bool getIsDead() const {
return isDead;
}
double getStrength() const {
return strength;
}
const string& getName() const {
return name;
}
//cannot change army but can access?
const vector<Warrior*>& getArmyOfWarriors() const {
return armyOfWarriors;
}
bool hire(Warrior& warrior){
//************ check on this error
//Check if the warrior exists
//check in main
// if(!warrior){
// cerr << "This warrior does not exist" << endl;
// exit(1);
// }
//Check if this noble exists
//******* What does this mean??? 'this' pointer cannot be null in well-defined C++
//code; pointer may be assumed to always convert to true
// if(!this){
// cerr << "This noble does not exist" << endl;
// exit(1);
// }
//If the Noble is dead, he cannot hire anyone
//Or if the warrior is already hired,
//the noble cannot hire him
if(isDead || warrior.getIsHired()){
return false;
}
else{
warrior.setIsHired(true);
armyOfWarriors.push_back(&warrior);
strength+= warrior.getStrength();
return true;
}
}
bool fire(Warrior& warrior){
//Check if the Noble exists.
// if(!this){
// return false;
// }
//Check if there is a warrior in the army
//that has the same name as this warrior
size_t count = 0;
for(Warrior* theWarrior: armyOfWarriors){
if(theWarrior->getName() == warrior.getName()){
count ++;
}
}
if(count == 0){
return false;
}
//If the Noble is dead, he cannot fire anyone
if(isDead){
return false;
}
else{
size_t wIndex;
for(size_t i = 0; i < armyOfWarriors.size(); ++i){
if(armyOfWarriors[i] == &warrior){
wIndex = i;
}
}
for(size_t i = wIndex; i < armyOfWarriors.size(); ++i){
armyOfWarriors[i] = armyOfWarriors[i+1];
}
armyOfWarriors.pop_back();
strength -= warrior.getStrength();
warrior.setIsHired(false);
return true;
}
}
/*
This method takes in the Noble that wins and the Noble that loses
and resets the strength of the noble that wins.
*/
void setStrengthWinner(Noble& winner, Noble& loser){
double ratio = loser.getStrength() / winner.getStrength();
for(Warrior* const warrior : winner.getArmyOfWarriors()){
double curr_strength = warrior->getStrength();
warrior->setStrength(curr_strength*(1-ratio));
}
winner.setStrength(winner.getStrength() * (1 - ratio));
}
/*
This method takes in the Noble that loses and announces
that the Noble and all his Warriors are now dead
*/
void setStrengthLoser(Noble& noble){
for(Warrior* const warrior : noble.getArmyOfWarriors()){
warrior->setStrength(0);
warrior->setIsDead(true);
}
noble.setStrength(0);
noble.setIsDead(true);
}
/*
This method starts the battle by taking in the Noble this object
this fighting against, and then change each warrior's strength
according to the following rules:
If a Noble has less strength then he and all of his Warriors are dead and
the stronger Noble and each Warrior loses only the amount of strength
that is proportional to his enemy's total army strength over his total
army strength
If two warriors have the same strength, they both lose all strength
Then, this method prints out the result of the battle.
*/
void battle(Noble& noble){
//Check if this noble exists
// if(!this){
// cerr << "This noble does not exist" << endl;
// exit(1);
// }
//!(this && &noble)
//Check if the enemy noble exists
// reference cannot be bound to dereferenced null pointer
// in well-defined C++ code; pointer may be assumed to always convert to true
//Check in main
// if(!noble){
// cerr << "This enemy noble does not exist" << endl;
// exit(1);
// }
cout << this->name << " battles " << noble.getName() << endl;
double enemyStrength = noble.getStrength();
if(this->isDead && noble.getIsDead()){
cout << "Oh, NO! They're both dead! Yuck!" << endl;
}
else if(this->isDead){
cout << "He's dead, " << noble.getName() << endl;
}
else if(noble.getIsDead()){
cout << "He's dead, " << this->name << endl;
}
else if(this->strength < enemyStrength){
cout << noble.getName() << " defeats " << this->name << endl;
setStrengthWinner(noble, *this);
setStrengthLoser(*this);
}
else if(this->strength == enemyStrength){
cout << "Mutual Annihalation: " << this->name << " and "
<< noble.getName() << " die at each other's hands" << endl;
setStrengthLoser(*this);
setStrengthLoser(noble);
}
else{
cout << this->name << " defeats " << noble.getName() << endl;
setStrengthWinner(*this, noble);
setStrengthLoser(noble);
}
}
};
void WarriorCommand(const string& name, double strength, vector<Warrior*>& warriors){
for(Warrior* warrior: warriors){
if(warrior->getName() == name){
cerr << "This warrior already exists" << endl;
exit(1);
}
}
warriors.push_back(new Warrior(name, strength));
}
void NobleCommand(const string& name, vector<Noble*>& nobles){
for(Noble* noble: nobles){
if(noble->getName() == name){
cerr << "This noble already exists" << endl;
exit(1);
}
}
nobles.push_back(new Noble(name));
}
void StatusCommand(vector<Noble*>& nobles, vector<Warrior*>& warriors){
//cout << nobles.size() << endl;
size_t numOfNoblesInHeap = 0;
for(Noble* noble: nobles){
if(noble){
cout << *noble << endl;
numOfNoblesInHeap++;
}
}
if(nobles.size() - numOfNoblesInHeap == nobles.size()){
cout << "NONE" << endl;
}
cout << "Unemployed Warriors:" << endl;
size_t numOfWarriorsInHeap = 0;
int numOfHiredWarriors = 0;
for(Warrior* warrior: warriors){
//&& warrior to make sure it's not deleted
if(warrior){
numOfWarriorsInHeap++;
}
else{
continue;
}
//
if(warrior->getIsHired()){
numOfHiredWarriors ++;
}
else{
cout << *warrior << endl;
}
}
if(warriors.size() - numOfHiredWarriors == 0 ||
warriors.size() - numOfWarriorsInHeap == warriors.size()){
cout << "NONE" << endl;
}
}
void HireCommand(const string& name1, const string& name2,
vector<Noble*>& nobles, vector<Warrior*>& warriors){
Noble* theNoble;
Warrior* theWarrior;
for(Noble* noble: nobles){
if(name1 == noble->getName()){
theNoble = noble;
break;
}
}
if(!theNoble){
cerr << "This Noble does not exist" << endl;
exit(1);
}
for(Warrior* warrior: warriors){
if(name2 == warrior->getName()){
theWarrior = warrior;
break;
}
}
if(!theWarrior){
cerr << "This Warrior does not exist" << endl;
exit(1);
}
theNoble->hire(*theWarrior);//**** hire(theWarrior*)?
}
void FireCommand(const string& name1, const string& name2,
vector<Noble*>& nobles, vector<Warrior*>& warriors){
Noble* theNoble;
Warrior* theWarrior;
for(Noble* noble: nobles){
if(name1 == noble->getName()){
theNoble = noble;
break;
}
}
if(!theNoble){
cerr << "This Noble does not exist" << endl;
exit(1);
}
for(Warrior* warrior: warriors){
if(name2 == warrior->getName()){
theWarrior = warrior;
break;
}
}
if(!theWarrior){
cerr << "This Warrior does not exist" << endl;
exit(1);
}
theNoble->fire(*theWarrior);//**** hire(theWarrior*)?
cout << "You don't work for me anymore" << theWarrior->getName() <<
"! -- " << theNoble->getName() << "." << endl;
}
void BattleCommand(const string& name1, const string& name2, vector<Noble*>& nobles){
Noble* theNoble1;
Noble* theNoble2;
for(Noble* noble: nobles){
if(name1 == noble->getName()){
theNoble1 = noble;
break;
}
}
for(Noble* noble: nobles){
if(name2 == noble->getName()){
theNoble2 = noble;
break;
}
}
if(!theNoble1){
cerr << "This Noble does not exist" << endl;
exit(1);
}
if(!theNoble2){
cerr << "The enemy Noble does not exist" << endl;
exit(1);
}
theNoble1->battle(*theNoble2);
}
void ClearCommand(vector<Noble*>& nobles, vector<Warrior*>& warriors){
//i need the reference in both cases
//order doesnt matter
for(Warrior*& warrior: warriors){
delete warrior;
warrior = nullptr;
}
for(Noble*& noble: nobles){
delete noble;
noble = nullptr;
}
}
int main(){
ifstream nobleText("nobleWarriors.txt");//single quote failed here
if(!nobleText){
cerr << "File not found" << endl;
exit(1);
}
// Each time a warrior or a noble is defined, we will create it on the heap.
// We will keep track of the nobles in a vector of pointers to nobles.
// We will keep track of all warriors using a vector of pointers to warriors.
// Noble. Create a Noble on the heap.
// Warrior. Create a Warrior on the heap.
// Hire. Call the Noble's hire method.
// Fire. Call the Noble's fire method.
// Battle. Call the Noble's battle method.
// Status. The status command shows the nobles, together with their armies,
// as we did previously. In addition, it will show separately the
// warriors who do not currentle have a employer
// Clear. Clear out all the nobles and warriors that were created.
// Our application is going to rely on each Noble having a unique name
//and each Warrior having a unique name. Otherwise, how would we be sure who we
// were hiring (or firing). Note that this is not a requirement of the Noble and
// Warrior classes themselves, just of this particular use of them, i.e. our application.
//so dont have to check for it in the class itself?
// Now we would like you to take some responsibility for checking the input.
// First, we still guarantee that the format of the file will be correct.
// That means that the Warrior command will always have a name and a strength.
// The Battle command will always have two names. The Status command will not have any other information on it than just the word Status.
// However, you will need to detect and report any issues indicating inconsistencies, such as:
// Noble command: if a Noble with a given name already exists.
// Warrior command:if a Warrior with a given name already exists.
// Hire command: If a Noble tries to hire a Warrior and either of them do not exist.
// Fire command: If a Noble tries to fire a Warrior and either the Noble does not exist or does not have the Warrior by that name in this army.
// Battle command: If a Noble initiates a battle with another Noble, but one or the other does not exist.
vector<Noble*> nobles;
vector<Warrior*> warriors;
string command, name;
double strength;
while(nobleText >> command){
string name1, name2;
//can create string name and strength here?
if(command == "Noble"){
nobleText >> name;
NobleCommand(name, nobles);
// for(Noble* noble: nobles){
// if(noble->getName() == name){
// cerr << "This noble already exists" << endl;
// exit(1);
// }
// }
// nobles.push_back(new Noble(name));
}
else if(command == "Warrior"){
nobleText >> name;
nobleText >> strength;
WarriorCommand(name, strength, warriors);
// for(Warrior* warrior: warriors){
// if(warrior->getName() == name){
// cerr << "This warrior already exists" << endl;
// exit(1);
// }
// }
// warriors.push_back(new Warrior(name, strength));
}
else if(command == "Status"){
cout << "Status" << endl;
cout << "======" << endl;
cout << "Nobles:" << endl;
StatusCommand(nobles, warriors);
// for(Noble* noble: nobles){
// cout << *noble << endl;
// }
// cout << "Unemployed Warriors:" << endl;
// int numOfHiredWarriors = 0;
// for(Warrior* warrior: warriors){
// if(warrior->getIsHired()){
// numOfHiredWarriors ++;
// }
// else{
// cout << *warrior << endl;
// }
// }
// if(warriors.size() - numOfHiredWarriors == 0){
// cout << "NONE" << endl;
// }
}
else if(command == "Hire"){
nobleText >> name1;
nobleText >> name2;
HireCommand(name1, name2, nobles, warriors);
// Noble* theNoble;
// Warrior* theWarrior;
// for(Noble* noble: nobles){
// if(name1 == noble->getName()){
// theNoble = noble;
// break;
// }
// }
// if(!theNoble){
// cerr << "This Noble does not exist" << endl;
// exit(1);
// }
// for(Warrior* warrior: warriors){
// if(name2 == warrior->getName()){
// theWarrior = warrior;
// break;
// }
// }
// if(!theWarrior){
// cerr << "This Warrior does not exist" << endl;
// exit(1);
// }
// theNoble->hire(*theWarrior);//**** hire(theWarrior*)?
}
else if(command == "Fire"){
nobleText >> name1;
nobleText >> name2;
FireCommand(name1, name2, nobles, warriors);
// Noble* theNoble;
// Warrior* theWarrior;
// for(Noble* noble: nobles){
// if(name1 == noble->getName()){
// theNoble = noble;
// break;
// }
// }
// if(!theNoble){
// cerr << "This Noble does not exist" << endl;
// exit(1);
// }
// for(Warrior* warrior: warriors){
// if(name2 == warrior->getName()){
// theWarrior = warrior;
// break;
// }
// }
// if(!theWarrior){
// cerr << "This Warrior does not exist" << endl;
// exit(1);
// }
// theNoble->fire(*theWarrior);//**** hire(theWarrior*)?
// cout << "You don't work for me anymore" << theWarrior->getName() <<
// "! -- " << theNoble->getName() << "." << endl;
}
else if(command == "Battle"){
nobleText >> name1;
nobleText >> name2;
BattleCommand(name1, name2, nobles);
// Noble* theNoble1;
// Noble* theNoble2;
// for(Noble* noble: nobles){
// if(name1 == noble->getName()){
// theNoble1 = noble;
// break;
// }
// }
// for(Noble* noble: nobles){
// if(name2 == noble->getName()){
// theNoble2 = noble;
// break;
// }
// }
// if(!theNoble1){
// cerr << "This Noble does not exist" << endl;
// exit(1);
// }
// if(!theNoble2){
// cerr << "The enemy Noble does not exist" << endl;
// exit(1);
// }
// theNoble1->battle(*theNoble2);
}
else if(command == "Clear"){
ClearCommand(nobles, warriors);
}
else{
cerr << "Command does not exist" << endl;
exit(1);
}
}
nobleText.close();
} | true |
137768a8f6d102fe0488af5395ba8f2051fbed82 | C++ | surendhar-code/OOPS-practice | /Stack(class).cpp | UTF-8 | 1,034 | 3.90625 | 4 | [] | no_license | #include<iostream>
#include<iomanip>
#define MAX 30
using namespace std;
class Stack
{
private:
int top;
int value;
int stack[MAX];
public:
Stack()
{
top= -1;
}
void push()
{
if(top==(MAX-1))
cout<<"Stack overflow\n";
else
{
cout<<"Enter the element to be inserted \n";
cin>>value;
top++;
stack[top]=value;
}
}
void pop()
{
if(top==-1)
cout<<"The stack is empty-underflow\n";
else{
cout<<"The deleted element is : "<<stack[top]<<endl;
top--;
}
}
void print()
{
display();
}
protected:
void display()
{
for(int i=0;i<=top;i++)
cout<<"value : "<<stack[i]<<endl;
}
};
int main()
{
Stack obj;
obj.push();
obj.push();
obj.push();
obj.pop();
obj.print();
return 0;
}
| true |
14c8c54ddd42d934686484f4f89cc75748ca7a0d | C++ | cyberfenrir/programs-C | /CHAP5_14.CPP | UTF-8 | 617 | 3.109375 | 3 | [] | no_license | #include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
double i;
double a;
cout<<"Enter the annual salary of a person: ";
cin>>i;
if((i>=0)&&(i<=10000))
{
cout<<"No need to pay Income Tax.";
}
else if((i>=100001)&&(i<=150000))
{
a =((10.0*(i-100000.0))/100.0);
cout<<"The person has to pay Rs."<<a;
}
else if((i>=150001)&&(i<=250000))
{
a =(5000+(20.0*(i-150000.0))/100.0);
cout<<"The person has to pay Rs."<<a;
}
else if(i>250000)
{
a =(25000+(20.0*(i-250000.0))/100.0);
cout<<"The person has to pay Rs."<<a;
}
else
{
cout<<"Invalid input of annual salary.";
}
getch();
} | true |
54e4e25894184b20911d0c6aa592bd76ef4bfbf9 | C++ | Airahc/Tstl | /test/test.hpp | UTF-8 | 4,072 | 2.796875 | 3 | [] | no_license | #ifndef _TEST_HPP_
#define _TEST_HPP_
#ifndef _KERNEL_TSTL
#include "stdio.h"
#else
#define printf_s DbgPrint
#endif
namespace Test {
class MyClass {
public:
MyClass() {
printf_s("地址:%p 构造: %s\n", this, __FUNCSIG__);
}
MyClass(int i): m_value(i) {
printf_s("地址:%p 构造: %s\n", this, __FUNCSIG__);
}
~MyClass() {
printf_s("地址:%p 析构:%s\n", this, __FUNCSIG__);
}
void _destory() {
// 析构函数
printf_s("地址:%p 析构:%s\n", this, __FUNCSIG__);
}
MyClass(const MyClass& t) {
printf_s("地址:%p 拷贝构造: %s\n", this, __FUNCSIG__);
if (&t == this) {
return;
}
this->m_value = t.m_value;
return;
}
MyClass(MyClass&& t) {
printf_s("地址:%p 拷贝构造: %s\n", this, __FUNCSIG__);
if (&t == this) {
return;
}
this->m_value = t.m_value;
t.m_value = 0;
return;
}
MyClass& operator=(const MyClass& t) {
printf_s("地址:%p 赋值构造: %s\n", this, __FUNCSIG__);
if (&t == this) {
return *this;
}
this->m_value = t.m_value;
return *this;
}
MyClass& operator=(MyClass&& t) {
printf_s("地址:%p 赋值构造: %s\n", this, __FUNCSIG__);
if (&t == this) {
return *this;
}
this->m_value = t.m_value;
t.m_value = 0;
return *this;
}
bool operator==(const MyClass& t) {
if (&t == this) {
return true;
}
return this->m_value == t.m_value ? false : true;
}
public:
void test1() {
printf_s("地址:%p 成员函数: %s\n", this, __FUNCSIG__);
}
virtual void test2() {
// 不支持
printf_s("地址:%p 虚函数: %s\n", this, __FUNCSIG__);
}
private:
int m_value;
};
Tstl::TList<int>* gtest;
Tstl::TList<MyClass>* g_listMyclass1;
Tstl::TList<MyClass>* g_listMyclass2;
MyClass* g_MyClass;
void __init() {
Tstl::init_global_vars(g_listMyclass1, gtest, g_listMyclass2, g_MyClass);
}
void __destory() {
Tstl::destory_global_vars(g_listMyclass1, gtest, g_listMyclass2, g_MyClass);
}
// 测试全局变量
void test_g_class() {
// Tstl::Constructor<MyClass> t3 , t4;
// t3.init_args(1);
// t4.init_args(2);
// t3.get().m_str = "t1";
// t4.get().m_str = "t2";
// gmyclass->add(t3);
// gmyclass->add(t4);
MyClass t1(1), t2(2), t3(6);
MyClass ttt1 = t1;
auto ttt2 = t1;
ttt2 = t1;
g_listMyclass1->add(t1);
g_listMyclass1->add(t2);
g_listMyclass1->add(Tstl::move(t3));
g_listMyclass1->remove(t1);
g_listMyclass1->clear();
auto fun = [](MyClass& my, int a, int b) {
g_MyClass->test1();
my.test1();
// my.test2();
return a + b;
};
auto testff = fun(t1, 1, 2);
}
// 测试局部变量
void test_l_class() {
Tstl::TList<MyClass> listMyclass;
MyClass t1(1), t2(2), t3(6);
MyClass ttt1 = t1;
auto ttt2 = t1;
ttt2 = t1;
listMyclass.add(t1);
listMyclass.add(t2);
listMyclass.add(Tstl::move(t3));
listMyclass.remove(t1);
listMyclass.clear();
auto fun = [](MyClass& my, int a, int b) {
g_MyClass->test1();
my.test1();
// my.test2();
return a + b;
};
auto testff = fun(t1, 1, 2);
}
} // namespace Test
#endif // !_TEST_HPP_
| true |
45f844ff395afb80281ed4af66b4c1717f1fd516 | C++ | rohit236c/Competitive-programming-CPP | /linkedlist01.cpp | UTF-8 | 2,313 | 3.640625 | 4 | [] | no_license | #include<iostream>
using namespace std;
class node {
public:
int data;
node*next;
node(int d) {
data = d;
next = NULL;
}
};
node * deletemid(node*head){
node*fast = head;
node*slow = head;
node*prev = NULL;
while(fast!=NULL && fast->next!=NULL){
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = slow->next;
return head;
}
node * reverseHead(node*&head){
if(head==NULL || head->next == NULL){
return head;
}
node * rev = reverseHead(head->next);
head->next->next = head;
head->next = NULL;
return rev;
}
void create(node*&head, int data) {
node *n = new node(data);
n -> next = head;
head = n;
}
void insertatmid(node*head, int data, int pos) {
if (head == NULL || pos == 1) {
create(head, data);
}
else {
node*ptr = head;
node*prev;
int cnt = 1;
while (cnt < pos) {
prev = ptr;
ptr = ptr->next;
cnt++;
}
node*n = new node(data);
n->next = prev->next;
prev->next = n;
}
}
void insertatend(node*&head, int data) {
if (head == NULL) {
node*n = new node(data);
head = n;
}
else {
node*temp = head;
while (temp->next != NULL) {
temp = temp->next;
} temp->next = new node(data);
}
}
void insert(node*&head) {
int data;
cin >> data;
node *n = new node(data);
head = n;
node*ptr = head;
cin >> data;
while (data != -1) {
insertatend(head, data);
cin >> data;
}
}
void circularlinkedlist(node*head) {
if (head == NULL) {
return;
}
else {
node*ptr = head;
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = head;
}
}
void print(node*head) {
node*temp = head;
do {
cout << temp->data << "->";
temp = temp->next;
} while (temp != head);
cout << endl;
}
void print1(node*head) {
while (head) {
cout << head->data << "->";
head = head->next;
}
}
bool detectcycle(node*head) {
node*slow = head;
node*fast = head;
while ( fast != NULL && fast->next != NULL ) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
return true;
}
}
return false;
}
int main() {
node*head = NULL;
cout << "ENTER THE ELEMENTS IN circularlinkedlist " << endl;
insert(head);
// circularlinkedlist(head);
// deletemid(head);
node * rev = reverseHead(head);
cout << "ELEMENTS of circularlinkedlist is" << endl;
print(rev);
// print1(head);
} | true |
918070e3c6fbf6073177a29342ab53a5cfad904e | C++ | solomonwzs/leetcode | /cpp/src/populating_next_right_pointers_in_each_node_2.cpp | UTF-8 | 1,601 | 3.3125 | 3 | [] | no_license | #include "leetcode.h"
using namespace std;
struct TreeLinkNode{
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x): val(x), left(NULL), right(NULL), next(NULL){}
};
class Solution{
public:
void connect(TreeLinkNode *root){
TreeLinkNode *level_head=root;
while (level_head){
TreeLinkNode *cur=NULL;
TreeLinkNode *pre=NULL;
TreeLinkNode *next_level_head=NULL;
while (level_head && !level_head->left && !level_head->right){
level_head=level_head->next;
}
if (level_head){
next_level_head=level_head->left?level_head->left:level_head->right;
cur=level_head;
pre=next_level_head;
if (cur->left && cur->right){
pre->next=cur->right;
pre=pre->next;
}
cur=cur->next;
}
while (cur){
if (cur->left){
pre->next=cur->left;
pre=pre->next;
}
if (cur->right){
pre->next=cur->right;
pre=pre->next;
}
cur=cur->next;
}
level_head=next_level_head;
}
}
};
int main(int argc, char **argv){
TreeLinkNode *arr[8];
for (int i=0; i<8; ++i){
arr[i]=new TreeLinkNode(i);
}
arr[0]->left=arr[1]; arr[0]->right=arr[2];
arr[1]->left=arr[3]; arr[1]->right=arr[4];
arr[2]->left=NULL; arr[2]->right=arr[6];
Solution s;
s.connect(arr[0]);
for (TreeLinkNode *i=arr[0]; i; i=i->left){
for (TreeLinkNode *j=i; j; j=j->next){
printf("%d ", j->val);
}
printf("\n");
}
for (int i=0; i<8; ++i){
delete arr[i];
}
return 0;
}
| true |
78de6d2eb760663db316fbafe57b6a93a1ce1557 | C++ | Tegon-McCloud/J3D | /J3D/Buffer.cpp | UTF-8 | 1,477 | 2.703125 | 3 | [] | no_license | #include "Buffer.h"
#include "Graphics.h"
Buffer::Buffer(
Graphics& gfx,
const void* data,
size_t size,
D3D11_USAGE usage,
uint32_t bindFlags,
uint32_t cpuAccessFlags,
uint32_t miscFlags,
size_t structureSize) {
D3D11_BUFFER_DESC desc;
desc.ByteWidth = static_cast<UINT>(size);
desc.Usage = usage;
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = cpuAccessFlags;
desc.MiscFlags = miscFlags;
desc.StructureByteStride = static_cast<UINT>(structureSize);
D3D11_SUBRESOURCE_DATA subDesc;
subDesc.pSysMem = data;
subDesc.SysMemPitch = 0;
subDesc.SysMemSlicePitch = 0;
tif(gfx.getDevice().CreateBuffer(&desc, &subDesc, &pBuffer));
}
Buffer::Buffer(
Graphics& gfx,
const std::vector<std::byte>& data,
D3D11_USAGE usage,
uint32_t bindFlags,
uint32_t cpuAccessFlags,
uint32_t miscFlags,
size_t structureSize) :
Buffer(gfx, data.data(), data.size(), usage, bindFlags, cpuAccessFlags, miscFlags, structureSize) {}
Buffer::Buffer(
Graphics& gfx,
size_t size,
D3D11_USAGE usage,
uint32_t bindFlags,
uint32_t cpuAccessFlags,
uint32_t miscFlags,
size_t structureSize) {
D3D11_BUFFER_DESC desc;
desc.ByteWidth = static_cast<UINT>(size);
desc.Usage = usage;
desc.BindFlags = bindFlags;
desc.CPUAccessFlags = cpuAccessFlags;
desc.MiscFlags = miscFlags;
desc.StructureByteStride = static_cast<UINT>(structureSize);
tif(gfx.getDevice().CreateBuffer(&desc, nullptr, &pBuffer));
}
ID3D11Buffer* Buffer::get() const {
return pBuffer.Get();
}
| true |
ffa48e8ed32c2cc06f0787a1e79d8d8f40a6818f | C++ | MayTzadoky/Election-System | /Project1_C++/Address.cpp | UTF-8 | 1,015 | 3.671875 | 4 | [] | no_license |
#include <iostream>
using namespace std;
#include "Address.h"
//c'tor
Address::Address(const string& city, const string& street, int num)
{
setCity(city);
setStreet(street);
setNum(num);
}
//Gets city for the address
const string& Address::getCity() const
{
return city;
}
//Gets street for the address
const string& Address::getStreet() const
{
return street;
}
//Gets apartment number for the address
int Address::getNum() const
{
return num;
}
//Updates the city
bool Address::setCity(const string& city)
{
this->city = city;
return true;
}
//Updates the street
bool Address::setStreet(const string& street)
{
this->street =street;
return true;
}
//Updates the apratment number
bool Address::setNum(int tmpNum)
{
if (tmpNum > 0)
{
num = tmpNum;
return true;
}
else
return false;
}
//Print the address
ostream& operator<<(ostream& os, const Address& address)
{
os << ", city: " << address.city << ", street: " << address.street << ", number: " << address.num << endl;
return os;
} | true |
c63c76f558f48b829824737b8f8bc591be36324d | C++ | ingemar100/DungeonsAndCrawlers | /GameObject.h | UTF-8 | 545 | 2.578125 | 3 | [] | no_license | #pragma once
#include <string>
#include "Held.h"
class GameObject
{
public:
GameObject();
~GameObject();
enum gameObjecten
{
WAPEN, ETEN, KLEDING
};
std::string naam() { return _naam; };
int getStrength() { return _strength; };
void setNaam(std::string naam) { _naam = naam; };
void setStrength(int strength) { _strength = strength; };
void setType(gameObjecten type) { soort = type; };
void use();
gameObjecten getType() { return soort; };
private:
std::string _naam = "";
int _strength = 0;
gameObjecten soort;
};
| true |
d27daee6bbc28ebb80752139b89d7f86de041937 | C++ | codingiam/jass | /src/jass/game_objects/intro/text.cc | UTF-8 | 2,119 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | // Copyright (c) 2015, Doru Budai. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "jass/game_objects/intro/text.h"
#include <array>
#include "jass/resources/image.h"
#include "jass/drawables/font.h"
namespace {
const std::array<const char *, 10> introText = {
" Acest joc este proiectul nostru pentru",
"cursul de grafica.",
" Sper ca va v-a face placere sa-l jucati si",
"bineintles sa ne dati o nota pe masura",
"efortului.",
" Scopul jocului este sa scapati cu nava",
"intacta din batalie.",
" ",
" Si acuma urmeaza tastele:",
" "
};
uint32_t intro_text_size(void) {
size_t size_intro_text = 0;
for (int i = 0; i < 10; i++) {
size_intro_text += strlen(introText[i]);
}
return static_cast<uint32_t>(size_intro_text);
}
} // namespace
namespace GameObjects {
namespace Intro {
Text::Text() : speed_intro_text_(10.0), size_intro_text_(intro_text_size()) {
}
Text::~Text() {
}
void Text::Start() {
this->ticks_intro_text_ = 0.0;
this->show_to_ = 0;
}
void Text::Create() {
this->font_ = std::make_shared<Drawables::Font>("resources/fonts/font.png");
this->font_->Create();
}
void Text::Update(const double dt) {
this->ticks_intro_text_ += dt;
this->position_text_ = ticks_intro_text_ / speed_intro_text_;
if (position_text_ >= 1.0) this->position_text_ = 1.0;
this->show_to_ = (uint32_t) (size_intro_text_ * position_text_);
}
void Text::Render() {
uint32_t marime = 0;
char buffer[100 + 1];
for (int i = 0; show_to_ > 0; i++) {
marime = (uint32_t) strlen(introText[i]); // introText[i].length();
if (marime > show_to_) marime = show_to_;
if (marime > 100) marime = 100;
// size_t copied = introText[i].copy(buffer, marime);
strncpy(buffer, introText[i], marime);
buffer[marime] = '\0';
show_to_ -= marime;
font_->translation(glm::vec3(40, 105 + 20 * i, 0));
font_->scale(glm::vec3(800.0 / 800.0, 600.0 / 600.0, 1.0));
font_->text(buffer);
font_->Render();
}
}
} // namespace Intro
} // namespace GameObjects
| true |
6ecf4036572f03dd2a5b39b421905b18b2dce090 | C++ | JackieZhai/ICPC_Training | /Spring_Training/ACM-ICPC/Round6/E.cpp | UTF-8 | 477 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Node{
char c;
int n;
friend bool operator < (const Node &a, const Node &b)
{
return a.n<b.n;
}
};
set<Node> num;
int n, m;
int main()
{
while(scanf("%d%d", &n, &m)!=EOF)
{
if(n==0 && m==0)
break;
num.clear();
getchar();
char buf[3];
for(int i=0; i<m; i++)
{
scanf("%s", buf);
}
}
return 0;
}
| true |
47dc30025cb576ba4ca402eef7a6cae55d5be989 | C++ | thisthat/TT-FFX-Butterfly | /TT-ControlMotor/Logger/logFile.cpp | UTF-8 | 343 | 2.828125 | 3 | [] | no_license | #include "logFile.hpp"
using namespace std;
LogFile::LogFile(string name){
_name = name;
cout << "File name: " << _name << endl;
}
void LogFile::open(){
log.open(_name);
}
void LogFile::close(){
log.close();
}
void LogFile::write(string msg){
log << formatMessage(msg);
log << "\n";
fprintf(stderr, "Message: %s\n", msg.c_str());
} | true |
d0deb45146d2dfadacf83a695ef32abf7dc33f5c | C++ | newcommander/cc | /solution1/action.cpp | UTF-8 | 3,356 | 3.078125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "action.h"
std::map<unsigned int, void*> g_actions;
extern Action action_1;
extern Action action_2;
extern Action action_3;
extern Action action_4;
static Action *online_actions[] = {
&action_1,
&action_2,
&action_3,
&action_4,
};
void show_all_actions()
{
std::map<unsigned int, void*>::iterator it;
Action *action;
for (it = g_actions.begin(); it != g_actions.end(); it++) {
action = (Action*)it->second;
std::cout << action->name << "[node=" << action->node_tag << "]" << std::endl;
}
}
static int mount_action(Json::Value &value)
{
std::map<unsigned int, void*>::iterator action_it;
Action *action;
Node *node;
unsigned int action_tag, node_tag;
if (!value.isMember("tag") || !value["tag"].isUInt() ||
!value.isMember("node_tag") || !value["node_tag"].isUInt()) {
std::cout << "Invalid action." << std::endl;
return -1;
}
action_tag = value["tag"].asUInt();
node_tag = value["node_tag"].asUInt();
action_it = g_actions.find(action_tag);
if (action_it == g_actions.end()) {
std::cout << "Cannot find action(tag=" << action_tag << ")" << std::endl;
return -1;
}
action = (Action*)action_it->second;
node = find_node_by_tag(node_tag, true);
if (!node) {
std::cout << "Cannot find node(tag=" << node_tag << ") for action(tag=" << action_tag << ")" << std::endl;
return -1;
}
action->node_tag = node_tag;
action->node = node;
node->action = action;
return 0;
}
int mount_all_actions(std::string config_file)
{
Json::Value::ArrayIndex i;
Json::Reader reader;
Json::Value root;
std::filebuf fb;
if (fb.open(config_file.c_str(), std::ios::in)) {
std::istream is(&fb);
if (!reader.parse(is, root)) {
std::cout << "Parse json data failed." << std::endl;
fb.close();
return -1;
}
fb.close();
} else {
std::cout << "Open file "<< config_file << " failed.\n" << std::endl;
return -1;
}
if (!root.isArray()) {
std::cout << config_file << ": Json data in file must be an Array." << std::endl;
return -1;
}
for (i = 0; i < root.size(); i++) {
if (mount_action(root[i]) < 0)
std::cout << "mount #" << i << " action failed." << std::endl;
}
return 0;
}
static void add_action(Action *action)
{
g_actions.insert(KV(action->tag, action));
}
int save_action_mount_config(std::string config_file)
{
std::map<unsigned int, void*>::iterator it;
Json::Value root, value;
Json::FastWriter writer;
std::ofstream outfile;
Action *action;
for (it = g_actions.begin(); it != g_actions.end(); it++) {
value.clear();
action = (Action*)it->second;
value["tag"] = action->tag;
value["node_tag"] = action->node_tag;
root.append(value);
}
outfile.open(config_file.c_str(), std::ofstream::out);
outfile << writer.write(root);
outfile.flush();
outfile.close();
return 0;
}
void clear_all_actions()
{
g_actions.clear();
}
void load_actions()
{
size_t i;
g_actions.clear();
for (i = 0; i < ARRAY_SIZE(online_actions); i++)
add_action(online_actions[i]);
}
| true |
dd2342119f348f8aebd0dfa02c26e12628c90f9f | C++ | JuicyJerry/mincoding | /(훈련반2) Level28.5 - 문제1번.cpp | UTF-8 | 890 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
struct Node {
char chr;
int vect;
};
int n;
void getNameArrange(Node t[10]) {
char temp, temp1;
for (int y = 0; y < n; y++) {
for (int x = 0; x < n; x++) {
if (t[y].chr < t[x].chr) {
temp = t[x].chr;
temp1 = t[x].vect;
t[x].chr = t[y].chr;
t[x].vect = t[y].vect;
t[y].chr = temp;
t[y].vect = temp1;
}
}
}
for (int y = 0; y < n; y++) {
for (int x = 0; x < n; x++) {
if (t[y].chr == t[x].chr && t[y].vect < t[x].vect) {
temp = t[x].chr;
temp1 = t[x].vect;
t[x].chr = t[y].chr;
t[x].vect = t[y].vect;
t[y].chr = temp;
t[y].vect = temp1;
}
}
}
}
int main() {
cin >> n;
Node t[10];
for (int i = 0; i < n; i++) {
cin >> t[i].chr;
cin >> t[i].vect;
}
getNameArrange(t);
for (int i = 0; i < n; i++) {
cout << t[i].chr << " " << t[i].vect << endl;
}
return 0;
} | true |
8e3967fab3a7918c55921a533d5d8b964ced1399 | C++ | mtalluto/WatershedTools | /src/hydrology.cpp | UTF-8 | 2,482 | 3.203125 | 3 | [
"MIT"
] | permissive | #include <Rcpp.h>
using namespace Rcpp;
//' Connect points in a watershed, accumulating a value as we go
//'
//' The values and ds pixels should match; i.e., values[i] is the value for pixel i,
//' and dsPixel[i] is that pixel's downstream pixel
//'
//' @param dsPixel A vector of downstream pixels, diPixel[i] is downstream from pixel i
//' @param upstream The id of the upstream point
//' @param downstream The id of the downstream point
//' @param value A vector of values to accumulate
//' @return A list, the first entry is the connected pixels, the second the accumulation
//' up to (but excluding) each pixel
// [[Rcpp::export]]
List connectCPP(NumericVector dsPixel, int upstream, int downstream,
NumericVector value) {
std::vector<int> connectedPts;
std::vector<double> distance;
double accum = 0.0;
int current = upstream;
connectedPts.push_back(current);
distance.push_back(accum);
while(current != downstream && !Rcpp::NumericVector::is_na(current)) {
accum += value(current - 1);
current = dsPixel(current - 1); // -1 to correct for C++ indexing
connectedPts.push_back(current);
distance.push_back(accum);
}
if(Rcpp::NumericVector::is_na(current) && !Rcpp::NumericVector::is_na(dsPixel(downstream))) {
connectedPts.clear();
distance.clear();
}
return Rcpp::List::create(connectedPts, distance);
}
//' Construct a distance matrix between one set of points and another
//'
//' @param x Set of pixels to which to compute distance
//' @param diPixel A vector of downstream pixels, diPixel[i] is downstream from pixel i
//' @param nx The total number of pixels in the network
//' @param value The value to be added (e.g., length) when computing distance
//' @return A matrix with dimensions `length(x)` by `nrow(ws)`
// [[Rcpp::export]]
NumericMatrix dmat(NumericVector x, NumericVector dsPixel, int nx, NumericVector value) {
NumericMatrix distance(x.size(), nx);
std::fill(distance.begin(), distance.end(), NumericVector::get_na());
int count = 0;
for(int xi = 0; xi < x.size(); ++xi) {
int i = (int) x[xi] - 1; // -1 to correct for C++ indexing
int j = i;
double total = 0;
distance(xi, j) = total;
while(j > 0) {
total += value(j);
j = (int) dsPixel(j) - 1;
distance(xi, j) = total;
NumericVector::iterator inx = std::find(x.begin(), x.end(), j);
if(inx != x.end())
distance(inx - x.begin(), xi) = -1 * total;
count++;
if(count > nx*x.size())
stop("Topology error");
}
}
return distance;
}
| true |
6a39a2b9933b5d5fdf26501ae25b6b8d06099cae | C++ | indrajeetpala19/Codeforces | /1030A.cpp | UTF-8 | 296 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int a;
cin>>a;
if(a==1)
{
cout<<"HARD"<<endl;
return 0;
}
}
cout<<"EASY"<<endl;
return 0;
}
| true |
2268764df421b713fe50592bd31fa5b86ec3ef81 | C++ | EdvinAlvarado/Code-Wars | /deleteNth.cpp | UTF-8 | 509 | 3.5625 | 4 | [
"BSD-2-Clause"
] | permissive | #include <vector>
#include <iostream>
#include <map>
using namespace std;
std::vector<int> deleteNth(std::vector<int> arr, int n)
{
std::map<int, int> counter;
std::vector<int> v;
for (const int& i: arr) {
// if (counter.find(i) == counter.end()) { // not in map
// counter[i] = 1;
// v.push_back(i);
// }
if (counter[i]++ < n) {
v.push_back(i);
}
}
return v;
}
int main()
{
auto vec = deleteNth({20,37,20,21}, 1);
for (const auto& n: vec) {
cout << n << " ";
}
cout << endl;
} | true |
06c82979be921bcd3f440d1c8e197cf1a8fc812f | C++ | rakhils/SpecialTopic | /Engine/Code/Engine/Math/Frustum.cpp | UTF-8 | 2,653 | 2.75 | 3 | [] | no_license | #include "Engine/Math/Frustum.hpp"
#include "Engine/Math/Matrix44.hpp"
#include "Engine/Math/AABB3.hpp"
// CONSTRUCTOR
Frustum::Frustum()
{
}
// DESTRUCTOR
Frustum::~Frustum()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*DATE : 2018/06/12
*@purpose : Check if frustrom contains the point
*@param : Given point
*@return : True if point is inside frustrum else false
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Frustum::DoContainPoint(Vector3 point)
{
for(int i = 0;i < 6;i++)
{
if(!m_planes[i].IsInFront(point))
{
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*DATE : 2018/06/17
*@purpose : Creates frustum from matrix
*@param : Given matrix
*@return : NIL
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Frustum Frustum::FromMatrix(Matrix44 matrix)
{
AABB3 ndc = AABB3::Center(Vector3::ZERO, Vector3(2.0f));
Vector3 corners[8];
ndc.GetCorners(corners);
matrix.Inverse();
Vector3 world_corners[8];
for (int cornerIndex = 0; cornerIndex < 8; cornerIndex++)
{
Vector4 ndc_pos = Vector4(corners[cornerIndex], 1);
Vector4 kinda_world_pos = ndc_pos * matrix;
world_corners[cornerIndex] = kinda_world_pos.XYZ() / kinda_world_pos.w;
}
Frustum frustum;
frustum.m_left = Plane(world_corners[0], world_corners[4], world_corners[2]);
frustum.m_right = Plane(world_corners[5], world_corners[1], world_corners[3]);
frustum.m_bottom = Plane(world_corners[0], world_corners[1], world_corners[5]);
frustum.m_top = Plane(world_corners[2], world_corners[6], world_corners[7]);
frustum.m_back = Plane(world_corners[4], world_corners[5], world_corners[6]);
frustum.m_front = Plane(world_corners[1], world_corners[0], world_corners[2]);
return frustum;
}*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*DATE : 2018/06/12
*@purpose : NIL
*@param : NIL
*@return : NIL
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Frustum Frustum::FromMatrix(Matrix44 mat)
{
/ *AABB3 ndc = AABB3(Vector3 ZER0, 1, 1);
Vector3 corners[8];
ndc.GetCorners(corners);
Matrix44 inverse = mat.Inverse();* /
}*/
| true |
29e0a535c0d32de1b28c7a0026edcb3f3353ef6b | C++ | juffson/nacos-sdk-cpp | /include/ResourceGuard.h | UTF-8 | 483 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by liuhanyu on 2020/9/6.
//
#ifndef NACOS_SDK_CPP_RESOURCEGUARD_H
#define NACOS_SDK_CPP_RESOURCEGUARD_H
namespace nacos{
template<typename T>
class ResourceGuard {
private:
T *_obj;//The object being watched
ResourceGuard();
public:
ResourceGuard(T *obj) { _obj = obj; };
~ResourceGuard() {
if (_obj != NULL) {
delete _obj;
_obj = NULL;
}
};
};
}//namespace nacos
#endif //NACOS_SDK_CPP_RESOURCEGUARD_H
| true |
3cb4b43302e66aa55520fa873caa20cd99417950 | C++ | tthsqe12/cas | /lint/source/headers/generic/generic_mpoly_mul_divides.h | UTF-8 | 16,493 | 3.0625 | 3 | [] | no_license | #pragma once
//////////////////////////////// heaps /////////////////////////////////////////
// a chain of nodes with the same exponent
struct mpoly_heap_chain
{
ulimb i, j;
mpoly_heap_chain* next;
};
/*
The heap can either store the exponents (of size ML) directly in the
mpoly_heap_entry_imm. Since these are shuffled while sorting, at some point
it is more efficient to store pointers as in mpoly_heap_entry_ptr and just
shuffle the pointers.
*/
template <ulimb ML>
struct mpoly_heap_entry_imm {
static_assert(ML > 0);
ulimb exp[ML];
mpoly_heap_chain* next;
};
struct mpoly_heap_entry_ptr {
ulimb* exp;
mpoly_heap_chain* next;
};
#define HEAP_LEFT(i) (2*(i))
#define HEAP_RIGHT(i) (2*(i) + 1)
#define HEAP_PARENT(i) ((i)/2)
// using mpoly_heap_entry_imm for small ML
template <bool MP, ulimb ML>
struct mpoly_heap {
ulimb next_loc;
ulimb heap_len; /* heap zero index unused */
mpoly_heap_entry_imm<ML>* heap;
mpoly_heap_chain* chain;
ulimb* store, * store_base;
ulimb* ind;
bool is_empty() {return heap_len <= 1;}
ulimb* top_exp() {
FLINT_ASSERT(!is_empty());
return heap[1].exp;
}
mpoly_heap(ulimb Blen, ulimb M, tmp_allocator& push)
{
FLINT_ASSERT(Blen > 0);
next_loc = Blen + 4; /* something bigger than heap can ever be */
heap = push.recursive_alloc<mpoly_heap_entry_imm<ML>>(Blen + 1);
chain = push.recursive_alloc<mpoly_heap_chain>(Blen);
store = store_base = push.recursive_alloc<ulimb>(2*Blen);
ind = push.recursive_alloc<ulimb>(Blen + 2);
ind += 1;
ind[-1] = ind[Blen] = UWORD_MAX;
for (ulimb i = 0; i < Blen; i++)
ind[i] = 1;
/* start with no heap nodes */
heap_len = 1;
}
void start_mul(const ulimb* Bexps, const ulimb* Cexps, ulimb M)
{
mpoly_heap_chain* x = chain + 0;
x->i = 0;
x->j = 0;
x->next = NULL;
heap[1].next = x;
mpoly_monomial_add<MP, ML>(heap[1].exp, Bexps + M*0, Cexps + M*0, M);
ind[0] = 2*1 + 0;
heap_len = 2;
}
void start_div(const ulimb* Aexps, ulimb M)
{
mpoly_heap_chain* x = chain + 0;
x->i = -ulimb(1);
x->j = 0;
x->next = NULL;
heap[1].next = x;
mpoly_monomial_set<ML>(heap[1].exp, Aexps, M);
heap_len = 2;
ind[0] = UWORD_MAX;
}
mpoly_heap_chain* pop(ulimb M)
{
mpoly_heap_chain* x = heap[1].next;
ulimb i = 1, j = 2, s = --heap_len;
while (j < s) {
j += !mpoly_monomial_gt<ML>(heap[j].exp, heap[j + 1].exp, M);
heap[i] = heap[j];
i = j;
j = HEAP_LEFT(j);
}
// insert last element into heap[i]
ulimb exp[ML];
mpoly_monomial_set<ML>(exp, heap[s].exp, M);
j = HEAP_PARENT(i);
while (i > 1 && mpoly_monomial_gt<ML>(exp, heap[j].exp, M)) {
heap[i] = heap[j];
i = j;
j = HEAP_PARENT(j);
}
heap[i] = heap[s];
return x;
}
void insert(mpoly_heap_chain* x, ulimb* exp, ulimb M)
{
ulimb i = heap_len, j, n = heap_len;
if (i != 1 && mpoly_monomial_equal<ML>(exp, heap[1].exp, M)) {
x->next = heap[1].next;
heap[1].next = x;
return;
}
if (next_loc < heap_len && mpoly_monomial_equal<ML>(exp, heap[next_loc].exp, M)) {
x->next = heap[next_loc].next;
heap[next_loc].next = x;
return;
}
while ((j = HEAP_PARENT(i)) >= 1) {
int cmp = mpoly_monomial_cmp<ML>(exp, heap[j].exp, M);
if (cmp == 0) {
x->next = heap[j].next;
heap[j].next = x;
next_loc = j;
return;
} else if (cmp > 0) {
i = j;
} else {
break;
}
}
heap_len++;
while (n > i) {
heap[n] = heap[HEAP_PARENT(n)];
n = HEAP_PARENT(n);
}
mpoly_monomial_set<ML>(heap[i].exp, exp, M);
heap[i].next = x;
}
void insert_mul(const ulimb* Bexps, ulimb ii, const ulimb* Cexps, ulimb jj, ulimb M)
{
mpoly_heap_chain* x = chain + ii;
x->next = nullptr;
x->i = ii;
x->j = jj;
ind[x->i] = 2*(x->j + 1) + 0;
ulimb exp[ML];
mpoly_monomial_add<MP, ML>(exp, Bexps + M*x->i, Cexps + M*x->j, M);
insert(x, exp, M);
}
void insert_div(const ulimb* Aexps, ulimb ii, ulimb jj, ulimb M)
{
mpoly_heap_chain* x = chain + 0;
x->next = nullptr;
x->i = ii;
x->j = jj;
ind[x->i] = 2*(x->j + 1) + 0;
ulimb exp[ML];
mpoly_monomial_set<ML>(exp, Aexps + M*x->j, M);
insert(x, exp, M);
}
void process_store_mul(const ulimb* Bexps, const ulimb* Cexps, ulimb Clen, ulimb M);
ulimb process_store_div(const ulimb* Aexps, ulimb Alen, const ulimb* Bexps, const ulimb* Qexps, ulimb Qi, ulimb M);
};
// using mpoly_heap_entry_ptr for general M
#define ML 0
template <bool MP>
struct mpoly_heap<MP, ML> {
ulimb next_loc;
ulimb heap_len; /* heap zero index unused */
mpoly_heap_entry_ptr* heap;
mpoly_heap_chain* chain;
ulimb* store, * store_base;
ulimb* exps;
ulimb** exp_list;
ulimb exp_next;
ulimb* ind;
bool is_empty() {return heap_len <= 1;}
ulimb* top_exp() {
FLINT_ASSERT(!is_empty());
return heap[1].exp;
}
mpoly_heap(ulimb Blen, ulimb M, tmp_allocator& push)
{
FLINT_ASSERT(Blen > 0);
next_loc = Blen + 4; // something bigger than heap can ever be
heap = push.recursive_alloc<mpoly_heap_entry_ptr>(Blen + 1);
chain = push.recursive_alloc<mpoly_heap_chain>(Blen);
store = store_base = push.recursive_alloc<ulimb>(2*Blen);
exps = push.recursive_alloc<ulimb>(Blen*M);
exp_list = push.recursive_alloc<ulimb*>(Blen);
ind = push.recursive_alloc<ulimb>(Blen + 2);
ind += 1;
ind[-1] = ind[Blen] = UWORD_MAX;
for (ulimb i = 0; i < Blen; i++)
{
exp_list[i] = exps + M*i;
ind[i] = 1;
}
// start with no heap nodes and no exponent vectors in use
exp_next = 0;
heap_len = 1;
}
void start_mul(const ulimb* Bexps, const ulimb* Cexps, ulimb M)
{
mpoly_heap_chain* x = chain + 0;
x->i = 0;
x->j = 0;
x->next = NULL;
heap[1].next = x;
heap[1].exp = exp_list[exp_next++];
mpoly_monomial_add<MP, ML>(heap[1].exp, Bexps + M*0, Cexps + M*0, M);
ind[0] = 2*1 + 0;
heap_len = 2;
}
void start_div(const ulimb* Aexps, ulimb M)
{
mpoly_heap_chain* x = chain + 0;
x->i = -ulimb(1);
x->j = 0;
x->next = NULL;
heap[1].next = x;
heap[1].exp = exp_list[exp_next++];
mpoly_monomial_set<ML>(heap[1].exp, Aexps, M);
heap_len = 2;
ind[0] = UWORD_MAX;
}
mpoly_heap_chain* pop(ulimb M)
{
exp_list[--exp_next] = heap[1].exp;
mpoly_heap_chain* x = heap[1].next;
ulimb i = 1, j = 2, s = --heap_len;
while (j < s) {
j += !mpoly_monomial_gt<ML>(heap[j].exp, heap[j + 1].exp, M);
heap[i] = heap[j];
i = j;
j = HEAP_LEFT(j);
}
// insert last element into heap[i]
ulimb* exp = heap[s].exp;
j = HEAP_PARENT(i);
while (i > 1 && mpoly_monomial_gt<ML>(exp, heap[j].exp, M)) {
heap[i] = heap[j];
i = j;
j = HEAP_PARENT(j);
}
heap[i] = heap[s];
return x;
}
void insert(mpoly_heap_chain* x, ulimb* exp, ulimb M)
{
ulimb i = heap_len, j, n = heap_len;
if (i != 1 && mpoly_monomial_equal<ML>(exp, heap[1].exp, M)) {
x->next = heap[1].next;
heap[1].next = x;
return;
}
if (next_loc < heap_len && mpoly_monomial_equal<ML>(exp, heap[next_loc].exp, M)) {
x->next = heap[next_loc].next;
heap[next_loc].next = x;
return;
}
while ((j = HEAP_PARENT(i)) >= 1) {
if (!mpoly_monomial_gt<ML>(exp, heap[j].exp, M))
break;
i = j;
}
if (j >= 1 && mpoly_monomial_equal<ML>(exp, heap[j].exp, M)) {
x->next = heap[j].next;
heap[j].next = x;
next_loc = j;
return;
}
heap_len++;
while (n > i) {
heap[n] = heap[HEAP_PARENT(n)];
n = HEAP_PARENT(n);
}
heap[i].exp = exp;
heap[i].next = x;
exp_next++;
}
void insert_mul(const ulimb* Bexps, ulimb ii, const ulimb* Cexps, ulimb jj, ulimb M)
{
mpoly_heap_chain* x = chain + ii;
x->next = nullptr;
x->i = ii;
x->j = jj;
ind[x->i] = 2*(x->j + 1) + 0;
ulimb* exp = exp_list[exp_next];
mpoly_monomial_add<MP, ML>(exp, Bexps + M*x->i, Cexps + M*x->j, M);
insert(x, exp, M);
}
void insert_div(const ulimb* Aexps, ulimb ii, ulimb jj, ulimb M)
{
mpoly_heap_chain* x = chain + 0;
x->next = nullptr;
x->i = ii;
x->j = jj;
ind[x->i] = 2*(x->j + 1) + 0;
ulimb* exp = exp_list[exp_next];
mpoly_monomial_set<ML>(exp, Aexps + M*x->j, M);
insert(x, exp, M);
}
void process_store_mul(const ulimb* Bexps, const ulimb* Cexps, ulimb Clen, ulimb M);
ulimb process_store_div(const ulimb* Aexps, ulimb Alen, const ulimb* Bexps, const ulimb* Qexps, ulimb Qi, ulimb M);
};
#undef ML
#undef HEAP_LEFT
#undef HEAP_RIGHT
#undef HEAP_PARENT
template <bool MP, ulimb ML>
void mpoly_heap<MP, ML>::process_store_mul(const ulimb* Bexps, const ulimb* Cexps, ulimb Clen, ulimb M)
{
while (store > store_base) {
ulimb j = *--store;
ulimb i = *--store;
// we have ind[-1] == UWORD_MAX and ind[Blen] == UWORD_MAX;
// should we go right?
if (ind[i + 1] == 2*j + 1)
insert_mul(Bexps, i + 1, Cexps, j, M);
// should we go up? */
if (j + 1 < Clen && is_odd(ind[i]) && ind[i - 1] >= 2*j + 5)
insert_mul(Bexps, i, Cexps, j + 1, M);
}
}
// TODO why must this be coppied with ML=0?
template <bool MP>
void mpoly_heap<MP, 0>::process_store_mul(const ulimb* Bexps, const ulimb* Cexps, ulimb Clen, ulimb M)
{
while (store > store_base) {
ulimb j = *--store;
ulimb i = *--store;
if (ind[i + 1] == 2*j + 1)
insert_mul(Bexps, i + 1, Cexps, j, M);
if (j + 1 < Clen && is_odd(ind[i]) && ind[i - 1] >= 2*j + 5)
insert_mul(Bexps, i, Cexps, j + 1, M);
}
}
template <bool MP, ulimb ML>
ulimb mpoly_heap<MP, ML>::process_store_div(const ulimb* Aexps, ulimb Alen, const ulimb* Bexps, const ulimb* Qexps, ulimb Qi, ulimb M)
{
ulimb s = 0;
while (store > store_base)
{
ulimb j = *--store;
ulimb i = *--store;
// FLINT_ASSERT(ind[0] == UWORD_MAX && ind[Blen] == UWORD_MAX);
if (i + 1 == 0) {
// take next dividend term
if (j + 1 < Alen)
insert_div(Aexps, i, j + 1, M);
} else {
// FLINT_ASSERT(0 < i && i < Blen);
// should we go right?
if (ind[i + 1] == 2*j + 1)
insert_mul(Bexps, i + 1, Qexps, j, M);
// should we go up?
if (j + 1 == Qi)
s++;
else if (is_odd(ind[i]) && ind[i - 1] >= 2*j + 5)
insert_mul(Bexps, i, Qexps, j + 1, M);
}
}
return s;
}
// TODO ditto
template <bool MP>
ulimb mpoly_heap<MP, 0>::process_store_div(const ulimb* Aexps, ulimb Alen, const ulimb* Bexps, const ulimb* Qexps, ulimb Qi, ulimb M)
{
ulimb s = 0;
while (store > store_base)
{
ulimb j = *--store;
ulimb i = *--store;
if (i + 1 == 0) {
if (j + 1 < Alen)
insert_div(Aexps, i, j + 1, M);
} else {
if (ind[i + 1] == 2*j + 1)
insert_mul(Bexps, i + 1, Qexps, j, M);
if (j + 1 == Qi)
s++;
else if (is_odd(ind[i]) && ind[i - 1] >= 2*j + 5)
insert_mul(Bexps, i, Qexps, j + 1, M);
}
}
return s;
}
template <bool MP = true, ulimb ML = 0, typename RingT, typename MPolyT>
void _generic_mpoly_mul_heap(
mpoly_ctx& ctxm, RingT& ctxc,
MPolyT& A,
typename MPolyT::input_t B,
typename MPolyT::input_t C,
tmp_allocator& push)
{
FLINT_ASSERT(B.len > 0);
FLINT_ASSERT(C.len > 0);
ulimb M = ctxm.stride(A.bits());
ulimb N = ctxc.stride();
mpoly_heap<MP, ML> H(B.len, M, push);
typename RingT::dotter_t dotter(ctxc);
H.start_mul(B.exps, C.exps, M);
ulimb Ai = 0;
while (!H.is_empty())
{
ulimb* Aexps = A.m.fit_alloc(M*(Ai + 1));
mpoly_monomial_set<ML>(Aexps + M*Ai, H.top_exp(), M);
dotter.zero(ctxc);
do {
auto x = H.pop(M);
do {
FLINT_ASSERT(x->i < B.len); FLINT_ASSERT(x->j < C.len);
H.ind[x->i] |= 1;
*H.store++ = x->i;
*H.store++ = x->j;
dotter.madd(ctxc, B.coeffs + N*x->i, C.coeffs + N*x->j);
} while ((x = x->next) != nullptr);
} while (!H.is_empty() && mpoly_monomial_equal<ML>(H.top_exp(), Aexps + M*Ai, M));
typename RingT::coeff_t* Acoeffs = A.c.fit_alloc(N*(Ai + 1));
dotter.reduce(ctxc, Acoeffs + N*Ai);
Ai += !is_zero(ctxc, Acoeffs + N*Ai);
H.process_store_mul(B.exps, C.exps, C.len, M);
}
A.set_length(Ai);
}
template <bool MP = true, ulimb ML = 0, typename RingT, typename MPolyT>
bool _generic_mpoly_divides_heap(
mpoly_ctx& ctxm, RingT& ctxc,
MPolyT& Q,
typename MPolyT::input_t A,
typename MPolyT::input_t B,
tmp_allocator& push)
{
FLINT_ASSERT(!MP || (Q.bits()%FLINT_BITS == 0));
FLINT_ASSERT(A.len > 0);
FLINT_ASSERT(B.len > 0);
ulimb M = ctxm.stride(Q.bits());
ulimb N = ctxc.stride();
mpoly_heap<MP, ML> H(B.len, M, push);
typename RingT::dotter_t dotter(ctxc);
typename RingT::divider_t divider(ctxc);
ulimb s = B.len; // number of terms * (latest quotient) we should put into heap
ulimb mask = ctxm.overflow_mask<MP>(Q.bits());
divider.set_divisor(ctxc, B.coeffs + N*0, true); // can throw
H.start_div(A.exps, M);
ulimb Qi = 0;
while (!H.is_empty())
{
ulimb* Qexps = Q.m.fit_alloc(M*(Qi + 2));
ulimb* texp = Qexps + M*(Qi + 1); // use next for tmp space
if (mpoly_monomial_set_overflowed<MP, ML>(texp, H.top_exp(), M, mask))
goto not_exact_division;
bool lm_not_divides = mpoly_monomial_sub_overflowed<MP, MP>(Qexps + M*Qi, H.top_exp(), B.exps + M*0, M, mask);
typename RingT::coeff_t* Qcoeffs = Q.c.fit_alloc(N*(Qi + 1));
dotter.zero(ctxc);
do {
auto x = H.pop(M);
do {
*H.store++ = x->i;
*H.store++ = x->j;
if (x->i + 1 == 0) {
FLINT_ASSERT(x->j < A.len);
dotter.sub(ctxc, A.coeffs + N*x->j);
} else {
FLINT_ASSERT(0 < x->i && x->i < B.len && x->j < Qi);
H.ind[x->i] |= 1;
dotter.madd(ctxc, B.coeffs + N*x->i, Qcoeffs + N*x->j);
}
} while ((x = x->next) != NULL);
} while (!H.is_empty() && mpoly_monomial_equal(H.top_exp(), texp, M));
dotter.reduce(ctxc, Qcoeffs + N*Qi);
s += H.process_store_div(A.exps, A.len, B.exps, Qexps, Qi, M);
if (!divider.divides(ctxc, Qcoeffs + N*Qi, Qcoeffs + N*Qi))
goto not_exact_division;
if (is_zero(ctxc, Qcoeffs + N*Qi))
continue;
if (lm_not_divides)
goto not_exact_division;
/* put newly generated quotient term back into the heap if neccesary */
if (s > 1)
H.insert_mul(B.exps, 1, Qexps, Qi, M);
s = 1;
Qi++;
}
Q.set_length(Qi);
return true;
not_exact_division:
Q.set_length(0);
return false;
}
| true |
9229d7cee25b7745135d7b0dac3564f009dd063a | C++ | niuxu18/logTracker-old | /second/download/git/gumtree/git_repos_function_5503_git-2.2.3.cpp | UTF-8 | 544 | 2.546875 | 3 | [] | no_license | static int is_dir_empty(const wchar_t *wpath)
{
WIN32_FIND_DATAW findbuf;
HANDLE handle;
wchar_t wbuf[MAX_PATH + 2];
wcscpy(wbuf, wpath);
wcscat(wbuf, L"\\*");
handle = FindFirstFileW(wbuf, &findbuf);
if (handle == INVALID_HANDLE_VALUE)
return GetLastError() == ERROR_NO_MORE_FILES;
while (!wcscmp(findbuf.cFileName, L".") ||
!wcscmp(findbuf.cFileName, L".."))
if (!FindNextFileW(handle, &findbuf)) {
DWORD err = GetLastError();
FindClose(handle);
return err == ERROR_NO_MORE_FILES;
}
FindClose(handle);
return 0;
} | true |
7d89dad2e639bf8493c5cb8185387f8bbfcf58c1 | C++ | steam228/GROUU | /ARCHIVE/arduino/GROUU_GREENHOUSE_0/PROBE_MF/PROBE_MF.ino | UTF-8 | 3,422 | 2.515625 | 3 | [
"CC-BY-4.0"
] | permissive |
#include "DHT.h"
#include "OneWire.h"
#include "math.h"
//#include <Wire.h>
#include "floatToString.h"
//Sensors location
#define DHTPIN 4
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
int ledPin = 13;
int moistPin = A0;
int wetPin = A1;
int lumPin = A2;
//int phPin = A3;
int soiltempPin = 5;
OneWire ds(soiltempPin);
//Variables
float h = 0;
float t = 0;
float l = 0;
int m = 0;
int w = 0;
int pH = 0;
float sT = 0;
//Analog calibration Values for Maping (input here)
int mMax=600;
int mMin=0;
int wMax=1013;
int wMin=100;
float lMax=1023/2;
int lMin=0;
// int pHMax=1023;
// int pHMin=0;
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
// Wire.begin();
pinMode (ledPin, OUTPUT);
}
void loop() {
//Reading Sensores
h = dht.readHumidity();
t = dht.readTemperature();
l = analogRead(lumPin);
m = analogRead(moistPin);
w = analogRead(wetPin);
// pH = analogRead(phPin);
sT = getTemp();
//Converting Units
//l = map(l,lMin,lMax,3,70000);
l = exp(0.02463*l-0.5522);
m = map(m,mMin,mMax,0,100);
w = map(w,wMin,wMax,100,0);
// int ph = map(pH, pHMin, pHMax,0,7);
// check if returns are valid, if they are NaN (not a number) then something went wrong!
// if (isnan(t) || isnan(h) {
// Serial.println("Failed to read from DHT");
// } else {
Serial.print("Relative Humidity: ");
Serial.println(h);
Serial.print("Temperature: ");
Serial.println(t);
Serial.print("Luminosity: ");
Serial.println(l);
Serial.print("Moisture: ");
Serial.println(m);
Serial.print("Soil Temperature: ");
// Serial.print(pH);
// Serial.print("%s/");
Serial.println(sT);
Serial.print("Leaf Wetness: ");
Serial.println(w);
Serial.println("///////////////////////////////");
Serial.println("///////////////////////////////");
// Wire.beginTransmission(4); // transmit to device #4
// Wire.write("floatToString(buffer,h,5);");
// Wire.write("floatToString(buffer,t,5);");
// Wire.write("floatToString(buffer,l,5);");
// Wire.write("floatToString(buffer,m,5);");
// Wire.write("floatToString(buffer,sT,5);");
// Wire.write("floatToString(buffer,w,5);");
// Wire.endTransmission(); // stop transmitting
if (t < 20) {
digitalWrite (ledPin, HIGH);
}
else {
digitalWrite (ledPin, LOW);
}
delay(4000);
// }
}
float getTemp(){
//returns the temperature from one DS18S20 in DEG Celsius
byte data[12];
byte addr[8];
if ( !ds.search(addr)) {
//no more sensors on chain, reset search
ds.reset_search();
return -1000;
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return -1000;
}
if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial.print("Device is not recognized");
return -1000;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
ds.reset_search();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); //using two's compliment
float TemperatureSum = tempRead / 16;
return TemperatureSum;
}
| true |
aa7c310c078f239b21c2bd650f56e46bafff0766 | C++ | Millsy242/GeneticRaceEditor | /BaseProject/Tools/SprayToolType.cpp | UTF-8 | 1,164 | 2.53125 | 3 | [] | no_license | //
// SprayToolType.cpp
// GeneticRaceEditor
//
// Created by Daniel Harvey on 02/09/2019.
// Copyright © 2019 Daniel Harvey. All rights reserved.
//
#include "Tool.hpp"
#include <iostream>
#include "Canvas.hpp"
#include <vector>
void SprayToolType::OnMouseDown(sf::Vector2i MousePos, Canvas& canvas, PaintOptions &options)
{
for(int y=-options.BrushSize; y<=options.BrushSize; y++)
{
for(int x=-options.BrushSize; x<=options.BrushSize; x++)
{
int actualX = MousePos.x + x;
int actualY = MousePos.y + y;
int dx = std::abs(MousePos.x - actualX);
int dy = std::abs(MousePos.y - actualY);
int randomnum = rand()%100;
if(std::sqrt(dx * dx + dy * dy) <= options.BrushSize && randomnum < 10)
{
canvas.SetPixel(sf::Vector2f(MousePos.x+x,MousePos.y+y), options.MainBrushColour);
}
}
}
}
void SprayToolType::OnMouseUp(sf::Vector2i MousePos, Canvas& canvas, PaintOptions &options)
{
}
void SprayToolType::OnMouseMove(sf::Vector2i MousePos, Canvas& canvas, PaintOptions &options)
{
}
| true |
1b324a4c95f12de06602125b84a58eba9ffa1993 | C++ | arielrodrigues/sOS-Sim | /FileManager.h | UTF-8 | 1,365 | 3.0625 | 3 | [] | no_license | #ifndef SIMPLE_OS_SIMULATOR_FILEMANAGER_H
#define SIMPLE_OS_SIMULATOR_FILEMANAGER_H
#include <sstream>
#include <fstream>
#include <iostream>
namespace FileManager {
static uint32_t numberofLines = 0;
/***
* Put the file in a stringstream
* @param filepath
* @return out (file stringstream)
*/
static std::stringstream readFile(std::string filepath) {
try {
numberofLines = 0;
std::stringstream out;
std::ifstream infile(filepath);
for (std::string line; getline(infile, line);
boost::replace_all(line, ",", " "), out << line << '\n', numberofLines++);
return out;
} catch (...) {
std::cout << "Erro ao abrir o arquivo de leitura\n";
exit(EXIT_FAILURE);
}
}
/***
* Write the stringstream content in a file
* @param filename
* @param content
* @return sucess?
*/
static bool writeFile(std::string filename, std::string content_) {
try {
std::ofstream outfile(filename);
std::stringstream content(content_);
outfile << content.str();
return true;
} catch (...) {
std::cout << "Erro ao escrever no arquivo\n";
}
return false;
}
};
#endif //SIMPLE_OS_SIMULATOR_FILEMANAGER_H
| true |
6b7b8e3f20c6593f6d5d8d7fe2085bc1e730dc44 | C++ | guti21js/235_Project1 | /delete.cpp | UTF-8 | 824 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<string.h>
using namespace std;
string set; //set
char *setPtr; //Where set string will be stored in to be used for string token
char *elmnt;
char *result; //where outputs of string token will be stored in
int elmntN=0; //Number of elements
int main(){
cout<<"Enter a set of elements: ";
cin>>set;
cout<<set<<endl;
setPtr=new char[set.length()+1];
strcpy(setPtr,set.c_str()); //copies a pointer version of the input into the pointer array so that be may split it up with stirng token
elmnt=new char[set.length()];
result=strtok(setPtr,",");
// strcpy(elmnt[elmntN],result);
elmnt[elmntN]=result;
while(result!=NULL){
result=strtok(NULL,",");
elmntN++;
elmnt[elmntN]=result;
//strcpy(elmnt[elmntN],result);
cout<<elmnt[elmntN];
}
}
| true |
2c085903a1349843ee83a7f370fa4ea6a1d5bccf | C++ | AshDr/Data-Struct-Experment-2020 | /Data Sturct Experiment/exp8/grpAdjLinkedList.h | GB18030 | 14,140 | 3.625 | 4 | [] | no_license | //************************************************************//
//* ͼڽʾͷļļGraphAdjLinkList.h *//
//* *//
//************************************************************//
#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#include "string.h"
#include<queue>
#include<stack>
#define INF 65535 //
#define MaxVerNum 100 //
typedef char elementType; //ͼж
typedef int eInfoType; //йڱߵϢͣ磬ȨͼпԱʾߵȨֵ
typedef int cellType; //ڽӾԪص
//Ȩͼ1-ڣбߣ0-ڣޱߣ
//ȨͼΪߵȨֵر
typedef enum{UDG, UDN, DG, DN} GraphKind; //öͼ--ͼͼ
typedef struct eNode //ṹ
{
int adjVer; //ڽӶַ˴Ϊڶţ1ʼ
eInfoType eInfo; //бʾߵϢȨֵ
struct eNode* next; //ָеһ
}EdgeNode; //
typedef struct vNode //Ԫؽṹ
{
elementType data; //ͼж
EdgeNode* firstEdge; //ָ˶ĵһߵָ룬ͷָ
}VerNode;
typedef struct GraphAdjLinkList
{
VerNode VerList[MaxVerNum+1]; //Ŷ˳0Ԫ
int VerNum; //
int ArcNum; //ߣ
GraphKind gKind; //ͼ:0-ͼ1-2-ͼ3-
}Graph; //ͼ
typedef struct minEdgeType {
int v;
eInfoType eWeight;
}MinEdgeType;
typedef struct edgetype {
int vbegin;
int vend;
eInfoType eWeight;
}EdgeType;
using namespace std;
bool visited[MaxVerNum+1]; //ȫ飬ǶǷѾʡ0--δʣ1--ѷʡ0Ԫ
//******************* ͼжĺ*********************//
//* ܣӡͼжԪأΪѾ *//
//* ڲ Graph Gʵͼint verID Ŀ궥 *//
//* ڲ *//
//* ֵ *//
//* visit(Graph &G, int verID) *//
//***********************************************************//
void visit(Graph &G, int verID)
{ //Ŵ1ʼ0Ԫ
cout<<G.VerList[verID].data<<"\t";
visited[verID]=true;
}
//******************* ͼвĿ궥 *********************//
//* ܣԪأͼвҴ˶Ԫصı *//
//* ڲ Graph GʵͼelementType v Ŀ궥 *//
//* ڲ *//
//* ֵintĿ궥ڣضţ *//
//* Ŵ1ʼ-1 *//
//* visit(Graph &G, int verID) *//
//***********************************************************//
int LocateVertex(Graph &G, elementType v)
{
for(int i=1;i<=G.VerNum;i++)
{
if( G.VerList[i].data==v )
return i;
}
return -1;
}
//vĵһڽӶ
int firstAdj(Graph &G, int v)
{
EdgeNode *p;
p=G.VerList[v].firstEdge;
if(p)
return p->adjVer;
else
return 0;
}
//vλڽӵw֮һڽӵ
int nextAdj(Graph &G, int v, int w)
{
EdgeNode *p;
p=G.VerList[v].firstEdge; //ȡvıͷָ
while(p->next)
{
if(p->adjVer==w)
return p->next->adjVer; //w֮һڽӵ
p=p->next;
}
return 0; //δҵһڽӵ㣬0
}
//******************** ӡͼϢ *********************//
//* ܣӡͼϢ *//
//* ڲ Graph Gӡͼ *//
//* ڲ *//
//* ֵ *//
//* printGraph(Graph &G) *//
//***********************************************************//
void printGraph(Graph &G)
{
int i=0,j=0;
//ӡͼ
switch(G.gKind)
{
case UDG:
cout<<"ͼͣͼ"<<endl;
break;
case UDN:
cout<<"ͼͣ"<<endl;
break;
case DG:
cout<<"ͼͣͼ"<<endl;
break;
case DN:
cout<<"ͼͣ"<<endl;
break;
default:
cout<<"ͼʹ"<<endl;
break;
}
//ӡͼĶ
cout<<""<<G.VerNum<<endl;
//ӡͼı
cout<<" "<<G.ArcNum<<endl;
//ӡ㼰
cout<<"\t\t"<<endl;
EdgeNode* p;
for(i=1;i<=G.VerNum;i++)
{
cout<<i<<"\t"<<G.VerList[i].data<<"\t";
p=G.VerList[i].firstEdge;
while(p!=NULL)
{
cout<<p->adjVer<<"\t";
p=p->next;
}
cout<<endl;
}
cout<<endl;
//ӡڽӾ
cout<<"ڽӾ"<<endl;
for(i=1;i<=G.VerNum;i++)
{
cout<<"\t";
p=G.VerList[i].firstEdge;
j=1;
while(p!=NULL || j<=G.VerNum)
{
if((j<=G.VerNum) && (p!=NULL) && j==p->adjVer) //б
{
cout<<p->eInfo<<"\t";
j++;
p=p->next;
}
else //ޱ
{
if(G.gKind==UDN || G.gKind==DN)
cout<<"INF"<<"\t"; //ޱʱӡȨֵΪáINFʾ
else
cout<<"0"<<"\t"; //ͼޱʱ0ʾ
j++;
}
}
cout<<endl;
}
}
void dfs(Graph G,int u) {
int v;
visit(G,u);
v = firstAdj(G,u);
while(v) {
if(!visited[v]) dfs(G,v);
v = nextAdj(G,u,v);
}
}
void bfs(Graph &G,int start) {
int u,v; queue<int> q;
visit(G,start);
q.push(start);
while(!q.empty()) {
u = q.front();
q.pop();
v = firstAdj(G,u);
while(v) {
if(!visited[v]) {
visit(G,v);
q.push(v);
}
v = nextAdj(G,u,v);
}
}
}
//
int getEdgeNum(Graph &G) {
return G.ArcNum;
}
//vʼdfs
void DfsTrav(Graph G, int u) {
dfs(G,u);
}
//vʼbfs
void BfsTrav(Graph G, int u) {
bfs(G,u);
}
//ȷǷб
bool HasEdge(Graph &G,int vbegin, int vend, eInfoType &eWeight) {
EdgeNode *p;
int f = false;
eWeight = INF;
p = G.VerList[vbegin].firstEdge;
while(p) {
if(p->adjVer==vend) {
f=true;
eWeight = p->eInfo;
break;
}
p = p->next;
}
return f;
}
//ʼѡ
void InitialTE(Graph G,MinEdgeType TE[], int vid) {
eInfoType eWeight;
for(int i=1; i<=G.VerNum; i++) {
if(HasEdge(G,vid,i,eWeight)) {
TE[i].v = vid;
TE[i].eWeight = eWeight;
}
else {
TE[i].eWeight = INF;
}
}
}
//С
int GetMinEdge(Graph G,MinEdgeType TE[] ) {
eInfoType eMin = INF;
int j = 0;
for(int i=1; i<=G.VerNum; i++) {
if(!visited[i] && TE[i].eWeight<eMin) {
j = i;
eMin = TE[i].eWeight;
}
}
return j;
}
//TE
void UpdateTE(Graph &G, MinEdgeType TE[], int vid) {
eInfoType eWeight;
for(int i=1; i<=G.VerNum; i++) {
if(!visited[i]) {
if(HasEdge(G,vid,i,eWeight) && eWeight<TE[i].eWeight) {
TE[i].v = vid;
TE[i].eWeight = eWeight;
}
}
}
}
//Prim㷨
void Prim(Graph &G, int vid) {
MinEdgeType TE[MaxVerNum];
int curid;
InitialTE(G,TE,vid);
visited[vid] = true;
for(int i=1; i<=G.VerNum; i++) {
curid = GetMinEdge(G,TE);
visited[curid] = true;
UpdateTE(G,TE,curid);
}
for(int i=2; i<=G.VerNum; i++) cout<<G.VerList[TE[i].v].data<<"->"<<G.VerList[i].data<<"="<<TE[i].eWeight<<endl;
}
//洢
void GetEdges(Graph &G,EdgeType edges[]) {
int k = 1;
EdgeNode *p;
for(int i=1; i<=G.VerNum; i++) {
p = G.VerList[i].firstEdge;
while(p) {
edges[k].vbegin = i;
edges[k].vend = p->adjVer;
edges[k].eWeight = p->eInfo;
p = p->next;
k++;
}
}
}
//ȡС
EdgeType getMinEdge(Graph &G, EdgeType edges[],int edgeUsed[],int &n) {
EdgeType minedge;
cellType wMin = INF;
int M;
if(G.gKind==UDG || G.gKind==UDN)
M = G.ArcNum*2;
else M = G.ArcNum;
for(int i=1; i<=M; i++) {
if(!edgeUsed[i] && edges[i].eWeight<wMin) {
wMin = edges[i].eWeight;
minedge.eWeight = edges[i].eWeight;
minedge.vbegin = edges[i].vbegin;
minedge.vend = edges[i].vend;
n = i;
}
}
return minedge;
}
//Kruskal
void Kruskal(Graph &G) {
int conVerID[MaxVerNum];
EdgeType edges[MaxVerNum*MaxVerNum];
EdgeType treeEdges[MaxVerNum];
int edgeUsed[MaxVerNum*MaxVerNum];
EdgeType minedge;
int conid,n;
GetEdges(G,edges);
int M;
if(G.gKind==UDG|| G.gKind==UDN)
M = G.ArcNum*2;
else M = G.ArcNum;
for(int i=0; i<=M; i++) {
edgeUsed[i] = 0;
}
for(int i=1; i<=G.VerNum; i++)
conVerID[i] = i;
for(int i=1; i<G.VerNum; i++) {
minedge = getMinEdge(G,edges,edgeUsed,n);
while(conVerID[minedge.vbegin]==conVerID[minedge.vend]) {
edgeUsed[n] = 1;
minedge = getMinEdge(G,edges,edgeUsed,n);
}
treeEdges[i] = minedge;
conid = conVerID[minedge.vend];
for(int j=1; j<=G.VerNum; j++) {
if(conVerID[j]==conid) conVerID[j] = conVerID[minedge.vbegin];
}
edgeUsed[n] = 1;
}
for(int i=1; i<G.VerNum; i++) cout<<treeEdges[i].vbegin<<"->"<<treeEdges[i].vend<<"="<<treeEdges[i].eWeight<<endl;
}
//Djikstra
void Djikstra(Graph &G,int path[],int dis[],int vid) {
int solved[MaxVerNum];
cellType mindis;
EdgeNode *p;
p = G.VerList[vid].firstEdge;
for(int i=1; i<=G.VerNum; i++) dis[i] = INF;
while(p) {
int v = p->adjVer;
dis[v] = p->eInfo;
p = p->next;
}
for(int i=1; i<=G.VerNum; i++) {
solved[i] = 0;
if(dis[i]!=INF)
path[i] = vid;
else path[i] = -1;
}
int v;
solved[vid] = 1;
dis[vid] = 0;
path[vid] = -1;
for(int i=1; i<G.VerNum; i++) {
mindis = INF;
for(int j=1; j<=G.VerNum; j++) {
if(!solved[j] && dis[j]<mindis) {
v = j;
mindis = dis[j];
}
}
if(mindis==INF) return ;
solved[v] = 1;
p = G.VerList[v].firstEdge;
while(p) {
int t = p->adjVer;
if(!solved[t] && mindis+(p->eInfo)<dis[t])
dis[t] = mindis+(p->eInfo),path[t] = v;
p = p->next;
}
}
}
//ӡ·
void PrintDjiksta(Graph &G,int path[],int dis[],int vid) {
int spath[MaxVerNum];
int vpre;
int top = 0;
for(int i=1; i<=G.VerNum; i++) {
cout<<G.VerList[vid].data<<"to"<<G.VerList[i].data<<":"<<endl;
if(dis[i]==INF) cout<<"Can't get"<<endl;
else {
cout<<"min_dis:"<<dis[i]<<endl;
cout<<"path:";
top++;
spath[top] = i;
vpre = path[i];
while(vpre!=-1) {
top++;
spath[top] = vpre;
vpre = path[vpre];
}
if(dis[i]!=INF) {
for(int j=top; j>=1; j--) {
cout<<G.VerList[spath[j]].data<<" ";
}
}
}
top = 0;
cout<<endl;
cout<<endl;
}
}
//Floyed㷨
void Floyed(Graph &G,int dis[MaxVerNum][MaxVerNum]) {
EdgeNode *p;
for(int i=1; i<=G.VerNum; i++) {
p = G.VerList[i].firstEdge;
while(p) {
int j = p->adjVer;
dis[i][j] = p->eInfo;
p = p->next;
}
}
for(int k=1; k<=G.VerNum; k++) {
for(int i=1; i<=G.VerNum; i++) {
for(int j=1; j<=G.VerNum; j++) {
if(i==j) dis[i][j] = 0;
if(i!=j && dis[i][k]+dis[k][j]<dis[i][j]) {
dis[i][j] = dis[i][k]+dis[k][j];
}
}
}
}
for(int i=1; i<=G.VerNum; i++) {
for(int j=1; j<=G.VerNum; j++) {
cout<<G.VerList[i].data<<"->"<<G.VerList[j].data<<"="<<dis[i][j]<<endl;
}
}
}
//
void GetInDegree(Graph &G, int in[]) {
EdgeNode *p;
for(int i=1; i<=G.VerNum; i++) {
p = G.VerList[i].firstEdge;
while(p) {
int j =p->adjVer;
in[j]++;
p = p->next;
}
}
}
//
bool toposort(Graph &G,int topo[]) {
int in[MaxVerNum];
stack<int> s;
int v,vcount=0;
memset(in,0,sizeof in);
for(int i=1; i<G.VerNum; i++) {
topo[i] = -1;
}
GetInDegree(G,in);
for(int i=1; i<=G.VerNum; i++) if(in[i]==0) s.push(i);
EdgeNode *p;
while(!s.empty()) {
v = s.top();
s.pop();
topo[vcount] = v;
vcount++;
p = G.VerList[v].firstEdge;
while(p) {
int j = p->adjVer;
in[j]--;
if(in[j]==0) s.push(j);
p = p->next;
}
}
if(vcount==G.VerNum) return 1;
else return 0;
}
//ؼ·
void KeyPath(Graph &G,int vet[],int vlt[],int topo[]) {
bool f = toposort(G,topo);
if(!f) {
cout<<"Failed"<<endl;
return ;
}
int vpre,vsuf;
for(int i=1; i<=G.VerNum; i++) vet[i] = 0;
EdgeNode *p;
for(int i=1; i<=G.VerNum; i++) {
vpre = topo[i-1];
p = G.VerList[vpre].firstEdge;
while(p) {
int j = p->adjVer;
if(vet[j]<vet[vpre]+p->eInfo) vet[j] = vet[vpre]+p->eInfo;
p = p->next;
}
}
for(int i=1; i<=G.VerNum; i++) vlt[i] = vet[G.VerNum];
for(int i=G.VerNum; i>=1; i--) {
vsuf = topo[i-1];
for(int j=1; j<=G.VerNum; j++) {
p = G.VerList[j].firstEdge;
while(p) {
int v = p->adjVer;
if(v==vsuf) {
if(vlt[v]>vlt[vsuf]-p->eInfo) vlt[j] = vlt[vsuf]-p->eInfo;
}
p = p->next;
}
}
}
}
//ӡؼ·
void PrintKeyPath(Graph &G,int topo[],int vet[],int vlt[]) {
cout<<"KeyPath: ";
int v = topo[0];
cout<<G.VerList[v].data<<" ";
int w;
while(v) {
w = firstAdj(G,v);
while(w) {
if(vet[w]==vlt[w]) {
cout<<G.VerList[w].data<<" ";
break;
}
else w = nextAdj(G,v,w);
}
v = w;
}
}
| true |
bebaaa83dac6694f451a3469167b6c5b86d67404 | C++ | muzammilpeer/BSCS | /Part time projects/Fast CGI based file sharing portal/cgi-bin/register.cpp | UTF-8 | 7,033 | 2.828125 | 3 | [] | no_license | // Fig. 19.12: post.cpp
// Demonstrates POST method with XHTML form.
#include <iostream>
#include <fstream>
/*using std::cout;
using std::cin;
using std::ofstream;
using std::ifstream;
using std::ios;*/
#include <string>
#include <cstring>
/*
using std::string;
using std::strlen;*/
#include <cstdlib>/*
using std::getenv;
using std::atoi;*/
using namespace std;
void cat(char* path,char* source,int len)
{
source=new char[len];
int j=0;
int len_s_p=len+strlen(source);
int i;
for (i=len;i<len_s_p;i++)
{
path[i]=source[j];
j++;
}
}
int len=0;
bool strlength(string& pass)
{
int i=0;
while(pass[i]!='\0')
{
i++;
len++;
}
if (i==0)
return false;
else return true;
//return i;
}
void change(string& pass)
{
int l=0;
while(pass[l]!='\0')
{l++;
}
for( int i=0;i<l;i++)
{
if (pass[i]==43)
{
pass[i]=32;
}
}
}
int length(char pass[30])
{
int i=0;
while(pass[i]!='\0')
{
i++;
}
return i;
}
int main()
{
char postString[ 1024 ] = ""; // variable to hold POST data
string dataString = "";
string nameString = "";
string f_name = "";
string l_name="";
string email="";
string sex="";
string password="";
string month="";
string day="";
string year="";
int contentLength = 0;
// content was submitted
if ( getenv( "CONTENT_LENGTH" ) )
{
contentLength = atoi( getenv( "CONTENT_LENGTH" ) );
cin.read( postString, contentLength );
dataString = postString;
} // end if
cout << "Content-Type: text/html\n\n"; // output header
// output XML declaration and DOCTYPE
cout << "<?xml version = \"1.0\"?>"
<< "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" "
<< "\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">";
// output XHTML element and some of its contents
cout << "<html xmlns = \"http://www.w3.org/1999/xhtml\">"
<< "<head><title>Registeration Form</title></head><body>";
cout<<"<style type=\"text/css\">"
<<"<!--"
<<"body {"
<<"background-image: url(http://localhost/vista%20home.jpg);"
<<"}"
<<"-->"
<<"</style>";
// output XHTML form
// data was sent using POST
int nameLocation = dataString.find_first_of( "f_name=" ) + 7;
int endLocation = dataString.find_first_of( "&" ) ;
int l_location = dataString.find( "l_name=" ) + 7;
int l_endLocation = dataString.find( "&email" ) ;
int email_loc=dataString.find("email=")+6;
int email_endLocation =dataString.find("&password");
int password_loc = dataString.find("password=")+9;
int password_end= dataString.find("&sex");
int sex_loc = dataString.find("sex=")+4;
int sex_end =dataString.find("&month");
int month_loc= dataString.find("month=")+6;
int month_end= dataString.find("&day");
int day_loc = dataString.find("day=")+4;
int day_end = dataString.find("&year");
int year_loc = dataString.find("year=")+5;
int year_end = dataString.find("®ister");
// retrieve entered word
f_name = dataString.substr(nameLocation, endLocation - nameLocation );
if (l_location>0)
l_name = dataString.substr(l_location, l_endLocation - l_location);
if (email_loc>0)
email = dataString.substr(email_loc,email_endLocation-email_loc);
if (password_loc>0)
password = dataString.substr(password_loc,password_end-password_loc);
if(sex_loc>0)
sex = dataString.substr(sex_loc,sex_end-sex_loc);
if(month_loc>0)
month = dataString.substr(month_loc,month_end-month_loc);
if(day_loc>0)
day = dataString.substr(day_loc,day_end-day_loc);
if(year_loc>0)
year = dataString.substr(year_loc,year_end-year_loc);
char serial[6];
int l=0;
while (password[l]!='\0')
{l++;
}
for (int i=0;i<l;i++)
{
password[i]=password[i]+25;
}
ifstream info(serial);
ofstream login("login.txt",ios::app);
ifstream number("number.txt");
number>>serial;
number.close();
int i=atoi(serial);
if (info.is_open())
{
// ofstream (path);
/* ofstream sysinfo(path);
sysinfo<<email<<endl<<password<<endl<<f_name<<endl<<l_name<<endl<<sex
<<endl<<month<<endl<<day<<endl<<year<<endl;
*/}
else
{
if (strlength(email)==true && strlength(password)==true && strlength(f_name)==true
&& strlength(l_name)==true)
{
char user_name[30];
char temp_name[30];
ofstream out("temp.txt",ios::trunc);
out<<email<<endl;
out.close();
ifstream iner("temp.txt");
iner>>temp_name;
iner.close();
bool permission=false;
for (int range=10001;range<=i;range++)
{
char path[5];
sprintf(path,"%d",range);
char* ext=".txt";
strcat(path,ext);
ifstream in(path);
in>>user_name;
in.close();
if (length(user_name)==length(temp_name))
{
permission=true;
}
}
if(permission==false)
{
i++;
ofstream writenumber("number.txt",ios::trunc);
writenumber<<i<<endl;
writenumber.close();
char path[5];
sprintf(path,"%d",i);
char* ext=".txt";
strcat(path,ext);
ofstream sysinfo(path);
sysinfo<<email<<endl<<password<<endl<<f_name<<endl<<l_name<<endl<<sex
<<endl<<month<<endl<<day<<endl<<year<<endl;
cout << "<p><h1>Register Form sucessfull </h1></p>";
cout<<"<meta http-equiv=\"refresh\" content=\"1;URL=http://localhost/macerma/main/bottom.html\" />";
}
else
{
cout<<"<h1> This User Name Already Exists.</h1>";
cout<<"<meta http-equiv=\"refresh\" content=\"4;URL=http://localhost/register.html\" />";
cout<<"<hr/><h1>Please Try Again........</h1>";
}
change(f_name);
change(l_name);
change(email);
change(password);
cout<<"<hr/><p>Full Name :"<<f_name<<" "<<l_name<<"</p>";
cout<<"<p>User Name :"<<email<<"</p>";
cout<<"<p>Password :"<<password<<"</p>";
cout<<"<p>Sex :"<<sex<<"</p>";
cout<<"<p>Birth day : "<<month<<" "<<day<<","<<year<<"</p>";
}
else
{
cout<<"<p>In-complete Data Entry</p> ";
}
}
cout<<"<meta http-equiv=\"refresh\" content=\"4;URL=http://localhost/register.html\" />";
cout << "</body></html>";
return 0;
} // end main
| true |
c04ac73f9e48a58861f12776f291f189ef01bc04 | C++ | botorabi/SensorStation | /Arduino/SensorStation/core.h | UTF-8 | 2,281 | 2.5625 | 3 | [
"MIT"
] | permissive | /**
* Copyright (c) 2019 by Botorabi. All rights reserved.
* https://github.com/botorabi/SensorStation
*
* License: MIT License (MIT), read the LICENSE text in
* main directory for more details.
*/
#ifndef CORE_H
#define CORE_H
#include "sensor.h"
#include "connectivity.h"
#include "httpserver.h"
#include "display.h"
class Core
{
public:
Core();
~Core();
void setSplashText(const String& text);
void setAppVersion(const String& version);
void initialize(int httpPort = 80, int displayOffTimeout = 10000);
void update();
void enableOTAUpdate();
void startWPS();
bool isWPSActive() const;
void displayTurn(bool on);
/**
* Pass false for 'toast' in order to persist the given display text, otherwise the display text
* will be updated with sensor values on next update. If you pass false for 'toast' then use
* method displayRestore() in order to remove the text persistence.
*/
void displaySetStatus(const String& text, bool toast = true);
void displaySetFooter(const String& text);
void displayRestore();
protected:
void setupDisplay();
void setupWiFi();
void setupSensors();
Sensor* createMoistureSensor(const String& name, int pin) const;
void updateHTTPServer();
void updateSensors();
void addSensorEntry();
void updateSensorDisplay();
String splashText;
String appVersion;
Sensor** sensors {nullptr};
int countSensors {0};
unsigned long lastSensorValueUpdate {0};
unsigned long lastSensorDisplayUpdate {0};
unsigned long sensorDisplayInterval {2000};
bool sensorDisplayUpdate {true};
Connectivity connectivity;
HTTPServer httpServer;
int httpPort {80};
bool otaUpdate {false};
Display display;
int displayOffTimeout {10000};
};
#endif /* CORE_H */
| true |
10a7a877b3e98ef34c7f7b7cdb57d8837d11b681 | C++ | iomeone/CSGOCheat | /PhysicsProps.h | UTF-8 | 2,907 | 2.59375 | 3 | [] | no_license | #pragma once
#include "RandomStuff.h"
struct surfacephysicsparams_t
{
float friction;
float elasticity;
float density;
float thickness;
float dampening;
};
struct surfaceaudioparams_t
{
float reflectivity; // like elasticity, but how much sound should be reflected by this surface
float hardnessFactor; // like elasticity, but only affects impact sound choices
float roughnessFactor; // like friction, but only affects scrape sound choices
float roughThreshold; // surface roughness > this causes "rough" scrapes, < this causes "smooth" scrapes
float hardThreshold; // surface hardness > this causes "hard" impacts, < this causes "soft" impacts
float hardVelocityThreshold; // collision velocity > this causes "hard" impacts, < this causes "soft" impacts
float highPitchOcclusion; //a value betweeen 0 and 100 where 0 is not occluded at all and 100 is silent (except for any additional reflected sound)
float midPitchOcclusion;
float lowPitchOcclusion;
};
struct surfacesoundnames_t
{
unsigned short walkStepLeft;
unsigned short walkStepRight;
unsigned short runStepLeft;
unsigned short runStepRight;
unsigned short impactSoft;
unsigned short impactHard;
unsigned short scrapeSmooth;
unsigned short scrapeRough;
unsigned short bulletImpact;
unsigned short rolling;
unsigned short breakSound;
unsigned short strainSound;
};
struct surfacegameprops_t
{
public:
float maxSpeedFactor;
float jumpFactor;
float flPenetrationModifier;
float flDamageModifier;
unsigned short material;
byte climbable;
char pad00[0x4];
};
struct surfacedata_t
{
surfacephysicsparams_t physics;
surfaceaudioparams_t audio;
surfacesoundnames_t sounds;
surfacegameprops_t game;
};
class IPhysicsProps
{
public:
virtual ~IPhysicsProps(void) {}
// parses a text file containing surface prop keys
virtual int ParseSurfaceData(const char *pFilename, const char *pTextfile) = 0;
// current number of entries in the database
virtual int SurfacePropCount(void) const = 0;
virtual int GetSurfaceIndex(const char *pSurfacePropName) const = 0;
virtual void GetPhysicsProperties(int surfaceDataIndex, float *density, float *thickness, float *friction, float *elasticity) const = 0;
virtual surfacedata_t *GetSurfaceData(int surfaceDataIndex) = 0;
virtual const char *GetString(unsigned short stringTableIndex) const = 0;
virtual const char *GetPropName(int surfaceDataIndex) const = 0;
// sets the global index table for world materials
// UNDONE: Make this per-CPhysCollide
virtual void SetWorldMaterialIndexTable(int *pMapArray, int mapSize) = 0;
// NOTE: Same as GetPhysicsProperties, but maybe more convenient
virtual void GetPhysicsParameters(int surfaceDataIndex, surfacephysicsparams_t *pParamsOut) const = 0;
}; | true |
1a64c16089a5b4d6b1bbfd00d3ea36423090c9e3 | C++ | oscstr-9/Lab-3-doa | /Lab 3/Lab 3/Main.cpp | WINDOWS-1252 | 3,194 | 3.453125 | 3 | [] | no_license | #include <IOstream>
#include <cstdlib>
#include <ctime>
using namespace std;
struct retStruct{
int largest;
int smallest;
int denominator; // nmnare
int numerator; // tljare
};
retStruct mergeSort(int* list, int size) {
int leftIndex = 0, rightIndex = size / 2;
retStruct ret{ 0,0,0,0 };
retStruct leftSolution;
retStruct rightSolution;
if (size > 3) {
retStruct leftSolution = mergeSort(list, size / 2); // cuts list into chunks of two // left side of list
retStruct rightSolution = mergeSort(list + size / 2, size - size / 2); // cuts list into chunks of two // right side of list
// set correct index for right side since it starts from the middle
rightSolution.denominator += size / 2;
rightSolution.numerator += size / 2;
rightSolution.largest += size / 2;
rightSolution.smallest += size / 2;
// calculate where best solution is
double leftQuota = list[leftSolution.numerator] / (double)list[leftSolution.denominator];
double rightQuota = list[rightSolution.numerator] / (double)list[rightSolution.denominator];
double midQuota = list[rightSolution.largest] / (double)list[leftSolution.smallest];
// set corret denominators and numerators
if (leftQuota < rightQuota && rightQuota > midQuota) {
ret.denominator = rightSolution.denominator;
ret.numerator = rightSolution.numerator;
}
else if (leftQuota < midQuota && midQuota> rightQuota) {
ret.denominator = leftSolution.smallest;
ret.numerator = rightSolution.largest;
}
else {
ret.denominator = leftSolution.denominator;
ret.numerator = leftSolution.numerator;
}
ret.largest = (list[leftSolution.largest] < list[rightSolution.largest]) ? rightSolution.largest : leftSolution.largest;
ret.smallest = (list[leftSolution.smallest] > list[rightSolution.smallest]) ? rightSolution.smallest : leftSolution.smallest;
return ret;
}
else if(size <= 2) { // if list is 2 in size
ret.largest = (list[1] > list[0]) ? 1 : 0;
ret.smallest = (list[0] < list[1]) ? 0 : 1;
ret.denominator = 0;
ret.numerator = 1;
return ret;
}
else { // if list is 3 in size
ret.largest = (list[1] > list[0]) ? 1 : 0; // find largest number
ret.largest = (list[ret.largest] < list[2]) ? 2 : ret.largest;
ret.smallest = (list[0] < list[1]) ? 0 : 1; // find smallest number
ret.smallest = (list[ret.smallest] < list[2]) ? ret.smallest : 2;
if (list[1] > list[2]) { // find denominator and numerator
ret.denominator = 0;
ret.numerator = 1;
}
else if (list[0] < list[1]) {
ret.denominator = 0;
ret.numerator = 2;
}
else{
ret.denominator = 1;
ret.numerator = 2;
}
return ret;
}
}
void main() {
srand(time(0));
int sizeOfList;
cout << "Enter any positive number: ";
cin >> sizeOfList;
cout << endl;
int* list = new int[sizeOfList]; // fill array with random numbers
for (int i = 0; i < sizeOfList; i++) {
list[i] = rand()% sizeOfList+1;
cout << list[i] << " , ";
}
retStruct ret = mergeSort(list, sizeOfList);
cout << endl << "Numerator index: " << ret.numerator << endl << "Denominator index: " << ret.denominator << endl << "Largest number: " << list[ret.largest] << endl << "Smallest number: " << list[ret.smallest];
} | true |
a78240cc7d22006a1a8dad97baecd3f899c13ed3 | C++ | friskycodeur/Coding | /Codeforces/Practice/510A.cpp | UTF-8 | 533 | 2.765625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void pattern(int n,char c){
for(int i=0;i<n;i++){
cout<<c;
}
}
int main(){
int n,m;cin>>n>>m;
for(int r=0;r<n;r++){
if(r%2==0){
pattern(m,'#');
}else{
if((r/2)%2==0){
pattern(m-1,'.');
cout<<"#";
}else{
cout<<"#";
pattern(m-1,'.');
}
}
cout<<"\n";
}
} | true |
b2771e079f7b299c81ef850750ab90e7e80dca99 | C++ | somodis/ClassRoomExamples | /SZE/OODB/20191112/Oliver/Music.h | UTF-8 | 326 | 2.84375 | 3 | [] | no_license | #pragma once
#include "Media.h"
class Music
: public Media
{
const std::string artist;
public:
Music(const std::string& artist, const std::string& title, int length)
: Media(title, length), artist(artist)
{}
virtual std::string toString() const;
virtual void print() const;
};
| true |
767173d78de36cc235759fe9d572a24b63f799c2 | C++ | vgherard/viterbi | /example.cpp | UTF-8 | 2,559 | 3.09375 | 3 | [] | no_license | #include "viterbi.h"
#include <iostream>
#include <cmath>
using std::cout;
using std::cin;
using std::vector;
int main() {
size_t H;
cout << "Enter dimension 'H' of hidden state space.\n" << "H: > ";
cin >> H;
cout << "Hidden state space: {h_1, h_2, ..., h_" << H << "}\n";
cout << "\nEnter transition probabilities.\n";
Matrix<double> T(H, H);
double p;
for (size_t j = 0; j < H; ++j) {
for (size_t i = 0; i < H; ++i) {
cout << "Pr(h_" << i + 1 << " <- h_" << j + 1 << ")" <<
": > ";
cin >> p;
T(i, j) = log(p);
}
}
cout << "\nEnter starting probabilities.\n";
vector<double> s(H);
for (size_t i = 0; i < H; ++i) {
cout << "Pr(h_" << i + 1 << " <- .): > ";
cin >> p;
s[i] = log(p);
}
size_t O;
cout << "\nEnter dimension 'O' of observable state space.\n" << "O: > ";
cin >> O;
cout << "Observable state space: {o_1, o_2, ..., o_" << O << "}\n";
cout << "\nEnter emission probabilities.\n";
Matrix<double> E(O, H);
for (size_t j = 0; j < H; ++j) {
for (size_t i = 0; i < O; ++i) {
cout << "Pr(o_" << i + 1 << " <- h_" << j + 1 << ")" <<
": > ";
cin >> p;
E(i, j) = log(p);
}
}
size_t L;
cout << "\nEnter length of path in observable space.\n" << "L: > ";
cin >> L;
size_t y_tmp;
vector<size_t> y(L);
cout << "\nEnter path in observable space.\n";
for (size_t l = 0; l < L; ++l) {
cout << "y(" << l + 1 << ") > ";
cin >> y_tmp;
while (y_tmp > O) {
cout << "Error: input is larger than " << O << ".\n";
cout << "y(" << l + 1 << "): > ";
cin >> y_tmp;
}
y[l] = y_tmp - 1;
}
cout << "\nComputing optimal path in hidden space...\n";
vector<size_t> x = viterbi::optimal_path(y, T, s, E);
cout << "\nx = (";
for (size_t l = 0; l < L - 1; ++l) {
cout << x[l] + 1 << ", ";
}
cout << x[L - 1] + 1 << ")\n";
return 0;
} | true |
e429ba660ec710da575b54f8059303c9e765c294 | C++ | Calibri-Software/Calibri-Library | /src/timers/timermetric.hpp | UTF-8 | 2,665 | 3.03125 | 3 | [
"MIT"
] | permissive | #ifndef CALIBRI_TIMERS_TIMERMETRIC_HPP
#define CALIBRI_TIMERS_TIMERMETRIC_HPP
// Std includes
#include <chrono>
// Calibri-Library includes
#include "global/types.hpp"
namespace Calibri {
namespace Timers {
// Enumerations
enum class TimerMetric : uint8 {
Hours,
Minutes,
Seconds,
Milliseconds,
Microseconds,
Nanoseconds
};
namespace Internal {
template<TimerMetric Metric,
typename std::enable_if<Metric == TimerMetric::Hours>::type * = nullptr>
static inline auto timeDifference(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &finish) -> uint64
{
return std::chrono::duration_cast<std::chrono::hours>(finish - start).count();
}
template<TimerMetric Metric,
typename std::enable_if<Metric == TimerMetric::Minutes>::type * = nullptr>
static inline auto timeDifference(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &finish) -> uint64
{
return std::chrono::duration_cast<std::chrono::minutes>(finish - start).count();
}
template<TimerMetric Metric,
typename std::enable_if<Metric == TimerMetric::Seconds>::type * = nullptr>
static inline auto timeDifference(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &finish) -> uint64
{
return std::chrono::duration_cast<std::chrono::seconds>(finish - start).count();
}
template<TimerMetric Metric,
typename std::enable_if<Metric == TimerMetric::Milliseconds>::type * = nullptr>
static inline auto timeDifference(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &finish) -> uint64
{
return std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();
}
template<TimerMetric Metric,
typename std::enable_if<Metric == TimerMetric::Microseconds>::type * = nullptr>
static inline auto timeDifference(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &finish) -> uint64
{
return std::chrono::duration_cast<std::chrono::microseconds>(finish - start).count();
}
template<TimerMetric Metric,
typename std::enable_if<Metric == TimerMetric::Nanoseconds>::type * = nullptr>
static inline auto timeDifference(const std::chrono::steady_clock::time_point &start, const std::chrono::steady_clock::time_point &finish) -> uint64
{
return std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count();
}
} // end namespace Internal
} // end namespace Timers
using Timers::TimerMetric;
} // end namespace Calibri
#endif // CALIBRI_TIMERS_TIMERMETRIC_HPP
| true |
cdc06ed5af3530fef1f53cb890d077bfaa1aee71 | C++ | marozau/cpp_craft_0314 | /solutions/igor_kolupaev/3/sources/3_5/averange_calculator.cpp | UTF-8 | 969 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <map>
#include "averange_calculator.h"
void average_calculator::calc( std::ifstream& in )
{
std::map<uint32_t, size_t> size_by_types;
time_counter_t curr_time_messages_by_types;
uint32_t curr_time = 0;
while( !in.eof() )
{
binary_reader::market_message message( in );
if( message.eof() )
{
break;
}
if( size_by_types[ message.type() ] + message.size() > MAX_BUFF_SIZE )
{
continue;
}
if( message.time() != curr_time )
{
counter_.merge( curr_time_messages_by_types );
size_by_types.clear();
curr_time_messages_by_types.clear();
curr_time = message.time();
}
curr_time_messages_by_types[ message.type() ]++;
size_by_types[ message.type() ] += message.size();
}
counter_.merge( curr_time_messages_by_types );
}
void average_calculator::write( std::ofstream& out ) const
{
try
{
counter_.output_avg( out );
}
catch( std::logic_error &error )
{
std::cerr << error.what();
}
} | true |
7d1e2248d45c689787d758738c227ddbdbf724fd | C++ | SamuelGallay/Cluedo | /main.cpp | UTF-8 | 3,122 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "cluedo.h"
using namespace std;
int main()
{
std::vector<std::string> listeJoueurs;
int nombreJoueurs = 0;
cout << "Combien y a t-il de joueurs ?" << endl;
cin >> nombreJoueurs;
string myName = "";
cout << "Mon nom : ";
cin >> myName;
listeJoueurs.push_back(myName);
for(int i=2; i<=nombreJoueurs; i++)
{
string name = "";
cout << "Nom du Joueur " << i << " : ";
cin >> name;
listeJoueurs.push_back(name);
}
Cluedo partie(listeJoueurs);
char input('h');
cout << "Bienvenue dans mon programme de Cluedo !!!" << endl;
cout << "Tapez 'h' pour ouvrir l'aide !!!" << endl;
do
{
cout << "@ ";
input = 'h';
cin >> input;
if(input == 'h')
{
cout << "Voici les différentes commandes : " << endl;
cout << "'q' pour quitter" << endl;
cout << "'a' pour afficher la partie" << endl;
cout << "'h' pour afficher l'aide" << endl;
cout << "'l' pour lister les cartes" << endl;
cout << "'r' pour réfléchir un peu" << endl;
cout << "'e' pour entrer un indice" << endl;
cout << "'n' pour creer une supposition" << endl;
cout << "'s' pour afficher les suppositions" << endl;
cout << "'d' pour entrer ses cartes de départ" << endl;
}
else if(input == 'a')
{partie.toutAfficher();}
else if(input == 'q')
{
cout << "Voulez-vous vraiement quitter ? Les données non-enregistrées seront perdues !"<<endl;
cout << "Tapez 'q' pour quitter : ";
cin >> input;
if(input == 'q')
{cout << "Bye, Bye !!!" << endl;}
}
else if(input == 'l')
{partie.liste();}
else if(input == 'e')
{
string Joueur;
string Indice;
cout << "Joueur : ";
cin >> Joueur;
cout << "Indice : ";
cin >> Indice;
partie.info(Joueur,Indice);
partie.reflechir();
}
else if(input == 'd')
{
int n;
cout << "Combien de cartes avez vous ? : " << endl;
cin >> n;
for(int i=0; i<n; i++)
{
string maCarte;
cout << i+1 << " : ";
cin >> maCarte;
partie.info(myName, maCarte);
}
partie.reflechir();
}
else if(input == 'r')
{partie.reflechir();}
else if(input == 's')
{partie.afficherSuppo();}
else if(input == 'n')
{
cout << "Hypothèse posée par : ";
string Joueur;
cin >> Joueur;
cout << "Lieu : ";
string Lieu;
cin >> Lieu;
cout << "Suspect : ";
string Suspect;
cin >> Suspect;
cout << "Arme : ";
string Arme;
cin >> Arme;
char Reponse = 'z';
do
{
string Personne;
cout << "Qui doit répondre ? ";
cin >> Personne;
cout << "Cette personne a-t-elle répondu ? ";
cin >> Reponse;
if(Reponse == 'o')
{
if(Personne != myName)
{partie.suppo(Joueur, Lieu, Suspect, Arme, Personne);}
}
else
{partie.pas(Personne, Lieu, Suspect, Arme);
cout <<"Bingo ";}
}while(Reponse != 'o');
}
else
{cout << "Tapez 'h' pour ouvrir l'aide !!!" << endl;}
}while(input != 'q');
}
| true |
84d737f430cd4a6b2221d3d88443d2ab31e8a371 | C++ | tigoe/MakingThingsTalk2 | /3rd_edition/chapter9/WriteTagMultipleRecords/WriteTagMultipleRecords.ino | UTF-8 | 1,056 | 2.703125 | 3 | [] | no_license | /*
NDEF card writer
context: Arduino
*/
#include <SPI.h> // include SPI library
#include <PN532_SPI.h> // include SPI library for PN532
#include <PN532.h> // include PN532 library
#include <NfcAdapter.h> // include NFC library
PN532_SPI pn532spi(SPI, 11); // initialize adapter
NfcAdapter nfc = NfcAdapter(pn532spi);
void setup() {
Serial.begin(9600); // open serial communications
nfc.begin(); // open NFC communications
}
void loop() {
Serial.println("Put a formatted Mifare Classic tag on the reader.");
if (nfc.tagPresent()) {
NdefMessage message = NdefMessage();
message.addTextRecord("Tom Igoe"); // user name
message.addTextRecord("1"); // switch number
message.addTextRecord("192.168.0.17"); // switch IP address
if (nfc.write(message)) {
Serial.println("Sucess. Tag written.");
} else {
Serial.println("Write failed");
}
}
Serial.println(); // blank line at the end
delay(3000); // give the user time to remove the tag
}
| true |
6937829790c527c14d559154189ceef4a547285f | C++ | SZUxiegumeng/Games-Graph | /Assignment7/PA7/Assignment7/Material.cpp | GB18030 | 11,345 | 2.6875 | 3 | [] | no_license | #include "Material.hpp"
//wi,woע⣬·٣Դ
//һ㶼ǹԴ㣬Ҫ뽻
float Material::Fresnels(const Vector3f &wi, const Vector3f &wo, const Vector3f &N, const Vector3f &h)
{
//ʵkr/ks(/)ĻҪһ
//ks/kd߹/ɢ䣩,F0Ǵֱʱ
switch (m_type)
{
case BSDF:
case Cook_Torrance:
{
float ansF = 1.0f;
if (dotProduct(h, wo) > 0)
ansF = F0 + (1.0f - F0)*pow5(1 - abs(dotProduct(h, wo)));//ӦüģΪ˵bsdf
else
ansF = F0 + (1.0f - F0)*pow5(1 - abs(dotProduct(h, wi)));
return std::max(0.0f, std::min(1.0f, ansF));
break;
}
case GGX:
return F0 + (1.0f - F0)*pow5(1 - dotProduct(h, wo));
break;
/*case BSDF:
{
float t_ni = this->ni, t_nt = this->nt;
if (dotProduct(wo, N) < 0)
std::swap(t_ni, t_nt);
float c = abs(dotProduct(wo,h));
float g = pow2(t_nt / t_ni) - 1 + c * c;
//ȫ
if (g < 0)
return 1.f;
g = sqrtf(g);
float F = pow2(g-c) / (2 * pow2(g+c));
F = F * (1 + pow2(c*(g + c) - 1) / pow2(c*(g - c) - 1) );
//std::cout << "this is Fresnels : " << F << std::endl;
return F;
break;
}*/
}
return 1.0f;
}
float Material::NormalDistrFunc(const Vector3f &wi, const Vector3f&wo, const Vector3f &N, const Vector3f &h)
{
//NǺ۷ߣhǰmDZֲڳ̶
//Beckmannֲ
float cosSita = dotProduct(N, h);
float cosSita_p2 = cosSita * cosSita;
//std::cout << "this is cos : " << cosSita << std::endl;
float m_p1 = this->roughness ,m_p2 = this->roughness * this->roughness;
switch (m_type)
{
//case BSDF:
case Cook_Torrance:
{
return exp(((cosSita_p2 - 1) / cosSita_p2) / m_p2) /
(M_PI * m_p2 * cosSita_p2 * cosSita_p2);
break;
}
case BSDF:
case GGX:
{
float N_d = characFc(cosSita) / M_PI *
pow2(m_p1 / (cosSita_p2*(m_p2 - 1) + 1));
// std::cout << "this is N : " << N_d << std::endl;
return N_d;
break;
}
}
return 0.0;
}
float Material::GeomAtteFactor(const Vector3f &wi, const Vector3f& wo, const Vector3f &N, const Vector3f &h)
{
//Beckmannֲǹڱ
//ڱΪ0
//if (dotProduct(wi, h)*dotProduct(wi, N) < 0 || dotProduct(wo, h)*dotProduct(wo, N) < 0)
// return 0;
switch (m_type)
{
case Cook_Torrance:
{
float Gb = 2 * dotProduct(N, h)*dotProduct(N, wi) / dotProduct(wi, h);
float Gc = 2 * dotProduct(N, h)*dotProduct(N, wo) / dotProduct(wo, h);
return std::min(1.0f, std::min(Gb, Gc));
break;
}
case GGX:
case BSDF:
{
float cos_i = dotProduct(wi, N), cos_o = dotProduct(wo, N), ag = this->roughness;
float G1 = 2 * characFc(dotProduct(wi, h) / cos_i) / (1 + sqrtf(1 + ag * ag*(1 - cos_i * cos_i)/(cos_i*cos_i)));
float G2 = 2 * characFc(dotProduct(wo, h) / cos_o) / (1 + sqrtf(1 + ag * ag*(1 - cos_o * cos_o)/(cos_o*cos_o)));
//std::cout << "this is G : " << G1 << " " << G2 << std::endl;
return G1 * G2;
}
}
return 0.0;
}
Vector3f Material::sample(const Vector3f &wi, const Vector3f &N,float& m_pdf) {
switch (m_type) {
case BSDF:
{
float m_p2 = this->roughness * this->roughness;
float x_1 = get_random_float(), x_2 = get_random_float(),x_3 = get_random_float();
float z = sqrtf( (1 - x_1) / (x_1*(m_p2 - 1) + 1) );
float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2;
Vector3f h(r*std::cos(phi), r*std::sin(phi), z);
h = normalize(toWorld(h, N));
float cosSita = dotProduct(h, N);
float F = Fresnels(wi, wi, N, h);
m_pdf = 2.0f*m_p2*z / (2 * M_PI*pow2(1 + z * z*(m_p2 - 1)));
// std::cout << "this is Fresnels : " << F << std::endl;
bool isreflect = true;
if (x_3 > F)
isreflect = false;
//std::cout << "this cos h and N : " << dotProduct(h, N) << std::endl;
Vector3f wo(0);
wo = normalize(refract(-wi, h, this->m_nt));
if (wo.norm() < EPSILON)
isreflect = true;
if (isreflect)
{
wo = normalize(reflect(wi, h));
if (dotProduct(wi, N) * dotProduct(wo, N) < 0)
{
m_pdf = -1.0;
// std::cout << "this is reflect : " << dotProduct(wi, N)<<" "<<dotProduct(wo,N)<< std::endl;
}
else
{
m_pdf *= 1;//F / (4.f*abs(dotProduct(wi, h)));
// std::cout << "this is reflect : " << dotProduct(wi, N)<<" "<<dotProduct(wo,N)<< std::endl;
}
}
else
{
float ni = this->m_ni, nt = this->m_nt;
wo = normalize(refract(-wi, h, nt));
// std::cout << "this is h/N " << dotProduct(h, N) << std::endl;
// std::cout << "this is F " << F << std::endl;
if (dotProduct(wo, N) < 0)
std::swap(ni, nt);
if (dotProduct(wi, N) * dotProduct(wo, N) > 0 || dotProduct(wi,N)*dotProduct(wi,h)<0 || dotProduct(wo, N)*dotProduct(wo, h) < 0)
{
m_pdf = -1.0;
//std::cout << "this refract : " << dotProduct(wi, h) << " " << dotProduct(wo, h) << std::endl;
}
else
{
m_pdf *= 1;//(1 - F)*nt*nt*abs(dotProduct(wi, h)) / pow2(ni*dotProduct(wo, h) + nt * dotProduct(wi, h));
// std::cout << "this refract with h : " << dotProduct(wi, h) << " " << dotProduct(wo, h) << std::endl;
// std::cout << "this refract with N : " << dotProduct(wi, N) << " " << dotProduct(wo, N) << std::endl;
// std::cout << "this wi,wo : " << dotProduct(wi, wi) << " " << dotProduct(wo, wo) << std::endl;
auto hpp = -normalize(wo*ni + wi * nt);
auto hppf = -normalize(wo*nt + wi * ni);
//std::cout << "this is htCos fan: " << dotProduct(hpp, h) <<" "<<dotProduct(hppf,h) << std::endl;
if (abs(dotProduct(hpp, h) - 1) > EPSILON)
std::cout << "this is fxck" << std::endl;
// std::cout << "this is pdf : " << m_pdf << std::endl;
}
}
// std::cout << "this is pdf : " << m_pdf << std::endl;
return wo;
break;
}
case DIFFUSE:
{
// uniform sample on the hemisphere
float x_1 = get_random_float(), x_2 = get_random_float();
float z = std::fabs(1.0f - 2.0f * x_1);
float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2;
Vector3f localRay(r*std::cos(phi), r*std::sin(phi), z);
Vector3f wo = toWorld(localRay, N);
m_pdf = pdf(wi, wo, N);
return wo;
break;
}
case DIFFUSE_COS:
{
float x_1 = get_random_float(), x_2 = get_random_float();
float z = (1.0f - 2.0f * x_1);
z = cos(acos(z) / 2);
float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2;
// std::cout << "this is r and phi : " << r << " " << phi << std::endl;
Vector3f localRay(r*std::cos(phi), r*std::sin(phi), z);
// std::cout << "localRay : " << localRay.x << " " << localRay.y << " " << localRay.z << std::endl;
// std::cout << "this is N_wo : " << dotProduct(localRay, Vector3f(0, 0, 1)) << std::endl;
Vector3f wo = toWorld(localRay, N);
m_pdf = pdf(wi, wo, N);
return wo;
break;
}
case Cook_Torrance:
{
float x_1 = get_random_float(), x_2 = get_random_float();
float z = std::fabs(1.0f - 2.0f * x_1);
float r = std::sqrt(1.0f - z * z), phi = 2 * M_PI * x_2;
Vector3f localRay(r*std::cos(phi), r*std::sin(phi), z);
Vector3f wo = toWorld(localRay, N);
m_pdf = pdf(wi, wo, N);
return wo;
break;
}
}
}
float Material::pdf(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) {
switch (m_type) {
case DIFFUSE:
{
// uniform sample probability 1 / (2 * PI)
if (dotProduct(wo, N) > 0.0f)
return 0.5f / M_PI;
else
return 0.0f;
break;
//cosʵϻҪf
}
case Cook_Torrance:
case DIFFUSE_COS:
{
float c = 0.0f;
if ((c = dotProduct(wo, N)) > EPSILON)
{
return c / M_PI;
}
else
return 0.0f;
break;
}
case BSDF:
{
return 0.25f / M_PI;
}
}
}
Vector3f Material::eval(const Vector3f &wi, const Vector3f &wo, const Vector3f &N) {
switch (m_type) {
case DIFFUSE:
{
// calculate the contribution of diffuse model
float cosalpha = dotProduct(N, wo);
// std::cout << "this is cosalpha " << cosalpha << std::endl;
if (cosalpha > 0.0f) {
Vector3f diffuse = Kd / M_PI;
return diffuse;
}
else
return Vector3f(0.0f);
break;
}
case DIFFUSE_COS:
{
//ɢķֲճ
float cosalpha = dotProduct(N, wo);
if (cosalpha > 0.0f) {
Vector3f diffuse = Kd / M_PI;
return diffuse;
}
else
return Vector3f(0.0f);
break;
}
case Cook_Torrance:
{
float cosalpha = dotProduct(N, wo);
if (cosalpha > 0.0f)
{
Vector3f hr = normalize(wi + wo);
Vector3f ks = Fresnels(wi, wo, N, hr);
// float n1 = dotProduct(N, wo), n2 = dotProduct(N, wi);
Vector3f specularW = NormalDistrFunc(wi, wo, N, hr)*ks*GeomAtteFactor(wi, wo, N, hr) /
(4 * dotProduct(N, wo)*dotProduct(N, wi));
Vector3f diffuseW = (Vector3f(1) - ks)*(1 - metal)*Kd / M_PI;
//std::cout << "this is specular: " << specularW << std::endl;
return specularW + diffuseW;
}
else
return Vector3f(0);
break;
}
case BSDF:
{
float ni = this->m_ni, no = this->m_nt;
if (dotProduct(N,wi)*dotProduct(N, wo) > 0)
{
Vector3f hr = normalize(wi + wo);
if (dotProduct(hr, N) < 0)
hr = -hr;
Vector3f F = Fresnels(wi, wo, N, hr);
Vector3f fr = NormalDistrFunc(wi, wo, N, hr)* F* GeomAtteFactor(wi, wo, N, hr) /
(4 * dotProduct(N, wo)*dotProduct(N, wi));
// std::cout << "this is BSDF fr ----------------->" << fr << std::endl;
return fr;
}
else
{
if (dotProduct(N, wo) < 0)
{
// std::cout << "this is wi/N " << dotProduct(wi, N) << std::endl;
// std::cout << "this is wo/N " << dotProduct(wo, N) << std::endl;
// std::cout << " --------------------- " << std::endl;
std::swap(ni, no);
// std::cout << "this is inside ft " << std::endl;
}
Vector3f ht = -normalize(wo * ni + no * wi);
// std::cout << "this is N/h - eval " << dotProduct(ht, N) << std::endl;
if (true && dotProduct(ht, N) < 0)
{
return Vector3f(0.0);
std::cout << "this is wi/h " << dotProduct(wi, ht) << std::endl;
std::cout << "this is wo/h " << dotProduct(wo, ht) << std::endl;
std::cout << "this is wi/N " << dotProduct(wi, N) << std::endl;
std::cout << "this is wo/N " << dotProduct(wo, N) << std::endl;
std::cout << "this is N/h " << dotProduct(N, ht) << std::endl;
auto hpp = -normalize(wo * no + ni * wi);
std::cout << "this is hpp " << dotProduct(N, hpp) << std::endl;
std::cout << " ======================= " << std::endl;
}
Vector3f ft = abs(dotProduct(wi, ht)) * abs(dotProduct(wo, ht)) *
no*no*(Vector3f(1.0f) - Fresnels(wi, wo, N, ht))*GeomAtteFactor(wi, wo, N, ht)*NormalDistrFunc(wi, wo, N, ht) /
(abs(dotProduct(wi, N))*abs(dotProduct(wo, N))*pow2(no*dotProduct(wi, ht) + ni * dotProduct(wo, ht)));
if (false )
{
std::cout << "this is BSDF ft ----------------->" << ft << std::endl;
std::cout << "this is F : " << Fresnels(wi, wo, N, ht) << std::endl;
std::cout << "this is G : " << GeomAtteFactor(wi, wo, N, ht) << std::endl;
std::cout << "this is D : " << NormalDistrFunc(wi, wo, N, ht) << std::endl;
}
return ft;
}
break;
}
}
return Vector3f(0);
} | true |
c02d05b72fd30850e07f6d47f01969b17a3f4017 | C++ | SokolovVadim/AdvancedCpp11 | /26_Koenig_lookup_ADL/main.cpp | UTF-8 | 744 | 3.1875 | 3 | [
"MIT"
] | permissive | #include <iostream>
namespace Uni
{
struct Student {};
void study(Student)
{
std::cout << "calling Uni::study()\n";
}
}
class Lesson{
public:
void study(Uni::Student)
{
std::cout << "calling Lesson::study()\n";
}
};
class School: public Lesson
{
public:
void work()
{
Uni::Student Max;
study(Max);
}
};
namespace Game
{
struct Player {};
void play(Player )
{
std::cout << "calling Game::play()\n";
}
namespace Football
{
void play()
{
std::cout << "calling Game::Football::play()\n";
}
void kick()
{
Player Mikita;
play(Mikita);
}
}
}
// --------------------------------------------------------------------
int main()
{
School school;
school.work();
Game::Football::kick();
return 0;
} | true |
189d637c61c5f660225e14b0e483337e19d53e5d | C++ | khuumi/Flat_Filesystem | /objlist.cpp | UTF-8 | 1,517 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <cstdlib>
#include "tools.h"
using namespace std;
int main(int argc, char * argv[]){
int show_size = 0;
if (argc < 1) {
cerr << "Usage:"
<< argv[0]
<< "[-l]"
<< endl;
exit(1);
}
if (argc == 2){
string option = argv[1];
if (option == "-l")
show_size = 1;
}
uid_t euid = get_uid("flat_fs");
// Set the egid to flat_fs's gid
if(raise_privilege(euid) < 0 ){
cerr << "Sorry there was an error accessing the repository" << endl;
exit(1);
}
string user_name = get_real_username();
string path_name = "/flat_fs_repo";
struct dirent *dir;
DIR *d = opendir(path_name.c_str());
char delim = '-';
string result;
if (d){
while ((dir = readdir(d)) != NULL){
struct stat st;
string file_path = path_name + "/" + dir->d_name;
if (stat(file_path.c_str(), &st) <0)
cerr << "Sory error calling stat" <<endl;
int size = st.st_size;
string file_name = dir->d_name;
int delim_loc = file_name.find(delim);
string files_user_name = file_name.substr(0, delim_loc);
string object_name = file_name.erase(0, delim_loc + 1);
if (user_name == files_user_name)
{
if (show_size > 0)
cout << object_name << "\t" << size << endl;
else
cout << object_name << endl;
}
}//end of while ((dir... ))
closedir(d);
}// end of if(d)
drop_privilege(euid);
return 0;
}
| true |
c1b84f1dddf1013b99fcc06ee07bed9c95144e39 | C++ | goodpaperman/template | /07.chapter/mix/mix.cpp | GB18030 | 3,890 | 2.640625 | 3 | [] | no_license | // mix.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <typeinfo>
template <typename T>
class List
{
public:
void clear() { printf("clear list\n"); }
T *buf;
};
typedef struct
{
double x, y, z;
} Point;
typedef enum { red, green, blue } *ColorPtr;
template <typename T, T nontype_param>
class C
{
public:
C() { printf("%s\n", typeid(T).name()); }
};
//static int a;
int a;
void f() { }
void f(int) { }
class X
{
public:
int n;
static bool b;
};
template <typename T>
void templ_func() { printf("this is a templ func.\n"); }
template <char const* str>
class Message
{
public:
Message() { printf("str: %s\n", str); }
};
extern char const hello[] = "Hello World!";
class Base
{
public:
int i;
} base;
class Derived : public Base
{
} derived_obj;
//int ab[10];
template <typename T, int I>
class Mix
{
public:
Mix() { printf("type: %s\n", typeid(*this).name()); }
};
template <typename T>
class Node;
template <typename T>
class Tree
{
friend class Node<T>;
template <typename T2>
friend class Node;
friend class Factory;
};
//template <typename T>
//class Node
//{
//public:
//};
template <typename T1, typename T2>
void combine(T1 a, T2 b)
{
printf("%d %d\n", a.i, b.i);
}
class Mixer
{
friend void combine<>(int&, int&);
friend void combine<int, int>(int, int);
friend void combine<char>(char, int);
friend void combine<char>(char&, int);
//friend void combine<>(long, long) {}
//friend void combine<Mixer&>(Mixer&, int);
template <typename T1, typename T2>
friend void combine(T1, T2);
public:
Mixer() : i(-1) {}
private:
int i;
};
void multiply(void *)
{
printf("multiply(void *)\n");
}
template <typename T>
void multiply(T a)
{
printf("template <typename T> multiply(T): %d\n", a.i);
}
class Comrades
{
friend void multiply(int) { }
friend void ::multiply(void *);
friend void ::multiply(Comrades com);
friend void ::multiply<double*>(double *);
//friend void ::error() { }
//friend void ::multiply(double) { }
public:
Comrades() : i(-2) {}
private:
int i;
};
template <typename T>
class Creator
{
friend void appear(){ printf("appear %s.\n", typeid(T).name()); }
public:
Creator() { appear();}
};
template <typename T>
class Generator
{
friend void feed(Generator<T> *const p) { printf("feed %s.\n", typeid(p).name()); }
public:
Generator() { feed(this); }
};
class Manager
{
template <typename T>
friend class Task;
//template <typename T>
//friend void Schedule<T>::dispatch(Task<T>*);
template <typename T>
friend int ticket()
{
return ++ Manager::counter;
}
static int counter;
};
int Manager::counter = 0;
int _tmain(int argc, _TCHAR* argv[])
{
//template <typename T>
//class error_templ
//{
//};
struct Association
{
int* p;
int* q;
};
List<Association*> list1;
list1.clear();
printf("enum name: %s\n", typeid(ColorPtr).name());
List<ColorPtr> list2;
list2.clear();
List<Point> list3;
list3.clear();
C<int, 33> c1;
C<int, 32>* c2;
//int a;
//static int a;
C<int*, &a> c3;
C<int*, &a>* c4;
C<void (*)(int), f> c5;
C<void (*)(), f>* c6;
C<bool&, X::b> c7;
C<bool&, X::b>* c8;
C<int X::*, &X::n> c9;
//C<int X::*, X::n>* c10;
C<void (*)(), &templ_func<double> > c11;
C<void (*)(), templ_func<float> >* c12;
Message<hello> hello_msg;
//C<Base*, &derived_obj> c13;
//C<int&, base.i> c14;
//C<int*, &ab[0]> c15;
typedef int Int;
Mix<int, 3*3> p1;
Mix<Int, 4+5> p2;
p2 = p1;
Tree<int> tree;
Mixer mx;
combine(mx, mx);
Comrades com;
//multiply(com);
multiply(com);
//Creator<void> miracle;
Creator<double> oops;
Generator<void> one;
Generator<double> two;
Manager man;
return 0;
}
| true |
59434900145d91b44bbeeee74c1df32ea35d2346 | C++ | nadnik13/OOP | /THexagon.h | UTF-8 | 613 | 3.09375 | 3 | [] | no_license | #ifndef Hexagon_H
#define Hexagon_H
#include "IPolygon.h"
#include <iostream>
class Hexagon : public Polygon
{
public:
Hexagon(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int x5, int y5, int x6, int y6);
Hexagon(std::istream &is);
Hexagon(const Hexagon &original);
virtual ~Hexagon() override;
void Print() override;
double Square() override;
bool operator==(const Hexagon &other);
Hexagon &operator=(const Hexagon &other);
private:
int a_x;
int a_y;
int b_x;
int b_y;
int c_x;
int c_y;
int d_x;
int d_y;
int e_x;
int e_y;
int f_x;
int f_y;
};
#endif //Hexagon_H | true |
3587ae077f7d54e0e3c991ffc513c4f161c6d3ac | C++ | NTimmons/ModernCPP_Examples | /C++17/Library/Sampling.h | UTF-8 | 545 | 3.109375 | 3 | [
"MIT"
] | permissive | #pragma once
//#ifdef MSVC_NOT_SUPPORTED_ENABLED
#include <algorithm>
#include <iostream>
#include <random>
#include <string>
namespace Sampling_Example
{
void Sampling()
{
std::string input = "Hello this is a test";
std::string output;
std::mt19937 randomDevice(std::random_device{}());
std::sample(input.begin(), input.end(), std::back_inserter(output), 10, randomDevice);
std::cout << "A selection of ten characters from the submitted string: " << input << " -> " << output << '\n';
}
}
//#endif | true |
36e100a1f0a62a4d79796e67bdfcbd2080a6ac6a | C++ | axxel/zxing-cpp | /core/src/pdf417/PDFBarcodeValue.h | UTF-8 | 669 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*/
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <map>
#include <vector>
namespace ZXing {
namespace Pdf417 {
/**
* @author Guenther Grau
*/
class BarcodeValue
{
std::map<int, int> _values;
public:
/**
* Add an occurrence of a value
*/
void setValue(int value);
/**
* Determines the maximum occurrence of a set value and returns all values which were set with this occurrence.
* @return an array of int, containing the values with the highest occurrence, or null, if no value was set
*/
std::vector<int> value() const;
int confidence(int value) const;
};
} // Pdf417
} // ZXing
| true |
2711ea42bbe13eb8a5e227fc4613e7a1eb2e1c23 | C++ | ChuaPingChan/SpaXI | /Submission/Team11/Code11/SPA/PQL/Validator/Selection/With/WithValidator.cpp | UTF-8 | 7,467 | 2.828125 | 3 | [] | no_license | #include "WithValidator.h"
WithValidator::WithValidator(QueryTree *qtPtrNew)
{
this->qtPtr = qtPtrNew;
}
WithValidator::~WithValidator()
{
}
void WithValidator::validate(string str)
{
string lhs = extractLhs(str);
string rhs = extractRhs(str);
if (isValidLhs(lhs) && isValidRhs(rhs) && isLhsSameTypeAsRhs())
{
if (lhsEntity == INTEGER && rhsEntity == INTEGER && lhsValue!=rhsValue)
{
this->validity = false;
}
else if (lhsEntity == IDENT_WITHQUOTES && rhsEntity == IDENT_WITHQUOTES && lhsValue != rhsValue)
{
this->validity = false;
}
else
{
this->validity = true;
}
}
else
{
this->validity = false;
}
}
bool WithValidator::isValid()
{
return this->validity;
}
WithType WithValidator::getLhsWithType()
{
return this->lhsWithType;
}
Entity WithValidator::getLhsEntity()
{
return this->lhsEntity;
}
string WithValidator::getLhsValue()
{
return this->lhsValue;
}
WithType WithValidator::getRhsWithType()
{
return this->rhsWithType;
}
Entity WithValidator::getRhsEntity()
{
return this->rhsEntity;
}
string WithValidator::getRhsValue()
{
return this->rhsValue;
}
string WithValidator::extractLhs(string str)
{
return Formatter::getStringBeforeDelim(str, "=");
}
string WithValidator::extractRhs(string str)
{
return Formatter::getStringAfterDelim(str, "=");
}
bool WithValidator::isValidLhs(string lhs)
{
if (RegexValidators::isValidAttrRefRegex(lhs))
{
string attrRefSynonymStr = getAttrRefSynonymStr(lhs);
string attrRefAttributeStr = getAttrRefAttributeStr(lhs);
try {
Entity entity = getEntityOfSynonym(attrRefSynonymStr);
WithType withType = getWithType(entity, attrRefAttributeStr);
this->lhsWithType = withType;
this->lhsEntity = entity;
this->lhsValue = attrRefSynonymStr;
return true;
}
catch (SynonymNotFoundException& snfe) {
return false;
}
catch (AttributeNotFoundException& anfe) {
return false;
}
}
else if (RegexValidators::isValidIntegerRegex(lhs))
{
this->lhsWithType = INTEGER_WITH;
this->lhsEntity = INTEGER;
this->lhsValue = lhs;
return true;
}
else if (RegexValidators::isValidIdentWithQuotesRegex(lhs))
{
string processedLhs = Formatter::removeAllQuotes(lhs);
this->lhsWithType = STRING_WITH;
this->lhsEntity = IDENT_WITHQUOTES;
this->lhsValue = processedLhs;
return true;
}
else if (RegexValidators::isValidSynonymRegex(lhs))
{
if (qtPtr->isEntitySynonymExist(lhs, PROG_LINE))
{
this->lhsWithType = INTEGER_WITH;
this->lhsEntity = PROG_LINE;
this->lhsValue = lhs;
return true;
}
}
else
{
return false;
}
}
bool WithValidator::isValidRhs(string rhs)
{
if (RegexValidators::isValidAttrRefRegex(rhs))
{
string attrRefSynonymStr = getAttrRefSynonymStr(rhs);
string attrRefAttributeStr = getAttrRefAttributeStr(rhs);
try {
Entity entity = getEntityOfSynonym(attrRefSynonymStr);
WithType withType = getWithType(entity, attrRefAttributeStr);
this->rhsWithType = withType;
this->rhsEntity = entity;
this->rhsValue = attrRefSynonymStr;
return true;
}
catch (SynonymNotFoundException& snfe) {
return false;
}
catch (AttributeNotFoundException& anfe) {
return false;
}
}
else if (RegexValidators::isValidIntegerRegex(rhs))
{
this->rhsWithType = INTEGER_WITH;
this->rhsEntity = INTEGER;
this->rhsValue = rhs;
return true;
}
else if (RegexValidators::isValidIdentWithQuotesRegex(rhs))
{
string processedrhs = Formatter::removeAllQuotes(rhs);
this->rhsWithType = STRING_WITH;
this->rhsEntity = IDENT_WITHQUOTES;
this->rhsValue = processedrhs;
return true;
}
else if (RegexValidators::isValidSynonymRegex(rhs))
{
if (qtPtr->isEntitySynonymExist(rhs, PROG_LINE))
{
this->rhsWithType = INTEGER_WITH;
this->rhsEntity = PROG_LINE;
this->rhsValue = rhs;
return true;
}
}
else
{
return false;
}
}
bool WithValidator::isLhsSameTypeAsRhs()
{
return this->lhsWithType == this->rhsWithType;
}
/*
* Returns the enum form of entity
* Throws SynonymNotFoundException when entity of synonym cannot be determined
*/
Entity WithValidator::getEntityOfSynonym(string syn)
{
if (qtPtr->isEntitySynonymExist(syn, PROCEDURE))
{
return PROCEDURE;
}
else if (qtPtr->isEntitySynonymExist(syn, STMT))
{
return STMT;
}
else if (qtPtr->isEntitySynonymExist(syn, ASSIGN))
{
return ASSIGN;
}
else if (qtPtr->isEntitySynonymExist(syn, CALL))
{
return CALL;
}
else if (qtPtr->isEntitySynonymExist(syn, WHILE))
{
return WHILE;
}
else if (qtPtr->isEntitySynonymExist(syn, IF))
{
return IF;
}
else if (qtPtr->isEntitySynonymExist(syn, VARIABLE))
{
return VARIABLE;
}
else if (qtPtr->isEntitySynonymExist(syn, CONSTANT))
{
return CONSTANT;
}
else
{
throw SynonymNotFoundException("In WithValidator.cpp, when calling getEntityOfSynonym(). Synonym cannot be found in the QueryTree and Entity cannot be assigned. Input string: " + syn);
}
}
/*
* Returns the with type given an entity
* Throws AttributeNotFoundException when attribute of entity cannot be determined
*/
WithType WithValidator::getWithType(Entity entity, string attr)
{
if (entity == PROCEDURE && RegexValidators::isValidProcNameString(attr)) {
return STRING_WITH;
}
else if (entity == STMT && RegexValidators::isValidStmtNumString(attr)) {
return INTEGER_WITH;
}
else if (entity == ASSIGN && RegexValidators::isValidStmtNumString(attr)) {
return INTEGER_WITH;
}
else if (entity == CALL && RegexValidators::isValidStmtNumString(attr)) {
return INTEGER_WITH;
}
else if (entity == CALL && RegexValidators::isValidProcNameString(attr)) {
return STRING_WITH;
}
else if (entity == WHILE && RegexValidators::isValidStmtNumString(attr)) {
return INTEGER_WITH;
}
else if (entity == IF && RegexValidators::isValidStmtNumString(attr)) {
return INTEGER_WITH;
}
else if (entity == VARIABLE && RegexValidators::isValidVarNameString(attr)) {
return STRING_WITH;
}
else if (entity == CONSTANT && RegexValidators::isValidValueString(attr)) {
return INTEGER_WITH;
}
else {
throw AttributeNotFoundException("In WithValidator.cpp, when calling getAttributeOfAttrRefAttribute(). Attribute does not match defined attribute or Entity does not have that attribute. Input Entity: " + to_string(entity) + ", Input String: " + attr);
}
}
string WithValidator::getAttrRefSynonymStr(string str)
{
return Formatter::getStringBeforeDelim(str, ".");
}
string WithValidator::getAttrRefAttributeStr(string str)
{
return Formatter::getStringAfterDelim(str, ".");
}
| true |
b4e999724439ec97259f731c5abf6463b7139094 | C++ | BuddhaCola/cpp | /m05/ex03/Bureaucrat.hpp | UTF-8 | 854 | 2.6875 | 3 | [] | no_license | #ifndef BUREAUCRAT_HPP
# define BUREAUCRAT_HPP
#include <iostream>
#include "AForm.hpp"
# define GOOD "\033[0m\033[32m"
# define BAD "\033[0m\033[31m"
# define TOOHIGH "\033[0m\033[35m"
# define TOOLOW "\033[0m\033[33m"
# define RESET "\033[0m"
class AForm;
class Bureaucrat {
protected:
const std::string _name;
int _grade;
public:
void executeForm(AForm &);
void signForm(AForm &);
const std::string getName() const;
int getGrade() const;
void upgrade();
void downgrade();
class GradeTooHighException;
class GradeTooLowException;
Bureaucrat(std::string name, int grade);
Bureaucrat();
Bureaucrat(Bureaucrat const &);
Bureaucrat &operator = (Bureaucrat &);
~Bureaucrat();
};
std::ostream & operator << (std::ostream &out, Bureaucrat const & current );
#endif // !BUREAUCRAT_HPP
| true |
fe7b96e98b4e78ee049652ec2607bf943515b030 | C++ | BEccentricity/Euegene | /comparator.cpp | UTF-8 | 944 | 3.296875 | 3 | [] | no_license | #include "comparator.h"
int str_compare_drct (struct c_string* a, struct c_string* b) {
int aPointer = 0;
int bPointer = 0;
int Diff = 0;
while (aPointer < a->Len - 1 && bPointer < b->Len - 1) {
if (!isalpha (a->Str[aPointer])) {
++aPointer;
continue;
}
if (!isalpha (b->Str[bPointer])) {
++bPointer;
continue;
}
Diff = a->Str[aPointer] - b->Str[bPointer];
if (Diff != 0) {
return Diff;
}
++aPointer;
++bPointer;
}
return b->Len - a->Len;
}
int str_compare_rvs (struct c_string* a, struct c_string* b) {
int aPointer = a->Len - 1;
int bPointer = b->Len - 1;
int Diff = 0;
while (aPointer >= 0 && bPointer >= 0) {
if (!isalpha (a->Str[aPointer])) {
--aPointer;
continue;
}
if (!isalpha (b->Str[bPointer])) {
--bPointer;
continue;
}
Diff = a->Str[aPointer] - b->Str[bPointer];
if (Diff != 0) {
return Diff;
}
--aPointer;
--bPointer;
}
return b->Len - a->Len;
} | true |
1b5537468130240540009951bf406721923ef537 | C++ | sircodesalotOfTheRound/VerbOS | /Assemblies/LoaderClasses/Types/FileInt8/FileInt8.h | UTF-8 | 445 | 2.578125 | 3 | [] | no_license | //
// Created by Reuben Kuhnert on 14/9/23.
// Copyright (c) 2014 Reuben Kuhnert. All rights reserved.
//
#ifndef __FileInt8_H_
#define __FileInt8_H_
#include <istream>
class FileInt8 {
uint8_t value_;
public:
FileInt8(std::istream& stream);
uint8_t value() const;
operator uint8_t() const;
friend std::ostream& operator<<(std::ostream& stream, const FileInt8& file_int) {
return stream << file_int.value_;
}
};
#endif //__FileInt8_H_
| true |
fc6418f76f2c8f5b15850d554df712b56071cd07 | C++ | SunTingxin/LightGuardian | /cpp/SuMax_Experiments/delay_distribution/Sketch.h | UTF-8 | 7,230 | 2.53125 | 3 | [] | no_license | #ifndef SKETCH
#define SKETCH
#include"param.h"
#include "EMFSD.h"
int get_delay_lev(unsigned delay){
rep2(i, 0, Lev_Num-1){
if(delay < delayLevThres[i]) return i;
}
return Lev_Num-1;
}
class buck{
public:
unsigned *Bin;
buck(){
Bin = new unsigned[Lev_Num];
rep2(i, 0, Lev_Num) Bin[i] = 0;
}
void insert(unsigned delay){
int delayLev = get_delay_lev(delay);
Bin[delayLev] += 1;
}
unsigned query(unsigned delay){
int lev = get_delay_lev(delay);
return Bin[lev];
}
unsigned query_all(){
int cnt = 0;
rep2(i, 0, Lev_Num) cnt += Bin[i];
return cnt;
}
~buck(){
if(Bin)delete[] Bin;
}
};
class row{
public:
buck **bucket;
BOBHash32 *bobhash;
bool *mask;
row(unsigned seed){
bucket = new buck*[Buck_Num_PerRow];
mask = new bool[Buck_Num_PerRow];
rep2(i, 0, Buck_Num_PerRow){
bucket[i] = new buck();
int randnum = rand()%100;
if(randnum < 100*collect_rate) mask[i] = 1;
else mask[i] = 0;
}
bobhash = new BOBHash32(seed);
}
~row(){
rep2(i, 0, Buck_Num_PerRow) if(bucket[i]) delete bucket[i];
if(bobhash) delete bobhash;
delete bucket;
}
int get_hash(const flow_t flow){
return bobhash->run((char*)&flow, 13) % Buck_Num_PerRow;
}
void insert(const flow_t flow, const unsigned delay){
int pos = get_hash(flow);
bucket[pos]->insert(delay);
}
int query(const flow_t flow, const unsigned delay){
int pos = get_hash(flow);
//cout << "pos " << pos << endl;
if(mask[pos])return (int)bucket[pos]->query(delay);
else return -1;
}
int query_all(const unsigned pos){
return (int)bucket[pos]->query_all();
}
};
class halfCUSketch{
public:
row **Row;
halfCUSketch(){
Row = new row*[Row_Num];
rep2(i, 0, Row_Num){
Row[i] = new row((unsigned)i);
}
}
~halfCUSketch(){
rep2(i, 0, Row_Num) if(Row[i]) delete Row[i];
if(Row) delete Row;
}
void insert(const flow_t flow, const unsigned delay){
unsigned Min = 0x5fffffff;
rep2(i, 0, Row_Num){
unsigned curr = Row[i]->query(flow, delay);
//cout << "curr " << curr << endl;
if(curr <= Min){
Row[i]->insert(flow, delay);
Min = curr;
}
}
}
int query(const flow_t flow, const unsigned delay){
int Min = 0x1fffffff;
bool flag = 0;
rep2(i, 0, Row_Num){
int curr = Row[i]->query(flow, delay);
if(curr != -1){
flag = 1;
if(curr <= Min) Min = curr;
}
}
if(flag) return Min;
else return -1;
}
unsigned query_lev(const flow_t flow, const int lev){
unsigned Min = 0x5fffffff;
bool flag = 0;
rep2(i, 0, Row_Num){
int pos = Row[i]->get_hash(flow);
bool status = Row[i]->mask[pos];
if(status){
int curr = Row[i]->bucket[pos]->Bin[lev];
if(curr <= Min) Min = curr;
flag = 1;
}
}
if(flag) return Min;
else return -1;
}
int get_cardinality(){
double zero_cnt = 0;
rep2(i, 0, Buck_Num_PerRow){
if(Row[0]->query_all((unsigned)i) == 0) zero_cnt += 1;
}
return (int)((double)Buck_Num_PerRow * log(Buck_Num_PerRow/(double)zero_cnt));
}
void get_distribution(vector<double> &dist, vector<double> &mice_dist){
int Maxrec = 0;
uint32_t temp[Buck_Num_PerRow];
rep2(i, 0, Buck_Num_PerRow){
if(Row[0]->query_all((unsigned)i) > Maxrec) Maxrec = Row[0]->query_all((unsigned)i);
temp[i] = Row[0]->query_all((unsigned)i);
}
mice_dist.resize(Maxrec + 1);
rep2(i, 0, Buck_Num_PerRow){
int flowsizetmp = Row[0]->query_all((unsigned)i);
mice_dist[flowsizetmp]++;
}
EMFSD *em_fsd_algo = new EMFSD();
em_fsd_algo->set_counters(Buck_Num_PerRow, temp);
rep2(i, 0, 10){
cout << "epoch " << i << endl;
em_fsd_algo->next_epoch();
}
dist = em_fsd_algo->ns;
}
void get_entropy(int &tot, double &entr, vector<double> &mice_dist)
{
for (int i = 1; i < mice_dist.size(); i++){
tot += mice_dist[i] * i;
entr += mice_dist[i] * i * log2(i);
}
}
};
class CMSketch{
public:
row **Row;
CMSketch(){
Row = new row*[Row_Num];
rep2(i, 0, Row_Num){
Row[i] = new row((unsigned)i);
}
}
~CMSketch(){
rep2(i, 0, Row_Num) if(Row[i]) delete Row[i];
if(Row) delete Row;
}
void insert(const flow_t flow, const unsigned delay){
rep2(i, 0, Row_Num){
Row[i]->insert(flow, delay);
}
}
unsigned query(const flow_t flow, const unsigned delay){
unsigned Min = 0x5fffffff;
rep2(i, 0, Row_Num){
unsigned curr = Row[i]->query(flow, delay);
if(curr <= Min) Min = curr;
}
return Min;
}
unsigned query_lev(const flow_t flow, const int lev){
unsigned Min = 0x5fffffff;
rep2(i, 0, Row_Num){
int pos = Row[i]->get_hash(flow);
unsigned curr = Row[i]->bucket[pos]->Bin[lev];
if(curr <= Min) Min = curr;
}
return Min;
}
};
class CUSketch{
public:
row **Row;
CUSketch(){
Row = new row*[Row_Num];
rep2(i, 0, Row_Num){
Row[i] = new row((unsigned)i);
}
}
~CUSketch(){
rep2(i, 0, Row_Num) if(Row[i]) delete Row[i];
if(Row) delete Row;
}
void insert(const flow_t flow, const unsigned delay){
unsigned Min = 0x5fffffff;
rep2(i, 0, Row_Num){
unsigned curr = Row[i]->query(flow, delay);
//cout << "curr " << curr << endl;
if(curr < Min){
Min = curr;
}
}
rep2(i, 0, Row_Num){
unsigned curr = Row[i]->query(flow, delay);
if(curr == Min) Row[i]->insert(flow, delay);
}
}
unsigned query(const flow_t flow, const unsigned delay){
unsigned Min = 0x5fffffff;
rep2(i, 0, Row_Num){
unsigned curr = Row[i]->query(flow, delay);
if(curr <= Min) Min = curr;
}
return Min;
}
unsigned query_lev(const flow_t flow, const int lev){
unsigned Min = 0x5fffffff;
rep2(i, 0, Row_Num){
int pos = Row[i]->get_hash(flow);
unsigned curr = Row[i]->bucket[pos]->Bin[lev];
if(curr <= Min) Min = curr;
}
return Min;
}
};
#endif | true |
1a0eece9bbc5239d3335cb67411bb4f55665146a | C++ | blackkaiserxjc/kraken | /libs/io/src/kr/io/compression.cpp | UTF-8 | 2,526 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by kaiser on 2021/1/2.
//
#include "compression.h"
#include <fmt/format.h>
#include <stdexcept>
namespace kr {
namespace io{
compression::compression(CompressType type, std::optional<int> level)
: type_(type)
{
}
std::string compression::compress(std::string_view data)
{
return {};
}
std::string compression::decompress(std::string_view data)
{
return {};
}
class gzip_compression : public compression
{
public:
static std::unique_ptr<compression> create(int level, CompressType type);
explicit gzip_compression(int level, CompressType type);
private:
};
class lzma_compression : public compression
{
public:
static std::unique_ptr<compression> create(int level, CompressType type);
explicit lzma_compression(int level, CompressType type);
private:
};
class bzip2_compression : public compression
{
public:
static std::unique_ptr<compression> create(int level, CompressType type);
explicit bzip2_compression(int level, CompressType type);
private:
};
class zstd_compression : public compression
{
public:
static std::unique_ptr<compression> create(int level, CompressType type);
explicit zstd_compression(int level, CompressType type);
private:
};
class zlib_compression : public compression
{
public:
static std::unique_ptr<compression> create(int level, CompressType type);
explicit zlib_compression(int level, CompressType type);
private:
};
using codec_factory = std::function<std::unique_ptr<compression>(int, CompressType)>;
struct factory
{
codec_factory codec;
};
constexpr factory codec_factorys[static_cast<size_t>(CompressType::NUM_TYPES)] =
{
{},
{gzip_compression::create},
{lzma_compression::create},
{bzip2_compression::create},
{zstd_compression::create},
{zlib_compression::create},
};
factory const &get_factory(CompressType type)
{
auto const idx = static_cast<size_t>(type);
if (idx >= static_cast<size_t>(CompressType::NUM_TYPES))
{
throw std::invalid_argument(fmt::format("compression type {} invaild.", idx));
}
return codec_factorys[idx];
}
std::unique_ptr<compression> make_compression(CompressType type, int level)
{
auto const factory = get_factory(type).codec;
if (!factory)
{
throw std::invalid_argument(fmt::format("compression type {} not supported.",
static_cast<size_t>(type)));
}
auto codec = (*factory)(level, type);
return codec;
}
} // namespace utility
} // namespace kr | true |