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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
536270d345197f5f66b9b93a37c4121edb0a2d2c | C++ | Marneus68/WorkingTitle | /src/Resource.cpp | UTF-8 | 1,137 | 2.9375 | 3 | [] | no_license | #include "Resource.h"
#include <ostream>
#include "ResourceType.h"
namespace wot {
Resource::Resource() {
resourceType = ResourceType::NONE;
rawPath = "";
name = "";
description = "";
loaded = false;
}
Resource::Resource(const Resource & resource){
resourceType = resource.resourceType;
rawPath = resource.rawPath;
name = resource.name;
description = resource.description;
loaded = resource.loaded;
}
Resource::~Resource() {}
Resource & Resource::operator=(const Resource & resource) {
resourceType = resource.resourceType;
rawPath = resource.rawPath;
name = resource.name;
description = resource.description;
loaded = resource.loaded;
return *this;
}
bool Resource::load() {return true;}
bool Resource::free() {return true;}
int Resource::construct(const std::string & rawPath) {
return 0;
}
std::string Resource::toString() {
return std::string("[" + ResourceTypeNames::names[resourceType] + "] " + name);
}
} /* wot */
| true |
ad79ff9a63e37a524e9db98c4a320c785abca636 | C++ | MehrajShakil/Solving-problem-in-different-OJ | /Leetcode/Graph/Flood fill/733. Flood Fill.cpp | UTF-8 | 949 | 2.859375 | 3 | [] | no_license | class Solution {
void dfs ( vector<vector<int>>& image , int row , int col , int x , int y ,int source , int newColor ){
if ( x<0 or x>=row or y<0 or y>=col or image[x][y]!=source ) return;
image[x][y] = newColor;
dfs ( image , row , col , x+1 , y , source , newColor );
dfs ( image , row , col , x , y+1 , source , newColor );
dfs ( image , row , col , x-1 , y , source , newColor );
dfs ( image , row , col , x , y-1 , source , newColor );
}
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(newColor==image[sr][sc]) return image;
int row = image.size();
int col = image[0].size();
int source = image[sr][sc];
dfs ( image , row , col , sr , sc , source , newColor );
return image;
}
};
| true |
b068ce4fa58b85981dc4e00009e219affa0f0c59 | C++ | sunn1t/shortest-superstring | /src/graph.h | UTF-8 | 586 | 3.015625 | 3 | [] | no_license | #ifndef GRAPH_H
#define GRAPH_H
#include <cstddef>
struct Path {
public:
size_t *v_sequence;
size_t n;
};
class Graph {
public:
Graph(size_t n_vertex);
Graph(const Graph &old);
Graph &operator = (const Graph &old);
void AddEdge(size_t from, size_t to, size_t length);
size_t ** GetMatrix() const;
size_t * GetEdgesFrom(const size_t from) const;
size_t GetSize() const;
size_t GetLength(Path const &path) const;
void PrintAdjMatrix() const;
~Graph();
private:
size_t n_vertex;
size_t ** adj_matrix;
};
#endif // GRAPH_H
| true |
5c89119f38cc7f6c79ecb06663f13ef41627b031 | C++ | luismoax/Competitive-Programming---luismo | /COJ_ACCEPTED/3141 - Fountain.cpp | UTF-8 | 3,371 | 2.90625 | 3 | [] | no_license | /*
Author: Luis Manuel D?az Bar?n (LUISMO)
Problem: Fountain
Online Judge: COJ
Idea: Solved using a custom Segment Tree, nice one
*/
#include<bits/stdc++.h>
// Types
#define ll long long
#define ull unsigned long long
// IO
#define sf scanf
#define pf printf
using namespace std;
const int lim = 1e5 + 5;
int N, Q;
int arr[lim];
struct node
{
int L, R;
ll cap, water;
ll lazy; // water loaded
node(){}
} t[lim << 2];
inline int ls(int idx){return (idx << 1) + 1;}
inline int rs(int idx){return (idx << 1) + 2;}
void buildTree(int idx, int L, int R)
{
t[idx].L = L; t[idx].R = R;
// if leaf
if(L == R)
{
t[idx].cap = arr[L];
return;
}
int mid = (L + R) >> 1;
//
buildTree(ls(idx), L, mid);
buildTree(rs(idx), mid + 1, R);
// merge
t[idx].cap = t[ls(idx)].cap + t[rs(idx)].cap;
}
void propagate(int idx)
{
// if lazy
if(t[idx].lazy > 0)
{
t[idx].cap -= t[idx].lazy;
t[idx].water += t[idx].lazy;
// if not leaf
if(t[idx].L != t[idx].R)
{
// try to fill the left son (the amount of watar that can still be filled)
ll toFill = min(t[ls(idx)].cap - t[ls(idx)].lazy, t[idx].lazy);
// fill it
t[ls(idx)].lazy += toFill;
t[idx].lazy-= toFill;
// fill the right son with the remaining water
t[rs(idx)].lazy+= t[idx].lazy;
}
}
t[idx].lazy = 0;
}
// updates and return the used water per node
int update(int idx, int QL, int QR, int upd)
{
propagate(idx);
// if contained
if(t[idx].L >= QL && t[idx].R <= QR)
{
ll toFillHere = 0;
if(t[idx].cap < upd)
toFillHere = t[idx].cap;
else toFillHere = upd;
// update the capacity and the water in this node
t[idx].water+= toFillHere;
t[idx].cap -= toFillHere;
// if not leaf
if(t[idx].L != t[idx].R)
{
// to fill left
ll toFillLeft = min(toFillHere, t[ls(idx)].cap - t[ls(idx)].lazy);
t[ls(idx)].lazy+= toFillLeft; // loading left son's lazyness
// update with the amont of water that remains
t[rs(idx)].lazy += (toFillHere - toFillLeft); // the ramining water goes right
}
// return the amount of used water in this node
return toFillHere;
}
// if outside
if(t[idx].L > QR || t[idx].R < QL)
return 0;
int mid = (t[idx].L + t[idx].R) >> 1;
// update left and get the amount of used water
int left = update(ls(idx), QL, QR, upd);
// update right and get the amount of used water
int right = update(rs(idx), QL, QR, upd - left);
// merging
t[idx].water = t[ls(idx)].water + t[rs(idx)].water;
t[idx].cap = t[ls(idx)].cap + t[rs(idx)].cap;
// return the total amount of used water in this node
return left + right;
}
int retrieve(int idx, int ii)
{
propagate(idx);
// if leaf
if(t[idx].L == t[idx].R)
return t[idx].water;
int mid = (t[idx].L + t[idx].R) >> 1;
if(ii <= mid)
return retrieve(ls(idx), ii);
return retrieve(rs(idx), ii);
}
void solve()
{
cin >> N;
// reading integers
for(int i = 0; i < N; i++)
cin >> arr[i];
// build Segment Tree
buildTree(0, 0 , N - 1);
cin >> Q;
int type, a, b;
// reading queries
for(int i = 0; i < Q; i++)
{
cin >> type;
if(type == 1)
{
cin >> a;
a--;
int answ = retrieve(0, a);
cout << answ << "\n";
}
else
{
cin >> a >> b;
a--;
update(0, a, N - 1, b);
}
}
}
int main()
{
if(fopen("d:\\lmo.in","r") != NULL)
freopen("d:\\lmo.in","r",stdin);
cin.sync_with_stdio(false);
cin.tie(0);
solve();
} | true |
e93fff6fab9299d4ff21bacdca3f8f88da588b01 | C++ | Rodousse/Arverne-Viewer | /src/renderer/src/camera/ArcBallCamera.cpp | UTF-8 | 2,039 | 2.9375 | 3 | [] | no_license | #include "renderer/camera/ArcBallCamera.h"
#include <glm/gtc/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include <math.h>
namespace renderer
{
#ifndef M_PI
const float M_PI = glm::pi<float>();
#endif
ArcBallCamera::ArcBallCamera():
Camera(),
radius_(2.0f),
phi_(3.0f * M_PI / 4.0f),
theta_(M_PI)
{
computePosition();
}
ArcBallCamera::~ArcBallCamera()
{
}
float ArcBallCamera::getRadius() const
{
return radius_;
}
void ArcBallCamera::setRadius(float radius)
{
radius_ = radius;
computePosition();
}
float ArcBallCamera::getPhi() const
{
return phi_;
}
void ArcBallCamera::setPhi(float phi)
{
phi_ = std::max(std::min(static_cast<float>(M_PI - 0.01f), phi), 0.01f);
computePosition();
}
float ArcBallCamera::getTheta() const
{
return theta_;
}
void ArcBallCamera::setTheta(float theta)
{
if(std::abs(theta) > 2 * M_PI)
{
theta_ = std::abs(theta) - 2 * M_PI;
}
theta_ = theta;
computePosition();
}
void ArcBallCamera::setCenter(const glm::vec3& center)
{
Camera::setCenter(center);
computePolar();
computePosition();
}
void ArcBallCamera::setPosition(const glm::vec3& position)
{
Camera::setPosition(position);
computePolar();
}
void ArcBallCamera::incrementPhi(float phiStep)
{
setPhi(phi_ - phiStep);
}
void ArcBallCamera::incrementTheta(float thetaStep)
{
setTheta(theta_ + thetaStep);
}
void ArcBallCamera::incrementRadius(float radiusStep)
{
setRadius(radius_ + radiusStep);
}
void ArcBallCamera::computePosition()
{
position_.x = radius_ * sin(phi_) * cos(theta_);
position_.y = radius_ * sin(phi_) * sin(theta_);
position_.z = radius_ * cos(phi_);
Camera::setPosition(position_ + center_);
}
void ArcBallCamera::computePolar()
{
glm::vec3 positionFromCenter = position_ - center_;
radius_ = positionFromCenter.length();
theta_ = atan(position_.y / position_.x);
phi_ = atan((pow(position_.x, 2) + pow(position_.y, 2)) / position_.z);
}
}
| true |
4a3643195a07c123374e2f00811a33079ff08dc9 | C++ | Retnirps/ITMO | /C++/HW2class/Report.cpp | UTF-8 | 1,603 | 3.53125 | 4 | [
"MIT"
] | permissive | #include <iostream>
#include <iomanip>
#include "Report.h"
Report::Report()
{
setZero();
mName = "";
}
Report::Report(const std::string name) : mName(name)
{
setZero();
}
void Report::setZero()
{
mAverage = 0;
mAdmissionNumber = 0;
for(int i = 0; i < MARKS_AMOUNT; ++i)
{
mMarks[i] = 0;
}
}
void Report::readInfo(const short admissionNumber, const std::string name,
const float marks[MARKS_AMOUNT]) throw (OverflowException)
{
if (name.size() > NAME_SIZE || admissionNumber >= FIVE_DIGITS)
{
throw OverflowException();
return;
}
mName = name;
mAdmissionNumber = admissionNumber;
for (int i = 0; i < MARKS_AMOUNT; ++i)
{
mMarks[i] = marks[i];
}
mAverage = getAvg();
}
void Report::displayInfo() const
{
std::cout << "AdmissionNumber: " << std::setw(ADM_NUM_SIZE)
<< std::setfill('0') << mAdmissionNumber << '\n'
<< "Name: " << mName << '\n'
<< "Marks:";
for (int i = 0; i < MARKS_AMOUNT; ++i)
{
std::cout << ' ' << mMarks[i];
}
std::cout << "\nAverage: " << mAverage << '\n';
}
float Report::getAvg()
{
float sum = 0.0;
for (int i = 0; i < MARKS_AMOUNT; ++i)
{
sum += mMarks[i];
}
return sum / MARKS_AMOUNT;
}
int main() {
Report C;
std::string name;
short admissionNumber;
float marks[MARKS_AMOUNT];
std::cin >> name >> admissionNumber;
for (int i = 0; i < MARKS_AMOUNT; ++i)
{
std::cin >> marks[i];
}
//C.displayInfo();
try
{
C.readInfo(admissionNumber, name, marks);
}
catch (OverflowException& e)
{
std::cout << "overflow, enter valid data\n";
return 0;
}
C.displayInfo();
}
| true |
d72b32c88cf181bbc41d51c179ce70f36a0b2e12 | C++ | effekseer/EffekseerForCocos2d-x | /Players/Cocos2d-x_v4/3rdParty/LLGI/src/Vulkan/LLGI.SingleFrameMemoryPoolVulkan.cpp | UTF-8 | 3,065 | 2.65625 | 3 | [
"MIT"
] | permissive | #include "LLGI.SingleFrameMemoryPoolVulkan.h"
#include "LLGI.BufferVulkan.h"
namespace LLGI
{
InternalSingleFrameMemoryPoolVulkan::InternalSingleFrameMemoryPoolVulkan() {}
InternalSingleFrameMemoryPoolVulkan ::~InternalSingleFrameMemoryPoolVulkan() {}
bool InternalSingleFrameMemoryPoolVulkan::Initialize(GraphicsVulkan* graphics, int32_t constantBufferPoolSize, int32_t drawingCount)
{
constantBufferSize_ = (constantBufferPoolSize + 255) & ~255; // buffer size should be multiple of 256
buffer_ = std::unique_ptr<BufferVulkan>(
static_cast<BufferVulkan*>(graphics->CreateBuffer(BufferUsageType::Constant | BufferUsageType::MapWrite, constantBufferSize_)));
return true;
}
void InternalSingleFrameMemoryPoolVulkan::Dispose() { buffer_ = nullptr; }
bool InternalSingleFrameMemoryPoolVulkan::GetConstantBuffer(int32_t size, BufferVulkan*& buffer, int32_t& outOffset)
{
if (constantBufferOffset_ + size > constantBufferSize_)
return false;
buffer = buffer_.get();
outOffset = constantBufferOffset_;
constantBufferOffset_ += size;
return true;
}
void InternalSingleFrameMemoryPoolVulkan::Reset() { constantBufferOffset_ = 0; }
Buffer* SingleFrameMemoryPoolVulkan::CreateBufferInternal(int32_t size)
{
auto obj = new BufferVulkan();
if (!obj->InitializeAsShortTime(graphics_, this, size))
{
SafeRelease(obj);
return nullptr;
}
return obj;
}
Buffer* SingleFrameMemoryPoolVulkan::ReinitializeBuffer(Buffer* cb, int32_t size)
{
auto obj = static_cast<BufferVulkan*>(cb);
if (!obj->InitializeAsShortTime(graphics_, this, size))
{
return nullptr;
}
return obj;
}
SingleFrameMemoryPoolVulkan::SingleFrameMemoryPoolVulkan(
GraphicsVulkan* graphics, bool isStrongRef, int32_t swapBufferCount, int32_t constantBufferPoolSize, int32_t drawingCount)
: SingleFrameMemoryPool(swapBufferCount), graphics_(graphics), isStrongRef_(isStrongRef), currentSwap_(-1), drawingCount_(drawingCount)
{
if (isStrongRef)
{
SafeAddRef(graphics_);
}
for (int32_t i = 0; i < swapBufferCount; i++)
{
auto memoryPool = std::make_shared<InternalSingleFrameMemoryPoolVulkan>();
if (!memoryPool->Initialize(graphics, constantBufferPoolSize, drawingCount))
{
return;
}
memoryPools.push_back(memoryPool);
}
}
SingleFrameMemoryPoolVulkan ::~SingleFrameMemoryPoolVulkan()
{
for (auto& pool : memoryPools)
{
pool->Dispose();
}
memoryPools.clear();
if (isStrongRef_)
{
SafeRelease(graphics_);
}
}
bool SingleFrameMemoryPoolVulkan::GetConstantBuffer(int32_t size, BufferVulkan*& buffer, int32_t& outOffset)
{
assert(currentSwap_ >= 0);
return memoryPools[currentSwap_]->GetConstantBuffer(size, buffer, outOffset);
}
InternalSingleFrameMemoryPoolVulkan* SingleFrameMemoryPoolVulkan::GetInternal() { return memoryPools[currentSwap_].get(); }
int32_t SingleFrameMemoryPoolVulkan::GetDrawingCount() const { return drawingCount_; }
void SingleFrameMemoryPoolVulkan::NewFrame()
{
currentSwap_++;
currentSwap_ %= memoryPools.size();
memoryPools[currentSwap_]->Reset();
SingleFrameMemoryPool::NewFrame();
}
} // namespace LLGI
| true |
adda0f1382d225c43ace39a0ac332e46ddb3e6d4 | C++ | PhoenixGS/Test | /Test000006.cpp | UTF-8 | 905 | 2.734375 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
using namespace std;
int x[40000];
int F1[40000][4];
int F2[40000][4];
int calc(int x, int y)
{
if (x == y)
{
return 0;
}
return 1;
}
int main()
{
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%d", &x[i]);
}
for (int i = 1; i <= n; i++)
{
F1[i][1] = F1[i - 1][1] + calc(1, x[i]);
F1[i][2] = min(F1[i - 1][1], F1[i - 1][2]) + calc(2, x[i]);
F1[i][3] = min(min(F1[i - 1][1], F1[i - 1][2]), F1[i - 1][3]) + calc(3, x[i]);
}
for (int i = 1; i <= n; i++)
{
F2[i][3] = F2[i - 1][3] + calc(3, x[i]);
F2[i][2] = min(F2[i - 1][3], F2[i - 1][2]) + calc(2, x[i]);
F2[i][1] = min(min(F2[i - 1][3], F2[i - 1][2]), F2[i - 1][1]) + calc(1, x[i]);
}
int ans = 1000000000;
for (int i = 1; i <= 3; i++)
{
ans = min(ans, min(F1[n][i], F2[n][i]));
//printf("%d %d\n", F1[n][i], F2[n][i]);
}
printf("%d\n", ans);
return 0;
}
| true |
5f70a4507a3c233413ffb35d18f7ce56a926c959 | C++ | icelinker/structured-light | /OpenFrameworks/apps/earlyDemos/slCapture/ThreadedImageSaver.h | UTF-8 | 1,412 | 3.015625 | 3 | [] | no_license | #pragma once
#include "ofxThread.h"
#include "GlobalLogger.h"
#include <queue>
struct SaveableImage {
ofImage img;
ofImage temp;
string filename;
void saveImage() {
img.saveImage(filename);
}
void rotate() {
int w = (int) img.getWidth();
int h = (int) img.getHeight();
temp.allocate(h, w, img.type);
unsigned char* srcPixels = img.getPixels();
unsigned char* destPixels = temp.getPixels();
int destPosition = 0, srcPosition = 0;
for(int y = 0; y < h; y++) {
for(int x = 0; x < w; x++) {
destPosition = ((x + 1) * h - y) * 3;
srcPosition = (y * w + x) * 3;
destPixels[destPosition + 0] = srcPixels[srcPosition + 0];
destPixels[destPosition + 1] = srcPixels[srcPosition + 1];
destPixels[destPosition + 2] = srcPixels[srcPosition + 2];
}
}
img.allocate(h, w, img.type);
img.setFromPixels(destPixels, h, w, img.type);
}
};
class ThreadedImageSaver : public ofxThread {
public:
void save(const ofImage& img, const string& filename) {
SaveableImage cur;
cur.img = img;
cur.filename = filename;
images.push(cur);
if(!isThreadRunning())
startThread(false, false);
}
int size() {
return images.size();
}
protected:
queue<SaveableImage> images;
void threadedFunction() {
while(images.size() > 0) {
images.front().rotate();
images.front().saveImage();
images.pop();
}
}
};
| true |
4b4244e369245f29415fd1536a789bc22802c709 | C++ | mengkaibulusili/leetcode | /cpp/0010-regular-expression-matching.cpp | UTF-8 | 1,286 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution
{
public:
bool isMatch(string s, string p)
{
int m = s.size();
int n = p.size();
auto matches = [&](int i, int j) {
if (i == 0)
{
return false;
}
if (p[j - 1] == '.')
{
return true;
}
return s[i - 1] == p[j - 1];
};
vector<vector<int>> f(m + 1, vector<int>(n + 1));
f[0][0] = true;
for (int i = 0; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (p[j - 1] == '*')
{
f[i][j] |= f[i][j - 2];
if (matches(i, j - 1))
{
f[i][j] |= f[i - 1][j];
}
}
else
{
if (matches(i, j))
{
f[i][j] |= f[i - 1][j - 1];
}
}
}
}
return f[m][n];
}
};
void rep()
{
string str1("123456");
string str;
str.assign(str1); //直接赋值
cout << str << endl;
str.assign(str1, 1, 1); //赋值给子串
cout << str << endl;
str.assign(str1, 2, str1.npos); //赋值给从位置 2 至末尾的子串
cout << str << endl;
return;
}
int main()
{
Solution solu;
cout << solu.isMatch("aaa", "a*a") << endl;
string a = "123";
rep();
} | true |
ca7281b2ec6094373e8a6415e5c9bd7b0eb540ed | C++ | sgumhold/cgv | /plugins/examples/visibility_sorting.cpp | UTF-8 | 4,024 | 2.5625 | 3 | [] | permissive | #include <random>
#include <cgv/base/node.h>
#include <cgv/gui/provider.h>
#include <cgv/render/drawable.h>
#include <cgv_gl/sphere_render_data.h>
#include <cgv_gpgpu/visibility_sort.h>
class visibility_sorting : public cgv::base::node, public cgv::render::drawable, public cgv::gui::provider {
protected:
cgv::render::view* view_ptr;
unsigned n;
cgv::render::sphere_render_style sphere_style;
cgv::render::sphere_render_data<rgba> spheres;
cgv::gpgpu::visibility_sort visibility_sorter;
bool do_sort;
public:
visibility_sorting() : cgv::base::node("visibility sorting test")
{
view_ptr = nullptr;
n = 10000;
sphere_style.radius = 0.01f;
sphere_style.surface_color = rgb(1.0f, 0.5f, 0.2f);
sphere_style.map_color_to_material = CM_COLOR_AND_OPACITY;
do_sort = true;
}
void on_set(void* member_ptr)
{
post_redraw();
update_member(member_ptr);
}
std::string get_type_name() const
{
return "visibility_sorting";
}
void clear(cgv::render::context& ctx)
{
cgv::render::ref_sphere_renderer(ctx, -1);
spheres.destruct(ctx);
visibility_sorter.destruct(ctx);
}
bool init(cgv::render::context& ctx)
{
cgv::render::ref_sphere_renderer(ctx, 1);
if(!spheres.init(ctx))
return false;
visibility_sorter.set_sort_order(cgv::gpgpu::visibility_sort::SO_DESCENDING);
create_data();
view_ptr = find_view_as_node();
return true;
}
void init_frame(cgv::render::context& ctx)
{
if(!view_ptr)
view_ptr = find_view_as_node();
}
void draw(cgv::render::context& ctx)
{
if(!view_ptr || spheres.ref_pos().size() == 0) return;
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
// use back-to-front blending
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
auto& sr = ref_sphere_renderer(ctx);
spheres.early_transfer(ctx, sr);
int pos_handle = 0;
int idx_handle = 0;
auto& aam = spheres.ref_aam();
pos_handle = sr.get_vbo_handle(ctx, aam, "position");
idx_handle = sr.get_index_buffer_handle(aam);
if(visibility_sorter.is_initialized()) {
if(pos_handle > 0 && idx_handle > 0 && do_sort) {
visibility_sorter.begin_time_query();
visibility_sorter.execute(ctx, pos_handle, idx_handle, view_ptr->get_eye(), view_ptr->get_view_dir());
float time = visibility_sorter.end_time_query();
std::cout << "Sorting done in " << time << " ms -> " << static_cast<float>(n) / (1000.0f * time) << " M/s" << std::endl;
}
} else {
std::cout << "Warning: GPU visibility sort is not initialized." << std::endl;
}
spheres.render(ctx, sr, sphere_style);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
}
void create_gui()
{
add_decorator("Visibility Sorting", "heading");
add_member_control(this, "N", n, "value_slider", "min=1000;max=10000000;ticks=true");
connect_copy(add_button("Generate")->click, cgv::signal::rebind(this, &visibility_sorting::create_data));
add_member_control(this, "Sort", do_sort, "check");
if(begin_tree_node("Sphere Style", sphere_style, false)) {
align("\a");
add_gui("", sphere_style);
align("\b");
end_tree_node(sphere_style);
}
}
void create_data()
{
auto& ctx = *get_context();
spheres.clear();
std::mt19937 rng(42);
std::uniform_real_distribution<float> pos_distr(-1.0f, 1.0f);
std::uniform_real_distribution<float> col_distr(0.2f, 0.9f);
for(unsigned i = 0; i < n; ++i) {
vec3 pos(
pos_distr(rng),
pos_distr(rng),
pos_distr(rng)
);
rgba col(
col_distr(rng),
col_distr(rng),
col_distr(rng),
col_distr(rng)
);
spheres.add(pos);
spheres.add(col);
}
spheres.ref_idx().resize(spheres.ref_pos().size());
if(!visibility_sorter.init(ctx, spheres.ref_idx().size()))
std::cout << "Error: Could not initialize GPU sorter!" << std::endl;
spheres.set_out_of_date();
post_redraw();
}
};
#include <cgv/base/register.h>
/// register a factory to create new visibility sorting tests
cgv::base::factory_registration<visibility_sorting> test_visibility_sorting_fac("New/GPGPU/Visibility Sorting");
| true |
ac2602429c63fb3b451fcf8c0aa9b1a4d004a605 | C++ | CodeWithKartik/Mafia | /Detective.cpp | UTF-8 | 538 | 2.796875 | 3 | [] | no_license | #include "Detective.h"
#include <iostream>
Detective::Detective(int ID, std::string nm):Player(ID, nm, DETECTIVE) {
}
std::string Detective::SuspectWho() {
std::cout<<"Do you suspect someone?";
bool ch;
std::string choice;
std::string who = "";
std::cin>>choice;
if (choice == "YES" || choice == "Yes" || choice == "yes" || choice == "y" || choice == "Y")
ch = true;
else
ch = false;
std::cout<<"Who?\n";
if (ch) {
std::cin>>who;
}
return who;
}
| true |
23bea3a3aec231a7e77ba1ca85ad6fdb90753b33 | C++ | Stypox/olympiad-exercises | /olinfo/panama/main.cpp | UTF-8 | 2,736 | 2.6875 | 3 | [] | no_license | #pragma GCC optimize ("O3")
#include <bits/stdc++.h>
using namespace std;
#define int int64_t
#define float long double
ifstream in{"input.txt"};
ofstream out{"output.txt"};
#ifdef DEBUG
template<class A,class B>ostream&operator<<(ostream&o,const pair<A,B>&p){cout<<"("<<p.first<<", "<<p.second<<")";return o;}
template<class T,typename=typename enable_if<!is_same<T, string>::value,decltype(*begin(declval<T>()))>::type>ostream&operator<<(ostream&o,const T&v){cout<<"[";for(auto it=v.begin();it!=v.end();++it){if(it!=v.begin()){cout<<", ";}cout<<*it;}cout<<"]";return o;}
void deb(){cout<<"\n";}template<class T,class...Ts>void deb(const T&t,const Ts&...args){cout<<t;if(sizeof...(args)!=0){cout<<" ";}deb(args...);}
#else
#define deb(...)
#endif
template<class T>
class SegmentTree {
static int higherPowerOf2(int x) {
int res = 1;
while (res < x) res *= 2;
return res;
}
const T neutralValue;
T(*merge)(const T&, const T&);
vector<T> data;
T query(int i, int a, int b, int x, int y) {
if (b <= x || a >= y) return neutralValue;
if (b <= y && a >= x) return data[i];
return merge(
query(i*2, a, (a+b)/2, x, y),
query(i*2+1, (a+b)/2, b, x, y)
);
}
const T& update(int i, int a, int b, int x, const T& v) {
if (x < a || x >= b) return data[i];
if (a == b-1) {
assert(a == x);
return data[i] = v;
}
return data[i] = merge(
update(i*2, a, (a+b)/2, x, v),
update(i*2+1, (a+b)/2, b, x, v)
);
}
public:
SegmentTree(int n, const T& neutralValue, T(*merge)(const T&, const T&)) :
neutralValue{neutralValue}, merge{merge}, data(2 * higherPowerOf2(n), neutralValue) {}
T query(int x, int y) {
assert(x <= y);
return query(1, 0, data.size()/2, x, y);
}
void update(int x, const T& v) {
update(1, 0, data.size()/2, x, v);
}
};
struct Data {
int all, left, right, inside;
};
signed main() {
int N, Q;
in>>N>>Q;
SegmentTree<Data> st1(
N,
Data{0,0,0,0},
[](const Data& l, const Data& r) {
return Data{
l.all + r.all,
max(l.all + r.left, l.left),
max(r.all + l.right, r.right),
max({l.inside, r.inside, l.right + r.left})
};
}
);
// st2 is just the opposite of st1 (panama sums can be from one or the other)
SegmentTree<Data> st2 = st1;
auto updateValue = [&](int n, int v) {
if (n%2 == 1) {
st1.update(n, Data{-v, 0, 0, 0});
st2.update(n, Data{v, v, v, v});
} else {
st1.update(n, Data{v, v, v, v});
st2.update(n, Data{-v, 0, 0, 0});
}
};
for(int n=0; n<N; ++n){
int v;
in>>v;
updateValue(n, v);
}
for(int q=0; q<Q; ++q){
int t, al, br;
in>>t>>al>>br;
if (t == 1) {
updateValue(al-1, br);
} else {
out << max(st1.query(al-1, br).inside, st2.query(al-1, br).inside) << "\n";
}
}
}
| true |
3893c6dd2150d3a5af8611941c7cb7cb9084b9c2 | C++ | chilogen/workspace | /acm/oj/codeforce/problems/ac/876c.cpp | UTF-8 | 569 | 2.84375 | 3 | [] | no_license | //because x no exceed 10^9,so the digtalsum
//no exceed 9*9==81
//so calc the digtal sum j from max(0,x-81) to x
//and add it to j,if equal to x,it is one of the anser
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL digtalsum(LL x)
{
LL sum=0;
while(x)
{
sum+=x%10;
x=x/10;
}
return sum;
}
int main()
{
LL x,i,j,k=0;
vector<LL> ans;
cin>>x;
i=max(x-100,0ll);
for(j=i;j<i+100;j++)
if(j+digtalsum(j)==x) ans.push_back(j);
cout<<ans.size()<<endl;
if(ans.size())
{
for(i=0;i<ans.size();i++)
cout<<ans[i]<<" ";
}
return 0;
} | true |
0c39f6d25948a5a099281b12ab8ab9275d0828ee | C++ | xczhang07/leetcode | /cpp/middle/longest_substring_without_repeating_charactors.cpp | UTF-8 | 2,549 | 3.421875 | 3 | [] | no_license | class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() <= 1)
return s.size();
int maxLen = 0;
int start = 0;
unordered_map<char, int> distance;
for(int i = 0; i < s.size(); ++i)
{
if(distance.find(s[i]) != distance.end() && distance[s[i]] > start) // the distance[s[i]] should be large than start, then we can update the new start.
start = distance[s[i]];
distance[s[i]] = i+1; // plus one because the distance means the length of the string until i position
maxLen = max(maxLen, i-start+1); //plus one because of the start idx is 0
}
return maxLen;
}
};
/*
Conclusion:
a middle level algorithm issue, which is not very easy. We have to update the index on the fly.
Time Complexity: O(n)
Space Complexity: O(n)
*/
Solution 2: using sliding window + hash_set to resolve the issue
abcabcbb
1. first round the sliding window is: abc, maxLen is 3.
2. then we find out a already exist in the hash set, we shift the sliding window, now sliding become: bca
3. when we meet some charactor already exist in the hash set, we shift the window: cab
4, sliding window is: abc
5, sliding window is: cb
6, sliding window is: b
class Solution {
public:
int lengthOfLongestSubstring(string s) {
/* maintain a sliding window */
if(s.size() <= 1)
return s.size();
int maxLen = 0;
int l = 0;
int r = 0;
unordered_set<char> visited;
while(r < s.size())
{
if(!visited.count(s[r]))
{
maxLen = max(maxLen, r-l+1);
visited.insert(s[r]);
}
else
{
while(l != r && s[l] != s[r])
{
visited.erase(s[l]);
++l;
}
++l;
}
++r;
}
return maxLen;
}
};
Solustion 3:
more efficient consistent memory
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() < 2)
return s.size();
int start = 0;
int max_len = 0;
vector<int> dict(256, 0);
for(int i = 0; i < s.size(); ++i)
{
while(dict[s[i]] == 1)
{
dict[s[start]] = 0;
++start;
}
dict[s[i]] = 1;
max_len = max(max_len, i-start+1);
}
return max_len;
}
};
| true |
54cb7117e8a1248ac2dc618e4a42ad24a8a78a40 | C++ | SV-Seeker/SeekerROV | /ROV4/CCommand.cpp | UTF-8 | 6,283 | 3.09375 | 3 | [
"MIT"
] | permissive | #include "CCommand.h"
// File local variables and methods
namespace
{
char dataBuffer[COMMAND_DATA_BUFFER_SIZE + 1]; //Add 1 for NULL terminator
byte dataBufferIndex = 0;
boolean commandReady = false;
const char endChar = ';'; // or '!', or whatever your end character is
boolean storeString = false; //This will be our flag to put the data in our buffer
TInternalCommand internalCommandBuffer[ COMMAND_MAX_COUNT ];
int internalCommandBuffer_head = 0;
int internalCommandBuffer_tail = 0;
// CRC-8 - based on the CRC8 formulas by Dallas/Maxim
// Code released under the therms of the GNU GPL 3.0 license
byte CRC8( byte start, char* data, byte len )
{
byte crc = 0x00;
for( byte j = 0; j < start; j++ )
{
*data++;
}
while( len-- )
{
byte extract = *data++;
for( byte tempI = 8; tempI; tempI-- )
{
byte sum = ( crc ^ extract ) & 0x01;
crc >>= 1;
if( sum )
{
crc ^= 0x8C;
}
extract >>= 1;
}
}
return crc;
}
boolean GetSerialString()
{
while( Serial.available() > 0 )
{
char incomingbyte = Serial.read();
// Start accumulating new string
if( storeString == false )
{
storeString = true;
dataBufferIndex = 0;
}
// If accumulating
if( storeString )
{
//Let's check our index here, and abort if we're outside our buffer size
//We use our define here so our buffer size can be easily modified
if( dataBufferIndex == COMMAND_DATA_BUFFER_SIZE )
{
//Oops, our index is pointing to an array element outside our buffer.
dataBufferIndex = 0;
break;
}
if( incomingbyte == endChar )
{
dataBuffer[dataBufferIndex++] = incomingbyte;
dataBuffer[dataBufferIndex] = 0; //null terminate the C string
storeString = false;
//Our data string is complete. return true
return true;
}
else
{
dataBuffer[dataBufferIndex++] = incomingbyte;
dataBuffer[dataBufferIndex] = 0; //null terminate the C string
}
}
else
{
}
}
//We've read in all the available Serial data, and don't have a valid string yet, so return false
return false;
}
}
// Static member initialization
int CCommand::m_arguments[COMMAND_MAX_ARGUMENTS];
char CCommand::m_text[COMMAND_DATA_BUFFER_SIZE + 1] ;
boolean CCommand::Equals( const char* targetcommand )
{
if( !commandReady )
{
return false;
}
char* pos = strstr( m_text, targetcommand );
if( pos == m_text ) //starts with
{
return true;
}
return false;
}
boolean CCommand::GetCommandString()
{
// Get string from buffer
commandReady = false;
strcpy( m_text, "" );
for( int i = 0; i < COMMAND_MAX_ARGUMENTS; i++ )
{
m_arguments[i] = 0;
}
if( GetSerialString() )
{
//String available for parsing. Parse it here
Parse();
commandReady = true;
return true;
}
if( internalCommandBuffer_head != internalCommandBuffer_tail )
{
// Advance tail index
internalCommandBuffer_tail++;
// Wrap around
if( internalCommandBuffer_tail == COMMAND_MAX_COUNT )
{
internalCommandBuffer_tail = 0;
}
// Get from the command buffer
TInternalCommand c = internalCommandBuffer[ internalCommandBuffer_tail ];
// Copy command text
strcpy( m_text, c.text );
// Check for invalid command
if( strcmp( m_text, "" ) == 0 )
{
Serial.print( F( "icmd: CMD MUNGED!;" ) );
return false;
}
// Print command
Serial.print( F( "icmd:" ) );
Serial.print( m_text );
Serial.print( '(' );
for( int i = 1; i < c.arguments[0] + 1; i++ )
{
m_arguments[i] = c.arguments[i];
if( i > 1 )
{
Serial.print( ',' );
}
Serial.print( m_arguments[i] );
}
m_arguments[0] = c.arguments[0];
//need to add the trailing # of arguments to the count or else have people do it in the call which sucks.
commandReady = true;
Serial.println( ");" );
return true;
}
return false;
}
void CCommand::PushCommand( char* cmdtext, int cmdargs[COMMAND_MAX_ARGUMENTS] )
{
// If commands are not being processed in time we overwrite the oldest ones. Technically we should probably
// have a global array for all possible commands where only the most recent is ever processed to prevent
// stale messages from floating around.
TInternalCommand c;
strcpy( c.text, cmdtext );
if( strlen( c.text ) < 1 )
{
Serial.print( F( "pushcmd: cmdtext MUNGED!;" ) );
}
for( int i = 0; i < cmdargs[0] + 1; i++ )
{
c.arguments[i] = cmdargs[i];
}
internalCommandBuffer_head++;
if( internalCommandBuffer_head == COMMAND_MAX_COUNT )
{
internalCommandBuffer_head = 0;
}
//go ahead and drop the command that has not yet been executed
if( internalCommandBuffer_head == internalCommandBuffer_tail )
{
Serial.println( F( "log: CommandBufferOverrun;" ) );
internalCommandBuffer_tail++;
}
if( internalCommandBuffer_tail == COMMAND_MAX_COUNT )
{
internalCommandBuffer_tail = 0;
}
internalCommandBuffer[internalCommandBuffer_head] = c;
}
void CCommand::Reset()
{
// Removes any state
commandReady = false;
storeString = false;
dataBufferIndex = 0;
internalCommandBuffer_head = 0;
internalCommandBuffer_tail = 0;
}
// get 'arguments' from command
void CCommand::Parse()
{
char* pch;
byte crc = 0;
byte i = 0;
crc = CRC8( 1, dataBuffer, dataBufferIndex - 1 );
Serial.print( F( "rawcmd:" ) );
byte tt = 0;
while( tt < dataBufferIndex )
{
byte zz = dataBuffer[tt];
Serial.print( zz, HEX );
Serial.print( ',' );
tt++;
}
Serial.println( ';' );
Serial.print( F( "crc:" ) );
byte testcrc = dataBuffer[0];
if( crc == testcrc )
{
Serial.print( F( "pass;" ) );
}
else
{
Serial.print( F( "fail," ) );
Serial.print( crc, HEX );
Serial.print( "/" );
Serial.print( testcrc, HEX );
Serial.print( ';' );
return;
}
char* db2 = dataBuffer;
db2++;
pch = strtok( db2, " ,();" );
while( pch != NULL )
{
if( i == 0 )
{
//this is the command text
Serial.print( F( "cmd:" ) );
Serial.print( pch );
Serial.print( '(' );
strcpy( m_text, pch );
}
else
{
//this is a parameter
m_arguments[i] = atoi( pch );
if( i > 1 )
{
Serial.print( ',' );
}
Serial.print( pch );
}
i++;
pch = strtok( NULL, " ,();" );
}
Serial.println( ");" );
m_arguments[0] = i - 1;
}
| true |
b6dc54137a79e3e09ae92c460d0f0ae7a9db87e0 | C++ | WProduction/ProjectOszi | /ProjectOszi/src/Oszi/Window.h | UTF-8 | 972 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <ozpch.h>
#include "Oszi/Core.h"
#include "Oszi/Events/Event.h"
namespace Oszi {
//Properties used to Create a Window
struct WindowProps
{
std::string Title;
unsigned int Width;
unsigned int Hight;
WindowProps(const std::string& title = "Oszi", unsigned int width = 1280, unsigned int hight = 720) : Title{ title }, Width{ width }, Hight{ hight }{}
};
//Interface representing a desktop window
class OSZI_API Window
{
public:
using EventCallbackFn = std::function<void(Event&)>;
virtual ~Window() = default;
virtual void OnUpdate() = 0;
virtual unsigned int GetWidth() const = 0;
virtual unsigned int GetHight() const = 0;
//Window attributes
virtual void SetEventCallback(const EventCallbackFn& callback) = 0;
virtual void SetVSync(bool enabled) = 0;
virtual bool IsVSync() const = 0;
virtual void* GetNativeWindow() const = 0;
static Window* Create(const WindowProps& props = WindowProps());
};
} | true |
cd90009e2f379c15b8726b45ae79d4cd904dd1bb | C++ | ahmad307/Visual-DataStructures | /DataStructures/DataStructures/BST/BST.cpp | UTF-8 | 8,987 | 2.875 | 3 | [] | no_license | #include "BST.h"
template<class T>
node<T>::node(T value, sf::Texture * nodeTexture, float radius)
{
this->value = value;
left = right = nullptr;
Circle.setTexture(nodeTexture);
Circle.setRadius(radius);
Circle.setFillColor(sf::Color(43, 62, 80));
Circle.setOutlineColor(sf::Color::Black);
Circle.setOutlineThickness(7.0f);
text.setString(to_string(value));
text.setFillColor(sf::Color::White);
text.setStyle(sf::Text::Bold);
}
template<class T>
sf::Vector2f node<T>::getposition()
{
return Circle.getPosition();
}
template<class T>
void node<T>::Reposition(sf::Vector2f newPos)
{
Circle.setPosition(newPos);
text.setPosition(sf::Vector2f(newPos.x + Circle.getRadius() * 3 / 4, newPos.y + Circle.getRadius() / 2));
}
template<class T>
BST<T>::BST(sf::RenderWindow & window, sf::View & view)
{
this->window = &window;
newpos[0][0] = sf::Vector2f(0.0f, 0.0f), newpos[0][1] = sf::Vector2f(0.0f, 0.0f);
newpos[1][0] = sf::Vector2f(-200.0f, 300.0f), newpos[1][1] = sf::Vector2f(200.0f, 300.0f);
newpos[2][0] = sf::Vector2f(-300.0f, 250.0f), newpos[2][1] = sf::Vector2f(300.0f, 250.0f);
newpos[3][0] = sf::Vector2f(-600.0f, 300.0f), newpos[3][1] = sf::Vector2f(600.0f, 300.0f);
newpos[4][0] = sf::Vector2f(-1200.0f, 400.0f), newpos[4][1] = sf::Vector2f(1200.0f, 400.0f);
newpos[5][0] = sf::Vector2f(-2400.0f, 800.0f), newpos[5][1] = sf::Vector2f(2400.0f, 800.0f);
newpos[6][0] = sf::Vector2f(-4800.0f, 1600.0f), newpos[6][1] = sf::Vector2f(4800.0f, 1600.0f);
newpos[7][0] = sf::Vector2f(-9600.0f, 3200.0f), newpos[7][1] = sf::Vector2f(9600.0f, 3200.0f);
this->view = &view;
font.loadFromFile("arial_font/arial.ttf");
title.setString("Binary Search Tree");
title.setStyle(sf::Text::Bold | sf::Text::Underlined);
title.setFont(font);
title.setColor(sf::Color::Black);
title.setCharacterSize(45);
title.setPosition(sf::Vector2f(-150.0f, -100.0f));
pre_order.setString("preOrder: ");
pre_order.setStyle(sf::Text::Bold);
pre_order.setFont(font);
pre_order.setColor(sf::Color::Black);
pre_order.setCharacterSize(45);
pre_order.setPosition(sf::Vector2f(300.0f, -100.0f));
post_order.setString("postOrder: ");
post_order.setStyle(sf::Text::Bold);
post_order.setFont(font);
post_order.setColor(sf::Color::Black);
post_order.setCharacterSize(45);
post_order.setPosition(sf::Vector2f(300.0f, -200.0f));
in_order.setString("inOrder: ");
in_order.setStyle(sf::Text::Bold);
in_order.setFont(font);
in_order.setColor(sf::Color::Black);
in_order.setCharacterSize(45);
in_order.setPosition(sf::Vector2f(300.0f, -300.0f));
root = light = nullptr;
}
template<class T>
void BST<T>::HandleInput()
{
if (root != nullptr && sf::Keyboard::isKeyPressed(sf::Keyboard::A) && light->left != nullptr)
{
light = light->left;
}
if (root != nullptr && sf::Keyboard::isKeyPressed(sf::Keyboard::D) && light->right != nullptr)
{
light = light->right;
}
if (root != nullptr && sf::Keyboard::isKeyPressed(sf::Keyboard::W) && getParent(light) != nullptr)
{
light = getParent(light);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1) || sf::Keyboard::isKeyPressed(sf::Keyboard::Numpad1))
{
cout << "Enter the number of entries: ";
int size; cin >> size;
for (int i = 0; i < size; i++)
{
T value;
cout << "Enter value: ";
cin >> value;
insert(value);
}
cout << "*****************\n";
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num2) || sf::Keyboard::isKeyPressed(sf::Keyboard::Numpad2))
{
traverse();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num3) || sf::Keyboard::isKeyPressed(sf::Keyboard::Numpad3))
{
Balance();
}
}
template<class T>
void BST<T>::insert(T value)
{
if (root == nullptr)
{
root = new node<T>(value, nullptr, 50.0f);
root->Reposition(sf::Vector2f(0.0f, 0.0f));
light = root;
return;
}
node<T>* temp = root;
while (true)
{
if (value > temp->value)
{
if (temp->right == nullptr)
{
if (getheight(root) - getheight(temp) == 7)
{
cout << "Canot Add:(\n";
return;
}
temp->right = new node<T>(value, nullptr, 50.0f);
break;
}
temp = temp->right;
}
else if (value < temp->value)
{
if (temp->left == nullptr)
{
if (getheight(root) - getheight(temp) == 7)
{
cout << "Canot Add:(\n";
return;
}
temp->left = new node<T>(value, nullptr, 50.0f);
break;
}
temp = temp->left;
}
else
{
return;
}
}
}
template<class T>
void BST<T>::draw()
{
window->draw(title);
window->draw(pre_order);
window->draw(in_order);
window->draw(post_order);
drawNodes(root);
}
template<class T>
void BST<T>::drawNodes(node<T>* current)
{
if (current == nullptr)
return;
if (current == light)
{
sf::CircleShape circle = current->Circle;
circle.setFillColor(sf::Color::Yellow);
view->setCenter(current->Circle.getPosition());
window->draw(circle);
window->setView(*view);
sf::Text text = current->text;
text.setFont(font);
text.setFillColor(sf::Color::Red);
window->draw(text);
}
else
{
window->draw(current->Circle);
sf::Text text = current->text;
text.setFont(font);
window->draw(text);
}
int height = getheight(current) - 1;
if (current->right != nullptr)
{
current->right->Reposition(current->Circle.getPosition() + newpos[height][1]);
drawArrow(current->Circle.getPosition().x + 2 * current->Circle.getRadius(), current->Circle.getPosition().y + 2 * current->Circle.getRadius(),
current->right->Circle.getPosition().x, current->right->Circle.getPosition().y);
drawNodes(current->right);
}
if (current->left != nullptr)
{
current->left->Reposition(current->Circle.getPosition() + newpos[height][0]);
drawArrow(current->Circle.getPosition().x, current->Circle.getPosition().y + 2 * current->Circle.getRadius(),
current->left->Circle.getPosition().x + 2 * current->left->Circle.getRadius(), current->left->Circle.getPosition().y);
drawNodes(current->left);
}
}
template<class T>
void BST<T>::drawArrow(float x1, float y1, float x2, float y2)
{
sf::RectangleShape Line;
Line.setSize(sf::Vector2f(sqrt(pow(x1 - x2, 2) + pow(y2 - y1, 2)), 10.0f));
Line.setPosition(sf::Vector2f(x1, y1));
Line.setFillColor(sf::Color::Black);
float slope = (y2 - y1) / (x2 - x1);
float PI = 3.14159265;
if (slope > 0)
Line.setRotation((atan(slope) * 180) / PI);
else if (slope < 0)
Line.setRotation(-(180 - (atan(slope) * 180) / PI));
window->draw(Line);
}
template<class T>
node<T>* BST<T>::getParent(node<T>* search)
{
node<T>* temp = root;
while (true)
{
if (search->value > temp->value)
{
if (temp->right == search)
return temp;
temp = temp->right;
}
else if (search->value < temp->value)
{
if (temp->left == search)
return temp;
temp = temp->left;
}
else
{
return nullptr;
}
}
}
template<class T>
int BST<T>::getheight(node<T>* current)
{
if (current == nullptr)
return 0;
return (1 + max(getheight(current->left), getheight(current->right)));
}
template<class T>
void BST<T>::traverse()
{
pre_order.setString("preOrder: ");
in_order.setString("inOrder: ");
post_order.setString("postOrder: ");
preOrder(root);
light = root;
waiting(3.0f);
postOrder(root);
light = root;
waiting(3.0f);
inOrder(root);
light = root;
}
template<class T>
void BST<T>::preOrder(node<T>* curr)
{
if (curr == nullptr)
return;
pre_order.setString(pre_order.getString() + " " + to_string(curr->value));
light = curr;
waiting(1.0f);
preOrder(curr->left);
preOrder(curr->right);
}
template<class T>
void BST<T>::inOrder(node<T>* curr)
{
if (curr == nullptr)
return;
inOrder(curr->left);
in_order.setString(in_order.getString() + " " + to_string(curr->value));
light = curr;
waiting(1.0f);
inOrder(curr->right);
}
template<class T>
void BST<T>::postOrder(node<T>* curr)
{
if (curr == nullptr)
return;
postOrder(curr->left);
postOrder(curr->right);
post_order.setString(post_order.getString() + " " + to_string(curr->value));
light = curr;
waiting(1.0f);
}
template<class T>
void BST<T>::waiting(float time)
{
sf::Clock clock;
while (clock.getElapsedTime().asSeconds() <= time)
{
window->clear(sf::Color::White);
draw();
window->display();
}
}
template<class T>
void BST<T>::Balance()
{
MyNodes.clear();
getVector(root);
clear(root);
root = nullptr;
sort(MyNodes.begin(), MyNodes.end());
DivideAndConquer(0, MyNodes.size() - 1);
}
template<class T>
void BST<T>::getVector(node<T>* current)
{
if (current == nullptr)
return;
MyNodes.push_back(current->value);
getVector(current->left);
getVector(current->right);
}
template<class T>
void BST<T>::DivideAndConquer(int start, int End)
{
if (start > End)
return;
int midd = (start + End) / 2;
insert(MyNodes[midd]);
DivideAndConquer(start, midd - 1);
DivideAndConquer(midd + 1, End);
}
template<class T>
void BST<T>::clear(node<T>* current)
{
if (current == nullptr)
return;
clear(current->right);
clear(current->left);
delete current;
}
template<class T>
BST<T>::~BST()
{
clear(root);
} | true |
9220e3608e72aa6931558f0cc4c201e8cecc8d7a | C++ | yisonPylkita/lonesome | /logger.cpp | UTF-8 | 416 | 2.578125 | 3 | [] | no_license | #include "logger.hpp"
namespace Engine {
namespace Logger {
_Logger::_Logger(const std::string & file_name)
{
log_file.open(file_name.c_str());
}
_Logger::~_Logger()
{
log_file.close();
}
void _Logger::log(std::string log_message)
{
log_file << "LOG MESSAGE: " << log_message << std::endl;
}
}
}
| true |
5b6718f86f591ea26402441418a55d3967bc5e1e | C++ | bradley27783/Concurrent-Parallel-and-Distributed-Programming | /Portfolios/Parallel/Task3/t3.cpp | UTF-8 | 1,512 | 2.890625 | 3 | [] | no_license | #include "omp.h"
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include "stdio.h"
#include <vector>
#include <random>
std::vector<std::vector<int>> matrix = {{5,14,10},
{7,-8,-14},
{-2,9,8},
{15,-6,3},
{12,4,-5},
{4,20,17},
{-16,5,-1},
{-11,3,16},
{3,10,-19},
{-16,7,4}};
void printMatrix(){
for(unsigned int j = 0; j < matrix.size(); j++){
std::cout << "Vector: " << j << " " << "Values: " << std::flush;
for(unsigned int i = 0; i < matrix[j].size(); i++){
std::cout << matrix[j][i] << " " << std::flush;
}
std::cout << std::endl;
}
}
int main (void)
{
for(unsigned int j = 0; j <= 10; j++){
if(j == 0 || j == 5 || j == 10){
std::cout << std::endl << "Step " << j << std::endl;
printMatrix();
}
#pragma omp parallel for schedule(runtime)
for(unsigned int i = 0; i < matrix.size(); i++){
int randomNum = rand() % 3; //Random number between 0 and 2
bool increment = rand() % 2; //Random number between 0 and 1
if(increment){
++matrix[i][randomNum];
}
else{
--matrix[i][randomNum];
}
}
}
return 0;
}; | true |
fe7706891c2edffad7c20a51df270833f6d01961 | C++ | chrinide/vowpal_wabbit | /library/library_example.cc | UTF-8 | 2,445 | 2.59375 | 3 | [] | no_license | #include <stdio.h>
#include "../vowpalwabbit/parser.h"
#include "../vowpalwabbit/vw.h"
inline feature vw_feature_from_string(VW::workspace& v, std::string fstr, unsigned long seed, float val)
{ auto foo = VW::hash_feature(v, fstr, seed);
feature f = { val, foo};
return f;
}
int main(int argc, char *argv[])
{
VW::workspace* model = VW::initialize("--hash all -q st --noconstant -f train2.vw --no_stdin");
example *vec2 = VW::read_example(*model, (char*)"|s p^the_man w^the w^man |t p^un_homme w^un w^homme");
model->learn(*vec2);
std::cerr << "p2 = " << vec2->pred.scalar << std::endl;
VW::finish_example(*model, *vec2);
VW::primitive_feature_space features[2];
VW::primitive_feature_space *s = features, *t = features + 1;
s->name = 's';
t->name = 't';
uint32_t s_hash = static_cast<uint32_t>(VW::hash_space(*model, "s"));
uint32_t t_hash = static_cast<uint32_t>(VW::hash_space(*model, "t"));
s->fs = new feature[3];
s->len = 3;
t->fs = new feature[3];
t->len = 3;
s->fs[0] = vw_feature_from_string(*model, "p^the_man", s_hash, 1.0);
s->fs[1] = vw_feature_from_string(*model, "w^the", s_hash, 1.0);
s->fs[2] = vw_feature_from_string(*model, "w^man", s_hash, 1.0);
t->fs[0] = vw_feature_from_string(*model, "p^le_homme", t_hash, 1.0);
t->fs[1] = vw_feature_from_string(*model, "w^le", t_hash, 1.0);
t->fs[2] = vw_feature_from_string(*model, "w^homme", t_hash, 1.0);
example* vec3 = VW::import_example(*model, "", features, 2);
model->learn(*vec3);
std::cerr << "p3 = " << vec3->pred.scalar << std::endl;
// TODO: this does not invoke m_vw->l->finish_example()
VW::finish_example(*model, *vec3);
VW::finish(*model);
VW::workspace* model2 = VW::initialize("--hash all -q st --noconstant -i train2.vw --no_stdin");
vec2 = VW::read_example(*model2, (char*)" |s p^the_man w^the w^man |t p^un_homme w^un w^homme");
model2->learn(*vec2);
std::cerr << "p4 = " << vec2->pred.scalar << std::endl;
size_t len=0;
VW::primitive_feature_space* pfs = VW::export_example(*model2, vec2, len);
for (size_t i = 0; i < len; i++)
{ std::cout << "namespace = " << pfs[i].name;
for (size_t j = 0; j < pfs[i].len; j++)
std::cout << " " << pfs[i].fs[j].weight_index << ":" << pfs[i].fs[j].x << ":" << VW::get_weight(*model2, static_cast<uint32_t>(pfs[i].fs[j].weight_index), 0);
std::cout << std::endl;
}
VW::finish_example(*model2, *vec2);
VW::finish(*model2);
}
| true |
a2e748e0a22ceadbef78c041a186b901d5a0f27d | C++ | root670/dance-pad | /Firmware/lib/firmware/src/Sensor.h | UTF-8 | 1,033 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <Arduino.h>
#include "Config.h"
class Sensor
{
public:
Sensor(uint8_t nPin);
// Set the thresholds based on the most recent reading
void calibrate();
// Read value from pin
void readSensor();
// Update state of the sensor
void update();
bool isPressed()const;
uint16_t getPressure()const;
uint16_t getTriggerThreshold()const;
uint16_t getReleaseThreshold()const;
uint8_t getPin()const;
private:
uint8_t m_nPin;
uint16_t m_nPressure;
uint16_t m_nTriggerOffset; // Amount above the baseline to trigger a hit.
uint16_t m_nReleaseOffset; // Amount above the baseline to trigger a release.
String m_strTriggerOffsetSetting; // Config name for trigger offset
String m_strReleaseOffsetSetting; // Config name for trigger offset setting
uint16_t m_nTriggerThreshold; // Absolute value to trigger a hit.
uint16_t m_nReleaseThreshold; // Absolute value to trigger a release.
uint64_t m_nLastChangeTimeMS;
bool m_bPressed;
};
| true |
5442477fffd58dd47e964900e78230237bfd0b88 | C++ | OfficialPouya/Safety_Suite_For_Electric_Longboard | /DEV Work/board_dev/board_battery_mimick/1way_remote.ino | UTF-8 | 1,793 | 2.5625 | 3 | [] | no_license | #include <SPI.h>
#include "RF24.h"
#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
RF24 myRadio (9, 10);
byte addresses[][6] = {"0"};
unsigned long lastTransmission;
// typedef struct package Package;
// Package dataTransmit;
byte dead_man_pin = 5;
byte red_led = 2;
byte yellow_led = 2;
byte green_led = 2;
int throttle = A1;
char str[11];
U8G2_SSD1306_128X32_UNIVISION_F_HW_I2C u8g2(U8G2_R0);
void setup() {
// Serial.begin(115200);
u8g2.begin();
delay(1000);
pinMode(red_led, OUTPUT);
pinMode(yellow_led, OUTPUT);
pinMode(green_led, OUTPUT);
pinMode(dead_man_pin, INPUT_PULLUP);
myRadio.begin();
myRadio.setChannel(115);
myRadio.setPALevel(RF24_PA_MAX);
myRadio.setDataRate(RF24_250KBPS);
myRadio.openWritingPipe(addresses[0]);
}
void loop() {
// read the value of POT
throttle = analogRead(A1);
// If dead man is triggered send value of POT, otherwise send
// 512 (the middle val of potentiometer)
if (digitalRead(dead_man_pin) == 0){throttle = throttle;}
else{throttle = 512;}
transmit_to_board();
update_screen();
}
void transmit_to_board(){
// Transmit once every 50 millisecond
if (millis() - lastTransmission >= 50) {
lastTransmission = millis();
boolean sendSuccess = false;
// Transmit the speed value (0-1024).
myRadio.write(&throttle, sizeof(throttle));
}
}
void update_screen(){
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
u8g2.drawStr(0,10, throttle); // write speed value
u8g2.sendBuffer(); // transfer internal memory to the display
}
| true |
cc76da19d7ea2017b0e91d1e7568d7068a03dc50 | C++ | melshazly89/Algo_ToolBox | /week3_greedy_algorithms/6_maximum_salary/largest_number.cpp | UTF-8 | 938 | 3.296875 | 3 | [] | no_license | #include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
string largest_number(vector<string> a) {
int temp;
std::vector<int> b;
for (int i=0; i< a.size(); i++)
{
int num = atoi(a.at(i).c_str());
while(num)
{
b.push_back(num%10);
num /= 10;
}
}
for (int i = 0; i < b.size(); i++)
{
for (int j = 0; j < b.size(); j++)
{
if(b[i]>b[j])
{
temp=b[i];
b[i]=b[j];
b[j]=temp;
}
}
}
std::stringstream ret;
for (size_t i = 0; i < b.size(); i++) {
ret << b[i];
}
string result;
ret >> result;
return result;
}
int main() {
int n;
std::cin >> n;
vector<string> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
std::cout << largest_number(a);
} | true |
34cfd4ad227f7bd6017d0863fe081da89f78155a | C++ | meister4ever/mi-biografia | /src/domain_AutorId.h | UTF-8 | 659 | 2.6875 | 3 | [] | no_license | #ifndef DOMAIN_AUTORID_H_INCLUDED
#define DOMAIN_AUTORID_H_INCLUDED
#include "logica_Comparable.h"
#include <iostream>
class AutorId : public Comparacion {
public:
AutorId(const char* autor, int id);
AutorId();
virtual ~AutorId();
virtual int comparar(Comparacion *c) const;
int getId() const;
void setId(int newId) ;
const char* getAutor() const;
friend std::istream& operator >> (std::istream &out, AutorId &ocur);
friend std::ostream& operator << (std::ostream &out, AutorId &ocur);
private:
char autor[100];
int id;
};
#endif // DOMAIN_AUTORID_H_INCLUDED
| true |
b4ddf232e40093ab827854eb8dabdf5fe1e94bab | C++ | CdecPGL/PlanetaEngine | /PlanetaEngine/src/planeta/core/Matrix2_2.hpp | UTF-8 | 1,030 | 2.90625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <array>
#include "Vector2D.hpp"
namespace plnt {
namespace math {
//2*2行列
template<typename T>
struct Matrix2_2 {
std::array<std::array<T, 2>, 2> lines;
std::array<T, 2>& operator[](int l) {
return lines[l];
}
constexpr const std::array<T, 2>& operator[](int l)const {
return lines[l];
}
};
//行列関数
//線形変換
template<typename T>
Vector2D<T> LinearTransformation(const Matrix2_2<T>& m, const Vector2D<T>& v) {
return Vector2D<T>(m[0][0] * v.x + m[1][0] * v.y, m[0][1] * v.x + m[1][1] * v.y);
}
//回転変換
template<typename T>
Vector2D<T> RotationalTransformation(double rota_rad, const Vector2D<T>& v) {
Matrix2_2<T> m;
m[0][0] = (T)cos(rota_rad);
m[1][0] = -(T)sin(rota_rad);
m[0][1] = (T)sin(rota_rad);
m[1][1] = (T)cos(rota_rad);
return LinearTransformation(m, v);
}
}
using Matrix2_2d = math::Matrix2_2<double>;
using Matrix2_2f = math::Matrix2_2<float>;
using Matrix2_2i = math::Matrix2_2<int32_t>;
}
| true |
3557a4a8b7603cefab71d19c13ccf00fb9cfee19 | C++ | liujun0603/option-hedge | /StrategyConstructible.h | UTF-8 | 1,364 | 3.09375 | 3 | [] | no_license | //
//
// StrategyConstructible.h
//
//
#ifndef STRATEGY_CONSTRUCTIBLE_H
#define STRATEGY_CONSTRUCTIBLE_H
#include <iostream>
#include "StrategyFactory.h"
#include <string>
//for each Strategy class, we declare a global variable of StrategyHelper<kind of Strategy>
// , which create the function that can return *Strategy and the pointer to the function
// , and registers the Strategy class with our factory
// (all global variables are intialized when the program begins before anything)
//get each Strategy class to communicate with the factory
// , without explicitly calling anything from the main routine
template <class T>
class StrategyHelper
{
public:
StrategyHelper(std::string);
//static: should not be associated with any particular object
static Strategy* Create(const wrapper<VanillaOption>&,const wrapper<Stock>&,double,double,unsigned long);
};
template <class T>
Strategy* StrategyHelper<T>::Create(const wrapper<VanillaOption>& Option,const wrapper<Stock>& Stock,double r,double d,unsigned long interval)
{
return new T(Option,Stock,r,d,interval);
}
template <class T>
StrategyHelper<T>::StrategyHelper(std::string id)
{
StrategyFactory& theStrategyFactory = StrategyFactory::Instance();
theStrategyFactory.RegisterStrategy(id, StrategyHelper<T>::Create);
}
#endif | true |
2ed902b9497eab66fa2449a49aaf4d5625aad4e2 | C++ | hosword/Study-Practice-Collection | /20150410SqHuiWen/SqHuiWen/Main.cpp | GB18030 | 755 | 2.90625 | 3 | [] | no_license | #include "SqStack.h"
#include "SqQueue.h"
#include <string>
#include <iostream>
using namespace std;
void HuiWen()
{
char str[MAXQSIZE];
cin >> str;
SqStack S1;
InitStack(S1);
SqQueue S2;
InitQueue(S2);
SElemType e1;
QElemType e2;
int len = strlen(str),i=0,temp1,temp2;
for (i = 0; i < len; i++){
Push(S1, str[i]);
EnQueue(S2, str[i]);
}
while (QueueEmpty(S2) && StackEmpty(S1)){
Pop(S1, e1);
temp1 = e1;
DeQueue(S2, e2);
temp2 = e2;
if (temp1 != temp2){
cout << "ǻ" << endl;
return;
}
}
cout << "ǻ" << endl;
}
void main()
{
int choice=1 ;
cout << "ҪԵַ" << endl;
while (choice){
HuiWen();
cout << "ҪԵַ" << endl;
}
} | true |
483ae802f5434d4e81f2b50e66367ae654d5c7c9 | C++ | Rillell/1_Grade_Project | /c언어/C언어 2학기/실습/0903/0903/0903-1.cpp | UHC | 212 | 2.828125 | 3 | [] | no_license | #include<stdio.h>
void main()
{
int num;
printf(" : ");
scanf("%d", &num);
if (num % 2 == 0)
{
printf(" ¦Դϴ.\n");
}
else
{
printf(" ȦԴϴ.\n");
}
} | true |
abffb033f0ca2c8fc152639033bfbc6d090e6531 | C++ | Rostik18/Homework-University | /FirstSecondYear/Cplusplus/1 семестр/B_10/B_10/B10.cpp | UTF-8 | 503 | 2.828125 | 3 | [] | no_license | // B10.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <math.h>>
using namespace std;
int main() {
int q = 1;
do {
double n, S = 0;
do {
cout << "Enter n : ";
cin >> n;
} while (n < 1);
int m = n;
for (int i = 0; i < n; i++) {
S = S + 1.0 / m;
m--;
}
cout << "S = " << S;
cout << "\npress 1 or 0 to exed: ";
cin >> q;
} while (q == 1);
return 0;
} | true |
bdbbb9df2d711fddd28c779f54896c0fcea550df | C++ | benreid24/BLIB | /include/BLIB/Util/Signal.hpp | UTF-8 | 2,923 | 3.234375 | 3 | [] | no_license | #ifndef BLIB_UTIL_SIGNAL_HPP
#define BLIB_UTIL_SIGNAL_HPP
#include <BLIB/Util/NonCopyable.hpp>
#include <functional>
#include <optional>
#include <variant>
#include <vector>
namespace bl
{
namespace util
{
/**
* @brief Utility class perform callback actions on events. Can be configured to perform
* multiple callbacks. Includes a helper method to simply set a boolean variable
*
* @tparam CallbackArgs Function signature of callbacks
* @ingroup Util
*
*/
template<typename... CallbackArgs>
class Signal : public NonCopyable {
public:
/**
* @brief Callback function signature for a Signal
*
*/
typedef std::function<void(CallbackArgs&&...)> Callback;
/**
* @brief When triggered, the Signal will set the given flag to the given value
*
* @param var The flag to set
* @param val The value to set the flag to
*/
void willSet(bool& var, bool val = true);
/**
* @brief When triggered, the Signal will call the provided callback
*
* @param cb The function to call on trigger
*/
void willCall(const Callback& cb);
/**
* @brief Set up a callback for always being called. Intended to be used by derived classes
* Callbacks set by this are not cleared by clear()
*
* @param cb The method to call when the signal is fired
*/
void willAlwaysCall(const Callback& cb);
/**
* @brief Clears any set or call actions
*
*/
void clear();
/**
* @brief Triggers the signal. This may be manually done to simulate input
*
* @param action The action that triggered the Singal
* @param id The Element that triggered the Signal
*/
void operator()(CallbackArgs&&... args);
private:
std::vector<std::pair<bool*, bool>> setActions;
std::vector<Callback> userCallbacks;
std::vector<Callback> internalCallbacks;
};
//////////////////////////// INLINE FUNCTIONS /////////////////////////////////
template<typename... CallbackArgs>
void Signal<CallbackArgs...>::willSet(bool& var, bool val) {
setActions.push_back(std::make_pair(&var, val));
}
template<typename... CallbackArgs>
void Signal<CallbackArgs...>::willCall(const Callback& cb) {
userCallbacks.push_back(cb);
}
template<typename... CallbackArgs>
void Signal<CallbackArgs...>::willAlwaysCall(const Callback& cb) {
internalCallbacks.push_back(cb);
}
template<typename... CallbackArgs>
void Signal<CallbackArgs...>::clear() {
setActions.clear();
userCallbacks.clear();
}
template<typename... CallbackArgs>
void Signal<CallbackArgs...>::operator()(CallbackArgs&&... args) {
for (const auto& set : setActions) { *set.first = set.second; }
for (const auto& cb : userCallbacks) { cb(std::forward<CallbackArgs>(args)...); }
for (const auto& cb : internalCallbacks) { cb(std::forward<CallbackArgs>(args)...); }
}
} // namespace util
} // namespace bl
#endif
| true |
f6909fb60557d290154f548cf7c41296350ae0af | C++ | czipobence/dp-gyakorlat | /1Gyak/10.cpp | UTF-8 | 169 | 2.953125 | 3 | [] | no_license | //take the first H element of the list
list take(const list L, const int H) {
if (L == nil) return L;
if (H == 0) return nil;
return cons(hd(L), take(tl(L), H-1));
}
| true |
f81b53c4b1adb715fd3b22e3a7889dcbcfb4de13 | C++ | eduhirt/CG | /t1/SCV 4.2.2 CodeBlocks/SCV/src/ComponentSpring.cpp | UTF-8 | 1,778 | 2.734375 | 3 | [
"BSD-2-Clause"
] | permissive | #include "SCV/stdafx.h"
#include "SCV/ComponentSpring.h"
namespace scv {
ComponentSpring::ComponentSpring(Component *component, int min, int pref, int max) : Spring() {
_component = component;
_min = min;
_pref = pref;
_max = max;
}
int ComponentSpring::calculateMinimumSize(Axis axis) {
if (!isVisible()) {
return 0;
}
if (_min >= 0) {
return _min;
}
if (_min == PREFERRED_SIZE) {
return calculatePreferredSize(axis);
}
assert (_min == DEFAULT_SIZE);
return getSizeAlongAxis(axis, _component->getMinimumSize());
}
int ComponentSpring::calculatePreferredSize(Axis axis) {
if (!isVisible()) {
return 0;
}
if (_pref >= 0) {
return _pref;
}
assert (_pref == DEFAULT_SIZE || _pref == PREFERRED_SIZE);
return getSizeAlongAxis(axis, _component->getPreferredSize());
}
int ComponentSpring::calculateMaximumSize(Axis axis) {
if (!isVisible()) {
return 0;
}
if (_max >= 0) {
return _max;
}
if (_max == PREFERRED_SIZE) {
return calculatePreferredSize(axis);
}
assert (_max == DEFAULT_SIZE);
return getSizeAlongAxis(axis, _component->getMaximumSize());
}
void ComponentSpring::setSize(Axis axis, int origin, int size) {
Spring::setSize(axis, origin, size);
switch (axis) {
case Spring::HORIZONTAL:
_component->setRelativePosition(Point(origin, _component->getRelativePosition().y));
_component->setWidth(size);
break;
case Spring::VERTICAL:
_component->setRelativePosition(Point(_component->getRelativePosition().x, origin));
_component->setHeight(size);
break;
}
}
int ComponentSpring::getSizeAlongAxis(Axis axis, scv::Point size) {
return (axis == HORIZONTAL)? size.x : size.y;
}
} //namespace scv
| true |
f770b033b4b1f786aa03d174f43208f041bd8849 | C++ | lww296/Kernel | /include/IDBHelper.h | UTF-8 | 3,359 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef __I_DB_HELPER_H__
#define __I_DB_HELPER_H__
#include "Types.h"
enum DbHelperStatus
{
HELPER_STATUS_NULL, // 无效状态
HELPER_STATUS_INIT, // 初始化
HELPER_STATUS_CONNECTING, // 正在连接
HELPER_STATUS_CONNECTED, // 已连接
HELPER_STATUS_FREE, // 空闲(可使用)
HELPER_STATUS_IDLE, // 忙
HELPER_STAUTS_STOP, // 停止
HELPER_STATUS_MAX,
};
/// @Brief 数据库助手接口类
class _KERNEL_EXPORTS IDBHelper
{
public:
virtual ~IDBHelper() { }
/// @function 初始化
///
/// @param poolName 池名称
/// @param dbName 数据库名称
/// @param addrInfo 地址信息
/// @return 连接成功返回true, 失败返回false
virtual bool Init(string poolName, string dbName, string addrInfo = "") = 0;
/// @function 获取数据库名称
///
/// @return 返回dbname
virtual string GetDbName() = 0;
/// @function 获取地址信息
///
/// @return 返回助手地址信息
virtual string GetHelperAddrInfo() = 0;
/// @function 设置状态
///
/// @param status 状态
virtual void SetStatus(DbHelperStatus status) = 0;
/// @function 获取助手编号
///
/// @return 返回助手编号
virtual int GetHelperNO() = 0;
/// @function 设置助手编号
///
/// @param no 助手编号
virtual void SetHelperNO(int no) = 0;
/// @function 获取状态
///
/// @return 返回状态
virtual DbHelperStatus GetStatus() = 0;
/// @function 建立连接
///
/// @param info 连接字符串
/// @return 成功返回true
virtual bool Connect(const char* info) = 0;
/// @function 建立连接
///
/// @param hostname : 主机名
/// @param port 端口
/// @return 成功返回true
virtual bool Connect(const char* hostname, unsigned short port) = 0;
/// @function 连接数据库
/// @param hostname : 主机名
/// @param user : 登录数据库用户
/// @param passwd : 登录数据库密码
/// @param dbname : 数据库名字
/// @return 成功返回true
virtual bool Connect(const char *hostname, const char *user, const char *passwd, const char *dbname) = 0;
/// @function 关闭连接
///
virtual void Close() = 0;
/// @function 执行sql
///
/// @param cmd sql语句 or 存储过程名称
/// @param isProc 执行的是否是存储过程
/// @param isStore 是否存储记录集
/// @return 返回执行结果,成功返回true
virtual bool Execute(const char* cmd, bool isProc, bool isStore) = 0;
/// @function 获取记录集行数量
///
/// @retrn 返回行数量
virtual long GetRows() = 0;
/// @function 获取记录集列数量
///
/// @return 返回列数量
virtual unsigned int GetConlums() = 0;
/// @function 移动到下一个记录行
///
virtual void MoveNext() = 0;
/// @function 是否是记录集尾部
///
/// @return 是返回true
virtual bool IsRecordsEnd() = 0;
/// @function 重置记录集
///
virtual void ResetRecordset() = 0;
/// @function 返回影响的行数
///
/// @return 返回结果
virtual unsigned long long GetAffectedRows() = 0;
/// @function 数据偏移
///
/// @param offset 偏移
virtual void DataSeek(unsigned long long offset) = 0;
/// @function 列偏移
///
/// @param offset 偏移
/// @return 返回实际偏移了多少列
virtual unsigned int FieldSeek(unsigned int offset) = 0;
}; // end by IDBHelper
#endif //__I_DB_HELPER_H__
| true |
a510e58fa63b7f802c91a92e88794587a2a89b87 | C++ | almost7/Csharp | /C#/repos/Classe Conta/Classe Conta/Conta.cpp | UTF-8 | 1,320 | 3.5 | 4 | [] | no_license | #include "Conta.h"
Conta::Conta() {
Titular = "sem nome";
Numero = 0;
Saldo = 0;
Estado = -1;
}
Conta::Conta(string t, int n) {
Titular = t;
Numero = n;
Saldo = 0;
Estado = 1;
}
Conta::Conta(const Conta &c) {
Titular = c.Titular;
Numero = c.Numero;
Saldo = c.Saldo;
Estado = c.Estado;
}
void Conta::setTitular(string t) {
Titular = t;
}
void Conta::setNumero(int n) {
Numero = n;
}
/*void Conta::setSaldo(double s) {
Saldo = s;
}
void Conta::setEstado(int e) {
Estado = e;
}*/
string Conta::getTitular() {
return Titular;
}
int Conta::getNumero() {
return Numero;
}
double Conta::getSaldo() {
return Saldo;
}
int Conta::getEstado() {
return Estado;
}
string Conta::toString() {
return "Conta: \nTitular: " + Titular + "\nNumero: " + to_string(Numero) + "\nSaldo: " + to_string(Saldo) + "\nEstado: " + to_string(Estado) + "\n";
}
int Conta::levantar(double s) {
if (Saldo - s < 0)
return -1;
Saldo -= s;
return 0;
}
int Conta::depositar(double s) {
if (s < 0)
return -1;
Saldo += s;
return 0;
}
void Conta::alterarEstado() {
if (Estado == -1)
Estado = 1;
if (Estado == 1)
Estado = -1;
}
double Conta::credito() {
if (Saldo < 500)
return 0;
if (Saldo < 1000)
return Saldo * 0.1;
if (Saldo < 5000)
return Saldo * 0.3;
if (Saldo >= 5000)
return Saldo * 0.5;
} | true |
48ac6fed39e693b682a38e273e27e734426d5b64 | C++ | mzlogin/LeetCode | /algorithms/cpp/sumOfTwoIntegers/solution.h | UTF-8 | 848 | 3.75 | 4 | [
"MIT"
] | permissive | /**
* Source : https://leetcode.com/problems/sum-of-two-integers/
* Author : Zhuang Ma
* Email : chumpma(at)gmail.com
* Date : 2016-11-02
* */
/**
* Problem:
* Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
*
* Example:
* Given a = 1 and b = 2, return 3.
*/
class Solution {
public:
// a + b = (a ^ b) + ((a & b) << 1)
// ^ ------- --------------
// | | |
// | v v
// | new a new b
// | | |
// | +-----+------+
// | |
// +--------------+
// iteration until b == 0
int getSum(int a, int b) {
while (b) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};
| true |
b0ae7eb21272ad708d595a4eaa50d257e5e997f0 | C++ | pelcointegrations/VxSdk.NET | /VxSdkNet/Include/AnalyticConfig.h | UTF-8 | 4,366 | 2.8125 | 3 | [] | no_license | // Declares the analytic config class.
#ifndef AnalyticConfig_h__
#define AnalyticConfig_h__
#include "VxSdk.h"
#include "Resolution.h"
#include "Utils.h"
namespace VxSdkNet {
ref class AnalyticBehavior;
ref class NewAnalyticBehavior;
/// <summary>
/// The AnalyticConfig class represents a specific analytic configuration for a data source.
/// </summary>
public ref class AnalyticConfig {
public:
/// <summary>
/// Constructor.
/// </summary>
/// <param name="vxAnalyticConfig">The vx analytic configuration.</param>
AnalyticConfig(VxSdk::IVxAnalyticConfig* vxAnalyticConfig);
/// <summary>
/// Destructor.
/// </summary>
virtual ~AnalyticConfig() {
this->!AnalyticConfig();
}
/// <summary>
/// Finaliser.
/// </summary>
!AnalyticConfig();
/// <summary>
/// Add a new analytic behavior to this analytic configuration.
/// </summary>
/// <param name="newAnalyticBehavior">The new analytic behavior to be added to the analytic configuration.</param>
/// <returns>The <see cref="Results::Value">Result</see> of adding the analytic behavior.</returns>
Results::Value AddAnalyticBehavior(NewAnalyticBehavior^ newAnalyticBehavior);
/// <summary>
/// Delete an analytic behavior from this analytic configuration.
/// </summary>
/// <param name="analyticBehavior">The analytic behavior to be deleted from the analytic configuration.</param>
/// <returns>The <see cref="Results::Value">Result</see> of deleting the analytic behavior.</returns>
Results::Value DeleteAnalyticBehavior(AnalyticBehavior^ analyticBehavior);
/// <summary>
/// Refreshes this instances properties.
/// </summary>
/// <returns>The <see cref="Results::Value">Result</see> of updating the properties.</returns>
Results::Value Refresh();
///<summary>
/// Gets all of the analytic behaviors for this analytic configuration.
///</summary>
///<value>A <c>List</c> of analytic behaviors.</value>
property System::Collections::Generic::List<AnalyticBehavior^>^ AnalyticBehaviors {
public:
System::Collections::Generic::List<AnalyticBehavior^>^ get() { return _GetAnalyticBehaviors(); }
}
/// <summary>
/// Gets the unique analytic configuration identifier.
/// </summary>
/// <value>The unique identifier.</value>
property System::String^ Id {
public:
System::String^ get() { return Utils::ConvertCppString(_analyticConfig->id); }
}
/// <summary>
/// Specifies the resolution of the grid used for all analytic behavior data.
/// </summary>
/// <value>The resolution value.</value>
property Resolution^ Size {
public:
Resolution^ get() { return gcnew Resolution(&_analyticConfig->size); }
void set(Resolution^ value) { _SetResolutionSize(value); }
}
/// <summary>
/// Specifies the minimum confidence filtering value for detected objects in a video scene.
/// </summary>
property float MinConfidence {
public:
float get() { return _analyticConfig->minConfidence; }
void set(float value) { _analyticConfig->SetMinConfidence(value); }
}
/// <summary>
/// Specifies the name of the PTZ preset that this configuration relates to. PTZ cameras supporting
/// analytics can only be configured on PTZ presets.
/// </summary>
property System::String^ PtzPresetName {
public:
System::String^ get() { return Utils::ConvertCppString(_analyticConfig->ptzPresetName); }
void set(System::String^ value) {
char name[64];
VxSdk::Utilities::StrCopySafe(name, Utils::ConvertCSharpString(value).c_str());
_analyticConfig->SetPtzPresetName(name);
}
}
internal:
VxSdk::IVxAnalyticConfig* _analyticConfig;
System::Collections::Generic::List<AnalyticBehavior^>^ _GetAnalyticBehaviors();
void _SetResolutionSize(Resolution^ value);
};
}
#endif // AnalyticConfig_h__
| true |
2d7de5c03ba6ff7f51a5b81165f715db4cf00c47 | C++ | shihchinw/baktsiu | /src/view.cpp | UTF-8 | 5,367 | 2.96875 | 3 | [
"MIT"
] | permissive | #include "view.h"
namespace baktsiu
{
Vec2f View::getViewportCoords(const Vec2f& imgCoords) const
{
Vec2f imageOffset = getImageOffset();
return glm::clamp(imgCoords * mImageScale + imageOffset, Vec2f(0.0f), mViewSize);
}
Vec2f View::getImageCoords(const Vec2f& viewCoords, bool* isClamped) const
{
Vec2f imageOffset = getImageOffset();
Vec2f coords = (viewCoords - imageOffset) / mImageScale;
if (isClamped) {
Vec2f mask = glm::step(Vec2f(0.0f), coords) - glm::step(mImageSize, coords);
*isClamped = (mask.x * mask.y == 0.0f);
}
return glm::clamp(coords, Vec2f(0.0f), mImageSize);
}
Vec2f View::getLocalOffset() const
{
return mLocalOffset;
}
void View::setImageSize(const Vec2f& size)
{
mImageSize = size;
}
void View::setLocalOffset(const Vec2f& offset)
{
mLocalOffset = offset;
}
void View::setViewportPadding(const Vec4f& padding)
{
mViewPadding = padding;
}
Vec2f View::getImageOffset() const
{
// Offset is relative to the origin at bottom left.
Vec2f visibleSize = getVisibleSize();
Vec3f offset((visibleSize - mImageSize) * 0.5f + mLocalOffset, 1.0);
offset.x += mViewPadding.w;
offset.y += mViewPadding.z;
offset = mTransform * offset;
return glm::round(Vec2f(offset) + Vec2f(0.5f)) - Vec2f(0.5f); // Round to pixel center of viewport.
}
float View::getImageScale() const
{
return mImageScale;
}
Vec2f View::getImageScalePivot() const
{
return mImageScalePivot;
}
void View::scale(float value, const Vec2f* pivot)
{
// When the scale value is less than one, we want the image scaled near to current pivot.
// On the contrary, when we magnify the image, we want to keep the pivot snaped to the
// image border to make the image always visible in the view.
if (value > 1.0f) {
if (pivot) {
mImageScalePivot = getConstrainedPivot(*pivot);
} else {
mImageScalePivot = getConstrainedPivot(mImageScalePivot);
}
}
Mat3f xform(1.0f);
xform[0][0] = value;
xform[1][1] = value;
xform[2] = Vec3f(-value * mImageScalePivot.x + mImageScalePivot.x, -value * mImageScalePivot.y + mImageScalePivot.y, 1.0f);
mTransform = xform * mTransform;
mImageScale *= value;
}
void View::translate(const Vec2f& value, bool localSpace)
{
if (!localSpace) {
mTransform[2][0] += value.x;
mTransform[2][1] += value.y;
} else {
mLocalOffset += value;
}
restrictTranslation();
}
void View::resize(const Vec2f& size)
{
mViewSize = size;
restrictTranslation();
}
Vec2f View::getConstrainedPivot(Vec2f pivot) const
{
const Vec2f imageOffset = getImageOffset();
const Vec2f scaledImageSize = mImageSize * mImageScale;
if (pivot.x < imageOffset.x) {
pivot.x = imageOffset.x;
} else if (pivot.x > imageOffset.x + scaledImageSize.x) {
pivot.x = (imageOffset.x + scaledImageSize.x);
}
if (pivot.y < imageOffset.y) {
pivot.y = imageOffset.y;
} else if (pivot.y > imageOffset.y + scaledImageSize.y) {
pivot.y = (imageOffset.y + scaledImageSize.y);
}
pivot = glm::round(pivot + Vec2f(0.5f)) - Vec2f(0.5f);
// Use reflected pivot would make noncontiguous jump.
/*if (pivot.x < imageOffset.x) {
pivot.x = imageOffset.x * 2.0f - pivot.x;
} else if (pivot.x > imageOffset.x + scaledImageSize.x) {
pivot.x = (imageOffset.x + scaledImageSize.x) * 2.0f - pivot.x;
}
if (pivot.y < imageOffset.y) {
pivot.y = imageOffset.y * 2.0f - pivot.y;
} else if (pivot.y > imageOffset.y + scaledImageSize.y) {
pivot.y = (imageOffset.y + scaledImageSize.y) * 2.0f - pivot.y;
}*/
return pivot;
}
void View::restrictTranslation()
{
const Vec2f imageOffset = getImageOffset();
const Vec2f scaledImageSize = mImageSize * mImageScale;
const auto safePadding = Vec2f(100.0f);
Vec2f minOffset = safePadding - scaledImageSize;
Vec2f maxOffset = getVisibleSize() - safePadding;
Vec2f coffset(0.0f);
coffset = glm::mix(coffset, minOffset - imageOffset, glm::lessThan(imageOffset, minOffset));
coffset = glm::mix(coffset, maxOffset - imageOffset, glm::greaterThan(imageOffset, maxOffset));
mTransform[2][0] += coffset.x;
mTransform[2][1] += coffset.y;
}
Vec2f View::getVisibleSize() const
{
Vec2f visibleSize = mViewSize;
visibleSize.x -= mViewPadding.y + mViewPadding.w;
visibleSize.y -= mViewPadding.x + mViewPadding.z;
return visibleSize;
}
void View::reset(bool fitViewport)
{
mTransform = Mat3f(1.0f);
mImageScale = 1.0f;
mLocalOffset = Vec2f(0.0f);
Vec2f visibleSize = getVisibleSize();
mImageScalePivot = visibleSize * 0.5f;
mImageScalePivot.x += mViewPadding.w;
mImageScalePivot.y += mViewPadding.z;
mImageScalePivot = glm::round(mImageScalePivot + Vec2f(0.5f)) - Vec2f(0.5f);
if (fitViewport) {
mImageScale = std::min(visibleSize.x / mImageSize.x, visibleSize.y / mImageSize.y);
Mat3f xform(1.0f);
mTransform[0][0] = mImageScale;
mTransform[1][1] = mImageScale;
mTransform[2] = Vec3f(-mImageScale * mImageScalePivot.x + mImageScalePivot.x, -mImageScale * mImageScalePivot.y + mImageScalePivot.y, 1.0f);
}
}
} // namespace baktsiu | true |
638c2d30fed741a8e8960dc2e33ac0935f80b5bd | C++ | menglecho/Kattis | /bijele.cpp | UTF-8 | 255 | 2.90625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
using namespace std;
int main(void){
int arr[6], cor[6] = {1,1,2,2,2,8};
for(int i = 0; i < 6; i++){
cin >> arr[i];
cout << cor[i] - arr[i] << " ";
}
cout << endl;
return 0;
}
| true |
91d76c113c585306e20bb4d14a74f52366b0a2d5 | C++ | gabriellerosa/Codigos-Maratona | /atCoder/beginner170/a/a.cpp | UTF-8 | 379 | 2.75 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int x1, x2, x3, x4, x5;
cin >> x1 >> x2 >> x3 >> x4 >> x5;
if(x1 == 0){
cout << "1\n";
}
if(x2 == 0){
cout << "2\n";
}
if(x3 == 0){
cout << "3\n";
}
if(x4 == 0){
cout << "4\n";
}
if(x5 == 0){
cout << "5\n";
}
return 0;
} | true |
1fdb33a5a18f9b3bd05b34e16bc54732acc88e02 | C++ | LucasYang7/JobduOJ-InterviewQuestions | /1503binarySearchTreeToSortDoubleLinklist/main.cpp | UTF-8 | 7,541 | 3.46875 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
#define MAX 3001
// 定义二叉树结点的结构
typedef struct Node
{
int data; // 数据域
Node * lchild; // 左子树指针
Node * rchild; // 右子树指针
Node * pre; // 中序遍历序列的前继指针
Node * next; // 中序遍历序列的后继指针
bool isConstructLeftChild; // 判断是否已经构造了结点的左孩子
bool isConstructRightChild; // 判断是否已经构造了结点的右孩子
}BinaryTreeNode;
BinaryTreeNode binaryTreeNode[MAX]; // 二叉树结点数组
BinaryTreeNode * lastVisitedinInOrderSequnce; // 标记中序遍历过程中上一次被遍历的结点
char preOrderString[5 * MAX]; // 先序遍历字符串
int numberOfBinaryTreeNode; // 二叉树的结点数目(包含了值为0的结点)
int preOrderSequence[MAX]; // 转换先序遍历字符串得到的整形数组
int indexOfPreOrderSequence; // 先序遍历整形数组的下标
/**
* 将先序遍历字符串转化为对应的整形数组
* @param char preOrderString[] 输入的先序遍历字符串
* @param int preOrderStringLen 先序遍历序列字符串的长度
* @return 二叉树的结点个数,注意:在这里0也算二叉树的结点
*/
int stringToIntArray(char preOrderString[],int preOrderStringLen)
{
int i = 0;
int indexForIntArray = 0; // 整形数组的长度
int nodeData; // 结点的数据
while(i < preOrderStringLen)
{
nodeData = 0;
while(preOrderString[i] >= '0' && preOrderString[i] <= '9') // 从字符串中分隔出整数
{
nodeData = 10 * nodeData + preOrderString[i] - '0';
i++;
}
preOrderSequence[indexForIntArray++] = nodeData;
i++; // 跳过字符串中的空格
}
return indexForIntArray;
}
/**
* 初始化二叉树中各个结点之间的关系,将先序遍历序列赋值给各个结点,
* 每个结点都看成是只有一个结点,左右子树都为NULL的二叉树
* @param int n 二叉树中的结点个数
* @return void
*/
void initBinaryTree(int n)
{
int i;
for(i = 0;i < n;i++)
{
binaryTreeNode[i].data = preOrderSequence[i];
binaryTreeNode[i].isConstructLeftChild = false;
binaryTreeNode[i].isConstructRightChild = false;
binaryTreeNode[i].lchild = NULL;
binaryTreeNode[i].rchild = NULL;
binaryTreeNode[i].pre = NULL;
binaryTreeNode[i].next = NULL;
}
}
/**
* 根据先序遍历序列构造二叉树
* @param BinaryTreeNode * root 表示当前二叉树的根结点
* @param preOrderSequence 先序遍历整形数组
* @param preOrderLen 先序遍历整形数组的长度
* @return void
*/
void createBinaryTreeByPreOrder(BinaryTreeNode * root,int preOrderSequence[],int preOrderLen)
{
if((indexOfPreOrderSequence + 1) < (preOrderLen - 1))
{
// 构造左子树
do
{
if(binaryTreeNode[numberOfBinaryTreeNode + 1].data != 0)
{
root -> lchild = &binaryTreeNode[numberOfBinaryTreeNode + 1];
numberOfBinaryTreeNode++;
indexOfPreOrderSequence++;
createBinaryTreeByPreOrder(root -> lchild,preOrderSequence,preOrderLen);
}
else // 遇到0则当做NULL处理
{
root -> lchild = NULL;
numberOfBinaryTreeNode++;
indexOfPreOrderSequence++;
}
root -> isConstructLeftChild = true;
}while(false == root -> isConstructLeftChild);
// 构造右子树
do
{
if(binaryTreeNode[numberOfBinaryTreeNode + 1].data != 0)
{
root -> rchild = &binaryTreeNode[numberOfBinaryTreeNode + 1];
numberOfBinaryTreeNode++;
indexOfPreOrderSequence++;
createBinaryTreeByPreOrder(root -> rchild,preOrderSequence,preOrderLen);
}
else // 遇到0则当做NULL处理
{
root -> rchild = NULL;
numberOfBinaryTreeNode++;
indexOfPreOrderSequence++;
}
root -> isConstructRightChild = true;
}while(false == root -> isConstructRightChild);
}
}// createBinaryTreeByPreOrder
/**
* 中序遍历二叉树排序树,根据中序遍历序列构造排好序的双向链表,这也是构造中序二叉线索树的过程
* @param BinaryTreeNode * root 待遍历的二叉树排序树的根结点
* @return void
*/
void createSortDuLinklistByInOrder(BinaryTreeNode * root)
{
if(NULL == root)
return ;
else
{
createSortDuLinklistByInOrder(root -> lchild);
root -> pre = lastVisitedinInOrderSequnce; // 将root结点的pre指针指向中序遍历序列中的上一个被访问的结点
if(NULL != lastVisitedinInOrderSequnce)
{
lastVisitedinInOrderSequnce -> next = root; // 将root结点添加中序遍历上一个访问的结点后面
}
lastVisitedinInOrderSequnce = root; // 将当前结点标记为最后访问的结点
createSortDuLinklistByInOrder(root -> rchild);
}
}
/**
* 遍历排好序的双向链表
* @param int preOrderLen 先序遍历序列的长度(包括值为0的结点)
* @return void
*/
void travelDoubleSortLinklist(int preOrderLen)
{
int i;
BinaryTreeNode * head = NULL; // 排序双向链表的首元结点
// 寻找双向链表的首元结点
for(i = 0;i < preOrderLen;i++)
{
if(0 != binaryTreeNode[i].data) //跳过值等于0的二叉树结点
{
//如果某个二叉树的结点无中序遍历前继结点,则可以证明该二叉树是中序遍历第一个遍历的结点
//也就是二叉树排序树中值最小的结点,当然也就是排序双向链表中的第一个结点
if(NULL == binaryTreeNode[i].pre)
{
head = &binaryTreeNode[i];
break;
}
}
}
while(head != NULL)
{
printf("%d ",head -> data);
head = head -> next;
}
printf("\n");
}
int main()
{
int n;
int preOrderStringLen; // 输入的先序遍历字符串长度
int preOrderLen; // 先序遍历整形数组的长度
BinaryTreeNode * root; // 二叉树的根结点
while(EOF != scanf("%d\n",&n))
{
while(n--)
{
numberOfBinaryTreeNode = 0; // 初始时二叉树的结点个数为0
indexOfPreOrderSequence = 0; // 指向先序遍历序列中的第0个元素
gets(preOrderString); // 输入先序遍历序列
preOrderStringLen = strlen(preOrderString);
preOrderLen = stringToIntArray(preOrderString,preOrderStringLen); // 将先序遍历序列字符串转化为整形数组
initBinaryTree(preOrderLen); // 初始化二叉树中的各个结点之间的关系
root = &binaryTreeNode[0]; // 因为是根据先序遍历构建的二叉树,所以根结点指针指向第0个二叉树结点
createBinaryTreeByPreOrder(root,preOrderSequence,preOrderLen);
lastVisitedinInOrderSequnce = NULL; // lastVisitedinInOrderSequnce的初始值赋为NULL
createSortDuLinklistByInOrder(root);
travelDoubleSortLinklist(preOrderLen);
}
}
return 0;
}
/**************************************************************
解题报告:http://blog.csdn.net/pengyan0812/article/details/46423241
****************************************************************/ | true |
75d81ae2c72e44659845690da6a600680cacf652 | C++ | enzoqueiroz/Arq | /sistemacadastro.cpp | UTF-8 | 1,295 | 3.265625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
string nome;
cout << "insira seu nome";
cin >> nome;
int diaInicio;
cout << "Insira o dia de inicio";
cin >> diaInicio;
int diaTermino;
cout << "Insira o dia de termino";
cin >> diaTermino;
int investimentoDia;
cout << "Insira o dia do investimento";
cin >> investimentoDia;
Anuncio anuncio;
anuncio.Nome = nome;
anuncio.diaInicio = diaInicio;
anuncio.diaTermino = diaTermino;
anuncio.InvestimentoDia = investimentoDia;
double total = anuncio.TotalInvestido();
}
int calculadora()
{
double din : int pessoas, comp : cout << "Insira o valor investido: R$ ";
cin >> din : pessoas += 30 * din;
int v1 = pessoas;
for (int 1 = 0; 1 < 3; 1 ++)
comp = 18 * v1 / 1000;
pessoas += comp * 40;
v1 = comp * 40;
return v1;
}
class Anuncio
{
public:
string Nome;
int diaInicio;
int diaTermino;
double InvestimentoDia;
public:
double TotalInvestido()
{
auto timeSpent = diaTermino - diaInicio;
return timeSpent.Days * InvestimentoDia;
}
public:
int VisualizacaoMaxima()
{
}
public:
int MaximaDeCliques()
{
}
public:
int CompartilhamentoMaximo()
{
}
} | true |
f97027caa1f43912322ec3d0ab7915af6dda4f34 | C++ | jimwwalker/drum_scope | /bar_drawer.cc | UTF-8 | 3,848 | 2.53125 | 3 | [] | no_license | #include <exception>
#include <string>
#include "bar.h"
#include "bar_drawer.h"
BarDrawer::BarDrawer(int screenX, int screenY, int barX, int barY, int beats,
int bpm)
: list(beats, bpm) {
const int border = 20;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
throw std::runtime_error("SDL_Init failed " + std::string(SDL_GetError()));
}
window.reset(SDL_CreateWindow("Jim's Drum Scope", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, screenX + (border * 2),
screenY + (border * 2), SDL_WINDOW_SHOWN));
if (!window) {
throw std::runtime_error("SDL_CreateWindow failed " +
std::string(SDL_GetError()));
}
renderer.reset(SDL_CreateRenderer(
window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));
if (!renderer) {
throw std::runtime_error("SDL_CreateRenderer failed " +
std::string(SDL_GetError()));
}
// calc how big the bars should be.
int barWidth = screenX / barX;
int barHeight = screenY / barY;
for (int i = 0; i < barY; i++) {
int posY = i * barHeight;
for (int j = 0; j < barX; j++) {
int posX = j * barWidth;
list.addBar(*renderer,
{posX + border, posY + border, barWidth, barHeight}, beats,
bpm);
}
}
notified = false;
}
void BarDrawer::beat(
int midiId, std::chrono::time_point<std::chrono::high_resolution_clock> t) {
std::unique_lock<std::mutex> lg(lock);
beatQueue.push(std::make_pair(midiId, t));
bool expected = false;
if (notified.compare_exchange_strong(expected, true)) {
}
}
static int mapMidiToScale(int midiId) {
switch (midiId) {
case 42:
case 46:
case 22: // hi-hat
return 3;
case 48: // hi tom
return 4;
case 45: // m tom
return 5;
case 41: // low tom
return 6;
case 38:
return 7; // snare
case 36:
return 8; // BD
case 51:
case 59:
return 1; // crash
case 55:
case 49:
return 2; // crash
default:
printf("Unknown %d\n", midiId);
return 0;
}
}
void BarDrawer::run() {
auto currentBar = list.end(); // first beat sets this to begin
auto beat1 = std::chrono::high_resolution_clock::now();
SDL_SetRenderTarget(renderer.get(), NULL);
for (auto &b : list) {
b.draw();
}
SDL_RenderPresent(renderer.get());
while (true) {
bool beat = false;
SDL_Event e;
while (SDL_PollEvent(&e) != 0) {
// User requests quit
if (e.type == SDL_QUIT) {
return;
}
}
if (notified.load()) {
notified = false;
std::unique_lock<std::mutex> lk(lock);
while (!beatQueue.empty()) {
if (currentBar == list.end()) {
beat1 = std::chrono::high_resolution_clock::now();
beat1 = list.setEpoch(beat1);
currentBar = list.begin();
}
auto b = beatQueue.front();
currentBar->makeRenderTarget();
if (currentBar->beat(mapMidiToScale(b.first), b.second)) {
currentBar++;
if (currentBar == list.end()) {
beat1 = list.setEpoch(beat1);
currentBar = list.begin();
list.wash();
}
currentBar->makeRenderTarget();
currentBar->beat(mapMidiToScale(b.first), b.second);
}
beatQueue.pop();
}
} else if (currentBar != list.end() &&
currentBar->pulse(std::chrono::high_resolution_clock::now())) {
currentBar++;
if (currentBar == list.end()) {
beat1 = list.setEpoch(beat1);
currentBar = list.begin();
list.wash();
}
currentBar->makeRenderTarget();
}
SDL_SetRenderTarget(renderer.get(), NULL);
for (auto &b : list) {
b.draw();
}
SDL_RenderPresent(renderer.get());
}
} | true |
7474e198d137a3554dc90b8b81e7562536293526 | C++ | achak98/Stuff-I-did-with-Cplusplus | /euler 3.cpp | UTF-8 | 555 | 2.875 | 3 | [] | no_license | #include<iostream>
using namespace std;
unsigned long long gNo=600851475143;
bool isPrime (unsigned long long a){
for(unsigned long long i=3l;i<=((a/2)+1);i+=2){
if (a%i==0 || a%2 == 0){
return 0;
}
}
return 1;
}
unsigned long long largestF(unsigned long long a){
unsigned long long max=1l, i=1l;
while((i*i)<gNo){
if (a%i==0){
if(i>max&&isPrime(i)==true){
max=i;
cout<<max<<endl;
gNo/=i;
i++;
}
}
}
return max;
}
int main(){
cout << largestF(gNo);
return 0;
}
| true |
bf6acdf03dae8597fa592a15ec84ff349c7223b9 | C++ | plasticlouie/Notes | /cpp/Offer/翻转单词顺序列/main.cpp | UTF-8 | 1,006 | 3.390625 | 3 | [] | no_license |
/*
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。
同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。
例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,
正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
*/
class Solution {
public:
string ReverseSentence(string str) {
if(str.size()==0)
return str;
str = " " + str;
string reverse = "";
int index1=str.size()-1, index2=str.size();
while(index1>=0)
{
if(str[index1]==' ')
{
reverse = reverse + " " + str.substr(index1+1, index2-index1-1);
index2 = index1;
}
index1--;
}
if(reverse.size()>0)
reverse = reverse.substr(1, reverse.size()-1);
return reverse;
}
};
| true |
99d8284fbf8f642d69f1c2a5f721327aa1c53dee | C++ | rapidsai/cudf | /cpp/include/cudf/strings/strip.hpp | UTF-8 | 2,459 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* 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.
*/
#pragma once
#include <cudf/column/column.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/side_type.hpp>
#include <cudf/strings/strings_column_view.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
namespace cudf {
namespace strings {
/**
* @addtogroup strings_modify
* @{
* @file
*/
/**
* @brief Removes the specified characters from the beginning or end
* (or both) of each string.
*
* The to_strip parameter can contain one or more characters.
* All characters in `to_strip` are removed from the input strings.
*
* If `to_strip` is the empty string, whitespace characters are removed.
* Whitespace is considered the space character plus control characters
* like tab and line feed.
*
* Any null string entries return corresponding null output column entries.
*
* @code{.pseudo}
* Example:
* s = [" aaa ", "_bbbb ", "__cccc ", "ddd", " ee _ff gg_"]
* r = strip(s,both," _")
* r is now ["aaa", "bbbb", "cccc", "ddd", "ee _ff gg"]
* @endcode
*
* @throw cudf::logic_error if `to_strip` is invalid.
*
* @param input Strings column for this operation
* @param side Indicates characters are to be stripped from the beginning, end, or both of each
* string; Default is both
* @param to_strip UTF-8 encoded characters to strip from each string;
* Default is empty string which indicates strip whitespace characters
* @param mr Device memory resource used to allocate the returned column's device memory.
* @return New strings column.
*/
std::unique_ptr<column> strip(
strings_column_view const& input,
side_type side = side_type::BOTH,
string_scalar const& to_strip = string_scalar(""),
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource());
/** @} */ // end of doxygen group
} // namespace strings
} // namespace cudf
| true |
f003fd66681f37dd2cc465b16380a7490b778f06 | C++ | tienanhnguyen191999/FinalContest_CTDL_GT | /69/main.cpp | UTF-8 | 916 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#include <stack>
using namespace std;
char x[1000] = "*-a/bc-/akl";
void init(){
cin >> x;
}
void solve(){
stack<char> s;
int c =0,save = 0;
for (int i = 0 ; i < strlen(x) ; i++){
if (x[i] >= 'a' && x[i] <= 'z'){
cout << x[i];
c++;
if (c == 2){
cout << s.top();
s.pop();
if (save == 1){
cout << s.top();
s.pop();
save = 0;
}
c = 0;
}
}
else{
s.push(x[i]);
if (c == 1) save = 1;
c = 0;
}
}
while (!s.empty()){
cout << s.top();
s.pop();
}
cout << endl;
}
int main(){
int turn;
cin >> turn;
while (turn--){
init();
solve();
}
return 0;
} | true |
a66a29c4e8980308c6dcbd3fe1d14b68546070c8 | C++ | flaming-snowman/pps | /2020-2021/summer-contest-3/MakingCheese/makingcheese.cpp | UTF-8 | 850 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll solve(ll inc, ll req, ll need) //"cheese mod" incrementer, cheese requirement, cheese needed
{
//binary search
ll hi = need;
ll lo = 0;
while(lo < hi) {
ll m = lo+(hi-lo)/2;
ll cheeselo=req-req%inc+inc; //floor of req/inc + inc
ll cheesehi=m-m%inc; //floor of m/inc (max amount of cheese to add)
ll amt=(cheesehi-cheeselo)/inc+1; //number of values of cheese
if(amt<0) amt=0;
ll cheese=amt*(cheeselo+cheesehi)/2; //arithmetic series
cheese+=m; //add initial value
if(cheese >= need) hi = m;
else lo = m+1;
}
return lo;
}
int main()
{
int n;
cin >> n;
ll k,m,x;
for(int i = 0; i<n; i++) {
cin >> k >> m >> x;
cout << solve(k, m, x) << endl;
}
}
| true |
8690ca82cdd224c8f46938eec1d89e8724d02e8f | C++ | flomerz/HomieSonoffRGBWW | /src/RGBController.hpp | UTF-8 | 4,652 | 3.09375 | 3 | [] | no_license | #ifndef RGBCONTROLLER_H
#define RGBCONTROLLER_H
#include <Arduino.h>
#define RGBRANGE 255
class RGBController {
const uint8_t pinRed;
const uint8_t pinGreen;
const uint8_t pinBlue;
unsigned short currentRed;
unsigned short currentGreen;
unsigned short currentBlue;
unsigned short currentBrightness;
unsigned short targetRed;
unsigned short targetGreen;
unsigned short targetBlue;
unsigned short targetBrightness;
unsigned long lastTransitionColorMicros;
unsigned long transitionColorMicrosOffset;
unsigned long lastTransitionBrightnessMicros;
unsigned long transitionBrightnessMicrosOffset;
bool rainbowOn = false;
unsigned short rainbowColorOffset;
unsigned short rainbowColorFactor;
unsigned long transitionRainbowMillis;
unsigned short mapPWM(byte const & color) const {
return map(color, 0, RGBRANGE, 0, PWMRANGE);
}
unsigned short mapPWMColor(byte const & color) const {
auto pwm = mapPWM(color);
return pow(2, (pwm + 1) / (PWMRANGE / 10)) - 1;
}
long offsetLong(long const & x, long const & y) const {
return x > y ? x - y : y - x;
}
long maxLong(long const & x, long const & y) const {
return x > y ? x : y;
}
unsigned long calcTransition(word const & transitionSeconds) const {
if (transitionSeconds > 0) {
auto steps = maxLong(
maxLong(
offsetLong(currentRed, targetRed),
offsetLong(currentGreen, targetGreen)
), maxLong(
offsetLong(currentBlue, targetBlue),
offsetLong(currentBrightness, targetBrightness)
)
);
if (steps > 0) {
return (transitionSeconds * 1000000) / steps;
}
}
return 0;
}
unsigned short calcRainbowColor(double const & colorOffset) const {
return sin((millis() * 2 * PI / transitionRainbowMillis) + colorOffset) * rainbowColorFactor + rainbowColorOffset;
}
void updateRGB() {
analogWrite(pinRed, currentRed * currentBrightness / PWMRANGE);
analogWrite(pinGreen, currentGreen * currentBrightness / PWMRANGE);
analogWrite(pinBlue, currentBlue * currentBrightness / PWMRANGE);
}
void updateColor() {
if (micros() - lastTransitionColorMicros > transitionColorMicrosOffset) {
lastTransitionColorMicros = micros();
bool needUpdate = false;
if (currentRed != targetRed) {
needUpdate = true;
currentRed -= constrain(currentRed - targetRed, -1, 1);
}
if (currentGreen != targetGreen) {
needUpdate = true;
currentGreen -= constrain(currentGreen - targetGreen, -1, 1);
}
if (currentBlue != targetBlue) {
needUpdate = true;
currentBlue -= constrain(currentBlue - targetBlue, -1, 1);
}
if (needUpdate) updateRGB();
}
}
void updateBrightness() {
if (micros() - lastTransitionBrightnessMicros > transitionBrightnessMicrosOffset) {
lastTransitionBrightnessMicros = micros();
bool needUpdate = false;
if (currentBrightness != targetBrightness) {
needUpdate = true;
currentBrightness -= constrain(currentBrightness - targetBrightness, -1, 1);
}
if (needUpdate) updateRGB();
}
}
void updateRainbow() {
currentRed = calcRainbowColor(0);
currentGreen = calcRainbowColor(2 * PI / 3);
currentBlue = calcRainbowColor(4 * PI / 3);
updateRGB();
}
public:
RGBController(uint8_t const & pinRed, uint8_t const & pinGreen, uint8_t const & pinBlue) :
pinRed{pinRed},
pinGreen{pinGreen},
pinBlue{pinBlue} {}
void setup() const {
pinMode(pinRed, OUTPUT);
pinMode(pinGreen, OUTPUT);
pinMode(pinBlue, OUTPUT);
}
void loop() {
updateBrightness();
if (rainbowOn) {
updateRainbow();
} else {
updateColor();
}
}
void setColor(byte const & red, byte const & green, byte const & blue, word const & transitionSeconds) {
disableRainbow();
targetRed = mapPWMColor(red);
targetGreen = mapPWMColor(green);
targetBlue = mapPWMColor(blue);
transitionColorMicrosOffset = calcTransition(transitionSeconds);
}
void setBrightness(byte const & brightness, word const & transitionSeconds) {
targetBrightness = mapPWM(brightness);
transitionBrightnessMicrosOffset = calcTransition(transitionSeconds);
}
void setRainbow(byte const & colorOffset, byte const & colorFactor, word const & transitionSeconds) {
rainbowOn = true;
rainbowColorOffset = mapPWM(colorOffset);
rainbowColorFactor = mapPWM(colorFactor);
transitionRainbowMillis = transitionSeconds * 1000;
}
void disableRainbow() {
rainbowOn = false;
}
};
#endif
| true |
a1912af3da5782a065a3ceab2acc2515d9c64f5b | C++ | mrcece/CppStrangeIoC | /CppStrangeIoC/framework/injector/injectionexception.h | UTF-8 | 649 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <string>
#include <stdexcept>
using namespace strange::extensions::injector::api;
namespace strange
{
namespace extensions
{
namespace injector
{
namespace impl
{
class InjectionException : public std::exception
{
private:
InjectionExceptionType privatetype = static_cast<InjectionExceptionType>( 0 );
public:
InjectionExceptionType gettype() const;
void settype( const InjectionExceptionType& value );
InjectionException();
/// Constructs an InjectionException with a message and InjectionExceptionType
InjectionException( const std::wstring& message, InjectionExceptionType exceptionType );
};
}
}
}
}
| true |
139b67063a7cfa4198ba2b02dcc5d26c5151c2e3 | C++ | chris-mcclure/C2P | /Circle.cpp | UTF-8 | 1,598 | 2.65625 | 3 | [] | no_license | //
// Circle.cpp
// C2P
//
// Created by Chris McClure on 3/21/18.
// Copyright © 2018 Chris McClure. All rights reserved.
//
#include "Circle.h"
using std::ostream;
using std::endl;
using std::string;
using std::ostringstream;
Circle::Circle(double width, const string & name):_radius(width/2),
_width(width), _height(width), _name(name)
{}
double Circle::getWidth(){
return _width;
}
double Circle::getHeight(){
return _height;
}
double Circle::getRadius(){
return _radius;
}
void Circle::setWidth(double w) {
_width = w;
}
void Circle::setHeight(double h) {
_height = h;
}
void Circle::setPostScript(ostringstream & stream){
_stream = std::move(stream);
}
string Circle::getName(){
return _name;
}
ostringstream & Circle::getPostScript(){
return _stream;
}
ostringstream & Circle::toPostScript(ostringstream & stream){
stream << "%%Circle" << endl;
stream << "/circle{" << endl;
stream << "/radius {" << getRadius() << " mul} def" << endl;
stream << "/width {" << getWidth() << " mul} def" << endl;
stream << "/height {" << getHeight() << " mul} def" << endl;
stream << "gsave" << endl;
stream << "1 radius 1 inch 1 radius add 1 radius 0 360 arc" << endl;
stream << "gsave" << endl;
stream << "0 1 0.5 setrgbcolor fill" << endl;
stream << "grestore" << endl;
stream << "stroke" << endl;
stream << "grestore" << endl;
//stream << "1 width 0 height rmoveto" << endl;
stream << "}def" << endl;
//stream << "circle" <<endl;
stream << endl;
// drawBoundingBox(radius, stream);
return stream;
}
| true |
6056738af49b99fbc0686203fb7d7f1a914df786 | C++ | storm-ptr/step | /test/longest_repeated_substring.hpp | UTF-8 | 2,246 | 3.03125 | 3 | [
"MIT"
] | permissive | // Andrew Naplavkov
#ifndef STEP_TEST_LONGEST_REPEATED_SUBSTRING_HPP
#define STEP_TEST_LONGEST_REPEATED_SUBSTRING_HPP
#include <map>
#include <step/longest_repeated_substring.hpp>
#include <step/test/case_insensitive.hpp>
#include <string_view>
TEST_CASE("longest_repeated_substring_hello_world")
{
auto range = step::longest_repeated_substring::find_with_suffix_array(
"the longest substring of a string that occurs at least twice");
CHECK("string " == std::string(range.first, range.second));
}
TEST_CASE("longest_repeated_substring_find")
{
struct {
std::string_view str;
std::string_view expect;
} tests[] = {
{"GEEKSFORGEEKS$", "GEEKS"},
{"AAAAAAAAAA$", "AAAAAAAAA"},
{"ABCDEFG$", ""},
{"ABABABA$", "ABABA"},
{"ATCGATCGA$", "ATCGA"},
{"banana$", "ana"},
{"ATCGATCGA$", "ATCGA"},
{"mississippi$", "issi"},
{"abcabcaacb$", "abca"},
{"aababa$", "aba"},
};
for (auto& [str, expect] : tests) {
auto arr_rng =
step::longest_repeated_substring::find_with_suffix_array(str);
CHECK(expect == std::string(arr_rng.first, arr_rng.second));
auto tree_rng =
step::longest_repeated_substring::find_with_suffix_tree<std::map>(
str);
CHECK(expect == std::string(tree_rng.first, tree_rng.second));
}
}
TEST_CASE("longest_repeated_substring_case_insensitive")
{
const char str[] = "geeksForGeeks";
const std::string expect = "geeks";
auto arr_rng = step::longest_repeated_substring::find_with_suffix_array<
step::case_insensitive::less>(str);
CHECK(std::equal(expect.begin(),
expect.end(),
arr_rng.first,
arr_rng.second,
step::case_insensitive::equal_to{}));
auto tree_rng = step::longest_repeated_substring::find_with_suffix_tree<
step::case_insensitive::unordered_map>(str);
CHECK(std::equal(expect.begin(),
expect.end(),
tree_rng.first,
tree_rng.second,
step::case_insensitive::equal_to{}));
}
#endif // STEP_TEST_LONGEST_REPEATED_SUBSTRING_HPP
| true |
d831f0d8a8d8c017c636c64f330bf0553bfc2731 | C++ | MercuriXito/PicProcess | /lib/ops/basicops.h | UTF-8 | 1,537 | 3.0625 | 3 | [] | no_license | #ifndef BASICOPS_H
#define BASICOPS_H
#include <cassert>
#include "lib/ops/ops.h"
class WImage;
typedef unsigned char uchar;
typedef struct hsipixel{
double i; // i \in [0,1]
double s; // s \in [0,1]
double h; // h \in [0,360]
hsipixel():h(0),s(0),i(0){};
hsipixel(double h, double s, double i):h(h),s(s),i(i){};
hsipixel(const struct hsipixel& p){this->h = p.h; this->s = p.s; this->i = p.i;};
bool operator=(const struct hsipixel& p){this->h = p.h; this->s = p.s; this->i = p.i;};
}HsiPixel;
class HSIImage{
public:
HsiPixel* ptr;
int h, w;
HSIImage(){};
explicit HSIImage(int h, int w, bool allocate = false):h(h), w(w){ if(allocate) this->ptr = new HsiPixel[h * w]; else this->ptr = NULL;};
HSIImage(const HSIImage& image){ // shallow copy
this->h = image.h; this->w = image.w;
this->ptr = image.ptr;
};
HsiPixel operator()(int i, int j) const{
assert(( (i > 0) && (i < this->w) ) && ((j > 0)&&(j < this->h)));
return this->ptr[i * this->w + j];
};
int width() const{ return this->w;};
int height() const {return this->h;};
};
class BasicOps : public Ops
{
public:
BasicOps();
static void toGrayScale(WImage& image);
static WImage toGrayScale(const WImage& image);
static void toBinary(WImage& image, int threshold);
static WImage toBinary(const WImage& image, int threshold);
static HSIImage rgb2hsv(const WImage& image);
static WImage hsv2rgb(const HSIImage& image);
};
#endif // BASICOPS_H
| true |
512a0005f00e9053c92af331b8b3492540c6b7d6 | C++ | gbrltorres/cmp1048-trabalho1 | /util2b.h | UTF-8 | 432 | 2.703125 | 3 | [] | no_license | #ifndef LIB2B_H
#define LIB2B_H
#include <iostream>
#include <cmath>
using namespace std;
int size(char* s);
int str_to_int(char* s, int q);
string remove_whitespaces(char* s1);
int count_words(string s, char c);
string* split(string s, char c, int & q);
int index_of(char* s1, char* s2);
char* complete_array(char* old_arr, int old_size, int difference);
char* sum_of_giant_numbers(char* n1, char* n2);
#endif // LIB2B_H
| true |
8bff66ba0e01c9c071a91fd24e7b21984169aaad | C++ | Leybee/DaniilYarokhmedov | /Laba_2/Laba_2_c++/Laba_2/main.cpp | WINDOWS-1251 | 2,988 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Row
{
string row;
public:
Row()
{
row = "";
}
Row(string r)
{
row = r;
}
char operator[] (const int index)
{
return row[index];
}
int length()
{
return row.length();
}
void set(string r)
{
row = r;
}
string get()
{
return row;
}
};
class Text
{
vector <Row> rows;
public:
Text(Row r)
{
rows.push_back(r);
}
void append(Row r)
{
rows.push_back(r);
}
void dropLast()
{
rows.pop_back();
}
void clearAll()
{
rows.clear();
}
string operator[] (const int index)
{
Row temp = rows[index];
return temp.get();
}
float getFrequencyOfCymvol(char ch)
{
Row temp;
float frequencyCym = 0;
float countCym = 0;
for (int i = 0; i < rows.size(); i++)
{
temp.set(rows[i].get());
for (int j = 0; j < temp.length(); j++)
{
countCym++;
if (temp[j] == ch) {
frequencyCym++;
}
}
}
return frequencyCym / countCym;
}
void deleteInd(int ind)
{
rows.erase(rows.begin() + ind);
}
void replacement(int ind, Row r)
{
rows[ind] = r;
}
void dropDublicate()
{
bool flag = false;
string temp;
for (int i = 0; i < rows.size(); i++)
{
temp = rows[i].get();
for (int j = i; j < rows.size(); j++)
{
for (int k = 0; k < temp.length() && k < rows[j].get().length(); k++)
{
if (temp[k] != rows[j].get()[k])
{
flag = true;
}
}
}
if (!flag)
{
deleteInd(i);
}
flag = false;
}
}
void Show()
{
cout << "==========================" << endl;
for (int i = 0; i < rows.size(); i++)
{
cout << rows[i].get() << endl;
}
cout << "==========================" << endl;
}
};
int main()
{
setlocale(LC_ALL, "RUS");
cout << "Laba_2, Yarokhmedov D., V-14" << endl;
Row first("i i ,");
Row second(" i ,");
Row third("i i");
Row fourth(" i.");
Text text(first);
text.append(second);
text.append(third);
text.append(fourth);
text.Show();
cout << " i '' - " << text.getFrequencyOfCymvol('') * 100 << '%' << endl;
cout << " i '' - " << text.getFrequencyOfCymvol('') * 100 << '%' << endl;
cout << " i '' - " << text.getFrequencyOfCymvol('') * 100 << '%' << endl;
text.Show();
cout << " 1 3 " << endl;
text.deleteInd(0);
text.deleteInd(1);
text.Show();
cout << " i" << endl;
text.append(second);
text.Show();
cout << " i " << endl;
text.dropDublicate();
text.Show();
return 0;
} | true |
45cb00b4ecba3180403b005fa6eac54c33e688de | C++ | swielgus/vctrsKL | /src/RegionConstructor.cpp | UTF-8 | 17,946 | 2.578125 | 3 | [] | no_license | #include <algorithm>
#include <deque>
#include <iostream>
#include "RegionConstructor.hpp"
RegionConstructor::RegionConstructor(const std::vector<PolygonSide>& usedSideData,
const std::vector<PixelGraph::edge_type>&& usedGraphData,
unsigned int usedWidth, unsigned int usedHeight)
: polygonSideData{usedSideData}, graphData{std::move(usedGraphData)}, width{usedWidth}, height{usedHeight},
wasNodeVisited{}, generatedBoundaries{}, colorRepresentatives{}
{
wasNodeVisited.resize(width * height, false);
generateBoundariesByRadialSweeps();
}
RegionConstructor::~RegionConstructor()
{
}
void RegionConstructor::generateBoundariesByRadialSweeps()
{
std::vector<ClipperLib::Paths> gatheredPolygonChains;
for(unsigned int row = 0; row < height; ++row)
for(unsigned int col = 0; col < width; ++col)
{
unsigned int idx = col + row * width;
if(!wasNodeVisited[idx])
{
//std::cout << "\n" << row << "," << col << " = ";
ClipperLib::Paths currentPolygonChain = createChainOfPolygonsForRoot(row, col);
if( !currentPolygonChain.empty() )
{
colorRepresentatives.emplace_back(row, col);
gatheredPolygonChains.push_back(std::move(currentPolygonChain));
}
//std::cout << "\n";
}
}
for(const auto& chain : gatheredPolygonChains)
{
ClipperLib::PolyTree unionResult;
ClipperLib::Clipper clipTool;
clipTool.PreserveCollinear(true);
clipTool.AddPaths(chain, ClipperLib::PolyType::ptSubject, true);
clipTool.Execute(ClipperLib::ClipType::ctUnion, unionResult, ClipperLib::PolyFillType::pftPositive,
ClipperLib::PolyFillType::pftPositive);
if( unionResult.GetFirst() )
{
/*std::cout << "\n";
for(const auto& point : unionResult.GetFirst()->Contour)
std::cout << point.X << "," << point.Y << "|";*/
generatedBoundaries.push_back(std::move(unionResult.GetFirst()->Contour));
}
}
}
ClipperLib::Paths RegionConstructor::createChainOfPolygonsForRoot(const unsigned int& row, const unsigned int& col)
{
ClipperLib::Paths result;
int currentRow = row;
int currentCol = col;
int currentIdx = col + row * width;
PixelGraph::edge_type currentNodeData = graphData[currentIdx];
GraphEdge previousDirection = GraphEdge::UP;
GraphEdge directionToHitEdge = get4DirectionWithNoNeighbor(currentNodeData, previousDirection);
while( isThereAnEdge(currentNodeData, directionToHitEdge) )
{
currentRow = getNeighborRowIdx(currentRow, directionToHitEdge);
currentCol = getNeighborColIdx(currentCol, directionToHitEdge);
currentIdx = col + row * width;
currentNodeData = graphData[currentIdx];
if(wasNodeVisited[currentIdx])
{
markComponentAsVisited(row, col);
return result;
}
directionToHitEdge = get4DirectionWithNoNeighbor(currentNodeData, directionToHitEdge);
}
previousDirection = getDirectionOfNextNeighbor(currentNodeData, directionToHitEdge);
if(previousDirection == directionToHitEdge)
{
wasNodeVisited[currentIdx] = true;
//std::cout << "\n" << currentIdx << ", " << currentIdx << " -- lonely polygon\n";
addPolygonToPath(row, col, result);
return result;
}
int previousRow = currentRow;
int previousCol = currentCol;
int previousIdx = currentIdx;
currentRow = getNeighborRowIdx(previousRow, previousDirection);
currentCol = getNeighborColIdx(previousCol, previousDirection);
currentIdx = currentCol + currentRow * width;
currentNodeData = graphData[currentIdx];
int idxBeforeFirst = currentIdx;
std::vector<int> sequenceOfPoints;
while(true)
{
GraphEdge nextDirection = getDirectionOfNextNeighbor(currentNodeData, getInvertedDirection(previousDirection));
previousRow = currentRow;
previousCol = currentCol;
previousIdx = currentIdx;
currentRow = getNeighborRowIdx(previousRow, nextDirection);
currentCol = getNeighborColIdx(previousCol, nextDirection);
currentIdx = currentCol + currentRow * width;
currentNodeData = graphData[currentIdx];
auto positionWhereCurrentIdxIsRepeated = std::find(sequenceOfPoints.begin(), sequenceOfPoints.end(), currentIdx);
if(positionWhereCurrentIdxIsRepeated != sequenceOfPoints.end())
{
bool didCurrentIdxOccurBefore = (previousIdx == idxBeforeFirst);
if(positionWhereCurrentIdxIsRepeated != sequenceOfPoints.begin())
didCurrentIdxOccurBefore = (previousIdx == *(--positionWhereCurrentIdxIsRepeated));
if(didCurrentIdxOccurBefore)
break;
}
sequenceOfPoints.push_back(currentIdx);
addPolygonToPath(currentRow, currentCol, result);
previousDirection = nextDirection;
}
markComponentAsVisited(row, col);
return result;
}
void
RegionConstructor::addPolygonToPath(const unsigned int& row, const unsigned int& col, ClipperLib::Paths& polygonChain)
{
//std::cout << "[" << row << ","<< col << "] - ";
ClipperLib::Path polygon;
addUpperLeftCornerOfPolygonToPath(row, col, polygon);
addLowerLeftCornerOfPolygonToPath(row, col, polygon);
addLowerRightCornerOfPolygonToPath(row, col, polygon);
addUpperRightCornerOfPolygonToPath(row, col, polygon);
/*std::cout << "-|";
for(const auto& point : polygon)
std::cout << point.X << "," << point.Y << "|";
*/
polygonChain.push_back(std::move(polygon));
}
void RegionConstructor::addUpperLeftCornerOfPolygonToPath(const unsigned int& row, const unsigned int& col, ClipperLib::Path& polygon)
{
const int idx = col + row * width;
const auto& nodeDetails = polygonSideData[idx];
if( nodeDetails.getType() == PolygonSide::Type::Backslash )
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointB[0]), static_cast<int>(nodeDetails.pointB[1]));
}
else if( nodeDetails.getType() == PolygonSide::Type::ForwardSlash )
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointB[0]), static_cast<int>(nodeDetails.pointB[1]));
}
else
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
}
}
void RegionConstructor::addLowerLeftCornerOfPolygonToPath(const unsigned int& row, const unsigned int& col, ClipperLib::Path& polygon)
{
if(col == 0 || row == height-1)
{
polygon << ClipperLib::IntPoint(static_cast<int>(100*(row+1)), static_cast<int>(100*col));
}
else
{
const int idx = col + (row+1) * width;
const auto& nodeDetails = polygonSideData[idx];
if( nodeDetails.getType() == PolygonSide::Type::Backslash )
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointB[0]), static_cast<int>(nodeDetails.pointB[1]));
}
else
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
}
}
}
void RegionConstructor::addUpperRightCornerOfPolygonToPath(const unsigned int& row, const unsigned int& col, ClipperLib::Path& polygon)
{
if(col == width-1 || row == 0)
{
polygon << ClipperLib::IntPoint(static_cast<int>(100*row), static_cast<int>(100*(col+1)));
}
else
{
const int idx = col+1 + row * width;
const auto& nodeDetails = polygonSideData[idx];
if( nodeDetails.getType() == PolygonSide::Type::Backslash )
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointB[0]), static_cast<int>(nodeDetails.pointB[1]));
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
}
else if( nodeDetails.getType() == PolygonSide::Type::ForwardSlash )
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointB[0]), static_cast<int>(nodeDetails.pointB[1]));
}
else
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
}
}
}
void RegionConstructor::addLowerRightCornerOfPolygonToPath(const unsigned int& row, const unsigned int& col, ClipperLib::Path& polygon)
{
if(col == width-1 || row == height-1)
{
polygon << ClipperLib::IntPoint(static_cast<int>(100*(row+1)), static_cast<int>(100*(col+1)));
}
else
{
const int idx = col+1 + (row+1) * width;
const auto& nodeDetails = polygonSideData[idx];
if( nodeDetails.getType() == PolygonSide::Type::ForwardSlash )
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointB[0]), static_cast<int>(nodeDetails.pointB[1]));
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
}
else
{
polygon << ClipperLib::IntPoint(static_cast<int>(nodeDetails.pointA[0]), static_cast<int>(nodeDetails.pointA[1]));
}
}
}
GraphEdge RegionConstructor::getDirectionOfNextNeighbor(const PixelGraph::edge_type& edges, GraphEdge direction)
{
GraphEdge startingDirection = direction;
do
{
rotateDirectionCounterClockwiseByOne(direction);
} while( direction != startingDirection && !isThereAnEdge(edges,direction) );
return direction;
}
GraphEdge RegionConstructor::get4DirectionWithNoNeighbor(const PixelGraph::edge_type& edges, GraphEdge initialDirection)
{
GraphEdge direction = initialDirection;
do
{
rotateDirectionCounterClockwiseByTwo(direction);
} while( direction != initialDirection && isThereAnEdge(edges,direction) );
return direction;
}
GraphEdge RegionConstructor::getInvertedDirection(const GraphEdge& direction) const
{
GraphEdge result = direction;
switch(direction)
{
case GraphEdge::DOWN: result = GraphEdge::UP; break;
case GraphEdge::LOWER_RIGHT: result = GraphEdge::UPPER_LEFT; break;
case GraphEdge::UPPER_LEFT: result = GraphEdge::LOWER_RIGHT; break;
case GraphEdge::UP: result = GraphEdge::DOWN; break;
case GraphEdge::LEFT: result = GraphEdge::RIGHT; break;
case GraphEdge::LOWER_LEFT: result = GraphEdge::UPPER_RIGHT; break;
case GraphEdge::UPPER_RIGHT: result = GraphEdge::LOWER_LEFT; break;
case GraphEdge::RIGHT: result = GraphEdge::LEFT; break;
}
return result;
}
void RegionConstructor::rotateDirectionCounterClockwiseByOne(GraphEdge& direction)
{
switch(direction)
{
case GraphEdge::DOWN: direction = GraphEdge::LOWER_RIGHT; break;
case GraphEdge::LOWER_RIGHT: direction = GraphEdge::RIGHT; break;
case GraphEdge::UPPER_LEFT: direction = GraphEdge::LEFT; break;
case GraphEdge::UP: direction = GraphEdge::UPPER_LEFT; break;
case GraphEdge::LEFT: direction = GraphEdge::LOWER_LEFT; break;
case GraphEdge::LOWER_LEFT: direction = GraphEdge::DOWN; break;
case GraphEdge::UPPER_RIGHT: direction = GraphEdge::UP; break;
case GraphEdge::RIGHT: direction = GraphEdge::UPPER_RIGHT; break;
}
}
void RegionConstructor::rotateDirectionCounterClockwiseByTwo(GraphEdge& direction)
{
switch(direction)
{
case GraphEdge::DOWN: direction = GraphEdge::RIGHT; break;
case GraphEdge::LOWER_RIGHT: direction = GraphEdge::UPPER_RIGHT; break;
case GraphEdge::UPPER_LEFT: direction = GraphEdge::LOWER_LEFT; break;
case GraphEdge::UP: direction = GraphEdge::LEFT; break;
case GraphEdge::LEFT: direction = GraphEdge::DOWN; break;
case GraphEdge::LOWER_LEFT: direction = GraphEdge::LOWER_RIGHT; break;
case GraphEdge::UPPER_RIGHT: direction = GraphEdge::UPPER_LEFT; break;
case GraphEdge::RIGHT: direction = GraphEdge::UP; break;
}
}
void RegionConstructor::markComponentAsVisited(const int rootRow, const int rootCol)
{
int currentIdx = rootCol + rootRow * width;
wasNodeVisited[currentIdx] = true;
std::deque<int> queueOfNodesToVisit;
queueOfNodesToVisit.push_back(currentIdx);
while( !queueOfNodesToVisit.empty() )
{
currentIdx = queueOfNodesToVisit.front();
queueOfNodesToVisit.pop_front();
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::UPPER_LEFT, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::LEFT, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::LOWER_LEFT, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::DOWN, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::LOWER_RIGHT, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::RIGHT, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::UPPER_RIGHT, queueOfNodesToVisit);
markNeighBorAsVisitedAndAddToQueue(currentIdx, GraphEdge::UP, queueOfNodesToVisit);
}
}
void RegionConstructor::markNeighBorAsVisitedAndAddToQueue(const int& currentIdx, const GraphEdge direction,
std::deque<int>& queueOfNodesToVisit)
{
PixelGraph::edge_type currentNodeData = graphData[currentIdx];
if( isThereAnEdge(currentNodeData, direction) )
{
int neighborIdx = getNeighborIdx(currentIdx, direction);
if(!wasNodeVisited[neighborIdx])
{
wasNodeVisited[neighborIdx] = true;
queueOfNodesToVisit.push_back(neighborIdx);
}
}
}
bool RegionConstructor::isThereAnEdge(const PixelGraph::edge_type& currentNodeData, const GraphEdge& direction) const
{
return currentNodeData & static_cast<PixelGraph::edge_type>(direction);
}
int RegionConstructor::getNeighborRowIdx(int row, GraphEdge direction)
{
if(direction == GraphEdge::UP || direction == GraphEdge::UPPER_LEFT || direction == GraphEdge::UPPER_RIGHT)
row--;
if(direction == GraphEdge::DOWN || direction == GraphEdge::LOWER_LEFT || direction == GraphEdge::LOWER_RIGHT)
row++;
if(row < 0 || row >= height)
{
throw std::out_of_range("Neighbor row out of graph area!");
}
return row;
}
int RegionConstructor::getNeighborColIdx(int col, GraphEdge direction)
{
if(direction == GraphEdge::LEFT || direction == GraphEdge::UPPER_LEFT || direction == GraphEdge::LOWER_LEFT)
col--;
if(direction == GraphEdge::RIGHT || direction == GraphEdge::UPPER_RIGHT || direction == GraphEdge::LOWER_RIGHT)
col++;
if(col < 0 || col >= width)
{
throw std::out_of_range("Neighbor col out of graph area!");
}
return col;
}
int RegionConstructor::getNeighborIdx(const int& idx, const GraphEdge direction)
{
int result;
switch(direction)
{
case GraphEdge::DOWN: result = idx + width; break;
case GraphEdge::LOWER_RIGHT: result = idx + width + 1; break;
case GraphEdge::UPPER_LEFT: result = idx - width - 1; break;
case GraphEdge::UP: result = idx - width; break;
case GraphEdge::LEFT: result = idx - 1; break;
case GraphEdge::LOWER_LEFT: result = idx + width - 1; break;
case GraphEdge::UPPER_RIGHT: result = idx - width + 1; break;
case GraphEdge::RIGHT: result = idx + 1; break;
}
if(result < 0 || result >= wasNodeVisited.size())
{
throw std::out_of_range("Neighbor idx out of graph area!");
}
return result;
}
const ClipperLib::Paths& RegionConstructor::getBoundaries() const
{
return generatedBoundaries;
}
std::vector<std::vector<PathPoint> > RegionConstructor::createPathPoints()
{
std::vector< std::vector<PathPoint> > result;
result.resize(generatedBoundaries.size());
for(int i = 0; i < generatedBoundaries.size(); ++i)
{
const auto& currentPathSource = generatedBoundaries.at(i);
auto& currentPath = result.at(i);
for(const auto& pathElement : currentPathSource)
{
PathPoint currentPoint{false, pathElement.X / 100, pathElement.Y / 100};
unsigned int rowRemainder = pathElement.X % 100;
unsigned int colRemainder = pathElement.Y % 100;
unsigned int rowQuotient = (pathElement.X - rowRemainder) / 100;
unsigned int colQuotient = (pathElement.Y - colRemainder) / 100;
if(rowRemainder == 25)
{
currentPoint.useBPoint = true;
currentPoint.rowOfCoordinates = rowQuotient;
}
else if(rowRemainder == 75)
{
currentPoint.rowOfCoordinates = rowQuotient + 1;
}
if(colRemainder == 25)
{
currentPoint.colOfCoordinates = colQuotient;
}
else if(colRemainder == 75)
{
currentPoint.colOfCoordinates = colQuotient + 1;
}
currentPath.push_back(std::move(currentPoint));
}
}
return result;
}
const std::vector<ClipperLib::IntPoint>& RegionConstructor::getColorRepresentatives() const
{
return colorRepresentatives;
}
| true |
315f7db471b1a874104258a0190a1afb51059ae2 | C++ | BoomerangDecompiler/boomerang | /src/boomerang/visitor/stmtmodifier/StmtModifier.h | UTF-8 | 2,895 | 2.625 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma region License
/*
* This file is part of the Boomerang Decompiler.
*
* See the file "LICENSE.TERMS" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*/
#pragma endregion License
#pragma once
#include "boomerang/core/BoomerangAPI.h"
#include <memory>
class ExpModifier;
class Assign;
class PhiAssign;
class ImplicitAssign;
class BoolAssign;
class GotoStatement;
class BranchStatement;
class CaseStatement;
class CallStatement;
class ReturnStatement;
/**
* StmtModifier is a class that for all expressions in this statement, makes a modification.
* The modification is as a result of an ExpModifier; there is a pointer to such an ExpModifier in a
* StmtModifier. Even the top level of the LHS of assignments are changed. This is useful e.g. when
* modifiying locations to locals as a result of converting from SSA form, e.g. eax := ebx -> local1
* := local2 Classes that derive from StmtModifier inherit the code (in the accept member functions)
* to modify all the expressions in the various types of statement. Because there is nothing
* specialised about a StmtModifier, it is not an abstract class (can be instantiated).
*
* \note This class' visitor functions don't return anything. Maybe we'll need return values at a
* later stage.
*/
class BOOMERANG_API StmtModifier
{
public:
StmtModifier(ExpModifier *em, bool ignoreCollector = false);
virtual ~StmtModifier() = default;
public:
bool ignoreCollector() const { return m_ignoreCol; }
/// Modify a statement.
/// \param[in] stmt Statement to modify
/// \param[out] visitChildren set to true to visit children of this statement
virtual void visit(const std::shared_ptr<Assign> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<PhiAssign> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<ImplicitAssign> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<BoolAssign> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<GotoStatement> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<BranchStatement> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<CaseStatement> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<CallStatement> &stmt, bool &visitChildren);
/// \copydoc StmtModifier::visit
virtual void visit(const std::shared_ptr<ReturnStatement> &stmt, bool &visitChildren);
public:
ExpModifier *m_mod; ///< The expression modifier object
protected:
bool m_ignoreCol;
};
| true |
f53cfe7648d430a6ba4a8b414b1d202ae21305d8 | C++ | michi201/gitrepo | /cpp/samogloski.cpp | UTF-8 | 1,009 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
using namespace std;
int liczZnaki(char nazwa[]) {
char kopia[15];
cout << kopia << endl;
// otwieranie pliku
ifstream wejscie(nazwa);
if (!wejscie) { cout << "Brak pliku!"; return 1; }
ofstream wyjscie(kopia);
if (!wyjscie) { cout << "Błąd pliku!"; return 1; }
char znak;
int ile = 0;
while(!wejscie.eof()) {
wejscie.get(znak); // odczytanie poj. znaku
if (wejscie && (znak == 'a') || znak == 'e' || znak == 'u' || znak == 'i' || znak == 'o' || znak == 'y') {
ile++;
wyjscie.put(znak); // zapisanie znaku do pliku
}
}
wejscie.close(); wyjscie.close();
cout << "Znaków: " << ile << endl;
return ile;
}
int main(int argc, char **argv)
{
char nazwa[20];
cout << "Podaj nazwę pliku: ";
cin.getline(nazwa, 20);
cout << nazwa << endl;
liczZnaki(nazwa);
return 0;
}
| true |
1c4df4d175af1c76b5ea612d3586432c81dd8807 | C++ | DHushchin/SeaBattle | /BattleShip/Cell.cpp | UTF-8 | 852 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "Cell.hpp"
Cell::Cell(float x, float y) {
isHit = isMiss = isBorder = isBoat = false;
pos = sf::Vector2f(x, y);
sprite.setPosition(pos);
}
bool Cell::SetUpSprite(string TextureName) {
if (!texture.loadFromFile(TextureName))
return false;
sprite.setTexture(texture);
return true;
}
sf::Sprite Cell::getSprite() {
return sprite;
}
void Cell::setHit() {
SetUpSprite("images\\Hit.png");
isHit = true;
}
void Cell::setMiss() {
SetUpSprite("images\\Miss.jpg");
isMiss = true;
}
void Cell::setBorder() {
if (!isBoat) {
SetUpSprite("images\\Miss.jpg");
isBorder = true;
}
}
void Cell::setBoat() {
isBoat = true;
}
bool Cell::getBorder() {
return isBorder;
}
bool Cell::getHit() {
return isHit;
}
bool Cell::getBlocked() {
return (isHit || isMiss || isBorder);
}
bool Cell::getBoat() {
return isBoat;
}
| true |
a4001438b6aba35fb8719674183730a17e64358c | C++ | aminbenarieb/cg_lab1 | /lab1/mainwindow.cpp | UTF-8 | 2,249 | 2.609375 | 3 | [] | no_license | #include "mainwindow.h"
#include "congif.h"
#include <QGridLayout>
#include <QEvent>
#include <QResizeEvent>
#include <QPushButton>
#include <QHeaderView>
#include <QStatusBar>
MainWindow::~MainWindow()
{
wgt->deleteLater();
}
void MainWindow::addRow(QPointF point)
{
// Сбрасываем решение
wgt->triangle.min = false;
// Добавление в массив
wgt->points.append(point);
// Обновление рисунка
wgt->update();
// Обновление таблицы
updateTable();
}
void MainWindow::updateTable()
{
while (tableView->rowCount() != 0)
{
delete tableView->item(tableView->rowCount()-1, 0);
delete tableView->item(tableView->rowCount()-1, 1);
delete tableView->item(tableView->rowCount()-1, 2);
tableView->removeRow(0);
}
foreach (QPointF point, wgt->points) {
tableView->insertRow(tableView->rowCount());
tableView->setItem(tableView->rowCount()-1, 0, new QTableWidgetItem(QString::number(tableView->rowCount())));
tableView->setItem(tableView->rowCount()-1, 1, new QTableWidgetItem(QString::number(point.x())));
tableView->setItem(tableView->rowCount()-1, 2, new QTableWidgetItem(QString::number(point.y())));
}
}
bool MainWindow::eventFilter(QObject *, QEvent *event)
{
if(event->type() == QEvent::Resize )
{
// QResizeEvent *res = reinterpret_cast<QResizeEvent*>(event); размер измененного окна
return true;
}
else if (event->type() ==QMouseEvent::MouseButtonDblClick)
{
// addRow( wgt->scalePoint( ((QMouseEvent*)event)->pos()) );
return true;
}
else if (event->type() ==QMouseEvent::MouseMove)
{
// QPointF pos = ((QMouseEvent*)event)->pos();
// wgt->cursorX = pos.x();
// wgt->cursorY = pos.y();
// pos = wgt->scalePoint(pos);
// this->setWindowTitle( QString("%1 (%2,%3)").arg(kTextTitle, QString::number(pos.x()), QString::number(pos.y())) );
// wgt->update();
return true;
}
else if (event->type() ==QEvent::Leave)
{
this->setWindowTitle(kTextTitle);
return true;
}
return false;
}
| true |
0e3984bd561b3642f20a42a1c17c1ae72296bfa5 | C++ | Kathelyss/Study | /LabyrinthProject-master/Labyrinth-master/Labyrinth/main.cpp | UTF-8 | 1,635 | 3.296875 | 3 | [] | no_license | //
// main.cpp
// Labyrinth
//
// Created by Екатерина Рыжова on 09.05.15.
// Copyright (c) 2015 Екатерина Рыжова. All rights reserved.
//
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int n = 10; //т. к. лабиринт квадратный
int array[n][n]; //т. к. лабиринт квадратный
int i = 0, j = 0;
int enter = arc4random_uniform(n-2)+1; //генерируем номер ячейки, где будет вход
int exit = arc4random_uniform(n-2)+1; //генерируем номер ячейки, где будет выход
cout << "enter = " << enter+1 << " exit = " << exit+1 << "\n\n";
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
//генерируем рамку (периметр)
if ((i == 0) || (j == 0) || (i == n-1) || (j == n-1)) {
if (!(i == 0 && j == enter) && !(i == n-1 && j == exit)) {
array[i][j] = 1;
} else {
array[i][j] = 0;
}
} else {
if ((i-1 == 0 && j == enter) || (i+1 == n-1 && j == exit)) {
array[i][j] = 0;
} else {
array[i][j] = arc4random_uniform(2);
//генерация лабиринта
}
}
if (array[i][j] == 1) {
cout << "⬛️";
} else {
cout << "⬜️";
}
}
cout << endl;
}
return 0;
}
| true |
4ec89cd5006dd2d6db02f0eda436a26a8d5ba47d | C++ | ArdoncII/Labos-de-progra | /guialabo3/Promedio.cpp | UTF-8 | 274 | 3.1875 | 3 | [] | no_license | #include "iostream"
using namespace std;
int main()
{
float a,b,c,prom;
cout << "Para realizar el promedio de tres cifras digite los valores" <<endl;
cin>> a >> b >> c;
prom = ((a+b+c)/3);
cout<< "El promedio de los valores es: "<<prom <<endl;
} | true |
efa708cc10adf9e9d2854da7f9350566c04a967b | C++ | jpmdossantos/SheetCreator | /src/PulseLoader.cpp | UTF-8 | 2,181 | 2.84375 | 3 | [] | no_license | /*
* PulseLoader.cpp
*
* Created on: 2 de abr de 2020
* Author: joaopaulo
*/
#include "PulseLoader.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>
PulseLoader::PulseLoader(std::string path) {
// TODO Auto-generated constructor stub
this->mPath = path;
this->Load();
}
void PulseLoader::Load() {
std::string filenames = ReadFilenames();
const char filename_delimiter = '\n';
auto parsed_filenames = ParseFilenames(filenames, filename_delimiter);
std::ifstream filestream;
std::string property, value, line;
for(auto file : parsed_filenames)
{
filestream.open(file);
if (!filestream){
throw std::runtime_error("File not found");
break;
}
property = value = line = "";
std::map<std::string,std::string> current_file_properties;
// Iterate through each line and split the content using delimeter
while (getline(filestream, line))
{
std::istringstream ss(line);
std::getline(ss, property, ':');
std::getline(ss, value);
boost::trim(property);
boost::trim(value);
std::pair<std::string,std::string> read_property{property, value};
current_file_properties.insert(read_property);
}
mPulses.push_back(current_file_properties);
filestream.close();
}
}
std::vector<std::string> PulseLoader::ParseFilenames(std::string& filenames, char delimiter) {
std::vector<std::string> results;
boost::split(results, filenames, [delimiter](char character){return character == delimiter;});
return results;
}
std::string PulseLoader::ReadFilenames() {
std::array<char, 128> buffer;
std::string result;
std::string command = "find " + mPath + " -name '*.dat' ";
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen( command.c_str(), "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
boost::trim(result);
return result;
}
| true |
68363412d50933c101e839d38721850728261f7a | C++ | dinesh5583/Data-Structure-and-Algorithm-using-c- | /Data Structure and algorithm/Tree/FindMax_in_BTree.cpp | UTF-8 | 1,534 | 3.78125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class node{
public:
int value;
node *left;
node *right;
};
class btree{
public:
btree();
void insert(int key);
void findmax();
private:
void insert(int key, node *leaf);
int find(node *root);
node *root;
};
btree::btree(){
root = NULL;
}
void btree::findmax()
{
cout<<find(root);
}
int btree::find(node *root)
{
int root_val,left,right,max=INT_MIN;
if(root!=NULL)
{
root_val=root->value;
left=find(root->left);
right=find(root->right);
if(left>right) max=left;
else max=right;
if(root_val>max)
max=root_val;
}
return max;
}
void btree::insert(int key, node *leaf){
if(key < leaf->value){
if(leaf->left != NULL){
insert(key, leaf->left);
}else{
leaf->left = new node;
leaf->left->value = key;
leaf->left->left = NULL;
leaf->left->right = NULL;
}
}else if(key >= leaf->value){
if(leaf->right != NULL){
insert(key, leaf->right);
}else{
leaf->right = new node;
leaf->right->value = key;
leaf->right->right = NULL;
leaf->right->left = NULL;
}
}
}
void btree::insert(int key){
if(root != NULL){
insert(key, root);
}else{
root = new node;
root->value = key;
root->left = NULL;
root->right = NULL;
}
}
int main(){
//btree tree;
btree *tree = new btree();
tree->insert(10);
tree->insert(6);
tree->insert(14);
tree->insert(5);
tree->insert(88);
tree->insert(11);
tree->insert(18);
tree->findmax();
}
| true |
19388254400655f142dfb74ef28211e7016481cb | C++ | soheil647/Advance_Programming_Cpp | /Hotel_Reservation/source/hotel.cpp | UTF-8 | 12,647 | 3.265625 | 3 | [] | no_license | #include "../header/hotel.hpp"
using namespace std;
struct Hotel::Rating {
float location;
float cleanliness;
float staff;
float facilities;
float value_for_money;
float overall_rating;
};
Hotel::Hotel(const vector<string> &information_path) {
parse_hotel_information(information_path);
assign_rooms_ids();
}
void Hotel::parse_hotel_information(const vector<string> &hotel_information) {
int column_number = 0;
for (const string &word : hotel_information) {
if (column_number == 0)
unique_id = word;
if (column_number == 1)
property_name = word;
if (column_number == 2)
hotel_star_rating = stoi(word);
if (column_number == 3)
hotel_overview = word;
if (column_number == 4)
property_amenities = word;
if (column_number == 5)
city = word;
if (column_number == 6)
latitude = stof(word);
if (column_number == 7)
longitude = stof(word);
if (column_number == 8)
image_url = word;
if (column_number == 9)
number_standard_room = stoi(word);
if (column_number == 10)
number_deluxe_room = stoi(word);
if (column_number == 11)
number_luxury_room = stoi(word);
if (column_number == 12)
number_premium_room = stoi(word);
if (column_number == 13)
standard_room_price = stoi(word);
if (column_number == 14)
deluxe_room_price = stoi(word);
if (column_number == 15)
luxury_room_price = stoi(word);
if (column_number == 16)
premium_room_price = stoi(word);
column_number++;
}
}
void Hotel::assign_rooms_ids() {
for (int room_number = 1; room_number <= number_standard_room; room_number++)
standard_rooms.push_back(new Room("s" + to_string(room_number), standard_room_price, "standard"));
for (int room_number = 1; room_number <= number_deluxe_room; room_number++)
deluxe_rooms.push_back(new Room("d" + to_string(room_number), deluxe_room_price, "deluxe"));
for (int room_number = 1; room_number <= number_luxury_room; room_number++)
luxury_rooms.push_back(new Room("l" + to_string(room_number), luxury_room_price, "luxury"));
for (int room_number = 1; room_number <= number_premium_room; room_number++)
premium_rooms.push_back(new Room("p" + to_string(room_number), premium_room_price, "premium"));
}
void Hotel::get_new_comment(const string& username, const string& comment) {
map<string, string> new_comment;
new_comment[username] = comment;
this->comments.push_back(new_comment);
}
string Hotel::get_id() {
return this->unique_id;
}
void Hotel::show_comments() {
reverse(this->comments.begin(), this->comments.end());
for (auto & comment : this->comments) {
for(auto &comment_value : comment)
cout << comment_value.first << ": " << comment_value.second << endl;
}
reverse(this->comments.begin(), this->comments.end());
}
void Hotel::get_new_rating(float location, float cleanliness, float staff, float facilities, float value_for_money, float overall_Rating) {
Rating new_rating = {.location=location, .cleanliness=cleanliness, .staff=staff, .facilities=facilities, .value_for_money=value_for_money, .overall_rating=overall_Rating};
ratings.push_back(new_rating);
}
void Hotel::show_ratings() {
float sum_location = 0, sum_cleanliness = 0, sum_facilities = 0, sum_staff = 0, sum_value_for_money = 0, sum_overall_rating = 0;
float average_location = 0, average_cleanliness = 0, average_facilities = 0, average_staff = 0, average_value_for_money = 0, average_overall_rating = 0;
int number_of_ratings = this->ratings.size();
if(number_of_ratings == 0)
throw Hotel_Exceptions(EMPTY);
for(auto& rate : ratings) {
sum_location += rate.location;
sum_cleanliness += rate.cleanliness;
sum_facilities += rate.facilities;
sum_staff += rate.staff;
sum_value_for_money += rate.value_for_money;
sum_overall_rating += rate.overall_rating;
}
average_location = ((sum_location)/float(number_of_ratings));
average_cleanliness = ((sum_cleanliness)/float(number_of_ratings));
average_facilities = ((sum_facilities)/float(number_of_ratings));
average_staff = ((sum_staff)/float(number_of_ratings));
average_value_for_money = ((sum_value_for_money)/float(number_of_ratings));
average_overall_rating = ((sum_overall_rating)/float(number_of_ratings));
cout << setprecision(2) << fixed;
cout << "location: " << average_location << endl;
cout << "cleanliness: " << average_cleanliness << endl;
cout << "staff: " << average_staff << endl;
cout << "facilities: " << average_facilities << endl;
cout << "value for money: " << average_value_for_money << endl;
cout << "overall rating: " << average_overall_rating << endl;
}
vector<Room *> Hotel::reserve_rooms(const std::string& room_type, int room_quantity, int check_in, int check_out) {
vector<Room*> wanted_rooms;
switch (resolve_room_type(room_type)){
case standard: {
if(room_quantity > number_standard_room)
throw Hotel_Exceptions(NOT_ENOUGH_ROOM);
int reserved = 0;
for(int i = 0; i < number_standard_room; i++) {
if(standard_rooms[i]->reserve_room(check_in, check_out)) {
wanted_rooms.push_back(standard_rooms[i]);
reserved += 1;
}
if(reserved == room_quantity)
return print_reserved_rooms(wanted_rooms);
}
break;
}
case deluxe: {
if(room_quantity > number_deluxe_room)
throw Hotel_Exceptions(NOT_ENOUGH_ROOM);
int reserved = 0;
for(int i = 0; i < number_deluxe_room; i++) {
if(deluxe_rooms[i]->reserve_room(check_in, check_out)) {
wanted_rooms.push_back(deluxe_rooms[i]);
reserved += 1;
}
if(reserved == room_quantity)
return print_reserved_rooms(wanted_rooms);
}
break;
}
case luxury: {
if(room_quantity > number_luxury_room)
throw Hotel_Exceptions(NOT_ENOUGH_ROOM);
int reserved = 0;
for(int i = 0; i < number_luxury_room; i++) {
if(luxury_rooms[i]->reserve_room(check_in, check_out)) {
wanted_rooms.push_back(luxury_rooms[i]);
reserved += 1;
}
if(reserved == room_quantity)
return print_reserved_rooms(wanted_rooms);
}
break;
}
case premium: {
if(room_quantity > number_premium_room)
throw Hotel_Exceptions(NOT_ENOUGH_ROOM);
int reserved = 0;
for(int i = 0; i < number_premium_room; i++) {
if(premium_rooms[i]->reserve_room(check_in, check_out)) {
wanted_rooms.push_back(premium_rooms[i]);
reserved += 1;
}
if(reserved == room_quantity)
return print_reserved_rooms(wanted_rooms);
}
break;
}
default:
throw (Hotel_Exceptions(BAD_REQUEST));
}
reset_reserved_rooms(wanted_rooms);
throw Hotel_Exceptions(NOT_ENOUGH_ROOM);
}
Hotel::RoomType Hotel::resolve_room_type(const std::string &type) {
if( type == "standard" ) return standard;
if( type == "deluxe" ) return deluxe;
if( type == "luxury" ) return luxury;
if( type == "premium" ) return premium;
return invalid_type;
}
vector<Room *> Hotel::print_reserved_rooms(const std::vector<Room *>& reserved_rooms) {
if(reserved_rooms.size() == 1)
cout << reserved_rooms[0]->get_id();
else {
for (Room *room : reserved_rooms) {
cout << room->get_id() << " ";
}
}
cout << endl;
return reserved_rooms;
}
void Hotel::reset_reserved_rooms(const std::vector<Room *>& reserved_rooms) {
for(Room* room : reserved_rooms)
room->reset_room_reservation();
}
int Hotel::get_room_price(const string& room_type) {
switch (resolve_room_type(room_type)) {
case standard:
return standard_room_price;
case deluxe:
return deluxe_room_price;
case luxury:
return luxury_room_price;
case premium:
return premium_room_price;
case invalid_type:
throw Hotel_Exceptions(BAD_REQUEST);
}
}
void Hotel::reset_reserve(const std::vector<Room *>& reserved_rooms) {
reset_reserved_rooms(reserved_rooms);
}
bool Hotel::check_city_name(const string& city_name) {
return city_name == this->city;
}
bool Hotel::check_star(int min_star, int max_star) {
return min_star <= this->hotel_star_rating && this->hotel_star_rating <= max_star;
}
bool Hotel::check_average_price(float min_price, float max_price) {
float sum_of_price = 0;
int number_of_room_type = 0;
if(this->standard_room_price != 0)
number_of_room_type += 1;
if(this->deluxe_room_price != 0)
number_of_room_type += 1;
if(this->luxury_room_price != 0)
number_of_room_type += 1;
if(this->premium_room_price != 0)
number_of_room_type += 1;
sum_of_price = float(standard_room_price + deluxe_room_price + luxury_room_price + premium_room_price);
float average_price = sum_of_price/float(number_of_room_type);
return min_price <= average_price && average_price <= max_price;
}
float Hotel::find_average_price(){
float sum_of_price = 0;
int number_of_room_type = 0;
if(this->standard_room_price != 0)
number_of_room_type += 1;
if(this->deluxe_room_price != 0)
number_of_room_type += 1;
if(this->luxury_room_price != 0)
number_of_room_type += 1;
if(this->premium_room_price != 0)
number_of_room_type += 1;
sum_of_price = float(standard_room_price + deluxe_room_price + luxury_room_price + premium_room_price);
if(number_of_room_type == 0)
return 0;
float average = sum_of_price/float(number_of_room_type);
return average;
}
bool Hotel::check_available_room(const std::string& room_type, int quantity, int check_in, int check_out) {
vector<Room*> wanted_rooms = get_rooms_of_type(room_type);
int number_of_available_room = 0;
for(auto room : wanted_rooms) {
if(room->check_availability(check_in, check_out))
number_of_available_room += 1;
}
return number_of_available_room >= quantity;
}
vector<Room*> Hotel::get_rooms_of_type(const std::string& room_type){
vector<Room*> wanted_rooms;
switch (resolve_room_type(room_type)) {
case standard: {
wanted_rooms = standard_rooms;
break;
}
case deluxe: {
wanted_rooms = deluxe_rooms;
break;
}
case luxury: {
wanted_rooms = luxury_rooms;
break;
}
case premium: {
wanted_rooms = premium_rooms;
break;
}
default:
throw Hotel_Exceptions(BAD_REQUEST);
}
return wanted_rooms;
}
void Hotel::print_hotel() {
cout << this->unique_id << endl;
cout << this->property_name << endl;
cout << "star: " << this->hotel_star_rating << endl;
cout << "overview: " << this->hotel_overview << endl;
cout << "amenities: " << this->property_amenities << endl;
cout << "city: " << this->city << endl;
cout << setprecision(2) << fixed;
cout << "latitude: " << this->latitude << endl;
cout << "longitude: " << this->longitude << endl;
cout << "#rooms: " << number_standard_room << " " << number_deluxe_room << " " << number_luxury_room << " " << number_premium_room << endl;
cout << "price: " << standard_room_price << " " << deluxe_room_price << " " << luxury_room_price << " " << premium_room_price << endl;
}
void Hotel::print_summery_of_hotel() {
int total_number_of_rooms = number_standard_room + number_deluxe_room + number_luxury_room + number_premium_room;
cout << this->unique_id << " " << this->property_name << " " << this->hotel_star_rating << " " << this->city << " ";
cout << total_number_of_rooms << " ";
cout << setprecision(2) << fixed;
cout << find_average_price() << " " << endl;
}
| true |
db425ad627bd8fd27a42e798ffd2ef8aebf93b60 | C++ | Dixcit-TV/Rasterizer-DX11-Software | /source/Texture.h | UTF-8 | 729 | 2.578125 | 3 | [] | no_license | #pragma once
#include <string>
#include <SDL_surface.h>
#include "ERGBColor.h"
#include "EMath.h"
class Texture final
{
public:
explicit Texture(const std::string& texturePath);
Texture(const Texture& texture) = delete;
Texture(Texture&& texture) noexcept = delete;
Texture& operator=(const Texture& texture) = delete;
Texture& operator=(Texture&& texture) noexcept = delete;
~Texture();
ID3D11ShaderResourceView* GetTextureResourceView() const { return m_pTextureView; };
Elite::RGBColor Sample(const Elite::FVector2& uv) const;
void LoadToGPU(ID3D11Device* pDevice);
void ClearGPUResources();
private:
SDL_Surface* m_pTextureSurface;
ID3D11Texture2D* m_pTexture;
ID3D11ShaderResourceView* m_pTextureView;
};
| true |
c962629f07e31846fa281b0e20563edb0874164e | C++ | SamMul815/A- | /sceneManager.cpp | UHC | 3,513 | 2.8125 | 3 | [] | no_license | #include "stdafx.h"
#include "sceneManager.h"
#include "gameNode.h"
//private publicó ٰ ĸȭ
DWORD CALLBACK LoadingThread(LPVOID prc)
{
//ü init Լ
sceneManager::_readyScene->Init();
// ü ٲ
sceneManager::_currentScene = sceneManager::_readyScene;
//ε
sceneManager::_loadingScene->Release();
sceneManager::_loadingScene = NULL;
sceneManager::_readyScene = NULL;
return 0;
}
gameNode* sceneManager::_currentScene = NULL;
gameNode* sceneManager::_loadingScene = NULL;
gameNode* sceneManager::_readyScene = NULL;
sceneManager::sceneManager()
{
}
sceneManager::~sceneManager()
{
}
HRESULT sceneManager::Init(void)
{
_currentScene = NULL;
_loadingScene = NULL;
_readyScene = NULL;
return S_OK;
}
void sceneManager::Release(void)
{
mapSceneIter miSceneList = _mSceneList.begin();
for (; miSceneList != _mSceneList.end();)
{
if (miSceneList->second != NULL)
{
if (miSceneList->second == _currentScene) miSceneList->second->Release();
SAFE_DELETE(miSceneList->second);
miSceneList = _mSceneList.erase(miSceneList);
}
else
{
++miSceneList;
}
}
_mSceneList.clear();
}
void sceneManager::Update(void)
{
if (_currentScene) _currentScene->Update();
}
void sceneManager::Render(void)
{
if (_currentScene) _currentScene->Render();
}
// ߰
gameNode* sceneManager::AddScene(wstring sceneName, gameNode* scene)
{
if (!scene) return NULL;
//scene->Init();
_mSceneList.insert(make_pair(sceneName, scene));
return scene;
}
//ε ߰
gameNode* sceneManager::AddLoadingScene(wstring loadingSceneName, gameNode* scene)
{
if (!scene) return NULL;
_mSceneList.insert(make_pair(loadingSceneName, scene));
return scene;
}
HRESULT sceneManager::ChangeScene(wstring sceneName)
{
//ã´
mapSceneIter find = _mSceneList.find(sceneName);
if (find == _mSceneList.end()) return E_FAIL;
if (find->second == _currentScene) return S_OK;
//// ҽ
////ٲٷ ʱȲ
//if (SUCCEEDED(find->second->Init()))
//{
// if (_currentScene) _currentScene->Release();
// _currentScene = find->second;
// return S_OK;
//}
//ٲٷ ʱȲ
if (!find->second->GetIsSceneInit())
{
if (SUCCEEDED(find->second->Init()))
{
find->second->SetIsSceneInit(true);
_currentScene = find->second;
}
return S_OK;
}
else
{
_currentScene = find->second;
return S_OK;
}
return S_OK;
}
gameNode* sceneManager::FindScene(wstring sceneName)
{
//ã´
mapSceneIter find = _mSceneList.find(sceneName);
if (find == _mSceneList.end()) return NULL;
else return find->second;
}
HRESULT sceneManager::ChangeScene(wstring sceneName, wstring loadingSceneName)
{
//ã´
mapSceneIter find = _mSceneList.find(sceneName);
if (find == _mSceneList.end()) return E_FAIL;
if (find->second == _currentScene) return S_OK;
mapSceneIter findLoading = _mLoadingSceneList.find(loadingSceneName);
if (find == _mLoadingSceneList.end()) return ChangeScene(loadingSceneName);
//ٲٷ ʱȲ
if (SUCCEEDED(find->second->Init()))
{
//
if (_currentScene) _currentScene->Release();
//ε Ʋ
_loadingScene = findLoading->second;
//غ ٲܷ ־
_readyScene = find->second;
CloseHandle(CreateThread(NULL, 0, LoadingThread, NULL, 0, &_loadThreadID));
}
return E_FAIL;
}
| true |
3ad7481c7a275226d2d27be4400d5281d7b7e313 | C++ | njuszj/leetcode | /leetcode76.cpp | UTF-8 | 1,957 | 3.28125 | 3 | [] | no_license | // 最小覆盖子串
// 给你一个字符串 S、一个字符串 T,请在字符串 S 里面找出:包含 T 所有字符的最小子串。
/*
示例:
输入: S = "ADOBECODEBANC", T = "ABC"
输出: "BANC"
说明:
如果 S 中不存这样的子串,则返回空字符串 ""。
如果 S 中存在这样的子串,我们保证它是唯一的答案。
*/
/*
// 官方题解
class Solution {
public:
unordered_map <char, int> ori, cnt;
bool check() {
for (const auto &p: ori) {
if (cnt[p.first] < p.second) {
return false;
}
}
return true;
}
string minWindow(string s, string t) {
for (const auto &c: t) {
++ori[c];
}
int l = 0, r = -1;
int len = INT_MAX, ansL = -1, ansR = -1;
while (r < int(s.size())) {
if (ori.find(s[++r]) != ori.end()) {
++cnt[s[r]];
}
while (check() && l <= r) {
if (r - l + 1 < len) {
len = r - l + 1;
ansL = l;
}
if (ori.find(s[l]) != ori.end()) {
--cnt[s[l]];
}
++l;
}
}
return ansL == -1 ? string() : s.substr(ansL, len);
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/minimum-window-substring/solution/zui-xiao-fu-gai-zi-chuan-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
*/
# include "leetcode.h"
class Solution {
public:
string minWindow(string s, string t) {
if(s.size() < t.size()) return "";
set<char> sset;
for(int i=0; i<t.size(); i++)
sset.insert(t[i]);
map<char, int> smap;
int left = 0, right = 0, res;
while(){
}
}
}; | true |
00ad48eaa9fd8556d6dc9d90f7c7352e7abdb251 | C++ | KhNishad/Programs-of-Data-Structure-and-Algorithms | /Linear search.cpp | UTF-8 | 375 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int i, n ,ar[13]={21,4,2,3,5,7,8,76,57,54,34,23,22} ;
cout<<"Enter the number to find :"<<endl;
cin>>n;
for(i=0;i<14;i++)
{
if(ar[i]==n)
{
cout<<"Element number "<<++i<<endl;
return 0;
}
}
cout<<"number not found"<<endl;
return 0;
}
| true |
eb2d19a2c8d0346b0329106d05a6d0bc058fc256 | C++ | SirNate0/Archival | /Utils.h | UTF-8 | 21,446 | 3.046875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <Urho3D/Graphics/Skeleton.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Graphics/DebugRenderer.h>
#include <Urho3D/Math/MathDefs.h>
#include <exception>
/// Unfinished code exception to be thrown.
struct Unfinished: public std::exception
{
};
inline void PrintBone(Urho3D::Skeleton& sk, Urho3D::Bone* bone, Urho3D::String indent = Urho3D::String::EMPTY)
{
using namespace Urho3D;
if (!bone)
return;
URHO3D_LOGRAW(indent + String(bone->name_) + "\n");
if (!bone->node_)
return;
for (auto child : bone->node_->GetChildren())
{
auto id = sk.GetBoneIndex(child->GetNameHash());
if (id != M_MAX_UNSIGNED)
PrintBone(sk,sk.GetBone(id),indent+"-");
}
return;
}
inline void PrintSkeleton(Urho3D::Skeleton sk)
{
using namespace Urho3D;
// if (!sk)
// {
// URHO3D_LOGERROR("Cannot print null skeleton.");
// return;
// }
PrintBone(sk, sk.GetRootBone());
}
/// Rescales the value x at time t lerping from min1 to max1 to a value between min2 and max2
inline float Rescale(float t1, float min1, float max1, float min2 = 0, float max2 = 1)
{
float t0 = (t1-min1)/(max1-min1);
float t2 = t0*(max2-min2) + min2;
return t2;
}
/// Returns an increasing Sawtooth |/|/| wave with period starting at t=0 to t=1 (basically a Modulus clamp on the interval).
inline float SawtoothWave(float t, float min = 0, float max = 1)
{
return min + (max - min) * Urho3D::AbsMod(t,1.f);
}
/// Emits a triangle wave where t = 0,1 corresponds to min and t = mid corresponds to max
inline float TriangleWave(float t, float min = 0, float max = 1)
{
// From Wikipedia, 2 * the absolute value of the specified sawtooth.
return min + (max - min) * 2 * Urho3D::Abs(t - Urho3D::Floor(t + 0.5f));
}
/// Emits a sort-of triangle wave that will go through the min to max point instead of through the excluded midle. Starts at exMin, goes to min, jumps to max, goes to exMax, reverses.
inline float OuterTriangleWave(float t, float excludedMin, float excludedMax, float min = 0, float max = 1)
{
using Urho3D::Abs;
auto excluded = Abs(excludedMax - excludedMin);
// auto excluded = Urho3D::Abs(excludedMax - excludedMin);
// if (excludedMax < excludedMin)
// Urho3D::Swap(min,max);
auto full = Abs(max - min);
auto region = full - excluded;
// region *= Urho3D::Sign(excluded);
region = Urho3D::Abs(region) * Urho3D::Sign(excludedMax - excludedMin);
return SawtoothWave(TriangleWave(t, excludedMin, excludedMin - region),min,max);
}
/// Smart (periodically) bounded triangle wave that will go from min to max to min through the middle if exmin < max and through the outside if min >= max. Reversing the periodic bounds will reverse which side the wave starts at.
inline float PeriodicTriangleWave(float t, float min, float max, float boundMin = 0, float boundMax = 1)
{
if (min < max)
if (boundMin < boundMax)
return TriangleWave(t, min, max);
else
return TriangleWave(t, max, min);
else
return OuterTriangleWave(t, min, max, boundMin, boundMax);
}
/// Returns 0 < min, 1 > min, and linear between the two.
inline float ClampRamp(float t, float min, float max)
{
if (t <= min)
return 0;
if (t >= max)
return 1;
return (t-min)/(max-min);
}
#include <cmath>
/// Hyperbolic Tangent based sigmoid step. Basically a smooth ClampRamp() that extends to +/- infinity.
inline float Sigmoid(float t, float min, float max)
{
return Rescale(tanh(Rescale(t,min,max,-1,1)),-1,1,min,max);
}
/// Sigmoid that is min at t=0 and max at t=inf, but close to max at t=max and close to min at t=min.
inline float PositiveSigmoid(float t, float min, float max)
{
float invT = 1/t;
float invMax = 1/min;
float invMin = 1/max;
float smoothed = Sigmoid(invT, invMin, invMax);
return 1/smoothed;
}
extern Urho3D::HashMap<Urho3D::String, Urho3D::String> uiStrings;
#include <Urho3D/UI/UI.h>
#include <Urho3D/UI/Text3D.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/Graphics/Renderer.h>
#include <Urho3D/Resource/ResourceCache.h>
namespace Urho3D
{
/// Samples values between min and max with even spacing.
inline PODVector<float> SampleLinspace(unsigned count, float min = 0, float max = 1)
{
PODVector<float> vals(count);
auto delta = (max - min) / count;
for (unsigned i = 0; i < count; ++i)
vals[i] = min + i*delta;
return vals;
}
/// Applies the function with specified extra arguments to the provided vector and returns the results
template <class F, class... T>
inline PODVector<float> ApplyTo(const PODVector<float>& pts, const F& fn, T&&... args)
{
PODVector<float> out(pts.Size());
for (unsigned i = 0; i < pts.Size(); ++i)
out[i] = fn(pts[i],std::forward(args)...);
return out;
}
/// Approximate equals for float based on provided tolerance
inline bool ApproximatelyEqual(float a, float b, float tolerance = 0.001f)
{
return Abs(a - b) <= tolerance;
}
inline float SmoothStep(float t, float min, float max)
{
// Scale, bias and saturate x to 0..1 range
t = Clamp((t - min) / (max - min), 0.0f, 1.0f);
// Evaluate polynomial
return t * t * (3 - 2 * t);
}
inline float InverseSmoothStep(float x) {
return 0.5 - Sin(Asin(1.0 - 2.0 * x) / 3.0);
}
// Returns binomial coefficient without explicit use of factorials,
// which can't be used with negative integers
inline int PascalTriangle(int a, int b) {
int result = 1;
for (int i = 0; i < b; ++i)
result *= (a - i) / (i + 1);
return result;
}
// Generalized smoothstep
inline float GeneralSmoothStep(int N, float x) {
x = Clamp(x, 0.f, 1.f); // x must be equal to or between 0 and 1
float result = 0;
for (int n = 0; n <= N; ++n)
result += PascalTriangle(-N - 1, n) *
PascalTriangle(2 * N + 1, N - n) *
pow(x, N + n + 1);
return result;
}
/// Store the values in the container in a VariantVector
template<class container>
VariantVector ConvertToVariantVector(const container& v)
{
VariantVector ret;
for (auto& s : v)
ret.EmplaceBack(s);
return ret;
}
/// Store the values in the string T*[] terminated with a sentinel nullptr (not included in the output)
template<class T>
VariantVector ConvertToVariantVector(T** v)
{
VariantVector ret;
for (T** p = v; *p; ++p)
ret.EmplaceBack(*p);
return ret;
}
//--------------------------
// Value To String Template
//--------------------------
/// Create a string from a type.
/// The base form must not be a reference so we can overload it with an int and not a const int& later.
template<class T>
String ToString(T val)
{
return val.ToString();
}
/// Create a string from a type.
template<class T>
String ToString(const T& val)
{
return val.ToString();
}
/// Create a string from a type.
template<> inline String ToString(const char* val) { return String(val); }
template<> inline String ToString(const String& val) { return String(val); }
template<> inline String ToString(bool val) { return String(val); }
template<> inline String ToString(float val) { return String(val); }
template<> inline String ToString(double val) { return String(val); }
template<> inline String ToString(int val) { return String(val); }
template<> inline String ToString(unsigned val) { return String(val); }
//-------------------------
// Get JSON Value Template
//-------------------------
template<class T>
inline bool GetJSON(JSONValue& holder, T& val);
template<>
inline bool GetJSON(JSONValue& holder, bool& val)
{
if (holder.IsBool())
{
val = holder.GetBool();
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, int& val)
{
if (holder.IsNumber())
{
val = holder.GetInt();
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, unsigned& val)
{
if (holder.IsNumber())
{
val = holder.GetUInt();
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, float& val)
{
if (holder.IsNumber())
{
val = holder.GetFloat();
return true;
}
else if (holder.IsNull())
{
val = NAN;
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, double& val)
{
if (holder.IsNumber())
{
val = holder.GetDouble();
return true;
}
else if (holder.IsNull())
{
val = NAN;
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, String& val)
{
if (holder.IsString())
{
val = holder.GetString();
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, JSONArray& val)
{
if (holder.IsString())
{
val = holder.GetArray();
return true;
}
return false;
}
template<>
inline bool GetJSON(JSONValue& holder, JSONObject& val)
{
if (holder.IsString())
{
val = holder.GetObject();
return true;
}
return false;
}
inline void AddLabel(DebugRenderer* dr, const Vector3& position, const String& name, const String& text, const Color& color, bool dynamicText){
auto* ui=dr->GetSubsystem<UI>();
auto labels = ui->GetRoot()->GetChild("LABELS",false);
if (!labels)
{
labels = ui->GetRoot()->CreateChild<UIElement>("LABELS");
labels->SetSize(ui->GetRoot()->GetSize());
}
Text* oldLabel = (Text*)labels->GetChild(name,false);
if(oldLabel)
{
auto* vp = dr->GetSubsystem<Renderer>()->GetViewport(0);
oldLabel->SetPosition(vp->WorldToScreenPoint(position));
oldLabel->SetColor(color);
if(!dynamicText)
return;
else
oldLabel->SetText(text);
}else{
Text* t = new Text(dr->GetContext());
t->SetText(text);
t->SetName(name);
// t->SetStyleAuto();
ResourceCache* cache = dr->GetSubsystem<ResourceCache>();
t->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 8);
auto* vp = dr->GetSubsystem<Renderer>()->GetViewport(0);
t->SetPosition(vp->WorldToScreenPoint(position));
t->SetColor(color);
t->SetTextAlignment(HA_CENTER);
labels->AddChild(t);
}
}
/// Removes all added label UI elements.
inline void ClearLabels(DebugRenderer* dr)
{
auto* ui=dr->GetSubsystem<UI>();
auto labels = ui->GetRoot()->GetChild("LABELS",false);
if (labels)
labels->Remove();
}
/// Add lines connecting the specified points
inline void AddLinesBetween(DebugRenderer* dr, const Matrix3x4& transform, const PODVector<Vector3>& points, const Color& color, bool depthTest)
{
for (unsigned i = 0; i + 1 < points.Size(); ++i)
{
dr->AddLine(transform*points[i],transform*points[i+1],color,depthTest);
}
}
/// Add an RGB XYZ axes matching the world transform.
inline void AddWorldTransform(DebugRenderer* dr, const Matrix3x4& transform, bool depthTest)
{
dr->AddLine(transform*Vector3::ZERO,transform*Vector3::RIGHT,Color::RED,depthTest);
dr->AddLine(transform*Vector3::ZERO,transform*Vector3::UP,Color::GREEN,depthTest);
dr->AddLine(transform*Vector3::ZERO,transform*Vector3::FORWARD,Color::BLUE,depthTest);
}
inline void ShowSkeleton(DebugRenderer* dr, const Skeleton& skeleton, const Color& color, bool depthTest)
{
const Vector<Bone>& bones = skeleton.GetBones();
if (!bones.Size())
return;
unsigned uintColor = color.ToUInt();
for (unsigned i = 0; i < bones.Size(); ++i)
{
// Skip if bone contains no skinned geometry
if (bones[i].radius_ < M_EPSILON && bones[i].boundingBox_.Size().LengthSquared() < M_EPSILON)
continue;
Node* boneNode = bones[i].node_;
if (!boneNode)
continue;
Vector3 start = boneNode->GetWorldPosition();
Vector3 end;
unsigned j = bones[i].parentIndex_;
Node* parentNode = boneNode->GetParent();
// If bone has a parent defined, and it also skins geometry, draw a line to it. Else draw the bone as a point
if (parentNode && (bones[j].radius_ >= M_EPSILON || bones[j].boundingBox_.Size().LengthSquared() >= M_EPSILON))
end = parentNode->GetWorldPosition();
else
end = start;
dr->AddLine(start, end, uintColor, depthTest);
dr->AddCross(start,0.02f,color,depthTest);
AddLabel(dr, start, ToString("Bone %d",i),bones[i].name_, Color(color.r_*0.75f,color.g_*0.75f,color.b_*0.75f,color.a_), false);
}
}
/// Utility to compute x to a given power while preserving it's sign.
inline float SignedPow(float x, float power)
{
return Sign(x) * Pow(Abs(x), power);
}
inline float SignedAngle(Vector3 from, Vector3 to, Vector3 axis)
{
float unsignedAngle = from.Angle(to);
float sign = axis.DotProduct(from.CrossProduct(to));
if(sign<0)
unsignedAngle = -unsignedAngle;
return unsignedAngle;
}
inline Vector3 VectorClamp(Vector3 vec, float maxLength)
{
float length = vec.Length();
if (Equals(length,0.f))
return vec;
return vec / length * Clamp(length,0.f,maxLength);
}
/// Returns the manhattan length of the vector (vec.DotProduct(ONE)).
inline float VectorSumComponents(const Vector2& vec)
{
return vec.x_ + vec.y_;
}
/// Returns the manhattan length of the vector (vec.DotProduct(ONE)).
inline float VectorSumComponents(const Vector3& vec)
{
return vec.x_ + vec.y_ + vec.z_;
}
template<class V>
inline bool FuzzyEqual(V lhs, V rhs)
{
V diff = rhs - lhs;
for (int i = 0; i < sizeof(V)/sizeof(float); ++i)
if (Abs(diff.Data()[i]) > M_EPSILON)
return false;
return true;
}
inline bool FuzzyEqual(Quaternion lhs, Quaternion rhs, float fuzzy = 0.0001f)
{
auto diff = rhs - lhs;
return Abs(diff.x_) <= fuzzy && Abs(diff.y_) <= fuzzy && Abs(diff.z_) <= fuzzy && Abs(diff.w_) <= fuzzy;
}
inline Vector3 operator%(const Vector3& lhs, float rhs)
{
return {Mod(lhs.x_, rhs), Mod(lhs.y_, rhs), Mod(lhs.z_, rhs)};
}
inline Vector3& operator %= (Vector3& lhs, float rhs)
{
return lhs = lhs % rhs;
}
template<template<class, typename...> class V, class T, typename... extra>
T Sum(const V<T,extra...>& container, const T& initial = {})
{
T sum = initial;
for (const T& t : container)
sum += t;
return sum;
}
template<class T>
T Sum(const Vector<T>& container, const T& initial = {})
{
T sum = initial;
for (const T& t : container)
sum += t;
return sum;
}
template<class T>
T Sum(const PODVector<T>& container, const T& initial = {})
{
T sum = initial;
for (const T& t : container)
sum += t;
return sum;
}
template<class V, class T>
T Prod(const V& container)
{
T sum{};
for (const T& t : container)
sum += t;
return sum;
}
template<class T>
Vector<T> Reversed(const Vector<T>& v)
{
Vector<T> out;
out.Reserve(v.Size());
for (unsigned i = v.Size(); i > 0; --i)
out.Push(v[i-1]);
return out;
}
namespace DebugRendererUtils
{
//inline AddArc
}
}
namespace Tests {
#if 0
PODVector<float> pts = SampleLinspace(500,-1,2);
ImGuiBackend::Graph("graph",pts.Buffer(),pts.Size());
{
auto tri = ApplyTo(pts,[](float pt){return TriangleWave(pt,0.25,0.75);});
ImGuiBackend::Graph("tri lh",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return TriangleWave(pt,0.75,0.25);});
ImGuiBackend::Graph("tri hl",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return OuterTriangleWave(pt,0.25,0.75);});
ImGuiBackend::Graph("otri lh",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return OuterTriangleWave(pt,0.75,0.25);});
ImGuiBackend::Graph("otri hl",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return OuterTriangleWave(pt,0.25,0.75,1,0);});
ImGuiBackend::Graph("otri lh2",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return OuterTriangleWave(pt,0.75,0.25,1,0);});
ImGuiBackend::Graph("otri hl2",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return PeriodicTriangleWave(pt,0.05,0.75);});
ImGuiBackend::Graph("stri lh",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return PeriodicTriangleWave(pt,0.75,0.05);});
ImGuiBackend::Graph("stri hl",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return PeriodicTriangleWave(pt,0.05,0.75,1,0);});
ImGuiBackend::Graph("stri lh2",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return PeriodicTriangleWave(pt,0.75,0.05,1,0);});
ImGuiBackend::Graph("stri hl2",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return SawtoothWave(pt,0.25,0.75);});
ImGuiBackend::Graph("sawtooth lh",tri.Buffer(),tri.Size());
}
{
auto tri = ApplyTo(pts,[](float pt){return SawtoothWave(pt,0.75,0.25);});
ImGuiBackend::Graph("saw hl",tri.Buffer(),tri.Size());
}
#endif
}
template<class C, int N>
class DequeuingRingQueue
{
public:
DequeuingRingQueue(): buffer_{} {}
const C& operator=(const C& insert) {
buffer_[write_idx] = insert;
++write_idx;
write_idx %= N;
size += 1;
if (size > N)
{
++read_idx;
read_idx %= N;
size = N;
}
return insert;
}
operator C() {
if (size)
{
++read_idx;
read_idx %= N;
--size;
return buffer_[read_idx];
}
else
{
assert(!"EMPTY BUFFER");
}
}
int Size() const {return size;}
private:
C buffer_[N];
int read_idx{0};
int write_idx{0};
int size{0};
};
template<class C, int N>
class RingQueue
{
public:
RingQueue(): buffer_{} {}
const C& operator=(const C& insert) {
buffer_[write_idx] = insert;
++write_idx;
write_idx %= N;
size += 1;
if (size > N)
{
++read_idx;
read_idx %= N;
size = N;
}
return insert;
}
operator C() {
if (size)
{
auto old = read_idx;
++read_idx;
read_idx %= N;
return buffer_[old];
}
else
{
assert(!"EMPTY BUFFER");
}
}
int Size() const {return size;}
void SetReadOldest()
{
read_idx = (write_idx-size)%N;
}
private:
C buffer_[N];
int read_idx{0};
int write_idx{0};
int size{0};
};
template <unsigned N, class T, class Weight=float>
class AverageOver
{
public:
struct ValWeight
{
T value;
Weight weight;
ValWeight(const T& val, const Weight& w): value{val}, weight{w} {}
};
T operator=(const ValWeight& vw)
{
if (vw.weight > 1e-4)
{
values_[idx] = vw.value;
weights_[idx] = vw.weight;
idx = (idx+1)%N;
}
return Value();
}
void SetValue(const T& val, const Weight& w)
{
if (w > 1e-4)
{
values_[idx] = val;
weights_[idx] = w;
idx = (idx+1)%N;
}
}
T Value() const {
T val{};
Weight total{};
for (unsigned i = 0; i < N; ++i)
{
val += values_[i] * weights_[i];
total += weights_[i];
}
if (total < 1e-4)
return {};
return val / total;
}
operator T() { return Value(); }
private:
std::array<T,N> values_;
std::array<Weight,N> weights_;
unsigned idx = 0;
};
template <unsigned N, class T, class Weight=float>
class AverageOverWithMax
{
public:
AverageOverWithMax(Weight maxTotal): max{maxTotal} {}
struct ValWeight
{
T value;
Weight weight;
ValWeight(const T& val, const Weight& w): value{val}, weight{w} {}
};
T operator=(const ValWeight& vw)
{
if (vw.weight > 1e-4)
{
values_[idx] = vw.value;
weights_[idx] = vw.weight;
TrimMax();
idx = (idx+1)%N;
}
return Value();
}
void SetValue(const T& val, const Weight& w)
{
if (w > 1e-4)
{
values_[idx] = val;
weights_[idx] = w;
TrimMax();
idx = (idx+1)%N;
}
}
T Value() const {
T val{};
Weight total{};
for (unsigned i = 0; i < N; ++i)
{
val += values_[i] * weights_[i];
total += weights_[i];
}
if (total < 1e-4)
return {};
return val / total;
}
operator T() { return Value(); }
private:
std::array<T,N> values_;
std::array<Weight,N> weights_;
unsigned idx = 0;
Weight max;
void TrimMax()
{
Weight total{};
// Only up to N-1 as we don't want to remove the just added term
for (unsigned i = 0; i+1 < N; ++i)
{
unsigned ci = (N + idx - i) % N;
total += weights_[ci];
if (total >= max)
{
values_[ci] = {};
weights_[ci] = 0;
}
}
}
};
| true |
81b6841e63ff54737b1bc5d60d5566b50711c56a | C++ | aiekick/engine | /src/modules/util/Console.h | UTF-8 | 2,617 | 2.703125 | 3 | [] | no_license | #pragma once
#include <SDL.h>
#include <vector>
#include <string>
#include "core/Var.h"
#include "core/IComponent.h"
#include "math/Rect.h"
namespace util {
enum ConsoleColor {
WHITE, BLACK, GRAY, BLUE, GREEN, YELLOW, RED, MAX_COLORS
};
extern std::string getColor(ConsoleColor color);
class Console : public core::IComponent {
protected:
typedef std::vector<std::string> Messages;
typedef Messages::const_reverse_iterator MessagesIter;
Messages _messages;
Messages _history;
uint32_t _historyPos = 0;
bool _consoleActive = false;
SDL_LogOutputFunction _logFunction = nullptr;
core::VarPtr _autoEnable;
std::string _commandLine;
// commandline character will get overwritten if this is true
bool _overwrite = false;
bool _cursorBlink = false;
int _frame = 0;
int _cursorPos = 0;
int _scrollPos = 0;
int _maxLines = 0;
static std::string removeAnsiColors(const char* message);
static void logConsole(void *userdata, int category, SDL_LogPriority priority, const char *message);
// cursor move on the commandline
void cursorLeft();
void cursorRight();
void cursorWordLeft();
void cursorWordRight();
// history 'scroll' methods
void cursorUp();
void cursorDown();
void scrollUp(const int lines = 1);
void scrollDown(const int lines = 1);
void scrollPageUp();
void scrollPageDown();
void executeCommandLine();
// removed the character under the cursor position
void cursorDelete(bool moveCursor = true);
void cursorDeleteWord();
bool insertClipboard();
void insertText(const std::string& text);
void drawString(int x, int y, const std::string& str, int len);
virtual void beforeRender(const math::Rect<int> &rect) {}
virtual void afterRender(const math::Rect<int> &rect) {}
virtual int lineHeight() = 0;
virtual glm::ivec2 stringSize(const char *c, int length) = 0;
virtual void drawString(int x, int y, const glm::ivec4& color, const char* str, int len) = 0;
public:
Console();
virtual ~Console() {}
virtual void construct();
virtual bool init() override;
virtual void shutdown() override;
virtual bool toggle();
void clear();
void clearCommandLine();
void render(const math::Rect<int> &rect, long deltaFrame);
bool isActive() const;
bool onTextInput(const std::string& text);
bool onKeyPress(int32_t key, int16_t modifier);
bool onMouseWheel(int32_t x, int32_t y);
bool onMouseButtonPress(int32_t x, int32_t y, uint8_t button);
void autoComplete();
const std::string& commandLine() const;
};
inline bool Console::isActive() const {
return _consoleActive;
}
inline const std::string& Console::commandLine() const {
return _commandLine;
}
}
| true |
1ca2a08fc94cf8c9ed1e6db248873308e0b0ede9 | C++ | ericlin1001/offlineJudge | /hws/problem1/16308109/zuoye.cpp | UTF-8 | 617 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
int main()
{
ifstream inData;
ofstream outdata;
inData.open("name.dat");
float a,b,c,d,e,f,g,h,i,j,k,l;
cin>>a>>b>>c>>d>>e>>f>>g>>h>>i>>j>>k>>l;
outdata.open("temdata.dat");
cout<<a<<'\t'<<endl;
cout<<b<<'\t'<<b-a<<endl;
cout<<c<<'\t'<<c-b<<endl;
cout<<d<<'\t'<<d-c<<endl;
cout<<e<<'\t'<<e-d<<endl;
cout<<f<<'\t'<<f-e<<endl;
cout<<g<<'\t'<<g-f<<endl;
cout<<h<<'\t'<<h-g<<endl;
cout<<i<<'\t'<<i-h<<endl;
cout<<j<<'\t'<<j-i<<endl;
cout<<k<<'\t'<<k-j<<endl;
cout<<l<<'\t'<<l-k<<endl;
return 0;
}
| true |
7051824a31d5ac081947fa736870a13814684f76 | C++ | sharhar/Grapher2DCL | /VS/CLTest/GLUI/CheckBox.cpp | UTF-8 | 3,004 | 2.59375 | 3 | [
"MIT"
] | permissive | #include <GLUI/GLUI.h>
#include <GLUIExt.h>
namespace glui {
CheckBox::CheckBox(Rectangle bounds, Layout* layout, std::string text, CheckBoxDescriptor desc) :
GLUIObject(bounds,layout){
m_text = text;
m_desc = desc;
m_checked = desc.checkedAtStart;
m_prevDown = false;
}
void CheckBox::poll() {
float posx = input::InputData::mousePosx * m_layout->getScaleX();
float posy = input::InputData::mousePosy * m_layout->getScaleY();
bool down = input::InputData::mouseLeftDown;
bool hovering = posx >= m_bounds.x &&
posx <= m_bounds.x + m_bounds.w &&
m_layout->getHeight() - posy >= m_bounds.y &&
m_layout->getHeight() - posy <= m_bounds.y + m_bounds.h;
if (down && !m_prevDown) {
if (hovering) {
m_checked = !m_checked;
}
m_prevDown = true;
} else if (!down && m_prevDown) {
m_prevDown = false;
}
}
void CheckBox::render() {
glBegin(GL_QUADS);
glColor3f(m_desc.theme.outline.r, m_desc.theme.outline.g, m_desc.theme.outline.b);
glVertex2f(m_bounds.x - m_desc.outLineThickness, m_bounds.y - m_desc.outLineThickness);
glVertex2f(m_bounds.x + m_bounds.w + m_desc.outLineThickness, m_bounds.y - m_desc.outLineThickness);
glVertex2f(m_bounds.x + m_bounds.w + m_desc.outLineThickness, m_bounds.y + m_bounds.h + m_desc.outLineThickness);
glVertex2f(m_bounds.x - m_desc.outLineThickness, m_bounds.y + m_bounds.h + m_desc.outLineThickness);
glColor3f(m_desc.theme.body.r, m_desc.theme.body.g, m_desc.theme.body.b);
glVertex2f(m_bounds.x , m_bounds.y );
glVertex2f(m_bounds.x + m_bounds.w, m_bounds.y );
glVertex2f(m_bounds.x + m_bounds.w, m_bounds.y + m_bounds.h);
glVertex2f(m_bounds.x , m_bounds.y + m_bounds.h);
glEnd();
glPushMatrix();
glTranslatef(m_bounds.x + m_bounds.w/2.0f, m_bounds.y + m_bounds.h/2.0f, 0);
glRotatef(-30, 0, 0, 1);
glBegin(GL_QUADS);
if(m_checked) {
glColor3f(m_desc.theme.check.r, m_desc.theme.check.g, m_desc.theme.check.b);
glVertex2f( 0 , -m_bounds.h/2.0f + m_bounds.h/15.0f);
glVertex2f( m_bounds.w/15.0f * 2, -m_bounds.h/2.0f + m_bounds.h/15.0f);
glVertex2f( m_bounds.w/15.0f * 2, m_bounds.h/2.0f - m_bounds.h/15.0f);
glVertex2f( 0 , m_bounds.h/2.0f - m_bounds.h/15.0f);
glVertex2f(-m_bounds.w/15.0f * 3.5f, -m_bounds.h/2.0f + m_bounds.h/15.0f + m_bounds.h / 20.0f);
glVertex2f( m_bounds.w/15.0f , -m_bounds.h/2.0f + m_bounds.h/15.0f );
glVertex2f( m_bounds.w/15.0f , -m_bounds.h/2.0f + m_bounds.h/15.0f * 3 );
glVertex2f(-m_bounds.w/15.0f * 3.5f, -m_bounds.h/2.0f + m_bounds.h/15.0f * 3 + m_bounds.h / 20.0f);
}
glEnd();
glPopMatrix();
Renderer::drawString(m_text, m_bounds.x + m_bounds.w + m_desc.outLineThickness + 3, m_bounds.y + m_desc.textStyle.size/10.0f, m_desc.textStyle.size, m_desc.textStyle.font, &(m_desc.theme.text));
}
} | true |
aff3c266c26098d546fe18da6bf229e3d9e4bf6d | C++ | AlexNilbak/Class_1 | /Autotest.h | UTF-8 | 603 | 2.84375 | 3 | [] | no_license | #pragma once
#include "CPoint.h"
#include "CDist.h"
using namespace std;
int Autotest1(){
CPoint A(0,1);
CDist B(1,2);
CPoint S=A+B;
if (S.X()==1 && S.Y()==3){
return 0;
}
else{
return 1;
}
}
int Autotest2(){
CDist A(-1,0);
CPoint B(1,2);
CPoint S=A+B;
if (S.X()==0 && S.Y()==2){
return 0;
}
else{
return 1;
}
}
int Autotest3(){
CPoint A(2,1);
CPoint B(1,2);
CDist S=A-B;
if (S.X()==1 && S.Y()==-1){
return 0;
}
else{
return 1;
}
}
| true |
4b4894ea3d9b9d50e5c86bd4e831387e3b8046cc | C++ | ElenoMome/atcoder | /others/typical_dp/B.cpp | UTF-8 | 2,636 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#include <tuple>
#include <cstdio>
#include <bitset>
#include <sstream>
#include <iterator>
#include <numeric>
#include <map>
#include <cstring>
using namespace std;
//#define DEBUG_ //!!提出時にコメントアウト!!
#ifdef DEBUG_
#define dump(x) cerr << #x << " = " << (x) << endl;
#else
#define dump(x) ; //何もしない文
#endif
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define SZ(x) ((int)(x).size()) //unsignedのサイズをint型に変換
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;
template <typename T>
std::string printVector(const std::vector<T> &data)
{
std::stringstream ss;
std::ostream_iterator<T> out_it(ss, ", ");
ss << "[";
std::copy(data.begin(), data.end() - 1, out_it);
ss << data.back() << "]";
return ss.str();
}
const int MOD = 1e9+7;
int a[1010], b[1010];
int A,B;
int dp[1010][1010];
int rec(int ta, int tb, int init)
{
dump(ta)
dump(tb)
if(dp[ta][tb] != -1)
{
dump("hit!")
return dp[ta][tb];
}
bool turn = ((ta + tb) % 2) == init % 2; // 1:先手番 0:後手番
if(turn) //先手番
{
if(ta == 0)
{
dp[ta][tb] = rec(0, tb-1, init) + b[B-tb];
return rec(0, tb-1, init) + b[B-tb];
}
else if(tb == 0)
{
dp[ta][tb] = rec(ta-1, 0, init) + a[A-ta];
return rec(ta-1, 0, init) + a[A-ta];
}
else
{
dp[ta][tb] = max(rec(ta-1,tb,init)+a[A-ta], rec(ta,tb-1,init)+b[B-tb]);
return max(rec(ta-1,tb,init)+a[A-ta], rec(ta,tb-1,init)+b[B-tb]);
}
}
else //後手番
{
if(ta == 0)
{
dp[ta][tb] = rec(0,tb-1,init);
return rec(0,tb-1,init);
}
else if(tb == 0)
{
dp[ta][tb] = rec(ta-1,tb,init);
return rec(ta-1,tb,init);
}
else
{
dp[ta][tb] = min(rec(ta-1,tb,init), rec(ta,tb-1,init));
return min(rec(ta-1,tb,init), rec(ta,tb-1,init));
}
}
}
//ここから書き始める
int main(int argc, char const *argv[])
{
cin.tie(0);
ios::sync_with_stdio(false);
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
cin >> A >> B;
REP(i,A)
{
cin >> a[i];
}
REP(i,B)
{
cin >> b[i];
}
dump(A)
dump(B)
cout << rec(A,B,A+B) << endl;
}
| true |
9ae41a102aa0daf8e36f260d90168f0001332521 | C++ | EvertonCa/ProgrammingMarathon | /Graphs/1317 - Eu Odeio SPAM, Mas Algumas Pessoas Amam.cpp | UTF-8 | 4,562 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm> // sort
#include <string.h> // memset
#include <list>
#define LIMPO 0
#define INFECTANDO 1
#define INFECTADO 2
using namespace std;
vector<vector<int>> conexoes;
class Spam
{
public:
int originador, limite1, limite2;
string a1, a2, a3;
public:
Spam(int originador, int t1, int t2, string a1, string a2, string a3)
{
this->originador = originador;
this->limite1 = t1;
this->limite2 = t2;
this->a1 = a1;
this->a2 = a2;
this->a3 = a3;
}
};
vector <Spam> vetorDeSpams;
class Pessoa
{
public:
string nome;
int indice;
vector<string> vetorDeSpamsPegos;
vector<int> vetorVerificadorDeSpamPego;
public:
Pessoa(string nome, int indice, int quantidadeDeSpams)
{
this->nome = nome;
this->indice = indice;
for (int i = 0; i < quantidadeDeSpams; ++i)
{
vetorVerificadorDeSpamPego.push_back(LIMPO);
}
inicializaSpam(quantidadeDeSpams);
}
void adicionaSpam(string spam, int indiceDoSpam)
{
vetorDeSpamsPegos[indiceDoSpam] = spam;
}
void inicializaSpam(int quantidadeDeSpams)
{
for (int i = 0; i < quantidadeDeSpams; ++i)
{
vetorDeSpamsPegos.push_back(vetorDeSpams[i].a1);
}
}
void infectando(int indice)
{
vetorVerificadorDeSpamPego[indice] = INFECTANDO;
}
void infectado(int indice)
{
vetorVerificadorDeSpamPego[indice] = INFECTADO;
}
void mostrarInfeccoes()
{
cout << nome << ": ";
for (int i = 0; i < vetorDeSpamsPegos.size(); ++i)
{
cout << vetorDeSpamsPegos[i] << " ";
}
cout << endl;
}
};
vector <Pessoa> vetorDePessoas;
void infecta(int indiceDaPessoa, int indiceDoSpam)
{
int quantidadeDeEmails;
quantidadeDeEmails = conexoes[indiceDaPessoa].size();
if(vetorDePessoas[indiceDaPessoa].vetorVerificadorDeSpamPego[indiceDoSpam] == LIMPO)
{
if(quantidadeDeEmails < vetorDeSpams[indiceDoSpam].limite1)
{
vetorDePessoas[indiceDaPessoa].adicionaSpam(vetorDeSpams[indiceDoSpam].a1, indiceDoSpam);
}
else if(quantidadeDeEmails >= vetorDeSpams[indiceDoSpam].limite1 && quantidadeDeEmails < vetorDeSpams[indiceDoSpam].limite2)
{
vetorDePessoas[indiceDaPessoa].adicionaSpam(vetorDeSpams[indiceDoSpam].a2, indiceDoSpam);
}
else
{
vetorDePessoas[indiceDaPessoa].adicionaSpam(vetorDeSpams[indiceDoSpam].a3, indiceDoSpam);
}
vetorDePessoas[indiceDaPessoa].infectando(indiceDoSpam);
}
}
void infectar_E_Espalhar(int originario, int indiceDoSpam)
{
infecta(originario, indiceDoSpam);
for (int i = 0; i < conexoes[originario].size(); ++i)
{
if(vetorDePessoas[conexoes[originario][i]].vetorVerificadorDeSpamPego[indiceDoSpam] == LIMPO )
{
infectar_E_Espalhar(conexoes[originario][i], indiceDoSpam);
}
}
vetorDePessoas[originario].infectado(indiceDoSpam);
}
int main()
{
while(true)
{
int numeroDePessoas;
cin >> numeroDePessoas;
if(numeroDePessoas == 0)
break;
vector<vector<int>> temp(numeroDePessoas);
conexoes = temp;
for (int i = 0; i < numeroDePessoas; ++i)
{
int pessoa;
cin >> pessoa;
while(pessoa != 0)
{
conexoes[i].push_back(pessoa-1);
cin >> pessoa;
}
}
int originadorDoSpam, t1, t2;
string a1, a2, a3;
cin >> originadorDoSpam;
while(originadorDoSpam != 0)
{
cin >> t1 >> t2 >> a1 >> a2 >> a3;
Spam temp(originadorDoSpam, t1, t2, a1, a2, a3);
vetorDeSpams.push_back(temp);
cin >> originadorDoSpam;
}
for (int j = 0; j < numeroDePessoas; ++j)
{
string nomeTemp;
cin >> nomeTemp;
Pessoa temp(nomeTemp, j, vetorDeSpams.size());
vetorDePessoas.push_back(temp);
}
for (int j = 0; j < vetorDeSpams.size(); ++j)
{
infectar_E_Espalhar(vetorDeSpams[j].originador - 1, j);
}
for (int k = 0; k < vetorDePessoas.size(); ++k)
{
vetorDePessoas[k].mostrarInfeccoes();
}
conexoes.clear();
vetorDeSpams.clear();
vetorDePessoas.clear();
}
} | true |
d17961fa9cae84ce22984a7a80486d4c0b585fd5 | C++ | navispeed/IFT-3100 | /src/model/material/Material.h | UTF-8 | 956 | 2.734375 | 3 | [] | no_license | #pragma once
#include <ofMain.h>
#include "MaterialType.h"
#include "BaseMaterial.h"
#include "MaterialGouraud.h"
#include "MaterialLambert.h"
#include "MaterialPhong.h"
enum class typeIllum:int {
BASE,GOURAUD,LAMBERT,PHONG
};
class Material {
public:
void beginMaterial(map<int,ofLight*> &lights);
void endMaterial();
void changeMaterialType(typeIllum type);
void setEmissiveColor(ofColor color);
const ofColor getEmissiveColor();
void setSpecularColor(ofColor color);
const ofColor getSpecularColor();
void setDiffuseColor(ofColor color);
const ofColor getDiffuseColor();
void setAmbientColor(ofColor color);
const ofColor getAmbientColor();
void setShininess(float shininess);
const float getShininess();
private:
typeIllum currentMaterial = typeIllum::BASE;
MaterialType * material = new BaseMaterial();
ofColor emissiveColor;
ofColor specularColor;
ofColor diffuseColor;
ofColor ambientColor;
float shininess = 0;
};
| true |
42de9e8b3d17017c575e12b109525af71c8d47b6 | C++ | csi-byte/cpp-maze-resolver-2016 | /maze-master/model/algorithm.h | ISO-8859-1 | 2,603 | 2.734375 | 3 | [
"MIT"
] | permissive | #ifndef ALGORITHM_H
#define ALGORITHM_H
//baptiste millot -- pierre antoine duchange 2017
class Maze;
class Room;
class Door;
#include<iostream>
#include <fstream>
#include "mazesolver.h"
#include "mazegenerator.h"
#include <stack>
//
using typePileRoom = std::stack<Room *>; // type d'un stack de *room
using typeTabVectorInt = std::vector<unsigned int>;
//using typeTabvectorVectorInt = std::vector<std::vector<unsigned int>>;
class debug {
public:
debug();
std::ofstream file;
void ecrire(std::string text);
void ecrire(int text);
};
class DFSMazeGenerator : public MazeGenerator, public debug {
Room* it_room;
public:
DFSMazeGenerator(Maze* maze);
bool isFinished() override;
void step() override;
bool condition; // condition pour fin du step()
int periode;
typePileRoom pile;
Room * itMain;
bool marcheADebut;
};
class KruskallMazeGenerator : public MazeGenerator, public debug {
public:
KruskallMazeGenerator(Maze* maze);
typeTabVectorInt tableauCell; // tableaux avec ID pour chaque cellule du maze unique.
typeTabVectorInt indiceDoorsTableau; // tableau qui sert appeler des portes au hasard
typeTabVectorInt::iterator doorsAleaIndice; //iterateur sur tab
Maze::DoorIterator It_doors; // iterator sur les portes
//bool belongDistingsSet(typeTabvectorVectorInt &tabSETcell, unsigned int &numerocell1, unsigned int &intnumerocell2);----> obsolte
//fonction qui sert dterminer si il existe un chemin entre 2 cellules ----> obsolte
bool isFinished() override;
void step() override;
};
class OpenAllMazeGenerator : public MazeGenerator, public debug {
Maze::DoorIterator nextDoorIt_;
public:
OpenAllMazeGenerator(Maze* maze);
int periode;
bool isFinished() override;
void step() override;
};
using typePileLockedRoom = std::stack<Direction>; // type d'un stack de lockedroom
//************* solvers
class DFSProgram : public MazeSolver::Program {
public:
typePileLockedRoom pile;
Direction direction;
Direction move(LockedRoom currentRoom, std::vector<AdjLockedRoom> adjRooms, const Position& targetPosition) override;
};
class CustomProgram : public MazeSolver::Program {
public:
CustomProgram();
int ratioB ;
int ratioE ;
typePileLockedRoom pile;
Direction direction;
Direction move(LockedRoom currentRoom, std::vector<AdjLockedRoom> adjRooms, const Position& targetPosition) override;
};
class RandomProgram : public MazeSolver::Program {
public:
Direction move(LockedRoom currentRoom, std::vector<AdjLockedRoom> adjRooms, const Position& targetPosition) override;
};
#endif // ALGORITHM_H
| true |
f04dcf97816446ab40e089db7e165b33c7368693 | C++ | pdschubert/WALi-OpenNWA | /Source/wali/lib/Markable.cpp | UTF-8 | 962 | 2.96875 | 3 | [
"MIT"
] | permissive | /*!
* @author Nicholas Kidd
*/
#include "wali/Common.hpp"
#include "wali/Markable.hpp"
namespace wali
{
Markable::Markable() : IMarkable(), marker(false) {}
/*!
* Anytime a Markable is created it is in the unmarked state.
* This makes the copy constructor do nothing.
*/
Markable::Markable( const Markable& m ATTR_UNUSED ) : IMarkable(), marker(false)
{
(void) m;
}
/*!
* The Markable object is already created and may or may not
* be marked. operator= does not perform any action b/c the
* interface of Markable specifies that state may only
* be changed through mark and unmark.
*/
Markable& Markable::operator=( const Markable& m ATTR_UNUSED )
{
(void) m;
return *this;
}
Markable::~Markable() {}
void Markable::mark() const throw()
{
marker = true;
}
void Markable::unmark() const throw()
{
marker = false;
}
bool Markable::marked() const throw()
{
return marker;
}
}
| true |
40fd8a81b40ff752a1c28fc2b8b38adb39d2c1ab | C++ | a-kashirin-official/spbspu-labs-2018 | /egorov.maxim/common/rectangle.cpp | UTF-8 | 2,592 | 3.25 | 3 | [] | no_license | #include "rectangle.hpp"
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace egorov;
Rectangle::Rectangle(const rectangle_t &rectangle) :
rectangle_(rectangle),
points_ {{rectangle_.pos.x - rectangle_.width / 2, rectangle_.pos.y + rectangle_.height / 2},
{rectangle_.pos.x + rectangle_.width / 2, rectangle_.pos.y + rectangle_.height / 2},
{rectangle_.pos.x - rectangle_.width / 2, rectangle_.pos.y - rectangle_.height / 2},
{rectangle_.pos.x + rectangle_.width / 2, rectangle_.pos.y - rectangle_.height / 2}}
{
if (rectangle_.height < 0.0 || rectangle_.width < 0.0)
{
throw std::invalid_argument("invalid_input");
}
}
double Rectangle::getArea() const noexcept
{
return rectangle_.width * rectangle_.height;
}
rectangle_t Rectangle::getFrameRect() const noexcept
{
point_t top_left = rectangle_.pos;
point_t bottom_right = rectangle_.pos;
for (size_t i = 0; i < 4; i++)
{
if (points_[i].x < top_left.x)
{
top_left.x = points_[i].x;
}
if (points_[i].y > top_left.y)
{
top_left.y = points_[i].y;
}
if (points_[i].x > bottom_right.x)
{
bottom_right.x = points_[i].x;
}
if (points_[i].y < bottom_right.y)
{
bottom_right.y = points_[i].y;
}
}
return {bottom_right.x - top_left.x, top_left.y - bottom_right.y, {rectangle_.pos}};
}
void Rectangle::move(const point_t &point) noexcept
{
move(point.x - rectangle_.pos.x, point.y - rectangle_.pos.y);
}
void Rectangle::move(const double deltaX, const double deltaY) noexcept
{
rectangle_.pos.x += deltaX;
rectangle_.pos.y += deltaY;
for (size_t i = 0; i < 4; i++)
{
points_[i].x += deltaX;
points_[i].y += deltaY;
}
}
void Rectangle::scale(const double coefficent)
{
if (coefficent < 0.0 )
{
throw std::invalid_argument("invalid_coefficent");
}
rectangle_.height *= coefficent;
rectangle_.width *= coefficent;
for (size_t i = 0; i < 4; i++)
{
points_[i] = {rectangle_.pos.x + coefficent * (points_[i].x - rectangle_.pos.x),
rectangle_.pos.y + coefficent * (points_[i].y - rectangle_.pos.y)};
}
}
void Rectangle::rotate(double angle) noexcept
{
angle = angle * M_PI / 180;
double cosA = cos(angle);
double sinA = sin(angle);
for (size_t i = 0; i < 4; i++)
{
points_[i] = {rectangle_.pos.x + cosA * (points_[i].x - rectangle_.pos.x) - sinA * (points_[i].y - rectangle_.pos.y),
rectangle_.pos.y + cosA * (points_[i].y - rectangle_.pos.y) + sinA * (points_[i].x - rectangle_.pos.x)};
}
}
std::string Rectangle::getName() const noexcept
{
return "Rectangle";
}
| true |
676bf43f20403faf1195d91f9fc00c45628e2f31 | C++ | Twinparadox/AlgorithmProblem | /Baekjoon/14489.cpp | UTF-8 | 166 | 2.75 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(void)
{
int a, b, c;
cin >> a >> b >> c;
if (a + b >= c * 2)
cout << (a + b) - c * 2;
else
cout << a + b;
}
| true |
25dd93bbaa2ab13560949599a88bbd6df4416fe7 | C++ | jlcrodrigues/Learning-cpp | /Sheet 1/Exercise 3/ex12.cpp | UTF-8 | 823 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
double area(double radius)
{
return pow(radius, 2) * 3.14156;
}
//returns the distance between 2 points (x1, y1) and (x2, y2)
double distance(double x1, double y1, double x2, double y2)
{
return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
}
//returns the area of a triangle using the heron's formula
double area(double x1, double y1, double x2, double y2, double x3, double y3)
{
double a, b, c; //lengths
double s; //semi-perimeter
a = distance(x1, y1, x2, y2);
b = distance(x1, y1, x3, y3);
c = distance(x2, y2, x3, y3);
s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
double area(double x1, double y1, double x2, double y2)
{
return abs(x1 - x2) * abs(y1 - y2);
}
int main()
{
return 0;
} | true |
ffd04659e7a09cfa41f5df769ee2bc6371f12fca | C++ | UniStuttgart-VISUS/tpf | /include/tpf/module/tpf_module_interface_parameters.h | UTF-8 | 1,246 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
namespace tpf
{
namespace modules
{
/// <summary>
/// Parameter interface for modules
/// </summary>
template <typename... Parameters>
class interface_parameters
{
public:
/// State that set_parameters(...) needs to be called before running the module
static constexpr bool needs_parameters() { return true; }
/// <summary>
/// Constructor.
/// </summary>
interface_parameters();
/// <summary>
/// Set the parameters needed for algorithm execution.
/// </summary>
void set_parameters(Parameters... parameters);
protected:
/// <summary>
/// Set the parameters needed for algorithm execution.
/// </summary>
virtual void set_algorithm_parameters(Parameters... parameters) = 0;
/// <summary>
/// Perform a sanity check on the parameters
/// </summary>
void sanity_check() const;
private:
/// Information for sanity checks
bool parameters_set;
};
}
}
#include "tpf_module_interface_parameters.inl"
| true |
95d6ee4ca3a4227a39608def6434fb7a11a03cad | C++ | rohitsingh2901/Fundamental_of_Cpp_questions | /DSA_Assignment_q5(number is Prime or Not).cpp | UTF-8 | 818 | 3.578125 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter any number: ";
cin>>n;
if (n%2==0 and n!=2)
{
cout<<"Number is not prime."<<endl;
}
else if(n%3==0 and n!=3)
{
cout<<"Number is not prime."<<endl;
}
else if(n%5==0 and n!=5)
{
cout<<"Number is not prime."<<endl;
}
else if (n%7==0 and n!=7)
{
cout<<"Number is not prime."<<endl;
}
else if(n%11==0 and n!=11)
{
cout<<"Number is not prime."<<endl;
}
else if (n==1)
{
cout<<"Number is not prime."<<endl;
}
else if (n<0)
{
cout<<"Negative numbers cannot be prime"<<endl;
}
else {
cout<<"Number is prime."<<endl;
}
return 0;
}
| true |
134ada8e05edee6c749f91eead21851e8a9e491b | C++ | roymacdonald/ofxHomography | /example/src/ofApp.cpp | UTF-8 | 2,853 | 2.78125 | 3 | [] | no_license | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
originalRect.set(0,0,ofGetWidth(), ofGetHeight());
originalRect.scaleFromCenter(0.7);
originalCorners = ofxHomography::rectangleToCorners(originalRect);
distortedCorners.resize(4);
for(int i =0; i < 4; i ++){
distortedCorners[i].x = originalCorners[i].x;
distortedCorners[i].y = originalCorners[i].y;
}
}
//--------------------------------------------------------------
void ofApp::updateHomography(){
homography = ofxHomography::findHomography(originalCorners, distortedCorners);
distPoly.clear();
for(auto& p: poly){
distPoly.addVertex(ofxHomography::toDestinationCoordinates(p, homography));
}
}
//--------------------------------------------------------------
void ofApp::draw(){
// Define a point to be drawn in the warped space
glm::vec3 point(originalRect.x + originalRect.width *0.8, originalRect.y + originalRect.height *0.8,0);
glm::vec3 warpedMouse = ofxHomography::toSourceCoordinates({ofGetMouseX(), ofGetMouseY(),0}, homography);
ofPushMatrix();
glMultMatrixf(glm::value_ptr(homography));
ofSetColor(ofColor::yellow);
ofDrawRectangle(originalRect);
ofSetColor(ofColor::black);
ofDrawCircle(originalRect.getCenter(), 50);
// Draw a point in the warped space
ofSetColor(ofColor::red);
ofDrawCircle(point, 10);
ofSetColor(ofColor::magenta);
ofDrawCircle(warpedMouse, 10);
ofPopMatrix();
for(int i = 0; i < 4; i++){
distortedCorners[i].draw();
}
ofPushStyle();
ofSetColor(0, 120);
ofSetLineWidth(4);
poly.draw();
distPoly.draw();
ofPopStyle();
// Draw the screen coordinates of that point
ofSetColor(ofColor::black);
glm::vec3 pointInScreen = ofxHomography::toDestinationCoordinates(point, homography);
ofDrawBitmapString("Local coordinates " + ofToString(point) + "\nScreen coordinates " + ofToString(pointInScreen) , pointInScreen);
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
bool bPoly = true;
for(int i = 0; i < 4; i++){
if(distortedCorners[i].mouseDragged({x,y})){
bPoly = false;
}
}
if(bPoly){
poly.lineTo(x,y);
}else{
updateHomography();
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
bool bPoly = true;
for(int i = 0; i < 4; i++){
if(distortedCorners[i].mousePressed({x,y})){
bPoly = false;
}
}
if(bPoly){
poly.clear();
poly.addVertex(x,y);
}
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
bool bUpdateHomography = false;
for(int i = 0; i < 4; i++){
if(distortedCorners[i].mouseReleased()){
bUpdateHomography = true;
}
}
if(bUpdateHomography){
updateHomography();
}
}
| true |
4cdfd407fee117c42a73696bd51bf226b6189459 | C++ | blizmax/galileo | /bounds.h | UTF-8 | 595 | 2.75 | 3 | [] | no_license | #ifndef _BOUNDS_H
#define _BOUNDS_H
#include "ray.h"
namespace galileo
{
class c_bounds
{
public:
c_bounds()
{
}
c_bounds(const c_vector3& min, const c_vector3& max)
{
pp[0] = min;
pp[1] = max;
}
const c_vector3& min() const
{
return pp[0];
}
const c_vector3& max() const
{
return pp[1];
}
bool ray_intersect(const c_ray& r, t_float tmin, t_float tmax) const;
protected:
c_vector3 pp[2];
};
inline c_bounds surround(const c_bounds& b1, const c_bounds& b2)
{
return c_bounds(min(b1.min(), b2.min()), max(b1.max(), b2.max()));
}
}
#endif
| true |
f1bc9a1c1d16161ab6b57952e0a6b19b9cd21a28 | C++ | JoaoDanielRufino/Algorithms | /String/permutation_in_string.cpp | UTF-8 | 893 | 3.078125 | 3 | [] | no_license | // https://leetcode.com/problems/permutation-in-string/description/
class Solution {
public:
bool equal(vector<int>& a, vector<int>& b) {
for(int i = 0; i < a.size(); i++) {
if(a[i] != b[i])
return false;
}
return true;
}
bool checkInclusion(string s1, string s2) {
if(s1.size() > s2.size())
return false;
vector<int> mpA(26), mpB(26);
for(int i = 0; i < s1.size(); i++) {
mpA[s1[i] - 'a']++;
mpB[s2[i] - 'a']++;
}
int l = 0;
int r = s1.size() - 1;
while(r < s2.size()) {
if(equal(mpA, mpB))
return true;
mpB[s2[l] - 'a']--;
l++;
r++;
if(r >= s2.size())
break;
mpB[s2[r] - 'a']++;
}
return false;
}
};
| true |
585320cfcc4b3d82985fb7616b22c7d68ff16776 | C++ | akoo1/auto-indexer | /test.cpp | UTF-8 | 4,637 | 3.21875 | 3 | [] | no_license | //
// Created by Alfred on 2/28/20.
//
#include "catch.h"
#include <cstring>
#include "DSString.h"
#include "DSVector.h"
// After each SECTION, the variables in the scope will be reset to the variables in the TEST_CASE
TEST_CASE("DSString class", "[DSString]"){
DSString s[10];
s[0] = DSString("testDSString");
s[1] = DSString("a test string");
s[2] = DSString("");
s[3] = DSString("THIS IS AN UPPERCASE STRING");
s[4] = DSString("this is an uppercase string");
s[5] = DSString("\n");
s[6] = DSString("");
s[7] = DSString(" split split split ");
s[8] = DSString(" ");
s[9] = DSString("testDSString");
SECTION("Equality operators"){
REQUIRE(s[0] == DSString("testDSString"));
REQUIRE(s[0] == s[9]);
REQUIRE(s[2] == "");
REQUIRE(s[1] == "a test string");
REQUIRE(!(s[3] == s[4]));
}
SECTION("Greater than operators"){
REQUIRE(s[0] > DSString("test"));
REQUIRE(s[0] > s[1]);
REQUIRE(s[4] > s[3]);
REQUIRE(s[9] > s[6]);
REQUIRE(s[7] > s[6]);
}
SECTION("Less than operators"){
REQUIRE(s[0] < DSString("testDSStringgg"));
REQUIRE(s[0] < s[4]);
REQUIRE((s[7] < s[4]));
}
SECTION("Assignment operators"){
DSString str;
str = "a test string";
REQUIRE(str == s[1]);
str = DSString("testDSString");
REQUIRE(str == s[0]);
str = "";
REQUIRE(str == s[6]);
str = DSString("\n");
REQUIRE(str == s[5]);
}
SECTION("get_data_length function"){
REQUIRE(s[9].get_data_length() == 12);
REQUIRE(s[2].get_data_length() == 0);
REQUIRE(s[8].get_data_length() == 26);
REQUIRE(s[3].get_data_length() == 27);
}
SECTION("is_empty function") {
REQUIRE(s[2].is_empty() == false);
REQUIRE(s[0].is_empty() == false);
}
SECTION("Substring function"){
REQUIRE(s[0].substring(0, 5) == "testD");
REQUIRE(s[4].substring(0, 4) == "this");
REQUIRE(s[4].substring(1, 3) == "his");
}
}
TEST_CASE("DSVector class", "[DSVector]"){
DSVector<int> v1;
DSVector<char> v2;
SECTION("get_size function") {
REQUIRE(v1.get_size() == 0);
REQUIRE(v2.get_size() == 0);
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
v1.push_back(6);
REQUIRE(v1.get_size() == 6);
v2.push_back('a');
v2.push_back('b');
v2.push_back('c');
REQUIRE(v2.get_size() == 3);
}
SECTION("get_capacity function") {
REQUIRE(v1.get_capacity() == 1);
REQUIRE(v2.get_capacity() == 1);
v1.push_back(1);
REQUIRE(v1.get_capacity() == 1);
v1.push_back(2);
REQUIRE(v1.get_capacity() == 2);
v1.push_back(3);
REQUIRE(v1.get_capacity() == 4);
v1.push_back(4);
REQUIRE(v1.get_capacity() == 4);
v1.push_back(5);
REQUIRE(v1.get_capacity() == 8);
v2.push_back('a');
REQUIRE(v2.get_capacity() == 1);
v2.push_back('b');
REQUIRE(v2.get_capacity() == 2);
v2.push_back('c');
REQUIRE(v2.get_capacity() == 4);
}
SECTION("pop function") {
v1.push_back(1);
v1.pop();
REQUIRE(v1.get_size() == 0);
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
v1.pop();
v1.pop();
REQUIRE(v1.get_size() == 3);
}
SECTION("[] operator") {
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
REQUIRE(v1[0] == 1);
REQUIRE(v1[1] == 2);
REQUIRE(v1[2] == 3);
REQUIRE(v1[3] == 4);
REQUIRE(v1[4] == 5);
v2.push_back('a');
v2.push_back('b');
v2.push_back('c');
REQUIRE(v2[0] == 'a');
REQUIRE(v2[1] == 'b');
REQUIRE(v2[2] == 'c');
}
SECTION("Copy assignment operator") {
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
DSVector<int> v3;
v3.push_back(99);
v1 = v3;
REQUIRE(v1[0] == 99);
}
SECTION("is_empty function") {
REQUIRE(v1.is_empty() == true);
v1.push_back(1);
REQUIRE(v1.is_empty() == false);
v1.pop();
REQUIRE(v1.is_empty() == true);
}
}
| true |
d2bbd8afd17d7fd7fe5be93d8c72eab41fca8560 | C++ | ssajnani/LifeVectorBluetoothServer | /LifeVectorServer/squasher.cpp | UTF-8 | 3,636 | 3.0625 | 3 | [] | no_license | /**
* @file squasher.cpp
* @brief Squasher to process raw data
*
* Used for processing raw data from front end, which recording
* the time stamps, latitude, and longitude. Adding unfound location
* into archived library and squash continuous points at same
* location together
*/
#include "squasher.h"
#include <vector>
#include <sstream>
#include "CoordinateInformation.h"
#include "ArchivedLocation.h"
#include "googleAPI.h"
#include "UserVisitInfo.h"
#include <iomanip>
/**
* @brief Squash unprocessed data
*
* Recording the time spent in each location
* Save the result into ArchiveLibrary
*/
void squasher::squash() {
std::vector<long> timeStamps = rawData.getTimeStamps();
std::map<long, int> log;
std::vector<long>::iterator itr = timeStamps.begin();
//Loop through all the data points
for (itr; itr != timeStamps.end(); itr++) {
double *coord = (double*) malloc(sizeof(double) * 2);
rawData.getCoordinates(coord, *itr);
double lat = *coord;
double lng = *(coord + 1);
//Search the location in the library based on coordinates, get 0 if not found
std::map<int, CoordinateInformation> matchedLocations = std::map<int, CoordinateInformation>();
int locationID = library.matchNearestLocation(matchedLocations,lat,lng);
if (locationID > 0){
//Location is found in library
//Push it into map for later squashing
log.emplace(*itr,locationID);
}
else {
//Location is not in library
//Search location from Google Map and Google Place API
locationID = currentID;
googleAPI gAPI(std::to_string(lat),std::to_string(lng));
//Setting up the location information
int id = currentID;
std::string name = gAPI.getName();
std::string address = gAPI.getFormattedLocation();
std::string description = gAPI.getTypes(0);
double eastbound = std::stod(gAPI.getNorthEastLng());
double northbound = std::stod(gAPI.getNorthEastLat());
double westbound = std::stod(gAPI.getSouthWestLng());
double southbound = std::stod(gAPI.getSouthWestLat());
//Build the ArchiveLocation object and save it into library
ArchivedLocation location = library.constructLocation(id,name,address,description,lat,lng,
northbound,southbound,eastbound,westbound);
library.saveLocationToDatabase(location);
//Push into map for later squashing
log.emplace(*itr, locationID);
incrementID();
}
}
//Another loop to squash the points
double lastTime = 0;
double timeSpent = 0;
int lastID = 0;
itr = timeStamps.begin();
for (itr; itr != timeStamps.end(); itr++) {
UserVisitInfo uvi;
int locID = log[*itr];
//Setting up for the first location
if (itr == timeStamps.begin()) {
lastTime = *itr;
lastID = locID;
if ((itr + 1) == timeStamps.end()){ //If only one input, push to library
uvi.addSingleLog(*itr, 0);
library.archiveUserLog(locID,username,deviceID,uvi);
}
}
else {
//If found a different location,
//add the last location to the user visit info
if (locID != lastID) {
timeSpent = *itr - lastTime;
uvi.addSingleLog(lastTime, (int)timeSpent);
library.archiveUserLog(lastID,username,deviceID,uvi);
lastTime = *itr;
lastID = locID;
timeSpent = 0;
}
//If location is the same with last one, do nothing
//If it's the last location, also add it to the user visit info
if ((itr + 1) == timeStamps.end()) {
timeSpent = *itr - lastTime;
UserVisitInfo uvi0; //Create a new user visit info to avoid conflict with the last one
uvi0.addSingleLog(lastTime, (int)timeSpent);
library.archiveUserLog(locID,username,deviceID,uvi0);
timeSpent = 0;
}
}
}
} | true |
e3c7eb553363571e977928ba10d551f521f155a7 | C++ | nagyistoce/liblearning | /include/camp/args.hpp | UTF-8 | 4,573 | 3.140625 | 3 | [] | no_license | /****************************************************************************
**
** Copyright (C) 2009-2010 TECHNOGERMA Systems France and/or its subsidiary(-ies).
** Contact: Technogerma Systems France Information (contact@technogerma.fr)
**
** This file is part of the CAMP library.
**
** CAMP is free software: you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** CAMP 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 Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with CAMP. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#ifndef CAMP_ARGS_HPP
#define CAMP_ARGS_HPP
#include <camp/config.hpp>
#include <vector>
namespace camp
{
class Value;
/**
* \brief Wrapper for packing an arbitrary number of arguments into a single object
*
* camp::Args is defined as a list of arguments of any type (wrapped in camp::Value instances),
* which can conveniently be passed to all the CAMP entities which may need an arbitrary number of arguments
* in a uniform way.
*
* Arguments lists can be constructed on the fly using one of the constructors (accept up to 5 arguments):
*
* \code
* camp::Args args(1, true, "hello", 5.24, myObject);
* \endcode
*
* ... or appended one by one using the + and += operators:
*
* \code
* camp::Args args;
* args += 1;
* args += true;
* args += "hello";
* args += 5.24;
* args = args + myObject;
* \endcode
*
*/
class CAMP_API Args
{
public:
/**
* \brief Default constructor (empty list of argument)
*/
Args();
/**
* \brief Construct the list with 1 argument
*
* \param a0 Argument to put in the list
*/
Args(const Value& a0);
/**
* \brief Construct the list with 2 arguments
*
* \param a0 First argument to put in the list
* \param a1 Second argument to put in the list
*/
Args(const Value& a0, const Value& a1);
/**
* \brief Construct the list with 3 arguments
*
* \param a0 First argument to put in the list
* \param a1 Second argument to put in the list
* \param a2 Third argument to put in the list
*/
Args(const Value& a0, const Value& a1, const Value& a2);
/**
* \brief Construct the list with 4 arguments
*
* \param a0 First argument to put in the list
* \param a1 Second argument to put in the list
* \param a2 Third argument to put in the list
* \param a3 Fourth argument to put in the list
*/
Args(const Value& a0, const Value& a1, const Value& a2, const Value& a3);
/**
* \brief Construct the list with 5 arguments
*
* \param a0 First argument to put in the list
* \param a1 Second argument to put in the list
* \param a2 Third argument to put in the list
* \param a3 Fourth argument to put in the list
* \param a4 Fifth argument to put in the list
*/
Args(const Value& a0, const Value& a1, const Value& a2, const Value& a3, const Value& a4);
/**
* \brief Return the number of arguments contained in the list
*
* \return Size of the arguments list
*/
std::size_t count() const;
/**
* \brief Overload of operator [] to access an argument from its index
*
* \param index Index of the argument to get
*
* \return Value of the index-th argument
*
* \throw InvalidIndex index is out of range
*/
const Value& operator[](std::size_t index) const;
/**
* \brief Overload of operator + to concatenate a list and a new argument
*
* \param arg Argument to concatenate to the list
*
* \return New list
*/
Args operator+(const Value& arg) const;
/**
* \brief Overload of operator += to append a new argument to the list
*
* \param arg Argument to append to the list
*
* \return Reference to this
*/
Args& operator+=(const Value& arg);
public:
/**
* \brief Special instance representing an empty set of arguments
*/
static const Args empty;
private:
std::vector<Value> m_values; ///< List of the values
};
} // namespace camp
#endif // CAMP_ARGS_HPP
| true |
0f0e46c353fbef74a4ea12ab6920f9bf91c6a9d9 | C++ | santhoshpro05/codekata | /minimumcost.cpp | UTF-8 | 774 | 2.9375 | 3 | [] | no_license | include <iostream>
#include <stdio.h>
#include<math.h>
using namespace std;
int main()
{
char str1[100],str2[100],i,cost=0,cost1=0;
cout<<"enter string1";
cin>>str1;
cout<<"enter string2";
cin>>str2;
int hash1[26]={0};
int hash2[26]={0};
int l1=strlen(str1);
int l2=strlen(str2);
int count=0,min;
for(i=0;str1[i];i++)
{
hash1[str1[i]-97]++;
}
for(i=0;str2[i];i++)
{
hash2[str2[i]-97]++;
}
for(i=0;i<26;i++)
{
count+=abs(hash1[i]-hash2[i]);}
if(l1!=l2){
if(count==abs(l1-l2))
{
cost=+count*3;
}}
else{
cost=((count/2)*3)+((count/2)*4);
cost1+=(count/2*5);}
min=(cost<cost1)?cost:cost1;
cout<<min;
return 0;}
| true |
ac101834cd4ed1449759751da28b3d355dd65c87 | C++ | yukeyi/LeetCode | /20 Valid Parentheses/Valid Parentheses.cpp | UTF-8 | 1,372 | 3.390625 | 3 | [] | no_license | class Solution {
public:
bool isValid(string s) {
int len = s.length();
int start = -1;
string stack = s;
for(int i = 0; i<len;i++)
{
switch(s[i])
{
case '(':
case '[':
case '{':
start++;
stack[start] = s[i];
break;
case ')':
if(start == -1)
return false;
if(stack[start] == '(')
start--;
else
return false;
break;
case ']':
if(start == -1)
return false;
if(stack[start] == '[')
start--;
else
return false;
break;
case '}':
if(start == -1)
return false;
if(stack[start] == '{')
start--;
else
return false;
break;
default:
return false;
}
}
if(start == -1)
return true;
else
return false;
}
}; | true |
24e9503373de391f4f26d18308c7bbc52a552679 | C++ | dzui42unit/Modern-Cpp | /compiler_generated_methods.cpp | UTF-8 | 1,052 | 3.796875 | 4 | [] | no_license | #include <iostream>
/*
1. default constructor(is geerated if no constructor is provided)
2. copy constructor (is generated only if no 3,4,5,6 provided)
3. coppy assignment operator (is generated only if 2,4,5,6 are not provided)
4. destructor
5. move constructor (is generated only if 2,3,4,6 are not provided)
6. move assignment operator (is generated only if 2,3,4,5 are not provided)
*/
// 1, 2, 4 (2 is depricated)
class One
{
One &operator=(const &One) = delete;
// will force a compiler to generate this method
One(const One &) = default;
};
// 3, 4 (4 is depricated)
class Two
{
Two(const Two&) {}
};
// 4
class Three
{
// move constructor
Three(Three &&)
{
}
};
// 4
class Four
{
// move constructor
Four(Four &&) {}
// default constructor
Four(int i = 0) {}
// copy constructor
Four(const Four &, int i = 0)
{
}
};
// 1, 2, 3 (2, 3 are depricated)
class Five()
{
~Five()
{
}
};
int main(void)
{
return (0);
} | true |
76c101eac0bb176c5a25de99baa191d856cc8a03 | C++ | MatteoMele98/GOP-Gioco-dell-oca-pazza | /src/Questions.cpp | UTF-8 | 4,677 | 2.921875 | 3 | [
"MIT"
] | permissive | /*
* Questions.cpp
*
* Created on: 30 apr 2018
* Author: Vincenzo
*/
#include "Questions.h"
#include "AuxiliaryFunctions.h"
using namespace std;
Question questions[] = {
{"La capitale del Nuova Zelanda è...?","Cracovia","Boston","Wellington","Washington",3},
{"La capitale di El Salvador è...?","San Salvador","Città del Savador","Salvador","Salvador Town",1},
{"Ernest Hemingway sta a scrittore come Pablo Picasso sta a...?","Solista","Musicista","Pittore","Artista",3},
{"Renzo Piano è un...?","Pittore","Cantante","Architetto","Geometra",3},
{"Ha 6 battiti del cuore al minuto (bpm)...?","Il Cane","Il Gatto","La Tartaruga","Il Colibr�",3},
{"Il Marzemino è un vitigno autoctono italiano particolarmente coltivato...?","in Calabria","in Trentino","in Sicilia","in Toscana",2},
{"Chi tra questi registi ha diretto 'La dolce vita'?","Federico Fellini","Dino Risi","Vittorio De Sica","Sergio Leone",1},
{"Il nome del noto showman Fiorello è...?","Rosario","Fiorenzo","Fiorello","Ubaldo",1},
{"La capitale della Repubblica Dominicana è...?","Oranjestad","Ottawa","Panama","Santo Domingo",4},
{"La capitale del Nicaragua è...?","Tegucigalpa","Managua","Nuuk","Washington",2},
{"Se mi trovo ad Hamilton, sono nella capitale...?","delle Bermuda","delle Antille Olandesi","del Messico","delle Isole vergini britannice",1},
{"Con due atomi di idrogeno e un'atomo di ossigeno ottengo...?","L'aria","La terra","Il fuoco","L'acqua",4},
{"La Rai venne fondata nel...?","1971","1948","1954","1938",3},
{"Il telescopio spaziale Hubble è stato lanciato nel...?","2000","1986","1990","2007",3},
{"Il campionato mondiale di calcio si disputa ogni...?","2 anni","4 anni","6 anni","Tutti gli anni",2},
{"Qual è l'unica squadra che ha partecipato a tutti i campionati di Serie A dalla sua fondazione ?","Il Milan","La Roma","L'Inter","La Sampdoria",3},
{"Quale tra queste squadre ha vinto il maggior numero di titoli UEFA Champions League?","Il Liverpool","Il Real Madrid","Il Bayern Monaco","Il Barcellona",2},
{"Dal 2004 nel campionato di serie A giocano...?","16 squadre","20 squadre","21 squadre","24 squadre",2},
{"Bucarest è la capitale...?","della Siria","della Turchia","della Croazia","nessuna delle precedenti",4},
{"La capitale del Australia è...?","Canbera","Sydney","Perth","Melbourne",1},
{"Se mi trovo ad Madrid, sono nella capitale...?","delle Bermuda","della Spagna","del Messico","della Francia",2},
{"Il titolo di Campione d'Italia venne assegnato per la prima volta nel 1898. Quale squadra lo ricevette?","L'Inter","Il Torino","La SPAL","Il Genoa",4},
{"In che anno si tenne la prima edizione del campionato mondiali di calcio?","1940","1900","1930","1948",3},
{"Con chi vinse l'Italia la finale dei campionati mondiali 2006?","Francia","Olanda","Germania","Spagna",1},
{"Il 17 ottobre 1975 fu giocata in messico la famosa partita Brasile-Nicaragua che finì...?","4-0","10-10","7-4","14-0",4},
{"Di che colore è la maglia indossata dalla nazionale italiana ai campionati del mondo?","Rossa","Azzurra","Nera","Verde",2},
{"Il Tour de France si volse la prima volta nel...?","1968","1940","1903","1898",3},
{"Google Chrome è un...?","Browser","Motore di ricerca","Social network","Editor di testi",1},
{"Non è una componente hardware: ","Stampante","Hard disk","Browser","Scheda video",3},
{"Venere possiede...?","Una massa simile a quella della terra","8 satelliti","2 anelli","un atmosfera densa di gas che lo rendono rossastro",1},
{"Il pianeta piu' piccolo del nostro stistema solare è...?","Marte","Venere","Nettuno","Plutone",4},
{"Quale di questi pianeti non e' uno dei giganti gassosi?","Giove","Urano","Nettuno","Marte,4"},
{"La Prima guerra mondiale è cominciata il 28 luglio 1914 con la dichiarazione di guerra...?","Della Germania alla Serbia","Dell'Austria alla Serbia","Dell'Italia alla Serbia","Della Francia alla Serbia",2},
{"Francesco Ferdinando, erede al trono d'Austria, venne ucciso a...?","Monaco","Sarajevo","Milano","Parigi",2},
{"La capitale del Brasile è...?","San Paolo","Kingston","Buenos Aires","Brasilia",4},
{"La capitale dell'Argentina è...?","Quinto","Buenos Aires","La Plata","Mbabane",2},
{"Il Patto di Londra venne stipulato in segreto il...?","25 Aprile 1918","2 Aprile 1914","26 Aprile 1915","12 Aprile 1916",3},
{"L'operazione Overlord è nota come...?","L'attacco a Pearl Harbor","Lo sbarco in Normandia","L'eliminazione sistematica degli Ebrei","L'invasione del Belgio",2},
{"Il campo di concentramento di Auschwitz venne liberato nel...?","1942","1943","1944","1945",4}
};
| true |
e47cf828b8b34c88890337caaf168ca6bb0d4a4f | C++ | nagyist/BaiduPS-tera | /src/master/test/procedure_executor_test.cc | UTF-8 | 2,344 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | #include "gflags/gflags.h"
#include "gtest/gtest.h"
#include "master/procedure_executor.h"
namespace tera {
namespace master {
namespace test {
class ProcedureExecutorTest : public ::testing::Test {
public:
ProcedureExecutorTest() : executor_(new ProcedureExecutor) {}
virtual ~ProcedureExecutorTest() {}
virtual void SetUp() {}
virtual void TearDown() {}
static void SetUpTestCase() {}
static void TearDownTestCase() {}
private:
std::shared_ptr<ProcedureExecutor> executor_;
};
class TestProcedure : public Procedure {
public:
TestProcedure(std::string id) : id_(id), done_(false) {}
virtual ~TestProcedure() {}
std::string ProcId() const { return id_; }
void RunNextStage() {
std::cout << "id: " << id_ << std::endl;
usleep(1000);
done_ = true;
}
bool Done() { return done_; }
std::string id_;
bool done_;
};
TEST_F(ProcedureExecutorTest, StartStopProcedureExecutor) {
EXPECT_FALSE(executor_->running_);
EXPECT_TRUE(executor_->Start());
EXPECT_TRUE(executor_->running_);
EXPECT_FALSE(executor_->Start());
EXPECT_TRUE(executor_->running_);
executor_->Stop();
EXPECT_FALSE(executor_->running_);
executor_->Stop();
}
TEST_F(ProcedureExecutorTest, AddRemoveProcedures) {
std::shared_ptr<Procedure> proc(new TestProcedure("TestProcedure1"));
EXPECT_EQ(executor_->AddProcedure(proc), 0);
// pretend Procedureexecutor_->is running by setting memeber field running_ to
// true
executor_->running_ = true;
EXPECT_GE(executor_->AddProcedure(proc), 0);
EXPECT_EQ(executor_->procedures_.size(), 1);
// add again, wil return 0
EXPECT_EQ(executor_->AddProcedure(proc), 0);
EXPECT_EQ(executor_->procedures_.size(), 1);
EXPECT_TRUE(executor_->RemoveProcedure(proc->ProcId()));
EXPECT_EQ(executor_->procedures_.size(), 0);
EXPECT_FALSE(executor_->RemoveProcedure(proc->ProcId()));
EXPECT_EQ(executor_->procedures_.size(), 0);
executor_->running_ = false;
}
TEST_F(ProcedureExecutorTest, ScheduleProcedures) {
std::shared_ptr<Procedure> proc1(new TestProcedure("TestProcedure1"));
executor_->Start();
EXPECT_TRUE(executor_->running_);
EXPECT_FALSE(proc1->Done());
executor_->AddProcedure(proc1);
EXPECT_EQ(executor_->procedures_.size(), 1);
usleep(50 * 1000);
EXPECT_TRUE(proc1->Done());
EXPECT_TRUE(executor_->procedures_.empty());
}
}
}
}
| true |
644f6ce350552eddb48ac1cf77a1d0ed7eda8703 | C++ | weak-dog/de-duplication-system | /client/client/security.cpp | UTF-8 | 7,169 | 2.71875 | 3 | [] | no_license | #include "security.h"
Security::Security()
{
}
QString Security::HashMD5(QString password)
{
// 创建加密对象
QCryptographicHash hash(QCryptographicHash::Md5);
// 添加明文数据
hash.addData(password.toUtf8());
// 获取加密后的数据
// 16个字节的数据
QByteArray new_password = hash.result();
// 转16进制
//qDebug()<<new_password.toHex();
return new_password.toHex();
}
QString Security::TextToBase64(QString str)
{
// base64进行加密
QByteArray text = str.toLocal8Bit();
QByteArray by = text.toBase64();
return QString(by);
}
QString Security::Base64ToText(QString str)
{
// base64进行解密
QByteArray text = str.toLocal8Bit();
QByteArray by = text.fromBase64(text);
QString result = QString::fromLocal8Bit(by);
return result;
}
//文件的sha256哈希值
QString Security::sha_f(QString filepath){
SHA256_CTX c;
unsigned char* digest=new unsigned char[32];
QFile file;
file.setFileName(filepath);
file.open(QIODevice::ReadOnly);
SHA256_Init(&c);
QByteArray array = file.readAll();
qDebug()<<array.size();
SHA256_Update(&c,array,array.size());
SHA256_Final(digest,&c);
file.close();
QString result=QByteArray((char*)digest,32).toHex();
return result;
}
//字符串sha256哈希值
unsigned char* Security::sha_s(char* str){
unsigned char* md=new unsigned char[SHA256_DIGEST_LENGTH];
SHA256((unsigned char *)str, strlen(str), md);
return md;
}
//字符串sha256哈希值
QString Security::sha_s2(char* str){
unsigned char* md=new unsigned char[SHA256_DIGEST_LENGTH];
SHA256((unsigned char *)str, strlen(str), md);
QString result=QByteArray((char*)md,32).toHex();
return result;
}
//文件的md5哈希值
QString Security::md5_f(QString filepath){
MD5_CTX c;
unsigned char* digest=new unsigned char[16];
QFile file;
file.setFileName(filepath);
file.open(QIODevice::ReadOnly);
MD5_Init(&c);
QByteArray array = file.readAll();
MD5_Update(&c,array,array.size());
MD5_Final(digest,&c);
file.close();
QString result=QByteArray((char*)digest,16).toHex();
return result;
}
//字符串md5哈希值
unsigned char* Security::md5_s(char* str){
unsigned char* md=new unsigned char[MD5_DIGEST_LENGTH];
MD5((unsigned char *)str, strlen(str), md);
return md;
}
QString Security::md5_s2(char* str){
unsigned char* md=new unsigned char[MD5_DIGEST_LENGTH];
MD5((unsigned char *)str, strlen(str), md);
QString result=QByteArray((char*)md,16).toHex();
return result;
}
//aes加密文件
int Security::Encrypt_File(unsigned char* key,QString filename){
unsigned char iv[EVP_MAX_KEY_LENGTH] = "EVP_AES_CTR"; //保存初始化向量的数组
EVP_CIPHER_CTX* ctx; //EVP加密上下文环境
ctx = EVP_CIPHER_CTX_new();
unsigned char out[1024]; //保存密文的缓冲区
int outl;
unsigned char in[1024]; //保存原文的缓冲区
int inl;
int rv;
FILE *fpIn;
FILE *fpOut;
//打开待加密文件
fpIn = fopen(filename.toStdString().c_str(), "rb");
if(fpIn == NULL)
{
return -1;
}
//打开保存密文的文件
char encryptedfname[100];
strcpy(encryptedfname, filename.toStdString().c_str());
strcat(encryptedfname, ".encrypted");
fpOut = fopen(encryptedfname, "wb");
if(fpOut == NULL)
{
fclose(fpIn);
return -1;
}
//初始化ctx
EVP_CIPHER_CTX_init(ctx);
//设置密码算法、key和iv
rv = EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), NULL, key, iv);
if(rv != 1)
{
printf("Err\n");
return -1;
}
//循环读取原文,加密后后保存到密文文件。
for(;;)
{
inl = fread(in,1,1024,fpIn);
if(inl <= 0)//读取原文结束
break;
rv = EVP_EncryptUpdate(ctx, out, &outl, in, inl);//加密
if(rv != 1)
{
fclose(fpIn);
fclose(fpOut);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
fwrite(out, 1, outl, fpOut);//保存密文到文件
}
//加密结束
rv = EVP_EncryptFinal_ex(ctx, out, &outl);
if(rv != 1)
{
fclose(fpIn);
fclose(fpOut);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
fwrite(out,1,outl,fpOut); //保密密文到文件
fclose(fpIn);
fclose(fpOut);
EVP_CIPHER_CTX_cleanup(ctx); //清除EVP加密上下文环境
printf("加密已完成\n");
return 1;
}
//aes解密文件
int Security::Decrypt_File(unsigned char* key,QString filename){
unsigned char iv[EVP_MAX_KEY_LENGTH] = "EVP_AES_CTR"; //保存初始化向量的数组
EVP_CIPHER_CTX* ctx; //EVP加密上下文环境
ctx=EVP_CIPHER_CTX_new();
unsigned char out[1024+EVP_MAX_KEY_LENGTH]; //保存解密后明文的缓冲区数组
int outl;
unsigned char in[1024]; //保存密文数据的数组
int inl;
int rv;
FILE *fpIn;
FILE *fpOut;
//打开待解密的密文文件
fpIn = fopen(filename.toStdString().c_str(), "rb");
if(fpIn == NULL)
{
return -1;
}
char decryptedfname[100];
strcpy(decryptedfname, filename.toStdString().c_str());
strcat(decryptedfname, ".decrypted");
//打开保存明文的文件
fpOut = fopen(decryptedfname, "wb");
if(fpOut == NULL)
{
fclose(fpIn);
return -1;
}
//初始化ctx
EVP_CIPHER_CTX_init(ctx);
//设置解密的算法、key和iv
rv = EVP_DecryptInit_ex(ctx, EVP_aes_128_ctr(), NULL, key, iv);
if(rv != 1)
{
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
//循环读取原文,解密后后保存到明文文件。
for(;;)
{
inl = fread(in, 1, 1024, fpIn);
if(inl <= 0)
break;
rv = EVP_DecryptUpdate(ctx, out, &outl, in, inl);//解密
if(rv != 1)
{
fclose(fpIn);
fclose(fpOut);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
fwrite(out, 1, outl, fpOut);//保存明文到文件
}
//解密结束
rv = EVP_DecryptFinal_ex(ctx, out, &outl);
if(rv != 1)
{
fclose(fpIn);
fclose(fpOut);
EVP_CIPHER_CTX_cleanup(ctx);
return -1;
}
fwrite(out,1,outl,fpOut);//保存明文到文件
fclose(fpIn);
fclose(fpOut);
EVP_CIPHER_CTX_cleanup(ctx);//清除EVP加密上下文环境
printf("解密已完成\n");
return 1;
}
void Security::get_rand_key(unsigned char * key,int l){
RAND_bytes(key, l);
}
QString Security::hmac(QByteArray key,QString filePath){
QMessageAuthenticationCode code(QCryptographicHash::Sha256);
code.setKey(key);
QFile file;
file.setFileName(filePath);
file.open(QIODevice::ReadOnly);
QByteArray message=file.readAll();
file.close();
code.addData(message);
return code.result().toHex();
}
QString Security::hmacS(QByteArray key,QByteArray message){
QMessageAuthenticationCode code(QCryptographicHash::Sha256);
code.setKey(key);
code.addData(message);
return code.result().toHex();
}
| true |
81e2df90d434bdb41c99e69affb6870612802303 | C++ | seddon-software/cplusplus | /24_RegEx/01.match_or_search.cpp | UTF-8 | 1,028 | 3.78125 | 4 | [] | no_license | //////////////////////////////////////////////////
//
// Advanced pattern matching ...
//
//////////////////////////////////////////////////
/*
* When we work with regular expressions we can "match"or "search".
* matches have to match the entire string
* searches match on substrings
*/
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <regex>
using namespace std;
int main()
{
string s("-------ABC------------");
regex re("(ABC)");
match_results<string::const_iterator> matcher;
match_results<string::const_iterator> searcher;
regex_match(s, matcher, re);
regex_search(s, searcher, re);
// match
cout << "Matches are:" << endl;
for (smatch::iterator it = matcher.begin(); it != matcher.end(); ++it) {
cout << *it << ", ";
}
cout << endl;
// search
cout << "Searches are:" << endl;
for (smatch::iterator it = searcher.begin(); it != searcher.end(); ++it) {
cout << *it << ", ";
}
cout << endl;
}
| true |
3844e01938cf43ea2303f597ad8d28ba843c8585 | C++ | Claudiaf26/Network_sharing | /TCPServerSocket/TCPServerSocket_Linux.cpp | UTF-8 | 1,886 | 2.875 | 3 | [] | no_license | #ifdef __linux__
#include "TCPServerSocket_Linux.h"
TCPServerSocket_Linux::TCPServerSocket_Linux(uint16_t port) : TCPServerSocket_Interface() {
accepting=false;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s < 0)
throw std::invalid_argument("Error during socket: " + errno);
u_int reuse = 1;
if ( setsockopt( s, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof( reuse ) ) <0 )
throw std::runtime_error( "Socket option error. " + errno );
address.sin_family = AF_INET;
address.sin_addr.s_addr=htonl(INADDR_ANY);
address.sin_port = htons(port);
if (bind(s, (struct sockaddr*) &address, sizeof(address)) < 0)
throw std::invalid_argument("Error during binding: " + errno);
if(listen(s, SOMAXCONN) < 0)
throw std::invalid_argument("Error during listen: " + errno);
started = true;
}
TCPServerSocket_Linux::~TCPServerSocket_Linux() {
if (started != false) {
started = false;
Close();
}
}
void TCPServerSocket_Linux::Close() {
started = false;
if(accepting){
/*The accept() in Linux will block, no matter what. The only way to unblock it is to connect to it and gracefully close the connection. */
try{
TCPSocket tcpToClose("127.0.0.1", 50000);
tcpToClose.Close();
} catch(...){
cout << "There was no opened connection." <<endl;
}
}
close(s);
}
TCPSocket TCPServerSocket_Linux::Accept() {
accepting=true;
int16_t connectedSocket;
sockaddr_in clientAddress;
socklen_t clen= sizeof(clientAddress);
connectedSocket = accept(s, (struct sockaddr*) &clientAddress, &clen);
accepting=false;
if (connectedSocket < 0 )
throw std::invalid_argument("The client has problems: " + errno);
int32_t bufferSize = 65664;
setsockopt( connectedSocket, SOL_SOCKET, SO_RCVBUF, (char*)&bufferSize, sizeof( bufferSize ) );
return TCPSocket(connectedSocket);
}
#endif
| true |
384b9468fbad419d9173df51c2e73630adc74d0f | C++ | kenkerr/lvLights | /include/modbusTransaction.h | UTF-8 | 1,892 | 2.59375 | 3 | [] | no_license | #ifndef MB_TRANSACTION_H
#define MB_TRANSACTION_H
class ModbusTransaction {
// Return Definitions
#define MB_VALID_REQUEST 0x00
#define MB_INVALID_FUNCTION 0x01
#define MB_ILLEGAL_ADDRESS 0x02
#define MB_ILLEGAL_DATA_VALUE 0x03
#define MB_INVALID_MBAP 0x20
#define MB_INVALID_REQUEST 0x21
#define MB_INCOMPLETE_REQUEST 0x22
#define MB_METHOD_SUCCESS 0x00
// Modbus Function Codes
#define FC_READ_MULTIPLE_REGISTERS 0x03
#define FC_WRITE_MULTIPLE_REGISTERS 0x10
// Misc constants
#define MAX_TRANSACTION_HRS 32
public:
ModbusTransaction ();
~ModbusTransaction();
short getFC(){
return fc;
};
int setFC(short newFC){
fc = newFC;
return MB_METHOD_SUCCESS;
}
short getTransID () {
return transID;
};
short getProtoID () {
return protoID;
};
short getlength();
short setlength();
char getUnitID() {
return unitID;
};
short setUnitID();
short getStAddr(){
return stAddr;
};
int setStAddr(short newStAddr) {
stAddr = newStAddr;
return MB_METHOD_SUCCESS;
}
short getNRegs(){
return nRegs;
};
int setNRegs(short newNRegs) {
nRegs = newNRegs;
return MB_METHOD_SUCCESS;
}
short getNBytes();
short setNBytes();
short getReg(int regNo){
return regs[regNo];
};
int setReg(int regNo, short regVal) {
regs[regNo] = regVal;
};
int parseStream (int nBytes, char *stream);
private:
// MBAP (ModBus Application Protocol - TCP header)
short transID;
short protoID;
short length;
char unitID;
// PDU (Protocol Data Unit)
char fc;
short stAddr;
short nRegs;
char nBytes;
short regs[MAX_TRANSACTION_HRS];
// Response
char excCode;
};
#endif
| true |
4f4a3cf39742aa6c00233a0b872c3dd664712972 | C++ | Mrsuyi/stl | /src/iterator/iterator_traits.hpp | UTF-8 | 1,180 | 2.75 | 3 | [] | no_license | #pragma once
#include "cstddef"
#include "iterator_category.hpp"
namespace mrsuyi {
template <class T>
class iterator_traits {
public:
using value_type = typename T::value_type;
using difference_type = typename T::difference_type;
using reference = typename T::reference;
using pointer = typename T::pointer;
using iterator_category = typename T::iterator_category;
};
template <class T>
class iterator_traits<T*> {
public:
using value_type = T;
using difference_type = std::ptrdiff_t;
using reference = T&;
using pointer = T*;
using iterator_category = random_access_iterator_tag;
};
template <class T>
class iterator_traits<const T*> {
public:
using value_type = T;
using difference_type = std::ptrdiff_t;
using reference = const T&;
using pointer = const T*;
using iterator_category = random_access_iterator_tag;
};
// this function is used for it-tag-dispatch
// i.e. template-function overload according to it-type-traits
template <class Iterator>
typename iterator_traits<Iterator>::iterator_category __iterator_category(
const Iterator&) {
return typename iterator_traits<Iterator>::iterator_category();
}
} // namespace mrsuyi
| true |