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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20d61003c7b4a35a96d825dff4d6bc7d810aba25 | C++ | bonfab/model_selection_abc | /GB_vs_NN/sample_bernoulli_matrix.cpp | UTF-8 | 1,284 | 2.671875 | 3 | [] | no_license |
#include "Rcpp.h"
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector bernoulli_matrix(NumericMatrix prob_matrix){
int nrow = prob_matrix.nrow();
int ncol = prob_matrix.ncol();
int var_sum = 0;
int count1, count2, sum;
double mean, variance, val;
NumericVector variance_flags(ncol);
for(int j=0; j<ncol; j++){
count1 = 0;
count2 = 0;
for(int i=0; i<nrow; i++){
if(::unif_rand() < prob_matrix(i,j)){
val = 1.0;
} else{
val = 0.0;
}
if(::unif_rand() < prob_matrix(i,j)){
val += 1.0;
}
if(val == 1) count1 += 1;
if(val == 2) count2 += 1;
prob_matrix(i, j) = val;
}
sum = count1 + count2 * 2;
mean = (double) sum/nrow;
if(sum != 0 && nrow != count1 && nrow != count2){
//variance = ((mean*mean)*(nrow - (count1+count2)) + (1 - mean)*(1-mean)*count1 + (2-mean)*(2-mean)*count2) /nrow;
for(int i=0; i<nrow; i++) prob_matrix(i, j) = (prob_matrix(i, j) - mean);// / variance;
variance_flags[j] = 1;
var_sum += 1;
}
}
NumericMatrix clean(nrow, var_sum);
int old_index = 0;
for(int j=0; j<var_sum; j++){
while(!variance_flags[old_index]) old_index += 1;
for(int i=0; i<nrow; i++) clean(i,j) = prob_matrix(i, old_index);
old_index += 1;
}
return(clean);
}
| true |
c3fcf663ab732bc79dff733e0d8d93b7b6faafe7 | C++ | lethe2211/aoj | /1002.cpp | UTF-8 | 1,463 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int t;
int n;
string data;
bool shelf[21000];
int count;
int left, right;
cin >> t;
for(int i = 0;i < t;i++) {
cin >> n;
cin >> data;
for(int i = 0;i < (int)(sizeof(shelf) / sizeof(shelf[0]));i++) {
shelf[i] = false;
}
count = 0;
left = 0;
right = 0;
if(data[0] == 'Y') shelf[0] = true;
for(int j = 1;j <= n-1;j++) {
if(data[2*j-1] == 'Y' || data[2*j] == 'Y') shelf[j] = true;
}
if(data[2*n-1] == 'Y') shelf[n] = true;
if(data[2*n] == 'Y') shelf[n+1] = true;
for(int j = n+2;j <= 2*n;j++) {
if(data[2*j-3] == 'Y' || data[2*j-2] == 'Y') shelf[j] = true;
}
if(data[4*n-1] == 'Y') shelf[2*n+1] = true;
// for(int j = 0;j <= 2*n+1;j++) cout << shelf[j] << endl;
for(int j = 0;j <= 2*n+1;j++) {
if(shelf[j] == true) count++;
}
for(int j = 0;j <= n;j++) {
if(shelf[j] == false && shelf[j+n+1] == false) continue;
else {
if(shelf[j] == true) {
left = 1;
}
else break;
}
}
for(int j = n;j >= 0;j--) {
if(shelf[j] == false && shelf[j+n+1] == false) continue;
else {
if(shelf[j] == true) {
right = 1;
}
else break;
}
}
// cout << count << endl;
// cout << left << endl;
// cout << right << endl;
cout << n + count + 2 - left - right << endl;
}
return 0;
}
| true |
0abf5cdf7455629227f9c703d877825aeb96036e | C++ | ymkjp/coc | /Classes/BuildingDefense.h | UTF-8 | 1,400 | 2.546875 | 3 | [] | no_license | #ifndef __BUILDING_DEFENSE_H__
#define __BUILDING_DEFENSE_H__
#include "cocos2d.h"
USING_NS_CC;
#include "Definitions.h"
#include "Building.h"
class BuildingDefense : public Building
{
public:
float minRange;
float maxRange;
static void updateAttackRangeGrid(Tmx* tmx);
bool startScan();
// 子クラスで再定義されてもよいメソッド
virtual float getMinRange() {return 0;};
virtual float getMaxRange() {return 0;};
Unit* targetUnit = {};
Vector<Unit*> targetUnits = {};
// 子クラスでのオーバーライド
virtual void attack() {};
virtual void shoot() {};
virtual void idle() {};
protected:
Vec2 aimedUnitPos;
float damagePerShot;
float attackSpeed;
void scan(float frame);
bool inAttackRange(Unit* unit);
static float normalize(float number);
const std::map<BuildingType, float> damagePerShotByType =
{
{Canon, 7.2},
{TrenchMortar, 30},
{ArcherTower, 19},
};
const std::map<BuildingType, float> attackSpeedByType =
{
{Canon, 0.8},
{TrenchMortar, 5},
{ArcherTower, 1},
};
float getDamagePerShot()
{
return damagePerShotByType.at(type);
}
float getAttackSpeed()
{
return attackSpeedByType.at(type);
}
};
#endif // __BUILDING_DEFENSE_H__
| true |
6edc65a23b8adaa00edd0a53f664751c8e0ee078 | C++ | wbzhang233/interviews_2020_fall | /netease0927/2.cpp | UTF-8 | 3,016 | 2.984375 | 3 | [] | no_license | //
// Created by wbzhang on 2020/9/27.
//
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
const int maxN = 1e5 + 100;
const int maxNF = 1e6 + 100;
enum OpType {
open,
dup,
dup2,
close,
query
};
OpType getOpType(string &command) {
string com;
for (auto ele:command) {
if (ele == ' ') break;
else com.push_back(ele);
}
if (com == "open") return open;
if (com == "dup") return dup;
if (com == "dup2") return dup2;
if (com == "close") return close;
if (com == "query") return query;
}
void splitCommmand(string &command, OpType &op, int &fd, int &new_fd, string &filename) {
// 先划分操作符
string com;
int i = 0;
for (auto ele:command) {
++i;
if (ele == ' ') break;
else com.push_back(ele);
}
if (com == "open") op = open;
if (com == "dup") op = dup;
if (com == "dup2") op = dup2;
if (com == "close") op = close;
if (com == "query") op = query;
// 则为文件名
if (isalpha(command[command.length() - 1])) {
while (i <= command.length()) filename.push_back(command[i]);
} else if (op == dup2) {
fd = 0, new_fd = 0;
bool fdF = true;
while (i <= command.length()) {
if (isdigit(command[i]) && fdF) {
fd = fd * 10 + (command[i] - '0');
fdF = false;
} else if (isdigit(command[i]) && !fdF) {
new_fd = new_fd * 10 + (command[i] - '0');
} else if (command[i] == ' ') continue;
}
} else {
fd = 0;
while (i <= command.length()) {
fd = fd * 10 + (command[i] - '0');
}
}
}
class Solution {
private:
int currId = 0;
map<string, int> file2fds; // 文件名对应的描述符
map<int, string> fd2file; // 描述符指向的文件名
multimap<int, string> filelists; //文件描述符->文件名列表
public:
int open(string &filename) {
file2fds[filename] = currId;
fd2file[currId] = filename;
filelists.insert(make_pair(currId, filename));
currId++;
return currId - 1;
}
int dup(int &fd) {
fd2file[currId] = fd2file[fd];
filelists.insert(make_pair(currId, fd2file[fd]));
currId++;
return currId - 1;
}
void dup2(int &fd, int &new_fd) {
fd2file[new_fd] = fd2file[fd];
}
void close(int &fd) {
fd2file.erase(fd);
}
string query(int &fd) {
return fd2file[fd];
}
};
int main() {
int T;
cin >> T;
string ns;
int N;
while (T > 0) {
cin >> N;
Solution solu;
string command;
char x;
OpType op;
string filename;
int fd, new_fd;
while (N > 0) {
// 读取每一行的函数调用
// cin>>command;
getline(cin, command);
// 解读操作
// splitCommmand(command,op,fd,new_fd,filename);
// 操作
switch (op) {
case open: {
cout << solu.open(filename) << endl;
break;
}
case dup: {
cout << solu.dup(fd) << endl;
break;
}
case dup2: {
solu.dup2(fd, new_fd);
break;
}
case close: {
solu.close(fd);
break;
}
case query: {
cout << solu.query(fd) << endl;
break;
}
}
--N;
}
--T;
}
return 0;
}
//2
//10
//open libc.so | true |
6da172a8251822c71fa132645e6e7cb886648fc5 | C++ | shreyansh26/CLRS_Algorithms | /Chapter12-BinarySearchTree/simplebst.cpp | UTF-8 | 2,906 | 4.15625 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <stdlib.h>
using namespace std;
struct node {
int key;
struct node *left, *right;
};
struct node* newNode(int data){
struct node* node = (struct node*)malloc(sizeof(struct node));
node->key = data;
node->left = NULL;
node->right = NULL;
return node;
}
struct node* insert(struct node *root, int key) {
struct node *new_node = newNode(key);
if(root == NULL) {
return new_node;
}
if(root != NULL) {
if(root->key > key)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
}
}
struct node* minValueNode(struct node *root) {
struct node *current = root;
while(current->left != NULL) {
current = current->left;
}
return current;
}
struct node* deleteNode(struct node* root, int key)
{
// base case
if (root == NULL) return root;
// If the key to be deleted is smaller than the root's key,
// then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key,
// then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);
// if key is same as root's key, then This is the node
// to be deleted
else
{
// node with only one child or no child
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
// node with two children: Get the inorder successor (smallest
// in the right subtree)
struct node* temp = minValueNode(root->right);
// Copy the inorder successor's content to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
return root;
}
/*
void transplant(struct node* root, struct node* u, struct node* v) {
if(u.parent == NULL)
root->key = v->key;
else if (u==u.parent.left)
u.parent.left = v;
else
u.parent.right = v;
if (v != NULL)
v.parent = u.parent;
}
*/
void inorder(struct node *root) {
if(root != NULL) {
inorder(root->left);
cout<<root->key<<" ";
inorder(root->right);
}
}
void preorder(struct node *root) {
if(root != NULL) {
cout<<root->key<<" ";
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct node *root) {
if(root != NULL) {
postorder(root->left);
postorder(root->right);
cout<<root->key<<" ";
}
}
int main() {
struct node* root = newNode(2);
insert(root, 1);
insert(root, 4);
insert(root, 3);
root = deleteNode(root, 2);
root = deleteNode(root, 1);
inorder(root);
cout<<"\n";
preorder(root);
cout<<"\n";
postorder(root);
return 0;
}
| true |
6a636f788fb3bb32f41297305bb7cc227b0d571e | C++ | zhanglongtumi/nQmlOpenCV | /videoimageprovider.cpp | UTF-8 | 2,374 | 2.59375 | 3 | [] | no_license | #include "videoimageprovider.h"
#include <QDebug>
#include "iostream"
#include "stdio.h"
#include "highgui.h"
#include "cv.h"
#include <QTimer>
#include <QImage>
#include <QPainter>
#include "opencv.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
using namespace cv;
using namespace std;
VideoImageProvider::VideoImageProvider()
: QQuickImageProvider(QQuickImageProvider::Pixmap)
{
capture_ = VideoCapture(0);
}
VideoImageProvider::~VideoImageProvider()
{
capture_.release();
}
QPixmap VideoImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
Mat frame;
QImage img;
capture_ >> frame;
img = Mat2QImage(frame);
return QPixmap::fromImage(img.mirrored(true, false));
}
QImage VideoImageProvider::MatToQImage(const Mat &mat)
{
// 8-bits unsigned, NO. OF CHANNELS=1
if(mat.type()==CV_8UC1)
{
// Set the color table (used to translate colour indexes to qRgb values)
QVector<QRgb> colorTable;
for (int i=0; i<256; i++)
colorTable.push_back(qRgb(i,i,i));
// Copy input Mat
const uchar *qImageBuffer = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_Indexed8);
img.setColorTable(colorTable);
return img;
}
// 8-bits unsigned, NO. OF CHANNELS=3
if(mat.type()==CV_8UC3)
{
// Copy input Mat
const uchar *qImageBuffer = (const uchar*)mat.data;
// Create QImage with same dimensions as input Mat
QImage img(qImageBuffer, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
return img.rgbSwapped();
}
else
{
qDebug() << "ERROR: Mat could not be converted to QImage.";
return QImage();
}
}
QImage VideoImageProvider::Mat2QImage(const Mat &src)
{
cv::Mat temp; // make the same cv::Mat
cvtColor(src, temp,CV_BGR2RGB); // cvtColor Makes a copt, that what i need
QImage dest((const uchar *) temp.data, temp.cols, temp.rows, temp.step, QImage::Format_RGB888);
dest.bits(); // enforce deep copy, see documentation
// of QImage::QImage ( const uchar * data, int width, int height, Format format )
return dest;
}
| true |
7e61702b0a09b2322fca408f7070c12d757bf150 | C++ | djairjr/RECON21 | /Puzzle_Pseudo_Code_Detailed_v2.ino | UTF-8 | 1,870 | 2.703125 | 3 | [
"CC0-1.0"
] | permissive | /*
* Puzzle Pseudo Code Detailed v2
*
* This is code for the All-in-One Cabinet Mag Lock puzzle.
*
* The tutorial for this puzzle was originally presented at RECON '21 during the "How to Build and Refine Your First Escape Room Tech Puzzle"
*
*
* Created 2021
* by Karmisha Jawell https://github.com/misha2ohh/
*
* This example code is in the public domain.
*
* https://github.com/misha2ohh/RECON21
*
*/
//Pull in libraries and set variables here
Include software serial library so the Arduino and MP3 board can talk
Define hall sensors
Create variables to store readings from hall sensors
// For testing purposes only, not needed for the puzzle)
Define LEDs
Create variable Initiate SFX
Create variable to store the puzzle state
//There are 2 states: Solved and Not Solved
Define the relay
void setup() {
// put your setup code here, to run once:
// Establish inputs and outputs
Set up hall sensors as inputs
Set up the LEDs as outputs
Set up the relay as an output
Start Serial communications
Then print message saying serial communications are ready
Then print message containing the file name
Start Software Serial communications
}
void loop() {
// put your main code here, to run repeatedly:
// This is where the action happens!
Read each hall sensor
Store the data in a variable
Print the new value of that variable
Setup IF statements to turn on LEDs
If a hall sensor detects a magnet
THEN turn on its respective LED
Setup IF statement to determine if puzzle has been solved
If all hall sensors are detecting a magnet
THEN change the puzzle state to solved
}
//Setup functions here
Write a function to run a sequence of events once the puzzle is solved
Write function to release mag lock...and turn on LED strip
Write function to tell the MP3 board to play the sound
| true |
a250a5886e05e789147de48b18a97716685d0a7c | C++ | AkimotoAkira0102/cpp-education-manual | /ch8-array&string/ch8-17.cpp | UTF-8 | 457 | 3.1875 | 3 | [] | no_license | #include <iostream> //include iostream files
#include <cstdlib> //include cstdlib files
#include <string> //include string files
using namespace std; //use namespace std
int main(void){ //begining of main block
string first = "Junie";
string last = "Hong";
cout << "Full name =" << first + " " + last << endl;
first += " ";
first += last;
cout << "Full name =" << first << endl;
system("pause"); //pause the o\program
return 0;
}
| true |
765b95e17290bfcab43b20ee37f4b6b4736d464f | C++ | luerera1/leetcode | /牛客网真题/序列交换/Project1/Project1/源.cpp | UTF-8 | 447 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin >> n;
long int a[n];
int count = 0;
for (int i = 0; i<n; i++){
cin >> a[i];
if (a[i] % 2 == 1) count++;
}
if (count == 0 || count == n){
for (int i = 0; i<n - 1; i++)
cout << a[i] << " ";
cout << a[n - 1] << endl;
}
else{
sort(a, a + n);
for (int i = 0; i<n - 1; i++){
cout << a[i] << " ";
}
cout << a[n - 1] << endl;
}
return 0;
} | true |
76f56f69f4abda76924a6ae6cafb616fd5947ef8 | C++ | thoasm/customized_precision_pagerank | /code/macros.hpp | UTF-8 | 4,680 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef MACROS_HPP
#define MACROS_HPP
#include <utility>
#ifdef __CUDACC__
#define MY_ATTRIBUTES __host__ __device__
#define MY_INLINE __forceinline__
#define MY_RESTRICT __restrict__
#else
#define MY_ATTRIBUTES
#define MY_INLINE inline
#define MY_RESTRICT __restrict__
#endif // __CUDACC__
namespace macros {
template <int... Values>
struct compile_int_list {
};
/*
//TODO
template <int Start, int End>
struct compile_int_range {
static_assert(Start > End, "Start needs to be smaller than End!");
//using list = ;
};
template<typename List, int... AdditionalValues>
struct merge_compile_int_list;
template<int... CurrentValues, int... AdditionalValues>
struct merge_compile_int_list<compile_int_list<CurrentValues...>, AdditionalValues...> {
using type = compile_int_list<CurrentValues..., AdditionalValues...>;
};
*/
template <typename... Values>
struct compile_type_list {
};
#define GKO_ENABLE_IMPLEMENTATION_SELECTION(_name, _callable) \
template <typename Predicate, int... IntArgs, typename... TArgs, \
typename... InferredArgs> \
inline void _name(macros::compile_int_list<>, Predicate, \
macros::compile_int_list<IntArgs...>, \
macros::compile_type_list<TArgs...>, \
InferredArgs...) {throw "whoops"; }; \
\
template <int K, int... Rest, typename Predicate, int... IntArgs, \
typename... TArgs, typename... InferredArgs> \
inline void _name(macros::compile_int_list<K, Rest...>, \
Predicate is_eligible, \
macros::compile_int_list<IntArgs...> int_args, \
macros::compile_type_list<TArgs...> type_args, \
InferredArgs... args) \
{ \
if (is_eligible(K)) { \
_callable<IntArgs..., TArgs...>( \
macros::compile_int_list<K>(), \
std::forward<InferredArgs>(args)...); \
} else { \
_name(macros::compile_int_list<Rest...>(), is_eligible, \
int_args, type_args, std::forward<InferredArgs>(args)...); \
} \
}
#define GKO_ENABLE_IMPLEMENTATION_ITERATION(_name, _callable) \
template <typename Predicate, int... IntArgs, typename... TArgs, \
typename... InferredArgs> \
inline void _name(macros::compile_int_list<>, Predicate, \
macros::compile_int_list<IntArgs...>, \
macros::compile_type_list<TArgs...>, \
InferredArgs...) {throw "whoops"; }; \
\
template <int K, int... Rest, typename Predicate, int... IntArgs, \
typename... TArgs, typename... InferredArgs> \
inline void _name(compile_int_list<K, Rest...>, \
Predicate is_satisfied, \
macros::compile_int_list<IntArgs...> int_args, \
macros::compile_type_list<TArgs...> type_args, \
InferredArgs... args) \
{ \
if (is_satisfied(K)) { \
_callable<IntArgs..., TArgs...>( \
macros::compile_int_list<K>(), \
std::forward<InferredArgs>(args)...); \
_name(macros::compile_int_list<Rest...>(), is_satisfied, \
int_args, type_args, std::forward<InferredArgs>(args)...); \
} \
}
} // namespace macros
#endif //MACROS_HPP
| true |
74e8020e5d4adca84e0909988ee1d8fe40c54058 | C++ | rahuls98/cpp-ladder | /Intermediate-CPP/dynamic_memory.cpp | UTF-8 | 529 | 3.640625 | 4 | [] | no_license | #include <iostream>
#define log(x, y) {std::cout<<x<<": "<<y<<std::endl;}
int main() {
/* creating and allocating required memory in heap */
int *ptr = new int;
log(ptr, *ptr); //0x7fbf0e401820: 0
/* setting value in the memory location */
*ptr = 5;
log(ptr, *ptr); //0x7fbf0e401820: 5
/* free dynamically allocated memory */
delete ptr;
log(ptr, *ptr); //0x7fbf0e401820: 5
/* handle the dangling pointer */
ptr = NULL;
log(ptr, *ptr); //Segmentation fault: 11
return 0;
} | true |
d31294abe0da48f5a3dd1d0742f6de2b69d41d12 | C++ | kostasli/Simple-Cpp-Program | /UserRating.cpp | UTF-8 | 474 | 3.03125 | 3 | [] | no_license | #include "UserRating.h"
#include <iostream>
UserRating::UserRating(unsigned int appNumOfStars, const char* appUserName, string appComments)
{
if (appNumOfStars <= 5)
{
stars = appNumOfStars;
name = appUserName;
comms = std::move(appComments);
}
else
{
cout<<"You must enter stars from 1 through 5."<<endl;
exit(1);
}
}
unsigned int UserRating::getStars() const{
return stars;
}
UserRating::~UserRating() {} | true |
bfd294887364b16167419e9f9149c1aa1c01eb80 | C++ | codedaotu/offer | /最长连续数字.cpp | UTF-8 | 433 | 2.96875 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<vector>
int longest_1(vector<int> &a)
{
vector<int> dp(a.size(),1);
int k=1;
for (int i = 1; i < a.size(); i++)
{
if(a[i]==a[i-1])dp[i]=max(dp[i-1],++k);
else
{
dp[i]=dp[i-1];
k=1;
}
cout<<dp[i]<<endl;
}
cout<<dp[a.size()-1];
return 0;
}
int main()
{
vector<int> a={1,2,3,4,1,1,1,0,0,9,9,9,9,9,1,1,1,1};
//vector<int> a={1,2};
longest_1(a);
return 0;
} | true |
2497ae38f2c665aa7927886af97c57ec2c818e06 | C++ | WuNianLuoMeng/Tutorial | /src/剑指offer/复杂链表复制/clone_list.cpp | UTF-8 | 2,978 | 3.53125 | 4 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
struct Node
{
struct Node *next;
struct Node *sibling;
int data;
};
struct List
{
struct Node *head;
};
typedef struct Node Node;
typedef struct List List;
void
list_initialize(List *list)
{
if(list == nullptr)
return;
list -> head = nullptr;
}
void
list_insert_tail(List *list, int data)
{
if(list == nullptr)
return;
Node *node = (Node *)malloc(sizeof(Node));
if(node == nullptr) {
printf("malloc error\n");
return;
}
node -> data = data;
node -> next = nullptr;
node -> sibling = nullptr;
if(list -> head == nullptr) {
list -> head = node;
return;
}
Node *ptr = list -> head;
while(ptr -> next != nullptr)
ptr = ptr -> next;
ptr -> next = node;
}
void
list_release(List *list)
{
if(list == nullptr)
return;
if(list -> head == nullptr)
return;
Node *ptr = list -> head;
Node *temp;
while(ptr != nullptr) {
temp = ptr;
ptr = ptr -> next;
free(temp);
}
}
void
list_print(List *list)
{
if(list == nullptr)
return;
if(list -> head == nullptr)
return;
Node *ptr = list -> head;
printf("List: \n");
while(ptr != nullptr) {
printf("%d\n", ptr -> data);
ptr = ptr -> next;
}
}
void
copy_list(List *list, List *new_list)
{
if(list == nullptr || list -> head == nullptr)
return;
if(new_list == nullptr)
return;
Node *ptr = list -> head;
while(ptr != nullptr) {
Node *node = (Node *)malloc(sizeof(Node));
if(node == nullptr) {
printf("malloc error");
return;
}
node -> data = ptr -> data;
node -> next = ptr -> next;
ptr -> next = node;
ptr = node -> next;
}
ptr = list -> head;
Node *copy_node = ptr -> next;
while(ptr != nullptr) {
copy_node -> sibling = ptr -> sibling;
ptr = copy_node -> next;
if(ptr != nullptr)
copy_node = ptr -> next;
else
break;
}
ptr = list -> head;
new_list -> head = ptr -> next;
Node *q = new_list -> head;
while(q != nullptr) {
ptr -> next = q -> next;
ptr = ptr -> next;
if(ptr == nullptr)
break;
q -> next = ptr -> next;
q = q -> next;
}
//ptr -> next = nullptr;
//q -> next = nullptr;
}
int
main(int argc, char *argv[])
{
List list, l2;
list_initialize(&list);
list_initialize(&l2);
int i;
for(i = 0; i < 4; ++i)
list_insert_tail(&list, i);
//list_print(&list);
copy_list(&list, &l2);
list_print(&l2);
//list_print(&list);
list_release(&list);
list_release(&l2);
return 0;
} | true |
da0c25f02d50cf13ae5c13bd2e903ad4d50a89ad | C++ | mCRL2org/mCRL2 | /libraries/data/include/mcrl2/data/untyped_sort_variable.h | UTF-8 | 3,328 | 2.796875 | 3 | [
"BSL-1.0"
] | permissive | // Author(s): Wieger Wesselink
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
/// \file mcrl2/data/untyped_sort_variable.h
/// \brief add your file description here.
#ifndef MCRL2_DATA_UNTYPED_SORT_VARIABLE_H
#define MCRL2_DATA_UNTYPED_SORT_VARIABLE_H
#include "mcrl2/data/sort_expression.h"
namespace mcrl2 {
namespace data {
//--- start generated class untyped_sort_variable ---//
/// \\brief Untyped sort variable
class untyped_sort_variable: public sort_expression
{
public:
/// \\brief Default constructor.
untyped_sort_variable()
: sort_expression(core::detail::default_values::UntypedSortVariable)
{}
/// \\brief Constructor.
/// \\param term A term
explicit untyped_sort_variable(const atermpp::aterm& term)
: sort_expression(term)
{
assert(core::detail::check_term_UntypedSortVariable(*this));
}
/// \\brief Constructor.
explicit untyped_sort_variable(const atermpp::aterm_int& value)
: sort_expression(atermpp::aterm_appl(core::detail::function_symbol_UntypedSortVariable(), value))
{}
/// Move semantics
untyped_sort_variable(const untyped_sort_variable&) noexcept = default;
untyped_sort_variable(untyped_sort_variable&&) noexcept = default;
untyped_sort_variable& operator=(const untyped_sort_variable&) noexcept = default;
untyped_sort_variable& operator=(untyped_sort_variable&&) noexcept = default;
const atermpp::aterm_int& value() const
{
return atermpp::down_cast<atermpp::aterm_int>((*this)[0]);
}
//--- start user section untyped_sort_variable ---//
/// \brief Constructor.
untyped_sort_variable(std::size_t value)
: sort_expression(atermpp::aterm_appl(core::detail::function_symbol_UntypedSortVariable(), atermpp::aterm_int(value)))
{}
//--- end user section untyped_sort_variable ---//
};
/// \\brief Make_untyped_sort_variable constructs a new term into a given address.
/// \\ \param t The reference into which the new untyped_sort_variable is constructed.
template <class... ARGUMENTS>
inline void make_untyped_sort_variable(atermpp::aterm_appl& t, const ARGUMENTS&... args)
{
atermpp::make_term_appl(t, core::detail::function_symbol_UntypedSortVariable(), args...);
}
/// \\brief Test for a untyped_sort_variable expression
/// \\param x A term
/// \\return True if \\a x is a untyped_sort_variable expression
inline
bool is_untyped_sort_variable(const atermpp::aterm_appl& x)
{
return x.function() == core::detail::function_symbols::UntypedSortVariable;
}
// prototype declaration
std::string pp(const untyped_sort_variable& x);
/// \\brief Outputs the object to a stream
/// \\param out An output stream
/// \\param x Object x
/// \\return The output stream
inline
std::ostream& operator<<(std::ostream& out, const untyped_sort_variable& x)
{
return out << data::pp(x);
}
/// \\brief swap overload
inline void swap(untyped_sort_variable& t1, untyped_sort_variable& t2)
{
t1.swap(t2);
}
//--- end generated class untyped_sort_variable ---//
} // namespace data
} // namespace mcrl2
#endif // MCRL2_DATA_UNTYPED_SORT_VARIABLE_H
| true |
c7db90a94acc4001cefe2b5ab707bb7eed7f664d | C++ | mrmoss/parrot_kinect | /src/msl/socket.hpp | UTF-8 | 9,244 | 2.9375 | 3 | [] | no_license | //Socket Header
// Created By: Mike Moss
// Modified On: 04/21/2014
//Required Libraries:
// Ws2_32 (windows only)
//Begin Define Guards
#ifndef MSL_SOCKET_H
#define MSL_SOCKET_H
//String Header
#include <string>
//String Stream Header
#include <sstream>
//Windows Dependencies
#if(defined(_WIN32)&&!defined(__CYGWIN__))
#include <winsock2.h>
#if(!defined(socklen_t))
typedef int socklen_t;
#endif
//Unix Dependencies
#else
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#ifndef SOCKET
#define SOCKET unsigned int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif
#endif
//MSL Namespace
namespace msl
{
//Socket Class Pre-Declaration(For msl::ipv4)
class socket;
//IPv4 Address Class Declaration
class ipv4
{
public:
//Constructor (Default)
ipv4(const unsigned char ip[4]=NULL,const unsigned short port=0);
//Copy Constructor
ipv4(const msl::ipv4& copy);
//Copy Assignment Operator
msl::ipv4& operator=(const msl::ipv4& copy);
//Build Function (Returns Raw Socket Address)
sockaddr_in build() const;
//String Accessor (X.X.X.X:PORT)
std::string str() const;
//Socket Class Friend
friend class msl::socket;
private:
//Member Variables
unsigned char _ip[4];
unsigned short _port;
};
//Socket Class Declaration
class socket
{
public:
//Constructor (Default)
socket(const std::string& address="0.0.0.0:0");
//Copy Constructor
socket(const msl::socket& copy);
//Copy Assignment Operator
socket& operator=(const msl::socket& copy);
//Boolean Operator (Tests if Socket is Good)
operator bool() const;
//Not Operator (For Boolean Operator)
bool operator!() const;
//Equality Operation
bool operator==(const msl::socket& rhs) const;
//Not Equality Operation
bool operator!=(const msl::socket& rhs) const;
//Good Function (Tests if Socket is Good)
bool good() const;
//Create Functions (Hosts a Socket Locally)
void create_tcp();
void create_udp(const unsigned int buffersize);
//Connect Functions (Connects to a Remote Socket)
void connect_tcp();
void connect_udp();
//Close Function (Closes a Local Socket)
void close();
//Accept Function (Accepts a Remote Connection to a Local Socket)
msl::socket accept();
//Available Function (Checks if there are Bytes to be Read)
int available() const;
//Read Function (Returns Number of Bytes Read, -1 on Error)
int read(void* buffer,const unsigned int size,const unsigned long time_out=0,const int flags=0) const;
//Write Function (Returns Number of Bytes Sent, -1 on Error)
int write(const void* buffer,const unsigned int size,const unsigned long time_out=0,const int flags=0);
int write(const std::string& str);
//IP Address Accessor (Read Only)
msl::ipv4 ip() const;
//System Socket Accessor
SOCKET system_socket() const;
private:
//Member Variables
msl::ipv4 _address;
SOCKET _socket;
bool _hosting;
};
}
//Socket Initialize Function (Sets up the use of sockets, operating system dependent...)
void socket_init();
//Socket Create Function (Hosts a Socket Locally)
SOCKET socket_create(const msl::ipv4 ip,const unsigned long time_out=0,const bool UDP=false,const unsigned int buffersize=200);
//Socket Connection Function (Connects to a Remote Socket)
SOCKET socket_connect(const msl::ipv4 ip,const unsigned long time_out=0,const bool UDP=false);
//Socket Accept Function (Accepts a Remote Connection to a Local Socket)
SOCKET socket_accept(const SOCKET socket,msl::ipv4& client_ip,const unsigned long time_out=0);
//Socket Close Function (Closes a Local Socket)
SOCKET socket_close(const SOCKET socket);
//Socket Available Function (Checks if there are Bytes to be Read, -1 on Error)
int socket_available(const SOCKET socket,const unsigned long time_out=0);
//Socket Peek Function (Same as socket_read but Leaves Bytes in Socket Buffer)
int socket_peek(const SOCKET socket,void* buffer,const unsigned int size,const unsigned long time_out=0,const int flags=0);
//Socket Read Function (Returns Number of Bytes Read, -1 on Error)
int socket_read(const SOCKET socket,void* buffer,const unsigned int size,const unsigned long time_out=0,const int flags=0);
//Socket Write Function (Returns Number of Bytes Sent, -1 on Error)
int socket_write(const SOCKET socket,const void* buffer,const unsigned int size,const unsigned long time_out=200,const int flags=0);
//End Define Guards
#endif
//Example (You need to make a folder called web and put index.html and not_found.html, located in comments below this example, in it for this to work)
/*
//Basic Web Server Source
// Created By: Mike Moss
// Modified On: 04/25/2013
//File Utility Header
#include "msl/file_util.hpp"
//IO Stream Header
#include <iostream>
//Socket Header
#include "msl/socket.hpp"
//Socket Utility Header
#include "msl/socket_util.hpp"
//String Header
#include <string>
//String Stream Header
#include <sstream>
//String Utility Header
#include "msl/string_util.hpp"
//Time Utility Header
#include "msl/time_util.hpp"
//Vector Header
#include <vector>
//Service Client Function Declaration
void service_client(msl::socket& client,const std::string& message);
//Main
int main(int argc,char* argv[])
{
//Create Port
std::string server_port="8080";
//Get Command Line Port
if(argc>1)
server_port=argv[1];
//Create Server
msl::socket server("0.0.0.0:"+server_port);
server.create_tcp();
//Check Server
if(server.good())
std::cout<<"=)"<<std::endl;
else
std::cout<<"=("<<std::endl;
//Vectors for Clients
std::vector<msl::socket> clients;
std::vector<std::string> client_messages;
//Be a server...forever...
while(true)
{
//Check for a Connecting Client
msl::socket client=server.accept();
//If Client Connected
if(client.good())
{
clients.push_back(client);
client_messages.push_back("");
}
//Handle Clients
for(unsigned int ii=0;ii<clients.size();++ii)
{
//Service Good Clients
if(clients[ii].good())
{
//Temp
char byte='\n';
//Get a Byte
if(clients[ii].available()>0&&clients[ii].read(&byte,1)==1)
{
//Add the Byte to Client Buffer
client_messages[ii]+=byte;
//Check for an End Byte
if(msl::ends_with(client_messages[ii],"\r\n\r\n"))
{
service_client(clients[ii],client_messages[ii]);
client_messages[ii].clear();
}
}
}
//Disconnect Bad Clients
else
{
clients[ii].close();
clients.erase(clients.begin()+ii);
client_messages.erase(client_messages.begin()+ii);
--ii;
}
}
//Give OS a Break
msl::nsleep(1000000);
}
//Call Me Plz T_T
return 0;
}
//Service Client Function Definition
void service_client(msl::socket& client,const std::string& message)
{
//Get Requests
if(msl::starts_with(message,"GET"))
{
//Create Parser
std::istringstream istr(msl::http_to_ascii(message));
//Parse the Request
std::string request;
istr>>request;
istr>>request;
//Web Root Variable (Where your web files are)
std::string web_root="web";
//Check for Index
if(request=="/")
request="/index.html";
//Mime Type Variable (Default plain text)
std::string mime_type="text/plain";
//Check for Code Mime Type
if(msl::ends_with(request,".js"))
mime_type="application/x-javascript";
//Check for Images Mime Type
else if(msl::ends_with(request,".gif"))
mime_type="image/gif";
else if(msl::ends_with(request,".jpeg"))
mime_type="image/jpeg";
else if(msl::ends_with(request,".png"))
mime_type="image/png";
else if(msl::ends_with(request,".tiff"))
mime_type="image/tiff";
else if(msl::ends_with(request,".svg"))
mime_type="image/svg+xml";
else if(msl::ends_with(request,".ico"))
mime_type="image/vnd.microsoft.icon";
//Check for Text Mime Type
else if(msl::ends_with(request,".css"))
mime_type="text/css";
else if(msl::ends_with(request,".htm")||msl::ends_with(request,".html"))
mime_type="text/html";
//File Data Variable
std::string file;
//Load File
if(msl::file_to_string(web_root+request,file,true))
{
std::string response=msl::http_pack_string(file,mime_type,false);
client.write(response.c_str(),response.size());
}
//Bad File
else if(msl::file_to_string(web_root+"/not_found.html",file,true))
{
std::string response=msl::http_pack_string(file);
client.write(response.c_str(),response.size());
}
//Close Connection
client.close();
}
//Other Requests (Just kill connection...it's either hackers or idiots...)
else
{
client.close();
}
}
*/
//index.html
/*
<html>
<head>
<title>Your here!</title>
</head>
<body>
<center>Now go away...</center>
</body>
</html>
*/
//not_found.html
/*
<html>
<head>
<title>Not found!</title>
</head>
<body>
<center>T_T</center>
</body>
</html>
*/
| true |
ef47dc8398e37e3af68c12f73e7a6820fc94d991 | C++ | unormal/MESSimpleSocketServer | /SimpleSocketServer/SimpleSocketServer.cpp | UTF-8 | 9,518 | 2.53125 | 3 | [] | no_license | // SimpleSocketServer.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#define WIN32_LEAN_AND_MEAN
#pragma comment (lib, "Ws2_32.lib")
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <thread>
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "4101"
#include <random>
#include <functional>
std::uniform_int_distribution<int> dice_distribution(1, 6);
std::mt19937 random_number_engine; // pseudorandom number generator
auto dice_roller = std::bind(dice_distribution, random_number_engine);
void enable_keepalive(int sock) {
int i = 1;
setsockopt( sock, IPPROTO_TCP, TCP_NODELAY, (char *)&i, sizeof(i));
int zero = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&zero, sizeof(int));
zero = 0;
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&zero, sizeof(int));
}
void respond(int ClientSocket)
{
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
char buf[1000];
time_t now = time(NULL);
struct tm tm;
gmtime_s(&tm,&now);
strftime(buf, sizeof buf, "%a, %d %b %Y %H:%M:%S %Z", &tm);
std::string strDate(buf);
std::string response = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nConnection: keep-alive\nDate:"+strDate+"\nTransfer-Encoding: chunked\n\n4\ntrue\n0\n\n\n\n";
//send( ClientSocket, response.c_str(), response.length(), 0 );
//string response = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: POST\nAccess-Control-Allow-Credentials: false\nAccess-Control-Max-Age: 86400\nAccess-Control-Allow-Headers: access-control-allow-headers,access-control-allow-origin,content-type\nConnection: keep-alive\nTransfer-Encoding: chunked\n\n28\n{\"id\":14,\"jsonrpc\":\"2.0\",\"result\":false}\n0\n\n";
std::string responseT = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nConnection: keep-alive\nDate:"+strDate+"\nTransfer-Encoding: chunked\n\n4\ntrue\n0\n\n\n\n";
std::string responseF = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nConnection: keep-alive\nDate:"+strDate+"\nTransfer-Encoding: chunked\n\n5\nfalse\n0\n\n\n\n";
int iSendResult;
int iResult = 0;
// Echo the buffer back to the sender
int random_roll = dice_roller(); // Generate one of the integers 1,2,3,4,5,6.
if( random_roll >= 4 )
{
send( ClientSocket, responseT.c_str(), responseT.length(), 0 );
}
else
{
send( ClientSocket, responseF.c_str(), responseF.length(), 0 );
}
//printf("Bytes sent: %d\n", response.length());
shutdown(ClientSocket,SD_SEND);
closesocket( ClientSocket);
/*
do {
int iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult);
//string response = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: POST\nAccess-Control-Allow-Credentials: false\nAccess-Control-Max-Age: 86400\nAccess-Control-Allow-Headers: access-control-allow-headers,access-control-allow-origin,content-type\nConnection: keep-alive\nTransfer-Encoding: chunked\n\n28\n{\"id\":14,\"jsonrpc\":\"2.0\",\"result\":false}\n0\n\n";
std::string response = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: POST\nAccess-Control-Allow-Credentials: false\nAccess-Control-Max-Age: 86400\nAccess-Control-Allow-Headers: access-control-allow-headers,access-control-allow-origin,content-type\nConnection: keep-alive\nTransfer-Encoding: chunked\n\n4\ntrue\n0\n\n";
// Echo the buffer back to the sender
int iSendResult = send( ClientSocket, response.c_str(), iResult, 0 );
printf("Bytes sent: %d\n", iSendResult);
closesocket(ClientSocket);
break;
}
else if (iResult == 0)
{
printf("Connection closing...\n");
break;
}
else
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
break;
}
} while (true); */
}
int main()
{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL;
struct addrinfo hints;
int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET6;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_IP;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
enable_keepalive(ListenSocket);
bool bOptVal = true;
int bOptLen = sizeof (BOOL);
iResult = setsockopt(ListenSocket, SOL_SOCKET, SO_KEEPALIVE, (char *) &bOptVal, bOptLen);
reaccept:
// Accept a client socket
while( true )
{
ClientSocket = accept(ListenSocket, NULL, NULL);
enable_keepalive(ClientSocket);
//printf("got new client...");
std::thread* clientThread = new std::thread(respond,ClientSocket);
}
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Receive until the peer shuts down the connection
do {
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %d\n", iResult);
//string response = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: POST\nAccess-Control-Allow-Credentials: false\nAccess-Control-Max-Age: 86400\nAccess-Control-Allow-Headers: access-control-allow-headers,access-control-allow-origin,content-type\nConnection: keep-alive\nTransfer-Encoding: chunked\n\n28\n{\"id\":14,\"jsonrpc\":\"2.0\",\"result\":false}\n0\n\n";
std::string responseT = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: POST\nAccess-Control-Allow-Credentials: false\nAccess-Control-Max-Age: 86400\nAccess-Control-Allow-Headers: access-control-allow-headers,access-control-allow-origin,content-type\nConnection: keep-alive\nTransfer-Encoding: chunked\n\n4\ntrue\n0\n\n";
std::string responseF = "HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\nAccess-Control-Allow-Methods: POST\nAccess-Control-Allow-Credentials: false\nAccess-Control-Max-Age: 86400\nAccess-Control-Allow-Headers: access-control-allow-headers,access-control-allow-origin,content-type\nConnection: keep-alive\nTransfer-Encoding: chunked\n\n5\nfalse\n0\n\n";
// Echo the buffer back to the sender
if( (rand()%10 + 1) > 5 )
{
iSendResult = send( ClientSocket, responseT.c_str(), iResult, 0 );
}
else
{
iSendResult = send( ClientSocket, responseF.c_str(), iResult, 0 );
}
printf("Bytes sent: %d\n", iSendResult);
closesocket(ClientSocket);
break;
}
else if (iResult == 0)
{
printf("Connection closing...\n");
break;
}
else
{
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
break;
}
} while (true);
goto reaccept;
// No longer need server socket
closesocket(ListenSocket);
// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
1c30ae3d391fda64021c6a8fd65aba41769fe4b0 | C++ | Traubert/FinnPos | /src/tagger/Trellis.cc | UTF-8 | 13,371 | 2.515625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* @file Trellis.cc
* @Author Miikka Silfverberg
* @brief A class that knows the Viterbi algorithm and the forward-backward
* algorithm.
*/
///////////////////////////////////////////////////////////////////////////////
// //
// (C) Copyright 2014, University of Helsinki //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// http://www.apache.org/licenses/LICENSE-2.0 //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// //
///////////////////////////////////////////////////////////////////////////////
#include "Trellis.hh"
#ifndef TEST_Trellis_cc
#define TEST_Trellis_cc
#include <cmath>
#include <cfloat>
#include "Word.hh"
void normalize(std::vector<float> &v)
{
float total = -FLT_MAX;
for (unsigned int i = 0; i < v.size(); ++i)
{
total = expsumlog(total, v[i]);
}
for (unsigned int i = 0; i < v.size(); ++i)
{
v[i] = exp(v[i] - total);
}
}
Trellis::Trellis(Sentence &sent,
unsigned int boundary_label,
Degree sublabel_order,
Degree model_order,
unsigned int beam):
s(&sent),
marginals_set(0),
bw(boundary_label),
beam(beam),
sublabel_order(sublabel_order),
model_order(model_order)
{
reserve(sent.size(), boundary_label);
for (unsigned int i = 0; i < sent.size(); ++i)
{
trellis[i].set_word(sent.at(i),
i == 0 ? 1 : sent.at(i - 1).get_label_count());
}
for (unsigned int i = 0; i < sent.size() - 1; ++i)
{
trellis[i].set_ncol(&trellis[i+1]);
}
}
LabelVector Trellis::get_maximum_a_posteriori_assignment(const ParamTable &pt)
{
LabelVector res;
trellis.back().compute_viterbi(pt);
trellis.back().set_labels(res);
return res;
}
LabelVector Trellis::get_marginalized_max_assignment(const ParamTable &pt)
{
set_marginals(pt);
LabelVector res;
for (unsigned int i = 0; i < s->size(); ++i)
{
float max_marginal = -FLT_MAX;
unsigned int max_label = -1;
for (unsigned int j = 0; j < s->at(i).get_label_count(); ++j)
{
if (unigram_marginals[i][j] > max_marginal)
{
max_marginal = unigram_marginals[i][j];
max_label = s->at(i).get_label(j);
}
}
res.push_back(max_label);
}
return res;
}
#include <cassert>
void Trellis::set_maximum_a_posteriori_assignment(const ParamTable &pt)
{
LabelVector labels = get_maximum_a_posteriori_assignment(pt);
assert(labels.size() == s->size());
for (unsigned int i = 0; i < labels.size(); ++i)
{
s->at(i).set_label(labels[i]);
assert(s->at(i).get_label() != static_cast<unsigned int>(-1));
}
}
void Trellis::set_marginalized_max_assignment(const ParamTable &pt)
{
LabelVector labels = get_marginalized_max_assignment(pt);
for (unsigned int i = 0; i < labels.size(); ++i)
{
s->at(i).set_label(labels[i]);
}
}
void Trellis::reserve_marginals(void)
{
trigram_marginals.assign(trellis.size(), std::vector<float>());
bigram_marginals.assign(trellis.size(), std::vector<float>());
unigram_marginals.assign(trellis.size(), std::vector<float>());
for (unsigned int i = 0; i < trellis.size(); ++i)
{
unsigned int labels = trellis[i].get_label_count();
unigram_marginals[i].assign(labels, 0);
unsigned int label_bigrams =
labels * (i == 0 ? 1 : trellis[i - 1].get_label_count());
bigram_marginals[i].assign(label_bigrams, 0);
if (i < 2)
{ continue; }
unsigned int label_trigrams =
label_bigrams * trellis[i - 2].get_label_count();
trigram_marginals[i].assign(label_trigrams, 0);
}
}
void Trellis::set_unigram_marginals(void)
{
for (unsigned int i = 0; i < trellis.size(); ++i)
{
for (unsigned int l = 0; l < trellis[i].get_label_count(); ++l)
{
float unigram_score = -FLT_MAX;
for (unsigned int pl = 0;
pl < (i == 0 ? 1 : trellis[i-1].get_label_count());
++pl)
{
unigram_score =
expsumlog(unigram_score,
bigram_marginals[i][get_index(i, l, pl)]);
}
unigram_marginals[i][get_index(i, l)] = unigram_score;
}
}
}
void Trellis::set_bigram_marginals(void)
{
for (unsigned int i = 0; i < trellis.size(); ++i)
{
for (unsigned int l = 0; l < trellis[i].get_label_count(); ++l)
{
for (unsigned int pl = 0;
pl < (i == 0 ? 1 : trellis[i-1].get_label_count());
++pl)
{
bigram_marginals[i][get_index(i, l, pl)] =
trellis[i].get_fw(pl, l) + trellis[i].get_bw(pl, l);
}
}
}
}
void Trellis::set_trigram_marginals(const ParamTable &pt)
{
for (unsigned int i = 2; i < trellis.size(); ++i)
{
for (unsigned int l = 0; l < trellis[i].get_label_count(); ++l)
{
unsigned int label = trellis[i].get_cell(0, l).label;
for (unsigned int pl = 0; pl < trellis[i-1].get_label_count(); ++pl)
{
unsigned int plabel = trellis[i - 1].get_cell(0, pl).label;
for (unsigned int ppl = 0;
ppl < trellis[i-2].get_label_count();
++ppl)
{
unsigned int pplabel = trellis[i - 2].get_cell(0, ppl).label;
trigram_marginals[i][get_index(i, l, pl, ppl)] =
trellis[i - 1].get_fw(ppl, pl) +
trellis[i].get_bw(pl, l) +
pt.get_all_struct_fw(pplabel, plabel, label, sublabel_order, model_order) +
pt.get_all_unstruct(s->at(i), label, sublabel_order);
}
}
}
}
}
void Trellis::set_marginals(const ParamTable &pt)
{
if (marginals_set)
{ return; }
marginals_set = 1;
trellis[0].compute_bw(pt);
trellis.back().compute_fw(pt);
reserve_marginals();
set_bigram_marginals();
set_unigram_marginals();
set_trigram_marginals(pt);
if (trellis.size() > 0)
{ normalize(unigram_marginals[0]); }
for (unsigned int i = 1; i < trellis.size(); ++i)
{
normalize(unigram_marginals[i]);
normalize(trigram_marginals[i]);
normalize(bigram_marginals[i]);
}
}
float Trellis::get_marginal(unsigned int position,
unsigned int label) const
{
return unigram_marginals[position][get_index(position, label)];
}
float Trellis::get_marginal(unsigned int position,
unsigned int plabel_index,
unsigned int label_index) const
{
return bigram_marginals[position][get_index(position,
label_index,
plabel_index)];
}
float Trellis::get_marginal(unsigned int position,
unsigned int pplabel_index,
unsigned int plabel_index,
unsigned int label_index) const
{
return trigram_marginals[position][get_index(position,
label_index,
plabel_index,
pplabel_index)];
}
unsigned int Trellis::size(void) const
{
return trellis.size();
}
void Trellis::set_beam_mass(float mass)
{
for (unsigned int i = 0; i < trellis.size(); ++i)
{ trellis.at(i).set_beam_mass(mass); }
}
void Trellis::set_beam(unsigned int beam)
{
for (unsigned int i = 0; i < trellis.size(); ++i)
{ trellis.at(i).set_beam(beam); }
}
void Trellis::reserve(unsigned int n, unsigned int boundary_label)
{
trellis.insert(trellis.end(),
n,
TrellisColumn(boundary_label,
beam,
sublabel_order,
model_order));
}
unsigned int Trellis::get_index(unsigned int position,
unsigned int l_index,
unsigned int pl_index,
unsigned int ppl_index) const
{
unsigned int index = l_index;
if (pl_index != static_cast<unsigned int>(-1))
{
index += pl_index * trellis[position].get_label_count();
}
if (ppl_index != static_cast<unsigned int>(-1))
{
index += ppl_index * trellis[position].get_label_count() *
trellis[position - 1].get_label_count();
}
return index;
}
void populate(Data &data,
TrellisVector &v,
unsigned int boundary_label,
Degree sublabel_order,
Degree model_order,
unsigned int beam)
{
for (unsigned int i = 0; i < data.size(); ++i)
{ v.push_back(new Trellis(data.at(i), boundary_label, sublabel_order, model_order, beam)); }
}
#else // TEST_Trellis_cc
class SillyLabelExtractor : public LabelExtractor
{
public:
SillyLabelExtractor(void):
LabelExtractor(1)
{}
void set_label_candidates(const std::string &word_form,
bool use_lexicon,
unsigned int count,
LabelVector &target) const
{
static_cast<void>(word_form);
static_cast<void>(use_lexicon);
int prev_size = target.size();
for (unsigned int i = 0; i < count - prev_size; ++i)
{
target.push_back(0);
}
}
};
#include <cassert>
#include <cfloat>
#include <cmath>
bool float_eq(float f1, float f2)
{
return fabs(f1 - f2) < 0.0001;
}
int main(void)
{
FeatureTemplateVector dog_feats;
dog_feats.push_back(0);
dog_feats.push_back(1);
LabelVector labels;
labels.push_back(1);
labels.push_back(9);
Word boundary(0);
Word dog("dog",
dog_feats,
labels,
"foo");
FeatureTemplateVector cat_feats;
cat_feats.push_back(2);
cat_feats.push_back(3);
Word cat("cat",
cat_feats,
labels,
"foo");
FeatureTemplateVector horse_feats;
horse_feats.push_back(4);
horse_feats.push_back(5);
Word horse("horse",
horse_feats,
labels,
"foo");
WordVector words;
words.push_back(dog);
words.push_back(cat);
words.push_back(horse);
SillyLabelExtractor label_extractor;
Sentence s(words, label_extractor, 2);
ParamTable pt;
// Random init parameters.
pt.update_unstruct(0, 1, 2.056);
pt.update_unstruct(0, 9, 4.096);
pt.update_unstruct(1, 1, 3.602);
pt.update_unstruct(1, 9, 8.519);
pt.update_unstruct(2, 1, 7.676);
pt.update_unstruct(2, 9, 9.619);
pt.update_unstruct(3, 1, 5.574);
pt.update_unstruct(3, 9, 3.167);
pt.update_unstruct(4, 1, 0.280);
pt.update_unstruct(4, 9, 0.778);
pt.update_unstruct(5, 1, 4.386);
pt.update_unstruct(5, 9, 1.145);
pt.update_struct3(0,0,1,6.521);
pt.update_struct3(0,0,9,7.494);
pt.update_struct2(0,9,5.891, false);
pt.update_struct2(0,1,0.883, false);
pt.update_struct1(9,2.275);
pt.update_struct1(1,3.68);
pt.update_struct3(1,1,1,5.206);
pt.update_struct3(1,1,9,4.958);
pt.update_struct2(1,1,3.883, false);
pt.update_struct2(1,9,4.309, false);
pt.update_struct3(1,9,1,9.494);
pt.update_struct3(1,9,9,6.355);
pt.update_struct2(9,1,0.358, false);
pt.update_struct2(9,9,6.690, false);
Trellis trellis(s, 0);
trellis.set_marginals(pt);
LabelVector v = trellis.get_maximum_a_posteriori_assignment(pt);
assert(v.size() == s.size());
LabelVector v1 = trellis.get_marginalized_max_assignment(pt);
assert(v == v1);
// Manually compute total score and scores for (1), (1,0) and
// (1,0,1) for horse in "dog cat horse".
float tot_score = -FLT_MAX;
float pos_3_l_1_score = -FLT_MAX;
float pos_3_l_1_0_score = -FLT_MAX;
float pos_3_l_1_0_1_score = -FLT_MAX;
std::vector<unsigned int> max_label_indices(3, -1);
for (unsigned int i = 0; i < 2; ++i)
{
for (unsigned int j = 0; j < 2; ++j)
{
for (unsigned int k = 0; k < 2; ++k)
{
float f = 0;
f += pt.get_unstruct(0, labels[i]);
f += pt.get_unstruct(1, labels[i]);
f += pt.get_unstruct(2, labels[j]);
f += pt.get_unstruct(3, labels[j]);
f += pt.get_unstruct(4, labels[k]);
f += pt.get_unstruct(5, labels[k]);
f += pt.get_struct3(0, 0, labels[i]);
f += pt.get_struct2(0, labels[i], false);
f += pt.get_struct1(labels[i]);
f += pt.get_struct3(0, labels[i], labels[j]);
f += pt.get_struct2(labels[i], labels[j], false);
f += pt.get_struct1(labels[j]);
f += pt.get_struct3(labels[i], labels[j], labels[k]);
f += pt.get_struct2(labels[j], labels[k], false);
f += pt.get_struct1(labels[k]);
f += pt.get_struct3(labels[j], labels[k], 0);
f += pt.get_struct3(labels[k], 0, 0);
f += pt.get_struct2(labels[k], 0, false);
tot_score = expsumlog(tot_score, f);
if (k == 1)
{
pos_3_l_1_score = expsumlog(pos_3_l_1_score, f);
if (j == 0)
{
pos_3_l_1_0_score = expsumlog(pos_3_l_1_0_score, f);
if (i == 1)
{
pos_3_l_1_0_1_score =
expsumlog(pos_3_l_1_0_1_score, f);
}
}
}
}
}
}
assert(float_eq(exp(pos_3_l_1_score - tot_score),
trellis.get_marginal(3,1)));
assert(float_eq(exp(pos_3_l_1_0_score - tot_score),
trellis.get_marginal(3,0,1)));
assert(float_eq(exp(pos_3_l_1_0_1_score - tot_score),
trellis.get_marginal(3,1,0,1)));
}
#endif // TEST_Trellis_cc
| true |
f56bca6997de44602dd8392431d884fc05f429ad | C++ | wilkru-7/D7049E | /events/collisionEvent.h | UTF-8 | 644 | 2.546875 | 3 | [] | no_license | //
// Class for collision event. It inherits the Event class and the EventListener
// class from ReactPhysics3D.
//
#ifndef D7049E_COLLISIONEVENT_H
#define D7049E_COLLISIONEVENT_H
#include "event.h"
#include "reactphysics3d/reactphysics3d.h"
#include "../objects/object.h"
namespace {
class CollisionEvent : public Event, public reactphysics3d::EventListener {
public:
CollisionEvent(std::vector<Object*> *objects);
int id() override {return 2;}
void onContact(const CollisionCallback::CallbackData &callbackData) override;
std::vector<Object*> *objects;
};
}
#endif //D7049E_COLLISIONEVENT_H
| true |
4d26c19413982a4d12be8c1ede625b9c188380d3 | C++ | karry3775/Motley | /Ceres_exploration/src/run_circle_fit.cpp | UTF-8 | 617 | 2.9375 | 3 | [] | no_license | #include <circle_fit.h>
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
// Generate points of a circle, to act as data
std::vector<double> x_data{}, y_data{};
circle_fit::generateData(x_data, y_data, 3, 1, 1, 0.5, M_PI / 180);
// Print out the data
std::cerr << "Data values are : \n";
for (size_t i = 0; i < x_data.size(); ++i) {
std::cerr << x_data[i] << ", " << y_data[i] << "\n";
}
std::cerr << "=======================================\n";
double cx{0.0}, cy{0.0}, r{0.1};
circle_fit::solve(x_data, y_data, cx, cy, r);
return 0;
} | true |
d1024ac6b09945cba62e68bfb2e112c8c75cdf18 | C++ | winhows5/Leetcode-Answers | /0095. Unique Binary Search Trees II/ans1.cpp | UTF-8 | 1,263 | 3.109375 | 3 | [] | no_license | /* time cost: 16ms (97.18%) */
/* time complexity: O(n^2log(n)) */
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static int x = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
vector<TreeNode*> iteration(int small, int great) {
vector<TreeNode*> res;
if (small > great)
return vector<TreeNode*>{nullptr};
if (small == great)
return vector<TreeNode*>{new TreeNode(small)};
for (int i = small; i <= great; ++i) {
vector<TreeNode*> left = iteration(small, i-1);
vector<TreeNode*> right = iteration(i+1, great);
for (TreeNode* l : left)
for (TreeNode* r : right) {
TreeNode* root = new TreeNode(i);
root->left = l;
root->right = r;
res.push_back(root);
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
if (n == 0) return vector<TreeNode*>{};
return iteration(1, n);
}
};
| true |
d2fe42bc37f7b20f00cb06b9eb10ad275831acda | C++ | csc2430-master/Lab6-Starter | /gridWindow.cpp | UTF-8 | 4,318 | 2.953125 | 3 | [] | no_license | // Title: Lab 6 - gridWindow.cpp
//
// Purpose: Implement the GridWindow class which bundles the behind the scenes Grid
// class functionality with the display elements.
//
// Class: CSC 2430 Winter 2020
// Author: Max Benson and <your name>
#include <assert.h>
#include "gridWindow.h"
// Grid Titles
const string HTITLE = "A B C D E F G H I J";
const string VTITLE = "0 1 2 3 4 5 6 7 8 9";
// Implement the GridWindow class which bundles the behind the scenes Grid
// class functionality with the display elements.
//
//
// Constructor
GridWindow::GridWindow(string title, bool isUser) :
_plot("Plot", HEIGHT, WIDTH),
_plotWithLabels("PlotWithLabels", true, HTITLE, VTITLE),
_labeledPlotWithTitle("LabeledPlotWithTitle", false, title) {
_isUser = isUser;
assert(5 == COLORS_MAX);
_colors[0] = GREEN;
_colors[1] = YELLOW;
_colors[2] = BLUE;
_colors[3] = MAGENTA;
_colors[4] = CYAN;
}
// Add the grid user interface elements to their containers. Must be called
// before Display is called.
// Parameters:
// none
// Returns:
// nothing
// Possible Errors:
// none expected
void GridWindow::Init() {
// Create view
_plotWithLabels.AddChild(&_plot);
_labeledPlotWithTitle.AddChild(&_plotWithLabels);
}
// Return a reference to the underlying VGroup so Display can be triggered on it
// Parameters:
// none
// Returns:
// a reference to the VGroup
// Possible Errors:
// none expected
VGroup& GridWindow::DisplayArea() {
return _labeledPlotWithTitle;
}
// Display the grid lines
// Parameters:
// none
// Returns:
// nothing
// Possible Errors:
// none expected
void GridWindow::DisplayLines() {
// Display the grid
for (int row = 0; row < HEIGHT; row ++) {
for (int col = 0; col < WIDTH; col ++) {
chtype ch;
if (0 == col) {
if (row == 0) {
ch = ACS_ULCORNER;
}
else if (row == HEIGHT-1) {
ch = ACS_LLCORNER;
}
else if (row % 2 == 0) {
ch = ACS_LTEE;
}
else {
ch = ACS_VLINE;
}
_plot.Write(col, row, ch);
}
else if (col == WIDTH-1) {
if (row == 0) {
ch = ACS_URCORNER;
}
else if (row == HEIGHT-1) {
ch = ACS_LRCORNER;
}
else if (row % 2 == 0) {
ch = ACS_RTEE;
}
else {
ch = ACS_VLINE;
}
_plot.Write(col, row, ch);
}
else if (row % 2 == 1) {
if (col % 2 == 0) {
_plot.Write(col, row, ACS_VLINE);
}
}
else {
if (col % 2 == 1) {
ch = ACS_HLINE;
}
else if (row == 0) {
ch = ACS_TTEE;
}
else if (row == HEIGHT-1) {
ch = ACS_BTEE;
}
else {
ch = ACS_PLUS;
}
_plot.Write(col, row, ch);
}
}
}
}
// Your work starts below this line...
// Display the initial state of the grid
// Parameters:
// none
// Returns:
// nothing
// Possible Errors:
// none expected
void GridWindow::Display() {
// You need to add code here
}
// Fire at a square of the grid. This method both updates the in memory Grid
// class and also displays the shot in the UI
// Parameters:
// row - row number of the shot
// column - column number of the shot
// outcome - outcome of the shot
// Returns:
// success/failure
// Possible Errors:
// none expected
bool GridWindow::FireShot(int row, int column, Outcome& outcome) {
// You need to add code here
return true;
}
// For you to add: LoadShips, RandomlyPlaceShips, DisplayShip
| true |
4a08b3c2bc7e33e9fe62b409a2bf7b5c3ffcd47c | C++ | TheMagnat/Mavoxel | /src/Helper/Benchmark/Profiler.hpp | UTF-8 | 608 | 2.78125 | 3 | [
"MIT"
] | permissive |
#pragma once
#include <string>
#include <chrono>
#include <iostream>
#include <mutex>
#include <map>
class Chronometer {
public:
void start();
double getElapsedTime();
private:
std::chrono::high_resolution_clock::time_point startTime_;
};
class Profiler {
public:
Profiler(std::string id);
~Profiler();
static void printProfiled(std::ostream& stream);
private:
Chronometer chrono;
std::string id_;
static std::mutex staticMutex_;
static std::map<std::string, std::pair<int, double>> savedTimes_;
};
| true |
3ac268a92646c8a4b32c10a2ddfa5cdb3e834605 | C++ | msrdinesh/Blue-Red-object-classification | /colour_detection.cpp | UTF-8 | 886 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main()
{
//Reading the image
Mat image = imread("object.jpeg",1);
//to find the intensity of red colour
Mat OutputImage1;
inRange(image,Scalar(100,10,10),Scalar(255,100,100),OutputImage1);
//to find the intensity of blue colour
Mat OutputImage2;
inRange(image,Scalar(10,10,100),Scalar(100,100,255),OutputImage2);
int x1,x2;
x1=countNonZero(OutputImage1);
x2=countNonZero(OutputImage2);
//comparing red and blue
if (x1>x2)
{cout<<"Blue Object";}
else
{cout<<"Red Object";}
//displaying blue component in grey scale
namedWindow("output",CV_WINDOW_FREERATIO);
imshow("output",OutputImage1);
waitKey(0);
//displaying red component
namedWindow("output",CV_WINDOW_FREERATIO);
imshow("output",OutputImage2);
waitKey(0);
}
| true |
ee8205b80c3953fca73a917d6b0ca372cc941c57 | C++ | cutz-j/AIRobotComputing | /homework1/test.cpp | UHC | 5,880 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <GL/glew.h>
#include <GL/wglew.h>
#include <GLFW/glfw3.h>
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glew32.lib")
// Լ & ʱȭ //
int program1(void);
int program2(void);
int program3(void);
static void Initialize(void);
static void RenderScene1(GLFWwindow* window);
static void RenderScene2(GLFWwindow* window);
static void RenderScene3(GLFWwindow* window);
static void MouseClickCallback(GLFWwindow* window, int button, int action, int mods);
static void MouseMotionCallback(GLFWwindow* window, double x, double y);
float mousex = 0, mousey = 0; // mouse button
bool dragging = false; // mouse drag
int pressing = 0; // mouse press
GLfloat RotateX, RotateY, RotateZ; // rotate
GLfloat TranslateX, TranslateY, TranslateZ; // tranlate
int main() {
//program1();
//program2();
program3();
return 0;
}
int program1(void) {
GLFWwindow* window;
glfwInit();
window = glfwCreateWindow(640, 480, "DISPLAY1", NULL, NULL);
glfwMakeContextCurrent(window);
Initialize();
while (!glfwWindowShouldClose(window)) {
RenderScene1(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
return 0;
}
static void Initialize(void) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(1.0, 1.0, 1.0, 1.0);
}
static void RenderScene1(GLFWwindow* window) {
float y = -1.0;
int swit = 1;
glClear(GL_COLOR_BUFFER_BIT);
for (int i = 0; i < 3; i++) {
for (float j = 0.0; j <= 2.0; j += 0.5) {
float x = -1.0;
glPushMatrix();
glBegin(GL_POLYGON);
glColor3f(swit % 2, 0, swit % 2);
glVertex2f(x + j, y);
glVertex2f(x + j + 0.5, y);
glVertex2f(x + j + 0.5, y + 0.666);
glVertex2f(x + j, y + 0.666);
glEnd();
glPopMatrix;
swit += 1;
}
y += 0.666;
}
}
int program2(void) {
GLFWwindow* window;
glfwInit();
window = glfwCreateWindow(640, 480, "DISPLAY1", NULL, NULL);
glfwMakeContextCurrent(window);
Initialize();
while (!glfwWindowShouldClose(window)) {
RenderScene2(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
return 0;
}
static void RenderScene2(GLFWwindow* window) {
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glBegin(GL_TRIANGLES);
glColor3f(0, 1, 0);
glVertex2f(0, 1);
glVertex2f(-1, -0.5);
glVertex2f(1, -0.5);
glEnd();
glPopMatrix();
glPushMatrix();
glBegin(GL_TRIANGLES);
glColor3f(0, 0, 1);
glVertex2f(0, -1);
glVertex2f(-1, 0.5);
glVertex2f(1, 0.5);
glEnd();
glPopMatrix();
}
int program3(void) {
/*
function: 콺 ư + 巡 + ȸ / 3
*/
GLFWwindow* window;
glfwInit();
window = glfwCreateWindow(640, 480, "DISPLAY1", NULL, NULL);
glfwMakeContextCurrent(window);
Initialize();
glfwSetMouseButtonCallback(window, MouseClickCallback);
glfwSetCursorPosCallback(window, MouseMotionCallback);
while (!glfwWindowShouldClose(window)) {
RenderScene3(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
return 0;
}
static void RenderScene3(GLFWwindow* window) {
glClear(GL_COLOR_BUFFER_BIT);
// 1° ~ 6° //
glPushMatrix();
// translate + rotate //
glTranslatef(TranslateX, TranslateY, TranslateZ);
glRotatef(RotateX, 1.0f, 0.0f, 0.0f);
glRotatef(RotateY, 0.0f, 1.0f, 0.0f);
glRotatef(RotateZ, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(0, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(0.5, 0, 0);
glVertex3f(0.5, 0.5, 0);
glVertex3f(0, 0.5, 0);
glEnd();
glPopMatrix();
// 2°
glPushMatrix();
glTranslatef(TranslateX, TranslateY, TranslateZ);
glRotatef(RotateX, 1.0f, 0.0f, 0.0f);
glRotatef(RotateY, 0.0f, 1.0f, 0.0f);
glRotatef(RotateZ, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(0.3, 0.3, 0.3);
glVertex3f(0.5, 0, 0);
glVertex3f(0.5, 0, 0.5);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0.5, 0.5, 0);
glEnd();
glPopMatrix();
// 3°
glPushMatrix();
glTranslatef(TranslateX, TranslateY, TranslateZ);
glRotatef(RotateX, 1.0f, 0.0f, 0.0f);
glRotatef(RotateY, 0.0f, 1.0f, 0.0f);
glRotatef(RotateZ, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(1, 0, 0);
glVertex3f(0.5, 0.5, 0);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0, 0.5, 0.5);
glVertex3f(0, 0.5, 0);
glEnd();
glPopMatrix();
// 4°
glPushMatrix();
glTranslatef(TranslateX, TranslateY, TranslateZ);
glRotatef(RotateX, 1.0f, 0.0f, 0.0f);
glRotatef(RotateY, 0.0f, 1.0f, 0.0f);
glRotatef(RotateZ, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(0, 1, 0);
glVertex3f(0, 0.5, 0);
glVertex3f(0, 0.5, 0.5);
glVertex3f(0, 0, 0.5);
glVertex3f(0, 0, 0);
glEnd();
glPopMatrix();
// 5°
glPushMatrix();
glTranslatef(TranslateX, TranslateY, TranslateZ);
glRotatef(RotateX, 1.0f, 0.0f, 0.0f);
glRotatef(RotateY, 0.0f, 1.0f, 0.0f);
glRotatef(RotateZ, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 0.5);
glVertex3f(0.5, 0, 0.5);
glVertex3f(0.5, 0, 0);
glEnd();
glPopMatrix();
// 6°
glPushMatrix();
glTranslatef(TranslateX, TranslateY, TranslateZ);
glRotatef(RotateX, 1.0f, 0.0f, 0.0f);
glRotatef(RotateY, 0.0f, 1.0f, 0.0f);
glRotatef(RotateZ, 0.0f, 0.0f, 1.0f);
glBegin(GL_QUADS);
glColor3f(1, 1, 0);
glVertex3f(0, 0, 0.5);
glVertex3f(0.5, 0, 0.5);
glVertex3f(0.5, 0.5, 0.5);
glVertex3f(0, 0.5, 0.5);
glEnd();
glPopMatrix();
}
static void MouseClickCallback(GLFWwindow* window, int button, int action, int mods) {
printf("button: %d\n", button);
switch (button) {
case GLFW_MOUSE_BUTTON_1:
dragging = action;
break;
}
}
static void MouseMotionCallback(GLFWwindow* window, double x, double y) {
double scale = 0.1;
if (dragging){
printf("x: %f, y: %f\n", (mousex - x), (mousey - y));
RotateY += (mousex - x) * scale;
RotateX += (mousey - y) * scale;
}
mousex = x;
mousey = y;
} | true |
d8d3264b846f9472ea7b4680cf800dc8401c2577 | C++ | Matthiaas/roads.sexy | /hackatum-2019/src/xodr/validation/road_link_validation.h | UTF-8 | 9,048 | 2.96875 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | #pragma once
#include <string>
#include <memory>
#include "validation/link_validation_base.h"
#include "xodr_map_keys.h"
namespace aid { namespace xodr {
class XodrMap;
class LaneSection;
/**
* @brief Validates the links (road links and lane links) in the given XodrMap.
*
* @param map The XodrMap whose links to validate.
* @param errors The vector to which errors will be appended if
* validation fails.
* @returns True if validation succeeded, false if there was at
* least a single error.
*/
bool validateLinks(const XodrMap& map, std::vector<std::unique_ptr<LinkValidationError>>& errors);
/**
* @brief Validates the links (both road and lane links) between the 'from'
* contact point and the 'to' contact point.
*
* This function should be used when the link from the 'from' contact point to
* the 'to' contact point is of type RoadLink::ElementType::ROAD.
*
* If the link is of type RoadLink::ElementType::JUNCTION, use
* validateIncomingConnectingLink() instead.
*
* The road link validation functions are directed, so to fully validate a pair
* of road contact points A and B, two calls to one of the road validation
* functions need to be made: One for links from A to B, and one for links from
* B to A.
*
* @param map The XodrMap which contains the data to validate.
* @param fromContactPointKey The key of the 'from' contact point.
* @param toContactPointKey The key of the 'to' contact point.
* @param errors The vector to which errors will be appended if
* validation fails.
* @returns True if validation succeeded, false if there was
* at least a single error.
*/
bool validateRoadRoadLink(const XodrMap& map, RoadContactPointKey fromContactPointKey,
RoadContactPointKey toContactPointKey,
std::vector<std::unique_ptr<LinkValidationError>>& errors);
/**
* @brief Validates the links (both road and lane links) between the 'from'
* contact point and the 'to' contact point, for the case when 'from' is
* connected to 'to' through a junction.
*
* See validateRoadRoadLink() for more details.
*
* @param map The XodrMap which contains the data to validate.
* @param fromContactPointKey The key of the 'from' contact point.
* @param toContactPointKey The key of the 'to' contact point.
* @param connectionKey The key of the junction connection which
* connects 'from' to 'to'.
* @param errors The vector to which errors will be appended if
* validation fails.
* @returns True if validation succeeded, false if there was
* at least a single error.
*/
bool validateIncomingConnectingLink(const XodrMap& map, RoadContactPointKey fromContactPointKey,
RoadContactPointKey toContactPointKey, JunctionConnectionKey connectionKey,
std::vector<std::unique_ptr<LinkValidationError>>& errors);
/**
* @brief The base class for link validation errors which relate to road links
* (as opposed to lane links).
*
* Road link validation errors always occur in the context of a road contact
* point A which links to a different road contact point B.
*/
class RoadLinkValidationError : public LinkValidationError
{
public:
/**
* @brief The key of contact point A.
*/
RoadContactPointKey aContactPointKey_;
/**
* @brief The key of contact point B.
*/
RoadContactPointKey bContactPointKey_;
};
/**
* @brief An error indicating that road link symmetry is violated because of a
* missing back-link.
*
* For any 2 roads contact points A and B, if contact point A links to contact
* point B, then contact point B must link back to contact point A. This error
* is generated when a link from contact point A to a contact point B exists,
* but a link from contact point B, which should link back to contact point A,
* isn't specified.
*/
class RoadBackLinkNotSpecifiedError : public RoadLinkValidationError
{
public:
/**
* @brief Provides a human readable description of this error
*
* @param map The XodrMap to which this error applies.
* @return The error message.
*/
virtual std::string description(const XodrMap& map) const override;
/**
* @brief If specified (ie, not -1), the index of the junction which
* contains the connection from contact point A to contact point B. If not
* specified (ie, -1), then contact point A directly links to contact point B.
*/
int aToBJunctionIdx_;
};
/**
* @brief An error indicating that road link symmetry is violated because of a
* missing back-link in a junction.
*
* For any 2 road contact points A and B, if contact point A links to contact
* point B, then contact point B must link back to contact point A. This error
* is generated when a link from contact point A to contact point B exists, but
* contact point B links to a junction which doesn't contain a connection back
* to contact point A.
*/
class RoadBackLinkNotSpecifiedInJunctionError : public RoadLinkValidationError
{
public:
/**
* @brief Provides a human readable description of this error
*
* @param map The XodrMap to which this error applies.
* @return The error message.
*/
virtual std::string description(const XodrMap& map) const override;
/**
* @brief If specified (ie, not -1), the index of the junction which
* contains the connection from contact point A to contact point B. If not
* specified (ie, -1), then contact point A directly links to contact point B.
*/
int aToBJunctionIdx_;
/**
* @brief The junction connected to contact point b, which was expected to
* contain a link back to contact point a, but actually doesn't.
*/
int backLinkJunctionIdx_;
};
/**
* @brief An error indicating that road link symmetry is violated because of
* mismatching road links.
*
* For any 2 road contact points A and B, if contact point A links to contact
* point B, then contact point B must link back to contact point A. This error
* is generated when a link from contact point A to a contact point B exists,
* but the link in B which should link back to A instead links to a different
* road contact point C.
*/
class RoadLinkMisMatchError : public RoadLinkValidationError
{
public:
/**
* @brief Provides a human readable description of this error
*
* @param map The XodrMap to which this error applies.
* @return The error message.
*/
virtual std::string description(const XodrMap& map) const override;
/**
* @brief The key of contact point C.
*
* This is the contact point to which the link from contact point B, which
* was expected to link back to contact point A, actually links.
*/
RoadContactPointKey cContactPointKey_;
/**
* @brief If specified (ie, not -1), the index of the junction which
* contains the connection from contact point A to contact point B. If not
* specified (ie, -1), then contact point A directly links to contact point B.
*/
int aToBJunctionIdx_ = -1;
};
/**
* @brief An error indicating that a direct link to a road in a junction was found.
*
* For any 2 road contact points A and B, if B is part of a junction, then the
* connection from A to B should by specified as a connection in the junction.
* This error is generated when B is part of a junction, yet contact point A
* tries to connect to it directly.
*/
class DirectLinkToJunctionRoadError : public RoadLinkValidationError
{
public:
/**
* @brief Provides a human readable description of this error
*
* @param map The XodrMap to which this error applies.
* @return The error message.
*/
virtual std::string description(const XodrMap& map) const override;
};
/**
* @brief An error indicating that adjacent junction paths (both in different
* junctions) have inconsistent directions.
*/
class InconsistentJunctionPathDirectionsError : public RoadLinkValidationError
{
public:
/**
* @brief Provides a human readable description of this error
*
* @param map The XodrMap to which this error applies.
* @return The error message.
*/
virtual std::string description(const XodrMap& map) const override;
/**
* @brief The junction which contains the connection from contact point A to
* contact point B.
*/
int aToBJunctionIdx_;
/**
* @brief The junction which contains the connection from contact point B to
* contact point A.
*/
int bToAJunctionIdx_;
};
}} // namespace aid::xodr
| true |
b0341ecfeb442ebdbec8596215aab81442f6fe8e | C++ | restuadipradana/SYF-EmbeddedSystem-Projects | /MD_ESP8266/MD_ESP8266.ino | UTF-8 | 1,758 | 2.59375 | 3 | [] | no_license | #include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
const char* ssid = "MES";
const char* password = "00000000";
IPAddress staticIP(172,16,3,80); // IP the board
IPAddress gateway(172,16,3,254);
IPAddress subnet(255,255,0,0);
void setup() {
Serial.begin(115200); //Serial connection
WiFi.begin(ssid, password); //WiFi connection
WiFi.config(staticIP, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
delay(500);
Serial.println("Waiting for connection");
}
Serial.println("Connected..! :*");
}
void loop() {
String LocalIP = String() + WiFi.localIP()[0] + "." + WiFi.localIP()[1] + "." + WiFi.localIP()[2] + "." +
WiFi.localIP()[3];
if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://172.16.1.7:80/MetalDetector/api/Sensor/Sensor"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
String httpRequestData = "device_ip=" + String(LocalIP) + "&device_mac=" + String(WiFi.macAddress())
+ "&detect_id=2&date_time=2020/3/9 18:1:40&date_only=2020/3/9 ";
Serial.println(httpRequestData);
int httpCode = http.POST(httpRequestData); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
}else{
Serial.println("Error in WiFi connection");
}
delay(20000); //Send a request every 30 seconds
}
| true |
8348123523855ca13ca3600bc0bb8383a2426a85 | C++ | HaMinhThanh/GimmickNes | /Gimmick/Gimmick/Camera.h | UTF-8 | 776 | 2.515625 | 3 | [] | no_license | #pragma once
class CCamera
{
public:
static CCamera* __instance;
CCamera();
~CCamera();
//RECT GetBound();
float cam_x = 0.0f;
float cam_y = 0.0f;
int _xLeft, _xRight, _yTop, _yBot;
bool isMovingCam = false;
int oLeft, oRight;
int oTop = 1;
void SetCamPos(float x, float y) { cam_x = x; cam_y = y; }
void GetCamPos(float& x, float& y) { x = cam_x; y = cam_y; }
void SetOldBound(int x, int y) { oLeft = x, oRight = y; }
int GetYBoundary() { return _yBot; }
void SetCamBoundary(float x1, float x2, float t) { _xLeft = x1; _xRight = x2; _yTop = t; }
void GetCamBoundary(float& x1, float& x2, float& t) { x1 = _xLeft; x2 = _xRight; t = _yTop; }
void SetYBoundary(int b) { _yBot = b; }
void MovingCamX(float cx);
static CCamera* GetInstance();
};
| true |
7e1625121a54f2961d319da374d48a189b42e714 | C++ | Duncan15/ACM_repository | /求排列的逆序数.cpp | UTF-8 | 1,191 | 3.078125 | 3 | [] | no_license | #include <iostream>
void Merge_and_Count(int a[],int s,int m,int e,int tmp[],long long & counter)
{
int pb=0;
int p1=s,p2=m+1;
while(p1<=m&&p2<=e)
{
if(a[p1]<=a[p2])
{
tmp[pb++]=a[p2++];
}
else
{
tmp[pb++]=a[p1++];
counter+=(e-p2+1);//计算s1 s2中能组成逆序数的对
}
}
while(p1<=m)
{
tmp[pb++]=a[p1++];
}
while(p2<=e)
{
tmp[pb++]=a[p2++];
}
for(int i=0;i<e-s+1;i++)
{
a[s+i]=tmp[i];
}
}
void MergeSort_and_Count(int a[],int s,int e,int tmp[],long long & counter)
{
if(s<e)
{
int m=s+(e-s)/2;
MergeSort_and_Count(a, s, m, tmp,counter);
MergeSort_and_Count(a, m+1, e, tmp,counter);
Merge_and_Count(a, s, m, e, tmp, counter);
}
}
using namespace std;
int main(int argc, const char * argv[]) {
int n;
scanf("%d",&n);
int* a=new int[n];
int* tmp=new int[n];
for(int i=0;i<n;i++)
{
scanf("%d",a+i);
}
long long counter=0;
MergeSort_and_Count(a, 0, n-1, tmp, counter);
printf("%lld\n",counter);
return 0;
}
| true |
98d75155d9720679534a85262495b94540ebb61b | C++ | dtcxzyw/OI-Source | /Unclassified/Done/3746.cpp | UTF-8 | 945 | 2.53125 | 3 | [] | no_license | #include <cstdio>
int prime[1<<15];
bool flag[1<<15]={};
int calcPhi(int x){
int cnt=0;
for(int i=2;i<=x;++i){
if(!flag[i])prime[++cnt]=i;
for(int j=1;prime[j]*i<(1<<15);++j){
flag[prime[j]*i]=true;
if(!(i%prime[j]))break;
}
}
for(int i=1;i<=cnt;++i)
if(!(x%prime[i]))
x=x/prime[i]*(prime[i]-1);
return x-1;
}
int powm(long long x,int k,long long p){
long long res=1;
while(k){
if(k&1)res=res*x%p;
k>>=1,x=x*x%p;
}
return res;
}
long long cache=1;
int C(int m,int n,int p,int phi){
long long res=cache;
for(int i=2;i<=m;++i)
res=res*powm(i,phi,p)%p;
for(int i=2;i<=n-m;++i)
res=res*powm(i,phi,p)%p;
return res;
}
int main(){
int n,p,k,r;
scanf("%d%d%d%d",&n,&p,&k,&r);
int phi=calcPhi(p);
n*=k;
for(int i=2;i<=n;++i)
cache=cache*i%p;
int ans=0;
for(int i=r;i<=n;i+=k)
ans=(ans+C(i,n,p,phi))%p;
printf("%d\n",ans);
return 0;
}
| true |
107de1c80b17cda104913252b5f250f5a423e3fa | C++ | TimCheers/Lab18.13 | /Lab18.13/Money.cpp | UTF-8 | 2,863 | 3.28125 | 3 | [] | no_license | #include "Money.h"
int random1(int a, int b)
{
if (a > 0) return a + rand() % (b - a);
else return a + rand() % (abs(a) + b);
}
Money::Money()
{
R = random1(1, 1000);
K = random1(1, 99);
}
Money::Money(unsigned long int R, unsigned int K)
{
this->K = K;
this->R = R;
}
Money::Money(const Money& other)
{
this->K = other.K;
this->R = other.R;
}
Money::~Money()
{
}
void Money::show()
{
cout << R << '.' << K << endl;
}
Money& Money:: operator = (const Money& other)
{
this->K = other.K;
this->R = other.R;
return *this;
}
bool Money:: operator == (const Money& other)
{
return this->R == other.R && this->K == other.K;
}
bool Money:: operator > (const Money& other)
{
if (this->R > other.R)
{
return true;
}
else
{
return false;
}
}
bool Money:: operator != (const Money& other)
{
return !(this->R == other.R && this->K == other.K);
}
Money Money:: operator +(const Money& other)
{
Money tmp;
int tmpK = 0, tmpR = 0;
tmp.K = this->K + other.K;
if (tmp.K >= 100)
{
tmpR = tmp.K / 100;
tmpK = tmp.K - tmpR * 100;
tmp.K = tmpK;
}
tmp.R = this->R + other.R + tmpR;
return tmp;
}
Money Money :: operator -(const Money& other)
{
Money tmp;
int tmpK = 0, tmpR = 0;
tmp.R = this->R - other.R;
tmp.K = this->K - other.K;
if (this->K < other.K)
{
tmp.R--;
tmp.K = 100 - abs(this->K - other.K);
}
return tmp;
}
Money Money :: operator -(const double value)
{
Money tmp;
int tmpp = (value - int(value)) * 100;
tmp.R = this->R - (int)value;
tmp.K = this->K - tmpp;
if (this->K < tmpp)
{
tmp.R--;
tmp.K = 100 - abs(this->K - tmpp);
}
return tmp;
}
Money Money :: operator /(const int value)
{
Money tmp;
tmp.R = this->R / value;
tmp.K = this->K;
return tmp;
}
bool Money:: operator < (const Money& other) const
{
if (this->R < other.R)
{
return true;
}
else
{
return false;
}
}
Money Money:: operator +(const Money& other) const
{
Money tmp;
int tmpK = 0, tmpR = 0;
tmp.K = this->K + other.K;
if (tmp.K >= 100)
{
tmpR = tmp.K / 100;
tmpK = tmp.K - tmpR * 100;
tmp.K = tmpK;
}
tmp.R = this->R + other.R + tmpR;
return tmp;
}
void Money:: operator +=(Money& other)
{
int tmpK = 0, tmpR = 0;
this->K = this->K + other.K;
if (this->K >= 100)
{
tmpR = this->K / 100;
tmpK = this->K - tmpR * 100;
this->K = tmpK;
}
this->R = this->R + other.R + tmpR;
}
ostream& operator << (ostream& out, const Money& other)
{
return (out << other.R << '.' << other.K);
}
istream& operator >> (istream& in, Money& other)
{
char ch;
in >> other.R >> ch >> other.K;
return in;
} | true |
dcadddbd2ac475ffcbe120b7c534fc9ae766edbd | C++ | ppdg123/lc | /1111.cpp | UTF-8 | 729 | 3.265625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> maxDepthAfterSplit(string seq) {
int l = 0;
int r = 0;
vector<int> ans;
for (int i=0; i< seq.size(); ++i) {
if (seq[i] == '(') {
if(l<=r) {
l ++;
ans.push_back(0);
} else {
r ++;
ans.push_back(1);
}
} else {
if(l<=r) {
r --;
ans.push_back(1);
} else {
l --;
ans.push_back(0);
}
}
}
return ans;
}
};
int main(){
Solution s;
vector<int> ans = s.maxDepthAfterSplit("()(())()");
for (int i = 0; i< ans.size(); ++i) {
printf("%d\n",ans[i]);
}
return 0;
}
| true |
bfc1cf93db7118a263a3a277f7aa2b23eca7457d | C++ | tkchris93/CS236 | /lab3/EvalContainer.h | UTF-8 | 774 | 2.78125 | 3 | [] | no_license | #ifndef _EVAL_CONTAINER_H
#define _EVAL_CONTAINER_H
#include "Relation.h"
#include "Parameter.h"
#include <vector>
using namespace std;
class EvalContainer
{
public:
EvalContainer()
{
this->relation = Relation();
this->projections = vector<Parameter>();
this->rename_before = vector<Parameter>();
this->rename_after = vector<Parameter>();
}
EvalContainer(Relation r, vector<Parameter> p, vector<Parameter> rb, vector<Parameter> ra)
{
this->relation = r;
this->projections = p;
this->rename_before = rb;
this->rename_after = ra;
}
Relation relation;
vector<Parameter> projections;
vector<Parameter> rename_before;
vector<Parameter> rename_after;
};
#endif
| true |
2ad81393d400547729d64d35ab7ede96a56d767d | C++ | aacuadras/hw_TILE | /HW-TILE/tiling.cpp | UTF-8 | 9,624 | 3.21875 | 3 | [] | no_license | #ifndef BIPARTGRAPH_H
#define BIPARTGRAPH_H
#include "tiling.h"
#include "vertex.h"
using namespace std;
// Finds a (shortest according to edge length) augmenting path
// from s to t in a graph with vertex set V.
// Returns whether there is an augmenting path.
bool augmenting_path(Vertex* s, Vertex* t, unordered_set<Vertex*> V, vector<Vertex*> &P)
{
// Check that s and t aren't nullptr
if (s == nullptr || t == nullptr)
{
cerr << "augmenting_path() was passed nullptr s or t." << endl;
abort();
}
// Check that s and t are in the graph
if (V.find(s) == V.end() || V.find(t) == V.end())
{
cerr << "augmenting_path() was passed s or t not in V." << endl;
abort();
}
// Check that every vertex has valid neighs/weights.
for (Vertex* v : V)
for (Vertex* vn : v->neighs)
if (v->weights.find(vn) == v->weights.end())
{
cerr << "augmenting_path() was passed invalid vertex." << endl;
abort();
}
// Since augmenting paths should have the fewest edges,
// not the minimum weight, run BFS.
queue<Vertex*> Q;
Q.push(s);
unordered_set<Vertex*> R;
R.clear();
R.insert(s);
unordered_map<Vertex*, Vertex*> prev;
while (!Q.empty())
{
Vertex* cur = Q.front();
Q.pop();
for (Vertex* nei : cur->neighs)
{
// Must have positive edge weight
if (cur->weights[nei] == 0)
continue;
if (R.find(nei) == R.end())
{
Q.push(nei);
R.insert(nei);
prev[nei] = cur;
}
}
}
// If BFS never reached t
if (R.find(t) == R.end())
return false;
// Reconstruct shortest path backwards
P.clear();
P.push_back(t);
while (P[P.size() - 1] != s)
P.push_back(prev[P[P.size() - 1]]);
// Reverse shortest path
for (int i = 0; i < P.size() / 2; ++i)
swap(P[i], P[P.size() - 1 - i]);
return true;
}
// Returns the maximum flow from s to t in a weighted graph with vertex set V.
// Assumes all edge weights are non-negative.
int max_flow(Vertex* s, Vertex* t, unordered_set<Vertex*> V)
{
// If s or t is invalid.
if (s == nullptr || t == nullptr)
{
cerr << "max_flow() was passed nullptr s or t." << endl;
abort();
}
// If s or t is not in the vertex set.
if (V.find(s) == V.end() || V.find(t) == V.end())
{
cerr << "max_flow() was passed s or t not in V." << endl;
abort();
}
// Check that every vertex has valid neighs/weights.
for (Vertex* v : V)
for (Vertex* vn : v->neighs)
if (v->weights.find(vn) == v->weights.end())
{
cerr << "max_flow() was passed invalid vertex." << endl;
abort();
}
// Create a deep copy of V to use as the residual graph
unordered_set<Vertex*> resV;
unordered_map<Vertex*, Vertex*> C; // Maps vertices in V to copies in resV
for (Vertex* vp : V)
{
Vertex* rp = new Vertex;
resV.insert(rp);
C[vp] = rp;
}
for (Vertex* vp : V)
for (Vertex* np : vp->neighs)
{
C[vp]->neighs.insert(C[np]);
C[vp]->weights[C[np]] = vp->weights[np];
}
// Add any missing necessary "back" edges.
for (Vertex* vp : V)
for (Vertex* np : vp->neighs)
{
if (C[np]->neighs.find(C[vp]) == C[np]->neighs.end())
{
C[np]->neighs.insert(C[vp]);
C[np]->weights[C[vp]] = 0;
}
}
// Run Edmonds-Karp
while (true)
{
// Find an augmenting path
vector<Vertex*> P;
if (!augmenting_path(C[s], C[t], resV, P))
break;
// Update residual graph
for (int i = 0; i < P.size() - 1; ++i)
{
--((*(resV.find(P[i])))->weights[P[i + 1]]);
++((*(resV.find(P[i + 1])))->weights[P[i]]);
}
}
// Compute actual flow amount
int flow = 0;
for (Vertex* snp : C[s]->neighs)
flow += 1 - C[s]->weights[snp];
// Delete residual graph
for (Vertex* vp : resV)
delete vp;
return flow;
}
class BiPartGraph
{
private:
//Stores the number of vertices, used to determine the first condition in has_tiling
int numVertices;
//Stores the set with all the vertices
unordered_set<Vertex*> totalCheckers;
//Stores the set of black checkers in the bipartite graph
unordered_set<Vertex*> blackCheckers;
//Stores the set of red checkers in the bipartite graph
unordered_set<Vertex*> redCheckers;
//Stores all the vertices in the graph with their coordinates
unordered_map<Vertex*, pair<int, int>> vertexDictionary;
//The vertices will be used for max flow and be computed for perfect matching
Vertex *source;
Vertex *sink;
void addNeighbors()
{
string dummy = "";
for (auto i : blackCheckers)
{
pair<int, int> up, down, left, right;
//Set up coordinates
up.first = vertexDictionary.at(i).first - 1;
up.second = vertexDictionary.at(i).second;
//Set down coordinates
down.first = vertexDictionary.at(i).first + 1;
down.second = vertexDictionary.at(i).second;
//Set left coordinates
left.first = vertexDictionary.at(i).first;
left.second = vertexDictionary.at(i).second - 1;
//Set right coordinates
right.first = vertexDictionary.at(i).first;
right.second = vertexDictionary.at(i).second + 1;
//Step 1: Try to search for a neighbor up
for (auto k : redCheckers)
{
if (vertexDictionary.at(k) == up)
{
i->neighs.insert(k);
i->weights[k] = 1;
}
else if (vertexDictionary.at(k) == down)
{
i->neighs.insert(k);
i->weights[k] = 1;
}
else if (vertexDictionary.at(k) == left)
{
i->neighs.insert(k);
i->weights[k] = 1;
}
else if (vertexDictionary.at(k) == right)
{
i->neighs.insert(k);
i->weights[k] = 1;
}
}
}
}
//This function connects the source to all the blac checkers
void setSource()
{
for (auto i : blackCheckers)
{
source->neighs.insert(i);
//Sets the max flow to 1
source->weights[i] = 1;
}
totalCheckers.insert(source);
}
//This function connects all the red checkers to the sink
void setSink()
{
for (auto i : redCheckers)
{
i->neighs.insert(sink);
//Sets the max flow to 1
i->weights[sink] = 1;
}
totalCheckers.insert(sink);
}
public:
//Default constructor
BiPartGraph()
{
source = new Vertex();
sink = new Vertex();
numVertices = 0;
}
//This function returns false if the two sets do not have the same number of elements
bool isValid()
{
if (blackCheckers.size() == redCheckers.size())
return true;
else
return false;
}
void constructGraph(string floor)
{
int row = 0;
int column = 0;
for (int i = 0; i < floor.length(); i++)
{
if (floor[i] == '#')
column++;
else if (floor[i] == '\n')
{
row++;
column = 0;
}
else if (floor[i] == 'b')
{
Vertex * baby = new Vertex();
pair<int, int> bPair;
bPair.first = row;
bPair.second = column;
blackCheckers.insert(baby);
totalCheckers.insert(baby);
vertexDictionary[baby] = bPair;
column++;
}
else
{
Vertex * baby = new Vertex();
pair<int, int> bPair;
bPair.first = row;
bPair.second = column;
redCheckers.insert(baby);
totalCheckers.insert(baby);
vertexDictionary[baby] = bPair;
column++;
}
}
addNeighbors();
setSource();
setSink();
}
Vertex* GetSource()
{
return source;
}
Vertex* GetSink()
{
return sink;
}
int getFlow()
{
return max_flow(source, sink, totalCheckers);
}
int getB()
{
int counter = 0;
for (auto i : blackCheckers)
{
counter++;
}
return counter;
}
///Helper method to display variables
void displayFlow()
{
int counter = 1;
cout << "Source" << endl;
cout << "Neighbors: ";
for (auto x : source->neighs)
cout << vertexDictionary[x].first << "," << vertexDictionary[x].second << " :: ";
cout << endl;
for (auto i : vertexDictionary)
{
cout << counter << ": " << i.second.first << "," << i.second.second << endl;
cout << "Neighbors: ";
for (auto k : i.first->neighs)
{
cout << vertexDictionary[k].first << "," << vertexDictionary[k].second << " :: ";
}
counter++;
cout << endl;
}
cout << "Sink" << endl;
cout << "Neighbors: ";
for (auto y : sink->neighs)
cout << vertexDictionary[y].first << "," << vertexDictionary[y].second << " :: ";
cout << endl;
system("pause");
}
};
bool has_tiling(string floor)
{
string modFloor = "";
int row = 0;
int column = 0;
int flow, numB;
bool firstElmnt = false;
bool startsEven;
//This loops transform the string into another string formated as a checkers board
for (int i = 0; i < floor.length(); i++)
{
if (floor[i] == '#')
{
modFloor += floor[i];
column++;
}
else if (floor[i] == '\n')
{
row++;
column = 0;
modFloor += floor[i];
}
else if (floor[i] == ' ')
{
if (!firstElmnt)
{
if (column % 2 == 0)
startsEven = true;
else
startsEven = false;
modFloor += 'b';
firstElmnt = true;
}
else if (startsEven)
{
if (row % 2 != 0)
{
if (column % 2 == 0)
modFloor += 'b';
else
modFloor += 'r';
}
else
{
if (column % 2 != 0)
modFloor += 'b';
else
modFloor += 'r';
}
}
else
{
if (row % 2 != 0)
{
if (column % 2 == 0)
modFloor += 'r';
else
modFloor += 'b';
}
else
{
if (column % 2 != 0)
modFloor += 'r';
else
modFloor += 'b';
}
}
column++;
}
}
BiPartGraph CheckerBoard;
CheckerBoard.constructGraph(modFloor);
if (CheckerBoard.isValid() == false)
{
return false;
}
Vertex *s = CheckerBoard.GetSource();
Vertex *t = CheckerBoard.GetSink();
//max flow
flow = CheckerBoard.getFlow();
numB = CheckerBoard.getB();
//augmented path
//cout << modFloor << endl;
//CheckerBoard.displayFlow();
if (flow == numB)
return true;
else
return false;
}
#endif // !BIPARTGRAPH_H | true |
ae6c2598c214bbb3856f44aeecd5a7e891982579 | C++ | ferthu/VulkanProject | /VulkanProject/VulkanProject/include/VertexBufferVulkan.h | UTF-8 | 961 | 2.65625 | 3 | [] | no_license | #pragma once
#include<vulkan/vulkan.h>
class VulkanRenderer;
class VertexBufferVulkan
{
public:
enum DATA_USAGE { STATIC = 0, DYNAMIC = 1, DONTCARE = 2 };
/* Binding used to bind vertex buffers.
*/
struct Binding {
uint32_t sizeElement, numElements, offset;
VertexBufferVulkan* buffer;
void bind(VkCommandBuffer cmdBuf, uint32_t location);
Binding();
Binding(VertexBufferVulkan* buffer, uint32_t sizeElement, uint32_t numElements, uint32_t offset);
size_t byteSize() { return sizeElement * numElements; }
};
VertexBufferVulkan(VulkanRenderer *renderHandle, size_t size, DATA_USAGE usage);
~VertexBufferVulkan();
void setData(const void* data, size_t size, size_t offset);
void setData(const void* data, Binding& binding);
void bind(VkCommandBuffer cmdBuf, size_t offset, size_t size, unsigned int location);
void unbind();
size_t getSize();
VkBuffer _bufferHandle;
private:
VulkanRenderer* _renderHandle;
size_t memSize;
};
| true |
f52331ec1118fca3984e6e8b05bca982dd0783f1 | C++ | symanli/just-p2p-live-p2pcommon2 | /new/util/BitMap.cpp | GB18030 | 12,652 | 2.640625 | 3 | [] | no_license |
#include "StdAfx.h"
#include <ostream>
#include "BitMap.h"
#include "util/HuffmanCoding.h"
void Bitfield::SetBit(size_t index, bool val)
{
if (!IsInRange(index))
{
LIVE_ASSERT(!"Bitfield::SetBit: index is out of range.");
return;
}
size_t pos = GetByteIndex(index);
LIVE_ASSERT(pos < m_bits->size());
BYTE& bit = reinterpret_cast<BYTE&>((*m_bits)[pos]);
BYTE mask = (BYTE)GetByteMask(index);
if (val)
{
// maskָλΪ1λΪ0
bit |= mask;
}
else
{
// maskָλΪ0λΪ1
bit &= (~mask);
}
}
string Bitfield::ToString() const
{
string str;
str.reserve(GetSize() + 1);
for(size_t i = 0; i< GetSize(); i ++)
{
if( GetBit(i) )
str += '1';
else
str += '0';
}
return str;
}
bool Bitfield::CheckIsAllBitsSet() const
{
if (GetSize() == 0)
return false;
bool ifMeetBit = false;
bool ifMeedZero = false;
size_t count = 0;
for (int index = (int)GetSize() - 1; index >= 0; --index, ++count)
{
bool isSet = GetBit(index);
if (isSet)
{
// 1
if (!ifMeetBit)
{
ifMeetBit = true;
}
}
else
{
// 0
if (ifMeetBit)
{
// 10
ifMeedZero = true;
}
else
{
if (count > 8)
return false;
}
}
}
return ifMeetBit && !ifMeedZero;
}
UINT Bitfield::FindSkipIndex() const
{
if (GetSize() == 0)
return 0;
const int max_hole = 5;
int leftHole = max_hole;
UINT skipIndex = 0;
for (size_t index = 0; index < GetSize(); ++index)
{
bool isSet = GetBit(index);
if (isSet)
{
// 1
skipIndex = (UINT)index;
}
else
{
--leftHole;
if (leftHole == 0)
break;
}
}
return skipIndex;
}
/*
void BitMap::Revise(UINT32 newMinIndex, UINT16 startPos, UINT16 resLen, const UINT8 resources[])
{
// ԴλͼoldMax
UINT32 oldMax = GetMaxIndex();
// ԴλͼnewMaxTemp
UINT32 newMaxTemp = newMinIndex + startPos + resLen * 8;
UINT32 newMax = max(oldMax, newMaxTemp);
LIVE_ASSERT(newMax >= newMinIndex);
size_t newSize = newMax - newMinIndex;
BitMap newBits(newMinIndex, newSize);
UINT32 i = 0;
for (i = newBits.GetMinIndex(); i < newBits.GetMaxIndex(); ++i)
{
LIVE_ASSERT(newBits.IsInRange(i));
newBits.SetBit(i, GetBit(i));
}
BitMap changedBits(newMinIndex + startPos, resLen, resources);
for (i = changedBits.GetMinIndex(); i < changedBits.GetMaxIndex(); ++i)
{
LIVE_ASSERT(newBits.IsInRange(i));
bool bit = changedBits[i];
// bitΪtrueʾУֲ
if (bit)
{
newBits.SetBit(i);
}
}
Swap(newBits);
LIVE_ASSERT(GetMinIndex() == newMinIndex);
LIVE_ASSERT(GetSize() == newSize);
LIVE_ASSERT(GetMaxIndex() == newMax);
}*/
void BitMap::EraseBit(UINT32 index)
{
if (!IsInRange(index))
return;
ResetBit(index);
}
string BitMap::ToString() const
{
char startTag[32] = { 0 };
::_snprintf(startTag, 31, "%u", m_minIndex);
string startTagString = startTag;
return "(" + startTagString + ":" + m_bits.ToString() + ")";
}
UINT8 BitMap::GetHuffmanString(pool_byte_string_ptr& buf, HuffmanCoding& coding)
{
return coding.Encode( m_bits.GetBuffer(), m_bits.GetSize(), buf );
}
std::ostream& operator<<(std::ostream& os, const Bitfield& bf)
{
return os << bf.ToString();
}
std::ostream& operator<<(std::ostream& os, const BitMap& bitmap)
{
return os << "(" << bitmap.GetMinIndex() << ":" << bitmap.GetData() << ")";
}
#ifdef _RUN_TEST
#include <ppl/util/random.h>
#include <ppl/util/test_case.h>
class BitfieldTestCase : public ppl::util::test_case
{
virtual void DoRun()
{
LIVE_ASSERT(CalcRound8(0) == 0);
LIVE_ASSERT(CalcRound8(1) == 8);
LIVE_ASSERT(CalcRound8(2) == 8);
LIVE_ASSERT(CalcRound8(3) == 8);
LIVE_ASSERT(CalcRound8(4) == 8);
LIVE_ASSERT(CalcRound8(5) == 8);
LIVE_ASSERT(CalcRound8(6) == 8);
LIVE_ASSERT(CalcRound8(7) == 8);
LIVE_ASSERT(CalcRound8(8) == 8);
LIVE_ASSERT(CalcRound8(9) == 16);
LIVE_ASSERT(CalcRoundQuotient8(0) == 0);
LIVE_ASSERT(CalcRoundQuotient8(1) == 1);
LIVE_ASSERT(CalcRoundQuotient8(2) == 1);
LIVE_ASSERT(CalcRoundQuotient8(3) == 1);
LIVE_ASSERT(CalcRoundQuotient8(4) == 1);
LIVE_ASSERT(CalcRoundQuotient8(5) == 1);
LIVE_ASSERT(CalcRoundQuotient8(6) == 1);
LIVE_ASSERT(CalcRoundQuotient8(7) == 1);
LIVE_ASSERT(CalcRoundQuotient8(8) == 1);
LIVE_ASSERT(CalcRoundQuotient8(9) == 2);
Bitfield bf;
LIVE_ASSERT(bf.GetSize() == 0);
LIVE_ASSERT(bf.GetByteCount() == 0);
BYTE bytes[1] = { 0x0 };
bf = Bitfield(1, bytes);
LIVE_ASSERT(bf.GetSize() == 8);
LIVE_ASSERT(bf.GetByteCount() == 1);
CheckBits(bf, 0, bf.GetSize(), false);
LIVE_ASSERT(bf.ToString() == "00000000");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
size_t i = 0;
for (i = 0; i < 8; ++i)
{
TestByte(bf, i);
}
bool status;
bf.GetData()[0] = 0xf0;
CheckBits(bf, 0, 4, true);
CheckBits(bf, 4, bf.GetSize(), false);
LIVE_ASSERT(bf.ToString() == "11110000");
LIVE_ASSERT(bf.CheckIsAllBitsSet());
bf.GetData()[0] = 0x0f;
CheckBits(bf, 0, 4, false);
CheckBits(bf, 4, bf.GetSize(), true);
LIVE_ASSERT(bf.ToString() == "00001111");
status = bf.CheckIsAllBitsSet();
LIVE_ASSERT(!status);
LIVE_ASSERT(bf.FindSkipIndex() == 7);
bf.ResetBit(5);
LIVE_ASSERT(!bf[5]);
LIVE_ASSERT(bf.ToString() == "00001011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
LIVE_ASSERT(bf.FindSkipIndex() == 4);
bf.SetBit(5);
LIVE_ASSERT(bf[5]);
LIVE_ASSERT(bf.ToString() == "00001111");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
bf.ResetBit(5);
LIVE_ASSERT(!bf[5]);
LIVE_ASSERT(bf.ToString() == "00001011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
bf.SetBit(2);
LIVE_ASSERT(bf.ToString() == "00101011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
bf.ResetBit(3);
LIVE_ASSERT(bf.ToString() == "00101011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
LIVE_ASSERT(!bf[3]);
LIVE_ASSERT(bf[2]);
LIVE_ASSERT(bf.ToString() == "00101011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
bf.SetBit(3);
LIVE_ASSERT(bf[3]);
LIVE_ASSERT(bf[2]);
LIVE_ASSERT(bf.ToString() == "00111011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
bf.ResetBit(3);
LIVE_ASSERT(!bf[3]);
LIVE_ASSERT(bf[2]);
LIVE_ASSERT(bf.ToString() == "00101011");
LIVE_ASSERT(!bf.CheckIsAllBitsSet());
TestZeroBitfield();
for (i = 0; i < bf.GetSize(); ++i)
{
bf.SetBit(i, true);
}
LIVE_ASSERT(bf.ToString() == "11111111");
LIVE_ASSERT(bf.CheckIsAllBitsSet());
{
BYTE bytes1[2] = { 0xFF, 0xE0 };
Bitfield bf1(2, bytes1);
LIVE_ASSERT(bf1.ToString() == "1111111111100000");
LIVE_ASSERT(bf1.CheckIsAllBitsSet());
LIVE_ASSERT(bf1.FindSkipIndex() == 10);
}
{
BYTE bytes1[2] = { 0xFF, 0xE8 };
Bitfield bf1(2, bytes1);
LIVE_ASSERT(bf1.ToString() == "1111111111101000");
LIVE_ASSERT(!bf1.CheckIsAllBitsSet());
LIVE_ASSERT(bf1.FindSkipIndex() == 12);
}
{
BYTE bytes1[3] = { 0xFF, 0xEA, 0xA8 };
Bitfield bf1(3, bytes1);
LIVE_ASSERT(bf1.ToString() == "111111111110101010101000");
LIVE_ASSERT(!bf1.CheckIsAllBitsSet());
LIVE_ASSERT(bf1.FindSkipIndex() == 18);
}
}
/// Ըݳȹλ
void TestZeroBitfield()
{
TestZeroBitfield(0);
TestZeroBitfield(1);
TestZeroBitfield(6);
TestZeroBitfield(16);
TestZeroBitfield(70);
TestZeroBitfield(180);
TestZeroBitfield(660);
TestZeroBitfield(1800);
}
void TestZeroBitfield(size_t size)
{
Bitfield bf(size);
CheckBits(bf, 0, bf.GetSize(), false);
LIVE_ASSERT(bf.ToString() == string(bf.GetSize(), '0'));
}
void CheckBits(const Bitfield& bf, size_t begin, size_t end, bool val)
{
for (size_t i = begin; i < end; ++i)
{
LIVE_ASSERT(bf[i] == val);
LIVE_ASSERT(bf[i] == bf.GetBit(i));
}
}
void TestByte(Bitfield& bf, size_t pos)
{
LIVE_ASSERT(bf.GetSize() == 8);
LIVE_ASSERT(bf.GetByteCount() == 1);
LIVE_ASSERT(pos < 8);
bf.GetData()[0] = static_cast<BYTE>(0x80 >> pos);
LIVE_ASSERT(bf[pos]);
CheckBits(bf, 0, pos, false);
CheckBits(bf, pos + 1, bf.GetSize(), false);
}
};
class StreamBitfieldTestCase : public ppl::util::test_case
{
Random m_random;
virtual void DoRun()
{
TestZeroBitfield();
BitMap bf;
LIVE_ASSERT(bf.GetSize() == 0);
LIVE_ASSERT(bf.GetByteCount() == 0);
BYTE bytes[1] = { 0x0 };
bf = BitMap(0, 1, bytes);
LIVE_ASSERT(bf.GetSize() == 8);
LIVE_ASSERT(bf.GetByteCount() == 1);
CheckBits(bf, 0, bf.GetSize(), false);
for (size_t i = 0; i < 8; ++i)
{
TestByte(bf, i);
}
bf.GetData().GetData()[0] = 0xf0;
CheckBits(bf, 0, 4, true);
CheckBits(bf, 4, bf.GetSize(), false);
bf.GetData().GetData()[0] = 0x0f;
CheckBits(bf, 0, 4, false);
CheckBits(bf, 4, bf.GetSize(), true);
bf.ResetBit(5);
LIVE_ASSERT(!bf[5]);
bf.SetBit(5);
LIVE_ASSERT(bf[5]);
bf.ResetBit(5);
LIVE_ASSERT(!bf[5]);
TestBasic();
}
/// Ըݳȹλ
void TestZeroBitfield()
{
TestZeroBitfield(0);
TestZeroBitfield(1);
TestZeroBitfield(6);
TestZeroBitfield(16);
TestZeroBitfield(70);
TestZeroBitfield(180);
TestZeroBitfield(660);
TestZeroBitfield(1800);
}
void TestZeroBitfield(size_t size)
{
UINT32 minIndex = m_random.Next();
BitMap bf(m_random.Next(), size);
CheckBits(bf, bf.GetMinIndex(), bf.GetMaxIndex(), false);
}
void CheckBits(const BitMap& bf, size_t begin, size_t end, bool val)
{
for (size_t i = begin; i < end; ++i)
{
LIVE_ASSERT(bf[i] == val);
LIVE_ASSERT(bf[i] == bf.GetBit(i));
}
}
void TestByte(BitMap& bf, size_t pos)
{
LIVE_ASSERT(bf.GetSize() == 8);
LIVE_ASSERT(bf.GetByteCount() == 1);
LIVE_ASSERT(pos < 8);
bf.GetData().GetData()[0] = static_cast<BYTE>(0x80 >> pos);
LIVE_ASSERT(bf[pos]);
CheckBits(bf, 0, pos, false);
CheckBits(bf, pos + 1, bf.GetSize(), false);
}
void TestBasic()
{
src[0] = 0xFF;
src[1] = 0x0F;
BitMap bmp(100, 2, src);
LIVE_ASSERT(bmp.GetMinIndex() == 100);
LIVE_ASSERT(bmp.GetMaxIndex() == 116);
size_t i = 0;
for (i = 100; i < 108; ++i)
{
LIVE_ASSERT(bmp[i]);
}
for (i = 108; i < 112; ++i)
{
LIVE_ASSERT(!bmp[i]);
}
for (i = 112; i < 116; ++i)
{
LIVE_ASSERT(bmp[i]);
}
LIVE_ASSERT(!bmp[98]);
LIVE_ASSERT(!bmp[99]);
LIVE_ASSERT(!bmp[116]);
LIVE_ASSERT(!bmp[117]);
}
UINT8 dest[1024];
UINT8 src[1024];
};
class BitMapTestCase : public ppl::util::test_case
{
protected:
virtual void DoRun()
{
// TestDecode();
TestBasic();
// TestHuffman();
}
void TestBasic()
{
src[0] = 0xFF;
src[1] = 0x0F;
BitMap bmp(100, 2, src);
LIVE_ASSERT(bmp.GetMinIndex() == 100);
LIVE_ASSERT(bmp.GetMaxIndex() == 116);
size_t i = 0;
for (i = 100; i < 108; ++i)
{
LIVE_ASSERT(bmp[i]);
}
for (i = 108; i < 112; ++i)
{
LIVE_ASSERT(!bmp[i]);
}
for (i = 112; i < 116; ++i)
{
LIVE_ASSERT(bmp[i]);
}
LIVE_ASSERT(!bmp[98]);
LIVE_ASSERT(!bmp[99]);
LIVE_ASSERT(!bmp[116]);
LIVE_ASSERT(!bmp[117]);
}
/*
void TestDecode()
{
src[0] = 1;
size_t size = BitMap::DecodeBitMap(dest, src, 1);
LIVE_ASSERT(size = 1);
src[0] = 3;
size = BitMap::DecodeBitMap(dest, src, 1);
LIVE_ASSERT(size = 1);
}
*/
/* void TestHuffman()
{
// BitMap bmp;
UINT8 times = 0;
UINT32 i, j = 0;
return;
freopen("D:\\announce\\pick\\pick.txt","r",stdin);
freopen("d:\\announce\\pick\\huf.out","w",stdout);
char b[600];
pool_byte_string huffs, a;
while (std::cin>>a)
{
if (a.length() > 4000||a.length()<=64) continue;
memset(b,0,sizeof(b));
for (i = 0; i < a.length(); i ++)
b[i/8] |=(a[i]-'0')<<(i%8);
//ֽڶʧ
BitMap bmp(0,(a.length()+7)/8,(const char*)b);
huffs = bmp.GetHuffmanString(times);
BitMap huffmap(0,times,huffs.length(),huffs.c_str());
for (i = 0; i < huffmap.GetByteCount()-1; i ++)
LIVE_ASSERT(huffmap.GetBytes()[i] == (BYTE)b[i]);
//printf("%d...........\n",++j);
UTIL_DEBUG(++j);
}
fclose(stdin);fclose(stdout);
}*/
public:
BYTE dest[1024];
BYTE src[1024];
};
CPPUNIT_TEST_SUITE_REGISTRATION(BitfieldTestCase);
CPPUNIT_TEST_SUITE_REGISTRATION(StreamBitfieldTestCase);
CPPUNIT_TEST_SUITE_REGISTRATION(BitMapTestCase);
#endif
| true |
af3cd0ebf3f4a031d01f6061d0cdbc390d8311a5 | C++ | samirharry/ProgramacionCompetitiva | /Clase2/elctronicShop.cpp | UTF-8 | 813 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long Long;
int main(){
Long a,b,c;
cin>>a>>b>>c;
vector<Long> keyboards,usb;
for(Long i=0;i<b;i++){
Long aux;
cin>>aux;
keyboards.push_back(aux);
}
for(Long i=0;i<c;i++){
Long aux;
cin>>aux;
usb.push_back(aux);
}
sort(keyboards.begin(),keyboards.end());
sort(usb.begin(),usb.end());
Long answer =-1;
for(Long i=b-1;i>=0;i--){
for(Long j=c-1;j>=0;j--){
if(keyboards[i]+usb[j]>a){
continue;
}else{
if(keyboards[i]+usb[j] > answer){
answer = keyboards[i]+usb[j];
break;
}
}
}
}
cout<<answer<<endl;
return 0;
} | true |
5d86ab76fb86d32bda0cfc5ba90c91f5e8f856c1 | C++ | adderly/VoltAir | /VoltEngine/Engine/LevelInfo.h | UTF-8 | 4,310 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LEVELINFO_H
#define LEVELINFO_H
#include <QObject>
#include <QString>
class Environment;
/**
* @ingroup Engine
* @brief Metadata for a Level.
*
* The information contained in LevelInfo can be used to load and display a Level.
*/
class LevelInfo : public QObject {
Q_OBJECT
/**
* @brief Human-readable name of the Level.
*/
Q_PROPERTY(QString name READ getName WRITE setName NOTIFY nameChanged)
/**
* @brief Name of QML level file to be used for loading the Level.
*/
Q_PROPERTY(QString fileName READ getFileName WRITE setFileName NOTIFY fileNameChanged)
/**
* @brief Whether or not the Level is a tutorial level.
*/
Q_PROPERTY(bool tutorial READ isTutorial WRITE setTutorial NOTIFY tutorialChanged)
/**
* @brief Name of image asset file for the Level screenshot / thumbnail.
*/
Q_PROPERTY(QString screenshotFileName READ getScreenshotFileName WRITE setScreenshotFileName
NOTIFY screenshotFileNameChanged)
/**
* @brief Environment to which this LevelInfo belongs, or @c null if defined out of the context
* of an Environment.
*/
Q_PROPERTY(Environment* environment READ getEnvironment)
public:
/**
* @brief Constructs a LevelInfo.
* @param parent Parent object
*/
explicit LevelInfo(QObject* parent = nullptr);
/**
* @brief Returns #name.
*/
const QString& getName() const { return mName; }
/**
* @brief Sets #name.
* @param value String to set #name to
*/
void setName(const QString& value);
/**
* @brief Returns #fileName.
*/
const QString& getFileName() const { return mFileName; }
/**
* @brief Sets #fileName.
* @param value String to set #fileName to
*/
void setFileName(const QString& value);
/**
* Return if the file is in level path.
*/
bool isInLevelPath(){return mFileInLevelPath;}
/**
* Set if file is in level path.
*/
void setFileInLevelPath(bool is){mFileInLevelPath = is;}
/**
* @brief Returns #tutorial.
*/
bool isTutorial() const { return mTutorial; }
/**
* @brief Sets #tutorial.
* @param value Boolean to set #tutorial to
*/
void setTutorial(bool value);
/**
* @brief returns if the level has an Environment.
* Note: This is manually set, this does not check
* whether the level's parent is an Environment.
*/
bool hasEnvironment() const { return mHasEnvironment; }
/**
* @brief set #mHasEnvironment to has.
*/
void setHasEnvironment(bool has){ mHasEnvironment = has; }
/**
* @brief Returns #screenshotFileName.
*/
const QString& getScreenshotFileName() const { return mScreenshotFileName; }
/**
* @brief Sets #screenshotFileName.
* @param value String to set #screenshotFileName to
*/
void setScreenshotFileName(const QString& value);
/**
* @brief Returns #environment.
*/
Environment* getEnvironment() const;
signals:
/**
* @brief Emitted when #name changes.
*/
void nameChanged();
/**
* @brief Emitted when #fileName changes.
*/
void fileNameChanged();
/**
* @brief Emitted when #tutorial changes.
*/
void tutorialChanged();
/**
* @brief Emitted when #screenshotFileName changes.
*/
void screenshotFileNameChanged();
private:
bool mFileInLevelPath;
bool mHasEnvironment;
QString mName;
QString mFileName;
bool mTutorial = false;
QString mScreenshotFileName;
mutable Environment* mEnvironment = nullptr;
};
Q_DECLARE_METATYPE(LevelInfo*)
#endif // LEVELINFO_H
| true |
e356a07115d7ed2c86416b8a8f17ca53c3100d05 | C++ | futureshocked/TE-Arduino-SbS-Getting-Serious | /_1300a2_-_nRF24_transmitter/_1300a2_-_nRF24_transmitter.ino | UTF-8 | 2,518 | 2.671875 | 3 | [] | no_license | /* 1300a2 - nRF24 Transmitter
*
* This sketch shows how to create a simple transmitter using the nRF24 module.
*
* This sketch was written by Peter Dalmaris for Arduino Step by Step
*
* Components
* ----------
* - Arduino Uno
* - nRF24L01+
* - 470 uF capacitor
* - Jumper wires
*
* Libraries
* ---------
* - SPI
* - RF24
*
* Connections
* -----------
* Arduino Uno and nRF24 (consult the schematic diagram as most
* nRF24 modules don't include any pin markings):
*
* Arduino Uno | nRF24
* ------------------------------
* - | IRQ
* 11 | MOSI
* 10 | CSN
* 5V | VCC
* GND | GND
* 9 | CE
* 13 | SCK
* 12 | MISO
*
*
* Connect the capacitor between the GND and 3.3V pins (beware of the polarity).
*
*
* Created on October 19 2017 by Peter Dalmaris, Tech Explorations, txplore.com
*
*/
#include <SPI.h>
#include "RF24.h"
#define BAUDRATE 9600
char message = 'A';
int led_pin = 8;
RF24 radio(9,10);
// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
void setup()
{
Serial.begin(BAUDRATE);
radio.begin();
radio.openWritingPipe(pipes[0]);
radio.openReadingPipe(1,pipes[1]);
radio.printDetails();
}
void loop()
{
radio.stopListening();
Serial.print("Sending:");
Serial.print(message);
Serial.print(" ");
radio.write( &message, 1 );
// Now, continue listening
radio.startListening();
// Wait here until we get a response, or timeout (250ms)
unsigned long started_waiting_at = millis();
bool timeout = false;
while ( ! radio.available() && ! timeout )
if (millis() - started_waiting_at > 200 )
timeout = true;
// Describe the results
if ( timeout )
{
Serial.println("Failed, response timed out.");
}
else
{
// Grab the response, compare, and send to debugging spew
byte response;
radio.read( &response, sizeof(response) );
Serial.print("Transmitter. Received response from receiver:");
Serial.println(response,BIN);
if (response == B0)
{
digitalWrite(led_pin,HIGH);
Serial.println("Ok");
}
else
{
digitalWrite(led_pin,LOW);
Serial.println("No connection");
}
}
// Try again later
delay(150);
}
| true |
b1c76844cbf7ddd7c9d6403199616c2df76af966 | C++ | mploof/PAL | /pal_controller/pal_controller.ino | UTF-8 | 2,356 | 2.921875 | 3 | [] | no_license | #include "Button.h"
#include <avr/wdt.h>
const int BUTTON_COUNT = 4;
int active_button = -1;
int last_active_button = -1;
int ledPin[BUTTON_COUNT] = {3, 5, 6, 9};
Button button[BUTTON_COUNT] = {
Button(3, 4, FRONT_LEFT),
Button(5, 2, BACK_LEFT),
Button(6, 8, BACK_RIGHT),
Button(9, 7, FRONT_RIGHT)
};
void startupSplash() {
for (int k = 0; k < 3; k++) {
for (int i = 0; i < BUTTON_COUNT; i++) {
for (int j = 0; j < 255; j += 5) {
analogWrite(ledPin[i], j);
delay(2);
}
for (int j = 255; j >= 0; j -= 5) {
analogWrite(ledPin[i], j);
delay(2 );
}
}
}
}
void setup() {
Serial.begin(300);
startupSplash();
}
void loop() {
if (isError()) {
// If the command failed, indicate error on button panel
Button::flashAll(10);
Button::cancelAll();
}
// Get new info about the button, update the brightness
for (int i = 0; i < BUTTON_COUNT; i++) {
button[i].updateButton();
}
// Small delay for the fade increment
Button::fadeWait(10);
// See if the active button has changed
active_button = Button::getActiveButton();
if (active_button != last_active_button) {
// If it has, send a new command to the indicator box
bool success;
if (active_button != -1) {
success = sendCommand(button[active_button].getIndicator());
}
else {
success = sendCommand(OFF);
}
}
last_active_button = active_button;
}
bool isError() {
if (Serial.available()) {
delay(50);
char input = 0;
// Keep reading till we get to a good character
while (Serial.available() && input != 'F') {
input = Serial.read();
}
// Dump the rest of the buffer
while (Serial.available()) {
Serial.read();
}
if (input == 'X') {
return true;
}
}
return false;
}
bool sendCommand(Indicator indicator) {
// Send the command
char output;
switch (indicator) {
case OFF:
output = 'F';
break;
case FRONT_LEFT:
output = 'A';
break;
case FRONT_RIGHT:
output = 'B';
break;
case BACK_LEFT:
output = 'C';
break;
case BACK_RIGHT:
output = 'D';
break;
}
for (int i = 0; i < 6; i++) {
Serial.print(indicator, HEX);
}
}
void reboot() {
wdt_disable();
wdt_enable(WDTO_15MS);
while (1) {}
}
| true |
c1356253243f0cb5c60127a5fd5042ab8c3f505a | C++ | lukasheinrich/code-snippets | /templated_matchingtool/DefaultMetrics.h | UTF-8 | 749 | 2.65625 | 3 | [] | no_license | #ifndef DEFAULTMETRICS_H
#define DEFAULTMETRICS_H
#include "trigTypes.h"
#include "recoTypes.h"
struct MatchMetrics{
double distance(const typeA& reco, const trigA& trig) const {
std::cout << "default A-type metric reco: " << reco.etaA() << " trig: " << trig.eta() << std::endl;
return reco.etaA()-trig.eta();
}
double distance(const typeB& reco, const trigB& trig) const {
std::cout << "default B-type metric reco: " << reco.etaB() << " trig: " << trig.eta() << std::endl;
return reco.etaB()-trig.eta();
}
double distance(const typeC& reco, const trigC& trig) const {
std::cout << "default C-type metric reco: " << reco.etaC() << " trig: " << trig.eta() << std::endl;
return reco.etaC()-trig.eta();
}
};
#endif | true |
0a568eec1fb264e5e772ff281a319b53ed6f7e25 | C++ | OverldAndrey/iu7-4sem-oop | /lab01/test/data.cpp | UTF-8 | 5,490 | 2.75 | 3 | [] | no_license | #include <cmath>
#include <iostream>
#include "figure.h"
#include "data.h"
#include "transform.h"
#include "drawing.h"
#include "file_wrap.h"
#include "error.h"
void clear_points(Figure &fig)
{
for (int i = array_size(fig.points) - 1; i >= 0; i--)
{
delete fig.points[i];
}
array_clear(fig.points);
}
void clear_edges(Figure &fig)
{
for (int i = array_size(fig.edges) - 1; i >= 0; i--)
{
delete fig.edges[i];
}
array_clear(fig.edges);
}
void trmatr_init(float m[4][4])
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
m[i][j] = (i == j) ? 1 : 0;
}
}
}
void projmatr_init(float m[4][4])
{
const float l = 0.75;
const float angle = 45;
trmatr_init(m);
m[2][2] = 0;
m[2][0] = -l*cos(angle);
m[2][1] = -l*sin(angle);
}
Error_codes fill_point(Point *p, file_t &fin)
{
float v1 = 0, v2 = 0, v3 = 0;
Error_codes err = success;
if (read_f(fin, &v1) != success || read_f(fin, &v2) != success || read_f(fin, &v3) != success)
err = file_read_error;
else
{
p->x = v1;
p->y = v2;
p->z = v3;
p->fx = p->x;
p->fy = p->y;
p->fz = p->z;
}
return err;
}
int find_point(vpoints_t &points, Point &p)
{
int ret = -1;
for (unsigned i = 0; i < array_size(points) && ret == -1; i++)
{
if (points[i]->x == p.x && points[i]->y == p.y && points[i]->z == p.z)
{
ret = i;
}
}
return ret;
}
Point *add_point(vpoints_t &points, Point *p)
{
int i = find_point(points, *p);
Point *ret = nullptr;
if (i != -1)
{
delete p;
ret = points[i];
}
else
{
array_push_back(points, p);
ret = p;
}
return ret;
}
Error_codes fill_edge(Point *p1, Point *p2, Figure &fig)
{
Edge *e = new(nothrow) Edge;
Error_codes err = success;
if (e == nullptr)
err = alloc_error;
else
{
e->p1 = add_point(fig.points, p1);
e->p2 = add_point(fig.points, p2);
array_push_back(fig.edges, e);
}
return err;
}
void init_figure(Figure &fig)
{
clear_points(fig);
clear_edges(fig);
trmatr_init(fig.trmatr);
trmatr_init(fig.cammatr);
projmatr_init(fig.projmatr);
}
Error_codes set_point_error(Error_codes err, Point *p1, Point *p2)
{
delete p1;
delete p2;
return err;
}
Error_codes check_points_alloc(Point *p1, Point *p2)
{
Error_codes err = success;
if (p1 == nullptr || p2 == nullptr)
{
err = set_point_error(alloc_error, p1, p2);
}
return err;
}
Error_codes fill_point_pair(file_t &fin, Figure &fig, Point *p1, Point *p2)
{
Error_codes err = success;
if (fill_point(p1, fin) != success || fill_point(p2, fin) != success)
{
err = set_point_error(file_read_error, p1, p2);
}
else
{
err = fill_edge(p1, p2, fig);
}
return err;
}
Error_codes read_point_pair(file_t &fin, Figure &fig)
{
Point *p1 = new(nothrow) Point;
Point *p2 = new(nothrow) Point;
Error_codes err = success;
err = check_points_alloc(p1, p2);
if (err == success)
{
err = fill_point_pair(fin, fig, p1, p2);
}
return err;
}
Error_codes fill_figure(file_t &fin, Figure &fig)
{
Error_codes err = success;
while (!is_eof(fin) && err == success)
{
err = read_point_pair(fin, fig);
}
return err;
}
Error_codes clear_data(Figure &figure)
{
clear_points(figure);
clear_edges(figure);
return success;
}
void copy_figure(Figure &figure, Figure &fig)
{
init_figure(figure);
array_copy(figure.points, fig.points);
array_copy(figure.edges, fig.edges);
}
Error_codes load_file(Figure &figure, const char * const fname)
{
file_t fin;
Error_codes error = success;
Figure fig;
open_file(fin, fname);
if (!file_is_open(fin))
{
error = file_load_error;
}
else
{
init_figure(fig);
error = fill_figure(fin, fig);
close_file(fin);
}
if (error == file_read_error)
clear_data(fig);
if (error == success)
copy_figure(figure, fig);
return error;
}
void write_edges(file_t &fout, vedges_t &edges)
{
for (unsigned i = 0; i < array_size(edges); i++)
{
Point *p1 = edges[i]->p1;
Point *p2 = edges[i]->p2;
write_f(fout, p1->x);
write_f(fout, " ");
write_f(fout, p1->y);
write_f(fout, " ");
write_f(fout, p1->z);
write_f(fout, " ");
write_f(fout, p2->x);
write_f(fout, " ");
write_f(fout, p2->y);
write_f(fout, " ");
write_f(fout, p2->z);
if (i < array_size(edges) - 1) {write_f(fout, "\n");}
}
}
Error_codes save_file(Figure &fig, const char * const fname)
{
file_t fout;
Error_codes error = success;
open_file(fout, fname);
if (!file_is_open(fout))
{
error = file_load_error;
}
else
{
transform_points(fig.points, fig.trmatr);
write_edges(fout, fig.edges);
close_file(fout);
}
return error;
}
| true |
218d0bdfa09b6a55f9eddbfbb88f0fddabfd8bf0 | C++ | zhenzeZ/HCI-Typography | /Typography/Credit.cpp | UTF-8 | 2,216 | 3.453125 | 3 | [] | no_license | #include "Credit.h"
#include <iostream>
Credit::Credit(Game& game, sf::Font font) :
m_game(&game),
m_font(font)
{
for (int i = 0; i < 10; i++) {
m_textMessage[i].setFont(m_font);
m_textMessage[i].setFillColor(sf::Color(1,1,1,0)); // set color to text
displayText[i] = false;
textColor[i] = 0;
}
file.open("./ASSETS/CREDIT/Credit.txt"); //oprn txt file
}
Credit::~Credit()
{
std::cout << "destructing Credits" << std::endl;
}
/// <summary>
/// display text on screen and swtich to new text
/// </summary>
/// <param name="t"></param>
void Credit::update(double t)
{
timer += t;
if (index < 10 && timer >= 0.5f) // read file every 0.5 sec
{
getText();
timer = 0; // reset the timer
}
if (file.eof() && timer >= 0.4f) // if system read the end of file, turn to close phase
{
m_game->setGameState(States::Close);
}
else if (!file.eof() && index >= 10) // if index is more than 10, reset the text states
{
index = 0;
for (int i = 0; i < 10; i++)
{
textColor[i] = 0;
displayText[i] = false;
}
}
for (int i = 0; i < 10; i++)
{
if (displayText[i] && textColor[i] < 255)
{
textColor[i]++;
m_textMessage[i].setFillColor(sf::Color(1, 0, 0, textColor[i])); // let text appear
}
}
m_textMessage[index].setPosition(50, 50 + index * 40); // set position to text
}
/// <summary>
/// read the text from file and sign to string
/// </summary>
void Credit::getText()
{
if (file.is_open())
{
if (index < 10)
{
/*spaceCheck = file.get();
while (spaceCheck != ' ')
{
word = word + spaceCheck;
spaceCheck = file.get();
}*/
std::getline(file, word);
//Getting every line of the .txt file and putting it in the 'line' string
m_textMessage[index].setString(word);
textList.push_back(m_textMessage[index]);
displayText[index] = true;
index++;
//word = " ";
}
}
else
{
std::string s("Error loading text ");
throw std::exception(s.c_str());
}
}
/// <summary>
/// draw the text on window
/// </summary>
/// <param name="window"></param>
void Credit::render(sf::RenderWindow & window)
{
window.clear(sf::Color::White);
for (int i = 0; i < 10; i++)
{
window.draw(m_textMessage[i]);
}
window.display();
} | true |
9fb26fe7e447c3e03b5c2eb5d5de12f50584f6e5 | C++ | dobson156/irc_client | /ui/tests/anchors.cpp | UTF-8 | 2,370 | 2.875 | 3 | [
"BSL-1.0"
] | permissive | #include <console.hpp>
#include <iostream>
#include <sstream>
int main() {
try {
using anchor_top =cons::anchor_view<cons::anchors::top>;
using anchor_bottom=cons::anchor_view<cons::anchors::bottom>;
using anchor_left =cons::anchor_view<cons::anchors::left>;
using anchor_right =cons::anchor_view<cons::anchors::right>;
using text_box =cons::stenciled_frame<cons::string_stencil>;
using str_list =cons::stenciled_list<cons::string_stencil>;
anchor_top p { cons::make_window(), 20 };
anchor_left& top=p.emplace_anchor<anchor_left>(20);
anchor_right& btm=p.emplace_fill<anchor_right>(20);
//TOP - left
cons::bordered& tlb=top.emplace_anchor<cons::bordered>(
cons::borders::right, cons::borders::left,
cons::borders::top, cons::borders::bottom);
text_box& tlf=tlb.emplace_element<text_box>("top left");
tlf.set_background(COLOR_YELLOW);
//TOP - right
cons::bordered& trb=top.emplace_fill<cons::bordered>(
cons::borders::right, cons::borders::left, cons::borders::top, cons::borders::bottom);
text_box& trf=trb.emplace_element<text_box>("top right");
trf.set_background(COLOR_BLUE);
//BTM - right
cons::bordered& brb=btm.emplace_anchor<cons::bordered>(
cons::borders::right, cons::borders::left, cons::borders::top, cons::borders::bottom);
text_box& brf=brb.emplace_element<text_box>("btm right");
brf.set_background(COLOR_RED);
//BTM - left
cons::bordered& blb=btm.emplace_fill<cons::bordered>(
cons::borders::right, cons::borders::left, cons::borders::top, cons::borders::bottom);
str_list& blf=blb.emplace_element<str_list>();
//blf.set_background(COLOR_GREEN);
blf.insert(blf.begin(), "hello");
blf.insert(blf.begin(), "world");
p.refresh();
int i;
while((i=getch())!='q') {
switch(i) {
case 'h': {
int n=p.get_partition();
p.set_partition(n+1);
p.refresh();
break;
}
case 'l': {
int n=p.get_partition();
p.set_partition(n-1);
p.refresh();
break;
}
case 'j': {
int n=top.get_partition();
top.set_partition(n+1);
top.refresh();
break;
}
case 'k': {
int n=top.get_partition();
top.set_partition(n-1);
top.refresh();
break;
}
default:
break;
}
}
} catch(const std::exception& e) {
std::cerr << "EXCEPTION: " << e.what() << std::endl;
}
}
| true |
e5322d57c700e65c3aea95f44cc5c4bb816b7670 | C++ | dntutty/FFmpeg | /app/src/main/cpp/safe_queue.h | UTF-8 | 3,277 | 3.09375 | 3 | [] | no_license | //
// Created by Eric on 2019/8/18.
//
#ifndef FFMPEG_SAFE_QUEUE_H
#define FFMPEG_SAFE_QUEUE_H
#include <pthread.h>
#include <queue>
#include "marco.h"
using namespace std;
template<typename T>
class SafeQueue {
typedef void (*release_func)(T *);
typedef void (*sync_func)(queue<T> &);
public:
SafeQueue() {
pthread_mutex_init(&mutex, NULL);//动态初始化的方式
pthread_cond_init(&cond, NULL);
}
~SafeQueue() {
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
/**
* 入队操作
* @param t
*/
void push(T t) {
//插入操作,队列加锁
pthread_mutex_lock(&mutex);
if (work) {
//工作状态需要push
q.push(t);
pthread_cond_signal(&cond);
} else {
//非工作状态
if (func) {
func(&t);
}
}
//队列解锁
pthread_mutex_unlock(&mutex);
}
/**
* 出队
* @param t
*/
int pop(T &t) {
int ret = 0;
pthread_mutex_lock(&mutex);
while (work && q.empty()) {
//工作状态,说明确实需要数据(pop),但是队列为空,需要等待
pthread_cond_wait(&cond, &mutex);
}
if (!q.empty()) {
t = q.front();
q.pop();
ret = 1;
}
pthread_mutex_unlock(&mutex);
return ret;
}
/**
* 设置队列的工作状态
* @param work
*/
void setWork(int work) {
pthread_mutex_lock(&mutex);
this->work = work;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
/**
* 判断队列是否为空
* @return
*/
int is_empty() {
return q.empty();
}
/**
* 获取队列大小
* @return
*/
int size() {
return q.size();
}
/**
* 清空队列
* 队列中的元素如何释放?
* AVPacket
*/
void clear() {
pthread_mutex_lock(&mutex);
//todo
// if (release) {
// while (!q.empty()) {
// T t = q.front();
// release(&t);
// q.pop();
// }
// }
//for循环清空队列
if (func) {
unsigned int size = q.size();
for (int i = 0; i < size; i++) {
T t = q.front();
func(&t);
q.pop();
}
}
pthread_mutex_unlock(&mutex);
}
void setReleaseFunc(release_func func) {
this->func = func;
}
void setSyncFunc(sync_func sync_handle) {
this->sync_handle = sync_handle;
}
/**
* 同步操作
*/
void sync() {
pthread_mutex_lock(&mutex);
sync_handle(q);
pthread_mutex_unlock(&mutex);
}
private:
queue<T> q;
pthread_mutex_t mutex;
pthread_cond_t cond;
int work = 0;//标记队列是否工作
release_func func;
sync_func sync_handle;
};
#endif //FFMPEG_SAFE_QUEUE_H
| true |
914679ef6c8144f01fce5369e37eb087477ce23a | C++ | Old-Fritz/M3DMath | /libM3DMath/Source/MatrixMath/Matrix/x86_64/MatrixFFunctions.cpp | UTF-8 | 11,033 | 2.828125 | 3 | [] | no_license | #include "M3DMath.h"
#include <cmath>
/// Implementation of MatrixF Functions
using namespace M3DM;
// Transforms
MatrixF M3DM::matrixFScaling(Float x, Float y, Float z)
{
return matrixFScaling(VectorF(x,y,z,0));
}
MatrixF M3DM::matrixFScaling(VectorF scale)
{
MatrixF matrixResult;
__m128 data = scale.getData();
matrixResult = matrixFIdentity();
matrixResult.m_rows[0] = vecFShuffle(data, matrixResult.m_rows[0], 0, 1, 2, 3);
matrixResult.m_rows[0] = vecFSwizzle(matrixResult.m_rows[0], 0, 3, 3, 3);
matrixResult.m_rows[1] = vecFShuffle(data, matrixResult.m_rows[1], 0, 1, 2, 3);
matrixResult.m_rows[1] = vecFSwizzle(matrixResult.m_rows[1], 3, 1, 3, 3);
matrixResult.m_rows[2] = vecFShuffle(matrixResult.m_rows[2], data, 0, 1, 2, 3);
matrixResult.m_rows[2] = vecFSwizzle(matrixResult.m_rows[2], 0, 0, 2, 0);
return matrixResult;
}
MatrixF M3DM::matrixFRotationX(Float angle)
{
return matrixFRotationX(VectorF(angle));
}
MatrixF M3DM::matrixFRotationX(VectorF angle)
{
MatrixF matrixResult;
VectorF cos, sin;
(-angle).sincos(sin, cos);
matrixResult = matrixFIdentity();
__m128 mask = VectorF(0, FNAN, FNAN, 0).getData();
matrixResult.m_rows[1] = vecFShuffle(cos.getData(), (-sin).getData(), 0, 1, 2, 3);
matrixResult.m_rows[2] = vecFShuffle(sin.getData(), cos.getData(), 0, 1, 2, 3);
matrixResult.m_rows[1] = _mm_and_ps(matrixResult.m_rows[1], mask);
matrixResult.m_rows[2] = _mm_and_ps(matrixResult.m_rows[2], mask);
return matrixResult;
}
MatrixF M3DM::matrixFRotationY(Float angle)
{
return matrixFRotationY(VectorF(angle));
}
MatrixF M3DM::matrixFRotationY(VectorF angle)
{
MatrixF matrixResult;
VectorF cos, sin;
(-angle).sincos(sin, cos);
matrixResult = matrixFIdentity();
__m128 mask = VectorF(FNAN, 0, FNAN, 0).getData();
matrixResult.m_rows[0] = vecFShuffle(cos.getData(), sin.getData(), 0, 1, 2, 3);
matrixResult.m_rows[2] = vecFShuffle((-sin).getData(), cos.getData(), 0, 1, 2, 3);
matrixResult.m_rows[0] = _mm_and_ps(matrixResult.m_rows[0], mask);
matrixResult.m_rows[2] = _mm_and_ps(matrixResult.m_rows[2], mask);
return matrixResult;
}
MatrixF M3DM::matrixFRotationZ(Float angle)
{
return matrixFRotationZ(VectorF(angle));
}
MatrixF M3DM::matrixFRotationZ(VectorF angle)
{
MatrixF matrixResult;
VectorF cos, sin;
(-angle).sincos(sin, cos);
matrixResult = matrixFIdentity();
__m128 mask = VectorF(FNAN, FNAN, 0, 0).getData();
matrixResult.m_rows[0] = vecFShuffle(cos.getData(), (-sin).getData(), 0, 1, 2, 3);
matrixResult.m_rows[1] = vecFShuffle(sin.getData(), cos.getData(), 0, 1, 2, 3);
matrixResult.m_rows[0] = vecFSwizzle(matrixResult.m_rows[0], 0, 2, 0, 0);
matrixResult.m_rows[1] = vecFSwizzle(matrixResult.m_rows[1], 0, 2, 0, 0);
matrixResult.m_rows[0] = _mm_and_ps(matrixResult.m_rows[0], mask);
matrixResult.m_rows[1] = _mm_and_ps(matrixResult.m_rows[1], mask);
return matrixResult;
}
MatrixF M3DM::matrixFRotationAxis(VectorF axis, Float angle)
{
return matrixFRotationAxis(axis, VectorF(angle));
}
MatrixF M3DM::matrixFRotationAxis(VectorF axis, VectorF angle)
{
return matrixFRotationNormal(axis.normalized3D(), angle);
}
MatrixF M3DM::matrixFRotationNormal(VectorF normal, Float angle)
{
return matrixFRotationNormal(normal, VectorF(angle));
}
MatrixF M3DM::matrixFRotationNormal(VectorF normal, VectorF angle)
{
MatrixF matrixResult;
VectorF cos, minuscos, sin, x, y, z;
(-angle).sincos(sin, cos);
x = vecFSwizzle(normal.getData(), 0, 0, 0, 0);
y = vecFSwizzle(normal.getData(), 1, 1, 1, 1);
z = vecFSwizzle(normal.getData(), 2, 2, 2, 2);
minuscos = VectorF(1) - cos;
matrixResult = matrixFIdentity();
__m128 mask = VectorF(FNAN, FNAN, FNAN, 0).getData();
VectorF m1 = cos + minuscos * x * x;
VectorF m2 = minuscos * x * y - sin * z;
VectorF m3 = minuscos * x * z + sin * y;
matrixResult.m_rows[0] = vecFShuffle(m1.getData(), m2.getData(), 0, 1, 2, 3);
matrixResult.m_rows[0] = vecFSwizzle(matrixResult.m_rows[0], 0, 2, 0, 0);
matrixResult.m_rows[0] = vecFShuffle(matrixResult.m_rows[0], m3.getData(), 0, 1, 2, 3);
matrixResult.m_rows[0] = _mm_and_ps(matrixResult.m_rows[0], mask);
m1 = minuscos * y * x + sin * z;
m2 = cos + minuscos * y * y;
m3 = minuscos * y * z - sin * x;
matrixResult.m_rows[1] = vecFShuffle(m1.getData(), m2.getData(), 0, 1, 2, 3);
matrixResult.m_rows[1] = vecFSwizzle(matrixResult.m_rows[1], 0, 2, 0, 0);
matrixResult.m_rows[1] = vecFShuffle(matrixResult.m_rows[1], m3.getData(), 0, 1, 2, 3);
matrixResult.m_rows[1] = _mm_and_ps(matrixResult.m_rows[1], mask);
m1 = minuscos * z * x - sin * y;
m2 = minuscos * z * y + sin * x;
m3 = cos + minuscos * z * z;
matrixResult.m_rows[2] = vecFShuffle(m1.getData(), m2.getData(), 0, 1, 2, 3);
matrixResult.m_rows[2] = vecFSwizzle(matrixResult.m_rows[2], 0, 2, 0, 0);
matrixResult.m_rows[2] = vecFShuffle(matrixResult.m_rows[2], m3.getData(), 0, 1, 2, 3);
matrixResult.m_rows[2] = _mm_and_ps(matrixResult.m_rows[2], mask);
return matrixResult;
}
MatrixF M3DM::matrixFRotationYawPitchRoll(Float yaw, Float pitch, Float roll)
{
return matrixFRotationYawPitchRoll(VectorF(yaw, pitch, roll, 0));
}
MatrixF M3DM::matrixFRotationYawPitchRoll(VectorF yawPitchRoll)
{
MatrixF matrixResult;
MatrixF yawMatrix, pitchMatrix, rollMatrix;
VectorF yaw, pitch, roll;
yaw = vecFSwizzle(yawPitchRoll.getData(), 0, 0, 0, 0);
pitch = vecFSwizzle(yawPitchRoll.getData(), 1, 1, 1, 1);
roll = vecFSwizzle(yawPitchRoll.getData(), 2, 2, 2, 2);
pitchMatrix = matrixFRotationX(pitch);
yawMatrix = matrixFRotationY(yaw);
rollMatrix = matrixFRotationZ(roll);
matrixResult = rollMatrix * pitchMatrix * yawMatrix;
return matrixResult;
}
MatrixF M3DM::matrixFTranslation(Float x, Float y, Float z)
{
return matrixFTranslation(VectorF(x,y,z, 0));
}
MatrixF M3DM::matrixFTranslation(VectorF vector)
{
MatrixF matrixResult;
matrixResult = matrixFIdentity();
matrixResult.m_rows[3] = _mm_add_ps(matrixResult.m_rows[3], _mm_and_ps(vector.getData(), VectorF(FNAN, FNAN, FNAN, 0).getData()));
return matrixResult;
}
VectorF M3DM::matrixFTransformCoord3D(VectorF vector, MatrixF matrix)
{
VectorF resultVec;
__m128 data, x, y, z, w, temp1, temp2;
data = vector.getData();
data = _mm_insert_ps(data, _mm_set1_ps(1), 3 << 4);
matrix = matrix.transpose();
x = _mm_dp_ps(data, matrix.m_rows[0], 0b11111111);
y = _mm_dp_ps(data, matrix.m_rows[1], 0b11111111);
z = _mm_dp_ps(data, matrix.m_rows[2], 0b11111111);
temp1 = vecFShuffle(x, y, 0, 1, 2, 3);
temp1 = vecFSwizzle(temp1, 0, 2, 2, 3);
temp2 = vecFShuffle(z, vector.getData(), 0, 1, 3, 3);
temp2 = vecFSwizzle(temp2, 0, 2, 2, 3);
resultVec = vecFShuffle_0101(temp1, temp2);
return resultVec;
}
VectorF M3DM::matrixFTransformNormal3D(VectorF vector, MatrixF matrix)
{
VectorF resultVec;
__m128 data, x, y, z, w, temp1, temp2;
data = vector.getData();
data = _mm_insert_ps(data, _mm_set1_ps(0), 3 << 4);
matrix = matrix.transpose();
x = _mm_dp_ps(data, matrix.m_rows[0], 0b11111111);
y = _mm_dp_ps(data, matrix.m_rows[1], 0b11111111);
z = _mm_dp_ps(data, matrix.m_rows[2], 0b11111111);
temp1 = vecFShuffle(x, y, 0, 1, 2, 3);
temp1 = vecFSwizzle(temp1, 0, 2, 2, 3);
temp2 = vecFShuffle(z, vector.getData(), 0, 1, 3, 3);
temp2 = vecFSwizzle(temp2, 0, 2, 2, 3);
resultVec = vecFShuffle_0101(temp1, temp2);
return resultVec;
}
VectorF M3DM::matrixFTransform(VectorF vector, MatrixF matrix)
{
VectorF resultVec;
__m128 x, y, z, w, temp1, temp2;
matrix = matrix.transpose();
x = _mm_dp_ps(vector.getData(), matrix.m_rows[0], 0b11111111);
y = _mm_dp_ps(vector.getData(), matrix.m_rows[1], 0b11111111);
z = _mm_dp_ps(vector.getData(), matrix.m_rows[2], 0b11111111);
w = _mm_dp_ps(vector.getData(), matrix.m_rows[3], 0b11111111);
temp1 = vecFShuffle(x, y, 0, 1, 2, 3);
temp1 = vecFSwizzle(temp1, 0, 2, 2, 3);
temp2 = vecFShuffle(z, w, 0, 1, 2, 3);
temp2 = vecFSwizzle(temp2, 0, 2, 2, 3);
resultVec = vecFShuffle_0101(temp1, temp2);
return resultVec;
}
// special matricies LH
MatrixF M3DM::matrixFOrthoLH(Float width, Float height, Float minZ, Float maxZ)
{
return matrixFOrthoLH(VectorF(width), VectorF(height), VectorF(minZ), VectorF(maxZ));
}
MatrixF M3DM::matrixFPerspectiveLH(Float width, Float height, Float minZ, Float maxZ)
{
return matrixFPerspectiveLH(VectorF(width), VectorF(height), VectorF(minZ), VectorF(maxZ));
}
MatrixF M3DM::matrixFPerspectiveFovLH(Float fov, Float aspect, Float minZ, Float maxZ)
{
return matrixFPerspectiveFovLH(VectorF(fov), VectorF(aspect), VectorF(minZ), VectorF(maxZ));
}
MatrixF M3DM::matrixFOrthoLH(VectorF width, VectorF height, VectorF minZ, VectorF maxZ)
{
MatrixF matrixResult;
matrixResult = matrixFIdentity();
matrixResult.m_rows[0] = _mm_insert_ps(matrixResult.m_rows[0], (VectorF(2) / width).getData(), 0 << 4);
matrixResult.m_rows[1] = _mm_insert_ps(matrixResult.m_rows[1], (VectorF(2) / height).getData(), 1 << 4);
VectorF deltaZ = maxZ - minZ;
matrixResult.m_rows[2] = _mm_insert_ps(matrixResult.m_rows[2], deltaZ.reciprocal().getData(), 2 << 4);
matrixResult.m_rows[3] = _mm_insert_ps(matrixResult.m_rows[3], (-minZ / deltaZ).getData(), 2 << 4);
return matrixResult;
}
MatrixF M3DM::matrixFPerspectiveLH(VectorF width, VectorF height, VectorF minZ, VectorF maxZ)
{
MatrixF matrixResult;
VectorF two = VectorF(2);
VectorF temp;
temp = two * minZ;
// 2 * minZ / width
matrixResult.m_rows[0] = _mm_insert_ps(matrixResult.m_rows[0], (temp / width).getData(), 0 << 4);
// 2 * minZ / height
matrixResult.m_rows[1] = _mm_insert_ps(matrixResult.m_rows[1], (temp / height).getData(), 1 << 4);
// maxZ / (maxZ - minZ)
temp = maxZ / (maxZ - minZ);
matrixResult.m_rows[2] = _mm_insert_ps(matrixResult.m_rows[2], temp.getData(), 2 << 4);
// minZ * maxZ / (minZ - maxZ);
matrixResult.m_rows[3] = _mm_insert_ps(matrixResult.m_rows[3], (-minZ*temp).getData(), 2 << 4);
matrixResult.m_rows[2] = _mm_insert_ps(matrixResult.m_rows[2], VectorF(1).getData(), 3 << 4);
return matrixResult;
}
MatrixF M3DM::matrixFPerspectiveFovLH(VectorF fov, VectorF aspect, VectorF minZ, VectorF maxZ)
{
VectorF width, height, two;
two = VectorF(2);
height = two * minZ * (fov / two).tan();
width = height * aspect;
return matrixFPerspectiveLH(width, height, minZ, maxZ);
}
MatrixF M3DM::matrixFLookAtLH(VectorF eye, VectorF at, VectorF up)
{
VectorF xAxis, yAxis, zAxis;
MatrixF matrixResult;
matrixResult = matrixFIdentity();
zAxis = (at - eye).normalized3D();
xAxis = vecFCross3D(up, zAxis).normalized3D();
yAxis = vecFCross3D(zAxis, xAxis);
matrixResult.m_rows[0] = xAxis.getData();
matrixResult.m_rows[1] = yAxis.getData();
matrixResult.m_rows[2] = zAxis.getData();
matrixResult.m_rows[0] = _mm_insert_ps(matrixResult.m_rows[0], (-vecFDotVec3D(xAxis, eye)).getData(), 3 << 4);
matrixResult.m_rows[1] = _mm_insert_ps(matrixResult.m_rows[1], (-vecFDotVec3D(yAxis, eye)).getData(), 3 << 4);
matrixResult.m_rows[2] = _mm_insert_ps(matrixResult.m_rows[2], (-vecFDotVec3D(zAxis, eye)).getData(), 3 << 4);
matrixResult = matrixResult.transpose();
return matrixResult;
} | true |
b700e5b0f35cfe20670a615deda633130994e9b5 | C++ | peanut-buttermilk/fun-run | /cpp/canJump.cpp | UTF-8 | 1,323 | 3.203125 | 3 | [] | no_license | //
// canJump.cpp
// CPP Test9
//
// Created by Balaji Cherukuri on 1/4/16.
// Copyright © 2016 FooBar. All rights reserved.
//
#include "canJump.hpp"
#include <vector>
#include <iostream>
static
bool canJump(std::vector<int>& nums) {
if (nums.size() == 1) {
return true;
}
size_t maxReach = 0;
for (size_t s = 0; s < nums.size() && maxReach >= s; ++s) {
if (maxReach == 0) {
maxReach = nums[s] + s;
} else {
maxReach = std::max(nums[s] + s, maxReach);
}
if (maxReach == 0) {
return false;
} else if (maxReach >= nums.size() - 1) {
return true;
}
}
return false;
}
void jump::unitTest() {
{
const int arr[] = {2,3,1,1,4};
std::vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]));
std::cout << std::boolalpha << "canJump: " << canJump(vec) << "\n";
}
{
const int arr[] = {3,2,1,0,4};
std::vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]));
std::cout << std::boolalpha << "canJump: " << canJump(vec) << "\n";
}
{
const int arr[] = {1,1,2,2,0,1,1};
std::vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]));
std::cout << std::boolalpha << "canJump: " << canJump(vec) << "\n";
}
} | true |
c4915e109582d40a7e10ef16c3decd46831492f1 | C++ | SayYoungMan/BaekJoon_OJ_Solutions | /Codes/10814_Sort_by_Age.cpp | UTF-8 | 551 | 3.421875 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
int n, age;
std::string name;
std::vector<std::pair<int, std::string>> people;
std::cin >> n;
for (int i=0; i < n; i++) {
std::cin >> age >> name;
people.push_back(std::make_pair(age, name));
}
std::stable_sort(people.begin(), people.end(), [](auto &left, auto &right) {
return left.first < right.first;
});
for (auto &p: people) std::cout << p.first << ' ' << p.second << '\n';
return 0;
} | true |
93031dd68c27b4271291f7e5e131b81dfd9dd9b6 | C++ | sith/MarkOS_Arduino_communication | /src/TR433.h | UTF-8 | 1,290 | 2.546875 | 3 | [] | no_license | //
// Created by Oleksandra Baukh on 3/21/18.
//
#ifndef MARKOS_ARDUINO_CONTROLLER_TRANSCEIVER430_H
#define MARKOS_ARDUINO_CONTROLLER_TRANSCEIVER430_H
#include <Transceiver.h>
#include <RH_ASK.h>
#include <Receiver.h>
#include <HardwareSerial.h>
#include <Arduino.h>
#include <types.h>
template<typename Content>
class TR433
: public mark_os::communication::Transceiver<Content>, public mark_os::communication::Receiver<Content> {
RH_ASK driver;
public:
TR433();
mark_os::commons::Optional<Message<Content>> receive() override;
void send(Message<Content> &message) override;
};
template<typename Content>
void TR433<Content>::send(Message<Content> &message) {
driver.send((uint8_t *) &message, sizeof(message));
driver.waitPacketSent();
}
template<typename Content>
TR433<Content>::TR433() {
if (!driver.init()) {
Serial.println("init failed");
}
}
template<typename Content>
mark_os::commons::Optional<Message<Content>> TR433<Content>::receive() {
Message<Content> message;
uint8_t buflen = sizeof(message);
if (driver.recv((uint8_t *) &message, &buflen)) {
return mark_os::commons::optional(message);
}
return mark_os::commons::none<Message<Content >>();
}
#endif //MARKOS_ARDUINO_CONTROLLER_TRANSCEIVER430_H
| true |
c42e8a841e80c7f12d2448856e26569462691d37 | C++ | kimtaeju01/algorithm | /tree/FORTRESS.cpp | UTF-8 | 1,707 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct TreeNode{
int x,y,r;
vector<TreeNode*> children;
};
bool inside(TreeNode* a,TreeNode* b){
if((b->x-a->x)*(b->x-a->x)+(b->y-a->y)*(b->y-a->y)<a->r*a->r) return true;
else return false;
}
void maketree(TreeNode* par,TreeNode* cur){
if(par->children.size()==0){
par->children.push_back(cur);
return ;
}
int i=0;
for(i=0;i<par->children.size();i++){
if(inside(par->children[i],cur)){
maketree(par->children[i],cur);
break;
}
}
if(i==par->children.size()){
par->children.push_back(cur);
return ;
}
}
int longest=0;
int height(TreeNode* root){
vector<int> heights;
for(int i=0;i<root->children.size();i++)
heights.push_back(height(root->children[i]));
if(heights.empty()) return 0;
sort(heights.begin(),heights.end());
if(heights.size()>1)
longest = max(longest,heights[heights.size()-1]+heights[heights.size()-2]+2);
return heights[heights.size()-1]+1;
}
int solve(TreeNode* root){
int h = height(root);
return max(h,longest);
}
int main(){
TreeNode treelist[8];
int lis[][3]={{21,15,20},
{15,15,10},
{32,10,7},
{13,12,5},
{30,24,5},
{32,9,4},
{12,12,3},
{19,19,2}};
for(int i=0;i<8;i++){
treelist[i].x = lis[i][0];
treelist[i].y = lis[i][1];
treelist[i].r = lis[i][2];
}
for(int i=1;i<8;i++) maketree(&treelist[0],&treelist[i]);
height(&treelist[0]);
cout<<longest;
return 0;
}
| true |
d6b0a38d68bd8d31dcdf451cc0dcd627870018ee | C++ | fqararyah/tensorflow | /testfiles/simulatePlacement.h | UTF-8 | 1,856 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <map>
using namespace std;
class GEdge;
class GNode;
class TimePartition {
int start;
int end;
int device;
public:
void setStart(int s) { start = s;}
void setEnd(int e) {end = e;}
void setDevice(int d) { device = d;}
int getStart() { return start;}
int getEnd() { return end;}
int getDevice() { return device;}
bool containsTP(TimePartition tp);
void printTP();
//Constructor
TimePartition();
TimePartition(int s, int e, int d)
: start(s),
end(e),
device(d){}
};
class GNode{
int id;
string name;
int weight;
vector<GEdge> childrenEdges;
bool visited;
int device;
int inDeg;
int outDeg;
public:
int getWeight();
int getID();
int getDevice();
string getName();
vector<GEdge> getChildrenEdges();
void setVisited(bool v);
bool getVisited();
void setWeight(int w);
void setDevice(int d);
int getInDeg();
int getOutDeg();
void setInDeg(int v);
void setOutDeg(int v);
void setName(string n);
GEdge edgeTo(string targetName);
void addEdge(GEdge e);
//Constructor
GNode(string n, int w, int i);
GNode();
};
class GEdge{
int id;
GNode src;
GNode dst;
int weight;
public:
int getWeight();
int getID();
GNode getSrc();
GNode getDst();
void setWeight(int w);
void setSrc(GNode n);
void setDst(GNode n);
//Constructor 1
GEdge(int w, GNode s, GNode d, int i);
GEdge();
};
class DGraph {
vector<GEdge> edges;
map<string,GNode> nodes;
public:
vector<GEdge> getEdges() { return edges;}
vector<GNode> getNodes();
GNode getNode(string l);
GNode addNode(string l, int weigth);
GEdge addEdge(int weigth, string from, string to);
void addSourceAndSink();
}; | true |
ff4757b118e846cc8b95fd147d1c28bda674bf44 | C++ | shivamvats/sandbox | /cpp/main/template_recursion.cpp | UTF-8 | 732 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include "template_recursion.h"
int main(){
std::cout<<"Testing Template Recursion\n";
std::cout<<"===========================\n";
std::cout<<"This code demonstrates how you can use templated"
" functions that take in multiple templates to write\n"
"recursive code. Is this faster? Found in Andrei's talk at\n"
"https://www.youtube.com/watch?v=ea5DiCg8HOY, time: 18:17.\n";
std::cout<<"\n";
std::cout<<"\nTesting Parameter Packs to define add function with variable number of arguments\n";
std::cout<<"add(1, 2): "<<add(1, 2)<< "\n";
std::cout<<"add(1, 2, 3): "<<add(1, 2, 3)<< "\n";
std::cout<<"The same function was called with different number of arguments\n";
}
| true |
43dbb0264197d3b42e49c68b5a7afcc4a10f3682 | C++ | SindhubalaGanesan/NandhaTraining | /sumfl.cpp | UTF-8 | 430 | 3.125 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
class Example
{
private:
int a,c=0,b=0,x[20],sum;
public:
void display()
{
cout<<"enter the number:";
cin>>a;
while(a!=0)
{
x[c]=a%10;
c++;
b++;
a=a/10;
}
sum=x[0]+x[c-1];
cout<<sum;
}
};
int main()
{
Example e;
e.display();
return 0;
}
| true |
469a95cdacb93efcc4f103894cbfaa49a1336467 | C++ | HyperdiXx/XEngine | /xengine/math/src/rect.h | UTF-8 | 1,163 | 3.21875 | 3 | [
"MIT"
] | permissive | #pragma once
#ifndef RECT_H
#define RECT_H
namespace Math
{
struct Rect
{
//left top point, width, height
real32 x, y, width, height;
Rect() : x(0), y(0), width(0), height(0) {}
Rect(real32 xVal, real32 yVal, real32 wVal, real32 hVal) : x(xVal), y(yVal), width(wVal), height(hVal) {}
Rect(const vec2f& pos, const vec2f& size) : x(pos.x), y(pos.y), width(size.x), height(size.y) {}
Rect(const Rect& rr) : x(rr.x), y(rr.y), width(rr.width), height(rr.height) {}
inline bool operator==(const Rect& rr)
{
return x == rr.x && y == rr.y && width == rr.width && height == rr.height;
}
inline void set(real32 xVal, real32 yVal, real32 wVal, real32 hVal)
{
x = xVal;
y = yVal;
width = wVal;
height = hVal;
}
inline void setPosition(real32 xVal, real32 yVal)
{
x = xVal;
y = yVal;
}
inline void setSize(real32 wVal, real32 hVal)
{
width = wVal;
height = hVal;
}
};
}
#endif // !RECT_H
| true |
60711bf49c6b9193d96488d1a9f998af8ae1fcbc | C++ | Mike-Leo-Smith/NoWayOut | /core/graphics/shader.h | UTF-8 | 1,506 | 2.65625 | 3 | [] | no_license | //
// Created by Mike Smith on 2019/10/8.
// Copyright (c) 2019 Mike Smith. All rights reserved.
//
#pragma once
#include <glad/glad.h>
#include <glm/ext.hpp>
#include <glm/glm.hpp>
#include <memory>
#include <util/util.h>
class Shader : util::Noncopyable {
public:
struct UniformProxy {
int32_t location;
UniformProxy &operator=(bool value) noexcept {
glUniform1i(location, value);
return *this;
}
UniformProxy &operator=(int32_t value) noexcept {
glUniform1i(location, value);
return *this;
}
UniformProxy &operator=(uint32_t value) noexcept {
glUniform1i(location, value);
return *this;
}
UniformProxy &operator=(float value) noexcept {
glUniform1f(location, value);
return *this;
}
UniformProxy &operator=(glm::vec3 v) noexcept {
glUniform3f(location, v.x, v.y, v.z);
return *this;
}
UniformProxy &operator=(glm::mat4 m) noexcept {
glUniformMatrix4fv(location, 1, 0, glm::value_ptr(m));
return *this;
}
};
private:
uint32_t _id;
explicit Shader(uint32_t id) noexcept : _id{id} {};
public:
~Shader() noexcept { glDeleteProgram(_id); }
[[nodiscard]] static std::unique_ptr<Shader>
create(const std::string &vs_source, const std::string &fs_source);
[[nodiscard]] UniformProxy operator[](const std::string &name) const noexcept;
template <typename Func> void with(Func &&func) noexcept {
glUseProgram(_id);
func(*this);
glUseProgram(0);
}
};
| true |
853a9b86c47fcb26c6e1bd55fdab4ad1d3b067e1 | C++ | runnycoder/LeetCodePrictice-withC- | /ManacherPalindromeStr.cpp | UTF-8 | 5,648 | 3.640625 | 4 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include<math.h>
using namespace std;
//字符串预处理 用#填充字符串空隙 以#开头和结尾 #字符的数目为 n-1+2 总长度为2n+1
string preProcess(string sentence){
int length = sentence.size();
if(!length){
return "";
}
char end = '#';
string newStr;
for(int i=0;i<length;i++){
newStr.push_back('#');
newStr.push_back(sentence[i]);
}
newStr.push_back(end);
return newStr;
}
//中心扩展的方式计算 以center为中心的回文字符串 左右两侧的扩展长度
int centerSpread(string sentence,int center){
int len = sentence.size();
int i = center-1;
int j = center+1;
int spread = 0;
while(i>=0&&j<len&&sentence[i]==sentence[j]){
i--;
j++;
spread++;
}
return spread;
}
//计算给定字符串中最长的回文子串 利用回文字符串的对称性质 遍历每一个字符i
//以i为中心向两边扩散计算最大的扩散距离spread
string normalPalindromeCalculate(string sentence){
int length = sentence.size();
if(length<2){
return sentence;
}
string fixStr = preProcess(sentence);//预处理原始字符串
int fixStrLen=2*length+1;//处理后的字符串长度
int maxLen = 1;//回文字符串最大
int start = 0;//回文字符串开头索引
for(int i =0;i<fixStrLen;i++){
int spreadLen = centerSpread(fixStr,i);
if(spreadLen>maxLen){
maxLen = spreadLen;
start = (i-spreadLen)/2;//i-spreadLen为fixStr的回文字符串开始索引 /2才是原始字符串的开始索引
}
}
cout<<"maxLen="<<maxLen<<endl;
return sentence.substr(start,start+maxLen);//substr 包含头也包含尾
}
//Manacher算法计算字符串的最大回文字串
//字符串预处理 将字符串(size = n)处理成 #a#b#c# 的这种形式 以# 开头和结尾 字符中间用#填充
//这样保证的是新字符串字符的个数是奇数个(size = n+ (n-1)+2 = 2n+1)个 方便利用回文字符串的对称性
//还有一条重要的性质 newIndex/2 =oldIndex 即 新字符串char<a>的下标是原始字符串char<a>下标的2倍
string preProcessStr(string sentence){
int length = sentence.size();
if(length==0){
return "";
}
string newStr = "";
for(int i=0;i<length;i++){
newStr+='#';
newStr+=sentence[i];
}
newStr+='#';
return newStr;
}
//manacher算法 计算字符串中的最大回文子串
string maxPalindromeCalculateByManacherAlgorithm(string sentence){
int s_len = sentence.size();
if(s_len<2){
return sentence;
}
//预处理字符串
string fix_str = preProcessStr(sentence);
int fix_len = 2*s_len+1;//预处理之后字符串的长度
int maxLen = 1;//最大回文子串的长度
int start = 0;//最大回文子串的开始索引
vector<int> p(fix_len,0);//定义新字符串索引对应的p数组 p[i]代表 以i为中心向两边扩散的最大扩散长度spread
int maxRight = 0;//扫描过程中 最右边能达到的最大索引
int center = 0; //扫描过程中 回文子串的中心索引
for (int i = 0; i < fix_len; i++)
{
/* code */
//i<maxRight的时候才可以利用中心对称性质 寻找镜像 i>=maxRight的时候只能进行中心扩展了
if(i<maxRight){
int mirror = center*2-i;//mirror是i关于 center的镜像坐标 center-mirror=i-center
/*由于回文字符串的对称性质 我们可以利用i关于center对称的镜像坐标来求p[i] 因为我们是从左到右扫描的
maxRight和center也在不断的更新
1 当p[mirror]<maxRright p[i]=p[mirror]=d
2 当p[mirror]=maxRright 需要从左侧的 i-p[mirror]-1和maxRright+1 继续向两侧扩散对比寻找 最大扩展长度
3 当p[mirror]>maxRright 时p[i]=maxRright-i 简单证明
p[i]>maxRight-i =>关于i对称 S[i-d-1]=S[maxRright+1]
=>关于center对称 S[i-d-1]=S[mirror+d+1] =>关于mirror对称 S[mirror+d+1]=S[mirror-d-1]
=> S[maxRight+1]=S[mirror-d-1] 这说明关于center的最大回文长度是可以加1 maxRight=maxRright+1
这与现在maxRight所在的位置矛盾 所以 p[i]最大值也就是maxRright-i
*/
p[i]=min(maxRight-i,p[mirror]);//综上所述 我们取p[i]的最小值 然后在这个最小值的基础上向两侧扩展
}
//定义开始中心扩散的左右端点
int left = i-p[i]-1;
int right = i+p[i]+1;
while(left>=0&&right<fix_len&&fix_str[left]==fix_str[right]){//开始扫描 指针不越界 对称字符相等继续循环
left--;
right++;
p[i]++;
}
//maxRight是向右侧扩展最大的索引 更新maxRight center;
//maxRight越大越容易进入i<maxRight的条件判断 也就是说可以更多的利用已经有的回文字符串信息
if(i+p[i]>maxRight){
maxRight = i+p[i];
center = i;
}
//更新最大回文字符串长度
if(p[i]>maxLen){
maxLen = p[i];
start = (i - maxLen)/2;//原始字符串中 最大回文字串的起始坐标 因为字符串是填充过的 原有字符串的坐标翻倍了
}
}
return sentence.substr(start,start+maxLen);//包含头 不包含尾
}
int main () {
string s = "abababacde";
string fixStr = maxPalindromeCalculateByManacherAlgorithm(s);
cout<<fixStr<<endl;
return 0;
} | true |
18f9281d84bc480226bb50679151217d47459d95 | C++ | jayakamal-geek/CPP-Lab-Assignments | /2810/LAB1/CS19B028_A1.cpp | UTF-8 | 13,018 | 3.890625 | 4 | [] | no_license | #include<iostream>
#include<string> //header file to use string class and its functions
#include<cstdlib> //header file for pointer operations
using namespace std;
/*-------------------------------------------------------------------------------------------------
* Author : Maddula Jaya Kamal(cs19b028)
* Code : CPP code to manage Matrix operations using classes.
* Question : CS2810 A1Q1
-------------------------------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------------------------------
* Class Name : Matrix
* Application : Used to represent & store matrices and perform some special operstions.
* Inheritances : Nil
-------------------------------------------------------------------------------------------------*/
class Matrix
{
int order; //an integer to store the order of the given square matrix.
int** matrix; // double pointer to store entries of the matrix as a 2-dimensional array.
public:
Matrix( int order, int** matrix) //class constructor of the Matrix class to easen up initialisation.
{
this->matrix = matrix; //assigning the order to the instance variable of Matrix class
this->order = order; //assigning the order to the instance variable of Matrix class
}
void SpecialSum(void); // A Special function defined in the question. keyword: SPSUM
void ModMultiplication(void); // A Special function defined in the question. Keyword: MOD
void MatrixRightShift(Matrix, int); // A special function defined in the question. keyword: MRS
void SpecialMatrixAddition(Matrix, int); // A special function defined in the question. keyword: MADD
};
/*-------------------------------------------------------------------------------------------------
* Function Name : SpecialSum(SPSUM)
* Args : Nil
* Return Type : None
* Application : This function Adds row index(i) and column index(j) of each element of the
matrix. If this sum is odd, it swaps the element A[i][j] with A[j][i].
Then, it prints the sum of each row of this new matrix.
-------------------------------------------------------------------------------------------------*/
void Matrix::SpecialSum()
{
int tempMatrix[order][order]; //temporary matrix to prevent any changes to original Matrix
for(int i=0; i<order; i++) //for loop to verify the asked condition
{
for(int j=0; j<=i; j++) //for loop only till j=i, to reduce number of operations to nearly half.
{
if((i+j)%2) //swapping if sum of indexes is odd
{
tempMatrix[i][j] = matrix[j][i]; //initialing the required matrix as asked in the question
tempMatrix[j][i] = matrix[i][j];
}
else //not changing the order if sum of indexes is even.
{
tempMatrix[i][j] = matrix[i][j]; //initialing the required matrix as asked in the question
tempMatrix[j][i] = matrix[j][i];
}
}
}
for(int i=0; i<order; i++) //for loop to find the sum of elements in each row
{
int sum=0; //sum variable initialised to zero
for(int j=0; j<order; j++) //for loop to traverse across row of the Matrix
{
sum+=tempMatrix[i][j]; // sum = sum + tempMatrix[i][j]
}
if(i==order-1)
cout << sum << endl; //printing sum and new line
else
cout << sum << ","; //printing sum and space
}
}
/*-------------------------------------------------------------------------------------------------
* Function Name : ModMultiplication(MOD)
* Args : Nil
* Return Type : None
* Application : If row index(i) is divisible by 3, then its key is max element of that row.
If i gives 1 on division by 3, then its key is minimum element of that row.
else it is the average of the elements of that row. This function gives the
product of all keys of the matrix.
-------------------------------------------------------------------------------------------------*/
void Matrix::ModMultiplication()
{
long long int product = 1; //variable to save the product of keys of all rows
for(int i=0; i<order; i++) //for loop to traverse through rows of the matrix
{
int key = matrix[i][0]; //defining key of a matrix to be the first element of the row
if(i%3==0) //if i is divisible by row
{
for(int j=1; j<order; j++) //for loop to traverse through the row to find the largest element in the row.
{
if(key < matrix[i][j]) //replacing key with a new element of its larger than key.(key = max element)
{
key = matrix[i][j];
}
}
}
else if(i%3==1) //if remainder is 1 when divided by i
{
for(int j=1; j<order; j++) //for loop to traverse through the row to find the smallest element in the row.
{
if(key > matrix[i][j]) //replacing key with a new element of its smaller than key.(key = min element)
{
key = matrix[i][j];
}
}
}
else
{
for(int j=1; j<order; j++) //for loop to traverse through the row to find the average of elements in the row.
{
key = key + matrix[i][j]; //finding sum of all elements
}
key = key/order; //dividing the sum with order to find the average
}
product = product*key; //multiplying the key of every row after finishing the operation on that row.
}
cout << product << endl; //printing the product of all keys of rows of the matrix.
}
/*-------------------------------------------------------------------------------------------------
* Function Name : MatrixRightShift(MRS)
* Args : Another Matrix and an integer for shift
* Return Type : None
* Application : Perform right shift operation on both the matrices(k times).
Print the sum of these shifted matrices.
-------------------------------------------------------------------------------------------------*/
void Matrix::MatrixRightShift(Matrix B, int k)
{
int j1, i1;
int tempMatrix[order][order]; //A matrix to store the sum of matrices after shift
for(int i=0; i<order; i++) //For loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //For loop to traverse across the matrix(column index)
{
j1 = (j+k)%order; //function to shift the value of j
i1 = (i+(j+k)/order)%order; //functiion to shift the value of i.
tempMatrix[i1][j1] = matrix[i][j] + B.matrix[i][j]; //finding the sum ater shift.
}
}
for(int i=0; i<order; i++) //for loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //for loop to traverse across the matrix(column index)
{
cout << tempMatrix[i][j] << " "; //prints the elements of matrix which is the sum of matrices after shift
}
cout << endl; //printing every row in a new line.
}
}
/*-------------------------------------------------------------------------------------------------
* Function Name : SpecialMatrixAddition
* Args : Another Matrix and an integer for selection
* Return Type : None
* Application : If x = 1, then perform a transformation on the elements of 1st matrix such
that A[i][j] gets swapped with A[j][i]. Then, add it to the 2nd matrix B and
print the resulting matrix. If x is 2 perform the swap on 2nd matrix.
-------------------------------------------------------------------------------------------------*/
void Matrix::SpecialMatrixAddition(Matrix B, int x)
{
int tempMatrix[order][order]; //temporary matrix to store the sum after making swap operaation
if(x==1) //checking on which matrix swap needs to be performed.
{
for(int i=0; i<order; i++) //for loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //for loop to traverse across the matrix(column index)
{
tempMatrix[i][j] = matrix[j][i] + B.matrix[i][j]; //finding sum by swapping elements of Matrix 1.
}
}
}
else if(x==2) //checking on which matrix swap needs to be performed.
{
for(int i=0; i<order; i++) //for loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //for loop to traverse across the matrix(column index)
{
tempMatrix[i][j] = matrix[i][j] + B.matrix[j][i]; //finding sum by swapping elements of Matrix 2.
}
}
}
else
cout << "Invalid Input" << endl; //Invalid Input of x!=1 and X!=2.
for(int i=0; i<order; i++) //for loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //for loop to traverse across the matrix(column index)
{
cout << tempMatrix[i][j] << " "; //prints the elements of matrix which is the sum of matrices after shift
}
cout << endl; //printing every row in a new line.
}
}
/***************Class functions End here***************/
/*-------------------------------------------------------------------------------------------------
* Function Name : main
* Args : Nil
* Return Type : None
* Application : Entry Point into the code
-------------------------------------------------------------------------------------------------*/
int main()
{
int q, order, key; //variables for number of instructions and order of the matrix and key for deciding shift or selection.
cin >> q; //taking input for number of instructions.
cin >>order; //taking input for the order of matrix.
string inputCommand; //string to take in the entered command.
int **tempMatrix1 = (int**)malloc(order*sizeof(int*)); //allocating necessary memory to the 2-d pointer array
int **tempMatrix2 = (int**)malloc(order*sizeof(int*)); //allocating necessary memory to the 2-d pointer array
for(int i=0; i<order; i++)
{
tempMatrix1[i] = (int*)malloc(order*sizeof(int)); //allocating necessary memory to the 2-d pointer array
tempMatrix2[i] = (int*)malloc(order*sizeof(int)); //allocating necessary memory to the 2-d pointer array
}
for(int i=0; i<order; i++) //for loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //for loop to traverse across the matrix(column index)
{
cin >> tempMatrix1[i][j]; //taking input for matrix1
}
}
for(int i=0; i<order; i++) //for loop to traverse across the matrix(row index)
{
for(int j=0; j<order; j++) //for loop to traverse across the matrix(column index)
{
cin >> tempMatrix2[i][j]; //taking input for matrix2
}
}
Matrix A(order, tempMatrix1), B(order, tempMatrix2); //creating objects through the taken inputs.
for(int i=0; i<q; i++) //for loop to perform all instructions
{
cin >> inputCommand; //taking the input command.
if(inputCommand.compare("SPSUM")==0) //comparing input instruction with defined instructions
A.SpecialSum(); //calling the appropriate function
else if(inputCommand.compare("MOD")==0) //comparing input instruction with defined instructions
A.ModMultiplication(); //calling the appropriate function
else if(inputCommand.compare("MRS")==0) //comparing input instruction with defined instructions
{
cin >> key ; //taking input of necessary second argument
A.MatrixRightShift(B, key); //calling the appropriate function
}
else if(inputCommand.compare("MADD")==0) //comparing input instruction with defined instructions
{
cin >> key; //taking input of necessary second argument
A.SpecialMatrixAddition(B, key); //calling the appropriate function
}
else //failsafe to prevent program misbehaviour on passing undefined arguments
cout << "Invalid Command" << endl;
}
return 0; //exit call to exit the program after succesful compilation.
} | true |
a42c5000aa302a2c73d2a7bf69b5b6d36633d5df | C++ | Nico99/Oyebanji-electronics | /Lab01/Lab01.ino | UTF-8 | 4,318 | 3.546875 | 4 | [] | no_license | //Nicholas Oyebanji
//Lab01
////Functions
//void printHappy(String name) {
// String result = "Happy Birthday" + name; ///This is cantantinating: add a string plus another string
// Serial.println(result);
//}//
//
////functions
//void printGospels() {
// String gospels[] = {"Matthew", "Mark", "Luke", "John"};
// Serial.println("The Gospels are:");
// for(int i = 0; i<4; i++) {
// Serial.println(gospels[i]);
// }
//
//}
//
//float computeArea(float wid, float hei) {
// float area = wid * hei;
// return(area);
//}
void function1() {
Serial.println("I am an Arduino and I communicate at \n 9600 Baud rate. Ports 0 and 1 are used \n for serial communication. \n \n Serial communication works well for debugging \n and monitoring sensor values during the \n execution of a program.");
}
void function2a(int x, int y) {
int result = (x/2) * y;
Serial.println(result);
}
void function2b(int x, int y) {
int result = (2 * x) + (x * y);
Serial.println(result);
}
void function3() {
String favCharacters [] = {"Troy", "Harry Potter", "Frank Cat", "Lee", "Carter"};
Serial.println("My favorite movie characters are:");
//for loop
for(int i = 0; i <5; i++) {
Serial.println(favCharacters[i]);
}
}
//function 4
void function4() {
int num[] = {1,2,3,4,5,6,7,8};
//for loop to increase
for(int i =0; i<8; i++) {
Serial.println(num[i]);
}
//for loop to decrease
for(int a=7; a>=0; a--) {
Serial.println(num[a]);
}
for(int b = 1; b < 8; b+=2) {
Serial.println(num[b]);
}
for(int c = 0; c < 8; c+=2) {
Serial.println(num[c]);
}
for(int d = 6; d >=0; d-=2) {
Serial.println(num[d]);
}
for(int e = 7; e>=0; e-=2) {
Serial.println(num[e]);
}
}
void function5() {
String pitchNames[] = {"C", "D", "E", "F", "G", "A", "B", "C"};
//Hey, I was wandering for this function, could I do a while loop so that this can repeat twice
//for loop()
for(int i = 0; i < 8; i++) {
Serial.println(pitchNames[i]);
}//increasing
//decreasing
for(int a = 8; a >=0; a--) {
Serial.println(pitchNames[a]);
}
//increasing
for(int b = 0; b < 8; b++) {
Serial.println(pitchNames[b]);
}//increasing
//decreasing
for(int c = 8; c >=0; c--) {
Serial.println(pitchNames[c]);
}
}
void printFibo(int n) {
int a = 0;//first digit
int b = 1;//next digit
for(int i = 0; i < n; i++) {
int result = a + b; // the first digit and the last digit sum
Serial.println( "Fibonacci sequence starts here:" + result);
a = b;
b = result;
}
}
//this finds the y-int in a linear x model
int findYIntercept(int a, int b) {
int yInt = (a * 0) + b;
return yInt;
}
//function 8
//Wild numbers
void function8() {
for(long i = 0; i < 100000; i++) {
Serial.println( i * 10);
}
//Answers to the questions
//a. I think the variables will be multiplied by 10
//b. The sequence continously goes from positive to negative when it hits 32,000 due to it begin an interger instead of a long
//c. The reason for this scenario is because everytime the number hits 100, 000, the number will switch to negative numbers. One way to change this from happening is to change the the int to a long, which will stop at the limit
//I put long so that it won't go up and down on the serial monitor, also, so that I can screenshoot
}
void function9() {
long result = 0;
for(int i = 0; i<1000; i++) {
if((i % 5 == 0) || (i % 3 == 0)) {
result +=i;
}
}
Serial.println(result);
}
//prints random words
void function10(int n) {
String resul = "";
String words[] = {"hi", "ferrari", "download", "ram", "nik"};
for(int i =0; i < n; i++) {
int a = int(random(5));
Serial.println(words[a]);
}
}
void setup() {
Serial.begin(9600);//Start serial communication
//Serial.println("Hello, World");
//Serial.println("This is printing");
//printHappy("Nicholas");
//Serial.println(computeArea(30, 40));
//function1();
//function2a(120, 512);
//function2b(97, 32);
function3();
//function4();
//function5();
Serial.println(findYIntercept(3, 4));//in a linear model y = mx + b, in which you plug in 0 for x;
// function8();//error in directions
//printFibo(19);
//function9();
//function10(3);
}//end setup
void loop() {
}//end loop
| true |
316585fb3c12497327c3b3f74fadaf8b4fe1d6ab | C++ | Cyborg108/USACO | /buylow.cpp | UTF-8 | 3,472 | 2.515625 | 3 | [] | no_license | /*
ID: rupertl1
PROG: buylow
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <algorithm>
#include <utility>
#include <string.h>
#include <iterator>
#include <vector>
#include <iomanip>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <unordered_set>
using namespace std;
const int infinity = 2000000000;
#define MAX 5002
#define MAXP 8
#define LIM 1000000000
using namespace std;
class hpnum {
public:
long sec[MAXP];
int seccnt;
hpnum() { sec[seccnt = 1] = 0; }
void plus(hpnum &P) {
int sect = seccnt>P.seccnt ? seccnt : P.seccnt;
long T, up = 0;
for (int i = 1; i <= sect; i++) {
if (i>seccnt)
sec[i] = 0;
if (i>P.seccnt)
P.sec[i] = 0;
T = sec[i] + P.sec[i] + up;
up = T / LIM;
sec[i] = T%LIM;
}
seccnt = sect;
if (up) sec[++seccnt] = up;
}
void cpy(hpnum &P) {
seccnt = P.seccnt;
for (int i = 1; i <= seccnt; i++)
sec[i] = P.sec[i];
}
}
;
int main() {
ofstream fout("buylow.out");
ifstream fin("buylow.in");
int n;
fin >> n;
int x[5000];
for (int i = 0; i < n; i++)
fin >> x[i];
fin.close();
int next[5000];
for (int i = 0; i < n; i++)
next[i] = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (x[j] == x[i]) {
next[i] = j;
break;
}
}
}
int dp[5000];
//For the nth element (of 5000)
//1st element: length of longest sequence
// starting with that element.
//XXXXXXXXXX 2nd element: number of ways.
for (int i = 0; i < n; i++) {
dp[i] = 1;
}
/*
vector <vector<int> > seq[5000];
vector <int> temp;
for (int i = 0; i < n; i++) {
seq[i].push_back(vector<int>(1,x[i]));
}
for (int i = n - 2; i >= 0; i--) {
int imax = 0;
for (int j = i + 1; j < n; j++) {
if (x[i] > x[j]) {
if (dp[j] > imax)
imax = dp[j];
}
}
for (int j = i + 1; j < n; j++) {
if (dp[j] == imax && imax > 0) {
for (int k = 0; k < seq[j].size(); k++) {
seq[i].push_back(seq[j][k]);
}
}
}
}
int ans = 0;
vector<vector<int>> anset;
for (int i = 0; i < n; i++) {
if (dp[i] > ans)
ans = dp[i];
}
for (int i = 0; i < n; i++) {
if (dp[i] == ans) {
for (int j = 0; j < seq[i].size(); j++) {
temp = seq[i][j];
if (find(anset.begin(), anset.end(), temp) == anset.end()) {
anset.push_back(temp);
}
}
}
}
fout << ans << ' ' << anset.size() << endl;
*/
hpnum dpc[5000];
for (int i = 0; i < n; i++) {
dpc[i].sec[1] = 1;
}
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++) {
if (next[j] && next[j] < i)
continue;
if (x[j] > x[i]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
dpc[i].cpy(dpc[j]);
}
else if (dp[j] + 1 == dp[i])
dpc[i].plus(dpc[j]);
}
}
int ans = 0;
hpnum ansc;
for (int i = 0; i < n; i++) {
if (!next[i]) {
if (dp[i] > ans) {
ans = dp[i];
}
}
}
for (int i = 0; i < n; i++) {
if (!next[i]) {
if (dp[i] == ans) {
ansc.plus(dpc[i]);
}
}
}
fout << ans << ' ';
long k;
for (int i = ansc.seccnt; i >= 1; i--) {
k = LIM / 10;
if (i != ansc.seccnt && ansc.sec[i] < k) {
while (ansc.sec[i] < k) {
fout << 0;
k /= 10;
}
}
if (ansc.sec[i])
fout << ansc.sec[i];
}
fout << endl;
fout.close();
return 0;
}
| true |
feb79071aa6f9084e16ab18b35638a1f6546193c | C++ | melshazly89/Algo_ToolBox | /week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.cpp | UTF-8 | 870 | 3.265625 | 3 | [] | no_license | #include <iostream>
long long Pisano_Period(long long m);
int fibonacci_sum_naive(long long n) {
int length=Pisano_Period(10);
n=n%length;
if (n <= 1)
return n;
long long previous = 0;
long long current = 1;
long long sum = 1;
for (long long i = 0; i < n - 1; ++i) {
long long tmp_previous = previous;
previous = current;
current = (tmp_previous + current)%10;
sum += current;
}
return sum%10;
}
long long Pisano_Period(long long m)
{
long long previous=0;
long long current=1;
long long Period=0;
long long Seq=previous+current;
while(1)
{
Seq=(previous+current)%m;
previous=current;
current=Seq;
Period++;
if(current==1&&previous==0)
{
break;
}
}
return Period;
}
int main() {
long long n = 0;
std::cin >> n;
std::cout << fibonacci_sum_naive(n);
}
| true |
5feff35ef7fe751a6595fa963cca6b059bb07261 | C++ | kimhyeyun/2020-1-datastructure | /Day9_P1_E.cpp | UTF-8 | 1,052 | 3.671875 | 4 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
class Heap {
public:
vector<int> data;
int heapSize;
Heap() {
data.push_back(-1);
heapSize = 0;
}
void insert(int x) {
data.push_back(x);
heapSize++;
int idx = heapSize;
while (idx > 1) {
if (data[idx] < data[idx / 2]) {
int tmp = data[idx];
data[idx] = data[idx / 2];
data[idx / 2] = tmp;
}
else
break;
idx /= 2;
}
}
int size() {
return heapSize;
}
bool isEmpty() {
if (heapSize == 0)
return 1;
return 0;
}
void print() {
if (heapSize == 0) {
cout << -1 << "\n";
return;
}
else {
for (int i = 1; i < data.size(); i++)
cout << data[i] << " ";
cout << "\n";
}
}
};
int main() {
Heap hp;
int N;
cin >> N;
while (N--) {
string str;
cin >> str;
if (str == "insert") {
int x;
cin >> x;
hp.insert(x);
}
else if (str == "size")
cout << hp.size() << "\n";
else if (str == "isEmpty")
cout << hp.isEmpty() << "\n";
else if (str == "print")
hp.print();
}
return 0;
} | true |
51a7ba16b619f8cb5898f36c44963f8a8c9a74c5 | C++ | hjh4638/C-11 | /ST2_day5/8_완벽한전달자4.cpp | UHC | 530 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
void foo(int&& k, int&& q) { cout << "foo" << endl; }
// 4. rvalue ڷ Ǹ Types&& rvalue_reference̴
// args... ü ̸ִ rvalue reference ̹Ƿ
// lvalue ȴ.
// forward<> Ѵ.
template<typename F, typename ... Types>
decltype(auto) HowLong(F f, Types&& ... args)
{
return f(forward<Types&&>(args)...);
// f(forward<T&&>(0), forward<T&&>(0));
}
int main()
{
foo(0, 0);
HowLong(foo, 0, 0);
} | true |
03f2e184776ce356e7f473ad8baaae3cc495639b | C++ | QXYcs/C-Primer-Exercise | /charpter9/9.28/9.28.cpp | UTF-8 | 658 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <forward_list>
using namespace std;
void insert_string(forward_list<string> &fl, string str1, string str2) {
auto pre = fl.before_begin();
auto curse = fl.begin();
bool isFound = false;
while (true) {
if (curse == fl.cend()) {
if (!isFound) fl.insert_after(pre, str2);
return;
}
if (*curse == str1) {
++pre;
curse = fl.insert_after(curse, str2);
isFound = true;
}
else {
++pre;
++curse;
}
}
}
int main() {
forward_list<string> fl{ "ab", "bc", "ccde", "ccde", "efgh" };
insert_string(fl, "fesf", "zz");
for (const auto &i : fl)
cout << i << endl;
system("pause");
} | true |
aeed1194b57b9b07898781b4fdfa207f841f2056 | C++ | jswilder/Orc-Siege-Game | /Classes/mySprite.cpp | UTF-8 | 7,551 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include "mySprite.h"
// velocity x & y, file name , 1 if plist/0 if not, num of frames
mySprite::mySprite(const int vx, const int vy, const std::string file, bool pl, int fnum) :
velocity(vx,vy),
viewSize( cocos2d::Director::getInstance()->getVisibleSize() ),
origin( cocos2d::Director::getInstance()->getVisibleOrigin() ),
speedScaled(false)
{
if(pl){
// Add all frames the cache for later use
cocos2d::SpriteFrameCache::getInstance()->addSpriteFramesWithFile( (file+"right.plist").c_str() );
cocos2d::SpriteFrameCache::getInstance()->addSpriteFramesWithFile( (file+"left.plist").c_str() );
cocos2d::SpriteFrameCache::getInstance()->addSpriteFramesWithFile( (file+"up.plist").c_str() );
cocos2d::SpriteFrameCache::getInstance()->addSpriteFramesWithFile( (file+"down.plist").c_str() );
cocos2d::SpriteFrameCache::getInstance()->addSpriteFramesWithFile( (file+"stand.plist").c_str() );
cocos2d::SpriteFrameCache::getInstance()->addSpriteFramesWithFile( (file+"die.plist").c_str() );
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames( (file + "stand%1d.png").c_str() , fnum);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
float newX = viewSize.width/2 + origin.x;
float newY = viewSize.height/2 + origin.y;
sprite->setPosition( cocos2d::Point(newX, newY) );
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/5);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
}else{
sprite = cocos2d::Sprite::create(file);
float newX = viewSize.width/2 + origin.x;
float newY = viewSize.height/2 + origin.y;
sprite->setPosition( cocos2d::Point(newX, newY) );
}
mySpriteWidth = sprite->getContentSize().width;
}
float getVelocity() {
float x = rand() % 5 + 1;
x = (rand()%2?-1:1)*x;
return x;
}
cocos2d::Rect mySprite::getIntersection(const cocos2d::Rect &r1, const cocos2d::Rect &r2) const {
float tempX;
float tempY;
float tempWidth;
float tempHeight;
if (r1.getMaxX() > r2.getMinX()) {
tempX = r2.getMinX();
tempWidth = r1.getMaxX() - r2.getMinX();
} else {
tempX = r1.getMinX();
tempWidth = r2.getMaxX() - r1.getMinX();
}
if (r2.getMaxY() < r1.getMaxY()) {
tempY = r1.getMinY();
tempHeight = r2.getMaxY() - r1.getMinY();
} else {
tempY = r2.getMinY();
tempHeight = r1.getMaxY() - r2.getMinY();
}
return cocos2d::Rect( tempX * CC_CONTENT_SCALE_FACTOR(), tempY * CC_CONTENT_SCALE_FACTOR(),
tempWidth * CC_CONTENT_SCALE_FACTOR(), tempHeight * CC_CONTENT_SCALE_FACTOR() );
}
bool mySprite::collidedPix(cocos2d::Sprite *sprite1) {
cocos2d::Sprite* orc = getSprite();
cocos2d::Rect r1 = sprite1->getBoundingBox();
cocos2d::Rect r2 = orc->getBoundingBox();
cocos2d::Rect intersection = this->getIntersection(r1, r2);
unsigned int numPixels = intersection.size.width * intersection.size.height;
if (numPixels > 5 ) return true;
/*else*/ return false;
}
bool mySprite::collidedRect(const mySprite* otherSprite){
int myWidth = sprite->getContentSize().width;
int myHeight = sprite->getContentSize().height;
int oWidth = otherSprite->getSprite()->getContentSize().width;
int oHeight = otherSprite->getSprite()->getContentSize().height;
cocos2d::Point myPos = sprite->getPosition();
cocos2d::Point oPos = otherSprite->getSprite()->getPosition();
if ( myPos.x+myWidth/2 < oPos.x-oWidth/2 ) return false;
if ( myPos.x-myWidth/2 > oPos.x+oWidth/2 ) return false;
if ( myPos.y-myHeight/2 > oPos.y+oHeight/2 ) return false;
if ( myPos.y+myHeight/2 < oPos.y-oHeight/2 ) return false;
return true;
}
cocos2d::Vector<cocos2d::SpriteFrame*> mySprite::getFrames(const char *format, int count) {
cocos2d::SpriteFrameCache*
spritecache = cocos2d::SpriteFrameCache::getInstance();
cocos2d::Vector<cocos2d::SpriteFrame*> animFrames;
char str[100];
for(int i = 1; i <= count; i++) {
sprintf(str, format, i);
animFrames.pushBack(spritecache->getSpriteFrameByName(str));
}
return animFrames;
}
void mySprite::setVel(int x, int y){
velocity.x = x;
velocity.y = y;
}
void mySprite::Scale(float val){
// Scales Image size
sprite->setScale(val);
// Scales velocity
if(val > 1.6){
if( !speedScaled ){
speedScaled = true;
velocity.x = static_cast<int>(velocity.x * (val*.7));
velocity.y = static_cast<int>(velocity.y * (val*.7));
}
}
else{
if(!speedScaled){
speedScaled = true;
velocity.x = static_cast<int>(velocity.x * val);
velocity.y = static_cast<int>(velocity.y * val);
}
}
}
void mySprite::runAnimRight(){
cocos2d::Point position = sprite->getPosition();
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames("orcright%1d.png", 9);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/9);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
sprite->setPosition( cocos2d::Point(position.x, position.y) );
}
void mySprite::runAnimLeft(){
cocos2d::Point position = sprite->getPosition();
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames("orcleft%1d.png", 9);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/9);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
sprite->setPosition( cocos2d::Point(position.x, position.y) );
}
void mySprite::runAnimUp(){
cocos2d::Point position = sprite->getPosition();
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames("orcup%1d.png", 9);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/9);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
sprite->setPosition( cocos2d::Point(position.x, position.y) );
}
void mySprite::runAnimDown(){
cocos2d::Point position = sprite->getPosition();
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames("orcdown%1d.png", 9);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/9);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
sprite->setPosition( cocos2d::Point(position.x, position.y) );
}
void mySprite::runAnimIdle(){
cocos2d::Point position = sprite->getPosition();
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames("orcstand%1d.png", 5);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/5);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
sprite->setPosition( cocos2d::Point(position.x, position.y) );
}
void mySprite::runAnimDeath(){
cocos2d::Point position = sprite->getPosition();
cocos2d::Vector<cocos2d::SpriteFrame*>frames = getFrames("orcdie%1d.png", 6);
sprite = cocos2d::Sprite::createWithSpriteFrame(frames.front());
cocos2d::Animation*animation = cocos2d::Animation::createWithSpriteFrames(frames, 1.0f/6);
sprite->runAction(cocos2d::RepeatForever::create(cocos2d::Animate::create(animation)));
sprite->setPosition( cocos2d::Point(position.x, position.y) );
}
| true |
7cc53faf583d25989e82e4f7bfef126292733818 | C++ | rolfrm/bigtalk | /src/table.hpp | UTF-8 | 2,232 | 2.921875 | 3 | [] | no_license | class table{
struct table_info{
column_base ** columns;
size_t column_count;
size_t row_count;
char * name;
};
void push_column(column_base * col);
table_info * info;
public:
table();
table(const char * name);
void print_csv();
size_t get_column_count();
size_t get_row_count(){
return info->row_count;
}
column_base * get_column(size_t index);
template<typename T>
column_base * add_column(const char * name){
column<T> * new_column = array.create<column<T>>(1);
new (new_column) column<T>();
new_column->name = array.clone(name, strlen(name) + 1);
push_column(new_column);
return new_column;
}
void resize(size_t new_row_count);
size_t add_row();
void dispose();
static table create(const char * name);
typed_box current_view;
template<typename T>
void get_view(T & theview){
T * newview = &theview;
void ** ptrs = (void **) newview;
view<int> * views = (view<int> *) (ptrs + 1);
((size_t *) ptrs)[0] = info->row_count;
for(size_t i = 0; i < info->column_count; i++){
views[i].check_flag();
views[i] = view<int>((int *)info->columns[i]->get_view(), info->row_count);
}
}
template<typename T>
T get_view(){
T out = T();
get_view(out);
return out;
}
};
class table_index{
size_t column;
table t;
size_t * current_index;
size_t current_index_size;
void update_index();
public:
table_index(table t, size_t column){
this->t = t;
this->column = column;
current_index_size = 0;
}
template<typename T>
void get_view(T & outview){
size_t cnt = t.get_row_count();
if(cnt > current_index_size){
current_index = array.resize(current_index, cnt);
current_index_size = cnt;
}
t.get_view<T>(outview);
T * newview = &outview;
void ** ptrs = (void **) newview;
view<int> * views = (view<int> *) (ptrs + 1);
for(size_t i = 0; i < t.get_column_count(); i++){
views[i] = views[i].with_index(current_index);
}
update_index();
}
template<typename T>
T get_view(){
T out = T();
get_view<T>(out);
return out;
}
void dispose(){
array.free(current_index);
}
};
| true |
e6a4d7bbd21d98dc4ba70d15e6a964b47519fbd5 | C++ | ritsuxis/kyoupro | /yukicoder/yuki46.cpp | UTF-8 | 371 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int gcd(int a, int b)
{
int c;
if (a < b) {
a+=b; b=a-b; a-=b;
}
while (b != 0) {
c = a % b;
a = b;
b = c;
}
return a;
}
int main(void){
int a, b, ans = 0;
cin >> a >> b;
if(b % a == 0) ans = b / a;
else ans = b / a + 1;
cout << ans << endl;
} | true |
aa64c3b052fdbdc3e003bdfb72d5c8d1a4d0aaf7 | C++ | UCC-Programacion3-historico/ejercicios-2018-SantiagoMerlo | /U02_Listas/Ej-01/fnInvierte.h | UTF-8 | 576 | 2.765625 | 3 | [] | no_license | #include "../Lista/Lista.h"
#ifndef FNINVIERTE_H
#define FNINVIERTE_H
template <class T>
void fnInvierte (Lista<T> *lis);
template <class T>
void fnInvierte (Lista<T> *lis){
int n = lis->getTamanio() - 1; //supongamosque pusimos 4 valores, el n =4; sin embargo el i empieza en 0 por lo que se tiene que disminuir
for(int i = 0; i < lis->getTamanio()/2 ; i++) { //de esta forma vamos inviertiendo los extremos
int aux = lis->getDato(i);
lis->reemplazar(i, lis->getDato(n - i));
lis->reemplazar(n - i, aux);
}
}
#endif //FNINVIERTE_H | true |
1500b46008aac52f2bf12a341e3fe5a66edb69b3 | C++ | souffle-lang/souffle | /src/include/souffle/profile/ProfileDatabase.h | UTF-8 | 13,116 | 2.96875 | 3 | [
"UPL-1.0"
] | permissive | #pragma once
#include "souffle/utility/ContainerUtil.h"
#include "souffle/utility/MiscUtil.h"
#include "souffle/utility/json11.h"
#include <cassert>
#include <chrono>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
namespace souffle {
namespace profile {
class DirectoryEntry;
class DurationEntry;
class SizeEntry;
class TextEntry;
class TimeEntry;
/**
* Visitor Interface
*/
class Visitor {
public:
virtual ~Visitor() = default;
// visit entries in a directory
virtual void visit(DirectoryEntry& e);
// visit entries
virtual void visit(DurationEntry&) {}
virtual void visit(SizeEntry&) {}
virtual void visit(TextEntry&) {}
virtual void visit(TimeEntry&) {}
};
/**
* Entry class
*
* abstract class for a key/value entry in a hierarchical database
*/
class Entry {
private:
// entry key
std::string key;
public:
Entry(std::string key) : key(std::move(key)) {}
virtual ~Entry() = default;
// get key
const std::string& getKey() const {
return key;
};
// accept visitor
virtual void accept(Visitor& v) = 0;
// print
virtual void print(std::ostream& os, int tabpos) const = 0;
};
/**
* DirectoryEntry entry
*/
class DirectoryEntry : public Entry {
private:
std::map<std::string, Own<Entry>> entries;
mutable std::mutex lock;
public:
DirectoryEntry(const std::string& name) : Entry(name) {}
// get keys
const std::set<std::string> getKeys() const {
std::set<std::string> result;
std::lock_guard<std::mutex> guard(lock);
for (auto const& cur : entries) {
result.insert(cur.first);
}
return result;
}
// write entry
Entry* writeEntry(Own<Entry> entry) {
assert(entry != nullptr && "null entry");
std::lock_guard<std::mutex> guard(lock);
const std::string& keyToWrite = entry->getKey();
// Don't rewrite an existing entry
if (entries.count(keyToWrite) == 0) {
entries[keyToWrite] = std::move(entry);
}
return entries[keyToWrite].get();
}
// read entry
Entry* readEntry(const std::string& keyToRead) const {
std::lock_guard<std::mutex> guard(lock);
auto it = entries.find(keyToRead);
if (it != entries.end()) {
return (*it).second.get();
} else {
return nullptr;
}
}
// read directory
DirectoryEntry* readDirectoryEntry(const std::string& keyToRead) const {
return as<DirectoryEntry>(readEntry(keyToRead));
}
// accept visitor
void accept(Visitor& v) override {
v.visit(*this);
}
// print directory
void print(std::ostream& os, int tabpos) const override {
os << std::string(tabpos, ' ') << '"' << getKey() << "\": {" << std::endl;
bool first{true};
for (auto const& cur : entries) {
if (!first) {
os << ',' << std::endl;
} else {
first = false;
}
cur.second->print(os, tabpos + 1);
}
os << std::endl << std::string(tabpos, ' ') << '}';
}
};
/**
* SizeEntry
*/
class SizeEntry : public Entry {
private:
std::size_t size; // size
public:
SizeEntry(const std::string& key, std::size_t size) : Entry(key), size(size) {}
// get size
std::size_t getSize() const {
return size;
}
// accept visitor
void accept(Visitor& v) override {
v.visit(*this);
}
// print entry
void print(std::ostream& os, int tabpos) const override {
os << std::string(tabpos, ' ') << "\"" << getKey() << "\": " << size;
}
};
/**
* TextEntry
*/
class TextEntry : public Entry {
private:
// entry text
std::string text;
public:
TextEntry(const std::string& key, std::string text) : Entry(key), text(std::move(text)) {}
// get text
const std::string& getText() const {
return text;
}
// accept visitor
void accept(Visitor& v) override {
v.visit(*this);
}
// write size entry
void print(std::ostream& os, int tabpos) const override {
os << std::string(tabpos, ' ') << "\"" << getKey() << "\": \"" << text << "\"";
}
};
/**
* Duration Entry
*/
class DurationEntry : public Entry {
private:
// duration start
microseconds start;
// duration end
microseconds end;
public:
DurationEntry(const std::string& key, microseconds start, microseconds end)
: Entry(key), start(start), end(end) {}
// get start
microseconds getStart() const {
return start;
}
// get end
microseconds getEnd() const {
return end;
}
// accept visitor
void accept(Visitor& v) override {
v.visit(*this);
}
// write size entry
void print(std::ostream& os, int tabpos) const override {
os << std::string(tabpos, ' ') << '"' << getKey();
os << R"_(": { "start": )_";
os << start.count();
os << ", \"end\": ";
os << end.count();
os << '}';
}
};
/**
* Time Entry
*/
class TimeEntry : public Entry {
private:
// time since start
microseconds time;
public:
TimeEntry(const std::string& key, microseconds time) : Entry(key), time(time) {}
// get start
microseconds getTime() const {
return time;
}
// accept visitor
void accept(Visitor& v) override {
v.visit(*this);
}
// write size entry
void print(std::ostream& os, int tabpos) const override {
os << std::string(tabpos, ' ') << '"' << getKey();
os << R"_(": { "time": )_";
os << time.count();
os << '}';
}
};
inline void Visitor::visit(DirectoryEntry& e) {
std::cout << "Dir " << e.getKey() << "\n";
for (const auto& cur : e.getKeys()) {
std::cout << "\t :" << cur << "\n";
e.readEntry(cur)->accept(*this);
}
}
class Counter : public Visitor {
private:
std::size_t ctr{0};
std::string key;
public:
Counter(std::string key) : key(std::move(key)) {}
void visit(SizeEntry& e) override {
std::cout << "Size entry : " << e.getKey() << " " << e.getSize() << "\n";
if (e.getKey() == key) {
ctr += e.getSize();
}
}
std::size_t getCounter() const {
return ctr;
}
};
/**
* Hierarchical databas
*/
class ProfileDatabase {
private:
Own<DirectoryEntry> root;
protected:
/**
* Find path: if directories along the path do not exist, create them.
*/
DirectoryEntry* lookupPath(const std::vector<std::string>& path) {
DirectoryEntry* dir = root.get();
for (const std::string& key : path) {
assert(!key.empty() && "Key is empty!");
DirectoryEntry* newDir = dir->readDirectoryEntry(key);
if (newDir == nullptr) {
newDir = as<DirectoryEntry>(dir->writeEntry(mk<DirectoryEntry>(key)));
}
assert(newDir != nullptr && "Attempting to overwrite an existing entry");
dir = newDir;
}
return dir;
}
void parseJson(const json11::Json& json, Own<DirectoryEntry>& node) {
for (auto& cur : json.object_items()) {
if (cur.second.is_object()) {
std::string err;
// Duration entries are also maps
if (cur.second.has_shape(
{{"start", json11::Json::NUMBER}, {"end", json11::Json::NUMBER}}, err)) {
auto start = std::chrono::microseconds(cur.second["start"].long_value());
auto end = std::chrono::microseconds(cur.second["end"].long_value());
node->writeEntry(mk<DurationEntry>(cur.first, start, end));
} else if (cur.second.has_shape({{"time", json11::Json::NUMBER}}, err)) {
auto time = std::chrono::microseconds(cur.second["time"].long_value());
node->writeEntry(mk<TimeEntry>(cur.first, time));
} else {
auto dir = mk<DirectoryEntry>(cur.first);
parseJson(cur.second, dir);
node->writeEntry(std::move(dir));
}
} else if (cur.second.is_string()) {
node->writeEntry(mk<TextEntry>(cur.first, cur.second.string_value()));
} else if (cur.second.is_number()) {
node->writeEntry(mk<SizeEntry>(cur.first, cur.second.long_value()));
} else {
std::string err;
cur.second.dump(err);
std::cerr << "Unknown types in profile log: " << cur.first << ": " << err << std::endl;
}
}
}
public:
ProfileDatabase() : root(mk<DirectoryEntry>("root")) {}
ProfileDatabase(const std::string& filename) : root(mk<DirectoryEntry>("root")) {
std::ifstream file(filename);
if (!file.is_open()) {
throw std::runtime_error("Log file could not be opened.");
}
std::string jsonString((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
std::string error;
json11::Json json = json11::Json::parse(jsonString, error);
if (!error.empty()) {
throw std::runtime_error("Parse error: " + error);
}
parseJson(json["root"], root);
}
// add size entry
void addSizeEntry(std::vector<std::string> qualifier, std::size_t size) {
assert(qualifier.size() > 0 && "no qualifier");
std::vector<std::string> path(qualifier.begin(), qualifier.end() - 1);
DirectoryEntry* dir = lookupPath(path);
const std::string& key = qualifier.back();
Own<SizeEntry> entry = mk<SizeEntry>(key, size);
dir->writeEntry(std::move(entry));
}
// add text entry
void addTextEntry(std::vector<std::string> qualifier, const std::string& text) {
assert(qualifier.size() > 0 && "no qualifier");
std::vector<std::string> path(qualifier.begin(), qualifier.end() - 1);
DirectoryEntry* dir = lookupPath(path);
const std::string& key = qualifier.back();
Own<TextEntry> entry = mk<TextEntry>(key, text);
dir->writeEntry(std::move(entry));
}
// add duration entry
void addDurationEntry(std::vector<std::string> qualifier, microseconds start, microseconds end) {
assert(qualifier.size() > 0 && "no qualifier");
std::vector<std::string> path(qualifier.begin(), qualifier.end() - 1);
DirectoryEntry* dir = lookupPath(path);
const std::string& key = qualifier.back();
Own<DurationEntry> entry = mk<DurationEntry>(key, start, end);
dir->writeEntry(std::move(entry));
}
// add time entry
void addTimeEntry(std::vector<std::string> qualifier, microseconds time) {
assert(qualifier.size() > 0 && "no qualifier");
std::vector<std::string> path(qualifier.begin(), qualifier.end() - 1);
DirectoryEntry* dir = lookupPath(path);
const std::string& key = qualifier.back();
Own<TimeEntry> entry = mk<TimeEntry>(key, time);
dir->writeEntry(std::move(entry));
}
// compute sum
std::size_t computeSum(const std::vector<std::string>& qualifier) {
assert(qualifier.size() > 0 && "no qualifier");
std::vector<std::string> path(qualifier.begin(), qualifier.end() - 1);
DirectoryEntry* dir = lookupPath(path);
const std::string& key = qualifier.back();
std::cout << "Key: " << key << std::endl;
Counter ctr(key);
dir->accept(ctr);
return ctr.getCounter();
}
/**
* Return the entry at the given path.
*/
Entry* lookupEntry(const std::vector<std::string>& path) const {
DirectoryEntry* dir = root.get();
auto last = --path.end();
for (auto it = path.begin(); it != last; ++it) {
dir = dir->readDirectoryEntry(*it);
if (dir == nullptr) {
return nullptr;
}
}
return dir->readEntry(*last);
}
/**
* Return a map of string keys to string values.
*/
std::map<std::string, std::string> getStringMap(const std::vector<std::string>& path) const {
std::map<std::string, std::string> kvps;
auto* parent = as<DirectoryEntry>(lookupEntry(path));
if (parent == nullptr) {
return kvps;
}
for (const auto& key : parent->getKeys()) {
auto* text = as<TextEntry>(parent->readEntry(key));
if (text != nullptr) {
kvps[key] = text->getText();
}
}
return kvps;
}
// print database
void print(std::ostream& os) const {
os << '{' << std::endl;
root->print(os, 1);
os << std::endl << '}' << std::endl;
};
};
} // namespace profile
} // namespace souffle
| true |
71a9ab90400a56ec597f8961664dbc7bf96ad667 | C++ | saroj-kumar-barik/cpp-codes-from-scratch | /Function Pointer/02-ponterToMemberFunctionPointerToDataMemberPointerToObject.cpp | UTF-8 | 1,333 | 3.859375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class ABC{
int a,b;
public:
int c,d;
void setdata(int, int);
void display();
};
void ABC::display(){
cout<<"C = "<<c<<" and D = "<<d<<endl;
}
void ABC::setdata(int c, int d){
ABC::c = c;
ABC::d = d;
}
int main(){
ABC X;
// ponter to dataMember
int ABC::* pmc = &ABC::c; // creating an integer type pointer 'pma' that holdes address of c and
int ABC::* pmd = &ABC::d; // ABC:: indicate that the pointers are created under the scope of the class
X.c = 11;
X.*pmd = 22;
cout<<"data of obejct X : "<<endl;
cout<<&X.c<<endl;
// cout<<pmc<<" "<<X.d<<endl; why the value of pmc = (garbage)
cout<<X.*pmc<<" "<<X.d<<endl;
// reference
// int *x = &X.c;
// cout<<x<<endl;
// cout<<&X.c<<endl;
// cout<<*x;
// pointer to member function
ABC Y;
void (ABC::*pfs)(int, int) = &ABC::setdata;
void (ABC::*pfd)() = &ABC::display;
(Y.*pfs)(33,44);
cout<<"data of obejct X : "<<endl;
(Y.*pfd)();
// Pointer to Object
// When use arrow(->) : When object is of type pointer
// When use dot(.) : When object is Normal object
cout<<"data of obejct X : "<<endl;
ABC *Z;
Z = &X;
Z->c = 55;
Z->d = 66;
(Z->*pfd)();
}
| true |
35a3b15412dc18d2baa30521da7128250bec82a1 | C++ | ibrahimlazaar0xff/pHake | /pHake/UI/pSettings.cpp | UTF-8 | 2,167 | 3.0625 | 3 | [] | no_license | #include "pSettings.hpp"
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <sstream>
pSettings::pSettings()
{
this->file_content_ = new std::vector<std::string>;
}
pSettings::~pSettings()
{
delete[] this->file_content_;
}
bool pSettings::Open(const std::string& Filepath)
{
this->file_path_ = Filepath;
if (std::filesystem::exists(Filepath))
{
std::ifstream file(Filepath);
std::string temp_string;
while (std::getline(file, temp_string))
{
if (temp_string.size() > 0)
this->file_content_->push_back(temp_string);
}
return 1;
}
else
{
std::ofstream file{ Filepath };
file.close();
return 0;
}
}
void pSettings::AddComment(const std::string& Key)
{
if (!this->CheckExistanceOfKey(Key))
{
this->file_content_->push_back(Key);
}
}
void pSettings::Save()
{
std::ofstream del;
del.open(this->file_path_, std::ofstream::out | std::ofstream::trunc);
del.close();
std::ofstream file;
file.open(this->file_path_);
for (size_t i = 0; i < this->file_content_->size(); i++)
file << (*this->file_content_)[i] + "\n";
file.close();
}
void pSettings::Clear()
{
std::ofstream del;
del.open(this->file_path_, std::ofstream::out | std::ofstream::trunc);
del.close();
}
void pSettings::AddKeyAndValue(const std::string& Key, const std::string& Value)
{
this->file_content_->push_back(Key + " = " + Value);
}
std::string pSettings::GetKeyByName(const std::string& Key)
{
for (size_t i = 0; i < this->file_content_->size(); i++)
{
if ((*file_content_)[i].find(Key) != std::string::npos)
return (*file_content_)[i].substr((*file_content_)[i].find("=") + 1);
}
return "";
}
bool pSettings::CheckExistanceOfKey(const std::string& Key)
{
for (size_t i = 0; i < this->file_content_->size(); i++)
{
if ((*file_content_)[i].find(Key) != std::string::npos) {
return true;
}
}
return false;
}
void pSettings::ChangeKeyValue(const std::string& Key, const std::string& Value)
{
for (size_t i = 0; i < this->file_content_->size(); i++)
{
if ((*file_content_)[i].find(Key) != std::string::npos)
{
(*file_content_)[i].clear();
(*file_content_)[i] = Key + " = " + Value;
}
}
} | true |
541c1705e42c97e4bb368c8981bc589a6dbd8b84 | C++ | conwnet/way-of-algorithm | /poj-cpp/2836/15019824_TLE.cc | UTF-8 | 1,590 | 2.625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct Point {
int x, y;
} dot[20];
const int INF = 0x3f3f3f3f;
int dp[1<<15], N;
int cal_area(int s)
{
int x1, x2, y1, y2;
x1 = y1 = INF;
x2 = y2 = -INF;
for(int i=0; i<N; i++) {
if(!(s & 1<<i)) continue;
if(dot[i].x < x1) x1 = dot[i].x;
if(dot[i].y < y1) y1 = dot[i].y;
if(dot[i].x > x2) x2 = dot[i].x;
if(dot[i].x > y2) y2 = dot[i].y;
}
return (x2-x1) * (y2-y1);
}
int Count(int s)
{
int ret = 0;
for(int i=0; i<N; i++)
if(s & 1<<i) ret++;
return ret;
}
int build_sta(int s, int t, int n)
{
int p = 0, ret = 0;
for(int i=0; i<n; i++) {
while(!(s & 1<<p)) p++;
if(t & 1<<i) continue;
ret += 1<<p;
}
return ret;
}
int dfs(int s)
{
if(dp[s]) return dp[s];
int ret = cal_area(s);
int n = Count(s);
for(int i=0; i<1<<n; i++) {
int s0 = build_sta(s, i, n);
int n0 = Count(s0);
if(n0<2 || n-n0<2) continue;
ret = min(ret, dfs(s0)+dfs(s-s0));
}
return dp[s] = ret;
}
int main()
{
while(scanf("%d", &N) && N) {
for(int i=0; i<N; i++)
scanf("%d%d", &dot[i].x, &dot[i].y);
memset(dp, 0, sizeof(dp));
printf("%d\n", dfs((1<<N)-1));
}
return 0;
}
| true |
80958cd8d870982df8eb6cd7566e5baad3584248 | C++ | sopyer/Infinity | /Samples/VGTest/DataTypes.h | UTF-8 | 790 | 3.09375 | 3 | [] | no_license | #ifndef __DATATYPES_H_INCLUDED__
# define __DATATYPES_H_INCLUDED__
#include <vector>
//Unoptimized version - uses dynamic allocations,
//Can be improved using custom implementation with stack cache
template<typename T>
class Array: public std::vector<T>
{
public:
T* begin() {return empty()?0:&*std::vector<T>::begin();}
T* end () {return empty()?0:begin()+size();}
const T* begin() const {return empty()?0:&*std::vector<T>::begin();}
const T* end () const {return empty()?0:begin()+size();}
void pushBack(const T& value) {push_back(value);}
template<typename I>
void pushBack(I itBegin, I itEnd) {insert(std::vector<T>::end(), itBegin, itEnd);}
T* expand(size_t count)
{
resize(size()+count);
return end()-count;
}
};
#endif | true |
bb810f71cfe641159440125610fa9f2dec2e7184 | C++ | likohank/mianshiti_2018 | /06.dumplication.cpp | UTF-8 | 900 | 3.59375 | 4 | [] | no_license | #include <cstdio>
#include <cstring>
int countRange(const int* numbers,int length,int start,int end)
{
if (numbers == nullptr)
return 0;
int count = 0;
for (int i=0;i<length;i++)
{
if (numbers[i]>=start && numbers[i]<=end)
count ++;
}
return count;
}
int getDumplication(const int* numbers,int length)
{
if(numbers == nullptr || length<=1)
return -1;
int start = 1;
int end = length - 1;
while(start<=end)
{
int middle = ((end-start)>>2) + start;
int count = countRange(numbers,length,start,middle);
if (start==end)
{
if(count>1)
return start;
else
break;
}
if (count>(middle-start+1))
end = middle;
else
{
start = middle+1;
}
}
return -1;
}
int main()
{
int numbers[] = {2,3,5,4,3,2,6,7};
int length = sizeof(numbers)/sizeof(int);
int dump = getDumplication(numbers,length);
printf("The dumplication numbers is:%d\n",dump);
}
| true |
76229caee9cf3f23377843fc6c373a2704db1400 | C++ | dmsenter89/learningProgramming | /Cpp/Primer/ch03/3.42.cpp | UTF-8 | 392 | 3.890625 | 4 | [] | no_license | /*
* copy a vector of ints into an array
*/
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> v{1,2,3,4};
auto sz = v.size();
int ar[sz];
for (int i=0; i<sz; ++i){
ar[i] = v[i];
}
cout << "Done copying the arrays. Printing.\n";
for (auto c : ar){
cout << c << " ";
}
cout << endl;
return 0;
}
| true |
2a11b6893276accb48cbf078bc2f173f8336c2ce | C++ | ailyanlu1/Programming-Challenges | /leetcode/Valid_Number_DFA.cpp | UTF-8 | 2,001 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
// states of the DFA
enum STATE {
REJECT = 0,
Q0 = 1,
Q1,
Q2,
Q3,
Q4,
Q5,
Q6,
Q7,
Q8,
Q9
};
// symbols of the DFA
enum SYMBOL {
BADSYMBOL = 0,
DIGIT = 1,
SIGNED,
DOT,
EXPON,
SPACE
};
const int STATE_NUM = 11;
const int SYMBOL_NUM = 6;
SYMBOL symbol_check(char input){
if(input >= '0' && input <= '9'){
return DIGIT;
}
if(input == '+' || input == '-'){
return SIGNED;
}
if(input == '.'){
return DOT;
}
if(input == 'e' || input == 'E'){
return EXPON;
}
if(input == ' '){
return SPACE;
}
return BADSYMBOL;
}
// Transition Function of the DFA
STATE transit(STATE cur_state, char input){
SYMBOL cur_symbol = symbol_check(input);
if(cur_symbol == BADSYMBOL) return REJECT;
STATE state_map[11][6] = {
{REJECT, REJECT, REJECT, REJECT, REJECT, REJECT},
{REJECT, Q2, Q1, Q3, REJECT, Q0},
{REJECT, Q2, REJECT, Q3, REJECT, REJECT},
{REJECT, Q2, REJECT, Q4, Q6, Q9},
{REJECT, Q5, REJECT, REJECT, REJECT, REJECT},
{REJECT, Q5, REJECT, REJECT, Q6, Q9},
{REJECT, Q5, REJECT, REJECT, Q6, Q9},
{REJECT, Q8, Q7, REJECT, REJECT, REJECT},
{REJECT, Q8, REJECT, REJECT, REJECT, REJECT},
{REJECT, Q8, REJECT, REJECT, REJECT, Q9},
{REJECT, REJECT, REJECT, REJECT, REJECT, Q9}
};
return state_map[cur_state][cur_symbol];
}
bool validate(const string& str){
STATE cur_state = Q0;
for(int i = 0; i < str.size(); ++i){
cur_state = transit(cur_state, str[i]);
if(cur_state == REJECT) break;
}
if(cur_state == Q2 || cur_state == Q4 || cur_state == Q5 || cur_state == Q8 || cur_state == Q9){
return true;
}
return false;
}
int main(){
string str;
while(cin >> str){
cout << (validate(str) ? "Accept" : "Reject") <<endl;
}
return 0;
}
| true |
d3597927dee4225d620931dd3c9553757daba5de | C++ | fengfengcloud/Programming | /algorithm/control/kalman/include/system_model.h | UTF-8 | 1,700 | 3 | 3 | [] | no_license | #ifndef KALMAN_INCLUDE_SYSTEMMODEL_H_
#define KALMAN_INCLUDE_SYSTEMMODEL_H_
#include <type_traits>
#include "Matrix.hpp"
#include "StandardBase.hpp"
namespace Kalman {
/**
* @brief Abstract base class of all system models
*
* @param StateType The vector-type of the system state (usually some type
* derived from Kalman::Vector)
* @param ControlType The vector-type of the control input (usually some type
* derived from Kalman::Vector)
* @param CovarianceBase The class template used for covariance storage (must be
* either StandardBase or SquareRootBase)
*/
template <class StateType,
class ControlType = Vector<typename StateType::Scalar, 0>,
template <class> class CovarianceBase = StandardBase>
class SystemModel : public CovarianceBase<StateType> {
static_assert(
/*StateType::RowsAtCompileTime == Dynamic ||*/ StateType::
RowsAtCompileTime > 0,
"State vector must contain at least 1 element" /* or be dynamic */);
static_assert(
/*ControlType::RowsAtCompileTime == Dynamic ||*/ ControlType::
RowsAtCompileTime >= 0,
"Control vector must contain at least 0 elements" /* or be dynamic */);
static_assert(std::is_same<typename StateType::Scalar,
typename ControlType::Scalar>::value,
"State and Control scalar types must be identical");
public:
// 状态向量
typedef StateType State;
// 控制向量
typedef ControlType Control;
public:
// 运动方程 --》 预测下一时刻的状态
virtual State f(const State& x, const Control& u) const = 0;
protected:
SystemModel() {}
virtual ~SystemModel() {}
};
} // namespace Kalman
#endif | true |
8e1c76bb9e9e4523b145301b9bd49a9b0eec46a1 | C++ | andrewwalker-mn/Condvar | /broadcasttest.cpp | UTF-8 | 1,318 | 2.921875 | 3 | [] | no_license |
#include "uthread.h"
#include "Lock.h"
#include "CondVar.h"
#include <cassert>
#include <cstdlib>
#include <iostream>
using namespace std;
static Lock lock;
static CondVar cv;
#define UTHREAD_TIME_QUANTUM 100000000
static int count = 0;
void* waits(void * arg) {
lock.lock();
cout << count << endl;
cv.wait(lock);
cout << count << endl;
count += 1;
lock.unlock();
return nullptr;
}
void* signals(void * arg) {
lock.lock();
cout << "broadcasting" << endl;
cv.broadcast();
cout << "aaaaaaaand we're back in signals" << endl;
lock.unlock();
return nullptr;
}
int main(int argc, char*argv[]) {
int ret = uthread_init(UTHREAD_TIME_QUANTUM);
if (ret != 0) {
cerr << "Error: uthread_init" << endl;
exit(1);
}
// Create producer threads
int *wait_threads = new int[10];
for (int i = 0; i < 10; i++) {
wait_threads[i] = uthread_create(waits, nullptr);
if (wait_threads[i] < 0) {
cerr << "Error: uthread_create waits" << endl;
}
}
int signal_thread = uthread_create(signals, nullptr);
for (int i = 0; i < 10; i++) {
int result = uthread_join(wait_threads[i], nullptr);
if (result < 0) {
cerr << "Error: uthread_join waits" << endl;
}
}
uthread_join(signal_thread, nullptr);
delete[] wait_threads;
return 0;
}
| true |
c2345d2d9fe211e22986b1a30c038b680cdcb6ad | C++ | arrayExample/Cpp | /Basic_Syntax&Functions/Outputs.cpp | UTF-8 | 1,095 | 4.3125 | 4 | [] | no_license | /*
Kevin Lippincott
Output Demo
~ Instructions ~
Write a program that uses while loops to perform the following steps:
Prompt the user to input two integers: firstNum and secondNum (firstNum must be less than secondNum).
Output all odd numbers between firstNum and secondNum.
Output the sum of all even numbers between firstNum and secondNum.
Output the numbers and their squares between 1 and 10.
Output the sum of the square of the odd numbers between firstNum and secondNum.
Output all uppercase letters.
~ Input ~
~ Output ~
*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int firstNum, secondNum, oddNum, evenNum, total;
cout << "First (smaller) Number: " << endl;
cin >> firstNum;
cout << "Second (larger) Number; " << endl;
cin >> secondNum;
int value = secondNum - firstNum;
while (value > firstNum)
{
value = secondNum--;
if (value % 2 == 0)
{
evenNum = value;
}
else
{
oddNum = value;
cout << oddNum << endl;
}
}
cout << "Are those your numbers?" << endl;
return 0;
} | true |
04154e1bc704d5e22c9b48fcd2499536deb55678 | C++ | yunyan/cppPractice | /miniSTL/src/miniVector.cpp | UTF-8 | 436 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#include "miniVector.h"
using namespace miniSTL;
#if 0
template <class T>
Vector<T>::Vector()
{
vectorSize = 0;
vectorCapacity = 0;
buffer = 0;
}
template <class T>
Vector<T>::Vector(unsigned int size)
{
vectorSize = size;
vectorCapacity = size;
buffer = new T*[size];
}
template <class T>
Vector<T>::~Vector()
{
if(buffer){
delete[] buffer;
}
}
#endif
| true |
5535f5a4861bebc37fe2ad9fc7d023c95f5db2c1 | C++ | SloanKi/FieaGameEngine | /source/UnitTestLibrary.Desktop/DatumTest.cpp | UTF-8 | 80,903 | 2.609375 | 3 | [] | no_license | #include "pch.h"
#include "CppUnitTest.h"
#include "Datum.h"
#include "Foo.h"
#include "Scope.h"
#pragma warning(push)
#pragma warning(disable:4201)
#include <glm/gtx/string_cast.hpp>
#pragma warning(pop)
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Library;
using namespace UnitTests;
using namespace std;
using namespace std::string_literals;
namespace Microsoft::VisualStudio::CppUnitTestFramework
{
template<>
inline std::wstring ToString<Library::DatumType>(const Library::DatumType& t)
{
RETURN_WIDE_STRING(&t);
}
template<>
inline std::wstring ToString<glm::vec4>(const glm::vec4& t)
{
RETURN_WIDE_STRING(&t);
}
template<>
inline std::wstring ToString<glm::mat4>(const glm::mat4& t)
{
RETURN_WIDE_STRING(&t);
}
template<>
inline std::wstring ToString<Library::RTTI>(Library::RTTI* t)
{
RETURN_WIDE_STRING(t);
}
template<>
inline std::wstring ToString<Library::Datum>(const Library::Datum& t)
{
RETURN_WIDE_STRING(&t);
}
template<>
inline std::wstring ToString<Library::Scope>(const Library::Scope& t)
{
RETURN_WIDE_STRING(&t);
}
template<>
inline std::wstring ToString<Library::Scope>(const Library::Scope* t)
{
RETURN_WIDE_STRING(t);
}
template<>
inline std::wstring ToString<Library::Scope>(Library::Scope* t)
{
RETURN_WIDE_STRING(t);
}
}
namespace UnitTestLibraryDesktop
{
TEST_CLASS(DatumTests)
{
public:
//check for memory leaks
TEST_METHOD_INITIALIZE(Initialize)
{
#if defined(DEBUG) || defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF);
_CrtMemCheckpoint(&sStartMemState);
#endif
}
//check for memory leaks
TEST_METHOD_CLEANUP(Cleanup)
{
#if defined(DEBUG) || defined(_DEBUG)
_CrtMemState endMemState, diffMemState;
_CrtMemCheckpoint(&endMemState);
if (_CrtMemDifference(&diffMemState, &sStartMemState, &endMemState))
{
_CrtMemDumpStatistics(&diffMemState);
Assert::Fail(L"Memory Leaks!");
}
#endif
}
TEST_METHOD(Constructor)
{
Datum datum(DatumType::Matrix);
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Type(), DatumType::Matrix);
Datum datum2(DatumType::Integer, 5);
Assert::AreEqual(datum2.Size(), 0_z);
Assert::AreEqual(datum2.Capacity(), 5_z);
Assert::AreEqual(datum2.Type(), DatumType::Integer);
}
TEST_METHOD(TypeSizeCapacity)
{
Datum datum;
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Type(), DatumType::Unknown);
Assert::IsTrue(datum.IsEmpty());
}
TEST_METHOD(SetType)
{
Datum datum;
Assert::AreEqual(datum.Type(), DatumType::Unknown);
//test 1: setting to unknown (valid but means this datum still isn't assigned a type)
datum.SetType(DatumType::Unknown);
Assert::AreEqual(datum.Type(), DatumType::Unknown);
//test 2: set type on datum without type
datum.SetType(DatumType::Float);
Assert::AreEqual(datum.Type(), DatumType::Float);
//test 3: set type on datum already assigned a type (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.SetType(DatumType::Integer); });
}
TEST_METHOD(Resize)
{
//test 1: datum without type (throw exception)
Datum invDatum;
Assert::ExpectException<std::runtime_error>([&invDatum] { invDatum.Resize(5); });
//Integer Datum Tests
{
//test 2: grow without default construct
Datum datum(DatumType::Integer);
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: grow with default construct
datum.Resize(3, true);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<int>(0), 0);
Assert::AreEqual(datum.Get<int>(1), 0);
Assert::AreEqual(datum.Get<int>(2), 0);
//test 4: shrink
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Get<int>(0), 0);
Assert::AreEqual(datum.Get<int>(1), 0);
//test 5: capacity = 0
datum.Resize(0);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//Float Datum Tests
{
//test 2: grow without default construct
Datum datum(DatumType::Float);
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: grow with default construct
datum.Resize(3, true);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<float>(0), 0.0f);
Assert::AreEqual(datum.Get<float>(1), 0.0f);
Assert::AreEqual(datum.Get<float>(2), 0.0f);
//test 4: shrink
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Get<float>(0), 0.0f);
Assert::AreEqual(datum.Get<float>(1), 0.0f);
//test 5: capacity = 0
datum.Resize(0);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//Vector Datum Tests
{
//test 2: grow without default construct
Datum datum(DatumType::Vector);
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: grow with default construct
datum.Resize(3, true);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<glm::vec4>(0), glm::vec4(0.0f));
Assert::AreEqual(datum.Get<glm::vec4>(1), glm::vec4(0.0f));
Assert::AreEqual(datum.Get<glm::vec4>(2), glm::vec4(0.0f));
//test 4: shrink
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Get<glm::vec4>(0), glm::vec4(0.0f));
Assert::AreEqual(datum.Get<glm::vec4>(1), glm::vec4(0.0f));
//test 5: capacity = 0
datum.Resize(0);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//Matrix Datum Tests
{
//test 2: grow without default construct
Datum datum(DatumType::Matrix);
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: grow with default construct
datum.Resize(3, true);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<glm::mat4>(0), glm::mat4(0.0f));
Assert::AreEqual(datum.Get<glm::mat4>(1), glm::mat4(0.0f));
Assert::AreEqual(datum.Get<glm::mat4>(2), glm::mat4(0.0f));
//test 4: shrink
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Get<glm::mat4>(0), glm::mat4(0.0f));
Assert::AreEqual(datum.Get<glm::mat4>(1), glm::mat4(0.0f));
//test 5: capacity = 0
datum.Resize(0);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//String Datum Tests
{
//test 2: grow without default construct
Datum datum(DatumType::String);
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: grow with default construct
datum.Resize(3, true);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<std::string>(0), std::string());
Assert::AreEqual(datum.Get<std::string>(1), std::string());
Assert::AreEqual(datum.Get<std::string>(2), std::string());
//test 4: shrink
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Get<std::string>(0), std::string());
Assert::AreEqual(datum.Get<std::string>(1), std::string());
//test 5: capacity = 0
datum.Resize(0);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//RTTI* Datum Tests
{
//test 2: grow without default construct
Datum datum(DatumType::Pointer);
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: grow with default construct
datum.Resize(3, true);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
//RTTI* test = datum.Get<RTTI*>();
//test;
Assert::AreEqual(datum.Get<RTTI*>(0), reinterpret_cast<RTTI*>(NULL));
Assert::AreEqual(datum.Get<RTTI*>(1), reinterpret_cast<RTTI*>(NULL));
Assert::AreEqual(datum.Get<RTTI*>(2), reinterpret_cast<RTTI*>(NULL));
//test 4: shrink
datum.Resize(2);
Assert::AreEqual(datum.Capacity(), 2_z);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Get<RTTI*>(0), reinterpret_cast<RTTI*>(NULL));
Assert::AreEqual(datum.Get<RTTI*>(1), reinterpret_cast<RTTI*>(NULL));
//test 5: capacity = 0
datum.Resize(0);
Assert::AreEqual(datum.Capacity(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//test 6: external (throw exception)
Datum extDatum;
int test1(5), test2(10), test3(15);
int arr[3] = { test1, test2, test3 };
extDatum.SetStorage(arr, 3);
Assert::ExpectException<std::runtime_error>([&extDatum, &arr] {extDatum.Resize(5); });
//test 7: resize on scope* with default construct (throw exception
{
Datum datum(DatumType::Table);
Assert::ExpectException<std::runtime_error>([&datum] {datum.Resize(5, true); });
}
}
TEST_METHOD(Reserve)
{
//test 1: datum without type (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum] { datum.Reserve(5); });
//test 2: valid reserve
datum.SetType(DatumType::Float);
datum.Reserve(5);
Assert::AreEqual(datum.Capacity(), 5_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 3: try to shrink (nothing happens)
datum.Reserve(1);
Assert::AreEqual(datum.Capacity(), 5_z);
Assert::AreEqual(datum.Size(), 0_z);
//test 4: external (throw exception)
Datum extDatum;
int test1(5), test2(10), test3(15);
int arr[3] = { test1, test2, test3 };
extDatum.SetStorage(arr, 3);
Assert::ExpectException<std::runtime_error>([&extDatum, &arr] {extDatum.Resize(5); });
}
TEST_METHOD(Clear)
{
//int datum
{
Datum datum(DatumType::Integer);
datum.Resize(5, true); //default construct items
Assert::AreEqual(datum.Size(), 5_z);
Assert::AreEqual(datum.Size(), 5_z);
datum.Clear();
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//float datum
{
Datum datum(DatumType::Float);
datum.Resize(5, true); //default construct items
Assert::AreEqual(datum.Size(), 5_z);
Assert::AreEqual(datum.Size(), 5_z);
datum.Clear();
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//vector datum
{
Datum datum(DatumType::Vector);
datum.Resize(5, true); //default construct items
Assert::AreEqual(datum.Size(), 5_z);
Assert::AreEqual(datum.Size(), 5_z);
datum.Clear();
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//matrix datum
{
Datum datum(DatumType::Matrix);
datum.Resize(5, true); //default construct items
Assert::AreEqual(datum.Size(), 5_z);
Assert::AreEqual(datum.Size(), 5_z);
datum.Clear();
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//string datum
{
Datum datum(DatumType::String);
datum.Resize(5, true); //default construct items
Assert::AreEqual(datum.Size(), 5_z);
Assert::AreEqual(datum.Size(), 5_z);
datum.Clear();
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
// pointer datum
{
Datum datum(DatumType::Pointer);
datum.Resize(5, true); //default construct items
Assert::AreEqual(datum.Size(), 5_z);
Assert::AreEqual(datum.Size(), 5_z);
datum.Clear();
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Size(), 0_z);
}
//test external (throw exception)
Datum extDatum;
int test1(5), test2(10), test3(15);
int arr[3] = { test1, test2, test3 };
extDatum.SetStorage(arr, 3);
Assert::ExpectException<std::runtime_error>([&extDatum, &arr] {extDatum.Resize(5); });
}
TEST_METHOD(Copy)
{
//int datum tests
{
int test1(5), test2(10), test3(20);
int arr[3] = { test1, test2, test3 };
//test 1: copy datum with internal memory
Datum datum1;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
Datum datum2(datum1);
Assert::AreEqual(datum2, datum1);
//test 2: datum with external memory
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(datum3);
Assert::AreEqual(datum3, datum4);
}
//float datum tests
{
float test1(5), test2(10), test3(20);
float arr[3] = { test1, test2, test3 };
//test 1: copy datum with internal memory
Datum datum1;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
Datum datum2(datum1);
Assert::AreEqual(datum2, datum1);
//test 2: datum with external memory
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(datum3);
Assert::AreEqual(datum3, datum4);
}
//vector datum tests
{
glm::vec4 test1(5), test2(10), test3(20);
glm::vec4 arr[3] = { test1, test2, test3 };
//test 1: copy datum with internal memory
Datum datum1;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
Datum datum2(datum1);
Assert::AreEqual(datum2, datum1);
//test 2: datum with external memory
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(datum3);
Assert::AreEqual(datum3, datum4);
}
//matrix datum tests
{
glm::mat4 test1(5), test2(10), test3(20);
glm::mat4 arr[3] = { test1, test2, test3 };
//test 1: copy datum with internal memory
Datum datum1;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
Datum datum2(datum1);
Assert::AreEqual(datum2, datum1);
//test 2: datum with external memory
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(datum3);
Assert::AreEqual(datum3, datum4);
}
//string datum tests
{
std::string test1("hello"), test2("Goodbye"), test3("ugh");
std::string arr[3] = { test1, test2, test3 };
//test 1: copy datum with internal memory
Datum datum1;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
Datum datum2(datum1);
Assert::AreEqual(datum2, datum1);
//test 2: datum with external memory
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(datum3);
Assert::AreEqual(datum3, datum4);
}
//RTTI datum tests
{
Foo test1(5), test2(10), test3(20);
RTTI* arr[3] = { &test1, &test2, &test3 };
//test 1: copy datum with internal memory
Datum datum1;
datum1.PushBack(&test1);
datum1.PushBack(&test2);
datum1.PushBack(&test3);
Datum datum2(datum1);
Assert::AreEqual(datum2, datum1);
//test 2: datum with external memory
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(datum3);
Assert::AreEqual(datum3, datum4);
}
//test 3: copy a default constructed datum (sanity check)
Datum datum5;
Datum datum6(datum5);
Assert::AreEqual(datum5, datum6);
}
TEST_METHOD(MoveSemantics)
{
std::string test1("Hello"), test2("Goodbye"), test3("ugh");
std::string arr[3] = { test1, test2, test3 };
std::string arr2[4] = { test3, test2, test1, test1 };
//test 1: rhs has internal memory (constructor)
Datum datum1;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
Datum datum2(std::move(datum1));
Assert::AreEqual(datum2.Size(), 3_z);
Assert::AreEqual(datum2.Get<std::string>(), test1);
Assert::AreEqual(datum1.Size(), 0_z); //make sure datum1 was invalidated
//test 2: rhs has external memory (constructor)
Datum datum3;
datum3.SetStorage(arr, 3);
Datum datum4(std::move(datum3));
Assert::AreEqual(datum4.Size(), 3_z);
Assert::AreEqual(datum4.Get<std::string>(), test1);
Assert::AreEqual(datum3.Size(), 0_z); //make sure datum1 was invalidated
//test 3: lhs has internal (assign)
Datum datum2Cpy = datum2; //internal
Datum datum4Cpy = datum4; //external
datum2Cpy = std::move(datum4);
Assert::AreEqual(datum2Cpy.Size(), 3_z);
Assert::AreEqual(datum2Cpy.Get<std::string>(), test1);
Assert::AreEqual(datum4.Size(), 0_z); //make sure datum1 was invalidated
//test 4: lhs has external (assign)
datum4Cpy = std::move(datum2);
Assert::AreEqual(datum4Cpy.Size(), 3_z);
Assert::AreEqual(datum4Cpy.Get<std::string>(), test1);
Assert::AreEqual(datum2.Size(), 0_z); //make sure datum1 was invalidated
}
TEST_METHOD(AssignmentDatum)
{
//int datum tests
{
int test1(5), test2(10), test3(20);
int arr[3] = { test1, test2, test3 };
int arr2[4] = { test3, test2, test1, test1 };
//test 1: default constructed datum = datum with internal memory
Datum datum1, datum2;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2 = datum1;
Assert::AreEqual(datum2, datum1);
//test 2: lhs internal rhs internal
Datum emptyDatum;
datum1 = emptyDatum;
Assert::AreEqual(datum1, emptyDatum);
//test 3: lhs internal rhs external
Datum datum3;
datum3.SetStorage(arr, 3);
datum1 = datum2; //give datum1 internal memory to make sure it doesn't leak
datum1 = datum3;
Assert::AreEqual(datum1, datum3);
//test 4: lhs external rhs internal
datum1 = datum2;
Assert::AreEqual(datum1, datum2);
//test 5: lhs external rhs external
Datum datum4;
datum4.SetStorage(arr, 4);
datum3 = datum4;
Assert::AreEqual(datum3, datum4);
//test 6: for sanity, lhs external rhs default constructed
datum4 = emptyDatum;
Assert::AreEqual(datum4, emptyDatum);
}
//float datum tests
{
float test1(5), test2(10), test3(20);
float arr[3] = { test1, test2, test3 };
float arr2[4] = { test3, test2, test1, test1 };
//test 1: default constructed datum = datum with internal memory
Datum datum1, datum2;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2 = datum1;
Assert::AreEqual(datum2, datum1);
//test 2: lhs internal rhs internal
Datum emptyDatum;
datum1 = emptyDatum;
Assert::AreEqual(datum1, emptyDatum);
//test 3: lhs internal rhs external
Datum datum3;
datum3.SetStorage(arr, 3);
datum1 = datum2; //give datum1 internal memory to make sure it doesn't leak
datum1 = datum3;
Assert::AreEqual(datum1, datum3);
//test 4: lhs external rhs internal
datum1 = datum2;
Assert::AreEqual(datum1, datum2);
//test 5: lhs external rhs external
Datum datum4;
datum4.SetStorage(arr, 4);
datum3 = datum4;
Assert::AreEqual(datum3, datum4);
//test 6: for sanity, lhs external rhs default constructed
datum4 = emptyDatum;
Assert::AreEqual(datum4, emptyDatum);
}
//vector datum tests
{
glm::vec4 test1(5), test2(10), test3(20);
glm::vec4 arr[3] = { test1, test2, test3 };
glm::vec4 arr2[4] = { test3, test2, test1, test1 };
//test 1: default constructed datum = datum with internal memory
Datum datum1, datum2;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2 = datum1;
Assert::AreEqual(datum2, datum1);
//test 2: lhs internal rhs internal
Datum emptyDatum;
datum1 = emptyDatum;
Assert::AreEqual(datum1, emptyDatum);
//test 3: lhs internal rhs external
Datum datum3;
datum3.SetStorage(arr, 3);
datum1 = datum2; //give datum1 internal memory to make sure it doesn't leak
datum1 = datum3;
Assert::AreEqual(datum1, datum3);
//test 4: lhs external rhs internal
datum1 = datum2;
Assert::AreEqual(datum1, datum2);
//test 5: lhs external rhs external
Datum datum4;
datum4.SetStorage(arr, 4);
datum3 = datum4;
Assert::AreEqual(datum3, datum4);
//test 6: for sanity, lhs external rhs default constructed
datum4 = emptyDatum;
Assert::AreEqual(datum4, emptyDatum);
}
//Matrix datum tests
{
glm::mat4 test1(5), test2(10), test3(20);
glm::mat4 arr[3] = { test1, test2, test3 };
glm::mat4 arr2[4] = { test3, test2, test1, test1 };
//test 1: default constructed datum = datum with internal memory
Datum datum1, datum2;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2 = datum1;
Assert::AreEqual(datum2, datum1);
//test 2: lhs internal rhs internal
Datum emptyDatum;
datum1 = emptyDatum;
Assert::AreEqual(datum1, emptyDatum);
//test 3: lhs internal rhs external
Datum datum3;
datum3.SetStorage(arr, 3);
datum1 = datum2; //give datum1 internal memory to make sure it doesn't leak
datum1 = datum3;
Assert::AreEqual(datum1, datum3);
//test 4: lhs external rhs internal
datum1 = datum2;
Assert::AreEqual(datum1, datum2);
//test 5: lhs external rhs external
Datum datum4;
datum4.SetStorage(arr, 4);
datum3 = datum4;
Assert::AreEqual(datum3, datum4);
//test 6: for sanity, lhs external rhs default constructed
datum4 = emptyDatum;
Assert::AreEqual(datum4, emptyDatum);
}
//string datum tests
{
std::string test1("Hello"), test2("Goodbye"), test3("ugh");
std::string arr[3] = { test1, test2, test3 };
std::string arr2[4] = { test3, test2, test1, test1 };
//test 1: default constructed datum = datum with internal memory
Datum datum1, datum2;
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2 = datum1;
Assert::AreEqual(datum2, datum1);
//test 2: lhs internal rhs internal
Datum emptyDatum;
datum1 = emptyDatum;
Assert::AreEqual(datum1, emptyDatum);
//test 3: lhs internal rhs external
Datum datum3;
datum3.SetStorage(arr, 3);
datum1 = datum2; //give datum1 internal memory to make sure it doesn't leak
datum1 = datum3;
Assert::AreEqual(datum1, datum3);
//test 4: lhs external rhs internal
datum1 = datum2;
Assert::AreEqual(datum1, datum2);
//test 5: lhs external rhs external
Datum datum4;
datum4.SetStorage(arr, 4);
datum3 = datum4;
Assert::AreEqual(datum3, datum4);
//test 6: for sanity, lhs external rhs default constructed
datum4 = emptyDatum;
Assert::AreEqual(datum4, emptyDatum);
}
//pointer datum tests
{
Foo test1(5), test2(10), test3(20);
RTTI* arr[3] = { &test1, &test2, &test3 };
RTTI* arr2[4] = { &test3, &test2, &test1, &test1 };
//test 1: default constructed datum = datum with internal memory
Datum datum1, datum2;
datum1.PushBack(&test1);
datum1.PushBack(&test2);
datum1.PushBack(&test3);
datum2 = datum1;
Assert::AreEqual(datum2, datum1);
//test 2: lhs internal rhs internal
Datum emptyDatum;
datum1 = emptyDatum;
Assert::AreEqual(datum1, emptyDatum);
//test 3: lhs internal rhs external
Datum datum3;
datum3.SetStorage(arr, 3);
datum1 = datum2; //give datum1 internal memory to make sure it doesn't leak
datum1 = datum3;
Assert::AreEqual(datum1, datum3);
//test 4: lhs external rhs internal
datum1 = datum2;
Assert::AreEqual(datum1, datum2);
//test 5: lhs external rhs external
Datum datum4;
datum4.SetStorage(arr, 4);
datum3 = datum4;
Assert::AreEqual(datum3, datum4);
//test 6: for sanity, lhs external rhs default constructed
datum4 = emptyDatum;
Assert::AreEqual(datum4, emptyDatum);
}
}
TEST_METHOD(AssignmentInt)
{
//test 1: undefined datum
Datum datum;
datum = 5;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<int>(), 5);
Assert::AreEqual(datum.Type(), DatumType::Integer);
//test 2: overwrite datum with 1 element
datum = 22;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<int>(), 22);
/*//test 3: overwrite datum with many elements
datum.Resize(5, true);
datum = 1;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<int>(), 1);*/
//test 4: datum with wrong type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum] { floatDatum = 5; });
}
TEST_METHOD(AssignmentFloat)
{
//test 1: undefined datum
Datum datum;
datum = 5.0f;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<float>(), 5.0f);
Assert::AreEqual(datum.Type(), DatumType::Float);
//test 2: overwrite datum with 1 element
datum = 22.0f;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<float>(), 22.0f);
//test 3: overwrite datum with many elements
/*datum.Resize(5, true);
datum = 1.0f;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<float>(), 1.0f);*/
//test 4: datum with wrong type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum = 5.0f; });
}
TEST_METHOD(AssignmentVector)
{
//test 1: undefined datum
Datum datum;
glm::vec4 testVector(1.0);
datum = testVector;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::vec4>(), testVector);
Assert::AreEqual(datum.Type(), DatumType::Vector);
//test 2: overwrite datum with 1 element
glm::vec4 testVector2(3.0);
datum = testVector2;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::vec4>(), testVector2);
//test 3: overwrite datum with many elements
/*datum.Resize(5, true);
datum = testVector;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::vec4>(), testVector);*/
//test 4: datum with wrong type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &testVector] { intDatum = testVector; });
}
TEST_METHOD(AssignmentMatrix)
{
//test 1: undefined datum
Datum datum;
glm::mat4 testMatrix(1.0);
datum = testMatrix;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::mat4>(), testMatrix);
Assert::AreEqual(datum.Type(), DatumType::Matrix);
//test 2: overwrite datum with 1 element
glm::mat4 testMatrix2(3.0);
datum = testMatrix2;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::mat4>(), testMatrix2);
//test 3: overwrite datum with many elements
/*datum.Resize(5, true);
datum = testMatrix;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::mat4>(), testMatrix);*/
//test 4: datum with wrong type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &testMatrix] { intDatum = testMatrix; });
}
TEST_METHOD(AssignmentString)
{
//test 1: undefined datum
Datum datum;
std::string testString = "Hello"s;
datum = testString;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<std::string>(), testString);
Assert::AreEqual(datum.Type(), DatumType::String);
//test 2: overwrite datum with 1 element
std::string testString2 = "Goodbye"s;
datum = testString2;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<std::string>(), testString2);
//test 3: overwrite datum with many elements
/*datum.Resize(5, true);
datum = testString;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<std::string>(), testString);*/
//test 4: datum with wrong type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &testString] { intDatum = testString; });
}
TEST_METHOD(AssignmentPointer)
{
//test 1: undefined datum
Datum datum;
Foo foo(5);
RTTI* testPointer = &foo;
datum = &foo;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<RTTI*>(), testPointer);
Assert::AreEqual(datum.Type(), DatumType::Pointer);
//test 2: overwrite datum with 1 element
Foo foo2(10);
RTTI* testPointer2 = &foo2;
datum = testPointer2;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<RTTI*>(), testPointer2);
//test 3: overwrite datum with many elements
/*datum.Resize(5, true);
datum = testPointer;
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<RTTI*>(), testPointer);*/
//test 4: datum with wrong type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &testPointer] { intDatum = testPointer; });
}
TEST_METHOD(Equality)
{
//test 1: two default constructed datums (equal)
{
Datum datum1, datum2;
Assert::AreEqual(datum1, datum2);
}
//test 2: mData's are equal (aliases)
//test 3: different types (not equal)
{
Datum datum1(DatumType::Float), datum2(DatumType::Integer);
Assert::IsTrue(datum1 != datum2);
}
//test 4: same type, different capacity (not equal)
{
Datum datum1(DatumType::Integer), datum2(DatumType::Integer, 5);
Assert::IsTrue(datum1 != datum2);
}
//test 5: same type, same capacity, different size (not equal)
{
Datum datum1(DatumType::Integer, 5), datum2(DatumType::Integer, 5);
datum1.PushBack(5);
Assert::IsTrue(datum1 != datum2);
}
//test 6: datums with same type, capacity, size, contents (equal)
//6.1: int datums
{
int test1(5), test2(10), test3(20), test4(15);
Datum datum1(DatumType::Integer, 5), datum2(DatumType::Integer, 5);
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2.PushBack(test1);
datum2.PushBack(test2);
datum2.PushBack(test3);
Assert::AreEqual(datum1, datum2);
//7.1 same type, capacity, size but different contents
datum2.PopBack();
datum2.PushBack(test4);
Assert::IsTrue(datum1 != datum2);
}
//6.2: float datums
{
float test1(5), test2(10), test3(20), test4(15);
Datum datum1(DatumType::Float, 5), datum2(DatumType::Float, 5);
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2.PushBack(test1);
datum2.PushBack(test2);
datum2.PushBack(test3);
Assert::AreEqual(datum1, datum2);
//7.2 same type, capacity, size but different contents
datum2.PopBack();
datum2.PushBack(test4);
Assert::IsTrue(datum1 != datum2);
}
//6.3 vector datums
{
glm::vec4 test1(5), test2(10), test3(20), test4(15);
Datum datum1(DatumType::Vector, 5), datum2(DatumType::Vector, 5);
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2.PushBack(test1);
datum2.PushBack(test2);
datum2.PushBack(test3);
Assert::AreEqual(datum1, datum2);
//7.3 same type, capacity, size but different contents
datum2.PopBack();
datum2.PushBack(test4);
Assert::IsTrue(datum1 != datum2);
}
//6.4: matrix datums
{
glm::mat4 test1(5), test2(10), test3(20), test4(15);
Datum datum1(DatumType::Matrix, 5), datum2(DatumType::Matrix, 5);
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2.PushBack(test1);
datum2.PushBack(test2);
datum2.PushBack(test3);
Assert::AreEqual(datum1, datum2);
//7.4 same type, capacity, size but different contents
datum2.PopBack();
datum2.PushBack(test4);
Assert::IsTrue(datum1 != datum2);
}
//6.5: string datums
{
std::string test1("Hello"), test2("Goodbye"), test3("ugh"), test4("blegh");
Datum datum1(DatumType::String, 5), datum2(DatumType::String, 5);
datum1.PushBack(test1);
datum1.PushBack(test2);
datum1.PushBack(test3);
datum2.PushBack(test1);
datum2.PushBack(test2);
datum2.PushBack(test3);
Assert::AreEqual(datum1, datum2);
//7.5 same type, capacity, size but different contents
datum2.PopBack();
datum2.PushBack(test4);
Assert::IsTrue(datum1 != datum2);
}
//6.6: pointer datums
{
Foo test1(5), test2(10), test3(20), test4(15);
Datum datum1(DatumType::Pointer, 5), datum2(DatumType::Pointer, 5);
datum1.PushBack(&test1);
datum1.PushBack(&test2);
datum1.PushBack(&test3);
datum2.PushBack(&test1);
datum2.PushBack(&test2);
datum2.PushBack(&test3);
Assert::AreEqual(datum1, datum2);
//7.6 same type, capacity, size but different contents
datum2.PopBack();
datum2.PushBack(&test4);
Assert::IsTrue(datum1 != datum2);
}
}
TEST_METHOD(EqualityInt)
{
//test 1: are equal
Datum datum;
datum.PushBack(5);
Assert::IsTrue(datum == 5);
//test 2: datum not scalar (not equal)
datum.PushBack(10);
Assert::IsTrue(datum != 5);
//test 3: datum with wrong type (not equal)
Datum datum2(DatumType::Float);
Assert::IsTrue(datum != 5);
}
TEST_METHOD(EqualityFloat)
{
//test 1: are equal
Datum datum;
datum.PushBack(5.0f);
Assert::IsTrue(datum == 5.0f);
//test 2: datum not scalar (not equal)
datum.PushBack(10.0f);
Assert::IsTrue(datum != 5.0f);
//test 3: datum with wrong type (not equal)
Datum datum2(DatumType::Integer);
Assert::IsTrue(datum != 5.0f);
}
TEST_METHOD(EqualityVector)
{
glm::vec4 test1(1), test2(2);
//test 1: are equal
Datum datum;
datum.PushBack(test1);
Assert::IsTrue(datum == test1);
//test 2: datum not scalar (not equal)
datum.PushBack(test2);
Assert::IsTrue(datum != test1);
//test 3: datum with wrong type (not equal)
Datum datum2(DatumType::Integer);
Assert::IsTrue(datum != test1);
}
TEST_METHOD(EqualityMatrix)
{
glm::mat4 test1(1), test2(2);
//test 1: are equal
Datum datum;
datum.PushBack(test1);
Assert::IsTrue(datum == test1);
//test 2: datum not scalar (not equal)
datum.PushBack(test2);
Assert::IsTrue(datum != test1);
//test 3: datum with wrong type (not equal)
Datum datum2(DatumType::Integer);
Assert::IsTrue(datum != test1);
}
TEST_METHOD(EqualityString)
{
std::string test1("Hello"), test2("Goodbye");
//test 1: are equal
Datum datum;
datum.PushBack(test1);
Assert::IsTrue(datum == test1);
//test 2: datum not scalar (not equal)
datum.PushBack(test2);
Assert::IsTrue(datum != test1);
//test 3: datum with wrong type (not equal)
Datum datum2(DatumType::Integer);
Assert::IsTrue(datum != test1);
}
TEST_METHOD(EqualityPointer)
{
Foo test1(1), test2(2);
//test 1: are equal
Datum datum;
datum.PushBack(&test1);
Assert::IsTrue(datum == &test1);
//test 2: datum not scalar (not equal)
datum.PushBack(&test2);
Assert::IsTrue(datum != &test1);
//test 3: datum with wrong type (not equal)
Datum datum2(DatumType::Integer);
Assert::IsTrue(datum != &test1);
}
TEST_METHOD(GetInt)
{
//test 1: valid get
Datum datum;
datum = 5;
Assert::AreEqual(datum.Get<int>(), 5);
//test 2: out of bounds (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.Get<int>(1); });
//test 3: invalid type (throw exception)
Datum floatDatum;
floatDatum.SetType(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum] { floatDatum.Get<int>(); });
//test 4: const
const Datum* constDat = &datum;
Assert::AreEqual(constDat->Get<int>(), 5);
}
TEST_METHOD(GetFloat)
{
//test 1: valid get
Datum datum;
datum = 5.0f;
Assert::AreEqual(datum.Get<float>(), 5.0f);
//test 2: out of bounds (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.Get<float>(1); });
//test 3: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Get<float>(); });
//test 4: const
const Datum* constDat = &datum;
Assert::AreEqual(constDat->Get<float>(), 5.0f);
}
TEST_METHOD(GetVector)
{
//test 1: valid get
Datum datum;
glm::vec4 testVector(1.0);
datum = testVector;
Assert::AreEqual(datum.Get<glm::vec4>(), testVector);
//test 2: out of bounds (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.Get<glm::vec4>(1); });
//test 3: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Get<glm::vec4>(); });
//test 4: const
const Datum* constDat = &datum;
Assert::AreEqual(constDat->Get<glm::vec4>(), testVector);
}
TEST_METHOD(GetMatrix)
{
//test 1: valid get
Datum datum;
glm::mat4 testMatrix(1.0);
datum = testMatrix;
Assert::AreEqual(datum.Get<glm::mat4>(), testMatrix);
//test 2: out of bounds (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.Get<glm::mat4>(1); });
//test 3: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Get<glm::mat4>(); });
//test 4: const
const Datum* constDat = &datum;
Assert::AreEqual(constDat->Get<glm::mat4>(), testMatrix);
}
TEST_METHOD(GetString)
{
//test 1: valid get
Datum datum;
std::string testString = "Hello"s;
datum = testString;
Assert::AreEqual(datum.Get<std::string>(), testString);
//test 2: out of bounds (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.Get<std::string>(1); });
//test 3: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Get<std::string>(); });
//test 4: const
const Datum* constDat = &datum;
Assert::AreEqual(constDat->Get<std::string>(), testString);
}
TEST_METHOD(GetPointer)
{
//test 1: valid get
Datum datum;
Foo foo(5);
RTTI* rttiPtr = &foo;
datum = &foo;
Assert::AreEqual(datum.Get<RTTI*>(), rttiPtr);
//test 2: out of bounds (throw exception)
Assert::ExpectException<std::runtime_error>([&datum] { datum.Get<RTTI*>(1); });
//test 3: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Get<RTTI*>(); });
//test 4: const
const Datum* constDat = &datum;
Assert::AreEqual(constDat->Get<RTTI*>(), rttiPtr);
}
TEST_METHOD(SetInt)
{
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum] { datum.Set(5); });
//test 2: out of bounds (throw exception)
datum.SetType(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&datum] { datum.Set(5); });
datum.Resize(3, true);
Assert::ExpectException<std::runtime_error>([&datum] { datum.Set(5, 3); });
//test 3: valid sets
datum.Set(1);
datum.Set(2, 1);
datum.Set(3, 2);
Assert::AreEqual(datum.Get<int>(0), 1);
Assert::AreEqual(datum.Get<int>(1), 2);
Assert::AreEqual(datum.Get<int>(2), 3);
datum.Set(5);
Assert::AreEqual(datum.Get<int>(0), 5);
//test 4: datum with invalid type
Datum floatDatum;
floatDatum = 5.0f;
Assert::ExpectException<std::runtime_error>([&floatDatum] { floatDatum.Set(5); });
}
TEST_METHOD(SetFloat)
{
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum] { datum.Set(5.0f); });
//test 2: out of bounds (throw exception)
datum.SetType(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&datum] { datum.Set(5.0f); });
datum.Resize(3, true);
Assert::ExpectException<std::runtime_error>([&datum] { datum.Set(5.0f, 3); });
//test 3: valid sets
datum.Set(1.0f);
datum.Set(2.0f, 1);
datum.Set(3.0f, 2);
Assert::AreEqual(datum.Get<float>(0), 1.0f);
Assert::AreEqual(datum.Get<float>(1), 2.0f);
Assert::AreEqual(datum.Get<float>(2), 3.0f);
datum.Set(5.0f);
Assert::AreEqual(datum.Get<float>(0), 5.0f);
//test 4: datum with invalid type
Datum intDatum;
intDatum = 5;
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Set(5.0f); });
}
TEST_METHOD(SetVector)
{
glm::vec4 test1(1), test2(2), test3(3);
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1); });
//test 2: out of bounds (throw exception)
datum.SetType(DatumType::Vector);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1); });
datum.Resize(3, true);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1, 3); });
//test 3: valid sets
datum.Set(test1);
datum.Set(test2, 1);
datum.Set(test3, 2);
Assert::AreEqual(datum.Get<glm::vec4>(0), test1);
Assert::AreEqual(datum.Get<glm::vec4>(1), test2);
Assert::AreEqual(datum.Get<glm::vec4>(2), test3);
datum.Set(test3);
Assert::AreEqual(datum.Get<glm::vec4>(0), test3);
//test 4: datum with invalid type
Datum floatDatum;
floatDatum = 5.0f;
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.Set(test1); });
}
TEST_METHOD(SetMatrix)
{
glm::mat4 test1(1), test2(2), test3(3);
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1); });
//test 2: out of bounds (throw exception)
datum.SetType(DatumType::Matrix);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1); });
datum.Resize(3, true);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1, 3); });
//test 3: valid sets
datum.Set(test1);
datum.Set(test2, 1);
datum.Set(test3, 2);
Assert::AreEqual(datum.Get<glm::mat4>(0), test1);
Assert::AreEqual(datum.Get<glm::mat4>(1), test2);
Assert::AreEqual(datum.Get<glm::mat4>(2), test3);
datum.Set(test3);
Assert::AreEqual(datum.Get<glm::mat4>(0), test3);
//test 4: datum with invalid type
Datum floatDatum;
floatDatum = 5.0f;
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.Set(test1); });
}
TEST_METHOD(SetString)
{
std::string test1("Hello"), test2("Goodbye"), test3("Ugh");
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1); });
//test 2: out of bounds (throw exception)
datum.SetType(DatumType::String);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1); });
datum.Resize(3, true);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(test1, 3); });
//test 3: valid sets
datum.Set(test1);
datum.Set(test2, 1);
datum.Set(test3, 2);
Assert::AreEqual(datum.Get<std::string>(0), test1);
Assert::AreEqual(datum.Get<std::string>(1), test2);
Assert::AreEqual(datum.Get<std::string>(2), test3);
datum.Set(test3);
Assert::AreEqual(datum.Get<std::string>(0), test3);
//test 4: datum with invalid type
Datum floatDatum;
floatDatum = 5.0f;
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.Set(test1); });
}
TEST_METHOD(SetPointer)
{
Foo test1(1), test2(2), test3(3);
RTTI* rttiPtr1 = &test1;
RTTI* rttiPtr2 = &test2;
RTTI* rttiPtr3 = &test3;
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(&test1); });
//test 2: out of bounds (throw exception)
datum.SetType(DatumType::Pointer);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(&test1); });
datum.Resize(3, true);
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Set(&test1, 3); });
//test 3: valid sets
datum.Set(&test1);
datum.Set(&test2, 1);
datum.Set(&test3, 2);
Assert::AreEqual(datum.Get<RTTI*>(0), rttiPtr1);
Assert::AreEqual(datum.Get<RTTI*>(1), rttiPtr2);
Assert::AreEqual(datum.Get<RTTI*>(2), rttiPtr3);
datum.Set(&test3);
Assert::AreEqual(datum.Get<RTTI*>(0), rttiPtr3);
//test 4: datum with invalid type
Datum floatDatum;
floatDatum = 5.0f;
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.Set(&test1); });
}
TEST_METHOD(PushBackInt)
{
//test 1: push to empty list
Datum datum;
datum.PushBack(5);
Assert::AreEqual(datum.Type(), DatumType::Integer);
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<int>(), 5);
//test 2: more valid pushes
datum.PushBack(10);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 2_z);
datum.PushBack(15);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Get<int>(), 5);
Assert::AreEqual(datum.Get<int>(1), 10);
Assert::AreEqual(datum.Get<int>(2), 15);
//test 3: invalid type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum] { floatDatum.PushBack(5); });
}
TEST_METHOD(PushBackFloat)
{
//test 1: push to empty list
Datum datum;
datum.PushBack(5.0f);
Assert::AreEqual(datum.Type(), DatumType::Float);
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<float>(), 5.0f);
//test 2: more valid pushes
datum.PushBack(10.0f);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 2_z);
datum.PushBack(15.0f);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Get<float>(), 5.0f);
Assert::AreEqual(datum.Get<float>(1), 10.0f);
Assert::AreEqual(datum.Get<float>(2), 15.0f);
//test 3: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.PushBack(5.0f); });
}
TEST_METHOD(PushBackVector)
{
glm::vec4 test1(1), test2(2), test3(3);
//test 1: push to empty list
Datum datum;
datum.PushBack(test1);
Assert::AreEqual(datum.Type(), DatumType::Vector);
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::vec4>(), test1);
//test 2: more valid pushes
datum.PushBack(test2);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 2_z);
datum.PushBack(test3);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Get<glm::vec4>(), test1);
Assert::AreEqual(datum.Get<glm::vec4>(1), test2);
Assert::AreEqual(datum.Get<glm::vec4>(2), test3);
//test 3: invalid type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.PushBack(test1); });
}
TEST_METHOD(PushBackMatrix)
{
glm::mat4 test1(1), test2(2), test3(3);
//test 1: push to empty list
Datum datum;
datum.PushBack(test1);
Assert::AreEqual(datum.Type(), DatumType::Matrix);
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<glm::mat4>(), test1);
//test 2: more valid pushes
datum.PushBack(test2);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 2_z);
datum.PushBack(test3);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Get<glm::mat4>(), test1);
Assert::AreEqual(datum.Get<glm::mat4>(1), test2);
Assert::AreEqual(datum.Get<glm::mat4>(2), test3);
//test 3: invalid type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.PushBack(test1); });
}
TEST_METHOD(PushBackString)
{
std::string test1("Hello"), test2("Goodbye"), test3("UGH");
//test 1: push to empty list
Datum datum;
datum.PushBack(test1);
Assert::AreEqual(datum.Type(), DatumType::String);
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<std::string>(), test1);
//test 2: more valid pushes
datum.PushBack(test2);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 2_z);
datum.PushBack(test3);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Get<std::string>(), test1);
Assert::AreEqual(datum.Get<std::string>(1), test2);
Assert::AreEqual(datum.Get<std::string>(2), test3);
//test 3: invalid type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.PushBack(test1); });
}
TEST_METHOD(PushBackPointer)
{
Foo test1(1), test2(2), test3(3);
//test 1: push to empty list
Datum datum;
datum.PushBack(&test1);
Assert::AreEqual(datum.Type(), DatumType::Pointer);
Assert::AreEqual(datum.Size(), 1_z);
Assert::AreEqual(datum.Capacity(), 1_z);
Assert::AreEqual(datum.Get<RTTI*>(), reinterpret_cast<RTTI*>(&test1));
//test 2: more valid pushes
datum.PushBack(&test2);
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 2_z);
datum.PushBack(&test3);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Get<RTTI*>(), reinterpret_cast<RTTI*>(&test1));
Assert::AreEqual(datum.Get<RTTI*>(1), reinterpret_cast<RTTI*>(&test2));
Assert::AreEqual(datum.Get<RTTI*>(2), reinterpret_cast<RTTI*>(&test3));
//test 3: invalid type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum, &test1] { floatDatum.PushBack(&test1); });
}
TEST_METHOD(PopBack)
{
//test 1: empty datum (nothing happens)
Datum datum;
datum.PopBack();
//test 2: valid pop backs
//2.1 int datum
Datum intDatum;
intDatum.PushBack(5);
intDatum.PushBack(10);
Assert::AreEqual(intDatum.Size(), 2_z);
Assert::AreEqual(intDatum.Capacity(), 2_z);
intDatum.PopBack();
Assert::AreEqual(intDatum.Get<int>(), 5);
Assert::AreEqual(intDatum.Size(), 1_z);
intDatum.PopBack();
Assert::AreEqual(intDatum.Size(), 0_z);
Assert::AreEqual(intDatum.Capacity(), 2_z);
//2.2 float datum
Datum floatDatum;
floatDatum.PushBack(5.0f);
floatDatum.PushBack(10.0f);
Assert::AreEqual(floatDatum.Size(), 2_z);
Assert::AreEqual(floatDatum.Capacity(), 2_z);
floatDatum.PopBack();
Assert::AreEqual(floatDatum.Get<float>(), 5.0f);
Assert::AreEqual(floatDatum.Size(), 1_z);
floatDatum.PopBack();
Assert::AreEqual(floatDatum.Size(), 0_z);
Assert::AreEqual(floatDatum.Capacity(), 2_z);
//2.3 vector datum
glm::vec4 testVector1(5), testVector2(10);
Datum vectorDatum;
vectorDatum.PushBack(testVector1);
vectorDatum.PushBack(testVector2);
Assert::AreEqual(vectorDatum.Size(), 2_z);
Assert::AreEqual(vectorDatum.Capacity(), 2_z);
vectorDatum.PopBack();
Assert::AreEqual(vectorDatum.Get<glm::vec4>(), testVector1);
Assert::AreEqual(vectorDatum.Size(), 1_z);
vectorDatum.PopBack();
Assert::AreEqual(vectorDatum.Size(), 0_z);
Assert::AreEqual(vectorDatum.Capacity(), 2_z);
//2.4 matrix datum
glm::mat4 testMatrix1(5), testMatrix2(10);
Datum matrixDatum;
matrixDatum.PushBack(testMatrix1);
matrixDatum.PushBack(testMatrix2);
Assert::AreEqual(matrixDatum.Size(), 2_z);
Assert::AreEqual(matrixDatum.Capacity(), 2_z);
matrixDatum.PopBack();
Assert::AreEqual(matrixDatum.Get<glm::mat4>(), testMatrix1);
Assert::AreEqual(matrixDatum.Size(), 1_z);
matrixDatum.PopBack();
Assert::AreEqual(matrixDatum.Size(), 0_z);
Assert::AreEqual(matrixDatum.Capacity(), 2_z);
//2.5 string datum
std::string testString1("Hello"), testString2("Goodbye");
Datum StringDatum;
StringDatum.PushBack(testString1);
StringDatum.PushBack(testString2);
Assert::AreEqual(StringDatum.Size(), 2_z);
Assert::AreEqual(StringDatum.Capacity(), 2_z);
StringDatum.PopBack();
Assert::AreEqual(StringDatum.Get<std::string>(), testString1);
Assert::AreEqual(StringDatum.Size(), 1_z);
StringDatum.PopBack();
Assert::AreEqual(StringDatum.Size(), 0_z);
Assert::AreEqual(StringDatum.Capacity(), 2_z);
//2.6 RTTI* datum
Foo test1(1), test2(2);
Datum PointerDatum;
PointerDatum.PushBack(&test1);
PointerDatum.PushBack(&test2);
Assert::AreEqual(PointerDatum.Size(), 2_z);
Assert::AreEqual(PointerDatum.Capacity(), 2_z);
PointerDatum.PopBack();
Assert::AreEqual(PointerDatum.Get<RTTI*>(), reinterpret_cast<RTTI*>(&test1));
Assert::AreEqual(PointerDatum.Size(), 1_z);
PointerDatum.PopBack();
Assert::AreEqual(PointerDatum.Size(), 0_z);
Assert::AreEqual(PointerDatum.Capacity(), 2_z);
}
TEST_METHOD(FindInt)
{
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum] { datum.Find(5); });
//test 2: type set but list empty
datum.SetType(DatumType::Integer);
Assert::AreEqual(datum.Find(5), 0_z);
//test 2: value exists
datum.PushBack(5);
datum.PushBack(10);
datum.PushBack(15);
Assert::AreEqual(datum.Find(5), 0_z);
Assert::AreEqual(datum.Find(10), 1_z);
Assert::AreEqual(datum.Find(15), 2_z);
//test 3: value does not exist
Assert::AreEqual(datum.Find(20), 3_z);
//test 4: invalid type (throw exception)
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum] { floatDatum.Find(5); });
}
TEST_METHOD(FindFloat)
{
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum] { datum.Find(5.0f); });
//test 2: type set but list empty
datum.SetType(DatumType::Float);
Assert::AreEqual(datum.Find(5.0f), 0_z);
//test 2: value exists
datum.PushBack(5.0f);
datum.PushBack(10.0f);
datum.PushBack(15.0f);
Assert::AreEqual(datum.Find(5.0f), 0_z);
Assert::AreEqual(datum.Find(10.0f), 1_z);
Assert::AreEqual(datum.Find(15.0f), 2_z);
//test 3: value does not exist
Assert::AreEqual(datum.Find(20.0f), 3_z);
//test 4: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum] { intDatum.Find(5.0f); });
}
TEST_METHOD(FindVector)
{
glm::vec4 test1(1), test2(2), test3(3), test4(4);
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Find(test1); });
//test 2: type set but list empty
datum.SetType(DatumType::Vector);
Assert::AreEqual(datum.Find(test1), 0_z);
//test 2: value exists
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::AreEqual(datum.Find(test1), 0_z);
Assert::AreEqual(datum.Find(test2), 1_z);
Assert::AreEqual(datum.Find(test3), 2_z);
//test 3: value does not exist
Assert::AreEqual(datum.Find(test4), 3_z);
//test 4: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &test1] { intDatum.Find(test1); });
}
TEST_METHOD(FindMatrix)
{
glm::mat4 test1(1), test2(2), test3(3), test4(4);
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Find(test1); });
//test 2: type set but list empty
datum.SetType(DatumType::Matrix);
Assert::AreEqual(datum.Find(test1), 0_z);
//test 2: value exists
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::AreEqual(datum.Find(test1), 0_z);
Assert::AreEqual(datum.Find(test2), 1_z);
Assert::AreEqual(datum.Find(test3), 2_z);
//test 3: value does not exist
Assert::AreEqual(datum.Find(test4), 3_z);
//test 4: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &test1] { intDatum.Find(test1); });
}
TEST_METHOD(FindString)
{
std::string test1("Hello"), test2("Goodbye"), test3("Ugh"), test4("Blegh");
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Find(test1); });
//test 2: type set but list empty
datum.SetType(DatumType::String);
Assert::AreEqual(datum.Find(test1), 0_z);
//test 2: value exists
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::AreEqual(datum.Find(test1), 0_z);
Assert::AreEqual(datum.Find(test2), 1_z);
Assert::AreEqual(datum.Find(test3), 2_z);
//test 3: value does not exist
Assert::AreEqual(datum.Find(test4), 3_z);
//test 4: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &test1] { intDatum.Find(test1); });
}
TEST_METHOD(FindPointer)
{
Foo test1(1), test2(2), test3(3), test4(4);
//test 1: type not set (throw exception)
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Find(&test1); });
//test 2: type set but list empty
datum.SetType(DatumType::Pointer);
Assert::AreEqual(datum.Find(&test1), 0_z);
//test 2: value exists
datum.PushBack(&test1);
datum.PushBack(&test2);
datum.PushBack(&test3);
Assert::AreEqual(datum.Find(&test1), 0_z);
Assert::AreEqual(datum.Find(&test2), 1_z);
Assert::AreEqual(datum.Find(&test3), 2_z);
//test 3: value does not exist
Assert::AreEqual(datum.Find(&test4), 3_z);
//test 4: invalid type (throw exception)
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &test1] { intDatum.Find(&test1); });
}
TEST_METHOD(RemoveAt)
{
//test 1: type not set/out of bounds
Datum unknownDatum;
Assert::IsFalse(unknownDatum.RemoveAt(0));
//int datum tests
{
int test1(5), test2(10), test3(20);
Datum datum;
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.RemoveAt(1));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
//float datum tests
{
float test1(5), test2(10), test3(20);
Datum datum;
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.RemoveAt(1));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
//vector datum tests
{
glm::vec4 test1(5), test2(10), test3(20);
Datum datum;
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.RemoveAt(1));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
//matrix datum tests
{
glm::mat4 test1(5), test2(10), test3(20);
Datum datum;
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.RemoveAt(1));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
//String datum tests
{
std::string test1("Hello"), test2("Goodbye"), test3("Ugh");
Datum datum;
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.RemoveAt(1));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
//pointer datum tests
{
Foo test1(5), test2(10), test3(20);
Datum datum;
datum.PushBack(&test1);
datum.PushBack(&test2);
datum.PushBack(&test3);
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(&test1), datum.Size());
Assert::IsTrue(datum.RemoveAt(1));
Assert::AreEqual(datum.Find(&test3), datum.Size());
Assert::IsTrue(datum.RemoveAt(0));
Assert::AreEqual(datum.Find(&test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
}
TEST_METHOD(RemoveInt)
{
int test1(5), test2(10), test3(20), test4(50);
//test 1: type not int
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Remove(test1); });
//test 2: does not exist
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsFalse(datum.Remove(test4));
//test 3: valid removes
Assert::IsTrue(datum.Remove(test1));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.Remove(test3));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.Remove(test2));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
TEST_METHOD(RemoveFloat)
{
float test1(5), test2(10), test3(20), test4(50);
//test 1: type not int
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Remove(test1); });
//test 2: does not exist
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsFalse(datum.Remove(test4));
//test 3: valid removes
Assert::IsTrue(datum.Remove(test1));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.Remove(test3));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.Remove(test2));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
TEST_METHOD(RemoveVector)
{
glm::vec4 test1(5), test2(10), test3(20), test4(50);
//test 1: type not int
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Remove(test1); });
//test 2: does not exist
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsFalse(datum.Remove(test4));
//test 3: valid removes
Assert::IsTrue(datum.Remove(test1));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.Remove(test3));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.Remove(test2));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
TEST_METHOD(RemoveMatrix)
{
glm::mat4 test1(5), test2(10), test3(20), test4(50);
//test 1: type not int
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Remove(test1); });
//test 2: does not exist
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsFalse(datum.Remove(test4));
//test 3: valid removes
Assert::IsTrue(datum.Remove(test1));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.Remove(test3));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.Remove(test2));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
TEST_METHOD(RemoveString)
{
std::string test1("Hello"), test2("Goodbye"), test3("ugh"), test4("blegh");
//test 1: type not int
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Remove(test1); });
//test 2: does not exist
datum.PushBack(test1);
datum.PushBack(test2);
datum.PushBack(test3);
Assert::IsFalse(datum.Remove(test4));
//test 3: valid removes
Assert::IsTrue(datum.Remove(test1));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(test1), datum.Size());
Assert::IsTrue(datum.Remove(test3));
Assert::AreEqual(datum.Find(test3), datum.Size());
Assert::IsTrue(datum.Remove(test2));
Assert::AreEqual(datum.Find(test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
TEST_METHOD(RemovePointer)
{
Foo test1(5), test2(10), test3(20), test4(50);
//test 1: type not int
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &test1] { datum.Remove(&test1); });
//test 2: does not exist
datum.PushBack(&test1);
datum.PushBack(&test2);
datum.PushBack(&test3);
Assert::IsFalse(datum.Remove(&test4));
//test 3: valid removes
Assert::IsTrue(datum.Remove(&test1));
Assert::AreEqual(datum.Size(), 2_z);
Assert::AreEqual(datum.Capacity(), 4_z);
Assert::AreEqual(datum.Find(&test1), datum.Size());
Assert::IsTrue(datum.Remove(&test3));
Assert::AreEqual(datum.Find(&test3), datum.Size());
Assert::IsTrue(datum.Remove(&test2));
Assert::AreEqual(datum.Find(&test2), datum.Size());
Assert::AreEqual(datum.Size(), 0_z);
Assert::AreEqual(datum.Capacity(), 4_z);
}
TEST_METHOD(SetStorageInt)
{
int test1(5), test2(10), test3(15);
int arr[3] = { test1, test2, test3 };
int* badptr = nullptr;
//test 1: nullptr
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &badptr] { datum.SetStorage(badptr, 0); });
//test2: valid
datum.SetStorage(arr, 3);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<int>(), test1);
Assert::AreEqual(datum.Get<int>(1), test2);
Assert::AreEqual(datum.Get<int>(2), test3);
//test 3: bad type
Datum floatDatum(DatumType::Float);
Assert::ExpectException<std::runtime_error>([&floatDatum, &arr] { floatDatum.SetStorage(arr, 3); });
//test 4: allocated memory already
Assert::ExpectException<std::runtime_error>([&datum, &arr] { datum.SetStorage(arr, 3); });
}
TEST_METHOD(SetStorageFloat)
{
float test1(5), test2(10), test3(15);
float arr[3] = { test1, test2, test3 };
float* badptr = nullptr;
//test 1: nullptr
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &badptr] { datum.SetStorage(badptr, 0); });
//test2: valid
datum.SetStorage(arr, 3);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<float>(), test1);
Assert::AreEqual(datum.Get<float>(1), test2);
Assert::AreEqual(datum.Get<float>(2), test3);
//test 3: bad type
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &arr] { intDatum.SetStorage(arr, 3); });
//test 4: allocated memory already
Assert::ExpectException<std::runtime_error>([&datum, &arr] { datum.SetStorage(arr, 3); });
}
TEST_METHOD(SetStorageVector)
{
glm::vec4 test1(5), test2(10), test3(15);
glm::vec4 arr[3] = { test1, test2, test3 };
glm::vec4* badptr = nullptr;
//test 1: nullptr
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &badptr] { datum.SetStorage(badptr, 0); });
//test2: valid
datum.SetStorage(arr, 3);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<glm::vec4>(), test1);
Assert::AreEqual(datum.Get<glm::vec4>(1), test2);
Assert::AreEqual(datum.Get<glm::vec4>(2), test3);
//test 3: bad type
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &arr] { intDatum.SetStorage(arr, 3); });
//test 4: allocated memory already
Assert::ExpectException<std::runtime_error>([&datum, &arr] { datum.SetStorage(arr, 3); });
}
TEST_METHOD(SetStorageMatrix)
{
glm::mat4 test1(5), test2(10), test3(15);
glm::mat4 arr[3] = { test1, test2, test3 };
glm::mat4* badptr = nullptr;
//test 1: nullptr
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &badptr] { datum.SetStorage(badptr, 0); });
//test2: valid
datum.SetStorage(arr, 3);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<glm::mat4>(), test1);
Assert::AreEqual(datum.Get<glm::mat4>(1), test2);
Assert::AreEqual(datum.Get<glm::mat4>(2), test3);
//test 3: bad type
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &arr] { intDatum.SetStorage(arr, 3); });
//test 4: allocated memory already
Assert::ExpectException<std::runtime_error>([&datum, &arr] { datum.SetStorage(arr, 3); });
}
TEST_METHOD(SetStorageString)
{
std::string test1("Hello"), test2("Goodbye"), test3("ugh");
std::string arr[3] = { test1, test2, test3 };
std::string* badptr = nullptr;
//test 1: nullptr
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &badptr] { datum.SetStorage(badptr, 0); });
//test2: valid
datum.SetStorage(arr, 3);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<std::string>(), test1);
Assert::AreEqual(datum.Get<std::string>(1), test2);
Assert::AreEqual(datum.Get<std::string>(2), test3);
//test 3: bad type
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &arr] { intDatum.SetStorage(arr, 3); });
//test 4: allocated memory already
Assert::ExpectException<std::runtime_error>([&datum, &arr] { datum.SetStorage(arr, 3); });
}
TEST_METHOD(SetStoragePointer)
{
Foo test1(10), test2(15), test3(25);
RTTI* arr[3] = { &test1, &test2, &test3 };
std::string* badptr = nullptr;
//test 1: nullptr
Datum datum;
Assert::ExpectException<std::runtime_error>([&datum, &badptr] { datum.SetStorage(badptr, 0); });
//test2: valid
datum.SetStorage(arr, 3);
Assert::AreEqual(datum.Capacity(), 3_z);
Assert::AreEqual(datum.Size(), 3_z);
Assert::AreEqual(datum.Get<RTTI*>(), reinterpret_cast<RTTI*>(&test1));
Assert::AreEqual(datum.Get<RTTI*>(1), reinterpret_cast<RTTI*>(&test2));
Assert::AreEqual(datum.Get<RTTI*>(2), reinterpret_cast<RTTI*>(&test3));
//test 3: bad type
Datum intDatum(DatumType::Integer);
Assert::ExpectException<std::runtime_error>([&intDatum, &arr] { intDatum.SetStorage(arr, 3); });
//test 4: allocated memory already
Assert::ExpectException<std::runtime_error>([&datum, &arr] { datum.SetStorage(arr, 3); });
}
TEST_METHOD(ToString)
{
//test 1: default constructed datum (throw exception)
Datum defaultDatum;
Assert::ExpectException<std::runtime_error>([&defaultDatum] { defaultDatum.ToString(); });
//test 2: index out of bounds (throw exception)
defaultDatum.SetType(DatumType::String);
Assert::ExpectException<std::runtime_error>([&defaultDatum] { defaultDatum.ToString(); });
//test 3: valid to strings
Datum intDatum;
intDatum = 5;
Assert::AreEqual(intDatum.ToString(), "5"s);
Datum floatDatum;
floatDatum = 5.0f;
Assert::AreEqual(floatDatum.ToString(), "5.000000"s);
Datum vectorDatum;
vectorDatum = glm::vec4(5);
Assert::AreEqual(vectorDatum.ToString(), "vec4(5.000000, 5.000000, 5.000000, 5.000000)"s);
Datum matrixDatum;
matrixDatum = glm::mat4(5);
Assert::AreEqual(matrixDatum.ToString(), "mat4x4((5.000000, 0.000000, 0.000000, 0.000000), (0.000000, 5.000000, 0.000000, 0.000000), (0.000000, 0.000000, 5.000000, 0.000000), (0.000000, 0.000000, 0.000000, 5.000000))"s);
Datum stringDatum;
stringDatum = "Hello"s;
Assert::AreEqual(stringDatum.ToString(), "Hello"s);
Datum RTTIDatum;
Foo foo(5);
RTTIDatum = &foo;
Assert::AreEqual(RTTIDatum.ToString(), "RTTI"s);
}
TEST_METHOD(SetFromString)
{
//int tests
{
std::string str1 = "5";
std::string str2 = "10";
Datum datum(DatumType::Integer);
datum.Resize(5, true);
datum.SetFromString<int>(str1);
datum.SetFromString<int>(str2, 1);
Assert::AreEqual(datum.Get<int>(), 5);
Assert::AreEqual(datum.Get<int>(1), 10);
//invalid string
Assert::ExpectException<invalid_argument>([&datum] { datum.SetFromString<int>("bleh"s); });
Assert::ExpectException<out_of_range>([&datum] { datum.SetFromString<int>("99999999999999"s); });
}
//float tests
{
std::string str1 = "5.123";
std::string str2 = "10.2901";
Datum datum(DatumType::Float);
datum.Resize(5, true);
datum.SetFromString<float>(str1);
datum.SetFromString<float>(str2, 1);
Assert::AreEqual(datum.Get<float>(), 5.123f);
Assert::AreEqual(datum.Get<float>(1), 10.2901f);
//invalid string
Assert::ExpectException<invalid_argument>([&datum] { datum.SetFromString<float>("bleh"s); });
//Assert::ExpectException<out_of_range>([&datum] { datum.SetFromString<float>("99999999999999.5"s); });
}
//vector tests
{
glm::vec4 vec1(5.123f, 10.2f, 3.1f, 2.3f);
glm::vec4 vec2(2.23f);
Datum datum(DatumType::Vector);
datum.Resize(5, true);
datum.SetFromString<glm::vec4>(glm::to_string(vec1));
datum.SetFromString<glm::vec4>(glm::to_string(vec2), 1);
Assert::AreEqual(datum.Get<glm::vec4>(), vec1);
Assert::AreEqual(datum.Get<glm::vec4>(1), vec2);
Assert::ExpectException<std::runtime_error>([&datum] { datum.SetFromString<glm::vec4>("bleh"s); });
}
//matrix tests
{
glm::mat4 mat1(5.00f);
glm::mat4 mat2(2.23f);
Datum datum(DatumType::Matrix);
datum.Resize(5, true);
datum.SetFromString<glm::mat4>(glm::to_string(mat1));
datum.SetFromString<glm::mat4>(glm::to_string(mat2), 1);
Assert::AreEqual(datum.Get<glm::mat4>(), mat1);
Assert::AreEqual(datum.Get<glm::mat4>(1), mat2);
Assert::ExpectException<std::runtime_error>([&datum] { datum.SetFromString<glm::mat4>("bleh"s); });
}
//string test
{
Datum datum(DatumType::String);
datum.Resize(5, true);
datum.SetFromString<string>("I'm tired"s);
Assert::AreEqual(datum.Get<string>(), "I'm tired"s);
}
}
private:
static _CrtMemState sStartMemState; //for memory leak detection
};
_CrtMemState DatumTests::sStartMemState;
} | true |
f2b5be3406dcd9b482f43ff4e23f20a6491dbe7f | C++ | syslot/leetcode | /leetcode/887.cpp | UTF-8 | 923 | 3.03125 | 3 | [] | no_license | #include "../common.h"
class Solution {
public:
int superEggDrop(int K, int N) {
if(N == 0)
return 0;
if(K==1)
return N;
int key = N*1000+K;
if(map_.find(key) != map_.end())
return map_[key];
int low = 1, high = N;
while(low<high){
int middle = (low+high)/2;
int lowVal = superEggDrop(K-1, middle -1);
int highVal = superEggDrop(K, N-middle);
if(lowVal < highVal)
low = middle+1;
else
high = middle;
}
int min_ = 1 +
min(max(superEggDrop(K-1, low-1), superEggDrop(K, N-low)),
max(superEggDrop(K-1, high-1), superEggDrop(K, N-high)));
map_[key] = min_;
}
map<int,int> map_;
};
int main(){
Solution s;
cout << s.superEggDrop(4,2000) << endl;
}
| true |
47e63e53d716b06b70bb442e32139c1599c8bafd | C++ | j-a-h-i-r/Online-Judge-Solutions | /Uva/108 - Bad Complexity.cpp | UTF-8 | 1,669 | 2.828125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
using namespace std;
void prSub(int is, int ie, int js, int je, int ara[200][200])
{
for (int k=is; k<=ie; k++)
{
for (int l=js; l<=je; l++)
{
cout<<ara[k][l]<<" ";
}
cout<<endl;
}
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int ara[200][200];
int n;
while(cin>>n)
{
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
cin>>ara[i][j];
}
}
int sum = 0, mxSum = -100000, colSum[200];
// colsum keeps track of sum in same row of previous column
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
// start at [i][j]
// traverse
//sum = 0;
for (int k=j; k<n; k++) // column
{
sum = 0;
for (int l=i; l<n; l++) // row
{
//prSub(i,l, j,k, ara); cout<<endl;
sum += ara[l][k];
if(k==j)colSum[l] = 0;
colSum[l] += sum;
//cout<<"s "<<sum<<" "<<colSum[l]<<endl;
if (colSum[l] > mxSum)
{
mxSum = colSum[l];
}
}
//cout<<endl;
}
}
}
cout<<mxSum<<endl;
}
return 0;
}
| true |
37c651319fc3e449c1d973fabe926a3363ccc720 | C++ | coderdamin/PAT-Basic-Level-Practise | /C++/1032.cpp | GB18030 | 1,173 | 3.15625 | 3 | [] | no_license | //
// Ϊʵ˵ھļǿPAT֯һھܴݱͳƳǿǸѧУ
//ʽ
// ڵ1и105NNУÿиһλߵϢͳɼѧУıţ1ʼţ
// ɼٷƣмԿոָ
//ʽ
// һиܵ÷ߵѧУıšܷ֣мԿոָĿ֤ΨһûвС
//
// 6
// 3 65
// 2 80
// 1 100
// 2 70
// 3 40
// 3 0
//
// 2 150
#include <iostream>
using namespace std;
int main() {
int anScore[105] = { 0 };
int nCount = 0;
cin >> nCount;
int nNumber, nScore;
int nMaxScore = -1, nMaxIndex = -1;
for (int i = 0; i < nCount; ++i) {
cin >> nNumber >> nScore;
anScore[nNumber - 1] += nScore;
if (nMaxScore < anScore[nNumber - 1]) {
nMaxScore = anScore[nNumber - 1];
nMaxIndex = nNumber - 1;
}
}
cout << nMaxIndex + 1 << ' ' << nMaxScore << endl;
return 0;
}
| true |
8d9a47f919d0ac34d506479161bdc7999a5d07d2 | C++ | Rayleigh0328/OJ | /leetcode/221_2.cpp | UTF-8 | 712 | 2.6875 | 3 | [] | no_license | class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> f(n, vector<int>(m,0));
for (int i=0; i<n;++i) f[i][0] = (matrix[i][0]=='1'?1:0);
for (int j=0; j<m;++j) f[0][j] = (matrix[0][j]=='1'?1:0);
for (int i=1;i<n;++i)
for (int j=1;j<m;++j)
if (matrix[i][j]=='1')
f[i][j] = 1 + min(min(f[i-1][j-1], f[i-1][j]), f[i][j-1]);
int ans = 0;
for (int i=0;i<n;++i)
for (int j=0;j<m;++j)
ans = max(ans,f[i][j] * f[i][j]);
return ans;
}
};
| true |
9a985c914b92078fefaff13b359549bf6e7ccc92 | C++ | aedalzotto/berimbau-avr | /src/SD.cpp | UTF-8 | 1,331 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | #include <SD.h>
#include <stdio.h>
SDCard SD::disk(&PORTB, &DDRB, PB0);
FAT SD::fs(&disk);
File SD::root(&fs);
File SD::rec(&fs);
File SD::file(&fs);
bool SD::mounted = false;
uint32_t SD::start_time = 0;
bool SD::first = true;
bool SD::init()
{
// Initialize disk and mount filesystem
return disk.init() &&
fs.mount() &&
root.open_root() &&
rec.open(root, "record", File::O_READ);
}
bool SD::open_record(char* fname)
{
first = true;
char strbuf[25];
sprintf(strbuf, "%s.dat", fname);
return file.open(rec, strbuf, File::O_CREAT | File::O_WRITE) &&
file.rm() &&
file.open(rec, strbuf, File::O_CREAT | File::O_WRITE);
}
size_t SD::record(uint32_t timestamp, uint8_t data)
{
if(first){
first = false;
start_time = timestamp;
}
timestamp -= start_time;
return file.write((uint8_t*)×tamp, 4) && file.write(&data, 1);
}
bool SD::stop_record()
{
return file.close();
}
bool SD::open_play(char *fname)
{
return file.open(rec, fname, File::O_READ);
}
bool SD::read_beat(uint32_t *timestamp, uint8_t *instrument)
{
if(file.available() >= 5)
return file.read((uint8_t*)timestamp, 4) && file.read(instrument, 1);
return false;
}
bool SD::close_play()
{
return file.close();
} | true |
bedee379ee24edf6cfa752ea299a992e5b7e3afe | C++ | TonyXYJ/c- | /韩信点兵.cpp | UTF-8 | 1,011 | 3.015625 | 3 | [] | no_license | #include<iostream>
using namespace std;
class HanXin
{
public:
HanXin();
int line3(int x);
int line5(int y);
int line7(int z);
void showMany();
int a[100],b[100],t,u,v,h,m,j;
private:
};
HanXin::HanXin()
{
}
int HanXin::line3(int x)
{
for(t=0;;t++)
{
a[t]=3*t+x;
if(a[t]>=100) break;
else continue;
}
}
int HanXin::line5(int y)
{
j=0;
for(h=0;h<t;h++)
{
if((a[h]-y)%5==0&&a[h]>10&&a[h]<100)
{
for(;;)
{
b[j]=a[h];
j++;
break;
}
}
else
continue;
}
if(b[j]>0) u=1;
else u=0;
return u;
}
int HanXin::line7(int z)
{
for(m=0;m<j;m++)
{
if((b[m]-z)%7==0&&b[m]>10&&b[m]<100)
{
v=1;
break;
}
else continue;
}
if(m==j) v=0;
return v;
}
void HanXin::showMany()
{
if(u&&v)
cout<<b[m]<<endl;
else
cout<<"impossible"<<endl;
}
int main()
{
int n,n1,n2,n3;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
cin>>n1>>n2>>n3;
HanXin hx;
hx.line3(n1);
hx.line5(n2);
hx.line7(n3);
hx.showMany();
}
return 0;
}
| true |
0c45e9156c4e7acbfd52a2eb1f5fc532295764f7 | C++ | MichalLebeda/BI-PA2-semestral-work | /src/physics/WorldContactListener.h | UTF-8 | 1,384 | 3 | 3 | [] | no_license | //
// Created by michal on 3/17/20.
//
#ifndef SEMESTRAL_WORK_WORLDCONTACTLISTENER_H
#define SEMESTRAL_WORK_WORLDCONTACTLISTENER_H
#include "PhysBody.h"
/**
* Abstract class for handling contacts with helper methods
*/
class WorldContactListener {
public:
/**
* @brief Called when contact occurs
* @param bodyA First body in contact
* @param bodyB Second body in contact
*/
virtual void onContact(PhysBody *bodyA, PhysBody *bodyB) = 0;
/**
* @brief Return whatever at least one of two bodies contain identifier
* @param identifier Identifier we are looking for
* @param bodyA Body to be searched for given identifier
* @param bodyB Another body to be searched for given identifier
* @return True if body was found false otherwise
*/
bool isInContact(int identifier, PhysBody *bodyA, PhysBody *bodyB) const;
/**
* @brief Get body with given identifier from two bodies
* @param identifier Identifier we are looking for
* @param bodyA Body to be searched for given identifier
* @param bodyB Another body to be searched for given identifier
* @return Body with given identifier or nullptr
*/
PhysBody *getFromContact(int identifier, PhysBody *bodyA, PhysBody *bodyB) const;
virtual ~WorldContactListener() = default;
};
#endif //SEMESTRAL_WORK_WORLDCONTACTLISTENER_H
| true |
ad2fff5101689ee6df46140bd3b52bedbfe2f834 | C++ | Iswarya125/CPP-Learning | /FriendClass.cpp | UTF-8 | 908 | 3.875 | 4 | [] | no_license | // 1. Keyword "friend" is used to make some [function OR class] as friend of your class.
// 2. Friend function OR friend class can access private/public/protected Data Member OR Member Functions of another class.
// 3. Function can not become friend of another function.
// 4. Class can not become friend of function.
// 5. Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend of A automatically.
// 6. Friendship is not inherited.
// Eg use case for friend - during unit testing, Manager->employee relationship
#include <iostream>
using namespace std;
class A
{
public:
friend class B;
private:
int x;
};
class B
{
public:
void update(A& a)
{
a.x = 10;
}
void show(A& a)
{
cout<<"value of x in class A is "<<a.x<<endl;
}
};
int main()
{
B b;
A a;
b.update(a);
b.show(a);
return 0;
} | true |
670bbbd51bcdb28484efdae66187996e2cd963e0 | C++ | awesomeabhi34/cpc-prep | /week 1/minmax with less comp.cpp | UTF-8 | 541 | 2.75 | 3 | [] | no_license | pair<int,int> minmax;
int i;
if(n%2==0){
if(arr[0]<arr[i]){
minmax.first= arr[0];
minmax.second= arr[1];
}else{
minmax.first= arr[1];
minmax.second= arr[0];
}
i=2;
}else{
minmax.first= arr[0];
minmax.second= arr[0];
i=1;
}
while(i<n-1){
if(arr[i]<arr[i+1]){
if(minmax.first>arr[i]){
minmax.first=arr[i];
}
if(minmax.second< arr[i+1]){
minmax.second=arr[i+1];
}
}else{
if(minmax.second<arr[i]){
minmax.second=arr[i];
}
if(minmax.first< arr[i+1]){
minmax.first=arr[i+1];
}
}
}
return minmax;
| true |
3e8b6f0b7b3239d14d6e3ee61560ecd43bf2b489 | C++ | kounkounsito/plaidml | /pmlc/dialect/stripe/types.h | UTF-8 | 5,269 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | // Copyright 2019, Intel Corporation
#pragma once
#include <string>
#include <tuple>
#include <vector>
#include "pmlc/dialect/eltwise/types.h"
#include "pmlc/dialect/stripe/mlir.h"
#include "tile/base/shape.h"
namespace pmlc {
namespace dialect {
namespace stripe {
namespace Types {
enum Kinds {
// An affine is a affine polynomial of indexes over integers
Affine = Type::Kind::FIRST_PRIVATE_EXPERIMENTAL_1_TYPE,
// A hardware device identifier
DeviceID,
// A hardware device path
DevicePath,
// A PRNG state
Prng,
// A fully-sized tensor with a memory layout
Tensor,
// A tensor reference
TensorRef,
};
} // namespace Types
// The Affine type represents an affine expression of indexes
// The type itself is trival, and actual expression is constructed on demand
class AffineType : public Type::TypeBase<AffineType, Type> {
public:
using Base::Base;
static bool kindof(unsigned kind) { return kind == Types::Affine; }
static AffineType get(MLIRContext* context) { return Base::get(context, Types::Affine); }
};
struct TensorDim {
// The size of a dimension, or 0 if the dimensions size is not fixed
int64_t size;
// The stride of a dimension in linear memory, or 0 if not yet known
int64_t stride;
bool operator==(const TensorDim& rhs) const { //
return size == rhs.size && stride == rhs.stride;
}
};
inline llvm::hash_code hash_value(const TensorDim& td) { //
return llvm::hash_combine(td.size, td.stride);
}
struct TensorTypeStorage : public mlir::TypeStorage {
TensorTypeStorage(Type elementType, llvm::ArrayRef<TensorDim> shape) : elementType(elementType), shape(shape) {}
using KeyTy = std::tuple<Type, std::vector<TensorDim>>;
bool operator==(const KeyTy& key) const { return elementType == std::get<0>(key) && shape == std::get<1>(key); }
static llvm::hash_code hashKey(const KeyTy& key) { return hash_value(key); }
static TensorTypeStorage* construct(mlir::TypeStorageAllocator& allocator, const KeyTy& key) { // NOLINT
return new (allocator.allocate<TensorTypeStorage>()) TensorTypeStorage(std::get<0>(key), std::get<1>(key));
}
Type elementType;
std::vector<TensorDim> shape;
};
struct TensorTypeBase {
/// Return the element type.
virtual Type getElementType() const = 0;
/// Return the rank.
virtual int64_t getRank() const = 0;
};
class TensorType : public Type::TypeBase<TensorType, Type, TensorTypeStorage> {
public:
using Base::Base;
static bool kindof(unsigned kind) { return kind == Types::Tensor; }
static TensorType get(Type elementType, llvm::ArrayRef<TensorDim> shape) {
return Base::get(elementType.getContext(), Types::Tensor, elementType, shape);
}
/// Return the element type.
Type getElementType() const { return getImpl()->elementType; }
/// Return the rank.
int64_t getRank() const { return getImpl()->shape.size(); }
/// Return the shape.
llvm::ArrayRef<TensorDim> getShape() const { return getImpl()->shape; }
};
struct TensorRefTypeStorage : public mlir::TypeStorage {
TensorRefTypeStorage(Type elementType, size_t rank) : elementType(elementType), rank(rank) {}
using KeyTy = std::tuple<Type, size_t>;
bool operator==(const KeyTy& key) const { return elementType == std::get<0>(key) && rank == std::get<1>(key); }
static llvm::hash_code hashKey(const KeyTy& key) { return hash_value(key); }
static TensorRefTypeStorage* construct(mlir::TypeStorageAllocator& allocator, const KeyTy& key) { // NOLINT
return new (allocator.allocate<TensorRefTypeStorage>()) TensorRefTypeStorage(std::get<0>(key), std::get<1>(key));
}
Type elementType;
size_t rank;
};
class TensorRefType : public Type::TypeBase<TensorRefType, Type, TensorRefTypeStorage> {
public:
using Base::Base;
static bool kindof(unsigned kind) { return kind == Types::TensorRef; }
static TensorRefType get(Type elementType, size_t rank) {
return Base::get(elementType.getContext(), Types::TensorRef, elementType, rank);
}
/// Return the element type.
Type getElementType() const { return getImpl()->elementType; }
/// Return the rank.
int64_t getRank() const { return getImpl()->rank; }
};
// A PRNG state.
class PrngType : public Type::TypeBase<PrngType, Type> {
public:
using Base::Base;
static bool kindof(unsigned kind) { return kind == Types::Prng; }
static PrngType get(MLIRContext* context) { return Base::get(context, Types::Prng); }
};
// A relative identifier for a hardware component capable of storing tensor data or executing a block of
// instructions.
class DeviceIDType : public Type::TypeBase<DeviceIDType, Type> {
public:
using Base::Base;
static bool kindof(unsigned kind) { return kind == Types::DeviceID; }
static DeviceIDType get(MLIRContext* context) { return Base::get(context, Types::DeviceID); }
};
// An absolute path to a hardware component capable of storing tensor data or executing a block of
// instructions.
class DevicePathType : public Type::TypeBase<DevicePathType, Type> {
public:
using Base::Base;
static bool kindof(unsigned kind) { return kind == Types::DevicePath; }
static DevicePathType get(MLIRContext* context) { return Base::get(context, Types::DevicePath); }
};
} // namespace stripe
} // namespace dialect
} // namespace pmlc
| true |
b459dc56602781889c423c40a94c4c64b32b5df2 | C++ | datoufeng/cluster_server | /f_exception/fd_exception.h | UTF-8 | 219 | 2.734375 | 3 | [] | no_license | class fd_exception{
public:
string exception_str;
fd_exception() throw();
fd_exception(const string& ex_str) throw(){
exception_str=ex_str;
}
virtual const char* what() const throw(){
return exception_str;
}
} | true |
3f362887a080e1b7b0ca307773215b65cafe56c1 | C++ | tats-u/breakout | /letter.hpp | UTF-8 | 493 | 3.1875 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | /********************コンストラクタ・デストラクタで表示を管理する文字************************/
//デストラクタ(表示消去)
Letter::~Letter() {
gamekernel::clearObjDisp(x,y,txt.length());
}
//コンストラクタ(表示)
Letter::Letter(int newx,int newy,string newtxt, int newcolor) {
x = newx;
y = newy;
txt = newtxt;
color = newcolor;
Refresh(); //表示する
}
//(再)表示関数
void Letter::Refresh() {
gamekernel::drawObj(x,y,txt,color);
}
| true |
1535d3982f9315a2793011b94bcf4553363463a3 | C++ | arunima18/Arunima-CS | /lab6-q1a.cpp | UTF-8 | 658 | 3.515625 | 4 | [] | no_license | /* Write a function that obtains from the user and returns a value for unitCst, units, and taxRt to the calling module. Choose an appropriate name for this function.
*/
#include<iostream>
using namespace std;
//write function to ask three values from user
int enterValue(int unitCst, int units, int taxRt){
cout<<"Enter the unit cost of the product"<<endl;
cin>>unitCst;
cout<<"Enter the number of units"<<endl;
cin>>units;
cout<<"Enter the tax rate"<<endl;
cin>>taxRt;
return unitCst;
return units;
return taxRt;
}
//Main function
int main(){
int unitCst,units,taxRt;
//Call the previous function
enterValue(unitCst,units,taxRt);
return 0;
}
| true |
278e64c19bd1c5cfeb642a78781cc9d5d93fcd7f | C++ | zxc112039zxc/RISC-V_Assembler | /SB-type.h | UTF-8 | 1,817 | 3.03125 | 3 | [] | no_license | #ifndef SB_TYPE_H
#define SB_TYPE_H
#include <iostream>
#include <string>
#include "Instruction.h"
#include "InstructionDatabse.h"
using namespace std;
class SB_type : public Instruction
{
private:
string imm12_10_5;
string rs2;
string rs1;
string funct3;
string imm4_1_11;
string opcode;
void genImm12_10_5();
void genRs2();
void genRs1();
void genFunct3();
void genImm4_1_11();
void genOpcode();
public:
SB_type(int inputIndex, string *inputReg, string inputLabel);
~SB_type();
void conversion();
void output(ofstream &outputFile);
};
SB_type::SB_type(int inputIndex, string *inputReg, string inputLabel) : Instruction(inputIndex, inputReg, inputLabel)
{
target = inputReg[2];
}
SB_type::~SB_type()
{
}
void SB_type::conversion()
{
genImm12_10_5();
genRs2();
genRs1();
genFunct3();
genImm4_1_11();
genOpcode();
}
void SB_type::output(ofstream &outputFile)
{
outputFile << imm12_10_5 << rs2 << rs1 << funct3 << imm4_1_11 << opcode << endl;
}
void SB_type::genImm12_10_5()
{
Reg[2] = bitset<13>(jump * 4).to_string(); //change decimal to binary
imm12_10_5.assign(Reg[2], 0, 1);
imm12_10_5.append(Reg[2], 2, 6);
}
void SB_type::genRs2()
{
if (Reg[1][0] == 'x')
{
Reg[1].erase(0, 1);
}
rs2 = bitset<5>(stoi(Reg[1])).to_string(); //change decimal to binary
}
void SB_type::genRs1()
{
if (Reg[0][0] == 'x')
{
Reg[0].erase(0, 1);
}
rs1 = bitset<5>(stoi(Reg[0])).to_string(); //change decimal to binary
}
void SB_type::genFunct3()
{
funct3 = instDatabase[index][2];
}
void SB_type::genImm4_1_11()
{
imm4_1_11.assign(Reg[2], 8, 4);
imm4_1_11.append(Reg[2], 1, 1);
}
void SB_type::genOpcode()
{
opcode = instDatabase[index][3];
}
#endif | true |
7bd4a3eeab756689b3b8aafc984be590030c92f7 | C++ | utkarsh1706/Codechef | /January Long Challenge/Encoded String.cpp | UTF-8 | 686 | 2.765625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void my_print(int x)
{
char symbol = (char)('a' + x );
cout << symbol;
return;
}
void tosolve(string str,int l,int r,int k)
{
if(r==l)
{
my_print(l);
return;
}
char now=str[k];
int mid= l + (r - l) / 2;
k=k+1;
if(now=='0')
{
tosolve(str,l,mid,k);
}
else
{
tosolve(str,mid+1,r,k);
}
return;
}
int main(int argc, char const *argv[])
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string str;
cin>>str;
for (int i = 0; i < n; i+=4)
{
string r=str.substr(i,4);
tosolve(r,0,15,0);
if(i==n-4)
{
cout<<endl;
}
}
}
return 0;
} | true |
5f36ecc46476935e20287fd1c5a7bfb0f8bb6d42 | C++ | Widurr/DigitalRegister | /group.cpp | UTF-8 | 711 | 3.03125 | 3 | [] | no_license | #include "group.h"
Group::Group()
{
id = getCurrentID();
}
void Group::setStudentIDs(const QVector<int>& students)
{
studentIDs = Group::vectorToString(students);
}
QString Group::getStudentIDs() const
{
return studentIDs;
}
int Group::getCurrentID()
{
static int i = 0;
++i;
return i;
}
QVector<int> Group::stringToVector(const QString& str)
{
QVector<int> vec;
const auto& arr = str.split(",");
for(auto& i : arr)
{
vec.append(i.toInt());
}
return vec;
}
QString Group::vectorToString(const QVector<int>& students)
{
QString str;
for(auto& i : students)
{
str += QString::number(i);
str += ',';
}
return str;
}
| true |
245e2fd0e1b4731608b37a295c4c442edaf71d75 | C++ | sumanch99/C-Program | /Untitled2.cpp | UTF-8 | 674 | 3.84375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Item
{
private:int x,y;
public: Item()
{
x=y=0;
}
Item(int a)
{
x=a;
y=0;
}
Item(int m,int n)
{
x=m;
y=n;
}
void output()
{
cout<<"\nx="<<x<<"\ny="<<y;
}
Item add(Item &a)
{
Item temp;
temp.x=x+a.x;
temp.y=y+a.y;
return temp;
}
};
int main(){
int x,y;
cout<<"\nEnter x & y for 1st object:";
cin>>x>>y;
Item obj1(x,y);
cout<<"\nEnter x & y for 2nd Object:";
cin>>x>>y;
Item obj2(x,y);
Item obj3=obj1.add(obj2);
cout<<"\nResultant Object:";
obj3.output();
return 0;
}
| true |
7d0a6b53744811f009f48b9e12574f4325a8e4cb | C++ | sd2017/Super-Haxagon | /include/Core/Structs.hpp | UTF-8 | 3,581 | 2.6875 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | #ifndef SUPER_HAXAGON_STRUCTS_HPP
#define SUPER_HAXAGON_STRUCTS_HPP
#include <cstdint>
#include <fstream>
#include <string>
namespace SuperHaxagon {
class Platform;
struct Color {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
struct Point {
float x;
float y;
};
enum class Movement {
CAN_MOVE,
CANNOT_MOVE_LEFT,
CANNOT_MOVE_RIGHT,
DEAD,
};
enum class LocColor {
FG = 0,
BG1,
BG2,
LAST // Unused, but used for iteration
};
static constexpr int COLOR_LOCATION_FIRST = static_cast<int>(LocColor::FG);
static constexpr int COLOR_LOCATION_LAST = static_cast<int>(LocColor::LAST);
static constexpr float PI = 3.14159265358979f;
static constexpr float TAU = PI * 2.0f;
static constexpr float SCALE_MENU = 3.5f;
static constexpr float SCALE_BASE_DISTANCE = 400.0f;
static constexpr float SCALE_HEX_LENGTH = 24.0f;
static constexpr float SCALE_HEX_BORDER = 4.0f;
static constexpr float SCALE_HUMAN_PADDING = 5.0f;
static constexpr float SCALE_HUMAN_HEIGHT = 5.0f;
static constexpr float SCALE_HUMAN_WIDTH = 5.0f;
static const Color COLOR_SHADOW = {0, 0, 0, 0xC0};
static const Color COLOR_TRANSPARENT = {0, 0, 0, 0xA0};
static const Color COLOR_GREY = {0xA0, 0xA0, 0xA0, 0xFF};
static const Color COLOR_WHITE = {0xFF, 0xFF, 0xFF, 0xFF};
static const Color COLOR_BLACK = {0, 0, 0, 0xFF};
static const Color COLOR_RED = {0xFF, 0x60, 0x60, 0xFF};
static const Color PULSE_LOW = {0xFF, 0xFF, 0xFF, 0x7F};
static const Color PULSE_HIGH = {0xFF, 0xFF, 0xFF, 0xFF};
/**
* Linear interpolation between two colors
*/
Color interpolateColor(const Color& one, const Color& two, float percent);
/**
* Rotates a color n degrees
*/
Color rotateColor(const Color& in, float degrees);
/**
* Linear interpolation between two floats
*/
float linear(float start, float end, float percent);
/**
* Rotates a cartesian point around the origin
*/
Point rotateAroundOrigin(const Point& point, float rotation);
/**
* Converts score into a string
*
* TTT:%% where TTT is the current time in seconds, and %% is the percent
* through the current second.
*/
std::string getTime(float score);
/**
* Will pulse between 0.0 and 1.0 at the speed given (in tenths of a second).
* start is when the pulse should (have) start(ed).
*/
float getPulse(float frame, float range, float start);
/**
* Gets the current level that the score represents (for example, point)
* if the user is less than 10 seconds into the game)
*/
const char* getScoreText(int score, bool reduced);
/**
* Compares a fixed length string to an expected string in a file.
* (useful for checking both headers and footers)
*/
bool readCompare(std::istream& stream, const std::string& str);
/**
* Reads an integer from a file advancing its internal pointer
*/
int32_t read32(std::istream& stream, int32_t min, int32_t max, Platform& platform, const std::string& noun);
/**
* Reads a short from a file advancing its internal pointer
*/
int16_t read16(std::istream& stream);
/**
* Read a float from a file advancing its internal pointer
*/
float readFloat(std::istream& stream);
/**
* Reads a color from a file advancing its internal pointer
*/
Color readColor(std::istream& stream);
/**
* Reads a string from the binary file
*/
std::string readString(std::istream& stream, Platform& platform, const std::string& noun);
/**
* Writes a string with a length to a binary file
*/
void writeString(std::ostream& stream, const std::string& str);
}
#endif //SUPER_HAXAGON_STRUCTS_HPP
| true |
9f712211102b7c3e132d0d1c78dffdbc65516e45 | C++ | watchpoints/weekly | /leetcode/code/2022/7.toHex.cpp | UTF-8 | 950 | 3.71875 | 4 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <map>
using namespace std;
//C++ LeetCode 405 数字转换为十六进制(位运算)
//https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/
class Solution {
public:
string toHex(int num)
{
if(num==0)
return "0";
string hex={"0123456789abcdef"};
string res="";
int p=-1;
if(num<0)
p=8; //负数右移8次
while(num)
{
if(p==0)
break;
int c=num & 0x0000000f;//每次取低4位
cout << "num & 0x0000000f>>:" << c << "hex[c]="<<hex[c]<< endl;
res=hex[c]+res;
num>>=4;
cout << "num>>:" << num << endl;
p--;
}
return res;
}
};
//g++ -std=c++11 7.toHex.cpp
int main()
{
//bin:0001 0010
//hex:12
//dec:18
//18(十进制) = 10010(二进制)
Solution test;
cout<< test.toHex(18)<<endl;
}
| true |
f2340d65ccf48c2ac413278e2802e2804dc1db87 | C++ | hugh-tong/Cpp-Learning-1 | /20190522/main.cpp | GB18030 | 2,736 | 3.15625 | 3 | [] | no_license | #include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include "tinyxml2.h"
#include <regex>
using namespace std;
using namespace tinyxml2;
class information
{
public:
information() {}
~information() {}
public:
string title;
string link;
string description;
string content;
};
void traverse(vector<information>& _vector) {
ofstream _ostream("result.dat", ofstream::app);
auto _begin = _vector.begin();
auto _end = _vector.end();
regex re("<[^>]*>");
++_begin;
static int count = 1;
while (_begin != _end) {
_ostream << "<doc>" << endl;
_ostream << "<docid>" << count++ << "</docid>" << endl;
_ostream << "<title>" << _begin->title << "</title>" << endl;
_ostream << "<link>" << _begin->link << "</link>" << endl;
_ostream << "<description>" << regex_replace(_begin->description, re, "") << "</description>" << endl;
_ostream << "<content>" << regex_replace(_begin->content, re, "") << "</content>" << endl;
_ostream << "</doc>" << endl;
++_begin;
}
}
int main() {
vector<information> info_vec;
//½һXMLDocument
XMLDocument docXml;
//öLoadFileļظerrXML
XMLError errXml = docXml.LoadFile("coolshell.xml");
//װسɹ
if (XML_SUCCESS == errXml)
{
//ȡXMLrootڵ
XMLElement* elmtRoot = docXml.RootElement();
//ȡelementRootڵµһΪ"channel"ӽڵ
XMLElement* channel = elmtRoot->FirstChildElement("channel");
//ȡchannelڵµһΪ"title"ӽڵ
XMLElement* title = channel->FirstChildElement("title");
//ȡchannelڵµһΪ"description"ӽڵ
XMLElement* description = channel->FirstChildElement("description");
//ȡchannelڵµһΪ"FirstChildElement"ӽڵ
XMLElement* item = channel->FirstChildElement("item");
while (item) {
information tmp;
XMLElement *item_child = item->FirstChildElement();
while (item_child) {
if (strcmp(item_child->Name(), "title") == 0) {
tmp.title.clear();
tmp.title.append(item_child->GetText());
}
else if (strcmp(item_child->Name(), "link") == 0) {
tmp.link.clear();
tmp.link.append(item_child->GetText());
}
else if (strcmp(item_child->Name(), "description") == 0) {
tmp.description.clear();
tmp.description.append(item_child->GetText());
}
else if (strncmp(item_child->Name(), "content", 7) == 0) {
tmp.content.clear();
tmp.content.append(item_child->GetText());
}
item_child = item_child->NextSiblingElement();
}
info_vec.push_back(tmp);
item = item->NextSiblingElement();
}
}
traverse(info_vec); //ļ
}
| true |