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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f909ed33faadeb3adff119cb594fe8ef2eed62a0 | C++ | WhiZTiM/coliru | /Archive2/2a/a5b7799708aa13/main.cpp | UTF-8 | 504 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b("00010010");
std::cout << "initial value: " << b << '\n';
// find the first unset bit
size_t idx = 0;
while (idx < b.size() && b.test(idx)) ++idx;
// continue setting bits until half the bitset is filled
while (idx < b.size() && b.count() < b.size()/2) {
b.set(idx);
std::cout << "setting bit " << idx << ": " << b << '\n';
while (idx < b.size() && b.test(idx)) ++idx;
}
} | true |
b3fdfce6535d7f7b3e1b55f21381448f93455d35 | C++ | sureshmangs/Code | /competitive programming/codeforces/1367A - Short Substrings.cpp | WINDOWS-1252 | 2,258 | 3.859375 | 4 | [
"MIT"
] | permissive | /*
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a as follows: he writes all the substrings of length 2 of the string a in the order from left to right, and then joins them in the same order into the string b.
For example, if Bob came up with the string a="abac", then all the substrings of length 2 of the string a are: "ab", "ba", "ac". Therefore, the string b="abbaac".
You are given the string b. Help Alice to guess the string a that Bob came up with. It is guaranteed that b was built according to the algorithm given above. It can be proved that the answer to the problem is unique.
Input
The first line contains a single positive integer t (1=t=1000) the number of test cases in the test. Then t test cases follow.
Each test case consists of one line in which the string b is written, consisting of lowercase English letters (2=|b|=100) the string Bob came up with, where |b| is the length of the string b. It is guaranteed that b was built according to the algorithm given above.
Output
Output t answers to test cases. Each answer is the secret string a, consisting of lowercase English letters, that Bob came up with.
Example
inputCopy
4
abbaac
ac
bccddaaf
zzzzzzzzzz
outputCopy
abac
ac
bcdaf
zzzzzz
Note
The first test case is explained in the statement.
In the second test case, Bob came up with the string a="ac", the string a has a length 2, so the string b is equal to the string a.
In the third test case, Bob came up with the string a="bcdaf", substrings of length 2 of string a are: "bc", "cd", "da", "af", so the string b="bccddaaf"
*/
#include<bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
string b;
cin >> b;
string a = "";
a += b[0];
int n = b.length();
for (int i = 1; i < n - 1; i+=2) {
a += b[i];
}
a += b[n - 1];
cout << a << endl;
}
return 0;
}
| true |
c0e2cd3402b85425820977815c2ffccf2132c8a6 | C++ | DanteRARA/STUST | /calender.cpp | BIG5 | 947 | 3.421875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int y, m, initDay, monthDay[12] = {31,28,31,30,31,30,31,31,30,31,30,31}; //CѼ
cout << "пJ~B" << endl;
cin >> y >> m;
if(y % 4 == 0){ //P_O_|~
monthDay[1]++; //O|~hb2++
initDay = (((y - 1900) / 4) * 366 + ((y - 1900) - ((y - 1900) / 4)) * 365) % 7; //pӦ~lP
}else{
initDay = (((y - 1900) / 4) * 366 + ((y - 1900) - ((y - 1900) / 4)) * 365 + 1) % 7;
}
cout << "\t@\tG\tT\t|\t\t\n";
for(int i = 0; i < m - 1; i++) initDay += monthDay[i]; //ƪ֥[
for(int i = 0; i < (initDay %= 7); i++) cout << "\t"; //p⩹ᲾX
for(int i = 1; i <= monthDay[m - 1]; i++){ //}lgJ
cout << i << "\t";
initDay++;
if(initDay >= 7){ //CCѴ
cout << endl;
initDay = 0;
}
}
return 0;
}
| true |
6d121a7251b186a60f5d41e7bd76d8ba2b3ea792 | C++ | computerphilosopher/BOJ | /10819/10819.cpp11.cpp | UTF-8 | 682 | 2.90625 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
int get_sum(const vector<int> &v){
int ret = 0;
int n = v.size();
for(int i=0; i<n-1; i++){
ret += abs(v[i] - v[i+1]);
}
return ret;
}
int main(){
int n = 0;
scanf("%d", &n);
vector<int> v;
for(int i=0; i<n; i++){
int temp = 0;
scanf("%d", &temp);
v.push_back(temp);
}
sort(v.begin(), v.end());
int ans = -101;
do{
ans = max(ans, get_sum(v));
}while(next_permutation(v.begin(), v.end()));
printf("%d", ans);
return 0;
}
| true |
7c1fab42855837d60679e435d910db14f2b74661 | C++ | arewas-fasuoy/Data-Structures | /Array-List/assignment-1.cpp | UTF-8 | 1,683 | 3.96875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Array_Operation{
private:
int *ptr1;
int *ptr2;
int length;
int *array;
int arr[8]={2,3,2,3,3,4,5,6};
public:
Array_Operation(){
ptr1=NULL;
ptr2=NULL;
length=0;
array= new int[15];
}
int * MostFrequentElementInSubArray(int left, int right, int frequency){
ptr1 = arr;
length=sizeof(arr)/sizeof(arr[0]); //finding length of array
if (left>=0 && right>=left && right<length){ //constraint 1
if (2*frequency>=right-left+1){ //constraint 2
for (int i =0; i<right; i++){
int count=1;
ptr2=arr+i+1;
for (int j= 0; j<right; j++){
if (*ptr1==*ptr2){
count++;
ptr2++;
}
else {
ptr2++;
}
}
ptr1++;
if(count>=frequency){
*(array+i)=*ptr1; //apending elements into array whose frequency is greater of equal to the given freqeuncy
cout<<endl<<"Elements whose Frequency is greater or equal to the given Frequency are: "<<*(array+i)<<endl;
}
}
}
else{
cout<<"Please Enter a valid Frequency that is greater than 1"<<endl;
}
}
else {
cout<<"Error: Invalid Indexes. Kindly Enter a valid index range "<<endl;
}
return array; //returning the address of array of matched frequency elements
}
};
int main(){
Array_Operation obj;
int *arr;
arr=obj.MostFrequentElementInSubArray(1,4,3);
cout<<endl<<"Elements whose Frequency is greater or equal to the given Frequency are: "<<endl;
int length1=sizeof(arr)/sizeof(arr[0]);
for (int i=0; i<length1; i++){ //printing the elements of array returned by function;
cout<<*(arr+i)<<endl;
}
return 0;
} | true |
59f1e338d817c36c300c4da36f5662eff33b9c3d | C++ | vermakriti/InterviewBit | /Tree/Path Sum/program.cpp | UTF-8 | 277 | 2.875 | 3 | [] | no_license | int Solution::hasPathSum(TreeNode* root, int B) {
if(!root)return 0;
if(!root->left && !root->right){
if(B==root->val)
return 1;
else return 0;
}
return hasPathSum(root->left,B-root->val) | hasPathSum(root->right,B-root->val);
}
| true |
5cfd6decc7677fb776babcd7963dec4e637c8be0 | C++ | oupjob/examples | /cpp/invalid_value_t/invalid_value_t.cpp | UTF-8 | 372 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
using namespace std;
template <typename T>
struct InvalidValue
{
operator T () {return false;}
};
template <typename T> const T invalidValue()
{
return sqrt(-1);
}
int main() {
int i = (int)InvalidValue<int>();
string s = (string)InvalidValue<string>();
int * pi = (int*)InvalidValue<int*>();
return 0;
}
| true |
3968a4dec6d21c67c4d95766dd6a2ba2a07b5118 | C++ | prinick96/procesos_e_hilos_SO | /PromedioSinSemaforo.cpp | UTF-8 | 2,754 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Deinir funciones
int *crearArreglo();
void *promediarArreglo(void *arg);
// Tipo de dato pasado por parámetro a la función que manejan los hilos
typedef struct {
int rango[2]; //Rango asignado
int hilo_actual;
} hilo_info;
// Definr variables
int *arreglo = crearArreglo();
int promd_h1 = 0;
int promd_h2 = 0;
int promd_h3 = 0;
int promd_h4 = 0;
// main
int main() {
// Definir hilos
pthread_t hilo1;
pthread_t hilo2;
pthread_t hilo3;
pthread_t hilo4;
// Definir parámetros para la función que maneja el hilo 1
hilo_info ph1;
ph1.rango[0] = 0;
ph1.rango[1] = 24;
ph1.hilo_actual = 1;
// Definir parámetros para la función que maneja el hilo 2
hilo_info ph2;
ph2.rango[0] = 25;
ph2.rango[1] = 50;
ph2.hilo_actual = 2;
// Definir parámetros para la función que maneja el hilo 3
hilo_info ph3;
ph3.rango[0] = 51;
ph3.rango[1] = 74;
ph3.hilo_actual = 3;
// Definir parámetros para la función que maneja el hilo 4
hilo_info ph4;
ph4.rango[0] = 75;
ph4.rango[1] = 99;
ph4.hilo_actual = 4;
// Crear los hilos
pthread_create(&hilo1,NULL,promediarArreglo,(void *)&ph1);
pthread_create(&hilo2,NULL,promediarArreglo,(void *)&ph2);
pthread_create(&hilo3,NULL,promediarArreglo,(void *)&ph3);
pthread_create(&hilo4,NULL,promediarArreglo,(void *)&ph4);
// Ejecutar los hilos
pthread_join(hilo1,NULL);
pthread_join(hilo2,NULL);
pthread_join(hilo3,NULL);
pthread_join(hilo4,NULL);
// Mostrar promedios
cout << "Promedio hilo 1: " << promd_h1 / 25 << endl;
cout << "Promedio hilo 2: " << promd_h2 / 25 << endl;
cout << "Promedio hilo 3: " << promd_h3 / 25 << endl;
cout << "Promedio hilo 4: " << promd_h4 / 25 << endl;
cout << "Promedio total: " << (promd_h1 + promd_h2 + promd_h3 + promd_h4 ) / 100 << endl;
return 0;
}
// Crea un arreglo
int *crearArreglo() {
int *arreglo = new int[100];
srand(time(NULL));
for(int i = 0; i < 100; i++) {
arreglo[i] = rand() % 1001;
}
return arreglo;
}
// Crear promedio del rango asignado
void *promediarArreglo(void *arg) {
hilo_info *p = (hilo_info *) arg;
for(int i = p->rango[0]; i <= p->rango[1]; i++) {
switch(p->hilo_actual) {
case 1:
promd_h1 += arreglo[i];
break;
case 2:
promd_h2 += arreglo[i];
break;
case 3:
promd_h3 += arreglo[i];
break;
case 4:
promd_h4 += arreglo[i];
break;
}
}
} | true |
84026206a56a0bc7e4e3da52eab9afe7335fbfb3 | C++ | nklemashev/phd | /uk/AxiomsPhD/AxiomsPhD/Backup/strfuns.hpp | UTF-8 | 279 | 2.703125 | 3 | [] | no_license | #include <vector>
#include <string>
namespace strfuns {
std::vector<std::string> split(const std::string& inStr, char sep);
std::string trim(std::string& inStr); //Removes spaces from the beginning and the ending of a string.
std::string int2str(int i);
}
| true |
3b33a8e595e4e602a449a9604ae00e75470c7fb4 | C++ | devedu-AI/Back_to_Basics | /c++_Functions/n_num_fact.cpp | UTF-8 | 261 | 3.265625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int fact(int a){
int ans;
if(a == 0){
return 1;
}
ans = fact(a - 1);
return a * ans;
}
int main()
{
int n;
cin>>n;
cout<<fact(n)<<endl;
return 0;
} | true |
6045bb42874c00108319f369abc3017f9d133dfc | C++ | benjaminhuanghuang/ben-leetcode | /0304_Range_Sum_Query_2D_-_Immutable/solution.cpp | UTF-8 | 1,303 | 3.453125 | 3 | [] | no_license | /*
304. Range Sum Query 2D - Immutable
Level: Medium
https://leetcode.com/problems/range-sum-query-2d-immutable
# 221. Maximal Square
*/
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
#include <algorithm>
#include "common/ListNode.h"
#include "common/TreeNode.h"
using namespace std;
/*
Solution: preprocessing
*/
class NumMatrix
{
private:
vector<vector<int>> sums_;
public:
NumMatrix(vector<vector<int>> &matrix)
{
sums_.clear();
if (matrix.empty())
return;
int m = matrix.size();
int n = matrix[0].size();
// sums_[i][j] = sum(matrix[0][0] ~ matrix[i-1][j-1])
sums_ = vector<vector<int>>(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; ++i)
for (int j = 1; j <= n; ++j)
sums_[i][j] = matrix[i - 1][j - 1] + sums_[i - 1][j] + sums_[i][j - 1] - sums_[i - 1][j - 1];
}
int sumRegion(int row1, int col1, int row2, int col2)
{
return sums_[row2 + 1][col2 + 1] - sums_[row2 + 1][col1] - sums_[row1][col2 + 1] + sums_[row1][col1];
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/ | true |
99a11ccc34121a80f2d5951f3f72fc396f6db9b5 | C++ | Ph0en1xGSeek/ACM | /POJ & HDU/LCM_Walk.cpp | GB18030 | 762 | 2.625 | 3 | [] | no_license | /**ѧƵ+ж**/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
int ca, cc = 1;
long long x, y;
int ans;
scanf("%d", &ca);
while(ca--)
{
ans = 1;
scanf("%I64d%I64d", &x, &y);
while(x != y)
{
if(x > y)
swap(x, y);
long long gcd = __gcd(x, y);
if(x*y % (gcd + x))
break;
long long z = x*y / (gcd + x);
if(z < x || z >= y || z%x != 0 || z%(y-z) != 0)
break;
ans++;
y -= z;
}
printf("Case #%d: %d\n", cc++, ans);
}
return 0;
}
| true |
2a107eeac19263edf9a93d7a2cdd1f472fb2b1ed | C++ | mihalyszekely/Snake2 | /include/options.h | UTF-8 | 596 | 2.546875 | 3 | [] | no_license | #pragma once
#include "SFML/Graphics.hpp"
#define MAX_NUMBER_OF_ITEMS 2
class Options
{
public:
Options(float width, float height);
~Options();
sf::RectangleShape hangnegyzett;
sf::RectangleShape hangnegyzetf;
bool hang=true;
void hangar(float width, float height,sf::RenderWindow &window);
void draw(sf::RenderWindow &window);
void MoveUp();
void MoveDown();
int GetPressedItem() { return selectedItemIndex; }
void pause(float width, float height, sf::RenderWindow &window);
private:
int selectedItemIndex;
sf::Font font;
sf::Text options[MAX_NUMBER_OF_ITEMS];
};
| true |
0663d161eb5237ebdcff56b28d25d158af9c9f74 | C++ | mehulthakral/logic_detector | /backend/CDataset/reverseList/reverseList_4.cpp | UTF-8 | 1,085 | 3.5625 | 4 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
class ListNode{
public:
ListNode* next;
int val;
};
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
//Take two nodes one to point and other to traverse with
ListNode* prev = NULL;
ListNode* curr = head;
while(curr->next!=NULL){
//Make a temp node to store the current node
ListNode* temp = curr;
//Move current to the next node
curr = curr->next;
//Reverse the arrow of temp (which was curr) to previous node
temp->next = prev;
// Move prev one step forward
prev = temp;
}
//At last reverse the arrow of last node to prev
curr->next = prev;
//Return current as head
return curr;
}
};
| true |
581120f30a2e0d9b7b6f77842599d49827a380e0 | C++ | ZakMaks/aip_semestr2 | /13nedela/HW1_13nedela/main.cpp | UTF-8 | 3,202 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
#include <fstream>
#include <ctime>
// 13неделя_1-5номер_
using namespace std;
int randArray[20] ;
int sless5=0;
int smore6=0;
int sless4=0;
int polojElem=0;
int otricElem=0;
int spol=0;
//int sotr=0;
float sredpol=0;
//float sredotr=0;
float srarif=0;
void Nomber1 ();
void Nomber2 ();
void Nomber3 ();
void Nomber4 ();
void Number5 ();
//1.Сгенерировать массив со случайными числами в диапазоне:
//f. [0,20]
void Nomber1(){
cout << "Massiv ot 0 do 20: ";
srand(time(NULL));
for (int i = 0; i < 20; i++){
if (i < (rand() % 21)) {
randArray[i] = rand() % 20; // 0 ... 20
}
cout << randArray[i] << " ";
if (i < 19) {
srarif += randArray[i];
}
else {
srarif = ((srarif + randArray[i]) / 20);
}
}
}
//Вычислить сумму элементов массива:
//c. меньших 5, больших 6, меньших 4,
void Nomber2 (){
for (int i = 0; i < 20; i++) {
if (randArray[i] > 6) {
smore6 =smore6 + randArray[i];
}
else if (randArray[i] < 4) {
sless4 += randArray[i];
sless5 += randArray[i];
}
else if (randArray[i] < 5) {
sless5 += randArray[i];
}
}
cout << "Summa chisel men'she 5: " << sless5 << endl;
cout << "Summa chisel bol'she 6: " << smore6 << endl;
cout << "Summa chisel men'she 4: " << sless4 << endl;
}
//8. Посчитать количество положительных/отрицательных элементов массива
void Nomber3 (){
for (int i = 0; i < 20; i++) {
if (randArray[i] > 0) {
polojElem += 1;
}
else if (randArray[i] < 0) {
otricElem += 1;
}
}
cout << "Kolichestvo polojitel'n elementov: " << polojElem << endl;
// cout << "Kolichestvo otricatel'n elementov: " << otricElem << endl;
}
//7. Найти среднее арифметическое положительных/отрицательных
void Nomber4 (){
for (int i = 0; i < 20; i++) {
if (randArray[i] > 0) {
polojElem += 1;
spol += randArray[i];
}
}
sredpol=spol/polojElem;
cout << "srednee arifmetich polojitel'n elementov: " << polojElem << endl;
}
//11. Вывести элементы массива, меньших среднего арифметического
void Nomber5(){
cout << "Srednee arifmeticheskoe: " << srarif << endl;
cout << "Element men'shi srednego arifmeticheskogo: ";
for (int i = 0; i < 20; i++) {
if (randArray[i] < srarif) {
cout << " " << randArray[i] << " ";
}
}
}
int main()
{
cout << " Pervoe zadanie"<<endl;
Nomber1();
cout << " Vtoroe zadanie"<<endl;
Nomber2();
cout << " Tret'e zadanie"<<endl;
Nomber3();
cout << " Chetvertoe zadanie"<<endl;
Nomber4();
cout << " Putoe zadanie"<<endl;
Nomber5();
}
| true |
d5d6606e4d5ee3efa2b02e1c8a45424e851b6687 | C++ | jianweiyao/Code | /c++/7/7-1.cpp | UTF-8 | 266 | 2.921875 | 3 | [] | no_license | // 默认参数值初探
#include <stdio.h>
int mul(int x = 0);
int main(int argc, const char *argv[]) {
printf("%d\n", mul());
printf("%d\n", mul(-1));
printf("%d\n", mul(2));
return 0;
}
int mul(int x) {
return x * x;
}
| true |
13b4fab5327f5039b683b5b13b9c042431d3bfd8 | C++ | E3798211/ProgLanguage | /Src/Tree.cpp | UTF-8 | 8,898 | 3 | 3 | [] | no_license | #include "../Head/Tree.h"
/*
*
* ============================================= NODE CLASS =============================================
*
*/
/*static*/ bool
Node::IsLast(const Node* check_node)
{
EnterFunction();
SAFE {
// Verificator
}
if (check_node->_left == nullptr && check_node->_right == nullptr){
SetColor(GREEN);
DEBUG printf("Given pointer is last\n");
SetColor(DEFAULT);
QuitFunction();
return true;
}else{
SetColor(GREEN);
DEBUG printf("Given pointer is not last\n");
SetColor(DEFAULT);
QuitFunction();
return false;
}
}
/*static*/ Node*
Node::CreateNode(Node* parent_node)
{
EnterFunction();
PrintVar(parent_node);
Node* new_node = nullptr;
try
{
new_node = new Node;
}
catch(const std::bad_alloc &ex)
{
SetColor(RED);
DEBUG printf("===== Cannot create new node =====\n");
SetColor(DEFAULT);
new_node = nullptr;
PrintVar(new_node);
QuitFunction();
return nullptr;
}
new_node->_parent = parent_node;
PrintVar(parent_node);
SetColor(GREEN);
DEBUG printf("New node created\n");
SetColor(DEFAULT);
QuitFunction();
return new_node;
}
// ================================================= SETTERS
int
Node::SetData(double new_data)
{
_data = new_data;
return OK;
}
int
Node::SetLeft(Node* left)
{
_left = left;
return OK;
}
int
Node::SetRight(Node* right)
{
_right = right;
return OK;
}
int
Node::SetParent(Node* parent)
{
_parent = parent;
return OK;
}
int
Node::SetDataType(int data_type)
{
_data_type = data_type;
return OK;
}
// ================================================= GETTERS
double
Node::GetData()
{
return _data;
}
Node*
Node::GetLeft()
{
return _left;
}
Node*
Node::GetRight()
{
return _right;
}
Node*
Node::GetParent()
{
return _parent;
}
int
Node::GetDataType()
{
return _data_type;
}
/*
*
* ============================================= TREE CLASS =============================================
*
*/
// ================================================= Supporting functions
// Related to Dot
int
SetNodes(FILE* output, Node* branch_root)
{
//PrintVar(branch_root);
if(branch_root == nullptr) return OK;
if(output == nullptr){
SetColor(RED);
DEBUG printf("===== Output file for DOT was not opened. =====\n");
SetColor(DEFAULT);
return FILE_NOT_OPENED;
}
fprintf(output, "_%p", branch_root);
fprintf(output, BEGIN_DECLARATION);
fprintf(output, LABELS);
fprintf(output, NEXT_FIELD);
fprintf(output, BEGIN_COLUMN);
fprintf(output, "_%p", branch_root);
fprintf(output, NEXT_FIELD);
fprintf(output, "%lg", branch_root->GetData());
fprintf(output, NEXT_FIELD);
fprintf(output, "%d", branch_root->GetDataType());
fprintf(output, NEXT_FIELD);
fprintf(output, "_%p", branch_root->GetLeft());
fprintf(output, NEXT_FIELD);
fprintf(output, "_%p", branch_root->GetRight());
fprintf(output, END_COLUMN);
fprintf(output, END_DECLARATION);
return OK;
}
// Related to Dot
int
BuildConnections(FILE* output, Node* branch_root)
{
if(branch_root == nullptr) return OK;
if(branch_root->GetLeft() != nullptr){
fprintf(output, "_%p", branch_root);
fprintf(output, TO);
fprintf(output, "_%p", branch_root->GetLeft());
fprintf(output, LEFT_DIRECTION);
}
if(branch_root->GetRight() != nullptr){
fprintf(output, "_%p", branch_root);
fprintf(output, TO);
fprintf(output, "_%p", branch_root->GetRight());
fprintf(output, RIGHT_DIRECTION);
}
return OK;
}
// ================================================= Private
bool
Tree::BelongsToTree(Node* branch_root, const Node* check_ptr)
{
if(check_ptr == nullptr) return false;
if(branch_root == nullptr) return false;
if(branch_root == check_ptr) return true;
return (BelongsToTree(branch_root->GetLeft(), check_ptr) ||
BelongsToTree(branch_root->GetRight(), check_ptr))? true : false;
}
int
Tree::PrintBranch(FILE* output, Node* branch_root, int (*print_type)(FILE* output, Node* node_to_print))
{
print_type(output, branch_root);
if(branch_root->GetLeft() != nullptr)
PrintBranch(output, branch_root->GetLeft(), print_type);
if(branch_root->GetRight() != nullptr)
PrintBranch(output, branch_root->GetRight(), print_type);
return OK;
}
// ================================================= Public
Tree::Tree()
{
EnterFunction();
try
{
//_root = new Node;
_root = Node::CreateNode();
_n_nodes = 1;
}
catch(const std::bad_alloc &ex)
{
SetColor(RED);
DEBUG printf("===== Cannot create root node =====\n");
SetColor(DEFAULT);
}
PrintVar(_root);
PrintVar(_n_nodes);
QuitFunction();
}
Tree::~Tree()
{
EnterFunction();
if(_alive){
_alive = false;
DeleteBranch(_root);
}
QuitFunction();
}
Node*
Tree::GetRoot()
{
return _root;
}
int
Tree::GetNNodes()
{
return _n_nodes;
}
bool
Tree::IsAlive()
{
return _alive;
}
Node*
Tree::FindNode(Node* branch_root, const double node_data)
{
EnterFunction();
SAFE {
if(branch_root == nullptr){
QuitFunction();
return nullptr;
}
}
//if(branch_root->_data == node_data){
if(branch_root->GetData() == node_data){
QuitFunction();
return branch_root;
}
Node* check_node = nullptr;
if(branch_root->GetLeft() != nullptr)
check_node = FindNode(branch_root->GetLeft(), node_data);
// If found
if(check_node != nullptr){
SetColor(GREEN);
//DEBUG printf("Element \"%d\" found. p = %p\n", check_node->_data, check_node);
DEBUG printf("Element \"%lg\" found. p = %p\n", check_node->GetData(), check_node);
SetColor(DEFAULT);
QuitFunction();
return check_node;
}
if(branch_root->GetRight() != nullptr)
check_node = FindNode(branch_root->GetRight(), node_data);
QuitFunction();
return check_node;
}
int
Tree::SetData(Node* change_node, const double data, int data_type)
{
EnterFunction();
PrintVar(change_node);
PrintVar(data);
assert(change_node != nullptr);
SAFE {
// Verificator
if(!BelongsToTree(_root, change_node)){
SetColor(BLUE);
USR_INFORM printf("Node does not belong to the tree\n");
SetColor(DEFAULT);
PrintVar(change_node);
PrintVar(data);
QuitFunction();
return NODE_DOES_NOT_EXIST;
}
}
// =============================
change_node->SetData(data);
change_node->SetDataType(data_type);
// =============================
PrintVar(change_node);
PrintVar(data);
QuitFunction();
return OK;
}
int
Tree::DeleteBranch(Node* branch_root, int rec_depth, bool right)
{
assert(branch_root != nullptr);
SetColor(MAGENTA);
DEBUG printf("\tIn: recursion depth = %d, right = %s\n", rec_depth, right? "true" : "false");
SetColor(DEFAULT);
PrintVar(branch_root);
PrintVar(branch_root->GetLeft());
PrintVar(branch_root->GetRight());
SAFE {
if(!BelongsToTree(_root, branch_root)){
SetColor(BLUE);
USR_INFORM printf("Node does not belong to the tree\n");
SetColor(DEFAULT);
return NODE_DOES_NOT_EXIST;
}
}
if(branch_root->GetLeft() != nullptr)
DeleteBranch(branch_root->GetLeft(), rec_depth + 1, false);
if(branch_root->GetRight() != nullptr)
DeleteBranch(branch_root->GetRight(), rec_depth + 1, true);
delete branch_root;
_n_nodes--;
SetColor(MAGENTA);
DEBUG printf("\tQuit: recursion depth = %d, right = %s\n", rec_depth, right? "true" : "false");
SetColor(DEFAULT);
return OK;
}
int
Tree::CallGraph()
{
FILE* output = fopen(DOT_FILENAME_DEFAULT, "w");
if(output == nullptr){
SetColor(RED);
DEBUG printf("===== Output file for DOT was not opened. =====\n");
SetColor(DEFAULT);
return FILE_NOT_OPENED;
}
fprintf(output, BEGIN);
fprintf(output, SET_RECORD_SHAPE);
PrintBranch(output, _root, SetNodes);
PrintBranch(output, _root, BuildConnections);
fprintf(output, END);
fclose(output);
char command[1000];
strcpy(command, DOT1);
strcat(command, DOT_FILENAME_DEFAULT);
strcat(command, DOT2);
strcat(command, IMG_FILENAME_DEFAULT);
system(command);
strcpy(command, OPEN);
strcat(command, IMG_FILENAME_DEFAULT);
return system(command);
}
| true |
9434766101b8aa255176bd6fc3e45209726475b1 | C++ | Lukinari/oop-vjezbe | /Vjezba 2/Vjezba 2 Zadatak 5/Zadatak 5.cpp | UTF-8 | 866 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int* fun(int& refsiz)
{
int siz = 0;
int j = 10;
int* arr;
int* temp;
arr = new int[j];
int i;
while(i)
{
cout << "Enter a number: ";
cin >> i;
if(i>0)
{
arr[siz] = i;
siz++;
}
if(siz==(j))
{
temp = new int[j * 2];
copy(arr, arr + j, temp);
delete [] arr;
arr = 0;
j = j * 2;
arr = new int[j];
copy(temp, temp + (j/2), arr);
delete [] temp;
temp = 0;
}
}
refsiz = siz;
return arr;
}
int main()
{
int tsiz;
int k = 0;
int* p_arr;
p_arr = fun(tsiz);
while(k<tsiz)
{
cout << p_arr[k] << " ";
k++;
}
delete [] p_arr;
p_arr = 0;
return 0;
}
| true |
be82c6600e73b568fc307860c06d390c705c79a5 | C++ | freem/SMOnline-v1 | /Crash/Linux/BacktraceNames.cpp | UTF-8 | 13,802 | 2.546875 | 3 | [
"MIT"
] | permissive | /* for dladdr: */
#define __USE_GNU
#include "../crashDefines.h"
#include "BacktraceNames.h"
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <unistd.h>
#include <cstring>
#include <cerrno>
#if defined(DARWIN)
#include "archutils/Darwin/Crash.h"
#endif
#if defined(HAVE_LIBIBERTY)
#include "libiberty.h"
/* This is in libiberty. Where is it declared? */
extern "C" {
char *cplus_demangle (const char *mangled, int options);
}
void BacktraceNames::Demangle()
{
char *f = cplus_demangle(Symbol, 0);
if(!f)
return;
Symbol = f;
free(f);
}
#elif defined(HAVE_CXA_DEMANGLE)
#include <cxxabi.h>
void BacktraceNames::Demangle()
{
if (Symbol==NULL)
return;
/* demangle the name using __cxa_demangle() if needed *///
// if( Symbol.substr(0, 2) != "_Z" )
// return;
int status = 0;
char *name = abi::__cxa_demangle( Symbol, 0, 0, &status );
if( name )
{
Symbol = name;
free( name );
return;
}
switch( status )
{
case -1:
fprintf( stderr, "Out of memory\n" );
break;
case -2:
fprintf( stderr, "Invalid mangled name: %s.\n", Symbol.c_str() );
break;
case -3:
fprintf( stderr, "Invalid arguments.\n" );
break;
default:
fprintf( stderr, "Unexpected __cxa_demangle status: %i", status );
break;
}
}
#else
void BacktraceNames::Demangle() { }
#endif
MString BacktraceNames::Format() const
{
MString ShortenedPath = File;
if( ShortenedPath != "" )
{
/* Abbreviate the module name. */
size_t slash = ShortenedPath.rfind('/');
if( slash != ShortenedPath.npos )
ShortenedPath = ShortenedPath.substr(slash+1);
ShortenedPath = MString("(") + ShortenedPath + ")";
}
MString ret = ssprintf( "%0*lx: ", int(sizeof(void*)*2), (long unsigned int) (Address) );
if( Symbol != "" )
ret += Symbol + " ";
ret += ShortenedPath;
return ret;
}
#if defined(BACKTRACE_LOOKUP_METHOD_DLADDR)
/* This version simply asks libdl, which is more robust. */
#include <dlfcn.h>
void BacktraceNames::FromAddr( const void *p )
{
Address = (intptr_t) p;
/*
* When calling a function that doesn't return, gcc will truncate a function.
* This results in our return addresses lying just beyond the end of a function.
* Those addresses are correct; our backtrace addresses are usually a list of
* return addresses (that's the same thing you'll see in gdb). dladdr won't work,
* because they're not actually within the bounds of the function.
*
* A generic fix for this would be to adjust the backtrace to be a list of
* places where control was lost, instead of where it'll come back to; to point
* to the CALL instead of just beyond the CALL. That's hard to do generically;
* the stack only contains the return pointers. (Some archs don't even contain
* that: on archs where gcc has to manually store the return address--by pushing
* the IP--it will omit the push when calling a function that never returns.)
*
* Let's try the address we're given, and if that fails to find a symbol, try
* moving up a few bytes. This usually makes "__cxa_throw, std::terminate,
* gsignal" stacks come out right. It probably won't work if there's no space
* between one function and the next, because the first lookup will succeed.
*/
Dl_info di;
if( !dladdr(p, &di) || di.dli_sname == NULL )
{
if( !dladdr( ((char *) p) - 8, &di) )
return;
}
Symbol = di.dli_sname;
File = di.dli_fname;
Offset = (char*)(p)-(char*)di.dli_saddr;
}
#elif defined(BACKTRACE_LOOKUP_METHOD_DARWIN_DYLD)
/*
Copyright (c) 2002 Jorge Acereda <jacereda@users.sourceforge.net> &
Peter O'Gorman <ogorman@users.sourceforge.net>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Cleaned and adapted. -glenn
*/
#include <mach-o/dyld.h>
#include <mach-o/nlist.h>
const load_command *next_load_command( const load_command *cmd )
{
const char *p = (const char *) cmd;
p += cmd->cmdsize;
return (load_command *) p;
}
/* Return the image index of the given pointer, or -1 if not found. */
int osx_find_image( const void *p )
{
unsigned long image_count = _dyld_image_count();
for( unsigned i = 0; i < image_count; i++ )
{
const struct mach_header *header = _dyld_get_image_header(i);
if( header == NULL )
continue;
/* The load commands directly follow the mach_header. */
const struct load_command *cmd = (struct load_command *) &header[1];
for( unsigned j = 0; j < header->ncmds; j++ )
{
/* We only care about mapped segments. */
if( cmd->cmd != LC_SEGMENT )
{
cmd = next_load_command(cmd);
continue;
}
const segment_command *scmd = (const segment_command *) cmd;
const unsigned long bottom = scmd->vmaddr + _dyld_get_image_vmaddr_slide( i );
const unsigned long top = scmd->vmaddr + scmd->vmsize + _dyld_get_image_vmaddr_slide( i );
if ( (unsigned long) p >= bottom && (unsigned long) p < top )
return i;
cmd = next_load_command(cmd);
}
}
return -1;
}
const char *osx_find_link_edit( const struct mach_header *header )
{
const struct load_command *cmd = (struct load_command *) &header[1];
for( unsigned i = 0; i < header->ncmds; i++, cmd = next_load_command(cmd) )
{
if( cmd->cmd != LC_SEGMENT )
continue;
const segment_command *scmd = (const segment_command *) cmd;
if( !strcmp(scmd->segname, "__LINKEDIT") )
return (char *) ( scmd->vmaddr - scmd->fileoff );
}
return NULL;
}
void BacktraceNames::FromAddr( const void *p )
{
Address = (intptr_t) p;
/* Find the image with the given pointer. */
int index = osx_find_image( p );
if( index == -1 )
return;
File = _dyld_get_image_name( index );
/* Find the link-edit pointer. */
const char *link_edit = osx_find_link_edit( _dyld_get_image_header(index) );
if( link_edit == NULL )
return;
link_edit += _dyld_get_image_vmaddr_slide( index );
unsigned long addr = (unsigned long)p - _dyld_get_image_vmaddr_slide(index);
const struct mach_header *header = _dyld_get_image_header( index );
const struct load_command *cmd = (struct load_command *) &header[1];
unsigned long diff = 0xffffffff;
const char *dli_sname = NULL;
void *dli_saddr = NULL;
for( unsigned long i = 0; i < header->ncmds; i++, cmd = next_load_command(cmd) )
{
if( cmd->cmd != LC_SYMTAB )
continue;
const symtab_command *scmd = (const symtab_command *) cmd;
struct nlist *symtable = (struct nlist *)( link_edit + scmd->symoff );
for( unsigned long j = 0; j < scmd->nsyms; j++ )
{
if( !symtable[j].n_value )
continue; /* Undefined */
if( symtable[j].n_type >= N_PEXT )
continue; /* Debug symbol */
if( addr >= symtable[j].n_value && diff >= (addr - symtable[j].n_value) )
{
diff = addr - (unsigned long)symtable[j].n_value;
dli_saddr = symtable[j].n_value + ((char *)p - addr);
dli_sname = (const char *)( link_edit + scmd->stroff + symtable[j].n_un.n_strx );
}
}
}
if( diff == 0xffffffff )
return;
Symbol = dli_sname;
Offset = (char*)(p)-(char*)dli_saddr;
/*
* __start -> _start
* __ZN7RageLog5TraceEPKcz -> _ZN7RageLog5TraceEPKcz (so demangling will work)
*/
if( Symbol.Left(1) == "_" )
Symbol = Symbol.substr(1);
}
#elif defined(BACKTRACE_LOOKUP_METHOD_BACKTRACE_SYMBOLS)
/* This version parses backtrace_symbols(), an doesn't need libdl. */
#include <execinfo.h>
void BacktraceNames::FromAddr( const void *p )
{
Address = (intptr_t) p;
void * bob;
bob = malloc(128);
memcpy(bob, p, 128);
char **foo = backtrace_symbols( &bob, 1);
free (bob);
if( foo == NULL )
return;
FromString( foo[0] );
free(foo);
}
/* "path(mangled name+offset) [address]" */
void BacktraceNames::FromString( MString s )
{
/* Hacky parser. I don't want to use regexes in the crash handler. */
MString MangledAndOffset, sAddress;
unsigned pos = 0;
while( pos < s.size() && s[pos] != '(' && s[pos] != '[' )
File += s[pos++];
// TrimRight( File ); //hack by cnlohr
// TrimLeft( File );
if( pos < s.size() && s[pos] == '(' )
{
pos++;
while( pos < s.size() && s[pos] != ')' )
MangledAndOffset += s[pos++];
}
if( MangledAndOffset != "" )
{
size_t plus = MangledAndOffset.rfind('+');
if(plus == MangledAndOffset.npos)
{
Symbol = MangledAndOffset;
Offset = 0;
}
else
{
Symbol = MangledAndOffset.substr(0, plus);
MString str = MangledAndOffset.substr(plus);
if( sscanf(str, "%i", &Offset) != 1 )
Offset=0;
}
}
}
#elif defined(BACKTRACE_LOOKUP_METHOD_ATOS)
void BacktraceNames::FromAddr( const void *p )
{
int fds[2];
pid_t pid;
pid_t ppid = getpid(); /* Do this before fork()ing! */
Offset = 0;
Address = intptr_t(p);
if (pipe(fds) != 0)
{
fprintf(stderr, "FromAddr pipe() failed: %s\n", strerror(errno));
return;
}
pid = fork();
if (pid == -1)
{
fprintf(stderr, "FromAddr fork() failed: %s\n", strerror(errno));
return;
}
if (pid == 0)
{
close(fds[0]);
for (int fd = 3; fd < 1024; ++fd)
if (fd != fds[1])
close(fd);
dup2(fds[1], fileno(stdout));
close(fds[1]);
char *addy;
asprintf(&addy, "0x%x", long(p));
char *p;
asprintf(&p, "%d", ppid);
execl("/usr/bin/atos", "/usr/bin/atos", "-p", p, addy, NULL);
fprintf(stderr, "execl(atos) failed: %s\n", strerror(errno));
free(addy);
free(p);
_exit(1);
}
close(fds[1]);
char f[1024];
bzero(f, 1024);
int len = read(fds[0], f, 1024);
Symbol = "";
File = "";
if (len == -1)
{
fprintf(stderr, "FromAddr read() failed: %s\n", strerror(errno));
return;
}
MStringArray mangledAndFile;
split(f, " ", mangledAndFile, true);
if (mangledAndFile.size() == 0)
return;
Symbol = mangledAndFile[0];
/* eg
* -[NSApplication run]
* +[SomeClass initialize]
*/
if (Symbol[0] == '-' || Symbol[0] == '+')
{
Symbol = mangledAndFile[0] + " " + mangledAndFile[1];
/* eg
* (crt.c:300)
* (AppKit)
*/
if (mangledAndFile.size() == 3)
{
File = mangledAndFile[2];
size_t pos = File.find('(');
size_t start = (pos == File.npos ? 0 : pos+1);
pos = File.rfind(')') - 1;
File = File.substr(start, pos);
}
return;
}
/* eg
* __start -> _start
* _SDL_main -> SDL_main
*/
if (Symbol[0] == '_')
Symbol = Symbol.substr(1);
/* eg, the full line:
* __Z1Ci (in a.out) (asmtest.cc:33)
* _main (in a.out) (asmtest.cc:52)
*/
if (mangledAndFile.size() > 3)
{
File = mangledAndFile[3];
size_t pos = File.find('(');
size_t start = (pos == File.npos ? 0 : pos+1);
pos = File.rfind(')') - 1;
File = File.substr(start, pos);
}
/* eg, the full line:
* _main (SDLMain.m:308)
* __Z8GameLoopv (crt.c:300)
*/
else if (mangledAndFile.size() == 3)
File = mangledAndFile[2].substr(0, mangledAndFile[2].rfind(')'));
}
#else
#warning Undefined BACKTRACE_LOOKUP_METHOD_*
void BacktraceNames::FromAddr( const void *p )
{
Address = intptr_t(p);
Offset = 0;
Symbol = "";
File = "";
}
#endif
/*
* (c) 2003-2004 Glenn Maynard
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| true |
6911df4be4345396199385f9a7ccd63108aa39e2 | C++ | inbdni/Programmers | /level03/풍선터트리기.cpp | UTF-8 | 634 | 3.125 | 3 | [] | no_license | #include <string>
#include <vector>
using namespace std;
int solution(vector<int> a) {
int answer = 0;
int i, l_min, r_min;
int size = a.size() - 1;
vector<int> left;
vector<int> right;
l_min = a[0];
left.push_back(l_min);
r_min = a[size];
right.push_back(r_min);
for (i = 1; i < size; i++)
{
l_min = min(l_min, a[i]);
left.push_back(l_min);
r_min = min(r_min, a[size - i]);
right.push_back(r_min);
}
for (i = 0; i <= size; i++)
{
if (a[i] <= left[i] || a[i] <= right[size - i])
answer++;
}
return answer;
}
| true |
d73be32579eb508f663e6c1a5787062226927019 | C++ | hennin67/UMLWars | /project1\project1\Pause.h | UTF-8 | 459 | 2.8125 | 3 | [] | no_license | /**
* \file Pause.h
*
* \author Team Zuse
*
* Class that implements the pause screen.
*
*/
#pragma once
#include <memory>
#include "Screen.h"
#include "ImageObject.h"
/** The Class that implements Pause
*/
class CPause : public CImageObject
{
public:
/// Constructor
CPause(CScreen* screen);
/// Default constructor (disabled)
CPause() = delete;
/// Copy constructor (disabled)
CPause(const CPause&) = delete;
};
| true |
208782b4cecce7cdd23c8a52c86ca4f149d84518 | C++ | Moto0116/Library | /Library/Library/Library/EventManager/EventManager.h | UTF-8 | 2,091 | 2.84375 | 3 | [] | no_license | /**
* @file EventManager.h
* @brief イベント管理クラス定義
* @author morimoto
*/
#ifndef LIB_EVENTMANAGER_H
#define LIB_EVENTMANAGER_H
//----------------------------------------------------------------------
// Include
//----------------------------------------------------------------------
#include <vector>
#include <map>
#include "Debugger\Debugger.h"
#include "..\SingletonBase\SingletonBase.h"
namespace Lib
{
class EventBase;
class EventListener;
/*** イベント管理クラス */
class EventManager final : public SingletonBase<EventManager>
{
public:
friend SingletonBase<EventManager>;
/**
* EventListenerをグループに追加する
* @param[in] _pEventListener 追加するイベントリスナ
* @param[in] _groupName イベントリスナを追加するグループの名前
*/
void AddEventListener(EventListener* _pEventListener, LPCTSTR _groupName);
/**
* EventListenerをグループから削除する
* @param[in] _pEventListener 削除するイベントリスナ
* @param[in] _groupName イベントリスナを削除するグループの名前
*/
void RemoveEventListener(EventListener* _pEventListener, LPCTSTR _groupName);
/**
* イベントをグループに通知する
* @param[in] _pEvent 通知するイベント
* @param[in] _groupName イベントを通知するグループ名
*/
void SendEventMessage(EventBase* _pEvent, LPCTSTR _groupName);
private:
/*** LPCTSTR比較用のオブジェクト */
struct CompareStr
{
public:
bool operator()(LPCTSTR _str1, LPCTSTR _str2) const
{
return strcmp(_str1, _str2) < 0;
}
};
/*** コンストラクタ */
EventManager();
/*** デストラクタ */
virtual ~EventManager();
std::map<
LPCTSTR,
std::vector<EventListener*>,
CompareStr>
m_pEventListenerGroups; //!< イベントリスナを格納するコンテナ.
#ifdef _DEBUG
Debugger::ConsoleWindow m_ConsoleWindow; //!< デバッグ情報を出力するウィンドウ.
#endif // _DEBUG
};
}
#endif // !LIB_EVENTMANAGER_H
| true |
2343bbbe19c4fe4a6392e6087e7a575ad5201201 | C++ | HimalayaITSolutions/CPP_Vector | /Complex.cpp | UTF-8 | 1,338 | 3.109375 | 3 | [] | no_license | #include "pch.h"
#include "Complex.h"
#include <iostream>
Complex::Complex(double r, double i)
:re(r),
img(i)
{
}
Complex::Complex(double r)
: re{r},
img(r)
{
}
Complex::~Complex()
{
re = img = 0.0f;
}
Complex operator+(Complex a, Complex b)
{
// TODO: insert return statement here
return a += b;
}
Complex operator-(Complex a, Complex b)
{
// TODO: insert return statement here
return a -= b;
}
Complex& Complex::operator+=(Complex & b)
{
// TODO: insert return statement here
re += b.re;
img += b.img;
return *this;
}
Complex & Complex::operator-=(Complex & b)
{
// TODO: insert return statement here
re -= b.re;
img -= b.img;
return *this;
}
Complex & Complex::operator*=(Complex & b)
{
// TODO: insert return statement here
re *= b.re;
img *= b.img;
return *this;
}
Complex operator*(Complex a, Complex b)
{
// TODO: insert return statement here
return a *= b;
}
bool operator!=(Complex & a, Complex & b)
{
return !(a==b);
}
bool Complex::operator==(Complex & b)
{
// TODO: insert return statement here
return (getReal() == b.getReal() &&
getImg() == b.getImg());
}
| true |
59300149d7b9e6d28abbfb4e76374dcdd677da30 | C++ | aajjbb/contest-files | /TC/500-DIV2-250.cpp | UTF-8 | 1,001 | 3 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class SRMCards {
public:
int maxTurns(vector <int> cards) {
sort(cards.begin(), cards.end());
int ans = 0;
for(; !cards.empty(); ) {
int acc = 10, index = 0, ind_prev = -1, ind_next = -1;
for(int j = 0; j < cards.size(); j++) {
int check = 1;
bool prev = false, next = false;
if(j + 1 < cards.size() && cards[j + 1] - 1 == cards[j]) { check += 1; next = true; }
if(j - 1 >= 0 && cards[j - 1] + 1 == cards[j]) { check += 1; prev = true; }
if(check < acc) {
if(prev) ind_prev = j - 1; else ind_prev = -1;
if(next) ind_next = j + 1; else ind_next = -1;
acc = check; index = cards[j];
}
}
ans += 1;
cards.erase(find(cards.begin(), cards.end(), index));
if(ind_prev != -1) cards.erase(find(cards.begin(), cards.end(), index - 1));
if(ind_next != -1) cards.erase(find(cards.begin(), cards.end(), index + 1));
}
return ans;
}
};
// Powered by FileEdit
| true |
e45b5053c6a4c10eee5724f82776fa24211c46c8 | C++ | SemaMolchanov/self_study | /useful/functions.cpp | UTF-8 | 1,190 | 3.328125 | 3 | [] | no_license | int sum_of_digits(int number){
int sum = 0;
if (number > 0){
while (number != 0){
sum = sum + number%10;
number = number/10;
}
}
return sum;
}
char to_upper(char c){
if (c >= 'a' && c <= 'z'){
c = c - 32;
}
return c;
}
bool is_prime(int x) {
if (x < 2) {
return false;
}
bool answer = true;
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) {
answer = false;
}
}
return answer;
}
long long itself_power(long long x){
long long product;
if (x == 0){
product = 1;
return product;
}
product = 1;
for (int i = 0; i < x; i++){
product *= x;
}
return product;
}
/*bool is_palindrome(vector<int> v){
for(int i = 0; i < v.size()/2; i++){
if(v[i] != v[v.size()-1 - i]){
return false;
}
}
return true;
}*/
/*void to_bin(int n){
string s = "";
if(n == 0){
s = "0";
}
while(n != 0){
s += char(n%2 + 48);
n /= 2;
}
for(int i = 0; i < s.size()/2; i++){
swap(s[i], s[s.size()-1-i]);
}
cout << s << endl;
}*/ | true |
49752a980423176f7db756020634d9f9a69c08f2 | C++ | fanafree/CodingTest | /16235.cpp | UHC | 2,391 | 3.09375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N, M, K;
int food[11][11] = { 5, };
int addFood[11][11] = { 0, };
int dir[8][2] = {
{-1, -1},
{-1 , 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
vector<int> treeList[11][11];
/*
: ڽ ̸ŭ 1 . ̸ŭ ٸ
: . ̸ 2 ߰
: . Ϸ ̰ 5 ϸ 8 ĭ ̰ 1
ܿ : κ ƴٴϸ ߰. ĭ ߰ Ǵ A[r][c]
*/
void breed(int y, int x) {
for (int i = 0; i < 8; i++) {
int ny = y + dir[i][0], nx = x + dir[i][1];
if (ny < 1 || ny > N || nx < 1 || nx > N) continue;
treeList[ny][nx].push_back(1);
}
}
void springAndSummer() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
//spring
if (treeList[i][j].empty()) continue;
vector<int> livingTree;
int deadTreeFood = 0;
sort(treeList[i][j].begin(), treeList[i][j].end());
for (int k = 0; k < treeList[i][j].size(); k++) {
if (treeList[i][j][k] <= food[i][j]) {
food[i][j] -= treeList[i][j][k];
treeList[i][j][k]++;
livingTree.push_back(treeList[i][j][k]);
}
else deadTreeFood += treeList[i][j][k] / 2;
}
treeList[i][j].clear();
for (int k = 0; k < livingTree.size(); k++) {
treeList[i][j].push_back(livingTree[k]);
}
//summer
food[i][j] += deadTreeFood;
}
}
}
void autumn() {
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
for (int k = 0; k < treeList[i][j].size(); k++)
if (treeList[i][j][k] % 5 == 0) breed(i, j);
}
void winter() {
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
food[i][j] += addFood[i][j];
}
int main() {
cin >> N >> M >> K;
int r, c, z;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++) {
cin >> addFood[i][j];
food[i][j] = 5;
}
for (int i = 0; i < M; i++) {
cin >> r >> c >> z;
treeList[r][c].push_back(z);
}
while (K--) {
springAndSummer();
autumn();
winter();
}
int sum = 0;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
sum += treeList[i][j].size();
cout << sum;
return 0;
} | true |
9ae6df98374cb3e5fd6bee8ffeb846baeb769028 | C++ | divyang4481/mipt-hw | /anastasyev_daniil/task07_BFS/BFS_matrix.cpp | UTF-8 | 1,367 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
enum color {BLACK, GREY, WHITE};
struct TNode
{
color clr;
int dist;
int parent;
};
void BFS (vector < vector <bool> > &g, int s)
{
vector < TNode > v(g.size());
queue < int > q;
for (int i = 0; i < g.size(); ++i)
{
if ( i != s)
{
v[i].clr = WHITE;
v[i].dist = -1;
v[i].parent = 0;
}
}
v[s].clr = GREY;
v[s].dist = 0;
v[s].parent = 0;
q.push (s);
int t;
while (!q.empty())
{
t = q.front();
q.pop();
for (int i = 1; i < g[t].size(); ++i)
{
if (g[t][i] && v[i].clr==WHITE)
{
v[i].clr = GREY;
v[i].dist = v[t].dist+1;
v[i].parent = t;
q.push(i);
}
}
v[t].clr = BLACK;
}
for (int i = 0; i < v.size(); ++i)
{
if (v[i].dist > 0)
{
cout << i+1 << " distance: " << v[i].dist << " parent: " << v[i].parent+1 << endl;
}
else cout << i+1 << " no links or initial node"<<endl;
}
}
int main()
{
FILE *in = fopen("in.txt","r");
int N, M;
fscanf(in, "%d %d", &N, &M);
vector<TNode*> ver(N);
vector < vector <bool> > g(N);
for (int i=0; i<N; ++i)
for (int j=0; j<N; ++j)
{
g[i].push_back(0);
}
int x, y;
for (int i=0; i<M; ++i)
{
fscanf(in, "%d %d", &x, &y);
g[x-1][y-1] = 1;
}
BFS (g, 0);
fclose(in);
return 0;
} | true |
e524287219cec9c6ecccc6d3cfbaa962fffbe3b6 | C++ | gkastrinis/talk-material | /IO_tutorial/fstream2.cpp | UTF-8 | 391 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void)
{
fstream tmp("data4.txt", ios::out);
tmp.close();
fstream file("data4.txt", ios::in | ios::out);
file << 1 << " www.photobucket.com" << endl;
file << 2 << " www.deviantart.com" << endl;
file.seekg(0, ios::beg);
int i;
string site;
file >> i >> site;
cout << i << " " << site << endl;
}
| true |
82a788db5986ca5a401fff2facfa8e73d8912a22 | C++ | TudorArnautu/ase_stuff | /ConsoleApplication11/ConsoleApplication11/Sas.cpp | UTF-8 | 6,660 | 2.734375 | 3 | [] | no_license | # include <iostream>
# include <string>
using namespace std;
class interviu
{
char *nume_candidat;
char *post;
int salariu;
float nota_1; // cele doua note reflecta rezultatul celor 2 teste sustinute de un candidat
float nota_2;
char *rezultat; // aceasta variabila va lua valoarea "acceptat/respins"
static int timp_alocat;
static int nr_posturi;
const int id;
public:
void set_nume_candidat(char *nume_candidat)
{
delete[] this->nume_candidat;
this->nume_candidat = new char[strlen(nume_candidat) + 1];
strcpy(this->nume_candidat, nume_candidat);
}
char * get_nume_cand()
{
return nume_candidat;
}
void set_post(char *post)
{
delete[] this->post;
this->post = new char[strlen(post) + 1];
strcpy(this->post, post);
}
char * get_post()
{
return post;
}
char * get_rezultat()
{
return rezultat;
}
void set_salariu(int salariu)
{
this->salariu = salariu;
}
int get_salariu()
{
return salariu;
}
float get_nota_1()
{
return nota_1;
}
float get_nota2()
{
return nota_2;
}
void set_note(float n1, float n2)
{
nota_1 = n1;
nota_2 = n2;
}
static void set_timp(int new_timp)
{
timp_alocat = new_timp;
}
static int get_timp()
{
return timp_alocat;
}
static int get_nr_posturi()
{
return nr_posturi;
}
void afisare()
{
cout << "Candidatul " << nume_candidat << " s-a prezentat la interviul pentru ocuparea postului de " << post << ",acesta sustinand doua teste la care a obtinut " << nota_1 << " puncte si " << nota_2 << " puncte, acestora fiind alocate " << timp_alocat << " minute.Rezultatul final pentru candidat este " << rezultat << ". Salariul pentru acest post este de " << salariu << " lei.\n";
}
void cand_rezultat()
{
if ((nota_1 + nota_2) / 2>7.5)
{
rezultat = new char[strlen("admis") + 1];
strcpy(rezultat, "admis");
}
else
{
rezultat = new char[strlen("respins") + 1];
strcpy(rezultat, "respins");
}
}
const int get_id()
{
return id;
}
interviu() :id(0)
{
nume_candidat = new char[strlen("Mihai Popescu") + 1];
strcpy(nume_candidat, "Mihai Popescu");
post = new char[strlen("Asistent manager") + 1];
strcpy(post, "asistent manager");
//timp_alocat=45;
nota_1 = (float)7;
nota_2 = (float)6.3;
salariu = 1000;
cand_rezultat();
nr_posturi++;
}
interviu(char *nume_candidat, int salariu, float nota_1, float nota_2, char*post, int id_nou) :id(id_nou)
{
this->nume_candidat = new char[strlen(nume_candidat) + 1];
strcpy(this->nume_candidat, nume_candidat);
this->salariu = salariu;
this->nota_1 = nota_1;
this->nota_2 = nota_2;
this->post = new char[strlen(post) + 1];
strcpy(this->post, post);
this->cand_rezultat();
}
~interviu()
{
delete[] nume_candidat;
//delete[] post;
delete[] rezultat;
}
interviu(const interviu &aux) :id(aux.id)
{
this->nume_candidat = new char[strlen(aux.nume_candidat) + 1];
strcpy(this->nume_candidat, aux.nume_candidat);
this->post = new char[strlen(aux.post) + 1];
strcpy(this->post, aux.post);
this->salariu = aux.salariu;
this->nota_1 = aux.nota_1;
this->nota_2 = aux.nota_2;
nr_posturi++;
}
operator int()
{
return nr_posturi;
}
interviu operator=(const interviu &obj)
{
delete[] nume_candidat;
delete[] post;
this->nume_candidat = new char[strlen(obj.nume_candidat) + 1];
strcpy(this->nume_candidat, obj.nume_candidat);
this->post = new char[strlen(obj.post) + 1];
strcpy(this->post, obj.post);
this->salariu = obj.salariu;
this->nota_1 = obj.nota_1;
this->nota_2 = obj.nota_2;
return *this;
}
interviu operator+(interviu obj)
{
interviu aux = *this;
aux.salariu += obj.salariu;
return aux;
}
interviu operator+(int value)
{
interviu aux;
aux = *this;
aux.salariu += value;
return aux;
}
interviu operator++()//preincrementare
{
this->nota_1++;
this->nota_2++;
return *this;
}
interviu operator++(int)//postincrementare
{
interviu aux = *this;
this->nota_1++;
this->nota_2++;
return aux;
}
bool operator<=(interviu aux)
{
bool temp = this->salariu <= aux.salariu;
return temp;
}
bool operator==(interviu aux)
{
bool temp = strcmp(this->post, aux.post);
return temp;
}
friend ostream &operator<<(ostream &c4, interviu obj);
friend istream &operator>>(istream &c4, interviu &obj);
friend int operator+(int a, interviu b);
};
int interviu::timp_alocat = 30;
int interviu::nr_posturi = 0;
int operator+(int a, interviu b)
{
return a + b.get_salariu();
}
ostream &operator<<(ostream &c4, interviu obj)
{
c4 << "Informatii candidat: \n";
c4 << "Nume:" << obj.nume_candidat << "\n";
c4 << "Post:" << obj.post << "\n";
c4 << "Salariu job: " << obj.salariu << "\n";
c4 << "Note obtinute: " << obj.nota_1 << " " << obj.nota_2 << "\n";
c4 << "Rezultatul Candidatului : " << obj.rezultat;
return c4;
}
istream &operator>>(istream &c4, interviu &obj)
{
char aux[20];
cout << "Dati numele candidatului : "; c4 >> aux;
obj.nume_candidat = new char[strlen(aux) + 1];
strcpy(obj.nume_candidat, aux);
cout << "Postul: "; c4 >> aux;
obj.post = new char[strlen(aux) + 1];
strcpy(obj.post, aux);
cout << "Salariul: "; c4 >> obj.salariu;
cout << "Notele obtinute:"; c4 >> obj.nota_1 >> obj.nota_2;
return c4;
}
void main()
{
interviu candidat("Andrei Mihai", 1500, 8, 8.3, "casier", 30);
candidat.cand_rezultat();
candidat.afisare();
cout << "\n\n";
interviu candidat2;
candidat2.afisare();
interviu candidat3;
//Getter, setter
cout << candidat3.get_nume_cand() << "\n";
candidat3.set_nume_candidat("Popescu Marian");
cout << candidat3.get_nume_cand() << "\n";
candidat3.get_timp();
cout << interviu::get_timp() << "\n";
candidat3.set_timp(25);
cout << interviu::get_timp() << "\n";
candidat3.set_note(10, 9);
candidat3.cand_rezultat();
candidat3.afisare();
//Operatorii >> , <<
interviu candidat0;
cin >> candidat0;
candidat0.cand_rezultat();
cout << candidat0;
//Operatorul =
candidat3 = candidat;
candidat3.cand_rezultat();
candidat3.afisare();
//Operatorul ++
candidat3++;
candidat3.cand_rezultat();
candidat3.afisare();
interviu candidat4;
candidat4 = candidat3++;
candidat4.cand_rezultat();
candidat4.afisare();
//Operatorul +
interviu candidat5;
candidat5 = candidat5 + 120;
candidat5.cand_rezultat();
interviu a, b;
b = a + candidat5;
b.cand_rezultat();
b.afisare();
} | true |
0b10365e8db2c99d281a399572717bb5a229f3e7 | C++ | gomdorilla99/Nuyt | /Node.h | UTF-8 | 2,793 | 2.78125 | 3 | [] | no_license | #pragma once
#include <assert.h>
struct POINT
{
int x;
int y;
};
enum NodeType
{
NODE_TYPE_HOME,
NODE_TYPE_SINGLE,
NODE_TYPE_BRANCH,
NODE_TYPE_CROSS,
NODE_TYPE_READY,
NODE_TYPE_OUT,
NODE_TYPE_MAX
};
class Mal;
class Node
{
int mUpdateNum;
NodeType mType;
POINT mLocation;
Node* inputPort[2];
Node* outputPort[2];
Mal* mpCheckedMal;
public:
Node(enum NodeType type)
{
mType = type;
inputPort[0] = nullptr;
inputPort[1] = nullptr;
outputPort[0] = nullptr;
outputPort[1] = nullptr;
mLocation.x = 0;
mLocation.y = 0;
mUpdateNum = -1;
mpCheckedMal = nullptr;
}
Mal* GetCheckedMal()
{
return mpCheckedMal;
}
enum NodeType getType()
{
return mType;
}
void setLocation(int x, int y)
{
mLocation.x = x;
mLocation.y = y;
}
POINT getLocation()
{
return mLocation;
}
Node* addSingle()
{
Node* pNewNode = new Node(NODE_TYPE_SINGLE);
SetNextNode(pNewNode);
return pNewNode;
}
void setInputNode(Node* pNode)
{
if (!inputPort[0])
inputPort[0] = pNode;
else if (!inputPort[1])
inputPort[1] = pNode;
else
assert(pNode);
}
Node* SetNextNode(Node* pNode)
{
if (!outputPort[0])
outputPort[0] = pNode;
else if (!outputPort[1])
outputPort[1] = pNode;
else
assert(outputPort[1]);
pNode->setInputNode(this);
return pNode;
}
Node * passThrough(int Count, Node* pPreviousNode, Node* pStart)
{
Node* pNodeNext = nullptr;
if (mType == NODE_TYPE_BRANCH)
{
if (this == pStart)
{
if(outputPort[1])
pNodeNext = outputPort[1];
else
pNodeNext = outputPort[0];
}
else
{
pNodeNext = outputPort[0];
}
}
else if (mType == NODE_TYPE_CROSS)
{
if (this == pStart)
{
pNodeNext = outputPort[1];
}
else
{
if (pPreviousNode == inputPort[0])
{
pNodeNext = outputPort[0];
}
else if (pPreviousNode == inputPort[1])
{
pNodeNext = outputPort[1];
}
}
}
else if (mType == NODE_TYPE_HOME)
{
if (pStart != this)
{
pNodeNext = this;
return pNodeNext;
}
else
{
if (outputPort[0])
pNodeNext = outputPort[0];
else
assert(outputPort[0]);
}
}
else if (mType == NODE_TYPE_OUT)
{
return this;
}
else // NODE_TYPE_SINGLE
{
if (outputPort[0])
pNodeNext = outputPort[0];
else
{
pNodeNext = this;
// ASSERT(outputPort[0]);
}
}
if (pNodeNext && Count > 1)
{
return pNodeNext->passThrough(Count - 1, this, pStart);
}
return pNodeNext;
}
bool CheckIn(Mal* pMal);
bool CheckOut(Mal* pMal);
//void Draw(CDC* pDC, int UpdateNum);
};
| true |
6e8fc368bf8bc541083189ed77561f2378c11b33 | C++ | roche-emmanuel/nervOct | /sources/test_nervcuda/src/basics_spec.cpp | UTF-8 | 22,658 | 2.75 | 3 | [] | no_license | #include <boost/test/unit_test.hpp>
#include <iostream>
#include <nervcuda.h>
#include <windows.h>
#include <cuda_runtime.h>
#include <cuda_profiler_api.h>
#include <boost/chrono.hpp>
BOOST_AUTO_TEST_SUITE( basic_suite )
BOOST_AUTO_TEST_CASE( test_loading_module )
{
// For this test we try to load/unload the NervMBP library.
HMODULE h = LoadLibrary("nervCUDA.dll");
// The pointer should not be null:
BOOST_CHECK(h != nullptr);
// Should be able to free the library:
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_retrieving_mult_mat )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (* MultMatFunc)(unsigned int nrowA, unsigned int ncolA, const double * A,
unsigned int nrowB, unsigned int ncolB, const double * B, double * C, bool tpA, bool tpB);
// We should be able to retrieve the train function:
MultMatFunc mult_mat = (MultMatFunc) GetProcAddress(h, "matmult");
BOOST_CHECK(mult_mat != nullptr);
BOOST_CHECK(FreeLibrary(h));
}
int random_int(int mini, int maxi)
{
return mini + (int)floor(0.5 + (maxi - mini) * (double)rand() / (double)RAND_MAX);
}
double random_double(double mini, double maxi)
{
return mini + (maxi - mini) * (double)rand() / (double)RAND_MAX;
}
BOOST_AUTO_TEST_CASE( test_mult_mat )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (* MultMatFunc)(unsigned int nrowA, unsigned int ncolA, const double * A,
unsigned int nrowB, unsigned int ncolB, const double * B, double * C, bool tpA, bool tpB);
// We should be able to retrieve the train function:
MultMatFunc mult_mat = (MultMatFunc) GetProcAddress(h, "matmult");
BOOST_CHECK(mult_mat != nullptr);
// Now we use the mult mat method to compute a few matrices multiplication:
unsigned int num = 100; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
unsigned int nrowA = random_int(10, 100);
unsigned int ncolA = random_int(10, 100);
unsigned int nrowB = ncolA;
unsigned int ncolB = random_int(10, 100);
// prepare the matrix data:
unsigned int count = nrowA * ncolA;
double *ptr;
double *A = new double[count];
ptr = A;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = random_double(-10.0, 10.0);
}
count = nrowB * ncolB;
double *B = new double[count];
ptr = B;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = random_double(-10.0, 10.0);
}
count = nrowA * ncolB;
double *C = new double[count];
memset((void *)C, 0, sizeof(double)*count);
double *predC = new double[count];
for (unsigned int row = 0; row < nrowA; ++row)
{
for (unsigned int col = 0; col < ncolB; ++col)
{
// compute the value C(row,col):
double val = 0.0;
for (unsigned int n = 0; n < ncolA; ++n)
{
// val += A(row,n)*B(n,col);
val += A[n * nrowA + row] * B[col * nrowB + n];
}
predC[nrowA * col + row] = val;
}
}
// Now compute the value using the CUDA kernel:
// logDEBUG("Testing wih A: "<<nrowA<<" x "<<ncolA<<" and B: "<<nrowB<<" x "<<ncolB);
mult_mat(nrowA, ncolA, A, nrowB, ncolB, B, C, false, false);
// finally we need to compare the computed matrices value by value:
for (unsigned int row = 0; row < nrowA; ++row)
{
for (unsigned int col = 0; col < ncolB; ++col)
{
double v1 = C[nrowA * col + row];
double v2 = predC[nrowA * col + row];
BOOST_CHECK_MESSAGE(abs(v1 - v2) < 1e-10, "Mismatch at element (" << row << ", " << col << "): " << v1 << "!=" << v2);
}
}
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_mult_mat_tp_a )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (* MultMatFunc)(unsigned int nrowA, unsigned int ncolA, const double * A,
unsigned int nrowB, unsigned int ncolB, const double * B, double * C, bool tpA, bool tpB);
// We should be able to retrieve the train function:
MultMatFunc mult_mat = (MultMatFunc) GetProcAddress(h, "matmult");
BOOST_CHECK(mult_mat != nullptr);
// Now we use the mult mat method to compute a few matrices multiplication:
unsigned int num = 100; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
unsigned int nrowA = random_int(10, 100);
unsigned int ncolA = random_int(10, 100);
unsigned int nrowB = nrowA;
unsigned int ncolB = random_int(10, 100);
// prepare the matrix data:
unsigned int count = nrowA * ncolA;
double *ptr;
double *A = new double[count];
ptr = A;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = random_double(-10.0, 10.0);
}
count = nrowB * ncolB;
double *B = new double[count];
ptr = B;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = random_double(-10.0, 10.0);
}
count = ncolA * ncolB;
double *C = new double[count];
memset((void *)C, 0, sizeof(double)*count);
double *predC = new double[count];
for (unsigned int row = 0; row < ncolA; ++row)
{
for (unsigned int col = 0; col < ncolB; ++col)
{
// compute the value C(row,col):
double val = 0.0;
for (unsigned int n = 0; n < nrowA; ++n)
{
// val += A(row,n)*B(n,col);
val += A[row * nrowA + n] * B[col * nrowB + n];
}
predC[ncolA * col + row] = val;
}
}
// Now compute the value using the CUDA kernel:
// logDEBUG("Testing wih A: "<<nrowA<<" x "<<ncolA<<" and B: "<<nrowB<<" x "<<ncolB);
mult_mat(nrowA, ncolA, A, nrowB, ncolB, B, C, true, false);
// finally we need to compare the computed matrices value by value:
for (unsigned int row = 0; row < ncolA; ++row)
{
for (unsigned int col = 0; col < ncolB; ++col)
{
double v1 = C[ncolA * col + row];
double v2 = predC[ncolA * col + row];
BOOST_CHECK_MESSAGE(abs(v1 - v2) < 1e-10, "Mismatch at element (" << row << ", " << col << "): " << v1 << "!=" << v2);
}
}
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_mult_mat_tp_b )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (* MultMatFunc)(unsigned int nrowA, unsigned int ncolA, const double * A,
unsigned int nrowB, unsigned int ncolB, const double * B, double * C, bool tpA, bool tpB);
// We should be able to retrieve the train function:
MultMatFunc mult_mat = (MultMatFunc) GetProcAddress(h, "matmult");
BOOST_CHECK(mult_mat != nullptr);
// Now we use the mult mat method to compute a few matrices multiplication:
unsigned int num = 100; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
unsigned int nrowA = random_int(10, 100);
unsigned int ncolA = random_int(10, 100);
unsigned int nrowB = random_int(10, 100);
unsigned int ncolB = ncolA;
// prepare the matrix data:
unsigned int count = nrowA * ncolA;
double *ptr;
double *A = new double[count];
ptr = A;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = random_double(-10.0, 10.0);
}
count = nrowB * ncolB;
double *B = new double[count];
ptr = B;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = random_double(-10.0, 10.0);
}
count = nrowA * nrowB;
double *C = new double[count];
memset((void *)C, 0, sizeof(double)*count);
double *predC = new double[count];
for (unsigned int row = 0; row < nrowA; ++row)
{
for (unsigned int col = 0; col < nrowB; ++col)
{
// compute the value C(row,col):
double val = 0.0;
for (unsigned int n = 0; n < ncolA; ++n)
{
// val += A(row,n)*B(n,col);
val += A[n * nrowA + row] * B[n * nrowB + col];
}
predC[nrowA * col + row] = val;
}
}
// Now compute the value using the CUDA kernel:
// logDEBUG("Testing wih A: "<<nrowA<<" x "<<ncolA<<" and B: "<<nrowB<<" x "<<ncolB);
mult_mat(nrowA, ncolA, A, nrowB, ncolB, B, C, false, true);
// finally we need to compare the computed matrices value by value:
for (unsigned int row = 0; row < nrowA; ++row)
{
for (unsigned int col = 0; col < nrowB; ++col)
{
double v1 = C[nrowA * col + row];
double v2 = predC[nrowA * col + row];
BOOST_CHECK_MESSAGE(abs(v1 - v2) < 1e-10, "Mismatch at element (" << row << ", " << col << "): " << v1 << "!=" << v2);
}
}
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_mult_mat_performances )
{
cudaProfilerStart();
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (* MultMatFunc)(unsigned int nrowA, unsigned int ncolA, const double * A,
unsigned int nrowB, unsigned int ncolB, const double * B, double * C, bool tpA, bool tpB);
// We should be able to retrieve the train function:
MultMatFunc mult_mat = (MultMatFunc) GetProcAddress(h, "matmult");
BOOST_CHECK(mult_mat != nullptr);
unsigned int nrowA = 500;
unsigned int ncolA = 500;
unsigned int nrowB = ncolA;
unsigned int ncolB = 500;
// prepare the matrix data:
unsigned int count = nrowA * ncolA;
double *ptr;
double *A = new double[count];
ptr = A;
for (unsigned int j = 0; j < count; ++j)
{
// (*ptr++) = random_double(-10.0,10.0);
(*ptr++) = sin(j) * 10.0;
}
count = nrowB * ncolB;
double *B = new double[count];
ptr = B;
for (unsigned int j = 0; j < count; ++j)
{
// (*ptr++) = random_double(-10.0,10.0);
(*ptr++) = cos(j) * 10.0;
}
count = nrowA * ncolB;
double *C = new double[count];
memset((void *)C, 0, sizeof(double)*count);
double *predC = new double[count];
// Now we use the mult mat method to compute a few matrices multiplication:
unsigned int num = 10; // number of tests to perform.
// Compute the matrix on the CPU:
boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
for (unsigned int i = 0; i < num; ++i)
{
for (unsigned int row = 0; row < nrowA; ++row)
{
for (unsigned int col = 0; col < ncolB; ++col)
{
// compute the value C(row,col):
double val = 0.0;
for (unsigned int n = 0; n < ncolA; ++n)
{
// val += A(row,n)*B(n,col);
val += A[n * nrowA + row] * B[col * nrowB + n];
}
predC[nrowA * col + row] = val;
}
}
}
boost::chrono::duration<double> sec = boost::chrono::system_clock::now() - start;
logDEBUG("CPU matrix mult taking " << (sec.count() / num) << " seconds.");
// Compute the matrix onthe GPU:
start = boost::chrono::system_clock::now();
for (unsigned int i = 0; i < num; ++i)
{
mult_mat(nrowA, ncolA, A, nrowB, ncolB, B, C, false, false);
}
sec = boost::chrono::system_clock::now() - start;
logDEBUG("GPU matrix mult taking " << (sec.count() / num) << " seconds.");
BOOST_CHECK(FreeLibrary(h));
cudaProfilerStop();
}
BOOST_AUTO_TEST_CASE( test_reduction )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (*ReductionFunc)(double * inputs, unsigned int n, double & output);
// We should be able to retrieve the train function:
ReductionFunc reducfunc = (ReductionFunc) GetProcAddress(h, "reductionCPU");
BOOST_CHECK(reducfunc != nullptr);
unsigned int num = 10; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
// prepare the input data:
unsigned int size = random_int(50, 1000);
double *inputs = new double[size];
double sum = 0.0;
for (unsigned int j = 0; j < size; ++j)
{
double val = random_double(-10.0, 10.0);
sum += val;
inputs[j] = val;
}
// compute the reduction on the CPU:
double res = 0.0;
reducfunc(inputs, size, res);
BOOST_CHECK_MESSAGE(abs(sum - res) < 1e-10, "Mismatch for CPU reduction: " << sum << "!=" << res);
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_gpu_reduction )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (*ReductionFunc)(double * inputs, unsigned int n, double & output);
// We should be able to retrieve the train function:
ReductionFunc reducfunc = (ReductionFunc) GetProcAddress(h, "reduce_sum");
BOOST_CHECK(reducfunc != nullptr);
unsigned int num = 10; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
// prepare the input data:
unsigned int size = random_int(50, 1000);
double *inputs = new double[size];
double sum = 0.0;
for (unsigned int j = 0; j < size; ++j)
{
double val = random_double(-10.0, 10.0);
sum += val;
inputs[j] = val;
}
// compute the reduction on the GPU:
double res = 0.0;
reducfunc(inputs, size, res);
delete [] inputs;
BOOST_CHECK_MESSAGE(abs(sum - res) < 1e-10, "Mismatch for GPU reduction: " << sum << "!=" << res);
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_gpu_reduction_cost )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (*ReductionFunc)(double * hx, double * yy, unsigned int n, double & output);
// We should be able to retrieve the train function:
ReductionFunc reducfunc = (ReductionFunc) GetProcAddress(h, "reduce_cost");
BOOST_CHECK(reducfunc != nullptr);
unsigned int num = 10; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
// prepare the input data:
unsigned int size = random_int(50, 1000);
double *hx = new double[size];
double *yy = new double[size];
double sum = 0.0;
for (unsigned int j = 0; j < size; ++j)
{
double hval = random_double(0.01, 0.99);
double yval = random_double(0.01, 0.99);
hx[j] = hval;
yy[j] = yval;
sum -= (yval * log(hval) + (1.0 - yval) * log(1.0 - hval));
}
// compute the reduction on the GPU:
double res = 0.0;
reducfunc(hx, yy, size, res);
delete [] hx;
delete [] yy;
BOOST_CHECK_MESSAGE(abs(sum - res) < 1e-10, "Mismatch for GPU reduction_cost: " << sum << "!=" << res);
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_gpu_reduce_cost_reg )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (*ReductionFunc)(double * params, double * regweights, unsigned int n, double & output);
// We should be able to retrieve the train function:
ReductionFunc reducfunc = (ReductionFunc) GetProcAddress(h, "reduce_cost_reg");
BOOST_CHECK(reducfunc != nullptr);
unsigned int num = 10; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
// prepare the input data:
unsigned int size = random_int(50, 1000);
double *params = new double[size];
double *regw = new double[size];
double sum = 0.0;
for (unsigned int j = 0; j < size; ++j)
{
double val = random_double(-10.0, 10.0);
regw[j] = (j % 3) == 0 ? 0.0 : 1.0;
params[j] = val;
sum += val * val * regw[j];
}
// compute the reduction on the GPU:
double res = 0.0;
reducfunc(params, regw, size, res);
delete [] params;
delete [] regw;
BOOST_CHECK_MESSAGE(abs(sum - res) < 1e-10, "Mismatch for GPU reduce_cost_reg: " << sum << "!=" << res);
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_CASE( test_cost_function )
{
HMODULE h = LoadLibrary("nervCUDA.dll");
BOOST_CHECK(h != nullptr);
typedef void (*CostFunc)(unsigned int nl, unsigned int *lsizes, unsigned int nsamples,
double * nn_params, double * X, double * yy, double lambda, double & J, double * gradients, double * deltas, double * inputs);
typedef void (*CostFuncCPU)(unsigned int nl, unsigned int *lsizes, unsigned int nsamples,
double * nn_params, double * X, double * yy, double lambda, double * activation, unsigned int ninputs, double * inputs, double & J, double * gradients, double * deltas);
// We should be able to retrieve the train function:
CostFunc costfunc = (CostFunc) GetProcAddress(h, "costFunc");
BOOST_CHECK(costfunc != nullptr);
CostFuncCPU costfunc_cpu = (CostFuncCPU) GetProcAddress(h, "costFuncCPU");
BOOST_CHECK(costfunc_cpu != nullptr);
// Now we use the mult mat method to compute a few matrices multiplication:
unsigned int num = 10; // number of tests to perform.
for (unsigned int i = 0; i < num; ++i)
{
// prepare number of samples:
unsigned int nsamples = random_int(500, 1000);
// Prepare the layer size vector:
unsigned int nl = random_int(3, 5);
unsigned int nt = nl - 1;
// logDEBUG("Num samples: "<<nsamples<<", num layers: "<<nl);
unsigned int *lsizes = new unsigned int[nl];
for (unsigned int j = 0; j < nl; ++j)
{
lsizes[j] = random_int(3, 6);
}
// prepare the X matrix data:
unsigned int count = nsamples * lsizes[0];
double *ptr;
double *X = new double[count];
ptr = X;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = sin(j) * 10.0;
// (*ptr++) = random_double(-10.0,10.0);
}
// Prepare the Xt matrix:
double *Xt = new double[count];
unsigned int nf = lsizes[0];
for (unsigned int r = 0; r < nsamples; ++r)
{
for (unsigned int c = 0; c < nf; ++c)
{
Xt[nf*r+c] = X[nsamples*c+r];
}
}
// Prepare the yy matrix:
count = nsamples * lsizes[nl - 1];
double *yy = new double[count];
ptr = yy;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = cos(j) * 10.0;
// (*ptr++) = random_double(-10.0,10.0);
}
// Prepare the current weights matrices:
count = 0;
for (unsigned j = 0; j < nt; ++j)
{
count += lsizes[j + 1] * (lsizes[j] + 1);
}
unsigned int np = count;
// logDEBUG("Allocating "<<count<<" bytes...")
double *params = new double[count];
ptr = params;
for (unsigned int j = 0; j < count; ++j)
{
(*ptr++) = sin(j + 0.5);
}
// prepare the output gradient array:
double *grads = new double[count];
memset(grads, 0, sizeof(double)*count);
double *pred_grads = new double[count];
memset(pred_grads, 0, sizeof(double)*count);
// prepare the lambda value:
double lambda = random_double(0.0, 1.0);
// Prepare the activation array:
unsigned int act_size = 0;
for (unsigned int j = 0; j < nl; ++j)
{
act_size += lsizes[j] + 1;
}
act_size *= nsamples;
double *activation = new double[act_size];
memset(activation, 0, sizeof(double)*act_size);
// Prepare the input array:
unsigned int input_size = 0;
for (unsigned int j = 0; j < nt; ++j)
{
input_size += lsizes[j + 1];
}
input_size *= nsamples;
double *inputs = new double[input_size];
memset(inputs, 0, sizeof(double)*input_size);
// Now we should manually compute the activation/input values:
double *pred_act = new double[act_size];
double *pred_input = new double[input_size];
memset(pred_act, 0, sizeof(double)*act_size);
memset(pred_input, 0, sizeof(double)*input_size);
// also prepare an array to hold the predictions for the delta matrices:
unsigned int nd = 0;
for (unsigned int i = 1; i < nl; ++i)
{
nd += lsizes[i] * nsamples;
}
double *deltas = new double[nd];
memset(deltas, 0, sizeof(double)*nd);
double *pred_deltas = new double[nd];
memset(pred_deltas, 0, sizeof(double)*nd);
cudaDeviceSynchronize();
// Now we call the cost function method:
double J = 0.0;
costfunc(nl, lsizes, nsamples, params, Xt, yy, lambda, J, grads, deltas, inputs);
// And we call the same on the CPU:
double pred_J = 0.0;
costfunc_cpu(nl, lsizes, nsamples, params, X, yy, lambda, pred_act, input_size, pred_input, pred_J, pred_grads, pred_deltas);
BOOST_CHECK_MESSAGE(abs(J - pred_J) < 1e-10, "Mismatch in J value: " << J << "!=" << pred_J);
// Also compare the delta arrays:
for (unsigned int j = 0; j < nd; ++j)
{
double v1 = deltas[j];
double v2 = pred_deltas[j];
BOOST_CHECK_MESSAGE(abs(v1 - v2) < 1e-10, "Mismatch on deltas element " << j << ": " << v1 << "!=" << v2);
}
// Compare the grads arrays:
// logDEBUG("Number of parameters: "<<np);
for (unsigned int j = 0; j < np; ++j)
{
double v1 = grads[j];
double v2 = pred_grads[j];
BOOST_CHECK_MESSAGE(abs(v1 - v2) < 1e-10, "Mismatch on gradient element " << j << ": " << v1 << "!=" << v2);
}
// Compare the content of the activation array:
// This doesn't make sense anymore since we do not compute activation matrices anymore
// (duplicate of input matrices)
// for(unsigned int j=0;j<act_size;++j) {
// double v1 = activation[j];
// double v2 = pred_act[j];
// BOOST_CHECK_MESSAGE(abs(v1-v2)<1e-10,"Mismatch on activation element "<<j<<": "<<v1<<"!="<<v2);
// }
// Compare the content of the input array:
for (unsigned int j = 0; j < input_size; ++j)
{
double v1 = inputs[j];
double v2 = pred_input[j];
BOOST_CHECK_MESSAGE(abs(v1 - v2) < 1e-10, "Mismatch on inputs element " << j << ": " << v1 << "!=" << v2);
}
delete [] lsizes;
delete [] X;
delete [] Xt;
delete [] yy;
delete [] params;
delete [] activation;
delete [] inputs;
delete [] grads;
delete [] deltas;
delete [] pred_act;
delete [] pred_input;
delete [] pred_deltas;
delete [] pred_grads;
}
BOOST_CHECK(FreeLibrary(h));
}
BOOST_AUTO_TEST_SUITE_END()
| true |
12b71864b10386b6a25829b0af3562fa0813b0dc | C++ | ibiscum/fast_ber | /test/ber_types/TaggedType.cpp | UTF-8 | 1,494 | 2.859375 | 3 | [
"BSL-1.0"
] | permissive | #include "fast_ber/ber_types/All.hpp"
#include "fast_ber/ber_types/Identifier.hpp"
#include "fast_ber/ber_types/Integer.hpp"
#include <catch2/catch.hpp>
#include <array>
TEST_CASE("TaggedType: Assign")
{
using Tag = fast_ber::Id<fast_ber::Class::universal, fast_ber::Tag(5)>;
using TaggedInt = fast_ber::Integer<Tag>;
fast_ber::Integer<> a(4);
TaggedInt b = a;
REQUIRE(b == 4);
REQUIRE(fast_ber::Identifier<TaggedInt>::tag() == 5);
static_assert(std::is_same<fast_ber::Identifier<TaggedInt>, Tag>::value, "Double Tagged Identifier");
}
TEST_CASE("TaggedType: Encode Decode")
{
fast_ber::Integer<fast_ber::Id<fast_ber::Class::universal, fast_ber::Tag(5)>> a = 10;
fast_ber::Integer<fast_ber::Id<fast_ber::Class::universal, fast_ber::Tag(5)>> b = 20;
std::array<uint8_t, 100> buffer = {};
fast_ber::encode(absl::Span<uint8_t>(buffer), a);
fast_ber::decode(absl::Span<const uint8_t>(buffer), b);
REQUIRE(b == 10);
}
TEST_CASE("TaggedType: Tagged Enum")
{
enum class TestEnumValues
{
option_one,
option_two,
option_three
};
using TestEnum = fast_ber::Enumerated<TestEnumValues, fast_ber::ExplicitId<fast_ber::UniversalTag::octet_string>>;
static_assert(
std::is_same<fast_ber::Identifier<TestEnum>, fast_ber::ExplicitId<fast_ber::UniversalTag::octet_string>>::value,
"Tagged Enum Identifier");
}
| true |
748249d8b080d7b018753a3539c41c7a455e4f70 | C++ | Eplistical/1d_rate_double_well | /include/para/para.hpp | UTF-8 | 878 | 2.703125 | 3 | [] | no_license | #ifndef _PARA_HPP
#define _PARA_HPP
#include <cstdlib>
#include <string>
#include "ioer.hpp"
namespace
{
using std::string;
using ioer::keyval;
using ioer::input_t;
using ioer::output_t;
using ioer::STDOUT;
struct Para
{
int M;
int Ne;
double W;
Para() = default;
Para(const string& fname) {
loadpara(fname);
}
void loadpara(const string& fname) {
input_t inp(fname);
inp.extract_para("M", M);
inp.extract_para("Ne", Ne);
inp.extract_para("W", W);
inp.read_text();
inp.close();
}
void showpara(output_t& outp=STDOUT)
{
outp.tabout("#", " M", M);
outp.tabout("#", " Ne", Ne);
outp.tabout("#", " W", W);
}
};
#endif // _PARA_HPP
| true |
469f7a35411b365b0608e82312f825e1b503411e | C++ | mirtaba/ACMICPC-INOI_Archive | /Olympiad Programs/SGU 397. Text Editor (2).cpp | UTF-8 | 844 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cmath>
using namespace std;
const int MAX = 100*100*100 + 25;
string s;
char p[MAX];
int f=1,la=1;
struct node
{
char ch;
int r,l;
node()
{
r = l = -1 ;
}
node(int i, int p)
{
r=i;
l=p;
}
} n[MAX];
int r=0,l=0;
int main()
{
ios::sync_with_stdio (false);
cin >> s;
int wh=1;
int kof=0;
for (int i=0;i<(s.length());i++)
{
if (s[i]=='L'&& n[wh].l != -1)
wh = (n[la].l);
if (s[i]=='R'&& n[wh].r != -1)
wh = (n[la].r);
if (s[i] != 'L' && s[i] != 'R')
{
n[la].ch = s[i];
if (n[kof].l!=-1)
{
n[n[kof].l].r=la;
n[la].l=n[kof].l;
}
n[la].r=kof;
n[kof].l=(la);
la++;
}
}
for (int i=0;i<=MAX-1;i++)
p[i]=' ';
//cout << char (n[1].ch);
int tt=0;
for (int i=0; i != -1;i = n[i].l)
p[tt]=(n[i].ch);
tt++;
for (int i=0;i<=tt;i++)
cout << p[i];
}
| true |
fcfd42770ca38c46038802e75d43107525481323 | C++ | Voley/Algorithmic-Problems | /Math/Toeplitz/main.cpp | UTF-8 | 415 | 3.03125 | 3 | [
"MIT"
] | permissive |
#include <iostream>
#include <vector>
bool isToeplitzMatrix(std::vector<std::vector<int>>& matrix) {
auto width = matrix[0].size();
auto height = matrix.size();
for (int i = 1; i < height; i++) {
for (int j = 1; j < width; j++) {
if (matrix[i][j] != matrix[i-1][j-1]) {
return false;
}
}
}
return true;
}
int main() {
return 0;
}
| true |
749fbc1b3430c1baa62e9b036fdc280171246897 | C++ | plazmist/Cellular | /conway.h | UTF-8 | 3,084 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Conway
{
private:
int **Field, **FieldOld;
int FieldSize;
int breed = 1;
int cntNghbr(int i, int j){
int cnt=0;
int left = (j == 0) ? FieldSize-1 : j-1;
int right = (j == FieldSize-1) ? 0 : j+1;
int upper = (i == 0) ? FieldSize-1 : i-1;
int bootom = (i == FieldSize-1) ? 0 : i+1;
if (FieldOld[upper][left] == breed) ++cnt;
if (FieldOld[upper][j] == breed) ++cnt;
if (FieldOld[upper][right] == breed) ++cnt;
if (FieldOld[i][left] == breed) ++cnt;
if (FieldOld[i][right] == breed) ++cnt;
if (FieldOld[bootom][left] == breed) ++cnt;
if (FieldOld[bootom][j] == breed) ++cnt;
if (FieldOld[bootom][right] == breed) ++cnt;
return cnt;
}
public:
Conway(int N, int varBreed = 1){
FieldSize = N;
breed = varBreed;
Field = new int*[N];
FieldOld = new int*[N];
for(int i = 0; i < N; ++i)
Field[i] = new int[N];
for(int i = 0; i < N; ++i)
FieldOld[i] = new int[N];
printf("Base Fields[N][N] constructed...\n");
}
virtual ~Conway(){
for(int i = 0; i < FieldSize; ++i)
delete [] Field[i];
for(int i = 0; i < FieldSize; ++i)
delete [] FieldOld[i];
delete [] Field;
delete [] FieldOld;
}
void FieldFillRand(float rate){
srand (time(NULL));
for (int i = 1; i < FieldSize-1; ++i) {
printf("\n");
for (int j = 1; j < FieldSize-1; ++j)
{
if (rand() % 2) Field[i][j] = breed;
printf("%d ",Field[i][j]);
}
}
printf("Random Fill finished...\n");
}
void addGlider(int shift_x = 0, int shift_y = 0, int direction = 0){
if (direction == 0) direction = rand()%4 + 1;
switch (direction) {
case 1 : Field[1+shift_x][2+shift_y]=Field[2+shift_x][3+shift_y]=Field[3+shift_x][1+shift_y]=Field[3+shift_x][2+shift_y]=Field[3+shift_x][3+shift_y]=breed; break;
case 2 : Field[1+shift_x][2+shift_y]=Field[1+shift_x][3+shift_y]=Field[2+shift_x][1+shift_y]=Field[2+shift_x][3+shift_y]=Field[3+shift_x][3+shift_y]=breed; break;
case 3 : Field[1+shift_x][1+shift_y]=Field[1+shift_x][2+shift_y]=Field[1+shift_x][3+shift_y]=Field[2+shift_x][1+shift_y]=Field[3+shift_x][2+shift_y]=breed; break;
case 4 : Field[1+shift_x][1+shift_y]=Field[2+shift_x][1+shift_y]=Field[2+shift_x][3+shift_y]=Field[3+shift_x][1+shift_y]=Field[3+shift_x][2+shift_y]=breed; break;
}
printf("Glider %d added on [%d][%d]\n",direction,shift_x,shift_y);
}
int Step(){
int alive=0;
for (int i = 0; i < FieldSize; ++i)
for (int j = 0; j < FieldSize; ++j){
FieldOld[i][j] = Field[i][j];
//Field[i][j] = 0;
}
short cur_cntNghbr;
for (int i = 0; i < FieldSize; ++i)
for (int j = 0; j < FieldSize; ++j){
cur_cntNghbr=cntNghbr(i,j);
if (cur_cntNghbr == 3) {Field[i][j] = breed; ++alive;}
else if ((cur_cntNghbr == 2) && (FieldOld[i][j] == breed)) {Field[i][j] = breed; ++alive;}
else if (Field[i][j] > 0) --Field[i][j];
}
return alive;
}
int Cell(int x, int y){
return Field[x][y];
}
};
| true |
a4ad69f1bf2b7ca9a7fd4afab9326751ebe214c2 | C++ | rhayatin/C-- | /JAVAC.cpp | UTF-8 | 915 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
char str[105];
while(scanf("%s",&str)>0)
{
int flag=0,flag1=0;;
int n=strlen(str);
for(int i=0;i<n;i++)
if(str[i]!=tolower(str[i]))
flag1=1;
if(str[0]!=tolower(str[0]))
cout<<"Error!";
else if(str[0]=='_')
cout<<"Error!";
else if(str[n-1]=='_')
cout<<"Error!";
else
{
if(flag1==0)
{
for(int i=0;i<n;i++)
{
if(str[i]=='_')
continue;
if(str[i-1]!='_')
cout<<str[i];
else
cout<<char(str[i]+'A'-'a');
}
}
else
{
for(int i=0;i<n;i++)
{
if(str[i]=='_')
{
flag=1;
break;
}
}
if(flag==1)
cout<<"Error!";
else
{
for(int i=0;i<n;i++)
if(str[i]==tolower(str[i]))
cout<<str[i];
else
cout<<"_"<<char(tolower(str[i]));
}
}
}
cout<<"\n";
}
}
| true |
2db07a39a9ee171cb5505e85fb55f5659c402b88 | C++ | satvikb/InteractiveContentFileFormat | /UI/Content/cButton.cpp | UTF-8 | 2,625 | 2.6875 | 3 | [] | no_license | #include "cButton.h"
cButton::cButton(cContainer* parent, struct Content* content, struct Style* style) : cStyledPanel((wxWindow*)parent, style, wxID_ANY) {
SetContent(content);
w = -1;
h = -1;
}
void cButton::interpretContent() {
if (content->data.size() > 0) {
std::vector<uint8_t> bytes = content->data;
int i = 0;
std::pair<uint8_t, uint32_t> actionID = readChunkTypeAndID((char*)&bytes[0], &i);
// TODO confirm if chunk type is action?
this->actionID = actionID.second;
// start with the key value pairs
while (bytes[i] != 0x0) {
uint8_t key = (unsigned char)bytes[i];
switch (key) {
case BUTTON_DEFAULT_STYLE: case BUTTON_HOVER_STYLE: case BUTTON_CLICK_STYLE:
{
std::pair<uint8_t, uint32_t> styleID = readChunkTypeAndID((char*)&bytes[0], &i);
struct Style* _style = FileManager::getStyleByID(styleID.second);
if (_style != nullptr) {
if (key == BUTTON_DEFAULT_STYLE) {
this->defaultStyle = _style;
} else if (key == BUTTON_HOVER_STYLE) {
this->hoverStyle = _style;
} else if (key == BUTTON_CLICK_STYLE) {
this->clickStyle = _style;
}
}
}
break;
default:
// unknown key, skip the rest
goto finish_interpret;
break;
}
}
finish_interpret:;
}
}
void cButton::ApplyContentStyle(struct Style* style) {
if (style != nullptr) {
}
}
void cButton::RenderContent(wxDC& dc) {
std::vector<uint8_t> bytes = content->data;
int numBytes = bytes.size();
if (numBytes > 0) {
int i = 0;
}
}
/*
* Here we call refresh to tell the panel to draw itself again.
* So when the user resizes the image panel the image should be resized too.
*/
void cButton::OnSize(wxSizeEvent& event) {
Refresh();
//skip the event.
event.Skip();
}
void cButton::mouseDown(wxMouseEvent& event) {
ApplyContentStyle(this->clickStyle);
}
void cButton::mouseReleased(wxMouseEvent& event) {
ApplyContentStyle(this->defaultStyle);
WindowManager::ExecuteActionID(this->actionID);
}
void cButton::windowEnter(wxMouseEvent& event) {
ApplyContentStyle(this->hoverStyle);
}
void cButton::windowLeave(wxMouseEvent& event) {
ApplyContentStyle(this->defaultStyle);
}
cButton::~cButton() {
} | true |
10c62cb2286cc8a32c1126e3ef1d13cf85c75e3d | C++ | MirkoFerrati/Ascari | /plugins/monitor/dummy_agent.hpp | UTF-8 | 1,332 | 2.703125 | 3 | [] | no_license | #ifndef DUMMY_AGENT_HPP
#define DUMMY_AGENT_HPP
#include <stdio.h>
#include <mutex>
#include "agent_to_dummy_communicator.hpp"
#include "../agent/agent.h"
#include <types/dummy_state.h>
#include <string>
struct dummy_agent
{
dummy_agent(std::string agent_name,const std::pair<const std::string, std::unique_ptr<Parsed_Behavior>>& behavior,int behavior_id,
const Parsed_World & world,std::shared_ptr<agent_namespace::world_communicator_abstract > communicator, const agent_state & ref_state)
:dummy(agent_name,behavior.second,world),behavior_identifier(behavior_id),identifier(agent_name)
{
//char temp[5];
//snprintf(temp,5,"%d",behavior_id);
identifier.append(std::to_string(behavior_id));
dummy.setCommunicator(communicator);
dummy.setControlCommandIdentifier(identifier);
dummy_state tmp;
for (auto dstate = dummy.getDiscreteStates().begin(); dstate != dummy.getDiscreteStates().end(); ++dstate) {
tmp.automatonState=*dstate;
tmp.state=ref_state;
states.push_front(tmp);
}
}
public:
agent dummy;
int behavior_identifier;
std::forward_list<dummy_state> states;
std::string identifier;
std::mutex comm_mutex;
inline std::forward_list<dummy_state> & getDummyStates() {
return states;
}
};
#endif //DUMMY_AGENT_HPP | true |
7e6b8a1e36924108fcf1858822aba537322736d7 | C++ | kartikdutt18/CPP-and-its-Algo-based-Problems | /To-Be-Restructured/Competitive/Berry_Jam.cpp | UTF-8 | 2,256 | 3 | 3 | [] | no_license | //
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int balance(vector<int> v){
int midLeft=v.size()/2-1;
int midRight=v.size()/2;
int berry=0;
int jam=0;
int berrymidLeft=0;
int berrymidRight=0;
int jammidLeft=0;
int jammidRight=0;
for(int i=0;i<v.size();i++){
if(i<v.size()/2){
if (v[i] == 1)
berrymidLeft++;
else
jammidLeft++;
}
else{
if (v[i] == 1)
berrymidRight++;
else
jammidRight++;
}
}
berry=berrymidLeft+berrymidRight;
jam=jammidLeft+jammidRight;
while(berry!=jam){
if(berry>jam){
if(berrymidLeft>berrymidRight && midLeft>0){
if(v[midLeft]==1){
berrymidLeft--;
midLeft--;
}
else{
jammidLeft--;
midLeft--;
}
}
else{
if(v[midRight]==1){
berrymidRight--;
midRight++;
}
else{
jammidRight--;
midRight++;
}
}
}
else{
if(jammidLeft>jammidRight && midLeft>0){
if (v[midLeft] == 1)
{
berrymidLeft--;
midLeft--;
}
else
{
jammidLeft--;
midLeft--;
}
}
else{
if (v[midRight] == 1)
{
berrymidRight--;
midRight++;
}
else
{
jammidRight--;
midRight++;
}
}
}
berry = berrymidLeft + berrymidRight;
jam = jammidLeft + jammidRight;
}
return v.size()-berry-jam;
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> v(n,0);
for(int i=0;i<n;i++)cin>>v[i];
cout<<balance(v)<<endl;
}
return 0;
} | true |
132945f42b7c3195bda4f7e96e9995825354019e | C++ | EnTaroYan/ExcelProgress | /ExcelProgress/ExcelProgress.cpp | GB18030 | 2,994 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include "libxl.h"
#include <algorithm>
#define COL_BARCODE 2
#define COL_NAME 3
#define COL_ID 4
#define COL_UNIT 8
#define COL_POSITION 16
#define COL_NUMBER 11
using namespace libxl;
using namespace std;
typedef struct Goods
{
public:
string barcode;
long id;
string name;
string unit;
string position;
int num;
}Goods;
bool SortByName(Goods m, Goods n)
{
if (m.name < n.name)
return true;
else
return false;
}
bool SortByPos(Goods m, Goods n)
{
if (m.position < n.position)
return true;
else
return false;
}
int main()
{
cout << "ʼ !!!" << endl;
Book* book = xlCreateXMLBook();
vector<Goods> goodsList;
if (book)
{
const char * x = "Halil Kural";
const char * y = "windows-2723210a07c4e90162b26966a8jcdboe";
book->setKey(x, y);
if (book->load("../1.xlsx"))
{
Sheet* sheet = book->getSheet(0);
if (sheet)
{
int row = 0;
int col = 0;
int rowNums = sheet->lastRow();
int colNums = sheet->lastCol();
//ȡ
for (int i = 1; i<rowNums; ++i)
{
Goods temp;
if(sheet->cellType(i, COL_BARCODE)!= CELLTYPE_EMPTY)
temp.barcode = sheet->readStr(i, COL_BARCODE);
temp.id = sheet->readNum(i, COL_ID);
temp.name = sheet->readStr(i, COL_NAME);
temp.position = sheet->readStr(i, COL_POSITION);
temp.unit = sheet->readStr(i, COL_UNIT);
temp.num = sheet->readNum(i, COL_NUMBER);
goodsList.push_back(temp);
}
//
sort(goodsList.begin(), goodsList.end(), SortByName);
for (vector<Goods>::iterator iter = goodsList.begin() + 1; iter != goodsList.end(); ++iter)
{
if (iter->name == (iter - 1)->name)
{
(iter - 1)->num += iter->num;
iter = goodsList.erase(iter) - 1;
}
}
sort(goodsList.begin(), goodsList.end(), SortByPos);
sheet->clear(0, rowNums,0, colNums);
//
sheet->writeStr(0, 0, "Ʒ");
sheet->writeStr(0, 1, "Ʒ");
sheet->writeStr(0, 2, "Ʒλ");
sheet->writeStr(0, 3, "ƷID");
sheet->writeStr(0, 4, "λ");
sheet->writeStr(0, 5, "");
for (int i = 1; i < goodsList.size()+1; ++i)
{
sheet->writeStr(i, 0, (goodsList[i - 1].barcode).c_str());
sheet->writeStr(i, 1, (goodsList[i - 1].name).c_str());
sheet->writeStr(i, 2, (goodsList[i - 1].unit).c_str());
sheet->writeNum(i, 3, (goodsList[i - 1].id));
sheet->writeStr(i, 4, (goodsList[i - 1].position).c_str());
sheet->writeNum(i, 5, (goodsList[i - 1].num));
}
}
if (book->save("../1.xlsx"))
{
cout << "" << endl; cout << "" << endl;
::ShellExecute(NULL, "open", "../1.xlsx", NULL, NULL, SW_SHOW);
}
else
{
cout << book->errorMessage() << endl;
}
}
else
{
cout << "Ҳļ !" << endl;
while (1);
}
book->release();
}
return 0;
} | true |
175f8f2d2120cc145672ea21b86a6c1023f41bdb | C++ | agmt/ngram | /finder.cpp | UTF-8 | 3,341 | 2.515625 | 3 | [
"Unlicense"
] | permissive | #include <stdio.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <ios>
#include <random>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <algorithm>
#define TRY(x) \
do { \
ssize_t __rc = (ssize_t)(x); \
if( __rc < 0 ) { \
fprintf(stderr, "ERROR: TRY(%s) failed\n", #x); \
fprintf(stderr, "ERROR: at %s:%d\n", __FILE__, __LINE__); \
fprintf(stderr, "ERROR: rc=%d errno=%d (%s)\n", \
(int)__rc, errno, strerror(errno)); \
exit(1); \
} \
} while( 0 )
char rdbuf[1024];
uint64_t left, right, mid;
struct timespec ts1, ts2;
static inline int64_t time_delta(const struct timespec &t1, const struct timespec &t2)
{
return ((int64_t)(t2.tv_sec - t1.tv_sec))*1000000000LL + t2.tv_nsec-t1.tv_nsec;
}
static inline unsigned long time_delta(const unsigned long t1, const unsigned long t2)
{
return ((t2-t1));
}
__attribute__((noinline)) void preCache()
{
const int count = 65536;
volatile char *vngrams = ngrams;
register char a;
for(size_t i = 0; i < count; i++)
{
size_t pos = ngrams_size*i/count;
a = vngrams[pos];
}
(void)a;
}
struct TextFile
{
size_t ngrams_size;
char *ngrams;
int fd;
TextFile(char *name)
{
fd = open("gensorted3grams.txt", O_RDONLY|O_LARGEFILE);
TRY(fd);
ngrams_size = lseek(fd, 0, SEEK_END);
ngrams = (char*)mmap(0, ngrams_size, PROT_READ, MAP_SHARED, fd, 0);
TRY(ngrams);
TRY(madvise(ngrams, ngrams_size, MADV_RANDOM));
preCache();
}
~TextFile()
{
TRY(munmap(ngrams, ngrams_size));
TRY(close(fd));
}
};
uint64_t getLineBegin(uint64_t p)
{
for(;;)
{
if(p == 0)
return p;
if(ngrams[p] == '\n')
return p + 1;
p--;
}
}
int main()
{
int count;
for(;;)
{
printf("Input your words: ");
fgets(rdbuf, sizeof(rdbuf), stdin);
if((rdbuf[0] == 0) || (rdbuf[0] == '\n'))
break;
rdbuf[strlen(rdbuf)-1] = 0;
left = 0;
right = ngrams_size-1;
count = 0;
size_t rdbuf_len = strlen(rdbuf);
clock_gettime(CLOCK_MONOTONIC, &ts1);
for(;;)
{
count++;
mid = getLineBegin((left+right)/2);
if(left == mid)
break;
int res = memcmp(&ngrams[mid], rdbuf, rdbuf_len);
if(res == 0)
break;
if(res > 0)
right = mid;
if(res < 0)
left = mid;
}
clock_gettime(CLOCK_MONOTONIC, &ts2);
printf("Found c=%d time=%ld off=%lu line=%40.40s\n", count, time_delta(ts1, ts2), mid, &ngrams[mid]);
}
printf("See u\n");
return 0;
}
| true |
c7f8a4d85fac84072582578dfe2bc8b15753d2bc | C++ | changgezuo/leetcode | /1456/1456.cpp | UTF-8 | 911 | 2.984375 | 3 | [] | no_license | #include<string>
#include<unordered_set>
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
int maxVowels(string s, int k) {
unordered_set<char>dic;
for(char c : vowels)dic.insert(c);
int l = 0, r = k;
int res = 0, curCnt = 0;
for(int i = 0; i < k; ++i){
if (dic.count(s[i]))curCnt++;
}
res = curCnt;
while (r < s.size()){
if(dic.count(s[r])){
}
}
}
private:
vector<char>vowels{'a', 'e', 'i', 'o', 'u'};
};
auto main () ->int{
string str1 = "hello world";
string str2 = str1;
printf ("Sharing the memory:/n");
printf ("/tstr1's address: %x/n", str1.c_str() );
printf ("/tstr2's address: %x/n", str2.c_str() );
str1[1]='q';
str2[1]='w';
printf ("After Copy-On-Write:/n");
printf ("/tstr1's address: %x/n", str1.c_str() );
printf ("/tstr2's address: %x/n", str2.c_str() );
return 0;
} | true |
e40ac36e366c420e186b7f9bd5350ca0464647b2 | C++ | DaniPreto/CG | /Ponto.h | UTF-8 | 441 | 2.78125 | 3 | [] | no_license |
#ifndef PONTO_H
#define PONTO_H
#include <iostream>
#include <vector>
#include "ObjGrafico.h"
#include<string>
class Ponto : public ObjGrafico {
public:
Ponto();
Ponto(const Ponto& orig);
virtual ~Ponto();
Ponto(double a, double b);
Ponto(double a, double b,std::string n);
Ponto(std::string n,Coordenada c){nome = n;tipo = 0;addCoordenada(c);}
};
#endif
| true |
90c9f2e2cfcc7523066885d26e9e2e34ae7cd6e6 | C++ | dastyk/Radiant | /Radiant/Radiant/RandomBlink.cpp | UTF-8 | 2,708 | 2.71875 | 3 | [] | no_license | #include "RandomBlink.h"
#include "System.h"
RandomBlink::RandomBlink(EntityBuilder* builder, Entity player, vector<FreePositions> positions) : Power(builder)
{
_type = power_id_t::RANDOMBLINK;
_timeSinceLastActivation = 100;
_cooldown = 5.0;
_lightIntensity = 0.0f;
_powerLevel = 0;
_powerEntity = _builder->EntityC().Create();
_builder->Transform()->CreateTransform(_powerEntity);
_builder->Bounding()->CreateBoundingSphere(_powerEntity, 0.05f);
_builder->Light()->BindPointLight(_powerEntity, XMFLOAT3(0, 0, 0), 8.0f, XMFLOAT3(1.0f, 1.0f, 1.0f), _lightIntensity);
_builder->Transform()->BindChild(player, _powerEntity);
viablePositions = positions;
_loading = false;
_powerName = "Random Blink";
_description = "Escape your enemies by quickly teleporting to a random location in the temple. Use it wisely or you might go out of the ashes and into the fire.";
_decalTexture = "Assets/Textures/PowerRandomBlink.png";
}
RandomBlink::~RandomBlink()
{
_builder->GetEntityController()->ReleaseEntity(_powerEntity);
}
void RandomBlink::Update(Entity playerEntity, float deltaTime)
{
_timeSinceLastActivation += deltaTime;
if (_loading)
{
_lightIntensity += deltaTime * 80;
_builder->Light()->ChangeLightIntensity(_powerEntity, _lightIntensity);
}
else
{
_lightIntensity -= deltaTime * 80;
if (_lightIntensity < 0.0f)
_lightIntensity = 0.0f;
_builder->Light()->ChangeLightIntensity(_powerEntity, _lightIntensity);
}
if (_loading && _lightIntensity >= MAXLIGHTINTENSITY)
{
_loading = false;
int randValue = rand() % viablePositions.size();
XMFLOAT3 temp;
XMStoreFloat3(&temp, _builder->Transform()->GetPosition(playerEntity));
temp.x = (float)viablePositions[randValue].x;
temp.z = (float)viablePositions[randValue].y;
_builder->Transform()->SetPosition(playerEntity, temp);
System::GetAudio()->PlaySoundEffect(L"teleport.wav", 0.5f);
}
}
float RandomBlink::Activate(bool& exec, float currentLight)
{
if (_cooldown - _timeSinceLastActivation <= 0.0f && currentLight >= 2.0f)
{
_timeSinceLastActivation = 0.0f;
_loading = true;
exec = true;
return 2.0f;
}
exec = false;
return 0.0f;
}
bool RandomBlink::Upgrade()
{
if (_powerLevel <= 5)
{
_cooldown -= 0.5f;
_powerLevel++;
return true;
}
return false;
}
//std::string RandomBlink::GetDescription(int textWidth) const
//{
// std::string spacing = "";
// std::string powerName = _powerName + "\n";
// std::string desc = _description;
// int spacesToAdd = (textWidth - powerName.size()) / 2;
// spacing.append(spacesToAdd, ' ');
// for (int i = textWidth; i < desc.size(); i += textWidth)
// {
// desc.insert(i, 1, '\n');
// }
// return spacing + powerName + desc;
//} | true |
30a84cf3209986cafa8b00f697bb8bc6fd570f1c | C++ | Auruncus/tp-lab-6 | /include/Programmer.h | UTF-8 | 610 | 2.859375 | 3 | [] | no_license | #pragma once
#include "Engineer.h"
class Programmer : public Engineer
{
public:
Programmer() : Engineer() {};
Programmer(int id, string name, int worktime, int base, string project, int budget, double contribution) {
this->id = id;
this->name = name;
this->base = base;
this->project = project;
this->worktime = worktime;
this->budget = budget;
//this->payment = payment;
this->contribution = contribution;
SetPayment();
}
void SetPayment() override
{
this->payment = (CalculateWorkTime(this->worktime, this->base) + ProjectPayment(budget, contribution));
}
~Programmer() {}
};
| true |
3f72d6379045aeb6dfe2dbad47561c76602b68cb | C++ | yuxineverforever/plinycompute | /pdb/src/storageManager/headers/PDBAbstractPageSet.h | UTF-8 | 972 | 2.796875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] | permissive | //
// Created by dimitrije on 3/5/19.
//
#ifndef PDB_ABSTRATCTPAGESET_H
#define PDB_ABSTRATCTPAGESET_H
#include <PDBPageHandle.h>
namespace pdb {
class PDBAbstractPageSet;
using PDBAbstractPageSetPtr = std::shared_ptr<PDBAbstractPageSet>;
class PDBAbstractPageSet {
public:
/**
* Gets the next page in the page set
* @param workerID - in the case that the next page is going to depend on the worker we need to specify an id for it
* @return - page handle if the next page exists, null otherwise
*/
virtual PDBPageHandle getNextPage(size_t workerID) = 0;
/**
* Creates a new page in this page set
* @return the page handle to that page set
*/
virtual PDBPageHandle getNewPage() = 0;
/**
* Return the number of pages in this page set
* @return the number
*/
virtual size_t getNumPages() = 0;
/**
* Resets the page set so it can be reused
*/
virtual void resetPageSet() = 0;
};
}
#endif //PDB_ABSTRATCTPAGESET_H
| true |
d806b346ee10e9f1e146eac30ec1676b6125ec2f | C++ | bobchin/self-study-cpp | /chapter3/prac3.4.1.cpp | UTF-8 | 1,667 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
class pr2;
class pr1
{
int printing;
public:
pr1() { printing = 0; };
void set_print(int status) { printing = status; }
friend int inuse(pr1 ob1, pr2 ob2);
};
class pr2
{
int printing;
public:
pr2() { printing = 0; };
void set_print(int status) { printing = status; }
friend int inuse(pr1 ob1, pr2 ob2);
};
int inuse(pr1 ob1, pr2 ob2)
{
int ret;
if (ob1.printing == 1 || ob2.printing == 1) {
ret = 1;
} else {
ret = 0;
}
return ret;
}
int main()
{
pr1 ob1;
pr2 ob2;
if (!inuse(ob1, ob2)) {
cout << "プリンタはアイドル状態です\n";
} else {
cout << "プリンタは使用中です\n";
}
cout << "ob1は印字設定中です\n";
ob1.set_print(1);
if (!inuse(ob1, ob2)) {
cout << "プリンタはアイドル状態です\n";
} else {
cout << "プリンタは使用中です\n";
}
cout << "ob1を解除\n";
ob1.set_print(0);
if (!inuse(ob1, ob2)) {
cout << "プリンタはアイドル状態です\n";
} else {
cout << "プリンタは使用中です\n";
}
cout << "ob2は印字設定中です\n";
ob2.set_print(1);
if (!inuse(ob1, ob2)) {
cout << "プリンタはアイドル状態です\n";
} else {
cout << "プリンタは使用中です\n";
}
cout << "ob1は印字設定中です\n";
ob1.set_print(1);
if (!inuse(ob1, ob2)) {
cout << "プリンタはアイドル状態です\n";
} else {
cout << "プリンタは使用中です\n";
}
return 0;
} | true |
f752246645b195eb75a69f1d8ee7851a562edd42 | C++ | Reesing/learn | /cpp/cpp.primer/exercises/6.1/abs.cc | UTF-8 | 293 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
int abs(int val)
{
if (val<0)
val = -1*val;
return val;
}
int main()
{
int ii;
cout << "Please input an integer: ";
cin >> ii;
cout << "The absolute value of " << ii << " is " << abs(ii) << endl;
return 0;
}
| true |
13cd0ca05f0899f8dd1ea8164cb87d76605274ec | C++ | fsuits/tapp | /ext/tapp_utils/MassSpectrometry/Isotope/Averagine.h | UTF-8 | 949 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2019, IBM Corporation
//
// This source code is licensed under the Apache License, Version 2.0 found in
// the LICENSE.md file in the root directory of this source tree.
#pragma once
#include <string>
#include <vector>
namespace TAPP::MassSpectrometry::Isotope
{
inline std::vector<std::pair<char, double>> CreateAveragineTable(void)
{
std::vector<std::pair<char, double>> averagine(5);
averagine[0] = { 'C', 4.9384 / 111.1254 };
averagine[1] = { 'H', 7.7583 / 111.1254 };
averagine[2] = { 'N', 1.3577 / 111.1254 };
averagine[3] = { 'O', 1.4773 / 111.1254 };
averagine[4] = { 'S', 0.0417 / 111.1254 };
return averagine;
}
inline std::string Averagine(std::vector<std::pair<char, double>>& averagine_table, double mass)
{
std::string result("");
for (std::pair<char, double>& atom : averagine_table)
{
result += atom.first + std::to_string((int)std::round(atom.second * mass));
}
return result;
}
}
| true |
68e2d0569291b2a05b4fbffa8eb061042894ae5d | C++ | naganath/SPOJ | /ABSYS.cpp | UTF-8 | 735 | 2.53125 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
int main()
{
int t;
string s;
cin>>t;
getline(cin,s);
while(t--)
{
getline(cin,s);getline(cin,s);
//cout<<s;
int i,num1[3],j=0,k=0,m=0,l=0;
for(i=0;i<s.length();i++)
{ if(s[i] == '+' || s[i] == '=')
{
num1[k++] = j;j=0;
}
else
if((s[i] >='0' && s[i] <='9') && j!=-1)
j= j*10 + s[i] -'0';
else
if (s[i] >60 )
{ j=-1;
if( m==0)
l=1; else l=0;
}
if(s[i] == '=')
m=1;
}
num1[k] = j;
if(num1[0] == -1)
num1[0] = num1[2]- num1[1];
else if(num1[1] ==-1)
num1[1] = num1[2]- num1[0];
else
num1[2] = num1[0] + num1[1];
cout<<num1[0]<<" + "<<num1[1]<<" = "<<num1[2]<<endl;
}
return 0;
} | true |
548acbf12c993f725623bb987f87fd917e15deba | C++ | dglyzin/tracercore | /src/state.cpp | UTF-8 | 5,508 | 2.609375 | 3 | [] | no_license | /*
* state.cpp
*
* Created on: 10 окт. 2016 г.
* Author: frolov
*/
#include "state.h"
using namespace std;
State::State(ProcessingUnit* _pu, NumericalMethod* _method, double** _blockCommonTempStorages, int elementCount) {
pu = _pu;
method = _method;
mBlockCommonTempStorages = _blockCommonTempStorages;
mElementCount = elementCount;
mState = pu->newDoubleArray(elementCount);
int kStorageCount = method->getKStorageCount();
//mKStorages = pu->newDoublePointerArray(kStorageCount);
mKStorages = new double*[kStorageCount];
for (int i = 0; i < kStorageCount; ++i) {
mKStorages[i] = pu->newDoubleArray(mElementCount);
}
}
State::~State() {
/*pu->deleteDeviceSpecificArray(mState);
int kStorageCount = method->getKStorageCount();
for (int i = 0; i < kStorageCount; ++i) {
pu->deleteDeviceSpecificArray(mKStorages[i]);
}
pu->deleteDeviceSpecificArray(mKStorages);*/
delete mKStorages;
}
/*double** State::getKStorages() {
return mKStorages;
}*/
/*double* State::getStorage(int storageNumber) {
if (storageNumber < method->getKStorageCount())
return mKStorages[storageNumber];
else
return NULL;
}*/
void State::init(initfunc_fill_ptr_t* userInitFuncs, unsigned short int* initFuncNumber, int blockNumber, double time) {
pu->initState(mState, userInitFuncs, initFuncNumber, blockNumber, 0.0);
}
double* State::getResultStorage(int stageNumber) {
//return mStorages[method->getStorageNumberResult(stageNumber)];
return method->getStorageResult(mState, mKStorages, mBlockCommonTempStorages, stageNumber);
}
double* State::getSourceStorage(int stageNumber) {
//return mStorages[method->getStorageNumberSource(stageNumber)];
return method->getStorageSource(mState, mKStorages, mBlockCommonTempStorages, stageNumber);
}
double* State::getState() {
//return method->getStateStorage(mKStorages);
return mState;
}
void State::getSubVolume(double* result, int zStart, int zStop, int yStart, int yStop, int xStart,
int xStop, int yCount, int xCount, int cellSize){
//printf("getting state subvolume z1 z2 y1 y2 x1 x2 yc xz cs: %d %d %d %d %d %d %d %d %d \n", zStart, zStop, yStart, yStop, xStart,
// xStop, yCount, xCount, cellSize);
pu->getSubVolume(result, mState, zStart, zStop, yStart, yStop, xStart,
xStop, yCount, xCount, cellSize);
}
void State::setSubVolume(double* source, int zStart, int zStop, int yStart, int yStop, int xStart,
int xStop, int yCount, int xCount, int cellSize){
pu->setSubVolume(mState, source, zStart, zStop, yStart, yStop, xStart,
xStop, yCount, xCount, cellSize);
}
void State::prepareArgument(double timeStep, int stageNumber) {
method->prepareArgument(pu, mState, mKStorages, mBlockCommonTempStorages, timeStep, stageNumber, mElementCount);
}
void State::computeDenseOutput(double timeStep, double theta, double* result) {
method->computeDenseOutput(pu, mState, mKStorages, mBlockCommonTempStorages, timeStep, theta, result,
mElementCount);
}
double State::computeStepError(double timeStep) {
return method->computeStepError(pu, mState, mKStorages, mBlockCommonTempStorages, timeStep, mElementCount);
}
void State::confirmStep(double timeStep, State* nextStepState, ISmartCopy* sc) {
method->confirmStep(pu, sc, &mState, mKStorages, &(nextStepState->mState), nextStepState->mKStorages,
mBlockCommonTempStorages, timeStep, mElementCount);
}
void State::rejectStep(double timeStep) {
method->rejectStep(pu, mState, mKStorages, mBlockCommonTempStorages, timeStep, mElementCount);
}
void State::saveGeneralStorage(char* path) {
pu->saveArray(mState, mElementCount, path);
//method->saveStateGeneralData(pu, mKStorages, path);
}
void State::saveAllStorage(char* path) {
saveGeneralStorage(path);
int kStorageCount = method->getKStorageCount();
for (int i = 0; i < kStorageCount; ++i) {
pu->saveArray(mKStorages[i], mElementCount, path);
}
//method->saveStateData(pu, mKStorages, path);
}
void State::saveStateForDrawDenseOutput(char* path, double timeStep, double theta) {
double* result = pu->newDoubleArray(mElementCount);
method->computeDenseOutput(pu, mState, mKStorages, mBlockCommonTempStorages, timeStep, theta, result,
mElementCount);
pu->saveArray(result, mElementCount, path);
pu->deleteDeviceSpecificArray(result);
}
void State::loadGeneralStorage(ifstream& in) {
pu->loadArray(mState, mElementCount, in);
//method->loadStateGeneralData(pu, mKStorages, in);
}
void State::loadAllStorage(std::ifstream& in) {
loadGeneralStorage(in);
int kStorageCount = method->getKStorageCount();
for (int i = 0; i < kStorageCount; ++i) {
pu->loadArray(mKStorages[i], mElementCount, in);
}
//method->loadStateData(pu, mKStorages, in);
}
bool State::isNan() {
return pu->isNan(mState, mElementCount);
}
void State::print(int zCount, int yCount, int xCount, int cellSize) {
//printf("################################################################################");
printf("\nState\n");
printf("State address: %p\n", mState);
int kStorageCount = method->getKStorageCount();
for (int i = 0; i < kStorageCount; ++i) {
printf("kStorage #%d address: %p\n", i, mKStorages[i]);
}
printf("\nState\n");
pu->printArray(mState, zCount, yCount, xCount, cellSize);
for (int i = 0; i < kStorageCount; ++i) {
printf("\nkStorage #%d\n", i);
pu->printArray(mKStorages[i], zCount, yCount, xCount, cellSize);
}
//printf("################################################################################");
//printf("\n\n\n");
}
| true |
6cac80a365defe40363d5447624a92586832d1ea | C++ | mahesh001/Myds-program | /tree/Huffmann.cpp | UTF-8 | 2,528 | 2.921875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int g=100;
struct node
{
char tag;
int fq;
node* left;
node* right;
int mark;
};
class stack
{
public:
node* c[50];
int size;
int top;
stack()
{
top=-1;
size=50;
}
int isempty()
{
if(top==-1)
return 1;
else
return 0;
}
void push(node* ch)
{
top++;
c[top]=ch;
}
node* pop()
{
return c[top--];
}
node* peek()
{
return c[top];
}
};
node** bsort(node** root,int n)
{
node* temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(root[i]->fq < root[j]->fq)
{
temp->fq=root[i]->fq;temp->tag=root[i]->tag;
root[i]->fq=root[j]->fq;root[i]->tag=root[j]->tag;
root[j]->fq=temp->fq;root[j]->tag=temp->tag;
}
}
}
return root;
}
void findcode(node* temp,int val)
{
if(temp==NULL)
return;
else if(val<temp->mark)
{
cout<<"0";
findcode(temp->left,val);
}
else if(val>temp->mark)
{
cout<<"1";
findcode(temp->right,val);
}
else
return;
}
void inorder(node* temp)
{
if(temp==NULL)
return ;
else
{
inorder(temp->left);
temp->mark=g++;
inorder(temp->right);
}
}
int main()
{
int i,n,j,f,k;
char ch;
stack s1,s2;
cout<<"how many type of characters does the file has?\n";
cin>>n;
node** root;
root=new node*[n];
for(i=0;i<n;i++)
{
cout<<"enter character\n";
cin>>ch;
cout<<"what is the frequncy of the character "<<ch<<" \n";
cin>>f;
node* temp=new node;
temp->tag=ch;
temp->fq=f;
temp->left=NULL;temp->right=NULL;
//q.enq(temp);
root[i]=temp;
//s1.push(temp);
}
root=bsort(root,n);
//for(i=0;i<5;i++)
//{
// cout<<root[i]->fq<<" "<<root[i]->tag<<endl;
//}
for(i=0;i<n;i++)
{ cout<<root[i]->fq<<" ";
s1.push(root[i]);
}
for(j=0;j<n-1;j++)
{
k=0;
node* temp1=s1.pop();
node* temp2=s1.pop();
node* tem=new node;
tem->left=temp1;
tem->right=temp2;
tem->fq = temp1->fq + temp2->fq;
tem->tag='#';
s1.push(tem);cout<<endl;
while(!s1.isempty()) {
node* tmp = s1.pop();
while(!s2.isempty() && s2.peek()->fq > tmp->fq) {
s1.push(s2.pop());
}
s2.push(tmp);
}
i=0;
while(!s2.isempty())
{
s1.push(s2.pop());
}
}
node* temp=s1.pop();
inorder(temp);
int intcode;
char code;
cout<<"enter the character to find its code\n";
cin>>code;
for(i=0;i<n;i++)
{
if(code==root[i]->tag)
intcode=root[i]->mark;
}
//cout<<intcode<<endl;
findcode(temp,intcode);
}
| true |
c6040c12ee4ded3fa47ce0515764531d3cc42f2f | C++ | mrashidz/CXX_Course_Demo | /Day3/2_Access/acc.h | UTF-8 | 366 | 2.953125 | 3 | [] | no_license | #include <iostream>
class Bar;
class Foo {
int x = -1;
friend void externalPrint(const Foo&);
public:
void printBar(const Bar &_b); /*{
std::cout << _b.x << std::endl;//Forward declaration does not specify Bar's interal
}*/
Foo() = default;
};
class Bar {
friend class Foo;
int x = 2;
public:
Bar() = default;
};
| true |
7c48f233153116512c3ddcb9cd77f6185185e020 | C++ | Mbd06b/cpp-learn | /C++II/LowerCaseString02-29/src/LowerCaseString.cpp | UTF-8 | 520 | 2.53125 | 3 | [] | no_license | /*
* LowerCaseString.cpp
*
* Created on: Feb 29, 2016
* Author: mbd06b
*/
#include "LowerCaseString.h"
LowerCaseString::LowerCaseString(){
}
LowerCaseString::LowerCaseString (const WCS_String & Str): WCS_String (Str){ //here we are calling the parent copy constructor :WCS_String (Str)
ToLower (); //this is method ofWCS_String
}
LowerCaseString::~LowerCaseString (){
}
LowerCaseString & LowerCaseString::Copy (const LowerCaseString & Str) {
WCS_String::Copy (Str);
ToLower ();
return *this;
}
| true |
e8de023ffbec94bdca1e8b57c55bf47fc92e0e61 | C++ | LolloSpring/TwTool | /twitter_01.cc | UTF-8 | 2,893 | 3.140625 | 3 | [] | no_license | #include "twitter.h"
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
const int dim=256;
const int est=4;
void concatena (const char a[], const char estensione[], char c[], int len_a, int len_b);
int main (int argc, char* argv[]){
fstream my_in, my_out; //i due stream: input e output su file
char hashtag[dim]; //dichiaro la stringa hashtag
char tema[dim]; //è file da cui prendo hashtags
char output[dim]; //è file di uscita del tweet;
char data[dim]; //questa è la data
char estensione[]=".txt";
char input[dim];
char scelta;
char vuoto[]="";
char universita[]="uni";
char politicatrentina[]="poltn";
char scuoladipolitiche[]="sdp";
cout<<"Ciao e benvenuto!\n";
cout<<"Che giorno è oggi?\n";
cout<<"Metti: ggmmaaaa\n"; //inserimento data
cin >>data;
cout<<"Quale tema di hashtag desideri?\n"; //quale tema degli hashtags
cout<<"Digita 'u' per hashtags su università, \n 't' per per hashtags su politica trentina, \n 's' per hashtags su Scuola di Politiche \n";
cin >> scelta;
switch (scelta) {
case 'u': concatena(vuoto,universita,tema,strlen(vuoto),strlen(universita));
break;
case 't': concatena(vuoto,politicatrentina,tema,strlen(vuoto),strlen(politicatrentina));
break;
case 's': concatena(vuoto,scuoladipolitiche,tema,strlen(vuoto),strlen(scuoladipolitiche));
break;
default: cout << "Errore nella compilazione\n";
break;
}
cout << tema << endl;
concatena(tema,estensione,input,strlen(tema),strlen(estensione)+1);
concatena(data,estensione,output,strlen(data),strlen(estensione)+1);
cout << input << endl;
cout << output << endl;
my_in.open(input, ios::in);
my_out.open(output, ios::out);
while (my_in>>hashtag) {
if (hashtag[0]=='#'){
my_out << hashtag << endl;
}
}
my_in.close();
my_out.close();
}
/*
concatena(vuoto,politicatrentina,tema,strlen(vuoto),strlen(politicatrentina));
char vuoto[]="";
char politicatrentina[]="poltn";
*/
void concatena (const char a[], const char b[], char c[], int len_a, int len_b){
for (int i=0; i<len_a;i++)
c[i]=a[i];
for (int i=0; i<len_b;i++)
c[i+len_a]=b[i];
}
/*TOdo
0.1far vedere i temi di hashtag per scegliere con 1 lettera
0.2far aggiungere gli hashtag da un file che contiene già un tweet da pubblicare
0.3 mettere tutti i messaggi di benvenuto in una procedura unica di saluto.
0.4 mettere procedura di saluto su file.h
0.5 fare procedura apposita per aggiungere il .txt alla data
0.6 creare possibilità di riscrivere il tema scelto
0.7 fare pulizzia di variabili inutili
0.8 fare controllo per immissioni dati da linea di comando
*/
| true |
dd1cdd1e5a57b7ea02f85660836c7fe6b392f970 | C++ | DeJuan/Kinect2.0ServerClient | /UDPServer.h | UTF-8 | 597 | 2.75 | 3 | [] | no_license | #ifndef UDP_SERVER_H
#define UDP_SERVER_H
#include <Windows.h>
#include <io.h>
#include <stdexcept>
namespace udp_server
{
class udp_server_runtime_error : public std::runtime_error
{
public:
udp_server_runtime_error(const char *w) : std::runtime_error(w){}
};
class udp_server
{
public:
udp_server(const std::string& addr, int port);
~udp_server();
int get_socket() const;
int get_port() const;
std::string get_addr() const;
int send(const char *msg, size_t size);
private:
int f_socket;
int f_port;
std::string f_addr;
struct addrinfo* f_addrinfo;
};
}
#endif | true |
810dcb97b469bb41e6c843c560ea6529383264fb | C++ | mugwhump/AIsteroids | /InputDirection.h | UTF-8 | 2,873 | 2.921875 | 3 | [] | no_license | #pragma once;
#include "EnumParser.h"
#include <vector>
/************************************************************************/
/* INPUT */
/************************************************************************/
namespace eInput{
enum Input : unsigned short
{
UP = 0,
DOWN = 1,
LEFT = 2,
RIGHT = 3,
FIRE = 4,
NumInputs
};
//static eDirection::Direction getDirection(std::vector<eInput::Input> inputs);
}
/************************************************************************/
/* STATIC FUNCTIONS AT GLOBAL/NAMESPACE SCOPE MEAN FUNCTION'S ARE ONLY USED IN THAT TRANSLATION UNIT */
/************************************************************************/
/************************************************************************/
/* DIRECTION */
/************************************************************************/
namespace eDirection{
enum Direction : unsigned short //IF NUMBERS CHANGED, MUST CHANGE METHODS
{
RIGHT = 0,
UPRIGHT = 1,
UP = 2,
UPLEFT = 3,
LEFT = 4,
DOWNLEFT = 5,
DOWN = 6,
DOWNRIGHT = 7,
NumDirections,
NODIRECTION = 9
};
//EnumParser specialization constructor
EnumParser<Direction> getEnumParser();
extern EnumParser<Direction> parser; //use parser to do conversions, don't need to include EnumParser.h
std::vector<eInput::Input> getDirectionInputs(Direction dir); //get inputs to go in that direction. Empty vector = NODIRECTION
}
/************************************************************************/
/* ACTION */
/************************************************************************/
namespace eAction{
enum ActionEnum : unsigned short //IF NUMBERS CHANGED, MUST CHANGE METHODS
{
RIGHT = 0,
UPRIGHT = 1,
UP = 2,
UPLEFT = 3,
LEFT = 4,
DOWNLEFT = 5,
DOWN = 6,
DOWNRIGHT = 7,
NODIRECTION = 8,
FIRERIGHT = 9,
FIREUPRIGHT = 10,
FIREUP = 11,
FIREUPLEFT = 12,
FIRELEFT = 13,
FIREDOWNLEFT = 14,
FIREDOWN = 15,
FIREDOWNRIGHT = 16,
FIRENODIRECTION = 17,
NumActions
};
//EnumParser specialization constructor
EnumParser<ActionEnum> getEnumParser();
extern EnumParser<ActionEnum> parser; //use parser to do conversions, don't need to include EnumParser.h
//THIS IS ALL RETARDED
eDirection::Direction getDirection(ActionEnum a); //get direction
ActionEnum getActionEnum(eDirection::Direction dir, bool isFiring); //get action enum given a direction and whether firing
std::vector<eInput::Input> getInputs(ActionEnum a); //get inputs to do action. Empty vector = NODIRECTION
} | true |
d578f1ce5e1eae0190da0ea00e56bad933667b5c | C++ | aparant777/AngryGameEngine | /MonsterChase/Player.cpp | UTF-8 | 2,340 | 2.921875 | 3 | [] | no_license | #include<stdio.h>
#include<conio.h>
#include"HeapAllocator.h"
#include "Player.h"
#include"Vector3.h"
CPlayer::CPlayer() { }
/*initializes the Player class*/
void CPlayer::InitializePlayer() {
printf("Enter the name of the player: ");
scanf_s("%s", mName, 100);
printf("player name is %s. \n\n", mName);
printf("all oke re..");
GameObject* temp = new GameObject(Vector3(0, 0, 0), mName);
printf("\n\n till herer we got");
SetGameObject(temp);
//player->gameObjectPlayer->SetPosition(Vector3::zero);
printf("\n");
printf("%s spawned at ", mName);
printf("location");
gameObjectPlayer->PrintPosition();
}
/* will spill out a character to Move or Exit*/
const char CPlayer::Input() {
char choice = 'a';
printf("Press 'A' to move Left, 'D' for Right, 'W' for Forward and 'S' for Down. Press 'Q' to Quit.\n");
choice = _getch();
DecideToMoveORQuit(choice);
return choice;
}
inline void CPlayer::DecideToMoveORQuit(const char choice) {
if (choice == 'A' || choice == 'a' || choice == 'W' || choice == 'w' || choice == 'S' || choice == 's' || choice == 'D' || choice == 'd') {
Move(choice);
}
else {
}
}
/*Moves the Player, either + or - in X or Y*/
inline void CPlayer::Move(const char choice) {
if (choice == 'A' || choice == 'a') {
Vector3 newPosition = gameObjectPlayer->GetPosition() + Vector3::left;
printf("%s moved left.\n",mName);
gameObjectPlayer->SetPosition(newPosition);
//gameObjectPlayer->PrintPosition();
}
else if (choice == 'W' || choice == 'w') {
Vector3 newPosition = gameObjectPlayer->GetPosition() + Vector3::up;
printf("%s moved up.\n", mName);
gameObjectPlayer->SetPosition(newPosition);
//gameObjectPlayer->PrintPosition();
}
else if (choice == 'S' || choice == 's') {
Vector3 newPosition = gameObjectPlayer->GetPosition() + Vector3::down;
printf("%s moved down.\n", mName);
gameObjectPlayer->SetPosition(newPosition);
//gameObjectPlayer->PrintPosition();
}
else if (choice == 'D' || choice == 'd') {
Vector3 newPosition = gameObjectPlayer->GetPosition() + Vector3::right;
printf("%s moved right.\n", mName);
gameObjectPlayer->SetPosition(newPosition);
//gameObjectPlayer->PrintPosition();
}
gameObjectPlayer->PrintPosition();
}
void CPlayer::GetMovementDirectionFromUserInput() {
}
void CPlayer::UpdateGameObject() {
}
CPlayer::~CPlayer() { }
| true |
9b1385f32128f3cef1b7371afd77ce81b727a6c8 | C++ | robertsdionne/sacred | /sacred/softmax_test.cpp | UTF-8 | 683 | 2.734375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "softmax.hpp"
#include "tensor.hpp"
namespace sacred {
TEST(Softmax, Run) {
auto input = Tensor<>({8}, {0, 1, 2, 3, 4, 5, 6, 7});
auto op = Softmax<>();
auto output = Tensor<>({8}, {0, 0, 0, 0, 0, 0, 0, 0});
op(input, output);
EXPECT_FLOAT_EQ(0.00057661271, output.at({0}));
EXPECT_FLOAT_EQ(0.0015673959, output.at({1}));
EXPECT_FLOAT_EQ(0.0042606238, output.at({2}));
EXPECT_FLOAT_EQ(0.011581576, output.at({3}));
EXPECT_FLOAT_EQ(0.031481985, output.at({4}));
EXPECT_FLOAT_EQ(0.0855769, output.at({5}));
EXPECT_FLOAT_EQ(0.23262219, output.at({6}));
EXPECT_FLOAT_EQ(0.63233268, output.at({7}));
}
} // namespace sacred
| true |
3a3516a873aa5b3f60b25bc79989ed37ca45fba4 | C++ | KMR-86/number-theory-resources | /codes/seive/cf-17a.cpp | UTF-8 | 919 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int prime_map[1001]={0};
vector<int>primes;
int prime_count[1001]={0};
void seive(){
prime_map[0]=1;
prime_map[1]=1;
for(int i=2;i<1001;i++){
if(prime_map[i]==0){
for(int j=i*i;j<1001;j=j+i){
prime_map[j]=1;
}
}
}
for(int i=1;i<1001;i++){
if(prime_map[i]==0){
primes.push_back(i);
}
}
prime_count[0]=0;
for(int i=1;i<1001;i++){
if(prime_map[i]==0){
prime_count[i]=prime_count[i-1]+1;
}
else{
prime_count[i]=prime_count[i-1];
}
}
}
int main(){
seive();
int n,k;
cin>>n>>k;
int c=0;
for(int i=0;primes[i]<=n;i++){
for(int j=0;j<primes.size();j++){
if(primes[j]+primes[j+1]+1==primes[i]){c++;break;}
}
}
if(c>=k){
cout<<"YES";
}
else{
cout<<"NO";
}
return 0;
}
| true |
56c0b5074bc0d8a22e797f3ea5b69867db716f93 | C++ | Luftschlosser/ATmighty | /src/ATmighty/ATmighty/Utilities/LUTs/HardwareOwnerID.h | UTF-8 | 1,583 | 3.09375 | 3 | [] | no_license | /*
* This headerfile defines several string-literals and helper functions which are used by ATmighty to set
* senseful OwnerID's for hardware-allocations and retrieve a senseful description for each ID for logging.
*/
#ifndef ATMIGHTY_UTILITIES_LUTS_HARDWAREOWNERID_H_
#define ATMIGHTY_UTILITIES_LUTS_HARDWAREOWNERID_H_
#include <avr/pgmspace.h>
namespace OwnerID
{
//ATmighty OwnerID's have to be negative numbers, as the positive range is reserved for the user.
///This enum defines different usages/OwnerID's for ATmighty's hardware-allocations
enum OwnerID : int8_t
{
Unused = 0, //Hw is actually not in use at all (free)
Default = -1, //Fallback OwnerID (gets used when HW is allocated by OwnerID 0)
DirectAbstraction = -2, //physical HW is used as an abstract HW of the same Type (e.g. PortA as IoPort->AbstractIoPort->AbstractPortA)
IndirectAbstraction = -3, //physical HW is partially used by an abstract HW of a dependent type Type (e.g. PortA by IoPin->AbstractIoPin->AbstractPinA0)
AbstractionDependency = -4, //HW is used by another abstract HW (e.g. AbstractIoPin as PWM-output by AbstractTimer8b)
MsgLogWriter = -5, //HW is used by MessageLogWriter-instance
};
/*!
* retrieves a string representation of an OwnerID for logging.
* \param id the owner-id to get as string
* \returns a PGM_P type pointer which points to the address in PROGMEM where the string is stored, or nullptr if the given id is not defined as string.
*/
PGM_P GetOwnerIdDescription(int8_t id);
}
#endif /* ATMIGHTY_UTILITIES_LUTS_HARDWAREOWNERID_H_ */
| true |
a3ef1d3f5b83c128b549e9e7c003b4806dd1e062 | C++ | aalessi18/FirstGame | /GameAssets/Map/Map.cpp | UTF-8 | 1,666 | 2.9375 | 3 | [] | no_license | /*
Implementation of Map Class
*/
#include "Map.hpp"
#include "Tokens.hpp"
#include <boost/graph/named_function_params.hpp>
using namespace std;
Map::Map() {
}
Map::~Map() {
}
void Map::printContents() {
for(int i=0;i<num_vertices(graphData);i++)
{
cout << "Vertex: " << graphData[i].getIndex() << endl;
graphData[i].printAdjacentContents(false);
}
cout << endl;
}
void Map::printAdjacentRegions(vector<int> &controlledRegions, bool withSea) {
cout << "Adjacent regions are: " << endl;
for(int i=0; i<controlledRegions.size(); i++)
{
int temp1 = controlledRegions.at(i);
for(int j=0;j<graphData[temp1].getAdjacentRegionsIndex().size(); j++)
{
int temp2 = graphData[temp1].getAdjacentRegionsIndex().at(j);
if(withSea==false && graphData[temp2].getRegionName()!="Sea")
{
cout << "Region: " << graphData[temp2].getIndex() << " ";
}
}
cout << endl;
}
cout << endl;
}
UndirectedGraph& Map::getGraph(){
return graphData;
}
void Map::findOutsideEdges() {
for(int i=0;i<num_vertices(graphData);i++)
{
if(graphData[i].isOutsideEdge() == true && graphData[i].getRegionName()!= "Sea")
outsideEdges.push_back(i);
}
}
void Map::setOutsideEdges(int region){ // USE FIND OUTSIDE EDGES TO ADD IN HERE
this->outsideEdges.push_back(region);
}
vector<int> Map::getOutsideEdges() {
return outsideEdges;
}
void Map::printOutsideEdges() {
for(int i=0;i<outsideEdges.size();i++)
{
cout << "Region: "<< outsideEdges.at(i) << " ";
}
cout << endl;
}
| true |
201eeb8f98a972942d899309d21d4034a8bf4006 | C++ | lwestjohn16/snakegame | /QTSnake-Cplusplus_Version1-master/snake.cpp | UTF-8 | 1,358 | 3.234375 | 3 | [] | no_license | #include "snake.h"
#include <iostream>
#include <iterator>
#include <list>
Snake::Snake(int x, int y, int growToSize): numQueuedSegments(growToSize) {
image.load(":/images/snake1.png");
QRect head;
head = image.rect();
head.moveTo(x, y);
putSegmentAt(image, head, x, y);
}
void Snake::putSegmentAt(QImage image, QRect rect, int x, int y) {
segments.push_front(Segment(image, rect, x, y));
if (numQueuedSegments > 0)
--numQueuedSegments;
else
segments.pop_back();
}
void Snake::growBy(unsigned int numSegments) {
numQueuedSegments += numSegments;
}
Snake::~Snake() {
std::cout << ("Snake deleted\n");
}
void Snake::move() {
QRect rect;
rect = image.rect();
int x = head().x;
int y = head().y;
switch (dir) {
case Snake::DOWN:
y += 10;
break;
case Snake::UP:
y -= 10;
break;
case Snake::LEFT:
x -= 10;
break;
case Snake::RIGHT:
x += 10;
break;
}
rect.moveTo(x, y);
putSegmentAt(image, rect, x, y);
}
/*bool Snake::checkOverlap(int x, int y){
for(SegmentIterator = segments.begin(); SegmentIterator != segments.end(); SegmentIterator++){
if(*SegmentIterator.rect.contains(x,y)){
return true;
}
}
return false;
}*/
| true |
990ff7736e328794b39589c0094ebc21cc9f9892 | C++ | aksel26/TIL | /200615_C++/1_of_5/for/for.cpp | UTF-8 | 713 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int score;
cout << "점수 입력 : ";
cin >> score;
if (score < 0 || score > 100)
{
cout << "유효하지 않은 점수입니다" << score << endl;
}
else
{
switch (score / 10)
{
case 10:
case 9:
cout << "A학점" << endl;
break;
case 8:
cout << "B학점" << endl;
break;
case 7:
cout << "C학점" << endl;
break;
case 6:
cout << "D학점" << endl;
break;
default:
cout << "F학점" << endl;
break;
}
}
return 0;
} | true |
6fdaa0838955169175a28a3c03f954e3454b9053 | C++ | kamyu104/LeetCode-Solutions | /C++/delete-characters-to-make-fancy-string.cpp | UTF-8 | 379 | 3.09375 | 3 | [
"MIT"
] | permissive | // Time: O(n)
// Space: O(1)
// inplace solution
class Solution {
public:
string makeFancyString(string s) {
int cnt = 0, j = 0;
for (int i = 0; i < size(s); ++i) {
cnt = (i >= 1 && s[i] == s[i - 1]) ? cnt + 1 : 1;
if (cnt < 3) {
s[j++] = s[i];
}
}
s.resize(j);
return s;
}
};
| true |
adf837e0a9ef55944407d968bff5990abfb145d3 | C++ | project-s/P3Game | /database.cpp | UTF-8 | 6,427 | 2.8125 | 3 | [] | no_license | #include "database.h"
database::database(Hero *LegacyBoy, statistics *P3Stats)
{
fullPath = "./LegacyGame.db";
LegacyBoyDB = LegacyBoy;
P3StatsDB = P3Stats;
if (openDatabase())
{
std::cout << "* DB : OPENED*" << std::endl;
}
}
database::~database()
{
//dtor
if (closeDatabase())
{
std::cout << "* DB : CLOSED*" << std::endl;
}
}
bool database::openDatabase()
{
sqlite3_initialize();
return sqlite3_open(getDbPathCStr().c_str(), &db) == SQLITE_OK;
}
irr::core::stringc database::getDbPathCStr()
{
return fullPath.c_str();
}
bool database::closeDatabase()
{
bool result = 0;
if (sqlite3_close_v2(db) == SQLITE_OK) {
result=1;
}
sqlite3_shutdown();
return result;
}
bool database::executeQuery(irr::core::stringw query)
{
char *errorMessage = 0;
irr::core::stringc sql = query.c_str();
bool result=0;
if (sqlite3_exec(db, sql.c_str(), NULL, 0, &errorMessage) == SQLITE_OK) {
result=1;
}
return result;
}
bool database::createTable()
{
irr::core::stringc sql = "CREATE TABLE IF NOT EXISTS T_GAME (idGame INTEGER PRIMARY KEY AUTOINCREMENT, heroName TEXT, strHero REAL, defHero REAL, sprHero REAL, spdHero REAL, maxHP REAL, legacyNum INTEGER, actualWorldLevel INTEGER, monsterKilled INTEGER, HighestWorld INTEGER, dmgDone REAL, dmgTaken REAL, PlayingTime REAL);";
return executeQuery(sql);
}
bool database::initTable()
{
int result;
irr::core::stringc sql = "SELECT COUNT(idGame) FROM T_GAME";
sqlite3_stmt *stmt;
if (!prepareQuery(sql, &stmt))
{
std::cout << "ERROR PREPARE QUERY : " << sql.c_str() << std::endl;
return false;
}
int returnValue = 0;
do
{
result = sqlite3_step(stmt);
if (result == SQLITE_ROW){
returnValue = sqlite3_column_int(stmt,0);
}
}
while (result == SQLITE_ROW);
if (returnValue>0)
{
std::cout << "DATABASE IS EMPTY" << std::endl;
return true;
}
else
{
sql = "INSERT INTO T_GAME (heroName, strHero, defHero, sprHero, spdHero, maxHP, legacyNum, actualWorldLevel, monsterKilled, HighestWorld, dmgDone, dmgTaken, PlayingTime) VALUES ('',0,0,0,0,0,0,0,0,0,0,0,0);";
return executeQuery(sql);
}
}
bool database::prepareQuery(irr::core::stringc query, sqlite3_stmt** stmt)
{
return sqlite3_prepare_v2(db, query.c_str(), strlen(query.c_str())+1, stmt, NULL) == SQLITE_OK;
}
bool database::updateTable(int actualWorldLevel)
{
irr::core::stringc sql = "UPDATE T_GAME SET heroName = '";
sql += LegacyBoyDB->getName().c_str();
sql += "', strHero = ";
sql += LegacyBoyDB->getSTR();
sql += ", defHero = ";
sql += LegacyBoyDB->getDEF();
sql += ", sprHero = ";
sql += LegacyBoyDB->getSPR();
sql += ", spdHero = ";
sql += LegacyBoyDB->getSpd();
sql += ", maxHP = ";
sql += LegacyBoyDB->getMaxHP();
sql += ", legacyNum = ";
sql += LegacyBoyDB->getLegacyNumber();
sql += ", actualWorldLevel = ";
sql += actualWorldLevel;
sql += ", monsterKilled = ";
sql += P3StatsDB->getMonsterKilled();
sql += ", HighestWorld = ";
sql += P3StatsDB->getHighestWorld();
sql += ", dmgDone = ";
sql += P3StatsDB->getDmgDone();
sql += ", dmgTaken = ";
sql += P3StatsDB->getDmgTaken();
sql += ", PlayingTime = ";
sql += P3StatsDB->getTimePlayed();
sql += " WHERE idGame = 1;";
return executeQuery(sql);
}
int database::loadGame()
{
//Check if there are rows in the table
int result=0;
irr::core::stringc sql = "SELECT COUNT(idGame) FROM T_GAME";
// Prepare the sql
sqlite3_stmt *stmt;
if (!prepareQuery(sql, &stmt))
{
std::cout << "ERROR PREPARE QUERY : " << sql.c_str() << std::endl;
return false;
}
//now to count
int returnValue = 0;
do
{
result = sqlite3_step(stmt);
if (result == SQLITE_ROW){
returnValue = sqlite3_column_int(stmt,0);
}
}
while (result == SQLITE_ROW);
closeDatabase();
openDatabase();
//var for the return
int actualWorldLevel=0;
if (returnValue>0)
{
sql = "SELECT idGame, heroName, strHero, defHero, sprHero, spdHero, maxHP, legacyNum, actualWorldLevel, monsterKilled, HighestWorld, dmgDone, dmgTaken, PlayingTime FROM T_GAME where idGame =1;";
if (!prepareQuery(sql, &stmt))
{
std::cout << "ERROR PREPARE QUERY : " << sql.c_str() << std::endl;
return false;
}
else
{
do
{
//Reader for the SQL : Add values to HERO/STATS and return the actualWorldNumber
result = sqlite3_step(stmt);
//if result = 100 (code for SQLITE_ROW)
if (result == SQLITE_ROW){
//Loading data to the hero and stats
irr::core::stringc heroName;
heroName = sqlite3_column_text(stmt, 1);
LegacyBoyDB->setName(heroName.c_str());//heroName
LegacyBoyDB->setSTR((float) sqlite3_column_double(stmt,2));//strHero
LegacyBoyDB->setDEF((float) sqlite3_column_double(stmt,3));//defHero
LegacyBoyDB->setSPR((float) sqlite3_column_double(stmt,4));// sprHero
LegacyBoyDB->setSPD((float) sqlite3_column_double(stmt,5));//spdHero
LegacyBoyDB->setMaxHP((float) sqlite3_column_double(stmt,6));//maxHP
LegacyBoyDB->setLegacyNumber(sqlite3_column_int(stmt,7));//legacyNum
actualWorldLevel = sqlite3_column_int(stmt,8);//actualWorldLevel
P3StatsDB->setMonsterKilled(sqlite3_column_int(stmt,9));//monsterKilled
P3StatsDB->setHighestWorld(sqlite3_column_int(stmt,10));//HighestWorld
P3StatsDB->setDmgDone((float) sqlite3_column_double(stmt,11));//dmgDone
P3StatsDB->setDmgTaken((float) sqlite3_column_double(stmt,12));//dmgTaken
P3StatsDB->setTimePlayed(sqlite3_column_double(stmt,13));//PlayingTime
}
}
while (result == SQLITE_ROW);
}
//returning the actualworldlevel : where the game will have to start
return actualWorldLevel;
}
else
{
return 0;
}
}
| true |
99b9b0eefe32338abc53f3aec310616c2c4c43a6 | C++ | alexcui03/luogu-test | /luogu/P1149 火柴棒等式.cpp | UTF-8 | 530 | 3.0625 | 3 | [] | no_license | #include <iostream>
using namespace std;
const int num_cnt[10] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
int cnt(int x);
int main() {
int n, sum = 0;
cin >> n;
n -= 4;
for (int a = 0; a < 1111; ++a) {
if ((cnt(a) << 1) + cnt(a << 1) == n) {
++sum;
}
for (int b = a + 1; b < 1111; ++b) {
if (cnt(a) + cnt(b) + cnt(a + b) == n) {
sum += 2;
}
}
}
cout << sum;
return 0;
}
int cnt(int x) {
int result = num_cnt[x % 10];
if (x >= 10) result += cnt(x / 10);
return result;
}
| true |
2b7cea210f5143650ff6a815102f3dbd6c1ca390 | C++ | roym899/vector_graphics | /include/vector_graphics/Point.hpp | UTF-8 | 873 | 3.140625 | 3 | [
"MIT"
] | permissive | // Author: Leonard Bruns (2019)
#ifndef VECTOR_GRAPHICS_POINT
#define VECTOR_GRAPHICS_POINT
// STL
#include <memory>
// vector_graphics
#include "Primitive.hpp"
namespace vectorgraphics {
///////////////////////////////////////////////////////////////////////////////
/// \brief A point in 2D space.
class Point2D : public Primitive {
public:
Point2D(double x, double y)
: x_(x), y_(y) {}
double x_, y_;
};
typedef std::shared_ptr<Point2D> Point2DPtr;
std::ostream& operator<<(std::ostream &out, const Point2D &point_2d);
///////////////////////////////////////////////////////////////////////////////
/// \brief A point in 3D space.
class Point3D : public Primitive {
public:
Point3D(double x, double y, double z)
: x_(x), y_(y), z_(z) {}
double x_, y_, z_;
};
typedef std::shared_ptr<Point3D> Point3DPtr;
}
#endif
| true |
80992d22b5e00644420d723d4758245533bc80a5 | C++ | duckdb/duckdb | /extension/httpfs/crypto.cpp | UTF-8 | 841 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "crypto.hpp"
#include "mbedtls_wrapper.hpp"
namespace duckdb {
void sha256(const char *in, size_t in_len, hash_bytes &out) {
duckdb_mbedtls::MbedTlsWrapper::ComputeSha256Hash(in, in_len, (char *)out);
}
void hmac256(const std::string &message, const char *secret, size_t secret_len, hash_bytes &out) {
duckdb_mbedtls::MbedTlsWrapper::Hmac256(secret, secret_len, message.data(), message.size(), (char *)out);
}
void hmac256(std::string message, hash_bytes secret, hash_bytes &out) {
hmac256(message, (char *)secret, sizeof(hash_bytes), out);
}
void hex256(hash_bytes &in, hash_str &out) {
const char *hex = "0123456789abcdef";
unsigned char *pin = in;
unsigned char *pout = out;
for (; pin < in + sizeof(in); pout += 2, pin++) {
pout[0] = hex[(*pin >> 4) & 0xF];
pout[1] = hex[*pin & 0xF];
}
}
} // namespace duckdb
| true |
bf7fe5ec76ae4e2a78e3ae50c3fca8922d83631f | C++ | adamcavendish/HomeworkGitShare | /DataStructures/Homework/09/No_14/No_14.cpp | UTF-8 | 1,183 | 3.8125 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <utility>
#include <string>
void
bubble_sort(int * array, int array_length) {
bool swap_flag = true;
for(int i = 0; i < array_length && swap_flag; i += 2) {
swap_flag = false;
for(int j = 0; j < array_length; ++j) {
if(array[j] > array[j+1]) {
std::swap(array[j], array[j+1]);
swap_flag = true;
}//if
}//for
if(swap_flag == false)
break;
for(int j = array_length-1; j > 0; --j) {
if(array[j-1] > array[j]) {
std::swap(array[j-1], array[j]);
swap_flag = true;
}//if
}//for
}//for
}//bubble_sort(array, array_length)
int main()
{
std::ifstream in("data.in");
// Get array length
std::size_t arr_len;
in >> arr_len;
// Get array
int * arr = new int[arr_len];
for(auto i = 0lu; i < arr_len; ++i)
in >> arr[i];
if(!in) {
std::cerr << "Check data.in!" << std::endl;
in.close();
return EXIT_FAILURE;
}//if
for(auto i = 0lu; i != arr_len; ++i)
std::cout << arr[i] << ' ';
std::cout << std::endl;
bubble_sort(arr, arr_len);
for(auto i = 0lu; i != arr_len; ++i)
std::cout << arr[i] << ' ';
std::cout << std::endl;
delete[] arr;
in.close();
return 0;
}//main
| true |
93d925b31f378917f149f578122507caa446bd3f | C++ | Dhikigame/games | /宝探しゲーム/宝探し/FPS.cpp | SHIFT_JIS | 913 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | #include "GV.h"
/*
FPSs
...̃W[͎lď̂ł͂ȂAقƂǎQl̂̃R[ĥ܂܂ł...
QlFhttp://dixq.net/g/03_14.html
*/
const int N = 60; //ςTv
const int FPS = 60; //ݒ肵FPS
bool Update(){
if (mCount == 0){ //1t[ڂȂ玞L
mStartTime = GetNowCount();
}
if (mCount == N){ //60t[ڂȂ畽ςvZ
int t = GetNowCount();
mFps = 1000 / ((t - mStartTime) / (float)N);
mCount = 0;
mStartTime = t;
}
mCount++;
return true;
}
void FPSDraw(){
DrawFormatString(600, 0, White, "%.1f", mFps);
}
void Wait(){
int tookTime = GetNowCount() - mStartTime; //
int waitTime = mCount * 1000 / FPS - tookTime; //҂ׂ
if (waitTime > 0){
Sleep(waitTime); //ҋ@
}
}
| true |
4c674ebbca0236c7fc4c17655c686c72a11cab2b | C++ | NicKarlovich/bus_simulator | /project/src/stop.h | UTF-8 | 2,229 | 3.125 | 3 | [
"MIT"
] | permissive | /**
* @file stop.h
*
* @copyright 2019 3081 Staff, All rights reserved.
*/
#ifndef SRC_STOP_H_
#define SRC_STOP_H_
#include <list>
#include <iostream>
#include "src/bus.h"
#include "src/passenger.h"
#include "src/data_structs.h"
class Bus;
/**
* @brief The main class for stops.
*/
class Stop {
public:
/**
* @brief Constructor for a Stop Object.
*
* @param[in] id The identifier of the stop.
* @param[in] longitude The GPS longitude coordinate, not currently used.
* @param[in] latitude The GPS latitude coordinate, not currently used.
*
* @return Stop Object
*/
explicit Stop(int, double = 44.973723, double = -93.235365);
/**
* @brief Gets the identifier of the stop.
*
* @return An integer representing the id of the stop.
*/
int GetId() const;
/**
* @brief Adds a Passenger to the stop.
*
* @param[in] pass The passenger we're going to add to the stop.
*
* @return An integer, value not defined yet.
*/
int AddPassengers(Passenger *);
/**
* @brief Updates the Stop.
*
* @description Calls Update() on all the passenger's at the stop effectively
* increasing all the passengers time_at_stop by 1.
*
* @return void
*/
void Update();
/**
* @brief Writes out a report of the Stop object to the specific output.
*
* @param[in] out The output we'd like our report functions to output to.
*
* @return void
*/
void Report(std::ostream &) const;
/**
* @brief Gets the list of passengers currently at the stop.
*
* @return A pointer to a list of Passenger pointers which is the list of
* passengers that are currently at the stop.
*/
std::list<Passenger *> * GetPassengers();
/**
* @brief A Getter to return the stop's Position struct.
*
* @return A position struct with the stop's latitude-longitude coordiantes.
*/
Position GetPosStruct();
private:
int id_;
std::list<Passenger *> passengers_; // considered array, vector, queue, list
double longitude_;
double latitude_; // are we using long/lat coords?
// derived information - not needed depending on passengers_
// data structure implementation?
// int passengers_present_;
};
#endif // SRC_STOP_H_
| true |
bbc3a2471b4c372e269ac4641c922673c28a6c80 | C++ | wzj1988tv/code-imitator | /data/dataset_2017/dataset_2017_8_formatted_macrosremoved/Shuto/5304486_5697460110360576_Shuto.cpp | UTF-8 | 2,182 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef pair<long long int, long long int> PI;
typedef pair<long long int, long long int> PI;
inline bool ok_1(long long int x, long long int unit) {
x *= 10;
unit *= 10;
long long int near = x / unit;
if (x >= unit * near * 9 / 10 && x <= unit * near * 11 / 10) {
return true;
}
++near;
if (x >= unit * near * 9 / 10 && x <= unit * near * 11 / 10) {
return true;
}
return false;
}
inline PI get_range(long long int x, long long int unit) {
PI res;
res.second = (x * 10 / 9) / unit;
res.first = (x * 10 / 11) / unit;
if ((x * 10 / 11) % unit > 0)
res.first++;
return res;
}
inline bool has_common(PI r1, PI r2) {
return r1.second >= r2.first && r2.second >= r1.first;
}
inline bool ok_2(PI x, PI unit) {
PI range1 = get_range(x.first, unit.first);
PI range2 = get_range(x.second, unit.second);
// p4(range1.F, range1.S, range2.F, range2.S);
return has_common(range1, range2);
}
inline void solve() {
long long int n, p;
cin >> n >> p;
vector<vector<long long int>> a(n, vector<long long int>(p));
vector<long long int> r(n);
for (long long int i = 0; i < ((long long int)(n)); i++) {
cin >> r[i];
}
for (long long int i = 0; i < ((long long int)(n)); i++) {
for (long long int j = 0; j < ((long long int)(p)); j++)
cin >> a[i][j];
}
if (n == 1) {
long long int res = 0;
for (long long int i = 0; i < ((long long int)(p)); i++) {
if (ok_1(a[0][i], r[0])) {
++res;
}
}
cout << res << endl;
} else if (n == 2) {
long long int res = 0;
do {
long long int tres = 0;
for (long long int i = 0; i < ((long long int)(p)); i++) {
if (ok_2(make_pair(a[0][i], a[1][i]), make_pair(r[0], r[1]))) {
++tres;
}
}
res = max(res, tres);
} while (next_permutation(a[1].begin(), a[1].end()));
cout << res << endl;
} else {
cout << 1 << endl;
}
}
int main() {
long long int t;
cin >> t;
for (long long int case_num = 0; case_num < ((long long int)(t));
case_num++) {
cout << "Case #" << case_num + 1 << ": ";
solve();
}
return 0;
}
| true |
a7fe317d2c7c936400e749bdeef887a972a0c783 | C++ | RasmusKarlsson/Raytracer | /raytrace/Objects.h | UTF-8 | 622 | 2.671875 | 3 | [] | no_license | #pragma once
#include "glm.hpp"
#include "Shape.h"
#include "Sphere.h"
#include "Plane.h"
#include <vector>
#include <iostream>
#include <iterator>
class Objects
{
public:
/*
std::vector<Sphere> spheres;
std::vector<Plane> planes;
*/
std::vector<Shape*> shapes;
Shape* s;
int objectID;
Objects(void);
bool createNewSphere(const glm::mat4 ltw, glm::vec3 c, const float r);
bool createNewPlane(glm::vec3 p0, glm::vec3 p1, glm::vec3 p2, glm::vec3 p3);
bool intersection(const glm::vec3 rayDirection, const glm::vec3 rayOrigPos, float &tMin, glm::vec3 &intersectionPoint, glm::vec3 &n, int &shapeID);
};
| true |
fcbbce27fa6557b207bf01464daca71ba4758ae1 | C++ | VB6Hobbyst7/vault_repo | /ezEnrollment/AdvancePCS/Recap2/Recap2/src/Matrix.cpp | UTF-8 | 2,154 | 2.515625 | 3 | [] | no_license | #include <client/Matrix.h>
#include <client/Messages.h>
//#include <client/StdAfx.h>
//#include <client/StringParser.h>
#include <wx/tokenzr.h>
SimpleVector::SimpleVector(wxString& str, wxString& colSeparator)
{
m_storage = new wxArrayString();
#if 1
wxStringTokenizer st(str, colSeparator, wxTOKEN_RET_EMPTY_ALL);
if ( str.IsEmpty() ) {
GetStorage()->Add(str);
} else {
while ( st.HasMoreTokens() ) {
GetStorage()->Add(st.GetNextToken());
}
}
#else
if ( wxString(COMMA_COLUMN_SEPARATOR).Cmp(colSeparator.c_str) == 0 ) {
LPCTSTR strLine = _T( str.c_str() );
CStringParser values;
values.Parse( strLine, poCsvLine );
for (int i=0; i<values.GetCount(); i++) {
GetStorage()->Add( wxString( values.GetAt(i) ) );
}
} else {
wxStringTokenizer st(str, colSeparator, wxTOKEN_RET_EMPTY_ALL);
if ( str.IsEmpty() ) {
GetStorage()->Add(str);
} else {
while ( st.HasMoreTokens() ) {
GetStorage()->Add(st.GetNextToken());
}
}
}
#endif
}
SimpleVector::~SimpleVector()
{
delete m_storage;
}
long SimpleVector::GetSize()
{
return GetStorage()->GetCount();
}
wxString& SimpleVector::GetDataAt(long index)
{
if ( index < GetSize() ) {
return GetStorage()->Item(index);
} else {
throw wxString(DESCRIPTOR_INVALID_INDEX);
}
}
//
// StringMatrix
//
StringMatrix::StringMatrix()
{
m_vectors = new VectorArray();
}
StringMatrix::~StringMatrix()
{
for (unsigned int i=0; i<GetVectors()->GetCount(); i++) {
Vector *v = IGetVector(i);
delete v;
}
delete m_vectors;
}
StringMatrix::Load(wxArrayString& strs, wxString& colSeparator)
{
for (unsigned int i=0; i<strs.GetCount(); i++) {
Vector *v = new SimpleVector(strs.Item(i), colSeparator);
GetVectors()->Add(v);
}
}
long StringMatrix::GetSize()
{
return GetVectors()->GetCount();
}
Vector& StringMatrix::GetVector(long index){
if ( index < GetSize() ) {
return *(IGetVector(index));
} else {
throw wxString(DESCRIPTOR_INVALID_INDEX);
}
}
| true |
930e026d566eb64c410da731aba875cb151cf5ed | C++ | maicolknales/proyecto_progra_3 | /Menus/Menus.cpp | UTF-8 | 6,952 | 3.15625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
//Menu Administrador del Sistema
char opcion,subopcion;
do{
system("cls");
cout<<"|==============================================================|"<<endl;
cout<<"| MENU ADMINISTRADOR DEL SISTEMA |"<<endl;
cout<<"|==============================================================|"<<endl;
cout<<"| A- Salir |"<<endl;
cout<<"| B- Administrar Usuarios del Sistema |"<<endl;
cout<<"| C- Administrar Informacion General de la Empresa |"<<endl;
cout<<"| D- Administrar Gerencias, Departamentos, Areas de la Empresa |"<<endl;
cout<<"| E- Administrar Puestos de la Empresa |"<<endl;
cout<<"| F- Administrar Bitacora del Sistema |"<<endl;
cout<<"|==============================================================|"<<endl;
cout<<endl<<"Opcion:";
cin>>opcion;
//evaluar opciones
switch(opcion){
case 'b':
//char subopcion;
do{
system("cls");
cout<<"|==================================|"<<endl;
cout<<"| ADMINISTRAR USUARIOS DEL SISTEMA |"<<endl;
cout<<"|==================================|"<<endl;
cout<<"| A- Salir |"<<endl;
cout<<"| B- Agregar Usuario al Sistemas |"<<endl;
cout<<"| C- Listar Usuarios del Sistema |"<<endl;
cout<<"| D- Modificar Usuario del Sistema |"<<endl;
cout<<"| E- Eliminar Usuario del Sistema |"<<endl;
cout<<"|==================================|"<<endl;
cout<<endl<<"Opcion:";
cin>>subopcion;
switch(subopcion){
case 'b':
system("cls");
system("pause");
break;
case 'c':
system("cls");
system("pause");
break;
case 'd':
system("cls");
system("pause");
break;
case 'e':
system("cls");
system("pause");
break;
case 'a':
cout<<endl;
break;
default: system("cls");
cout<<"Esta opcion no existe.../n Elija de nuevo una opcion valida"<<endl;
system("pause");
break;
}
}while(subopcion != 'a');
break;
case 'c':
system("cls");
system("pause");
break;
case 'd':
do{
system("cls");
cout<<"|===========================================================|"<<endl;
cout<<"| Administrar Gerencias, Departamentos, Areas de la Empresa |"<<endl;
cout<<"|===========================================================|"<<endl;
cout<<"| A- Salir |"<<endl;
cout<<"| B- Administrar Gerencias |"<<endl;
cout<<"| C- Administrar Departamentos |"<<endl;
cout<<"| D- Administrar Areas |"<<endl;
cout<<"|===========================================================|"<<endl;
cout<<endl<<"Opcion:";
cin>>subopcion;
switch(subopcion){
case 'b':
system("cls");
system("pause");
break;
case 'c':
system("cls");
system("pause");
break;
case 'd':
system("cls");
system("pause");
break;
case 'a':
cout<<endl;
break;
default: system("cls");
cout<<"Esta opcion no existe.../n Elija de nuevo una opcion valida"<<endl;
system("pause");
break;
}
}while(subopcion != 'a');
break;
case 'e':
do{
system("cls");
cout<<"|===================================|"<<endl;
cout<<"| Administrar Puestos de la Empresa |"<<endl;
cout<<"|===================================|"<<endl;
cout<<"| A- Salir |"<<endl;
cout<<"| B- xxx |"<<endl;
cout<<"| C- xxx |"<<endl;
cout<<"| D- xxx |"<<endl;
cout<<"|===================================|"<<endl;
cout<<endl<<"Opcion:";
cin>>subopcion;
switch(subopcion){
case 'b':
system("cls");
system("pause");
break;
case 'c':
system("cls");
system("pause");
break;
case 'd':
system("cls");
system("pause");
break;
case 'a':
cout<<endl;
break;
default: system("cls");
cout<<"Esta opcion no existe.../n Elija de nuevo una opcion valida"<<endl;
system("pause");
break;
}
}while(subopcion != 'a');
break;
case 'f':
system("cls");
cout<<"Bitacora de del Sistema Vacia"<<endl;
system("pause");
break;
case 'a':
cout<<endl;
break;
default: system("cls");
cout<<"Esta opcion no existe.../n Elija de nuevo una opcion valida"<<endl;
system("pause");
break;
}
}while(opcion != 'a');
return 0;
}
| true |
999dd19da78be0bab793636dbe87e82be0fd3dd4 | C++ | HCMY/UnCategoticalableAlgorithm | /Leetcode/BinarySearch/Medium/FindFirstandLastPositionofElementinSortedArray.cc | UTF-8 | 770 | 3.328125 | 3 | [] | no_license | class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left = 0;
int right = nums.size()-1;
bool left_flag = 1;
bool right_flag = 1;
int start = -1;
int end = -1;
vector<int> ans;
while((left_flag||right_flag) &&(left<right))){
if(left_flag && nums[left++]==target){start=left-1;left--;left_flag=0;}
if(right_flag && nums[right--]==target){end=right+1;right++;right_flag=0;}
}
ans.push_back(start);
ans.push_back(end);
return ans;
}
};
int int main(int argc, char const *argv[]) {
Solution solu;
vector<int> arr = {5,7,7,8,8,10};
vector<int> ans = solu.searchRange(arr,5);
for(auto item:arr)
cout<<item<<" ";
return 0;
}
| true |
85eb22ba67d149adbd9559b2fcb1e28f0af72b2f | C++ | alandefreitas/Evolutionary_Computation_Course | /class_02/naive_EA.hpp | UTF-8 | 5,621 | 2.90625 | 3 | [] | no_license | //
// Created by Alan de Freitas on 12/04/2018.
//
#include "naive_EA.h"
template <typename problem, typename solution>
std::default_random_engine naive_EA<problem,solution>::_generator = std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count());
template <typename problem, typename solution>
naive_EA<problem,solution>::naive_EA(problem &p) :
_problem(p),
// Parameters
_max_generations(1000),
_population_size(200),
_parents_per_children(2),
_children_proportion(7),
_crossover_probability(0.9),
_mutation_strength(0.1),
// Data
_current_generation(0)
{
_mutation_strength = (1.0/this->_problem.size());
// Initialize population
this->_population.reserve(_population_size);
for (int i = 0; i < this->_population_size; ++i) {
this->_population.emplace_back(this->_problem);
}
}
template <typename problem, typename solution>
void naive_EA<problem,solution>::run() {
for (int i = 0; i < this->_max_generations; ++i) {
evolutionary_cycle();
}
// To be replaced by:
// while (!stopping_criteria()){
// evolutionary_cycle();
// }
}
template <typename problem, typename solution>
void naive_EA<problem,solution>::run(size_t iterations) {
for (int i = 0; i < iterations; ++i) {
evolutionary_cycle();
}
}
template <typename problem, typename solution>
void naive_EA<problem,solution>::evolutionary_cycle() {
display_status();
evaluate(this->_population);
std::vector<size_t> parent_position = selection(this->_population, n_of_selection_candidates(),selection_strategy::uniform);
std::vector<individual> children = reproduction(this->_population, parent_position);
evaluate(children);
std::vector<size_t> children_position = selection(this->_population, this->_population_size,selection_strategy::truncate);
this->_population = update_population(children,children_position);
}
template <typename problem, typename solution>
double naive_EA<problem,solution>::best_fx() {
if (this->_problem.is_minimization()) {
return -this->_best_fx;
} else {
return this->_best_fx;
}
}
template <typename problem, typename solution>
void naive_EA<problem,solution>::evaluate(std::vector<individual>& population){
for (individual& item : population) {
item.fx = item.evaluate(this->_problem);
if (this->_problem.is_minimization()){
item.fx = -item.fx;
}
if (item.fx > this->_best_fx){
this->_best_fx = item.fx;
}
}
};
template <typename problem, typename solution>
size_t naive_EA<problem,solution>::n_of_selection_candidates(){
return this->_population_size*
this->_parents_per_children*
this->_children_proportion;
};
template <typename problem, typename solution>
std::vector<size_t> naive_EA<problem,solution>::selection(std::vector<individual>& population,
size_t n_of_candidates,
selection_strategy s){
switch (s){
case selection_strategy::uniform: {
std::vector<size_t> parent_position(n_of_candidates);
std::uniform_int_distribution<size_t> pos_d(0,population.size()-1);
for (size_t& position : parent_position) {
position = pos_d(naive_EA::_generator);
}
return parent_position;
}
case selection_strategy::truncate: {
std::vector<size_t> parent_position(n_of_candidates);
std::partial_sort(population.begin(),
population.begin() + parent_position.size(),
population.end(),
[](individual& a, individual& b){
return a.fx > b.fx;
}
);
std::iota(parent_position.begin(),parent_position.end(),0);
return parent_position;
}
}
};
template <typename problem, typename solution>
std::vector<typename naive_EA<problem,solution>::individual> naive_EA<problem,solution>::reproduction(std::vector<individual>& population, std::vector<size_t>& parent_position){
std::uniform_real_distribution<double> r(0.0,1.0);
std::vector<individual> children;
for (int j = 0; j < parent_position.size(); j += 2) {
if (r(naive_EA::_generator) < this->_crossover_probability) {
// Crossover
children.push_back(
population[parent_position[j]].s.crossover(
this->_problem,
population[parent_position[j+1]].s
)
);
} else {
// Mutation
children.push_back(population[parent_position[j]]);
children.back().s.mutation(this->_problem,this->_mutation_strength);
}
}
return children;
}
template <typename problem, typename solution>
std::vector<typename naive_EA<problem,solution>::individual> naive_EA<problem,solution>::update_population(std::vector<individual>& population, std::vector<size_t>& positions) {
std::vector<individual> r;
r.reserve(population.size());
for (size_t position : positions) {
r.push_back(population[position]);
}
return r;
}
template <typename problem, typename solution>
void naive_EA<problem,solution>::display_status() {
std::cout << "Generation #" << ++_current_generation;
std::cout << " - Best_fx: " << this->best_fx() << std::endl;
}
| true |
70bcf3b4e451aa4141e520cef9d41c765fd671f6 | C++ | exokitxr/aardvark | /src/tools/systools.cpp | UTF-8 | 2,091 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | #include "tools/systools.h"
#include <windows.h>
#include <tools/logging.h>
#include <tools/stringtools.h>
namespace tools
{
static std::string formatWindowsError( LONG error )
{
LPWSTR buffer = nullptr;
FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, 0, (LPWSTR)&buffer, 0, nullptr );
std::string result = WStringToUtf8( buffer );
LocalFree( buffer );
return result;
}
bool registerURLSchemeHandler( const std::string & urlScheme, const std::string & commandToRun)
{
std::string classPath = "Software\\Classes\\" + urlScheme;
HKEY hSchemeKey;
LONG error = RegCreateKeyExA( HKEY_CURRENT_USER, classPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hSchemeKey, NULL );
if( error != ERROR_SUCCESS )
{
LOG( ERROR ) << "Failed to register URI scheme " << urlScheme << ": " << formatWindowsError( error );
return false;
}
std::string baseValue = "URL:" + urlScheme + " Protocol";
if ( ERROR_SUCCESS != RegSetKeyValueA( hSchemeKey, nullptr, nullptr, REG_SZ, baseValue.c_str(), (DWORD)( baseValue.size() + 1 ) ) )
{
LOG( ERROR ) << "Failed to set base value for URI scheme " << urlScheme;
return false;
}
if ( ERROR_SUCCESS != RegSetKeyValueA( hSchemeKey, nullptr, "URL Protocol", REG_SZ, "", 1 ) )
{
LOG( ERROR ) << "Failed to set protocol value for URI scheme " << urlScheme;
return false;
}
HKEY hCommandKey;
error = RegCreateKeyExA( hSchemeKey, "Shell\\Open\\Command", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hCommandKey, NULL );
if ( error != ERROR_SUCCESS )
{
LOG( ERROR ) << "Failed create command key for " << urlScheme;
return false;
}
if ( ERROR_SUCCESS != RegSetKeyValueA( hCommandKey, nullptr, nullptr, REG_SZ, commandToRun.c_str(), (DWORD)( commandToRun.size() + 1 ) ) )
{
LOG( ERROR ) << "Failed to set command value for URI scheme " << urlScheme;
return false;
}
return true;
}
void invokeURL( const std::string& url )
{
::ShellExecuteA( nullptr, url.c_str(), nullptr, nullptr, nullptr, SW_SHOW );
}
} | true |
2a1c90fc3295bd31f5d0c77347b5930083d62ad9 | C++ | Merna177/ProblemSolving | /Medium/MinPath_M.cpp | UTF-8 | 777 | 3.046875 | 3 | [] | no_license | //Medium
// solve-->https://leetcode.com/problems/minimum-falling-path-sum/
class Solution {
public:
int dp[101][101];
int minFallingPathSum(vector<vector<int>>& A) {
int value=1e9;
memset(dp,-1,sizeof dp);
for(int i=0;i<A[0].size();i++){
value = min(value,go(0,i,A));
}
return value;
}
int go(int row,int column,vector<vector<int>>& A){
if(row>=A.size() )return 0;
if(column >= A[0].size())return 1e9;
if(dp[row][column]!=-1)return dp[row][column];
int first = A[row][column]+go(row+1,column+1,A);
int second = A[row][column]+go(row+1,column-1,A);
int third = A[row][column]+go(row+1,column,A);
return dp[row][column]=min(first,min(second,third));
}
};
| true |
a89b856190dd43f4a768b58be82c3a2301a053c5 | C++ | rensfo/QtOrm | /QtOrm/Mappings/SubClassMap.cpp | UTF-8 | 1,751 | 2.75 | 3 | [
"MIT"
] | permissive | #include "SubClassMap.h"
namespace QtOrm {
namespace Mapping {
SubClassMap::SubClassMap(QObject *parent) : ClassMapBase(parent) {
}
QSharedPointer<ClassMapBase> SubClassMap::getSuperClass() const {
return superClass;
}
void SubClassMap::setSuperClass(const QSharedPointer<ClassMapBase>&value) {
superClass = value;
}
bool SubClassMap::isSubclass() {
return true;
}
InheritanceType SubClassMap::getInheritanceType() const {
return inheritanceType;
}
QSharedPointer<ClassMapBase> SubClassMap::getBaseClass() const {
if(superClass->isSubclass()) {
return superClass->toSubclass()->getBaseClass();
}
return superClass;
}
bool SubClassMap::isClassTableInheritance(const QSharedPointer<ClassMapBase>&classBase) {
return classBase->isSubclass() && classBase->toSubclass()->getInheritanceType() == InheritanceType::ClassTable;
}
QMap<QString, QSharedPointer<PropertyMap>> SubClassMap::getAllProperties() {
QMap<QString, QSharedPointer<PropertyMap>> allProperties = superClass->getProperties();
for(auto prop : getProperties().toStdMap()){
allProperties.insert(prop.first, prop.second);
}
return allProperties;
}
QString SubClassMap::getClassNameByProperty(const QString&property){
if(getProperties().keys().contains(property)) {
return getClassName();
}
if(superClass->isSubclass()) {
return superClass->toSubclass()->getClassNameByProperty(property);
} else {
if(superClass->getProperties().keys().contains(property)){
return superClass->getClassName();
}
}
return QString::null;
}
void SubClassMap::setInheritanceType(const InheritanceType&value) {
inheritanceType = value;
}
QString SubClassMap::getSuperClassName() const {
return superClass->getClassName();
}
}
}
| true |
28ab823589f1900b0de4132e023ea40ae81491e0 | C++ | latusikl/pacman | /pacmanRemake/mapGeneratorModule/mapGeneratorPlacer.cpp | WINDOWS-1250 | 1,540 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "mapGeneratorPlacer.h"
Vector2f mapGeneratorPlacer::getPosition()
{
return rect.getPosition();
}
bool mapGeneratorPlacer::checkMovement()
{
return movable;
}
bool mapGeneratorPlacer::isBonus()
{
return bonus;
}
bool mapGeneratorPlacer::isSpecialBonus()
{
return specialBonus;
}
void mapGeneratorPlacer::stopMovement()
{
movable = false;
}
void mapGeneratorPlacer::update()
{
if (movable)
{
if (Keyboard::isKeyPressed(Keyboard::Left) && getPosition().x >= 0) //W lewo
{
velocity.x = -rectVelocity;
}
else if (Keyboard::isKeyPressed(Keyboard::Right) && getPosition().x <= 600) //W prawo
{
velocity.x = rectVelocity;
}
//Ruch Pacmana w gre lub w d
else if (Keyboard::isKeyPressed(Keyboard::Up) && getPosition().y >= 0)
{
velocity.y = -rectVelocity;
}
else if (Keyboard::isKeyPressed(Keyboard::Down) && getPosition().y <= 800)
{
velocity.y = rectVelocity;
}
else if (Keyboard::isKeyPressed(Keyboard::Enter))
{
stopMovement();
}
else
{
velocity.y = 0;
velocity.x = 0;
}
rect.move(velocity);
}
}
void mapGeneratorPlacer::makeBonus()
{
rect.setFillColor(Color::Yellow);
this->bonus = true;
}
void mapGeneratorPlacer::makeSpecialBonus()
{
rect.setFillColor(Color::Magenta);
this->specialBonus = true;
}
void mapGeneratorPlacer::draw(RenderTarget& target, RenderStates state) const
{
target.draw(rect, state);
}
mapGeneratorPlacer::mapGeneratorPlacer()
{
rect.setSize(size);
rect.setFillColor(Color::Green);
rect.setPosition(startPosition);
}
| true |
8d7c988c7134c64f01e0d164f1d63cefbfca74a0 | C++ | leon-schi/iot-nixie-tube-clock | /time_server.h | UTF-8 | 5,001 | 2.75 | 3 | [] | no_license | #include <ESP8266WebServer.h>
#include "time_html.h"
#include "wifi_credentials.h"
#ifndef SERVER_H
#define SERVER_H
class ClockServer {
private:
ESP8266WebServer* server;
ClockController* controller;
int mode = clockMode;
public:
ClockServer(ClockController* c) {
server = new ESP8266WebServer(80);
controller = c;
server->on("/", [this](){
server->send(200, "text/html", steering_html);
});
// Mode switches
server->on("/switch/clock", [this](){
controller->setMode(clockMode);
server->send(200, "text/plain", "Switched to clock mode");
});
server->on("/switch/stopwatch", [this](){
controller->setMode(stopwatchMode);
server->send(200, "text/plain", "Switched to stopwatch mode");
});
server->on("/switch/random", [this](){
controller->setMode(randomMode);
server->send(200, "text/plain", "Switched to random mode");
});
server->on("/switch/off", [this](){
controller->setMode(off);
server->send(200, "text/plain", "Switched to off mode");
});
// General Info
server->on("/timezone", [this](){
timezone_rep timezone = controller->getTimezone();
server->send(200, "application/json", "{\"utcOffset\": " + String(timezone.utcOffset) + ", \"name\": \"" + String(timezone.name) + "\"}");
});
server->on("/mode", [this](){
Mode mode = controller->getMode();
if (mode == clockMode)
server->send(200, "text/plain", "clock");
else if (mode == stopwatchMode)
server->send(200, "text/plain", "stopwatch");
else if (mode == randomMode)
server->send(200, "text/plain", "random");
else
server->send(200, "text/plain", "off");
});
server->on("/network", [this]() {
server->send(200, "text/plain", SSID);
});
server->on("/time", [this]() {
server->send(200, "text/plain", controller->getCurrentTime());
});
server->on("/sync-interval", [this]() {
String value = String(controller->getUpdateInterval());
server->send(200, "text/plain", value);
});
// Set Parameters
server->on("/set/timezone/name", [this](){
if (server->hasArg("plain")) {
timezone_rep timezone = controller->getTimezone();
timezone.name = server->arg("plain");
controller->setTimezone(timezone);
server->send(200, "text/plain", "success");
}
server->send(400, "text/plain", "value not supplied");
});
server->on("/set/timezone/utcOffset", [this](){
if (server->hasArg("plain")) {
timezone_rep timezone = controller->getTimezone();
timezone.utcOffset = server->arg("plain").toInt();
controller->setTimezone(timezone);
server->send(200, "text/plain", "success");
}
server->send(400, "text/plain", "value not supplied");
});
server->on("/set/sync-interval", [this](){
if (server->hasArg("plain")) {
controller->setUpdateInterval(server->arg("plain").toInt());
server->send(200, "text/plain", "success");
}
server->send(400, "text/plain", "value not supplied");
});
server->on("/set/random-seed", [this](){
controller->getRandomStrategy()->init();
server->send(200, "text/plain", "success");
});
// Stopwatch steering
server->on("/stopwatch/reset", [this](){
controller->getStopwatchStrategy()->reset();
server->send(200, "text/plain", "stopwatch resetted");
});
server->on("/stopwatch/start", [this](){
controller->getStopwatchStrategy()->start();
server->send(200, "text/plain", "stopwatch started");
});
server->on("/stopwatch/stop", [this](){
controller->getStopwatchStrategy()->stop();
server->send(200, "text/plain", "stopwatch stopped");
});
server->on("/stopwatch/round", [this](){
server->send(200, "text/plain", controller->getStopwatchStrategy()->getCurrentTime());
});
server->begin();
}
void handleClient() {
server->handleClient();
}
};
#endif | true |
1996a1e01280a22a792d2761227bc4b3569f426e | C++ | SVilcaLim03/cc2-proyect | /src/game_object.cpp | UTF-8 | 852 | 2.609375 | 3 | [] | no_license | #include "game_object.hpp"
GameObject::GameObject(Object *&&object, int &&x, int &&y)
: object_(object), animation_(nullptr), location_(new Location(x, y)),
observer_(nullptr) {}
GameObject::~GameObject() {
delete animation_;
delete location_;
delete object_;
}
void GameObject::SetAnimation(
std::string sprite_path, std::map<int, std::pair<SDL_Rect, int>> sprite_map,
SDL_Renderer *renderer) {
animation_ = new Animation(object_, sprite_path, sprite_map, renderer);
}
Location *&GameObject::GetLocation() { return location_; }
Animation *GameObject::GetAnimation() { return animation_; }
Object *GameObject::GetObject() { return object_; }
void GameObject::SetObserver(Observer *&&observer, Observable *observable) {
observer_ = observer;
observer_->SetObservable(observable);
observable->AddObserver(observer_);
}
| true |
ed42c72550e56e8ca4c06158686f4039513fbfad | C++ | JianHangChen/LeetCode | /157. Read N Characters Given Read4.cpp | UTF-8 | 1,921 | 3.296875 | 3 | [] | no_license |
// !!! sol2, gy, O(n), O(1), read all 4 * times, and then use min(ibuf, n) to get the smallest size
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
int ibuf = 0;
for(int i = 0; i <= n / 4; i++){ // if n == 16-> n / 4 = 4
int cur = read4(buf+ibuf);
ibuf += cur;
if(cur == 0) break;
}
return min(ibuf, n);
}
};
// !!!!!!! sol1.1, revised to for loop, O(n), O(4), use extra buf4
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
char buf4[4];
int ibuf4 = 0, buf4len = 0;
for(int i = 0; i < n; i++){
if(buf4len == 0){
buf4len = read4(buf4);
ibuf4 = 0;
if(buf4len == 0) return i;
}
buf[i] = buf4[ibuf4++];
buf4len--;
}
return n;
}
};
// sol1, my, O(n), O(4), using extra buf4 to store tmp result
class Solution {
public:
/**
* @param buf Destination buffer
* @param n Number of characters to read
* @return The number of actual characters read
*/
int read(char *buf, int n) {
int ibuf = 0, ibuf4 = 0;
char buf4[4];
int buf4len = 0;
int i = 0;
while( i < n ){
if(buf4len > 0){
buf4len--;
buf[i++] = buf4[ibuf4++];
}
else{
buf4len = read4(buf4);
ibuf4 = 0;
if(buf4len == 0) break;
}
}
return i;
}
};
| true |
03aa7a4559a890b8b973d8e6619de95a606074a8 | C++ | khovanskiy/Rush | /common/bullet.h | UTF-8 | 1,023 | 2.75 | 3 | [] | no_license | #ifndef BULLET_H
#define BULLET_H
#include "physicsobject.h"
#include <QString>
class Bullet : public PhysicsObject
{
int bullet_type;
PhysicsObject* source;
double width, height;
double damage;
public:
static const int BULLET;
static const int MISSILE;
static const int CUT;
Bullet(int id, Vector2D r, Vector2D speed, double mass, int bullet_type,
double width, double height, double dt, double time_to_live);
virtual ~Bullet();
void setDamage(double damage);
double getDamage() const;
GameObjectType getFamilyId();
double getWidth() { return width;}
double getHeight() { return height;}
void setSource(PhysicsObject* source);
PhysicsObject* getSource() const;
virtual CrossingResult2D collidesWith(PhysicsObject *other);
virtual int getBulletType();
virtual void applyCollision(const Collision &collision, double dt);
virtual void calculateInnerState(double dt);
virtual bool isProjectile();
};
#endif // BULLET_H
| true |
48d89f24c6c1c90c1e1d4a2f7cca7c58fe3ca32b | C++ | andrei-toterman/oop_lab | /5-6/tests.cpp | UTF-8 | 6,820 | 2.96875 | 3 | [] | no_license | #include "tests.h"
#include "controller.h"
#include "dynamicarray.h"
#include "repository.h"
#include <cassert>
void test_dv_add() {
DynamicVector<int> vector;
assert(vector.size() == 0);
vector.add(1);
assert(vector.size() == 1);
assert(vector[0] == 1);
}
void test_dv_remove() {
DynamicVector<int> vector;
vector.add(1);
vector.remove(0);
assert(vector.size() == 0);
try {
vector.remove(0);
assert(false);
} catch (...) { assert(true); }
}
void test_dv_index_operator() {
DynamicVector<int> vector;
vector.add(1);
assert(vector[0] == 1);
try {
vector[1];
assert(false);
} catch (...) { assert(true); }
}
void test_dv_assign_operator() {
DynamicVector<int> vector;
vector.add(1);
DynamicVector<int> vector2;
vector2 = vector;
assert(vector2.size() == 1);
assert(vector2[0] == 1);
}
void test_dv_plus_operator() {
DynamicVector<int> vector;
assert(vector.size() == 0);
vector + 1;
2 + vector;
assert(vector.size() == 2);
assert(vector[0] == 1);
assert(vector[1] == 2);
}
void test_dv() {
test_dv_add();
test_dv_remove();
test_dv_index_operator();
test_dv_assign_operator();
test_dv_plus_operator();
}
void test_repo_add() {
MovieRepo repo;
repo.add(Movie("a", "b", 1, 2, "c"));
repo.add(Movie("d", "e", 3, 4, "f"));
repo.add(Movie("g", "e", 5, 6, "i"));
assert(repo.get_movies().size() == 3);
assert(repo.get_genres().size() == 2);
repo.add(Movie("j", "k", 7, 8, "l"));
assert(repo.get_movies().capacity() == 6);
}
void test_repo_remove() {
MovieRepo repo;
repo.add(Movie("a", "b", 1, 2, "c"));
repo.add(Movie("d", "e", 3, 4, "f"));
repo.remove(0);
assert(repo.size() == 1);
assert(repo.get_genres().size() == 1);
try {
repo.remove(1);
assert(false);
} catch (...) { assert(true); }
}
void test_repo_index_operator() {
MovieRepo repo;
Movie m{"a", "b", 1, 2, "c"};
repo.add(m);
assert(repo.get_movies()[0] == m);
try {
repo.get_movies()[1];
assert(false);
} catch (...) { assert(true); }
}
void test_repo_find() {
MovieRepo repo;
repo.add(Movie("a", "b", 1, 2, "c"));
assert(repo.find("a_1") >= 0);
assert(repo.find("a_2") == -1);
}
void test_repo_assign_operator() {
MovieRepo repo;
repo.add(Movie("a", "b", 1, 2, "c"));
MovieRepo new_repo;
new_repo = repo;
assert(new_repo.size() == 1);
assert(new_repo.get_movies().capacity() == 3);
assert(new_repo[0] == repo[0]);
}
void test_repo_update() {
MovieRepo repo;
repo.add(Movie("a", "b", 1, 2, "c"));
repo.update(0, Movie{"c", "d", 2, 3, "e"});
assert(repo.find("c_2") >= 0);
assert(repo.find("a_1") == -1);
}
void test_repo_filter() {
MovieRepo repo;
repo.populate();
MovieRepo filtered{repo.filter_by([](Movie m) { return m.get_genre() == "action"; })};
assert(filtered.size() == 3);
assert(filtered[0].get_id() == "Avengers_2019");
assert(filtered[1].get_id() == "Avengers_2018");
assert(filtered[2].get_id() == "Batman_2008");
}
void test_repo() {
test_repo_add();
test_repo_remove();
test_repo_index_operator();
test_repo_assign_operator();
test_repo_find();
test_repo_update();
test_repo_filter();
}
void test_ctrl_add() {
MovieRepo database;
MovieRepo watchlist;
Controller ctrl{database, watchlist};
ctrl.database_add("a", "b", 1, 2, "www.google.com");
assert(ctrl.get_database().size() == 1);
try {
ctrl.database_add("a", "b", 1, 2, "www.google.com");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_add("", "a", 1, 2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_add("a", "", 1, 2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_add("a", "b", -1, 2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_add("a", "b", 1, -2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_add("a", "b", 1, 2, "");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_add("a", "b", 1, 2, "dbkjgrbg");
assert(false);
} catch (...) { assert(true); }
ctrl.watchlist_add(database[0]);
assert(ctrl.get_watchlist().size() == 1);
}
void test_ctrl_remove() {
MovieRepo database;
MovieRepo watchlist;
Controller ctrl{database, watchlist};
ctrl.database_add("a", "b", 1, 2, "www.google.com");
ctrl.database_add("b", "b", 1, 2, "www.google.com");
ctrl.watchlist_add(database[0]);
ctrl.watchlist_add(database[1]);
ctrl.database_remove("a_1");
assert(ctrl.get_database().size() == 1);
assert(ctrl.get_watchlist().size() == 1);
ctrl.watchlist_remove("b_1", true);
assert(ctrl.get_watchlist().size() == 0);
try {
ctrl.database_remove("adwada");
assert(false);
} catch (...) { assert(true); }
}
void test_ctrl_update() {
MovieRepo database;
MovieRepo watchlist;
Controller ctrl{database, watchlist};
Movie m{"b", "c", 2, 3, "www.reddit.com"};
ctrl.database_add("a", "b", 1, 2, "www.google.com");
ctrl.watchlist_add(database[0]);
ctrl.database_update("a_1", "b", "c", 2, 3, "www.reddit.com");
assert(database[0] == m);
assert(watchlist[0] == m);
try {
ctrl.database_update("a_1", "b", "c", 2, 3, "www.reddit.com");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_update("b_2", "", "a", 1, 2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_update("b_2", "a", "", 1, 2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_update("b_2", "a", "b", -1, 2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_update("b_2", "a", "b", 1, -2, "www.");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_update("b_2", "a", "b", 1, 2, "");
assert(false);
} catch (...) { assert(true); }
try {
ctrl.database_update("b_2", "a", "b", 1, 2, "dbkjgrbg");
assert(false);
} catch (...) { assert(true); }
}
void test_ctrl() {
test_ctrl_add();
test_ctrl_remove();
test_ctrl_update();
}
| true |
6a37d73a89f35a30fa74f74514e8fca71f88f00d | C++ | JaykayChoi/AlgorithmicProblem | /AlgorithmicProblem/Solved/Online Judge/USACO/1_3_MixingMilk.cpp | UTF-8 | 921 | 2.859375 | 3 | [] | no_license | /*
ID: jkchoik1
PROG: milk
LANG: C++11
*/
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
//http://train.usaco.org/usacoprob2?a=qxjyGzruutH&S=milk
int buyMilk(multimap<int, int>& sellers, int needMilk)
{
int cost = 0;
int leftBuyingMilk = needMilk;
for (multimap<int, int>::iterator it = sellers.begin(); it != sellers.end(); it++)
{
if (it->second <= leftBuyingMilk)
{
leftBuyingMilk -= it->second;
cost += it->second * it->first;
}
else
{
cost += leftBuyingMilk * it->first;
break;
}
}
return cost;
}
int sub_main()
{
ofstream fout("milk.out");
ifstream fin("milk.in");
int needMilk, numFarmers;
fin >> needMilk >> numFarmers;
multimap<int, int> sellers;
for (int i = 0; i < numFarmers; i++)
{
int price, amount;
fin >> price >> amount;
sellers.insert(make_pair(price, amount));
}
fout << buyMilk(sellers, needMilk) << endl;
return 0;
}
| true |
46e507b4fd98a9dcc2fa70f3dac9572449973818 | C++ | krofna/uva | /10943.cpp | UTF-8 | 398 | 2.515625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int dp[101][101];
int f(int n, int k)
{
if (n == 0 || k == 1)
return 1;
if (dp[n][k])
return dp[n][k];
int sum = 0;
for (int i = 0; i <= n; ++i)
sum += f(n - i, k - 1) % 1000000;
return dp[n][k] = sum % 1000000;
}
int main()
{
int n, k;
while (cin >> n >> k, n || k)
cout << f(n, k) << '\n';
}
| true |
50c4a89e595e6804eca8523a2bc7e73b00856fe6 | C++ | clean-code-craft-tcq-1/stream-bms-data-soundarya1112 | /Receive/test/bms-rx-test.cpp | UTF-8 | 1,451 | 2.59375 | 3 | [
"MIT"
] | permissive | #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "bms-rx-data.h"
#include "stddef.h"
#include "string.h"
TEST_CASE("Test from Console - Valid data")
{
float tempCalc, ChrgRateCalc;
char str[100];
strcpy(str,"{'temperature': 37.37, 'state_of_charge': 23.64, 'charge_rate': 0.35}");
tempCalc = getParameterFromConsole(str,temperature);
ChrgRateCalc = getParameterFromConsole(str,charge_rate);
REQUIRE(fabs(tempCalc - 37.37)<0.01);
REQUIRE(fabs(ChrgRateCalc - 0.35)<0.01);
}
TEST_CASE("Test from Console - Invalid temperature data")
{
float tempCalc, ChrgRateCalc;
char str[100];
strcpy(str,"{'TemperAture': 37.37, 'state_of_charge': 23.64, 'charge_rate': 0.35}");
tempCalc = getParameterFromConsole(str,temperature);
ChrgRateCalc = getParameterFromConsole(str,charge_rate);
REQUIRE(fabs(tempCalc - VALUE_NOTFOUND) <0.01);
REQUIRE(fabs(ChrgRateCalc - 0.35)<0.01);
}
TEST_CASE("Test from Console - ChargeRate data invalid")
{
float tempCalc, ChrgRateCalc;
char str[100];
strcpy(str,"{'TemperAture': 37.37, 'state_of_charge': 23.64, 'ChargeRate': 0.35}");
tempCalc = getParameterFromConsole(str,temperature);
ChrgRateCalc = getParameterFromConsole(str,charge_rate);
REQUIRE(fabs(tempCalc - 37.37) <0.01);
REQUIRE(fabs(ChrgRateCalc - VALUE_NOTFOUND)<0.01);
}
| true |
41985a0f828210c83c86a15c47a755ac94e9d32b | C++ | aorura/qt_modeling_language | /qmlextensionplugins/timemodel.cpp | UTF-8 | 990 | 2.734375 | 3 | [] | no_license | #include "timemodel.h"
#include <QCoreApplication>
#include <QDebug>
int TimeModel::instances = 0;
MinuteTimer *TimeModel::timer = 0;
TimeModel::TimeModel(QObject *parent):
QObject(parent)
{
// By default, QQuickItem does not draw anything. If you subclass
// QQuickItem to create a visual item, you will need to uncomment the
// following line and re-implement updatePaintNode()
// setFlag(ItemHasContents, true);
if (++instances == 1) {
if(!timer)
timer = new MinuteTimer(QCoreApplication::instance());
connect(timer, SIGNAL(timeChanged()), this, SIGNAL(timeChanged()));
timer->start();
}
}
TimeModel::~TimeModel()
{
if(--instances == 0) {
timer->stop();
}
}
int TimeModel::minute() const {
return timer->minute();
}
int TimeModel::hour() const {
return timer->hour();
}
void TimeModel::printLog()
{
qDebug() << timer->minute();
}
void TimeModel::changeTime() {
emit timeChanged();
}
| true |
86a36be27a95b1d86e3263677b947d67f3115b19 | C++ | chxj1980/orwell | /cpp/common/FrameUpdater.h | UTF-8 | 801 | 2.71875 | 3 | [] | no_license | #ifndef FRAMEUPDATER_H
#define FRAMEUPDATER_H
/*
Why create such a silly class? Well because I don't want XVideoWidget things
inside MediaStream because I don't want QT things there because I'm going to use
mediaStream on Android and iOS too. But I need to use the method updateData of
XVideoWidget and possibly other widgets (for Android and iOS), so they must
implement this interface.
*/
class FrameUpdater {
public:
virtual void updateData(unsigned char**data, int frameWidth, int frameHeight)= 0;//https://stackoverflow.com/a/36909641/10116440
void setFrameWidth(int width) {
this->frameWidth = width;
}
void setFrameHeight(int height) {
this->frameHeight = height;
}
int frameWidth = 0;
int frameHeight = 0;
};
#endif // FRAMEUPDATER_H
| true |
17c2eb9c40cab749c6d13bc986adadad684a6cc7 | C++ | snnmbb/lab_11 | /lab11_1.cpp | UTF-8 | 342 | 3.421875 | 3 | [] | no_license | #include<iostream>
using namespace std;
long long int fibonacci(long long int x);
int main(){
cout << fibonacci(50);
return 0;
}
long long int fibonacci(long long int x)
{
if(x>1)
{
return fibonacci(x-1)+fibonacci(x-2);
}
else if(x==0)
{
return 0;
}
else
{
return 1;
}
} | true |
92b8938e37b598b3166e73d87f2ad729c72f97c7 | C++ | 543877815/algorithm | /leetcode/c++/557. Reverse Words in a String III.cpp | UTF-8 | 635 | 3.21875 | 3 | [] | no_license | // 时间复杂度:O(n)
// 空间复杂度:O(1)
class Solution {
public:
string reverseWords(string s) {
int n = s.size();
if (n == 0) return s;
int left = 0, right = 0;
while (right < n) {
if (s[right] != ' ') right++;
else {
reverse(s.begin() + left, s.begin() + right);
right++;
while (right < n && s[right] == ' ') {
right++;
}
left = right;
}
}
if (left != right) reverse(s.begin() + left, s.begin() + right);
return s;
}
}; | true |
e5391854a5dec456ce9e55c911fb1828359c7257 | C++ | anil-adepu/HPC_lab | /OMP/pi.cpp | UTF-8 | 1,221 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <omp.h>
using namespace std;
#include <time.h>
#define ll long long
static int steps;
int N;
int32_t main(int count, char* cli[]) {
N = atoi(cli[1]); steps = atoi(cli[2]);
int i;
double increment = 1.0/steps;
double sum =0.0,x;
for(i=1;i<=N;i++) {
// double x;
printf("running on %d thread(s): ",i);
//cout<<"running on "<<i<<" threads!\t";
omp_set_num_threads(i);
clock_t b,e;
b = clock();
double start = omp_get_wtime();
sum = 0.0;
//#pragma omp parallel for reduction(+:sum) private(x)
#pragma omp parallel for reduction(+:sum)
for(ll j=0;j<steps;j++) {
double x;
x = (j + 0.5) * increment;
sum += 4.0 / (1.0+x*x);
}
double pi = sum*increment;
e = clock();
double end = omp_get_wtime() - start;
printf("PI = %.16g computed in %.4g secs(Wall_clock).....%.4g secs(time.h)\n", pi, end, (double)(e-b)/CLOCKS_PER_SEC);
// cout<<"Pi value is : "<<pi<<" calculated in "<<end<<" secs"<<endl;
}
}
| true |
bc525bc01f29abfdccd26af23d16bbaa9ccb4ee5 | C++ | Mukund-Raj/C-plus-plus-Programs | /pointer_example.cpp | UTF-8 | 1,000 | 3.3125 | 3 | [] | no_license | #include<iostream>
using namespace std;
/*
int main()
{
char *ptr = "GeeksQuiz";
printf("%s\n", *&*&ptr);
/*
int a;
char *x;
x = (char *) &a;
a = 512;
x[0] = 1;
x[1] = 2;
cout<<a<<endl;
//cout<<sizeof(int);
cout<<sizeof(x);*/
/*
float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
float *ptr1 = &arr[0];
float *ptr2 = ptr1 + 3;
printf("%f ", *ptr2);
printf("%d", ptr2 - ptr1);
int p[]={1,2,3};
float q=89;
int k=5;
int *ptr1=&k;
char c='a';
char *ch=&c;
float *ptr=&q;
cout<<sizeof(ptr);
cout<<endl<<sizeof(ptr1);
cout<<endl<<sizeof(&ch);*/
/*
for(int i=0;i<3;i++)
{
cout<<*(ptr+i)<<endl;
}
//cout<<ptr<<endl;
//cout<<&k<<endl;
//*ptr=10;
//cout<<*ptr<<endl<<k;
return 0;
}*/
void fun(int *arr)
{
int i;
int arr_size = sizeof(arr)/sizeof(arr[0]);
for (i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
}
int main()
{
int i;
int arr[4] = {10, 20 ,30, 40};
cout<<sizeof(arr)<<endl;
fun(arr);
return 0;
}
| true |
896350797e6329103c06ac28596047df5e04c72b | C++ | cbchoi/sit22005 | /2018/01.spring/02.final/Problem01/problem01.cpp | UTF-8 | 705 | 3.265625 | 3 | [
"MIT"
] | permissive | #include "problem01.h"
#include <iostream>
Student::Student(int _id, std::string _name, int _point)
:m_id(_id), m_name(_name), m_point(_point)
{
}
int get_id()
{
return _id;
}
std::string get_name()
{
return m_name;
}
int get_point()
{
return m_point;
}
void set_id(int _id)
{
m_id = _id;
}
void set_name(std::string _name)
{
m_name = _name;
}
void update_point(int _point)
{
m_point = _point;
}
void print()
{
std::cout << "--------------------" << std::endl;
std::cout << "ID:" << Student.m_id << ", Name:" << Student.m_name << std::endl;
std::cout << "Point: " << Student.m_point << std::endl;
std::cout << "--------------------" << std::endl;
} | true |
6f2e867c1b3c0b733e1067653c9a53d7c9252dcf | C++ | jasonleakey/CrapCodes | /C++/FFT/main.cpp | UTF-8 | 1,637 | 2.59375 | 3 | [] | no_license | /*
* CPP_FFT - TODO
*
* Copyleft(R) by jasonleakey
* <jasonleakey@gmail.com>
* <QQ:174481438>
* --------------------------------------------------------------------
* 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
* (at your option) 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
* --------------------------------------------------------------------
*/
#include <iostream>
#include <fstream>
#include <complex>
using namespace std;
extern complex<double>* recursive_FFT(complex<double>* a, int n);
int main(int argc, char **argv)
{
int n = 0;
ifstream datfile("fft.dat");
if (!datfile)
{
cerr << "error: could not open file!" << endl;
return -1;
}
datfile >> n;
complex<double> *Ak = new complex<double>(n);
complex<double> *Xn = NULL;
for (int i = 0; i < n; i++)
{
datfile >> Ak[i];
}
datfile.close();
for (int i = 0; i < n; i++)
{
cout << Ak[i] << endl;
}
Xn = recursive_FFT(Ak, n);
for (int i = 0; i < n; i++)
{
cout << Xn[i] << endl;
}
delete[] Ak;
delete[] Xn;
return 0;
}
| true |
3a465990151237d43235108e37e71001e65e85bd | C++ | rg7000/Arrays | /ar_inp.cpp | UTF-8 | 730 | 3.34375 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
using namespace std;
class arr_op
{
int N;
int i;
public:
int get_n();
void set_n();
void initialize_arr(int a[], int size);
void print(int a[], int size);
};
int arr_op::get_n()
{
return N;
}
void arr_op::set_n()
{
cin>>N;
}
void arr_op::initialize_arr(int a[], int size)
{
for(i = 0; i<size; i++)
cin>>a[i];
}
void arr_op::print(int a[], int size)
{
for(i = size - 1; i>=0; i--)
cout<<a[i]<<" ";
}
int main()
{
int N;
/*cin>>N;
int a[N];*/
arr_op obj;
obj.set_n();
N = obj.get_n();
int a[N];
cin>>N;
int a[N];
arr_op obj;
obj.initialize_arr(a,N);
obj.print(a,N);
}
| true |