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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cd817a0d0b2d4c261bf17d92296d616cc9e154af | C++ | RadionaOrg/LoRa_Fuzine | /tilt/tilt.ino | UTF-8 | 807 | 3.0625 | 3 | [] | no_license | //KY017 Mercury open optical module
int Led = 2 ;// define LED Interface
int buttonpin = 4; // define the mercury tilt switch sensor interface
int val ;// define numeric variables val
int count = 0;
bool state, prevState;
void setup ()
{
pinMode (Led, OUTPUT) ;// define LED as output interface
pinMode (buttonpin, INPUT) ;// define the mercury tilt switch sensor output interface
Serial.begin(115200);
}
void loop ()
{
val = digitalRead (buttonpin) ;// read the values assigned to the digital interface 3 val
if (val == LOW){
state = true;
if( state != prevState ){
count ++;
Serial.println(count);
digitalWrite (Led, HIGH);
prevState = state;
delay(1000);
}
}
else{
digitalWrite (Led, LOW);
state = false;
prevState = false;
}
}
| true |
21e92400c586a16345f52669a03ccee5f0e60ccc | C++ | Sumit1608/CodingNinjas-C-Foundation-Solution | /Lecture 10/Print like a wave.cpp | UTF-8 | 606 | 3.40625 | 3 | [] | no_license | #include<iostream>
using namespace std;
void printWave(int arr[][100],int row, int column){
int m = row, n = column;
for(int j=0; j<n; j++){
if(j%2 == 0){
for(int i=0; i<m; i++){
cout<<arr[i][j]<<" ";
}
}
else{
for(int i=m-1 ; i>=0; i--){
cout<<arr[i][j]<<" ";
}
}
}
}
int main(){
int arr[100][100];
int m,n;
cout<<"Enter the no of rows and columns : ";
cin>>m>>n;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
cin>>arr[i][j];
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
printWave(arr,m,n);
}
| true |
7bdcdd8c9b488f442dddec4051aa62221b622297 | C++ | ngaarrr/LearningCPP | /Practice/Session13/struct.cpp | UTF-8 | 504 | 3.84375 | 4 | [] | no_license | #include <iostream>
struct Students
{
std::string name;
int age;
int grade;
};
int main()
{
Students student1;
student1.name = "negar";
student1.age = 17;
student1.grade = 12;
std::cout << "Name: " << student1.name << std::endl;
std::cout << "Age: " << student1.age << std::endl;
std::cout << "Grade: " << student1.grade << std::endl;
Students student[3];
student[0].name = "Negar";
student[1].age = 17;
student[2].grade = 12;
return 0;
}
| true |
5b0c65cdb91ab2589be44ec7ddfd6fe9d972d39a | C++ | SaulZhang/Algorithm-Templates | /1-PAT专题训练/STL应用/1054.cpp | UTF-8 | 559 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int n,m,x;
vector<int>Vec;
unordered_map<int,int> Ma;
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin>>x;
if(Ma.count(x)==0)
Vec.push_back(x);
Ma[x]++;
}
}
int maxNum=0,ans;
for(int i=0;i<Vec.size();i++){
if(Ma[Vec[i]]>maxNum)
maxNum = Ma[Vec[i]],ans=Vec[i];
}
cout<<ans<<endl;
return 0;
}
| true |
7141a4a55a4818e583e81b5bb99a2c22892e8a4d | C++ | buptlxb/leetcode | /1st/rotate_list.cpp | UTF-8 | 1,747 | 3.625 | 4 | [] | no_license | #include <iostream>
using std::cout;
using std::endl;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (!head || !head->next)
return head;
int n = lenof(head);
k %= n;
if (!k)
return head;
head = reverse(head, 0, n-k-1);
head = reverse(head, n-k, n-1);
head = reverse(head, 0, n-1);
return head;
}
ListNode *reverse(ListNode *head, int m, int n) {
if (!head || !head->next || m == n)
return head;
ListNode helper(-1);
helper.next = head;
ListNode *pos = &helper;
int i;
for (i = 0; i < m; ++i) {
pos = pos->next;
}
ListNode *in = pos->next;
while (i < n) {
ListNode *tmp = in->next;
in->next = tmp->next;
tmp->next = pos->next;
pos->next = tmp;
++i;
}
return helper.next;
}
int lenof(ListNode *head) {
int ret = 0;
while (head) {
++ret;
head = head->next;
}
return ret;
}
};
void print_list(ListNode *head)
{
if (!head)
return;
cout << head->val;
head = head->next;
while (head) {
cout << "->" << head->val;
head = head->next;
}
cout << endl;
}
int main(void)
{
ListNode n1(1);
ListNode n2(2);
ListNode n3(3);
ListNode n4(4);
ListNode n5(5);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
ListNode *ret = Solution().rotateRight(&n1, 2);
print_list(ret);
return 0;
}
| true |
662f91bda6f59bc22987e4cef68dccad5cd387cd | C++ | quzery/Leetcode2019 | /26.删除排序数组中的重复项.cpp | UTF-8 | 489 | 2.90625 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=26 lang=cpp
*
* [26] 删除排序数组中的重复项
*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() == 0){
return 0;
}
int i = 0, j = 0;
while(i<nums.size()-1){
if(nums[i] == nums[i+1]){
i++;
}
else{
nums[++j] = nums[++i];
}
}
//size = j + 1;
return j+1;
}
};
| true |
983014cac8afbe1a6c9d4ecc60a0e963bba8b2cf | C++ | CM4all/beng-proxy | /src/pool/StringBuilder.hxx | UTF-8 | 588 | 2.71875 | 3 | [] | permissive | // SPDX-License-Identifier: BSD-2-Clause
// Copyright CM4all GmbH
// author: Max Kellermann <mk@cm4all.com>
#pragma once
#include "AllocatorPtr.hxx"
#include "util/StaticVector.hxx"
#include <string_view>
template<size_t MAX>
class PoolStringBuilder {
StaticVector<std::string_view, MAX> items;
public:
void push_back(std::string_view s) noexcept {
items.push_back(s);
}
template<typename... Args>
void emplace_back(Args&&... args) noexcept {
items.emplace_back(std::forward<Args>(args)...);
}
char *operator()(AllocatorPtr alloc) const noexcept {
return alloc.Concat(items);
}
};
| true |
07952623bbcd36d42be6f68580ee3f7cc8d733dd | C++ | miguelsantoss/AVT1516 | /src/PerspectiveCamera.cpp | UTF-8 | 1,221 | 2.625 | 3 | [] | no_license | #include "PerspectiveCamera.h"
#include "Camera.h"
#include "GameManager.h"
#include <stdio.h>
PerspectiveCamera::PerspectiveCamera(float fov, float ratio, float dnear, float dfar) {
_fov = fov;
_ratio = ratio;
_near = dnear;
_far = dfar;
}
PerspectiveCamera::~PerspectiveCamera() {}
void PerspectiveCamera::update(float posX, float posY, float posZ, float eyeX, float eyeY, float eyeZ, float upX, float upY, float upZ) {
loadIdentity(PROJECTION);
perspective(53.13f, 1.0f, 0.1f, 1000.0f);
loadIdentity(VIEW);
loadIdentity(MODEL);
lookAt(posX, posY, posZ,
eyeX, eyeY, eyeZ,
upX, upY, upZ);
}
void PerspectiveCamera::computeProjectionMatrix() {
/*glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(_fov, _aspect, _near, _far);*/
loadIdentity(PROJECTION);
perspective(_fov, _ratio, _near, _far);
loadIdentity(VIEW);
loadIdentity(MODEL);
lookAt(-5, 10, -5,
10, 0, 10,
1, 0, 1);
}
void PerspectiveCamera::computeVisualizationMatrix(double eyeX, double eyeY, double eyeZ, double targetX, double targetY, double targetZ, double upX, double upY, double upZ) {
/*glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(eyeX, eyeY, eyeZ, targetX, targetY, targetZ, upX, upY, upZ);*/
}
| true |
45ed63c099d71c8530dc29be1ed64ee5438d0571 | C++ | Hung150/Lab8 | /Excercise4.cpp | UTF-8 | 688 | 3.28125 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
int main(){
float x,y;
printf("enter the coordinates x");
scanf("%f", &x);
printf("enter the coordinates y");
scanf("%f", &y);
if(fmin(x,y)>0){
printf("the point is in the first quadrant");
}else
{
if(fmax(x,y)<0){
printf("the point is in the third quadrant");
}else
{
if((x < 0)&&(y > 0)){
printf("the point is in the second quadrant");
}else
{
printf("the point is in the fourth quadrant");
}
}
}
return 0;
}
| true |
27c7ce20e9d182d6cf3a6898d1c4312c68a23eab | C++ | JakMobius/mipt | /sem_1/course_algorithms/hw_contest_4/D.cpp | UTF-8 | 8,258 | 3.5 | 4 | [
"MIT"
] | permissive | /*
Даны n отрезков на прямой. Пара отрезков называются вложенной, если отрезки не совпадают, и один отрезок содержит второй. Посчитать количество пар вложенных отрезков.
*/
#include <cstdlib>
#include <cstdio>
#include <climits>
template <typename T>
const T &min(const T &first, const T &second) {
return first < second ? first : second;
}
template <typename T>
const T &max(const T &first, const T &second) {
return second < first ? first : second;
}
#ifndef GENERAL_VECTOR
#define GENERAL_VECTOR
#include <stdexcept>
template <typename T>
class Vector {
private:
T *buffer;
size_t cur_size;
size_t capacity;
void realloc_bufer(const size_t new_capacity) {
capacity = new_capacity;
T* ptr = (T*) realloc(buffer, capacity * sizeof(T));
if (!ptr) {
throw std::length_error("[ERR]<vector>: realloc fail");
}
buffer= ptr;
}
public:
Vector (const Vector& other) = delete;
Vector& operator=(const Vector& other) = delete;
Vector() :
buffer(nullptr),
cur_size(0),
capacity(0)
{}
void ctor() {
capacity = 32;
buffer = (T*) malloc(capacity * sizeof(T));
cur_size = 0;
}
static Vector<T> *NEW() {
Vector<T> *cake = (Vector<T>*) calloc(1, sizeof(Vector<T>));
if (!cake) {
return nullptr;
}
cake->ctor();
return cake;
}
Vector(const size_t size_) :
buffer(nullptr),
cur_size(0),
capacity(0)
{}
void ctor(const size_t size_) {
capacity = cur_size * 2;
buffer = (T*) calloc(capacity, sizeof(T));
cur_size = size_;
}
static Vector<T> *NEW(const size_t size_) {
Vector<T> *cake = (Vector<T>*) calloc(1, sizeof(Vector<T>));
if (!cake) {
return nullptr;
}
cake->ctor(size_);
return cake;
}
~Vector() {}
void dtor() {
cur_size = 0;
free(buffer);
}
static void DELETE(Vector<T> *vector) {
if (!vector) {
return;
}
vector->dtor();
free(vector);
}
T &operator[](const size_t i) const {
if (i >= cur_size) {
throw std::length_error("[ERR]<vector>: index overflow");
}
return buffer[i];
}
T &push_back(const T &val) {
if (cur_size + 1 == capacity) {
realloc_bufer(capacity * 2);
}
return buffer[cur_size++] = val;
}
T &pop_back() {
if (cur_size == 0) {
throw std::length_error("[ERR]<vector>: pop underflow");
}
return buffer[--cur_size];
}
size_t size() const {
return cur_size;
}
void quadratic_pointer_sort() {
bool flag = false;
for (size_t i = 0; i < size(); ++i) {
for (size_t j = 0; j < size(); ++j) {
if (*buffer[i] > *buffer[j]) {
T tmp = buffer[i];
buffer[i] = buffer[j];
buffer[j] = tmp;
flag = true;
}
}
if (!flag) {
return;
}
}
}
bool contains(const T &item) const {
for (size_t i = 0; i < size(); ++i) {
if (buffer[i] == item) {
return true;
}
}
return false;
}
void print_as_ints() const {
if (!size()) {
return;
}
for (size_t i = 0; i < size() - 1; ++i) {
printf("%d ", (*this)[i]);
}
printf("%d", (*this)[size() - 1]);
}
};
#endif // GENERAL_VECTOR
template <typename T, typename T_OP, typename T_REV>
class FenvikTree {
private:
T *buffer;
size_t size;
T neutral;
const T get(int i) {
T ret = neutral;
for (; i >= 0; i = (i & (i + 1)) - 1) {
ret = T_OP()(ret, buffer[i]);
}
return ret;
}
public:
FenvikTree () {}
~FenvikTree() {}
void ctor(const T *arr, const size_t arr_size, const T &neutral_) {
buffer = (T*) calloc(arr_size + 1, sizeof(T));
size = arr_size;
neutral = neutral_;
if (arr) {
for (int i = 0; i < size; ++i) {
set(i, arr[i]);
}
}
}
void dtor() {
free(buffer);
}
const T &operator[](int i) {
if (i >= size) {
throw "Bad index";
}
return get(i, i);
}
void upd(int i, const T &val) {
for (; i < size; i |= i + 1) {
buffer[i] = T_OP()(buffer[i], val);
}
}
void set(int i, const T &val) {
T delta = T_REV()(val, get(i, i));
upd(i, delta);
}
T get(int l, int r) {
return T_REV()(get(r), get(l - 1));
}
void dump() {
for (int i = 0; i < size; ++i) {
printf("%lld ", buffer[i]);
}
printf("\n");
}
};
struct functor_sum {
public:
long long operator()(long long a, long long b) {
return a + b;
}
};
struct functor_sub {
public:
long long operator()(long long a, long long b) {
return a - b;
}
};
struct Segment {
long long x;
long long y;
long long cnt;
Segment() {
x = 0;
y = 0;
cnt = 0;
}
Segment(long long x_, long long y_) {
x = x_;
y = y_;
cnt = 1;
}
bool operator<(const Segment &other) {
if (x < other.x) {
return true;
} else if (x > other.x) {
return false;
}
if (cnt * y < cnt * other.y) {
return false;
} else if (cnt * y > cnt * other.y) {
return true;
}
return false;
}
void swap_sides() {
long long tmp = y;
y = x;
x = tmp;
//cnt *= -1;
}
};
template <typename T>
void merge(T *arr, const int left, const int middle, const int right, T *buffer) {
int i = 0;
int j = 0;
while (i < middle - left && j < right - middle) {
if (arr[left + i] < arr[middle + j]) {
buffer[left + i + j] = arr[left + i];
++i;
} else {
buffer[left + i + j] = arr[middle + j];
++j;
}
}
while(i < middle - left) {
buffer[left + i + j] = arr[left + i];
++i;
}
while (j < right - middle) {
buffer[left + i + j] = arr[middle + j];
++j;
}
for (int i = left; i < right; ++i) {
arr[i] = buffer[i];
}
}
template <typename T>
void do_merge_sort(T *arr, const int left, const int right, T *buffer) {
if (right - left <= 1) { return; }
int middle = (left + right) / 2;
do_merge_sort(arr, left, middle, buffer);
do_merge_sort(arr, middle, right, buffer);
merge(arr, left, middle, right, buffer);
}
template <typename T>
void merge_sort(T *arr, const size_t arr_size) {
T *buffer = (T*) malloc(arr_size * sizeof(T));
do_merge_sort(arr, 0, arr_size, buffer);
free(buffer);
}
// Отсортируем отрезки по левому концу, а правые их концы заменим на 1..n, чтобы через фенвика
// считать кол-во отрезков с ПК (правыми концами) левее ПК текущего отрезка. Это даст нам возможность
// считать кол-во отрезков вложенных в данный, т.к. из итерироваться мы будем слева направо, значит
// чтобы отрезок был вложен наш, хватит того, что его ПК <= нашему
int main() {
int n = 0;
scanf("%d", &n);
Segment *arr = (Segment*) calloc(n, sizeof(Segment));
for (int i = 0; i < n; ++i) {
long long x, y;
scanf("%lld %lld", &x, &y);
arr[i] = Segment(y, x);
}
merge_sort(arr, n);
// printf("-----\n");
// for (int i = 0; i < n; ++i) {
// printf("%lld %lld\n", arr[i].x, arr[i].y);
// }
long long last = arr[0].x;
long long max_r = 0;
for (int i = 0; i < n; ++i) {
Segment &sg = arr[i];
if (sg.x != last) {
++max_r;
}
last = sg.x;
sg.x = max_r;
sg.swap_sides();
}
merge_sort(arr, n);
Vector<Segment> a; // awful way not to think about segment duplicats
a.ctor();
a.push_back(arr[0]);
Segment *pr = &a[0];
for (int i = 1; i < n; ++i) {
if (pr->x == arr[i].x && pr->y == arr[i].y) {
pr->cnt += 1;
} else {
a.push_back(arr[i]);
pr = &a[a.size() - 1];
}
}
FenvikTree<long long, functor_sum, functor_sub> tree;
tree.ctor(nullptr, max_r + 10, 0);
FenvikTree<long long, functor_sum, functor_sub> tree_l;
tree_l.ctor(nullptr, max_r + 10, 0);
for (int i = 0; i < a.size(); ++i) {
Segment &sg = a[i];
tree.upd(sg.y, sg.cnt);
tree_l.upd(sg.x, sg.cnt);
}
long long cnt = 0;
for (int i = 0; i < a.size(); ++i) {
Segment &sg = a[i];
//printf("[%lld %lld] - %lld\n", sg.x, sg.y, sg.cnt);
tree.upd(sg.y, -sg.cnt);
tree_l.upd(sg.x, -sg.cnt);
cnt += tree.get(0, sg.y) * sg.cnt;
//cnt -= min(tree_l.get(sg.x, sg.x), tree.get(sg.y, sg.y));
}
printf("%lld\n", cnt);
return 0;
}
// O(O) | true |
e30e120b2751e92ca536a52b7f676a231aca88d3 | C++ | tomsloj/PSZT-rozdzielanie-ciastek | /src/main.cpp | UTF-8 | 7,939 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <random>
#include <tuple>
#include <cfloat>
#include <climits>
#include "EvolutionarySolution.hpp"
#include "IterativeSolution.hpp"
#include "TestGenerator.hpp"
using namespace std;
const int NUMBER_OF_TESTS = 15;
const int NUMBER_OF_SEEDS = 5;
const std::string FILE_NAME_BASE = "./in/input";
const std::string FILE_NAME_BASE_EXTENSION = ".txt";
const int NUMBER_OF_VERSIONS = 3;
const int DEFAULT_POPULATION_SIZE = 15;
const double DEFAULT_MUTATION_FACTOR = 0.05;
const int DEFAULT_MUTATION_VERSION = 1;
const int DEFAULT_PERIOD = 10000;
const int DEFAULT_TIMES = 35;
const int NUMBER_OF_MUTATION_FACTOR_TESTS = 8;
const int NUMBER_OF_POPULATION_TESTS = 3;
//najlepsze parametry
const int BEST_VERSION = 1;
const double BEST_MUTATION_FACTOR = 1.6;
const int BEST_POPULATION_SIZE = 5;
void tests(int times, int propabilityBase, int populationBase, vector<int>versions);
void run();
vector<int> readFile(string fileName);
vector<int> readStdin();
pair<long long, long long> parseResault(std::chrono::steady_clock::time_point begin, std::chrono::steady_clock::time_point end, int result);
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
int times = DEFAULT_TIMES;
int propabilityBase = DEFAULT_MUTATION_FACTOR;
int populationBase = DEFAULT_POPULATION_SIZE;
vector<int>versions;
bool gMode = false; //czy uruchomic tryb generowania testow
bool tMode = false; //czy uruchomic tryb testowania
bool rMode = false; //czy uruchomic tryb uruchamiania najlepszego rozwiazania
//analiza flag
for(int i = 1; i < argc; i+=2 )
{
if(i+1 < argc)
{
switch(argv[i][1])
{
case 'g'://wlaczenie generowania testow
//generujemy testy
gMode = true;
--i;
break;
case 't': //tests - tryb uruchomienia testowania paramertow
tMode = true;
--i;
break;
case 'r': //run - tryb uruchomienia z ustawionymi przez nas najlepszymi parametrami
rMode = true;
break;
case 'p': //period - liczba okresow w ktorych zbieramy wyniki wynikow
if(stoi(argv[i+1]) <= 0)
{
cout << "ilosc razy musi byc wiekszy od 0\n";
return 0;
}
else
{
times = stoi(argv[i+1]);
}
break;
case 'm': //wspolczynnik mutacji
if(stof(argv[i+1]) <= 0)
{
cout << "wspolczynnik mutacji musi byc wiekszy od 0\n";
return 0;
}
else
{
propabilityBase = stof(argv[i+1]);
}
break;
case 'v': //wersja mutacji - wersje mutacji z ktorymi wykonywac testy
if(stoi(argv[i+1]) > NUMBER_OF_VERSIONS || stoi(argv[i+1]) < 0)
{
cout << "nie ma takiej wersji mutacji\n";
return 0;
}
else
{
versions.push_back(stoi(argv[i+1]));
}
break;
}
}
else
if(argv[i][1] == 'g') //wlaczenie generowania testow
{
//generujemy testy
gMode = true;
--i;
}
else
if(argv[i][1] == 't') //tests - tryb uruchomienia testowania paramertow
{
tMode = true;
--i;
}
else
if(argv[i][1] == 'r') //run - tryb uruchomienia z ustawionymi przez nas najlepszymi parametrami
{
rMode = true;
}
else
{
cout << "bledna liczba parametrow wykonania\n";
return 0;
}
}
if(gMode)
{
TestGenerator::generateTests();
}
if(tMode)
{
tests(times, propabilityBase, populationBase, versions);
}
if(rMode)
{
run();
}
}
//uruchomienie testow
void tests(int times, int propabilityBase, int populationBase, vector<int>versions)
{
int period = DEFAULT_PERIOD;
//wywoloanie iteracyjne
pair<long long, long long> iterationResults[NUMBER_OF_TESTS];
for( int i = 0; i < NUMBER_OF_TESTS; ++i )
{
//wczytanie pliku z danymi testowymi
vector<int> marks = readFile(FILE_NAME_BASE + to_string(i) + FILE_NAME_BASE_EXTENSION);
//znalezienie rozwiazania dla wywolania iteracyjnego
IterativeSolution iSolution(marks);
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
iSolution.runSolution();
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
iterationResults[i] = parseResault(begin, end, iSolution.getResult());
}
/***************************************************
* rozwiazania ewolucyjne
***************************************************/
//miejsce na zapisywanie wynikow ewolucyjnych
//dla kazdego pliku [] przechowujemy wektor roznych caseow testowania
//w kazdym vectorze - vector wynikow
vector< vector<MileStone> > results[NUMBER_OF_TESTS * NUMBER_OF_SEEDS];
//nazwy kolejnych plikow
vector<string> fileNames;
//labels
vector<string> labels;
for( int i = 0; i < NUMBER_OF_TESTS; ++i )
{
//wczytanie pliku z danymi testowymi
vector<int> marks = readFile(FILE_NAME_BASE + to_string(i) + FILE_NAME_BASE_EXTENSION);
propabilityBase = DEFAULT_MUTATION_FACTOR;
for(int j = 1; j <= NUMBER_OF_MUTATION_FACTOR_TESTS; ++j )
{
populationBase = DEFAULT_POPULATION_SIZE;
for(int k = 1; k <= NUMBER_OF_POPULATION_TESTS; ++k)
{
for(int version : versions)
{
if( i == 0 ) // dodajemy kolejna nazwe pliku
{
fileNames.push_back("./out/outV" + to_string(version) + "m" + to_string(propabilityBase) + "p" + to_string(populationBase) + ".txt" );
labels.push_back("wersja nr " + to_string(version) + ";wspolczynnik mutacji " + to_string(propabilityBase) +
";wielkosc populacji " + to_string(populationBase) );
}
for( int l = 0; l < NUMBER_OF_SEEDS; ++l ) // zmienne seedy
{
//uruchamiamy rozwizanie ewolucyjne
EvolutionarySolution eSolution(marks, populationBase, propabilityBase);
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
eSolution.runSolution(version, l, begin, period, times);
results[NUMBER_OF_SEEDS * i + l].push_back(eSolution.getMilestones());
}
}
populationBase *= 2;
}
propabilityBase *= 2;
}
}
//wypisujemy rozwiazanie iteracyjne
fstream itFile;
itFile.open("./out/outIt.txt", ios::out);
if(itFile.good())
{
itFile << "iteracyjne wynik\tczas\n";
for(pair<long long, long long> p : iterationResults)
{
itFile << p.first << "\t" << p.second <<"\n";
}
}
//wypisujemy rozwiazania ewolucyjne
for(unsigned int i = 0; i < fileNames.size(); ++i )
{
fstream evFile;
evFile.open(fileNames[i], ios::out);
if(evFile.good())
{
evFile << labels[i] << "\n";
for(int j = 0; j < NUMBER_OF_TESTS * NUMBER_OF_SEEDS; ++j)
{
for(unsigned int k = 0; k < results[j][i].size(); ++k )
{
evFile << results[j][i][k].generations << "\t" << results[j][i][k].time << "\t" << results[j][i][k].result <<"\t";
}
evFile << "\n";
}
}
}
}
//uruchamiamy rozwiazanie z najlepszymi parametrami
void run()
{
//wczytujemy oceny ze standardowego wejscia
vector<int> marks = readStdin();
EvolutionarySolution eSolution(marks, BEST_POPULATION_SIZE, BEST_MUTATION_FACTOR);
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
eSolution.runSolution(BEST_VERSION, 0, begin, DEFAULT_PERIOD, DEFAULT_TIMES);
eSolution.writeResult();
}
//wczytujemy wejscie z pliku
vector<int> readFile(string fileName)
{
vector<int> v;
ifstream file;
file.open (fileName);
int word;
while (file >> word)
{
v.push_back(word);
}
return v;
}
//wczytujemy wejscie ze standardowego wejscia
vector<int> readStdin()
{
vector<int> v;
int number;
string s;
getline(std::cin, s);
std::stringstream iss( s );
while ( iss >> number )
{
v.push_back( number );
}
return v;
}
pair<long long, long long> parseResault(std::chrono::steady_clock::time_point begin, std::chrono::steady_clock::time_point end, int result)
{
return make_pair(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(), result);
} | true |
8e9059c716f582bdc72360048112f24c197d4f10 | C++ | moyin1004/learning | /TimeLine/20190218/netlib/v3/Thread.h | UTF-8 | 650 | 2.65625 | 3 | [] | no_license | /// @file Thread.h
/// @author moyin(moyin1004@163.com)
/// @data 2019-02-10 11:04:57
#ifndef __THREAD_H__
#define __THREAD_H__
#include "Noncopyable.h"
#include <pthread.h>
#include <functional>
namespace wd {
class Thread
:Noncopyable
{
public:
using ThreadCallback = std::function<void()>;
Thread(ThreadCallback &&);
~Thread();
void start();
void join();
bool isRunning() const { return _isRunning; }
pthread_t getThreadID() const { return _pthid; }
private:
static void *threadFunc(void *);
ThreadCallback _callback;
pthread_t _pthid;
bool _isRunning;
};
} //end of namespace wd
#endif
| true |
70c72494531b906dea8301cd9cb7ace847e69764 | C++ | Dj0ulo/UniTag | /UniTag.cpp | UTF-8 | 3,627 | 2.84375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include "Utils.h"
#include "UniTag.h"
using namespace std;
using namespace UniTag;
using namespace utils;
UniTag::Frame::Frame()
{
}
UniTag::Frame::Frame(const std::string &flag_, const std::vector <char> &data_)
{
data = data_;
flag = flag_;
}
bool UniTag::Frame::operator == (const std::string& flag_) const
{
return utils::absEquals(flag, flag_);
}
UniTag::Chunk::Chunk()
{
pos = 0;
size = 0;
}
UniTag::Chunk::Chunk(const unsigned int pos_, const unsigned int size_)
{
pos = pos_;
size = size_;
}
unsigned int UniTag::Chunk::end() const
{
return pos + size;
}
Tag::Tag(const std::string path)
{
_path = path;
_state = Tag::INIT;
_posEndTag = 0;
_fileSize = 0;
_bitrate = 0;
_samplerate = 0;
_duration = (unsigned int)-1;
}
std::string Tag::getPath() const
{
return _path;
}
std::vector <unsigned int> Tag::getFramesIndexes(const std::string flag) const
{
std::vector <unsigned int> result;
auto it = _frames.begin();
while( (it = find(it,_frames.end(),flag)) != _frames.end() )
{
result.push_back(it - _frames.begin());
it++;
}
return result;
}
unsigned int Tag::getFramesNumber() const
{
return _frames.size();
}
std::string Tag::get(const unsigned int flag) const
{
return get(getFrameFlag(flag));
}
std::string Tag::getType() const {return _type;}
unsigned int Tag::getBitRate() const {return _bitrate;}
unsigned int Tag::getSamplingRate() const {return _samplerate;}
unsigned int Tag::getState() const {return _state;}
size_t Tag::getSize() const {return _posEndTag;}
size_t Tag::getFileSize() const {return _fileSize;}
void Tag::deleteFrame(const unsigned int flag)
{
for(unsigned int i=0;i<_frames.size();i++)
if(_frames[i].flag == getFrameFlag(flag))
{
_frames.erase(_frames.begin() + i);
i--;
}
}
void Tag::set(const std::string &flag, const std::vector <char> &data)
{
auto it = find(_frames.begin(), _frames.end(), flag);
if(it == _frames.end())
_frames.push_back(Frame(flag, data));
else
it->data = data;
}
void Tag::printAllFrames() const
{
cout<<"--------------------"<<endl;
cout<<"> Path : "<<_path<<endl;
cout<<"> Tag type : "<<getType();
if(getType() == "ID3")
cout<<" 2."<<((UniTag::ID3v2*)this)->getMajorVersion();
cout<<endl;
cout<<"There is "<<_frames.size()<<" frame(s)"<<endl;
for(int i=0;i<_frames.size();i++)
cout<<"> "<<_frames[i].flag<<" : "<<parseFrameWidthIndex(i)<<endl;
cout<<"--------------------"<<endl;
}
///////////////////////////////////////////////////////////////////////////////////////////
std::vector <std::string> UniTag::getReadableFileType()
{
return {"ogg", "flac", "m4a", "m4p", "3gp", "mp3"};
}
bool UniTag::isFileTypeReadable(const std::string &path)
{
auto types = getReadableFileType();
std::string ext = getExtension(path);
std::transform(ext.begin(), ext.end(),ext.begin(), ::tolower);
if (find(types.begin(),types.end(),ext)!=types.end())
return true;
return false;
}
UniTag::Tag *UniTag::getTag(const std::string &path)
{
std::string ext = getExtension(path);
std::transform(ext.begin(), ext.end(),ext.begin(), ::tolower);
if(ext=="ogg" || ext=="flac")
return new VorbisComment(path);
else if(ext=="m4a" || ext=="m4p" || ext=="3gp")
return new M4(path);
else if(ext=="mp3")
return new ID3v2(path);
cerr<<"UniTag : ERROR : "<<path<<" : INVALID file type"<<endl;
return new NonValidTag(path);
}
| true |
d3bb88c40f02b1fd049ed1368430c03e77a8ec7a | C++ | LeeJuhae/42_projects | /cpp_module/cpp08/ex01/main.cpp | UTF-8 | 1,493 | 3.390625 | 3 | [] | no_license | #include "./span.hpp"
int main(void)
{
std::cout << "\n\t\t\033[1;31m SPAN TEST\033[0m" << std::endl;
Span span1 = Span(7);
Span span2 = Span(100);
Span span3 = Span(10);
std::cout << ">>> TEST_1: span1 = Span(7) <<<" << std::endl;
span1.addNumber(1);
span1.addNumber(3);
span1.addNumber(20);
span1.addNumber(9);
span1.addNumber(11);
span1.addNumber(21);
span1.addNumber(6);
std::cout << "span1 : 1, 3, 20, 9, 11, 21, 6" << std::endl;
std::cout << "span1.shortestSpan(): " << span1.shortestSpan() << std::endl;
std::cout << "span1.longestSpan(): " << span1.longestSpan() << std::endl;
std::cout << std::endl;
std::cout << ">>> TEST_2: span2 = Span(100) <<<" << std::endl;
for (int i = 0 ; i < 100 ; i++)
span2.addNumber(i + 1);
std::cout << "span2 : 1, 2, 3, ..., 98, 99, 100" << std::endl;
std::cout << "span2.shortestSpan(): " << span2.shortestSpan() << std::endl;
std::cout << "span2.longestSpan(): " << span2.longestSpan() << std::endl;
std::cout << std::endl;
std::cout << ">>> TEST_3: addNumber function overloading <<<" << std::endl;
std::cout << "span3.addNumber(0, 9, 1)" << std::endl;
span3.addNumber(0, 9, 1);
std::cout << "span3.shortestSpan(): " << span3.shortestSpan() << std::endl;
std::cout << "span3.longestSpan(): " << span3.longestSpan() << std::endl;
for (std::vector<int>::iterator it = span3.getVector().begin() ; it != span3.getVector().end() ; it++)
std::cout << *it << std::endl;
return (EXIT_SUCCESS);
}
void testSpan()
{
}
| true |
6c6cea1d1420ce9cc644111ca66cb5ff797ba7ad | C++ | OC-MCS/p2finalproject-02-NateBellcock | /game/Projectle.h | UTF-8 | 1,829 | 3.078125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <list>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
class Projectle
{
private:
Sprite missile;
bool isOnSreen;
public:
Projectle(Texture& missileTexture, Sprite ship)
{
missile.setTexture(missileTexture);
missile.setPosition(ship.getPosition().x + 8, ship.getPosition().y - 5);
isOnSreen = true;
}
void move()
{
missile.move(0, -6);
if (missile.getPosition().y < 0)
{
isOnSreen = false;
}
}
void draw(RenderWindow &win)
{
win.draw(missile);
}
bool getIsOnSreen()
{
return isOnSreen;
}
Sprite getProjtle()
{
return missile;
}
};
class Missiles
{
private:
list<Projectle> missiles;
list<Projectle>::iterator iter;
public:
Missiles()
{
}
void addMissile(Projectle &missile)
{
missiles.push_back(missile);
}
void move()
{
if (!missiles.empty())
{
for (iter = missiles.begin(); iter != missiles.end(); iter++)
{
iter->move();
}
}
}
void draw(RenderWindow &win)
{
if (!missiles.empty())
{
for (iter = missiles.begin(); iter != missiles.end(); iter++)
{
iter->draw(win);
}
}
}
void removeMissiles()
{
if (!missiles.empty())
{
for (iter = missiles.begin(); iter != missiles.end();)
{
if (!iter->getIsOnSreen())
{
iter = missiles.erase(iter);
}
else
{
iter++;
}
}
}
}
bool hitOrMiss(Sprite target)
{
bool hit = false;
if (!missiles.empty())
{
for (iter = missiles.begin(); iter != missiles.end() && !hit;)
{
if (!iter->getProjtle().getGlobalBounds().intersects(target.getGlobalBounds()))
{
iter = missiles.erase(iter);
hit = true;
}
else
{
iter++;
}
}
}
return hit;
}
~Missiles()
{
while (!missiles.empty())
{
missiles.pop_front();
}
}
}; | true |
88f83756029099ec7fbc386154dcb1cad4154255 | C++ | IgorYunusov/ZheatEngine | /ZheatEngine/ZheatEngine/UIParamWidget.h | UTF-8 | 9,952 | 2.546875 | 3 | [] | no_license | #pragma once
#include <limits>
#include <QWidget>
#include <QList>
#include <QVariant>
#include <QLineEdit>
#include <QLayout>
#include <QString>
#include <QValidator>
#include "Scan.h"
#include "ScanNBytes.h"
#include "ScanFloatType.h"
#include "HelperFunctions.h"
class UIParamWidget : public QWidget
{
Q_OBJECT
public:
static UIParamWidget* Factory(Scan::ValueType, int scanType, bool initial);
virtual ~UIParamWidget() {};
virtual QList<QVariant> Param() const = 0;
bool MatchType(Scan::ValueType, int scanType, bool initial) const;
protected:
UIParamWidget(Scan::ValueType v, int scanType, bool initial);
private:
template<typename T>
static UIParamWidget* FactoryNBytes(Scan::ValueType valueType, int scanType, bool initial);
template<typename T>
static UIParamWidget* FactoryFloatType(Scan::ValueType valueType, int scanType, bool initial);
protected:
Scan::ValueType valueType;
int scanType;
bool initial;
};
class UIEmptyParamWidget : public UIParamWidget
{
public:
UIEmptyParamWidget(Scan::ValueType v, int scanType, bool initial);
QList<QVariant> Param() const override;
};
template<typename T>
class SimpleValidator : public QValidator
{
public:
State validate(QString &input, int &pos) const override;
void fixup(QString &input) const override;
};
template<typename T>
class UIParamNBytes : public QWidget
{
public:
UIParamNBytes(QWidget* parent = Q_NULLPTR);
T Get() const;
private:
QLineEdit * lineEdit;
};
template<typename T>
class UISingleParamNBytes : public UIParamWidget
{
public:
UISingleParamNBytes(Scan::ValueType v, int scanType, bool initial);
QList<QVariant> Param() const override;
private:
UIParamNBytes<T>* param;
};
template<typename T>
class UIDoubleParamNBytes : public UIParamWidget
{
public:
UIDoubleParamNBytes(Scan::ValueType v, int scanType, bool initial);
QList<QVariant> Param() const override;
private:
UIParamNBytes<T>* paramLeft;
UIParamNBytes<T>* paramRight;
};
template<typename T>
class UIParamFloatType :public QWidget
{
public:
UIParamFloatType(QWidget* parent = Q_NULLPTR);
T Get() const;
private:
QLineEdit * lineEdit;
};
template<typename T>
class UISingleParamFloatType : public UIParamWidget
{
public:
UISingleParamFloatType(Scan::ValueType v, int scanType, bool initial);
QList<QVariant> Param() const override;
private:
UIParamFloatType<T>* param;
};
template<typename T>
class UIDoubleParamFloatType : public UIParamWidget
{
public:
UIDoubleParamFloatType(Scan::ValueType v, int scanType, bool initial);
QList<QVariant> Param() const override;
private:
UIParamFloatType<T>* paramLeft;
UIParamFloatType<T>* paramRight;
};
template<typename T>
QValidator::State SimpleValidator<T>::validate(QString & input, int & pos) const
{
bool ok = false;
auto ret = ToType<T>(input, &ok);
if (!ok)
return State::Intermediate;
if (ret > std::numeric_limits<T>::max() || ret < std::numeric_limits<T>::min())
return State::Intermediate;
return State::Acceptable;
}
template<typename T>
void SimpleValidator<T>::fixup(QString & input) const
{
bool ok = false;
auto ret = ToType<T>(input, &ok);
if (!ok)
{
input = "0";
return;
}
if (ret > std::numeric_limits<T>::max())
{
input = QString::number(std::numeric_limits<T>::max());
}
else if (ret < std::numeric_limits<T>::min())
{
input = QString::number(std::numeric_limits<T>::min());
}
}
template<typename T>
UIParamNBytes<T>::UIParamNBytes(QWidget * parent)
:QWidget(parent), lineEdit(new QLineEdit(this))
{
auto layout = new QVBoxLayout(this);
layout->addWidget(lineEdit);
lineEdit->setValidator(new SimpleValidator<T>());
lineEdit->setText("0");
}
template<typename T>
T UIParamNBytes<T>::Get() const
{
return ToType<T>(lineEdit->text());
}
template<typename T>
UISingleParamNBytes<T>::UISingleParamNBytes(Scan::ValueType v, int scanType, bool initial)
:UIParamWidget(v, scanType, initial), param(new UIParamNBytes<T>(this))
{
auto layout = new QHBoxLayout(this);
layout->addWidget(param);
}
template<typename T>
QList<QVariant> UISingleParamNBytes<T>::Param() const
{
return { param->Get() };
}
template<typename T>
UIDoubleParamNBytes<T>::UIDoubleParamNBytes(Scan::ValueType v, int scanType, bool initial)
:UIParamWidget(v, scanType, initial),
paramLeft(new UIParamNBytes<T>(this)),
paramRight(new UIParamNBytes<T>(this))
{
auto layout = new QHBoxLayout(this);
layout->addWidget(paramLeft);
layout->addWidget(paramRight);
}
template<typename T>
QList<QVariant> UIDoubleParamNBytes<T>::Param() const
{
return { paramLeft->Get(),paramRight->Get() };
}
template<typename T>
UIParamWidget * UIParamWidget::FactoryNBytes(Scan::ValueType valueType, int scanType, bool initial)
{
if (initial)
{
// same InitialScanType, just use Scan4Bytes::InitialScanType here
auto type = Scan4Bytes::InitialScanType(scanType);
switch (type)
{
case Scan4Bytes::InitialScanType::Equal:
case Scan4Bytes::InitialScanType::NotEqual:
case Scan4Bytes::InitialScanType::GreaterThan:
case Scan4Bytes::InitialScanType::LessThan:
case Scan4Bytes::InitialScanType::GreaterThanOrEqualTo:
case Scan4Bytes::InitialScanType::LessThanOrEqualTo:
return new UISingleParamNBytes<T>(valueType, scanType, initial);
case Scan4Bytes::InitialScanType::Between:
case Scan4Bytes::InitialScanType::NotBetween:
return new UIDoubleParamNBytes<T>(valueType, scanType, initial);
case Scan4Bytes::InitialScanType::Unknown:
return new UIEmptyParamWidget(valueType, scanType, initial);
default:
ErrorExit("Unknown ScanNBytes::InitialScanType");
}
}
else
{
// same InitialScanType, just use Scan4Bytes::InitialScanType here
auto type = Scan4Bytes::ScanType(scanType);
switch (type)
{
case Scan4Bytes::ScanType::Equal:
case Scan4Bytes::ScanType::NotEqual:
case Scan4Bytes::ScanType::GreaterThan:
case Scan4Bytes::ScanType::LessThan:
case Scan4Bytes::ScanType::GreaterThanOrEqualTo:
case Scan4Bytes::ScanType::LessThanOrEqualTo:
case Scan4Bytes::ScanType::IncreasedBy:
case Scan4Bytes::ScanType::NotIncreasedBy:
case Scan4Bytes::ScanType::DecreasedBy:
case Scan4Bytes::ScanType::NotDecreasedBy:
return new UISingleParamNBytes<T>(valueType, scanType, initial);
case Scan4Bytes::ScanType::Between:
case Scan4Bytes::ScanType::NotBetween:
return new UIDoubleParamNBytes<T>(valueType, scanType, initial);
case Scan4Bytes::ScanType::IncreasedValue:
case Scan4Bytes::ScanType::DecreasedValue:
case Scan4Bytes::ScanType::ChangedValue:
case Scan4Bytes::ScanType::UnChangedValue:
return new UIEmptyParamWidget(valueType, scanType, initial);
default:
ErrorExit("Unknown ScanNBytes::ScanType");
}
}
}
template<typename T>
UIParamFloatType<T>::UIParamFloatType(QWidget * parent)
:QWidget(parent), lineEdit(new QLineEdit(this))
{
auto layout = new QVBoxLayout(this);
layout->addWidget(lineEdit);
lineEdit->setValidator(new SimpleValidator<T>());
lineEdit->setText("0");
}
template<typename T>
T UIParamFloatType<T>::Get() const
{
return ToType<T>(lineEdit->text());
}
template<typename T>
UISingleParamFloatType<T>::UISingleParamFloatType(Scan::ValueType v, int scanType, bool initial)
:UIParamWidget(v, scanType, initial), param(new UIParamFloatType<T>(this))
{
auto layout = new QHBoxLayout(this);
layout->addWidget(param);
}
template<typename T>
QList<QVariant> UISingleParamFloatType<T>::Param() const
{
return { param->Get() };
}
template<typename T>
UIDoubleParamFloatType<T>::UIDoubleParamFloatType(Scan::ValueType v, int scanType, bool initial)
:UIParamWidget(v, scanType, initial),
paramLeft(new UIParamFloatType<T>(this)),
paramRight(new UIParamFloatType<T>(this))
{
auto layout = new QHBoxLayout(this);
layout->addWidget(paramLeft);
layout->addWidget(paramRight);
}
template<typename T>
QList<QVariant> UIDoubleParamFloatType<T>::Param() const
{
return { paramLeft->Get(),paramRight->Get() };
}
template<typename T>
UIParamWidget * UIParamWidget::FactoryFloatType(Scan::ValueType valueType, int scanType, bool initial)
{
if (initial)
{
// same InitialScanType, just use ScanFloat::InitialScanType here
auto type = ScanFloat::InitialScanType(scanType);
switch (type)
{
case ScanFloat::InitialScanType::Equal:
case ScanFloat::InitialScanType::NotEqual:
case ScanFloat::InitialScanType::GreaterThan:
case ScanFloat::InitialScanType::LessThan:
case ScanFloat::InitialScanType::GreaterThanOrEqualTo:
case ScanFloat::InitialScanType::LessThanOrEqualTo:
return new UISingleParamFloatType<T>(valueType, scanType, initial);
case ScanFloat::InitialScanType::Between:
case ScanFloat::InitialScanType::NotBetween:
return new UIDoubleParamFloatType<T>(valueType, scanType, initial);
case ScanFloat::InitialScanType::Unknown:
return new UIEmptyParamWidget(valueType, scanType, initial);
default:
ErrorExit("Unknown ScanFloat::InitialScanType");
}
}
else
{
// same InitialScanType, just use ScanFloat::InitialScanType here
auto type = ScanFloat::ScanType(scanType);
switch (type)
{
case ScanFloat::ScanType::Equal:
case ScanFloat::ScanType::NotEqual:
case ScanFloat::ScanType::GreaterThan:
case ScanFloat::ScanType::LessThan:
case ScanFloat::ScanType::GreaterThanOrEqualTo:
case ScanFloat::ScanType::LessThanOrEqualTo:
case ScanFloat::ScanType::IncreasedBy:
case ScanFloat::ScanType::NotIncreasedBy:
case ScanFloat::ScanType::DecreasedBy:
case ScanFloat::ScanType::NotDecreasedBy:
return new UISingleParamFloatType<T>(valueType, scanType, initial);
case ScanFloat::ScanType::Between:
case ScanFloat::ScanType::NotBetween:
return new UIDoubleParamFloatType<T>(valueType, scanType, initial);
case ScanFloat::ScanType::IncreasedValue:
case ScanFloat::ScanType::DecreasedValue:
case ScanFloat::ScanType::ChangedValue:
case ScanFloat::ScanType::UnChangedValue:
return new UIEmptyParamWidget(valueType, scanType, initial);
default:
ErrorExit("Unknown ScanFloat::ScanType");
}
}
}
| true |
013882d3bee1866f61beb844270e7db8bcea4294 | C++ | Hyski/ParadiseCracked | /muffle/new.h | UTF-8 | 1,262 | 2.640625 | 3 | [] | no_license | #if !defined(__NEW_H_INCLUDED_7552370787048739__)
#define __NEW_H_INCLUDED_7552370787048739__
//=====================================================================================//
// void *operator new() //
//=====================================================================================//
inline void *operator new(size_t size, const char *file, unsigned line)
{
void *ptr = ::operator new(size);
std::ostringstream sstr;
sstr << "Allocated " << ptr << "(" << size << ") at " << file << "(" << line << ")\n";
OutputDebugString(sstr.str().c_str());
return ptr;
}
//=====================================================================================//
// void operator delete() //
//=====================================================================================//
inline void operator delete(void *ptr, const char *file, unsigned line)
{
::operator delete(ptr);
std::ostringstream sstr;
sstr << "Freed " << ptr << file << "(" << line << ")\n";
OutputDebugString(sstr.str().c_str());
}
#define DEBUG_NEW new(__FILE__,__LINE__)
#define new DEBUG_NEW
#endif // !defined(__NEW_H_INCLUDED_7552370787048739__) | true |
d4d8e4becb31181e9b02105850dfc0db64ad7fa6 | C++ | MaciejGrudziaz/character-editor | /CHARACTER_EDITOR/ConsoleLayer.h | UTF-8 | 1,330 | 2.90625 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
#include "ConsoleCommand.h"
struct ConsoleLayer {
std::string name;
ConsoleLayer* parent;
std::vector<ConsoleLayer*> children;
std::vector<ConsoleCommand*> commands;
virtual void InitCommands() = 0;
ConsoleLayer(std::string name_) :name(name_),parent(nullptr) { }
void JoinToParent(ConsoleLayer* parent_);
bool JoinChild(ConsoleLayer* child_);
void AddCommand(ConsoleCommand* command_);
bool PerformCommand(std::string command_);
ConsoleLayer* GetChildLayer(std::string name_);
ConsoleLayer* GetParentLayer() { return parent; }
virtual void Say() = 0;
~ConsoleLayer() {
for (ConsoleCommand* command : commands)
delete command;
}
};
struct ConsoleMenu :public ConsoleLayer {
ConsoleMenu() :ConsoleLayer("menu"){ InitCommands(); InitChildren(); }
void InitCommands();
void InitChildren();
void Say();
};
struct ModelEditMenu :public ConsoleLayer {
ModelEditMenu() :ConsoleLayer("edit") { InitCommands(); }
void InitCommands();
void Say();
};
struct AnimationsMenu :public ConsoleLayer {
AnimationsMenu() :ConsoleLayer("anim") { InitCommands(); }
void InitCommands();
void Say();
};
struct ImportExportMenu :public ConsoleLayer {
ImportExportMenu() :ConsoleLayer("file") { InitCommands(); }
void InitCommands();
void Say();
};
| true |
93845b201c588db2411b15782249903b6edfec79 | C++ | kostr2010/game-engine | /src-next/utils/vec2.hpp | UTF-8 | 517 | 3.59375 | 4 | [] | no_license | #pragma once
#include <iostream>
// ====================
// Vec2
// implementation of the simple 2d vector
struct Vec2 {
int x, y;
};
bool operator==(Vec2 left, Vec2 right) {
return (left.x == right.x) && (left.y == right.y);
}
void operator+=(Vec2& left, Vec2& right) {
left.x += right.x;
left.y += right.y;
}
Vec2 operator+(Vec2& left, Vec2& right) {
return {left.x + right.x, left.y + right.y};
}
std::ostream& operator<<(std::ostream& os, Vec2 v) {
return os << "x: " << v.x << " y: " << v.y;
} | true |
3b9ea313173a899a906869a3c8ca1c2ad5608ae6 | C++ | NikosKolitsas/algolab | /initial_problems/aliens/aliensfalse.cpp | UTF-8 | 3,320 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <assert.h>
using namespace std;
struct Alien{
unsigned long start;
unsigned long end;
bool proud;
bool operator<(const Alien& rhs) const{
return start < rhs.start;
}
Alien(int s,int e){ start = s; end=e; proud=true; }
Alien(){};
};
int main ( void ) {
std::ios_base::sync_with_stdio(false);
int cases; //plhthos peiramatwn
cin >> cases ;
vector<Alien> alienVector; //τα αρχικοποιω ολα στο 1. μηκος n+1 γιατι η θεση 0 δεν χρησιμοποιειται.
for ( int c =0; c < cases ; c ++) {
unsigned long n; //aliens
cin >> n;
unsigned long m; //humans
cin >> m;
alienVector.clear();
//alienVector.resize(n);
for(unsigned long i=0; i<n; i++){
int begin, end;
cin >> begin >> end;
//cout <<"\n"<< begin <<" "<< end;
if(begin==0 && end==0) //den bazw mesa tous losers
continue;
alienVector.push_back(Alien(begin,end));
}
//cout << "initial n= " << n << endl;
//cout << "alienVector.size()= " << alienVector.size() << endl;
n=alienVector.size(); //ws n θεωρω το μεγεθος χωρις τους losers
std::sort(alienVector.begin(),alienVector.end());
unsigned long current=0;
unsigned long next=1;
bool noone=false;
bool allPeople=false;
if(alienVector[0].start==1){//dhladh to prwto alien αρχιζει να καλυπτει απο την αρχη τους ανθρωπους. δεν αφηνει τους πρωτους
while(current<n && next<n){
Alien currentA = alienVector[current];
Alien nextA = alienVector[next];
if(currentA.end==m || nextA.end==m)
allPeople=true;
if( (currentA.start==nextA.start) && (currentA.end==nextA.end) ){//kanena apo ta dyo
currentA.proud = false;
nextA.proud = false;
next++;
}else if( (currentA.start==nextA.start) && (currentA.end<nextA.end) ){ //den eimai proud
currentA.proud = false;
current=next;
next++;
}else if( (currentA.start<nextA.start) && (currentA.end<nextA.end) ){ //eimai proud kai paw ston epwmeno
if(currentA.end+1<nextA.start){ //tote den nikountai oloi oi anthrwpoi ara 0 to apotelesma
noone=true; //prepei to ena na καλυπτεται με το επωμενο ή τουλαχιστον να ειναι συνεχομενα
break; //επισης πρεπει το τελευταιο να φτανει μεχρι τον τελευταιο ανθρωπο δηλαδη m
}
current=next;
next++;
}else{
nextA.proud = false;
next++;
}
}
}
// cout << "current= " << current << " next= "<< next << endl;
// cout << "noone flag= " << noone << endl << "alienVector[current].end= " << alienVector[current].end << endl;
if(noone==true || !allPeople ){
// cout << "current= " << current << " next= "<< next << endl;
// cout << "noone flag= " << noone << endl << "alienVector[current].end= " << alienVector[current].end << endl;
cout << 0 << endl;
}else{
unsigned long resultCnt=0;
for(Alien a : alienVector){
if(a.proud==true)
resultCnt++;
}
cout << resultCnt << endl;
}
/* cout << "\nprint alienVector.proud \n";
for(unsigned long int i=0;i<n;i++){
cout << i <<"= " << alienVector[i].proud << endl;
}
*/ }
return 0;
}
| true |
6b32250c2ade3b62f7502a6830cac2716d239c8a | C++ | leoreisdias/hangmanGame-C | /forca.cpp | UTF-8 | 5,521 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<windows.h>
#define tamanho 20
using namespace std;
char palavra_sec[tamanho];
char chutes[26];
int chutes_dados = 0;
int verifica_letra(char letra);
int chute_feito();
int enforca();
void intro();
void chute();
int chute_feito(char letra);
int ganhou();
void forca();
void getPalavra();
void setPalavra();
int main(int argv, char * argc[])
{
intro();
getPalavra();
do{
forca();
chute();
}while(!ganhou() && !enforca());
if(ganhou()){
printf("\nParabens, palavra descoberta!\n\n");
printf(" \'-=======-'/ \n");
printf(" _| .=. |_ \n");
printf(" ((| {{1}} |)) \n");
printf(" \| /|\ |/ \n");
printf(" \__ '`' __/ \n");
printf(" _`) (`_ \n");
printf(" _/_______\_ \n");
printf(" /___________\ \n");
}
else{
printf("\nNao foi dessa vez, HAHAHAHAHAHA!\n");
printf("A palavra era -- %s -- \n\n", palavra_sec);
printf(" { } \n");
printf(" K, } \n");
printf(" / `Y` \n");
printf(" _ / / \n");
printf(" {_'-K.__/ \n");
printf(" `/-.__L._ \n");
printf(" / ' /`\_} \n");
printf(" / ' / \n");
printf("____ / ' / \n");
printf(",-'~~~~ ~~/ ' /_ \n");
printf(" ,' ``~~~%%', \n");
printf(" ( % Y \n");
printf(" { %% I \n");
printf(" { - % `. \n");
printf(" | ', % ) \n");
printf(" | | ,..__ __. Y \n");
printf(" | .,_./ Y ' / ^Y J )| \n");
printf(" \ |' / | | || \n");
printf(" \ L_/ . _ (_,.'( \n");
printf(" \, , ^^""' / | ) \n");
printf(" \_ \ /,L] / \n");
printf(" '-_`-, ` ` ./` \n");
printf(" `-(_ ) \n");
printf(" ^^\..___,.--` \n");
}
setPalavra();
return 0;
}
int verifica_letra(char letra){
for(int i=0;i < strlen(palavra_sec); i++){
if(letra == palavra_sec[i])
return 1;
}
return 0;
}
int letra_errada(){
int erros = 0;
for(int i=0;i < chutes_dados;i++){
if(!verifica_letra(chutes[i])){
erros++;
}
}
return erros;
}
int enforca(){
return letra_errada() >= 5;
}
int ganhou(){
for(int i=0;i < strlen(palavra_sec); i++){
if(!chute_feito(palavra_sec[i])){
return 0;
}
}
return 1;
}
void intro(){
printf("/******************/\n");
printf("/ Forca - xD */\n");
printf("/******************/\n\n");
}
void chute(){
char chute;
cout << "Qual letra? ";
cin >> chute;
if(verifica_letra(chute)){
cout << "Voce acertou: a palavra tem a letra " << chute << "\n\n";
Sleep(900);
system("cls");
}
else{
cout << "\nVoce errou: a palavra NAO tem a letra " << chute<< "\n\n";
Sleep(900);
system("cls");
}
chutes[chutes_dados] = chute;
chutes_dados++;
}
int chute_feito(char letra){
int achou = 0;
for(int i=0;i < chutes_dados;i++){
if(chutes[i] == letra){
achou = 1;
break;
}
}
return achou;
}
void forca(){
int erros = letra_errada();
printf(" ________ \n");
printf(" |/ | \n");
printf(" | %c%c%c \n", (erros>=1?'(':' '), (erros>=1?'_':' '), (erros>=1?')':' '));
printf(" | %c%c%c \n", (erros>=3?'\\':' '), (erros>=2?'|':' '), (erros>=3?'/':' '));
printf(" | %c \n", (erros>=2?'|':' '));
printf(" | %c %c \n", (erros>=4?'/':' '),(erros>=4?'\\':' '));
printf(" | \n");
printf("_|___ \n");
printf("\n\n");
for(int i=0;i < strlen(palavra_sec); i++){
if(chute_feito(palavra_sec[i]))
cout << palavra_sec[i] << " ";
else
cout << "_ ";
}
cout << endl;
}
void getPalavra(){
FILE *f;
f = fopen("palavras.txt", "r");
if(f == 0){
cout << "Banco de dados de palavras invalido\n\n";
exit(1);
}
int num_palavras;
fscanf(f, "%d", &num_palavras);
srand(time(0));
int random = rand() % num_palavras;
for(int i=0;i <= random; i++){
fscanf(f, "%s", palavra_sec);
}
fclose(f);
}
void setPalavra(){
char op;
cout << "Voce deseja adiciona uma nova palavra no jogo (s/n)? ";
cin >> op;
if(op == 'S'){
char nova_palavra[tamanho];
cout << "Digite a palavra, em letras maiusculas: ";
cin >> nova_palavra;
FILE *f;
f = fopen("palavras.txt", "r+");
if(f == 0){
cout << "Arquivo com erro\n\n";
exit(1);
}
int qtd;
fscanf(f,"%d", &qtd);
qtd++;
fseek(f,0,SEEK_SET);
fprintf(f, "%d", qtd);
fseek(f,0,SEEK_END);
fprintf(f, "\n%s", nova_palavra);
fclose(f);
}
}
| true |
5155068e8b3aa005ddcf4b485c988668ad891c6f | C++ | PiKesi522/Cpp-Test | /1046c.cpp | UTF-8 | 1,241 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <math.h>
#include <cstring>
#include <sstream>
using namespace std;
int present_location = 0;
void print()
{
cout << "case #" << present_location << ":" << endl;
return;
}
void question()
{
char ch;
int loc = 0;
vector<char> table[500];
memset(table, '\0', sizeof(table));
while((ch = getchar()) != '\n')
{
if(isalpha(ch))
{
table[loc].push_back(ch);
}
else
{
if(table[loc].size() > 0)
loc++;
}
}
if(table[loc].size() > 0)
loc++;
print();
set<string> ans;
//stringstream line;
for (int i = 0; i < loc;i++)
{
string s;
for(auto v : table[i])
s += v;
ans.insert(s);
}
for (auto it = ans.begin(); it != ans.end();it++)
{
cout << *it << ' ';
}
cout << endl;
return;
}
int main()
{
int T;
cin >> T;
getchar();
for (; present_location < T;present_location++)
{
question();
}
return 0;
} | true |
46425a2f93d33322d57e5ef19d64f4e872d8ce2a | C++ | xueer828/practice_code | /cpp/POJ/poj1018.h | GB18030 | 4,709 | 2.65625 | 3 | [] | no_license | #ifndef _TEST_
#define _TEST_
// poj1018
// Copyright (c) 2012/12/08
// Author: xdutaotao (xdutaotao@gmail.com)
// Communication System
// 1<=1<=100 豸1<=mi<=100 ̵Ĵͼ۸B/P /۸
//DPʽ: f(n)=max{(B(n-1)+Bn)/(P(n-1)+Pn)}
//ȷ˼·ΪBPΪԼҪ"ʱ̶"ijһȻһļֵ
// + ö , ˮ
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
#include <cstdlib>
using namespace std;
typedef struct DV{
int b,p;
}DV;
//dv[i][j], iΪ豸ţjΪ豸
DV dv[100][100]={0};
int n_dv[100]={0};
int sorted_band[100000]={0};
int band_idx=0;
int compare1(const void* d1,const void* d2)
{
DV* da=(DV*)d1;
DV* db=(DV*)d2;
if (da->p < db->p || (da->p == db->p && da->b < db->b))
return -1;
else if(da->p == db->p && da->b == db->b)
return 0;
else
return 1;
}
int compare2(const void* d1, const void* d2)
{
return (*((int*)d1) - *((int*)d2));
}
void solve()
{
int ct_cases,ct_dvs;
cin>>ct_cases;
while(ct_cases--)
{
cin>>ct_dvs;
int idx=0;
while(idx < ct_dvs)
{
cin>>n_dv[idx];
int max_band_4_dv=0;
for(int i=0;i<n_dv[idx];++i)
{
cin>>dv[idx][i].b>>dv[idx][i].p;
sorted_band[band_idx++]=dv[idx][i].b;
assert(band_idx<100000);
}
++idx;
}
//ÿһ豸ȼ۸
for(int i=0;i<ct_dvs;++i)
qsort(&(dv[i]),n_dv[i],sizeof(dv[0][0]),compare1);
qsort(sorted_band,band_idx,sizeof(sorted_band[0]),compare2);
#if 0
cout<<"-------------------\n";
for(int q=0;q<band_idx;++q)
cout<<sorted_band[q]<<" ";
cout<<endl;
cout<<"-------------------\n";
#endif
//bandȥ
int band_id=0,tmp_id=0;
sorted_band[band_id]=sorted_band[tmp_id++];
while(tmp_id < band_idx)
{
if(sorted_band[band_id]!=sorted_band[tmp_id])
sorted_band[++band_id] = sorted_band[tmp_id];
++tmp_id;
}
#if 0
for(int q=0;q<=band_id;++q)
cout<<sorted_band[q]<<" ";
cout<<endl;
cout<<"-------------------\n";
#endif
double total=0;
//ʼСö
for(int k=0;k<=band_id;++k)
{
int total_band,total_price;
int w = sorted_band[k];
total_price = total_band = 0;
for(int i=0;i<ct_dvs;++i) //ѡȡÿ豸(>=ǰѯ)priceС
{
int tmpi=0;
while(tmpi < n_dv[i])
{
if(dv[i][tmpi].b >= w)
break;
++tmpi;
}
if(tmpi == n_dv[i])
{
total_price = 0;
#if 0
cout<<w<<endl;
#endif
break;
}
total_price += dv[i][tmpi].p;
#if 0
cout<<"["<<dv[i][tmpi].p<<"] ";
#endif
}
if(total_price>0 && total < w*1.0/total_price)
{
total = w*1.0/total_price;
#if 0
cout<<w<<":"<<total_price<<endl;
#endif
}
}
printf("%.3lf\n",total);
band_idx = 0;
memset(n_dv,0,sizeof(n_dv));
}
}
#if 0
//DP˼·
typedef struct dv_sum
{
int band;
int price;
double b_p;
dv_sum(){band=price=0;}
dv_sum(const int &b,const int &p){band=b;price=p;b_p=1.0*band/price;}
} dv_sum;
dv_sum dvs[100];
dv_sum cdvs[100];
void solve()
{
int ct_case,ct_dv;
cin>>ct_case;
while(ct_case--) //case
{
cin>>ct_dv;
int num=0,old=0,b,p;
double total_max=0;
for(int i=0;i<ct_dv;++i) //豸һ豸жЧѱ
{
old = num; //һε
cin>>num;
for(int j=0;j<num;++j) //Եǰj豸ΪڵЧѱ
{
cin>>b>>p;
double tmp_max=0;
dv_sum tmp_dv(b,p);
for(int k=0;k<old;++k) //ȡǰһ豸Чѱ+豸Чѱ
{
int tmp_b,tmp_p;
tmp_b = b < dvs[k].band ? b:dvs[k].band;
tmp_p = dvs[k].price + p;
double tmp=tmp_b*1.0/tmp_p;
if(tmp_max < tmp|| (tmp_max==tmp && tmp_b > tmp_dv.band))
{
tmp_max = tmp;
tmp_dv.band = tmp_b;
tmp_dv.price = tmp_p;
tmp_dv.b_p = tmp_max;
}
}
//ʱó豸jӦЧѱ
cdvs[j]=tmp_dv;
}
//豸jתԭdvs
for(int m=0;m<num;++m)
{
dvs[m]=cdvs[m];
if(i==ct_dv-1 && total_max < dvs[m].b_p)
total_max = dvs[m].b_p;
}
}
printf("%.3f\n",total_max);
total_max = 0;
memset(dvs,0,sizeof(dvs));
memset(cdvs,0,sizeof(cdvs));
}
}
#endif
#endif | true |
4504b186c6e918522c75b7e84f18b2620ffe699d | C++ | axshen/reproducibility_ci | /sample_code/cpp/Creature.h | UTF-8 | 828 | 3.28125 | 3 | [] | no_license | // Copyright 2021 Austin Shen
#ifndef SAMPLE_CODE_CPP_CREATURE_H_
#define SAMPLE_CODE_CPP_CREATURE_H_
#include <iostream>
#include <string>
class Creature {
protected:
std::string m_name;
char m_symbol;
int m_health;
int m_strength;
int m_gold;
public:
Creature(std::string name, char symbol, int health, int strength, int gold)
: m_name(name), m_symbol(symbol), m_health(health),
m_strength(strength), m_gold(gold) {}
std::string getName() const { return m_name; }
char getSymbol() const { return m_symbol; }
int getHealth() const { return m_health; }
int getStrength() const { return m_strength; }
int getGold() const { return m_gold; }
void reduceHealth(int damage);
bool isDead() const;
void addGold(int amount);
};
#endif // SAMPLE_CODE_CPP_CREATURE_H_
| true |
0fb956303bb5d2137a4748ca577e71e636885542 | C++ | UtotingPuwet/2021_Spring_CSC5 | /Project1/Constructing_Deck_V2/main.cpp | UTF-8 | 1,721 | 3.59375 | 4 | [] | no_license | /*
Author: Christian Fuentes
Date: April 18th, 2021 11:14pm
Purpose:Upgrading to make it print lines when certain number chosen using
switch case
*/
//System Libraries
#include <iostream> //Input/Output Library
#include <cstdlib> //Random library
#include <ctime> //Time library
using namespace std; //Library Name-space
//User Libraries
//Global/Universal Constants -- No Global Variables
//Science, Math, Conversions, Higher Dimensioned constants only
//Function Prototypes
//Execution Begins Here
int main(int argc, char** argv) {
//Set the Random number seed
srand (static_cast<unsigned int>(time(0)));
//Declare variables
//Initialize variables
for (int i = 0; i<2; i++){
int deck = rand()% 12 + 1;
switch (deck){
case 1: cout << "You got an ace" << '\n'; break;
case 2: cout << "You got a 2" << '\n'; break;
case 3: cout << "You got a 3" << '\n'; break;
case 4: cout << "You got a 4" << '\n'; break;
case 5: cout << "You got a 5" << '\n'; break;
case 6: cout << "You got a 6" << '\n'; break;
case 7: cout << "You got a 7" << '\n'; break;
case 8: cout << "You got a 8" << '\n'; break;
case 9: cout << "You got a 9" << '\n'; break;
case 10: cout << "You got a Jack" << '\n'; break;
case 11: cout << "You got a Queen" << '\n'; break;
case 12: cout<< "You got a King" << '\n'; break;
}
}
//Process, map inputs to outputs
//Display your initial conditions as well as outputs.
//Exit stage right
return 0;
}
| true |
fe6db2f1fd9912dee58013bceb4eeec9304857fc | C++ | kfaeghi/BTP305 | /Station.cpp | UTF-8 | 3,156 | 2.90625 | 3 | [] | no_license | /*
Name: Khashayar Faeghi
Senca Email: kfaeghi@myseneca.ca
Seneca Id: 125630186
Date: 11/28/2020
I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments.
*/
#include "Station.h"
size_t Station::id_generator = 0;
size_t Station::m_widthField = 0;
Station::Station()
{
setSafeState();
}
Station::Station(const std::string& record)
{
setSafeState();
++id_generator;
m_stationID = id_generator;
size_t next_pos = 0;
bool more = true;
Utilities utl;
while (more)
{
m_itemName = utl.extractToken(record, next_pos, more);
m_serialNumb = std::stoi(utl.extractToken(record, next_pos, more));
m_stockQty = std::stoi(utl.extractToken(record, next_pos, more));
m_stationDesc = utl.extractToken(record, next_pos, more);
if (this->m_widthField < utl.getFieldWidth())
{
this->m_widthField = utl.getFieldWidth();
}
}
if (this->m_widthField < utl.getFieldWidth())
m_widthField = utl.getFieldWidth();
}
const std::string& Station::getItemName() const
{
return this->m_itemName;
}
unsigned int Station::getNextSerialNumber()
{
return this->m_serialNumb++;
}
unsigned int Station::getQuantity() const
{
return this->m_stockQty;
}
void Station::updateQuantity()
{
if (m_stockQty > 0)
--m_stockQty;
}
void Station::display(std::ostream& os, bool full) const
{
if (full)
{
os << "[" << std::setw(3) << std::setfill('0') << std::right << this->m_stationID << "]" << std::setfill(' ');
os << " Item: " << std::setw(m_widthField) << std::left << getItemName();
os << " [" << std::setw(6) << std::setfill('0') << std::right << this->m_serialNumb << "]" << std::setfill(' ');
os << " Quantity: " << std::setw(m_widthField) << std::left << getQuantity();
os << " Description: " << this->m_stationDesc << std::endl;
}
else
{
os << "[" << std::setw(3) << std::setfill('0') << std::right << this->m_stationID << "]" << std::setfill(' ');
os << " Item: " << std::setw(m_widthField) << std::left << getItemName();
os << " [" << std::setw(6) << std::setfill('0') << std::right << this->m_serialNumb << "]" << std::setfill(' ') << std::endl;
//os << std::setfill('0') << this->m_stationID << std::unse
//os << "]";
//os << std::setw(m_widthField) << " Item: " << getItemName();
//os << std::setw(6) << "[" << this->m_serialNumb << "]" << std::endl;
}
}
void Station::setSafeState()
{
m_itemName = "";
m_serialNumb = 0u;
m_stationDesc = "";
m_stockQty = 0u;
}
| true |
173816160dd10e00fef486441552d453075e4fcd | C++ | SkingXQ/codeTraining | /cppVersion/missingNumber.cpp | UTF-8 | 695 | 3.046875 | 3 | [] | no_license | /*
Link: https://leetcode.com/problems/missing-number/
Tips: similar with first missing number
*/
class Solution {
public:
int missingNumber(vector<int>& nums) {
if(!nums.size()) return 1;
int s = nums.size();
for(int i=0; i<s; i++) {
cout<<nums[i]<<endl;
if(s == nums[i]) nums.push_back(s);
else if(nums[i] != i && nums[nums[i]] != nums[i]){
int t = nums[nums[i]];
nums[nums[i]] = nums[i];
nums[i] = t;
i--;
}
}
for(auto i=0; i<s+1; i++) {
if(nums[i] != i) return i;
}
return nums.back()+1;
}
};
| true |
71c3452cd17534ab554708c0a146b5dfd1cb41db | C++ | joeaoregan/LIT-Yr3-AdvancedDigitalGameProgramming | /2-CodeBlocks/BoundaryStuff.h | UTF-8 | 963 | 2.6875 | 3 | [] | no_license | /*
2017/04/25 Joe made this
#include <SDL.h>
#include "Observer.h"
#include "GameObject.h"
#include "Message.h"
// Observer Virtual Base Class
class BoundaryStuff : public Observer { // Boundary Stuff class is a sub type of the Observer class
public:
~BoundaryStuff() { // Destructor
}
//virtual void whenNotified(const GameObject& gameobject, int action) { // Inherits pure virtual notify recieved function
virtual void whenNotified(int action) { // Inherits pure virtual notify recieved function // Only Player observing
if (action == MESSAGE1) {
std::cout << "Action 1 has happened" << std::endl;
displayMessage1();
}
else if (action == MESSAGE2) {
std::cout << "Action 2 has happened" << std::endl;
displayMessage2();
}
}
private:
void displayMessage1() {
std::cout << "Message for observation 1" << std::endl;
}
void displayMessage2() {
std::cout << "Message for observation 2" << std::endl;
}
};
*/
| true |
26f9f2515ec47a1affa45c0f9db7d944a1c05114 | C++ | DDDANBO/All-In-One-Project | /数据结构实验/实验二/实验二 一元稀疏多项式计算终版.cpp | GB18030 | 10,033 | 3.15625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define N 7 //Ķʽĸ
#define M 20 //ķΧ
typedef int ElemType;
typedef int Status;
typedef struct //ıʾ
{
float coef; // ϵ
int expn; // ָ
} LElemType_E;
typedef struct PNode // ͣ
{
LElemType_E data;
struct PNode * next;
}*PositionPtr;
typedef struct //, ʽʾ
{
PositionPtr head, tail;
int len;
} Polynomial;
void CreatePolyn(Polynomial &P, int m); //mϵָʾһԪʽP
//void DestroyPolyn(Polynomial &P); //һԪʽP
void PrintPolyn(Polynomial P); //ӡһԪʽP
//int PolyLength(Polynomial P); //һԪʽPе
void AddPolyn(Polynomial &Pa, Polynomial &Pb); //ɶʽ㣬Pa=Pa+PbһԪʽPb
void SubtractPolyn(Polynomial &Pa, Polynomial &Pb); //ɶʽ㣬Pa=Pa-PbһԪʽPb
int Cmp(LElemType_E c1, LElemType_E c2);//aֵָ<=>bֱֵָ-10+1
Status DelFirst(Polynomial &L, PositionPtr h, PositionPtr q);
void FreeNode(PositionPtr p); //ͷſռ
LElemType_E GetCurElem(PositionPtr p); //õǰԪ
PositionPtr GetHead(Polynomial L); //õͷ
void InsFirst(Polynomial &L, PositionPtr h, PositionPtr s);
Status MakeNode(PositionPtr &p, LElemType_E e); //
PositionPtr NextPos(PositionPtr p); //һ
void SetCurElem(PositionPtr p, LElemType_E e); //pָĽ㸳ֵ
Status InitList(Polynomial &L); //ʼ
void Append(Polynomial &L, PositionPtr s); //ʣĽ㵽һ
int Srand(int m,int t,int *a); //ظ
void Combine(Polynomial &Pa); //ϲPaеͬ
void RverList(Polynomial &Pa); //
int main()
{
srand((int) time(0));
Polynomial P,Q, A,B;
int m;
printf ("%dʽ\n",N);
CreatePolyn(P,N);
printf ("\nһԪϡʽPΪ\n");
PrintPolyn(P);
CreatePolyn(Q,N);
printf ("\nһԪϡʽQΪ\n");
PrintPolyn(Q);
AddPolyn(P, Q);
printf ("\nһԪϡʽP+QĺΪ\n");
Combine(P);
PrintPolyn(P);
printf ("\n");
printf ("\n%dʽ\n",N);
CreatePolyn(A,N);
printf ("\nһԪϡʽAΪ\n");
PrintPolyn(A);
CreatePolyn(B,N);
printf ("\nһԪϡʽBΪ\n");
PrintPolyn(B);
SubtractPolyn(A, B);
printf ("\nһԪϡʽA-BIJΪ\n");
Combine(A);
PrintPolyn(A);
printf ("\n");
printf ("\nA-BIJ\n");
RverList(A);
PrintPolyn(A);
return 0;
}
int Cmp(LElemType_E c1, LElemType_E c2)
{
int i = c1.expn - c2.expn;
if(i<0)
return -1;
else if(i==0)
return 0;
else
return 1;
}
//mϵָʾһԪʽP
void CreatePolyn(Polynomial &P, int m)
{
PositionPtr h,p;
LElemType_E e;
int i,a[N+1];
e.expn = rand() % M+1;
InitList(P); //ʼһչĵŶʽ
h = GetHead(P); //ȡʽͷָ
//e.coef = 0.0;
//e.expn = -1;
SetCurElem(h, e); //ͷԪ
h->next = NULL;
for(i=1; i<=m; i++) //¼n0
{
//scanf ("%f %d",&e.coef,&e.expn);
//e.coef = rand() % M+1;
//e.expn = rand() % M+1;
e.coef = rand() % M+1;
e.expn = Srand(i,e.expn,a);
MakeNode(p, e);
p->next = NULL;
InsFirst(P, h, p);
h = h->next;
}
}
int Srand(int m,int t,int *a)
{
int i,j;
i = rand() % M+1;
for (j = 0; j<m; j++)
{
while (i == a[j])
{
i = rand() % M+1;
}
}
a[j] = i;
return i;
}
//ʽӷPa=Pa+PbʽĽ㹹ɡͶʽ
void AddPolyn(Polynomial &Pa, Polynomial &Pb)
{
PositionPtr ha, hb, qa, qb, head;
LElemType_E a, b;
float sum;
ha = GetHead(Pa); //hahbֱָPaPbͷ
hb = GetHead(Pb);
head = qa = NextPos(ha); //qaqbֱָPaPbĵǰ
qb = NextPos(hb);
while(qa && qb) //qaqbǿ
{
a = GetCurElem(qa); //abΪеǰȽԪ
b = GetCurElem(qb);
switch(Cmp(a,b)) //ȽϵǰԪصָС
{
case -1: //ʽPaеǰֵָС
ha = qa;
qa = NextPos(ha);
break;
case 0: //ֵ
sum = a.coef + b.coef;
if(sum != 0.0) //ӲܵʱPaϵֵ
{
qa->data.coef = sum;
SetCurElem(qa, qa->data);
ha = qa; //ʱha
}
else //ӵʱɾPaеǰ
{
DelFirst(Pa, ha, qa);
FreeNode(qa);
}
DelFirst(Pb, hb, qb); //ɾPbɨĽ
FreeNode(qb);
qb = NextPos(hb); //qaqb
qa = NextPos(ha);
break;
case 1: //ʽPbеǰֵָС
DelFirst(Pb, hb, qb); //ժPbǰ
InsFirst(Pa, ha, qb); //ժ½Pa
qb = NextPos(hb);
ha = NextPos(ha);
break;
}
}
if(qb) //Pbδɨ꣬ʣӵPa
Append(Pa, qb);
FreeNode(hb); //ͷPbͷ
Pb.head = Pb.tail = NULL; //PbΪ״̬
Pb.len = 0;
}
void Combine(Polynomial &Pa) //ϲPaеͬ
{
PositionPtr ha,qa, qb, head;
ha = GetHead(Pa); //haֱָPaͷ
head = qa = NextPos(ha); //qaֱָPaĵǰ
for (; qa; qa = qa->next)
{
for (ha = qa->next; ha; ha = ha->next)
{
if (qa->data.expn == ha->data.expn)
{
qb = head;
while(qb->next != ha)
{
qb = qb->next;
}
qa->data.coef += ha->data.coef;
qb->next = ha->next;
FreeNode(ha);
ha = qb;
Pa.len--;
}
}
}
}
void SubtractPolyn(Polynomial &Pa, Polynomial &Pb)
{
PositionPtr ha, hb, qa, qb, r;
LElemType_E a, b;
float sum;
ha = GetHead(Pa); //hahbֱָPaPbͷ
hb = GetHead(Pb);
qa = NextPos(ha); //qaqbֱָPaPbĵǰ
qb = NextPos(hb);
while(qa && qb) //qaqbǿ
{
a = GetCurElem(qa); //abΪеǰȽԪ
b = GetCurElem(qb);
switch(Cmp(a,b)) //ȽϵǰԪصָС
{
case -1: //ʽPaеǰֵָС
ha = qa;
qa = NextPos(ha);
break;
case 0: //ֵ
sum = a.coef - b.coef;
if(sum != 0.0) //ܵʱPaϵֵ
{
qa->data.coef = sum;
SetCurElem(qa, qa->data);
ha = qa; //ʱha
}
else //ӵʱɾPaеǰ
{
DelFirst(Pa, ha, qa);
FreeNode(qa);
}
DelFirst(Pb, hb, qb); //ɾPbɨĽ
FreeNode(qb);
qb = NextPos(hb); //qaqb
qa = NextPos(ha);
break;
case 1: //ʽPbеǰֵָС
DelFirst(Pb, hb, qb); //ժPbǰ
qb->data.coef = - qb->data.coef; //ı䵱ǰ
InsFirst(Pa, ha, qb); //ժ½Pa
qb = NextPos(hb);
ha = NextPos(ha);
break;
}
}
if(qb) //Pbδɨ
{
r = qb;
while(r)
{
r->data.coef = - r->data.coef; //ıʣ
r = r->next;
}
Append(Pa, qb);
}
FreeNode(hb); //ͷPbͷ
Pb.head = Pb.tail = NULL;
Pb.len = 0;
}
void RverList(Polynomial &Pa) //
{
PositionPtr p=Pa.head->next;
PositionPtr q=p->next;
Pa.head->next=NULL;
while(p)
{
q=p->next;
p->next=Pa.head->next;
Pa.head->next=p;
p=q;
}
}
void Append(Polynomial &L, PositionPtr s)
{
int count = 0;
L.tail->next = s;
while(s) //sΪյ
{
L.tail = s;
s = s->next;
count++;
}
L.len += count;
}
PositionPtr GetHead(Polynomial L)
{
return L.head;
}
PositionPtr NextPos(PositionPtr p)
{
return p->next;
}
LElemType_E GetCurElem(PositionPtr p)
{
return p->data;
}
void SetCurElem(PositionPtr p, LElemType_E e)
{
p->data = e;
}
Status DelFirst(Polynomial &L, PositionPtr h, PositionPtr q)
{
q = h->next;
if(q) //ǿ
{
h->next = q->next;
if(!h->next) //hֻһ
L.tail = h;
L.len--; //ͷűɾռռ
return OK;
}
return ERROR;
}
void FreeNode(PositionPtr p) //ͷſռ
{
free(p);
p = NULL;
}
void InsFirst(Polynomial &L, PositionPtr h, PositionPtr s)
{
s->next = h->next;
h->next = s;
if(h==L.tail) //hΪβ
L.tail = h->next;
L.len++;
}
Status MakeNode(PositionPtr &p, LElemType_E e)
{
p = (PositionPtr)malloc(sizeof(PNode)); //ռ
if(!p)
exit(OVERFLOW);
p->data = e;
p->next = NULL;
return OK;
}
Status InitList(Polynomial &L)
{
PositionPtr p;
p = (PositionPtr)malloc(sizeof(PNode));
if(!p)
exit(OVERFLOW);
p->next = NULL;
L.head =L.tail = p;
L.len = 0;
return OK;
}
void PrintPolyn(Polynomial P)
{
int i;
PositionPtr p;
p = P.head->next;
for(i=1; i<=P.len; i++)
{
if(i==1)
printf("%2.0f", p->data.coef);
else
{
if(p->data.coef>0)
{
printf(" + ");
printf("%2.0f", p->data.coef);
}
else
{
printf(" - ");
printf("%2.0f", -p->data.coef);
}
}
if(p->data.expn)
{
printf("x");
if(p->data.expn!=1)
printf("^%d", p->data.expn);
}
p = p->next;
}
}
| true |
e97ace04901b60695a9b2606b6643425ca44f7f6 | C++ | yardimli/Arduino | /kit/kit.ino | UTF-8 | 3,219 | 2.8125 | 3 | [] | no_license | int xPin = 0;
int yPin = 0;
int WalkSpeed = 25;
int potpin = 0; // analog pin used to connect the potentiometer
int WalkDirection = 0;
int WalkRGB = 0;
int OldWalkSpeed = 0;
int RedColor = 255;
int BlueColor = 255;
int GreenColor = 255;
#define BLUE_LED_DIO 10 /* Select the DIO for driving the BLUE LED */
#define RED_LED_DIO 11 /* Select the DIO for driving the RED LED */
#define GREEN_LED_DIO 9 /* Select the DIO for driving the GREEN LED */
void setup() {
pinMode(BLUE_LED_DIO, OUTPUT);
pinMode(RED_LED_DIO, OUTPUT);
pinMode(GREEN_LED_DIO, OUTPUT);
analogWrite(BLUE_LED_DIO, 255);
analogWrite(RED_LED_DIO, 255);
analogWrite(GREEN_LED_DIO, 255);
for (int xPin = 2; xPin < 10; xPin++)
{
if (xPin==9) {yPin=12;} else {yPin=xPin;}
pinMode(yPin, OUTPUT);
digitalWrite(yPin, LOW); // turn the LED off by making the voltage LOW
}
WalkDirection=1;
WalkRGB = 1;
xPin = 1;
Serial.begin(115200);
}
void loop() {
OldWalkSpeed = WalkSpeed;
WalkSpeed = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
WalkSpeed = 1024-WalkSpeed;
WalkSpeed = map(WalkSpeed, 0, 1023, 0, 200); // scale it to use it with the servo (value between 0 and 180)
if (WalkRGB == 1)
{
analogWrite(RED_LED_DIO, RedColor);
RedColor -=10;
if (RedColor<=0) { WalkRGB=2; RedColor=0; analogWrite(RED_LED_DIO, RedColor); }
}
if (WalkRGB == 2)
{
analogWrite(RED_LED_DIO, RedColor);
RedColor +=10;
if (RedColor>=255) { RedColor=255; analogWrite(RED_LED_DIO, RedColor); }
}
if (WalkRGB == 2)
{
analogWrite(BLUE_LED_DIO, BlueColor);
BlueColor -=5;
if (BlueColor<=0) { WalkRGB=5; BlueColor=0; analogWrite(BLUE_LED_DIO, BlueColor); }
}
if (WalkRGB == 5)
{
analogWrite(BLUE_LED_DIO, BlueColor);
BlueColor +=10;
if (BlueColor>=255) { BlueColor=255; analogWrite(BLUE_LED_DIO, BlueColor); }
}
if (WalkRGB == 5)
{
analogWrite(GREEN_LED_DIO, GreenColor);
GreenColor -=5;
if (GreenColor<=0) { WalkRGB=6; GreenColor=0; analogWrite(GREEN_LED_DIO, GreenColor); }
}
if (WalkRGB == 6)
{
analogWrite(GREEN_LED_DIO, GreenColor);
GreenColor +=10;
if (GreenColor>=255) { WalkRGB=1; GreenColor=255; analogWrite(GREEN_LED_DIO, GreenColor); BlueColor=255; }
}
if (WalkDirection == 1)
{
xPin++;
if (xPin==9) {yPin=12;} else {yPin=xPin;}
digitalWrite(yPin, LOW); // turn the LED
delay(WalkSpeed);
if (xPin==9) { WalkDirection=2; xPin=1; }
} else
if (WalkDirection == 2)
{
xPin++;
if (xPin==9) {yPin=12;} else {yPin=xPin;}
digitalWrite(yPin, HIGH); // turn the LED
delay(WalkSpeed);
if (xPin==9) { WalkDirection=3; xPin=10;}
} else
if (WalkDirection == 3)
{
xPin--;
if (xPin==9) {yPin=12;} else {yPin=xPin;}
digitalWrite(yPin, LOW); // turn the LED
delay(WalkSpeed);
if (xPin==2) { WalkDirection=4; xPin=10; }
} else
if (WalkDirection == 4)
{
xPin--;
if (xPin==9) {yPin=12;} else {yPin=xPin;}
digitalWrite(yPin, HIGH); // turn the LED
delay(WalkSpeed);
if (xPin==2) { WalkDirection=1; xPin=1; }
}
}
| true |
5b7d4c2dd9caba2d90296603f1a2e569bb2f5f4d | C++ | ecolog/IndustrialC | /preprocessor/main.cpp | UTF-8 | 1,583 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <stack>
#include <fstream>
extern int yylex();
extern FILE *yyin;
extern std::string cur_filename;
extern bool pp_gen_line_markers;
extern bool pp_retain_comments;
//extern std::stack<unsigned int> line_nums;
//extern std::stack<std::string> filenames;
FILE *output_file;
int main(int argc, char **argv)
{
std::string input_filename = "input.blah";
std::string output_filename = "output.blah";
//1: Parse command line arguments
if(argc <= 1)
{
std::cout<<"Error: no input file specified"<<std::endl;
return -1;
}
else
{
input_filename = argv[argc-1];
for(int i=1;i<argc-1;i++)
if("-no-line-markers" == std::string(argv[i]))
pp_gen_line_markers = false;
else if("-retain-comments" == std::string(argv[i]))
pp_retain_comments = true;
else if("-o" == std::string(argv[i]) && i+1 < argc)
output_filename = argv[++i];
}
//2: open input file and set flex to read from it instead of defaulting to STDIN
FILE *myfile = fopen(input_filename.c_str(), "r");
if (!myfile)
{
std::cout << "Can't find " << input_filename << std::endl;
return -1;
}
yyin = myfile;
//line_nums.push(0);
//filenames.push(input_filename);
cur_filename = input_filename;
output_file = fopen(output_filename.c_str(), "w+");
if (!myfile)
{
std::cout << "Can't find " << output_filename << std::endl;
return -1;
}
//3: parser pass
//std::cout<<"parsing..."<<std::endl;
int parse_result = yylex();
fclose(myfile);
fclose(output_file);
//std::cout<<"parser finished"<<std::endl;
return 0;
}
| true |
c19059b40e53e58bbcc6916cd4d7bfc74230e3d6 | C++ | Pkotova/Object-Oriented-Programming | /Polinom/task01/Polinom.cpp | UTF-8 | 6,187 | 3.09375 | 3 | [] | no_license | #include "stdafx.h"
#include "Polinom.h"
#include "Coefficient.h"
#include<iostream>
using namespace std;
void Polinom::copy(const Polinom& other)
{
this->power = other.power;
this->size = other.size;
this->capacity = other.capacity;
this->coefficients = new Coefficient[capacity];
for (int i = 0; i < other.size; i++)
{
this->coefficients[i] = other.coefficients[i];
}
}
void Polinom::destroy()
{
delete[] this->coefficients;
}
Polinom::Polinom()
{
this->capacity = 4;
this->coefficients = new Coefficient[this->capacity];
this->size = 0;
this->power = 0;
}
Polinom::Polinom(const Polinom& other)
{
copy(other);
}
Polinom::Polinom(Coefficient* newCoefs,const int& newPower, const int& newSize, const int newCapacity)
{
this->coefficients = newCoefs;
this->power = newPower;
this->size = newSize;
this->capacity = newCapacity;
}
Polinom& Polinom::operator=(const Polinom& other)
{
if (this != &other)
{
destroy();
copy(other);
}
return *this;
}
Polinom::~Polinom()
{
destroy();
}
//_________________________________
void Polinom::resize()
{
this->capacity *= 2;
this->capacity *= 2;
Coefficient* temp = new Coefficient[capacity];
for (int i = 0; i < this->size; i++)
{
temp[i] = this->coefficients[i];
}
destroy();
this->coefficients = temp;
}
//void Polinom::setCoefficients(double* newCoefs)
//{
// //this->coefficients = newCoefs;
// for (size_t i = 0; i < 4; i++)
// {
// this->coefficients[i] = newCoefs[i];
// }
//}
//double* Polinom::getCoefficients()const
//{
// return this->coefficients;
//}
void Polinom::setSize(const int& newSize)
{
this->size = newSize;
}
int Polinom::getSize()const
{
return this->size;
}
void Polinom::setCapacity(const int& newCapacity)
{
this->capacity = newCapacity;
}
int Polinom::getCapacity()const
{
return this->capacity;
}
int Polinom::getPower() const
{
return this->power;
}
void Polinom::setPower()
{
for (size_t i = 0; i < this->size; i++)
{
if (this->coefficients[i].getCoef() != 0)
{
this->power = this->size - 1;
}
}
}
void Polinom::print()
{
cout << "Coefficients:" << endl;
for (int i = this->size - 1; i >= 0; i--)
{
cout << showpos << " " << this->coefficients[i] << "x^" << noshowpos << i;
}
cout << " = 0";
cout << endl;
}
void Polinom::add(const Coefficient& coef)
{
if (size == capacity)
{
resize();
}
this->coefficients[size] = coef;
size++;
if (coef.getCoef() != 0)
{
this->power = this->size - 1;
}
}
ostream& operator<<(ostream& out, const Polinom& other)
{
for (int i = other.size - 1; i >= 0; i--)
{
out << showpos << " " << other.coefficients[i] << "x^" << noshowpos << i;
}
cout << " = 0";
return out;
}
istream& operator >>(istream &in, Polinom &p)
{
cout << "Imput coefs: " << endl;
for (int i = 0; i < p.getSize(); i++)
{
in >> p.coefficients[i];
}
return in;
}
Polinom& operator^(Polinom& p1, Polinom& p2)
{
return (p1.getPower() > p2.getPower()) ? p1 : p2;
}
Polinom& operator^=(Polinom& p1, Polinom& p2)
{
return (p1.getPower() < p2.getPower()) ? p1 : p2;
}
bool operator<(const Polinom& p1, const Polinom& p2)
{
return (p1.getPower() < p2.getPower()) ? true : false;
}
bool operator>(const Polinom& p1, const Polinom& p2)
{
return (p1.getPower() > p2.getPower()) ? true : false;
}
bool operator==(const Polinom& p1, const Polinom& p2)
{
bool result = true;
if (p1.getPower() == p2.getPower())
{
for (int i = 0; i < p1.getPower(); i++)
{
if (p1.coefficients[i].getCoef() != p2.coefficients[i].getCoef())
{
return !result;
}
}
}
else return !result;
}
bool operator>=(const Polinom& p1, const Polinom& p2)
{
return (p1.getPower() >= p2.getPower()) ? true : false;
}
bool operator<=(const Polinom& p1, const Polinom& p2)
{
return (p1.getPower() <= p2.getPower()) ? true : false;
}
Polinom operator&(const Polinom& p, const double& k)
{
Polinom temp;
for (int i = 0; i < p.getSize(); i++)
{
temp.add((k * (p.coefficients[i].getCoef())));
}
return temp;
}
Polinom operator|(const Polinom& p, const double& k)
{
Polinom temp;
for (int i = 0; i < p.getSize(); i++)
{
temp.add(((p.coefficients[i].getCoef()) / k));
}
return temp;
}
Coefficient Polinom::operator[](const int& index)
{
Coefficient c;
c.setCoefficient(0);
if (index <= size)
{
return this->coefficients[index];
}
return c;
}
double Polinom::operator()(const double& x)
{
int result = 0;
for (int i = 0; i < this->getSize(); i++)
{
result += (x * this->coefficients[i].getCoef());
}
return result;
}
int minimum(int s1, int s2)
{
return (s1 < s2) ? s1 : s2;
}
int maximum(int s1, int s2)
{
return (s1 > s2) ? s1 : s2;
}
Polinom operator+(Polinom& p1, Polinom& p2)
{
Polinom temp;
for (int i = 0; i < minimum(p1.size, p2.size); i++)
{
temp.add(p1.coefficients[i].getCoef() + p2.coefficients[i].getCoef());
}
for (int i = minimum(p1.size, p2.size); i < maximum(p1.size, p2.size); i++)
{
temp.add(( p1 ^ p2).coefficients[i]);
}
return temp;
}
Polinom operator-(Polinom& p1, Polinom& p2)
{
Polinom temp;
for (int i = 0; i < minimum(p1.size, p2.size); i++)
{
temp.add(p1.coefficients[i].getCoef() - p2.coefficients[i].getCoef());
}
if (p2 > p1)
{
for (int i = p1.getSize(); i < p2.getSize(); i++)
{
temp.add(-(p2.coefficients[i].getCoef()));
}
}
else
{
for (int i = p1.getSize(); i < p2.getSize(); i++)
{
temp.add((p1.coefficients[i].getCoef()));
}
}
return temp;
}
Polinom operator~(const Polinom& p)
{
Polinom temp;
for (int i = 1; i < p.getSize(); i++)
{
temp.add(((p.getSize() - 1) * p.coefficients[i].getCoef()));
}
return temp;
}
Polinom operator*(const Polinom& p1, const Polinom& p2)
{
int powers = (p1.getSize() + p2.getSize()) - 1;
Polinom temp;
temp.setSize(powers);
for (size_t i = 0; i < powers; i++)
{
temp.add(0);
}
for (int i = 0; i < p1.getSize(); i++)
{
for (int j = 0; j < p2.getSize(); j++)
{
temp.coefficients[i+j] = temp.coefficients[i+j].getCoef() + p1.coefficients[i].getCoef()
* p2.coefficients[j].getCoef();
}
}
return temp;
}
bool operator!(const Polinom& p)
{
for (int i = 0; i < p.getSize(); i++)
{
if (p.coefficients[i].getCoef() != 0)
{
return false;
}
}
return false;
}
| true |
891d42a2eb0e67aa26ed149af32b78c5b9353d35 | C++ | evilncrazy/spooner | /src/include/object.h | UTF-8 | 760 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef SPOONER_OBJECT_H
#define SPOONER_OBJECT_H
#include <string>
enum ObjectType {
T_NONE, T_INT, T_DECIMAL, T_FUNCTION, T_CLOSURE, T_LIST, T_EXPR, T_NAME,
T_MAP
};
ObjectType str_to_type(const std::string& str);
// defines the functionality and attributes shared by all objects in Spooner
class SpObject {
private:
ObjectType type_;
public:
explicit SpObject(ObjectType type);
virtual ObjectType type() const { return type_; }
virtual ~SpObject() { };
virtual const SpObject *self() const { return this; }
virtual SpObject *shallow_copy() const = 0;
virtual bool equals(const SpObject *other) const = 0;
virtual bool is_truthy() const = 0;
virtual std::string inspect() const { return "(Object)"; }
};
#endif
| true |
2385df05359c164afb55dcf4e75b2a692bc96fa3 | C++ | HunterSun2018/sqlite_orm | /dev/pragma.h | UTF-8 | 5,426 | 2.578125 | 3 | [
"MIT",
"AGPL-3.0-only"
] | permissive | #pragma once
#include <string> // std::string
#include <sqlite3.h>
#include <functional> // std::function
#include <memory> // std::shared_ptr
#include <vector> // std::vector
#include "error_code.h"
#include "util.h"
#include "row_extractor.h"
#include "journal_mode.h"
#include "connection_holder.h"
namespace sqlite_orm {
namespace internal {
struct storage_base;
template<class T>
int getPragmaCallback(void* data, int argc, char** argv, char**) {
auto& res = *(T*)data;
if(argc) {
res = row_extractor<T>().extract(argv[0]);
}
return 0;
}
template<>
inline int getPragmaCallback<std::vector<std::string>>(void* data, int argc, char** argv, char**) {
auto& res = *(std::vector<std::string>*)data;
res.reserve(argc);
for(decltype(argc) i = 0; i < argc; ++i) {
auto rowString = row_extractor<std::string>().extract(argv[i]);
res.push_back(move(rowString));
}
return 0;
}
struct pragma_t {
using get_connection_t = std::function<internal::connection_ref()>;
pragma_t(get_connection_t get_connection_) : get_connection(move(get_connection_)) {}
void busy_timeout(int value) {
this->set_pragma("busy_timeout", value);
}
int busy_timeout() {
return this->get_pragma<int>("busy_timeout");
}
sqlite_orm::journal_mode journal_mode() {
return this->get_pragma<sqlite_orm::journal_mode>("journal_mode");
}
void journal_mode(sqlite_orm::journal_mode value) {
this->_journal_mode = -1;
this->set_pragma("journal_mode", value);
this->_journal_mode = static_cast<decltype(this->_journal_mode)>(value);
}
int synchronous() {
return this->get_pragma<int>("synchronous");
}
void synchronous(int value) {
this->_synchronous = -1;
this->set_pragma("synchronous", value);
this->_synchronous = value;
}
int user_version() {
return this->get_pragma<int>("user_version");
}
void user_version(int value) {
this->set_pragma("user_version", value);
}
int auto_vacuum() {
return this->get_pragma<int>("auto_vacuum");
}
void auto_vacuum(int value) {
this->set_pragma("auto_vacuum", value);
}
std::vector<std::string> integrity_check() {
return this->get_pragma<std::vector<std::string>>("integrity_check");
}
template<class T>
std::vector<std::string> integrity_check(T table_name) {
std::ostringstream oss;
oss << "integrity_check(" << table_name << ")";
return this->get_pragma<std::vector<std::string>>(oss.str());
}
std::vector<std::string> integrity_check(int n) {
std::ostringstream oss;
oss << "integrity_check(" << n << ")";
return this->get_pragma<std::vector<std::string>>(oss.str());
}
private:
friend struct storage_base;
int _synchronous = -1;
signed char _journal_mode = -1; // if != -1 stores static_cast<sqlite_orm::journal_mode>(journal_mode)
get_connection_t get_connection;
template<class T>
T get_pragma(const std::string& name) {
auto connection = this->get_connection();
auto query = "PRAGMA " + name;
T result;
auto db = connection.get();
auto rc = sqlite3_exec(db, query.c_str(), getPragmaCallback<T>, &result, nullptr);
if(rc == SQLITE_OK) {
return result;
} else {
throw std::system_error(std::error_code(sqlite3_errcode(db), get_sqlite_error_category()),
sqlite3_errmsg(db));
}
}
/**
* Yevgeniy Zakharov: I wanted to refactor this function with statements and value bindings
* but it turns out that bindings in pragma statements are not supported.
*/
template<class T>
void set_pragma(const std::string& name, const T& value, sqlite3* db = nullptr) {
auto con = this->get_connection();
if(!db) {
db = con.get();
}
std::stringstream ss;
ss << "PRAGMA " << name << " = " << value;
internal::perform_void_exec(db, ss.str());
}
void set_pragma(const std::string& name, const sqlite_orm::journal_mode& value, sqlite3* db = nullptr) {
auto con = this->get_connection();
if(!db) {
db = con.get();
}
std::stringstream ss;
ss << "PRAGMA " << name << " = " << internal::to_string(value);
internal::perform_void_exec(db, ss.str());
}
};
}
}
| true |
e12805bb85fcf8ec20408b1af5f0c0f51c72b6b3 | C++ | anfavretto/JogoCores_PG201602 | /Jogo/JogoCores.cpp | ISO-8859-1 | 7,244 | 2.578125 | 3 | [] | no_license | #include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <GLFW/glfw3.h>
#include <vector>
#include <time.h>
#include "Jogo.h"
#include "Imagem.h"
#include "Fonte.h"
#include <stdlib.h>
#include <string>
#include<fstream>
using namespace Jogo;
using namespace std;
const int TotalRetangulosComprimento = 20;
const int TotalRetangulosAltura = 40;
const int TamanhoJanelaDesenho = 40;
const int TamanhoJanela = 43;
const GLdouble CoordenadaInicial = 0.0;
const GLdouble CoordenadaFinalX = 40.0;
const GLdouble CoordenadaFinalY = 43.0;
const GLdouble AlturaRetangulo = 1;
const GLdouble LarguraRetangulo = 2;
const int NumeroMaximoDeJogadas = 4;
const int ValorPontosPrimeiraRodada = 10;
const int ValorPontosSegundaRodada = 5;
const int ValorPontosTerceiraRodada = 2;
const int ValorPontosQuartaRodada = 1;
GLfloat ultimoX = -1.0, ultimoY = -1.0;
int LarguraJanelaPixels = 800;
int AlturaJanelaPixels = 640;
vector<Retangulo> retangulos;
GLdouble AlturaBarraPontuacao;
int JogadasEfetuadas;
int PontosJogador = 0;
Fonte *arial = new Fonte("arial.ptm", 16, 16);
float ObterComponenteDeCor() {
return rand() % 256;
}
void ExibirPontuacao() {
bool fgJogadaFinal = JogadasEfetuadas == NumeroMaximoDeJogadas;
std::string pontuacao = fgJogadaFinal ? "Pontuacao Final: " : "Pontuacao: ";
std::string exibir = pontuacao + std::to_string(PontosJogador);
arial->escrever(exibir, 1, (int)AlturaBarraPontuacao);
glFlush();
}
void drawRect(GLdouble x, GLdouble y, GLdouble w, GLdouble h, float r, float g, float b) {
glColor3ub(r, g, b);
glVertex2d(x, y); // ponto esquerda inferior
glVertex2d(x, y + h); // ponto esquerda superior
glVertex2d(x + w, y + h);// ponto direita superior
glVertex2d(x + w, y); // ponto direita inferior
}
void redimensionar(GLFWwindow *window, int w, int h) {
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
AlturaJanelaPixels = h;
LarguraJanelaPixels = w;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(CoordenadaInicial, CoordenadaFinalX, CoordenadaFinalY, CoordenadaInicial, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
GLubyte* ObterCorSelecionada() {
float tamanhoRetangulo = (float)AlturaJanelaPixels / (float)TamanhoJanela;
float limiteRetangulos = tamanhoRetangulo * 40;
GLubyte *pixels = new unsigned char[3]{ 0,0,0 };
//Converso da coordenada para coordenada de tela.
int xTela = (ultimoX * LarguraJanelaPixels) / TamanhoJanelaDesenho;
int yTela = (ultimoY * AlturaJanelaPixels) / TamanhoJanelaDesenho;
if (yTela < limiteRetangulos) {
glReadPixels(xTela, AlturaJanelaPixels - yTela, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixels);
}
return pixels;
}
int AumentarPontuacao(int pontosRodada) {
switch (JogadasEfetuadas)
{
case 1:
return pontosRodada + ValorPontosPrimeiraRodada;
case 2:
return pontosRodada + ValorPontosSegundaRodada;
case 3:
return pontosRodada + ValorPontosTerceiraRodada;
default:
return pontosRodada + ValorPontosQuartaRodada;
}
}
void Jogar(Cor corSelecionadaTela) {
int pontosRodada = 0;
for (vector<Retangulo>::iterator retanguloAtual = retangulos.begin(); retanguloAtual != retangulos.end(); ++retanguloAtual) {
if (retanguloAtual->EstaVisivel()) {
Cor* corRetangulo = retanguloAtual->ObterCor();
bool coresParecidas = corRetangulo->EhProximo(corSelecionadaTela);
if (coresParecidas) {
retanguloAtual->AlterarVisibilidade(false);
pontosRodada = AumentarPontuacao(pontosRodada);
}
}
}
JogadasEfetuadas++;
PontosJogador += pontosRodada;
}
void init() {
//Selecionando a cor para limpar cor de fundo
glClearColor(0.0, 0.0, 0.0, 0.0);
glViewport(0, 0, (GLsizei)LarguraJanelaPixels, (GLsizei)AlturaJanelaPixels);
//Inicializa a visualizao
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(CoordenadaInicial, CoordenadaFinalX, CoordenadaFinalY, CoordenadaInicial, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void reset() {
JogadasEfetuadas = 0;
retangulos.clear();
float r, g, b;
srand((unsigned)time(NULL));
int tamanhoVetorRetangulos = TotalRetangulosAltura * TotalRetangulosComprimento;
for (int indice = 0; indice < tamanhoVetorRetangulos; indice++) {
r = ObterComponenteDeCor();
g = ObterComponenteDeCor();
b = ObterComponenteDeCor();
Retangulo *novoRetangulo = new Retangulo(r, g, b);
retangulos.push_back(*novoRetangulo);
}
}
void render() {
glClear(GL_COLOR_BUFFER_BIT);
int indiceRetanguloAtual = 0;
GLdouble xx; // Canto 0 da tela
GLdouble yy = 0;
for (int y = 0; y < TotalRetangulosAltura; y++) {
xx = 0;
for (int x = 0; x < TotalRetangulosComprimento; x++) {
Retangulo retanguloAtual = retangulos[indiceRetanguloAtual];
if (retanguloAtual.EstaVisivel()) {
glBegin(GL_QUADS);
Cor *corRetangulo = retanguloAtual.ObterCor();
drawRect(xx, yy, LarguraRetangulo, AlturaRetangulo, corRetangulo->ObterR(), corRetangulo->ObterG(), corRetangulo->ObterB());
glEnd();
}
indiceRetanguloAtual++;
xx += LarguraRetangulo; // aumento na largura para desenhar prximo retngulo
}
yy += AlturaRetangulo; // aumenta altura base para desenhar prximo retngulo
}
AlturaBarraPontuacao = yy + AlturaRetangulo + 1;
ExibirPontuacao();
}
void tratarTeclado(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_R && action == GLFW_PRESS) {
reset();
}
}
static void tratarPosMouse(GLFWwindow* window, double xpos, double ypos)
{
float xx = xpos / (float)LarguraJanelaPixels;
ultimoX = xx * TamanhoJanelaDesenho;
float yy = ypos / (float)AlturaJanelaPixels;
ultimoY = yy * TamanhoJanelaDesenho;
}
void tratarMouse(GLFWwindow* window, int button, int action, int mods)
{
if (JogadasEfetuadas < NumeroMaximoDeJogadas) {
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS)
{
GLubyte *rgb = ObterCorSelecionada();
Cor corSelecionada = Cor(rgb[0], rgb[1], rgb[2]);
if (!corSelecionada.EhPreto()) {
Jogar(corSelecionada);
}
}
}
}
int CALLBACK WinMain(
__in HINSTANCE hInstance,
__in HINSTANCE hPrevInstance,
__in LPSTR lpCmdLine,
__in int nCmdShow
) {
GLFWwindow* window;
//Inicializar a biblioteca
if (!glfwInit())
return -1;
//Criar a a janela
window = glfwCreateWindow(LarguraJanelaPixels, AlturaJanelaPixels, "Jogo das Cores", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
//Torna a janela o contexto ativo
glfwMakeContextCurrent(window);
//Define a funo de callback para redimensionar
glfwSetWindowSizeCallback(window, redimensionar);
//Define a funo de callback para tratar eventos do teclado
glfwSetKeyCallback(window, tratarTeclado);
//Define a funo de callback para tratar eventos do mouse
glfwSetMouseButtonCallback(window, tratarMouse);
//Define a funo de callback para tratar posio do mouse
glfwSetCursorPosCallback(window, tratarPosMouse);
//Inicializa a camera
init();
reset(); // inicializa vetor de retangulos e contagem de jogadas.
//Faa o loop at fechar a janela
while (!glfwWindowShouldClose(window) && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
{
render(); // desenha
//Swap dos buffers
glfwSwapBuffers(window);
//Processa eventos
glfwPollEvents();
}
//Encerra
glfwTerminate();
return 0;
} | true |
fa53e9927c753cfe4a43023e4e38a88d7cdcfb21 | C++ | chen0040/cpp-ogre-mllab | /HTTPEngine/HTTPManager.cpp | UTF-8 | 3,684 | 2.8125 | 3 | [
"MIT"
] | permissive | #include "HTTPManager.h"
#include <Ogre.h>
#include "../OSEnvironment/OSEnvironment.h"
#include "../tinyxml/tinyxml.h"
HTTPManager* HTTPManager::mSingleton=NULL;
HTTPManager::HTTPManager()
: mEnabled(false)
{
if(mSingleton==NULL)
{
mSingleton=this;
}
else
{
throw Ogre::Exception(42, "Multiple instances not allowed!", "HTTPManager::HTTPManager()");
}
curl_global_init(CURL_GLOBAL_ALL);
TiXmlDocument doc;
std::string filename=OSEnvironment::getFullPath("..\\config\\curl.xml");
if(!doc.LoadFile(filename.c_str()))
{
throw Ogre::Exception(42, OSEnvironment::append("Failed to parse ", filename).c_str(), "HTTPManager::HTTPManager()");
}
TiXmlElement* xmlRoot=doc.RootElement();
for(TiXmlElement* xmlLevel1=xmlRoot->FirstChildElement(); xmlLevel1 != NULL; xmlLevel1=xmlLevel1->NextSiblingElement())
{
if(strcmp(xmlLevel1->Value(), "easyhandler")==0)
{
std::string handlerName=xmlLevel1->Attribute("name");
int min_interval_in_ms=0;
xmlLevel1->QueryIntAttribute("min_interval_in_ms", &min_interval_in_ms);
CURLEasyHandler* handler=createHandler(handlerName);
handler->setUrl(xmlLevel1->Attribute("url"));
handler->set_min_interval_in_ms(min_interval_in_ms);
}
}
}
HTTPManager::~HTTPManager()
{
std::map<std::string, CURLEasyHandler*>::iterator iter=mHandlers.begin();
std::map<std::string, CURLEasyHandler*>::iterator iter_end=mHandlers.end();
for(; iter != iter_end; ++iter)
{
delete iter->second;
}
mHandlers.clear();
}
CURLEasyHandler* HTTPManager::createHandler(const std::string &name)
{
CURLEasyHandler* handler=getHandler(name);
if(handler != NULL)
{
return handler;
}
handler=new CURLEasyHandler();
mHandlers[name]=handler;
return handler;
}
bool HTTPManager::post(const std::string& handlerName, const std::map<std::string, std::string>& msg, std::string& result)
{
if(!mEnabled) return false;
CURLEasyHandler* handler=getHandler(handlerName);
if(handler==NULL)
{
throw Ogre::Exception(42, "getHandler(name) return NULL!", "HTTPManager::post(const std::string& handlerName, const std::map<std::string, std::string>& msg)");
}
if(handler->post(msg, result)==false)
{
enable(false);
return false;
}
return true;
}
bool HTTPManager::post(const std::string& handlerName, std::string& result)
{
std::map<std::string, std::string> msg;
return this->post(handlerName, msg, result);
}
CURLEasyHandler* HTTPManager::getHandler(const std::string &name)
{
std::map<std::string, CURLEasyHandler*>::iterator fnd=mHandlers.find(name);
if(fnd != mHandlers.end())
{
return fnd->second;
}
return NULL;
}
bool HTTPManager::handlerExists(const std::string& name)
{
return getHandler(name) != NULL;
}
void HTTPManager::removeHandler(const std::string &name)
{
std::map<std::string, CURLEasyHandler*>::iterator fnd=mHandlers.find(name);
if(fnd != mHandlers.end())
{
delete fnd->second;
mHandlers.erase(fnd);
}
}
void HTTPManager::enable(bool enabled)
{
mEnabled=enabled;
mEnableNotified(enabled);
}
bool HTTPManager::enabled() const
{
return mEnabled;
}
boost::signals::connection HTTPManager::subscribeEvent_onEnabled(boost::signal<void (bool)>::slot_function_type subscriber)
{
return mEnableNotified.connect(subscriber);
}
bool HTTPManager::post(const std::string& handlerName, const std::map<std::string, std::string>& msg)
{
std::string result;
return this->post(handlerName, msg, result);
}
bool HTTPManager::post(const std::string& handlerName)
{
std::string result;
return this->post(handlerName, result);
}
bool HTTPManager::postBuffer(const std::string& handlerName, std::string& result)
{
bool r=this->post(handlerName, mSimpleBuffer, result);
return r;
} | true |
ae1cffd5aa565e5c2331859186efa5f0f2e3b436 | C++ | rekafekili/DataStructure | /BOJ/2230.cpp | UHC | 898 | 2.96875 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int N;
unsigned long M;
int seq[100001];
unsigned long res = 2000000000;
// 2230 :
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
for (int i = 0; i < N; i++)
{
cin >> seq[i];
}
sort(seq, seq + N);
int first = 0, second = 1;
// M ּҿ Ƿ ٷ
// M ι° Ѽ .
// M Ŀ ù° Ѽ ּ ̰ ãƳ.
while (first < N) {
unsigned long diff = seq[second] - seq[first];
if (diff < M) {
second++;
}
else if (diff == M) {
res = M;
break;
}
else {
res = min(diff, res);
first++;
}
}
cout << res << '\n';
return 0;
} | true |
17776f9237a128f9ca459650f2638cc687570510 | C++ | cow-coding/algorithm | /BOJ/C++/4796.cpp | UTF-8 | 645 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int cnt{1};
while (1)
{
unsigned long long int L, P, V;
cin >> L >> P >> V;
if (L ==0 && P == 0 && V == 0)
break;
else {
unsigned long long int tmp;
tmp = V % P;
if (tmp <= L)
tmp = tmp;
else if (tmp > L)
tmp = L;
unsigned int day = (V / P) * L + tmp;
cout << "Case " << cnt << ": " << day << "\n";
cnt++;
}
}
return 0;
}
| true |
d314ad98448dc3a75537644b94e53ae166b7f65c | C++ | Arcan1010/Raycasting-engine | /include/Observer.h | UTF-8 | 1,070 | 2.875 | 3 | [] | no_license | //
// Created by Mateusz on 31.07.2020.
//
#ifndef GAME_OBSERVER_H
#define GAME_OBSERVER_H
#include "Camera.h"
#include "typedefs.h"
class Observer
{
Camera camera;
float sightRange;
float sightAngle;
// Ray casting variables
float rayStartingAngle;
float rayAngleDifference;
public:
//Constructor
Observer(float cX,float cY, float cZ, float cTilt, float cSightRange, float cSightAngle, float cRayStartingAngle, float cRayAngleDifference);
//Destructor
virtual ~Observer();
//Setter
void setCameraPosition(sf::Vector3f newPosition);
void setCameraTilt(float newTilt);
void setRayStartingAngle(float newRayStartingAngle);
//Getter
const Camera &getCamera() const;
const float &getSightRange() const;
const float &getSightAngle() const;
const float &getRayStartingAngle() const;
const float &getRayAngleDifference() const;
//Methods
void watch(const sf::Image &map,DoubleVertexVector &doubleVertexVector);
void followPlayer(Player &player);
};
#endif //GAME_OBSERVER_H
| true |
8371e5c438f900e6a43f5d1c84dfbb0142f11bc1 | C++ | jasons8021/POSD_ERDiagram | /ERDiagram/ERDiagram_UnitTesting/IntegrationTest.cpp | BIG5 | 14,247 | 2.90625 | 3 | [] | no_license | #include "IntegrationTest.h"
void IntegrationTest::SetUp()
{
_mkdir("testdata");
ofstream outputFile("testdata/test_file1.erd");
outputFile << "E, Engineer" << endl;
outputFile << "A, Emp_ID" << endl;
outputFile << "R, Has" << endl;
outputFile << "A, Name" << endl;
outputFile << "E, PC" << endl;
outputFile << "A, PC_ID" << endl;
outputFile << "A, Purchase_Date" << endl;
outputFile << "C" << endl;
outputFile << "C" << endl;
outputFile << "C" << endl;
outputFile << "C" << endl;
outputFile << "C, 1" << endl;
outputFile << "C, 1" << endl;
outputFile << "A, Department" << endl;
outputFile << "C" << endl;
outputFile << endl;
outputFile << "7 0,1" << endl;
outputFile << "8 0,3" << endl;
outputFile << "9 4,5" << endl;
outputFile << "10 4,6" << endl;
outputFile << "11 0,2" << endl;
outputFile << "12 2,4" << endl;
outputFile << "14 0,13" << endl;
outputFile << endl;
outputFile << "0 1,3" << endl;
outputFile << "4 5" << endl;
outputFile.close();
_erModel = new ERModel();
_presentationModel = new PresentationModel(_erModel);
}
void IntegrationTest::TearDown()
{
delete _erModel;
remove("testdata/test_file1.erd");
_rmdir("testdata");
}
// LoadFileNotExist
TEST_F(IntegrationTest, testLoadFileNotExist)
{
string result;
result = _erModel->loadERDiagram("testdata\\file_not_exist.erd");
EXPECT_EQ("File not found!!\n", result);
}
// IsPrimaryExist
TEST_F(IntegrationTest, testIsPrimaryExist)
{
string result;
string inputFileTextSet;
string componentTableString;
string connectionTableString;
// Load the test_file1.erd under the testdata directory
inputFileTextSet = _erModel->loadERDiagram("testdata\\test_file1.erd");
// Assert the diagram is loaded correctly
EXPECT_EQ("The ER diagram is displayed as follows:\n", inputFileTextSet);
// Display the table
componentTableString = _erModel->getComponentsTable(PARAMETER_ALL);
EXPECT_EQ(" E | 0 | Engineer\n A | 1 | Emp_ID\n R | 2 | Has\n A | 3 | Name\n E | 4 | PC\n A | 5 | PC_ID\n A | 6 | Purchase_Date\n C | 7 | \n C | 8 | \n C | 9 | \n C | 10 | \n C | 11 | 1\n C | 12 | 1\n A | 13 | Department\n C | 14 | \n", componentTableString);
connectionTableString = _erModel->getConnectionTable();
EXPECT_EQ(" 7 | 0 | 1 |\n 8 | 0 | 3 |\n 9 | 4 | 5 |\n 10 | 4 | 6 |\n 11 | 0 | 2 |\n 12 | 2 | 4 |\n 14 | 0 | 13 |\n", connectionTableString);
// Assert Engineers primary key is Name and Emp_ID
// EngineeruPK
EXPECT_EQ(2, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey().size());
EXPECT_EQ(1, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey()[0]);
EXPECT_EQ(3, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey()[1]);
// Assert PCs primary key is PC_ID
// PCu@PK : PC_ID
EXPECT_EQ(1, static_cast<NodeEntity*>(_erModel->searchComponent(4))->getPrimaryKey().size());
EXPECT_EQ(5, static_cast<NodeEntity*>(_erModel->searchComponent(4))->getPrimaryKey()[0]);
}
// UndoDeleteComponent
TEST_F(IntegrationTest, testUndoDeleteComponent)
{
string inputFileTextSet;
// Load the test_file1.erd under the testdata directory
inputFileTextSet = _erModel->loadERDiagram("testdata\\test_file1.erd");
// Assert the diagram is loaded correctly
EXPECT_EQ("The ER diagram is displayed as follows:\n", inputFileTextSet);
// Add an entity with text Test
_presentationModel->addNodeCmd(PARAMETER_ENTITY, "Test", 0 , 0);
// sWTestAComponentID15
EXPECT_EQ("Test", _erModel->searchComponent(15)->getText());
// Delete the entity added above
_presentationModel->deleteCmd(15);
// Assert the entity has been deleted
EXPECT_EQ(NULL, _erModel->searchComponent(15));
// Undo
_presentationModel->undoCmd();
// Assert there is an entity with text Test
EXPECT_EQ("Test", _erModel->searchComponent(15)->getText());
}
// RedoConnectComponent
TEST_F(IntegrationTest, testRedoConnectComponent)
{
string inputFileTextSet;
// Load the test_file1.erd under the testdata directory
inputFileTextSet = _erModel->loadERDiagram("testdata\\test_file1.erd");
// Assert the diagram is loaded correctly
EXPECT_EQ("The ER diagram is displayed as follows:\n", inputFileTextSet);
// Add an entity with text Test
_presentationModel->addNodeCmd(PARAMETER_ENTITY, "Test", 0 , 0);
EXPECT_EQ("Test", _erModel->searchComponent(15)->getText());
// sWTestAComponentID15
EXPECT_EQ("Test", _erModel->searchComponent(15)->getText());
// Add an entity with text Test Attr
_presentationModel->addNodeCmd(PARAMETER_ATTRIBUTE, "Test Attr", 0 , 0);
// sWTestAComponentID16
EXPECT_EQ("Test Attr", _erModel->searchComponent(16)->getText());
// Connect node 15 and 16
// Assert there is a connection between node 15 and 16
_presentationModel->addConnectionCmd(15, 16, PARAMETER_NULL);
EXPECT_EQ("C", _erModel->searchComponent(17)->getType());
// Undo
_presentationModel->undoCmd();
// Assert there is no connection between node 15 and 16
// 1516connectionwgŤFAܤwgRs
EXPECT_EQ(0, _erModel->searchRelatedComponent(15).size());
EXPECT_EQ(0, _erModel->searchRelatedComponent(16).size());
// Redo
_presentationModel->redoCmd();
// Assert node 15 and 16 are connected
EXPECT_EQ("C", _erModel->searchComponent(17)->getType());
}
// CommonUsage
TEST_F(IntegrationTest, testCommonUsage)
{
bool checkPK = false;
string inputFileTextSet;
vector<int> primaryKeys;
// Load the test_file1.erd under the testdata directory
inputFileTextSet = _erModel->loadERDiagram("testdata\\test_file1.erd");
// Assert the diagram is loaded correctly
EXPECT_EQ("The ER diagram is displayed as follows:\n", inputFileTextSet);
// Add an Entity with text "Work Diary"
_presentationModel->addNodeCmd(PARAMETER_ENTITY, "Work Diary", 0 , 0);
// sWWork DiaryAComponentID15
EXPECT_EQ("Work Diary", _erModel->searchComponent(15)->getText());
// Add a Relationship with text "Write"
_presentationModel->addNodeCmd(PARAMETER_RELATIONSHIP, "Write", 0 , 0);
// sWWriteAComponentID16
EXPECT_EQ("Write", _erModel->searchComponent(16)->getText());
// Connect node 0 and 16, and set its cardinality as "1"
_presentationModel->addConnectionCmd(0, 16, "1");
// Assert node 0 and 16 are connected
EXPECT_EQ("C", _erModel->searchComponent(17)->getType());
EXPECT_EQ("1", _erModel->searchComponent(17)->getText());
// Connect node 15 and 16
_presentationModel->addConnectionCmd(15, 16, PARAMETER_NULL);
// Assert node 15 and 16 are connected
EXPECT_EQ("C", _erModel->searchComponent(18)->getType());
// Add an Attribute with text "Content"
_presentationModel->addNodeCmd(PARAMETER_ATTRIBUTE, "Content", 0 , 0);
// sWContentAComponentID19
EXPECT_EQ("Content", _erModel->searchComponent(19)->getText());
// Add an Attribute with text "WD_ID"
_presentationModel->addNodeCmd(PARAMETER_ATTRIBUTE, "WD_ID", 0 , 0);
// sWWD_IDAComponentID20
EXPECT_EQ("WD_ID", _erModel->searchComponent(20)->getText());
// Add an Attribute with text "WD_date"
_presentationModel->addNodeCmd(PARAMETER_ATTRIBUTE, "WD_date", 0 , 0);
// sWWD_IDAComponentID21
EXPECT_EQ("WD_date", _erModel->searchComponent(21)->getText());
// Connect node 15 and 19
_presentationModel->addConnectionCmd(15, 19, PARAMETER_NULL);
// Assert node 15 and 19 are connected
EXPECT_EQ("C", _erModel->searchComponent(22)->getType());
// Connect node 15 and 20
_presentationModel->addConnectionCmd(15, 20, PARAMETER_NULL);
// Assert node 15 and 20 are connected
EXPECT_EQ("C", _erModel->searchComponent(23)->getType());
// Connect node 15 and 21
_presentationModel->addConnectionCmd(15, 21, PARAMETER_NULL);
// Assert node 15 and 21 are connected
EXPECT_EQ("C", _erModel->searchComponent(24)->getType());
// Set "Work Diary" primary key "WD_ID"
primaryKeys.push_back(20);
_erModel->setPrimaryKey(15, primaryKeys);
primaryKeys.pop_back();
// Assert "Work Diary" has the primary key "WD_ID"
for (int i = 0; i < _erModel->searchRelatedComponent(15).size(); i++)
{
if (_erModel->searchRelatedComponent(15)[i]->getID() == 20)
{
if (static_cast<NodeAttribute*>(_erModel->searchRelatedComponent(15)[i])->getIsPrimaryKey())
{
checkPK = true;
break;
}
}
}
EXPECT_TRUE(checkPK);
checkPK = false;
// Display the table
EXPECT_EQ(" E | 0 | Engineer\n A | 1 | Emp_ID\n R | 2 | Has\n A | 3 | Name\n E | 4 | PC\n A | 5 | PC_ID\n A | 6 | Purchase_Date\n C | 7 | \n C | 8 | \n C | 9 | \n C | 10 | \n C | 11 | 1\n C | 12 | 1\n A | 13 | Department\n C | 14 | \n E | 15 | Work Diary\n R | 16 | Write\n C | 17 | 1\n C | 18 | \n A | 19 | Content\n A | 20 | WD_ID\n A | 21 | WD_date\n C | 22 | \n C | 23 | \n C | 24 | \n", _erModel->getComponentsTable(PARAMETER_ALL));
EXPECT_EQ(" 7 | 0 | 1 |\n 8 | 0 | 3 |\n 9 | 4 | 5 |\n 10 | 4 | 6 |\n 11 | 0 | 2 |\n 12 | 2 | 4 |\n 14 | 0 | 13 |\n 17 | 0 | 16 |\n 18 | 15 | 16 |\n 22 | 15 | 19 |\n 23 | 15 | 20 |\n 24 | 15 | 21 |\n", _erModel->getConnectionTable());
EXPECT_EQ(" Engineer | PK(Emp_ID, Name), Department, FK(PC_ID)\n PC | PK(PC_ID), Purchase_Date\n Work Diary| PK(WD_ID), Content, WD_date\n", _erModel->getERDiagramTable());
// Assert the Entity "Work Diary" exists
EXPECT_TRUE(_erModel->searchComponentExist("15", PARAMETER_ENTITY));
// Assert "Work Diary" has the primary key "WD_ID"
for (int i = 0; i < _erModel->searchRelatedComponent(15).size(); i++)
{
if (_erModel->searchRelatedComponent(15)[i]->getID() == 20)
{
if (static_cast<NodeAttribute*>(_erModel->searchRelatedComponent(15)[i])->getIsPrimaryKey())
{
checkPK = true;
break;
}
}
}
EXPECT_TRUE(checkPK);
checkPK = false;
// Delete the Entity he/she added above
_presentationModel->deleteCmd(15);
// Assert the Entity has been deleted
// 18: 15-16 | 22: 15-19 | 23 : 15-20 | 24 : 15-21
EXPECT_EQ(NULL, _erModel->searchComponent(18));
EXPECT_EQ(NULL, _erModel->searchComponent(22));
EXPECT_EQ(NULL, _erModel->searchComponent(23));
EXPECT_EQ(NULL, _erModel->searchComponent(24));
// Display the table
EXPECT_EQ(" E | 0 | Engineer\n A | 1 | Emp_ID\n R | 2 | Has\n A | 3 | Name\n E | 4 | PC\n A | 5 | PC_ID\n A | 6 | Purchase_Date\n C | 7 | \n C | 8 | \n C | 9 | \n C | 10 | \n C | 11 | 1\n C | 12 | 1\n A | 13 | Department\n C | 14 | \n R | 16 | Write\n C | 17 | 1\n A | 19 | Content\n A | 20 | WD_ID\n A | 21 | WD_date\n", _erModel->getComponentsTable(PARAMETER_ALL));
EXPECT_EQ(" 7 | 0 | 1 |\n 8 | 0 | 3 |\n 9 | 4 | 5 |\n 10 | 4 | 6 |\n 11 | 0 | 2 |\n 12 | 2 | 4 |\n 14 | 0 | 13 |\n 17 | 0 | 16 |\n", _erModel->getConnectionTable());
EXPECT_EQ(" Engineer | PK(Emp_ID, Name), Department, FK(PC_ID)\n PC | PK(PC_ID), Purchase_Date\n", _erModel->getERDiagramTable());
// Assert the Entity "Work Diary" does not exist
EXPECT_EQ(NULL, _erModel->searchComponent(15));
// Assert Engineer's primary key is "Name" and "Emp_ID"
EXPECT_EQ(2, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey().size());
EXPECT_EQ(1, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey()[0]);
EXPECT_EQ(3, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey()[1]);
// Undo
_presentationModel->undoCmd();
// Display the table
EXPECT_EQ(" E | 0 | Engineer\n A | 1 | Emp_ID\n R | 2 | Has\n A | 3 | Name\n E | 4 | PC\n A | 5 | PC_ID\n A | 6 | Purchase_Date\n C | 7 | \n C | 8 | \n C | 9 | \n C | 10 | \n C | 11 | 1\n C | 12 | 1\n A | 13 | Department\n C | 14 | \n E | 15 | Work Diary\n R | 16 | Write\n C | 17 | 1\n C | 18 | \n A | 19 | Content\n A | 20 | WD_ID\n A | 21 | WD_date\n C | 22 | \n C | 23 | \n C | 24 | \n", _erModel->getComponentsTable(PARAMETER_ALL));
EXPECT_EQ(" 7 | 0 | 1 |\n 8 | 0 | 3 |\n 9 | 4 | 5 |\n 10 | 4 | 6 |\n 11 | 0 | 2 |\n 12 | 2 | 4 |\n 14 | 0 | 13 |\n 17 | 0 | 16 |\n 18 | 15 | 16 |\n 22 | 15 | 19 |\n 23 | 15 | 20 |\n 24 | 15 | 21 |\n", _erModel->getConnectionTable());
EXPECT_EQ(" Engineer | PK(Emp_ID, Name), Department, FK(PC_ID)\n PC | PK(PC_ID), Purchase_Date\n Work Diary| PK(WD_ID), Content, WD_date\n", _erModel->getERDiagramTable());
// Assert "Work Diary" has the primary key "WD_ID"
for (int i = 0; i < _erModel->searchRelatedComponent(15).size(); i++)
{
if (_erModel->searchRelatedComponent(15)[i]->getID() == 20)
{
if (static_cast<NodeAttribute*>(_erModel->searchRelatedComponent(15)[i])->getIsPrimaryKey())
{
checkPK = true;
break;
}
}
}
EXPECT_TRUE(checkPK);
checkPK = false;
// Redo
_presentationModel->redoCmd();
// Assert the Entity "Work Diary" does not exist
EXPECT_EQ(NULL, _erModel->searchComponent(15));
// Assert Engineer's primary key is "Name" and "Emp_ID"
EXPECT_EQ(2, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey().size());
EXPECT_EQ(1, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey()[0]);
EXPECT_EQ(3, static_cast<NodeEntity*>(_erModel->searchComponent(0))->getPrimaryKey()[1]);
}
| true |
ae583874148e651147b02980e1c990ee129979e7 | C++ | bojotamara/MapReduce | /partition.h | UTF-8 | 632 | 3.203125 | 3 | [] | no_license | #pragma once
#include <pthread.h>
#include <map>
// Comparator struct that allows the sorting of char * keys
struct CStringComparator {
bool operator()(char* a, char* b);
};
// Struct for the intermediate data structure used by the mappers and reducer
struct Partition
{
// holds the key/value pairs
std::multimap<char *, char *, CStringComparator> map;
// pointer that references the current key/value pair the reducer is processing
std::multimap<char *, char *, CStringComparator>::iterator iterator;
// mutex lock for the partition
pthread_mutex_t partition_mutex = PTHREAD_MUTEX_INITIALIZER;
}; | true |
fa4255b693539af6b12b84359634d4a2972bbfb2 | C++ | ocdian/competitive-code | /AtCoder/Educational DP Contest/F - LCS/main.cpp | UTF-8 | 1,115 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int dp[3010][3010];
string a,b;
string generateLCS(int n, int m) {
string lcs = "";
while (n > 0 && m > 0)
{
if (a[n-1]==b[m-1]) {
lcs += a[n-1];
n--;
m--;
}
else {
if (dp[n-1][m]>dp[n][m-1]) n--;
else m--;
}
}
reverse(lcs.begin(), lcs.end());
return lcs;
}
string lcs(int n, int m) {
pair<int,int> maxCell;
int ans = 0;
for (int i=0; i <= n; i++) {
for (int j=0; j <= m; j++) {
if (i==0 || j==0) dp[i][j] = 0;
else if (a[i-1]==b[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
if (dp[i][j]>ans) {
ans = dp[i][j];
maxCell.first = i;
maxCell.second = j;
}
}
}
return generateLCS(maxCell.first, maxCell.second);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> a >> b;
cout << lcs(a.size(), b.size()) << "\n";
return 0;
}
| true |
902109b9038a45b0c68a4a61e50fd128e63e732c | C++ | kbavishi/MineBench | /SEMPHY/programs/rateShift/posData.h | UTF-8 | 1,780 | 2.84375 | 3 | [] | no_license | // $Id: posData.h 2399 2014-03-13 22:43:51Z wkliao $
#ifndef POS_DATA
#define POS_DATA
#include "someUtil.h"
#include <iostream>
#include <iomanip>
class posData {
public:
posData(int num,const string& content, int numOfSeqsWithoutGaps, int numOfSeqs) :
_num(num), _content(content), _numOfSeqsWithoutGaps(numOfSeqsWithoutGaps), _numOfSeqs(numOfSeqs) {}
friend ostream& operator<<(ostream &out, const posData &pos);
protected:
int _num; // the number of the position in the sequence (starting from 1)
string _content; // the alphabet content of the position in the reference sequence
int _numOfSeqsWithoutGaps;
int _numOfSeqs;
};
class posDataSSRV : public posData {
public:
posDataSSRV(int num, const string& content, int numOfSeqsWithoutGaps, int numOfSeqs,MDOUBLE probSSRV) :
posData(num,content,numOfSeqsWithoutGaps,numOfSeqs), _probSSRV(probSSRV) {}
friend ostream& operator<<(ostream &out, const posDataSSRV &pos);
int operator<(const posDataSSRV other) const;
private:
MDOUBLE _probSSRV;
};
// compare two pointers to posDataSSRV
class cmpPosDataSSRVPointers {
public:
int operator()(const posDataSSRV* p1, const posDataSSRV* p2) const {return (*p2)<(*p1);}
};
class posDataBranchShift {
public:
posDataBranchShift(int num, MDOUBLE probAcceleration, MDOUBLE probDeceleration);
MDOUBLE getProbAcceleration() const {return _probAcceleration;}
MDOUBLE getProbDeceleration() const {return _probDeceleration;}
MDOUBLE getProbRateShift() const {return _probAcceleration+_probDeceleration;}
MDOUBLE getProbNoRateShift() const {return 1.0-getProbRateShift();}
friend ostream& operator<<(ostream &out, const posDataBranchShift &pos);
private:
int _num;
MDOUBLE _probAcceleration;
MDOUBLE _probDeceleration;
};
#endif // POS_DATA
| true |
586fed469160627c5f54cbb260ec14e532024c4b | C++ | RucheCo/project | /Arduino/DHT11.cpp | UTF-8 | 432 | 2.53125 | 3 | [] | no_license |
#include <SimpleDHT.h>
// for DHT11,
// VCC: 5V or 3V
// GND: GND
// DATA: 2
// 100nF entre VDD et GND
// R: 1.5 Kohm
int pinDHT11 = 2;
SimpleDHT11 dht11;
unsigned int GetHumidity() {
// read without samples.
byte humidity = 0;
byte temperature = 0;
if (dht11.read(pinDHT11, &temperature, &humidity, NULL)) {
Serial.print("Read DHT11 failed.");
return;
}
return((unsigned int)humidity);
}
| true |
00b9c367085298f39c8e951b153db8d596b08f80 | C++ | Liam0205/leetcode | /algorithm/0811-Subdomain-Visit-Count/solution.cc | UTF-8 | 947 | 2.71875 | 3 | [] | no_license | class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
std::unordered_map<std::string, size_t> visit_count;
for (auto s : cpdomains) {
std::istringstream iss(s);
size_t count;
std::string domain;
iss >> count >> domain;
for (size_t cut = 0; cut != std::string::npos; cut = domain.find_first_of("."), domain = domain.substr(cut + 1, std::string::npos)) {
if (visit_count.find(domain) == visit_count.end()) {
visit_count.insert({domain, count});
} else {
visit_count[domain] += count;
}
}
}
std::vector<std::string> res;
for (auto iter = visit_count.begin(); iter != visit_count.end(); ++iter) {
res.emplace_back(std::to_string(iter->second) + " " + iter->first);
}
return res;
}
};
| true |
48ace0cbd7cc2ece71407331c5e03215601cdf5a | C++ | stradivarius10/Stradivarius | /ex5/Observer.cpp | UTF-8 | 702 | 2.53125 | 3 | [] | no_license | #include "Observer.h"
/* This code is a copy of the code we saw in class. YOSSI approved to use it as is!*/
//================================================================================
// Subject Implemenation
//================================================================================
void Subject::Attach(Observer* ob) {
m_observers.push_back(ob);
}
void Subject::Detach(Observer* ob) {
size_t i = 0;
for (i = 0; i < m_observers.size(); i++)
{
if (m_observers[i] == ob) break;
}
if (i != m_observers.size())
{
m_observers.erase(m_observers.begin() + i);
}
}
void Subject::Notify() {
for (size_t i = 0; i < m_observers.size(); i++)
(m_observers[i])->Update(this);
}
| true |
711c37295ceec19f4cac13ddc5d1a4827dee60ed | C++ | sticnarf/hane | /src/utils/buffer.cpp | UTF-8 | 4,841 | 3.265625 | 3 | [
"MIT",
"Vim",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #include "buffer.hpp"
#include <cstring>
#include <algorithm>
#include <stdexcept>
Buffer::Buffer()
: length(0), head(0) {
blocks.push_back(new BufferBlock);
}
void Buffer::push(const char *bytes, size_t len) {
size_t bytesPtr = 0;
while (bytesPtr < len) {
BufferBlock *block = blocks.back();
if (block->length == BLOCK_SIZE) {
block->nextBlock = new BufferBlock;
block = block->nextBlock;
blocks.push_back(block);
}
size_t &blockPtr = block->length;
size_t copySize = std::min(len - bytesPtr, BLOCK_SIZE - blockPtr);
memcpy(block->block + blockPtr, bytes + bytesPtr, copySize);
this->length += copySize;
bytesPtr += copySize;
blockPtr += copySize;
}
}
char &Buffer::operator[](size_t index) {
if (index > length) {
throw std::out_of_range("Buffer access out of range");
}
size_t actualIndex = index + head;
size_t blockIndex = actualIndex >> BLOCK_SIZE_EXP;
size_t blockPtr = actualIndex - (blockIndex << BLOCK_SIZE_EXP);
return blocks[blockIndex]->block[blockPtr];
}
BufferPtr Buffer::split(size_t pos) {
if (pos > length) {
throw std::out_of_range("Buffer access out of range");
}
size_t actualPos = pos + head;
size_t blockIndex = actualPos >> BLOCK_SIZE_EXP;
size_t blockPtr = actualPos - (blockIndex << BLOCK_SIZE_EXP);
BufferPtr newBuffer = std::make_shared<Buffer>(nullptr);
for (size_t i = 0; i < blockIndex; i++) {
BufferBlock *block = this->blocks[i];
newBuffer->blocks.push_back(block);
}
auto *lastBlock = new BufferBlock;
if (!newBuffer->blocks.empty())
newBuffer->blocks.back()->nextBlock = lastBlock;
lastBlock->length = blockPtr;
memcpy(lastBlock->block, this->blocks[blockIndex]->block, blockPtr);
newBuffer->blocks.push_back(lastBlock);
newBuffer->head = head;
newBuffer->length = pos;
blocks.erase(blocks.begin(), blocks.begin() + blockIndex);
if (blocks.empty())
blocks.push_back(new BufferBlock);
head = blockPtr;
length -= pos;
return newBuffer;
}
Buffer::~Buffer() {
while (!blocks.empty()) {
delete blocks.back();
blocks.pop_back();
}
}
size_t Buffer::len() {
return length;
}
Buffer::iterator::iterator(Buffer *buffer, size_t pos)
: buffer(buffer), pos(pos) {}
Buffer::iterator Buffer::begin() {
return {this, 0};
}
Buffer::iterator Buffer::end() {
return {this, length - 1};
}
size_t Buffer::find(const char *pattern, size_t len) {
size_t i = 0;
for (; i < this->len(); i++) {
for (size_t j = 0; j < len; j++) {
if ((*this)[i + j] != pattern[j]) {
break;
}
if (j == (len - 1)) {
return i;
}
}
}
return i;
}
size_t Buffer::find(char c) {
size_t i = 0;
for (; i < this->len(); i++) {
if ((*this)[i] == c) {
break;
}
}
return i;
}
std::string Buffer::toString() {
return toString(0, len());
}
std::string Buffer::toString(size_t from, size_t to) {
std::string s;
s.reserve(to - from);
size_t actualFrom = from + head;
size_t fromBlockIndex = actualFrom >> BLOCK_SIZE_EXP;
size_t fromBlockPtr = actualFrom - (fromBlockIndex << BLOCK_SIZE_EXP);
size_t actualTo = to + head;
size_t toBlockIndex = actualTo >> BLOCK_SIZE_EXP;
size_t toBlockPtr = actualTo - (toBlockIndex << BLOCK_SIZE_EXP);
if (fromBlockIndex == toBlockIndex) {
s.append(blocks[fromBlockIndex]->block + fromBlockPtr, toBlockPtr - fromBlockPtr);
} else {
s.append(blocks[fromBlockIndex]->block + fromBlockPtr, blocks[fromBlockIndex]->length - fromBlockPtr);
for (size_t i = fromBlockIndex + 1; i < toBlockIndex; i++) {
s.append(blocks[i]->block, blocks[i]->length);
}
s.append(blocks[toBlockIndex]->block, toBlockPtr);
}
return s;
}
Buffer::Buffer(void *_)
: length(0), head(0) {}
BufferBlock::BufferBlock() {
this->length = 0;
this->block = new char[BLOCK_SIZE];
this->nextBlock = nullptr;
}
BufferBlock::~BufferBlock() {
delete[] this->block;
}
char &Buffer::iterator::operator*() {
return (*buffer)[pos];
}
Buffer::iterator Buffer::iterator::operator++() {
iterator it = *this;
pos++;
return it;
}
Buffer::iterator Buffer::iterator::operator++(int) {
pos++;
return *this;
}
char *Buffer::iterator::operator->() {
return &(*buffer)[pos];
}
bool Buffer::iterator::operator==(const Buffer::iterator rhs) {
return buffer == rhs.buffer && pos == rhs.pos;
}
bool Buffer::iterator::operator!=(const Buffer::iterator rhs) {
return buffer != rhs.buffer || pos != rhs.pos;
}
| true |
8ebce158430e0df2ec79b89096ccc82036ff3178 | C++ | TaniyaPeters/BorealEngine | /include/VertexBuffer.h | UTF-8 | 1,074 | 3.234375 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "Vertex.h"
namespace Boreal {
/**
* @brief Allows user to create and manage vertex buffers
*
* @section Description
*
* The vertex buffer class allows the user to create, bind, and unbind vertex buffers. This is used to create models along with the index buffer.
*
*/
class VertexBuffer {
public:
/**
* @brief Constructor that initializes the vertex buffer with a pointer to an array of vertices and the count of vertices in the array
*
* @param [in] vertices A pointer to an array of vertices
* @param [in] vertexCount The number of vertices in the array pointed to by the vertices parameter
*
*/
VertexBuffer(Vertex* vertices, unsigned int vertexCount);
/**
* @brief Destructor that deletes the vertex buffer.
*/
~VertexBuffer();
/**
* @brief Bind function binds the vertex buffer to the current context
*
*/
void Bind();
/**
* @brief UnBind function unbinds the vertex buffer from the current context
*
*/
void UnBind();
private:
unsigned int m_VBO; // ID of Vertex Buffer Object
};
}
| true |
0c3784bc09cbc237f5e625172f80a2dbdde2ce88 | C++ | rheehot/Algorithm-40 | /BOJ/1316/1316.cpp | UHC | 1,276 | 3.578125 | 4 | [] | no_license | #include <iostream>
bool isGroupWord(std::string str) {
bool check[26] = { false, };
int i = 0;
while (i < str.length() - 1) {
if (str[i] != str[i + 1]) {
check[str[i] - 'a'] = true;
if (check[str[i + 1] - 'a']) return false;
}
i++;
}
return true;
}
int main() {
int n, cnt = 0;
scanf("%d", &n);
std::string str[100];
for (int i = 0; i < n; i++) {
std::cin >> str[i];
if (isGroupWord(str[i])) cnt++;
}
printf("%d", cnt);
return 0;
}
/*
ܾ ܾ ϴ ڿ ؼ, ڰ ؼ Ÿ 츸 Ѵ.
, ccazzzzbb c, a, z, b ؼ Ÿ, kin k, i, n ؼ Ÿ ܾ,
aabbbccb b Ÿ ܾ ƴϴ.
ܾ N Է ܾ ϴ α ۼϽÿ.
Է
ù° ٿ ܾ N ´. N 100 ۰ų ڿ̴.
° ٺ N ٿ ܾ ´. ܾ ĺ ҹڷθ Ǿְ ߺ , ̴ ִ 100̴.
ù° ٿ ܾ Ѵ.
*/ | true |
727dc17fd8b027622b8a5bfa33990d72ee5f6a45 | C++ | GunterMueller/DBJ | /dbj/include/DbjRecordIterator.hpp | UTF-8 | 4,190 | 2.515625 | 3 | [] | no_license | /*************************************************************************\
* *
* (C) 2004-2005 *
* Lehrstuhl fuer Datenbanken und Informationssysteme *
* Friedrich-Schiller-Universitaet Jena *
* Ernst-Abbe-Platz 1-2 *
* 07745 Jena *
* *
\*************************************************************************/
#if !defined(__DbjRecordIterator_hpp__)
#define __DbjRecordIterator_hpp__
#include "Dbj.hpp"
#include "DbjIterator.hpp"
// Vorwaertsdeklaration
class DbjRecordManager;
class DbjRecord;
/** Iterator ueber Records.
*
* Dieser Iterator wird dazu verwendet ueber die Records einer Tabelle zu
* traversieren. Er implementiert damit einen Table-Scan. Der Iterator wird
* vom Record Manager erzeugt, und er verwendet diesen auch, um die einzelnen
* Records selbst zu erhalten und anschliessend zurueckzugeben.
*
* Der Record Iterator wird vom Tupel-Iterator dazu verwendet, um an die
* eigentlichen Daten des Tupels heranzukommen. Die Daten selber stehen in
* den Datenbankseiten, die im Systempuffer zur Verfuegung gestellt werden.
*
* Intern steht der Iterator grundsaetzlich auf dem zuletzt zurueckgegebenen
* Tupel. Eine Ausnahme bildet dabei logischerweise der erste Record, der
* keinen Vorgaenger hat. Daher wird das Flag "gotNextRecordTid", welches
* markiert, ob wir schon die naechste Tupel-ID bestimmt haben, beim Start des
* Scans auf "true" gesetzt.
*/
class DbjRecordIterator : public DbjIterator
{
public:
/** Gib naechsten Record.
*
* Liefere den naechsten Record der Tabelle zurueck. Wenn kein weitere
* Record existiert bzw. alle Records bereits verarbeitet wurden, so wird
* der Fehlercode <code>DBJ_NOT_FOUND_WARN</code> zurueckzugeben.
* Zusaetzlich kann zuvor ueber "hasNext" abgefragt werden, ob ein
* weiterer Record zur Verfuegung steht.
*
* Der Aufrufer muss entweder einen NULL-Zeiger uebergeben, in welchem
* Fall ein neues DbjRecord Objekt erzeugt wird. Andernfalls muss ein
* existierendes DbjRecord Objekt uebergeben wird, und dieses Objekt wird
* mit den Daten des naechsten Records initialisiert.
*
* @param record Referenz auf den zurueckzugebenden Record
*/
virtual DbjErrorCode getNext(DbjRecord *&record);
/** Abfrage nach naechsten Record.
*
* Mit dieser Methode kann abgefragt werden, ob der Iterator einen
* weiteren Record zurueckliefern wird, oder ob das Ende der Tabelle ueber
* die iteriert wird bereits erreicht ist. Sind noch weitere Records
* vorhanden, so wird "true" zurueckgegeben, andernfalls ist das Ergebnis
* "false".
*/
virtual bool hasNext() const;
/** Setze Iterator zurueck.
*
* Setze den Iterator wieder auf den Anfang der Tabelle zurueck. Der
* naechste Aufruf zu "getNext" wird wieder das allererste Tupel der
* Tabelle zurueckliefern.
*/
virtual DbjErrorCode reset();
private:
/// Konstruktor (wird ausschliesslich vom Record Manager aufgerufen)
DbjRecordIterator(const TableId tableId);
/// ID der Tabelle, auf welcher der Iterator operiert
TableId tableId;
/// ID der Seite, auf der das erstes Tupel des Iterators zu finden ist
PageId firstPage;
/// Id des Slot des ersten Tupels
Uint8 firstSlot;
/// ID der Seite, auf der das zuletzt (aktuell) gelesene Tupel zu finden ist
PageId currentPage;
/// ID der Slots des aktuellen Tupels
Uint8 currentSlot;
/// Flag, ob die TID des naechsten Records bereits ermittelt wurde
bool gotNextRecordTid;
/// Zeiger auf die Instanz des Record Managers
DbjRecordManager *recordMgr;
friend class DbjRecordManager;
};
#endif /* __DbjRecordIterator_hpp__ */
| true |
68092a7b475a6467e4c72c24394b007a07e2efa2 | C++ | ebirenbaum/ParticleSolver | /cpu/src/constraint/contactconstraint.cpp | UTF-8 | 2,254 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "contactconstraint.h"
ContactConstraint::ContactConstraint(int first, int second, bool st)
: Constraint(), i1(first), i2(second), stabile(st)
{
}
ContactConstraint::~ContactConstraint()
{
}
void ContactConstraint::project(QList<Particle *> *estimates, int *counts)
{
Particle *p1 = estimates->at(i1), *p2 = estimates->at(i2);
if (p1->tmass == 0.f && p2->tmass == 0.f) {
return;
}
glm::dvec2 diff = p1->getP(stabile) - p2->getP(stabile);
double wSum = p1->tmass + p2->tmass,
dist = glm::length(diff),
mag = dist - PARTICLE_DIAM;
// Previous iterations have moved particles out of collision
if (mag > 0) {
return;
}
double scale = mag / wSum;
glm::dvec2 dp = (scale / dist) * diff,
dp1 = -p1->tmass * dp / (double)counts[i1],
dp2 = p2->tmass * dp / (double)counts[i2];
p1->ep += dp1;
p2->ep += dp2;
if (stabile) {
p1->p += dp1;
p2->p += dp2;
}
}
void ContactConstraint::draw(QList<Particle *> *particles)
{
Particle *p1 = particles->at(i1), *p2 = particles->at(i2);
glColor3f(1,1,0);
glBegin(GL_LINES);
glVertex2f(p1->p.x, p1->p.y);
glVertex2f(p2->p.x, p2->p.y);
glEnd();
glPointSize(3);
glBegin(GL_POINTS);
glVertex2f(p1->p.x, p1->p.y);
glVertex2f(p2->p.x, p2->p.y);
glEnd();
}
double ContactConstraint::evaluate(QList<Particle *> *estimates)
{
Particle *p1 = estimates->at(i1), *p2 = estimates->at(i2);
double dist = glm::length(p1->getP(stabile) - p2->getP(stabile));
return dist > PARTICLE_DIAM ? 0 : dist - PARTICLE_DIAM;
}
glm::dvec2 ContactConstraint::gradient(QList<Particle *> *estimates, int respect)
{
if (!(respect == i1 || respect == i2)) {
return glm::dvec2();
}
Particle *p1 = estimates->at(i1), *p2 = estimates->at(i2);
glm::dvec2 diff = p1->getP(stabile) - p2->getP(stabile);
double dist = glm::length(diff);
if (dist > PARTICLE_DIAM) {
return glm::dvec2();
}
glm::dvec2 n = diff / dist;
if (respect == i1) {
return n;
} else {
return -n;
}
}
void ContactConstraint::updateCounts(int *counts)
{
counts[i1]++;
counts[i2]++;
}
| true |
fb954b00f86c4d815da366eb63374d4a92f7cd2c | C++ | wayne155/Algorithm | /templates/binary_search/binaryPow.cpp | UTF-8 | 875 | 3.203125 | 3 | [] | no_license | //
// Created by dell on 2021/9/8.
//
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL
// binaryPow 求 a^b % m
// 基于以下事实
// b % 2 = 1 : a^b = a * a ^(b-1)
// b % 2 = 0 : a^b = a^(b/2) * a^(b/2)
LL binaryPowRecursive( LL a, LL b , LL m ){
if (b ==0 ) return 1;
if ( b %2 ) return a * binaryPowRecursive(a , b-1 , m) % m;
else{
LL mul = binaryPowRecursive(a , b/2 , m );
return mul * mul % m;
}
}
// binaryPowIter 求 a^b % m
// 基于以下事实
// b % 2 = 1 : a^b = a * a ^(b-1)
// b % 2 = 0 : a^b = a^(b/2) * a^(b/2)
LL binaryPowIter( LL a, LL b , LL m ){
LL ans = 1;
while(b > 0){
if (b&1){
ans = ans * a %m;
}
a = a * a %m;
b >>= 1;
}
return ans;
}
int main(){
int A[10] = {1,2,3,4,5,6,7,7,9,10};
return 0;
} | true |
4599690203bf36e9a50da7702b9428c604c7a29a | C++ | nessim-m/CS-202 | /myStackMain.cpp | UTF-8 | 2,285 | 4.25 | 4 | [] | no_license | #include <iostream>
#include <string>
#include "myStack.h"
using namespace std;
int main()
{
string str;// string variable to cin user input
cout<< "Enter the arithmetic expression: ";
getline(cin, str);
int leftside=0;
int rightside=0;// int counter variable
int k=0;// int counter variable
//the following while loop counts how many of the following specified characters below was read in
while(str[k] != '\0')
{
//if it read a the following characters it incremnet rightside by 1
if(str[k] == '[' or str[k] == '(' or str[k] == '{')
{
rightside++;
}
//if it read a the following characters it incremnet leftside by 1
if(str[k] == ']' or str[k] == ')' or str[k] == '}')
{
leftside++;
}
k++;
}
//if the leftside does not equal to the right side then it output the following and terminate the program
if(leftside!= rightside)
{
cout<< "Oops, looks like something went wrong" << endl;
return 0;
}
myStack list(rightside);// mystack object with a size of the user's input
int i=0;
/*The following while loop runs through the end of the line read in.*/
while(str[i]!= '\0')
{
//if the following characters are read, it pushes it to the list object
if(str[i] == '[' or str[i] == '(' or str[i] == '{')
{
list.push(str[i]);
}
//if the following character read in from string matches with the last character pushed to list's object, it pops it
if(list.top() == '[' and str[i] == ']')
{
list.pop();
}
//if the following character read in from string matches with the last character pushed to list's object, it pops it
if(list.top() == '{' and str[i] == '}')
{
list.pop();
}
///if the following character read in from string matches with the last character pushed to list's object, it pops it
if(list.top() == '(' and str[i] == ')')
{
list.pop();
}
i++;
}
//The following calls the empty funciton, if returns true it outputs the following
if(list.isEmpty() == true)
{
cout<< "All brackets/parenthesis are matched correctly" << endl;
}
//If the function called returns false it output the following
else
{
cout<< "Oops, looks like something went wrong" << endl;
}
return 0;
} | true |
5d687d40e4a308add03b37278b7650ff04f3a102 | C++ | FOSS-society/libre-engine | /include/system/Mouse.hpp | UTF-8 | 645 | 2.703125 | 3 | [] | no_license | #ifndef MOUSE_HPP
#define MOUSE_HPP
#include "../math/vector2.hpp"
#include <SDL2/SDL.h>
namespace libre{
namespace system{
enum class ButtonPress{
LEFT,MIDDLE,RIGHT,X1 , X2, NONE
};
class Mouse{
private:
math::Vector2<int32_t> mousePosition;
ButtonPress m_ButtonPress;
public:
Mouse();
void setMousePosition(int x, int y);
void setButtonPress(ButtonPress press);
inline math::Vector2<int32_t> getMousePosition(){ return this->mousePosition;}
inline ButtonPress getButtonPress(){return this->m_ButtonPress;}
};
}
}
#endif // MOUSE_HPP
| true |
6a76ea3cfe4a60da07d10276c3995202dc5e908c | C++ | clatisus/ACM-ICPC-Team-Archive | /zhongzihao-personal/51nod/1170.cpp | UTF-8 | 11,634 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
typedef long long ll;
typedef __int128 i128;
const ll base1 = 1ll << 50;
const ll base2 = 298023223876953125ll;
int tot;
struct Big{ // 仅支持非负整数
static ll base; // 修改它时记得修改输入输出格式
static int type;
static int maxbit;
std::vector <ll> a;
int len;
Big():len(0){}
Big(ll len, int mark):len(len){a.resize(len);}
explicit Big(ll p){
for ( ; p; p /= base){
a.push_back(p % base);
}
len = a.size();
}
Big(char *s, int len){
for (int i = len - 1; i >= 0; -- i){
a.push_back(s[i] - '0');
}
this -> len = a.size();
normal();
}
ll operator [] (int sit)const{return sit >= len || sit < 0 ? 0 : a[sit];}
void normal(){
for ( ; len && !a[len - 1]; -- len)
;
}
void resize(int len){
a.resize(len);
this -> len = len;
normal();
}
bool operator < (const Big &q)const{
if (len != q.len) return len < q.len;
for (int i = len - 1; ~i; -- i){
if (a[i] != q.a[i]) return a[i] < q.a[i];
}
return false;
}
Big operator + (const Big &p)const{
if (type){
Big ret(maxbit, -1);
for (int i = 0; i < maxbit; ++ i){
ret.a[i] += (*this)[i] + p[i];
if (ret.a[i] >= base){
ret.a[i] -= base;
if (i < maxbit - 1){
++ ret.a[i + 1];
}
}
}
return ret;
}
Big ret(std::max(len, p.len) + 1, -1);
for (int i = 0; i < ret.len - 1; ++ i){
ret.a[i] += (*this)[i] + p[i];
if (ret.a[i] >= base) ret.a[i] -= base, ++ ret.a[i + 1];
}
ret.normal();
return ret;
}
Big operator - (const Big &p)const{
if (type){
Big ret(maxbit, -1);
for (int i = 0; i < maxbit; ++ i){
ret.a[i] += (*this)[i] - p[i];
if (ret.a[i] < 0){
ret.a[i] += base;
if (i < maxbit - 1){
-- ret.a[i + 1];
}
} } return ret;
}
Big ret(std::max(len, p.len) + 1, -1);
for (int i = 0; i < ret.len - 1; ++ i){
ret.a[i] += (*this)[i] - p[i];
if (ret.a[i] < 0) ret.a[i] += base, -- ret.a[i + 1];
}
ret.normal();
return ret;
}
Big operator * (const Big &p)const{ // 注意长度太长可能会爆 __int128,视情况需要将 18 位调小
if (type){
int begin = clock();
std::vector <__int128> vec(maxbit);
for (int i = 0; i < maxbit; ++ i){
for (int j = 0; i + j < maxbit; ++ j){
vec[i + j] += (__int128) (*this)[i] * p[j];
}
}
Big ret(maxbit, -1);
for (int i = 0; i < maxbit; ++ i){
ret.a[i] = vec[i] % base;
if (i < maxbit - 1) vec[i + 1] += vec[i] / base;
}
tot += clock() - begin;
return ret;
}
std::vector <i128> vec(len + p.len);
for (int i = 0; i < len; ++ i){
for (int j = 0; j < p.len; ++ j){
vec[i + j] += (i128) a[i] * p.a[j];
}
}
Big ret(len + p.len, -1);
for (int i = 0; i < ret.len; ++ i){
ret.a[i] = vec[i] % base;
vec[i + 1] += vec[i] / base;
}
ret.normal();
return ret;
}
Big operator * (ll p)const{
if (!len || !p) return Big();
i128 remain = 0;
Big ret;
for (int i = 0; i < len || remain; ++ i){
remain += (i128) (*this)[i] * p;
ret.a.push_back(remain % base);
remain /= base;
}
ret.len = ret.a.size();
return ret;
}
static ll divide(Big &b, const ll &p){
assert(p);
i128 remain = 0;
for (int i = b.len - 1; ~i; -- i){
remain = remain * base + b.a[i];
b.a[i] = remain / p;
remain %= p;
}
b.normal();
return remain;
}
Big operator / (const ll &p)const{
Big ret = *this;
divide(ret, p);
return ret;
}
ll operator % (const ll &p)const{
Big ret = *this;
return divide(ret, p);
}
static Big divide(Big &b, const Big &p){
assert(p.len);
if (b.len < p.len) return Big();
b.a.resize(b.len + 1);
Big ret(b.len - p.len + 1, -1);
for (int i = b.len - p.len; i >= 0; -- i){
i128 num = 0, den = 0;
for (int j = 0; j <= 2; ++ j){
num = num * base + b[i + p.len - j];
}
for (int j = 1; j <= 2; ++ j){
den = den * base + p[p.len - j];
}
ll x = num / den;
if (!x) continue;
i128 remain = 0;
for (int j = 0; j < p.len; ++ j){
remain = remain + b.a[i + j] - (i128) p.a[j] * x;
b.a[i + j] = remain % base;
remain /= base;
if (b.a[i + j] < 0) b.a[i + j] += base, -- remain;
}
b.a[i + p.len] += remain;
if (b.a[i + p.len] < 0){
-- x;
for (int j = 0; j < p.len; ++ j){
b.a[i + j] += p.a[j];
if (b.a[i + j] >= base) b.a[i + j] -= base, ++ b.a[i + j + 1];
}
}
ret.a[i] = x;
}
b.normal();
ret.normal();
return ret;
}
Big operator / (const Big &p)const{
Big ret = *this;
return divide(ret, p);
}
Big operator % (const Big &p)const{
Big ret = *this;
divide(ret, p);
return ret;
}
ll toint(){
ll ret = 0;
for (int i = len - 1; i >= 0; -- i){
ret = ret * base + a[i];
}
return ret;
}
};
ll Big::base = 10;
int Big::type = 1;
int Big::maxbit = 4;
const int N = 1010;
typedef std::pair <Big, Big> pbb;
typedef std::pair <Big, int> pbi;
Big s[N][N];
Big inv[N];
int invcnt[N];
Big power[N];
Big poly[N];
Big inter[N];
Big powermod(Big a, Big exp){
Big ret(1);
for ( ; exp.len; exp = exp / 2){
int tot = 0;
if (Big::base & 1){
for (int i = 0; i < exp.len; ++ i){
tot += exp[i] & 1;
}
}
else{
tot = 1;
}
if (tot & 1){
ret = ret * a;
}
a = a * a;
}
return ret;
}
Big getinv(Big x, int p, int e){
return powermod(x, power[e - 1] * (p - 1) - Big(1));
}
void initpower(int p, int e){
Big::type = 0;
power[0] = Big(1);
for (int i = 1; i < e; ++ i){
power[i] = power[i - 1] * p;
}
Big::type = 1;
}
void inits(int p, int e){
s[0][0] = Big(1);
for (int i = 1; i <= p; ++ i){
for (int j = 1, sz = std::min(p, e); j <= sz; ++ j){
s[i][j] = j > i ? Big() : s[i - 1][j] * (i - 1) + s[i - 1][j - 1];
}
}
}
void initinv(int p, int e){
inv[0] = Big(1);
for (int i = 1, sz = std::max(2 * e - 2, p - 1); i <= sz; ++ i){
int x = i;
invcnt[i] = 0;
while (x % p == 0){
++ invcnt[i];
x /= p;
}
invcnt[i] += invcnt[i - 1];
inv[i] = inv[i - 1] * getinv(Big(x), p, e);
}
}
Big calcinter(Big u, int v, int p, int e){
Big ans(0), now(1);
Big mult = u * p;
for (int i = 0, sz = std::min(v, e - 1); i <= sz; ++ i){
ans = ans + now * s[v + 1][i + 1];
now = now * mult;
}
return ans;
}
void initpoly(int p, int e){
poly[0] = Big(1);
for (int i = 1; i <= 2 * e - 2; ++ i){
poly[i] = poly[i - 1] * calcinter(Big(i - 1), p - 1, p, e) * inv[p - 1];
}
for (int i = 0; i <= 2 * e - 2; ++ i){
inter[i] = poly[i] * inv[i] * inv[2 * e - 2 - i];
}
}
Big tobase(Big a, ll base){
Big ret;
while (a.len){
ret.a.push_back(a % base);
a = a / base;
}
ret.len = ret.a.size();
return ret;
}
pbb solve(Big n, int p, int e){
int max = e + invcnt[2 * e - 2];
Big ans(1), cnt;
while (n.len){
Big u = n / p;
int v = n % p;
n = u;
Big::type = 0;
cnt = cnt + u;
Big::type = 1;
ans = ans * calcinter(u, v, p, e);
int sz = 2 * e - 2;
if (!(Big(sz) < u)){
ans = ans * poly[u.toint()];
continue;
}
std::vector <pbi> pre(sz + 1), suf(sz + 1);
pre[0] = suf[sz] = {Big(1), 0};
for (int i = 1; i <= sz; ++ i){
Big::type = 0;
Big x = u - Big(i - 1);
Big::type = 1;
while (x % p == 0 && pre[i].second < max){
++ pre[i].second;
x = x / p;
}
pre[i].second += pre[i - 1].second;
pre[i].first = pre[i - 1].first * x;
}
for (int i = sz - 1; i >= 0; -- i){
Big::type = 0;
Big x = u - Big(i + 1);
Big::type = 1;
while (x % p == 0 && suf[i].second < max){
++ suf[i].second;
x = x / p;
}
suf[i].second += suf[i + 1].second;
suf[i].first = suf[i + 1].first * x;
}
Big sum(0);
for (int i = 0; i <= sz; ++ i){
int cnt = pre[i].second + suf[i].second - invcnt[i] - invcnt[sz - i];
if (cnt >= e) continue;
Big tmp = power[cnt] * pre[i].first * suf[i].first * inter[i];
//<==>(2 * e - 2 - i & 1 ? -1ll : 1ll)
sum = i & 1 ? sum - tmp : sum + tmp;
}
ans = ans * sum;
}
ans = ans * powermod(s[p][1], cnt);
return {ans, cnt};
}
Big combmoder(Big n, Big m, int p){
ll base = p == 2 ? base1 : base2;
Big::base = 10;
n = tobase(n, base);
m = tobase(m, base);
Big::base = base;
Big::maxbit = p == 2 ? 2 : 4;
Big::type = 0;
Big x = n - m;
Big::type = 1;
initpower(p, 100);
inits(p, 100);
initinv(p, 100);
initpoly(p, 100);
pbb p1 = solve(n, p, 100);
pbb p2 = solve(m, p, 100);
pbb p3 = solve(x, p, 100);
Big::type = 0;
Big cnt = p1.second - p2.second - p3.second;
Big::type = 1;
if (!(cnt < Big(100))){
return Big();
}
return p1.first * getinv(p2.first, p, 100) * getinv(p3.first, p, 100) * power[cnt.toint()];
}
char str[N];
int main(){
scanf("%s", str);
Big n(str, strlen(str));
scanf("%s", str);
Big m(str, strlen(str));
Big ans1 = combmoder(n, m, 2);
Big x1(1);
for (int i = 0; i < 100; ++ i){
x1 = x1 * 5;
}
Big x2 = getinv(x1, 2, 100);
ans1 = tobase(ans1, 10);
x1 = tobase(x1, 10);
x2 = tobase(x2, 10);
Big ans2 = combmoder(n, m, 5);
Big x3(1);
for (int i = 0; i < 100; ++ i){
x3 = x3 * 2;
}
Big x4 = getinv(x3, 5, 100);
ans2 = tobase(ans2, 10);
x3 = tobase(x3, 10);
x4 = tobase(x4, 10);
Big::type = 0;
Big::base = 10;
Big ans = ans1 * x1 * x2 + ans2 * x3 * x4;
int k;
scanf("%d", &k);
ans.resize(k);
if (!ans.len){
puts("0");
return 0;
}
for (int i = ans.len - 1; i >= 0; -- i){
putchar('0' + ans[i]);
}
puts("");
return 0;
}
| true |
d46027d39961450b6be59b861c658fdbf4b856e1 | C++ | openbmc/phosphor-ipmi-blobs | /test/ipmi_close_unittest.cpp | UTF-8 | 1,318 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #include "ipmi.hpp"
#include "manager_mock.hpp"
#include <cstring>
#include <string>
#include <gtest/gtest.h>
namespace blobs
{
using ::testing::Return;
TEST(BlobCloseTest, ManagerRejectsCloseReturnsFailure)
{
// The session manager returned failure to close, which we need to pass on.
ManagerMock mgr;
uint16_t sessionId = 0x54;
size_t dataLen;
std::vector<uint8_t> request;
struct BmcBlobCloseTx req;
req.crc = 0;
req.sessionId = sessionId;
dataLen = sizeof(req);
request.resize(dataLen);
std::memcpy(request.data(), &req, dataLen);
EXPECT_CALL(mgr, close(sessionId)).WillOnce(Return(false));
EXPECT_EQ(ipmi::responseUnspecifiedError(), closeBlob(&mgr, request));
}
TEST(BlobCloseTest, BlobClosedReturnsSuccess)
{
// Verify that if all goes right, success is returned.
ManagerMock mgr;
uint16_t sessionId = 0x54;
size_t dataLen;
std::vector<uint8_t> request;
struct BmcBlobCloseTx req;
req.crc = 0;
req.sessionId = sessionId;
dataLen = sizeof(req);
request.resize(dataLen);
std::memcpy(request.data(), &req, dataLen);
EXPECT_CALL(mgr, close(sessionId)).WillOnce(Return(true));
EXPECT_EQ(ipmi::responseSuccess(std::vector<uint8_t>{}),
closeBlob(&mgr, request));
}
} // namespace blobs
| true |
950e39136521222d30808d76ee8729b1f913e3ee | C++ | iwoplaza/Desidia-Engine | /Desidia Engine/src/engine/gameobject/component/ComponentMesh.cpp | UTF-8 | 1,407 | 2.59375 | 3 | [] | no_license | #include "ComponentMesh.hpp"
#include "../../rendering/shader/ShaderManager.hpp"
#include "../../rendering/geometry/Mesh.hpp"
#include "../../Resources.hpp"
#include "../../rendering/material/Material.hpp"
#include <iostream>
ComponentMesh::ComponentMesh(std::string _model, std::string _material, unsigned int _polygonMode) : Component() {
model = _model;
material = _material;
polygonMode = _polygonMode;
}
void ComponentMesh::draw() {
if (polygonMode == 1) {
glDisable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
Resources::MATERIAL[material]->use();
Resources::MODEL[model]->draw();
if (polygonMode == 1) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_CULL_FACE);
}
}
const char* ComponentMesh::getType() {
return "ComponentMesh";
}
Component* ComponentMesh::parseJSON(const Value& value) {
if (!value.HasMember("model") || !value.HasMember("material")) {
cerr << "[SceneLoader] Necessary parameters weren't specified for a ComponentMesh." << endl;
return nullptr;
}
std::string model = value["model"].GetString();
std::string material = value["material"].GetString();
unsigned int polygonMode = 0;
if(value.HasMember("polygonMode"))
polygonMode = value["polygonMode"].GetInt();
Resources::loadModel(model);
Resources::loadMaterial(material);
Component* component = new ComponentMesh(model, material, polygonMode);
return component;
} | true |
6f5c36c3c75c1463127705356969ddc7f61658bb | C++ | minotru/Bizarre | /character_interface.cpp | UTF-8 | 4,011 | 3.25 | 3 | [] | no_license | #include "stdinclude.h"
#include "character.h"
#include "items.h"
void createCharacter( Character& pers )
{
int k;
cout << "Hi \nPress 1. to start a new game \nPress 2. to load saved parametres\n";
cin >> k;
while ( k<1 || k>2 )
{
cout << "Incorrect enter, try again" << endl;
cin >> k;
}
if ( k == 1 )
{
cout << "Enter your character's name" << endl;
cin.ignore();
cin.getline( pers.name , 20 );
pers.pointsOfSkills = 20;
selectRace( pers );
cout << "Now you need to upgrade characteristics\n";
upgradeCharacteristicsWithPoints( pers );
}
else if ( k == 2 )
{
bool wellRead = false;
char nameOfFile[20];
int time = 0;
do
{
cout << "Enter your character's name\n";
if (time == 0)
cin.ignore();
cin.getline( nameOfFile , 20 );
//cout << nameOfFile << '#' << endl;
strcat(nameOfFile, ".txt");
ifstream in( nameOfFile );
if (in.is_open()) //file exists
{
in >> pers.name >> pers.race >> pers.stren >> pers.agil
>> pers.intel >> pers.pointsOfSkills;
wellRead = true;
}
else
cout << "Error, no such saved name. Try again.\n";
time++;
} while (!wellRead);
cout << "Loaded.\n";
}
}
void selectRace( Character& pers )
{
cout << "Select your race\n"
"1.Human (+Intelligence)\n2.Orc (+Strength)\n3.Elf (+Agility)\n";
int l;
cin >> l;
while ( l<1 || l>3 )
{
cout << "Incorrect enter, try again" << endl;
cin >> l;
}
if ( l == 1 )
{
strcpy( pers.race , "Human" );
pers.intel += 10;
}
if ( l == 2 )
{
strcpy( pers.race , "Orc" );
pers.stren += 10;
}
if ( l == 3 )
{
strcpy( pers.race , "Elf" );
pers.agil += 10;
}
}
void upgradeCharacteristicsWithPoints( Character& pers )
{
int k=1;
while (pers.pointsOfSkills>0 && k!=0)
{
cout << "You have " << pers.pointsOfSkills << " points of skills.\n";
cout << "What characteristic do you want to up?\n"
"1.Strength \n2.Agility \n3.Intelligence\n0.Exit\n";
cin >> k;
if ( k >= 1 && k <= 3 )
{
int p;
cout << "How many points?\n";
cin >> p;
if ( p > pers.pointsOfSkills )
cout << "Not enough points!\n";
else
{
switch (k)
{
case 1:
pers.stren += p;
break;
case 2:
pers.agil += p;
break;
case 3:
pers.intel += p;
break;
default:
break;
}
pers.pointsOfSkills -= p;
cout << "Done.\n";
// << pers.pointsOfSkills << " points left\n";
}
}
else
switch (k)
{
case 0:
cout << "Returning back to the menu\n";
break;
default:
cout << "Wrong, try again\n";
break;
}
}
if (!pers.pointsOfSkills)
{
cout << "You have no points, returning back to the menu\n";
}
}
void saveCharacterInfo(const Character& pers )
{
char fileName[80];
strcpy(fileName, pers.name);
strcat(fileName, ".txt");
ofstream out(fileName);
out << pers.name << ' ' << pers.race << ' ' << pers.stren << ' '
<< pers.agil << ' ' << pers.intel << ' ' << pers.pointsOfSkills;
out.close();
}
| true |
9782b6bcd6e09d2e3f23d8ffcbfe84cbb75fecbd | C++ | housemeow/POSD | /103598010/103598010_Test/ellipse_decorator_test.cpp | UTF-8 | 1,428 | 3.03125 | 3 | [] | no_license | #include "stdafx.h"
#include <limits.h>
#include "gtest/gtest.h"
#include "ellipse_decorator.h"
#include "node.h"
class MockGraphics : public IGraphics
{
public:
void drawText(string text, int x, int y, int width, int height)
{
throw string("drawText");
}
void drawRectangle(int x1, int y1, int x2, int y2)
{
throw string("drawRectangle");
}
void drawEllipse(int x1, int y1, int x2, int y2)
{
throw string("drawEllipse");
}
void drawTriangle(int x1, int y1, int x2, int y2)
{
throw string("drawTriangle");
}
};
class EllipseDecoratorTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
}
virtual void TearDown()
{
}
};
TEST_F(EllipseDecoratorTest, testEllipseDecoratorTest)
{
Node node(1);
EllipseDecorator ellipseDecorator(&node);
ellipseDecorator.setX(0);
ASSERT_EQ(ellipseDecorator.getX(), 0);
ellipseDecorator.setY(0);
ASSERT_EQ(ellipseDecorator.getY(), 0);
ASSERT_EQ(ellipseDecorator.getWidth(), node.getWidth() + ComponentDecorator::PADDING * 2);
ASSERT_EQ(ellipseDecorator.getHeight(), node.getHeight() + ComponentDecorator::PADDING * 2);
MockGraphics mockGraphics;
try {
ellipseDecorator.draw(&mockGraphics);
FAIL();
} catch (string str) {
SUCCEED();
}
ASSERT_EQ(ellipseDecorator.getTypeName(), EllipseDecorator::NAME);
} | true |
5932ae0bcff12328aff818d5455c9feeeb427de8 | C++ | dibakma/revreaddy | /src/MeanSquaredDisplacement.cpp | UTF-8 | 4,930 | 2.8125 | 3 | [] | no_license | /* MeanSquaredDisplacement.cpp */
#include "MeanSquaredDisplacement.h"
MeanSquaredDisplacement::MeanSquaredDisplacement(
std::vector<Particle>& activeParticles,
unsigned int pTypeId,
double time,
double boxsize,
std::string inFilename)
{
this->recPeriod = 1;
this->clearPeriod = 0;
this->filename = inFilename;
this->particleTypeId = pTypeId;
this->startTime = time;
this->boxsize = boxsize;
/* add uniqueIds of all particles of type
* "particleTypeId" to observedParticleIds */
for (unsigned int i=0; i<activeParticles.size(); i++) {
if (activeParticles[i].typeId == this->particleTypeId) {
this->observedParticleIds.push_back( activeParticles[i].uniqueId );
positionTuple pt;
pt.position = activeParticles[i].position;
pt.boxCoordinates = activeParticles[i].boxCoordinates;
this->startPoints.push_back(pt);
}
}
}
MeanSquaredDisplacement::~MeanSquaredDisplacement()
{
}
void MeanSquaredDisplacement::record(
std::vector<Particle>& activeParticles,
double t)
{
std::vector<double> displacement = {0.,0.,0.};
std::vector<long> relativeBoxCoordinates = {0,0,0};
std::vector<double> squaredDisplacements;
double squaredDisplacement = 0.;
double mean = 0.;
int index = 0;
unsigned int stillExisting = 0;
for (int i=0; i < this->observedParticleIds.size(); i++) {
// check if particle still exists. if not: index = -1
index = this->findParticleIndex(
activeParticles,
observedParticleIds[i]);
if (index != -1) {
stillExisting += 1;
relativeBoxCoordinates[0] =activeParticles[index].boxCoordinates[0]
- startPoints[i].boxCoordinates[0];
relativeBoxCoordinates[1] =activeParticles[index].boxCoordinates[1]
- startPoints[i].boxCoordinates[1];
relativeBoxCoordinates[2] =activeParticles[index].boxCoordinates[2]
- startPoints[i].boxCoordinates[2];
displacement[0] = (double) relativeBoxCoordinates[0]
* this->boxsize
+ activeParticles[index].position[0]
- startPoints[i].position[0];
displacement[1] = (double) relativeBoxCoordinates[1]
* this->boxsize
+ activeParticles[index].position[1]
- startPoints[i].position[1];
displacement[2] = (double) relativeBoxCoordinates[2]
* this->boxsize
+ activeParticles[index].position[2]
- startPoints[i].position[2];
squaredDisplacement = displacement[0]*displacement[0]
+ displacement[1]*displacement[1]
+ displacement[2]*displacement[2];
squaredDisplacements.push_back(squaredDisplacement);
mean += squaredDisplacement;
}
}
// if no more particles still exist, stop here. nothing is recorded
if (stillExisting == 0) {return;}
this->numberOfParticles.push_back(stillExisting);
mean /= (double) stillExisting;
this->meanSquaredDisplacements.push_back(mean);
double standardDeviation = 0.;
for (int j=0; j<squaredDisplacements.size(); j++) {
standardDeviation += (squaredDisplacements[j] - mean)
* (squaredDisplacements[j] - mean);
}
standardDeviation /= (double) (stillExisting - 1);
double standardError = standardDeviation
/ (double) stillExisting;
standardDeviation = sqrt(standardDeviation);
standardError = sqrt(standardError);
this->standardDeviations.push_back(standardDeviation);
this->standardErrors.push_back(standardError);
this->time.push_back(t - this->startTime);
}
void MeanSquaredDisplacement::writeBufferToFile()
{
// first determine the file extension
unsigned int lastDot = this->filename.find_last_of(".");
std::string extension = this->filename.substr(lastDot);
if ( (extension == ".h5") || (extension == ".hdf5") ) {
this->writeBufferToH5();
}
else if ( (extension == ".dat") || (extension == ".txt") ) {
this->writeBufferToDat();
}
else {
this->writeBufferToDat();
}
}
void MeanSquaredDisplacement::writeBufferToH5()
{
BinaryFile file(this->filename);
file.addDatasetDouble(
"time",
this->time);
file.addDatasetDouble(
"meanSquaredDisplacement",
this->meanSquaredDisplacements);
file.addDatasetDouble(
"standardDeviation",
this->standardDeviations);
file.addDatasetDouble(
"standardError",
this->standardErrors);
file.addDatasetUnsignedInt(
"numberOfParticles",
this->numberOfParticles);
}
void MeanSquaredDisplacement::writeBufferToDat()
{
std::ofstream file;
file.open(this->filename);
file << "Time\tMeanSquaredDisplacement\tStandardDeviation\t"
"StandardError\tNumberOfParticles\n";
for (int i=0; i<meanSquaredDisplacements.size(); i++) {
file << time[i] << "\t";
file << meanSquaredDisplacements[i] << "\t";
file << standardDeviations[i] << "\t";
file << standardErrors[i] << "\t";
file << numberOfParticles[i] << "\n";
}
file.close();
}
| true |
2ac1e8812d6d450451e79820a10f39fd51edb7bb | C++ | dududududd/Computer-Graphics | /完全镜面反射【区域光】渲染/Ray casting/World.h | GB18030 | 3,321 | 2.546875 | 3 | [] | no_license | #pragma once
#include<vector>//vector
#include"ViewPlane.h"
#include"Sphere.h"
#include"Plane.h"
#include"GeometricObject.h"
#include"Whitted.h"
#include"Maths.h"
class Light;
#include"Camera.h"
class PinHole;
#include"Instance.h"
//#include"Grid.h"
//#include"CBezierPatch.h"
#include"CTeapot.h"
#include"Box.h"
#include"SolidCylinder.h"
#include"CRectangle.h"
#include"Torus.h"
#include"Directional.h"
#include"PointLight.h"
#include"AmbientOccluder.h"
#include"AreaLighting.h"
#include"EnvironmentLight.h"
#include"Emissive.h"
#include"AreaLight.h"
#include"PointLight.h"
#include"Matte.h"
#include"Phong.h"
#include"Reflective.h"
class World
{
public:
World(void);//ĬϹ캯
~World(void);//
World(const World& _world);//캯
World& operator=(const World& _world);//ֵ
void build(void);//ز
void add_object(GeometricObject* object_ptr);//Ⱦ
void add_light(Light* light_ptr);
RGBColor max_to_one(const RGBColor& c)const;//ɫ1
RGBColor clamp_to_color(const RGBColor& raw_color)const;//ɫ2
ShadeRec hit_objects(const Ray& ray);//ȡײ
//void render_scene(void)const;//ƽͶȾ
//void render_perspective(void)const;//ڼһߴԽλʱͼ
void open_window(const int hres, const int vres)const;//Ⱦ
void display_pixel(const int row, const int column,RGBColor& raw_color)const;//
public:
ViewPlane vp;//ƽ
RGBColor background_color;//ɫ
Tracer* tracer_ptr;//ָ
std::vector<GeometricObject*>objects;//
CDC* pDC;//MFCͼָ
static const double kHugeValue;//Ϊֵ
//double eye;//Ӽ
//double d;//ƽ
Camera* camera_ptr;//ָ
Light* ambient_ptr;
std::vector<Light*>lights;
};
/*
˵
1.open_window(hres,vres)ǿһȾڣڱõMFC⣬ûʹõú
2.ĹͶȾ̣Ҫ˵ã
ShadeRec洢ֵġ
ڼζ洢ĻϢ-ཻԺġ
۸㾭ഫݹĶIJʹյġ
Worldǵ࣬佫ʵһĸ൱main()
3.δصļζͣڼζ̳вνṹеͣʵ˻hit()Ĺӿڡ
4.ͶӰrender_perspective()ʵ֣е滻ԭrender_scene()
5.ambient_ptrָLightָAmbientָ룬ӦAmbient͵ĸֵ
6.WorldĬϹ캯УAmbientָ뽫ʼΪָijһAmbientǿָ롣ҪԸʶka
AmbientӦڶСսΪҪlsʱıĬɫʱbuild()Ambientա
*/ | true |
658ce73cf3501f41e62ae77f534785edd9f62a98 | C++ | yqekzb123/homework-wkdb | /system/abort_txn_queue.h | UTF-8 | 833 | 2.59375 | 3 | [] | no_license |
#ifndef _ABORTTXN_QUEUE_H_
#define _ABORTTXN_QUEUE_H_
#include "global.h"
#include "universal.h"
struct abort_txn_entry {
uint64_t penalty_end;
uint64_t txn_id;
abort_txn_entry() {
}
abort_txn_entry(uint64_t penalty_end, uint64_t txn_id) {
this->penalty_end = penalty_end;
this->txn_id = txn_id;
}
};
struct CompareAbortTxnEntry {
bool operator()(const abort_txn_entry* lhs, const abort_txn_entry* rhs) {
return lhs->penalty_end > rhs->penalty_end;
//return lhs->penalty_end < rhs->penalty_end;
}
};
class AbortTxnQueue {
public:
void init();
uint64_t enqueue(uint64_t thd_id, uint64_t txn_id, uint64_t abort_cnt);
void process(uint64_t thd_id);
private:
std::priority_queue<abort_txn_entry*,std::vector<abort_txn_entry*>,CompareAbortTxnEntry> queue;
pthread_mutex_t mtx;
};
#endif
| true |
f0da57ef18f2e944c7a9945da6cd09c14da019e3 | C++ | rkgilbert10/CSCI-21-FALL-2015 | /Project3/DLNode.h | UTF-8 | 1,642 | 3.359375 | 3 | [] | no_license | /* Header file for DLNode
* Created by Rachel Gilbert
* Created:10/30/15
* Modified: 10/31/15
* Notes:
*/
#pragma once
#include <iostream>
#include <sstream>
using namespace std;
class DLNode {
private:
int contents;
DLNode* nextNode;
DLNode* previousNode;
public:
/* Default constructor.
* Sets contents to 0, next and previous nodes to NULL.
*/
DLNode();
/* Overloaded constructor.
* Sets newContents to contents.
* Sets next and previous nodes to NULL.
* @param newContents
*/
DLNode(int newContents);
/* Destructor.
* Does nothing.
*/
virtual ~DLNode();
/* setContents
* @param newContents sets to contents.
*/
void setContents(int newContents);
/* Gets contents
* @returns contents
*/
int getContents() const;
/* Sets next node
* @param newNext - sets nextNode to newNext
*/
void setNext(DLNode* newNext);
/* Gets next node
* @return the next node.
*/
DLNode* getNext() const;
/* Sets previous node.
* @param newPrevious - sets previous node to newPrevious
*/
void setPrevious(DLNode* newPrevious);
/* Get previous node.
* @return previousNode.
*/
DLNode* getPrevious() const;
}; | true |
c7315435e6600161a8588740f4f66df8815e1b5a | C++ | bamelegari/cs372_chainOfResponsibility | /assemblers.cpp | UTF-8 | 920 | 2.578125 | 3 | [] | no_license | //assemblers.cpp
#include "assemblers.h"
#include <iostream>
using std::cout;
using std::endl;
void partAAssembler::assemble(char part)
{
if (part == 'A')
cout << "Assembling part A" << endl;
else
{
cout << "Assembler A skipping" << endl;
assemblyInterface::assemble(part);
}
}
void partBAssembler::assemble(char part)
{
if (part == 'B')
cout << "Assembling part B" << endl;
else
{
cout << "Assembler B skipping" << endl;
assemblyInterface::assemble(part);
}
}
void partCAssembler::assemble(char part)
{
if (part == 'C')
cout << "Assembling part C" << endl;
else
{
cout << "Assembler C skipping" << endl;
assemblyInterface::assemble(part);
}
}
void partDAssembler::assemble(char part)
{
if (part == 'D')
cout << "Assembling part D" << endl;
else
{
cout << "Assembler D skipping" << endl;
assemblyInterface::assemble(part);
}
} | true |
40ecd815da4693df7975699e62d10a70a79adaf7 | C++ | zyxrrr/LeetCode | /300-Longest Increasing Subsequence/Solution.cpp | UTF-8 | 696 | 2.6875 | 3 | [] | no_license | class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.empty()){return 0;}
int maxans = 1, maxtmp = 0;
vector<int> ans(nums.size(), 1);
for (int i = 1; i < nums.size(); i++){
maxtmp = 0;
for (int j = 0; j < i; j++){
if (nums[j] < nums[i]){
maxtmp = max(maxtmp , ans[j]);
}
}
//cout << "a[i]: " << ans[i] << "maxtmp : " << maxtmp <<endl;
ans[i] += maxtmp;
//cout << ans[i] <<endl;
if (ans[i] > maxans){
maxans = ans[i];
}
}
return maxans;
}
};
| true |
3c9ca135cef60b4ae56c4de88cb969cc053b6607 | C++ | HaoyaWHL/LeetCode | /LeetCode_List/86. Partition List.cpp | UTF-8 | 868 | 3.609375 | 4 | [] | no_license | // 86. Partition List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (head==NULL) { return NULL; }
ListNode *s=new ListNode(0);
ListNode *h=new ListNode(0);
ListNode *small=s,*high=h; //容易出错的地方,small前面写了*,但是high忘了,下次记住。。。。
ListNode *cur=head;
while(cur!=NULL)
{
if( (cur->val) < x)
{
s->next = cur;
s=s->next;
}
else
{
h->next = cur;
h=h->next;
}
cur=cur->next;
}
h->next=NULL;
s->next=high->next;
return small->next;
}
}; | true |
65c8d1e436c760a8124bb53b26b0cc80060011f6 | C++ | ahamache/projet_lo21 | /xml_dom.cpp | UTF-8 | 12,667 | 2.828125 | 3 | [] | no_license | #include "xml_dom.h"
#include <iostream>
using namespace std;
Xml_Dom::Xml_Dom(const QString& param) : QWidget(){
QDomDocument *dom = new QDomDocument("list_Automate"); /*! On créé un objet dom de type QDomDocument*/
QFile xml_doc("save_autocell.xml"); /*! On ouvre le fichier XML qui contient les automates avec QFile*/
if(!xml_doc.open(QIODevice::ReadWrite)) /*! On teste si on arrive à ouvrir le fichier XML */
{
QMessageBox::warning(this,"Erreur à l'ouverture du document XML","Le document XML n'a pas pu être ouvert. Vérifiez que le nom est le bon et que le document est bien placé");
return;
}
if(xml_doc.size()==0){ /*! Si le fichier XML est vide, on insert l'en-tête du fichier XML et une balise racine Document puis on ferme le document*/
xml_doc.write("<?xml version='1.0' encoding='UTF-8'?>\n<Document>\n</Document>");
xml_doc.close();
xml_doc.open(QIODevice::ReadOnly);
}
if (!dom->setContent(&xml_doc)) /*! On associe le fichier XML à l'objet DOM, si ça ne fonctionne pas alors fermeture du document XML avec message d'erreur*/
{
xml_doc.close();
QMessageBox::warning(this,"Erreur à l'ouverture du document XML","Le document XML n'a pas pu être attribué à l'objet QDomDocument.");
return;
}
xml_doc.close(); /*! On ferme le fichier xml après sa lecture */
QDomElement dom_element=dom->documentElement(); /*! On affecte à dom_element la valeur du document XML entier*/
QDomNode noeud = dom_element.firstChildElement(); /*! On affecte à noeud la valeur du premier noeud du fichier, <Automate1D> par exemple */
/*! Dans le fichier on stocke les trois types d'automates */
while(!noeud.isNull()){ /*! on rentre dans une boucle while pour parcourir tous les automates */
QDomElement element = noeud.toElement(); /*! On transforme le noeud en élément */
if(element.tagName()== param){
if(element.tagName() == "Automate1D"){
QDomNode n2 = noeud.firstChildElement(); /*! On regarde à l'intérieur de Automate1D */
QDomElement elem2 = n2.toElement();
if(elem2.tagName() == "Numero"){ /*! On vérifie que les balises sont correctes */
num=elem2.text().toInt(); /*! On récupère le numéro de la règle écrite à l'intérieur avec .toInt()*/
AutomateManager::getInstance().getAutomate1D(num); //besoin que d'un des deux paramètres
}
else if(elem2.tagName() == "NumeroBit"){
numBit=elem2.text().toStdString();
AutomateManager::getInstance().getAutomate1D(numBit); //besoin que d'un des deux paramètres
}
/*! Inutile de chercher la deuxième balise NumeroBit car on a besoin que d'un des deux attributs pour le constructeur*/
else QMessageBox::warning(this,"Erreur de lecture du document XML","Le document XML présente une balise incorrecte.");
}
else if(element.tagName() == "Automate2D"){ /*! On effectue des opérations similaires pour Automate2D et AutomateEpidemie*/
QDomNode n2 = noeud.firstChildElement();
QDomElement elem2 = n2.toElement();
int t=1;
while(!n2.isNull() && t==1){
if(elem2.tagName() == "Minimumvivant")
miniV=elem2.text().toInt();
else if(elem2.tagName() == "Maximumvivant")
maxiV=elem2.text().toInt();
else if(elem2.tagName() == "Minimummort")
miniM=elem2.text().toInt();
else if(elem2.tagName() == "Maximummort")
maxiM=elem2.text().toInt();
else t=0; //vérification de la validité des balises
n2=n2.nextSibling();
elem2 = n2.toElement();
}
if(t==1)
AutomateManager::getInstance().getAutomate2D(miniV, maxiV, miniM, maxiM);
}
else if(element.tagName() == "AutomateEpidemie"){
QDomNode n2 = noeud.firstChildElement();
QDomElement elem2 = n2.toElement();
int t=1;
while(!n2.isNull() && t==1){
if(elem2.tagName() == "Chance1")
c1=elem2.text().toInt();
else if(elem2.tagName() == "Chance2")
c2=elem2.text().toInt();
else t=0;
n2=n2.nextSibling();
elem2 = n2.toElement();
}
if (t==1)
AutomateManager::getInstance().getAutomateEp(c1, c2);
}
}
noeud=noeud.nextSibling(); /*! On passe au noeud automate suivant avec nextSibling()*/
}
}
/*void Xml_Dom::ajouter_Automate(){
QDomDocument dom("list_Automate");
QFile doc_xml("save_autocell.xml"); //on charge le document existant
if(!doc_xml.open(QIODevice::ReadOnly)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;}
if(!dom.setContent(&doc_xml)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;
}
doc_xml.close();
QDomElement docElem = dom.documentElement(); //permet d'explorer le nouveau document DOM
afficher : "quel type d'automate voulez-vous ajouter ?"
for(std::vector<string>::iterator it = AutomateManager::getInstance().TypesAutomates.begin(); it != AutomateManager::getInstance().TypesAutomates.end(); ++it)
afficher *it
en fonction du choix de l'utiisateur, demander les paramètres et exécuter une des fonctions 1d, 2d ou ep avec ces paramètres
}*/
void Xml_Dom::ajouter_Automate1D(unsigned int n){ /*! On ajoute un nouvel automate dans le fichier XML en ajoutant son numéro de règle*/
QDomDocument dom("list_Automate");
QFile doc_xml("save_autocell.xml"); /*! On charge le document existant */
if(!doc_xml.open(QIODevice::ReadWrite)){ /*! On teste l'ouverture du fichier */
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;}
if(!dom.setContent(&doc_xml)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML 22222");
doc_xml.close();
return;
}
doc_xml.close();
QDomElement docElem = dom.documentElement(); /*! On créé un objet QDomElement qui contiendra l'ensemble des balises*/
QDomElement aut_elem = dom.createElement("Automate1D"); /*! On crée un QDomElement qui a comme nom de balise "Automate 1D"*/
QDomElement num_elem = dom.createElement("Numero"); /*! On créé un nouvel élément dont le nom de balise est Numero*/
QString nb = QString::number(n); /*! On utilise un objet de type QString auquel on affecte le numéro de règle rentré en paramètre*/
num_elem.appendChild(dom.createTextNode(nb)); /*! A l'intérieur de la balise on ajoute le texte n*/
QDomElement numB_elem = dom.createElement("NumeroBit"); /*! On créé aussi une balise NumeroBit*/
numB_elem.appendChild(dom.createTextNode(QString::fromStdString(NumToNumBit(n)))); /*! On rentre dans la balise NumeroBit la conversion en binaire du numéro de la règle*/
docElem.appendChild(aut_elem); /*! On ajoute le noeud racine du nouvel automate à l'objet global DOM */
aut_elem.appendChild(num_elem); /*! On attache au noeud racine ses deux noeuds fils */
aut_elem.appendChild(numB_elem);
QString write_doc = dom.toString(); /*! On transforme DOM en string */
QFile fichier("save_autocell.xml"); /*! On créer un QFile pour pouvoir écrire dedans */
if(!fichier.open(QIODevice::WriteOnly)){ /*! on ouvre le fichier*/
fichier.close();
QMessageBox::critical(this,"Erreur","Impossible d'écrire dans le document XML");
return;
}
QTextStream stream(&fichier);
stream << write_doc; /*! L'opérateur << permet d'écrire dans write_doc */
fichier.close();
}
void Xml_Dom::ajouter_Automate2D(unsigned int mnV, unsigned int mxV, unsigned int mnM, unsigned int mxM){ /*! On veut ajouter un nouvel automate dans le fichier à partir des règles rentrées en argument*/
if(mnV>mxV || mnM>mxM){
QMessageBox::critical(this,"Erreur","Nombre de voisinnage invalide");
return;
}
QDomDocument dom("list_Automate");
QFile doc_xml("save_autocell.xml"); /*! On charge le document existant*/
if(!doc_xml.open(QIODevice::ReadOnly)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;}
if(!dom.setContent(&doc_xml)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;
}
doc_xml.close();
QDomElement docElem = dom.documentElement(); /*! Comme pour la fonction Ajouter_1D, on créé un noeud global dans lequel on créé de nouveaux noeuds afin de construire l'arborescence du XML*/
QDomElement aut_elem = dom.createElement("Automate2D");
QDomElement mnV_elem = dom.createElement("Minimumvivant"); /*! On rentre dans chaque balise les données qui leur correspondent rentrées en argument*/
mnV_elem.appendChild(dom.createTextNode(QString::number(mnV)));
QDomElement mxV_elem = dom.createElement("Maximumvivant");
mxV_elem.appendChild(dom.createTextNode(QString::number(mxV)));
QDomElement mnM_elem = dom.createElement("Minimummort");
mnM_elem.appendChild(dom.createTextNode(QString::number(mnM)));
QDomElement mxM_elem = dom.createElement("Maximummort");
mxM_elem.appendChild(dom.createTextNode(QString::number(mxM)));
docElem.appendChild(aut_elem);
aut_elem.appendChild(mnV_elem); /*! On rattache les quatre noeuds fils au noeud racine*/
aut_elem.appendChild(mxV_elem);
aut_elem.appendChild(mnM_elem);
aut_elem.appendChild(mxM_elem);
QString write_doc = dom.toString(); /*! On transforme DOM en string */
QFile fichier("save_autocell.xml"); /*! On créer un QFile pour pouvoir écrire dedans*/
if(!fichier.open(QIODevice::WriteOnly)){ /*! On ouvre le fichier*/
fichier.close();
QMessageBox::critical(this,"Erreur","Impossible d'écrire dans le document XML");
return;
}
QTextStream stream(&fichier);
stream << write_doc; /*! L'opérateur << permet d'écrire dans write_doc */
fichier.close();
}
void Xml_Dom::ajouter_AutomateEp(unsigned int c1, unsigned int c2){ /*! On ajoute un nouvel automate en le construisant à partir des paramètres avec lesquels la fonction est appelée*/
QDomDocument dom("list_Automate");
QFile doc_xml("save_autocell.xml"); /*! On charge le document existant */
if(!doc_xml.open(QIODevice::ReadOnly)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;}
if(!dom.setContent(&doc_xml)){
QMessageBox::critical(this,"Erreur","Impossible d'ouvrir le ficher XML");
doc_xml.close();
return;
}
doc_xml.close();
QDomElement docElem = dom.documentElement();
QDomElement aut_elem = dom.createElement("AutomateEpidemie");
QDomElement c1_elem = dom.createElement("Chance1");
c1_elem.appendChild(dom.createTextNode(QString::number(c1)));
QDomElement c2_elem = dom.createElement("Chance2");
c2_elem.appendChild(dom.createTextNode(QString::number(c2)));
docElem.appendChild(aut_elem);
aut_elem.appendChild(c1_elem);
aut_elem.appendChild(c2_elem);
QString write_doc = dom.toString(); /*! on transforme DOM en string*/
QFile fichier("save_autocell.xml"); /*! on créer un QFile pour pouvoir écrire dedans*/
if(!fichier.open(QIODevice::WriteOnly)){ /*! on ouvre le fichier*/
fichier.close();
QMessageBox::critical(this,"Erreur","Impossible d'écrire dans le document XML");
return;
}
QTextStream stream(&fichier);
stream << write_doc; /*! L'opérateur << permet d'écrire dans write_doc */
fichier.close();
}
| true |
1ab0c632c53ecfeb4d471d1ff035f9119c3b15cb | C++ | kamyu104/LeetCode-Solutions | /C++/parse-lisp-expression.cpp | UTF-8 | 1,747 | 3.0625 | 3 | [
"MIT"
] | permissive | // Time: O(n^2)
// Space: O(n^2)
class Solution {
public:
int evaluate(string expression) {
vector<string> tokens{""};
unordered_map<string, string> lookup;
vector<pair<vector<string>, unordered_map<string, string>>> stk;
for (const auto& c : expression) {
if (c == '(') {
if (tokens[0] == "let") {
evaluate(tokens, &lookup);
}
stk.emplace_back(move(tokens), lookup);
tokens = {""};
} else if (c == ' ') {
tokens.emplace_back();
} else if (c == ')') {
const auto& val = evaluate(tokens, &lookup);
tie(tokens, lookup) = move(stk.back());
stk.pop_back();
tokens.back() += val;
} else {
tokens.back().push_back(c);
}
}
return stoi(tokens[0]);
}
private:
string evaluate(const vector<string>& tokens, unordered_map<string, string>* lookup) {
static const unordered_set<string> operators{"add", "mult"};
if (operators.count(tokens[0])) {
const auto& a = stoi(getval(*lookup, tokens[1]));
const auto& b = stoi(getval(*lookup, tokens[2]));
return to_string(tokens[0] == "add" ? a + b : a * b);
}
for (int i = 1; i < tokens.size() - 1; i += 2) {
if (!tokens[i + 1].empty()) {
(*lookup)[tokens[i]] = getval(*lookup, tokens[i + 1]);
}
}
return getval(*lookup, tokens.back());
}
string getval(const unordered_map<string, string>& lookup, const string& x) {
return lookup.count(x) ? lookup.at(x) : x;
}
};
| true |
48a904eafd0c5ce14ac920ca9911c947223bcdbc | C++ | cc-catch/cppcourse | /course02/homework01/joost/linkedlist.h | UTF-8 | 447 | 3.15625 | 3 | [] | no_license | #pragma once
#include <array>
#include <stdexcept>
#include <memory>
struct Node
{
int value;
Node* next;
};
class LinkedListInt
{
public:
LinkedListInt();
//LinkedList(IteratorInt);
int size() const; // time complexity = 1
void append(int value); // time complexity = o*n
int pop_front(); // time complexity = 1
void clear(); // time complexity = 1
private:
Node* mHead;
std::size_t mSize; // how many items are in the vector
};
| true |
8caa1709462111a492dfba886e41f18faca8817e | C++ | shootan/Terraria | /terraria/HelloWorld/win32/AttackManager.h | UTF-8 | 1,574 | 2.734375 | 3 | [] | no_license | #pragma once
#include "cocos2d.h"
using namespace cocos2d;
#include "ItemManager.h"
#include "Object_Hero.h"
class AttackManager
{
private:
AttackManager()
{
m_pHero = NULL;
instance = NULL;
}
~AttackManager()
{
m_pHero = NULL;
instance = NULL;
}
Object_Hero* m_pHero;
public:
static AttackManager* instance;
static AttackManager* sharedManager()
{
if( instance == NULL ) instance = new AttackManager;
return instance;
}
void SetHero(Object_Hero* _hero)
{
m_pHero = _hero;
}
void Attack(CGPoint _MousePos)
{
CGPoint pos = m_pHero->getPosition();
CGPoint m_Vector2D = ccp(_MousePos.x - pos.x, _MousePos.y- pos.y);
float fDistance = sqrtf(m_Vector2D.x*m_Vector2D.x + m_Vector2D.y*m_Vector2D.y);
m_Vector2D.x /= fDistance;
m_Vector2D.y /= fDistance;
pos.x += m_Vector2D.x * 2.f;
pos.y += m_Vector2D.y * 2.f;
float r = atan2(m_Vector2D.x, m_Vector2D.y);
r = r / 3.141592f * 180.f;
if(m_pHero->m_iState != JUMP && m_pHero->m_iState != DOWN)
{
if(ItemManager::sharedManager()->GetSelectItemIndex()== 0 )
m_pHero->m_iState = IDLE;
if(ItemManager::sharedManager()->GetSelectItemIndex()!= 0 &&
ItemManager::sharedManager()->GetSelectItemIndex()<3)
{
m_pHero->setWeapon(r);
m_pHero->m_iState = ITEM;
}
if(ItemManager::sharedManager()->GetSelectItemIndex() == 5)
{
m_pHero->setWeapon(r);
m_pHero->m_iState = BOWATTACK;
}
if(ItemManager::sharedManager()->GetSelectItemIndex() == 6)
{
m_pHero->setWeapon(r);
m_pHero->m_iState = ATTACK;
}
}
}
}; | true |
73096e61a25b2de3578ac50b4ccd12e917128551 | C++ | Computational-Physics-Research/Computational-Physics-1 | /CxxProgramming/MolecularDynamics/src/particlegod.cpp | UTF-8 | 4,630 | 3.03125 | 3 | [] | no_license | #include <vector>
#include <random>
#include <fstream>
#include <string>
#include <sstream>
#include "../include/particlegod.hpp"
#include "../include/particle.hpp"
#include "../include/settings.hpp"
void ParticleGod::generate_particles()
{
int idx = 1;
// Generate particles on a quasi random grid
// each particle has a unique id (idx)
for (int i=5; i<GRID_SIZE_X; i+=5)
{
for (int j=5; j<GRID_SIZE_Y;j+=5)
{
particles.push_back(Particle(idx, i, j));
idx += 1;
}
}
}
void ParticleGod::update(float time)
{
// Update particle stuff
for (auto &particle: particles)
{
// update positions
particle.x += particle.vx*time + particle.ax*time*time*0.5;
particle.y += particle.vy*time + particle.ay*time*time*0.5;
// update velocities
particle.vx += particle.ax*time;
particle.vy += particle.ay*time;
// check boundaries
particle.boundary_check();
}
}
void ParticleGod::new_accelerations()
{
for (auto &particle: particles)
{
// initialize accel to 0 and declare working variables
particle.ax = 0;
particle.ay = 0;
double rx = 0;
double ry = 0;
double r2 = 0;
double nx = 0;
double ny = 0;
double accel = 0;
for (auto &target: particles)
{
// Don't count force between particle and itself!
if (particle.id == target.id) continue;
// find x distance between nearest version of target particle
rx = particle.x - target.x;
if (rx > GRID_SIZE_X/2)
{
rx -= GRID_SIZE_X;
}
if (ry < -1*GRID_SIZE_X/2)
{
rx += GRID_SIZE_X;
}
// find y distance between nearest version of target particle
ry = particle.y - target.y;
if (ry > GRID_SIZE_Y/2)
{
ry -= GRID_SIZE_Y;
}
if (ry < -1*GRID_SIZE_Y/2)
{
ry += GRID_SIZE_Y;
}
// Distance between particle centers & normal vector along that axis
r2 = sqrtf(rx*rx + ry*ry);
r2 = (r2 < 0.9) ? 0.9 : r2;
nx = rx/r2;
ny = ry/r2;
// accelerations from potential & add to particle accels.
accel = (2*powf((1/r2),13) - powf((1/r2),7));
particle.ax += accel*nx;
particle.ay += accel*ny;
}
}
}
void ParticleGod::check_collisions()
{
for (int i=0; i < total; ++i)
{
for (int j=i+1; j<total; ++j)
{
// references for readability
Particle &particle = particles[i];
Particle &target = particles[j];
// If particles overlap some amount
if (do_particles_overlap(particle, target))
{
// Calculate overlap between particles
float x1 = particle.x;
float x2 = target.x;
float y1 = particle.y;
float y2 = target.y;
float distance_2 = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);
float distance = sqrtf(distance_2);
float overlap = 0.5*(distance - RADIUS*2);
// Move the particles
particle.x -= overlap*(x1 - x2)/distance;
particle.y -= overlap*(y1 - y2)/distance;
target.x += overlap*(x1 - x2)/distance;
target.y += overlap*(y1 - y2)/distance;
particle_collision(particle, target, distance);
}
}
}
}
void ParticleGod::record_positions(int time_step, float time)
{
// create buffer so we only write once (because stream overhead is HUGE apparently)
const int buff_size = NUM_PARTICLES*NUM_PARTICLES;
char buffer[buff_size];
int cx = 0;
// record positions of each particle controlled by the ParticleGod
for (auto &particle: particles)
{
// cx is updated so we don't overwrite the buffer
cx += std::snprintf(buffer+cx, buff_size-cx,
"%d\t%0.3f\t%0.3f\n",
time_step, particle.x, particle.y);
}
// create unique filename & output buffer to file (100 is arbitrary length)
char filename[100];
sprintf(filename, "./out/timestep%06d.txt", time_step);
ofstream out(filename);
out << buffer;
}
void ParticleGod::record_velocities()
{
//TODO: write function that records the velocites at each timestep
}
| true |
a3d0b2e43a299dccd7455923470d2b8f74c39570 | C++ | socc-io/algostudy | /BackTrackWorld/scale/scale_by_young.cpp | UTF-8 | 1,041 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int cnt;
int compare(const void * a, const void * b)
{
return (*(int*)a - *(int*)b);
}
void UtilGetNumber(int _jurely_num, int _mid, int start, int _jurely[], int sum)
{
for (int j = start; j < _jurely_num; j++) {
if (_jurely[j] + sum > _mid)
break;
else if (_jurely[j] + sum == _mid)
cnt++;
else
UtilGetNumber(_jurely_num, _mid, j + 1, _jurely, _jurely[j] + sum);
}
}
void GetNumber(int jurely_num, int jurely[], int jurely_sum)
{
int sum = 0;
int mid_sum = jurely_sum / 2;
UtilGetNumber(jurely_num, mid_sum, 0, jurely, sum);
cout << cnt;
}
int main()
{
int jurely_num;
int jurely_weight[31];
int jurely_sum = 0;
cnt = 0;
cin >> jurely_num;
for (int i = 0; i < jurely_num; i++)
{
int num;
cin >> num;
jurely_weight[i] = num;
jurely_sum += num;
}
qsort(jurely_weight, jurely_num, sizeof(int), compare);
if (jurely_sum % 2 != 0)
cout << "impossible";
else
GetNumber(jurely_num, jurely_weight, jurely_sum);
return 0;
} | true |
65242b24eeab91fd8598ad6e278c022ecffad7fd | C++ | asundov/Parking_Sensor_Project | /Transmitter/Sensors.cpp | UTF-8 | 836 | 2.859375 | 3 | [] | no_license | #include "Sensors.h"
#define IN4 4
const int trigPin = 5;
const int echoPin = 6;
SENSORS::SENSORS(){}
SENSORS::~SENSORS(){}
float SENSORS::distance(){
long duration;
int distance = 0;
delayMicroseconds(10);
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance); //distance is the returned integer, it is the distance in cm*/
return distance;
}
| true |
e7731b2e7b4e86fa300cfdc69522d8f263eea0ba | C++ | xixi2/linux_system_programing | /process/mmap1.cpp | UTF-8 | 695 | 2.640625 | 3 | [] | no_license | //
// Created by xixi2 on 2020/3/5.
//
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main(int argc, char *argv[]) {
int fd = open("english.txt", O_RDWR);
int len = lseek(fd, 0, SEEK_END);
void *ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) {
perror("mmap error");
exit(1);
}
printf("%s", (char *) ptr);
char *p = (char *) ptr;
++p;
printf("%s", p);
// 释放内存映射区
int ret = munmap(ptr, len);
if (ret == -1) {
perror("munmap error");
exit(1);
}
close(fd);
return 0;
} | true |
f082d0805ce1a66fc8ed3b9b931bbbecab7b28be | C++ | hinnalear/esp32cam-demo | /Misc/VeryBasicWebserver.ino | UTF-8 | 14,527 | 2.8125 | 3 | [] | no_license | // ----------------------------------------------------------------
//
//
// ESP32 / ESp8266 very basic web server demo - 11Jan21
//
// shows use of AJAX to show updating info on the web page
//
//
// ----------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// Wifi Settings
#include <wifiSettings.h> // delete this line, un-comment the below two lines and enter your wifi details
//const char *SSID = "your_wifi_ssid";
//const char *PWD = "your_wifi_pwd";
// ---------------------------------------------------------------------------------------------------------
bool serialDebug = 1; // enable debugging info on serial port
// ----------------------------------------------------------------
//#include <arduino.h> // required by platformio?
#if defined ESP32
// esp32
byte LEDpin = 2;
#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
WebServer server(80);
#elif defined ESP8266
//Esp8266
byte LEDpin = D4;
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "ESP8266HTTPClient.h"
ESP8266WebServer server(80);
#else
#error "This sketch only works with the ESP8266 or ESP32"
#endif
// ----------------------------------------------------------------
// this section runs once at startup
void setup() {
Serial.begin(115200); // start serial comms at speed 115200
delay(200);
Serial.println("\n\nWebserver demo sketch");
Serial.println("- Reset reason: " + ESP.getResetReason());
// onboard LEDs
pinMode(LEDpin, OUTPUT);
digitalWrite(LEDpin, HIGH);
// Connect to Wifi
Serial.print("Connecting to ");
Serial.println(SSID);
WiFi.begin(SSID, PWD);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print("\nConnected - IP: ");
Serial.println(WiFi.localIP());
// set up web server pages to serve
server.on("/", handleRoot); // root web page (i.e. when root page is requested run procedure 'handleroot')
server.on("/test", handleTest); // test web page
server.on("/button", handleButton); // demo simple use of buttons
server.on("/ajax", handleAJAX); // demo using AJAX to update information on the page (also javascript buttons)
server.on("/senddata", handleSendData); // requested by the AJAX web page to request current millis value
server.on("/setLED", handleLED); // action when a button is clicked on the AJAX page
server.onNotFound(handleNotFound); // if invalid url is requested
// start web server
server.begin();
// stop the wifi being turned off if not used for a while
#if defined ESP32
WiFi.setSleep(false);
#else
WiFi.setSleepMode(WIFI_NONE_SLEEP);
#endif
WiFi.mode(WIFI_STA); // turn off access point - options are WIFI_AP, WIFI_STA, WIFI_AP_STA or WIFI_OFF
} // setup
// ----------------------------------------------------------------
// this section runs repeatedly in a loop
void loop() {
server.handleClient(); // service any web page requests
//// flash onboard LED
//digitalWrite(LEDpin, !digitalRead(LEDpin)); // invert onboard LED status
//delay(200); // wait 200 milliseconds
} // loop
// ----------------------------------------------------------------
// -test web page requested i.e. http://x.x.x.x/
// ----------------------------------------------------------------
// demonstrate sending a plain text reply
void handleRoot(){
if (serialDebug) Serial.println("Root page requested");
String message = "root web page";
server.send(404, "text/plain", message); // send reply as plain text
} // handleRoot
// ----------------------------------------------------------------
// -test web page requested i.e. http://x.x.x.x/test
// ----------------------------------------------------------------
// demonstrate sending html reply
void handleTest(){
if (serialDebug) Serial.println("Test page requested");
WiFiClient client = server.client(); // open link with client
// html header
client.print("<!DOCTYPE html> <html lang='en'> <head> <title>Web Demo</title> </head> <body>\n"); // basic html header
// html body
client.print("<h1>Test Page</h1>\n");
// end html
client.print("</body></html>\n");
delay(3);
client.stop();
} // handleTest
// ----------------------------------------------------------------
// -button web page requested i.e. http://x.x.x.x/button
// ----------------------------------------------------------------
// demonstrate simple use of a html buttons without using Javascript
void handleButton(){
if (serialDebug) Serial.println("Button page requested");
// check if button1 has been pressed
if (server.hasArg("button1")) {
Serial.println("Button 1 was pressed");
}
// check if button2 has been pressed
if (server.hasArg("button2")) {
Serial.println("Button 2 was pressed");
}
// send reply to client
WiFiClient client = server.client(); // open link with client
// html header
client.print("<!DOCTYPE html> <html lang='en'> <head> <title>Web Demo</title> </head> <body>\n"); // basic html header
client.print("<FORM action='/button' method='post'>\n"); // used by the buttons in the html (action = the web page to send it to
// html body
client.print("<h1>Button demo page</h1>\n");
if (server.hasArg("button1")) client.print("Button 1 has been pressed!");
if (server.hasArg("button2")) client.print("Button 2 has been pressed!");
client.print("<br><br><input style='height: 35px;' name='button1' value='Demo button 1' type='submit'> \n");
client.print("<br><br><input style='height: 35px;' name='button2' value='Demo button 2' type='submit'> \n");
// end html
client.print("</body></html>\n");
delay(3);
client.stop();
} // handleButton
// ----------------------------------------------------------------
// -ajax web page requested i.e. http://x.x.x.x/ajax
// ----------------------------------------------------------------
// demonstrate use of AJAX to refresh info. on web page
// see: https://circuits4you.com/2018/02/04/esp8266-ajax-update-part-of-web-page-without-refreshing/
void handleAJAX() {
WiFiClient client = server.client(); // open link with client
// log page request including clients IP address
IPAddress cip = client.remoteIP();
Serial.println("Ajax page requested from: " + String(cip[0]) +"." + String(cip[1]) + "." + String(cip[2]) + "." + String(cip[3]) );
// ---------------------- html ----------------------
client.print (R"=====(
<!DOCTYPE html>
<html lang='en'>
<head>
<title>AJAX Demo</title>
</head>
<body>
<div id='demo'>
<h1>Update web page using AJAX</h1>
<button type='button' onclick='sendData(1)'>LED ON</button>
<button type='button' onclick='sendData(0)'>LED OFF</button><BR>
</div>
<div>
Current Millis : <span id='MillisValue'>0</span><br>
Received text : <span id='ReceivedText'>NA</span><br>
LED State is : <span id='LEDState'>NA</span><br>
</div>
)=====");
// ------------------- JavaScript -------------------
client.print (R"=====(<script>
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('LEDState').innerHTML = this.responseText;
}
};
xhttp.open('GET', 'setLED?LEDstate='+led, true);
xhttp.send();}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var receivedArr = this.responseText.split(',');
document.getElementById('MillisValue').innerHTML = receivedArr[0];
document.getElementById('ReceivedText').innerHTML = receivedArr[1];
}
};
xhttp.open('GET', 'senddata', true);
xhttp.send();}
setInterval(function() {
getData();
}, 2000);
</script>)=====");
// --------------------------------------------------
// close html page
client.print("</body></html>\n"); // close HTML
delay(3);
client.stop();
} // handleAJAX
// send data to AJAX web page
// it replies with two items comma separated: the value in millis and some text
void handleSendData() {
String reply = String(millis()); // item 1
reply += ",";
reply += "This text sent by handleSendtime()"; // item 2
server.send(200, "text/plane", reply); //Send millis value only to client ajax request
}
// handle button clicks on AJAX web page
// it sets the onboard LED status and replies with it's status as plain text
void handleLED() {
String ledState = "OFF";
String t_state = server.arg("LEDstate"); //Refer xhttp.open("GET", "setLED?LEDstate="+led, true);
Serial.println(t_state);
if(t_state == "1") {
digitalWrite(LEDpin,LOW); //LED ON
ledState = "ON"; //Feedback parameter
} else {
digitalWrite(LEDpin,HIGH); //LED OFF
ledState = "OFF"; //Feedback parameter
}
server.send(200, "text/plane", ledState); //Send web page
}
// ----------------------------------------------------------------
// -invalid web page requested
// ----------------------------------------------------------------
// send this reply to any invalid url requested
void handleNotFound() {
if (serialDebug) Serial.println("Invalid page requested");
String tReply;
tReply = "File Not Found\n\n";
tReply += "URI: ";
tReply += server.uri();
tReply += "\nMethod: ";
tReply += ( server.method() == HTTP_GET ) ? "GET" : "POST";
tReply += "\nArguments: ";
tReply += server.args();
tReply += "\n";
for ( uint8_t i = 0; i < server.args(); i++ ) {
tReply += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
}
server.send ( 404, "text/plain", tReply );
tReply = ""; // clear variable
} // handleNotFound
// ----------------------------------------------------------------------------------------------------------------
// Not used in this sketch but provided as an example of how to request an external web page and receive the reply as a string
// ----------------------------------------------------------------
// request a web page
// ----------------------------------------------------------------
// parameters = ip address, page to request, port to use (usually 80), maximum chars to receive, ignore all in reply before this text
// e.g. String reply = requestWebPage("192.168.1.166","/log",80,600,"");
String requestWebPage(String ip, String page, int port, int maxChars, String cuttoffText = ""){
int maxWaitTime = 3000; // max time to wait for reply (ms)
char received[maxChars + 1]; // temp store for incoming character data
int received_counter = 0; // number of characters which have been received
if (!page.startsWith("/")) page = "/" + page; // make sure page begins with "/"
if (serialDebug) {
Serial.print("requesting web page: ");
Serial.print(ip);
Serial.println(page);
}
WiFiClient client;
// Connect to the site
if (!client.connect(ip.c_str() , port)) {
if (serialDebug) Serial.println("Web client connection failed");
return "web client connection failed";
}
if (serialDebug) Serial.println("Connected to host - sending request...");
// send request - A basic request looks something like: "GET /index.html HTTP/1.1\r\nHost: 192.168.0.4:8085\r\n\r\n"
client.print("GET " + page + " HTTP/1.1\r\n" +
"Host: " + ip + "\r\n" +
"Connection: close\r\n\r\n");
if (serialDebug) Serial.println("Request sent - waiting for reply...");
// Wait for a response
uint32_t ttimer = millis();
while ( !client.available() && (uint32_t)(millis() - ttimer) < maxWaitTime ) {
delay(10);
}
if ( ((uint32_t)(millis() - ttimer) > maxWaitTime ) && serialDebug) Serial.println("-Timed out");
// read the response
while ( client.available() && received_counter < maxChars ) {
delay(4);
received[received_counter] = char(client.read()); // read one character
received_counter+=1;
}
received[received_counter] = '\0'; // end of string marker
if (serialDebug) {
Serial.println("--------received web page-----------");
Serial.println(received);
Serial.println("------------------------------------");
Serial.flush(); // wait for serial data to finish sending
}
client.stop(); // close connection
if (serialDebug) Serial.println("Connection closed");
// if cuttoffText was supplied then only return the text following this
if (cuttoffText != "") {
char* locus = strstr(received,cuttoffText.c_str()); // locus = pointer to the found text
if (locus) { // if text was found
if (serialDebug) Serial.println("The text '" + cuttoffText + "' was found in reply");
return locus; // return the reply text following 'cuttoffText'
} else if (serialDebug) Serial.println("The text '" + cuttoffText + "' WAS NOT found in reply");
}
return received; // return the full reply text
}
// ----------------------------------------------------------------
// end
| true |
23479739fccde07f4bb9b80a3bcdf3e867d29dae | C++ | holequotin/Discrete-Math | /subset1.cpp | UTF-8 | 1,028 | 3.453125 | 3 | [] | no_license | #include<iostream>
using namespace std;
//Khai báo giá trị ban đầu
void Init(int k,int arr[]){
for(int i=1;i<=k;i++){
arr[i]=i;
}
}
void Out(int arr[],int k){
for(int i=1;i<=k;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
//Hàm sinh phần tử tiếp theo,tìm phần tử đầu tiên chưa đạt max rồi đưa nó lên, các phần tử phía sau nó thì mình reset lại
void Next_Element(int n,int arr[],int k){
int i=k;
//tìm phần tử đầu tiên chưa đạt max
while (i>=1&&arr[i]==n-k+i)
{
i--;
}
arr[i]++;
for(int j=i+1;j<=k;j++){
arr[j]=arr[i]+j-i;
}
Out(arr,k);
}
bool check(int n,int arr[],int k){
for(int i=1;i<=k;i++){
if(arr[i]!=n-k+i) return false;
}
return true;
}
void Try(int n,int arr[],int k){
Init(n,arr);
Out(arr,k);
while (check(n,arr,k)==false)
{
Next_Element(n,arr,k);
}
}
int main() {
int n,k,arr[100];
cin>>n>>k;
Try(n,arr,k);
return 0;
}
| true |
b178e6f4e1255bb49663fb965c65f682fee52d7e | C++ | bgoodger/engsci331 | /eigen/myEigenFunctions.h | UTF-8 | 580 | 2.703125 | 3 | [
"MIT"
] | permissive | /*
EIGEN FUNCTION HEADER FILE
Ben Goodger
1822049
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#define PI 3.14159265358979323846
#define eps 0.00000000000000000000001
void power_method(double **A, double *y, int n, double &lamdba, double delta);
void eigen_all (double **A, double *y, int n, double &lambda, double delta);
double** deflate (double **A, int n, double *y, double lambda);
void eigen_shift (double **A, double *y, int n, double &lambda, double delta);
double DotProduct(double *A, double *B, int n);
double Norm(double *A, int n); | true |
f0f8f14ca536f3f096e3e3be98802fec19b6b5a6 | C++ | paulosuzart/graphic_editor | /src/VerticalSegmentCommand.cpp | UTF-8 | 814 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | /*
* VerticalSegmentCommand.cpp
*
* Created on: Jan 14, 2017
* Author: suzart
*/
#include "VerticalSegmentCommand.h"
namespace paulosuzart {
VerticalSegmentCommand::VerticalSegmentCommand(GraphEditor* editor,
string command) :
Command(editor, command) {
}
VerticalSegmentCommand::~VerticalSegmentCommand() {
}
bool VerticalSegmentCommand::doRun() {
editor->drawRect(line1, col, line2, col, color);
return true;
}
bool VerticalSegmentCommand::parseCommand(vector<string>& params) {
if (params.size() != 5)
return false;
col = boost::lexical_cast<unsigned int>(params[1]) - 1;
line1 = boost::lexical_cast<unsigned int>(params[2]) - 1;
line2 = boost::lexical_cast<unsigned int>(params[3]) - 1;
color = boost::lexical_cast<char>(params[4]);
return true;
}
} /* namespace paulosuzart */
| true |
caf783686d0a8142a52ac9f281086519e674ce0b | C++ | skxabc/skx | /c++_learn/src/specialTemplate/specialTemplate.cpp | UTF-8 | 566 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
//function template
template<class T>
int compare(const T& l, const T& r){
cout<<"in template<class T>..."<<endl;
return l-r;
}
//function template special
//template <>
int compare(const char* l, const char* r){
cout<<"in special template<>..."<<endl;
return strcmp(l, r);
}
//class template
template<class T>
class Compare
{
public:
static
}
int main(int argc, char** argv)
{
compare(1,2);
const char* l = "";
const char* r = "";
compare(l,r);
return 0;
} | true |
62f512f26e72777cebe681ddf314a4db57d2ce2b | C++ | IvanFilipov/FMI-OOP | /theoritical_examples/Polymorphism/Farm/Dog.cpp | UTF-8 | 326 | 3.046875 | 3 | [] | no_license | #include "Dog.h"
Dog::Dog(const char* src) : Animal(src) {
}
void Dog::makeSound() {
std::cout << "Dog with name " << name << " : bark! \n";
}
Animal* Dog::clone() {
//this is how we make a new heap object as same as ours
//and we return base class pointer in order to use the polymorphism
return new Dog(*this);
} | true |
8c6c266e438928b762650cba4f2d7ca50d1024e1 | C++ | cminusbrain/my_own_std | /transport/socket/io_socket.h | UTF-8 | 567 | 2.90625 | 3 | [] | no_license | #pragma once
#include <transport/socket/base_socket.h>
#include <vector>
#include <cstdint>
class IoSocket : public BaseSocket
{
public:
IoSocket();
explicit IoSocket(int fd);
IoSocket(IoSocket &&another) noexcept;
IoSocket &operator=(IoSocket &&another) noexcept ;
void Send(std::vector<uint8_t> data);
std::vector<uint8_t> Receive(size_t size);
friend void swap(IoSocket &first, IoSocket &second) noexcept
{
using std::swap;
swap(static_cast<BaseSocket&>(first), static_cast<BaseSocket&>(second));
}
};
| true |
a7d3d25a34dc77fc4439cfedf484cc2afc78ab14 | C++ | closedsum/core | /CsPlugin/Source/CsCore/Public/Types/Property/Value/CsProperty_Value.h | UTF-8 | 1,731 | 2.65625 | 3 | [
"MIT"
] | permissive | // Copyright 2017-2023 Closed Sum Games, LLC. All Rights Reserved.
#include "Types/Property/CsProperty.h"
#pragma once
template<typename ValueType>
struct TCsProperty : public ICsProperty
{
public:
ValueType DefaultValue;
ValueType Value;
ValueType Last_Value;
protected:
bool bDirty;
public:
TMulticastDelegate<void(const ValueType&)> OnChange_Event;
public:
TCsProperty()
{
bDirty = false;
OnChange_Event.Clear();
}
virtual ~TCsProperty(){}
void SetDefaultValue(const ValueType& inDefaultValue)
{
DefaultValue = inDefaultValue;
}
FORCEINLINE virtual void UpdateIsDirty()
{
bDirty = Value != Last_Value;
Last_Value = Value;
if (bDirty)
OnChange_Event.Broadcast(Value);
}
FORCEINLINE TCsProperty& operator=(const ValueType& B)
{
Value = B;
UpdateIsDirty();
return *this;
}
FORCEINLINE bool operator==(const ValueType& B) const
{
return Value == B;
}
FORCEINLINE bool operator!=(const ValueType& B) const
{
return !(*this == B);
}
FORCEINLINE virtual void Set(const ValueType& inValue)
{
Value = inValue;
UpdateIsDirty();
}
FORCEINLINE const ValueType& Get() { return Value; }
FORCEINLINE virtual void Clear()
{
bDirty = false;
}
void ResetValue()
{
Value = DefaultValue;
Last_Value = Value;
bDirty = false;
}
void Reset()
{
ResetValue();
OnChange_Event.Clear();
}
FORCEINLINE bool HasChanged() { return bDirty; }
FORCEINLINE void MarkDirty() { bDirty = true; }
FORCEINLINE void Resolve()
{
UpdateIsDirty();
Clear();
}
};
#define CS_AXES_2D 2
#define CS_AXES_3D 3
#define CS_AXIS_X 0
#define CS_AXIS_Y 1
#define CS_AXIS_Z 2
#define CS_AXES_3D_ALL 3
#define CS_AXIS_ROLL 0
#define CS_AXIS_PITCH 1
#define CS_AXIS_YAW 2 | true |
b7bdd05b5bd570406b5e2e1c546aa76551a49584 | C++ | jpiercefield/CPlusPlus | /CSC 2110/Prog2/prog2.cpp | UTF-8 | 966 | 3.59375 | 4 | [] | no_license | //James Logan Piercefield
#include "deck.h"
//Main of the Program, This also counts the consolidations for us.
//Meanwhile it also tracks how many consecutive consolidations we have
int main()
{
int num_consolidation=0;
int num_consecutive_consolidation=0;
int num_max_consolidation=0;
Deck list;
ifstream file("deckofcards.txt");
while(!file.eof()) //file.is_open()
{
Card* temp;
temp = new Card;
file >> *temp;
list.add(temp);
list.display();
cout << endl;
num_consecutive_consolidation = 0;
while(list.consolidate())
{
list.display();
num_consolidation++;
num_consecutive_consolidation++;
cout << endl;
}
if(num_consecutive_consolidation > num_max_consolidation)
{
num_max_consolidation = num_consecutive_consolidation;
}
}
file.close();
cout << "\nNumber of total consolidations: " << num_consolidation << endl;
cout << "Highest number of consecutive consolidations: ";
cout << num_max_consolidation << endl;
return 0;
} | true |
e1e3dbff0b3a905655c678c6721c6c18de53384d | C++ | mkltaneja/DS-ALGO | /TREE_revision/graph_1.cpp | UTF-8 | 4,171 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class edge
{
public:
int v = 0;
int w = 0;
edge(int v, int w)
{
this->v = v;
this->w = w;
}
};
int N = 7;
vector<vector<edge>> graph(N, vector<edge>());
// BASIC=======================================================================================
void addEdge(vector<vector<edge>> &gp, int u, int v, int w)
{
// if (u >= graph.size() || v >= graph.size() || u < 0 || v < 0)
// return;
gp[u].push_back(edge(v, w));
gp[v].push_back(edge(u, w));
}
int findEdge(int v1, int v2)
{
int i = 0;
while (i < graph[v1].size())
{
edge e = graph[v1][i];
if (e.v == v2)
break;
i++;
}
return i;
}
void removeEdge(int u, int v)
{
int idx1 = findEdge(u, v);
int idx2 = findEdge(v, u);
graph[u].erase(graph[u].begin() + idx1);
graph[v].erase(graph[v].begin() + idx2);
}
void removeVtx(int vtx)
{
// for(edge e : graph[u])
// {
// removeEdge(u,e.v);
// }
while(graph[vtx].size() != 0)
{
edge e = graph[vtx].back();
removeEdge(vtx,e.v);
}
}
//QUESTIONS====================================================================================
bool HasPath(int src, int dest, vector<bool> vis) //DFS
{
if(src == dest)
return true;
bool res = false;
vis[src] = true; //MARK
for(edge e : graph[src])
{
if(!vis[e.v]) //CHECK
{
res |= HasPath(e.v,dest,vis);
}
}
return res;
}
int allPath(int src, int dest, vector<bool> vis, int wsf, string ans)
{
if(src == dest)
{
cout<<ans<<" @ "<<wsf<<endl;
return 1;
}
int count = 0;
vis[src] = true;
for(edge e : graph[src])
{
if(!vis[e.v])
{
count += allPath(e.v,dest,vis,wsf+e.w,ans+to_string(e.v)+" --> ");
}
}
vis[src] = false;
return count;
}
class allSolpair
{
public:
int floor = -1e9;
int ceil = 1e9;
int lightW = 1e9;
int heavyW = 0;
};
void allSolution(int src, int dest, vector<bool> vis, int wsf, string ans, allSolpair &pair, int data)
{
if(src == dest)
{
cout<<ans<<" @ "<<wsf<<endl;
pair.lightW = min(pair.lightW,wsf);
pair.heavyW = max(pair.heavyW,wsf);
if(wsf < data)
pair.floor = max(wsf,pair.floor);
if(wsf > data)
pair.ceil = min(wsf,pair.ceil);
return;
}
vis[src] = true;
for(edge e : graph[src])
{
if(!vis[e.v])
{
allSolution(e.v,dest,vis,wsf+e.w,ans+to_string(e.v)+" --> ",pair,data);
}
}
vis[src] = false;
}
void preoder(int src, int dest, vector<bool> vis, int wsf, string ans)
{
cout<<ans<<" @ "<<wsf<<endl;
vis[src] = true;
for(edge e : graph[src])
if(!vis[e.v])
preoder(e.v,dest,vis,wsf+e.w,ans+to_string(e.v)+ "->");
vis[src] = false;
}
void display(vector<vector<edge>> &gp)
{
for (int i = 0; i < gp.size(); i++)
{
cout << i << " --> ";
for (edge e : graph[i])
cout << "(" << e.v << ", " << e.w << ") ";
cout << endl;
}
cout << endl;
}
void constructGraph()
{
addEdge(graph, 0, 1, 10);
addEdge(graph, 0, 3, 10);
addEdge(graph, 1, 2, 10);
addEdge(graph, 2, 3, 40);
addEdge(graph, 3, 4, 2);
addEdge(graph, 4, 5, 2);
addEdge(graph, 4, 6, 3);
addEdge(graph, 5, 6, 8);
}
int main()
{
constructGraph();
// display(graph);
addEdge(graph, 1, 3, 10);
// display(graph);
// removeEdge(3,4);
// display(graph);
// removeVtx(3);
// display(graph);
vector<bool> vis(graph.size(),0);
// cout<<(boolalpha)<<HasPath(0,6,vis);
// cout<<allPath(0,6,vis,0,"0 --> ");
allSolpair pair;
// allSolution(0,6,vis,0,"0 --> ",pair,30);
// cout<<"Lightest weight = "<<pair.lightW<<", Heaviest weight = "<<pair.heavyW<<", Floor value = "<<pair.floor<<", Ceil value = "<<pair.ceil<<endl;
cout<<"Preoder Traversal : \n";
preoder(0,6,vis,0,"0->");
} | true |
a68229d3c852f93ba9d2d9d92a39290ab59a28b9 | C++ | boryssmejda/CryptoChallenges | /src/Numbers/inc/Decimal.hpp | UTF-8 | 730 | 3.03125 | 3 | [] | no_license | #pragma once
#include <array>
#include "BaseNumber.hpp"
#include "Binary.hpp"
namespace crypto
{
class Decimal final: public BaseNumber
{
public:
explicit Decimal(const crypto::Binary& t_binaryRepresentation);
explicit Decimal(const std::string& t_number);
auto getStringRepresentation() const -> std::string override;
auto getBinaryRepresentation() const -> Binary override;
static constexpr std::array<char, 10> kAllowedDigits{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private:
auto isNumberCorrect() const -> bool override;
auto convertFromBinaryToDesiredBase(const Binary& t_binaryForm) const -> std::string override;
auto areDigitsBetweenZeroAndNine() const -> bool;
};
}//crypto
| true |
f25a7c3a0ca5e8414fc33d233b45492e4f4a0d98 | C++ | Bots-United/joebot | /wpstat3d/cwpstuff.h | UTF-8 | 9,392 | 2.65625 | 3 | [] | no_license | /******************************************************************************
JoeBOT - a bot for Counter-Strike
Copyright (C) 2000-2002 Johannes Lampel
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
******************************************************************************/
#ifndef __CWPSTUFF
#define __CWPSTUFF
#include <limits.h>
#include <iostream.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//=========================================================
// 2DVector - used for many pathfinding and many other
// operations that are treated as planar rather than 3d.
//=========================================================
class Vector2D
{
public:
inline Vector2D(void) { }
inline Vector2D(float X, float Y) { x = X; y = Y; }
inline Vector2D operator+(const Vector2D& v) const { return Vector2D(x+v.x, y+v.y); }
inline Vector2D operator-(const Vector2D& v) const { return Vector2D(x-v.x, y-v.y); }
inline Vector2D operator*(float fl) const { return Vector2D(x*fl, y*fl); }
inline Vector2D operator/(float fl) const { return Vector2D(x/fl, y/fl); }
inline float Length(void) const { return sqrt(x*x + y*y ); }
inline Vector2D Normalize ( void ) const
{
Vector2D vec2;
float flLen = Length();
if ( flLen == 0 )
{
return Vector2D( 0, 0 );
}
else
{
flLen = 1 / flLen;
return Vector2D( x * flLen, y * flLen );
}
}
float x, y;
};
inline float DotProduct(const Vector2D& a, const Vector2D& b) { return( a.x*b.x + a.y*b.y ); }
inline Vector2D operator*(float fl, const Vector2D& v) { return v * fl; }
//=========================================================
// 3D Vector
//=========================================================
class Vector // same data-layout as engine's vec3_t,
{ // which is a vec_t[3]
public:
// Construction/destruction
inline Vector(void) { }
inline Vector(float X, float Y, float Z) { x = X; y = Y; z = Z; }
//inline Vector(double X, double Y, double Z) { x = (float)X; y = (float)Y; z = (float)Z; }
//inline Vector(int X, int Y, int Z) { x = (float)X; y = (float)Y; z = (float)Z; }
inline Vector(const Vector& v) { x = v.x; y = v.y; z = v.z; }
inline Vector(float rgfl[3]) { x = rgfl[0]; y = rgfl[1]; z = rgfl[2]; }
// Operators
inline Vector operator-(void) const { return Vector(-x,-y,-z); }
inline int operator==(const Vector& v) const { return x==v.x && y==v.y && z==v.z; }
inline int operator!=(const Vector& v) const { return !(*this==v); }
inline Vector operator+(const Vector& v) const { return Vector(x+v.x, y+v.y, z+v.z); }
inline Vector operator-(const Vector& v) const { return Vector(x-v.x, y-v.y, z-v.z); }
inline Vector operator*(float fl) const { return Vector(x*fl, y*fl, z*fl); }
inline Vector operator/(float fl) const { return Vector(x/fl, y/fl, z/fl); }
// Methods
inline void CopyToArray(float* rgfl) const { rgfl[0] = x, rgfl[1] = y, rgfl[2] = z; }
inline float Length(void) const { return sqrt(x*x + y*y + z*z); }
operator float *() { return &x; } // Vectors will now automatically convert to float * when needed
operator const float *() const { return &x; } // Vectors will now automatically convert to float * when needed
inline Vector Normalize(void) const
{
float flLen = Length();
if (flLen == 0) return Vector(0,0,1); // ????
flLen = 1 / flLen;
return Vector(x * flLen, y * flLen, z * flLen);
}
inline Vector2D Make2D ( void ) const
{
Vector2D Vec2;
Vec2.x = x;
Vec2.y = y;
return Vec2;
}
inline float Length2D(void) const { return sqrt(x*x + y*y); }
// Members
float x, y, z;
};
inline Vector operator*(float fl, const Vector& v) { return v * fl; }
inline float DotProduct(const Vector& a, const Vector& b) { return(a.x*b.x+a.y*b.y+a.z*b.z); }
inline Vector CrossProduct(const Vector& a, const Vector& b) { return Vector( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x ); }
#define _MAXTEMPDIV 250
#define MAX_WAYPOINTS 4096
#define REACHABLE_RANGE 400 // ???? to change some time
#define WAYPOINT_UNREACHABLE USHRT_MAX
#define WAYPOINT_MAX_DISTANCE (USHRT_MAX-1)
// defines for waypoint flags field (32 bits are available)
#define W_FL_TEAM ((1<<0) + (1<<1)) /* allow for 4 teams (0-3) */
#define W_FL_TEAM_SPECIFIC (1<<2) /* waypoint only for specified team */
#define W_FL_CROUCH (1<<3) /* must crouch to reach this waypoint */
#define W_FL_LADDER (1<<4) /* waypoint on a ladder */
#define W_FL_LIFT (1<<5) /* wait for lift to be down before approaching this waypoint */
#define W_FL_PAUSE (1<<6) /* pause here (wait for door to open, etc.) */
#define W_FL_HEALTH (1<<7) /* health kit (or wall mounted) location */
#define W_FL_ARMOR (1<<8) /* armor (or HEV) location */
#define W_FL_AMMO (1<<9) /* ammo location */
#define W_FL_SNIPER (1<<10) /* sniper waypoint (a good sniper spot) */
#define W_FL_FLAG (1<<11) /* flag position (or hostage or president) */
#define W_FL_FLAG_GOAL (1<<12) /* flag return position (or rescue zone) */
#define W_FL_VISIT (1<<13) /* locations to visit every once in a while */
#define W_FL_AIMING (1<<14) /* locations to look at while camping (additional to others)*/
#define W_FL_DONTAVOID (1<<15) /**/
#define W_FL_RESET (1<<16) /**/
#define W_FL_DELETED (1<<31) /* used by waypoint allocation code */
#define WAYPOINT_VERSION 1
// define the waypoint file header structure...
typedef struct {
char filetype[8]; // should be "Joe_bot\0"
int waypoint_file_version;
int waypoint_file_flags; // not currently used
int number_of_waypoints;
char mapname[32]; // name of map for these waypoints
} WAYPOINT_HDR;
// define the structure for waypoints...
typedef struct {
int flags; // button, lift, flag, health, ammo, etc.
Vector origin; // location
} WAYPOINT;
#define MAX_PATH_INDEX 4
// define the structure for waypoint paths (paths are connections between
// two waypoint nodes that indicates the bot can get from point A to point B.
// note that paths DON'T have to be two-way. sometimes they are just one-way
// connections between two points. There is an array called "paths" that
// contains head pointers to these structures for each waypoint index.
typedef struct path {
short int index[MAX_PATH_INDEX]; // indexes of waypoints (index -1 means not used)
struct path *next; // link to next structure
} PATH;
typedef struct way{
short int iIndices[MAX_WAYPOINTS];
int iNum;
}WAY;
#define MAX_TIMES_PWP 4
// structure to contain statistical information
typedef struct WPStatitem{
long lKill; // number of kills
long lKilled; // number of bots being killed
float fpKilledTime[MAX_TIMES_PWP]; // time of kills
int lKilledT;
float fpKillTime[MAX_TIMES_PWP]; // time of kills
int lKillT;
float fADEn; // average distance to enemy (if 0 set to distance, else (nx+cdist)/(n+1))
int iNVWp; // number of visible waypoints
float fADVWp; // average distance to visible waypoints
float fMaxDVWp;
float fMinDVWp;
float fAHDVWp; // average height difference of visible waypoints to this waypoint
long lTraffic[2]; // for the two teams each one variable
}WPStatITEM;
#define _FTNAME "JoeBOT StatFile\0"
#define _WPSVERSION 14
typedef struct wpsheader{
char szFTName[20];
char szMapname[40]; // store map name here. because at every global init of this structure the gpGlobals->mapname is the right stuff, this can be set while loading. because it's not clear which content this variable has when a new map has started, or let's say the var has the name of the new map, the save function just stores the data to the name defined in here
long lVersion;
}WPSHEADER;
typedef struct WPStatdata{
long lKill;
long lKilled;
WPStatITEM FItem[MAX_WAYPOINTS];
}WPStatDATA;
class CWPStat{
public:
CWPStat();
~CWPStat();
int Load(char *);
int GetVisible(long,long);
//int Save(void);
//int Search(int,int,int,float,float);
//int SearchNearest(int,int,int,float);
WPSHEADER wpsHeader;
WPStatDATA d;
long *pWPV;
bool bRecalcWPV;
long lNWPfWPV; // number of waypoints for table pWPV
long lWPSlice;
long lPercent; // just for messages
WPStatITEM &operator [] (long);
long lKillMax;
long lKilledMax;
protected:
private:
};
extern bool g_waypoint_paths; // have any paths been allocated?
extern bool g_waypoint_on;
extern bool g_auto_waypoint;
extern bool g_auto_addpath;
extern bool g_path_waypoint;
extern int num_waypoints;
extern WAYPOINT waypoints[MAX_WAYPOINTS];
extern PATH *paths[MAX_WAYPOINTS];
extern CWPStat WPStat;
bool WaypointLoad(const char *);
#endif | true |
e8218e8087c03d0942459835c28a60dd369e4e60 | C++ | kyleashcraft/COMP130 | /labs/lab09/nine_increments.cpp | UTF-8 | 500 | 3.96875 | 4 | [] | no_license | //File: nine_increments.cpp
//Name: Ashcraft, Kyle
//Date: 2/14/2018
//Compiler used: MS Visual Studio 2018
//Purpose: Increment from 0 to 117 in steps of 9 using a for and while loop.
#include <iostream>
using namespace std;
int main(){
cout << "Output from the for-loop... \n";
for(int i = 0; i <= 117; i += 9){
cout << i << " ";
}
cout << "\nOutput from the while-loop... \n";
int i = 0;
while(i <= 117){
cout << i << " ";
i += 9;
}
return 0;
}
| true |
8ed385b9b047493b438c8b743999e84cf0be9915 | C++ | Minyeob/Algorithm | /Algorithm Practice/Algorithm Practice/11444.cpp | UTF-8 | 633 | 2.859375 | 3 | [] | no_license | #include <cstdio>
#include <map>
using namespace std;
map<long long, long long> trans;
#define div 1000000007LL;
long long fibo(long long n)
{
if (n == 1 || n == 2)
return 1;
else if (trans[n])
return trans[n];
else
{
if (n % 2 == 1)
{
long long m = (n + 1) / 2;
long long result = fibo(m)*fibo(m) + fibo(m - 1)*fibo(m - 1);
trans[n] = result%div;
return result%div;
}
if (n % 2 == 0)
{
long long m = n / 2;
long long result = (fibo(m - 1) + fibo(m + 1))*fibo(m);
trans[n] = result%div;
return result%div;
}
}
}
int main()
{
long long n;
scanf("%lld", &n);
printf("%lld", fibo(n));
} | true |
23af4c5df3f42bb1006ef7c4ee91619a5b55fab3 | C++ | mcarreiro/martin301290-sistemasoperativos | /tp2/src/backend-pthreads-aMano/RWLock.cpp | UTF-8 | 380 | 2.609375 | 3 | [] | no_license | #include "RWLock.h"
RWLock :: RWLock() {
pthread_rwlock_init(&(this->rwlock),NULL);
}
void RWLock :: rlock() {
pthread_rwlock_rdlock(&(this->rwlock));
}
void RWLock :: wlock() {
pthread_rwlock_wrlock(&(this->rwlock));
}
void RWLock :: runlock() {
pthread_rwlock_unlock(&(this->rwlock));
}
void RWLock :: wunlock() {
pthread_rwlock_unlock(&(this->rwlock));
}
| true |
f98b546b6c3a9116d5e442bc8557bf88f5cf931b | C++ | andeplane/molecular-dynamics | /src/filemanager/filemanager.cpp | UTF-8 | 2,380 | 2.546875 | 3 | [] | no_license | #include <filemanager/filemanager.h>
#include <topology.h>
#include <particles/atom.h>
#include <filemanager/mts0io.h>
#include <system.h>
#include <unitconverter.h>
FileManager::FileManager() :
m_movieFile(NULL)
{
}
FileManager::~FileManager()
{
if(isMovieFileOpen()) m_movieFile->close();
}
bool FileManager::isMovieFileOpen() const {
return (m_movieFile!=NULL);
}
ofstream *FileManager::getMovieFile() const
{
return m_movieFile;
}
void FileManager::finalize()
{
if(isMovieFileOpen()) m_movieFile->close();
}
void FileManager::saveMovieFrame(const vector<Atom> &atoms, Topology &topology) {
if(!isMovieFileOpen()) {
char *filename = new char[10000];
sprintf(filename,"movie_files/movie%04d.bin",topology.processorIndex());
m_movieFile = new ofstream(filename,std::ios::out | std::ios::binary);
if(!m_movieFile->is_open()) {
std::cout << "Could not open movie file: " << filename << ". Please check that the movie_file folder exists." << std::endl;
exit(1);
}
delete filename;
}
m_dataArray.clear();
for(const Atom &atom : atoms) {
double x = UnitConverter::lengthToAngstroms(atom.position[0] + topology.origo()[0]);
double y = UnitConverter::lengthToAngstroms(atom.position[1] + topology.origo()[1]);
double z = UnitConverter::lengthToAngstroms(atom.position[2] + topology.origo()[2]);
double atomicNumber = atom.type()->atomicNumber();
double atomID = atom.id();
m_dataArray.push_back(x);
m_dataArray.push_back(y);
m_dataArray.push_back(z);
m_dataArray.push_back(atomicNumber);
m_dataArray.push_back(atomID);
}
unsigned long numberOfAtoms = atoms.size();
m_movieFile->write (reinterpret_cast<char*>(&numberOfAtoms), sizeof(unsigned long));
m_movieFile->write (reinterpret_cast<char*>(&m_dataArray.front()), 5*numberOfAtoms*sizeof(double));
}
void FileManager::loadMts0(string mts0Directory, vector<int> numberOfCPUs, System &system)
{
Mts0IO reader(numberOfCPUs);
reader.loadMts0(mts0Directory, system);
system.atomManager().atoms().resetVelocityMaxwellian(UnitConverter::temperatureFromSI(0));
}
void FileManager::loadState(string stateFolder, vector<Atom> &atoms) {
}
void FileManager::saveState(string stateFolder, vector<Atom> &atoms) {
}
| true |
6ff7c25c570e3051ad672b9a610074f7a0b8d2cc | C++ | RaideNetSquad/shapes | /main.cpp | UTF-8 | 1,184 | 3.625 | 4 | [] | no_license | #include <iostream>
#include "vector.h"
double dotProduct(const Vector& vect_A, const Vector& vect_B);
double crossProduct(const Vector& Vector1,const Vector& Vector2);
bool collinear (const Vector& Vector1, const Vector& Vector2);
int main()
{
double v1x = 0.0;
double v1y = 10.0;
double v2x = 10.0;
double v2y = 6.1;
Vector v1(v1x, v1y);
Vector v2(v2x, v2y);
std::cout << ((v1 == v2) ? "True" : "False") << std::endl;
std::cout << ((v1 != v2) ? "True" : "False") << std::endl;
Vector v3 = v1 + v2;
std::cout << "x: " << v3.x << " y: " << v3.y << std::endl;
Vector v4 = v3 - v2;
std::cout << "x: " << v4.x << " y: " << v4.y << std::endl;
std::cout << "Vector len is " << v3.length() << std::endl;
std::cout << "* Vector on double scalar is " << v3 * 0.2 << std::endl;
std::cout << "/ Vector on double scalar is " << v3 / 0.2 << std::endl;
std::cout << "DotProduct v1 and v2 " << dotProduct(v1, v2) << std::endl;
std::cout << "CrossProduct v1 and v2 " << crossProduct(v1, v2) << std::endl;
std::cout << "Collinear v1 and v2 ? " << (collinear(v1, v2) ? "True" : "False") << std::endl;
return 0;
}
| true |
36aa2eb3d80d395bce6facf7919346d00c148544 | C++ | dfm/AstroFlow | /astroflow/ops/kepler_op.cc | UTF-8 | 2,593 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/shape_inference.h"
#include <cmath>
#include <limits>
using namespace tensorflow;
template <typename T>
inline T kepler (const T& M, const T& e, int maxiter, float tol) {
T E0 = M, E = M;
if (std::abs(e) < tol) return E;
for (int i = 0; i < maxiter; ++i) {
T g = E0 - e * sin(E0) - M, gp = 1.0 - e * cos(E0);
E = E0 - g / gp;
if (std::abs((E - E0) / E) <= T(tol)) {
return E;
}
E0 = E;
}
// If we get here, we didn't converge, but return the best estimate.
return E;
}
REGISTER_OP("Kepler")
.Attr("T: {float, double}")
.Attr("maxiter: int = 2000")
.Attr("tol: float = 1.234e-7")
.Input("manom: T")
.Input("eccen: T")
.Output("eanom: T")
.SetShapeFn([](shape_inference::InferenceContext* c) {
shape_inference::ShapeHandle e;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &e));
c->set_output(0, c->input(0));
return Status::OK();
});
template <typename T>
class KeplerOp : public OpKernel {
public:
explicit KeplerOp(OpKernelConstruction* context) : OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("maxiter", &maxiter_));
OP_REQUIRES(context, maxiter_ >= 0,
errors::InvalidArgument("Need maxiter >= 0, got ", maxiter_));
OP_REQUIRES_OK(context, context->GetAttr("tol", &tol_));
// Make sure that the tolerance isn't smaller than machine precision.
auto eps = std::numeric_limits<T>::epsilon();
if (tol_ < eps) tol_ = 2 * eps;
}
void Compute(OpKernelContext* context) override {
// Inputs
const Tensor& M_tensor = context->input(0);
const Tensor& e_tensor = context->input(1);
// Dimensions
const int64 N = M_tensor.NumElements();
// Output
Tensor* E_tensor = NULL;
OP_REQUIRES_OK(context, context->allocate_output(0, M_tensor.shape(), &E_tensor));
// Access the data
const auto M = M_tensor.template flat<T>();
const auto e = e_tensor.template scalar<T>()(0);
auto E = E_tensor->template flat<T>();
for (int64 n = 0; n < N; ++n) {
E(n) = kepler<T>(M(n), e, maxiter_, tol_);
}
}
private:
int maxiter_;
float tol_;
};
#define REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("Kepler").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
KeplerOp<type>)
REGISTER_KERNEL(float);
REGISTER_KERNEL(double);
#undef REGISTER_KERNEL
| true |
efe2042d0c0fc3687983194dd8637dc182240a5a | C++ | algorithm-archivists/GathVL | /include/objects/curve.h | UTF-8 | 522 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef GATHVL_CURVE_H
#define GATHVL_CURVE_H
#include "object.h"
#include "../types/color.h"
#include "../types/vec.h"
struct curve : object {
color clr;
vec origin;
std::vector<vec> points;
void draw(cairo_t *) const override;
curve(const std::vector<vec>& points, vec origin) :
clr({1.0, 1.0, 1.0, 1.0}), points(points), origin(origin) {}
curve(color clr, const std::vector<vec>& points, vec origin) :
clr(clr), points(points), origin(origin) {}
};
#endif //GATHVL_CURVE_H
| true |
c5022a8c95194fbcd996a0fb58b4b66faf5806f4 | C++ | JPenuchot/eve | /include/eve/function/ellint_1.hpp | UTF-8 | 3,349 | 2.90625 | 3 | [
"MIT"
] | permissive | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/detail/overload.hpp>
namespace eve
{
//================================================================================================
//! @addtogroup elliptic
//! @{
//! @var ellint_1
//!
//! @brief Callable object computing the elliptic integrals of the first kind :
//! \f$\int_0^{\phi} \frac{\mathrm{d}t}{\sqrt{1-k^2\sin^2 t}}\f$.
//!
//! **Required header:** `#include <eve/function/ellint_1.hpp>`
//!
//! #### Members Functions
//!
//! | Member | Effect |
//! |:-------------|:-----------------------------------------------------------|
//! | `operator()` | the ellint_1 operation |
//! | `operator[]` | Construct a conditional version of current function object |
//!
//! ---
//!
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
//! auto operator()(floating_real_value auto k) const noexcept;
//! auto operator()(floating_real_value auto phi, floating_real_value auto k) const noexcept;
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//!
//! **Parameters**
//!
//!`phi`, `k`: [floating real values](@ref eve::floating_real_value).
//!
//! computes the complete and incomplete elliptic integrals of the first kind :
//!
//!\f[ F(\phi,k) = \int_0^{\phi} \frac{\mbox{d}t}{\sqrt{1-k^2\sin^2 t}}\f]
//!
//!The complete case corresponds to \f$\phi = \pi/2\f$.
//!
//! - `k` must verify \f$k^2\sin^2\phi \le 1\f$ or the result is nan.
//!
//! - In the complete case this means \f$|k| \le 1\f$.
//!
//! In any other case the result is nan.
//!
//!@warning
//! Be aware that as \f$\pi/2\f$ is not exactly represented by floating point values the result of the incomplete
//! function with a \f$\phi\f$ value near \f$\pi/2\f$ can differ a lot with the result of the complete call.
//!
//! **Return value**
//!
//!Returns [elementwise](@ref glossary_elementwise) the elliptic integral of the first kind.
//!
//! The result type is of the compatibility type of the three parameters.
//!
//! ---
//!
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
//! auto operator[]( conditional_expression auto cond ) const noexcept;
//! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//!
//! Higher-order function generating a masked version of eve::ellint_1
//!
//! **Parameters**
//!
//! `cond` : conditional expression
//!
//! **Return value**
//!
//! A Callable object so that the expression `ellint_1[cond](x, ...)` is equivalent to `if_else(cond,ellint_1(x, ...),x)`
//!
//! ---
//!
//! #### Supported decorators
//!
//! no decorators are supported
//!
//! #### Example
//!
//! @godbolt{doc/core/ellint_1.cpp}
//!
//! @}
//================================================================================================
EVE_MAKE_CALLABLE(ellint_1_, ellint_1);
}
#include <eve/module/real/elliptic/function/regular/generic/ellint_1.hpp>
| true |
8acf6456edfb19322edd7804bfc58e56908bf015 | C++ | AlterFritz88/intro_to_prog_c_plus_plus | /task_1_5_15.cpp | UTF-8 | 380 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int maxs = 0, n;
vector<int> array;
cin >> n;
while (n != 0){
array.push_back(n);
cin >> n;}
for (int i=1; i < array.size() - 1; i++){
if ((array[i-1] < array[i]) and (array[i] > array[i+1])){
maxs++;
}
}
cout << maxs;
return 0;
}
| true |
6e86d18e134614b95255a3e71c7ac960a46952f0 | C++ | CrimsonCrow/codeforces | /4-div_2_A/05/helpful_maths.cpp | UTF-8 | 521 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::string st = "";
std::cin >> st;
std::vector<char> vc;
std::string re = "";
for(auto i : st) {
if(i == '+'){
continue;
} else {
vc.push_back(i);
}
}
std::sort(vc.begin(), vc.end());
for(auto i : vc){
re.append(1,i);
re.append(1,'+');
}
re.erase(re.end()-1);
std::cout << re << "\n";
return 0;
}
//76434399 Apr/12/2020 22:38UTC 2156200 339A - Helpful Maths GNU C++17 Accepted 62 ms 0 KB
| true |
5555963c89fe9ed9f36bd5858a9ad5c36e34feab | C++ | MatloobAltaf/LUMS-Projects | /CHESS on Console/UInterface.cpp | UTF-8 | 4,111 | 3.421875 | 3 | [] | no_license | #include <iostream>
//#include <iomanip>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
#include "UInterface.h"
// Save the next message to be displayed (regardind last command)
string next_message;
// User interface
// All the functions regarding the user interface are in this section
// Logo, Menu, Board, messages to the user
void createNextMessage(string msg)
{
next_message = msg;
}
void appendToNextMessage(string msg)
{
next_message += msg;
}
void clearScreen(void)
{
system("cls");
}
void printMessage(void)
{
cout << next_message << endl;
next_message = "";
}
void printLine(int iLine, int iColor1, int iColor2, Game& game)
{
// Example (for CELL = 6):
// [6-char]
// |______| subline 1
// |___Q__| subline 2
// |______| subline 3
// Define the CELL variable here.
// It represents how many horizontal characters will form one square
// The number of vertical characters will be CELL/2
// You can change it to alter the size of the board (an odd number will make the squares look rectangular)
int CELL = 6;
// Since the width of the characters BLACK and WHITE is half of the height,
// we need to use two characters in a row.
// So if we have CELL characters, we must have CELL/2 sublines
for (int subLine = 0; subLine < CELL / 2; subLine++)
{
// A sub-line is consisted of 8 cells, but we can group it
// in 4 iPairs of black&white
//write the number of line on the left
cout << "\t\t\t\t";
if (1 == subLine)
{
cout << iLine + 1;
}
else
{
cout << " ";
}
cout << "||";
for (int iPair = 0; iPair < 4; iPair++)
{
// First cell of the pair
for (int subColumn = 0; subColumn < CELL; subColumn++)
{
// The piece should be in the "middle" of the cell
// For 3 sub-lines, in sub-line 1
// For 6 sub-columns, sub-column 3
if (subLine == 1 && subColumn == 3)
{
cout <<char(game.getPieceAtPosition(iLine, iPair * 2) != 0x20 ? game.getPieceAtPosition(iLine, iPair * 2) : iColor1);
}
else
{
cout <<char(iColor1);
}
}
// Second cell of the pair
for (int subColumn = 0; subColumn < CELL; subColumn++)
{
// The piece should be in the "middle" of the cell
// For 3 sub-lines, in sub-line 1
// For 6 sub-columns, sub-column 3
if (subLine == 1 && subColumn == 3)
{
cout << char(game.getPieceAtPosition(iLine, iPair * 2 + 1) != 0x20 ? game.getPieceAtPosition(iLine, iPair * 2 + 1) : iColor2);
}
else
{
cout <<char(iColor2);
}
}
}
//boundry wall
cout << "||";
// Write the number of the line on the right
if (1 == subLine)
{
cout << " " << iLine + 1;
}
cout << "\n";
}
}
void printCaptured(Game& game)
{
// Captured pieces - print only if at least one piece has been captured
if (0 != game.white_captured.size() || 0 != game.black_captured.size())
{
cout << "\t\t\t\t---------------------------------------------\n";
cout << "\t\t\t\tWHITE captured: ";
for (unsigned i = 0; i < game.white_captured.size(); i++)
{
cout << char(game.white_captured[i]) << " ";
}
cout << "\n";
cout << "\t\t\t\tblack captured: ";
for (unsigned i = 0; i < game.black_captured.size(); i++)
{
cout << char(game.black_captured[i]) << " ";
}
cout << "\n";
cout << "\t\t\t\t---------------------------------------------\n";
}
// Current turn
cout << "\t\t\t\tCurrent turn: " << (game.getCurrentTurn() == chess::WHITE_PIECE ? "WHITE (upper case)" : "BLACK (lower case)") << "\n\n";
}
void printBoard(Game& game)
{
cout << "\t\t\t\t A B C D E F G H\n";
cout << "\t\t\t\t ==================================================\n";
for (int iLine = 7; iLine >= 0; iLine--)
{
if (iLine % 2 == 0)
{
// Line starting with BLACK
printLine(iLine, BLACK_SQUARE, WHITE_SQUARE, game);
}
else
{
// Line starting with WHITE
printLine(iLine, WHITE_SQUARE, BLACK_SQUARE, game);
}
}
cout << "\t\t\t\t ==================================================\n";
cout << "\t\t\t\t A B C D E F G H\n";
} | true |
510f10f1e2af6fa63926db2ab16fdc340d66a2ea | C++ | bradbell/dismod_at | /include/dismod_at/weight_info.hpp | UTF-8 | 1,759 | 2.546875 | 3 | [] | no_license | // SPDX-License-Identifier: AGPL-3.0-or-later
// SPDX-FileCopyrightText: University of Washington <https://www.washington.edu>
// SPDX-FileContributor: 2014-22 Bradley M. Bell
// ----------------------------------------------------------------------------
# ifndef DISMOD_AT_WEIGHT_INFO_HPP
# define DISMOD_AT_WEIGHT_INFO_HPP
# include <cppad/utility/vector.hpp>
# include "get_weight_table.hpp"
# include "get_weight_grid.hpp"
namespace dismod_at { // BEGIN_DISMOD_AT_NAMESPACE
class weight_info {
private:
// grid of age values for this weighting
CppAD::vector<size_t> age_id_;
// grid of time values for this weighting
CppAD::vector<size_t> time_id_;
// vector of weights for each age, time pair
CppAD::vector<double> weight_;
public:
// assignment operator
void operator=(const weight_info& w_info);
// default constructor
weight_info(void);
// testing constructor
weight_info(
const CppAD::vector<double>& age_table ,
const CppAD::vector<double>& time_table ,
const CppAD::vector<size_t>& age_id ,
const CppAD::vector<size_t>& time_id ,
const CppAD::vector<double>& weight
);
// normal constructor
weight_info(
const CppAD::vector<double>& age_table ,
const CppAD::vector<double>& time_table ,
size_t weight_id ,
const CppAD::vector<weight_struct>& weight_table ,
const CppAD::vector<weight_grid_struct>& weight_grid_table
);
//
size_t age_size(void) const;
size_t time_size(void) const;
//
size_t age_id(size_t i) const;
size_t time_id(size_t j) const;
//
double weight(size_t i, size_t j) const;
};
} // END_DISMOD_AT_NAMESPACE
# endif
| true |
dc100f59da21a4c180203ffe4a2074a3e030981f | C++ | haibin-chen/leetcode_record | /leetcode_29.cpp | UTF-8 | 3,950 | 3.765625 | 4 | [] | no_license | //
// Created by 陈海斌 on 2020-01-25.
//
#include <string>
#include <iostream>
using namespace std;
//divide two integers without using multiplication, division and mod operator.
//思路1 减法 超时
/*
class Solution {
public:
int divide(int dividend, int divisor) {
if (dividend < INT32_MIN or divisor < INT32_MIN or dividend > INT32_MAX or divisor > INT32_MAX)
return INT32_MAX;
long dividend_tmp = dividend;
long divisor_tmp = divisor;
long res = 0;
int negative = 1;
if ((dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0))
negative = -1;
if (dividend_tmp < 0)
dividend_tmp = -dividend_tmp;
if (divisor_tmp < 0)
divisor_tmp = -divisor_tmp;
while (dividend_tmp >= divisor_tmp)
{
dividend_tmp -= divisor_tmp;
res += 1;
}
return res * negative;
}
};
*/
//思路2 位运算
// 迭代写法
int add(int num1, int num2){
int sum = num1 ^ num2;
int carry = (num1 & num2) << 1;
while(carry != 0){
int a = sum;
int b = carry;
sum = a ^ b;
carry = (a & b) << 1;
}
return sum;
}
int substract(int num1, int num2){
int subtractor = add(~num2, 1);// 先求减数的补码(取反加一)
int result = add(num1, subtractor); // add()即上述加法运算
return result ;
}
//乘法 按上面的方式做会超时的
int multiply(int a, int b) {
//将乘数和被乘数都取绝对值
int multiplicand = a < 0 ? add(~a, 1) : a;
int multiplier = b < 0 ? add(~b , 1) : b;
//计算绝对值的乘积
int product = 0;
while(multiplier > 0) {
if((multiplier & 0x1) > 0) {// 每次考察乘数的最后一位
product = add(product, multiplicand);
}
multiplicand = multiplicand << 1;// 每运算一次,被乘数要左移一位
multiplier = multiplier >> 1;// 每运算一次,乘数要右移一位(可对照上图理解)
}
//计算乘积的符号
if((a ^ b) < 0) {
product = add(~product, 1);
}
return product;
}
//用减法
int divide_v1(int a, int b)
{
if (a == INT32_MIN && b == -1)
return INT32_MAX;
long dividend = labs(a);
long divisor = labs(b);
long res = 0;
int sign = a > 0 ^ b > 0 ? -1 : 1;
while (dividend >= divisor)
{
long tmp = divisor, m = 1;
while (tmp << 1 <= dividend)
{
tmp = tmp << 1;
m = m << 1;
}
dividend -= tmp;
res += m;
}
return res * sign;
}
// 本质上是有序数组的查找 可以用排序数组加速
// https://github.com/azl397985856/leetcode/blob/master/problems/29.divide-two-integers.md
int divide_v2(int a,int b)
{
if (a == INT32_MIN && b == -1)
return INT32_MAX;
// 先取被除数和除数的绝对值
long dividend = labs(a);
long divisor = labs(b);
long quotient = 0;// 商
long remainder = 0;// 余数
for(int i = 31; i >= 0; i--) {
//比较dividend是否大于divisor的(1<<i)次方,不要将dividend与(divisor<<i)比较,而是用(dividend>>i)与divisor比较,
//效果一样,但是可以避免因(divisor<<i)操作可能导致的溢出,如果溢出则会可能dividend本身小于divisor,但是溢出导致dividend大于divisor
if (dividend >= (divisor<<i)) {
quotient = quotient + (1 << i);
dividend = dividend - (divisor << i);
}
}
// 确定商的符号
if((a ^ b) < 0){
// 如果除数和被除数异号,则商为负数
quotient = -quotient;
}
return quotient;// 返回商
}
/*
int main()
{
// cout << (-2147483648 << 1) << endl;
//Solution s;
//cout << s.divide(-2147483648,1);
cout << divide_v2(-2147483648,-1);
}
*/ | true |
bb86fc26fa16db961266807fd8acc9ac487cc74f | C++ | sameer-h/CSCE121 | /Homeworks/miscellaneous/LW5/pimain.cpp | UTF-8 | 852 | 3.234375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
bool isInseedno(double x, double y, double r)
{
// inscribed inseedno of the circle
return sqrt(x*x + y*y) <= r;
}
bool throwDart(int s)
{
int x, y;
x = -s / 2 + rand() % (s + 1);
y = -s / 2 + rand() % (s + 1);
return isInseedno(x, y, s / 2);
}
int main()
{
srand(999);
int seedno;
int tries;
cout << "Random seed for darts: ";
cin >> seedno;
cout << "Enter the number of tries: ";
cin >> tries;
int inCount = 0; //counter
for (int i = 0; i < tries; ++i) {
//throw a dart
if (throwDart(seedno)) {
inCount++;
}
}
double pi = 4.0 * ((double)inCount / tries);
cout << "The estimated value of PI: " << pi << endl;
return 0;
} | true |