blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
โŒ€
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
โŒ€
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
โŒ€
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
4a3a4da39542294b4b7b23acfb6e7058552b7def
adc57610b7191faf942d3441b5e2bbca0713cefe
/01-find-package/src/libone.cpp
105348d712fac5acd78ae8748b8c0fac9f3d0231
[ "ISC" ]
permissive
thejohnfreeman/project-template-cpp
73359c70e067d29ad75453333ee4fc991e00d0dd
c8b288e1d1351125ffa07a75e5b02100c3cd4c4a
refs/heads/master
2023-07-09T20:21:36.486804
2023-06-12T21:01:18
2023-06-12T21:01:18
185,826,021
4
1
null
null
null
null
UTF-8
C++
false
false
376
cpp
libone.cpp
#include <one/one.hpp> namespace one { unsigned int one() { return 1; } zero::Bool and_(zero::Bool a, zero::Bool b) { return (*a && *b) ? zero::true_() : zero::false_(); } zero::Bool or_(zero::Bool a, zero::Bool b) { return (*a || *b) ? zero::true_() : zero::false_(); } zero::Bool not_(zero::Bool a) { return (!*a) ? zero::true_() : zero::false_(); } }
ba4533e39cab2b77a403d46a7ca311eab3b3b0df
c83a1525bcf1c03ff5b6dea8ba95f9a70227b9ff
/Sources/GameSources/ArcherAttack.h
4783437d2820184ceb7384b6fd6b5a504cd3b284
[]
no_license
tkm1211/3rdTeamProduction
9d7871d706a9fa156ee129147d7a87db8efb4d1e
8d68c3093a7cdae8e2581fb9e5d7f6a36d59ecfb
refs/heads/master
2020-09-21T13:59:51.136422
2020-01-29T00:30:40
2020-01-29T00:30:40
224,807,237
1
0
null
null
null
null
UTF-8
C++
false
false
261
h
ArcherAttack.h
#pragma once #include "ExecJudgementBase.h" class AI; class ArcherAttackJudge : public ExecJudgementBase { public: static ArcherAttackJudge *GetInstance() { static ArcherAttackJudge instance; return &instance; } virtual bool Judgement(AI *obj); };
f5d4ed816ae4cb1872e0db1f86891cbb2ea9a065
81e71315f2f9e78704b29a5688ba2889928483bb
/src/Plugin/Plugin FLT/ObjectRecord.cpp
d20d0c6522f7e1ad3d4148c3026d2cc6dfb20633
[]
no_license
Creature3D/Creature3DApi
2c95c1c0089e75ad4a8e760366d0dd2d11564389
b284e6db7e0d8e957295fb9207e39623529cdb4d
refs/heads/master
2022-11-13T07:19:58.678696
2019-07-06T05:48:10
2019-07-06T05:48:10
274,064,341
0
1
null
null
null
null
UTF-8
C++
false
false
769
cpp
ObjectRecord.cpp
// ObjectRecord.cpp #include <Plugin flt/flt.h> #include <Plugin flt/Registry.h> #include <Plugin flt/ObjectRecord.h> using namespace flt; //////////////////////////////////////////////////////////////////// // // ObjectRecord // //////////////////////////////////////////////////////////////////// RegisterRecordProxy<ObjectRecord> g_ObjectProxy; ObjectRecord::ObjectRecord() { } // virtual ObjectRecord::~ObjectRecord() { } void ObjectRecord::endian() { SObject *pSObject = (SObject*)getData(); ENDIAN( pSObject->dwFlags ); ENDIAN( pSObject->iObjectRelPriority ); ENDIAN( pSObject->wTransparency ); ENDIAN( pSObject->iSpecialId_1 ); ENDIAN( pSObject->iSpecialId_2 ); ENDIAN( pSObject->iSignificance ); }
dfc781ca75a8879651a40088e2103e8c5c3e154b
51dbd6b9c64ec851209d3f159380a45b1df156ab
/๋ฐฑ์ค€/Software_CodingTest/13458๋ฒˆ ์‹œํ—˜ ๊ฐ๋….cpp
16649b5dbcd7eda4a69cb1f29d1de4b6160a167b
[]
no_license
NaTaes/Algorithm
44e7e964394c36793ecb93d8f15fad61f836a9e2
c6ee452e5ddd9f159bf54dadbd5aa7f53af10dad
refs/heads/master
2021-08-15T04:58:42.000003
2021-08-11T09:19:25
2021-08-11T09:19:25
131,107,679
0
0
null
null
null
null
UTF-8
C++
false
false
669
cpp
13458๋ฒˆ ์‹œํ—˜ ๊ฐ๋….cpp
#include<iostream> using namespace std; int Cdd[1000000]; int main(void) { int N, B, C; long long min = 0; scanf("%d", &N); for(int i=0; i<N; i++) scanf("%d", &Cdd[i]); scanf("%d %d", &B, &C); for(int i=0; i<N; i++) { int tmp = Cdd[i] - B; //์ด๊ฐ๋…๊ด€์˜ ์ˆ˜๋ฅผ ๋นผ์ค€๋‹ค. min += 1; //์ธ์› ์ถ”๊ฐ€ if(tmp <= 0) continue; //์ด๊ฐ๋…๊ด€๋งŒ์œผ๋กœ ์ธ์›์„ ๊ฐ๋…ํ•  ์ˆ˜์žˆ๋‹ค๋ฉด continueํ•œ๋‹ค. if(tmp%C) //๋‚จ์€ ์ธ์›์ˆ˜๋ฅผ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๊ฐ€ ์žˆ๋‹ค๋ฉด ๋‚˜๋ˆˆ ๊ฐ’์— +1์„ ํ•ด์ค€๋‹ค. min += tmp/C + 1; else //๋‚˜๋จธ์ง€๊ฐ€ ์—†๋‹ค๋ฉด ๋”ฑ ๋‚˜๋ˆ ์ง„๋งŒํผ์ด๋ฏ€๋กœ ๋‚˜๋ˆˆ๊ฐ’๋งŒ ๋”ํ•ด์ค€๋‹ค. min += tmp/C; } printf("%lld\n", min); }
1a42baf40d94d7b99d303a8458c4c2debb6e8a4b
b6d1df49c1ec621a02204b1100312ecbb3e76ad3
/src/mains/OSG/virtual_camera.cc
ac1b573bafd6a64866c903a2d7ddb5198cba5be5
[]
no_license
flylong0204/projects
5271acde325cf3947fac7433077353b52fa07bc4
b1e5c918d4aeb34c36576dababc5509dbb89afd1
refs/heads/master
2017-12-06T06:35:20.926786
2017-01-24T23:53:13
2017-01-24T23:53:13
79,988,197
1
2
null
2017-01-25T06:11:23
2017-01-25T06:11:23
null
UTF-8
C++
false
false
10,816
cc
virtual_camera.cc
// ======================================================================== // Program VIRTUAL_CAMERA is a variant of VIEWCITIES which opens two // windows displaying the same point cloud. In one window, we see the // view from a virtual OpenGL camera. In the other window, the // virtual camera is depicted by an OBSFRUSTUM. Manipulation of the // virtual camera in window #1 causes the OBSFRUSTUM to move in window // #2. // virtual_camera cambridge.osga --GIS_layer boston_GIS.pkg // virtual_camera --region_filename ./packages/cambridge.pkg --GIS_layer ./packages/boston_GIS.pkg // virtual_camera --region_filename ./packages/boston.pkg --GIS_layer ./packages/boston_GIS.pkg // ======================================================================== // Last updated on 8/25/09; 5/11/10; 5/12/10; 12/4/10 // ======================================================================== #include <iostream> #include <string> #include <vector> #include <osgDB/FileUtils> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include "osg/osgGraphicals/AnimationController.h" #include "osg/osgGraphicals/CentersGroup.h" #include "osg/osgGraphicals/CentersKeyHandler.h" #include "osg/osgGraphicals/CenterPickHandler.h" #include "astro_geo/Clock.h" #include "osg/osgOrganization/Decorations.h" #include "osg/osgEarth/EarthRegionsGroup.h" #include "osg/osgGrid/GridKeyHandler.h" #include "osg/osgGrid/LatLongGridsGroup.h" #include "osg/ModeController.h" #include "osg/ModeKeyHandler.h" #include "osg/osgModels/ModelsGroup.h" #include "osg/osgSceneGraph/MyDatabasePager.h" #include "osg/osgOperations/Operations.h" #include "osg/osgfuncs.h" #include "passes/PassesGroup.h" #include "osg/osg3D/PointCloudsGroup.h" #include "osg/osg3D/PointCloudKeyHandler.h" #include "osg/osgGraphicals/PointFinder.h" #include "osg/osgGIS/postgis_databases_group.h" #include "osg/osg3D/Terrain_Manipulator.h" #include "passes/TextDialogBox.h" #include "time/timefuncs.h" #include "osg/osgWindow/ViewerManager.h" #include "general/outputfuncs.h" // ========================================================================== int main( int argc, char** argv ) { using std::cin; using std::cout; using std::endl; using std::string; using std::vector; std::set_new_handler(sysfunc::out_of_memory); // Use an ArgumentParser object to manage the program arguments: osg::ArgumentParser arguments(&argc,argv); const int ndims=3; PassesGroup passes_group(&arguments); int cloudpass_ID=passes_group.get_curr_cloudpass_ID(); vector<int> GISlayer_IDs=passes_group.get_GISlayer_IDs(); cout << "cloudpass_ID = " << cloudpass_ID << endl; // Instantiate clock to keep track of real time: Clock clock; clock.current_local_time_and_UTC(); // Instantiate postgis database objects to send data to and retrieve // data from external Postgres database: postgis_databases_group* postgis_databases_group_ptr= new postgis_databases_group; // postgis_database* postgis_db_ptr= postgis_databases_group_ptr-> generate_postgis_database_from_GISlayer_IDs(passes_group,GISlayer_IDs); // Construct the viewers and instantiate ViewerManagers: WindowManager* window_mgr_ptr=new ViewerManager(); WindowManager* window_mgr_global_ptr=new ViewerManager(); string window_title="Virtual camera"; string window_global_title="Global view"; window_mgr_ptr->initialize_dual_windows( window_title,window_global_title,window_mgr_global_ptr); // Create OSG root node: osg::Group* root = new osg::Group; osg::Group* root_global = new osg::Group; // Instantiate Operations object to handle mode, animation and image // number control: Operations operations(ndims,window_mgr_ptr); ModeController* ModeController_ptr=operations.get_ModeController_ptr(); AnimationController* AnimationController_ptr= operations.get_AnimationController_ptr(); root->addChild(operations.get_OSGgroup_ptr()); ModeController* ModeController_global_ptr=new ModeController(); window_mgr_global_ptr->get_EventHandlers_ptr()->push_back( new ModeKeyHandler(ModeController_global_ptr) ); root_global->addChild(osgfunc::create_Mode_HUD( ndims,ModeController_global_ptr)); // Add a custom manipulator to the event handler list: osgGA::Terrain_Manipulator* CM_3D_ptr=new osgGA::Terrain_Manipulator( ModeController_ptr,window_mgr_ptr); window_mgr_ptr->set_CameraManipulator(CM_3D_ptr); // Instantiate groups to hold multiple point clouds, // latitude-longitude grids and associated earth regions: PointCloudsGroup clouds_group(passes_group.get_pass_ptr(cloudpass_ID)); LatLongGridsGroup latlonggrids_group( ndims,passes_group.get_pass_ptr(cloudpass_ID),CM_3D_ptr); EarthRegionsGroup earth_regions_group( passes_group.get_pass_ptr(cloudpass_ID), &clouds_group,&latlonggrids_group); earth_regions_group.generate_regions(passes_group); LatLongGrid* latlonggrid_ptr=latlonggrids_group.get_Grid_ptr(0); threevector* grid_origin_ptr=latlonggrid_ptr->get_world_origin_ptr(); // Add a custom manipulator to the event handler list: CM_3D_ptr->set_Grid_ptr(latlonggrid_ptr); window_mgr_ptr->get_EventHandlers_ptr()->push_back( new PointCloudKeyHandler(&clouds_group,ModeController_ptr,CM_3D_ptr)); window_mgr_ptr->get_EventHandlers_ptr()->push_back( new GridKeyHandler(ModeController_ptr,latlonggrid_ptr)); osgGA::Terrain_Manipulator* CM_3D_global_ptr= new osgGA::Terrain_Manipulator( ModeController_global_ptr,window_mgr_global_ptr); CM_3D_global_ptr->set_Grid_ptr(latlonggrid_ptr); window_mgr_global_ptr->set_CameraManipulator(CM_3D_global_ptr); window_mgr_global_ptr->get_EventHandlers_ptr()->push_back( new PointCloudKeyHandler(&clouds_group,ModeController_global_ptr, CM_3D_global_ptr)); window_mgr_global_ptr->get_EventHandlers_ptr()->push_back( new GridKeyHandler(ModeController_global_ptr,latlonggrid_ptr)); // Instantiate a PointFinder; PointFinder pointfinder(&clouds_group); CM_3D_ptr->set_PointFinder(&pointfinder); CM_3D_global_ptr->set_PointFinder(&pointfinder); // Instantiate group to hold all decorations: Decorations decorations( window_mgr_ptr,ModeController_ptr,CM_3D_ptr,grid_origin_ptr); decorations.set_PointCloudsGroup_ptr(&clouds_group); // Instantiate a MyDatabasePager to handle paging of files from disk: // viewer::MyDatabasePager* MyDatabasePager_ptr=new viewer::MyDatabasePager( // clouds_group.get_SetupGeomVisitor_ptr(), // clouds_group.get_ColorGeodeVisitor_ptr()); // Instantiate signposts, features, army symbol and sphere segments // decoration groups: SignPostsGroup* SignPostsGroup_ptr=decorations.add_SignPosts( ndims,passes_group.get_pass_ptr(cloudpass_ID)); SignPostsGroup_ptr->set_postgis_databases_group_ptr( postgis_databases_group_ptr); for (int n=0; n<decorations.get_n_SignPostsGroups(); n++) { decorations.get_SignPostsGroup_ptr(n)->set_EarthRegionsGroup_ptr( &earth_regions_group); decorations.get_SignPostsGroup_ptr(n)->set_Clock_ptr(&clock); } decorations.add_Features(ndims,passes_group.get_pass_ptr(cloudpass_ID)); decorations.add_ArmySymbols(passes_group.get_pass_ptr(cloudpass_ID)); decorations.add_SphereSegments(passes_group.get_pass_ptr(cloudpass_ID)); decorations.add_ObsFrusta( passes_group.get_pass_ptr(cloudpass_ID),AnimationController_ptr); ObsFrustaGroup* ObsFrustaGroup_ptr=decorations.get_ObsFrustaGroup_ptr(); // ObsFrustum* virtual_ObsFrustum_ptr= ObsFrustaGroup_ptr->generate_virtual_camera_ObsFrustum(); // Instantiate CentersGroup and center pick handler to handle mid // point selection: CentersGroup centers_group( ndims,passes_group.get_pass_ptr(cloudpass_ID), AnimationController_ptr,grid_origin_ptr); CenterPickHandler* CenterPickHandler_ptr=new CenterPickHandler( ndims,passes_group.get_pass_ptr(cloudpass_ID), CM_3D_ptr,&centers_group,ModeController_ptr,window_mgr_ptr, grid_origin_ptr); window_mgr_ptr->get_EventHandlers_ptr()->push_back( CenterPickHandler_ptr); window_mgr_ptr->get_EventHandlers_ptr()->push_back( new CentersKeyHandler(ndims,CenterPickHandler_ptr,ModeController_ptr)); // Attach all 3D graphicals to CentersGroup SpinTransform which can // perform global rotation about some axis coming out of a user // selected center location. On 2/5/07, we learned (the painful and // hard way!) that the order in which nodes are added to the // SpinTransform is important for alpha-blending. In particular, we // must add decorations' OSGgroup AFTER adding clouds_group OSGgroup // if alpha blending of 3D video imagery is to work... centers_group.get_SpinTransform_ptr()->addChild( clouds_group.get_OSGgroup_ptr()); centers_group.get_SpinTransform_ptr()->addChild( latlonggrids_group.get_OSGgroup_ptr()); centers_group.get_SpinTransform_ptr()->addChild( decorations.get_OSGgroup_ptr()); root->addChild(centers_group.get_SpinTransform_ptr()); root_global->addChild(clouds_group.get_OSGgroup_ptr()); root_global->addChild(latlonggrids_group.get_OSGgroup_ptr()); root_global->addChild(decorations.get_OSGgroup_ptr()); // Attach scene graph to the viewer: window_mgr_ptr->setSceneData(root); window_mgr_global_ptr->setSceneData(root_global); // Viewer's realize method calls the Custom Manipulator's home() method: window_mgr_ptr->realize(); window_mgr_global_ptr->realize(); // Set initial camera lateral posn to grid's midpoint and scale its // altitude according to grid's maximal linear dimension: CM_3D_ptr->set_worldspace_center(latlonggrid_ptr->get_world_middle()); CM_3D_ptr->set_eye_to_center_distance( 2*basic_math::max( latlonggrid_ptr->get_xsize(),latlonggrid_ptr->get_ysize())); CM_3D_ptr->update_M_and_Minv(); CM_3D_global_ptr->set_worldspace_center( latlonggrid_ptr->get_world_middle()); CM_3D_global_ptr->set_eye_to_center_distance( 2*basic_math::max( latlonggrid_ptr->get_xsize(),latlonggrid_ptr->get_ysize())); CM_3D_global_ptr->update_M_and_Minv(); // Reset Producer Viewer's horizontal and vertical FOVs so that they // match the *CM_3D_ptr->ViewFrustum's: window_mgr_ptr->process(); window_mgr_ptr->match_viewer_fovs_to_viewfrustum( CM_3D_ptr->get_ViewFrustum_ptr()); while( !window_mgr_ptr->done() && !window_mgr_global_ptr->done() ) { window_mgr_ptr->process(); window_mgr_global_ptr->process(); } // Wait for all cull and draw threads to complete before exiting: delete postgis_databases_group_ptr; delete window_mgr_ptr; delete window_mgr_global_ptr; }
02d7342f65768676d66a2ec015bef55482993b6f
f313c6df81673cfb79c478359d00aad4a38d4c54
/sd-n100f-proto-1-31-01-ps2/Projects/ScoobyDoo/Code/Engine/x/xNMA.cpp
82fdfdf2c8488e9e5142330d3aef0e2208f2b30e
[]
no_license
seilweiss/dwarfdb
2ee1a1d748d83f6d14413bd58312c99059af99bc
9afc2132cd69f11ed6e69bd4b2b67805bc1828b9
refs/heads/main
2023-08-14T23:48:48.254038
2021-10-07T05:40:50
2021-10-07T05:40:50
414,475,004
2
0
null
null
null
null
UTF-8
C++
false
false
2,639
cpp
xNMA.cpp
typedef struct tagxStateLink; typedef struct tagxState; typedef tagxStateLink type_0[1]; typedef tagxStateLink type_1[3]; typedef tagxStateLink type_2[1]; typedef tagxStateLink type_3[1]; typedef uint8 type_4[16]; typedef tagxStateLink type_5[1]; typedef tagxStateLink type_6[1]; typedef tagxStateLink type_7[1]; typedef tagxStateLink type_8[1]; typedef tagxStateLink type_9[1]; typedef tagxStateLink type_10[1]; typedef tagxStateLink type_11[1]; typedef tagxStateLink type_12[1]; typedef uint8 type_13[16]; typedef tagxStateLink type_14[19]; typedef tagxStateLink type_15[1]; typedef tagxStateLink type_16[3]; typedef tagxState type_17[21]; typedef tagxStateLink type_18[1]; typedef tagxStateLink type_19[1]; typedef tagxStateLink type_20[1]; typedef tagxStateLink type_21[1]; typedef tagxStateLink type_22[1]; typedef tagxStateLink type_23[11]; struct tagxStateLink { uint8 m_command; uint8 m_flags; uint16 m_state; }; struct tagxState { uint32 m_assetID; int32 m_animState; uint8* m_activeJoints; int16 m_calloutNumber; uint8 m_enterEvent; uint8 m_exitEvent; int32 m_linkCount; tagxStateLink* m_links; }; uint8 g_nmaJointsAll[16]; uint8 g_nmaJointsUpperOnly[16]; tagxStateLink link_nma_Idle[19]; tagxStateLink link_nma_Run[11]; tagxStateLink link_nma_DodgeLeft[1]; tagxStateLink link_nma_DodgeRight[1]; tagxStateLink link_nma_BlockLeft[1]; tagxStateLink link_nma_BlockRight[1]; tagxStateLink link_nma_AttackMelee[1]; tagxStateLink link_nma_AttackBow[1]; tagxStateLink link_nma_AttackBowQuick[1]; tagxStateLink link_nma_InjuryFrontInIdle[1]; tagxStateLink link_nma_InjuryStrongInIdle[1]; tagxStateLink link_nma_InjuryFrontInRun[1]; tagxStateLink link_nma_InjuryStrongInRun[1]; tagxStateLink link_nma_InjuryInThread[1]; tagxStateLink link_nma_DeathMelee1[1]; tagxStateLink link_nma_DeathRange1[1]; tagxStateLink link_nma_ComboIdle[3]; tagxStateLink link_nma_ComboIdleChainsaw[3]; tagxStateLink link_nma_ComboMissDeath[1]; tagxStateLink link_nma_ComboDeathGun[1]; tagxStateLink link_nma_ComboDeathAxe[1]; tagxState g_nmaStates[21]; void xNMAStateReset(); void xNMAStateInit(); // xNMAStateReset__Fv // Start address: 0x355e10 void xNMAStateReset() { // Line 78, Address: 0x355e10, Func Offset: 0 // Line 80, Address: 0x355e18, Func Offset: 0x8 // Line 82, Address: 0x355e2c, Func Offset: 0x1c // Func End, Address: 0x355e3c, Func Offset: 0x2c } // xNMAStateInit__Fv // Start address: 0x355e40 void xNMAStateInit() { // Line 67, Address: 0x355e40, Func Offset: 0 // Line 69, Address: 0x355e48, Func Offset: 0x8 // Line 70, Address: 0x355e5c, Func Offset: 0x1c // Func End, Address: 0x355e6c, Func Offset: 0x2c }
c4707a0688e5b8f7f6c956b5bd06812620cd30e9
45279dd0d44bfdc3d20af1bf1d92fdc274faa61c
/armstrongN.cpp
c4d82e31353c27bea8f24c17c682861db65f6f35
[]
no_license
varunchopraa/Nagarro-Bootcamp
22753cc29f686513c66f6578d3d8ae2ca9927c56
e8ce07033f7813f1a4ca9197af6725f652d0c3fa
refs/heads/master
2020-12-23T04:11:03.966484
2020-02-10T18:07:12
2020-02-10T18:07:12
237,029,724
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
armstrongN.cpp
//Armstrong No. of order n #include<iostream> #include<math.h> using namespace std; int main() { int n; cin>>n; int temp = n; int arm = 0; int rem; int order = 0; while(n!=0) { n /= 10; order++; } n = temp; while(n!=0) { rem = n%10; arm += pow(rem, order); n /= 10; } if(arm == temp) cout<<"true"; else cout<<"false"; return 0; }
7503447ff7e42a3248f9e3177553604b5e7c18bf
5b4261634cf91be31f0dabeeefa4e35cdd2c2762
/Intersection.hpp
dbee1d80ce0cae8b0f3ad43339ef79e0ccdb15f2
[]
no_license
janssens/PIF
72f57f79d1922d7809ff37a4603109682681a97a
6179b021df3a26c2a167e86d32c3167493fb2d05
refs/heads/master
2021-01-15T12:26:23.808371
2011-06-29T16:24:51
2011-06-29T16:24:51
1,492,353
0
1
null
null
null
null
UTF-8
C++
false
false
7,584
hpp
Intersection.hpp
/* * Polyhedron Intersection Framework * * FileName: Intersection.hpp * Creation: 29.06.2011 * Author: Gaรซtan Janssens * Last Edit: 29.06.2011 * */ #ifndef INTER_H #define INTER_H #define DEBUG #include <iostream> #include <typeinfo> #include <sstream> #include <fstream> #include <string> #include <list> #include <vector> #include <math.h> #include <boost/smart_ptr/shared_ptr.hpp> #include "Type.hpp" #include "Edge.hpp" #include "Face.hpp" namespace pif { template<class T> class Intersection { public: Intersection() {}; Intersection(Edge<T> e,Face<T> f) : _data(new Obj(e,f)){ this->giveFeedback(); }; bool isNull(void) const { return !(bool)_data;}; bool exist(void) const { return _data->exist;}; Vertex<T> getPoint(void) const { return _data->point; }; Face<T> getFace(void) const { return _data->face; }; Edge<T> getEdge(void) const { return _data->edge; }; void giveFeedback(void){ // lets give a feedback to the vertex of the two halfedge behind the edge in order to compute the inside & outside information if ((bool)_data&&!(bool)_data->point.isNull()) { // intersection exist! if (_data->edge.getHalfEdge().getVertex().isClosestIntersectionInSpaceDefined()){//yes if (dist(_data->edge.getHalfEdge().getVertex().getClosestIntersectionInSpace().getPoint(),_data->edge.getHalfEdge().getVertex())>dist(this->getPoint(),_data->edge.getHalfEdge().getVertex())){ // this intersection is the closest so far _data->edge.getHalfEdge().getVertex().setClosestIntersectionInSpace(*this); #ifdef DEBUG std::cout << "=> feedback for " << _data->edge.getHalfEdge().getVertex() << ": " << "the closest intersection is now " << _data->edge.getHalfEdge().getVertex().getClosestIntersectionInSpace().getPoint() << std::endl; #endif } }else{//no _data->edge.getHalfEdge().getVertex().setClosestIntersectionInSpace(*this); // lets defined it #ifdef DEBUG std::cout << "=> feedback for " << _data->edge.getHalfEdge().getVertex() << ":" << "the closest intersection is " << _data->edge.getHalfEdge().getVertex().getClosestIntersectionInSpace().getPoint() << std::endl; #endif } if (_data->edge.getPair().getVertex().isClosestIntersectionInSpaceDefined()){//yes if (dist(_data->edge.getPair().getVertex().getClosestIntersectionInSpace().getPoint(),_data->edge.getPair().getVertex())>dist(this->getPoint(),_data->edge.getPair().getVertex())){ // this intersection is the closest so far _data->edge.getPair().getVertex().setClosestIntersectionInSpace(*this); #ifdef DEBUG std::cout << "=> feedback for " << _data->edge.getPair().getVertex() << ": " << "the closest intersection is now " << _data->edge.getPair().getVertex().getClosestIntersectionInSpace().getPoint() << std::endl; #endif } }else{//no _data->edge.getPair().getVertex().setClosestIntersectionInSpace(*this); // lets defined it #ifdef DEBUG std::cout << "=> feedback for " << _data->edge.getPair().getVertex() << ":" << "the closest intersection is " << _data->edge.getPair().getVertex().getClosestIntersectionInSpace().getPoint() << std::endl; #endif } } }; private: struct Obj{ Vertex<T> point; Edge<T> edge; Face<T> face; bool exist; Obj(Edge<T> e,Face<T> f) { //http://paulbourke.net/geometry/linefacet/ edge = e; face = f; #ifdef DEBUG std::cout << "interesction of" << e << " vs " << f << std::endl; #endif if (face.getNormal().isNull()) face.computeNormal(); T denominator = face.getA()*(edge.getA().getX()-edge.getB().getX()); denominator += face.getB()*(edge.getA().getY()-edge.getB().getY()); denominator += face.getC()*(edge.getA().getZ()-edge.getB().getZ()); if (denominator!=(T)0) { //intersection exist (If the denominator is 0 then the line is parallel to the plane and they don't intersect.) T mu = face.getD() ; mu += face.getA()*edge.getA().getX() ; mu += face.getB()*edge.getA().getY() ; mu += face.getC()*edge.getA().getZ() ; mu /= denominator; mu /= sqrt((double)(face.getA()*face.getA() + face.getB()*face.getB() + face.getC()*face.getC())); Vertex<T> ptmp = edge.getA() + mu *(edge.getB() - edge.getA()); //P = P1 + mu (P2 - P1) bool liesOn = false; HalfEdge<T> firstHalfEdge = face.getHalfEdge(); HalfEdge<T> halfEdge = firstHalfEdge; std::vector<Vertex<T> > vertex; int nvert=0; do{ vertex.push_back(halfEdge.getVertex()); nvert++; halfEdge = halfEdge.getNext(); } while (halfEdge != firstHalfEdge); int i, j; i=0; j=nvert - 1; T tmp_x = abs(face.getNormal().getDx()); T tmp_y = abs(face.getNormal().getDy()); T tmp_z = abs(face.getNormal().getDz()); if (tmp_z>tmp_x&&tmp_z>tmp_y) { // projection on Z axis #ifdef DEBUG std::cout << "projection on Z axis" << " (normal:" << face.getNormal() << ")" << std::endl; #endif for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((vertex[i].getY()>ptmp.getY()) != (vertex[j].getY()>ptmp.getY())) && (ptmp.getX() < (vertex[j].getX()-vertex[i].getX()) * (ptmp.getY()-vertex[i].getY()) / (vertex[j].getY()-vertex[i].getY()) + vertex[i].getX()) ) liesOn = !liesOn; } } else if (tmp_x>tmp_y&&tmp_x>tmp_z) { // projection on X axis #ifdef DEBUG std::cout << "projection on X axis" << " (normal:" << face.getNormal() << ")" << std::endl; #endif for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((vertex[i].getY()>ptmp.getY()) != (vertex[j].getY()>ptmp.getY())) && (ptmp.getZ() < (vertex[j].getZ()-vertex[i].getZ()) * (ptmp.getY()-vertex[i].getY()) / (vertex[j].getY()-vertex[i].getY()) + vertex[i].getZ()) ) liesOn = !liesOn; } } else { // projection on Y axis #ifdef DEBUG std::cout << "projection on Y axis" << " (normal:" << face.getNormal() << ")" << std::endl; #endif for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((vertex[i].getZ()>ptmp.getZ()) != (vertex[j].getZ()>ptmp.getZ())) && (ptmp.getX() < (vertex[j].getX()-vertex[i].getX()) * (ptmp.getZ()-vertex[i].getZ()) / (vertex[j].getZ()-vertex[i].getZ()) + vertex[i].getX()) ) liesOn = !liesOn; } } if (liesOn){ //the intersection of the line vs the face is inside the face point = ptmp; #ifdef DEBUG std::cout << "mu =" << mu << std::endl; #endif if ((mu<1)&&(mu>0)) {//For the intersection point to lie on the line segment, mu must be between 0 and denominator. exist = true; }else{// intersection point doesn't lie on the segment exist = false; #ifdef DEBUG std::cout << "intersection with the plan doesn't lie on the segment" << std::endl; #endif } }else{ #ifdef DEBUG std::cout << "intersection with the plan doesn't lie on the face" << std::endl; #endif exist = false; } }else{ #ifdef DEBUG std::cout << "intersection doesn't exist" << std::endl; #endif exist = false; } }; }; boost::shared_ptr<Obj> _data; }; template<class T> std::ostream& operator<< (std::ostream& o,const Intersection<T> i){ if (i.isNull()) { return o << "(NULL)"; }else{ return o << "int(" << i.getPoint() << ")"; } }; } #endif
d26cd50af03f91e33773b60099bdeadcb4b027ad
4f05236606d5dbd483e5d0ae9e99d82f7eb94636
/ServerNetPackets/NetPacketsGameBrowser.h
d976d82bc278e2747d579b6f652fd1ea90fe5ae1
[]
no_license
Mateuus/newundead
bd59de0b81607c03cd220dced3dac5c6d5d2365f
c0506f26fa7f896ba3b94bb2ae2878517bd0063a
refs/heads/master
2020-06-03T14:20:00.375106
2014-09-23T03:58:13
2014-09-23T03:58:13
22,456,183
5
0
null
null
null
null
UTF-8
C++
false
false
4,526
h
NetPacketsGameBrowser.h
#pragma once #include "r3dNetwork.h" #include "NetPacketsGameInfo.h" namespace NetPacketsGameBrowser { #pragma pack(push) #pragma pack(1) #define GBNET_VERSION (0x00000004 + GBGAMEINFO_VERSION) #define GBNET_KEY1 0x25e022aa // // Game Browser Packet IDs // enum gbpktType_e { GBPKT_ValidateConnectingPeer = r3dNetwork::FIRST_FREE_PACKET_ID, // client vs master server codes GBPKT_C2M_RefreshList, GBPKT_M2C_StartGamesList, GBPKT_M2C_SupervisorData, GBPKT_M2C_GameData, GBPKT_M2C_EndGamesList, GBPKT_C2S_RentGameKick, GBPKT_C2M_BanPlayer, GBPKT_C2M_RentGameChangeSet, GBPKT_C2M_PlayerListEnd, GBPKT_C2M_JoinGameReq, GBPKT_C2M_RentGameReq, GBPKT_C2M_RentGameAns, GBPKT_C2M_RentGameStr, GBPKT_C2M_PlayerListReq, GBPKT_C2M_PlayerListAns, GBPKT_C2M_QuickGameReq, GBPKT_M2C_JoinGameAns, GBPKT_M2C_ServerInfo, GBPKT_M2C_ShutdownNote, GBPKT_LAST_PACKET_ID, }; #if GBPKT_LAST_PACKET_ID > 255 #error Shit happens, more that 255 packet ids #endif #ifndef CREATE_PACKET #define CREATE_PACKET(PKT_ID, VAR) PKT_ID##_s VAR #endif struct GBPKT_ValidateConnectingPeer_s : public r3dNetPacketMixin<GBPKT_ValidateConnectingPeer> { DWORD version; DWORD key1; }; struct GBPKT_C2M_RefreshList_s : public r3dNetPacketMixin<GBPKT_C2M_RefreshList> { }; struct GBPKT_M2C_StartGamesList_s : public r3dNetPacketMixin<GBPKT_M2C_StartGamesList> { }; struct GBPKT_M2C_SupervisorData_s : public r3dNetPacketMixin<GBPKT_M2C_SupervisorData> { GBPKT_M2C_SupervisorData_s& operator=(const GBPKT_M2C_SupervisorData_s& rhs) { memcpy(this, &rhs, sizeof(*this)); return *this; } BYTE region; WORD ID; DWORD ip; }; struct GBPKT_M2C_GameData_s : public r3dNetPacketMixin<GBPKT_M2C_GameData> { GBPKT_M2C_GameData_s& operator=(const GBPKT_M2C_GameData_s& rhs) { memcpy(this, &rhs, sizeof(*this)); return *this; } WORD superId; // ID of supervisor GBGameInfo info; BYTE status; // 0-good. 1-finished, 2-full, 4-too_late, 8-passworded,16-not avail for join int curPlayers; }; struct GBPKT_M2C_EndGamesList_s : public r3dNetPacketMixin<GBPKT_M2C_EndGamesList> { }; struct GBPKT_C2M_JoinGameReq_s : public r3dNetPacketMixin<GBPKT_C2M_JoinGameReq> { GBPKT_C2M_JoinGameReq_s() { pwd[0] = 0; } DWORD CustomerID; DWORD gameServerId; char pwd[16]; }; struct GBPKT_C2M_QuickGameReq_s : public r3dNetPacketMixin<GBPKT_C2M_QuickGameReq> { DWORD CustomerID; BYTE region; // EGBGameRegion BYTE gameMap; // 0xFF for any map }; struct GBPKT_M2C_JoinGameAns_s : public r3dNetPacketMixin<GBPKT_M2C_JoinGameAns> { GBPKT_M2C_JoinGameAns_s& operator=(const GBPKT_M2C_JoinGameAns_s &rhs) { memcpy(this, &rhs, sizeof(*this)); return *this; } enum { rUnknown = 0, rNoGames, rGameFull, rGameFinished, rGameNotFound, rWrongPassword, rLevelTooLow, rLevelTooHigh, rJoinDelayActive, rInputPassword, rOk, }; GBPKT_M2C_JoinGameAns_s() { result = rUnknown; } BYTE result; DWORD ip; WORD port; __int64 sessionId; }; struct GBPKT_M2C_ServerInfo_s : public r3dNetPacketMixin<GBPKT_M2C_ServerInfo> { BYTE serverId; }; struct GBPKT_C2S_RentGameKick_s : public r3dNetPacketMixin<GBPKT_C2S_RentGameKick> { DWORD serverid; char name[32*2]; }; struct GBPKT_M2C_ShutdownNote_s : public r3dNetPacketMixin<GBPKT_M2C_ShutdownNote> { BYTE reason; }; struct GBPKT_C2M_PlayerListEnd_s : public r3dNetPacketMixin<GBPKT_C2M_PlayerListEnd> { }; struct GBPKT_C2M_PlayerListReq_s : public r3dNetPacketMixin<GBPKT_C2M_PlayerListReq> { DWORD serverId; }; struct GBPKT_C2M_PlayerListAns_s : public r3dNetPacketMixin<GBPKT_C2M_PlayerListAns> { char gamertag[32*2]; int alive; int rep; int xp; }; struct GBPKT_C2M_RentGameChangeSet_s : public r3dNetPacketMixin<GBPKT_C2M_RentGameChangeSet> { DWORD gameserverid; char pwd[512]; }; struct GBPKT_C2M_RentGameReq_s : public r3dNetPacketMixin<GBPKT_C2M_RentGameReq> { /*char name[16]; char pwd[16]; int mapid; int slot; int period; int ownercustomerid;*/ }; struct GBPKT_C2M_RentGameAns_s : public r3dNetPacketMixin<GBPKT_C2M_RentGameAns> { int anscode; char msg[128]; }; struct GBPKT_C2M_RentGameStr_s : public r3dNetPacketMixin<GBPKT_C2M_RentGameStr> { char name[16]; char pwd[16]; int mapid; int slot; int period; int ownercustomerid; }; struct GBPKT_C2M_BanPlayer_s : public r3dNetPacketMixin<GBPKT_C2M_BanPlayer> { char name[16]; int customerid; }; #pragma pack(pop) }; // namespace NetPacketsGameBrowser
b206841588a919c13d5b732fc5a876937e5e7133
41a0fa3b6fa55f2c278e06718a04ad38e645dfa0
/CircularArrayRotation.cpp
c539faa32cc53516dfd382f768566448fad04a7b
[]
no_license
sharmarajdaksh/cp
d3a42bca8349fd958f2a3f19a173980d4aa94e44
c0f900e14a4f502c647b0f40c2b00871e2fd43de
refs/heads/master
2023-07-28T22:04:02.357209
2021-09-13T14:59:50
2021-09-13T14:59:50
277,243,723
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
CircularArrayRotation.cpp
#include <bits/stdc++.h> using namespace std; int main() { /* Faster IO */ ios_base::sync_with_stdio(false); cin.tie(NULL); /* Faster IO */ unsigned long n, k, q, i, t; vector<unsigned long> a; cin >> n >> k >> q; for (i = 0; i < n; ++i) { cin >> t; a.push_back(t); } while (q > 0) { cin >> t; cout << a[(t - (k % n) + n) % n] << '\n'; --q; } return 0; }
3a27533068258cb65dcc3825857f0452fa26c338
b8263b1abe81388082a67a8cf2895c1a8e5610b0
/ejemplosGraficacion/08_MiDibujo3D.cpp
7e6feb1e58ad5e9b6497a5bb81a229d8a9de24a5
[]
no_license
MasterBlck/opengl-programs
5cd35bad7d86f56f448334df11356859af02682b
7eadf2147ba9e15d7a42d56ab3757a81924a363b
refs/heads/main
2023-06-05T06:10:50.028086
2021-06-14T03:15:06
2021-06-14T03:15:06
376,687,422
0
0
null
null
null
null
UTF-8
C++
false
false
12,507
cpp
08_MiDibujo3D.cpp
#include <windows.h> #include <GL/glut.h> float alpha, beta; int x0, y0; //Menu de figuras a elegir typedef enum{L1,L2,L3,L4,S1,S2}opcionMenu; //Matriz de colores float colores[9][3]= { {0.0,0.0,0.0}, //0 negro {1.0,0.0,0.0}, //1 rojo {0.0,1.0,0.0}, //2 verde {1.0,1.0,0.0}, //3 amarillo {0.0,0.5,1.0}, //4 azul {1.0,0.0,1.0}, //5 magenta {0.0,1.0,1.0}, //6 cian {1.0,1.0,1.0}, //7 blanco {0.9,0.9,0.9} //8 gris }; int color = 7; int colorf = 0; int colorl = 3; void plasticoRojo(); void plasticoNegro(); void plataBrillante(); void plata(); void cobre(); void brass(); void turqueza(); void obsidianaRoja(); void tracktor(void) { //VENTANAS glPushMatrix(); turqueza(); glScalef(1.0, 1.0, 0.9); glPushMatrix(); glTranslatef(-0.55, 0.825, 0.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.65, 1.0); glVertex3f(-0.4, 0.0, 1.0); glEnd(); glPopMatrix(); glPushMatrix(); glTranslatef(-0.55, 0.825, -2.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.65, 1.0); glVertex3f(-0.4, 0.0, 1.0); glEnd(); glPopMatrix(); //PARABRISAS glPushMatrix(); glTranslatef(-0.55, 0.825, 0.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.65, 1.0); glVertex3f(-0.4, 0.0, 1.0); glVertex3f(-0.4, 0.0, -1.0); glVertex3f(0.0, 0.65, -1.0); glEnd(); glPopMatrix(); //VENTANAS TRASERAS glPushMatrix(); glTranslatef(0.4, 0.0, 0.0); glRotatef(180, 0.0, 1.0, 0.0); glPushMatrix(); glTranslatef(-0.55, 0.825, 0.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.65, 1.0); glVertex3f(-0.3, 0.0, 1.0); glEnd(); glPopMatrix(); glPushMatrix(); glTranslatef(-0.55, 0.825, -2.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.0, 1.0); glVertex3f(0.0, 0.65, 1.0); glVertex3f(-0.3, 0.0, 1.0); glEnd(); glPopMatrix(); //PARABRISAS TRASERO glPushMatrix(); glTranslatef(-0.55, 0.825, 0.0); glBegin(GL_POLYGON); glVertex3f(0.0, 0.65, 1.0); glVertex3f(-0.3, 0.0, 1.0); glVertex3f(-0.3, 0.0, -1.0); glVertex3f(0.0, 0.65, -1.0); glEnd(); glPopMatrix(); glPopMatrix(); glPopMatrix(); //CABINA glPushMatrix(); plasticoRojo(); glTranslatef(0.2, 1.5, 0.0); glScalef(1.5, 0.1, 1.9); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); plasticoRojo(); glTranslatef(0.7, 1.15, 0.0); glScalef(0.7, 0.655, 1.9); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); turqueza(); glTranslatef(0.2, 1.15, 0.0); glScalef(1.5, 0.65, 1.8); glutSolidCube(1.0); glPopMatrix(); //CHACIS glPushMatrix(); plasticoRojo(); glTranslatef(0.0, 0.5, 0.0); glScalef(3.0, 0.65, 2.0); glutSolidCube(1.0); glPopMatrix(); //DEFENSA glPushMatrix(); plataBrillante(); glTranslatef(0.0, 0.0, 0.0); glScalef(3.5, 0.6, 2.5); glutSolidSphere(0.5, 45, 45); glPopMatrix(); glPushMatrix(); plataBrillante(); glTranslatef(0.0, 0.0, 0.0); glScalef(3.25, 0.35, 2.1); glutSolidCube(1.0); glPopMatrix(); //FAROS DELANTEROS brass(); glPushMatrix(); glTranslatef(-1.5, 0.6, 0.8); glScalef(0.15, 0.40, 0.40); glutSolidSphere(0.5, 45, 45); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0.6, -0.8); glScalef(0.15, 0.40, 0.40); glutSolidSphere(0.5, 45, 45); glPopMatrix(); plata(); glPushMatrix(); glTranslatef(-1.5, 0.37, 0.0); glScalef(0.05, 0.50, 0.10); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0.37, 0.12); glScalef(0.05, 0.50, 0.07); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0.37, 0.22); glScalef(0.05, 0.50, 0.07); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0.37, -0.12); glScalef(0.05, 0.50, 0.07); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); glTranslatef(-1.5, 0.37, -0.22); glScalef(0.05, 0.50, 0.07); glutSolidCube(1.0); glPopMatrix(); //FAROS TRASEROS obsidianaRoja(); glPushMatrix(); glTranslatef(1.45, 0.6, 0.8); glScalef(0.15, 0.35, 0.45); glutSolidCube(1.0); glPopMatrix(); glPushMatrix(); glTranslatef(1.45, 0.6, -0.8); glScalef(0.15, 0.35, 0.45); glutSolidCube(1.0); glPopMatrix(); //LLANTAS glLineWidth(0.5); plasticoNegro(); glPushMatrix(); glTranslatef(-1.0, -0.5, -0.75); glRotatef(180.0, 1.0, 1.0, 0.0); glScalef(1.0, 1.0, 1.0); glutSolidTorus(0.25, 0.5, 25, 25); glPopMatrix(); glPushMatrix(); glTranslatef(1.0, -0.5, -0.75); glRotatef(180.0, 1.0, 1.0, 0.0); glScalef(1.0, 1.0, 1.0); glutSolidTorus(0.25, 0.5, 25, 25); glPopMatrix(); glPushMatrix(); glTranslatef(-1.0, -0.5, 0.75); glRotatef(180.0, 1.0, 1.0, 0.0); glScalef(1.0, 1.0, 1.0); glutSolidTorus(0.25, 0.5, 25, 25); glPopMatrix(); glPushMatrix(); glTranslatef(1.0, -0.5, 0.75); glRotatef(180.0, 1.0, 1.0, 0.0); glScalef(1.0, 1.0, 1.0); glutSolidTorus(0.25, 0.5, 25, 25); glPopMatrix(); } void luzCero(void) { GLfloat l_a_color[]={colores[7][0], colores[7][1], colores[7][2], 1.0f}; GLfloat l_difusa[]={colores[7][0], colores[7][1], colores[7][2], 1.0f}; GLfloat l_especular[]={colores[7][0], colores[7][1], colores[7][2], 1.0f}; GLfloat l_posicion[]={10.0, 10.0, 10.0, 0.0}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT,l_a_color); glLightfv(GL_LIGHT0, GL_DIFFUSE, l_difusa); glLightfv(GL_LIGHT0, GL_SPECULAR, l_difusa); glLightfv(GL_LIGHT0, GL_POSITION, l_posicion); glLightfv(GL_LIGHT0, GL_AMBIENT, l_a_color); glEnable (GL_LIGHT0); } void luzUno(void) { GLfloat l_difusa[]={colores[8][0], colores[8][1], colores[8][2], 1.0f}; GLfloat l_especular[]={colores[8][0], colores[8][1], colores[8][2], 1.0f}; GLfloat l_posicion[]={-5.0, 0.0, 5.0, 1.0}; glLightfv(GL_LIGHT1, GL_DIFFUSE, l_difusa); glLightfv(GL_LIGHT1, GL_SPECULAR, l_difusa); glLightfv(GL_LIGHT1, GL_POSITION, l_posicion); //glEnable (GL_LIGHT1); } void luzDos(void) { GLfloat l_difusa[]={colores[4][0], colores[4][1], colores[4][2], 1.0f}; GLfloat l_especular[]={colores[4][0], colores[4][1], colores[4][2], 1.0f}; GLfloat l_posicion[]={5.0, 0.0, 5.0, 1.0}; glLightfv(GL_LIGHT2, GL_DIFFUSE, l_difusa); glLightfv(GL_LIGHT2, GL_SPECULAR, l_difusa); glLightfv(GL_LIGHT2, GL_POSITION, l_posicion); //glEnable (GL_LIGHT2); } void luzTres(void) { GLfloat l_difusa[]={1.0, 1.0, 1.0, 1.0f}; GLfloat l_especular[]={1.0, 1.0, 1.0, 1.0f}; GLfloat l_posicion[]={0.0, 0.0, 5.0, 1.0}; //GLfloat spot_direccion[]={0.0, 0.0, 0.0, 0.0}; glLightfv(GL_LIGHT3, GL_DIFFUSE, l_difusa); glLightfv(GL_LIGHT3, GL_SPECULAR, l_difusa); glLightfv(GL_LIGHT3, GL_POSITION, l_posicion); glLightf(GL_LIGHT3, GL_SPOT_CUTOFF, 11.0); glLightf(GL_LIGHT3, GL_SPOT_EXPONENT, 0.0); //glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, spot_direccion); //glEnable (GL_LIGHT3); } void plasticoRojo() { GLfloat l_ambiente[]={0.0f, 0.0f, 0.0f, 1.0f}; GLfloat l_difusa[]={0.5f, 0.0f, 0.0f, 1.0f}; GLfloat l_especular[]={0.7f, 0.6f, 0.6f, 1.0f}; GLfloat brillo[]={32.0}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void plasticoNegro() { GLfloat l_ambiente[]={0.02f, 0.02f, 0.02f, 1.0f}; GLfloat l_difusa[]={0.01f, 0.01f, 0.01f, 1.0f}; GLfloat l_especular[]={0.4f, 0.4f, 0.4f, 1.0f}; GLfloat brillo[]={10.0}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void plata() { GLfloat l_ambiente[]={0.19225f, 0.19225f, 0.19225f, 1.0f}; GLfloat l_difusa[]={0.50754f, 0.50754f, 0.50754f, 1.0f}; GLfloat l_especular[]={0.508273f, 0.508273f, 0.508273f, 1.0f}; GLfloat brillo[]={51.2}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void plataBrillante() { GLfloat l_ambiente[]={0.23125f, 0.23125f, 0.23125f, 1.0f}; GLfloat l_difusa[]={0.2775f, 0.2775f, 0.2775f, 1.0f}; GLfloat l_especular[]={0.773911f, 0.773911f, 0.773911f, 1.0f}; GLfloat brillo[]={89.6}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void cobre() { GLfloat l_ambiente[]={0.19125f, 0.0735f, 0.0225f, 1.0f}; GLfloat l_difusa[]={0.7038f, 0.27048f, 0.0828f, 1.0f}; GLfloat l_especular[]={0.256777f, 0.137622f, 0.086014f, 1.0f}; GLfloat brillo[]={12.8}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void brass() { GLfloat l_ambiente[]={0.329412f, 0.223529f, 0.027451f, 1.0f}; GLfloat l_difusa[]={0.780932f, 0.568627f, 0.113725f, 1.0f}; GLfloat l_especular[]={0.992157f, 0.941176f, 0.807843f, 1.0f}; GLfloat brillo[]={27.8974}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void turqueza() { GLfloat l_ambiente[]={0.1f, 0.18725f, 0.1745f, 0.8f}; GLfloat l_difusa[]={0.396f, 0.74151f, 0.69102f, 0.8f}; GLfloat l_especular[]={0.297254f, 0.30829f, 0.306678f, 0.8f}; GLfloat brillo[]={12.8}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void obsidianaRoja() { GLfloat l_ambiente[]={1.0f, 0.1f, 0.1f, 0.82f}; GLfloat l_difusa[]={1.0f, 0.1f, 0.01f, 0.82f}; GLfloat l_especular[]={0.332741f, 0.328634f, 0.346435f, 0.82f}; GLfloat brillo[]={38.4}; glMaterialfv(GL_FRONT, GL_AMBIENT, l_ambiente); glMaterialfv(GL_FRONT, GL_DIFFUSE, l_difusa); glMaterialfv(GL_FRONT, GL_SPECULAR, l_especular); glMaterialfv(GL_FRONT, GL_SHININESS, brillo); } void init(void) { luzCero(); //luzUno(); //luzDos(); //luzTres(); glEnable(GL_LIGHTING); glEnable(GL_NORMALIZE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); } void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //PARAMETROS DE gluPerspective(float alpha, float aspect, float near, float far); //angulo de vision vertical(y) //relaciรณn entre angulo de vision horizontal y vertical (altura/anchura) //La relaciรณn entre far/near deberรญa ser lo mรกs cercana posible a 1 gluPerspective(65.0, 1.0, 1.0, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0f, 0.0f, 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); glPushMatrix(); glRotatef(alpha, 1.0f, 0.0f, 0.0f); glRotatef(beta, 0.0f, 1.0f, 0.0f); tracktor(); glPopMatrix(); glFlush(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { if ( (button == GLUT_LEFT_BUTTON) & (state == GLUT_DOWN) ) { x0 = x; y0 = y; } } void onMotion(int x, int y) { alpha = (alpha + (y - y0)); beta = (beta + (x - x0)); x0 = x; y0 = y; glutPostRedisplay(); } void menuFiguras(int opcion) { switch(opcion) { case L1: glEnable(GL_LIGHT1); break; case L2: glEnable(GL_LIGHT2); break; case L3: glDisable(GL_LIGHT1); break; case L4: glDisable(GL_LIGHT2); break; case S1: glEnable(GL_LIGHT3); break; case S2: glDisable(GL_LIGHT3); break; } luzCero(); luzUno(); luzDos(); luzTres(); glutPostRedisplay(); } void creacionMenu(void) { int menuLUCES, menuMain; int on, off; on = glutCreateMenu(menuFiguras); glutAddMenuEntry("Luz 1", L1); glutAddMenuEntry("Luz 2", L2); glutAddMenuEntry("Spot", S1); off = glutCreateMenu(menuFiguras); glutAddMenuEntry("Luz 1", L3); glutAddMenuEntry("Luz 2", L4); glutAddMenuEntry("Spot", S2); menuLUCES = glutCreateMenu(menuFiguras); glutAddSubMenu("Activar", on); glutAddSubMenu("Desactivar", off); menuMain = glutCreateMenu(menuFiguras); glutAddSubMenu("Luces", menuLUCES); glutAttachMenu(GLUT_RIGHT_BUTTON); } main(void) { glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutCreateWindow("Camioneta 3D"); init(); glutDisplayFunc(display); glutMouseFunc(onMouse); glutMotionFunc(onMotion); creacionMenu(); glutMainLoop(); }
77ce3d558879c32180f0b44bdf79c918170ccbcd
b1e67e65aed6dae759db870259e3c5dca3ead8db
/Codes/OrganizedData.cpp
70044b35dfcfbe8d1a21460cb3019cd2c088aea6
[]
no_license
qminh93/RVGP
a558a1368cd036b82c7e561d195e224e284587fb
0d247a0f193fb53206f861ab51441fd646303442
refs/heads/master
2021-01-23T22:07:41.247611
2015-05-31T01:39:28
2015-05-31T01:39:28
36,595,832
2
1
null
null
null
null
UTF-8
C++
false
false
4,833
cpp
OrganizedData.cpp
#include "OrganizedData.h" #include "kmean.h" OrganizedData::OrganizedData() { train.clear(); test.clear(); support.clear(); hyper = new HyperParams(); nTrain = nTest = nSupport = nDim = nBlock = 0; } OrganizedData::~OrganizedData() { train.clear(); test.clear(); support.clear(); } void OrganizedData::save(vs dataset) { train.save (dataset[0].c_str(),arma_binary); test.save (dataset[1].c_str(),arma_binary); support.save (dataset[2].c_str(),arma_binary); hyper->save (dataset[3].c_str()); } void OrganizedData::load(vs dataset) { train.load (dataset[0].c_str(),auto_detect); test.load (dataset[1].c_str(),auto_detect); support.load (dataset[2].c_str(),auto_detect); hyper->load (dataset[3].c_str()); nBlock = train.n_rows; nSupport = getxm().n_rows; for (int i = 0; i < nBlock; i++) { nDim = getxb(i).n_cols; nTrain += getxb(i).n_rows; nTest += getxt(i).n_rows; } } void OrganizedData::loadHyp(string hypfile, string mode) { if (mode == "csv") hyper->loadcsv(hypfile.c_str()); else hyper->load(hypfile.c_str()); } void OrganizedData::process(RawData* raw, int nBlock, double pTest, int nSupport) { int nData = raw->nData, nDim = raw->nDim - 1; this->nSupport = nSupport; this->nBlock = nBlock; this->nDim = nDim; train = field<mat>(nBlock,2); test = field<mat>(nBlock,2); support = field<mat>(1,2); mat xm(nSupport,nDim), ym(nSupport,1); vec mark(nData); mark.fill(0); printf("Randomly selecting %d supporting point ...\n", nSupport); for (int i = 0; i < nSupport; i++) { int pos = IRAND(0, nData - 1); while (mark[pos] > 0) pos = IRAND(0, nData - 1); mark[pos] = 1; for (int j = 0; j < nDim; j++) xm(i, j) = raw->X(pos,j); ym(i,0) = raw->X(pos,nDim); } support(0,0) = xm; xm.clear(); support(0,1) = ym; ym.clear(); cout << "Partitioning the remaining data into " << nBlock << " cluster using K-Mean ..." << endl; vvd _remain; for (int i = 0; i < nData; i++) if (!mark(i)) { rowvec R = raw->X.row(i); _remain.push_back(r2v(R)); } mat remaining = v2m(_remain); mark.clear(); RawData* remain = new RawData(remaining); KMean* partitioner = new KMean(remain); Partition* clusters = partitioner->cluster(nBlock); cout << "Packaging training/testing data points into their respective cluster" << endl; for (int i = 0; i < nBlock; i++) { cout << "Processing block " << i + 1 << endl; int bSize = (int) clusters->member[i].size(), tSize = (int) floor(bSize * pTest), pos = 0, counter = 0; mark = vec(bSize); mark.fill(0); if (bSize > tSize) // if we can afford to draw tSize test points from this block without depleting it ... { mat xt(tSize,nDim), yt(tSize,1); for (int j = 0; j < tSize; j++) { pos = IRAND(0, bSize - 1); while (mark[pos] > 0) pos = IRAND(0, bSize - 1); mark[pos] = 1; pos = clusters->member[i][pos]; for (int t = 0; t < nDim; t++) xt(j, t) = remain->X(pos,t); yt(j,0) = remain->X(pos,nDim); } bSize -= tSize; nTest += tSize; test(i,0) = xt; xt.clear(); test(i,1) = yt; yt.clear(); } nTrain += bSize; mat xb(bSize,nDim), yb(bSize,1); //cout << remain->X.n_rows << endl; for (int j = 0; j < (int)mark.n_elem; j++) if (mark[j] < 1) { for (int t = 0; t < nDim; t++) { xb(counter,t) = remain->X(clusters->member[i][j],t); } yb(counter++,0) = remain->X(clusters->member[i][j],nDim); } train(i,0) = xb; xb.clear(); train(i,1) = yb; yb.clear(); mark.clear(); printf("Done ! nData[%d] = %d, nTrain[%d] = %d, nTest[%d] = %d .\n", i, (int) clusters->member[i].size(), i, train(i,0).n_rows, i, (int) test(i,0).n_rows); } } mat OrganizedData::getxb(int i) { return train(i,0); } mat OrganizedData::getyb(int i) { return train(i,1); } mat OrganizedData::getxt(int i) { return test(i,0); } mat OrganizedData::getyt(int i) { return test(i,1); } mat OrganizedData::getxm() { return support(0,0); } mat OrganizedData::getym() { return support(0,1); } mat OrganizedData::kparams() { return hyper->kparams(); } double OrganizedData::mean() { return hyper->mean(); } double OrganizedData::noise() { return hyper->noise(); } double OrganizedData::signal() { return hyper->signal(); } double OrganizedData::ls(int i) { return hyper->ls(i); }
52620c08ddae82b3ecb1c14fe83a715d4bba3ceb
f23dd325d01c0b32493398263f4e19e363fccd01
/Server_2014-7-8/Venus3D/Source/VePower/VeFile.cpp
9f2c0c47540a59b749e72df1a1330407d6f853da
[]
no_license
snailwork/Texas-cs
b27b95b739e781a1af0dbbc716fdf1e59c9ba08c
bdbd663e4cf3d0ef4a79c919b4fa8a09ece59fcc
refs/heads/master
2020-04-15T22:30:47.022466
2015-08-08T14:44:17
2015-08-08T14:44:17
41,007,333
2
2
null
null
null
null
UTF-8
C++
false
false
13,196
cpp
VeFile.cpp
//////////////////////////////////////////////////////////////////////////// // // Venus Engine Source File. // Copyright (C), Venus Interactive Entertainment.2012 // ------------------------------------------------------------------------- // File name: VeFile.cpp // Version: v1.00 // Created: 6/10/2012 by Napoleon // Compilers: Visual Studio.NET // Description: // ------------------------------------------------------------------------- // History: // http://www.venusie.com //////////////////////////////////////////////////////////////////////////// #include "VePowerPCH.h" //-------------------------------------------------------------------------- VeFileIStream::VeFileIStream(const VeChar8* pcFileName, VeInt32 i32Cache) : m_pkFile(NULL), m_pbyCache(NULL), m_i32FileSize(0), m_i32CacheSize(i32Cache) , m_i32Pointer(0), m_i32CachePointer(0), m_i32CacheUse(0) { if(VE_SUCCEEDED(VeAccess(pcFileName, VeDirectory::ACCESS_F_OK))) { #if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM) fopen_s(&m_pkFile, pcFileName, "rb"); #else m_pkFile = fopen(pcFileName, "rb"); #endif if(m_pkFile) { UpdateLenth(); VE_ASSERT(m_i32CacheSize > 0); m_pbyCache = VeAlloc(VeByte, m_i32CacheSize); VE_ASSERT(m_pbyCache); return; } } SetError(true); } //-------------------------------------------------------------------------- VeFileIStream::~VeFileIStream() { Finish(); } //-------------------------------------------------------------------------- VeInt32 VeFileIStream::Read(void* pvBuffer, VeInt32 i32Bytes) { VE_ASSERT(pvBuffer && (i32Bytes > 0)); VeInt32 i32Cached = Cached(); VeInt32 i32Res(0); { VeInt32 i32Space = m_i32Pointer < m_i32FileSize ? m_i32FileSize - m_i32Pointer : 0; i32Bytes = (i32Space >= i32Bytes) ? i32Bytes : i32Space; } while(i32Bytes) { if(i32Cached <= 0) { CacheReload(); i32Cached = m_i32CacheUse; } if(i32Bytes <= i32Cached) { VeCrazyCopy((VeChar8*)pvBuffer + i32Res, (VeChar8*)m_pbyCache + m_i32Pointer - m_i32CachePointer, i32Bytes); i32Res += i32Bytes; m_i32Pointer += i32Bytes; i32Bytes = 0; break; } else { VeCrazyCopy((VeChar8*)pvBuffer + i32Res, (VeChar8*)m_pbyCache + m_i32Pointer - m_i32CachePointer, i32Cached); i32Res += i32Cached; m_i32Pointer += i32Cached; i32Bytes -= i32Cached; i32Cached = 0; } } return i32Res; } //-------------------------------------------------------------------------- void* VeFileIStream::Skip(VeInt32 i32Bytes) { VeInt32 i32Skip = VE_MIN(i32Bytes, RemainingLength()); m_i32Pointer += i32Skip; return NULL; } //-------------------------------------------------------------------------- void VeFileIStream::Restart() { m_i32Pointer = 0; } //-------------------------------------------------------------------------- VeInt32 VeFileIStream::RemainingLength() const { return m_i32FileSize - m_i32Pointer; } //-------------------------------------------------------------------------- VeChar8 VeFileIStream::Peek() { if(m_i32Pointer >= m_i32FileSize) { m_bError = true; return -1; } if(!Cached()) { CacheReload(); } return *((VeChar8*)m_pbyCache + m_i32Pointer - m_i32CachePointer); } //-------------------------------------------------------------------------- void VeFileIStream::Finish() { m_i32Pointer = m_i32FileSize; if(m_pkFile) { fclose(m_pkFile); m_pkFile = NULL; } if(m_pbyCache) { VeFree(m_pbyCache); m_pbyCache = NULL; } } //-------------------------------------------------------------------------- void VeFileIStream::CacheReload() { fseek(m_pkFile, m_i32Pointer, SEEK_SET); m_i32CacheUse = (VeInt32)fread(m_pbyCache, 1, m_i32CacheSize, m_pkFile); m_i32CachePointer = m_i32Pointer; } //-------------------------------------------------------------------------- void VeFileIStream::UpdateLenth() { fseek(m_pkFile, 0, SEEK_END); m_i32FileSize = (VeInt32)ftell(m_pkFile); } //-------------------------------------------------------------------------- bool VeFileIStream::IsCached() { return (m_i32Pointer >= m_i32CachePointer) && (m_i32Pointer < (m_i32CachePointer + m_i32CacheUse)); } //-------------------------------------------------------------------------- VeInt32 VeFileIStream::Cached() { return IsCached() ? VeInt32(m_i32CacheUse + m_i32CachePointer - m_i32Pointer) : 0; } //-------------------------------------------------------------------------- VeFileOStream::VeFileOStream(const VeChar8* pcFileName, VeInt32 i32Cache, VeDirectory::WriteType eType) : m_pkFile(NULL), m_pbyCache(NULL), m_i32FileSize(0), m_i32CacheSize(i32Cache), m_i32CachePointer(0) { const VeChar8* pcMode = (eType == VeDirectory::WRITE_CREATE_COVER) ? "wb" : "ab"; #if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM) fopen_s(&m_pkFile, pcFileName, pcMode); #else m_pkFile = fopen(pcFileName, pcMode); #endif VE_ASSERT(m_pkFile); VE_ASSERT(m_i32CacheSize > 0); m_pbyCache = VeAlloc(VeByte, m_i32CacheSize); VE_ASSERT(m_pbyCache); } //-------------------------------------------------------------------------- VeFileOStream::~VeFileOStream() { if(m_pkFile) { WriteBackCache(); fclose(m_pkFile); m_pkFile = NULL; } if(m_pbyCache) { VeFree(m_pbyCache); m_pbyCache = NULL; } } //-------------------------------------------------------------------------- VeInt32 VeFileOStream::Write(const void* pvBuffer, VeInt32 i32Bytes) { VE_ASSERT(pvBuffer && (i32Bytes > 0)); const VeInt32 i32Res = i32Bytes; const VeChar8* pcBuffer = (const VeChar8*)pvBuffer; if(HasCacheUse()) { VeInt32 i32Cache = VE_MIN(CacheCanUse(), i32Bytes); VeCrazyCopy(Cache(), pcBuffer, i32Cache); pcBuffer += i32Cache; m_i32FileSize += i32Cache; i32Bytes -= i32Cache; WriteBackCache(); } if(i32Bytes >= m_i32CacheSize) { fwrite(pcBuffer, 1, i32Bytes, m_pkFile); m_i32FileSize += i32Bytes; m_i32CachePointer = m_i32FileSize; } else { VeCrazyCopy(Cache(), pcBuffer, i32Bytes); m_i32FileSize += i32Bytes; } return i32Res; } //-------------------------------------------------------------------------- VeInt32 VeFileOStream::Size() const { return m_i32FileSize; } //-------------------------------------------------------------------------- bool VeFileOStream::HasCacheUse() { VE_ASSERT(m_i32FileSize >= m_i32CachePointer); return m_i32FileSize > m_i32CachePointer; } //-------------------------------------------------------------------------- VeInt32 VeFileOStream::CacheUse() { return m_i32FileSize - m_i32CachePointer; } //-------------------------------------------------------------------------- VeInt32 VeFileOStream::CacheCanUse() { return m_i32CacheSize - CacheUse(); } //-------------------------------------------------------------------------- VeByte* VeFileOStream::Cache() { return m_pbyCache + CacheUse(); } //-------------------------------------------------------------------------- void VeFileOStream::WriteBackCache() { fwrite(m_pbyCache, 1, CacheUse(), m_pkFile); m_i32CachePointer = m_i32FileSize; } //-------------------------------------------------------------------------- VeFileDir::VeFileDir(const VeChar8* pcName) : VeDirectory(pcName) { VE_ASSERT(VE_SUCCEEDED(VeAccess(m_kName, ACCESS_F_OK))); } //-------------------------------------------------------------------------- VeFileDir::~VeFileDir() { } //-------------------------------------------------------------------------- bool VeFileDir::Access(VeUInt32 u32Flag) const { return VE_SUCCEEDED(VeAccess(m_kName, u32Flag)); } //-------------------------------------------------------------------------- bool VeFileDir::HasFile(const VeChar8* pcFileName) const { VeStringA kFilePath = m_kName + "/" + pcFileName; bool bRes = false; #if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM) _finddata_t kData; VeSizeT stHandle = _findfirst(kFilePath, &kData); if((stHandle != VE_ELF) && ((kData.attrib & 0xf0) == _A_ARCH)) { bRes = true; } #else struct stat kBuf; if(VE_SUCCEEDED(lstat(kFilePath, &kBuf))) { bRes = S_ISREG(kBuf.st_mode); } #endif return bRes; } //-------------------------------------------------------------------------- bool VeFileDir::HasDirectory(const VeChar8* pcDirName) const { VeStringA kFilePath = m_kName + "/" + pcDirName; bool bRes = false; #if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM) _finddata_t kData; VeSizeT stHandle = _findfirst(kFilePath, &kData); if((stHandle != VE_ELF) && ((kData.attrib & 0xf0) == _A_SUBDIR)) { bRes = true; } #else struct stat kBuf; if(VE_SUCCEEDED(lstat(kFilePath, &kBuf))) { bRes = S_ISDIR(kBuf.st_mode); } #endif return bRes; } //-------------------------------------------------------------------------- bool VeFileDir::Change(const VeChar8* pcDirName, bool bCreate) { if(HasDirectory(pcDirName)) { m_kName += "/"; m_kName += pcDirName; return true; } else if(bCreate && Access(ACCESS_W_OK)) { VeStringA kDirName = m_kName + "/" + pcDirName; if(VE_SUCCEEDED(VeMakeDirectory(kDirName))) { m_kName = kDirName; return true; } else { return false; } } else { return false; } } //-------------------------------------------------------------------------- VeDirectory::Type VeFileDir::GetType() const { return VeDirectory::TYPE_FILE; } //-------------------------------------------------------------------------- VeBinaryIStreamPtr VeFileDir::OpenSync(const VeChar8* pcFileName) const { if(HasFile(pcFileName)) { VeStringA kFilePath = m_kName + "/" + pcFileName; return VE_NEW VeFileIStream(kFilePath); } else { return NULL; } } //-------------------------------------------------------------------------- void VeFileDir::ReadAsync(const VeChar8* pcFileName, ReadDelegate& kDelegate) const { VeStringA kFilePath = m_kName + "/" + pcFileName; ReadTask* pkTask = VE_NEW ReadTask(kFilePath, kDelegate); g_pResourceManager->AddBGTask(VeResourceManager::BG_QUEUE_FILE, pkTask); } //-------------------------------------------------------------------------- void VeFileDir::WriteAsync(const VeChar8* pcFileName, const VeMemoryOStreamPtr& spContent, WriteDelegate& kDelegate, WriteType eType) const { VeStringA kFilePath = m_kName + "/" + pcFileName; WriteTask* pkTask = VE_NEW WriteTask(kFilePath, spContent, kDelegate, eType); g_pResourceManager->AddBGTask(VeResourceManager::BG_QUEUE_FILE, pkTask); } //-------------------------------------------------------------------------- VeFileDir::ReadTask::ReadTask(const VeChar8* pcFullPath, ReadDelegate& kDelegate) : m_kFileFullPath(pcFullPath) { m_kEvent.AddDelegate(kDelegate); } //-------------------------------------------------------------------------- VeFileDir::ReadTask::~ReadTask() { } //-------------------------------------------------------------------------- void VeFileDir::ReadTask::DoBackgroundTask(VeBackgroundTaskQueue& kMgr) { if(VE_SUCCEEDED(VeAccess(m_kFileFullPath, ACCESS_R_OK))) { FILE* pkFile(NULL); # if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM) fopen_s(&pkFile, m_kFileFullPath, "rb"); # else pkFile = fopen(m_kFileFullPath, "rb"); # endif if(pkFile) { fseek(pkFile, 0, SEEK_END); VeInt32 i32Len = (VeInt32)ftell(pkFile); fseek(pkFile, 0, SEEK_SET); VeBlobPtr spBlob = VE_NEW VeBlob(i32Len); VeSizeT stRead = fread(spBlob->GetBuffer(), 1, i32Len, pkFile); fclose(pkFile); if(VeInt32(stRead) == i32Len) { m_spData = VE_NEW VeMemoryIStream(spBlob); } } } kMgr.AddMainThreadTask(this); } //-------------------------------------------------------------------------- void VeFileDir::ReadTask::DoMainThreadTask(VeBackgroundTaskQueue& kMgr) { m_kEvent.Callback(m_spData); m_spData = NULL; } //-------------------------------------------------------------------------- VeFileDir::WriteTask::WriteTask(const VeChar8* pcFullPath, const VeMemoryOStreamPtr& spContent, WriteDelegate& kDelegate, VeDirectory::WriteType eType) : m_kFileFullPath(pcFullPath), m_spData(spContent), m_eType(eType) { m_kEvent.AddDelegate(kDelegate); } //-------------------------------------------------------------------------- VeFileDir::WriteTask::~WriteTask() { } //-------------------------------------------------------------------------- void VeFileDir::WriteTask::DoBackgroundTask(VeBackgroundTaskQueue& kMgr) { FILE* pkFile(NULL); const VeChar8* pcMode = (m_eType == VeDirectory::WRITE_CREATE_COVER) ? "wb" : "ab"; # if defined(VE_PLATFORM_WIN) || defined(VE_PLATFORM_MOBILE_SIM) fopen_s(&pkFile, m_kFileFullPath, pcMode); # else pkFile = fopen(m_kFileFullPath, pcMode); # endif if(pkFile) { VeSizeT stWrite = fwrite(m_spData->GetDataForRead(), 1, m_spData->RemainingLength(), pkFile); fclose(pkFile); if(VeInt32(stWrite) == m_spData->RemainingLength()) { m_eResult = VE_S_OK; } else { m_eResult = VE_E_FILE_WRITE; } m_spData->AfterReadData(VeInt32(stWrite)); } else { m_eResult = VE_E_FILE_CREATE; } kMgr.AddMainThreadTask(this); } //-------------------------------------------------------------------------- void VeFileDir::WriteTask::DoMainThreadTask(VeBackgroundTaskQueue& kMgr) { m_spData = NULL; m_kEvent.Callback(m_eResult); } //--------------------------------------------------------------------------
de81c7dada6a55295b633994c44e42d77c4f4cca
882e0f8e3d14ad22c58df00fb8d3887c99fb2d13
/taio/Graph.h
195527d225825cd58c2eb8182b3d7e1b5d8caccc
[]
no_license
khlebous/maximum-common-induced-subgraph
82e61e3f54409243abbc3cd4a3ec1ee8aa4b7f5a
a1b4cc8fc4b1322ba2728606b17558a67ca10cdb
refs/heads/master
2020-04-01T04:46:03.388430
2018-11-20T15:10:02
2018-11-20T15:10:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
Graph.h
#pragma once class Graph { private: size_t vertCount; bool** edges; public: Graph(size_t vertCount, bool** edges) : vertCount(vertCount), edges(edges) {} ~Graph(); size_t verticesCount() { return vertCount; } bool edge(size_t i, size_t j); void setEdge(size_t i, size_t j, bool value); void print(); void printEdges(); };
6e1cad324e96a0aa9435877d9f5c7618b16907a5
34e85d338757cb99c047a9f2d30f6f1982d222ae
/Aulas 1_2018/C++/Adeivis.cpp
a0187a24027d11f82ce210aa070506dbc9b7c1b6
[]
no_license
rafaelaraujobsb/URI-CodeForces
2d1c9b7c7e7e654108c643f883edb9b337a4a4f3
3bf6c6d17d9e78e06c3d61fbf6995f790996dc49
refs/heads/master
2021-09-13T20:12:31.409431
2018-05-03T19:12:27
2018-05-03T19:12:27
126,056,738
1
0
null
null
null
null
UTF-8
C++
false
false
322
cpp
Adeivis.cpp
#include <bits/stdc++.h> using namespace std; int main(){ int n,v, cont=0, maior=0; scanf("%d", &n); vector<int> cds; for(int i=0; i<n; i++){ scanf("%d", &v); cds.push_back(v); if(maior < v){ maior = v; } } for(int i=0; i<n; i++){ cont += maior - cds[i]; } printf("%d\n", cont); return 0; }
284308a4781b811192062f5812e38512146c4f68
de8472c3d42011f440ccc3dc13474a697a13695f
/HEPGenPlusPlus-1.2-RC1/libGKPi0/tableNator.cpp
b13ecd07aeed889bf7637c6bd9fb3b174953d8fe
[]
no_license
drewkenjo/hepgen
17ebfd8c9007662033a1b8c9b9ad57a4fa427d2c
030e2ac23c47d1e3edb4fc6b1900d6aec33eefa1
refs/heads/master
2023-05-25T09:17:33.014437
2023-05-20T06:16:04
2023-05-20T06:16:04
162,611,707
0
0
null
null
null
null
UTF-8
C++
false
false
866
cpp
tableNator.cpp
#include <iostream> #include <cstdio> #include <cstring> #include <ctime> #include <fstream> #include <string> #include <sys/stat.h> #include <unistd.h> int main (int argc, char** argv){ if (argc < 2){ printf("Use me like: %s outFile \n",argv[0]); return -1; } for (double qsq = 2.0; qsq < 16; qsq++){ std::cout << qsq << std::endl; for (double xbjC = 0.005; xbjC < 0.35; xbjC+=0.01){ // for(double tprimCount = -0.1; tprimCount > -0.75; tprimCount-= 0.05){ double tprimCount = -0.30; char buffer[200]; sprintf(buffer,"./libGKPi0/gkCrossSection %f %f %f | grep Final | cut -d':' -f2 >> %s",qsq,xbjC,tprimCount,argv[1]); std::cout << "running: " << buffer << std::endl; system(buffer); } } }
5e4ec1f813cfa781122fa203541e3e54c29279af
da3a2d867984a41270c9e92b38f26967673959c0
/src/Physics.cpp
820cefe92f5c68eaeb28c87425ef70d704bd7502
[]
no_license
andrewrk/motrs
713c1bf05e5fc284da4e23f9a8e53ce60a447c11
f4f0494cf4c76c30b6aeff78bfc89925fb61b541
refs/heads/master
2023-03-13T06:59:08.515898
2012-12-08T19:49:23
2012-12-08T19:49:23
7,071,350
0
1
null
null
null
null
UTF-8
C++
false
false
3,842
cpp
Physics.cpp
#include "Physics.h" #include "Utils.h" #include "Debug.h" void Physics::circleAndCircle(double cx1, double cy1, double r1, double cx2, double cy2, double r2, double & out_dx, double & out_dy) { double distance = Utils::distance(cx1, cy1, cx2, cy2); double minDistance = r1 + r2; double overlap = minDistance - distance; if (overlap > 0.0) { double dx = cx2 - cx1, dy = cy2 - cy1; double normalX = dx / distance, normalY = dy / distance; out_dx = normalX * overlap; out_dy = normalY * overlap; } else { out_dx = 0; out_dy = 0; } } void Physics::squareAndCircle(double cx1, double cy1, double a1, double cx2, double cy2, double r2, double & out_dx, double & out_dy) { // zones: // 0 1 2 // 3 4 5 // 6 7 8 int zoneX = 1 * ((cx1 - a1 < cx2) + (cx1 + a1 < cx2)); int zoneY = 3 * ((cy1 - a1 < cy2) + (cy1 + a1 < cy2)); int zone = zoneX + zoneY; switch (zone) { case 0: pointAndCircle(cx1 - a1 , cy1 - a1 , cx2, cy2, r2, out_dx, out_dy); break; case 1: out_dx = 0.0; out_dy = Utils::min(0.0, (cy1 - a1) - (cy2 + r2)); break; case 2: pointAndCircle(cx1 + a1, cy1 - a1 , cx2, cy2, r2, out_dx, out_dy); break; case 3: out_dx = Utils::min(0.0, (cx1 - a1) - (cx2 + r2)); out_dy = 0.0; break; case 4: // omg inside the square! gtfo! pointAndCircle(cx1, cy1, cx2, cy2, r2 + a1, out_dx, out_dy); break; case 5: out_dx = Utils::max(0.0, (cx1 + a1) - (cx2 - r2)); out_dy = 0.0; break; case 6: pointAndCircle(cx1 - a1 , cy1 + a1, cx2, cy2, r2, out_dx, out_dy); break; case 7: out_dx = 0.0; out_dy = Utils::max(0.0, (cy1 + a1) - (cy2 - r2)); break; case 8: pointAndCircle(cx1 + a1, cy1 + a1, cx2, cy2, r2, out_dx, out_dy); break; default: assert(false); } } void Physics::squareAndSquare(double cx1, double cy1, double a1, double cx2, double cy2, double a2, double &out_dx, double &out_dy) { // zones: // \ 1 / // +-+ // 0 | | 3 // +-+ // / 2 \ (don't warn me about multi-line comments) double minDistance = a1 + a2; out_dx = 0.0; out_dy = 0.0; int zone1 = 1 * (cx1 - cy1 < cx2 - cy2); int zone2 = 2 * (cx1 + cy1 < cx2 + cy2); int zone = zone1 + zone2; switch (zone) { case 0: { double actualDistance = cx1 - cx2; if (actualDistance < minDistance) out_dx = actualDistance - minDistance; } break; case 1: { double actualDistance = cy1 - cy2; if (actualDistance < minDistance) out_dy = actualDistance - minDistance; } break; case 2: { double actualDistance = cy2 - cy1; if (actualDistance < minDistance) out_dy = minDistance - actualDistance; } break; case 3: { double actualDistance = cx2 - cx1; if (actualDistance < minDistance) out_dx = minDistance - actualDistance; } break; default: assert(false); } } void Physics::pointAndCircle(double px1, double py1, double cx2, double cy2, double r2, double &out_dx, double &out_dy) { double distance = Utils::distance(px1, py1, cx2, cy2); double overlap = r2 - distance; if (overlap > 0.0) { double normX = (cx2 - px1) / distance; double normY = (cy2 - py1) / distance; out_dx = normX * overlap; out_dy = normY * overlap; } else { out_dx = 0.0; out_dy = 0.0; } }
925a6c693523c9051bf5b4f237c18e870e6a4890
f5f35d054c2be925771f62f3ce15619ea1ddc27d
/Campion.ro/ucif.cpp
8dc4e0d7434a5612680639787afd32e8bb863ada
[]
no_license
edionu97/Algorithms-DataStructures-ContestsSolutions
fd01f4b00a02c846c50b0316b261c09eb42495ed
a1438543a0ecc551645cdef19694f926532db158
refs/heads/master
2021-06-12T15:41:19.745300
2020-12-02T13:18:03
2020-12-02T13:18:03
128,730,131
1
0
null
null
null
null
UTF-8
C++
false
false
717
cpp
ucif.cpp
#include <fstream> #include <iostream> using namespace std; ifstream f("ucif.in"); ofstream g("ucif.out"); short n; short cifra_imp(short i) {long a=i*i*i,b=i*i*i*i*i,m=1,c,v[100]; v[3]=a%10; c=v[3]; v[5]=b%10; for(short j=5;j<=i;j+=2) {m++; if(m==2)c=v[5],m=0; else c=v[3]; } return c; } short cifra_para(short i) {unsigned a=i*i,b=i*i*i*i,m=1,c,v[100]; v[2]=a%10; c=v[2]; v[4]=b%10; for(short j=6;j<=i;j+=2) {m++; if(m==2){c=v[2];m=0;} else c=v[4]; } return c; } void citire() {f>>n; long s=1; if(n==89)g<<3; else if(n==100)g<<0; else {for(short i=2;i<=n;i++) if((i%10)%2!=0)s+=cifra_imp(i); else if((i%10)%2==0&&i%10!=0)s+=cifra_para(i); g<<s%10; } } int main() {citire(); return 0; }
d68a9b232d63b6bbaa11190bddc09e93a9645a26
74447cbdd07dd95826b8e8c8477d245142ef0d28
/codeChef/cupCake.cpp
8a563d89327bcfb0247ed63996f3d97b9db75aec
[]
no_license
akshay7802/codeChef-C-
d58f57dc9e15cbf4ab14a3957262590be0e83b82
c671ad101789b56659afd52a03370c7b2c96a353
refs/heads/master
2022-12-01T13:16:25.297474
2020-08-15T05:52:20
2020-08-15T05:52:20
287,686,501
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
cupCake.cpp
#include<iostream> using namespace std; int main(){ int t,a; // cout<<"Enter test cases"<<endl; cin>>t; for(int i=0;i<t;i++){ // cout<<"Enter packet size"<<endl; cin>>a; int cc; // cout<<"Enetr cupcakes"<<endl; cin>>cc; int ans=cc-a; cout<<ans<<endl; } }
47bd82e9dc094736e89e81be076dc0b9b7f0b08c
81e49fb3773b9ef92102e54764cb35fd3b74d7bb
/SpaceFighter/GameObject.cpp
359bc3f4479a8e2696a51d8b6a44ca4ee7143b9c
[ "MIT" ]
permissive
issuran/SpaceFighter
b730e18a3b6e5314a8c25a1d3bef4e61df6b4f2b
d0ff09bcb4d91b003d9dba3a7386e39d5471bc00
refs/heads/master
2022-04-05T08:12:24.264026
2019-07-18T00:09:10
2019-07-18T00:09:10
108,918,782
7
0
MIT
2020-01-11T15:13:33
2017-10-30T23:14:46
C++
UTF-8
C++
false
false
515
cpp
GameObject.cpp
#include "GameObject.h" #include "TextureManager.h" GameObject::GameObject(const char* texturesheet, int x, int y) { objTexture = TextureManager::LoadTexture(texturesheet); xpos = x; ypos = y; } void GameObject::Update() { xpos++; ypos++; srcRect.h = 106; srcRect.w = 36; srcRect.x = 0; srcRect.y = 0; destRect.x = xpos; destRect.y = ypos; destRect.w = srcRect.w * 2; destRect.h = srcRect.h * 2; } void GameObject::Render() { SDL_RenderCopy(Game::renderer, objTexture, &srcRect, &destRect); }
6523f9af5d3bbe628f15432f5de9589f648655ab
a59b827169c90993a475466010c87641a3b62982
/M5Stack-Pomodoro.ino
3dfeaff4d69ae62ab60243d6d37a7cd9fb92a337
[ "MIT" ]
permissive
lunard/M5Stack-Pomodoro
567c1bd10e143721c184c272827ce767bcdcefef
4a6d7b5d244ee270796cdf48575f1e5e5a648114
refs/heads/master
2021-03-21T00:52:08.062835
2020-04-04T09:50:49
2020-04-04T09:50:49
247,249,051
2
0
null
null
null
null
UTF-8
C++
false
false
14,046
ino
M5Stack-Pomodoro.ino
/********************************************* * Author Luca Nardelli (lunard@gmail.com) * * Description: the project aims to create a funny (and I hope usefult) pomodoro with the M5Stack Dev Kit ********************************************/ // define must ahead #include <M5Stack.h> #define M5STACK_MPU6886 #include <Free_Fonts.h> #include <M5Display.h> #include <M5Stack.h> #include <WiFiHelper.h> #include <ArduinoJson.h> #include <SD.h> // IMU data // Global variables float IMUTreshhold = 0.85; float IMUTreshhold2 = 0.3; float accX = 0.0F; float accY = 0.0F; float accZ = 0.0F; float gyroX = 0.0F; float gyroY = 0.0F; float gyroZ = 0.0F; float pitch = 0.0F; float roll = 0.0F; float yaw = 0.0F; float temp = 0.0F; // refresh timer unsigned long refreshOrientationTimeout = 500; unsigned long lastRefreshOrientation = 0; int lastOrientation = -1; #define ORIENTATION_UP 1 #define ORIENTATION_DOWN 2 #define ORIENTATION_LEFT 3 #define ORIENTATION_RIGHT 4 #define TICK_CONTEINER_HEIGHT_IN_PX 190 #define TICK_CONTEINER_WIDTH_IN_PX 160 int tickDurationInSec = 300; int currentTick = 0; unsigned long lastTickCheck = 0; unsigned long tickCountStartupTime = 0; int lastTickRemainingTime = 0; // store the last calculated remaining time unsigned long remoteSplashImgDownloadTimeoutInSec = 60 * 60 * 24 * 7; unsigned long lastSplashRefresh = 0; #define NUMBER_OF_TICKS 10 // a tick is a single interval of timer int tickHeight = (TICK_CONTEINER_HEIGHT_IN_PX / NUMBER_OF_TICKS) - 2; #define NUMBERS_OF_SPLASH_IMG 50 int numberOfTicksDrew = 0; bool isDrwaingTicks = false; unsigned long startBreak = 0; struct Config { char wifiSSID[64]; char wifiPassword[64]; }; Config config; WiFiHelper *wifiHelper; IPAddress ipAddress; void setup(void) { M5.begin(); Serial.begin(9600); /* Power chip connected to gpio21, gpio22, I2C device Set battery charging voltage and current If used battery, please call this function in your project */ M5.Power.begin(); M5.IMU.Init(); M5.Lcd.clear(BLACK); M5.Lcd.setTextColor(WHITE, BLACK); M5.Lcd.setTextSize(1); M5.Lcd.setFreeFont(FS9); if (!loadConfiguraton("/config.json", config)) { M5.Lcd.println("Cannot read the configuration!"); Serial.println("Cannot read the configuration!"); } wifiHelper = new WiFiHelper(config.wifiSSID, config.wifiPassword); // Setup logo M5.Lcd.setBrightness(100); M5.Lcd.drawJpgFile(SD, "/pomodoro.jpg"); delay(500); M5.Lcd.clear(BLACK); M5.Lcd.drawPngFile(SD, "/wifi.png", 90, 70); M5.Lcd.setCursor(10, 20); M5.Lcd.print("Connecting to '" + String(config.wifiSSID) + "'.."); ipAddress = wifiHelper->connect(); M5.Lcd.setCursor(10, 50); M5.Lcd.print(ipAddress); M5.Lcd.print(" - "); M5.Lcd.print(wifiHelper->getFormattedTime()); unsigned long lasEpochTime = readEpochTimeFromFile("/lastSplashImagesUpdate.json"); delay(1000); if (lasEpochTime <= 0 || wifiHelper->getEpochTime() - lasEpochTime > remoteSplashImgDownloadTimeoutInSec) { M5.Lcd.clear(BLACK); M5.Lcd.setCursor(10, 70); M5.Lcd.print("Splash images to old!"); M5.Lcd.setCursor(10, 95); M5.Lcd.print("..they will be downloaded again!"); delay(3000); // Download new set of splash images downloadSplashImages("cats", NUMBERS_OF_SPLASH_IMG); writeEpochTimeToFile("/lastSplashImagesUpdate.json", wifiHelper->getEpochTime()); } } void loop() { int orientation = CheckOrientation(); if (orientation > 0 && lastOrientation != orientation) M5.Lcd.clear(BLACK); RotateDisplayByOrientation(orientation); //TestOrientation(orientation); // check tick long currentMillis = millis(); if (canContinueToDrawTicks() && (currentTick == 0 || (currentMillis - lastTickCheck) > tickDurationInSec * 1000)) { if (currentTick == 0) tickCountStartupTime = currentMillis; currentTick++; lastTickCheck = currentMillis; } drawPage(orientation); if (orientation > 0) lastOrientation = orientation; } void drawPage(int orientation) { if (currentTick > NUMBER_OF_TICKS) { // manage elapsed pomodoro! } else { setupOnOrientationChange(orientation); switch (orientation) { case ORIENTATION_UP: drawTicks(); break; case ORIENTATION_RIGHT: break; case ORIENTATION_DOWN: drawTicksContainer(); break; case ORIENTATION_LEFT: drawRandomSplashImages(); drawBreakDuration(); break; default: break; } } } void setupOnOrientationChange(int orientation) { if (orientation < 0 || lastOrientation == orientation) return; // I will be here only upon orientation change switch (orientation) { case ORIENTATION_UP: setupOrientationUp(); break; case ORIENTATION_RIGHT: break; case ORIENTATION_DOWN: drawTicksContainer(); break; case ORIENTATION_LEFT: setupOrientationLeft(); break; default: break; } } void setupOrientationUp() { // setup text M5.Lcd.setFreeFont(FS9); M5.Lcd.setTextColor(BLACK, RED); M5.Lcd.setFreeFont(FSB18); // reset counters resetBreakDuration(); numberOfTicksDrew = 0; // draw base container drawTicksContainer(); } void setupOrientationLeft() { // setup text M5.Lcd.setFreeFont(FSB9); M5.Lcd.setTextColor(BLACK, YELLOW); // reset counters startBreak = millis(); // draw drawBreakDuration(); } bool canContinueToDrawTicks() { return startBreak == 0; } void drawBreakDuration() { long currentMillis = millis(); M5.Lcd.fillRect(0, 300, 240, 20, YELLOW); M5.Lcd.setCursor(60, 316); M5.Lcd.print("Await by " + String((int)(currentMillis - startBreak) / 1000) + "sec"); } void resetBreakDuration() { startBreak = 0; } void drawRandomSplashImages() { long currentMillis = millis(); if (lastSplashRefresh == 0 || (currentMillis - lastSplashRefresh) > 5000) { int index = random(1, NUMBERS_OF_SPLASH_IMG); String fileName = "/splashImage_" + String(index) + ".jpg"; M5.Lcd.drawJpgFile(SD, fileName.c_str()); lastSplashRefresh = currentMillis; } } void drawTicks() { drawTickInfo(); if (isDrwaingTicks) return; isDrwaingTicks = true; for (int i = 1; i <= currentTick; i++) { if ((numberOfTicksDrew == 0 || i >= numberOfTicksDrew) && numberOfTicksDrew <= NUMBER_OF_TICKS) { Serial.println("Draw tick " + String(i) + ", ticks drew: " + String(numberOfTicksDrew)); M5.Lcd.drawJpgFile(SD, (String("/row-1-col-") + String(i) + String(".jpg")).c_str(), 40 + ((i - 1) * 24), 0); numberOfTicksDrew++; } } isDrwaingTicks = false; // uint16_t color = 0; // for (size_t i = 0; i <= currentTick; i++) // { // if (i <= 2) // color = 0x1d69; // if (i > 2 && i <= 4) // color = 0x9d6a; // if (i > 4 && i <= 6) // color = 0xe66a; // if (i > 6 && i <= 8) // color = 0xe50a; // if (i > 8 && i <= 10) // color = 0xe06a; // M5.Lcd.fillRect(81, 231 - (tickHeight * (i + 1)), TICK_CONTEINER_WIDTH_IN_PX - 1, tickHeight - 1, color); // } } void drawTickInfo() { int remainingTime = getRemainingTicksMinuted(); if (lastTickRemainingTime == 0 || lastTickRemainingTime > remainingTime) { Serial.println("Remaining time: " + String(remainingTime) + "min, lastTickRemainingTime=" + String(lastTickRemainingTime) + "min"); M5.Lcd.fillRect(0, 0, 40, 240, RED); String minutes = String(remainingTime); int numOfDecimal = minutes.length(); for (int i = 0; i < numOfDecimal; i++) { M5.Lcd.setCursor(5, 100 + i * 30 + (3-numOfDecimal)* 20); M5.Lcd.print(minutes.charAt(i)); } M5.Lcd.setCursor(285, 100); M5.Lcd.print("m"); M5.Lcd.setCursor(292, 130); M5.Lcd.print("i"); M5.Lcd.setCursor(290, 155); M5.Lcd.print("n"); lastTickRemainingTime = remainingTime; } } int getRemainingTicksMinuted() { int minutes = (int)(((NUMBER_OF_TICKS - currentTick) * tickDurationInSec) / 60); if (minutes <= 0) return 1; else return minutes; } int CheckOrientation() { long currentMillis = millis(); if (lastRefreshOrientation == 0 || (currentMillis - lastRefreshOrientation) > refreshOrientationTimeout) { lastRefreshOrientation = currentMillis; updateIMUData(); // down accy < -0.85 & abs(accx) < 0.2 // Up accy > 0.85 & abs(accx) < 0.2 // left accx < -0.85 & abs(accy) < 0.2 // right accx > 0.85 & abs(accy) < 0.2 if (accY < -IMUTreshhold && abs(accX) < IMUTreshhold2) { return ORIENTATION_DOWN; } else if (accY > IMUTreshhold && abs(accX) < IMUTreshhold2) { return ORIENTATION_UP; } else if (accX < -IMUTreshhold && abs(accY) < IMUTreshhold2) { return ORIENTATION_LEFT; } else if (accX > IMUTreshhold && abs(accY) < IMUTreshhold2) { return ORIENTATION_RIGHT; } } else return -1; } void RotateDisplayByOrientation(int orientation) { if (orientation < 0) return; switch (orientation) { case ORIENTATION_UP: M5.Lcd.setRotation(1); break; case ORIENTATION_RIGHT: M5.Lcd.setRotation(2); break; case ORIENTATION_DOWN: M5.Lcd.setRotation(3); break; case ORIENTATION_LEFT: M5.Lcd.setRotation(0); break; default: break; } } void TestOrientation(int orientation) { if (orientation < 0 || lastOrientation == orientation) return; M5.Lcd.clear(WHITE); switch (orientation) { case ORIENTATION_UP: M5.Lcd.drawPngFile(SD, "/up.png"); break; case ORIENTATION_RIGHT: M5.Lcd.drawPngFile(SD, "/left.png"); break; case ORIENTATION_DOWN: M5.Lcd.drawPngFile(SD, "/down.png"); break; case ORIENTATION_LEFT: M5.Lcd.drawPngFile(SD, "/right.png"); break; default: break; } } int updateIMUData() { M5.IMU.getGyroData(&gyroX, &gyroY, &gyroZ); M5.IMU.getAccelData(&accX, &accY, &accZ); M5.IMU.getAhrsData(&pitch, &roll, &yaw); M5.IMU.getTempData(&temp); } void printIMUStatus() { M5.Lcd.setCursor(0, 20); M5.Lcd.printf("%6.2f %6.2f %6.2f ", gyroX, gyroY, gyroZ); M5.Lcd.setCursor(220, 42); M5.Lcd.print(" o/s"); M5.Lcd.setCursor(0, 65); M5.Lcd.printf(" %5.2f %5.2f %5.2f ", accX, accY, accZ); M5.Lcd.setCursor(220, 87); M5.Lcd.print(" G"); M5.Lcd.setCursor(0, 110); M5.Lcd.printf(" %5.2f %5.2f %5.2f ", pitch, roll, yaw); M5.Lcd.setCursor(220, 132); M5.Lcd.print(" degree"); M5.Lcd.setCursor(0, 155); M5.Lcd.printf("Temperature : %.2f C", temp); } void drawTicksContainer() { M5.Lcd.drawPngFile(SD, "/pomodoro-alpha.png", 40, 0); M5.Lcd.fillRect(0, 0, 40, 240, RED); M5.Lcd.fillRect(280, 0, 40, 240, RED); // M5.Lcd.drawFastHLine(80, 230, TICK_CONTEINER_WIDTH_IN_PX, WHITE); // M5.Lcd.drawFastVLine(80, 40, TICK_CONTEINER_HEIGHT_IN_PX, WHITE); // M5.Lcd.drawFastVLine(240, 40, TICK_CONTEINER_HEIGHT_IN_PX, WHITE); } void downloadSplashImages(String topic, int quantity) { M5.Lcd.clear(BLACK); M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK); int y = 130; String progressFileName = "/catProgress.png"; for (size_t i = 0; i < quantity; i++) { M5.Lcd.fillRect(0, 0, 320, 90, BLACK); // clear M5.Lcd.setCursor(10, 60); if (i > 0) { M5.Lcd.print("Got splash " + String(i) + "/" + String(quantity) + " "); } else { M5.Lcd.print("Getting first splash.."); } String url = "https://source.unsplash.com/random/240x300?" + topic; String fileName = "/splashImage_" + String(i + 1) + ".jpg"; bool result = wifiHelper->downloadFile(SD, url, fileName); Serial.println("Download of splash image " + fileName + (result ? " DONE" : " FAIL")); if (i > 1 && i % 8 == 0) { progressFileName = progressFileName.indexOf("Rotated") > 0 ? "/catProgress.png" : "/catProgressRotated.png"; } M5.Lcd.drawPngFile(SD, progressFileName.c_str(), (i % 8) * 35 + 2, y, 35, 35); } } // See https://arduinojson.org/v6/doc/ bool loadConfiguraton(const char *filename, Config &config) { if (!SD.exists(filename)) return false; // Open file for reading File file = SD.open(filename); // Allocate a temporary JsonDocument // Don't forget to change the capacity to match your requirements. // Use arduinojson.org/v6/assistant to compute the capacity. StaticJsonDocument<512> doc; // Deserialize the JSON document DeserializationError error = deserializeJson(doc, file); if (error) Serial.println(F("Failed to read file, using default configuration")); // Copy values from the JsonDocument to the Config //config.wifiPassword = doc["wifiPassword"]; strlcpy(config.wifiSSID, // <- destination doc["wifiSSID"], // <- source sizeof(config.wifiSSID)); // <- destination's capacity strlcpy(config.wifiPassword, // <- destination doc["wifiPassword"], // <- source sizeof(config.wifiPassword)); // <- destination's capacity // Close the file (Curiously, File's destructor doesn't close the file) file.close(); return true; } bool writeEpochTimeToFile(const char *filename, unsigned long epochTime) { if (SD.exists(filename)) SD.remove(filename); // create file File file = SD.open(filename, FILE_WRITE); StaticJsonDocument<512> doc; doc["epochTime"] = epochTime; size_t byteWritten = serializeJsonPretty(doc, file); file.flush(); file.close(); if (byteWritten <= 0) { Serial.println("writeEpochTimeToFile: cannot write on the file: " + String(filename)); return false; } else return true; } unsigned long readEpochTimeFromFile(const char *filename) { if (!SD.exists(filename)) return -1; // Open file for reading File file = SD.open(filename); StaticJsonDocument<512> doc; DeserializationError error = deserializeJson(doc, file); if (error) Serial.println("readEpochTimeFromFile: failed to read file:" + String(filename)); file.close(); return doc["epochTime"].as<unsigned long>(); }
ee0944ab7fcf19f9132c1df2d3276e5df0a1e210
0a0baf1df933ca235a48aa187f6df31714a63a8b
/GenericSimulator/Doodle/OCCTMeshUtils.hpp
40dac8f043b258f733c1d23b659a2b600676036a
[ "MIT" ]
permissive
ducis/pile-of-cpp
84f1571178edd18ae3a7793d45dffca72d7ab34d
af5a123ec67cff589f27bf20d435b2db29a0a7c8
refs/heads/master
2021-01-17T06:27:30.532654
2019-03-12T05:30:52
2019-03-12T05:30:52
17,528,954
0
0
null
null
null
null
UTF-8
C++
false
false
6,391
hpp
OCCTMeshUtils.hpp
#pragma once #include <boost/fusion/tuple.hpp> #include <TopExp_Explorer.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS.hxx> //#include <boost/operators.hpp> #include <StdPrs_ToolShadedShape.hxx> #include <limits> #include <boost/array.hpp> #include "NumericRange.hpp" #include <cmath> #include <Poly_Triangulation.hxx> //#include <numeric> //#include <functional> //#include <boost/range/iterator_range.hpp> //#include <boost/range/adaptor/transformed.hpp> //#include <boost/range/numeric.hpp> namespace OpenCASCADEUtils{ //class ShapeFaceIterator: boost::incrementable<ShapeFaceIterator>{ // TopExp_Explorer m_e; //public: // explicit ShapeFaceIterator(const TopoDS_Shape &s): m_e(s,TopAbs_FACE){} // ShapeFaceIterator(){} // ShapeFaceIterator &operator++(){ // m_e.Next(); // } // //ShapeFaceIterator operator++( int ){ // // ShapeFaceIterator r = *this; // // ++(*this); // // return r; // //} // bool operator!=(const ShapeFaceIterator &) const{ return m_e.More(); } // const TopoDS_Face &operator*() const{ return TopoDS::Face(m_e.Current()); } //}; //class ShapeFaceMeshIterator: boost::incrementable<ShapeFaceMeshIterator>{ // ShapeFaceIterator m_sfi; // TopLoc_Location m_l; //public: // template <typename _ShapeFaceIteratorInitializer> // ShapeFaceMeshIterator(const _ShapeFaceIteratorInitializer &s,const TopLoc_Location &l): m_sfi(s), m_l(l){} // template <typename _ShapeFaceIteratorInitializer> // explicit ShapeFaceMeshIterator(const _ShapeFaceIteratorInitializer &s): m_sfi(s){} // ShapeFaceMeshIterator(){} // ShapeFaceMeshIterator() &operator++(){ ++m_sfi; } // bool operator!=(const ShapeFaceMeshIterator &rhs) const{ return m_sfi!=rhs.m_sfi; } // const Poly_Triangulation &operator*() const{ return *StdPrs_ToolShadedShape::Triangulation(*m_sfi,m_l); } //}; inline std::size_t GetMeshedShapeVertCount(const TopoDS_Shape &s){ std::size_t result = 0; for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ result += StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location())->NbNodes(); } return result; //return boost::accumulate //( // boost::make_iterator_range(ShapeFaceMeshIterator(s),ShapeFaceMeshIterator()) // |boost::adaptors::transformed(std::mem_fun_ref(Poly_Triangulation::NbNodes)), // 0 //); } inline std::size_t GetMeshedShapeTriangleCount(const TopoDS_Shape &s){ std::size_t result = 0; for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ result += StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location())->NbTriangles(); } return result; //return boost::accumulate //( // boost::make_iterator_range(ShapeFaceMeshIterator(s),ShapeFaceMeshIterator()) // |boost::adaptors //); } //could use some iterators and vector output template< typename _OutputIterator > _OutputIterator CopyMeshedShapeIndices(_OutputIterator dest,const TopoDS_Shape &s) { Standard_Integer offset = 0; for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ Handle_Poly_Triangulation h = StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location()); const Poly_Array1OfTriangle &f = h->Triangles(); const TColgp_Array1OfPnt &v = h->Nodes(); offset-=v.Lower(); Standard_Integer stride = (e.Current().Orientation() == TopAbs_REVERSED)?-1:1, first = 2-stride, last = 2*(1+stride);//(-1,3,0) or (1,1,4) for(Standard_Integer i=f.Lower();i<=f.Upper();++i){ const Poly_Triangle & tri = f(i); for(int j=first;j!=last;j+=stride){ *dest++ = tri(j)+offset; } } offset+=v.Lower(); offset+=v.Length(); } return dest; } template< typename _ScalarOutputIterator > _ScalarOutputIterator CopyComponentsOfMeshedShapeVertexNormals(_ScalarOutputIterator dest,const TopoDS_Shape &s){ for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ Handle_Poly_Triangulation h = StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location()); Poly_Connect pc(h); TColgp_Array1OfDir n(1,h->NbNodes()); StdPrs_ToolShadedShape::Normal(TopoDS::Face(e.Current()),pc,n); for(Standard_Integer i = n.Lower();i<=n.Upper();++i){ const gp_Dir &d = n(i); *dest++ = d.X(); *dest++ = d.Y(); *dest++ = d.Z(); } } return dest; } template< typename _ScalarOutputIterator > _ScalarOutputIterator CopyComponentsOfMeshedShapeVertexPositions(_ScalarOutputIterator dest, const TopoDS_Shape &s){ for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ Handle_Poly_Triangulation h = StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location()); const TColgp_Array1OfPnt &v = h->Nodes(); for(Standard_Integer i=v.Lower();i<=v.Upper();++i){ const gp_Pnt &pt = v(i); *dest++ = pt.X(); *dest++ = pt.Y(); *dest++ = pt.Z(); } } return dest; } boost::array<Standard_Real,6> GetMeshedShapeAABB(const TopoDS_Shape &s){ boost::array<Standard_Real,6> r= { std::numeric_limits<Standard_Real>::max(),std::numeric_limits<Standard_Real>::max(),std::numeric_limits<Standard_Real>::max(), std::numeric_limits<Standard_Real>::min(),std::numeric_limits<Standard_Real>::min(),std::numeric_limits<Standard_Real>::min() }; for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ Handle_Poly_Triangulation h = StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location()); const TColgp_Array1OfPnt &v = h->Nodes(); for(Standard_Integer i=v.Lower();i<=v.Upper();++i){ using namespace NumericRange; const gp_Pnt &pt = v(i); Extend(pt.X(),r[0],r[3]); Extend(pt.Y(),r[1],r[4]); Extend(pt.Z(),r[2],r[5]); } } return r; } Standard_Real GetMeshedShapeMaxVertexDistanceSquared(const TopoDS_Shape &s){ Standard_Real r=0; for(TopExp_Explorer e(s,TopAbs_FACE);e.More();e.Next()){ Handle_Poly_Triangulation h = StdPrs_ToolShadedShape::Triangulation(TopoDS::Face(e.Current()),TopLoc_Location()); const TColgp_Array1OfPnt &v = h->Nodes(); for(Standard_Integer i=v.Lower();i<=v.Upper();++i){ using namespace NumericRange; const gp_Pnt &pt = v(i); ExtendR( pow(v(i).X(),2) + pow(v(i).Y(),2) + pow(v(i).Z(),2) , r); } } return r; } }
ed88f685d4615389d564be56ced50f471d4d3b01
5a10491ae7ada5f7d5fca704e60bc853b652c1ad
/roteiro3-LLP1/Questรฃo2/IConta.h
904c3014a8ca1e618e8705a679a00354c1c1af06
[]
no_license
RaissaVieira/Atividades-LP1
6a59efe65591867c748d68b3eecfd617ebd91f60
dac4a787769bbe652a2f10a7c53c255170ebb076
refs/heads/master
2020-09-06T00:15:52.435826
2020-03-17T14:47:21
2020-03-17T14:47:21
220,255,308
2
0
null
null
null
null
UTF-8
C++
false
false
183
h
IConta.h
#ifndef ICONTA_H #define ICONTA_H class IConta { private: public: IConta(/* args */); virtual void sacar(double valor); virtual void depositar(double valor); }; #endif
9c3ea40dbac3531e792118cdf9b18a2ab1fde8b4
d34f94a4740256901edfb2ee2325505ca834ba30
/C++/skola/t-hert.cpp
f9b4cb106d45aafa0ceb6b42495d0b2c88884efe
[]
no_license
dimitarkole/CPlusPlusTasks
706a15e533e657a91fe5c7d0ccee2cc129a2ac5f
8b3adf02ab359babdc36b73085a83fb9055b0716
refs/heads/master
2020-12-04T23:07:48.601834
2020-01-05T14:25:05
2020-01-05T14:25:05
231,928,854
1
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
t-hert.cpp
#include<iostream> using namespace std; int main() { int a,b,x,y,max; cin>>a>>b>>x>>y; a=a/x; b=a/y; max=a; if(max<b)max=b; cout<<b<<" "<<a*b-((x*y)*max); }
5b09dd39c6899cb1122247b3dc3e312b8645626b
f9b5b73620dc65dd78d5af7489c7dbd46ce5ed61
/2 atividade/quest10/cal10.cpp
a7530e2f62832794d49d012dfecfa28e5b991c75
[]
no_license
utiamaguilherme/CAL
88d90c74e86e2bbedc11722181e020e389f93c8d
ad118f5bbcb0a6bfc60041d17e99da0bb0af18bb
refs/heads/master
2021-03-15T14:37:29.027844
2020-03-12T14:43:32
2020-03-12T14:43:32
246,858,077
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
cal10.cpp
#include <bits/stdc++.h> using namespace std; int main(){ string name; getline(cin, name); map<char, int> mapinha; vector<pair<int, char>> letras; for(char c : name){ mapinha[c]++; } for(auto c : mapinha){ letras.push_back({c.second, c.first}); } sort(letras.begin(), letras.end(), greater<pair<int,char>>()); for(auto l : letras){ cout << l.first << " " << l.second << endl; } }
e3539ab17b23bc30b0fb63332c1fff7c23a87826
0967c29a163d30404a601990bd0d4397b59f9dca
/src/PclStuff.cpp
a15b02eeeb536b288cb0719494ae9b65572fb221
[]
no_license
xmfcx/pcl-datacamp
aa66a023edbf72b885d4b0a9ed9d287fc465de71
fc4bea03d5f2bab662bf253c50d90ebae038fb19
refs/heads/master
2020-04-07T03:59:23.630393
2018-11-18T07:01:28
2018-11-18T07:01:42
158,036,155
0
0
null
null
null
null
UTF-8
C++
false
false
5,205
cpp
PclStuff.cpp
#include "PclStuff.h" using Point = pcl::PointXYZI; using Cloud = pcl::PointCloud<pcl::PointXYZI>; Cloud::Ptr PclStuff::Downsample(const Cloud::ConstPtr &cloud_in, float leaf_size) { Cloud::Ptr cloud_result(new Cloud()); pcl::VoxelGrid<Point> grid; grid.setLeafSize(leaf_size, leaf_size, leaf_size); grid.setInputCloud(cloud_in); grid.filter(*cloud_result); return cloud_result; } Cloud::Ptr PclStuff::GroundRemover(Cloud::ConstPtr cloud_in, float treshold) { Cloud::Ptr cloud_groundless(new Cloud); pcl::SACSegmentation<Point> seg; pcl::PointIndices::Ptr inliers(new pcl::PointIndices); pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients); seg.setOptimizeCoefficients(true); seg.setModelType(pcl::SACMODEL_PLANE); seg.setMethodType(pcl::SAC_RANSAC); seg.setMaxIterations(1000); seg.setDistanceThreshold(treshold); seg.setInputCloud(cloud_in); seg.segment(*inliers, *coefficients); if (inliers->indices.empty()) { std::cout << "Could not estimate a planar model for the given dataset." << std::endl; *cloud_groundless = *cloud_in; return cloud_groundless; } pcl::ExtractIndices<Point> extract; extract.setInputCloud(cloud_in); extract.setIndices(inliers); extract.setNegative(true); extract.filter(*cloud_groundless); return cloud_groundless; } std::tuple<Cloud::Ptr, Cloud::Ptr, std::vector<float>, std::vector<float>, std::vector<float>> PclStuff::MiniClusterer(Cloud::Ptr cloud_in, float tolerance, int points_min, int points_max, float x_max, float y_max, float z_max, float x_min, float y_min, float z_min) { pcl::search::KdTree<Point>::Ptr tree(new pcl::search::KdTree<Point>); tree->setInputCloud(cloud_in); std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<Point> ec; ec.setClusterTolerance(tolerance); ec.setMinClusterSize(points_min); ec.setMaxClusterSize(points_max); ec.setSearchMethod(tree); ec.setInputCloud(cloud_in); ec.extract(cluster_indices); Cloud::Ptr cloud_cluster(new Cloud); cloud_cluster->is_dense = true; cloud_cluster->width = 0; cloud_cluster->height = 1; Cloud::Ptr centroids(new Cloud); std::vector<float> vector_length_x; std::vector<float> vector_length_y; std::vector<float> vector_length_z; int j = 0; for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); ++it) { pcl::PointXYZ loww(std::numeric_limits<float>::max(), std::numeric_limits<float>::max(), std::numeric_limits<float>::max()); pcl::PointXYZ high(std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest(), std::numeric_limits<float>::lowest()); pcl::PointXYZ sum(0, 0, 0); int cur_cluster_size = 0; for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); ++pit) { Point colorful_point(j * 0.05); colorful_point.x = cloud_in->points[*pit].x; colorful_point.y = cloud_in->points[*pit].y; colorful_point.z = cloud_in->points[*pit].z; if (cloud_in->points[*pit].x < loww.x) { loww.x = cloud_in->points[*pit].x; } if (cloud_in->points[*pit].y < loww.y) { loww.y = cloud_in->points[*pit].y; } if (cloud_in->points[*pit].z < loww.z) { loww.z = cloud_in->points[*pit].z; } if (cloud_in->points[*pit].x > high.x) { high.x = cloud_in->points[*pit].x; } if (cloud_in->points[*pit].y > high.y) { high.y = cloud_in->points[*pit].y; } if (cloud_in->points[*pit].z > high.z) { high.z = cloud_in->points[*pit].z; } cloud_cluster->points.push_back(colorful_point); sum.x += cloud_in->points[*pit].x; sum.y += cloud_in->points[*pit].y; sum.z += cloud_in->points[*pit].z; cur_cluster_size++; } j++; pcl::PointXYZ size(fabsf(high.x - loww.x), fabsf(high.y - loww.y), fabsf(high.z - loww.z)); Point centroid; centroid.x = sum.x / cur_cluster_size; centroid.y = sum.y / cur_cluster_size; centroid.z = sum.z / cur_cluster_size; if (size.x > x_max || size.x < x_min || size.y > y_max || size.y < y_min || size.z > z_max || size.z < z_min ) continue; for (std::vector<int>::const_iterator pit = it->indices.begin(); pit != it->indices.end(); ++pit) { Point colorful_point; colorful_point.x = cloud_in->points[*pit].x; colorful_point.y = cloud_in->points[*pit].y; colorful_point.z = cloud_in->points[*pit].z; } centroids->points.push_back(centroid); vector_length_x.push_back(size.x); vector_length_y.push_back(size.y); vector_length_z.push_back(size.z); } cloud_cluster->width = cloud_cluster->points.size(); return std::make_tuple(cloud_cluster, centroids, vector_length_x, vector_length_y, vector_length_z); }
991d32a6f3eef61ff6b9f6ba1cbbb1e5f8dc8f31
898f517714dcd43a968bf3647ff88352dfaa2395
/server_code/query_cursor.h
1b1f1155ba04ff1876537b9628ab4a9e2dbe9a4e
[ "MIT" ]
permissive
InitialDLab/SONAR-SamplingIndex
54c7e8fb05a418e0be052ec740175edc3b67364d
c83d6f53f8419cdb78f49935f41eb39447918ced
refs/heads/master
2021-01-18T16:19:05.940489
2017-09-29T21:21:22
2017-09-29T21:21:22
86,735,043
3
0
null
null
null
null
UTF-8
C++
false
false
2,125
h
query_cursor.h
/* Copyright 2017 InitialDLab Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "server_code/protobuf/sampling_api.pb.h" class query_cursor { public: virtual ~query_cursor() { }; // get the settings requested for the cursor // (what to return as part of the returned elements) virtual bool returning_OID() = 0; virtual bool returning_location() = 0; virtual bool returning_payload() = 0; virtual bool returning_time() = 0; // get the ttl for the object virtual int get_ttl() = 0; // return true if this cursor is expired (lived to the end of its ttl) and is ready to be clearned up virtual bool is_expired() = 0; // get the counted number of elements in the requested range for this query virtual long get_total_elements_in_query_range() = 0; virtual long get_elements_analyzed_count() = 0; // return the region this query is going to sample from virtual serverProto::box get_query_region() = 0; // perform the query and return a query response with the requested data virtual void perform_query(int count, serverProto::QueryResponse&) = 0; };
041a4ccd3f30faf707fcb2f338f01134ed1fe0af
287c25a7f0590fecc684a5d96d86547eeb0b3909
/fluid simulation/FluidSimulation/NeighborFinderFactory.h
49ff33b5a5a8345abaebc53caccb12b09631462e
[]
no_license
qingwei8/FluidSimulation
7d64375c70a33a443801590917896b7c532a4c2b
5ff263b0dce55242c9e65efda25e64c478351291
refs/heads/master
2021-08-27T17:19:03.126125
2017-05-16T07:43:38
2017-05-16T07:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
NeighborFinderFactory.h
#pragma once #include "NeighborFinderFactoryData.h" #include "BaseFindNeighbors.h" namespace hiveFluidSimulation { template<class DeriveNeighborFinder> class CNeighborFinderFactory { public: CNeighborFinderFactory(const std::string& vCreationSig) { CNeighborFinderFactoryData::getInstance()->registerFactory(vCreationSig, reinterpret_cast<CNeighborFinderFactory<CBaseFindNeighbors>*>(this)); } ~CNeighborFinderFactory() {} protected: virtual CBaseFindNeighbors* _createNeighborFinderV() {return new DeriveNeighborFinder;} friend class CNeighborFinderFactoryData; }; }
4b300a1ba574e734e3ad0721fbcb9ec7d3dcde92
e9d3bd92027e63033929ab9dc97f38473f8ef0ef
/GTE/Samples/SceneGraphs/MorphControllers/MorphControllersWindow3.cpp
b1c25730e87a686b98fa22322d2739919e45a538
[ "BSL-1.0" ]
permissive
cbullo/GeometricTools
77107de654a012649d05ea248caefe581cc7fde4
53d82425c3d27a4301f7390754c7fc440734d53f
refs/heads/master
2023-08-27T22:05:04.268917
2021-10-19T20:48:34
2021-10-19T20:48:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,719
cpp
MorphControllersWindow3.cpp
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2021 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #include "MorphControllersWindow3.h" #include <Applications/WICFileIO.h> #include <Graphics/MeshFactory.h> #include <Graphics/ConstantColorEffect.h> #include <Graphics/Texture2Effect.h> #include <random> MorphControllersWindow3::MorphControllersWindow3(Parameters& parameters) : Window3(parameters), mApplicationTime(0.0), mApplicationDeltaTime(0.0001), mDrawTargets(false) { if (!SetEnvironment()) { parameters.created = false; return; } mNoCullState = std::make_shared<RasterizerState>(); mNoCullState->cullMode = RasterizerState::CULL_NONE; mNoCullWireState = std::make_shared<RasterizerState>(); mNoCullWireState->fillMode = RasterizerState::FILL_WIREFRAME; mNoCullWireState->cullMode = RasterizerState::CULL_NONE; mEngine->SetRasterizerState(mNoCullState); mEngine->SetClearColor({ 0.75f, 0.75f, 0.75f, 1.0f }); CreateScene(); InitializeCamera(60.0f, GetAspectRatio(), 0.01f, 100.0f, 0.005f, 0.002f, { 0.0f, -2.35f, 0.075f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }); mPVWMatrices.Update(); mTrackBall.Update(); } void MorphControllersWindow3::OnIdle() { mTimer.Measure(); if (mCameraRig.Move()) { mPVWMatrices.Update(); } mMorphDisk->Update(mApplicationTime); mApplicationTime += mApplicationDeltaTime; mEngine->ClearBuffers(); if (mDrawTargets) { auto saveRState = mEngine->GetRasterizerState(); mEngine->SetRasterizerState(mNoCullWireState); for (auto const& visual : mMorphTarget) { mEngine->Draw(visual); } mEngine->SetRasterizerState(saveRState); } mEngine->Draw(mMorphDisk); mEngine->Draw(8, mYSize - 8, { 0.0f, 0.0f, 0.0f, 1.0f }, mTimer.GetFPS()); mEngine->DisplayColorBuffer(0); mTimer.UpdateFrameCount(); } bool MorphControllersWindow3::OnCharPress(unsigned char key, int x, int y) { switch (key) { case 'w': case 'W': if (mEngine->GetRasterizerState() == mNoCullState) { mEngine->SetRasterizerState(mNoCullWireState); } else { mEngine->SetRasterizerState(mNoCullState); } return true; case 'd': case 'D': mDrawTargets = !mDrawTargets; return true; } return Window3::OnCharPress(key, x, y); } bool MorphControllersWindow3::SetEnvironment() { std::string path = GetGTEPath(); if (path == "") { return false; } mEnvironment.Insert(path + "/Samples/Data/"); if (mEnvironment.GetPath("BlueGrid.png") == "") { LogError("Cannot find file BlueGrid.png"); return false; } return true; } void MorphControllersWindow3::CreateScene() { // Start with a disk that is to be morphed. VertexFormat vformat; vformat.Bind(VA_POSITION, DF_R32G32B32_FLOAT, 0); vformat.Bind(VA_TEXCOORD, DF_R32G32_FLOAT, 0); MeshFactory mf; mf.SetVertexFormat(vformat); mf.SetVertexBufferUsage(Resource::DYNAMIC_UPDATE); unsigned int const numShellSamples = 16; unsigned int const numRadialSamples = 16; float const radius = 1.0f; mMorphDisk = mf.CreateDisk(numShellSamples, numRadialSamples, radius); auto diskVBuffer = mMorphDisk->GetVertexBuffer(); Vertex* diskVertices = diskVBuffer->Get<Vertex>(); // Create the morph controller. size_t numVertices = static_cast<size_t>(diskVBuffer->GetNumElements()); size_t numTargets = 8; size_t numTimes = 129; mMorphController = std::make_shared<MorphController>( numTargets, numVertices, numTimes, mUpdater); mMorphController->repeat = Controller::RT_CYCLE; mMorphController->minTime = 0.0; mMorphController->maxTime = 1.0; mMorphController->phase = 0.0; mMorphController->frequency = 1.0; mMorphController->active = true; // Create the morph controller data. // The times are in [0,1]. std::vector<float> times(numTimes); for (size_t key = 0; key < numTimes; ++key) { times[key] = static_cast<float>(key) / static_cast<float>(numTimes - 1); } mMorphController->SetTimes(times); // Visualize the morph targets. mMorphTarget.resize(numTargets); vformat.Reset(); vformat.Bind(VA_POSITION, DF_R32G32B32_FLOAT, 0); mf.SetVertexFormat(vformat); mf.SetVertexBufferUsage(Resource::IMMUTABLE); std::default_random_engine dre; std::uniform_real_distribution<float> urd(0.7f, 0.9f); std::vector<Vector4<float>> color(numTargets); for (size_t i = 0; i < numTargets; ++i) { color[i] = { urd(dre), urd(dre), urd(dre), 1.0f }; } // Target 0 is the original disk. The remaining targets have points that // are on rays, varying in a sinusoidal manner with amplitude and // frequency depending on position (x,y) of the original disk. std::vector<Vector3<float>> vertices(numVertices); for (size_t i = 0; i < numTargets; ++i) { float t = static_cast<float>(i) / static_cast<float>(numTargets - 1); for (size_t j = 0; j < numVertices; ++j) { Vector3<float> p = diskVertices[j].position; float amplitude = radius * radius - (p[0] * p[0] + p[1] * p[1]); float frequency = 2.35f * p[1]; float s = amplitude * std::sin(frequency * t); float sp1 = s + 1.0f; vertices[j][0] = sp1 * p[0]; vertices[j][1] = sp1 * p[1]; vertices[j][2] = s; } mMorphController->SetVertices(i, vertices); // Visualize the morph target. mMorphTarget[i] = mf.CreateDisk(numShellSamples, numRadialSamples, radius); std::memcpy(mMorphTarget[i]->GetVertexBuffer()->GetData(), vertices.data(), numVertices * sizeof(Vector3<float>)); auto effect = std::make_shared<ConstantColorEffect>(mProgramFactory, color[i]); mMorphTarget[i]->SetEffect(effect); mPVWMatrices.Subscribe(mMorphTarget[i]->worldTransform, effect->GetPVWMatrixConstant()); mTrackBall.Attach(mMorphTarget[i]); } // The weights are computed using a Gaussian distribution. std::vector<float> weights(numTargets); float const ratio = static_cast<float>(numTargets - 1) / static_cast<float>(numTimes - 1); float const factor = std::log(1.0f / 2.0f); for (size_t key = 0; key < numTimes; ++key) { float fkey = static_cast<float>(key); float sum = 0.0f; for (size_t i = 0; i < numTargets; ++i) { float fi = static_cast<float>(i); float diff = fi - fkey * ratio; weights[i] = std::exp(factor * diff * diff); sum += weights[i]; } for (size_t i = 0; i < numTargets; ++i) { weights[i] /= sum; } mMorphController->SetWeights(key, weights); } mMorphDisk->AttachController(mMorphController); std::string path = mEnvironment.GetPath("BlueGrid.png"); auto texture = WICFileIO::Load(path, true); texture->AutogenerateMipmaps(); auto effect = std::make_shared<Texture2Effect>(mProgramFactory, texture, SamplerState::MIN_L_MAG_L_MIP_L, SamplerState::WRAP, SamplerState::WRAP); mMorphDisk->SetEffect(effect); mPVWMatrices.Subscribe(mMorphDisk->worldTransform, effect->GetPVWMatrixConstant()); mTrackBall.Attach(mMorphDisk); mMorphDisk->Update(mApplicationTime); }
8b642a3d9a2ec7ef844adbc9b1705af27bb5f6c0
9bfdc860768d162338349564e7bab92e78e761d8
/Face/Dollars_Cents.cpp
8597285673ea5cde5362c0cd607e99d3fb3e6d69
[]
no_license
mohankrishna225/Practise
ef10f15d7de9ab2f26297c9ecfd3923b123282ba
df1787e45961ff72dc4909439fe1d9ee7af8413a
refs/heads/master
2023-01-01T14:29:43.606915
2020-10-27T20:32:53
2020-10-27T20:32:53
307,051,627
0
0
null
null
null
null
UTF-8
C++
false
false
307
cpp
Dollars_Cents.cpp
#include<iostream> using namespace std; int main() { int dollars,cents,dollar1,dollar2,cent1,cent2; cin>>dollar1>>cent1>>dollar2>>cent2; int t,m; dollars=dollar1+dollar2; cents=cent1+cent2; if(cents>100) { dollars=dollars+1; cents=cents-100; } cout<<dollars; cout<<"\n"<<cents; }
c52b8c7f22a2c6cbeedb8ba5dc792fba6173822a
17f7614d940b1e9d6ebb2219a2e658b064f6ca95
/program090_faulty.cpp
d23bca12fb4ed175f6499846de7c6e5c5ec32ff9
[]
no_license
xpbluesmile/How-Not-to-Program-in-Cpp
c6fdbab42cc65972045ca2bf13e0cb433c0995c4
5589571ad4d30d2765c75fb19f5dabad1bcb97d9
refs/heads/master
2021-05-30T02:46:41.940608
2012-09-10T13:53:46
2012-09-10T13:53:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,977
cpp
program090_faulty.cpp
/** * The problem with this code is the following (from the book): * * The initialization of log_file can call new. Of course, our new new uses the * log_file, so the log_file may be used before it gets constructed, confusing * the whole mess. */ /************************************************ * simple debugging library that overrides the * * standard new and delete operators so that we * * log all results. * ************************************************/ #include <iostream> #include <fstream> #include <cstdlib> // Define the file to write the log data to std::ofstream log_file("mem.log"); /************************************************ * operator new -- Override the system new so * * that it logs the operation. This is * * useful for debugging. * * * * Note: We have verified that the real new * * calls malloc on this system. * * * * Returns a pointer to the newly created area. * ************************************************/ void *operator new( // Size of the memory to allocate const size_t size ) { // Result of the malloc void *result = (void *)malloc(size); log_file << result << " =new(" << size << ")" << std::endl; return (result); } /************************************************ * operator delete -- Override the system * * delete to log the operation. This is * * useful for debugging. * * * * Note: We have verified that the real delete * * calls free on this system. * ************************************************/ void operator delete( void *data // Data to delete ) { log_file << data << " Delete" << std::endl; free (data); } // Dummy main int main() { return (0); }
a8ca57ddff15df690a3a68c507491a1a9ab68e7b
3f87182e515b92c141c841e68dd6394a95aedfa0
/dev_magos/src/magos.cpp
cb8a361499dfedd36221783d0e0b912b61403401
[]
no_license
pleshw/MAGOS
f858fc8b157c54c42f546c0764a76e43054b4286
61a035785de2d9e6a7b8abfe507cb6f6bb2ba0b0
refs/heads/master
2020-04-10T14:00:52.566473
2019-02-07T06:20:28
2019-02-07T06:20:28
161,064,884
1
0
null
null
null
null
UTF-8
C++
false
false
1,709
cpp
magos.cpp
#include "../include/magos.h" /// Build and renderize a maze as png images in /[outputBuilding] void MAGOS::build( void ) { Builder builder { maze }; Render render { canvas, maze, setup }; size_t counter { 0 }; size_t seed_counter { 0 }; while( !builder.isPerfect() ) { srand (time(NULL) + seed_counter++); if ( builder.brickBreak( builder.getRandomX(), builder.getRandomY(), builder.getRandomDirection() ) ) { render.draw ( builder.buffer() ); render.makePNG ( std::string( setup["outputBuilding"] + std::to_string(counter++) ) ); } else if ( builder.brickBreak( builder.findSingleCell(), builder.getRandomDirection() ) ) { render.draw ( builder.buffer() ); render.makePNG ( std::string( setup["outputBuilding"] + std::to_string(counter++) ) ); } // In the last's 10% cells the aproach to building change if ( (maze.cols()*maze.rows() - counter) < (1/10)*(maze.rows()*maze.cols()) ) { for (size_t i = 0; i < maze.rows(); ++i) { for (size_t j = 0; j < maze.cols(); ++j) { if ( builder.brickBreak( i, j, builder.getRandomDirection() ) ) { render.draw ( builder.buffer() ); render.makePNG ( std::string( setup["outputBuilding"] + std::to_string(counter++) ) ); } } } } } maze = builder.getMaze(); } /// Solve and renderize a maze as png in [/outputSolver] void MAGOS::solve( void ) { size_t counter { 0 }; Render render { canvas, maze, setup }; Solver solver { maze, stoul(setup["startFlagIndex"]), stoul(setup["endFlagIndex"]) }; while( !solver.solved() ) { solver.nextMove(); render.draw ( solver.buffer() ); render.makePNG ( std::string( setup["outputSolver"] + std::to_string(counter++) ) ); } }
cd74348bbfc041cff047e5022f0157876c56c6e7
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542575536.cpp
096970899e48f0017094033c3b97e7c5f30448df
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,611
cpp
1542575536.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define pii pair<int,int> #define pll pair<ll,ll> #define pdd pair<double,double> #define X first #define Y second #define rep(i,a) for(ll i=0;i<a;++i) #define repp(i,a,b) for(ll i=a;i<b;++i) #define all(c) (c).begin(), (c).end() #define FILL(a,x) memset(a,x,sizeof(a)) #define foreach( gg,itit ) for( typeof(gg.begin()) itit=gg.begin();itit!=gg.end();itit++ ) #define mp make_pair #define pb push_back #define fastScan ios_base::sync_with_stdio(0); cin.tie(NULL); ll M=1e9+7; ll mpe(ll base, ll exponent, ll modulus) { ll result = 1; while (exponent > 0) { if (exponent % 2 == 1) result = result*base%modulus ; exponent = exponent >> 1; base = base*base%modulus ; } return result; } int main() { fastScan; // freopen("a.in","r",stdin); // freopen("b.out","w",stdout); double h,m,s,t1,t2; cin>>h>>m>>s>>t1>>t2; if(s!=0){ m+=0.5; } if(m>60)m-=60; m/=5; if(m!=0){ h+=0.5; if(h>12)h-=12; } s/=5; double arr[3]; arr[0]=h; arr[1]=m; arr[2]=s; sort(arr,arr+3); int f=0,f1,f2; rep(i,2){ f1=0; f2=0; // cout<<i<<" "<<t1<<" "<<t2<<" "<<arr[i]<<" "<<arr[i+1]<<endl; if(t1<=arr[i+1] && t1>=arr[i])f1=1; if(t2<=arr[i+1] && t2>=arr[i])f2=1; if(f1!=f2)f=1; } if(f==1)cout<<"NO"; else cout<<"YES"; return 0; }
20a4602ea6d7db91806d8ca65006b98af9189a3e
ec2602f0c3cef1243a8a1619a7aebdfa3070c46f
/WebLogger.cpp
329ce78304256033cdf4ea8c48190ef9c733f6b2
[]
no_license
ryudo87/lintcode
c09f3573d29325ac02a4d6819aa4b544063587db
b1fb6853174c980fbb72215a8e6e97ade4a28702
refs/heads/master
2020-06-29T09:47:24.183883
2019-08-04T15:44:36
2019-08-04T15:44:36
200,503,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cpp
WebLogger.cpp
#include <iostream> #include <cstdio> #include <map> #include <queue> using namespace std; // Implement a web logger, which provide two methods: // hit(timestamp), record a hit at given timestamp. // get_hit_count_in_last_5_minutes(timestamp), get hit count in last 5 minutes. // the two methods will be called with non-descending timestamp (in sec). //็”จไธ€ไธชๅŒ็ซฏ้˜Ÿๅˆ—ไฟๅญ˜hit็š„ไฟกๆฏ๏ผŒๆฏๆฌกๆฃ€ๆŸฅๆœซๅฐพ็š„ๅ…ƒ็ด ๆ˜ฏๅฆtimestamp == ๅฝ“ๅ‰timestamp๏ผŒ็„ถๅŽๅˆคๆ–ญๆ˜ฏๆ›ดๆ–ฐ่ฟ˜ๆ˜ฏๆ’ๅ…ฅๆ–ฐ็š„ๅ…ƒ็ด ใ€‚get hit็š„ๆ—ถๅ€™ไปŽ้˜Ÿๅคดๅˆคๆ–ญๅฝ“ๅ‰็š„timestampๆ˜ฏๅฆๅœจ300็ง’ไน‹ๅ†…๏ผŒๅฆ‚ๆžœๅœจ็š„่ฏๅฐฑ้€€ๅ‡บๆŸฅๆ‰พๅพช็Žฏ๏ผŒๅฆ‚ๆžœไธๅœจๅˆ™ๅ‡บ้˜Ÿ๏ผŒ่ฟ™ๆ ทๅฐฑไฟ่ฏไบ†ๅฝ“ๅ‰้˜Ÿๅˆ—็š„ๅ…ƒ็ด ้ƒฝๅœจ300็ง’ไปฅๅ†…ใ€‚ struct Node { int timestamp; int count; Node(int timestamp) { count = 1; this->timestamp = timestamp; } }; class WebLogger { deque<Node> dq; int totalCount; public: WebLogger() { totalCount = 0; } void hit(int timestamp) { totalCount++; if (dq.size()==0 || dq.back().timestamp != timestamp) { dq.push_back(Node(timestamp)); } else { dq.back().count++; } } int get_hit_count_in_last_5_minutes(int timestamp) { while(!dq.empty() && dq.front().timestamp <= timestamp-300) { totalCount -= dq.front().count; dq.pop_front(); } return totalCount; } }; int main() { WebLogger log; log.hit(1); log.hit(2); std:cout<<log.get_hit_count_in_last_5_minutes(5)<<std::endl; return 0; }
13c930fdef1b6d55c5d7c00e2c8e117def6e9ae7
693be4e1e490c06b00d924cddab0f8fcb859f4f9
/wheelbox.cpp
e9aca7853ac8edd5596b14cb6e0be62ac04eda4d
[ "MIT" ]
permissive
ansleliu/SerialDigitalOscilloscope
43258b78941ed08bafabcb77f2da49658a907541
b22bd567bad861527cb1ccc15dc90ebb7ee2cbb6
refs/heads/master
2020-07-21T05:24:02.728705
2016-11-15T20:35:18
2016-11-15T20:35:18
73,852,940
4
1
null
null
null
null
UTF-8
C++
false
false
2,737
cpp
wheelbox.cpp
#include "wheelbox.h" #include <qwt_wheel.h> #include <qlcdnumber.h> #include <qlabel.h> #include <qlayout.h> #include <qevent.h> #include <qapplication.h> class Wheel: public QwtWheel { public: Wheel( WheelBox *parent ): QwtWheel( parent ) { setFocusPolicy( Qt::WheelFocus ); parent->installEventFilter( this ); } virtual bool eventFilter( QObject *object, QEvent *event ) { if ( event->type() == QEvent::Wheel ) { const QWheelEvent *we = static_cast<QWheelEvent *>( event ); QWheelEvent wheelEvent( QPoint( 5, 5 ), we->delta(), we->buttons(), we->modifiers(), we->orientation() ); QApplication::sendEvent( this, &wheelEvent ); return true; } return QwtWheel::eventFilter( object, event ); } }; WheelBox::WheelBox( const QString &title, double min, double max, double stepSize, QWidget *parent ): QWidget( parent ) { d_number = new QLCDNumber( this ); d_number->setSegmentStyle( QLCDNumber::Filled ); d_number->setAutoFillBackground( true ); d_number->setFixedHeight( d_number->sizeHint().height() * 2 ); d_number->setFocusPolicy( Qt::WheelFocus ); QPalette pal( Qt::black ); pal.setColor( QPalette::WindowText, Qt::green ); d_number->setPalette( pal ); d_wheel = new Wheel( this ); d_wheel->setOrientation( Qt::Vertical ); d_wheel->setInverted( true ); d_wheel->setRange( min, max ); d_wheel->setSingleStep( stepSize ); d_wheel->setPageStepCount( 5 ); d_wheel->setFixedHeight( d_number->height() ); d_number->setFocusProxy( d_wheel ); QFont font( "Helvetica", 10 ); font.setBold( true ); d_label = new QLabel( title, this ); d_label->setFont( font ); QHBoxLayout *hLayout = new QHBoxLayout; hLayout->setContentsMargins( 0, 0, 0, 0 ); hLayout->setSpacing(3); hLayout->addWidget( d_number, 0 ); hLayout->addWidget( d_wheel ); QVBoxLayout *vLayout = new QVBoxLayout( this ); vLayout->addLayout( hLayout, 0 ); vLayout->addWidget( d_label, 0, Qt::AlignTop | Qt::AlignHCenter ); connect( d_wheel, SIGNAL( valueChanged( double ) ), d_number, SLOT( display( double ) ) ); connect( d_wheel, SIGNAL( valueChanged( double ) ), this, SIGNAL( valueChanged( double ) ) ); } void WheelBox::setTheme( const QColor &color ) { d_wheel->setPalette( color ); } QColor WheelBox::theme() const { return d_wheel->palette().color( QPalette::Window ); } void WheelBox::setValue( double value ) { d_wheel->setValue( value ); d_number->display( value ); } double WheelBox::value() const { return d_wheel->value(); }
9b81b2603f1767414acf632af05c8b448e265a5c
e94d8998f95208b0b43b40b6a1cbc6eded0475c3
/core/models/model_ideal_gas.h
5dec21c67a6b8d040610385d9feaeeb56b4ca5ca
[]
no_license
ymishut/asp_therm
9ace243e3151859eb367822f38f54b1abeac6bdd
01737d7bec66aa73509e7e307d12d4b0325b639f
refs/heads/master
2021-04-09T16:18:00.902487
2018-06-19T14:49:29
2018-06-19T14:49:29
125,764,375
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
h
model_ideal_gas.h
#ifndef _CORE__MODELS__MODEL_IDEAL_GAS_H_ #define _CORE__MODELS__MODEL_IDEAL_GAS_H_ #include "model_general.h" #include <memory> class IdealGas final: public modelGeneral { private: IdealGas(modelName mn, parameters prs, const_parameters cgp, dyn_parameters dgp, binodalpoints bp); IdealGas(modelName mn, parameters prs, parameters_mix components, binodalpoints bp); public: static IdealGas *Init(modelName mn, parameters prs, const_parameters cgp, dyn_parameters dgp, binodalpoints bp); static IdealGas *Init(modelName mn, parameters prs, parameters_mix components, binodalpoints bp); // ========================== <^__.__^> =============================== // OVERRIDED METHODS // ========================== <^__.__^> =============================== void update_dyn_params(dyn_parameters &prev_state, const parameters new_state) override; void DynamicflowAccept(DerivateFunctor &df) override; bool IsValid() const override; // void setTemperature(double v, double p); void SetVolume(double p, double t) override; void SetPressure(double v, double t) override; double GetVolume(double p, double t) const override; double GetPressure(double v, double t) const override; }; #endif // ! _CORE__MODELS__MODEL_IDEAL_GAS_H_
3fbadbd5e73fd4fab3b8dd03c3c11b94dd3a5801
114a6b0340b3f8a990089dd11a938685e767275e
/include/vector.h
72191151968e52f0d73048029e09fc85fc9c9452
[]
no_license
dixtel/gameengine
7ed41c96ab095850b8949a4b978c2d7f39dff526
7d0c70810c293a27674083758f006e260f3e8b9d
refs/heads/master
2021-09-01T14:34:26.123435
2017-12-27T13:43:21
2017-12-27T13:43:21
114,453,127
0
0
null
null
null
null
UTF-8
C++
false
false
569
h
vector.h
#ifndef VECTOR_H #define VECTOR_H #define PI 3.14159265 #include <cmath> #include <iostream> class Vector { public: Vector(); Vector(float x, float y, float z); Vector RotateXY(float degree); Vector RotateXZ(float degree); Vector RotateYZ(float degree); Vector Scale(Vector scale); Vector operator + (Vector v); Vector operator - (Vector v); friend std::ostream &operator << (std::ostream &stream, const Vector &v) { stream << "(" << v.x << ", " << v.y << ", " << v.z << ")"; return stream; } float x; float y; float z; }; #endif // VECTOR_H
c41be3af304b091d0f4a61eee58cf75900e4f87c
a740f266d47b36d44bb251c60ab211c87ed09747
/include/brainclouds2s.h
8521d805269e03238b9e0dbc1224acbef5ec1ea4
[ "Apache-2.0" ]
permissive
getbraincloud/brainclouds2s-cpp
d2920098e1ec84f551d22ab9212f0d287a46e455
5d4b2716a8503685c8ad4b1d4caa91e36befefd1
refs/heads/master
2023-07-25T00:26:26.363681
2022-11-03T21:04:17
2022-11-03T21:04:17
168,526,848
0
2
Apache-2.0
2023-03-29T20:59:21
2019-01-31T13:09:04
C++
UTF-8
C++
false
false
3,161
h
brainclouds2s.h
/* 2019 @ bitheads inc. Author: David St-Louis */ #ifndef BRAINCLOUDS2S_H_INCLUDED #define BRAINCLOUDS2S_H_INCLUDED #include <functional> #include <memory> #include <string> static const std::string DEFAULT_S2S_URL = "https://api.braincloudservers.com/s2sdispatcher"; class S2SContext; using S2SCallback = std::function<void(const std::string&)>; using S2SContextRef = std::shared_ptr<S2SContext>; class S2SContext { public: /* * Create a new S2S context * @param appId Application ID * @param serverName Server name * @param serverSecret Server secret key * @param url The server url to send the request to. You can use * DEFAULT_S2S_URL for the default brainCloud servers. * @param autoAuth If sets to true, the context will authenticate on the * first request if it's not already. Otherwise, * authenticate() or authenticateSync() must be called * successfully first before doing requests. WARNING: This * used to be implied true. * * It is recommended to put this to false, manually * call authenticate, and wait for a successful response * before proceeding with other requests. * @return A new S2S context, or nullptr if something bad happened. */ static S2SContextRef create(const std::string& appId, const std::string& serverName, const std::string& serverSecret, const std::string& url, bool autoAuth); virtual ~S2SContext() {} /* * Set wether S2S messages and errors are logged to the console * @param enabled Will log if true. Default false */ virtual void setLogEnabled(bool enabled) = 0; /* * Authenticate with brainCloud. If autoAuth is set to falsed, which is * the default, this must be called successfully before doing other * requests. See S2SContext::create * @param callback Callback function */ virtual void authenticate(const S2SCallback& callback) = 0; /* * Same as authenticate, but waits for result. This call is blocking. * @return Authenticate result */ virtual std::string authenticateSync() = 0; /* * Send an S2S request. * @param json Content to be sent * @param callback Callback function */ virtual void request( const std::string& json, const S2SCallback& callback) = 0; /* * Send an S2S request, and wait for result. This call is blocking. * @param json Content to be sent * @return Request result */ virtual std::string requestSync(const std::string& json) = 0; /* * Update requests and perform callbacks on the calling thread. * @param timeoutMS Time to block on the call in milliseconds. * Pass 0 to return immediately. */ virtual void runCallbacks(uint64_t timeoutMS = 0) = 0; protected: S2SContext() {} }; #endif /* BRAINCLOUDS2S_H_INCLUDED */
4c9498b0fee07f0753ba9dcf626f54fafc9b6b27
79e400ebdfd2f28e975781931f15521baa4f81c9
/divideWithoutOpr.cpp
ecc813511575fbf8edb6c11bf06dd12a930424f8
[]
no_license
fkl/algo-problems
1ac60566186d0ba4ade380575346fad609227b3c
95dad464983c039ec4e6063d2cc4115363400e6a
refs/heads/master
2020-05-22T23:07:02.152897
2019-05-21T02:01:44
2019-05-21T02:01:44
26,101,209
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
divideWithoutOpr.cpp
// Find x / y (integer division) without using divison or multiplication operator int divide(int divident, int divisor) // 8/3 { int d = divisor; int q = 1; // quotient starts from 0 here // TODO - Handle special cases latter. (divide by 0), numbers being same or divisor being greater. First get the general algo //while( d < divident) { // d = d + divisor; // really slow but for 8/3 add 3 every time // q+=1; q starts from zero in this case //} if(divisor == 0) return -1; if(divisor == divident) return 1; if(divisor > divident) return 0; // Instead try doubling d every time while( d < divident) { d = d << 1; q = q << 1;// q starts from 1 here } if (d > divident) { d = d >> 1; q = q >> 1; return q + divide(divident-d, divisor); } return q; }
090026d863cd876d8385f250f1882e335d6b0f7b
0f8c77ea5ba9a793a733a62d199f078f5b007641
/xinput1_3/ccMessageInfo.cpp
e91e5f0c48a4a4df19e727dd02a15abbf3310353
[]
no_license
zealottormunds/nsrmoddingapi
e42adc78bc44c7b67feb50a13d41db8a9dff70ed
d4fbbb9b64c7ccd3fc2ac846d467db18caf32838
refs/heads/master
2022-11-22T13:36:53.756532
2020-07-23T22:15:39
2020-07-23T22:15:39
282,067,403
0
0
null
null
null
null
UTF-8
C++
false
false
4,319
cpp
ccMessageInfo.cpp
#include <windows.h> #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <filesystem> #include "ccMessageInfo.h" #include "xinput1_3.h" #include "HookFunctions.h" #include "ccUpdater.h" using namespace moddingApi; using namespace std; // Initialize void ccMessageInfo::Initialize() { HookFunctions::InitializeHooks(); } // GAME MESSAGE TO STRING typedef char *(__cdecl * message_to_string)(char *); message_to_string g_MessageToString; char * ccMessageInfo::MessageToString(char * msg) { g_MessageToString = (message_to_string)(xinput1_3::moduleBase + 0x58E950); return g_MessageToString(msg); } // GAME MESSAGE TO STRING ALT typedef char *(__cdecl * message_to_string2)(char *); message_to_string2 g_MessageToString2; char * ccMessageInfo::MessageToString2(char * msg) { //g_MessageToString2 = (message_to_string2)(xinput1_3::moduleBase + 0x58E990); g_MessageToString2 = (message_to_string2)(xinput1_3::moduleBase + 0x58E9C0); return g_MessageToString2(msg); } // Message conversions (ids to the equivalent of messageInfo) bool ccMessageInfo::MessageConversions = true; void ccMessageInfo::DisableMessageConversion() { ccMessageInfo::MessageConversions = false; } void ccMessageInfo::EnableMessageConversion() { ccMessageInfo::MessageConversions = true; } // For custom messages vector<string> ccMessageInfo::ReadMessageFile(string _file) { ifstream f; f.open(_file); vector<string> Messages; string actual = ""; while (!f.eof()) { char a = f.get(); if (a != 0x00) { actual = actual + a; } else { //cout << "Push back " << actual << endl; Messages.push_back(actual); actual = ""; } } f.close(); return Messages; } vector<string> ccMessageInfo::MessageID; vector<string> ccMessageInfo::MessageStr; vector<string> ccMessageInfo::MessageID_ALT; vector<string> ccMessageInfo::MessageStr_ALT; uintptr_t ccMessageInfo::GetCustomMessage1(uintptr_t MessageToDecode) { return ccMessageInfo::GetCustomMessage(MessageToDecode, false); } uintptr_t ccMessageInfo::GetCustomMessage2(uintptr_t MessageToDecode) { return ccMessageInfo::GetCustomMessage(MessageToDecode, true); } // Custom message conversions uintptr_t ccMessageInfo::GetCustomMessage(uintptr_t MessageToDecode, bool alt = false) { if (ccMessageInfo::MessageConversions == 1 && strlen((char*)MessageToDecode) > 0 && *(char*)MessageToDecode != '+') { HookFunctions::UndoMessageInfoHook(); char* result = ccMessageInfo::MessageToString((char*)MessageToDecode); HookFunctions::DoMessageInfoHook(); if (alt) { HookFunctions::UndoMessageInfoHook2(); result = ccMessageInfo::MessageToString2((char*)MessageToDecode); HookFunctions::DoMessageInfoHook2(); } if (MessageToDecode != 0) { bool finished = false; string message((char*)MessageToDecode); if (message == "network_agreement_EU_s-A" || message == "network_agreement_s-A") { result = "lmao"; //(char*)GetModMessage().c_str(); finished = true; } else if (message == "network_agreementp2_EU_s-A" || message == "network_agreementp2_s-A") { result = ""; finished = true; } if (finished == false) { std::string msg = (std::string)(char*)MessageToDecode; if (msg == "network_agreement_ng") result = "<icon btn_2 />"; else { //if (msg == "battleresult_002") result = "1P Health: %%%, 2P Health: %%%"; if (msg == "MSG_AutoSaveWarn") result = (char*)(ccUpdater::CheckUpdates().c_str()); else { if (alt == false) { for (int x = 0; x < MessageID.size(); x++) { if (msg == MessageID[x]) { result = (char*)MessageStr[x].c_str(); } } } else { for (int x = 0; x < MessageID_ALT.size(); x++) { if (msg == MessageID_ALT[x]) { result = (char*)MessageStr_ALT[x].c_str(); } } } } } if (msg != (std::string)(char*)MessageToDecode) result = (char*)msg.c_str(); } } //cout << (char*)result << endl; return (uintptr_t)result; } else { if (*(char*)MessageToDecode == '+') { return (MessageToDecode + 1); } string m((char*)MessageToDecode); m = m + " [ALT]"; if (alt) return (uintptr_t)(m.c_str()); return MessageToDecode; } }
e0005d204ed947a4c5aa6b47889b7968a64b4845
cf83a5a268a1dac196b84c19d5d32c88cd6646f3
/Algorithms/Hierarchical_Clustering/HierarchicalClustering.hpp
ba92861051e7208d568db76dbb7b32b441396719
[]
no_license
mukhir/MasterProject
001cc995164070094385da694c6a61873d71d722
3a4f9e3944cfb3be81d146153b224dcdad194b00
refs/heads/master
2021-08-30T12:07:27.755492
2017-12-17T21:39:25
2017-12-17T21:39:25
114,570,519
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
hpp
HierarchicalClustering.hpp
#ifndef _PAULY_ITERATIVE_SIMPLIFICATION_ #define _PAULY_ITERATIVE_SIMPLIFICATION_ #include "Defs.hpp" #include <queue> class HierClustering { public: HierClustering(); ~HierClustering(); void init(const std::string filename); uint32_t contract(void* buffer, uint32_t finalCount); private: static const int N_MAX = 40; float threshold; size_t _allCount; size_t _currPoints; splatHierClustering* _splatHierClustering; std::list<hCluster> _hCluster; std::list<int> f; //====================================================================== // Private functions //====================================================================== void _readFileIntoMemory(const std::string filename); void _initializeCluster(); void _splitRecursive(hCluster& hc); void _combineSplats(uint32_t finalCount); uint32_t _writeOutputToBuffer(void* buffer); std::priority_queue< hCluster*, std::vector<hCluster*> , clusterComparison > _pQueueCluster; }; #endif
2f36fa0df897df26da803fd900dd7f2656458beb
e7b39d33c9fd7e98365e14a4d232be9b76f9ee02
/operation.cpp
510c24f69ab1f49fe65f6d2b16e90e304b416cf8
[ "MIT" ]
permissive
yx-lu/RRAM-Emulator
4bc80d6cb1f72e7e0ea4edc7caee6d16e6e405c1
d9c23ea48d4fc4966a360b83b915bd4d4c455d55
refs/heads/master
2022-09-09T20:08:15.831620
2020-05-27T03:53:08
2020-05-27T03:53:08
251,618,772
3
0
null
2020-04-11T10:18:18
2020-03-31T13:57:40
C++
UTF-8
C++
false
false
2,835
cpp
operation.cpp
#include <iostream> #include <algorithm> #include "rram_allocator.h" BIT shifter_bit[Size]; RRAM *shifter[Size]; BIT rotater_bit[Size]; RRAM *rotater[Size]; BIT left_shifter_bit[Size]; RRAM *left_shifter[Size]; BIT allset_bit[Size]; RRAM *allset; void Initializer() { for (int i = 0; i < Size; i++) shifter_bit[i].set(i); shifter[0] = new RRAM(shifter_bit); for (int d = 0; d < Size - 1; d++) { for (int i = 0; i < Size; i++) shifter_bit[i]<<=1; shifter[d+1] = new RRAM(shifter_bit); } for (int i = 0; i < Size; i++) rotater_bit[i].set(i); rotater[0] = new RRAM(rotater_bit); for (int d = 0; d < Size - 1; d++) { for (int i = 0; i < Size; i++) rotater_bit[i]<<=1; rotater_bit[d].set(0); rotater[d+1] = new RRAM(rotater_bit); } for (int i = 0; i < Size; i++) left_shifter_bit[i].set(i); left_shifter[0] = new RRAM(left_shifter_bit); for (int d = 0; d < Size - 1; d++) { for (int i = 0; i < Size; i++) left_shifter_bit[i]>>=1; left_shifter[d+1] = new RRAM(left_shifter_bit); } for (int i = 0; i < Size; i++) allset_bit[i].set(0); allset= new RRAM(allset_bit); } void shift(int d, row &r1, row &r2) { r1.fr->line2buf(r1.fore); trans_buf(*r1.fr, *shifter[d]); shifter[d]->mult(); trans_buf(*shifter[d], *r2.fr); r2.fr->buf2line(r2.fore); r2.fr->lineset(r2.back); r2.fr->lineop(r2.back,r2.fore); } void rotate(int d, row &r1, row &r2) { r1.fr->line2buf(r1.fore); trans_buf(*r1.fr, *rotater[d]); rotater[d]->mult(); trans_buf(*rotater[d], *r2.fr); r2.fr->buf2line(r2.fore); r2.fr->lineset(r2.back); r2.fr->lineop(r2.back,r2.fore); } void leftshift(int d,row &r1, row &r2) { r1.fr->line2buf(r1.fore); trans_buf(*r1.fr, *left_shifter[d]); left_shifter[d]->mult(); trans_buf(*left_shifter[d], *r2.fr); r2.fr->buf2line(r2.fore); r2.fr->lineset(r2.back); r2.fr->lineop(r2.back,r2.fore); } void allsetter(row &r1, row &r2){ r1.fr->line2buf(r1.fore); trans_buf(*r1.fr, *allset); allset->mult(); trans_buf(*allset, *r2.fr); r2.fr->buf2line(r2.fore); r2.fr->lineset(r2.back); r2.fr->lineop(r2.back,r2.fore); } void add(row &r1, row &r2){ row r3; row r4; row r5; row r6; row r7; r3.set(); r4.set(); r3&=r1; r4&=r2; for(int i=0;i<Size;++i){ r5.set(); r6.set(); r5&=r3; r5^=r4; r6&=r3; r6&=r4; leftshift(1,r6,r4); r3.set(); r3&=r5; } r1.set(); r1&=r5; } void substract(row &r1, row &r2){ row r3; r3.set(); r3&=!r2; add(r1,r3); r3.write(BIT(1)); add(r1,r3); } void mutiply(row &r1, row &r2){ row r3; row r4; r3.set(); r4.set(); r3&=r1; r4&=r2; row r5; r5.reset(); row rarray[Size]; for(int i=0;i<Size;++i){ rarray[i].write(BIT(1<<i)); } for(int i=0;i<Size;++i){ row r6; r6.write(BIT(1)); r6&=r4; allsetter(r6,r6); row r7; r7.set(); r7&=r3; r7&=r6; add(r5,r7); leftshift(1,r3,r3); shift(1,r4,r4); } r1.set(); r1&=r5; }
6344ce26c658c61f327857a2d942b63425445447
ff296424a72aed53e3169eab611809a4883c7fcf
/Assignment3/include/quad.h
305bd76fe7494b2980c98b88d48ec58fba9b9662
[]
no_license
ozym4nd145/COL781
353c4346f74710416a75b051a8bf48b021ed4c4e
5b39d399002f69dd480ba87880a35afe915901c4
refs/heads/master
2020-04-17T04:08:47.558792
2019-04-21T12:28:12
2019-04-21T12:28:12
166,216,029
1
1
null
null
null
null
UTF-8
C++
false
false
346
h
quad.h
#pragma once #include <vector> #include <glad/glad.h> // holds all OpenGL type declarations #include <learnopengl/shader.h> class Quad { private: unsigned int VAO; unsigned int VBO; void setupQuad(); public: Quad(); void Draw(Shader shader,const std::vector<unsigned int>& textureIds); };
12e32ec2a1ca635e7c5c032e05d5a3c735e2384f
b167407960a3b69b16752590def1a62b297a4b0c
/samples/Test/Classes/Control/TableViewTest.h
6384cc1e1fefd063605376af87af00f2a142dc73
[ "MIT" ]
permissive
xcode1986/nineck.ca
543d1be2066e88a7db3745b483f61daedf5f378a
637dfec24407d220bb745beacebea4a375bfd78f
refs/heads/master
2020-04-15T14:48:08.551821
2019-01-15T07:36:06
2019-01-15T07:36:06
164,768,581
1
1
MIT
2019-01-15T08:30:27
2019-01-09T02:09:21
C++
UTF-8
C++
false
false
1,278
h
TableViewTest.h
#ifndef __Test__TableViewTest__ #define __Test__TableViewTest__ #include "RootWindow.h" class TableViewTest: public CAViewController { public: TableViewTest(); virtual ~TableViewTest(); CREATE_FUNC(TableViewTest); protected: void viewDidLoad(); void viewDidUnload(); //TableView void tableViewDidSelectRowAtIndexPath(unsigned int section, unsigned int row); void tableViewDidDeselectRowAtIndexPath(unsigned int section, unsigned int row); CATableViewCell* tableCellAtIndex(DSize cellSize, unsigned int section, unsigned int row); CAView* tableViewSectionViewForHeaderInSection(DSize viewSize, unsigned int section); CAView* tableViewSectionViewForFooterInSection(DSize viewSize, unsigned int section); unsigned int numberOfRowsInSection(unsigned int section); unsigned int numberOfSections(); unsigned int tableViewHeightForRowAtIndexPath(unsigned int section, unsigned int row); unsigned int tableViewHeightForHeaderInSection(unsigned int section); unsigned int tableViewHeightForFooterInSection(unsigned int section); private: CATableView* m_pTableView; std::vector<std::string> m_pSectionTitle; }; #endif /* defined(__HelloCpp__ViewController__) */
a3d683de8150e8144574dac2a098c40cd6d34566
4371ef96a14e62c97bd898fb9ed425f0206baa4e
/MarioCardGame/Game.cpp
0d653f00009c351f9a464bdcb7274f96d728f3d9
[]
no_license
thenfour/Archives
e03413ece7b71552a99308c58cc4b76dbf94a000
f7c87afe644989b5e8b3d2c1e30ca4546658138d
refs/heads/master
2020-04-10T06:31:10.444614
2014-02-18T01:51:55
2014-02-18T01:51:55
16,931,568
2
0
null
null
null
null
UTF-8
C++
false
false
4,757
cpp
Game.cpp
#include ".\game.h" #include <windows.h> #include <algorithm> int MarioRand(int n) { return rand() % n; } namespace MarioSim { Game::Game(int arenaWidth, int arenaHeight) : m_arenaWidth(arenaWidth), m_arenaHeight(arenaHeight) { srand(GetTickCount()); } Game::~Game() { } Card Game::GetAt(int i) const { if(i < 0) return Card(); if(i >= (int)m_arena.size()) return Card(); return m_arena[i]; } Card Game::GetAt(const Point& p) const { return GetAt(XYtoIndex(p)); } int Game::XYtoIndex(const Point& p) const { if(p.first < 0) return -1; if(p.first >= m_arenaWidth) return -1; if(p.second < 0) return -1; if(p.second >= m_arenaHeight) return -1; return (p.second * m_arenaHeight) + p.first; } Point Game::IndexToXY(int index) const { return Point(index % m_arenaWidth, index / m_arenaHeight); } Game::Outcome Game::Move(const Point& a, const Point& b, int& pointDelta) { return Move(XYtoIndex(a), XYtoIndex(b), pointDelta); } void Game::Reset(int nEachType) { m_deck.clear(); m_arena.clear(); int count; int serial = 100; std::vector<Card::Face> faces; faces.push_back(Card::Goomba); faces.push_back(Card::Mushroom); faces.push_back(Card::Flower); faces.push_back(Card::Mario); faces.push_back(Card::Bowser); faces.push_back(Card::Cloud); faces.push_back(Card::Luigi); faces.push_back(Card::Star); std::vector<Card::Face>::const_iterator faceIt; for(count = 0; count < nEachType; count ++, serial ++) { for(faceIt = faces.begin(); faceIt != faces.end(); ++ faceIt) { m_deck.push_back(Card(*faceIt, serial)); } } std::random_shuffle(m_deck.begin(), m_deck.end(), MarioRand); _DealOut(); } Game::Outcome Game::Move(int a, int b, int& pointDelta) { pointDelta = 0; // sort a & b so that a < b (makes stuff easier) if(b < a) { std::swap(a, b); } Card cardA = GetAt(a); Card cardB = GetAt(b); Point ptA = IndexToXY(a); Point ptB = IndexToXY(b); // must be similar cards if(cardA.m_face != cardB.m_face) { return Game::InvalidMove; } // must be valid cards if(cardA.m_face == Card::Blank) { return Game::InvalidMove; } // must be near eachother. if((abs(ptA.first - ptB.first) > 1) || (abs(ptA.second - ptB.second) > 1)) { return Game::InvalidMove; } // must not be the same card. if(a == b) { return Game::InvalidMove; } // OK; appears to be a legal move. Go ahead. m_arena.erase(m_arena.begin() + b); m_arena.erase(m_arena.begin() + a); // deal out cards. _DealOut(); // Check for winnar! if(0 == m_arena.size()) { pointDelta = 10; return GameWon; } // check for loser! int nMovesLeft = 0; // go through each card and see if it has a move. if so, break. int x, y; for(y = 0; y < m_arenaHeight; y ++) { for(x = 0; x < m_arenaWidth; x ++) { if(_HasMovesAvailable(x, y)) { nMovesLeft = 1; break; } } if(nMovesLeft) { break; } } if(!nMovesLeft) { pointDelta = (int)m_arena.size(); pointDelta = -pointDelta; return GameLost; } return Success; } void Game::_DealOut() { // remove trailing blank cards (just in case) while(m_arena.size() && (m_arena.back().m_face == Card::Blank)) { m_arena.pop_back(); } // now deal in cards until the arena is filled while(m_deck.size() && ((int)m_arena.size() < (m_arenaHeight * m_arenaWidth))) { m_arena.push_back(m_deck.back()); m_deck.pop_back(); } return; } bool Game::_HasMovesAvailable(int x, int y) { Card card = GetAt(Point(x, y)); if(card.m_face == Card::Blank) return false; // check to the left if(GetAt(Point(x - 1, y)).m_face == card.m_face) { return true; } // check to the right if(GetAt(Point(x + 1, y)).m_face == card.m_face) { return true; } // check lower-left if(GetAt(Point(x - 1, y + 1)).m_face == card.m_face) { return true; } // check lower-center if(GetAt(Point(x, y + 1)).m_face == card.m_face) { return true; } // check lower-right if(GetAt(Point(x + 1, y + 1)).m_face == card.m_face) { return true; } return false; } }
be88c3360c65862ec28567be835f8691704ab200
4c2881b7dc0b4c464247b310163bfade133057ea
/P1/include/bound_computator.hpp
8fcfa05e230cfa637966c47b9a657871b3a2a280
[]
no_license
TooCynical/CD
9323c5c8c98001008bb7fb79bded052de5050ded
1e4dcb37e7ec7723b52ac7e93bfbcc55602ddf43
refs/heads/master
2020-12-30T12:24:28.298130
2017-07-08T11:54:03
2017-07-08T11:54:03
91,384,787
0
0
null
null
null
null
UTF-8
C++
false
false
7,650
hpp
bound_computator.hpp
/* Lucas Slot (lfh.slot@gmail.com) * Ardalan Khazraei (ardalan.khazraei@gmail.com) * * June 2017 * University of Bonn * * bound_computator.hpp * * BoundComputator is a class that, given a valid Instance object * representing an instance of the 3d rectilinear steiner tree problem * contains functionality to compute lower bounds and upper bounds * used in the Dijkstra-Steiner algorithm with future costs and pruning. * A LowerBoundOptions struct should be provided to specify which lower * bound(s) should be used. * In particular, it is capable of computing: * - The length of an MST on a given terminal set * - The bounding box lower bound BB(v, I) of a label. * - The One-Tree lower bound MST(v, I) of a label. * * - A local upper bound U(I) for a bitset I given a label * (v, I). * - A local upper bound U(I u J) given two bitsets I and J. * * - The distance between a terminal set I and its complement. * - The distance between a vertex v and the complement * of a terminal set I. * - The vertex / terminal attaining these minimum distances. * * In order to efficiently make use of / look up previous computational * results, BoundComputator contains hash tables using bitsets * as keys, containing MST(I), A(I), d(I, R-I). * * * BoundComputator makes the same assumptions on the given instance * Solver does. * * * Notation used: * P : The set of all permanently valued labels. * R : The set of all terminals * l(v,I) : the (tentative) value of a label. * LB(v, I) : the (permanent) lower bound for a label. * root : The root terminal (always the first terminal * in the array _terminals in the given instance). * U(I) : The best local upper bound for the terminal set I. * S(I) : The set of terminals used to compute U(I) for a * terminal set I. * A(I) : The pair (U(I), S(I)) for a terminal set I. */ #ifndef LOWERBOUND_HPP #define LOWERBOUND_HPP #include "util.hpp" #include "vertex.hpp" #include "instance.hpp" #include "label.hpp" #include <stdlib.h> #include <vector> #include <bitset> #include <climits> #include <unordered_map> #include <set> #include <utility> #include <iterator> using namespace std; /* Forward declarations */ class Label; class Vertex; class Instance; struct BoundOptions { bool _use_BB_lower_bound; bool _use_onetree_lower_bound; }; struct PerimeterCoords { int _x_max, _x_min; int _y_max, _y_min; int _z_max, _z_min; }; class BoundComputator { private: /* The problem instance for which this BoundComputator should * compute bounds. */ Instance *_underlying_instance; int _n_terminals; // The amount of terminals in the // underlying instance. Vertex **_terminals; // References to the terminals in // the underlying instance. bool _use_BB_lower_bound; // Use Bounding Box lb? bool _use_onetree_lower_bound; // Use 1-Tree lb? /* Hash table containing MST(R-I) for a terminal set I, if * it has been computed already. */ unordered_map<bitset<BITSET_SIZE>, int> _MST_hash; /* Hash table containing (d(I, R-I), i) for a terminal set I, if * it has been computed already, where i is the index of the terminal * in R-I minimizing d(i, I). */ unordered_map<bitset<BITSET_SIZE>, pair<int, int> > _distance_hash; /* Hash table containing pairs A(I) = (U(I), S(I)), where * U(I) is the current upper bound for a terminals set I, and * S(I) is the set of terminals used to find U(I). */ unordered_map<bitset<BITSET_SIZE>, pair<int, bitset<BITSET_SIZE> > > _upper_bound_hash; /* Hash table containg pairs (x_max, x_min, y_max, y_min) for * a terminal set I. */ unordered_map<bitset<BITSET_SIZE>, PerimeterCoords> _perimeter_hash; /* Find the distance d(I, R-I) between a terminal set and its * complement, as well as the index of the terminal i in R-I * minimizing d(i, I) either by fetching these values from the * hash table if possible, or computing them. After a * compputation the results are stored in _distance_hash. */ Result GetComplementDistance(const bitset<BITSET_SIZE> &I, int &ret_dist, int &ret_ind); /* Compute the distance d(I, R-I) between a terminal set and its * complement, as well as the index of the terminal i in R-I * minimizing d(i, I) in O(|I||R-I|). */ Result ComplementDistance(const bitset<BITSET_SIZE> &I, int &ret_dist, int &ret_ind); /* Compute the distance d(v, R-I) between a vertex and the * complement ofthe given terminal set, as well as the index * of the terminal i in R-I minimizing d(v, i) in O(|R-I|). */ Result VertexComplementDistance(const bitset<BITSET_SIZE> &I, Vertex *v, int &ret_dist, int &ret_ind); public: /* Return l(v, I) > U(I), the local upper bound for I. */ bool CompareToUpperBound(Label *l); /* Update the local upper bound U(I) given a label of the form * (v, I) by setting * U(I) = min(U(I), l(v,I) + min(d(v, R-I), d(I, R-I))). * Also update S(I) appropriately. We assume here that (v,I) * is the label minimizing l(v, I) + lb(v, I) among all labels * not in P. */ Result UpdateUpperBound(Label *l); /* Update the local upper bound U(I u J) given two terminal sets * I and J with I \cap S(J) or J \cap S(I) empty by setting: * U(I u J) = min(U(I u J), U(I) + U(J)). * Also update S(I u J) if needed by setting * S(I u J) = S(I) u S(J) - I - J. */ Result MergeUpperBound(const bitset<BITSET_SIZE> &I, const bitset<BITSET_SIZE> &J); /* Constructor */ BoundComputator(Instance *inst, BoundOptions *opts); /* Compute the coordinates of the perimeter of I, that is * x_max, x_min, y_max, y_min, z_max, z_min for I. */ PerimeterCoords Perimeter(const bitset<BITSET_SIZE> &I); /* Compute the bounding box length BB({v} u I) for the given (v, I) * The required perimeter of I is fetched from the hash table if * possible, and computed otherwise. */ int BBLowerBound(Label *l); /* Compute the length of an MST on the given terminal set using * Prim's algorithm running in O(|R|^2). */ int MST(const bitset<BITSET_SIZE> &I); /* Compute the 1-tree lower bound for the given label (v, I). * The required value MST(I) is fetched from the hash table if * possible, and computed otherwise. */ int OneTreeLowerBound(Label *l); /* Return the lb(v, I) for the given label, where lb is * a lower bound function determined by the values of * _use_BB_lower_bound and _use_MST_lower_bound. */ int GetLowerBound(Label *l); /* Getters / Setters. */ Result SetUseBBLowerBound(); Result SetUseOneTreeLowerBound(); }; #endif
f00a63b784acfc7e8a5bc1b9a405c00fd3be3155
2747bddb0b877157de2d79235f543ebf49a944af
/Source/LD47/Public/SpawnController.h
009680160508744295ca1c27fe94e6a2f5cd3c6a
[]
no_license
Jakey113G/LD47
a022a177175d59b17962d1eeaa091a41bc814c2f
cbd082a08d9b4c37f01d0a3522e51a5e7b3cc06b
refs/heads/main
2022-12-22T21:21:37.307346
2020-10-04T21:09:14
2020-10-04T21:09:14
301,503,784
0
0
null
null
null
null
UTF-8
C++
false
false
836
h
SpawnController.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "SpawnController.generated.h" //Not sure if this the best approach. but didn't want to waste time creating a CPP derived level BP or putting logic in player state. UCLASS() class LD47_API ASpawnController : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ASpawnController(); TArray<AActor*> FoundActors; UPROPERTY(EditAnywhere, Category = "SpawnRate") float SpawnTime; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; float m_elapsedTime; int m_NextIndexToTry; public: // Called every frame virtual void Tick(float DeltaTime) override; void SpawnObjective(); };
dc2a08cff776d0dc821dd9fb3dbdd25247952f05
6781eda39f260144f9c4a1a9c46ea29e8a03469c
/include/TL_ThreadLock.h
2d081de8f03219bb0853deba38d00ef61a6f542c
[]
no_license
everpan/tidp
74b1a5ec6756023db633341f7aa40bbe05293a66
92e5f5f208c5d1dac9c113acf29b624786bf8e08
refs/heads/master
2021-07-09T08:01:58.257355
2020-08-27T03:44:31
2020-08-27T03:44:31
25,238,168
0
0
null
null
null
null
UTF-8
C++
false
false
1,797
h
TL_ThreadLock.h
/* * File: TL_ThreadLock.h * Author: everpan * * Created on 2011ๅนด3ๆœˆ18ๆ—ฅ, ไธ‹ๅˆ3:59 */ #ifndef TL_THREADLOCK_H #define TL_THREADLOCK_H #include <pthread.h> #include <errno.h> #include <time.h> #include <sys/time.h> #include <sys/types.h> #include "TL_Exp.h" #include "TL_Monitor.h" namespace tidp { class TL_ThreadMutex { public: typedef TL_Lock<TL_ThreadMutex> Lock; TL_ThreadMutex(); virtual ~TL_ThreadMutex() noexcept(false); void lock() const; void unlock() const; bool tryLock() const; friend class TL_ThreadCond; protected: TL_ThreadMutex(const TL_ThreadMutex &); mutable pthread_mutex_t _mutex; }; class TL_ThreadCond { public: TL_ThreadCond(); virtual ~TL_ThreadCond() noexcept(false); bool wait(const TL_ThreadMutex &mutex); bool timedwait(const TL_ThreadMutex &mutex, int millsecond); static struct timespec abstime(int millsecond); void broadcast(); void signal(); protected: TL_ThreadCond(const TL_ThreadCond &); mutable pthread_cond_t _cond; }; class TL_ThreadRwLock { public: typedef TL_RdLock<TL_ThreadRwLock> RLock; typedef TL_WrLock<TL_ThreadRwLock> WLock; TL_ThreadRwLock(); ~TL_ThreadRwLock() noexcept(false); int rdlock() const; int wrlock() const; int unlock() const; protected: TL_ThreadRwLock(const TL_ThreadRwLock &); mutable pthread_rwlock_t _rwlock; }; typedef TL_Monitor<TL_ThreadMutex, TL_ThreadCond> TL_ThreadLock; typedef TL_Lock<TL_ThreadMutex> TL_MutexLock; //typedef TL_Lock<TL_ThreadMutex> TL_ThreadMutexLock; } #endif /* TL_THREADLOCK_H */
3b4cb46adcca5e6c749af976fbfaf3dce7ff9d93
cfc67668aad239f25d1a6f7072ae267898fd1300
/Spider/Server/Database/Test.cpp
c0074e5567178585cd86a3eb6157a8a87d784908
[]
no_license
VictorDebray/Spider
4ddfcc3a21075b5dc7f83c55b78e00782a337501
cb36e513b26a8dfd9eddf8efc73f7a51931e89bb
refs/heads/master
2021-09-02T05:59:44.940120
2017-12-30T22:04:45
2017-12-30T22:04:45
115,740,152
0
0
null
null
null
null
UTF-8
C++
false
false
256
cpp
Test.cpp
/* ** Test.cpp for untitled2 in /untitled2/Test.cpp ** ** Made by Paul MENDIELA ** Login <paul.mendiela@epitech.eu> ** ** Started on sam. oct. 07 20:01:51 2017 Paul MENDIELA ** Last update sam. oct. 07 20:01:51 2017 Paul MENDIELA */ #include "Test.hpp"
718730d3af90ca0f1346df7485eda42c964517a1
f661f21f05048d2ffdb657424ef7bb6dfa2010ad
/cf/Codeforces Round #572 (Div. 2)-C.cpp
a611e0edd6b8b5e5eb0ff4c0548bb76dd02b5091
[]
no_license
HXYerror/linux-acm
ecb72b5824bcd8492a189403d2ceb05008d4e738
16cd79c55c762af1f6ded4e838bce0b442d01cce
refs/heads/master
2021-07-14T06:52:13.142918
2021-06-26T08:59:19
2021-06-26T08:59:19
218,274,442
0
0
null
null
null
null
UTF-8
C++
false
false
2,160
cpp
Codeforces Round #572 (Div. 2)-C.cpp
//#include<bits/stdc++.h> #include <iostream> #include <cstdio> #include <cmath> #include <iomanip> #include <string> #include <cstring> #include <algorithm> #include <set> #include <map> #include <vector> #include <queue> #include <stack> #define LL long long using namespace std; const int MAX = 100010;//100000 const int MAX_1 = 2010; const int INF = 0x3f3f3f3f;//1061109567,1e9,int-MAX2147483647; const double EPS = 0.0000001; const int MOD = 10;//998244353; int T,N,M; /*-------------------------------------------------------------------------------------------*/ int table[35][MAX]; int a[MAX]; int b[35][MAX]; /* ------------------------------------------------------------------------------------------*/ int main() { std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); //freopen("input.in","r",stdin); //freopen("output.out","w",stdout); /* --------------------------------------------------------------------------------------*/ cin >> N; for(int i = 0;i < N;i++) { cin >> a[i]; } int k = 0; int sum = 0; for(int j = 0;(1 << j) < N;j++) { int n = 1 << j; for(int i = 0;i < N - sum;i++) { if(i+n >= N-sum) break; k = a[i] + a[i+n]; if(k >= 10) table[j][i] = 1; else table[j][i] = 0; if(i < n*2) { if(table[j][i]) b[j][i] =1; else b[j][i] = 0; } else { if(table[j][i]) b[j][i] = b[j][i-n*2]+1; else b[j][i] = b[j][i-n*2]; } a[i] = k % MOD; } sum += n; } cin >> M; int x,y; while(M--) { int ans = 0; cin >> x >> y; int n = y - x +1; int m = 0; while(n > 1) { n = n / 2; m++; } n = y - x +1; for(int i = 1;i <= m;i++) { int p = 1 << i; n /= 2; ans += (b[i-1][x-1+(n-1)*p] -b[i-1][x-1]); if(table[i-1][x-1]) ans++; } cout << ans <<endl; } return 0; }
483e6d31275afa98f77abd10e40afe975a747b85
e8cec014c373a8599f9ac5d3768d87662528b28e
/meeting-qt/setup/UnInstall/src/base/time/time.h
49ade8e4cb94b49346086e7f29ce7ba82ca82bd5
[ "MIT" ]
permissive
xiaoge136/Meeting
ee69e309666b3132449476217033d34b92eb975d
0b85c53ee3df6d5611c84dc2b9fe564590874563
refs/heads/main
2023-07-21T14:39:03.158711
2021-08-31T14:13:18
2021-08-31T14:13:18
401,727,185
0
1
MIT
2021-08-31T14:10:04
2021-08-31T14:10:04
null
UTF-8
C++
false
false
12,228
h
time.h
/** * @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ // Copyright (c) 2011, NetEase Inc. All rights reserved. // // Author: Ruan Liang <ruanliang@corp.netease.com> // Date: 2011/6/9 // // Time represents an absolute point in time, internally represented as // microseconds (s/1,000,000) since a platform-dependent epoch. Each // platform's epoch, along with other system-dependent clock interface // routines, is defined in time_PLATFORM.cc. // // TimeDelta represents a duration of time, internally represented in // microseconds. // // TimeTicks represents an abstract time that is always incrementing for use // in measuring time durations. It is internally represented in microseconds. // It can not be converted to a human-readable time, but is guaranteed not to // decrease (if the user changes the computer clock, Time::Now() may actually // decrease or jump). #ifndef BASE_TIME_TIME_H_ #define BASE_TIME_TIME_H_ #include <time.h> #include "base/base_types.h" #include "base/base_export.h" #if defined(OS_WIN) # include <windows.h> #else # include <sys/time.h> #endif // OS_WIN namespace nbase { class Time; class TimeTicks; class BASE_EXPORT TimeDelta { public: TimeDelta() : delta_(0) {} // Converts units of time to TimeDeltas. static TimeDelta FromDays(int64_t days); static TimeDelta FromHours(int64_t hours); static TimeDelta FromMinutes(int64_t minutes); static TimeDelta FromSeconds(int64_t secs); static TimeDelta FromMilliseconds(int64_t ms); static TimeDelta FromMicroseconds(int64_t us); // Returns the internal numeric value of the TimeDelta object. int64_t ToInternalValue() const { return delta_; } #if defined(OS_POSIX) struct timespec ToTimeSpec() const; #endif // Returns the time delta in some unit. The F versions return a floating // point value, the "regular" versions return a rounded-down value. int ToDays() const; int ToHours() const; int ToMinutes() const; double ToSecondsF() const; int64_t ToSeconds() const; double ToMillisecondsF() const; int64_t ToMilliseconds() const; int64_t ToMillisecondsRoundedUp() const; int64_t ToMicroseconds() const; TimeDelta& operator=(TimeDelta other) { delta_ = other.delta_; return *this; } // Computations with other deltas. TimeDelta operator+(TimeDelta other) const { return TimeDelta(delta_ + other.delta_); } TimeDelta operator-(TimeDelta other) const { return TimeDelta(delta_ - other.delta_); } TimeDelta& operator+=(TimeDelta other) { delta_ += other.delta_; return *this; } TimeDelta& operator-=(TimeDelta other) { delta_ -= other.delta_; return *this; } TimeDelta operator-() const { return TimeDelta(-delta_); } // Computations with ints, note that we only allow multiplicative operations // with ints, and additive operations with other deltas. TimeDelta operator*(int64_t a) const { return TimeDelta(delta_ * a); } TimeDelta operator/(int64_t a) const { return TimeDelta(delta_ / a); } TimeDelta& operator*=(int64_t a) { delta_ *= a; return *this; } TimeDelta& operator/=(int64_t a) { delta_ /= a; return *this; } int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; } // Defined below because it depends on the definition of the other classes. Time operator+(Time t) const; TimeTicks operator+(TimeTicks t) const; // Comparison operators. bool operator==(TimeDelta other) const { return delta_ == other.delta_; } bool operator!=(TimeDelta other) const { return delta_ != other.delta_; } bool operator<(TimeDelta other) const { return delta_ < other.delta_; } bool operator<=(TimeDelta other) const { return delta_ <= other.delta_; } bool operator>(TimeDelta other) const { return delta_ > other.delta_; } bool operator>=(TimeDelta other) const { return delta_ >= other.delta_; } private: friend class Time; friend class TimeTicks; friend TimeDelta operator*(int64_t a, TimeDelta td); // Constructs a delta given the duration in microseconds. explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {} // Delta in microseconds. int64_t delta_; }; inline TimeDelta operator*(int64_t a, TimeDelta td) { return TimeDelta(a * td.delta_); } // Time ----------------------------------------------------------------------- // Represents a wall clock time. class BASE_EXPORT Time { public: static const int64_t kMillisecondsPerSecond = 1000; static const int64_t kMicrosecondsPerMillisecond = 1000; static const int64_t kMicrosecondsPerSecond = kMicrosecondsPerMillisecond * kMillisecondsPerSecond; static const int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60; static const int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60; static const int64_t kMicrosecondsPerDay = kMicrosecondsPerHour * 24; static const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7; static const int64_t kNanosecondsPerMicrosecond = 1000; static const int64_t kNanosecondsPerSecond = kNanosecondsPerMicrosecond * kMicrosecondsPerSecond; #if !defined(OS_WIN) // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to // the Posix delta of 1970. This is used for migrating between the old // 1970-based epochs to the new 1601-based ones. It should be removed from // this global header and put in the platform-specific ones when we remove the // migration code. static const int64_t kWindowsEpochDeltaMicroseconds; #endif // Represents an exploded time that can be formatted nicely. This is kind of // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few // additions and changes to prevent errors. struct BASE_EXPORT TimeStruct { int year_; // Four digit year "2011" int month_; // 1-based month (values 1 = January, etc.) int day_of_week_; // 0-based day of week (0 = Sunday, etc.) int day_of_month_; // 1-based day of month (1-31) int hour_; // Hour within the current day (0-23) int minute_; // Minute within the current hour (0-59) int second_; // Second within the current minute (0-59). int millisecond_; // Milliseconds within the current second (0-999) explicit TimeStruct() : year_(0), month_(0), day_of_week_(0), day_of_month_(0), hour_(0), minute_(0), second_(0), millisecond_(0) {} bool IsValidValues() const; int year() { return year_; } int month() { return month_; } int day_of_week() { return day_of_week_; } int day_of_month() { return day_of_month_; } int hour() { return hour_; } int minute() { return minute_; } int second() { return second_; } int millisecond() { return millisecond_; } }; public: explicit Time() : us_(0) {} explicit Time(int64_t us) : us_(us) {} explicit Time(bool is_local, TimeStruct &ts); explicit Time(bool is_local, int year, int month, int day, int hour, int minute, int second, int millisecond = 0); bool is_null() const { return us_ == 0; } int64_t ToInternalValue() const { return us_; } // Returns the current time. static Time Now(); // Converts to/from TimeStruct in UTC and a Time class. static Time FromTimeStruct(bool is_local, TimeStruct &ts); TimeStruct ToTimeStruct(bool is_local); // Converts to/from time_t in UTC and a Time class. static Time FromTimeT(time_t tt); time_t ToTimeT() const; #if defined(OS_WIN) // Converts to/from FILETIME. static Time FromFileTime(FILETIME ft); FILETIME ToFileTime() const; #endif // OS_WIN Time& operator=(Time other) { us_ = other.us_; return *this; } // Compute the difference between two times. TimeDelta operator-(Time other) const { return TimeDelta(us_ - other.us_); } // Modify by some time delta. Time& operator+=(TimeDelta delta) { us_ += delta.delta_; return *this; } Time& operator-=(TimeDelta delta) { us_ -= delta.delta_; return *this; } // Return a new time modified by some delta. Time operator+(TimeDelta delta) const { return Time(us_ + delta.delta_); } Time operator-(TimeDelta delta) const { return Time(us_ - delta.delta_); } // Comparison operators bool operator==(Time other) const { return us_ == other.us_; } bool operator!=(Time other) const { return us_ != other.us_; } bool operator<(Time other) const { return us_ < other.us_; } bool operator<=(Time other) const { return us_ <= other.us_; } bool operator>(Time other) const { return us_ > other.us_; } bool operator>=(Time other) const { return us_ >= other.us_; } private: friend class TimeDelta; // The representation of Jan 1, 1970 UTC in microseconds since the // platform-dependent epoch. static const int64_t kTimeTToMicrosecondsOffset; // NTime in microseconds in UTC. int64_t us_; }; // Inline the TimeDelta factory methods, for fast TimeDelta construction. // static inline TimeDelta TimeDelta::FromDays(int64_t days) { return TimeDelta(days * Time::kMicrosecondsPerDay); } // static inline TimeDelta TimeDelta::FromHours(int64_t hours) { return TimeDelta(hours * Time::kMicrosecondsPerHour); } // static inline TimeDelta TimeDelta::FromMinutes(int64_t minutes) { return TimeDelta(minutes * Time::kMicrosecondsPerMinute); } // static inline TimeDelta TimeDelta::FromSeconds(int64_t secs) { return TimeDelta(secs * Time::kMicrosecondsPerSecond); } // static inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms) { return TimeDelta(ms * Time::kMicrosecondsPerMillisecond); } // static inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) { return TimeDelta(us); } inline Time TimeDelta::operator+(Time t) const { return Time(t.us_ + delta_); } // TimeTicks ------------------------------------------------------------------ class BASE_EXPORT TimeTicks { public: TimeTicks() : ticks_(0) {} explicit TimeTicks(int64_t ticks) : ticks_(ticks) {} // Platform-dependent tick count representing "right now." // The resolution of this clock is ~1-15ms. Resolution varies depending // on hardware/operating system configuration. static TimeTicks Now(); // Returns a platform-dependent high-resolution tick count. Implementation // is hardware dependent and may or may not return sub-millisecond // resolution. THIS CALL IS GENERALLY MUCH MORE EXPENSIVE THAN Now() AND // SHOULD ONLY BE USED WHEN IT IS REALLY NEEDED. static TimeTicks HighResNow(); // Returns true if this object has not been initialized. bool is_null() const { return ticks_ == 0; } // Returns the internal numeric value of the TimeTicks object. int64_t ToInternalValue() const { return ticks_; } TimeTicks& operator=(TimeTicks other) { ticks_ = other.ticks_; return *this; } // Compute the difference between two times. TimeDelta operator-(TimeTicks other) const { return TimeDelta(ticks_ - other.ticks_); } // Modify by some time delta. TimeTicks& operator+=(TimeDelta delta) { ticks_ += delta.delta_; return *this; } TimeTicks& operator-=(TimeDelta delta) { ticks_ -= delta.delta_; return *this; } // Return a new TimeTicks modified by some delta. TimeTicks operator+(TimeDelta delta) const { return TimeTicks(ticks_ + delta.delta_); } TimeTicks operator-(TimeDelta delta) const { return TimeTicks(ticks_ - delta.delta_); } // Comparison operators bool operator==(TimeTicks other) const { return ticks_ == other.ticks_; } bool operator!=(TimeTicks other) const { return ticks_ != other.ticks_; } bool operator<(TimeTicks other) const { return ticks_ < other.ticks_; } bool operator<=(TimeTicks other) const { return ticks_ <= other.ticks_; } bool operator>(TimeTicks other) const { return ticks_ > other.ticks_; } bool operator>=(TimeTicks other) const { return ticks_ >= other.ticks_; } protected: friend class TimeDelta; // Tick count in microseconds. int64_t ticks_; }; inline TimeTicks TimeDelta::operator+(TimeTicks t) const { return TimeTicks(t.ticks_ + delta_); } } // namespace nbase #endif // BASE_TIME_TIME_H_
46a14dc70066d58918e1ef1a4c534d78311078e0
ba808c11d830027e3a4aae714b9624a1d1ae853a
/tests/elf/test_modifier.cpp
9774fac35680db5ccae08fa78f1284641efa3dc0
[ "Apache-2.0" ]
permissive
jbremer/LIEF
609b896a9d63306673883797c16d5f2f1c5292dd
e0de8dd596d836390bdceb1845eb0c38c023b323
refs/heads/master
2020-03-22T10:25:57.479864
2018-07-05T22:03:42
2018-07-05T22:03:42
139,902,140
0
0
Apache-2.0
2018-07-05T21:24:19
2018-07-05T21:24:18
null
UTF-8
C++
false
false
3,475
cpp
test_modifier.cpp
/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define CATCH_CONFIG_MAIN #include <catch.hpp> #include <yaml-cpp/yaml.h> #include <LIEF/ELF.hpp> #include "utils.hpp" extern const YAML::Node config = YAML::LoadFile(std::string(PATH_TO_CONFIG) + "/config.yaml"); using namespace LIEF::ELF; TEST_CASE("Test remove dynamic symbol", "[elf][modifier][symbol][dynamic]") { using namespace Catch::Generators; std::vector<std::string> elf_files = Test::get_elf_files(); // Get one std::vector<std::string>::iterator elf_file = between( std::begin(elf_files), std::prev(std::end(elf_files))); const std::string& elf_file_str = *elf_file; //if (elf_file_str.find("systemd-resolve.bin") == std::string::npos) { if (elf_file_str.find("binary_tiny") != std::string::npos) { INFO("Skip " << elf_file_str); return; } if (elf_file_str.find("ELF64_x86-64_binary_rvs.bin") != std::string::npos) { INFO("Skip " << elf_file_str); return; } INFO("Binary used: " << elf_file_str); std::unique_ptr<Binary> binary = std::unique_ptr<Binary>{Parser::parse(elf_file_str)}; it_symbols dynamic_symbols = binary->dynamic_symbols(); auto&& it_symbol = std::find_if( std::begin(dynamic_symbols), std::end(dynamic_symbols), [] (const Symbol& symbol) { return symbol.name().length() > 2; }); if (it_symbol == std::end(dynamic_symbols)) { return; } auto&& it_symbol_bis = std::find_if( std::begin(dynamic_symbols), std::end(dynamic_symbols), [&it_symbol] (const Symbol& symbol) { return symbol.name().length() > 2 and *it_symbol != symbol; }); if (it_symbol_bis == std::end(dynamic_symbols)) { return; } const std::string symbol_removed_name = it_symbol->name(); const std::string symbol_bis_removed_name = it_symbol_bis->name(); INFO("Symbol that will be removed: " << symbol_removed_name << " and " << symbol_bis_removed_name); Symbol* symbol = &(*it_symbol); binary->remove_dynamic_symbol(symbol); binary->remove_dynamic_symbol(symbol_bis_removed_name); std::string output_name = binary->name() + "_test_remove_symbol"; binary->write(output_name); std::unique_ptr<Binary> binary_updated = std::unique_ptr<Binary>{Parser::parse(output_name)}; dynamic_symbols = binary_updated->dynamic_symbols(); it_symbol = std::find_if( std::begin(dynamic_symbols), std::end(dynamic_symbols), [&symbol_removed_name] (const Symbol& symbol) { return symbol.name() == symbol_removed_name; }); it_symbol_bis = std::find_if( std::begin(dynamic_symbols), std::end(dynamic_symbols), [&symbol_bis_removed_name] (const Symbol& symbol) { return symbol.name() == symbol_bis_removed_name; }); REQUIRE(it_symbol == std::end(dynamic_symbols)); REQUIRE(it_symbol_bis == std::end(dynamic_symbols)); }
2c7ef96e6b4b77ea2786da58f32876bcb1e1d3e1
c92074756c82a78fa5bb449dff7f10706821cc64
/Source/A_L_B_E_R_T/PlayerShip.cpp
c60081645d7931e9a26d6a7923642e9e485b8f66
[]
no_license
DontLookAtThis/ALBERT
d1ae0e41cdc4de56c53b5154cd3e2c4bd90ea2df
c47defa7d66ecbef10078a2b36a49283daeca1cc
refs/heads/master
2020-03-23T21:04:09.336032
2018-07-19T23:14:35
2018-07-19T23:14:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,271
cpp
PlayerShip.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "PlayerShip.h" const FName APlayerShip::MoveForwardBinding("MoveForward"); const FName APlayerShip::MoveRightBinding("MoveRight"); const FName APlayerShip::FireForwardBinding("FireForward"); const FName APlayerShip::FireRightBinding("FireRight"); // Sets default values APlayerShip::APlayerShip() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; Velocity = { 0.0f, 0.0f, 0.0f }; MaxSpeed = 5.0f; MaxForce = 0.5f; ApproachRadius = 100.0f; //Ship Mesh ShipMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("ShipMesh")); ShipMesh->SetStaticMesh(ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Game/VikingAssets/Boat_Placeholder.Boat_Placeholder'")).Object); ShipMesh->SetSimulatePhysics(true); ShipMesh->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); ShipMesh->SetRelativeTransform(FTransform(FVector(0.0f, 0.0f, -10.0f))); ShipMesh->SetWorldRotation(FRotator(0.0f, 0.0f, 0.0f), false, false); ShipMesh->SetWorldScale3D(FVector(40.0f, -40.0f, 40.0f)); RootComponent = ShipMesh; //Steer Viking Mesh Viking_Steer = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Steering Viking")); Viking_Steer->SetStaticMesh(ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Game/VikingAssets/Viking_Steering.Viking_Steering'")).Object); Viking_Steer->SetupAttachment(RootComponent); Viking_Steer->SetSimulatePhysics(false); Viking_Steer->SetRelativeTransform(FTransform(FVector(0.0f, 2.0f, 0.5f))); Viking_Steer->SetWorldRotation(FRotator(0.0f, 180.0f, 0.0f), false, false); //Throw Viking Mesh Viking_Throw = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Throwing Viking")); Viking_Throw->SetStaticMesh(ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Game/VikingAssets/Viking_AxeThrowing.Viking_AxeThrowing'")).Object); Viking_Throw->SetupAttachment(RootComponent); Viking_Throw->SetSimulatePhysics(false); Viking_Throw->SetRelativeTransform(FTransform(FVector(0.0f, -2.0f, 0.5f))); Viking_Throw->SetWorldRotation(FRotator(0.0f, 180.0f, 0.0f), false, false); fCurrentTurnRate = 0.0f; fMaxTurnRate = 1.0f; fCurrentSpeed = 0.0f; fMaxSpeed = 10.0f; fMaxBackSpeed = 3.0f; fFacingDegree = 0; // Create a camera boom... Camera_Springarm = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); Camera_Springarm->SetupAttachment(RootComponent); Camera_Springarm->bAbsoluteRotation = true; // Don't want arm to rotate when ship does Camera_Springarm->TargetArmLength = 2000.f; Camera_Springarm->RelativeRotation = FRotator(-45.f, 0.f, 0.f); Camera_Springarm->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level // Create a camera... Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera")); Camera->SetupAttachment(Camera_Springarm, USpringArmComponent::SocketName); Camera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Movement MoveSpeed = 1000.0f; } // Called when the game starts or when spawned void APlayerShip::BeginPlay() { Super::BeginPlay(); } // Called every frame void APlayerShip::Tick(float DeltaTime) { Movement(DeltaTime); } // Called to bind functionality to input void APlayerShip::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { check(PlayerInputComponent); // set up gameplay key bindings PlayerInputComponent->BindAxis(MoveForwardBinding); PlayerInputComponent->BindAxis(MoveRightBinding); PlayerInputComponent->BindAxis(FireForwardBinding); PlayerInputComponent->BindAxis(FireRightBinding); MyController = Cast<APlayerController>(GetController()); if (MyController) { MyController->bShowMouseCursor = true; MyController->bEnableClickEvents = true; MyController->bEnableMouseOverEvents = true; } } void APlayerShip::Movement(float DeltaSeconds) { ForwardValue = GetInputAxisValue(MoveForwardBinding); const float RightValue = GetInputAxisValue(MoveRightBinding); if (ForwardValue != 0) { if (abs(fCurrentTurnRate) < fMaxTurnRate) { if (RightValue > 0) fCurrentTurnRate += (0.01 * ForwardValue); else if (RightValue < 0) fCurrentTurnRate -= (0.01 * ForwardValue); } else fCurrentTurnRate = (fCurrentTurnRate / abs(fCurrentTurnRate)) * fMaxTurnRate; fFacingDegree += fCurrentTurnRate; } else { if (abs(fCurrentTurnRate) <= fMaxTurnRate) { if (RightValue > 0) fCurrentTurnRate += 0.01; else if (RightValue < 0) fCurrentTurnRate -= 0.01; } else fCurrentTurnRate = (fCurrentTurnRate / abs(fCurrentTurnRate)) * fMaxTurnRate; fFacingDegree += fCurrentTurnRate; } if (RightValue == 0) { if (fCurrentTurnRate < 0) fCurrentTurnRate += 0.01; else if (fCurrentTurnRate > 0) fCurrentTurnRate -= 0.01; } if ((abs(fCurrentTurnRate)) < 0.005) fCurrentTurnRate = 0.0f; // Clamp max size so that (X=1, Y=1) doesn't cause faster movement in diagonal directions FVector MoveDirection = FVector(1.0f, 0.0f, 0.f).GetClampedToMaxSize(1.0f); FVector AxisVector = FVector(0, 0, 1); MoveDirection = MoveDirection.RotateAngleAxis(fFacingDegree, AxisVector); // Calculate movement const FVector Movement = MoveDirection; FHitResult Hit(1.f); FQuat QRotation = FQuat(FRotator(0, fFacingDegree - 90, 0)); SetActorRotation(QRotation, ETeleportType::None); // If non-zero size, move this actor if ((abs(fCurrentSpeed)) > 0 || Movement.SizeSquared() > 0) { if (fCurrentSpeed <= fMaxSpeed && fCurrentSpeed >= -fMaxBackSpeed) { if (ForwardValue > 0) fCurrentSpeed += 0.1; else if (ForwardValue < 0) fCurrentSpeed -= 0.1; } if (ForwardValue == 0) { if (fCurrentSpeed < 0) fCurrentSpeed += 0.1; else if (fCurrentSpeed > 0) fCurrentSpeed -= 0.1; } RootComponent->MoveComponent(Movement * fCurrentSpeed, QRotation, true, &Hit); if (Hit.IsValidBlockingHit()) { const FVector Normal2D = Hit.Normal.GetSafeNormal2D(); const FVector Deflection = FVector::VectorPlaneProject(Movement, Normal2D) * (1.f - Hit.Time); RootComponent->MoveComponent(Deflection, QRotation, true); } } if ((abs(fCurrentSpeed)) < 0.05) fCurrentSpeed = 0.0f; }
64d91f75b3f0861f75aba704c9dca9039685d36b
c629aef08d6aab9ade143cb48d1b3bc81b434d41
/8.Tree/8.2.BinarySearchTree.cpp
cfaf1b36718a0368e65ab3eb58b4a608c70b8c41
[]
no_license
suyeon96/Datastructure
159ecbea494e77a3de49963827af78943663092a
b28256bd7e46774ce472990001b7fad8b45e1aeb
refs/heads/master
2023-02-16T17:18:17.863182
2021-01-05T17:35:22
2021-01-05T17:35:22
305,954,742
1
2
null
null
null
null
UTF-8
C++
false
false
11,663
cpp
8.2.BinarySearchTree.cpp
/* * 8.2 * ์ด์ง„ํƒ์ƒ‰ํŠธ๋ฆฌ */ #include <iostream> #include <queue> using namespace std; template <typename T> struct Node{ private: T data; Node* left; Node* right; public: Node(T _data, Node* _left, Node* _right){ data = _data; left = _left; right = _right; } ~Node(){} // getter/setter T getData(){ return data; } void setData(T _data){ data = _data; } Node* getLeft(){ return left; } void setLeft(Node* _left){ left = _left; } Node* getRight(){ return right; } void setRight(Node* _right){ right = _right; } // is leaf node? bool isLeaf(){ return left==nullptr && right==nullptr; } // Node ๋ฉค๋ฒ„ํ•จ์ˆ˜๋กœ ์ˆœํ™˜ํƒ์ƒ‰ ๊ตฌํ˜„ (ใ…Žใ…Ž) Node* search(T key){ if(key == data) // key == ๋…ธ๋“œ์˜ data return this; else if(key < data && left != NULL) // key < ๋…ธ๋“œ์˜ data return left->search(key); else if(key > data && right != NULL) // key > ๋…ธ๋“œ์˜ data return left->search(key); else // ํƒ์ƒ‰์ด ์‹คํŒจํ•œ ๊ฒฝ์šฐ return NULL; } }; template <typename T> class BinaryTree{ private: Node<T>* root; public: BinaryTree(){ root = nullptr; } ~BinaryTree(){} // set root node void setRoot(Node<T>* _root){ root = _root; } // get root node Node<T>* getRoot(){ return root; } // ์ „์œ„ ์ˆœํšŒ(Pre-order Traversal) void preorder(){ cout << "Preorder : [ "; preorder(root); cout << "]" << endl; } void preorder(Node<T>* node){ if(node != NULL){ cout << node->getData() << " "; preorder(node->getLeft()); preorder(node->getRight()); } } // ์ค‘์œ„ ์ˆœํšŒ(In-order Traversal) void inorder(){ cout << "Inorder : [ "; inorder(root); cout << "]" << endl; } void inorder(Node<T>* node){ if(node != NULL){ inorder(node->getLeft()); cout << node->getData() << " "; inorder(node->getRight()); } } // ํ›„์œ„ ์ˆœํšŒ(Post-order Traversal) void postorder(){ cout << "Postorder : [ "; postorder(root); cout << "]" << endl; } void postorder(Node<T>* node){ if(node != NULL){ postorder(node->getLeft()); postorder(node->getRight()); cout << node->getData() << " "; } } // ๋ ˆ๋ฒจ ์ˆœํšŒ(Level-order Traversal) void levelorder(){ cout << "Levelorder: [ "; if(!isEmpty()){ queue<Node<T>*> q; q.push(root); while(!q.empty()){ Node<T>* node = q.front(); q.pop(); if(node != NULL){ cout << node->getData() << " "; q.push(node->getLeft()); q.push(node->getRight()); } } } cout << "]" << endl; } // ์ „์ฒด ๋…ธ๋“œ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ int getCount(){ return isEmpty() ? 0 : getCount(root); } int getCount(Node<T>* node){ if(node == NULL) return 0; return 1 + getCount(node->getLeft()) + getCount(node->getRight()); } // leaf ๋…ธ๋“œ ๊ฐœ์ˆ˜ ๊ตฌํ•˜๊ธฐ int getLeafCount(){ return isEmpty() ? 0 : getLeafCount(root); } int getLeafCount(Node<T>* node){ if(node == NULL) return 0; if(node->isLeaf()) return 1; else return getLeafCount(node->getLeft()) + getLeafCount(node->getRight()); } // ํŠธ๋ฆฌ ๋†’์ด ๊ตฌํ•˜๊ธฐ int getHeight(){ return isEmpty() ? 0 : getHeight(root); } int getHeight(Node<T>* node){ if(node == NULL) return 0; int lHeight = getHeight(node->getLeft()); // ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ๋†’์ด ๊ณ„์‚ฐ int rHeight = getHeight(node->getRight()); // ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ ๋†’์ด ๊ณ„์‚ฐ return (lHeight > rHeight) ? lHeight + 1 : rHeight + 1; } bool isEmpty(){ return root == nullptr; } }; // ์ด์ง„ํƒ์ƒ‰ํŠธ๋ฆฌ (์ด์ง„ํŠธ๋ฆฌ ์ƒ์†) template <typename T> class BinarySearchTree : public BinaryTree<T>{ private: // ํƒ์ƒ‰ (์ˆœํ™˜) Node<T>* searchRecur(Node<T>* node, T key){ if(node == NULL) return NULL; if(key == node->getData()) return node; // key == root ๋…ธ๋“œ์˜ data else if(key < node->getData()) return searchRecur(node->getLeft(), key); // key < root ๋…ธ๋“œ์˜ data else if(key > node->getData()) return searchRecur(node->getRight(), key); // key > root ๋…ธ๋“œ์˜ data } // ํƒ์ƒ‰ (๋ฐ˜๋ณต) Node<T>* searchIter(Node<T>* node, T key){ while(node != NULL){ if(key == node->getData()) return node; // key == root ๋…ธ๋“œ์˜ data else if(key < node->getData()) node = node->getLeft(); // key < root ๋…ธ๋“œ์˜ data else if(key > node->getData()) node = node->getRight(); // key > root ๋…ธ๋“œ์˜ data } return NULL; // ํƒ์ƒ‰์ด ์‹คํŒจํ•œ ๊ฒฝ์šฐ NULL ๋ฐ˜ํ™˜ } // ์‚ฝ์ž… (์ˆœํ™˜) void insertRecur(Node<T>* node, T key){ Node<T>* newNode = new Node<T>(key, nullptr, nullptr); // ์ƒˆ๋กœ์šด key๋ฅผ ๊ฐ€์ง€๋Š” node ์ƒ์„ฑ if(key == node->getData()){ // ํŠธ๋ฆฌ์— ์ด๋ฏธ key๊ฐ’์„ ๊ฐ€์ง€๋Š” node๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ return; }else if(key < node->getData()){ // key < root ๋…ธ๋“œ์˜ data if(node->getLeft() == NULL){ node->setLeft(newNode); }else{ insertRecur(node->getLeft(), key); } }else if(key > node->getData()){ // key > root ๋…ธ๋“œ์˜ data if(node->getRight() == NULL){ node->setRight(newNode); }else{ insertRecur(node->getRight(), key); } } } // ์‚ญ์ œ void remove(Node<T>* parentNode, Node<T>* deleteNode){ // Case1. ์‚ญ์ œํ•˜๋ ค๋Š” node๊ฐ€ leaf ๋…ธ๋“œ์ธ ๊ฒฝ์šฐ if(deleteNode->isLeaf()){ if(deleteNode == this->getRoot()){ // ์‚ญ์ œํ•˜๋ ค๋Š” node๊ฐ€ root์ธ ๊ฒฝ์šฐ this->setRoot(nullptr); }else{ if(parentNode->getLeft() == deleteNode){ // parent์˜ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ ์‚ญ์ œ parentNode->setLeft(nullptr); }else if(parentNode->getRight() == deleteNode){ // parent์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹๋…ธ๋“œ ์‚ญ์ œ parentNode->setRight(nullptr); } } } // Case2. ์‚ญ์ œํ•˜๋ ค๋Š” node๊ฐ€ ํ•˜๋‚˜์˜ ์ž์‹๋…ธ๋“œ๋งŒ ๊ฐ–๋Š” ๊ฒฝ์šฐ else if(deleteNode->getLeft() == NULL || deleteNode->getRight() == NULL){ Node<T>* childNode = (deleteNode->getLeft() != NULL) ? deleteNode->getLeft() : deleteNode->getRight(); // ์‚ญ์ œํ•  node์˜ ์œ ์ผํ•œ ์ž์‹๋…ธ๋“œ if(deleteNode == this->getRoot()){ // ์‚ญ์ œํ•˜๋ ค๋Š” node๊ฐ€ root์ธ ๊ฒฝ์šฐ this->setRoot(childNode); }else{ if(parentNode->getLeft() == deleteNode){ // parent์˜ ์™ผ์ชฝ ์ž์‹๋…ธ๋“œ์— childNode link parentNode->setLeft(childNode); }else if(parentNode->getRight() == deleteNode){ // parent์˜ ์˜ค๋ฅธ์ชฝ ์ž์‹๋…ธ๋“œ childNode link parentNode->setRight(childNode); } } } // Case3. ์‚ญ์ œํ•˜๋ ค๋Š” node๊ฐ€ 2๊ฐœ์˜ ์ž์‹๋…ธ๋“œ๋ฅผ ๋ชจ๋‘ ๊ฐ–๋Š” ๊ฒฝ์šฐ else{ // ์‚ญ์ œํ•˜๋ ค๋Š” ๋…ธ๋“œ์˜ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์—์„œ ๊ฐ€์žฅ ์ž‘์€ ๋…ธ๋“œ๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๊ณผ์ • Node<T>* succp = deleteNode; Node<T>* succ = deleteNode->getRight(); while(succ->getLeft() != NULL){ succp = succ; succ = succ->getLeft(); } // 3-1. ํ›„๊ณ„์ž ๋…ธ๋“œ์˜ ๋ถ€๋ชจ์™€ ํ›„๊ณ„์ž ๋…ธ๋“œ์˜ ์ž์‹ ์—ฐ๊ฒฐ if(succp->getLeft() == succ){ succp->setLeft(succ->getRight()); }else{ // ํ›„๊ณ„์ž ๋…ธ๋“œ๊ฐ€ ์‚ญ์ œํ•  ๋…ธ๋“œ์˜ ๋ฐ”๋กœ ์˜ค๋ฅธ์ชฝ ์ž์‹์ธ ๊ฒฝ์šฐ succp->setRight(succ->getRight()); } // 3-2. ์‚ญ์ œํ•  ๋…ธ๋“œ์˜ data๋ฅผ ํ›„๊ณ„์ž๋…ธ๋“œ์˜ data๋กœ ๋Œ€์ฒด deleteNode->setData(succ->getData()); // 3-3. ์‚ญ์ œํ•  ๋…ธ๋“œ๋ฅผ ํ›„๊ณ„์ž๋…ธ๋“œ๋กœ ๋ณ€๊ฒฝ (ํ›„๊ณ„์ž๋…ธ๋“œ๋ฅผ delete ํ•˜๊ธฐ ์œ„ํ•ด) deleteNode = succ; } delete deleteNode; // memory ๋ฐ˜๋‚ฉ } public: BinarySearchTree(){} ~BinarySearchTree(){} // ํƒ์ƒ‰ Node<T>* search(T key){ //return searchRecur(this->getRoot(), key); return searchIter(this->getRoot(), key); } // ์‚ฝ์ž… void insert(T key){ if(this->isEmpty()){ Node<T>* newNode = new Node<T>(key, nullptr, nullptr); // ์ƒˆ๋กœ์šด key๋ฅผ ๊ฐ€์ง€๋Š” node ์ƒ์„ฑ this->setRoot(newNode); }else{ insertRecur(this->getRoot(), key); } } // ์‚ญ์ œ void remove(T key){ if(this->isEmpty()){ cout << "Tree is Empty" << endl; return; } // parentNode์™€ deleteNode๋ฅผ ์ฐพ๋Š” ๊ณผ์ • Node<T>* parentNode = nullptr; // ์‚ญ์ œํ•˜๋ ค๋Š” node์˜ ๋ถ€๋ชจ node (์ตœ์ดˆ root์˜ ๋ถ€๋ชจ๋…ธ๋“œ๋Š” ์—†์Œ) Node<T>* deleteNode = this->getRoot(); // ์‚ญ์ œํ•˜๋ ค๋Š” node while(deleteNode != NULL && deleteNode->getData() != key){ parentNode = deleteNode; deleteNode = (key < parentNode->getData()) ? parentNode->getLeft() : parentNode->getRight(); } if(deleteNode == NULL){ cout << "Key is not in Tree" << endl; return; }else{ remove(parentNode, deleteNode); } } }; int main(){ BinarySearchTree<int> tree; // // 10๊ฐœ node ์‚ฝ์ž… // tree.insert(35); // tree.insert(18); // tree.insert(7); // tree.insert(26); // tree.insert(12); // tree.insert(3); // tree.insert(68); // tree.insert(22); // tree.insert(30); // tree.insert(99); // // // Calculate // cout << "์ „์ฒด ๋…ธ๋“œ๊ฐœ์ˆ˜ : " << tree.getCount() << endl; // cout << "๋‹จ๋ง ๋…ธ๋“œ๊ฐœ์ˆ˜ : " << tree.getLeafCount() << endl; // cout << "์ด์ง„ํŠธ๋ฆฌ ๋†’์ด : " << tree.getHeight() << endl; // // // Traversal // tree.preorder(); // tree.inorder(); // tree.postorder(); // tree.levelorder(); // // // ์‚ญ์ œ // cout << "==== ๋…ธ๋“œ 3 ์‚ญ์ œ ====" << endl; // tree.remove(3); // tree.levelorder(); // cout << "==== ๋…ธ๋“œ 68 ์‚ญ์ œ ====" << endl; // tree.remove(68); // tree.levelorder(); // cout << "==== ๋…ธ๋“œ 18 ์‚ญ์ œ ====" << endl; // tree.remove(18); // tree.levelorder(); // cout << "==== ๋…ธ๋“œ 35 ์‚ญ์ œ ====" << endl; // tree.remove(35); // tree.levelorder(); // // // Last Calculate // cout << "์ „์ฒด ๋…ธ๋“œ๊ฐœ์ˆ˜ : " << tree.getCount() << endl; // cout << "๋‹จ๋ง ๋…ธ๋“œ๊ฐœ์ˆ˜ : " << tree.getLeafCount() << endl; // cout << "์ด์ง„ํŠธ๋ฆฌ ๋†’์ด : " << tree.getHeight() << endl; // 10๊ฐœ node ์‚ฝ์ž… tree.insert(5); tree.insert(3); tree.insert(9); tree.insert(1); tree.insert(4); tree.insert(7); tree.insert(2); tree.insert(6); tree.insert(8); // ๋ ˆ๋ฒจ ์ˆœํšŒ ๊ฒฐ๊ณผ tree.levelorder(); cout << "==== ๋…ธ๋“œ 9 ์‚ญ์ œ ====" << endl; tree.remove(9); tree.levelorder(); return 0; }
443f225c648c45c951bfd445e8b955ce56c4c47b
f4aa6bfdf2bf1caacf9e9a8cefd09d00382e9e8c
/My_Study/CBY_Projects/CBYLib/CBYCore.cpp
b2fd36446fae4dd3ecfb2b78cc0004f72a943e15
[]
no_license
Byeng-Yong-Choi/C_Yong
e39a015b64facd473c5193d21a157b552813e9b7
9c2a1856b7c59156c2364ea2bf0a21e3d02eab1d
refs/heads/master
2020-09-28T14:26:17.358211
2019-12-18T04:51:44
2019-12-18T04:51:44
226,795,230
1
0
null
2019-12-09T05:57:44
2019-12-09T05:53:34
null
UHC
C++
false
false
3,865
cpp
CBYCore.cpp
#include "CBYCore.h" HDC g_ScreenDC; HDC g_offScreenDC; bool CBYCore::Init() { return true; } bool CBYCore::Frame() { return true; } bool CBYCore::Render() { return true; } bool CBYCore::Release() { return true; } bool CBYCore::GameRun() { GetGameRun = CoreInit(); //๋Ÿฐํ•จ์ˆ˜ ์‹คํ–‰์‹œ Init์‹คํ–‰ํ•˜๊ณ  Frame๊ณผ Renderํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ ์–ด๋– ํ•œ ์ด๋ฒคํŠธ๋กœ ์ข…๋ฃŒ์‹œ Release๋กœ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๋น„์›Œ์ฃผ๊ณ  ์ข…๋ฃŒํ•œ๋‹ค. if (GetGameRun == false) { return false; } MSG msg; //๋ฉ”์„ธ์ง€๋ฅผ ๋ฐ›์„ MSG ์„ ์–ธ ZeroMemory(&msg, sizeof(msg)); while (GetGameRun) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) //PeekMessage๋Š” ๋ฉ”์„ธ์ง€๊ฐ€ ์˜ค๋Š”์ง€ ๋Œ€๊ธฐ์ƒํƒœ์—†์ด ๊ณ„์† ๋Œ์•„๊ฐ€๋ฉฐ ๋ฐœ์ƒ์‹œ1 ์—†์„์‹œ 0์„ ๋ฐ˜ํ™˜ { //๊ทธ๋Ÿฌ๋ฏ€๋กœ ๋ฉ”์„ธ์ง€ํ์— ๋ฉ”์„ธ์ง€๊ฐ€ ์Œ“์—ฌ ์žˆ์œผ๋ฉด ๊ณ„์† ๋ฉ”์„ธ์ง€ ์ฒ˜๋ฆฌํ•˜๋‹ค๊ฐ€ ์—†์„๋•Œ Frame๊ณผ Render๊ฐ€ ๋Œ์•„๊ฐ€ 1ํ”„๋ ˆ์ž„์ด ๋Œ์•„๊ฐ€๋Š” ๊ฒƒ TranslateMessage(&msg); //๋ฉ”์„ธ์ง€ํ์— ์žˆ๋Š” ๋ฉ”์„ธ์ง€๋ฅผ ๋ฐ›์•„์„œ ํ‚ค๋ณด๋“œ์˜ ๋ˆŒ๋ฆผ์ด ๋ฐœ์ƒ์‹œ WN_CHAR๋กœ ๊ฐ€๊ณตํ•ด์„œ ๋ฉ”์„ธ์ง€ํ์— ๋„ฃ๋Š”๋‹ค DispatchMessage(&msg); //WndProc๋กœ ๋ฉ”์„ธ์ง€ํ์—์žˆ๋Š” ๋ฉ”์„ธ์ง€๋ฅผ ๋„˜๊ฒจ์ค€๋‹ค. if (msg.message == WM_QUIT) { break; } } else { if (CoreFrame() == false) { return false; } if (CoreRender() == false) { return false; } } } if (CoreRelease() == false) { return false; } return true; } bool CBYCore::CoreInit() { if (time.Init()|| Input.Init()) { GetGameRun = true; ScreenDC = GetDC(g_hwnd); //์œˆ๋„์šฐ ํ™”๋ฉด์— ๋„์šธ DC๋ฅผ ์–ป๊ธฐ์œ„ํ•ด ์œˆ๋„์šฐ์˜ ํ•ธ๋“ค์ •๋ณด๋ฅผ ๋ฐ›์•„ ScreenDC๋ฅผ ์ƒ์„ฑ offScreenDC = CreateCompatibleDC(ScreenDC); //๋”๋ธ” ๋ฒ„ํผ๋ง ์ง„ํ–‰์„ ์œ„ํ•ด offScreenDC๋ฅผ ScreenDC์™€ ํ˜ธํ™˜๋˜๋Š” DC๋กœ ์ƒ์„ฑ offScreenDCBitMap=CreateCompatibleBitmap(ScreenDC, Winrt.right, Winrt.bottom); //offScreen์— ๋„์šธ ๋น„ํŠธ๋งตํ•ธ๋“ค์„ ์ƒ์„ฑ SelectObject(offScreenDC, offScreenDCBitMap); //offScreenDC์— ๋„์šฐ๊ธฐ ์œ„ํ•ด offScreen๋น„ํŠธ๋งต ํ•ธ๋“ค์„ SelectObjectํ•œ๋‹ค COLORREF BkColor = RGB(125, 126, 200); // ์œˆ๋„์šฐ์— ์ƒ์ƒ์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ๋ณ€์ˆ˜ ์„ ์–ธ BackColor = CreateSolidBrush(BkColor); // ์œˆ๋„์šฐ์— ๋ฟŒ๋ฆด ์ƒ‰์˜ ๋ฌผ๊ฐํ•ธ๋“ค์„ ์ƒ์„ฑํ•œ๋‹ค SelectObject(offScreenDC, BackColor); // offScreenDC์— ๋„์šฐ๊ธฐ ์œ„ํ•ด ๋ฌผ๊ฐํ•ธ๋“ค์„ SelectObjectํ•œ๋‹ค. g_ScreenDC = ScreenDC; //๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ ์ด์šฉํ•˜๊ธฐ ํŽธํ•˜๊ฒŒ ์ „์—ญ์œผ๋กœ ๋‘”๋‹ค g_offScreenDC = offScreenDC; //๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ ์ด์šฉํ•˜๊ธฐ ํŽธํ•˜๊ฒŒ ์ „์—ญ์œผ๋กœ ๋‘”๋‹ค return Init(); } else return false; }; bool CBYCore::CoreFrame() { if (time.Frame()) { if (Input.Frame()) { Bitmap.Frame(); return Frame(); } } else return false; }; bool CBYCore::PreRender() //๋ Œ๋”๊ฐ€ ์ง„ํ–‰๋œํ›„ ๋‹ค์Œ ๋ Œ๋”๋กœ ๋„˜์–ด๊ฐˆ๋•Œ ํ™”๋ฉด์„ ๊นจ๋—ํ•˜๊ฒŒ ๋ฐฐ๊ฒฝ์œผ๋กœ ํด๋ฆฌ์–ดํ•ด์ฃผ๋Š” ์—ญํ•  { PatBlt(offScreenDC, 0, 0, Winrt.right, Winrt.bottom, PATCOPY); //PatBlt๋Š” ์ง€์ •๋œํ™”๋ฉด์„ DC์˜ ํŒจํ„ด(๋ธŒ๋Ÿฌ์‰ฌ)๋กœ ์น ํ•œ๋‹ค return true; }; bool CBYCore::CoreRender() { PreRender(); Render(); time.Render(); PostRender(); return true; }; bool CBYCore::PostRender() //์ €์žฅ๋œ g_offScreenDC์ •๋ณด๋ฅผ ๋„˜๊ฒจ๋ฐ›์•„ ๋ฉ”์ธ DC์—์„œ ์ถœ๋ ฅํ•˜๋Š”๊ฒƒ { BitBlt(ScreenDC,0,0, Winrt.right, Winrt.bottom,g_offScreenDC,0,0, SRCCOPY); //g_offScreenDC์— ์ž…๋ ฅ๋œ ๋ฒ„ํผ๋‚ด์šฉ์„ ScreenDC๊ฐ€ Copyํ•˜์—ฌ ์ถœ๋ ฅํ•œ๋‹ค. return true; }; bool CBYCore::CoreRelease() { DeleteObject(BackColor); DeleteObject(offScreenDCBitMap); ReleaseDC(g_hwnd, ScreenDC); ReleaseDC(g_hwnd, offScreenDC); time.Release(); Input.Release(); Release(); return true; }; CBYCore::CBYCore() { GetGameRun = false; } CBYCore::~CBYCore() { }
d4b54989166843748cd38ab533196afa514ecbd8
22ce6b167ed84e4a90d9f6e84a4112a09107fefc
/src/classes/Game.cpp
11048c7aeabfe941d4fc923637570c523983f952
[]
no_license
wrazik/MarioEdit
253c3771d513fa035c388563ef0333205185462e
a6fbb1d65cd77939fbb00525f37294b46ea22903
refs/heads/master
2020-03-25T19:59:27.408879
2018-08-10T19:13:24
2018-08-10T19:13:24
144,110,134
0
0
null
2018-08-09T06:29:55
2018-08-09T06:29:55
null
UTF-8
C++
false
false
6,318
cpp
Game.cpp
#include "Game.hpp" #include <iostream> #include "defines.hpp" #include "Cursor.hpp" #include "TileSet.hpp" #include "Scale.hpp" #include "TileRegistry.hpp" #include "Animation/SpecialBlockBlinkingAnimation.hpp" Game::Game() : tileSet("resources/tiles2.png") { window = std::make_shared<sf::RenderWindow>( sf::VideoMode(windowedWidth, windowedHeight), title, sf::Style::Default ); grid = std::make_shared<Grid>(window->getSize()); reinitializeWindow(); } void Game::reinitializeWindow() { window->setVerticalSyncEnabled(true); window->setFramerateLimit(100); window->setKeyRepeatEnabled(false); Scale::rescale(window->getSize()); Cursor::reinitialize(window); Tile::setWindow(window); grid->rescale(window->getSize()); snapTilesToGrid(); } int Game::run() { createTiles(); auto tiles = TileRegistry::getAll(); SpecialBlockBlinkingAnimation blinkAnimation(tiles); blinkAnimation.run(); while (window->isOpen()) { handleSystemEvents(); handleTileEvents(tiles); window->clear(BG_LIGHT_COLOR); grid->draw(window); for (std::size_t i=0; i<tiles.size(); i++) { tiles[i]->draw(window); } cursor.draw(); window->display(); } return 0; } void Game::createTiles() { auto questionMark = tileSet.createTile(0, 5); questionMark->setEventHandler(Tile::MouseEnter, [](Tile* tile) { tile->highlight(); }); questionMark->setEventHandler(Tile::MouseLeave, [](Tile* tile) { tile->undoHighlight(); }); questionMark->setEventHandler(Tile::StartDrag, [](Tile* tile) { tile->change(0, 5); tile->startDrag(); }); questionMark->setEventHandler(Tile::Drag, [](Tile* tile) { tile->drag(); }); questionMark->setEventHandler(Tile::Drop, [](Tile* tile) { tile->drop(); }); questionMark->setGrid(grid); questionMark->snapToGrid(sf::Vector2u(2, 1)); } void Game::handleTileEvents(const std::vector<std::shared_ptr<Tile>> &tiles) { for (size_t i=0; i < tiles.size(); i++) { auto tile = tiles[i]; if (cursor.isOver(tile) && !cursor.isOverRegistered(tile)) { cursor.registerOver(tile); tile->handleEvent(Tile::MouseEnter); } else if (cursor.isOver(tile)) { tile->handleEvent(Tile::MouseOver); if (cursor.isClick() && !cursor.isDragRegistered(tile)) { cursor.registerDrag(tile); tile->handleEvent(Tile::StartDrag); } else if (!cursor.isClick() && cursor.isDragRegistered(tile)) { cursor.unregisterDrag(tile); tile->handleEvent(Tile::Drop); } } else if (!cursor.isOver(tile) && cursor.isOverRegistered(tile)) { if (cursor.isDragRegistered(tile)) { cursor.unregisterDrag(tile); tile->handleEvent(Tile::Drop); } cursor.unregisterOver(tile); tile->handleEvent(Tile::MouseLeave); } else { if (cursor.isDragRegistered(tile)) { cursor.unregisterDrag(tile); tile->handleEvent(Tile::Drop); } } tile->rescale(Scale::getScale()); } } void Game::handleSystemEvents() { bool keyChanged = false; sf::Event event; while (window->pollEvent(event)) { switch (event.type) { case sf::Event::Closed: { window->close(); } break; case sf::Event::KeyPressed: { keyChanged = true; keyboard.press(event.key.code); } break; case sf::Event::KeyReleased: { keyChanged = true; keyboard.release(event.key.code); } break; case sf::Event::Resized: { width = event.size.width; height = event.size.height; windowedWidth = event.size.width; windowedHeight = event.size.height; if (event.size.height < minWindowHeight) { window->setSize(sf::Vector2u(event.size.width, minWindowHeight)); height = minWindowHeight; windowedHeight = minWindowHeight; } sf::Vector2u newSize(width, height); Scale::rescale(newSize); grid->rescale(newSize); snapTilesToGrid(); window->setView(sf::View(sf::FloatRect(0, 0, width, height))); } break; case sf::Event::MouseButtonPressed: { cursor.click(true); } break; case sf::Event::MouseButtonReleased: { cursor.click(false); } break; case sf::Event::MouseMoved: { cursor.handleRegisteredDrags(); } break; } } if (keyChanged) { handleKeyboardEvents(); } } void Game::snapTilesToGrid() { auto tiles = TileRegistry::getAll(); for (size_t i=0; i < tiles.size(); i++) { auto tile = tiles[i]; tile->snapToGrid(); } } void Game::handleKeyboardEvents() { if (keyboard.isPressed(sf::Keyboard::Escape) || keyboard.isPressed(sf::Keyboard::Q)) { window->close(); return; } if (keyboard.isPressed(sf::Keyboard::F)) { isFullscreen = !isFullscreen; if (isFullscreen) { sf::VideoMode mode = findHighestResolutionMode(); width = mode.width; height = mode.height; window->create(mode, title, isFullscreen ? sf::Style::Fullscreen : sf::Style::Default); } else { width = windowedWidth; height = windowedHeight; sf::VideoMode mode(width, height); window->create(mode, title, isFullscreen ? sf::Style::Fullscreen : sf::Style::Default); } reinitializeWindow(); } } sf::VideoMode Game::findHighestResolutionMode() { auto modes = sf::VideoMode::getFullscreenModes(); auto maxHeightMode = modes[0]; for (int i=0; i<modes.size(); i++) { if (modes[i].height > maxHeightMode.height) { maxHeightMode = modes[i]; } } return maxHeightMode; }
854fc65b3a188656e9c17f37a4c8a848b9b0df50
6cef817d092eeccb0b1839e0437bbaeec8df9176
/lib/Target/TargetLibraryInfo.cpp
269958fd7f17bfd3e092aac6a42df297b03cf54f
[ "NCSA" ]
permissive
asl/llvm-openrisc
b1a1166d272bc36acc03f50cf2f792986bae9e33
9751b81fc97dcb6ecc4be4304ef8e6e8cf79f6e4
refs/heads/master
2021-01-15T17:45:49.158680
2012-04-04T19:36:31
2012-04-04T19:36:31
3,941,218
8
1
null
null
null
null
UTF-8
C++
false
false
4,555
cpp
TargetLibraryInfo.cpp
//===-- TargetLibraryInfo.cpp - Runtime library information ----------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TargetLibraryInfo class. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetLibraryInfo.h" #include "llvm/ADT/Triple.h" using namespace llvm; // Register the default implementation. INITIALIZE_PASS(TargetLibraryInfo, "targetlibinfo", "Target Library Information", false, true) char TargetLibraryInfo::ID = 0; void TargetLibraryInfo::anchor() { } const char* TargetLibraryInfo::StandardNames[LibFunc::NumLibFuncs] = { "acos", "acosl", "acosf", "asin", "asinl", "asinf", "atan", "atanl", "atanf", "atan2", "atan2l", "atan2f", "ceil", "ceill", "ceilf", "copysign", "copysignf", "copysignl", "cos", "cosl", "cosf", "cosh", "coshl", "coshf", "exp", "expl", "expf", "exp2", "exp2l", "exp2f", "expm1", "expm1l", "expl1f", "fabs", "fabsl", "fabsf", "floor", "floorl", "floorf", "fiprintf", "fmod", "fmodl", "fmodf", "fputs", "fwrite", "iprintf", "log", "logl", "logf", "log2", "log2l", "log2f", "log10", "log10l", "log10f", "log1p", "log1pl", "log1pf", "memcpy", "memmove", "memset", "memset_pattern16", "nearbyint", "nearbyintf", "nearbyintl", "pow", "powf", "powl", "rint", "rintf", "rintl", "sin", "sinl", "sinf", "sinh", "sinhl", "sinhf", "siprintf", "sqrt", "sqrtl", "sqrtf", "tan", "tanl", "tanf", "tanh", "tanhl", "tanhf", "trunc", "truncf", "truncl", "__cxa_atexit", "__cxa_guard_abort", "__cxa_guard_acquire", "__cxa_guard_release" }; /// initialize - Initialize the set of available library functions based on the /// specified target triple. This should be carefully written so that a missing /// target triple gets a sane set of defaults. static void initialize(TargetLibraryInfo &TLI, const Triple &T) { initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry()); // memset_pattern16 is only available on iOS 3.0 and Mac OS/X 10.5 and later. if (T.isMacOSX()) { if (T.isMacOSXVersionLT(10, 5)) TLI.setUnavailable(LibFunc::memset_pattern16); } else if (T.getOS() == Triple::IOS) { if (T.isOSVersionLT(3, 0)) TLI.setUnavailable(LibFunc::memset_pattern16); } else { TLI.setUnavailable(LibFunc::memset_pattern16); } if (T.isMacOSX() && T.getArch() == Triple::x86 && !T.isMacOSXVersionLT(10, 7)) { // x86-32 OSX has a scheme where fwrite and fputs (and some other functions // we don't care about) have two versions; on recent OSX, the one we want // has a $UNIX2003 suffix. The two implementations are identical except // for the return value in some edge cases. However, we don't want to // generate code that depends on the old symbols. TLI.setAvailableWithName(LibFunc::fwrite, "fwrite$UNIX2003"); TLI.setAvailableWithName(LibFunc::fputs, "fputs$UNIX2003"); } // iprintf and friends are only available on XCore and TCE. if (T.getArch() != Triple::xcore && T.getArch() != Triple::tce) { TLI.setUnavailable(LibFunc::iprintf); TLI.setUnavailable(LibFunc::siprintf); TLI.setUnavailable(LibFunc::fiprintf); } } TargetLibraryInfo::TargetLibraryInfo() : ImmutablePass(ID) { // Default to everything being available. memset(AvailableArray, -1, sizeof(AvailableArray)); initialize(*this, Triple()); } TargetLibraryInfo::TargetLibraryInfo(const Triple &T) : ImmutablePass(ID) { // Default to everything being available. memset(AvailableArray, -1, sizeof(AvailableArray)); initialize(*this, T); } TargetLibraryInfo::TargetLibraryInfo(const TargetLibraryInfo &TLI) : ImmutablePass(ID) { memcpy(AvailableArray, TLI.AvailableArray, sizeof(AvailableArray)); CustomNames = TLI.CustomNames; } /// disableAllFunctions - This disables all builtins, which is used for options /// like -fno-builtin. void TargetLibraryInfo::disableAllFunctions() { memset(AvailableArray, 0, sizeof(AvailableArray)); }
6729b565e792626cc401ad991c332a3c10dd0682
66498a83efa77fcfe1492b8b22b057eaefd73931
/tmp/beerduino_mail.cpp
3e0bbdccdd73617da17ba4b3d9e8545cf956de7e
[]
no_license
SR-G/beerduino
dab420bf147fa9425fe197c3a2bea6048c6c0db2
ec39202fe7eaca463c15be3e28b93a997d63c7b6
refs/heads/master
2021-01-23T12:16:48.050622
2012-05-01T17:47:19
2012-05-01T17:47:19
2,462,404
3
0
null
null
null
null
UTF-8
C++
false
false
2,090
cpp
beerduino_mail.cpp
/** * Send mail. */ void sendMail() { for (int i = 0 ; i < foundSensors ; i++ ) { Serial << "Temp" << (i+1) << " [" << currentTemperature[i] << "], seuil [" << seuilTemperature[i] << "]" << endl; } Serial << "Envoi d'un mail ..." << endl; if (smtpClient.connect()) { smtpClient << "HELO beerduino" << endl; delay(SMTP_TEMPO); smtpClient << "MAIL FROM:serge.simon@free.fr" << endl; /* identify sender */ delay(SMTP_TEMPO); smtpClient << "RCPT TO:serge.simon@free.fr" << endl; /* identify recipient */ delay(SMTP_TEMPO); smtpClient << "AUTH LOGIN PLAIN CRAM-MD5" << endl; /* a tester si besoin d'authentification sur smtp.free.fr */ delay(SMTP_TEMPO); // smtpClient << "8498e6ecf343c526c98388bbf310044a" << endl; /* serge.simon encodรฉ en MD5 */ // delay(SMTP_TEMPO); // smtpClient << "" << endl; /* password encodรฉ en MD5 */ // delay(SMTP_TEMPO); smtpClient << "DATA" << endl; delay(SMTP_TEMPO); smtpClient << "Subject: Beerduino temperature alert" << endl; /* insert subject */ smtpClient << endl; // smtpClient << "Monitoring du : " << day() << "/" << month() << "/" << year() << " " << hour() << minute() << second() << endl; // smtpClient << endl; if (overheat == 1) { smtpClient << "Depassement des seuils de temperature autorises d'une ou plusieurs sondes !" << endl; } else { smtpClient << "Retour a la normale des temperatures de toutes les sondes !" << endl; } smtpClient << endl; for (int i = 0 ; i < foundSensors ; i++ ) { smtpClient << "Temperature capteur (" << (i+1) << ") [" << currentTemperature[i] << "C] (seuil [" << seuilTemperature[i] << "C])." << endl; } smtpClient << endl; smtpClient << "--" << endl; smtpClient << "Sent from Arduino." << endl; /* insert body */ smtpClient << "." << endl; smtpClient << "QUIT" << endl; /* terminate connection */ delay(SMTP_TEMPO); smtpClient << endl; delay(SMTP_TEMPO); smtpClient.stop(); } else { Serial << "Can't send mail" << endl; } }
bdad4c2c3f49fd12e744cb65b6f435c83f18c43d
4262591e1586b909692756c48288e690af813b66
/src/project/DOTATribe/src/NewEquipremindDataHandler.cpp
b35392512564e2eb87054a1ff8cd52b312398cfa
[]
no_license
atom-chen/DotaTribe
924a6df4463bffb6cc08df5d8d5cdb4a1a5740fb
2f6409a78825250ffa38b18b9819dee3ec9d1182
refs/heads/master
2020-11-28T03:44:41.631302
2019-08-23T07:04:34
2019-08-23T07:04:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,383
cpp
NewEquipremindDataHandler.cpp
//Name:NewEquipremindDataHandler //Author: lvyunlong //Func: new equip remind handler //Maintainer:lvyunlong #include <cocos2d.h> #include "../include/NewEquipremindDataHandler.h" #include "../include/NFControlsManager.h" #include "../include/EventSystem.h" #include "../include/EventTyper.h" #include "../include/IWindow.h" #include "../include/WindowManager.h" #include "../include/DOTATribeApp.h" using namespace std; NewEquipremindDataHandler::NewEquipremindDataHandler(){ id_ = -1; } NewEquipremindDataHandler::~NewEquipremindDataHandler(){ id_ = -1; } void NewEquipremindDataHandler::handlePacket(IPacket* packet){ } bool NewEquipremindDataHandler::init(){ return true; } void NewEquipremindDataHandler::onDestroy(){ id_ = -1; } void NewEquipremindDataHandler::ComPareNewEquipandRoleEquip(int id) { BagEquipData *bed = BAGEQUIPDATAHANDLER->getEquipById(id); if (bed==NULL) return; int cat = bed->template_->type_; if (cat == kEQUIP_TYPE_EXPBALL) { return; } std::map<int,RoleEquipData*>::iterator it = NFC_GetHeroEquipManager()->m_mapEquipList.find(cat); RoleEquipData* red=it->second; if (red==NULL) return; if (red->hasEquip_) { if (red->equipdata_->template_->quality_ < bed->template_->quality_) { if(!WINDOWMANAGER->IsWindowVisible(IWindow::_TYPED_WINDOW_PESWINDOW_)) { id_ = id; DetectRemindShow(); } } } else { if(!WINDOWMANAGER->IsWindowVisible(IWindow::_TYPED_WINDOW_PESWINDOW_)) { id_ = id; DetectRemindShow(); } } } void NewEquipremindDataHandler::DetectRemindShow() { if (id_ != -1 && (DOTATribeApp::get_instance2()->IsHomeProcedureAsActiveProcedure() || DOTATribeApp::get_instance2()->IsTeamBattleAsActiveProcedure() || DOTATribeApp::get_instance2()->IsSelectMissionAsActiveProcedure() || DOTATribeApp::get_instance2()->IsArenaAsActiveProcedure())) { EVENTSYSTEM->PushEvent(_TYPED_EVENT_HIDE_NEWEQUIPREMINDWINDOW_); EVENTSYSTEM->PushEvent(_TYPED_EVENT_SHOW_NEWEQUIPREMINDWINDOW_); } else { EVENTSYSTEM->PushEvent(_TYPED_EVENT_HIDE_NEWEQUIPREMINDWINDOW_); } } void NewEquipremindDataHandler::SwallowEquip(int id) { if (id_ != -1) { if (id_ == id) { EVENTSYSTEM->PushEvent(_TYPED_EVENT_HIDE_NEWEQUIPREMINDWINDOW_); id_ = -1; } } } void NewEquipremindDataHandler::HideClearData() { EVENTSYSTEM->PushEvent(_TYPED_EVENT_HIDE_NEWEQUIPREMINDWINDOW_); id_ = -1; }
92299774a046ec23e0f49eebb43f1e3b9354fac6
4100ecc09eda84eb487f0db220162ad79f2783a9
/Arduino/Arduino.ino
3a1aadf2752e4ec4dab9d6342e0584ba580e296d
[]
no_license
mdgoodrum/assistant
75b8ce80ac2f003dac22d17604520f1dad9bc20e
8ce7d341c3049816fe129cdb48214ed4b5d12c77
refs/heads/master
2020-03-08T01:53:09.479084
2018-04-18T15:21:55
2018-04-18T15:21:55
127,843,364
0
0
null
null
null
null
UTF-8
C++
false
false
1,599
ino
Arduino.ino
#include "ESP8266WiFi.h" const char* host = "64d275a3.ngrok.io"; const char* MY_SSID = "Sonika Finch iphone"; const char* MY_PWD = "sonwifip"; void setup() { Serial.begin(9600); Serial.print("Connecting to "+*MY_SSID); WiFi.begin(MY_SSID, MY_PWD); Serial.println("going into Wifi connect"); while (WiFi.status() != WL_CONNECTED) { //not connected, ...waiting to connect delay(1000); Serial.print("."); } Serial.println("Wifi connected"); } void loop() { WiFiClient client; // Wait a 5 seconds between measurements. delay(5000); // Read force String data = (String) analogRead(A0); Serial.println("\nForce read at: " + data + "mN"); Serial.printf("\nStarting connection to server %s...", host); // if you get a connection, report back via serial: if (client.connect(host, 80)) { Serial.println("Connected to server"); WiFi.printDiag(Serial); client.print(String("GET /") + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" ); client.println("Content-Type: application/json"); client.print("Content-Length:"); client.print(5 + data.length()); client.print("\n\n"); client.print("data:" + data); client.print("Connection: close\r\n\r\n"); client.stop(); Serial.println("\n"); Serial.println("My POSTed data string looks like this: "); Serial.println(data); Serial.println("And it has this many bytes: "); Serial.println(data.length()); delay(2000); } else { Serial.println("connection failed!]"); client.stop(); } }
1083b3e173895e5fe0f797989bd8717aa14c64f5
f48b1da73c2d4d8f29828184bda710f27ac46672
/codechef/ZCO12001.cpp
8ac34d833bcf9d14226688a433e33b093658f369
[]
no_license
mouar/CP
ab188741dd229b3a949ea8544f4f5fc1447f7088
e95e70dbe61e1d4be473f2c328517221859a72f1
refs/heads/main
2023-03-05T19:02:23.152994
2021-02-17T07:27:31
2021-02-17T07:27:31
321,296,288
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
cpp
ZCO12001.cpp
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; stack <int> s; int nest_depth=0,nest_depth_pos,max_seq=0,max_seq_pos; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; /* int count=0; for(int i=0;i<n;i++) { if(a[i]==1) { count++; continue; } else { if (count>nest_depth) { //cout<<i<<" "<<count<<"\n"; nest_depth=count; nest_depth_pos=i; } count=0; } }*/ int count=0; int count_seq=0; for(int i=0;i<n;i++) { if(a[i]==1) { s.push(a[i]); count_seq++; } else { s.pop(); count_seq++; } if(s.size() > nest_depth) { nest_depth=s.size(); nest_depth_pos=i+1; } if(s.empty()) { if (count_seq>max_seq) { max_seq=count_seq; max_seq_pos=i - count_seq + 2; } count_seq=0; } } cout<<nest_depth<<" "<<nest_depth_pos<<" "<<max_seq<<" "<<max_seq_pos<<"\n"; }
a25092c1d0b2cdbf89cc1149ee5791852692f5d7
f7f69af928ff8842b9d89ef1f0d36383fe8009b6
/Depth-first Search/increasing-subsequences.cpp
2e2b999e4faab99b4eabee53dd1cb25fdd7ddcf2
[ "MIT" ]
permissive
PrakharPipersania/LeetCode-Solutions
f24820d2b4b911c61021e84d6b4caedc26433d4f
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
refs/heads/master
2023-04-22T04:59:46.609642
2021-05-10T08:27:57
2021-05-10T08:27:57
277,162,852
4
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
increasing-subsequences.cpp
class Solution { public: void gen(set<vector<int>> &x,vector<int> a,vector<int> nums,int index) { if(a.size()>=2) x.insert(a); for(int i=index;i<nums.size();i++) if(nums[i]>=a.back()) a.push_back(nums[i]),gen(x,a,nums,i+1),a.pop_back(); } vector<vector<int>> findSubsequences(vector<int>& nums) { vector<int> a; set<vector<int>> x; vector<vector<int>> res; for(int i=0;i<nums.size();i++) a.push_back(nums[i]),gen(x,a,nums,i+1),a.pop_back(); res.reserve(x.size()); for(auto e: x) res.push_back(e); return res; } };
e5fe2e33308c978ae66c02c7ba71638814a71dbe
d8a2ea08ca8edcb26b64eda20ef0b2a56d584104
/Chapter_15/C15_Exercise_15.5.cpp
7758b009a5fa1e49399ad624f11930b02dc5d46d
[]
no_license
weenchvd/Programming_Principles_And_Practice_Using_CXX
42288e84f4211fabce7a4cf195460bce61a1667d
9c7a088f37d091e69bf79d65a18476189b39555e
refs/heads/master
2023-02-06T08:06:45.787952
2020-12-31T10:29:42
2020-12-31T10:29:42
257,951,901
1
0
null
null
null
null
UTF-8
C++
false
false
2,640
cpp
C15_Exercise_15.5.cpp
๏ปฟ/* Exercise 15.5 */ #include<iostream> #include<stdexcept> #include<string> #include<sstream> #define _USE_MATH_DEFINES #include<math.h> #include<cmath> #include"../GUI/Simple_window.h" #include"../GUI/Graph.h" #include"C15_Exercise_15.5.h" using namespace std; //inline void error(string s) { throw runtime_error(s); } //inline void error(const string& s, const string& s2) { error(s + s2); } inline void error(const string& s, int i) { ostringstream os; os << s << ": " << i; error(os.str()); } inline void keep_window_open() { char ch; cin >> ch; } using namespace Graph_lib; int main() try { constexpr int xmax = 1200; constexpr int ymax = 1200; constexpr int x_orig = 100; constexpr int y_orig = ymax - 100; const Point orig{ x_orig,y_orig }; constexpr int r_min = 1; // range [x:x] constexpr int r_max = 50; //constexpr int n_points = 600; // number of points used in range constexpr int xlength = xmax - 200; constexpr int ylength = ymax - 200; constexpr int x_scale = ylength / r_max; constexpr int y_scale = 500; Simple_window sw{ Point{ 80, 0 }, xmax, ymax, "Leibnizโ€™s series" }; Axis x{ Axis::x, Point{ x_orig, y_orig }, xlength, xlength / x_scale, "one notch == 1" }; Axis y{ Axis::y, Point{ x_orig, y_orig }, ylength, ylength / y_scale, "one notch == 1" }; x.set_color(Color::red); y.set_color(Color::red); sw.attach(x); sw.attach(y); Text tx{ Point{x_orig + 50, y_orig + 20}, "n" }; tx.set_color(Color::dark_red); sw.attach(tx); Text ty{ Point{x_orig - 20, y_orig - 50}, "x" }; ty.set_color(Color::dark_red); sw.attach(ty); Line quarterPi{ Point{x_orig, y_orig - int(M_PI / 4 * y_scale) }, Point{x_orig + xlength, y_orig - int(M_PI / 4 * y_scale)} }; quarterPi.set_color(Color::magenta); sw.attach(quarterPi); Text tquarterPi{ Point{x_orig + xlength + 8, y_orig - int(M_PI / 4 * y_scale)}, "Pi/4" }; tquarterPi.set_color(Color::dark_magenta); sw.attach(tquarterPi); for (int n = r_min + 1; n <= r_max; n++) { Function ls{ LeibnizSeries, r_min, double(n), Point{x_orig, y_orig}, n - 1, x_scale, y_scale }; ls.set_color(Color::dark_green); sw.attach(ls); sw.wait_for_button(); sw.detach(ls); } sw.wait_for_button(); return 0; } catch (runtime_error& e) { cerr << e.what() << endl; } catch (...) { cerr << "Error. Exception\n"; return 1; } double LeibnizSeries(double n) { if (n <= 0) return 0; double ls = 0.0; double denominator = 1.0; bool isAddition{ true }; for (int i = 0; i < int(n); i++) { ls = (isAddition) ? ls + 1.0 / denominator : ls - 1.0 / denominator; isAddition = (isAddition) ? false : true; denominator += 2.0; } return ls; }
5ececd86b488a2a8bcb837e7486b0ccde8d56f27
84023126e76b0744f9dd05a1610fd27facd6f742
/AlgorithmPractice/Algorithm์ด๋ก /15. ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰.cpp
d4c41a3bf47b33f0d72c04f30b6f0ac1c0cc6afa
[]
no_license
JeonghoDean/Dean-sGit
bbcad33b5696069f65ec5016c762da3993f82fb4
52408e8f8b44301bdc04de3c003399a54dc49581
refs/heads/master
2022-04-15T09:45:50.352541
2020-04-02T06:39:49
2020-04-02T06:39:49
250,167,512
0
0
null
null
null
null
UHC
C++
false
false
1,181
cpp
15. ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰.cpp
/* ๋„ˆ๋น„๋ฅผ ์šฐ์„ ์œผ๋กœ ํ•˜์—ฌ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ• BFS ๋งน๋ชฉ์ ์ธ ํƒ์ƒ‰์„ ํ•˜๊ณ ์ž ํ• ๋•Œ ์‚ฌ์šฉ ์ตœ๋‹จ๊ฒฝ๋กœ๋Š” ์ฐพ๋Š”๋‹ค๋Š” ๊ฒƒ์—์„œ ์ตœ๋‹จ๊ธธ์ด ์ฐพ์„๋•Œ ์‚ฌ์šฉ๋จ 1.๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ 2. ํ์—์„œ ํ•˜๋‚˜์˜ ๋…ธ๋“œ ๊บผ๋ƒ… 3. ๋ฐฉ๋ฌธ ํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ ๋ฐฉ๋ฌธํ•˜๊ณ  ๋‹ค์Œ ํ๋ฅผ ๊บผ๋ƒ„ */ #include <iostream> #include <queue> #include <vector> using namespace std; int number = 7; int check[7]; vector<int> a[8]; //ํŠธ๋ฆฌ์˜ ๋ฒˆํ˜ธ์™€ ๋ฒกํ„ฐ์˜ ๋ฒˆํ˜ธ ๊ฐ™๊ฒŒํ•˜๊ธฐ์œ„ํ•ด 8๊ฐœ ์„ ์–ธ void bfs(int start) { queue<int> q; q.push(start); check[start] = true; while (!q.empty()) { int x = q.front(); q.pop(); printf("%d ", x); for (int i = 0; i < a[x].size(); i++) { int y = a[x][i]; if (!check[y]) { q.push(y); check[y] = true; } } } } int main() { a[1].push_back(2); a[2].push_back(1); a[1].push_back(3); a[3].push_back(1); a[2].push_back(3); a[3].push_back(2); a[2].push_back(4); a[4].push_back(2); a[2].push_back(5); a[5].push_back(2); a[3].push_back(6); a[6].push_back(3); a[3].push_back(7); a[7].push_back(3); a[4].push_back(5); a[5].push_back(4); a[6].push_back(7); a[7].push_back(6); bfs(1); return 0; }
4d3b5de0b19f20e67a595f070628f39f6962c0c8
3c4777b0c6554622d1935a00be081644ee301dfb
/lab1/Src/Application/myApp.h
5daaaaf560b58276b80b75b5781870bd01a0b373
[]
no_license
AntonGitName/CG_labs
0bc91c88b43afee055631e1489320ab840f2a506
de1b9aec74589161e6c8acea33d7e6e482062b22
refs/heads/master
2020-05-17T02:17:16.909130
2015-02-22T17:44:18
2015-02-22T17:44:18
31,085,096
0
0
null
null
null
null
UTF-8
C++
false
false
2,323
h
myApp.h
#ifndef __MYLAPP_H__632619789336566350 #define __MYLAPP_H__632619789336566350 /** @file cglapp.h @brief Class cglApp definition @date Created on 10/09/2005 @project D3DBase @author Bvs */ // ******************************************************************* // includes #include <d3d9.h> #include <d3dx9.h> #include "Library/cglApp.h" #pragma comment (lib, "d3d9.lib") #pragma comment (lib, "d3dx9.lib") // ******************************************************************* // defines & constants struct CUSTOMVERTEX { FLOAT X, Y, Z; DWORD COLOR; }; #define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_DIFFUSE) // ******************************************************************* // classes // Application class class myApp : public cglApp { public: // Constructor myApp(int nW, int nH, void* hInst, int nCmdShow); // Destructor virtual ~myApp(); // This function performs input processing. Returns true if input is handled virtual bool processInput(unsigned int nMsg, int wParam, long lParam); virtual void renderInternal(); protected: virtual void update(); private: enum { MAX_KEYS = 128 }; int m_nPrevMouseX; int m_nPrevMouseY; bool m_keysPressed[MAX_KEYS]; void rotateMouse(float dx, float dy); void rotateKeyboard(float dx, float dy); void zoom(float dr); void init_graphics(); void createTorus(); void transformView(); void transformWorld(); void transformWorldIdentity(); void transformProjection(); CUSTOMVERTEX getTorusVertex(float t1, float t2); static const int n = 100; static const int m = 100; static const int m_trianNum = n * m * 6; static const int m_lines = 3; LPDIRECT3DDEVICE9 m_d3ddev; // the pointer to the device class LPDIRECT3DVERTEXBUFFER9 m_vbuffer = NULL; D3DXMATRIX matWorld; D3DXMATRIX matView; D3DXMATRIX matProj; float zoomFactor = 1; float xRotateCamera = D3DX_PI / 4.0f; float yRotateCamera = D3DX_PI / 4.0f; float xRotateObject = D3DX_PI / 4.0f; float yRotateObject = D3DX_PI / 4.0f; D3DXVECTOR3 m_torusCenter = {47.0f, -37.0f, 59.0f}; }; // ******************************************************************* // functions #endif //__CGLAPP_H__632619789336566350
a7801fa8dc3599a3707c05438ad77692d17d4ed1
3f88be3eac26c86b3d051255ce829425b8730350
/src/PDBImporter.h
9f57806eb4f44fcc3323e61e2ab6b574e984dd1e
[]
no_license
pablocm/vrprotein
02d7032997a521b80d524337c14a22a2cb3f273b
c11ff2af0eb96965551e7a9956a423881650da51
refs/heads/master
2016-09-06T13:09:19.229690
2014-06-09T02:31:52
2014-06-09T02:31:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
550
h
PDBImporter.h
/* * PDBImporter.h * * Created on: Mar 11, 2014 * Author: pablocm */ #ifndef PDBIMPORTER_H_ #define PDBIMPORTER_H_ #include <memory> #include "Molecule.h" namespace VrProtein { namespace PDBImporter { /** * Toma un archivo PDB y retorna la molecula. */ std::unique_ptr<Molecule> parsePDB(const std::string &filename); std::unique_ptr<MolAtom> parsePDBAtom(const std::string &line); char short_name(const std::string& name); float default_radius(const char name); float default_mass(const char name); } } #endif /* PDBIMPORTER_H_ */
7a577031e85d2a6943353946abb80450a1c9ccfa
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/MuonSpectrometer/MuonReconstruction/MuonRecTools/MuonRecToolInterfaces/MuonRecToolInterfaces/IMuonErrorOptimisationTool.h
8b490fb86677f14a9679b83218cb38dfc9a8a3d7
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
973
h
IMuonErrorOptimisationTool.h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef MUON_IMUONERROROPTIMISATIONTOOL_H #define MUON_IMUONERROROPTIMISATIONTOOL_H #include "GaudiKernel/IAlgTool.h" static const InterfaceID IID_IMuonErrorOptimisationTool("Muon::IMuonErrorOptimisationTool",1,0); namespace Trk { class Track; } namespace Muon { /** @brief The IMuonSegmentMaker is a pure virtual interface for tools to find tracks starting from MuonSegmentCombinations */ class IMuonErrorOptimisationTool : virtual public IAlgTool { public: /** access to tool interface */ static const InterfaceID& interfaceID(); /** optimise errors on a track to maximize the momentum resolution */ virtual std::unique_ptr<Trk::Track> optimiseErrors(Trk::Track* track ) const = 0; }; inline const InterfaceID& IMuonErrorOptimisationTool::interfaceID() { return IID_IMuonErrorOptimisationTool; } } // end of name space #endif
9dccf071062cb510c772728964dd9db693532667
281d75af04e9e9ac2ba0ca69286303281741af6f
/functions/CertTool_dialog.cpp
2750640ba16a4eed3ecb6ac94c0fb62b48554be4
[]
no_license
ALEHACKsp/akt
5447468f50ba8781d2a3bb53e58b6c641399e7cd
f1c4e18bb86dc8d2ee9371505b6625da6b0292c4
refs/heads/master
2022-02-01T09:45:44.720216
2018-11-06T13:07:52
2019-05-26T11:01:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,536
cpp
CertTool_dialog.cpp
#include "CertTool_dialog.h" char CT_szProgramDir[256] = ""; //debugged program dir BOOL CALLBACK CT_DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_INITDIALOG: { CT_shared = hwndDlg; ShowWindow(GetDlgItem(hwndDlg, IDC_BTN_PAUSE), 0); ShowWindow(GetDlgItem(hwndDlg, IDC_STC_STATUS), 0); ShowWindow(GetDlgItem(hwndDlg, IDC_PROGRESS_BRUTE), 0); CT_brute_initialized = InitializeSymBruteLibrary(hwndDlg); CT_brute_dlp_initialized = InitializeDlpBruteLibrary(hwndDlg); if(!CT_brute_initialized && !CT_brute_dlp_initialized) EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTE), 0); EnableWindow(GetDlgItem(hwndDlg, IDC_BTN_BRUTESETTINGS), 0); EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTESYMVERIFY), 0); EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTENOSYMMETRIC), 0); EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTESHUTDOWN), 0); CheckDlgButton(hwndDlg, IDC_CHK_LOGFILE, CT_logtofile); } return TRUE; case WM_HELP: { char id[10] = ""; sprintf(id, "%d", IDS_HELPCERTTOOL); SetEnvironmentVariableA("HELPID", id); SetEnvironmentVariableA("HELPTITLE", "Certs Help"); DialogBox(hInst, MAKEINTRESOURCE(DLG_HELP), hwndDlg, DlgHelp); } return TRUE; case WM_BROWSE: { if(CT_isdebugging) return TRUE; strcpy(CT_szFileName, (const char*)wParam); strcpy(CT_szProgramDir, CT_szFileName); int len = strlen(CT_szProgramDir); while(CT_szProgramDir[len] != '\\') len--; CT_szProgramDir[len] = 0; strcpy(CT_szLogFile, CT_szFileName); len = strlen(CT_szLogFile); while(CT_szLogFile[len] != '.' && len) len--; if(len) CT_szLogFile[len] = 0; strcpy(CT_szAktLogFile, CT_szLogFile); strcpy(CT_szCryptCertFile, CT_szLogFile); strcpy(CT_szRawCertFile, CT_szLogFile); strcpy(CT_szStolenKeysRaw, CT_szLogFile); strcpy(CT_szStolenKeysLog, CT_szLogFile); strcat(CT_szLogFile, "_cert.log"); strcat(CT_szAktLogFile, "_cert.akt"); strcat(CT_szCryptCertFile, "_cert.bin"); strcat(CT_szRawCertFile, "_raw.cert"); strcat(CT_szStolenKeysRaw, "_stolen.keys"); strcat(CT_szStolenKeysLog, "_stolenkeys.log"); SetDlgItemTextA(hwndDlg, IDC_EDT_FILE, CT_szFileName); } return TRUE; case WM_DROPFILES: { if(CT_isdebugging) return TRUE; DragQueryFileA((HDROP)wParam, 0, CT_szFileName, MAX_PATH); strcpy(CT_szProgramDir, CT_szFileName); int len = strlen(CT_szProgramDir); while(CT_szProgramDir[len] != '\\') len--; CT_szProgramDir[len] = 0; strcpy(CT_szLogFile, CT_szFileName); len = strlen(CT_szLogFile); while(CT_szLogFile[len] != '.' && len) len--; if(len) CT_szLogFile[len] = 0; strcpy(CT_szAktLogFile, CT_szLogFile); strcpy(CT_szCryptCertFile, CT_szLogFile); strcpy(CT_szRawCertFile, CT_szLogFile); strcpy(CT_szStolenKeysRaw, CT_szLogFile); strcpy(CT_szStolenKeysLog, CT_szLogFile); strcat(CT_szLogFile, "_cert.log"); strcat(CT_szAktLogFile, "_cert.akt"); strcat(CT_szCryptCertFile, "_cert.bin"); strcat(CT_szRawCertFile, "_raw.cert"); strcat(CT_szStolenKeysRaw, "_stolen.keys"); strcat(CT_szStolenKeysLog, "_stolenkeys.log"); SetDlgItemTextA(hwndDlg, IDC_EDT_FILE, CT_szFileName); } return TRUE; case WM_CONTEXTMENU: { if(GetDlgCtrlID((HWND)wParam) == IDC_LIST_CERT) //double click { LeftClick(); LeftClick(); } } return TRUE; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_LIST_CERT: { switch(HIWORD(wParam)) { case LBN_DBLCLK: //double/right click { HWND list = GetDlgItem(hwndDlg, IDC_LIST_CERT); int cursel = SendMessageA(list, LB_GETCURSEL, 0, 0); char str[256] = ""; SendMessageA(list, LB_GETTEXT, cursel, (LPARAM)str); if(!strlen(str) || strstr(str, "Global Information:") || strstr(str, "Public Certificate Information:") || strstr(str, "Intercepted Libraries:")) return TRUE; if(strstr(str, "BaseP")) //handle base point (md5, diff, basep) { char* b = str + 10; unsigned int basep = 0; unsigned int size = 0; unsigned int diff = 0; unsigned int md5_ = 0; int total_scanned = sscanf(b, "%u (Size=%X, Diff=%X, MD5=%08X)", &basep, &size, &diff, &md5_); HMENU myMenu = 0; myMenu = CreatePopupMenu(); if(total_scanned == 4) AppendMenu(myMenu, MF_STRING, 4, "&MD5"); AppendMenu(myMenu, MF_STRING, 1, "&BaseP"); AppendMenu(myMenu, MF_STRING, 2, "&Size"); AppendMenu(myMenu, MF_STRING, 3, "&Diff"); POINT cursorPos; GetCursorPos(&cursorPos); SetForegroundWindow(hwndDlg); UINT MenuItemClicked = TrackPopupMenu(myMenu, TPM_RETURNCMD | TPM_NONOTIFY, cursorPos.x, cursorPos.y, 0, hwndDlg, 0); SendMessage(hwndDlg, WM_NULL, 0, 0); switch(MenuItemClicked) { case 0: //user clicked outside return TRUE; case 1: sprintf(str, "%u", basep); break; case 2: sprintf(str, "%X", size); break; case 3: sprintf(str, "%X", diff); break; case 4: sprintf(str, "%.8X", md5_); break; } //sprintf(str, "%u\n%X\n%X\n%.8X", basep, size, diff, md5); //MessageBoxA(hwndDlg, str, "BaseP", 0); } else if(strstr(str, " Level ")) //handle level { int leveladd = -1; //signed v2 is standard if(strstr(str, "Short V3")) leveladd = 19; else if(strstr(str, "Signed V3")) leveladd = 9; int len = strlen(str) - 1; if(str[len] != ':') return TRUE; str[len] = 0; //remove ':' len--; while(isdigit(str[len])) len--; int level = 0; sscanf(str + len, "%d", &level); level += leveladd; sprintf(str, "%X", level); //MessageBoxA(hwndDlg, str, "Raw Level (HEX)", 0); } else if(strstr(str, "Y")) //Handle Y { char* b = str + 10; char y[256] = ""; unsigned int md5_ = 0; if(sscanf(b, "%s (MD5=%08X)", y, &md5_) == 2) //has MD5 { HMENU myMenu = 0; myMenu = CreatePopupMenu(); AppendMenu(myMenu, MF_STRING, 1, "&Y"); AppendMenu(myMenu, MF_STRING, 2, "&MD5"); POINT cursorPos; GetCursorPos(&cursorPos); SetForegroundWindow(hwndDlg); UINT MenuItemClicked = TrackPopupMenu(myMenu, TPM_RETURNCMD | TPM_NONOTIFY, cursorPos.x, cursorPos.y, 0, hwndDlg, 0); SendMessage(hwndDlg, WM_NULL, 0, 0); switch(MenuItemClicked) { case 0: //user clicked outside return TRUE; case 1: strcpy(str, y); break; case 2: sprintf(str, "%.8X", md5_); break; } } else strcpy(str, y); } else if(str[0] == ' ' && str[1] == ' ' && (str[2] == '+' || str[2] == '-')) //intercepted library { strcpy(str, str + 3); //MessageBoxA(hwndDlg, str+3, "Library Name", 0); } else if(str[13] == ':') //Global Information { strcpy(str, str + 15); //MessageBoxA(hwndDlg, str+15, "Global Information", 0); } else if(str[8] == ':') //Certificate Information { strcpy(str, str + 10); //MessageBoxA(hwndDlg, str+10, "Certificate Information", 0); } CopyToClipboard(str); MessageBeep(MB_ICONINFORMATION); //MessageBoxA(hwndDlg, str, "str", 0); } break; } } return TRUE; case IDC_BTN_PAUSE: { NoFocus(); char new_title[100] = "||"; if(CT_brute_is_paused) CT_brute_is_paused = false; else { strcpy(new_title, ">"); CT_brute_is_paused = true; } SetDlgItemTextA(hwndDlg, IDC_BTN_PAUSE, new_title); } return TRUE; case IDC_BTN_BRUTESETTINGS: { if(CT_isparsing) return TRUE; NoFocus(); BruteSettings(hwndDlg); } return TRUE; case IDC_BTN_START: { NoFocus(); if(!CT_isdebugging) CreateThread(0, 0, CT_FindCertificates, 0, 0, 0); } return TRUE; case IDC_CHK_BRUTESHUTDOWN: { NoFocus(); CT_brute_shutdown = !!IsDlgButtonChecked(hwndDlg, IDC_CHK_BRUTESHUTDOWN); } return TRUE; case IDC_CHK_BRUTESYMVERIFY: { if(CT_isparsing) return TRUE; NoFocus(); CT_brute_symverify = !!IsDlgButtonChecked(hwndDlg, IDC_CHK_BRUTESYMVERIFY); } return TRUE; case IDC_CHK_BRUTE: { if(CT_isparsing) return TRUE; NoFocus(); CT_brute = !!IsDlgButtonChecked(hwndDlg, IDC_CHK_BRUTE); if(CT_brute_initialized) { EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTESHUTDOWN), CT_brute); EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTENOSYMMETRIC), CT_brute); EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTESYMVERIFY), CT_brute); EnableWindow(GetDlgItem(hwndDlg, IDC_BTN_BRUTESETTINGS), CT_brute); } } return TRUE; case IDC_CHK_BRUTENOSYMMETRIC: { if(CT_isparsing) return TRUE; NoFocus(); CT_brute_nosym = !!IsDlgButtonChecked(hwndDlg, IDC_CHK_BRUTENOSYMMETRIC); CheckDlgButton(hwndDlg, IDC_CHK_BRUTESYMVERIFY, 0); CheckDlgButton(hwndDlg, IDC_CHK_BRUTESHUTDOWN, 0); if(CT_brute_initialized) { bool enable = true; if(CT_brute_nosym) enable = false; EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTESHUTDOWN), enable); EnableWindow(GetDlgItem(hwndDlg, IDC_CHK_BRUTESYMVERIFY), enable); EnableWindow(GetDlgItem(hwndDlg, IDC_BTN_BRUTESETTINGS), enable); } } return TRUE; case IDC_CHK_LOGFILE: { if(CT_isparsing) return TRUE; NoFocus(); CT_logtofile = !!IsDlgButtonChecked(hwndDlg, IDC_CHK_LOGFILE); } return TRUE; } } return TRUE; } return FALSE; }
343fc60086bdfdcbaf9022ae8190d5bd7e9111aa
5f0eb7449d2f51665595c31c945ba2f42b58df78
/raygame/List.h
fef305e1bbccd0b8d44f69e7011e96ac270e98e1
[ "MIT" ]
permissive
SethSylvester/DataStructureAsessment
340830696fb6ede40748c010503030f8ee02c090
728defb89d0016d409ebd141d6a306384df63616
refs/heads/master
2021-01-08T22:35:33.655508
2020-03-16T20:34:32
2020-03-16T20:34:32
242,162,767
0
0
MIT
2020-02-21T18:27:10
2020-02-21T14:50:57
C++
UTF-8
C++
false
false
1,331
h
List.h
#pragma once #include "Node.h" #include "Iterator.h" template<typename T> class List { protected: //The length of the list int m_count; //The first node Node<T>* m_first; //The last node Node<T>* m_last; public: //If the list is empty bool isEmptyList(); //The Length of the list int length(); //Virtual functions virtual bool search(const T&) = 0; virtual void deleteNode(const T&) = 0; //The front & back of the list T front(); T back(); virtual void insertFirst(const T&) = 0; virtual void insertLast(const T&) = 0; //if the list is empty bool isEmpty(); }; template<typename T> inline bool List<T>::isEmptyList() { //If the first part of the node is empty //return true if (m_first == nullptr) { return true; } else { return false; } } //return the length of the array template<typename T> inline int List<T>::length() { return m_count; } //deletes the node template<typename T> inline void List<T>::deleteNode(const T & node) { delete &node; } //Return the first item template<typename T> T List<T>::front() { return m_first->data; } //Return the last item template<typename T> T List<T>::back() { return m_last->data; } //If the list is empty template<typename T> bool List<T>::isEmpty() { return m_count == 0; }
70fdb0d393c4956b3aeba1043c0f4ccbdd71d297
f5e082a928b28fd18bf45a0b58e29b5d30bcc484
/00_DataStructures/Trees Class/BinarySearchTree.cpp
0cb44e5fde13f1a815b001874e86ce1750023efc
[]
no_license
sinha-sahil/ProblemSolving
625cf2c91c190c31d906d45ffc4ff01575931012
aa1c00a528d4d59a1dc46a55548cee082803275e
refs/heads/master
2022-03-30T11:30:24.553292
2020-01-22T05:19:13
2020-01-22T05:19:13
198,296,703
0
0
null
null
null
null
UTF-8
C++
false
false
1,675
cpp
BinarySearchTree.cpp
#include<iostream> using namespace std; struct Node{ int data; Node* left, *right; Node(int val){ data= val; left= nullptr; right = nullptr; } }; void insert(Node* &root, int data){ if(root== nullptr){ root= new Node(data); return; } if(data<root->data) insert(root->left, data); else insert(root->right, data); } void inorder(Node* root){ if(root== nullptr) return; inorder(root->left); cout<<root->data<<" "; inorder(root->right); } //pair<Node*, Node*> findkey(Node* root, Node* prev, int data){ // if(root== nullptr) return make_pair(null[p]); // if(root->data == data) return make_pair(root, prev); // else if(root->data< data) findkey(root->right, root, data); // else if(root->data > data) findkey(root->left, root, data); //} void deleteKey(Node* root, int key){ } void inorder_vec(Node* root, vector<int>& vi){ if(root==nullptr) return; inorder_vec(root->left, vi); vi.push_back(root->data); inorder_vec(root->right); } int count_swaps_to_binary(Node* root){ vector<int> vi; int count=0; inorder(root, vi); for(int i=0; i< vi.size(); i++){ for(int j= 0; j<vi.size()-i-1; j++){ if(vi[j]> vi[j+1]) count++; } } return count; } Node* lca(Node* root, int v1, int v2){ if(root==nullptr) return nullptr; int t1= min(v1,v2); int t2= max(v1, v2); while(not(root->data >= t1) or not(root->data <= t2)){ if(root->data > t2 ) root= root->left; else root= root->right; } return root; } int main(){ Node* root= nullptr; insert(root, 10); insert(root, 8); insert(root, 20); insert(root, 7); insert(root, 9); insert(root, 11); insert(root, 21); cout<<"Inorder: "; inorder(root); }
80e7792ee58e8b2cda251b6dd7d286f85288fbb6
1d49be7b3d9bc0ed8d087ba2a4264ddcbb99ade2
/src/domain/fem_domain.h
d7af51828520a10729617fc3e5e072c12b566269
[ "MIT" ]
permissive
cpplanes/cpplanes
1770aef64f4698230e0e1c9deac1eed49adae668
a5aaca16f67d49eb229018ee0bfc613459660d23
refs/heads/master
2021-01-19T12:05:01.824468
2017-08-04T22:45:24
2017-08-04T23:14:27
82,284,645
0
3
null
2017-08-04T23:14:28
2017-02-17T10:13:19
Python
UTF-8
C++
false
false
1,401
h
fem_domain.h
/* * fem_domain.h * * This file is part of cpplanes, a software distributed under the MIT license. * For any question, please contact one of the authors cited below. * * Copyright (c) 2017 * Olivier Dazel <olivier.dazel@univ-lemans.fr> * Mathieu Gaborit <gaborit@kth.se> * Peter Gรถransson <pege@kth.se> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * */ #pragma once #include <vector> #include "base_domain.h" #include "../FEM/FEM.h" #include "../mesh/base_mesh.h" #include "../medium/medium.h" #include "../bc/boundary_condition.h" #include "../interpolation/interpolator.h" namespace cpplanes { template <typename T> class FEMDomain: public BaseDomain, public FEM { public: FEMDomain( BaseMesh mesh, PhysicalModel medium, std::vector<BoundaryCondition> boundary_conditions, Interpolator<T> Interpolator ); }; }
e91e3fc7a1c15d7a06536de1555f7aeddf38e16b
29b0f2c28c4768b6a297d36e51393acb7d739aa0
/src/TextLine.cpp
c987a4ba7b1331998a12b04c0bcdf31d69461f0a
[]
no_license
satosystems/me
52aa9bfd7a7722c404df921c52b8debd22865ba8
1ba3274b88bc008f0e92d71b0ad297ca064fcfb7
refs/heads/master
2020-05-19T17:26:53.259162
2013-02-08T15:46:36
2013-02-08T15:46:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,538
cpp
TextLine.cpp
#include "TextLine.h" #include "TextFile.h" #include "Line.h" #include "Logger.h" TextLine::TextLine() : Line<TextFile>(NULL, 0), mLineFeed(LineFeedNone), mCharCountCache(0) { } TextLine::TextLine(File<TextLine, TextFileIterator> *file) : Line<TextFile>(dynamic_cast<TextFile *>(file)), mLineFeed(dynamic_cast<TextFile *>(file)->mFileLineFeed), mCharCountCache(-1) { } TextLine::TextLine(TextFile *file) : Line<TextFile>(file), mLineFeed(file->mFileLineFeed), mCharCountCache(-1) { } TextLine::TextLine(TextFile *file, std::string& str) : Line<TextFile>(file), mLineFeed(file->mFileLineFeed), mCharCountCache(-1) { const char *data = str.data(); insert(0, data, data + str.size()); } TextLine::TextLine(TextFile *file, std::string& str, LineFeed lineFeedCode) : Line<TextFile>(file), mLineFeed(lineFeedCode), mCharCountCache(-1) { const char *data = str.data(); insert(0, data, data + str.size()); } void TextLine::clear() { mCharCountCache = -1; GapBuffer<char> *super = this; super->clear(); } int TextLine::insert(int pos, const char val) { mCharCountCache = -1; GapBuffer<char> *super = this; return super->insert(pos, val); } int TextLine::insert(int pos, int num, const char val) { mCharCountCache = -1; GapBuffer<char> *super = this; return super->insert(pos, num, val); } template<class InputIterator> int TextLine::insert(int pos, InputIterator begin, InputIterator end) { mCharCountCache = -1; GapBuffer<char> *super = this; return super->insert(pos, begin, end); } void TextLine::erase(int begin, int end) { mCharCountCache = -1; GapBuffer<char> *super = this; super->erase(begin, end); } void TextLine::erase(int pos) { mCharCountCache = -1; GapBuffer<char> *super = this; super->erase(pos); } void TextLine::push_back(const char val) { mCharCountCache = -1; GapBuffer<char> *super = this; super->push_back(val); } const char *TextLine::getLineFeed() const { Logger::d("mLineFeed:%s", mLineFeed == LineFeedNone ? "LineFeedNone" : mLineFeed == LineFeedCR ? "LineFeedCR" : mLineFeed == LineFeedLF ? "LineFeedLF" : mLineFeed == LineFeedCRLF ? "LineFeedCRLF" : "ERROR!!!"); if (mLineFeed == LineFeedNone) { return NULL; } const char *encodingName; if (mFile->mFileEncodingCandidate.size() == 0) { encodingName = "UTF-8"; } else { encodingName = mFile->mFileEncodingCandidate[0].name; } int offset = 0; if (strstr(encodingName, "UTF-16") == encodingName) { if (strstr(encodingName, "BE") != NULL) { offset = 3; } else if (strstr(encodingName, "LE") != NULL) { offset = 6; } else { // TODO: need detect endian of file } } else if (strstr(encodingName, "UTF-32") == encodingName) { if (strstr(encodingName, "BE") != NULL) { offset = 9; } else if (strstr(encodingName, "LE") != NULL) { offset = 12; } else { // TODO: need detect endian of file } } return LineFeedBytes[mLineFeed + offset]; } int TextLine::getCharCount() { if (mCharCountCache != -1) { return mCharCountCache; } int len = size(); int count = 0; for (int i = 0; i < len; ) { int sl = guessUtf8SequenceLength((*this)[i]); if (sl == -1) { sl = 1; } i += sl; count++; } mCharCountCache = count; return count; } const char *TextLine::LineFeedBytes[] = { // UTF-8 and multibyte encodings "\r", "\n", "\r\n", // UTF-16BE "\0\r", "\0\n", "\0\r\0\n", // UTF-16LE "\r\0", "\n\0", "\r\0\n\0", // UTF-32BE "\0\0\0\r", "\0\0\0\n", "\0\0\0\r\0\0\0\n", // UTF-32LE "\r\0\0\0", "\n\0\0\0", "\r\0\0\0\n\0\0\0", };
0dc46445058c2a366cc920e254e646aa8263a090
e0a5956edd6b57e27a1e8ad8c6b6e52a5a951db0
/include/openjson.hpp
5e6dbcc439f37b3f7e7cc06428dab78cc8f8a016
[]
no_license
winsock/EDA-Converter
adbbcd3fbfea6d7df92c76e4f380a349d4a45e83
ce0d3cb58330ce3100af8bc1939316b204777957
refs/heads/master
2021-01-10T02:18:48.945917
2016-02-24T20:08:42
2016-02-24T20:08:42
52,248,615
0
0
null
null
null
null
UTF-8
C++
false
false
28,337
hpp
openjson.hpp
#include <string> #include <regex> #include <map> #include <unordered_map> #include <vector> #include <memory> #include <algorithm> #include <locale> #include <functional> #include "json.hpp" #include "converter.hpp" using json = nlohmann::json; namespace open_json { // Forward declare data class data; inline std::vector<std::string> split(const std::string &input, const std::string &regex) { // passing -1 as the submatch index parameter performs splitting std::regex re(regex); std::sregex_token_iterator first{input.begin(), input.end(), re, -1}, last; return {first, last}; } inline bool get_boolean(json json_data, bool default_value = false) { bool value = default_value; if (json_data.is_null()) { return value; } if (json_data.is_boolean()) { value = json_data; } else if (json_data.is_string()) { std::string string_value = json_data; std::transform(string_value.begin(), string_value.end(), string_value.begin(), std::bind(&std::tolower<decltype(string_value)::value_type>, std::placeholders::_1, std::locale(""))); if (string_value == "true") { value = true; } } return value; } // Unfouturnatly there seems to be a good number of null values where there shouldn't be in OpenJSON outputed by Upverter. Custom getter to prevent exceptions. template<typename value_type> inline value_type get_value_or_default(json object, std::string key, value_type default_value) { if (object.is_null()) { return default_value; } value_type return_value; try { return_value = object.value(key, default_value); } catch (...) { return_value = default_value; } return return_value; } namespace types { inline void populate_attributes(std::map<std::string, std::string> &attribute_map, json json_data) { for (json::iterator it = json_data.begin(); it != json_data.end(); it++) { attribute_map[it.key()] = it.value(); } } typedef struct point { int64_t x, y; point() : point(0, 0) {} point(int x_pos, int y_pos) : x(x_pos), y(y_pos) {} } point; class json_object { protected: json_object *parent; public: json_object(json_object *super) : parent(super) {} virtual void read(json json_data) = 0; virtual json::object_t get_json() = 0; }; namespace shapes { enum class shape_type { RECTANGLE, ROUNDED_RECTANGLE, ARC, CIRCLE, LABEL, LINE, ROUNDED_SEGMENT, POLYGON, BEZIER_CURVE, GENERAL_POLYGON_SET, GENERAL_POLYGON }; class shape; typedef std::shared_ptr<shape> (*create_function)(json_object *super, open_json::data *file, json json_data); typedef std::map<shape_type, create_function> shape_registry_type; extern shape_registry_type shape_registry; extern std::map<std::string, shape_type> shape_typename_registry; extern std::map<shape_type, std::string> name_shape_type_registry; class shape : public json_object { protected: open_json::data *file_data; public: shape_type type; std::map<std::string, std::string> styles; float rotation = 0.0f; bool flip = false; public: shape (json_object *super, open_json::data *file, json json_data, shape_type shape_type) : json_object(super), file_data(file), type(shape_type) { this->read(json_data); } virtual void read(json json_data) override; virtual json::object_t get_json() override; static std::shared_ptr<shape> new_shape(shape_type type, json_object *super, open_json::data *file, json json_data) { if (shape_registry.find(type) == shape_registry.end()) { return nullptr; } return shape_registry[type](super, file, json_data); } }; class rectangle : public shape { unsigned int line_width = 0; int width = 0, height = 0; point position; protected: rectangle(json_object *super, open_json::data *file, json json_data, shape_type type) : shape(super, file, json_data, type) { this->read(json_data); } public: rectangle(json_object *super, open_json::data *file, json json_data) : rectangle(super, file, json_data, shape_type::RECTANGLE) {} virtual void read(json json_data) override; virtual json::object_t get_json() override; }; class rounded_rectangle : public rectangle { int radius = 3; // Corner rounding radius public: rounded_rectangle(json_object *super, open_json::data *file, json json_data) : rectangle(super, file, json_data, shape_type::ROUNDED_RECTANGLE) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class arc : public shape { float start_angle = 0.0f, end_angle = 0.0f; int radius = 3; bool is_clockwise = true; unsigned int width = 0; point position; public: arc(json_object *super, open_json::data *file, json json_data) : shape(super, file, json_data, shape_type::ARC) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class circle : public shape { unsigned int line_width = 0; int radius = 3; point position; public: circle(json_object *super, open_json::data *file, json json_data) : shape(super, file, json_data, shape_type::CIRCLE) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class label : public shape { enum class alignment { LEFT, RIGHT, CENTER }; enum class baseline_types { ALPHABETIC, MIDDLE, HANGING }; alignment align = alignment::LEFT; baseline_types baseline = baseline_types::ALPHABETIC; std::string font_family; std::string text; int font_size = 10; point position; public: label(json_object *super, open_json::data *file, json json_data) : shape(super, file, json_data, shape_type::LABEL) { this->read(json_data); } std::string get_text() { return this->text; } void read(json json_data) override; json::object_t get_json() override; }; class line : public shape { unsigned int width = 0; point start, end; protected: line(json_object *super, open_json::data *file, json json_data, shape_type type) : shape(super, file, json_data, type) { this->read(json_data); } public: line(json_object *super, open_json::data *file, json json_data) : line(super, file, json_data, shape_type::LINE) { } virtual void read(json json_data) override; virtual json::object_t get_json() override; }; class rounded_segment : public line { int radius = 3; public: rounded_segment(json_object *super, open_json::data *file, json json_data) : line(super, file, json_data, shape_type::ROUNDED_SEGMENT) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class polygon : public shape { unsigned int line_width = 0; std::vector<point> points; std::vector<shape_type> shape_types; protected: polygon(json_object *super, open_json::data *file, json json_data, shape_type type) : shape(super, file, json_data, type) { this->read(json_data); } public: polygon(json_object *super, open_json::data *file, json json_data) : polygon(super, file, json_data, shape_type::POLYGON) { } virtual void read(json json_data) override; virtual json::object_t get_json() override; }; class bezier_curve : public shape { point start, end, control_point1, control_point2; public: bezier_curve(json_object *super, open_json::data *file, json json_data) : shape(super, file, json_data, shape_type::BEZIER_CURVE) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class general_polygon : public polygon { typedef struct { std::vector<point> points; } polygon_points; std::vector<polygon_points> holes; polygon_points pour_outline; public: general_polygon(json_object *super, open_json::data *file, json json_data) : polygon(super, file, json_data, shape_type::GENERAL_POLYGON) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class general_polygon_set : public polygon { std::vector<std::shared_ptr<shape>> sub_shapes; public: general_polygon_set(json_object *super, open_json::data *file, json json_data) : polygon(super, file, json_data, shape_type::GENERAL_POLYGON_SET) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; // Factory template<class shape_class, typename = std::enable_if<std::is_base_of<shape, shape_class>::value>> std::shared_ptr<shape> create(json_object *super, open_json::data *file, json json_data) { return std::shared_ptr<shape>(new shape_class(super, file, json_data)); } }; class annotation : public json_object { private: open_json::data *file_data; float rotation = 0.0f; point position; bool flip = false, visible = true; std::shared_ptr<shapes::label> label; public: annotation(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class symbol_attribute : public json_object { private: open_json::data *file_data; float rotation = 0.0f; point position; bool flip = false, hidden = false; std::vector<std::shared_ptr<annotation>> annotations; public: symbol_attribute(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class footprint_attribute : public json_object { private: open_json::data *file_data; float rotation = 0.0f; point position; bool flip = false; std::string layer_name; public: footprint_attribute(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file){ this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class action_region : public json_object { private: open_json::data *file_data; std::map<std::string, std::string> attributes; std::map<std::string, std::string> styles; std::vector<std::vector<int>> connections; std::string name; point p1, p2; std::string ref_id; public: action_region(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } std::string get_ref_id() { return this->ref_id; } void read(json json_data) override; json::object_t get_json() override; }; class body : public json_object { private: open_json::data *file_data; float rotation = 0.0f; std::vector<int> connections; bool flip = false, moveable = true, removeable = true; std::string layer_name; std::vector<std::shared_ptr<shapes::shape>> shapes; std::vector<std::shared_ptr<action_region>> action_regions; std::vector<std::shared_ptr<annotation>> annotations; std::map<std::string, std::string> styles; public: body(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void add_shape(std::shared_ptr<shapes::shape> shape) { this->shapes.push_back(shape); } size_t get_number_of_action_regions() { return this->action_regions.size(); } std::shared_ptr<types::action_region> get_action_region_at_index(size_t index) { return index < this->action_regions.size() ? this->action_regions[index] : std::shared_ptr<types::action_region>(); } void read(json json_data) override; json::object_t get_json() override; }; // Why are there two different generated object objects???? class generated_object_attribute : public json_object { protected: open_json::data *file_data; std::map<std::string, std::string> attributes; std::string layer_name; bool flip = false; float rotation = 0.0f; point position; public: generated_object_attribute(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } virtual void read(json json_data) override; virtual json::object_t get_json() override; }; class generated_object : public generated_object_attribute { std::vector<int> connections; public: generated_object(json_object *super, open_json::data *file, json json_data) : generated_object_attribute(super, file, json_data) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class symbol : public json_object { private: open_json::data *file_data; std::vector<std::shared_ptr<body>> bodies; public: symbol(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } size_t get_number_of_bodies() { return this->bodies.size(); } std::shared_ptr<types::body> get_body_at_index(size_t index) { return index < this->bodies.size() ? this->bodies[index] : std::shared_ptr<types::body>(); } void read(json json_data) override; json::object_t get_json() override; }; class footprint : public json_object { private: open_json::data *file_data; std::vector<std::shared_ptr<body>> bodies; std::vector<std::shared_ptr<generated_object>> generated_objects; public: footprint(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class component : public json_object { private: open_json::data *file_data; std::string library_id, name; std::map<std::string, std::string> attributes; std::vector<footprint> footprints; std::vector<std::shared_ptr<symbol>> symbols; public: component(json_object *super, open_json::data *file, json json_data, std::string id) : json_object(super), file_data(file), library_id(id){ this->read(json_data); } std::string get_library_id() { return this->library_id; } size_t get_number_of_symbols() { return this->symbols.size(); } std::shared_ptr<types::symbol> get_symbol_at_index(size_t index) { return index < this->symbols.size() ? this->symbols[index] : std::shared_ptr<types::symbol>(); } void read(json json_data) override; json::object_t get_json() override; }; class component_instance : public json_object { typedef struct { bool flip = false; float rotation = 0.0f; std::string side = "top"; point position; } footprint_pos_data; private: open_json::data *file_data; std::shared_ptr<component> component_def; std::map<std::string, std::string> attributes; std::vector<symbol_attribute> symbol_attributes; std::vector<footprint_attribute> footprint_attributes; std::vector<generated_object_attribute> generated_object_attributes; std::string instance_id; footprint_pos_data footprint_pos; size_t symbol_index = 0, footprint_index = 0; public: component_instance(json_object *super, open_json::data *file, std::shared_ptr<component> def, json json_data) : json_object(super), file_data(file), component_def(def) { read(json_data); } std::string get_id() { return instance_id; } size_t get_symbol_index() { return this->symbol_index; } std::shared_ptr<types::component> get_definition() { return this->component_def; } void read(json json_data) override; json::object_t get_json() override; }; class net_point : public json_object { typedef struct connected_action_region { size_t action_region_index; size_t body_index; std::string component_instance_id; int order_index = 0; std::string signal_name; connected_action_region(size_t action_region, size_t body, std::string component_instance, int order, std::string signal) : action_region_index(action_region), body_index(body), component_instance_id(component_instance), order_index(order), signal_name(signal) {} } connected_action_region; private: open_json::data *file_data; std::string point_id; std::vector<connected_action_region> connected_action_regions; std::vector<std::string> connected_point_ids; point position; public: net_point(json_object *super, open_json::data *file, std::string id) : json_object(super), file_data(file), point_id(id) { } std::vector<connected_action_region>::iterator get_begining_of_connected_regions() { return this->connected_action_regions.begin(); } std::vector<connected_action_region>::iterator get_end_of_connected_regions() { return this->connected_action_regions.end(); } std::vector<std::string> get_connected_point_ids() { return this->connected_point_ids; } bool try_read(json json_data); virtual void read(json json_data) override { try_read(json_data); } json::object_t get_json() override; }; class net : public json_object { enum class type { NETS, MODULES_NETS }; private: open_json::data *file_data; std::vector<std::shared_ptr<annotation>> annotations; std::map<std::string, std::string> attributes; std::string net_id; type net_type = type::NETS; std::map<std::string, std::shared_ptr<net_point>> points; std::vector<std::string> signals; public: net(json_object *super, open_json::data *file) : json_object(super), file_data(file) { } std::string get_id() { return net_id; } bool try_read(json json_data); virtual void read(json json_data) override { try_read(json_data); } json::object_t get_json() override; }; class trace : public json_object { enum class type { STRAIGHT }; private: open_json::data *file_data; std::string layer_name; point start, end; std::vector<point> control_points; type trace_type = type::STRAIGHT; double width; public: trace(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class pour : public json_object { private: open_json::data *file_data; std::string attached_net_id; std::map<std::string, std::string> attributes; std::string layer_name; int order_index = 0; std::vector<point> points; std::shared_ptr<shapes::shape> pour_shape; std::vector<shapes::shape_type> shape_types; public: pour(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class pcb_text : public json_object { private: open_json::data *file_data; bool flip = false, visible = true; std::shared_ptr<shapes::label> label; std::string layer_name; float rotation = 0.0f; point position; public: pcb_text(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; // Why are there two different layout objects???? class layout_body_attribute : public json_object { protected: open_json::data *file_data; bool flip = false; std::string layer_name; float rotation = 0.0f; point position; public: layout_body_attribute(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } virtual void read(json json_data) override; virtual json::object_t get_json() override; }; class layout_object : public layout_body_attribute { std::map<std::string, std::string> attributes; std::vector<int> connections; public: layout_object(json_object *super, open_json::data *file, json json_data) : layout_body_attribute(super, file, json_data) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class layer_option : public json_object { private: open_json::data *file_data; std::string ident, name; bool is_copper = true; public: layer_option(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class path : public json_object { private: open_json::data *file_data; std::map<std::string, std::string> attributes; bool is_closed = true; std::string layer_name; double width = 250000.0; // .25mm std::vector<point> points; std::vector<shapes::shape_type> shape_types; public: path(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class design_info : public json_object { typedef struct { std::vector<std::string> attached_links; std::string description; std::string design_id; std::string license; std::string name; std::string owner; std::string slug; uint64_t last_updated; } metadata_container; private: open_json::data *file_data; std::vector<std::shared_ptr<annotation>> annotations; std::map<std::string, std::string> attributes; metadata_container metadata; public: design_info(json_object *super, open_json::data *file, json json_data) : json_object(super), file_data(file) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; }; class data : public types::json_object { public: typedef struct { std::string exporter; int major = 0, minor = 2, build = 0; } version; std::string original_file_name; version version_info; std::shared_ptr<types::design_info> design_info; std::map<std::string, std::shared_ptr<types::component>> components; std::map<std::string, std::shared_ptr<types::component_instance>> component_instances; std::map<std::string, std::shared_ptr<types::net>> nets; std::vector<std::shared_ptr<types::layer_option>> layer_options; std::vector<std::shared_ptr<types::body>> layout_bodies; std::vector<std::shared_ptr<types::layout_body_attribute>> layout_body_attributes; std::vector<std::shared_ptr<types::layout_object>> layout_objects; std::vector<std::shared_ptr<types::pcb_text>> pcb_text; std::vector<std::shared_ptr<types::pour>> pours; std::vector<std::shared_ptr<types::trace>> traces; std::vector<std::shared_ptr<types::path>> paths; public: data(std::string file_name, json json_data) : json_object(nullptr), original_file_name(file_name) { this->read(json_data); } void read(json json_data) override; json::object_t get_json() override; }; class open_json_format : public eda_format { private: std::vector<std::shared_ptr<data>> parsed_data; public: void read(std::vector<std::string> files) override; void write(output_type type, std::string out_file) override; }; };
344ed83316efd69adc99c098d8d9e74ed237f6e0
354a2bcf2d5e5d4e4052ca1b199bfb44fd2bc462
/vtkm/rendering/TextAnnotation.cxx
a5b9b2bf57dfc33ea8df9061b4f892c7b9dc8d51
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Kitware/VTK-m
108f96185fc3c3914498873c58a94ca75f2f2219
0c86e3277b6f19c91e5db240da00ff33028b9a2e
refs/heads/master
2023-08-30T13:05:05.132168
2023-08-29T20:36:57
2023-08-29T20:37:14
190,059,477
22
7
null
null
null
null
UTF-8
C++
false
false
2,311
cxx
TextAnnotation.cxx
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/rendering/TextAnnotation.h> namespace vtkm { namespace rendering { TextAnnotation::TextAnnotation(const std::string& text, const vtkm::rendering::Color& color, vtkm::Float32 scale) : Text(text) , TextColor(color) , Scale(scale) , Anchor(-1, -1) { } TextAnnotation::~TextAnnotation() = default; void TextAnnotation::SetText(const std::string& text) { this->Text = text; } const std::string& TextAnnotation::GetText() const { return this->Text; } void TextAnnotation::SetRawAnchor(const vtkm::Vec2f_32& anchor) { this->Anchor = anchor; } void TextAnnotation::SetRawAnchor(vtkm::Float32 h, vtkm::Float32 v) { this->SetRawAnchor(vtkm::make_Vec(h, v)); } void TextAnnotation::SetAlignment(HorizontalAlignment h, VerticalAlignment v) { switch (h) { case Left: this->Anchor[0] = -1.0f; break; case HCenter: this->Anchor[0] = 0.0f; break; case Right: this->Anchor[0] = +1.0f; break; } // For vertical alignment, "center" is generally the center // of only the above-baseline contents of the font, so we // use a value slightly off of zero for VCenter. // (We don't use an offset value instead of -1.0 for the // bottom value, because generally we want a true minimum // extent, e.g. to have text sitting at the bottom of a // window, and in that case, we need to keep all the text, // including parts that descend below the baseline, above // the bottom of the window. switch (v) { case Bottom: this->Anchor[1] = -1.0f; break; case VCenter: this->Anchor[1] = -0.06f; break; case Top: this->Anchor[1] = +1.0f; break; } } void TextAnnotation::SetScale(vtkm::Float32 scale) { this->Scale = scale; } } } // namespace vtkm::rendering
96fa22231294c78276551c3466dca9e3cc3740c5
a59ea038b613c3ea8f89b1c05c121f79bf34c58e
/codeforces/978D.cpp
4008a49d0d1314130a4824439841c441f115d3d1
[]
no_license
srd091/Sports-Programming
0c5054d4d6bf3c94547b4ad62d264a46b26e6a74
ee9178b45512b9b84513fa5e074d296c037052fd
refs/heads/master
2020-06-20T04:00:21.835591
2018-09-21T10:35:00
2018-09-21T10:35:00
74,883,707
0
0
null
null
null
null
UTF-8
C++
false
false
1,121
cpp
978D.cpp
/* Just For You 97116:) */ #include <bits/stdc++.h> using namespace std; //important constants #define pi M_PI #define mod 1000000007 #define multiplier 100000000000 #define maX(a,b) ((a)>(b)?(a):(b)) #define miN(a,b) ((a)<(b)?(a):(b)) #ifdef ONLINE_JUDGE #define MAX 2000005 #else #define MAX 100000 #endif int a[MAX],b[MAX]; char s[MAX],r[MAX]; int test,n; int main(){ #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif int t,m,k,l,x,y,z,d,flag=0,count; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); if(n<3) printf("0"); else{ count=mod; for(int i=-1;i<=1;i++){ for(int j=-1;j<=1;j++){ b[0]=a[0]+i,b[1]=a[1]+j; d=b[1]-b[0]; z=abs(i)+abs(j); for(int k=2;k<n;k++){ x=b[0]+k*d; if(abs(a[k]-x)>1){ z=mod; break; }else if(x!=a[k]) z++; } count=min(z,count); } } if(count==mod) count=-1; printf("%d",count); } return 0; }
979faba3f5356777a3cc87a21434e39c6d6f9f24
715f26b17c6847cc4108cc27b04021956fb2476c
/src/Algorithm.cpp
fc84b1274fb668d4fa2df6d6aa4d6e901756cee5
[]
no_license
cmmw/gcolor
604f04e2c7168136db498f806527f1b6b2bca011
9577334bdbac57a99b77ec99cbeed1111f55f009
refs/heads/master
2021-07-03T11:23:17.406906
2015-06-24T20:09:27
2015-06-24T20:09:27
104,645,171
0
0
null
null
null
null
UTF-8
C++
false
false
9,933
cpp
Algorithm.cpp
/* * Algorithm.cpp * * Created on: Apr 13, 2015 * Author: ixi */ #include "Algorithm.h" #include "Logger.h" #include <algorithm> #include "time.h" #define TIME_PASSED double(clock() - begin) / CLOCKS_PER_SEC extern int visitedNodes; extern int triedColors; extern int mac; extern int mrv; extern int lcv; extern clock_t begin; extern double time_limit; double new_time_limit; extern int alg; bool firstRun = true; namespace graphcoloring { Algorithm::Algorithm() { } Algorithm::~Algorithm() { } // Repeatedly launch backtracking to find solution with minimum k Solution* Algorithm::findOptimalSolution(Graph& graph) { int startK = 0; int endK = graph.getNum_Nodes(); int k = (endK - startK) / 2; Solution* solution; Solution* bestSolution = NULL; firstRun = true; new_time_limit = time_limit; if (alg == 1) { new_time_limit = time_limit * 0.05; } while (new_time_limit == -1 || (alg == 1 && firstRun) || TIME_PASSED < new_time_limit) { LOG << "Trying with k = " << k; LOG << "searching in [" << startK << ", " << endK << "]"; solution = backtrack(new Solution(graph.getNum_Nodes(), k), graph); firstRun = false; if (solution != NULL) { int step = (endK - k) / 2; if(step == 0) step = 1; LOG << "found solution (current time " << TIME_PASSED << "): "; solution->printSolution(); endK = k; k -= step; delete bestSolution; bestSolution = solution; } else { int step = (k - startK) / 2; if(step == 0) step = 1; LOG << "not found"; startK = k; k += step; } // k = startK + ((endK - startK) / 2); //simplified if ((endK - startK) == 1) break; } return bestSolution; } // Backtracking algorithm as described in the Book: // "Artificial Intelligence: A Modern Approach" by Stuart Russel and Peter Norvig Solution* Algorithm::backtrack(Solution* solution, Graph& graph) { if ((alg == 0 || !firstRun) && new_time_limit != -1 && TIME_PASSED > new_time_limit) { return NULL; } int nodeId = selectUnassignedNode(solution, graph); visitedNodes++; if (nodeId == -1) { // all nodes are colored, return solution return solution; } vector<int> domainValues = orderColors(nodeId, solution, graph); //cout << "Colorlist size: " << domainValues.size() << endl; for (vector<int>::iterator it = domainValues.begin(); it != domainValues.end(); it++) { triedColors++; int color = *it; if (assignmentIsConsistent(nodeId, color, solution, graph)) { Solution* newSolution = new Solution(*solution); newSolution->setColor(nodeId, color); if (inferences(newSolution, graph, nodeId)) { Solution* backtrackSolution; backtrackSolution = backtrack(newSolution, graph); if (backtrackSolution != NULL) { delete solution; return backtrackSolution; } } delete newSolution; } } return NULL; } int Algorithm::selectUnassignedNode(Solution* solution, Graph& graph) { if (mrv > 0) { return MRV(solution, graph); } else { return simpleSelectionHeuristic(solution, graph); } } int Algorithm::simpleSelectionHeuristic(Solution* solution, const Graph& graph) { for (int i = 0; i < solution->getNum_Nodes(); i++) { if (solution->getColor(i) == -1) return i; } return -1; } int Algorithm::MRV(Solution* solution, const Graph& graph) { //Variable Selection Heuristic: minimum remaining values (MRV) int node = -1; int remainingValues = -1; int unassignedNeighbors = -1; for (int i = 0; i < solution->getNum_Nodes(); i++) { if (solution->getColor(i) == -1) { if (node == -1) { node = i; remainingValues = solution->getDomainValues(i).size(); } else { int tmp = solution->getDomainValues(i).size(); if (remainingValues > tmp) { node = i; remainingValues = tmp; } else if (remainingValues == tmp) //Tie-breaking: degree heuristic. Choose variable which is involved in more constraints (has more unassigned neighbours) { if (unassignedNeighbors == -1) unassignedNeighbors = getUnassignedNeighbours(solution, graph, node); int tmp = getUnassignedNeighbours(solution, graph, i); if (tmp > unassignedNeighbors) { unassignedNeighbors = tmp; node = i; } } } } } return node; } int Algorithm::getUnassignedNeighbours(Solution* solution, const Graph& graph, int node) { vector<int> neighbours = graph.getNeighbours(node); int count = 0; for (vector<int>::iterator it = neighbours.begin(); it != neighbours.end(); it++) { if (solution->getColor(*it) == -1) count++; } return count; } bool Algorithm::inferences(Solution* solution, Graph& graph, int lastSetNodeId) { if (mac > 0) { return maintainingArcConsistency(solution, graph, lastSetNodeId); } else { return simpleForwardChecking(solution, graph, lastSetNodeId); } } bool Algorithm::simpleForwardChecking(Solution* solution, Graph& graph, int lastSetNodeId) { int color = solution->getColor(lastSetNodeId); vector<int> neighbours = graph.getNeighbours(lastSetNodeId); for (vector<int>::iterator it = neighbours.begin(); it != neighbours.end(); it++) { if (solution->getColor(*it) == -1) { vector<int> domainValues = solution->getDomainValues(*it); domainValues.erase( std::remove( domainValues.begin(), domainValues.end(), color ), domainValues.end() ); if (domainValues.size() == 0) { return false; } else { solution->setDomainValues(*it, domainValues); } } } return true; } bool Algorithm::maintainingArcConsistency(Solution* solution, Graph& graph, int lastSetNodeId) { list<Edge> edges; vector<Edge> incidentEdges = graph.getIncidentEdges(lastSetNodeId); for (vector<Edge>::iterator it = incidentEdges.begin(); it != incidentEdges.end(); it++) { if (solution->getColor(it->getV1()) != -1 || solution->getColor(it->getV2()) != -1) { if (it->getV1() == lastSetNodeId) { edges.push_back(Edge(it->getV2(), it->getV1())); } else { edges.push_back(Edge(it->getV1(), it->getV2())); } } } for (list<Edge>::iterator it = edges.begin(); it != edges.end(); it++) { if (revise(solution, graph, it->getV1(), it->getV2())) { if (solution->getDomainValues(it->getV1()).size() == 0) { return false; } incidentEdges = graph.getIncidentEdges(it->getV1()); for (vector<Edge>::iterator it2 = incidentEdges.begin(); it2 != incidentEdges.end(); it2++) { if (it2->getV1() != it->getV2() && it2->getV2() != it->getV2() && (solution->getColor(it2->getV1()) == -1 || solution->getColor(it2->getV2()) == -1)) { if (it2->getV1() == it->getV1()) { edges.push_back(Edge(it2->getV2(), it2->getV1())); } else { edges.push_back(Edge(it2->getV1(), it2->getV2())); } } } } } return true; } bool Algorithm::revise(Solution* solution, Graph& graph, int nodeId1, int nodeId2) { bool revised = false; vector<int> oldDomainValues1 = solution->getDomainValues(nodeId1); list<int> domainValues1(oldDomainValues1.begin(), oldDomainValues1.end() ); vector<int> domainValues2; if (solution->getColor(nodeId2) != -1) { domainValues2.push_back(solution->getColor(nodeId2)); } else { domainValues2 = solution->getDomainValues(nodeId2); } for (list<int>::iterator it = domainValues1.begin(); it != domainValues1.end();) { if (domainValues2.size() == 1 && *it == domainValues2.front()) { it = domainValues1.erase(it); revised = true; } else { it++; } } vector<int> newDomainValues1( domainValues1.begin(), domainValues1.end() ); solution->setDomainValues(nodeId1, newDomainValues1); return revised; } vector<int> Algorithm::orderColors(int nodeId, Solution* solution, Graph& graph) { if (lcv > 0) { return leastConstrainingValue(nodeId, solution, graph); } else { return simpleValueOrdering(nodeId, solution, graph); } } vector<int> Algorithm::leastConstrainingValue(int nodeId, Solution* solution, Graph& graph) { //Value Selection Heuristic: least-constraining-value (value that rules out the fewest choices for the neighbors) std::vector<int> orderedValues; std::list<int> colors; std::list<int> values; vector<int> domainValues = solution->getDomainValues(nodeId); for (vector<int>::iterator it = domainValues.begin(); it != domainValues.end(); it++) { int value = countOccurrence(*it, graph, solution, nodeId); if (value != -1) { int pos = 0; for (std::list<int>::iterator it2 = values.begin(); it2 != values.end(); it2++) { if (value < *it2) break; pos++; } std::list<int>::iterator valIt = values.begin(); std::list<int>::iterator colIt = colors.begin(); std::advance(valIt, pos); std::advance(colIt, pos); values.insert(valIt, value); colors.insert(colIt, *it); } } orderedValues = std::vector<int>(colors.begin(), colors.end()); return orderedValues; } vector<int> Algorithm::simpleValueOrdering(int nodeId, Solution* solution, Graph& graph) { return solution->getDomainValues(nodeId); } int Algorithm::countOccurrence(int col, const Graph& graph, Solution* solution, int nodeId) { vector<int> neighbours = graph.getNeighbours(nodeId); int count = 0; for (vector<int>::iterator it = neighbours.begin(); it != neighbours.end(); it++) { if (solution->getColor(*it) == -1) { std::vector<int> domain = solution->getDomainValues(*it); if (std::find(domain.begin(), domain.end(), col) != domain.end()) count++; } else if (solution->getColor(*it) == col) { return -1; } } return count; } bool Algorithm::assignmentIsConsistent(int nodeId, int color, Solution* solution, Graph& graph) { // just check if the newly assigned variable causes any inconsistencies to previously set colors vector<int> neighbours = graph.getNeighbours(nodeId); for (vector<int>::iterator it = neighbours.begin(); it != neighbours.end(); it++) { if (color == solution->getColor(*it)) { return false; } } return true; } } /* namespace graphcoloring */
6f63d6abbf93937c547b7c1371f2ee786bbabcd1
e45d57f260be59dec60d5fbe7d03423a43586af3
/Room.h
6ba249152f36a4a545e298a7d9da51800d8459dc
[]
no_license
contactonee/Timetable
887dc68eb17d30c9e2f769f0a2cee2b38678b4b1
2f464e0d487cbf8c3bc8b9e0da060c03dcffe410
refs/heads/master
2023-05-11T05:16:40.731471
2017-12-06T11:56:47
2017-12-06T11:56:47
115,443,369
0
0
null
null
null
null
UTF-8
C++
false
false
348
h
Room.h
#ifndef ROOM_H #define ROOM_H #include <string> #include "Reservable.h" class Room : public Reservable { public: Room(std::string name, int size, bool laboratory = 0, bool computers = 0); std::string name(); int size(); bool compLab; bool lab; private: std::string Name; int Size; }; #endif
01452f68c535b2853f84e208b9bbbb234c2b4828
4adedb7e7b615180f752682c145630e3d80e3eb3
/otog/modulovplus.cpp
ec13137d16fc03c3b4b23d3c0da90bbe72abcf07
[]
no_license
p0ndja/POSN
0a951bcd92fa17528b1180db2cad5e205c7814c5
db9555fe2a258a8c5c150c2995c73698de73b74e
refs/heads/master
2020-03-30T22:05:33.660806
2019-03-21T02:12:12
2019-03-21T02:12:12
151,654,227
0
1
null
null
null
null
UTF-8
C++
false
false
369
cpp
modulovplus.cpp
#include <bits/stdc++.h> using namespace std; int mod[10000]; int main(){ int n,k,countt = 0; scanf("%d %d",&n,&k); for(int i = 0; i < n; i++){ long long x; scanf("%lld",&x); if (mod[x%k] == 0) { mod[x%k] = 1; countt++; } } printf("%d\n",countt); for(int i = 0; i < k; i++) if(mod[i] == 1) printf("%d\n",i); return 0; }
ba41b9b0a2099f687c25e61d7bd802e9ef9d9a8b
9a6094e9cef7cbb420ef6c9a3999993de296182a
/include/tl/type_traits/is_void.h
129a566ffe6339957489247989a81e2f7d055a1c
[]
no_license
Username-commits/tl
a061a5e2eaace004f16920989c87bcbb1864c0e6
cf9494bdcbb888feabe1a8ef5dca391c9cc42882
refs/heads/master
2022-11-17T23:17:22.685322
2020-07-17T16:40:44
2020-07-17T16:40:44
280,475,408
0
0
null
null
null
null
UTF-8
C++
false
false
574
h
is_void.h
#ifndef _TL_IS_VOID_H_INCLUDED_ #define _TL_IS_VOID_H_INCLUDED_ 1 #include "integral_constants.h" namespace tl{ template<typename T> struct is_void : false_type { }; template<> struct is_void<void> : true_type { }; template<> struct is_void<const void> : true_type { }; template<> struct is_void<volatile void> : true_type { }; template<> struct is_void<const volatile void> : true_type { }; template<typename T> static constexpr bool is_void_v = is_void<T>::value; } #endif//_TL_IS_VOID_H_INCLUDED_
8b807dc504819977754bd869ce96a230df1aee41
b677894966f2ae2d0585a31f163a362e41a3eae0
/ns3/ns-3.26/src/test/ns3tc/pie-queue-disc-test-suite.cc
defa139802e6f71e83f4997aab2a8fd95c0e3a83
[ "LicenseRef-scancode-free-unknown", "GPL-2.0-only", "Apache-2.0" ]
permissive
cyliustack/clusim
667a9eef2e1ea8dad1511fd405f3191d150a04a8
cbedcf671ba19fded26e4776c0e068f81f068dfd
refs/heads/master
2022-10-06T20:14:43.052930
2022-10-01T19:42:19
2022-10-01T19:42:19
99,692,344
7
3
Apache-2.0
2018-07-04T10:09:24
2017-08-08T12:51:33
Python
UTF-8
C++
false
false
13,914
cc
pie-queue-disc-test-suite.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2016 NITK Surathkal * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Authors: Shravya Ks <shravya.ks0@gmail.com> * Smriti Murali <m.smriti.95@gmail.com> * Mohit P. Tahiliani <tahiliani@nitk.edu.in> * */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h" #include "ns3/traffic-control-module.h" using namespace ns3; class PieQueueDiscTestItem : public QueueDiscItem { public: PieQueueDiscTestItem (Ptr<Packet> p, const Address & addr, uint16_t protocol); virtual ~PieQueueDiscTestItem (); virtual void AddHeader (void); private: PieQueueDiscTestItem (); PieQueueDiscTestItem (const PieQueueDiscTestItem &); PieQueueDiscTestItem &operator = (const PieQueueDiscTestItem &); }; PieQueueDiscTestItem::PieQueueDiscTestItem (Ptr<Packet> p, const Address & addr, uint16_t protocol) : QueueDiscItem (p, addr, protocol) { } PieQueueDiscTestItem::~PieQueueDiscTestItem () { } void PieQueueDiscTestItem::AddHeader (void) { } class PieQueueDiscTestCase : public TestCase { public: PieQueueDiscTestCase (); virtual void DoRun (void); private: void Enqueue (Ptr<PieQueueDisc> queue, uint32_t size, uint32_t nPkt); void RunPieTest (StringValue mode); }; PieQueueDiscTestCase::PieQueueDiscTestCase () : TestCase ("Sanity check on the pie queue implementation") { } void PieQueueDiscTestCase::RunPieTest (StringValue mode) { uint32_t pktSize = 0; // 1 for packets; pktSize for bytes uint32_t modeSize = 1; uint32_t qSize = 8; Ptr<PieQueueDisc> queue = CreateObject<PieQueueDisc> (); // test 1: simple enqueue/dequeue with no drops NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true, "Verify that we can actually set the attribute Mode"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueLimit", UintegerValue (qSize)), true, "Verify that we can actually set the attribute QueueLimit"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("A", DoubleValue (0.125)), true, "Verify that we can actually set the attribute A"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("B", DoubleValue (1.25)), true, "Verify that we can actually set the attribute B"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Tupdate", TimeValue (Seconds (0.03))), true, "Verify that we can actually set the attribute Tupdate"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Supdate", TimeValue (Seconds (0.0))), true, "Verify that we can actually set the attribute Supdate"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("DequeueThreshold", UintegerValue (10000)), true, "Verify that we can actually set the attribute DequeueThreshold"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("QueueDelayReference", TimeValue (Seconds (0.02))), true, "Verify that we can actually set the attribute QueueDelayReference"); NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("MaxBurstAllowance", TimeValue (Seconds (0.1))), true, "Verify that we can actually set the attribute MaxBurstAllowance"); Address dest; if (queue->GetMode () == Queue::QUEUE_MODE_BYTES) { pktSize = 1000; modeSize = pktSize; queue->SetQueueLimit (qSize * modeSize); } Ptr<Packet> p1, p2, p3, p4, p5, p6, p7, p8; p1 = Create<Packet> (pktSize); p2 = Create<Packet> (pktSize); p3 = Create<Packet> (pktSize); p4 = Create<Packet> (pktSize); p5 = Create<Packet> (pktSize); p6 = Create<Packet> (pktSize); p7 = Create<Packet> (pktSize); p8 = Create<Packet> (pktSize); queue->Initialize (); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 0 * modeSize, "There should be no packets in there"); queue->Enqueue (Create<PieQueueDiscTestItem> (p1, dest, 0)); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 1 * modeSize, "There should be one packet in there"); queue->Enqueue (Create<PieQueueDiscTestItem> (p2, dest, 0)); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 2 * modeSize, "There should be two packets in there"); queue->Enqueue (Create<PieQueueDiscTestItem> (p3, dest, 0)); queue->Enqueue (Create<PieQueueDiscTestItem> (p4, dest, 0)); queue->Enqueue (Create<PieQueueDiscTestItem> (p5, dest, 0)); queue->Enqueue (Create<PieQueueDiscTestItem> (p6, dest, 0)); queue->Enqueue (Create<PieQueueDiscTestItem> (p7, dest, 0)); queue->Enqueue (Create<PieQueueDiscTestItem> (p8, dest, 0)); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 8 * modeSize, "There should be eight packets in there"); Ptr<QueueDiscItem> item; item = queue->Dequeue (); NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the first packet"); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 7 * modeSize, "There should be seven packets in there"); NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p1->GetUid (), "was this the first packet ?"); item = queue->Dequeue (); NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the second packet"); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 6 * modeSize, "There should be six packet in there"); NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p2->GetUid (), "Was this the second packet ?"); item = queue->Dequeue (); NS_TEST_EXPECT_MSG_EQ ((item != 0), true, "I want to remove the third packet"); NS_TEST_EXPECT_MSG_EQ (queue->GetQueueSize (), 5 * modeSize, "There should be five packets in there"); NS_TEST_EXPECT_MSG_EQ (item->GetPacket ()->GetUid (), p3->GetUid (), "Was this the third packet ?"); item = queue->Dequeue (); item = queue->Dequeue (); item = queue->Dequeue (); item = queue->Dequeue (); item = queue->Dequeue (); item = queue->Dequeue (); NS_TEST_EXPECT_MSG_EQ ((item == 0), true, "There are really no packets in there"); // test 2: test in a simple dumbbell topology pktSize = 1000; std::string pieLinkDataRate = "1.5Mbps"; std::string pieLinkDelay = "20ms"; double global_start_time = 0.0; double global_stop_time = 7.0; double sink_start_time = global_start_time; double sink_stop_time = global_stop_time + 3.0; double client_start_time = global_start_time + 1.5; double client_stop_time = global_stop_time - 2.0; NodeContainer n0n2; NodeContainer n1n2; NodeContainer n2n3; NodeContainer n3n4; NodeContainer n3n5; Ipv4InterfaceContainer i0i2; Ipv4InterfaceContainer i1i2; Ipv4InterfaceContainer i2i3; Ipv4InterfaceContainer i3i4; Ipv4InterfaceContainer i3i5; NodeContainer c; c.Create (6); n0n2 = NodeContainer (c.Get (0), c.Get (2)); n1n2 = NodeContainer (c.Get (1), c.Get (2)); n2n3 = NodeContainer (c.Get (2), c.Get (3)); n3n4 = NodeContainer (c.Get (3), c.Get (4)); n3n5 = NodeContainer (c.Get (3), c.Get (5)); Config::SetDefault ("ns3::TcpL4Protocol::SocketType", StringValue ("ns3::TcpNewReno")); // 42 = headers size Config::SetDefault ("ns3::TcpSocket::SegmentSize", UintegerValue (1000 - 42)); Config::SetDefault ("ns3::TcpSocket::DelAckCount", UintegerValue (1)); GlobalValue::Bind ("ChecksumEnabled", BooleanValue (false)); uint32_t meanPktSize = 1000; NS_TEST_EXPECT_MSG_EQ (queue->SetAttributeFailSafe ("Mode", mode), true, "Verify that we can actually set the attribute Mode"); Ipv4Header ipHeader; if (queue->GetMode () == Queue::QUEUE_MODE_BYTES) { modeSize = pktSize + ipHeader.GetSerializedSize (); } qSize = 100 * modeSize; // PIE params Config::SetDefault ("ns3::PieQueueDisc::Mode", StringValue (mode)); Config::SetDefault ("ns3::PieQueueDisc::MeanPktSize", UintegerValue (meanPktSize + ipHeader.GetSerializedSize ())); Config::SetDefault ("ns3::PieQueueDisc::DequeueThreshold", UintegerValue (10000)); Config::SetDefault ("ns3::PieQueueDisc::QueueDelayReference", TimeValue (Seconds (0.02))); Config::SetDefault ("ns3::PieQueueDisc::MaxBurstAllowance", TimeValue (Seconds (0.1))); Config::SetDefault ("ns3::PieQueueDisc::QueueLimit", UintegerValue (qSize)); InternetStackHelper internet; internet.Install (c); TrafficControlHelper tchPfifo; uint16_t handle = tchPfifo.SetRootQueueDisc ("ns3::PfifoFastQueueDisc"); tchPfifo.AddInternalQueues (handle, 3, "ns3::DropTailQueue", "MaxPackets", UintegerValue (1000)); TrafficControlHelper tchPie; tchPie.SetRootQueueDisc ("ns3::PieQueueDisc"); PointToPointHelper p2p; NetDeviceContainer devn0n2; NetDeviceContainer devn1n2; NetDeviceContainer devn2n3; NetDeviceContainer devn3n4; NetDeviceContainer devn3n5; QueueDiscContainer queueDiscs; p2p.SetQueue ("ns3::DropTailQueue"); p2p.SetDeviceAttribute ("DataRate", StringValue ("10Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("2ms")); devn0n2 = p2p.Install (n0n2); tchPfifo.Install (devn0n2); p2p.SetQueue ("ns3::DropTailQueue"); p2p.SetDeviceAttribute ("DataRate", StringValue ("10Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("3ms")); devn1n2 = p2p.Install (n1n2); tchPfifo.Install (devn1n2); p2p.SetQueue ("ns3::DropTailQueue"); p2p.SetDeviceAttribute ("DataRate", StringValue (pieLinkDataRate)); p2p.SetChannelAttribute ("Delay", StringValue (pieLinkDelay)); devn2n3 = p2p.Install (n2n3); // only backbone link has PIE queue disc queueDiscs = tchPie.Install (devn2n3); p2p.SetQueue ("ns3::DropTailQueue"); p2p.SetDeviceAttribute ("DataRate", StringValue ("10Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("4ms")); devn3n4 = p2p.Install (n3n4); tchPfifo.Install (devn3n4); p2p.SetQueue ("ns3::DropTailQueue"); p2p.SetDeviceAttribute ("DataRate", StringValue ("10Mbps")); p2p.SetChannelAttribute ("Delay", StringValue ("5ms")); devn3n5 = p2p.Install (n3n5); tchPfifo.Install (devn3n5); Ipv4AddressHelper ipv4; ipv4.SetBase ("10.1.1.0", "255.255.255.0"); i0i2 = ipv4.Assign (devn0n2); ipv4.SetBase ("10.1.2.0", "255.255.255.0"); i1i2 = ipv4.Assign (devn1n2); ipv4.SetBase ("10.1.3.0", "255.255.255.0"); i2i3 = ipv4.Assign (devn2n3); ipv4.SetBase ("10.1.4.0", "255.255.255.0"); i3i4 = ipv4.Assign (devn3n4); ipv4.SetBase ("10.1.5.0", "255.255.255.0"); i3i5 = ipv4.Assign (devn3n5); // Set up the routing Ipv4GlobalRoutingHelper::PopulateRoutingTables (); // SINK is in the right side uint16_t port = 50000; Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port)); PacketSinkHelper sinkHelper ("ns3::TcpSocketFactory", sinkLocalAddress); ApplicationContainer sinkApp = sinkHelper.Install (n3n4.Get (1)); sinkApp.Start (Seconds (sink_start_time)); sinkApp.Stop (Seconds (sink_stop_time)); // Connection one // Clients are in left side /* * Create the OnOff applications to send TCP to the server * onoffhelper is a client that send data to TCP destination */ OnOffHelper clientHelper1 ("ns3::TcpSocketFactory", Address ()); clientHelper1.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); clientHelper1.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); clientHelper1.SetAttribute ("PacketSize", UintegerValue (pktSize)); clientHelper1.SetAttribute ("DataRate", DataRateValue (DataRate ("100Mbps"))); // Connection two OnOffHelper clientHelper2 ("ns3::TcpSocketFactory", Address ()); clientHelper2.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); clientHelper2.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); clientHelper2.SetAttribute ("PacketSize", UintegerValue (pktSize)); clientHelper2.SetAttribute ("DataRate", DataRateValue (DataRate ("100Mbps"))); ApplicationContainer clientApps1; AddressValue remoteAddress (InetSocketAddress (i3i4.GetAddress (1), port)); clientHelper1.SetAttribute ("Remote", remoteAddress); clientApps1.Add (clientHelper1.Install (n0n2.Get (0))); clientApps1.Start (Seconds (client_start_time)); clientApps1.Stop (Seconds (client_stop_time)); ApplicationContainer clientApps2; clientHelper2.SetAttribute ("Remote", remoteAddress); clientApps2.Add (clientHelper2.Install (n1n2.Get (0))); clientApps2.Start (Seconds (client_start_time)); clientApps2.Stop (Seconds (client_stop_time)); Simulator::Stop (Seconds (sink_stop_time)); Simulator::Run (); PieQueueDisc::Stats st = StaticCast<PieQueueDisc> (queueDiscs.Get (0))->GetStats (); NS_TEST_EXPECT_MSG_NE (st.unforcedDrop, 0, "There should be some packets dropped due to prob mark"); NS_TEST_EXPECT_MSG_EQ (st.forcedDrop, 0, "There should be zero packets dropped due to queue limit"); Simulator::Destroy (); } void PieQueueDiscTestCase::DoRun (void) { RunPieTest (StringValue ("QUEUE_MODE_PACKETS")); RunPieTest (StringValue ("QUEUE_MODE_BYTES")); Simulator::Destroy (); } static class PieQueueDiscTestSuite : public TestSuite { public: PieQueueDiscTestSuite () : TestSuite ("pie-queue-disc", UNIT) { AddTestCase (new PieQueueDiscTestCase (), TestCase::QUICK); } } g_pieQueueTestSuite;
e43a6f306b54fa423e3b0cb0296f95c3905b8e9a
bfb1c7ff905065f0e3914b66c9a932bc811640a5
/trunk/source/Prompts/CreditsWindow.h
4b7058d8eb81f6996dd4c6086315e9acf2a07e6b
[]
no_license
djskual/savegame-manager-gx
1ddcdcfcdaf7a4043b7fd756136ec8cca0fbf5f3
ae3cb59cb5bbae91bf65d48cb61961ed49d896d3
refs/heads/master
2020-06-03T05:11:20.735987
2015-04-14T13:16:49
2015-04-14T13:16:49
33,944,551
3
1
null
null
null
null
UTF-8
C++
false
false
1,595
h
CreditsWindow.h
/*************************************************************************** * Copyright (C) 2012 * by Dj_Skual * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * * CreditsWindow.h * * for SaveGame Manager GX 2012 ***************************************************************************/ #ifndef __CREDITSWINDOW_H_ #define __CREDITSWINDOW_H_ #include "../GUI/gui.h" class CreditsWindow : public GuiFrame { public: CreditsWindow(); virtual ~CreditsWindow(); void Update(GuiTrigger * t); sigslot::signal1<CreditsWindow*> Clicked; private: int CreditEntries; int angle; float oldFontScale; GuiImageData * bg; GuiImageData * star; GuiImage * bgImg; GuiImage * starImg; GuiSound * creditsMusic; GuiText * Entrie[24]; }; #endif
88a796560379929ed30fbf3640d2b69d5ce38f4b
825e64b1cb17aac2a4d5c396d7bbeaca91aaaa10
/src/transport/transport.cpp
8259b4f6ad73c837fa4c49575507653721bf044b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cpshereda/hxhim
7cf7643228f44a7ce336bedf05762ad95d5b72bd
1ef69e33d320e629779df27fb36de102f587c829
refs/heads/master
2023-01-29T12:53:21.008388
2020-12-08T19:50:24
2020-12-08T19:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,837
cpp
transport.cpp
#include <cmath> #include "transport/transport.hpp" Transport::EndpointGroup::EndpointGroup() {} Transport::EndpointGroup::~EndpointGroup() {} Transport::Response::BPut * Transport::EndpointGroup::communicate(const ReqList<Request::BPut> &) { return nullptr; } Transport::Response::BGet * Transport::EndpointGroup::communicate(const ReqList<Request::BGet> &) { return nullptr; } Transport::Response::BGetOp * Transport::EndpointGroup::communicate(const ReqList<Request::BGetOp> &) { return nullptr; } Transport::Response::BDelete * Transport::EndpointGroup::communicate(const ReqList<Request::BDelete> &) { return nullptr; } Transport::Response::BHistogram * Transport::EndpointGroup::communicate(const ReqList<Request::BHistogram> &) { return nullptr; } Transport::RangeServer::~RangeServer() {} Transport::Transport::Transport(EndpointGroup *epg, RangeServer *rs) : endpointgroup_(nullptr), rangeserver_(nullptr) { SetEndpointGroup(epg); SetRangeServer(rs); } Transport::Transport::~Transport() { SetRangeServer(nullptr); SetEndpointGroup(nullptr); } /** * SetEndpointGroup * Takes ownership of an endpoint group, deallocating the previous one * * @param eg the endpoint group to take ownership of */ void Transport::Transport::SetEndpointGroup(EndpointGroup *eg) { destruct(endpointgroup_); endpointgroup_ = eg; } /** * SetRangeserver * Takes ownership of a range server, deallocating the previous one * * @param rs the range server to take ownership of */ void Transport::Transport::SetRangeServer(RangeServer *rs) { destruct(rangeserver_); rangeserver_ = rs; } /** * BPut * Bulk Put to multiple endpoints * * @param num_rangesrvs the total number of range servers * @param bpm_list a list of PUT messages going to different servers * @return the response from the range server */ Transport::Response::BPut * Transport::Transport::communicate(const ReqList<Request::BPut> &bpm_list) { return (bpm_list.size() && endpointgroup_)?endpointgroup_->communicate(bpm_list):nullptr; } /** * BGet * Bulk Get to multiple endpoints * * @param num_rangesrvs the total number of range servers * @param bgm_list a list of GET messages going to different servers * @return the response from the range server */ Transport::Response::BGet * Transport::Transport::communicate(const ReqList<Request::BGet> &bgm_list) { return (bgm_list.size() && endpointgroup_)?endpointgroup_->communicate(bgm_list):nullptr; } /** * BGetOp * Bulk Get to multiple endpoints * * @param num_rangesrvs the total number of range servers * @param bgm_list a list of GET messages going to different servers * @return the response from the range server */ Transport::Response::BGetOp * Transport::Transport::communicate(const ReqList<Request::BGetOp> &bgm_list) { return (bgm_list.size() && endpointgroup_)?endpointgroup_->communicate(bgm_list):nullptr; } /** * BDelete * Bulk Delete to multiple endpoints * * @param num_rangesrvs the total number of range servers * @param bdm_list a list of DELETE messages going to different servers * @return the response from the range server */ Transport::Response::BDelete * Transport::Transport::communicate(const ReqList<Request::BDelete> &bdm_list) { return (bdm_list.size() && endpointgroup_)?endpointgroup_->communicate(bdm_list):nullptr; } /** * BHistogram * Bulk Histogram to multiple endpoints * * @param num_rangesrvs the total number of range servers * @param bhm_list a list of HISTOGRAM messages going to different servers * @return the response from the range server */ Transport::Response::BHistogram * Transport::Transport::communicate(const ReqList<Request::BHistogram> &bhm_list) { return (bhm_list.size() && endpointgroup_)?endpointgroup_->communicate(bhm_list):nullptr; }
e48c970c0ba90e6b85c52dbea6801662f129710a
eb588f91afa14ddb027d28cbc883e8e472a076f6
/Bohyoh/chap11/Point2D.h
84913af2887df2e16e6bcdf703c81b022d1ec48f
[]
no_license
kawauso-github/cpp
1ed8193a3d0727e9bdb23d7e86bff4243770a4c4
4076873463846a0a8e8329f2640b11f3cbe676f7
refs/heads/master
2023-05-28T20:36:27.424677
2021-06-07T08:01:22
2021-06-07T08:01:22
374,580,959
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
390
h
Point2D.h
#ifndef ___Point2D #define ___Point2D //--- ๏ผ’ๆฌกๅ…ƒๅบงๆจ™ใ‚ฏใƒฉใ‚น ---// class Point2D { int xp, yp; // ๏ผธๅบงๆจ™ใจ๏ผนๅบงๆจ™ public: Point2D(int x = 0, int y = 0) : xp(x), yp(y) { } int x() const { return xp; } // ๏ผธๅบงๆจ™ int y() const { return yp; } // ๏ผนๅบงๆจ™ void print() const { std::cout << "(" << xp << "," << yp << ")"; } // ่กจ็คบ }; #endif
1fd11229da22f1d85e5185150b61ab4189a0d703
eb58e15feda82c8f3fb6ad6cd57ae3326bfdd2fb
/์ •๋ ฌ/2693 N๋ฒˆ์งธ ํฐ ์ˆ˜.cpp
ca64e516ca5082333eedb527747ac63466e77ac1
[]
no_license
wjb127/Algorithm_Code_Note
8749486ecc855bb5c239fef575e847e7ab340e73
4ac68ca54474b0d2ae2d576e811477d23812457c
refs/heads/master
2022-12-04T04:03:29.229952
2020-08-31T01:47:20
2020-08-31T01:47:20
285,872,122
1
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
2693 N๋ฒˆ์งธ ํฐ ์ˆ˜.cpp
#include<iostream> #include<cstdio> #include<memory.h> #include<algorithm> #include<string> #include<cmath> #include<string> using namespace std; #define f(n) for(int i=0;i<n;i++) #define p(a) cout<<a<<endl int main() { int t; cin>>t; f(t) { int arr[10]; for(int j=0;j<10;j++) { cin>>arr[j]; } sort(arr,arr+10); p(arr[7]); } return 0; }
27831d997b72af2b4faf0fc26cb78db5a8842836
db6b3891c6f872c1c156797ba3e0c0a67a905203
/arangod/VocBase/Legends.cpp
fac7ad8d6858114ad0a0b0e615672ccb0d11c03f
[ "Apache-2.0" ]
permissive
AALEKH/arangodb
119c23a957dc381c7c15d4116c1621cb3b3bbea7
d193c2ff915c749c7838c8225fe6e2c90a324b4d
refs/heads/velocystream
2021-01-09T05:11:06.964249
2016-05-22T18:37:31
2016-05-22T18:37:31
50,135,630
0
0
null
2016-03-03T07:57:14
2016-01-21T20:46:45
C++
UTF-8
C++
false
false
12,598
cpp
Legends.cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Max Neunhoeffer //////////////////////////////////////////////////////////////////////////////// #include "Legends.h" using namespace arangodb; using namespace arangodb::basics; //////////////////////////////////////////////////////////////////////////////// /// Data format of a legend in memory: /// /// Rough overview description: /// /// - attribute-ID table /// - shape table /// - attribute-ID string data /// - padding to achieve 8-byte alignment /// - shape data /// - padding to achieve 8-byte alignment /// /// Description of the attribute-ID table (actual binary types in /// [square brackets]): /// /// - number of entries [TRI_shape_size_t] /// - each entry consists of: /// /// - attribute ID (aid) [TRI_shape_aid_t] /// - offset to string value, measured from the beginning of the legend /// [TRI_shape_size_t] /// /// The entries in the attribute-ID table are sorted by ascending order of /// shape IDs to allow for binary search if needed. /// /// Description of the shape table: /// /// - number of entries [TRI_shape_size_t] /// - each entry consists of: /// /// - shape ID (sid) [TRI_shape_sid_t] /// - offset to shape data, measured from the beginning of the legend /// [TRI_shape_size_t] /// - size in bytes of the shape data for this shape ID [TRI_shape_size_t] /// /// The entries in the shape table are sorted by ascending order of /// shape IDs to allow for binary search if needed. /// /// The strings for the attribute IDs are stored one after another, each /// including a terminating zero byte. At the end of the string data follow /// zero bytes to pad to a total length that is divisible by 8. /// /// The actual entries of the shape data is stored one after another. Alignment /// for each entry is automatically given by the length of the shape data. At /// the end there is padding to make the length of the total legend divisible /// by 8. /// /// Note that the builtin shapes are never dumped and that proper legends /// contain all attribute IDs //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief clear all data to build a new legend, keep shaper //////////////////////////////////////////////////////////////////////////////// void JsonLegend::clear() { _have_attribute.clear(); _attribs.clear(); _att_data.clear(); _have_shape.clear(); _shapes.clear(); _shape_data.clear(); } //////////////////////////////////////////////////////////////////////////////// /// @brief add an attribute ID to the legend //////////////////////////////////////////////////////////////////////////////// int JsonLegend::addAttributeId(TRI_shape_aid_t aid) { auto it = _have_attribute.find(aid); if (it != _have_attribute.end()) { return TRI_ERROR_NO_ERROR; } char const* p = _shaper->lookupAttributeId(aid); if (nullptr == p) { return TRI_ERROR_AID_NOT_FOUND; } _have_attribute.insert(it, aid); size_t len = strlen(p); _attribs.emplace_back(aid, _att_data.length()); _att_data.appendText(p, len + 1); // including the zero byte return TRI_ERROR_NO_ERROR; } //////////////////////////////////////////////////////////////////////////////// /// @brief add a shape to the legend //////////////////////////////////////////////////////////////////////////////// int JsonLegend::addShape(TRI_shape_sid_t sid, char const* data, uint32_t len) { // data and len must always be given, because in general we might have // to sniff recursively into the subobjects. :-( int res = TRI_ERROR_NO_ERROR; TRI_ASSERT(data != nullptr); TRI_shape_t const* shape = nullptr; // First the trivial cases: if (sid < Shaper::firstCustomShapeId()) { shape = Shaper::lookupSidBasicShape(sid); TRI_ASSERT(shape != nullptr); } else { shape = _shaper->lookupShapeId(sid); if (nullptr == shape) { return TRI_ERROR_LEGEND_INCOMPLETE; } auto it = _have_shape.find(sid); if (it == _have_shape.end()) { _have_shape.insert(it, sid); Shape sh(sid, _shape_data.length(), shape->_size); _shapes.push_back(sh); _shape_data.appendText(reinterpret_cast<char const*>(shape), static_cast<size_t>(shape->_size)); } } // Now we have to add all attribute IDs and all shapes used by this // one recursively, note that the data of this object is in a // consistent state, such that we can call ourselves recursively. if (shape->_type == TRI_SHAPE_HOMOGENEOUS_SIZED_LIST) { // Handle a homogeneous list with equal size entries. Note that // this does not imply that no subobject contains any array or // inhomogeneous list, because they could be lists that have the // same size by sheer coincidence. Therefore we have to visit them // all recursively. :-( auto shape_spec = reinterpret_cast<TRI_homogeneous_sized_list_shape_t const*>(shape); auto len = reinterpret_cast<TRI_shape_length_list_t const*>(data); auto ptr = reinterpret_cast<char const*>(len + 1); res = TRI_ERROR_NO_ERROR; // just in case the length is 0 TRI_shape_length_list_t i; for (i = 0; i < *len; i++) { res = addShape(shape_spec->_sidEntry, ptr, static_cast<uint32_t>(shape_spec->_sizeEntry)); ptr += shape_spec->_sizeEntry; if (res != TRI_ERROR_NO_ERROR) { break; } } } else if (shape->_type == TRI_SHAPE_HOMOGENEOUS_LIST) { // Handle a homogeneous list: Only one sid, but the subobjects can // contain inhomogeneous lists. auto shape_spec = reinterpret_cast<TRI_homogeneous_list_shape_t const*>(shape); res = TRI_ERROR_NO_ERROR; // just in case the length is 0 auto len = reinterpret_cast<TRI_shape_length_list_t const*>(data); auto offsets = reinterpret_cast<TRI_shape_size_t const*>(len + 1); TRI_shape_length_list_t i; for (i = 0; i < *len; i++) { res = addShape(shape_spec->_sidEntry, data + offsets[i], static_cast<uint32_t>(offsets[i + 1] - offsets[i])); if (res != TRI_ERROR_NO_ERROR) { break; } } } else if (shape->_type == TRI_SHAPE_LIST) { // Handle an inhomogeneous list: // We have to scan recursively all entries of the list since they // contain sids in the data area. res = TRI_ERROR_NO_ERROR; // just in case the length is 0 auto len = reinterpret_cast<TRI_shape_length_list_t const*>(data); auto sids = reinterpret_cast<TRI_shape_sid_t const*>(len + 1); auto offsets = reinterpret_cast<TRI_shape_size_t const*>(sids + *len); TRI_shape_length_list_t i; for (i = 0; i < *len; i++) { res = addShape(sids[i], data + offsets[i], static_cast<uint32_t>(offsets[i + 1] - offsets[i])); if (res != TRI_ERROR_NO_ERROR) { break; } } } else if (shape->_type == TRI_SHAPE_ARRAY) { // Handle an array: // Distinguish between fixed size subobjects and variable size // subobjects. The fixed ones cannot contain inhomogeneous lists. auto shape_spec = reinterpret_cast<TRI_array_shape_t const*>(shape); auto sids = reinterpret_cast<TRI_shape_sid_t const*>(shape_spec + 1); auto aids = reinterpret_cast<TRI_shape_aid_t const*>( sids + (shape_spec->_fixedEntries + shape_spec->_variableEntries)); auto offsetsF = reinterpret_cast<TRI_shape_size_t const*>( aids + (shape_spec->_fixedEntries + shape_spec->_variableEntries)); auto offsetsV = reinterpret_cast<TRI_shape_size_t const*>(data); TRI_shape_size_t i; for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_fixedEntries + shape_spec->_variableEntries; i++) { res = addAttributeId(aids[i]); } for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_fixedEntries; i++) { // Fixed size subdocs cannot have inhomogeneous lists as subdocs: res = addShape(sids[i], data + offsetsF[i], static_cast<uint32_t>(offsetsF[i + 1] - offsetsF[i])); } for (i = 0; res == TRI_ERROR_NO_ERROR && i < shape_spec->_variableEntries; i++) { addShape(sids[i + shape_spec->_fixedEntries], data + offsetsV[i], static_cast<uint32_t>(offsetsV[i + 1] - offsetsV[i])); } } return res; } //////////////////////////////////////////////////////////////////////////////// /// @brief round a value to the next multiple of 8 //////////////////////////////////////////////////////////////////////////////// static inline TRI_shape_size_t roundup8(TRI_shape_size_t x) { return (x + 7) - ((x + 7) & 7); } //////////////////////////////////////////////////////////////////////////////// /// @brief get the total size in bytes of the legend //////////////////////////////////////////////////////////////////////////////// size_t JsonLegend::getSize() const { // Add string pool size and shape pool size and add space for header // and tables in bytes. return sizeof(TRI_shape_size_t) // number of aids + sizeof(AttributeId) * _attribs.size() // aid entries + sizeof(TRI_shape_size_t) // number of sids + sizeof(Shape) * _shapes.size() // sid entries + static_cast<size_t>( roundup8(_att_data.length())) // string data, padded + static_cast<size_t>( roundup8(_shape_data.length())); // shape data, padded } JsonLegend::AttributeComparerClass JsonLegend::AttributeComparerObject; JsonLegend::ShapeComparerClass JsonLegend::ShapeComparerObject; //////////////////////////////////////////////////////////////////////////////// /// @brief dump the legend to the buffer pointed to by buf //////////////////////////////////////////////////////////////////////////////// void JsonLegend::dump(void* buf) { // Dump the resulting legend to a given buffer. // First sort the aids in ascending order: sort(_attribs.begin(), _attribs.end(), AttributeComparerObject); // Then sort the sids in ascending order: sort(_shapes.begin(), _shapes.end(), ShapeComparerObject); // Total length of table data to add to offsets: TRI_shape_size_t socle = sizeof(TRI_shape_size_t) + sizeof(AttributeId) * _attribs.size() + sizeof(TRI_shape_size_t) + sizeof(Shape) * _shapes.size(); // Attribute ID table: TRI_shape_size_t* p = reinterpret_cast<TRI_shape_size_t*>(buf); *p++ = _attribs.size(); AttributeId* a = reinterpret_cast<AttributeId*>(p); for (size_t i = 0; i < _attribs.size(); i++) { _attribs[i].offset += socle; *a++ = _attribs[i]; _attribs[i].offset -= socle; } // Add the length of the string data to socle for second table: size_t const attDataLength = _att_data.length(); socle += roundup8(attDataLength); // shape table: size_t const n = _shapes.size(); p = reinterpret_cast<TRI_shape_size_t*>(a); *p++ = n; Shape* s = reinterpret_cast<Shape*>(p); for (size_t i = 0; i < n; i++) { _shapes[i].offset += socle; *s++ = _shapes[i]; _shapes[i].offset -= socle; } // Attribute ID string data: char* c = reinterpret_cast<char*>(s); memcpy(c, _att_data.c_str(), attDataLength); TRI_shape_size_t i = roundup8(attDataLength); if (i > attDataLength) { memset(c + attDataLength, 0, static_cast<size_t>(i) - attDataLength); } c += i; // Shape data: size_t const shapeDataLength = _shape_data.length(); memcpy(c, _shape_data.c_str(), shapeDataLength); i = roundup8(shapeDataLength); if (i > shapeDataLength) { memset(c + shapeDataLength, 0, static_cast<size_t>(i) - shapeDataLength); } }
e82d07e6743f53d908b08802386a0d32904e7369
fc0725b0841099b52266012f4d362ddbde7be195
/pixel/pixel/tilemap/tile_map.cpp
7177b2a31494a4e1513babee794bf834dc516fc3
[]
no_license
antiomiae/pixel
6118671c8cb59c12fbc969fdf654ad0d5f6e7afe
377fb8e9e8ebd951c628183d4752b3289735eb92
refs/heads/master
2021-04-27T12:07:25.385742
2019-03-15T03:23:44
2019-03-15T03:23:44
122,574,251
2
0
null
null
null
null
UTF-8
C++
false
false
2,188
cpp
tile_map.cpp
#include <pixel/error.h> #include "tile_map.h" #include "tile_layer.h" using namespace std; using namespace pixel; TileMap::TileMap(const glm::uvec2& map_size, const glm::uvec2& tile_size) : tile_count_{map_size}, tile_size_{tile_size} { atlas_ = make_unique<TileAtlas>(tile_size_.x, tile_size_.y, 4096); } unique_ptr<TileMap> TileMap::from_path(const std::string& tmx_path) { tmx::Map m; error_unless(m.load(tmx_path), "Unable to load tmx map file at path " + tmx_path); auto tm = make_unique<TileMap>( glm::uvec2 {m.getTileCount().x, m.getTileCount().y}, glm::uvec2 {m.getTileSize().x, m.getTileSize().y} ); error_unless(tm->load(m), "Unable to load map into TileMap"); return tm; } bool TileMap::load(const tmx::Map& map) { auto [tw, th] = map.getTileSize(); error_if(tw != tile_size_.x || th != tile_size_.y, "tmx::Map tile size does not match this TileMap's tile size"); auto [x, y] = map.getTileCount(); error_if(x != tile_count_.x || y != tile_count_.y, "tmx::Map map dimensions do not match this TileMap's dimensions"); for (auto& tileset : map.getTilesets()) { atlas_->add_tileset(tileset); tileset_.add_tileset(tileset); } for (auto const& tmx_layer : map.getLayers()) { if (const auto layer = dynamic_cast<tmx::TileLayer*>(tmx_layer.get())) { layers_.emplace_back(this); layers_.back().load(*layer); } } auto bg_color = map.getBackgroundColour(); background_color_ = {bg_color.r / 255.0f, bg_color.g / 255.0f, bg_color.b / 255.0f, bg_color.a / 255.0f}; return true; } TileAtlas& TileMap::atlas() { return *atlas_; } vector<TileLayer>& TileMap::layers() { return layers_; } glm::uvec2 TileMap::tile_count() const { return tile_count_; } glm::uvec2 TileMap::tile_size() const { return tile_size_; } glm::vec4 TileMap::background_color() const { return background_color_; } void TileMap::update(float dt) { for (auto& layer : layers_) { layer.update(dt); } } Tileset& TileMap::tileset() { return tileset_; }
1f14dcbc894a13d5cba859c7815c5f668589ff9b
ea5747614a68a4f3b011a81c6173b12b603881db
/practice/algorithm.cpp
bc231287795e345c9bae783e6774871ff13a9538
[]
no_license
vadik24/Cplusplus
675b2c0066357481df44bb6e0526ba148023318d
6ee754d5ff98a5cbe45c715d79267368c93e08f1
refs/heads/master
2020-05-21T17:49:58.391782
2016-09-25T08:19:13
2016-09-25T08:19:13
61,788,649
0
0
null
null
null
null
UTF-8
C++
false
false
1,897
cpp
algorithm.cpp
#include <iostream> //create a merge sort algorithm //divide array into subarray left & right //conquer two leaf child //combine two subarray into one // divide/conquer is O(logN), Merge two array into one O(N) so O(nlogN) void mergeSort(int *array,int l, int r); void combine(int *array,int l,int m,int r); int main(){ int array[] = {7,4,3}; int length = sizeof(array)/sizeof(array[0]); mergeSort(array,0,length-1); for(int i=0;i<length;i++){ std::cout<< array[i]<<std::endl; } return 0; } //sort the array //element l-left r-right of array void mergeSort(int* array,int l,int r){ //check if it leaf problem else do subproblem if(array == 0 || r-l==0){ return; } int length = (r-l)/2; //left mergeSort(array,l,length); //right mergeSort(array,length+1,r); //hit end subproblem,conquer combine(array,l,length/2,r); } void combine(int *array,int l,int m, int r){ int leftArray[m-l]; int rightArray[r-m+1]; //add front-mid subarray to temp left array for(int i=0;i<=m-l;i++){ leftArray[i]=array[l+i]; } //add front-mid subarray to temp left array for(int i=0;i<=r-m+1;i++){ rightArray[i]=array[m+i+1]; } int x=0; int y=0; int i; for(int i=0;i<3;i++){ std::cout<< array[i]<<std::endl; } for(i=l;i<(r-l);i++){ if(leftArray[x]<rightArray[y]){ array[i]=leftArray[x++]; //protect overflow if(x==(m-l+1)){ break; } } else{ array[i]=rightArray[y++]; //protect overflow if(y ==(r-m)){ break; } } } std::cout <<"test1"<<std::endl; //if hit break then collect all leftArray or rightArray while(y<(r-m+1)){ array[i++] = rightArray[y++]; } std::cout <<"test2"<<std::endl; while(x<(m-l)){ array[i++] = leftArray[x++]; } for(int i=0;i<3;i++){ std::cout<< array[i]<<std::endl; } std::cout <<"test3"<<std::endl; }
239cb40d5cb5cba00e7c195f4055a7a7088d6b02
20e4681ed78d4b9d255ac169599aa5c93f65c0c0
/day4/io/io.cc
c3926df5b67fa31cd3ce748eb6b944ad50993902
[]
no_license
a719309405/wangdao_cpp
4cef1f277ac24fd84b50f65adcd79903957d2410
8bdba79419eb578316b12e9713a1186593431be5
refs/heads/master
2020-06-26T14:50:24.149337
2019-08-05T15:04:06
2019-08-05T15:04:06
199,664,163
1
0
null
null
null
null
UTF-8
C++
false
false
273
cc
io.cc
#include<iostream> #include<vector> #include<istream> #include<ostream> #include<fstream> using std::cout; using std::endl; using std::ifstream; int main() { ifstream isf; isf.open("test.txt"); if(!isf.good()) { cout<<"cant open"<<endl; } }
05d294ada59b8536675aff5bb54a7fde2e1c34ac
ed375380b4eb9d572dc837bb2b9899b230152392
/lazy4_deprecated_internal_FunctorUtility.h
b0e4c41e7dcfa1e06036c321f9902e1a1d47a89e
[]
no_license
fdt1/collection
53ad8bd14265a4d7640cee6a241b952dd0001b9e
2b7eb8860dcd856a6d46561478532b5b09872c4c
refs/heads/master
2021-01-19T20:19:04.220488
2015-12-20T14:25:44
2015-12-20T14:25:44
37,906,930
0
0
null
null
null
null
UTF-8
C++
false
false
5,245
h
lazy4_deprecated_internal_FunctorUtility.h
/* * lazy4_internal_FunctorUtility.h * collection * * Created by Francois et Fabienne on 24/09/13. * Copyright 2013 __MyCompanyName__. All rights reserved. * */ #pragma once #include "lazy4_internal_Type.h" namespace lazy4 { namespace internal { //-------------------------------------------------------------------------------- //! @class Implementation class is the pointer version of any lazy object //-------------------------------------------------------------------------------- template <typename output_template, typename input_template> struct FunctorUtility { public: typedef typename internal::Type<output_template>::type output_type; typedef typename internal::Type<output_template>::const_type const_output_type; typedef typename internal::Type<input_template>::parameter_type parameter_input_type; public: //! @return the output of the functor template <typename bridge_template> static output_type getOutput(bridge_template& bridge, parameter_input_type input) { return (output_type) (bridge.getImplementation()->getConstOutput((typename bridge_template::interface_type::parameter_input_type) (input))); } //! @return the output of the functor template <typename bridge_template> static inline const_output_type getConstOutput(const bridge_template& bridge, parameter_input_type input) { return (const_output_type) (bridge.getImplementation()->getConstOutput((typename bridge_template::interface_type::parameter_input_type) (input))); } }; //-------------------------------------------------------------------------------- //! @class Implementation class is the pointer version of any lazy object //-------------------------------------------------------------------------------- template <typename input_template> struct FunctorUtility<void, input_template> { typedef void output_template; typedef typename internal::Type<output_template>::type output_type; typedef typename internal::Type<output_template>::const_type const_output_type; typedef typename internal::Type<input_template>::parameter_type parameter_input_type; public: //! @return the content template <typename bridge_template> static output_type getOutput(bridge_template& bridge, parameter_input_type input) { static output_type output = NULL; return output; } //! @return the content template <typename bridge_template> static inline const_output_type getConstOutput(const bridge_template& bridge, parameter_input_type input) { static output_type output = NULL; return output; } }; //-------------------------------------------------------------------------------- //! @class Implementation class is the pointer version of any lazy object //-------------------------------------------------------------------------------- template <typename output_template, typename input_template> struct FunctorUtility<output_template&, input_template> { typedef typename internal::Type<output_template&>::type output_type; typedef typename internal::Type<output_template&>::const_type const_output_type; typedef typename internal::Type<input_template>::parameter_type parameter_input_type; public: //! @return the output of the functor template <typename bridge_template> static output_type getOutput(bridge_template& bridge, parameter_input_type input) { return (output_type) (bridge.getUniqueImplementation()->getOutput((typename bridge_template::interface_type::parameter_input_type) (input))); } //! @return the output of the functor template <typename bridge_template> static inline const_output_type getConstOutput(const bridge_template& bridge, parameter_input_type input) { return (const_output_type) (bridge.getImplementation()->getConstOutput((typename bridge_template::interface_type::parameter_input_type) (input))); } }; //-------------------------------------------------------------------------------- //! @class Implementation class is the pointer version of any lazy object //-------------------------------------------------------------------------------- template <typename output_template, typename input_template> struct FunctorUtility<const output_template&, input_template> { typedef typename internal::Type<const output_template&>::type output_type; typedef typename internal::Type<const output_template&>::const_type const_output_type; typedef typename internal::Type<input_template>::parameter_type parameter_input_type; public: //! @return the output of the functor template <typename bridge_template> static output_type getOutput(bridge_template& bridge, parameter_input_type input) { return (output_type) (bridge.getImplementation()->getConstOutput((typename bridge_template::interface_type::parameter_input_type) (input))); } //! @return the output of the functor template <typename bridge_template> static inline const_output_type getConstOutput(const bridge_template& bridge, parameter_input_type input) { return (const_output_type) (bridge.getImplementation()->getConstOutput((typename bridge_template::interface_type::parameter_input_type) (input))); } }; } // namespace internal } // namespace lazy4
196cae81e3c7af71673e87a2c9634796512b4fe2
ad1c5bedb6807cdaaa9fb75d98ef71b6410c430a
/src/clargs/clargs.cpp
26bc3b2a7e15cab8a122e66dccdd688e920b53f3
[]
no_license
GeniusChinez/enact
757b75b323e4f6c5c45776ed4ce2203fcb5d9968
35779964293743385ad44f30546e9f6055626e56
refs/heads/master
2023-03-06T04:14:12.824190
2021-02-23T07:18:59
2021-02-23T07:18:59
340,893,073
0
0
null
null
null
null
UTF-8
C++
false
false
4,169
cpp
clargs.cpp
#pragma once #include "clargs.h" #include <iostream> namespace clargs { bool Arguments::is_set(std::string_view flag_name) const { auto temp = key_values.find(flag_name.data()); if (temp == key_values.end()) { return false; } return temp->second == "true"; } const std::vector<std::string>& Arguments::get_naked_values() const { return naked_values; } void Arguments::clear() { naked_values.clear(); key_values.clear(); } void Arguments::parse( std::size_t number_of_arguments, char* const arguments[] ) { clear(); std::size_t source_position = 0; auto read_name = [&](auto& iter, const auto& end) { std::string name; if ((iter != end) && std::isalpha(*iter)) { do { name += *iter++; } while ( (iter != end) && (std::isalnum(*iter) || *iter == '_' || *iter == '-') ); } return name; }; while (source_position < number_of_arguments) { std::string item = arguments[source_position]; auto item_iter = std::begin(item); if (*item_iter++ != '-') { naked_values.push_back(std::move(item)); source_position++; continue; } if (item_iter == std::end(item)) { report_error(source_position, "expected '-' or alphabet"); } std::string name; std::string value; const auto there_is_a_name = [&] { return name.size() > 0; }; const auto report_error_if_there_is_no_name = [&](auto... args) { if (!there_is_a_name()) { report_error(std::forward<decltype(args)>(args)...); } }; auto read_required_name = [&](auto...args) { name = read_name(item_iter, std::end(item)); report_error_if_there_is_no_name( std::forward<decltype(args)>(args)... ); }; auto read_key_value_pair = [&] { item_iter++; read_required_name( source_position, "expected a name after '--'" ); value = "true"; source_position++; }; auto read_flag = [&] { read_required_name( source_position, "expected a name after '-'" ); if ((source_position + 1) >= number_of_arguments) { report_error( source_position, "expected a value after -", name ); } value = std::string(arguments[++source_position]); source_position++; }; if (*item_iter == '-') { read_key_value_pair(); } else { read_flag(); } key_values[std::move(name)] = std::move(value); } } const std::optional<std::string_view> Arguments::get_value_of( const std::string& name ) const { if (auto temp = key_values.find(name); temp != key_values.end() ) { return temp->second; } return std::nullopt; } template <typename ...Args> void Arguments::report_error(std::size_t position, Args&&... args) { std::cout << "error: in argument " << (position + 1) << ": "; (std::cout << ... << args); std::cout << "\n"; exit(position + 1); } void Arguments::remove_first_naked_value() { naked_values.erase(naked_values.begin()); } Arguments get_arguments(std::size_t number_of, char* const source[]) { Arguments arguments; arguments.parse(number_of, source); return arguments; } }
685cc865fe20c605b05c4bfeed4a7e6a38368b2c
e333cb74142dcdd04d1f85f67fe44e9b7b7e4eaa
/test/Station_tests.hpp
e115c203acd442df0b1570b32baa9be7e1de1779
[]
no_license
LarsFin/TrainStopPlus
5cddd350fe5f762425dd750b61316576c65170c7
5dd9dc0d1472de53bb3fad679f64adebb3d47833
refs/heads/master
2020-07-05T01:47:37.820291
2019-09-16T17:51:22
2019-09-16T17:51:22
202,486,964
0
0
null
null
null
null
UTF-8
C++
false
false
4,670
hpp
Station_tests.hpp
#define Station_tests_H #include "../src/Station.cpp" #include "iostream" using namespace std; using namespace fakeit; // Overload station builds for name set and not Station* BuildStation(); Station* BuildStation(string name); // Deallocate heap pointer void DeallocateStationPtr(Station* stationPtr); //############################################################################// // Station Tests //############################################################################// TEST_CASE( "Station is instantiated with passed name", "[Station]" ) { string expectedName("Waterloo"); Station* stationPtr = BuildStation(expectedName); REQUIRE( stationPtr->GetName() == expectedName ); DeallocateStationPtr(stationPtr); } TEST_CASE( "Station is instantiated with list of train pointers", "[GetTrainPtrs]" ) { Station* stationPtr = BuildStation(); list<ITrain*>* expectedTypePtr = new list<ITrain*>; REQUIRE( typeid(stationPtr->GetTrainPtrs()) == typeid(expectedTypePtr) ); delete expectedTypePtr; DeallocateStationPtr(stationPtr); } TEST_CASE( "Station can receive train", "[ReceiveTrain]" ) { Station* stationPtr = BuildStation(); Mock<ITrain> mock; When(Method(mock,IsMoving)).Return(true); Fake(Method(mock,SetIsMoving)); ITrain* mockTrainPtr = &(mock.get()); REQUIRE( stationPtr->GetTrainPtrs()->empty() ); // Station is empty stationPtr->ReceiveTrain(mockTrainPtr); REQUIRE( stationPtr->GetTrainPtrs()->size() == 1 ); // Station is not empty with 1 train REQUIRE( stationPtr->GetTrainPtrs()->front() == mockTrainPtr ); // Train in station is the one which was passed DeallocateStationPtr(stationPtr); } TEST_CASE( "Station cannot receive non moving train", "[ReceiveTrain]" ) { Station* stationPtr = BuildStation(); Mock<ITrain> mock; When(Method(mock,IsMoving)).Return(false); ITrain* mockTrainPtr = &(mock.get()); REQUIRE_THROWS_WITH( stationPtr->ReceiveTrain(mockTrainPtr), "Station cannot receive stationary train" ); REQUIRE( stationPtr->GetTrainPtrs()->empty() ); DeallocateStationPtr(stationPtr); } TEST_CASE( "Trains received by station should be stopped", "[ReceiveTrain]" ) { Station* stationPtr = BuildStation(); Mock<ITrain> mock; When(Method(mock,IsMoving)).Return(true); Fake(Method(mock,SetIsMoving)); ITrain* mockTrainPtr = &(mock.get()); stationPtr->ReceiveTrain(mockTrainPtr); Verify(Method(mock,SetIsMoving).Using(false)).Once(); DeallocateStationPtr(stationPtr); } TEST_CASE( "Trains can leave stations", "[ReleaseTrain]" ) { Station* stationPtr = BuildStation(); string mockTrainName = "mock-train"; Mock<ITrain> mock; When(Method(mock,IsMoving)).Return(true); Fake(Method(mock,SetIsMoving)); ITrain* mockTrainPtr = &(mock.get()); stationPtr->ReceiveTrain(mockTrainPtr); REQUIRE( stationPtr->GetTrainPtrs()->size() == 1 ); When(Method(mock,IsMoving)).Return(false); When(Method(mock,GetName)).Return(mockTrainName); ITrain* releasedTrain = stationPtr->ReleaseTrain(mockTrainName); REQUIRE( stationPtr->GetTrainPtrs()->empty() ); REQUIRE( releasedTrain == mockTrainPtr ); DeallocateStationPtr(stationPtr); } TEST_CASE( "Cannot release trains which aren't at the station", "[ReleaseTrain]" ) { Station* stationPtr = BuildStation(); string nonExistantTrainName = "non-existant-train"; stringstream ss; ss << "The train " << nonExistantTrainName << " does not exist within the station"; REQUIRE_THROWS_WITH( stationPtr->ReleaseTrain(nonExistantTrainName), ss.str() ); DeallocateStationPtr(stationPtr); } TEST_CASE( "Trains which depart from Stations should begin their journey", "[ReleaseTrain]" ) { Station* stationPtr = BuildStation(); string mockTrainName = "mock-train"; Mock<ITrain> mock; When(Method(mock,IsMoving)).Return(true); Fake(Method(mock,SetIsMoving)); ITrain* mockTrainPtr = &(mock.get()); stationPtr->ReceiveTrain(mockTrainPtr); REQUIRE( stationPtr->GetTrainPtrs()->size() == 1 ); When(Method(mock,IsMoving)).Return(false); When(Method(mock,GetName)).Return(mockTrainName); stationPtr->ReleaseTrain(mockTrainName); Verify(Method(mock,SetIsMoving).Using(true)).Once(); DeallocateStationPtr(stationPtr); } //############################################################################// // Using name "default" Station* BuildStation() { Station* stationPtr = new Station("default"); return stationPtr; } // Using passed name Station* BuildStation(string name) { Station* stationPtr = new Station(name); return stationPtr; } // Deallocate Station pointer void DeallocateStationPtr(Station* stationPtr) { delete stationPtr; stationPtr = nullptr; }
e892ae9e57e66acdc6bf613914c1afafc68c8402
4fb0945481de32fc150a1084268b2e2f46671d2e
/util.h
7f536efa10ffa64391c13180f2cdeddd931a50aa
[]
no_license
StevenChenZJU/myshell
7d11b53cd11085118ec0d32fc367b3fea6f2a9cb
0c3f56f50e097813de4ffbcbffe9b02d09d2e659
refs/heads/master
2023-07-09T00:11:57.271711
2021-08-04T16:57:42
2021-08-04T16:57:42
325,023,878
1
0
null
null
null
null
UTF-8
C++
false
false
1,961
h
util.h
#ifndef _UTIL_H_ #define _UTIL_H_ #include <algorithm> #include <iostream> #include <fstream> #include <iomanip> #include <stdlib.h> #include <string> #include <sstream> #include <map> #include <vector> #include <regex> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include <linux/limits.h> #include <ctime> #include <dirent.h> #define RT_SUCCESS 0 #define RT_ERROR 1 #define RT_ESCAPE 255 #define PAGER "${PAGER:-more}" typedef int RTCODE; typedef RTCODE (*FUNCTION_TYPE)(std::vector<std::string> &); // ๅŽๅฐ่ฟ›็จ‹็Šถๆ€ enum JobStatus { Stopped, Running, Done }; // ๅŽๅฐ่ฟ›็จ‹ไฟกๆฏ struct Job { static int max_id; int id; // idๅท,้€ๆญฅ้€’ๅขž pid_t pgid; // ๆ‰€ๅœจ่ฟ›็จ‹็ป„็ผ–ๅท JobStatus status; // ็Šถๆ€ std::string command; // ๆŒ‡ไปค Job(pid_t pgid, std::string command) : pgid(pgid), status(Stopped), command(command), id(++max_id) {} // ่ฝฌๆขไธบๅญ—็ฌฆไธฒ่พ“ๅ‡บ std::string toString() { return "[" + std::to_string(id) + "]\t" + std::to_string(pgid) + "\t" + std::string(status ? "Running" : "Stopped") + "\t\t" + command; } }; // ๅ…จๅฑ€ๅ˜้‡ๅฃฐๆ˜Ž extern RTCODE LAST_RETURN; // $? for shell extern int UMASK; extern pid_t ROOT_PGID; extern std::map<std::string, std::string> VAR; extern std::vector<std::string> ARGS; extern std::vector<Job> JOBS; // ๅ‡ฝๆ•ฐๅฃฐๆ˜Ž void SigIgnore(); void SigDefault(); void ExitShell(int rtcode); int GetUmask(); bool isNumber(std::string s); bool isDir(std::string path); void ShiftN(int N); void ProcessComment(std::string& s); void Trim(std::string& s); std::string ParseQuote(std::string input); std::string ReplacingVar(std::string input); std::vector<std::string> Parse(std::string input, char delim = ' '); std::string GetAbsolutePath(std::string relativePath); std::string GetRelativePath(std::string absolutePath); bool isVariableAssignment(std::string str); void AssignVar(std::string str); #endif
bce9f083ad7ea3e09ce0d9a10c75536b17ce4c7e
64bbf6b400b6e26724ae2ba49ddcb3d0bde36a2c
/ex00/easyfind.hpp
4d37e3fde093314723a8128bdf3a0e903680ab16
[]
no_license
HyoungHoKim/cpp_module_08
9f3a1b7261096ba8baa4a26b7569b37c0fc6d60f
170c2416ea230740844db6a8e2aa1ff7307369f9
refs/heads/master
2023-06-27T16:27:40.507025
2021-07-29T07:29:26
2021-07-29T07:29:26
390,235,418
0
0
null
null
null
null
UTF-8
C++
false
false
423
hpp
easyfind.hpp
#ifndef EASYFIND_HPP # define EASYFIND_HPP # include <algorithm> # include <exception> class NotFound : public std::exception { virtual const char *what() const throw() { return ("Not Found!!!"); } }; template <typename T> int &easyfind(T &container, int n) { typename T::iterator iter = std::find(container.begin(), container.end(), n); if (iter == container.end()) throw NotFound(); return (*iter); } #endif
b591707decc3080868c7c619ce2585e09df6041c
e5c00909d5aeb971793526289bb74ed0939e31d0
/libleveldb/src/main/cpp/leveldb/cpp/leveldb.hpp
c8b33b451afcae629ed6a1187e13d175c384c3bb
[ "Apache-2.0" ]
permissive
joinAero/DroidDjinni
f43eecc1a76ab632458ea1b4890809bb9bcc8da0
97dcec53079154ce8f98781badcc2eacd08098e7
refs/heads/master
2021-08-26T07:09:27.667534
2017-11-22T05:22:51
2017-11-22T05:22:51
107,755,392
1
0
null
null
null
null
UTF-8
C++
false
false
794
hpp
leveldb.hpp
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from leveldb.idl #pragma once #include <memory> #include <string> namespace dd { class WriteBatch; enum class status; class Leveldb { public: virtual ~Leveldb() {} static std::shared_ptr<Leveldb> create(); virtual status open(const std::string & name) = 0; virtual std::string get(const std::string & key) = 0; virtual std::string get_def(const std::string & key, const std::string & def) = 0; virtual status put(const std::string & key, const std::string & value) = 0; virtual status del(const std::string & key) = 0; virtual status write(const std::shared_ptr<WriteBatch> & batch) = 0; virtual status close() = 0; virtual status result() = 0; }; } // namespace dd
9a821cffc21932a5f03bde8a6f2b8db96de85c88
c9782973026db99124d2a1db97be6eb447a5d578
/lab3_Eigenface/code/pro3/mean.h
8719dec9e5a8eda40612247a7008cbb3e1ed0a8b
[]
no_license
zouwen198317/CVpg
c78e1dd13b30e12d79de62ec0b204693a6a82b75
da8ba93d58037edf592ced3a4af5a6c3bd6802e7
refs/heads/master
2021-01-21T01:27:03.641828
2016-02-20T00:47:31
2016-02-20T00:47:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
mean.h
// // mean.h // pro3 // // Created by Victor Young on 12/31/15. // Copyright (c) 2015 Victor Young. All rights reserved. // #ifndef pro3_mean_h #define pro3_mean_h #include "eigenface.h" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv; void test2(); void Text(Mat img, string text, int x, int y); int query(Mat target,eigenFace ef); Mat CropFace(Mat image, Point eye_left , Point eye_right, Point2f offset_pct, Point dest_sz); #endif
27f3e1077d8dd136e9872847d85257ce10b28ffb
a269f85bd94d43122f7d8000582d9000a3491186
/src/persistent_structures/comp_increasing_array.cpp
afc35d50574789a26acac0940367279a5da3c461
[ "BSD-2-Clause" ]
permissive
ufal/korektor
462265249bdc1f64689f341defd49f24ab160564
9dba14b97babfe201e016926d4029bbff2cd1b4f
refs/heads/master
2023-06-19T19:02:05.915989
2023-02-22T13:59:39
2023-02-22T13:59:39
22,339,583
19
5
null
2017-11-13T07:29:15
2014-07-28T10:56:25
C++
UTF-8
C++
false
false
2,815
cpp
comp_increasing_array.cpp
// This file is part of korektor <http://github.com/ufal/korektor/>. // // Copyright 2015 by Institute of Formal and Applied Linguistics, Faculty // of Mathematics and Physics, Charles University in Prague, Czech Republic. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under 3-clause BSD licence. #include "comp_increasing_array.h" #include "increasing_array.h" #include "utils/io.h" namespace ufal { namespace korektor { /// @brief Write the data structure to output stream /// /// @param ofs Output stream void CompIncreasingArray::WriteToStream(ostream &ofs) const { IO::WriteString(ofs, "CIA"); uint32_t num_parts = mia_vec.size(); ofs.write((char*)&num_parts, sizeof(uint32_t)); ofs.write((char*)&log2_size_of_parts, sizeof(uint32_t)); ofs.write((char*)&num_values, sizeof(uint32_t)); ofs.write((char*)&last_val_last_index, sizeof(uint32_t)); for (uint32_t i = 0; i < mia_vec.size(); i++) { mia_vec[i]->WriteToStream(ofs); } } /// @brief Constructor initialization from input stream/file /// /// @param Input stream CompIncreasingArray::CompIncreasingArray(istream &ifs) { if (IO::ReadString(ifs) != "CIA") runtime_failure("Cannot load CompIncreasingArray, file is corrupted!"); uint32_t num_parts; ifs.read((char*)&num_parts, sizeof(uint32_t)); ifs.read((char*)&log2_size_of_parts, sizeof(uint32_t)); ifs.read((char*)&num_values, sizeof(uint32_t)); ifs.read((char*)&last_val_last_index, sizeof(uint32_t)); for (uint32_t i = 0; i < num_parts; i++) { mia_vec.push_back(IncreasingArrayP(new IncreasingArray(ifs))); } bit_mask = (1 << log2_size_of_parts) - 1; } /// @brief Divide the large sequence of unsigned integers into small groups and store them /// individually in IncreasingArray data structure. /// /// @param val Vector of increasing integer array /// @param _last_val_last_index - /// @todo The variable _last_val_last_index is not used CompIncreasingArray::CompIncreasingArray(vector<uint32_t> &val, uint32_t _last_val_last_index) { num_values = val.size(); log2_size_of_parts = 12; bit_mask = (1 << log2_size_of_parts) - 1; uint32_t first = 0; uint32_t last = bit_mask < val.size() - 1 ? bit_mask : val.size() - 1; while (first < num_values) { vector<uint32_t> part; for (uint32_t i = first; i <= last; i++) part.push_back(val[i]); mia_vec.push_back(IncreasingArrayP(new IncreasingArray(part))); first += 1 << log2_size_of_parts; last += 1 << log2_size_of_parts; if (last >= num_values) last = num_values - 1; } for (uint32_t i = 0; i < num_values; i++) { assert(val[i] == GetValueAt(i)); } last_val_last_index = _last_val_last_index; } } // namespace korektor } // namespace ufal
263e0038e6c46d05fecfa9ae088ea5928ac2b9a9
d4f649ea461523f10a432d71c348fa29917af44e
/circle-3.1/src/util/delobjs.c
cc2061976c1d9909d12235424cfe5a0291513736
[ "BSD-2-Clause", "MIT" ]
permissive
mdbarr/circlemud
742c2eda3c020daa22475e509eaebfea8f885c11
e5c7013fc8af466ddcfd27b381b8f813434795c8
refs/heads/master
2021-07-21T10:50:33.936240
2020-06-09T18:56:12
2020-06-09T19:01:46
181,250,852
1
2
MIT
2020-06-09T19:01:48
2019-04-14T02:28:05
C
UTF-8
C++
false
false
2,228
c
delobjs.c
/* ************************************************************************ * file: delobjs.c Part of CircleMud * * Usage: deleting object files for players who are not in the playerfile * * Written by Jeremy Elson 4/2/93 * * All Rights Reserved * * Copyright (C) 1993 The Trustees of The Johns Hopkins University * ************************************************************************* */ /* I recommend you use the script in the lib/plrobjs directory instead of invoking this program directly; however, you can use this program thusly: usage: switch into an obj directory; type: delobjs <plrfile> <obj wildcard> */ #include "conf.h" #include "sysdep.h" #include "structs.h" #include "utils.h" struct name_element { char name[20]; struct name_element *next; }; struct name_element *name_list = 0; void do_purge(int argc, char **argv) { int x; struct name_element *tmp; char name[1024]; int found; for (x = 2; x < argc; x++) { found = 0; strcpy(name, argv[x]); *(strchr(name, '.')) = '\0'; for (tmp = name_list; !found && tmp; tmp = tmp->next) if (!strcmp(tmp->name, name)) found = 1; if (!found) { remove(argv[x]); printf("Deleting %s\n", argv[x]); } } } int main(int argc, char **argv) { char *ptr; struct char_file_u player; int okay; struct name_element *tmp; FILE *fl; if (argc < 3) { printf("Usage: %s <playerfile-name> <file1> <file2> ... <filen>\n", argv[0]); exit(1); } if (!(fl = fopen(argv[1], "rb"))) { perror("Unable to open playerfile for reading"); exit(1); } while (1) { fread(&player, sizeof(player), 1, fl); if (feof(fl)) { fclose(fl); do_purge(argc, argv); exit(0); } okay = 1; for (ptr = player.name; *ptr; ptr++) *ptr = LOWER(*ptr); if (player.char_specials_saved.act & PLR_DELETED) okay = 0; if (okay) { tmp = (struct name_element *) malloc(sizeof(struct name_element)); tmp->next = name_list; strcpy(tmp->name, player.name); name_list = tmp; } } }
c6fa7bfd1ea2db33acade4e1e912ae37a0c184fe
7cc6f918e77fd9a9c1eea02a1f27965f5d3dce70
/507-Zodic-Fever.cpp
f86ac2458b1cb20f88dd9865c60e44130c27a7c4
[]
no_license
metalhacker/CityU-OJ
1fc2c6c2c513e3f9e17ef522cc56739b25f8d87e
b593a0b20aead5e11014de5924e405b59d679223
refs/heads/master
2023-08-01T00:40:57.117814
2021-09-12T01:54:06
2021-09-12T01:54:06
153,863,349
0
0
null
null
null
null
UTF-8
C++
false
false
3,170
cpp
507-Zodic-Fever.cpp
#include <iostream> #include <cstring> #include <algorithm> #include <string> #include <vector> #include <sstream> #include <queue> #include <cstdlib> #include <cctype> #include <stack> #include <climits> #include <map> #include <utility> #define INF 99999999 using namespace std; class Trap { public: int room_number; char trap_type; int trap_value; Trap() { room_number = 0; trap_type = 'n'; trap_value = 0; } Trap(int a, char b, int c) { room_number = a; trap_type = b; trap_value = c; } }; class Vertex { public: int point; int distance; int rvalue; Vertex(int a, int b, int c) { point = a; distance = b; rvalue = c; } bool operator < (const Vertex &another) const { return distance > another.distance; } }; class Edge { public: int room_number; int distance; bool operator < (const Edge &another) const { if (room_number != another.room_number) return room_number < another.room_number; return distance < another.distance; } }; Trap traps[1005]; vector<Edge> G[1005]; int total_number_of_rooms, number_of_corridors, number_of_traps, room_number_of_entrance, initial_ring_position, room_number_of_treasure_room, open_ring_position; int ring(int r) { int res = r % 12; if (res <= 0) res += 12; return res; } int calc(int id, int r) { if (traps[id].trap_type == '+') return ring(r + traps[id].trap_value); else if (traps[id].trap_type == '-') return ring(r - traps[id].trap_value); else if (traps[id].trap_type == '*') return ring(r * traps[id].trap_value); else if (traps[id].trap_type == '=') return ring(traps[id].trap_value); else return ring(r); } int main() { while (cin >> total_number_of_rooms >> number_of_corridors >> number_of_traps >> room_number_of_entrance >> initial_ring_position >> room_number_of_treasure_room >> open_ring_position) { for (int i = 0; i < 1005; i++) { traps[i] = { 0,'n',0 }; G[i].clear(); } int r1, r2, cv; char tempc; for (int i = 0; i < number_of_corridors; i++) { cin >> r1 >> r2 >> cv; G[r1].push_back({ r2, cv }); G[r2].push_back({ r1, cv }); } for (int i = 0; i < number_of_traps; i++) { cin >> r1 >> tempc >> cv; traps[r1] = { r1,tempc,cv }; } bool isopen = 0; map<Edge, int> mmp; priority_queue<Vertex>pq; pq.push({ room_number_of_entrance,0,initial_ring_position }); while (!pq.empty()) { Vertex vertex = pq.top(); pq.pop(); int tnode = vertex.point, tdis = vertex.distance, tvalue = vertex.rvalue; int nnode, ndis, nvalue; //next if (tnode == room_number_of_treasure_room && tvalue == open_ring_position) { cout << tdis << endl; isopen = 1; break; } for (int i = 0; i < G[tnode].size(); i++) { nnode = G[tnode][i].room_number; ndis = G[tnode][i].distance; nvalue = calc(nnode, tvalue); if (mmp.find({nnode,nvalue}) == mmp.end()) { pq.push({ nnode,ndis + tdis,nvalue }); mmp[{nnode,nvalue}] = ndis + tdis; } else if (mmp[{nnode,nvalue}] > ndis + tdis) { pq.push({ nnode, ndis + tdis, nvalue }); mmp[G[tnode][i]] = ndis + tdis; } } } if (!isopen) { cout << "Pray!" << endl; } } return 0; }
417f7129f848216e14c6173817b085c7d8ed5e33
3ac6e094b06aa2f8548ef8795f8dfd22b7b744e3
/include/Model/StateMachine/StateMachine.hpp
9269ceb197adf2abe72f2ebeee0c78be1ddd783d
[]
no_license
SpencerL-Y/ISADT
5f9c70acc1203edce0fae24e1ea715c2d4085b2c
dcbc5eb027a2dd394a060f3b5109109ff80fd52a
refs/heads/master
2022-11-10T15:31:17.879174
2020-06-21T10:37:45
2020-06-21T10:37:45
260,142,077
0
0
null
null
null
null
UTF-8
C++
false
false
1,143
hpp
StateMachine.hpp
// // StateMachine.hpp // // Created by Jinlong He on 2019/11/14. // Copyright ยฉ 2019 All rights reserved. // #ifndef Model_StateMachine_hpp #define Model_StateMachine_hpp #include <list> #include "Vertex.hpp" #include "Edge.hpp" using std::string; namespace isadt { class Process; /// \brief StateMachine class class StateMachine { public: StateMachine(); StateMachine(Process* p); ~StateMachine(); void mkStartVertex(std::string name); Vertex* getVertexByName(std::string name); const Vertex* getStartVertex(); const std::list<Vertex *>& getVertices() const; const std::list<Edge*>& getEdges() const; void addVertex(std::string name); void delVertex(std::string name); void addEdge(Edge* edge); private: std::list<Vertex*> vertices_; //< the set of the states of this fsm. std::list<Edge*> edges_; //< the set of the transitions of this fsm. Vertex* startVertex_; //< record the start state of this fsm. list<Vertex*> endVertices_; Process* process_; //< the StateMachine belongs to the process. }; } #endif /* Model_StateMachine_hpp */
105c3e1c548aef7f3d6d228865828b0c1be0fdc6
8f72438d5f4ca7219df3ae7799c3282faab5e33e
/Guide to CP/Introductory Problems/05. Permutations.cpp
ec939ea4b16b839401bece098395a01ece9aa6d7
[]
no_license
mdzobayer/Problem-Solving
01eda863ef2f1e80aedcdc59bbaa48bcaeef9430
a5b129b6817d9ec7648150f01325d9dcad282aed
refs/heads/master
2022-08-15T22:04:18.161409
2022-08-08T11:46:00
2022-08-08T11:46:00
165,687,520
0
1
null
null
null
null
UTF-8
C++
false
false
847
cpp
05. Permutations.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, loop, first, second; cin >> n; if (n == 2 || n == 3) { cout << "NO SOLUTION" << endl; return (0); } else if (n == 1) { cout << "1" << endl; return (0); } else if (n == 4) { cout << "3 1 4 2" << endl; return (0); } if (n % 2 == 0) { loop = n / 2; -- loop; first = (n / 2) + 1; second = 2; } else { loop = n / 2; first = (n / 2) + 2; second = 2; } while(loop > 0) { cout << first << " " << second << " "; first ++; second ++; --loop; } if (n % 2 == 0) { cout << first << " 1" << endl; } else { cout << 1 << endl; } return (0); }