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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9618fae7fff8682df1565ca89a3604c883678337 | C++ | Tudor67/Competitive-Programming | /LeetCode/Problems/Algorithms/#15_3Sum_sol4_binary_search_O(N^2logN)_928ms_19.9MB.cpp | UTF-8 | 1,090 | 3.296875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> answer;
for(int i = 0; i < nums.size(); ++i){
if(i > 0 && nums[i - 1] == nums[i]){
// Ignore duplicate triplets with the same first element
continue;
}
for(int j = i + 1; j < nums.size(); ++j){
if(j > i + 1 && nums[j - 1] == nums[j]){
// Ignore duplicate triplets with the same first & second element
continue;
}
int complement = -(nums[i] + nums[j]);
if(nums[j] <= complement){
vector<int>::iterator it = lower_bound(nums.begin() + j + 1, nums.end(), complement);
if(it != nums.end() && *it == complement){
answer.push_back({nums[i], nums[j], complement});
}
}
}
}
return answer;
}
}; | true |
51d39ef3bc31ad652c0c5bfc522cbdd38cd23b54 | C++ | LL-CH/LL | /多数元素/多数元素/test2.cpp | UTF-8 | 569 | 2.71875 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
using namespace std;
int main(){
string str;
while(getline(cin,str)){
vector<int> v;
for(size_t i=0;i<str.size();i++){
if(str[i]!=' ')
v.push_back(str[i]-'0');
}
map<int,int> mi;
for(auto e:v){
mi[e]++;
}
int ret=v[0];
for(size_t i=0;i<v.size();i++){
if(mi[v[i]]>mi[ret])
ret=v[i];
}
cout<<ret<<endl;
}
return 0;
} | true |
c01c0e1c239c3b1d6294dca42107b138c5aa303a | C++ | jinkyongpark/practicealgorithm | /Code/점심식사시간(더확실) - solok2.cpp | UTF-8 | 2,640 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAX = 15;
struct PI {
int x, y;
};
int area[MAX][MAX];
PI person[MAX], stair[MAX];
bool check[MAX];
int personN = 0, stairN = 0;
int testCase, n; // 원자갯수
int stairInfo1[MAX], stairInfo2[MAX];
int mintime = 987987987;
int s1, s2;
void calcDistance() {
int sx = stair[0].x, sy = stair[0].y;
for (int p = 0; p < personN; p++) {
int d = int(abs(sx - person[p].x)) + int(abs(sy - person[p].y));
stairInfo1[p] = d;
}
s1 = area[sx][sy];
sx = stair[1].x, sy = stair[1].y;
for (int p = 0; p < personN; p++) {
int d = int(abs(sx - person[p].x)) + int(abs(sy - person[p].y));
stairInfo2[p] = d;
}
s2 = area[sx][sy];
}
void dfs(int idx) {
if (idx >= personN) {
int first[MAX], ffront = 0, frear = 0;
int second[MAX], sfront = 0, srear = 0;
int stair1[100], stair2[100];
int onefront = 0, onerear = 0, twofront = 0, tworear = 0;
for (int i = 0; i < personN; i++) {
if (!check[i])
first[frear++] = stairInfo1[i]+1;
else
second[srear++] = stairInfo2[i]+1;
}
int fn = frear, sn = srear;
sort(first, first + fn);
sort(second, second + sn);
int t ;
for (t = 1; ; t++) {
for (int i = onefront; i<onerear; i++) {
if (t >= stair1[i]) {
onefront++;
fn--;
}
}
for (int i = ffront; i < frear; i++) {
if (onerear - onefront >= 3) break;
if (t >= first[ffront]) {
stair1[onerear++] = (t + s1);
ffront++;
}
}
for (int i = twofront; i<tworear; i++) {
if (t >= stair2[i]) {
twofront++;
sn--;
}
}
for (int i = sfront; i < srear; i++) {
if (tworear-twofront >= 3) break;
if (t >= second[sfront]) {
stair2[tworear++] = t + s2;
sfront++;
}
}
if ( fn<=0 && sn<=0)
break;
}
mintime = min(mintime, t);
return;
}
else {
check[idx] = false;
dfs(idx + 1);
check[idx] = true;
dfs(idx + 1);
}
}
int main() {
scanf_s("%d", &testCase);
for (int tt = 1; tt <= testCase; tt++) {
scanf_s("%d", &n);
mintime = 987987987;
personN = 0, stairN = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf_s("%d", &area[i][j]);
if (area[i][j] == 1) person[personN++] = { i,j };
else if(area[i][j] >= 2) stair[stairN++] = { i,j };
}
}
calcDistance();
dfs(0);
printf("#%d %d\n", tt, mintime);
for (int i = 0; i < personN; i++) person[i] = { 0,0 };
for (int i = 0; i < stairN; i++) stair[i] = { 0,0 };
}
return 0;
} | true |
c70fb6aede79c75e639ab5763cc0246790f3ee08 | C++ | DanielRLowe/cliqueR | /src/paraclique_cp/Clique_Test2.cpp | UTF-8 | 553 | 2.65625 | 3 | [] | no_license | #include "Clique_Test2.h"
bool Edge_Test::operator() (const Graph::Vertices &v, int min_size, int node)
const
{
if (node != -1)
{
cerr << "Error - edge test called with specific node." << endl;
exit(EXIT_FAILURE);
}
int degree_sum = 0;
const int degree_sum_needed = min_size * (min_size - 1);
Graph::Vertices::Vex_ptr vp(v);
for (; !vp.end(); ++vp)
{
degree_sum += v.degree(*vp);
if (degree_sum >= degree_sum_needed) return 0;
}
return 1;
}
| true |
340cd0dc6e01ca1495c44f6d714c4db110b3d380 | C++ | joshuabezaleel/cp | /tokilearning/TOKI PI Day Contest/penguji.cpp | UTF-8 | 3,452 | 2.796875 | 3 | [] | no_license | /*
Author: Risan
Some part of the code taken from penguji.cpp, TOKI Open Contest December 2012
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <sstream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
#define MAXROW 100
#define MAXCOL 100
#define MAXK 10000
#define MAXELEMENT 1000
#define MAGICNUMBER 10000000
int nrows, ncols, K;
int M[MAXROW + 5][MAXCOL + 5];
int strToInt(char *s) {
int ret;
stringstream ss(s);
if (!(ss >> ret)) return -1;
if (ret < 0) return -1;
return ret;
}
int getRandom(int lbound, int rbound) {
return rand() % (rbound - lbound + 1) + lbound;
}
void generateInputFile(int seed) {
srand(seed);
FILE *fin = fopen("tukar.in", "w");
nrows = getRandom(1, MAXROW);
ncols = getRandom(1, MAXCOL);
K = getRandom(1, MAXK);
fprintf(fin, "%d %d %d\n", nrows, ncols, K);
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
if (j > 0) fprintf(fin, " ");
M[i][j] = getRandom(0, MAXELEMENT);
fprintf(fin, "%d", M[i][j]);
}
fprintf(fin, "\n");
}
fclose(fin);
}
bool execute(char *sol, int seed) {
cout << "Menjalankan kasus uji dengan umpan = " << seed << " ..." << endl;
cout << "banyak baris = " << nrows << endl;
cout << "banyak kolom = " << ncols << endl;
cout << "K = " << K << endl;
if (system((string() + sol + " < tukar.in > tukar.out").c_str())) {
cout << "Program solusi Anda mengalami kesalahan!" << endl;
return false;
} else {
return true;
}
}
bool valid(int r, int c) {
return r >= 1 && r <= nrows && c >= 1 && c <= ncols;
}
bool adjacent(int r1, int c1, int r2, int c2) {
return ((r1 == r2) && abs(c1 - c2) == 1) || ((c1 == c2) && abs(r1 - r2) == 1);
}
int grade() {
try {
ifstream sol;
sol.open("tukar.out");
int Y;
if (!(sol >> Y)) {
cout << "Keluaran program solusi Anda tidak sesuai format!" << endl;
return 0;
}
if (Y < 0) {
cout << "Y harus bilangan bulat nonnegatif!" << endl;
return 0;
}
for (int i = 0; i < Y; i++) {
int r1, c1, r2, c2;
if (!(sol >> r1 >> c1 >> r2 >> c2)) {
cout << "Keluaran program solusi Anda tidak sesuai format!" << endl;
return 0;
}
if (!valid(r1, c1) || !valid(r2, c2) || !adjacent(r1, c1, r2, c2)) {
cout << "Sel yang dideskripsikan tidak valid!" << endl;
return 0;
} else {
swap(M[r1 - 1][c1 - 1], M[r2 - 1][c2 - 1]);
}
}
int ret = MAGICNUMBER;
for (int i = 0; i + 1 < nrows; i++) {
for (int j = 0; j + 1 < ncols; j++) {
ret -= abs(M[i + 1][j] - M[i][j]);
ret -= abs(M[i][j + 1] - M[i][j]);
}
}
sol.close();
return ret;
} catch(...) {
cout << "Keluaran program solusi Anda tidak sesuai format!" << endl;
return 0;
}
}
int main(int argc, char **argv) {
if (argc != 3) {
cout << "Pemakaian: penguji <umpan> <program>" << endl;
} else {
int seed;
if ((seed = strToInt(argv[1])) == -1) {
cout << "Seed must be a valid nonnegative integer" << endl;
} else {
generateInputFile(seed);
if (execute(argv[2], seed)) {
cout << "Nilai Anda = " << grade() << endl;
}
}
}
return 0;
}
| true |
f535571c8e132a122b3affe55e0ba5aee2497e0b | C++ | semicloud/QuakeAnalysis | /tec_api/timed_tensor.h | GB18030 | 4,245 | 3.03125 | 3 | [] | no_license | #pragma once
namespace tec_api
{
template <typename T = double, unsigned D = 2>
class __declspec(dllexport) timed_tensor
{
friend bool operator<(timed_tensor const& lhs, timed_tensor const& rhs)
{
return lhs.time() < rhs.time();
}
public:
timed_tensor() : time_(boost::posix_time::not_a_date_time), tensor_ptr_(nullptr) {}
timed_tensor(boost::posix_time::ptime time, std::shared_ptr<xt::xtensor<T, D>> tensor_ptr) : time_(time), tensor_ptr_(tensor_ptr) {}
timed_tensor(timed_tensor const& other) : time_(other.time_), tensor_ptr_(other.tensor_ptr_) {}
timed_tensor& operator=(timed_tensor const& rhs)
{
if (this == &rhs) return *this;
time_ = rhs.time_;
tensor_ptr_ = rhs.tensor_ptr_;
return *this;
}
~timed_tensor() = default;
boost::posix_time::ptime time() const { return time_; }
std::shared_ptr<xt::xtensor<T, D>> tensor_ptr() const { return tensor_ptr_; }
private:
boost::posix_time::ptime time_;
std::shared_ptr<xt::xtensor<T, D>> tensor_ptr_;
};
__declspec(dllexport) boost::posix_time::ptime __cdecl parse_time(boost::filesystem::path const&);
__declspec(dllexport) xt::xtensor<float, 2 > __cdecl load_tif(boost::filesystem::path const&);
/**
* \brief ʱ
* \tparam T ʱͣĬΪdouble
* \tparam D ʱάȣĬΪ2
*/
template<typename T = double, unsigned D = 2>
class __declspec(dllexport) timed_tensor_series
{
public:
timed_tensor_series() : timed_tensors_(std::vector<timed_tensor<T, D>>{}) {}
~timed_tensor_series() = default;
static timed_tensor_series load_from_files(std::vector<boost::filesystem::path> const&);
timed_tensor_series sub_series(size_t, size_t) const;
void add(timed_tensor<T, D> const&);
size_t size() const& { return timed_tensors_.size(); }
timed_tensor<T, D>& operator[](size_t);
std::vector<boost::posix_time::ptime> get_times() const;
xt::xtensor<T, D + 1> get_tensor_as_whole() const;
void sort();
private:
std::vector<timed_tensor<T, D>> timed_tensors_;
};
template <typename T, unsigned D>
void timed_tensor_series<T, D>::add(timed_tensor<T, D> const& tt)
{
timed_tensors_.push_back(tt);
}
template <typename T, unsigned D>
timed_tensor<T, D>& timed_tensor_series<T, D>::operator[](size_t idx)
{
return timed_tensors_.at(idx);
}
template <typename T, unsigned D>
std::vector<boost::posix_time::ptime> timed_tensor_series<T, D>::get_times() const
{
std::vector<boost::posix_time::ptime> times;
std::transform(timed_tensors_.cbegin(), timed_tensors_.cend(), std::back_inserter(times));
return times;
}
template <typename T, unsigned D>
xt::xtensor<T, D + 1> timed_tensor_series<T, D>::get_tensor_as_whole() const
{
if (timed_tensors_.empty())
throw std::runtime_error("timed_tensors is empty!");
std::vector<T> container;
const size_t C = timed_tensors_.size();
const size_t NROW = timed_tensors_.at(0).tensor_ptr()->shape(0);
const size_t NCOL = timed_tensors_.at(0).tensor_ptr()->shape(1);
for (timed_tensor<T, D> tt : timed_tensors_)
{
std::copy(tt.tensor_ptr()->template begin<xt::layout_type::row_major>(),
tt.tensor_ptr()->template end<xt::layout_type::row_major>(),
std::back_inserter(container));
}
xt::xarray<T> arr = xt::adapt(container);
arr.reshape({ C,NROW,NCOL });
return arr;
}
template <typename T, unsigned D>
void timed_tensor_series<T, D>::sort()
{
std::sort(timed_tensors_.begin(), timed_tensors_.end());
}
template <typename T, unsigned D>
timed_tensor_series<T, D> timed_tensor_series<T, D>::load_from_files(std::vector<boost::filesystem::path> const& paths)
{
timed_tensor_series series;
for (const boost::filesystem::path& path : paths)
{
boost::posix_time::ptime time = parse_time(path);
std::shared_ptr<xt::xtensor<T, D>> ptr = std::make_shared<xt::xtensor<T, 2>>(load_tif(path));
series.add(timed_tensor<T, D>(time, ptr));
}
series.sort();
return series;
}
template <typename T, unsigned D>
timed_tensor_series<T, D> timed_tensor_series<T, D>::sub_series(size_t start, size_t stop) const
{
timed_tensor_series<T, D> ans;
for (size_t i = start; i != stop + 1; ++i)
ans.add(timed_tensors_.at(i));
return ans;
}
}
| true |
59cc9993d83ab1a72fb8cc59690cfe0a65082bb4 | C++ | TheChernoCommunity/GameProject-0 | /src/Grid.cpp | UTF-8 | 1,128 | 3.265625 | 3 | [] | no_license | #include "Grid.h"
#include <iterator>
namespace ccm
{
// Grid Method Implementations
Grid::Grid(int x, int y, int w, int h, int columns, int rows)
: Grid(Rect{ x, y, w, h }, columns, rows)
{
}
Grid::Grid(const Rect& position, int columns, int rows)
: m_object(position, Color(128, 128, 128, 255)), m_numColumns(columns), m_numRows(rows)
{
int tileWidth = m_object.rect.w / columns;
int tileHeigh = m_object.rect.h / rows;
m_tiles.reserve(columns * rows);
for (int y = 0; y < m_numRows; ++y)
for (int x = 0; x < m_numColumns; ++x)
m_tiles.emplace_back(x * tileWidth + 1 + m_object.rect.x, y * tileHeigh + 1 + m_object.rect.y, tileWidth - 2, tileHeigh - 2);
}
Tile& Grid::getTile(int x, int y)
{
return m_tiles[y * m_numColumns + x];
}
const std::vector<Tile>& Grid::getTiles() const
{
return m_tiles;
}
int Grid::getWidth() const
{
return m_numColumns;
}
int Grid::getHeight() const
{
return m_numRows;
}
std::pair<int, int> Grid::getDimensions() const
{
return std::make_pair(m_numColumns, m_numRows);
}
const Object& Grid::draw() const
{
return m_object;
}
}
| true |
c13c00c8764fa196c8f72ccde3e86803bfb42463 | C++ | xiangsanliu/OperatingSystem | /storage_manage.h | GB18030 | 4,617 | 3.234375 | 3 | [] | no_license | //
// Created by xiang on 2017/12/12.
// 洢
//
#ifndef OPERATINGSYSTEM_STORAGE_MANAGE_H
#define OPERATINGSYSTEM_STORAGE_MANAGE_H
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#define MAX_LOOP 999
using namespace std;
typedef struct {
int start_index;
int size;
}Memory;
typedef struct {
int flag;
int memory;
int start_index;
}Process;
vector<Memory> memoryList;
vector<Process> processList;
int n;
void printProcess();
void printMemory();
bool sortByStartIndex(Memory m1, Memory m2){
return m1.size < m2.size;
}
//״Ӧ㷨
void assign_ff(Process *process) {
for (unsigned int i=0 ; i < memoryList.size(); i++ ) {
if (process->memory == memoryList.at(i).size) { //պõڵǰռ
process->start_index = memoryList.at(i).start_index;
process->flag = 1;
memoryList.erase(memoryList.cbegin()+i); //ӿռɾ
return;
} else if (process->memory < memoryList.at(i).size) {
process->start_index = memoryList.at(i).start_index; //ǰռռ
memoryList.at(i).start_index += process->memory;
process->flag = 1;
memoryList.at(i).size -= process->memory;
return;
}
}
cout<<"ʧ"<<endl<<endl;
}
//
void recycle(Process process) {
Memory memory{};
memory.start_index = process.start_index;
memory.size = process.memory;
memoryList.push_back(memory);
sort(memoryList.begin(), memoryList.end(), sortByStartIndex); //ݷʼλ
int size = 0;
for (unsigned int i=0 ;i<memoryList.size()-1; i++) { //ڴ
if (memoryList.at(i).start_index+memoryList.at(i).size == memoryList.at(i+1).start_index) {
memoryList.at(i).size += memoryList.at(i+1).size;
memoryList.erase(memoryList.cbegin()+i+1);
}
}
cout<<"ճɹ"<<endl<<endl;
}
//Ӧ㷨
void assign_bf(Process *process) {
int di = 65535;
unsigned int index = 0;
for (unsigned int i=0; i< memoryList.size(); i++) {
if (memoryList.at(i).size - process->memory < di) {
di = memoryList.at(i).size - process->memory;
index = i;
}
}
if (di == 0) {
process->start_index = memoryList.at(index).start_index;
process->flag = 1;
memoryList.erase(memoryList.cbegin()+index);
} else if (di > 0) {
process->start_index = memoryList.at(index).start_index;
memoryList.at(index).start_index += process->memory;
process->flag = 1;
memoryList.at(index).size -= process->memory;
} else {
cout<<"ʧ"<<endl;
}
}
void domain() {
Memory first{
0, 1024
};
memoryList.push_back(first);
cout<<"ĸ";
cin>>n;
cout<<"ڴռ䣺";
for (int i=0 ;i<n; i++) {
Process process{};
process.flag = 0;
process.start_index = -1;
cin>> process.memory;
processList.push_back(process);
}
printProcess();
printMemory();
cout<<"ѡ,״Ӧ㷨call 1Ӧ㷨call2:"<<endl;
int fun;
cin>>fun;
for (int i=0; i<MAX_LOOP; i++) {
cout<<"ѡţ";
unsigned int index;
cin>>index;
if (processList.at(index).flag==0) {
if (fun==1) {
assign_ff(&processList.at(index)); //ʹ״Ӧ㷨
} else if (fun==2) {
assign_bf(&processList.at(index)); //ʹӦ㷨
} else {
return;
}
printProcess(); //ӡ
printMemory(); //ӡ洢ռ
} else {
recycle(processList.at(index));
printProcess(); //ӡϢ
printMemory(); //ӡ洢ռϢ
}
}
}
void printProcess() {
cout<<"ҪĿռ"<<'\t'<<"̷״̬"<<'\t'<<"ռʼλ"<<endl;
for (auto & item:processList) {
cout<<item.memory<<'\t'<<item.flag<<'\t'<<item.start_index<<endl;
}
cout<<endl;
}
void printMemory() {
cout<<"ռʼλ"<<"\t"<<"ռС"<<endl;
for (auto &item: memoryList) {
cout<<item.start_index<<"\t"<<item.size<<endl;
}
cout<<endl;
}
#endif //OPERATINGSYSTEM_STORAGE_MANAGE_H
| true |
2e798af1dadf6b45ef935105f02faee1379258d5 | C++ | wma1729/simple-n-fast | /http/include/common/scanner.h | UTF-8 | 1,584 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef _SNF_HTTP_CMN_SCANNER_H_
#define _SNF_HTTP_CMN_SCANNER_H_
#include <string>
#include <istream>
#include <vector>
#include <utility>
namespace snf {
namespace http {
using param_vec_t = std::vector<std::pair<std::string, std::string>>;
/*
* Scanner for HTTP messages.
*/
class scanner
{
private:
size_t m_cur;
size_t m_len;
const std::string &m_str;
int get() { return (m_cur < m_len) ? m_str[m_cur++] : -1; }
void unget() { if (m_cur < m_len) m_cur--; }
int peek() { return (m_cur < m_len) ? m_str[m_cur] : -1; }
public:
scanner() = delete;
/*
* Initializes the scanner with the input string.
* @param [in] is - reference to the input stream.
*/
scanner(const std::string &s)
: m_cur{0}, m_len{s.size()}, m_str{s} {}
scanner(const std::string &s, size_t start, size_t len)
: m_cur{start}, m_len{len}, m_str{s} {}
~scanner() {}
bool read_space();
bool read_opt_space();
bool read_special(int);
bool read_crlf();
bool read_token(std::string &, bool lower = true);
bool read_uri(std::string &);
bool read_version(std::string &);
bool read_status(std::string &);
bool read_reason(std::string &);
bool read_qstring(std::string &);
bool read_comments(std::string &);
bool read_parameters(param_vec_t &);
bool read_chunk_size(size_t *);
bool read_path_parameter(std::string &, std::string &);
bool read_all(std::string &);
};
bool readline(std::istream &, std::string &);
bool read(std::istream &, char *, int, int *);
} // namespace http
} // namespace snf
#endif // _SNF_HTTP_CMN_SCANNER_H_
| true |
82040d254e83ffc9bc770f883a72117f2c536066 | C++ | david30907d/Online-judge | /UVA/AC/d19-11462AgeSort.cpp | BIG5 | 566 | 3.015625 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<stdio.h>
using namespace std;
int main(){
int num,input,age[101];
while((scanf("%d",&num)==1)&&num){//scanfn\JBnum=0
memset(age,0,sizeof(age));
for(int i=0;i<num;i++){
scanf("%d",&input);
age[input]++;//age[]ƦrNӦ~֪
}
int first=1;//Xfirst=1ܨSXL
for(int i=1;i<100;i++){
for(int j=1;j<=age[i];j++){
if(!first){
printf(" ");
}
first=0;
printf("%d",i);
}
}
cout<<endl;
}
return 0;
}
| true |
3a14da2f03c59ff506b53d71ca908626dc146253 | C++ | Beedle/Prosjekt | /Prosjekt/Rom.cpp | WINDOWS-1252 | 2,861 | 3.375 | 3 | [] | no_license | #include "Header.h"
using namespace std;
//constructor, sender ID videre
Rom::Rom(int ID, ifstream &file):Num_element(ID){
//lager en ny liste med reservasjoner
reservasjoner = new List(Sorted);
//leser inn antallet reservasjoner og reservasjonene
int trash;
int resID;
Reservasjon *res;
file >> trash; file.ignore();
for(int x = 1; x <= trash; x++){
file >> resID;
res = new Reservasjon(resID, file);
reservasjoner->add(res);
}
//leser inn antall senger for rommet og om frokost er inkludert
file >> antSenger >> inklFrokost;
}
//viser data
void Rom::display(bool all){
cout << "\n\nRomnummer: " << number << endl;
cout << "\tAntall senger: " << antSenger << endl;
cout << "\tFrokost er ";
if(!inklFrokost) cout << "ikke ";
cout << "inkludert" << endl;
//dersom alle reservasjonene skulle vre med.
Reservasjon *temp;
if (all)
{
for (int x = 1; x <= reservasjoner->no_of_elements(); x ++){
temp = (Reservasjon*)reservasjoner->remove_no(x);
reservasjoner->add(temp);
temp->display(all);
}
}
}
//skriver til fil.
void Rom::toFile(ofstream &file){
//romnummer og antallet reservasjoner.
file << number << " " << reservasjoner->no_of_elements() << endl;
//skriver reservasjoner til fil.
Reservasjon *temp;
for(int x = 1; x <= reservasjoner->no_of_elements(); x++){
//fjerner og legger til reservasjonen, og skriver s til fil.
temp = (Reservasjon*)reservasjoner->remove_no(x);
reservasjoner->add(temp);
temp->tofile(file);
}
//antallet senger og om frokost er inkludert.
file << antSenger << " " << inklFrokost;
}
bool Rom::finnReservasjon(string navn, int dato)
{
//hjelpedata
Reservasjon *temp;
bool returnVal = false;
//kjr til du er i slutten av listen.
for (int x = 1; x <= reservasjoner->no_of_elements(); x++)
{
//fjerner og legger til igjen reservasjonsobjektet for f pekeren
temp = (Reservasjon*)reservasjoner->remove_no(x);
reservasjoner->add(temp);
if (navn == temp->getNavn() && dato == temp->getAnkomst())
{
//hvis navn og dato passer, returner true.
returnVal = true;
}
}
return returnVal;
}
//returnerer listen i klassen.
List* Rom::getlist(){
return reservasjoner;
}
//returnerer romnummer
int Rom::getid(){
return number;
}
//returnerer antallet senger
int Rom::getsenger(){
return antSenger;
}
void Rom::replaceList(List* liste)
{
reservasjoner = liste;
}
void Rom::innsjekk(string navn, int dato)
{
//hjelpedata
Reservasjon *temp;
//kjr til du er i slutten av listen.
for (int x = 1; x <= reservasjoner->no_of_elements(); x++)
{
//fjerner reservasjonsobjektet
temp = (Reservasjon*)reservasjoner->remove_no(x);
if (navn == temp->getNavn() && dato == temp->getAnkomst())
{
//hvis navn og dato passer, kjr innskjekk p reservasjonen.
temp->innsjekk();
}
reservasjoner->add(temp);
}
} | true |
56c5d6a218c29971869d91d49077140d46b900e9 | C++ | jimpix/msbot | /Pixel.h | UTF-8 | 1,744 | 3.875 | 4 | [] | no_license | // header file for Pixel.cpp
#ifndef PIXEL_CLS
#define PIXEL_CLS
#include <iostream>
using namespace std;
// a class representing a sequence of RGB values; begins with blue because BMP format orders intensities in BGR order
class Pixel {
private:
unsigned char blue;
unsigned char green;
unsigned char red;
public:
// default constructor does nothing
inline Pixel() {}
// constructor with args specifying color intensities
inline Pixel(const unsigned char B, const unsigned char G, const unsigned char R) : blue(B), green(G), red(R) { }
// overloads operator== to compare two Pixel objects
inline bool operator==(const Pixel& p) const {
return (red == p.red && green == p.green && blue == p.blue);
}
// calculate squared euclidean distance (SED) of two pixels with THIS pixel, which approximates the "distance" between two pixels, and hence the difference between their intensities
// returns the Pixel that matches the closest with current one based on the SED
inline Pixel match(const Pixel& p, const Pixel& p2) const {
if (sed(p) < sed(p2)) {
return p;
} else
return p2;
}
// computes squared euclidean distance between P and THIS pixel, then returns the result
inline int sed(const Pixel& p) const {
int sed = (p.blue - blue) * (p.blue - blue);
sed += (p.red - red) * (p.red - red);
sed += (p.green - green) * (p.green - green);
return sed;
}
// returns true iff Pixel is white
inline bool isWhite() const {
return (255 == red == green == blue);
}
// displays char values of THIS pixel object
inline void display() const {
wcout << "red: " << (unsigned int) red << endl;
wcout << "green: " << (unsigned int) green << endl;
wcout << "blue: " << (unsigned int) blue << endl;
}
};
#endif
| true |
339ae169e86abe3ba4f70ccd2eb80b4a4ee6bf6b | C++ | bpfel/windows | /Software/CameraHandler/camera_handler.cpp | UTF-8 | 2,990 | 3.109375 | 3 | [] | no_license | #include "camera_handler.hpp"
//Constructor
CameraHandler::CameraHandler(){
this->showTriangulationPoint = false;
this->showFaceOrientation = false;
frame = cv::Mat::zeros(1,1,cv::DataType<double>::type);
}
//COnstructor for visualization purposes
CameraHandler::CameraHandler(bool showTriangulation, bool showFaceOrientation){
this->showTriangulationPoint = showTriangulation;
this->showFaceOrientation = showFaceOrientation;
frame = cv::Mat::zeros(1,1,cv::DataType<double>::type);
}
//Rotate the image so that it is correctly positioned
void CameraHandler::OrientView (){
#ifdef CMOUNT_INVERTED
flip(frame, frame, -1);
#endif
}
//Open the camera, set resolution and focus with the given ID
bool CameraHandler::OpenCamera(int cameraID){
try
{
cap = VideoCapture(cameraID);
if (!cap.isOpened())
{
cerr << "Unable to connect to camera" << endl;
return false;
}
SetResolution();
SetFocus();
return true;
}
catch(exception& e)
{
cout << e.what() << endl;
return false;
}
}
//Return the next camera frame in the correct orientation
Mat CameraHandler::ObtainNextFrame(){
if(cap.isOpened()){
// Grab a frame
if ( !cap.read(frame) ){ // the camera might need some warmup
std::cout<<"No read frame"<<std::endl;
}
else{
//Rotate the frame by 180deg
OrientView();
}
}
else{
std::cout<<"Camera not opened"<<std::endl;
}
return frame;
}
//Returns the image with the visualized face orientation and triangulation point
Mat CameraHandler::VisualizePointAndOrientation(Point2d faceOrientationOrigin, Point2d faceOrientationEnd, Point2d triangPoint){
if(showFaceOrientation){
cv::line(frame,faceOrientationOrigin, faceOrientationEnd, cv::Scalar(255,0,0), 2);
}
if(showTriangulationPoint){
cv::circle(frame, triangPoint, 3, cv::Scalar(0,0,255), -1);
}
return frame;
}
//Returns the image with the visualized triangulation point
Mat CameraHandler::VisualizePoint(Point2d triangPoint){
if(showTriangulationPoint){
cv::circle(frame, triangPoint, 3, cv::Scalar(0,0,255), -1);
}
return frame;
}
//Sets the camera resolution
void CameraHandler::SetResolution(){
//if defined set the camera to the desired resolution
#if RESOLUTION==1080
this->cap.set(CAP_PROP_FRAME_WIDTH, 1920);
this->cap.set(CAP_PROP_FRAME_HEIGHT, 1080);
#elif RESOLUTION==720
this->cap.set(CAP_PROP_FRAME_WIDTH, 1280);
this->cap.set(CAP_PROP_FRAME_HEIGHT, 720);
#elif RESOLUTION==480
this->cap.set(CAP_PROP_FRAME_WIDTH, 858);
this->cap.set(CAP_PROP_FRAME_HEIGHT, 480);
#elif RESOLUTION==360
this->cap.set(CAP_PROP_FRAME_WIDTH, 480);
this->cap.set(CAP_PROP_FRAME_HEIGHT, 360);
#endif
}
//Sets the camera focus
void CameraHandler::SetFocus(){
this->cap.set(CAP_PROP_AUTOFOCUS, false);
this->cap.set(CAP_PROP_FOCUS, 0);
}
//Release the oppened camera
CameraHandler::~CameraHandler(){
this->cap.release();
}
| true |
0901d95d70dc488ea4b2968994839a514036cb83 | C++ | shradheyt/Monkfox-Training | /Day 3/RecursivePowerFunction.cpp | UTF-8 | 260 | 3.203125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
using namespace std;
int pow(int a, int b)
{
if(b == 1)
return a;
int m = b/2;
if ( b%2 == 0)
return pow( a, m) * pow( a, m);
return pow( a, m) * pow( a, m+1);
}
int main()
{
int p = pow(3,4);
cout << p;
} | true |
2ee611fe8fb9aabbf77428807ca50930d32cea64 | C++ | fendou1997/devsim | /src/math/TimeData.hh | UTF-8 | 1,816 | 2.53125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /***
DEVSIM
Copyright 2013 Devsim LLC
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 TIMEDATA_HH
#define TIMEDATA_HH
#include <vector>
#include <cstddef>
enum class TimePoint_t {TM0 = 0, TM1, TM2};
template <typename DoubleType>
class TimeData
{
public:
static TimeData &GetInstance();
static void DestroyInstance();
void SetI(TimePoint_t, const std::vector<DoubleType> &);
void SetQ(TimePoint_t, const std::vector<DoubleType> &);
//// from -> to
void CopyI(TimePoint_t, TimePoint_t);
void CopyQ(TimePoint_t, TimePoint_t);
void ClearI(TimePoint_t);
void ClearQ(TimePoint_t);
void AssembleI(TimePoint_t, DoubleType, std::vector<DoubleType> &);
void AssembleQ(TimePoint_t, DoubleType, std::vector<DoubleType> &);
bool ExistsI(TimePoint_t tp)
{
return !IData[static_cast<size_t>(tp)].empty();
}
bool ExistsQ(TimePoint_t tp)
{
return !QData[static_cast<size_t>(tp)].empty();
}
private:
TimeData();
TimeData(TimeData &);
TimeData &operator=(TimeData &);
~TimeData();
static TimeData *instance;
std::vector<std::vector<DoubleType > > IData;
std::vector<std::vector<DoubleType > > QData;
};
#endif
| true |
547d7e6b5722c94d68c969ff2d84fd0b8fc501af | C++ | LuisLuettgens/motion_primitives | /external/transworhp/src/imaging/imageformat.cpp | UTF-8 | 1,588 | 2.875 | 3 | [] | no_license | #ifdef WIN32
#include "windows.h"
#endif
#include "imageformat.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
ImageFormat* ImageFormat::newFormat(const std::string &filename) {
//std::cout << "newFormat(" << filename << ")" << std::endl;
std::string suffix = filename.substr(filename.length()-3);
//std::cout << suffix << std::endl;
ImageFormat *ret=nullptr;
/* if (suffix == "png") {
ret = new PNGImageFormat(filename);
} else if (suffix == "tif") {
ret = new TIFFImageFormat(filename);
} else if (suffix == "gif") {
ret = new GIFImageFormat(filename);
} else if (suffix == "bmp") {
ret = new BMPImageFormat(filename);
} else if (suffix == "jpg" || suffix == "jpeg" || suffix == "JPG" || suffix == "JPEG") {
ret = new JPEGImageFormat(filename);
}*/
return ret;
}
ImageFormat::ImageFormat() : data(nullptr), type("") {}
ImageFormat::ImageFormat(const std::string &t) : data(nullptr), type(t) {}
ImageFormat::ImageFormat(const std::string &f_name, const std::string &t)
: data(nullptr), filename(f_name), type(t) {}
ImageFormat::~ImageFormat() {
delete [] data;
}
bool ImageFormat::Read() {
return false;
}
bool ImageFormat::Write(GLubyte */*p*/) {
return false;
}
color4 ImageFormat::Get(int x, int y) {
color4 ret;
if (data) {
unsigned char *c = &data[(x+y*width)*depth];
if (depth==4) {
ret = color4(*c/256.f,*(c+1)/256.f,*(c+2)/256.f,*(c+3)/256.f);
}
if (depth==3) {
ret = color4(*c/256.f,*(c+1)/256.f,*(c+2)/256.f);
}
if (depth==1) {
ret = color4(1,1,1,*(c)/256.f);
}
}
return ret;
}
| true |
cc69ab5b6a4bf4b59af03447bb2f907ba6202b06 | C++ | takahiro1127/LearningGo | /atcoder/begginersContest/5月31日/d.cpp | UTF-8 | 789 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<map>
using namespace std;
typedef unsigned long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
ll kount(ll cou) {
ll index = 0;
for (ll i = 1; ;i++) {
if (cou < i) {
break;
} else {
cou -= i;
index++;
}
}
return index;
}
map<ll, ll> prime_factor(ll n) {
map< ll, ll > ret;
for(ll i = 2; i * i <= n; i++) {
while(n % i == 0) {
ret[i]++;
n /= i;
}
}
if(n != 1) ret[n] = 1;
return ret;
}
int main() {
ll n, c;
map<ll, ll> count;
cin >> n;
count = prime_factor(n);
ll cc = 0;
for (map<ll, ll>::iterator i = count.begin(); i != count.end(); ++i){
cc += kount(i->second);
}
cout << cc << endl;
}
| true |
42bd9d8de15116d9366b8faf50309e8520b64b8f | C++ | Mani5871/C-Algos | /BackTracking/RatMaze.cpp | UTF-8 | 1,409 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool isSafe(int **arr, int x, int y, int n)
{
if(x <= n && y <= n && arr[x][y] == 1)
return true;
return false;
}
bool Rat(int **arr, int x, int y, int **sol, int n)
{
if(x == n - 1 && y == n - 1)
{
sol[x][y] = 1;
return true;
}
if(isSafe(arr, x, y, n))
{
sol[x][y] = 1;
if(Rat(arr, x, y + 1, sol, n))
return true;
if(Rat(arr, x + 1, y, sol, n))
return true;
sol[x][y] = 0;
return false;
}
}
int main()
{
int n;
cin >> n;
int i, j, k;
int ** a = new int *[n];
for(i = 0; i < n; i ++)
{
a[i] = new int[n];
}
for(i = 0; i < n; i ++)
for(j = 0; j < n; j ++)
cin >> a[i][j];
int ** sol = new int *[n];
for(i = 0; i < n; i ++)
{
sol[i] = new int[n];
}
for(i = 0; i < n; i ++)
for(j = 0; j < n; j ++)
sol[i][j] = 0;
if(Rat(a, 0, 0, sol, n))
{
cout << "Rat Escaped" << endl;
for(i = 0; i < n; i ++)
{
for(j = 0; j < n; j ++)
cout<<sol[i][j] << " ";
cout << endl << " ";
}
}
else
cout <<"Rat not escaped" << endl;
}
| true |
571d858ef329788de0491038d6dfd85c76587071 | C++ | shinjeongmin/Baekzoon-Online-judge | /cpp/14442.cpp | UHC | 1,921 | 3 | 3 | [] | no_license | #include<iostream>
#include<string>
#include <queue>
using namespace std;
const int MAX = 1000;
typedef struct {
int y, x;
}Dir;
Dir moveDir[4] = { {1,0},{-1,0},{0,1}, {0,-1} };
int N, M, K;
int graph[MAX][MAX];
int cache[MAX][MAX][10+1]; // 11 ձ
int BFS() {
queue<pair<pair<int, int>, int>>q; //y, x, ձ
q.push(make_pair(make_pair(0, 0), K)); // , ձ
cache[0][0][K] = 1; // 湮 ó
while (!q.empty()) {
int y = q.front().first.first;
int x = q.front().first.second;
int block = q.front().second;
q.pop();
// ϸ
if (y == N - 1 && x == M - 1) // ε 0,0 ̹Ƿ -1
return cache[y][x][block]; // ϴ ĭ
for (int i = 0; i < 4; i++) {
int nextY = y + moveDir[i].y;
int nextX = x + moveDir[i].x;
if (0 <= nextY && nextY < N &&
0 <= nextX && nextX < M) {
// ְ, 10 ʾҴٸ, 湮 ʾҴٸ
if (graph[nextY][nextX] == 1 && block > 0 && cache[nextY][nextX][block] == 0) {
cache[nextY][nextX][block - 1] = cache[y][x][block] + 1; // հ ̵
q.push(make_pair(make_pair(nextY, nextX), block - 1)); // ̵ ڸ ť ֱ ( ձ Ҹ)
}
// 湮 ʾҴ ̶
else if (graph[nextY][nextX] == 0 && cache[nextY][nextX][block] == 0) {
cache[nextY][nextX][block] = cache[y][x][block] + 1; // ڸ 湮 ó
q.push(make_pair(make_pair(nextY, nextX), block)); // ̵ ڸ ť ֱ ( ձ δ )
}
}
}
}
return -1;
}
int main() {
ios_base::sync_with_stdio;
cin.tie(0);
cin >> N >> M >> K;
for (int i = 0; i < N; i++) {
string temp;
cin >> temp;
for (int j = 0; j < M; j++)
graph[i][j] = temp[j] - '0';
}
cout << BFS() << "\n";
return 0;
} | true |
a2257ae90b5dca4dbee4a5e1f036966a754ead78 | C++ | RickAtCodeMojo/Patterns | /CMMahjongSpike/CMTileState.cpp | UTF-8 | 3,890 | 2.515625 | 3 | [] | no_license | //
// CMTileState.cpp
// CMDesignPatterns
//
// Created by Richard Dalley on 2017-09-07.
// Copyright © 2017 CodeMojo. All rights reserved.
//
#include "CMTileState.h"
#include "CMTile.h"
CMTileState* CMMahjongState::handleAction(CMTile* tile, CMTileAction action){
return nullptr;
}
void CMMahjongState::update(CMTile* tile){
}
CMTileState* CMMeldState::handleAction(CMTile* tile, CMTileAction action){
switch (action) {
case CMTileAction::Kong:{
if (tile->meldKind() == CMMeldKind::Pung) {
tile->meld(CMMeldKind::Kong);
return new CMMeldState();
}
}
break;
case CMTileAction::Rob:{
if (tile->meldKind() == CMMeldKind::Kong) {
return new CMMahjongState();
}
}
default:
return nullptr;
}
return nullptr;
}
void CMMeldState::update(CMTile* tile){
}
CMTileState* CMTakenState::handleAction(CMTile* tile, CMTileAction action){
switch (action) {
case CMTileAction::Mahjong:{
return new CMMahjongState();
}
break;
case CMTileAction::Kong:{
tile->meld(CMMeldKind::Kong);
return new CMMeldState();
}
break;
case CMTileAction::Pung:{
tile->meld(CMMeldKind::Pung);
return new CMMeldState();
}
break;
case CMTileAction::Chow:{
tile->meld(CMMeldKind::Chow);
return new CMMeldState();
}
break;
default:
return nullptr;
}
return nullptr;
}
void CMTakenState::update(CMTile* tile){
}
CMTileState* CMDiscardState::handleAction(CMTile* tile, CMTileAction action){
switch (action) {
case CMTileAction::Take:{
return new CMTakenState();
}
break;
default:
return nullptr;
}
return nullptr;
}
void CMDiscardState::update(CMTile* tile){
}
CMTileState* CMHeldState::handleAction(CMTile* tile, CMTileAction action){
switch (action) {
case CMTileAction::Discard:{
return new CMDiscardState();
}
break;
case CMTileAction::Kong:{
tile->meld(CMMeldKind::Kong);
return new CMMeldState();
}
break;
case CMTileAction::ConcealKong:{
tile->meld(CMMeldKind::Kong);
tile->conceal();
return new CMMeldState();
}
break;
case CMTileAction::Pung:{
tile->meld(CMMeldKind::Pung);
return new CMMeldState();
}
break;
case CMTileAction::Chow:{
tile->meld(CMMeldKind::Chow);
return new CMMeldState();
}
break;
default:
return nullptr;
}
return nullptr;
}
void CMHeldState::update(CMTile* tile){
}
CMTileState* CMDrawnState::handleAction(CMTile* tile, CMTileAction action){
switch (action) {
case CMTileAction::Discard:{
return new CMDiscardState();
}
break;
case CMTileAction::Keep:{
return new CMHeldState();
}
break;
case CMTileAction::Mahjong:{
return new CMMahjongState();
}
break;
default:
return nullptr;
}
return nullptr;
}
void CMDrawnState::update(CMTile* tile){
}
CMTileState* CMBuiltState::handleAction(CMTile* tile, CMTileAction action){
if (action == CMTileAction::Draw) {
return new CMDrawnState();
}
return nullptr;
}
void CMBuiltState::update(CMTile* tile){
}
| true |
f661b14d2ef156757475dca1a5010e07a6210399 | C++ | rasikazope/gollum | /practice/array/two_dimensional_array.cc | UTF-8 | 726 | 3.6875 | 4 | [] | no_license | #include <stdio.h>
#include <iostream>
using namespace std;
void
create_duplicate_and_print(int myarr[][5], int m, int n)
{
int **newarr = new int *[m];
for (int i = 0; i < m; i++) {
newarr[i] = new int [n];
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
newarr[i][j] = myarr[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << newarr[i][j] << " ";
}
cout << endl;
}
}
int main() {
int myarr[4][5] = {
{1, 2, 3, 4, 17},
{5, 6, 7, 8, 18},
{9, 10, 11, 12, 19},
{13, 14, 15, 16, 20}
};
create_duplicate_and_print(myarr, 4, 5);
}
| true |
a8e3e82aef0568ee15fa07753efd81855cd91b59 | C++ | GezelligCode/Student-Roster-Database | /main.cpp | UTF-8 | 747 | 2.625 | 3 | [] | no_license | // C867 Project 02.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <array>
#include <vector>
#include "Student.h"
#include "Roster.h"
#include "Student.cpp"
#include "Roster.cpp"
using namespace std;
using namespace Degrees;
int main()
{
cout << "Created Student Roster" << endl;
Roster classRoster;
classRoster.PrintAll();
classRoster.PrintInvalidEmails();
//loop through classRosterArray and for each element:
classRoster.PrintAverageDaysInCourse("A3");
classRoster.PrintByDegreeProgram(SOFTWARE);
cout << endl;
classRoster.Remove("A3");
cout << endl;
classRoster.PrintAll();
classRoster.Remove("A3");
}
| true |
fde569c17d842d0a712728779e896bf21627b798 | C++ | daniel0412/coding | /leetcode/code/LongestIncreasingPathInMatrix.h | UTF-8 | 2,142 | 2.984375 | 3 | [] | no_license | /*
*
*/
#include <string>
#include <vector>
#include <list>
#include <stack>
#include <sstream>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <queue>
#include <functional>
#include <algorithm>
#include <utility>
#include "utils.h"
using namespace std;
class LongestIncreasingPathInMatrix {
public:
int longestIncreasingPath(vector<vector<int> >& matrix)
{
return dfs(matrix);
}
int dfs(vector<vector<int> >& matrix)
{
if(matrix.empty() || matrix[0].empty())
return 0;
int m = matrix.size(), n = matrix[0].size();
int maxLen = 0;
vector<vector<int> > lmatrix(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
int tmpLen = dfsImpl(i, j, m, n, matrix, lmatrix);
maxLen = max(maxLen, tmpLen);
}
}
return maxLen;
}
private:
int dfsImpl(const int i,
const int j,
const int m,
const int n,
const vector<vector<int> >& matrix,
vector<vector<int> >& lmatrix)
{
if(lmatrix[i][j])
return lmatrix[i][j];
int leftLen =
(valid(i, j - 1, m, n) && matrix[i][j] < matrix[i][j - 1]) ?
dfsImpl(i, j - 1, m, n, matrix, lmatrix) :
0;
int rightLen =
(valid(i, j + 1, m, n) && matrix[i][j] < matrix[i][j + 1]) ?
dfsImpl(i, j + 1, m, n, matrix, lmatrix) :
0;
int upLen =
(valid(i - 1, j, m, n) && matrix[i][j] < matrix[i - 1][j]) ?
dfsImpl(i - 1, j, m, n, matrix, lmatrix) :
0;
int downLen =
(valid(i + 1, j, m, n) && matrix[i][j] < matrix[i + 1][j]) ?
dfsImpl(i + 1, j, m, n, matrix, lmatrix) :
0;
lmatrix[i][j] = 1 + max(max(leftLen, rightLen), max(upLen, downLen));
return lmatrix[i][j];
}
bool validIndex(const int i, const int j, const int m, const int n)
{
return i >= 0 && i < m && j >= 0 && j < n;
}
};
| true |
5721b5d070f5a5ac914c7f9109e083c2506b7e2e | C++ | hki2345/AngryBird | /Core/InputManager.h | UHC | 3,526 | 2.53125 | 3 | [] | no_license | #pragma once
#include <vector>
#include <unordered_map>
#include "KMacro.h"
#include "DirectXHeader.h"
#include "Stl_Assistor.h"
#include "SmartPtr.h"
#define KEY_PRESS(ACTION) InputManager::Press(L##ACTION)
#define KEY_UP(ACTION) InputManager::Up(L##ACTION)
#define KEY_DOWN(ACTION) InputManager::Down(L##ACTION)
#define KEY_UNPRESS(ACTION) InputManager::UnPress(L##ACTION)
#define KEY_OVER(ACTION) InputManager::Over(L##ACTION)
#define KEY_OVER_RESET(ACTION) InputManager::Over_Reset(L##ACTION)
enum INPUT_ERROR
{
INPUT_OK,
INPUT_CREATE_ERROR,
INPUT_FIND_ERROR,
INPUT_MAX,
};
class InputManager
{
public:
friend class KCore;
private:
static POINT m_WIN_MOUSEPOINT;
static KVector2 m_SCREEN_MOUSEPOS;
public:
static KVector2 mouse_pos()
{
return m_SCREEN_MOUSEPOS;
}
static const char m_ErrorMsg[INPUT_MAX][256];
private:
// ̹ Ű char ϳ ϵ Ѵ.
// Ƴ ִ. -> Ʋ ̴.
// ̷ Ƴ ƶ -> ϴ غ
class Command : public SmartPtr
{
private:
static const char g_IsUp;
static const char g_IsUnPress;
static const char g_IsDown;
static const char g_IsPress;
static const char g_IsRevUp;
static const char g_IsRevUnPress;
static const char g_IsRevDown;
static const char g_IsRevPress;
public:
friend InputManager;
private:
std::vector<int> m_vec_Command;
char m_Data;
// ߰ ->> ִ ð Ͽ Over ->
// ð ִ°
float m_PressTime;
public:
// ڸ ϳ -> ϳ Լ ȴٴ
// ϵ .
template<typename T, typename... Rest>
void Insert_Command(const T& _Key, Rest... _Arg)
{
m_vec_Command.push_back(_Key);
Insert_Command(_Arg...);
}
// ÷
void Insert_Command() { }
private:
bool Command_Check();
void Update();
inline bool Up();
inline bool UnPress();
inline bool Down();
inline bool Press();
inline bool Over(float _Time);
inline bool Over_Reset(float _Time);
public:
Command(const size_t _RSize);
~Command();
};
public:
static const char* MSG_ERROR(INPUT_ERROR _Msg);
private:
static std::unordered_map<std::wstring, KPtr<Command>>::iterator m_Iter_ComStart;
static std::unordered_map<std::wstring, KPtr<Command>>::iterator m_Iter_ComEnd;
static std::unordered_map<std::wstring, KPtr<Command>> m_Map_Command;
public:
template<typename... Rest>
static INPUT_ERROR Create_Command(const wchar_t* _Name, Rest... _Arg)
{
KPtr<Command> pKEY = Map_Find<KPtr<Command>>(m_Map_Command, _Name);
if (nullptr != pKEY)
{
return INPUT_CREATE_ERROR;
}
Command* New_Command = new Command(sizeof...(_Arg));
New_Command->Insert_Command(_Arg...);
m_Map_Command.insert(std::unordered_map<std::wstring, KPtr<Command>>::value_type(_Name, New_Command));
return INPUT_OK;
}
static KPtr<Command> Find_Command(const wchar_t* _Name);
public:
static bool Up(const wchar_t* _Name);
static bool UnPress(const wchar_t* _Name);
static bool Down(const wchar_t* _Name);
static bool Press(const wchar_t* _Name);
static bool Over(const wchar_t* _Name, float _Time);
static bool Over_Reset(const wchar_t* _Name, float _Time);
private:
static void Update();
private:
InputManager();
~InputManager();
};
| true |
e4252773503f0d3e559a351ca6e936d87987e50c | C++ | braindigitalis/sleepy-discord | /sleepy_discord/asignments_client.cpp | UTF-8 | 2,136 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "client.h"
namespace SleepyDiscord {
void AssignmentBasedDiscordClient::resumeMainLoop() {
//assignments should be ordered based on dueTime
for (std::forward_list<Assignment>::iterator
assignment = assignments.begin(); assignment != assignments.end(); assignment = assignments.begin())
if (assignment->dueTime <= getEpochTimeMillisecond())
doAssignment();
else
break;
}
int AssignmentBasedDiscordClient::setDoAssignmentTimer(const time_t) {
static unsigned int uniqueNumber = 0;
return ++uniqueNumber;
}
void AssignmentBasedDiscordClient::doAssignment() {
Assignment assignment = assignments.front();
assignment.function();
assignments.pop_front();
}
Timer AssignmentBasedDiscordClient::schedule(TimedTask code, const time_t milliseconds) {
const time_t millisecondsEpochTime = getEpochTimeMillisecond() + milliseconds;
const int newJobID = setDoAssignmentTimer(milliseconds);
const Assignment newAssignemt = {
newJobID,
code,
millisecondsEpochTime
};
if (assignments.begin() == assignments.end() || millisecondsEpochTime < assignments.front().dueTime) {
assignments.push_front(newAssignemt);
} else {
std::forward_list<Assignment>::iterator lastAssignment = assignments.begin();
for (std::forward_list<Assignment>::iterator
assignment = ++(assignments.begin());
assignment != assignments.end();
++assignment) {
if (millisecondsEpochTime < assignment->dueTime)
break;
lastAssignment = assignment;
}
assignments.insert_after(lastAssignment, newAssignemt);
}
return Timer(std::bind(&AssignmentBasedDiscordClient::unschedule, this, newJobID));
}
void AssignmentBasedDiscordClient::unschedule(const int jobID) {
std::forward_list<Assignment>::iterator
lastAssignment = assignments.begin();
for (std::forward_list<Assignment>::iterator
assignment = assignments.begin(); assignment != assignments.end();
++assignment) {
if (assignment->jobID == jobID) {
assignments.erase_after(lastAssignment);
stopDoAssignmentTimer(assignment->jobID);
break;
}
lastAssignment = assignment;
}
}
}
| true |
393fede225b79397731f7636091041a1dcd3b1df | C++ | marcinbielinski/MemoryAllocTracking | /main.cpp | UTF-8 | 1,152 | 3.765625 | 4 | [] | no_license | #include <iostream>
#include <memory>
struct Object {
int x, y, z;
};
struct AllocMetrics
{
uint32_t TotalAllocated = 0;
uint32_t TotalFreed = 0;
[[nodiscard]] uint32_t CurrentUsage() const { return TotalAllocated - TotalFreed; }
};
static AllocMetrics s_AllocMetrics;
void* operator new (size_t size)
{
// std::cout << "Allocating " << size << " bytes\n";
s_AllocMetrics.TotalAllocated += size;
return malloc(size);
}
void operator delete (void* memory, size_t size)
{
// std::cout << "Freeing " << size << " bytes\n";
s_AllocMetrics.TotalFreed += size;
free(memory);
}
static void printMemoryUsage()
{
std::cout << "Memory Usage: " << s_AllocMetrics.CurrentUsage() << " bytes\n";
}
int main() {
// before allocating a string
{
printMemoryUsage();
std::string str = "1234567890123456";
std::cout << str << "\n";
printMemoryUsage();
{
std::unique_ptr<Object> obj = std::make_unique<Object>();
printMemoryUsage();
}
// after freeing unique
printMemoryUsage();
}
printMemoryUsage();
return 0;
}
| true |
f07b3d0068b70819acf9f62fea9154f99fe451cc | C++ | technolapin/E4 | /genericite_et_Cpp/TPs/00/exo2/one_vector.hh | UTF-8 | 910 | 3.34375 | 3 | [] | no_license | class one_vector : public abstract_vector
{
private:
int value;
public:
one_vector(int dim, int value = 1):
abstract_vector(dim)
{
this->value = value;
}
~one_vector() override {}
void
print() const override
{
std::cout << "[";
for (int i = 0; i < this->n; i++)
{
std::cout << this->value
<< " ";
}
std::cout << "]\n";
}
int
operator[](const int i) const
{
if (i >= this->get_dim())
{
throw 42;
}
else
{
return this->value;
}
}
one_vector& operator =(const one_vector& sempai)
{
this->n = sempai.get_dim();
this->value = sempai.value;
return *this;
}
one_vector operator *(const int scalar) const
{
return one_vector(this->n, this->value*scalar);
}
one_vector operator+(const int notascalar) const
{
return one_vector(this->n, this->value+notascalar);
}
};
| true |
26f3b836213e383c39bdcad388623c135bbbb95d | C++ | Pkotova/Object-Oriented-Programming | /Ice-Cream pt 2/Task02/IceCreamFlavour.h | UTF-8 | 976 | 2.78125 | 3 | [] | no_license | #pragma once
#include<iostream>
using namespace std;
class IceCreamFlavour
{
private:
char flavour[32];
double price;
public:
IceCreamFlavour();
IceCreamFlavour(const IceCreamFlavour&);
IceCreamFlavour& operator=(const IceCreamFlavour&);
IceCreamFlavour(const char*, const double&);
void setFlavour(const char*);
char* getFlavour();
void setPrice(const double&);
double getPrice();
friend ostream& operator<<(ostream&, const IceCreamFlavour&);
friend istream& operator>>(istream&, IceCreamFlavour&);
friend bool operator<(const IceCreamFlavour&, const IceCreamFlavour&);
friend bool operator>(const IceCreamFlavour&, const IceCreamFlavour&);
friend bool operator<=(const IceCreamFlavour&, const IceCreamFlavour&);
friend bool operator==(const IceCreamFlavour&, const IceCreamFlavour&);
friend bool operator>=(const IceCreamFlavour&, const IceCreamFlavour&);
friend bool operator!=(const IceCreamFlavour&, const IceCreamFlavour&);
//~IceCreamFlavour();
};
| true |
05314be3fc07b4d1a4927cf7b987f35ccc287135 | C++ | sukritishah15/DS-Algo-Point | /C-Plus-Plus/string_hasing.cpp | UTF-8 | 1,488 | 2.984375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mxn = 2e5+5, seed = 131; //the maximum length of the string and a prime number as the seed
int fn[26], fh[26]; string n, h; ll hsh[mxn], p[mxn] = {1};
unordered_set<ll> sett; //used to count the freq of needle in haystack
bool check(int fn[], int fh[]) { //checking if freq match (if so, needle exists)
for (int i=0;i<26;i++) {
if(fn[i]!=fh[i]) return false;
} return true;
}
ll substrHash(int l, int r) {
return hsh[r] - hsh[l-1]*p[r-l+1];
}
int main() {
cin >> n >> h;
for (int i=0;i<n.size();i++) {
fn[n[i]-'a']++;
} //counting letter frequency
for (int i=1;i<=h.size();i++) {
hsh[i] = hsh[i-1]*seed + h[i-1]; //hashing the string
p[i] = p[i-1]*seed; //precomputing powers of the seed
}
for (int i=1;i<=h.size();i++) {
fh[h[i-1]-'a']++;
if(i>n.size()) fh[h[i-n.size()-1]-'a']--;
if(check(fn, fh)) sett.insert(substrHash(i-n.size()+1, i));
}
cout << sett.size() << "\n";
}
/*
Description:
- Given a string N, the needle, and a string H, the haystack, find the number
of disctice permutations of which N apperas in H.
Input specification:
- String N, H where N<=H in length and H<=2e5
Output specification:
- The number of distinct permutation s of N which appear as a substring of H
Sample Input:
aab
abacabaa
Sample Output:
2
Time Complextiy: O(n) preprocessing with O(1) queries
Space Complexity: O(n)
*/
| true |
371b0455d8b848bb8a7f7a3326de797e59eb4cd0 | C++ | EQ4/Fl2flanger | /Source/SineGenerator.h | UTF-8 | 743 | 2.546875 | 3 | [] | no_license | /*
==============================================================================
SineGenerator.h
Created: 1 Feb 2014 11:48:52am
Author: Marc Wilhite
==============================================================================
*/
#ifndef SINEGENERATOR_H_INCLUDED
#define SINEGENERATOR_H_INCLUDED
#include <math.h>
class SineGenerator
{
public:
SineGenerator();
void setFrequency(double frequency);
void setSampleRate(double sampleRate);
void reset();
float tick();
private:
const double twoPI;
double kFrequency;
double kPhase;
double kSampleRate;
double kPhaseIncrement;
void updateIncrement();
};
#endif // SINEGENERATOR_H_INCLUDED
| true |
60115fa5f411c9db431f3de2ea470cf213d82a52 | C++ | eiichiroi/project-euler | /problem2.cpp | UTF-8 | 252 | 2.796875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
const size_t n = 4000000;
size_t sum = 0;
for (size_t a = 1, b = 1, c; (c = a + b) <= n; a = b, b = c) {
if (c % 2 == 0) {
sum += c;
}
}
cout << sum << endl;
return 0;
}
| true |
b292cad79fc9eb685da5ab25471c9b3b28d88ec3 | C++ | pechischev-old/space_shooter | /main.cpp | WINDOWS-1251 | 2,249 | 2.75 | 3 | [] | no_license | #include <SFML/Graphics.hpp>
#include <sstream>
#include <iostream>
#include <math.h>
#include "Game.h"
#include "Menu.h"
using namespace sf;
using namespace std;
const Time TIME_PER_FRAME = seconds(1.f / 60.f);
void processEvents(RenderWindow & window, Menu & menu, Game & game, GlobalBool & globalBool) {
Event event;
while (window.pollEvent(event))
{
if (globalBool.g_isMenu) {
ProcessEventsMenu(window, menu, globalBool, event); //
}
else {
processEventsGame(game, globalBool, event);
}
if (event.type == Event::KeyPressed && event.key.code == Keyboard::P) { //
if (!globalBool.g_isPause) {
globalBool.g_isPause = true;
}
else {
globalBool.g_isPause = false;
}
}
//
if ((event.type == Event::Closed) || (event.type == Event::KeyPressed && event.key.code == Keyboard::T)) {
window.close();
}
}
}
int CallGame(GlobalBool & globalBool, Menu & menu)
{
RenderWindow window(VideoMode(SCRN_WIDTH, SCRN_HEIGTH), TITLE_GAME);
Game *game = new Game();
InitializeGame(*game);
InitMenu(menu, window, menu.textureMenu, *game->textInfo);
Clock clock;
Time timeSinceLastUpdate = Time::Zero;
Player & player = *game->player;
window.setVerticalSyncEnabled(true);
while (window.isOpen())
{
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TIME_PER_FRAME)
{
timeSinceLastUpdate -= TIME_PER_FRAME;
processEvents(window, menu, *game, globalBool);
if ((!globalBool.g_isMenu && !globalBool.g_isPause) && globalBool.g_isNewGame) {
updateGame(*game, TIME_PER_FRAME, window, globalBool);
}
else {
UpdateMenu(menu, window, *game->textInfo);
}
}
if (globalBool.g_isRestart) {
ResetGame(*game);
globalBool.g_isRestart = false;
}
if ((!globalBool.g_isMenu) && globalBool.g_isNewGame) {
renderGame(window, *game);
}
else {
RenderMenu(menu, window, *game->textInfo);
}
}
Delete(*game);
delete game;
return 0;
}
int main()
{
Menu menu;
GlobalBool globalBool; //
CallGame(globalBool, menu);
return 0;
}
| true |
fd36f0f99ae7dae18b9306f9029da91b8db3bfee | C++ | Nagi3582/Hasegawa | /長谷川雅恭0323/GhostHouse/Source/World/World.cpp | UTF-8 | 1,511 | 2.703125 | 3 | [] | no_license | #include "World.h"
#include "../GameObject/Field/Field.h"
#include"../Utility/Renderer/Renderer.h"
World::World()
: m_Manager{}
, m_UImanager{}
, m_Field{ nullptr }
, m_Camera{ nullptr }
{
}
void World::Update(float deltaTime)
{
m_Manager.Update(deltaTime);
m_UImanager.update(deltaTime);
m_Camera->Update(deltaTime);
}
void World::DirectionUpdate(float deltaTime)
{
m_Manager.EffectUpdate(deltaTime);
m_Camera->Update(deltaTime);
}
void World::Draw(bool is_shadow, Renderer& renderer) const
{
m_Camera->Draw(is_shadow, renderer);
m_Field->Draw(is_shadow, renderer);
m_Manager.Draw(is_shadow, renderer);
}
void World::Draw_UI()
{
m_UImanager.draw();
}
ActorPtr World::FindActor(const std::string name)
{
return m_Manager.FindActor(name);
}
UIPtr World::FindUI(const std::string name)
{
return m_UImanager.find_UI(name);
}
void World::AddActor(ActorGroup group, const ActorPtr & actor)
{
m_Manager.AddActor(group, actor);
}
void World::AddUI(UIGroup group, const UIPtr & ui)
{
m_UImanager.add_ui(group, ui);
}
void World::AddCollideActor(ActorGroup group, const CollideActorPtr & actor)
{
m_Manager.AddCollideActor(group, actor);
}
void World::AddCamera(const ActorPtr & camera)
{
m_Camera = camera;
}
void World::AddField(const FieldPtr & field)
{
m_Field = field;
}
void World::SetNextField(FieldName name)
{
m_Field->SetNextField(name);
}
FieldPtr World::GetField() const
{
return m_Field;
}
| true |
9288e4aff0cb425931005afde38510e157c5bf9e | C++ | lusparon/C-semester3-hometasks | /HomeWork15/main.cpp | WINDOWS-1251 | 3,215 | 3.21875 | 3 | [] | no_license | #include "iterator.h"
#include <assert.h>
void main()
{
setlocale(LC_ALL,"RUSSIAN");
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);
cout << " 1\n";
cout << " : \n";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ; ";
cout << endl;
cout << " : \n";
my_rotate(v.begin(), v.end());
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ; ";
cout << endl;
cout << endl;
cout << "list : \n";
list<int> l{1,2,3,4,5,6};
for (auto i = l.begin();i != l.end();i++)
cout << *i << " ; ";
cout << endl;
cout << "list : \n";
my_rotate(l.begin(), l.end());
for (auto i = l.begin(); i != l.end();i++)
cout << *i << " ; ";
cout << endl;
cout << endl;
cout << " 2\n";
list<int> l1{1,2,-3,4,5 -6};
cout << "list : \n";
for (auto i = l1.begin();i != l1.end();i++)
cout << *i << " ; ";
cout << endl;
insert_null(l1);
cout << "list : \n";
for (auto i = l1.begin(); i != l1.end();i++)
cout << *i << " ; ";
cout << endl;
cout << endl;
cout << " 3\n";
vector<int> v2;
for (int i = 1; i < 10; ++i) v2.push_back(i);
cout << " : \n";
for (int i = 0; i < v2.size(); i++)
cout << v2[i] << " ; ";
cout << endl;
cout << " : \n";
gather(v2.begin(), v2.end(), next(v2.begin(), distance(v2.begin(), v2.end()) / 2), [](int i) {return i % 2==0;});
for (int i = 0; i < v2.size(); i++)
cout << v2[i] << " ; ";
cout << endl;
list<int> l2{ 1,-2,-3,4,5 - 6 };
cout << "list : \n";
for (auto i = l2.begin();i != l2.end();i++)
cout << *i << " ; ";
cout << endl;
gather(l2.begin(), l2.end(), next(l2.begin(), distance(l2.begin(), l2.end()) / 2), [](int i) {return i > 0;});
cout << "list : \n";
for (auto i = l2.begin(); i != l2.end();i++)
cout << *i << " ; ";
cout << endl;
cout << endl;
// 2
cout << " 4\n";
cout << " : ";
for (int i = 0; i < v2.size(); i++)
cout << v2[i] << " ; ";
cout << endl;
cout << " : " << sum(v2.begin() , v2.end() , 0);
cout << endl;
cout << endl;
cout << " 5\n";
cout << " : ";
for (int i = 0; i < v2.size(); i++)
cout << v2[i] << " ; ";
cout << endl;
auto s = sum(v2.begin(), v2.end());
cout << " : " << s ;
cout << endl;
cout << endl;
list<double> l3{1.4,5.6,2.3};
cout << "list : ";
for (auto i = l3.begin();i != l3.end();i++)
cout << *i << " ; ";
cout << endl;
cout << " : " << sum(l3.begin(),l3.end());
cout << endl;
cout << endl;
cout << " 6\n";
auto il = { 10, 20, 30 };
cout << " : " << sum(il.begin(),il.end());
cout << endl;
system("pause");
} | true |
26eb0b6bde64acf0cfbd8bc424507ad2d65751ff | C++ | maidis/coreutils-cpp | /yes/yes.cpp | UTF-8 | 924 | 3.5625 | 4 | [
"BSL-1.0"
] | permissive | #include <iostream>
#include <string>
#include <vector>
int main(int argc, char *argv[])
{
if (argc == 2 && argv[1] == std::string("--help"))
{
std::cout << R"(Usage: yes [STRING]...
or: yes OPTION
Repeatedly output a line with all specified STRING(s), or 'y'.
--help display this help and exit
--version output version information and exit)" << '\n';
return 0;
}
else if (argc == 1)
{
while(true)
{
std::cout << "y\n";
}
}
else
{
// https://stackoverflow.com/questions/15344714/convert-command-line-argument-to-string
std::vector<std::string> all_args;
all_args.assign(argv + 1, argv + argc);
while(true)
{
for (auto a : all_args)
{
std::cout << a << " ";
}
std::cout << '\n';
}
}
return 0;
}
| true |
2b5fd6a90644fb388766d7329cf4f596aa7e10cc | C++ | Juliiii/leetcode-everyday | /medium/322. Coin Change.cpp | UTF-8 | 764 | 2.625 | 3 | [] | no_license | class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if (coins.empty() || amount == 0) return 0;
sort(coins.begin(), coins.end());
vector<int> dp(amount + 1, 0);
for (int i = 1; i <= amount; i++) {
bool flag = false;
for (int j = 0; j < coins.size(); j++) {
if (i - coins[j] < 0) continue;
if (dp[i - coins[j]] == -1) continue;
flag = true;
if (dp[i] == 0) {
dp[i] = dp[i - coins[j]] + 1;
} else {
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
}
}
if (!flag) dp[i] = -1;
}
return dp.back();
}
};
| true |
3d973cecbd2811f78a4b21d63a855e1928a14337 | C++ | srtipu5/Problem-Solving-Using-CPP | /Birthday_cake_candles.cpp | UTF-8 | 450 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int n,a[100000],i,max_value,total=0;
cin>>n;
for(i=0;i<n;i++){
cin>>a[i];
}
max_value = a[0];
for(i=1;i<n;i++){
if(max_value>a[i])
max_value = max_value;
else
max_value = a[i];
}
for(i=0;i<n;i++){
if(max_value == a[i])
total+=1;
}
cout<<total;
return 0;
}
| true |
0f9d1c50a6affc4825a652813d95cdcca4c6aa7d | C++ | LatorreDev/nesicide | /apps/ide/model/cprojectmodel.h | UTF-8 | 2,192 | 2.578125 | 3 | [] | no_license | #ifndef CPROJECTMODEL_H
#define CPROJECTMODEL_H
#include "model/iuuidvisitor.h"
#include <QObject>
class CNesicideProject;
class CAttributeModel;
class CBinaryFileModel;
class CCartridgeModel;
class CFilterModel;
class CGraphicsBankModel;
class CSourceFileModel;
class CTileStampModel;
class CMusicModel;
class CProjectModel : public QObject
{
Q_OBJECT
signals:
void itemAdded(const QUuid &item);
void itemRemoved(const QUuid & item);
void reset();
public:
CProjectModel();
~CProjectModel();
void setProject(CNesicideProject* project);
// Retrieve a list of all Uuids present in the project.
QList<QUuid> getUuids() const;
// Accepts a IUuidVisitor that receives additional type information
// for the given Uuid. This allows making choices on the type of
// underlying data without exposing data outside of models.
// Furthermore, this prevents chained calls to getModel->contains(uuid)
// methods.
void visitDataItem(const QUuid& uuid, IUuidVisitor& visitor);
// Submodel retrieval.
CAttributeModel* getAttributeModel() { return m_pAttributeModel; }
CBinaryFileModel* getBinaryFileModel() { return m_pBinaryFileModel; }
CCartridgeModel* getCartridgeModel() { return m_pCartridgeModel; }
CFilterModel* getFilterModel() { return m_pFilterModel; }
CGraphicsBankModel* getGraphicsBankModel() { return m_pGraphicsBankModel; }
CSourceFileModel* getSourceFileModel() { return m_pSourceFileModel; }
CTileStampModel* getTileStampModel() { return m_pTileStampModel; }
CMusicModel* getMusicModel() { return m_pMusicModel; }
private:
CNesicideProject* m_pNesicideProject;
CAttributeModel* m_pAttributeModel;
CBinaryFileModel* m_pBinaryFileModel;
CCartridgeModel* m_pCartridgeModel;
CFilterModel* m_pFilterModel;
CGraphicsBankModel* m_pGraphicsBankModel;
CSourceFileModel* m_pSourceFileModel;
CTileStampModel* m_pTileStampModel;
CMusicModel* m_pMusicModel;
private slots:
void onItemAdded(const QUuid & item);
void onItemRemoved(const QUuid & item);
};
#endif // CPROJECTMODEL_H
| true |
4c98e92fdae65f702182f7c8229c455b6a0c0447 | C++ | niuxu18/logTracker-old | /second/download/CMake/CMake-old-new/CMake-old-new-joern/Kitware_CMake_old_new_old_function_668.cpp | UTF-8 | 1,702 | 2.578125 | 3 | [] | no_license | void
DumpSymbolTable(PIMAGE_SYMBOL pSymbolTable, PIMAGE_SECTION_HEADER pSectionHeaders, FILE *fout, unsigned cSymbols)
{
unsigned i;
PSTR stringTable;
std::string sectionName;
std::string sectionCharacter;
int iSectNum;
fprintf(fout, "Symbol Table - %X entries (* = auxillary symbol)\n",
cSymbols);
fprintf(fout,
"Indx Name Value Section cAux Type Storage Character\n"
"---- -------------------- -------- ---------- ----- ------- -------- ---------\n");
/*
* The string table apparently starts right after the symbol table
*/
stringTable = (PSTR)&pSymbolTable[cSymbols];
for ( i=0; i < cSymbols; i++ ) {
fprintf(fout, "%04X ", i);
if ( pSymbolTable->N.Name.Short != 0 )
fprintf(fout, "%-20.8s", pSymbolTable->N.ShortName);
else
fprintf(fout, "%-20s", stringTable + pSymbolTable->N.Name.Long);
fprintf(fout, " %08X", pSymbolTable->Value);
iSectNum = pSymbolTable->SectionNumber;
GetSectionName(pSymbolTable, sectionName);
fprintf(fout, " sect:%s aux:%X type:%02X st:%s",
sectionName.c_str(),
pSymbolTable->NumberOfAuxSymbols,
pSymbolTable->Type,
GetSZStorageClass(pSymbolTable->StorageClass) );
GetSectionCharacteristics(pSectionHeaders,iSectNum,sectionCharacter);
fprintf(fout," hc: %s \n",sectionCharacter.c_str());
#if 0
if ( pSymbolTable->NumberOfAuxSymbols )
DumpAuxSymbols(pSymbolTable);
#endif
/*
* Take into account any aux symbols
*/
i += pSymbolTable->NumberOfAuxSymbols;
pSymbolTable += pSymbolTable->NumberOfAuxSymbols;
pSymbolTable++;
}
} | true |
4c28afffa6db47874340c1d243382b39d9da4290 | C++ | jamsterwes/Minecraft-CPP | /src/gfx/v_buffer.hpp | UTF-8 | 2,416 | 2.78125 | 3 | [] | no_license | #pragma once
#include <glad/glad.h>
#include <functional>
#include "util.hpp"
#include <list>
#include <initializer_list>
namespace gfx
{
template <typename vertexType>
class v_buffer
{
public:
v_buffer() : indexCount(0)
{
glGenVertexArrays(1, &this->vaoID);
glGenBuffers(1, &this->vboID);
glGenBuffers(1, &this->eboID);
internalData = new std::vector<vertexType>{};
indexData = new std::vector<unsigned int>{};
}
const unsigned int indexDataTri[6] = {
0, 1, 2, 2, 3, 0
};
void PushBack(vertexType vertex0, vertexType vertex1, vertexType vertex2, vertexType vertex3)
{
unsigned int indexOffset = internalData->size();
internalData->push_back(vertex0);
internalData->push_back(vertex1);
internalData->push_back(vertex2);
internalData->push_back(vertex3);
for (int i = 0; i < 6; i++)
{
indexData->push_back(indexOffset + indexDataTri[i]);
}
}
void Update(std::function<void()> vertexAttributeProvider)
{
glBindVertexArray(this->vaoID);
glDeleteBuffers(1, &this->vboID);
glGenBuffers(1, &this->vboID);
glBindBuffer(GL_ARRAY_BUFFER, this->vboID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->eboID);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexType) * internalData->size(), internalData->data(), GL_DYNAMIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indexData->size(), indexData->data(), GL_DYNAMIC_DRAW);
vertexAttributeProvider();
glBindVertexArray(0);
indexCount = indexData->size();
delete internalData;
internalData = new std::vector<vertexType>{};
delete indexData;
indexData = new std::vector<unsigned int>{};
}
void Draw()
{
glBindVertexArray(this->vaoID);
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
}
unsigned int vaoID;
unsigned int indexCount;
private:
std::vector<vertexType>* internalData;
std::vector<unsigned int>* indexData;
unsigned int vboID, eboID;
};
} | true |
63178ed65b929251463576fb3cd90289c18dc918 | C++ | kubasejdak/graph-analyzer | /src/core/ExploitInfo.h | UTF-8 | 1,479 | 2.53125 | 3 | [] | no_license | /*
* Filename : ExploitInfo.h
* Author : Kuba Sejdak
* Created on : 03-05-2012
*/
#ifndef EXPLOITINFO_H_
#define EXPLOITINFO_H_
#include <list>
#include <string>
#include <memory>
#include <QDate>
#include <QMap>
#include <QMultiMap>
typedef QMap<std::string, std::string> TraitEntry;
typedef std::shared_ptr<TraitEntry> TraitEntryHandle;
typedef QMultiMap<std::string, TraitEntryHandle> TraitMap;
typedef std::shared_ptr<TraitMap> TraitMapHandle ;
class ExploitInfo {
public:
ExploitInfo();
~ExploitInfo() {}
int id();
std::string name();
std::string extractedFrom();
std::string graphName();
QDate captureDate();
int size();
std::string fileType();
int fileSize();
int codeOffset();
bool isExploitPresent();
TraitMapHandle traits();
bool isBroken();
bool isValuable();
void setId(int id);
void setName(std::string name);
void setExtractedFrom(std::string name);
void setGraphName(std::string name);
void setCaptureDate(std::string date);
void setSize(int size);
void setFileType(std::string fileType);
void setFileSize(int fileSize);
void setCodeOffset(int codeOffset);
void setTrait(std::string name, TraitEntryHandle value);
private:
int m_id;
std::string m_name;
std::string m_extractedFrom;
std::string m_graphName;
QDate m_captureDate;
int m_size;
std::string m_fileType;
int m_fileSize;
int m_codeOffset;
TraitMapHandle m_traits;
};
typedef std::shared_ptr<ExploitInfo> ExploitInfoHandle;
#endif /* EXPLOITINFO_H_ */
| true |
ac557027e40625b89acb6d7d98d825f73cf73670 | C++ | MaxAlala/objectdetectionapp | /include/stereo_camera.h | UTF-8 | 4,917 | 2.59375 | 3 | [] | no_license | #pragma once
#include "cv_ext/pinhole_camera_model.h"
namespace cv_ext
{
class StereoRectification
{
public:
/** @brief Set the parameters that define the stereo pair
*
* @param[in] cam_models Camera models of each camera (i.e., the intrincs of the two cameras)
* @param[in] r_mat Rotation matrix between the first and the second camera
* @param[in] t_vec Translation vector between the two cameras
*/
void setCameraParameters( const PinholeCameraModel cam_models[2],
const cv::Mat &r_mat, const cv::Mat &t_vec );
/** @brief Set the image scale factor.
*
* @param[in] scale_factor The scaling parameter
*
* The output rectified image will be rescaled using this scale factor
*/
void setImageScaleFacor( double scale_factor );
/** @brief If enable is set to true, the left to right minimum disparity will be zero
*
* @todo Double check this!
*/
void setZeroDisparity( bool enable ){ zero_disp_ = enable; };
/** @brief Set the parameter used to scale the rectified images.
*
* @param[in] val The scaling parameter
*
* The val parameter should be between 0 and 1: 0 (the default value) means that in the rectified images
* all pixel are valid (no black areas after rectification, getRegionsOfInterest() return region of interest
* that match the image size); 1 means that the rectified images is resized and shifted so
* that all the pixels from the original images are retained in the rectified images.
*/
void setScalingParameter( double val );
/** @brief Update the rectification map
*
* This method should be called after setting all the parameters (setCameraParameters(),
* setScalingParameter(), ...)
*/
void update();
/** @brief Provide the resulting disparity-to-depth mapping matrix
*
* @param[out] map A 4x4 disparity-to-depth mapping matrix
*
* @note This method should be called after setting the stereo camera parameters with setCameraParameters()
* otherwise an empty matrix will be returned.
*/
void getDisp2DepthMap( cv::Mat &map ){ map = disp2depth_mat_; };
/** @brief Provide the resulting inverse disparity-to-depth mapping matrix
*
* @param[out] map A 4x4 disparity-to-depth mapping matrix
*
* This map considers is computed considering the inverse transformation between the two cameras.
* (E.g., right to left in place to left to right)
* @note This method should be called after setting the stereo camera parameters with setCameraParameters()
* otherwise an empty matrix will be returned.
*/
void getInvDisp2DepthMap( cv::Mat &map ){ map = inv_disp2depth_mat_; };
/** @brief Provide a pair of region of interest representing the areas of the rectified image where
* all pixels are valid
*
* @param[out] roi Output rect pair
*
* @note This method should be called after setting the stereo camera parameters with setCameraParameters()
* otherwise two undefined roi will be returned
*/
void getRegionsOfInterest( cv::Rect roi[2] );
/** @brief Rectify an input stereo pair images
*
* @param[in] imgs Input image pair
* @param[out] corners_img Output rectified image pair
*
* @note This method should be called after setting the stereo camera parameters with setCameraParameters()
* otherwise two empty images will be returned.
*/
void rectifyImagePair( const cv::Mat imgs[2], cv::Mat rect_imgs[2] );
/** @brief Provide the camera models of the rectified stereo images
*
* @param[out] cam_models Output camera models
*
* @note Call this method after update(), othervise it will
* provide just two default PinholeCameraModel objects.
*/
void getCamModels( PinholeCameraModel cam_models[2] );
/** @brief Provide the size of the output rectified image.
*
* The rectified image will be rescaled using the scale factor set with the setScalingParameter()
* method, this method will provide the resulting size.
* @note Call this method after update(), othervise it will provide a (-1, -1) size.
*/
cv::Size getOutputImageSize(){ return out_image_size_; };
/** @brief Provide the (x,y) displacement between the two rectified cameras
*
* @param[out] cam_shift X,Y displacement
*
* @note Call this method after update(), othervise it will
* provides just a (0,0) displacement.
*/
void getCamDisplacement( cv::Point2f &cam_shift );
private:
cv::Size image_size_ = cv::Size(-1,-1), out_image_size_ = cv::Size(-1,-1);
cv::Mat camera_matrices_[2], dist_coeffs_[2];
cv::Mat r_mat_, t_vec_;
cv::Mat rect_map_[2][2];
cv::Mat disp2depth_mat_, inv_disp2depth_mat_;
cv::Rect rect_roi_[2];
cv::Mat proj_mat_[2];
double scaling_param_ = 0, scale_factor_ = 1.0;
bool zero_disp_ = false;
};
} | true |
49d43a06e014a08bbf814a7d81a056605036fb5d | C++ | verogzz/Compiladores | /CompiladorSolstice/CompiladorSolstice/VM3_Avance_A0045665_A01087523/Cubo.cpp | UTF-8 | 11,268 | 3.359375 | 3 | [] | no_license | #include<iostream>
#include "Cubo.h"
Cubo::Cubo() {
/* Cubo[OP1][OP2][OPR] = TIPO
OP#
INT 0
DOUBLE 1
STRING 2
BOOL 3
ERROR -1
OPERADOR
+ 0
- 1
* 2
/ 3
% 4
& 5
| 6
< 7
> 8
== 9
<> 10
>= 11
<= 12
^ 13
= 14*/
// INT
cubo[0][0][0] = 0; // int + int = int
cubo[0][1][0] = -1; // int + double = error
cubo[0][2][0] = -1; // int + string = error
cubo[0][3][0] = -1; // int + bool = error
cubo[0][0][1] = 0; // int - int = int
cubo[0][1][1] = -1; // int - double = error
cubo[0][2][1] = -1; // int - string = error
cubo[0][3][1] = -1; // int - bool = error
cubo[0][0][2] = 0; // int * int = int
cubo[0][1][2] = -1; // int * double = error
cubo[0][2][2] = -1; // int * string = error
cubo[0][3][2] = -1; // int * bool = error
cubo[0][0][3] = 0; // int / int = int
cubo[0][1][3] = -1; // int / double = error
cubo[0][2][3] = -1; // int / string = error
cubo[0][3][3] = -1; // int / bool = error
cubo[0][0][4] = 0; // int % int = int
cubo[0][1][4] = -1; // int % double = error
cubo[0][2][4] = -1; // int % string = error
cubo[0][3][4] = -1; // int % bool = error
cubo[0][0][5] = -1; // int & int = error
cubo[0][1][5] = -1; // int & double = error
cubo[0][2][5] = -1; // int & string = error
cubo[0][3][5] = -1; // int & bool = error
cubo[0][0][6] = -1; // int | int = error
cubo[0][1][6] = -1; // int | double = error
cubo[0][2][6] = -1; // int | string = error
cubo[0][3][6] = -1; // int | bool = error
cubo[0][0][7] = 3; // int < int = bool
cubo[0][1][7] = -1; // int < double = error
cubo[0][2][7] = -1; // int < string = error
cubo[0][3][7] = -1; // int < bool = error
cubo[0][0][8] = 3; // int > int = bool
cubo[0][1][8] = -1; // int > double = error
cubo[0][2][8] = -1; // int > string = error
cubo[0][3][8] = -1; // int > bool = error
cubo[0][0][9] = 3; // int == int = bool
cubo[0][1][9] = -1; // int == double = error
cubo[0][2][9] = -1; // int == string = error
cubo[0][3][9] = -1; // int == bool = error
cubo[0][0][10] = 3; // int <> int = bool
cubo[0][1][10] = -1; // int <> double = error
cubo[0][2][10] = -1; // int <> string = error
cubo[0][3][10] = -1; // int <> bool = error
cubo[0][0][11] = 3; // int >= int = bool
cubo[0][1][11] = -1; // int >= double = error
cubo[0][2][11] = -1; // int >= string = error
cubo[0][3][11] = -1; // int >= bool = error
cubo[0][0][12] = 3; // int <= int = bool
cubo[0][1][12] = -1; // int <= double = error
cubo[0][2][12] = -1; // int <= string = error
cubo[0][3][12] = -1; // int <= bool = error
cubo[0][0][13] = 2; // int ^ int = string
cubo[0][1][13] = 2; // int ^ double = string
cubo[0][2][13] = 2; // int ^ string = string
cubo[0][3][13] = 2; // int ^ bool = string
cubo[0][0][14] = 1; // int = int
cubo[0][1][14] = -1; // int = double
cubo[0][2][14] = -1; // int = string
cubo[0][3][14] = -1; // int = bool
// DOUBLE
cubo[1][0][0] = -1; // double + int = error
cubo[1][1][0] = 1; // double + double = double
cubo[1][2][0] = -1; // double + string = error
cubo[1][3][0] = -1; // double + bool = error
cubo[1][0][1] = -1; // double - int = error
cubo[1][1][1] = 1; // double - double = double
cubo[1][2][1] = -1; // double - string = error
cubo[1][3][1] = -1; // double - bool = error
cubo[1][0][2] = -1; // double * int = error
cubo[1][1][2] = 1; // double * double = double
cubo[1][2][2] = -1; // double * string = error
cubo[1][3][2] = -1; // double * bool = error
cubo[1][0][3] = -1; // double / int = error
cubo[1][1][3] = 1; // double / double = double
cubo[1][2][3] = -1; // double / string = error
cubo[1][3][3] = -1; // double / bool = error
cubo[1][0][4] = -1; // double % int = error
cubo[1][1][4] = 0; // double % double = int
cubo[1][2][4] = -1; // double % string = error
cubo[1][3][4] = -1; // double % bool = error
cubo[1][0][5] = -1; // double & int = error
cubo[1][1][5] = -1; // double & double = error
cubo[1][2][5] = -1; // double & string = error
cubo[1][3][5] = -1; // double & bool = error
cubo[1][0][6] = -1; // double | int = error
cubo[1][1][6] = -1; // double | double = error
cubo[1][2][6] = -1; // double | string = error
cubo[1][3][6] = -1; // double | bool = error
cubo[1][0][7] = -1; // double < int = error
cubo[1][1][7] = 3; // double < double = bool
cubo[1][2][7] = -1; // double < string = string
cubo[1][3][7] = -1; // double < bool = string
cubo[1][0][8] = -1; // double > int = error
cubo[1][1][8] = 3; // double > double = bool
cubo[1][2][8] = -1; // double > string = error
cubo[1][3][8] = -1; // double > bool = error
cubo[1][0][9] = -1; // double == int = error
cubo[1][1][9] = 3; // double == double = bool
cubo[1][2][9] = -1; // double == string = error
cubo[1][3][9] = -1; // double == bool = error
cubo[1][0][10] = -1; // double <> int = error
cubo[1][1][10] = 3; // double <> double = double
cubo[1][2][10] = -1; // double <> string = error
cubo[1][3][10] = -1; // double <> bool = error
cubo[1][0][11] = -1; // double >= int = error
cubo[1][1][11] = 3; // double >= double = bool
cubo[1][2][11] = -1; // double >= string = error
cubo[1][3][11] = -1; // double >= bool = error
cubo[1][0][12] = -1; // double <= int = error
cubo[1][1][12] = 3; // double <= double = bool
cubo[1][2][12] = -1; // double <= string = error
cubo[1][3][12] = -1; // double <= bool = error
cubo[1][0][13] = 2; // double ^ int = string
cubo[1][1][13] = 2; // double ^ double = string
cubo[1][2][13] = 2; // double ^ string = string
cubo[1][3][13] = 2; // double ^ bool = string
cubo[1][0][14] = -1; // double = int
cubo[1][1][14] = 1; // double = double
cubo[1][2][14] = -1; // double = string
cubo[1][3][14] = -1; // double = bool
// STRING
cubo[2][0][0] = -1; // string + int = error
cubo[2][1][0] = -1; // string + double = error
cubo[2][2][0] = -1; // string + string = error
cubo[2][3][0] = -1; // string + bool = error
cubo[2][0][1] = -1; // string - int = error
cubo[2][1][1] = -1; // string - double = error
cubo[2][2][1] = -1; // string - string = error
cubo[2][3][1] = -1; // string - bool = error
cubo[2][0][2] = -1; // string * int = error
cubo[2][1][2] = -1; // string * double = error
cubo[2][2][2] = -1; // string * string = error
cubo[2][3][2] = -1; // string * bool = error
cubo[2][0][3] = -1; // string / int = error
cubo[2][1][3] = -1; // string / double = error
cubo[2][2][3] = -1; // string / string = error
cubo[2][3][3] = -1; // string / bool = error
cubo[2][0][4] = -1; // string % int = error
cubo[2][1][4] = -1; // string % double = error
cubo[2][2][4] = -1; // string % string = error
cubo[2][3][4] = -1; // string % bool = error
cubo[2][0][5] = -1; // string & int = error
cubo[2][1][5] = -1; // string & double = error
cubo[2][2][5] = -1; // string & string = error
cubo[2][3][5] = -1; // string & bool = error
cubo[2][0][6] = -1; // string | int = error
cubo[2][1][6] = -1; // string | double = error
cubo[2][2][6] = -1; // string | string = error
cubo[2][3][6] = -1; // string | bool = error
cubo[2][0][7] = -1; // string < int = error
cubo[2][1][7] = -1; // string < double = error
cubo[2][2][7] = -1; // string < string = error
cubo[2][3][7] = -1; // string < bool = error
cubo[2][0][8] = -1; // string > int = error
cubo[2][1][8] = -1; // string > double = error
cubo[2][2][8] = -1; // string > string = error
cubo[2][3][8] = -1; // string > bool = error
cubo[2][0][9] = -1; // string == int = error
cubo[2][1][9] = -1; // string == double = error
cubo[2][2][9] = 3; // string == string = bool
cubo[2][3][9] = -1; // string == bool = error
cubo[2][0][10] = -1; // string <> int = error
cubo[2][1][10] = -1; // string <> double = error
cubo[2][2][10] = 3; // string <> string = bool
cubo[2][3][10] = -1; // string <> bool = error
cubo[2][0][11] = -1; // string >= int = error
cubo[2][1][11] = -1; // string >= double = error
cubo[2][2][11] = -1; // string >= string = error
cubo[2][3][11] = -1; // string >= bool = error
cubo[2][0][12] = -1; // string <= int = error
cubo[2][1][12] = -1; // string <= double = error
cubo[2][2][12] = -1; // string <= string = error
cubo[2][3][12] = -1; // string <= bool = error
cubo[2][0][13] = 2; // string ^ int = string
cubo[2][1][13] = 2; // string ^ double = string
cubo[2][2][13] = 2; // string ^ string = string
cubo[2][3][13] = 2; // string ^ bool = string
cubo[2][0][14] = -1; // string = int
cubo[2][1][14] = -1; // string = double
cubo[2][2][14] = 2; // string = string
cubo[2][3][14] = -1; // string = bool
// BOOL
cubo[3][0][0] = -1; // bool + int = error
cubo[3][1][0] = -1; // bool + double = error
cubo[3][2][0] = -1; // bool + string = error
cubo[3][3][0] = -1; // bool + bool = error
cubo[3][0][1] = -1; // bool - int = error
cubo[3][1][1] = -1; // bool - double = error
cubo[3][2][1] = -1; // bool - string = error
cubo[3][3][1] = -1; // bool - bool = error
cubo[3][0][2] = -1; // bool * int = error
cubo[3][1][2] = -1; // bool * double = error
cubo[3][2][2] = -1; // bool * string = error
cubo[3][3][2] = -1; // bool * bool = error
cubo[3][0][3] = -1; // bool / int = error
cubo[3][1][3] = -1; // bool / double = error
cubo[3][2][3] = -1; // bool / string = error
cubo[3][3][3] = -1; // bool / bool = error
cubo[3][0][4] = -1; // bool % int = error
cubo[3][1][4] = -1; // bool % double = error
cubo[3][2][4] = -1; // bool % string = error
cubo[3][3][4] = -1; // bool % bool = error
cubo[3][0][5] = -1; // bool & int = error
cubo[3][1][5] = -1; // bool & double = error
cubo[3][2][5] = -1; // bool & string = error
cubo[3][3][5] = 3; // bool & bool = bool
cubo[3][0][6] = -1; // bool | int = error
cubo[3][1][6] = -1; // bool | double = error
cubo[3][2][6] = -1; // bool | string = error
cubo[3][3][6] = 3; // bool | bool = bool
cubo[3][0][7] = -1; // bool < int = error
cubo[3][1][7] = -1; // bool < double = error
cubo[3][2][7] = -1; // bool < string = error
cubo[3][3][7] = -1; // bool < bool = error
cubo[3][0][8] = -1; // bool > int = error
cubo[3][1][8] = -1; // bool > double = error
cubo[3][2][8] = -1; // bool > string = error
cubo[3][3][8] = -1; // bool > bool = error
cubo[3][0][9] = -1; // bool == int = error
cubo[3][1][9] = -1; // bool == double = error
cubo[3][2][9] = -1; // bool == string = error
cubo[3][3][9] = 3; // bool == bool = bool
cubo[3][0][10] = -1; // bool <> int = error
cubo[3][1][10] = -1; // bool <> double = error
cubo[3][2][10] = -1; // bool <> string = error
cubo[3][3][10] = 3; // bool <> bool = bool
cubo[3][0][11] = -1; // bool >= int = error
cubo[3][1][11] = -1; // bool >= double = error
cubo[3][2][11] = -1; // bool >= string = error
cubo[3][3][11] = -1; // bool >= bool = error
cubo[3][0][12] = -1; // bool <= int = error
cubo[3][1][12] = -1; // bool <= double = error
cubo[3][2][12] = -1; // bool <= string = error
cubo[3][3][12] = -1; // bool <= bool = error
cubo[3][0][13] = 2; // bool ^ int = string
cubo[3][1][13] = 2; // bool ^ double = string
cubo[3][2][13] = 2; // bool ^ string = string
cubo[3][3][13] = 2; // bool ^ bool = string
cubo[3][0][14] = -1; // bool = int
cubo[3][1][14] = -1; // bool = double
cubo[3][2][14] = -1; // bool = string
cubo[3][3][14] = 3; // bool = bool
} | true |
bd97991b05ada73e08727093aaf3c27a71e5ec66 | C++ | NColey/coursework | /mac-101/while-loops/print-stars-while-loop.cpp | UTF-8 | 243 | 2.671875 | 3 | [] | no_license | /*name
program name*/
#include <iostream>
using namespace std;
int main()
{
int rows, i=1;
cout << "Select the number of rows";
cin >> rows;
while (i<=rows)
char star="*";
star = i;
{
cout<<"star ";
}
i++;
return 0;
}
| true |
74f6be72af02a1c5b4d61c882df9b6f9a8c8638c | C++ | Plaristote/crails | /modules/signin/crails/signin/model.hpp | UTF-8 | 759 | 2.671875 | 3 | [] | no_license | #ifndef CRAILS_SIGNIN_MODEL_HPP
# define CRAILS_SIGNIN_MODEL_HPP
# include <string>
# include <ctime>
namespace Crails
{
#pragma db object abstract
class AuthenticableModel
{
public:
static const std::time_t session_duration;
const std::string& get_authentication_token() const { return authentication_token; }
std::time_t get_sign_in_at() const { return sign_in_at; }
void set_authentication_token(const std::string& v) { authentication_token = v; }
void set_sign_in_at(std::time_t v) { sign_in_at = v; }
void generate_authentication_token();
std::time_t get_token_expires_in() const;
private:
std::string authentication_token;
std::time_t sign_in_at = 0;
};
}
#endif
| true |
ca312a46e31a3a07ba56d4b1ebabfb6a435dbe92 | C++ | CarlRiley99/Memory-Allocation | /pa2.cpp | UTF-8 | 2,477 | 3.484375 | 3 | [] | no_license | /*
* pa2.cpp
*
* Created on: Mar 4, 2018
* Author: CarlRiley
*/
#include <iostream>
#include "pa2.h"
using namespace std;
int mainMenu(int mode) {
int userOption = 1;
bool printMenu = true;
while (printMenu) {
if (mode == 1) {
cout << "Using best fit algorithm" << endl;
cout << endl;
}
else {
cout << "Using worst fit algorithm" << endl;
cout << endl;
}
cout << "1. Add program" << endl;
cout << "2. Kill program" << endl;
cout << "3. Fragmentation" << endl;
cout << "4. Print memory" << endl;
cout << "5. Exit" << endl;
cout << "Enter Menu Option: ";
cin >> userOption;
cout << endl;
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Invalid input. Please enter a number between 1 - 5" << endl;
printMenu = true;
}
else {
printMenu = false;
}
}
return userOption;
}
void lowerCase(string& algorithmMode) {
for (unsigned int i = 0; i < algorithmMode.length(); i++) {
algorithmMode[i] = tolower(algorithmMode[i]);
}
}
int main(int argc, char** argv) {
string algorithmMode = argv[1] ;
lowerCase(algorithmMode);
int mode = 0;
int userOption = 1;
double programSize = 0.0;
int memorySize = 128;
int numOfPages = 32;
int fragmentCounter = 0;
string program = "";
if (algorithmMode.compare("best") == 0) {
mode = 1;
}
if (mode == 1) {
cout << "Best mode" << endl;
}
else {
cout << "Worst Mode" << endl;
}
LinkedList memory;
//Fills the linked list with 32 pages of "FREE" space.
for (int i = 0; i < numOfPages; i++) {
memory.createMemorySpace("FREE");
}
while (userOption != 5) {
userOption = mainMenu(mode);
switch (userOption) {
case 1:
cout << "Program name: ";
cin >> program;
cout << endl;
while (true) {
cout << "Program size (KB)";
cin >> programSize;
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Please input an integer" << endl;
}
else {
break;
}
}
memory.addProgram(program, programSize, memorySize, numOfPages, mode);
break;
case 2:
cout << "Name of program to be deleted: " << endl;
cin >> program;
memory.deleteProgram(program);
break;
case 3:
fragmentCounter = memory.checkFragments();
cout << "There are " << fragmentCounter << " fragment(s)" << endl;
break;
case 4:
memory.printList();
break;
case 5:
cout << "You have shutdown the program!" << endl;
break;
default:
cout << "Invalid Input" << endl;
}
}
return 0;
}
| true |
5355a7b5b6ed3bf2a7f5c1e8ba7a71e30a9489ef | C++ | abhijeetmallick65/DsAlgo | /playground.cpp | UTF-8 | 762 | 3.53125 | 4 | [] | no_license | #include<stdio.h>
#include<iostream>
using namespace std;
class Machine{
public:
int price = 10;
string name;
Machine(string name){
this->name = name;
cout << "constructor ran " << endl;
}
string getname(){
return name;
}
void printing(){
cout << "this is a string" << endl;
}
};
class Camera : public Machine{
public:
Camera(string name) : Machine(name){
cout<<"s"<<endl;
}
void printing2(){
cout << "this is a camera string" << endl;
}
};
int main(){
Machine machine("new ,machine");
// machine.printing();
Camera cam("naming");
cam.printing();
cam.printing2();
return 0;
}
| true |
63052290d07aaadf2756e9f0dad8fcaee1365eff | C++ | Abysman/MyLeetCode | /113.Path Sum II/113.Path Sum II/main.cpp | UTF-8 | 1,350 | 3.265625 | 3 | [] | no_license | //
// main.cpp
// 113.Path Sum II
//
// Created by Abysman on 2018/5/1.
// Copyright © 2018年 Abysman. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> path;
vector<int> record;
helper(root, path, sum, record, 0);
return path;
}
void helper(TreeNode* curr_node, vector<vector<int>> &path, int sum, vector<int> &record, int record_sum) {
if (curr_node) {
int temp = record_sum + curr_node->val;
record.push_back(curr_node->val);
if (curr_node->left == NULL && curr_node->right == NULL) {
if (temp == sum) {
path.push_back(record);
}
}
vector<int> record_copy(record.begin(), record.end());
helper(curr_node->left, path, sum, record, temp);
helper(curr_node->right, path, sum, record_copy ,temp);
}
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
vector<int> b = {1,2,3,4};
h(b);
return 0;
}
| true |
f557a2de6b0872f7757adebcd8a67894463266fc | C++ | mcarranzad/Hoja-de-Trabajo-6 | /HT6_EJERCICIO_01.CPP | WINDOWS-1252 | 3,452 | 3.390625 | 3 | [] | no_license | /*EJERCICIO # 1: En una librera se venden 4 modelos diferentes de cuadernos, con los siguientes precios:
• Modelo#1 – Q10.00 • Modelo#2 – Q15.00 • Modelo#3 – Q18.50 • Modelo#4 – Q25.00
Por otra parte, se tiene informacin sobre las ventas realizadas durante los ltimos 30 das, estos movimientos se deben de
guardar en un archivo de la siguiente forma:
DIA1,MOD,CANT DIA2,MOD,CANT . . . DIA30,MODELO,CANTIDAD DIAi = Variable que representa el da que se efectua
la venta i (1 - 30) MOD= Variable que representa codigo de Modelo que se vendia. (1 – 4) CANT= Variable que representa
la cantidad de unidades vendidas. El programa debe ser capaz de: • Modificar el numero de unidades vendidas, solicitando al
usuario el da y cdigo de articulo (modificacin del archivo) • Eliminacin de un da especifico de venta
(modificacin del archivo) • Calcular el total recaudado por modelo en los 30 das. • Calcular cual fue el modelo que
se vendia mas en los 30 das.*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct cuaderno{
string modelo;
float dias30;
float cantidad;
float precio mod1=10.00,mod2=15.00,mod3=18,mod4=25:
};
void mp(); //definicion de la funcion
void inventario();
void leer_archivo();
int main(){
mp();
//return 0;
}
void mp(){ // cuadernos
int resp;
string nombrearchivo;
cout<<"Indique nombre de archivo: ";
getline(cin,nombrearchivo);
do{
system("CLS");
cout<<"--------------------------"<<"\n";
cout<<" modelos de cuadernos "<<"\n";
cout<<"-------------------"<<"\n";
cout<<" 1 - ingrese que modelo necesita "<<"\n";
cout<<" 2 - mostrar el modelos que necesite"<<"\n";
cout<<" 3 - Salir"<<"\n";
cout<<"--------------------------"<<"\n";
cout<<" Seleccione su opción: ";
cin>>resp;
if (resp==1){
system("CLS");
inventario();
}
else if (resp==2){
system("CLS");
leer_archivo();
}
else if (resp==3)
break;
else
break;
} while(resp!=3);
}
void inventario(){
string cuaderno_v;
string modelo_v;
float precio_v;
ofstream archivo; //grabar archivo
fflush(stdin);
cout<<"Ingrese modelo: "<<endl;
getline(cin,modelo_v);
fflush(stdin);
cout<<"Ingrese cantida: "<<endl;
getline(cin,marca_v);
cout<<"Ingrese dia: "<<endl;
cin>>dia_v;
cout<<"Ingrese precio: "<<endl;
cin>>precio_v;
archivo.open("cuaderno.txt",ios::app); //abrir archivo append
archivo<<placa_v<<"\t"<<modelo_v<<"\t"<<dia<<"\t"<<precio_v<<endl;
archivo.close();
}
void leer_archivo(){
ifstream archivo; //leer archivo
archivo.open("cuaderno.txt",ios::in);
int lineas,i=0;
string s,linea;
while (getline(archivo, s))
lineas++;
archivo.close();
cuadernosrecordset[lineas];
archivo.open("cuaderno txt",ios::in);
if(archivo.fail()){
cout<<"No se pudo abrir el archivo!!!";
exit(1);
}
/*Leer datos del archivo*/
for (int 0 = 30; i < lineas; i++)
{
if (!archivo)
{
cerr << "No se puede abrir el archivo " << endl;
system("PAUSE");
}
archivo>>recordset[i].placa>>recordset[i].marca>>recordset[i].anho>>recordset[i].precio;
}
archivo.close();
for(int i = 30; i <lineas; i++){
cout<<recordset[i].cuaderno<<" "<<dia[i].modelo<<" "<<recordset[i].precio<<endl;
}
system("Pause");
}
} | true |
ac4ce45b9584ac026e5a15837c10ff5bfe0a2c86 | C++ | josepvidalcanet/Epitech | /Tek2/B3 - C++ Seminar/Day15/ex03/ex03.hpp | UTF-8 | 415 | 2.640625 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2021
** B-CPP-300-STG-3-1-CPPD15-pierre.jeannin
** File description:
** ex03
*/
#ifndef EX03_HPP_
#define EX03_HPP_
#include <iostream>
template<typename T>
void foreach(const T *tab, void (func)(const T &), int size)
{
for (int i = 0; i < size; ++i)
(func)(tab[i]);
}
template<typename T>
void print(const T &elem) { std::cout << elem << std::endl; }
#endif /* !EX03_HPP_ */ | true |
b916bd5aa27aea370f48bb056ccd8797086ce20c | C++ | 15600800736/Cpp | /数据结构/map by RBTree/RBTree/Map.h | WINDOWS-1252 | 14,218 | 3.421875 | 3 | [] | no_license |
//
//RBTree.h
//--------------
#pragma once
#include "RBNode.h"
#include "Iterator.h"
//Declare Class CMap
//CMap
//CMap is a kv data structure.It realize with RBTree.The data is visited by key(include inserting,removing and searching)
//CMap has two forms to pass the information to insert the node,one is combining key and data in CPair,the other is offering them partly.
//CMap offers a interface to loop through with an external function
template < class K, class D >class CMap
{
public:
//iterator
typedef typename CMapIterator<K, D> iterator;
//basic function
//Insert a node in the tree,the position is depend on the key
//overloading:insert a node in the tree
//Insert a node by being offerd key and data partly
//It will create a node object as a parameter to call another version
//It will return a CPair contains a iterator pointing to the new node and a boolean variable to show if the insertion successful
CPair<iterator, bool> Insert(K k, D d)
{
CRBNode<K, D> n(k,d);
return Insert(n);
}
//Insert a node by being offerd a pair contains a key and data partly
//It will create a node object as a parameter to call another version
//It will return a CPair contains a iterator pointing to the new node and a boolean variable to show if the insertion successful
CPair<iterator, bool> Insert(CPair<K, D> pair)
{
CRBNode<K, D> n(pair);
return Insert(n);
}
//
CPair<Node(K,D),bool> Erase(K);//return success of fail and the succeed
CPair<iterator,bool> Find(K);
template<class VST>void Travel(VST visit);//visit every node with the function
int Clear();//delete all the nodes
//Only Read
iterator GetBegin()const{ return *m_begin; }
iterator GetEnd()const{ return *m_end; }
Node(K, D) GetRoot()const{ return m_root; }
int GetSize()const{ return m_size; }
bool IsEmpty()const{ return !m_size; }//empty or not,if it's empty , return true.if not, return the begin and false
//operator overloading
const D& operator[](K);
//constructor
CMap():m_root(NULL),m_begin(NULL),m_end(NULL),m_size(0),m_height(0){};//empty tree
explicit CMap(D data) :m_size(1)
{
m_root = new CRBNode<K, D>(data);
m_root->SetColor(Black);
m_root->SetHeight(1);
m_begin = new CMapIterator<K, D>(m_root);
m_end = new CMapIterator<K, D>(m_root);
m_height = m_root->GetHeight();
}
explicit CMap(K key, D data) :m_size(1)
{
m_root = new CRBNode<K, D>(data, key);
m_root->SetColor(Black);
m_root->SetHeight(1);
m_begin = new CMapIterator<K, D>(m_root);
m_end = new CMapIterator<K, D>(m_root);
}
explicit CMap(Node(K, D) r) :m_root(r), m_size(1)
{
m_root->SetColor(Black);//to promise the color of root is black}//empty tree with only a root
m_root->SetHeight(1);
m_begin = new CMapIterator<K, D>(m_root);
m_end = new CMapIterator<K, D>(m_root);
m_height = m_root->GetHeight();
}
explicit CMap(D*,int);//construct by array of D
virtual ~CMap();
protected:
//functions
void UpdateSize(Node(K, D));//update the size of node over the node
CPair<Node(K, D), Node(K, D)> Remove(Node(K, D));//return the actual node removed and its succ
void Release(Node(K, D));
void DoubleRed(Node(K, D));
void DoubleBlack(Node(K, D),Node(K,D));
void UpdateHeight(Node(K, D));
Node(K,D) ConnectThreeFour(Node(K, D));
Node(K, D) ConnectThreeFour(Node(K, D), Node(K, D), Node(K, D),
Node(K, D), Node(K, D), Node(K, D), Node(K, D));
CPair<iterator, bool>InsertAsRoot(CRBNode<K,D>);
CPair<iterator, bool> Insert(CRBNode<K, D>);
int Clear(Node(K, D));//overload: delete the tree below the node
//variables
Node(K,D) m_root;//node of root
iterator* m_begin;
iterator* m_end;
int m_size;
int m_height;//the black height of whole tree
};
//Def
template<class K, class D>
CPair<CMapIterator<K,D>, bool> CMap<K, D>::Find(K key)
{
Node(K, D) target = m_root;
bool success = true;
while (target->GetKey() != key)
{
if (target->GetKey() > key)//aseert 'key' has order
{
if (target->GetLC() == NULL)
{
success = false;
break;
}
else target = target->GetLC();//turn to left child
}
else
{
if (target->GetRC() == NULL)
{
success = false;
break;
}
else target = target->GetRC();//turn to right child
}
}
iterator it(target);
CPair<iterator, bool> pair(it, success);
return pair;
}
template<class K,class D>
CPair<CMapIterator<K, D>, bool> CMap<K, D>::Insert(CRBNode<K,D> n)
{
if (IsEmpty())
{
m_size++; return InsertAsRoot(n);
}
else
{
Node(K, D) node = new CRBNode<K, D>(n);
CPair<iterator, bool> f = Find(node->GetKey());
if (f.second)
{
f.second = false;//if key already exits,It means insert fail,return the iterator to the node
return f;
}
node->SetParent(*f.first);
if (node->GetKey() > (*f.first)->GetKey())
{
(*f.first)->SetRC(node);
}
else
{
(*f.first)->SetLC(node);
}
DoubleRed(node);//sovle the double red problem
f.first = iterator(node);
f.second = true;
m_size++;
if (node->GetKey() < m_begin->GetNode()->GetKey())
{
delete m_begin;
m_begin = new CMapIterator<K, D>(f.first);
}
else if (node->GetKey() > m_end->GetNode()->GetKey())
{
delete m_end;
m_end = new CMapIterator<K, D>(f.first);
}
return f;
}
}
template<class K,class D>
void CMap<K, D>::DoubleRed(Node(K, D) node)
{
if (node == m_root)
{
node->SetColor(Black);
m_root->SetHeight(m_root->GetHeight() + 1);
m_height = m_root->GetHeight();
}
else
{
Node(K, D) parent = node->GetParent();
Node(K, D) grand = parent->GetParent();
//case 1:
//the color of father is black
if (parent->GetColor() == Black) return;
//case 2:
//the color of father is red and the color of uncle is red
else if (parent->GetColor() == Red)
{
Node(K, D) uncle = UNCLE(node);
if (uncle->GetColor() == Red)
{
parent->SetColor(Black); parent->SetHeight(parent->GetHeight() + 1);
uncle->SetColor(Black); uncle->SetHeight(uncle->GetHeight() + 1);
grand->SetColor(Red);
//UpdateAboveHeight(node);
DoubleRed(grand);
}
else if (uncle->GetColor() == Black)
{
Node(K, D) root = ConnectThreeFour(node);
root->SetColor(Black); root->SetHeight(root->GetHeight() + 1);
if(!ISRED(root->GetLC()))
root->GetLC()->SetHeight(root->GetLC()->GetHeight() - 1);
root->GetLC()->SetColor(Red);
if (!ISRED(root->GetRC()))
root->GetRC()->SetHeight(root->GetRC()->GetHeight() - 1);
root->GetRC()->SetColor(Red);
}
}
}
}
template<class K,class D>
CMap<K, D>::CMap(D* Array,int n)
{
int tmp = 0;
m_root = new CRBNode<K, D>(Array[0], static_cast<K>(tmp));
m_root->SetColor(Black);
m_root->SetHeight(1);
m_begin = new CMapIterator<K, D>(m_root);
m_end = new CMapIterator<K, D>(m_root);
for (int i = 1; i < n; i++)
{
Insert(static_cast<K>(i), Array[i]);
}
m_size = n;
m_height = m_root->GetHeight();
}
//code refactoring!!!!!!!!
template<class K,class D>
Node(K, D) CMap<K, D>::ConnectThreeFour(Node(K, D) a, Node(K, D) b, Node(K, D) c,
Node(K, D) ta_l, Node(K, D) ta_r, Node(K, D) tc_l, Node(K, D) tc_r)
{
b->SetLC(a);
a->SetParent(b);
b->SetRC(c);
c->SetParent(b);
a->SetLC(ta_l);
if (ta_l)ta_l->SetParent(a);
a->SetRC(ta_r);
if (ta_r)ta_r->SetParent(a);
c->SetLC(tc_l);
if (tc_l)tc_l->SetParent(c);
c->SetRC(tc_r);
if (tc_r)tc_r->SetParent(c);
return b;
}
template<class K,class D>
Node(K, D) CMap<K, D>::ConnectThreeFour(Node(K, D) x)
{
//get three nodes and four trees
Node(K, D) p = x->GetParent();
Node(K, D) g = p->GetParent();
Node(K, D) tree1 = BROTHER(p);
Node(K, D) tree2 = BROTHER(x);
Node(K, D) tree3 = SAMESIDECHILD(x);
Node(K, D) tree4 = DIFFSIDECHILD(x);
//if x and p on the same side.
if (ISLC(x) && ISLC(p))
{
p->SetParent(g->GetParent());
if (g == m_root)m_root = p;
else REPLACE(g, p);
return ConnectThreeFour(x, p, g, tree3, tree4, tree2, tree1);
}
else if (ISRC(x) && ISRC(p))
{
p->SetParent(g->GetParent());
if (g == m_root)m_root = p;
else REPLACE(g, p);
return ConnectThreeFour(g, p, x, tree1, tree2, tree4, tree3);
}
//if x and p on the different side
else if (ISRC(x) && ISLC(p))
{
x->SetParent(g->GetParent());
if (g == m_root)m_root = x;
else REPLACE(g, p);
return ConnectThreeFour(p, x, g, tree2, tree4, tree3, tree1);
}
else if (ISLC(x) && ISRC(p))
{
x->SetParent(g->GetParent());
if (g == m_root)m_root = x;
else REPLACE(g, p);
return ConnectThreeFour(g, x, p, tree1, tree3, tree4, tree2);
}
else return x;
}
template<class K, class D>template<class VST>
void CMap<K, D>::Travel(VST visit)
{
Node(K, D) x = m_root;
//Go to the most left
while (HAVELC(x))
x = x->GetLC();
while (x)
{
visit(x);
x = x->GetSucc();
}
}
template<class K, class D>
void CMap<K, D>::Release(Node(K, D) node)
{
node->SetParent(NULL);
node->SetLC(NULL);
node->SetRC(NULL);
node->SetKey(NULL);
node->SetData(NULL);
node->SetColor(Red);
node->SetHeight(0);
delete node;
}
template<class K, class D>
CPair<Node(K, D), bool> CMap<K, D>::Erase(K key)//return the father of actual node removed and its succ
{
CPair<iterator, bool> f = Find(key);
CPair<Node(K, D), bool> result(NULL, false);
if (!f.second)
{
return result;
}
result.second = true;
Node(K, D) node = *(f.first);
CPair<Node(K, D), Node(K, D)> pair = Remove(node);
if (IsEmpty())return result;
Node(K, D) a_parent = pair.first;
Node(K, D) replace = pair.second;
result.first = replace;
if (!a_parent)//this means the node has been removed is the root
{
if (ISRED(m_root))
{
m_root->SetColor(Black);
//HEIGHT?
}
return result;
}
if (BALANCE(a_parent))
return result;
if (replace && ISRED(replace))
{
replace->SetColor(Black);
replace->SetHeight(replace->GetHeight() + 1);
return result;
}
DoubleBlack(replace,a_parent);
//Can Clear(node) repalce it?
Release(node);
return result;
}
template<class k,class d>CMap<k,d>::~CMap()
{
if (m_root)
{
Clear();
m_root = NULL;
m_begin = NULL;
m_end = NULL;
m_size = 0;
m_height = 0;
}
else
return;
}
template<class K, class D>
CPair<Node(K, D), Node(K, D)> CMap<K, D>::Remove(Node(K, D) node)
{
Node(K, D) replace = NULL;
Node(K, D) a_parent = node->GetParent();
if (node == **m_begin)
{
delete m_begin;
m_begin = new CMapIterator<K, D>(node->GetSucc());
}
if (node == **m_end)
{
delete m_end;
m_end = new CMapIterator<K, D>(node->GetFore());
}
//remove
if (!HAVELC(node) && HAVERC(node))
{
replace = node->GetRC();
//swap
replace->SetParent(node->GetParent());
if (node == m_root) m_root = replace;
else REPLACE(node, replace);
}
else if (!HAVERC(node) && HAVELC(node))
{
replace = node->GetLC();
//swap
replace->SetParent(node->GetParent());
if (node == m_root) m_root = replace;
else REPLACE(node, replace);
}
else if (ISLEAF(node) && !ISROOT(node))
REPLACE(node, NULL);
else if (ISLEAF(node) && ISROOT(node))
m_root = NULL;
//update m_begin & m_end;
else
{
Node(K,D) succ = node->GetSucc();
Node(K, D) actual_deleted = succ;
//if node's succ's parent,then node is the actual node deleted
if (succ->GetParent() == node)
{
actual_deleted = node;
}
//record information
replace = actual_deleted->GetRC();
a_parent = actual_deleted->GetParent();
//swap and remove
//from child
succ->SetLC(node->GetLC());
node->GetLC()->SetParent(succ);
if (succ->GetParent() != node)
{
succ->SetRC(node->GetRC());
node->GetRC()->SetParent(succ);
a_parent->SetLC(replace);
replace->SetParent(a_parent);
}
//from parent
succ->SetParent(node->GetParent());
if (node == m_root)m_root = succ;
else REPLACE(node, succ);
}
m_size--;
CPair<Node(K, D), Node(K, D)> result(a_parent, replace);
return result;
}
template<class K, class D>int CMap<K, D>::Clear()
{
return Clear(m_root);
}
template<class K, class D>int CMap<K, D>::Clear(Node(K, D) node)
{
if (!node) return 0;
Node(K, D) lc = node->GetLC();
Node(K, D) rc = node->GetRC();
delete node;
Clear(lc);
Clear(rc);
}
template<class K,class D>
CPair<CMapIterator<K,D>, bool> CMap<K, D>::InsertAsRoot(CRBNode<K,D> n)
{
m_root = new CRBNode<K, D>(n);
m_root->SetColor(Black);
m_root->SetHeight(1);
m_begin = new CMapIterator<K, D>(m_root);
m_end = new CMapIterator<K, D>(m_root);
m_size = 1;
m_height = m_root->GetHeight();
iterator it(m_root);
CPair<iterator, bool> ret(it, true);
return ret;
}
template<class K,class D>
void CMap<K, D>::DoubleBlack(Node(K, D) replace,Node(K,D) a_parent)
{
if (a_parent)
{
Node(K, D) brother = BROTHER(replace);
if (!ISRED(brother))
{
Node(K, D) nephew = GETREDCHILD(brother);
if (nephew)
{
Node(K, D) grand = a_parent->GetParent();
Color oldcolor = a_parent->GetColor();
Node(K, D) new_parent = ConnectThreeFour(nephew);
grand ? (REPLACE(a_parent, new_parent)) : (m_root = new_parent);
new_parent->SetColor(oldcolor);
if (HAVELC(new_parent))
new_parent->GetLC()->SetColor(Black);
if (HAVERC(new_parent))
new_parent->GetRC()->SetColor(Black);
/*UpdateHeight(new_parent);*/
}
else
{
nephew->SetColor(Red);
if (ISRED(a_parent))
a_parent->SetColor(Black);
else
{
a_parent->SetHeight(a_parent->GetHeight() - 1);
DoubleBlack(a_parent, a_parent->GetParent());
}
}
}
else
{
brother->SetColor(Black);
a_parent->SetColor(Red);
brother->SetParent(a_parent->GetParent());
a_parent->SetParent(brother);
if (ISLC(brother))
{
brother->SetRC(a_parent);
a_parent->SetLC(brother->GetRC());
if (brother->GetRC()) brother->GetRC()->SetParent(a_parent);
}
else
{
brother->SetLC(a_parent);
a_parent->SetRC(brother->GetLC());
if (brother->GetLC())brother->GetLC()->SetParent(a_parent);
}
DoubleBlack(replace,a_parent);
}
}
}
template<class K,class D>
void CMap<K, D>::UpdateHeight(Node(K, D) node)
{
if (!node) return;
node->SetHeight(ISRED(node) ?
max(HEIGHT(node->GetLC()->GetHeight()), HEIGHT(node->GetRC()->GetHeight())) :
max(HEIGHT(node->GetLC()->GetHeight()), HEIGHT(node->GetRC()->GetHeight())) + 1);
Node(K, D) p = node->GetParent();
UpdateHeight(p);
}
template<class K,class D>
void CMap<K, D>::UpdateSize(Node(K, D) node)
{
} | true |
928e7ae853d0098d21814611038114fb2d8bd554 | C++ | amoljore7/01-Logic-Building-Program-All | /01-Problems-On-C/06_Problems On String/50_PalindromeCaseInsensitive/MainFile.cpp | UTF-8 | 1,018 | 3.34375 | 3 | [] | no_license | #include<stdio.h>
#define TRUE 1
#define FALSE 0
typedef int BOOL;
BOOL Palindrome(char *str)
{
if(NULL == str)
{
return FALSE;
}
char *Start;
char *End;
char Temp;
Start=str;
End=str;
while(*End != '\0')
{
End++;
}
End--;
while(Start<=End)
{
if( ((*Start>='A')&&(*Start<='Z'))&&((*End>='a')&&(*End<='z')) )
{
*Start=*Start+32;
}
else if( ((*Start>='a')&&(*Start<='z'))&&((*End>='A')&&(*End<='Z')) )
{
*Start=*Start-32;
}
if(*Start != *End)
{
break;
}
Start++;
End--;
}
if(Start>End)
{
return TRUE;
}
else
{
return FALSE;
}
}
int main(int argc, char* arhv[])
{
char cArr[30]={'\0'};
BOOL bRet=TRUE;
printf("\t\tEnter String: ");
scanf("%[^'\n']s",cArr);
printf("\n");
bRet=Palindrome(cArr);
printf("\n");
if(bRet==TRUE)
{
printf("\t\tString is Palindrom\n");
}
else
{
printf("\t\tString is Not Palindrome\n");
}
return 0;
}
| true |
7f23fc66dbf8673f979b30ec9ae8bd4f6e9cf4f2 | C++ | karngyan/cnslab | /myutility.h | UTF-8 | 744 | 3.328125 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
template<typename _Ty1, typename _Ty2>
std::ostream& operator<<(std::ostream& _os, const std::pair<_Ty1, _Ty2>& _p) {
_os << _p.first << ' ' << _p.second;
return _os;
}
void _capitalise(string &s) {
for (auto &it: s) {
if (it >= 'a' and it <= 'z') {
it = it - 'a' + 'A';
}
}
}
// legacy
// now it removes anything thats not a
// capital letter
string _remove_spaces(string s) {
string ans = "";
for (auto it: s) {
if (it >= 'A' and it <= 'Z')
ans += it;
}
return ans;
}
bool _check_specific_char(string &s, char c) {
for (auto it : s) {
if (it == c)
return true;
}
return false;
} | true |
2d9cf9d821700f13ed45cb5c9d0d120a5518900c | C++ | jwakely/Sprout | /sprout/functional/hash/hash.hpp | UTF-8 | 9,877 | 2.6875 | 3 | [
"BSL-1.0"
] | permissive | #ifndef SPROUT_FUNCTIONAL_HASH_HASH_HPP
#define SPROUT_FUNCTIONAL_HASH_HASH_HPP
#include <cstddef>
#include <limits>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/iterator/operation.hpp>
#include <sprout/functional/hash/hash_fwd.hpp>
#include <sprout/type_traits/enabler_if.hpp>
namespace sprout {
//
// hash_value
//
inline SPROUT_CONSTEXPR std::size_t hash_value(bool v);
inline SPROUT_CONSTEXPR std::size_t hash_value(char v);
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned char v);
inline SPROUT_CONSTEXPR std::size_t hash_value(signed char v);
inline SPROUT_CONSTEXPR std::size_t hash_value(char16_t v);
inline SPROUT_CONSTEXPR std::size_t hash_value(char32_t v);
inline SPROUT_CONSTEXPR std::size_t hash_value(wchar_t v);
inline SPROUT_CONSTEXPR std::size_t hash_value(short v);
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned short v);
inline SPROUT_CONSTEXPR std::size_t hash_value(int v);
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned int v);
inline SPROUT_CONSTEXPR std::size_t hash_value(long v);
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned long v);
inline SPROUT_CONSTEXPR std::size_t hash_value(long long v);
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned long long v);
//inline SPROUT_CONSTEXPR std::size_t hash_value(float v);
//inline SPROUT_CONSTEXPR std::size_t hash_value(double v);
//inline SPROUT_CONSTEXPR std::size_t hash_value(long double v);
template<
typename T,
typename sprout::enabler_if<std::is_pointer<typename std::remove_reference<T>::type>::value>::type
>
inline SPROUT_CONSTEXPR std::size_t hash_value(T&& v);
template<typename T, std::size_t N>
inline SPROUT_CONSTEXPR std::size_t hash_value(T const (&v)[N]);
namespace hash_detail {
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_value_signed_2(T val, int length, std::size_t seed, T positive, std::size_t i) {
return i > 0
? hash_value_signed_2(
val,
length,
seed ^ static_cast<std::size_t>((positive >> i) + (seed << 6) + (seed >> 2)),
positive,
i - std::numeric_limits<std::size_t>::digits
)
: seed ^ static_cast<std::size_t>(val + (seed << 6) + (seed >> 2))
;
}
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_value_signed_1(T val, int length, std::size_t seed, T positive) {
return hash_value_signed_2(val, length, seed, positive, length * std::numeric_limits<std::size_t>::digits);
}
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_value_signed(T val) {
return sprout::hash_detail::hash_value_signed_1(
val,
(std::numeric_limits<T>::digits - 1) / std::numeric_limits<std::size_t>::digits,
0,
val < 0 ? -1 - val : val
);
}
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_value_unsigned_2(T val, int length, std::size_t seed, std::size_t i) {
return i > 0
? hash_value_unsigned_2(
val,
length,
seed ^ static_cast<std::size_t>((val >> i) + (seed << 6) + (seed >> 2)),
i - std::numeric_limits<std::size_t>::digits
)
: seed ^ static_cast<std::size_t>(val + (seed << 6) + (seed >> 2))
;
}
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_value_unsigned_1(T val, int length, std::size_t seed) {
return hash_value_unsigned_2(val, length, seed, length * std::numeric_limits<std::size_t>::digits);
}
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_value_unsigned(T val) {
return sprout::hash_detail::hash_value_unsigned_1(
val,
(std::numeric_limits<T>::digits - 1) / std::numeric_limits<std::size_t>::digits,
0
);
}
inline std::size_t hash_value_pointer_1(std::size_t x) {
return x + (x >> 3);
}
template<typename T>
std::size_t hash_value_pointer(T const* v) {
return sprout::hash_detail::hash_value_pointer_1(static_cast<std::size_t>(reinterpret_cast<std::ptrdiff_t>(v)));
}
} // namespace hash_detail
//
// hash_value
//
inline SPROUT_CONSTEXPR std::size_t hash_value(bool v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(char v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned char v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(signed char v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(char16_t v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(char32_t v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(wchar_t v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(short v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned short v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(int v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned int v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(long v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned long v) {
return static_cast<std::size_t>(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(long long v) {
return sprout::hash_detail::hash_value_signed(v);
}
inline SPROUT_CONSTEXPR std::size_t hash_value(unsigned long long v) {
return sprout::hash_detail::hash_value_unsigned(v);
}
template<
typename T,
typename sprout::enabler_if<std::is_pointer<typename std::remove_reference<T>::type>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR std::size_t hash_value(T&& v) {
return sprout::hash_detail::hash_value_pointer(v);
}
template<typename T, std::size_t N>
inline SPROUT_CONSTEXPR std::size_t hash_value(T const (&v)[N]) {
return sprout::hash_range(&v[0], &v[0] + N);
}
//
// to_hash
//
template<typename T>
inline SPROUT_CONSTEXPR std::size_t to_hash(T const& v) {
using sprout::hash_value;
return hash_value(v);
}
//
// hash_combine
//
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_combine(std::size_t seed, T const& v) {
return seed ^ (sprout::to_hash(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
}
//
// hash_range
//
template<typename Iterator>
inline SPROUT_CONSTEXPR std::size_t hash_range(std::size_t seed, Iterator first, Iterator last) {
return first != last
? sprout::hash_range(sprout::hash_combine(seed, *first), sprout::next(first), last)
: seed
;
}
template<typename Iterator>
inline SPROUT_CONSTEXPR std::size_t hash_range(Iterator first, Iterator last) {
return sprout::hash_range(0, first, last);
}
namespace detail {
template<typename T>
inline SPROUT_CONSTEXPR std::size_t hash_values_combine_impl(std::size_t seed, T const& v) {
return sprout::hash_combine(seed, v);
}
template<typename Head, typename... Tail>
inline SPROUT_CONSTEXPR std::size_t hash_values_combine_impl(std::size_t seed, Head const& head, Tail const&... tail) {
return sprout::detail::hash_values_combine_impl(sprout::hash_combine(seed, head), tail...);
}
} // namespace detail
//
// hash_values_combine
//
template<typename... Args>
inline SPROUT_CONSTEXPR std::size_t hash_values_combine(std::size_t seed, Args const&... args) {
return sprout::detail::hash_values_combine_impl(seed, args...);
}
//
// hash_values
//
template<typename... Args>
inline SPROUT_CONSTEXPR std::size_t hash_values(Args const&... args) {
return sprout::hash_values_combine(0, args...);
}
//
// hash
//
template<typename T>
struct hash {
public:
typedef T argument_type;
typedef std::size_t result_type;
public:
SPROUT_CONSTEXPR std::size_t operator()(T const& v) const {
return sprout::to_hash(v);
}
};
template<typename T>
struct hash<T const>
: public sprout::hash<T>
{};
template<typename T>
struct hash<T volatile>
: public sprout::hash<T>
{};
template<typename T>
struct hash<T const volatile>
: public sprout::hash<T>
{};
#define SPROUT_HASH_SPECIALIZE(type) \
template<> \
struct hash<type> { \
public: \
typedef type argument_type; \
typedef std::size_t result_type; \
public: \
SPROUT_CONSTEXPR std::size_t operator()(type v) const { \
return sprout::to_hash(v); \
} \
}
#define SPROUT_HASH_SPECIALIZE_REF(type) \
template<> \
struct hash<type> { \
public: \
typedef type argument_type; \
typedef std::size_t result_type; \
public: \
SPROUT_CONSTEXPR std::size_t operator()(type const& v) const { \
return sprout::to_hash(v); \
} \
}
SPROUT_HASH_SPECIALIZE(bool);
SPROUT_HASH_SPECIALIZE(char);
SPROUT_HASH_SPECIALIZE(signed char);
SPROUT_HASH_SPECIALIZE(unsigned char);
SPROUT_HASH_SPECIALIZE(char16_t);
SPROUT_HASH_SPECIALIZE(char32_t);
SPROUT_HASH_SPECIALIZE(wchar_t);
SPROUT_HASH_SPECIALIZE(short);
SPROUT_HASH_SPECIALIZE(unsigned short);
SPROUT_HASH_SPECIALIZE(int);
SPROUT_HASH_SPECIALIZE(unsigned int);
SPROUT_HASH_SPECIALIZE(long);
SPROUT_HASH_SPECIALIZE(unsigned long);
SPROUT_HASH_SPECIALIZE(long long);
SPROUT_HASH_SPECIALIZE(unsigned long long);
#undef SPROUT_HASH_SPECIALIZE
#undef SPROUT_HASH_SPECIALIZE_REF
template<typename T>
struct hash<T*> {
public:
typedef T* argument_type;
typedef std::size_t result_type;
public:
std::size_t operator()(T* v) const {
return sprout::to_hash(v);
}
};
} //namespace sprout
#endif // #ifndef SPROUT_FUNCTIONAL_HASH_HASH_HPP
| true |
7fbd5aaad36678f4f183581ad9e470360384b75d | C++ | RichardUSTC/JyRender | /Engine/Device/DeviceBuffer.h | UTF-8 | 2,441 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Common/Ref.h"
#include <vector>
class Buffer : public Ref
{
protected:
uint32_t mBufferSize{0};
};
const uint8_t MAX_BONE_COUNT = 255;
const uint8_t MAX_BONE_PER_VERTEX = 4;
const uint8_t BONE_INDEX_SIZE = sizeof(uint8_t);
const uint8_t BONE_WEIGHT_SIZE = sizeof(float);
enum class ElementUsage
{
Position,
UV0,
UV1,
UV2,
UV3,
UV4,
UV5,
UV6,
UV7,
Normal,
Tangent,
VertexColor,
BoneIndices,
BoneWeights,
};
inline const char* ATTRIBUTE_BINDING_DEFINES =
"#define POSITION 0\n"
"#define UV0 1\n"
"#define UV1 2\n"
"#define UV2 3\n"
"#define UV3 4\n"
"#define UV4 5\n"
"#define UV5 6\n"
"#define UV6 7\n"
"#define UV7 8\n"
"#define NORMAL 9\n"
"#define TANGENT 10\n"
"#define VERTEX_COLOR 11\n"
"#define BONE_INDICES 12\n"
"#define BONE_WEIGHTS 13\n";
enum class BufferUsage
{
StaticDraw,
StaticRead,
StaticCopy,
DynamicDraw,
DynamicRead,
DynamicCopy,
StreamDraw,
StreamRead,
StreamCopy,
};
uint8_t GetElementUsageSize(ElementUsage usage);
struct VertexFormat
{
void PushElement(ElementUsage usage);
std::vector<ElementUsage> mElements;
size_t mStride{0};
};
class VertexBuffer : public Buffer
{
public:
const VertexFormat& GetFormat() const { return mFormat; }
protected:
VertexFormat mFormat;
};
using VertexBufferPtr = OwnerPtr<VertexBuffer>;
enum class IndexType
{
Index8,
Index16,
Index32,
};
inline size_t GetIndexSize(IndexType indexType)
{
static const size_t IndexSizes[] = {1, 2, 4};
return IndexSizes[static_cast<uint8_t>(indexType)];
}
class IndexBuffer : public Buffer
{
public:
IndexType GetIndexType() const { return mIndexType; }
protected:
IndexType mIndexType{IndexType::Index16};
};
using IndexBufferPtr = OwnerPtr<IndexBuffer>;
enum class PrimitiveType
{
PointList,
LineList,
LineStrip,
TriangleList,
TriangleStrip,
TriangleFan,
};
struct Geometry
{
std::vector<VertexBufferPtr> mVertexBuffers;
IndexBufferPtr mIndexBuffer{nullptr};
size_t mVertexStart{0}; // Only used when mIndexBuffer is nullptr
size_t mIndexStart{0};
size_t mPrimitiveCount{0};
PrimitiveType mPrimitiveType{PrimitiveType::PointList};
};
| true |
d3c520c9fd05e9f19e22ed03127f5987d8e00a39 | C++ | mauricelos/CarND-Path-Planning-Project | /src/main.cpp | UTF-8 | 31,765 | 2.875 | 3 | [] | no_license | #include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"
#include "spline.h"
#include <algorithm>
using namespace std;
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_first_of("}");
if (found_null != string::npos) {
return "";
} else if (b1 != string::npos && b2 != string::npos) {
return s.substr(b1, b2 - b1 + 2);
}
return "";
}
double distance(double x1, double y1, double x2, double y2) {
return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
//converting mph to inc
double mphtoinc(double mph) {
return mph * 0.02 * 0.44704;
}
//converting ms to inc
double mstoinc(double ms) {
return ms * 0.02;
}
//converting mph to ms
double mph_to_ms(double mph) {
return mph * 0.44704;
}
//converting ms to mph
double ms_to_mph(double ms) {
return ms * 2.23694;
}
//function to constently changing dist_inc to approach given speed limit
double set_speed(double desired, double pre_speed) {
//takes the difference in current speed to desired speed and increases dist_inc if error is negative and decreases dist_inc if error positive
double error = desired - pre_speed;
if(fabs(error) < 0.01){
error = 0;
}
return mphtoinc(pre_speed+error);
}
//same as set_speed just for meters per second
double set_speedms(double desired, double pre_speed) {
double desired_mph = desired * 2.23694;
double error = desired_mph - pre_speed;
if(fabs(error) < 0.01){
error = 0;
}
return mphtoinc(pre_speed+error);
}
//creating a Path Planning class to handle actions like Lane Cahnges and Acceleration and Deacceleration
class PathPlanning {
private:
//creating a speed changing status with acceleration and deacceleration
enum SPEED_CHANGE {ACCELERATE, DEACCELERATE};
SPEED_CHANGE speedchange;
//creating a lane changing status with left and right turn
enum LANE_CHANGE {CHANGE_LEFT, CHANGE_RIGHT};
LANE_CHANGE lanechange;
//progress
double progress;
public:
PathPlanning();
~PathPlanning() {};
//bool operation to determine each action and void operation to execute actions
bool IsNoChange();
//speed change with desired goal inc as input
bool IsChangeSpeed();
void SetChangeSpeed(double goal_inc);
void ChangeSpeed();
//lane change with desired lane and desired speed (to accelerate back to ca. 50 mph)
bool IsChangeLane();
void SetChangeLane(double goal_lane, double carspeed);
void ChangeLane();
//all possible actions available
enum STATUS {CHANGE_SPEED, CHANGE_LANE, NO_CHANGE};
STATUS status;
//initializing parameters
double dist_inc;
double start_inc;
double goal_inc;
double start_lane;
double goal_lane;
double carspeed;
double lane;
double diff;
double pi = M_PI;
};
PathPlanning::PathPlanning() {
status = CHANGE_SPEED;
status = NO_CHANGE;
}
//bool operations to determine which action to execute
bool PathPlanning::IsNoChange() {
return status == NO_CHANGE;
}
bool PathPlanning::IsChangeSpeed() {
return status == CHANGE_SPEED;
}
//executing determined action
void PathPlanning::SetChangeSpeed(double goal_inc) {
status = CHANGE_SPEED;
this->goal_inc = goal_inc;
progress = 0.0001;
start_inc = dist_inc;
//checking if desired speed is lower or higher than current speed
if (goal_inc > start_inc) {
//calculating the differnce in speed
speedchange = ACCELERATE;
diff = (goal_inc - start_inc);
}
else {
//calculating the differnce in speed
speedchange = DEACCELERATE;
diff = (start_inc - goal_inc);
}
}
//changing speed function
void PathPlanning::ChangeSpeed() {
//checking if car should accelerate or deaccelerate or not change. And changing dist_inc smoothly to desired value
if ((speedchange == ACCELERATE) and (progress < 100.0)) {
progress += 1/(diff*6);
dist_inc += 0.0015;
}
else if ((speedchange == DEACCELERATE) and (progress < 100.0)) {
progress += 1/(diff*6);
dist_inc -= 0.002;
}
else {
status = NO_CHANGE;
}
}
//bool operations to determine which action to execute
bool PathPlanning::IsChangeLane() {
return status == CHANGE_LANE;
}
//executing determined action
void PathPlanning::SetChangeLane(double goal_lane, double carspeed) {
status = CHANGE_LANE;
this->goal_lane = goal_lane;
this->carspeed = carspeed;
progress = 0.0001;
start_lane = lane;
//checking if desired d is lower or higher than current d
if (goal_lane > start_lane) {
//calculating the differnce in d
lanechange = CHANGE_RIGHT;
}
else {
//calculating the differnce in d
lanechange = CHANGE_LEFT;
}
}
void PathPlanning::ChangeLane() {
//checking if car should change right or change left or not change. And steering smoothly to desired lane
if ((lanechange == CHANGE_RIGHT) and (progress < 1.0) and (lane <= goal_lane)) {
progress += 0.008;
lane = start_lane + (2 * (1 - cos(progress * pi)));
if (dist_inc < set_speed(46.0, carspeed)) {
dist_inc += 0.001;
}
}
else if ((lanechange == CHANGE_LEFT) and (progress < 1.0) and (lane >= goal_lane)) {
progress += 0.008;
lane = start_lane - (2 * (1 - cos(progress * pi)));
if (dist_inc < set_speed(46.0, carspeed)) {
dist_inc += 0.001;
}
}
else {
status = NO_CHANGE;
}
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
vector<double> map_waypoints_angle;
// Waypoint map to read from
string map_file_ = "./data/highway_map.csv";
// // The max s value before wrapping around the track back to 0
double max_s = 6945.554;
ifstream in_map_(map_file_.c_str(), ifstream::in);
string line;
while (getline(in_map_, line)) {
istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
map_waypoints_angle.push_back(pi()/2 + atan2(d_y,d_x));
}
//adding some extra waypoints to the end for a smoother transition between laps
for (int i = 0; i < 10; ++i) {
map_waypoints_x.push_back(map_waypoints_x[i]);
map_waypoints_y.push_back(map_waypoints_y[i]);
map_waypoints_s.push_back(max_s+map_waypoints_s[i]);
map_waypoints_dx.push_back(map_waypoints_dx[i]);
map_waypoints_dy.push_back(map_waypoints_dy[i]);
}
//creating splines
tk::spline sx;
tk::spline sy;
tk::spline sdx;
tk::spline sdy;
sx.set_points(map_waypoints_s, map_waypoints_x);
sy.set_points(map_waypoints_s, map_waypoints_y);
sdx.set_points(map_waypoints_s, map_waypoints_dx);
sdy.set_points(map_waypoints_s, map_waypoints_dy);
//setting initial parameters for lane position and speed (dist_inc)
PathPlanning pp;
pp.dist_inc = 0.00;
pp.lane = 6.0;
h.onMessage([&pp, &map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy, &sx, &sy, &sdx, &sdy](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
//auto sdata = string(data).substr(0, length);
//cout << sdata << endl;
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
json msgJson;
vector<double> next_x_vals;
vector<double> next_y_vals;
//evaluating in which lane the car is currently
enum LANE_ID { LEFT, MID, RIGHT };
LANE_ID car_lane;
if (car_d < 3.0) {
car_lane = LEFT;
}
else if ((car_d >= 3.0) and (car_d < 9.0)) {
car_lane = MID;
}
else if (car_d > 9.0) {
car_lane = RIGHT;
}
//creating vectors to sort different information
vector<double> leftlane_infront;
vector<double> midlane_infront;
vector<double> rightlane_infront;
vector<double> rightlane_infront_dist;
vector<double> midlane_infront_dist;
vector<double> leftlane_infront_dist;
vector<double> leftlane_behind;
vector<double> midlane_behind;
vector<double> rightlane_behind;
vector<double> leftlane_behind_dist;
vector<double> midlane_behind_dist;
vector<double> rightlane_behind_dist;
//asigning each value to a category and calucaling speed and distance of the other cars with given sensor information
for (int i = 0; i < sensor_fusion.size(); ++i) {
auto ai = sensor_fusion[i];
double ai_id = ai[0];
double ai_x = ai[1];
double ai_y = ai[2];
double ai_vx = ai[3];
double ai_vy = ai[4];
double ai_s = ai[5];
double ai_d = ai[6];
double ai_v = sqrt(ai_vx*ai_vx + ai_vy*ai_vy);
double ai_distance = distance(car_x, car_y, ai_x, ai_y);
//only considering cars within range of 40 meters
if (ai_distance < 40.0) {
//sorting by lane and if car is infront or behind my car
if ((ai_d < 5.0)) {
//for left lane
if (ai_s > car_s) {
leftlane_infront.push_back(ai_v);
leftlane_infront_dist.push_back(ai_distance);
}
else {
leftlane_behind.push_back(ai_v);
leftlane_behind_dist.push_back(ai_distance);
}
}
else if ((ai_d >= 3.0) and (ai_d < 9.0) ) {
//for middle lane
if (ai_s > car_s) {
midlane_infront.push_back(ai_v);
midlane_infront_dist.push_back(ai_distance);
}
else {
midlane_behind.push_back(ai_v);
midlane_behind_dist.push_back(ai_distance);
}
}
else if ((ai_d > 7.0)) {
//for right lane
if (ai_s > car_s) {
rightlane_infront.push_back(ai_v);
rightlane_infront_dist.push_back(ai_distance);
}
else {
rightlane_behind.push_back(ai_v);
rightlane_behind_dist.push_back(ai_distance);
}
}
}
}
//just to see the progress around the track
cout << "Track completed: " << (float)(int)(100*(100*(car_s/max_s)))/100 << "%" << endl;
//just to display the car's postion and where other cars are
if (car_lane == RIGHT) {
cout << endl;
cout << "| " << leftlane_infront.size();
cout << " | " << midlane_infront.size();
cout << " | " << rightlane_infront.size() << " |" << endl;
cout << "| |" << " " << "|Car|" << endl;
cout << "| " << leftlane_behind.size();
cout << " | " << midlane_behind.size();
cout << " | " << rightlane_behind.size() << " |" << endl << endl;
}
else if (car_lane == MID) {
cout << endl;
cout << "| " << leftlane_infront.size();
cout << " | " << midlane_infront.size();
cout << " | " << rightlane_infront.size() << " |" << endl;
cout << "| |" << "Car" << "| |" << endl;
cout << "| " << leftlane_behind.size();
cout << " | " << midlane_behind.size();
cout << " | " << rightlane_behind.size() << " |" << endl << endl;
}
else {
cout << endl;
cout << "| " << leftlane_infront.size();
cout << " | " << midlane_infront.size();
cout << " | " << rightlane_infront.size() << " |" << endl;
cout << "|Car|" << " " << "| |" << endl;
cout << "| " << leftlane_behind.size();
cout << " | " << midlane_behind.size();
cout << " | " << rightlane_behind.size() << " |" << endl << endl;
}
double pos_x;
double pos_y;
double pos_s;
//creating the trajectory with pervious path points if existent
for(int i = 0; i < previous_path_x.size(); i++) {
next_x_vals.push_back(previous_path_x[i]);
next_y_vals.push_back(previous_path_y[i]);
}
if(previous_path_x.size() == 0) {
pos_x = car_x;
pos_y = car_y;
pos_s = car_s;
}
else {
pos_x = previous_path_x[previous_path_x.size()-1];
pos_y = previous_path_y[previous_path_x.size()-1];
double pos_x2 = previous_path_x[previous_path_x.size()-2];
double pos_y2 = previous_path_y[previous_path_x.size()-2];
}
//waypoints created with Frenet s and x,y,dx,dy
double w_sx, w_sy, w_sdx, w_sdy;
for(int i = 0; i < 50-previous_path_x.size(); i++) {
//checking if speed has to be changed and if so change it. The same applies for lane changes
if (pp.IsChangeSpeed()) {
pp.ChangeSpeed();
}
else if (pp.IsChangeLane()) {
pp.ChangeLane();
}
else {
//checking if car is in left lane and assigning 46mph speed target to car if no other car is in front
if(car_lane == LEFT) {
if (leftlane_infront.size() == 0) {
if (pp.dist_inc < set_speed(46.0, car_speed)) {
pp.SetChangeSpeed(set_speed(46.0, car_speed));
}
}
else {
//if there is a car infront check for other lane/lanes and accelerate back to traget speed if possible
if ((midlane_infront.size() == 0) and (midlane_behind.size() == 0)) {
pp.SetChangeLane(6.0, car_speed);
}//also change lane if there is no car infront in the target lane plus cars in the target lane have to be 20 meters away and not travel 2m/s faster than own car
else if ((midlane_infront.size() == 0) and (*min_element(midlane_behind_dist.begin(), midlane_behind_dist.end()) > 20.0) and (midlane_behind[std::distance(midlane_behind_dist.begin(),min_element(midlane_behind_dist.begin(), midlane_behind_dist.end()))] - mph_to_ms(car_speed)) < 2.0) {
pp.SetChangeLane(6.0, car_speed);
}//if there is no way to change lane the car travels at the speed of the car right infront of it
else if (leftlane_infront.size() > 0) {
double min_dist = *min_element(leftlane_infront_dist.begin(), leftlane_infront_dist.end());
int min_dist_n = std::distance(leftlane_infront_dist.begin(), min_element(leftlane_infront_dist.begin(), leftlane_infront_dist.end()));
//if distance to car infront is to low, speed gets reduces by 1.5 m/s until distance is back to normal
if (min_dist < 20.0) {
pp.SetChangeSpeed(set_speedms(leftlane_infront[min_dist_n]-1.5, car_speed));
}//if distance is to big, speed get increased until distance is back to normal
else if (min_dist > 40.0) {
pp.SetChangeSpeed(set_speedms(leftlane_infront[min_dist_n]+1, car_speed));
}//ideal scenario where own car holds perfect distance to car infront
else {
pp.SetChangeSpeed(set_speedms(leftlane_infront[min_dist_n], car_speed));
}
}
} //////////// SAME FOR ALL OTHER LANES, SEE COMMENTARY ABOVE ////////////
}
else if (car_lane == MID) {
if (midlane_infront.size() == 0) {
if (pp.dist_inc < set_speed(46.0, car_speed)) {
pp.SetChangeSpeed(set_speed(46.0, car_speed));
}
}
else {
if ((leftlane_infront.size() == 0) and (leftlane_behind.size() == 0)) {
pp.SetChangeLane(2.0, car_speed);
}
else if ((leftlane_infront.size() == 0) and (*min_element(leftlane_behind_dist.begin(), leftlane_behind_dist.end()) > 20.0) and (leftlane_behind[std::distance(leftlane_behind_dist.begin(),min_element(leftlane_behind_dist.begin(), leftlane_behind_dist.end()))] - mph_to_ms(car_speed)) < 2.0) {
pp.SetChangeLane(2.0, car_speed);
}
else if ((rightlane_infront.size() == 0) and (rightlane_behind.size() == 0)) {
pp.SetChangeLane(10.0, car_speed);
}
else if ((rightlane_infront.size() == 0) and (*min_element(rightlane_behind_dist.begin(), rightlane_behind_dist.end()) > 20.0) and (rightlane_behind[std::distance(rightlane_behind_dist.begin(),min_element(rightlane_behind_dist.begin(), rightlane_behind_dist.end()))] - mph_to_ms(car_speed)) < 2.0) {
pp.SetChangeLane(10.0, car_speed);
}
else if (midlane_infront.size() > 0) {
double min_dist = *min_element(midlane_infront_dist.begin(), midlane_infront_dist.end());
int min_dist_n = std::distance(midlane_infront_dist.begin(),min_element(midlane_infront_dist.begin(), midlane_infront_dist.end()));
if (min_dist < 20.0) {
pp.SetChangeSpeed(set_speedms(midlane_infront[min_dist_n]-1.5, car_speed));
}
else if (min_dist > 40.0) {
pp.SetChangeSpeed(set_speedms(midlane_infront[min_dist_n]+1, car_speed));
}
else {
pp.SetChangeSpeed(set_speedms(midlane_infront[min_dist_n], car_speed));
}
}
}
}
else if (car_lane == RIGHT) {
if (rightlane_infront.size() == 0) {
if (pp.dist_inc < set_speed(46.0, car_speed)) {
pp.SetChangeSpeed(set_speed(46.0, car_speed));
}
}
else {
if ((midlane_infront.size() == 0) and (midlane_behind.size() == 0)) {
pp.SetChangeLane(6.0, car_speed);
}
else if ((midlane_infront.size() == 0) and (*min_element(midlane_behind_dist.begin(), midlane_behind_dist.end()) > 20.0) and (midlane_behind[std::distance(midlane_behind_dist.begin(),min_element(midlane_behind_dist.begin(), midlane_behind_dist.end()))] - mph_to_ms(car_speed)) < 2.0) {
pp.SetChangeLane(6.0, car_speed);
}
else if (rightlane_infront.size() > 0) {
double min_dist = *min_element(rightlane_infront_dist.begin(), rightlane_infront_dist.end());
int min_dist_n = std::distance(rightlane_infront_dist.begin(),min_element(rightlane_infront_dist.begin(), rightlane_infront_dist.end()));
if (min_dist < 20.0) {
pp.SetChangeSpeed(set_speedms(rightlane_infront[min_dist_n]-1.5, car_speed));
}
else if (min_dist > 40.0) {
pp.SetChangeSpeed(set_speedms(rightlane_infront[min_dist_n]+1, car_speed));
}
else {
pp.SetChangeSpeed(set_speedms(rightlane_infront[min_dist_n], car_speed));
}
}
}
}
}
//adding dist_inc to the position in s coordinates
pos_s += pp.dist_inc;
pos_s = fmod(pos_s, max_s);
//calculating the functions with position s as x value
w_sx = sx(pos_s);
w_sy = sy(pos_s);
w_sdx = sdx(pos_s);
w_sdy = sdy(pos_s);
//getting the current lane from pathplanning
double lane = pp.lane;
//calculating the final positions for the trajectory with the lane d value, sx, sy, sdx, sdy value
pos_x = w_sx + lane * w_sdx;
pos_y = w_sy + lane * w_sdy;
next_x_vals.push_back(pos_x);
next_y_vals.push_back(pos_y);
}
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
//this_thread::sleep_for(chrono::milliseconds(1000));
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the
// program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1) {
res->end(s.data(), s.length());
} else {
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
| true |
1882ffd3ba8c12de44fbb830792e727ef44e8347 | C++ | NoCodeBugsFree/EndlessRunner | /Source/EndlessRunner/EndlessRunnerCharacter.h | UTF-8 | 6,853 | 2.640625 | 3 | [] | no_license | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/Character.h"
#include "EndlessRunnerCharacter.generated.h"
UCLASS(config=Game)
class AEndlessRunnerCharacter : public ACharacter
{
GENERATED_BODY()
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;
/** Follow camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;
public:
AEndlessRunnerCharacter();
virtual void BeginPlay() override;
virtual void Tick(float DeltaSeconds) override;
virtual void OnConstruction(const FTransform& Transform) override;
/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseTurnRate;
/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseLookUpRate;
/** Death it is */
UFUNCTION(BlueprintCallable, Category = "AAA")
void Death(FHitResult Hit);
/** Returns current coins number */
UFUNCTION(BlueprintCallable, Category = "AAA")
int32 GetCoins() const { return Coins; }
/** Returns passed distance */
UFUNCTION(BlueprintCallable, Category = "AAA")
float GetDistance() const { return Distance; }
/** Add one Coin */
UFUNCTION(BlueprintCallable, Category = "AAA")
void AddCoin() { Coins++; }
/** Enable/disable turn ability */
UFUNCTION(BlueprintCallable, Category = "AAA")
void SetCanTurn(bool NewCanTurn) { bCanTurn = NewCanTurn; }
/** Returns can character attract coins */
UFUNCTION(BlueprintCallable, Category = "AAA")
bool IsMagneto() const { return bIsMagneto; }
/** Returns can character break blockers */
UFUNCTION(BlueprintCallable, Category = "AAA")
bool IsBobmer() const { return bIsBomber; }
/** Activate Magneto state */
UFUNCTION(BlueprintCallable, Category = "AAA")
void ActivateMagneto();
/** Deactivate Magneto state */
UFUNCTION(BlueprintCallable, Category = "AAA")
void DeactivateMagneto();
/** Activate Bomber state */
UFUNCTION(BlueprintCallable, Category = "AAA")
void ActivateBomber();
/** Deactivate Bomber state */
UFUNCTION(BlueprintCallable, Category = "AAA")
void DeactivateBomber();
/** Death FX, blood, decal, sound */
UFUNCTION(BlueprintCallable, Category = "AAA")
void SpawnImpactFX(FHitResult Hit);
protected:
/** Called in Tick() */
void MoveForward();
void MoveRight(float Value);
/** if we should to turn now, perform it in Tick */
void TurnCorner(float DeltaSeconds);
void RestartLevel();
/** Character's rotation speed at the corner */
UPROPERTY(meta = (ClampMin = 3, ClampMax = 10), EditAnywhere, BlueprintReadWrite, Category = "AAA")
float InterpSpeed = 10.f;
/** Shows whether Character can turn now or not */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AAA", meta = (AllowPrivateAccess = "true"))
uint32 bCanTurn : 1;
/** Shows whether Character can turn now or not */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AAA", meta = (AllowPrivateAccess = "true"))
uint32 bIsDead : 1;
/** Shows whether Character IsMagneto now or not =) Hi, Eric! */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AAA", meta = (AllowPrivateAccess = "true"))
uint32 bIsMagneto : 1;
/** Shows whether Character IsMagneto now or not =) Hi, Eric! */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AAA", meta = (AllowPrivateAccess = "true"))
uint32 bIsBomber : 1;
/** Character's current desired rotation */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
FRotator DesiredRotation;
/** Character Death Blood FX */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
UParticleSystem* EmmiterTemplate;
/** Character Death Sound */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
USoundBase* DeathSound;
/** Restart Level timer */
FTimerHandle RestartTimer;
/** Total COins */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
int32 Coins = 0;
/**Timer to activate Magneto ability*/
FTimerHandle MagnetoTimer;
/** Magneto time in seconds */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
float MagnetoTime = 5.f;
/**Timer to activate Magneto ability*/
FTimerHandle BomberTimer;
/** Magneto time in seconds */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
float BomberTime = 5.f;
/** Blood Material */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
UMaterialInterface* DecalMaterial;
/** Blood Decal Size */
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
FVector DecalSize = FVector(20.f, 20.f, 20.f);
/** Magneto Particles */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
UParticleSystemComponent* MagnetoParticles;
/** Bomber Particles */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
UParticleSystemComponent* BomberParticles;
/** Bomber Particles */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "AAA", meta = (AllowPrivateAccess = "true"))
float Distance = 0.f;
/** Calculate Distance */
void CalcDistance(float DeltaSeconds);
/** Dynamic Material reference */
UPROPERTY(Meta = (BlueprintProtected = "true"), VisibleAnywhere, BlueprintReadWrite, Category = "AAA")
UMaterialInstanceDynamic* EndlessRunnerMaterial;
/** Color in Magneto state */
UPROPERTY(Meta = (BlueprintProtected = "true"), EditAnywhere, BlueprintReadWrite, Category = "AAA")
FLinearColor MagnetoColor = FLinearColor(0.f, 0.091f, 1.f, 1.f);
/** Color in Bomber state */
UPROPERTY(Meta = (BlueprintProtected = "true"), EditAnywhere, BlueprintReadWrite, Category = "AAA")
FLinearColor BomberColor = FLinearColor(1.f, 0.31f, 0.f, 1.f);
/** Initial character color */
FLinearColor InitialColor;
protected:
// APawn interface
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// End of APawn interface
public:
/** Returns CameraBoom subobject **/
FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; }
/** Returns FollowCamera subobject **/
FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; }
};
| true |
97efc8e37210419ccf8a3b1da04a1effe313aa65 | C++ | Nuos/autocom | /include/autocom/util/exception.h | UTF-8 | 1,359 | 2.703125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // :copyright: (c) 2015-2016 The Regents of the University of California.
// :license: MIT, see LICENSE.md for more details.
/*
* \addtogroup AutoCOM
* \brief COM exception definitions.
*/
#pragma once
#include <stdexcept>
#include <string>
#include <typeinfo>
namespace autocom
{
// EXCEPTION
// ---------
/** \brief Wraps a general COM method error.
*/
class ComFunctionError: public std::exception
{
protected:
std::string message;
virtual const char *what() const throw()
{
return message.data();
}
public:
ComFunctionError(const std::string &function);
};
/** \brief Wraps a general COM method error.
*/
class ComMethodError: public std::exception
{
protected:
std::string message;
virtual const char *what() const throw()
{
return message.data();
}
public:
ComMethodError(const std::string &object,
const std::string &method);
};
/** \brief Wraps a general COM type error.
*/
class ComTypeError: public std::exception
{
protected:
std::string message;
virtual const char *what() const throw()
{
return message.data();
}
public:
ComTypeError(const std::string &expected,
const std::string &actual,
const std::string &op);
};
} /* autocom */
| true |
00b926f18000e434890b2fde5a7c22d2d0eac420 | C++ | nanifour/hackerrank-practice | /challenges/30-days-of-code/cpp/day6-review.cpp | UTF-8 | 835 | 3.40625 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
//get n for array length
int n;
cin >> n;
//loop for indexes
for (int i = 0; i < n; i++){
string s;
//even odd character
string s1, s2;
//get string
cin >> s;
//loop through the 2 strings
for(int k = 0; k < s.size(); k++){
//even letters in array
if(k%2==0){
//if even add to even
s1 += s[k];
}
else{
//if odd
s2 += s[k];
}
}
cout << s1 << " " << s2 << endl ;
}
return 0;
}
| true |
242984843407d40d9f725fb8f85e750368cd9c83 | C++ | fjanisze/Gioco | /economic/finance.cpp | UTF-8 | 658 | 2.875 | 3 | [] | no_license | #include "finance.hpp"
namespace finance
{
game_wallet::game_wallet() : money_cash( 0 )
{ }
game_wallet& game_wallet::operator=( const game_wallet& wl )
{
money_cash = wl.money_cash;
return *this;
}
game_wallet& game_wallet::operator=( const currency_type& value )
{
money_cash = value;
return *this;
}
game_wallet::game_wallet( const currency_type& value )
{
money_cash = value;
}
game_wallet::game_wallet( const game_wallet& wallet )
{
money_cash = wallet.money_cash;
}
currency_type game_wallet::available_free_cash()
{
return money_cash;
}
currency_type& game_wallet::get_money_cash()
{
return money_cash;
}
}
| true |
4d522bac282cee0781b849b2ab01b019e1174828 | C++ | lkimprove/Study_C | /Knowledge/HashTable/开散列.cc | UTF-8 | 4,112 | 3.875 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
//哈希节点
template <class K, class V>
struct HashNode{
pair<K, V> _data; //节点值
HashNode<K, V>* _next; //下一个位置
//初始化
HashNode(const pair<K, V>& data = pair<K, V>()) :
_data(data), _next(nullptr)
{}
};
//哈希表
template <class K, class V>
class HashTable{
public:
typedef HashNode<K, V> Node;
typedef Node* pNode;
//拷贝函数
HashTable(const size_t n = 10){
_ht.resize(n);
_size = 0;
}
//插入
bool Insert(const pair<K, V>& data){
//检查容量
CheckCapacity();
//计算索引
int index = data.first % _ht.size();
//遍历单链表
pNode cur = _ht[index];
while (cur){
//不插入相同的元素
if (cur->_data.first == data.first){
return false;
}
//向下遍历
cur = cur->_next;
}
//插入(头插)
//创建cur
cur = new Node(data);
cur->_next = _ht[index];
_ht[index] = cur;
_size++;
return true;
}
//检查容量
void CheckCapacity(){
//如果单链表上的元素过多,会影响插入,删除等操作的效率
if (_size == _ht.size()){
//新表的大小
size_t new_size = (_ht.size() == 0 ? 10 : _ht.size() * 2);
//创建新表
vector<pNode> new_ht(new_size);
//遍历旧表
for (size_t i = 0; i < _ht.size(); i++){
pNode cur = _ht[i];
//遍历头节点
while (cur){
//计算索引
int index = cur->_data.first % new_size;
pNode next = cur->_next;
//头插进旧表
cur->_next = new_ht[index];
new_ht[index] = cur;
//继续遍历
cur = next;
}
//旧表置空
_ht[i] = nullptr;
}
//交换
swap(_ht, new_ht);
}
}
//查找
pNode Find(const K& key){
//计算索引
int index = key % _ht.size();
//遍历单链表
pNode cur = _ht[index];
while (cur){
//当前元素等于key
if (cur->_data.first == key){
return cur;
}
//向下遍历
cur = cur->_next;
}
//没找到
return false;
}
//删除
bool Erase(const K& key){
//计算索引
int index = key % _ht.size();
//遍历单链表
pNode cur = _ht[index];
pNode prev = nullptr;
while (cur){
if (cur->_data.first == key){
//判断cur是否为头节点
if (prev == nullptr){
_ht[index] = cur->_next;
}
else{
prev->_next = cur->_next;
}
//删除该元素
delete cur;
cur = nullptr;
_size--;
return true;
}
//向下遍历
prev = cur;
cur = cur->_next;
}
//没找到该元素
return false;
}
//打印
void Print(){
for (size_t i = 0; i < _ht.size(); i++){
pNode cur = _ht[i];
while (cur){
//打印
cout << cur->_data.first << "-" << cur->_data.second << endl;
//向下遍历
cur = cur->_next;
}
}
cout << endl;
}
private:
//指针数组
vector<pNode> _ht;
//已存储的元素个数
size_t _size;
};
//测试
void Test()
{
HashTable<int, int> _ht;
_ht.Insert(make_pair(1, 1));
_ht.Insert(make_pair(3, 3));
_ht.Insert(make_pair(6, 6));
_ht.Insert(make_pair(0, 0));
_ht.Insert(make_pair(10, 10));
_ht.Insert(make_pair(13, 13));
_ht.Insert(make_pair(16, 16));
_ht.Insert(make_pair(11, 11));
_ht.Insert(make_pair(14, 14));
_ht.Insert(make_pair(15, 15));
_ht.Insert(make_pair(110, 110));
_ht.Print();
int cur = 11;
bool erase = _ht.Erase(cur);
if (!erase){
cout << cur << "删除失败" << endl;
}
else{
cout << cur << "删除成功" << endl;
}
cur = 6;
erase = _ht.Erase(cur);
if (!erase){
cout << cur << "删除失败" << endl;
}
else{
cout << cur << "删除成功" << endl;
}
cur = 2;
erase = _ht.Erase(cur);
if (!erase){
cout << cur << "删除失败" << endl;
}
else{
cout << cur << "删除成功" << endl;
}
cout << endl;
_ht.Print();
cur = 110;
if (_ht.Find(cur) == nullptr){
cout << cur << "没找到" << endl;
}
else{
cout << cur << "找到了" << endl;
}
cur = 78;
if (_ht.Find(cur) == nullptr){
cout << cur << "没找到" << endl;
}
else{
cout << cur << "找到了" << endl;
}
}
//测试
int main()
{
Test();
return 0;
}
| true |
fec5f6de84161d8ceb591035f3eee54eff5b5b02 | C++ | MarioStoev99/Data-Structures-and-Algorithms-2019-2020 | /Binary Tree/maxLeafValue.cpp | UTF-8 | 1,058 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
struct node
{
int data;
node* left;
node* right;
node(int _data, node* _left = nullptr, node* _right = nullptr)
: data(_data), left(_left), right(_right) {}
};
node* createTree()
{
node* l6 = new node(1);
node* l5 = new node(6);
node* l4 = new node(7);
node* l3 = new node(4);
node* l2 = new node(8, l5, l6);
node* l1 = new node(3, l3, l4);
node* root = new node(5, l1, l2);
return root;
}
int findMaxLeafValue(node* root)
{
int maxLeafValue = -999;
if (root == nullptr)
return 0;
if (root->left == nullptr && root->right == nullptr)
{
if (maxLeafValue < root->data)
return root->data;
else return maxLeafValue;
}
maxLeafValue = maxLeafValue > findMaxLeafValue(root->left) ? maxLeafValue : findMaxLeafValue(root->left);
maxLeafValue = maxLeafValue > findMaxLeafValue(root->right) ? maxLeafValue : findMaxLeafValue(root->right);
return maxLeafValue;
}
int main()
{
node* root = createTree();
cout << "max leaf value : " << findMaxLeafValue(root) << endl;
return 0;
} | true |
490b2ebff28462cbbed7e194f3909393b43a9c68 | C++ | KGBOperative/OOPLibrary_Nick | /Main.cpp | UTF-8 | 38,588 | 2.90625 | 3 | [] | no_license | // File: Main.cpp
// Authors: Alex Bretow, Nick Mahnke, Jonah Cohen
// Contents: This file contains the description of a class called Member
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include "stdio.h"
#include "ctype.h"
#include <ctime>
#include <locale>
#include "Member.h"
#include "Library.h"
#include "Book.h"
#include "Periodical.h"
#include "Date.h"
#include "Asset.h"
#include <algorithm>
#include <iomanip>
using namespace std;
vector <Library *> vM;
vector <Library *> vB;
vector <Library *> vP;
vector <Library *> vL;
vector <Library *> AssetsOverdue;
vector <Library *> MembersOverdue;
int Menu();
void RestoreLibrary();
void SaveLibrary();
void AddCard();
void RemoveCard();
void AddAsset();
void RemoveAsset();
void CheckoutAsset();
void ReturnAsset();
void GenerateReport();
void Quit();
Date GetCurrentDate();
int ReportSubmenu();
void ReportMembersOverdue();
void ReportOverdueAssets();
void ReportAreaCode();
void DaysOverdueSort (vector <Library*> L);
bool CompareOverdueAssets (Library* A, Library* B);
bool isfound (vector <Library *> L, Library * Ptr);
void OverdueAssets ();
int main ()
{
int choice = Menu();
while (choice == -1)
choice = Menu();
switch (choice)
{
case 1: RestoreLibrary(); main(); break;
case 2: SaveLibrary(); main(); break;
case 3: AddCard(); main(); break;
case 4: RemoveCard(); main(); break;
case 5: AddAsset(); main(); break;
case 6: RemoveAsset(); main(); break;
case 7: CheckoutAsset(); main(); break;
case 8: ReturnAsset(); main(); break;
case 9: GenerateReport(); main(); break;
case 0: Quit(); break;
}
return 0;
}
int Menu ()
{
char selection;
cout << "---------------------------------------------------\n";
cout << "Select one of the following options: " << endl << endl;
cout << "\t1. Restore Library Information from a File\n";
cout << "\t2. Save Library Information to a File\n";
cout << "\t3. Add Library Card Holder\n";
cout << "\t4. Remove Library Card Holder\n";
cout << "\t5. Add New Library Asset\n";
cout << "\t6. Remove Library Asset\n";
cout << "\t7. Card Holder Checkout Asset\n";
cout << "\t8. Card Holder Return Asset\n";
cout << "\t9. Generate Reports\n";
cout << "\t0. Quit\n";
cin >> selection;
cin.ignore(256, '\n');
int sel = selection - '0';
if (sel >= 0 && sel <= 9)
return sel;
else if (selection == 'q')
return 0;
else
cout << "Invalid input\n";
return -1;
}
void RestoreLibrary ( )
{
string fname;
cout << "Enter the name of the File you want to restore: ";
cin >> fname;
ifstream fin;
fin.open(fname.c_str(), ifstream::in);
if (fin.fail())
{
cerr << "File: " << fname << " not found " << endl;
return;
string choice = "";
}
string line;
while (fin >> line)
{
if (line == "Type:")
{
getline(fin, line);
line.erase(line.begin());
}
if (line == "MEMBER")
{
Library *M = new Member();
M->ReadIn(fin);
if (!isfound(vL, M))
vL.push_back(M);
}
else if (line == "BOOK")
{
Library * B = new Book();
B->ReadIn(fin);
if (!isfound(vL, B))
vL.push_back(B);
}
else if (line == "PERIODICAL")
{
Library *P = new Periodical();
P->ReadIn(fin);
if (!isfound(vL, P))
vL.push_back(P);
}
}
for (int i = 0; i < vL.size(); i++) {
if (vL[i]->IsA() == Library::MEMBER) {
for (int j = 0; j < vL.size(); j++) {
if (vL[j]->IsA() != Library::MEMBER) {
debug << "checkout link for member " << vL[i]->GetID() << " and asset " << vL[j]->GetID() << endl;
vL[i]->CheckoutLink(vL[j]);
vL[j]->CheckoutLink(vL[i]);
}
}
}
}
/*
// will have to do for entire vector <Library *> vL
for (int i = 0; i < vM.size(); i++)
{
vM[i]->CheckoutLink(vB, vP);
}
for (int i = 0; i < vB.size(); i++)
{
vB[i]->CheckoutLink(vM, vB);
}
for (int i = 0; i < vP.size(); i++)
{
vP[i]->CheckoutLink(vM, vP);
}
*/
}
void SaveLibrary() {
string fname;
cout << "Enter the name of the File you want to save to: ";
cin >> fname;
string filename = fname;
ofstream fout (filename.c_str());
for (int i = 0; i < vL.size(); i++)
vL[i]->WriteOut(fout);
}
void AddCard() {
string fname, choice, temp, endLineClear;
stringstream Ins;
cout << "Would you like to add from a file (1) or manually (2)? ";
cin >> choice;
if (choice == "1") {
cout << "Enter the name of the File you want to add: ";
cin >> fname;
ifstream fin;
fin.open(fname.c_str(), ifstream::in);
if (fin.fail())
{
cerr << "File: " << fname << " not found " << endl;
string choice = "";
}
string line;
while (fin >> line)
{
if (line == "Type:")
{
getline(fin, line);
line.erase(line.begin());
}
if (line != "MEMBER")
{
cerr << "File: " << fname << " is not a Card Holder " << endl;
break;
}
else
{
Library *M = new Member();
M->ReadIn(fin);
if (!isfound(vL, M))
vL.push_back(M);
}
}
}
else if (choice == "2") {
getline (cin, endLineClear);
cout << "Name: ";
getline(cin, temp);
Ins << "Name: " + temp + "\n";
temp.clear();
cout << "ID: ";
getline(cin, temp);
Ins << "ID: " + temp + "\n";
temp.clear();
cout << "Address: ";
getline(cin, temp);
Ins << "Address: " + temp + "\n";
temp.clear();
cout << "City: ";
getline(cin, temp);
Ins << "City: " + temp + "\n";
temp.clear();
cout << "State: ";
getline(cin, temp);
Ins << "State: " + temp + "\n";
temp.clear();
cout << "Zip: ";
getline(cin, temp);
Ins << "Zip: " + temp + "\n";
temp.clear();
cout << "Phone Number: ";
getline(cin, temp);
Ins << "Phone_Number: " + temp + "\n";
temp.clear();
cout << "Checked Out (Asset ID): ";
getline(cin, temp);
Ins << "Checked_Out: " + temp + "\n";
temp.clear();
Library *M = new Member();
M->ReadIn(Ins);
if (!isfound(vL, M))
vL.push_back(M);
}
else {
cout << "That was not an option. Please try again. \n";
AddCard();
}
/*for (int i = 0; i < vM.size(); i++)
{
vM[i]->CheckoutLink(vB, vP);
}
for (int i = 0; i < vB.size(); i++)
{
vB[i]->CheckoutLink(vM, vB);
}
for (int i = 0; i < vP.size(); i++)
{
vP[i]->CheckoutLink(vM, vP);
}*/ // will have to do link after adding card
}
void RemoveCard() {
string forget;
string remove;
string check = "";
Date ret = Date();
cout << "Enter the ID of the Card you want to remove: ";
getline (cin, check); //remove;
if (check.at(0) == 'M') {
for (int i = 0; i < vL.size(); i++) {
if (vL[i]->GetID() == check) {
vector<Library*> checkedout = vL[i]->GetCheckedOutVec();
debug << "Member " << vL[i]->GetID() << " has " << checkedout.size() << " assets checked out\n";
for (int j = 0; j < checkedout.size(); j++) {
vector <Library::Issue> issues = checkedout[j]->GetIssues();
debug << "does " << checkedout[j]->GetID() << " have issues?\n";
if (issues.size() > 0) {
for (int k = 0; k < issues.size(); k++) {
debug << "is " << issues[k].CheckedOutByStr << " == " << check << "?\n";
if (issues[k].CheckedOutByStr == check) {
debug << "Member " << check << " is returning " << checkedout[j]->GetID() << ":" << k << " before being removed\n";
checkedout[j]->Return(k);
}
}
}
else {
debug << "Member " << check << " is returning " << checkedout[j]->GetID() << " before being removed\n";
checkedout[j]->Return(0);
}
}
vL.erase (vL.begin()+i);
break;
}
}
}
else
cout << "That Member ID does not exist. \n";
/*if (putchar (tolower(vM[i].Name.c_str())) == putchar (tolower(remove.c_str())))
vM.erase (vM.begin()+i);*/
}
void AddAsset() {
string fname, choice, temp, endLineClear;
stringstream Ins;
cout << "Would you like to add from a file (1) or manually (2)? ";
cin >> choice;
if (choice == "1") {
cout << "Enter the name of the File you want to add: ";
cin >> fname;
ifstream fin;
fin.open(fname.c_str(), ifstream::in);
if (fin.fail())
{
cerr << "File: " << fname << " not found " << endl;
string choice = "";
}
string line;
while (fin >> line)
{
if (line == "Type:")
{
getline(fin, line);
line.erase(line.begin());
}
if (line != "BOOK" && line != "PERIODICAL")
{
cerr << "File: " << fname << " is not an Asset" << endl;
break;
}
else if (line == "BOOK")
{
Book *B = new Book();
B->ReadIn(fin);
Library *l = B;
if (!isfound(vB, l))
vB.push_back(B);
vL.push_back(B);
}
else if (line == "PERIODICAL")
{
Periodical *P = new Periodical();
P->ReadIn(fin);
Library *l = P;
if (!isfound(vP, l))
vP.push_back(P);
vL.push_back(P);
}
}
}
else if (choice == "2") {
cout << "\nBook (1) or Periodical (2): ";
temp.clear();
cin >> temp;
if (temp == "1") {
getline (cin, endLineClear);
cout << "Name: ";
getline(cin, temp);
Ins << "Name: " + temp + "\n";
temp.clear();
cout << "ID: ";
getline(cin, temp);
Ins << "ID: " + temp + "\n";
temp.clear();
cout << "Asset Type: ";
getline(cin, temp);
Ins << "Asset_Type: " + temp + "\n";
temp.clear();
cout << "Author: ";
getline(cin, temp);
Ins << "Author: " + temp + "\n";
temp.clear();
cout << "ISBN: ";
getline(cin, temp);
Ins << "ISBN: " + temp + "\n";
temp.clear();
cout << "Type: ";
getline(cin, temp);
Ins << "Type: " + temp + "\n";
temp.clear();
cout << "Checked Out On (mm/dd/yyy): ";
getline(cin, temp);
Ins << "Checked_Out_On: " + temp + "\n";
temp.clear();
cout << "Checked Out By (Member ID): ";
getline(cin, temp);
Ins << "Checked_Out_By: " + temp + "\n";
temp.clear();
Library *B = new Book();
B->ReadIn(Ins);
if (!isfound(vL, B))
vL.push_back(B);
}
else if (temp == "2")
{
int issues;
getline (cin, endLineClear);
cout << "Name: ";
getline(cin, temp);
Ins << "Name: " + temp + "\n";
temp.clear();
cout << "ID: ";
getline(cin, temp);
Ins << "ID: " + temp + "\n";
temp.clear();
cout << "Asset Type: ";
getline(cin, temp);
Ins << "Asset_Type: " + temp + "\n";
temp.clear();
cout << "ISSN: ";
getline(cin, temp);
Ins << "ISSN: " + temp + "\n";
temp.clear();
cout << "Issues: ";
getline(cin, temp);
Ins << "Issues: " + temp + "\n";
issues = atoi(temp.c_str());
temp.clear();
for (int i = 0; i < issues; i++)
{
cout << "Volume: ";
getline(cin, temp);
Ins << "Volume: " + temp + "\t\t";
temp.clear();
cout << "Number: ";
getline(cin, temp);
Ins << "Number: " + temp + "\n";
temp.clear();
cout << "Publication Date (mm/dd/yyy): ";
getline(cin, temp);
Ins << "Publication_Date: " + temp + "\n";
temp.clear();
cout << "Checked Out On (mm/dd/yyy): ";
getline(cin, temp);
Ins << "Checked_Out_On: " + temp + "\n";
temp.clear();
cout << "Checked Out By (Member ID): ";
getline(cin, temp);
Ins << "Checked_Out_By: " + temp + "\n";
temp.clear();
}
Library *P = new Periodical();
P->ReadIn(Ins);
if (!isfound(vL, P))
vL.push_back(P);
}
}
else {
cout << "That was not an option. Please try again. \n";
AddAsset();
}
/*for (int i = 0; i < vM.size(); i++)
{
vM[i]->CheckoutLink(vB, vP);
}
for (int i = 0; i < vB.size(); i++)
{
vB[i]->CheckoutLink(vM, vB);
}
for (int i = 0; i < vP.size(); i++)
{
vP[i]->CheckoutLink(vM, vP);
}*/ // will have to do link after adding assets
}
void RemoveAsset() {
// create bool RemoveCard functions for Book and Periodical <-- Ultimately do on vector <Library> vL
string check = "";
string choice = "";
int memcount = 0;
Date ret = Date();
cout << "Enter the ID of the Asset you want to remove: ";
getline (cin, check); //remove;
if (check.at(0) == 'B' || check.at(0) == 'P')
{
for (int i = 0; i < vL.size(); i++) {
if (vL[i]->GetID() == check) {
vector<Library::Issue> issues = vL[i]->GetIssues();
if (issues.size() > 0) {
for (int j = 0; j < issues.size(); j++) {
for (int k = 0; k < vL.size(); k++) {
if (issues[j].CheckedOutByStr == vL[k]->GetID()) {
vector<Library*> checkedout = vL[k]->GetCheckedOutVec();
for (int l = checkedout.size()-1; l >= 0; l--) {
if (checkedout[l]->GetID() == check) {
vL[k]->Return(l);
}
}
}
}
}
}
else {
for (int j = 0; j < vL.size(); j++) {
vector<Library*> checkedout = vL[j]->GetCheckedOutVec();
for (int k = 0; k < checkedout.size(); k++) {
if (checkedout[k]->GetID() == check) {
checkedout.erase(checkedout.begin()+k);
break;
}
}
}
}
vL.erase (vL.begin()+i);
}
}
}
else
cout << "That Asset ID does not exist. \n";
}
Date GetCurrentDate () {
time_t theTime;
time (&theTime);
struct tm *aTime = localtime(&theTime);
char buffer [80];
strftime (buffer, 80, "%m/%d/%Y", aTime);
stringstream temp;
temp.str(buffer);
Date today;
today.ReadIn(temp);
return today;
}
bool isfound (vector <Library *> L, Library * Ptr)
{
debug << "inside isfound\n";
for (int i = 0; i < L.size(); i++) {
debug << "comparing " << L[i]->GetID() << " to " << Ptr->GetID() << endl;
if (L[i]->GetID() == Ptr->GetID()) {
debug << Ptr->GetID() << " was found at i = " << i << endl;
return true;
}
}
debug << Ptr->GetID() << " was not found\n";
return false;
}
void OverdueAssets () {
debug << "Entering OverdueAssets\n";
Date today = GetCurrentDate();
for (int i = 0; i < vL.size(); i++)
{
if (vL[i] == NULL) {
debug << "vL[" << i << "] is NULL\n";
break;
}
if (vL[i]->IsA() != Library::MEMBER) {
vector <Library::Issue> issues = vL[i]->GetIssues();
if (issues.size() > 0) {
for (int j = 0; j < issues.size(); j++)
{
if (issues[j].DaysOverdue(today) > 0)
{
Library *p = vL[i];
Library *m = issues[j].CheckedOutBy;
if (m == NULL) {
debug << "issues[" << j << "].CheckedOutBy is NULL, p->GetID() == " << p->GetID() << endl;
debug << "days overdue == " << issues[j].DaysOverdue(today) << endl;
break;
}
else {
debug << "checking if " << p->GetID() << " is in AssetsOverdue\n";
if (!isfound(AssetsOverdue, p)) {
debug << "adding " << p->GetID() << " to AssetsOverdue\n";
AssetsOverdue.push_back(p);
}
debug << "checking if " << m->GetID() << " is in MembersOverdue\n";
if (!isfound(MembersOverdue, m)) {
debug << "adding " << m->GetID() << " to MembersOverdue\n";
MembersOverdue.push_back(m);
}
}
}
}
}
else if (vL[i]->DaysOverdue(today) > 0)
{
Library *p = vL[i];
Library *m = vL[i]->GetCheckedOutBy()[0];
if (m == NULL) {
debug << "vL[" << i << "]->GetCheckedOutBy()[0] is NULL, p->GetID() == " << p->GetID() << endl;
continue;
}
else {
debug << "checking if " << p->GetID() << " is in AssetsOverdue\n";
if (!isfound(AssetsOverdue, p)) {
debug << "adding " << p->GetID() << " to AssetsOverdue\n";
AssetsOverdue.push_back(p);
}
debug << "checking if " << m->GetID() << " is in MembersOverdue\n";
if (!isfound(MembersOverdue, m)) {
debug << "adding " << m->GetID() << " to MembersOverdue\n";
MembersOverdue.push_back(m);
}
}
}
}
}
debug << "Leaving OverdueAssests\n";
}
// for (int i = 0; i < MembersOverdue.size(); i++)
//MembersOverdue[i]->WriteOut(cout);
void CheckoutAsset()
{
string memID;
cout << "Enter the ID of Member who is checking out an Asset: ";
cin >> memID;
Library *searchMem = new Member();
searchMem->SetID(memID);
if (!isfound(vL, searchMem)) {
cout << "That Member ID does not exist. " << endl;
return;
}
int memIndex;
for (int i = 0; i < vL.size(); i++) {
if (memID == vL[i]->GetID()) {
memIndex = i;
break;
}
}
string assetID;
cout << "Enter the ID of the Asset: ";
cin >> assetID;
Date today = GetCurrentDate();
for (int i = 0; i < vL.size(); i++) {
if (vL[i]->GetID() == assetID) {
if (vL[i]->IsA() == Library::PERIODICAL) {
vector<Library::Issue> issues = vL[i]->GetIssues();
int issue = 0;
cout << "Please enter the Issue Number to checkout: ";
cin >> issue;
cout << "response: " << issue << " of number of issues: " << issues.size() << endl;
if (issue > 0 && issue <= issues.size()) {
cout << "check 0\n";
cout << "coBy.size == " << vL[i]->GetCheckedOutBy().size() << endl;
if (vL[i]->GetCheckedOutBy()[issue-1] == NULL) {
cout << "check 1\n";
vL[memIndex]->Checkout(vL[i], assetID, 0);
cout << "check 2\n";
vL[i]->Checkout(vL[memIndex], memID, issue-1);
cout << "check 3\n";
issues[issue-1].CheckedOut = today;
}
else {
cout << "That Issue is already checked out\n";
}
}
else {
cout << "That Issue was not found\n";
}
}
else if (vL[i]->IsA() == Library::BOOK) {
if (vL[i]->GetCheckedOutBy()[0] == NULL) {
vL[memIndex]->Checkout(vL[i], assetID, 0);
vL[i]->Checkout(vL[memIndex], memID, 0);
vL[i]->SetCheckedOut(today);
}
else {
cout << "That Asset has already been checked out\n";
}
}
return;
}
}
cout << "That Asset ID does not exist. " << endl;
// Create functions in classes and set CheckedOutStr to asset, vM[memcount]->CheckedOut push back pointer to vB[assetcount]
// or vP[assetcount], vB or vP[assetcount]->CheckedOutByStr to member, vBor vP[assetcount]->CheckedOutBy push back
// pointer to vM[memcount], setFunction vB or vP->CheckedOutOn to today
}
// reimplement each Classes checkout function to checkout one item, get pointer linking to work in Main.cpp
void ReturnAsset()
{
string memID, assetID;
Date ret = Date();
int memIndex;
cout << "Enter the ID of Member who is returning an Asset: ";
cin >> memID;
for (int i = 0; i < vL.size(); i++) {
if (memID == vL[i]->GetID()) {
cout << "Enter the ID of the Asset to return: ";
cin >> assetID;
vector<Library*> checkedout = vL[i]->GetCheckedOutVec();
for (int j = 0; j < checkedout.size(); j++) {
if (assetID == checkedout[j]->GetID()) {
vector<Library::Issue> issues = checkedout[j]->GetIssues();
if (issues.size() > 0) {
int vol;
cout << "Enter the issue number to return: ";
cin >> vol;
if (vol <= issues.size() && issues[vol-1].CheckedOutByStr == memID) {
checkedout[j]->Return(vol-1);
vL[i]->Return(j);
return;
}
else {
cout << "Member " << memID << " does not have that Asset checked out\n";
return;
}
}
else {
if (checkedout[j]->GetCheckedOutByStr()[0] == memID) {
checkedout[j]->Return(0);
vL[i]->Return(j);
return;
}
}
cout << "Member " << memID << " does not have that Asset checked out\n";
return;
}
}
cout << "Member " << memID << " does not have that Asset checked out\n";
return;
}
}
cout << "Member " << memID << " was not found\n";
}
int ReportSubmenu()
{
char selection;
cout << "---------------------------------------------------\n";
cout << "Select one of the following reports: " << endl << endl;
cout << "\t1. Members with Overdue Assets\n";
cout << "\t2. All Overdue Assets\n";
cout << "\t3. Members in a Specific Area Code\n";
cout << "\t0. Main Menu\n";
cin >> selection;
cin.ignore(256, '\n');
int sel = selection - '0';
if (sel >= 0 && sel <= 3)
return sel;
else if (selection == 'q')
return 0;
else {
cout << "Invalid input\n";
return -1;
}
}
void GenerateReport()
{
OverdueAssets();
sort (AssetsOverdue.begin(), AssetsOverdue.end(), CompareOverdueAssets);
int choice;
do {
choice = ReportSubmenu();
} while (choice < 0);
switch (choice)
{
case 1: ReportMembersOverdue(); GenerateReport(); break;
case 2: ReportOverdueAssets(); GenerateReport(); break;
case 3: ReportAreaCode(); GenerateReport(); break;
case 0: main(); break;
}
}
void ReportMembersOverdue()
{
char choice;
Date today = GetCurrentDate();
int count;
cout << "Do you want your report in a file(1) or on the screen(2)? : ";
cin >> choice;
if (choice == '1')
{
string fname;
cout << "Enter the name of the File you want to save to: ";
cin >> fname;
string filename = fname + ".report";
ofstream fout (filename.c_str());
fout << "Members with Overdue Assets \t\t Today's Date: ";
today.WriteOut(fout);
fout << endl << endl;
for (int i = 0; i < MembersOverdue.size(); i++)
{
if (MembersOverdue[i] != NULL)
{
count = 0;
MembersOverdue[i]->WriteOut(fout);
vector <Library *> checkedout;
checkedout = MembersOverdue[i]->GetCheckedOutVec();
for (int i = 0; i < checkedout.size(); i++)
if (isfound(AssetsOverdue, checkedout[i]))
count++;
fout << "\t" << "Assets Overdue Count: " << count << endl;
for (int j = 0; j < AssetsOverdue.size(); j++)
{
for (int k = 0; k < checkedout.size(); k++) {
if (AssetsOverdue[j]->GetID() == checkedout[k]->GetID())
{
if (AssetsOverdue[j]->IsA() == Library::BOOK)
{
fout << "\t" << AssetsOverdue[j]->GetID() << ": ";
fout << setw (18) << left << AssetsOverdue[j]->GetName() << "\t";
fout << "Days Overdue: " << AssetsOverdue[j]->DaysOverdue(today) << endl;
}
else
{
vector <Library::Issue> issues;
issues = AssetsOverdue[j]->GetIssues();
for (int z = 0; z < issues.size(); z++)
if (issues[z].DaysOverdue(today) > 0 && !issues[z].CheckedOut.IsNull())
{
fout << "\t" << AssetsOverdue[j]->GetID() << ": ";
fout << setw (18) << left << AssetsOverdue[j]->GetName() << "\t";
fout << "Days Overdue: " << issues[z].DaysOverdue(today) << endl;
}
}
}
}
}
fout << endl;
}
}
}
else if (choice == '2')
{
cout << "\nMembers with Overdue Assets \t\t Today's Date: ";
today.WriteOut(cout);
cout << endl << endl;
for (int i = 0; i < MembersOverdue.size(); i++)
{
if (MembersOverdue[i] != NULL)
{
count = 0;
MembersOverdue[i]->WriteOut(cout);
vector <Library *> checkedout;
checkedout = MembersOverdue[i]->GetCheckedOutVec();
for (int i = 0; i < checkedout.size(); i++)
if (isfound(AssetsOverdue, checkedout[i]))
count++;
cout << "\t" << "Assets Overdue Count: " << count << endl;
for (int j = 0; j < AssetsOverdue.size(); j++)
{
for (int k = 0; k < checkedout.size(); k++) {
if (AssetsOverdue[j]->GetID() == checkedout[k]->GetID())
{
if (AssetsOverdue[j]->IsA() == Library::BOOK)
{
cout << "\t" << AssetsOverdue[j]->GetID() << ": ";
cout << setw (18) << left << AssetsOverdue[j]->GetName() << "\t";
cout << "Days Overdue: " << AssetsOverdue[j]->DaysOverdue(today) << endl;
}
else
{
vector <Library::Issue> issues;
issues = AssetsOverdue[j]->GetIssues();
for (int z = 0; z < issues.size(); z++)
if (issues[z].DaysOverdue(today) > 0 && !issues[z].CheckedOut.IsNull())
{
cout << "\t" << AssetsOverdue[j]->GetID() << ": ";
cout << setw (18) << left << AssetsOverdue[j]->GetName() << "\t";
cout << "Days Overdue: " << issues[z].DaysOverdue(today) << endl;
}
}
}
}
}
cout << endl;
}
else
{
}
}
return;
}
}
void ReportOverdueAssets()
{
//OverdueAssets(vB, vP);
DaysOverdueSort(AssetsOverdue);
char choice;
string type;
Date today = GetCurrentDate();
cout << "Do you want your report in a file(1) or on the screen(2)? : ";
cin >> choice;
if (choice == '1')
{
string fname;
cout << "Enter the name of the File you want to save to: ";
cin >> fname;
string filename = fname + ".report";
ofstream fout (filename.c_str());
fout << "Overdue Assets \t\t Today's Date: ";
today.WriteOut(fout);
fout << endl << endl ;
for (int i = 0; i < AssetsOverdue.size(); i++)
{
if (AssetsOverdue[i]->IsA() == Library::BOOK)
{
if (AssetsOverdue[i]->GetCheckedOutBy()[0] != NULL)
{
/*Library *b = new Book();
b = AssetsOverdue[i];
if (!b->CheckedOut.IsNULL())
{*/
type = "BOOK";
fout << "\nType: " << type << endl;
fout << "Asset Name: " << AssetsOverdue[i] -> GetName() << endl;
fout << "Days Overdue: " << AssetsOverdue[i] -> DaysOverdue(today) << endl;
fout << "ID: " << AssetsOverdue[i] -> GetID() << endl;
fout << "Name: " << AssetsOverdue[i] -> GetCheckedOutBy()[0] -> GetName() <<
endl << endl;
//}
}
}
else
{
type = "PERIODICAL";
vector <Library::Issue> issues;
for (int j = 0; j < AssetsOverdue[i]->GetIssues().size(); j++)
{
issues = AssetsOverdue[i]->GetIssues();
if (issues[j].DaysOverdue(today) > 0 && issues[j].CheckedOutBy != NULL)
{
if (!issues[j].CheckedOut.IsNull())
{
fout << "\nType: " << type << endl;
fout << "Asset Name: " << AssetsOverdue[i] -> GetName() << endl;
fout << "Days Overdue: " << issues[j].DaysOverdue(today) << endl;
fout << "ID: " << AssetsOverdue[i] -> GetID() << endl;
fout << "Name: " << issues[j].CheckedOutBy -> GetName() << endl << endl;
}
}
}
}
}
fout << "Total: " << AssetsOverdue.size() << endl;
fout << "Total Fees: $" << 13 * AssetsOverdue.size() << endl;
}
else if (choice == '2')
{
cout << "\nOverdue Assets \t\t Today's Date: ";
today.WriteOut(cout);
cout << endl << endl;
for (int i = 0; i < AssetsOverdue.size(); i++)
{
if (AssetsOverdue[i] != NULL)
{
if (AssetsOverdue[i]->IsA() == Library::BOOK)
{
type = "BOOK";
cout << "Type: " << type << endl;
cout << "Asset Name: " << AssetsOverdue[i] -> GetName() << endl;
cout << "Days Overdue: " << AssetsOverdue[i] -> DaysOverdue(today) << endl;
cout << "ID: " << AssetsOverdue[i] -> GetID() << endl;
cout << "Name: " << AssetsOverdue[i] -> GetCheckedOutBy()[0] -> GetName() <<
endl << endl;
}
else
{
type = "PERIODICAL";
vector <Library::Issue> issues;
for (int j = 0; j < AssetsOverdue[i]->GetIssues().size(); j++)
{
issues = AssetsOverdue[i]->GetIssues();
if (issues[j].DaysOverdue(today) > 0 && issues[j].CheckedOutBy != NULL)
{
cout << "Type: " << type << endl;
cout << "Asset Name: " << AssetsOverdue[i] -> GetName() << endl;
cout << "Days Overdue: " << issues[j].DaysOverdue(today) << endl;
cout << "ID: " << AssetsOverdue[i] -> GetID() << endl;
cout << "Name: " << issues[j].CheckedOutBy -> GetName() << endl << endl;
}
}
}
}
}
cout << "Total: " << AssetsOverdue.size() << endl;
cout << "Total Fees: $" << 13 * AssetsOverdue.size() << endl;
}
}
void ReportAreaCode()
{
char choice;
string type;
Date today = GetCurrentDate();
cout << "Do you want your report in a file(1) or on the screen(2)? : ";
cin >> choice;
if (choice == '1')
{
string fname;
cout << "Enter the name of the File you want to save to: ";
cin >> fname;
string filename = fname + ".report";
ofstream fout (filename.c_str());
string areacode;
cout << "What area code do you want to see? : ";
cin >> areacode;
fout << "Members in " << areacode << endl;
fout << "Generated on: ";
today.WriteOut(fout);
fout << endl;
fout << "---------------------------------------------------" << endl;
fout << setw(6) << left << "ID" << setw(22) << left << "Name" << setw(14) << left << "Phone Number" << endl << endl;
for (int i = 0; i < vL.size(); i++) {
if (vL[i]->IsA() == Library::MEMBER && areacode == vL[i]->GetPhone().substr(0,3)) {
fout << setw(4) << left << vL[i]->GetID() << " " << setw(20) << left << vL[i]->GetName() << " " << setw(12) << left << vL[i]->GetPhone() << endl;
}
}
}
if (choice == '2')
{
string areacode;
cout << "What area code do you want to see? : ";
cin >> areacode;
cout << "\nMembers in " << areacode << endl;
cout << "Generated on: ";
today.WriteOut(cout);
cout << endl;
cout << "---------------------------------------------------" << endl;
cout << setw(6) << left << "ID" << setw(22) << "Name" << setw(14) << "Phone Number" << endl << endl;
for (int i = 0; i < vL.size(); i++) {
if (vL[i]->IsA() == Library::MEMBER && areacode == vL[i]->GetPhone().substr(0,3)) {
cout << setw(4) << left << vL[i]->GetID() << " " << setw(20) << vL[i]->GetName() << " " << setw(12) << vL[i]->GetPhone() << endl;
}
}
}
}
bool CompareOverdueAssets ( Library* A, Library* B)
{
return (A->GetID() < B->GetID());
}
void Quit ()
{
string choice;
bool cont = true;
while (cont == true) {
cout << "Do you want to save changes made to Library (Y/N)? ";
cin >> choice;
if (choice == "y" || choice == "Y" || choice == "yes" || choice == "Yes" || choice == "YES")
{
SaveLibrary();
exit(0);
cont = false;
}
else if (choice == "n" || choice == "N" || choice == "no" || choice == "No" || choice == "NO")
{
exit(0);
cont = false;
}
else
cout << "Please enter Y or N ";
}
}
void DaysOverdueSort (vector <Library*> L)
{
Library* temp;
Date today = GetCurrentDate();
for (int i = 0; i < L.size()-1; i++)
if (L[i]->DaysOverdue(today) < L[i+1]->DaysOverdue(today))
{
temp = L[i];
L[i] = L[i+1];
L[i+1] = temp;
}
}
| true |
42c2f7ab873c501a66b1d549d462390f813e0a1a | C++ | jbarontennis/410_proj3_threads | /src/tester.cpp | UTF-8 | 1,415 | 2.640625 | 3 | [] | no_license | /*
* tester.cpp
*
* Created on: Mar 11, 2020
* Author: james
*/
#include <thread>
#include <iostream>
#include <vector>
#include <mutex>
#include <time.h>
#include <chrono>
#include "../header files/tester.h"
#include "../header files/print_ts.h"
using namespace std;
std::mutex mtx;
std::vector<std::thread> threads;
bool cancel;
void threadHandler(int numThreads, int numPrints, int mili, WHICH_PRINT w,
string m) {
for (int j = 0; j < numPrints; j++) {
if(cancel){
break;
}
else if (w == P1) {
PRINT1(m);
} else if (w == P2) {
PRINT2(m, m);
} else if (w == P3) {
PRINT3(m, m, m);
} else if (w == P4) {
PRINT4(m, m, m, m);
} else {
PRINT5(m, m, m, m, m);
}
this_thread::sleep_for(chrono::milliseconds(mili));
}
}
void startThreads(std::string s, int numThreads, WHICH_PRINT wp,
int numTimesToPrint, int millisecond_delay) {
setCancelThreads(false);
for (int i = 0; i < numThreads; i++) {
threads.push_back(
std::thread(threadHandler, numThreads, numTimesToPrint,
millisecond_delay, wp, s));
}
}
void setCancelThreads(bool bCancel) {
std::mutex tmp;
cancel = bCancel;
if (bCancel) {
for (auto &t : threads) {
lock_guard<mutex> lock(tmp);
this_thread::sleep_for(chrono::milliseconds(100));
printf("%s\n", USER_CHOSE_TO_CANCEL.c_str());
}
}
}
void joinThreads() {
for (auto &t : threads) {
t.join();
}
threads.clear();
}
| true |
4299e39c0df939c9f55c197db774e2c2f43abc8f | C++ | KBog/college-projects | /CS381/KBoghossian - CS381 - Ass04/FuzzyEngine_Camera/Test/sound.h | UTF-8 | 6,623 | 2.546875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #ifndef SoundH
#define SoundH
#include <windows.h>
#include "bass.h"
#include "Camera.h"
enum {smaller, bigger, same};
void InitializeBASS();
void CreateSounds();
void UpdateListener();
void UpdateChannel(int ChannelNumber, Vector3D* Position, Vector3D* Orientation, Vector3D* Velocity);
void PlayChannel(int ChannelNumber);
class SOUND_SAMPLE
{
public:
SOUND_SAMPLE(){};
~SOUND_SAMPLE(){};
int Compare(const SOUND_SAMPLE& Sample);
int GetMyPosition() const {return linkPosition;}
void SetMyPosition(int newPosition) {linkPosition = newPosition;}
int linkPosition;
HSAMPLE hSample; // the sample's handle
char name[32]; // filename
int max; // number of simultaneous playbacks
DWORD flags; // option flags
DWORD volume;
float mindist;
float maxdist;
};
class SOUND_CHANNEL
{
public:
SOUND_CHANNEL(){};
~SOUND_CHANNEL(){};
int Compare(const SOUND_CHANNEL& Channel);
int GetMyPosition() const {return linkPosition;}
void SetMyPosition(int newPosition) {linkPosition = newPosition;}
int linkPosition;
HCHANNEL hChannel; // the channel's handle
HSAMPLE hSample; // handle of the sample associated with this channel
BASS_3DVECTOR position; // position
BASS_3DVECTOR orientation; // orientation
BASS_3DVECTOR velocity; // velocity
int direction; // direction of the channel
bool looped; // flag for looped sample
bool intermittent; // flag for intermittent sound
bool random; // random intermittent sound
unsigned int lowerrand; // minimum repeat time
unsigned int upperrand; // maximum repeat time
unsigned int interval; // time between plays
unsigned int idEvent; // unique timer id (set this to the channel number)
};
// Forward declarations
template <class T> class Node;
template <class T> class HeadNode;
template <class T> class InternalNode;
template <class T> class TailNode;
template <class T>
class Node
{
public:
Node() {};
virtual ~Node() {};
virtual Node * Insert(T * pNewObject, Node<T> * pPrevious) = 0;
virtual void ModifyLinkPosition() = 0;
virtual void SetPrevious(Node<T> * pPrevious) = 0;
virtual void SetNext(Node<T> * pNext) = 0;
virtual void DeleteList() = 0;
virtual T * Get(int val) = 0;
virtual void Delete(int val) = 0;
private:
};
template <class T>
class InternalNode: public Node<T>
{
public:
InternalNode(T * pNewObject, Node<T> * pNext, Node<T> * pPrevious);
~InternalNode() {}
virtual Node<T> * Insert(T * pNewObject, Node<T> * pPrevious);
virtual void DeleteList() {pMyNext->DeleteList(); delete pThisObject; delete this;}
virtual void ModifyLinkPosition() {pMyNext->ModifyLinkPosition(); pThisObject->linkPosition--;}
virtual void SetPrevious(Node<T> * pPrevious) {pMyPrevious = pPrevious;}
virtual void SetNext(Node<T> * pNext) {pMyNext = pNext;}
virtual T * Get(int val)
{
if (pThisObject->GetMyPosition() == val)
return pThisObject;
else
return pMyNext->Get(val);
}
virtual void Delete(int val)
{
if (pThisObject->GetMyPosition() == val)
{
this->ModifyLinkPosition();
pMyNext->SetPrevious(pMyPrevious);
pMyPrevious->SetNext(pMyNext);
delete this;
}
else
pMyNext->Delete(val);
}
private:
T * pThisObject;
Node<T> * pMyNext;
Node<T> * pMyPrevious;
};
template <class T>
InternalNode<T>::InternalNode(T * pNewObject, Node<T> * pNext, Node<T> * pPrevious):
pThisObject(pNewObject),pMyNext(pNext),pMyPrevious(pPrevious)
{
}
template <class T>
Node<T> * InternalNode<T>::Insert(T * pNewObject, Node<T> * pPrevious)
{
int answer = pThisObject->Compare(*pNewObject);
switch(answer)
{
case same:
case bigger:
{
InternalNode<T> * internal = new InternalNode<T>(pNewObject, this, pPrevious);
pMyPrevious->SetNext(internal);
pMyPrevious = internal;
return internal;
}
case smaller:
pMyNext = pMyNext->Insert(pNewObject, this);
return this;
}
return this;
}
template <class T>
class TailNode: public Node<T>
{
public:
TailNode(HeadNode<T> * pHead);
~TailNode() {}
virtual Node<T> * Insert(T * pNewObject, Node<T> * pPrevious);
virtual void ModifyLinkPosition() {};
virtual void SetPrevious(Node<T> * pPrevious) {};
virtual void SetNext(Node<T> * pNext) {};
virtual void DeleteList() {delete this;}
// virtual T * Get(int val) {T * pNewObject = new T(); pNewObject->linkPosition = val; pMyHead->Insert(pNewObject, pMyHead); return pNewObject;}
virtual T * Get(int val) {return NULL;}
virtual void Delete(int val) {};
private:
HeadNode<T> * pMyHead;
};
template <class T>
TailNode<T>::TailNode(HeadNode<T> * pHead):
pMyHead(pHead)
{
}
template <class T>
Node<T> * TailNode<T>::Insert(T * pNewObject, Node<T> * pPrevious)
{
InternalNode<T> * internal = new InternalNode<T>(pNewObject, this, pPrevious);
return internal;
}
template <class T>
class HeadNode: public Node<T>
{
public:
HeadNode();
~HeadNode() {};
virtual Node<T> * Insert(T * pNewObject, Node<T> * pPrevious);
virtual void ModifyLinkPosition() {};
virtual void SetPrevious(Node<T> * pPrevious) {};
virtual void SetNext(Node<T> * pNext) {pMyNext = pNext;}
virtual void DeleteList() {pMyNext->DeleteList(); delete this;}
virtual T * Get(int val) {return pMyNext->Get(val);}
virtual void Delete(int val) {pMyNext->Delete(val);}
private:
Node<T> * pMyNext;
};
template <class T>
HeadNode<T>::HeadNode()
{
pMyNext = new TailNode<T>(this);
}
template <class T>
Node<T> * HeadNode<T>::Insert(T * pNewObject, Node<T> * pPrevious)
{
pMyNext = pMyNext->Insert(pNewObject, pPrevious);
return this;
}
template <class T>
class LinkedList
{
public:
LinkedList();
~LinkedList() {pMyHead->DeleteList();}
void Insert(T * pNewObject);
T * Get(int val) {return pMyHead->Get(val);}
void Delete(int val) {pMyHead->Delete(val);}
private:
HeadNode<T> * pMyHead;
};
template <class T>
LinkedList<T>::LinkedList()
{
pMyHead = new HeadNode<T>;
}
template <class T>
void LinkedList<T>::Insert(T * pNewObject)
{
pMyHead->Insert(pNewObject, pMyHead);
}
#endif
| true |
c8e55c23c484949956480bb4b52a9fe948528ba3 | C++ | XuenanZhang/GameServer | /engine/src/lib/common/FileUtil.h | UTF-8 | 1,581 | 2.515625 | 3 | [] | no_license | /**********************************************************
* Author : zxn
* Email : 176108053@qq.com
* GitHub : https://github.com/XuenanZhang
* Create time : 2018-04-23 16:06
* Last modified : 2018-04-23 16:06
* Filename : FileUtil.h
* Description : 读写文件操作
* *******************************************************/
#ifndef _BLING_FILEUTIL_H_
#define _BLING_FILEUTIL_H_
#include "common/noncopyable.h"
#include "common/Type.h"
namespace bling
{
namespace FileUtil
{
class ReadSmallFile : bling::noncopyable
{
public:
ReadSmallFile(string filename);
~ReadSmallFile();
int readToString(int maxSize, string* content, int64_t* fileSize, int64_t* modifyTime, int64_t* createTime);
int readToBuffer(int* size);
const char* buffer() const { return _buff; }
static const int kBufferSize = 64*1024;
private:
int _fd;
int _err;
char _buff[kBufferSize];
}; // class ReadSmallFile
/** 直接读取文件内容 **/
int readFile(string filename, int maxSize, string* content, int64_t* fileSize = NULL, int64_t* modifyTime = NULL, int64_t* createTime = NULL);
class AppendFile : bling::noncopyable
{
public:
AppendFile(string filename);
~AppendFile();
void append(const char* str, const size_t len);
void flush();
off_t writtenBytes() const { return _writtenBytes; }
private:
size_t write(const char* str, size_t len);
FILE* _fp;
char _buff[64*1024];
off_t _writtenBytes;
}; // class AppendFile
}; // ns FileUtil
}; //ns bling
#endif // _BLING_FILEUTIL_H_
| true |
eaafc3d74cb9c81de3b1d02b98e49ac87d9f366e | C++ | charliebruce/1B-IDP | /src/Navigation.cpp | UTF-8 | 14,041 | 2.921875 | 3 | [] | no_license | /*
* Navigation.cpp
*
* Created on: 19 Feb 2015
* Author: Charlie
*/
#include "Navigation.h"
#define LOGLEVEL LL_DEBUG
#include "Log.h"
ABS_DIRECTION flip (ABS_DIRECTION in) {
//This should simplify to ((in + 2) % 4) provided NORTH == 0
switch (in) {
case NORTH:
return SOUTH;
case SOUTH:
return NORTH;
case EAST:
return WEST;
case WEST:
return EAST;
default:
WARN("Incorrect use of flip!");
return NORTH;
}
}
void Navigation::addDeadend(NODEINDEX n, ABS_DIRECTION dir) {
nodes[n].neighbours[dir] = NODE_DEADEND; //Essentially an unreachable node
}
//The link starts at FROM, runs DIRECTION to TARGET, with the length LENGTH
void Navigation::addLink(NODEINDEX from, ABS_DIRECTION dir, NODEINDEX to, int length) {
nodes[from].neighbours[dir] = to;
nodes[to].neighbours[flip(dir)] = from;
nodes[from].lengths[dir] = length;
nodes[to].lengths[flip(dir)] = length;
}
void Navigation::setForwardsDirection(ABS_DIRECTION dir) {
forwards = dir;
}
Navigation::Navigation() {
DEBUG("[NAV] Creator.");
//The game state starts with all collection points occupied
for(int i = 0; i<NUM_CP; i++) {
cpHasEgg[i] = true;
}
//We start pointing EAST
setForwardsDirection(EAST);
//At the starting location
currentNode = NODE_START;
//No target initially
targetNode = NODE_START;
//Set up the world map - doing it this way stops redundancy
//If it isn't connected to anything it is a deadend
for(int i = 0; i < NODE_DEADEND; i++) {
for(int d = 0; d < 4; d++) {
nodes[i].neighbours[d] = NODE_DEADEND;
}
}
//The upper section
addLink(NODE_DP2DP3, EAST, NODE_1, 85);
addLink(NODE_1, EAST, NODE_2, 85);
//addLink(NODE_2, SOUTH, NODE_3A, 30);
addLink(/*NODE_3A*/NODE_2, SOUTH, NODE_3, /*114*/144);
addLink(NODE_3, SOUTH, NODE_4, 24);
//Collection points, E-W roads
addLink(NODE_3, WEST, NODE_CP4, 44);
addLink(NODE_4, WEST, NODE_CP4S, 44);
addLink(NODE_CP4S, WEST, NODE_CP3S, 20);
addLink(NODE_CP4, WEST, NODE_CP3, 20);
addLink(NODE_CP3S, WEST, NODE_CP2S, 20);
addLink(NODE_CP3, WEST, NODE_CP2, 20);
addLink(NODE_CP2S, WEST, NODE_CP1S, 20);
addLink(NODE_CP2, WEST, NODE_CP1, 20);
addLink(NODE_CP1S, WEST, NODE_CP0S, 20);
addLink(NODE_CP1, WEST, NODE_CP0, 20);
//Collection points, N-S roads
addLink(NODE_CP0, SOUTH, NODE_CP0S, 24);
addLink(NODE_CP1, SOUTH, NODE_CP1S, 24);
addLink(NODE_CP2, SOUTH, NODE_CP2S, 24);
addLink(NODE_CP3, SOUTH, NODE_CP3S, 24);
addLink(NODE_CP4, SOUTH, NODE_CP4S, 24);
//The start, and dropoff loop for D1
addLink(NODE_START, EAST, NODE_7, 19);
addLink(NODE_7, EAST, NODE_CP0, 26);
addLink(NODE_START, WEST, NODE_8, 19);
addLink(NODE_START, SOUTH, NODE_6, 14);
addLink(NODE_6, SOUTH, NODE_5, 9999); //Distance uncertain
addLink(NODE_5, EAST, NODE_CP0S, 44);
addLink(NODE_START, NORTH, NODE_9, 14);
addLink(NODE_9, NORTH, NODE_10, 46);
addLink(NODE_10, EAST, NODE_DP1, 85);
addLink(NODE_DP1, SOUTH, NODE_CP2, 62); //Distance uncertain
//Mark T junctions
nodes[NODE_CP0].tJunction = true;
nodes[NODE_CP0].tOrientation = NORTH;
nodes[NODE_CP1].tJunction = true;
nodes[NODE_CP1].tOrientation = NORTH;
nodes[NODE_CP3].tJunction = true;
nodes[NODE_CP3].tOrientation = NORTH;
nodes[NODE_CP4].tJunction = true;
nodes[NODE_CP4].tOrientation = NORTH;
//TODO finish list of dead ends
}
Navigation::~Navigation() {
DEBUG("[NAV] Destructor.");
}
void Navigation::goHome(HAL* hal) {
DEBUG("[NAV] Returning home...");
calculateRouteToNode(NODE_START);
travelRoute(hal);
DEBUG("[NAV] Orienting in the E-W direction...");
if((forwards == EAST) || (forwards == WEST)) {
INFO("[NAV] Made it home - no need to turn.");
return;
}
junctionTurn(false, hal); //False: Clockwise (right) turn
if(forwards == NORTH)
forwards = EAST; //Clockwise turn from NORTH
else
forwards = WEST; //Clockwise turn from SOUTH
INFO("[NAV] Home after turning!");
}
void Navigation::travelToCP(COLLECTION_POINT cp, HAL* h) {
DEBUG("[NAV] Travelling to "<<cp);
calculateRouteToNode(nodeForCP(cp));
travelRoute(h);
}
void Navigation::travelToDP(DROPOFF_POINT dp, HAL* h) {
DEBUG("[NAV] Travelling to "<<dp);
calculateRouteToNode(nodeForDP(dp));
travelRoute(h);
}
void Navigation::travelToStart(HAL* h) {
DEBUG("[NAV] Returning home.");
calculateRouteToNode(NODE_START);
travelRoute(h);
}
void Navigation::collectEgg(COLLECTION_POINT cp, HAL* h) {
WARN("[NAV] Not yet tested egg pickup.");
//Orient ourselves at the CP ie always face south
if(forwards == EAST) {
//Rotate Clockwise (ie right)
junctionTurn(false, h);
}
if(forwards == WEST) {
//Rotate Anticlockwise (ie left)
junctionTurn(true, h);
}
if(forwards == NORTH) {
//WTF?
ERR("We should never be collecting but facing NORTH!");
return;
}
//We will now be facing south, to the CP.
forwards = SOUTH;
//Safety: Ensure that our claw is open and in the up position.
h->pneumaticOperation(PNEU_CLAW, CLAW_OPEN);
h->carriageMove(POS_UP);
//We're actually very lucky: if we are just behind CPxS, our claw lines up.
//Approach and hit CPxS
followLineToNext(24, false, false, h);
//In case we overshot the junction
reverseToJunction(h);
reverseJustBeyondJunction(h);
//Line up straight (ie centre ourselves on the line)
//Probably not necessary if we have wide jaws: centreOnLine(h);
//Operate claw
h->pneumaticOperation(PNEU_CLAW, CLAW_CLOSED);
//Wait for pneumatic action.
delay(3000);
//Verify a good grab
if(!h->switchRead(SWITCH_EGG)) {
ERR("Failed to grab egg! Bad egg!");
//return;
}
reverseToJunction(h);
reverseJustBeyondJunction(h);
reverseToJunction(h);
//We find ourselves back on the CPx node, facing south, as expected.
}
void Navigation::dropoffEgg(DROPOFF_POINT dp, HAL* h) {
INFO("[NAV] Depositing egg in " << dp);
//Orient in the correct direction
ABS_DIRECTION nextdir = WEST;
switch(dp) {
case DP_1:
nextdir = NORTH;
break;
case DP_2:
nextdir = SOUTH;
break;
case DP_3:
nextdir = WEST;
break;
case NUM_DP:
default:
WARN("[NAV] Incorrect use of dropoff!");
}
if(forwards != nextdir) {
//Work out if we want to perform a left or a right turn. This assumes that the orientations are defined clockwise as seen from above looking down
bool left = true;
if (((forwards + 1) % 4) == nextdir){
left = false;
} else {
left = true;
}
DEBUG("[NAV] Current orientation is "<<forwards<<" but we need " << nextdir << " - we need to rotate "<<(left?"left":"right"));
//Perform the rotation and update the orientation
junctionTurn(left, h);
forwards = nextdir;
}
//Approach the DP
junctionStraight(h);
//Operate lift to lower position
h->carriageMove(POS_DOWN);
//Operate claw
h->pneumaticOperation(PNEU_CLAW, CLAW_OPEN);
//Lift again
h->carriageMove(POS_UP);
//Reverse to junction
reverseToJunction(h);
}
static const int HIGHWEIGHT = 100000;
bool Navigation::notFinishedWeighting(void) {
for(int i = 0; i < NODE_DEADEND; i++) {
if (nodes[i].weight == HIGHWEIGHT)
return true;
}
return false;
}
//Return the distance from current location to the node
int Navigation::calculateRouteToNode(NODEINDEX givenTarget) {
DEBUG("[NAV] Calculating route to node " << givenTarget);
targetNode = givenTarget;
//Assign weight of 100000 to all nodes including the DEADEND node
for(int i = 0; i< NUM_NODES; i++) {
nodes[i].weight = HIGHWEIGHT;
}
//Start at the target node, assign a weight of 0
nodes[givenTarget].weight = 0;
//Now loop until no node is at -1 (unreachable nodes will cause a loop until the failsafe catches it)
int runs = 0;
while(notFinishedWeighting()) {
runs++;
TRACE("[NAV] Weighting: Run " << runs);
//For each of the nodes except dead ends
for(int i = 0; i < NODE_DEADEND; i++) {
//For each of the directions
for(int dir = 0; dir < 4; dir++) {
//Consider the neighbour in each direction
NODEINDEX neighbour = nodes[i].neighbours[dir];
TRACE("[NAV] Considering "<<i<<"'s neighbour in the "<<dir <<" direction. Has weight "<<nodes[neighbour].weight);
//If the neighbour in that direction is reachable (weight realistic)
if(nodes[neighbour].weight < HIGHWEIGHT) {
TRACE("[NAV] That neighbour is weighted!");
//The total weight through that neighbour is (neighbour weight + interconnecting line length)
int neighbourRouteWeight = nodes[neighbour].weight + nodes[i].lengths[dir];
//The weight of the current node should be min ( ( current weight ) , ( weight of neighbouring node + distance between them ) )
if(neighbourRouteWeight < nodes[i].weight)
nodes[i].weight = neighbourRouteWeight;
}
}
//This algorithm isn't very fast but for a small map (around 30 nodes) we don't care, we have the power - we're not an 8-bit microcontroller.
}
//This should typically reach a conclusion in under 20 loops - guards against un-linked nodes (we won't spin forever)
if (runs > 25) {
WARN("[NAV] Possibly unreachable node in navigation mesh!");
WARN("[NAV] Not yet weighted: ");
for(int i = 0; i< NODE_DEADEND; i++) {
if(nodes[i].weight == HIGHWEIGHT)
WARN("Node " << i);
}
return nodes[currentNode].weight;
}
}
//NOTE: This algorithm does not take in to account the fact that changing direction has a cost associated with it.
DEBUG("[NAV] Found weights, distance is " << nodes[currentNode].weight);
return nodes[currentNode].weight;
}
//Go down the "weight gradient" to the target node
void Navigation::travelRoute(HAL* h) {
TRACE("[NAV] I walk this lonely road...");
//While we haven't arrived
int juncs = 0;
while(currentNode != targetNode) {
juncs++;
DEBUG("[NAV] Not there yet: at "<<currentNode);
NODEINDEX next;
ABS_DIRECTION nextdir;
int lowest = 100000;
//Work out which neighbour to head towards (lowest numbered neighbour)
for(int dir = 0; dir < 4; dir++) {
NODEINDEX n = nodes[currentNode].neighbours[dir];
if (nodes[n].weight < lowest)
{
next = n;
nextdir = (ABS_DIRECTION) dir;
lowest = nodes[n].weight;
TRACE("[NAV] "<<n <<" has lower weight of "<<nodes[n].weight<<"; a better candidate.");
}
}
DEBUG("[NAV] Next node will be " << next);
//U-Turns implemented in a special case (we are turning on the spot)
bool uTurned = false;
if(nextdir == flip(forwards)) {
DEBUG("[NAV] U Turn.");
uTurn(h);
DEBUG("[NAV] U Turned.");
forwards = flip(forwards);
uTurned = true;
}
//If we need to change orientation, do so
if(forwards != nextdir) {
//Work out if we want to perform a left or a right turn. This assumes that the orientations are defined clockwise as seen from above looking down
bool left = true;
if (((forwards + 1) % 4) == nextdir){
left = false;
} else {
left = true;
}
DEBUG("[NAV] Current orientation is "<<forwards<<" but we need " << nextdir << " - we need to rotate "<<(left?"left":"right"));
//Perform the rotation and update the orientation
junctionTurn(left, h);
forwards = nextdir;
//Are we approaching a T junction from the side?
bool approachingTSide = false;
if(nodes[next].tJunction && (forwards != flip(nodes[next].tOrientation)))
approachingTSide = true;
if(approachingTSide)
TRACE("[NAV] We are approaching a T junction from the side!");
//Follow the line
followLineToNext(nodes[currentNode].lengths[nextdir], false, approachingTSide, h);
} else {
if(!uTurned)
junctionStraight(h);
//Are we approaching a T junction from the side?
bool approachingTSide = false;
if(nodes[next].tJunction && (forwards != flip(nodes[next].tOrientation)))
approachingTSide = true;
if(approachingTSide)
TRACE("[NAV] We are approaching a T junction from the side!");
//Follow the line to the next node
followLineToNext(nodes[currentNode].lengths[nextdir], true, approachingTSide, h);
}
//Update the current node
currentNode = next;
}
}
//Find the nearest location from which we can collect an egg, given our current location
COLLECTION_POINT Navigation::getNearestEggyCP(void) {
//if at D1, we prioritise CP2, 3, 4, 1, 0 to get the points ASAP
//If at D2 or D3, prioritise in descending order
//If at start, we prioritise in ascending order
//We should not be asked this if located anywhere else! Maybe if we discard an egg or encounter another error.
//In that case a non-optimal pickup location is the least of our worries.
COLLECTION_POINT priority[NUM_CP];
if(currentNode == NODE_START) {
priority[0] = CP_0;
priority[1] = CP_1;
priority[2] = CP_2;
priority[3] = CP_3;
priority[4] = CP_4;
}
else if(currentNode == NODE_DP1) { //If at DP1 we're almost certain to need to take it up the ramp (assuming we can't reach from below!!!!)
priority[0] = CP_2;
priority[1] = CP_3;
priority[2] = CP_4;
priority[3] = CP_1;
priority[4] = CP_0;
}
else { //TODO if we're not at D2 or D3 this may not be optimal!
priority[0] = CP_4;
priority[1] = CP_3;
priority[2] = CP_2;
priority[3] = CP_1;
priority[4] = CP_0;
}
int i = 0;
while(i < NUM_CP && !cpHasEgg[priority[i]]) {
//If the egg has been collected, move to the next-highest ranking pickup location
i++;
}
if(i == NUM_CP) {
WARN("[NAV] No valid collection point found!");
return CP_0;
}
DEBUG("[NAV] Found nearest CP: " << priority[i]);
return priority[i];
}
NODEINDEX Navigation::nodeForDP(DROPOFF_POINT dp) {
switch(dp) {
case DP_1:
return NODE_DP1;
case DP_2:
return NODE_DP2DP3;
case DP_3:
return NODE_DP2DP3;
default:
ERR("[NAV] Tried to get node for an unknown or invalid dropoff point!");
return NODE_START;
}
}
NODEINDEX Navigation::nodeForCP(COLLECTION_POINT cp) {
switch(cp) {
case CP_0:
return NODE_CP0;
case CP_1:
return NODE_CP1;
case CP_2:
return NODE_CP2;
case CP_3:
return NODE_CP3;
case CP_4:
return NODE_CP4;
default:
ERR("[NAV] Tried to get node for an unknown or invalid collection point!");
return NODE_START;
}
}
void Navigation::setNoEgg(COLLECTION_POINT cp) {
cpHasEgg[cp] = false;
}
| true |
f3e340064477bfa329b895048954295575d152ff | C++ | wendymunyasi/cool-project3 | /original_tables/BFILE.CC | UTF-8 | 6,658 | 2.9375 | 3 | [] | no_license | /* BFile.CC
----------------------------------------------------------------
Jim Sare - jimsare@ameritech.net
Last Modified: 04/17/1998
Binary File read/write routines. This is a subclass
of the file class in Visual dBASE 7 .
ReadDouble, WriteDouble, ReadLDouble, WriteLDouble are based on
code by Ken Chan and rewritten to support direct file read/write.
NOTE: There is no error checking to ensure that values passed
to the Write functions are within the proper range.
There is no EOF handling within this class. EOF handling
should be performed prior to and/or after Read calls.
Backup any files that will be accessed via this class.
Usage:
Write To File:
b = New BFile() // Create a new instance
b.Create("Test.BIN") // Create a file/overwrite existing
b.WriteULong(0xAA55AA55) // Write unsigned long
b.WriteUShort(0x55AA) // Write unsigned short
b.Close() // Close the file
Read From File:
b = New BFile() // Create a new instance
b.Open("Test.BIN") // Open existing binary file
? IToH(b.ReadULong()) // Read unsigned long
? IToH(b.ReadUShort()) // Read unsigned short
b.Close() // Close the file
Methods:
ReadChar()
Read 8-bit signed numeric
ReadDouble()
Read 64-bit float
ReadLDouble()
Read 80-bit float
ReadLong()
Read 32-bit signed numeric
ReadShort()
Read 16-bit signed numeric
ReadUChar()
Read 8-bit unsigned numeric
ReadULong()
Read 32-bit unsigned numeric
ReadUShort()
Read 16-bit unsigned numeric
WriteChar()
Write 8-bit signed numeric
WriteDouble()
Write 64-bit float
WriteLDouble()
Write 80-bit float
WriteLong()
Write 16-bit signed numeric
WriteShort()
Write 16-bit signed numeric
WriteUChar()
Write 8-bit unsigned numeric
WriteULong()
Write 32-bit unsigned numeric
WriteUShort()
Write 16-bit unsigned numeric
----------------------------------------------------------------
*/
CLASS BFile Of File
// Type Description Size Range
// -----------------------------------------
// UChar unsigned char 8 bits 0 to 255
// Char char 8 bits -128 to 127
// UShort ushort 16 bits 0 - 65535
// Short short int 16 bits -32,768 to 32,767
// ULong unsigned long 32 bits 0 to 4,294,967,295
// Long long 32 bits -2,147,483,648 to 2,147,483,647
// Double double 64 bits 1.7 x 10-308 to 1.7 x 10+308
// LDouble long double 80 bits 3.4 x 10-4932 to 1.1 x 10+4932
#define DOUBLE_EBIAS 0x3FF
#define DOUBLE_MANTBITS 52
#define LDOUBLE_EBIAS 0x3FFF
#define LDOUBLE_MANTBITS 64
FUNCTION ReadUChar // Read 8-bit unsigned numeric
RETURN Asc(this.Read(1))
FUNCTION WriteUChar(n) // Write 8-bit unsigned numeric
RETURN this.Write(Chr(BitAnd(n, 0xFF)))
FUNCTION ReadChar // Read 8-bit signed numeric
LOCAL n
n = this.ReadUChar()
RETURN IIf(n < 0x80, n, -0x100 + n)
FUNCTION WriteChar(n) // Write 8-bit signed numeric
RETURN this.WriteUChar(IIf(n > 0, BitAnd(n, 0x7F), 0x100 + n))
FUNCTION ReadUShort // Read 16-bit unsigned numeric
LOCAL c
c = this.Read(2)
RETURN Int(Asc(SubStr(c, 1)) +;
BitLShift(Asc(SubStr(c, 2)), 8))
FUNCTION WriteUShort(n) // Write 16-bit unsigned numeric
RETURN this.Write(Chr(BitAnd(n, 0xFF)) +;
Chr(BitAnd(BitRShift(n, 8), 0xFF)))
FUNCTION ReadShort // Read 16-bit signed numeric
LOCAL n
n = this.ReadUShort()
RETURN IIf(n < 0x8000, n, -0x10000 + n)
FUNCTION WriteShort(n) // Write 16-bit signed numeric
RETURN this.WriteUShort(IIf(n > 0, n, 0x10000 + n))
FUNCTION ReadULong // Read 32-bit unsigned numeric
LOCAL c
c = this.Read(4)
RETURN Int(Asc(SubStr(c, 1)) +;
BitLShift(Asc(SubStr(c, 2)), 8) +;
BitLShift(Asc(SubStr(c, 3)), 16) +;
BitLShift(Asc(SubStr(c, 4)), 24))
FUNCTION WriteULong(n) // Write 32-bit unsigned numeric
RETURN this.Write(Chr(BitAnd(n, 0xFF)) +;
Chr(BitAnd(BitRShift(n, 8), 0xFF)) +;
Chr(BitAnd(BitRShift(n, 16), 0xFF)) +;
Chr(BitAnd(BitRShift(n, 24), 0xFF)))
FUNCTION ReadLong // Read 32-bit signed numeric
LOCAL n
n = this.ReadULong()
RETURN IIf(n < 0x80000000, n, -0x100000000 + n)
FUNCTION WriteLong(n) // Write 32-bit signed numeric
RETURN this.WriteULong(IIf(n > 0, n, 0x100000000 + n))
FUNCTION ReadDouble // Read 64-bit float
LOCAL c, n, bNeg, nExp, nMant
c = this.Read(8)
n = Asc(SubStr(c, 8))
bNeg = BitSet(n, 7)
nExp = BitLShift(BitAnd(n, 0x7F), 4)
n = Asc(SubStr(c, 7))
nExp += BitZRShift(n, 4)
nMant = 0x10 + BitAnd(n, 0x0F)
For n = 6 To 1 Step -1
nMant *= 256.0
nMant += Asc(SubStr(c, n))
EndFor
nMant *= 2^(nExp - DOUBLE_EBIAS - DOUBLE_MANTBITS)
RETURN IIf(bNeg, -nMant, nMant)
FUNCTION WriteDouble(n) // Write 64-bit float
LOCAL nAbs, bNeg, nExp, nMant, nInd, c
c = ""
bNeg = n < 0
nAbs = Abs(n)
nExp = Floor(Log(nAbs) / Log(2))
nMant = Floor(nAbs / 2^(nExp - DOUBLE_MANTBITS))
nExp += DOUBLE_EBIAS
For nInd = 1 To 6
c += Chr(nMant % 0x100)
nMant /= 0x100
EndFor
nMant := BitAnd(nMant, 0x0F)
c += Chr(nMant + BitLShift(BitAnd(nExp, 0x0F), 4))
nExp := BitZRShift(nExp, 4)
c += Chr(nExp + IIf(bNeg, 0x80, 0))
RETURN this.Write(c)
FUNCTION ReadLDouble // Read 80-bit float
LOCAL c, n, bNeg, nExp, nMant
c = this.Read(10)
n = Asc(SubStr(c, 9)) + BitLShift(Asc(SubStr(c, 10)), 8)
bNeg = BitSet(n, 15)
nExp = BitAnd(n, 0x7FFF)
nMant = 0
For n = 8 To 1 Step -1
nMant *= 256.0
nMant += Asc(SubStr(c, n))
EndFor
nMant *= 2^(nExp - LDOUBLE_EBIAS - LDOUBLE_MANTBITS + 1)
RETURN IIf(bNeg, -nMant, nMant)
FUNCTION WriteLDouble(n) // Write 80-bit float
LOCAL nAbs, bNeg, nExp, nMant, nInd, c
c = ""
bNeg = n < 0
nAbs = Abs(n)
nExp = Floor(Log(nAbs) / Log(2))
nMant = Floor(nAbs / 2^(nExp - LDOUBLE_MANTBITS + 1))
nExp += LDOUBLE_EBIAS
For nInd = 1 To 8
c += Chr(nMant % 0x100)
nMant /= 0x100
EndFor
c += Chr(BitAnd(nExp, 0xFF))
nExp := BitZRShift(nExp, 8)
c += Chr(nExp + IIf(bNeg, 0x80, 0))
RETURN this.Write(c)
ENDCLASS // BFile Of File
// EOF: BFile.CC
| true |
912018fc5fe874d6303f8131b3288bbd0f9cf89c | C++ | Gr1dlock/OOP | /LR_3/LR_3/cabin.cpp | UTF-8 | 2,192 | 2.9375 | 3 | [] | no_license | #include "cabin.h"
Cabin::Cabin()
{
cur_direction = NO_DIRECTION;
cur_floor = 1;
target_floor = 1;
state = WAITING;
connect(&doors, SIGNAL(closedDoors()), this, SLOT(movement()));
connect(&timerMovement, SIGNAL(timeout()), this, SLOT(movement()));
connect(this, SIGNAL(stoppedOnTargetFloor()), this, SLOT(stopOnFloor()));
connect(this, SIGNAL(move()), &doors, SLOT(closeDoors()));
connect(this, SIGNAL(targetAchieved(int, Direction)), &doors, SLOT(openingDoors()));
connect(&doors, SIGNAL(statusChanged(QString)), this, SLOT(sendDoorsMessage(QString)));
timerMovement.setSingleShot(true);
}
void Cabin::movement()
{
if (this->state == BUSY)
{
state = MOVING;
if (cur_floor == target_floor)
{
emit stoppedOnTargetFloor();
}
else
{
timerMovement.start(TIME_BETWEEN_FLOORS);
}
}
else if (state == MOVING)
{
if (cur_floor < target_floor)
{
cur_direction = UP;
cur_floor += 1;
}
else
{
cur_direction = DOWN;
cur_floor -= 1;
}
if (cur_floor == target_floor)
{
emit stoppedOnTargetFloor();
}
else
{
emit intermediatePassed(cur_floor, cur_direction);
timerMovement.start(TIME_BETWEEN_FLOORS);
QString message = QStringLiteral("Лифт сейчас на %1 этаже.").arg(cur_floor);
emit statusChanged(message);
}
}
}
void Cabin::stopOnFloor()
{
state = WAITING;
timerMovement.stop();
QString message = QStringLiteral("Лифт остановился на %1 этаже.").arg(cur_floor);
emit statusChanged(message);
emit targetAchieved(cur_floor, cur_direction);
}
void Cabin::sendDoorsMessage(QString message)
{
emit statusChanged(message);
}
void Cabin::getTarget(int floor)
{
state = BUSY;
target_floor = floor;
if (cur_floor == target_floor)
{
emit stoppedOnTargetFloor();
}
else
{
cur_direction = target_floor > cur_floor ? UP : DOWN;
emit move();
}
}
| true |
762fb74ed56007f30cd1a08865906f112f5c855a | C++ | dixonwi3/UMLWars | /Testing/CScoreboardTest.cpp | UTF-8 | 1,050 | 2.5625 | 3 | [] | no_license | #include "pch.h"
#include "CppUnitTest.h"
#include "UmlGame.h"
#include "Scoreboard.h"
#include <iostream>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
namespace Testing
{
TEST_CLASS(CScoreboardTest)
{
public:
TEST_METHOD_INITIALIZE(methodName)
{
extern wchar_t g_dir[];
::SetCurrentDirectory(g_dir);
}
TEST_METHOD(TestScoreboardConstruct)
{
CUmlGame game;
CScoreboard board(&game);
}
TEST_METHOD(TestScoreboardRaiseScore)
{
CUmlGame game;
// test incrementing correct score
game.GetScoreboard()->RaiseCorrect();
Assert::IsTrue(game.GetScoreboard()->GetCorrect() == 1, L"Testing raising Correct scores.");
// test incrememnting missed score
game.GetScoreboard()->RaiseMissed();
Assert::IsTrue(game.GetScoreboard()->GetMissed() == 1, L"Testing raising Missed scores.");
// test incrememnting missed score
game.GetScoreboard()->RaiseUnfair();
Assert::IsTrue(game.GetScoreboard()->GetUnfair() == 1, L"Testing raising Unfair scores.");
}
};
} | true |
039c0739d31278bbc070f8ef1fa4bac7e202fa82 | C++ | rp4ri/URI-Online-Judge | /1176.cpp | UTF-8 | 351 | 2.9375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a;
int t, i;
int long long f[61];
int j;
cin >> t;
f[0]=0;
f[1]=1;
for (j=2; j<=60; j++)
{
f[j] = f[j-2]+f[j-1];
}
for (i=0; i<t; i++)
{
cin >> a;
cout << "Fib(" << a << ") = " << f[a] << endl;
}
return 0;
}
| true |
c7a59d98e51d5582cd0a85e36dd714ecc9c7e62b | C++ | Alex23013/ADA_algorithms | /Sorts/radix&insertion&heapSortsWithVector.cpp | UTF-8 | 4,220 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <chrono>
#include <utility>
#include <vector>
#include <string>
#include<sstream>
#include <algorithm>
using namespace std;
using namespace std::chrono;
template <typename T>
void Insertion_Sort(vector<T>* _array){
int n = _array->size(),
j = 0,
x = 0;
for (int i = 1; i < n; i++){
x = _array->at(i);
j = i;
while(j > 0 && ( _array->at(j-1) > x ) ){
_array->at(j) = _array->at(j-1);
j--;
}
_array->at(j) = x;
}
}
template <typename T>
void print(vector<T> _array){
int n = _array.size();
for (int i = 0; i < n; i++){
cout<<_array[i]<<"-";
}
cout<<endl;
}
void heapify(vector<int> *arr , int n, int i)
{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
if (l < n && arr->at(l) > arr->at(largest))
largest = l;
if (r < n && arr->at(r) > arr->at(largest))
largest = r;
if (largest != i)
{
swap(arr->at(i), arr->at(largest));
heapify(arr, n, largest);
}
}
void heapSort(vector<int>* arr)
{
int n = arr->size();
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i=n-1; i>=0; i--)
{
swap(arr->at(0), arr->at(i));
heapify(arr, i, 0);
}
}
template <typename T>
int digitos_num ( T Number )
{
string number;
stringstream ss;
ss << Number;
number = ss.str();
return number.size();
}
template <typename T>
int max_digitos(vector<T>* a){
int n = a->size();
int max=0;
for(int i =0;i< n;i++){
if(max < a->at(i)){
max=a->at(i);
}
}
return max;
}
template <typename T>
void radix_sort(vector<T> *a){
int n = a->size();
int temp[10];
int res[n];
int div =10;
int digito;
int num_digitos = digitos_num(max_digitos(a));
for(int j =0;j<num_digitos;j++){
for(int i=0;i<10;i++){temp[i]= 0;}
for(int i =0;i<n;i++){
//cout<<(a[i]%div)/(div/10)<<" / ";//para ver que digito se esta analizando
digito =(a->at(i)%div)/(div/10);
temp[digito]+=1;
}
for(int i=0;i<10;i++){;
temp[i+1]=temp[i]+temp[i+1];}
for(int i=n-1;i>=0;i--){
digito =(a->at(i)%div)/(div/10);
temp[digito]-=1;
res[temp[digito]]=a->at(i);
}
for(int i =0;i <n ;i++){
a->at(i)= res[i];
}
div=div*10;
//cout<<"\n------------------------\n";//para asegurarse la cantidad de loops
}
}
int main() {
vector<int> array;
int n;
srand(time(NULL));
int elementos[4] = {100,3000,5000,7000};
int opcion = 7;
while(opcion != 0){
cout<<"Desea ver: \n 1) Mejor caso \n 2) Caso medio \n 3) Peor caso\n 0) salir\n";
cin>>opcion;
for(int i = 0; i < 4; i++){
n = elementos[i];
double time = 0;
int tests = 10;
for (int i = 0; i < tests ; i++) {
if(opcion < 3 && opcion != 0){
for (int i = 0; i < n; i++){array.push_back(i);}
if (opcion == 2){
auto randomFun =[] (int i) { return rand()%i;};
random_shuffle(array.begin(), array.end(), randomFun);
}
}
if(opcion ==3){
for (int i = 0; i < n; i++){array.push_back(n-i);}
}
high_resolution_clock::time_point t1 = high_resolution_clock::now();
// intercambiar las linea comentadas para ver los tiempos de los 3 sorts
Insertion_Sort(&array);
// heapSort(&array);
//radix_sort(&array);
//print(array); //para verificar que los array estan ordenados
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto res = duration_cast<microseconds>( t2 - t1 ).count();
time += res;
array.clear();
}
long long ttime = time/tests;
if(opcion != 0){
cout << "tiempo:" << ttime/1000.0<< " milliseconds con " <<elementos[i]<< endl ;
}
}
}
}
| true |
55fb20048615eb374eb3d5363769f3587bf6cf28 | C++ | Deepakku28/Leetcode | /778. Swim in Rising Water.cpp | UTF-8 | 1,302 | 2.765625 | 3 | [] | no_license | class Solution {
public:
bool check(int upperLimit,int &n,vector<vector<int>> &grid){
vector<vector<bool>> visited(n,vector<bool>(n,false));
queue<pair<int,int>> q;
q.push({0,0});
visited[0][0]=true;
vector<vector<int>> dir={{0, 1}, {0, -1}, {1, 0}, { -1, 0}};
while(!q.empty()){
pair<int,int> curr=q.front();
q.pop();
if(grid[curr.first][curr.second]<=upperLimit){
if(curr.first==n-1 && curr.second==n-1){
return true;
}
for(auto it:dir){
int x=curr.first+it[0];
int y=curr.second+it[1];
if(x>=0 && x<n && y>=0 && y<n && visited[x][y]==false){
visited[x][y]=true;
q.push({x,y});
}
}
}
}
return false;
}
int swimInWater(vector<vector<int>>& grid) {
int n=grid.size();
int left=0;
int right=n*n-1;
while(left<right){
int mid=(left+right)/2;
if(check(mid,n,grid)){
right=mid;
}
else{
left=mid+1;
}
}
return right;
}
};
| true |
60ea6924163f312a836c5cab05a1371cd721f594 | C++ | Segs/SegsEngine | /drivers/gles3/rasterizer_gl_unique_handle.h | UTF-8 | 5,415 | 3 | 3 | [
"BSD-3-Clause",
"CC-BY-3.0",
"FTL",
"Zlib",
"Bitstream-Vera",
"MPL-2.0",
"curl",
"MIT",
"OFL-1.1",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-free-unknown"
] | permissive | #pragma once
#include "glad/glad.h"
#include <cstring> // for memset
#include <stdint.h>
using GLuint = uint32_t;
struct GLBufferImpl {
static void release(int count,GLuint *data) noexcept {
if(count && data[0]) {
glDeleteBuffers(count,data);
memset(data,0,sizeof(GLuint)*count);
}
}
static void create(int count,GLuint *data) noexcept {
release(count,data);
glGenBuffers(count,data);
}
};
struct GLVAOImpl {
static void release(int count,GLuint *data) noexcept {
if(count && data[0]) {
glDeleteVertexArrays(count,data);
memset(data,0,sizeof(GLuint)*count);
}
}
static void create(int count,GLuint *data) noexcept {
release(count,data);
glGenVertexArrays(count,data);
}
};
struct GLTextureImpl {
static void release(int count,GLuint *data) noexcept {
if(count && data[0]) {
glDeleteTextures(count,data);
memset(data,0,sizeof(GLuint)*count);
}
}
static void create(int count,GLuint *data) noexcept {
release(count,data);
glGenTextures(count,data);
}
};
struct GLFramebufferImpl {
static void release(int count,GLuint *data) noexcept {
if(count && data[0]) {
glDeleteFramebuffers(count,data);
memset(data,0,sizeof(GLuint)*count);
}
}
static void create(int count,GLuint *data) noexcept {
release(count,data);
glGenFramebuffers(count,data);
}
};
struct GLRenderBufferImpl {
static void release(int count,GLuint *data) noexcept {
if(count && data[0]) {
glDeleteRenderbuffers(count,data);
memset(data,0,sizeof(GLuint)*count);
}
}
static void create(int count,GLuint *data) noexcept {
release(count,data);
glGenRenderbuffers(count,data);
}
};
template<uint32_t count,typename ResourceImpl>
struct GLMultiHandle {
GLuint value[count];
// auto conversion operator, for single entry handles returns the stored value, otherwise return the pointer to storage
operator auto() const {
if constexpr(count==1)
return value[0];
else
return value;
}
void release() noexcept {
ResourceImpl::release(count,value);
}
void create() noexcept {
release();
ResourceImpl::create(count,value);
}
[[nodiscard]] bool is_initialized() const { return value[0]!=0; }
constexpr bool operator!=(GLuint e) const { static_assert(count==1); return value[0]!=e; }
constexpr bool operator==(GLuint e) const { static_assert(count == 1); return value[0]==e; }
GLMultiHandle(const GLMultiHandle &) = delete;
GLMultiHandle &operator=(const GLMultiHandle &) = delete;
GLMultiHandle(GLMultiHandle &&f) noexcept {
memcpy(value,f.value,sizeof(GLuint)*count);
memset(f.value,0,sizeof(GLuint)*count);
}
GLMultiHandle &operator=(GLMultiHandle &&f) noexcept {
ResourceImpl::release(count,value);
if(this!=&f) // do we actually need to copy anything ? NOTE: This conditional might be removed if it results in shorter code
memcpy(value,f.value,sizeof(GLuint)*count);
memset(f.value,0,sizeof(GLuint)*count);
return *this;
}
GLuint operator[](uint32_t idx) const {
return value[idx];
}
GLuint &operator[](uint32_t idx) {
return value[idx];
}
constexpr GLMultiHandle() {
value[0] = 0;
}
~GLMultiHandle() noexcept {
release();
}
};
template<uint32_t count>
using GLMultiBufferHandle = GLMultiHandle<count, GLBufferImpl>;
template<uint32_t count>
using GLMultiTextureHandle = GLMultiHandle<count, GLTextureImpl>;
template<uint32_t count>
using GLMultiVAOHandle = GLMultiHandle<count, GLVAOImpl>;
template<uint32_t count>
using GLMultiFBOHandle = GLMultiHandle<count, GLFramebufferImpl>;
using GLBufferHandle= GLMultiHandle<1, GLBufferImpl>;
using GLTextureHandle = GLMultiHandle<1, GLTextureImpl>;
using GLFBOHandle = GLMultiHandle<1, GLFramebufferImpl>;
using GLRenderBufferHandle = GLMultiHandle<1, GLRenderBufferImpl>;
using GLVAOHandle = GLMultiHandle<1, GLVAOImpl>;
struct GLNonOwningHandle {
GLuint value{0};
// auto conversion operator, for single entry handles returns the stored value, otherwise return the pointer to storage
operator auto() const {
return value;
}
[[nodiscard]] constexpr bool is_initialized() const { return value!=0; }
constexpr bool operator!=(GLuint e) const { return value!=e; }
constexpr bool operator==(GLuint e) const { return value==e; }
GLNonOwningHandle(const GLNonOwningHandle &) = delete;
GLNonOwningHandle &operator=(const GLNonOwningHandle &) = delete;
GLNonOwningHandle &operator=(const GLTextureHandle &f) {
value = f;
return *this;
}
GLNonOwningHandle(GLNonOwningHandle &&f) noexcept {
value = f.value;
f.value = 0;
}
GLNonOwningHandle &operator=(GLNonOwningHandle &&f) noexcept {
value = f.value;
f.value = 0; // this is set to 0 to help with debugging when moved-from handle is used
return *this;
}
constexpr GLNonOwningHandle() = default;
constexpr GLNonOwningHandle(GLuint v) : value(v) {}
~GLNonOwningHandle() noexcept = default;
};
| true |
c751fbae7e9c140c4d5382bdd36bcae29701118d | C++ | AlexZablotsky450501/Scheduler | /Source/addwindow.cpp | UTF-8 | 2,708 | 2.671875 | 3 | [] | no_license | #include "addwindow.h"
#include "ui_addwindow.h"
addWindow::addWindow(QDate &startDate,QWidget *parent) :
QDialog(parent),
ui(new Ui::addWindow)
{
ui->setupUi(this);
this->setWindowTitle("Добавление события"); //Изменение названия окна
ui->dateEdit->setDate(startDate); //Установка начальной даты
ui->dateEdit->setCalendarPopup(true);
ui->timeEdit->setTime(QTime::currentTime()); //Установка начального времени
ui->pushButtonOK->setDisabled(true); //"Выключение" кнопки "ОК"
}
addWindow::~addWindow()
{
delete ui;
}
void addWindow::on_pushButtonCancel_clicked() //Действие кнопки "Отмена":
{
close(); //закрыть окно добавления события
}
void addWindow::on_textPlan_textChanged() //Действия при изменении текста события
{
if (ui->textPlan->toPlainText() != "") //если не поле пустое
{
plan = ui->textPlan->toPlainText(); //занести текст поля в строку plan
ui->pushButtonOK->setDisabled(false); //"включить" кнопку "ОК"
} else //если поле пустое
{
ui->pushButtonOK->setDisabled(true); //"выключить" кнопку "ОК"
}
}
void addWindow::on_pushButtonOK_clicked() //Действие кнопки "ОК":
{
date = ui->dateEdit->date().toString("dd.MM.yyyy"); //запомнить дату, время, категорию события
time = ui->timeEdit->time().toString("hh:mm");
category = ui->comboBox->currentText();
MainWindow c; //создать экземпляр главного окна приложения
QSqlQuery qry; //занести в базу данных новую запись (событие)
qry.prepare("insert into plans (Дата,Время,Событие,Категория) values ('"+date+"','"+time+"','"+plan+"','"+category+"')");
qry.exec();
c.close();
ui->textPlan->setText("");
close(); //закрыть окно добавления события
}
| true |
f4c476eaac88366bca833fda6650c62d9a703552 | C++ | ujwalramesh/VLSIPlacement | /code/Pin/Pin.h | UTF-8 | 2,000 | 2.734375 | 3 | [] | no_license | # include <common.h>
# ifndef PIN_H
# define PIN_H
/* Pin direction definitions */
# define PIN_DIR_INPUT 0x1
# define PIN_DIR_OUTPUT 0x1 << 1
# define PIN_DIR_INOUT 0x1 << 2
# define PIN_DIR_ALL 0x1 << 3
class Cell;
class Net;
class Pin {
private:
int Id;
double cellXpos, cellYpos;
char dir;
bool isClock;
string libPinName;
public:
Cell *ParentCell;
Net *ConnectedNet;
int xOffset, yOffset;
string Name;
bool isHidden;
/* Constructors */
Pin();
Pin(int);
Pin(char);
Pin(int, int, int);
Pin(int, int, int, char);
Pin(int, const string&);
Pin(int, int, int, const string&);
Pin(int, int, int, char, const string&);
Pin(int, const Cell&);
Pin(int, int, int, const Cell&);
Pin(int, int, int, char, const Cell&);
Pin(int, const Cell&, const string&);
Pin(int, int, int, const Cell&, const string&);
Pin(int, int, int, char, const Cell&, const string&);
Pin(int, const Cell&, const Net&);
Pin(int, int, int, const Cell&, const Net&);
Pin(int, int, int, char, const Cell&, const Net&);
/* Set functions */
void PinSetId(int);
void PinSetName(string);
void PinSetLibName(string);
void PinSetParentCell(const Cell&);
void PinSetXOffset(int);
void PinSetYOffset(int);
void PinSetDirection(char);
void PinSetIsClock(const bool&);
void PinSetIsHidden(const bool&);
/* Get functions */
int PinGetId(void);
int PinGetXOffset(void);
int PinGetYOffset(void);
int PinGetAbsXPos(void) const;
int PinGetAbsYPos(void) const;
char PinGetDirection(void) const;
string PinGetName(void) const;
string PinGetLibName(void) const;
Cell& PinGetParentCell(void);
Cell* PinGetParentCellPtr(void);
Net& PinGetNet(void);
bool PinIsClock(void);
bool PinIsHidden(void);
/* Other functions */
void Connect(const Net&);
Net& Disconnect(void);
void PinGetXposYpos(int *, int*);
/* To be removed later */
string GetParentCellName();
uint GetParentCellXpos();
uint GetParentCellYpos();
};
# endif
| true |
15baa268a9bfead5f0e2b1e2dd770b7813b79e3e | C++ | Lcch/TopcoderSRM | /srm621/RadioRange.cpp | UTF-8 | 5,371 | 2.984375 | 3 | [] | no_license | // BEGIN CUT HERE
// END CUT HERE
#include <iostream>
#include <cstdio>
#include <string.h>
#include <string>
#include <algorithm>
#include <math.h>
#include <vector>
#include <sstream>
using namespace std;
class RadioRange {
public:
pair<double, double> GetInterval(double x, double y, double r, double z) {
double len = sqrt(x*x + y*y);
return make_pair(max(0.0, min(len - r, z)), min(len + r, z));
}
double RadiusProbability(vector <int> X, vector <int> Y, vector <int> R, int Z) {
int n = X.size();
vector<pair<double, double> > a;
for (int i = 0; i != n; i++) {
a.push_back(GetInterval(X[i], Y[i], R[i], Z));
}
sort(a.begin(), a.end());
double ans = a[0].second - a[0].first;
double right = a[0].second;
for (int i = 1; i != n; i++) {
if (a[i].first <= right) {
ans += max(right, a[i].second) - right;
right = max(right, a[i].second);
} else {
right = a[i].second;
ans += a[i].second - a[i].first;
}
}
return (Z - ans) / Z;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); if ((Case == -1) || (Case == 7)) test_case_7(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {5}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 0.5; verify_case(0, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 0.0; verify_case(1, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 0.4142135623730951; verify_case(2, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { int Arr0[] = {11, -11, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 0, 11, -11}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10, 10, 10, 10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 31; double Arg4 = 0.3548387096774194; verify_case(3, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_4() { int Arr0[] = {100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 1.0; verify_case(4, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_5() { int Arr0[] = {1000000000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1000000000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1000000000}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1000000000; double Arg4 = 0.41421356237309503; verify_case(5, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_6() { int Arr0[] = {20, -20, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 0, 20, -20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {50, 50, 50, 50}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 100; double Arg4 = 0.3; verify_case(6, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_7() { int Arr0[] = {0, -60, -62, -60, 63, -97}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {-72, 67, 61, -8, -32, 89}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {6, 7, 8, 7, 5, 6}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 918; double Arg4 = 0.9407071068962471; verify_case(7, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RadioRange ___test;
___test.run_test(-1);
return 0;
}
// END CUT HERE
| true |
b74cb33717bc55051d752db8f2b0420b9a8631bd | C++ | green-fox-academy/CodeMasterDog | /week-07/day 01/01.cpp/main.cpp | UTF-8 | 468 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
// Write a try - catch block.
// Throw an integer in the try block
// Catch it in the catch block and write it out.
int main()
{
try
{
int a = 20;
int b = 0;
if (b == 0)
throw -1;
int c = a / b;
cout << a << "/" << b << " = " << c << endl;
}
catch (int x)
{
cout << "Error num is: " << x << " Can't divide by zero." << endl;
}
return 0;
}
| true |
10e01ce281c86190fff30842081b084c6881b68d | C++ | NiklasRolleberg/asv-navigator | /polygon.hpp | UTF-8 | 2,900 | 2.84375 | 3 | [] | no_license | #ifndef POLYGON_H
#define POLYGON_H
#ifndef SHOW_GUI
#define SHOW_GUI false
#endif
#include <vector>
#include <iostream>
#include <set>
#include "element.hpp"
#include "segment.hpp"
#include "view.hpp"
struct Point {
double x, y;
Point(int px = 99, int py = -99): x(px), y(py){}
bool operator <(const Point &p) const
{
return x < p.x || (x == p.x && y < p.y);
}
};
/**The polygon class contains coordinates for the nodes, both in local and
lat/long coordinate systems and methods for calculating if a position
is inside the polygon*/
class Polygon
{
private:
std::vector<double>* latitude;// = nullptr;
std::vector<double>* longitude;// = nullptr;
bool localSet;
std::vector<double>* xPoints;// = nullptr;
std::vector<double>* yPoints;// = nullptr;
void addBoundaryElements(PolygonSegment* ps);
std::vector<PolygonSegment*>* triangulateRegion(PolygonSegment* ps);
PolygonSegment* createSegmentFromElements(std::set<Element*>);
/**vecor cross product*/
double cross(const Point &O, const Point &A, const Point &B);
/** true if element is connected to a scanned element*/
bool BFS(Element* e, std::set<Element*> &container);
bool showGUI;
PathView* GUI;
public:
int nx;
int ny;
double maxX;
double minX;
double maxY;
double minY;
double delta;
Element*** matrix;
std::vector<PolygonSegment*>polygonSegments;
/**Constructor*/
Polygon(std::vector<double> *lat, std::vector<double> *lon);
/**Destructor*/
~Polygon();
//for global coordinates
std::vector<double>* getLonBoundaries();
std::vector<double>* getLatBoundaries();
/** set boundaries for the local coorinate system */
void setLocalBoundaries(std::vector<double>*x,std::vector<double>*y);
/**set the grid resolution*/
void setGridSize(double delta);
/**Calculate min,max values for area and creates the grid matrix
and creates the first polygonsegment (searchCell i kexet)*/
void initialize();
std::vector<double>* getXBoundaries();
std::vector<double>* getYBoundaries();
/**Save all data so the scan can be restarted from this moment*/
void saveAll(std::string filename, double currentLat, double currentLon);
/**Save the element matrix for debuging*/
void saveMatrix();
/**remove a region from the list and delete it*/
void removeRegion(PolygonSegment* region);
/**remove all regions*/
void removeAllRegions();
/**Creates regions from the unscanned elements in the matrix*/
void generateRegions();
/**Marks elements contained by land as land*/
void idland();
/**Creates a nx x ny matrix with costs for all accessible elements with cost=0 at cx,cy*/
double** createCostMatrix(int cx, int cy);
/**update the window*/
void updateView(double currentX, double currentY,double heading);
};
#endif // POLYGON_H
| true |
cd4f9f5d201b4a022faa79549d802d2354328f0f | C++ | losinieckipiotr/raspberryPenthaus | /raspberryPenthaus/device/MotionSensor.h | UTF-8 | 974 | 2.609375 | 3 | [] | no_license | #ifndef MOTION_SENSOR_H
#define MOTION_SENSOR_H
#include <string>
#include "DeviceBase.h"
#include "IReadable.h"
namespace device
{
struct MotionSensorReadVal
{
public:
MotionSensorReadVal(
bool val,
unsigned int deviceID)
: val(val), deviceID(deviceID)
{ }
bool val;
unsigned int deviceID;
};
class MotionSensor : public DeviceBase, public IReadable
{
public:
MotionSensor(int, int, bool = true);
virtual ~MotionSensor() { }
virtual std::string ToString() const;
virtual void SaveToTree(boost::property_tree::ptree&, const std::string&) const;
virtual bool LoadFromTree(boost::property_tree::ptree::value_type&);
virtual event::eventPtr Read();
virtual std::string Execute(std::string&);
static const std::string name;
protected:
virtual bool _Read() = 0;
//TO DO: WYWALIC STATE I LOGIC I ZOSTWIC
//TYLKO TO
int _pin;
bool _logic;
int _state;
MotionSensorReadVal _myVal;
};
}
#endif // !MOTION_SENSOR_H
| true |
87764bab7e3b911cc1fbc25d13e2bc7e4734b640 | C++ | Sertarus/Date | /Date/Date.hpp | UTF-8 | 511 | 2.90625 | 3 | [] | no_license | #ifndef DATE_H
#define DATE_H
#include <iostream>
class Date {
public:
Date(int year, int month, int day);
~Date();
void SetDate(int year, int month, int day);
Date& operator++();
Date& operator--();
Date operator++(int);
Date operator--(int);
friend std::ostream& operator<< (std::ostream& out, const Date& date);
friend std::istream& operator>> (std::istream& in, Date& date);
private:
int year;
int month;
int day;
static bool isValidDate(int year, int month, int day);
};
#endif
| true |
2234b43a94c6351fa3b6aca5f63e86fb6b3128bb | C++ | hydraskillz/NetworkShooter | /src/MageMath/Numerics/Range.h | UTF-8 | 1,451 | 3.125 | 3 | [] | no_license | /*
* Author : Matthew Johnson
* Date : 10/Apr/2013
* Description :
*
*/
#pragma once
#include <RNG.h>
namespace mage
{
template< typename T >
class Range
{
public:
Range();
Range( T min, T max );
~Range();
// Inclusive: true iff value in [Min, Max]
inline bool IsValueInRange( const T& value ) const;
// Get random from range, inclusive
inline T GetRandomFromRange() const;
T Min;
T Max;
};
//---------------------------------------
// Imp
//---------------------------------------
template< typename T >
Range< T >::Range() { /* NOT INIT */ }
//---------------------------------------
template< typename T >
Range< T >::Range( T min, T max )
: Min( min )
, Max( max )
{}
//---------------------------------------
template< typename T >
Range< T >::~Range()
{}
//---------------------------------------
template< typename T >
bool Range< T >::IsValueInRange( const T& value ) const
{
return ( value >= Min && value <= Max );
}
//---------------------------------------
template< typename T >
inline T Range< T >::GetRandomFromRange() const
{
return RNG::RandomInRange( Min, Max );
}
//---------------------------------------
//---------------------------------------
// Types
//---------------------------------------
typedef Range< int > IntRange;
typedef Range< float > FloatRange;
typedef Range< double > DoubleRange;
//---------------------------------------
} | true |
1c9b4fea685cb687960e088a0ef89302db02a72b | C++ | GR6250-2019/hw6 | /xlloption/fms_cumulant.h | UTF-8 | 2,943 | 2.890625 | 3 | [
"MIT"
] | permissive | // fms_cumulant.h - A cumulant is a sequence of cumulants and operator() for the cumulant
#pragma once
#include <cmath>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <valarray>
#include "fms_sequence.h"
#include "fms_cumulant_constant.h"
#include "fms_cumulant_normal.h"
#include "fms_cumulant_poisson.h"
namespace fms::cumulant {
// K is the cumulant sequence
template<class K>
using value_type = std::invoke_result_t<decltype(&K::operator*), K>;
// Cumulants under the measure P_ with dP_/dP = exp(s X - kappa(s))
template<class K, class S = value_type<K>>
class _ { // ???Better name???
K k;
S s;
public:
_(const K& k, const S& s)
: k(k), s(s)
{ }
operator bool() const
{
return k;
}
// kappa^{X_}_n = sum_{k >= 0} kappa_{n + k} s^k/k!
S operator*() const
{
using fms::sequence::sum;
using fms::sequence::epsilon;
using fms::sequence::power;
using fms::sequence::factorial;
//K k2(k);
//auto s2 = *++k2; // variance
S s2 = 1;
return sum(epsilon(k * power(s) / factorial<S>{}, s2, 2));
}
_& operator++()
{
++k;
return *this;
}
S operator()(const S& u) const
{
return k(u + s) - k(s);
}
};
template<class K, class S = value_type<K>>
inline auto shift(const K& k, const S& s)
{
return _(k, s);
}
// Cumulants of a scalar multiple of a random variable.
// kappa^{cX}_n = c^n kappa^X_n
template<class K, class S = value_type<K>>
class scale {
K k;
S c, cn; // c^n
public:
scale(const K& k, const S& c, const S& cn = 0)
: k(k), c(c), cn(cn == 0 ? c : cn)
{ }
operator bool() const
{
return k;
}
S operator*() const
{
return cn * (*k);
}
scale& operator++()
{
++k;
cn *= c;
return *this;
}
// kappa^{cX}(s) = kappa(cs)
S operator()(const S& s) const
{
return k(c * s);
}
};
// Convert to mean 0, variance 1: X' = (X - mu)/sigma
// kappa'_1 = kappa_1 - mu = 0, kappa'_2 = kappa_2/sigma^2 = 1, kappa_n' = kappa_n/sigma^n for n > 2.
// Return original mean, standard deviation, and normalized kappa_n, n >= 3.
template<class K, class S = value_type<K>>
inline auto normalize(K kappa)
{
S mean = *kappa;
++kappa;
S variance = *kappa;
++kappa;
S sigma = sqrt(variance);
return std::tuple(mean, sigma, scale(kappa, 1/sigma, 1/variance));
}
}
| true |
b95cf66bc0c2a1b2e99b237c0358aff944f30542 | C++ | b-mc-c/Threading-projects | /Threading Before threaded/Threading/KeyBoardInput.h | UTF-8 | 521 | 2.875 | 3 | [] | no_license | #ifndef KEYBOARDINPUT_H
#define KEYBOARDINPUT_H
#include <iostream>
#include <SDL.h> //SDL
#include <stdio.h>
#include <list>
class KeyBoardInput
{
public:
void updateKeyboard(SDL_Event e);
bool isKeyPressed(SDL_Keycode key);
void clearKeys();
static KeyBoardInput* GetInstance();
~KeyBoardInput()
{
instanceFlag = false;
}
private:
KeyBoardInput()
{
pressedKeys = std::list<SDL_Keycode>();
}
std::list<SDL_Keycode> pressedKeys;
static bool instanceFlag;
static KeyBoardInput* instance;
};
#endif
| true |
1c5f394ced8e73c688e5325e18dcfd1cf02375b7 | C++ | LeonardoRibeiro161/Grafo_Cidade | /grafo.cpp | UTF-8 | 1,347 | 3.078125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<stdlib.h>
#define Vertice char
#include<string.h>
#include "grafo.h"
using namespace std;
typedef struct no
{
Vertice w;
struct no *prox;
}No;
typedef struct noGrafo
{
Vertice v;
No *adj;
struct noGrafo *prox;
float distancia;
}Lista;
No *cria(Vertice v1, No *p)
{
No *novo;
novo = (No *)malloc(sizeof(No));
novo->w = v1;
novo->prox = p;
return novo;
}
Lista *criaGrafo(Vertice v1, No *p, Lista *g)
{
Lista *novo;
novo = (Lista *)malloc(sizeof(Lista));
novo->v = v1;
novo->adj = p;
novo->prox = g;
return novo;
}
void Inserir(Lista *g)
{
No *l;
int qte, i;
Vertice v;
while(g != NULL)
{
l = NULL;
cout<<"Informe o numero de ligacoes partindo da cidade "<<g->v<<":";
cin>>qte;
fflush(stdin);
for(i = 0; i < qte;i++)
{
cout<<"Codigo da cidade de chegada:";
scanf("%c", &v);
cout<<"Informe a quilometragem:";
cin>>g->distancia;
fflush(stdin);
l = cria(v,l);
}
g->adj = l;
g = g->prox;
}
}
void percorrer(Lista *g)
{
while(g != NULL)
{
cout<<"Codigo da cidade:"<<g->v<<endl;
while(g->adj != NULL)
{
cout<<"Cidade ("<<g->v<<") --> Cidade("<<g->adj->w<<") Distancia: "<<g->distancia<<"km"<<endl;
g->adj = g->adj->prox;
}
g = g->prox;
}
}
| true |
692d0c318a4f0fc794a5c58e1ea7443da46e72f0 | C++ | 3agwa/CompetitiveProgramming | /CodeForces/CF474-D2-C.cpp | UTF-8 | 4,712 | 2.890625 | 3 | [] | no_license | /*
for each point, subtract the value of "home" from it, so we can translate about origin
we try all configurations of rotations and check whether the 4 new points for a non-empty square or not
we need to add the home value we subtracted earlier as we're (supposedly) rotating about the home, not the origin
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define vll vector<ll>
#define pii pair<int, int>
#define vii vector<pii>
#define vs vector<string>
#define vb vector<bool>
#define vi vector<int>
#define vd vector<double>
#define vvi vector< vector<int> >
#define vvii vector< vector< pii > >
#define ld long double
#define mapii map<int, int>
#define mapsi map<string, int>
#define erep(i, x, n) for (auto i = x; i<=(ll)(n); i++)
#define rep(i, x, n) for(auto i = x; i<(ll)(n); i++)
//#define INF LLONG_MAX
#define all(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define pie acos(-1)
#define mod(n,m) ((n % m + m) % m)
#define eps (1e-8)
#define reset(n, m) memset(n, m, sizeof n)
#define endl '\n'
#define output freopen("output.txt", "w", stdout)
#define mp(x, y, z) {x, {y, z}}
double INF = 1e100;
double EPS = 1e-7;
struct PT
{
double x, y;
PT() {}
PT(double x, double y) : x(x), y(y) {}
PT(const PT &p) : x(p.x), y(p.y) {}
PT operator + (const PT &p) const
{
return PT(x+p.x, y+p.y);
}
PT operator - (const PT &p) const
{
return PT(x-p.x, y-p.y);
}
PT operator * (double c) const
{
return PT(x*c, y*c );
}
PT operator / (double c) const
{
return PT(x/c, y/c );
}
bool operator<(const PT &p) const
{
return make_pair(x,y)<make_pair(p.x,p.y);
}
bool operator==(const PT &p) const
{
return !(*this < p) && !(p < *this);
}
};
double dot(PT p, PT q)
{
return p.x*q.x+p.y*q.y;
}
double dist2(PT p, PT q)
{
return dot(p-q,p-q);
}
double cross(PT p, PT q)
{
return p.x*q.y-p.y*q.x;
}
PT norm(PT x, double l)
{
return x * sqrt(l*l / dot(x,x));
}
istream &operator>>(istream &is, PT &p)
{
return is >> p.x >> p.y;
}
ostream &operator<<(ostream &os, const PT &p)
{
return os << "(" << p.x << "," << p.y << ")";
}
/*around the origin*/
PT RotateCCW90(PT p)
{
return PT(-p.y,p.x);
}
PT RotateCW90(PT p)
{
return PT(p.y,-p.x);
}
PT RotateCCW(PT p, double t)
{
return PT(p.x*cos(t)-p.y*sin(t), p.x*sin(t)+p.y*cos(t));
}
// project point c onto line through a and b (assuming a != b)
PT ProjectPointLine(PT a, PT b, PT c)
{
return a + (b-a)*dot(c-a, b-a)/dot(b-a, b-a);
}
// project point c onto line segment through a and b (assuming a != b)
PT ProjectPointSegment(PT a, PT b, PT c)
{
double r = dot(c-a, b-a)/dot(b-a,b-a);
if (r < 0) return a;
if (r > 1) return b;
return a + (b-a)*r;
}
PT arr[101][4], home[101][4];
bool square(PT a, PT b, PT c, PT d)
{
if (a == b || a == c || a == d || b == a || b == c || b == d || c == a || c == b || c == d || d == a || d == b || d == c) return 0;
set<int> st;
st.insert(dist2(a, b));
st.insert(dist2(a, c));
st.insert(dist2(a, d));
st.insert(dist2(b, a));
st.insert(dist2(b, c));
st.insert(dist2(b, d));
st.insert(dist2(c, b));
st.insert(dist2(c, a));
st.insert(dist2(c, d));
st.insert(dist2(d, b));
st.insert(dist2(d, c));
st.insert(dist2(d, a));
return (sz(st) <= 2);
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
rep(i, 0, n)
{
rep(j, 0, 4)
{
cin >> arr[i][j] >> home[i][j];
}
}
rep(i, 0, n)
{
int mn = INT_MAX;
PT a(arr[i][0]-home[i][0]);
PT b(arr[i][1]-home[i][1]);
PT c(arr[i][2]-home[i][2]);
PT d(arr[i][3]-home[i][3]);
rep(j, 0, 5)
{
if (j) a = RotateCCW90(a);
rep(k, 0, 5)
{
if (k) b = RotateCCW90(b);
rep(l, 0, 5)
{
if (l) c = RotateCCW90(c);
rep(m, 0, 5)
{
if (m) d = RotateCCW90(d);
if (square(a + home[i][0], b + home[i][1], c + home[i][2], d + home[i][3])) mn = min(mn, j+k+l+m);
}
}
}
}
if (mn == INT_MAX) cout << -1 << endl;
else cout << mn << endl;
}
return 0;
}
| true |
ab4ea67d18315746a7e99bfd03345c8596168c00 | C++ | wku/ViberDesktop | /src/Controls/StarLabel.cpp | UTF-8 | 704 | 3 | 3 | [] | no_license | #include "StarLabel.h"
StarLabel::StarLabel (QWidget* parent):QLabel (parent),m_isShowStar(false)
{
toggleStar(m_isShowStar);
}
void StarLabel::mousePressEvent ( QMouseEvent * event )
{
if ( event->button () == Qt::LeftButton )
{
emit clicked();
}
}
bool StarLabel::isShowStar () const
{
return m_isShowStar;
}
void StarLabel::toggleStar( bool isShowStar )
{
m_isShowStar = isShowStar;
//change state
if (m_isShowStar)
{
m_state = sFavorite;
}
else
{
m_state = sNormal;
}
setStyleSheet(styleSheet());
}
QString StarLabel::getStateString()
{
switch (m_state)
{
case sFavorite: return "favorite";
default: return "normal";
}
}
StarLabel::~StarLabel()
{
}
| true |
b06c9d779cf098cf5550002dde50ea57afae5e04 | C++ | Knueppl/achsenlastwaage | /src/vehicle_manager.cpp | UTF-8 | 9,478 | 2.703125 | 3 | [] | no_license | #include "vehicle_manager.h"
#include "SupplierDialog.h"
#include "ProductDialog.h"
#include "CreateVehicleDialog.h"
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include <QShortcut>
#include "control.h"
VehicleManager::VehicleManager(Control* control, QWidget* parent) : QWidget(parent)
{
m_control = control;
m_mainLayout = new QHBoxLayout(this);
m_groupVehicle = new QGroupBox("Fahrzeuge");
m_groupVehicle->setMinimumWidth(200);
m_vehicleLayout = new QVBoxLayout;
m_vehicleLayout->addStretch();
m_groupVehicle->setLayout(m_vehicleLayout);
m_mainLayout->addWidget(m_groupVehicle);
m_groupOption = new QGroupBox("Optionen");
m_optionLayout = new QGridLayout;
m_optionLayout->setAlignment(Qt::AlignTop);
m_createVehicle = new QPushButton("Neues Fahrzeug");
m_optionLayout->addWidget(m_createVehicle, 0, 0);
m_deleteVehicle = new QPushButton("Lösche Fahrzeug");
m_optionLayout->addWidget(m_deleteVehicle, 0, 1);
m_abortWeighting = new QPushButton("Abruch");
m_abortWeighting->setEnabled(false);
m_optionLayout->addWidget(m_abortWeighting, 2, 0);
m_groupOption->setLayout(m_optionLayout);
m_productsAndSuppliers = new ProductsAndSuppliers;
QVBoxLayout* tmpLayout = new QVBoxLayout;
tmpLayout->addWidget(m_groupOption);
tmpLayout->addWidget(m_productsAndSuppliers);
m_signalLight = new SignalLight("/dev/ttyACM0");
tmpLayout->addWidget(m_signalLight);
tmpLayout->addStretch();
m_mainLayout->addLayout(tmpLayout);
connect(m_createVehicle, SIGNAL(clicked()), this, SLOT(createVehicle()));
connect(m_deleteVehicle, SIGNAL(clicked()), this, SLOT(deleteVehicle()));
connect(m_abortWeighting, SIGNAL(clicked()), this, SLOT(abortWeighting()));
connect(new QShortcut(QKeySequence("ESC"), this), SIGNAL(activated()), this, SLOT(abortWeighting()));
}
VehicleManager::~VehicleManager(void)
{
while (!m_vehicles.isEmpty())
{
delete m_vehicles.takeFirst();
}
}
void VehicleManager::addVehicle(Vehicle* vehicle)
{
m_vehicles.push_front(vehicle);
m_vehicleLayout->insertWidget(0, vehicle->button());
connect(vehicle->button(), SIGNAL(pressed()), this, SLOT(startWeighting()));
this->saveToFile("vehicles");
}
void VehicleManager::createVehicle(void)
{
CreateVehicleDialog dialog(this);
dialog.exec();
}
void VehicleManager::removeVehicle(Vehicle* vehicle)
{
m_vehicleLayout->removeWidget(vehicle->button());
disconnect(vehicle->button(), SIGNAL(pressed()), this, SLOT(startWeighting()));
delete vehicle->button();
m_vehicles.removeOne(vehicle);
delete vehicle;
this->saveToFile("vehicles");
}
void VehicleManager::deleteVehicle(void)
{
DeleteVehicleDialog dialog(this);
dialog.exec();
}
void VehicleManager::loadFromFile(const QString& filename)
{
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Fehler beim öffnen der Datei: " << filename;
return;
}
QTextStream in(&file);
while (!in.atEnd())
{
QString line(in.readLine());
QStringList list(line.split(":"));
Vehicle* vehicle = new Vehicle;
vehicle->setName(list.at(0));
vehicle->setNumberOfAxis(list.at(1).toInt());
vehicle->setTara(list.at(2).toInt());
vehicle->setButton(new QPushButton(vehicle->name()));
this->addVehicle(vehicle);
}
file.close();
}
void VehicleManager::saveToFile(const QString& filename)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
qDebug() << "Fehler beim öffnen der Datei: " << filename;
return;
}
QTextStream out(&file);
for (int i = m_vehicles.size() - 1; i >= 0; i--)
{
out << m_vehicles.at(i)->name() << ':';
out << m_vehicles.at(i)->numberOfAxis() << ':';
out << m_vehicles.at(i)->tara() << '\n';
}
file.close();
}
void VehicleManager::startWeighting(void)
{
for (int i = 0; i < m_vehicles.size(); i++)
{
if (m_vehicles.at(i)->button()->isDown())
{
m_abortWeighting->setEnabled(true);
QString product, supplier;
if (m_productsAndSuppliers->isChecked())
{
product.append(m_productsAndSuppliers->product());
supplier.append(m_productsAndSuppliers->supplier());
}
m_control->startWeighting(new Weight(m_vehicles.at(i)->name(),
m_vehicles.at(i)->tara(),
m_vehicles.at(i)->numberOfAxis(),
product, supplier));
qDebug() << m_vehicles.at(i)->name() << "is pressed";
}
else
{
m_vehicles.at(i)->button()->setEnabled(false);
}
}
if (m_signalLight->isEnabled())
{
m_signalLight->green();
}
}
void VehicleManager::abortWeighting(void)
{
for (int i = 0; i < m_vehicles.size(); i++)
{
m_vehicles.at(i)->button()->setEnabled(true);
}
m_abortWeighting->setEnabled(false);
m_control->abortWeighting();
if (m_signalLight->isEnabled())
{
m_signalLight->red();
}
}
void VehicleManager::finishWeight(void)
{
for (int i = 0; i < m_vehicles.size(); i++)
{
m_vehicles.at(i)->button()->setEnabled(true);
}
m_abortWeighting->setEnabled(false);
if (m_signalLight->isEnabled())
{
m_signalLight->red();
}
}
DeleteVehicleDialog::DeleteVehicleDialog(VehicleManager* manager, QWidget* parent) : QDialog(parent)
{
this->setWindowTitle("Lösche Fahrzeug");
m_manager = manager;
m_mainLayout = new QVBoxLayout(this);
m_list = new QListWidget;
m_mainLayout->addWidget(m_list);
m_buttonLayout = new QHBoxLayout;
m_delete = new QPushButton("Lösche");
m_close = new QPushButton("Schließen");
m_buttonLayout->addWidget(m_delete);
m_buttonLayout->addWidget(m_close);
m_mainLayout->addLayout(m_buttonLayout);
this->updateList();
connect(m_delete, SIGNAL(clicked()), this, SLOT(deleteVehicle()));
connect(m_close, SIGNAL(clicked()), this, SLOT(accept()));
}
void DeleteVehicleDialog::deleteVehicle(void)
{
if (m_list->currentRow() >= 0 && m_list->currentRow() < m_list->count())
{
m_manager->removeVehicle(m_manager->vehicles().at(m_list->currentRow()));
}
this->updateList();
}
void DeleteVehicleDialog::updateList(void)
{
m_list->clear();
for (int i = 0; i < m_manager->vehicles().size(); i++)
{
m_list->addItem(m_manager->vehicles().at(i)->name());
}
}
ProductsAndSuppliers::ProductsAndSuppliers(QWidget* parent) : QGroupBox("Wiegeschein", parent)
{
m_mainLayout = new QGridLayout(this);
this->setCheckable(true);
m_products = new QComboBox;
m_products->setFont(QFont("system", 20, QFont::Normal));
m_products->setIconSize(QSize(32, 32));
this->loadProductsFromFile();
m_mainLayout->addWidget(m_products, 1, 0);
m_suppliers = new QComboBox;
m_suppliers->setFont(QFont("system", 20, QFont::Normal));
this->loadSuppliersFromFile();
m_suppliers->setIconSize(QSize(32, 32));
m_mainLayout->addWidget(m_suppliers, 1, 1);
m_infoProduct = new QLabel("\nWare:");
m_infoProduct->setFont(QFont("system", 10, QFont::Bold));
m_mainLayout->addWidget(m_infoProduct, 0, 0);
m_infoSupplier = new QLabel("\nLieferant:");
m_infoSupplier->setFont(QFont("system", 10, QFont::Bold));
m_mainLayout->addWidget(m_infoSupplier, 0, 1);
m_editProduct = new QPushButton("editieren");
m_mainLayout->addWidget(m_editProduct, 2, 0);
m_editSupplier = new QPushButton("editieren");
m_mainLayout->addWidget(m_editSupplier, 2, 1);
this->connect(m_editSupplier, SIGNAL(clicked()), this, SLOT(editSupplier()));
this->connect(m_editProduct, SIGNAL(clicked()), this, SLOT(editProducts()));
}
void ProductsAndSuppliers::loadProductsFromFile(void)
{
QFile file("products");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Kann die Datei " << file.fileName() << " nicht öffnen.";
return;
}
QTextStream in(&file);
m_products->clear();
while (!in.atEnd())
{
QString line(in.readLine());
QStringList list(line.split(":"));
m_products->insertItem(0, list.at(0));
m_products->setItemIcon(0, QIcon(QString("picture/").append(list.at(1))));
}
}
void ProductsAndSuppliers::loadSuppliersFromFile(void)
{
QFile file("suppliers");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Kann die Datei " << file.fileName() << " nicht öffnen.";
return;
}
QTextStream in(&file);
m_suppliers->clear();
while (!in.atEnd())
{
QString line(in.readLine());
QStringList list(line.split(":"));
m_suppliers->insertItem(0, list.at(0));
m_suppliers->setItemIcon(0, QIcon(QString("picture/").append(list.at(1))));
}
}
void ProductsAndSuppliers::editSupplier(void)
{
SupplierDialog dialog("suppliers");
dialog.exec();
this->loadSuppliersFromFile();
}
void ProductsAndSuppliers::editProducts(void)
{
ProductDialog dialog("products");
dialog.exec();
this->loadProductsFromFile();
}
| true |
4fcc0b5c83c811a94b73b143f6f7ad45acbece20 | C++ | Sergiara/APractica | /examineSimilarItems/src/motor.cpp | UTF-8 | 1,071 | 2.890625 | 3 | [] | no_license | #include "motor.h"
motor::motor()
{
//ctor
}
motor::~motor()
{
//dtor
}
double motor::jaccard(string fitxer1, string fitxer2, int k){
int num_unio = 0, num_inter = 0;
string conjunt_S;
cargaDatos c(fitxer1);
c.carga_fichero_a_string(conjunt_S);
string conjunt_T;
cargaDatos c2(fitxer2);
c2.carga_fichero_a_string(conjunt_T);
pair<set<string>::iterator, bool> ret;
set<string> m1;
for (int i = 0; i < conjunt_S.length() - (k-1); i++){
string aux = conjunt_S.substr(i, k);
ret = m1.insert(aux);
if (ret.second) num_unio++;
}
set<string> m2;
set<string>::iterator it;
for (int i = 0; i < conjunt_T.length() - (k-1); i++){
string aux = conjunt_T.substr(i, k);
ret = m2.insert(aux);
if (ret.second){
it = m1.find(aux);
if (it != m1.end()) num_inter++;
else num_unio++;
}
}
double res = (double)num_inter / (double)num_unio;
return res;
}
| true |
c5d519ec2720071b3355229bcb3dc6dfc4df61a5 | C++ | Suminsky/redesigningv1 | /redesigningv0/namespace win/FileLogger.h | WINDOWS-1252 | 3,800 | 2.859375 | 3 | [] | no_license | //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/*
created: 2012/07/07
created: 7:7:2012 23:40
filename: c:\Users\Gateway\Documents\Visual Studio 2008\Projects\TestandoGFrameOnly\TestandoGFrameOnly\FileLogger.h
file path: c:\Users\Gateway\Documents\Visual Studio 2008\Projects\TestandoGFrameOnly\TestandoGFrameOnly
file base: FileLogger
file ext: h
author: Giuliano Suminsky (a.k.a. Icebone1000)
purpose: Logger class that logs to file, txt, ascii.
Windows only.
Giuliano Suminsky (a.k.a. Icebone1000) , rights reserved.
*/
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#pragma once
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
namespace win{
class FileLogger{
//100KB
#define SZBUFF_SIZE 10240
#define SZ_TAB "\t"
#define SZ_NEWLINE "\r\n"
#define SZ_ABOVE_FLUSHED "-ABOVE FLUSHED-\r\n"
#define I_ABOVEFLUSHED_LEN 17
//buff size accounting above flushed string
#define I_BUFFSIZE_MINUS_SZABOVEFLUSHED (SZBUFF_SIZE-I_ABOVEFLUSHED_LEN)
private:
HANDLE m_hLogFile;
UINT m_nBuffChars; //remember to always account for SZ_ABOVE_FLUSHED
UINT m_iAvailableSize;
UINT m_nBytesWritten;
OVERLAPPED m_fileOffset; //data need to append to file
UINT m_nMinDigits; //the minimum number of digits to write for numbers, after comma.
UINT m_nFractionalDigits; //the max number of digits after comma
//char m_szBuff[SZBUFF_SIZE];
char * m_szBuff;
//------------------------------------------------------------------------
static UINT CountString( const char* string_p )
{
int counter = 0;
while( string_p[counter] != 0x00 ) ++counter;
return counter;
}
static bool CompareString( const char* string1_p, const char* string2_p)
{
int it = 0;
while( string1_p[it] == string2_p[it] )
{
if( string1_p[it] == 0x00 )
{
return true;
}
else
++it;
}
return false;
}
//------------------------------------------------------------------------
public:
enum E_DATE_DESIGN{
eDAY_MONTH_YEAR_HMS,
eMONTH_DAY_YEAR_HMS
};
//------------------------------------------------------------------------
// ctors
//------------------------------------------------------------------------
FileLogger(const char* szFileName_p);
FileLogger(const E_DATE_DESIGN eDateOrder = eDAY_MONTH_YEAR_HMS);
//------------------------------------------------------------------------
// dctor
//------------------------------------------------------------------------
virtual ~FileLogger();
//------------------------------------------------------------------------
//Sets the max n of digits after comma.
//------------------------------------------------------------------------
void SetDigitsCount( UINT minCount_p = 6, UINT fractionalCount_p = 4){
m_nMinDigits = minCount_p;
m_nFractionalDigits = fractionalCount_p;
}
//-----------------------------------------
// Log Operators:
//-----------------------------------------
FileLogger& operator <<( const char* stringA_p );
FileLogger& operator <<( const double &float_p );//used for float e double
FileLogger& operator<<( const int &int_p );
//------------------------------------------------------------------------
// Forces file writing/buffer cleaning.This is also a helper function used
// by the class to write to the file always it needs
// [-ABOVE FLUSHED-][newline]
//------------------------------------------------------------------------
void FlushToFile();
};
//------------------------------------------------------------------------
// unique logger
//------------------------------------------------------------------------
extern FileLogger& UniqueFileLogger();
} | true |
2b10ef0ae2ac36c13d8133941a69b62e9d17ea05 | C++ | UCLA-CS130/AAAAA | /test/http_response_test.cpp | UTF-8 | 595 | 2.796875 | 3 | [] | no_license | #include "../http_response.h"
#include "gtest/gtest.h"
#include <string>
TEST(ResponseTest, ResponseClassTest) {
Response response;
std::string str_req = "GET /echo HTTP/1.1\r\ntest\r\n\r\n";
response.SetStatus(Response::OK);
response.AddHeader("Content-Length", std::to_string(str_req.size() - 4));
response.AddHeader("Content-Type", "text/plain");
response.SetBody(str_req);
std::string expected_response = response.ToString();
EXPECT_EQ(expected_response, "HTTP/1.1 200 OK\r\nContent-Length: 24\r\nContent-Type: text/plain\r\n\r\nGET /echo HTTP/1.1\r\ntest\r\n\r\n");
}
| true |
1ae43f54f3f24d8181d37a1dffd568713aabf88e | C++ | wlgys8/chaos3d | /src/asset/resource.h | UTF-8 | 690 | 2.78125 | 3 | [] | no_license | #ifndef _RESOURCE_H
#define _RESOURCE_H
// not sure yet, use shared_ptr for now
//#include "common/referenced_count.h"
#include <memory>
/**
* load expensive data from IO i.e. file/network to memory
* keeping the lightweight data
*/
class resource {
public:
typedef std::shared_ptr<resource> ptr;
public:
virtual ~resource() {};
// load the resource from the IO
virtual bool load() = 0;
// unload the resource
virtual bool unload() = 0;
// swap the resource out of the memory
virtual bool offline() = 0;
// reload the resouce
virtual bool is_loaded() = 0;
virtual bool is_loading() = 0;
};
template<class R>
class resource_base : public resource {
};
#endif
| true |
c2d38fafb8e534052a09e3b1f82a452c0430e2ed | C++ | bgirtten/SDLPlayer | /video/video_factory.h | UTF-8 | 334 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include "video/video_frame.h"
namespace VideoPlayer {
class VideoFactory {
public:
virtual ~VideoFactory() {}
// Get one available frame to render from factory.
// Function may block to wait frame or return null.
virtual std::unique_ptr<stream_hub::VideoFrame> GetAvailableFrame() = 0;
};
} | true |
82369fd016ea20f4506db1ae9554ac44209170be | C++ | casfire/life-hs | /src/MovableView.hpp | UTF-8 | 2,877 | 2.53125 | 3 | [] | no_license | /* MovableView v1.1.3 Date: 2012-04-20 */
#pragma once
#ifndef _MOVABLEVIEW_HPP_
#define _MOVABLEVIEW_HPP_
#define _MOVABLEVIEW_VER_ 113
#include "SDL_gfxPrimitives.h"
class MovableView{
float tPosX, tPosY;
float tOffX, tOffY;
float tZoom, tRot;
bool tRevX, tRevY;
Uint8 dragMask, dragMaskOther;
bool eventCanZoom; float eventZoomAmount;
float dragX, dragY, dragOffX, dragOffY;
bool useAA;
public:
MovableView();
bool Event(SDL_Event *event, int posX1 = 0, int posY1 = 0, int posX2 = 0, int posY2 = 0, int offX = 0, int offY = 0);
void SetMiddle(float x, float y);
void SetOff(float offX, float offY);
void SetOffX(float offX);
void SetOffY(float offY);
void SetZoom(float zoom);
void SetRot(float rotation);
void SetUseAA(bool useAntiAliasing);
void SetReverse(bool reverseX = false, bool reverseY = true);
void SetReverseX(bool reverseX = false);
void SetReverseY(bool reverseY = true);
float GetOffX();
float GetOffY();
float GetZoom();
float GetRot();
bool GetUseAA();
bool GetReverseX();
bool GetReverseY();
void SetCanZoom(bool canZoom);
void SetZoomAmount(float amount);
void SetCanDrag(Uint8 SDLButton, bool enable); //set particular SDL_BUTTON to true/false
void SetDragMask(Uint8 SDLButtonMask = SDL_BUTTON(SDL_BUTTON_LEFT)|SDL_BUTTON(SDL_BUTTON_RIGHT)); //set mask of all buttons - 0 to disable
bool GetCanZoom();
bool IsDrag(Uint8 button);
void GetCoords(float x, float y, int *outX, int *outY);
void GetCoords(float x, float y, Sint16 *outX, Sint16 *outY);
void GetRevCoords(int x, int y, float *outX, float *outY);
void pixel(SDL_Surface *dst, float x, float y, Uint32 color);
void line(SDL_Surface *dst, float x1, float y1, float x2, float y2, Uint32 color);
void rectangle(SDL_Surface *dst, float x1, float y1, float x2, float y2, Uint32 color);
void box(SDL_Surface *dst, float x1, float y1, float x2, float y2, Uint32 color);
void circle(SDL_Surface *dst, float x, float y, float rad, Uint32 color);
void filledCircle(SDL_Surface *dst, float x, float y, float rad, Uint32 color);
void ellipse(SDL_Surface *dst, float x, float y, float rx, float ry, Uint32 color);
void arc(SDL_Surface *dst, float x, float y, float rad, float start, float end, Uint32 color); //in radians
void pie(SDL_Surface *dst, float x, float y, float rad, float start, float end, Uint32 color); //in radians
void filledPie(SDL_Surface *dst, float x, float y, float rad, float start, float end, Uint32 color); //in radians
void trigon(SDL_Surface *dst, float x1, float y1, float x2, float y2, float x3, float y3, Uint32 color);
void filledTrigon(SDL_Surface *dst, float x1, float y1, float x2, float y2, float x3, float y3, Uint32 color);
void polygon(SDL_Surface *dst, const float *vx, const float *vy, int n, Uint32 color);
void filledPolygon(SDL_Surface *dst, const float *vx, const float *vy, int n, Uint32 color);
};
#endif
| true |
7230515ddf3efdf98cabe2d6a4306931da349a9d | C++ | danAllmann/wgtf | /src/core/lib/core_serialization/i_datastream.cpp | UTF-8 | 2,089 | 2.78125 | 3 | [] | no_license | #include "i_datastream.hpp"
// TODO: this whole file contains deprecated content; non-deprecated interface should be pure virtual
namespace wgt
{
IDataStream::~IDataStream()
{
}
std::streamsize IDataStream::read( void* destination, std::streamsize size )
{
// warning: infinite recursion will happen if neither read or readRaw was overriden
return readRaw( destination, static_cast< size_t >( size ) );
}
std::streamsize IDataStream::write( const void* source, std::streamsize size )
{
// warning: infinite recursion will happen if neither write or writeRaw was overriden
return writeRaw( source, static_cast< size_t >( size ) );
}
size_t IDataStream::pos() const
{
const auto pos = const_cast<IDataStream*>( this )->seek( 0, std::ios_base::cur );
if (pos < 0)
{
return 0;
}
return static_cast< size_t >( pos );
}
size_t IDataStream::size() const
{
IDataStream* s = const_cast<IDataStream*>( this );
const auto pos = s->seek( 0, std::ios_base::cur );
if (pos < 0)
{
return 0;
}
const auto size = s->seek( 0, std::ios_base::end );
s->seek( pos );
return static_cast< size_t >( size );
}
const void * IDataStream::rawBuffer() const
{
return nullptr;
}
size_t IDataStream::readRaw( void * o_Data, size_t length )
{
auto result = read( o_Data, length );
return static_cast< size_t >( result );
}
size_t IDataStream::writeRaw( const void * data, size_t length )
{
auto result = write( data, length );
return static_cast< size_t >( result );
}
bool IDataStream::eof() const
{
IDataStream* s = const_cast<IDataStream*>( this );
const auto pos = s->seek( 0, std::ios_base::cur );
if (pos < 0)
{
return false;
}
const auto size = s->seek( 0, std::ios_base::end );
s->seek( pos );
return pos >= size;
}
bool IDataStream::read( Variant & variant )
{
return readValue( variant );
}
bool IDataStream::write( const Variant & variant )
{
return writeValue( variant );
}
bool IDataStream::writeValue( const Variant & variant )
{
return false;
}
bool IDataStream::readValue( Variant & variant )
{
return false;
}
} // end namespace wgt
| true |
6a06a53666965c32d6c83179d3f6c7ce3871da18 | C++ | jc2324083/CastanedaJustin_46090 | /Labs/Factorial/main.cpp | UTF-8 | 509 | 3.03125 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Justin Castaneda
*
* Created on July 2, 2015, 12:10 PM
*/
//System Libraires
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
//User Libraries
//Global Constant
//Function Prototypes
//Execution!!
int main(int argc, char** argv) {
float fact=1;
unsigned n=6;
//Loop and find the n!
for(int i=1;i<=n;i++){
fact*=i;
}
//Output the result
cout<<static_cast<int>(n)<<"!="<<fact<<endl;
return 0;
}
| true |
c345f1090a090f94f3bcc33d64354d67d8c70015 | C++ | paswd/os-lab2 | /handler.cpp | UTF-8 | 563 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
string str = "";
bool lspace = false;
for (size_t i = 0; argv[0][i] != '\0'; i++) {
if (argv[0][i] == ' ' && lspace) {
continue;
}
str += argv[0][i];
if (argv[0][i] == ' ') {
lspace = true;
} else {
lspace = false;
}
}
string filename = "";
for (size_t i = 0; argv[1][i] != '\0'; i++) {
filename += argv[1][i];
}
ofstream out(filename.c_str());
out << str << endl;
out.close();
return 0;
}
| true |
0f0e0cd47dd3e5965e7b849b10527fba734de2be | C++ | psallandre/IVRM | /MarketDataAdapters/include/Activ 1.7.1.0/ActivMiddleware/ActivFieldTypes/Date.h | UTF-8 | 30,992 | 2.828125 | 3 | [] | no_license | /**
* @file Date.h
*
* @brief Header file for the date class.
*
* $Log: $
*/
#if !defined (ACTIV_DATE_H)
#define ACTIV_DATE_H
#include "ActivMiddleware/ActivFieldTypes/External.h"
#include "ActivMiddleware/ActivFieldTypes/IFieldType.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include <ctime>
namespace Activ
{
/**
* @brief The day list.
*/
#define ACTIV_DAY_LIST(d) \
d(SUNDAY, "Sunday") \
d(MONDAY, "Monday") \
d(TUESDAY, "Tuesday") \
d(WEDNESDAY, "Wednesday") \
d(THURSDAY, "Thursday") \
d(FRIDAY, "Friday") \
d(SATURDAY, "Saturday")
/**
* @brief The month list.
*/
#define ACTIV_MONTH_LIST(d) \
d(UNDEFINED, "Undefined") \
d(JANUARY, "January") \
d(FEBRUARY, "February") \
d(MARCH, "March") \
d(APRIL, "April") \
d(MAY, "May") \
d(JUNE, "June") \
d(JULY, "July") \
d(AUGUST, "August") \
d(SEPTEMBER, "September") \
d(OCTOBER, "October") \
d(NOVEMBER, "November") \
d(DECEMBER, "December")
class MessageBuilder;
class MessageValidator;
/**
* @brief Date class.
*/
class Date : public IFieldType
{
public:
static const FieldType FIELD_TYPE = FIELD_TYPE_DATE; ///< The field type.
static const uint32_t MONTHS_PER_YEAR = 12; ///< The number of months in an year.
static const uint32_t DAYS_PER_WEEK = 7; ///< The number of days in a week.
static const uint32_t DAYS_PER_MONTH = 31; ///< The number of days in a month.
using IFieldType::FromString;
using IFieldType::Serialize;
using IFieldType::SerializeBody;
using IFieldType::SerializeLengthAndBody;
using IFieldType::Deserialize;
using IFieldType::DeserializeBody;
using IFieldType::DeserializeLengthAndBody;
/**
* @brief Day enumeration.
*/
enum
{
ACTIV_DAY_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_DAYS
};
/**
* @brief Month enumeration.
*/
enum
{
ACTIV_MONTH_LIST(ACTIV_DECLARE_ELEMENT_1_WITH_COMMA)
NUM_MONTHS
};
/**
* @brief Default constructor.
*/
Date();
/**
* @brief Constructor.
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @throw StatusCodeException
*/
Date(const uint32_t year, const uint32_t month, const uint32_t day);
/**
* @brief Constructor.
*
* @param julianDate the julian date.
*
* @throw StatusCodeException
*/
Date(const int32_t julianDate);
/**
* @brief Constructor.
*
* Uses the tm_year, tm_mon and tm_mday fields of the provided tm structure.
*
* @param tm reference to a tm structure specifying the date.
*
* @throw StatusCodeException
*/
Date(const std::tm &tm);
/**
* @brief Destructor.
*/
virtual ~Date();
/**
* @brief Equality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator==(const Date &rhs) const;
/**
* @brief Inequality operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator!=(const Date &rhs) const;
/**
* @brief Less than operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator<(const Date &rhs) const;
/**
* @brief Less than or equal to operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator<=(const Date &rhs) const;
/**
* @brief Greater than operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator>(const Date &rhs) const;
/**
* @brief Greater than or equal to operator.
*
* @param rhs the object to compare with.
*
* @return the result of the test.
*
* @throw StatusCodeException
*/
bool operator>=(const Date &rhs) const;
/**
* @brief Prefix increment operator.
*
* @return Reference to the updated object.
*
* @throw StatusCodeException
*/
Date &operator++();
/**
* @brief Postfix increment operator.
*
* @return Copy of the original object.
*
* @throw StatusCodeException
*/
const Date operator++(int);
/**
* @brief Addition operator.
*
* @param nDays the number of days to add to this object.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
const Date operator+(const int32_t nDays) const;
/**
* @brief Addition assignment operator.
*
* @param nDays the number of days to add to this object.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
Date& operator+=(const int32_t nDays);
/**
* @brief Prefix decrement operator.
*
* @return Reference to the updated object.
*
* @throw StatusCodeException
*/
Date &operator--();
/**
* @brief Postfix decrement operator.
*
* @return Copy of the original object.
*
* @throw StatusCodeException
*/
const Date operator--(int);
/**
* @brief Subtraction operator.
*
* @param nDays the number of days to subtract from this object.
*
* @return an object containing the result of the operation.
*
* @throw StatusCodeException
*/
const Date operator-(const int32_t nDays) const;
/**
* @brief Subtraction assignment operator.
*
* @param nDays the number of days to subtract from this object.
*
* @return a reference to this object.
*
* @throw StatusCodeException
*/
Date& operator-=(const int32_t nDays);
/**
* @brief Store a new date.
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const uint32_t year, const uint32_t month, const uint32_t day);
/**
* @brief Store a new date.
*
* @param julianDate the julian date.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const int32_t julianDate);
/**
* @brief Store a new date.
*
* Uses the tm_year, tm_mon and tm_mday fields of the provided tm structure.
*
* @param tm reference to a tm structure specifying the date.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
StatusCode Set(const std::tm &tm);
/**
* @brief Get the date.
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(uint32_t &year, uint32_t &month, uint32_t &day) const;
/**
* @brief Get the julian date.
*
* @return the julian date.
*
* @throw StatusCodeException
*/
int32_t Get() const;
/**
* @brief Get the date.
*
* Only sets the tm_year, tm_mon and tm_mday fields of the provided tm structure.
*
* @param tm reference to a tm structure to receive the date.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_INITIALIZED
*/
StatusCode Get(std::tm &tm) const;
/**
* @brief Get the year.
*
* @return the year.
*
* @throw StatusCodeException
*/
uint32_t GetYear() const;
/**
* @brief Get the month.
*
* @return the month.
*
* @throw StatusCodeException
*/
uint32_t GetMonth() const;
/**
* @brief Get the day.
*
* @return the day.
*
* @throw StatusCodeException
*/
uint32_t GetDay() const;
/**
* @brief Get the day of the week.
*
* @return the day of the week.
*
* @throw StatusCodeException
*/
uint32_t GetDayOfWeek() const;
/**
* @brief Get the day of the year.
*
* @return the day of the year.
*
* @throw StatusCodeException
*/
uint32_t GetDayOfYear() const;
/**
* @brief Get the week of the year.
*
* @return the week of the year.
*
* @throw StatusCodeException
*/
uint32_t GetWeekOfYear() const;
/**
* @brief Add days.
*
* @param nDays the number of days to add to this object.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_INITIALIZED
*/
ACTIV_FIELD_TYPES_API StatusCode AddDays(const int32_t nDays);
/**
* @brief Subtract days.
*
* @param nDays the number of days to subtract from this object.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_INITIALIZED
*/
ACTIV_FIELD_TYPES_API StatusCode SubtractDays(const int32_t nDays);
/**
* @brief Reset the object.
*/
virtual void Reset();
/**
* @brief Clear the object.
*/
virtual void Clear();
/**
* @brief Compare.
*
* @param rhs the object to compare with.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
*/
ACTIV_FIELD_TYPES_API StatusCode Compare(const Date &rhs, int &result) const;
/**
* @brief Compare.
*
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode Compare(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result) const;
/**
* @brief Convert another IFieldType object to this type.
*
* @param pIFieldType the value to convert from.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode Convert(const IFieldType * const pIFieldType);
/**
* @brief Convert the object to a string.
*
* @return the object as a string.
*/
ACTIV_FIELD_TYPES_API virtual std::string ToString() const;
/**
* @brief Convert the object from a string.
*
* @param messageValidator the message validator.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_LENGTH
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode FromString(MessageValidator &messageValidator);
/**
* @brief Serialize the object into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode Serialize(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength) const;
/**
* @brief Serialize the object's body into the supplied data buffer.
*
* @param pSerializedBody the buffer to store a serialized version of the object's body in.
* @param maxSerializedBodyLength the maximum serialized body length.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode SerializeBody(void *pSerializedBody, const size_t maxSerializedBodyLength, size_t &serializedBodyLength) const;
/**
* @brief Serialize the object's length and body into the supplied message builder.
*
* @param messageBuilder the message builder to store a serialized version of the object in.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval STATUS_CODE_NOT_INITIALIZED
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode SerializeLengthAndBody(MessageBuilder &messageBuilder, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED) const;
/**
* @brief Deserialize the object from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode Deserialize(MessageValidator &messageValidator, const size_t maxSerializedBodyLength);
/**
* @brief Deserialize the object's body from the supplied data buffer.
*
* @param pSerializedBody the buffer from which the object's body will be extracted.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode DeserializeBody(const void * const pSerializedBody, const size_t serializedBodyLength);
/**
* @brief Deserialize the object's length and body from the supplied message validator.
*
* @param messageValidator the message validator from which the object will be extracted.
* @param maxSerializedBodyLength the maximum serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode DeserializeLengthAndBody(MessageValidator &messageValidator, const size_t maxSerializedBodyLength = MAX_SERIALIZED_BODY_LENGTH_UNDEFINED);
/**
* @brief Get the serialized length of the object.
*
* @return the serialized length of the object.
*/
virtual size_t GetSerializedLength() const;
/**
* @brief Get the serialized length of the object's body.
*
* @return the serialized length of the object's body.
*/
virtual size_t GetSerializedBodyLength() const;
/**
* @brief Is different.
*
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param isDifferent indicates whether the two objects are different.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FIELD_TYPES_API virtual StatusCode IsDifferent(const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, bool &isDifferent) const;
/**
* @brief Get the maximum serialized length of the object.
*
* @return the maximum serialized length of the object.
*/
static size_t GetMaxSerializedLength();
/**
* @brief Get the maximum serialized length of the object's body.
*
* @return the maximum serialized length of the object's body.
*/
static size_t GetMaxSerializedBodyLength();
/**
* @brief Compare two objects serialized bodies.
*
* @param pLhsSerializedBody the buffer containing the lhs serialized version of the object's body in.
* @param lhsSerializedBodyLength the lhs serialized body length.
* @param pRhsSerializedBody the buffer containing the rhs serialized version of the object's body in.
* @param rhsSerializedBodyLength the rhs serialized body length.
* @param result the result of the comparison.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
ACTIV_FIELD_TYPES_API static StatusCode Compare(const void * const pLhsSerializedBody, const size_t lhsSerializedBodyLength, const void * const pRhsSerializedBody, const size_t rhsSerializedBodyLength, int &result);
/**
* @brief Get the number of days in a month.
*
* @param year the year.
* @param month the month.
*
* @return the number of days in the month.
*/
ACTIV_FIELD_TYPES_API static uint32_t GetDaysInMonth(const uint32_t year, const uint32_t month);
/**
* @brief Get the day of the week.
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @return the day of the week (Sunday = 0, Monday = 1, ..., Saturday = 6).
*/
ACTIV_FIELD_TYPES_API static uint32_t GetDayOfWeek(const uint32_t year, const uint32_t month, const uint32_t day);
/**
* @brief Get the day of the year.
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @return the day of the year (Jan 1st = 1, Jan 2nd = 2, ..., Dec 31st = 365).
*/
ACTIV_FIELD_TYPES_API static uint32_t GetDayOfYear(const uint32_t year, const uint32_t month, const uint32_t day);
/**
* @brief Get the week of the year.
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @return the week of the year (the week containing January 4th = 1)
*/
ACTIV_FIELD_TYPES_API static uint32_t GetWeekOfYear(const uint32_t year, const uint32_t month, const uint32_t day);
/**
* @brief Is the year a leap year.
*
* @param year the year.
*
* @return whether the year is a leap year.
*/
ACTIV_FIELD_TYPES_API static bool IsLeapYear(const uint32_t year);
/**
* @brief Create an object intitialized with the current UTC date.
*
* @return the initialized object.
*/
ACTIV_FIELD_TYPES_API static Date CreateUtcDate();
/**
* @brief Create an object intitialized with the current local date.
*
* @return the initialized object.
*/
ACTIV_FIELD_TYPES_API static Date CreateLocalDate();
/**
* @brief Convert julian to gregorian date.
*
* Algorithm only valid for non-negative julian date number (gregorian date on or after -4713/11/24).
*
* @param julianDate the julian date.
* @param year the year.
* @param month the month.
* @param day the day.
*/
ACTIV_FIELD_TYPES_API static void ConvertJulianToGregorianDate(const int32_t julianDate, int32_t &year, int32_t &month, int32_t &day);
/**
* @brief Convert gregorian to julian date.
*
* Algorithm only valid for non-negative julian date number (gregorian date on or after -4713/11/24).
*
* @param year the year.
* @param month the month.
* @param day the day.
*
* @return the julian date.
*/
ACTIV_FIELD_TYPES_API static int32_t ConvertGregorianToJulianDate(const int32_t year, const int32_t month, const int32_t day);
/**
* @brief Convert the day of the week to a string.
*
* @param dayOfWeek the day of the week to convert.
*
* @return the day of the week as a string.
*/
ACTIV_FIELD_TYPES_API static std::string DayOfWeekToString(const uint32_t dayOfWeek);
/**
* @brief Convert the month to a string.
*
* @param month the month to convert.
*
* @return the month as a string.
*/
ACTIV_FIELD_TYPES_API static std::string MonthToString(const uint32_t month);
/**
* @brief Validate the serialized length and body.
*
* @param messageValidator the message validator.
* @param serializedBodyOffset the serialized body offset.
* @param serializedBodyLength the serialized body length.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_FIELD_TYPES_API static StatusCode ValidateSerializedLengthAndBody(MessageValidator &messageValidator, size_t &serializedBodyOffset, size_t &serializedBodyLength);
/**
* @brief Is valid serialized body length.
*
* @param serializedBodyLength the serialized body length.
*
* @return whether the serialized body length is valid.
*/
static bool IsValidSerializedBodyLength(const size_t serializedBodyLength);
private:
static const size_t DAY_OFFSET = 0; ///< The day offset.
static const size_t DAY_LENGTH = 5; ///< The day length.
static const size_t MONTH_OFFSET = (DAY_OFFSET + DAY_LENGTH); ///< The month offset.
static const size_t MONTH_LENGTH = 4; ///< The month length.
static const size_t YEAR_OFFSET = (MONTH_OFFSET + MONTH_LENGTH); ///< The year offset.
static const size_t YEAR_LENGTH = 15; ///< The year length.
static const size_t MAX_OFFSET = (YEAR_OFFSET + YEAR_LENGTH); ///< The maximum offset.
static const size_t MAX_DAY = ((1 << DAY_LENGTH) - 1); ///< The maximum day.
static const size_t MAX_MONTH = ((1 << MONTH_LENGTH) - 1); ///< The maximum month.
static const size_t MAX_YEAR = ((1 << YEAR_LENGTH) - 1); ///< The maximum year.
/**
* @brief Get an unsigned 32 bit value.
*
* @param pData pointer to the data.
* @param size the size of the data.
* @param value the value to be copied to.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_INVALID_PARAMETER
*/
static StatusCode GetUnsignedInt32(const void * const pData, const size_t size, uint32_t &value);
uint32_t m_year; ///< The year.
uint8_t m_month; ///< The month.
uint8_t m_day; ///< The day.
friend class DateTime;
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date::Date() :
IFieldType(FIELD_TYPE)
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date::Date(const uint32_t year, const uint32_t month, const uint32_t day) :
IFieldType(FIELD_TYPE)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(year, month, day));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date::Date(const int32_t julianDate) :
IFieldType(FIELD_TYPE)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(julianDate));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date::Date(const std::tm &tm) :
IFieldType(FIELD_TYPE)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Set(tm));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date::~Date()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::operator==(const Date &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (0 == result);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::operator!=(const Date &rhs) const
{
return !((*this) == rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::operator<(const Date &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (result < 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::operator<=(const Date &rhs) const
{
return !((*this) > rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::operator>(const Date &rhs) const
{
int result;
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, Compare(rhs, result));
return (result > 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::operator>=(const Date &rhs) const
{
return !((*this) < rhs);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date &Date::operator++()
{
return (*this) += 1;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Date Date::operator++(int)
{
const Date oldValue = *this;
++(*this);
return oldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Date Date::operator+(const int32_t nDays) const
{
return Date(*this) += nDays;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date& Date::operator+=(const int32_t nDays)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, AddDays(nDays));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date &Date::operator--()
{
return (*this) -= 1;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Date Date::operator--(int)
{
const Date oldValue = *this;
--(*this);
return oldValue;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const Date Date::operator-(const int32_t nDays) const
{
return Date(*this) -= nDays;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline Date& Date::operator-=(const int32_t nDays)
{
ACTIV_THROW_RESULT_IF(STATUS_CODE_SUCCESS, !=, SubtractDays(nDays));
return (*this);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Date::Set(const uint32_t year, const uint32_t month, const uint32_t day)
{
if ((year > MAX_YEAR) || (month < 1) || (month > MONTHS_PER_YEAR) || (day > GetDaysInMonth(year, month)))
return STATUS_CODE_INVALID_PARAMETER;
m_year = static_cast<uint32_t>(year);
m_month = static_cast<uint8_t>(month);
m_day = static_cast<uint8_t>(day);
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Date::Set(const int32_t julianDate)
{
int32_t year, month, day;
ConvertJulianToGregorianDate(julianDate, year, month, day);
if ((year < 0) || (year > static_cast<int32_t>(MAX_YEAR)) || (month < 1) || (month > static_cast<int32_t>(MONTHS_PER_YEAR)) || (day < 1) || (static_cast<uint32_t>(day) > GetDaysInMonth(static_cast<uint32_t>(year), static_cast<uint32_t>(month))))
return STATUS_CODE_INVALID_PARAMETER;
m_year = static_cast<uint32_t>(year);
m_month = static_cast<uint8_t>(month);
m_day = static_cast<uint8_t>(day);
m_isInitialized = true;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Date::Set(const std::tm &tm)
{
return Set(static_cast<uint32_t>(tm.tm_year + 1900), static_cast<uint32_t>(tm.tm_mon + 1), static_cast<uint32_t>(tm.tm_mday));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Date::Get(uint32_t &year, uint32_t &month, uint32_t &day) const
{
if (!IsInitialized())
return STATUS_CODE_NOT_INITIALIZED;
year = m_year;
month = m_month;
day = m_day;
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline int32_t Date::Get() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return ConvertGregorianToJulianDate(m_year, m_month, m_day);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline StatusCode Date::Get(std::tm &tm) const
{
if (!IsInitialized())
return STATUS_CODE_NOT_INITIALIZED;
tm.tm_year = static_cast<int>(m_year - 1900);
tm.tm_mon = static_cast<int>(m_month - 1);
tm.tm_mday = static_cast<int>(m_day);
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t Date::GetYear() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return static_cast<uint32_t>(m_year);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t Date::GetMonth() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return static_cast<uint32_t>(m_month);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t Date::GetDay() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return static_cast<uint32_t>(m_day);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t Date::GetDayOfWeek() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return GetDayOfWeek(m_year, m_month, m_day);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t Date::GetDayOfYear() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return GetDayOfYear(m_year, m_month, m_day);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline uint32_t Date::GetWeekOfYear() const
{
if (!IsInitialized())
ACTIV_THROW(StatusCodeException, STATUS_CODE_NOT_INITIALIZED);
return GetWeekOfYear(m_year, m_month, m_day);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Date::Reset()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void Date::Clear()
{
m_isInitialized = false;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Date::GetSerializedLength() const
{
return (IsInitialized() ? GetMaxSerializedLength() : 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Date::GetSerializedBodyLength() const
{
return (IsInitialized() ? GetMaxSerializedBodyLength() : 0);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Date::GetMaxSerializedLength()
{
return GetMaxSerializedBodyLength();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t Date::GetMaxSerializedBodyLength()
{
return (((MAX_OFFSET - 1) / CHAR_BIT) + 1);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool Date::IsValidSerializedBodyLength(const size_t serializedBodyLength)
{
return (GetMaxSerializedBodyLength() == serializedBodyLength);
}
} // namespace Activ
#endif // !defined (ACTIV_DATE_H)
| true |
aa2985a15272c63f6b54d6cf464abf5f6d614f16 | C++ | MysteriousBox/Renderer | /Renderer/Vector2.h | UTF-8 | 351 | 2.75 | 3 | [] | no_license | #ifndef _Vector2
#define _Vector2
#include "Vector.h"
class Vector2 :public Vector
{
public:
double value[2];//value[0]表示X,value[1]表示Y,value[2]表示Z,value[3]表示W
Vector2(double x, double y);
static double dot(Vector2& a, Vector2& b);
virtual double Mod();
virtual void Normalize();//单位化
~Vector2();
};
#endif // !_Vector2
| true |
0eb78ee74e5b0ba18705f10b40af2b6747abdc30 | C++ | alexandre-macedo/ecole-polytechnique | /PSC/merged/interface/interfacepsc.cpp | UTF-8 | 1,612 | 2.59375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "interfacepsc.h"
#include "ui_interfacepsc.h"
#include <QDialog>
#include <QTableWidgetItem>
#include <QTableWidget>
#include <iostream>
InterfacePSC::InterfacePSC(QWidget *parent, std::vector<std::string> v) :
QMainWindow(parent),
ui(new Ui::InterfacePSC)
{
//int* valores[2];
//QStringList titulos;
//std::vector<std::string> vetor;
ui->setupUi(this);
this->vetor = v;
//ui->myTable->setColumnCount(1);
//titulos << "Value";
//ui->myTable->setHorizontalHeaderLabels(titulos);
// Latitude
ui->myTable->setItem(-1, 1, new QTableWidgetItem( vetor.at(0).c_str() )); // "latitude"
// Longitude
ui->myTable->setItem(0, 1, new QTableWidgetItem( vetor.at(1).c_str() )); // "longitude"
// Compass
ui->myTable->setItem(1, 1, new QTableWidgetItem( vetor.at(2).c_str() )); // // "compass"
// Temperature
ui->myTable->setItem(2, 1, new QTableWidgetItem( vetor.at(3).c_str() )); // "temperature"
// Acceleration
ui->myTable->setItem(3, 1, new QTableWidgetItem( vetor.at(4).c_str() )); // "acceleration"
//std::cout << "primeira posicao: " << vetor.at(0)<< std::endl;
}
InterfacePSC::~InterfacePSC()
{
delete ui;
}
//void InterfacePSC::setValues(std::vector<std::string> v){
// this->vetor = v;
//}
void InterfacePSC::on_quitButton_clicked()
{
delete this;
}
/*
void InterfacePSC::saveDataIntoTable(std::string GPS)
{
if (!myTable)
return;
const int currentRow = myTable->rowCount();
myTable->setRowCount(currentRow + 1);
myTable->setItem(currentRow, 1, new QTableWidgetItem(GPS));
}
*/
| true |