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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
81e18feb3dde1704d4d6784c5605f7e8e91c5dac | C++ | lgbutad/p1 | /practica_1/Drop.cpp | UTF-8 | 398 | 2.5625 | 3 | [] | no_license | #include "stdafx.h"
#include "constants.h"
#include "Drop.h"
CDrop::CDrop(int pos) {
m_status = 0;
m_pos = pos;
}
int CDrop::GetStatus() const {
return m_status;
}
int CDrop::GetPos() const {
return m_pos;
}
char CDrop::GetSymbol() const {
return s_drop_status[m_status];
}
void CDrop::NextStatus() {
m_status++;
}
const char CDrop::s_drop_status[] = { SYMBOL_RAIN_1, SYMBOL_RAIN_2 };
| true |
fb5e343e0b9b47927f396377a835674f63b26db5 | C++ | Bryandevx/basicAlgorithms | /insertionSort.cpp | UTF-8 | 679 | 3.78125 | 4 | [] | no_license | #include<iostream>
using namespace std;
void insertionSort(int array[], int n){
for(int i=1; i < n; i++){
int possibleMin = array[i];
int j = i - 1;
while(j >= 0 && array[j] > possibleMin){
array[j+1] = array[j];
j = j - 1; // switching pos while finding if some array pos contains less than possibleMin
}
array[j+1] = possibleMin; // if nothings happens it will put the number in the same initial position
}
for(int i=0; i < n; i++){
cout << array[i] << " ";
}
}
int main(){
int array[7];
array[0] = 5;
array[1] = 1;
array[2] = 8;
array[3] = 9;
array[4] = 44;
array[5] = 22;
array[6] = 12;
insertionSort(array, 7);
return 0;
}
| true |
4cfe4836eca90aebaf5666e44df1e354f4aba664 | C++ | sizzle0121/leetcode | /Top 100 Liked Questions/p41-first missing positive.cpp | UTF-8 | 2,769 | 3.859375 | 4 | [] | no_license | /*
* Brute-force:
* Starting from i=1 and search for i in the array
* Time complexity: O(n^2)
* Space complexity: O(1)
*
* Sort:
* Sort the array and search for 1, 2, ...
* Time complexity: O(nlogn)
* Space complexity: O(1)
*
* Using extra memory:
* Scan the array once to mark all positive numbers existing in the array, and store the record in a table\
* then find 1, 2, ... from the table, if not found -> return
* Time complexity: O(n)
* Space complexity: O(n)
*
*
* Optimal Solution:
* The main idea is to place all positive numbers into their correct position\
* correct position: the index of the position matches the number itself
* Iterate through the array, if the current number doesn't match current index, place it to its correct position\
* Before placing it, we should first temporarily store the number in the correct position\
* After placing it, we should go to the correct position of the number we temporarily stored and repeat the above process\
* until the number in the correct position <= 0 or > nums.size() or already matches the index
*
* After placing all positive numbers in the array to their correct positions, we can simply scan through the array and see\
* if the index matches the number in the position, if not, then return the index
*
* Time complexity: O(n)
* Space complexity: O(1)
*
* */
#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
using namespace std;
int NaiveSolution(vector<int> &nums){
if(nums.empty()) return 1;
unordered_set<int> exist;
for(auto &num: nums)
if(num > 0)
exist.insert(num);
int n = 1;
while(1){
if(exist.find(n) == exist.end()) break;
n++;
}
return n;
}
int Solution(vector<int> &nums){//time complexity: O(n), space complexity: O(1)
if(nums.empty()) return 1;
int N = nums.size();
nums.push_back(-1);
for(int i=0; i<N; i++){
if(nums[i] > 0 && nums[i] <= N && nums[i] != i){
int ii = nums[i];
while(1){
if(nums[ii] > 0 && nums[ii] < nums.size() && nums[ii] != ii){
int tmp = nums[ii];
nums[ii] = ii;
ii = tmp;
}else{
nums[ii] = ii;
break;
}
}
}
}
for(int i=1; i<=N; i++){
//cout << i << ": " << nums[i] << endl;
if(nums[i] != i)
return i;
}
return N+1;
}
int Solution2(vector<int> &nums){//by swap, same time/space complexity
if(nums.empty()) return 1;
int N = nums.size();
for(int i=0; i<N; i++){
while(nums[i] > 0 && nums[i] <= N && nums[nums[i]-1] != nums[i])
swap(nums[i], nums[nums[i]-1]);
}
for(int i=0; i<N; i++)
if(nums[i] != i+1)
return i+1;
return N+1;
}
int main(){
int T;
cin >> T;
vector<int> nums(T);
for(auto &num: nums)
cin >> num;
cout << NaiveSolution(nums) << endl;
cout << Solution(nums) << endl;
}
| true |
650f242281fc01b570ea14143afcabbd302b4043 | C++ | ElectrodeYT/AlphaServer | /AlphaServer/ChunkManager.cpp | UTF-8 | 1,073 | 2.953125 | 3 | [] | no_license | #include "ChunkManager.h"
Chunk& ChunkManager::GetChunk(int x, int y, bool mark) {
// Try and find chunk
for (int i = 0; i < chunks.size(); i++) {
if (chunks[i].x == x && chunks[i].y == y) {
if (mark) { chunks[i].chunk_is_loaded_by_players = true; }
return chunks[i];
}
}
// Chunk not found, make new one
Chunk new_chunk(x, y);
new_chunk.Generate();
if (mark) { new_chunk.chunk_is_loaded_by_players = true; }
chunks.push_back(new_chunk);
return chunks[chunks.size() - 1];
}
void ChunkManager::MarkAllAsNotLoadedByClients() {
for (int i = 0; i < chunks.size(); i++) {
chunks[i].chunk_is_loaded_by_players = false;
}
}
void ChunkManager::RemoveAllNotMarkedChunks() {
for (int i = 0; i < chunks.size(); i++) {
if (!chunks[i].chunk_is_loaded_by_players) { chunks[i].Unload(); }
}
}
int ChunkManager::GetBlock(Vec3i block) {
int chunk_x = block.x / 16;
int chunk_y = block.z / 16;
Chunk& chunk = GetChunk(chunk_x, chunk_y);
int block_x = block.x % 16;
int block_z = block.z % 16;
return chunk.GetBlock(Vec3i(block_x, block.y, block_z));
}
| true |
8ec0b1a5c6a2e685a955024cab0fb209ac92888d | C++ | jordandong/myITint5 | /29_Multiply.cpp | UTF-8 | 1,031 | 3.734375 | 4 | [] | no_license | /*
给定两个字符串表示的整数a和b,计算它们的乘积a*b,结果也用字符串表示。
注意:a和b有可能是负数。对于0,只有一种合法的表示"0","-0"是不合法的。
*/
//返回a*b的结果
string multiply(const string& a, const string& b) {
int n1=a.size();
int n2=b.size();
bool sign = false;
if(a[0]=='-'){
sign=!sign;
}
if(b[0]=='-')
sign=!sign;
int n3=n1+n2;
int num[n3];
memset(num, 0, sizeof(int)*(n3));
for(int i=n1-1; i>=0&&a[i]!='-'; i--){
int carry = 0;
int j;
int t;
for(j=n2-1; j>=0&&b[j]!='-';j--){
t = carry + num[i+j+1] + (a[i]-'0') * (b[j]-'0');
num[i+j+1] = t % 10;
carry = t / 10;
}
num[i+j+1] = carry;
}
string res="";
int i = 0;
while(i<n3-1 && num[i]==0)
i++;
if(sign && num[i]!=0)
res.push_back('-');
while (i<n3)
res.push_back('0' + num[i++]);
return res;
}
| true |
0fd0f83f9d7697d512cd20d8af53074d6354577c | C++ | cachefish/LeetCode | /动规/354_俄罗斯套娃.cpp | UTF-8 | 1,939 | 3.390625 | 3 | [] | no_license | /*
354. 俄罗斯套娃信封问题
给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。
请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。
说明:
不允许旋转信封。
示例:
输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
输出: 3
解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
*/
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes){
if (envelopes.size() <= 1) return envelopes.size();
sort(envelopes.begin(), envelopes.end(), [](const vector<int> &a, const vector<int> &b)
{
if (a[0] == b[0]) return a[1] > b[1];
return a[0] < b[0];
});
int ans = 0;
vector<int> vec(envelopes.size(), INT_MAX);
for (auto &e : envelopes)
{
int low = 0;
int high = envelopes.size() - 1;
while (high > low)
{
int mid = low + (high - low) / 2;
if (vec[mid] >= e[1]) high = mid;
else low = mid + 1;
}
vec[low] = e[1];
ans = max(ans, low);
}
return ans + 1;
}
};
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
//动态规划,一维数组
sort(envelopes.begin(), envelopes.end());
int n = envelopes.size(), total_max = 1;
if(n <= 0) return 0;
vector<int> dp(n + 1);
dp[0] = 1;
for(int i = 1 ; i < n ; i++){
int cur = 0;
for(int j = 0 ; j < i ; j++){
cur = max(cur, (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) ? dp[j] + 1: 1) ;
}
dp[i] = cur;
total_max = max(dp[i] , total_max);
}
return total_max;
}
};
| true |
baccfc6aee93eb0960ea1114f28d81b07d107c19 | C++ | kanhaiyatripathi/cplusplusKP2 | /Mathematics/meanMedianMode.cpp | UTF-8 | 1,128 | 3.40625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
double findMean(int a[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return (double)sum/(double)n;
}
double findMedian(int a[], int n)
{
sort(a, a+n);
if (n % 2 != 0)
return (double)a[n/2];
return (double)(a[(n-1)/2] + a[n/2])/2.0;
}
int findMode(int a[], int n)
{
int mode,freq=0;
map<int,int> mapp;
for(int i=0;i<n;i++)
{
mapp[a[i]]=mapp[a[i]]+1;
}
map<int, int>::iterator it;
for (it = mapp.begin(); it != mapp.end(); it++)
{
if(it->second>freq)
{
freq=it->second;
mode=it->first;
}
}
return mode;
}
int main()
{
int n;
cout<<"Enter the size of array : ";
cin>>n;
int arr[n+1];
cout<<"Enter the numbers : ";
for(int i=0;i<n;i++)
{
int x;
cin>>x;
arr[i]=x;
}
cout << "Mean = " << findMean(arr, n) << endl;
cout << "Median = " << findMedian(arr, n) << endl;
cout << "Mode = " << findMode(arr, n) << endl;
return 0;
} | true |
fc3fddb23bfef55307ffcb005707576930a0bfcd | C++ | radiganm/cli | /src/packages/cli/Cli.cc | UTF-8 | 2,912 | 2.859375 | 3 | [] | no_license | /// Cli.cc
/// Copyright 2017 Mac Radigan
/// All Rights Reserved
#include "packages/cli/Cli.h"
#include <iostream>
#include <iomanip>
#include <cstring>
#include <atomic>
#include <sstream>
#include <cstdlib>
#include <stdexcept>
#ifdef CLI__ENABLE_STACKTRACE
#include <boost/stacktrace.hpp>
#endif
namespace rad::cli {
namespace po = boost::program_options;
using std::cout;
using std::cerr;
using std::endl;
using std::flush;
Cli *theCli = nullptr;
static void interrupt(int signo)
{
theCli->interrupt(signo);
}
void Cli::interrupt(int signo)
{
auto sig = static_cast<Interrupt_Signal>(signo);
const auto ok = signal_fn_(sig);
if (not ok)
{
#ifdef CLI__ENABLE_STACKTRACE
cerr << boost::stacktrace::stacktrace() << endl << flush;
#endif
exit(EXIT_SUCCESS);
}
}
Cli::Cli()
{
/// default interrupt
cli_interrupt_fn_t interrupt_fn = [&](Interrupt_Signal &sig) -> bool {
return true;
};
set_interrupt(interrupt_fn);
}
po::options_description_easy_init Cli::operator()()
{
return set_options();
}
int Cli::count(std::string name)
{
return vm_.count(name.c_str());
}
bool Cli::exists(std::string name)
{
return 0 != vm_.count(name.c_str());
}
const po::variable_value& Cli::operator[](std::string name) const
{
if (not vm_.count(name.c_str()))
throw std::runtime_error("invalid option access");
return vm_[name.c_str()];
}
Cli::~Cli()
{
}
po::options_description_easy_init Cli::set_options()
{
return desc_.add_options()
("help,h", "print this help message")
;
}
void Cli::parse(int argc, char* argv[])
{
argc_ = argc;
argv_ = argv;
po::store(po::parse_command_line(argc, argv, desc_), vm_);
po::notify(vm_);
if(argc_ < 2)
{
cout << desc_ << endl;
exit(EXIT_FAILURE);
}
if(vm_.count("help"))
{
cout << desc_ << endl;
exit(EXIT_SUCCESS);
}
}
void Cli::set_interrupt(cli_interrupt_fn_t &fn)
{
theCli = this;
if(SIG_ERR == signal(SIGINT, ::rad::cli::interrupt)) {
perror("unable to set signal");
throw std::runtime_error("unable to set signal handler");
}
}
std::ostream& operator<<(std::ostream &os, const rad::cli::Cli &o)
{
std::ios::fmtflags flags(os.flags());
for (const auto& it : o.get_options())
{
os << it.first.c_str() << ": ";
auto &value = it.second.value();
if (auto v = boost::any_cast<uint32_t>(&value))
{
os << *v;
}
else if (auto v = boost::any_cast<bool>(&value))
{
os << std::boolalpha << *v;
}
else if (auto v = boost::any_cast<std::string>(&value))
{
os << *v;
}
os << std::endl;
}
os.flags(flags);
return os;
}
} // namespace
using namespace rad::cli;
/// *EOF*
| true |
c0b9a3cc77a0911112393fb7bd296e7ba04422b6 | C++ | standard-software-ru/k-means | /Point.hpp | UTF-8 | 263 | 2.578125 | 3 | [] | no_license | #pragma once
class Point
{
private:
float x;
float y;
int idCluster;
public:
Point(float x, float y, int idCluster = 0);
float getX();
float getY();
void setX(float x);
void setY(float y);
int getIdCluster();
void setIdCluster(int idCluster);
};
| true |
51bd99fe73b489408a7c4806ccf5e068df325648 | C++ | IgorBender/Works | /GLPolygonTest/GpcPolygon.cpp | UTF-8 | 6,573 | 2.8125 | 3 | [] | no_license | #include <GpcPolygon.h>
GpcPolygon::GpcPolygon()
{
m_PolygonPtr = new gpc_polygon;
m_PolygonPtr->num_contours = 0;
m_PolygonPtr->contour = NULL;
m_PolygonPtr->hole = NULL;
}
GpcPolygon::GpcPolygon(uint32_t NumOfVertices, double* Vertices)
{
m_PolygonPtr = new gpc_polygon;
m_PolygonPtr->num_contours = 1;
m_PolygonPtr->contour = (gpc_vertex_list*)malloc(sizeof(gpc_vertex_list));
m_PolygonPtr->contour->num_vertices = NumOfVertices;
m_PolygonPtr->contour->vertex = (gpc_vertex*)malloc(sizeof(gpc_vertex) * NumOfVertices);
uint32_t i, j;
for(i = 0, j= 0; i < NumOfVertices; ++i, ++j)
{
m_PolygonPtr->contour->vertex[i].x = Vertices[j++];
m_PolygonPtr->contour->vertex[i].y = Vertices[j];
}
m_PolygonPtr->hole = (int*)malloc(sizeof(int));
m_PolygonPtr->hole[0] = 0;
}
GpcPolygon::GpcPolygon(uint32_t NumOfVertices, std::pair<double, double>* Vertices)
{
m_PolygonPtr = new gpc_polygon;
m_PolygonPtr->num_contours = 1;
m_PolygonPtr->contour = (gpc_vertex_list*)malloc(sizeof(gpc_vertex_list));
m_PolygonPtr->contour->num_vertices = NumOfVertices;
m_PolygonPtr->contour->vertex = (gpc_vertex*)malloc(sizeof(gpc_vertex) * NumOfVertices);
uint32_t i = 0;
for(i = 0; i < NumOfVertices; ++i)
{
m_PolygonPtr->contour->vertex[i].x = Vertices[i].first;
m_PolygonPtr->contour->vertex[i].y = Vertices[i].second;
}
m_PolygonPtr->hole = (int*)malloc(sizeof(int));
m_PolygonPtr->hole[0] = 0;
}
GpcPolygon::GpcPolygon(const GpcPolygon& Polygon)
{
m_PolygonPtr = new gpc_polygon;
m_PolygonPtr->num_contours = 0;
m_PolygonPtr->contour = NULL;
m_PolygonPtr->hole = NULL;
GpcPolygon EmptyPolygon;
gpc_polygon_clip(GPC_UNION, EmptyPolygon.m_PolygonPtr, const_cast < gpc_polygon* > (Polygon.m_PolygonPtr), m_PolygonPtr);
}
GpcPolygon::GpcPolygon(const gpc_polygon& Polygon)
{
m_PolygonPtr = new gpc_polygon;
m_PolygonPtr->num_contours = 0;
m_PolygonPtr->contour = NULL;
m_PolygonPtr->hole = NULL;
GpcPolygon EmptyPolygon;
gpc_polygon_clip(GPC_UNION, EmptyPolygon.m_PolygonPtr, const_cast < gpc_polygon* > (&Polygon), m_PolygonPtr);
}
GpcPolygon::~GpcPolygon()
{
gpc_free_polygon(m_PolygonPtr);
delete m_PolygonPtr;
}
GpcPolygon& GpcPolygon::operator=(const GpcPolygon& Polygon)
{
GpcPolygon EmptyPolygon;
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_UNION, EmptyPolygon.m_PolygonPtr, const_cast < gpc_polygon* > (Polygon.m_PolygonPtr),
TmpPolygon.m_PolygonPtr);
gpc_free_polygon(m_PolygonPtr);
gpc_polygon_clip(GPC_UNION, EmptyPolygon.m_PolygonPtr, TmpPolygon.m_PolygonPtr, m_PolygonPtr);
return *this;
}
GpcPolygon& GpcPolygon::operator+=(const GpcPolygon& Polygon)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_UNION, m_PolygonPtr, const_cast < gpc_polygon* > (Polygon.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
gpc_free_polygon(m_PolygonPtr);
*this = TmpPolygon;
return *this;
}
GpcPolygon& GpcPolygon::operator-=(const GpcPolygon& Polygon)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_DIFF, m_PolygonPtr, const_cast < gpc_polygon* > (Polygon.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
gpc_free_polygon(m_PolygonPtr);
*this = TmpPolygon;
return *this;
}
GpcPolygon& GpcPolygon::operator&=(const GpcPolygon& Polygon)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_INT, m_PolygonPtr, const_cast < gpc_polygon* > (Polygon.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
gpc_free_polygon(m_PolygonPtr);
*this = TmpPolygon;
return *this;
}
GpcPolygon& GpcPolygon::operator^=(const GpcPolygon& Polygon)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_XOR, m_PolygonPtr, const_cast < gpc_polygon* > (Polygon.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
gpc_free_polygon(m_PolygonPtr);
*this = TmpPolygon;
return *this;
}
GpcPolygon operator+(const GpcPolygon& a, const GpcPolygon& b)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_UNION, a.m_PolygonPtr, const_cast < gpc_polygon* > (b.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
return TmpPolygon;
}
GpcPolygon operator-(const GpcPolygon& a, const GpcPolygon& b)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_DIFF, a.m_PolygonPtr, const_cast < gpc_polygon* > (b.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
return TmpPolygon;
}
GpcPolygon operator&(const GpcPolygon& a, const GpcPolygon& b)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_INT, a.m_PolygonPtr, const_cast < gpc_polygon* > (b.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
return TmpPolygon;
}
GpcPolygon operator^(const GpcPolygon& a, const GpcPolygon& b)
{
GpcPolygon TmpPolygon;
gpc_polygon_clip(GPC_XOR, a.m_PolygonPtr, const_cast < gpc_polygon* > (b.m_PolygonPtr), TmpPolygon.m_PolygonPtr);
return TmpPolygon;
}
std::ostream& operator << (std::ostream& ostr, GpcPolygon& Poly)
{
ostr << "-------------------------------" << std::endl << "Polygon" << std::endl;
ostr << " Contours : " << Poly.getPolyPtr()->num_contours << std::endl;
for(int i = 0; i < Poly.getPolyPtr()->num_contours; ++i)
{
ostr << (Poly.getPolyPtr()->hole[i] ? " Hole " : " Contour ") << i << std::endl;
for(int j = 0; j < Poly.getPolyPtr()->contour[i].num_vertices; ++j)
{
ostr << " Vertex" << j << " : x = " << Poly.getPolyPtr()->contour[i].vertex[j].x << "; y : "
<< Poly.getPolyPtr()->contour[i].vertex[j].y << std::endl;
}
}
ostr << "-------------------------------" << std::endl;
return ostr;
}
GpcTrianglesStrips::GpcTrianglesStrips()
{
m_TristripPtr = new gpc_tristrip;
}
GpcTrianglesStrips::GpcTrianglesStrips(const GpcPolygon& Polygon)
{
m_TristripPtr = new gpc_tristrip;
gpc_polygon_to_tristrip(const_cast < gpc_polygon* > (Polygon.getPolyPtr()), m_TristripPtr);
}
GpcTrianglesStrips::~GpcTrianglesStrips()
{
gpc_free_tristrip(m_TristripPtr);
delete m_TristripPtr;
}
GpcTrianglesStrips& GpcTrianglesStrips::operator=(const GpcPolygon& Polygon)
{
gpc_free_tristrip(m_TristripPtr);
gpc_polygon_to_tristrip(const_cast < gpc_polygon* > (Polygon.getPolyPtr()), m_TristripPtr);
return *this;
}
int GpcTrianglesStrips::getVertex(int StripNum, int VertexNum, gpc_vertex& Vertex)
{
if(0 <= StripNum && StripNum < m_TristripPtr->num_strips && 0 <= VertexNum && VertexNum < m_TristripPtr->strip[StripNum].num_vertices)
Vertex = m_TristripPtr->strip[StripNum].vertex[VertexNum];
return -1;
}
| true |
8ada96da83c6e7950ad869fd922ffa1b7f9d333c | C++ | khabya/Common | /Network2/networknode.cpp | UTF-8 | 2,299 | 2.703125 | 3 | [
"MIT"
] | permissive |
#include "stdafx.h"
#include "networknode.h"
using namespace network2;
cNetworkNode::cNetworkNode(const StrId &name //= "NetNode"
, const bool isPacketLog //= false
)
: cSession(common::GenerateId(), name, isPacketLog)
, m_packetHeader(nullptr)
{
}
cNetworkNode::~cNetworkNode()
{
Close();
SAFE_DELETE(m_packetHeader);
}
void cNetworkNode::RegisterProtocol(iProtocol *protocol)
{
protocol->SetNode(this);
CreatePacketHeader(protocol->m_format);
}
void cNetworkNode::Close()
{
cSession::Close();
}
// Add ProtocolHandler
bool cNetworkNode::AddProtocolHandler(iProtocolHandler *handler)
{
for (auto &p : m_protocolHandlers)
if (p == handler)
return false; // already exist
m_protocolHandlers.push_back(handler);
CreatePacketHeader(handler->m_format);
return true;
}
// Remove ProtocolHandler
bool cNetworkNode::RemoveProtocolHandler(iProtocolHandler *handler)
{
for (auto &p : m_protocolHandlers)
{
if (p == handler)
{
common::removevector(m_protocolHandlers, handler);
return true;
}
}
return false;
}
// return protocolhandlers
vector<iProtocolHandler*>& cNetworkNode::GetProtocolHandlers()
{
return m_protocolHandlers;
}
// return Protocol Packet Header
iPacketHeader* cNetworkNode::GetPacketHeader()
{
return m_packetHeader;
}
// create packet header
bool cNetworkNode::CreatePacketHeader(const ePacketFormat format)
{
if (m_packetHeader)
return true; // already created!
switch (format)
{
case ePacketFormat::BINARY: m_packetHeader = new cPacketHeader(); break;
case ePacketFormat::ASCII: m_packetHeader = new cPacketHeaderAscii(); break;
case ePacketFormat::JSON: m_packetHeader = new cPacketHeaderJson(); break;
case ePacketFormat::FREE: m_packetHeader = new cPacketHeaderNoFormat(); break;
default: return false; // error type
}
return true;
}
// default send
int cNetworkNode::SendPacket(const SOCKET sock, const cPacket &packet)
{
const int result = send(sock, (const char*)packet.m_data, packet.GetPacketSize(), 0);
return result;
}
// default sendto
int cNetworkNode::SendToPacket(const SOCKET sock, const sockaddr_in &sockAddr
, const cPacket &packet)
{
const int result = sendto(sock, (const char*)packet.m_data, packet.GetPacketSize()
, 0, (struct sockaddr*) &sockAddr, sizeof(sockAddr));
return result;
}
| true |
bd7a5ef1a872a649a9350ba136c40e0343eada9b | C++ | ducthanhtran/taocp | /volume_1/chapter_1/extended_euclid.cpp | UTF-8 | 993 | 3.625 | 4 | [] | no_license | // Extended Euclid's algorithm: algorithm E in "The Art of Programming, volume 1 (3rd edition), chapter 1.2.1".
#include <iostream>
#include <string>
struct Result {
int gcd;
int a;
int b;
};
// Algorithm E
Result extended_euclid(int m, int n) {
int a_ = 1;
int b = 1;
int a = 0;
int b_ = 0;
int r = m % n;
int q = m / n;
while(r != 0) {
m = n;
n = r;
int t = a_;
a_ = a;
a = t - q * a;
t = b_;
b_ = b;
b = t - q * b;
r = m % n;
q = m / n;
}
return Result{n, a, b};
}
// Arguments: m n
int main(int argc, char* argv[]) {
const int m = std::stoi(argv[1]);
const int n = std::stoi(argv[2]);
const auto res = extended_euclid(m, n);
std::cout << "Greatest common divisor of (" << m << ", " << n << ") is " << res.gcd
<< " with coefficients a=" << res.a << ", b=" << res.b << " for Bézout's identity\n";
return 0;
}
| true |
e4b0a21467ea6034e343b7516a3065bdb35234bc | C++ | insieme/insieme | /test/seq/cpp/cpp11/cpp11enums/cpp11enums.cpp | UTF-8 | 474 | 3.296875 | 3 | [] | no_license | #include <future>
#include <iostream>
namespace test {
enum class A { A=1, B=2 };
}
int main() {
//test with an intercepted scoped enum type
if(std::launch::async == std::launch::deferred) {
std::cout << "enum elements match\n";
} else {
std::cout << "enum elements do not match\n";
}
//test with namespaced scoped enum type
if(test::A::B == test::A::A) {
std::cout << "elements match\n";
} else {
std::cout << "elements do not match\n";
}
return 0;
}
| true |
a2198e051ca492f1fd0bd5fc3da4463877eedb80 | C++ | sakibsadmanshajib/NSU-CSE225L | /Unsorted (Array Based)/StudentInfo.cpp | UTF-8 | 859 | 3.328125 | 3 | [] | no_license | #include "StudentInfo.h"
StudentInfo::StudentInfo()
{
ID = 0;
Name = "";
CGPA = 0;
}
StudentInfo::StudentInfo(int id, string name, float cgpa)
{
ID = id;
Name = name;
CGPA = cgpa;
}
bool StudentInfo::operator!=(StudentInfo std1)
{
if(ID!=std1.ID || Name!=std1.Name || CGPA!=std1.CGPA)
{
return true;
}
else
return false;
}
void StudentInfo::print()
{
cout << ID << ", " << Name << ", " << CGPA << endl;
}
void StudentInfo::setID(int id)
{
ID = id;
}
void StudentInfo::setName(string name)
{
Name = name;
}
void StudentInfo::setCGPA(float cgpa)
{
CGPA = cgpa;
}
int StudentInfo::getID()
{
return ID;
}
bool StudentInfo::operator==(StudentInfo std1)
{
if(ID==std1.ID && Name==std1.Name && CGPA==std1.CGPA)
{
return true;
}
else
return false;
}
| true |
64b50e3ca5414f51610615a9266090b03bc712d5 | C++ | braveheartwm/leetcode | /src/data_structure/kill_man/second_max.h | UTF-8 | 1,375 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
template<class T>
struct Node {
T data;
Node* next;
Node() {}
Node(T x) {
data = x;
next = NULL;
}
};
template<class T>
T second_max(T a[],int n)
{
// if (n < 2) {
// throw "error";
// }
// T result = a[0];
// Node<T> list[n];
// for (int i = 0;i < n; ++i) {
// list[i].data = a[i];
// }
// for(int i = 0; i < (n)/2; ++i) {
// if(a[2*i] > a[2*i+1]) {
// list[2*i].next = new Node<T>(a[2*i+1]);
// } else {
// list[2*i+1].next = new Node<T>(a[2*i]);
// b[i] = a[2*i+1];
// }
// }
// if (n %2 != 0) {
// b[(n+1)/2-1] = a[n-1];
// // cout << "aaa"<< endl;
// }
// for (int i = 0; i < (n+1)/2; ++i) {
// cout << b[i] << " ";
// }
// cout << endl;
// return result;
T max = a[0],second = a[1];
if(a[0] < a[1]) {
max = a[1];
second = a[0];
}
for(int i = 2; i < n; ++i) {
if (a[i] > max) {
second = max;
max = a[i];
} else if (a[i] > second) {
second = a[i];
}
}
return second;
}
template <class T>
T second_max_list(T a[], int n) {
T result = a[0];
Node<T> list[n];
for (int i = 0;i < n; ++i) {
list[i].data = a[i];
}
} | true |
121285f659a15aa03edd4d74573cbc0438e39a5d | C++ | Shikhar-S/CodesSublime | /Google Drive/CodesSublime/CodeJam/b.cpp | UTF-8 | 498 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main()
{
int t;
cin>>t;
int j=0;
while(t--)
{
j++;
string x;
cin>>x;
int n=x.length();
int dp[n];
dp[0]=(x[0]=='-')?1:0;
for(int i=1;i<n;i++)
{
if(x[i]=='+')
{
dp[i]=dp[i-1];
}
else
{
int k;
for(k=i-1;k>=0;k--)
{
if (x[k]!='-')
{
dp[i]=dp[k]+2;
break;
}
}
if (k==-1)
{
dp[i]=1;
}
}
}
cout<<"Case #"<<j<<": "<<dp[n-1]<<"\n";
}
} | true |
7b961d3e5c44eaca3c3e04408b41daf598f8ae11 | C++ | vrichmon/6.179-Final-Project | /Ball.cpp | UTF-8 | 5,062 | 3 | 3 | [] | no_license | #include <SDL.h>
#include <SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <stdio.h>
#include <string>
#include <cmath>
//good place to look for general help (how I got this far): http://lazyfoo.net/tutorials/SDL/index.php
//Screen dimension constants (you can change)
const int SCREEN_WIDTH = 600;
const int SCREEN_HEIGHT = 420;
//Starts up SDL and creates window, apparently
bool init();
//??
bool loadMedia();
void close();
SDL_Texture* loadTexture( std::string path );
//The window to "render" to
SDL_Window* gWindow = NULL;
//The renderer
SDL_Renderer* gRenderer = NULL;
bool init()
{
//flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL couldn't' initialize... SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//texture stuff
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning...texture issues" );
}
//makes window
gWindow = SDL_CreateWindow( "Ball Game!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window couldn't be created.. :( SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );
if( gRenderer == NULL )
{
printf( "the renderer couldn't be created... :((( SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
// renderer color (blue right now)
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
//for pictures
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "image had issues... SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
}
}
}
return success;
}
//copied from online... don't think this is ever used
bool loadMedia()
{
bool success = true;
return success;
}
void close()
{
//close window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit everything!
IMG_Quit();
SDL_Quit();
}
SDL_Texture* loadTexture( std::string path )
{
SDL_Texture* newTexture = NULL;
//for pics
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL )
{
printf( "Image load issues for: %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
}
else
{
//"texture" stuff
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
{
printf( "exture issues from: %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
SDL_FreeSurface( loadedSurface );
}
return newTexture;
}
//Actual graphics stuff contained here
int main( int argc, char* args[] )
{
//start everything, make a window
if( !init() )
{
printf( "couldn't initialize\n" );
}
else
{
if( !loadMedia() )
{
printf( "couldn't 'load media'\n" );
}
else
{
bool quit = false;
//Event handler
SDL_Event e;
//While window should be open + running
while( !quit )
{
//Handle events
while( SDL_PollEvent( &e ) != 0 )
{
//close window
if( e.type == SDL_QUIT )
{
quit = true;
}
}
//Clear screen
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gRenderer );
//
// //Render green outlined quad
// SDL_Rect outlineRect = { SCREEN_WIDTH / 6, SCREEN_HEIGHT / 6, SCREEN_WIDTH * 2 / 3, SCREEN_HEIGHT * 2 / 3 };
// SDL_SetRenderDrawColor( gRenderer, 0x00, 0xFF, 0x00, 0xFF );
// SDL_RenderDrawRect( gRenderer, &outlineRect );
//Blue horizontal line, for scorekeeping box(?)
SDL_SetRenderDrawColor( gRenderer, 0x00, 0x00, 0xFF, 0xFF );
SDL_RenderDrawLine( gRenderer, 0, SCREEN_HEIGHT / 10, SCREEN_WIDTH/8, SCREEN_HEIGHT / 10 );
//vertical line for scorekeeping box (?)
for( int i = 0; i < SCREEN_HEIGHT/10; i++ )
{
SDL_RenderDrawPoint( gRenderer, SCREEN_WIDTH / 8, i );
}
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0x00, 0xFF, 0xFF );
//draw circle in middle
double R = 10;
double Deg0 = 0;
double Deg90 = M_PI / 2;
double DegStep = Deg90 / (R * 4);
double CurrDeg = Deg0;
double OffsetX = R;
double OffsetY = 0;
double TmpR = R;
double CX = SCREEN_WIDTH/2;
double CY = SCREEN_HEIGHT/2;
while(TmpR>0 )
{
while(CurrDeg < Deg90)
{
OffsetX = cos(CurrDeg) * TmpR;
OffsetY = sin(CurrDeg) * TmpR;
SDL_RenderDrawPoint(gRenderer, CX+(int)OffsetX, CY+(int)OffsetY);
SDL_RenderDrawPoint(gRenderer, CX-(int)OffsetY, CY+(int)OffsetX);
SDL_RenderDrawPoint(gRenderer, CX-(int)OffsetX, CY-(int)OffsetY);
SDL_RenderDrawPoint(gRenderer, CX+(int)OffsetY, CY-(int)OffsetX);
CurrDeg+=DegStep;
}
CurrDeg = Deg0;
TmpR-=1;
}
//Update screen
SDL_RenderPresent( gRenderer );
}
}
}
//done
close();
return 0;
}
| true |
aa83a876baf8a775c8427dc41e4f6a2b2a1d7a59 | C++ | ztao-sd/robotics-prototype | /robot/demos/WatchDogInterrupt/WatchDogInterrupt.ino | UTF-8 | 1,378 | 2.78125 | 3 | [] | no_license | int dogTimer = 0;
unsigned long int previousMillis = 0;
const int led = 13;
bool ledState = LOW;
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
Serial.begin(9600);
setDogTime(500);
kickDog();
}
void loop() {
unsigned long int currentTime = millis();
while (true) {
Blink();
if((currentTime - dogTimer) > 10){
kickDog();
dogTimer = millis();
} //if
} //while
} //loop
//The function "kicks the dog". Refreshes its timeout counter. If not refreshed, system will be reset.
void kickDog(){
noInterrupts();
WDOG_REFRESH = 0xA602;
WDOG_REFRESH = 0xB480;
interrupts();
}
void Blink(){
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= 100){
previousMillis = currentMillis;
ledState = !ledState;
digitalWrite(led, ledState);
Serial.println("test");
}
}
void setDogTime(int duration){
WDOG_UNLOCK = WDOG_UNLOCK_SEQ1;
WDOG_UNLOCK = WDOG_UNLOCK_SEQ2;
WDOG_TOVALL = duration; // The next 2 lines sets the time-out value. This is the value that the watchdog timer compare itself to.
WDOG_TOVALH = 0; //End value WDT compares itself to.
WDOG_STCTRLH = (WDOG_STCTRLH_ALLOWUPDATE | WDOG_STCTRLH_WDOGEN |
WDOG_STCTRLH_WAITEN | WDOG_STCTRLH_STOPEN); // Enable WDG
WDOG_PRESC = 0; //Sets watchdog timer to tick at 1 kHz inseast of 1/4 kHz
}
| true |
4f915cb0ec4284556ad870e0183f858b3deb0912 | C++ | rahulgyawali/Algorithms | /Place/Graph/dijkstra.cpp | UTF-8 | 1,063 | 2.890625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
int e;
int a;
int b;
int c;
int i;
int s;
cin>>n;
cin>>e;
vector <pair<int,int> > g[n+1];
for(i = 0; i < e ; i++) {
cin>>a>>b>>c;
g[a].push_back(make_pair(c,b));
}
s = 1;
bool vis[n+1];
int dis[n+1];
int par[n+1];
for(i = 1; i <= n; i++) {
vis[i] = false;
dis[i] = 999;
}
par[s] = -1;
dis[s] = 0;
priority_queue < pair <int,int> ,vector < pair<int,int> > ,greater < pair<int,int> > > p;
p.push(make_pair(0,s));
while(!p.empty()) {
pair<int,int> x= p.top();
p.pop();
a = x.second;
if(vis[a] == true)
continue;
vis[a] = true;
for(i = 0; i < g[a].size(); i++) {
int ne = g[a][i].second;
int wt = g[a][i].first;
if(dis[ne] > wt + dis[a]) {
dis[ne] = dis[a] + wt;
par[ne] = a;
p.push(make_pair(dis[ne],ne));
}
}
}
cout<<"---------------"<<endl;
for(i = 1; i <= n; i++) {
cout<<"Parent of "<< i <<" : " << par[i]<<" "<<" at distance "<<dis[i]<<" from "<<s<<endl;
}
return 0;
}
| true |
b65ebcd99c24d892a00ef85adae12958230233d5 | C++ | sahkashif/Sorting | /Assignment_4/BubbleSort.cpp | UTF-8 | 1,050 | 3.65625 | 4 | [] | no_license | #include "BubbleSort.h"
BubbleSort::BubbleSort()
{
}
BubbleSort::~BubbleSort()
{
}
void BubbleSort::swap(int & first, int & second)
{
int temp = first;
first = second;
second = temp;
}
void BubbleSort::bullble_sorter(int arr[], int size)
{
bool swaped = true;
int tracker = 0;
while (swaped)
{
swaped = false;
tracker++;
for (int index = 0; index < size-tracker; index++)
{
if (arr[index] > arr[index + 1])
{
swap(arr[index], arr[index + 1]);
swaped = true;
}
}
for (int index = 0; index < size; index++)
{
cout << arr[index] << " ";
}
cout << endl;
}
}
void BubbleSort::bubble_sorter_vector(vector<int> arr)
{
int size = arr.size();
bool swaped = true;
int tracker = 0;
while (swaped)
{
swaped = false;
tracker++;
for (int index = 0; index < size - tracker; index++)
{
if (arr[index] > arr[index + 1])
{
swap(arr[index], arr[index + 1]);
swaped = true;
}
}
for (int index = 0; index < size; index++)
{
cout << arr[index] << " ";
}
cout << endl;
}
}
| true |
4e12e42e279d1e7673efa2ea94101a64a3bd02ef | C++ | JakimPL/Roguelike | /src/item.hpp | UTF-8 | 3,030 | 2.8125 | 3 | [] | no_license | #ifndef ITEM_HPP
#define ITEM_HPP
#include "structures.hpp"
#include "color.hpp"
#include "text.hpp"
enum class Elementals : unsigned char {
physical,
magic,
fire,
ice,
electricity,
acid,
missile,
count
};
enum class ItemType : unsigned char {
miscellaneous,
weapon,
armor,
helmet,
gloves,
cloak,
boots,
ring,
amulet,
shield,
quiver,
quick,
count
};
enum class ItemCategory : unsigned char {
unused,
dagger,
short_sword,
long_sword,
staff,
spear,
club,
axe,
bow,
crossbow,
sling,
clothing,
leather_armor,
chain_mall,
plate_armor,
robe,
shield,
ammunition,
potion,
spell,
count
};
enum class ItemFlag {
none,
broken,
magic,
unidentified,
count
};
struct ItemEffect {
unsigned int nameID;
};
struct Item {
private:
unsigned int nameID;
unsigned int descriptionID;
Color color;
ItemType type;
ItemCategory category;
ItemFlag flag;
unsigned long price;
int damage;
int damageDelta;
int attackRate;
unsigned int delay;
int defense;
int defenseRate;
unsigned int requiredLevel;
unsigned int requiredAbilities[Ability::count];
std::vector<ItemEffect> effects;
public:
Item();
Item(const std::string& filename, bool fullPath = false);
unsigned int getNameID() const;
unsigned int getDescriptionID() const;
Color getColor() const;
ItemType getType() const;
ItemCategory getCategory() const;
ItemFlag getFlag() const;
unsigned long getPrice() const;
int getDamage() const;
int getDamageDelta() const;
int getAttackRate() const;
int getDelay() const;
int getDefense() const;
int getDefenseRate() const;
int getRequiredLevel() const;
int getRequiredAbility(const Ability ability) const;
void setNameID(unsigned int value);
void setDescriptionID(unsigned int value);
void setColor(Color value);
void setType(ItemType value);
void setCategory(ItemCategory value);
void setFlag(ItemFlag value);
void setPrice(unsigned long value);
void setDamage(int value);
void setDamageDelta(int value);
void setAttackRate(int value);
void setDelay(unsigned int value);
void setDefense(int value);
void setDefenseRate(int value);
void setRequiredLevel(unsigned int value);
void setRequiredAbility(const Ability ability, unsigned int value);
bool loadFromFile(const std::string& filename, bool fullPath = false);
bool saveToFile(const std::string& filename, bool fullPath = false);
bool load(std::ifstream& resource);
void save(std::ofstream& resource);
};
typedef std::vector<Item> Backpack;
typedef std::map<ItemType, int> Stack;
struct Inventory {
private:
Backpack backpack;
Stack stack;
public:
Inventory();
unsigned int addItem(const std::string& filename);
unsigned int addItem(Item item);
void clear();
void dropItem(ItemType type);
void dropItem(Item* item);
void equipItem(int index);
void removeItem(int index);
unsigned int getBackpackSize();
Item* getBackpackItem(int index);
int getStackItemIndex(ItemType type);
Item* getStackItem(ItemType type);
bool isEmpty() const;
bool isFull() const;
};
#endif // ITEM_HPP
| true |
4b99d81b98e8c3295562290b6b956fb4253bba62 | C++ | vbutzke/RaysManipulation | /HelloTriangle/Source.cpp | ISO-8859-1 | 6,716 | 2.703125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <assert.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <vector>
using namespace std;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
//ponto de interseco
//sombra
//interpolao
const GLuint WIDTH = 800, HEIGHT = 600;
const GLchar* vertexShaderSource = "#version 410\n"
"layout (location = 0) in vec3 position;\n"
"void main()\n"
"{\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\0";
const GLchar* fragmentShaderSource = "#version 410\n"
"uniform vec4 inputColor;\n"
"out vec4 color;\n"
"void main()\n"
"{\n"
"color = inputColor;\n"
"}\n\0";
void normalize(glm::vec3& normal) {
GLfloat length = sqrt(normal.x*normal.x + normal.y*normal.y + normal.z+normal.z);
normal.x = normal.x / length;
normal.y = normal.y / length;
normal.z = normal.z / length;
}
void shadow() {
}
void reflect(glm::vec3 ray, glm::vec3 rayDir, glm::vec3 intersection, glm::vec3& reflected) {
glm::vec3 normal = glm::vec3(ray + rayDir * intersection); // point of intersection
normalize(normal);
reflected = ray - normal * 2.0f * glm::dot(ray, normal);
}
void refract(glm::vec3 ray, glm::vec3 rayDir, glm::vec3 intersection, glm::vec3& refracted) {
glm::vec3 normal = glm::vec3(ray + rayDir * intersection); // point of intersection
normalize(normal);
float cosi = glm::dot(-normal, rayDir); // -nhit.dot(raydir);
float k = 1.0f - 0.8f * 0.8f * (1.0f - cosi * cosi);
refracted = rayDir * 0.8f + normal * (0.8f *cosi - sqrt(k));
}
GLFWwindow* init() {
glfwInit();
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glewExperimental = GL_TRUE;
glewInit();
const GLubyte* renderer = glGetString(GL_RENDERER); /* get renderer string */
const GLubyte* version = glGetString(GL_VERSION); /* version as a string */
cout << "Renderer: " << renderer << endl;
cout << "OpenGL version supported " << version << endl;
int width, height;
glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
return window;
}
void initShaders(GLuint& shaderProgram) {
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
void bindBuffers(GLuint& VAO, GLuint& reflectVAO, GLuint& refractVAO, GLuint& VBO, GLuint& VBOreflect, GLuint& refractVBO, GLuint& shaderProgram) {
glm::vec3 rayOr = glm::vec3(-0.5f, -0.5f, 0.0f);
glm::vec3 rayDir = glm::vec3(-rayOr.y, rayOr.x, rayOr.z);
glm::vec3 intersection = glm::vec3(-0.3f, -0.1f, 0.0f); //intersection point, static for now
glm::vec3 reflectedDir;
reflect(rayOr, rayDir, intersection, reflectedDir);
glm::vec3 refractDir;
refract(rayOr, rayDir, intersection, refractDir);
GLfloat vertices[] = {
rayOr.x, rayOr.y, rayOr.z,
intersection.x, intersection.y, intersection.z
};
GLfloat reflect[] = {
intersection.x, intersection.y, intersection.z,
reflectedDir.x, reflectedDir.y, reflectedDir.z
};
GLfloat refract[] = {
intersection.x, intersection.y, intersection.z,
refractDir.x, refractDir.y, refractDir.z
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glGenVertexArrays(1, &reflectVAO);
glGenBuffers(1, &VBOreflect);
glBindVertexArray(reflectVAO);
glBindBuffer(GL_ARRAY_BUFFER, VBOreflect);
glBufferData(GL_ARRAY_BUFFER, sizeof(reflect), reflect, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
glGenVertexArrays(1, &refractVAO);
glGenBuffers(1, &refractVBO);
glBindVertexArray(refractVAO);
glBindBuffer(GL_ARRAY_BUFFER, refractVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(refract), refract, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
GLint colorLoc = glGetUniformLocation(shaderProgram, "inputColor");
assert(colorLoc > -1);
glUseProgram(shaderProgram);
glUniform4f(colorLoc, 1.0f, 0.0f, 1.0f, 1.0f);
}
int main() {
GLuint VBO, VBOreflect, VBOrefract, VAO, reflectVAO, refractVAO, shaderProgram;
GLFWwindow* window = init();
initShaders(shaderProgram);
bindBuffers(VAO, reflectVAO, refractVAO, VBO, VBOreflect, VBOrefract, shaderProgram);
while (!glfwWindowShouldClose(window)){
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_LINES, 0, 3);
glBindVertexArray(0);
glBindVertexArray(reflectVAO);
glDrawArrays(GL_LINES, 0, 3);
glBindVertexArray(0);
glBindVertexArray(refractVAO);
glDrawArrays(GL_LINES, 0, 3);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &VAO);
glDeleteVertexArrays(1, &reflectVAO);
glDeleteVertexArrays(1, &refractVAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &VBOreflect);
glDeleteBuffers(1, &VBOrefract);
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
| true |
8e0a7436079c125d3f72b0fec910ea9c8c28acda | C++ | breezy1812/MyCodes | /LeetCode/740-Delete and Earn/solution.cpp | UTF-8 | 516 | 2.640625 | 3 | [] | no_license | class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
int gains[100002] = {0};
int max_num = 0;
for(auto x: nums)
{
gains[x]++;
max_num = max(max_num, x);
}
int ans = 0, dpm1 = 0, dpm2 = 0;
for(int i = 1; i < 100001; i++)
{
ans = max(dpm2 + gains[i] * i, dpm1);
dpm2 = dpm1;
dpm1 = ans;
if(i == max_num)
break;
}
return ans;
}
};
| true |
ccb1b6177b1560d870bd8ad8ee0be3fd51f28998 | C++ | shoaibrain/cse1325--school-projects | /P08/Sprint4/section.cpp | UTF-8 | 624 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "section.h"
#include "course.h"
#include "semester.h"
#include "subject.h"
#include <iostream>
Section::Section(Course course, Semester semester, int year )
: _course{course}, _semester{semester}, _year{year} {}
/*
Section::Section(std::istream& ist){
_course(ist);
load_semester(ist);
ist >> _year;
ist.ignore(32767, '\n');
}
*/
void Section::save(std::ostream &ost)
{
_course.save(ost);
ost << _semester << "\n" << _year << "\n";
}
std::ostream &operator<<(std::ostream &ost, const Section §ion)
{
//Todo
ost << section;
return ost;
}
| true |
9f009f6fbd7b57396b5735274f19c21d8a9ebb24 | C++ | PaintPPJ/Programming-week-8 | /Programming week 8/Source.cpp | UTF-8 | 1,085 | 2.578125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int k, j;
char x[10][5][5] =
{
{
"xxxx",
"x x",
"x x",
"x x",
"xxxx"
},
{
" x",
" x",
" x",
" x",
" x"
},
{
"xxxx",
" x",
"xxxx",
"x ",
"xxxx"
},
{
"xxxx",
" x",
"xxxx",
" x",
"xxxx"
},
{
"x x",
"x x",
"xxxx",
" x",
" x"
},
{
"xxxx",
"x ",
"xxxx",
" x",
"xxxx"
},
{
"xxxx",
"x ",
"xxxx",
"x x",
"xxxx"
},
{
"xxxx",
" x",
" x",
" x",
" x"
},
{
"xxxx",
"x x",
"xxxx",
"x x",
"xxxx"
},
{
"xxxx",
"x x",
"xxxx",
" x",
"xxxx"
},
};
int num, temp[100], i=0, count=0;
scanf("%d", &num);
if (num < 1000000000&&num>0) {
while (num > 0)
{
temp[i] = num % 10;
num = num / 10;
i++;
}
count = i;
for (k = 0; k < 5; k++)
{
for (i = count - 1; i >= 0; i--)
{
printf("%s\t", x[temp[i]][k]);
}
printf("\n");
}
}
else
{
printf("Error");
}
return 0;
} | true |
8c8c38a36297ef81226000f3e3caf7f9c6c5eb02 | C++ | baatochan/FirstTryWithCpp | /gruz5/main.cpp | UTF-8 | 4,285 | 3.4375 | 3 | [
"Unlicense"
] | permissive | #include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int ilosc_wierszy = 5;
int ilosc_kolumn = 5;
int tablica[5][5]; //ilosc elementow
int zaladuj_tablice() {
for (int i=0; i<ilosc_wierszy; i++) {
for (int j=0; j<ilosc_kolumn; j++) {
cout<<"Podaj "<<j+1<<" wyraz "<<i+1<<" rzedu: ";
//tablica[i][j] = rand() % 19 - 9;
cin>>tablica[i][j];
//cout<<tablica[i][j]<<endl;
}
}
cout<<endl;
}
void wypisz_zawartosc() {
for (int i=0; i<ilosc_wierszy; i++) {
cout<<"Wyrazy "<<i+1<<" rzedu:";
for (int j=0; j<ilosc_kolumn; j++) {
cout<<" "<<tablica[i][j];
}
cout<<endl;
}
cout<<endl;
}
int policz_sume_pierwszej_przekatnej() {
int suma = 0;
for (int i=0; i<ilosc_wierszy; i++) {
suma += tablica[i][i];
}
return suma;
}
int policz_sume_drugiej_przekatnej() {
int suma = 0;
for (int i=0; i<ilosc_wierszy; i++) {
suma += tablica[i][ilosc_kolumn-i-1];
}
return suma;
}
int policz_sume_nad_przekatna() {
int suma = 0;
for (int i=0; i<ilosc_wierszy; i++) {
for (int j=i+1; j<ilosc_kolumn; j++) {
suma += tablica[i][j];
}
}
return suma;
}
int policz_sume_pod_przekatna() {
int suma = 0;
for (int i=0; i<ilosc_wierszy; i++) {
for (int j=0; j<i; j++) {
suma += tablica[i][j];
}
}
return suma;
}
int wyznacz_minimum() {
int minimum = tablica[0][0];
for (int i=0; i<ilosc_wierszy; i++) {
for (int j=0; j<ilosc_kolumn; j++) {
if (minimum > tablica[i][j]) {
minimum = tablica[i][j];
}
}
}
return minimum;
}
int menu() {
int wybrany;
cout<<"Zadania: "<<endl;
cout<<"1. Wypisz zawartosc tabeli"<<endl;
cout<<"2. Policz sume pierwszej przekatnej (lewy-gora - prawy-dol)"<<endl;
cout<<"3. Policz sume drugiej przekatnej (lewy-dol - prawy-gora)"<<endl;
cout<<"4. Policz sume nad pierwsza przekatna"<<endl;
cout<<"5. Policz sume pod pierwsza przekatna"<<endl;
cout<<"6. Wyznacz najmniejszy wyraz tabeli"<<endl;
cout<<endl;
cout<<"9. Zaladuj tabele ponownie"<<endl;
cout<<"0. Wyjscie"<<endl;
cout<<"Podaj numer zadania: ";
cin>>wybrany;
cout<<endl;
return wybrany;
}
int main()
{
reset:
int wybor_menu;
zaladuj_tablice();
start_menu:
wybor_menu = menu();
switch (wybor_menu) {
case 0: {
goto exit;
break;
}
case 1: {
wypisz_zawartosc();
break;
}
case 2: {
int suma_pierwszej = policz_sume_pierwszej_przekatnej();
cout<<"Suma pierwszej przekatnej: "<<suma_pierwszej<<endl;
cout<<endl;
break;
}
case 3: {
int suma_drugiej = policz_sume_drugiej_przekatnej();
cout<<"Suma drugiej przekatnej: "<<suma_drugiej<<endl;
cout<<endl;
break;
}
case 4: {
int suma_nad = policz_sume_nad_przekatna();
cout<<"Suma nad przekatna: "<<suma_nad<<endl;
cout<<endl;
break;
}
case 5: {
int suma_pod = policz_sume_pod_przekatna();
cout<<"Suma pod przekatna: "<<suma_pod<<endl;
cout<<endl;
break;
}
case 6: {
int minimum = wyznacz_minimum();
cout<<"Najmniejszy wyraz: "<<minimum<<endl;
cout<<endl;
break;
}
case 9: {
goto reset;
break;
}
default: {
cout<<"///////////////////////////////////////////////"<<endl;
cout<<"///Takie zadanie nie istnieje, wybierz inne.///"<<endl;
cout<<"///////////////////////////////////////////////"<<endl;
cout<<endl;
goto start_menu;
break;
}
}
goto start_menu;
exit:
return 0;
}
| true |
e38e3bc3ea5eb44a11a9128ca2191d353f09b15d | C++ | hdsmtiger/Solution4LeetCode | /Restore-IP-Addresses.cpp | UTF-8 | 1,500 | 2.96875 | 3 | [] | no_license | class Solution {
public:
void findNextDigit(string s, int index, int numberPos, vector<string> &result, string oneSolution, int length)
{
if(index == length && numberPos == 4)
{
result.push_back(oneSolution);
return;
}else if(index == length || numberPos == 4)
return;
for(int i=1; i<=3 && i+index <= length; i++)
{
if( (length - index - i) > (3-numberPos) * 3)
continue;
string digitStr = s.substr(index, i);
if(digitStr.size() > 1 && digitStr.at(0) == '0')
continue;
int digit = atoi(digitStr.c_str());
if(digit <=255)
{
oneSolution.push_back('.');
oneSolution.append(digitStr);
findNextDigit(s, index+i, numberPos + 1, result, oneSolution,length);
oneSolution.erase(index + numberPos - 1, i+1);
}
}
}
vector<string> restoreIpAddresses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int length = s.size();
vector<string> result;
if(length<4 || length>12)
return result;
string oneSolution;
for(int i=1; i<=3; i++)
{
if( (length - i) > 9)
continue;
string digitStr = s.substr(0, i);
if(digitStr.size() > 1 && digitStr.at(0) == '0')
continue;
int digit = atoi(digitStr.c_str());
if(digit <=255)
{
oneSolution.append(digitStr);
findNextDigit(s, i, 1, result, oneSolution,length);
oneSolution.erase(0, i);
}
}
return result;
}
};
| true |
b2b36b656ec8901ac2fbca025eebd5e7f70c3700 | C++ | JayParanjape/AI_Sem5 | /A3/graph_solve2.cpp | UTF-8 | 5,001 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <vector>
#include<algorithm>
using namespace std;
int count_clauses=0; //number of clauses
int count_vars=0; //number of variables
vector<int> smaller_graph_nodes; //nodes in the smaller graph
vector<int> bigger_graph_nodes; //nodes in the bigger graph
vector<vector<int>> edges_big; //edges in bigger graph
vector<vector<int>> edges_small; //edges in smaller graph
int max_small=0; //biggest node in the smaller graph
int max_big=0; //biggest node in the bigger graph
string out = "";
bool finder(vector<int> vec, int val)
{
for(unsigned int i=0;i<vec.size();i++)
{
if(vec.at(i)==val)
return true;
}
return false;
}
void input(string filename)
{
int c1,c2;
ifstream file;
ofstream tempfile;
file.open(filename);
if(file.is_open())
{
while(file>>c1>>c2)
{
if(c1==0 && c2==0)
{
break;
}
if(c1>max_big)
max_big = c1;
if(c2>max_big)
max_big = c2;
//Input the bigger graph first
if(!finder(bigger_graph_nodes,c1))
{
bigger_graph_nodes.push_back(c1);
}
if(!finder(bigger_graph_nodes,c2))
{
bigger_graph_nodes.push_back(c2);
}
}
//Input the smaller graph
while(file>>c1>>c2)
{
if(c1>max_small)
max_small = c1;
if(c2>max_small)
max_small = c2;
if(!finder(smaller_graph_nodes,c1))
smaller_graph_nodes.push_back(c1);
if(!finder(smaller_graph_nodes,c2))
smaller_graph_nodes.push_back(c2);
}
}
else
cout<<"FILE DOES NOT EXIST"<<endl;
file.close();
//Reading file again to fill the mapping vector
edges_big.assign(max_big+1, vector<int>(max_big+1,0));
edges_small.assign(max_small+1, vector<int>(max_small+1,0));
file.open(filename);
if(file.is_open())
{
//fill the bigger graph edges
while(file>>c1>>c2)
{
if(c1==0 && c2==0)
break;
edges_big.at(c1).at(c2) = 1;
}
//fill the smaller graph edges
while(file>>c1>>c2)
{
edges_small.at(c1).at(c2) = 1;
}
}
else
cout<<"File does not exist"<<endl;
file.close();
count_vars = (edges_big.size()-1)*(edges_small.size()-1);
// cout<<"IO DONE "<<(edges_big.size()-1)<<" "<<(edges_small.size()-1)<<endl;
tempfile.open("temp.txt");
tempfile << (edges_big.size()-1);
tempfile.close();
}
void make_all_clauses()
{
//this function makes all clauses for the sat solver, assuming that Graph is the bigger graph
string out_trivial="";
string out_exact="";
string out_constrain="";
string out_extra = "";
unsigned int bigger_size = edges_big.size();
// unsigned int bigger_size_present = bigger_graph_nodes.size();
unsigned int smaller_size = edges_small.size();
// unsigned int smaller_size_present = smaller_graph_nodes.size();
// int big_node,small_node;
for(unsigned int j=0;j<bigger_size-1;j++)
{
for(unsigned int i=1;i<smaller_size; i++)
{
for(unsigned int k=i+1;k<smaller_size;k++)
{
out_extra += (to_string(-1*(j+1 + (bigger_size-1)*(k-1))) + " " + to_string(-1*(j+1+(bigger_size-1)*(i-1))));
out_extra += " 0\n";
count_clauses++;
}
}
}
for(unsigned int i=1;i<smaller_size; i++)
{
// cout<<i<<endl;
for(unsigned int j=0;j<bigger_size-1;j++)
{
//make_out_trivial
out_trivial += (to_string(j+1 + (bigger_size-1)*(i-1)) + " ");
//cout<<"Made trivial clauses"<<endl;
//make out_exact
for(unsigned int k=j+1;k<bigger_size-1;k++)
{
out_exact += (to_string(-1*(k+1+(bigger_size-1)*(i-1))) + " " + to_string(-1*(j+1+(bigger_size-1)*(i-1))));
out_exact+=" 0\n"; count_clauses++;
}
//cout<<"Made exact nodes"<<endl;
//make out_constrain
for(unsigned int idash=1;idash<edges_small.at(i).size();idash++)
{
if(idash==i)
continue;
if(edges_small.at(i).at(idash)==0)
{
for(unsigned int jdash=0;jdash<edges_big.at(j).size()-1;jdash++)
{
if(jdash==j)
continue;
if(edges_big.at(j+1).at(jdash+1)==1)
{
out_constrain += (to_string(-1*(j+1+(bigger_size-1)*(i-1))) + " " + to_string(-1*(jdash+1+(bigger_size-1)*(idash-1))) + " 0\n");
count_clauses++;
}
}
}
else
{
for(unsigned int jdash=0;jdash<edges_big.at(j).size()-1;jdash++)
{
if(jdash==j)
continue;
if(edges_big.at(j+1).at(jdash+1)==0)
{
out_constrain += (to_string(-1*(j+1+(bigger_size-1)*(i-1))) + " " + to_string(-1*(jdash+1+(bigger_size-1)*(idash-1))) + " 0\n");
count_clauses++;
}
}
}
}
}
out_trivial+="0\n"; count_clauses++;
}
out = out_trivial + out_exact + out_extra + out_constrain;
}
int main(int argc,char *argv[]){
string file(argv[1]);
input(file + ".graphs");
ofstream outfile;
outfile.open(file + ".satinput");
make_all_clauses();
//Question == why is count_var not simply equal to the product of the sizes of the two graphs?
out = "p cnf " + to_string(count_vars) + " " + to_string(count_clauses) + "\n" + out;
outfile << out;
outfile.close();
return 0;
}
| true |
198a48e7049297676479d5f9f891f10d577bc2a0 | C++ | Dragon9815/Ridge | /Engine/src/Ridge/Platform/OpenGL/GLVertexArray.cpp | UTF-8 | 835 | 2.59375 | 3 | [] | no_license | #include "RidgePCH.h"
#include "GLVertexArray.h"
#include "GLUtil.h"
namespace Ridge { namespace Graphics {
GLVertexArray::GLVertexArray()
{
GLCall(glCreateVertexArrays(1, &m_id));
}
GLVertexArray::~GLVertexArray()
{
GLCall(glDeleteVertexArrays(1, &m_id));
}
Ridge::Graphics::VertexBuffer* GLVertexArray::GetBuffer(int index /*= 0*/)
{
return m_buffers[index];
}
void GLVertexArray::PushBuffer(VertexBuffer* buffer, const BufferLayout& bufferLayout)
{
m_buffers.push_back(buffer);
Bind();
buffer->SetLayout(bufferLayout);
}
void GLVertexArray::Bind() const
{
GLCall(glBindVertexArray(m_id));
}
void GLVertexArray::Unbind() const
{
GLCall(glBindVertexArray(0));
}
void GLVertexArray::Draw(uint32 count) const
{
GLCall(glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, NULL));
}
} } | true |
5a8e13e9757cdd33b5cffd6ea27a94707eb4823f | C++ | gnboorse/cpp-class-hmwk | /WA_5/WA5_exercise1.cpp | UTF-8 | 5,331 | 3.296875 | 3 | [] | no_license | /*
@author gabriel boorse
Compiled using g++ on CentOS 7 Linux
Use:
g++ -std=c++0x WA5_exercise1.cpp -o WA5exercise1
./WA5exercise1
**
Creates a list of random bank accounts (Savings or Checking)
And then it iterates over those random accounts,
performs operations based on which type they are
And then cleans up memory and exits.
**
Example output:
[gboorse@localhost WA_5]$ ./WA5exercise1
We have 11 accounts
Account with balance $741
How much do you want to withdraw (debit)? $10
How much do you want to deposit (credit)? $0
Account is Savings.
Added interest = $21.93
Final balance = $752.93
Account with balance $327
How much do you want to withdraw (debit)? $12
How much do you want to deposit (credit)? $2
Account is Checking.
Final balance = $316.96
Account with balance $1843
How much do you want to withdraw (debit)? $223
How much do you want to deposit (credit)? $1
Account is Savings.
Added interest = $81.05
Final balance = $1702.05
Account with balance $1247
How much do you want to withdraw (debit)? $224
How much do you want to deposit (credit)? $33
Account is Savings.
Added interest = $21.12
Final balance = $1077.12
Account with balance $1110
How much do you want to withdraw (debit)? $44
How much do you want to deposit (credit)? $211
Account is Savings.
Added interest = $63.85
Final balance = $1340.85
Account with balance $831
How much do you want to withdraw (debit)? $334
How much do you want to deposit (credit)? $0
Account is Savings.
Added interest = $14.91
Final balance = $511.91
Account with balance $245
How much do you want to withdraw (debit)? $22
How much do you want to deposit (credit)? $11133
Account is Checking.
Final balance = $11355.9
Account with balance $585
How much do you want to withdraw (debit)? $335
How much do you want to deposit (credit)? $111
Account is Savings.
Added interest = $10.83
Final balance = $371.83
Account with balance $1672
How much do you want to withdraw (debit)? $2
How much do you want to deposit (credit)? $0
Account is Checking.
Final balance = $1669.94
Account with balance $1505
How much do you want to withdraw (debit)? $33
How much do you want to deposit (credit)? $3
Account is Savings.
Added interest = $44.25
Final balance = $1519.25
Account with balance $1452
How much do you want to withdraw (debit)? $55
How much do you want to deposit (credit)? $1
Account is Savings.
Added interest = $27.96
Final balance = $1425.96
Goodbye!
*/
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include "BankAccount.h"
#include "Savings.h"
#include "Checking.h"
#include <typeinfo>
using namespace std;
typedef vector<BankAccount*> account_list;
account_list random_accounts();
void free_accounts(account_list* accounts_);
int main()
{
account_list accounts = random_accounts();
account_list::size_type size_ = accounts.size();
cout << "We have " << size_ << " accounts" << endl;
for(account_list::size_type i = 0; i != accounts.size(); i++)
{
BankAccount* b = accounts[i];
double startingBalance = accounts[i]->getBalance();
cout << "Account with balance $" << startingBalance << endl;
double debit_amount;
cout << " How much do you want to withdraw (debit)? $";
cin >> debit_amount;
b->debit(debit_amount);
double credit_amount;
cout << " How much do you want to deposit (credit)? $";
cin >> credit_amount;
b->credit(credit_amount);
if (dynamic_cast<Savings*>(b)) // check if Savings account
{
cout << " Account is Savings." << endl;
//calculate interest and add to balance
Savings* s = dynamic_cast<Savings*>(b);
double interest = s->calculateInterest();
s->credit(interest);
cout << " Added interest = $" << interest << endl;
}
if (dynamic_cast<Checking*>(b)) //check if Checking account
{
cout << " Account is Checking." << endl;
}
double endingBalance = accounts[i]->getBalance();
cout << " Final balance = $" << endingBalance << endl;
}
//free up memory from this pointer vector
free_accounts(&accounts);
cout << "Goodbye!" << endl;
return 0;
}
void free_accounts(account_list* accounts_)
{
account_list accounts = *(accounts_);
for(account_list::size_type i = 0; i != accounts.size(); i++)
{
BankAccount* b = accounts[i];
delete b;
}
}
//get a list of random bank accounts
account_list random_accounts()
{
srand (time(NULL)); //seed your random
account_list v;
int total = rand() % 20 + 1;
if (total < 5) { total = 5; }
v.reserve(total);
for (int i = 0; i < total; i++)
{
int _switch = rand() % 2 + 1;
if (_switch == 1)
{
double r = static_cast <double> (rand() % 5 + 1) / (double) 100;
//checking bank account
Checking* c = new Checking((double)(rand()%2000 + 1), r);
v.push_back(c);
}
else if (_switch == 2)
{
double r = static_cast <double> (rand() % 5 + 1) / (double) 100;
//savings bank account
Savings* s = new Savings((double)(rand()%2000 + 1), r);
v.push_back(s);
}
}
return v;
} | true |
c63a6051c937368a85daa343561fc7d63323f874 | C++ | KlgTurtle/TITM | /TcpClientSocket.cpp | UTF-8 | 1,506 | 2.984375 | 3 | [] | no_license | #include "TcpClientSocket.h"
#include <string>
TcpClientSocket::TcpClientSocket(const std::string & TargetAddress, const std::string & TargetPort)
: m_TargetAddress(TargetAddress), m_TargetPort(TargetPort)
{
}
void TcpClientSocket::Connect()
{
struct addrinfo *result = NULL;
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
int iResult = getaddrinfo(m_TargetAddress.c_str(), m_TargetPort.c_str(), &hints, &result);
if (iResult != 0)
{
throw std::runtime_error("getaddrinfo failed with error: " + std::to_string(iResult));
}
// Attempt to connect to an address until one succeeds
for (addrinfo* ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
// Create a SOCKET for connecting to server
m_Socket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (m_Socket == INVALID_SOCKET)
{
throw std::runtime_error("socket failed with error: " + std::to_string(WSAGetLastError()));
}
// Connect to server.
iResult = connect(m_Socket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
{
closesocket(m_Socket);
m_Socket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (m_Socket == INVALID_SOCKET)
{
throw std::runtime_error("Failed to connect to target: " + m_TargetAddress + ":" + m_TargetPort);
}
}
| true |
9a542824fffeddc536657a76ea7097c44da3ca48 | C++ | WuyangPeng/Engine | /Engine/Code/Mathematics/Intersection/Intersection3D/DynamicTestIntersectorSegment3Triangle3Detail.h | GB18030 | 5,224 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// ߣʶ
/// ϵߣ94458936@qq.com
///
/// std:c++20
/// 汾0.9.0.12 (2023/06/09 09:23)
#ifndef MATHEMATICS_INTERSECTION_DYNAMIC_TEST_INTERSECTOR_SEGMENT3_TRIANGLE3_DETAIL_H
#define MATHEMATICS_INTERSECTION_DYNAMIC_TEST_INTERSECTOR_SEGMENT3_TRIANGLE3_DETAIL_H
#include "DynamicTestIntersectorSegment3Triangle3.h"
#include "TestIntersectorAxisDetail.h"
#include "CoreTools/Helper/ClassInvariant/MathematicsClassInvariantMacro.h"
template <typename Real>
Mathematics::DynamicTestIntersectorSegment3Triangle3<Real>::DynamicTestIntersectorSegment3Triangle3(const Segment3& segment, const Triangle3& triangle, Real tmax, const Vector3& lhsVelocity, const Vector3& rhsVelocity, const Real epsilon)
: ParentType{ tmax, lhsVelocity, rhsVelocity, epsilon }, segment{ segment }, triangle{ triangle }
{
Test();
MATHEMATICS_SELF_CLASS_IS_VALID_1;
}
#ifdef OPEN_CLASS_INVARIANT
template <typename Real>
bool Mathematics::DynamicTestIntersectorSegment3Triangle3<Real>::IsValid() const noexcept
{
if (ParentType::IsValid())
return true;
else
return false;
}
#endif // OPEN_CLASS_INVARIANT
template <typename Real>
Mathematics::Segment3<Real> Mathematics::DynamicTestIntersectorSegment3Triangle3<Real>::GetSegment() const noexcept
{
MATHEMATICS_CLASS_IS_VALID_CONST_1;
return segment;
}
template <typename Real>
Mathematics::Triangle3<Real> Mathematics::DynamicTestIntersectorSegment3Triangle3<Real>::GetTriangle() const noexcept
{
MATHEMATICS_CLASS_IS_VALID_CONST_1;
return triangle;
}
template <typename Real>
void Mathematics::DynamicTestIntersectorSegment3Triangle3<Real>::Test()
{
// ȡöεյ㡣
using SegmentType = std::array<Vector3, 2>;
SegmentType segmentType{ segment.GetBeginPoint(), segment.GetEndPoint() };
// ȡεıԵ
auto edge0 = triangle.GetVertex(1) - triangle.GetVertex(0);
auto edge1 = triangle.GetVertex(2) - triangle.GetVertex(0);
// ȡ߶εٶ
auto relVelocity = this->GetRhsVelocity() - this->GetLhsVelocity();
// η.
const auto edgeNormal = Vector3Tools::CrossProduct(edge0, edge1);
const TestIntersectorAxis<Real> intersector{ edgeNormal, segmentType, triangle, relVelocity, this->GetTMax() };
auto contactTime = intersector.GetTFirst();
if (!intersector.GetResult())
{
this->SetContactTime(contactTime);
this->SetIntersectionType(IntersectionType::Empty);
return;
}
// ߶ǷƽΣЧزԣ sin(Angle(NormV,DirU)) > 1 - epsilon
auto directionU = segmentType.at(1) - segmentType.at(0);
const auto normalU = Vector3Tools::CrossProduct(edgeNormal, directionU);
auto directionUSqrLen = Vector3Tools::GetLengthSquared(directionU);
auto normalUSqrLen = Vector3Tools::GetLengthSquared(normalU);
auto edgeNormalSqrLen = Vector3Tools::GetLengthSquared(edgeNormal);
auto oneMinusEpsilon = Math::GetValue(1) - Math::GetZeroTolerance();
// ƽ
if (oneMinusEpsilon * edgeNormalSqrLen * directionUSqrLen < normalUSqrLen)
{
// ηߺ߶η
const TestIntersectorAxis<Real> normalUIntersector{ normalU, segmentType, triangle, relVelocity, this->GetTMax() };
contactTime = normalUIntersector.GetTFirst();
if (!normalUIntersector.GetResult())
{
this->SetContactTime(contactTime);
this->SetIntersectionType(IntersectionType::Empty);
return;
}
// ηߺ߶αߡ
for (auto i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
{
const auto axis = Vector3Tools::CrossProduct(edgeNormal, (triangle.GetVertex(i1) - triangle.GetVertex(i0)));
const TestIntersectorAxis<Real> testIntersectorAxis{ axis, segmentType, triangle, relVelocity, this->GetTMax() };
contactTime = testIntersectorAxis.GetTFirst();
if (!testIntersectorAxis.GetResult())
{
this->SetContactTime(contactTime);
this->SetIntersectionType(IntersectionType::Empty);
return;
}
}
}
else // ƽ
{
// ߶ηαߡ
for (auto i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
{
const auto axis = Vector3Tools::CrossProduct(directionU, (triangle.GetVertex(i1) - triangle.GetVertex(i0)));
const TestIntersectorAxis<Real> testIntersectorAxis{ axis, segmentType, triangle, relVelocity, this->GetTMax() };
contactTime = testIntersectorAxis.GetTFirst();
if (!testIntersectorAxis.GetResult())
{
this->SetContactTime(contactTime);
this->SetIntersectionType(IntersectionType::Empty);
return;
}
}
}
this->SetContactTime(contactTime);
this->SetIntersectionType(IntersectionType::Point);
}
#endif // MATHEMATICS_INTERSECTION_DYNAMIC_TEST_INTERSECTOR_SEGMENT3_TRIANGLE3_DETAIL_H | true |
adf8aa987ccfd713a466dea62582c1ec9e1518f4 | C++ | pkerspe/ESP-StepperMotor-Server | /src/ESPStepperMotorServer_PositionSwitch.h | UTF-8 | 2,725 | 2.6875 | 3 | [
"MIT"
] | permissive |
#ifndef ESPStepperMotorServer_PositionSwitch_h
#define ESPStepperMotorServer_PositionSwitch_h
#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESPStepperMotorServer_Logger.h>
#include <ESPStepperMotorServer_MacroAction.h>
#define SWITCHTYPE_STATE_ACTIVE_HIGH_BIT 1
#define SWITCHTYPE_STATE_ACTIVE_LOW_BIT 2
#define SWITCHTYPE_LIMITSWITCH_POS_BEGIN_BIT 3
#define SWITCHTYPE_LIMITSWITCH_POS_END_BIT 4
#define SWITCHTYPE_POSITION_SWITCH_BIT 5
#define SWITCHTYPE_EMERGENCY_STOP_SWITCH_BIT 6
#define SWITCHTYPE_LIMITSWITCH_COMBINED_BEGIN_END_BIT 7
//size calculated using https://arduinojson.org/v6/assistant/
#define RESERVED_JSON_SIZE_ESPStepperMotorServer_PositionSwitch 170
class ESPStepperMotorServer_MacroAction;
class ESPStepperMotorServer_PositionSwitch
{
friend class ESPStepperMotorServer;
public:
ESPStepperMotorServer_PositionSwitch();
~ESPStepperMotorServer_PositionSwitch();
ESPStepperMotorServer_PositionSwitch(byte ioPin, int stepperIndex, byte switchType, String name = "", long switchPosition = 0);
/**
* setter to set the id of this switch.
* Only use this if you know what you are doing
*/
void setId(byte id);
/**
* get the id of the switch
*/
byte getId();
int getStepperIndex(void);
byte getIoPinNumber(void);
/**
* return the type of this switch if set.
* It indicates whether the switch as limit, position or emergency switch
* See constants
* SWITCHTYPE_LIMITSWITCH_POS_BEGIN_BIT
* SWITCHTYPE_LIMITSWITCH_POS_END_BIT
* SWITCHTYPE_LIMITSWITCH_COMBINED_BEGIN_END_BIT
* SWITCHTYPE_POSITION_SWITCH_BIT
* SWITCHTYPE_EMERGENCY_STOP_SWITCH_BIT
*/
byte getSwitchType(void);
String getPositionName(void);
void setPositionName(String name);
bool isActiveHigh();
bool isEmergencySwitch();
bool isLimitSwitch();
bool isTypeBitSet(byte bitToCheck);
long getSwitchPosition(void);
void setSwitchPosition(long position);
void addMacroAction(ESPStepperMotorServer_MacroAction *macroAction);
std::vector<ESPStepperMotorServer_MacroAction*> getMacroActions();
bool hasMacroActions(void);
void clearMacroActions(void);
int serializeMacroActionsToJsonArray(JsonArray macroActionsJsonArray);
private:
byte _stepperIndex;
byte _switchIndex;
byte _ioPinNumber = 255;
byte _switchType = 0; //this is a bit mask representing the active state (bit 1 and 2) and the general type (homing/limit/position or emergency stop switch) in one byte
String _positionName;
long _switchPosition;
ESPStepperMotorServer_Logger _logger;
std::vector<ESPStepperMotorServer_MacroAction*> _macroActions;
};
#endif
| true |
b8891a4104141418a941bae46382d26d4c8eb9ea | C++ | qcscine/swoose | /src/Swoose/Swoose/MolecularMechanics/Interactions/BondedTerm.h | UTF-8 | 1,639 | 2.640625 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#ifndef MOLECULARMECHANICS_BONDEDTERM_H
#define MOLECULARMECHANICS_BONDEDTERM_H
#include "../Topology/BondType.h"
#include "Bond.h"
#include "InteractionTermBase.h"
#include <Utils/Typenames.h>
#include <string>
namespace Scine {
namespace Utils {
class AtomicSecondDerivativeCollection;
} // namespace Utils
namespace MolecularMechanics {
/**
* @class BondedTerm BondedTerm.h
* @brief Class evaluating harmonic bonded interaction between two atoms.
*/
class BondedTerm : public InteractionTermBase {
public:
using AtomIndex = int;
/** @brief Constructor from two atom indices and instances of Bond and BondType classes. */
BondedTerm(AtomIndex firstAtom, AtomIndex secondAtom, const Bond& bond, const BondType& typeOfBond);
/** @brief Destructor. */
~BondedTerm();
/**
* @brief Evaluates energy contribution and adds the derivatives.
*/
double evaluateBondTerm(const Utils::PositionCollection& positions, Utils::AtomicSecondDerivativeCollection& derivatives) const;
/**
* @brief Getter for the bond type.
*/
BondType getTypeOfBond() const;
/**
* @brief Getter for first atom.
*/
int getFirstAtom() const;
/**
* @brief Getter for second atom.
*/
int getSecondAtom() const;
private:
AtomIndex firstAtom_, secondAtom_;
Bond bond_;
BondType typeOfBond_;
};
} // namespace MolecularMechanics
} // namespace Scine
#endif // MOLECULARMECHANICS_BONDEDTERM_H | true |
5f1fd3bc64182f89dc92fc49edca2e9087534afa | C++ | mh-cfd/ls_derivs | /leastsquaressolver.h | UTF-8 | 3,051 | 2.546875 | 3 | [] | no_license | #ifndef LEASTSQUARESSOLVER_H
#define LEASTSQUARESSOLVER_H
#include <vector>
//number of variables
#define VAR_NUM 10
//maximum number of points
#define MAX_EQNS 10000
typedef struct
{double x ,y,z,f,ax,ay,az;
int is_boundary; //if<0 than it's not the boundary oterwise it's boundary plane number
double f_bound;//value of the gradient at the boundary
double rhs;// value of the rhs for a poisson equation at the boundary
double INV[VAR_NUM][VAR_NUM];
} node3d;
typedef struct
{double d[VAR_NUM];} deriv3D;
typedef struct
{double nx,ny,nz;
double d;//normal distance from coordinate origin i.e. nx*x+ny*y+nz*z=d
} boundary_plane;
class leastSquaresSolver
{
private:
double M_[MAX_EQNS][50],
M_0[MAX_EQNS][50],
MWM[MAX_EQNS][50],
x_m[MAX_EQNS],
b_m[MAX_EQNS],
w[MAX_EQNS],
mwb[MAX_EQNS],
LU[MAX_EQNS][50],
Inv[MAX_EQNS][50];
int ps[MAX_EQNS];
public:
enum deriv_order
{
F,
FX,
FY,
FZ,
FXX,
FXY,
FXZ,
FYY,
FYZ,
FZZ
};
leastSquaresSolver();
std::vector<node3d> m_p; //points cloud
std::vector<deriv3D> m_d,m_d0; //derivs cloud
std::vector<boundary_plane> walls; //all boundaries are here for now
double pww;
double rad;
void init_with_points();
void init_for_benchmark();
void LU_decompose(void);
void m_solve(void);
void m_invert(void);
void LU_decompose2(int num);
void m_solve2(int num);
void m_invert2(int num);
void LU_decompose_krig(int num);
void m_solve_krig(int num);
void m_invert_krig(int num);
void LU_decompose_krig_2(int num);
void m_solve_krig_2(int num);
void nullify_m(double m[MAX_EQNS][50]);
void nullify_v(double v[MAX_EQNS]);
void get_derivs(node3d &p, deriv3D &res, double delta);
void get_derivs_fast(node3d &p, deriv3D &res, double delta);
void interpKrig(node3d &p);
void interpKrigDx(node3d &p);
double dist(node3d &p1,node3d &p2);
double distDx(node3d &p1,node3d &p2);
double distLapl(node3d &p1, node3d &p2);
void get_poisson_internal(node3d &p, deriv3D &res, double delta);
void get_poisson_boundary(node3d &p, deriv3D &res, double delta);
void get_poisson_combo(node3d &p, deriv3D &res, double delta);
void get_poisson_matr(node3d &p, deriv3D &res, double delta);// only gets the inverse matirx
void get_poisson_nomatr(node3d &p, deriv3D &res, double delta); //solves with given inverse matrix;
void draw_points(double sc);
void get_derivs_bench(node3d &p, deriv3D &res);
void getKrigInv();
void interpKrig_nomatr(node3d &p);
void solvePoisson_krig();
double distAx(node3d &p1, node3d &p2);
double distAy(node3d &p1, node3d &p2);
double distAz(node3d &p1, node3d &p2);
void solveKrig_grad(int itn, double delta);
void solveKrig_ls();
};
#endif // LEASTSQUARESSOLVER_H
| true |
f0fd6a182ebd893d9b84c468385beb0733a17eae | C++ | Senth/bats | /BATS/code/BTHAIModule/Source/RefineryAgent.h | UTF-8 | 494 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "StructureAgent.h"
#include <vector>
class WorkerAgent;
/** The RefineryAgent handles Refinery buildings for all races.
*
* Implemented abilities:
* - Makes sure each Refinery has 3 workers assigned to gather gas.
*
* @author Johan Hagelback (johan.hagelback@gmail.com)
*/
class RefineryAgent : public StructureAgent {
private:
std::vector<WorkerAgent*> assignedWorkers;
public:
RefineryAgent(BWAPI::Unit* mUnit);
/** Called each update to issue orders. */
void computeActions();
};
| true |
ab0e30e3a8fd6244dce0dd7d3a1b1875342c8162 | C++ | Binyamin-Brion/L-System-Visualizer | /ModelLoading/Model.h | UTF-8 | 2,664 | 2.96875 | 3 | [] | no_license | //
// Created by BinyBrion on 11/21/2019.
//
#ifndef MINECRAFT_MODEL_H
#define MINECRAFT_MODEL_H
class aiNode;
class aiScene;
class aiMesh;
#include <string>
#include <vector>
#include <QString>
#include "Mesh.h"
#include "Face.h"
#include "mat4x4.hpp"
namespace ModelLoading
{
/**
* Loads a model from a file, and makes it available by returning the list of meshes that compose the model.
*/
class Model
{
public:
/**
* Loads the model contained in the passed in file.
*
* @param fileLocation where the model information is held
*/
explicit Model(const std::string &fileLocation);
/**
* Checks for an intersection between a ray with a known start position and this model. Every mesh is checked
* by first converting it to world space using the passed in transformation matrix.
*
* @param cameraPosition position of the camera in world space
* @param rayDirection direction of the camera in world space
* @param transformationMatrix matrix to transform model into world space
* @return true if there is an intersection
*/
bool checkIntersection(const glm::vec3 &cameraPosition, const glm::vec3 &rayDirection, const glm::mat4 &transformationMatrix) const;
/**
* Get the individual meshes that compose the loaded model.
*
* @return vector of the model's meshes
*/
const std::vector<Mesh>& getMeshes() const;
/**
* Get the name of the file used to load this model.
*
* @return name of file containing information used to load this model
*/
const QString &getModelFileName() const;
private:
/**
* Extracts all of the required rendering data for a mesh of the model.
*
* @param mesh pointer to the mesh resource
* @param scene pointer to the scene resource
*/
void processMesh(const aiMesh* const mesh, const aiScene* const scene);
/**
* Extracts all of the required rendering data for a mesh of the model.
*
* @param mesh pointer to the mesh resource
* @param scene pointer to the scene resource
*/
void processNode(const aiNode* const node, const aiScene* const scene);
std::vector<Mesh> meshes;
QString modelFileName;
};
}
#endif //MINECRAFT_MODEL_H
| true |
88d3cdf2c349da9df35469eef1510617b9ea279f | C++ | Louis-tiany/Cpp_learn | /algorithm/data_struct/hash/longSANDiv.cpp | UTF-8 | 1,442 | 3.96875 | 4 | [] | no_license | //Given an array of N non-negative integers, task is to find the maximum size of a subarray such that the pairwise sum of the elements of this subarray is not divisible by a given integer, K. Also, print this subarray as well. If there are two or more subarrays which follow the above stated condition, then print the first one from the left.
#include<iostream>
#include<map>
using namespace std;
// function to find the subarray with // no pair sum divisible by k
void subarrayNDiv(int arr[],int n,int k)
{
map<int,int> mp;//store remainders obtained by k
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
//starting index of the maximum
//size subarray so far, maxe : ending
//index of the maximum size subarray
int s=0,e=0,maxs=0,maxe=0;
mp[arr[0]%k]++;
for(int i=1;i<n;i++)
{
int mod=arr[i]%k;
while(mp[k-mod]!=0||(mod==0&&mp[mod]!=0))
{
mp[arr[s]%k]--;
s++;
}
//include current element
mp[mod]++;
e++;
if((e-s)>maxe-maxs)
{
maxe=e;
maxs=s;
}
}
cout << "The maximum size is "
<< maxe - maxs + 1 << " and "
"the subarray is as follows\n";
for (int i=maxs; i<=maxe; i++)
cout << arr[i] << " "<<"\n";
}
int main()
{
int k = 3;
int arr[] = {5, 10, 15, 20, 25};
int n = sizeof(arr)/sizeof(arr[0]);
subarrayNDiv(arr, n, k);
return 0;
}
| true |
789b4bbac105a1f3cedb2300c42f66c3d40cf761 | C++ | DesignPatternWorks/CSE-335-Qt | /Lectures/Lecture08 - Abstract Factory Pattern/C++AbstractFactorySorting/AbstractFactorySorting/main.cpp | UTF-8 | 941 | 2.96875 | 3 | [
"MIT"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: alexliu
*
* Created on January 26, 2017, 5:34 PM
*/
#include <cstdlib>
#include <iostream>
using namespace std;
#include "BubbleSort.h"
#include "IntegerVectorSortable.h"
int main(int argc, char** argv) {
BubbleSort bs;
IntegerVectorSortable ivs;
ivs.insertInteger(5);
ivs.insertInteger(4);
ivs.insertInteger(6);
ivs.insertInteger(10);
cout<<"***************** Before Sorting Integers Decreasing"<<endl;
ivs.print();
cout<<"***************** After Sorting Integers Decreasing"<<endl;
bs.sortDecreasing(&ivs);
ivs.print();
cout<<"***************** After Sorting Integers Increasing"<<endl;
bs.sortIncreasing(&ivs);
ivs.print();
return 0;
}
| true |
a1f38a7bd9c7b1224f677c6f8191451805ce6107 | C++ | keivanzavari/computer-science-basics | /graphs/graph_definitions.h | UTF-8 | 1,265 | 3.296875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "../include/ostream_overload.h"
#include "linked_list.h"
template <typename T>
using Edges = std::set<T>;
template <typename T>
using AdjList = std::unordered_map<T, Edges<T>>;
// Graph implementation using adjacency list.
template <typename T>
class Graph {
public:
explicit Graph(bool directed = false) : directed_{directed} {}
bool addVertex(T vertex_name) {
if (!graph_.contains(vertex_name)) {
graph_[vertex_name] = {};
return true;
}
return false;
}
bool addEdge(T from, T to) {
if (!graph_.contains(from)) {
addVertex(from);
}
if (!graph_.contains(to)) {
addVertex(to);
}
graph_[from].insert(to);
if (!directed_) {
graph_[to].insert(from);
}
return true;
}
void print() const {
std::cout << "--------\n";
std::cout << "Graph:\n";
for (const auto& [vertex, edges] : graph_) {
std::cout << "vertex: " << vertex << " edges: " << edges << "\n";
}
std::cout << "--------\n";
}
const AdjList<T>& get() const { return graph_; }
private:
AdjList<T> graph_;
const bool directed_;
};
| true |
f7f234b9cfbe97362d4cae7effab62c74c5f59a8 | C++ | bamboo-hust/icpc-trainings | /mipt-nus-19/day6/h.cpp | UTF-8 | 1,108 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
long long f2[N];
long long f3[N];
long long sz[N];
int n;
vector<int> a[N];
void dfs1(int u, int p) {
sz[u] = 1;
for (int v : a[u]) if (v != p) {
dfs1(v, u);
sz[u] += sz[v];
}
}
void dfs2(int u, int p) {
long long pref = 0;
for (int v : a[u]) if (v != p) {
dfs2(v, u);
f2[u] += f2[v];
f2[u] += pref * sz[v];
pref += sz[v];
}
}
void dfs3(int u, int p) {
long long pref = 0;
long long pref2 = 0;
long long pref_sz = 0;
for (int v : a[u]) if (v != p) {
dfs3(v, u);
f3[u] += f3[v];
f3[u] += pref * sz[v];
f3[u] += pref2 * sz[v];
f3[u] += pref_sz * f2[v];
f3[u] += f2[v];
pref += f2[v];
pref2 += pref_sz * sz[v];
pref_sz += sz[v];
}
}
int main() {
cin >> n;
for (int i = 1; i < n; ++i) {
int u, v;
cin >> u >> v;
a[u].push_back(v);
a[v].push_back(u);
}
dfs1(1, 0);
dfs2(1, 0);
dfs3(1, 0);
cout << f3[1] << endl;
} | true |
8f9c02df0dd332ecb8a15a81438e4518b959d6c8 | C++ | nshokri/Movie-Rental-Project | /classics.cpp | UTF-8 | 1,417 | 3.484375 | 3 | [] | no_license | #include "classics.h"
Classics::Classics(char type, int stock, string director, string title, string majorActor, int releaseMonth, int releaseYear)
: Movie(type, stock, director, title, releaseYear)
{
this->majorActor = majorActor;
this->releaseMonth = releaseMonth;
this->releaseYear = releaseYear;
}
Classics::~Classics()
{
}
void Classics::print() const
{
cout << type << ", " << stock << ", " + director + ", " + title
+ ", " << majorActor + " " << releaseMonth << " " << releaseYear;
}
string Classics::getMajorActor() const
{
return majorActor;
}
int Classics::getYear() const
{
return releaseYear;
}
int Classics::getMonth() const
{
return releaseMonth;
}
bool Classics::operator<(const Classics& other) const
{
if (releaseYear < other.releaseYear)
{
return true;
}
else if (releaseYear == other.releaseYear && releaseMonth < other.releaseMonth)
{
return true;
}
else if (releaseYear == other.releaseYear && releaseMonth == other.releaseMonth)
{
if (majorActor < other.majorActor)
{
return true;
}
}
return false;
}
bool Classics::operator==(const Classics& other) const
{
//If the movies are exactly the same
if (stock == other.stock && director == other.director
&& title == other.title && year == other.year
&& majorActor == other.majorActor && releaseMonth == other.releaseMonth
&& releaseYear == other.releaseYear)
{
return true;
}
return false;
} | true |
010693f2bb9f423d1e2d26088230827bc37d98d3 | C++ | YBTayeb/Cpp | /CodesSource/exo141.cpp | UTF-8 | 520 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std ;
main()
{ void f() ;
try
{ f() ;
}
catch (int n)
{ cout << "except int dans main : " << n << "\n" ;
}
catch (...)
{ cout << "exception autre que int dans main \n" ;
}
cout << "fin main\n" ;
}
void f()
{
try
{ int n=1 ; throw n ;
}
catch (int n)
{ cout << "except int dans f : " << n << "\n" ;
throw ;
}
}
void f()
{
try
{ float x=2.5 ; throw x ;
}
catch (int n)
{ cout << "except int dans f : " << n << "\n" ;
throw ;
}
}
| true |
a49bc834e6799a76e64c5efdd9b366350e31ab07 | C++ | InvincibleSarthak/Competitive-Programming | /STL/BinarySearch.cpp | UTF-8 | 756 | 3.703125 | 4 | [] | no_license | //Binary Search (in-built function), Lower Bound, Upper Bound
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
int arr[]={10,20,30,40,40,40,50,70};
int n = sizeof(arr)/sizeof(int);
int key;
cin>>key;
bool present = binary_search(arr,arr+n,key);
if(present){
cout<<"The number is present in the array. "<<endl;
}
else{
cout<<"The number is absent from the array."<<endl;
}
auto it1 = lower_bound(arr,arr+n,key); //first element greater than or equal to the key
cout<<*it1<<endl;
auto it2 = upper_bound(arr,arr+n,key); // first element greater than key
cout<<*it2<<endl;
cout<<it2-it1<<endl; // To print the frequency of a number in an array
return 0;
}
| true |
2837bd51f0cfbd012d3f7af68d198e31fc8ec88f | C++ | jayantsa/AlgorithmicCoding | /gfg/sortinstl.cpp | UTF-8 | 369 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int comp(int a,int b)
{
return a>b;
}
int main()
{
vector<int> arr={5,1,3,20,0,7,-1};
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<" ";
cout<<"\n";
sort(arr.begin(),arr.end(),comp);
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<" ";
cout<<"\n";
}
| true |
10c243bb48481ac5919a55f7e20a2ee11557a12c | C++ | bhsphd/cpplects-beamer | /codes/chap05/0XShapeClass/Point2D.h | UTF-8 | 953 | 3.09375 | 3 | [] | no_license | #ifndef POINT2D_H_INCLUDED
#define POINT2D_H_INCLUDED
#include <iostream>
#include <cmath>
using namespace std;
#if !defined(M_PI)
#define M_PI 3.1415926535897932384626433832795
#endif
class CPoint2D
{
float x, y;
public:
CPoint2D()
{
x = y = 0;
}
CPoint2D(float x, float y)
{
this->x = x;
this->y = y;
}
void Translate(float x, float y)
{
this->x = this->x + x;
this->y = this->y + y;
}
void Scale(float r)
{
x = r * x;
y = r * y;
}
void Rotate(float angle)
{
angle = angle * M_PI / 180.0;
float tmp;
tmp = x;
x = x * cos(angle) + y * sin(angle);
y = y * cos(angle) - tmp * sin(angle);
}
friend class CShape;
friend class CRectangle;
friend class CEllipse;
friend class CDonut;
};
#endif // POINT2D_H_INCLUDED
| true |
5e7fa7524199610d93c2d330ab3d0735fb55f761 | C++ | YueJi95/LeetCode | /339. Nested List Weight Sum.cpp | UTF-8 | 1,616 | 3.421875 | 3 | [] | no_license | /**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
queue<NestedInteger> q;
for(int i = 0; i < nestedList.size(); i++) q.push(nestedList[i]);
int depth = 1;
int count = nestedList.size();
int bcount = 0;
int sum = 0;
while(q.empty() == false){
NestedInteger current = q.front();
q.pop();
if(current.isInteger() == true) sum = sum + current.getInteger() * depth;
else{
for(int i = 0; i < current.getList().size(); i++){
q.push((current.getList())[i]);
bcount++;
}
}
count--;
if(count == 0){
depth++;
count = bcount;
bcount = 0;
}
}
return sum;
}
}; | true |
c78029b97f3b329f822f35f21a7c590c54233f11 | C++ | songxiaopeng/Ray-Tracing-in-One-Weekend | /ch00&01/Main.cpp | GB18030 | 1,290 | 2.875 | 3 | [] | no_license | //*************************************
// book1(RT in 1 weekend) ch0&1
// ԭ飬¹ܣ
// *(ch00&01)Ϊpngʽ
// *(ch00&01)Ⱦ
//*************************************
// from https://github.com/nothings/stb.git
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include <iostream>
int main() {
// width, height, channels of image
int nx = 1920; // width
int ny = 1080; // height
int channels = 3;
// 洢ͼ
unsigned char *data = new unsigned char[nx*ny*channels];
// ѭͼnx*nyеÿ
for (int j = ny - 1; j >= 0; j--) {
for (int i = 0; i < nx; i++) {
float r = float(i) / float(nx);
float g = float(j) / float(ny);
float b = 0.2f;
int ir = int(255.99*r);
int ig = int(255.99*g);
int ib = int(255.99*b);
// data[y*width*channels + x*channels + index]
data[(ny - j - 1)*nx*3 + 3 * i] = ir;
data[(ny - j - 1)*nx*3 + 3 * i + 1] = ig;
data[(ny - j - 1)*nx*3 + 3 * i + 2] = ib;
}
// Ⱦ
std::cout << (ny - j) / float(ny) * 100.0f << "%\n";
}
// дpngͼƬ
stbi_write_png("ch00&01.png", nx, ny, channels, data, 0);
std::cout << "Completed.\n";
system("PAUSE");
} | true |
d61e66365db06a766ed9e89307158b15981a0fe7 | C++ | vgromov/esfwx | /escore/EsSyncObjects.win.cxx | UTF-8 | 4,897 | 2.8125 | 3 | [] | no_license | // Mutex
//
EsMutex::EsMutex(EsMutex::Type type /*= typeDefault*/) :
m_type(type),
m_owningThreadId(0),
m_mx(0)
{
m_mx = ::CreateMutex( 0, // default secutiry attributes
FALSE, // not initially locked
0 // no name
);
if( 0 == m_mx )
EsException::ThrowOsError(EsUtilities::osErrorCodeGet());
}
//---------------------------------------------------------------------------
EsMutex::~EsMutex()
{
if( m_mx )
{
::CloseHandle( m_mx );
m_mx = 0;
}
}
//---------------------------------------------------------------------------
bool EsMutex::isOk() const
{
return 0 != m_mx;
}
//---------------------------------------------------------------------------
EsMutex::Result EsMutex::lock(ulong ms)
{
if( m_type != typeRecursive &&
0 != m_owningThreadId &&
m_owningThreadId == EsThread::currentIdGet() )
return resultDeadlock;
if( !isOk() )
return resultInvalid;
esU32 rc = ::WaitForSingleObject(m_mx, ms);
switch( rc )
{
case WAIT_ABANDONED:
// the previous caller died without releasing the mutex, so even
// though we did get it, log a message about this
ES_DEBUG_TRACE(esT("WaitForSingleObject() returned WAIT_ABANDONED"));
// fall through
case WAIT_OBJECT_0:
// ok
break;
case WAIT_TIMEOUT:
return resultTimeout;
default:
ES_FAIL;
// fall through
case WAIT_FAILED:
return resultError;
}
if(m_type == typeDefault) // required for checking recursion
m_owningThreadId = EsThread::currentIdGet();
return resultOk;
}
//---------------------------------------------------------------------------
EsMutex::Result EsMutex::unlock()
{
// required for checking recursion
m_owningThreadId = 0;
if( !isOk() )
return resultInvalid;
if( !::ReleaseMutex(m_mx) )
return resultError;
return resultOk;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Critical section
//
EsCriticalSection::EsCriticalSection()
{
::InitializeCriticalSection(&m_cs);
}
//---------------------------------------------------------------------------
EsCriticalSection::~EsCriticalSection()
{
::DeleteCriticalSection(&m_cs);
}
//---------------------------------------------------------------------------
void EsCriticalSection::enter()
{
::EnterCriticalSection(&m_cs);
}
//---------------------------------------------------------------------------
bool EsCriticalSection::tryEnter()
{
return 0 != ::TryEnterCriticalSection(&m_cs);
}
//---------------------------------------------------------------------------
void EsCriticalSection::leave()
{
::LeaveCriticalSection(&m_cs);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Semaphore
//
EsSemaphore::EsSemaphore( ulong initialCount /*= 0*/, ulong maxCount /*= 0 */) :
m_sem(0)
{
if( maxCount == 0 ) // make it practically infinite
maxCount = INT_MAX;
if( initialCount > maxCount )
initialCount = maxCount;
m_sem = ::CreateSemaphore(0, // default security attributes
initialCount,
maxCount,
0 // no name
);
if( 0 == m_sem )
EsException::ThrowOsError(EsUtilities::osErrorCodeGet());
}
//---------------------------------------------------------------------------
EsSemaphore::~EsSemaphore()
{
if( m_sem )
{
::CloseHandle(m_sem);
m_sem = 0;
}
}
//---------------------------------------------------------------------------
bool EsSemaphore::isOk() const
{
return 0 != m_sem;
}
//---------------------------------------------------------------------------
EsSemaphore::Result EsSemaphore::wait(ulong ms)
{
if( !isOk() )
return resultInvalid;
esU32 rc = ::WaitForSingleObject( m_sem, ms );
switch( rc )
{
case WAIT_OBJECT_0:
return resultOk;
case WAIT_TIMEOUT:
return resultTimeout;
}
return resultError;
}
//---------------------------------------------------------------------------
EsSemaphore::Result EsSemaphore::post()
{
if( !isOk() )
return resultInvalid;
if( !::ReleaseSemaphore(m_sem, 1, 0) )
{
if( ERROR_TOO_MANY_POSTS == EsUtilities::osErrorCodeGet() )
return resultOverflow;
else
{
ES_DEBUG_TRACE(esT("EsSemaphore::post result in error"));
return resultError;
}
}
return resultOk;
}
//---------------------------------------------------------------------------
| true |
e5170554d3777e058d40a18fc0b0022db6f2549d | C++ | sdegtiarev/mtsp | /t7.cc | UTF-8 | 459 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include "alt.h"
auto data=alt::shared_ptr<int>(0);
void read_data() {
for(;;)
auto sp=data;
}
int main()
{
alt::shared_ptr<int> p(1);
std::cout<<*p<<std::endl;
auto q=p; ++*q;
std::cout<<*p<<std::endl;
auto r=std::move(q); ++*r;
std::cout<<*p<<std::endl;
p=alt::shared_ptr<int>(*r+1);
std::cout<<*p<<std::endl;
std::thread(read_data).detach();
for(;;)
data=alt::shared_ptr<int>(0);
return 0;
}
| true |
7db97a7ef371e0bc1e51ca4b8b82e02776642305 | C++ | PCBob/MPF | /src/MPF.Platform/Media/FontFamily.cpp | UTF-8 | 2,158 | 2.515625 | 3 | [] | no_license | //
// MPF Platform
// Font Family
// 作者:SunnyCase
// 创建时间:2016-08-09
//
#include "stdafx.h"
#include "FontFamily.h"
using namespace WRL;
HRESULT __stdcall GetSystemFontFaceLocation(BSTR faceName, BSTR* location) noexcept
{
try
{
static const LPWSTR fontRegistryPath = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
HKEY hKey;
std::wstring wsFaceName(faceName, SysStringLen(faceName));
// Open Windows font registry key
ThrowWin32IfNot(RegOpenKeyEx(HKEY_LOCAL_MACHINE, fontRegistryPath, 0, KEY_READ, &hKey) == ERROR_SUCCESS);
auto fin = make_finalizer([&] {RegCloseKey(hKey); });
DWORD maxValueNameSize, maxValueDataSize;
ThrowWin32IfNot(RegQueryInfoKey(hKey, 0, 0, 0, 0, 0, 0, 0, &maxValueNameSize, &maxValueDataSize, 0, 0) == ERROR_SUCCESS);
DWORD valueIndex = 0;
auto valueName = std::make_unique<WCHAR[]>(maxValueNameSize);
auto valueData = std::make_unique<BYTE[]>(maxValueDataSize);
DWORD valueNameSize, valueDataSize, valueType;
std::wstring wsFontFile;
LONG result;
// Look for a matching font name
do {
wsFontFile.clear();
valueDataSize = maxValueDataSize;
valueNameSize = maxValueNameSize;
result = RegEnumValue(hKey, valueIndex, valueName.get(), &valueNameSize, 0, &valueType, valueData.get(), &valueDataSize);
valueIndex++;
if (result != ERROR_SUCCESS || valueType != REG_SZ) {
continue;
}
std::wstring wsValueName(valueName.get(), valueNameSize);
// Found a match
if (_wcsnicmp(wsFaceName.c_str(), wsValueName.c_str(), wsFaceName.length()) == 0) {
wsFontFile.assign((LPWSTR)valueData.get(), valueDataSize);
break;
}
} while (result != ERROR_NO_MORE_ITEMS);
ThrowIfNot(!wsFontFile.empty(), L"Cannot find font file.");
if(wsFontFile.length() >= 2 && wsFontFile[1] == L':')
*location = _bstr_t(wsFontFile.c_str()).Detach();
else
{
// Build full font file path
WCHAR winDir[MAX_PATH];
ThrowWin32IfNot(GetWindowsDirectory(winDir, MAX_PATH));
std::wstringstream ss;
ss << winDir << "\\Fonts\\" << wsFontFile;
*location = _bstr_t(ss.str().c_str()).Detach();
}
return S_OK;
}
CATCH_ALL();
} | true |
63734a7e545979b2a7a927b13a4895046f6523be | C++ | google-code/afti-2013-oop-nsu | /Kutlimetov/scrambler_1/scrambler_1/Scrambler.h | WINDOWS-1251 | 908 | 3.46875 | 3 | [] | no_license | #pragma once
#include <vector>
template <class T>
class Scrambler {
public:
Scrambler(const int onesNumber);
void ScrambleData(const T & data, T & outdata) const; //const , " " - , , .
int oneNumber;
};
template <class T>
Scrambler<T>::Scrambler(const int onesNumber) {
oneNumber = onesNumber;
}
template <class T>
void Scrambler<T>::ScrambleData(const T & data, T & outdata) const
{
int i, counter = 0;
for (i = 0; i < data.size(); i++)
{
if (data[i] == 1){
counter++;
}
else{
counter = 0;
}
if (counter == oneNumber){
outdata.push_back(data[i]);
outdata.push_back(0);
counter = 0;
}
else{
outdata.push_back(data[i]);
}
}
}
| true |
d58fbc5090a15252fa520b5166a0bbc48b46cd9e | C++ | EvanSpeciale/cs162_battle_sim | /Menu.cpp | UTF-8 | 9,470 | 3.546875 | 4 | [] | no_license | /******************************************************************************
** Name: Evan Speciale
** Date: July 30, 2019
** Description: Character class implementation
******************************************************************************/
#include "Menu.hpp"
#include "Character.hpp"
#include "Vampire.hpp"
#include "Barbarian.hpp"
#include "BlueMen.hpp"
#include "Medusa.hpp"
#include "HarryPotter.hpp"
#include <iostream>
#include <climits>
using std::cin;
using std::cout;
using std::endl;
/******************************************************************************
Menu default constructor just prints some into lines
******************************************************************************/
Menu::Menu()
{
cout << "Welcome to Fantasy Battle Simulator 2k19" << endl
<< "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << endl << endl;
}
/******************************************************************************
prompts the user to choose two fighters. Verifies user input and then creates
a new instance of the chosen class and has the fighter1 and fighter2 Character
pointers point at the new object.
******************************************************************************/
void Menu::chooseFighters()
{
int choice;
bool valid;
//prompts user to select first fighter
do
{
cin.clear();
cout << "Choose two fighters to duel to the death!" << endl
<< "-----------------------------------------" << endl
<< "1 - Vampire" << endl
<< "2 - Barbarian" << endl
<< "3 - Blue Men" << endl
<< "4 - Medusa" << endl
<< "5 - Harry Potter" << endl
<< endl;
cout << "Choose first fighter [1-5]: ";
cin >> choice;
valid = this->checkIntRange(1, 5, choice); //checks if input is int between 1 and 5
cout << endl;
} while (!valid);
//creates character subclass instance and points the fighter1 variable at it
switch (choice)
{
case 1:
{
fighter1 = new Vampire;
break;
}
case 2:
{
fighter1 = new Barbarian;
break;
}
case 3:
{
fighter1 = new BlueMen;
break;
}
case 4:
{
fighter1 = new Medusa;
break;
}
case 5:
{
fighter1 = new HarryPotter;
break;
}
}
//same for fighter2
do
{
cin.clear();
cout << "1 - Vampire" << endl
<< "2 - Barbarian" << endl
<< "3 - Blue Men" << endl
<< "4 - Medusa" << endl
<< "5 - Harry Potter" << endl
<< endl;
cout << "Choose second fighter [1-5]: ";
cin >> choice;
valid = this->checkIntRange(1, 5, choice); //checks if input is int between 1 and 5
cout << endl;
} while (!valid);
switch (choice)
{
case 1:
{
fighter2 = new Vampire;
break;
}
case 2:
{
fighter2 = new Barbarian;
break;
}
case 3:
{
fighter2 = new BlueMen;
break;
}
case 4:
{
fighter2 = new Medusa;
break;
}
case 5:
{
fighter2 = new HarryPotter;
break;
}
}
}
/******************************************************************************
The main fight loop has the first fighter attack, checks if the second fighter
is still alive, and, if so, the second fighter attacks. If either fighter dies
during the round, the loop calls to the hogwarts function of the dead character
and revives them if possible. The loop then increments the round counter and
loops again if both fighters are still alive. After one fighter wins, announces
the winner and deletes the character objects.
******************************************************************************/
void Menu::fight()
{
int roundCount = 1;
do
{
cout << "====================ROUND "<<roundCount<<"====================" << endl << endl;
this->fighter1Attack();
if (fighter2->getStrengthPoints() > 0)
{
this->fighter2Attack();
if (fighter1->getStrengthPoints() <= 0)
{
fighter1->hogwarts();
}
}
else
{
fighter2->hogwarts();
}
roundCount++;
} while (fighter1->getStrengthPoints() > 0 && fighter2->getStrengthPoints() > 0);
if (fighter1->getStrengthPoints() <= 0)
{
cout << "Fighter 2 Wins!!" << endl << endl;
}
else if (fighter2->getStrengthPoints() <= 0)
{
cout << "Fighter 1 Wins!!" << endl << endl;
}
delete fighter1;
delete fighter2;
fighter1 = nullptr;
fighter2 = nullptr;
}
/******************************************************************************
Function prints information about attacker and defender. If one or both of the
fighters are vampires, sets the "charmed" status on the vampire's opponent.
The function then rolls attack and defense, then calculates the damage to the
defender. If the damage is 0 or less, prints "NO DAMAGE" instead. Prints the
defender's remaining strength points.
******************************************************************************/
void Menu::fighter1Attack()
{
//prints attacker and defender stats
cout << "========================================" << endl
<< "|| Attacker:\t" << fighter1->getCharType() << endl
<< "========================================" << endl
<< "|| Defender:\t" << fighter2->getCharType() << endl
<< "|| Armor Rating:\t" << fighter2->getArmor() << endl
<< "|| Strength Points:\t" << fighter2->getStrengthPoints() << endl
<< "========================================" << endl << endl;
//sets charmed status if opponent is a vampire
if (fighter2->isVampire())
{
if (fighter1->isVampire())
{
cout << "The Vampires remembers how gross it is to be a vampire with all the blood" << endl
<< "and coffins stuff and resist their opponent's charm!" << endl << endl;
}
else
{
fighter1->setCharmed();
}
}
//rolls attack and defense, calculates damage to defender
fighter1->rollAttack();
fighter2->rollDefense();
int damage = fighter1->getAttack() - fighter2->getDefense() - fighter2->getArmor();
fighter2->doDamage(damage);
//displays damage calculation
cout << "========================================" << endl
<< "|| Attack Roll:\t\t" << fighter1->getAttack() << endl
<< "|| Defense Roll:\t" << fighter2->getDefense() << endl
<< "|| Armor Rating:\t" << fighter2->getArmor() << endl
<< "|| ---------------------------" << endl
<< "|| Total Damage:\t";
//prints total damage or NO DAMAGE if damage is 0 or less
if (damage <= 0)
{
cout << "NO DAMAGE!";
}
else
{
cout << damage;
}
cout << endl
<< "||" << endl
<< "|| Fighter 2's Strength Points:\t" << fighter2->getStrengthPoints() << endl
<< "========================================" << endl << endl;
}
/******************************************************************************
same as fighter1Attack function
******************************************************************************/
void Menu::fighter2Attack()
{
cout << "========================================" << endl
<< "|| Attacker:\t" << fighter2->getCharType() << endl
<< "========================================" << endl
<< "|| Defender:\t" << fighter1->getCharType() << endl
<< "|| Armor Rating:\t" << fighter1->getArmor() << endl
<< "|| Strength Points:\t" << fighter1->getStrengthPoints() << endl
<< "========================================" << endl << endl;
if (fighter1->isVampire())
{
fighter2->setCharmed();
}
fighter2->rollAttack();
fighter1->rollDefense();
int damage = fighter2->getAttack() - fighter1->getDefense() - fighter1->getArmor();
fighter1->doDamage(damage);
cout << "========================================" << endl
<< "|| Attack Roll:\t\t" << fighter2->getAttack() << endl
<< "|| Defense Roll:\t" << fighter1->getDefense() << endl
<< "|| Armor Rating:\t" << fighter1->getArmor() << endl
<< "|| ---------------------------" << endl
<< "|| Total Damage:\t";
if (damage <= 0)
{
cout << "NO DAMAGE!";
}
else
{
cout << damage;
}
cout << endl
<< "||" << endl
<< "|| Fighter 1's Strength Points:\t" << fighter1->getStrengthPoints() << endl
<< "========================================" << endl << endl;
}
/******************************************************************************
prompts the user to play again or quit. If user chooses to quit, returns false
and exits the gameplay loop in the main function
******************************************************************************/
bool Menu::replay()
{
int choice;
bool valid;
bool loop = true;
do
{
cin.clear();
cout << "Play Again?" << endl
<< "-----------" << endl
<< "1 - Play Again" << endl
<< "2 - Quit Program" << endl << endl;
cout << "Enter Selection: ";
cin >> choice;
valid = this->checkIntRange(1, 2, choice); //checks if input is int between 1 and 5
cout << endl;
} while (!valid);
switch (choice)
{
case 1:
{
loop = true;
break;
}
case 2:
{
loop = false;
break;
}
}
return loop;
}
/******************************************************************************
input validation function checks if input is within chosen range
******************************************************************************/
bool Menu::checkIntRange(int min, int max, int input)
{
if (input < min || input > max)
{
cout << "Please enter a valid choice [" << min << "-" << max << "]" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
return false;
}
else
{
return true;
}
} | true |
4c1cf39daa4a839809d7e7864523cfd1595c758e | C++ | AltSysrq/Abendstern | /src/net/windows_firewall_opener.hxx | UTF-8 | 1,364 | 2.90625 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef WINDOWS_FIREWALL_OPENER_HXX_
#define WINDOWS_FIREWALL_OPENER_HXX_
/**
* @file
* @author Jason Lingle
* @date 2012.04.18
* @brief Provides the WindowsFirewallOpener class
*/
class Antenna;
/**
* Sends packets to open the Windows firewall.
*
* Normally, Abendstern would require a Windows firewall exception to work on
* LAN games, since it requires receiving a unicast packet from an unknown
* source. However, non-administrators do not have the privelages needed to add
* an exception.
*
* But, according to the Windows Firewall Technical Reference, "When a
* computer sends a multicast or broadcast message, Windows Firewall waits for
* up to 3 seconds for a unicast response."
*
* This class will send an empty broadcast packet once four seconds, to keep
* this rule active. This means that no firewall exception is necessary. (The
* four second interval allows Windows to forget the "connection" and start a
* new one.)
*
* @see http://technet.microsoft.com/en-us/library/cc755604(v=ws.10).aspx#BKMK_protocols
*/
class WindowsFirewallOpener {
Antenna*const antenna;
unsigned timeSinceTransmission;
public:
///Creates the WindowsFirewallOpener for the given Antenna
WindowsFirewallOpener(Antenna*);
///Updates the timer and may send a packet.
void update(unsigned) throw();
};
#endif /* WINDOWS_FIREWALL_OPENER_HXX_ */
| true |
2e2943b1b31a975fa0ae148b4db60ddcadc9d251 | C++ | nicksya/XLFileSorter | /Indexer/Utils.cpp | UTF-8 | 1,003 | 2.8125 | 3 | [] | no_license | //
// indexer.cpp
// Indexer
//
// Created by Mykyta on 29.04.17.
// Copyright © 2017 Mykyta Khomenko. All rights reserved.
//
#include "Utils.hpp"
using namespace std;
void tryFile(std::fstream& stream, std::string& path, std::ios_base::openmode mode) {
stream.open(path, mode);
if (!stream.is_open()){
stream.close();
std::cout << "Cannot access the file " << path << " !\nTerminating.\n"<< std::endl;
exit (EXIT_FAILURE);
}
}
bool fileExists(std::string& filename) {
ifstream file(filename);
if ( file ) return true;
return false;
}
unsigned long long getFileSize(std::string& filePath) {
unsigned long long length = 0;
std::ifstream is(filePath, std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
length = is.tellg();
is.close();
return length;
}
std::cout << "Cannot access the file " << filePath << " !\nExiting now\n"<< std::endl;
exit (EXIT_FAILURE);
};
| true |
676f308032a2b586fcb4275a18327adb276b53d4 | C++ | bsumirak/AoC | /AoC2022/day08.h | UTF-8 | 1,148 | 3.125 | 3 | [] | no_license | /*
* day08.h
*
* Created on: 2022-12-08
* Author: mbreit
*/
template <>
void executeDay<8>(const std::string& fn)
{
// read input
std::vector<char> v;
{
std::ifstream infile(fn.c_str());
char c;
while (infile >> c)
v.push_back(c);
infile.close();
}
const std::size_t sz = v.size();
unsigned resA = 0;
unsigned resB = 0;
for (size_t t = 0; t < sz; ++t)
{
bool vis = false;
unsigned score = 1;
unsigned dist = 0;
size_t s;
// to top
for (s = t; s >= 99; s -= 99)
{
++dist;
if (v[s - 99] >= v[t])
break;
}
vis |= s < 99;
score *= dist;
// to bottom
for (s = t, dist = 0; s < 98*99; s += 99)
{
++dist;
if (v[s + 99] >= v[t])
break;
}
vis |= s >= 98*99;
score *= dist;
// to left
for (s = t, dist = 0; s % 99 > 0; --s)
{
++dist;
if (v[s-1] >= v[t])
break;
}
vis |= s % 99 == 0;
score *= dist;
//to right
for (s = t, dist = 0; s % 99 < 98; ++s)
{
++dist;
if (v[s+1] >= v[t])
break;
}
vis |= s % 99 == 98;
score *= dist;
// evaluate
resA += vis;
resB = std::max(resB, score);
}
writeSolution(resA, resB);
}
| true |
54523103655e41d676050fd39796956f754951b6 | C++ | JustBeYou/infoarena | /codeforces/agm20_computer_error.cpp | UTF-8 | 4,192 | 2.6875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef unsigned int uint;
struct cond {
char op;
int num;
bool real;
bool operator< (const cond& rhs) const {
return num < rhs.num;
}
bool operator== (const cond& rhs) const {
return num == rhs.num;
}
};
vector<cond> normalize(vector<cond> A) {
vector<cond> S(A), N(A.size()); // O(2N)
sort(S.begin(), S.end()); // O (N * log N)
for(uint i = 0; i < A.size(); ++i) { // O(N)
auto found = lower_bound(S.begin(), S.end(), A[i]); // O(log N)
N[i].num = found - S.begin();
while (*found == A[i] and found->op == '!') { // O(3)
++found;
}
N[i].op = found->op;
N[i].real = found->real;
found->op = '!';
}
sort(N.begin(), N.end()); // O(N * log N)
return N;
}
void solve(uint m, vector<cond>& conditions) {
sort(conditions.begin(), conditions.end()); // O(N * log N)
for (uint i = 0; i < m - 1; i++) { // O(N)
if (conditions[i].num + 1 < conditions[i + 1].num) {
conditions.push_back({'#', conditions[i].num + 1, true});
}
}
conditions.push_back({'#', 1000000000 + 1, true});
conditions.push_back({'#', 0, true});
auto normalized = normalize(conditions);
vector<uint> satisf(normalized.size(), 0);
uint to_add = 0;
for (uint i = 0; i < normalized.size(); i++) { // O(3 * N)
satisf[normalized[i].num] += to_add;
uint old = i;
while (normalized[old].num == normalized[i].num) {
switch(normalized[i].op) {
case '=':
if (normalized[i].real) satisf[normalized[i].num]++;
else { to_add += 1; }
break;
case '<':
if (not normalized[i].real) {
satisf[normalized[i].num]++;
to_add++;
}
break;
case '>':
if (normalized[i].real) {
to_add++;
}
break;
case '#':
break;
}
i++;
if (i >= normalized.size()) break;
}
i--;
}
to_add = 0;
for (int i = normalized.size() - 1; i >= 0; i--) { // O(3 * N)
satisf[normalized[i].num] += to_add;
int old = i;
while (normalized[old].num == normalized[i].num) {
switch(normalized[i].op) {
case '<':
if (normalized[i].real) {
to_add++;
}
break;
case '>':
if (not normalized[i].real) {
satisf[normalized[i].num]++;
to_add++;
}
break;
case '#':
break;
}
i--;
if (i < 0) break;
}
i++;
}
//for (auto it: normalized) {
// cout << it.op << " " << it.num << " " << (it.real ? "true" : "false") << endl;
//}
uint max_satisf = 0;
for (auto it: satisf) { // O(N)
max_satisf = max(it, max_satisf);
//cout << it << " ";
}
//cout << endl;
cout << m - max_satisf << endl;
}
int main() {
cin.tie(0);
ios_base::sync_with_stdio(0);
freopen("inp.in", "r", stdin);
vector<cond> conditions;
uint n;
cin >> n;
for (uint i = 0; i < n; i++) { // O (N)
uint m;
cin >> m;
if (i == 0) conditions.reserve(m);
char op; int num; string real;
for (uint j = 0; j < m; j++) { // O(M)
cin >> op >> num >> real;
if (real[0] == 'T') {
conditions.push_back({op, num, true});
//cout << op << " " << num << " " << true << endl;
} else {
conditions.push_back({op, num, false});
//cout << op << " " << num << " " << false << endl;
}
}
solve(m, conditions);
conditions.clear();
}
return 0;
}
| true |
47f98df3c052eb894e3a6e2bae44e05b26a4c46d | C++ | CmdrFop/Practical2 | /GroupsBuilder.hpp | UTF-8 | 481 | 2.59375 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include <tuple>
#include "Group.hpp"
#include <map>
using namespace std;
class GroupsBuilder {
public:
void create_groups(int number_of_products, int number_of_dividers, vector<int> all_costs);
int round(int cost);
tuple<int, vector<string>, int, string, int, string> recursion_solution(string group, vector<int> cost, int max_divisions, vector<string> elements, int group_cost, int other_item_cost, string not_in_group);
}; | true |
d8c565342d81156328dbfcf21a7bcb61472f7e49 | C++ | Trinhnt3027/Utility | /Utility/src/Logger/Logger.cpp | UTF-8 | 6,285 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <sstream>
#include <algorithm>
#include <mutex>
#include <fstream>
#include <boost/filesystem.hpp>
#ifdef _WIN32
#else
#include <unistd.h>
#include <sys/syscall.h>
#endif
#include "Logger/Logger.h"
#include "TimeHelper/TimeHelper.h"
using namespace Utility::Logger;
using namespace Utility::TimeHelper;
namespace fs = boost::filesystem;
class Logger::LoggerImlp {
public:
LoggerImlp();
void initialize(const std::string &appName, const std::list<LogOutput>& logOutput);
void initialize(const std::string &appName, const std::string &logPath, const std::list<LogOutput>& logOutput);
void writeLog(const LogType &type, const std::string &logData);
private:
void initLogEnable();
void initLogFile();
public:
std::string m_appName;
std::string m_logPath;
private:
fs::path m_fsPath;
std::string m_logFilePrefix;
u_int8_t m_fileCout;
std::list<LogOutput> m_logOutput;
bool m_enableLogConsole;
bool m_enableLogFile;
bool m_enableLog;
const std::map<LogType, std::string> m_LogName
{
{LogType::INFO, "INF"},
{LogType::DEBUG, "DBG"},
{LogType::WARNING, "WAR"},
{LogType::ERROR, "ERR"}
};
std::mutex m_mutex;
private:
const uint64_t m_MaxFileSize = uint64_t(5242880); // 5MB * 1024
const u_int8_t m_maxFileCount = 5;
};
Logger::LoggerImlp::LoggerImlp()
: m_appName("")
, m_logPath("")
, m_logFilePrefix("")
, m_fileCout(0)
, m_logOutput{}
, m_enableLogConsole(false)
, m_enableLogFile(false)
, m_enableLog(false)
{
}
void Logger::LoggerImlp::initialize(const std::string &appName, const std::list<LogOutput> &logOutput)
{
m_appName = appName;
m_logOutput = logOutput;
initLogEnable();
initLogFile();
}
void Logger::LoggerImlp::initialize(const std::string &appName, const std::string &logPath, const std::list<LogOutput> &logOutput)
{
m_logPath = logPath;
initialize(appName, logOutput);
}
void Logger::LoggerImlp::writeLog(const LogType &type, const std::string &logData)
{
if ((m_enableLog) && (m_appName.empty() == false)) {
std::stringstream outLog;
unsigned long pid;
unsigned long tid;
#ifdef _WIN32
#else
pid = syscall(__NR_getpid);
tid = syscall(__NR_gettid);
#endif
outLog << TimeHelper::TimeHelper::getInstance().getCurrentDateTime().toString(TimeFormat::yyyy_MM_dd, TimeExtension::MICRO_SEC)
<< " " << m_LogName.at(type) << " " << m_appName
<< " " << "[" << pid << ":" << tid << "]" << logData;
std::string logData = outLog.str();
// Enable console log
if (m_enableLogConsole) {
std::lock_guard<std::mutex> guard(m_mutex);
std::cout << logData;
}
//Enable file log
if (m_enableLogFile) {
std::lock_guard<std::mutex> guard(m_mutex);
if (fs::file_size(m_fsPath) > m_MaxFileSize) {
if (m_fileCout == m_maxFileCount) {
//remove the first log file
fs::path previousLogFile = fs::path(m_logPath) / (m_logFilePrefix + "1.log");
fs::remove(previousLogFile);
//shift file
for (uint8_t i = 2; i <= m_fileCout; i++) {
fs::path nextLogFile = fs::path(m_logPath) / (m_logFilePrefix + std::to_string(i) + ".log");
fs::rename(nextLogFile, previousLogFile);
previousLogFile = nextLogFile;
}
}
else {
m_fileCout++;
m_fsPath = fs::path(m_logPath) / (m_logFilePrefix + std::to_string(m_fileCout) + ".log");
}
}
std::ofstream outFile{m_fsPath.string().c_str(), std::ios::out | std::ios::app};
outFile << logData;
outFile.flush();
outFile.close();
}
}
}
void Logger::LoggerImlp::initLogEnable()
{
m_enableLogConsole = std::find(m_logOutput.begin(), m_logOutput.end(), LogOutput::CONSOLE) != m_logOutput.end();
m_enableLogFile = std::find(m_logOutput.begin(), m_logOutput.end(), LogOutput::FILE) != m_logOutput.end();
m_enableLog = m_enableLogFile || m_enableLogConsole;
}
void Logger::LoggerImlp::initLogFile()
{
if (m_logPath.empty()) {
m_fsPath = fs::current_path();
m_logPath = m_fsPath.string();
}
else {
m_fsPath = fs::path(m_logPath);
}
if (fs::exists(m_fsPath) == false) {
fs::create_directory(m_fsPath);
}
m_logFilePrefix = m_appName;
fs::path logFilePath = m_fsPath / (m_logFilePrefix + "1.log");
if (fs::exists(logFilePath) == false) {
m_fsPath = logFilePath;
m_fileCout = 1;
std::ofstream logFile{logFilePath.string().c_str(), std::ios::out};
logFile.close();
}
else {
int idx = 1;
std::string logFileTmp = m_logFilePrefix;
fs::path lastFilePath;
do {
idx++;
lastFilePath = logFilePath;
logFileTmp =m_logFilePrefix + std::to_string(idx);
logFilePath = m_fsPath / (logFileTmp + ".log");
} while (fs::exists(logFilePath));
m_fsPath = lastFilePath;
m_fileCout = idx - 1;
}
}
/*******************************************/
Logger* Logger::mInstancePtr = nullptr;
Logger::Logger()
{
mImplPtr = std::make_unique<LoggerImlp>();
}
Logger &Logger::getInstance()
{
if (mInstancePtr == nullptr) {
mInstancePtr = new Logger();
}
return *mInstancePtr;
}
void Logger::initialize(const std::string &appName, const std::list<LogOutput>& logOutput)
{
mImplPtr->initialize(appName, logOutput);
}
void Logger::initialize(const std::string &appName, const std::string &logPath, const std::list<LogOutput>& logOutput)
{
mImplPtr->initialize(appName, logPath, logOutput);
}
std::string Logger::getAppName() const
{
return mImplPtr->m_appName;
}
std::string Logger::getLogPath() const
{
return mImplPtr->m_logPath;
}
void Logger::writeLog(const LogType &type, const std::string &logData)
{
mImplPtr->writeLog(type, logData);
}
| true |
0403ff24e89a155a2941ab274c98abd32022edac | C++ | 96189/xteam | /算法/leetcode/989.数组形式的整数加法.cpp | UTF-8 | 1,702 | 3.328125 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=989 lang=cpp
*
* [989] 数组形式的整数加法
*/
class Solution {
public:
vector<int> addToArrayForm(vector<int>& A, int K) {
// 转换K为数组形式
vector<int> KA;
while (K)
{
KA.push_back(K % 10);
K /= 10;
}
int lenA = A.size();
int lenKA = KA.size();
int difflen = abs(lenA - lenKA);
reverse(A.begin(), A.end());
while (difflen-- > 0)
{
if (lenKA > lenA)
{
A.push_back(0);
}
else
{
KA.push_back(0);
}
}
// 数组模式相加
vector<int> newA;
int sa = 0;
int ska = 0;
int carry = 0;
while (sa < lenA && ska < lenKA)
{
int sum = carry + A[sa] + KA[ska];
if (sum >= 10)
carry = 1;
else
carry = 0;
newA.push_back(sum % 10);
++sa;
++ska;
}
while (sa < lenA)
{
int sum = carry + A[sa];
if (sum >= 10)
carry = 1;
else
carry = 0;
newA.push_back(sum % 10);
++sa;
}
while (ska < lenKA)
{
int sum = carry + KA[ska];
if (sum >= 10)
carry = 1;
else
carry = 0;
newA.push_back(sum % 10);
++ska;
}
if (carry)
{
newA.push_back(carry);
}
reverse(newA.begin(), newA.end());
return newA;
}
};
| true |
d5cad151b2a8ddb0a1ba1e899c2ab21dfc1de054 | C++ | aavegmit/Visual-Cryptography | /stream.cc | UTF-8 | 2,181 | 3.234375 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include "stream.h"
#include <sys/types.h>
#include <openssl/md5.h>
#include <stdlib.h>
#include <string.h>
using namespace std ;
/* Constructor definition
* Takes in pphrase and len as arguments.
* The generated stream is saved in the private buffer
*/
Stream::Stream(char *pphrase, int len){
// allocate memory to sBuffer = len+1
sBuffer = (unsigned char *)malloc(len+1) ;
// Find the number of iterations needed
int loop = (len/8) ;
if (len % 8 > 0)
++loop ;
// Initialise the buffer with 0
memset(sBuffer, '\0', loop*8) ;
// Set the len private member
length = len ;
// length = loop*8 ;
// To find the length of a temp buffer
int tempLen = strlen(pphrase) + 2 + MD5_DIGEST_LENGTH ;
// Allocate temp buffer the memory
unsigned char *tempBuf = (unsigned char *)malloc(tempLen + 1) ;
// MD5 of the pphrase
unsigned char md5_buf[MD5_DIGEST_LENGTH ] ;
MD5((unsigned char*)pphrase, strlen(pphrase), (unsigned char *)md5_buf) ;
// loop to iterate for (len/8 + 1) times
for (int i = 0; i < loop ; i++){
// Initialize temp buffer
memset(tempBuf, '\0', tempLen+1) ;
// Construct the tempBuf
sprintf((char *)&tempBuf[MD5_DIGEST_LENGTH], "%02d%s", (i%100) , pphrase) ;
memcpy(tempBuf, (char *)md5_buf, MD5_DIGEST_LENGTH) ;
tempBuf[tempLen] = '\0' ;
// Find the new md5_buf
MD5((unsigned char *)tempBuf, tempLen , (unsigned char *)md5_buf) ;
// copy the first 8 bytes from tempBuf into sBuffer
memcpy(&sBuffer[i*8], md5_buf, 8) ;
}
// Terminate the buffer with null
sBuffer[len] = '\0' ;
free(tempBuf) ;
}
/*
* Returns the key stored in sBuffer
*/
unsigned char *Stream::getStream(){
return sBuffer ;
}
/*
* Displays the KEY in hex format
*/
void Stream::display(){
for (int i = 0; i < length; i++){
printf("%02x", sBuffer[i]) ;
if ((i+1)%8==0 && i!=0 )
printf("\n") ;
}
if (length)
printf("\n") ;
}
/*
* Displays the KEY in binary format
*/
void Stream::flushout(){
for (int i = 0; i < length; i++){
printf("%c", sBuffer[i]) ;
}
}
/* Destructor class
* Free up all the memory, basically cleans up
*/
Stream::~Stream(){
// free up sBuffer
}
| true |
9990daa7d3cd631c4592a2855f19a2718664f562 | C++ | Gupta-Aniket/codeforces | /800/59A.cpp | UTF-8 | 764 | 3.15625 | 3 | [] | no_license | // https://codeforces.com/problemset/problem/59/A
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
#include <iterator>
#include <map>
using namespace std;
int main()
{
// your code goes here
int upper = 0, lower = 0;
string s;
cin >> s;
int n = s.length();
vector< char > c;
copy(s.begin(), s.end(), back_inserter(c));
for(int i=0; i<n; i++){
if(isupper(c[i]))
upper ++;
else
lower ++;
}
if(upper <= lower)
for(int i=0; i<n; i++){
cout << char(tolower(c[i]));
}
else
for(int i=0; i<n; i++){
cout << char(toupper(c[i]));
}
// your code goes here
return 0;
} | true |
8cb501eb8ad4b03352e71a1e79c9448906e54314 | C++ | napylov/libeventloop | /test/src/test_fd_factory.cpp | UTF-8 | 1,292 | 3.015625 | 3 | [] | no_license | #include <unistd.h>
#include <sys/signalfd.h>
#include "test_fd_factory.h"
#include "eventloop/fd_factory.h"
bool test_fd_factory::test_create_signal_fd()
{
std::array<int, 2> sig_arr{ SIGUSR1, SIGUSR2 };
int fd = eventloop::fd_factory::create_signal_fd( sig_arr );
if ( fd < 0 )
{
std::cout << "Signal fd isn't created.\n";
return false;
}
pid_t pid = getpid();
int i = 0;
for ( auto &it : sig_arr )
{
if ( !check_signal( fd, pid, it, ++i ) )
return false;
}
return true;
}
bool test_fd_factory::check_signal( int fd, pid_t pid, int signo, int custom )
{
std::cout << __PRETTY_FUNCTION__ << "\n ";
sigval sv = { 0 };
sv.sival_int = custom;
std::cout << "Send signal " << signo << " with custom data " << custom << "\n";
sigqueue( pid, signo, sv );
usleep( 100000 );
std::cout << "Try read.\n";
signalfd_siginfo si = { 0 };
ssize_t readed = read( fd, &si, sizeof(si) );
std::cout << "readed " << readed << "\n";
if ( readed < (ssize_t)sizeof(si) )
return false;
return si.ssi_signo == static_cast<uint32_t>( signo ) && si.ssi_int == custom;
}
TEST_F( test_fd_factory, test_create_signal_fd )
{
ASSERT_TRUE( test_create_signal_fd() );
}
| true |
9c4ae8bd9065b62b81ff142a8f38ea683b1ca548 | C++ | franciscoSoler/nebla | /distribuidos/EjGrupal_Robot5/src/IPC/SharedMemory/EstadoRobot11SharedMemory.cpp | UTF-8 | 543 | 2.578125 | 3 | [] | no_license | #include "EstadoRobot11SharedMemory.h"
//-----------------------------------------------------------------------------
size_t EstadoRobot11SharedMemory::getMemorySize() {
return sizeof(bool);
}
//-----------------------------------------------------------------------------
bool *EstadoRobot11SharedMemory::readInfo () {
return (bool*)(this->data);
}
//-----------------------------------------------------------------------------
void EstadoRobot11SharedMemory::writeInfo ( bool *dato ) {
memcpy(this->data, dato, sizeof(bool));
} | true |
512cc4ab3e8d28fb40c252053c9c4ce5a3be1c6e | C++ | King-01/AlgorithmsLab | /bstimplementation.cpp | UTF-8 | 5,071 | 3.703125 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct node{
int val;
node *left, *right;
node(int a)
{
val = a;
left = NULL;
right = NULL;
}
};
class BST{
private:
node* head;
public:
BST()
{
head = NULL;
}
void assigner(int val, int i)
{
if(i == 1)insert(val);
else if(i == 2){
int presence = present(val);
if(presence == 1)
{
cout << "Element is present in BST" << endl;
}
else if(presence == 2)
cout << "Element is not present in BST" << endl;
}
else if(i == 3)traverse();
else deletenode(val);
}
void insert(int val)
{
node *temp = new node(val);
if(head == NULL)
{
head = temp;
}
else
{
node *pointer = head;
while(true)
{
if(pointer->val >= val){
if(pointer->left!=NULL)
pointer = pointer->left;
else{
pointer->left = temp;
break;
}
}
else{
if(pointer->right!=NULL)
pointer = pointer->right;
else
{
pointer->right = temp;
break;
}
}
}
}
cout << "Insertion Successful!" << endl;
}
int present(int val)
{
if(head == NULL)
{
cout << "The tree is empty!" << endl;
return 3;
}
node *pointer = head;
while(true)
{
if(val == pointer->val)
{
return 2;
}
if(val > pointer->val)
{
if(pointer->right == NULL)return 1;
pointer = pointer->right;
}
else{
if(pointer->left == NULL)return 1;
pointer = pointer->left;
}
}
}
void traverse()
{
if(head == NULL)
{
cout << "The tree is empty!" << endl;
return ;
}
node *pointer = head;
stack <node*> s;
node *cur = head;
cout << "Tree:" << endl;
while(cur != NULL || !s.empty())
{
while(cur!=NULL)
{
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
cout << cur->val << " ";
cur = cur->right;
}
cout << endl;
}
void deletenode(int val)
{
int ok = present(val);
if(ok == 1)
{
cout << "Node not in BST" << endl;
return;
}
else if(ok == 3)return;
else
{
cout<<"Node " << val << " was deleted successfully!" << endl;
if(head->val == val)
{
if(head->left == NULL)
{
head = head->right;
}
else
{
if(head->right == NULL)
head = head->left;
else
{
node *replacement = head->left, *parent;
while(replacement->right != NULL){
parent = replacement;
replacement = replacement->right;
}
node *dummy = replacement;
if(replacement == head->left)
{
replacement->right = head->right;
head = replacement;
return;
}
if(replacement->left != NULL)
parent->right = replacement->left;
else
parent->right = 0;
head->val = dummy->val;
return;
}
}
}
else
{
node *pointer = head, *parent = head;
while(val != pointer->val)
{
parent = pointer;
if(val > pointer->val)pointer = pointer->right;
else
pointer = pointer->left;
}
if(pointer->left == NULL)
{
if(pointer->right == NULL)
{
if(parent->right == pointer)parent->right = NULL;
else parent->left = NULL;
}
else
{
pointer->val = pointer->right->val;
pointer->left = pointer->right->left;
pointer->right = pointer->right->right;
}
}
else
{
if(pointer->right == NULL)
{
pointer->val = pointer->left->val;
pointer->left = pointer->left->left;
pointer->right = pointer->left->right;
}
else
{
node *nextparent = pointer, *replacement = pointer->left;
while(replacement->right != NULL)
{
nextparent = replacement;
replacement = replacement->right;
}
if(nextparent == pointer)
{
pointer->val = replacement->val;
pointer->left = replacement->left;
return;
}
else
{
pointer->val = replacement->val;
replacement = replacement->left;
return;
}
}
}
}
}
}
};
int main()
{
cout << "---------------Welcome---------------" << endl;
int input = 1;
BST tree;
int flag = 1;
while(input-5)
{
if(!(flag-1)){
cout << "Select one of the operations to execute:" << endl;
cout << "1. Insert" << endl;
cout << "2. Search" << endl;
cout << "3. Inorder Traversal" << endl;
cout << "4. Delete" << endl;
cout << "5. Quit" << endl;
}
cout << "Select operations from above-";
cin >> input;
int val = 0;
if(input-3&&input<5)
{
cout << "Enter value of the node" << endl;
cin >> val;
}
if(input<5)
tree.assigner(val, input);
else if(input > 5){
cout << "Invalid Input, please try again!" << endl;
continue;
}
flag++;
}
cout << "Thank You!" << endl;
return 0;
} | true |
0922afd35c340b63f72bc11b8824cf9bcd441754 | C++ | Nillouise/Algorithm | /Algorithm/CF/Codeforces Round #435/C. Mahmoud and Ehab and the xor.cpp | UTF-8 | 1,707 | 2.78125 | 3 | [] | no_license | //这是错的
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int a[100000 + 5];
int one[100000 + 5];
int dfs(int b, int e, int curbit, vector<int> arr, int inverse)
{
if (curbit >= arr.size())return 0;
if (b == e)return 0;
//if (b == e - 1)return 0; 错的
if (inverse == 0)
{
for (size_t i = b; i < b + arr[curbit]; i++)
{
a[i] = a[i] | (1 << curbit);
}
}
else {
//for (size_t i = b + arr[curbit]-1; i >= b ; i--)
for (int i = b + arr[curbit] - 1; i >= b; i--)
{
a[i] = a[i] | (1 << curbit);
}
}
vector<int> arr1(arr);
vector<int> arr2(arr);
for (size_t i = 0; i < arr.size(); i++)
{
if (inverse == 0)
{
arr1[i] = arr1[i] / 2;
arr2[i] = arr2[i] / 2 + arr[i] % 2;
}
else {
arr1[i] = arr1[i] / 2 + arr[i] % 2;
arr2[i] = arr2[i] / 2;
}
//arr2[i] /= 2 + arr[i] % 2;//这里错了
}
int mid = b + (e - b) / 2;
dfs(b, mid, curbit + 1, arr1, !inverse);
//dfs(mid + 1, e, curbit + 1, arr2);错的
if (mid == b)return 0;
dfs(mid, e, curbit + 1, arr2, !inverse);
return 0;
}
int main()
{
ios::sync_with_stdio(false);
freopen("input.txt", "r", stdin);
int n, x;
cin >> n >> x;
int t = x;
vector<int> arr;
for (int i = 0; t; i++)
{
t /= 2;
if ((1 << i)&x)
{
one[i] = n / 2 - (n / 2) % 2 + 1;
}
else {
one[i] = n / 2 - (n / 2) % 2;
//one[i] = n / 2+ n%2;
//one[i] = n / 2;
}
arr.push_back(one[i]);
}
dfs(0, n, 0, arr, 0);
sort(a, a + n);
for (size_t i = 1; i < n; i++)
{
if (a[i] == a[i - 1])
{
cout << "NO" << endl;
return 0;
}
}
cout << "YES" << endl;
for (size_t i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
} | true |
c0a5fb6898e45cec9d1d44944b13fda75b286120 | C++ | Adityagithub24/data-structures | /heap sort.cpp | UTF-8 | 926 | 3.46875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int traverse(int a[],int n)
{
cout<<"resultant array"<<endl;
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
}
int swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
int heapify(int i,int a[],int n,int &hss)
{
int max,l,r;
max=i;
l=2*i+1;
r=2*i+2;
if(a[max]<a[l]&&l<=hss)
max=l;
if(a[max]<a[r]&&r<=hss)
max=r;
if(i!=max)
{
swap(a[i],a[max]);
heapify(max,a,n,hss);
}
}
int builtheap(int a[],int n,int hss)
{
for(int i=(n/2)-1;i>=0;i--)
{
heapify(i,a,n,hss);
}
}
int hs(int a[],int n)
{
int hss=n-1;
builtheap(a,n,hss);
while(hss>=1)
{
swap(a[0],a[hss]);
hss--;
heapify(0,a,n,hss);
}
}
int main()
{
int n;
cout<<"enter the size of array"<<endl;
cin>>n;
cout<<"enter the elements of array"<<endl;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
hs(a,n);
traverse(a,n);
}
| true |
de85dd0fb05d32c3d073a5bfcf4147e8f6dc9d21 | C++ | Entroyp/Option_Prices | /payoff.h | UTF-8 | 708 | 2.75 | 3 | [] | no_license | #ifndef PAYOFF_H
#define PAYOFF_H
#include<string>
class PayOff{
public:
PayOff();
virtual ~PayOff(){};
virtual double operator() (const double& s ) const = 0;
virtual std::string gettype() const = 0;
};
class PayOffCall : public PayOff {
private:
double K;
char Type;
public:
PayOffCall(const double& k );
virtual ~PayOffCall() {};
virtual double operator() (const double& s ) const;
virtual std::string gettype() const;
};
class PayOffPut : public PayOff {
private:
double K;
public:
PayOffPut(const double& k );
virtual ~PayOffPut() {};
virtual double operator() (const double& s) const;
virtual std::string gettype() const;
};
#endif | true |
9c2d76f322814a7095ece79de2b1a35e0cf65a01 | C++ | Dvuglaf/cpp_labs | /lab-9-qt/application/Snake.h | WINDOWS-1251 | 4,699 | 2.609375 | 3 | [] | no_license | #pragma once
#include <QWidget>
#include <QTimer>
#include "Fruit.h"
#include <QSize>
#include <QVector>
#include <QKeyEvent>
#include "Settings.h"
#include <random>
#include <QPainter>
/**
* .
*/
class Snake : public QWidget {
Q_OBJECT
public:
static const qint64 _DOT_SIZE = 24; /**< . */
private:
const QSize _size; /**< . */
std::mt19937 _random; /**< . */
enum class Directions {UP, LEFT, RIGHT, DOWN}; /**< . */
bool _game = false; /**< . */
bool _left = false; /**< . */
bool _right = false; /**< . */
bool _up = false; /**< . */
bool _down = false; /**< . */
bool _randomFruit = true; /**< . */
QImage _dot; /**< */
Settings& _settings; /**< . */
QTimer* _timer; /**< . */
Fruit _fruit; /**< . */
Directions _direction ; /**< . */
qint32 _score = 0; /**< . */
QVector<QPoint> _body; /**< . */
/**
* .
*
* @params painter .
*/
void pressStart(QPainter& painter);
/**
* .
*/
void eatFruit();
/**
* .
*/
void checkCollision();
/**
* .
*/
void move();
/**
* .
*/
void showResult();
/**
* .
*/
void gameOver();
/**
* , .
*
*@ params event .
*/
void paintEvent(QPaintEvent* event);
/**
* , .
*
*@ params key .
*/
void keyPressEvent(QKeyEvent* key);
/**
* .
*
*@param index , .
*@return .
*/
char* getPath(qint32 index);
private slots:
/**
* , .
*/
void updateScene();
/**
* , .
*/
void start();
/**
* , .
*/
void scoreMustIncreament();
public slots:
/**
* , .
*
*@param value .
*/
void changeDifficulty(qint32 value);
/**
* , .
*
* @param index , .
* @param random , , .
*/
void changeFruitIcon(qint32 index , bool random);
signals:
/**
* .
*/
void statusBarMustUpdate();
public:
/**
* .
*
*@return .
*/
int getScore();
public:
/**
* , 576576.
*
*@paran parent .
*/
Snake(Settings& settings, QWidget* parent = 0);
/**
* .
*/
Snake(const Snake&) = delete;
/**
* .
*/
Snake& operator=(const Snake&) = delete;
};
| true |
a582b9a5bc721ea98b9d2910068b9b42dacdce8a | C++ | akash-eth/CPP | /Advanced Functions/sumOfNNaturalNumbers.cpp | UTF-8 | 197 | 3.109375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int sum(int num) {
int naturalSum = num*(num+1)/2;
return naturalSum;
}
int main() {
int n;
cin >> n;
cout << sum(n);
return 0;
} | true |
a0299581b138e8d61ddc4b227aacca07ff3b2845 | C++ | kretzmoritz/syl_net | /src/syl_net/net/connection.cpp | UTF-8 | 358 | 2.828125 | 3 | [] | no_license | #include "connection.h"
namespace SylNet
{
Connection::Connection()
{
}
Connection::Connection(sf::IpAddress _address, unsigned short _port)
: address(_address), port(_port)
{
}
bool Connection::operator<(Connection const& _other) const
{
if (port == _other.port)
{
return address < _other.address;
}
return port < _other.port;
}
}; | true |
70cb7893c77f486b424334b2b700f5adabb60b56 | C++ | yechang1897/algorithm | /Array/leetcode_867.cpp | UTF-8 | 644 | 3.53125 | 4 | [] | no_license | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<vector<int>> transpose(vector<vector<int>>& A) {
vector<vector<int>> res;
int x = A[0].size();
int y = A.size();
for (int i = 0; i < x; i++) {
vector<int> temp;
for (int j = 0; j < y; j++) {
temp.push_back(A[j][i]);
}
res.push_back(temp);
}
return res;
}
int main() {
vector<vector<int>> A = {{1, 2, 3}, {4, 5, 6}};
vector<vector<int>> res = transpose(A);
for(vector<int> v : res) {
for(int i : v) {
cout << i << " ";
}
cout << endl;
}
} | true |
498e895df247557e05bf088ad712611b71dc1f5f | C++ | hasibulhasan763/Advance-C-Programming | /C/Printing Fibonaci Series.cpp | UTF-8 | 219 | 2.703125 | 3 | [] | no_license | #include<stdio.h>
int main ()
{
int i,n,a=0,b=1,next;
printf("Enter a number: ");
scanf("%d",&n);
for(i=0; i<=n; i++)
{
printf("%d\n",a);
next=a+b;
a=b;
b=next;
}
return 0;
}
| true |
830b7aa2702da9ae825461887fd4cdad89e4fe4f | C++ | martiansideofthemoon/CS-213 | /Assignment 2/Q2/helper.cpp | UTF-8 | 738 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include "queue_list.cpp"
using namespace std;
int main() {
queue_list<float> ab;
float abc = 0;
ab.push_back(6);
ab.front(&abc);
cout << abc << " ";
ab.push_back(4);
ab.front(&abc);
cout << abc << " ";
ab.push_back(7);
ab.front(&abc);
cout << abc << " ";
ab.push_back(8.4);
ab.front(&abc);
cout << abc << " ";
ab.pop_front();
ab.front(&abc);
cout << abc << " ";
ab.pop_front();
ab.front(&abc);
cout << abc << " ";
ab.pop_front();
ab.front(&abc);
cout << abc << " ";
ab.pop_front();
ab.front(&abc);
cout << abc << " ";
ab.pop_front();
ab.front(&abc);
cout << abc << endl;
cout << ab.size() << endl;
ab.push_back(2.3);
cout << ab.size() << endl;
ab.front(&abc);
cout << abc << endl;
} | true |
c2b4a6a599ce37177b30154854adad4cc4338a48 | C++ | iandownie07/Air-Conditioning-Control | /Commented Air-Conditioning Control/Embedded system/Main.cpp | UTF-8 | 2,911 | 2.734375 | 3 | [] | no_license | //
// Main.cpp
// main for air-conditioning control implemented in Raspberry Pi Pico with Arm M0+ processor
//
// Created by Ian Downie on 13/03/21.
//
#include "AirCon.cpp"
#include "States.cpp"
#include "AirConState.cpp"
#include <iostream>
#include "pico/stdlib.h"
#include "hardware/uart.h"
#include "hardware/irq.h"
#include "hardware/gpio.h"
#define UART_ID uart0
#define BAUD_RATE 57600
#define DATA_BITS 8
#define STOP_BITS 1
#define PARITY UART_PARITY_NONE
// We are using pins 0 and 1 for UART communication
#define UART_TX_PIN 0
#define UART_RX_PIN 1
// Core 0 Main Code
int main()
{
multicore_launch_core1(core1_entry); // Start core 1 of Raspberry Pi Pico
while(true)
{
// allocate GPIOS
stdio_init_all(); // Initialize all of the present standard stdio types that are linked into the binary
// Set up our UART with a basic baud rate.
uart_init(UART_ID, BAUD_RATE);
// Set the TX and RX pins by using the function select on the GPIO
// Set datasheet for more information on function select
gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART);
gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART);
// Set UART flow control CTS/RTS, we don't want these, so turn them off
uart_set_hw_flow(UART_ID, false, false);
// Set our data format
uart_set_format(UART_ID, DATA_BITS, STOP_BITS, PARITY);
// Turn off FIFO's - we want to do this character by character
uart_set_fifo_enabled(UART_ID, false);
// Set up a RX interrupt
// We need to set up the handler first
// Select correct interrupt for the UART we are using
int UART_IRQ = UART_ID == uart0 ? UART0_IRQ : UART1_IRQ;
// And set up and enable the interrupt handlers
irq_set_exclusive_handler(UART_IRQ, on_uart_rx);
irq_set_enabled(UART_IRQ, true);
// Now enable the UART to send interrupts - RX only
uart_set_irq_enables(UART_ID, true, false);
// Enable all the pins that will be used, besides the UART ones
gpio_init(3);
gpio_set_dir(3, GPIO_OUT);
gpio_init(10);
gpio_set_dir(10, GPIO_IN);
gpio_init(12);
gpio_set_dir(12, GPIO_OUT);
gpio_init(15);
gpio_set_dir(15, GPIO_IN);
gpio_init(17);
gpio_set_dir(17, GPIO_OUT);
gpio_init(22);
gpio_set_dir(22, GPIO_OUT);
// Proxy signal for the existence of the door and window
gpio_put(12,1); // set door out pin
gpio_put(3,1); // set window out pin
AirCon* p_air; // pointer to a Total object to initiate state ResetClock
p_air = new AirCon(); // create pointer to an AirCon object to initiate state Idle. We thus enter the constructor of AirCon
delete p_air;
}
return 0;
}
| true |
656b5fd3c0aeb0144304480e1bb48693d8aaf8a9 | C++ | herbstluftwm/herbstluftwm | /src/namedhook.h | UTF-8 | 2,047 | 2.75 | 3 | [
"BSD-2-Clause"
] | permissive | #ifndef __HLWM_NAMED_HOOK_H_
#define __HLWM_NAMED_HOOK_H_
#ifdef ENABLE_NAMED_HOOK
#include "attribute_.h"
#include "hook.h"
#include "object.h"
class NamedHook : public Object, public Hook {
public:
NamedHook(const std::string &path);
void hook_into(Object* root);
Type type() { return Type::HOOK; }
// emit hook, used by path elements
void operator()(Object* sender, HookEvent event,
const std::string &name);
void trigger(const std::string &action, ArgList args);
std::string name() { return name_; }
private:
/* are we listening to an object rather an attribute? If so,
* our complete chain is 1 element longer than the path (includes root) */
bool targetIsObject() { return path_.size() < chain_.size(); }
// for external trigger and called by others
void emit(const ArgList args);
// for Event::CHILD_* cases
void emit(HookEvent event, const std::string &name);
// for Event::ATTRIBUTE_CHANGED case
void emit(const std::string &old, const std::string ¤t);
// check if chain needs to be altered
void check_chain(std::shared_ptr<Object> sender, HookEvent event,
const std::string &name);
// remove tail from chain
void cutoff_chain(size_t length);
// rebuild chain after existing elements
void complete_chain();
void debug_hook(std::shared_ptr<Object> sender = {},
HookEvent event = HookEvent::ATTRIBUTE_CHANGED,
const std::string &name = {});
std::string name_;
// counter attribute
Attribute_<int> counter_;
// test if hook is currently working
Attribute_<bool> active_;
// external trigger for hook
Action emit_;
// chain of directories that report to us
std::vector<std::weak_ptr<Object>> chain_;
// tokenized path (derived from our name)
std::vector<std::string> path_;
// last known value, used to print new value vs. old value
std::string value_;
};
#endif // ENABLE_NAMED_HOOK
#endif
| true |
2225140175f11b98deec0e0f3889b2df0db6120b | C++ | marcogmaia/radl | /radl/fov.hpp | UTF-8 | 632 | 2.84375 | 3 | [] | no_license | #pragma once
#include "permissive-fov/permissive-fov.hpp"
namespace radl {
class IFov {
public:
virtual ~IFov() = default;
/**
* @brief check if @p location is blocked
*
* @param x in the map
* @param y in the map
*
* @return true if can't see through, false otherwise
*/
virtual bool is_blocked(int x, int y) = 0;
/**
* @brief Visit a location in the map, we can perform some action, like: add
* the visited location to a vector with visible locations
*
* @param x
* @param y
*/
virtual void visit(int x, int y) = 0;
};
} // namespace radl
| true |
6c8cd22d8418d5d23b56dfcb20bac3f8c5aa9094 | C++ | abdulrcs/CP | /TLX/courses/Pemrograman Dasar/05 Percabangan/If_Then_Case.cpp | UTF-8 | 278 | 2.671875 | 3 | [] | no_license | #include <cstdio>
int x;
int main(void)
{
scanf("%i", &x);
if(x/10000 > 0)
printf("puluhribuan\n");
else if(x/1000 > 0)
printf("ribuan\n");
else if(x/100 > 0)
printf("ratusan\n");
else if(x/10 > 0)
printf("puluhan\n");
else
printf("satuan\n");
}
| true |
f306bb8d0d2988e022ccb66c627bbdb4f6b2a847 | C++ | denizumuteser/CS_300 | /HW 1/denizumut_eser_denizumut_hw1_Stack.h | UTF-8 | 1,005 | 3.5 | 4 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
struct Underflow : public exception {
const char* what () const throw () {
return "Exception: trying to access element of empty Stack.";
}
};
template<class Object>
class Stack
{
public:
Stack();
Stack(const Stack & rhs);
~Stack();
//utility functions
bool isEmpty() const; //check if stack is emptly
bool isFull() const; //check if stack is full
void makeEmpty(); //make stack empty
//main functions
void pop(); //remove element from top
void push(const Object & x); //add element to top
Object topAndPop(); //get top element then remove it from stack
const Object & top() const; //get the element on top of the stack
//operators
const Stack& operator=(const Stack& rhs); //deep copy
private:
struct ListNode
{
Object element;
ListNode* next;
ListNode(const Object& theElement, ListNode* n = NULL)
: element(theElement), next(n) {}
};
ListNode* topOfStack;
};
#include "denizumut_eser_denizumut_hw1_Stack.cpp"
| true |
26873840fe9d71e452bd703e77cad89715c0b66d | C++ | JHEBentley/FYP | /RobotArduino/ParseDelimitedMessage/ParseDelimitedMessage.ino | UTF-8 | 1,992 | 3.15625 | 3 | [] | no_license | /*
* Reads the serial feed and parses ints, then writes this in as the servo motor position.
* Does this for a string of values with "," delimiters.
* Can be used in conjunction with the Arduino comms script in Unity.
*/
#include <Servo.h>;
//Servo stuff
Servo servos[6];
int data[] = {90,90,90,90,90,90};
int oldData[] = {90,90,90,90,90,90};
//Parsing stuff
String serialMessage = "";
//Max number of characters expected, including delimiters
const int MaxMessageLength = 24;
String results[6];
int intResults[6];
void setup()
{
Serial.begin(9600);
//Attatch the 6 servos to pins 6 - 12
for(int i = 0; i < 6; i++)
{
servos[i].attach(i + 6);
}
Serial.println("Arduino is ready");
}
void loop()
{
//If there's new serial data available, assign it as the data var and flush the channel to prevent contamination of serial feeds
if (Serial.available())
{
ParseMessage();
UpdateArray(data, 6, intResults);
Serial.flush();
}
else
{/*
for(int i = 0; i < 6; i++)
{
data[i] = 90;
}*/
}
//If we have recieved new data, send it back to the monitor
for(int i = 0; i < 6; i++)
{
if (data[i] != oldData[i])
{
oldData[i] = data[i];
Serial.print(i);
Serial.print(" is at: ");
Serial.println(data[i]);
}
}
for(int i = 0; i < 6; i++)
{
servos[i].write(data[i]);
}
}
void UpdateArray(int _array[], int _length, int newArray[])
{
for(int i = 0; i < _length; i++)
{
_array[i] = newArray[i];
}
}
void ParseMessage()
{
serialMessage = Serial.readStringUntil('\r\n');
char messageArray[MaxMessageLength];
serialMessage.toCharArray(messageArray, sizeof(messageArray));
char *messagePointer = messageArray;
char *result;
int counter = 0;
while ((result = strtok_r(messagePointer, ",", &messagePointer))!= NULL)
{
results[counter] = result;
counter++;
}
for(int i = 0; i < 6; i++)
{
intResults[i] = results[i].toInt();
}
}
| true |
34b8353c4fa3fb5c1ae5d887f6498c381bbb269f | C++ | TartanLlama/cpp-con | /cpp-con/cpp-con.cpp | UTF-8 | 1,059 | 2.671875 | 3 | [] | no_license | // cpp-con.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <ranges>
#include <tl/generator.hpp>
#include "xorshift.hpp"
int main()
{
auto random_numbers = cppcon::xorshift(4)
| std::views::take(4)
| std::views::transform([](auto i) {return i % 100; });
for (auto i : random_numbers) {
std::cout << i << '\n';
}
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
3825a7068fd0ab0a3886af9f79acb241a73a0107 | C++ | gitqwerty777/Online-Judge-Code | /categorized/[Not Solved] 11149.cpp | UTF-8 | 998 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include "matrix.h"
/*
hint:
A+A^2+...+A^(2n) = (A+A^2+...+A^n) + A^n (A+A^2+...+A^n)
*/
int main(){
int N, P;
while(scanf("%d %d", &N, &P) == 2 && N + P){
matrix arr(N, N);
matrix sum(N, N);
for(int r = 0; r < N; r++)
for(int c = 0; c < N; c++){
scanf("%d", &arr.s[r][c]);
sum.s[r][c] = arr.s[r][c];
}
bool sq[20]; // log_2 (1000000) = 19.93...
memset(sq, false, sizeof(sq));
int sqnum = P;
int count = 0;
while(sqnum){
if(sqnum % 2)
sq[count] = true;
count++;
sqnum /= 2;
}
for(int i = count-1; i >= 0; i--)
printf("%d", sq[i]?1:0);
puts("");
if(count == 1){
} else {
matrix ori(arr);
//square and multiply
for(int i = count-2; i >= 0; i--){//start from 10
sum = sum + sum * arr;
if(sq[i]){
sum = sum * ori + ori;
}
arr = arr ^ 2;
sum.mod(10);
arr.mod(10);
}
}
sum.print();
puts("");
}
return 0;
}
| true |
fa996461afdc8f7c14340f3f96ec3473cecae4f4 | C++ | onww1/Problem-Solving | /LeetCode/Medium/lc986.cpp | UTF-8 | 4,822 | 3.6875 | 4 | [] | no_license | #include <algorithm>
#include <functional>
#include <vector>
#include <cstdio>
#include <string>
#include <cassert>
#include <queue>
#include <unordered_map>
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
ListNode* makeList(vector<int>& nodes);
TreeNode* makeTree(vector<int>& nodes);
bool matchList(ListNode* anode, ListNode* bnode);
bool matchTree(TreeNode* anode, TreeNode* bnode);
const int EMPTY = 0x7f7f7f7f;
/* Solution Class */
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
vector<vector<int>> intersections;
int firstPtr = 0, secondPtr = 0;
while (firstPtr < firstList.size() && secondPtr < secondList.size()) {
int compare = compareInterval(firstList[firstPtr], secondList[secondPtr]);
if (!compare) {
vector<int> intersection = getIntersection(firstList[firstPtr], secondList[secondPtr]);
intersections.push_back(intersection);
compare = strictCompareInterval(firstList[firstPtr], secondList[secondPtr]);
}
if (compare == -1)
firstPtr++;
else if (compare == 1)
secondPtr++;
}
return intersections;
}
private:
/**
* If two intervals are intersected, return 0.
* If {intervalA} precedes {intervalB}, return -1.
* Otherwise, return 1.
*/
int compareInterval(vector<int>& intervalA, vector<int>& intervalB) {
if (intervalA[1] < intervalB[0])
return -1;
if (intervalB[1] < intervalA[0])
return 1;
return 0;
}
/**
* If {intervalA.end} <= {intervalB.end}, return -1.
* Otherwise, return 1.
*/
int strictCompareInterval(vector<int>& intervalA, vector<int>& intervalB) {
return intervalA[1] <= intervalB[1] ? -1 : 1;
}
vector<int> getIntersection(vector<int>& intervalA, vector<int>& intervalB) {
int left = max(intervalA[0], intervalB[0]);
int right = min(intervalA[1], intervalB[1]);
vector<int> intersection = {left, right};
return intersection;
}
};
int main(int argc, char *argv[]) {
Solution solution;
/* Input */
vector<vector<vector<int>>> firstList = {
{{0, 2}, {5, 10}, {13, 23}, {24, 25}},
{{1, 3}, {5, 9}},
{},
{{1, 7}}
};
vector<vector<vector<int>>> secondList = {
{{1, 5}, {8, 12}, {15, 24}, {25, 26}},
{},
{{4, 8}, {10, 12}},
{{3, 10}}
};
/* Output */
vector<vector<vector<int>>> ret;
for (int i = 0; i < firstList.size(); i++)
ret.push_back(solution.intervalIntersection(firstList[i], secondList[i]));
/* Answer */
vector<vector<vector<int>>> answer = {
{{1, 2}, {5, 5}, {8, 10}, {15, 23}, {24, 24}, {25, 25}},
{},
{},
{{3, 7}}
};
/* Check */
assert(ret == answer);
puts("PASS!");
return 0;
}
ListNode* makeList(vector<int>& nodes) {
if (nodes.empty())
return nullptr;
ListNode* head = new ListNode(nodes[0]);
ListNode* ptr = head;
for (int i = 1; i < nodes.size(); i++) {
ptr->next = new ListNode(nodes[i]);
ptr = ptr->next;
}
return head;
}
TreeNode* makeTree(vector<int>& nodes) {
if (nodes.empty())
return NULL;
TreeNode* root = new TreeNode(nodes[0]);
queue<TreeNode*> que;
que.push(root);
int idx = 1;
while (!que.empty() && idx < nodes.size()) {
TreeNode* node = que.front();
que.pop();
if (nodes[idx] != EMPTY) {
node->left = new TreeNode(nodes[idx]);
que.push(node->left);
}
idx++;
if (nodes[idx] != EMPTY) {
node->right = new TreeNode(nodes[idx]);
que.push(node->right);
}
idx++;
}
return root;
}
bool matchList(ListNode* anode, ListNode* bnode) {
while (anode && bnode) {
if (anode->val != bnode->val)
return false;
anode = anode->next;
bnode = bnode->next;
}
return !anode && !bnode;
}
bool matchTree(TreeNode* anode, TreeNode* bnode) {
if (!anode && !bnode)
return true;
if (!anode || !bnode)
return false;
if (anode->val != bnode->val)
return false;
return matchTree(anode->left, bnode->left) && matchTree(anode->right, bnode->right);
} | true |
483a544071c9f4876eaa88cc32e1ea3569f6c190 | C++ | PugnaHAN/C-Primer | /DesignPatterns/Structor/Structor/TimeImp.h | UTF-8 | 1,075 | 3.390625 | 3 | [] | no_license | #pragma once
#ifndef __TIMEIMP_H__
#define __TIMEIMP_H__
#include "common.h"
class TimeImp
{
public:
TimeImp() = default;
TimeImp(int hr, int min) : hour(hr), minute(min) {}
virtual void tell()
{
std::cout << "time is " << std::setw(2) << std::setfill('0')
<< hour << ":" << minute << std::endl;
}
protected:
int hour, minute;
};
class CivilianTimeImp : public TimeImp
{
public:
CivilianTimeImp(int hr, int min, bool pm) : TimeImp(hr, min),
whichM(pm? "PM" : "AM") {}
void tell()
{
std::cout << "time is " << std::setw(2) << std::setfill('0')
<< hour << ":" << minute << " " << whichM << std::endl;
}
private:
std::string whichM;
};
class ZuluTimeImp : public TimeImp
{
public:
ZuluTimeImp(int hr, int min, int zn) : TimeImp(hr, min)
{
if (zn == 5)
zone = " Eastern Standard Time";
else if (zn == 6)
zone = " Central Standard Time";
}
void tell()
{
std::cout << "time is " << std::setw(2) << std::setfill(':')
<< hour << ":" << minute << zone << std::endl;
}
private:
std::string zone;
};
#endif /* __TIMEIMP_H__ */ | true |
e6b45c768b98b9ebc83d39fab15a23a4d06701e9 | C++ | hughzeng/llrbt | /test_llrbt.cpp | UTF-8 | 2,253 | 2.75 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <ctime>
#include <map>
#include <random>
#include <functional>
#include "llrbt.hpp"
int main() {
std::default_random_engine rand_engine;
std::uniform_int_distribution<int> rand_range(0, 1e9);
auto rand_gen = std::bind(rand_range, rand_engine);
std::vector<int>data;
const int N = 1E6;
for (int i = 0; i < N; ++i) {
data.push_back(rand_gen());
}
std::sort(data.begin(),data.end());
data.erase(std::unique(data.begin(), data.end()), data.end());
for (int i = 0; i < data.size(); ++i) {
int j = rand_gen() % data.size();
std::swap(data[i], data[j]);
}
LLRBTree<int, int> rbt;
std::map<int, int> mp;
clock_t t1 = clock();
for (int key: data) {
rbt.Insert(key, 0);
}
clock_t t2 = clock();
std::cout << "llrbt insert " << data.size() << " keys takes " << (t2 - t1) / 1000 << " ms\n";
t1 = clock();
for (int key: data) {
mp.insert({key, 0});
}
t2 = clock();
std::cout << "map insert " << data.size() << " keys takes " << (t2 - t1) / 1000 << " ms\n";
for (int i = 0; i < data.size(); ++i) {
int j = rand_gen() % data.size();
std::swap(data[i], data[j]);
}
for (int i = 0; i < data.size(); ++i) {
int j = rand_gen() % data.size();
std::swap(data[i], data[j]);
}
t1 = clock();
for (int key: data) {
rbt[key];
}
t2 = clock();
std::cout << "llrbt query " << data.size() << " keys takes " << (t2 - t1) / 1000 << " ms\n";
t1 = clock();
for (int key: data) {
mp[key];
}
t2 = clock();
std::cout << "map query " << data.size() << " keys takes " << (t2 - t1) / 1000 << " ms\n";
t1 = clock();
for (int key: data) {
rbt.Remove(key);
}
t2 = clock();
std::cout << "llrbt remove " << data.size() << " keys takes " << (t2 - t1) / 1000 << " ms\n";
t1 = clock();
for (int key: data) {
mp.erase(key);
}
t2 = clock();
std::cout << "map remove " << data.size() << " keys takes " << (t2 - t1) / 1000 << " ms\n";
}
| true |
bd512ae7e6d06599d805b3c9df3dd03da8649deb | C++ | fraser-campbell/CS106B | /Assignment_4/Fill a Region/Fillregion.cpp | UTF-8 | 2,617 | 3.734375 | 4 | [] | no_license | /*
* File: Fillregion.cpp
* --------------------------
* Name: Fraser Campbell
* Section: Write a function to fill a region in C++
*/
// #include <map>
#include <string>
#include <vector>
#include <iostream>
// #include "grid.h"
// #include <set>
using namespace std;
enum pixelStateT { White, Black };
struct pointT { int row, col; };
typedef vector<vector<pixelStateT> > grid; //This sets the size of the grid to 100*100 pixels
void FillRegion(pointT pt, grid &screen, pixelStateT current){
if( 0 < pt.row < 9 && screen[pt.row][pt.col] == current){
//First need to check where the pointT pt is
//Then check if any of the adjacent points in that row are the same color and change those
//Check the positive direction with a for loop
int positive = pt.col;
// pixelStateT current = screen[pt.row][pt.col];
while(screen[pt.row][positive] == current && positive<screen.size()){
cout << screen[pt.row][positive] << " " ;
if(screen[pt.row][positive] == White) screen[pt.row][positive] = Black;
else screen[pt.row][positive] = White;
positive++;
}
//Check the other direction with a for loop
int negative = pt.col - 1;
cout << negative << endl;
while(screen[pt.row][negative] == current && negative>=0){
cout << screen[pt.row][negative] << " " ;
if(screen[pt.row][negative] == White) screen[pt.row][negative] = Black;
else screen[pt.row][negative] = White;
negative--;
}
pointT pt_above;
pt_above.row = pt.row-1;
pt_above.col = pt.col;
pointT pt_below;
pt_below.row = pt.row+1;
pt_below.col = pt.col;
FillRegion(pt_below, screen, current);
FillRegion(pt_above, screen, current);
}
//Then need to pass the initial pointT pt to two recursive functions one which increments the row by one, one which decrements it by one
}
void CheckPrint(grid &screen){
vector< vector<pixelStateT> >::iterator row;
vector<pixelStateT>::iterator col;
for(row = screen.begin(); row !=screen.end(); row++){
cout << "" << endl;
for(col = row->begin(); col != row->end(); col++){
cout << *col << " " ;
}
}
}
int main(){
pixelStateT pixely = White;
grid screen;
pointT pt;
pt.row = 10;
pt.col = 10;
screen.resize(pt.row);
for (int i=0; i<pt.row; ++i){
screen[i].resize(pt.col);
for(int j=0; j<pt.col; ++j){
if(j<3 && i<4 || j>7 && i>6) screen[i][j] = White;
else screen[i][j] = Black;
}
}
CheckPrint(screen);
cout << "Checking" << endl;
pointT pt_change;
pt_change.row = 1;
pt_change.col = 1;
pixelStateT current = screen[pt_change.row][pt_change.col];
FillRegion(pt_change, screen, current);
CheckPrint(screen);
return 0;
}
| true |
aab6d4e5aec197d4954361fff1ce3796aeed97e1 | C++ | ChimesZ/THU-PUMC-Courses-Project | /Grade 1 Spring/程序设计基础(hwt)/3.2/2020040043_2020.3.2_1.cpp | GB18030 | 494 | 2.796875 | 3 | [] | no_license | #include "stdio.h"
int main()
{float a,b,c,d,result1,result2,result;
printf("ĸͬʵÿո\n");
scanf("%f%f%f%f",&a,&b,&c,&d);
if((a==0)&&(b==0)&&(c==0)&&(d==0))
{}
else
{if((a>=-1e6)&&(a<=1e6)&&(b>=-1e6)&&(b<=1e6)&&(c>=-1e6)&&(c<=1e6)&&(d>=-1e6)&&(d<=1e6))
{result1=a>=b? a:b;
result2=c>=d? c:d;
result=result1>=result2? result1:result2;
printf("Ϊ%f\n",result);
}
else printf("\n");
}
} | true |
ce47388a0ce2f688827dd31929d3dbe578cfaf94 | C++ | dclcs/AutoSittingPoseGenerate | /SourceCode/ReshapeCode/Reshape/HumanSegmentation/HumanSegmentation/Voxel.cpp | UTF-8 | 10,945 | 2.765625 | 3 | [] | no_license | // Voxel
#include "Voxel.h"
#include "Mesh.h"
namespace ManSeg {
// constructor
VoxelHandler::VoxelHandler(Mesh* in_mesh, float voxel_size) : mesh(in_mesh) {
voxels_init(voxel_size);
find_boundary_voxel();
find_outside_voxel();
find_inside_voxel();
}
VoxelHandler::VoxelHandler(Mesh* in_mesh, float voxel_size, float multiplier) : mesh(in_mesh) {
voxels_init(voxel_size, multiplier);
find_boundary_voxel();
find_outside_voxel();
find_inside_voxel();
}
void VoxelHandler::write_ply(string ply_path) {
struct PlyPart {
float x; float y; float z; float nx; float ny; float nz;
unsigned char r; unsigned char g; unsigned char b; unsigned char a;
};
int size = 0;
for (int i = 0; i < voxels.size(); i++) {
if (voxels[i].type == Voxel::skeleton || voxels[i].type == Voxel::inside || voxels[i].type == Voxel::boundary)
size++;
}
char t[256];
sprintf(t, "%d", size);
string size_str = t;
FILE* fp = fopen(ply_path.c_str(), "wb");
string header = "ply\nformat binary_little_endian 1.0\ncomment VCGLIB generated\nelement vertex ";
header += size_str;
header += "\nproperty float x\nproperty float y\nproperty float z\nproperty float nx\nproperty float ny\nproperty float nz\nproperty uchar red\nproperty uchar green\nproperty uchar blue\nproperty uchar alpha\nelement face 0\nproperty list uchar int vertex_indices\nend_header\n";
int len = (int)strlen(header.c_str());
fwrite(header.c_str(), len, 1, fp);
PlyPart* ply = new PlyPart[size];
int count = 0;
for (int i = 0; i < voxels.size(); i++) {
if (voxels[i].type == Voxel::skeleton || voxels[i].type == Voxel::inside || voxels[i].type == Voxel::boundary) {
Vertex center = voxel_center(i);
ply[count].x = (float)center.x;
ply[count].y = (float)center.y;
ply[count].z = (float)center.z;
ply[count].nx = 0;
ply[count].ny = 0;
ply[count].nz = 0;
ply[count].r = 255;
ply[count].g = 0;
ply[count].b = 0;
ply[count].a = 255;
count++;
}
}
fwrite(ply, sizeof(PlyPart)*size, 1, fp);
delete[] ply;
fclose(fp);
}
// judge
bool VoxelHandler::is_object(int index)
{
Voxel::VoxelType t = voxels[index].type;
if (t == Voxel::inside || t == Voxel::skeleton /*|| t == Voxel::boundary*/)
return true;
return false;
}
bool VoxelHandler::is_inside(int index)
{
Voxel::VoxelType t = voxels[index].type;
if (t == Voxel::inside)
return true;
return false;
}
bool VoxelHandler::is_boundary(int index)
{
Voxel::VoxelType t = voxels[index].type;
if (t == Voxel::boundary)
return true;
return false;
}
bool VoxelHandler::is_object_border(int index)
{
Voxel::VoxelType t = voxels[index].type;
if (t == Voxel::inside || t == Voxel::skeleton || t == Voxel::boundary)
return true;
return false;
}
bool VoxelHandler::is_skeleton(int index)
{
Voxel::VoxelType t = voxels[index].type;
if (t == Voxel::skeleton)
return true;
return false;
}
// init
void VoxelHandler::voxels_init(float voxel_size, float multiplier)
{
// find bounding box
vxsize = voxel_size;
int mini[3] = { 0 }, maxi[3] = { 0 };
float min[3] = { DECIMAL_MAX, DECIMAL_MAX, DECIMAL_MAX };
float max[3] = { DECIMAL_MIN, DECIMAL_MIN, DECIMAL_MIN };
for (int i = 0; i < mesh->v.size(); i++)
{
const Vertex& vtx = mesh->v[i];
if (vtx.x > max[0]) { max[0] = vtx.x; maxi[0] = i; }
if (vtx.x < min[0]) { min[0] = vtx.x; mini[0] = i; }
if (vtx.y > max[1]) { max[1] = vtx.y; maxi[1] = i; }
if (vtx.y < min[1]) { min[1] = vtx.y; mini[1] = i; }
if (vtx.z > max[2]) { max[2] = vtx.z; maxi[2] = i; }
if (vtx.z < min[2]) { min[2] = vtx.z; mini[2] = i; }
}
// resize
if (multiplier > 0) {
for (int i = 0; i < 3; i++) {
float len = max[i] - min[i];
float d = (len * multiplier - len) / 2;
min[i] -= d;
max[i] += d;
}
}
// origin of bounding box
for (int i = 0; i < 3; i++)
vxorg[i] = min[i];
// voxel amount of each dimension
float tempf[3];
tempf[0] = (float)((max[0] - min[0]) / voxel_size);
tempf[1] = (float)((max[1] - min[1]) / voxel_size);
tempf[2] = (float)((max[2] - min[2]) / voxel_size);
for (int i = 0; i < 3; i++)
vxlen[i] = (int)ceil(tempf[i]);
// generate voxels
voxels.resize(vxlen[0] * vxlen[1] * vxlen[2]);
for (int i = 0; i < vxlen[2]; i++)
{
for (int j = 0; j < vxlen[1]; j++)
{
for (int k = 0; k < vxlen[0]; k++)
{
int index = i*vxlen[1] * vxlen[0] + j*vxlen[0] + k;
voxels[index].x = k;
voxels[index].y = j;
voxels[index].z = i;
}
}
}
}
void VoxelHandler::find_boundary_voxel()
{
for (int i = 0; i < mesh->t.size(); i++)
{
// find bounding box of each triangle
Voxel vx[3];
vx[0] = voxels[vertex_in_which_voxel(mesh->v[mesh->t[i].v[0]])];
vx[1] = voxels[vertex_in_which_voxel(mesh->v[mesh->t[i].v[1]])];
vx[2] = voxels[vertex_in_which_voxel(mesh->v[mesh->t[i].v[2]])];
int mini[3], maxi[3];
mini[0] = std::min(std::min(vx[0].x, vx[1].x), vx[2].x);
mini[1] = std::min(std::min(vx[0].y, vx[1].y), vx[2].y);
mini[2] = std::min(std::min(vx[0].z, vx[1].z), vx[2].z);
maxi[0] = std::max(std::max(vx[0].x, vx[1].x), vx[2].x);
maxi[1] = std::max(std::max(vx[0].y, vx[1].y), vx[2].y);
maxi[2] = std::max(std::max(vx[0].z, vx[1].z), vx[2].z);
// initiate boundary voxels
update_boundary(mini, maxi, i);
}
int count = 0;
for (int i = 0; i < voxels.size(); i++)
{
if (voxels[i].type == Voxel::boundary) {
voxels[i].face_start = count;
count += voxels[i].face_num;
}
}
for (int i = 0; i < voxels.size(); i++)
voxels[i].label = 0;
boundary_faces.resize(count);
for (int i = 0; i < mesh->t.size(); i++)
{
// find bounding box of each triangle
Voxel vx[3];
vx[0] = voxels[vertex_in_which_voxel(mesh->v[mesh->t[i].v[0]])];
vx[1] = voxels[vertex_in_which_voxel(mesh->v[mesh->t[i].v[1]])];
vx[2] = voxels[vertex_in_which_voxel(mesh->v[mesh->t[i].v[2]])];
int mini[3], maxi[3];
mini[0] = std::min(std::min(vx[0].x, vx[1].x), vx[2].x);
mini[1] = std::min(std::min(vx[0].y, vx[1].y), vx[2].y);
mini[2] = std::min(std::min(vx[0].z, vx[1].z), vx[2].z);
maxi[0] = std::max(std::max(vx[0].x, vx[1].x), vx[2].x);
maxi[1] = std::max(std::max(vx[0].y, vx[1].y), vx[2].y);
maxi[2] = std::max(std::max(vx[0].z, vx[1].z), vx[2].z);
// initiate boundary voxels
update_boundary_face(mini, maxi, i);
}
for (int i = 0; i < voxels.size(); i++)
voxels[i].label = -1;
}
void VoxelHandler::update_boundary_face(int mini[], int maxi[], int face)
{
for (int iz = mini[2]; iz <= maxi[2]; iz++)
{
for (int iy = mini[1]; iy <= maxi[1]; iy++)
{
for (int ix = mini[0]; ix <= maxi[0]; ix++)
{
int index = voxel_index(ix, iy, iz);
boundary_faces[voxels[index].face_start + voxels[index].label] = face;
voxels[index].label++;
}
}
}
}
void VoxelHandler::update_boundary(int mini[], int maxi[], int face)
{
for (int iz = mini[2]; iz <= maxi[2]; iz++)
{
for (int iy = mini[1]; iy <= maxi[1]; iy++)
{
for (int ix = mini[0]; ix <= maxi[0]; ix++)
{
int index = voxel_index(ix, iy, iz);
voxels[index].type = Voxel::boundary;
voxels[index].face_num++;
}
}
}
}
void VoxelHandler::find_outside_voxel()
{
// using BFS (DFS is also OK)
ArrayQueue<int> Q((int)voxels.size());
voxels[0].type = Voxel::outside;
Q.push(0);
while (!Q.empty())
{
int current = Q.front();
Q.pop();
for (int i = 0; i < 27; i++)
{
int neighbor = -1;
if (voxel_neighbor(current, i, neighbor))
{
if (voxels[neighbor].type == Voxel::undefined)
{
voxels[neighbor].type = Voxel::outside;
Q.push(neighbor);
}
}
}
}
}
void VoxelHandler::find_inside_voxel()
{
// not outside or boundary, then voxel is inside
for (int i = 0; i < voxels.size(); i++)
{
if (voxels[i].type == Voxel::undefined)
voxels[i].type = Voxel::inside;
}
}
// reset
void VoxelHandler::voxels_reset_label()
{
for (int i = 0; i < voxels.size(); i++)
voxels[i].label = -1;
}
void VoxelHandler::voxels_reset_SS_code()
{
for (int i = 0; i < (int)voxels.size(); i++)
voxels[i].SS_code = -1;
}
void VoxelHandler::voxels_set_unvisited()
{
for (int i = 0; i < voxels.size(); i++)
voxels[i].visited = false;
}
// functions
int VoxelHandler::voxel_index(int x, int y, int z) {
if (x < 0 || x >= vxlen[0] ||
y < 0 || y >= vxlen[1] ||
z < 0 || z >= vxlen[2])
return -1; // out of range
return z*vxlen[1] * vxlen[0] + y*vxlen[0] + x;
}
int VoxelHandler::vertex_in_which_voxel(const Vertex& vertex) {
int ix = (int)((vertex.x - vxorg[0]) / vxsize);
if (ix < 0 || ix >= vxlen[0]) return -1;
int iy = (int)((vertex.y - vxorg[1]) / vxsize);
if (iy < 0 || iy >= vxlen[1]) return -1;
int iz = (int)((vertex.z - vxorg[2]) / vxsize);
if (iz < 0 || iz >= vxlen[2]) return -1;
int ret = voxel_index(ix, iy, iz);
return ret;
}
bool VoxelHandler::voxel_neighbor(int index, int num, int& neighbor)
{
if (num == 13) // itself
return false;
const Voxel& current = voxels[index];
int temp[3];
temp[0] = current.x + (num % 3) - 1;
temp[1] = current.y + ((int)((float)num / (float)3) % 3) - 1;
temp[2] = current.z + (int)((float)num / (float)9) - 1;
if (temp[0] < 0 || temp[0] >= vxlen[0] ||
temp[1] < 0 || temp[1] >= vxlen[1] ||
temp[2] < 0 || temp[2] >= vxlen[2])
return false; // out of range
neighbor = voxel_index(temp[0], temp[1], temp[2]);
return true;
}
bool VoxelHandler::voxel_six_neighbor(int index, int num, int& neighbor)
{
const int nummap[6] = { 12, 14, 10, 16, 4, 22 };
num = nummap[num];
const Voxel& current = voxels[index];
int temp[3];
temp[0] = current.x + (num % 3) - 1;
temp[1] = current.y + ((int)((float)num / (float)3) % 3) - 1;
temp[2] = current.z + (int)((float)num / (float)9) - 1;
if (temp[0] < 0 || temp[0] >= vxlen[0] ||
temp[1] < 0 || temp[1] >= vxlen[1] ||
temp[2] < 0 || temp[2] >= vxlen[2])
return false; // out of range
neighbor = voxel_index(temp[0], temp[1], temp[2]);
return true;
}
Vertex VoxelHandler::voxel_center(int index) {
Vertex ret;
ret.x = (float)voxels[index].x*vxsize + vxorg[0];
ret.y = (float)voxels[index].y*vxsize + vxorg[1];
ret.z = (float)voxels[index].z*vxsize + vxorg[2];
float half = 0.5;
ret.x += half*vxsize;
ret.y += half*vxsize;
ret.z += half*vxsize;
return ret;
}
float VoxelHandler::voxel_distance_s(int index0, int index1)
{
Vertex v0;
v0.x = (float)voxels[index0].x*vxsize;
v0.y = (float)voxels[index0].y*vxsize;
v0.z = (float)voxels[index0].z*vxsize;
Vertex v1;
v1.x = (float)voxels[index1].x*vxsize;
v1.y = (float)voxels[index1].y*vxsize;
v1.z = (float)voxels[index1].z*vxsize;
float temp = v0.x - v1.x;
float ret = temp*temp;
temp = v0.y - v1.y;
ret += temp*temp;
temp = v0.z - v1.z;
ret += temp*temp;
return ret;
}
} | true |
2620fd6e8892cf1838bdbe5a3fd6e9198680a8ca | C++ | annavedenin/Crime-Prediction-Using-Hidden-Markov-Model | /HmmDll code/hmm.h | UTF-8 | 1,369 | 2.828125 | 3 | [] | no_license | /*********************************************************************************************/
// Name: hmm.h
//
// class of the Hidden Markov Model structur
//
/*********************************************************************************************/
#pragma once
#include <iostream>
#include <fstream>
#include<vector>
#include"seq.h"
using std::fstream;
typedef double** matrix_2D;
typedef double*** matrix_3D;
class HMM
{
private:
int N; // number of states; Q={1,2,...,N}
int M; // number of observation symbols; V={1,2,...,M}
long double **A; /* A[1..N][1..N]. a[i][j] is the transition prob
of going from state i at time t to state j
at time t+1 */
long double **B; /* B[1..N][1..M]. b[j][k] is the probability of
of observing symbol k in state j */
long double *pi; /* pi[1..N] pi[i] is the initial state distribution. */
public:
HMM(std::fstream&); // initialize the hmm model from a file
HMM(int, int); // initialize a random hmm model by specifying N and M
~HMM();
void print();
void print(std::ofstream&);
double givePrediction();
friend double** forward(HMM&, Seq&, vector<double>&);
friend double** backward(HMM&, Seq&);
friend int* viterbi(HMM&, Seq&);
friend double baumWelch(HMM&, vector<Seq>, int, double);
friend vector<double> posterior(HMM&, vector<Seq>, int);
}; | true |
f5258751943bd6a87948d9d29143892c027ffa82 | C++ | WubiCookie/cdm | /tests/matrix3.cpp | UTF-8 | 22,081 | 2.90625 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include <common.hpp>
TEST_CASE("matrix3::matrix3(std::array<float, 9>)",
"[working][unittest][matrix3]")
{
const std::array<float, 9> a{0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f};
matrix3 m1 = matrix3(a);
REQUIRE(m1.column(0).row(0) == 0.0f);
REQUIRE(m1.column(0).row(1) == 0.0f);
REQUIRE(m1.column(0).row(2) == 0.0f);
REQUIRE(m1.column(1).row(0) == 0.0f);
REQUIRE(m1.column(1).row(1) == 0.0f);
REQUIRE(m1.column(1).row(2) == 0.0f);
REQUIRE(m1.column(2).row(0) == 0.0f);
REQUIRE(m1.column(2).row(1) == 0.0f);
REQUIRE(m1.column(2).row(2) == 0.0f);
const std::array<float, 9> b{
//
1.0f, 2.5f, 0.1f, //
112.0f, 51.0f, -660.5f, //
-89453.6654f, 3.14159f, -3.23123f //
};
matrix3 m2 = matrix3(b);
REQUIRE(m2.column(0).row(0) == 1.0f);
REQUIRE(m2.column(0).row(1) == 112.0f);
REQUIRE(m2.column(0).row(2) == -89453.6654f);
REQUIRE(m2.column(1).row(0) == 2.5f);
REQUIRE(m2.column(1).row(1) == 51.0f);
REQUIRE(m2.column(1).row(2) == 3.14159f);
REQUIRE(m2.column(2).row(0) == 0.1f);
REQUIRE(m2.column(2).row(1) == -660.5f);
REQUIRE(m2.column(2).row(2) == -3.23123f);
}
TEST_CASE("matrix3::matrix3(matrix3)", "[working][unittest][matrix3]")
{
const std::array<float, 9> a{1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
6.0f, 7.0f, 8.0f, 9.0f};
const matrix3 m1(a);
REQUIRE(m1.column(0).row(0) == 1.0f);
REQUIRE(m1.column(1).row(0) == 2.0f);
REQUIRE(m1.column(2).row(0) == 3.0f);
REQUIRE(m1.column(0).row(1) == 4.0f);
REQUIRE(m1.column(1).row(1) == 5.0f);
REQUIRE(m1.column(2).row(1) == 6.0f);
REQUIRE(m1.column(0).row(2) == 7.0f);
REQUIRE(m1.column(1).row(2) == 8.0f);
REQUIRE(m1.column(2).row(2) == 9.0f);
const matrix3 m2(m1);
CHECK(m2.column(0).row(0) == m1.column(0).row(0));
CHECK(m2.column(1).row(0) == m1.column(1).row(0));
CHECK(m2.column(2).row(0) == m1.column(2).row(0));
CHECK(m2.column(0).row(1) == m1.column(0).row(1));
CHECK(m2.column(1).row(1) == m1.column(1).row(1));
CHECK(m2.column(2).row(1) == m1.column(2).row(1));
CHECK(m2.column(0).row(2) == m1.column(0).row(2));
CHECK(m2.column(1).row(2) == m1.column(1).row(2));
CHECK(m2.column(2).row(2) == m1.column(2).row(2));
}
TEST_CASE("matrix3::zero()", "[working][unittest][matrix3]")
{
matrix3 m = matrix3::zero();
REQUIRE(m.column(0).row(0) == 0.0f);
REQUIRE(m.column(0).row(1) == 0.0f);
REQUIRE(m.column(0).row(2) == 0.0f);
REQUIRE(m.column(1).row(0) == 0.0f);
REQUIRE(m.column(1).row(1) == 0.0f);
REQUIRE(m.column(1).row(2) == 0.0f);
REQUIRE(m.column(2).row(0) == 0.0f);
REQUIRE(m.column(2).row(1) == 0.0f);
REQUIRE(m.column(2).row(2) == 0.0f);
}
TEST_CASE("matrix3::identity()", "[working][unittest][matrix3]")
{
matrix3 m = matrix3::identity();
REQUIRE(m.column(0).row(0) == 1.0f);
REQUIRE(m.column(1).row(1) == 1.0f);
REQUIRE(m.column(2).row(2) == 1.0f);
REQUIRE(m.column(0).row(1) == 0.0f);
REQUIRE(m.column(0).row(2) == 0.0f);
REQUIRE(m.column(1).row(0) == 0.0f);
REQUIRE(m.column(1).row(2) == 0.0f);
REQUIRE(m.column(2).row(0) == 0.0f);
REQUIRE(m.column(2).row(1) == 0.0f);
}
TEST_CASE("matrix3::operator==(const matrix3&)",
"[working][unittest][matrix3]")
{
matrix3 m1 = matrix3::zero();
matrix3 m2 = matrix3::zero();
REQUIRE(m1 == m2);
m1 = matrix3::identity();
m2 = matrix3::identity();
REQUIRE(m1 == m2);
const std::array<float, 9> a{
1.0f, 2.5f, 0.1f, //
112.0f, 51.0f, -660.5f, //
-89453.6654f, 3.14159f, -3.23123f //
};
m1 = matrix3(a);
m2 = matrix3(a);
REQUIRE(m1 == m2);
m2.column(0).row(0) = 2.0f;
REQUIRE_FALSE(m1 == m2);
m1.column(0).row(0) = 1.0f;
m1.column(0).row(1) = 2.0f;
m1.column(0).row(2) = 3.0f;
m1.column(1).row(0) = 5.0f;
m1.column(1).row(1) = 6.0f;
m1.column(1).row(2) = 7.0f;
m1.column(2).row(0) = 9.0f;
m1.column(2).row(1) = 10.0f;
m1.column(2).row(2) = 11.0f;
m2.column(0).row(0) = 1.0f;
m2.column(0).row(1) = 2.0f;
m2.column(0).row(2) = 3.0f;
m2.column(1).row(0) = 5.0f;
m2.column(1).row(1) = 6.0f;
m2.column(1).row(2) = 7.0f;
m2.column(2).row(0) = 9.0f;
m2.column(2).row(1) = 10.0f;
m2.column(2).row(2) = 11.0f;
REQUIRE(m1 == m2);
REQUIRE_THAT(m1, Matrix3Matcher(m2, 0.0));
}
TEST_CASE("matrix3::to_array() and matrix3::matrix3(array)",
"[working][unittest][matrix3]")
{
matrix3 m1 = matrix3::zero();
matrix3 m2 = matrix3::zero();
REQUIRE(m1 == m2);
REQUIRE(m1.to_array() == m2.to_array());
m1 = matrix3::identity();
m2 = matrix3::identity();
REQUIRE(m1 == m2);
REQUIRE(m1.to_array() == m2.to_array());
const std::array<float, 9> a{
1.0f, 2.5f, 0.1f, //
112.0f, 51.0f, -660.5f, //
-89453.6654f, 3.14159f, -3.23123f //
};
m1 = matrix3(a);
m2 = matrix3(a);
REQUIRE(m1.to_array() == m2.to_array());
REQUIRE(matrix3(m1.to_array()) == matrix3(m2.to_array()));
REQUIRE(matrix3(m1.to_array()).to_array() ==
matrix3(m2.to_array()).to_array());
m2.column(0).row(0) = 2.0f;
REQUIRE_FALSE(m1 == m2);
REQUIRE_FALSE(m1.to_array() == m2.to_array());
}
TEST_CASE("matrix3::rotation(euler_angles)_X", "[working][unittest][matrix3]")
{
const auto angle = radian(float(pi / 2.0));
const euler_angles r{angle, 0_rad, 0_rad};
const matrix3 m = matrix3::rotation(r);
const std::array<float, 9> a = m.to_array();
const auto rotx = m * vector3(1.0f, 0.0f, 0.0f);
CHECK_THAT(rotx, Vector3Matcher({1.0f, 0.0f, 0.0f}));
const auto roty = m * vector3(0.0f, 1.0f, 0.0f);
CHECK_THAT(roty, Vector3Matcher({0.0f, 0.0f, 1.0f}));
const auto rotz = m * vector3(0.0f, 0.0f, 1.0f);
CHECK_THAT(rotz, Vector3Matcher({0.0f, -1.0f, 0.0f}));
{
const matrix3 m2 = matrix3::rotation_around_x(angle);
CHECK_THAT(m, Matrix3Matcher(m2));
}
}
TEST_CASE("matrix3::rotation(euler_angles)_Y", "[working][unittest][matrix3]")
{
const auto angle = radian(float(pi / 2.0));
const euler_angles r{0_rad, angle, 0_rad};
const matrix3 m = matrix3::rotation(r);
const std::array<float, 9> a = m.to_array();
const auto rotx = m * vector3(1.0f, 0.0f, 0.0f);
CHECK_THAT(rotx, Vector3Matcher({0.0f, 0.0f, -1.0f}));
const auto roty = m * vector3(0.0f, 1.0f, 0.0f);
CHECK_THAT(roty, Vector3Matcher({0.0f, 1.0f, 0.0f}));
const auto rotz = m * vector3(0.0f, 0.0f, 1.0f);
CHECK_THAT(rotz, Vector3Matcher({1.0f, 0.0f, 0.0f}));
{
const matrix3 m2 = matrix3::rotation_around_y(angle);
CHECK_THAT(m, Matrix3Matcher(m2));
}
}
TEST_CASE("matrix3::rotation(euler_angles)_Z", "[working][unittest][matrix3]")
{
const auto angle = radian(float(pi / 2.0));
const euler_angles r{0_rad, 0_rad, angle};
const matrix3 m = matrix3::rotation(r);
const std::array<float, 9> a = m.to_array();
const auto rotx = m * vector3(1.0f, 0.0f, 0.0f);
CHECK_THAT(rotx, Vector3Matcher({0.0f, 1.0f, 0.0f}));
const auto roty = m * vector3(0.0f, 1.0f, 0.0f);
CHECK_THAT(roty, Vector3Matcher({-1.0f, 0.0f, 0.0f}));
const auto rotz = m * vector3(0.0f, 0.0f, 1.0f);
CHECK_THAT(rotz, Vector3Matcher({0.0f, 0.0f, 1.0f}));
{
const matrix3 m2 = matrix3::rotation_around_z(angle);
CHECK_THAT(m, Matrix3Matcher(m2));
}
}
TEST_CASE("matrix3::rotation(quaternion)", "[working][unittest][matrix3]")
{
quaternion q{1.0f, 2.0f, 3.0f, 4.0f};
q.normalize();
const matrix3 m2 = matrix3::rotation(q);
const matrix4 m4 = matrix4::rotation(q);
matrix3 m3;
m3.row(0) = m4.row(0).xyz();
m3.row(1) = m4.row(1).xyz();
m3.row(2) = m4.row(2).xyz();
const std::array<float, 9> a = m2.to_array();
const std::array<float, 9> b = m3.to_array();
REQUIRE(a == b);
}
TEST_CASE("matrix3::scale(vector3)", "[working][unittest][matrix3]")
{
vector3 s{0.5f, 0.4f, 0.3f};
matrix3 m = matrix3::scale(s);
REQUIRE(m.column(0).row(0) == s.x);
REQUIRE(m.column(1).row(1) == s.y);
REQUIRE(m.column(2).row(2) == s.z);
REQUIRE(m.column(0).row(1) == 0.0f);
REQUIRE(m.column(0).row(2) == 0.0f);
REQUIRE(m.column(1).row(0) == 0.0f);
REQUIRE(m.column(1).row(2) == 0.0f);
REQUIRE(m.column(2).row(0) == 0.0f);
REQUIRE(m.column(2).row(1) == 0.0f);
}
TEST_CASE("matrix3::scale(float, float, float)",
"[working][unittest][matrix3]")
{
float x{0.5f};
float y{0.4f};
float z{0.3f};
matrix3 m = matrix3::scale(x, y, z);
REQUIRE(m.column(0).row(0) == x);
REQUIRE(m.column(1).row(1) == y);
REQUIRE(m.column(2).row(2) == z);
REQUIRE(m.column(0).row(1) == 0.0f);
REQUIRE(m.column(0).row(2) == 0.0f);
REQUIRE(m.column(1).row(0) == 0.0f);
REQUIRE(m.column(1).row(2) == 0.0f);
REQUIRE(m.column(2).row(0) == 0.0f);
REQUIRE(m.column(2).row(1) == 0.0f);
}
TEST_CASE("matrix3::scale(float)", "[working][unittest][matrix3]")
{
float s{0.5f};
matrix3 m = matrix3::scale(s);
REQUIRE(m.column(0).row(0) == s);
REQUIRE(m.column(1).row(1) == s);
REQUIRE(m.column(2).row(2) == s);
REQUIRE(m.column(0).row(1) == 0.0f);
REQUIRE(m.column(0).row(2) == 0.0f);
REQUIRE(m.column(1).row(0) == 0.0f);
REQUIRE(m.column(1).row(2) == 0.0f);
REQUIRE(m.column(2).row(0) == 0.0f);
REQUIRE(m.column(2).row(1) == 0.0f);
}
TEST_CASE("matrix3::rotation_around_x(radian)", "[working][unittest][matrix3]")
{
using ::Catch::Matchers::WithinAbs;
const direction3 axis = direction3::posX();
const vector3 v0{0.0f, 1.0f, 0.0f};
const vector3 vE{0.0f, 0.0f, 1.0f};
{
const radian rotation{0_rad};
const matrix3 m = matrix3::rotation_around_x(rotation);
const vector3 v1 = m * v0;
CHECK(v1 == v0);
}
{
const radian rotation{90_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const vector3 v1 = m * v0;
CHECK_THAT(v1, Vector3Matcher(vE));
const matrix3 m2 =
matrix3::rotation(quaternion{axis, static_pi_fraction<1, 2>{}});
const vector3 v2 = m2 * v0;
CHECK_THAT(v2, Vector3Matcher(vE));
CHECK_THAT(m, Matrix3Matcher(m2));
const matrix3 m3 = matrix3::rotation(axis, rotation);
const vector3 v3 = m3 * v0;
CHECK_THAT(v3, Vector3Matcher(vE));
CHECK_THAT(m2, Matrix3Matcher(m3));
const matrix3 m4 = matrix3::rotation(axis, static_pi_fraction<1, 2>{});
const vector3 v4 = m4 * v0;
CHECK_THAT(v4, Vector3Matcher(vE));
CHECK_THAT(m3, Matrix3Matcher(m4));
}
{
const radian rotation{15_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const matrix3 m2 = matrix3::rotation(quaternion{axis, rotation});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{45_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const matrix3 m2 = matrix3::rotation(quaternion{axis, rotation});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{90_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const matrix3 m2 = matrix3::rotation(quaternion{axis, rotation});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{180_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const matrix3 m2 = matrix3::rotation(quaternion{axis, rotation});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{270_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const matrix3 m2 = matrix3::rotation(quaternion{axis, rotation});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{360_deg};
const matrix3 m = matrix3::rotation_around_x(rotation);
const matrix3 m2 = matrix3::rotation(quaternion{axis, rotation});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{pi};
const matrix3 m = matrix3::rotation_around_x(rotation);
const vector3 v1 = m * v0;
CHECK_THAT(v1, Vector3Matcher(-v0));
}
}
TEST_CASE("matrix3::rotation_around_y(radian)", "[working][unittest][matrix3]")
{
using ::Catch::Matchers::WithinAbs;
const vector3 v0{0.0f, 0.0f, 1.0f};
const vector3 vE{1.0f, 0.0f, 0.0f};
{
radian rotation{0_rad};
matrix3 m = matrix3::rotation_around_y(rotation);
vector3 v1 = m * v0;
CHECK(v1 == v0);
}
const auto almost_0 = Approx(0.0f).margin(1.0e-6);
{
radian rotation{90_deg};
matrix3 m = matrix3::rotation_around_y(rotation);
vector3 v1 = m * v0;
CHECK_THAT(v1, Vector3Matcher(vE));
matrix3 m2 = matrix3::rotation(
quaternion{direction3::posY(), static_pi_fraction<1, 2>{}});
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
radian rotation{pi};
matrix3 m = matrix3::rotation_around_y(rotation);
vector3 v1 = m * v0;
CHECK_THAT(v1, Vector3Matcher(-v0));
}
}
TEST_CASE("matrix3::rotation_around_z(radian)", "[working][unittest][matrix3]")
{
using ::Catch::Matchers::WithinAbs;
const vector3 v0{1.0f, 0.0f, 0.0f};
const vector3 vE{0.0f, 1.0f, 0.0f};
{
const radian rotation{0_rad};
const matrix3 m = matrix3::rotation_around_z(rotation);
const vector3 v1 = m * v0;
CHECK(v1 == v0);
}
{
const radian rotation{90_deg};
const matrix3 m = matrix3::rotation_around_z(rotation);
const vector3 v1 = m * v0;
CHECK_THAT(v1, Vector3Matcher(vE));
const matrix3 m2 = matrix3::rotation(
quaternion{direction3::posZ(), static_pi_fraction<1, 2>{}});
const vector3 v2 = m2 * v0;
CHECK_THAT(v2, Vector3Matcher(vE));
CHECK_THAT(m, Matrix3Matcher(m2));
}
{
const radian rotation{pi};
const matrix3 m = matrix3::rotation_around_z(rotation);
const vector3 v1 = m * v0;
CHECK_THAT(v1, Vector3Matcher(-v0));
}
}
TEST_CASE("matrix3::rotation_around_z(complex)",
"[working][unittest][matrix3]")
{
const vector3 v0{1.0f, 0.0f, 0.0f};
{
normalized<complex> rotation{0_rad};
matrix3 m = matrix3::rotation_around_z(rotation);
vector3 v1 = m * v0;
CHECK(v1 == v1);
}
const auto almost_0 = Approx(0.0f).margin(1.0e-6);
{
normalized<complex> rotation{90_deg};
matrix3 m = matrix3::rotation_around_z(rotation);
vector3 v1 = m * v0;
CHECK(std::abs(v1.x) == almost_0);
CHECK(v1.y == Approx(1.0f).margin(1.0e-6));
CHECK(std::abs(v1.z) == almost_0);
matrix3 m2 = matrix3::rotation(
quaternion{direction3::posZ(), static_pi_fraction<1, 2>{}});
REQUIRE_THAT(m, Matrix3Matcher(m2));
}
{
normalized<complex> rotation{1_pi};
matrix3 m = matrix3::rotation_around_z(rotation);
vector3 v1 = m * v0;
CHECK(v1.x == Approx(-v0.x).margin(1.0e-6));
CHECK(v1.y == Approx(-v0.y).margin(1.0e-6));
CHECK(v1.z == Approx(-v0.z).margin(1.0e-6));
}
}
TEST_CASE("matrix3::rows(vector3, vector3, vector3)",
"[working][unittest][matrix3]")
{
matrix3 m = matrix3::rows({1.0f, 2.0f, 3.0f}, {5.0f, 6.0f, 7.0f},
{9.0f, 10.0f, 11.0f});
REQUIRE(m.row(0).column(0) == 1.0f);
REQUIRE(m.row(0).column(1) == 2.0f);
REQUIRE(m.row(0).column(2) == 3.0f);
REQUIRE(m.row(1).column(0) == 5.0f);
REQUIRE(m.row(1).column(1) == 6.0f);
REQUIRE(m.row(1).column(2) == 7.0f);
REQUIRE(m.row(2).column(0) == 9.0f);
REQUIRE(m.row(2).column(1) == 10.0f);
REQUIRE(m.row(2).column(2) == 11.0f);
}
TEST_CASE("matrix3::columns(vector3, vector3, vector3)",
"[working][unittest][matrix3]")
{
matrix3 m = matrix3::columns({1.0f, 2.0f, 3.0f}, {5.0f, 6.0f, 7.0f},
{9.0f, 10.0f, 11.0f});
REQUIRE(m.column(0).row(0) == 1.0f);
REQUIRE(m.column(0).row(1) == 2.0f);
REQUIRE(m.column(0).row(2) == 3.0f);
REQUIRE(m.column(1).row(0) == 5.0f);
REQUIRE(m.column(1).row(1) == 6.0f);
REQUIRE(m.column(1).row(2) == 7.0f);
REQUIRE(m.column(2).row(0) == 9.0f);
REQUIRE(m.column(2).row(1) == 10.0f);
REQUIRE(m.column(2).row(2) == 11.0f);
}
TEST_CASE("matrix3::row(int)", "[working][unittest][matrix3]")
{
vector3 v0{1.0f, 2.0f, 3.0f};
vector3 v1{5.0f, 6.0f, 7.0f};
vector3 v2{9.0f, 10.0f, 11.0f};
matrix3 m = matrix3::rows(v0, v1, v2);
REQUIRE(v0 == m.row(0));
REQUIRE(v1 == m.row(1));
REQUIRE(v2 == m.row(2));
for (int i = 0; i < 3; ++i)
{
m.row(i) = vector3(-1.0f, -2.0f, -3.0f);
REQUIRE(m.row(i).column(0) == -1.0f);
REQUIRE(m.row(i).column(1) == -2.0f);
REQUIRE(m.row(i).column(2) == -3.0f);
REQUIRE(m.row(i) == vector3(-1.0f, -2.0f, -3.0f));
}
}
TEST_CASE("matrix3::column(int)", "[working][unittest][matrix3]")
{
vector3 v0{1.0f, 2.0f, 3.0f};
vector3 v1{5.0f, 6.0f, 7.0f};
vector3 v2{9.0f, 10.0f, 11.0f};
matrix3 m = matrix3::columns(v0, v1, v2);
REQUIRE(v0 == m.column(0));
REQUIRE(v1 == m.column(1));
REQUIRE(v2 == m.column(2));
for (int i = 0; i < 3; ++i)
{
m.column(i) = vector3(-1.0f, -2.0f, -3.0f);
REQUIRE(m.column(i).row(0) == -1.0f);
REQUIRE(m.column(i).row(1) == -2.0f);
REQUIRE(m.column(i).row(2) == -3.0f);
REQUIRE(m.column(i) == vector3(-1.0f, -2.0f, -3.0f));
}
}
TEST_CASE("matrix3::diag(int)", "[working][unittest][matrix3]")
{
vector3 v0{1.0f, 2.0f, 3.0f};
vector3 v1{5.0f, 6.0f, 7.0f};
vector3 v2{9.0f, 10.0f, 11.0f};
matrix3 m = matrix3::columns(v0, v1, v2);
REQUIRE(v0.x == m.diag(0));
REQUIRE(v1.y == m.diag(1));
REQUIRE(v2.z == m.diag(2));
m.diag(0) = -1.0f;
m.diag(1) = -2.0f;
m.diag(2) = -3.0f;
REQUIRE(m.diag(0) == -1.0f);
REQUIRE(m.diag(1) == -2.0f);
REQUIRE(m.diag(2) == -3.0f);
REQUIRE(m.diag() == vector3(-1.0f, -2.0f, -3.0f));
}
TEST_CASE("matrix3::diag()", "[working][unittest][matrix3]")
{
vector3 v0{1.0f, 2.0f, 3.0f};
vector3 v1{5.0f, 6.0f, 7.0f};
vector3 v2{9.0f, 10.0f, 11.0f};
matrix3 m = matrix3::columns(v0, v1, v2);
REQUIRE(v0.x == m.diag().x);
REQUIRE(v1.y == m.diag().y);
REQUIRE(v2.z == m.diag().z);
m.diag() = vector3(-1.0f, -2.0f, -3.0f);
REQUIRE(m.diag().x == -1.0f);
REQUIRE(m.diag().y == -2.0f);
REQUIRE(m.diag().z == -3.0f);
REQUIRE(m.diag() == vector3(-1.0f, -2.0f, -3.0f));
}
TEST_CASE("matrix3::is_orthogonal()", "[working][unittest][matrix3]")
{
CHECK(false == matrix3::zero().is_orthogonal());
const matrix3 m2 = matrix3::identity();
CHECK(true == m2.is_orthogonal());
}
TEST_CASE("matrix3::inverse()", "[working][unittest][matrix3]")
{
matrix3 m1;
// scale
{
const vector3 scale{4589.0f, 132.015f, 0.00125f};
const vector3 invScale{1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z};
m1 = matrix3::scale(scale);
m1.inverse();
matrix3 m2 = matrix3::scale(invScale);
CHECK_THAT(m1, Matrix3Matcher(m2));
}
const radian rotation = 90_deg;
// rotation around x
{
const vector3 p0{1.f, 2.0f, 3.0f};
m1 = matrix3::rotation_around_x(rotation);
const vector3 p1 = m1 * p0;
m1.inverse();
const vector3 p2 = m1 * p1;
CHECK_THAT(p0, Vector3Matcher(p2));
}
// rotation around y
{
const vector3 p0{1.f, 2.0f, 3.0f};
m1 = matrix3::rotation_around_y(rotation);
const vector3 p1 = m1 * p0;
m1.inverse();
const vector3 p2 = m1 * p1;
CHECK_THAT(p0, Vector3Matcher(p2));
}
// rotation around z
{
const vector3 p0{1.f, 2.0f, 3.0f};
m1 = matrix3::rotation_around_z(rotation);
const vector3 p1 = m1 * p0;
m1.inverse();
const vector3 p2 = m1 * p1;
CHECK_THAT(p0, Vector3Matcher(p2));
}
}
TEST_CASE("matrix3::get_inversed()", "[working][unittest][matrix3]")
{
const std::array<float, 9> a{1.0f, 4.0f, 2.0f, 3.0f, 8.0f,
10.0f, 2.0f, 6.0f, 1.0f};
matrix3 m1{a};
const matrix3 m2{m1.get_inversed()};
m1.inverse();
REQUIRE(m1 == m2);
}
TEST_CASE("matrix3::transpose()", "[working][unittest][matrix3]")
{
matrix3 m1;
m1.column(0).row(0) = 1.0f;
m1.column(0).row(1) = 2.0f;
m1.column(0).row(2) = 3.0f;
m1.column(1).row(0) = 5.0f;
m1.column(1).row(1) = 6.0f;
m1.column(1).row(2) = 7.0f;
m1.column(2).row(0) = 9.0f;
m1.column(2).row(1) = 10.0f;
m1.column(2).row(2) = 11.0f;
matrix3 m2 = m1;
m2.transpose();
REQUIRE(m2.row(0).column(0) == 1.0f);
REQUIRE(m2.row(0).column(1) == 2.0f);
REQUIRE(m2.row(0).column(2) == 3.0f);
REQUIRE(m2.row(1).column(0) == 5.0f);
REQUIRE(m2.row(1).column(1) == 6.0f);
REQUIRE(m2.row(1).column(2) == 7.0f);
REQUIRE(m2.row(2).column(0) == 9.0f);
REQUIRE(m2.row(2).column(1) == 10.0f);
REQUIRE(m2.row(2).column(2) == 11.0f);
}
TEST_CASE("matrix3::get_transposed()", "[working][unittest][matrix3]")
{
matrix3 m1;
m1.column(0).row(0) = 1.0f;
m1.column(0).row(1) = 2.0f;
m1.column(0).row(2) = 3.0f;
m1.column(1).row(0) = 5.0f;
m1.column(1).row(1) = 6.0f;
m1.column(1).row(2) = 7.0f;
m1.column(2).row(0) = 9.0f;
m1.column(2).row(1) = 10.0f;
m1.column(2).row(2) = 11.0f;
matrix3 m2 = m1;
m2.transpose();
CHECK(m1.get_transposed() == m2);
}
TEST_CASE("matrix3::determinant()", "[working][unittest][matrix3]")
{
const matrix3 m2 = matrix3(std::array<float, 9>{
1.0f, 4.0f, 2.0f, 3.0f, 8.0f, 10.0f, 2.0f, 6.0f, 1.0f});
const float d = m2.determinant();
CHECK(d == 20.0f);
}
TEST_CASE("matrix3::operator*(const matrix3&)", "[working][unittest][matrix3]")
{
matrix3 m1;
m1.column(0).row(0) = 1.0f;
m1.column(0).row(1) = 2.0f;
m1.column(0).row(2) = 3.0f;
m1.column(1).row(0) = 4.0f;
m1.column(1).row(1) = 5.0f;
m1.column(1).row(2) = 6.0f;
m1.column(2).row(0) = 7.0f;
m1.column(2).row(1) = 8.0f;
m1.column(2).row(2) = 9.0f;
matrix3 m2 = m1 * m1;
REQUIRE(m2.column(0).row(0) == 30.0f);
REQUIRE(m2.column(0).row(1) == 36.0f);
REQUIRE(m2.column(0).row(2) == 42.0f);
REQUIRE(m2.column(1).row(0) == 66.0f);
REQUIRE(m2.column(1).row(1) == 81.0f);
REQUIRE(m2.column(1).row(2) == 96.0f);
REQUIRE(m2.column(2).row(0) == 102.0f);
REQUIRE(m2.column(2).row(1) == 126.0f);
REQUIRE(m2.column(2).row(2) == 150.0f);
vector3 s{123.0f, 456.0f, 789.0f};
m1 = matrix3::scale(s);
m2 = m1 * m1;
REQUIRE(m2.column(0).row(0) == s.x * s.x);
REQUIRE(m2.column(0).row(1) == 0.0f);
REQUIRE(m2.column(0).row(2) == 0.0f);
REQUIRE(m2.column(1).row(0) == 0.0f);
REQUIRE(m2.column(1).row(1) == s.y * s.y);
REQUIRE(m2.column(1).row(2) == 0.0f);
REQUIRE(m2.column(2).row(0) == 0.0f);
REQUIRE(m2.column(2).row(1) == 0.0f);
REQUIRE(m2.column(2).row(2) == s.z * s.z);
}
TEST_CASE("matrix3::operator*(vector3)", "[working][unittest][matrix3]")
{
const vector3 v0{1.0f, 2.0f, 3.0f};
const vector3 s{123.0f, 456.0f, 789.0f};
matrix3 m = matrix3::scale(s);
vector3 v1 = m * v0;
REQUIRE(v1.x == (v0.x * s.x));
REQUIRE(v1.y == (v0.y * s.y));
REQUIRE(v1.z == (v0.z * s.z));
float scale{20.01f};
m = matrix3::scale(scale);
v1 = m * v0;
REQUIRE(v1.x == (v0.x * scale));
REQUIRE(v1.y == (v0.y * scale));
REQUIRE(v1.z == (v0.z * scale));
}
| true |
630b7f3ebc2187aeaea41316ef3680db347da5d1 | C++ | cdriveraus/OpenMx | /src/finiteDifferences.h | UTF-8 | 1,052 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef _finiteDifferences_H_
#define _finiteDifferences_H_
template <typename T1, typename T2, typename T3>
void fd_gradient(T1 ff, Eigen::MatrixBase<T2> &point, Eigen::MatrixBase<T3> &gradOut)
{
const double refFit = ff(point); // maybe could avoid this? TODO
const double eps = 1e-5;
Eigen::VectorXd p2;
for (int px=0; px < int(point.size()); ++px) {
p2 = point;
double offset = std::max(fabs(p2[px] * eps), eps);
p2[px] += offset;
gradOut[px] = (ff(p2) - refFit) / offset;
}
}
template <typename T1, typename T2, typename T3, typename T4>
void fd_jacobian(T1 ff, Eigen::MatrixBase<T2> &point, Eigen::MatrixBase<T3> &ref,
bool refOnly, Eigen::MatrixBase<T4> &jacobiOut)
{
const double eps = 1e-5;
ff(point, ref);
if (refOnly) return;
Eigen::VectorXd p2;
for (int px=0; px < int(point.size()); ++px) {
p2 = point;
double offset = std::max(fabs(p2[px] * eps), eps);
p2[px] += offset;
Eigen::VectorXd probe(jacobiOut.cols());
ff(p2, probe);
jacobiOut.row(px) = (probe - ref) / offset;
}
}
#endif
| true |
f7fdcfca8feeff4270707e8d78734c2d7459f115 | C++ | ColinShaw/cpp-pid-controller-driving-project | /src/PID.cpp | UTF-8 | 650 | 2.828125 | 3 | [] | no_license | #include "PID.h"
PID::PID(double Kp_in, double Ki_in, double Kd_in)
{
// Initial coefficients
Kp = Kp_in;
Ki = Ki_in;
Kd = Kd_in;
// PID Error terms
p_error = 0.0;
i_error = 0.0;
d_error = 0.0;
// Last sample error and total error
last_error = 0.0;
total_error = 0.0;
}
PID::~PID() {}
double PID::Update(double error)
{
// Update the error term
p_error = error;
i_error += error;
d_error = error - last_error;
// Update last error
last_error = error;
// update total error
total_error += error * error;
// Return the evaluated filter
return -1.0 * (Kp * p_error + Ki * i_error + Kd * d_error);
}
| true |
06466c78a5db9d771658f46ac2af79422a22bd46 | C++ | RENHaowen/Vanet | /geologic-core/include/geologic-core/objects/geo/untemporal/MeshGrid.h | UTF-8 | 1,330 | 2.9375 | 3 | [] | no_license | /**
* \file MeshGrid.h
*/
#ifndef MeshGrid_H
#define MeshGrid_H
#include "ogr_geometry.h"
#include <unordered_map>
template <typename T> class MeshGrid {
public:
//*/ -------------------------------------------------
using Position = std::pair<int, int>;
std::unordered_map<Position, T>& getGrid() {return grid;}
const std::unordered_map<Position, T>& getGrid()const {return grid;}
T& get(int i, int j) noexcept(false) {return grid.at({i, j});}
const T& get(int i, int j)const noexcept(false) {return grid.at({i, j});}
private:
//*/ -------------------------------------------------
std::unordered_map<Position, T> grid; ///< the content of the grid, one element for each mesh with information
OGRPoint origin; ///< its point of origin (with its attached spatial reference).
double mesh_x_length; ///< the width of each mesh (in _origin spatial reference units)
double mesh_y_length; ///< the height of each mesh (in _origin spatial reference units)
int x_count; ///< the number of meshes on the x coordinate (from left to right)
int y_count; ///< the number of meshes on the y coordinate (from bottom to top)
};
#endif // MeshGrid_H
| true |
7db01d7cf9795339698a3f565213ed1c84cab5da | C++ | luni64/TeensyStep | /examples/Applications/Winder/Winder.h | UTF-8 | 1,188 | 2.84375 | 3 | [
"MIT"
] | permissive | #pragma once
#include "TeensyStep.h"
class Winder
{
public:
Winder(Stepper &spindle, Stepper &feeder);
void begin();
Winder &setSpindleParams(unsigned stpPerRev, unsigned acceleration); // steps per spindle revolution & acceleration in stp/s^2
Winder &setFeederParams(unsigned stpPerMM, unsigned acceleration); // steps to move the feeder 1mm, acceleration for pitch trimming
void setSpindleSpeed(float rpm); // changes the spindle speed to the given rpm
void setPitch(float pitch_in_mm); // changes the winder pitch to the given value
void updateSpeeds();
inline int getCurSpindleSpeed() { return spindleCtrl.isRunning() ? spindleCtrl.getCurrentSpeed() : 0; }
inline int getCurFeederSpeed() { return feederCtrl.isRunning() ? feederCtrl.getCurrentSpeed() : 0; }
inline float getCurPitch(){return (float)getCurFeederSpeed()/getCurSpindleSpeed()/pitchFactor; }
protected:
Stepper &spindle;
Stepper &feeder;
unsigned spindleStpPerRev, spindleAcc, feederStpPerMM, feederAcc;
float pitchFactor;
float targetSpindleSpeed, targetPitch;
float oldSpindleSpeed, oldPitch;
RotateControl feederCtrl, spindleCtrl;
}; | true |
006d97a01da9a73d8794b015e4d0f6d9400f0df5 | C++ | Mohit21/Questions | /AmazonNumberofoccurrences.cpp | UTF-8 | 1,286 | 3.03125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int start(int A[],int beg,int end1,int x,int N){
if(end1>=beg){
int mid=(beg+end1)/2;
if((mid==0 || A[mid]==x) && A[mid-1]<x){
//cout<<"h1"<<mid<<endl;
return mid;
}
else if(A[mid]<x){
//cout<<"h2";
return start(A,(mid+1),end1,x,N);
}
else{
//cout<<"h3";
return start(A,beg,(mid-1),x,N);
}
}
else{
return -1;
}
}
int last(int A[],int beg,int end1,int x,int N){
if(end1>=beg){
int mid=(beg+end1)/2;
if((mid==N-1 || A[mid+1]>x) && A[mid]==x){
return mid;
}
else if(A[mid]>x){
return last(A,beg,(mid-1),x,N);
}
else{
return last(A,(mid+1),end1,x,N);
}
}
else{
return -1;
}
}
int occur(int A[],int N,int x){
int stroc,endoc;
stroc=start(A,0,N-1,x,N);
if(stroc==-1){
return stroc;
}
endoc=last(A,stroc,N-1,x,N);
//cout<<endl<<str<<" "<<end<<endl;
return (endoc-stroc+1);
}
int main(){
int A[]={1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8, 9};
int N=sizeof(A)/sizeof(A[0]);
int x;
cin>>x;
cout<<occur(A,N,x);
return 0;
}
| true |
6165429f303a45289b1d8b825bd54feda3335d21 | C++ | jinsenglin/cplusplus | /10.bst/main.cpp | UTF-8 | 7,345 | 3.953125 | 4 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
class Pair {
friend class Tree;
friend class BST;
public:
Pair(int key, int element) {
first = key;
second = element;
}
~Pair() {}
string ToString() {
return to_string(this->first) + " : " + to_string(this->second);
}
private:
int first;
int second;
};
class TreeNode {
friend class Tree;
friend class BST;
public:
TreeNode(const Pair & pair) {
this->data = new Pair(pair);
this->leftChild = NULL;
this->rightChild = NULL;
this->leftSize = 0;
}
TreeNode(const Pair & pair, const TreeNode & left, const TreeNode & right) {
this->data = new Pair(pair);
this->leftChild = new TreeNode(left);
this->rightChild = new TreeNode(right);
}
~TreeNode() {}
void SetLeft(const TreeNode & n) {
this->leftChild = new TreeNode(n);
}
void SetRight(const TreeNode & n) {
this->rightChild = new TreeNode(n);
}
void SetLeftSize(int s) {
this->leftSize = s;
}
private:
Pair* data;
TreeNode* leftChild;
TreeNode* rightChild;
int leftSize;
};
class Tree {
public:
Tree() {
root = NULL;
}
~Tree() {}
void InorderVisit() {
this->Inorder(root);
}
void PreorderVisit() {
this->Preorder(root);
}
void PostorderVisit() {
this->Postorder(root);
}
void LevelorderVisit() {
// TODO
}
void SetRoot(const TreeNode & n) {
this->root = new TreeNode(n);
}
private:
TreeNode* root;
void Visit(TreeNode* currentNode) {
cout << currentNode->data->ToString() << endl;
}
void Inorder(TreeNode* currentNode) {
if (currentNode) {
Inorder(currentNode->leftChild);
Visit(currentNode); // e.g., printout information
Inorder(currentNode->rightChild);
}
}
void Preorder(TreeNode* currentNode) {
if (currentNode) {
Visit(currentNode); // e.g., printout information
Preorder(currentNode->leftChild);
Preorder(currentNode->rightChild);
}
}
void Postorder(TreeNode* currentNode) {
if (currentNode) {
Postorder(currentNode->leftChild);
Postorder(currentNode->rightChild);
Visit(currentNode); // e.g., printout information
}
}
};
class BST {
public:
BST() {
root = NULL;
}
~BST() {}
void SetNodeLeftSize(int k, int s) {
TreeNode* currentNode = root;
while (currentNode) {
if (k < currentNode->data->first) currentNode = currentNode->leftChild;
else if (k > currentNode->data->first) currentNode = currentNode->rightChild;
else {
currentNode->leftSize = s;
return;
}
}
}
// Recursive Search Codes
Pair* Get(int k) {
return this->Get(root, k);
}
Pair* Get(TreeNode* p, int k) {
if (!p) return 0;
if (k < p->data->first) return this->Get(p->leftChild, k);
if (k > p->data->first) return this->Get(p->rightChild, k);
return p->data;
}
/*
// Iterative Search Codes
Pair* Get(int k) {
TreeNode* currentNode = root;
while (currentNode) {
if (k < currentNode->data->first) currentNode = currentNode->leftChild;
else if (k > currentNode->data->first) currentNode = currentNode->rightChild;
else return currentNode->data;
}
return NULL;
}
*/
Pair* RankGet(int r) {
TreeNode* currentNode = root;
while (currentNode) {
if (r < currentNode->leftSize) currentNode = currentNode->leftChild;
else if (r > currentNode->leftSize) {
r -= currentNode->leftSize;
currentNode = currentNode->rightChild;
}
else return currentNode->data;
}
return 0;
}
void Insert(const Pair & thePair) {
// Search for key “thePair.first”, pp is the parent of p
TreeNode* p = root, *pp = 0;
while (p) {
pp = p;
if (thePair.first < p->data->first) p = p->leftChild;
else if (thePair.first > p->data->first) p = p->rightChild;
else {
// Duplicate, update the value of element
p->data->second = thePair.second;
return;
}
}
// Perform the insertion
p = new TreeNode(thePair);
if (root) {
// tree is not empty
if (thePair.first < pp->data->first) pp->leftChild = p;
else pp->rightChild = p;
}
else root = p;
}
void Delete(int k) {
// TODO
}
void InorderVisit() {
this->Inorder(this->root);
cout << endl;
}
private:
TreeNode* root;
void Inorder(TreeNode* currentNode) {
if (currentNode) {
Inorder(currentNode->leftChild);
cout << to_string(currentNode->data->first) << " ";
Inorder(currentNode->rightChild);
}
}
};
int main() {
/*
// Demo 1
Pair p (1, 1);
TreeNode n (p);
Tree t;
t.SetRoot(n);
t.InorderVisit();
t.PreorderVisit();
t.PostorderVisit();
*/
/*
// Demo 2
TreeNode n15 (*(new Pair(15, 15)));
TreeNode n25 (*(new Pair(25, 25)));
TreeNode root (*(new Pair(20, 20)), n15, n25);
Tree t;
t.SetRoot(root);
t.InorderVisit();
t.PreorderVisit();
t.PostorderVisit();
*/
// Demo 3
BST t;
Pair p1 (30, 30);
Pair p2 (5, 5);
Pair p3 (40, 40);
Pair p4 (2, 2);
Pair p5 (35, 35);
Pair p6 (80, 80);
Pair p7 (1, 1);
Pair p8 (3, 3);
t.Insert(p1);
t.Insert(p2);
t.Insert(p3);
t.Insert(p4);
t.Insert(p5);
t.Insert(p6);
t.Insert(p7);
t.Insert(p8);
t.InorderVisit();
t.SetNodeLeftSize(30, 5);
t.SetNodeLeftSize(5, 4);
t.SetNodeLeftSize(40, 2);
t.SetNodeLeftSize(2, 2);
t.SetNodeLeftSize(35, 1);
t.SetNodeLeftSize(80, 1);
t.SetNodeLeftSize(1, 1);
t.SetNodeLeftSize(3, 1);
Pair* r3 = t.RankGet(3);
if (r3) cout << "DEBUG: " << r3->ToString() << endl;
Pair* r7 = t.RankGet(7);
if (r7) cout << "DEBUG: " << r7->ToString() << endl;
Pair* r6 = t.RankGet(6);
if (r6) cout << "DEBUG: " << r6->ToString() << endl;
Pair* p40 = t.Get(40);
if (p40) cout << "DEBUG: " << p40->ToString() << endl;
return 0;
}
| true |
8516759edbafa0d827a3a2c32d0fa0cfc1e5ce61 | C++ | harshvasoya008/Cpp_Templates | /splitString.cpp | UTF-8 | 263 | 3.125 | 3 | [] | no_license | vector<string> split(const string& s, const char& c){
string buff("");
vector<string> v;
for(auto ch: s){
if(ch != c) buff += ch;
else if(ch == c && buff != "") {
v.push_back(buff);
buff = "";
}
}
if(buff != "") v.push_back(buff);
return v;
} | true |
fd1213b55023f4113f39517e542aa969df4af4bf | C++ | 95ankitmishra/Program-data_structure | /C-my-code-master/52.cpp | UTF-8 | 1,131 | 3.484375 | 3 | [] | no_license | #include<process.h>
#include<malloc.h>
#include<stdio.h>
#include<stdlib.h>
int start,no,choice,item;
struct stack
{
//int no;
struct stack *next;
} *top=NULL;
typedef struct stack st;
void push();
void pop();
void display();
int main()
{
char ch;
//int choice,item;
do
{
printf("\n1: push");
printf("\n2: pop");
printf("\n3: display");
printf("\n4: exit");
printf("\n enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: item = pop();
printf("the deleted element is %d",item);
break;
case 3: display();
break;
case 4: exit(0);
}
}
while(choice !=4)
}
void push()
{
st *p;
p=(st *)malloc(sizeof(st));
printf("enter the number:");
scanf("%d",&p->no);
p->next=top;
top=p;
}
int pop()
{
st *p;
p=start;
if(top==NULL){
printf("stack is already empty:");}
else
{
top=top->next;
return(p->no);
free(p);
}
}
void display()
{
st* p;
p=top;
while(p!=NULL)
{
printf("\n no=%d",p->no);
p=p->next;
}
printf("\n no =%d",p->no);
}
| true |
b782af90200aacade61f8e1fbf6d1e1130a81e9a | C++ | zhangj1024/QtWebrtc | /WebrtcLogic/HttpAPI/ServerHelper.cpp | UTF-8 | 1,269 | 2.515625 | 3 | [] | no_license | #include "StdAfx.h"
#include "ServerHelper.h"
QString ServerHelper::s_serverUrl = "";
ServerHelper::ServerHelper(const QString& url, const QByteArray& content, http_callback const& receiver, QString &contenttype)
{
m_url = url;
m_content = content;
m_receiver = receiver;
m_contenttype = contenttype;
}
ServerHelper::~ServerHelper()
{
}
void ServerHelper::request(QString cmd, QString &content, http_callback const& receiver)
{
QString szUrl = s_serverUrl + "/" + cmd;
QString szContentType = "application/json";
ServerHelper* p = new ServerHelper(szUrl, content.toLatin1(), receiver, szContentType);
p->doRequest();
}
void ServerHelper::doRequest()
{
NetworkHelper::post( m_url, m_content, std::bind(&ServerHelper::OnNetworkReply, this, _1, _2), 5000, m_contenttype);
}
void ServerHelper::OnNetworkReply( int errCode, const QByteArray& bytes)
{
if (!m_receiver)
{
delete this;
return;
}
if (errCode==E_NetTimeOut)
{
m_receiver(E_ServerTimeOut, "Not received reply unitl timeout.", "");
}
else if (errCode==E_NetReplyError)
{
m_receiver(E_ServerNetReplyError, "Network reply error.", "");
}
else if (errCode==E_NetOK)
{
m_receiver(E_ServerOK, "", bytes);
}
delete this;
}
| true |
8d191b33cf164e5b829b0c1aa63813ef9bfed55c | C++ | TTLIUJJ/acker_redis | /sds.cpp | UTF-8 | 2,216 | 2.765625 | 3 | [] | no_license | #pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "sds.h"
#include "zmalloc.h"
sds sdsNewlen(const void *init, size_t len)
{
struct sdshdr *sh;
if (init) {
sh = (struct sdshdr *)zmalloc(sizeof(struct sdshdr) + len + 1);
}
else {
sh = (struct sdshdr *)zcalloc(sizeof(struct sdshdr) + len + 1);
}
if (sh == NULL)
return NULL;
sh->len = len;
sh->free = 0;
if (init && len)
memcpy(sh->buf, init, len);
sh->buf[len] = '\0';
return (char *)sh->buf;
}
sds sdsEmpty()
{
return sdsNewlen("", 0);
}
sds sdsNew(const char *init)
{
size_t len = (init == NULL) ? 0 : strlen(init);
return sdsNewlen(init, len);
}
sds sdsUp(const sds s)
{
return sdsNewlen(s, strlen(s));
}
void sdsFree(sds s)
{
if (s == NULL)
return;
char *p = s - sizeof(struct sdshdr);
zfree(p);
}
void sdsClear(sds s)
{
struct sdshdr *sh = (struct sdshdr *)(s - sizeof(struct sdshdr));
sh->free += sh->len;
sh->len = 0;
sh->buf[0] = '\0';
}
int sdsCmp(const sds s1, const sds s2)
{
size_t l1, l2, minlen;
l1 = strlen(s1);
l2 = strlen(s2);
minlen = l1 > l2 ? l2 : l1;
int cmp = memcmp(s1, s2, minlen);
if (cmp == 0)
return l1 - l2;
else
return cmp;
}
sds sdsMakeRoomFor(sds s, size_t addlen)
{
struct sdshdr *sh, *newsh;
size_t free = sdsavail(s);
size_t len, newlen;
if (free > addlen)
return s;
sh = (struct sdshdr *)(s - sizeof(struct sdshdr));
len = sdslen(s);
newlen = sh->len + addlen;
if (newlen < SDS_MAX_PERALLOC)
newlen *= 2;
else
newlen += SDS_MAX_PERALLOC;
newsh = (struct sdshdr *)zrealloc(sh, sizeof(struct sdshdr) + newlen + 1);
if (newsh == NULL)
return NULL;
newsh->len = newlen;
newsh->free = newlen - len;
return newsh->buf;
}
sds sdsCat(sds s, const char *p)
{
size_t curlen = sdslen(s);
size_t len = strlen(p);
s = sdsMakeRoomFor(s, len);
if (s == NULL)
return NULL;
struct sdshdr *sh = (struct sdshdr *)(s - (sizeof(struct sdshdr)));
memcpy(s + curlen, p, len);
sh->len = curlen + len;
sh->free = sh->free - len;
s[curlen + len] = '\0';
return s;
} | true |