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
930238bb5fb4897b94898d62f9685bd600c90ce0
C++
manet-sih/location_aided_manet_routing
/RoutingTable.cc
UTF-8
2,831
2.875
3
[]
no_license
#include "RoutingTable.h" RoutingTable::RoutingTable(){} void RoutingTable::addEvent(ns3::Ipv4Address addr,ns3::EventId id){ auto itr = eventTable.find(addr); if(itr==eventTable.end()){ eventTable[addr] = id; }else{ itr->second = id; } } void RoutingTable::addRouteEntry(RoutingTableEntry& entry){ rTable[entry.getDsptIp()] = entry; } bool RoutingTable::search(ns3::Ipv4Address addr,RoutingTableEntry& entry){ if(rTable.empty()) return false; auto itr = rTable.find(addr); if(itr==rTable.end()) return false; entry = itr->second; return true; } ns3::Time RoutingTable::getHoldTime() const{ return holdTime; } void RoutingTable::setHoldTime(ns3::Time time){ holdTime = time; } uint32_t RoutingTable::size() const{ return rTable.size(); } bool RoutingTable::updateRoute(RoutingTableEntry& route){ auto itr = rTable.find(route.getDsptIp()); if(itr==rTable.end()){ return false; } route = itr->second; return true; } void RoutingTable::deleteRouteEntries(ns3::Ipv4InterfaceAddress interface){ for(auto itr = rTable.begin(); itr!=rTable.end();itr++){ if(itr->second.getLink() == interface){ auto tmpIterator = itr; itr++; rTable.erase(tmpIterator); }else{ itr++; } } } bool RoutingTable::deleteRouteEntry(ns3::Ipv4Address ip){ auto itr = rTable.find(ip); if(itr==rTable.end()) return false; rTable.erase(itr); return true; } bool RoutingTable::deleteEvent(ns3::Ipv4Address addr){ auto itr = eventTable.find(addr); if(eventTable.empty()) return false; else if(itr == eventTable.end()) return false; else if(itr->second.IsRunning()) return false; else if(itr->second.IsExpired()) { itr->second.Cancel(); eventTable.erase(itr); return true; } else{ eventTable.erase(itr); return true; } } bool RoutingTable::forceDeleteEvent(ns3::Ipv4Address addr){ auto itr = eventTable.find(addr); if(itr == eventTable.end()) return false; ns3::Simulator::Cancel(itr->second); eventTable.erase(itr); return true; } void RoutingTable::deleteRoutesWithInterface(ns3::Ipv4InterfaceAddress addr){ for(auto itr = rTable.begin();itr!=rTable.end();){ if(itr->second.getLink() == addr) { auto tmp = itr; itr++; rTable.erase(tmp); }else{ itr++; } } } void RoutingTable::getAllRoutes(std::map<ns3::Ipv4Address,RoutingTableEntry>& table){ for(auto itr = rTable.begin();itr!=rTable.end();itr++){ if(itr->first != ns3::Ipv4Address("127.0.0.1") && itr->second.getEntryState()!=EntryState::INVALID){ table[itr->first] = itr->second; } } } void RoutingTable::deleteAllInvalidRoutes(){ for(auto itr = rTable.begin();itr!=rTable.end();){ if(itr->second.getEntryState() == EntryState::INVALID) { auto tmp = itr; itr++; rTable.erase(tmp); }else if(itr->second.getLifeTime()>holdTime){ auto tmp = itr; itr++; rTable.erase(tmp); } else itr++; } }
true
9175b170d8ed8e7ec83d4b4ec28e5bae56c1a1bd
C++
m1keall1son/ofxMediaSystem
/src/mediasystem/rendering/LayeredRenderer.hpp
UTF-8
10,569
2.65625
3
[ "MIT" ]
permissive
// // LayeredRenderer.hpp // WallTest // // Created by Michael Allison on 6/19/18. // #pragma once #include <tuple> #include "ofMain.h" #include "mediasystem/core/Entity.h" #include "mediasystem/rendering/IPresenter.h" #include "mediasystem/rendering/DefaultPresenter.h" #include "mediasystem/util/TupleHelpers.hpp" #include "mediasystem/util/MemberDetection.hpp" namespace mediasystem { GENERATE_HAS_MEMBER_FUNCTION_SIGNITURE(draw); template<typename T> class Drawable : public T { public: static_assert( has_member_function_signiture_draw<T,void()>(), "Passed type T must have member function void draw();" ); template<typename...Args> Drawable(Entity& entity, Args&&...args): T(std::forward<Args>(args)...), mEntity(entity) {} //setters void setLayer(std::string layer){ mLayer = std::move(layer); } void setDrawOrder(float order){ mDrawOrder = order; } void hide(){ mVisible = false; } void show(){ mVisible = true; } void setColor(const ofFloatColor& color){ mColor = ofFloatColor(color.r,color.g,color.b,mColor.a); } void setAlpha(float alpha){ mColor.a = alpha; } //layered concept const std::string& getLayer() const { return mLayer; } float getDrawOrder() const { return mDrawOrder; } bool isVisible()const{ return mVisible; } const ofFloatColor& getColor()const{ return mColor; } ofFloatColor* getColorPtr(){ return &mColor; } float getAlpha() const { return mColor.a; } float* getAlphaPtr() { return &mColor.a; } glm::mat4 getGlobalTransformMatrix(){ if(auto node = mEntity.getComponent<ofNode>()){ return node->getGlobalTransformMatrix(); } return glm::mat4(); } //drawable concept void draw(){ T::draw(); //must have a draw function } private: Entity& mEntity; ofFloatColor mColor{1.,1.,1.,1.}; float mDrawOrder{0.f}; std::string mLayer{"default"}; bool mVisible{true}; }; template<typename T> using DrawableHandle = Handle<Drawable<T>>; template<typename T> using DrawableHandleList = std::list<DrawableHandle<T>,Allocator<DrawableHandle<T>>>; template<typename...DrawableTypes> class LayeredRenderer { using TypesList = std::tuple<DrawableHandleList<DrawableTypes>...>; using OrderedLayer = std::map<float /* draw order */, TypesList>; struct Layer { Layer( std::string _name, std::shared_ptr<IPresenter> _presenter, float order = 0.f ): name(std::move(_name)), presenter(std::move(_presenter)) {} std::string name; float order{0.f}; OrderedLayer layer; std::shared_ptr<IPresenter> presenter; }; using LayerList = std::list<Layer>; public: LayeredRenderer(Scene& scene): mScene(scene) { mLayers.emplace_back("default", std::make_shared<DefaultPresenter>(), std::numeric_limits<float>::max()); mScene.addDelegate<Draw>(EventDelegate::create<LayeredRenderer,&LayeredRenderer::onDraw>(this)); int l[] = {(addNewComponentDelegate<DrawableTypes>(),0)...}; UNUSED_VARIABLE(l); } ~LayeredRenderer(){ mScene.removeDelegate<Draw>(EventDelegate::create<LayeredRenderer,&LayeredRenderer::onDraw>(this)); int l[] = {(removeNewComponentDelegate<DrawableTypes>(),0)...}; UNUSED_VARIABLE(l); } void addLayer(std::string name, std::shared_ptr<IPresenter> presenter = std::make_shared<DefaultPresenter>(), float order = 0.f){ auto found = std::find_if(mLayers.begin(), mLayers.end(), [order](const Layer& layer){ return layer.order >= order; }); if(found != mLayers.end()){ mLayers.emplace(found, std::move(name), std::move(presenter), order); }else{ mLayers.emplace_back(std::move(name), std::move(presenter), order); } } void setDefault(std::shared_ptr<IPresenter> presenter, float order = std::numeric_limits<float>::max()){ auto found = std::find_if(mLayers.begin(), mLayers.end(), [](const Layer& layer){ return layer.name == "default"; }); found->presenter = presenter; found->order = order; } void draw(){ for(auto & layer : mLayers){ for ( auto & order : layer.layer ) { for_each_in_tuple(order.second,OrderChecker<DrawableTypes...>(*this, layer.name, order.first)); } } for(auto & layer : mLayers){ layer.presenter->begin(); for ( auto & order : layer.layer ) { for_each_in_tuple(order.second,LayerDrawer<DrawableTypes...>(*this)); } layer.presenter->end(); } for(auto & layer : mLayers){ layer.presenter->present(); } } void setGlobalAlpha(float alpha){ mGlobalAlpha = alpha; } float getGlobalAlpha() const { return mGlobalAlpha; } private: template<typename...Args> struct OrderChecker { OrderChecker(LayeredRenderer<Args...>& renderer, std::string layer, float order):mRenderer(renderer), mLayer(std::move(layer)), mOrder(order){} template<typename T> void operator ()(T&& t){ mRenderer.checkOrder(mLayer, mOrder, t); } LayeredRenderer<Args...>& mRenderer; std::string mLayer; float mOrder{0.f}; }; template<typename...Args> struct LayerDrawer { LayerDrawer(LayeredRenderer<Args...>& renderer):mRenderer(renderer){} template<typename T> void operator ()(T&& t){ mRenderer.drawLayer(t); } LayeredRenderer<Args...>& mRenderer; }; template<typename T> void addNewComponentDelegate(){ mScene.addDelegate<NewComponent<Drawable<T>>>(EventDelegate::create<LayeredRenderer, &LayeredRenderer::onNewLayeredComponent<T>>(this)); } template<typename T> void removeNewComponentDelegate(){ mScene.removeDelegate<NewComponent<Drawable<T>>>(EventDelegate::create<LayeredRenderer, &LayeredRenderer::onNewLayeredComponent<T>>(this)); } template<typename T> void insertIntoOrderedLayer(const std::string& layerName, float order, DrawableHandle<T> handle){ auto found = std::find_if(mLayers.begin(), mLayers.end(), [&layerName](const Layer& layer){ return layer.name == layerName; }); if(found != mLayers.end()){ //we have this layer, pull the typed list from the tuple at a given draw order auto foundOrder = found->layer.find(order); if(foundOrder != found->layer.end()){ auto& list = get_element_by_type<DrawableHandleList<T>>(foundOrder->second); list.emplace_back(std::move(handle)); }else{ TypesList l{DrawableHandleList<DrawableTypes>(mScene.getAllocator<DrawableHandle<T>>())...}; auto& list = get_element_by_type<DrawableHandleList<T>>(l); list.emplace_back(std::move(handle)); found->layer.emplace(order, std::move(l)); } }else{ //error and put it in default auto& defaultLayer = *(std::find_if(mLayers.begin(), mLayers.end(), [](const Layer& layer){ return layer.name == "default"; })); auto foundOrder = defaultLayer.layer.find(order); if(foundOrder != defaultLayer.layer.end()){ auto& list = get_element_by_type<DrawableHandleList<T>>(foundOrder->second); list.emplace_back(std::move(handle)); }else{ TypesList l{DrawableHandleList<DrawableTypes>(mScene.getAllocator<DrawableHandle<T>>())...}; auto& list = get_element_by_type<DrawableHandleList<T>>(l); list.emplace_back(std::move(handle)); defaultLayer.layer.emplace(order, std::move(l)); } MS_LOG_ERROR("Didnt have a rendering layer called: " + layerName + " placeing drawable in default layer."); } } template<typename T> void checkOrder(const std::string& layer, float order, DrawableHandleList<T>& handles){ auto it = handles.begin(); auto end = handles.end(); while( it != end ){ if(auto component = it->lock()){ if(component->getDrawOrder() != order || component->getLayer() != layer){ it = handles.erase(it); insertIntoOrderedLayer<T>(component->getLayer(), component->getDrawOrder(), std::move(component)); }else{ ++it; } }else{ it = handles.erase(it); } } } template<typename T> void drawLayer(DrawableHandleList<T>& handles){ auto it = handles.begin(); auto end = handles.end(); while (it!=end) { if (auto component = (*it).lock()) { if (component->isVisible()) { auto model = component->getGlobalTransformMatrix(); auto c = component->getColor(); c.a *= mGlobalAlpha; ofSetColor(c); ofPushMatrix(); ofMultMatrix(model); component->draw(); ofPopMatrix(); } ++it; } else { it = handles.erase(it); } } } template<typename T> EventStatus onNewLayeredComponent( const IEventRef& event ){ auto cast = std::static_pointer_cast<NewComponent<Drawable<T>>>(event); if(cast->getComponentType() == &type_id<Drawable<T>>){ auto compHandle = cast->getComponentHandle(); if(auto comp = compHandle.lock()){ auto layer = comp->getLayer(); auto order = comp->getDrawOrder(); insertIntoOrderedLayer<T>(layer, order, std::move(compHandle)); } return EventStatus::SUCCESS; } MS_LOG_ERROR("Something is wrong, the type_ids should match on new component event!"); return EventStatus::FAILED; } EventStatus onDraw( const IEventRef& event ){ draw(); return EventStatus::SUCCESS; } float mGlobalAlpha{1.f}; Scene& mScene; LayerList mLayers; }; }//end namespace mediasystem
true
971f33e22d69e8d358f56ebbf6654d8eda4c80a9
C++
hoangtrongtin/quanlysinhvien
/ui/MyIO.cpp
UTF-8
794
2.5625
3
[]
no_license
#include "MyIO.h" MyIO::MyIO(){} void MyIO::DataIn(TableUnit* ptU){ map<string, string> mapMember = ptU->GetMapMember(); for(auto it = mapMember.begin(); it != mapMember.end(); it++){ cout << "Enter value of " + it->first + ": "; string value = ""; getline (cin, value); ptU->SetMemberValue(it->first, value); //getline(cin, it->second); //ptU->FromMapMember(); } } void MyIO::DataOut(TableUnit* ptU){ cout << ptU->ToString(); } void MyIO::PrintData(TableData* ptD){ cout << ptD->ToString(); } void MyIO::AddData(TableData* ptD){ TableUnit* unit = ptD->GetTableUnitPtr(); DataIn(unit); DataOut(unit); ptD->PushBack(unit); PrintData(ptD); } void MyIO::EditData(TableData*){ } void MyIO::DeleteData(TableData*){ }
true
add4a4cf64a8da0b608bd65fc7538df5c4d9c11a
C++
tetat/Codeforces-Problems-Sol
/Difficulty1300/1155C.cpp
UTF-8
842
2.53125
3
[]
no_license
/// Problem Name: Alarm Clocks Everywhere /// Problem Link: https://codeforces.com/problemset/problem/1155/C #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; int main() { int n, m; scanf("%d %d", &n, &m); vector <long long> v; long long x[n+1], p[m+1]; for (int i = 0;i < n;i++){ scanf("%I64d", &x[i]); } for (int i = 0;i < m;i++){ scanf("%I64d", &p[i]); } for (int i = 1;i < n;i++){ v.push_back(x[i]-x[i-1]); } long long gc = v[0]; int len = v.size(); for (int i = 1;i < len;i++){ gc = __gcd(gc, v[i]); } // cout << gc << endl; for (int i = 0;i < m;i++){ if (gc%p[i] == 0)return !printf("YES\n%I64d %d\n", x[0], i+1); } return puts("NO"), 0; }
true
861bfd7cbeca80290dfadc708eb5c346bcfa19a1
C++
Jaehwi-So/Algorithm-Data-Structure
/a09_network_AOE_graph.cpp
UTF-8
2,803
3.328125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include"a09_network_AOE_graph.h" /* #define TRUE 1 #define FALSE 0 #define MAX_VERTICES 50 #define MAX_STACK_SIZE 100 typedef int element; typedef struct GraphNode { int vertex; //정점 int value; //현재까지의 작업량 GraphNode* link; //링크 } GraphNode; typedef struct GraphType { int n; // 정점의 개수 int weight[MAX_VERTICES][MAX_VERTICES]; //작업량을 나타내는 인접배열 GraphNode* adj_list[MAX_VERTICES]; //헤드의 배열 int work_number; //작업의 수(간선의 수) int work_start[MAX_VERTICES * 2]; //작업의 시작 정점 int work_end[MAX_VERTICES * 2]; //작업의 끝 정점 } GraphType; //스택 typedef struct { element stack[MAX_STACK_SIZE]; int top; } Stack; */ // 그래프 초기화 void init_graph(GraphType* g) { int v; g->n = 0; for (v = 0; v < MAX_VERTICES; v++) g->adj_list[v] = NULL; for (int i = 0; i < MAX_VERTICES; i++) { for (int j = 0; j < MAX_VERTICES; j++) { g->weight[i][j] = 0; } } g->work_number = 0; } // 정점 추가 void insert_vertex(GraphType* g, int v) { if (((g->n) + 1) > MAX_VERTICES) { printf("정점 개수 초과"); return; } g->n++; } // 간선 추가, vertex2를 vertex1의 인접 리스트에 삽입한다. void insert_edge(GraphType* g, int vertex1, int vertex2, int weight) { if (vertex1 >= g->n || vertex2 >= g->n) { printf("정점 번호 오류"); return; } GraphNode* node = (GraphNode*)malloc(sizeof(GraphNode)); node->vertex = vertex2; node->link = g->adj_list[vertex1]; node->value = 0; g->adj_list[vertex1] = node; g->weight[vertex1][vertex2] = weight; //간선(작업)의 시작정점과 끝정점을 배열(work_start, work_end)에 추가한다. for (int i = g->work_number - 1; i >= 0; i--) { g->work_start[i + 1] = g->work_start[i]; g->work_end[i + 1] = g->work_end[i]; } g->work_start[0] = vertex1; g->work_end[0] = vertex2; g->work_number++; } //그래프의 모든 노드의 value값 초기화 void init_value(GraphType* g, int number) { for (int i = 0; i < g->n; i++) { GraphNode* node = g->adj_list[i]; //해당 정점의 헤드부터 NULL까지 순회하며 차수 계산 while (node != NULL) { node->value = number; node = node->link; } } } // 스택 초기화 함수 void init_stack(Stack* s) { s->top = -1; } // 공백 상태 검출 함수 int is_empty(Stack* s) { return (s->top == -1); } // 포화 상태 검출 함수 int is_full(Stack* s) { return (s->top == (MAX_STACK_SIZE - 1)); } // 삽입함수 void push(Stack* s, element item) { if (is_full(s)) { printf("스택 포화"); return; } else s->stack[++(s->top)] = item; } // 삭제함수 element pop(Stack* s) { if (is_empty(s)) { printf("스택 공백"); return -1; } else return s->stack[(s->top)--]; }
true
e09caacddb8679fed1bc1047b2830cbc99ef8537
C++
xcode1986/nineck.ca
/CrossApp/ccTypes.h
UTF-8
5,176
2.71875
3
[ "MIT" ]
permissive
#ifndef __CCTYPES_H__ #define __CCTYPES_H__ #include <string> #include "basics/CASize.h" #include "basics/CAPoint.h" #include "basics/CAPoint3D.h" #include "basics/CARect.h" #include "basics/CAColor.h" #include "CCGL.h" NS_CC_BEGIN /** A texcoord composed of 2 floats: u, y @since v0.8 */ typedef struct _ccTex2F { GLfloat u; GLfloat v; } ccTex2F; static inline ccTex2F tex2(const float u, const float v) { ccTex2F t = {u , v}; return t; } //! Point Sprite component typedef struct _DPointSprite { DPoint pos; // 8 bytes CAColor4B color; // 4 bytes GLfloat size; // 4 bytes } DPointSprite; //! A 2D Quad. 4 * 2 floats typedef struct _ccQuad2 { DPoint tl; DPoint tr; DPoint bl; DPoint br; } ccQuad2; //! A 3D Quad. 4 * 3 floats typedef struct _ccQuad3 { DPoint3D bl; DPoint3D br; DPoint3D tl; DPoint3D tr; } ccQuad3; //! a Point with a vertex point, a tex coord point and a color 4B typedef struct _ccV2F_C4B_T2F { //! vertices (2F) DPoint vertices; //! colors (4B) CAColor4B colors; //! tex coords (2F) ccTex2F texCoords; } ccV2F_C4B_T2F; //! a Point with a vertex point, a tex coord point and a color 4F typedef struct _ccV2F_C4F_T2F { //! vertices (2F) DPoint vertices; //! colors (4F) CAColor4F colors; //! tex coords (2F) ccTex2F texCoords; } ccV2F_C4F_T2F; //! a Point with a vertex point, a tex coord point and a color 4B typedef struct _ccV3F_C4B_T2F { //! vertices (3F) DPoint3D vertices; // 12 bytes // char __padding__[4]; //! colors (4B) CAColor4B colors; // 4 bytes // char __padding2__[4]; // tex coords (2F) ccTex2F texCoords; // 8 bytes } ccV3F_C4B_T2F; //! A Triangle of ccV2F_C4B_T2F typedef struct _ccV2F_C4B_T2F_Triangle { //! Point A ccV2F_C4B_T2F a; //! Point B ccV2F_C4B_T2F b; //! Point B ccV2F_C4B_T2F c; } ccV2F_C4B_T2F_Triangle; //! A Quad of ccV2F_C4B_T2F typedef struct _ccV2F_C4B_T2F_Quad { //! bottom left ccV2F_C4B_T2F bl; //! bottom right ccV2F_C4B_T2F br; //! top left ccV2F_C4B_T2F tl; //! top right ccV2F_C4B_T2F tr; } ccV2F_C4B_T2F_Quad; //! 4 DPoint3DTex2FColor4B typedef struct _ccV3F_C4B_T2F_Quad { //! top left ccV3F_C4B_T2F tl; //! bottom left ccV3F_C4B_T2F bl; //! top right ccV3F_C4B_T2F tr; //! bottom right ccV3F_C4B_T2F br; } ccV3F_C4B_T2F_Quad; //! 4 DPointTex2FColor4F Quad typedef struct _ccV2F_C4F_T2F_Quad { //! bottom left ccV2F_C4F_T2F bl; //! bottom right ccV2F_C4F_T2F br; //! top left ccV2F_C4F_T2F tl; //! top right ccV2F_C4F_T2F tr; } ccV2F_C4F_T2F_Quad; struct CC_DLL BlendFunc { /** source blend function */ GLenum src; /** destination blend function */ GLenum dst; bool operator==(const BlendFunc &a) const { return src == a.src && dst == a.dst; } bool operator!=(const BlendFunc &a) const { return src != a.src || dst != a.dst; } bool operator<(const BlendFunc &a) const { return src < a.src || (src == a.src && dst < a.dst); } }; const BlendFunc BlendFunc_disable = {GL_ONE, GL_ZERO}; const BlendFunc BlendFunc_alpha_premultiplied = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA}; const BlendFunc BlendFunc_alpha_non_premultiplied = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}; const BlendFunc BlendFunc_additive = {GL_SRC_ALPHA, GL_ONE}; static const BlendFunc kCCBlendFuncDisable = {GL_ONE, GL_ZERO}; // types for animation in particle systems // texture coordinates for a quad typedef struct _ccT2F_Quad { //! bottom left ccTex2F bl; //! bottom right ccTex2F br; //! top left ccTex2F tl; //! top right ccTex2F tr; } ccT2F_Quad; // struct that holds the size in pixels, texture coordinates and delays for animated CCParticleSystemQuad typedef struct { ccT2F_Quad texCoords; float delay; DSize size; } CACustomAnimationFrameData; enum class CAStatusBarStyle { Default = 0, // Dark content, for use on light backgrounds LightContent = 1, // Light content, for use on dark backgrounds }; enum class CAInterfaceOrientation { Unknown = 0, Portrait = 1, Landscape = 2, }; static const char* CAApplicationDidChangeStatusBarOrientationNotification = "CAApplicationDidChangeStatusBarOrientationNotification"; static const char* CROSSAPP_CCLOG_NOTIFICATION = "CROSSAPP_CCLOG_NOTIFICATION"; //script namespace script { static int viewDidLoad = 0x11; static int viewDidUnload = 0x12; static int viewSizeDidChanged = 0x13; static int viewDidAppear = 0x14; static int viewDidDisappear = 0x15; } #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #ifdef _WIN64 typedef signed __int64 ssize_t; #else /* _WIN64 */ typedef _W64 signed int ssize_t; #endif /* _WIN64 */ #endif NS_CC_END #endif //__CCTYPES_H__
true
6263ef2bf0dea842da95c643db075b81aa06e849
C++
errolyan/C-Xcode
/04 - Pointers/04 - Pointers/main.cpp
UTF-8
1,254
3.546875
4
[]
no_license
// // main.cpp // 04 - Pointers // // Created by Victor Bolinches Marin on 19/11/15. // Copyright © 2015 Victor Bolinches Marin. All rights reserved. // #include <iostream> using namespace std; void pointer() { int x; int* p; p = &x; cout << " int *p = &x " << endl; cout << " Please enter a number x = " << endl; cin >> x; cin.ignore(); cout << "Value x = "<< x << endl; cout << "Address &x = "<< &x << endl; cout << "Pointer *p = "<< *p << endl; cout << "Set *p = "<< *p << endl; cin >> *p; cin.ignore(); cout << "Value x = "<< x << endl; cout << "Address &x = "<< &x << endl; cout << "Pointer *p = "<< *p << endl; cout << "Set *p = "<< *p << endl; cin.get(); } void pointerFromFreeMemory(){ int* ptr = new int; cout << " int* ptr = new int" << endl; cout << " Please enter a number *ptr = " << endl; cin >> *ptr; cin.ignore(); cout << "Address &prt = "<< &ptr << endl; cout << "Pointer *ptr = "<< *ptr << endl; cin.get(); delete ptr; cout << "Delete ptr"<< endl; } void showExample04(){ pointer(); pointerFromFreeMemory(); } int main(int argc, const char * argv[]) { showExample04(); return 0; }
true
c9b4547fffe4612dcb59c38324abbc3e6ba146b0
C++
sharon-cohen/maze-pattern
/Demo.h
UTF-8
1,040
2.65625
3
[]
no_license
#include "MyMaze2dGenerator.h" #include "MazeSearcable.h" #include "AstarA.h" #include "AstarM.h" #pragma once template<class T> class Demo { public: Demo() {} void run() { MyMaze2dGenerator gen; Maze2d *maz1 = new Maze2d(); maz1 = gen.generate(); cout<<endl<<"Time"<<gen.measureAlgorithmTime()<<endl; string*result= maz1->getAllPossibleMoves(); cout << "All the possible moves:"<< *result<<endl; maz1->Redraw(); MazeSearchable MazeSerch(*maz1); Searcher<T>* _searcher; _searcher = new BFSAstar<Cell>(); Solutiont sol1(_searcher->search(MazeSerch)); _searcher = new AstarM<Cell>(); Solutiont sol2(_searcher->search(MazeSerch)); _searcher = new AstarA<Cell>(); Solutiont sol3(_searcher->search(MazeSerch)); cout <<endl <<"The number of nodes in BFS solution" << endl << sol1.sizesol() << endl; cout << "The number of nodes in AStar Manhattan solution " << endl << sol2.sizesol() << endl; cout << "The number of nodes in AStar Air Line solution " << endl << sol3.sizesol() << endl; } };
true
fdc5603eb1089e65ad15486fa3bccfd3444122b2
C++
tuxdna/sourcecode
/c++/qt/utf/utf.cpp
UTF-8
346
2.515625
3
[ "Apache-2.0" ]
permissive
#include <QTextStream> #include <QFile> int main() { QFile data("utf.txt"); QString line; if(data.open(QFile::ReadOnly)) { QTextStream in(&data); QTextStream out(stdout); out.setCodec("UTF-8"); in.setCodec("UTF-8"); do { line = in.readLine(); out << line << endl; } while(!line.isNull()); } }
true
1318c05c5e83b95d0c257db1d817a4867a2a35bc
C++
divyaagarwal24/coderspree
/Web/Archi24_ArchiMittal_2024it1052_2/function and arrays/rotatearray.cpp
UTF-8
526
3.0625
3
[]
no_license
#include<iostream> using namespace std; void rotate(int arr[],int n) { int i,l; l=arr[n-1]; for(i=n-1;i>=0;i--) { arr[i]=arr[i-1]; } arr[0]=l; } int main() { int n,k,i,arr[100]; { cin>>n; for(i=0;i<n;i++) { scanf("%d",&arr[i]); } cin>>k; for(i=0;i<k;i++) { rotate(arr,n); } for(i=0;i<n;i++) { cout<<arr[i]<<" "; } } return 0; }
true
591c25d16ecc0a49ad91f81f4a40d021c0107204
C++
sw15-algorithm-study/algorithm_study
/영재/7주차/7_1_4811.cpp
UTF-8
760
3.109375
3
[]
no_license
// 카탈란 수.... 경로 문제처럼 생각하자 #include <iostream> #include <vector> using namespace std; int main() { vector<int> testCaseList; long long* catalan = new long long[31](); catalan[0] = 1; catalan[1] = 1; catalan[2] = 2; int inputNum; while(true) { cin >> inputNum; if(inputNum <= 0) { break; } testCaseList.push_back(inputNum); } for(int i = 3; i <= 30; i++) { for(int j = 0; j < i; j++) { catalan[i] += catalan[i-j-1] * catalan[j]; } } for(int i = 0; i < testCaseList.size(); i++) { int medicineNum = testCaseList[i]; cout << catalan[medicineNum] << "\n"; } }
true
40e0e757ac5e3aef4be8c81f5227c57af5b25315
C++
oneofthezombies/test-server
/base/FileDescriptor.cpp
UTF-8
2,121
2.671875
3
[ "MIT" ]
permissive
// // Created by hunhoekim on 2021/01/24. // #include "Precompile.h" #include "base/FileDescriptor.h" #include <unistd.h> #include <sys/socket.h> #include "base/Result.h" namespace ootz { FileDescriptor::FileDescriptor(int32_t fd) : fd_(fd) { } FileDescriptor::FileDescriptor(FileDescriptor&& other) noexcept : fd_(undefined) { moveFrom(std::move(other)); } FileDescriptor& FileDescriptor::operator=(FileDescriptor&& other) noexcept { moveFrom(std::move(other)); return *this; } FileDescriptor::~FileDescriptor() { clear(); } void FileDescriptor::moveFrom(FileDescriptor&& other) noexcept { std::swap(fd_, other.fd_); other.clear(); } void FileDescriptor::clear() { if (undefined != fd_) { const int32_t result = ::close(fd_); assert(-1 != result); fd_ = undefined; } } Result<FileDescriptor> FileDescriptor::socket(int32_t domain, int32_t type, int32_t protocol) { using ReturnType = Result<FileDescriptor>; const int32_t fd = ::socket(domain, type, protocol); return (-1 == fd) ? ReturnType(GET_LAST_ERROR()) : ReturnType(FileDescriptor(fd)); } Result<FileDescriptor> FileDescriptor::accept(int32_t sockfd, struct sockaddr* address, socklen_t* addressSize) { using ReturnType = Result<FileDescriptor>; const int32_t fd = ::accept(sockfd, address, addressSize); return (-1 == fd) ? ReturnType(GET_LAST_ERROR()) : ReturnType(FileDescriptor(fd)); } int32_t FileDescriptor::get() const { return fd_; } Result<ReadSizeType> FileDescriptor::read(void* buffer, size_t bufferSize) const { using ReturnType = Result<ReadSizeType>; const int32_t readSize = ::read(fd_, buffer, bufferSize); return (-1 == readSize) ? ReturnType(GET_LAST_ERROR()) : ReturnType(ReadSizeType(readSize)); } Result<WriteSizeType> FileDescriptor::write(const void* buffer, size_t bufferSize) const { using ReturnType = Result<WriteSizeType>; const int32_t writeSize = ::write(fd_, buffer, bufferSize); return (-1 == writeSize) ? ReturnType(GET_LAST_ERROR()) : ReturnType(WriteSizeType(writeSize)); } } // namnespace ootz
true
07f2b267cee43c54d1b7f93f16bf52bcd5f21768
C++
AcuteAngleCloud/Acute-Angle-Chain
/externals/binaryen/test/emscripten/tests/poppler/poppler/NameToCharCode.cc
UTF-8
2,152
2.6875
3
[ "MIT", "Apache-2.0", "BSD-3-Clause", "NCSA", "GPL-1.0-or-later", "GPL-2.0-or-later", "LGPL-2.0-or-later", "GPL-2.0-only" ]
permissive
//======================================================================== // // NameToCharCode.cc // // Copyright 2001-2003 Glyph & Cog, LLC // //======================================================================== #include <config.h> #ifdef USE_GCC_PRAGMAS #pragma implementation #endif #include <string.h> #include "goo/gmem.h" #include "NameToCharCode.h" //------------------------------------------------------------------------ struct NameToCharCodeEntry { char *name; CharCode c; }; //------------------------------------------------------------------------ NameToCharCode::NameToCharCode() { int i; size = 31; len = 0; tab = (NameToCharCodeEntry *)gmallocn(size, sizeof(NameToCharCodeEntry)); for (i = 0; i < size; ++i) { tab[i].name = NULL; } } NameToCharCode::~NameToCharCode() { int i; for (i = 0; i < size; ++i) { if (tab[i].name) { gfree(tab[i].name); } } gfree(tab); } void NameToCharCode::add(char *name, CharCode c) { NameToCharCodeEntry *oldTab; int h, i, oldSize; // expand the table if necessary if (len >= size / 2) { oldSize = size; oldTab = tab; size = 2*size + 1; tab = (NameToCharCodeEntry *)gmallocn(size, sizeof(NameToCharCodeEntry)); for (h = 0; h < size; ++h) { tab[h].name = NULL; } for (i = 0; i < oldSize; ++i) { if (oldTab[i].name) { h = hash(oldTab[i].name); while (tab[h].name) { if (++h == size) { h = 0; } } tab[h] = oldTab[i]; } } gfree(oldTab); } // add the new name h = hash(name); while (tab[h].name && strcmp(tab[h].name, name)) { if (++h == size) { h = 0; } } if (!tab[h].name) { tab[h].name = copyString(name); } tab[h].c = c; ++len; } CharCode NameToCharCode::lookup(char *name) { int h; h = hash(name); while (tab[h].name) { if (!strcmp(tab[h].name, name)) { return tab[h].c; } if (++h == size) { h = 0; } } return 0; } int NameToCharCode::hash(char *name) { char *p; unsigned int h; h = 0; for (p = name; *p; ++p) { h = 17 * h + (int)(*p & 0xff); } return (int)(h % size); }
true
03f9fef8d73e56564c4ae7c8d9c72b7c15c45575
C++
octaviansoldea/H261
/Src/libCommon/Singleton.h
UTF-8
248
2.625
3
[]
no_license
#ifndef SINGLETON_H #define SINGLETON_H template <class T> class Singleton { private: static T m_instance; public: static T *instance(void) { return &m_instance; } }; template <class T> T Singleton<T> :: m_instance; #endif /* SINGLETON_H */
true
3e2751005723aed33ae35639d0123b267ff7992c
C++
neophob/ArduinoPlayground
/ws2801_fastspi_example/ws2801_fastspi_example.ino
UTF-8
3,489
2.515625
3
[]
no_license
/* * PixelInvaders serial-led-gateway, Copyright (C) 2012 michael vogt <michu@neophob.com> * Tested on Teensy and Arduino * * ------------------------------------------------------------------------ * * This is the SPI version, unlike software SPI which is configurable, hardware * SPI works only on very specific pins. * * On the Arduino Uno, Duemilanove, etc., clock = pin 13 and data = pin 11. * For the Arduino Mega, clock = pin 52, data = pin 51. * For the ATmega32u4 Breakout Board and Teensy, clock = pin B1, data = B2. * * ------------------------------------------------------------------------ * * This file is part of PixelController. * * PixelController is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * PixelController is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <FastSPI_LED.h> #define NUM_LEDS 50 // Sometimes chipsets wire in a backwards sort of way struct CRGB { unsigned char b; unsigned char r; unsigned char g; }; // struct CRGB { unsigned char r; unsigned char g; unsigned char b; }; struct CRGB *leds; int k=0, jj=0; // Create a 24 bit color value from R,G,B uint32_t Color(byte r, byte g, byte b) { uint32_t c; c = r; c <<= 8; c |= g; c <<= 8; c |= b; return c; } //Input a value 0 to 255 to get a color value. //The colours are a transition r - g -b - back to r uint32_t Wheel(byte WheelPos) { if (WheelPos < 85) { return Color(WheelPos * 3, 255 - WheelPos * 3, 0); } else if (WheelPos < 170) { WheelPos -= 85; return Color(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return Color(0, WheelPos * 3, 255 - WheelPos * 3); } } // -------------------------------------------- // do some animation until serial data arrives // -------------------------------------------- void rainbow() { delay(1); k++; if (k>50) { k=0; jj++; if (jj>255) { jj=0; } for (int j = 0; j < 3; j++) { for (int i = 0 ; i < NUM_LEDS; i++ ) { uint32_t color = Wheel( (i + jj) % 255); leds[i].r = (color>>16)&255; leds[i].g = (color>>8)&255; leds[i].b = color&255; } } FastSPI_LED.show(); } } // -------------------------------------------- // setup // -------------------------------------------- void setup() { FastSPI_LED.setLeds(NUM_LEDS); FastSPI_LED.setChipset(CFastSPI_LED::SPI_WS2801); // FastSPI_LED.setChipset(CFastSPI_LED::SPI_LPD8806); //select spi speed, 7 is very slow, 0 is blazing fast //hint: the small (1 led, 5v) spi modules can run maximal at speed2! FastSPI_LED.setDataRate(2); FastSPI_LED.init(); FastSPI_LED.start(); leds = (struct CRGB*)FastSPI_LED.getRGBData(); rainbow(); // display some colors } // -------------------------------------------- // main loop // -------------------------------------------- void loop() { rainbow(); delay(50); }
true
8eb693416b29b273f28140a451d4800090ad1e72
C++
venkatarajasekhar/adved-games
/src/ps4_input.h
UTF-8
415
2.578125
3
[]
no_license
#pragma once class PS4_Input { public: static bool Init(); static bool Update(); static bool Shutdown(); protected: private: PS4_Input() = delete; ~PS4_Input() = delete; // delete copy/move constructors & assign operators PS4_Input(PS4_Input const &) = delete; PS4_Input(PS4_Input &&) = delete; PS4_Input &operator=(PS4_Input const &) = delete; PS4_Input &operator=(PS4_Input &&) = delete; };
true
da9131d59d0467fac2aa5ceeb498f3e6b0d3a142
C++
BakeSs/University_Test
/LB5_af_edit.cpp
UTF-8
441
2.796875
3
[]
no_license
#include <iostream> #include <iomanip> #include "windows.h" using namespace std; int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); double a, b, c, x, F; cout << "Введіть a, b, c, x" << endl; cin >> a >> b >> c >> x; if ((x < 0) && (b != 0)) F = (-a * x * x) + b; else if ((x > 0) && (b == 0)) F = (x / (x - c)) + 5.5; else F = x / -c; cout << endl << endl << " F = " << F << endl; }
true
c772a2d658e0492c20b86474fe04460f04d83eed
C++
krishnateja-nanduri/MyCodePractice
/InterviewBit/Math/Sorted Permutation rank.cpp
UTF-8
655
3.140625
3
[]
no_license
//https://www.interviewbit.com/problems/sorted-permutation-rank/ int factorial(int n) { int i=0,ans=1; for(i=1;i<=n;i++) { ans=ans*i; ans=ans%1000003; } return ans; } int Solution::findRank(string A) { int i=0,j,c,ans=0; vector<int> H; while(A[i]!='\0') { j=i; c=0; while(A[j]!='\0') { if(A[i]>A[j]) c++; j++; } H.push_back(c); i++; } c=0; i=H.size()-1; j=0; while(i>=0) { ans+=H[i]*factorial(j); ans=ans%1000003; j++; i--; } return ans+1; }
true
3c4cdb794cba3c747bc3b4971490fe270a849ace
C++
Stephenhua/CPP
/DataStruct/Code/TEST-Heap.cc
UTF-8
839
2.84375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; void merge(vector<int>&v,int min,int mid,int max){ vector<int>s; int i=min,j=mid+1; while(i<=mid&&j<=max){ if(v[i]>=v[j]) s.push_back(v[j++]); else s.push_back(v[i++]); } while(i<=mid) s.push_back(v[i++]); while(j<=max) s.push_back(v[j++]); for(int l=min,k=0;l<=max;k++,l++) v[l]=s[k]; cout<<"输出v"; for(int oo=0;oo<v.size();oo++){ cout<<v[oo]; } cout<<endl<<"--------------------"<<endl; for(int p=0;p<s.size();p++) cout<<s[p]; cout<<endl; s.clear(); } void Msort(vector<int>&v,int min,int max){ if(min>=max) return; else{ Msort(v,min,(max+min)/2); Msort(v,(min+max)/2+1,max); merge(v,min,(min+max)/2,max); } } int main(){ vector<int>v(10); for(int i=0;i<10;i++) v[i]=9-i; Msort(v,0,9); system("pause"); return 0; }
true
f44103caf7e3f05b35f0c40501895e37f7a16c02
C++
raghu98/DS
/Theory/link list/New folder/most imp.cpp
UTF-8
1,250
2.765625
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; struct Node { int info; struct Node *next; }; void insert(struct Node **start,int num) { // cout<<"in insert"; struct Node *ptr=new Node; if(*start==NULL) { ptr->info=num; ptr->next=NULL; *start=ptr; } else { ptr->info=num; ptr->next=*start; *start=ptr; } } void display(struct Node *start) { //cout<<"in display"; struct Node *temp; temp=start; while(temp!=NULL) { //cout<<"hi"; cout<<temp->info<<"\t"; temp=(temp->next)->next; } } int main() { int number,i,n; cin>>n; struct Node *head = NULL; for(i = n; i > 0; i--) { cin>>number; insert(&head, number); } display(head); return 0; }
true
d73f26fa217f7fdb7c2d8a17fc351397eb49526e
C++
cmsxbc/insertionfinder
/src/insertion/multi-insertion.cpp
UTF-8
10,994
2.828125
3
[ "MIT" ]
permissive
#include <cstddef> #include <algorithm> #include <deque> #include <limits> #include <utility> #include <vector> #include <insertionfinder/algorithm.hpp> #include <insertionfinder/insertion.hpp> #include <insertionfinder/termcolor.hpp> #include <insertionfinder/twist.hpp> using std::size_t; using Algorithm = InsertionFinder::Algorithm; using Insertion = InsertionFinder::Insertion; using MergedInsertion = InsertionFinder::MergedInsertion; using Rotation = InsertionFinder::Rotation; using Solution = InsertionFinder::Solution; namespace { constexpr size_t invalid = std::numeric_limits<size_t>::max() >> 1; class MultiInsertion { private: Algorithm skeleton; Algorithm current_skeleton; std::vector<std::vector<std::size_t>> insert_places_before; std::vector<std::vector<std::size_t>> insert_places_after; std::vector<const Algorithm*> insertions; std::vector<std::size_t> positions; public: MultiInsertion(const Algorithm& skeleton); public: const Algorithm& get_skeleton() const noexcept { return this->skeleton; } const Algorithm& get_current_skeleton() const noexcept { return this->current_skeleton; } std::vector<std::pair<std::size_t, std::vector<std::size_t>>> get_insert_places() const; const std::vector<const Algorithm*>& get_insertions() const noexcept { return this->insertions; } public: bool try_insert(const Insertion& insertion); }; }; MultiInsertion::MultiInsertion(const Algorithm& skeleton): skeleton(skeleton), current_skeleton(skeleton), insert_places_before(skeleton.length() + 1), insert_places_after(skeleton.length() + 1) { this->positions.reserve(skeleton.length()); for (size_t i = 0; i < skeleton.length(); ++i) { this->positions.push_back(i); } } std::vector<std::pair<size_t, std::vector<size_t>>> MultiInsertion::get_insert_places() const { std::vector<std::pair<size_t, std::vector<size_t>>> result; for (size_t i = 0; i <= this->skeleton.length(); ++i) { const auto& before = this->insert_places_before[i]; const auto& after = this->insert_places_after[i]; if (!before.empty() || !after.empty()) { result.emplace_back(i, std::vector<size_t>(before.crbegin(), before.crend())); result.back().second.insert(result.back().second.cend(), after.cbegin(), after.cend()); } } return result; } bool MultiInsertion::try_insert(const Insertion& insertion) { size_t length = this->current_skeleton.length(); if (insertion.skeleton.length() != length) { return false; } for (size_t i = 0; i < length; ++i) { if (this->current_skeleton[i] == insertion.skeleton[i]) { } else if ( this->current_skeleton.swappable(i + 1) && this->current_skeleton[i] == insertion.skeleton[i + 1] && this->current_skeleton[i + 1] == insertion.skeleton[i] ) { if (insertion.insert_place == i + 1) { if (this->positions[i + 1] - this->positions[i] == 1) { this->skeleton.swap_adjacent(this->positions[i] + 1); this->current_skeleton.swap_adjacent(i + 1); } else { return false; } } ++i; } else { return false; } } if (insertion.insert_place == 0) { this->insert_places_before.front().push_back(this->insertions.size()); } else if (insertion.insert_place == length) { this->insert_places_after.back().push_back(this->insertions.size()); } else if (this->positions[insertion.insert_place] != invalid) { this->insert_places_after[this->positions[insertion.insert_place]].push_back(this->insertions.size()); } else if (this->positions[insertion.insert_place - 1] != invalid) { this->insert_places_before[this->positions[insertion.insert_place - 1] + 1].push_back(this->insertions.size()); } else { return false; } this->insertions.push_back(insertion.insertion); auto [ insertion_result, skeleton_marks, insertion_marks ] = this->current_skeleton.insert_return_marks(*insertion.insertion, insertion.insert_place); for (size_t i = 1; i < insertion.insert_place; ++i) { if (skeleton_marks[i - 1] != 0 && skeleton_marks[i] == 0 && this->positions[i] - this->positions[i - 1] == 1) { this->skeleton.swap_adjacent(this->positions[i]); this->current_skeleton.swap_adjacent(i); std::swap(skeleton_marks[i - 1], skeleton_marks[i]); if (skeleton_marks[i - 1] == 1) { insertion_result.swap_adjacent(i); } break; } } for (size_t i = insertion.insert_place + 1; i < length; ++i) { if (skeleton_marks[i - 1] == 0 && skeleton_marks[i] != 0 && this->positions[i] - this->positions[i - 1] == 1) { this->skeleton.swap_adjacent(this->positions[i]); this->current_skeleton.swap_adjacent(i); std::swap(skeleton_marks[i - 1], skeleton_marks[i]); if (skeleton_marks[i] == 1) { insertion_result.swap_adjacent(i); } break; } } std::vector<std::size_t> new_positions(insertion_result.length(), invalid); for (size_t i = 0; i < std::min(insertion.insert_place, insertion_result.length()); ++i) { if (skeleton_marks[i] == 0) { new_positions[i] = this->positions[i]; } } for (size_t i = insertion.insert_place; i < length; ++i) { if (skeleton_marks[i] == 0) { new_positions[insertion_result.length() + i - length] = this->positions[i]; } } this->current_skeleton = std::move(insertion_result); this->positions = std::move(new_positions); return true; } std::vector<std::pair<size_t, std::vector<MergedInsertion::SubInsertion>>> MergedInsertion::get_insertions() const { std::vector<std::pair<size_t, std::vector<SubInsertion>>> result; result.reserve(this->insert_places.size()); for (const auto& [insert_place, orders]: this->insert_places) { std::vector<SubInsertion> insertions; insertions.reserve(orders.size()); for (size_t order: orders) { insertions.push_back(SubInsertion{&this->insertions[order], order}); } result.emplace_back(insert_place, std::move(insertions)); } return result; } void MergedInsertion::print(std::ostream& out, std::size_t initial_order, const Solution& solution) const { auto [ result, skeleton_marks, insertion_masks ] = this->skeleton.multi_insert_return_marks(this->insertions, this->insert_places); bool skeleton_has_space = this->insert_places.front().first > 0; this->skeleton.print(out, skeleton_marks, 0, this->insert_places.front().first); for (size_t order: this->insert_places.front().second) { if (skeleton_has_space) { out << ' '; } skeleton_has_space = true; out << termcolor::bold << "[@" << initial_order + order + 1 << ']' << termcolor::reset; } for (size_t i = 1; i < this->insert_places.size(); ++i) { out << ' '; this->skeleton.print(out, skeleton_marks, this->insert_places[i - 1].first, this->insert_places[i].first); for (size_t order: this->insert_places[i].second) { out << termcolor::bold << " [@" << initial_order + order + 1 << ']' << termcolor::reset; } } if (this->insert_places.back().first < this->skeleton.length()) { out << ' '; this->skeleton.print(out, skeleton_marks, this->insert_places.back().first, this->skeleton.length()); } for (const auto& [_, orders]: this->insert_places) { for (size_t order: orders) { const Algorithm& insertion = this->insertions[order]; out << std::endl << termcolor::bold << "Insert at @" << initial_order + order + 1 << ": " << termcolor::reset; insertion.print(out, insertion_masks[order]); size_t length_before = solution.insertions[initial_order + order].skeleton.length(); size_t length_after = initial_order + order + 1 >= solution.insertions.size() ? solution.final_solution.length() : solution.insertions[initial_order + order + 1].skeleton.length(); out << termcolor::dark << termcolor::italic << " (+" << insertion.length() << " -" << length_before + insertion.length() - length_after << ')' << termcolor::reset; } } } std::vector<MergedInsertion> Solution::merge_insertions(const Algorithm& skeleton) const { std::vector<MultiInsertion> multi_insertion_list; multi_insertion_list.emplace_back(skeleton); auto multi_insertion = multi_insertion_list.rbegin(); for (const Insertion& insertion: this->insertions) { if (bool success = multi_insertion->try_insert(insertion); !success) { multi_insertion_list.emplace_back(multi_insertion->get_current_skeleton()); multi_insertion = multi_insertion_list.rbegin(); multi_insertion->try_insert(insertion); } } std::vector<MergedInsertion> merged_insertion_list; merged_insertion_list.reserve(multi_insertion_list.size()); for (const MultiInsertion& multi_insertion: multi_insertion_list) { MergedInsertion merged_insertion; merged_insertion.skeleton = multi_insertion.get_skeleton(); merged_insertion.final_solution = multi_insertion.get_current_skeleton(); merged_insertion.insert_places = multi_insertion.get_insert_places(); auto insertions = multi_insertion.get_insertions(); size_t insertion_count = insertions.size(); merged_insertion.insertions.reserve(insertion_count); for (size_t i = insertion_count; i-- > 0;) { Algorithm insertion = *insertions[i]; Rotation rotation = 0; for (const auto& [_, orders]: merged_insertion.insert_places) { bool found = false; for (size_t order: orders) { if (order == i) { found = true; break; } else if (order < i) { rotation *= insertions[order]->cube_rotation(); } } if (found) { break; } } insertion.rotate(rotation); insertion.normalize(); merged_insertion.insertions.emplace_back(std::move(insertion)); } std::reverse(merged_insertion.insertions.begin(), merged_insertion.insertions.end()); merged_insertion_list.emplace_back(std::move(merged_insertion)); } return merged_insertion_list; }
true
4c0eda438304a929703b69f4f231eaa209c4cad9
C++
CLaraRR/C-plus-plus-practice
/92. Reverse Linked List II.cpp
UTF-8
593
3.34375
3
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (head == NULL || head->next == NULL) return head; ListNode *L = new ListNode(0); L->next = head; ListNode *p = head->next, *tail = head,*q=L; int times = n - m; while (--m){ p = p->next; tail = tail->next; q = q->next; } while (times--){ tail->next = p->next; p->next = q->next; q->next = p; p = tail->next; } return L->next; } };
true
7609b65d454866cc39f5eaf0fa159010b9f69c52
C++
Polako912/LibraryDynamic
/dynamic-books/Book.cpp
UTF-8
2,291
2.9375
3
[]
no_license
#include "Book.h" #include "Person.h" #include <vector> #include <iostream> using namespace std; Book::Book(string AuthorFirstName, string AuthorName, string BookTitle, int Number, int Year, int BookId) { this->AuthorFirstName = AuthorFirstName; this->AuthorName = AuthorName; this->BookTitle = BookTitle; this->Number = Number; this->Year = Year; this->BookId = BookId; ++Book::bAmount; } void Book::setAuthorFirstName(string AuthorFirstName) { this->AuthorFirstName = AuthorFirstName; } void Book::setAuthorName(string AuthorName) { this->AuthorName = AuthorName; } void Book::setBookTitle(string BookTitle) { this->BookTitle = BookTitle; } void Book::setNumber(int Number) { this->Number = Number; } void Book::setYear (int Year) { this->Year = Year; } void Book::setBookId (int BookId) { this->BookId = BookId; } /*void Book::addBook(Book& bk) { Book data; for (int i = 0; i < 10; i++) cin >> data; bk1.push_back(data); //istream operator>>(const istream& cin, const vector<Book>& bk); }*/ /*void Book::showBook(vector<Book> bk1) { for (int i = 0; i < 10; i++) cout << bk1[i]; //Book data; //vector <Book> ::iterator bk0 = bk.begin(); //for (; bk0 != bk.end(); bk0++) //cout << *bk0; }*/ void Book::AttachBook(Book bk, Person& ppl, Book& bk1, Book ppl1) { //przypisanie int numberppl, numberbk; for (int i=0; i<10; i++) { cout << "Podaj numer id ksiazki i osoby" << endl; cin >> numberppl; cin >> numberbk; if (numberppl == PersonId && numberbk == BookId) cout << ppl1[i]; cout << bk1[i]; } } string Book::getAuthorFirstName() { return AuthorFirstName; } string Book::getAuthorName() { return AuthorName; } string Book::getBookTitle() { return BookTitle; } int Book::getNumber() { return Number; } int Book::getYear() { return Year; } int Book::getBookId() { return BookId; } std::ostream& operator<<(std::ostream& ostr, const Book& bk) { ostr << bk.AuthorFirstName << "/n"; ostr << bk.AuthorName << "/n"; ostr << bk.BookTitle << "/n"; ostr << bk.Number << "/n"; ostr << bk.Year << "/n"; ostr << bk.BookId << "/n"; return ostr; } std::istream& operator>>(std::istream& is, Book& bk) { is >> bk.AuthorFirstName; is >> bk.AuthorName; is >> bk.BookTitle; is >> bk.Number; is >> bk.Year; is >> bk.BookId; return is; }
true
034f03788efea58a9b044e66a273f076e0927846
C++
pkilli/INF4331
/assignment4/mandelbrot_swig/mandelbrot_4.cc
UTF-8
608
2.59375
3
[]
no_license
#include <mandelbrot_4.h> #include <complex> void mandelbrot(int Nx, double *real, int Ny, double *imag,int max_escape_time, int** iterations){ double complex c, fc, tmp; int iterations[Nx][Ny]; for (int i=0;i<Nx;i++){ for (int j=0;j<Ny;j++){ c = real[i] + I*imag[j]; fc = c; iterations[i][j] = max_escape_time; for (int k=0;k<max_escape_time;k++){ tmp = fc*fc + c; double complex divergent = conj(tmp); double complex check = 2*2; if(divergent > check){ if(iterations[i][j] == max_escape_time){ iterations[i][j] = k; } } fc = tmp; } } } }
true
240cc80a36ad4e899d19b1f65526994d0feab12b
C++
pillowpilot/pdi_comparison
/tests/entropy_tests.cpp
UTF-8
724
2.703125
3
[]
no_license
#include <gtest/gtest.h> #include <opencv2/opencv.hpp> #include <entropy.hpp> #include <iostream> TEST(EntropyTests, OneIntensityImage) { const int intensity = 10; cv::Mat testImage(1000, 1000, CV_8UC1, cv::Scalar(intensity)); double metricValue = Entropy::calculate(testImage); EXPECT_DOUBLE_EQ(metricValue, 0.0); } TEST(EntropyTest, RealImage) { const std::string testImagePath("../tests/testimage.jpg"); cv::Mat colorTestImage = cv::imread(testImagePath); ASSERT_TRUE(colorTestImage.data); cv::Mat testImage; cv::cvtColor(colorTestImage, testImage, cv::COLOR_RGB2GRAY); double metricValue = Entropy::calculate(testImage); //std::cout << metricValue << "\n"; EXPECT_TRUE(metricValue != 0.0); }
true
7a25a509b76d29a296db688dec9d612c9cff26c9
C++
green-fox-academy/nicobognar
/week-01/day-3/Cuboid/main.cpp
UTF-8
583
3.90625
4
[]
no_license
#include <iostream> int main(int argc, char *args[]) { double sideX = 145; double sideY = 60; double sideZ = 95; int surface_area = sideX * 2 + sideY * 2 + sideZ * 2; int volume_cuboid = sideX * sideY * sideZ; std::cout << "Surface Area: " << surface_area << std::endl; std::cout << "Volume: " << volume_cuboid << std::endl; // Write a program that stores 3 sides of a cuboid as variables (doubles) // The program should write the surface area and volume of the cuboid like: // // Surface Area: 600 // Volume: 1000 return 0; }
true
6b887d192bc0a66ef81d509fef1631dde0961263
C++
xjorma/LaserCube
/SimpleLaserCpp/UDPSocket.h
UTF-8
3,260
2.734375
3
[]
no_license
#pragma once #include <string> #include <iostream> #include <WinSock2.h> #include <Ws2tcpip.h> class WSASession { public: WSASession() { if (!m_count) { int ret = WSAStartup(MAKEWORD(2, 2), &data); if (ret != 0) throw std::system_error(WSAGetLastError(), std::system_category(), "WSAStartup Failed"); } m_count++; } ~WSASession() { if (!m_count) { WSACleanup(); } } private: static int m_count; static WSAData data; }; class UDPSocket { public: UDPSocket(u_long iMode = 1) { m_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (m_sock == INVALID_SOCKET) throw std::system_error(WSAGetLastError(), std::system_category(), "Error opening socket"); int iResult = ioctlsocket(m_sock, FIONBIO, &iMode); if (iResult != NO_ERROR) throw std::system_error(WSAGetLastError(), std::system_category(), "Cannot set socket to non-blocking"); } ~UDPSocket() { closesocket(m_sock); } void SendTo(const std::string& address, unsigned short port, const char* buffer, int len, int flags = 0) { sockaddr_in add; add.sin_family = AF_INET; InetPton(AF_INET, std::wstring(address.begin(), address.end()).c_str(), &add.sin_addr.s_addr); add.sin_port = htons(port); int ret = sendto(m_sock, buffer, len, flags, reinterpret_cast<SOCKADDR*>(&add), sizeof(add)); if (ret < 0) throw std::system_error(WSAGetLastError(), std::system_category(), "sendto failed"); } void SendTo(sockaddr_in& address, const char* buffer, int len, int flags = 0) { int ret = sendto(m_sock, buffer, len, flags, reinterpret_cast<SOCKADDR*>(&address), sizeof(address)); if (ret < 0) throw std::system_error(WSAGetLastError(), std::system_category(), "sendto failed"); } int RecvFrom(char* buffer, int len, int flags = 0) { sockaddr_in from; int size = sizeof(from); int ret = recvfrom(m_sock, buffer, len, flags, reinterpret_cast<SOCKADDR*>(&from), &size); if (ret < -1) { throw std::system_error(WSAGetLastError(), std::system_category(), "recvfrom failed"); } else if (ret == -1) { return ret; } else { // make the buffer zero terminated buffer[ret] = 0; } return ret; } void Bind(unsigned short port) { sockaddr_in add; add.sin_family = AF_INET; add.sin_addr.s_addr = htonl(INADDR_ANY); add.sin_port = htons(port); int ret = bind(m_sock, reinterpret_cast<SOCKADDR*>(&add), sizeof(add)); if (ret < 0) throw std::system_error(WSAGetLastError(), std::system_category(), "Bind failed"); } void SetBroadCast() { char broadcast = '1'; int ret = setsockopt(m_sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)); if (ret < 0) throw std::system_error(WSAGetLastError(), std::system_category(), "Broadcast failed"); } private: WSASession m_WSASession; SOCKET m_sock; };
true
d03c09228dd4915bfa0848cde21a4465f4343c30
C++
uwuser/MCsim
/src/ClockDomain.h
UTF-8
1,357
2.765625
3
[ "MIT" ]
permissive
#include <iostream> #include <cmath> #include <stdint.h> namespace ClockDomain { template <typename ReturnT> class CallbackBase { public: virtual ReturnT operator()() = 0; }; template <typename ConsumerT, typename ReturnT> class Callback : public CallbackBase<ReturnT> { private: typedef ReturnT (ConsumerT::*PtrMember)(); public: Callback(ConsumerT *const object, PtrMember member) : object(object), member(member) {} Callback(const Callback<ConsumerT, ReturnT> &e) : object(e.object), member(e.member) {} ReturnT operator()() { return (const_cast<ConsumerT *>(object)->*member)(); } private: ConsumerT *const object; const PtrMember member; }; typedef CallbackBase<void> ClockUpdateCB; class ClockDomainCrosser { public: ClockUpdateCB *callback; uint64_t clock1, clock2; uint64_t counter1, counter2; ClockDomainCrosser(ClockUpdateCB *_callback); ClockDomainCrosser(uint64_t _clock1, uint64_t _clock2, ClockUpdateCB *_callback); ClockDomainCrosser(double ratio, ClockUpdateCB *_callback); void update(); }; class TestObj { public: TestObj() {} void cb(); int test(); }; } // namespace ClockDomain
true
454ca3b046a0c1e51e6a2bc34fd03e7684a9f410
C++
hughrover/leetcode
/src/main/java/problems/Q160IOTLL.cpp
UTF-8
1,097
3.734375
4
[]
no_license
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *p1 = headA, *p2 = headB; while (p1 != NULL && p2 != NULL) { if (p1 == p2) { return p1; } else { if (p1->next != NULL && p2->next != NULL) { p1 = p1->next; p2 = p2->next; } else if (p1->next == NULL && p2->next == NULL) { return NULL; } else if (p1->next == NULL) { p1 = headB; p2 = p2->next; } else { p2 = headA; p1 = p1->next; } } } return NULL; } }; int main() { ListNode *n1 = new ListNode(1); ListNode *n2 = new ListNode(2); ListNode *n3 = new ListNode(3); ListNode *n4 = new ListNode(4); n1->next = n4; n2->next = n3; n3->next = n4; Solution* solution = new Solution(); ListNode *p = solution->getIntersectionNode(n1, n2); cout << p->val; }
true
441c5e08c748e98711d7f3d1077f3ea23cfa9a2c
C++
ydk1104/PS
/boj/2000~2999/2576.cpp
UTF-8
354
2.578125
3
[]
no_license
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; vector<int> v; int main(void){ for(int i=0; i<7; i++){ int x; scanf("%d", &x); if(x%2) v.push_back(x); } sort(v.begin(), v.end()); if(v.size()){ int sum = 0; for(int i=0; i<v.size(); i++) sum+=v[i]; printf("%d\n%d", sum, v[0]); } else{ printf("-1"); } }
true
7e3fdb114b6cf3b3ae9806b3de8ba9363b66fcc9
C++
almas-ashruff/DSASolutions
/August/7 Aug/longestIncreasingSubsequence.cpp
UTF-8
1,411
3.75
4
[]
no_license
// Given an array of integers, find the length of the longest (strictly) increasing subsequence // from the given array. // https://www.geeksforgeeks.org/lower_bound-in-cpp/ // https://www.algoexpert.io/questions/Longest%20Increasing%20Subsequence // OPTIMIZED DP - O(N Log N) - solution. Can also be solved using less complex DP solution in O(N ^ 2) int longestSubsequence(int n, int a[]) { vector<int> dp; dp.push_back(a[0]); for(int i = 0; i < n; i++) { if(dp.back() < a[i]) { dp.push_back(a[i]); // if the current value in the array is greater than the // last value in the DP, push the current value in the DP at the end } else { // if the current array value is smaller int index = lower_bound(dp.begin(), dp.end(), a[i]) - dp.begin(); // The lower_bound() method in C++ is used to return an iterator // pointing to the first element in the range [first, last) // which has a value not less than val. // https://www.geeksforgeeks.org/lower_bound-in-cpp/ // index = the first index that has the value // greater than or equal to current array value. // You have to subtract the begining index to get // the index in the array dp[index] = a[i]; } } return dp.size(); }
true
5beaa6eb0f98fdd5fc10c30e94d9bc30c272ea34
C++
Sascha8a/MapReduce
/server/include/Task.hpp
UTF-8
237
2.515625
3
[ "BSL-1.0" ]
permissive
#pragma once #include <string> /** * @brief Struct containing information of a task. * Contains a unique identifier and some form of protobuf message, that is delivered to nodes. * */ struct Task { long id; std::string job; };
true
6abf8edbfe30ffe934b54e3da4bbbf883fa59b79
C++
Mtarginoo/DCA1202
/Tratamento de poligonos/Projeto_1/point.h
UTF-8
2,043
3.859375
4
[]
no_license
#ifndef POINT_H #define POINT_H /** * @brief The Point class serve para * estabelecer informações básicas de um * tipo comum chamado Point */ class Point { private: float x, y; public: /** * @brief setX é um método que serve * para realizar a atribuição da coordenada x * de um ponto. */ void setX(float); /** * @brief setY é um método que serve * para realizar a atribuição da coordenada y * de um ponto. */ void setY(float); /** * @brief setXY é um método que serve * pare realizar a atribuição, simultaneamente, das coordenadas x e y * de um ponto. */ void setXY(float, float); /** * @brief getX é um método que retorna o valor * da coordenada x de um ponto. * @return float <coordenada_x_do_ponto> */ float getX(void); /** * @brief é um método que retorna o valor * da coordenada y de um ponto. * @return float <coordenada_y_do_ponto> */ float getY(void); /** * @brief add Realiza a adição das coordenadas * x e y de dois pontos. * @param p1 O parâmetro p1 é o ponto a ser adicionado. * @return Retorna o ponto com as coordenadas somadas. */ Point add(Point p1); /** * @brief sub Realiza a subtração das coordenadas * x e y de dois pontos. * @param p1 O parâmetro p1 é ponto a ser subtraído. * @return Retorna o ponto com as coordendas subtraídas. */ Point sub(Point p1); /** * @brief norma Método que retorna o módulo do vetor. * @return float <modulo> */ float norma(); /** * @brief translada Método que translada as coordenadas x e y * do ponto para (x+a, y+b). * @param a É o valor que será somado a coordenada x. * @param b É o valor que será somado a coordenada y. */ void translada(float a, float b); /** * @brief imprime Método que imprime o ponto na forma (x,y) */ void imprime(); }; #endif // POINT_H
true
6d6e52489cace6f875c841df413c33dd2ad57ea7
C++
QCDogsquad/vex-metal-hounds-2020
/src/tyler_utilities.h
UTF-8
3,231
2.5625
3
[]
no_license
#if !defined(TYLER_UTILITIES_H) #define TYLER_UTILITIES_H //~ Primitive types #include <stddef.h> #include <stdint.h> typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef s8 b8; typedef s16 b16; typedef s32 b32; typedef s64 b64; typedef uintptr_t rawptr; #define U8_MAX 0xff #define U16_MAX 0xffff #define U32_MAX 0xffffffff #define U64_MAX 0xffffffffffffffff #define S8_MAX 0x7f #define S16_MAX 0x7fff #define S32_MAX 0x7fffffff #define S64_MAX 0x7fffffffffffffff #define S8_MIN 0x80 #define S16_MIN 0x8000 #define S32_MIN 0x80000000 #define S64_MIN 0x8000000000000000 typedef size_t memory_index; typedef float f32; typedef double f64; #define internal static #define global static #define global_constant static const #define local_persist static #define local_constant static const //~ Platform interface struct memory_arena; struct file_info { memory_index Size; void *Data; }; file_info PlatformReadEntireFile(const char *Path); void FreeFileInfo(memory_arena *Arena, file_info File); //~ Helpers #define ArrayCount(Array) (sizeof(Array)/sizeof(*Array)) #define Kilobytes(Size) (1024*(Size)) #define Megabytes(Size) (1024*Kilobytes(Size)) #define Gigabytes(Size) (1024L*(u64)Megabytes(Size)) #if defined(_MSC_VER) #define Assert(Expr) do {if (!(Expr)) __debugbreak();} while(0) #else #include <assert.h> #define Assert(Expr) assert(Expr) #endif #if !defined(CopyMemory) void CopyMemory(void *Dest, void *Source, memory_index Size); #endif template <typename Type> inline Type Minimum(Type A, Type B) { Type Result = (A > B) ? B : A; return(Result); } template <typename Type> inline Type Maximum(Type A, Type B) { Type Result = (A > B) ? A : B; return(Result); } //~ Memory arena struct memory_arena { u8 *Memory; memory_index Used; memory_index Size; u32 TempCount; }; struct temporary_memory { memory_arena *Arena; memory_index Size; }; void InitializeArena(memory_arena *Arena, void *Memory, memory_index Size); #define PushStruct(Arena, Struct) PushMemory(Arena, sizeof(Struct)) #define PushArray(Arena, Size, Type) (Type *)PushMemory(Arena, Size*sizeof(Type)) void *PushMemory(memory_arena *Arena, memory_index Size); b32 AddMemory(memory_arena *Arena, memory_index Size); void FreeMemory(memory_arena *Arena, void *Memory, memory_index Size); //~ Strings struct string_u8 { u64 Size; u8 *Str; }; struct string_const_u8 { u64 Size; const u8 *Str; }; u64 CStringLength(const char *CString); string_u8 Su8(u8 *Str, u64 Size); string_u8 Su8(char *CString); string_const_u8 SCu8(string_u8 String); string_const_u8 SCu8(const u8 *Str, u64 Size); string_const_u8 SCu8(char *CString); string_u8 PushStringU8(memory_arena *Arena, u64 Size); string_const_u8 PushStringConstU8(memory_arena *Arena, u64 Size); string_u8 NewStringU8(memory_arena *Arena, u8 *Str, u64 Size); void FreeString(memory_arena *Arena, string_u8 String); void FreeStringConst(memory_arena *Arena, string_const_u8 String); b32 DoStringsMatch(string_const_u8 A, string_const_u8 B); #endif //TYLER_UTILITIES_H
true
195abfa8dc543696fe848726802071a65b0cc98e
C++
signmotion/person
/person/include/Person.h
WINDOWS-1251
3,183
3.078125
3
[]
no_license
#pragma once #include "Character.h" #include "LikeMemory.h" #include "AffectionMemory.h" #include "InfoMemory.h" #include <string> namespace person { class Person; typedef std::shared_ptr< Person > PersonPtr; typedef std::unique_ptr< Person > PersonUPtr; } namespace std { inline std::ostream& operator<<( std::ostream&, const person::Person& ); } namespace person { /** * . * . */ class Person { public: inline Person() { } inline virtual ~Person() { } /** * @return . */ inline std::string operator()() const { std::ostringstream ss; ss << *this; return ss.str(); } inline Character const& character() const { return mCharacter; } inline Character& character() { return mCharacter; } inline InfoMemory const& infoMemory() const { return mInfoMemory; } inline InfoMemory& infoMemory() { return mInfoMemory; } inline LikeMemory const& likeMemory() const { return mLikeMemory; } inline LikeMemory& likeMemory() { return mLikeMemory; } inline AffectionMemory const& affectionMemory() const { return mAffectionMemory; } inline AffectionMemory& affectionMemory() { return mAffectionMemory; } inline Person& operator<<( const Character& ch ) { mCharacter = ch; return *this; } inline Person& operator<<( const Info& info ) { mInfoMemory << info; return *this; } private: /** * . */ Character mCharacter; /** * -. * . */ InfoMemory mInfoMemory; /** * " -> / ". * , .. * - - . */ LikeMemory mLikeMemory; /** * " -> ". * , .. * - - . */ AffectionMemory mAffectionMemory; /** * @todo . */ /** * @todo . */ }; } // person namespace std { inline std::ostream& operator<<( std::ostream& out, const person::Person& p ) { out << "{ " << "\"character\": " << p.character() << ", " << "\"info-memory\": " << p.infoMemory() << ", " << "\"like-memory\": " << p.likeMemory() << ", " << "\"affection-memory\": " << p.affectionMemory() << " }"; return out; } } // std
true
ee99de69214faa6b91299fbfc7c2aff8ed745169
C++
hlissner/practice
/codeeval/easy/208highestscore/solution.cpp
UTF-8
867
2.84375
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; int main(int argc, char *argv[]) { ifstream infile(argv[1]); string line; while (getline(infile, line)) { stringstream ss(line); vector<int> tokens; int cols = 0; int rows = 0; string x; for (int i = 0; ss >> x; ++i) { if (x == "|") { if (cols == 0) cols = i; ++rows; continue; } tokens.push_back(strtol(x.c_str(), NULL, 10)); } for (int i = 0; i < cols; ++i) { int m = tokens[i]; for (int j = 1; j <= rows; ++j) { m = max(m, tokens[i+(cols*j)]); } cout << m << (i == cols-1 ? "" : " "); } cout << endl; } return 0; }
true
3824e0dedcb429c3ea7b94d6b83abb2abb2d8219
C++
vsmawoex/GeeksForGeeks
/MaximumAs/SourceCode.cpp
UTF-8
800
3.171875
3
[]
no_license
// Solution for below link // http://www.geeksforgeeks.org/how-to-print-maximum-number-of-a-using-given-four-keys/ #include <iostream> #include <cmath> #include <vector> using namespace std; void CalculateNbAs(vector<int> &nbAs, int nbMaxStrokes) { nbAs[0] = 0; nbAs[1] = 1; nbAs[2] = 2; nbAs[3] = 3; if(nbMaxStrokes >= 4) { int nbMaxAs = nbMaxStrokes; int power = 2; for(int nbStrokes = nbMaxStrokes - 3; nbStrokes >= 1; --nbStrokes) { if(nbAs[nbStrokes] == 0) CalculateNbAs(nbAs, nbStrokes); nbMaxAs = max(nbMaxAs, power*nbAs[nbStrokes]); power++; } nbAs[nbMaxStrokes] = nbMaxAs; } } int main(int argc, char* argv[]) { int nbMaxStrokes = 0; cin >> nbMaxStrokes; vector<int> nbAs(nbMaxStrokes+1); CalculateNbAs(nbAs, nbMaxStrokes); cout << nbAs[nbMaxStrokes]; return 0; }
true
4ae7d633f4e1520fb7579648aaca323ff19621ca
C++
InvincibleSarthak/Competitive-Programming
/InterviewBit/Painter's Partition.cpp
UTF-8
1,053
3.3125
3
[]
no_license
/* 1. Calculate the maximum possible time. 2. Now, using binary search find the time limit within 1....sum in which all the tasks can be completed with the help of A painters. 3. Finally we get the units, now multiply these units with time per unit B to get the total time taken. */ bool check(int A, vector<int>&C, long long int mid){ int n = C.size(); long long int sum = 0; int painter = 1; for(int i=0;i<n;i++){ if(C[i] > mid) return false; else if(sum + C[i] > mid){ painter++; if(painter > A) return false; else sum = C[i]; } else sum += C[i]; } return true; } int Solution::paint(int A, int B, vector<int> &C) { int n = C.size(); long long int sum = 0; for(int i=0;i<n;i++){ sum += C[i]; } long long int start = 0, end = sum; while(start <= end){ long long int mid = ((end-start)>>1) + start; if(check(A,C,mid)) end = mid-1; else start = mid+1; } return (start*B)%10000003; }
true
4c26da8649a3777939195a60d9b7b47acd2f17ca
C++
dragon-web/second_stage_review
/Sort/Insert_Sort/insert_sort2.cpp
UTF-8
620
3.6875
4
[]
no_license
#include <iostream> using namespace std; void Insert_Sort(int *arr, size_t sz) { for(size_t i = 1; i < sz; ++i) { int key = arr[i]; // 当前要插入元素 int end = i - 1; while(key <= arr[end] && end >= 0) { arr[end+1] = arr[end]; end--; } arr[end + 1] = key; } } int main() { int arr[100]; for(int i = 0 ; i < 100 ;++i) { arr[i] = 100 - i; } size_t sz = sizeof(arr)/sizeof(arr[0]); Insert_Sort(arr,sz); for(size_t i = 0;i < sz;++i) { cout << arr[i] <<" "; } return 0; }
true
d6e77fe0e1c382424771ee5df6c299e264eaeb10
C++
CryptoLover705/3d_game_engine
/src/Engine/EntityManager.cpp
UTF-8
1,284
2.828125
3
[]
no_license
#include "EntityManager.h" #include <algorithm> #include <vector> Entity* EntityManager::SpawnInternal(Entity* NewEntity) { EntityList.push_back(std::unique_ptr<Entity>(NewEntity)); NewEntity->GameEngine = GameEngine; NewEntity->BeginPlay(); return NewEntity; } Component* EntityManager::AddComponentInternal(Entity* Parent, Component* NewComponent) { Parent->Components.push_back(std::unique_ptr<Component>(NewComponent)); NewComponent->GameEngine = GameEngine; NewComponent->Owner = Parent; NewComponent->BeginPlay(); return NewComponent; } void EntityManager::RefreshComponents(Entity* PendingEntity) { PendingEntity->Components.erase( std::remove_if( PendingEntity->Components.begin(), PendingEntity->Components.end(), [&] (std::unique_ptr<Component>& comp) { return comp.get() == nullptr || comp->IsDestroyed(); }), PendingEntity->Components.end() ); } void EntityManager::RefreshEntities() { EntityList.erase( std::remove_if( EntityList.begin(), EntityList.end(), [&] (std::unique_ptr<Entity>& ent) { return ent.get() == nullptr || ent->IsDestroyed(); }), EntityList.end() ); }
true
c441b611e2d29876b313ff10000777628922b3dd
C++
Akaflieg/startkladde
/src/model/Plane.cpp
UTF-8
9,714
2.609375
3
[]
no_license
#include "Plane.h" #include <cassert> #include <QApplication> #include "src/text.h" #include "src/db/result/Result.h" #include "src/db/Query.h" #include "src/i18n/notr.h" // ****************** // ** Construction ** // ****************** Plane::Plane (): Entity () { initialize (); } Plane::Plane (dbId id): Entity (id) { initialize (); } void Plane::initialize () { numSeats=0; category=categoryNone; } // ********************* // ** Property access ** // ********************* bool Plane::selfLaunchOnly () const { // Note that motorgliders can be gliders; and there are even some TMGs // which can do winch launch. return category==categoryAirplane || category==categoryUltralight; } /** * Returns the registration in form "D-XXXX (YY)" (or user-defined) if both * registration and callsign are non-blank, or just one of the components if the * other one is blank. * * To change the form of the result if both the registration and callsign are * non-blank, pass the template in fullTemplate. %1 will be replaced with the * registration and %2 with the callsign. * * @see FlarmNetRecord::fullRegistration */ QString Plane::fullRegistration (const QString &fullTemplate) const { if (isBlank (callsign)) return registration; else if (isBlank (registration)) return callsign; else return fullTemplate.arg (registration, callsign); } QString Plane::registrationWithType () const { if (isBlank (type)) return registration; else if (isBlank (registration)) return type; else return qnotr ("%1 (%2)").arg (registration, type); } // **************** // ** Formatting ** // **************** QString Plane::toString () const { return qnotr ("id=%1, registration=%2, callsign=%3, type=%4, club=%5, category=%6, seats=%7, Flarm ID=%8") .arg (id) .arg (registration) .arg (callsign) .arg (type) .arg (club) .arg (categoryText (category)) .arg (numSeats) .arg (flarmId) ; } QString Plane::toNiceString() const { QString result = registration; if (!callsign.isEmpty()) result += QString(" (%1)").arg(callsign); if (!type.isEmpty()) result += QString(", %1").arg(type); return result; } bool Plane::clubAwareLessThan (const Plane &p1, const Plane &p2) { QString club1=simplifyClubName (p1.club); QString club2=simplifyClubName (p2.club); if (club1<club2) return true; if (club1>club2) return false; if (p1.registration<p2.registration) return true; if (p1.registration>p2.registration) return false; return false; } QString Plane::getDisplayName () const { return registration; } // ********************** // ** Category methods ** // ********************** QList<Plane::Category> Plane::listCategories (bool includeInvalid) { QList<Category> result; result << categoryAirplane << categoryGlider << categoryMotorglider << categoryUltralight << categoryHelicopter << categoryOther; if (includeInvalid) result << categoryNone; return result; } QString Plane::categoryText (Plane::Category category) { switch (category) { case categoryAirplane: return qApp->translate ("Plane", "airplane"); case categoryGlider: return qApp->translate ("Plane", "glider"); case categoryMotorglider: return qApp->translate ("Plane", "motorglider"); case categoryUltralight: return qApp->translate ("Plane", "ultralight"); case categoryHelicopter: return qApp->translate ("Plane", "helicopter"); case categoryOther: return qApp->translate ("Plane", "other"); case categoryNone: return qApp->translate ("Plane", "none"); // no default } assert (!notr ("Unhandled category")); return notr ("?"); } /** * Tries to determine the category of an aircraft from its registration. This * only works for countries where the category follows from the registration. * Currently, this is only implemented for german (D-....) registrations * * @param registration the registration * @return the category for the registration reg, or categoryNone or * categoryOther */ Plane::Category Plane::categoryFromRegistration (QString registration) { if (registration.length () < 3) return categoryNone; if (registration[0] != 'D') return categoryNone; if (registration[1] != '-') return categoryNone; QChar kbu = registration.at (2).toLower (); if (kbu == '0' || kbu == '1' || kbu == '2' || kbu == '3' || kbu == '4' || kbu == '5' || kbu == '6' || kbu == '7' || kbu == '8' || kbu == '9' || kbu == 'n') return categoryGlider; else if (kbu == 'e' || kbu == 'f' || kbu == 'g' || kbu == 'i' || kbu == 'c' || kbu == 'b' || kbu == 'a') return categoryAirplane; else if (kbu == 'm') return categoryUltralight; else if (kbu == 'k') return categoryMotorglider; else if (kbu == 'h') return categoryHelicopter; else return categoryOther; } /** * Returns the maximum number of seats in a plane of a given category, or -1 * if there is no maximum. */ int Plane::categoryMaxSeats (Plane::Category category) { switch (category) { case categoryNone: return -1; case categoryAirplane: return -1; case categoryGlider: return 2; case categoryMotorglider: return 2; case categoryUltralight: return 2; case categoryHelicopter: return -1; case categoryOther: return -1; } assert (false); return -1; } // ***************** // ** ObjectModel ** // ***************** int Plane::DefaultObjectModel::columnCount () const { return 9; } QVariant Plane::DefaultObjectModel::displayHeaderData (int column) const { switch (column) { case 0: return qApp->translate ("Plane::DefaultObjectModel", "Registration"); case 1: return qApp->translate ("Plane::DefaultObjectModel", "Callsign"); case 2: return qApp->translate ("Plane::DefaultObjectModel", "Model"); case 3: return qApp->translate ("Plane::DefaultObjectModel", "Category"); case 4: return qApp->translate ("Plane::DefaultObjectModel", "Seats"); case 5: return qApp->translate ("Plane::DefaultObjectModel", "Club"); case 6: return qApp->translate ("Plane::DefaultObjectModel", "Flarm ID"); case 7: return qApp->translate ("Plane::DefaultObjectModel", "Comments"); // TODO remove from DefaultItemModel? case 8: return qApp->translate ("Plane::DefaultObjectModel", "ID"); } assert (false); return QVariant (); } QVariant Plane::DefaultObjectModel::displayData (const Plane &object, int column) const { switch (column) { case 0: return object.registration; case 1: return object.callsign; case 2: return object.type; case 3: return firstToUpper (categoryText(object.category)); case 4: return object.numSeats>=0?QVariant (object.numSeats):QVariant (notr ("?")); case 5: return object.club; case 6: return object.flarmId; case 7: return object.comments; case 8: return object.id; } assert (false); return QVariant (); } // ******************* // ** SQL interface ** // ******************* QString Plane::dbTableName () { return notr ("planes"); } QString Plane::selectColumnList () { return notr ("id,registration,club,num_seats,type,category,callsign,flarm_id,comments"); } Plane Plane::createFromResult (const Result &result) { Plane p (result.value (0).toLongLong ()); p.registration =result.value (1).toString (); p.club =result.value (2).toString (); p.numSeats =result.value (3).toInt (); p.type =result.value (4).toString (); p.category =categoryFromDb ( result.value (5).toString ()); p.callsign =result.value (6).toString (); p.flarmId =result.value (7).toString (); p.comments =result.value (8).toString (); return p; } Plane Plane::createFromDataMap(const QMap<QString,QString> map) { Plane p (map["id"].toLongLong()); p.registration = map["registration"]; p.club = map["club"]; p.numSeats = map["num_seats"].toInt(); p.type = map["type"]; p.category = categoryFromDb(map["category"]); p.callsign = map["callsign"]; p.flarmId = map["flarm_id"]; p.comments = map["comments"]; return p; } QString Plane::insertColumnList () { return notr ("registration,club,num_seats,type,category,callsign,flarm_id,comments"); } QString Plane::insertPlaceholderList () { return notr ("?,?,?,?,?,?,?,?"); } void Plane::bindValues (Query &q) const { q.bind (registration); q.bind (club); q.bind (numSeats); q.bind (type); q.bind (categoryToDb (category)); q.bind (callsign); q.bind (flarmId); q.bind (comments); } QList<Plane> Plane::createListFromResult (Result &result) { QList<Plane> list; while (result.next ()) list.append (createFromResult (result)); return list; } // *** Enum mappers QString Plane::categoryToDb (Category category) { switch (category) { case categoryNone : return notr ("?") ; case categoryAirplane : return notr ("airplane") ; case categoryGlider : return notr ("glider") ; case categoryMotorglider : return notr ("motorglider"); case categoryUltralight : return notr ("ultralight") ; case categoryHelicopter : return notr ("helicopter") ; case categoryOther : return notr ("other") ; // no default } assert (!notr ("Unhandled category")); return notr ("?"); } Plane::Category Plane::categoryFromDb (QString category) { if (category==notr ("airplane") ) return categoryAirplane; else if (category==notr ("glider") ) return categoryGlider; else if (category==notr ("motorglider")) return categoryMotorglider; else if (category==notr ("ultralight") ) return categoryUltralight; else if (category==notr ("helicopter") ) return categoryHelicopter; else if (category==notr ("other") ) return categoryOther; else return categoryNone; }
true
53dfa9decf61975cf5b540c5e8156ba2bb4959b5
C++
googed/coursera-Foundamentals-of-Programming-and-Algorithms
/Intro-to-C-Programming/week07/money.cpp
UTF-8
326
2.75
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; int a[6] = {100, 50, 20, 10, 5, 1}; int b[6] = {0}; int i = 0; cin >> n; while (n > 0) { b[i] = n / a[i]; n = n % a[i]; i++; } for (int j = 0; j < 6; j++) cout << b[j] << endl; return 0; }
true
e8a7d56484cc701001a27f13a7841cd125c2cc7a
C++
VinayRana5674/MyProrammingWrok
/Array erase duplicate.cpp
UTF-8
427
3.046875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { // Initializing vector with array values int arr[] = {5,56,65,7,8,97, 10, 15, 20, 20, 23, 42, 45}; int n = sizeof(arr)/sizeof(arr[0]); vector<int> vec(arr,arr+n); sort(vec.begin(),vec.end()); vec.erase(unique(vec.begin(),vec.end()),vec.end()); for (int i=0; i<n; i++) cout << vec[i] << " "; }
true
8281d81249f98b2b33f2210078fb91518cec6564
C++
ghosty-png/Laboratory-works
/21/Triad.cpp
UTF-8
1,203
3.78125
4
[]
no_license
#include "Triad.h" Triad::Triad(void) { first = 0; second = 0; third = 0; } Triad::~Triad(void) { } Triad::Triad(int f, int s, int t) { first = f; second = s; third = t; } Triad::Triad(const Triad& t) { first = t.first; second = t.second; third = t.third; } void Triad::Set_first(int f) { first = f; } void Triad::Set_second(int s) { second = s; } void Triad::Set_third(int t) { third = t; } void Triad::plusone() { first = first + 1; second = second + 1; third = third + 1; } Triad& Triad:: operator=(const Triad& t) { if (&t == this)return *this; first = t.first; second = t.second; third = t.third; return*this; } istream& operator>>(istream& in, Triad& t) { cout << "\nFirst: "; in >> t.first; cout << "\nSecond: "; in >> t.second; cout << "\nThird: "; in >> t.third; return in; } ostream& operator<<(ostream& out, const Triad& t) { out << "\nFIRST: " << t.first; out << "\nSECOND: " << t.second; out << "\nTHIRD: " << t.third; out << "\n"; return out; } void Triad::Show() { cout << "\nFIRST: " << first; cout << "\nSECOND: " << second; cout << "\nTHIRD: " << third; cout << endl; }
true
340a2e72bbee7ae04774e65524eb436efc62e623
C++
kkob999/my_mono_pj
/Asset/Dice.h
UTF-8
172
2.609375
3
[]
no_license
#ifndef DICE_H #define DICE_H class dice { private: int sides; public: //constructor dice(); //functions to get values int rollDice(); }; #endif
true
18fcadcf8f6416587c8997cc2e321be6dd9d02ca
C++
MateuszJiang/Cpp_Advanced_Purell
/Prata_Ch14_1/Wine.cpp
UTF-8
813
2.71875
3
[]
no_license
#include "Wine.h" Wine::Wine(const char* l, int numberOfYears, const int yr[], const int bot[]) :PairArray(numberOfYears, numberOfYears), std::string("sss") { NumberOfYears = numberOfYears; for (int i = 0; i < numberOfYears; i++) { PairArray::first[i] = yr[i]; PairArray::second[i] = bot[i]; } } Wine::Wine(const char* l, int numberOfYears) :PairArray(numberOfYears, numberOfYears), std::string("sss") { NumberOfYears = numberOfYears; } void Wine::GetBottles() { for (int i = 0; i < NumberOfYears; i++) { PairArray::first[i] = i; PairArray::second[i] = i; } } std::string Wine::Label() { return std::string::data(); } int Wine::Sum() { return PairArray::second.sum(); } void Wine::Show() { for (int i = 0; i < NumberOfYears; i++) { std::cout << PairArray::second[i] << std::endl; } }
true
6a7fb13f9b3a78694a5f4e1a449ca69a5bb86d30
C++
sylwiamolitor/Projekty
/Tamagotchi/Tamagotchi/Animal.h
UTF-8
914
2.875
3
[]
no_license
#pragma once #include <iostream> #include <SFML/Graphics.hpp> #include <TGUI/TGUI.hpp> #include "GraphicalObject.h" using namespace std; using namespace sf; class Animal : public GraphicalObject, public Sprite { protected: int enableWalking; int counterWalking = 0; int counterEating = 0; int counterSleeping = 0; Texture animalTexture; int colorIterator; public: Animal() {}; int flagPosition = 0; Animal(string imgDirectory,int pPosX, int pPosY,int pSize) :GraphicalObject(pPosX,pPosY,pSize) { if (!animalTexture.loadFromFile(imgDirectory)) { cerr << "Error"; } }; void drawAnimal(RenderWindow &window); void setColorIterator(int colorIterator); void changeEnableWalking(int e); int getColorIterator(); virtual void moveAnimal(char direction, float moveSpeed) = 0; virtual void eat() = 0; virtual void sleep() = 0; virtual void play() = 0; virtual void setInitialPosition() = 0; };
true
91e6a3f459d2f05ecf1a87b8f5ce2c8d6b474249
C++
oha-yashi/cpplibs
/regex.cpp
UTF-8
1,956
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; #define LIMIT 1000000007 //10^9+7 #define rep(i, n) for(int i=0; i<(int)n; i++) #define all(v) (v).begin(), (v).end() namespace /* debug */{ #define DEBUG(...) do{cout<<#__VA_ARGS__<<" = ";debug(__VA_ARGS__);}while(0) //変数 #define ldebug(...) do{cout<<"["<<setw(3)<<__LINE__<<"] ";debug(__VA_ARGS__);}while(0) //行数 #define lDEBUG(...) do{cout<<"["<<setw(3)<<__LINE__<<"] "<<#__VA_ARGS__<<" = ";debug(__VA_ARGS__);}while(0) //変数, 行数 template<class T>void show(T&x){cout<<x<<" ";} //出力 template<class T>void showendl(T&x){cout<<x<<endl;} //出力改行 template<class P,class Q>void show(pair<P,Q>&x){cout<<"("<<x.first<<", "<<x.second<<") ";} //pair出力 template<class P,class Q>void showendl(pair<P,Q>&x){cout<<"("<<x.first<<", "<<x.second<<")"<<endl;} //pair出力改行 template<class H>void debug(H&&h){showendl(h);} //引数1つ template<class H,class...Ts>void debug(H&&h,Ts&&...ts){show(h);debug(forward<Ts>(ts)...);} //可変引数 template<class T>void debug(vector<T>&vt){int i=0;for(auto x:vt)++i!=vt.size()?show(x):showendl(x);} //vector出力 template<class T>void debug(initializer_list<T>init){int i=0;for(auto x:init)++i!=init.size()?show(x):showendl(x);} //初期化子リスト出力 } bool check(string S, string T){ bool can_skip; int sl = S.length(); int tl = T.length(); if(sl > tl)return false; if(sl == tl)return S==T; vector<regex> rlist; for(int i=0; i<=sl; i++){ string s = S; s.insert(i, "."); //debug(s); rlist.push_back(regex(s)); } smatch m; bool ans = false; for(int i=0; i<rlist.size(); i++){ if(regex_search(T, m, rlist[i])){ //DEBUG(i); ans=true; } } return ans; } int main(){ int N;cin>>N; string S;cin>>S; while(N--){ string T;cin>>T; bool ok = check(S,T); cout<<(ok?"valid":"invalid")<<endl; } }
true
13b6ae7e1e9fb12dae00ec8a08c0cc7b23dd7ddd
C++
FrankWork/cpptorch
/minitext/app.cc
UTF-8
818
2.515625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <fstream> #include "dictionary.h" #include "vector.h" #include "densematrix.h" int main(int argc, char* argv[]){ //std::string input = argv[1]; //auto args_ = std::make_shared<fasttext::Args>(); //auto dict_ = std::make_shared<fasttext::Dictionary>(args_); //std::ifstream ifs(input); //dict_->readFromFile(ifs); //ifs.close(); fasttext::Vector a(3); for (size_t i=0; i < a.size(); ++i){ a[i] = 1. * (i+2); } std::cout << a << "\n"; fasttext::DenseMatrix m(2, 3); fasttext::real* m_ptr = m.data(); for (size_t i=0; i < 6; ++i){ m_ptr[i] = 1. * i; std::cout << m_ptr[i] << " "; } std::cout << "\n"; m.multiplyRow(a, 0, -1); for (size_t i=0; i < 6; ++i){ std::cout << m_ptr[i] << " "; } std::cout << "\n"; return 0; }
true
6a51b55de0f6bd282400767dd70500d38cb081f7
C++
qinenergy/leetCode
/96. Unique Binary Search Trees.cpp
UTF-8
311
2.796875
3
[ "MIT" ]
permissive
class Solution2 { public: int numTrees(int n) { vector<int> nbsts(n + 1, 0); nbsts[0] = 1, nbsts[1] = 1, nbsts[2] = 2; for(int i = 3; i <= n; ++i) for(int root = 1; root <= n; ++root) nbsts[i] += nbsts[root - 1] * nbsts[i - root]; return nbsts[n]; } };
true
008a6e7df51c927d9d7a3ae3547a022e8bc7fc8a
C++
emilk/emath
/emath/math.cpp
UTF-8
1,292
2.671875
3
[]
no_license
// Created by Emil Ernerfeldt on 2012-10-15. #include "math.hpp" #include "fwd.hpp" #include <cassert> namespace emath { static_assert(std::numeric_limits<float>::has_denorm, "has_denorm"); /* See http://randomascii.wordpress.com/2012/01/11/tricks-with-the-floating-point-format/ for the potential portability problems with the union and bit-fields below. */ union Float_t { Float_t(float num = 0.0f) : f(num) {} // Portable extraction of components. bool Negative() const { return (i >> 31) != 0; } int32_t RawMantissa() const { return i & ((1 << 23) - 1); } int32_t RawExponent() const { return (i >> 23) & 0xFF; } int32_t i; float f; #ifdef _DEBUG struct { // Bitfields for exploration. Do not use in production code. uint32_t mantissa : 23; uint32_t exponent : 8; uint32_t sign : 1; } parts; #endif }; static_assert(sizeof(Float_t)==sizeof(float), "Pack"); float next_float(float arg) { if (std::isnan(arg)) { return arg; } if (arg == +INFf) { return +INFf; } // Can't go higher. if (arg==0) { return std::numeric_limits<float>::denorm_min(); } Float_t f = arg; f.i += 1; assert(f.f > arg); return f.f; } // ------------------------------------------------ const zero_tag zero_tag::s_instance; const zero_tag Zero(zero_tag::s_instance); } // namespace emath
true
b8ef4100e578b6fd3222faf72139b4e06c808bcf
C++
cloudnero/leetcode
/Integer_To_Roman.cpp
UTF-8
1,085
3.765625
4
[]
no_license
/* Integer to Roman Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. */ string intToRoman(int num) { map<int,string> roman; roman.insert(make_pair(1000,"M")); roman.insert(make_pair(900,"CM")); roman.insert(make_pair(500,"D")); roman.insert(make_pair(400,"CD")); roman.insert(make_pair(100,"C")); roman.insert(make_pair(90,"XC")); roman.insert(make_pair(50,"L")); roman.insert(make_pair(40,"XL")); roman.insert(make_pair(10,"X")); roman.insert(make_pair(9,"IX")); roman.insert(make_pair(5,"V")); roman.insert(make_pair(4,"IV")); roman.insert(make_pair(1,"I")); string ans; for(map<int,string>::reverse_iterator it = roman.rbegin(); it != roman.rend(); it++){ //因为要从高位开始,所以这里用reverse_iterator while(num >= it -> first){ ans += it -> second; num -= it -> first; } } return ans; }
true
96f439fc06638b5d858010275f3f0250995bafc6
C++
youngkan/design-patterns
/StrategyPattern/98/StrategyPattern.cc
UTF-8
2,752
3.453125
3
[]
no_license
//策略模式:定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略 //模式让算法可以独立于使用它的客户变化 //策略模式3个角色 //1、Context(环境类) //2、Strategy(抽象策略类) //3、ConcreteStrategy(具体策略类) //泡妞秘籍使用场景 //跟不同类型MM约会,要用不同的策略,有的请电影比较好, //有的则去吃小吃效果不错,有的去海边浪漫最合适,但目的都是为了得到MM的芳心 //我们追MM锦囊中有好多Strategy哦 //软件使用场景 //1、一个系统需要动态地在几种算法选择一种 //2、避免使用难以维护的多重条件选择语句 //3、不希望客户端知道复杂的、与算法相关的数据结构,提高算法的保密性与安全性 //具体场景 //1、影院售票系统,在系统中需要为不同类型的用户提供不同的电影票打折方式 //2、xml、txt、dat、access四种格式的数据操作,读取,删除,修改 //优点: //1、提供了对开闭原则的完美支持,用户可以在不修改原有系统的基础上选择算法或行为 //2、提供了管理相关的算法族方法 //3、提供了一种可以替换继承关系的办法 //4、可以避免多重条件选择语句 //5、提供了一种算法复用机制,不同的环境类可以方便地复用策略类 //缺点: //1、客户端必须知道所有的策略类,并自行选择使用哪一个策略类 //2、将造成系统产生很多具体策略类 //3、无法同时在客户端使用多个策略类 #include<iostream> #include<string> using namespace std; /**************策略基类****************************/ //主要定义了虚函数 class Strategy{ public: virtual void Interface() = 0; virtual ~Strategy(){} }; /***************具体策略类***************************/ //负责对子类定义的虚函数进行具体实现 class ConcreteStrategyA : public Strategy{ public: void Interface(){ cout << "ConcreteStrategyA::Interface..."<<endl; } }; class ConcreteStrategyB: public Strategy{ public: void Interface(){ cout << "ConcreteStrategyB:Interface..."<<endl; } }; /*****************调度类********************************/ class Context{ public: Context(Strategy *stg) { stg_ = stg; } void DoAction() { stg_->Interface(); } private: Strategy *stg_; }; int main() { Strategy * pStrategyA = new ConcreteStrategyA(); Context *pContextA = new Context(pStrategyA); pContextA->DoAction(); Strategy * pStrategyB = new ConcreteStrategyB(); Context *pContextB = new Context(pStrategyB); pContextB->DoAction(); delete pContextA; delete pStrategyA; delete pContextB; delete pStrategyB; cin.get(); return 0; }
true
0967f4d195059e9b7cd3871e51d41be7e47de4d9
C++
Dips2705/DSandAlgoLab
/c++ craxx/count.cpp
UTF-8
657
2.859375
3
[]
no_license
lli lowerIndex(lli arr[],lli n,lli x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } lli upperIndex(lli arr[],lli n,lli y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } lli cir(lli arr[],lli n,lli x,lli y) { int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; }
true
3420237367607d462c1a3710c38a5d93f2ebebbc
C++
ehdgus8077/algorithm
/programmers/다음큰숫자.cpp
UTF-8
517
2.796875
3
[]
no_license
#include <string> #include <vector> #include <iostream> using namespace std; int solution(int n) { int one = 0; int zero = 0; while(n) { if (n % 2 == 1){ break; } zero += 1; n /= 2; } while(n) { if (n % 2 != 1){ break; } one += 1; n /= 2; } one -= 1; zero += 1; n += 1; n = n << zero; while(one) { n *= 2; n += 1; one -=1; } return n; }
true
24337afb9df979b3d784bc8ffef6aba6243ee557
C++
lrank/Classifier-demo
/parseFeatureExtract.cpp
UTF-8
1,033
2.65625
3
[]
no_license
#include <cstdio> #include <cstring> char a[150][50]; int main() { //freopen("sample.output.txt", "r", stdin); //freopen("sampleparse.out", "w", stdout); int count = 0; // #s of () int maxcount = 0; //hy of tree int SentenceLength = 0; int totalSentence = 0; // total #s of sentence char str[50]; while (scanf("%s", &str) != EOF) { if (str[0] == '(') { ++ count; if (count > maxcount) maxcount = count; } int length = strlen(str); if (str[length - 1] == ')') { int j = length - 1; for (;str[j] == ')' && j > 0; --j) --count; if (count < 0) { count = 0; continue; } ++ SentenceLength; strncpy(a[SentenceLength], str, j + 1); } if (str[0] != '(' && str[length - 1] != ')') continue; if (count == 0) { printf("%d %d\n", SentenceLength, maxcount); for (int i = 1; i <= SentenceLength; ++i) printf("%s\n", a[i]); ++ totalSentence; SentenceLength = 0; maxcount = 0; memset(a, 0, sizeof(a)); } } // printf("%d\n", totalSentence); return 0; }
true
48440ca55958c3e85890210db366895d26d319bf
C++
tyagi619/Labs
/OpenGL/L3/L3.cpp
UTF-8
11,225
2.6875
3
[]
no_license
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> enum {SPHERE_PLASTIC = 1, SPHERE_TEXTURE, SPHERE_GLOSSY, LIGHT, LEFTWALL, FLOOR}; GLuint texture_sphere; GLfloat shadow_matrix_left[4][4]; GLfloat shadow_matrix_floor[4][4]; GLfloat light_position[] = {50.f, 50.f, -320.f, 1.f}; GLfloat mat[] = {0.f, 0.f, 0.f, 0.f}; GLfloat Amat[] = {0.f, 0.f, 0.f, 0.f}; // Draw the texture for the sphere void make_tex(void){ unsigned char data[256][256][3]; for (int y = 0; y < 255; y++) { for (int x = 0; x < 255; x++) { unsigned char *p = data[y][x]; // changing the function changes the texture pattern p[0] = p[1] = p[2] = (x+y) & 8 ? 255 : 0; } } glGenTextures(1, &texture_sphere); glBindTexture(GL_TEXTURE_2D, texture_sphere); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, (const GLvoid *) data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // create a matrix that will project the desired shadow void shadowmatrix(GLfloat shadow_matrix[4][4],GLfloat plane[4],GLfloat light_position[4]){ GLfloat dot_product; // find dot_product product between light position vector and ground plane normal dot_product = plane[0] * light_position[0] + plane[1] * light_position[1] + plane[2] * light_position[2] +plane[3] * light_position[3]; shadow_matrix[0][0] = dot_product - light_position[0] * plane[0]; shadow_matrix[1][0] = 0.f - light_position[0] * plane[1]; shadow_matrix[2][0] = 0.f - light_position[0] * plane[2]; shadow_matrix[3][0] = 0.f - light_position[0] * plane[3]; shadow_matrix[0][1] = 0.f - light_position[1] * plane[0]; shadow_matrix[1][1] = dot_product - light_position[1] * plane[1]; shadow_matrix[2][1] = 0.f - light_position[1] * plane[2]; shadow_matrix[3][1] = 0.f - light_position[1] * plane[3]; shadow_matrix[0][2] = 0.f - light_position[2] * plane[0]; shadow_matrix[1][2] = 0.f - light_position[2] * plane[1]; shadow_matrix[2][2] = dot_product - light_position[2] * plane[2]; shadow_matrix[3][2] = 0.f - light_position[2] * plane[3]; shadow_matrix[0][3] = 0.f - light_position[3] * plane[0]; shadow_matrix[1][3] = 0.f - light_position[3] * plane[1]; shadow_matrix[2][3] = 0.f - light_position[3] * plane[2]; shadow_matrix[3][3] = dot_product - light_position[3] * plane[3]; } // find the plane equation given 3 points void findplane(GLfloat plane[4],GLfloat vertex0[3], GLfloat vertex1[3], GLfloat vertex2[3]){ GLfloat vector1[3], vector2[3]; // compute the two vectors lying in the plane // vertex0->vertex1 and vertex0->vertex2 vector1[0] = vertex1[0] - vertex0[0]; vector1[1] = vertex1[1] - vertex0[1]; vector1[2] = vertex1[2] - vertex0[2]; vector2[0] = vertex2[0] - vertex0[0]; vector2[1] = vertex2[1] - vertex0[1]; vector2[2] = vertex2[2] - vertex0[2]; // find cross product to get the normal to the plane // the normal along with one point in the plane forms the equation the plane plane[0] = vector1[1] * vector2[2] - vector1[2] * vector2[1]; plane[1] = -(vector1[0] * vector2[2] - vector1[2] * vector2[0]); plane[2] = vector1[0] * vector2[1] - vector1[1] * vector2[0]; plane[3] = -(plane[0] * vertex0[0] + plane[1] * vertex0[1] + plane[2] * vertex0[2]); } // Render plastic sphere void spherePlastic(){ glPushMatrix(); // set position of plastic sphere glTranslatef(0.0f, -75.f, -360.f); glCallList(SPHERE_PLASTIC); glPopMatrix(); } // Render textured sphere void sphereTexture(){ glPushMatrix(); // set position of texture sphere glTranslatef(-40.f, -40.f, -400.f); glCallList(SPHERE_TEXTURE); glPopMatrix(); } // Render Glossy sphere void sphereGlossy(){ glPushMatrix(); // set position of glossy sphere glTranslatef(40.f, -40.f, -400.f); glCallList(SPHERE_GLOSSY); glPopMatrix(); } void draw(){ glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); // Set wall material properties static GLfloat wall_material[] = {1.f, 1.f, 1.f, 1.f}; glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, wall_material); glBegin(GL_QUADS); // Render Floor glNormal3f(0.f, 1.f, 0.f); glVertex3f(-100.f, -100.f, -320.f); glVertex3f( 100.f, -100.f, -320.f); glVertex3f( 100.f, -100.f, -520.f); glVertex3f(-100.f, -100.f, -520.f); glEnd(); // disable lighting glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); // set shadow color to black glColor3f(0.f, 0.f, 0.f); // compute shadow of texture sphere on ground glPushMatrix(); glMultMatrixf((GLfloat *)shadow_matrix_floor); sphereTexture(); glPopMatrix(); // compute shadow of plastic sphere on floor glPushMatrix(); glMultMatrixf((GLfloat *)shadow_matrix_floor); spherePlastic(); glPopMatrix(); // compute shadow of glossy sphere on floor glPushMatrix(); glMultMatrixf((GLfloat *)shadow_matrix_floor); sphereGlossy(); glPopMatrix(); // enable lighting again glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_STENCIL_TEST); glStencilFunc(GL_ALWAYS, 1, 0); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glBegin(GL_QUADS); // Render left wall glNormal3f(1.f, 0.f, 0.f); glVertex3f(-100.f, -100.f, -320.f); glVertex3f(-100.f, -100.f, -520.f); glVertex3f(-100.f, 100.f, -520.f); glVertex3f(-100.f, 100.f, -320.f); glEnd(); glStencilFunc(GL_EQUAL, 1, 1); // Disable lighting so that shadow is rendered as black glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); // Set shadow color to black glColor3f(0.f, 0.f, 0.f); glDisable(GL_DEPTH_TEST); // Compute the shadow of texture sphere on left wall glPushMatrix(); glMultMatrixf((GLfloat *)shadow_matrix_left); sphereTexture(); glPopMatrix(); // Compute the shadow of plastic sphere on left wall glPushMatrix(); glMultMatrixf((GLfloat *)shadow_matrix_left); spherePlastic(); glPopMatrix(); // compute the shadow of glossy sphere on left wall glPushMatrix(); glMultMatrixf((GLfloat *)shadow_matrix_left); sphereGlossy(); glPopMatrix(); // Enable lighting glEnable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glBegin(GL_QUADS); // Render right wall glNormal3f(-1.f, 0.f, 0.f); glVertex3f( 100.f, -100.f, -320.f); glVertex3f( 100.f, 100.f, -320.f); glVertex3f( 100.f, 100.f, -520.f); glVertex3f( 100.f, -100.f, -520.f); // Render ceiling glNormal3f(0.f, -1.f, 0.f); glVertex3f(-100.f, 100.f, -320.f); glVertex3f(-100.f, 100.f, -520.f); glVertex3f( 100.f, 100.f, -520.f); glVertex3f( 100.f, 100.f, -320.f); // Render back wall glNormal3f(0.f, 0.f, 1.f); glVertex3f(-100.f, -100.f, -520.f); glVertex3f( 100.f, -100.f, -520.f); glVertex3f( 100.f, 100.f, -520.f); glVertex3f(-100.f, 100.f, -520.f); glEnd(); glPushMatrix(); glTranslatef(light_position[0], light_position[1], light_position[2]); glDisable(GL_LIGHTING); glColor3f(1.f, 1.f, .7f); glCallList(LIGHT); glEnable(GL_LIGHTING); glPopMatrix(); // Display the textured sphere sphereTexture(); // set material properties for glossy sphere Amat[0] = 0.19225; Amat[1] = 0.19225; Amat[2] = 0.19225; Amat[3] = 1.0; glMaterialfv(GL_FRONT, GL_AMBIENT, Amat); mat[0] = 0.50754; mat[1] = 0.50754; mat[2] = 0.50754; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat); mat[0] = 0.508273; mat[1] = 0.508273; mat[2] = 0.508273; glMaterialfv(GL_FRONT, GL_SPECULAR, mat); glMaterialf(GL_FRONT, GL_SHININESS, 0.4 * 128.0); // display glossy sphere sphereGlossy(); // set material properties for plastic sphere Amat[0] = 0.0; Amat[1] = 0.0; Amat[2] = 0.0; Amat[3] = 1.0; glMaterialfv(GL_FRONT, GL_AMBIENT, Amat); mat[0] = 0.1; mat[1] = 0.35; mat[2] = 0.1; glMaterialfv(GL_FRONT, GL_DIFFUSE, mat); mat[0] = 0.45; mat[1] = 0.55; mat[2] = 0.45; glMaterialfv(GL_FRONT, GL_SPECULAR, mat); glMaterialf(GL_FRONT, GL_SHININESS, 0.25 * 128.0); // display plastic sphere spherePlastic(); glutSwapBuffers(); } // Press Esc to exit the code void key(unsigned char key, int x, int y){ if(key == '\033') exit(0);} int main(int argc, char *argv[]){ glutInit(&argc, argv); glutInitWindowSize(1000, 1000); glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_STENCIL|GLUT_DOUBLE); glutCreateWindow("Sphere"); glutDisplayFunc(draw); glutKeyboardFunc(key); // draw a perspective scene glMatrixMode(GL_PROJECTION); glFrustum(-100., 100., -100., 100., 320., 640.); glMatrixMode(GL_MODELVIEW); // turn on lighting glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); // make shadow matricies GLfloat vertex0[3], vertex1[3], vertex2[3]; GLfloat plane[4]; // 3 points on floor vertex0[0] = -100.f; vertex0[1] = -100.f; vertex0[2] = -320.f; vertex1[0] = 100.f; vertex1[1] = -100.f; vertex1[2] = -320.f; vertex2[0] = 100.f; vertex2[1] = -100.f; vertex2[2] = -520.f; // FInd equation of plane of the floor findplane(plane, vertex0, vertex1, vertex2); // Find shadow matrix for the floor shadowmatrix(shadow_matrix_floor, plane, light_position); // Choose 3 points on left wall to get equation of plane vertex0[0] = -100.f; vertex0[1] = -100.f; vertex0[2] = -320.f; vertex1[0] = -100.f; vertex1[1] = -100.f; vertex1[2] = -520.f; vertex2[0] = -100.f; vertex2[1] = 100.f; vertex2[2] = -520.f; // Find the equation of plane of left wall findplane(plane, vertex0, vertex1, vertex2); // compute the shadow matrix for left wall shadowmatrix(shadow_matrix_left, plane, light_position); /* place light 0 in the right place */ glLightfv(GL_LIGHT0, GL_POSITION, light_position); // get texture for sphere make_tex(); GLUquadricObj *sphere; //Add different types of spheres to list. This saves time //when rendering the spheres since it does not have to create //a new sphere every time the draw function is called //TEXTURED glNewList(SPHERE_TEXTURE, GL_COMPILE); sphere = gluNewQuadric(); glEnable(GL_TEXTURE_2D); gluQuadricDrawStyle(sphere, GLU_FILL); glBindTexture(GL_TEXTURE_2D, texture_sphere); gluQuadricTexture(sphere, GL_TRUE); gluSphere(sphere, 20.f, 20, 20); glDisable(GL_TEXTURE_2D); gluDeleteQuadric(sphere); glEndList(); // PLASTIC glNewList(SPHERE_PLASTIC, GL_COMPILE); sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluSphere(sphere, 20.f, 20, 20); gluDeleteQuadric(sphere); glEndList(); //GLOSSY glNewList(SPHERE_GLOSSY, GL_COMPILE); sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluSphere(sphere, 20.f, 20, 20); gluDeleteQuadric(sphere); glEndList(); // LIGHT BULB glNewList(LIGHT, GL_COMPILE); sphere = gluNewQuadric(); gluSphere(sphere, 5.f, 20, 20); gluDeleteQuadric(sphere); glEndList(); // FLOOR glNewList(FLOOR, GL_COMPILE); glEndList(); //LEFTWALL glNewList(LEFTWALL, GL_COMPILE); glEndList(); glutMainLoop(); }
true
7c4bf9d497415a28af56f3b64fbc13904911c3db
C++
MihaiZhao/vetetris
/VeTetrisGameSolution/VeTetrisGameSolution/Game.cpp
UTF-8
780
3.140625
3
[]
no_license
#include "Game.h" #include "Timer.h" void Game::run() { const float k_frameRate = 60.0f; // Number of times-per-second to try and run game const float k_frameRateTime = 1.0f / k_frameRate; // Time-per-frame // Instantiate a Timer Timer timer; // Useful vars for managing frame-rate float lastTime = timer.getElapsedSeconds(); float currentTime; float timeAccumulator = 0.0f; while (true) { currentTime = timer.getElapsedSeconds(); float timePassed = currentTime - lastTime; lastTime = currentTime; timeAccumulator += timePassed; if (timeAccumulator > k_frameRateTime) { // Consume 1 frame's worth of time timeAccumulator -= k_frameRateTime; // Enough time has passed so perform one cycle loop(k_frameRateTime); } } }
true
32339049a3565742bfebe1f133c3a1c42c0718bd
C++
alex-dias/ParalelizacaoArq2
/mandelbrot_simd_avx.cpp
UTF-8
4,208
2.609375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS // Exigido pelo VS para usar a operação fopen #include <time.h> // Biblioteca para medir o tempo de execução #include <immintrin.h> // Biblioteca para o uso de instruções intrínsecas do AVX #include <stdio.h> #include <math.h> int main() { clock_t start, end; start = clock(); // Início da contagem de tempo const int iXmax = 16384; // Tamanho da imagem const int iYmax = 16384; float cpu_time_used; // A variavel Cx teve seu nome trocado para evitar conflito com o registrador cx do Assembly, Cy tambem foi trocado para manter o padrao float CxPara[8], CyPara[8]; const float CxMin = -2.5; // O tipo das variaveis foram mudadas de Double para Float para possibilitar o const float CxMax = 1.5; // uso de 8 variaveis por registrador YMM do AVX const float CyMin = -2.0; const float CyMax = 2.0; float PixelWidth = (CxMax - CxMin) / iXmax; float PixelHeight = (CyMax - CyMin) / iYmax; const int MaxColorComponentValue = 255; FILE * fp; char *filename = "mandelbrot_simd_avx.ppm"; static unsigned char color[3]; float Zx, Zy; float Zx2, Zy2; int Iteration; const int IterationMax = 256; const float EscapeRadius = 2; float ER2 = EscapeRadius*EscapeRadius; fp = fopen(filename, "wb"); fprintf(fp, "P6\n %d\n %d\n %d\n", iXmax, iYmax, MaxColorComponentValue); // Declaração intrínseca com os 8 valores iniciais de iY __m256 iY = _mm256_set_ps(0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f); // Todas as variaves utilizadas para calcular CyPara e CxPara devem ser vetores de Float possibilitando a paralelização __m256 PixelHeight256 = _mm256_set1_ps(PixelHeight); __m256 CyMin256 = _mm256_set1_ps(CyMin); __m256 PixelWidth256 = _mm256_set1_ps(PixelWidth); __m256 CxMin256 = _mm256_set1_ps(CxMin); // Essa vetor incrementa todos os valores de iX e iY para prepará-lo para a próxima iteração __m256 soma = _mm256_set1_ps(8.0f); for (int i = 0; i < iYmax / 8; i++) // iYmax/8 pois são calculados 8 valores de uma só vez { // Inline Assembly __asm { vmovaps ymm0, [iY] vmulps ymm1, ymm0, [PixelHeight256] vaddps ymm1, ymm1, [CyMin256] vmovups [CyPara], ymm1 vaddps ymm0, ymm0, [soma] // Novos valores para a próxima iteração vmovups [iY], ymm0 } for (int j = 0; j < 8; j++) // Esse loop é necessário para passar cada valor de CyPara calculado { // Declaração intrínseca com os 8 valores iniciais de iX // Perceba que o valor de iX deve ser reiniciado para cada valor de iY, por isso a declaração de iX está dentro desse "for" __m256 iX = _mm256_set_ps(0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f); if (fabs(CyPara[j]) < PixelHeight / 2) CyPara[j] = 0.0; for (int k = 0; k < iXmax / 8; k++) { // Inline Assembly __asm { vmovaps ymm0, [iX] vmulps ymm1, ymm0, [PixelWidth256] vaddps ymm1, ymm1, [CxMin256] vmovups [CxPara], ymm1 vaddps ymm0, ymm0, [soma] // Novos valores para a próxima iteração vmovups [iX], ymm0 } for (int l = 0; l < 8; l++) { Zx = 0.0; Zy = 0.0; Zx2 = 0.0; // O código original executava uma operação desnecessária nesse trecho Zy2 = 0.0; for (Iteration = 0; Iteration < IterationMax && ((Zx2 + Zy2) < ER2); Iteration++) { // CyPara e CxPara são calculados 8 a 8, mas Zy e Zx precisam ser calculados 1 a 1 pois esse loop não é paralelizável Zy = 2 * Zx*Zy + CyPara[j]; Zx = Zx2 - Zy2 + CxPara[l]; Zx2 = Zx*Zx; Zy2 = Zy*Zy; }; if (Iteration == IterationMax) { color[0] = 0; color[1] = 0; color[2] = 0; } else { color[0] = ((IterationMax - Iteration) % 8) * 63; /* Red */ color[1] = ((IterationMax - Iteration) % 4) * 127; /* Green */ color[2] = ((IterationMax - Iteration) % 2) * 255; /* Blue */ }; fwrite(color, 1, 3, fp); } } } } fclose(fp); end = clock(); // fim da contagem de tempo cpu_time_used = ((double)(end - start)) / CLOCKS_PER_SEC; printf("time = %f seconds\n", cpu_time_used); return 0; }
true
530d8e959dde8730108603f1de978ce54717d1a9
C++
XU-zzy/zzy_win10
/note/2_rbtree.cpp
UTF-8
2,579
3.34375
3
[]
no_license
#include<stdio.h> #define RED 1 #define BLACK 2 typedef int KEY_TYPE; typedef struct _rbtree_node{ //rbtree unsigned char color; rbtree_node *parent; rbtree_node *left; rbtree_node *right; //end KEY_TYPE key; //value } rbtree_node; struct rbtree{ rbtree_node *root; //空黑 将所有叶子节点指向这里,当作判断是叶子节点还是NULL的方法,NULL没有颜色属性 rbtree_node *nil; }; //rotate旋转 //六根指针指向变化 //插入节点的时候,要通过左旋或右旋来调整平衡,以维持红黑树的性质 //左旋 void rbtree_left_rotate(rbtree *T,rbtree_node *x){ //NULL ->> T->nil if(x == T->nil) return ; rbtree_node *y = x->right; //1 //先让x指向y的右节点 x->right = y->left; if(y->left != T->nil){ y->left->parent = x; } //2 //让x的父节点指向y y->parent = x->parent; //如果x的父节点是哨兵,那就让y成为root节点 //之后判断x是其父节点的左节点还是右节点 if(x->parent == T->nil){ T->root = y; }else if(x == x->parent->left) { x->parent->left = y; }else{ x->parent->right = y; } //3 //建立x与y的关系,让x成为y的左节点 y->left = x; x->parent = y; } //右旋 //只需要:x->y , y->x , left -> right , right -> left就可以了 void rbtree_right_rotate(rbtree *T,rbtree_node *y){ if(y == T->nil) return ; rbtree_node *x = y->left; //1 y->left = x->right; if(x->right != T->nil){ x->right->parent = y; } //2 x->parent = y->parent; if(y->parent == T->nil){ T->root = x; }else if(y == y->parent->right) { y->parent->right = x; }else{ y->parent->left = x; } //3 x->right = y; y->parent = x; } //插入节点 void rbtree_insert(rbtree *T,rbtree_node *z){ rbtree_node *node = T->root; rbtree_node *tmp = T->nil; while(node != T->nil){ tmp = node; if(z->key < node->key){ node = node->left; }else if(z->key > node->key){ node = node->right; }else{ //Exist return ; } } z->parent = tmp->parent; if(z->key < tmp->key){ tmp->left = z; }else if(z->key > tmp->key){ tmp->right = z; }else{ T->root = z; } z->left = T->nil; z->right = T->nil; z->color = RED; rbtree_insert_fixup(T,z); } void rbtree_insert_fixup(rbtree *T,rbtree_node *x){ }
true
3b6b70c8cb1d3e9f22df5560e41025025dfcda23
C++
fengjixuchui/QuickSearch
/QuickSearch/IndexManager.cpp
UTF-8
1,915
2.578125
3
[]
no_license
#include "IndexManager.h" #include "Lock.h" #include <Shlwapi.h> #include "FileNameMemoryManager.h" IndexManager *g_pIndexManager = new IndexManager(); IndexManager::IndexManager() { } IndexManager::~IndexManager() { } BOOL IndexManager::AddEntry(FileEntry fileEntry,int nVolIndex) { DeleteEntry(fileEntry.FileReferenceNumber, nVolIndex); m_VolFileIndex[nVolIndex].insert(fileEntry); return TRUE; } BOOL IndexManager::DeleteEntry(KEY FRN, int nVolIndex) { FileEntry_By_FRN& index = m_VolFileIndex[nVolIndex].get<0>(); FileEntry_By_FRN::iterator itr = index.find(FRN); if (itr != index.end()) { FileEntry tmpEntry = *itr; g_pMemoryManager->FreeFileEntry(tmpEntry.pFileName, nVolIndex); index.erase(itr); } return TRUE; } DWORD IndexManager::GetVolFileCnt(int nVolIndex) { return m_VolFileIndex[nVolIndex].size(); } BOOL IndexManager::isFindEntry(KEY FRN, int nVolIndex) { FileEntry_By_FRN& fileSet = m_VolFileIndex[nVolIndex].get<0>(); FileEntry_By_FRN::iterator itr = m_VolFileIndex[nVolIndex].find(FRN); if (fileSet.find(FRN) != fileSet.end()) { return TRUE; } return FALSE; } //FileEntry_Set & IndexManager::GetVolIndex(int nVolIndex) //{ // return m_VolFileIndex[nVolIndex]; //} void IndexManager::Save(std::wstring& strDbFilePath, int nVolIndex) { const FileEntry_Set& fs = m_VolFileIndex[nVolIndex]; std::ofstream ofs(strDbFilePath); boost::archive::text_oarchive oa(ofs); oa << fs; } void IndexManager::Load(std::wstring& strDbFilePath, int nVolIndex) { FileEntry_Set& fs = m_VolFileIndex[nVolIndex]; std::ifstream ifs(strDbFilePath); boost::archive::text_iarchive ia(ifs); ia >> fs; } void IndexManager::UnInit() { g_pMemoryManager->UnInit(); for (int i = 0; i < VOLUME_COUNT; ++i) { m_VolFileIndex[i].clear(); } delete g_pIndexManager; }
true
b192ec737868abfed8839e3955019ff4b8921dd8
C++
PhoenixDD/LeetCode
/1244-Design A Leaderboard.cpp
UTF-8
1,380
3.03125
3
[]
no_license
class Leaderboard { public: Leaderboard() { } void addScore(int playerId, int score) { if(!leaderBoard.count(playerId)) leaderBoard[playerId]=score,rLeaderBoard.insert(make_pair(score,playerId)); else { it=rLeaderBoard.find(leaderBoard[playerId]); while(it->second!=playerId) it++; rLeaderBoard.erase(it); rLeaderBoard.insert(make_pair(leaderBoard[playerId]+score,playerId)); leaderBoard[playerId]+=score; } } int top(int K) { int sum=0; for(it2=rLeaderBoard.rbegin();it2!=rLeaderBoard.rend()&&K;it2++,K--) sum+=it2->first; return sum; } void reset(int playerId) { it=rLeaderBoard.lower_bound(leaderBoard[playerId]); while(it!=rLeaderBoard.end()&&it->second!=playerId) it++; rLeaderBoard.erase(it); leaderBoard.erase(playerId); } private: multimap<int,int> rLeaderBoard; multimap<int,int>::iterator it; multimap<int,int>::reverse_iterator it2; unordered_map<int,int> leaderBoard; }; /** * Your Leaderboard object will be instantiated and called as such: * Leaderboard* obj = new Leaderboard(); * obj->addScore(playerId,score); * int param_2 = obj->top(K); * obj->reset(playerId); */
true
e10da0b903c6c7f73b0f52808f0c7b905170b35f
C++
Hartawan007/Data-Rumah-Sakit
/191110051_HartawanMartinOdnielSianturi.cpp
UTF-8
3,138
2.6875
3
[]
no_license
#include<stdio.h> #include<conio.h> int main() { struct Rumah_sakit { char nama[50]; char alamat[100]; int tggi[5], brt[5]; char golda[3]; char ayah[50]; char ibu[50]; }; printf ("+++++++++++++++++++++++++++++++++++++++++++++\n"); printf ("========Rumah Sakit Harta Jaya ==============\n"); printf ("++++++++++++++++++++++++++++++++++++++++++++++++\n\n"); Rumah_sakit pasien; printf("Masukkan Identitas Pasien di bawah ini : \n"); printf("\nNama : "); scanf("%s",pasien.nama); printf("Alamat : "); scanf("%s",pasien.alamat); printf("Golongan darah : "); scanf("%s",pasien.golda); printf("Tinggi Badan : "); scanf("%d",pasien.tggi); printf("Berat badan : "); scanf("%d",pasien.brt); printf("\n========================================\n"); printf(" Masukkan Nama Orang tua Pasien...\n"); printf("\nAyah : "); scanf("%s",pasien.ayah); printf("Ibu : "); scanf("%s",pasien.ibu); getch(); int kamar; FILE *frs; printf("\n\n"); printf("Anda Memasuki tahap selanjutnya...\n"); printf("\n>>Pemesanan Kamar\n"); printf("Anda ingin memesan kamar : \n"); printf("\n1. Kamar VVIP\n2. Kamar VIP\n3. General\n\n"); printf("Masukkan pilihan Anda : "); kamar = getch(); int total; int vvip=3, vip=2, gen=1; int hari; char setuju; switch (kamar) { case '1': printf("\nAnda telah memilih kamar VVIP\n"); printf("Harga sewa kamar Rp 3.000.000,00/hari\n"); printf("Apakah Anda setuju? (Y/N)\n"); setuju = getch(); switch (setuju) { case 'y': printf("\nBerapa hari hari Pasien dirawat : \n"); scanf("%d",&hari); total=hari*vvip; printf("\nTotal Biaya Yang Pasien Bayar : %d juta",total); (frs,"\nAnda telah memilih kamar VIP\nHarga sewa kamar Rp 3.000.000,00 /hari\nselama %d hari\ndengan biaya %d juta rupiah\n",hari,total); getch(); return 0; break; case 'n': printf("Mohon maaf anda tidak dapat menginap disini"); break; }; break; case '2': printf("\nAnda telah memilih kamar VIP\n"); printf("Harga sewa kamar Rp 2.000.000,00 /hari\n"); printf("Apakah Anda setuju? (Y/N)\n"); setuju = getch(); switch (setuju) { case 'y': printf("\nBerapa hari hari Pasien dirawat : \n"); scanf("%d",&hari); total=hari*vip; printf("\nTotal Biaya Yang Pasien Bayar : %d juta",total); printf("\nAnda telah memilih kamar VIP\nHarga sewa kamar Rp 2.000.000,00 /hari\nselama %d hari\ndengan biaya %d juta rupiah\n",hari,total); getch(); return (0); break; case 'n': printf("Mohon maaf anda tidak dapat menginap disini"); break; }; break; case '3': printf("\nAnda telah memilih kamar General\n"); printf("Harga sewa kamar Rp 1.000.000,00/hari\n"); printf("Apakah Anda setuju? (Y/N)\n"); setuju = getch(); switch (setuju) { case 'y': printf("\nBerapa hari Pasien dirawat : "); scanf("%d",&hari); total =hari*gen; printf("\nTotal Biaya Yang Pasien Bayar : %d juta",total); printf("\nAnda telah memilih kamar VIP\nHarga sewa kamar Rp 1.000.000,00 @hari\nselama %d hari\ndengan biaya %d juta rupiah\n",hari,total); getch(); return (0); break; case 'n': printf("Mohon maaf anda tidak dapat menginap disini"); break; }; break; }getch(); }
true
e58e3e514bc1a34fa4b7472df86dc9dc87175059
C++
zhudisheng/The-Cplusplus-programming-language
/difference/cplusplus.cpp
UTF-8
244
3.078125
3
[]
no_license
#include <stdio.h> struct Student { const char*name; int age; }; f(i) { printf("i = %d\n",i); } g() { return 5; } int main() { Student s1 = {"Delphi",30}; Student s2 = {"Tang",30}; f(10); printf("g()=%d\n",g(1,2,3,4,5)); return 0; }
true
495b698fe5c43854f2f07b2ae19a6192a8b8b9b6
C++
pineal/-O_O-
/Cache Design/Cache Design/LRU_Cache.cpp
UTF-8
1,178
3.140625
3
[]
no_license
// // LRU_Cache.cpp // Cache Design // // Created by Hesen Zhang on 2/3/17. // Copyright © 2017 Hesen Zhang. All rights reserved. // #include "LRU_Cache.hpp" LRU_Cache::LRU_Cache(int c) { set_capacity(c); cout << "LRU Cache Initialzied" << endl; }; int LRU_Cache ::get(int key) { if (_entries.find(key) == _entries.end()) { cout << "Error: key not found" << endl; return -1; } else { int v = _entries[key]->second; update(key, v); return v; } }; void LRU_Cache::put(int key, int value) { if (_list.size() == get_capacity() && _entries.find(key) == _entries.end()) { auto p = _list.back(); _list.pop_back(); _entries.erase(p.first); } this->update(key, value); }; void LRU_Cache::update(int key, int value) { //try to find the <key,iterator> entry found entries auto it = _entries.find(key); //if entry found if (it != _entries.end()) { //delete the current node in list _list.erase(it->second); } //update the position to the front of the list _list.emplace_front(key, value); //remap the entry _entries[key] = _list.begin(); }
true
291ad300a5a6eec44fb823e30a9241b3aa9a6e7d
C++
Ghiordy/Curso-Microcontroladores
/KeyPad_NoController_00.ino
UTF-8
2,275
3.0625
3
[ "MIT" ]
permissive
/* Keypad Interfacing with Arduino Without Keypad Library Author : Kunchala Anil It is implemented using a method called Column Searching */ #include <LiquidCrystal.h> const int rs = 8, en = 9, d4 = 4, d5 = 5, d6 = 6, d7 = 7; LiquidCrystal lcd(rs, en, d4, d5, d6, d7); int p=0; const int row_pin[] = {36, 34, 32, 30}; const int col_pin[] = {44, 42, 40, 38}; // defining row and column pins as integer arrays const int rows = 4, cols = 4; //defining the multi dimensional array size constants const char key[rows][cols] = { // defining characters //for keystrokes in Multidimensional Array {'D','#','0','*'}, {'C','9','8','7'}, {'B','6','5','4'}, {'A','3','2','1'} }; void setup(){ Serial.begin(9600); //begin the serial communication for(int i = 0; i<4; i++) { pinMode(row_pin[i],OUTPUT); //Configuring row_pins as Output Pins digitalWrite(row_pin[i],HIGH);//write HIGH to all row pins pinMode(col_pin[i],INPUT_PULLUP);//configure column pin as Input and activate internal //Pullup resistor }//end of for loop lcd.begin(16,2); lcd.clear(); }//end of setup void loop(){ char key = read_key(); if(key !='\n'){ Serial.println(key); delay(100); } if(p==16){ lcd.setCursor(0,1);} if(p==32){ lcd.setCursor(0,0); p=0;} lcd.blink(); if (key=='1' || key=='2' || key=='3' || key=='A' || key=='4' || key=='5' || key=='6' || key=='B' || key=='7' || key=='8' || key=='9' || key=='C' || key=='*' || key=='0' || key=='#' || key=='D'){ if( key=='*'){lcd.clear(); lcd.setCursor(0,0),p=0;} else{ lcd.print(key); p++;} } }//end of loop char read_key(){ delay(250); for(int row = 0;row < 4;row++) { digitalWrite(row_pin[0],HIGH); digitalWrite(row_pin[1],HIGH); digitalWrite(row_pin[2],HIGH); digitalWrite(row_pin[3],HIGH); digitalWrite(row_pin[row],LOW); //Serial.println(row_pin[row]); for(int col = 0;col<4;col++) { int col_state = digitalRead(col_pin[col]); if(col_state == LOW) { return key[row][col]; }//end of if }//end of col for loop }//end of row for loop return '\n'; }//end of read_key
true
3e83b8c970bb81ff03552314439d9c33b51e7d92
C++
derekzhang79/TopCoder
/153/items.cpp
UTF-8
604
3.265625
3
[]
no_license
#include <iostream> #include <vector> #include <string> using namespace std; string bestItem(vector<int> costs, vector<int> prices, vector<int> sales, vector<string> items){ int i,length = costs.size(); string retval = ""; int profits[length]; for(i =0 ;i<length;i++) profits[i] = sales[i]*(prices[i] - costs[i]); int max = 0,maxin = -1; for(i=0;i<length;i++){ if(profits[i] > max){ max = profits[i]; maxin = i; } } if(maxin != -1) retval = items[maxin]; return retval; } int main(){ vector<int> a,b,c; vector<string> d; cout<<bestItem(a,b,c,d)<<endl; return 0; }
true
949f06c9f4634fa4ac2503f0bdde28e9a87e6e85
C++
HotPot-J/exercises
/exercises_day89/exercises_day89/test.cpp
GB18030
4,194
3.515625
4
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 /* һţţΪһһУǷǵ ǵݼġţţһΪnAһǰAֳɶ Уţţ֪ٿ԰ΪС ţţ԰A1 2 3 2 2 1Ϊ1 2 3 2 2 1УҪ 2 ĵһΪһn1<=n<=10^5 ڶаn 1~10^9 : һʾţţԽAٻΪٶ */ //˼·ҵҵݼ/ݼҵ #include<iostream> #include<vector> using namespace std; void fun( vector<int> arr){ size_t res = 0, p = 0; size_t flag = 0;//ֵΪ߲ if (arr.size() <= 2){ //Сʱֻһ cout << 1 << endl; return; } while (p < arr.size() - 1){ if (arr[p] < arr[p + 1]){ // while (p<arr.size()-1&&arr[p] <= arr[p + 1]){ ++p; } ++res; flag = p; // ++p; } else if (arr[p] == arr[p + 1]){ ++p; } else { //ݼ while (p < arr.size() - 1 && arr[p] >= arr[p + 1]){ ++p; } ++res; flag = p;// ++p; } } if (flag != arr.size() - 1){ ++res; } cout << res; } //int main(){ // vector<int> arr; // int n = 0, tmp = 0; // cin >> n; // for (int i = 0; i < n; ++i){ // cin >> tmp; // arr.push_back(tmp); // } // fun(arr); // return 0; //} /* 2һַstrַstrеִ abcd1234ed125ss123456789 123456789 */ //˼·˫ָ룬ͬʱַ /*substr(pos, length):stringposλÿʼȡΪlengthַ*/ #include<iostream> #include<string> using namespace std; void fun1(string& str){ string res; int max = 0; int tmp = 0; size_t front = 0; size_t rear = 0; size_t tail = 0; while (rear < str.size()){ while (rear<str.size() && !isdigit(str[rear])){ // ++rear; } front = rear; while (rear < str.size() && isdigit(str[rear])){ //ҵöֵĩβλ ++tmp; ++rear; } if (tmp>max){ //ֶδڵǰִ ֵ̽ıҪ tail = rear - 1; //ֶεĩβ //ʱĿתΪѰַ ûڽ rear = front; tmp = 0; //¼ڳ while (rear <= tail){ if (str[rear + 1] - str[rear] == 1){ // ++tmp;//¼ǰڳ ++rear; } else{ // if (tmp>max){ res = str.substr(front, tmp+1); max = tmp; tmp = 0; } ++rear; front = rear; } } rear = tail + 1;//һֺ һ } } cout << res << endl; } //int main(){ // string str; // getline(cin, str); // fun1(str); // return 0; //} /* 3гִһ */ /* ˼·1ϣ ʱ临ӶO2n */ #include<iostream> #include<unordered_map> #include<vector> class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { unordered_map<int, int> map; int tmp = 0; for (int i = 0; i < numbers.size(); ++i){ tmp = ++map[numbers[i]]; if (tmp>numbers.size()/2){ return numbers[i]; } } return 0; } }; //˼·2Ѱ #include<iostream> #include<vector> #include<algorithm> //class Solution { //public: // int MoreThanHalfNum_Solution(vector<int> numbers) { // if ( numbers.empty()){ // return 0; // } // sort(numbers.begin(), numbers.end()); // int tmp = 1, i = 0, j = 1, res = 0; // while (j < numbers.size()){ // while (numbers[i] == numbers[j]){ // ++j; // ++tmp; // } // if (tmp>numbers.size() / 2){ // return numbers[i]; // } // tmp = 1; // i = j; // ++j; // } // return 0; // } //}; int main(){ Solution a; vector<int> arr = { 1, 2, 3, 2, 2, 2, 5, 4, 2 }; a.MoreThanHalfNum_Solution(arr); return 0; }
true
f4a54e993bc609c4ed8e0146b38ad822216869f3
C++
MisakiFx/C
/C-twice/4月23作业/平均值,最小值,最大值.cpp
UTF-8
532
3
3
[]
no_license
#include <stdio.h> int main() { int i; /**********FOUND**********/ float a[10],min,max,avg; printf("input 10 score:"); for(i=0;i<=9;i++) { printf("input a score of student:"); /**********FOUND**********/ scanf("%f",&a[i]); } max=min=avg=a[0]; for(i=1;i<=9;i++) { /**********FOUND**********/ if(min>a[i]) min=a[i]; if(max<a[i]) max=a[i]; avg=avg+a[i]; } avg=avg/10; printf("max:%f\nmin:%f\navg:%f\n",max,min,avg); }
true
c0cc57db56818dda65e9d0fc6493c4d49bc5771e
C++
surgura/AMQP-CPP
/tests/libboostasio.cpp
UTF-8
1,604
2.703125
3
[ "Apache-2.0" ]
permissive
/** * LibBoostAsio.cpp * * Test program to check AMQP functionality based on Boost's asio io_service. * * @author Gavin Smith <gavin.smith@coralbay.tv> * * Compile with g++ libboostasio.cpp -o boost_test -lpthread -lboost_system -lamqpcpp */ /** * Dependencies */ #include <boost/asio/io_service.hpp> #include <boost/asio/strand.hpp> #include <boost/asio/deadline_timer.hpp> #include <amqpcpp.h> #include <amqpcpp/libboostasio.h> /** * Main program * @return int */ int main() { // access to the boost asio handler // note: we suggest use of 2 threads - normally one is fin (we are simply demonstrating thread safety). boost::asio::io_service service(4); // create a work object to process our events. boost::asio::io_service::work work(service); // handler for libev AMQP::LibBoostAsioHandler handler(service); // make a connection AMQP::TcpConnection connection(&handler, AMQP::Address("amqp://guest:guest@localhost/")); // we need a channel too AMQP::TcpChannel channel(&connection); // create a temporary queue channel.declareQueue(AMQP::exclusive).onSuccess([&connection](const std::string &name, uint32_t messagecount, uint32_t consumercount) { // report the name of the temporary queue std::cout << "declared queue " << name << std::endl; // now we can close the connection connection.close(); }); // run the handler // a t the moment, one will need SIGINT to stop. In time, should add signal handling through boost API. return service.run(); }
true
07649ba9da597fb3768c47be45e96eee1d7d5813
C++
aleclouisgrant/sms-bingo
/Source/sms-bingo/ServerClient/BingoClient.cpp
UTF-8
3,340
2.6875
3
[]
no_license
#include "BingoClient.h" #include "BingoReceiver.h" #include <WS2tcpip.h> #include <string> #include <thread> #include <qdebug.h> #pragma comment(lib, "ws2_32.lib") #define BUFFER_SIZE 4096 /* * */ BingoClient::BingoClient(BingoReceiver *receiver) { m_receiver = receiver; qDebug() << "CLIENT: Ready"; std::thread scannerThread(&BingoClient::Start, this); scannerThread.detach(); } BingoClient::~BingoClient() { } /* * */ void BingoClient::Start() { if (Connect() != 0) { return; } if (GetSetupData() != 0) { return; } if (SendSetupData() != 0) { return; } Listen(); } /* * */ int BingoClient::Connect() { std::string ipAddress = "127.0.0.1"; // ip address of the server int port = m_receiver->GetPort(); // listening port on the server WSAData wsData; WORD ver = MAKEWORD(2, 2); int wsResult = WSAStartup(ver, &wsData); //initialize winsock if (wsResult != 0) { qDebug() << "CLIENT: Can't intialize WinSock"; return -1; } m_serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (m_serverSocket == INVALID_SOCKET) { qDebug() << "CLIENT: Error creating socket"; WSACleanup(); return -1; } sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons(port); inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr); int connectionResult = connect(m_serverSocket, (sockaddr *)&hint, sizeof(hint)); if (connectionResult == SOCKET_ERROR) { qDebug() << "CLIENT: Cannot connect to server"; closesocket(m_serverSocket); WSACleanup(); return -1; } qDebug() << "CLIENT: Connected to server"; return 0; } /* * */ int BingoClient::GetSetupData() { char buf[BUFFER_SIZE]; memset(buf, 0, BUFFER_SIZE); //clear buffer int bytesReceived = recv(m_serverSocket, buf, sizeof(buf), 0); if (bytesReceived == SOCKET_ERROR) { qDebug() << "CLIENT: Error receiving data from client"; return -1; } if (bytesReceived == 0) { //client disconnected return -1; } qDebug() << "CLIENT: Setup data received"; m_receiver->SetupDataReceived(buf); return 0; } /* * */ int BingoClient::SendSetupData() { if (m_serverSocket == INVALID_SOCKET) { qDebug() << "CLIENT: Socket not created yet"; return -1; } const char * data = "p2"; char buf[BUFFER_SIZE]; memcpy(&buf[0], data, sizeof(data)); qDebug() << "CLIENT: Sending: " << buf; send(m_serverSocket, buf, BUFFER_SIZE, 0); return 0; } /* * receiving loop for the button id's in game */ void BingoClient::Listen() { char buf[BUFFER_SIZE]; while (true) { memset(buf, 0, BUFFER_SIZE); //clear buffer int bytesReceived = recv(m_serverSocket, buf, sizeof(buf), 0); if (bytesReceived == SOCKET_ERROR) { qDebug() << "CLIENT: Error receiving data from client"; break; } if (bytesReceived == 0) { //client disconnected break; } int id; sscanf(buf, "%d", &id); m_receiver->DataReceived(id); qDebug() << "CLIENT: Received data: " << buf; } closesocket(m_serverSocket); WSACleanup(); } /* * */ void BingoClient::Send(int buttonId) { if (m_serverSocket == INVALID_SOCKET) { qDebug() << "CLIENT: Socket not created yet"; return; } char buf[BUFFER_SIZE]; sprintf(buf, "%ld", buttonId); qDebug() << "CLIENT: Sending: " << buf; send(m_serverSocket, buf, BUFFER_SIZE, 0); } /* * */ void BingoClient::Disconnect() { closesocket(m_serverSocket); WSACleanup(); }
true
6f20b0206366bd084b11466b12f90b28fda7a915
C++
ormalkai/AdvancedProgramming
/PlayerStatistics.h
UTF-8
1,424
2.953125
3
[]
no_license
#pragma once #include "BattleshipAlgoSmart.h" using namespace std; /** *@Details Class for managing tournament results table */ class PlayerStatistics { private: int m_playerIndex; string m_playerName; int m_gamesPlayed; int m_wins; int m_losses; int m_ties; int m_ptsFor; int m_ptsAgainst; public: PlayerStatistics(int index, string name) : m_playerIndex(index), m_playerName(name), m_gamesPlayed(0), m_wins(0), m_losses(0), m_ties(0), m_ptsFor(0), m_ptsAgainst(0) { } PlayerStatistics(const PlayerStatistics&) = default; PlayerStatistics(PlayerStatistics&&) = default; PlayerStatistics& operator=(const PlayerStatistics &) = default; ~PlayerStatistics() = default; /** * @Details Update player result for game */ void update(const pair<int, int> score, WinLoseTie result); /** * @Details Get number of wins for player */ int getWins() const { return m_wins; } /** * @Details Get number of losses for player */ int getLosses() const { return m_losses; } /** * @Details Get number of points for player */ int getPointsFor() const { return m_ptsFor; } /** * @Details Get number of points against player */ int getPointsAgainst() const { return m_ptsAgainst; } /** * @Details Get player name for printing */ string getPlayerName() const { return m_playerName; } /** * @Details Get player index */ int getPlayerIndex() const { return m_playerIndex; } };
true
12c151f089d218dc5cb5ef3c0bfb2fc9a202dcd2
C++
hendrikdevestel/arduino-bomb
/bomb-with-keypad/bomb-with-keypad.ino
UTF-8
4,660
3.015625
3
[]
no_license
#include <Wire.h> #include <LiquidCrystal_I2C.h> #include <Keypad.h> int buzzerPin = 10; const byte ledPin = 13; //using the built in LED /* KEYPAD: */ const byte numRows= 4; const byte numCols= 4; char keymap[numRows][numCols]= { {'1', '2', '3', 'A'},{'4', '5', '6', 'B'},{'7', '8', '9', 'C'},{'*', '0', '#', 'D'} }; byte rowPins[numRows] = {9,8,7,6}; //Rows 0 to 3 byte colPins[numCols]= {5,4,3,2}; //Columns 0 to 3 /* Application variables: */ String code = "2305"; //The code to defuse the bomb int maxSec = 1000; // Time to defuse the bomb String inseredCode = ""; bool EXPLODED = false; bool DEFUSED = false; unsigned long period = 10000; //Amount of milliseconds between the buzzers bool canEnterCode = false; // Whether the code can be entered (after pressing *) int keyIndex = 12; //Where the code will be insered on the display /* TIMERS */ unsigned long startMillis; //global start time of the program unsigned long startMillisForBuzzer; //Start timer for buzzer unsigned long startMillisForBlinking; //Start timer for buzzer bool showResult= true; int totalSec = 0; // Ellapsed time since start unsigned long currentMillis; LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols); void setup() { lcd.init(); lcd.backlight(); startMillisForBuzzer = millis(); startMillis = millis(); } void loop() { if(EXPLODED || DEFUSED){ if(EXPLODED){ checkBuzzer(1000); } return; } timer(); //Continue timer char keypressed = myKeypad.getKey(); if (keypressed != NO_KEY) { if(canEnterCode){ // If the code can be entered inseredCode = String(inseredCode + keypressed); if(inseredCode == code){ defuse(); } else{ if(inseredCode.length() <= 3){ tone(buzzerPin, 500, 100); lcd.setCursor(keyIndex,1); lcd.print(keypressed); keyIndex++; } else{ explode(); } } } else{ if(keypressed == '*'){ tone(buzzerPin, 500, 100); inseredCode = ""; writeLine(1,0, "Enter code: ____"); canEnterCode = true; } } } } void checkBuzzer(int duration){ currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started) if (currentMillis - startMillisForBuzzer >= period) //check whether the period has elapsed { //tone(buzzerPin, 800, duration); //if so, buzzer to the player startMillisForBuzzer = currentMillis; //save the current time to the starttime for the buzzer } } void timer(){ currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started) int ellapsedSeconds = (currentMillis - startMillis) / 1000; //get total seconds since start if(ellapsedSeconds > maxSec){ explode(); } else{ if(ellapsedSeconds > totalSec){ totalSec = ellapsedSeconds; writeLine(0,4,getCountdown(totalSec)); } } } String getCountdown(int ellapsedSeconds){ int secToGo = maxSec - ellapsedSeconds; int timerSec = secToGo % 60; int timerMin = secToGo / 60; int timerHour = secToGo / (60*60); String sTimerMin = String(timerMin); if(timerMin < 10){ sTimerMin = String("0" + sTimerMin); } String sTimerSec = String(timerSec); if(timerSec < 10){ sTimerSec = String("0" + sTimerSec); } String sTimerHour = String(timerHour); if(timerHour < 10){ sTimerHour = String("0" + sTimerHour); } return String(sTimerHour + ":" + sTimerMin + ":" + sTimerSec); } void explode(){ EXPLODED = true; writeCurrentTime(); writeLine(1,1,"BOMB EXPLODED"); period = 2000; } void defuse(){ DEFUSED = true; writeCurrentTime(); writeLine(1,2, "BOMB DEFUSED"); } void writeCurrentTime(){ currentMillis = millis(); //get the current "time" (actually the number of milliseconds since the program started) int total = (currentMillis - startMillis) / 1000; writeLine(0,4,getCountdown(totalSec)); } void writeLine(int line, int column, String text){ clearLine(line); lcd.setCursor(column, line); lcd.print(text); } void clearLine(int line){ lcd.setCursor(0,line); lcd.print(" "); } void checkBlinking(){ int blinkPeriod = 1000; currentMillis = millis(); if(currentMillis - startMillisForBlinking >= blinkPeriod){ if(showResult){ writeLine(1,1, "BOMB EXPLODED"); showResult = false; } else{ clearLine(1); showResult = true; } startMillisForBlinking = currentMillis; } }
true
12acb9c3b887d976a835ed5a97b235a06ae24a11
C++
SilenceWang123/test
/adsa.cpp
UTF-8
756
2.75
3
[]
no_license
#include<cstdio> #include<cstring> using namespace std; const int direction[4][2]={{-1,0},{0,-1},{0,1},{1,0}}; char map[100][101]; int row; int col; int bfs(int r,int c) { int counter=0; if('p'==map[r][c]) ++counter; map[r][c]='#'; for(int d=0;d<4;++d) { int dr=r+direction[d][0]; int dc=c+direction[d][1]; if(dr>=0 && dr<row && dc>=0 && dc < col && map[dr][dc] != '#') { counter += bfs(dr,dc); } } return counter; } int main() { while(scanf("%d%d",&row,&col),row!=0 && col!=0) { for(int i=0;i<row;++i) { scanf("%s",map[i]); } int counter=0; for(int i=0;i<row;++i) { for(int k=0; k<col; ++k) { if(map[i][k]=='d') { counter += bfs(i,k); } } } printf("%d\n",counter); } return 0; }
true
4bdfc516bfe987633a7a11c242d6d2a33d3329e6
C++
denis-gubar/Leetcode
/Array/1584. Min Cost to Connect All Points.cpp
UTF-8
1,258
2.609375
3
[]
no_license
class Solution { public: struct UnionFind { vector<int> id; vector<int> sz; UnionFind(int N) : id(vector<int>(N)), sz(vector<int>(N, 1)) { for (int i = 0; i < N; ++i) id[i] = i; } int root(int i) { while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; } bool find(int p, int q) { return root(p) == root(q); } void unite(int p, int q) { int i = root(p); int j = root(q); if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } } void checkedUnite(int p, int q) { if (!find(p, q)) unite(p, q); } }; int minCostConnectPoints(vector<vector<int>>& points) { int result = 0; int N = points.size(); UnionFind uf(N); vector<long long> A; A.reserve(500'000); for (int i = 0; i < N; ++i) for (int j = i + 1; j < N; ++j) A.push_back((abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])) * 1'000'000LL + i * 1'000LL + j); sort(A.begin(), A.end()); int K = 1; for (int i = 0; i < A.size() && K < N; ++i) { int V = A[i] % 1000; int U = A[i] / 1000 % 1000; if (!uf.find(U, V)) { uf.unite(U, V); result += A[i] / 1'000'000; ++K; } } return result; } };
true
335a564126f0a4d784701c5166f90c24290ecc07
C++
runforu/Miscellaneous
/AsynTask.cpp
UTF-8
14,314
3.03125
3
[]
no_license
#include <atomic> #include <functional> #include <iostream> #include <list> #include <mutex> #include <queue> #include <random> #include <thread> #include "Common.h" namespace Utils { /* Examples: { AsyncTaskHelper ath; ath.AddTask([&ath](){ // do something. ath.AddTask([](){ //do something. }); }); ath.AddTask(std::bind(...)); ath.WaitForComplete(); // WaitForComplete can be called many times. } // Blocked here by WaitForComplete in dtor. */ class AsyncTask { private: using Task = std::function<void()>; using Lock = std::unique_lock<std::mutex>; public: /// \brief Constructor, /// Parameters: /// maxthread: the number of threads in the threadpool, default value of the number of processors is not optimal. AsyncTask(size_t maxthread = std::thread::hardware_concurrency()) noexcept; ~AsyncTask(); inline size_t MaxConcurrency() { return m_Threads.size(); } inline explicit operator bool() { return !m_StopRunning; } /// \brief Add new task to queue. Can called from Task. void AddTask(Task&& task); /// \brief Shut down task queue. Can called from any thread. /// Parameters: /// force: true, forbid adding new task and clear pending tasks, waiting for running task. /// false, forbid adding new task and waiting for running task and pending task. void Shutdown(bool force = false); /// \brief Idempotent. Wait for the task queue complete, make sure add at least one task before waiting, otherwise, it /// return immediately. Do not call it in child thread's context, that is, do not call it in the Task. void WaitForComplete(); private: // Each thread runs this loop. void Loop(); AsyncTask(const AsyncTask& self) = delete; AsyncTask(AsyncTask&& self) = delete; AsyncTask& operator=(const AsyncTask& self) = delete; AsyncTask& operator=(AsyncTask&& self) = delete; private: std::condition_variable m_Condition; std::mutex m_Mutex; std::vector<std::thread> m_Threads; // All the following members are protected by Lock. bool m_StopRunning; int m_RunningTasks; std::list<Task> m_TaskQueue; }; AsyncTask::AsyncTask(size_t maxthread /*= std::thread::hardware_concurrency()*/) noexcept : m_StopRunning(false), m_RunningTasks(0) { try { m_Threads.reserve(maxthread); for (decltype(maxthread) i = 0; i < maxthread; ++i) { m_Threads.emplace_back(&AsyncTask::Loop, this); } std::this_thread::sleep_for(std::chrono::seconds(1)); } catch (...) { m_StopRunning = true; } } AsyncTask::~AsyncTask() { WaitForComplete(); } void AsyncTask::AddTask(Task&& task) { Lock lock(m_Mutex); if (!m_StopRunning) { m_TaskQueue.emplace_back(task); } lock.unlock(); m_Condition.notify_all(); } void AsyncTask::Shutdown(bool force) { Lock lock(m_Mutex); m_StopRunning = true; if (force) { // Clear pending task. m_TaskQueue.clear(); } // Notify all including WaitForComplete. lock.unlock(); m_Condition.notify_all(); } void AsyncTask::Loop() { while (true) { try { Task job; { Lock lock(m_Mutex); m_Condition.wait(lock, [this] { return !m_TaskQueue.empty() || m_StopRunning; }); if (m_StopRunning && m_TaskQueue.empty()) { break; } if (!m_TaskQueue.empty()) { job = std::move(m_TaskQueue.front()); m_TaskQueue.pop_front(); ++m_RunningTasks; } } if (job) { job(); } { Lock lock(m_Mutex); --m_RunningTasks; if (m_TaskQueue.empty() && m_RunningTasks == 0) { m_StopRunning = true; lock.unlock(); // No pending tasks and running tasks. m_Condition.notify_all(); } } } catch (...) { } } } void AsyncTask::WaitForComplete() { { Lock lock(m_Mutex); m_Condition.wait(lock, [this] { return m_TaskQueue.empty() && m_RunningTasks == 0; }); } // Notify threads to exit by set m_StopRunning with true if no task is added to the pool ^_^. m_StopRunning = true; // Invoke all waiting thread to exit loop. m_Condition.notify_all(); for (std::thread& thread : m_Threads) { if (thread.joinable()) { thread.join(); } } } } // namespace Utils namespace AsynTask_T { using namespace Utils; void Run(std::atomic_int& value) { std::default_random_engine engine( static_cast<unsigned int>(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count())); int random = engine(); value += random; std::this_thread::sleep_for(std::chrono::milliseconds(random % 100)); value -= random; } struct Functor { Functor(std::atomic_int& value) : m_value(value) { } Functor(const Functor& f) : m_value(f.m_value) { } void operator()() { Run(m_value); } void operator()(std::atomic_int& value) { Run(value); } void Method() { Run(m_value); } void Method(std::atomic_int& value) { Run(value); } private: std::atomic_int& m_value; }; void NormalFunc(std::atomic_int& value) { Run(value); } static std::atomic_int g_value = 0; void Function() { Run(g_value); } // case: Idempotent void TCase0() { auto start = std::chrono::system_clock::now(); auto sleep_time = 10000; { Utils::AsyncTask at; at.AddTask([sleep_time]() { Function(); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time)); Run(g_value); }); at.WaitForComplete(); at.WaitForComplete(); at.WaitForComplete(); at.WaitForComplete(); } assert(g_value.load() == 0); auto elapse = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count(); assert(elapse >= sleep_time); } // case: functor void TCase1() { std::atomic_int value = 0; { Utils::AsyncTask at; at.AddTask(Functor{value}); } assert(value.load() == 0); } // case: normal function void TCase2() { { Utils::AsyncTask at; at.AddTask(Function); } assert(g_value.load() == 0); } // case: std::bind (deprecated since C++ 17, to be removed) void TCase3() { std::atomic_int value = 0; { Utils::AsyncTask at; at.AddTask(std::bind(NormalFunc, std::ref(value))); Functor functor{value}; at.AddTask(std::bind(static_cast<void (Functor::*)()>(&Functor::operator()), &functor)); at.AddTask(std::bind(static_cast<void (Functor::*)()>(&Functor::Method), &functor)); at.AddTask(std::bind(static_cast<void (Functor::*)(std::atomic_int&)>(&Functor::operator()), &functor, std::ref(value))); at.AddTask(std::bind(static_cast<void (Functor::*)(std::atomic_int&)>(&Functor::Method), &functor, std::ref(value))); } assert(value.load() == 0); } // case: lambda void TCase4() { std::atomic_int value = 0; { Utils::AsyncTask at; at.AddTask([&value]() { Functor functor{value}; functor.operator()(value); }); } assert(value.load() == 0); } // case: functionality (a little intricate) void TCase6() { std::atomic_int value = 0; { auto test_task = [](Utils::AsyncTask& at, std::atomic_int& value, int times) { static auto worker = [](std::atomic_int& value) { Functor functor{value}; functor(); functor.operator()(value); functor.Method(); functor.Method(value); NormalFunc(value); Function(); }; static auto lambda0 = [&at, &value, times]() { at.AddTask([&at, &value, times]() { worker(value); }); }; static auto lambda1 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda0); } worker(value); }; static auto lambda2 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda1); } worker(value); }; static auto lambda3 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda2); } worker(value); }; static auto lambda4 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda3); } worker(value); }; static auto lambda5 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda4); } worker(value); }; static auto lambda6 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda5); } worker(value); }; static auto lambda7 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda6); } worker(value); }; static auto lambda8 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda7); } worker(value); }; static auto lambda9 = [&at, &value, times]() { worker(value); int tmp = times; while (tmp-- > 0) { at.AddTask(lambda8); } worker(value); }; lambda9(); }; Utils::AsyncTask at; at.AddTask([&test_task, &at, &value]() { test_task(at, value, 2); }); } assert(value.load() == 0); assert(g_value.load() == 0); } // case: functionality (a little intricate) void TCase7() { std::atomic_int value = 0; { auto test_task = [](Utils::AsyncTask& at, std::atomic_int& value, int times) { static auto worker = [](std::atomic_int& value) { Functor functor{value}; functor(); functor.operator()(value); functor.Method(); functor.Method(value); NormalFunc(value); Function(); }; static auto lambda0 = [&at, &value, times]() { at.AddTask([&at, &value, times]() { worker(value); }); }; #define DEF_LAMBDA(at, value, times, num, prev) \ static auto lambda##num = [&at, &value, times]() { \ worker(value); \ int tmp = times; \ while (tmp-- > 0) { \ at.AddTask(lambda##prev); \ } \ worker(value); \ }; DEF_LAMBDA(at, value, times, 1, 0); DEF_LAMBDA(at, value, times, 2, 1); DEF_LAMBDA(at, value, times, 3, 2); DEF_LAMBDA(at, value, times, 4, 3); DEF_LAMBDA(at, value, times, 5, 4); DEF_LAMBDA(at, value, times, 6, 5); DEF_LAMBDA(at, value, times, 7, 6); DEF_LAMBDA(at, value, times, 8, 7); DEF_LAMBDA(at, value, times, 9, 8); lambda9(); }; Utils::AsyncTask at; at.AddTask([&test_task, &at, &value]() { test_task(at, value, 2); }); } assert(value.load() == 0); assert(g_value.load() == 0); } // case: Performance #pragma warning(disable : 4996 4244) void TCase8() { auto lambda = [](int times, int loop) { constexpr int PI_LEN = 1024; char* result_pi = new char[times * PI_LEN]{}; { auto calculate_pi = [](char* pi) { int a = 1e4, c = 3e3, b = c, d = 0, e = 0, f[3000], g = 1, h = 0; do { if (!--b) { sprintf(pi, "%04d", e + d / a), e = d % a, h = b = c -= 15; pi += 4; } else { f[b] = (d = d / g * b + a * (h ? f[b] : 2e3)) % (g = b * 2 - 1); } } while (b); }; Utils::AsyncTask at; for (auto i = 0; i < times; ++i) { at.AddTask([&calculate_pi, buf{result_pi + i * PI_LEN}, loop]() { for (auto i = 0; i < loop; i++) { calculate_pi(buf); } }); } } for (auto i = 1; i < times; ++i) { assert(memcmp(result_pi, result_pi + i * PI_LEN, PI_LEN) == 0); } delete result_pi; }; constexpr int LOOP = 2048; for (auto i = 0; i < 32; ++i) { auto start = std::chrono::system_clock::now(); lambda(i, LOOP); auto elapse = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count(); std::cout << "Run " << i << " * " << LOOP << " tiems of PI computing takes: " << elapse << std::endl; } } } // namespace AsynTask_T void AsynTask_Test() { UT_Case_ALL(AsynTask_T); }
true
e1ab17464f9444746de98bf31c3d775d117e2006
C++
alexkorep/ProgrammingProblems
/ByteIsle/ByteIsleTest/ByteIsleTest.cpp
UTF-8
2,921
2.984375
3
[]
no_license
#include "tinytest.h" #include "../ByteIsle.h" struct RemoverTester { static int testFindFirstInterval() { IntervalRemover remover; remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.findFirstIntervalToTheRight(2) == 3); TINYTEST_ASSERT(remover.findFirstIntervalToTheRight(3) == 3); TINYTEST_ASSERT(remover.findFirstIntervalToTheRight(4) == 3); TINYTEST_ASSERT(remover.findFirstIntervalToTheRight(5) == 6); TINYTEST_ASSERT(remover.findFirstIntervalToTheRight(6) == 6); TINYTEST_ASSERT(remover.findFirstIntervalToTheRight(7) == -1); return 1; } static int testFindLastInterval() { IntervalRemover remover; remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.findFistIntervalToTheLeft(2) == -1); TINYTEST_ASSERT(remover.findFistIntervalToTheLeft(3) == 4); TINYTEST_ASSERT(remover.findFistIntervalToTheLeft(4) == 4); TINYTEST_ASSERT(remover.findFistIntervalToTheLeft(5) == 4); TINYTEST_ASSERT(remover.findFistIntervalToTheLeft(6) == 6); TINYTEST_ASSERT(remover.findFistIntervalToTheLeft(7) == 6); return 1; } static int testGetNumberOfPoints() { IntervalRemover remover; remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.getNumberOfPoinst(remover.begins.find(3), remover.begins.find(6)) == 2); TINYTEST_ASSERT(remover.getNumberOfPoinst(remover.begins.find(6), remover.begins.end()) == 1); TINYTEST_ASSERT(remover.getNumberOfPoinst(remover.begins.find(3), remover.begins.end()) == 3); return 1; } static int testIntervalRemoving() { IntervalRemover remover; remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.removeIntervals(5, 9, 2) == 1); // 1 point removed TINYTEST_ASSERT(remover.size() == 1); TINYTEST_ASSERT(remover.getInterval(3) == 4); remover.clear(); remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.removeIntervals(4, 9, 2) == 2); // 1 point removed TINYTEST_ASSERT(remover.size() == 1); TINYTEST_ASSERT(remover.getInterval(3) == 3); remover.clear(); remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.removeIntervals(4, 9, 1) == 0); TINYTEST_ASSERT(remover.size() == 2); TINYTEST_ASSERT(remover.getInterval(3) == 4); TINYTEST_ASSERT(remover.getInterval(6) == 6); remover.clear(); remover.add(3, 4); remover.add(6, 6); TINYTEST_ASSERT(remover.removeIntervals(1, 10, 5) == 3); TINYTEST_ASSERT(remover.size() == 0); remover.clear(); TINYTEST_ASSERT(remover.removeIntervals(1, 10, 5) == 0); TINYTEST_ASSERT(remover.size() == 0); return 1; } }; int Test1() { if (!RemoverTester::testFindFirstInterval()) return 0; if (!RemoverTester::testFindLastInterval()) return 0; if (!RemoverTester::testGetNumberOfPoints()) return 0; if (!RemoverTester::testIntervalRemoving()) return 0; return 1; } TINYTEST_START_SUITE(SimpleSuite); TINYTEST_ADD_TEST(Test1); TINYTEST_END_SUITE(); TINYTEST_MAIN_SINGLE_SUITE(SimpleSuite);
true
ab4ede0f1958905ca9c03634ede61789a00b43e9
C++
Aaronyoungjs/AutoCar
/Linux/src/motor/motor.h
UTF-8
1,146
2.65625
3
[]
no_license
#pragma once #include "config.h" #include "base.h" class Motor: public Base, Device { public: // enum Mode { ONE_STEP, TWO_STEP }; // Motor(int pin, int speed = 0, Mode mode = ONE_STEP, int range = 255); explicit Motor(const Motor &) = delete; Motor &operator=(const Motor &) = delete; Motor(int speed, int range = 255); void setPin(int left = MOTOR_LEFT_PIN, int right = MOTOR_RIGHT_PIN, int INT0 = MOTOR_INT0_PIN, int INT1 = MOTOR_INT1_PIN, int INT2 = MOTOR_INT2_PIN, int INT3 = MOTOR_INT3_PIN); // void setMode(Mode mode) { proMode = mode; }; virtual void setLeftSpeed(int speed); virtual void setRightSpeed(int speed); virtual void brake(void) {} ~Motor(); // Mode getMode(void) { return proMode; }; private: int proLeftPin; int proRightPin; int proINT0; int proINT1; int proINT2; int proINT3; int proLeftSpeed; int proRightSpeed; int proRange; // int proDelay; // Mode proMode; };
true
6169886e2a6e25710829ec2ae8584de9957e3e57
C++
taominfang/xdata2
/src/UnitFunctionsTestCases.h
UTF-8
1,555
2.65625
3
[]
no_license
/* * UnitFunctionsTestCases.h * * Created on: 2016��4��9�� * Author: minfang */ #ifndef UNITFUNCTIONSTESTCASES_H_ #define UNITFUNCTIONSTESTCASES_H_ #include "UnitTestBase.h" #include "RegAwk.h" #include "VariablePatternParser.h" class TestRegexSplit: public UnitTestBase { public: virtual bool test() { RegAwk t; boost::regex exp("[sc]"); vector<string> re; string test("s"); areEqual(0, t.regexSplit(exp, test, re), "'s' split by 's':"); re.clear(); test = " s"; areEqual(1, t.regexSplit(exp, test, re), "' s' split by 's':"); if (re.size() > 0) areEqual(" ", re[0], "' s' split by 's', the first element:"); test = "asca"; areEqual(3, t.regexSplit(exp, test, re), "' s' split by 's':"); if (re.size() > 2) areEqual("", re[2], "' s' split by 's', the second element:"); return error_messages.size() == 0; } }; class TestStringVariableParser: public UnitTestBase { public: virtual bool test() { const char * s = "a${b}${1}${2}${c}\\$c"; map<string, string> vm; vm["b"] = "bb"; vm["2"] = "22"; vector<string> rs; rs.push_back("000"); rs.push_back("1111"); VariableProcessor rr; std::ostringstream errorMessage; int size = VariablePatternParser::parse(s, rr, errorMessage); if (size <= 0) { cerr << errorMessage.str() << endl; return false; } std::ostringstream result; rr.contruct(&rs, &vm,true, result); if(result.str()==string("abb111122${c}$c")){ return true; } else{ return false; } } }; #endif /* UNITFUNCTIONSTESTCASES_H_ */
true
5363211a57f6e6aaa2184464fd7f4fe86cc82824
C++
wcary2/lab3
/Source.cpp
UTF-8
4,503
3.46875
3
[]
no_license
#include <iostream> #include <string> using namespace std; bool sumShort(); bool factorialTest(); bool sumLong(); bool factorialTestDouble(); bool strangeBehavior(); bool strangeBehaviorDouble(); bool puzzle(); bool puzzleDouble(); int main() { string option = ""; while (option != "close") { cout << endl << "sumshort" << endl << "sumlong" << endl << "factorial" << endl << "factorialdouble" << endl << "strange" << endl << "strangedouble" << endl << "puzzle" << endl << "puzzledouble" << endl << "Enter the command you wish to call: "; cin >> option; if (option == "sumshort") { bool overflowShort = sumShort(); } if (option == "sumlong") { bool overflowLong = sumLong(); } if (option == "factorial") { bool overflowFactorial = factorialTest(); } if (option == "factorialdouble") { bool overflowFactorial = factorialTestDouble(); } if (option == "strange") { bool overflowStrange = strangeBehavior(); } if (option == "strangedouble") { bool overflowStrangeDouble = strangeBehaviorDouble(); } if (option == "puzzle") { bool puzzlebool = puzzle(); } if (option == "puzzledouble") { bool puzzledoublebool = puzzleDouble(); } } return 0; } bool sumShort() { int n; cout << "Enter value of n: "; cin >> n; short sumShort = 0; for (int i = 1; i <= n; i++) { if (SHRT_MAX < sumShort + i) { cout << endl; cout << "An overflow was detected: the operation was stopped." << endl; cout << "last value of sumShort: " << sumShort << endl; cout << "last value of n before overflow: " << i - 1 << endl << endl; cout << "Value of n that caused overflow: " << i << endl << endl; return false; } sumShort += i; } cout << "sumShort = " << sumShort << endl; return true; } bool sumLong() { long n; cout << "Enter value of n: "; cin >> n; long sumLong = 0; for (long i = 1; i <= n; i++) { if (sumLong > 0 && i > 0 && sumLong + i < 0) { cout << endl << "An overflow was detected: the operation was stopped" << endl; cout << "last value of sumLong: " << sumLong << endl; cout << "last value of n before overflow: " << i - 1 << endl << endl; cout << "Value of n that caused overflow: " << i << endl << endl; return false; } sumLong += i; } cout << endl <<"sumShort = " << sumLong << endl; return true; } bool factorialTest() { long n; cout << "Enter value of n: "; cin >> n; float testNumber = 1; for (long i = 1; i <= n; i++) { if (testNumber * i == INFINITY) { cout << endl <<"An overflow was detectedL the operation was stopped" << endl; cout << "last value of the factorial was: " << testNumber << endl; cout << "last value of n before overflow: " << i - 1 << endl; cout << "value of n that caused the overflow: " << i << endl << endl; return false; } testNumber *= i; } cout << "factorial product: " << testNumber << endl; return true; } bool factorialTestDouble() { long n; cout << "Enter value of n: "; cin >> n; double testNumber = 1; for (long i = 1; i <= n; i++) { if (testNumber * i == INFINITY) { cout << endl << "An overflow was detectedL the operation was stopped" << endl; cout << "last value of the factorial was: " << testNumber << endl; cout << "last value of n before overflow: " << i - 1 << endl << endl; cout << "value of n that caused the overflow: " << i << endl << endl; return false; } testNumber *= i; } cout << "factorial product: " << testNumber << endl; return true; } bool strangeBehavior() { double n; cout << "Enter value of n: "; cin >> n; float ratio = 1.0 / n; float sum = 0; for (float i = 1.0; i <= n; i++) { sum += ratio; } cout << "value of the ratio is: " << ratio << endl; cout << "the sum of the ratio " << n << " times is: " << sum << endl; return 0; } bool strangeBehaviorDouble() { double n; cout << "Enter value of n: "; cin >> n; double ratio = (1.0/ n); double sum = 0; for (double i = 1.0; i <= n; i++) { sum += ratio; } cout << "value of the ratio is: " << ratio << endl; cout << "the sum of the ratio" << n << " times is: " << sum << endl; return true; } bool puzzle() { for (float i = 3.4; i < 4.4; i += 0.2) { cout << "i = " << i << endl; } return true; } bool puzzleDouble() { for (double i = 3.4; i < 4.4; i += 0.2) { cout << "i = " << i << endl; } return true; }
true
4ae4febc32017ac9a427016c8a2bb015b127082c
C++
1998factorial/Codeforces
/contests/educationalRound75/D.cpp
UTF-8
1,209
2.609375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; typedef long long ll; typedef pair<int , int> ii; const int maxn = 2e5 + 10; int N; ll S; ii p[maxn]; bool check(ll x){ //cout << "checking " << x << endl; ll ret = 0; vector<int> ps; int cnt = 0; for(int i = 1; i <= N; ++i){ if(p[i].second < x){ ret += p[i].first; } else if(p[i].first >= x){ ret += p[i].first; ++cnt; } else{ ps.push_back(p[i].first); } } //cout << cnt << " " << ps.size() << endl; if(cnt + ps.size() < N / 2 + 1)return false; for(int i = ps.size() - 1 , j = 0; i >= 0; --i , ++j){ if(j < N / 2 + 1 - cnt){ ret += x; } else{ ret += ps[i]; } } return ret <= S; } int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for(int t = 1; t <= T; ++t){ cin >> N >> S; for(int i = 1; i <= N; ++i){ cin >> p[i].first >> p[i].second; } sort(p + 1 , p + 1 + N); ll l = 0 , r = S , best = -1; while(l <= r){ ll mid = (l + r) >> 1; if(check(mid)) best = mid , l = mid + 1; else r = mid - 1; } cout << best << endl; } }
true
00ec88da504d8d4dc00fe03312cb834913b9d30e
C++
gitank007/Company-Wise-Coding-Questions
/Amazon/is_sudoku_valid.cpp
UTF-8
1,035
2.84375
3
[]
no_license
/* @Author - Jatin Goel @Institute - IIIT Allahabad Hardwork definitely pays off. There is no substitute of hardwork. There is no shortcut to success. */ #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { int board[9][9]; for(int i=0;i<9;i++) { for(int j=0;j<9;j++) { cin >> board[i][j]; } } int row[9][10]={0},column[9][10]={0},box[9][10]={0}; int flag = 1; for(int i = 0; i < 9 && flag; ++ i) { for(int j = 0; j < 9 && flag; ++ j) { if(board[i][j] != 0) { int num = board[i][j] ; int k = i / 3 * 3 + j / 3; if(row[i][num] || column[j][num] || box[k][num]) flag = 0; row[i][num] = column[j][num] = box[k][num] = 1; } } } cout << flag << endl; } return 0; }
true
48b7ca4b073659e7e67f6c20cf2d84d58ca25db3
C++
Jzjerry/Cpp-for-College
/19-5-20/Problem_23.cpp
UTF-8
354
3.171875
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; int f(char *c,int length) { int i=0; int count=0; for(i=0;i<length;i++) { if(c[i]>='0'&&c[i]<='9') { count++; } } return count; } int main() { char s[100]; int j; for(j=0;j<=99;j++) { s[j]=234*cos(j*0.6); } cout<<f(s,100)<<endl; return 0; }
true
dbe07e031276e6e70840e6aae855349913f69ca4
C++
Akigeor/Y-Fast-Trie
/splay_test.cpp
GB18030
3,929
3.0625
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <map> #include <iostream> #include <string> #include "splay.hpp" using namespace std; int main() { ////////// ʹ auto t = new sjtu::Splay<int, string>(); ////////// Insert t -> insert(233, "abc"); t -> insert(666, "efg"); t -> insert(450, "hij"); t -> insert(-1, "***"); t -> insert(233, "xyz"); //Ḳ <233, xyz> ////////// Erase t -> erase(233); //233ʧ t -> erase(233); //ʲôᷢ auto t2 = new sjtu::Splay<int, string>(); ////////// Split auto t1t2 = sjtu::split(t); //Ҫ (->)/delete t after doing this! Ըt¸ֵ t = t1t2.first, t2 = t1t2.second; ////////// Size cout << t -> size() << " " << t2 -> size() << endl; //cout 2 1 ////////// Min & Max cout << t -> min() << " " << t2 -> max() << endl; //cout -1 666 // t : {-1, 450} t2 : {666} ////////// Merge auto newt = sjtu::merge(t, t2); //Ҫ (->)/delete t, t2 after doing this! Ըt, t2¸ֵ ////////// Find auto it = newt -> find(233); //it == nullptr it = t -> find(666); //it -> key == 666 ////////// <key, data> cout << "<" << it -> key << ", " << it -> data << ">" << endl; //cout 666 efg ////////// Previous & Next it = newt -> previous(it); //it -> key == 450 it = newt -> next(it); //it -> key == 666 it = newt -> next(it); //it == nullptr ////////// First one it = newt -> begin(); //it -> key == -1 ////////// Last one it = newt -> rbegin(); //it -> key == 666 ////////// first >= it = newt -> geq(449); //it -> key == 450 it = newt -> geq(450); //it -> key == 450 it = newt -> geq(667); //it -> key == 666 (the last one) ////////// first <= it = newt -> leq(449); //it -> key == -1 it = newt -> leq(450); //it -> key == 450 it = newt -> leq(-2); //it -> key == -1 (the first one) ////////// Dzô /*int n = 1e4; sjtu::Splay<int, int> tree11, tree2, tree3; std::map<int, int> t1, t2; for (int i = 0; i < n * 2; ++ i) { int x = rand() % 200, y = rand() % 200; tree11.insert(x, y); t1[x] = y; } for (int i = 0; i < n; ++ i) { int x = rand() + rand(); tree2.insert(x, x); t2[x] = x; } for (int i = 0; i <= n; ++ i) { int x = rand() % 1000, y = rand() % 1000; //int x = (rand() % 2 * 2 - 1) * (rand() << 15) + rand(); tree3.insert(x, y); t1[x] = y; }*/ /*tree1.merge(tree2); tree1.merge(tree3); tree1.split(tree3);*/ /*auto tree1 = sjtu::merge(&tree11, &tree2); tree1 = sjtu::merge(tree1, &tree3); auto tmtmp = sjtu::split(tree1); auto tr1 = tmtmp.first, tr2 = tmtmp.second; printf("%d %d\n", tr1 ->size(), tr2 -> size()); tree1 = sjtu::merge(tr1, tr2); t1.insert(t2.begin(), t2.end()); printf("%d %d\n", tree1 -> size(), t1.size()); printf("%d %d\n", tree1 -> max(), t1.rbegin() -> first); assert(tree1 -> max() == t1.rbegin() -> first);*/ /* //auto tm = tree1.begin(); //for (; tm; tm = tree1.next(tm)) printf("%d ", tm -> data); //puts(""); //tm = tree3.begin(); //for (; tm; tm = tree3.next(tm)) printf("%d ", tm -> data); //puts(""); tree1.merge(tree3); t1.insert(t2.begin(), t2.end()); for (int i = 0; i < n; ++ i) { int x = rand(); //, y = rand(); //x = n - i + 1; tree1.erase(x); t1.erase(x); assert(t1.size() == tree1.size()); } auto tmp = tree1.begin(); auto tt = t1.begin(); for (; tmp; tmp = tree1.next(tmp), ++ tt) { assert(tt -> first == tmp -> key); //cout << tt -> second << " " << tmp -> data << endl; assert(tt -> second == tmp -> data); } assert(tt == t1.end()); for (int i = 0; i < n; ++ i) { int x = rand(); x = i; auto a = tree1.leq(x); auto b = t1.upper_bound(x); if (b == t1.begin()) { b = t1.end(); } else { b --; } if (a) { assert(b != t1.end()); assert(b -> first == a -> key); assert(b -> second == a -> data); } else { assert(b == t1.end()); } } puts("correct");*/ }
true
6381e18e87252b5b4c11c7c219bc4934bc1308a7
C++
xzjqx/FindAJob
/C++/CodeExam/剑指Offer/斐波那契数列.h
UTF-8
213
2.78125
3
[]
no_license
class Solution { public: int Fibonacci(int n) { int a[40]; a[0] = 0; a[1] = 1; for(int i = 2; i < 40; i ++) { a[i] = a[i-1] + a[i-2]; } return a[n]; } };
true
7ec86aaa6789f5914d1be10c7749fdb4f14fda2c
C++
ssh352/cppcode
/DotNet/ProVisualC++CLI/Chapter19/TcpServer/TcpServer.cpp
UTF-8
1,892
2.84375
3
[]
no_license
using namespace System; using namespace System::Net; using namespace System::Net::Sockets; using namespace System::Threading; using namespace System::Text; ref class TcpServer { public: void ProcessThread(Object ^clientObj); }; void TcpServer::ProcessThread(Object ^clientObj) { Socket^ client = (Socket^)clientObj; IPEndPoint^ clientEP = (IPEndPoint^)client->RemoteEndPoint; Console::WriteLine("Connected on IP: {0} Port: {1}", clientEP->Address, clientEP->Port); array<unsigned char>^ msg = Encoding::ASCII->GetBytes( String::Format("Successful connection to the server on port {0}", clientEP->Port)); client->Send(msg); int rcv; while (true) { msg = gcnew array<unsigned char>(1024); if ((rcv = client->Receive(msg)) == 0) break; Console::WriteLine("Port[{0}] {1}", clientEP->Port, Encoding::ASCII->GetString(msg, 0, rcv)); client->Send(msg, rcv, SocketFlags::None); } client->Close(); Console::WriteLine("Connection to IP: {0} Port {1} closed.", clientEP->Address, clientEP->Port); } void main() { TcpServer^ server = gcnew TcpServer(); Socket^ tcpListener = gcnew Socket(AddressFamily::InterNetwork, SocketType::Stream, ProtocolType::Tcp); IPEndPoint^ iped = gcnew IPEndPoint(IPAddress::Any, 12345); tcpListener->Bind(iped); tcpListener->Listen((int)SocketOptionName::MaxConnections); while(true) { Console::WriteLine("Waiting for client connection."); Socket^ client = tcpListener->Accept(); Thread ^thr = gcnew Thread( gcnew ParameterizedThreadStart(server, &TcpServer::ProcessThread)); thr->Start(client); } }
true
5eb785da6927acb89d848871d90f021050d256fc
C++
ishandutta2007/Number_Theory_in_CP_PS
/7. Mobius function과 그 활용/divisor_cnt_sum.cpp
UTF-8
1,923
3.0625
3
[]
no_license
#include <bits/stdc++.h> #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); using namespace std; typedef long long int ll; typedef unsigned long long int ull; typedef long double ldb; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // take modulos if you want/need // 1 : naive // 2 : after double count // 3 : sqrt technique with n/i-type values ll cnt_factor(ll n) { ll ret=0; for(ll i=1 ; i*i<=n ; i++) { if(n%i==0) { if(i*i==n) ret+=1; else ret+=2; } } return ret; } ll sum_factor(ll n) { ll ret=0; for(ll i=1 ; i*i<=n ; i++) { if(n%i==0) { if(i*i==n) ret+=i; else ret+=i+n/i; } } return ret; } ll sum_tau_1(ll n) { ll ret=0; for(ll i=1 ; i<=n ; i++) ret+=cnt_factor(i); return ret; } ll sum_tau_2(ll n) { ll ret=0; for(ll i=1 ; i<=n ; i++) ret+=n/i; return ret; } ll sum_tau_3(ll n) { ll ret=0; for(ll i=1, la ; i<=n ; i=la+1) { la=n/(n/i); // (n/i), (n/(i+1)), ... , (n/la) are all the same values ret += (la-i+1) * (n/i); // there are la - i + 1 values equal to (n/i) } return ret; } ll sum_sig_1(ll n) { ll ret=0; for(ll i=1 ; i<=n ; i++) ret+=sum_factor(i); return ret; } ll sum_sig_2(ll n) { ll ret=0; for(ll i=1 ; i<=n ; i++) ret+=i*(n/i); return ret; } ll sum_i(ll x) // 1 + 2 + ... + x { return x*(x+1)/2; } ll sum_sig_3(ll n) { ll ret=0; for(ll i=1, la ; i<=n ; i=la+1) { la=n/(n/i); // (n/i), (n/(i+1)), ... , (n/la) are all the same values ret += (sum_i(la)-sum_i(i-1)) * (n/i); // add (i + (i+1) + ... + la) * (n/i) } return ret; } int main(void) { cout << sum_tau_1(10000) << "\n"; cout << sum_tau_2(10000) << "\n"; cout << sum_tau_3(10000) << "\n"; cout << sum_sig_1(10000) << "\n"; cout << sum_sig_2(10000) << "\n"; cout << sum_sig_3(10000) << "\n"; return 0; }
true
c3dc4834a78b35291c4e3f5e60b33f5865fee817
C++
ashukharde3/Decomposer
/dependency.h
UTF-8
5,303
3.734375
4
[]
no_license
/*! @file dependency.h * * @brief Includes declaration for the class Dependency and its members. * * @details * This file declares the definition of the class Dependency along with its * subsequent data members and the member functions prototype. * */ #ifndef DEPENDENCY_H #define DEPENDENCY_H #include "declaration.h" #include "utility.h" #include <set> using std::set; #include <iostream> using std::istream; using std::ostream; /*! * \class Dependency * \brief The Dependency class that represents the functional dependency of the * relation using the attribute set. * \details The Dependency class contains the data member that represents the * left-hand side and right-hand of the functional dependency. Both lhs and rhs * are considered as the set of attributes. Attributes will be represented by the * string representing its name. Note that this class have private constructor which * restricts the creation of its object other than its friend member functions and * class. The object of this class can be constructed in the Relation class methods. * This is to ensure the fact that dependency belongs to a particular relation and * to identify that unique relation. */ class Dependency { friend class Relation; friend class dependency_test; friend class relation_test; friend ostream& operator<<(ostream &, const Dependency &); public: /** * @breif Destructor of the Dependency class. */ ~Dependency(); /** * @breif The copy constructor of the Dependency class. */ Dependency(const Dependency& orig); /** * @breif The overloaded less operator for testing inequality the dependency * objects. */ bool operator<(const Dependency&) const; /** * @breif The getter method for retrieve the left-hand side attribute set. */ set_str getLhs() const { return lhs; } /** * @breif The getter method for retrieve the right-hand side attribute set. */ set_str getRhs() const { return rhs; } /** * @breif The getter method for retrieve the all the attribute from dependency. */ set_str getAttribs() const; private: set_str lhs; /*!< The string of set or set_str object that reprensents the * left-hand side of the functional dependency*/ set_str rhs; /*!< The string of set or set_str object that reprensents the * right-hand side of the functional dependency*/ /** * @breif The overloaded relational operator != to check inequality between * the two Dependency objects. */ bool operator!=(const Dependency&) const; /** * @breif The overloaded relational operator ==to check equality between * the two Dependency objects. */ bool operator==(const Dependency&) const; /** * @breif The overloaded relational operator > to check inequality between * the two Dependency objects. */ bool operator>(const Dependency&) const; /** * @breif The overloaded operator += to combine the rhs of the two dependency * object if possible. */ Dependency& operator+=(const Dependency&); /** * @breif Constructor for the Dependency class initializing the data members. */ Dependency(const set_str &lhs, const set_str &rhs); /** * @breif A member function to add an attribute string to the lhs set. */ bool addLhs(const string &); /** * @breif A member function to add an attribute string to the rhs set. */ bool addRhs(const string &); /** * @breif A member function to remove an attribute string from the lhs set. */ bool removeLhs(const string &); /** * @breif A member function to remove an attribute string from the rhs set. */ bool removeRhs(const string &); /** * @breif A member function to check is an attribute string is present in lhs set. */ bool isPresentLhs(const string&) const; /** * @breif A member function to check is an attribute string is present in rhs set. */ bool isPresentRhs(const string&) const; /** * @breif A member function to check is an attribute string is present in * either lhs set or rhs set. */ bool isPresent(const string&) const; /** * @breif A member function to calculate total number of attributes present * in the lhs set and rhs set. */ unsigned int size(void) const; /** * @breif The setter method to reinitialize the left-hand side attribute set. */ void setLhs(const set_str &lhs) { this->lhs = lhs; } /** * @breif The setter method to reinitialize the right-hand side attribute set. */ void setRhs(const set_str &rhs) { this->rhs = rhs; } /** * @breif The method to clear left-hand side attribute set. */ void clearLhs(void) { this->lhs.clear(); } /** * @breif The method to clear right-hand side attribute set. */ void clearRhs(void) { this->rhs.clear(); } /** * @breif The method to clear both lhs and rhs attribute set. */ void clear(void) { clearLhs(); clearRhs(); } }; #endif /* DEPENDENCY_H */
true
d18a2c84afa55ea7e5b06cd4ad16a94585b2e218
C++
jonatajefferson/irp
/src/Driver.h
UTF-8
1,166
2.828125
3
[ "MIT" ]
permissive
#ifndef DRIVER_H_INCLUDED #define DRIVER_H_INCLUDED #include "TimeWindow.h" #include <vector> class Trailer; class Driver{ public: Driver(); Driver(int index, int maxDriving, std::vector<TimeWindow*> timeWindows, int minInterShift, double timeCost); Driver(int index, int maxDriving, std::vector<TimeWindow*> timeWindows, std::vector<Trailer*>trailers, int minInterShift, double timeCost); virtual ~Driver(); int getIndex() const; int getMaxDriving() const; std::vector<TimeWindow*> getTimeWindow() const; std::vector<Trailer*> getTrailers() const; int getMinInterShift() const; double getTimeCost() const; void setIndex(int); void setMaxDriving(int); void setTimeWindow(std::vector<TimeWindow*>); void setTrailers(std::vector<Trailer*>); void setMinInterShift(int); void setTimeCost(double); private: int index_; int maxDriving_; std::vector<TimeWindow*> timeWindows_; std::vector<Trailer*> trailers_; int minInterShift_; double timeCost_; }; #endif // DRIVER_H_INCLUDED
true
cdacb50d9b86aada6d818fd63b65af26b0bc2f20
C++
milad-mr/DistributedSystemScheduling
/src/Computing.cpp
UTF-8
1,934
3.0625
3
[]
no_license
#include "Computing.h" #include <memory> #include <string> #include <zmq.hpp> #include "DataAdaptor.h" /*Constructor for Computing process. This object is composed of DataAdaptor object which does providing data.*/ Computing::Computing(const DataAdaptor &da, int vmId, int jobId){ adaptor = da; //~ this -> vmId = vmId; //for example vm ip //~ this -> jobId = jobId; } //access multiple elements std::unique_ptr<int[]> Computing::access(int index, int count){ std::unique_ptr<int[]> elements(new int[count]); for(int i=0; i<count; ++i){ std::cout << "This Process Wants to Access Element number" << index << " of Input" << std::endl; elements[i] = adaptor.get(index); ++index; } return std::move(elements); } //access one element int Computing::access(int index){ //~ int rawIndex = index + reservedSpace; std::cout << "This Process Wants to Access Element number" << index << " of Input" << std::endl; return adaptor.get(index); } /*This method can be used in computing processes. When this method is called in a process, That process will listen for data access requests and if it receives any index, it access the data through DataAdaptor object.*/ void Computing::replytoReqs(const std::string &port){ std::cout << "This Process is Ready for Access Requests..." << std::endl; zmq::context_t context1 (1); zmq::socket_t socket1 (context1, ZMQ_REP); std::string prefix = "tcp://*:"; socket1.bind (prefix + port); while (true) { zmq::message_t req; socket1.recv (&req); std::string d = std::string(static_cast<char*>(req.data()), req.size()); int index = stoi(d); std::cout << "Element number" << index << " is Requested" << std::endl; int data = adaptor.localGet(index); std::string dataStr = std::to_string(data); zmq::message_t reply (5); memcpy (reply.data (), dataStr.c_str(), 5); std::cout << "Reply " << data << std::endl; socket1.send (reply); } }
true
07a0f5ff673738216eec3988e2707b8079f10326
C++
nic-cs151-master/sp21-lecture
/01-ch09/StudentClass/student.h
UTF-8
779
3.34375
3
[]
no_license
// Guard #ifndef STUDENT_H #define STUDENT_H #include <string> #include <iostream> #include <iomanip> using namespace std; // constant global variables // function prototypes // class declarations // struct declarations class Student { public: // constructors Student(); Student(int id, string name, int age); // setters or mutators void setStudent(int id, string name, int age); void setId(int id); void setName(string name); void setAge(int age); // getters or accessors int getId() const; string getName() const; int getAge() const; private: int mId; string mName; int mAge; }; // display an array of students void display(const Student array[], int size); void sortByName(Student array[], int size); #endif
true
613bca59964596b941b40f0aab979f3a27ee70ee
C++
monty68/EasyIOT
/src/core/http/PAGEHandler.h
UTF-8
2,175
2.515625
3
[ "Apache-2.0" ]
permissive
/* ** EasyIOT - (HTTP) Really Simple Web Server Class ** ** This is based upon the ESP8266WebServer library, ** Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. ** ** This program is provided free for you to use in any way that you wish, ** subject to the laws and regulations where you are using it. Due diligence ** is strongly suggested before using this code. Please give credit where due. ** ** The Author makes no warranty of any kind, express or implied, with regard ** to this program or the documentation contained in this document. The ** Author shall not be liable in any event for incidental or consequential ** damages in connection with, or arising out of, the furnishing, performance ** or use of these programs. */ #ifndef _IOT_PAGE_HANDLER_H #define _IOT_PAGE_HANDLER_H #include "HTTPHandler.h" class PAGEHandler : public HTTPHandler { public: PAGEHandler(IOTHTTP::http_callback_t fn, IOTHTTP::http_callback_t ufn, const String &uri, HTTPMethod method) : _fn(fn), _ufn(ufn), _uri(uri), _method(method) { } bool httpCanHandle(HTTPMethod requestMethod, String requestUri) override { if (_method != HTTP_ANY && _method != requestMethod) return false; if (requestUri != _uri) return false; return true; } bool httpCanUpload(String requestUri) override { if (!_ufn || !httpCanHandle(HTTP_POST, requestUri)) return false; return true; } bool httpHandle(IOTHTTP &server, HTTPMethod requestMethod, String requestUri) override { (void)server; if (!httpCanHandle(requestMethod, requestUri)) return false; _fn(server); return true; } void httpUpload(IOTHTTP &server, String requestUri, HTTPUpload &upload) override { (void)server; (void)upload; if (httpCanUpload(requestUri)) _ufn(server); } protected: IOTHTTP::http_callback_t _fn; IOTHTTP::http_callback_t _ufn; HTTPMethod _method; String _uri; }; #endif // _IOT_PAGE_HANDLER_H /******************************************************************************/
true
12d81d97ca0dad1df75a5f454c13044710974a6c
C++
neutronest/mcts_legend_of_heros
/player.cc
UTF-8
1,733
2.9375
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <vector> #include <string> #include <algorithm> #include <map> #include <cmath> #include "player.h" using namespace std; double player::get_base_hp() { return this->base_hp; } void player::set_base_hp(double hp) { this->base_hp = hp; return; } double player::get_base_ep() { return this->base_ep; } void player::set_base_ep(double ep) { this->base_ep = ep; return; } double player::get_base_sp() { return this->base_sp; } void player::set_base_sp(double sp) { this->base_sp = sp; return; } double player::get_base_atk() { return this->base_atk; } void player::set_base_atk(double atk) { this->base_atk = atk; return; } player::player(double hp, double ep, double sp, double atk) { this->set_base_hp(hp); this->set_base_ep(ep); this->set_base_sp(sp); this->set_base_atk(atk); this->cur_hp = this->get_base_hp(); this->cur_ep = this->get_base_ep(); this->cur_sp = this->get_base_sp(); this->cur_atk = this->get_base_atk(); this->encouraged = 0; this->shell = 0; this->is_dead = false; } player* player::dcopy() { player* new_player = new player(0, 0, 0, 0); new_player->base_hp = this->base_hp; new_player->base_ep = this->base_ep; new_player->base_sp = this->base_sp; new_player->base_atk = this->base_atk; new_player->cur_hp = this->cur_hp; new_player->cur_ep = this->cur_ep; new_player->cur_sp = this->cur_sp; new_player->cur_atk = this->cur_atk; new_player->encouraged = this->encouraged; new_player->shell = this->shell; new_player->is_dead = this->is_dead; //cout<<"player'hp: "<<cur_hp<<endl; return new_player; }
true
7e95ed32203bab61feb6a29ab9fb4c670152dac4
C++
matajupi/HackAssembler
/Assembler.h
UTF-8
2,269
2.875
3
[]
no_license
// // Created by Kosuke Futamata on 21/08/2021. // #include <vector> #include <string> #include <map> #include "Parser.h" #include "Instruction.h" #include "CodeGenerator.h" class Assembler { std::vector<std::string> *source; public: explicit Assembler(std::vector<std::string> *source) : source(source) { } void assemble(std::vector<std::string> *object_code) { Parser parser(source); auto instructions = new std::vector<Instruction*>(); parser.parse(instructions); // Create symbol_table auto symbol_table = new std::map<std::string, int> { { "SP", 0 }, { "LCL", 1 }, { "ARG", 2 }, { "THIS", 3 }, { "THAT", 4 }, { "SCREEN", 16384 }, { "KBD", 24576 }, { "R0", 0 }, { "R1", 1 }, { "R2", 2 }, { "R3", 3 }, { "R4", 4 }, { "R5", 5 }, { "R6", 6 }, { "R7", 7 }, { "R8", 8 }, { "R9", 9 }, { "R10", 10 }, { "R11", 11 }, { "R12", 12 }, { "R13", 13 }, { "R14", 14 }, { "R15", 15 }, }; auto line_number = 0; for (auto instruction : *instructions) { if (instruction->kind == InstructionKind::L_COMMAND) { if (symbol_table->contains(instruction->symbol)) { std::cerr << "Error: The label name '" << instruction->symbol << "' is already defined." << std::endl; continue; } (*symbol_table)[instruction->symbol] = line_number; } else line_number++; } auto address = 16; for (auto instruction : *instructions) { if (instruction->kind == InstructionKind::A_COMMAND && !instruction->is_numeric) { if (symbol_table->contains(instruction->symbol)) continue; (*symbol_table)[instruction->symbol] = address++; } } CodeGenerator generator(instructions, symbol_table); generator.generate(object_code); } };
true
528d9fe79d55267393c12bb5c479d04ea01428da
C++
Ronoman/RBE-1001
/Drivebase.cpp
UTF-8
3,474
3.21875
3
[]
no_license
#include "Drivebase.h" #include "Constants.h" /** * Helper function. Maps one range of values to another * @param x input * @param in_min minimum input value * @param in_max maximum input value * @param out_min minimum output value * @param out_max maximum output value * @return the mapped value */ double mapVal(double x, double in_min, double in_max, double out_min, double out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } /** * Helper function. Maps a joystick value to the range [-1, 1] * @param in joystick value * @return mapped joystick value */ double mapJoy(double in) { double val = mapVal(in, 0.0, 180.0, -1.0, 1.0); return val; } Drivebase::Drivebase() { //Setup both motors _left.attach(LEFT_DRIVE, 1000, 2000); _right.attach(RIGHT_DRIVE, 1000, 2000); //Construct both encoders _rightDist = new Encoder(RIGHT_POS_A, RIGHT_POS_B); _leftDist = new Encoder(LEFT_POS_A, LEFT_POS_B); //Construct both a straight and turning PID _distPID = new PID(_leftDist, _rightDist, DRIVEBASE_FORWARD_P, STRAIGHT); _turnPID = new PID(_leftDist, _rightDist, DRIVEBASE_TURN_P, TURN); } /** * Sets the left speed of the drivebase * @param speed motor speed, between -1 and 1 */ void Drivebase::setLeft(double speed) { speed = mapVal(speed, 1.0, -1.0, 0.0, 180.0); _left.write(speed); } /** * Sets the right speed of the drivebase * @param speed motor speed, between -1 and 1 */ void Drivebase::setRight(double speed) { speed = mapVal(speed, -1.0, 1.0, 0.0, 180.0); _right.write(speed); } /** * Get the left encoder value * @return left encoder value */ float Drivebase::getLeftDist() { return _leftDist->getPosition(); } /** * Get the right encoder value * @return right encoder value */ float Drivebase::getRightDist() { return _rightDist->getPosition(); } /** * Update the state of encoders, and motor speed during teleop. */ void Drivebase::update() { //If we're in teleop, read joystick inputs if(_robot->getGamePeriod() == TELEOP) { setLeft(mapJoy(_robot->getLeftJoy())); setRight(mapJoy(_robot->getRightJoy())); } _rightDist->update(); _leftDist->update(); Serial.println(getRightDist()); } /** * Sets the robot instance * @param robot instance of Robot */ void Drivebase::setRobot(Robot *robot) { _robot = robot; } /** * Update the distance PID with a new offset * @param pos number of ticks to travel, added to the current position */ void Drivebase::setStraightOffset(float pos) { //TODO: Make this work (bad right now) _distPID->setSetpoint((getLeftDist() + getRightDist())/2 + pos); } void Drivebase::setTurnOffset(float pos) { //TODO: Document and make work _turnPID->setSetpoint(pos); } /** * Get the error of the straight-line PID * @return error of _distPID */ float Drivebase::getStraightError() { return _distPID->getError(); } /** * Get the error of the point-turn PID * @return error of _turnPID */ float Drivebase::getTurnError() { return _turnPID->getError(); } /** * Whether or not the straight PID is within tolerance * @return is straight PID in tolerance */ bool Drivebase::straightWithinTolerance() { return _distPID->withinTolerance(); } /** * Whether or not the turn PID is within tolerance * @return is turn PID in tolerance */ bool Drivebase::turnWithinTolerance() { return _turnPID->withinTolerance(); }
true
a384e8d656f4a50a28f084e34ee570924d2ac27a
C++
aastha621/Launchpad_29Dec2019
/Lecture37/longestIncSubseq.cpp
UTF-8
1,050
3.109375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int lis(int* arr, int n) { int dp[1000] = {0}; for (int i = 0 ; i < n; i++) { dp[i] = 1; } int maxLength = 0; for (int i = 1; i < n ; ++i) { for (int j = 0; j < i; ++j) { if (arr[i] > arr[j]) { dp[i] = max(dp[i], dp[j] + 1); } } maxLength = max(maxLength, dp[i]); } for (int i = 0; i < n ; ++i) { cout << dp[i] << ", "; } cout << endl; return maxLength; } int longestIncSubseqOptimized(int *arr, int n) { vector<int> dp; dp.push_back(arr[0]); for (int i = 1; i < n; ++i) { int currEle = arr[i]; auto idx = lower_bound(dp.begin(), dp.end(), currEle); if (idx == dp.end()) { dp.push_back(currEle); } else { *idx = currEle; } } for (int i = 0; i < dp.size(); ++i) { cout << dp[i] << ","; } cout << endl; return dp.size(); } int main(int argc, char const *argv[]) { int n = 6; int arr[100] = {50, 3, 10, 7, 40, 50}; cout << lis(arr, n) << endl; cout << longestIncSubseqOptimized(arr, n) << endl; return 0; }
true
f8ff54f40dea8d1527a8a921da553021478d8dc4
C++
krishna-NIT/Algo-Tree
/Code/C++/Dijkstra.cpp
UTF-8
2,511
3.859375
4
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
/* Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a graph. It is applicable for: * Both directed and undirected graphs * All edges must have None-Negative weights * Graph must be connected */ #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <queue> using namespace std; #define INF 0x3f3f3f3f typedef vector<int> vi; typedef pair<int, int> pii; typedef vector<pii> vii; typedef pair<int, int> pii; // Graph -> Vector - Pair vii *Graph; // It Stores the Distance of every other node from start. vi Distance; void Dijkstra(int start, int N) { // min heap priority_queue<pii, vector<pii>, greater<pii>> Q; Distance.assign(N, INF); Distance[start] = 0; Q.push({0, start}); while (!Q.empty()) { int v1 = Q.top().second; Q.pop(); for (auto &c : Graph[v1]) { int v2 = c.first; int weight = c.second; if (Distance[v2] > Distance[v1] + weight) { Distance[v2] = Distance[v1] + weight; Q.push({Distance[v2], v2}); } } } } int main() { // N - total no of nodes, M - no. of edges // v1, v2 and weight are the end vertices and the weight associated with an edge // start is the sStarting Point from where we have to find Shortest Path int N, M, v1, v2, weight, start; cin >> N >> M; Graph = new vii[N + 1]; for (int i = 0; i < M; ++i) { cin >> v1 >> v2 >> weight; Graph[v1].push_back({v2, weight}); Graph[v2].push_back({v1, weight}); } cin >> start; Dijkstra(start, N); for (int i = 0; i < N; i++) cout << "Distance From " << start << " to Node " << i << " is " << Distance[i] << " " << endl; cout << endl; return 0; } /* Test Cases: Input 1 : 5 5 0 1 17 0 2 2 0 3 9 0 4 24 0 5 28 1 Output 1 : Distance From 1 to Node 0 is 17 Distance From 1 to Node 1 is 0 Distance From 1 to Node 2 is 19 Distance From 1 to Node 3 is 26 Distance From 1 to Node 4 is 41 Input 2 : 4 4 0 1 11 0 2 2 0 3 31 0 4 24 0 5 28 1 Output 2 : Distance From 0 to Node 0 is 0 Distance From 0 to Node 1 is 11 Distance From 0 to Node 2 is 2 Distance From 0 to Node 3 is 31 Time complexity : O(ElogV) where E is no. of Edges and V are no. of Vertices Space Complexity: O(V^2) */
true
be6b4bd73153e43d38be82f0750a5d6e26ee7a8e
C++
DenkaKrenka/Pavlovskaya
/pavf/чивапчичи4/чивапчичи4.cpp
UTF-8
2,485
2.71875
3
[]
no_license
// чивапчичи4.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> using namespace std; const int N = 4; int main() { int a[3 * N][2]; int n = 3 * N; for (int i = 0; i < n; i++) for (int j = 0; j <= 1; j++) cin >> a[i][j]; for (int i = 0; i < n; i++) { for (int j = 0; j <= 1; j++) cout << a[i][j] << " "; cout << "\n"; } cout << "\n"; for (int i=0; i<n;i++) for (int j=0; j< n-1; j++) if (a[j][0] + a[j][1] < a[j + 1][0] + a[j + 1][1]) { int w1 = a[j][0]; int w2 = a[j][1]; a[j][0] = a[j + 1][0]; a[j][1] = a[j + 1][1]; a[j + 1][0] = w1; a[j + 1][1] = w2; } for (int i = 0; i < n; i += 3) { cout << "Triangle with dots: \n"; for (int k = i; k < i + 3; k++) { for (int j = 0; j <= 1; j++) cout << a[k][j] << " "; cout << "\n"; } cout << "\n"; } /*for (int i = 0; i < n; i++) { for (int j = 0; j <= 1; j++) cout << a[i][j] << " "; cout << a[i][0] + a[i][1]; cout << "\n"; }*/ } // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
true
81afb4cb35b6229c9bf0d25af45a79fa8dede3e4
C++
sahilgoyals1999/GFG-Algorithms
/10. Mathematical Algorithms/07. Multiply two integers without using multiplication, division and bitwise operators, and no loops.cpp
UTF-8
362
3.71875
4
[]
no_license
// https://www.geeksforgeeks.org/multiply-two-numbers-without-using-multiply-division-bitwise-operators-and-no-loops/ // T.C => O(y) int multiply(int x, int y) { // 0 multiplied with anything gives 0 if (y == 0) return 0; // Add x one by one if (y > 0) return (x + multiply(x, y - 1)); // the case where y is negative if (y < 0) return -multiply(x, -y); }
true
4720a448da3c462277ea6b538991c498582f4770
C++
zhen3410/myWebServer
/muduo/EventLoop.cpp
UTF-8
4,086
2.71875
3
[]
no_license
#include"EventLoop.h" #include"EPoller.h" #include"channel.h" #include<iostream> #include<assert.h> #include<sys/eventfd.h> #include<unistd.h> #include<sys/syscall.h> using namespace server; namespace{ __thread EventLoop* t_loopInThisThread=0; const int kPollTimeMs=10000; int createEventFd(){ int fd=::eventfd(0,EFD_NONBLOCK|EFD_CLOEXEC); if(fd<0){ std::cerr<<"createEventFd() : failed!"<<std::endl; abort(); } return fd; } } EventLoop::EventLoop() :looping_(false), quit_(false), callingPendingFunctors_(false), threadId_(syscall(SYS_gettid)), poller_(new EPoller(this)), timerQueue_(new TimerQueue(this)), wakeupFd_(createEventFd()), wakeupChannel_(new Channel(this,wakeupFd_)) { if(t_loopInThisThread){ std::cerr<<"another thread exist"<<std::endl; }else{ t_loopInThisThread=this; } std::cout<<"EventLoop::EventLoop() set wakeupChannel wakeFd = "<<wakeupFd_<<std::endl; wakeupChannel_->setReadCallback(std::bind(&EventLoop::handleRead,this)); wakeupChannel_->enableReading(); } EventLoop::~EventLoop(){ assert(!looping_); t_loopInThisThread=NULL; wakeupChannel_->disableAll(); wakeupChannel_->remove(); ::close(wakeupFd_); } void EventLoop::runInLoop(const EventLoop::functor& cb){ std::cout<<"EventLoop::runInLoop()"<<std::endl; if(isInLoopThread()){ std::cout<<"cb()"<<std::endl; cb(); }else{ std::cout<<"queueInLoop()"<<std::endl; queueInLoop(cb); } } void EventLoop::queueInLoop(const EventLoop::functor& cb){ { MutexGuard lock(mutex_); pendingFunctors_.push_back(cb); } // 由于doPendingFunctors()调用的Functor可能再次调用queueInLoop(), // 这时queueInLoop()就必须wakeup(),窦泽新加入的cb就不能被及时调用了 if(!isInLoopThread()||callingPendingFunctors_){ wakeup(); } } EventLoop* EventLoop::getEventLoopOfCurrentThread(){ return t_loopInThisThread; } void EventLoop::loop(){ assert(!looping_); assertInLoopThread(); looping_=true; quit_=false; while(!quit_){ activeChannels_.clear(); pollReturnTime_=poller_->poll(kPollTimeMs,&activeChannels_); for(ChannelList::iterator it=activeChannels_.begin();it!=activeChannels_.end();++it){ (*it)->handleEvent(pollReturnTime_); } doPendingFunctors(); } //::poll(NULL,0,5*1000); std::cout<<"EventLoop"<<threadId_<<"stop looping"<<std::endl; looping_=false; } void EventLoop::doPendingFunctors(){ std::vector<functor> functors; callingPendingFunctors_=true; { MutexGuard lock(mutex_); functors.swap(pendingFunctors_); } for(size_t i=0;i<functors.size();++i){ functors[i](); } callingPendingFunctors_=false; } void EventLoop::wakeup(){ uint64_t one=1; // sizeof()和sizeof的区别 // sizeof(int) // int a; sizeof a; ssize_t n=::write(wakeupFd_,&one,sizeof one); if(n!=sizeof one){ std::cerr<<"EventLoop::wakeup() writes "<<n<<" bytes instead of 8"<<std::endl; } } void EventLoop::handleRead(){ uint64_t one=1; ssize_t n=::read(wakeupFd_,&one,sizeof one); if(n!=sizeof one){ std::cerr<<"EventLoop::handleRead() reads "<<n<<"bytes instead of 8"<<std::endl; } } void EventLoop::quit(){ quit_=true; // 可以及时终止循环,否则可能会阻塞在调用队列中 // 在IO线程中调用quit()会由于Poll超时而退出循环 if(!isInLoopThread()){ wakeup(); } } void EventLoop::updateChannel(Channel* channel){ assert(channel->ownerLoop()==this); assertInLoopThread(); poller_->updateChannel(channel); } void EventLoop::removeChannel(Channel* channel){ assert(channel->ownerLoop()==this); assertInLoopThread(); poller_->removeChannel(channel); } void EventLoop::abortNotInLoopThread(){ std::cerr<<"EventLoop::abortNotInLoopThread() EventLoop was created in threadId_ = " << threadId_ << " , current thread id = " <<pthread_self()<<std::endl; }
true