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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f388271069851c63d1fa0175cde8f595cd94098b | C++ | msrishu65/codes | /codes/array n dp/minimumunsortedarray.cpp | UTF-8 | 504 | 2.578125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int c=0,start,end;
int m=0;
int a[]={10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60};
//int a[]={0, 1, 15, 25, 6, 7, 30, 40, 50};
for(int i=0;i<10;i++)
{
if(a[i]>m)
m=a[i];
if(a[i]<m)
end=i;
if(a[i]>a[i+1] && c==0)
{
c=a[i+1];
}
}
for(int i=0;i<10;i++)
{
if(a[i]>c)
{
start=i;
break;
}
}
cout<<start<<" "<<end;
return 0;
}
| true |
e6888d4a1c1d86dc1190fe83b72f2c64996e7d1d | C++ | duskmoon314/THU_homework | /C++ program design/cpp files/exp9-1-1.cpp | UTF-8 | 658 | 2.953125 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main() {
int iNumberOfSheep;
cout << "Please input the number of sheep: \n";
cin >> iNumberOfSheep;
int iWeightOfSheep[1024] = { 0 };
for (int i = 0; i < iNumberOfSheep; ++i) {
iWeightOfSheep[i] = rand();
}
for (int i = 0; i < 100; ++i) {
for (int j = iNumberOfSheep - 1; j > i; --j) {
if (iWeightOfSheep[j] > iWeightOfSheep[j - 1]) {
iWeightOfSheep[j - 1] += iWeightOfSheep[j];
iWeightOfSheep[j] = iWeightOfSheep[j - 1] - iWeightOfSheep[j];
iWeightOfSheep[j - 1] -= iWeightOfSheep[j];
}
}
}
for (int i = 0; i < 100; ++i) {
cout << iWeightOfSheep[i] << endl;
}
return 0;
} | true |
952b3c3a5037bf513910b698c52133941009ada1 | C++ | pjx3/DirectXTex | /DirectXTex/DirectXTexRAW.cpp | UTF-8 | 2,865 | 2.78125 | 3 | [
"MIT"
] | permissive | //-------------------------------------------------------------------------------------
// DirectXTexRAW.cpp
//
// DirectX Texture Library - RAW file format reader/writer
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
//-------------------------------------------------------------------------------------
#include "directxtexp.h"
// This implementation currently only supports headerless R32G32B32A32_Float format
// RAW files in a little endian order.
// It relies on metadata given via command line arguments to determine width & height
using namespace DirectX;
//=====================================================================================
// Private utility functions
//=====================================================================================
namespace
{
//-------------------------------------------------------------------------------------
// Copies pixel data from a RAW into the target image
//-------------------------------------------------------------------------------------
HRESULT CopyPixels(
_In_reads_bytes_(size) const void* pSource,
size_t size,
_In_ const Image* image)
{
if (!pSource ||
!size ||
!image ||
!image->pixels)
{
return E_POINTER;
}
auto src = reinterpret_cast<float const*>(pSource);
auto dst = reinterpret_cast<float*>(image->pixels);
for (size_t y = 0; y < image->height; y++)
{
for (size_t x = 0; x < image->width; x++)
{
float r = *src++;
float g = *src++;
float b = *src++;
float a = *src++;
(void)a; // unused
*dst++ = r;
*dst++ = g;
*dst++ = b;
*dst++ = 1.0f; // note: forcing alpha!
}
}
return S_OK;
}
} // namespace
//=====================================================================================
// Public entry-points
//=====================================================================================
//-------------------------------------------------------------------------------------
// Load a RAW file in memory
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT DirectX::LoadFromRAWMemory(
const void* pSource,
size_t size,
TexMetadata* metadata,
ScratchImage& image)
{
if (!pSource ||
size == 0 ||
!metadata ||
metadata->width == 0 ||
metadata->height == 0 ||
metadata->format != DXGI_FORMAT_R32G32B32A32_FLOAT)
{
return E_INVALIDARG;
}
image.Release();
const void* pPixels = static_cast<const uint8_t*>(pSource);
HRESULT hr = image.Initialize2D(metadata->format, metadata->width, metadata->height, 1, 1);
if (FAILED(hr)) {
return hr;
}
hr = CopyPixels(pPixels, size, image.GetImage(0, 0, 0));
if (FAILED(hr))
{
image.Release();
return hr;
}
return S_OK;
}
| true |
4236e7df39343d2b1d907742aaad8f29bef2d17d | C++ | maksymshvaiko/Circle_buffer | /tests/auto/ewq/tst_ewq.h | UTF-8 | 1,743 | 3.265625 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <gmock/gmock-matchers.h>
#include <iostream>
using namespace testing;
TEST(ewq, qwe)
{
EXPECT_EQ(1, 1);
ASSERT_THAT(0, Eq(0));
}
template<typename EL, int _size>
class ring_buff
{
private:
size_t m_size;
EL m_buf[_size];
size_t m_front;
size_t m_back;
void insert()
{
m_back = (m_back + 1) % _size;
if(_size == size())
m_front = (m_front + 1) % _size;
else
m_size++;
}
public:
ring_buff() { clear(); }
int size() { return m_size; }
int max_size() { return _size; }
bool empty() const { return m_size == 0;}
bool full() const { return m_size == _size;}
void clear()
{
m_size = 0;
m_front = 0;
m_back = _size - 1;
}
EL& front() { return m_buf[m_front]; }
EL& back() { return m_buf[m_back]; }
void push(const EL &elem)
{
insert();
back() = elem;
}
void pop()
{
if(m_size != 0)
{
m_size--;
m_front = (m_front + 1) % _size;
}
}
void erase_front(const size_t m)
{
if(m >= m_size)
clear();
else
{
m_size -= m;
m_front = (m_front + m) % _size;
}
}
void erase_back(const size_t m)
{
if(m >= m_size)
clear();
else
{
m_size -= m;
m_back = (m_front + m_size + 1) % _size;
}
}
void show_buffer()
{
if(!empty())
for(int i = 0; i < m_size; i++)
std::cout << m_buf[i] << std::endl;
else
std::cout << "Buffer is empty..." << std::endl;
}
};
| true |
4e8584365b46235833409b6fdc22753d4e06204e | C++ | sankarsh98/codeforces | /trainTickets.cpp | UTF-8 | 624 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
#include<set>
using namespace std;
#define loop(i,a,n) for(int i=a;i<=n;i++);
typedef unsigned long long ll;
int main(){
int n,m,a,b;
cin>>n>>m>>a>>b;
int p=min(b,a*m);
int c=n/m;
int res=c*p;
int d=n%m;
res+=min(d*a,b);
cout<<res;
}
// n=number of rides
// m=number of rides with b rupees
// a=amount for single ride
// 1.p=find max of b and a*m
// 2.find amount of m tickets needed to complete n rides c=n/m
// 3.calculate res=c*p
// 4.calculate d=n%m
// 5.find res+=min(d*a,b) | true |
17dd6cc65b5a7549a41f906d7573639704d3b838 | C++ | xiaoqixian/Wonderland | /leetcode/cloneGraph.cpp | UTF-8 | 1,241 | 3.0625 | 3 | [] | no_license | /**********************************************
> File Name : cloneGraph.cpp
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Sun Jul 3 17:37:25 2022
> Location : Shanghai
> Copyright@ https://github.com/xiaoqixian
**********************************************/
#include <vector>
#include <unordered_map>
using namespace std;
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
class Solution {
public:
Node* cloneGraph(Node* node) {
unordered_map<Node*, Node*> m;
return cloneNode(node, m);
}
Node* cloneNode(Node* node, unordered_map<Node*, Node*>& m) {
auto iter = m.find(node);
if (iter != m.end())
return iter->second;
Node* newNode = new Node(node->val);
m.insert({node, newNode});
for (auto neighborNode: node->neighbors) {
newNode->neighbors.push_back(cloneNode(neighborNode, m));
}
return newNode;
}
};
| true |
2ad77ab1e21a22b1ec4376abaf0a7da41739a136 | C++ | Yu-ChenChang/LeetCode | /src/39_combination_sum.cpp | UTF-8 | 1,097 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<algorithm>
using namespace::std;
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int> > res;
vector<int> combinations;
combinationSum(candidates,res,combinations,target,0);
return res;
}
private:
void combinationSum(vector<int> &candidates,vector<vector<int> >& res,vector<int>& combinations,int target,int begin){
if(!target)
{
res.push_back(combinations);
return;
}
for(int i=begin;i!=candidates.size() && target>=candidates[i];i++)
{
combinations.push_back(candidates[i]);
combinationSum(candidates,res,combinations,target-candidates[i],i);
combinations.pop_back();
}
}
};
int main(){
int array[4] = {2,3,6,7};
int target = 7;
vector<int> candidates(array,array+4);
vector<vector<int> >res;
Solution sol;
res = sol.combinationSum(candidates,target);
for(int i=0;i<res.size();i++)
{
for(int j=0;j<res[i].size();j++)
{
cout<<res[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| true |
048250e0eaeb2e12637a227216ee89cb6ec07c6c | C++ | li487941081/HDOJ | /1003Max Sum solution1.cpp | UTF-8 | 1,933 | 3.421875 | 3 | [] | no_license | /*
Problem Description
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
*/
#include<iostream>
#include<conio.h>
#include<algorithm>
using namespace std;
int main()
{
int num;//the number of test cases
int a[100011];//store the integer in the sequence
int b[100011];//max sum
int count=0;//what number of case
int sum = 0;
int max0 = -1001;//must less than all int
int n;//integer in the sequence
int begin;
int end;
cin >> num;
while (num--)
{
cin >> n;
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for (int i = 1; i <= n; i++)
{
cin >> a[i];
b[i] = max(b[i-1] + a[i], a[i]);
if (max0 < b[i])
{
max0 = b[i];//record the max
end = i;//record the last
}
}
for (int i = end; i >= 1; i--)
{
sum = sum + a[i];
if (sum == max0)
{
begin = i;
}
}
cout << "Case " << ++count <<":"<< endl;
cout << max0 <<" "<< begin << " " << end << endl;
if (num>0)
{
cout << endl;
}
max0 = -1001;
sum = 0;
}
_getch();
return 0;
} | true |
0a57354f28ad744c1ac32d817c5c9ef581cd978b | C++ | Raj6713/CodeChef | /chefsum.cpp | UTF-8 | 737 | 3.4375 | 3 | [] | no_license | //chef solves a new problem
#include<iostream>
using namespace std;
#include<climits>
inline long int summer(int *,int index,int size);
int main()
{
int testCases,size,index;
long int minimum;
cin>>testCases;
while(testCases--)
{
minimum=LONG_MAX;
cin>>size;
int *arr=new int[size];
for(int i=0;i<size;i++)
cin>>*(arr+i);
for(int i=size-1;i>=0;i--)
{
long int val=summer(arr,i,size);
if(val<=minimum)
{index=i;minimum=val;}
}
cout<<index+1<<endl;
}
return 0;
}
inline long int summer(int *arr, int index,int size)
{
long int prevSum,afterSum;
prevSum=afterSum=0;
for(int i=0;i<=index;i++)
prevSum+=*(arr+i);
for(int i=size-1;i>=index;i--)
afterSum+=*(arr+i);
return prevSum+afterSum;
} | true |
cfa42192cad13a26745c15302ccf638bd4e76994 | C++ | yuqi-lee/program-design | /homework/hw4/分解因数.cpp | UTF-8 | 1,175 | 3.515625 | 4 | [
"MIT"
] | permissive | /*
李昱祁 PB18071496 程序设计II第 4 次作业
题目 1:分解因数
2020.04.22
*/
#include <iostream>
using namespace std;
int _count = 0;
void my_func(int i, int a);
int main(void)
{
int a;
cout << "输入正整数a:";
cin >> a;
for (int i = 2; i <= a; i++)
{
if (a % i == 0)
{
if (a / i >= i) //后续的最大可能因子要大于i,才有效
{
_count++;
my_func(i, a / i); //计算 a/i 的分解种数
}
if (a == i) //此时没有后续因子,直接计数加1
_count++;
}
}
cout << endl
<< "分解的种数为:"
<< _count << " ";
return (0);
}
void my_func(int i, int a)
{
for (int j = i; j <= a; j++)
{
if (a % j == 0)
{
if (a / j >= j)
{
_count++;
my_func(j, a / j); //递归计算 a/i 的分解种数
}
}
// a == i 的情况在上层函数中已经记录
}
return;
} | true |
00eb5a65b935a1cb14acccdaac4160101ceb4b08 | C++ | rajarahul12/Programs | /LinkedList/palindrome_ll_effe.cpp | UTF-8 | 1,206 | 3.359375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
Node *head=NULL;
Node *last= NULL;
void node(int val){
Node *n = new Node;
n->data = val;
n->next = NULL;
if(head == NULL){
head = last = n;
}
else{
last->next = n;
last =n;
}
}
void reverseLinkedlist(int len,int mid){
Node *prev=head,*curr=head;
Node *temp;
int count=1;
while(true){
if(count<=mid){
prev=curr;
curr=curr->next;
count++;
}
else{
temp=curr;
curr=curr->next;
temp->next=prev;
prev=temp;
if(curr==NULL){
last=prev;
break;
}
}
}
}
bool checkPalindrome(int n){
int count=1,mid=ceil(n/2);
Node *p=head,*q=last;
while(count<=mid){
if(p->data==q->data){
// cout<<p->data<<"\t"<<q->data<<"\n";
count++;
p=p->next;
q=q->next;
}
else
return false;
}
return true;
}
int main(){
node(2);
node(3);
node(3);
node(2);
int len=0,mid;
Node *p=head;
while(p!=NULL){
p=p->next;
len++;
}
if(len%2 == 0)
mid=len/2;
else
mid=(len/2)+1;
// cout<<len<<"\t"<<mid<<"\n";
reverseLinkedlist(len,mid);
// cout<<head->data<<"\n"<<last->data;
if(checkPalindrome(len)){
cout<<"YES\n";
}
else
cout<<"NO\n";
return 0;
}
| true |
872e93797c4e43f30fa6b6d4f338d39b9c9b91f4 | C++ | alexandraback/datacollection | /solutions_5708921029263360_0/C++/cseteram/C.cpp | UTF-8 | 2,976 | 2.546875 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <utility>
#include <functional>
#include <algorithm>
using namespace std;
void make_all(int m, int k, int j, int p, int s, vector<int> &S) {
if (k >= 3) {
S.push_back(m);
return;
}
if (k == 0) {
for(int i=1 ; i<=j ; i++)
make_all(m + 100*i, k+1, j, p, s, S);
}
else if (k == 1) {
for(int i=1 ; i<=p ; i++)
make_all(m + 10*i, k+1, j, p, s, S);
}
else {
for(int i=1 ; i<=s ; i++)
make_all(m + i, k+1, j, p, s, S);
}
}
void back(int r, int n, int k, vector<int> &order, map<int,int> &cnt, vector<int> &ans_order, vector<int> &S, int st) {
if (r >= n) {
if (order.size() > ans_order.size()) {
ans_order = order;
}
return;
}
if (st == r) {
back(r+1, n, k, order, cnt, ans_order, S, st);
return;
}
// for(int i=r ; i<n ; i++) {
for(int i=r ; i<=r ; i++) {
int p1, p2, p3;
p1 = S[i] - S[i]%10;
p2 = (S[i]/100)*100 + S[i]%10;
p3 = S[i] - (S[i]/100)*100;
cnt[p1]++, cnt[p2]++, cnt[p3]++;
if (cnt[p1] <= k && cnt[p2] <= k && cnt[p3] <= k) {
order.push_back(S[i]);
back(r+1, n, k, order, cnt, ans_order, S, st);
order.pop_back();
}
cnt[p1]--, cnt[p2]--, cnt[p3]--;
}
/*
if (n - r - 1 + (int) order.size() > ans_order.size())
back(r + 1, n, k, order, cnt, ans_order, S);
*/
return;
}
void solve_small(int j, int p, int s, int k) {
vector<int> S;
make_all(0,0,j,p,s,S);
int n = (int) S.size();
vector<int> ans_order, order;
map<int,int> cnt;
for(int i=0 ; i<n ; i++) {
int p1, p2, p3;
p1 = S[i] - S[i] % 10;
p2 = (S[i] / 100) * 100 + S[i] % 10;
p3 = S[i] - (S[i] / 100) * 100;
if (cnt[p1] < k && cnt[p2] < k && cnt[p3] < k) {
cnt[p1]++, cnt[p2]++, cnt[p3]++;
order.push_back(S[i]);
}
}
ans_order = order;
order = vector<int>();
for(auto &iter : cnt) {
iter.second = 0;
}
// back(0, n, k, order, cnt, ans_order, S);
for(int i=0 ; i<n ; i++) {
int p1, p2, p3;
p1 = S[i] - S[i] % 10;
p2 = (S[i] / 100) * 100 + S[i] % 10;
p3 = S[i] - (S[i] / 100) * 100;
if (cnt[p1] < k && cnt[p2] < k && cnt[p3] < k) {
cnt[p1]++, cnt[p2]++, cnt[p3]++;
order.push_back(S[i]);
back(0, n, k, order, cnt, ans_order, S, i);
cnt[p1]--, cnt[p2]--, cnt[p3]--;
order.pop_back();
}
}
int ans = (int) ans_order.size();
printf("%d\n", ans);
for(int i=0 ; i<ans ; i++) {
int ord = ans_order[i];
printf("%d %d %d\n", ord/100, (ord%100)/10, ord%10);
}
return;
}
int main() {
freopen("C.in", "r", stdin);
freopen("C.out", "w", stdout);
int T;
scanf("%d", &T);
for (int tc = 1; tc <= T; tc++) {
int j, p, s, k;
scanf("%d%d%d%d", &j, &p, &s, &k);
printf("Case #%d: ", tc);
solve_small(j,p,s,k);
}
return 0;
} | true |
25fb6e47c93f611ecdc203c9089798ec255b296c | C++ | fenixGames/WvV | /src/nodes/board.cpp | UTF-8 | 356 | 2.984375 | 3 | [
"BSD-2-Clause"
] | permissive | #include <nodes/board.hpp>
std::list<Piece*> Board::create_row(int ncols)
{
std::list<Piece*> row;
for (int idx = 0; idx < ncols; idx++)
row.push_back();
}
Board::Board(int ncols, int nrows, const Point &position, const Size &size) :
Node(position, size){
for (int idx = 0; idx < nrows; idx++)
this->pieces.push_back(this->create_row(ncols));
}
| true |
71d22d6643a1f3dadb5b2a3c3d5bfbe4312da89f | C++ | xoyowade/solutions | /leetcode/66_plus_one.cpp | UTF-8 | 639 | 3.265625 | 3 | [] | no_license | class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int carry = 1;
vector<int> new_digits;
for (int i = digits.size()-1; i >= 0; i--) {
int sum = digits[i]+carry;
carry = sum/10;
new_digits.push_back(sum%10);
}
if (carry > 0) {
new_digits.push_back(carry);
}
for (int i = 0; i < new_digits.size()/2; i++) {
swap(new_digits[i], new_digits[new_digits.size()-i-1]);
}
return new_digits;
}
};
| true |
003fa7918c3f8d9eaab8132fd5d17b7237cdd16c | C++ | AmanAswal/cpp-competitve-coding | /Array/NxN_multiply_matrix.cpp | UTF-8 | 1,220 | 3.546875 | 4 | [] | no_license | // WAP to take and print Nxn matrix. ( same no. of rows and columns)
#include<iostream>
using namespace std;
int main()
{
int a[10][10], b[10][10],c[10][10], r, co;
cout<<"Enter the number of rows: ";
cin>> r;
cout<<"Enter the number of columns: ";
cin>> co;
cout<<"Enter elements of 1st matrix: "<<endl;
for(int i=0; i<r; i++)
{
for(int j=0; j<co; j++)
{
cin>>a[i][j];
}
}
cout<<endl;
cout<<"Enter elements of 2nd matrix: "<<endl;
for(int i=0; i<r; i++)
{
for(int j=0; j<co; j++)
{
cin>>b[i][j];
}
}
cout<<endl;
for( int i=0; i<r; i++)
{
for(int j=0; j<co; j++)
{
c[i][j] = 0;
for( int k=0; k<co; k++)
{
c[i][j] = c[i][j] + (a[i][k] * b[k][j]);
}
}
}
cout<<endl;
cout<<"Multiplication of the metrices: "<<endl;
for(int i=0; i<r; i++)
{
for( int j=0; j<co; j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| true |
9e73205ebbcecda2bb26859b22a6345c3675cd9c | C++ | jinhang87/qtutil | /app/MessageBox/messagebox.cpp | UTF-8 | 1,253 | 2.546875 | 3 | [] | no_license | #include "messagebox.h"
#include "ui_messagebox.h"
MessageBox::MessageBox(Icon icon, const QString &text, QMessageBox::StandardButtons buttons, QWidget *parent) :
QDialog(parent),
ui(new Ui::MessageBox)
{
ui->setupUi(this);
ui->buttonBox->setStyleSheet("QPushButton { min-width: 150px ; min-height: 60px}");
ui->buttonBox->setStandardButtons(QDialogButtonBox::StandardButtons(int(buttons)));
ui->label_2->setText(text);
}
MessageBox::~MessageBox()
{
delete ui;
}
int MessageBox::information(QWidget *parent, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton)
{
MessageBox messageBox(MessageBox::Information, text, buttons, parent);
return messageBox.exec();
}
int MessageBox::question(QWidget *parent, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton)
{
MessageBox messageBox(MessageBox::Question, text, buttons, parent);
return messageBox.exec();
}
int MessageBox::critical(QWidget *parent, const QString &text, QMessageBox::StandardButtons buttons, QMessageBox::StandardButton defaultButton)
{
MessageBox messageBox(MessageBox::Critical, text, buttons, parent);
return messageBox.exec();
}
| true |
3e02fc724d8bc8097e921cd98494835a93030ad2 | C++ | xalyes/adapter | /adapter/reciever.cpp | UTF-8 | 1,332 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "network_helpers.h"
#include "translator.h"
#include "reciever.h"
#include <sstream>
using namespace boost::asio;
void Reciever::Acceptor(int port, unsigned int module)
{
ip::tcp::endpoint ep(ip::tcp::v4(), port);
ip::tcp::acceptor acc(g_service, ep);
boost::thread_group threads;
while (m_exitStatus != true)
{
ip::tcp::socket sock(g_service);
std::cout << "socket is open: " << port << std::endl;
acc.accept(sock);
std::cout << "accept" << std::endl;
boost::asio::streambuf response;
size_t bytes = read_until(sock, response, '\0');
sock.close();
boost::asio::streambuf::const_buffers_type bufs = response.data();
std::string msg(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + bytes - 1);
std::cout << "get it: " << msg << std::endl;
//std::string msg(response_stream.str(), bytes - 1);
threads.create_thread(boost::bind(TranslateMessage, msg, module, m_settings.GetType(module)));
}
threads.join_all();
}
void Reciever::Start()
{
m_exitStatus = false;
for (unsigned int i = 0; i < m_settings.GetAmount(); ++i)
{
m_threads.create_thread(boost::bind(&Reciever::Acceptor, this, m_settings.GetInputPort(i), i));
}
std::cout << "reciever started" << std::endl;
}
void Reciever::Stop()
{
m_exitStatus = true;
m_threads.join_all();
}
| true |
dba45b61428121ed6bf12b797767760c101f7352 | C++ | dsmo7206/genesis | /shapes.cpp | UTF-8 | 620 | 3.046875 | 3 | [] | no_license | #include "shapes.h"
#include "planet.h"
#include "star.h"
Shape* Shape::buildFromXMLNode(XMLNode& node)
{
if (rapidxml::count_attributes(&node) != 1)
raiseXMLException(node, "Expected 1 attribute");
XMLAttribute* attr = node.first_attribute();
if (strcmp(attr->name(), "type"))
raiseXMLException(node, "Missing \"type\" attribute");
const std::string type(attr->value());
if (type == "Planet")
return Planet::buildFromXMLNode(node);
else if (type == "Star")
return Star::buildFromXMLNode(node);
raiseXMLException(node, std::string("Invalid type: ") + type);
return nullptr; // Keep compiler happy
}
| true |
0bcbda517d5d07805e727522abf03f624c875585 | C++ | acttell/practice | /dynamic/edit_distance.cpp | UTF-8 | 840 | 2.984375 | 3 | [] | no_license | //https://www.cnblogs.com/grandyang/p/4344107.html
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int edit_distance(string& s1,string& s2)
{
int m=s1.size();
int n=s2.size();
vector<vector<int>> dp(m+1,vector<int>(n+1));
for(int i=0;i<m+1;i++) dp[i][0]=i;
for(int i=0;i<n+1;i++) dp[0][i]=i;
for(int i=1;i<m+1;i++)
{
for(int j=1;j<n+1;j++)
{
if(s1[i-1]==s2[j-1])
{
dp[i][j]=dp[i-1][j-1];
} else
{
dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
}
}
}
return dp[m][n];
}
int main()
{
//string s1="intention";
//string s2="execution";
string s1="horse";
string s2="ros";
cout<<edit_distance(s1,s2)<<endl;
return 0;
}
| true |
ceda628136fdb3b7e9478a4686ab08b0a2282c82 | C++ | Thisnicknameisalreadytaken/kaoyan | /algorithm_note/cp10-graph/bfsForwardOfWeibo.cpp | UTF-8 | 2,000 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
/*
* P363 给出微博中的几个人,每个人关注的其他人,当一个人发布动态的时候可以被关注他的人转发,求经过 L 层转发后,总共最大被转发了几次
* 微博人的关注关系构成一张图,本题与层级有关,应选用 BFS 解决
*/
const int maxn = 1010;
typedef struct Node {
int no; // 节点编号
int level; // 节点所在层级
} node;
bool G[maxn][maxn] = {false}; // 图的邻接矩阵
bool hasInQueue[maxn] = {false};
/**
* 计算从 k 发送的动态,在层级 level 下最多能被基本转发
* @param k
* @param level
* @return
*/
int countForward(int k, int level) {
int count = 0;
queue<node> q;
hasInQueue[k] = true;
node kNode = {k, 0};
q.push(kNode);
while (!q.empty()) {
node topNode = q.front();
q.pop();
for (int i = 0; i < maxn; ++i) {
if (topNode.level < level && G[topNode.no][i] && !hasInQueue[i]) { // 父节点层级小于l,有关注关系,未入队过
hasInQueue[i] = true;
node iNode = {i, topNode.level + 1};
q.push(iNode);
count++;
}
}
}
return count;
}
/*
* input:
* 7 3
* 3 2 3 4
* 0
* 2 5 6
* 2 3 1
* 2 3 4
* 1 4
* 1 5
* 2 2 6
* output:
* 4
* 5
*/
int main() {
int n, l;
cin >> n >> l;
int followNum; // 关注的总数
int followIndex; // 被关注的人id
for (int i = 1; i <= n; ++i) { // input edge
cin >> followNum;
for (int j = 0; j < followNum; ++j) {
cin >> followIndex;
G[followIndex][i] = true; // i 关注了 followIndex,则 followIndex 发送的动态可以被 i 转发
}
}
int m, k;
cin >> m;
for (int i = 0; i < m; ++i) {
memset(hasInQueue, false, sizeof(hasInQueue));
cin >> k;
cout << countForward(k, l) << endl;
}
return 0;
}
| true |
bb242f9f5c36c817e6f281c3a33d613f314d83e5 | C++ | gonzhitova/laba5.1 | /55.cpp | UTF-8 | 367 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
class pr{
public:
int a,b,r;
int getS(){
return a*b;
}
int getP(){
return 2*(a+b);
}
int getSs(){
return 3.14*r*r;
}
int getPe(){
return 2*3.14*r;
}
};
void main()
{
pr p;
p.a=5;
p.b=8;
p.r=8;
cout<<p.getS();
cout<<" ";
cout<<p.getP();
cout<<"\n";
cout<<p.getSs();
cout<<" ";
cout<<p.getPe();
cout<<"\n";
system("pause");
} | true |
8668b73d839efeffd96be1339afc44c4e7deee29 | C++ | JokerIsol/GitLearn | /src/head_file/Axis.h | UTF-8 | 999 | 2.71875 | 3 | [] | no_license | #ifndef AXIS_H
#define AXIS_H
// "Axis_h"
struct Axis_state{ //状态
bool Request; //是否接受指指令
bool Done; //是否已完成运动指令
};
struct parameter{ //运动参数
double Position; //位置
double Velocity; //速度
double Acceleration; //加速度
double Deceleration; //减速度
};
struct new_cmd{ //接受命令
double Position;
double Velocity;
double Acceleration;
double Deceleration;
};
class Axis
{
public:
Axis_state State;
parameter Parameter;
new_cmd New_Cmd;
void init_Axis(Axis_state, parameter, new_cmd); //轴初始化函数
Axis_state Get_state(); //返回Axis对象的状态
parameter Get_parameter(); //返回Axis对象的参数
new_cmd Get_new_cmd(); //返回Axis对象的接受命令参数
void take_order(new_cmd init_new_cmd); //执行命令,并及时更新Axis对象
};
#endif
| true |
75d1f8315d27b21468b665edf0a834a2ee263cd0 | C++ | KristinaKulabuhova/Automate-for-regular-expressions | /automate.cpp | UTF-8 | 2,745 | 3.25 | 3 | [] | no_license | #include "automate.h"
const char *IncorrectRegularExpression::what() const noexcept
{
return "Incorrect regular expression";
}
bool IsCorrectRegularExpression(std::string regular)
{
int counter = 0;
for (int i = 0; i < regular.size(); ++i)
{
if (regular[i] == 'a' || regular[i] == 'b' || regular[i] == 'c' || regular[i] == '1')
{
++counter;
}
else if (regular[i] == '.' || regular[i] == '+')
{
--counter;
}
if (counter < 1)
{
return false;
}
}
return counter == 1;
}
Automate::Automate() = default;
Automate::Automate(const char symbol)
{
vertices = {
{{symbol, {1}}},
{{'e', {}}}};
n_vertices = 2;
term_idx = 1;
}
Automate::Automate(int n, int idx, Verts other)
{
auto other_it = other.begin();
for (; other_it != other.end(); ++other_it)
{
this->vertices.push_back(*other_it);
}
this->n_vertices = n;
this->term_idx = idx;
}
Automate::Automate(const Automate& other) : vertices(other.vertices), n_vertices(other.n_vertices), term_idx(other.term_idx){}
Automate::~Automate() = default;
Automate &Automate::operator+=(Automate &other)
{
*this += 1;
vertices.push_front({{'e', {1, n_vertices + 1}}});
vertices.back()['e'].push_back(n_vertices + other.n_vertices + 1);
other.vertices.back()['e'].push_back(other.n_vertices);
other += n_vertices + 1;
mergeVertices(vertices, other.vertices);
vertices.push_back({{'e', {}}});
n_vertices += other.n_vertices + 2;
term_idx = n_vertices - 1;
return *this;
}
void Automate::concatenation(Automate &other)
{
other += n_vertices;
mergeVertices(vertices, other.vertices);
auto it = vertices.begin();
std::advance(it, term_idx);
(*it)['e'].push_back(n_vertices);
n_vertices += other.n_vertices;
term_idx = n_vertices - 1;
}
void Automate::closure()
{
*this += 1;
vertices.push_front({{'e', {1, n_vertices + 1}}});
vertices.back()['e'].push_back(n_vertices + 1);
vertices.push_back({{'e', {0}}});
n_vertices += 2;
term_idx = n_vertices - 1;
}
void Automate::mergeVertices(Verts &first, Verts &second)
{
for (auto &elem : second)
{
first.push_back(elem);
}
}
Automate &Automate::operator+=(int n)
{
for (auto &el : vertices)
{
for (auto &letter : el)
{
for (auto &transition : letter.second)
{
transition += n;
}
}
}
term_idx += n;
return *this;
}
int Automate::get_terminal() const
{
return term_idx;
}
int Automate::get_number_of_vertices() const
{
return this->get_terminal() + 1;
} | true |
af042cef6c24e52da50a5489c0ab73d896e5e67c | C++ | yusuke-matsunaga/ymtools | /libym_logic/src/sat/ymsat/VarHeap.h | UTF-8 | 6,756 | 2.640625 | 3 | [] | no_license | #ifndef VARHEAP_H
#define VARHEAP_H
/// @file VarHeap.h
/// @brief VarHeap のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2011, 2014 Yusuke Matsunaga
/// All rights reserved.
#include "YmLogic/sat_nsdef.h"
#include "YmLogic/VarId.h"
BEGIN_NAMESPACE_YM_SAT
//////////////////////////////////////////////////////////////////////
/// @class VarHeap VarHeap.h "VarHeap.h"
/// @brief 変数のヒープ木
///
/// mActivity[] の値に基づいて整列させる.
//////////////////////////////////////////////////////////////////////
class VarHeap
{
public:
/// @brief コンストラクタ
VarHeap();
/// @brief デストラクタ
~VarHeap();
public:
//////////////////////////////////////////////////////////////////////
// 外部インターフェイス
//////////////////////////////////////////////////////////////////////
/// @brief アクティビティの低減率を設定する.
/// @param[in] decay 低減率
void
set_decay(double decay);
/// @brief 変数のアクティビティを増加させる.
/// @param[in] var 変数番号
void
bump_var_activity(VarId var);
/// @brief 変数のアクティビティを定率で減少させる.
void
decay_var_activity();
/// @brief 空にする.
void
clear();
/// @brief size 個の要素を格納出来るだけの領域を確保する.
/// @param[in] size 必要なサイズ
void
alloc_var(ymuint size);
/// @brief 要素が空の時 true を返す.
bool
empty() const;
/// @brief 変数を始めてヒープに追加する.
/// @param[in] var 追加する変数
void
add_var(VarId var);
/// @brief 変数を再びヒープに追加する.
/// @param[in] var 追加する変数
void
push(VarId var);
/// @brief アクティビティ最大の変数番号を取り出す.
/// @note 該当の変数はヒープから取り除かれる.
ymuint
pop_top();
/// @brief 変数のアクティビティを返す.
/// @param[in] var 対象の変数
double
activity(VarId var) const;
/// @brief 変数のアクティビティを初期化する.
void
reset_activity();
/// @brief 与えられた変数のリストからヒープ木を構成する.
void
build(const vector<VarId>& var_list);
/// @brief 内容を出力する
/// @param[in] s 出力先のストリーム
void
dump(ostream& s) const;
private:
//////////////////////////////////////////////////////////////////////
// 内部で用いられる関数
//////////////////////////////////////////////////////////////////////
/// @brief 引数の位置にある要素を適当な位置まで沈めてゆく
/// @param[in] pos 対象の要素の位置
void
move_down(ymuint pos);
/// @brief 引数の位置にある要素を適当な位置まで上げてゆく
/// @param[in] vindex 対象の変数番号
void
move_up(ymuint vindex);
/// @brief 変数を配列にセットする.
/// @param[in] vindex 対象の変数番号
/// @param[in] pos 位置
/// @note mHeap と mHeapPos の一貫性を保つためにはこの関数を使うこと.
void
set(ymuint vindex,
ymuint pos);
/// @brief 左の子供の位置を計算する
/// @param[in] pos 親の位置
static
ymuint
left(ymuint pos);
/// @brief 右の子供の位置を計算する.
/// @param[in] pos 親の位置
static
ymuint
right(ymuint pos);
/// @brief 親の位置を計算する.
/// @param[in] pos 子供の位置
/// @note 左の子供でも右の子供でも同じ
static
ymuint
parent(ymuint pos);
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// 変数のアクティビティの増加量
double mVarBump;
// 変数のアクティビティの減衰量
double mVarDecay;
// 変数の数
ymuint32 mVarNum;
// 変数関係の配列のサイズ
ymuint32 mVarSize;
// ヒープ上の位置の配列
// サイズは mVarSize
ymint32* mHeapPos;
// アクティビティ
// サイズは mVarSize
double* mActivity;
// ヒープ用の配列
// サイズは mVarSize
ymuint32* mHeap;
// ヒープの要素数
ymuint32 mHeapNum;
};
//////////////////////////////////////////////////////////////////////
// インライン関数の定義
//////////////////////////////////////////////////////////////////////
// @brief アクティビティの低減率を設定する.
inline
void
VarHeap::set_decay(double decay)
{
mVarDecay = decay;
}
// @brief 空にする.
inline
void
VarHeap::clear()
{
mHeapNum = 0;
}
// @brief 要素が空の時 true を返す.
inline
bool
VarHeap::empty() const
{
return mHeapNum == 0;
}
// @brief 変数を始めてヒープに追加する.
// @param[in] var 変数番号
inline
void
VarHeap::add_var(VarId var)
{
ymuint vindex = var.val();
set(vindex, mHeapNum);
mActivity[vindex] = 0.0;
++ mHeapNum;
}
// @brief 変数のアクティビティを返す.
// @param[in] var 変数番号
inline
double
VarHeap::activity(VarId var) const
{
return mActivity[var.val()];
}
// @brief 要素を追加する.
inline
void
VarHeap::push(VarId var)
{
ymuint vindex = var.val();
if ( mHeapPos[vindex] == -1 ) {
ymuint pos = mHeapNum;
++ mHeapNum;
set(vindex, pos);
move_up(pos);
}
}
// @brief もっともアクティビティの高い変数を返す.
inline
ymuint
VarHeap::pop_top()
{
ASSERT_COND(mHeapNum > 0 );
ymuint ans = mHeap[0];
mHeapPos[ans] = -1;
-- mHeapNum;
if ( mHeapNum > 0 ) {
ymuint vindex = mHeap[mHeapNum];
set(vindex, 0);
move_down(0);
}
return ans;
}
// 引数の位置にある要素を適当な位置まで上げてゆく
inline
void
VarHeap::move_up(ymuint pos)
{
ymuint vindex = mHeap[pos];
double val = mActivity[vindex];
while ( pos > 0 ) {
ymuint pos_p = parent(pos);
ymuint vindex_p = mHeap[pos_p];
double val_p = mActivity[vindex_p];
if ( val_p >= val ) {
break;
}
set(vindex, pos_p);
set(vindex_p, pos);
pos = pos_p;
}
}
// 変数を配列にセットする.
inline
void
VarHeap::set(ymuint vindex,
ymuint pos)
{
mHeap[pos] = vindex;
mHeapPos[vindex] = pos;
}
// @brief 左の子供の位置を計算する
inline
ymuint
VarHeap::left(ymuint pos)
{
return pos + pos + 1;
}
// @brief 右の子供の位置を計算する.
inline
ymuint
VarHeap::right(ymuint pos)
{
return pos + pos + 2;
}
// @brief 親の位置を計算する.
inline
ymuint
VarHeap::parent(ymuint pos)
{
return (pos - 1) >> 1;
}
END_NAMESPACE_YM_SAT
#endif // VARHEAP_H
| true |
881865a26e8afb5634dac81f39300e9059db3818 | C++ | deepakshisud/Competitive-Coding | /Cpp implementations/Multiplication_Recursion.cpp | UTF-8 | 226 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int multiplication(int m, int n) {
if(n==0)
return 0;
int smallAns = multiplication(m, n-1);
return m+smallAns;
}
int main() {
cout<<multiplication(2,3);
return 0;
}
| true |
a264ac842ca872a8626cdcf7c47c7a0eeb737970 | C++ | ydk1104/PS | /6321.cpp | UTF-8 | 266 | 2.84375 | 3 | [] | no_license | #include<stdio.h>
int main(void){
int N;
scanf("%d", &N);
char s[51];
for(int i=1; i<=N; i++){
scanf("%s", &s);
for(int j=0; s[j]!='\0'; j++){
if(s[j] == 'Z'){
s[j] = 'A';
}
else{
s[j]++;
}
}
printf("String #%d\n%s\n\n", i, s);
}
}
| true |
b05909e75056cb795ee768ec960fc1ed089b5db3 | C++ | zenanswer/lintcode-practice | /src/cpp/test612.cpp | UTF-8 | 1,967 | 3.421875 | 3 | [] | no_license | #include "lintcode_comm.h"
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class PointW {
public:
PointW(int x, int y, Point& origin) {
this->x = x;
this->y = y;
this->count = 1;
this->dis = sqrt(pow(origin.x-x, 2) + pow(origin.y-y, 2));
};
int x;
int y;
float dis;
mutable int count;
bool operator<(const PointW & right) const{
if(dis<right.dis) {
return true;
} else if (dis==right.dis) {
if(x<right.x) {
return true;
} else if (x==right.x) {
if(y<right.y) {
return true;
} else if (y==right.y) {
count ++;
return false;
}
}
}
return false;
};
};
class Solution {
public:
/*
* @param points: a list of points
* @param origin: a point
* @param k: An integer
* @return: the k closest points
*/
vector<Point> kClosest(vector<Point> points, Point origin, int k) {
set<PointW> cache;
for(int i=0; i<points.size(); i++) {
PointW temp(points[i].x, points[i].y, origin);
cache.insert(temp);
}
vector<Point> result;
std::set<PointW>::iterator it = cache.begin();
for (; it != cache.end(); ++it) {
for (int i=0; i<(*it).count; i++) {
result.push_back(Point((*it).x, (*it).y));
k--;
if(k==0) return result;
}
}
return result;
}
};
int main(void) {
vector<Point> points = \
{Point(4,6), Point(4,7),Point(4,4),Point(2,5),Point(1,1)};
Point origin(0, 0);
int k=3;
Solution s;
vector<Point> result = s.kClosest(points, origin, k);
showVector(result);
return 0;
}
| true |
eb645c009b278d2eaaa7bb9f9b63af15b7453403 | C++ | RuslanLytvynov/University_WIT | /Programowanie Obiektowe/Lesson_7/C07/03_ID03P06/C07_Proj_ID03P06_0001/Application.cpp | UTF-8 | 1,320 | 2.671875 | 3 | [] | no_license | ///*****************************************
void Application::Run(){
Main07();
}
///*****************************************
void Application::Main01(){
cout<<"\n\n\t\tApplication::Main01\n\n";
}
///*****************************************
void Application::Main02(){
MyClass m0;
m0.Ini(1,2,3);
m0.Print("\n");
cout<<"m0: ";
m0.Adr();
cout<<"&m0: "<<&m0<<endl;
}
///*****************************************
void Application::Main03(){
MyClass m0;
}
///*****************************************
void Application::Main04(){
MyClass m0(1, 2, 3), m1, m2(4,2,7), m3;
m0.Print("\n");
m1.Print("\n");
m2.Print("\n");
m3.Print("\n");
}
///*****************************************
void Application::Main05(){
MyClass m0(1, 2, 3);
m0.Print("\n");
///m0.x2 =9999;
m0.Ini(9999,2,3);
m0.Print("\n");
}
///*****************************************
void Application::Main06(){
MyClass m0(1111, 2222, 3333);
m0.Print("\n");
m0.Ini(9999,m0.GetX1(),m0.GetX0());
m0.Print("\n");
}
///*****************************************
void Application::Main07(){
MyClass m0(1, 2, 3);
m0.Print();
//m0.x1 = 9;
*(((int*)&m0)+1) = 9;
m0.Print();
}
///*****************************************
| true |
970a6a8ee3b42e71c1d573610730519165a57c1f | C++ | RotoscopMe/RotoscopMe-Desktop | /gui/createprojectdialog.cpp | UTF-8 | 3,021 | 2.609375 | 3 | [
"MIT"
] | permissive | #include "createprojectdialog.h"
CreateProjectDialog::CreateProjectDialog(QWidget *parent) :
QDialog(parent)
{
setWindowTitle(tr("Rotoscop'Me - Nouveau Projet "));
QLabel *nomLabel = new QLabel("Nom : ");
_nomEdit = new QLineEdit();
QLabel *workspaceLabel = new QLabel("Workspace : ");
_workspaceEdit = new QLineEdit();
QPushButton *workspaceParcourirButton = new QPushButton("...");
connect(workspaceParcourirButton, SIGNAL(clicked()), this, SLOT(workspaceParcourir()));
QLabel *videoLabel = new QLabel("Vidéo : ");
_videoEdit = new QLineEdit();
QPushButton *videoParcourirButton = new QPushButton("...");
connect(videoParcourirButton, SIGNAL(clicked()), this, SLOT(videoParcourir()));
QLabel *freqImageLabel = new QLabel("Fréquence d'images : ");
_freqImgComboBox = new QComboBox();
_freqImgComboBox->addItem("6");
_freqImgComboBox->addItem("8");
_freqImgComboBox->addItem("12");
_freqImgComboBox->addItem("24");
QPushButton *createButton = new QPushButton("Créer");
createButton->setGeometry(QRect(800, 450, 100, 50));
connect(createButton, SIGNAL(clicked()), this, SLOT(close()));
QHBoxLayout* nomLayout = new QHBoxLayout();
nomLayout->addWidget(nomLabel);
nomLayout->addWidget(_nomEdit);
QHBoxLayout* workspaceLayout = new QHBoxLayout();
workspaceLayout->addWidget(workspaceLabel);
workspaceLayout->addWidget(_workspaceEdit);
workspaceLayout->addWidget(workspaceParcourirButton);
QHBoxLayout* videoLayout = new QHBoxLayout();
videoLayout->addWidget(videoLabel);
videoLayout->addWidget(_videoEdit);
videoLayout->addWidget(videoParcourirButton);
QHBoxLayout* freqImLayout = new QHBoxLayout();
freqImLayout->addWidget(freqImageLabel);
freqImLayout->addWidget(_freqImgComboBox);
QHBoxLayout* buttonLayout = new QHBoxLayout();
buttonLayout->addWidget(createButton);
buttonLayout->setAlignment(createButton, Qt::AlignRight);
QVBoxLayout* homeLayout = new QVBoxLayout();
homeLayout->addStretch(1);
homeLayout->addLayout(nomLayout);
homeLayout->addLayout(workspaceLayout);
homeLayout->addLayout(videoLayout);
homeLayout->addLayout(freqImLayout);
homeLayout->addStretch(1);
homeLayout->addLayout(buttonLayout);
setLayout(homeLayout);
}
QString CreateProjectDialog::getNom()
{
return _nomEdit->text();
}
QString CreateProjectDialog::getWorkspace()
{
return _workspaceEdit->text();
}
QString CreateProjectDialog::getVideo()
{
return _videoEdit->text();
}
int CreateProjectDialog::getFrequence()
{
return _freqImgComboBox->currentText().toInt();
}
void CreateProjectDialog::workspaceParcourir()
{
QString path = QFileDialog::getExistingDirectory();
if(!path.isEmpty())
{
_workspaceEdit->setText(path);
}
}
void CreateProjectDialog::videoParcourir()
{
QString path = QFileDialog::getOpenFileName();
if(!path.isEmpty())
{
_videoEdit->setText(path);
}
}
| true |
e2b40a9955c82a77182424744ea0be2667624b30 | C++ | willyii/CS230-Project3-RigidBodySimulation | /CS230-RigidBodySimulation/CS230-RigidBodySimulation/init.cpp | UTF-8 | 1,501 | 2.6875 | 3 | [] | no_license | //
// init.cpp
// CS230-RigidBodySimulation
//
// Created by 易昕龙 on 2/29/20.
// Copyright © 2020 易昕龙. All rights reserved.
//
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);// call back function of size
GLFWwindow* init(){
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);// Mac use
//initialize the window
GLFWwindow* window = glfwCreateWindow(800, 600, "RigidBodySimulation", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return NULL;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
//Glad stuff
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return NULL;
}
return window;
}
// call back function of size
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
//Check if there are some keys was pushed
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
| true |
d2f3208af461b9b2c714434d72fa79d0645aee3d | C++ | Bridge12Technologies/Gyrotron-Control-System---OLD | /device.cpp | UTF-8 | 3,322 | 2.53125 | 3 | [] | no_license | // the commented-out lines are for a later implimentation of pre-programmed command lists
#include "device.h"
ethdevice :: ethdevice()
{
name = "";
hostname = "";
portno = 0;
preread = false;
socket = 0;
pause = false;
recon_count = -1;
}
//ethdevice :: ethdevice(std::string n, std::string h, int p, bool ir, bool pr) : name(n), hostname(h), portno(p), preread(pr) {}
ethdevice :: ethdevice(std::string n, std::string h, int p, bool pr, bool pa)
{
name = n;
hostname = h;
portno = p;
preread = pr;
socket = 0;
pause = pa;
recon_count = -1;
}
ethdevice :: ~ethdevice() {}
bool ethdevice :: getpreread() { return preread; }
int ethdevice :: getportno() { return portno; }
std::string ethdevice :: gethostname() { return hostname; }
std::string ethdevice :: getname() { return name; }
int ethdevice :: getsock() { return socket; }
void ethdevice :: setsock(int s) { socket = s; }
bool ethdevice :: get_pause() { return pause; }
int ethdevice :: get_recon_count() { return recon_count; }
void ethdevice :: recon_tick() { recon_count++; }
void ethdevice :: reset_recon_count() { recon_count = -1; }
serdevice :: serdevice()
{
name = "";
port = "";
baud = B9600;
sCR = true;
sLF = false;
pread = false;
fd = 0;
sRead = false;
recon_count = -1;
}
//serdevice :: serdevice(std::string n, std::string po, speed_t b, bool cr, bool lf) : name(n), port(po), baud(b), sCR(cr), sLF(lf) {}
serdevice :: serdevice(std::string n, std::string po, speed_t b, bool cr, bool lf, bool prd, bool sr)
{
name = n;
port = po;
baud = b;
sCR = cr;
sLF = lf;
pread = prd;
fd = 0;
sRead = sr; // stream read instead of recv
recon_count = -1;
}
serdevice :: ~serdevice() {}
std::string serdevice :: getport() { return port; }
speed_t serdevice :: getbaud() { return baud; }
bool serdevice :: sendCR() { return sCR; }
bool serdevice :: sendLF() { return sLF; }
std::string serdevice :: getname() { return name; }
bool serdevice :: getpreread() { return pread; }
int serdevice :: get_fd() { return fd; }
void serdevice :: set_fd(int f) { fd = f; }
int serdevice :: open_stream() { in_stream.open(port); if(in_stream.is_open()) return 0; else return -1; }
int serdevice :: close_stream() { in_stream.close(); if(in_stream.is_open()) return -1; else return 0; }
bool serdevice :: using_str() { return sRead; }
std::string serdevice :: read_stream()
{
std::string result;
in_stream >> result;
return result;
}
int serdevice :: get_recon_count() { return recon_count; }
void serdevice :: recon_tick() { recon_count++; }
void serdevice :: reset_recon_count() { recon_count = -1; }
serdevice SD_XGS600("XGS-600", "/dev/ttyUSB0", B9600, true, false, false, false);
serdevice SD_SCITECH("Scientech Power Meter", "/dev/ttyUSB0", B19200, true, true, false, true);
ethdevice ED_SPCE("Gamma Vac SPCe", (char *)"192.168.1.10", 23, true, false);
ethdevice ED_SG385("SRS SG385", (char *)"10.12.70.165", 5024, true, false);
ethdevice ED_DXM("Spellman DXM", (char *)"192.168.1.4", 50001, false, true);
ethdevice ED_SLM("Spellman SLM", (char *)"192.168.1.5", 50001, false, true);
ethdevice ED_RIGOL("Rigol DP821A", (char *)"192.168.1.3", 5555, false, false);
ethdevice ED_FMS("FMS", (char *)"10.12.70.121", 51717, false, true);
| true |
8ec62518e67eda82d2976b29d2365cc87481dd56 | C++ | dxhans5/bull_cow | /BullCowGame/main.cpp | UTF-8 | 2,741 | 3.546875 | 4 | [] | no_license | /*
This is the console executable, that makes use of the BullCow class
This acts as the view in a MVC pattern, and is responsible for all
user interaction. For game logic, see the FBullCow class.
*/
#include <iostream>
#include <string>
#include "FBullCow.h"
using FText = FString;
using int32 = int;
void PrintIntro();
void PlayGame();
bool AskToPlayAgain();
FText GetValidGuess();
FBullCow BCGame; // Instantiate a new game
// Entry point for application
int main()
{
bool bPlayAgain = false;
do
{
PrintIntro();
PlayGame();
bPlayAgain = AskToPlayAgain();
}
while (bPlayAgain);
return 0; // Exit the application
}
void PlayGame()
{
BCGame.Reset();
int32 MaxTries = BCGame.GetMaxTries();
while (!BCGame.IsGameWon() && BCGame.GetCurrentTry() <= MaxTries)
{
FText Guess = GetValidGuess();
FBullCowCount FBullCowCount = BCGame.SubmitValidGuess(Guess);
std::cout << "Bulls = " << FBullCowCount.Bulls;
std::cout << " Cows = " << FBullCowCount.Cows << std::endl << std::endl;
}
return;
}
void PrintIntro()
{
std::cout << std::endl;
std::cout << "Welcome to Bulls and Cows, a fun word game.\n";
std::cout << std::endl;
std::cout << " } { ___ " << std::endl;
std::cout << " (o o) (o o)" << std::endl;
std::cout << " /-------\\ / \\ /------\\" << std::endl;
std::cout << " / | BULL |0 0| COW |\\" << std::endl;
std::cout << "* |-,--- | |------| *"<< std::endl;
std::cout << " ^ ^ ^ ^" << std::endl;
std::cout << std::endl;
std::cout << "Can you guess the " << BCGame.GetHiddenWordLength() << " letter isogram I'm thinking of?\n";
std::cout << std::endl;
return;
}
bool AskToPlayAgain()
{
std::cout << "Do you want to play again? (y/n) ";
FText Response = "";
std::getline(std::cin, Response);
return Response[0] == 'y' || Response[0] == 'Y';
}
FText GetValidGuess()
{
FText Guess = "";
EWordStatus GuessStatus = EWordStatus::Invalid_Status;
do
{
std::cout << "Try " << BCGame.GetCurrentTry() << " of " << BCGame.GetMaxTries() << ". Enter your guess: ";
std::getline(std::cin, Guess);
EWordStatus Status = BCGame.CheckGuessValidity(Guess);
switch (Status)
{
case EWordStatus::Wrong_Length:
std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word.\n";
break;
case EWordStatus::Not_Isogram:
std::cout << "Please enter an isogram (no letters repeat).\n";
break;
case EWordStatus::Not_Lowercase:
std::cout << "Please enter only lower case letters.\n";
break;
default:
return Guess;
}
std::cout << std::endl;
} while (GuessStatus != EWordStatus::OK);
return Guess;
} | true |
1e0789dc3d13cb14de1ba9342e29549839ad73d8 | C++ | TanDung2512/tandung251298 | /execises theory class BK/lab_danhsachke/lab_danhsachke/main.cpp | UTF-8 | 2,671 | 3.125 | 3 | [] | no_license | //
// main.cpp
// lab_danhsachke
//
// Created by nguyen tan dung on 11/4/17.
// Copyright © 2017 nguyen tan dung. All rights reserved.
//
#include <iostream>
using namespace std;
class point{
public:
int data;
point*link;
bool check;
point(){
this->data=0;
this->link=NULL;
this->check=false;
}
point(int point){
this->data=point;
this->link=NULL;
this->check=false;
}
};
class list{
public:
point*pointhead;
point *pointnext;
int count;
list(){
this->pointnext=NULL;
this->pointhead=NULL;
this->count=0;
}
void insert(int data){
if(this->pointhead==NULL){
this->pointhead=new point(data);
}
else{
point*temp=this->pointhead;
while(temp->link!=NULL){
temp=temp->link;
}
temp->link=new point(data);
}
this->pointnext=this->pointhead->link;
this->count++;
}
int nodenotcheck(){
point*temp=this->pointnext;
while(temp!=NULL){
if(temp->check==false){
temp->check=true;
return temp->data;
}
temp=temp->link;
}
return -1;
}
void settrue(int i ){
point*temp=this->pointnext;
while(temp->data!=i){
temp=temp->link;
}
temp->check=true;
}
void print(){
if(this->pointnext!=NULL){
point*temp=this->pointnext;
while(temp!=NULL){
cout<<this->pointhead->data<<" "<<temp->data<<endl;
temp=temp->link;
}
}
}
};
bool euler(list *listpoint,int i,int head){
int a;
bool check;
a= listpoint[i].nodenotcheck();
if(a==-1){
if(i==head){
return true;
}
else return false;
}
else{
listpoint[a].settrue(i);
check=euler(listpoint, a, head);
if (check==true){
return true;
}
else return false;
}
}
int main(int argc, const char * argv[]) {
int n;
int point;
cin>>n;
list *listpoint=new list[n];
for(int i=0;i<n;i++){
listpoint[i].insert(i);
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>point;
if(point==1){
listpoint[i].insert(j);
}
}
}
for(int i=0;i<n;i++){
listpoint[i].print();
}
bool check=euler(listpoint,0,0);
if(check==true){
cout<<"co duong di euler" <<endl;
}
return 0;
}
| true |
6c9f959ccc00cb47e2e065153be736e4b1e0900b | C++ | zaimoni/Iskandria | /z_n.hpp | UTF-8 | 682 | 2.53125 | 3 | [
"BSL-1.0"
] | permissive | // z_n.hpp
#ifndef Z_N_HPP
#define Z_N_HPP 1
#include "Zaimoni.STL/Logging.h"
#include "Zaimoni.STL/augment.STL/type_traits"
namespace zaimoni {
namespace math {
// modulo arithmetic classes
template<uintmax_t n>
class Z_
{
static_assert(0<n);
private:
typename min_unsigned<n>::type _x;
public:
Z_() = default;
Z_(uintmax_t src) : _x(src%n) {}
explicit Z_(intmax_t src) : _x(0<=src ? src%n : (n-1)-norm(src)%n) {};
ZAIMONI_DEFAULT_COPY_DESTROY_ASSIGN(Z_);
operator uintmax_t() const {return _x;};
explicit operator intmax_t() const {return n/2>=_x ? _x : -(intmax_t)((n-1)-_x);}
};
} // namespace math
} // namespace zaimoni
#endif
| true |
c985fa7b8b777afc6bb1c5f924576432df4b1ff0 | C++ | wh2per/Programmers-Algorithm | /Programmers/Lv2/Lv2_교점에별만들기.cpp | UTF-8 | 1,921 | 3 | 3 | [] | no_license | #include <string>
#include <vector>
#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
vector<string> solution(vector<vector<int>> line) {
vector<string> answer;
vector<pair<long long, long long>> cross;
long long minX = LLONG_MAX, minY = LLONG_MAX;
long long maxX = LLONG_MIN, maxY = LLONG_MIN;
for (int i = 0; i < line.size() - 1; ++i) {
long long a = line[i][0];
long long b = line[i][1];
long long e = line[i][2];
for (int j = i + 1; j < line.size(); ++j) {
long long c = line[j][0];
long long d = line[j][1];
long long f = line[j][2];
long long x1 = b * f - e * d;
long long y1 = e * c - a * f;
long long common = a * d - b * c;
if (common == 0)
continue;
if (x1 % common == 0 && y1 % common==0) {
long long ix = x1 / common;
long long iy = y1 / common;
if (maxX < ix)
maxX = ix;
if (minX > ix)
minX = ix;
if (maxY < iy)
maxY = iy;
if (minY > iy)
minY = iy;
cross.push_back({ ix, iy });
}
}
}
string s = "";
for (long long j = 0; j <= maxX - minX; ++j)
s += ".";
for (long long i = 0; i <= maxY - minY; ++i)
answer.push_back(s);
for (auto a : cross)
answer[a.second - minY][a.first - minX] = '*';
reverse(answer.begin(), answer.end());
return answer;
}
int main() {
vector<vector<int>> line = {{2, -1, 4}, {-2, -1, 4}, {0, -1, 1}, {5, -8, -12}, {5, 8, 12}};
vector<vector<int>> line1 = { {0, 1, -1},{1, 0, -1},{1, 0, 1 }};
vector<string> answer = solution(line);
for (auto a : answer)
cout << a << endl;
return 0;
} | true |
7c165ea5de6be320d79690f5d53d1065511fbfcf | C++ | roycefanproxy/CPP_Primer_5th | /Chapter 10/10.29.cpp | UTF-8 | 388 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <vector>
#include <fstream>
using namespace std;
int main()
{
ifstream fs("Sales_Item.h");
istream_iterator<string> ifsi(fs), eof;
vector<string> vs;
//string s;
while(ifsi != eof)
//while(getline(fs, s))
vs.push_back(*ifsi++);
//vs.push_back(s);
for(auto& x : vs)
cout << x << ends;
}
| true |
eb6862eda05218963c3ea4e7f9ad5f0f91f59526 | C++ | igankevich/subordination | /src/bscheduler/kernel/foreign_kernel.hh | UTF-8 | 957 | 2.640625 | 3 | [] | no_license | #ifndef BSCHEDULER_KERNEL_FOREIGN_KERNEL_HH
#define BSCHEDULER_KERNEL_FOREIGN_KERNEL_HH
#include <bscheduler/kernel/kernel.hh>
#include <bscheduler/kernel/kernel_type.hh>
namespace bsc {
class foreign_kernel: public kernel {
private:
typedef char char_type;
typedef size_t size_type;
typedef ::bsc::kernel_type::id_type id_type;
private:
size_type _size = 0;
char_type* _payload = nullptr;
id_type _type = 0;
public:
foreign_kernel() = default;
foreign_kernel(const foreign_kernel&) = delete;
foreign_kernel&
operator=(const foreign_kernel&) = delete;
inline
~foreign_kernel() {
this->free();
}
inline id_type
type() const noexcept {
return this->_type;
}
void
write(sys::pstream& out) const override;
void
read(sys::pstream& in) override;
private:
inline void
free() {
delete[] this->_payload;
this->_payload = nullptr;
this->_size = 0;
}
};
}
#endif // vim:filetype=cpp
| true |
5c8cccbcebe3fdf6895852c3a3829da946869efd | C++ | minlexx/l2-unlegits | /l2ooghelper/UserBuffs.h | UTF-8 | 1,496 | 2.75 | 3 | [] | no_license | #ifndef H_USER_BUFFS
#define H_USER_BUFFS
class UserBuff
{
public:
UserBuff() { clear(); }
UserBuff( const UserBuff& other ) { this->operator=( other ); }
UserBuff& operator=( const UserBuff& other )
{
this->skillID = other.skillID;
this->skillLvl = other.skillLvl;
this->duration = other.duration;
wcscpy( this->cached_skillName, other.cached_skillName );
return (*this);
}
~UserBuff() { clear(); }
public:
void clear() { skillID = 0; skillLvl = 0; duration = -1; cached_skillName[0] = 0; }
wchar_t *getSkillNameW();
void getSkillName( wchar_t *out, size_t maxCount );
public:
unsigned int skillID;
int skillLvl;
int duration;
protected:
wchar_t cached_skillName[256];
};
class UserBuffs
{
public:
static const int USER_MAX_BUFFS = 64;
static const int USER_MAX_SHORT_BUFFS = 16;
public:
UserBuffs();
~UserBuffs();
void clear();
void clearShortBuffs();
public:
int addBuff( UserBuff *addbuff );
int addShortBuff( UserBuff *addbuff );
public:
int getBuffnfoBySkillId( unsigned int skillID, UserBuff *outbuff );
public:
void parse_AbnormalStatusUpdate( void *l2_game_packet );
void parse_ShortBuffStatusUpdate( void *l2_game_packet );
public:
void process_BuffTick( unsigned int curTick );
public:
int buffCount;
int shortBuffCount;
UserBuff buff[USER_MAX_BUFFS];
UserBuff short_buff[USER_MAX_SHORT_BUFFS];
unsigned int lastBuffKnownTick;
unsigned int lastShortBuffKnownTick;
};
#endif
| true |
9f08d720fe354037d5fb790e66b7f43c795173a0 | C++ | SofiaQuintana/ESTRU_2019 | /Proyecto 2/Guatemala's DB/Table.cpp | UTF-8 | 626 | 2.96875 | 3 | [] | no_license | #include "Table.hpp"
using namespace std;
Table::Table() {
setName("");
}
Table::Table(string name) {
setName(name);
this -> hashmap = new Hashtable();
}
void Table::addColumn(string name, string type) {
Column *column = new Column(type, name);
this -> columns.push_back(column);
}
void Table::addTuple(Data* data) {
this -> hashmap -> addData(data);
}
string Table::getName() {
return this -> name;
}
void Table::setName(string name) {
this -> name = name;
}
list<Column*> Table::getColumns() {
return this -> columns;
}
Hashtable* Table::getHash() {
return this -> hashmap;
} | true |
96a7c267236122c727dae4c8c0a4c13c51eb55f1 | C++ | mlepicka/Depth_Creator | /src/functions.cpp | UTF-8 | 2,939 | 3.03125 | 3 | [] | no_license | #include "../include/functions.hpp"
std::vector<String> read_sample_images_names(std::string path){
std::vector<String> images_filenames;
cv::glob(path, images_filenames, false);
std::cout << "Number of files in directory " << images_filenames.size() << std::endl;
return images_filenames;
}
std::vector<Mat> load_images(std::string path){
std::vector<Mat> images;
std::vector<String> images_filenames;
Mat src;
images_filenames = read_sample_images_names(path);
for(int iter= 0; iter < images_filenames.size() ; ++iter){
src = imread(images_filenames[iter], IMREAD_COLOR ); // Load an image
images.push_back(src);
}
return images;
}
std::pair<Mat, Mat> create_sharp_image_and_depth_map(std::vector<Mat> images){
std::vector<Mat> edge_maps;
std::vector<double> weights;
std::pair<Mat,Mat> result;
double weight_diff = 255.00/(double) images.size();
for(int iter= 0; iter < images.size() ; ++iter){
Mat edge_map = create_edge_map(images[iter]);
edge_maps.push_back(edge_map);
weights.push_back((double)iter*weight_diff);
}
Mat depth_map = edge_maps[0].clone();
depth_map = 0;
for(int iter= 1; iter < images.size() ; ++iter){
result = smart_max_mat(iter == 1 ? std::pair<Mat, Mat>(images[iter-1], edge_maps[iter-1]) : result,
std::pair<Mat, Mat>(images[iter], edge_maps[iter]),
depth_map, weights[iter]);
}
medianBlur(depth_map, depth_map, 3);
//second was just image with edges, we need depth map
result.second = depth_map;
return result;
}
std::pair<Mat, Mat> smart_max_mat(std::pair<Mat, Mat> firstImage, std::pair<Mat, Mat> secondImage, Mat depth_map, double color_modificator){
Mat color = firstImage.first.clone();
Mat grey = firstImage.second.clone();
for(int j=0; j< grey.rows; j++){
for (int i=0; i< grey.cols; i++){
if((uchar)firstImage.second.at<uchar>(j,i) <= (uchar)secondImage.second.at<uchar>(j,i)){
//second mat grey value is bigger - more edgy -> sharper part of image
color.at<Vec3b>(j,i) = secondImage.first.at<Vec3b>(j,i);
grey.at<uchar>(j,i) = secondImage.second.at<uchar>(j,i);
depth_map.at<uchar>(j,i) = (int)(255.00-color_modificator);
}
}
}
return std::pair<Mat, Mat>(color, grey);
}
Mat create_edge_map(Mat img) {
int scale = 1;
int delta = 0;
int ddepth = CV_16S;
Mat src_gray, edge_map;
cvtColor( img, src_gray, COLOR_BGR2GRAY );
Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y;
Sobel( src_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT );
Sobel( src_gray, grad_y, ddepth, 0, 1, 3, scale, delta, BORDER_DEFAULT );
convertScaleAbs( grad_x, abs_grad_x );
convertScaleAbs( grad_y, abs_grad_y );
addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, edge_map);
GaussianBlur(edge_map, edge_map, Size(5,5), 0, 0, BORDER_DEFAULT );
return edge_map;
} | true |
e214bdc1c384557d511f6e447c3d556c863eea02 | C++ | fengxueem/Home_Surveillance | /Day6/ngrok-c-master/https.cpp | UTF-8 | 36,659 | 2.953125 | 3 | [] | no_license | #include "https.h"
struct http_response* handle_redirect_get(struct http_response* hresp, char* custom_headers)
{
if(hresp->status_code_int > 300 && hresp->status_code_int < 399)
{
char *token = strtok(hresp->response_headers, "\r\n");
while(token != NULL)
{
if(str_contains(token, "Location:"))
{
/* Extract url */
char *location = str_replace("Location: ", "", token);
return http_get(location, custom_headers);
}
token = strtok(NULL, "\r\n");
}
}
else
{
/* We're not dealing with a redirect, just return the same structure */
return hresp;
}
}
/*
Handles redirect if needed for head requests
*/
struct http_response* handle_redirect_head(struct http_response* hresp, char* custom_headers)
{
if(hresp->status_code_int > 300 && hresp->status_code_int < 399)
{
char *token = strtok(hresp->response_headers, "\r\n");
while(token != NULL)
{
if(str_contains(token, "Location:"))
{
/* Extract url */
char *location = str_replace("Location: ", "", token);
return http_head(location, custom_headers);
}
token = strtok(NULL, "\r\n");
}
}
else
{
/* We're not dealing with a redirect, just return the same structure */
return hresp;
}
}
/*
Handles redirect if needed for post requests
*/
struct http_response* handle_redirect_post(struct http_response* hresp, char* custom_headers, char *post_data)
{
if(hresp->status_code_int > 300 && hresp->status_code_int < 399)
{
char *token = strtok(hresp->response_headers, "\r\n");
while(token != NULL)
{
if(str_contains(token, "Location:"))
{
/* Extract url */
char *location = str_replace("Location: ", "", token);
return http_post(location, custom_headers, post_data);
}
token = strtok(NULL, "\r\n");
}
}
else
{
/* We're not dealing with a redirect, just return the same structure */
return hresp;
}
}
/*
Makes a HTTP request and returns the response
*/
struct http_response* http_req(char *http_headers, struct parsed_url *purl)
{
/* Parse url */
if(purl == NULL)
{
printf("Unable to parse url");
return NULL;
}
/* Declare variable */
int sock;
int tmpres;
char buf[BUFSIZ+1];
struct sockaddr_in remote;
/* Allocate memeory for htmlcontent */
struct http_response *hresp = (struct http_response*)malloc(sizeof(struct http_response));
if(hresp == NULL)
{
printf("Unable to allocate memory for htmlcontent.");
return NULL;
}
hresp->body = NULL;
hresp->request_headers = NULL;
hresp->response_headers = NULL;
hresp->status_code = NULL;
hresp->status_text = NULL;
/* Create TCP socket */
if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
printf("Can't create TCP socket");
free(hresp);
return NULL;
}
/* Set remote->sin_addr.s_addr */
remote.sin_family = AF_INET;
#if WIN32
remote.sin_addr.s_addr= inet_addr(purl->ip);
#else
tmpres = inet_pton(AF_INET, purl->ip, (void *)(&(remote.sin_addr.s_addr)));
if( tmpres < 0)
{
printf("Can't set remote->sin_addr.s_addr");
free(hresp);
return NULL;
}
else if(tmpres == 0)
{
printf("Not a valid IP");
free(hresp);
return NULL;
}
#endif // WIN32
remote.sin_port = htons(atoi(purl->port));
/* Connect */
if(connect(sock, (struct sockaddr *)&remote, sizeof(struct sockaddr)) < 0)
{
printf("Could not connect");
free(hresp);
return NULL;
}
ssl_info *sslinfo;
if ( strcmp(purl->scheme,"https")==0)
{
sslinfo=(ssl_info*)malloc(sizeof(ssl_info));
if(ssl_init_info(&sock,sslinfo)==-1)
{
ssl_free_info(sslinfo);
free(sslinfo);
free(hresp);
return NULL;
}
}
/* Send headers to server */
int sent = 0;
while(sent < strlen(http_headers))
{
if ( strcmp(purl->scheme,"https")==0)
{
tmpres = ssl_write(&sslinfo->ssl, (unsigned char*)http_headers+sent, strlen(http_headers)-sent);
}
else
{
tmpres = send(sock, http_headers+sent, strlen(http_headers)-sent, 0);
}
if(tmpres == -1)
{
printf("Can't send headers");
if ( strcmp(purl->scheme,"https")==0)
{
ssl_free_info(sslinfo);
free(sslinfo);
}
free(hresp);
return NULL;
}
sent += tmpres;
}
/* Recieve into response*/
char *response = (char*)malloc(0);
char BUF[BUFSIZ];
int recived_len = 0;
if ( strcmp(purl->scheme,"https")==0)
{
while((recived_len = ssl_read(&sslinfo->ssl, (unsigned char *)BUF, BUFSIZ-1)) > 0)
{
BUF[recived_len] = '\0';
response = (char*)realloc(response, strlen(response) + recived_len + 1);
// sprintf(response, "%s%s", response, BUF);
memcpy(response+strlen(response),BUF,recived_len+1);
}
}
else
{
while((recived_len = recv(sock, BUF, BUFSIZ-1, 0)) > 0)
{
BUF[recived_len] = '\0';
response = (char*)realloc(response, strlen(response) + recived_len + 1);
// sprintf(response, "%s%s", response, BUF);
memcpy(response+strlen(response),BUF,recived_len+1);
}
}
//POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY remote close notify
if (recived_len < 0&&recived_len!=POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
{
free(http_headers);
#ifdef _WIN32
closesocket(sock);
#else
close(sock);
#endif
if(strcmp(purl->scheme,"https")==0)
{
ssl_free_info(sslinfo);
free(sslinfo);
}
free(response);
free(hresp);
return NULL;
}
/* Reallocate response */
response = (char*)realloc(response, strlen(response) + 1);
/* Close socket */
#ifdef _WIN32
closesocket(sock);
#else
close(sock);
#endif
/* Parse status code and text */
char *status_line = get_until(response, "\r\n");
status_line = str_replace("HTTP/1.1 ", "", status_line);
char *status_code = str_ndup(status_line, 4);
status_code = str_replace(" ", "", status_code);
char *status_text = str_replace(status_code, "", status_line);
status_text = str_replace(" ", "", status_text);
hresp->status_code = status_code;
hresp->status_code_int = atoi(status_code);
hresp->status_text = status_text;
/* Parse response headers */
char *headers = get_until(response, "\r\n\r\n");
hresp->response_headers = headers;
/* Assign request headers */
hresp->request_headers = http_headers;
/* Assign request url */
hresp->request_uri = purl;
int responselen=strlen(response);
int bodystart=strpos(response,"\r\n\r\n",0);
char *body;
if(bodystart+4>=responselen||bodystart<1)
{
body="";
}
else
{
body=response+bodystart+4;
}
//old
//char *body = strstr(response, "\r\n\r\n");
//body = str_replace("\r\n\r\n", "", body);
hresp->body = body;
/* Return response */
if (strcmp(purl->scheme,"https")==0)
{
ssl_free_info(sslinfo);
free(sslinfo);
}
return hresp;
}
/*
Makes a HTTP GET request to the given url
*/
struct http_response* http_get(char *url, char *custom_headers)
{
/* Parse url */
struct parsed_url *purl = parse_url(url);
if(purl == NULL)
{
printf("Unable to parse url");
return NULL;
}
/* Declare variable */
char *http_headers = (char*)malloc(1024);
/* Build query/headers */
if(purl->path != NULL)
{
if(purl->query != NULL)
{
sprintf(http_headers, "GET /%s?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->path, purl->query, purl->host);
}
else
{
sprintf(http_headers, "GET /%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->path, purl->host);
}
}
else
{
if(purl->query != NULL)
{
sprintf(http_headers, "GET /?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->query, purl->host);
}
else
{
sprintf(http_headers, "GET / HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->host);
}
}
/* Handle authorisation if needed */
if(purl->username != NULL)
{
/* Format username:password pair */
char *upwd = (char*)malloc(1024);
sprintf(upwd, "%s:%s", purl->username, purl->password);
upwd = (char*)realloc(upwd, strlen(upwd) + 1);
/* Base64 encode */
char *base64 = base64_encode(upwd);
/* Form header */
char *auth_header = (char*)malloc(1024);
sprintf(auth_header, "Authorization: Basic %s\r\n", base64);
auth_header = (char*)realloc(auth_header, strlen(auth_header) + 1);
/* Add to header */
http_headers = (char*)realloc(http_headers, strlen(http_headers) + strlen(auth_header) + 2);
sprintf(http_headers, "%s%s", http_headers, auth_header);
}
/* Add custom headers, and close */
if(custom_headers != NULL)
{
sprintf(http_headers, "%s%s\r\n", http_headers, custom_headers);
}
else
{
sprintf(http_headers, "%s\r\n", http_headers);
}
http_headers = (char*)realloc(http_headers, strlen(http_headers) + 1);
/* Make request and return response */
struct http_response *hresp = http_req(http_headers, purl);
if(hresp!=NULL)
{
return handle_redirect_get(hresp, custom_headers);
}
/* Handle redirect */
return NULL;
}
/*
Makes a HTTP POST request to the given url
*/
struct http_response* http_post(char *url, char *custom_headers, char *post_data)
{
/* Parse url */
struct parsed_url *purl = parse_url(url);
if(purl == NULL)
{
printf("Unable to parse url");
return NULL;
}
/* Declare variable */
char *http_headers = (char*)malloc(1024);
/* Build query/headers */
if(purl->path != NULL)
{
if(purl->query != NULL)
{
sprintf(http_headers, "POST /%s?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\nContent-Length:%d\r\nContent-Type:application/x-www-form-urlencoded\r\n", purl->path, purl->query, purl->host, strlen(post_data));
}
else
{
sprintf(http_headers, "POST /%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\nContent-Length:%d\r\nContent-Type:application/x-www-form-urlencoded\r\n", purl->path, purl->host, strlen(post_data));
}
}
else
{
if(purl->query != NULL)
{
sprintf(http_headers, "POST /?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\nContent-Length:%d\r\nContent-Type:application/x-www-form-urlencoded\r\n", purl->query, purl->host, strlen(post_data));
}
else
{
sprintf(http_headers, "POST / HTTP/1.1\r\nHost:%s\r\nConnection:close\r\nContent-Length:%d\r\nContent-Type:application/x-www-form-urlencoded\r\n", purl->host, strlen(post_data));
}
}
/* Handle authorisation if needed */
if(purl->username != NULL)
{
/* Format username:password pair */
char *upwd = (char*)malloc(1024);
sprintf(upwd, "%s:%s", purl->username, purl->password);
upwd = (char*)realloc(upwd, strlen(upwd) + 1);
/* Base64 encode */
char *base64 = base64_encode(upwd);
/* Form header */
char *auth_header = (char*)malloc(1024);
sprintf(auth_header, "Authorization: Basic %s\r\n", base64);
auth_header = (char*)realloc(auth_header, strlen(auth_header) + 1);
/* Add to header */
http_headers = (char*)realloc(http_headers, strlen(http_headers) + strlen(auth_header) + 2);
sprintf(http_headers, "%s%s", http_headers, auth_header);
}
if(custom_headers != NULL)
{
sprintf(http_headers, "%s%s\r\n", http_headers, custom_headers);
sprintf(http_headers, "%s\r\n%s", http_headers, post_data);
}
else
{
sprintf(http_headers, "%s\r\n%s", http_headers, post_data);
}
http_headers = (char*)realloc(http_headers, strlen(http_headers) + 1);
/* Make request and return response */
struct http_response *hresp = http_req(http_headers, purl);
// printf("post_data:%s\r\n",post_data);
if(hresp==NULL)
{
return NULL;
}
/* Handle redirect */
return handle_redirect_post(hresp, custom_headers, post_data);
}
/*
Makes a HTTP HEAD request to the given url
*/
struct http_response* http_head(char *url, char *custom_headers)
{
/* Parse url */
struct parsed_url *purl = parse_url(url);
if(purl == NULL)
{
printf("Unable to parse url");
return NULL;
}
/* Declare variable */
char *http_headers = (char*)malloc(1024);
/* Build query/headers */
if(purl->path != NULL)
{
if(purl->query != NULL)
{
sprintf(http_headers, "HEAD /%s?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->path, purl->query, purl->host);
}
else
{
sprintf(http_headers, "HEAD /%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->path, purl->host);
}
}
else
{
if(purl->query != NULL)
{
sprintf(http_headers, "HEAD/?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->query, purl->host);
}
else
{
sprintf(http_headers, "HEAD / HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->host);
}
}
/* Handle authorisation if needed */
if(purl->username != NULL)
{
/* Format username:password pair */
char *upwd = (char*)malloc(1024);
sprintf(upwd, "%s:%s", purl->username, purl->password);
upwd = (char*)realloc(upwd, strlen(upwd) + 1);
/* Base64 encode */
char *base64 = base64_encode(upwd);
/* Form header */
char *auth_header = (char*)malloc(1024);
sprintf(auth_header, "Authorization: Basic %s\r\n", base64);
auth_header = (char*)realloc(auth_header, strlen(auth_header) + 1);
/* Add to header */
http_headers = (char*)realloc(http_headers, strlen(http_headers) + strlen(auth_header) + 2);
sprintf(http_headers, "%s%s", http_headers, auth_header);
}
if(custom_headers != NULL)
{
sprintf(http_headers, "%s%s\r\n", http_headers, custom_headers);
}
else
{
sprintf(http_headers, "%s\r\n", http_headers);
}
http_headers = (char*)realloc(http_headers, strlen(http_headers) + 1);
/* Make request and return response */
struct http_response *hresp = http_req(http_headers, purl);
/* Handle redirect */
return handle_redirect_head(hresp, custom_headers);
}
/*
Do HTTP OPTIONs requests
*/
struct http_response* http_options(char *url)
{
/* Parse url */
struct parsed_url *purl = parse_url(url);
if(purl == NULL)
{
printf("Unable to parse url");
return NULL;
}
/* Declare variable */
char *http_headers = (char*)malloc(1024);
/* Build query/headers */
if(purl->path != NULL)
{
if(purl->query != NULL)
{
sprintf(http_headers, "OPTIONS /%s?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->path, purl->query, purl->host);
}
else
{
sprintf(http_headers, "OPTIONS /%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->path, purl->host);
}
}
else
{
if(purl->query != NULL)
{
sprintf(http_headers, "OPTIONS/?%s HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->query, purl->host);
}
else
{
sprintf(http_headers, "OPTIONS / HTTP/1.1\r\nHost:%s\r\nConnection:close\r\n", purl->host);
}
}
/* Handle authorisation if needed */
if(purl->username != NULL)
{
/* Format username:password pair */
char *upwd = (char*)malloc(1024);
sprintf(upwd, "%s:%s", purl->username, purl->password);
upwd = (char*)realloc(upwd, strlen(upwd) + 1);
/* Base64 encode */
char *base64 = base64_encode(upwd);
/* Form header */
char *auth_header = (char*)malloc(1024);
sprintf(auth_header, "Authorization: Basic %s\r\n", base64);
auth_header = (char*)realloc(auth_header, strlen(auth_header) + 1);
/* Add to header */
http_headers = (char*)realloc(http_headers, strlen(http_headers) + strlen(auth_header) + 2);
sprintf(http_headers, "%s%s", http_headers, auth_header);
}
/* Build headers */
sprintf(http_headers, "%s\r\n", http_headers);
http_headers = (char*)realloc(http_headers, strlen(http_headers) + 1);
/* Make request and return response */
struct http_response *hresp = http_req(http_headers, purl);
/* Handle redirect */
return hresp;
}
/*
Free memory of http_response
*/
void http_response_free(struct http_response *hresp)
{
if(hresp != NULL)
{
if(hresp->request_uri != NULL) parsed_url_free(hresp->request_uri);
if(hresp->body != NULL) free(hresp->body);
if(hresp->status_code != NULL) free(hresp->status_code);
if(hresp->status_text != NULL) free(hresp->status_text);
if(hresp->request_headers != NULL) free(hresp->request_headers);
if(hresp->response_headers != NULL) free(hresp->response_headers);
free(hresp);
}
}
/*
Gets the offset of one string in another string
*/
int str_index_of(const char *a, char *b)
{
char *offset = (char*)strstr(a, b);
return offset - a;
}
/*
Checks if one string contains another string
*/
int str_contains(const char *haystack, const char *needle)
{
char *pos = (char*)strstr(haystack, needle);
if(pos)
return 1;
else
return 0;
}
/*
Removes last character from string
*/
char* trim_end(char *string, char to_trim)
{
char last_char = string[strlen(string) -1];
if(last_char == to_trim)
{
char *new_string = string;
new_string[strlen(string) - 1] = 0;
return new_string;
}
else
{
return string;
}
}
/*
Concecates two strings, a wrapper for strcat from string.h, handles the resizing and copying
*/
char* str_cat(char *a, char *b)
{
char *target = (char*)malloc(strlen(a) + strlen(b) + 1);
strcpy(target, a);
strcat(target, b);
return target;
}
/*
Converts an integer value to its hex character
*/
char to_hex(char code)
{
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/*
URL encodes a string
*/
char *urlencode(char *str)
{
char *pstr = str, *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf;
while (*pstr)
{
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if (*pstr == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
/*
Replacement for the string.h strndup, fixes a bug
*/
char *str_ndup (const char *str, size_t max)
{
size_t len = strnlen(str, max);
char *res = (char*)malloc (len + 1);
if (res)
{
memcpy (res, str, len);
res[len] = '\0';
}
return res;
}
/*
Replacement for the string.h strdup, fixes a bug
*/
char *str_dup(const char *src)
{
char *tmp = (char*)malloc(strlen(src) + 1);
if(tmp)
strcpy(tmp, src);
return tmp;
}
/*
Search and replace a string with another string , in a string
*/
char *str_replace(char *search , char *replace , char *subject)
{
char *p = NULL , *old = NULL , *new_subject = NULL ;
int c = 0 , search_size;
search_size = strlen(search);
for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
{
c++;
}
c = ( strlen(replace) - search_size )*c + strlen(subject);
new_subject = (char*)malloc( c );
strcpy(new_subject , "");
old = subject;
for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
{
strncpy(new_subject + strlen(new_subject) , old , p - old);
strcpy(new_subject + strlen(new_subject) , replace);
old = p + search_size;
}
strcpy(new_subject + strlen(new_subject) , old);
return new_subject;
}
/*
Get's all characters until '*until' has been found
*/
char* get_until(char *haystack, char *until)
{
int offset = str_index_of(haystack, until);
return str_ndup(haystack, offset);
}
/* decodeblock - decode 4 '6-bit' characters into 3 8-bit binary bytes */
void decodeblock(unsigned char in[], char *clrstr)
{
unsigned char out[4];
out[0] = in[0] << 2 | in[1] >> 4;
out[1] = in[1] << 4 | in[2] >> 2;
out[2] = in[2] << 6 | in[3] >> 0;
out[3] = '\0';
strncat((char *)clrstr, (char *)out, sizeof(out));
}
/*
Decodes a Base64 string
*/
char* base64_decode(char *b64src)
{
char *clrdst = (char*)malloc( ((strlen(b64src) - 1) / 3 ) * 4 + 4 + 50);
char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int c, phase, i;
unsigned char in[4];
char *p;
clrdst[0] = '\0';
phase = 0; i=0;
while(b64src[i])
{
c = (int) b64src[i];
if(c == '=')
{
decodeblock(in, clrdst);
break;
}
p = strchr(b64, c);
if(p)
{
in[phase] = p - b64;
phase = (phase + 1) % 4;
if(phase == 0)
{
decodeblock(in, clrdst);
in[0]=in[1]=in[2]=in[3]=0;
}
}
i++;
}
clrdst = (char*)realloc(clrdst, strlen(clrdst) + 1);
return clrdst;
}
/* encodeblock - encode 3 8-bit binary bytes as 4 '6-bit' characters */
void encodeblock( unsigned char in[], char b64str[], int len )
{
char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char out[5];
out[0] = b64[ in[0] >> 2 ];
out[1] = b64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
out[2] = (unsigned char) (len > 1 ? b64[ ((in[1] & 0x0f) << 2) |
((in[2] & 0xc0) >> 6) ] : '=');
out[3] = (unsigned char) (len > 2 ? b64[ in[2] & 0x3f ] : '=');
out[4] = '\0';
strncat((char *)b64str, (char *)out, sizeof(out));
}
/*
Encodes a string with Base64
*/
char* base64_encode(char *clrstr)
{
char *b64dst = (char*)malloc(strlen(clrstr) + 50);
char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
unsigned char in[3];
int i, len = 0;
int j = 0;
b64dst[0] = '\0';
while(clrstr[j])
{
len = 0;
for(i=0; i<3; i++)
{
in[i] = (unsigned char) clrstr[j];
if(clrstr[j])
{
len++; j++;
}
else in[i] = 0;
}
if( len )
{
encodeblock( in, b64dst, len );
}
}
b64dst = (char*)realloc(b64dst, strlen(b64dst) + 1);
return b64dst;
}
/*
http-client-c
Copyright (C) 2012-2013 Swen Kooij
This file is part of http-client-c.
http-client-c is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
http-client-c is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with http-client-c. If not, see <http://www.gnu.org/licenses/>.
Warning:
This library does not tend to work that stable nor does it fully implent the
standards described by IETF. For more information on the precise implentation of the
Hyper Text Transfer Protocol:
http://www.ietf.org/rfc/rfc2616.txt
*/
/*
Free memory of parsed url
*/
void parsed_url_free(struct parsed_url *purl)
{
if ( NULL != purl )
{
if ( NULL != purl->scheme ) free(purl->scheme);
if ( NULL != purl->host ) free(purl->host);
if ( NULL != purl->port ) free(purl->port);
if ( NULL != purl->path ) free(purl->path);
if ( NULL != purl->query ) free(purl->query);
if ( NULL != purl->fragment ) free(purl->fragment);
if ( NULL != purl->username ) free(purl->username);
if ( NULL != purl->password ) free(purl->password);
free(purl);
}
}
/*
Retrieves the IP adress of a hostname
*/
char* hostname_to_ip(char *hostname)
{
char *ip = "0.0.0.0";
struct hostent *h;
if ((h=gethostbyname(hostname)) == NULL)
{
printf("gethostbyname");
return NULL;
}
return inet_ntoa(*((struct in_addr *)h->h_addr));
}
/*
Check whether the character is permitted in scheme string
*/
int is_scheme_char(int c)
{
return (!isalpha(c) && '+' != c && '-' != c && '.' != c) ? 0 : 1;
}
/*
Parses a specified URL and returns the structure named 'parsed_url'
Implented according to:
RFC 1738 - http://www.ietf.org/rfc/rfc1738.txt
RFC 3986 - http://www.ietf.org/rfc/rfc3986.txt
*/
struct parsed_url *parse_url(const char *url)
{
/* Define variable */
struct parsed_url *purl;
const char *tmpstr;
const char *curstr;
int len;
int i;
int userpass_flag;
int bracket_flag;
/* Allocate the parsed url storage */
purl = (struct parsed_url*)malloc(sizeof(struct parsed_url));
if ( NULL == purl )
{
return NULL;
}
purl->scheme = NULL;
purl->host = NULL;
purl->port = NULL;
purl->path = NULL;
purl->query = NULL;
purl->fragment = NULL;
purl->username = NULL;
purl->password = NULL;
curstr = url;
/*
* <scheme>:<scheme-specific-part>
* <scheme> := [a-z\+\-\.]+
* upper case = lower case for resiliency
*/
/* Read scheme */
tmpstr = strchr(curstr, ':');
if ( NULL == tmpstr )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
/* Get the scheme length */
len = tmpstr - curstr;
/* Check restrictions */
for ( i = 0; i < len; i++ )
{
if (is_scheme_char(curstr[i]) == 0)
{
/* Invalid format */
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
}
/* Copy the scheme to the storage */
purl->scheme = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->scheme )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->scheme, curstr, len);
purl->scheme[len] = '\0';
/* Make the character to lower if it is upper case. */
for ( i = 0; i < len; i++ )
{
purl->scheme[i] = tolower(purl->scheme[i]);
}
/* Skip ':' */
tmpstr++;
curstr = tmpstr;
/*
* //<user>:<password>@<host>:<port>/<url-path>
* Any ":", "@" and "/" must be encoded.
*/
/* Eat "//" */
for ( i = 0; i < 2; i++ )
{
if ( '/' != *curstr )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
curstr++;
}
/* Check if the user (and password) are specified. */
userpass_flag = 0;
tmpstr = curstr;
while ( '\0' != *tmpstr )
{
if ( '@' == *tmpstr )
{
/* Username and password are specified */
userpass_flag = 1;
break;
}
else if ( '/' == *tmpstr )
{
/* End of <host>:<port> specification */
userpass_flag = 0;
break;
}
tmpstr++;
}
/* User and password specification */
tmpstr = curstr;
if ( userpass_flag )
{
/* Read username */
while ( '\0' != *tmpstr && ':' != *tmpstr && '@' != *tmpstr )
{
tmpstr++;
}
len = tmpstr - curstr;
purl->username = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->username )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->username, curstr, len);
purl->username[len] = '\0';
/* Proceed current pointer */
curstr = tmpstr;
if ( ':' == *curstr )
{
/* Skip ':' */
curstr++;
/* Read password */
tmpstr = curstr;
while ( '\0' != *tmpstr && '@' != *tmpstr )
{
tmpstr++;
}
len = tmpstr - curstr;
purl->password = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->password )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->password, curstr, len);
purl->password[len] = '\0';
curstr = tmpstr;
}
/* Skip '@' */
if ( '@' != *curstr )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
curstr++;
}
if ( '[' == *curstr )
{
bracket_flag = 1;
}
else
{
bracket_flag = 0;
}
/* Proceed on by delimiters with reading host */
tmpstr = curstr;
while ( '\0' != *tmpstr ) {
if ( bracket_flag && ']' == *tmpstr )
{
/* End of IPv6 address. */
tmpstr++;
break;
}
else if ( !bracket_flag && (':' == *tmpstr || '/' == *tmpstr) )
{
/* Port number is specified. */
break;
}
tmpstr++;
}
len = tmpstr - curstr;
purl->host = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->host || len <= 0 )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->host, curstr, len);
purl->host[len] = '\0';
curstr = tmpstr;
/* Is port number specified? */
if ( ':' == *curstr )
{
curstr++;
/* Read port number */
tmpstr = curstr;
while ( '\0' != *tmpstr && '/' != *tmpstr )
{
tmpstr++;
}
len = tmpstr - curstr;
purl->port = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->port )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->port, curstr, len);
purl->port[len] = '\0';
curstr = tmpstr;
}
else
{
purl->port = (char*)malloc(4);
memset(purl->port,0,4);
if(strcmp(purl->scheme,"https")==0)
{
(void)strncpy(purl->port, "443", 3);
}
else
{
(void)strncpy(purl->port, "80", 3);
}
}
/* Get ip */
char *ip = hostname_to_ip(purl->host);
purl->ip = ip;
/* Set uri */
purl->uri = (char*)url;
/* End of the string */
if ( '\0' == *curstr )
{
return purl;
}
/* Skip '/' */
if ( '/' != *curstr )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
curstr++;
/* Parse path */
tmpstr = curstr;
while ( '\0' != *tmpstr && '#' != *tmpstr && '?' != *tmpstr )
{
tmpstr++;
}
len = tmpstr - curstr;
purl->path = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->path )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->path, curstr, len);
purl->path[len] = '\0';
curstr = tmpstr;
/* Is query specified? */
if ( '?' == *curstr )
{
/* Skip '?' */
curstr++;
/* Read query */
tmpstr = curstr;
while ( '\0' != *tmpstr && '#' != *tmpstr )
{
tmpstr++;
}
len = tmpstr - curstr;
purl->query = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->query )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->query, curstr, len);
purl->query[len] = '\0';
curstr = tmpstr;
}
/* Is fragment specified? */
if ( '#' == *curstr )
{
/* Skip '#' */
curstr++;
/* Read fragment */
tmpstr = curstr;
while ( '\0' != *tmpstr )
{
tmpstr++;
}
len = tmpstr - curstr;
purl->fragment = (char*)malloc(sizeof(char) * (len + 1));
if ( NULL == purl->fragment )
{
parsed_url_free(purl); fprintf(stderr, "Error on line %d (%s)\n", __LINE__, __FILE__);
return NULL;
}
(void)strncpy(purl->fragment, curstr, len);
purl->fragment[len] = '\0';
curstr = tmpstr;
}
return purl;
}
#if WIN32
size_t strnlen (const char *str, size_t maxlen)
{
const char *char_ptr, *end_ptr = str + maxlen;
const unsigned long int *longword_ptr;
unsigned long int longword, magic_bits, himagic, lomagic;
if (maxlen == 0)
return 0;
if (__builtin_expect (end_ptr < str, 0))
end_ptr = (const char *) ~0UL;
/* Handle the first few characters by reading one character at a time.
Do this until CHAR_PTR is aligned on a longword boundary. */
for (char_ptr = str; ((unsigned long int) char_ptr
& (sizeof (longword) - 1)) != 0;
++char_ptr)
if (*char_ptr == '/0')
{
if (char_ptr > end_ptr)
char_ptr = end_ptr;
return char_ptr - str;
}
/* All these elucidatory comments refer to 4-byte longwords,
but the theory applies equally well to 8-byte longwords. */
longword_ptr = (unsigned long int *) char_ptr;
/* Bits 31, 24, 16, and 8 of this number are zero. Call these bits
the "holes." Note that there is a hole just to the left of
each byte, with an extra at the end:
bits: 01111110 11111110 11111110 11111111
bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
The 1-bits make sure that carries propagate to the next 0-bit.
The 0-bits provide holes for carries to fall into. */
magic_bits = 0x7efefeffL;
himagic = 0x80808080L;
lomagic = 0x01010101L;
if (sizeof (longword) > 4)
{
/* 64-bit version of the magic. */
/* Do the shift in two steps to avoid a warning if long has 32 bits. */
magic_bits = ((0x7efefefeL << 16) << 16) | 0xfefefeffL;
himagic = ((himagic << 16) << 16) | himagic;
lomagic = ((lomagic << 16) << 16) | lomagic;
}
if (sizeof (longword) > 8)
abort ();
/* Instead of the traditional loop which tests each character,
we will test a longword at a time. The tricky part is testing
if *any of the four* bytes in the longword in question are zero. */
while (longword_ptr < (unsigned long int *) end_ptr)
{
/* We tentatively exit the loop if adding MAGIC_BITS to
LONGWORD fails to change any of the hole bits of LONGWORD.
1) Is this safe? Will it catch all the zero bytes?
Suppose there is a byte with all zeros. Any carry bits
propagating from its left will fall into the hole at its
least significant bit and stop. Since there will be no
carry from its most significant bit, the LSB of the
byte to the left will be unchanged, and the zero will be
detected.
2) Is this worthwhile? Will it ignore everything except
zero bytes? Suppose every byte of LONGWORD has a bit set
somewhere. There will be a carry into bit 8. If bit 8
is set, this will carry into bit 16. If bit 8 is clear,
one of bits 9-15 must be set, so there will be a carry
into bit 16. Similarly, there will be a carry into bit
24. If one of bits 24-30 is set, there will be a carry
into bit 31, so all of the hole bits will be changed.
The one misfire occurs when bits 24-30 are clear and bit
31 is set; in this case, the hole at bit 31 is not
changed. If we had access to the processor carry flag,
we could close this loophole by putting the fourth hole
at bit 32!
So it ignores everything except 128's, when they're aligned
properly. */
longword = *longword_ptr++;
if ((longword - lomagic) & himagic)
{
/* Which of the bytes was the zero? If none of them were, it was
a misfire; continue the search. */
const char *cp = (const char *) (longword_ptr - 1);
char_ptr = cp;
if (cp[0] == 0)
break;
char_ptr = cp + 1;
if (cp[1] == 0)
break;
char_ptr = cp + 2;
if (cp[2] == 0)
break;
char_ptr = cp + 3;
if (cp[3] == 0)
break;
if (sizeof (longword) > 4)
{
char_ptr = cp + 4;
if (cp[4] == 0)
break;
char_ptr = cp + 5;
if (cp[5] == 0)
break;
char_ptr = cp + 6;
if (cp[6] == 0)
break;
char_ptr = cp + 7;
if (cp[7] == 0)
break;
}
}
char_ptr = end_ptr;
}
if (char_ptr > end_ptr)
char_ptr = end_ptr;
return char_ptr - str;
}
#endif
int strpos(const char *haystack,const char *needle, int ignorecase = 0)
{
register unsigned char c, needc;
unsigned char const *from, *end;
int len = strlen(haystack);
int needlen = strlen(needle);
from = (unsigned char *)haystack;
end = (unsigned char *)haystack + len;
const char *findreset = needle;
for (int i = 0; from < end; ++i) {
c = *from++;
needc = *needle;
if (ignorecase) {
if (c >= 65 && c < 97)
c += 32;
if (needc >= 65 && needc < 97)
needc += 32;
}
if(c == needc) {
++needle;
if(*needle == '\0') {
if (len == needlen)
return 0;
else
return i - needlen+1;
}
}
else {
if(*needle == '\0' && needlen > 0)
return i - needlen +1;
needle = findreset;
}
}
return -1;
}
| true |
80048da699e51546ef62efee5735b40bf08cb7b3 | C++ | InigoRomero/CPP-Modules | /CPP04/ex03/main.cpp | UTF-8 | 1,125 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include "Cure.hpp"
#include "Ice.hpp"
#include "MateriaSource.hpp"
#include "Character.hpp"
int main()
{
IMateriaSource* src = new MateriaSource();
src->learnMateria(new Ice());
src->learnMateria(new Cure());
ICharacter* moi = new Character("moi");
AMateria* tmp = NULL;
AMateria* tmp2 = NULL;
tmp = src->createMateria("ice");
moi->equip(tmp);
std::cout << tmp->getType() << std::endl;
tmp2 = src->createMateria("cure");
moi->equip(tmp2);
std::cout << tmp2->getType() << std::endl;
ICharacter* bob = new Character("bob");
moi->use(-1, *bob);
moi->use(0, *bob);
moi->use(0, *bob);
moi->use(0, *bob);
moi->use(1, *bob);
moi->use(2, *bob);
std::cout << tmp->getType() << " xp = " << tmp->getXP() << std::endl;
std::cout << tmp2->getType() << " xp = " << tmp2->getXP() << std::endl;
moi->unequip(0);
moi->use(0, *bob);
moi->use(1, *bob);
std::cout << tmp2->getType() << " xp = " << tmp2->getXP() << std::endl;
delete bob;
delete moi;
delete src;
return 0;
} | true |
1e5e06dac93077d05cf2ae4a0cf0e0b397d239cd | C++ | gptakhil/Cpp-Revision | /Calculator_using_class.cpp | UTF-8 | 915 | 4.09375 | 4 | [
"MIT"
] | permissive | # include <iostream>
using namespace std;
class calculator{
float num1,num2;
public:
calculator(){
num1 = 0;
num2 = 0;
}
int add(float n1 , float n2){
num1 = n1;
num2 = n2;
return num1 + num2;
}
float subtract(float n1, float n2){
num1 = n1;
num2 = n2;
return num2 - num1;
}
float multiply(float n1, float n2){
num1 = n1;
num2 = n2;
return n1*n2;
}
float divide(float n1, float n2){
num1 = n1;
num2 = n2;
return num2/num1;
}
};
int main(){
calculator obj;
cout << "Addition of 10 and 94: " << obj.add(10, 94) << endl;
cout << "Subtraction of 10 and 94: " << obj.subtract(10, 94) << endl;
cout << "Multiplication of 10 and 94: " << obj.multiply(10, 94) << endl;
cout << "Division of 10 and 94: " << obj.divide(10, 94) << endl;
}
| true |
fc73330c0c787c95ca35d868251200acfa645b4e | C++ | SyssouREB/Odin | /Programmes/Programmes-intermédiaires/Programmes-Scanner-Ecran/affichage2dim.ino | UTF-8 | 6,639 | 2.578125 | 3 | [] | no_license | #include<Servo.h>
#include<math.h>
#include<SoftwareSerial.h>
#define RX 7
#define TX 8
#define RXb 2
#define TXb 3
Servo servoVer;
Servo servoHor;
char scan=' ';
int byt[9];
int distance;
const int HEADER=0x59;
char printout[4];
#include <TFT.h>
#include <SPI.h>
#define TFT_CS 10
#define TFT_RST 9
#define TFT_DC 8
#define TFT_SCLK 52
#define TFT_MOSI 51
TFT screen=TFT(TFT_CS,TFT_DC,TFT_RST);//mise en place de l'écran
//////////////////////////////////////////////////
int laserfct(){
if(Serial2.available()){//vérifie que le laser possède des données
for(int i=0;i<9;i++){//lecture des 9 bytes envoyé par le laser
byt[i]=Serial2.read();//lit les 8 bytes et les place dans un tableau
}
if((HEADER==byt[0]) && (HEADER==byt[1])){//vérifie les 2 premiers bytes
int check=byt[0]+byt[1]+byt[2]+byt[3]+byt[4]+byt[5]+byt[6]+byt[7];//variable qui va vérifier le bon fonctionnement du laser et si les données recu sont bonnes
if(byt[8]==(check&0xff)){
distance=byt[2]+byt[3]*256;//calcul de la distance
return distance;//retour de la distance
}
}
}
return;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
void scanner(){ //fonction permettant de scanner
Serial2.begin(115200);
float k=0;
float l=0;
for(int j=110;j>=50;j--){//boucle pour le servo verticale
servoVer.attach(6);// permet d'attacher le servo verticale au port lui correspondant
servoVer.write(j);
for(int i=40;i<=120;i+=1){//boucle pour le servo horizontale aller
servoHor.attach(5);
servoHor.write(i);
Serial2.end();
Serial2.begin(115200);
delay(10);
k=sin((float)j*PI/180)*sin((float)i*PI/180)*laserfct();
Serial.println(k);
if((k<60)&&(k>=40)){// si la distance est inférieur a 30cm active la couleur
screen.stroke(255-k,0,0);
}
else if((k<40)&&(k>=30)){
screen.stroke(0,255-k,255-k);
}
else if((k<30)&&(k>=20)){
screen.stroke(0,165-k,255-k);
}
else if((k<20)&&(k>0)){
screen.stroke(0,0,255-k);
}
else{
screen.stroke(0,0,0);
}
screen.point(i,j);// dessin du point aux coordonnées x,y
delay(10);
servoHor.detach();
}
j=j-1;
servoVer.write(j);
for(int i=120;i>=40;i--){// 2ème boucle pour le servo horizontale retour
servoHor.attach(5);
servoHor.write(i);
Serial2.end();
Serial2.begin(115200);
delay(10);
l=sin((float)j*PI/180)*sin((float)i*PI/180)*laserfct();
Serial.println(l);
if((l<60)&&(l>=40)){// si la distance est inférieur a 30cm active la couleur
screen.stroke(255-l,0,0);
}
else if((l<40)&&(l>=30)){
screen.stroke(0,255-l,255-l);
}
else if((l<30)&&(l>=20)){
screen.stroke(0,165-l,255-l);
}
else if((l<20)&&(l>0)){
screen.stroke(0,0,255-l);
}
else{
screen.stroke(0,0,0);
}
screen.point(i,j);
delay(10);
servoHor.detach();
}
delay(10);
servoVer.detach();//permet de détacher le servo verticale de son port (plus de fluifité)
}
servoVer.attach(6);
servoHor.attach(5);
servoVer.write(90);
delay(3000);
screen.background(0,0,0);
}
//////////////////////
bool scanBT(){// fonction pour le bluetooth
while(Serial3.available()){// si le bluetooth recoit quelque chose faire la suite
scan=char(Serial3.read());// lit la lettre recu par le bluetooth
}
if(scan=='A'){// lance scanner si le bluetooth recoit la lettre A
scanner();
scan="E";
return true;
}
else{return false;}
}
///////////////////////////////////////////////////////////
void setup() {
servoVer.attach(6);
servoHor.attach(5);
Serial.begin(250000);
Serial2.begin(115200);
Serial3.begin(9600);
screen.begin();//allume l'écran
screen.background(0,0,0);//met le fond en noir
}
void loop() {
int temps=millis();
int k;
int currentmillis=millis();
Serial.println(laserfct());// fonction laser qui print les valeurs ddistances
for(int h=10;h<=150;h++){// boucles for afin de déplacer le servo horizontale de gauche à droite
servoHor.write(h);
k=laserfct();
scanBT();// appel de la fonction bluetooth a chaque boucle afin de recevoir l'information pour lancer scanner
delay(10);
if((k<50)&&(k>10)){
Serial.println("cc");
Serial2.end();
temps=millis();
currentmillis=millis();
while((currentmillis-temps)/1000<5){
if(scanBT()){
temps=millis();
}
currentmillis=millis();
screen.stroke(255,0,255);
screen.setTextSize(1);
screen.text("Appuyez sur le bouton rouge",1,1);
int t=(currentmillis-temps)/1000;
String ts=String(t);
ts.toCharArray(printout,4);
screen.text(printout,1,30);
delay(1000);
screen.background(0,0,0);
}
temps=millis();
currentmillis=millis();
while((currentmillis-temps)/1000<=5){
currentmillis=millis();
}
Serial2.begin(115200);
}
Serial.println(k);
delay(5);
}
Serial.println(laserfct());
for(int h=150;h>=10;h--){// boucles for afin de déplacer le servo horizontale de droite à gauche
servoHor.write(h);
scanBT();
k=laserfct();
delay(10);
if((k<60)&&(k>10)){
Serial2.end();
Serial.println("cc");
temps=millis();
currentmillis=millis();
while((currentmillis-temps)/1000<5){
if(scanBT()){
temps=millis();
}
currentmillis=millis();
screen.stroke(255,0,255);
screen.setTextSize(1);
screen.text("Appuyez sur le bouton rouge",1,1);
int t=(currentmillis-temps)/1000;
String ts=String(t);
ts.toCharArray(printout,4);
screen.text(printout,1,30);
delay(1000);
screen.background(0,0,0);
}
temps=millis();
currentmillis=millis();
while((currentmillis-temps)/1000<=5){
currentmillis=millis();
}
Serial2.begin(115200);
}
Serial.println(k);
delay(5);
}
}
| true |
1de4b7f63d9a478605b5580268bc80bc57c289ef | C++ | BinFench/CppBoil | /src/arg.h | UTF-8 | 1,677 | 3.4375 | 3 | [] | no_license | /*
Author: Ben Finch
Email: benjamincfinch@gmail.com
Desc: declaration of arg. Arg holds any amount of parameters to be used
in a stack or recursion function.
*/
#include "stack/stackLink.h"
#include "stack/stack.h"
#include "parser/rule.h"
#include "ast/ASTNode.h"
#include <type_traits>
#ifndef ARG_H
#define ARG_H
class arg {
// Arg class holds any amount of items as parameters.
public:
arg();
template <typename... Args>
arg(Args... args);
void *get(int i);
int getSize();
stack *values;
arg *copy();
~arg();
protected:
stackLink *link;
int size = 0;
template <typename T, typename... Args>
void populate(stackLink *current, T par, Args... Arg);
template <typename T>
void populate(stackLink *current, T par);
void checkRule(stackLink *add, rule *par);
void checkRule(stackLink *add, void *par);
};
// Can pass any number of items into arg.
template <typename... Args>
arg::arg(Args... args) {
size = 0;
link = new stackLink();
link->test = "init";
populate(link, args...);
}
// Parametric recursion to build linked list of arguments.
template <typename T, typename... Args>
void arg::populate(stackLink *current, T par, Args... Arg) {
current->test = "append";
current->hasItem = true;
checkRule(current, par);
size++;
current->link = new stackLink();
populate(current->link, Arg...);
};
// Base case of parametric recursion for arg population.
template <typename T>
void arg::populate(stackLink *current, T par) {
current->test = "append";
current->item = par;
current->hasItem = true;
checkRule(current, par);
size++;
};
#endif | true |
199f72ed39255f09c24008dfe425427c80953e7c | C++ | vedantpople4/problem_solving_cpp | /1528.cpp | UTF-8 | 242 | 2.609375 | 3 | [] | no_license | class Solution {
public:
string restoreString(string s, vector<int>& indices) {
string retStr = s;
for(int i = 0; i < indices.size(); i ++){
retStr[indices[i]] = s[i];
}
return retStr;
}
};
| true |
c41b1e8822bcb0273e14c6c399c9756bed8eb293 | C++ | rbjoshi1309/tf_idf | /main.cpp | UTF-8 | 6,060 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
long long number_of_files(vector<string> &file_name_list, string file_name)
{
long long count = 0;
string temp;
ifstream no_of_files("./data/" + file_name);
while (no_of_files >> temp)
{
file_name_list.push_back(temp);
++count;
}
no_of_files.close();
return count;
}
double idf_word(string word, vector<vector<string>> words_in_each_file, long long total_no_of_files)
{
long long documents_with_word = 0;
for (long long i = 0; i < total_no_of_files; ++i)
{
if (binary_search(words_in_each_file[i].begin(), words_in_each_file[i].end(), word) == true)
++documents_with_word;
}
if (documents_with_word == 0)
return 1;
else
return 1 + log(double(total_no_of_files) / double(documents_with_word));
}
void processing_input_documents(vector<map<string, double>> &normalized_tf_documents, vector<vector<string>> &words_in_each_file, set<string> &total_unique_words, string file_name)
{
string files;
long long current_file = 0;
ifstream file_with_names("./data/" + file_name);
while (file_with_names >> files)
{
vector<string> words_in_current_file;
map<string, double> current_file_words;
string words;
long long total_words_in_file = 0;
ifstream each_file("./data/" + files);
while (each_file >> words)
{
current_file_words[words] += 1;
++total_words_in_file;
total_unique_words.insert(words);
words_in_current_file.push_back(words);
}
normalized_tf_documents.push_back(current_file_words);
map<string, double>:: iterator itr;
for (itr = normalized_tf_documents[current_file].begin(); itr != normalized_tf_documents[current_file].end(); ++itr)
{
double count = itr->second;
itr->second = count / double(total_words_in_file);
}
sort(words_in_current_file.begin(), words_in_current_file.end());
words_in_each_file.push_back(words_in_current_file);
each_file.close();
++current_file;
}
file_with_names.close();
}
vector<vector<double>> tf_idf_doc(vector<map<string, double>> normalized_tf_documents, map<string, double> idf, vector<string> given_words, long long total_no_of_files)
{
long long total_given_words = given_words.size();
vector<vector<double>> tf_idf_documents(total_given_words, vector<double>(total_no_of_files, 0));
for (long long i = 0; i < total_given_words; ++i)
{
string current_word_from_input = given_words[i];
for (long long j = 0; j < total_no_of_files; ++j)
tf_idf_documents[i][j] = normalized_tf_documents[j][current_word_from_input] * idf[current_word_from_input];
}
return tf_idf_documents;
}
vector<double> cosine_similarity(vector<vector<double>> tf_idf_documents, vector<double> tf_idf_input, long long total_no_of_files, long long total_given_words)
{
vector<double> final_scores(total_no_of_files, 0);
for (long long i = 0; i < total_no_of_files; ++i)
{
double magnitude_document = 0, magnitude_query = 0;
for (long long j = 0; j < total_given_words; ++j)
{
final_scores[i] += (tf_idf_documents[j][i] * tf_idf_input[j]);
magnitude_document += (tf_idf_documents[j][i] * tf_idf_documents[j][i]);
magnitude_query += (tf_idf_input[j] * tf_idf_input[j]);
}
if (magnitude_document != 0)
final_scores[i] = final_scores[i] / (sqrt(magnitude_document) * sqrt(magnitude_query));
}
return final_scores;
}
int main(int argc, char* argv[])
{
if (argc == 1)
cout << "Please Enter Filename and Query" << endl;
else if (argc == 2)
cout << "Please Enter Query" << endl;
else
{
vector<string> given_words;
for (long long i = 2; i < argc; ++i)
given_words.push_back(argv[i]);
long long total_given_words = argc - 2;
string file_name = argv[1];
vector<string> file_name_list;
long long total_no_of_files = number_of_files(file_name_list, file_name);
vector<map<string, double>> normalized_tf_documents;
vector<vector<string>> words_in_each_file;
set<string> total_unique_words;
processing_input_documents(normalized_tf_documents, words_in_each_file, total_unique_words, file_name);
map<string, double> inverse_document_frequency;
for (auto i : total_unique_words)
inverse_document_frequency[i] = idf_word(i, words_in_each_file, total_no_of_files);
vector<vector<double>> tf_idf_documents = tf_idf_doc(normalized_tf_documents, inverse_document_frequency, given_words, total_no_of_files);
map<string, double> tf_input;
for (long long i = 0; i < total_given_words; ++i)
tf_input[given_words[i]] += 1;
map<string, double> normalized_tf_input;
map<string, double>:: iterator input_words;
for (input_words = tf_input.begin(); input_words != tf_input.end(); ++input_words)
normalized_tf_input[input_words->first] = input_words->second / double(total_given_words);
vector<double> tf_idf_input(total_given_words);
for (long long i = 0; i < total_given_words; ++i)
{
string current_word_from_input = given_words[i];
tf_idf_input[i] = normalized_tf_input[current_word_from_input] * inverse_document_frequency[current_word_from_input];
}
vector<double> final_scores = cosine_similarity(tf_idf_documents, tf_idf_input, total_no_of_files, total_given_words);
double max_value = *max_element(final_scores.begin(), final_scores.end());
cout << "Relevant Documents : " << endl;
for (long long i = 0; i < total_no_of_files; ++i)
{
if (float(final_scores[i]) == float(max_value))
cout << file_name_list[i] << endl;
}
}
return 0;
}
| true |
9a3f286e8f2802dc91619d8fd58df399a1d7bf6e | C++ | SunTalk/CPP-Reference | /HW01/Gernic_Programming/rand.h | UTF-8 | 577 | 3.0625 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<ctime>
#include<fstream>
#include<cstdlib>
void init_randseed(){
srand(time(NULL));
}
int rand_Ascii(int left, int right){
return left + (rand() % (right - left) + 1);
}
std::string rand_string(int len){
std::string tmp;
for(int i = 0 ; i < len ; i++)
tmp += char(rand_Ascii(32, 126));
return tmp;
}
void gen_to_file(std::string fileName, int size, int len){
std::ofstream fout(fileName);
for(int i = 0 ; i < size ; i++)
fout << rand_string(len) << std::endl;
} | true |
0147f0f00224e912c9c081b681edd27ec8346009 | C++ | poweihuang17/practice_leetcode_and_interview | /Leetcode/Greedy/714_Best_Time_to_Buy_and_Sell_Stock_with_Transaction.cpp | UTF-8 | 386 | 2.65625 | 3 | [] | no_license | class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
vector<int> own(prices.size()+1,-50001);
vector<int> sell(prices.size()+1,0);
for(int i=1;i<=prices.size();i++)
{
own[i]=max(sell[i-1]-prices[i-1],own[i-1]);
sell[i]=max(own[i-1]+prices[i-1]-fee,sell[i-1]);
}
return sell[prices.size()];
}
}; | true |
913b0a83be65a2f36eab93b5d65203ba8b438f17 | C++ | wynnliam/an_engine_of_ice_and_fire | /src/GameStateHandler.cpp | UTF-8 | 2,261 | 2.625 | 3 | [] | no_license | //Liam "AFishyFez" Wynn, 6/17/2015, A Clash of Colors
#include "GameStateHandler.h"
#include "GameStates/GameState.h"
//States
#include "GameStates/StateIntro.h"
#include "GameStates/StateMainMenu.h"
#include "GameStates/StateTopDown.h"
using namespace ACOC_GameState;
/*HANDLER IMPLEMENTATIONS*/
GameStateHandler::GameStateHandler()
{
states = new GameState*[NUM_GAME_STATES];
for(int i = 0; i < NUM_GAME_STATES; ++i)
states[i] = NULL;
dataHandler = new GameDataHandler;
states[STATE_INTRO] = new StateIntro;
states[STATE_MAIN_MENU] = new StateMainMenu;
states[STATE_IN_TOP_DOWN] = new StateTopDown;
currStateIndex = 0;
}
GameStateHandler::~GameStateHandler()
{
if(states)
{
for(int i = 0; i < NUM_GAME_STATES; ++i)
{
if(states[i])
{
delete states[i];
states[i] = NULL;
}
}
delete[] states;
states = NULL;
}
if(dataHandler)
{
delete dataHandler;
dataHandler = NULL;
}
}
//Loop through each item, if it is not NULL, then initialize it
void GameStateHandler::Initialize(SDL_Renderer* renderer)
{
if(!renderer || !states)
return;
dataHandler = new GameDataHandler(renderer);
dataHandler->LoadDrawComponents();
dataHandler->LoadAudioComponents();
for(int i = 0; i < NUM_GAME_STATES; ++i)
{
if(states[i])
{
states[i]->SetGameDataHandler(dataHandler);
states[i]->Initialize(renderer);
}
}
}
void GameStateHandler::ProcessInput(SDL_Event& e, bool& bQuit)
{
states[currStateIndex]->ProcessInput(e);
//After we process input, we can examine here if we should
//quit the game
CheckQuit(bQuit);
}
void GameStateHandler::CheckQuit(bool& bQuit)
{
//Only check if bQuit is false! If it was true
//then this state could change it, locking the
//user into the game forever!
if(!bQuit)
bQuit = states[currStateIndex]->ShouldQuit();
}
void GameStateHandler::Update(float deltaTime)
{
states[currStateIndex]->Update(this, deltaTime);
}
void GameStateHandler::Draw(SDL_Renderer* renderer)
{
states[currStateIndex]->Draw(renderer);
}
//First we make a new node. We set the data
//to toAdd, and next to head. Then we make the
//new node the new head
void GameStateHandler::SetCurrentState(int stateType)
{
if(stateType >= NUM_GAME_STATES)
return;
currStateIndex = stateType;
}
| true |
2a84bd9a3cfe209e38ac078751f25730c67a2433 | C++ | radii-dev/rpi3-self-driving-model-shuttle-bus | /Raspi backup/20190902/final/final.cpp | UTF-8 | 15,319 | 2.6875 | 3 | [
"MIT"
] | permissive | /* g++ final.cpp -o final `pkg-config --libs opencv` -larmadillo -lwiringPi */
#include <iostream>
#include <armadillo>
#include <string>
#include "opencv2/core/core.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <vector>
#include <fstream>
#include <math.h>
#include <ctime>
#include <errno.h>
#include <string.h>
#include <wiringPi.h>
#include <wiringSerial.h>
//add OpenCV and Armadillo namespaces
using namespace cv;
using namespace std;
using namespace arma;
// Functions for UART
void uart_ch(char ch)
{
int fd ;
if ((fd = serialOpen ("/dev/ttyAMA0", 9600)) < 0)
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno));
return;
}
serialPutchar(fd,ch);
serialClose(fd);
}
void uart_str(char *str)
{
while(*str) uart_ch(*str++);
}
class LineFinder {
private:
// original image
cv::Mat img;
// vector containing the end points
// of the detected lines
vector<Vec4i> lines;
// accumulator resolution parameters
double deltaRho;
double deltaTheta;
// minimum number of votes that a line
// 선으로 간주되기 전에 받아야 하는 투표 최소 개수 (threshold)
int minVote;
// 선의 최소 길이
double minLength;
// 선을 따라가는 최대 허용 간격(gap)
double maxGap;
public:
// Default accumulator resolution is 1 pixel by 1 degree
// no gap, no mimimum length
LineFinder() : deltaRho(1), deltaTheta(CV_PI/180), minVote(10), minLength(0.), maxGap(0.) {}
// Set the minimum number of votes
void setMinVote(int minv) {
minVote = minv;
}
// Set line length and gap
void setLineLengthAndGap(double length, double gap) {
minLength = length;
maxGap = gap;
}
// Apply probabilistic Hough Transform
vector<Vec4i> findLines(cv::Mat& binary) {
lines.clear();
HoughLinesP(binary, lines, deltaRho, deltaTheta, minVote, minLength, maxGap);
return lines;
}
// Draw the detected lines on an image
void drawDetectedLines(cv::Mat &image, Scalar color = Scalar(0, 0, 255)) {
// Draw the lines
vector<Vec4i>::const_iterator it2 = lines.begin();
while (it2 != lines.end()) {
if((*it2)[0] != (*it2)[2]) {
Point pt1((*it2)[0], (*it2)[1]);
Point pt2((*it2)[2], (*it2)[3]);
line(image, pt1, pt2, color, 2);
}
++it2;
}
}
//일관성 없는 방향 라인 제거
vector<Vec4i> removeLinesOfInconsistentOrientations(const cv::Mat &orientations, double percentage, double delta) {
vector<Vec4i>::iterator it = lines.begin();
// check all lines
while (it != lines.end()) {
// end points
int x1= (*it)[0];
int y1= (*it)[1];
int x2= (*it)[2];
int y2= (*it)[3];
// line orientation + 90o to get the parallel line
double ori1 = atan2(static_cast<double>(y1 - y2), static_cast<double>(x1 - x2)) + CV_PI / 2; // double 형으로 변환하는 함수를 호출!
if (ori1 > CV_PI) ori1 = ori1 - 2 * CV_PI;
double ori2 = atan2(static_cast<double>(y2 - y1), static_cast<double>(x2 - x1)) + CV_PI / 2;
if (ori2 > CV_PI) ori2 = ori2 - 2 * CV_PI;
// for all points on the line
LineIterator lit(orientations, Point(x1, y1), Point(x2, y2));
int i, count = 0;
for(i = 0, count = 0; i < lit.count; i++, ++lit) {
float ori = *(reinterpret_cast<float *>(*lit)); // lineiterate의 값들을 float형으로 인식해라!
// is line orientation similar to gradient orientation ?
if (min(fabs(ori - ori1), fabs(ori - ori2)) < delta) // fabs 부동소수점 숫자의 절대값 반환
count++;
}
double consistency = count / static_cast<double>(i); // 일관성
// set to zero lines of inconsistent orientation
if (consistency < percentage) {
(*it)[0] = (*it)[1] = (*it)[2] = (*it)[3] = 0;
}
++it;
}
return lines;
}
};
class EdgeDetector {
private:
// original image
cv::Mat img;
// 16-bit signed int image
cv::Mat sobel;
// Aperture size of the Sobel kernel
int aperture; // 조리개??
// Sobel magnitude
cv::Mat sobelMagnitude;
// Sobel orientation
cv::Mat sobelOrientation;
public:
EdgeDetector() : aperture(3) {}
// Compute the Sobel
void computeSobel(const cv::Mat& image) {
cv::Mat sobelX;
cv::Mat sobelY;
// Compute Sobel
Sobel(image, sobelX, CV_32F, 1, 0, aperture);
Sobel(image, sobelY, CV_32F, 0, 1, aperture);
// Compute magnitude and orientation
cartToPolar(sobelX, sobelY, sobelMagnitude, sobelOrientation);
}
// Get Sobel orientation
cv::Mat getOrientation() {
return sobelOrientation;
}
};
class vanishingPt {
public:
cv::Mat image;
cv::Mat frame;
vector< vector<int> > points;
mat A, b, prevRes;
mat Atemp, btemp, res, aug, error, soln;
// store minimum length for lines to be considered while estimating vanishing point
// define minimum length requirement for any line
int minlength = image.cols * image.cols * 0.001;
// temporary vector for intermediate storage
vector<int> temp;
// store (x1, y1) and (x2, y2) endpoints for each line segment
vector<cv::Vec4i> lines_std;
// to store intermediate errors
double temperr;
// constructor to set video/webcam and find vanishing point
vanishingPt() {}
void init() {
for(int i = 0; i < lines_std.size(); i++) {
// ignore if almost vertical
if (abs(lines_std[i][0] - lines_std[i][2]) < 10 || abs(lines_std[i][1] - lines_std[i][3]) < 10) // check if almost vertical
continue;
// ignore shorter lines (x1-x2)^2 + (y2-y1)^2 < minlength
if (((lines_std[i][0] - lines_std[i][2]) * (lines_std[i][0] - lines_std[i][2]) + (lines_std[i][1] - lines_std[i][3]) * (lines_std[i][1] - lines_std[i][3])) < minlength)
continue;
/*
// ignore (0, x)
double slope = abs(lines_std[i][1] - lines_std[i][3]) / abs(lines_std[i][0] - lines_std[i][2]);
if(slope < 0.001) continue;
*/
// store valid lines' endpoints for calculations
for(int j = 0; j < 4; j++) {
temp.push_back(lines_std[i][j]);
}
points.push_back(temp);
temp.clear();
}
cout << "Detected:" << lines_std.size() << endl;
cout << "Filtered:" << points.size() << endl;
}
void makeLines() {
// to solve Ax = b for x
A = zeros<mat>(points.size(), 2);
b = zeros<mat>(points.size(), 1);
// convert given end-points of line segment into a*x + b*y = c format for calculations
// do for each line segment detected
for(int i = 0; i < points.size(); i++) {
A(i, 0) = -(points[i][3] - points[i][1]); // -(y2-y1)
A(i, 1) = (points[i][2] - points[i][0]); // x2-x1
b(i, 0) = A(i, 0) * points[i][0] + A(i, 1) * points[i][1]; // -(y2-y1)*x1 + (x2-x1)*y1 = x2*y1 - x1*y2
}
}
// estimate the vanishing point
void eval() {
// stores the estimated co-ordinates of the vanishing point with respect to the image
soln = zeros<mat>(2, 1);
// theta
int theta = 0;
double delta = 0.0;
// buffer for UART
char buffer;
// initialize error
double err = 9999999999;
// calculate point of intersection of every pair of lines and
// find the sum of distance from all other lines
// select the point which has the minimum sum of distance
for(int i = 0; i < points.size(); i++) {
for(int j = 0; j < points.size(); j++) {
if(i >= j)
continue;
// armadillo vector
uvec indices;
// store indices of lines to be used for calculation
indices << i << j;
// extract the rows with indices specified in uvec indices
// stores the ith and jth row of matrices A and b into Atemp and btemp respectively
// hence creating a 2x2 matrix for calculating point of intersection
Atemp = A.rows(indices);
btemp = b.rows(indices);
// if lines are parallel then skip
if(arma::rank(Atemp) != 2)
continue;
// solves for 'x' in A*x = b
res = calc(Atemp, btemp);
if(res.n_rows == 0 || res.n_cols == 0)
continue;
// calculate error assuming perfect intersection is
error = A * res - b;
// reduce size of error
error = error / 1000;
// to store intermediate error values
temperr = 0;
// summation of errors
for(int i = 0; i < error.n_rows; i++)
temperr += (error(i, 0) * error(i, 0)) / 1000;
// scale errors to prevent any overflows
temperr /= 1000000;
// if current error is smaller than previous min error then update the solution (point)
if(err > temperr) {
soln = res;
err = temperr;
}
}
}
cout<<"\n\nResult:\n"<<soln(0,0)<<","<<soln(1,0)<<"\nError:"<<err<<"\n\n";
/*
// draw a circle to visualize the approximate vanishing point
if(soln(0, 0) > 0 && soln(0, 0) < image.cols && soln(1, 0) > 0 && soln(1, 0) < image.rows) {
cv::circle(frame, Point(soln(0, 0), soln(1, 0)), 15, cv::Scalar(0, 0, 255), 2);
Point start(240, 320);
Point end(soln(0, 0), soln(1, 0));
line(frame, start, end, cv::Scalar(0, 0, 255), 2);
theta = atan2(320 - soln(1, 0), soln(0, 0) - 240) * (180 / CV_PI);
cout << theta << endl;
// toDo: use previous frame's result to reduce calculations and stabilize the region of vanishing point
prevRes = soln;
}
else {
cv::circle(frame, Point(prevRes(0, 0), prevRes(1, 0)), 15, cv::Scalar(0, 0, 255), 2);
Point start(240, 320);
Point end(prevRes(0, 0), prevRes(1, 0));
line(frame, start, end, cv::Scalar(0, 0, 255), 2);
theta = atan2(320 - prevRes(1, 0), prevRes(0, 0) - 240) * (180 / CV_PI);
cout << theta << endl;
}
if(theta < 0) {
theta += 360;
}
if(theta > 120) theta = 120;
else if(theta < 90) theta = 90;
buffer = theta;
uart_ch(buffer);
cv::namedWindow("Line");
cv::imshow("Line", frame);
// flush the vector
points.clear();
*/
// draw a circle to visualize the approximate vanishing point
if(soln(0, 0) > 0 && soln(0, 0) < image.cols && soln(1, 0) > 0 && soln(1, 0) < image.rows) {
cv::circle(frame, Point(soln(0, 0), soln(1, 0)), 15, cv::Scalar(0, 0, 255), 2);
if(soln(0, 0) < 240) {
// 좌회전 연산
delta = ((240 - soln(0, 0)) / 240) * 120 * ((130 - soln(1, 0)) / 65);
}/*
else if(soln(0, 0) >= 230 && soln(0, 0) < 250) {
// 직진
delta = 0;
}*/
else if(soln(0, 0) >= 240) {
// 우회전 연산
delta = -((240 - soln(0, 0)) / 240) * 120 * ((130 - soln(1, 0)) / 65);
}
// toDo: use previous frame's result to reduce calculations and stabilize the region of vanishing point
prevRes = soln;
}
else {
cv::circle(frame, Point(prevRes(0, 0), prevRes(1, 0)), 15, cv::Scalar(0, 0, 255), 2);
if(prevRes(0, 0) < 240) {
// 좌회전 연산
delta = ((240 - prevRes(0, 0)) / 240) * 120 * ((130 - prevRes(1, 0)) / 65);
}/*
else if(prevRes(0, 0) >= 230 && prevRes(0, 0) < 250) {
// 직진
delta = 0;
}*/
else if(prevRes(0, 0) >= 240) {
// 우회전 연산
delta = -((240 - prevRes(0, 0)) / 240) * 120 * ((130 - prevRes(1, 0)) / 65);
}
}
buffer = (int)delta + 60;
cout << (int)buffer << endl;
uart_ch(buffer);
cv::namedWindow("Line");
cv::imshow("Line", frame);
// flush the vector
points.clear();
}
//function to calculate and return the intersection point
mat calc(mat A, mat b) {
mat x = zeros<mat>(2, 1);
solve(x, A, b);
return x;
}
};
int main()
{
// make object
vanishingPt vp;
// to calculate fps
clock_t begin, end;
// read from video file on disk
// to read from webcam initialize as: cap = VideoCapture(int device_id);
VideoCapture cap(0);
cv::Mat source;
if(cap.isOpened()) { // check if camera/ video stream is available
// get first frame to intialize the values
cap.read(vp.frame);
vp.image = cv::Mat(cv::Size(vp.frame.rows, vp.frame.cols), CV_8UC1, 0.0);
}
while(cap.isOpened()) { // check if camera/ video stream is available
cap >> source;
cv::resize(source, source, cv::Size(480, 320));
if(!cap.grab())
continue;
// to calculate fps
begin = clock();
cv::Mat ROI(source, Rect(0, 240, 480, 80));
cv::Mat tmp = ROI;
medianBlur(tmp, tmp, 5);
// Compute Sobel
EdgeDetector ed;
ed.computeSobel(tmp);
// Apply Canny algorithm
cv::Mat contours;
Canny(tmp, contours, 150, 200); // 125, 200
cv::namedWindow("contours");
imshow("contours", contours);
// Create LineFinder instance
LineFinder ld;
ld.setLineLengthAndGap(50, 20); // 50, 20
ld.setMinVote(60); // 60
// Detect lines
vector<Vec4i> li = ld.findLines(contours);
// remove inconsistent lines
// ld.removeLinesOfInconsistentOrientations(ed.getOrientation(), 0.4, 0.1); // 0.4 0.1
ld.drawDetectedLines(tmp);
for(int i = 0; i < li.size(); i++){
for(int j = 0; j < 4; j++){
if(j == 1 || j == 3) li[i][j] += 240;
// else if(j == 0 || j == 2) li[i][j] += 80;
cout << li[i][j] << " ";
}
cout << endl;
}
source.copyTo(tmp);
vp.lines_std = li;
// it's advised not to modify image stored in the buffer structure of the opencv.
vp.frame = tmp.clone();
cv::cvtColor(vp.frame, vp.image, cv::COLOR_BGR2GRAY);
// resize frame to 480x320
cv::resize(vp.image, vp.image, cv::Size(480, 320));
cv::resize(vp.frame, vp.frame, cv::Size(480, 320));
// equalize histogram
cv::equalizeHist(vp.image, vp.image);
// initialize the line segment matrix in format y = m*x + c
vp.init();
// draw lines on image and display
vp.makeLines();
// approximate vanishing point
vp.eval();
// to calculate fps
end = clock();
cout << "fps: " << 1 / (double(end - begin) / CLOCKS_PER_SEC) << endl;
// hit 'esc' to exit program
int k = cv::waitKey(1);
if (k == 27)
break;
}
cv::destroyAllWindows();
return 0;
}
| true |
f3dfbceef3c1c2f3ff321c488b43bf213359c46e | C++ | petrarce/alhorythms-cpp | /euler-project/problem_11/main.cpp | UTF-8 | 1,142 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include "lib_euler_project.h"
using namespace std;
int count_factors(vector<prime_factor_entire_t> & local_primes_db){
uint64_t sum1 = 0, sum2 = 0;
for (int i = 0; i < local_primes_db.size(); i++)
sum1 += local_primes_db[i].count;
for (int i = 0; i < local_primes_db.size() - 1; i++){
uint64_t sum3 = 0, mult1;
for (int j = i+1; j < local_primes_db.size(); j++)
sum3+=local_primes_db[j].count;
mult1=local_primes_db[0].count;
for (int k = 1; k < i; k++)
mult1*=local_primes_db[k].count;
sum2+=(i+1)*sum3*mult1;
}
return sum1+sum2+1;
}
int main(int argc, char** argv)
{
vector<prime_factor_entire_t> primes_db;
uint64_t max_factors = 0, count = 0;
uint64_t triangle = 28;
for (uint64_t i = 8; ; i++){
triangle += i;
cout << "triangle " << i << ":" << triangle << endl;
get_prime_factors(triangle, primes_db);
count = count_factors(primes_db);
cout << "divisors:" << count;
}
return 0;
} | true |
4ebe9b3ca5c4f877149245719d39983e81aec612 | C++ | barbararaquelperez/dev-C- | /PUNTERO 2.cpp | UTF-8 | 1,299 | 2.953125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>//printf
#include<stdlib.h>//malloc
#include<raquel_func.h>
#include<string.h>//strcpy
using namespace std;
//ORDENAMOS POR EL METODO DE LA BURBUJA
void puntero(){
int veces;
int cont;
char *palabras[4];
int longitud;
char *p_aux;
char aux[20];
for(veces=1;veces<4;veces++){
for(cont=0;cont<3;cont++){
strcpy(palabras[cont], palabras[cont+1]); //stream comparation
p_aux=palabras[cont];
palabras[cont]=palabras[cont+1];
palabras[cont+1]=p_aux;
}
}
}
int main(){
char *palabra[4];
int cont;
int longitud;
int veces;
char salir;
char *p_aux;
char aux[20];
//Leo cuatro palabras
for(cont=0; cont<4; cont++){
cout<< "palabra: ";
cin>> aux;
longitud=devuelve_longitud(aux);
palabra[cont]= (char *)malloc((longitud+1)*sizeof(char)); //reservar sitio //Conversion forzada se ve a transforamr en un puntero
strcpy(palabra [cont],aux); //destino, origen //pensada para que los dos parametros sean la posicion de memoria de las primera letra de cada una de las palabras
}
cout<< "\nLISTA DE PALABRAS\n";
for(cont=0;cont<4;cont++){
printf("%s\n", palabra[cont]);
}
cin >> salir;
}
| true |
77571bd2a2aa5d2b6264a81c90351b16be9f6c4e | C++ | saranshbht/codes-and-more-codes | /codeforces/1076/1076a.cpp | UTF-8 | 475 | 2.53125 | 3 | [
"MIT"
] | permissive | #include<bits/stdc++.h>
using namespace std;
#define endl "\n"
int main() {
ios_base :: sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
string s;
cin >> n >> s;
char maxm = CHAR_MIN;
for (int i = 0; i < n; i++) {
maxm = max(maxm , s[i]);
}
int i;
n--;
for (i = 0; i < n; i++) {
if (s[i] > s[i + 1]) {
break;
} else {
cout << s[i];
}
}
if (i != n) {
i++;
n++;
for (; i < n; i++) {
cout << s[i];
}
}
cout << endl;
return 0;
} | true |
671a542499caf5e4cee9b351892a9b1577ca8c5f | C++ | jss8649/IPCV | /imgs/ipcv/frequency_filtering/FrequencyFilter.cpp | UTF-8 | 2,961 | 2.890625 | 3 | [] | no_license | /** Implementation file for image filtering
*
* \file ipcv/spatial_filtering/Filter2D.cpp
* \author <your name> (<your e-mail address>)
* \date DD MMM YYYY
*/
#include "FrequencyFilter.h"
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include "imgs/ipcv/utils/Utils.h"
using namespace std;
namespace ipcv {
/** Correlates an image with the provided kernel
*
* \param[in] src source cv::Mat of CV_8UC3
* \param[out] dst destination cv::Mat of ddepth type
* \param[in] ddepth desired depth of the destination image
* \param[in] kernel convolution kernel (or rather a correlation
* kernel), a single-channel floating point matrix
* \param[in] anchor anchor of the kernel that indicates the relative
* position of a filtered point within the kernel;
* the anchor should lie within the kernel; default
* value (-1,-1) means that the anchor is at the
* kernel center
* \param[in] delta optional value added to the filtered pixels
* before storing them in dst
* \param[in] border_mode pixel extrapolation method
* \param[in] border_value value to use for constant border mode
*/
bool FrequencyFilter(const cv::Mat& src, cv::Mat& dst, const int ddepth, const FilterType filter_type, const int cutoffFrequency, const int order, const FilterShape filter_shape, const int delta){
cv::Mat filter;
filter = ipcv::Dist(src.rows, src.cols, true);
if (filter_shape == ipcv::FilterShape::IDEAL) {
cv::threshold(filter, filter, cutoffFrequency, 1, cv::THRESH_BINARY_INV);
if (filter_type == ipcv::FilterType::HIGHPASS) {
filter = 1-filter;
}
}
else if (filter_shape == ipcv::FilterShape::BUTTERWORTH){
filter /= cutoffFrequency;
cv::pow(filter, 2*order, filter);
filter += 1;
cv::sqrt(filter, filter);
cv::divide(1, filter, filter);
if (filter_type == ipcv::FilterType::HIGHPASS) {
double minVal, maxVal;
cv::minMaxLoc(filter, &minVal, &maxVal);
filter = maxVal-filter;
}
}
else if (filter_shape == ipcv::FilterShape::GAUSSIAN){
filter /= cutoffFrequency;
cv::pow(filter, 2*order, filter);
filter *= -0.5;
cv::exp(filter, filter);
if (filter_type == ipcv::FilterType::HIGHPASS) {
double minVal, maxVal;
cv::minMaxLoc(filter, &minVal, &maxVal);
filter = maxVal-filter;
}
}
cv::Mat freqSrc;
src.convertTo(freqSrc, CV_64F);
cv::dft(freqSrc, freqSrc);
cv::multiply(freqSrc, filter, freqSrc);
cv::dft(freqSrc, dst, cv::DFT_INVERSE + cv::DFT_SCALE);
dst.convertTo(dst, ddepth);
dst += delta;
return true;
}
}
| true |
4a3c5a8eca6c2516c8a632120fca912ade87f584 | C++ | cyj407/ACM-practice | /UVA-10420.cpp | UTF-8 | 835 | 3.171875 | 3 | [] | no_license | #include<cstdio>
#include<map>
#include<string>
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int main(){
int n;
while(scanf("%d\n",&n)!=EOF){
map<string,int> m;
map<string,int>::iterator it;
string str;
for(int i = 0;i<n;++i){
/* cut the string to nation */
getline(cin,str);
char *temp = new char [str.length()+1];
strcpy(temp,str.c_str());
char *nat = strtok(temp," ");
string data(nat);
/* insert to the map,and update the value */
pair<map<string,int>::iterator,bool>insert_pair;
insert_pair = m.insert(pair<string,int>(data,1));
if(insert_pair.second == false){
it = m.find(data);
(*it).second++;
}
}
/* print the map */
for(it = m.begin();it != m.end();++it){
cout << it->first << " " << it->second << endl;
}
}
return 0;
}
| true |
ff43968a9834f87563c41095f561f133ed85c359 | C++ | EShourav/lightojaccodes | /1225 - Palindromic Numbers (II).cpp | UTF-8 | 652 | 2.71875 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int n,i,numb,rem,temp;
scanf("%d",&n);
for(i=1; i<=n; i++)
{
int reverse=0;
scanf("%d",&numb);
temp=numb;
while(temp!=0)
{
rem=temp%10;
reverse=reverse*10+rem;
temp/=10;
}
if(reverse==numb)
{
printf("Case %d: Yes\n",i);
}
else
{
printf("Case %d: No\n",i);
}
}
return 0;
}
| true |
a7cb728aabfc01fb3ca670a514e8160055c9856e | C++ | gurudattapatil/Data-stuctures | /dsa/course 1/week1_programming_challenges/2_maximum_pairwise_product/max_pairwise_product.cpp | UTF-8 | 810 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
long long MaxPairwiseProduct(const std::vector<int>& numbers) {
int max_index1 = -1;
int max_index2 = -1;
int n = numbers.size();
for(int i=0;i<n;i++)
{
if((max_index1==-1)||(numbers[i]>numbers[max_index1]))
{
max_index1= i;
}
}
for(int j=0;j<n;j++)
{
if((j!=max_index1)&&((max_index2==-1)||(numbers[j]>numbers[max_index2])))
{
max_index2= j;
}
}
return((long long)(numbers[max_index1])*numbers[max_index2]);
}
int main() {
int n;
std::cin >> n;
std::vector<int> numbers(n);
for (int i = 0; i < n; ++i) {
std::cin >> numbers[i];
}
std::cout << MaxPairwiseProduct(numbers) << "\n";
return 0;
}
| true |
d38307fd238bb727966c871cd15aa8fa57754394 | C++ | OGStudio/lua-cross-platform-examples | /features/main/Example+application.nodePool.node.rotation.cpp | UTF-8 | 1,714 | 2.75 | 3 | [] | no_license | FEATURE main.h/Setup
this->setup_application_nodePool_node_rotation();
FEATURE main.h/Impl
private:
void setup_application_nodePool_node_rotation()
{
MAIN_EXAMPLE_REGISTER_ENVIRONMENT_CLIENT(
{
"application.nodePool.node.rotation"
},
this->process_application_nodePool_node_rotation
);
}
MAIN_EXAMPLE_ENVIRONMENT_FUNCTION(process_application_nodePool_node_rotation)
{
// Make sure there is at least one component.
if (values.size() < 1)
{
MAIN_EXAMPLE_LOG(
"ERROR Could not set value for key '%s' "
"because values' count is less than 1",
key.c_str()
);
return { };
}
auto nodeName = values[0];
auto node = this->app->nodePool->node(nodeName);
// Make sure node exists.
if (!node)
{
MAIN_EXAMPLE_LOG(
"ERROR Could not get or set rotation for node '%s' "
"because it does not exist",
nodeName.c_str()
);
return { };
}
// Set.
if (values.size() == 4)
{
osg::Vec3 rotation(
atof(values[1].c_str()),
atof(values[2].c_str()),
atof(values[3].c_str())
);
scene::setSimpleRotation(node, rotation);
}
// Get.
auto rotation = scene::simpleRotation(node);
return {
format::printfString("%f", rotation.x()),
format::printfString("%f", rotation.y()),
format::printfString("%f", rotation.z()),
};
}
| true |
1e9736efe26d5dcbbee0fc1fed21a22009d027c4 | C++ | gnosiop/fromPhone | /C++/Essential/Ios/rdstate(streamErrors).cpp | UTF-8 | 997 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <errno.h>
using namespace std;
char str[1024];
int main()
{
ifstream in("test.txt");
while(in){
in.getline(str,1024,' ');
if(str[0] == '\0') continue;
cout<<"\n::::"<<in.rdstate()<<":::"<<str;
if(in.rdstate() & ios::failbit) {
cout << "Formate error!\n";
return 0;
}
if(in.rdstate() & ios::badbit){
cout << "Fatal error!\n";
return 0;
}
}
//контроль ошибок на вводе - выводе:
//rdstate сравнивается с флагами ios
//goodbit = 0x00; // Нет ошибок
// eofbit = 0x01; // Достигнут конец файла
// failbit = 0x02; //Ошибка форматирования или преобразования
// badbit = 0x04; // Серьёзная ошибка, после которой пользоваться потоком невозможно
//hardfail = 0x08; // Неисправность оборудования
in.close();
return 0;
}
| true |
c331c2c4e20511a13112a13a864669b3174e15ad | C++ | 2002patryk/zamiana | /main.cpp | UTF-8 | 1,079 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
ifstream plik;
ofstream plik1;
string liczba1;
string liczba2;
string liczba3;
string liczba4;
plik.open("liczby.txt");
plik1.open("wyjscie.txt");
if( plik.good() == true )
{
plik>>liczba1;
plik>>liczba1;
cout <<liczba1<<endl;
plik>>liczba2;
plik>>liczba2;
cout <<liczba2<<endl;
plik>>liczba3;
plik>>liczba3;
cout <<liczba3<<endl;
plik>>liczba4;
plik>>liczba4;
cout <<liczba4<<endl<<endl;
string str1 = liczba1;
string str2 = liczba2;
string str3 = liczba3;
string str4 = liczba4;
int a = strtol(str1.c_str(), NULL, 2);
int b = strtol(str2.c_str(), NULL, 10);
int c = strtol(str3.c_str(), NULL, 16);
int d = strtol(str4.c_str(), NULL, 2);
cout <<a<<endl;
cout <<b<<endl;
cout <<c<<endl;
cout <<d;
plik1<<a<<endl;
plik1<<b<<endl;
plik1<<c<<endl;
plik1<<d<<endl;
plik.close();
plik1.close();
}
return 0;
}
| true |
cfbcad89a8c3776b097f0ce0f21c6defa9b4e9c8 | C++ | shrikadam/codeforces | /122a_luckydivision.cpp | UTF-8 | 314 | 2.953125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int l[] {4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744, 747, 774, 777};
int n;
cin >> n;
for(int i:l){
if(n%i==0){
cout << "YES" << endl;
return 0;
}
}
cout << "NO" << endl;
return 0;
} | true |
c8d42e30433d61a35fa5c044b178869c4092980b | C++ | apmfifty/outbrain-click-prediction | /00_reference_code/04_AlexeyNoskov_02th_code/prepare-leak.cpp | UTF-8 | 5,627 | 2.53125 | 3 | [] | no_license | #include "util/io.h"
#include "util/data.h"
std::vector<std::pair<std::string, std::string>> filesets {
std::make_pair("cache/clicks_cv1_train.csv.gz", "cache/leak_cv1_train.csv.gz"),
std::make_pair("cache/clicks_cv1_test.csv.gz", "cache/leak_cv1_test.csv.gz"),
std::make_pair("cache/clicks_cv2_train.csv.gz", "cache/leak_cv2_train.csv.gz"),
std::make_pair("cache/clicks_cv2_test.csv.gz", "cache/leak_cv2_test.csv.gz"),
std::make_pair("../input/clicks_train.csv.gz", "cache/leak_full_train.csv.gz"),
std::make_pair("../input/clicks_test.csv.gz", "cache/leak_full_test.csv.gz"),
};
struct event_info {
int uid;
int timestamp;
};
std::unordered_map<std::string, int> uuid_map;
std::unordered_map<std::pair<int, int>, std::vector<int>> doc_views_map;
std::unordered_map<int,int> documents_map;
std::pair<int, event_info> read_event_info(const std::vector<std::string> & row) {
auto id = stoi(row[0]);
auto uuid = row[1];
event_info res;
res.timestamp = stoi(row[3]);
auto it = uuid_map.find(uuid);
if (it == uuid_map.end()) {
res.uid = uuid_map.size();
uuid_map.insert(std::make_pair(uuid, res.uid));
} else {
res.uid = it->second;
}
return std::make_pair(id, res);
}
std::pair<int, int> read_ad_document(const std::vector<std::string> & row) {
int ad_document_id = stoi(row[1]);
if (documents_map.count(ad_document_id) == 0)
documents_map.insert(std::make_pair(ad_document_id, 0));
return std::make_pair(stoi(row[0]), ad_document_id);
}
int main() {
using namespace std;
cout << "Loading reference data..." << endl;
auto events = read_vector("cache/events.csv.gz", read_event_info, 23120127);
auto ad_documents = read_vector("../input/promoted_content.csv.gz", read_ad_document, 573099);
cout << "Loading click data..." << endl;
for (auto it = filesets.begin(); it != filesets.end(); ++ it) {
cout << " Loading " << it->first << "... ";
cout.flush();
clock_t begin = clock();
compressed_csv_file file(it->first);
for (int i = 0;; ++i) {
auto row = file.getrow();
if (row.empty())
break;
auto ev = events.at(stoi(row[0]));
auto document_id = ad_documents.at(stoi(row[1]));
doc_views_map[make_pair(document_id, ev.uid)] = std::vector<int>();
if (i > 0 && i % 5000000 == 0) {
cout << (i / 1000000) << "M... ";
cout.flush();
}
}
clock_t end = clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "done in " << elapsed << " seconds" << endl;
}
{
cout << "Processing leak data... ";
cout.flush();
clock_t begin = clock();
compressed_csv_file file("../input/page_views.csv.gz");
int found = 0;
for (int i = 0;; ++i) {
auto row = file.getrow();
if (row.empty())
break;
auto uuid = row[0];
auto document_id = stoi(row[1]);
// Register view
auto uid_it = uuid_map.find(uuid);
if (uid_it != uuid_map.end()) {
auto uid = uid_it->second;
auto dv_it = doc_views_map.find(make_pair(document_id, uid));
if (dv_it != doc_views_map.end()) {
dv_it->second.push_back(stoi(row[2]));
found ++;
}
}
// Register document view
auto doc_it = documents_map.find(document_id);
if (doc_it != documents_map.end()) {
doc_it->second ++;
}
if (i > 0 && i % 5000000 == 0) {
cout << (i / 1000000) << "M... ";
cout.flush();
}
}
clock_t end = clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "done in " << elapsed << " seconds, found " << found << " entries" << endl;
}
cout << "Generating leak features..." << endl;
for (auto it = filesets.begin(); it != filesets.end(); ++ it) {
cout << " Generating " << it->second << "... ";
cout.flush();
clock_t begin = clock();
compressed_csv_file file(it->first);
ofstream outfile(it->second, std::ios_base::out | std::ios_base::binary);
streamsize buffer_size = 1024*1024;
boost::iostreams::filtering_streambuf<boost::iostreams::output> buf;
buf.push(boost::iostreams::gzip_compressor(), buffer_size, buffer_size);
buf.push(outfile, buffer_size, buffer_size);
std::ostream out(&buf);
out << "viewed,not_viewed" << endl;
for (int i = 0;; ++i) {
auto row = file.getrow();
if (row.empty())
break;
auto ev = events.at(stoi(row[0]));
auto document_id = ad_documents.at(stoi(row[1]));
auto doc_view_times = doc_views_map.at(make_pair(document_id, ev.uid));
auto doc_views = documents_map.at(document_id);
out << doc_view_times.size() << ","
<< int(doc_view_times.size() == 0 && doc_views > 0) << endl;
if (i > 0 && i % 5000000 == 0) {
cout << (i / 1000000) << "M... ";
cout.flush();
}
}
clock_t end = clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
cout << "done in " << elapsed << " seconds" << endl;
}
cout << "Done." << endl;
}
| true |
df4d3ad6b65a1f3bce878e80de256a4d3a492df4 | C++ | enginBozkurt/perception_pipeline | /src/octreevoxelgrid.h | UTF-8 | 2,873 | 3.171875 | 3 | [
"BSD-2-Clause"
] | permissive | #pragma once
#include <pcl/point_types.h>
#include <pcl/octree/octree.h>
template<class PointT>
class OctreeCentroidContainer : public pcl::octree::OctreeContainerBase<int>
{
public:
/** \brief Class initialization. */
OctreeCentroidContainer() : point_counter_(0)
{
this->reset();
}
/** \brief Empty class deconstructor. */
virtual ~OctreeCentroidContainer()
{
}
/** \brief deep copy function */
virtual OctreeCentroidContainer *
deepCopy() const
{
return (new OctreeCentroidContainer(*this));
}
/** \brief Add new point to voxel.
* \param[in] new_point the new point to add
*/
void addPoint(const PointT& new_point)
{
++point_counter_;
pt_sum_.x += new_point.x;
pt_sum_.y += new_point.y;
pt_sum_.z += new_point.z;
}
/** \brief Calculate centroid of voxel.
* \param[out] centroid_arg the resultant centroid of the voxel
*/
void getCentroid(PointT& centroid_arg) const
{
if(point_counter_) {
float fc = static_cast<float>(point_counter_);
centroid_arg.x = pt_sum_.x / fc;
centroid_arg.y = pt_sum_.y / fc;
centroid_arg.z = pt_sum_.z / fc;
}
}
/** \brief Reset leaf container. */
void reset()
{
point_counter_ = 0;
pt_sum_.x = pt_sum_.y = pt_sum_.z = 0;
}
private:
unsigned int point_counter_;
PointT pt_sum_;
};
// Specializations for pcl::PointNormal where the normal is averaged, too
template<>
void OctreeCentroidContainer<pcl::PointNormal>::addPoint(const pcl::PointNormal& new_point)
{
++point_counter_;
pt_sum_.x += new_point.x;
pt_sum_.y += new_point.y;
pt_sum_.z += new_point.z;
pt_sum_.normal_x += new_point.normal_x;
pt_sum_.normal_y += new_point.normal_y;
pt_sum_.normal_z += new_point.normal_z;
}
template<>
void OctreeCentroidContainer<pcl::PointNormal>::getCentroid(pcl::PointNormal& centroid_arg) const
{
if(point_counter_) {
float fc = static_cast<float>(point_counter_);
centroid_arg.x = pt_sum_.x / fc;
centroid_arg.y = pt_sum_.y / fc;
centroid_arg.z = pt_sum_.z / fc;
centroid_arg.normal_x = pt_sum_.normal_x / fc;
centroid_arg.normal_y = pt_sum_.normal_y / fc;
centroid_arg.normal_z = pt_sum_.normal_z / fc;
}
}
template<>
void OctreeCentroidContainer<pcl::PointNormal>::reset()
{
point_counter_ = 0;
pt_sum_.x = pt_sum_.y = pt_sum_.z = 0;
pt_sum_.normal_x = pt_sum_.normal_y = pt_sum_.normal_z = 0;
}
template<class PointT>
class OctreeVoxelGrid : public pcl::octree::OctreePointCloudVoxelCentroid< PointT, OctreeCentroidContainer<PointT> >
{
public:
OctreeVoxelGrid(double resolution_arg)
: pcl::octree::OctreePointCloudVoxelCentroid< PointT, OctreeCentroidContainer<PointT> >(resolution_arg)
{
}
void filter(pcl::PointCloud<PointT>& cloud)
{
this->defineBoundingBox();
this->addPointsFromInputCloud();
size_t count = getVoxelCentroids(cloud.points);
cloud.width = count;
cloud.height = 1;
cloud.is_dense = false;
}
};
| true |
78db9e2fc17e7e293796adadf9c91120bfc17879 | C++ | Opal21/tic_tac_toe | /User.hpp | UTF-8 | 761 | 2.84375 | 3 | [] | no_license | #ifndef USER_HPP
#define USER_HPP
#include "Plane.hpp"
#include <iostream>
class User
{
protected:
char player_sign{};
public:
[[nodiscard]] virtual Move decide_move(const Plane& plane) const = 0;
[[nodiscard]] virtual int UserMode() const = 0;
[[nodiscard]] char get_player_sign() const;
};
class Player : public User
{
private:
public:
explicit Player(char player_sign);
[[nodiscard]] Move decide_move(const Plane& plane) const;
[[nodiscard]] int UserMode() const;
};
class Bot : public User
{
private:
[[nodiscard]] static int loss(const int& min, const int& max) ;
public:
explicit Bot(char player_sign);
[[nodiscard]] Move decide_move(const Plane& plane) const;
[[nodiscard]] int UserMode() const;
};
#endif | true |
7ba78e9762a6569012f4cfbf10ec8a2bec903d59 | C++ | saikiranpalimpati/AntColonySystem | /Graph/Graph/Colony.h | UTF-8 | 919 | 3.21875 | 3 | [] | no_license | /*colony class will take a graph and hold the individual ants.
It makes the ant to move around the graph and tour trough all the cities(or vertices)
on the graph using different algorithms.It initaialises the pheromone by calculating
m/cnn, where 'm' is number of ants and 'cnn' is the length of tour generated by
nearest-neighbour heuristic
*/
#pragma once
#include"Ant.h"
//header files
class Colony
{
Graph *Gph;
//graph variable
vector<Ant> Ants;
//vector to hold the ant objects
public:
//initilaising the graph in a colony
Colony(Graph&);
//initilaising the ants
void initialiseAnts(int,int);
//dispalying the ant attributes
void displayAnts();
//make ants tour around the graph by using nearest neighbour algorithm
double AnttourUsingNearestNeighbourAlgorithm(int);
//implement acs algorithm on graph
void implementingAcs();
//destructor
~Colony();
}; | true |
788edf297e1cd33ca59898372d8824dea51c1e4a | C++ | aprilandjan/learn-cpp-primer-plus | /src/chapter12/2_queue/use_queue.cpp | UTF-8 | 3,067 | 3.25 | 3 | [] | no_license | //
// Created by May on 2018/12/11.
//
#include <iostream>
#include <cstdlib> // provide rand
#include <ctime> // provide time
#include "use_queue.h"
#include "./Queue.h"
const int MINUTES_PER_HOUR = 60;
/**
* check should create a new customer or not
* @param x
* @return
*/
bool check_new_customer(double x) {
return (std::rand() * x / RAND_MAX) < 1;
}
void use_queue() {
using std::cout;
using std::endl;
using std::cin;
using namespace L12_2;
// std::time: get current second count from 1970.1.1
std::cout << std::time(nullptr) << "\n";
// 以当前秒数作为伪随机种子
std::srand(std::time(nullptr));
cout << "ICBC Teller\n";
cout << "Enter maximum size of queue:";
int qs;
cin >> qs;
Queue queue(qs);
cout << "Enter the number of simulation hours: ";
int hours;
cin >> hours;
long minutes = hours * MINUTES_PER_HOUR;
cout << "Enter the average number of customer per hour: ";
double customers_per_hour;
cin >> customers_per_hour;
// 平均每个人耗时多少分钟
double average_customer_time_spent = MINUTES_PER_HOUR / customers_per_hour;
Item temp;
int t = 0;
// 队列中正在等待的人的剩余等待时间
int remain_wait_time = 0;
// 因队列满了,被赶走的人
int num_leave = 0;
// 总共的加入队列的顾客
int num_queued = 0;
for (t = 0; t < minutes; t++) {
// 随机生成是否有新客户
cout << "====> minute=" << t << " <====\n";
if (check_new_customer(average_customer_time_spent)) {
cout << "new customer incoming!\n";
if (queue.is_full()) {
// 队列满了,该顾客只能走了
num_leave++;
cout << "Current queue(size=" << queue.get_size() << ") is full, had to go away...\n";
} else {
num_queued++;
temp.init(t);
queue.enqueue(temp);
cout << "Added to the queue(size=" << queue.get_size() << ")\n";
}
}
if (queue.is_empty()) {
cout << "no customer, rest...\n";
continue;
}
// 应该开始处理队列里的第一个人
if (remain_wait_time == 0) {
remain_wait_time = queue.first().get_process_time();
cout << "now begin to handle customer. current queue(size=" << queue.get_size() << "). it takes " << remain_wait_time << " minutes. \n";
}
// time pass...
remain_wait_time--;
cout << "Time pass..." << remain_wait_time << "\n";
// 如果队列非空,且队列中当前等待的人剩余等待时间已满,那么该 shift 了...
if (remain_wait_time <= 0) {
queue.dequeue(temp);
// 设置为下一个顾客的等待时间
// remain_wait_time = temp.get_process_time();
cout << "ok, successfully handled one customer. current queue(size=" << queue.get_size() << ")\n";
}
}
} | true |
80989a47117424a53a8473e24935e8a0d5abcabf | C++ | agoffer/secretary | /src/competitorCtrl.cpp | WINDOWS-1251 | 4,287 | 2.703125 | 3 | [] | no_license | //---------------------------------------------------------------------------
#pragma hdrstop
#include "competitorCtrl.h"
#include "competitorDM.h"
#include "utils.h"
void TCompetitor::extend(TPerson inPerson, TSkill inSkill, TRequest inRequest){
person = inPerson;
skill = inSkill;
request = inRequest;
//
extended = true;
}
TCompetitor::TCompetitor(
int inPersonId, int inSkillId,
int inRequestId, double inWeight){
//
requestId = inRequestId;
skillId = inSkillId;
personId = inPersonId;
weight = inWeight;
id = 0;
//
extended = false;
skill.setId(0);
person.setId(0);
request.setId(0);
}
TCompetitor::~TCompetitor(void){
}
bool TCompetitor::valid(AnsiString &errmess){
//
if(!personId){
//
errmess = " !";
return false;
}
//
if(!skillId){
errmess = " !";
return false;
}
//
if(weight < 10){
errmess = " !";
return false;
}
//
return true;
}
void TCompetitor::store(void){
dmCompetitorDAO->store(*this);
}
void TCompetitor::erase(void){
dmCompetitorDAO->erase(*this);
}
TCompetitor TCompetitor::getCurrent(void){
return dmCompetitorDAO->getCurrent();
}
void TCompetitor::makeCurrent(void){
return dmCompetitorDAO->makeCurrent(*this);
}
TCompetitor TCompetitor::getExtendedTableCurrent(void){
return dmCompetitorDAO->getExtendedTableCurrent();
}
void TCompetitor::makeExtendedTableCurrent(void){
return dmCompetitorDAO->makeExtendedTableCurrent(*this);
}
TList* TCompetitor::getAll(void){
return NULL;
}
TList* TCompetitor::getByRequestId(int requestId){
return dmCompetitorDAO->getByRequestId(requestId);
}
TList* TCompetitor::getByCompetitionId(int competitionId){
return dmCompetitorDAO->getByCompetitionId(competitionId);
}
TList* TCompetitor::getExtendedByCompetitionId(int competitionId){
return dmCompetitorDAO->getExtendedByCompetitionId(competitionId);
}
TList* TCompetitor::getExtendedUncategoryByCompetitionId(int competitionId, bool female){
return dmCompetitorDAO->getExtendedUncategoryByCompetitionId(competitionId, female);
}
TList* TCompetitor::getExtendedByRequestId(int requestId){
return dmCompetitorDAO->getExtendedByRequestId(requestId);
}
TList* TCompetitor::getExtendedByCategoryId(int categoryId){
return dmCompetitorDAO->getExtendedByCategoryId(categoryId);
}
void TCompetitor::getById(int id){
return dmCompetitorDAO->getById(id, *this);
}
void TCompetitor::setFightVersion(int *ids, int count){
dmCompetitorDAO->setFightVersion(id, ids, count);
}
TList* TCompetitor::getFightVersion(void){
return dmCompetitorDAO->getFightVersion(id);
}
TList* TCompetitor::getUncategoryFightVersion(void){
return dmCompetitorDAO->getUncategoryFightVersion(id);
}
TList* TCompetitor::getExtendedFightVersion(void){
return dmCompetitorDAO->getExtendedFightVersion(id);
}
void TCompetitor::eraseFightVersion(void){
dmCompetitorDAO->eraseFightVersion(id);
}
void TCompetitor::setRecordMoveCallback(CallbackFunction cbf){
dmCompetitorDAO->setScrollCallback(cbf);
}
void TCompetitor::loadResult(void){
result.getResults(id);
}
void TCompetitor::storeResult(void){
result.setResults(id);
}
void TCompetitor::loadResult(int categoryId){
result.getResults(id, categoryId);
}
void TCompetitor::storeResult(int categoryId){
result.setResults(id, categoryId);
}
//---------------------------------------------------------------------------
#pragma package(smart_init)
| true |
3aa217d7e8009527df9368028e7ffa799c124598 | C++ | Veterun/Interview-1 | /Leetcode/42.trappingRainWater/42.cpp | UTF-8 | 1,175 | 3.15625 | 3 | [] | no_license | https://leetcode.com/discuss/16171/sharing-my-simple-c-code-o-n-time-o-1-space
//we should do it in a cumulative way. We set 2 pointers from the two end.
//Meanwhile, we keep two value maxleft, maxright to maintain the max height of left and
//right respectively. In the process when we move the two pointers towards the center.
//if the height[l] <= height[r], we could fill the water in the left bin. So we compare the height[left] with the maxleft,
//if height[l] is greater. then we just updated the maxleft, else we fill the water.
int trap(vector<int>& height) {
int n=height.size();
int left=0,right=n - 1;
int res=0;
int maxleft=0,maxright=0;
while(left<=right)//< works too, because in the end the two pointers will meet in the highest place
{
if(height[left]<=height[right]){
if(height[left]>=maxleft)
maxleft=height[left];
else res+=maxleft-height[left];
left++;
}
else{
if(height[right]>=maxright)maxright=height[right];
else res+=maxright-height[right];
right--;
}
}
return res;
}
| true |
06daa7846549c693a3847e94379e2270dc56263a | C++ | HarryCha777/USACO-Solutions | /Train - Chapter 2/nocows.cpp | UTF-8 | 703 | 2.875 | 3 | [] | permissive | /*
ID: harrych2
PROG: nocows
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream in("nocows.in");
ofstream out("nocows.out");
int n, k; in >> n >> k;
int dpTable[110][220] = {}; for (int i = 1; i <= k; i++) dpTable[i][0] = dpTable[i][1] = 1; // must set dpTable[i][0] to 1 too!
for (int l = 1; l <= k; l++) // levels
for (int i = 1; i <= n; i += 2) // nodes
for (int j = 1; j < i; j += 2) // node indices
dpTable[l][i] = (dpTable[l][i] + dpTable[l - 1][j] * dpTable[l - 1][i - j - 1]) % 9901; // don't use +=
out << (dpTable[k][n] - dpTable[k - 1][n] + 9901) % 9901 << endl; // don't use abs...use + 9901
return 0;
} | true |
dd16dcb5bddc03a9644dfa55e0a44ae9e690636b | C++ | niwa/interoperable_land_water_models | /Examples/BMI/Lookup/src/lib/lookup.h | UTF-8 | 964 | 2.640625 | 3 | [] | no_license | #ifndef LOOKUP_LIB_H
#define LOOKUP_LIB_H
#include <string>
#include <variant>
#include <vector>
namespace lup {
struct Input {
std::string name;
std::variant<std::string, double, int> value;
};
class Lookup {
public:
static Lookup *Create(std::string filename);
static void Dispose(Lookup* lookup);
virtual ~Lookup() = 0;
virtual int count_inputs() = 0;
virtual int count_outputs() = 0;
virtual int get_var_index(const std::string&) = 0;
virtual int get_output_index(const std::string&) = 0;
virtual std::vector<std::string> get_input_names() = 0;
virtual std::vector<std::string> get_output_names() = 0;
virtual std::string get_var_type(std::string) = 0;
virtual std::string get_var_units(std::string) = 0;
virtual std::vector<double> get_values(std::vector<lup::Input> inputs) = 0;
};
}
#endif // LOOKUP_LIB_H
| true |
c75e236fce354ffc24d33800178f65196e91b968 | C++ | kwhitehouse/graspit_msgs | /src/grasp_msg.cpp | UTF-8 | 2,403 | 2.5625 | 3 | [] | no_license | /*
* grasp_msg.cpp
*
* Created on: Oct 12, 2010
* Author: hao
*/
#include "grasp_common/grasp_msg.h"
#include <sstream>
namespace grasp_common
{
GraspMsg::GraspMsg(const std::vector<double> &pre_grasp, const std::vector<double> &final_grasp, double epsilon, double volume)
{
epsilon_ = epsilon;
volume_ = volume;
pre_pos_.push_back(pre_grasp[0]/1000.0);
pre_pos_.push_back(pre_grasp[1]/1000.0);
pre_pos_.push_back(pre_grasp[2]/1000.0);
pre_quaternion_.push_back(pre_grasp[3]);
pre_quaternion_.push_back(pre_grasp[4]);
pre_quaternion_.push_back(pre_grasp[5]);
pre_quaternion_.push_back(pre_grasp[6]);
for(size_t i = 7; i < pre_grasp.size(); ++i)
{
pre_dofs_.push_back(pre_grasp[i]);
}
final_pos_.push_back(final_grasp[0]/1000.0);
final_pos_.push_back(final_grasp[1]/1000.0);
final_pos_.push_back(final_grasp[2]/1000.0);
final_quaternion_.push_back(final_grasp[3]);
final_quaternion_.push_back(final_grasp[4]);
final_quaternion_.push_back(final_grasp[5]); // added by soonhac @11/10/10
final_quaternion_.push_back(final_grasp[6]);
for(size_t i = 7; i < final_grasp.size(); ++i)
{
final_dofs_.push_back(final_grasp[i]);
}
}
GraspMsg::GraspMsg(const std::vector<double> & pre_dofs, const std::vector<double> & pre_pos,
const std::vector<double> & pre_quaternion, const std::vector<double> & final_dofs,
const std::vector<double> & final_pos, const std::vector<double> & final_quaternion,
double epsilon, double volume)
{
epsilon_ = epsilon;
volume_ = volume;
pre_dofs_ = pre_dofs;
pre_pos_ = pre_pos;
pre_quaternion_ = pre_quaternion;
final_dofs_ = final_dofs;
final_pos_ = final_pos;
final_quaternion_ = final_quaternion;
}
std::string GraspMsg::toMsg()
{
std::ostringstream msg;
msg << "[";
msg << epsilon_ << " ";
msg << volume_ << " ";
for(size_t i = 0; i < pre_pos_.size(); ++i)
{
msg << pre_pos_[i] << " ";
}
for(size_t i = 0; i < pre_quaternion_.size(); ++i)
{
msg << pre_quaternion_[i] << " ";
}
for(size_t i = 0; i < pre_dofs_.size(); ++i)
{
msg << pre_dofs_[i] << " ";
}
for(size_t i = 0; i < final_pos_.size(); ++i)
{
msg << final_pos_[i] << " ";
}
for(size_t i = 0; i < final_quaternion_.size(); ++i)
{
msg << final_quaternion_[i] << " ";
}
for(size_t i = 0; i < final_dofs_.size(); ++i)
{
msg << final_dofs_[i] << " ";
}
msg << "]";
return msg.str();
}
}//namespace grasp_common
| true |
bd947dfc6d8d16e5babef5abcbac99823cf78f3f | C++ | durba-s/dsa_assignment | /A2/J.AirTicket.cpp | UTF-8 | 2,072 | 3.15625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include<limits.h>
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int);
struct Graph {
int nov;
struct node** adjLists;
};
struct node * createNode(int v){
struct node * newnode=(struct node *)malloc(sizeof(struct node));
newnode->vertex=v;
newnode->next=NULL;
return newnode;
}
void addEdge(struct Graph* graph, int s, int d) {
struct node* newNode = createNode(d);
newNode->next = graph->adjLists[s];
graph->adjLists[s] = newNode;
newNode = createNode(s);
newNode->next = graph->adjLists[d];
graph->adjLists[d] = newNode;
}
void BFS(Graph* graph, int startVertex, int endVertex) {
if (startVertex == endVertex) {
printf("0");
return;
}
int visited[5001] = {0}, dist[5001] = {INT_MAX}, pred[5001] = {-1};
int q[5001], front = 0, rear = 0;
q[rear++] = startVertex;
visited[startVertex] = 1;
dist[startVertex] = 0;
while (front < rear) {
int v = q[front++];
front %= 5001;
for (node* u = graph->adjLists[v]; u != NULL; u = u->next) {
if (!visited[u->vertex]) {
visited[u->vertex] = 1;
dist[u->vertex] = dist[v] + 1;
pred[u->vertex] = v;
q[rear++] = u->vertex;
rear %= 5001;
if (u->vertex == endVertex) {
printf("%d", dist[u->vertex] * 100);
return;
}
}
}
}
printf("0");
}
int main() {
int n,m,s,t;
scanf("%d",&n);
scanf("%d",&m);
scanf("%d",&s);
scanf("%d",&t);
struct Graph* graph = (struct Graph *)malloc(sizeof(struct Graph));
graph->nov=n;
graph->adjLists = (struct node **)malloc(n*sizeof(struct node *));
for(int i=0;i<n;i++){
graph->adjLists[i]=NULL;
}
int v1,v2;
for(int k=0;k<m;k++){
scanf("%d",&v1);
scanf("%d",&v2);
addEdge(graph, v1, v2);
}
BFS(graph,s,t);
return 0;
}
| true |
690b4e3209e89702057a837d50e8c2ee197f8c6a | C++ | Juseong-Bang/algorithms | /13458.cpp | UTF-8 | 1,476 | 3.484375 | 3 | [] | no_license | /*
문제
총 N개의 시험장이 있고, 각각의 시험장마다 응시자들이 있다. i번 시험장에 있는 응시자의 수는 Ai명이다.
감독관은 총감독관과 부감독관으로 두 종류가 있다. 총감독관은 한 방에서 감시할 수 있는 응시자의 수가 B명이고, 부감독관은 한 방에서 감시할 수 있는 응시자의 수가 C명이다.
각각의 시험장에 총감독관은 오직 1명만 있어야 하고, 부감독관은 여러 명 있어도 된다.
각 시험장마다 응시생들을 모두 감시해야 한다. 이 때, 필요한 감독관 수의 최소값을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 시험장의 개수 N(1 ≤ N ≤ 1,000,000)이 주어진다.
둘째 줄에는 각 시험장에 있는 응시자의 수 Ai (1 ≤ Ai ≤ 1,000,000)가 주어진다.
셋째 줄에는 B와 C가 주어진다. (1 ≤ B, C ≤ 1,000,000)
출력
각 시험장마다 응시생을 모두 감독하기 위해 필요한 감독관의 최소 수를 출력한다.
11:25
*/
#include<iostream>
#include<cmath>
using namespace std;
int b,c,n;
long a=0;
long q[1000000];
int main (){
cin>>n;
for(int i=0;i<n;i++)
{
cin>>q[i];
}
cin>>b>>c;
long ret=0;
long i=0,j=0;
for(int k=0;k<n;k++)
{
i=q[k]-b;
if(i<=0){//만약 B가 학생수보다 크다면!!!!!!!!!
ret++;
continue;
}
j=i/c;
if(i%c>0)
ret=ret+2+j;
else
ret=ret+1+j;
}
cout<<ret;
return 0;
} | true |
b947a43dcb6f76dc9b13726907e30ec758a57f11 | C++ | siahuat0727/lab3 | /questionA.cpp | UTF-8 | 549 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
int main(){
ifstream inFile("file.in", ios::in);
if(!inFile){
cerr << "Failed opening" << endl;
exit(1);
}
int numberOfCow;
inFile >> numberOfCow;
vector<int>cow(numberOfCow);
for(int i=0; i<numberOfCow; ++i){
inFile >> cow.at(i);
}
sort(cow.begin(), cow.end());
int sum = 0;
for(int term = 1; term <= 5; ++term){
sum += cow.at(numberOfCow - term);
}
cout << sum << endl;
return 0;
}
| true |
0cd13caa39ec456381db35e4ccb4661017f935bf | C++ | jordsti/stigame | /StiGame/gui/TableRow.cpp | UTF-8 | 1,690 | 3.203125 | 3 | [
"MIT"
] | permissive | #include "TableRow.h"
namespace StiGame
{
namespace Gui
{
TableRow::TableRow()
{
valueObject = nullptr;
}
TableRow::~TableRow()
{
auto cit(cells.begin()), cend(cells.end());
for(;cit!=cend;++cit)
{
delete (*cit);
}
if(valueObject != nullptr)
{
delete valueObject;
}
}
ValueObject* TableRow::getValueObject(void)
{
return valueObject;
}
void TableRow::setValueObject(ValueObject *m_valueObject)
{
valueObject = m_valueObject;
}
void TableRow::addCell(TableCell *cell)
{
cells.push_back(cell);
}
TableCell* TableRow::getCell(int index)
{
return cells[index];
}
int TableRow::cellsCount(void)
{
return cells.size();
}
void TableRow::subscribeCells(CellValueChangedEventListener *listener)
{
auto cit(cells.begin()), cend(cells.end());
for(;cit!=cend;++cit)
{
TableCell *cell = (*cit);
cell->subscribe(listener);
}
}
void TableRow::setValue(int index, std::string m_value)
{
if(index < cells.size())
{
TableCell *cell = cells[index];
cell->setValue(m_value);
}
}
int TableRow::getCellIndex(TableCell *cell)
{
int i=0;
auto cit(cells.begin()), cend(cells.end());
for(;cit!=cend;++cit)
{
if((*cit) == cell)
{
return i;
}
i++;
}
return -1;
}
void TableRow::setForeground(Color *m_foreground)
{
auto cit(cells.begin()), cend(cells.end());
for(;cit!=cend;++cit)
{
(*cit)->setForeground(m_foreground);
}
}
void TableRow::setFont(Font *m_font)
{
auto cit(cells.begin()), cend(cells.end());
for(;cit!=cend;++cit)
{
(*cit)->setFont(m_font);
}
}
}
}
| true |
ffff7589f3293d37bd575db66152c93780911186 | C++ | ZephirDev/PocoJsonPath | /src/PocoJsonPath/Operators/MultOperator.hpp | UTF-8 | 1,439 | 2.59375 | 3 | [] | no_license | //
// Created by desrumaux on 13/10/2021.
//
#ifndef POCOJSONPATH_MULTOPERATOR_HPP
#define POCOJSONPATH_MULTOPERATOR_HPP
#include "AbstractOperator.hpp"
namespace PocoJsonPath {
namespace Operators {
class MultOperator : public AbstractOperator {
public:
/***
* Invoke an operator on number
*
* @param scope
* @param leftMember
* @param rightMember
*
* @return result
*/
virtual Poco::Dynamic::Var invokeStringMult(const JsonPathScope& scope, std::string& leftMember, double& rightMember) const;
/***
* Invoke an operator on number
*
* @param scope
* @param leftMember
* @param rightMember
*
* @return result
*/
virtual Poco::Dynamic::Var invokeNumber(const JsonPathScope& scope, double& leftMember, double& rightMember) const;
/***
* Invoke an operator
*
* @param scope
* @param leftMember
* @param rightMember
*
* @return result
*/
virtual Poco::Dynamic::Var invoke(const JsonPathScope& scope, Poco::Dynamic::Var& leftMember, Poco::Dynamic::Var& rightMember) const;
};
}
}
#endif //POCOJSONPATH_MULTOPERATOR_HPP
| true |
5c222112065da98f20cd3aae0742dd8f90048d6c | C++ | yerson001/ProgramacionCompetitiva | /Contest/C.cpp | UTF-8 | 325 | 2.515625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
long cont; cin>>cont;
while(cont--){
long a, b, n;
cin>>a>>b>>n;
long cnt(0);
while(a <= n && b <= n){
if(a < b){a += b;}
else{b += a;}
++cnt;
}
cout<<cnt;
}
return 0;
} | true |
456a9039cf0668ce5edd01842b894e5ade0f3edd | C++ | danielpmachado/PROG-FEUP-Parte2 | /Menus.cpp | ISO-8859-1 | 6,997 | 3.1875 | 3 | [] | no_license | #include "Menus.h"
/*
Funo que pede ao utilizar para inserir o nome da loja e dos ficheiros (clientes, produtos e transaoes)
e que verifica se os ficheiros de clientes, produtos e transaes abrem corretamente.
*/
bool infoInicial(string & loja, string & fichClientes, string & fichProdutos, string & fichTransacoes) {
cout << "\nIntroduza o nome da loja: ";
getline(cin, loja);
cout << "\nIntroduza o nome do ficheiro de clientes: ";
cin >> fichClientes;
cout << "\nIntroduza o nome do ficheiro de produtos: ";
cin >> fichProdutos;
cout << "\nIntroduza o nome do ficheiro de transacoes: ";
cin >> fichTransacoes;
ifstream clientes, produtos, transacoes;
clientes.open(fichClientes);
produtos.open(fichProdutos);
transacoes.open(fichTransacoes);
if (clientes.fail())
return false;
if (produtos.fail())
{
clientes.close();
return false;
}
if (transacoes.fail())
{
clientes.close();
produtos.close();
return false;
}
return true;
}
/******************************************
* Gestao de Clientes
******************************************/
unsigned short int menuGestaoClientes()
{
unsigned short int opcao;
clearScreen();
layout();
cout << TAB_BIG << "| MENU GESTAO CLIENTES |" << endl;
cout << endl;
cout << TAB << "| 1 | Listar clientes ordenados alfabeticamente\n" << endl;
cout << TAB << "| 2 | Ver informacao de um cliente\n" << endl;
cout << TAB << "| 3 | Editar cliente\n" << endl;
cout << TAB << "| 4 | Remover cliente\n" << endl;
cout << TAB << "| 5 | Adicionar cliente\n" << endl;
cout << TAB << "| 6 | Imprime todos os clientes\n" << endl;
cout << TAB << "| 7 | Voltar ao menu inicial" << endl << endl;
cout << TAB << "Opcao: ";
opcao = leUnsignedShortInt(1, 7);
if (opcao == 7)
return 0;
return opcao;
}
void opcoesGestaoClientes(VendeMaisMais & supermercado) {
unsigned int opcao;
string nome;
while ((opcao = menuGestaoClientes()))
switch (opcao) {
case 1:
clearScreen();
layout();
cout << endl << TAB_BIG << "| CLIENTES |\n\n";
supermercado.displayClientesABC();
cin.get();
break;
case 2:
clearScreen();
layout();
cout << endl << TAB_BIG << "| CLIENTE |\n\n";
supermercado.printSingleClient();
cin.get();
break;
case 3:
clearScreen();
layout();
cout << endl << TAB_BIG << "| EDITAR CLIENTE |\n\n";
supermercado.alterarCliente();
cin.get();
break;
case 4:
clearScreen();
layout();
cout << endl << TAB_BIG << "| REMOVER CLIENTE |\n\n";
supermercado.removerCliente();
cin.get();
break;
case 5:
clearScreen();
layout();
cout << endl << TAB_BIG << "| ADICIONAR CLIENTE |\n\n";
supermercado.criarCliente();
cin.get();
break;
case 6:
clearScreen();
layout();
cout << endl << TAB_BIG << "| TODOS OS CLIENTES |\n\n";
supermercado.printClients();
cin.get();
}
}
/******************************************
* Gestao de Transacoes
******************************************/
unsigned short int menuGestaoTransacoes() {
unsigned short int opcao;
clearScreen();
layout();
cout << TAB_BIG << "| MENU GESTAO TRANSACOES |" << endl;
cout << endl;
cout << TAB << "| 1 | Listar transacoes entre 2 datas\n" << endl;
cout << TAB << "| 2 | Listar transacoes de um cliente por ordem cronologica\n" << endl;
cout << TAB << "| 3 | Adicionar transacao\n" << endl;
cout << TAB << "| 4 | Ver transacoes de um cliente\n" << endl;
cout << TAB << "| 5 | Ver todas as transacoes\n" << endl;
cout << TAB << "| 6 | Ver transacoes de uma data\n" << endl;
cout << TAB << "| 7 | Voltar ao menu inicial" << endl << endl;
cout << TAB << "Opcao: ";
opcao = leUnsignedShortInt(1, 7);
if (opcao == 7)
return 0;
return opcao;
}
void opcoesGestaoTransacoes(VendeMaisMais & supermercado) {
unsigned int opcao;
while ((opcao = menuGestaoTransacoes()))
switch (opcao) {
case 1:
clearScreen();
layout();
cout << endl << TAB_BIG << "| TRANSACOES ENTRE 2 DATAS |\n\n";
supermercado.imprimeEntreDatas();
cin.get();
break;
case 2:
clearScreen();
layout();
cout << endl << TAB_BIG << "| TRANSACOES DE UM CLIENTE |\n\n";
supermercado.printCronologicamente();
cin.get();
break;
case 3:
clearScreen();
layout();
cout << endl << TAB_BIG << "| ADICIONAR TRANSACAO |\n\n";
supermercado.addTransaction();
cin.get();
break;
case 4:
clearScreen();
layout();
cout << endl << TAB_BIG << "| TRANSACOES DE UM CLIENTE |\n\n";
supermercado.printClientTransaction();
cin.get();
break;
case 5:
clearScreen();
layout();
cout << endl << TAB_BIG << "| TODAS TRANSACOES |\n\n";
supermercado.printTransactions();
cin.get();
break;
case 6:
clearScreen();
layout();
cout << endl << TAB_BIG << "| TRANSACOES DE UMA DATA |\n\n";
supermercado.imprimeDiaTrans();
cin.get();
break;
}
}
/******************************************
* Gestao de Recomendacoes
******************************************/
unsigned short int menuRecomendacao()
{
unsigned short int opcao;
clearScreen();
layout();
cout << TAB_BIG << "| MENU DE RECOMENDACAO |" << endl;
cout << endl;
cout << TAB << "| 1 | Visualizar Bottom 10\n" << endl;
cout << TAB << "| 2 | Publicidade\n" << endl;
cout << TAB << "| 3 | Voltar ao menu inicial" << endl << endl;
cout << TAB << "Opcao: ";
opcao = leUnsignedShortInt(1, 3);
if (opcao == 3)
return 0;
return opcao;
}
void opcoesRecomendacao(VendeMaisMais & supermercado) {
unsigned int opcao;
while ((opcao = menuRecomendacao()))
switch (opcao) {
case 1:
clearScreen();
layout();
cout << endl << TAB_BIG << "| BOTTOM 10 |\n\n";
supermercado.printBottom10();
cin.get();
break;
case 2:
cout << "Funcionalidade temporariamente indisponivel";
cin.get();
//publicidade
break;
}
}
/******************************************
* Menu Inicial
******************************************/
unsigned short int menuInicial() {
unsigned short int opcao;
clearScreen();
layout();
cout << TAB_BIG << "| MENU INICIAL |" << endl;
cout << endl;
cout << TAB << "| 1 | Gestao de clientes\n" << endl;
cout << TAB << "| 2 | Lista produto disponiveis\n" << endl;
cout << TAB << "| 3 | Gestao de transacoes\n" << endl;
cout << TAB << "| 4 | Recomendacoes\n" << endl;
cout << TAB << "| 5 | Sair do programa" << endl << endl;
cout << TAB << "Opcao: ";
opcao = leUnsignedShortInt(1, 5);
if (opcao == 5)
return 0;
return opcao;
}
void opcoesIniciais(VendeMaisMais & supermercado)
{
unsigned int opcao;
while ((opcao = menuInicial()))
switch (opcao) {
case 1: opcoesGestaoClientes(supermercado);
break;
case 2:
clearScreen();
layout();
cout << endl << TAB_BIG << "| PRODUTOS |\n\n";
supermercado.printProducts();
cin.get();
break;
case 3: opcoesGestaoTransacoes(supermercado);
break;
case 4: opcoesRecomendacao(supermercado);
break;
}
supermercado.saveChanges();
}
| true |
d7f906ce8ced480b127c8562e62ff563dd5b514d | C++ | SadSock/acm-template | /uva/UVa369.cpp | UTF-8 | 1,573 | 2.578125 | 3 | [] | no_license | #include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <fstream>
#include <iomanip>
#include <bitset>
#include <list>
#include <ctime>
#include <climits>
#include <array>
using std::cin;
using std::cout;;
using std::vector;
using std::map;
using std::stack;
using std::string;
using std::endl;
using std::array;
#define READ freopen("in.txt", "r", stdin)
#define WRITE freopen("fracdec.out", "w", stdout)
#define SYNCOFF std::ios_base::sync_with_stdio(false);
#define ESP 1e-5
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
template<class T> inline void AMin(T &a,T b){if(a>b)a=b;}
template<class T> inline void AMax(T &a,T b){if(a<b)a=b;}
template<class T> inline bool is_in_square(T x, T y,T minw, T minh, T maxw ,T maxh)
{
if(x >= minw && x < maxw && y >= minh && y < maxh)
return true;
else
return false;
}
array<array<int,110>,110> C;
int32_t main(int32_t argc,char* argv[])
{
for(int32_t i = 1 ; i <= 100 ; i++)
C[i][1] = C[i][i + 1] = 1;
for(int32_t j = 2 ; j <= 100 ; j++)
{
for(int32_t i = 2 ; i <= j+1 ; i++)
{
C[j][i] = C[j-1][i] + C[j-1][i-1];
}
}
int32_t n,m;
while(cin>>n>>m && !(n== 0 && m == 0) )
{
cout<<n<<" things taken "<<m<<" at a time is "<<C[n][m+1]<<" exactly."<<endl;
}
return 0;
}
| true |
144f7846c28c72a4683a4c33c78de72b10453ab3 | C++ | patilrajat/hackerrank | /cavity_map.cpp | UTF-8 | 906 | 3.15625 | 3 | [] | no_license | /*
Sample Input
4
1112
1912
1892
1234
Sample Output
1112
1X12 if left,right,upper,lower elements are less then replace with X(this is not for element on edge)
18X2
1234
Explanation
The two cells with the depth of 9 are not on the border and are surrounded on all sides by shallower cells.
Their values have been replaced by X.
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
char input[101][101];
cin >> n;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
cin >> input[i][j];
}
}
for(int i = 1; i < n-1; i++){
for(int j = 1; j < n-1; j++){
if(input[i][j] > input[i-1][j] && input[i][j] > input[i][j-1] &&
input[i][j] > input[i][j+1] && input[i][j] > input[i+1][j]){
input[i][j] = 'X';
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++)cout << input[i][j];
cout << endl;
}
return 0;
}
| true |
56a9c4ec65c49dd23730dbc7f897c327216b03b9 | C++ | dkStephanos/robotSymbol | /RobotSymbol/OGLReferenceFrame.h | UTF-8 | 1,140 | 2.78125 | 3 | [] | no_license | #pragma once
#ifndef OGL_REFERENCE_FRAME
#define OGL_REFERENCE_FRAME
#include "MathUtil.h"
#include <glm\glm.hpp>
#include <string>
using std::string;
#include <vector>
using std::vector;
class OGLReferenceFrame
{
public:
glm::mat4 orientation;
vector<Transform> transforms;
public:
OGLReferenceFrame();
virtual ~OGLReferenceFrame();
// Sets the position
void setPosition(const glm::vec3& position);
void setPosition(float x, float y, float z);
// Gets the position
glm::vec3 getPosition() { return glm::vec3(orientation[3]); }
void rotateZ(float degrees);
void rotateWorldZ(float degrees);
void rotateY(float degrees);
void rotateWorldY(float degrees);
void rotateX(float degrees);
void rotateWorldX(float degrees);
void move(const glm::vec3& direction, float speed);
void move(const glm::vec3& velocity);
void moveForward(float speed);
void moveBackward(float speed);
void translate(float dx, float dy, float dz);
void translateWorld(float dx, float dy, float dz);
void addTransform(const Transform& transform) {
this->transforms.push_back(transform);
}
void applyTransforms();
};
#endif
| true |
d201ec53dfe43981165d24dc0036c3bcc6f7e7c8 | C++ | shenfumin/tools | /source/protocol/usercontent.h | UTF-8 | 8,098 | 2.609375 | 3 | [] | no_license | #ifndef USERCONTENT_H
#define USERCONTENT_H
#include <QObject>
#include <QString>
#include <QDateTime>
#include <QTime>
#include <QDebug>
#include "../source/device/userdevice.h"
class UserContent : public QObject
{
Q_OBJECT
public:
enum Direction {Upper=0,Lower=1};
explicit UserContent(enum Direction dir,QObject *parent=0);
explicit UserContent(enum Direction dir,const QString &mn,const QString &pw,const QString &st,int version,QObject *parent=0);
~UserContent();
bool contentUnpack(const QString &content,int cn); //报文内容解包
QString contentPack(int cn); //报文内容打包
enum Direction direction() {return DeviceDir;}
int version() {return Version;} //标准版本获取
void setVersion(int version) {Version = version;} //标准版本设置
QString deviceMN() {return DeviceMN;} //设备唯一标识获取
void setDeviceMN(const QString &mn) {DeviceMN = mn;} //设备唯一标识设置
QString devicePW() {return DevicePW;} //设备密码获取
void setDevicePW(const QString &pw) {DevicePW = pw;} //设备密码设置
QString deviceST() {return DeviceST;} //系统类型获取
void setDeviceST(const QString &st) {DeviceST = st;} //系统类型设置
int request() {return Request;} //请求应答标志获取
void setRequest(int request) {Request = request;} //请求应答标志设置
int result() {return Result;} //执行结果标志获取
void setResult(int result) {Result = result;} //执行结果标志设置
void setOverTime(int time) {OverTime = time;} //超时时间设置
void setReCount(int count) {ReCount = count;} //重发次数设置
void setRealCycle(int cycle) {RealCycle = cycle;} //实时数据上报时间间隔设置
void setMinuteCycle(int cycle) {MinuteCycle = cycle;} //分钟数据上报时间间隔设置
void setPassword(const QString &password) {Password = password;} //数采仪密码设置
void setSystemTime(const QDateTime &time) {SystemTime = time;} //系统时间设置
void setStartTime(const QDateTime &time) {StartTime = time;} //历史数据请求起始时间设置
void setStopTime(const QDateTime &time) {StopTime = time;} //历史数据请求截止时间
void setDataTime(const QDateTime &time) {DataTime = time;} //设置上报数据时间
void setPowerOnTime(const QDateTime &time) {PowerOnTime = time;} //数采仪开机时间设置
void setAnalyzer(const QString &code) {Analyzer = code;} //在线监控(监测)仪器仪表编码设置
void setSamplingStart(const QTime &time) {SamplingBaseTime = time;} //采样基准时间设置
void setSamplingCycle(int cycle) {SamplingCycle = cycle;} //采样时间间隔设置
void setSamplingStopCycle(int cycle) {SamplingStopCycle = cycle;} //出样时间间隔设置
void setInfoCode(QString &code) {InfoCode = code;} //现场设备信息编码设置
void setInformation(QString &info) {Information = info;} //现场机信息设置
UserDevice* device() {return Device;} //获取关联数采仪
void setDevice(UserDevice *device) {Device = device;} //关联数采仪设置
private:
enum Direction DeviceDir; //设备类型,Upper表示上位机,Lower表示数采仪
UserDevice *Device; //数采仪
int Version; //标准版本
QString DeviceMN; //设备唯一标识
QString DevicePW; //设备密码
QString DeviceST; //系统类型
int Request; //请求应答标志
int Result; //执行结果标志
int OverTime; //超时时间
int ReCount; //重发次数
int RealCycle; //实时数据上报时间间隔
int MinuteCycle; //分钟数据上报时间间隔
QString Password; //数采仪密码
QDateTime SystemTime; //系统时间,用于时间校准
QDateTime StartTime; //历史数据请求起始时间
QDateTime StopTime; //历史数据请求截止时间
QDateTime DataTime; //上报数据时间
QDateTime PowerOnTime; //数采仪开机时间
QString Analyzer; //在线监控(监测)仪器仪表编码
QTime SamplingBaseTime; //采样基准时间
int SamplingCycle; //采样时间间隔
int SamplingStopCycle; //出样时间间隔
QString Identifier; //设备唯一标识
QString InfoCode; //现场设备信息编码
QString Information; //现场机信息
QString fieldExtract(const QString &content,const QString &field,bool *ok);
QDateTime datetimeExtract(const QString &datetime);
QTime timeExtract(const QString &time);
//请求应答解包/打包
bool requestRespondUnpack(const QString &content);
QString requestRespondPack();
//执行结果解包/打包
bool resultRespondUnpack(const QString &content);
QString resultRespondPack();
//数据内容为空的包解包打包
bool emptyContentUnpack(const QString &content);
QString emptyContentPack();
//超时时间及重发次数解包/打包
bool overTimeAndReCountSetUnpack(const QString &content);
QString overTimeAndReCountSetPack();
//数采仪时间校准解包/打包
bool timeSetAndQueryUnpack(const QString &content);
QString timeSetAndQueryPack();
bool timeCalibrationRespondUnpack(const QString &content);
QString timeCalibrationRespondPack();
//实时数据上报时间间隔解包/打包
bool realCycleSetAndQueryUnpack(const QString &content);
QString realCycleSetQndQueryPack();
//分钟数据上报时间间隔解包/打包
bool minCycleSetAndQueryUnpack(const QString &content);
QString minCycleSetAndQueryPack();
//数采仪密码修改解包/打包
bool passwordSetUnpack(const QString &content);
QString passwordSetPack();
//实时数据上报解包/打包
bool realDataUploadUnpack(const QString &content);
QString realDataUploadPack();
//分钟数据上报解包/打包
bool minuteDataUploadUnpack(const QString &content);
QString minuteDataUploadPack();
//小时数据上报解包/打包
bool hourDataUploadUnpack(const QString &content);
QString hourDataUploadPack();
//日数据上报解包/打包
bool dayDataUploadUnpack(const QString &content);
QString dayDataUploadPack();
//污染治理设施状态解包/打包
bool manageFacilityStatusUploadUnpack(const QString &content);
QString manageFacilityStatusUploadPack();
//污染治理日运行时间解包/打包
bool manageFacilityTimeUploadUnpack(const QString &content);
QString manageFacilityTimeUploadPack();
//历史数据请求解包/打包
bool historyRequestUnpack(const QString &content);
QString historyRequestPack();
//数采仪开机时间上报解包/打包
bool restartTimeUploadUnpack(const QString &content);
QString restartTimeUploadPack();
//在线监控(监测)仪器仪表控制指令解包/打包
bool analyzerRequestUnpack(const QString &content);
QString analyzerRequestPack();
//在线监控(监测)仪器仪表时间校准解包/打包
bool analyzerTimeCalibrationRequestUnpack(const QString &content);
QString analyzerTimeCalibrationRequestPack();
//在线监控(监测)仪器仪表采样时间间隔解包/打包
bool analyzerSamplingCycleUnpack(const QString &content);
QString analyzerSamplingCyclePack();
//在线监控(监测)仪器仪表出样时间间隔解包/打包
bool analyzerSamplingStopTimeRespondUnpack(const QString &content);
QString analyzerSamplingStopTimeRespondPack();
//在线监控(监测)仪器仪表设备唯一标识解包/打包
bool analyzerIdentifierUploadUnpack(const QString &content);
QString analyzerIdentifierUploadPack();
//现场机信息解包/打包
bool informationRequestUnpack(const QString &content);
QString informationRequestPack();
bool informationUploadUnpack(const QString &content);
QString informationUploadPack();
};
#endif // USERCONTENT_H
| true |
c0fb1c50c79a24abbceb2f501f4f2206e912dd8a | C++ | chenzhiqiang1/enjoy | /test6.cpp | GB18030 | 3,128 | 3.25 | 3 | [] | no_license | /*
Ŀ
ÿһͯ,JOBDUһЩСȥ¶ԺС,ˡHFΪJOBDUԪ,ȻҲһЩСϷ,иϷ:,СΧһȦȻ,ָһm,ñΪ1СѿʼÿκmǸСҪг,ȻƷѡ,ҲٻصȦ,һСѿʼ,1...m....ȥ....ֱʣһС,Բñ,õJOBDUġ̽ϡذ(Ŷ!!^_^),ĸСѻõƷأ
룺
жݡ
ÿһ,2n(0<=n<=1,000,000),m(1<=m<=1,000,000),n,mֱʾСѵ(1....n-1,n)HFָǸm()n=0,롣
Ӧÿ,õСѱš
룺
1 10
8 5
6 6
0
1
3
4
*/
#include<stdio.h>
typedef struct Node
{
int next; //һԪصı
int num; //ţ1ʼ
}Node;
Node arr[1000000];
int FindLastRemaining(int n,int m)
{
if(n<1 || m<1)
return 0;
int start = 1;
int current = start;
int pre = current;
while(start != arr[start].next)
{
//ҵɾԪغǰһԪ
int i;
for(i=0;i<m-1;i++)
{
pre = current;
current = arr[current].next;
}
//ɾԪأ½
arr[pre].next = arr[current].next;
start = arr[pre].next;
current = start;
}
return arr[start].num;
}
int main()
{
int n;
while(scanf("%d",&n) != EOF && n != 0)
{
int m;
scanf("%d",&m);
//ɻ
int i;
for(i=1;i<=n;i++)
{
arr[i].num = i;
if(i == n)
arr[i].next = 1;
else
arr[i].next = i+1;
}
printf("%d\n",FindLastRemaining(n,m));
}
return 0;
}
/**************************************************************
Problem: 1356
User: mmc_maodun
Language: C
Result: Accepted
Time:290 ms
Memory:912 kb
****************************************************************/
//#include<stdio.h>
//
//int LastRemaining(int n,int m)
//{
// if(n<1 || m<1)
// return 0;
//
// int last = 0;
// int i;
// for(i=2;i<=n;i++)
// last = (last + m)%i;
// return last;
//}
//
//int main()
//{
// int n;
// while(scanf("%d",&n) != EOF && n != 0)
// {
// int m;
// scanf("%d",&m);
// printf("%d\n",LastRemaining(n,m)+1);
// }
// return 0;
//}
| true |
45af88f48372c2ba3949e046003723cf5f6d8c8c | C++ | liux0229/settings | /tools/codes/rand.cpp | UTF-8 | 691 | 2.765625 | 3 | [] | no_license | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <mylib.h>
#define NUL '\0'
int
main(int argc, char **argv)
{
char *usage = "rand <lower> <upper> [n_num] [-n] (inclusive; -n : every number in a line)";
int lower, upper, n_num;
int i;
if ( argc < 3 ) {
printf("%s\n", usage);
exit(EXIT_FAILURE);
}
lower = atoi(argv[1]);
upper = atoi(argv[2]);
if ( argc >= 4 )
n_num = atoi(argv[3]);
else
n_num = 1;
bool nl = 0;
if ( argc >= 5 ) nl = 1;
Randomize();
for ( i = 0; i < n_num; i++ ) {
if ( ! nl && i ) printf(" ");
printf("%d", RandomInt(lower, upper));
if ( nl ) printf("\n");
}
if ( ! nl ) printf("\n");
return EXIT_SUCCESS;
}
| true |
a983b293f59311f361600c7a252abd707efdd1d7 | C++ | joel-perez/9515Algo2TP2 | /src/Terreno.h | UTF-8 | 1,757 | 2.875 | 3 | [] | no_license | #ifndef TERRENO_H_
#define TERRENO_H_
#include "Lista.h"
#include "Parcela.h"
#include "Dificultad.h"
#include "Constantes.h"
#include "Texto.h"
class Terreno {
private:
Lista<Parcela*>* parcelas;
Texto texto;
unsigned int tamanioColumnas;
unsigned int tamanioFilas;
unsigned int precio;
public:
/*
* PRE:
* POST: Crea un Terreno con 0 tamanioFilas y 0 tamanioColumnas.
*/
Terreno();
/*
* PRE: filas y columnas estas en el intervalos de [TERRENO_MIN_FILA_COLUMNA,
* TERRENO_MAX_FILA_COLUMNA].
* POST: Terreno de 'filas'x'columnas' con 'filas'*'columas' Parcelas
* vacias y sin cultivo.
*/
Terreno(unsigned int filas, unsigned int columnas);
/*
* PRE:
* POST: delvuelve el alto del terreno,
*/
unsigned int obtenerFilas();
/*
* POST: Devuelve la lista de parcelas que componen este terreno.
*/
Lista<Parcela*>* obtenerParcelas();
/*
* PRE:
* POST: devuelve el ancho del terreno.
*/
unsigned int obtenerColumnas();
/*
* PRE: fila y columna deben estar en el rango permitido.
* POST: devuelve la parcela dada una fila y una columna.
*/
Parcela* obtenerParcela(unsigned int fila, unsigned int columna);
/*
* PRE:Solicita al usuario que ingrese uno de los terrenos disponibles
* POST:
* y devuelve una referencia a ese terreno, si solo tiene un terreno
* devolvera ese terreno.
*/
Lista<Parcela*>* seleccionarTerreno(Lista<Terreno*>* terrenosJugadorActual);
/*
* POST: Devuelve el precio de este terreno.
*/
unsigned int obtenerPrecio();
/*
* POST: Deja asignado el precio de este terreno en base a la dificultad actual.
*/
void asignarPrecio(Dificultad dificultad);
~Terreno();
};
#endif
| true |
c45d08c026625fb9c555ab637892ff6f732169db | C++ | miodek/Thinking_in_cpp_1 | /examples_from_the_book/C14/Combined.cpp | UTF-8 | 620 | 2.90625 | 3 | [] | no_license | //: C14:Combined.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Dziedziczenie i kompozycja
class A {
int i;
public:
A(int ii) : i(ii) {}
~A() {}
void f() const {}
};
class B {
int i;
public:
B(int ii) : i(ii) {}
~B() {}
void f() const {}
};
class C : public B {
A a;
public:
C(int ii) : B(ii), a(ii) {}
~C() {} // Wywoluje ~A() i ~B()
void f() const { // Zmiana definicji
a.f();
B::f();
}
};
int main() {
C c(47);
} ///:~
| true |
9a8e9a31aec7abc24ae2747808e25afad8ec2840 | C++ | KN-2018-Praktikum/up-problems-groups-1-2 | /exercise-03/problem02.cpp | UTF-8 | 611 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main() {
char firstLetter, secondLetter, firstNum, secondNum;
char thirdNum, forthNum, thirdLetter, forthLetter;
cin >> firstLetter >> secondLetter >> firstNum >> secondNum;
cin >> thirdNum >> forthNum >> thirdLetter >> forthLetter;
int multiplication = (firstNum - 48) * (secondNum - 48) * (thirdNum - 48) * (forthNum - 48);
int sum = (firstLetter + secondLetter + thirdLetter + forthLetter) / 10;
if(multiplication == sum) {
cout << "Yes " << sum << endl;
} else {
cout << "No" << endl;
}
return 0;
}
| true |
0252516959324bb0e2cd0fdc93e25b10109a11b8 | C++ | toHelandback/CircularQueueArray | /Circular Queue Template.cpp | UTF-8 | 1,519 | 3.875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
template<class T>
class CircularQueue
{
private:
T *arr;
int size, front, rear, cap;
public:
CircularQueue(int size);
bool isEmpty();
bool isFull();
void Enqueue(T val);
void Dequeue(T &val);
T frontval();
T rearval();
};
template<class T>
CircularQueue<T>::CircularQueue(int size)
{
this->size = size;
arr = new T[size];
cap = front = rear = 0;
}
template<class T>
bool CircularQueue<T>::isEmpty()
{
if (cap == 0)
{
return true;
}
else
{
return false;
}
}
template<class T>
bool CircularQueue<T>::isFull()
{
if (cap == size)
{
return true;
}
else
{
return false;
}
}
template<class T>
void CircularQueue<T>::Enqueue(T val)
{
if (!isFull())
{
cap++;
arr[rear] = val;
rear++;
rear = rear % size;
}
else
{
return;
}
}
template<class T>
void CircularQueue<T>::Dequeue(T &val)
{
if (!isEmpty())
{
cap--;
val = arr[front];
front++;
front = front % size;
}
}
template<class T>
T CircularQueue<T>::frontval()
{
if (!isEmpty())
{
return arr[front];
}
else
{
return T();
}
}
template<class T>
T CircularQueue<T>::rearval()
{
if (!isEmpty())
{
return arr[rear - 1];
}
else
{
return T();
}
}
// Driver Program
int main()
{
CircularQueue<int> q(5);
q.Enqueue(10);
q.Enqueue(20);
int val = 0;
q.Dequeue(val);
cout << val << endl;
q.Dequeue(val);
cout << val << endl;
}
| true |
23700650aeecef6588e6ee594c499c023557a6bd | C++ | CLOBOT-Co-Ltd/rmf_traffic | /rmf_traffic/src/rmf_traffic/geometry/SimplePolygon.hpp | UTF-8 | 6,091 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2019 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef RMF_TRAFFIC__GEOMETRY__POLYGON_HPP
#define RMF_TRAFFIC__GEOMETRY__POLYGON_HPP
#include <rmf_traffic/geometry/Shape.hpp>
#include <Eigen/Geometry>
#include <array>
#include <exception>
#include <vector>
namespace rmf_traffic {
namespace geometry {
// TODO(MXG): This header has been moved out of the public API because our
// collision detection does not properly support it yet. This should be moved
// back to the public API once the support is available.
//==============================================================================
/// \brief The SimplePolygon class represent a simple polygon. A polygon is
/// "simple" if it never intersects itself. It is also expected to have at least
/// 3 vertices. The polygon is allowed to be convex or concave.
///
/// A simple polygon is also closed, but this class will automatically "close"
/// itself by assuming a connection between the last vertex and the first.
class SimplePolygon : public Shape
{
public:
/// \brief A simple struct to provide information about an edge on the
/// polygon, including the index and location of each vertex.
struct EdgeInfo
{
/// \brief The index of each vertex along this edge.
std::array<std::size_t, 2> indices;
/// \brief The location of each vertex on this edge.
std::array<Eigen::Vector2d, 2> points;
};
using IntersectingPair = std::array<EdgeInfo, 2>;
using Intersections = std::vector<IntersectingPair>;
/// \brief Construct this SimplePolygon with a set of points.
///
/// The set of points is expected to be a connected sequence of vertices. Each
/// edge of the polygon will be created by sequential pairs of these points.
///
/// Similarly, points inside the SimplePolygon shape will be stored in a
/// sequence based on how they are connected to each other.
///
/// The last point will be automatically connected to the first point to
/// ensure a closed polygon.
SimplePolygon(std::vector<Eigen::Vector2d> points);
// The typical copy constructor/assignment operator
SimplePolygon(const SimplePolygon& other);
SimplePolygon& operator=(const SimplePolygon& other);
/// \brief Compute any self-intersections that may exist in this SimplePolygon
/// due to the current arrangement of points. Note that if the SimplePolygon
/// has any self-intersections, an exception will be raised if it gets passed
/// to a scheduler.
Intersections get_self_intersections() const;
/// \brief Check whether or not the SimplePolygon has any self-intersections.
/// This will return faster than get_self_intersections() in the event that a
/// self-intersection exists.
bool has_self_intersections() const;
/// \brief Get an array of the current points.
std::vector<Eigen::Vector2d> get_points() const;
/// \brief Get the number of points currently in this polygon.
std::size_t get_num_points() const;
/// \brief Get a specific point of the polygon.
Eigen::Vector2d& get_point(std::size_t index);
/// \brief const-qualified version of get_point()
const Eigen::Vector2d& get_point(std::size_t index) const;
/// \brief Remove the point at index.
void remove_point(std::size_t index);
/// \brief Add a point to the end of the polygon sequence.
void add_point(const Eigen::Vector2d& p);
/// \brief Insert a point into the sequence at the specified index. All points
/// currently at the specified index and after will have their indices
/// incremented.
void insert_point(std::size_t index, const Eigen::Vector2d& p);
// Documentation inherited
FinalShape finalize() const final;
};
//==============================================================================
/// Equality operator for SimplePolygon objects.
///
/// \param[in] lhs
/// A const reference to the left-hand-side of the comparison.
///
/// \param[in] rhs
/// A const reference to the right-hand-side of the comparison.
bool operator==(
const SimplePolygon& lhs,
const SimplePolygon& rhs);
//==============================================================================
/// Non-equality operator for SimplePolygon objects.
///
/// \param[in] lhs
/// A const reference to the left-hand-side of the comparison.
///
/// \param[in] rhs
/// A const reference to the right-hand-side of the comparison.
bool operator!=(
const SimplePolygon& lhs,
const SimplePolygon& rhs);
//==============================================================================
/// \brief If an invalid simple polygon (a polygon having self-intersections or
/// having less than 3 vertices) is passed into a schedule, this exception will
/// be raised.
struct InvalidSimplePolygonException : public std::exception
{
/// \brief Constructor for an invalid Polygon that has self-intersections.
InvalidSimplePolygonException(
SimplePolygon::Intersections intersections,
std::size_t num_vertices);
/// \brief Constructor for an invalid Polygon that has too few vertices.
InvalidSimplePolygonException(std::size_t num_vertices);
const char* what() const noexcept final;
/// If the error was caused by intersecting pairs, this field will describe
/// which pairs were the problem.
const SimplePolygon::Intersections intersecting_pairs;
/// This field will point to the number of vertices that were present.
const std::size_t num_vertices;
const std::string _what;
};
} // namespace geometry
} // namespace rmf_traffic
#endif // RMF_TRAFFIC__GEOMETRY__POLYGON_HPP
| true |
3b053cce4d2bfafd35a3e5d9173c886c72e33692 | C++ | seanjkim/CS256 | /CargoShip.cpp | UTF-8 | 1,765 | 3.75 | 4 | [] | no_license | #include <stdio.h>
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
class Ship
{
protected:
string shipName;
string yearMade;
public:
Ship(string name, string year)
{
shipName = name;
yearMade = year;
}
string getShipName(){ return shipName;}
void setShipName(string name){shipName = name;}
string getYearMade(){return yearMade;}
void setYearMade(string year){yearMade = year;}
virtual void print()
{
cout << "Ship's name: " << shipName << endl;
cout << "Year made: " << yearMade << endl;
}
};
class CruiseShip : public Ship
{
int maxPassengers;
public:
CruiseShip(int p, string n, string y);
int getMaxPassengers(){return maxPassengers;}
void setMaxPassengers(int passengers){maxPassengers = passengers;}
void print()
{
cout << "Ship's name: " << getShipName() << endl;
cout << "Maximum number of passengers: " << maxPassengers << endl;
}
};
CruiseShip::CruiseShip(int passengers, string name, string year) : Ship(name, year)
{
maxPassengers = passengers;
shipName = name;
yearMade = year;
}
class CargoShip : public Ship
{
int cargoCapacity;
public:
CargoShip(int c, string n, string y);
int getCargoCapacity(){return cargoCapacity;}
void setCargoCapacity(int capacity){cargoCapacity = capacity;}
void print()
{
cout << "Ship's name: " << getShipName() << endl;
cout << "Cargo Capacity in tons: " << cargoCapacity << endl;
}
};
CargoShip::CargoShip(int capacity, string name, string year) : Ship(name, year)
{
cargoCapacity = capacity;
shipName = name;
yearMade = year;
}
int main()
{
Ship* array[3] = {new Ship("Baby", "1969"), new CruiseShip(500, "Kevin", "1958"), new CargoShip(5000, "Mom", "2011")};
for(int i = 0; i < 3; i++)
{
array[i]->print();
}
return 0;
}
| true |
6ea060d3bd033ffd9e8dba613d923fb2fb6a30e8 | C++ | martinspedro/lidar-interference-analysis | /src/multiple_lidar_interference_mitigation_bringup/include/multiple_lidar_interference_mitigation_bringup/datasets_info.hpp | UTF-8 | 15,585 | 3.21875 | 3 | [] | no_license | /**
* \file datasets_info.hpp
* \brief Set of constants and methods usefull to manage the datasets
*
*/
#ifndef DATASETS_INFO_H
#define DATASETS_INFO_H
#include <string>
/*!
* \namespace datasets_path
* \brief namespace for datasets manipulation
*/
namespace datasets_path
{
/*!
* \brief Get full path to the test scenario
* \param[in] test_scenario_name string indicating the test scenario codename
* \return the full path to the scenario
* \throws std::out_of_range if test scenario codename is invalid
*
* Given a test scenario code name, returns the full path for that test scenario root folder
*/
const std::string getTestScenarioFullPath(const std::string test_scenario_name);
/*!
* \brief Get full path to the test scenario dataset
* \param[in] dataset_name string indicating the dataset codename
* \return the full path to the dataset
* \throws std::out_of_range if dataset codename is invalid
*
* Given a test scenario dataset code name, returns the full path for that dataset root folder
*/
const std::string getTestScenarioDatasetFullPath(const std::string dataset_name);
/*!
* \brief Get full path to the output results folder
* \param[in] result_file_name string indicating the result file codename
* \return the full path to the specific output results folder
* \throws std::out_of_range if result file codename is invalid
*
* Given a result file codename, returns the full path for the specific output results folder
*/
const std::string getResultsFolderRelativePath(const std::string result_file_name);
/*!
* \brief Get full path to the output graphics folder
* \param[in] graphic_file_name string indicating the graphic file codename
* \return the full path to the specific output graphics folder
* \throws std::out_of_range if graphics folder codename is invalid
*
* Given a graphics folder codename, returns the full path for the specific output graphics folder
*/
const std::string getGraphicsFolderRelativePath(const std::string graphic_file_name);
/*!
* \brief Get full path to the test scenario specific file
* \param[in] test_scenario_name string indicating the test scenario codename
* \param[in] file_name desired file name or codename
* \return the full path to the desired file on the test scenario
* \throws std::out_of_range if test scenario codename is invalid
*
* Given a test scenario code name and a file codename/name, returns the full path for that test scenario
* file name/codename
*/
const std::string constructFullPathToTestScenario(const std::string test_scenario_name, const std::string file_name);
/*!
* \brief Get full path to the test scenario dataset specific file
* \param[in] dataset_name string indicating the dataset codename
* \param[in] file_name desired file name or codename
* \return the full path to the desired file on the dataset
* \throws std::out_of_range if dataset codename is invalid
*
* Given a test scenario dataset code name and a file codename/name, returns the full path for that dataset file
* name/codename
*/
const std::string constructFullPathToDataset(const std::string dataset_name, const std::string file_name);
/*!
* \brief Get full path to the output results folder specific file
* \param[in] dataset_name string indicating the result file codename
* \param[in] results_name desired file name or codename of the result
* \return the full path to the specific output result file
* \throws std::out_of_range if result file codename is invalid
*
* Given a test scenario dataset code name and a file codename/name, returns the full path for that dataset file
* name/codename on the results folder
*/
const std::string constructFullPathToResults(const std::string dataset_name, const std::string results_name);
/*!
* \brief Get full path to the output graphics folder specific file
* \param[in] dataset_name string indicating the result file codename
* \param[in] graphic_name desired file name or codename of the graphic
* \return the full path to the specific output graphic file
* \throws std::out_of_range if result file codename is invalid
*
* Given a test scenario dataset code name and a file codename/name, returns the full path for that dataset file
* name/codename on the graphics folder
*/
const std::string constructFullPathToGraphics(const std::string dataset_name, const std::string graphic_name);
/*!
* \brief Creates and empty dir for the results output folder
* \param[in] dataset_name string indicating the result file codename
* \param[in] results_folder the name/codename of the folder to be created
* \return the full path to the specific output results folder
* \throws std::ios_base::failure if cannot create the folder
*
* Given a test scenario dataset code name and a folder codename/name, creates a empty folder wiht the name specified on
* results_folder on the dataset folder indicated by dataset_name, returning the full path to the folder
*
* \remark Folder permissions: user read, write and execute. Group read and write and others have tranverse permission
*
*/
const std::string makeResultsDirectory(const std::string dataset_name, const std::string results_folder);
/*!
* \brief Creates and empty dir for the graphics output folder
* \param[in] dataset_name string indicating the result file codename
* \param[in] graphics_folder the name/codename of the folder to be created
* \return the full path to the specific output graphic folder
* \throws std::ios_base::failure if cannot create the folder
*
* Given a test scenario dataset code name and a folder codename/name, creates a empty folder wiht the name specified on
* graphics_folder on the dataset folder indicated by dataset_name, returning the full path to the folder
*
* \remark Folder permissions: user read, write and execute. Group read and write and others have tranverse permission
*
*/
const std::string makeGraphicsDirectory(const std::string dataset_name, const std::string graphics_folder);
/*!
* \brief Prints all available datasets folder codename
*/
void printAvailableDatasetsCodenames(void);
extern const std::string DATASETS_FULL_PATH;
// Bosch related datasets
extern const std::string BOSCH_DATASETS_FULL_PATH;
extern const std::string BOSCH_TEST_DATASET_FULL_PATH;
extern const std::string BOSCH_TEST_DATASET_BAG;
extern const std::string BOSCH_INTERFERENCE_DATASET_FULL_PATH;
extern const std::string BOSCH_PANDAR40_INTERFERENCE_DATASET_BAG;
extern const std::string BOSCH_VLP16_INTERFERENCE_DATASET_BAG_1;
extern const std::string BOSCH_VLP16_INTERFERENCE_DATASET_BAG_2;
// Kitti related Datasets
extern const std::string KITTI_DATASETS_FULL_PATH;
extern const std::string KITTI_DATASETS_FULL_PATH_2011_09_26;
extern const std::string KITTI_DATASETS_FULL_PATH_2011_09_28;
extern const std::string KITTI_DATASETS_FULL_PATH_2011_09_29;
extern const std::string KITTI_DATASETS_FULL_PATH_2011_09_30;
extern const std::string KITTI_DATASETS_FULL_PATH_2011_10_03;
// Ouster related Datasets
extern const std::string OUSTER_DATASETS_FULL_PATH;
// Udacity related Datasets
extern const std::string UDACITY_DATASETS_FULL_PATH;
extern const std::string UDACITY_DATASETS_CH2_FULL_PATH;
extern const std::string UDACITY_DATASETS_CH2_001_FULL_PATH;
extern const std::string UDACITY_DATASETS_CH2_002_FULL_PATH;
extern const std::string UDACITY_CH2_002_HMB1_BAG;
extern const std::string UDACITY_CH2_002_HMB2_BAG;
extern const std::string UDACITY_CH2_002_HMB3_BAG;
extern const std::string UDACITY_CH2_002_HMB4_BAG;
extern const std::string UDACITY_CH2_002_HMB5_BAG;
extern const std::string UDACITY_CH2_002_HMB6_BAG;
extern const std::string UDACITY_DATASETS_CHX_FULL_PATH;
extern const std::string UDACITY_CHX_BAG;
extern const std::string UDACITY_CHX_CAMERA_AND_LIDAR_BAG;
extern const std::string UDACITY_CHX_CAMERA_BAG;
extern const std::string UDACITY_CHX_LIDAR_BAG;
// My datasets
extern const std::string EXPERIMENTAL_DATASETS_FULL_PATH;
extern const std::string ANECOIC_CHAMBER_DATASETS_FULL_PATH;
extern const std::string IT2_DARK_ROOM_DATASETS_FULL_PATH;
extern const std::string IT2_DARK_ROOM_SCENARIO_A1_DATASETS_FULL_PATH;
extern const std::string IT2_DARK_ROOM_SCENARIO_A2_DATASETS_FULL_PATH;
extern const std::string IT2_DARK_ROOM_SCENARIO_B1_DATASETS_FULL_PATH;
extern const std::string IT2_DARK_ROOM_SCENARIO_B1_CAMERA_CALIBRATION_FOLDER_FULL_PATH;
extern const std::string IT2_DARK_ROOM_SCENARIO_B1_GROUND_TRUTH_FOLDER_FULL_PATH;
extern const std::string IT2_DARK_ROOM_SCENARIO_B1_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_DATASETS_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_DATASETS_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_B_DATASETS_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_CAMERA_CALIBRATION_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_GROUND_TRUTH_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_DISTANCE_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_HEIGHT_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_HUMAN_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_LIDARS_LOS_OBSTACLE_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_A_ROTATION_FREQUENCY_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_B_CAMERA_CALIBRATION_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_B_GROUND_TRUTH_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_B_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMBADA_SCENARIO_B_DIRECTION_INTERFERENCE_FOLDER_FULL_PATH;
extern const std::string CAMERA_CALIBRATION_BAG_NAME;
extern const std::string GROUND_TRUTH_BAG_NAME;
extern const std::string GROUND_TRUTH_BEGINNING_BAG_NAME;
extern const std::string GROUND_TRUTH_FINAL_BAG_NAME;
extern const std::string GROUND_TRUTH_ROI_BAG_NAME;
extern const std::string INTERFERENCE_BAG_NAME;
extern const std::string INTERFERENCE_ROI_BAG_NAME;
extern const std::string RAW_BAG_NAME;
extern const std::string GROUND_TRUTH_MODEL_FOLDER_RELATIVE_PATH;
extern const std::string INTERFERENCE_ANALYSIS_FOLDER_RELATIVE_PATH;
extern const std::string GRAPHICS_FOLDER_RELATIVE_PATH;
extern const std::string ORGANIZED_GROUND_TRUTH_MODEL_PCD_NAME;
extern const std::string ICP_GROUND_TRUTH_MODEL_PCD_NAME;
extern const std::string ICP_UNVOXELIZED_GROUND_TRUTH_MODEL_PCD_NAME;
extern const std::string GROUND_TRUTH_ROI_MODEL_PCD_NAME;
extern const std::string GROUND_TRUTH_AZIMUTH_INTENSITY_BIN_NAME;
extern const std::string GROUND_TRUTH_LASER_INTENSITY_BIN_NAME;
extern const std::string GROUND_TRUTH_AVERAGE_POINT_DISTANCE_BIN_NAME;
extern const std::string GROUND_TRUTH_POINT_DISTANCE_VARIANCE_BIN_NAME;
extern const std::string GROUND_TRUTH_AVERAGE_POINT_INTENSITY_BIN_NAME;
extern const std::string GROUND_TRUTH_POINT_INTENSITY_VARIANCE_BIN_NAME;
extern const std::string GROUND_TRUTH_BAG_POINTS_DISTANCE_VECTOR_BIN_NAME;
extern const std::string GROUND_TRUTH_BAG_POINTS_INTENSITY_VECTOR_BIN_NAME;
extern const std::string ROI_GROUND_TRUTH_BAG_POINTS_DISTANCE_VECTOR_BIN_NAME;
extern const std::string INTERFERENCE_BAG_POINTS_DISTANCE_VECTOR_BIN_NAME;
extern const std::string ROI_INTERFERENCE_BAG_POINTS_DISTANCE_VECTOR_BIN_NAME;
extern const std::string INTERFERENCE_BAG_POINTS_INTENSITY_VECTOR_BIN_NAME;
extern const std::string INTERFERENCE_ANALYSIS_OCTREE_OCUPATION_BIN_NAME;
extern const std::string INTERFERENCE_BOX_FILTER_FILE_NAME;
extern const std::string INTERFERENCE_DISTANCE_VS_LOS_BOX_FILTER_BAR_FILE;
// Graphics
extern const std::string GROUND_TRUTH_AVERAGE_POINT_DISTANCE_HIST_FILE_NAME;
extern const std::string GROUND_TRUTH_AVERAGE_POINT_DISTANCE_COLOR_MESH_FILE_NAME;
extern const std::string GROUND_TRUTH_AVERAGE_POINT_INTENSITY_HIST_FILE_NAME;
extern const std::string GROUND_TRUTH_AVERAGE_POINT_INTENSITY_COLOR_MESH_FILE_NAME;
extern const std::string GROUND_TRUTH_POINT_DISTANCE_VARIANCE_HIST_FILE_NAME;
extern const std::string GROUND_TRUTH_POINT_DISTANCE_VARIANCE_COLOR_MESH_FILE_NAME;
extern const std::string GROUND_TRUTH_POINT_INTENSITY_VARIANCE_HIST_FILE_NAME;
extern const std::string GROUND_TRUTH_POINT_INTENSITY_VARIANCE_COLOR_MESH_FILE_NAME;
extern const std::string GROUND_TRUTH_AZIMUTH_INTENSITY_POLAR_FILE_NAME;
extern const std::string GROUND_TRUTH_LASER_INTENSITY_BAR_FILE_NAME;
extern const std::string GROUND_TRUTH_BAG_INTENSITY_HIST_FILE_NAME;
extern const std::string GROUND_TRUTH_BAG_DISTANCE_HIST_FILE_NAME;
extern const std::string INTERFERENCE_BAG_INTENSITY_HIST_FILE_NAME;
extern const std::string INTERFERENCE_BAG_DISTANCE_HIST_FILE_NAME;
extern const std::string INTERFERENCE_ANALYSIS_OCTREE_OCUPATION_COMPARISON_BAR_FILE_NAME;
extern const std::string INTERFERENCE_ANALYSIS_OCTREE_OCUPATION_BAR_FILE_NAME;
extern const std::string DIFFERENCE_INTERFERENCE_MESH_FILE_NAME;
extern const std::string INTERFERENCE_HEIGHT_ABSOLUTE_ERRORS_FILE_NAME;
extern const std::string INTERFERENCE_HEIGHT_TOTAL_POINTS_FILE_NAME;
extern const std::string INTERFERENCE_HEIGHT_NORMALIZED_ERRORS_FILE_NAME;
extern const std::string INTERFERENCE_HEIGHT_ERRORS_COLOR_MESH_FILE_NAME;
extern const std::string INTERFERENCE_HEIGHT_ERRORS_SCATTER_FILE_NAME;
extern const std::string GROUND_TRUTH_HEIGHT_ABSOLUTE_ERRORS_FILE_NAME;
extern const std::string GROUND_TRUTH_HEIGHT_TOTAL_POINTS_FILE_NAME;
extern const std::string GROUND_TRUTH_HEIGHT_NORMALIZED_ERRORS_FILE_NAME;
extern const std::string GROUND_TRUTH_HEIGHT_ERRORS_COLOR_MESH_FILE_NAME;
extern const std::string GROUND_TRUTH_HEIGHT_ERRORS_SCATTER_FILE_NAME;
extern const std::string INTERFERENCE_LOS_VS_DISTANCE_ERRORS_NORMALIZED_DIFFERENCE_FILE_NAME;
extern const std::string GROUND_TRUTH_LOS_VS_DISTANCE_ERRORS_NORMALIZED_DIFFERENCE_FILE_NAME;
extern const std::string INTERFERENCE_LOS_VS_DISTANCE_ERRORS_NORMALIZED_DIFFERENCE_COMPARISON_BAR_FILE;
extern const std::string GROUND_TRUTH_LOS_VS_DISTANCE_ERRORS_NORMALIZED_DIFFERENCE_COMPARISON_BAR_FILE;
extern const std::string INTERFERENCE_LOS_VS_DISTANCE_ERRORS_NORMALIZED_DIFFERENCE_COMPARISON_COLOR_MESH_FILE;
extern const std::string GROUND_TRUTH_LOS_VS_DISTANCE_ERRORS_NORMALIZED_DIFFERENCE_COMPARISON_COLOR_MESH_FILE;
extern const std::string INTERFERENCE_DIRECTION_DISTANCE_ERRORS_POLAR_PLOT_LASER_BASE_NAME;
extern const std::string INTERFERENCE_DIRECTION_DISTANCE_ERRORS_POLAR_PLOT_DIRECTION_BASE_NAME;
extern const std::string INTERFERENCE_BOX_FILTER_BAR_FILE;
extern const std::string GROUND_TRUTH_ROI_DISTANCE_ERRORS_COLOR_MESH_FILE_NAME;
extern const std::string INTERFERENCE_ROI_DISTANCE_ERRORS_COLOR_MESH_FILE_NAME;
extern const std::string DIFFERENCE_ROI_DISTANCE_ERRORS_COLOR_MESH_FILE_NAME;
extern const std::string OCTREE_INTERFERENCE_COLOR_MESH;
extern const std::string OCTREE_GROUND_TRUTH_COLOR_MESH;
extern const std::string OCTREE_DIFFERENCE_COLOR_MESH;
extern const std::string ICP_LOGGER_FILE_NAME;
extern const std::string INTERFERENCE_ANALYSIS_LOGGER_FILE_NAME;
extern const std::string ROI_INTERFERENCE_ANALYSIS_LOGGER_FILE_NAME;
extern const std::string OCTREE_INTERFERENCE_ANALYSIS_LOGGER_FILE_NAME;
extern const std::string CLOSER_DISTANCE_AFFIX;
extern const std::string HALFWAY_DISTANCE_AFFIX;
extern const std::string FURTHER_DISTANCE_AFFIX;
extern const std::string BELOW_HEIGHT_AFFIX;
extern const std::string ALIGNED_HEIGHT_AFFIX;
extern const std::string ABOVE_HEIGHT_AFFIX;
extern const std::string AFFIX_SEPARATOR;
} // namespace datasets_path
#endif /* DATASETS_INFO_H */
| true |
58948c2e2517129c9757148df2994b7d696254b3 | C++ | jwvg0425/DSAndAlgo3 | /src/countNode/countNode.cpp | UTF-8 | 189 | 3 | 3 | [
"MIT"
] | permissive | struct Node
{
int data;
Node* left = nullptr;
Node* right = nullptr;
};
int count(Node* node)
{
if (node == nullptr)
return 0;
return count(node->left) + count(node->right) + 1;
} | true |
cbf99fac0e11fd7f0d2e6f82c192bc570fe0f96d | C++ | ljtg24/Offer68 | /S38_permutation.cpp | UTF-8 | 777 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
using std::cout;
using std::endl;
void permutationCore(char* pStr, char* pBegin)
{
if (*pBegin == '\0')
{
// cout << (*pStr) << endl;
printf("%s\n", pStr);
}
else
{
for (char* pCh = pBegin; *pCh != '\0'; pCh++)
{
char temp = *pCh;
*pCh = *pBegin;
*pBegin = temp;
permutationCore(pStr, pBegin+1);
temp = *pCh;
*pCh = *pBegin;
*pBegin = temp; // 换回来,pCh+1与pBegin继续换
}
}
}
void permutation(char* pStr)
{
if (pStr == nullptr)
return;
permutationCore(pStr, pStr);
}
int main()
{
char a[] = "abc";
char* pStr = a;
permutation(pStr);
return 0;
} | true |
35df65940ace72152df16da2928c71be88a6fd67 | C++ | amandugar/5X5-Matrix-of-Motors | /Slave_2/Slave_2.ino | UTF-8 | 555 | 3 | 3 | [] | no_license | #include <Servo.h>
#include <Wire.h>
Servo myServo[12];
void setup()
{
for (int i = 0; i < 13; i++)
{
myServo[i].attach(i + 1);
myServo[i].write(0);
}
Wire.begin(2);
Wire.onReceive(receiveEvent);
}
void runServo(byte x) {
for (int pos = 0; pos <= 180; pos ++) // goes from 0 degrees to 180 degrees
{
myServo[x-1].write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
}
void loop()
{
delay(100);
}
void receiveEvent(int howMany)
{
int x = Wire.read();
runServo(x);
}
| true |
db412d2726fba740eb08060be0a2bb059915ab90 | C++ | liviuq/Petrache_Andrei_Liviu_A3 | /lambdaLab/myVector.cpp | UTF-8 | 852 | 3.453125 | 3 | [] | no_license | //
// Created by andrew on 12.05.2021.
//
#include <iostream>
#include "myVector.h"
bool myVectorClass::Add(int newElement)
{
myArray.push_back(newElement);
this->size++;
return true;
}
bool myVectorClass::Delete(int index)
{
myArray.erase(myArray.begin() + index);
this->size--;
return true;
}
void myVectorClass::Iterate( void(*callback) (int& element))
{
for(int i = 0; i < size; i++)
{
callback(myArray[i]);
}
}
void myVectorClass::Filter( bool(*callback)(int))
{
for(int i = 0; i < size; i++)
{
if( callback(myArray[i]))
{
for( int j = i; j < size; j++)
myArray[j] = myArray[j + 1];
myArray[size] = 0;
size--;
i--; // re-check the element on the position we just deleted
}
}
}
void myVectorClass::Print()
{
for (int i = 0; i < size; i++)
{
std::cout << myArray[i] << " ";
}
std::cout << std::endl;
} | true |
e3b99f0f180e26057fbc0827d390dec1584641d9 | C++ | edenreich/http-component | /tests/unit/request_test.cpp | UTF-8 | 881 | 2.734375 | 3 | [
"MIT"
] | permissive |
#include <gtest/gtest.h>
#include <http/message.h>
#include <http/request.h>
#include <http/response.h>
#include <http/interfaces/response_interface.h>
#include <http/url.h>
#include <http/types/status_codes.h>
#include <http/exceptions/invalid_message_exception.h>
using namespace Http;
TEST(RequestTest, ItThrowsAnInvalidMessageExceptionIfAnInvalidRequestMessageWasPassed) {
EXPECT_THROW(new Request(new Message("HTTP/1.1 200 OK")), Exceptions::InvalidMessageException);
EXPECT_THROW(new Request(new Message("UNKNOWN_HTTP_VERB /path HTTP/1.1")), Exceptions::InvalidMessageException);
}
// TEST(RequestTest, ItReturnsAnHttpStatusCode) {
// Request request;
// Interfaces::ResponseInterface * response = request.get(Url("https://www.google.com"));
// StatusCode statusCode = response->getStatusCode();
// EXPECT_EQ(statusCode, StatusCode::OK);
// } | true |
7223bade28820862bfdaecc45878c386f01eead7 | C++ | RlingDK/QTTime | /QTTime/Period.h | UTF-8 | 1,751 | 3.421875 | 3 | [] | no_license | /*
* Period.h
*
* Created on: May 26, 2016
* Author: rling
*/
#ifndef PERIOD_H_
#define PERIOD_H_
#include <stdio.h>
/**
* Enumeration for the time period types (work and relax)
*/
enum TYPE {
fail, // Indicator type for when the whole plan has failed
work,
relax,
end // Indicator type for when the whole plan was completed
};
/**
* This class represents each of the time periods in the time plan.
*/
class Period {
/** The minimum length of a time period. */
const static int minLength = 10;
/** Length of the time period (in seconds) */
int length;
/** The type of activity for the time period e.g work or relaxation*/
TYPE type;
/** The sound played for the user, to indicate that the time period has started. There should be a sound for each of activity types */
int sound;
public:
Period();
/** Flexible constructor*/
Period(int len = minLength, TYPE typ=work, int snd = 0);
virtual ~Period();
// ------------------------------------------------- Get & set for all members
int getLength() const {
return length;
}
/** Enforces the min length */
bool setLength(int length) { // Check length (min.)
if(length < minLength) {
printf("Time length too small (minimum %i sec.)\n", minLength);
return false;
}
this->length = length;
return true;
}
int getSound() const {
return sound;
}
void setSound(int sound) {
this->sound = sound;
}
TYPE getType() const {
return type;
}
void setType(TYPE type) {
this->type = type;
}
int getMinLength() const {
return minLength;
}
};
#endif /* PERIOD_H_ */
| true |
d23110ba25dd2e20bb8c422a5495a3ebf9ab117a | C++ | tiagochst/PIM2013 | /src/Config.cpp | UTF-8 | 2,054 | 2.640625 | 3 | [] | no_license | #include "Config.h"
const std::string USR_HOME = std::string(getenv("HOME"));
std::string Config::_rootPath(USR_HOME + "/.pim2013/");
std::string Config::_resourcesPath("");
std::string Config::_dataPath("");
std::string Config::_outputPath("");
std::string Config::_configPath("");
std::string Config::_capturedFramesPath("");
void Config::LoadConfigs(const std::string& iFilename)
{
std::ifstream configFile( iFilename.c_str(), std::fstream::in);
std::string line;
if ( !configFile.good() ) {
std::cout << "Could not open settings file." << std::endl;
return;
}
while ( !configFile.eof() ) {
std::getline( configFile, line );
std::stringstream lineStream(line);
std::string tag;
lineStream >> tag;
if ( tag.compare("RSC_DIR") == 0 ) {
lineStream >> Config::_resourcesPath;
std::cout << "RSC_DIR = " << Config::ResourcesPath() << std::endl;
}
}
if (Config::_resourcesPath.empty() ) {
std::cout << "Error loading settings from " << _rootPath + iFilename << std::endl;
exit(-1);
}
if ( Config::_dataPath.empty() ) {
Config::_dataPath = ResourcesPath() + "Data/";
}
if ( Config::_outputPath.empty() ) {
Config::_outputPath = DataPath() + "Output/";
}
if ( Config::_capturedFramesPath.empty() ) {
Config::_capturedFramesPath = OutputPath() + "CapturedFrames/";
}
if ( Config::_configPath.empty() ) {
Config::_configPath = DataPath() + "Config/";
}
}
const std::string& Config::RootPath()
{
return Config::_rootPath;
}
const std::string& Config::ResourcesPath()
{
return Config::_resourcesPath;
}
const std::string& Config::DataPath()
{
return Config::_dataPath;
}
const std::string& Config::OutputPath()
{
return Config::_outputPath;
}
const std::string& Config::FramesPath()
{
return Config::_capturedFramesPath;
}
const std::string& Config::ConfigPath()
{
return Config::_configPath;
}
| true |
b2618653196c7bea6368cd215b5b9857fb1628e2 | C++ | luqilinok/Leetcode | /leetcode-algorithms/242. Valid Anagra/242. Valid Anagram.cpp | UTF-8 | 1,360 | 3.53125 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=242 lang=cpp
*
* [242] 有效的字母异位词
*
* https://leetcode-cn.com/problems/valid-anagram/description/
*
* algorithms
* Easy (51.90%)
* Total Accepted: 27.2K
* Total Submissions: 52.4K
* Testcase Example: '"anagram"\n"nagaram"'
*
* 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
*
* 示例 1:
*
* 输入: s = "anagram", t = "nagaram"
* 输出: true
*
*
* 示例 2:
*
* 输入: s = "rat", t = "car"
* 输出: false
*
* 说明:
* 你可以假设字符串只包含小写字母。
*
* 进阶:
* 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
*
*/
class Solution
{
public:
bool isAnagram(string s, string t)
{
int x[26] = {0};
int y[26] = {0};
for (int i = 0; i < s.size(); i++)
{
x[s[i] - 'a']++; //s[i]-'a'表示数组s中下标为i的数和'a'的距离,eg:'b'-'a'==1、'c'-'a'==2,所以表达式x[s[i] - 'a']++可以用来计数
}
for (int i = 0; i < t.size(); i++)
{
y[t[i] - 'a']++;
}
for (int i = 0; i < 26; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
};
| true |