hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
5bd1c4c60b0a518115e14cce3ff262dcad624695
1,005
cpp
C++
examples/make_stereo_panorama.cpp
jonathanventura/spherical-sfm
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
[ "MIT" ]
6
2020-03-26T15:07:14.000Z
2022-02-04T06:27:32.000Z
examples/make_stereo_panorama.cpp
jonathanventura/spherical-sfm
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
[ "MIT" ]
1
2020-07-09T06:32:52.000Z
2020-07-09T07:26:47.000Z
examples/make_stereo_panorama.cpp
jonathanventura/spherical-sfm
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
[ "MIT" ]
1
2022-03-08T20:30:46.000Z
2022-03-08T20:30:46.000Z
#include <iostream> #include <vector> #include <cmath> #include <fstream> #include <gflags/gflags.h> #include "stereo_panorama_tools.h" using namespace sphericalsfm; using namespace stereopanotools; DEFINE_string(intrinsics, "", "Path to intrinsics (focal centerx centery)"); DEFINE_string(video, "", "Path to video or image search pattern like frame%06d.png"); DEFINE_string(output, "", "Path to output directory"); DEFINE_int32(width, 8192, "Width of output panorama"); DEFINE_bool(loop, true, "Trajectory is a closed loop"); int main( int argc, char **argv ) { gflags::ParseCommandLineFlags(&argc, &argv, true); double focal, centerx, centery; std::ifstream intrinsicsf( FLAGS_intrinsics ); intrinsicsf >> focal >> centerx >> centery; std::cout << "intrinsics : " << focal << ", " << centerx << ", " << centery << "\n"; Intrinsics intrinsics(focal,centerx,centery); make_stereo_panoramas( intrinsics, FLAGS_video, FLAGS_output, FLAGS_width, FLAGS_loop ); }
30.454545
92
0.705473
5bd4623cc9a5404f3652cce6bd2ce9c8e03da0f5
617
cpp
C++
2017/APP5/Q.7.cpp
HemensonDavid/Estudando-C
fb5a33b399b369dce789bf77c06834da71fe0a4d
[ "MIT" ]
null
null
null
2017/APP5/Q.7.cpp
HemensonDavid/Estudando-C
fb5a33b399b369dce789bf77c06834da71fe0a4d
[ "MIT" ]
null
null
null
2017/APP5/Q.7.cpp
HemensonDavid/Estudando-C
fb5a33b399b369dce789bf77c06834da71fe0a4d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int ismedia(int nota1, int nota2, int nota3, int nota4){ int media=(nota1*2)+(nota2*2)+(nota3*3)+(nota4*3)/10; if(media>=60){ return 1; } } int main(){ cout<<"Digite sua nota no 1 bimestre: "; int nota1; cin>> nota1; cout<<"Digite sua nota no 2 bimestre: "; int nota2; cin>> nota2; cout<<"Digite sua nota no 3 bimestre: "; int nota3; cin>> nota3; cout<<"Digite sua nota no 4 bimestre: "; int nota4; cin>> nota4; if(ismedia(nota1,nota2,nota3,nota4)==1){ cout<<"Voce nao passou. "<<endl; }else{ cout<<"voce passou :) "<<endl; } //hemenson }
16.675676
56
0.628849
5bd6994380e19f199c9e9f98d6d356ea80f44954
3,721
hpp
C++
include/tcb_manager.hpp
Qanora/mstack-cpp
a1b6de6983404558e46b87d0e81da715fcdccd55
[ "MIT" ]
15
2020-07-20T12:32:38.000Z
2022-03-24T19:24:02.000Z
include/tcb_manager.hpp
Qanora/mstack-cpp
a1b6de6983404558e46b87d0e81da715fcdccd55
[ "MIT" ]
null
null
null
include/tcb_manager.hpp
Qanora/mstack-cpp
a1b6de6983404558e46b87d0e81da715fcdccd55
[ "MIT" ]
5
2020-07-20T12:42:58.000Z
2021-01-16T10:13:39.000Z
#pragma once #include <memory> #include <optional> #include <unordered_map> #include <unordered_set> #include "circle_buffer.hpp" #include "defination.hpp" #include "packets.hpp" #include "socket.hpp" #include "tcb.hpp" #include "tcp_transmit.hpp" namespace mstack { class tcb_manager { private: tcb_manager() : active_tcbs(std::make_shared<circle_buffer<std::shared_ptr<tcb_t>>>()) {} ~tcb_manager() = default; std::shared_ptr<circle_buffer<std::shared_ptr<tcb_t>>> active_tcbs; std::unordered_map<two_ends_t, std::shared_ptr<tcb_t>> tcbs; std::unordered_set<ipv4_port_t> active_ports; std::unordered_map<ipv4_port_t, std::shared_ptr<listener_t>> listeners; public: tcb_manager(const tcb_manager&) = delete; tcb_manager(tcb_manager&&) = delete; tcb_manager& operator=(const tcb_manager&) = delete; tcb_manager& operator=(tcb_manager&&) = delete; static tcb_manager& instance() { static tcb_manager instance; return instance; } public: int id() { return 0x06; } std::optional<tcp_packet_t> gather_packet() { while (!active_tcbs->empty()) { std::optional<std::shared_ptr<tcb_t>> tcb = active_tcbs->pop_front(); if (!tcb) continue; std::optional<tcp_packet_t> tcp_packet = tcb.value()->gather_packet(); if (tcp_packet) return tcp_packet; } return std::nullopt; } void listen_port(ipv4_port_t ipv4_port, std::shared_ptr<listener_t> listener) { this->listeners[ipv4_port] = listener; active_ports.insert(ipv4_port); } void register_tcb( two_ends_t& two_end, std::optional<std::shared_ptr<circle_buffer<std::shared_ptr<tcb_t>>>> listener) { DLOG(INFO) << "[REGISTER TCB] " << two_end; if (!two_end.remote_info || !two_end.local_info) { DLOG(FATAL) << "[EMPTY TCB]"; } std::shared_ptr<tcb_t> tcb = std::make_shared<tcb_t>(this->active_tcbs, listener, two_end.remote_info.value(), two_end.local_info.value()); tcbs[two_end] = tcb; } void receive(tcp_packet_t in_packet) { two_ends_t two_end = {.remote_info = in_packet.remote_info, .local_info = in_packet.local_info}; if (tcbs.find(two_end) != tcbs.end()) { tcp_transmit::tcp_in(tcbs[two_end], in_packet); } else if (active_ports.find(in_packet.local_info.value()) != active_ports.end()) { register_tcb(two_end, this->listeners[in_packet.local_info.value()]->acceptors); if (tcbs.find(two_end) != tcbs.end()) { tcbs[two_end]->state = TCP_LISTEN; tcbs[two_end]->next_state = TCP_LISTEN; tcp_transmit::tcp_in(tcbs[two_end], in_packet); } else { DLOG(ERROR) << "[REGISTER TCB FAIL]"; } } else { DLOG(ERROR) << "[RECEIVE UNKNOWN TCP PACKET]"; } } }; } // namespace mstack
43.267442
99
0.504703
5bdd86a3c1457620c62c505b2444d4cdcf64f68e
4,666
hpp
C++
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Exception #include "System/Exception.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: SerializationInfo class SerializationInfo; } // Completed forward declares // Type namespace: System.Runtime.CompilerServices namespace System::Runtime::CompilerServices { // Size: 0x90 #pragma pack(push, 1) // Autogenerated type: System.Runtime.CompilerServices.RuntimeWrappedException class RuntimeWrappedException : public System::Exception { public: // private System.Object m_wrappedException // Size: 0x8 // Offset: 0x88 ::Il2CppObject* m_wrappedException; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // Creating value type constructor for type: RuntimeWrappedException RuntimeWrappedException(::Il2CppObject* m_wrappedException_ = {}) noexcept : m_wrappedException{m_wrappedException_} {} // Creating conversion operator: operator ::Il2CppObject* constexpr operator ::Il2CppObject*() const noexcept { return m_wrappedException; } // private System.Void .ctor(System.Object thrownObject) // Offset: 0x1401DE0 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeWrappedException* New_ctor(::Il2CppObject* thrownObject) { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>(thrownObject))); } // public override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x1401E90 // Implemented from: System.Exception // Base method: System.Void Exception::GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) void GetObjectData(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context); // System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x1401F9C // Implemented from: System.Exception // Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeWrappedException* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>(info, context))); } // System.Void .ctor() // Offset: 0x1402090 // Implemented from: System.Exception // Base method: System.Void Exception::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeWrappedException* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>())); } }; // System.Runtime.CompilerServices.RuntimeWrappedException #pragma pack(pop) static check_size<sizeof(RuntimeWrappedException), 136 + sizeof(::Il2CppObject*)> __System_Runtime_CompilerServices_RuntimeWrappedExceptionSizeCheck; static_assert(sizeof(RuntimeWrappedException) == 0x90); } DEFINE_IL2CPP_ARG_TYPE(System::Runtime::CompilerServices::RuntimeWrappedException*, "System.Runtime.CompilerServices", "RuntimeWrappedException");
60.597403
165
0.747964
5be030ae46f3c7267b32ffaa56e54e1ce0567db1
9,157
cxx
C++
Dax/LowLevelDax/threshold.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
9
2015-01-10T04:31:50.000Z
2019-03-04T13:55:08.000Z
Dax/LowLevelDax/threshold.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
2
2016-10-19T12:56:47.000Z
2017-06-02T13:55:35.000Z
Dax/LowLevelDax/threshold.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
5
2015-01-05T15:52:50.000Z
2018-02-14T18:08:19.000Z
//Description: //Show how we can threshold any arbitrary dataset inside of dax. #include <dax/cont/DeviceAdapter.h> #include <dax/cont/ArrayHandle.h> #include <dax/cont/ArrayHandleCounting.h> #include <dax/cont/UniformGrid.h> #include <dax/cont/UnstructuredGrid.h> #include <dax/CellTag.h> #include <dax/CellTraits.h> //headers needed for testing #include <dax/cont/testing/TestingGridGenerator.h> //exec headers we need #include <dax/exec/internal/WorkletBase.h> //required for error handling #include <dax/exec/CellVertices.h> #include <algorithm> #include <iostream> #include <numeric> #include <vector> //The functor used to determine if a single cell passes the threshold reqs template<class GridType, class T> struct threshold_cell : public dax::exec::internal::WorkletBase { //we inherit from WorkletBase so that we can throw errors in the exec //env and the control env can find out why the worklet failed //store the cell type that we are working on typedef typename GridType::CellTag CellTag; //determine the topology type that we need in the exec env typedef typename GridType::TopologyStructConstExecution TopologyType; TopologyType Topology; //holds the cell connectivity //hold a portal so that we can get values in the exec env typedef typename dax::cont::ArrayHandle< T >::PortalConstExecution PortalType; PortalType ValuePortal; //holds the array of of what cells pass or fail the threshold reqs typedef typename dax::cont::ArrayHandle< int >::PortalExecution OutPortalType; OutPortalType PassesThreshold; T MinValue; T MaxValue; DAX_CONT_EXPORT threshold_cell(const GridType& grid, dax::cont::ArrayHandle<T> values, T min, T max, dax::cont::ArrayHandle<int> passes): Topology(grid.PrepareForInput()), //upload grid topology to exec env ValuePortal(values.PrepareForInput()), //upload values to exec env MinValue(min), MaxValue(max), PassesThreshold(passes.PrepareForOutput( grid.GetNumberOfCells() )) { } DAX_EXEC_EXPORT void operator()( int cell_index ) const { //get all the point ids for the cell index dax::exec::CellVertices<CellTag> verts = this->Topology.GetCellConnections(cell_index); //for each vertice see if we are between the min and max which is //inclusive on both sides. We hint to the compiler that this is //a fixed size array by using NUM_VERTICES. This can be easily //unrolled if needed int valid = 1; for(int i=0; i < dax::CellTraits<CellTag>::NUM_VERTICES; ++i) { const T value = this->ValuePortal.Get( verts[i] ); valid &= (value >= this->MinValue && value <= this->MaxValue); } this->PassesThreshold.Set(cell_index,valid); } }; //this struct will do the cell sub-setting by being given the input topology //and the cell ids that need to be added to the new output grid template<class GridType, class OutGridType > struct cell_subset: public dax::exec::internal::WorkletBase { //we inherit from WorkletBase so that we can throw errors in the exec //env and the control env can find out why the worklet failed //store the cell type that we are working on typedef typename GridType::CellTag CellTag; //determine the topology type for the input grid typedef typename GridType::TopologyStructConstExecution InTopologyType; InTopologyType InputTopology; //holds the input cell connectivity //determine the topology type for the output grid typedef typename OutGridType::TopologyStructExecution OutTopologyType; OutTopologyType OutputTopology; //holds the output cell connectivity typedef typename dax::cont::ArrayHandle< int >::PortalConstExecution PortalType; PortalType PermutationPortal; DAX_CONT_EXPORT cell_subset(const GridType& grid, OutGridType& outGrid, dax::cont::ArrayHandle<int> permutationIndices): InputTopology(grid.PrepareForInput()), OutputTopology(outGrid.PrepareForOutput( permutationIndices.GetNumberOfValues())), PermutationPortal(permutationIndices.PrepareForInput()) { } DAX_EXEC_EXPORT void operator()( const int index ) const { //map index to original cell id const int cell_index = PermutationPortal.Get(index); dax::exec::CellVertices<CellTag> verts = this->InputTopology.GetCellConnections(cell_index); const int offset = dax::CellTraits<CellTag>::NUM_VERTICES * index; for(int i=0; i < dax::CellTraits<CellTag>::NUM_VERTICES; ++i) { this->OutputTopology.CellConnections.Set(offset+i,verts[i]); } } }; template<class GridType ,class T> void ThresholdExample(GridType grid, std::vector<T> &array, T minValue, T maxValue) { const int numCells = grid.GetNumberOfCells(); //find the default device adapter typedef DAX_DEFAULT_DEVICE_ADAPTER_TAG AdapterTag; //Make it easy to call the DeviceAdapter with the right tag typedef dax::cont::DeviceAdapterAlgorithm<AdapterTag> DeviceAdapter; //make a handle to the std::vector, this actually doesn't copy any memory //but waits for something to call PrepareForInput or PrepareForOutput before //moving the memory to cuda/tbb if required dax::cont::ArrayHandle<T> arrayHandle = dax::cont::make_ArrayHandle(array); //schedule the thresholding on a per cell basis dax::cont::ArrayHandle<int> passesThreshold; threshold_cell<GridType,T> tc(grid, arrayHandle, minValue, maxValue, passesThreshold); DeviceAdapter::Schedule( tc, numCells ); dax::cont::ArrayHandle<int> onlyGoodCellIds; const dax::Id numNewCells = DeviceAdapter::ScanInclusive( passesThreshold, onlyGoodCellIds ); dax::cont::ArrayHandle<int> cellUpperBounds; DeviceAdapter::UpperBounds( onlyGoodCellIds, dax::cont::make_ArrayHandleCounting(0,numNewCells), cellUpperBounds ); //now that we have the good cell ids only //lets extract the topology for those cells by calling cell_subset //first step is to find the cell type for the output grid. Since //the input grid can be any cell type, we need to find the //CanonicalCellTag for the cell type to determine what kind of cell //it will be in an unstructured grid typedef dax::CellTraits<typename GridType::CellTag> CellTraits; typedef typename CellTraits::CanonicalCellTag OutCellType; typedef dax::cont::ArrayContainerControlTagBasic CellContainerTag; //the second step is to copy the grid point coordinates in full //as we are doing cell sub-setting really. The first step is to //get the container tag type from the input point coordinates typedef typename GridType::PointCoordinatesType PointCoordsArrayHandle; typedef typename PointCoordsArrayHandle::ArrayContainerControlTag PointContainerTag; //now determine the out unstructured grid type typedef dax::cont::UnstructuredGrid<OutCellType, CellContainerTag, PointContainerTag> OutGridType; OutGridType outGrid; outGrid.SetPointCoordinates(grid.GetPointCoordinates()); //now time to do the actual cell sub-setting //since we are doing a cell sub-set we don't need to find the subset //of the property that we thresholded on cell_subset<GridType,OutGridType> cs(grid,outGrid,cellUpperBounds); DeviceAdapter::Schedule(cs,cellUpperBounds.GetNumberOfValues()); std::cout << "Input Grid number of cells: " << numCells << std::endl; std::cout << "Output Grid number of cells: " << outGrid.GetNumberOfCells() << std::endl; }; //helper class so we can test on all grid types struct TestOnAllGridTypes { template<typename GridType> DAX_CONT_EXPORT void operator()(const GridType&) const { //grid size is 4*4*4 cells dax::cont::testing::TestGrid<GridType> grid(4); std::vector<float> data_store(5*5*5); //fill the vector with random numbers std::srand(42); //I like this seed :-) std::generate(data_store.begin(),data_store.end(),std::rand); const float sum = std::accumulate(data_store.begin(),data_store.end(),0.0f); const float average = sum / static_cast<float>(data_store.size()); const float max = *(std::max_element(data_store.begin(),data_store.end())); //use the average as the min boundary so we get only a subset ThresholdExample(grid.GetRealGrid(),data_store,average,max); } }; int main(int, char**) { //load up a uniform grid and point based array and threshold //this is a basic example of using the Threshold dax::cont::UniformGrid<> grid; grid.SetExtent( dax::Id3(0,0,0), dax::Id3(4,4,4) ); //use an array which every value will pass std::vector<float> data_store(5*5*5,25); float min=0, max=100; ThresholdExample(grid,data_store,min,max); //next we are going to use the dax testing infastructure to pump this //example through every grid structure and cell type. //so that we show we can threshold voxels, triangles, wedges, verts, etc dax::cont::testing::GridTesting::TryAllGridTypes(TestOnAllGridTypes()); }
36.7751
90
0.719668
5be09ff0afe0e481f52fc2c48e30d71f5aa1fbc0
1,185
cpp
C++
testMain.cpp
chuanstudyup/GPSM8N
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
[ "Apache-2.0" ]
1
2022-03-28T13:57:20.000Z
2022-03-28T13:57:20.000Z
testMain.cpp
chuanstudyup/GPSM8N
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
[ "Apache-2.0" ]
null
null
null
testMain.cpp
chuanstudyup/GPSM8N
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
[ "Apache-2.0" ]
null
null
null
// testMain.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // g++ GPS.cpp testMain.cpp -o testMain /* NMEA examples $GNRMC,083712.40,A,3030.83159,N,11424.56558,E,0.150,,291221,,,A*65\r\n $GNRMC,083712.60,A,3030.83159,N,11424.56559,E,0.157,,291221,,,A*61\r\n $GNRMC,083712.80,A,3030.83158,N,11424.56558,E,0.033,,291221,,,A*6C\r\n $GNGGA,083712.80,3030.83158,N,11424.56558,E,1,10,1.00,49.7,M,-10.6,M,,*5B\r\n */ #include <iostream> #include <math.h> #include "GPS.h" using std::cout; using std::endl; int main() { char buf0[200] = "$GNRMC,083708.20,A,3030."; char buf1[200] = "83171,N,11424.56579,E,0.094,,291221,,,A*68\r\n$GNGGA,0"; char buf2[200] = "83712.80,3030.83158,N,11424.56558,E,1"; char buf3[200] = ",10,1.00,49.7,M,-10.6,M,,*5B\r\n"; GPS gps; gps.parseNAME(buf0); gps.parseNAME(buf1); gps.parseNAME(buf2); gps.parseNAME(buf3); cout <<"Lat:"<< gps.lat << endl; cout <<"Lng:"<< gps.lon << endl; cout <<"Velocity:"<< gps.velocity << endl; cout <<"Course:"<< gps.course << endl; cout << "SVs:" << static_cast<int>(gps.SVs) << endl; cout << "Altitude:" << gps.altitude << endl; cout << "HDOP:" << gps.HDOP << endl; return 0; }
29.625
78
0.61519
5be0ae2694bfc8d46a7a0329e74bc69410ee79cc
1,156
cpp
C++
android-31/android/icu/util/ULocale_Category.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/icu/util/ULocale_Category.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/icu/util/ULocale_Category.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JArray.hpp" #include "../../../JString.hpp" #include "./ULocale_Category.hpp" namespace android::icu::util { // Fields android::icu::util::ULocale_Category ULocale_Category::DISPLAY() { return getStaticObjectField( "android.icu.util.ULocale$Category", "DISPLAY", "Landroid/icu/util/ULocale$Category;" ); } android::icu::util::ULocale_Category ULocale_Category::FORMAT() { return getStaticObjectField( "android.icu.util.ULocale$Category", "FORMAT", "Landroid/icu/util/ULocale$Category;" ); } // QJniObject forward ULocale_Category::ULocale_Category(QJniObject obj) : java::lang::Enum(obj) {} // Constructors // Methods android::icu::util::ULocale_Category ULocale_Category::valueOf(JString arg0) { return callStaticObjectMethod( "android.icu.util.ULocale$Category", "valueOf", "(Ljava/lang/String;)Landroid/icu/util/ULocale$Category;", arg0.object<jstring>() ); } JArray ULocale_Category::values() { return callStaticObjectMethod( "android.icu.util.ULocale$Category", "values", "()[Landroid/icu/util/ULocale$Category;" ); } } // namespace android::icu::util
23.12
78
0.697232
5be406b3951e569d1d65d9f0d519775ff52015e3
1,168
cpp
C++
code/components/conhost-v2/src/DrawFPS.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
null
null
null
code/components/conhost-v2/src/DrawFPS.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
null
null
null
code/components/conhost-v2/src/DrawFPS.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
null
null
null
#include "StdInc.h" #include <ConsoleHost.h> #include <imgui.h> #include <CoreConsole.h> #include "FpsTracker.h" static InitFunction initFunction([]() { static bool drawFpsEnabled; static bool streamingListEnabled; static bool streamingMemoryEnabled; static ConVar<bool> drawFps("cl_drawFPS", ConVar_Archive, false, &drawFpsEnabled); ConHost::OnShouldDrawGui.Connect([](bool* should) { *should = *should || drawFpsEnabled; }); ConHost::OnDrawGui.Connect([]() { if (!drawFpsEnabled) { return; } auto& io = ImGui::GetIO(); static FpsTracker fpsTracker; fpsTracker.Tick(); ImGui::SetNextWindowBgAlpha(0.0f); ImGui::SetNextWindowPos(ImVec2(ImGui::GetMainViewport()->Pos.x + 10, ImGui::GetMainViewport()->Pos.y + 10), 0, ImVec2(0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); if (ImGui::Begin("DrawFps", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) { if (fpsTracker.CanGet()) { ImGui::Text("%llufps", fpsTracker.Get()); } } ImGui::PopStyleVar(); ImGui::End(); }); });
22.901961
186
0.710616
5be4b1c6a414d33b6af76f4904a7e05f7c281c00
56
hpp
C++
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/preprocessed/bcc551/bitor.hpp>
28
55
0.803571
5be9cdbd51e0b4addd5637585abfd4f1db2ec933
769
cpp
C++
12-10-21/balanced_binary_tree.cpp
ahanavish/GDSC-DSA-Interview-Preparation
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
[ "MIT" ]
null
null
null
12-10-21/balanced_binary_tree.cpp
ahanavish/GDSC-DSA-Interview-Preparation
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
[ "MIT" ]
null
null
null
12-10-21/balanced_binary_tree.cpp
ahanavish/GDSC-DSA-Interview-Preparation
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
[ "MIT" ]
1
2021-11-29T06:10:48.000Z
2021-11-29T06:10:48.000Z
// https://leetcode.com/problems/balanced-binary-tree/ class Solution { public: bool isBalanced(TreeNode *root) { vector<int> ans; int h = is(root, ans); if (check(ans)) return true; else return false; } bool check(vector<int> &ans) { for (int i = 0; i < ans.size(); i++) { if (ans[i] - ans[i + 1] > 1 || ans[i + 1] - ans[i] > 1) return false; i++; } return true; } int is(TreeNode *node, vector<int> &ans) { if (!node) return 0; int l = is(node->left, ans), r = is(node->right, ans); ans.push_back(l); ans.push_back(r); return max(l, r) + 1; } };
19.717949
67
0.443433
5beadd1842d02dfee23f1bd4393c91e0d0bee8e1
2,370
cpp
C++
qt-creator-opensource-src-4.6.1/src/tools/screenshotcropper/cropimageview.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/tools/screenshotcropper/cropimageview.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/tools/screenshotcropper/cropimageview.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "cropimageview.h" #include <QPainter> #include <QMouseEvent> CropImageView::CropImageView(QWidget *parent) : QWidget(parent) { } void CropImageView::mousePressEvent(QMouseEvent *event) { setArea(QRect(event->pos(), m_area.bottomRight())); update(); } void CropImageView::mouseMoveEvent(QMouseEvent *event) { setArea(QRect(m_area.topLeft(), event->pos())); update(); } void CropImageView::mouseReleaseEvent(QMouseEvent *event) { mouseMoveEvent(event); } void CropImageView::setImage(const QImage &image) { m_image = image; setMinimumSize(image.size()); update(); } void CropImageView::setArea(const QRect &area) { m_area = m_image.rect().intersected(area); emit cropAreaChanged(m_area); update(); } void CropImageView::paintEvent(QPaintEvent *event) { Q_UNUSED(event) QPainter p(this); if (!m_image.isNull()) p.drawImage(0, 0, m_image); if (!m_area.isNull()) { p.setPen(Qt::white); p.drawRect(m_area); QPen redDashes; redDashes.setColor(Qt::red); redDashes.setStyle(Qt::DashLine); p.setPen(redDashes); p.drawRect(m_area); } }
27.882353
77
0.659494
5bec9814ab09dd8bd09eb94fab72070f1ee18118
4,071
hpp
C++
src/libraries/thermophysicalModels/specie/reaction/reactionRate/thirdBodyEfficiencies/thirdBodyEfficiencies.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/thermophysicalModels/specie/reaction/reactionRate/thirdBodyEfficiencies/thirdBodyEfficiencies.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/thermophysicalModels/specie/reaction/reactionRate/thirdBodyEfficiencies/thirdBodyEfficiencies.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2018 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::thirdBodyEfficiencies Description Third body efficiencies \*---------------------------------------------------------------------------*/ #ifndef thirdBodyEfficiencies_HPP #define thirdBodyEfficiencies_HPP #include "scalarList.hpp" #include "speciesTable.hpp" #include "Tuple2.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of friend functions and operators class thirdBodyEfficiencies; Ostream& operator<<(Ostream&, const thirdBodyEfficiencies&); /*---------------------------------------------------------------------------*\ Class thirdBodyEfficiencies Declaration \*---------------------------------------------------------------------------*/ class thirdBodyEfficiencies : public scalarList { const speciesTable& species_; public: //- Construct from components inline thirdBodyEfficiencies ( const speciesTable& species, const scalarList& efficiencies ) : scalarList(efficiencies), species_(species) { if (size() != species_.size()) { FatalErrorInFunction << "number of efficiencies = " << size() << " is not equal to the number of species " << species_.size() << exit(FatalError); } } //- Construct from dictionary inline thirdBodyEfficiencies ( const speciesTable& species, const dictionary& dict ) : scalarList(species.size()), species_(species) { if (dict.found("coeffs")) { List<Tuple2<word, scalar> > coeffs(dict.lookup("coeffs")); if (coeffs.size() != species_.size()) { FatalErrorInFunction << "number of efficiencies = " << coeffs.size() << " is not equat to the number of species " << species_.size() << exit(FatalIOError); } forAll(coeffs, i) { operator[](species[coeffs[i].first()]) = coeffs[i].second(); } } else { scalar defaultEff = readScalar(dict.lookup("defaultEfficiency")); scalarList::operator=(defaultEff); } } // Member functions //- Calculate and return M, the concentration of the third-bodies inline scalar M(const scalarList& c) const { scalar M = 0; forAll(*this, i) { M += operator[](i)*c[i]; } return M; } //- Write to stream inline void write(Ostream& os) const { List<Tuple2<word, scalar> > coeffs(species_.size()); forAll(coeffs, i) { coeffs[i].first() = species_[i]; coeffs[i].second() = operator[](i); } os.writeKeyword("coeffs") << coeffs << token::END_STATEMENT << nl; } // Ostream Operator friend Ostream& operator<< ( Ostream& os, const thirdBodyEfficiencies& tbes ) { tbes.write(os); return os; } }; } // End namespace CML #endif
25.12963
83
0.517809
5beeb662e275ac7b93836be860aee060f93fdb61
233
cpp
C++
codes/moderncpp/strtol/strtol02/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
3
2022-01-25T07:33:43.000Z
2022-03-30T10:25:09.000Z
codes/moderncpp/strtol/strtol02/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
null
null
null
codes/moderncpp/strtol/strtol02/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
2
2022-01-17T13:39:12.000Z
2022-03-30T10:25:12.000Z
#include <iostream> int main ( int argc, char **argv ) { { if ( argc > 1 ) { long i = strtol( argv[1], NULL, 0 ); std::cout << " i = " << i << std::endl; } } return 0; }
15.533333
52
0.377682
5bf1be12a66207f9e5154926b9760b12e52a5f0c
3,920
cpp
C++
src/tnl/t_vb_points.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
src/tnl/t_vb_points.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
src/tnl/t_vb_points.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
/* $Id: t_vb_points.c,v 1.10 2002/10/29 20:29:04 brianp Exp $ */ /* * Mesa 3-D graphics library * Version: 4.1 * * Copyright (C) 1999-2002 Brian Paul All Rights Reserved. * * 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 * BRIAN PAUL 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. * * Authors: * Brian Paul */ #include "mtypes.h" #include "imports.h" #include "t_context.h" #include "t_pipeline.h" struct point_stage_data { GLvector4f PointSize; }; #define POINT_STAGE_DATA(stage) ((struct point_stage_data *)stage->privatePtr) /* * Compute attenuated point sizes */ static GLboolean run_point_stage( GLcontext *ctx, struct gl_pipeline_stage *stage ) { struct point_stage_data *store = POINT_STAGE_DATA(stage); struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; const GLfloat (*eye)[4] = (const GLfloat (*)[4]) VB->EyePtr->data; const GLfloat p0 = ctx->Point.Params[0]; const GLfloat p1 = ctx->Point.Params[1]; const GLfloat p2 = ctx->Point.Params[2]; const GLfloat pointSize = ctx->Point._Size; GLfloat (*size)[4] = store->PointSize.data; GLuint i; if (stage->changed_inputs) { /* XXX do threshold and min/max clamping here? */ for (i = 0; i < VB->Count; i++) { const GLfloat dist = -eye[i][2]; /* GLfloat dist = GL_SQRT(pos[0]*pos[0]+pos[1]*pos[1]+pos[2]*pos[2]);*/ size[i][0] = pointSize / (p0 + dist * (p1 + dist * p2)); } } VB->PointSizePtr = &store->PointSize; return GL_TRUE; } /* If point size attenuation is on we'll compute the point size for * each vertex in a special pipeline stage. */ static void check_point_size( GLcontext *ctx, struct gl_pipeline_stage *d ) { d->active = ctx->Point._Attenuated && !ctx->VertexProgram.Enabled; } static GLboolean alloc_point_data( GLcontext *ctx, struct gl_pipeline_stage *stage ) { struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; struct point_stage_data *store; stage->privatePtr = MALLOC(sizeof(*store)); store = POINT_STAGE_DATA(stage); if (!store) return GL_FALSE; _mesa_vector4f_alloc( &store->PointSize, 0, VB->Size, 32 ); /* Now run the stage. */ stage->run = run_point_stage; return stage->run( ctx, stage ); } static void free_point_data( struct gl_pipeline_stage *stage ) { struct point_stage_data *store = POINT_STAGE_DATA(stage); if (store) { _mesa_vector4f_free( &store->PointSize ); FREE( store ); stage->privatePtr = 0; } } const struct gl_pipeline_stage _tnl_point_attenuation_stage = { "point size attenuation", /* name */ _NEW_POINT, /* build_state_change */ _NEW_POINT, /* run_state_change */ GL_FALSE, /* active */ VERT_BIT_EYE, /* inputs */ VERT_BIT_POINT_SIZE, /* outputs */ 0, /* changed_inputs (temporary value) */ NULL, /* stage private data */ free_point_data, /* destructor */ check_point_size, /* check */ alloc_point_data /* run -- initially set to alloc data */ };
31.36
78
0.688265
5bf4a1b12bd0ba842830ce713cef0b21e2e0da15
799
cpp
C++
learncpp.com/11_Inheritance/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
learncpp.com/11_Inheritance/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
learncpp.com/11_Inheritance/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
/** * Chapter 11 :: Question 3 * * Fighting with a monster * use almost everything learned by bar * * KoaLaYT 23:15 04/02/2020 * */ #include "Player.h" #include <iostream> #include <string> Player initPlayer() { std::cout << "Enter you name: "; std::string name{}; std::getline(std::cin, name); std::cout << "Welcome, " << name << '\n'; return Player{name}; } int main() { Player p{initPlayer()}; while (!(p.hasWon() || p.isDead())) { p.fightMonster(); } if (p.hasWon()) { std::cout << "You won! And you have " << p.getGold() << " golds!\n"; } if (p.isDead()) { std::cout << "You died at level " << p.getLevel() << " and with " << p.getGold() << " gold.\n"; std::cout << "Too bad you can't take it with you!\n"; } return 0; }
19.02381
72
0.544431
5bf54790d03dad868eb1e1f926a2969a61ad40ca
12,838
hpp
C++
key/key.hpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
5
2019-12-27T07:30:03.000Z
2020-10-13T01:08:55.000Z
key/key.hpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
null
null
null
key/key.hpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
1
2020-07-27T22:36:40.000Z
2020-07-27T22:36:40.000Z
/* -------------------------------------------------------------------------------- key/key.hpp copyright(C) kyuhyun park 1993.07.13 -------------------------------------------------------------------------------- */ #ifdef def_key_key_hpp #error 'key/key.hpp' duplicated. #endif #define def_key_key_hpp #ifndef def_pub_config_hpp #include <pub/config.hpp> #endif /* -------------------------------------------------------------------------------- shift keys -------------------------------------------------------------------------------- */ #define def_key_rshift 0x0100 #define def_key_lshift 0x0101 #define def_key_rctrl 0x0102 #define def_key_lctrl 0x0103 #define def_key_ralt 0x0104 #define def_key_lalt 0x0105 #define def_key_rmachine 0x0106 #define def_key_lmachine 0x0107 #define def_key_num_lock 0x0108 #define def_key_caps_lock 0x0109 /* -------------------------------------------------------------------------------- character keys -------------------------------------------------------------------------------- */ #define def_key_a00 0x0200 #define def_key_a01 0x0201 #define def_key_a02 0x0202 #define def_key_a03 0x0203 #define def_key_a04 0x0204 #define def_key_a05 0x0205 #define def_key_a06 0x0206 #define def_key_a07 0x0207 #define def_key_a08 0x0208 #define def_key_a09 0x0209 #define def_key_a10 0x020a #define def_key_a11 0x020b #define def_key_a12 0x020c #define def_key_a13 0x020d #define def_key_a14 0x020e #define def_key_a15 0x020f #define def_key_b00 0x0220 #define def_key_b01 0x0221 #define def_key_b02 0x0222 #define def_key_b03 0x0223 #define def_key_b04 0x0224 #define def_key_b05 0x0225 #define def_key_b06 0x0226 #define def_key_b07 0x0227 #define def_key_b08 0x0228 #define def_key_b09 0x0229 #define def_key_b10 0x022a #define def_key_b11 0x022b #define def_key_b12 0x022c #define def_key_b13 0x022d #define def_key_b14 0x022e #define def_key_b15 0x022f #define def_key_c00 0x0240 #define def_key_c01 0x0241 #define def_key_c02 0x0242 #define def_key_c03 0x0243 #define def_key_c04 0x0244 #define def_key_c05 0x0245 #define def_key_c06 0x0246 #define def_key_c07 0x0247 #define def_key_c08 0x0248 #define def_key_c09 0x0249 #define def_key_c10 0x024a #define def_key_c11 0x024b #define def_key_c12 0x024c #define def_key_c13 0x024d #define def_key_c14 0x024e #define def_key_c15 0x024f #define def_key_d00 0x0260 #define def_key_d01 0x0261 #define def_key_d02 0x0262 #define def_key_d03 0x0263 #define def_key_d04 0x0264 #define def_key_d05 0x0265 #define def_key_d06 0x0266 #define def_key_d07 0x0267 #define def_key_d08 0x0268 #define def_key_d09 0x0269 #define def_key_d10 0x026a #define def_key_d11 0x026b #define def_key_d12 0x026c #define def_key_d13 0x026d #define def_key_d14 0x026e #define def_key_d15 0x026f #define def_key_qwt_q 0x0220 #define def_key_qwt_w 0x0221 #define def_key_qwt_e 0x0222 #define def_key_qwt_r 0x0223 #define def_key_qwt_t 0x0224 #define def_key_qwt_y 0x0225 #define def_key_qwt_u 0x0226 #define def_key_qwt_i 0x0227 #define def_key_qwt_o 0x0228 #define def_key_qwt_p 0x0229 #define def_key_qwt_a 0x0240 #define def_key_qwt_s 0x0241 #define def_key_qwt_d 0x0242 #define def_key_qwt_f 0x0243 #define def_key_qwt_g 0x0244 #define def_key_qwt_h 0x0245 #define def_key_qwt_j 0x0246 #define def_key_qwt_k 0x0247 #define def_key_qwt_l 0x0248 #define def_key_qwt_z 0x0260 #define def_key_qwt_x 0x0261 #define def_key_qwt_c 0x0262 #define def_key_qwt_v 0x0263 #define def_key_qwt_b 0x0264 #define def_key_qwt_n 0x0265 #define def_key_qwt_m 0x0266 /* -------------------------------------------------------------------------------- character keys on keypad -------------------------------------------------------------------------------- */ #define def_key_pad_0 0x0300 #define def_key_pad_1 0x0301 #define def_key_pad_2 0x0302 #define def_key_pad_3 0x0303 #define def_key_pad_4 0x0304 #define def_key_pad_5 0x0305 #define def_key_pad_6 0x0306 #define def_key_pad_7 0x0307 #define def_key_pad_8 0x0308 #define def_key_pad_9 0x0309 #define def_key_pad_slash 0x030a #define def_key_pad_asterisk 0x030b #define def_key_pad_minus 0x030c #define def_key_pad_plus 0x030d #define def_key_pad_period 0x030e /* -------------------------------------------------------------------------------- special keys -------------------------------------------------------------------------------- */ #define def_key_esc 0x0400 #define def_key_backspace 0x0401 #define def_key_tab 0x0402 #define def_key_enter 0x0403 #define def_key_space 0x0404 #define def_key_insert 0x0405 #define def_key_delete 0x0406 #define def_key_print_screen 0x0407 #define def_key_scroll_lock 0x0408 #define def_key_pause 0x0409 #define def_key_sys_req 0x040a #define def_key_break 0x040b // 0x040c reserved for clear key #define def_key_hangul 0x040d #define def_key_hanja 0x040e /* -------------------------------------------------------------------------------- special keys on keypad -------------------------------------------------------------------------------- */ #define def_key_pad_enter 0x0503 #define def_key_pad_insert 0x0505 #define def_key_pad_delete 0x0506 #define def_key_pad_clear 0x050c /* -------------------------------------------------------------------------------- movement keys -------------------------------------------------------------------------------- */ #define def_key_up 0x0600 #define def_key_down 0x0601 #define def_key_left 0x0602 #define def_key_right 0x0603 #define def_key_page_up 0x0604 #define def_key_page_down 0x0605 #define def_key_home 0x0606 #define def_key_end 0x0607 /* -------------------------------------------------------------------------------- movement keys on keypad -------------------------------------------------------------------------------- */ #define def_key_pad_up 0x0700 #define def_key_pad_down 0x0701 #define def_key_pad_left 0x0702 #define def_key_pad_right 0x0703 #define def_key_pad_page_up 0x0704 #define def_key_pad_page_down 0x0705 #define def_key_pad_home 0x0706 #define def_key_pad_end 0x0707 /* -------------------------------------------------------------------------------- function keys -------------------------------------------------------------------------------- */ #define def_key_f1 0x0800 #define def_key_f2 0x0801 #define def_key_f3 0x0802 #define def_key_f4 0x0803 #define def_key_f5 0x0804 #define def_key_f6 0x0805 #define def_key_f7 0x0806 #define def_key_f8 0x0807 #define def_key_f9 0x0808 #define def_key_f10 0x0809 #define def_key_f11 0x080a #define def_key_f12 0x080b /* -------------------------------------------------------------------------------- function keys on keypad -------------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------------- additonal defines -------------------------------------------------------------------------------- */ #define def_key_type_null 0x0000u #define def_key_type_shift 0x0100u #define def_key_type_char 0x0200u #define def_key_type_pad_char 0x0300u #define def_key_type_action 0x0400u #define def_key_type_pad_action 0x0500u #define def_key_type_cursor 0x0600u #define def_key_type_pad_cursor 0x0700u #define def_key_type_function 0x0800u #define def_key_type_pad_function 0x0900u #define def_key_mask_rshift 0x0001u #define def_key_mask_lshift 0x0002u #define def_key_mask_rctrl 0x0004u #define def_key_mask_lctrl 0x0008u #define def_key_mask_ralt 0x0010u #define def_key_mask_lalt 0x0020u #define def_key_mask_rmachine 0x0040u #define def_key_mask_lmachine 0x0080u #define def_key_mask_num_lock 0x0100u #define def_key_mask_caps_lock 0x0200u #define def_key_mask_shift (def_key_mask_rshift | def_key_mask_lshift) #define def_key_mask_ctrl (def_key_mask_rctrl | def_key_mask_lctrl) #define def_key_mask_alt (def_key_mask_ralt | def_key_mask_lalt) #define def_key_mask_machine (def_key_mask_rmachine | def_key_mask_lmachine) #define def_key_mask_code_type 0xff00u #define def_key_mask_code_offset 0x00ffu /* -------------------------------------------------------------------------------- */ struct cls_key_frame { bool make_flg; uint16 code_u16; uint16 shifted_u16; uint16 toggled_u16; }; #if (defined def_dos) || (defined def_os2 && !defined def_pm) void key_on(); void key_off(); void key_reset(); bool key_pressed(); void key_get(cls_key_frame*); #endif
45.524823
123
0.426157
5bfdbaa805eb89ccfca66a4e290910af697b6e15
439
cpp
C++
modules/cadac/env/wind_constant.cpp
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
1
2020-03-26T07:09:54.000Z
2020-03-26T07:09:54.000Z
modules/cadac/env/wind_constant.cpp
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
null
null
null
modules/cadac/env/wind_constant.cpp
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
null
null
null
#include "wind_constant.hh" #include <cstring> cad::Wind_Constant::Wind_Constant(double dvba, double dir, double twind_In, double vertical_wind) : Wind(twind_In, vertical_wind) { snprintf(name, sizeof(name), "Constant Wind"); altitude = 0; vwind = dvba; psiwdx = dir; } cad::Wind_Constant::~Wind_Constant() { } void cad::Wind_Constant::set_altitude(double altitude_in_meter) { altitude = altitude_in_meter; }
18.291667
97
0.710706
7500881c595656b36cf3bf9aa8b7ebdf0d282e2f
8,635
cpp
C++
http.cpp
kissbeni/tinyhttp
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
[ "Apache-2.0" ]
2
2021-11-27T18:35:20.000Z
2022-03-23T08:11:57.000Z
http.cpp
kissbeni/tinyhttp
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
[ "Apache-2.0" ]
null
null
null
http.cpp
kissbeni/tinyhttp
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
[ "Apache-2.0" ]
null
null
null
#include "http.hpp" #include <vector> /*static*/ TCPClientStream TCPClientStream::acceptFrom(short listener) { struct sockaddr_in client; const size_t clientLen = sizeof(client); short sock = accept( listener, reinterpret_cast<struct sockaddr*>(&client), const_cast<socklen_t*>(reinterpret_cast<const socklen_t*>(&clientLen)) ); if (sock < 0) { perror("accept failed"); return {-1}; } return {sock}; } void TCPClientStream::send(const void* what, size_t size) { if (::send(mSocket, what, size, MSG_NOSIGNAL) < 0) throw std::runtime_error("TCP send failed"); } size_t TCPClientStream::receive(void* target, size_t max) { ssize_t len; if ((len = recv(mSocket, target, max, MSG_NOSIGNAL)) < 0) throw std::runtime_error("TCP receive failed"); return static_cast<size_t>(len); } std::string TCPClientStream::receiveLine(bool asciiOnly, size_t max) { std::string res; char ch; while (res.size() < max) { if (recv(mSocket, &ch, 1, MSG_NOSIGNAL) != 1) throw std::runtime_error("TCP receive failed"); if (ch == '\r') continue; if (ch == '\n') break; if (asciiOnly && !isascii(ch)) throw std::runtime_error("Only ASCII characters were allowed"); res.push_back(ch); } return res; } void TCPClientStream::close() { if (mSocket < 0) return; ::close(mSocket); mSocket = -1; } bool HttpRequest::parse(std::shared_ptr<IClientStream> stream) { std::istringstream iss(stream->receiveLine()); std::vector<std::string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (results.size() < 2) return false; std::string methodString = results[0]; if (methodString == "GET" ) { mMethod = HttpRequestMethod::GET; } else if (methodString == "POST" ) { mMethod = HttpRequestMethod::POST; } else if (methodString == "PUT" ) { mMethod = HttpRequestMethod::PUT; } else if (methodString == "DELETE" ) { mMethod = HttpRequestMethod::DELETE; } else if (methodString == "OPTIONS") { mMethod = HttpRequestMethod::OPTIONS; } else return false; path = results[1]; ssize_t question = path.find("?"); if (question > 0) { query = path.substr(question); path = path.substr(0, question); } if (query.empty()) std::cout << methodString << " " << path << std::endl; else std::cout << methodString << " " << path << " (Query: " << query << ")" << std::endl; while (true) { std::string line = stream->receiveLine(); if (line.empty()) break; ssize_t sep = line.find(": "); if (sep <= 0) return false; std::string key = line.substr(0, sep), val = line.substr(sep+2); (*this)[key] = val; //std::cout << "HEADER: <" << key << "> set to <" << val << ">" << std::endl; } std::string contentLength = (*this)["Content-Length"]; ssize_t cl = std::atoll(contentLength.c_str()); if (cl > MAX_HTTP_CONTENT_SIZE) throw std::runtime_error("request too large"); if (cl > 0) { char* tmp = new char[cl]; bzero(tmp, cl); stream->receive(tmp, cl); mContent = std::string(tmp, cl); delete[] tmp; #ifdef TINYHTTP_JSON if ( (*this)["Content-Type"] == "application/json" || (*this)["Content-Type"].rfind("application/json;",0) == 0 // some clients gives us extra data like charset ) { std::string error; mContentJson = miniJson::Json::parse(mContent, error); if (!error.empty()) std::cerr << "Content type was JSON but we couldn't parse it! " << error << std::endl; } #endif } return true; } /*static*/ bool HttpHandlerBuilder::isSafeFilename(const std::string& name, bool allowSlash) { static const char allowedChars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-+@"; for (auto x : name) { if (x == '/' && !allowSlash) return false; bool ok = false; for (size_t i = 0; allowedChars[i] && !ok; i++) ok = allowedChars[i] == x; if (!ok) return false; } return true; } /*static*/ std::string HttpHandlerBuilder::getMimeType(std::string name) { static std::map<std::string, std::string> mMimeDatabase; if (mMimeDatabase.empty()) { mMimeDatabase.insert({"js", "application/javascript"}); mMimeDatabase.insert({"pdf", "application/pdf"}); mMimeDatabase.insert({"gz", "application/gzip"}); mMimeDatabase.insert({"xml", "application/xml"}); mMimeDatabase.insert({"html", "text/html"}); mMimeDatabase.insert({"htm", "text/html"}); mMimeDatabase.insert({"css", "text/css"}); mMimeDatabase.insert({"txt", "text/plain"}); mMimeDatabase.insert({"png", "image/png"}); mMimeDatabase.insert({"jpg", "image/jpeg"}); mMimeDatabase.insert({"jpeg", "image/jpeg"}); mMimeDatabase.insert({"json", "application/json"}); } ssize_t pos = name.rfind("."); if (pos < 0) return "application/octet-stream"; auto f = mMimeDatabase.find(name.substr(pos+1)); if (f == mMimeDatabase.end()) return "application/octet-stream"; return f->second; } HttpServer::HttpServer() { mDefault404Message = HttpResponse{404, "text/plain", "404 not found"}.buildMessage(); mDefault400Message = HttpResponse{400, "text/plain", "400 bad request"}.buildMessage(); } void HttpServer::startListening(uint16_t port) { #ifndef TINYHTTP_FUZZING mSocket = socket(AF_INET, SOCK_STREAM, 0); if (mSocket == -1) throw std::runtime_error("Could not create socket"); struct sockaddr_in remote = {0}; remote.sin_family = AF_INET; remote.sin_addr.s_addr = htonl(INADDR_ANY); remote.sin_port = htons(port); int iRetval; while (true) { iRetval = bind(mSocket, reinterpret_cast<struct sockaddr*>(&remote), sizeof(remote)); if (iRetval < 0) { perror("Failed to bind socket, retrying in 5 seconds..."); usleep(1000 * 5000); } else break; } listen(mSocket, 3); #else mSocket = 0; #endif printf("Waiting for incoming connections...\n"); while (mSocket != -1) { #ifdef TINYHTTP_FUZZING auto stream = std::make_shared<StdinClientStream>(); #else auto stream = std::shared_ptr<IClientStream>(new TCPClientStream{TCPClientStream::acceptFrom(mSocket)}); #endif std::thread th([stream,this]() { ICanRequestProtocolHandover* handover = nullptr; std::unique_ptr<HttpRequest> handoverRequest; try { while (stream->isOpen()) { HttpRequest req; try { if (!req.parse(stream)) { stream->send(mDefault400Message); stream->close(); continue; } } catch (...) { stream->send(mDefault400Message); stream->close(); continue; } auto res = processRequest(req.getPath(), req); if (res) { auto builtMessage = res->buildMessage(); stream->send(builtMessage); if (res->acceptProtocolHandover(&handover)) { handoverRequest = std::make_unique<HttpRequest>(req); break; } goto keep_alive_check; } stream->send(mDefault404Message); keep_alive_check: if (req["Connection"] != "keep-alive") break; } if (handover) handover->acceptHandover(mSocket, *stream.get(), std::move(handoverRequest)); } catch (std::exception& e) { std::cerr << "Exception in HTTP client handler (" << e.what() << ")\n"; } stream->close(); }); #ifdef TINYHTTP_FUZZING th.join(); break; #else th.detach(); #endif } puts("Listen loop shut down"); } void HttpServer::shutdown() { close(mSocket); mSocket = -1; }
30.298246
122
0.550434
7504ec031afcc508c6f5e58eb8b1c0be91f0d33a
9,092
cpp
C++
MOWER/src/MowerMoves/MowerMoves.cpp
Mrgove10/AutoMower
9f157f27da13b94d0138208efebbe4f26b5d9187
[ "MIT" ]
2
2022-03-29T05:34:31.000Z
2022-03-29T06:04:40.000Z
MOWER/src/MowerMoves/MowerMoves.cpp
Mrgove10/AutoMower
9f157f27da13b94d0138208efebbe4f26b5d9187
[ "MIT" ]
null
null
null
MOWER/src/MowerMoves/MowerMoves.cpp
Mrgove10/AutoMower
9f157f27da13b94d0138208efebbe4f26b5d9187
[ "MIT" ]
1
2022-03-29T03:32:22.000Z
2022-03-29T03:32:22.000Z
#include <Arduino.h> #include "pin_definitions.h" #include "Environment_definitions.h" #include "myGlobals_definition.h" #include "MowerMoves/MowerMoves.h" #include "MotionMotor/MotionMotor.h" #include "Utils/Utils.h" #include "Display/Display.h" /** * Mower mouvement stop function */ void MowerStop() { DebugPrintln("Mower Stop", DBG_VERBOSE, true); MotionMotorStop(MOTION_MOTOR_RIGHT); MotionMotorStop(MOTION_MOTOR_LEFT); // Wait before any movement is made - To limit mechanical stress delay(150); } /** * Mower forward move * @param Speed to travel */ void MowerForward(const int Speed) { DebugPrintln("Mower Forward at " + String(Speed) + "%", DBG_VERBOSE, true); MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_FORWARD, Speed); MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_FORWARD, Speed); } /** * Sets/changes Mower speed * @param Speed to travel */ void MowerSpeed(const int Speed) { static int lastSpeed = 0; if (Speed != lastSpeed) { DebugPrintln("Mower speed at " + String(Speed) + "%", DBG_VERBOSE, true); lastSpeed = Speed; } MotionMotorSetSpeed(MOTION_MOTOR_RIGHT, Speed); MotionMotorSetSpeed(MOTION_MOTOR_LEFT, Speed); } /** * Mower reverse move * @param Speed to reverse * @param Duration of reverse (in ms) */ void MowerReverse(const int Speed, const int Duration) { DebugPrintln("Mower Reverse at " + String(Speed) + "%", DBG_VERBOSE, true); MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_REVERSE, Speed); MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_REVERSE, Speed); delay(Duration); MowerStop(); // Wait before any movement is made - To limit mechanical stress delay(150); } /** * Mower turn function * @param Angle to turn in degrees (positive is right turn, negative is left turn) * @param OnSpot turn with action of both wheels * */ void MowerTurn(const int Angle, const bool OnSpot) { // Limit angle to [-360,+360] degrees int LimitedAngle = min(Angle, 360); LimitedAngle = max(LimitedAngle, -360); float turnDuration = float(abs(LimitedAngle) / (MOWER_MOVES_TURN_ANGLE_RATIO)); DebugPrintln("Mower turn of " + String(Angle) + " Deg => " + String(turnDuration, 0) + " ms", DBG_VERBOSE, true); if (LimitedAngle < 0) // Left turn { MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_FORWARD, MOWER_MOVES_TURN_SPEED); if (OnSpot) { MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_REVERSE, MOWER_MOVES_TURN_SPEED); } delay(turnDuration); MotionMotorStop(MOTION_MOTOR_RIGHT); MotionMotorStop(MOTION_MOTOR_LEFT); } else // Right turn { MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_FORWARD, MOWER_MOVES_TURN_SPEED); if (OnSpot) { MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_REVERSE, MOWER_MOVES_TURN_SPEED); } delay(turnDuration); MotionMotorStop(MOTION_MOTOR_LEFT); MotionMotorStop(MOTION_MOTOR_RIGHT); } } /** * Mower reverse and turn function * @param Angle to turn in degrees (positive is right turn, negative is left turn) * @param Duration of reverse (in ms) * @param OnSpot turn with action of both wheels * */ void MowerReserseAndTurn(const int Angle, const int Duration, const bool OnSpot) { int correctedAngle = Angle; int correctedDuration = Duration; // Check if mower facing downwards, increase turning angle and duration to compensate for tilt angle if (g_pitchAngle < MOTION_MOTOR_PITCH_TURN_CORRECTION_ANGLE) { DebugPrintln("Mower facing downwards (Pitch:" + String(g_pitchAngle) + ") : turn angle and duration corrected", DBG_DEBUG, true); correctedAngle = correctedAngle - int(g_pitchAngle * MOTION_MOTOR_PITCH_TURN_CORRECTION_FACTOR); // pitch angle is negative when going downwards correctedDuration = correctedDuration - int(100 * g_pitchAngle * MOTION_MOTOR_PITCH_TURN_CORRECTION_FACTOR); // pitch angle is negative when going downwards } MowerReverse(MOWER_MOVES_REVERSE, correctedDuration); MowerTurn(correctedAngle, OnSpot); // Wait before any movement is made - To limit mechanical stress delay(150); } /** * Mower checks selected obstacle types and reduces speed if conditions are met * @param SpeedDelta as int: the speed reduction to be applied expressed as a positive value (in absolue %). If multiple conditions are selected, same speed reduction is applied. * @param Front as optional int: sonar measured front distance under which mower needs to slow down. 0 disbales the check. Default is 0 * @param Left as optional int: sonar measured left distance under which mower needs to slow down. 0 disbales the check. Default is 0 * @param Right as optional int: sonar measured right distance under which mower needs to slow down. 0 disbales the check. Default is 0 * @param Perimeter as optional int: perimeter wire signal magnitude under which mower needs to slow down. 0 disables the check. Absolute value is used to perform the check (applies to both inside and outside perimeter wire). Default is 0. * @return boolean indicating if the function triggered a speed reduction */ bool MowerSlowDownApproachingObstables(const int SpeedDelta, const int Front, const int Left, const int Right, const int Perimeter) { static unsigned long lastSpeedReduction = 0; bool SpeedReductiontiggered = false; static bool SpeedReductionInProgress = false; // To avoid a jerky mouvement, speed reduction is maintained at least for a set duration // if (millis() - lastSpeedReduction < OBSTACLE_APPROACH_LOW_SPEED_MIN_DURATION) // { // return true; // } // else // { // // SpeedReductionInProgress = false; // } // Check for objects in Front if (Front > 0 && g_SonarDistance[SONAR_FRONT] < Front) { DebugPrintln("Front approaching object: Slowing down ! (" + String(g_SonarDistance[SONAR_FRONT]) + "cm)", DBG_DEBUG, true); SpeedReductiontiggered = true; } // Check for objects on left side if (Left > 0 && g_SonarDistance[SONAR_LEFT] < Left) { DebugPrintln("Left approaching object: Slowing down ! (" + String(g_SonarDistance[SONAR_LEFT]) + "cm)", DBG_DEBUG, true); SpeedReductiontiggered = true; } // Check for objects on right side if (Right > 0 && g_SonarDistance[SONAR_RIGHT] < Right) { DebugPrintln("Right approaching object: Slowing down ! (" + String(g_SonarDistance[SONAR_RIGHT]) + "cm)", DBG_DEBUG, true); SpeedReductiontiggered = true; } // Check for Perimeter wire if (Perimeter > 0 && abs(g_PerimeterMagnitudeAvg) > Perimeter) { DebugPrintln("Approaching perimeter: Slowing down ! (" + String(g_PerimeterMagnitude) + ")", DBG_VERBOSE, true); SpeedReductiontiggered = true; } // If at least one of the conditions are met and if motor speed is higher that minimum threshold, reduce speed // Left Motor // if (SpeedReductiontiggered && g_MotionMotorSpeed[MOTION_MOTOR_LEFT] - SpeedDelta > MOTION_MOTOR_MIN_SPEED ) if (SpeedReductiontiggered && !SpeedReductionInProgress) { DebugPrintln("Left motor speed reduced by " + String(SpeedDelta) + "%", DBG_VERBOSE, true); MotionMotorSetSpeed(MOTION_MOTOR_LEFT, - SpeedDelta, true); } // Right Motor // if (SpeedReductiontiggered && g_MotionMotorSpeed[MOTION_MOTOR_RIGHT] - SpeedDelta > MOTION_MOTOR_MIN_SPEED) if (SpeedReductiontiggered && !SpeedReductionInProgress) // if (SpeedReductiontiggered) { DebugPrintln("Right motor speed reduced by " + String(SpeedDelta) + "%", DBG_VERBOSE, true); MotionMotorSetSpeed(MOTION_MOTOR_RIGHT, - SpeedDelta, true); SpeedReductionInProgress = true; } // keep track of when last speed reduction was triggered if (SpeedReductiontiggered) { lastSpeedReduction = millis(); } else { SpeedReductionInProgress = false; } return SpeedReductiontiggered; } /** * Mower arc function : mower moves in given direction with motors running at a different speed, thus turning forming an arc : used for spiral mowing * @param direction forward (MOTION_MOTOR_FORWARD) or reverse (MOTION_MOTOR_REVERSE) * @param leftSpeed Left motor speed (in %) * @param rightSpeed Right motor speed (in %) */ void MowerArc(const int direction, const int leftSpeed, const int rightSpeed) { if (direction == MOTION_MOTOR_FORWARD) { if (leftSpeed != rightSpeed) { DebugPrintln("Mower arc Forward (Left:" + String(leftSpeed) + "%, Right:" + String(rightSpeed) + "%)", DBG_VERBOSE, true); } else { DebugPrintln("Mower Forward @ " + String(leftSpeed) + "%", DBG_VERBOSE, true); } } else { if (leftSpeed != rightSpeed) { DebugPrintln("Mower arc Reverse (Left:" + String(leftSpeed) + "%, Right:" + String(rightSpeed) + "%)", DBG_VERBOSE, true); } else { DebugPrintln("Mower Reverse @ " + String(leftSpeed) + "%", DBG_VERBOSE, true); } } MotionMotorStart(MOTION_MOTOR_RIGHT, direction, rightSpeed); MotionMotorStart(MOTION_MOTOR_LEFT, direction, leftSpeed); } /* void getMeUnstuck() { // stop motor // go back 10 cm // turn right or left (by certain angle) turn(15, true); // go forward } */
34.570342
241
0.723603
7506f8c3b63aff5e8b7ddfd042bcdccd46e947ac
50,640
cpp
C++
element.cpp
orkzking/openxfem
66889ea05ec108332ab8566b510124ee1a3f334d
[ "FTL" ]
null
null
null
element.cpp
orkzking/openxfem
66889ea05ec108332ab8566b510124ee1a3f334d
[ "FTL" ]
null
null
null
element.cpp
orkzking/openxfem
66889ea05ec108332ab8566b510124ee1a3f334d
[ "FTL" ]
null
null
null
/************************************************************************************ Copyright (C) 2005 Stephane BORDAS, Cyrille DUNANT, Vinh Phu NGUYEN, Quang Tri TRUONG, Ravindra DUDDU This file is part of the XFEM C++ Library (OpenXFEM++) written and maintained by above authors. This program is free software; you can redistribute it and/or modify it. 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 license text for more details. Any feedback is welcome. Emails : nvinhphu@gmail.com, ... *************************************************************************************/ // file ELEMENT.CPP #include "element.h" #include "tri_u.h" #include "tri6.h" #include "quad_u.h" #include "plateiso4.h" #include "tetra4.h" #include "mitc4.h" #include "domain.h" #include "timestep.h" #include "timinteg.h" #include "node.h" #include "dof.h" #include "material.h" #include "bodyload.h" #include "gausspnt.h" #include "intarray.h" #include "flotarry.h" #include "flotmtrx.h" #include "diagmtrx.h" #include "enrichmentitem.h" #include "cracktip.h" #include "crackinterior.h" #include "materialinterface.h" #include "enrichmentfunction.h" #include "standardquadrature.h" #include "splitgaussquadrature.h" #include "vertex.h" #include "feinterpol.h" #include "linsyst.h" #include "functors.h" #include "skyline.h" #include <stdlib.h> #include <stdio.h> #include <vector> #include <map> #include <algorithm> #include <iostream> #include "planelast.h" using namespace std; Element :: Element (int n, Domain* aDomain) : FEMComponent (n, aDomain) // Constructor. Creates an element with number n, belonging to aDomain. { material = 0 ; numberOfNodes = 0 ; nodeArray = NULL ; locationArray = NULL ; constitutiveMatrix = NULL ; massMatrix = NULL ; stiffnessMatrix = NULL ; bodyLoadArray = NULL ; gaussPointArray = NULL ; neighbors = NULL ; // XFEM, NVP 2005 numberOfGaussPoints = 0 ; // XFEM, NVP 2005 numOfGPsForJ_Integral = 0 ; // XFEM, NVP 2005-08-13 numberOfIntegrationRules = 0 ; // XFEM, NVP 2005 quadratureRuleArray= NULL ; // XFEM, NVP 2005 standardFEInterpolation = NULL ; // XFEM, NVP 2005 enrichmentFEInterpolation= NULL ; // XFEM, NVP 2005 enrichmentItemListOfElem = NULL ; // XFEM, NVP 2005 checked = false; // XFEM, NVP 2005 isUpdated = false ; // XFEM, NVP 2005-09-03 isMultiMaterial = false ; // one material element //materialIDs = } Element :: ~Element () // Destructor. { delete nodeArray ; delete locationArray ; delete massMatrix ; delete stiffnessMatrix ; delete constitutiveMatrix ; if (gaussPointArray) { for (size_t i = 0 ; i < numberOfGaussPoints ; i++) delete gaussPointArray[i] ; delete gaussPointArray ; } if (quadratureRuleArray) { for (size_t i = 0 ; i < numberOfIntegrationRules ; i++) delete quadratureRuleArray[i] ; delete quadratureRuleArray ; } delete bodyLoadArray ; delete enrichmentItemListOfElem ; delete standardFEInterpolation ; delete enrichmentFEInterpolation ; delete neighbors ; } FloatMatrix* Element :: ComputeTangentStiffnessMatrix () // Computes numerically the tangent stiffness matrix of the receiver, with // the mesh subject to the total displacements D. // Remark: geometrical nonlinarities are not acccounted for. // MODIFIED TO TAKE ACCOUNT FOR MULTIMATERIALS ELEMENT !!! { GaussPoint *gp; FloatMatrix *b,*db,*d; double dV; //test ConstantStiffness? char nlSolverClassName[32] ; NLSolver* nlSolver = this->domain->giveNLSolver(); nlSolver -> giveClassName(nlSolverClassName) ; if (stiffnessMatrix) { delete stiffnessMatrix; } stiffnessMatrix = new FloatMatrix(); Material *mat = this->giveMaterial(); for (size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i]; b = this->ComputeBmatrixAt(gp); // compute D matrix if(! strcmp(nlSolverClassName,"ConstantStiffness")) d = this->giveConstitutiveMatrix()->GiveCopy(); // NO USED LONGER !!! else d = mat->ComputeConstitutiveMatrix(gp,this); // USE THIS ONE //d->printYourself(); dV = this->computeVolumeAround(gp); db = d->Times(b); stiffnessMatrix->plusProduct(b,db,dV); delete d; delete db; delete b; // SC-Purify-10.09.97 } stiffnessMatrix->symmetrized(); return stiffnessMatrix->GiveCopy(); // fix memory leaks !!! } FloatArray* Element :: ComputeInternalForces (FloatArray* dElem) // Computes the internal force vector of the receiver, with the domain sub- // ject to the displacements D. { GaussPoint *gp; FloatMatrix *b; double dV; Material *mat = this->giveMaterial(); FloatArray *f = new FloatArray(); for(size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i]; b = this->ComputeBmatrixAt(gp); mat -> ComputeStress(dElem,this,gp); dV = this->computeVolumeAround(gp); f->plusProduct(b,gp->giveStressVector(),dV); delete b; } return f; } void Element :: assembleLhsAt (TimeStep* stepN) // Assembles the left-hand side (stiffness matrix) of the receiver to // the linear system' left-hand side, at stepN. { //FloatMatrix* elemLhs ; //Skyline* systLhs ; //IntArray* locArray ; //elemLhs = this -> ComputeLhsAt(stepN) ; //systLhs = domain -> giveNLSolver() -> giveLinearSystem() -> giveLhs() ; //locArray = this -> giveLocationArray() ; //systLhs -> assemble(elemLhs,locArray) ; //delete elemLhs ; } void Element :: assembleRhsAt (TimeStep* stepN) // Assembles the right-hand side (load vector) of the receiver to // the linear system' right-hand side, at stepN. { //FloatArray* elemRhs ; //FloatArray* systRhs ; //IntArray* locArray ; //elemRhs = this -> ComputeRhsAt(stepN) ; //if (elemRhs) { // systRhs = domain -> giveNLSolver() -> giveLinearSystem() -> giveRhs() ; // locArray = this -> giveLocationArray() ; // systRhs -> assemble(elemRhs,locArray) ; // delete elemRhs ;} } void Element :: assembleYourselfAt (TimeStep* stepN) // Assembles the contributions of the receiver to the linear system, at // time step stepN. This may, or may not, require assembling the receiver's // left-hand side. { # ifdef VERBOSE printf ("assembling element %d\n",number) ; # endif //CB - Modified by SC - 25.07.97 //because we ALWAYS reform the system! //if (stepN -> requiresNewLhs()) //CE - Modified by SC - 25.07.97 //this -> assembleLhsAt(stepN) ; //this -> assembleRhsAt(stepN) ; } FloatArray* Element :: ComputeBcLoadVectorAt (TimeStep* stepN) // Computes the load vector due to the boundary conditions acting on the // receiver's nodes, at stepN. Returns NULL if this array contains only // zeroes. // Modified by NVP 2005-09-04 for XFEM implementation. { FloatArray *d, *answer ; FloatMatrix *k; d = this -> ComputeVectorOfPrescribed('d',stepN) ; if(this->domain->isXFEMorFEM() == false && stepN->giveNumber() > 1) { FloatArray *previousDPr; previousDPr = this -> ComputeVectorOfPrescribed ('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ; d->minus(previousDPr); delete previousDPr; } if (d -> containsOnlyZeroes()) { answer = NULL ; } else { k = this -> GiveStiffnessMatrix() ; answer = k -> Times(d) -> negated() ; delete k ; } delete d ; return answer ; } FloatArray* Element :: ComputeBodyLoadVectorAt (TimeStep* stepN) // Computes numerically the load vector of the receiver due to the body // loads, at stepN. { double dV ; GaussPoint* gp ; FloatArray *answer,*f,*ntf ; FloatMatrix *n,*nt ; if (this -> giveBodyLoadArray() -> isEmpty()) // no loads return NULL ; else { f = this -> ComputeResultingBodyForceAt(stepN) ; if (! f) // nil resultant return NULL ; else { answer = new FloatArray(0) ; for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; n = this -> ComputeNmatrixAt(gp) ; dV = this -> computeVolumeAround(gp) ; nt = n -> GiveTransposition() ; ntf = nt -> Times(f) -> times(dV) ; answer -> add(ntf) ; delete n ; delete nt ; delete ntf ; } delete f ; return answer ; } } } FloatMatrix* Element :: ComputeConsistentMassMatrix () // Computes numerically the consistent (full) mass matrix of the receiver. { double density,dV ; FloatMatrix *n,*answer ; GaussPoint *gp ; answer = new FloatMatrix() ; density = this -> giveMaterial() -> give('d') ; for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; n = this -> ComputeNmatrixAt(gp) ; dV = this -> computeVolumeAround(gp) ; answer -> plusProduct(n,n,density*dV) ; delete n ; } return answer->symmetrized() ; } FloatMatrix* Element :: computeLhsAt (TimeStep* stepN) // Computes the contribution of the receiver to the left-hand side of the // linear system. { TimeIntegrationScheme* scheme ; scheme = domain -> giveTimeIntegrationScheme() ; if (scheme -> isStatic()) return this -> ComputeStaticLhsAt (stepN) ; else if (scheme -> isNewmark()) return this -> ComputeNewmarkLhsAt(stepN) ; else { printf ("Error : unknown time integration scheme : %c\n",scheme) ; exit(0) ; return NULL ; //SC } } FloatArray* Element :: ComputeLoadVectorAt (TimeStep* stepN) // Computes the load vector of the receiver, at stepN. { FloatArray* loadVector ; FloatArray* bodyLoadVector = NULL ; FloatArray* bcLoadVector = NULL ; loadVector = new FloatArray(0) ; bodyLoadVector = this -> ComputeBodyLoadVectorAt(stepN) ; if (bodyLoadVector) { loadVector -> add(bodyLoadVector) ; delete bodyLoadVector ; } // BCLoad vector only at the first iteration if (this->domain->giveNLSolver()->giveCurrentIteration() == 1) { bcLoadVector = this -> ComputeBcLoadVectorAt(stepN) ; if (bcLoadVector) { loadVector -> add(bcLoadVector) ; delete bcLoadVector ; } } if (loadVector -> isNotEmpty()) return loadVector ; else { delete loadVector ; return NULL ; } } FloatMatrix* Element :: computeMassMatrix () // Returns the lumped mass matrix of the receiver. { FloatMatrix* consistentMatrix ; consistentMatrix = this -> ComputeConsistentMassMatrix() ; massMatrix = consistentMatrix -> Lumped() ; delete consistentMatrix ; return massMatrix ; } FloatMatrix* Element :: ComputeNewmarkLhsAt (TimeStep* stepN) // Computes the contribution of the receiver to the left-hand side of the // linear system, using Newmark's formula. { FloatMatrix *m,*lhs ; double beta,dt ; if (stepN->giveNumber() == 0) { lhs = this -> GiveStiffnessMatrix() ; } else { beta = domain -> giveTimeIntegrationScheme() -> giveBeta() ; if (beta == 0.0) { printf ("Error: beta = 0.0 in Newmark \n") ; exit(0) ; } else { dt = stepN -> giveTimeIncrement() ; m = this -> giveMassMatrix() -> Times(1.0 / (beta*dt*dt)); lhs = this -> GiveStiffnessMatrix(); lhs->plus(m); delete m; } } return lhs ; } FloatArray* Element :: ComputeNewmarkRhsAt (TimeStep* stepN, FloatArray* dxacc) // Computes the contribution of the receiver to the right-hand side of the // linear system, using Newmark's formula. { FloatMatrix *K; DiagonalMatrix *M; FloatArray *fExt,*dPred,*rhs,*a,*d,*dElem,*dPrev,*temp; double beta,dt ; fExt = this -> ComputeLoadVectorAt(stepN) ; if (stepN->giveNumber() == 0) { // computes also the true stress state at the intial step, through the internal // forces computation. K = this -> GiveStiffnessMatrix () ; d = this -> ComputeVectorOf ('d',stepN) ; dElem = dxacc->Extract(this->giveLocationArray()); rhs = K -> Times(d) -> add(fExt) -> add (this->ComputeInternalForces(dElem)->negated()); delete d; delete dElem; delete K; } else { dPred = this -> ComputeVectorOf ('D',stepN) ; dPrev = this -> ComputeVectorOf ('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ; double aNorm = dxacc->giveNorm(); if (aNorm == 0.) { //means iteration zero (dxacc = 0) dElem = dPred->Minus(dPrev); rhs = (this->ComputeInternalForces(dElem)->negated()) -> add(fExt); delete dElem; } else { M = (DiagonalMatrix*) this -> giveMassMatrix () ; dt = stepN -> giveTimeIncrement() ; beta = domain -> giveTimeIntegrationScheme() -> giveBeta() ; dElem = dxacc->Extract(this->giveLocationArray()); a = dElem->Times(1.0 / (beta*dt*dt)); temp = dPred->Minus(dPrev); temp->add(dElem); rhs = (M->Times(a->negated())) -> add(this->ComputeInternalForces(temp)->negated()) -> add(fExt); delete a ; delete dElem; delete temp; } delete dPred; delete dPrev; } delete fExt ; return rhs ; } int Element :: computeNumberOfDofs () // Returns the total number of dofs of the receiver's nodes. { int n = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) n += this -> giveNode(i+1) -> giveNumberOfDofs() ; return n ; } size_t Element :: computeNumberOfDisplacementDofs () // ************************************************** // Returns the total number of "true" dofs of the receiver's nodes. // just read from the input file, the dofs of each node { size_t n = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { n += this -> giveNode(i+1) -> readInteger("nDofs") ; } return n ; } FloatArray* Element :: ComputeResultingBodyForceAt (TimeStep* stepN) // Computes at stepN the resulting force due to all body loads that act // on the receiver. This force is used by the element for computing its // body load vector. { int n ; BodyLoad* load ; FloatArray *force,*resultant ; resultant = new FloatArray(0) ; int nLoads = this -> giveBodyLoadArray() -> giveSize() ; for (size_t i = 1 ; i <= nLoads ; i++) { n = bodyLoadArray -> at(i) ; load = (BodyLoad*) domain->giveLoad(n) ; force = load -> ComputeForceOn(this,stepN) ; resultant -> add(force) ; delete force ; } if (resultant->giveSize() == 0) { delete resultant ; return NULL ; } else return resultant ; } FloatArray* Element :: computeRhsAt (TimeStep* stepN, FloatArray* dxacc) // Computes the contribution of the receiver to the right-hand side of the // linear system. { TimeIntegrationScheme* scheme = domain -> giveTimeIntegrationScheme() ; if (scheme -> isStatic()) return this -> ComputeStaticRhsAt (stepN,dxacc) ; else if (scheme -> isNewmark()) return this -> ComputeNewmarkRhsAt(stepN,dxacc) ; else { printf ("Error : unknown time integration scheme : %c\n",scheme) ; assert(false) ; return NULL ; //SC } } FloatMatrix* Element :: ComputeStaticLhsAt (TimeStep* stepN) // Computes the contribution of the receiver to the left-hand side of the // linear system, in a static analysis. // Modified by NVP 21-10-2005 for XFEM update // Only recompute the stiffness matrices for updated elements!!! { //if (stepN->giveNumber() == 1) return this -> ComputeTangentStiffnessMatrix() ; //else //{ // if(isUpdated) /// return this -> ComputeTangentStiffnessMatrix() ; // return stiffnessMatrix->GiveCopy() ; //} } FloatArray* Element :: ComputeStaticRhsAt (TimeStep* stepN, FloatArray* dxacc) // Computes the contribution of the receiver to the right-hand side of the // linear system, in a static analysis. // Modified by NVP 2005-09-05 for XFEM ( crack growth simulation part). { FloatArray *answer,*fInternal,*fExternal,*dElem,*dElemTot; dElem = dxacc->Extract(this->giveLocationArray()); //add delta prescribed displacement vector - SC 29.04.99 if(this->domain->giveNLSolver()->giveCurrentIteration() != 1)// from second iteration on { FloatArray *currentDPr,*previousDPr; currentDPr = this -> ComputeVectorOfPrescribed('d',stepN) ; if( (stepN->giveNumber() > 1) && (this->domain->isXFEMorFEM() == false) ) { previousDPr = this -> ComputeVectorOfPrescribed('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ; dElemTot = (dElem->Plus(currentDPr))->Minus(previousDPr); delete previousDPr; } else { dElemTot = dElem->Plus(currentDPr); } delete currentDPr; } else // first iteration { dElemTot = dElem->Times(1.); } fInternal = this->ComputeInternalForces(dElemTot); fExternal = this->ComputeLoadVectorAt(stepN); answer = fExternal->Minus(fInternal); delete dElem; delete dElemTot; delete fExternal; delete fInternal; return answer; } FloatMatrix* Element :: computeStiffnessMatrix () // Computes numerically the stiffness matrix of the receiver. // NOT USED ANYMORE !!! { double dV ; FloatMatrix *b,*db,*d ; GaussPoint *gp ; stiffnessMatrix = new FloatMatrix() ; for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; b = this -> ComputeBmatrixAt(gp) ; d = this -> giveConstitutiveMatrix() ; dV = this -> computeVolumeAround(gp) ; db = d -> Times(b) ; stiffnessMatrix -> plusProduct(b,db,dV) ; delete b ; delete db ; } return stiffnessMatrix -> symmetrized() ; } FloatArray* Element :: computeStrainVector (GaussPoint* gp, TimeStep* stepN) // Computes the vector containing the strains at the Gauss point gp of // the receiver, at time step stepN. The nature of these strains depends // on the element's type. { FloatMatrix *b ; FloatArray *u,*Epsilon ; b = this -> ComputeBmatrixAt(gp) ; u = this -> ComputeVectorOf('d',stepN) ; Epsilon = b -> Times(u) ; gp -> letStrainVectorBe(Epsilon) ; // gp stores Epsilon, not a copy delete b ; delete u ; return Epsilon ; } /* FloatArray* Element :: computeStressAt(GaussPoint* gp,TimeStep* stepN) // ******************************************************************** // computes stress at Stress point gp. { FloatMatrix *b = this -> ComputeBmatrixAt(gp) ; FloatArray *u = this -> ComputeVectorOf('d',stepN) ; FloatArray *Epsilon = b -> Times(u) ; FloatMatrix *D = this->giveConstitutiveMatrix(); FloatArray *stress = D->Times(Epsilon); delete b ; delete u ; delete Epsilon ; return stress ; }*/ void Element :: computeStrain (TimeStep* stepN) // compute strain vector at stepN { GaussPoint* gp ; for (size_t i = 1 ; i <= this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i-1] ; this -> computeStrainVector(gp,stepN) ; } } FloatArray* Element :: computeStrainIncrement (GaussPoint* gp, FloatArray* dElem) // Returns the vector containing the strains incr. at point 'gp', with the nodal // displacements incr. of the receiver given by dElem. { FloatArray* depsilon; FloatMatrix* b; b = this -> ComputeBmatrixAt(gp); depsilon = b -> Times(dElem); delete b; return depsilon; } FloatArray* Element :: ComputeVectorOf (char u, TimeStep* stepN) // ************************************************************* // Forms the vector containing the values of the unknown 'u' (e.g., the // displacement) of the dofs of the receiver's nodes. // Modified by NVP to take into account the enriched DOFs for XFEM. 2005/07/15 // u = [u1 v1 ...un vn | a1 b1 ..an bn ] { Node *nodeI ; int nDofs ; FloatArray *answer = new FloatArray(this->computeNumberOfDofs()) ; int k = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; nDofs = nodeI->giveNumberOfTrueDofs () ; for (size_t j = 1 ; j <= nDofs ; j++) answer->at(++k) = nodeI->giveDof(j)->giveUnknown(u,stepN) ; } if(this->isEnriched() == false) // non-enriched element return answer ; // enriched element size_t numOfTrueDofs ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; numOfTrueDofs = nodeI->giveNumberOfTrueDofs() ; nDofs = nodeI->giveNumberOfDofs() - numOfTrueDofs ; for (size_t j = 1 ; j <= nDofs ; j++) answer->at(++k) = nodeI->giveDof(j+numOfTrueDofs)->giveUnknown(u,stepN) ; } return answer ; } FloatArray* Element :: ComputeVectorOfDisplacement (char u, TimeStep* stepN) // ************************************************************************* // computes the "true" displacement vector of the receiver // XFEM implementation. { Node *nodeI ; size_t nDofs ; FloatArray *answer = new FloatArray(this->computeNumberOfDisplacementDofs()) ; int k = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; nDofs = nodeI->giveNumberOfTrueDofs() ; for (size_t j = 1 ; j <= nDofs ; j++) answer->at(++k) = nodeI->giveDof(j)->giveUnknown(u,stepN) ; } return answer ; } FloatArray* Element :: ComputeVectorOfPrescribed (char u, TimeStep* stepN) // Forms the vector containing the prescribed values of the unknown 'u' // (e.g., the prescribed displacement) of the dofs of the receiver's // nodes. Puts 0 at each free dof. { Node *nodeI ; Dof *dofJ ; FloatArray *answer ; int nDofs ; answer = new FloatArray(this->computeNumberOfDofs()) ; int k = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; nDofs = nodeI->giveNumberOfDofs() ; for (size_t j = 1 ; j <= nDofs ; j++) { dofJ = nodeI->giveDof(j) ; if (dofJ -> hasBc()) answer->at(++k) = dofJ->giveUnknown(u,stepN) ; else answer->at(++k) = 0. ; } } return answer ; } IntArray* Element :: giveBodyLoadArray () // Returns the array which contains the number of every body load that act // on the receiver. { int numberOfLoads ; if (! bodyLoadArray) { numberOfLoads = this -> readIfHas("bodyLoads") ; bodyLoadArray = new IntArray(numberOfLoads) ; for (size_t i = 1 ; i <= numberOfLoads ; i++) bodyLoadArray->at(i) = this->readInteger("bodyLoads",i+1) ; } return bodyLoadArray ; } FloatMatrix* Element :: giveConstitutiveMatrix () // Returns the elasticity matrix {E} of the receiver. { if (! constitutiveMatrix) this -> computeConstitutiveMatrix() ; return constitutiveMatrix ; } IntArray* Element :: giveLocationArray () // Returns the location array of the receiver. // Modified by NVP to take into account the presence of enriched Dofs { if (! locationArray) { this->computeLocationArray(); } return locationArray ; } IntArray* Element :: computeLocationArray () // ****************************************** // Returns the location array of the receiver. // Modified by NVP to take into account the presence of enriched Dofs { IntArray* nodalStandardArray ; // standard scatter vector of node IntArray* nodalEnrichedArray ; // enriched scatter vector of node locationArray = new IntArray(0) ; // total scatter vector of element for(size_t i = 0 ; i < numberOfNodes ; i++) { nodalStandardArray = this->giveNode(i+1)->giveStandardLocationArray() ; locationArray = locationArray -> followedBy(nodalStandardArray) ; } // non-enriched elements if(this->isEnriched() == false) { /* // DEBUG ... std::cout << "Dealing with element " << this->giveNumber() << std::endl ; for(size_t i = 0 ; i < locationArray->giveSize() ; i++) std::cout << (*locationArray)[i] << " " ; std::cout << std::endl ; */ return locationArray ; } // enriched elements for (size_t i = 0 ; i < numberOfNodes ; i++) { nodalEnrichedArray = this -> giveNode(i+1) -> giveEnrichedLocationArray() ; if(nodalEnrichedArray) // enriched node locationArray = locationArray -> followedBy(nodalEnrichedArray) ; } /*// ----------------- DEBUG ONLY 2005-09-29 ------------------------- if(this->isEnriched()) { std::cout << " Location array of element " << this->giveNumber() << " is :" << endl ; for(size_t i = 0 ; i < locationArray->giveSize() ; i++) std::cout << (*locationArray)[i] << " " ; std::cout << std::endl ; } // --------------------------------------------------------------------*/ return locationArray ; } GaussPoint** Element :: giveGaussPointArray() // ******************************************* // 2005-09-03 : modify for crack growth problem // Some elements need changed Gauss Quadrature. { if (gaussPointArray == NULL) this->computeGaussPoints(); else if(isUpdated) this->computeGaussPoints(); return gaussPointArray; } FloatMatrix* Element :: giveMassMatrix () // Returns the mass matrix of the receiver. { if (! massMatrix) this -> computeMassMatrix() ; return massMatrix ; } Material* Element :: giveMaterial () // ********************************** // Returns the material of the receiver. { if (! material) { material = this -> readInteger("mat") ; //std::cout <<this->giveNumber() << " CUC CUT !!! " ; } return domain -> giveMaterial(material) ; } Node* Element :: giveNode (int i) // Returns the i-th node of the receiver. { int n ; if (! nodeArray) nodeArray = new IntArray(numberOfNodes) ; n = nodeArray->at(i) ; if (! n) { n = this -> readInteger("nodes",i) ; nodeArray->at(i) = n ;} return domain -> giveNode(n) ; } IntArray* Element ::giveNodeArray() { if (! nodeArray) { nodeArray = new IntArray(numberOfNodes) ; for (size_t i = 0 ; i < numberOfNodes ; i++) (*nodeArray)[i] = this->readInteger("nodes",i+1) ; } return nodeArray; } size_t Element :: giveNumberOfGaussPoints() // **************************************** { if(numberOfGaussPoints == 0) this->computeGaussPoints(); return numberOfGaussPoints ; } size_t Element :: giveNumOfGPtsForJ_Integral() // ******************************************* { if(numOfGPsForJ_Integral == 0) this->setGaussQuadForJ_Integral(); return numOfGPsForJ_Integral ; } FloatMatrix* Element :: GiveStiffnessMatrix () // ******************************************** // Returns the stiffness matrix of the receiver. // Modification made by NVP for multistep problems (XFEM). // 2005-09-03 { if (! stiffnessMatrix) return this -> ComputeTangentStiffnessMatrix() ; //else if(isUpdated) // return this -> ComputeTangentStiffnessMatrix() ; return stiffnessMatrix->GiveCopy() ; } void Element :: instanciateYourself () // Gets from input file all data of the receiver. { int i ; # ifdef VERBOSE printf ("instanciating element %d\n",number) ; # endif material = this -> readInteger("mat") ; nodeArray = new IntArray(numberOfNodes) ; for (i=1 ; i<=numberOfNodes ; i++) nodeArray->at(i) = this->readInteger("nodes",i) ; this -> giveBodyLoadArray() ; } void Element :: printOutputAt (TimeStep* stepN, FILE* strFile, FILE* s01File) // Performs end-of-step operations. { GaussPoint* gp ; # ifdef VERBOSE printf ("element %d printing output\n",number) ; # endif fprintf (strFile,"element %d :\n",number) ; for (size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; this -> computeStrainVector(gp,stepN) ; //no computation of the stress vector here, it //has already been done during the calculation //of Finternal!!! gp -> computeStressLevel() ; gp -> printOutput(strFile) ; gp -> printBinaryResults(s01File) ; } } Element* Element :: typed () // Returns a new element, which has the same number than the receiver, // but is typed (PlaneProblem, or Truss2D,..). { Element* newElement ; char type[32] ; this -> readString("class",type) ; newElement = this -> ofType(type) ; return newElement ; } void Element :: updateYourself() // ****************************** // Updates the receiver at end of step. // Modified by NVP for XFEM implementation. 2005-09-05 { # ifdef VERBOSE printf ("updating element %d\n",number) ; # endif if(this->domain->isXFEMorFEM() == false) { for (size_t i = 0 ; i < numberOfGaussPoints ; i++) gaussPointArray[i] -> updateYourself() ; } else { for (size_t i = 0 ; i < numberOfGaussPoints ; i++) gaussPointArray[i] -> updateYourselfForXFEM() ; } delete locationArray ; locationArray = NULL ; } FloatMatrix* Element ::ComputeBmatrixAt(GaussPoint *aGausspoint) // ************************************************************** // Computes the general B matrix of the receiver, B = [Bu Ba] // Including non enriched part and enriched parts if element is enriched // B = [Bu Ba] with // Bu = [N1,x 0 N2,x 0 N3,x 0 // 0 N1,y 0 N2,y 0 N3,y // N1,y N1,x N2,y N2,x N3,y N3,x] // // Ba = [(Nbar1(phi-phiAtNode1)),x 0 (Nbar2(phi-phiAtNode2)),x 0 (Nbar3(phi-phiAtNode3)),x 0 // 0(Nbar1(phi-phiAtNode1)),y 0 (Nbar2(phi-phiAtNode2)),y 0 (Nbar3(phi-phiAtNode3)),y // (Nbar1(phi-phiAtNode1)),y (Nbar1(phi-phiAtNode1)),x ...] { // computes the standard part of B matrix : Bu FloatMatrix *Bu = this->ComputeBuMatrixAt(aGausspoint); // non enriched elements if (this->isEnriched() == false) return Bu; // enriched elements,then computes the enriched part Ba FloatMatrix *Ba = new FloatMatrix(); vector<EnrichmentFunction*> *enrFnVector; // vector of enrichment functions FloatArray *gradPhiGP ; // grad of enr. func. at Gauss points FloatMatrix *temp ; double N,dNdx,dNdy,phiGP,phiNode,dPhidXGP,dPhidYGP ; Mu::Point *Coord = aGausspoint -> giveCoordinates() ; // local coord. of Gauss point // Get the shape functions multiplied with the enr. functions... FloatArray *Nbar = this->giveXFEInterpolation()->evalN(Coord); FloatMatrix *gradNbar = this->giveXFEInterpolation()->evaldNdx(domain,this->giveNodeArray(),Coord); for(size_t i = 0 ; i < numberOfNodes ; i++) { Node* nodeI = this->giveNode(i+1) ; if (nodeI->getIsEnriched()) // this node is enriched, then continue ... { N = (*Nbar)[i]; // shape function Ni dNdx = gradNbar->at(i+1,1) ; // derivative of Ni w.r.t x coord. dNdy = gradNbar->at(i+1,2) ; // derivative of Ni w.r.t y coord. // loop on enrichment items of nodeI list<EnrichmentItem*> *enrItemList = nodeI->giveEnrItemListOfNode(); for (list<EnrichmentItem*>::iterator iter = enrItemList->begin(); iter != enrItemList->end(); ++iter) { // get the enrichment funcs of current enr. item enrFnVector = (*iter)->giveEnrFuncVector(); //loop on vector of enrichment functions ... for(size_t k = 0 ; k < enrFnVector->size() ; k++ ) { EnrichmentFunction* enrFn = (*enrFnVector)[k]; // let Enr. function,enrFn, know for which enr. item it is modeling enrFn->findActiveEnrichmentItem(*iter); // value of enrichment function at gauss point phiGP = enrFn->EvaluateYourSelfAt(aGausspoint); // value of enrichment function at node phiNode = enrFn->EvaluateYourSelfAt(this,nodeI); // grad of enrichment function at Gauss point gradPhiGP = enrFn->EvaluateYourGradAt(aGausspoint); dPhidXGP = (*gradPhiGP)[0] ; // derivative of Phi w.r.t x coord. dPhidYGP = (*gradPhiGP)[1] ; // derivative of Phi w.r.t y coord. double a = dNdx * (phiGP - phiNode) + N * dPhidXGP ; double b = dNdy * (phiGP - phiNode) + N * dPhidYGP ; temp = new FloatMatrix(4,2); temp->at(1,1) = a ; temp->at(1,2) = 0.0 ; temp->at(2,1) = 0.0 ; temp->at(2,2) = b ; temp->at(3,1) = b ; temp->at(3,2) = a ; Ba = Ba->FollowedBy(temp); delete temp ; // Purify, 11-10-05 delete gradPhiGP ; // Purify, 11-10-05 } // end of loop on enr. functions } // end of loop on enr. items } } // end of loop on element nodes FloatMatrix *answer = Bu->FollowedBy(Ba); delete Ba ; // Purify, 11-10-05 delete Nbar ; delete gradNbar ; // Purify, 11-10-05 return answer; } bool Element:: isEnriched() // ************************ // Returns true if element is enriched (at least one node is enriched) // and false otherwise { size_t count = 0 ; for(size_t i = 0 ; i < numberOfNodes ; i++) { if(this->giveNode(i+1)->getIsEnriched()) { count += 1 ; i = numberOfNodes ; } } return (count != 0)? true:false ; } Element* Element :: ofType (char* aClass) // *************************************** // Returns a new element, which has the same number than the receiver, // but belongs to aClass (Tri3_U, Tetra4, ...). { Element* newElement ; if (! strcmp(aClass,"Q4U")) newElement = new Quad4_U(number,domain); else if (! strcmp(aClass,"T3U")) newElement = new Tri3_U(number,domain) ; else if (! strcmp(aClass,"T6U")) newElement = new Tri6_U(number,domain) ; else if (! strcmp(aClass,"PQ4")) newElement = new PlateIsoQ4(number,domain) ; else if (! strcmp(aClass,"MITC4")) newElement = new MITC4(number,domain) ; else if (! strcmp(aClass,"H4U")) newElement = new Tetra4(number,domain) ; else { printf ("%s : unknown element type \n",aClass) ; assert(false) ; } return newElement ; } void Element::treatGeoMeshInteraction() // ************************************ // Check if element interacts with enrichment item or not. If so, insert this element // into the list of each enrichment item // Modified at 2005-09-07 to make it more efficient than before. // 28-12-2005: MATERIAL INTERFACE IMPLEMENTATION, ASSUMING 2 MATERIALS { EnrichmentItem *enrItem; for(size_t i = 0 ; i < domain->giveNumberOfEnrichmentItems() ; i++) { enrItem = domain->giveEnrichmentItem(i+1); enrItem->treatMeshGeoInteraction(this); } } void Element :: isEnrichedWith(EnrichmentItem* enrItem) // ***************************************************** // If element is enriched with enrichment item enrItem, then insert // enrItem into the list of enrichment items { if(enrichmentItemListOfElem == NULL) enrichmentItemListOfElem = new std::list<EnrichmentItem*>; if( find(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),enrItem) == enrichmentItemListOfElem->end()) enrichmentItemListOfElem->push_back(enrItem); } std::list<Element*>* Element :: ComputeNeighboringElements() // ********************************************************** // Loop on Element's nodes and get the nodal support of these nodes // and insert into list<Element*> neighbors // Since there are redundancies, first sort this list and then list.unique() // Criterion for sort is defined by operator < ( compare the element.number) { map<Node*,vector<Element*> > nodeElemMap = this->domain->giveNodalSupports(); neighbors = new std::list<Element*> ; for (size_t i = 0 ; i < numberOfNodes ; i++) { Node *aNode = this->giveNode(i+1); neighbors->insert(neighbors->end(),nodeElemMap[aNode].begin(),nodeElemMap[aNode].end()) ; } // removing the redundancies in neighbors ... neighbors->sort(); neighbors->unique(); neighbors->remove(this); // not contain the receiver !!! return neighbors ; } std::list<Element*>* Element :: giveNeighboringElements() // ******************************************************* // returns the neighboring elements of the receiver, if it does not exist yet, // compute it. { if (neighbors == NULL) neighbors = this->ComputeNeighboringElements(); return neighbors ; } void Element :: printMyNeighbors() // ******************************* // Print neighbors of the receiver. // Useful for debugging { neighbors = this->giveNeighboringElements(); std::cout << " Neighbors of element " << number << " : "; for (list<Element*>::iterator it = neighbors->begin(); it != neighbors->end(); ++it) std::cout << (*it)->giveNumber() << " " ; std::cout << std::endl; } Mu::Point* Element :: giveMyCenter() // ********************************* // compute the gravity center of the receiver { double sumX = 0.0 ; double sumY = 0.0 ; for(size_t i = 0 ; i < numberOfNodes ; i++) { Node *nodeI = this -> giveNode(i+1); double xI = nodeI->giveCoordinate(1); double yI = nodeI->giveCoordinate(2); sumX += xI ; sumY += yI ; } double xc = sumX/numberOfNodes ; double yc = sumY/numberOfNodes ; return new Mu::Point(xc,yc); } bool Element :: in(Mu::Circle *c) // ****************************** // if at least one node of the receiver belong to the circle c, then // this element is considered locate inside c. { size_t count = 0 ; Mu::Point *p; Node *aNode; for(size_t i = 0 ; i < numberOfNodes ; i++) { aNode = this->giveNode(i+1) ; p = aNode->makePoint(); if(c->in(p)) { count += 1 ; delete p; i = numberOfNodes ; } } return (count != 0)? true:false ; } std::list<Element*> Element :: conflicts(Mu::Circle *c) // **************************************************** // With the help of Cyrille Dunant. { checked = true ; std::list<Element*> ret,temp ; ret.push_back(this); std::list<Element*>* myNeighbors = this->giveNeighboringElements(); for (std::list<Element*>::iterator it = myNeighbors->begin(); it != myNeighbors->end(); it++) { if( ((*it)->checked == false) && ((*it)->in(c))) { temp = (*it)->conflicts(c); ret.insert(ret.end(),temp.begin(),temp.end()); } } return ret ; } bool Element :: intersects(Mu::Circle *c) // ************************************** // Check the intersection between element and circle c // used for determining the annular domain for J integral computation. // 2005-08-10. { std::vector<double> distanceVect ; double radius = c->getRadius() ; double centerX = c->getCenter()->x ; double centerY = c->getCenter()->y ; for(size_t i = 0 ; i < numberOfNodes ; i++) { double x = this->giveNode(i+1)->giveCoordinate(1); double y = this->giveNode(i+1)->giveCoordinate(2); double r = sqrt((x-centerX)*(x-centerX)+(y-centerY)*(y-centerY)); distanceVect.push_back(r-radius); } double max = (*std::max_element(distanceVect.begin(),distanceVect.end())); double min = (*std::min_element(distanceVect.begin(),distanceVect.end())); return ( max*min <= 0 ? true : false ) ; } bool Element::intersects(Mu::Segment *seg) // *************************************** { std::vector<Mu::Point> pts ; for(size_t i = 0 ; i < numberOfNodes ; i++) { Mu::Point *p = this->giveNode(i+1)->makePoint() ; pts.push_back(*p); delete p ; } bool ret = false ; for(size_t i = 0 ; i < pts.size() ; i++) { Mu::Segment s(pts[i],pts[(i+1)%pts.size()]) ; ret = ret || seg->intersects(&s) ; } return ret ; } bool Element :: IsOnEdge(Mu::Point* testPoint) // ******************************************* // This method allows the tip touch element edge or element node // 2005-09-06 { size_t i; std::vector<Mu::Point> pts ; for(i = 0 ; i < numberOfNodes ; i++) { Mu::Point *p = this->giveNode(i+1)->makePoint() ; pts.push_back(*p); delete p ; } bool found = false ; i = 0 ; while( (i < pts.size()) && (!found) ) { Mu::Segment s(pts[i],pts[(i+1)%pts.size()]) ; if(s.on(testPoint)) { std:: cout << " Ah, I found you ! " << std::endl ; found = true ; } i++ ; } return found ; } bool Element :: isWithinMe(Mu::Point *p) // ************************************* // check if p is within the receiver using orientation test. // Used in method PartitionMyself() to detect kink points // 2005-09-06 { double const EPSILON = 0.00000001; double x0 = p->x ; double y0 = p->y ; double delta,x1,y1,x2,y2 ; size_t count = 0; for (size_t i = 1 ; i <= numberOfNodes ; i++) { // coordinates of first node x1 = this->giveNode(i)->giveCoordinate(1); y1 = this->giveNode(i)->giveCoordinate(2); // coordinates of second node if(i != numberOfNodes) { x2 = this->giveNode(i+1)->giveCoordinate(1); y2 = this->giveNode(i+1)->giveCoordinate(2); } else { x2 = this->giveNode(1)->giveCoordinate(1); y2 = this->giveNode(1)->giveCoordinate(2); } delta = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0) ; if (delta > EPSILON) count += 1 ; } return (count == numberOfNodes); } bool Element :: isCoincidentToMyNode(Mu::Point *p) // *********************************************** { for(size_t i = 0 ; i < numberOfNodes ; i++) { Mu::Point *pp = this->giveNode(i+1)->makePoint() ; if( pp == p ) return true ; delete pp ; } return false ; } void Element :: clearChecked() // *************************** // set checked false for the next time checking { checked = false ; } void Element :: printMyEnrItems() // ****************************** // debug only { if(enrichmentItemListOfElem != NULL) { std::cout << " Element " << number << " interacted with " ; for (list<EnrichmentItem*>::iterator it = enrichmentItemListOfElem->begin(); it != enrichmentItemListOfElem->end(); ++it) { (*it)->printYourSelf(); } std::cout << std::endl ; } } /*! RB-SB-2004-10-29 takes a string and appends it with the values of stress for the receiver. Goes to the next line to allow further information to be stored in the string. */ void Element :: exportStressResultsToMatlab(string& theStringStress) // ***************************************************************** { double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0; double val5 = 0.0; double vonMises ; FloatArray* stressveci; for(size_t i = 1 ; i <= this->giveNumberOfGaussPoints(); i++) { stressveci = this->giveGaussPointNumber(i)->giveStressVector(); vonMises = this->giveGaussPointNumber(i)->computeVonMisesStress();//NVP 2005 assert(stressveci->giveSize() == 4); val1 = stressveci->at(1); val2 = stressveci->at(2); val3 = stressveci->at(3); val4 = stressveci->at(4); val5 = vonMises ; //NVP 2005 char val1c[50]; char val2c[50]; char val3c[50]; char val4c[50]; char val5c[50]; //NVP 2005 _gcvt( val1, 17, val1c ); _gcvt( val2, 17, val2c ); _gcvt( val3, 17, val3c ); _gcvt( val4, 17, val4c ); _gcvt( val5, 17, val5c ); //NVP 2005 string space(" "); string newline("\n"); string valString; valString += val1c; valString += space; valString += val2c; valString += space; valString += val3c; valString += space; valString += val4c; valString += space; valString += val5c; valString += newline; theStringStress += valString; } } /*! RB-SB-2004-10-29 takes a string and appends it with the values of strain for all of the receiver's Gauss points. Goes to the next line to allow further information to be stored in the string. Results are written as for GAUSS POINT 1 : on row 1 : sigmaxx sigmayy sigmaxy sigmazz ... for GAUSS POINT N : on row N : sigmaxx sigmayy sigmaxy sigmazz N is the number of Gauss points of the receiver. */ void Element :: exportStrainResultsToMatlab(string& theStringStrain) // ***************************************************************** { double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0;//values FloatArray* strainveci;//strain vector int ngp = this->giveNumberOfGaussPoints();//number of Gauss points GaussPoint* gp;//Gauss point TimeStep* stepN = this->domain->giveTimeIntegrationScheme()->giveCurrentStep();//current step for (size_t i = 1 ; i <= ngp ; i++) { gp = this->giveGaussPointNumber(i); //get Gauss point number i this->computeStrainVector(gp,stepN); //compute the strain vector to make sure its value exists strainveci = this->giveGaussPointNumber(i)->giveStrainVector();//get the strain vector assert(strainveci->giveSize() == 4); //make sure it's ok val1 = strainveci->at(1); //get the values of the strains val2 = strainveci->at(2); val3 = strainveci->at(3); val4 = strainveci->at(4); char val1c[50]; //for transformation into chars and strings char val2c[50]; char val3c[50]; char val4c[50]; _gcvt( val1, 17, val1c );//transform the values val1... into chars val1c taking 14 digits _gcvt( val2, 17, val2c ); _gcvt( val3, 17, val3c ); _gcvt( val4, 17, val4c ); string space(" ");//define some useful strings for output string newline("\n"); string valString; valString += val1c;//concatenate the strings together valString +=space; valString += val2c; valString +=space; valString += val3c; valString +=space; valString += val4c; valString +=newline; //final string composed of the four values of the strains at the Gauss point theStringStrain+=valString;//the final, modified, string used for output } } /*! RB-SB-2004-10-29 Returns the global coordinates of the Gauss points of the receiver. */ void Element :: exportGaussPointsToMatlab(string& theString) { GaussPoint* gp; //Gauss point FloatMatrix* N; //array of shape functions FloatArray* XI; //array of nodal coordinates FloatArray* globalCoords; //array of global coords. //double weight = 0. ; // total weight of Gauss points, for debug only. NVP 2005-07-28 char value[30]; string space(" "); string newline("\n"); for (size_t k = 1 ; k <= this->giveNumberOfGaussPoints() ; k++) { gp = this->giveGaussPointNumber(k); //weight += gp->giveWeight(); N = this->ComputeNmatrixAt(gp); XI = this->ComputeGlobalNodalCoordinates(); globalCoords = N->Times(XI); _gcvt(globalCoords->at(1),17,value);//transforms the double param1 in char param3 with 14 digits theString+=value; theString+=space; _gcvt(globalCoords->at(2),17,value); theString+=value; theString+=space; theString+=newline; delete N; delete XI; delete globalCoords; } // _gcvt(weight,3,value); //theString+=value; //theString+=space; //Changed by M. Forton 5/11/11 - Uncomment to fix //theString += newline; } /*! RB-SB-2004-10-29 Returns the array of nodal coordinates for an element. The values are stored as follows: [xNode1 yNode1 xNode2 yNode2 ... xNode_numnode yNode_numnode] */ FloatArray* Element :: ComputeGlobalNodalCoordinates() { size_t n = this->giveNumberOfNodes(); FloatArray* result = new FloatArray(2*n); Node* node; for (int k = 1 ; k <= n ; k++) { node = this->giveNode(k); result->at(2*k-1) = node->giveCoordinate(1); result->at(2*k) = node->giveCoordinate(2); } return result; } GaussPoint* Element :: giveGaussPointNumber(int i) // ************************************************ { if (gaussPointArray) { return gaussPointArray[i-1]; } else { printf("Sorry, cannot give Gauss point number %d of element %d \n",i,number); printf("The Gauss Point Array for element %d was never created \n",number); return NULL; exit(0); } } /* void Element :: exportStressPointsToMatlab(string& theStringStress,TimeStep* stepN) // ******************************************************************************** // NVP - 2005-07-19 { double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0; FloatArray *stressveci; this->computeStressPoints(); for (size_t i = 0 ; i < this->giveNumberOfStressPoints(); i++) { stressveci = this->computeStressAt(gpForStressPlot[i],stepN); double II = stressveci->computeInvariantJ2(); double equiStress = sqrt(3.0 * II) ; // equivalent von Mises stress. val1 = stressveci->at(1); val2 = stressveci->at(2); val3 = stressveci->at(3); val4 = stressveci->at(4); double val5 = equiStress ; char val1c[50]; char val2c[50]; char val3c[50]; char val4c[50]; char val5c[50]; _gcvt( val1, 17, val1c ); _gcvt( val2, 17, val2c ); _gcvt( val3, 17, val3c ); _gcvt( val4, 17, val4c ); _gcvt( val5, 17, val5c ); string space(" "); string valString; valString += val1c; valString += space; valString += val2c; valString += space; valString += val3c; valString += space; valString += val4c; valString += space; valString += val5c; valString += space; theStringStress += valString; } string newline("\n"); theStringStress += newline ; }*/ void Element::reinitializeStiffnessMatrix() { delete stiffnessMatrix; stiffnessMatrix = NULL; } void Element::computeNodalLevelSets(EnrichmentItem* enrItem) { GeometryEntity *geo = enrItem->giveMyGeo(); for(size_t i = 0 ; i < numberOfNodes ; i++) { Node *nodeI = this->giveNode(i+1); Mu::Point *p = nodeI->makePoint(); double ls = geo->computeSignedDistanceOfPoint(p); nodeI->setLevelSets(enrItem,ls); } } void Element::updateMaterialID() { if(material == 0) material = 2; else material += 1 ; } void Element :: resolveConflictsInEnrItems() // **************************************** // check if this list contains both a CrackTip and a CrackInterior // then remove the CrackInterior from the list. // functor IsType<CrackTip,EnrichmentItem>() defined generically in file "functors.h" { list<EnrichmentItem*> ::iterator iter1,iter2; iter1=find_if(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),IsType<MaterialInterface,EnrichmentItem>()); iter2=find_if(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),IsType<CrackInterior,EnrichmentItem>()); if (iter1 != enrichmentItemListOfElem->end() && iter2 != enrichmentItemListOfElem->end()) enrichmentItemListOfElem->remove(*iter2); }
28.337997
127
0.612638
7507e24f930050d37452586d5f7b9f3c34743c26
3,581
cpp
C++
src/TitleScene.cpp
ccabrales/ZoneRush
0ded2f31580b9a369b19d59268000cff939e2bbd
[ "MIT" ]
null
null
null
src/TitleScene.cpp
ccabrales/ZoneRush
0ded2f31580b9a369b19d59268000cff939e2bbd
[ "MIT" ]
null
null
null
src/TitleScene.cpp
ccabrales/ZoneRush
0ded2f31580b9a369b19d59268000cff939e2bbd
[ "MIT" ]
null
null
null
#include "TitleScene.h" void TitleScene::setup(){ title.load("ZoneRush2.png"); playButton.load("PlaySelected.png"); exitButton.load("Exit.png"); loadingImage.load("Loading.png"); resetPosition(); selectedIndex = 0; loadState = TITLE; imageDx = -20.0; rightEmitter.setPosition(ofVec3f(ofGetWidth()-1,ofGetHeight()/2.0)); rightEmitter.setVelocity(ofVec3f(-310,0.0)); rightEmitter.posSpread = ofVec3f(0,ofGetHeight()); rightEmitter.velSpread = ofVec3f(120,20); rightEmitter.life = 13; rightEmitter.lifeSpread = 0; rightEmitter.numPars = 3; rightEmitter.size = 12; rightEmitter.color = ofColor(100,100,200); rightEmitter.colorSpread = ofColor(70,70,70); logoEmitter.setPosition(ofVec3f(ofGetWidth()-1, titlePos.y + 50)); logoEmitter.posSpread = ofVec3f(0, -60); logoEmitter.setVelocity(ofVec3f(-2810,0.0)); logoEmitter.velSpread = ofVec3f(520,20); logoEmitter.life = 4; logoEmitter.lifeSpread = 3; logoEmitter.numPars = 2; // logoEmitter.size = 12; logoEmitter.color = ofColor(140,140,220); logoEmitter.colorSpread = ofColor(70,70,70); } void TitleScene::resetPosition(){ playPos = ofPoint((ofGetWidth() / 2.0) - (playButton.getWidth() / 2.0), 3 * ofGetHeight() / 5.0); exitPos = ofPoint((ofGetWidth() / 2.0) - (exitButton.getWidth() / 2.0), playPos.y+playButton.getHeight() + 10.0); titlePos = ofPoint((ofGetWidth() / 2.0) - (title.getWidth() / 2.0), ofGetHeight() / 5.0); loadingPos = ofPoint(ofGetWidth(), (ofGetHeight() / 2.0) - loadingImage.getHeight()); } void TitleScene::update(){ selectedIndex = 1 - selectedIndex; //Swap between 0 and 1 for the selected index switch (selectedIndex) { case 0: playButton.load("PlaySelected.png"); exitButton.load("Exit.png"); break; case 1: playButton.load("Play.png"); exitButton.load("ExitSelected.png"); break; default: break; } } void TitleScene::backgroundUpdate(const Track::Data* data, ofxParticleSystem* particleSystem){ if (loadState == TRANSITION) { //update titlePos.x += imageDx; playPos.x += imageDx; exitPos.x += imageDx; loadingPos.x += imageDx; if (loadingPos.x <= ((ofGetWidth() / 2.0) - (loadingImage.getWidth() / 2.0)) ) { loadState = LOAD; //finished transition } } else if (loadState == TOGAME) { loadingPos.x += imageDx; if (loadingPos.x <= (-loadingImage.getWidth())) loadState = END; } rightEmitter.numPars = max((int)(data->intensity*20) + (data->onBeat?12:0), 2); rightEmitter.setVelocity(data->onBeat?ofVec3f(-510,0.0):ofVec3f(-310,0.0)); particleSystem->addParticles(logoEmitter); particleSystem->addParticles(rightEmitter); } void TitleScene::draw(){ ofPushStyle(); if (loadState == TITLE || loadState == TRANSITION) { title.draw(titlePos); playButton.draw(playPos); exitButton.draw(exitPos); } if (loadState != TITLE || loadState != END) loadingImage.draw(loadingPos); ofPopStyle(); } void TitleScene::windowResized(int w, int h) { resetPosition(); } bool TitleScene::isPlaySelected() { return selectedIndex == 0; } //Toggle the variable flag void TitleScene::setLoading(LoadState state) { loadState = state; if (loadState == TITLE) resetPosition(); } TitleScene::LoadState TitleScene::getCurrentState() { return loadState; }
29.352459
117
0.63055
7508f423ff4f2dd47d6703130584e1bc6a1e2d1d
3,347
cpp
C++
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
VBota1/project_booking
13337130e1294df43c243cf1df53edfa736c42b7
[ "MIT" ]
null
null
null
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
VBota1/project_booking
13337130e1294df43c243cf1df53edfa736c42b7
[ "MIT" ]
2
2019-03-01T09:25:32.000Z
2019-03-01T09:26:08.000Z
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
VBota1/project_booking
13337130e1294df43c243cf1df53edfa736c42b7
[ "MIT" ]
null
null
null
#include "reports.h" Reports::Reports(QTreeWidget *month,QListWidget *standard,QListWidget *project,QLabel *current,StatusDisplay *statusWidget) { monthReport=month; standardReport=standard; projectReport=project; currentProject=current; statusDisplay = statusWidget; } void Reports::updateMonthReport(BackendHandler backend, int month){ monthReport->clear(); Result< QList<Data> > report = backend.reportForMonth(month); if (report.hasError) { statusDisplay->update(report.err()); return; } Data day; foreach (day,report.ok()) { QTreeWidgetItem *dayItem = new QTreeWidgetItem(monthReport); monthReport->addTopLevelItem(dayItem); dayItem->setText(0,day.date); TaskDay task; foreach (task,day.tasks) { QTreeWidgetItem *taskItem = new QTreeWidgetItem(dayItem); taskItem->setText(0,task.task); QTreeWidgetItem *timeItem = new QTreeWidgetItem(taskItem); timeItem->setText(0,"time_spent: " + task.time_spent); QTreeWidgetItem *labelCollectionItem = new QTreeWidgetItem(taskItem); labelCollectionItem->setText(0,"labels"); QString label; foreach (label, task.labels) { QTreeWidgetItem *labelItem = new QTreeWidgetItem(labelCollectionItem); labelItem->setText(0, label); } } } } void Reports::updateStandardReport(BackendHandler backend) { standardReport->clear(); Result< QList<TaskReport> > report = backend.standardReport(); if (report.hasError) { statusDisplay->update(report.err()); return; } updateCurrentProject("None"); TaskReport task; foreach (task,report.ok()){ QString taskText = "name: " + task.name.leftJustified(30,' ',true) + "\t time: " + task.time_spent + "\t labels:"; QString label; foreach(label,task.labels) taskText.append(" "+label); if(task.clock_in_timestamp!="None") { taskText.append("\t clockedIn: "+task.clock_in_timestamp); updateCurrentProject(task); } standardReport->addItem(taskText); } } void Reports::updateCurrentProject(TaskReport task) { QString taskText = task.name + "\t labels:"; QString label; foreach(label,task.labels) taskText.append(" "+label); updateCurrentProject(taskText); } void Reports::updateCurrentProject(QString task) { currentProject->setText("Active Project: "+task); currentProject->update(); } void Reports::updateProjectReport(BackendHandler backend) { projectReport->clear(); Result< QList<LabelReport> > report = backend.projectLabelReport(); if (report.hasError) { statusDisplay->update(report.err()); return; } LabelReport project; foreach(project,report.ok()) { QString projectText = "project: " + project.label.leftJustified(30,' ',true) + "\t time: " + project.time_spent; projectReport->addItem(projectText); } } void Reports::refresh(){ BackendHandler backend; updateMonthReport(backend, QDate::currentDate().month()); updateStandardReport(backend); updateProjectReport(backend); }
27.211382
125
0.632805
75097d8a49eeac251bc1667c6a93628f398378e3
274
hpp
C++
modules/spdlog/shiva/spdlog/spdlog.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
176
2018-06-06T12:20:21.000Z
2022-01-27T02:54:34.000Z
modules/spdlog/shiva/spdlog/spdlog.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
11
2018-06-09T21:30:02.000Z
2019-09-14T16:03:12.000Z
modules/spdlog/shiva/spdlog/spdlog.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
19
2018-08-15T11:40:02.000Z
2020-08-31T11:00:44.000Z
// // Created by roman Sztergbaum on 19/06/2018. // #pragma once #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> namespace shiva { namespace log = spdlog; } namespace shiva::logging { using logger = std::shared_ptr<shiva::log::logger>; }
14.421053
55
0.70073
7509db9a401daf1896cb04c933a014f57817ff92
362
hpp
C++
sources/dansandu/chocolate/interpolation.hpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
sources/dansandu/chocolate/interpolation.hpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
sources/dansandu/chocolate/interpolation.hpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
#pragma once #include "dansandu/chocolate/common.hpp" namespace dansandu::chocolate::interpolation { Vector3 interpolate(const Vector3& a, const Vector3& b, const float x, const float y, const float epsilon); Vector3 interpolate(const Vector3& a, const Vector3& b, const Vector3& c, const float x, const float y, const float epsilon); }
25.857143
107
0.720994
750c844815ad49209ee37371cb7a5b86dea0d376
4,486
hxx
C++
include/opengm/learning/gridsearch-learning.hxx
chaubold/opengm
acc42b98b713db33f2b35aad05a7a1cf9752e862
[ "MIT" ]
null
null
null
include/opengm/learning/gridsearch-learning.hxx
chaubold/opengm
acc42b98b713db33f2b35aad05a7a1cf9752e862
[ "MIT" ]
null
null
null
include/opengm/learning/gridsearch-learning.hxx
chaubold/opengm
acc42b98b713db33f2b35aad05a7a1cf9752e862
[ "MIT" ]
null
null
null
#pragma once #ifndef OPENGM_GRIDSEARCH_LEARNER_HXX #define OPENGM_GRIDSEARCH_LEARNER_HXX #include <vector> namespace opengm { namespace learning { template<class DATASET> class GridSearchLearner { public: typedef DATASET DatasetType; typedef typename DATASET::GMType GMType; typedef typename DATASET::LossType LossType; typedef typename GMType::ValueType ValueType; typedef typename GMType::IndexType IndexType; typedef typename GMType::LabelType LabelType; class Parameter{ public: std::vector<double> parameterUpperbound_; std::vector<double> parameterLowerbound_; std::vector<size_t> testingPoints_; Parameter(){;} }; GridSearchLearner(DATASET&, const Parameter& ); template<class INF> void learn(const typename INF::Parameter& para); //template<class INF, class VISITOR> //void learn(typename INF::Parameter para, VITITOR vis); const opengm::learning::Weights<double>& getWeights(){return weights_;} Parameter& getLerningParameters(){return para_;} private: DATASET& dataset_; opengm::learning::Weights<double> weights_; Parameter para_; }; template<class DATASET> GridSearchLearner<DATASET>::GridSearchLearner(DATASET& ds, const Parameter& p ) : dataset_(ds), para_(p) { weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights()); if(para_.parameterUpperbound_.size() != ds.getNumberOfWeights()) para_.parameterUpperbound_.resize(ds.getNumberOfWeights(),10.0); if(para_.parameterLowerbound_.size() != ds.getNumberOfWeights()) para_.parameterLowerbound_.resize(ds.getNumberOfWeights(),0.0); if(para_.testingPoints_.size() != ds.getNumberOfWeights()) para_.testingPoints_.resize(ds.getNumberOfWeights(),10); } template<class DATASET> template<class INF> void GridSearchLearner<DATASET>::learn(const typename INF::Parameter& para){ // generate model Parameters opengm::learning::Weights<double> modelPara( dataset_.getNumberOfWeights() ); opengm::learning::Weights<double> bestModelPara( dataset_.getNumberOfWeights() ); double bestLoss = std::numeric_limits<double>::infinity(); std::vector<size_t> itC(dataset_.getNumberOfWeights(),0); bool search=true; while(search){ // Get Parameter for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ modelPara.setWeight(p, para_.parameterLowerbound_[p] + double(itC[p])/double(para_.testingPoints_[p]-1)*(para_.parameterUpperbound_[p]-para_.parameterLowerbound_[p]) ); } // Evaluate Loss opengm::learning::Weights<double>& mp = dataset_.getWeights(); mp = modelPara; const double loss = dataset_. template getTotalLoss<INF>(para); // ************** if(loss<bestLoss){ // *call visitor* for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ std::cout << modelPara[p] <<" "; } std::cout << " ==> "; std::cout << loss << std::endl; bestLoss=loss; bestModelPara=modelPara; if(loss<=0.000000001){ search = false; } } //Increment Parameter for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ if(itC[p]<para_.testingPoints_[p]-1){ ++itC[p]; break; } else{ itC[p]=0; if (p==dataset_.getNumberOfWeights()-1) search = false; } } } std::cout << "Best"<<std::endl; for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ std::cout << bestModelPara[p] <<" "; } std::cout << " ==> "; std::cout << bestLoss << std::endl; weights_ = bestModelPara; // save best weights in dataset for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ dataset_.getWeights().setWeight(p, weights_[p]); } }; } } #endif
35.322835
183
0.56041
750cfaefd4746b7cea1bfd20de616b38d29defa8
4,698
cpp
C++
google/code_jam/2020/r3/pen_testing.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
google/code_jam/2020/r3/pen_testing.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
google/code_jam/2020/r3/pen_testing.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
#include "common/hash.h" #include "common/stl/base.h" #include "common/stl/hash/vector.h" #include "common/vector/enumerate.h" #include "common/vector/mask.h" #include <unordered_map> namespace { static const unsigned N = 15; class CompactState { public: unsigned l; uint64_t mask; vector<unsigned> vc; CompactState() { l = N; mask = (1ull << N) - 1; vc.resize(l, 0); } bool operator==(const CompactState& r) const { return (mask == r.mask) && (vc == r.vc); } }; } // namespace namespace std { template <> struct hash<CompactState> { size_t operator()(const CompactState& s) const { hash<vector<unsigned>> h; return HashCombine(h(s.vc), s.mask); } }; } // namespace std namespace { class Solver { public: unordered_map<CompactState, pair<double, unsigned>> m; uint64_t Count(const CompactState& s) { uint64_t r = 1; auto v = nvector::MaskToVector(s.mask); assert(v.size() == s.l); unsigned k = s.l; for (unsigned i = 0; i < s.l; ++i) { for (; (k > 0) && (v[k - 1] >= s.vc[i]);) --k; r *= (s.l - i - k); } return r; } double P2(const CompactState& s) { assert(s.l == 2); unsigned ss = 0; for (unsigned i = 0; i < N; ++i) { if (s.mask & (1ull << i)) ss += i; } for (auto c : s.vc) ss -= c; return (ss >= N) ? 1.0 : 0.; } bool GaveUp(const CompactState& s) const { auto v = nvector::MaskToVector(s.mask); assert(v.size() == s.l); unsigned ss = v[s.l - 1] + v[s.l - 2] - s.vc[s.l - 1] - s.vc[s.l - 2]; return ss < N; } double P(const CompactState& s) { assert(s.l >= 2); auto it = m.find(s); if (it != m.end()) return it->second.first; double p = 0; unsigned r = N; if (s.l == 2) { p = P2(s); } else if (!GaveUp(s)) { CompactState st(s); uint64_t sc = Count(st); for (unsigned i = 0; i < s.l; ++i) { if ((i > 0) && (s.vc[i - 1] == s.vc[i])) continue; unsigned k = 0, j = 0; for (; j < s.vc[i]; ++j) { if (s.mask & (1ull << j)) ++k; } for (;; ++j) { if (s.mask & (1ull << j)) break; } if ((i > 0) && (j >= s.vc[i - 1])) continue; unsigned c = s.vc[i]; st.vc[i] = j + 1; uint64_t scn = Count(st); double q1 = double(scn) / double(sc); double pc = ((q1 > 0) ? q1 * P(st) : 0.); st.vc[i] = c; st.mask &= ~(1ull << j); st.l -= 1; st.vc.erase(st.vc.begin() + i); pc += (1 - q1) * P(st); st.vc.insert(st.vc.begin() + i, c); st.l += 1; st.mask |= (1ull << j); if (p < pc) { p = pc; r = i; } } } m[s] = make_pair(p, r); return p; } public: unsigned Request(const CompactState& s) { // if (s.l > (N + 3) / 2) return 0; // We never output first elements if (s.l > 6) return 0; // Trade off between performance and quality P(s); return m[s].second; } size_t MapSize() const { return m.size(); } }; class FullState : public CompactState { public: vector<unsigned> vp; FullState() { vp = nvector::Enumerate<unsigned>(1, N + 1); } }; class SolverProxy { protected: Solver& s; FullState fs; unsigned last_request; public: SolverProxy(Solver& _s) : s(_s), last_request(N) {} double P() { return s.P(fs); } unsigned Request() { last_request = s.Request(fs); return (last_request == N) ? 0 : fs.vp[last_request]; } void Update(unsigned result) { if (last_request != N) { if (result) { fs.vc[last_request] += 1; } else { unsigned k = fs.vc[last_request]; fs.l -= 1; assert(fs.mask & (1ull << k)); fs.mask &= ~(1ull << k); fs.vc.erase(fs.vc.begin() + last_request); fs.vp.erase(fs.vp.begin() + last_request); } } } unsigned Get1() const { return fs.vp[fs.l - 2]; } unsigned Get2() const { return fs.vp[fs.l - 1]; } }; } // namespace int main_pen_testing() { Solver s; unsigned T, t1, t2; cin >> T >> t1 >> t2; // cerr << s.P(CompactState()) * T << " " << s.MapSize() << endl; std::vector<SolverProxy> vs(T, SolverProxy(s)); bool all_zero = false; for (unsigned it = 1; !all_zero; ++it) { all_zero = true; for (SolverProxy& s : vs) { unsigned u = s.Request(); if (u) all_zero = false; cout << u << " "; } cout << endl; if (all_zero) { for (SolverProxy& s : vs) { cout << s.Get1() << " " << s.Get2() << " "; } cout << endl; } else { for (SolverProxy& s : vs) { cin >> t1; s.Update(t1); } } } return 0; }
23.373134
74
0.504683
750e33686e6c97f42691a16b2d3c80c696e33a99
2,984
cpp
C++
C++/hoffman_encoding.cpp
evidawei/HacktoberFest_2021
3c950c6a6451ac732c4090f374c7dc4b6ef36c50
[ "MIT" ]
null
null
null
C++/hoffman_encoding.cpp
evidawei/HacktoberFest_2021
3c950c6a6451ac732c4090f374c7dc4b6ef36c50
[ "MIT" ]
null
null
null
C++/hoffman_encoding.cpp
evidawei/HacktoberFest_2021
3c950c6a6451ac732c4090f374c7dc4b6ef36c50
[ "MIT" ]
1
2021-10-11T14:05:10.000Z
2021-10-11T14:05:10.000Z
#include <bits/stdc++.h> using namespace std; #define EMPTY_STRING "" struct Node { char ch; int freq; Node *left, *right; }; Node* getNode(char ch, int freq, Node* left, Node* right) { Node* node = new Node(); node->ch = ch; node->freq = freq; node->left = left; node->right = right; return node; } struct comp { bool operator()(const Node* l, const Node* r) const { return l->freq > r->freq; } }; bool isLeaf(Node* root) { return root->left == nullptr && root->right == nullptr; } void encode(Node* root, string str, unordered_map<char, string> &huffmanCode) { if (root == nullptr) { return; } if (isLeaf(root)) { huffmanCode[root->ch] = (str != EMPTY_STRING) ? str : "1"; } encode(root->left, str + "0", huffmanCode); encode(root->right, str + "1", huffmanCode); } void decode(Node* root, int &index, string str) { if (root == nullptr) { return; } if (isLeaf(root)) { cout << root->ch; return; } index++; if (str[index] == '0') { decode(root->left, index, str); } else { decode(root->right, index, str); } } void buildHuffmanTree(string text) { if (text == EMPTY_STRING) { return; } unordered_map<char, int> freq; for (char ch: text) { freq[ch]++; } priority_queue<Node*, vector<Node*>, comp> pq; for (auto pair: freq) { pq.push(getNode(pair.first, pair.second, nullptr, nullptr)); } while (pq.size() != 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); int sum = left->freq + right->freq; pq.push(getNode('\0', sum, left, right)); } Node* root = pq.top(); unordered_map<char, string> huffmanCode; encode(root, EMPTY_STRING, huffmanCode); cout << "Huffman Codes are:\n" << endl; for (auto pair: huffmanCode) { cout << pair.first << " " << pair.second << endl; } cout << "\nThe original string is:\n" << text << endl; string str; for (char ch: text) { str += huffmanCode[ch]; } cout << "\nThe encoded string is:\n" << str << endl; cout << "\nThe decoded string is:\n"; if (isLeaf(root)) { // Special case: For input like a, aa, aaa, etc. while (root->freq--) { cout << root->ch; } } else { // Traverse the Huffman Tree again and this time, // decode the encoded string int index = -1; while (index < (int)str.size() - 1) { decode(root, index, str); } } } // Huffman coding algorithm implementation in C++ int main() { string text = "Huffman coding is a data compression algorithm."; buildHuffmanTree(text); return 0; }
22.778626
78
0.510054
7511d416a4978fcd2aa044fd577ad9edd11ae6b8
1,495
hpp
C++
libcaf_core/caf/flow/step/map.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/flow/step/map.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/flow/step/map.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/detail/type_traits.hpp" #include "caf/fwd.hpp" #include <utility> namespace caf::flow::step { template <class F> class map { public: using trait = detail::get_callable_trait_t<F>; static_assert(!std::is_same_v<typename trait::result_type, void>, "map functions may not return void"); static_assert(trait::num_args == 1, "map functions must take exactly one argument"); using input_type = std::decay_t<detail::tl_head_t<typename trait::arg_types>>; using output_type = std::decay_t<typename trait::result_type>; explicit map(F fn) : fn_(std::move(fn)) { // nop } map(map&&) = default; map(const map&) = default; map& operator=(map&&) = default; map& operator=(const map&) = default; template <class Next, class... Steps> bool on_next(const input_type& item, Next& next, Steps&... steps) { return next.on_next(fn_(item), steps...); } template <class Next, class... Steps> void on_complete(Next& next, Steps&... steps) { next.on_complete(steps...); } template <class Next, class... Steps> void on_error(const error& what, Next& next, Steps&... steps) { next.on_error(what, steps...); } private: F fn_; }; } // namespace caf::flow::step
25.775862
80
0.671572
75138d319658400837893d58e2aee8f95eb1f383
1,081
hpp
C++
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file reverse.hpp * * @brief reverse の定義 * * @author myoukaku */ #ifndef BKSGE_FND_ALGORITHM_REVERSE_HPP #define BKSGE_FND_ALGORITHM_REVERSE_HPP #include <bksge/fnd/algorithm/config.hpp> #if defined(BKSGE_USE_STD_ALGORITHM) #include <algorithm> namespace bksge { using std::reverse; } // namespace bksge #else #include <bksge/fnd/algorithm/iter_swap.hpp> #include <bksge/fnd/config.hpp> namespace bksge { /** * @brief 要素の並びを逆にする。 * * @tparam BidirectionalIterator * * @param first * @param last * * @require *first は Swappable でなければならない * * @effect 0 以上 (last - first) / 2 未満の整数 i について、 * iter_swap(first + i, (last - i) - 1) を行う * * @complexity 正確に (last - first) / 2 回 swap する */ template <typename BidirectionalIterator> inline void reverse( BidirectionalIterator first, BidirectionalIterator last) { for (; first != last && first != --last; ++first) { bksge::iter_swap(first, last); } } } // namespace bksge #endif #endif // BKSGE_FND_ALGORITHM_REVERSE_HPP
16.630769
51
0.650324
7518a26a3f9a48b498a5a0f719682f3753612846
3,880
cc
C++
src/tot_compare.cc
Mu2e/TrackerMCTune
6472497f9359b33a236d47f39192a7faffc71dae
[ "Apache-2.0" ]
null
null
null
src/tot_compare.cc
Mu2e/TrackerMCTune
6472497f9359b33a236d47f39192a7faffc71dae
[ "Apache-2.0" ]
1
2021-12-03T14:37:41.000Z
2021-12-03T14:37:41.000Z
src/tot_compare.cc
Mu2e/TrackerMCTune
6472497f9359b33a236d47f39192a7faffc71dae
[ "Apache-2.0" ]
2
2019-10-31T18:17:00.000Z
2021-11-22T21:43:02.000Z
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <stdlib.h> #include <vector> #include <TFile.h> #include <TTree.h> #include <TH1F.h> #include <TH2F.h> #include <TF1.h> #include <TCanvas.h> #include <TLegend.h> #include <TApplication.h> #include <TLatex.h> #include <TLine.h> #include <TPaveText.h> #include <TMath.h> #include <TProfile.h> int main(int argc, char** argv) { std::string filename[2]; filename[0] = ""; filename[1] = ""; std::string help = "./tot_compare -d <data filename> -s <sim filename>"; std::string inputcommand = std::string(argv[0]); for (int i=1;i<argc;i++) inputcommand += " " + std::string(argv[i]); int c; while ((c = getopt (argc, argv, "hd:s:")) != -1){ switch (c){ case 'h': std::cout << help << std::endl; return 0; case 'd': filename[0] = std::string(optarg); break; case 's': filename[1] = std::string(optarg); break; case '?': if (optopt == 'd' || optopt == 's') std::cout << "Option -" << optopt << " requires an argument." << std::endl; else std::cout << "Unknown option `-" << optopt << "'." << std::endl; return 1; } } if (filename[0].size() == 0 && filename[1].size() == 0 && optind == argc-2){ for (int index = optind; index < argc; index++){ filename[index-optind] = std::string(argv[index]); } } if (filename[0].size() == 0 || filename[1].size() == 0){ std::cout << help << std::endl; return 1; } int argc2 = 0;char **argv2;TApplication theApp("tapp", &argc2, argv2); std::vector<double> times[2]; std::vector<double> docas[2]; std::vector<double> tots[2]; TH2F* h[2]; for (int ifile=0;ifile<2;ifile++){ TFile *f = new TFile(filename[ifile].c_str()); TTree *t = (TTree*) f->Get("tot"); double t_time, t_tot, t_doca; t->SetBranchAddress("tot",&t_tot); t->SetBranchAddress("time",&t_time); t->SetBranchAddress("doca",&t_doca); for (int i=0;i<t->GetEntries();i++){ t->GetEntry(i); tots[ifile].push_back(t_tot); times[ifile].push_back(t_time); docas[ifile].push_back(t_doca); } h[ifile] = new TH2F(TString::Format("tot_%d",ifile),"tot",32,0,64,120,-20,100); for (int j=0;j<tots[ifile].size();j++){ if (docas[ifile][j] < 2.5) h[ifile]->Fill(tots[ifile][j],times[ifile][j]); } } TCanvas *cscatter = new TCanvas("cscatter","scatter",600,600); h[0]->SetStats(0); h[0]->SetTitle(""); h[0]->GetXaxis()->SetTitle("Time over threshold (ns)"); h[0]->GetYaxis()->SetTitle("Drift time (ns)"); h[0]->Draw(); h[1]->SetMarkerColor(kRed); h[1]->Draw("same"); TLegend *l = new TLegend(0.55,0.65,0.85,0.85); l->AddEntry(h[0],"8-Straw Prototype Data","P"); l->AddEntry(h[1],"G4 + Straw Simulation","P"); l->SetBorderSize(0); l->Draw(); TCanvas *chist = new TCanvas("chist","chist",600,600); TProfile *hdata = (TProfile*) h[0]->ProfileX("hdata",1,-1,"S"); TProfile *hsim = (TProfile*) h[1]->ProfileX("hsim",1,-1,"S"); hdata->SetLineColor(kBlue); hdata->SetTitle(""); hdata->SetStats(0); hdata->GetXaxis()->SetTitle("Time over threshold (ns)"); hdata->GetYaxis()->SetTitle("Drift time (ns)"); hdata->SetMarkerStyle(22); // hdata->GetXaxis()->SetRangeUser(4,50); hdata->Draw(); hsim->SetLineColor(kRed); hsim->SetFillColor(kRed); hsim->SetMarkerColor(kRed); hsim->SetFillStyle(3001); hsim->Draw("same E2"); TProfile *hsim2 = (TProfile*) hsim->Clone("hsim2"); hsim2->SetLineColor(kRed); hsim2->SetFillStyle(0); hsim2->Draw("hist same"); TLegend *l2 = new TLegend(0.55,0.65,0.85,0.85); l2->AddEntry(hdata,"8-Straw Prototype Data","PL"); l2->AddEntry(hsim,"G4 + Straw Simulation","FL"); l2->SetBorderSize(0); l2->Draw(); theApp.Run(); return 0; }
26.575342
85
0.584794
75190d8b3eaf38c7736806ffc0e6b19f972a5745
12,435
cpp
C++
viewer/sokol_imgui.cpp
JCash/dungeonmaker
c64a90bdf1cff79d69f32ea6a8f219bb9daba7d9
[ "MIT" ]
4
2018-08-27T05:31:58.000Z
2018-09-01T00:02:29.000Z
viewer/sokol_imgui.cpp
JCash/dungeonmaker
c64a90bdf1cff79d69f32ea6a8f219bb9daba7d9
[ "MIT" ]
null
null
null
viewer/sokol_imgui.cpp
JCash/dungeonmaker
c64a90bdf1cff79d69f32ea6a8f219bb9daba7d9
[ "MIT" ]
null
null
null
#include "imgui.h" #if defined(__APPLE__) #define SOKOL_METAL #elif defined(WIN32) #define SOKOL_D3D11 #elif defined(__EMSCRIPTEN__) #define SOKOL_GLES2 #else #error "No GFX Backend Specified" #endif #define SOKOL_IMPL #include "sokol_app.h" #include "sokol_gfx.h" #include "sokol_time.h" #include <stdio.h> const int MaxVertices = (1<<16); const int MaxIndices = MaxVertices * 3; extern const char* vs_src_imgui; extern const char* fs_src_imgui; static sg_draw_state draw_state = { }; ImDrawVert vertices[MaxVertices]; uint16_t indices[MaxIndices]; typedef struct { ImVec2 disp_size; } vs_params_t; void imgui_sokol_event(const sapp_event* e) { switch (e->type) { case SAPP_EVENTTYPE_KEY_DOWN: ImGui::GetIO().KeysDown[e->key_code] = true; break; case SAPP_EVENTTYPE_KEY_UP: ImGui::GetIO().KeysDown[e->key_code] = false; break; case SAPP_EVENTTYPE_CHAR: ImGui::GetIO().AddInputCharacter(e->char_code); break; case SAPP_EVENTTYPE_MOUSE_DOWN: ImGui::GetIO().MouseDown[e->mouse_button] = true; break; case SAPP_EVENTTYPE_MOUSE_UP: ImGui::GetIO().MouseDown[e->mouse_button] = false; break; case SAPP_EVENTTYPE_MOUSE_SCROLL: ImGui::GetIO().MouseWheel = 0.25f * e->scroll_y; break; case SAPP_EVENTTYPE_MOUSE_MOVE: ImGui::GetIO().MousePos = ImVec2(e->mouse_x, e->mouse_y); break; default: break; } } static void imgui_draw_cb(ImDrawData* draw_data); void imgui_setup() { // setup the imgui environment ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = 0; io.RenderDrawListsFn = imgui_draw_cb; io.Fonts->AddFontDefault(); io.KeyMap[ImGuiKey_Tab] = SAPP_KEYCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SAPP_KEYCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SAPP_KEYCODE_RIGHT; io.KeyMap[ImGuiKey_DownArrow] = SAPP_KEYCODE_DOWN; io.KeyMap[ImGuiKey_UpArrow] = SAPP_KEYCODE_UP; io.KeyMap[ImGuiKey_Home] = SAPP_KEYCODE_HOME; io.KeyMap[ImGuiKey_End] = SAPP_KEYCODE_END; io.KeyMap[ImGuiKey_Delete] = SAPP_KEYCODE_DELETE; io.KeyMap[ImGuiKey_Backspace] = SAPP_KEYCODE_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SAPP_KEYCODE_ENTER; io.KeyMap[ImGuiKey_Escape] = SAPP_KEYCODE_ESCAPE; // io.KeyMap[ImGuiKey_A] = 0x00; // io.KeyMap[ImGuiKey_C] = 0x08; // io.KeyMap[ImGuiKey_V] = 0x09; // io.KeyMap[ImGuiKey_X] = 0x07; // io.KeyMap[ImGuiKey_Y] = 0x10; // io.KeyMap[ImGuiKey_Z] = 0x06; // // OSX => ImGui input forwarding // osx_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); }); // osx_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; }); // osx_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; }); // osx_mouse_wheel([] (float v) { ImGui::GetIO().MouseWheel = 0.25f * v; }); // osx_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; }); // osx_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; }); // osx_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); }); // dynamic vertex- and index-buffers for ImGui-generated geometry sg_buffer_desc vbuf_desc = { .usage = SG_USAGE_STREAM, .size = sizeof(vertices) }; draw_state.vertex_buffers[0] = sg_make_buffer(&vbuf_desc); sg_buffer_desc ibuf_desc = { .type = SG_BUFFERTYPE_INDEXBUFFER, .usage = SG_USAGE_STREAM, .size = sizeof(indices) }; draw_state.index_buffer = sg_make_buffer(&ibuf_desc); // font texture for ImGui's default font unsigned char* font_pixels; int font_width, font_height; io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); sg_image_desc img_desc = { .width = font_width, .height = font_height, .pixel_format = SG_PIXELFORMAT_RGBA8, .wrap_u = SG_WRAP_CLAMP_TO_EDGE, .wrap_v = SG_WRAP_CLAMP_TO_EDGE, .min_filter = SG_FILTER_LINEAR, .mag_filter = SG_FILTER_LINEAR, .content.subimage[0][0] = { .ptr = font_pixels, .size = font_width * font_height * 4 } }; draw_state.fs_images[0] = sg_make_image(&img_desc); // shader object for imgui renering sg_shader_desc shd_desc = { .vs.uniform_blocks[0].size = sizeof(vs_params_t), .vs.uniform_blocks[0].uniforms[0].name = "disp_size", .vs.uniform_blocks[0].uniforms[0].type = SG_UNIFORMTYPE_FLOAT2, .vs.source = vs_src_imgui, .fs.images[0].type = SG_IMAGETYPE_2D, .fs.images[0].name = "tex", .fs.source = fs_src_imgui, }; sg_shader shd = sg_make_shader(&shd_desc); // pipeline object for imgui rendering sg_pipeline_desc pip_desc = { .layout = { .buffers[0].stride = sizeof(ImDrawVert), .attrs = { [0] = { .offset=IM_OFFSETOF(ImDrawVert, pos), .format=SG_VERTEXFORMAT_FLOAT2 }, [1] = { .offset=IM_OFFSETOF(ImDrawVert, uv), .format=SG_VERTEXFORMAT_FLOAT2 }, [2] = { .offset=IM_OFFSETOF(ImDrawVert, col), .format=SG_VERTEXFORMAT_UBYTE4N } } }, .shader = shd, .index_type = SG_INDEXTYPE_UINT16, .blend = { .enabled = true, .src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA, .dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA, .color_write_mask = SG_COLORMASK_RGB } }; draw_state.pipeline = sg_make_pipeline(&pip_desc); } static void imgui_draw_cb(ImDrawData* draw_data) { if (draw_data->CmdListsCount == 0) { return; } // copy vertices and indices int num_vertices = 0; int num_indices = 0; int num_cmdlists = 0; for (; num_cmdlists < draw_data->CmdListsCount; num_cmdlists++) { const ImDrawList* cl = draw_data->CmdLists[num_cmdlists]; const int cl_num_vertices = cl->VtxBuffer.size(); const int cl_num_indices = cl->IdxBuffer.size(); // overflow check if ((num_vertices + cl_num_vertices) > MaxVertices) { break; } if ((num_indices + cl_num_indices) > MaxIndices) { break; } // copy vertices memcpy(&vertices[num_vertices], &cl->VtxBuffer.front(), cl_num_vertices*sizeof(ImDrawVert)); // copy indices, need to rebase to start of global vertex buffer const ImDrawIdx* src_index_ptr = &cl->IdxBuffer.front(); const uint16_t base_vertex_index = num_vertices; for (int i = 0; i < cl_num_indices; i++) { indices[num_indices++] = src_index_ptr[i] + base_vertex_index; } num_vertices += cl_num_vertices; } // update vertex and index buffers const int vertex_data_size = num_vertices * sizeof(ImDrawVert); const int index_data_size = num_indices * sizeof(uint16_t); sg_update_buffer(draw_state.vertex_buffers[0], vertices, vertex_data_size); sg_update_buffer(draw_state.index_buffer, indices, index_data_size); // render the command list vs_params_t vs_params; vs_params.disp_size = ImGui::GetIO().DisplaySize; sg_apply_draw_state(&draw_state); sg_apply_uniform_block(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params)); int base_element = 0; for (int cl_index = 0; cl_index < num_cmdlists; cl_index++) { const ImDrawList* cmd_list = draw_data->CmdLists[cl_index]; //for (const ImDrawCmd& cmd : cmd_list->CmdBuffer) { for (size_t i = 0; i < cmd_list->CmdBuffer.size(); ++i) { const ImDrawCmd& cmd = cmd_list->CmdBuffer[i]; if (cmd.UserCallback) { cmd.UserCallback(cmd_list, &cmd); } else { const int sx = (int) cmd.ClipRect.x; const int sy = (int) cmd.ClipRect.y; const int sw = (int) (cmd.ClipRect.z - cmd.ClipRect.x); const int sh = (int) (cmd.ClipRect.w - cmd.ClipRect.y); sg_apply_scissor_rect(sx, sy, sw, sh, true); sg_draw(base_element, cmd.ElemCount, 1); } base_element += cmd.ElemCount; } } } void imgui_teardown() { ImGui::DestroyContext(); } #if defined(SOKOL_GLCORE33) const char* vs_src_imgui = "#version 330\n" "uniform vec2 disp_size;\n" "in vec2 position;\n" "in vec2 texcoord0;\n" "in vec4 color0;\n" "out vec2 uv;\n" "out vec4 color;\n" "void main() {\n" " gl_Position = vec4(((position/disp_size)-0.5)*vec2(2.0,-2.0), 0.5, 1.0);\n" " uv = texcoord0;\n" " color = color0;\n" "}\n"; const char* fs_src_imgui = "#version 330\n" "uniform sampler2D tex;\n" "in vec2 uv;\n" "in vec4 color;\n" "out vec4 frag_color;\n" "void main() {\n" " frag_color = texture(tex, uv) * color;\n" "}\n"; #elif defined(SOKOL_GLES2) const char* vs_src_imgui = "uniform vec2 disp_size;\n" "attribute vec2 position;\n" "attribute vec2 texcoord0;\n" "attribute vec4 color0;\n" "varying vec2 uv;\n" "varying vec4 color;\n" "void main() {\n" " gl_Position = vec4(((position/disp_size)-0.5)*vec2(2.0,-2.0), 0.5, 1.0);\n" " uv = texcoord0;\n" " color = color0;\n" "}\n"; const char* fs_src_imgui = "precision mediump float;\n" "uniform sampler2D tex;\n" "varying vec2 uv;\n" "varying vec4 color;\n" "void main() {\n" " gl_FragColor = texture2D(tex, uv) * color;\n" "}\n"; #elif defined(SOKOL_GLES3) const char* vs_src_imgui = "#version 300 es\n" "uniform vec2 disp_size;\n" "in vec2 position;\n" "in vec2 texcoord0;\n" "in vec4 color0;\n" "out vec2 uv;\n" "out vec4 color;\n" "void main() {\n" " gl_Position = vec4(((position/disp_size)-0.5)*vec2(2.0,-2.0), 0.5, 1.0);\n" " uv = texcoord0;\n" " color = color0;\n" "}\n"; const char* fs_src_imgui = "#version 300 es\n" "precision mediump float;" "uniform sampler2D tex;\n" "in vec2 uv;\n" "in vec4 color;\n" "out vec4 frag_color;\n" "void main() {\n" " frag_color = texture(tex, uv) * color;\n" "}\n"; #elif defined(SOKOL_METAL) const char* vs_src_imgui = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct params_t {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos [[attribute(0)]];\n" " float2 uv [[attribute(1)]];\n" " float4 color [[attribute(2)]];\n" "};\n" "struct vs_out {\n" " float4 pos [[position]];\n" " float2 uv;\n" " float4 color;\n" "};\n" "vertex vs_out _main(vs_in in [[stage_in]], constant params_t& params [[buffer(0)]]) {\n" " vs_out out;\n" " out.pos = float4(((in.pos / params.disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " out.uv = in.uv;\n" " out.color = in.color;\n" " return out;\n" "}\n"; const char* fs_src_imgui = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct fs_in {\n" " float2 uv;\n" " float4 color;\n" "};\n" "fragment float4 _main(fs_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler smp [[sampler(0)]]) {\n" " return tex.sample(smp, in.uv) * in.color;\n" "}\n"; #elif defined(SOKOL_D3D11) const char* vs_src_imgui = "cbuffer params {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos: POSITION;\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" "};\n" "struct vs_out {\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" " float4 pos: SV_Position;\n" "};\n" "vs_out main(vs_in inp) {\n" " vs_out outp;\n" " outp.pos = float4(((inp.pos/disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " outp.uv = inp.uv;\n" " outp.color = inp.color;\n" " return outp;\n" "}\n"; const char* fs_src_imgui = "Texture2D<float4> tex: register(t0);\n" "sampler smp: register(s0);\n" "float4 main(float2 uv: TEXCOORD0, float4 color: COLOR0): SV_Target0 {\n" " return tex.Sample(smp, uv) * color;\n" "}\n"; #endif
33.790761
119
0.604664
751f699db40b8db0c4cffb7c35b3f5337e15d5f6
1,868
cpp
C++
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // ***** string make(int P, int R, int S) { assert(P >= 0 && R >= 0 && S >= 0); if (P + R + S == 1) { if (P == 1) return "P"; if (R == 1) return "R"; if (S == 1) return "S"; assert(false); } int a = (P + R + S) / 2 - S; // P vs R -> P (write PR) int b = (P + R + S) / 2 - P; // R vs S -> R (write RS) int c = (P + R + S) / 2 - R; // S vs P -> S (write PS) if (a < 0 || b < 0 || c < 0) return ""; auto s = make(a, b, c); if (s.empty()) return ""; string w; for (char p : s) if (p == 'P') w += "RP"; else if (p == 'R') w += "SR"; else w += "SP"; return w; } auto get(int N, int P, int R, int S) { int M = P + R + S; assert(M == (1 << N)); auto s = make(P, R, S); if (s.empty()) return "IMPOSSIBLE"s; for (int n = 1; n < M; n <<= 1) { for (int i = 0; i < M; i += 2 * n) { auto a = s.substr(i, n), b = s.substr(i + n, n); if (a > b) { s.replace(i, n, b); s.replace(i + n, n, a); } } } return s; } void test() { for (int N = 1; N <= 3; N++) { for (int M = 1 << N, P = 0; P <= M; P++) { for (int R = 0, S = M - P - R; P + R <= M; R++, S--) { printf("%d %2d %2d %2d -- %s\n", N, P, R, S, get(N, P, R, S).data()); } } } } auto solve() { int N, P, R, S; cin >> N >> P >> R >> S; return get(N, P, R, S); } // ***** int main() { // test(); unsigned T; cin >> T >> ws; for (unsigned t = 1; t <= T; ++t) { auto solution = solve(); cout << "Case #" << t << ": " << solution << '\n'; } return 0; }
21.72093
85
0.336188
75222869cec69877f7cf1812e300de8d226b149e
3,234
cxx
C++
model_server/obj/src/string_to_int.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
model_server/obj/src/string_to_int.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
model_server/obj/src/string_to_int.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ /////////////////////// File string_to_int.C ///////////////////// // // -- Converts ASCII string into integer number using UNIX LEX str_to_int() // // Relations :none. // // Constructors : none // // Methods : none // // History: 08/19/91 S. Spibvakovsky Initial coding //----------------------------------------------------------------------- #include "genError.h" #ifndef ISO_CPP_HEADERS #include <stdio.h> #else /* ISO_CPP_HEADERS */ #include <cstdio> using namespace std; #endif /* ISO_CPP_HEADERS */ extern "C" int str_to_int(char *, int *); // This call just separates c from C and intercepts the error code. int string_to_int(char *str) { int value; int err_stat = 0; Initialize(string_to_int); value = str_to_int(str, &err_stat); if (err_stat) Error(ERR_INPUT); ReturnValue(value); } /* START-LOG------------------------------------------- $Log: string_to_int.cxx $ Revision 1.2 2000/07/10 23:07:30EDT ktrans mainline merge from Visual C++ 6/ISO (extensionless) standard header files Revision 1.2.1.2 1992/10/09 18:55:39 boris Fix comments END-LOG--------------------------------------------- */
40.936709
77
0.527829
752307c05d9b1adb8aa85249d908665b5ecf029f
2,565
hpp
C++
src/common/thread.hpp
longlonghands/fps-challenge
020c133a782285364d52b1c98e9661c9aedfd96d
[ "MIT" ]
null
null
null
src/common/thread.hpp
longlonghands/fps-challenge
020c133a782285364d52b1c98e9661c9aedfd96d
[ "MIT" ]
null
null
null
src/common/thread.hpp
longlonghands/fps-challenge
020c133a782285364d52b1c98e9661c9aedfd96d
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <memory> #include <stdexcept> #include <thread> namespace common { namespace async { void sleep(int ms); /// This class implements a platform-independent /// wrapper around an operating system thread. class Thread { public: typedef std::shared_ptr<Thread> Ptr; Thread(); virtual ~Thread(); // call the OS to start the thread bool start(std::function<void()> target); bool start(std::function<void(void *)> target, void *arg); // Waits until the thread exits. void join(); // Waits until the thread exits. // The thread should be canceled before calling this method. // This method must be called from outside the current thread // context or deadlock will ensue. bool waitForExit(int timeout = 5000); // Returns the native thread ID. std::thread::id id() const; // Returns the native thread ID of the current thread. static std::thread::id currentID(); bool isStarted() const; bool isRunning() const; protected: // The context which we send to the thread context. // This allows us to gracefully handle late callbacks // and avoid the need for deferred destruction of Runner objects. struct Context { typedef Context *ptr; bool threadIsAlive; bool OwnerIsAlive; // Thread-safe POD members // May be accessed at any time std::string tid; bool started; bool running; // Non thread-safe members // Should not be accessed once the Runner is started std::function<void()> target; std::function<void(void *)> target1; void *arg; // The implementation is responsible for resetting // the context if it is to be reused. void reset() { OwnerIsAlive = true; threadIsAlive = false; tid = ""; arg = nullptr; target = nullptr; target1 = nullptr; started = false; running = false; } Context() { reset(); } ~Context() { // printf("\ncontext deleting ...\n"); } }; bool startAsync(); static void runAsync(Context::ptr context); Thread(const Thread &) = delete; Thread &operator=(const Thread &) = delete; Context::ptr m_context; std::unique_ptr<std::thread> m_handle; }; }} // namespace tidy::async
26.173469
71
0.579337
970891b77c47801c8b11786a89e88ae016939709
10,383
cpp
C++
src/particle.cpp
ndevenish/nsl
03dd69ce39258cad0547b968c062074e4b90fdf0
[ "MIT" ]
null
null
null
src/particle.cpp
ndevenish/nsl
03dd69ce39258cad0547b968c062074e4b90fdf0
[ "MIT" ]
null
null
null
src/particle.cpp
ndevenish/nsl
03dd69ce39258cad0547b968c062074e4b90fdf0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2006-2012 Nicholas Devenish * * 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. * */ #include <string> #include <sstream> #include <stdexcept> #include <iostream> #include <fstream> #include "nslobject.h" #include "nslobjectfactory.h" #include "particle.h" #include "container.h" #include "physics.h" #include "vector3.h" #include "errors.h" #include "random.h" #include "electromagnetics.h" #include "neutronphysics.h" using std::runtime_error; using std::string; using std::ofstream; using nsl::rand_normal; using nsl::rand_uniform; using std::endl; /* particle::mag_field = 0; particle::elec_field = 0; particle::particlebox = 0; */ // Hack: File global pointers to avoid initialisation static container *g_particlebox = 0; static bfield *g_mag_field = 0; static efield *g_elec_field = 0; particle::particle() { initvals(); objecttype = "particle"; types.push_back(objecttype); } void particle::initvals( void ) { particlebox = 0; fake_edm = 0.; flytime = 0.; gamma = 0.0; position.x = position.y = position.z = 0.0; velocity_vec.x = velocity_vec.y = velocity_vec.z = 0.0; velocity = 0.0; spinEplus.x = spinEplus.y = spinEplus.z = 0.0; spinEminus = spinEplus; E_sum_phase = E_minus_sum_phase = 0.0; vxEeffect *= 0; bounces = 0; } bool particle::prepareobject() { readsettings(); return true; } void particle::readsettings(void) { // Reset all the per-phase run variables here fake_edm = 0.; flytime = 0.; frequencydiff = 0.; E_sum_phase = E_minus_sum_phase = 0.; bounces = 0; vxEeffect *= 0; active = true; sampledBz.reset(); sampledBz2.reset(); sampleBz.reset(); sampleZ.reset(); // Get and validate the positions read_positionsettings(); // Get and validate the velocities (this depends on positions being initialisied) read_velocitysettings(); // Read the spin settings read_spinsettings(); // This section now reads into static variables, as the process was taking inordinate // amounts of time for large particle numbers // Find a container! if (!g_particlebox) { g_particlebox = (container*)findbytype("container"); if (!g_particlebox) throw runtime_error("Unable to find a container for particle"); } particlebox = g_particlebox; // Find a magnetic field to link to if (!g_mag_field) g_mag_field = (bfield*)findbytype("bfield"); mag_field = g_mag_field; // Look for an electric field to link to if (!g_elec_field) g_elec_field = (efield*)findbytype("efield"); elec_field = g_elec_field; } void particle::read_velocitysettings( void ) { // First get the vector if we have one if (isset("vx") || isset("vy") || isset("vz")) { velocity_vec.x = getlongdouble("vx", 0.0); velocity_vec.y = getlongdouble("vy", 0.0); velocity_vec.z = getlongdouble("vz", 0.0); } else { velocity_vec.x = velocity_vec.y = velocity_vec.z = 1.0; } if (isset("velocity")) { velocity = getlongdouble("velocity", 0.0); velocity_vec.scaleto(velocity); } else { velocity = velocity_vec.mod(); } // Warn for zero velocity if (velocity == 0.0) Warning("Velocity in particle is unset (or set to 0.0)"); ///////////////////////////////////////////// // Maxwell-Boltzmann distribution if (get("maxwelldistribution", "off") == "on") generate_maxwellianvelocity(); // Calculate the energy group energygroup = 0.5 * velocity * velocity / g + position.z; // Calculate the relativistic gamma factor vgamma = sqrtl(1. / (1. - (velocity*velocity)/csquared)); } void particle::generate_maxwellianvelocity( void ) { //We want this particle to have a velocity on a maxwell-boltzmann distribution // Don't do it if we have no mass information if (!isset("mass")) throw runtime_error("Cannot set maxwell-boltzmann velocity without mass information."); // Read in the mass information mass = getlongdouble("mass", 0); if (mass <= 0.) throw runtime_error("Zero and negative mass particles unsupported"); // Calculate the effective temperature for the desired maximum velocity long double T = (velocity*velocity * mass ) / (2.*k); //long double T = mass / (velocity * velocity * 2. * k); long double factor = sqrtl((k*T) / mass ); long double mwcutoff = getlongdouble("maxwelliancutoff", position.z + 1.); // Check we are not above the cutoff if (mwcutoff < position.z) throw runtime_error("Particle start position is higher than maxwellian cutoff"); // Do a stupid uniform thing to save time long double egroup = sqrt(rand_uniform() * pow(0.04 + mwcutoff, 2.)) - 0.04; velocity = sqrt(2.*g*(egroup - position.z)); velocity_vec.z = -velocity; velocity_vec.x = velocity_vec.y = 0.; return; /* //ofstream max("maxwellians.txt"); // Loop until we have a valid velocity while(1) { // Generate random maxwellian velocities - http://research.chem.psu.edu/shsgroup/chem647/project14/project14.html velocity_vec.x = rand_normal() * factor; velocity_vec.y = rand_normal() * factor; velocity_vec.z = rand_normal() * factor; // Read back the velocity magnitude velocity = velocity_vec.mod(); // Are we using a cutoff height? If so, see if we are within it if (isset("maxwelliancutoff")) { // Is this above our cutoff? long double cutoff = sqrtl(2*g*(getlongdouble("maxwelliancutoff", 0.79) - position.z)); // If not, it is valid! otherwise recast. if (velocity < cutoff) { long double egroup = (( velocity * velocity ) / ( 2. * g )) + position.z; max << velocity << endl; static long count = 0; logger << ++count << endl; // break; continue; } } else { break; } } // while(1) */ } void particle::read_positionsettings( void ) { position.x = getlongdouble("x", 0.0); position.y = getlongdouble("y", 0.0); position.z = getlongdouble("z", 0.0); // See if we have set a startvolume string startvolume; if (isset("startvolume")) { startvolume = get("startvolume"); string startposition; startposition = get("startposition", "center"); /*if (isset("startposition")) startposition = get("startposition"); else startposition = "center"; */ // Get the base position for this nslobject *startvol; startvol = particlebox->findbyname(startvolume); if (startvol->isoftype("container")) position = ((container*)startvol)->getposition(startposition); else throw runtime_error("Attempting to start particle in non-container volume"); } } void particle::read_spinsettings( void) { // Gamma value gamma = getlongdouble("gamma", 0.0); if (!isset("gamma")) Warning("Gamma in particle is unset (or set to 0.0)"); // Multiply by 2pi Because we will mostly want to use this setting // NOTE: Be careful if changing this in future, as is assumed to be 2*pi*gamma elsewhere gamma *= 2. * pi; // ~~~~~ Spin stuff long double start_spin_polar_angle, start_spin_phase; // Start by getting the spin polar angles start_spin_polar_angle = pi*getlongdouble("start_spin_polar_angle", 0.5); start_spin_phase = pi*getlongdouble("start_spin_phase", 0.0); spinEplus.x = sinl(start_spin_polar_angle)*cosl(start_spin_phase); spinEplus.y = sinl(start_spin_polar_angle)*sinl(start_spin_phase); spinEplus.z = cosl(start_spin_polar_angle); spinEminus = spinEplus; } /** Updates the Exv effect for the particle. */ void particle::updateExv ( efield &elecfield ) { /* vector3 vxE; vector3 E; elecfield.getfield(E, this->position); this->vxEeffect = (crossproduct(E, this->velocity_vec) * this->vgamma)/ csquared; */ // void neutron_physics::Exveffect( const vector3 &position, const vector3 &velocity, const long double gamma, vector3 &vxEeffect ) neutron_physics::Exveffect( this->position, this->velocity_vec, this->vgamma, elecfield, this->vxEeffect ); } /* // Physical Properties values vector3 position; vector3 velocity_vec; vector3 spinEplus; vector3 spinEminus; // A 'cache' for the exB effect that only changes every bounce (in a linear electric field) vector3 vxEeffect; long double velocity; // m s^-1 // Gyromagnetic ratio of the particle long double gamma; // 2*pi*Hz/Tesla // Particles velocity gamma long double vgamma; // Number of bounces! long bounces; long double E_sum_phase, E_minus_sum_phase; // Radians long double flytime; // s // particles mass long double mass; // kg // Our calculated edm parameters long double frequencydiff; //radians long double fake_edm; // e.cm x10(-26) dataset cumulativeedm; // Utility class pointers container *particlebox; bfield *mag_field; efield *elec_field; */ std::ostream& operator<<(std::ostream& os, const particle& p) { using std::scientific; os.precision(3); //os.setscientific(); os << "Particle Property dump:" << endl; os << "Position: " << p.position << endl; os << "Velocity: " << p.velocity << " ( " << p.velocity_vec << " )" << endl; os << "Spin E+: " << p.spinEplus << endl; os << " E-: " << p.spinEminus << endl; os << "VxE Effect: " << p.vxEeffect << endl; os << "Gamma (L): " << p.gamma << endl; os << "Gamme (R): " << p.vgamma << endl; os << "Bounces: " << p.bounces << endl; os << "Sum Phase, E+: " << p.E_sum_phase << endl; os << " E-: " << p.E_minus_sum_phase << endl; os << "Flytime: " << p.flytime << endl; os << "Mass: " << p.mass << endl; os << "Frequency Diff: " << p.frequencydiff << endl; os << "Fake EDM: " << p.fake_edm << endl; return os; }
27.323684
131
0.690456
97090938d893075b49d16b6dd0c8497823d900d3
1,059
cc
C++
src/main/native/darwin/util.cc
kjlubick/bazel
6f0913e6e75477ec297430102a8213333a12967e
[ "Apache-2.0" ]
1
2022-02-04T05:06:03.000Z
2022-02-04T05:06:03.000Z
src/main/native/darwin/util.cc
kjlubick/bazel
6f0913e6e75477ec297430102a8213333a12967e
[ "Apache-2.0" ]
3
2017-07-10T13:18:04.000Z
2018-08-30T19:29:46.000Z
src/main/native/darwin/util.cc
kjlubick/bazel
6f0913e6e75477ec297430102a8213333a12967e
[ "Apache-2.0" ]
1
2022-01-12T18:08:14.000Z
2022-01-12T18:08:14.000Z
// Copyright 2021 The Bazel Authors. All rights reserved. // // 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. #include "src/main/native/darwin/util.h" #include "src/main/cpp/util/logging.h" namespace bazel { namespace darwin { dispatch_queue_t JniDispatchQueue() { static dispatch_once_t once_token; static dispatch_queue_t queue; dispatch_once(&once_token, ^{ queue = dispatch_queue_create("build.bazel.jni", DISPATCH_QUEUE_SERIAL); BAZEL_CHECK_NE(queue, nullptr); }); return queue; } } // namespace darwin } // namespace bazel
31.147059
76
0.745042
97094f6541bda09c47adf1bc12acd753f4e0a99b
1,307
cpp
C++
test/dataalign/test_dataalign.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
4
2016-09-07T07:02:52.000Z
2019-06-22T08:55:53.000Z
test/dataalign/test_dataalign.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
null
null
null
test/dataalign/test_dataalign.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
3
2019-06-22T16:00:39.000Z
2022-03-09T13:46:27.000Z
#include <stdio.h> #include <windows.h> int mswindows_handle_hardware_exceptions (DWORD code) { printf("Handling exception\n"); if (code == STATUS_DATATYPE_MISALIGNMENT) { printf("misalignment fault!\n"); return EXCEPTION_EXECUTE_HANDLER; } else return EXCEPTION_CONTINUE_SEARCH; } void test() { __try { char temp[10]; memset(temp, 0, 10); double *val; val = (double *)(&temp[3]); printf("%lf\n", *val); } __except(mswindows_handle_hardware_exceptions (GetExceptionCode ())) {} } int main() { char a; char b; class S1 { public: char m_1; // 1-byte element // 3-bytes of padding are placed here int m_2; // 4-byte element double m_3, m_4; // 8-byte elements }; S1 x; long y; S1 z[5]; printf("sizeof S1 : %d\n\n", sizeof(S1)); printf("a = %p\n", &a); printf("b = %p\n", &b); printf("x = %p\n", &x); printf("x.m_1 = %p\n", &x.m_1); printf("x.m_2 = %p\n", &x.m_2); printf("x.m_3 = %p\n", &x.m_3); printf("x.m_4 = %p\n", &x.m_4); printf("y = %p\n", &y); printf("z[0] = %p\n", z); printf("z[1] = %p\n", &z[1]); test(); return 0; }
20.107692
72
0.497322
9709fcca401e1a7f071545e31f5dc431f22736ac
7,362
cpp
C++
src/engine/private/rendererandroid.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/private/rendererandroid.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/private/rendererandroid.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file rendererandroid.cpp * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2017-12-09 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/precompiled.h" #include "o3d/engine/renderer.h" // ONLY IF O3D_ANDROID IS SELECTED #ifdef O3D_ANDROID #include "o3d/engine/glextdefines.h" #include "o3d/engine/glextensionmanager.h" #include "o3d/core/gl.h" #include "o3d/engine/context.h" #include "o3d/core/appwindow.h" #include "o3d/core/application.h" #include "o3d/core/debug.h" #ifdef O3D_EGL #include "o3d/core/private/egldefines.h" #include "o3d/core/private/egl.h" #endif using namespace o3d; // Create the OpenGL context. void Renderer::create(AppWindow *appWindow, Bool debug, Renderer *sharing) { if (m_state.getBit(STATE_DEFINED)) { O3D_ERROR(E_InvalidPrecondition("The renderer is already initialized")); } if (!appWindow || (appWindow->getHWND() == NULL_HWND)) { O3D_ERROR(E_InvalidParameter("Invalid application window")); } if ((sharing != nullptr) && m_sharing) { O3D_ERROR(E_InvalidOperation("A shared renderer cannot be sharing")); } O3D_MESSAGE("Creating a new OpenGLES context..."); if (GL::getImplementation() == GL::IMPL_EGL) { // // EGL implementation // #ifdef O3D_EGL EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); EGLSurface eglSurface = reinterpret_cast<EGLSurface>(appWindow->getHDC()); EGLConfig eglConfig = reinterpret_cast<EGLConfig>(appWindow->getPixelFormat()); // EGL_CONTEXT_OPENGL_DEBUG EGLint contextAttributes[] = { /*EGL_CONTEXT_MAJOR_VERSION_KHR*/EGL_CONTEXT_CLIENT_VERSION, 3, /* EGL_CONTEXT_MINOR_VERSION_KHR, 2,*/ debug ? EGL_CONTEXT_FLAGS_KHR : EGL_NONE, debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : EGL_NONE, // debug ? EGL_CONTEXT_FLAGS_KHR : EGL_NONE, debug ? EGL_CONTEXT_OPENGL_DEBUG : EGL_NONE, EGL_NONE }; EGLContext eglContext = eglCreateContext( eglDisplay, eglConfig, sharing ? reinterpret_cast<EGLContext>(sharing->getHGLRC()) : EGL_NO_CONTEXT, contextAttributes); if (eglContext == EGL_NO_CONTEXT) { O3D_ERROR(E_InvalidResult("Unable to create the OpenGLES context")); } EGL::makeCurrent(eglDisplay, eglSurface, eglSurface, eglContext); m_HDC = appWindow->getHDC(); m_HGLRC = reinterpret_cast<_HGLRC>(eglContext); m_state.enable(STATE_DEFINED); m_state.enable(STATE_EGL); #else O3D_ERROR(E_UnsuportedFeature("Support for EGL is missing")); #endif } else { O3D_ERROR(E_UnsuportedFeature("Support for EGL only")); } GLExtensionManager::init(); O3D_MESSAGE("Video renderer: " + getRendererName()); O3D_MESSAGE("OpenGL version: " + getVersionName()); computeVersion(); m_appWindow = appWindow; m_bpp = appWindow->getBpp(); m_depth = appWindow->getDepth(); m_stencil = appWindow->getStencil(); m_samples = appWindow->getSamples(); if (sharing) { m_sharing = sharing; m_sharing->m_shareCount++; } if (debug) { initDebug(); } m_glContext = new Context(this); doAttachment(m_appWindow); } // delete the renderer void Renderer::destroy() { if (m_state.getBit(STATE_DEFINED)) { if (m_refCount > 0) { O3D_ERROR(E_InvalidPrecondition("Unable to destroy a referenced renderer")); } if (m_shareCount > 0) { O3D_ERROR(E_InvalidPrecondition("All shared renderer must be destroyed before")); } // unshare if (m_sharing) { m_sharing->m_shareCount--; if (m_sharing->m_shareCount < 0) { O3D_ERROR(E_InvalidResult("Share counter reference is negative")); } m_sharing = nullptr; } deletePtr(m_glContext); if (m_HGLRC && m_appWindow) { if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); EGL::makeCurrent(eglDisplay, 0, 0, 0); EGL::destroyContext(eglDisplay, reinterpret_cast<EGLContext>(m_HGLRC)); #endif } m_HGLRC = NULL_HGLRC; } m_HDC = NULL_HDC; m_depth = m_bpp = m_stencil = m_samples = 0; m_state.zero(); m_version = 0; if (m_appWindow) { disconnect(m_appWindow); m_appWindow = nullptr; } m_glErrno = GL_NO_ERROR; } } void *Renderer::getProcAddress(const Char *ext) const { return EGL::getProcAddress(ext); } // Is it the current OpenGL context. Bool Renderer::isCurrent() const { if (!m_state.getBit(STATE_DEFINED)) { return False; } if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL return EGL::getCurrentContext() == reinterpret_cast<EGLContext>(m_HGLRC); #endif } else { return False; } } // Set as current OpenGL context void Renderer::setCurrent() { if (!m_state.getBit(STATE_DEFINED)) { return; } if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL if (EGL::getCurrentContext() == reinterpret_cast<EGLContext>(m_HGLRC)) { return; } EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); if (EGL::makeCurrent( eglDisplay, reinterpret_cast<EGLSurface>(m_HDC), reinterpret_cast<EGLSurface>(m_HDC), reinterpret_cast<EGLContext>(m_HGLRC))) { O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context")); } #else O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context")); #endif } else { O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context")); } } Bool Renderer::setVSyncMode(VSyncMode mode) { if (!m_state.getBit(STATE_DEFINED)) { return False; } int value = 0; if (mode == VSYNC_NONE) { value = 0; } else if (mode == VSYNC_YES) { value = 1; } else if (mode == VSYNC_ADAPTIVE) { value = -1; } if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); if (!EGL::swapInterval(eglDisplay, value)) { return False; } #else return False; #endif } else { return False; } if (mode == VSYNC_NONE) { m_state.setBit(STATE_VSYNC, False); m_state.setBit(STATE_ADAPTIVE_VSYNC, False); } else if (mode == VSYNC_YES) { m_state.setBit(STATE_VSYNC, True); m_state.setBit(STATE_ADAPTIVE_VSYNC, False); } else if (mode == VSYNC_ADAPTIVE) { m_state.setBit(STATE_VSYNC, True); m_state.setBit(STATE_ADAPTIVE_VSYNC, True); } return True; } #endif // O3D_ANDROID
27.470149
123
0.619669
970a0dc9bef87e899dc9a929f4a47aa138c8dc3b
3,481
cpp
C++
Codility_CommonPrimerDivisor.cpp
CharlieGearsTech/Codility
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
[ "MIT" ]
1
2021-01-31T22:59:59.000Z
2021-01-31T22:59:59.000Z
Codility_CommonPrimerDivisor.cpp
CharlieGearsTech/Codility
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
[ "MIT" ]
null
null
null
Codility_CommonPrimerDivisor.cpp
CharlieGearsTech/Codility
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
[ "MIT" ]
null
null
null
#include <iostream> #include <assert.h> #include <math.h> #include <vector> #include <algorithm> #include <numeric> #include <map> #include <deque> #include <stdlib.h> #include <string> #include <set> #include <vector> #include <new> #include <memory> using namespace std; /*Crea un arreglo en la que los indices muestran el numero divisible de la secuencia y el valor es el numero divisor*/ map<int,int> prepareArrayFactor(int n) { map<int,int> f; auto i = 2u; /*Rango para numeros que pueden dividir a N*/ while(i+i <=(size_t)n) { auto k=i*i; while(k <= (size_t)n) { f[k] = i; k+=i; } i++; } return f; } /* Encontrar los numeros que multiplicados nos dan a X, X debe de ser un numero menor al tamaño de A*/ vector<int> factorization(int x, map<int,int>& A) { vector<int> primeFactors; /*Revisar unicamente numeros que son divisibles*/ while(A[x] > 0) { /*Agregar el divisor a la lista de factorizacion*/ primeFactors.push_back(A[x]); /* Dividir para disminuir el numero divisible en un factor menor.*/ x /= A[x]; } /*Agregar el ultimo numero divisor.*/ primeFactors.push_back(x); return primeFactors; } /*Esta solucion se basa en usar la formula de factorizacion que nos devuelve un contenedor con todos los factores de X numero, despues de eso comparamos los arreglos iguales. Uso set para organizar y hacer unicos los factores.*/ int solution(vector<int> &A, vector<int> &B) { auto N=A.size(); set<int> holder; copy(A.begin(),A.end(),inserter(holder,holder.begin())); copy(B.begin(),B.end(),inserter(holder,holder.begin())); int max_element=*holder.rbegin(); //O(logN) auto maxFactorArray=prepareArrayFactor(max_element); int count=0; //O(n*logn*logn) for(auto k=0u; k<N; ++k) { auto Afactor=factorization(A[k],maxFactorArray); auto Bfactor=factorization(B[k],maxFactorArray); set<int> AfactorSet; set<int> BfactorSet; copy(Afactor.begin(),Afactor.end(),inserter(AfactorSet,AfactorSet.begin())); copy(Bfactor.begin(),Bfactor.end(),inserter(BfactorSet,BfactorSet.begin())); if(std::equal(AfactorSet.begin(),AfactorSet.end(),BfactorSet.begin())) ++count; } return count; } /*Imprimir vector<int>s*/ void printV(vector<int>& vRes) { for(auto it= vRes.begin(); it != vRes.end();++it) { cout<<*it<<"\t"; } cout<<endl; } /*Assertion de vectores de ints*/ void assertV( vector<int>& result, vector<int>&& comp) { bool res = std::equal(result.begin(),result.end(),comp.begin()); assert(res); } int main() { int result; vector<int> a; vector<int> b; a={15,10,3}; b={75,30,5}; result=solution(a,b); cout<<result<<endl; assert(result==1); a.clear(); b.clear(); a={15}; b={75}; result=solution(a,b); cout<<result<<endl; assert(result==1); a.clear(); b.clear(); a={12,12,18}; b={24,25,9}; result=solution(a,b); cout<<result<<endl; assert(result==1); a.clear(); b.clear(); /*This algorithm is unable to execute large number since it allocates all the prime divisor for each element*/ // a={2147483647}; // b={2147483647}; // result=solution(a,b); // cout<<result<<endl; // assert(result==1); // a.clear(); // b.clear(); return 0; }
23.362416
228
0.607871
970df27bbd8f99dc06963233fda0aa18d6bbaf7f
2,258
hpp
C++
include/rllib/bundle/Bundle.hpp
loriswit/rllib
a09a73f8ac353db76454007b2ec95bf438c0fc1a
[ "MIT" ]
1
2022-02-15T17:49:44.000Z
2022-02-15T17:49:44.000Z
include/rllib/bundle/Bundle.hpp
loriswit/rllib
a09a73f8ac353db76454007b2ec95bf438c0fc1a
[ "MIT" ]
null
null
null
include/rllib/bundle/Bundle.hpp
loriswit/rllib
a09a73f8ac353db76454007b2ec95bf438c0fc1a
[ "MIT" ]
null
null
null
#ifndef RLLIB_BUNDLE_HPP #define RLLIB_BUNDLE_HPP #include <string> #include <rllib/stream/ByteStream.hpp> #include <rllib/bundle/FileProperties.hpp> namespace rl { /** * A bundle is a collection of files packed in a big single file. It is used to store all the game assets. * In particular, this is where scene are being extracted from the game. */ class RL_API Bundle { public: /** * Creates an empty bundle. */ Bundle() = default; /** * Creates a bundle loaded from a file. * * @param path The path to the bundle file */ explicit Bundle(FilePath path); /** * Load the bundle from a file. * * @param path The path to the bundle file */ void load(FilePath path); /** * Reads a file in the bundle and returns its content. * * @param path The path to the file in the bundle * @return The content of the file */ ByteStream readFile(const FilePath & path) const; /** * Overwrites a file in the bundle. * The file path must already exist in the bundle. * * @warning The original content will be lost. * * @param path The path to the file in the bundle * @param data The data that is to be written */ void writeFile(const FilePath & path, const ByteStream & data); /** * Creates a new bundle file and returns its instance. * * @param bundlePath The path to the new bundle file that is to be created * @param files A list of pairs containing file paths with associated contents * @return The instance of the new bundle */ static Bundle create(FilePath bundlePath, const std::vector<std::pair<FilePath, ByteStream>> & files); private: /** * Finds a file in the bundle index and returns its properties. * * @param path The path to the file in the bundle * @return A pair containing the file properties and the offset of the properties */ const std::pair<FileProperties, std::streampos> & findFile(const FilePath & path) const; FilePath m_path; std::vector<std::pair<FileProperties, std::streampos>> m_fileList; std::size_t m_baseOffset = 0; }; } // namespace rl #endif //RLLIB_BUNDLE_HPP
27.204819
106
0.647476
970e072080a9ec4db50ac4aeb4e5ca80634a2942
18,605
cpp
C++
OOP/Project_2/main.cpp
moyfdzz/University-Projects
8d6ab689fd3fba43994494245e489b1c97544fbd
[ "MIT" ]
4
2018-04-27T00:03:39.000Z
2019-01-27T07:31:57.000Z
OOP/Project_2/main.cpp
moyfdzz/University-Projects
8d6ab689fd3fba43994494245e489b1c97544fbd
[ "MIT" ]
1
2018-04-08T18:55:36.000Z
2018-11-01T02:30:11.000Z
OOP/Project_2/main.cpp
moyfdzz/University-Assignments
8d6ab689fd3fba43994494245e489b1c97544fbd
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <iostream> using namespace std; #include "EjemploVideo.h" Materia materias[5]; Tema temas[10]; Autor autores[10]; EjemploVideo eVideos[20]; int cantidadTemasG = 0, cantidadAutoresG = 0, cantidadMateriasG = 0, cantidadEVideosG = 0; void cargarDatosMaterias() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de las materias" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaMaterias; listaMaterias.open(extensionArchivo); int cveMateria; string nombreMateria; while(listaMaterias >> cveMateria && getline(listaMaterias, nombreMateria)) { materias[cantidadMateriasG].setIdMateria(cveMateria); materias[cantidadMateriasG].setNombreMateria(nombreMateria); cantidadMateriasG++; } listaMaterias.close(); } void cargarDatosTemas() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de los temas" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaTemas; listaTemas.open(extensionArchivo); int idTema, idMateria; string nombreTema; while(listaTemas >> idTema >> idMateria && getline(listaTemas, nombreTema)) { temas[cantidadTemasG].setIdTema(idTema); temas[cantidadTemasG].setIdMateria(idMateria); temas[cantidadTemasG].setNombreTema(nombreTema); cantidadTemasG++; } listaTemas.close(); } void cargarDatosAutores() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de los autores" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaAutores; listaAutores.open(extensionArchivo); int idAutor; string nombreAutor; while(listaAutores >> idAutor && getline(listaAutores, nombreAutor)) { autores[cantidadAutoresG].setIdAutor(idAutor); autores[cantidadAutoresG].setNombreAutor(nombreAutor); cantidadAutoresG++; } listaAutores.close(); } void checarIdAutor(int numAutores, bool &idAutorExiste, int idAutor) { for (int counter2 = 0; counter2 < cantidadAutoresG; ++counter2) { if (autores[counter2].getIdAutor() == idAutor) { idAutorExiste = true; break; } else { idAutorExiste = false; } } } void checarIdTema(int idTema, bool &idTemaExiste) { for(int counter = 0; counter < cantidadTemasG; counter++) { if(idTema != temas[counter].getIdTema()) { idTemaExiste = false; } else { idTemaExiste = true; break; } } } void checarIdMateria(int idMateria, bool &idMateriaExiste) { for(int counter = 0; counter < cantidadTemasG; counter++) { if(idMateria != materias[counter].getIdMateria()) { idMateriaExiste = false; } else { idMateriaExiste = true; break; } } } void cargarDatosEVideos() { string nombreArchivo, extensionArchivo; cout << "Ingrese el nombre del archivo de los ejemplo videos" << endl; cin >> nombreArchivo; extensionArchivo = nombreArchivo + ".txt"; ifstream listaEVideos; listaEVideos.open(extensionArchivo); int idVideo, idTema, dia, mes, anio, numAutores, idAutor; Fecha fechaElaboracion; string nombreEVideo; bool idTemaExiste = true, idAutorExiste = true; while(listaEVideos >> idVideo >> nombreEVideo >> idTema >> dia >> mes >> anio >> numAutores) { cout << "Agregando video" << endl; int posAutores[numAutores]; for (int counter = 0; counter < numAutores; ++counter) { listaEVideos >> idAutor; checarIdAutor(numAutores, idAutorExiste, idAutor); if(!idAutorExiste) { break; } posAutores[counter] = idAutor; } checarIdTema(idTema, idTemaExiste); cout << idAutorExiste << idTemaExiste << endl; if (idAutorExiste && idTemaExiste) { fechaElaboracion.setFecha(dia, mes, anio); eVideos[cantidadEVideosG].setIdVideo(idVideo); eVideos[cantidadEVideosG].setNombreEjemploVideo(nombreEVideo); eVideos[cantidadEVideosG].setIdTema(idTema); eVideos[cantidadEVideosG].setFechaElaboracion(fechaElaboracion); for (int counter = 0; counter < numAutores; ++counter) { if (!eVideos[cantidadEVideosG].agregaAutor(posAutores[counter])) { cout << "El id del autor del video número " << posAutores[counter] << " es inválido." << endl; } } cout << eVideos[cantidadEVideosG].getNombreEjemploVideo() << endl; cantidadEVideosG++; cout << "Sumando a cantidad videos" << endl; } else { cout << "El video " << nombreEVideo << " tiene el o los id(s) del autor o del tema mal por "; cout << "lo que no fue contado." << endl; } cout << endl << endl; } listaEVideos.close(); } void mostrarMaterias() { cout << endl << "Materias" << endl; cout << endl << "ID Materia Nombre Materia" << endl; for(int counter = 0; counter < cantidadMateriasG; counter++) { cout << " " << materias[counter].getIdMateria(); cout << " " << materias[counter].getNombreMateria() << endl; } cout << endl; } void mostrarTemas() { cout << "Temas" << endl; cout << endl << "ID Tema ID Materia Nombre Tema" << endl; for(int counter = 0; counter < cantidadTemasG; counter++) { cout << " " << temas[counter].getIdTema(); cout << " " << temas[counter].getIdMateria() << " "; cout << " " << temas[counter].getNombreTema() << endl; } cout << endl; } void mostrarAutores() { cout << "Autores" << endl; cout << endl << "ID Autor Nombre Autor" << endl; for(int counter = 0; counter < cantidadAutoresG; counter++) { cout << " " << autores[counter].getIdAutor() << " "; cout << " " << autores[counter].getNombreAutor() << endl; } cout << endl; } void checarIdVideo(bool &idVideoExiste, int idVideo) { for (int counter = 0; counter < cantidadEVideosG; ++counter) { if (idVideo == eVideos[counter].getIdVideo()) { cout << "Este id se repite: " << idVideo << endl; idVideoExiste = false; break; } else { idVideoExiste = true; } } } void checarCantAutores(bool &cantAutoresPosible, int numAutoresUsuario) { if (numAutoresUsuario < 1 || numAutoresUsuario > 10) { cantAutoresPosible = false; } else { cantAutoresPosible = true; } } void agregarEVideos() { int idVideo, idTema, dia, mes, anio, numAutoresUsuario, idAutor; Fecha fechaElaboracion; string nombreEVideo; bool idTemaExiste = true, idAutorExiste = true, idVideoExiste = true, cantAutoresPosible = true; cout << "Ingrese el id del video" << endl; cin >> idVideo; checarIdVideo(idVideoExiste, idVideo); while(!idVideoExiste) { cout << "El id de video existe. Por favor ingrese uno diferente." << endl; cin >> idVideo; checarIdVideo(idVideoExiste, idVideo); } cin.ignore(); eVideos[cantidadEVideosG].setIdVideo(idVideo); cout << "Ingrese el nombre del video" << endl; getline(cin, nombreEVideo); eVideos[cantidadEVideosG].setNombreEjemploVideo(nombreEVideo); cout << "Ingrese el id del tema" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); while(!idTemaExiste) { cout << "El id del tema no es válido. Vuelva a ingresarlo" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); } eVideos[cantidadEVideosG].setIdTema(idTema); cout << "Ingrese el día en el que el video fue elaborado" << endl; cin >> dia; cout << "Ingrese el mes en el que el video fue elaborado (número)" << endl; cin >> mes; cout << "Ingrese el año en el que el video fue elaborado" << endl; cin >> anio; fechaElaboracion.setFecha(dia, mes, anio); eVideos[cantidadEVideosG].setFechaElaboracion(fechaElaboracion); cout << "Ingrese la cantidad de autores del video" << endl; cin >> numAutoresUsuario; checarCantAutores(cantAutoresPosible, numAutoresUsuario); while(!cantAutoresPosible) { cout << "La cantidad de autores debe ser entre 1 y 10. Por favor vuelva a ingresarla" << endl; cin >> numAutoresUsuario; checarCantAutores(cantAutoresPosible, numAutoresUsuario); } for (int counter = 0; counter < numAutoresUsuario; counter++) { cout << "Introduzca el id del autor número " << counter + 1 << endl; do { cin >> idAutor; checarIdAutor(numAutoresUsuario, idAutorExiste, idAutor); if (!idAutorExiste) { cout << "El id del autor no existe. Por favor vuelva a ingresarlo" << endl; } else { idAutorExiste = eVideos[cantidadEVideosG].agregaAutor(idAutor); if(!idAutorExiste) { cout << "El id del autor ya ha sido ingresado. Por favor introduzca otro" << endl; } else { cout << "Autor agregado cantidad: " << eVideos[cantidadEVideosG].getCantidadAutores() << endl; } } }while(!idAutorExiste); } cantidadEVideosG++; } void buscarPorTema() { int idTema; bool idTemaExiste = true; cout << "¿Cuál es el id del tema?" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); while(!idTemaExiste) { cout << "El id del tema que ingresó es inválido. Por favor vuelva a ingresarlo" << endl; cin >> idTema; checarIdTema(idTema, idTemaExiste); } if(idTemaExiste) { cout << "Los datos de los videos con el id del tema " << idTema << " son los siguientes:" << endl; for(int counter = 0; counter < cantidadEVideosG; counter++) { if(idTema == eVideos[counter].getIdTema()) { cout << "ID del video: " << eVideos[counter].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[counter].getNombreEjemploVideo() << endl; cout << "Tema del video: "; for(int counter2 = 0; counter2 < cantidadEVideosG; counter2++) { if(idTema == eVideos[counter].getIdTema()) { cout << temas[counter2].getNombreTema() << endl; break; } } cout << "Fecha de elaboración: "; cout << eVideos[counter].getFechaElaboracion().getDd() << "."; cout << eVideos[counter].getFechaElaboracion().getMm() << "."; cout << eVideos[counter].getFechaElaboracion().getAa(); cout << endl << "Autor(es):" << endl; for(int counter2 = 0; counter2 < eVideos[counter].getCantidadAutores(); counter2++) { for(int counter3 = 0; counter3 < cantidadAutoresG; counter3++) { if(eVideos[counter].getListaAutores(counter2) == autores[counter3].getIdAutor()) { cout << " - " << autores[counter3].getNombreAutor() << endl; } } } cout << endl; } } } } void buscarPorMateria() { int idMateria; bool idMateriaExiste = true; cout << "Ingrese el id de la materia" << endl; cin >> idMateria; checarIdMateria(idMateria, idMateriaExiste); while(!idMateriaExiste) { cout << "El id de la materia que ingresó es inválido. Por favor vuelva a ingresarlo" << endl; cin >> idMateria; checarIdMateria(idMateria, idMateriaExiste); } if(idMateriaExiste) { cout << "Los datos de los videos con el id de la materia " << idMateria << " son los siguientes:" << endl; for(int counter = 0; counter < cantidadTemasG; counter++) { if(idMateria == temas[counter].getIdMateria()) { for (int counter2 = 0; counter2 < cantidadEVideosG; ++counter2) { if (temas[counter].getIdTema() == eVideos[counter2].getIdTema()) { cout << "ID del video: " << eVideos[counter2].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[counter2].getNombreEjemploVideo() << endl; cout << "ID del tema: " << eVideos[counter2].getIdTema() << endl; cout << "Fecha de elaboración: "; cout << eVideos[counter2].getFechaElaboracion().getDd() << "."; cout << eVideos[counter2].getFechaElaboracion().getMm() << "."; cout << eVideos[counter2].getFechaElaboracion().getAa(); cout << endl << "Autor(es):" << endl; for(int counter3 = 0; counter3 < eVideos[counter].getCantidadAutores(); counter3++) { for(int counter4 = 0; counter4 < cantidadAutoresG; counter4++) { if(eVideos[counter2].getListaAutores(counter3) == autores[counter4].getIdAutor()) { cout << " - " << autores[counter4].getNombreAutor() << endl; } } } cout << endl; } } } } } } void consultarVideos() { int counterTemporal, dia, mes, anio; cout << endl << "Videos" << endl << endl; for (int counter = 0; counter < cantidadEVideosG; ++counter) { cout << "Id del video: " << eVideos[counter].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[counter].getNombreEjemploVideo() << endl; cout << "Tema: "; for (int counter2 = 0; counter2 < cantidadTemasG; ++counter2) { if (temas[counter2].getIdTema() == eVideos[counter].getIdTema()) { cout << temas[counter2].getNombreTema() << endl; counterTemporal = counter2; break; } } cout << "Materia: "; for (int counter2 = 0; counter2 < cantidadMateriasG; ++counter2) { if (materias[counter2].getIdMateria() == temas[counterTemporal].getIdMateria()) { cout << materias[counter2].getNombreMateria() << endl; break; } } dia = eVideos[counter].getFechaElaboracion().getDd(); mes = eVideos[counter].getFechaElaboracion().getMm(); anio = eVideos[counter].getFechaElaboracion().getAa(); cout << "Fecha de Elaboracion: " << dia << "." << mes << "." << anio << endl; cout << "Autor(es): " << endl; for (int iCounter2 = 0; iCounter2 < eVideos[counter].getCantidadAutores(); ++iCounter2) { for (int iCounter3 = 0; iCounter3 < cantidadAutoresG; ++iCounter3) { if (eVideos[counter].getListaAutores(iCounter2) == autores[iCounter3].getIdAutor()) { cout << " - " << autores[iCounter3].getNombreAutor() << endl; } } } cout << endl; } } void buscarPorAutor() { int idAutor; bool idAutorExiste = false; cout << "Introduce el id del autor" << endl; cin >> idAutor; checarIdAutor(cantidadAutoresG, idAutorExiste, idAutor); while(!idAutorExiste) { cout << "El id del autor es inválido. Por favor introdzque uno correcto" << endl; cin >> idAutor; checarIdAutor(cantidadAutoresG, idAutorExiste, idAutor); } cout << endl << "Videos" << endl; for (int iCounter = 0; iCounter < cantidadEVideosG; ++iCounter) { for (int iCounter2 = 0; iCounter2 < eVideos[iCounter].getCantidadAutores(); ++iCounter2) { if (eVideos[iCounter].getListaAutores(iCounter2) == idAutor) { cout << "Id del video: " << eVideos[iCounter].getIdVideo() << endl; cout << "Nombre del video: " << eVideos[iCounter].getNombreEjemploVideo() << endl; break; } } cout << endl; } } void menu(char &opcion) { do { cout << endl << "M E N U " << endl; cout << "a. consultar información de materias, temas y autores" << endl; cout << "b. dar de alta videos de ejemplo" << endl; cout << "c. consultar la lista de videos por tema" << endl; cout << "d. consultar la lista de videos por materia" << endl; cout << "e. consultar lista de videos" << endl; cout << "f. consultar videos por autor" << endl; cout << "g. terminar" << endl; cout << "Opcion -> "; cin >> opcion; switch (opcion) { case 'a': mostrarMaterias(); mostrarTemas(); mostrarAutores(); break; case 'b': agregarEVideos(); break; case 'c': buscarPorTema(); break; case 'd': buscarPorMateria(); break; case 'e': consultarVideos(); break; case 'f': buscarPorAutor(); break; } } while (opcion != 'g'); } //meter los ifstreams a cada función de cargar datos int main() { char opcion; cargarDatosMaterias(); cargarDatosTemas(); cargarDatosAutores(); cargarDatosEVideos(); menu(opcion); cantidadEVideosG++; return 0; }
28.623077
114
0.5448
9710455bfa31dd6d4cbc8488a2e2b731c93b7598
2,848
cpp
C++
projects-lib/opengl-wrapper/draw/GLSquare.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
15
2019-01-13T16:07:27.000Z
2021-09-27T15:18:58.000Z
projects-lib/opengl-wrapper/draw/GLSquare.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
1
2019-03-14T00:36:35.000Z
2020-12-29T11:48:09.000Z
projects-lib/opengl-wrapper/draw/GLSquare.cpp
A-Ribeiro/OpenGLStarter
0552513f24ce3820b4957b1e453e615a9b77c8ff
[ "MIT" ]
3
2020-03-02T21:28:56.000Z
2021-09-27T15:18:50.000Z
#include "GLSquare.h" #include <opengl-wrapper/PlatformGL.h> namespace openglWrapper { //short drawOrder[6] = { 0, 1, 2, 0, 2, 3 }; // order to draw vertices GLSquare::GLSquare() { } void GLSquare::draw(GLShaderColor *shader) { const int COORDS_PER_POS = 3; const int STRUCTURE_STRIDE_BYTES_POS = COORDS_PER_POS * sizeof(float); const int VERTEX_COUNT = 4; const float vertexBuffer[12] = { -1.0f, 1.0f, 0.0f, // top left -1.0f, -1.0f, 0.0f, // bottom left 1.0f, -1.0f, 0.0f, // bottom right 1.0f, 1.0f, 0.0f }; // top right // // Set the vertex position attrib array // OPENGL_CMD(glEnableVertexAttribArray(GLShaderColor::vPosition)); OPENGL_CMD(glVertexAttribPointer(GLShaderColor::vPosition, COORDS_PER_POS, GL_FLOAT, false, STRUCTURE_STRIDE_BYTES_POS, vertexBuffer)); // // Draw quad // OPENGL_CMD(glDrawArrays(GL_TRIANGLE_FAN, 0, VERTEX_COUNT)); // // Disable arrays after draw // OPENGL_CMD(glDisableVertexAttribArray(GLShaderTextureColor::vPosition)); } void GLSquare::draw(GLShaderTextureColor *shader) { const int COORDS_PER_POS = 3; const int STRUCTURE_STRIDE_BYTES_POS = COORDS_PER_POS * sizeof(float); const int COORDS_PER_UV = 2; const int STRUCTURE_STRIDE_BYTES_UV = COORDS_PER_UV * sizeof(float); const int VERTEX_COUNT = 4; const float vertexBuffer[12] = { -1.0f, 1.0f, 0.0f, // top left -1.0f, -1.0f, 0.0f, // bottom left 1.0f, -1.0f, 0.0f, // bottom right 1.0f, 1.0f, 0.0f }; // top right const float uvBuffer[8] = { 0, 0, // top left 0, 1, // bottom left 1, 1, // bottom right 1, 0 }; // top right // // Set the vertex position attrib array // OPENGL_CMD(glEnableVertexAttribArray(GLShaderTextureColor::vPosition)); OPENGL_CMD(glVertexAttribPointer(GLShaderTextureColor::vPosition, COORDS_PER_POS, GL_FLOAT, false, STRUCTURE_STRIDE_BYTES_POS, vertexBuffer)); // // Set the vertex uv attrib array // OPENGL_CMD(glEnableVertexAttribArray(GLShaderTextureColor::vUV)); OPENGL_CMD(glVertexAttribPointer(GLShaderTextureColor::vUV, COORDS_PER_UV, GL_FLOAT, false, STRUCTURE_STRIDE_BYTES_UV, uvBuffer)); // // Draw quad // OPENGL_CMD(glDrawArrays(GL_TRIANGLE_FAN, 0, VERTEX_COUNT)); // // Disable arrays after draw // OPENGL_CMD(glDisableVertexAttribArray(GLShaderTextureColor::vPosition)); OPENGL_CMD(glDisableVertexAttribArray(GLShaderTextureColor::vUV)); } }
30.956522
150
0.601475
9710f58c33f0561bfe2070f30e4e86b72d6a9a41
10,075
cc
C++
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/auth/negotiate/auth_negotiate.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 29 Negotiate Authenticator * AUTHOR: Robert Collins, Henrik Nordstrom, Francesco Chemolli * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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, USA. * */ /* The functions in this file handle authentication. * They DO NOT perform access control or auditing. * See acl.c for access control and client_side.c for auditing */ #include "squid.h" #include "auth/negotiate/auth_negotiate.h" #include "auth/Gadgets.h" #include "auth/State.h" #include "cache_cf.h" #include "mgr/Registration.h" #include "Store.h" #include "client_side.h" #include "HttpHeaderTools.h" #include "HttpReply.h" #include "HttpRequest.h" #include "SquidTime.h" #include "auth/negotiate/Scheme.h" #include "auth/negotiate/User.h" #include "auth/negotiate/UserRequest.h" #include "wordlist.h" /** \defgroup AuthNegotiateInternal Negotiate Authenticator Internals \ingroup AuthNegotiateAPI */ /* Negotiate Scheme */ static AUTHSSTATS authenticateNegotiateStats; /// \ingroup AuthNegotiateInternal statefulhelper *negotiateauthenticators = NULL; /// \ingroup AuthNegotiateInternal static int authnegotiate_initialised = 0; /// \ingroup AuthNegotiateInternal static hash_table *proxy_auth_cache = NULL; /* * * Private Functions * */ void Auth::Negotiate::Config::rotateHelpers() { /* schedule closure of existing helpers */ if (negotiateauthenticators) { helperStatefulShutdown(negotiateauthenticators); } /* NP: dynamic helper restart will ensure they start up again as needed. */ } void Auth::Negotiate::Config::done() { authnegotiate_initialised = 0; if (negotiateauthenticators) { helperStatefulShutdown(negotiateauthenticators); } if (!shutting_down) return; delete negotiateauthenticators; negotiateauthenticators = NULL; if (authenticateProgram) wordlistDestroy(&authenticateProgram); debugs(29, DBG_IMPORTANT, "Reconfigure: Negotiate authentication configuration cleared."); } void Auth::Negotiate::Config::dump(StoreEntry * entry, const char *name, Auth::Config * scheme) { wordlist *list = authenticateProgram; storeAppendPrintf(entry, "%s %s", name, "negotiate"); while (list != NULL) { storeAppendPrintf(entry, " %s", list->key); list = list->next; } storeAppendPrintf(entry, "\n%s negotiate children %d startup=%d idle=%d concurrency=%d\n", name, authenticateChildren.n_max, authenticateChildren.n_startup, authenticateChildren.n_idle, authenticateChildren.concurrency); storeAppendPrintf(entry, "%s %s keep_alive %s\n", name, "negotiate", keep_alive ? "on" : "off"); } Auth::Negotiate::Config::Config() : keep_alive(1) { } void Auth::Negotiate::Config::parse(Auth::Config * scheme, int n_configured, char *param_str) { if (strcasecmp(param_str, "program") == 0) { if (authenticateProgram) wordlistDestroy(&authenticateProgram); parse_wordlist(&authenticateProgram); requirePathnameExists("auth_param negotiate program", authenticateProgram->key); } else if (strcasecmp(param_str, "children") == 0) { authenticateChildren.parseConfig(); } else if (strcasecmp(param_str, "keep_alive") == 0) { parse_onoff(&keep_alive); } else { debugs(29, DBG_CRITICAL, "ERROR: unrecognised Negotiate auth scheme parameter '" << param_str << "'"); } } const char * Auth::Negotiate::Config::type() const { return Auth::Negotiate::Scheme::GetInstance()->type(); } /** * Initialize helpers and the like for this auth scheme. * Called AFTER parsing the config file */ void Auth::Negotiate::Config::init(Auth::Config * scheme) { if (authenticateProgram) { authnegotiate_initialised = 1; if (negotiateauthenticators == NULL) negotiateauthenticators = new statefulhelper("negotiateauthenticator"); if (!proxy_auth_cache) proxy_auth_cache = hash_create((HASHCMP *) strcmp, 7921, hash_string); assert(proxy_auth_cache); negotiateauthenticators->cmdline = authenticateProgram; negotiateauthenticators->childs.updateLimits(authenticateChildren); negotiateauthenticators->ipc_type = IPC_STREAM; helperStatefulOpenServers(negotiateauthenticators); } } void Auth::Negotiate::Config::registerWithCacheManager(void) { Mgr::RegisterAction("negotiateauthenticator", "Negotiate User Authenticator Stats", authenticateNegotiateStats, 0, 1); } bool Auth::Negotiate::Config::active() const { return authnegotiate_initialised == 1; } bool Auth::Negotiate::Config::configured() const { if (authenticateProgram && (authenticateChildren.n_max != 0)) { debugs(29, 9, HERE << "returning configured"); return true; } debugs(29, 9, HERE << "returning unconfigured"); return false; } /* Negotiate Scheme */ void Auth::Negotiate::Config::fixHeader(Auth::UserRequest::Pointer auth_user_request, HttpReply *rep, http_hdr_type reqType, HttpRequest * request) { if (!authenticateProgram) return; /* Need keep-alive */ if (!request->flags.proxyKeepalive && request->flags.mustKeepalive) return; /* New request, no user details */ if (auth_user_request == NULL) { debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate"); if (!keep_alive) { /* drop the connection */ rep->header.delByName("keep-alive"); request->flags.proxyKeepalive = 0; } } else { Auth::Negotiate::UserRequest *negotiate_request = dynamic_cast<Auth::Negotiate::UserRequest *>(auth_user_request.getRaw()); assert(negotiate_request != NULL); switch (negotiate_request->user()->credentials()) { case Auth::Failed: /* here it makes sense to drop the connection, as auth is * tied to it, even if MAYBE the client could handle it - Kinkie */ rep->header.delByName("keep-alive"); request->flags.proxyKeepalive = 0; /* fall through */ case Auth::Ok: /* Special case: authentication finished OK but disallowed by ACL. * Need to start over to give the client another chance. */ if (negotiate_request->server_blob) { debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate " << negotiate_request->server_blob << "'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate %s", negotiate_request->server_blob); safe_free(negotiate_request->server_blob); } else { debugs(29, 9, HERE << "Connection authenticated"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate"); } break; case Auth::Unchecked: /* semantic change: do not drop the connection. * 2.5 implementation used to keep it open - Kinkie */ debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate"); break; case Auth::Handshake: /* we're waiting for a response from the client. Pass it the blob */ debugs(29, 9, HERE << "Sending type:" << reqType << " header: 'Negotiate " << negotiate_request->server_blob << "'"); httpHeaderPutStrf(&rep->header, reqType, "Negotiate %s", negotiate_request->server_blob); safe_free(negotiate_request->server_blob); break; default: debugs(29, DBG_CRITICAL, "ERROR: Negotiate auth fixHeader: state " << negotiate_request->user()->credentials() << "."); fatal("unexpected state in AuthenticateNegotiateFixErrorHeader.\n"); } } } static void authenticateNegotiateStats(StoreEntry * sentry) { helperStatefulStats(sentry, negotiateauthenticators, "Negotiate Authenticator Statistics"); } /* * Decode a Negotiate [Proxy-]Auth string, placing the results in the passed * Auth_user structure. */ Auth::UserRequest::Pointer Auth::Negotiate::Config::decode(char const *proxy_auth) { Auth::Negotiate::User *newUser = new Auth::Negotiate::User(Auth::Config::Find("negotiate")); Auth::UserRequest *auth_user_request = new Auth::Negotiate::UserRequest(); assert(auth_user_request->user() == NULL); auth_user_request->user(newUser); auth_user_request->user()->auth_type = Auth::AUTH_NEGOTIATE; /* all we have to do is identify that it's Negotiate - the helper does the rest */ debugs(29, 9, HERE << "decode Negotiate authentication"); return auth_user_request; }
33.250825
151
0.669181
97119b216fa931d06d1caaf67a230202aa9805f0
451
cpp
C++
game/tile.cpp
StylishTriangles/Scrabble
9d24a598ad552533d1cdf4a47fae586d8f6cb607
[ "MIT" ]
null
null
null
game/tile.cpp
StylishTriangles/Scrabble
9d24a598ad552533d1cdf4a47fae586d8f6cb607
[ "MIT" ]
null
null
null
game/tile.cpp
StylishTriangles/Scrabble
9d24a598ad552533d1cdf4a47fae586d8f6cb607
[ "MIT" ]
null
null
null
#include "tile.h" /** * @brief Default constructor for Tile. **/ Tile::Tile() : modified(false), bonus(BONUS_NONE), letter(L' '), backup(letter) { } /** * @brief Set character representing this Tile. * @param ch: Character to represent this Tile object. **/ void Tile::set(wchar_t ch) { if (ch != letter) { if (!modified) { backup = letter; modified = true; } letter = ch; } }
16.703704
54
0.547672
97147701e11e92d08470269a5d390fa33c4699b5
6,715
cpp
C++
src/tcp/socket_manager.cpp
alipay/sofa-bolt-cpp
6f422c0a8767ff8292db2b7c0557f9990219eb6b
[ "Apache-2.0" ]
13
2018-09-05T07:10:11.000Z
2019-04-30T01:31:32.000Z
src/tcp/socket_manager.cpp
sofastack/sofa-bolt-cpp
6f422c0a8767ff8292db2b7c0557f9990219eb6b
[ "Apache-2.0" ]
1
2018-11-03T03:54:40.000Z
2018-11-05T11:37:33.000Z
src/tcp/socket_manager.cpp
sofastack/sofa-bolt-cpp
6f422c0a8767ff8292db2b7c0557f9990219eb6b
[ "Apache-2.0" ]
2
2019-09-08T13:52:09.000Z
2021-04-21T08:42:08.000Z
// Copyright (c) 2018 Ant Financial, Inc. All Rights Reserved // Created by zhenggu.xwt on 18/4/13. // #include "socket_manager.h" #include <future> #include <poll.h> #include "common/utils.h" #include "session/session.h" #include "schedule/schedule.h" #include "common/log.h" namespace antflash { bool SocketManager::init() { _exit.store(false, std::memory_order_release); int reclaim_fd[2]; reclaim_fd[0] = -1; reclaim_fd[1] = -1; if (pipe(reclaim_fd) != 0) { return false; } _reclaim_fd[0] = reclaim_fd[0]; _reclaim_fd[1] = reclaim_fd[1]; auto size = Schedule::getInstance().scheduleThreadSize(); _on_reclaim.reserve(size); _reclaim_notify_flag.resize(size, false); for (size_t i = 0; i < size; ++i) { _on_reclaim.emplace_back([this, i]() { _reclaim_notify_flag[i] = true; Schedule::getInstance().removeSchedule( _reclaim_fd[1].fd(), POLLOUT, i); std::lock_guard<std::mutex> guard(_reclaim_mtx); _reclaim_notify.notify_one(); }); } _thread.reset(new std::thread([this](){ while (!_exit.load(std::memory_order_acquire)) { watchConnections(); std::this_thread::sleep_for(std::chrono::seconds(1)); } })); return true; } void SocketManager::destroy() { _exit.store(true, std::memory_order_release); if (_thread && _thread->joinable()) { _thread->join(); _thread.reset(); } //reclaim all socket's memory for (auto& socket : _list) { //If channel still holds exclusive when socket manager destroy, //which means channel is still alive when whole process is //going to shut down, in this case, we granted that no more //socket request will be sent, and related socket will be // destroyed in channel. if (socket->_sharers.tryUpgrade()) { socket->_sharers.exclusive(); } //Just push to reclaim list _reclaim_list.push_back(socket); } _list.clear(); //As socket manager is destroyed after schedule manager, clear reclaim list directly for (auto socket : _reclaim_list) { socket->_on_read = std::function<void()>(); LOG_DEBUG("reset socket:{}", socket->fd()); } _reclaim_list.clear(); } void SocketManager::addWatch(std::shared_ptr<Socket>& socket) { std::lock_guard<std::mutex> lock_guard(_mtx); _list.push_back(socket); } void SocketManager::watchConnections() { std::vector<std::shared_ptr<Socket>> sockets; //1. Collect sockets to be reclaimed or to be watched { std::lock_guard<std::mutex> lock_guard(_mtx); sockets.reserve(_list.size()); for (auto itr = _list.begin(); itr != _list.end();) { //As channel always exclusive it's socket when socket is active //If socket's exclusive status can be catch in socket manager, //it means this socket needs to be reclaimed. if ((*itr)->tryExclusive()) { LOG_INFO("socket[{}] is going to be reclaimed.", (*itr)->fd()); //Disconnect socket just remove OnRead handler, we can not reclaim this // socket directly after disconnect as schedule manager may still call // this socket's OnRead event in its loop before it receive schedule // remove message, we could only do it in next loop. (*itr)->disconnect(); _reclaim_list.emplace_back(*itr); itr = _list.erase(itr); } else { sockets.emplace_back(*itr); ++itr; } } } //2. Try to reclaim socket if (!_reclaim_list.empty()) { size_t schedule_size = Schedule::getInstance().scheduleThreadSize(); size_t cur_idx = _reclaim_counter++ % schedule_size; _reclaim_notify_flag[cur_idx] = false; Schedule::getInstance().addSchedule( _reclaim_fd[1].fd(), POLLOUT, _on_reclaim[cur_idx], cur_idx); std::unique_lock<std::mutex> lock(_reclaim_mtx); auto status = _reclaim_notify.wait_for( lock, std::chrono::milliseconds(500), [this, cur_idx]() { return _reclaim_notify_flag[cur_idx]; }); //Receiving notify successfully from schedule must happen in next loop as //adding schedule of reclaim is after removing schedule of sockets. //And in this case, sockets can be reclaimed safety. if (status) { for (auto itr = _reclaim_list.begin(); itr != _reclaim_list.end();) { if (((*itr)->fd() % schedule_size) == cur_idx) { //release socket shared_from_this so that memory can be reclaimed (*itr)->_on_read = std::function<void()>(); LOG_DEBUG("reset socket:{}", (*itr)->fd()); itr = _reclaim_list.erase(itr); } else { ++itr; } } } } //3. send heartbeat to watch sockets for (auto& socket : sockets) { //If socket status is not active, and still in watch list, it means //this socket is not used by any other session yet, just skip it if (!socket->active()) { continue; } auto last_active_time = socket->get_last_active_time(); if (SOCKET_MAX_IDLE_US < Utils::getHighPrecisionTimeStamp() - last_active_time) { if (socket->_protocol && socket->_protocol->assemble_heartbeat_fn) { std::shared_ptr<RequestBase> request; std::shared_ptr<ResponseBase> response; if (socket->_protocol->assemble_heartbeat_fn(request, response)) { Session ss; ss.send(*request) .to(socket) .timeout(SOCKET_TIMEOUT_MS) .receiveTo(*response) .sync(); if (ss.failed()) { socket->setStatus(RPC_STATUS_SOCKET_CONNECT_FAIL); } else { if (!socket->_protocol->parse_heartbeat_fn(response)) { socket->setStatus(RPC_STATUS_SOCKET_CONNECT_FAIL); } else { LOG_INFO("remote[{}] heartbeat success", socket->getRemote().ipToStr()); } } } } } } } }
36.494565
88
0.554728
971667fd5c4d2259c9287db4407c7eaa04968372
10,064
cpp
C++
src/subsys/CompBot/CompBotChassis.cpp
Team302/2017Steamworks
757a5332c47dd007482e30ee067852d13582ba39
[ "MIT" ]
null
null
null
src/subsys/CompBot/CompBotChassis.cpp
Team302/2017Steamworks
757a5332c47dd007482e30ee067852d13582ba39
[ "MIT" ]
1
2018-09-07T14:14:28.000Z
2018-09-13T04:01:33.000Z
src/subsys/CompBot/CompBotChassis.cpp
Team302/2017Steamworks
757a5332c47dd007482e30ee067852d13582ba39
[ "MIT" ]
null
null
null
/* * CompBotChassis.cpp * * Created on: Jan 16, 2017 * Author: Austin/Neethan */ #include <utils/DragonTalon.h> #include <utils/LimitValue.h> #include <subsys/CompBot/CompBotChassis.h> #include <subsys/CompBot/CompMap.h> #include <subsys/interfaces/IChassis.h> #include <SmartDashboard/SmartDashboard.h> namespace Team302 { float CompBotChassis::GetLeftDistance() const { return GetRightDistance(); } float CompBotChassis::GetRightDistance() const { float rightPos = m_rightMasterMotor->GetEncPosition(); frc::SmartDashboard::PutNumber("encoder distance conversion", ENCODER_DISTANCE_CONVERSION); return ((rightPos) * ENCODER_DISTANCE_CONVERSION ); } float CompBotChassis::GetLeftBackDistance() const { return GetRightBackDistance(); } float CompBotChassis::GetLeftFrontDistance() const { return GetRightFrontDistance(); } float CompBotChassis::GetRightBackDistance() const { return GetRightDistance(); } float CompBotChassis::GetRightFrontDistance() const { return GetRightDistance(); } float CompBotChassis::GetLeftVelocity() const { return GetRightVelocity(); } float CompBotChassis::GetRightVelocity() const { float rightMotorVel = m_rightMasterMotor->GetEncVel(); return ((rightMotorVel) * ENCODER_VELOCITY_CONVERSION ); } float CompBotChassis::GetLeftBackVelocity() const { return GetRightBackVelocity(); } float CompBotChassis::GetLeftFrontVelocity() const { return GetRightFrontVelocity(); } float CompBotChassis::GetRightBackVelocity() const { return GetRightVelocity(); } float CompBotChassis::GetRightFrontVelocity() const { return GetRightVelocity(); } void CompBotChassis::ResetDistance() { m_leftSlaveMotor->Reset(); m_leftMasterMotor->Reset(); m_rightSlaveMotor->Reset(); m_rightMasterMotor->Reset(); } void CompBotChassis::SetLeftPower(float power) { //Make sure the left side speed is within range and then set both left motors to this speed float leftSpeed = LimitValue::ForceInRange( power, -0.98, 0.98 ); m_leftMasterMotor->Set( leftSpeed ); } void CompBotChassis::SetRightPower(float power) { // Make sure the right side speed is within range and then set both right motors to this speed float rightSpeed = LimitValue::ForceInRange( power, -0.98, 0.98 ); m_rightMasterMotor->Set( rightSpeed ); } void CompBotChassis::SetBrakeMode(bool mode) { if(mode) { m_leftSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); m_rightSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); m_leftMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); m_rightMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Brake ); } else { m_leftSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); m_rightSlaveMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); m_leftMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); m_rightMasterMotor->ConfigNeutralMode( frc::CANSpeedController::kNeutralMode_Coast ); } } void CompBotChassis::SetControlMode(DragonTalon::DRAGON_CONTROL_MODE mode) { switch (mode) { case DragonTalon::POSITION: m_rightMasterMotor->SetControlMode(DragonTalon::POSITION); m_leftMasterMotor->SetControlMode(DragonTalon::POSITION); break; case DragonTalon::VELOCITY: m_rightMasterMotor->SetControlMode(DragonTalon::VELOCITY); m_leftMasterMotor->SetControlMode(DragonTalon::VELOCITY); break; case DragonTalon::THROTTLE: m_rightMasterMotor->SetControlMode(DragonTalon::THROTTLE); m_leftMasterMotor->SetControlMode(DragonTalon::THROTTLE); break; case DragonTalon::FOLLOWER: m_rightMasterMotor->SetControlMode(DragonTalon::FOLLOWER); m_leftMasterMotor->SetControlMode(DragonTalon::FOLLOWER); break; default: m_rightMasterMotor->SetControlMode(DragonTalon::THROTTLE); m_leftMasterMotor->SetControlMode(DragonTalon::THROTTLE); } } //---------------------------------------------------------------------------------- // Method: SetControlParams // Description: Sets PID and F factors to the motors and sets target. Target is // double for position in feet. Make sure to set // motor to POSITION control first. Once target is set, // motor will immediately start using it for position control // Params: double kP - proportional-gain value // double kI - integral-gain value // double kD - derivative-gain value // double kF - feed-forward factor // double leftTarget - target position in feet for left // double rightTarget - target position in feet for right //---------------------------------------------------------------------------------- void CompBotChassis::SetPositionParams(double kP, double kI, double kD, double kF, double leftTarget, double rightTarget) { m_rightMasterMotor->SetF(kF); //set feed-forward gain m_rightMasterMotor->SetP(kP); //set p-gain m_rightMasterMotor->SetI(kI); //set i-gain m_rightMasterMotor->SetD(kD); //set d-gain m_leftMasterMotor->SetF(kF); //set feed-forward gain m_leftMasterMotor->SetP(kP); //set p-gain m_leftMasterMotor->SetI(kI); //set i-gain m_leftMasterMotor->SetD(kD); //set d-gain m_rightMasterMotor->Set(rightTarget * FEET_TO_ROTATIONS); //set target position in rotations m_leftMasterMotor->Set(leftTarget * FEET_TO_ROTATIONS); //set target position in rotations } //---------------------------------------------------------------------------------- // Method: SetVelocityParams // Description: Sets PID and F factors to the motors and sets target. Target is // double for velocity in feet per second. Make sure to set // motor to VELOCITY control first. Once target is set, // motor will immediately start using it for velocity control // Params: double kP - proportional-gain value // double kI - integral-gain value // double kD - derivative-gain value // double kF - feed-forward factor // double leftTarget - target speed in feet per second for left // double rightTarget - target speed in feet per second for right //---------------------------------------------------------------------------------- void CompBotChassis::SetVelocityParams(double kP, double kI, double kD, double kF, double leftTarget, double rightTarget) { // SetControlMode(DragonTalon::VELOCITY); m_rightMasterMotor->SetF(kF); //set feed-forward gain m_rightMasterMotor->SetP(kP); //set p-gain m_rightMasterMotor->SetI(kI); //set i-gain m_rightMasterMotor->SetD(kD); //set d-gain m_leftMasterMotor->SetF(kF); //set feed-forward gain m_leftMasterMotor->SetP(kP); //set p-gain m_leftMasterMotor->SetI(kI); //set i-gain m_leftMasterMotor->SetD(kD); //set d-gain m_rightMasterMotor->Set(rightTarget * FPS_TO_RPM); //set target speed, converts from feet per second to rpm for talon use m_leftMasterMotor->Set(leftTarget * FPS_TO_RPM); //set target speed, converts from feet per second to rpm for talon use } void CompBotChassis::EnableCurrentLimiting() //Y key on driver { //Enable current limit m_leftMasterMotor->EnableCurrentLimit(true); m_leftSlaveMotor->EnableCurrentLimit(true); m_rightMasterMotor->EnableCurrentLimit(true); m_rightSlaveMotor->EnableCurrentLimit(true); } void CompBotChassis::DisableCurrentLimiting() //A key on driver { //Disable current limiting m_leftMasterMotor->EnableCurrentLimit(false); m_leftSlaveMotor->EnableCurrentLimit(false); m_rightMasterMotor->EnableCurrentLimit(false); m_rightSlaveMotor->EnableCurrentLimit(false); } void CompBotChassis::SetCurrentLimit(int amps) { //Set current limit m_leftMasterMotor->SetCurrentLimit(amps); m_leftSlaveMotor->SetCurrentLimit(amps); m_rightMasterMotor->SetCurrentLimit(amps); m_rightSlaveMotor->SetCurrentLimit(amps); } CompBotChassis::CompBotChassis(): //declare all of the motors m_leftSlaveMotor(new DragonTalon(LEFT_FRONT_DRIVE_MOTOR)), m_rightSlaveMotor(new DragonTalon(RIGHT_FRONT_DRIVE_MOTOR)), m_leftMasterMotor(new DragonTalon(LEFT_BACK_DRIVE_MOTOR)), m_rightMasterMotor(new DragonTalon(RIGHT_BACK_DRIVE_MOTOR)) { // Left Back Motor m_leftMasterMotor->SetFeedbackDevice(CANTalon::CtreMagEncoder_Relative); //sets the left master talon to use encoder as sensor m_leftMasterMotor->ConfigEncoderCodesPerRev(DRIVE_COUNTS_PER_REVOLUTION), // defines encoder counts per revolution m_leftMasterMotor->SetInverted (IS_LEFT_BACK_DRIVE_MOTOR_INVERTED); m_leftMasterMotor->SetSensorDirection (IS_LEFT_BACK_DRIVE_ENCODER_INVERTED); // Left Front Motor m_leftSlaveMotor->SetControlMode(DragonTalon::FOLLOWER); //sets the front left slave to follow output of the master m_leftSlaveMotor->Set(LEFT_BACK_DRIVE_MOTOR); //specifies that the left slave will follow master m_leftSlaveMotor->SetInverted(IS_LEFT_FRONT_DRIVE_MOTOR_INVERTED); // Right Back Motor m_rightMasterMotor->SetFeedbackDevice(CANTalon::CtreMagEncoder_Relative); //sets the right master talon to use encoder as sensor m_rightMasterMotor->ConfigEncoderCodesPerRev(DRIVE_COUNTS_PER_REVOLUTION), // defines encoder counts per revolution m_rightMasterMotor->SetInverted (IS_RIGHT_BACK_DRIVE_MOTOR_INVERTED); m_rightMasterMotor->SetSensorDirection (IS_RIGHT_BACK_DRIVE_ENCODER_INVERTED); // Right Front Motor m_rightSlaveMotor->SetControlMode(DragonTalon::FOLLOWER); //sets the front right to follow output of the master m_rightSlaveMotor->Set(RIGHT_BACK_DRIVE_MOTOR); //specifies that the right slave will follow master m_rightSlaveMotor->SetInverted (IS_RIGHT_FRONT_DRIVE_MOTOR_INVERTED); SetCurrentLimit( TALON_CURRENT_LIMIT ); EnableCurrentLimiting(); // //Enable current limit // m_leftMasterMotor->EnableCurrentLimit(true); // m_leftSlaveMotor->EnableCurrentLimit(true); // m_rightMasterMotor->EnableCurrentLimit(true); // m_rightSlaveMotor->EnableCurrentLimit(true); // // //Set current limit // m_leftMasterMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); // m_leftSlaveMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); // m_rightMasterMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); // m_rightSlaveMotor->SetCurrentLimit(TALON_CURRENT_LIMIT); } } /* namespace Team302 */
35.066202
129
0.760036
971733900a376ce3f61885343dbbdf7b00d930ed
6,427
cc
C++
lab5/set_assoc.cc
microHertz/ECS154B
e11bcc3299059358ae2e0435b60469382eb37364
[ "CC-BY-4.0" ]
null
null
null
lab5/set_assoc.cc
microHertz/ECS154B
e11bcc3299059358ae2e0435b60469382eb37364
[ "CC-BY-4.0" ]
null
null
null
lab5/set_assoc.cc
microHertz/ECS154B
e11bcc3299059358ae2e0435b60469382eb37364
[ "CC-BY-4.0" ]
1
2021-04-01T04:22:33.000Z
2021-04-01T04:22:33.000Z
#include <cassert> #include <cstring> #include "set_assoc.hh" #include "memory.hh" #include "processor.hh" #include "util.hh" SetAssociativeCache::SetAssociativeCache(int64_t size, Memory& memory, Processor& processor, int ways) : Cache(size, memory, processor), ways(ways), lines(size / memory.getLineSize()), tagBits(processor.getAddrSize() - log2int(lines) + log2int(ways) - memory.getLineBits()), indexMask(size / memory.getLineSize() / ways - 1), nextVictim(0), blocked(false) { assert(ways > 0); for (int i=0; i<ways; i++) { // Create one tag/data array for each way tagArrays.emplace_back(lines / ways, 2, tagBits); dataArrays.emplace_back(lines / ways, memory.getLineSize()); } } SetAssociativeCache::~SetAssociativeCache() { } int64_t SetAssociativeCache::getIndex(uint64_t address) { return (address >> memory.getLineBits()) & indexMask; } int SetAssociativeCache::getBlockOffset(uint64_t address) { return address & (memory.getLineSize() - 1); } uint64_t SetAssociativeCache::getTag(uint64_t address) { return address >> (processor.getAddrSize() - tagBits); } bool SetAssociativeCache::receiveRequest(uint64_t address, int size, const uint8_t* data, int request_id) { assert(size <= memory.getLineSize()); // within line size // within address range assert(address < ((uint64_t)1 << processor.getAddrSize())); assert((address & (size - 1)) == 0); // naturally aligned if (blocked) { DPRINT("Cache is blocked!"); // Cache is currently blocked, so it cannot receive a new request return false; } (++nextVictim) %= ways; int index = getIndex(address); int way = hit(address); if (way != -1) { DPRINT("Hit in cache"); // get a pointer to the data uint8_t* line = dataArrays[way].getLine(index); int block_offset = getBlockOffset(address); if (data) { // if this is a write, copy the data into the cache. memcpy(&line[block_offset], data, size); sendResponse(request_id, nullptr); // Mark dirty tagArrays[way].setState(index, Dirty); } else { // This is a read so we need to return data sendResponse(request_id, &line[block_offset]); } } else { int victim_way = evictionPolicy(address); uint64_t wb_address = tagArrays[victim_way].getTag(index) << (processor.getAddrSize() - tagBits); wb_address |= (index << memory.getLineBits()); DPRINT("Miss in cache. Victim way " << victim_way << " State " << tagArrays[victim_way].getState(index) << " Addr " << wb_address); if (dirty(address, victim_way)) { DPRINT("Dirty, writing back"); // If the line is dirty, then we need to evict it. uint8_t* line = dataArrays[victim_way].getLine(index); // Calculate the address of the writeback. // No response for writes, no need for valid request_id sendMemRequest(wb_address, memory.getLineSize(), line, -1); } // Mark the line invalid. tagArrays[victim_way].setState(index, Invalid); // Forward to memory and block the cache. // no need for req id since there is only one outstanding request. // We need to read whether the request is a read or write. uint64_t block_address = address & ~(memory.getLineSize() -1); sendMemRequest(block_address, memory.getLineSize(), nullptr, 0); // remember the CPU's request id mshr.savedId = request_id; // Remember the address mshr.savedAddr = address; // Remember the data if it is a write. mshr.savedSize = size; mshr.savedData = data; mshr.savedWay = victim_way; // Mark the cache as blocked blocked = true; } // We have accepted the request, so return true. return true; } void SetAssociativeCache::receiveMemResponse(int request_id, const uint8_t* data) { assert(request_id == 0); assert(data); int index = getIndex(mshr.savedAddr); int way = mshr.savedWay; // Copy the data into the cache. uint8_t* line = dataArrays[way].getLine(index); memcpy(line, data, memory.getLineSize()); assert(tagArrays[way].getState(index) == Invalid); // Mark valid tagArrays[way].setState(index, Valid); // Set tag tagArrays[way].setTag(index, getTag(mshr.savedAddr)); // Treat as a hit int block_offset = getBlockOffset(mshr.savedAddr); if (mshr.savedData) { // if this is a write, copy the data into the cache. memcpy(&line[block_offset], mshr.savedData, mshr.savedSize); sendResponse(mshr.savedId, nullptr); // Mark dirty tagArrays[way].setState(index, Dirty); } else { // This is a read so we need to return data sendResponse(mshr.savedId, &line[block_offset]); } blocked = false; mshr.savedId = -1; mshr.savedAddr = 0; mshr.savedSize = 0; mshr.savedWay = -1; mshr.savedData = nullptr; } int SetAssociativeCache::hit(uint64_t address) { int index = getIndex(address); int way = 0; for (auto& tagArray : tagArrays) { State state = (State)tagArray.getState(index); uint64_t line_tag = tagArray.getTag(index); // dirty implies valid if ((state == Valid || state == Dirty) && line_tag == getTag(address)) { return way; } way++; } return -1; // miss } bool SetAssociativeCache::dirty(uint64_t address, int way) { int index = getIndex(address); State state = (State)tagArrays[way].getState(index); return state == Dirty; } int SetAssociativeCache::evictionPolicy(uint64_t address) { int index = getIndex(address); int victim_way = nextVictim; int way = 0; for (auto& tagArray : tagArrays) { State state = (State)tagArray.getState(index); if (state == Invalid) { DPRINT("Address " << std::hex << address << " has room." << std::endl); return way; } way++; } DPRINT("Address " << std::hex << address << " NO room." << std::endl); return victim_way; }
29.481651
83
0.606504
9717b27939f1cd716d928179a9561929900d5c66
3,709
cpp
C++
src/base/muduo/net/poller/poll_poller.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
src/base/muduo/net/poller/poll_poller.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
src/base/muduo/net/poller/poll_poller.cpp
sbfhy/server1
b9597a3783a0f7bb929b4b9fa7f621c81740b056
[ "BSD-3-Clause" ]
null
null
null
#include "muduo/net/poller/poll_poller.h" #include "muduo/net/common/channel.h" #include "muduo/base/common/logging.h" #include "define/define_types.h" #include <asm-generic/errno-base.h> #include <assert.h> #include <errno.h> #include <poll.h> #include <sys/cdefs.h> using namespace muduo; using namespace muduo::net; PollPoller::PollPoller(EventLoop* loop) : Poller(loop) { } PollPoller::~PollPoller() = default; TimeStamp PollPoller::poll(SDWORD timeoutMs, ChannelList* activeChannels) { // XXX pollfds_ shouldn't change SDWORD numEvents = ::poll(&*m_pollfds.begin(), m_pollfds.size(), timeoutMs); SDWORD savedErrno = errno; TimeStamp now(TimeStamp::now()); if (numEvents > 0) { LOG_TRACE << numEvents << " events happened"; fillActiveChannels(numEvents, activeChannels); } else if (numEvents == 0) { LOG_TRACE << " nothing happened"; } else { if (savedErrno != EINTR) { errno = savedErrno; LOG_SYSERR << "PollPoller::poll()"; } } return now; } void PollPoller::fillActiveChannels(SDWORD numEvents, ChannelList* activeChannels) const { for (PollFdList::const_iterator pfd = m_pollfds.begin(); pfd != m_pollfds.end() && numEvents > 0; ++ pfd) { if (pfd->revents > 0) { -- numEvents; ChannelMap::const_iterator ch = m_channels.find(pfd->fd); assert(ch != m_channels.end()); Channel* channel = ch->second; assert(channel->getFd() == pfd->fd); channel->setRevents(pfd->revents); activeChannels->push_back(channel); } } } void PollPoller::UpdateChannel(Channel* channel) { Poller::AssertInLoopThread(); LOG_TRACE << "fd = " << channel->getFd() << " events = " << channel->getEvents(); if (channel->getIndex() < 0) { // a new one, add to pollfds_ assert(m_channels.find(channel->getFd()) == m_channels.end()); struct pollfd pfd; pfd.fd = channel->getFd(); pfd.events = static_cast<SWORD>(channel->getEvents()); pfd.revents = 0; m_pollfds.push_back(pfd); SDWORD idx = static_cast<SDWORD>(m_pollfds.size()) - 1; channel->setIndex(idx); m_channels[pfd.fd] = channel; } else { // update existing one assert(m_channels.find(channel->getFd()) != m_channels.end()); assert(m_channels[channel->getFd()] == channel); SDWORD idx = channel->getIndex(); assert(0 <= idx && idx < static_cast<SDWORD>(m_pollfds.size())); struct pollfd& pfd = m_pollfds[idx]; assert(pfd.fd == channel->getFd() || pfd.fd == -channel->getFd()-1); pfd.fd = channel->getFd(); pfd.events = static_cast<SWORD>(channel->getEvents()); pfd.revents = 0; if (channel->IsNoneEvent()) { pfd.fd = -channel->getFd() - 1; // 删除,屏蔽掉这个fd } } } void PollPoller::RemoveChannel(Channel* channel) { Poller::AssertInLoopThread(); LOG_TRACE << "fd = " << channel->getFd(); assert(m_channels.find(channel->getFd()) != m_channels.end()); assert(m_channels[channel->getFd()] == channel); assert(channel->IsNoneEvent()); SDWORD idx = channel->getIndex(); assert(0 <= idx && idx < static_cast<SDWORD>(m_pollfds.size())); const struct pollfd& pfd = m_pollfds[idx]; (void)pfd; assert(pfd.fd == -channel->getFd()-1 && pfd.events == channel->getEvents()); size_t n = m_channels.erase(channel->getFd()); assert(n == 1); (void)n; if (implicit_cast<size_t>(idx) == m_pollfds.size() - 1) { m_pollfds.pop_back(); } else { SDWORD channelAtEnd = m_pollfds.back().fd; iter_swap(m_pollfds.begin() + idx, m_pollfds.end() - 1); if (channelAtEnd < 0) { channelAtEnd = -channelAtEnd - 1; } m_channels[channelAtEnd]->setIndex(idx); m_pollfds.pop_back(); } }
28.312977
88
0.640874
97183bf80c9dbf7b6f32600a7f96ade0928d99f5
4,191
cpp
C++
Practice/2018/2018.12.29/BZOJ5417.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.12.29/BZOJ5417.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.12.29/BZOJ5417.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<vector> #include<iostream> using namespace std; #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define ll long long #define NAME "name" const int maxL=505000*2; const int maxAlpha=26; class Node{ public: int son[maxAlpha],fail,len; }; class SAM{ public: int nodecnt,root,lst,Pos[maxL]; Node S[maxL]; SAM(){ nodecnt=root=lst=1;return; } void Init(){ nodecnt=root=lst=1;mem(S[1].son,0);S[1].fail=S[1].len=0;Pos[1]=0; return; } int New(){ int p=++nodecnt;S[p].len=S[p].fail=0;mem(S[p].son,0);Pos[p]=0;return p; } void Extend(int c,int id){ int np=New(),p=lst;lst=np;S[np].len=S[p].len+1;Pos[np]=id; while (p&&!S[p].son[c]) S[p].son[c]=np,p=S[p].fail; if (!p) S[np].fail=root; else{ int q=S[p].son[c]; if (S[q].len==S[p].len+1) S[np].fail=q; else{ int nq=New();S[nq]=S[q];S[q].fail=S[np].fail=nq;S[nq].len=S[p].len+1;Pos[nq]=Pos[q]; while (p&&S[p].son[c]==q) S[p].son[c]=nq,p=S[p].fail; } } return; } }; int n,Mtc[maxL]; char Input[maxL]; SAM S,T; vector<int> TS[maxL]; void dfs_build(int x); namespace DS{ class SegmentData{ public: int ls,rs; }; int nodecnt,root[maxL]; SegmentData S[maxL*20]; void Insert(int &x,int l,int r,int pos); int Query(int x,int l,int r,int ql,int qr); int Merge(int x,int y); void outp(int x,int l,int r); } int main(){ //freopen(NAME".in","r",stdin);freopen(NAME".out","w",stdout); scanf("%s",Input+1);n=strlen(Input+1); for (int i=1;i<=n;i++){ S.Extend(Input[i]-'a',i); DS::Insert(DS::root[S.lst],1,n,i); } /* for (int i=1;i<=S.nodecnt;i++) for (int j=0;j<maxAlpha;j++) if (S.S[i].son[j]) cout<<i<<"->"<<S.S[i].son[j]<<" "<<(char)(j+'a')<<endl; for (int i=1;i<=S.nodecnt;i++) cout<<S.S[i].len<<" ";cout<<endl; for (int i=1;i<=S.nodecnt;i++) cout<<S.S[i].fail<<" ";cout<<endl; //*/ for (int i=2;i<=S.nodecnt;i++) TS[S.S[i].fail].push_back(i); dfs_build(1); int Q;scanf("%d",&Q); while (Q--){ int L,R,m;scanf("%s",Input+1);scanf("%d%d",&L,&R); m=strlen(Input+1);T.Init(); for (int i=1;i<=m;i++) T.Extend(Input[i]-'a',i); for (int i=1,x=1,cnt=0;i<=m;i++){ int c=Input[i]-'a'; //cout<<"running on :"<<i<<endl; while (x&&((!S.S[x].son[c])||( !DS::Query(DS::root[S.S[x].son[c]],1,n,L+S.S[S.S[S.S[x].son[c]].fail].len,R)))){ //cout<<"GetQ:"<<S.S[x].son[c]<<" ["<<L<<"+"<<S.S[S.S[S.S[x].son[c]].fail].len<<","<<R<<"]"<<endl; x=S.S[x].fail,cnt=S.S[x].len; } //cout<<"now:"<<x<<" "<<cnt<<endl; if (x==0){ x=1;cnt=0;Mtc[i]=0;continue; } x=S.S[x].son[c];++cnt; //cout<<"Q:"<<i<<" "<<x<<" "<<S.S[S.S[x].fail].len+1<<" "<<cnt<<endl; if (S.S[S.S[x].fail].len+1!=cnt){ int l=S.S[S.S[x].fail].len+1,r=cnt; do{ int mid=(l+r)>>1; if (DS::Query(DS::root[x],1,n,L+mid-1,R)) cnt=mid,l=mid+1; else r=mid-1; } while (l<=r); } Mtc[i]=cnt; } ll Ans=0; //for (int i=1;i<=m;i++) cout<<Mtc[i]<<" ";cout<<endl; for (int i=1;i<=T.nodecnt;i++) Ans=Ans+max(0,T.S[i].len-max(T.S[T.S[i].fail].len,Mtc[T.Pos[i]])); printf("%lld\n",Ans); } return 0; } void dfs_build(int x){ for (int i=0,sz=TS[x].size();i<sz;i++){ dfs_build(TS[x][i]); DS::root[x]=DS::Merge(DS::root[x],DS::root[TS[x][i]]); } return; } namespace DS{ void Insert(int &x,int l,int r,int pos){ if (x==0) x=++nodecnt; if (l==r) return; int mid=(l+r)>>1; if (pos<=mid) Insert(S[x].ls,l,mid,pos); else Insert(S[x].rs,mid+1,r,pos); return; } int Query(int x,int l,int r,int ql,int qr){ //cout<<"Q:"<<x<<" "<<l<<" "<<r<<" "<<ql<<" "<<qr<<endl; if (ql>qr) return 0; if (x==0) return 0;if ((l==ql)&&(r==qr)) return 1; int mid=(l+r)>>1; if (qr<=mid) return Query(S[x].ls,l,mid,ql,qr); else if (ql>=mid+1) return Query(S[x].rs,mid+1,r,ql,qr); else return Query(S[x].ls,l,mid,ql,mid)|Query(S[x].rs,mid+1,r,mid+1,qr); } int Merge(int x,int y){ if ((!x)||(!y)) return x+y; int u=++nodecnt; S[u].ls=Merge(S[x].ls,S[y].ls);S[u].rs=Merge(S[x].rs,S[y].rs); return u; } void outp(int x,int l,int r){ if (x==0) return; if (l==r){ return; } int mid=(l+r)>>1; outp(S[x].ls,l,mid);outp(S[x].rs,mid+1,r);return; } }
25.4
102
0.545455
97189995a32bdf90aa00afcba997e87849321c16
6,186
cpp
C++
Tools/DcmCmoveSCU/dicomquery.cpp
zyq1569/HealthApp
9e96e8759aad577693f597b5763febd2094767ee
[ "BSD-3-Clause" ]
3
2020-06-30T02:44:30.000Z
2022-01-13T12:27:09.000Z
Tools/DcmCmoveSCU/dicomquery.cpp
zyq1569/HealthApp
9e96e8759aad577693f597b5763febd2094767ee
[ "BSD-3-Clause" ]
3
2021-12-14T20:45:20.000Z
2021-12-18T18:22:04.000Z
Tools/DcmCmoveSCU/dicomquery.cpp
zyq1569/HealthApp
9e96e8759aad577693f597b5763febd2094767ee
[ "BSD-3-Clause" ]
6
2019-09-19T11:40:48.000Z
2020-12-07T08:01:52.000Z
#include "dicomquery.h" #include <boost/thread.hpp> // work around the fact that dcmtk doesn't work in unicode mode, so all string operation needs to be converted from/to mbcs #ifdef _UNICODE #undef _UNICODE #undef UNICODE #define _UNDEFINEDUNICODE #endif #include "dcmtk/ofstd/ofstd.h" #include "dcmtk/oflog/oflog.h" #include "dcmtk/dcmdata/dctk.h" #include "dcmtk/dcmnet/scu.h" // check DCMTK functionality #if !defined(WIDE_CHAR_FILE_IO_FUNCTIONS) && defined(_WIN32) //#error "DCMTK and this program must be compiled with DCMTK_WIDE_CHAR_FILE_IO_FUNCTIONS" #endif #ifdef _UNDEFINEDUNICODE #define _UNICODE 1 #define UNICODE 1 #endif DICOMQueryScanner::DICOMQueryScanner(PatientData &patientdata) : patientdata(patientdata) { cancelEvent = doneEvent = false; } DICOMQueryScanner::~DICOMQueryScanner() { } bool DICOMQueryScanner::ScanPatientName(std::string name, DestinationEntry &destination) { class MyDcmSCU : public DcmSCU { public: MyDcmSCU(PatientData &patientdata, DICOMQueryScanner &scanner) : patientdata(patientdata), scanner(scanner) {} PatientData &patientdata; DICOMQueryScanner &scanner; OFCondition handleFINDResponse(const T_ASC_PresentationContextID presID, QRResponse *response, OFBool &waitForNextResponse) { OFCondition ret = DcmSCU::handleFINDResponse(presID, response, waitForNextResponse); if (ret.good() && response->m_dataset != NULL) { OFString patientname, patientid, birthday; OFString studyuid, modality, studydesc, studydate; response->m_dataset->findAndGetOFString(DCM_StudyInstanceUID, studyuid); response->m_dataset->findAndGetOFString(DCM_PatientID, patientid); response->m_dataset->findAndGetOFString(DCM_PatientName, patientname); response->m_dataset->findAndGetOFString(DCM_StudyDescription, studydesc); response->m_dataset->findAndGetOFString(DCM_StudyDate, studydate); patientdata.AddStudy(studyuid.c_str(), patientid.c_str(), patientname.c_str(), studydesc.c_str(), studydate.c_str()); } if (scanner.IsCanceled()) waitForNextResponse = false; return ret; } }; if (IsCanceled()) return true; MyDcmSCU scu(patientdata, *this); scu.setVerbosePCMode(true); scu.setAETitle(destination.ourAETitle.c_str()); scu.setPeerHostName(destination.destinationHost.c_str()); scu.setPeerPort(destination.destinationPort); scu.setPeerAETitle(destination.destinationAETitle.c_str()); scu.setACSETimeout(30); scu.setDIMSETimeout(60); scu.setDatasetConversionMode(true); OFList<OFString> defaulttransfersyntax; defaulttransfersyntax.push_back(UID_LittleEndianExplicitTransferSyntax); scu.addPresentationContext(UID_FINDStudyRootQueryRetrieveInformationModel, defaulttransfersyntax); OFCondition cond; if (scu.initNetwork().bad()) return false; if (scu.negotiateAssociation().bad()) return false; T_ASC_PresentationContextID pid = scu.findAnyPresentationContextID(UID_FINDStudyRootQueryRetrieveInformationModel, UID_LittleEndianExplicitTransferSyntax); DcmDataset query; query.putAndInsertString(DCM_QueryRetrieveLevel, "STUDY"); query.putAndInsertString(DCM_StudyInstanceUID, ""); query.putAndInsertString(DCM_PatientName, name.c_str()); query.putAndInsertString(DCM_PatientID, ""); query.putAndInsertString(DCM_StudyDate, ""); query.putAndInsertString(DCM_StudyDescription, ""); query.putAndInsertSint16(DCM_NumberOfStudyRelatedInstances, 0); scu.sendFINDRequest(pid, &query, NULL); scu.releaseAssociation(); return true; } void DICOMQueryScanner::DoQueryAsync(DestinationEntry &destination) { SetDone(false); ClearCancel(); m_destination = destination; boost::thread t(DICOMQueryScanner::DoQueryThread, this); t.detach(); } void DICOMQueryScanner::DoQueryThread(void *obj) { DICOMQueryScanner *me = (DICOMQueryScanner *) obj; if(me) { me->DoQuery(me->m_destination); me->SetDone(true); } } void DICOMQueryScanner::DoQuery(DestinationEntry &destination) { OFLog::configure(OFLogger::OFF_LOG_LEVEL); // catch any access errors try { ScanPatientName("a", destination); ScanPatientName("e", destination); ScanPatientName("i", destination); ScanPatientName("o", destination); ScanPatientName("u", destination); } catch(...) { } } bool DICOMQueryScanner::Echo(DestinationEntry destination) { DcmSCU scu; scu.setVerbosePCMode(true); scu.setAETitle(destination.ourAETitle.c_str()); scu.setPeerHostName(destination.destinationHost.c_str()); scu.setPeerPort(destination.destinationPort); scu.setPeerAETitle(destination.destinationAETitle.c_str()); scu.setACSETimeout(30); scu.setDIMSETimeout(60); scu.setDatasetConversionMode(true); OFList<OFString> transfersyntax; transfersyntax.push_back(UID_LittleEndianExplicitTransferSyntax); transfersyntax.push_back(UID_LittleEndianImplicitTransferSyntax); scu.addPresentationContext(UID_VerificationSOPClass, transfersyntax); OFCondition cond; cond = scu.initNetwork(); if (cond.bad()) return false; cond = scu.negotiateAssociation(); if (cond.bad()) return false; cond = scu.sendECHORequest(0); scu.releaseAssociation(); if (cond == EC_Normal) { return true; } return false; } void DICOMQueryScanner::Cancel() { boost::mutex::scoped_lock lk(mutex); cancelEvent = true; } void DICOMQueryScanner::ClearCancel() { boost::mutex::scoped_lock lk(mutex); cancelEvent = false; } bool DICOMQueryScanner::IsDone() { boost::mutex::scoped_lock lk(mutex); return doneEvent; } bool DICOMQueryScanner::IsCanceled() { boost::mutex::scoped_lock lk(mutex); return cancelEvent; } void DICOMQueryScanner::SetDone(bool state) { boost::mutex::scoped_lock lk(mutex); doneEvent = state; }
27.371681
159
0.707727
971ba38196a99e61d55b148d731d5f280f161836
5,735
cpp
C++
src/TEXBModify.cpp
MikuAuahDark/Itsudemo
3e939414bff6d21abd41670dd7278435721075ae
[ "Zlib" ]
30
2016-02-26T16:21:39.000Z
2021-07-21T06:42:33.000Z
src/TEXBModify.cpp
Ink-33/Itsudemo
3e939414bff6d21abd41670dd7278435721075ae
[ "Zlib" ]
3
2016-08-25T16:37:12.000Z
2016-11-27T06:26:32.000Z
src/TEXBModify.cpp
Ink-33/Itsudemo
3e939414bff6d21abd41670dd7278435721075ae
[ "Zlib" ]
14
2016-04-03T15:42:56.000Z
2019-09-16T02:08:33.000Z
/** * TEXBModify.cpp * Modification of TextureBank class **/ #include "TEXB.h" #include "xy2uv.h" #include <algorithm> #include <vector> #include <map> #include <string> #include <cerrno> #include <cstdlib> #include <cstring> TextureBank::TextureBank(uint32_t _Width,uint32_t _Height):Width(RawImageWidth),Height(RawImageHeight),Flags(_Flags) { uint32_t rawimage_size=_Width*_Height*4; RawImageWidth=_Width; RawImageHeight=_Height; RawImage=LIBTEXB_ALLOC(uint8_t,rawimage_size); // 4-byte/pixel _Flags=0; memset(RawImage,0,rawimage_size); } TextureBank::~TextureBank() { for(uint32_t i=0;i<this->ImageList_Id.size();i++) { TextureImage* a=this->ImageList_Id[i]; uint32_t* b=this->VertexIndexUVs[i]; if(a->from_texb==this) delete a; LIBTEXB_FREE(b); } } TextureBank* TextureBank::Clone() { TextureBank* texb=new TextureBank; uint32_t memsize=Width*Height*4; texb->RawImageWidth=Width; texb->RawImageHeight=Height; texb->RawImage=LIBTEXB_ALLOC(uint8_t,memsize); texb->Name=Name; memcpy(texb->RawImage,RawImage,memsize); memsize=ImageList_Id.size(); for(uint32_t i=0;i<memsize;i++) { TextureImage* timg=ImageList_Id[i]->Clone(); uint32_t* VrtxMem=reinterpret_cast<uint32_t*>(LIBTEXB_ALLOC(uint8_t,70)); timg->from_texb=texb; texb->ImageList_Id.push_back(timg); texb->ImageList_Names[timg->Name]=i; texb->VertexIndexUVs.push_back(VrtxMem); memcpy(VrtxMem,VertexIndexUVs[i],70); } return texb; } int32_t TextureBank::ReplaceImage(TextureImage* Image) { std::map<std::string,uint32_t>::iterator i=ImageList_Names.find(Image->Name); if(i!=ImageList_Names.end()) return ReplaceImage(Image,i->second); return EINVAL; } int32_t TextureBank::ReplaceImage(TextureImage* Image,uint32_t Index) { if(Index>=ImageList_Id.size()) return ERANGE; TextureImage* target=ImageList_Id[Index]; if(target->Width!=Image->Width || target->Height!=Image->Height || target->Name!=Image->Name) return EINVAL; if(target->from_texb==this) delete target; ImageList_Id[Index]=Image; // Copy raw TIMG image to raw TEXB image uint32_t* Vrtx=VertexIndexUVs[Index]; uint32_t* texbBmp=reinterpret_cast<uint32_t*>(RawImage); uint32_t* rawBmp=reinterpret_cast<uint32_t*>(Image->RawImage); Point v[4]={ {Vrtx[0]/65536,Vrtx[1]/65536}, {Vrtx[4]/65536,Vrtx[5]/65536}, {Vrtx[8]/65536,Vrtx[9]/65536}, {Vrtx[12]/65536,Vrtx[13]/65536} }; UVPoint t[4]={ {Vrtx[2]/65536.0,Vrtx[3]/65536.0}, {Vrtx[6]/65536.0,Vrtx[7]/65536.0}, {Vrtx[10]/65536.0,Vrtx[11]/65536.0}, {Vrtx[14]/65536.0,Vrtx[15]/65536.0} }; for(uint32_t y=0;y<Image->Height;y++) { for(uint32_t x=0;x<Image->Width;x++) { UVPoint uv=xy2uv(x,y,v[0],v[1],v[2],v[3],t[0],t[1],t[2],t[3]); texbBmp[uint32_t(uv.U*Width+0.5)+uint32_t(uv.V*Height+0.5)*Width]=rawBmp[x+y*Image->Width]; } } return 0; } int32_t TextureBank::DefineImage(const Point* Vertexes,const UVPoint* UVs,std::string Name,uint32_t* Index) { if(Index==NULL) return EINVAL; TextureImage* timg=new TextureImage(); timg->Width=Vertexes[2].X; timg->Height=Vertexes[2].Y; timg->from_texb=this; timg->Name=Name; uint32_t* Vertex=reinterpret_cast<uint32_t*>(LIBTEXB_ALLOC(uint8_t,70)); uint8_t* RawMem=LIBTEXB_ALLOC(uint8_t,timg->Width*timg->Height*4); timg->RawImage=RawMem; memcpy(&Vertex[16],"\x00\x01\x03\x03\x01\x02",6); memset(RawMem,0,timg->Width*timg->Height*4); for(uint32_t i=0;i<4;i++) { Vertex[i*4]=Vertexes[i].X*65536; Vertex[i*4+1]=Vertexes[i].Y*65536; Vertex[i*4+2]=uint32_t(UVs[i].U*65536); Vertex[i*4+3]=uint32_t(UVs[i].V*65536); } *Index=ImageList_Id.size(); VertexIndexUVs.push_back(Vertex); ImageList_Id.push_back(timg); ImageList_Names[Name]=*Index; return 0; } int32_t TextureBank::DefineImage(const Point* WhereWidthHeight,std::string Name,uint32_t* Index) { Point v[4]={ {0,0}, {WhereWidthHeight[1].X,0}, {WhereWidthHeight[1].X,WhereWidthHeight[1].Y}, {0,WhereWidthHeight[1].Y} }; // Applied MiraiNoHana TEXBModify.cpp patch. UVPoint t[4]={ {double(WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[0].Y)/double(Height)}, {double(WhereWidthHeight[1].X+WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[0].Y)/double(Height)}, {double(WhereWidthHeight[1].X+WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[1].Y+WhereWidthHeight[0].Y)/double(Height)}, {double(WhereWidthHeight[0].X)/double(Width),double(WhereWidthHeight[1].Y+WhereWidthHeight[0].Y)/double(Height)} }; return DefineImage(v,t,Name,Index); } void TextureBank::ReflectChanges() { for(uint32_t i=0;i<ImageList_Id.size();i++) { TextureImage* timg=ImageList_Id[i]; uint32_t* Vrtx=VertexIndexUVs[i]; uint32_t* texbBmp=reinterpret_cast<uint32_t*>(RawImage); uint32_t* rawBmp=reinterpret_cast<uint32_t*>(timg->RawImage); Point v[4]={ {Vrtx[0]/65536,Vrtx[1]/65536}, {Vrtx[4]/65536,Vrtx[5]/65536}, {Vrtx[8]/65536,Vrtx[9]/65536}, {Vrtx[12]/65536,Vrtx[13]/65536} }; UVPoint t[4]={ {Vrtx[2]/65536.0,Vrtx[3]/65536.0}, {Vrtx[6]/65536.0,Vrtx[7]/65536.0}, {Vrtx[10]/65536.0,Vrtx[11]/65536.0}, {Vrtx[14]/65536.0,Vrtx[15]/65536.0} }; uint32_t min_x = std::min(v[0].X, std::min(v[1].X, std::min(v[2].X, v[3].X))); uint32_t min_y = std::min(v[0].Y, std::min(v[1].Y, std::min(v[2].Y, v[3].Y))); uint32_t max_x = std::max(v[0].X, std::max(v[1].X, std::max(v[2].X, v[3].X))); uint32_t max_y = std::max(v[0].Y, std::max(v[1].Y, std::max(v[2].Y, v[3].Y))); for(uint32_t y = min_y; y < max_y; y++) { for(uint32_t x = min_x; x < max_x; x++) { UVPoint uv=xy2uv(x, y, v[0], v[1], v[2], v[3], t[0], t[1], t[2], t[3]); texbBmp[uint32_t(uv.U * Width + 0.5) + uint32_t(uv.V * Height + 0.5) * Width] = rawBmp[x + y * timg->Width]; } } } }
28.532338
137
0.689799
971cd7c3d55ec832dc00c68b332983eccc0351c9
748
cpp
C++
src/Island.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
null
null
null
src/Island.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
1
2019-08-14T13:36:33.000Z
2019-08-14T13:36:33.000Z
src/Island.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
null
null
null
// Copyright 2018, // Author: Luka Steinbach <luka.steinbach@gmx.de> #include "./Island.h" #include <string> #include <vector> // _____________________________________________________________________________ Island::Island(int x, int y, int count) : Field(x, y) { _islandCount = count; _correctBridgeCount = 0; _symbol = std::to_string(_islandCount); } // _____________________________________________________________________________ Island::~Island() {} // _____________________________________________________________________________ int Island::getCount() const { return _islandCount; } // _____________________________________________________________________________ std::string Island::getType() const { return "type_island"; }
27.703704
80
0.798128
971d0e7be632f513340bede6a7f76ecd77082369
77,961
cpp
C++
simulation-code/Network.cpp
jlubo/memory-consolidation-stc
f9934760e12de324360297d7fc7902623169cb4d
[ "Apache-2.0" ]
2
2021-03-02T21:46:56.000Z
2021-06-30T03:12:07.000Z
simulation-code/Network.cpp
jlubo/memory-consolidation-stc
f9934760e12de324360297d7fc7902623169cb4d
[ "Apache-2.0" ]
null
null
null
simulation-code/Network.cpp
jlubo/memory-consolidation-stc
f9934760e12de324360297d7fc7902623169cb4d
[ "Apache-2.0" ]
3
2021-03-22T12:56:52.000Z
2021-09-13T07:42:36.000Z
/************************************************************************************************** *** Model of a network of neurons with long-term plasticity between excitatory neurons *** **************************************************************************************************/ /*** Copyright 2017-2021 Jannik Luboeinski *** *** licensed under Apache-2.0 (http://www.apache.org/licenses/LICENSE-2.0) ***/ #include <random> #include <sstream> using namespace std; #include "Neuron.cpp" struct synapse // structure for synapse definition { int presyn_neuron; // the number of the presynaptic neuron int postsyn_neuron; // the number of the postsynaptic neuron synapse(int _presyn_neuron, int _postsyn_neuron) // constructor { presyn_neuron = _presyn_neuron; postsyn_neuron = _postsyn_neuron; } }; /*** Network class *** * Represents a network of neurons */ class Network { #if (PROTEIN_POOLS != POOLS_C && PROTEIN_POOLS != POOLS_PD && PROTEIN_POOLS != POOLS_PCD) #error "Unsupported option for PROTEIN_POOLS." #endif friend class boost::serialization::access; private: /*** Computational parameters ***/ double dt; // s, one timestep for numerical simulation int N; // total number of excitatory plus inhibitory neurons int t_syn_delay_steps; // constant t_syn_delay converted to timesteps int t_Ca_delay_steps; // constant t_Ca_delay converted to timesteps /*** State variables ***/ vector<Neuron> neurons; // vector of all N neuron instances (first excitatory, then inhibitory) bool** conn; // the binary connectivity matrix, the main diagonal is zero (because there is no self-coupling) double** Ca; // the matrix of postsynaptic calcium concentrations double** h; // the matrix of early-phase coupling strengths double** z; // the matrix of late-phase coupling strengths int* last_Ca_spike_index; // contains the indices of the last spikes that were important for calcium dynamics minstd_rand0 rg; // default uniform generator for random numbers to establish connections (seed is chosen in constructor) uniform_real_distribution<double> u_dist; // uniform distribution, constructed in Network class constructor normal_distribution<double> norm_dist; // normal distribution to obtain Gaussian white noise, constructed in Network class constructor int stimulation_end; // timestep by which all stimuli have ended double* sum_h_diff; // sum of all early-phase changes for each postsynaptic neuron double* sum_h_diff_p; // sum of E-LTP changes for each postsynaptic neuron double* sum_h_diff_d; // sum of E-LTD changes for each postsynaptic neuron protected: /*** Physical parameters ***/ int Nl_exc; // number of neurons in one line (row or column) of the exc. population (better choose an odd number, for there exists a "central" neuron) int Nl_inh; // number of neurons in one line (row or column) of the inh. population (better choose an odd number, for there exists a "central" neuron) double tau_syn; // s, the synaptic time constant double t_syn_delay; // s, the synaptic transmission delay for PSPs - has to be at least one timestep! double p_c; // connection probability (prob. that a directed connection exists) double w_ee; // nC, magnitude of excitatory PSP effecting an excitatory postsynaptic neuron double w_ei; // nC, magnitude of excitatory PSP effecting an inhibitory postsynaptic neuron double w_ie; // nC, magnitude of inhibitory PSP effecting an excitatory postsynaptic neuron double w_ii; // nC, magnitude of inhibitory PSP effecting an inhibitory postsynaptic neuron /*** Plasticity parameters ***/ double t_Ca_delay; // s, delay for spikes to affect calcium dynamics - has to be at least one timestep! double Ca_pre; // s^-1, increase in calcium current evoked by presynaptic spike double Ca_post; // s^-1, increase in calcium current evoked by postsynaptic spike double tau_Ca; // s, time constant for calcium dynamics double tau_Ca_steps; // time constant for calcium dynamics in timesteps double tau_h; // s, time constant for early-phase plasticity double tau_pp; // h, time constant of LTP-related protein synthesis double tau_pc; // h, time constant of common protein synthesis double tau_pd; // h, time constant of LTD-related protein synthesis double tau_z; // min, time constant of consolidation double gamma_p; // constant for potentiation process double gamma_d; // constant for depression process double theta_p; // threshold for calcium concentration to induce potentiation double theta_d; // threshold for calcium concentration to induce depotentiation double sigma_plasticity; // nA s, standard deviation of plasticity noise double alpha_p; // LTP-related protein synthesis rate double alpha_c; // common protein synthesis rate double alpha_d; // LTD-related protein synthesis rate double h_0; // nA, initial value for early-phase plasticity double theta_pro_p; // nA s, threshold for LTP-related protein synthesis double theta_pro_c; // nA s, threshold for common protein synthesis double theta_pro_d; // nA s, threshold for LTD-related protein synthesis double theta_tag_p; // nA s, threshold for LTP-related tag double theta_tag_d; // nA s, threshold for LTD-related tag double z_max; // upper z bound public: #ifdef TWO_NEURONS_ONE_SYNAPSE bool tag_glob; // specifies if a synapse was tagged ever bool ps_glob; // specifies if protein synthesis ever occurred in any neuron #endif double max_dev; // maximum deviation from h_0 (deviation of the synapse with the largest change) int tb_max_dev; // time bin at which max_dev was encountered #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD double max_sum_diff; // maximum sum of early-phase changes (sum of the neuron with the most changes) int tb_max_sum_diff; // time bin at which max_sum_diff was encountered #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD double max_sum_diff_p; // maximum sum of LTP early-phase changes (sum of the neuron with the most changes) int tb_max_sum_diff_p; // time bin at which max_sum_diff_p was encountered double max_sum_diff_d; // maximum sum of LTD early-phase changes (sum of the neuron with the most changes) int tb_max_sum_diff_d; // time bin at which max_sum_diff_d was encountered #endif /*** rowG (macro) *** * Returns the row number for element n (in consecutive numbering), be * * aware that it starts with one, unlike the consecutive number (general case for a row/column size of d) * * - int n: the consecutive element number * * - int d: the row/column size */ #define rowG(n, d) ((((n) - ((n) % d)) / d) + 1) /*** colG (macro) *** * Returns the column number for element n (in consecutive numbering), be * * aware that it starts with one, unlike the consecutive number (general case for a row/column size of d) * * - int n: the consecutive element number * * - int d: the row/column size */ #define colG(n, d) (((n) % d) + 1) /*** cNN (macro) *** * Returns a consecutive number for excitatory neuron (i|j) rather than a pair of numbers like (i|j), be * * aware that it starts with zero, unlike i and j * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located */ #define cNN(i, j) (((i)-1)*Nl_exc + ((j)-1)) /*** row (macro) *** * Returns the row number for excitatory neuron n, be * * aware that it starts with one, unlike the consecutive number * * - int n: the consecutive neuron number */ #define row(n) (rowG(n, Nl_exc)) /*** col (macro) *** * Returns the column number for excitatory neuron n, be * * aware that it starts with one, unlike the consecutive number * * - int n: the consecutive neuron number */ #define col(n) (colG(n, Nl_exc)) /*** symm (macro) *** * Returns the number of the symmetric element for an element given * * by its consecutive number * * - int n: the consecutive element number */ #define symm(n) (cNN(col(n),row(n))) /*** shallBeConnected *** * Draws a uniformly distributed random number from the interval 0.0 to 1.0 and returns, * * depending on the connection probability, whether or not a connection shall be established * * - int m: consecutive number of presynaptic neuron * * - int n: consecutive number of postsynaptic neuron * * - return: true if connection shall be established, false if not */ bool shallBeConnected(int m, int n) { #ifdef TWO_NEURONS_ONE_SYNAPSE // in this paradigm, there is only one synapse from neuron 1 to neuron 0 if (m == 1 && n == 0) { neurons[m].addOutgoingConnection(n, TYPE_EXC); return true; } #else // exc.->exc. synapse if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_EXC); neurons[m].addOutgoingConnection(n, TYPE_EXC); return true; } } // exc.->inh. synapse else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_EXC); neurons[m].addOutgoingConnection(n, TYPE_INH); return true; } } // inh.->exc. synapse else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_INH); neurons[m].addOutgoingConnection(n, TYPE_EXC); return true; } } // inh.->inh. synapse else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) { if (u_dist(rg) <= p_c) // draw random number { neurons[n].incNumberIncoming(TYPE_INH); neurons[m].addOutgoingConnection(n, TYPE_INH); return true; } } #endif return false; } /*** areConnected *** * Returns whether or not there is a synapse from neuron m to neuron n * * - int m: the number of the first neuron in consecutive order * * - int n: the number of the second neuron in consecutive order * * - return: true if connection from m to n exists, false if not */ bool areConnected(int m, int n) const { if (conn[m][n]) return true; else return false; } /*** saveNetworkParams *** * Saves all the network parameters (including the neuron and channel parameters) to a given file */ void saveNetworkParams(ofstream *f) const { *f << endl; *f << "Network parameters:" << endl; *f << "N_exc = " << pow2(Nl_exc) << " (" << Nl_exc << " x " << Nl_exc << ")" << endl; *f << "N_inh = " << pow2(Nl_inh) << " (" << Nl_inh << " x " << Nl_inh << ")" << endl; *f << "tau_syn = " #if SYNAPSE_MODEL == DELTA << 0 #elif SYNAPSE_MODEL == MONOEXP << tau_syn #endif << " s" << endl; *f << "t_syn_delay = " << t_syn_delay << " s" << endl; *f << "h_0 = " << h_0 << " nA s" << endl; *f << "w_ee = " << dtos(w_ee/h_0,1) << " h_0" << endl; *f << "w_ei = " << dtos(w_ei/h_0,1) << " h_0" << endl; *f << "w_ie = " << dtos(w_ie/h_0,1) << " h_0" << endl; *f << "w_ii = " << dtos(w_ii/h_0,1) << " h_0" << endl; *f << "p_c = " << p_c << endl; *f << endl; *f << "Plasticity parameters" #if PLASTICITY == OFF << " <switched off>" #endif << ": " << endl; *f << "t_Ca_delay = " << t_Ca_delay << " s" << endl; *f << "Ca_pre = " << Ca_pre << endl; *f << "Ca_post = " << Ca_post << endl; *f << "tau_Ca = " << tau_Ca << " s" << endl; *f << "tau_h = " << tau_h << " s" << endl; *f << "tau_pp = " << tau_pp << " h" << endl; *f << "tau_pc = " << tau_pc << " h" << endl; *f << "tau_pd = " << tau_pd << " h" << endl; *f << "tau_z = " << tau_z << " min" << endl; *f << "z_max = " << z_max << endl; *f << "gamma_p = " << gamma_p << endl; *f << "gamma_d = " << gamma_d << endl; *f << "theta_p = " << theta_p << endl; *f << "theta_d = " << theta_d << endl; *f << "sigma_plasticity = " << dtos(sigma_plasticity/h_0,2) << " h_0" << endl; *f << "alpha_p = " << alpha_p << endl; *f << "alpha_c = " << alpha_c << endl; *f << "alpha_d = " << alpha_d << endl; double nm = 1. / (theta_pro_c/h_0) - 0.001; // compute neuromodulator concentration from threshold theta_pro_c *f << "theta_pro_p = " << dtos(theta_pro_p/h_0,2) << " h_0" << endl; *f << "theta_pro_c = " << dtos(theta_pro_c/h_0,2) << " h_0 (nm = " << dtos(nm,2) << ")" << endl; *f << "theta_pro_d = " << dtos(theta_pro_d/h_0,2) << " h_0" << endl; *f << "theta_tag_p = " << dtos(theta_tag_p/h_0,2) << " h_0" << endl; *f << "theta_tag_d = " << dtos(theta_tag_d/h_0,2) << " h_0" << endl; neurons[0].saveNeuronParams(f); // all neurons have the same parameters, take the first one } /*** saveNetworkState *** * Saves the current state of the whole network to a given file using boost function serialize(...) * * - file: the file to read the data from * * - tb: current timestep */ void saveNetworkState(string file, int tb) { ofstream savefile(file); if (!savefile.is_open()) throw runtime_error(string("Network state could not be saved.")); boost::archive::text_oarchive oa(savefile); oa << tb; // write the current time (in steps) to archive oa oa << *this; // write this instance to archive oa savefile.close(); } /*** loadNetworkState *** * Load the state of the whole network from a given file using boost function serialize(...); * * connectivity matrix 'conn' of the old and the new simulation has to be the same! * * - file: the file to read the data from * * - return: the simulation time at which the network state was saved (or -1 if nothing was loaded) */ int loadNetworkState(string file) { ifstream loadfile(file); int tb; if (!loadfile.is_open()) return -1; boost::archive::text_iarchive ia(loadfile); ia >> tb; // read the current time (in steps) from archive ia ia >> *this; // read this instance from archive ia loadfile.close(); cout << "Network state successfully loaded." << endl; return tb; } /*** serialize *** * Saves all state variables to a file using serialization from boost * * - ar: the archive stream * * - version: the archive version */ template<class Archive> void serialize(Archive &ar, const unsigned int version) { for (int m=0; m<N; m++) { ar & neurons[m]; // read/write Neuron instances for (int n=0; n<N; n++) { ar & Ca[m][n]; // read/write matrix of postsynaptic Calcium concentrations ar & h[m][n]; // read/write early-phase weight matrix ar & z[m][n]; // read/write late-phase weight matrix } ar & last_Ca_spike_index[m]; // read/write array of the indices of the last spikes that were important for calcium dynamics ar & sum_h_diff[m]; // read/write sum of all early-phase changes for each postsynaptic neuron ar & sum_h_diff_p[m]; // read/write sum of E-LTP changes for each postsynaptic neuron ar & sum_h_diff_d[m]; // read/write sum of E-LTD changes for each postsynaptic neuron } } /*** processTimeStep *** * Processes one timestep (of duration dt) for the network [rich mode / compmode == 1] * * - int tb: current timestep (for evaluating stimulus and for computing spike contributions) * * - ofstream* txt_spike_raster [optional]: file containing spike times for spike raster plot * * - return: number of spikes that occurred within the considered timestep in the whole network */ int processTimeStep(int tb, ofstream* txt_spike_raster = NULL) { int spike_count = 0; // number of neurons that have spiked in this timestep int st_PSP = tb - t_syn_delay_steps; // presynaptic spike time for evoking PSP in this timestep tb int st_CA = tb - t_Ca_delay_steps; // presynaptic spike time for evoking calcium contribution in this timestep tb bool STC = false; // specifies if at least one synapse is tagged and receives proteins bool ps_neuron = false; // specifies if at least one neuron is exhibiting protein synthesis /*******************************************************/ // compute neuronal dynamics for (int m=0; m<N; m++) // loop over neurons (in consecutive order) { neurons[m].processTimeStep(tb, -1); // computation of individual neuron dynamics // add spikes to raster plot and count spikes in this timestep if (neurons[m].getActivity()) { #if SPIKE_PLOTTING == RASTER || SPIKE_PLOTTING == NUMBER_AND_RASTER *txt_spike_raster << tb*dt << "\t\t" << m << endl; // add this spike to the raster plot #endif spike_count += 1; } #if COND_BASED_SYN == OFF #if SYNAPSE_MODEL == DELTA neurons[m].setSynapticCurrent(0.); // reset synaptic current contributions #elif SYNAPSE_MODEL == MONOEXP neurons[m].setSynapticCurrent(neurons[m].getSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions #endif #else #if SYNAPSE_MODEL == DELTA neurons[m].setExcSynapticCurrent(0.); // reset synaptic current contributions neurons[m].setInhSynapticCurrent(0.); // reset synaptic current contributions #elif SYNAPSE_MODEL == MONOEXP neurons[m].setExcSynapticCurrent(neurons[m].getExcSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions neurons[m].setInhSynapticCurrent(neurons[m].getInhSynapticCurrent() * exp(-dt/tau_syn)); // exponential decay of previous synaptic current contributions //[simple Euler: neurons[m].setExcSynapticCurrent(neurons[m].getExcSynapticCurrent() * (1.-dt/tau_syn)); ] //[simple Euler: neurons[m].setInhSynapticCurrent(neurons[m].getInhSynapticCurrent() * (1.-dt/tau_syn)); ] #endif #endif // COND_BASED_SYN == ON // Protein dynamics (for neuron m) #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC #ifdef TWO_NEURONS_ONE_SYNAPSE ps_glob = ps_glob || (sum_h_diff[m] >= theta_pro_c); #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD double pa_p = neurons[m].getPProteinAmount(); double pa_d = neurons[m].getDProteinAmount(); if (sum_h_diff_p[m] > max_sum_diff_p) { max_sum_diff_p = sum_h_diff_p[m]; tb_max_sum_diff_p = tb; } if (sum_h_diff_d[m] > max_sum_diff_d) { max_sum_diff_d = sum_h_diff_d[m]; tb_max_sum_diff_d = tb; } ps_neuron = ps_neuron || (sum_h_diff_p[m] >= theta_pro_p) || (sum_h_diff_d[m] >= theta_pro_d); pa_p = pa_p * exp(-dt/(tau_pp * 3600.)) + alpha_p * step(sum_h_diff_p[m] - theta_pro_p) * (1. - exp(-dt/(tau_pp * 3600.))); pa_d = pa_d * exp(-dt/(tau_pd * 3600.)) + alpha_d * step(sum_h_diff_d[m] - theta_pro_d) * (1. - exp(-dt/(tau_pd * 3600.))); // [simple Euler: pa += (- pa + alpha * step(sum_h_diff - theta_pro)) * (dt / (tau_p * 3600.));] sum_h_diff_p[m] = 0.; sum_h_diff_d[m] = 0.; #else double pa_p = 0.; double pa_d = 0.; #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD double pa_c = neurons[m].getCProteinAmount(); if (sum_h_diff[m] > max_sum_diff) { max_sum_diff = sum_h_diff[m]; tb_max_sum_diff = tb; } ps_neuron = ps_neuron || (sum_h_diff[m] >= theta_pro_c); pa_c = pa_c * exp(-dt/(tau_pc * 3600.)) + alpha_c * step(sum_h_diff[m] - theta_pro_c) * (1. - exp(-dt/(tau_pc * 3600.))); // === ESSENTIAL === sum_h_diff[m] = 0.; #else double pa_c = 0.; #endif neurons[m].setProteinAmounts(pa_p, pa_c, pa_d); #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC } /*******************************************************/ // compute synaptic dynamics for (int m=0; m<N; m++) // loop over presynaptic neurons (in consecutive order) { bool delayed_PSP; // specifies if a presynaptic spike occurred t_syn_delay ago // go through presynaptic spikes for PSPs; start from most recent one delayed_PSP = neurons[m].spikeAt(st_PSP); //delayed_PSP = neurons[m].getActivity(); // in case no synaptic delay is used #if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC bool delayed_Ca = false; // specifies if a presynaptic spike occurred t_Ca_delay ago if (m < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections { // go through presynaptic spikes for calcium contribution; start from last one that was used plus one for (int k=last_Ca_spike_index[m]; k<=neurons[m].getSpikeHistorySize(); k++) { int st = neurons[m].getSpikeTime(k); if (st >= st_CA) { if (st == st_CA) // if presynaptic spike occurred t_Ca_delay ago { delayed_Ca = true; // presynaptic neuron fired t_Ca_delay ago last_Ca_spike_index[m] = k + 1; // next time, start with the next possible spike } break; } } } #endif /*******************************************************/ for (int in=0; in<neurons[m].getNumberOutgoing(); in++) // loop over postsynaptic neurons { int n = neurons[m].getOutgoingConnection(in); // get index (in consecutive order) of postsynaptic neuron double h_dev; // the deviation of the early-phase weight from its resting state // Synaptic current if (delayed_PSP) // if presynaptic spike occurred t_syn_delay ago { if (neurons[m].getType() == TYPE_EXC) { double psc; // the postsynaptic current if (neurons[n].getType() == TYPE_EXC) // E -> E { psc = h[m][n] + h_0 * z[m][n]; neurons[n].increaseExcSynapticCurrent(psc); } else // E -> I { psc = w_ei; neurons[n].increaseExcSynapticCurrent(psc); } #if DENDR_SPIKES == ON neurons[n].updateDendriteInput(psc); // contribution to dendritic spikes #endif } else { if (neurons[n].getType() == TYPE_EXC) // I -> E { neurons[n].increaseInhSynapticCurrent(w_ie); } else // I -> I { neurons[n].increaseInhSynapticCurrent(w_ii); } } } // Long-term plasticity if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections { #if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC // Calcium dynamics Ca[m][n] *= exp(-dt/tau_Ca); // === ESSENTIAL === if (delayed_Ca) // if presynaptic spike occurred t_Ca_delay ago Ca[m][n] += Ca_pre; if (neurons[n].getActivity()) // if postsynaptic spike occurred in previous timestep Ca[m][n] += Ca_post; // E-LTP/-LTD if ((Ca[m][n] >= theta_p) // if there is E-LTP and "STDP-like" condition is fulfilled #if LTP_FR_THRESHOLD > 0 && (neurons[m].spikesInInterval(tb-2500,tb+1) > LTP_FR_THRESHOLD/2 && neurons[n].spikesInInterval(tb-2500,tb+1) > LTP_FR_THRESHOLD/2) #endif ) { double noise = sigma_plasticity * sqrt(tau_h) * sqrt(2) * norm_dist(rg) / sqrt(dt); // division by sqrt(dt) was not in Li et al., 2016 double C = 0.1 + gamma_p + gamma_d; double hexp = exp(-dt*C/tau_h); h[m][n] = h[m][n] * hexp + (0.1*h_0 + gamma_p + noise) / C * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]) + gamma_p * (1-h[m][n]) - gamma_d * h[m][n] + noise)*(dt/tau_h));] if (abs(h[m][n] - h_0) > abs(max_dev)) { max_dev = h[m][n] - h_0; tb_max_dev = tb; } } else if ((Ca[m][n] >= theta_d) // if there is E-LTD #if LTD_FR_THRESHOLD > 0 && (neurons[m].spikesInInterval(tb-2500,tb+1) > LTD_FR_THRESHOLD/2 && neurons[n].spikesInInterval(tb-2500,tb+1) > LTD_FR_THRESHOLD/2) #endif ) { double noise = sigma_plasticity * sqrt(tau_h) * norm_dist(rg) / sqrt(dt); // division by sqrt(dt) was not in Li et al., 2016 double C = 0.1 + gamma_d; double hexp = exp(-dt*C/tau_h); h[m][n] = h[m][n] * hexp + (0.1*h_0 + noise) / C * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]) + gamma_d * h[m][n] + noise)*(dt/tau_h));] if (abs(h[m][n] - h_0) > abs(max_dev)) { max_dev = h[m][n] - h_0; tb_max_dev = tb; } } else // if early-phase weight just decays { double hexp = exp(-dt*0.1/tau_h); h[m][n] = h[m][n] * hexp + h_0 * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]))*(dt/tau_h));] } h_dev = h[m][n] - h_0; #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD if (h_dev > 0.) sum_h_diff_p[n] += h_dev; // sum of early-phases changes (for LTP-related protein synthesis) else if (h_dev < 0.) sum_h_diff_d[n] -= h_dev; // sum of early-phases changes (for LTD-related protein synthesis) #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD sum_h_diff[n] += abs(h_dev); // sum of early-phases changes (for protein synthesis) #endif #endif // PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC // L-LTP/-LTD if (h_dev >= theta_tag_p) // LTP { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getPProteinAmount()*neurons[n].getCProteinAmount(); // LTP protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getPProteinAmount(); // LTP protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-dt / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-dt / (tau_z * 60. * z_max) * pa); z[m][n] = z[m][n] * zexp + z_max * (1. - zexp); STC = true; } } else if (-h_dev >= theta_tag_d) // LTD { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getDProteinAmount()*neurons[n].getCProteinAmount(); // LTD protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getDProteinAmount(); // LTD protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-dt / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-dt / (tau_z * 60.) * pa); z[m][n] = z[m][n] * zexp - 0.5 * (1. - zexp); STC = true; } } // [simple Euler: z[m][n] += (pa * ((1 - z[m][n]) * step1 - (0.5 + z[m][n]) * step2) * (dt / (tau_z * 6.0 * 10)));] #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC #if PLASTICITY == STDP double Ap = 1.2, Am = -1.0; double tau_syn_stdp = 3e-3; double tau_p_stdp = 1e-3; double tau_m_stdp = 20e-3; double tau_pt_stdp = tau_syn_stdp * tau_p_stdp / (tau_syn_stdp + tau_p_stdp); double tau_mt_stdp = tau_syn_stdp * tau_m_stdp / (tau_syn_stdp + tau_m_stdp); double eta = 12e-2; // if presynaptic neuron m spiked in previous timestep if (delayed_PSP) { int last_post_spike = neurons[n].getSpikeHistorySize(); if (last_post_spike > 0) { int tb_post = neurons[n].getSpikeTime(last_post_spike); double stdp_delta_t = (tb + 1 - tb_post) * dt; h[m][n] += eta * exp(-abs(stdp_delta_t) / tau_syn_stdp) * (Ap * (1. + abs(stdp_delta_t)/tau_pt_stdp) + Am * (1. + abs(stdp_delta_t)/tau_mt_stdp)); if (h[m][n] < 0.) h[m][n] = 0.1;//h_0 / 100.; // set to a very small value } } // if postsynaptic neuron n spiked in previous timestep bool delayed_PSP2 = false; for (int k=neurons[n].getSpikeHistorySize(); k>0; k--) { int st = neurons[n].getSpikeTime(k); if (st <= st_PSP) // spikes that have already arrived { if (st == st_PSP) // if presynaptic spike occurred t_syn_delay ago { delayed_PSP2 = true; // presynaptic neuron fired t_syn_delay ago } break; } } if (delayed_PSP2) { int last_pre_spike = neurons[m].getSpikeHistorySize(); if (last_pre_spike > 0) { int tb_pre = neurons[n].getSpikeTime(last_pre_spike); double stdp_delta_t = (tb_pre - tb - 1) * dt; h[m][n] += eta * (Ap * exp(-abs(stdp_delta_t) / tau_p_stdp) + Am * exp(-abs(stdp_delta_t) / tau_m_stdp)); if (h[m][n] < 0.) h[m][n] = 0.1;//h_0 / 100.; // set to a very small value } } #endif // PLASTICITY == STDP } // plasticity within excitatory population #if SYN_SCALING == ON h[m][n] += ( eta_ss * pow2(h[m][n] / g_star) * (- r[n]) ) * dt; #endif } // loop over postsynaptic neurons } // loop over presynaptic neurons return spike_count; } /*** processTimeStep_FF *** * Processes one timestep for the network only computing late-phase observables [fast-forward mode / compmode == 2] * * - int tb: current timestep (for printing purposes only) * * - double delta_t: duration of the fast-forward timestep * * - ofstream* logf: pointer to log file handle (for printing interesting information) * * - return: true if late-phase dynamics are persisting, false if not */ int processTimeStep_FF(int tb, double delta_t, ofstream* logf) { bool STC = false; // specifies if at least one synapse is tagged and receives proteins bool ps_neuron = false; // specifies if at least one neuron is exhibiting protein synthesis /*******************************************************/ // compute neuronal dynamics for (int m=0; m<N; m++) // loop over neurons (in consecutive order) { // Protein dynamics (for neuron m) - computation from analytic functions #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC #ifdef TWO_NEURONS_ONE_SYNAPSE ps_glob = ps_glob || (sum_h_diff[m] >= theta_pro_c); #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD double pa_p = neurons[m].getPProteinAmount(); double pa_d = neurons[m].getDProteinAmount(); double p_synth_end_p = 0.; double p_synth_end_d = 0.; // Potentiation pool if (sum_h_diff_p[m] > theta_pro_p) // still rising { ps_neuron = ps_neuron || true; p_synth_end_p = tau_h / 0.1 * log(sum_h_diff_p[m] / theta_pro_p); if (delta_t < p_synth_end_p) // rising phase only { pa_p = pa_p * exp(-delta_t/(tau_pp * 3600.)) + alpha_p * (1. - exp(-delta_t/(tau_pp * 3600.))); } else // rising phase transitioning to declining phase { pa_p = pa_p * exp(-p_synth_end_p/(tau_pp * 3600.)) + alpha_p * (1. - exp(-p_synth_end_p/(tau_pp * 3600.))); pa_p = pa_p * exp(-(delta_t-p_synth_end_p)/(tau_pp * 3600.)); *logf << "Protein synthesis (P) ending in neuron " << m << " (t = " << p_synth_end_p + tb*dt << " s)" << endl; } } else // declining phase only { pa_p = pa_p * exp(-delta_t/(tau_pp * 3600.)); } // Depression pool if (sum_h_diff_d[m] > theta_pro_d) // still rising { ps_neuron = ps_neuron || true; p_synth_end_d = tau_h / 0.1 * log(sum_h_diff_d[m] / theta_pro_d); if (delta_t < p_synth_end_d) // rising phase only { pa_d = pa_d * exp(-delta_t/(tau_pd * 3600.)) + alpha_d * (1. - exp(-delta_t/(tau_pd * 3600.))); } else // rising phase transitioning to declining phase { pa_d = pa_d * exp(-p_synth_end_d/(tau_pd * 3600.)) + alpha_d * (1. - exp(-p_synth_end_d/(tau_pd * 3600.))); pa_d = pa_d * exp(-(delta_t-p_synth_end_d)/(tau_pd * 3600.)); *logf << "Protein synthesis (D) ending in neuron " << m << " (t = " << p_synth_end_d + tb*dt << " s)" << endl; } } else // declining phase only { pa_d = pa_d * exp(-delta_t/(tau_pd * 3600.)); } sum_h_diff_p[m] = 0.; sum_h_diff_d[m] = 0.; #else double pa_p = 0.; double pa_d = 0.; #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD double pa_c = neurons[m].getCProteinAmount(); double p_synth_end_c = 0.; // Common pool if (sum_h_diff[m] > theta_pro_c) // still rising { ps_neuron = ps_neuron || true; p_synth_end_c = tau_h / 0.1 * log(sum_h_diff[m] / theta_pro_c); if (delta_t < p_synth_end_c) // rising phase only { pa_c = pa_c * exp(-delta_t/(tau_pc * 3600.)) + alpha_c * (1. - exp(-delta_t/(tau_pc * 3600.))); } else // rising phase transitioning to declining phase { pa_c = pa_c * exp(-p_synth_end_c/(tau_pc * 3600.)) + alpha_c * (1. - exp(-p_synth_end_c/(tau_pc * 3600.))); pa_c = pa_c * exp(-(delta_t-p_synth_end_c)/(tau_pc * 3600.)); *logf << "Protein synthesis (C) ending in neuron " << m << " (t = " << p_synth_end_c + tb*dt << " s)" << endl; } } else // declining phase only { pa_c = pa_c * exp(-delta_t/(tau_pc * 3600.)); } sum_h_diff[m] = 0.; #else double pa_c = 0.; #endif neurons[m].setProteinAmounts(pa_p, pa_c, pa_d); #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC } /*******************************************************/ // compute synaptic dynamics for (int m=0; m<N; m++) // loop over presynaptic neurons (in consecutive order) { for (int in=0; in<neurons[m].getNumberOutgoing(); in++) // loop over postsynaptic neurons { int n = neurons[m].getOutgoingConnection(in); // get index (in consecutive order) of postsynaptic neuron double h_dev; // the deviation of the early-phase weight from its resting state // Long-term plasticity if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // plasticity only for exc. -> exc. connections { #if PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC // early-phase weight just decays double hexp = exp(-delta_t*0.1/tau_h); h[m][n] = h[m][n] * hexp + h_0 * (1.- hexp); // [simple Euler: h[m][n] += ((0.1 * (h_0 - h[m][n]))*(delta_t/tau_h));] h_dev = h[m][n] - h_0; #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD if (h_dev > 0.) sum_h_diff_p[n] += h_dev; // sum of early-phases changes (for LTP-related protein synthesis) else if (h_dev < 0.) sum_h_diff_d[n] -= h_dev; // sum of early-phases changes (for LTD-related protein synthesis) #endif #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD sum_h_diff[n] += abs(h_dev); // sum of early-phases changes (for protein synthesis) #endif #endif // PLASTICITY == CALCIUM || PLASTICITY == CALCIUM_AND_STC #if PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC // L-LTP/-LTD if (h_dev >= theta_tag_p) // LTP { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getPProteinAmount()*neurons[n].getCProteinAmount(); // LTP protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getPProteinAmount(); // LTP protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-delta_t / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-delta_t / (tau_z * 60. * z_max) * pa); z[m][n] = z[m][n] * zexp + z_max * (1. - zexp); STC = true; } } else if (-h_dev >= theta_tag_d) // LTD { #if PROTEIN_POOLS == POOLS_PCD double pa = neurons[n].getDProteinAmount()*neurons[n].getCProteinAmount(); // LTD protein amount times common protein amount from previous timestep #elif PROTEIN_POOLS == POOLS_PD double pa = neurons[n].getDProteinAmount(); // LTD protein amountfrom previous timestep #elif PROTEIN_POOLS == POOLS_C double pa = neurons[n].getCProteinAmount(); // common protein amount from previous timestep #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = true; #endif if (pa > EPSILON) { //double zexp = exp(-delta_t / (tau_z * 60.) * pa*(step1 + step2)); double zexp = exp(-delta_t / (tau_z * 60.) * pa); z[m][n] = z[m][n] * zexp - 0.5 * (1. - zexp); STC = true; } } // [simple Euler: z[m][n] += (pa * ((1 - z[m][n]) * step1 - (0.5 + z[m][n]) * step2) * (delta_t / (tau_z * 6.0 * 10)));] #endif // PLASTICITY == CALCIUM_AND_STC || PLASTICITY == STDP_AND_STC } // plasticity within excitatory population } // loop over postsynaptic neurons } // loop over presynaptic neurons if (!STC) // no late-phase dynamics can take place anymore { return false; } return true; } /*** getSumDiff *** * Returns the sum of absolute values of weight differences to the initial value for a specific neuron * * - n: number of the neuron to be considered * * - return: sum_h_diff for a specific neuron */ double getSumDiff(int n) { return sum_h_diff[n]; } #ifdef TWO_NEURONS_ONE_SYNAPSE /*** getPlasticityType *** * Returns the kind of plasticity evoked by the stimulus * * - return: 0 for ELTP, 1 for ELTP with tag, 2 for LLTP, 3 for ELTD, 4 for ELTD with tag, 5 for LLTD, -1 else */ int getPlasticityType() { if (max_dev > EPSILON) // LTP { if (!tag_glob) return 0; else { if (!ps_glob) return 1; else return 2; } } else if (max_dev < -EPSILON) // LTD { if (!tag_glob) return 3; else { if (!ps_glob) return 4; else return 5; } } return -1; } /*** getMaxDev *** * Returns the maximum deviation from h_0 * * - return: max_dev*/ double getMaxDev() { return max_dev; } #endif /*** getTagVanishTime *** * Returns the time by which all tags will have vanished, based on * * the largest early-phase deviation from the mean h_0 (max_dev) * * - return: the time difference */ double getTagVanishTime() { double tag_vanish = tau_h / 0.1 * log(abs(max_dev) / min(theta_tag_p, theta_tag_d)); if (abs(max_dev) > EPSILON && tag_vanish > EPSILON) return tag_vanish + tb_max_dev*dt; else return 0.; } /*** getProteinSynthesisEnd *** * Returns the time (for every pool) by which all protein synthesis will halt, based on the * * largest sum of early-phase deviations from the mean h_0 (max_sum_diff*) * * - return: the times for the different pools (P,C,D) in a vector */ vector<double> getProteinSynthesisEnd() { vector<double> ret(3,0.); #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD if (max_sum_diff > theta_pro_c) ret[1] = tau_h / 0.1 * log(max_sum_diff / theta_pro_c) + tb_max_sum_diff*dt; #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD if (max_sum_diff_p > theta_pro_p) ret[0] = tau_h / 0.1 * log(max_sum_diff_p / theta_pro_p) + tb_max_sum_diff_p*dt; if (max_sum_diff_d > theta_pro_d) ret[2] = tau_h / 0.1 * log(max_sum_diff_d / theta_pro_d) + tb_max_sum_diff_d*dt; #endif return ret; } /*** getThreshold *** * Returns a specified threshold value (for tag or protein synthesis) * * - plast: the type of plasticity (1: LTP, 2: LTD) * - which: the type of threshold (1: early-phase calcium treshold, 2: tagging threshold, 3: protein synthesis threshold) * - return: the threshold value */ double getThreshold(int plast, int which) { if (plast == 1) // LTP { if (which == 1) // early-phase calcium treshold return theta_p; else if (which == 2) // tagging threshold return theta_tag_p; else // protein synthesis threshold return theta_pro_p; } else // LTD { if (which == 1) // early-phase calcium treshold return theta_d; else if (which == 2) // tagging threshold return theta_tag_d; else // protein synthesis threshold return theta_pro_d; } } /*** setRhombStimulus *** * Sets a spatially rhomb-shaped firing rate stimulus in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons, radius 4 to 41, radius 5 to 61, radius 9 to 181) */ void setRhombStimulus(Stimulus& _st, int center, int radius) { for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { neurons[center+i*Nl_exc+j].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron } } setStimulationEnd(_st.getStimulationEnd()); } /*** setRhombPartialRandomStimulus *** * Sets stimulation for randomly drawn neurons out of a rhomb shape in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons) * * - double fraction: the fraction of neurons in the rhomb that shall be stimulated */ void setRhombPartialRandomStimulus(Stimulus& _st, int center, int radius, double fraction) { int total_assembly_size = 2*pow2(radius) + 2*radius + 1; // total number of neurons within the rhomb int ind = 0, count = 0; uniform_int_distribution<int> rhomb_dist(1, total_assembly_size); int* indices; // array of indices (consectuive neuron numbers) for rhomb neurons indices = new int[total_assembly_size]; // gather indices of neurons belonging to the rhomb for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { indices[ind++] = center+i*Nl_exc+j; } } // draw random neurons out of the rhomb while(count < fraction*total_assembly_size) { int chosen_n = rhomb_dist(rg); if (indices[chosen_n-1] >= 0) // found a neuron that has not be assigned a stimulus { neurons[indices[chosen_n-1]].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron count++; indices[chosen_n-1] = -1; } } setStimulationEnd(_st.getStimulationEnd()); delete[] indices; } /*** setRhombPartialStimulus *** * Sets stimulation for first fraction of neurons out of a rhomb shape in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons) * * - double fraction: the fraction of neurons in the rhomb that shall be stimulated */ void setRhombPartialStimulus(Stimulus& _st, int center, int radius, double fraction) { int count = int(fraction * (2*radius*(radius+1)+1)); for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { neurons[center+i*Nl_exc+j].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron count--; if (count == 0) break; } if (count == 0) break; } setStimulationEnd(_st.getStimulationEnd()); } /*** setRandomStimulus *** * Sets a randomly distributed firing rate stimulus in the exc. population * * - Stimulus& _st: shape of one stimulus period * * - int num: the number of neurons to be drawn (i.e., to be stimulated) * * - ofstream* f [optional]: handle to a file for output of the randomly drawn neuron numbers * * - int range_start [optional]: the lowest neuron number that can be drawn * * - int range_end [optional]: one plus the highest neuron number that can be drawn (-1: highest possible) */ void setRandomStimulus(Stimulus& _st, int num, ofstream* f = NULL, int range_start=0, int range_end=-1) { int range_len = (range_end == -1) ? (pow2(Nl_exc) - range_start) : (range_end - range_start); // the number of neurons eligible for being drawn bool* stim_neurons = new bool [range_len]; uniform_int_distribution<int> u_dist_neurons(0, range_len-1); // uniform distribution to draw neuron numbers int neurons_left = num; if (f != NULL) *f << "Randomly drawn neurons for stimulation:" << " { "; for (int i=0; i<range_len; i++) stim_neurons[i] = false; while (neurons_left > 0) { int neur = u_dist_neurons(rg); // draw a neuron if (!stim_neurons[neur]) // if the stimulus has not yet been assigned to the drawn neuron { neurons[neur+range_start].setCurrentStimulus(_st); // set temporal course of current stimulus for drawn neuron stim_neurons[neur] = true; neurons_left--; if (f != NULL) *f << neur+range_start << ", "; // print stimulated neuron to file } } setStimulationEnd(_st.getStimulationEnd()); if (f != NULL) *f << " }" << endl; delete[] stim_neurons; } /*** setSingleNeuronStimulus *** * Sets a firing rate stimulus for a specified neuron * * - int m: number of the neuron to be stimulated * * - Stimulus& _st: shape of one stimulus period */ void setSingleNeuronStimulus(int m, Stimulus& _st) { neurons[m].setCurrentStimulus(_st); setStimulationEnd(_st.getStimulationEnd()); } /*** setBlockStimulus *** * Sets a stimulus for a given block of n neurons in the network * * - Stimulus& _st: shape of one stimulus period * * - int n: the number of neurons that shall be stimulated * * - int off [optional]: the offset that defines at which neuron number the block begins */ void setBlockStimulus(Stimulus& _st, int n, int off=0) { for (int i=off; i<(n+off); i++) { neurons[i].setCurrentStimulus(_st); // set temporal course of current stimulus for given neuron } setStimulationEnd(_st.getStimulationEnd()); } /*** setConstCurrent *** * Sets the constant current for all neurons to a newly defined value * - double _I_const: constant current in nA */ void setConstCurrent(double _I_const) { for (int m=0; m<N; m++) { neurons[m].setConstCurrent(_I_const); } } #if STIPULATE_CA == ON /*** stipulateRhombAssembly *** * Stipulates a rhomb-shaped cell assembly with strong interconnections * * - int center: the index of the neuron in the center of the rhomb * * - int radius: the "radius" of the rhomb in neurons (radius 3 corresponds to a rhomb containing 25 neurons, radius 5 to 61 neurons) */ void stipulateRhombAssembly(int center, int radius) { double value = 2*h_0; // stipulated value for (int i=-radius; i<=radius; i++) { int num_cols = (radius-abs(i)); for (int j=-num_cols; j<=num_cols; j++) { int m = center+i*Nl_exc+j; for (int k=-radius; k<=radius; k++) { int num_cols = (radius-abs(k)); for (int l=-num_cols; l<=num_cols; l++) { int n = center+k*Nl_exc+l; if (conn[m][n]) // set all connections within the assembly to this value h[m][n] = value; } } } } } /*** stipulateFirstNeuronsAssembly *** * Stipulates an cell assembly consisting of the first neurons with strong interconnections * * - int n: the number of neurons that shall be stimulated */ void stipulateFirstNeuronsAssembly(int n) { double value = 2*h_0; // stipulated value for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (conn[i][j]) // set all connections within the assembly to this value h[i][j] = value; } } } #endif /*** setSigma *** * Sets the standard deviation for the external input current for all neurons to a newly defined value * - double _sigma: standard deviation in nA s^(1/2) */ void setSigma(double _sigma) { for (int m=0; m<N; m++) { neurons[m].setSigma(_sigma); } } /*** setSynTimeConstant *** * Sets the synaptic time constant * * - double _tau_syn: synaptic time constant in s */ void setSynTimeConstant(double _tau_syn) { tau_syn = _tau_syn; for (int m=0; m<N; m++) { neurons[m].setTauOU(tau_syn); } } /*** setCouplingStrengths *** * Sets the synaptic coupling strengths * * - double _w_ee: coupling strength for exc. -> exc. connections in units of h_0 * * - double _w_ei: coupling strength for exc. -> inh. connections in units of h_0 * * - double _w_ie: coupling strength for inh. -> exc. connections in units of h_0 * * - double _w_ii: coupling strength for inh. -> inh. connections in units of h_0 */ void setCouplingStrengths(double _w_ee, double _w_ei, double _w_ie, double _w_ii) { w_ee = _w_ee * h_0; w_ei = _w_ei * h_0; w_ie = _w_ie * h_0; w_ii = _w_ii * h_0; } /*** getInitialWeight *** * Returns the initial exc.->exc. weight (typically h_0) */ double getInitialWeight() { return w_ee; } /*** getSynapticCalcium *** * Returns the calcium amount at a given synapse * * - synapse s: structure specifying pre- and postsynaptic neuron * * - return: the synaptic calcium amount */ double getSynapticCalcium(synapse s) const { return Ca[s.presyn_neuron][s.postsyn_neuron]; } /*** getEarlySynapticStrength *** * Returns the early-phase synaptic strength at a given synapse * * - synapse s: structure specifying pre- and postsynaptic neuron * * - return: the early-phase synaptic strength */ double getEarlySynapticStrength(synapse s) const { return h[s.presyn_neuron][s.postsyn_neuron]; } /*** getLateSynapticStrength *** * Returns the late-phase synaptic strength at a given synapse * * - synapse s: structure specifying pre- and postsynaptic neuron * * - return: the late-phase synaptic strength */ double getLateSynapticStrength(synapse s) const { return z[s.presyn_neuron][s.postsyn_neuron]; } /*** getMeanEarlySynapticStrength *** * Returns the mean early-phase synaptic strength (averaged over all synapses within the given set of neurons) * * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the mean early-phase synaptic strength */ double getMeanEarlySynapticStrength(int n, int off=0) const { double h_mean = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; h_mean += h[i][j]; } } } h_mean /= c_number; return h_mean; } /*** getMeanLateSynapticStrength *** * Returns the mean late-phase synaptic strength (averaged over all synapses within the given set of neurons) * * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the mean late-phase synaptic strength */ double getMeanLateSynapticStrength(int n, int off=0) const { double z_mean = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; z_mean += z[i][j]; } } } z_mean /= c_number; return z_mean; } /*** getSDEarlySynapticStrength *** * Returns the standard deviation of the early-phase synaptic strength (over all synapses within the given set of neurons) * * - double mean: the mean of the early-phase syn. strength within the given set * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the std. dev. of the early-phase synaptic strength */ double getSDEarlySynapticStrength(double mean, int n, int off=0) const { double h_sd = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; h_sd += pow2(h[i][j] - mean); } } } h_sd = sqrt(h_sd / c_number); return h_sd; } /*** getSDLateSynapticStrength *** * Returns the standard deviation of the late-phase synaptic strength (over all synapses within the given set of neurons) * * - double mean: the mean of the late-phase syn. strength within the given set * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the std. dev. of the late-phase synaptic strength */ double getSDLateSynapticStrength(double mean, int n, int off=0) const { double z_sd = 0.; int c_number = 0; for (int i=off; i < (n+off); i++) { for (int j=off; j < (n+off); j++) { if (conn[i][j]) { c_number++; z_sd += pow2(z[i][j] - mean); } } } z_sd = sqrt(z_sd / c_number); return z_sd; } /*** getMeanCProteinAmount *** * Returns the mean protein amount (averaged over all neurons within the given set) * * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the mean protein amount */ double getMeanCProteinAmount(int n, int off=0) const { double pa = 0.; for (int i=off; i < (n+off); i++) { pa += neurons[i].getCProteinAmount(); } pa /= n; return pa; } /*** getSDCProteinAmount *** * Returns the standard deviation of the protein amount (over all neurons within the given set) * * - double mean: the mean of the protein amount within the given set * - int n: the number of neurons that shall be considered (e.g., n=Nl_exc^2 for all excitatory neurons, or n=N for all neurons) * * - int off [optional]: the offset that defines at which neuron number the considered range begins * * - return: the std. dev. of the protein amount */ double getSDCProteinAmount(double mean, int n, int off=0) const { double pa_sd = 0.; for (int i=off; i < (n+off); i++) { pa_sd += pow2(neurons[i].getCProteinAmount() - mean); } pa_sd = sqrt(pa_sd / n); return pa_sd; } /*** readConnections *** * Reads the connectivity matrix from a file, either given by a text-converted numpy array or a plain matrix structure * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened, 0 - dimension mismatch */ int readConnections(string file, int format = 0) { ifstream f(file, ios::in); // the file handle string buf; // buffer to read one line int m, n = 0; // pre- and postsynaptic neuron int initial_brackets = 0; // specifies if the initial brackets have been read yet if (!f.is_open()) // check if file was opened successfully return 1; for (int a=0;a<N;a++) // reset connections of all neurons neurons[a].resetConnections(); if (format == 0) m = -1; else m = 0; while (getline(f, buf)) // while end of file has not yet been reached { if (format == 0 && buf.size() > 0) { m++; n = 0; } for (int i=0; i<buf.size(); i++) // go through all characters in this line { if (format == 1 && buf[i] == '[') { if (initial_brackets < 2) // still reading the initial brackets initial_brackets++; else { m++; n = 0; } } else if (buf[i] == '1') { if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // exc. -> exc. { neurons[m].addOutgoingConnection(n, TYPE_EXC); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_EXC); } else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) // exc. -> inh. { neurons[m].addOutgoingConnection(n, TYPE_INH); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_EXC); } else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) // inh. -> exc. { neurons[m].addOutgoingConnection(n, TYPE_EXC); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_INH); } else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) // inh. -> inh. { neurons[m].addOutgoingConnection(n, TYPE_INH); //cout << m << " -> " << n << " added" << endl; neurons[n].incNumberIncoming(TYPE_INH); } conn[m][n] = true; n++; } else if (buf[i] == '0') { conn[m][n] = false; n++; } } } f.close(); reset(); if (m != (N-1) || n != N) // if dimensions do not match return 0; return 2; } /*** printConnections *** * Prints the connection matrix to a given file (either in numpy structure or in plain matrix structure) * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened */ int printConnections(string file, int format = 0) { ofstream f(file); // the file handle if (!f.is_open()) // check if file was opened successfully return 1; if (format == 1) f << "["; for (int m=0;m<N;m++) { if (format == 1) f << "["; for (int n=0;n<N;n++) { if (conn[m][n]) f << "1 "; else f << "0 "; } if (format == 1) f << "]"; f << endl; } if (format == 1) f << "]"; f.close(); return 2; } /*** printConnections2 *** * FOR TESTING THE CONNECTIONS SAVED IN ARRAYS IN NEURONS * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened * int printConnections2(string file, int format = 0) { ofstream f(file); // the file handle if (!f.is_open()) // check if file was opened successfully return 1; if (format == 1) f << "["; for (int m=0;m<N;m++) { if (format == 1) f << "["; int in=0; for (int n=0;n<N;n++) { if (conn[m][n] && neurons[m].getNumberOutgoing() > in && neurons[m].getOutgoingConnection(in) == n) { f << "1 "; in++; } else f << "0 "; } if (format == 1) f << "]"; f << endl; } if (format == 1) f << "]"; f.close(); return 2; }*/ /*** printAllInitialWeights *** * Prints the connection matrix to a given file (either in numpy structure or in plain matrix structure) * * - file: a text file where the matrix is located * * - format: 0 for plain matrix structure, 1 for numpy structure with square brackets * - return: 2 - successful, 1 - file could not opened */ int printAllInitialWeights(string file, int format = 0) { ofstream f(file); // the file handle if (!f.is_open()) // check if file was opened successfully return 1; if (format == 1) f << "["; for (int m=0;m<N;m++) { if (format == 1) f << "["; for (int n=0;n<N;n++) { // Output of all initial weights if (conn[m][n]) { if (m < pow2(Nl_exc) && n < pow2(Nl_exc)) // exc. -> exc. f << h[m][n] << " "; else if (m < pow2(Nl_exc) && n >= pow2(Nl_exc)) // exc. -> inh. f << w_ei << " "; else if (m >= pow2(Nl_exc) && n < pow2(Nl_exc)) // inh. -> exc. f << w_ie << " "; else if (m >= pow2(Nl_exc) && n >= pow2(Nl_exc)) // inh. -> inh. f << w_ii << " "; } else f << 0. << " "; } if (format == 1) f << "]"; f << endl; } if (format == 1) f << "]"; f.close(); return 2; } /*** readCouplingStrengths *** * Reads the excitatory coupling strengths from a text file that contains a matrix for early-phase weights and a matrix * * for late-phase weights, each terminated by a blank line * * - file: a text file where the matrix is located * * - return: 2 - successful, 1 - file could not opened, 0 - dimension mismatch */ int readCouplingStrengths(string file) { int phase = 1; // 1: reading early-phase values, 2: reading late-phase values int m = 0, n; // pre- and postsynaptic neuron double strength; ifstream f(file, ios::in); // the file handle string buf; // buffer to read one line if (!f.is_open()) return 1; // Read early- and late-phase matrix while (getline (f, buf)) { istringstream iss(buf); if (!buf.empty()) { n = 0; while(iss >> strength) { if (phase == 1) h[m][n] = strength; else z[m][n] = strength; n++; } m++; } else // blank line encountered { if (phase == 1) // now begins the second phase { if (m != pow2(Nl_exc) || n != pow2(Nl_exc)) // if dimensions do not match { f.close(); return 0; } phase = 2; m = 0; n = 0; } else break; } } f.close(); if (m != pow2(Nl_exc) || n != pow2(Nl_exc)) // if dimensions do not match { return 0; } return 2; } /*** setStimulationEnd *** * Tells the Network instance the end of stimulation (even if not all stimuli are yet set) * * - int stim_end: the timestep in which stimulation ends */ void setStimulationEnd(int stim_end) { if (stim_end > stimulation_end) stimulation_end = stim_end; } /*** setSpikeStorageTime *** * Sets the number of timesteps for which spikes have to be kept in RAM * * - int storage_steps: the size of the storage timespan in timesteps */ void setSpikeStorageTime(int storage_steps) { for (int m=0; m<N; m++) { neurons[m].setSpikeHistoryMemory(storage_steps); } } /*** resetLastSpikeIndex *** * Resets the last spike index of a neuron important to its calcium dynamics * * - int m: the neuron number */ void resetLastSpikeIndex(int m) { last_Ca_spike_index[m] = 1; } /*** resetPlasticity *** * Depending on the arguments, undoes plastic changes that the network has undergone, * * resets calcium values or protein values * * - bool early_phase: resets all early-phase weights and calcium concentrations * * - bool late_phase: resets all late-phase weights * * - bool calcium: resets all calcium concentrations * * - bool proteins: resets all neuronal protein pools */ void resetPlasticity(bool early_phase, bool late_phase, bool calcium, bool proteins) { for (int m=0; m<N; m++) { if (proteins) neurons[m].setProteinAmounts(0., 0., 0.); for (int n=0; n<N; n++) // reset synapses { if (early_phase) { if (conn[m][n]) h[m][n] = h_0; else h[m][n] = 0.; } if (calcium) Ca[m][n] = 0.; if (late_phase) z[m][n] = 0.; } } } /*** reset *** * Resets the network and all neurons to initial state (but maintain connectivity) */ void reset() { rg.seed(getClockSeed()); // set new seed by clock's epoch u_dist.reset(); // reset the uniform distribution for random numbers norm_dist.reset(); // reset the normal distribution for random numbers for (int m=0; m<N; m++) { neurons[m].reset(); for (int n=0; n<N; n++) // reset synapses { if (conn[m][n]) h[m][n] = h_0; else h[m][n] = 0.; Ca[m][n] = 0.; z[m][n] = 0.; } resetLastSpikeIndex(m); sum_h_diff[m] = 0.; sum_h_diff_p[m] = 0.; sum_h_diff_d[m] = 0.; } stimulation_end = 0; max_dev = 0.; tb_max_dev = 0; #if PROTEIN_POOLS == POOLS_C || PROTEIN_POOLS == POOLS_PCD max_sum_diff = 0.; tb_max_sum_diff = 0; #endif #if PROTEIN_POOLS == POOLS_PD || PROTEIN_POOLS == POOLS_PCD max_sum_diff_p = 0.; tb_max_sum_diff_p = 0; max_sum_diff_d = 0.; tb_max_sum_diff_d = 0; #endif #ifdef TWO_NEURONS_ONE_SYNAPSE tag_glob = false; ps_glob = false; #endif } /*** setCaConstants *** * Set constants for the calcium dynamics * * - double _theta_p: the potentiation threshold * * - double _theta_d: the potentiation threshold */ void setCaConstants(double _theta_p, double _theta_d, double _Ca_pre, double _Ca_post) { theta_p = _theta_p; theta_d = _theta_d; Ca_pre = _Ca_pre; Ca_post = _Ca_post; } /*** setPSThresholds *** * Set thresholds for the onset of protein synthesis * * - double _theta_pro_P: the threshold for P synthesis (in units of h0) * * - double _theta_pro_C: the threshold for C synthesis (in units of h0) * * - double _theta_pro_D: the threshold for D synthesis (in units of h0) */ void setPSThresholds(double _theta_pro_P, double _theta_pro_C, double _theta_pro_D) { theta_pro_p = _theta_pro_P*h_0; theta_pro_c = _theta_pro_C*h_0; theta_pro_d = _theta_pro_D*h_0; } /*** Constructor *** * Sets all parameters, creates neurons and synapses * * --> it is required to call setSynTimeConstant and setCouplingStrengths immediately * * after calling this constructor! * * - double _dt: the length of one timestep in s * * - int _Nl_exc: the number of neurons in one line in excitatory population (row/column) * * - int _Nl_inh: the number of neurons in one line in inhibitory population (row/column) - line structure so that stimulation of inhib. * population could be implemented more easily * * - double _p_c: connection probability * * - double _sigma_plasticity: standard deviation of the plasticity * * - double _z_max: the upper z bound */ Network(const double _dt, const int _Nl_exc, const int _Nl_inh, double _p_c, double _sigma_plasticity, double _z_max) : dt(_dt), rg(getClockSeed()), u_dist(0.0,1.0), norm_dist(0.0,1.0), Nl_exc(_Nl_exc), Nl_inh(_Nl_inh), z_max(_z_max) { N = pow2(Nl_exc) + pow2(Nl_inh); // total number of neurons p_c = _p_c; // set connection probability t_syn_delay = 0.003; // from https://www.britannica.com/science/nervous-system/The-neuronal-membrane#ref606406, accessed 18-06-21 #if defined TWO_NEURONS_ONE_SYNAPSE && !defined TWO_NEURONS_ONE_SYNAPSE_ALT t_syn_delay = dt; #endif t_syn_delay_steps = int(t_syn_delay/dt); // Biophysical parameters for stimulation, Ca dynamics and early phase t_Ca_delay = 0.0188; // from Graupner and Brunel (2012), hippocampal slices t_Ca_delay_steps = int(t_Ca_delay/dt); Ca_pre = 1.0; // from Graupner and Brunel (2012), hippocampal slices Ca_post = 0.2758; // from Graupner and Brunel (2012), hippocampal slices tau_Ca = 0.0488; // from Graupner and Brunel (2012), hippocampal slices tau_Ca_steps = int(tau_Ca/dt); tau_h = 688.4; // from Graupner and Brunel (2012), hippocampal slices gamma_p = 1645.6; // from Graupner and Brunel (2012), hippocampal slices gamma_d = 313.1; // from Graupner and Brunel (2012), hippocampal slices h_0 = 0.5*(gamma_p/(gamma_p+gamma_d)); // from Li et al. (2016) theta_p = 3.0; // from Li et al. (2016) theta_d = 1.2; // from Li et al. (2016) sigma_plasticity = _sigma_plasticity; // from Graupner and Brunel (2012) but corrected by 1/sqrt(1000) // Biophysical parameters for protein synthesis and late phase tau_pp = 1.0; // from Li et al. (2016) tau_pc = 1.0; // from Li et al. (2016) tau_pd = 1.0; // from Li et al. (2016) alpha_p = 1.0; // from Li et al. (2016) alpha_c = 1.0; // from Li et al. (2016) alpha_d = 1.0; // from Li et al. (2016) tau_z = 60.0; // from Li et al. (2016) - includes "gamma" theta_pro_p = 0.5*h_0; // theta_pro_c = 0.5*h_0; // from Li et al. (2016) theta_pro_d = 0.5*h_0; // theta_tag_p = 0.2*h_0; // from Li et al. (2016) theta_tag_d = 0.2*h_0; // from Li et al. (2016) // Create neurons and synapse matrices neurons = vector<Neuron> (N, Neuron(_dt)); conn = new bool* [N]; Ca = new double* [N]; h = new double* [N]; z = new double* [N]; last_Ca_spike_index = new int [N]; sum_h_diff = new double [N]; sum_h_diff_p = new double [N]; sum_h_diff_d = new double [N]; for (int m=0; m<N; m++) { if (m < pow2(Nl_exc)) // first Nl_exc^2 neurons are excitatory neurons[m].setType(TYPE_EXC); else // remaining neurons are inhibitory neurons[m].setType(TYPE_INH); conn[m] = new bool [N]; Ca[m] = new double [N]; h[m] = new double [N]; z[m] = new double [N]; // create synaptic connections for (int n=0; n<N; n++) { conn[m][n] = false; // necessary for resetting the connections if (m != n) // if not on main diagonal (which should remain zero) { conn[m][n] = shallBeConnected(m, n); // use random generator depending on connection probability } } } #ifdef TWO_NEURONS_ONE_SYNAPSE neurons[1].setPoisson(true); #ifdef PLASTICITY_OVER_FREQ neurons[0].setPoisson(true); #endif #endif } /*** Destructor *** * Cleans up the allocated memory for arrays */ ~Network() { for(int i=0; i<N; i++) { delete[] conn[i]; delete[] Ca[i]; delete[] h[i]; delete[] z[i]; } delete[] conn; delete[] Ca; delete[] h; delete[] z; delete[] last_Ca_spike_index; delete[] sum_h_diff; delete[] sum_h_diff_p; delete[] sum_h_diff_d; } /* =============================================================================================================================== */ /* ==== Functions redirecting to corresponding functions in Neuron class ========================================================= */ /* Two versions are given for each function, one for consecutive and one for row/column numbering */ /*** getType *** * Returns the type of neuron (i|j) (inhbitory/excitatory) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the neuron type */ int getType(int i, int j) const { return neurons[cNN(i,j)].getType(); } int getType(int m) const { return neurons[m].getType(); } /*** getVoltage *** * Returns the membrane potential of neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the membrane potential in mV */ double getVoltage(int i, int j) const { return neurons[cNN(i,j)].getVoltage(); } double getVoltage(int m) const { return neurons[m].getVoltage(); } /*** getThreshold *** * Returns the value of the dynamic membrane threshold of neuron (i|j) * * - return: the membrane threshold in mV */ double getThreshold(int i, int j) const { return neurons[cNN(i,j)].getThreshold(); } double getThreshold(int m) const { return neurons[m].getThreshold(); } /*** getCurrent *** * Returns total current effecting neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the instantaneous current in nA */ double getCurrent(int i, int j) const { return neurons[cNN(i,j)].getCurrent(); } double getCurrent(int m) const { return neurons[m].getCurrent(); } /*** getStimulusCurrent *** * Returns current evoked by external stimulation in neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the instantaneous current stimulus in nA */ double getStimulusCurrent(int i, int j) const { return neurons[cNN(i,j)].getStimulusCurrent(); } double getStimulusCurrent(int m) const { return neurons[m].getStimulusCurrent(); } /*** getBGCurrent *** * Returns background noise current entering neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the instantaneous fluctuating current in nA */ double getBGCurrent(int i, int j) const { return neurons[cNN(i,j)].getBGCurrent(); } double getBGCurrent(int m) const { return neurons[m].getBGCurrent(); } /*** getConstCurrent *** * Returns the constant current elicited by the surrounding network (not this network!) in neuron (i|j) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the constant current in nA */ double getConstCurrent(int i, int j) const { return neurons[cNN(i,j)].getConstCurrent(); } double getConstCurrent(int m) const { return neurons[m].getConstCurrent(); } /*** getSigma *** * Returns the standard deviation of the white noise entering the external current * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the standard deviation in nA s^(1/2) */ double getSigma(int i, int j) const { return neurons[cNN(i,j)].getSigma(); } double getSigma(int m) const { return neurons[m].getSigma(); } /*** getSynapticCurrent *** * Returns the synaptic current that arrived in the previous timestep * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the synaptic current in nA */ double getSynapticCurrent(int i, int j) const { return neurons[cNN(i,j)].getSynapticCurrent(); } double getSynapticCurrent(int m) const { return neurons[m].getSynapticCurrent(); } #if DENDR_SPIKES == ON /*** getDendriticCurrent *** * Returns the current that dendritic spiking caused in the previous timestep * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the synaptic current in nA */ double getDendriticCurrent(int i, int j) const { return neurons[cNN(i,j)].getDendriticCurrent(); } double getDendriticCurrent(int m) const { return neurons[m].getDendriticCurrent(); } #endif #if COND_BASED_SYN == ON /*** getExcSynapticCurrent *** * Returns the internal excitatory synaptic current that arrived in the previous timestep * * - return: the excitatory synaptic current in nA */ double getExcSynapticCurrent(int i, int j) const { return neurons[cNN(i,j)].getExcSynapticCurrent(); } double getExcSynapticCurrent(int m) const { return neurons[m].getExcSynapticCurrent(); } /*** getInhSynapticCurrent *** * Returns the internal inhibitory synaptic current that arrived in the previous timestep * * - return: the inhibitory synaptic current in nA */ double getInhSynapticCurrent(int i, int j) const { return neurons[cNN(i,j)].getInhSynapticCurrent(); } double getInhSynapticCurrent(int m) const { return neurons[m].getInhSynapticCurrent(); } #endif /*** getActivity *** * Returns true if neuron (i|j) is spiking in this instant of duration dt * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: whether neuron is firing or not */ bool getActivity(int i, int j) const { return neurons[cNN(i,j)].getActivity(); } bool getActivity(int m) const { return neurons[m].getActivity(); } /*** spikeAt *** * Returns whether or not a spike has occurred at a given spike, begins searching * * from latest spike * * - int t_step: the timebin at which the spike should have occurred * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: true if a spike occurred, false if not */ bool spikeAt(int t_step, int i, int j) const { return neurons[cNN(i,j)].spikeAt(t_step); } bool spikeAt(int t_step, int m) const { return neurons[m].spikeAt(t_step); } /*** getSpikeTime *** * Returns the spike time for a given spike number (in temporal order, starting with 1) of neuron (i|j) * * ATTENTION: argument n should not exceed the result of getSpikeHistorySize() * * - int n: the number of the considered spike (in temporal order, starting with 1) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the spike time for the n-th spike (or -1 if there exists none) */ int getSpikeTime(int n, int i, int j) const { return neurons[cNN(i,j)].getSpikeTime(n); } int getSpikeTime(int n, int m) const { return neurons[m].getSpikeTime(n); } /*** removeSpikes *** * Removes a specified set of spikes from history, to save memory * * - int start: the number of the spike to start with (in temporal order, starting with 1) * - int end: the number of the spike to end with (in temporal order, starting with 1) * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located */ void removeSpikes(int start, int end, int i, int j) { neurons[cNN(i,j)].removeSpikes(start, end); } void removeSpikes(int start, int end, int m) { neurons[m].removeSpikes(start, end); } /*** getSpikeCount *** * Returns the number of spikes that have occurred since the last reset (including those that have been removed) of neuron (i|j) * * - return: the number of spikes */ int getSpikeCount(int i, int j) const { return neurons[cNN(i,j)].getSpikeCount(); } int getSpikeCount(int m) const { return neurons[m].getSpikeCount(); } /*** getSpikeHistorySize *** * Returns the current size of the spike history vector of neuron (i|j) * * - return: the size of the spike history vector */ int getSpikeHistorySize(int i, int j) const { return neurons[cNN(i,j)].getSpikeHistorySize(); } int getSpikeHistorySize(int m) const { return neurons[m].getSpikeHistorySize(); } /*** setCurrentStimulus *** * Sets a current stimulus for neuron (i|j) * - Stimulus& _cst: shape of one stimulus period * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located */ void setCurrentStimulus(Stimulus& _cst, int i, int j) { neurons[cNN(i,j)].setCurrentStimulus(_cst); } void setCurrentStimulus(Stimulus& _cst, int m) { neurons[m].setCurrentStimulus(_cst); } /*** getNumberIncoming *** * Returns the number of either inhibitory or excitatory incoming connections to this neuron * * from other neurons in the network * * - int type: the type of incoming connections (inh./exc.) * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the number of incoming connections */ int getNumberIncoming(int type, int i, int j) const { return neurons[cNN(i,j)].getNumberIncoming(type); } int getNumberIncoming(int type, int m) const { return neurons[m].getNumberIncoming(type); } /*** getNumberOutgoing *** * Returns the number of connections outgoing from this neuron to other * * neurons of a specific type * * - int type: the type of postsynaptic neurons (inh./exc.) * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: the number of outgoing connections */ int getNumberOutgoing(int type, int i, int j) const { return neurons[cNN(i,j)].getNumberOutgoing(type); } int getNumberOutgoing(int type, int m) const { return neurons[m].getNumberOutgoing(type); } /*** getPProteinAmount *** * Returns the LTP-related protein amount in a neuron * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: momentary LTP-related protein amount */ double getPProteinAmount(int i, int j) const { return neurons[cNN(i,j)].getPProteinAmount(); } double getPProteinAmount(int m) const { return neurons[m].getPProteinAmount(); } /*** getCProteinAmount *** * Returns the common protein amount in a neuron * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: momentary LTP-related protein amount */ double getCProteinAmount(int i, int j) const { return neurons[cNN(i,j)].getCProteinAmount(); } double getCProteinAmount(int m) const { return neurons[m].getCProteinAmount(); } /*** getDProteinAmount *** * Returns the LTD-related protein amount in a neuron * * - int i: the row where the neuron is located * * - int j: the column where the neuron is located * * - return: momentary LTD-related protein amount */ double getDProteinAmount(int i, int j) const { return neurons[cNN(i,j)].getDProteinAmount(); } double getDProteinAmount(int m) const { return neurons[m].getDProteinAmount(); } /*** saveNeuronParams *** * Saves all the neuron parameters (including the channel parameters) to a given file; * * all neurons have the same parameters, so the first one is taken */ void saveNeuronParams(ofstream *f) const { neurons[0].saveNeuronParams(f); } /* =============================================================================================================================== */ };
32.375831
161
0.659689
97223cf5eab0d82cf2ae033407622716e90e72ba
1,428
cpp
C++
Oem/dbxml/dbxml/src/dbxml/query/QueryPlanToAST.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/dbxml/src/dbxml/query/QueryPlanToAST.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/dbxml/src/dbxml/query/QueryPlanToAST.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // // #include "../DbXmlInternal.hpp" #include "QueryPlanToAST.hpp" #include "ASTToQueryPlan.hpp" #include "QueryPlan.hpp" #include "NodeIterator.hpp" #include <xqilla/ast/XQNav.hpp> #include <xqilla/context/DynamicContext.hpp> using namespace DbXml; using namespace std; QueryPlanToAST::QueryPlanToAST(QueryPlan *qp, StaticContext *context, XPath2MemoryManager *mm) : DbXmlASTNode(QP_TO_AST, mm), qp_(qp) { qp_->staticTypingLite(context); _src.copy(qp_->getStaticAnalysis()); _src.availableCollectionsUsed(true); } ASTNode *QueryPlanToAST::staticTypingImpl(StaticContext *context) { _src.clear(); _src.availableCollectionsUsed(true); _src.copy(qp_->getStaticAnalysis()); if(qp_->getType() == QueryPlan::AST_TO_QP) { return ((ASTToQueryPlan*)qp_)->getASTNode(); } return this; } Result QueryPlanToAST::createResult(DynamicContext* context, int flags) const { return new QueryPlanToASTResult(qp_->createNodeIterator(context), this); } //////////////////////////////////////////////////////////////////////////////////////////////////// QueryPlanToASTResult::~QueryPlanToASTResult() { delete it_; } Item::Ptr QueryPlanToASTResult::next(DynamicContext *context) { if(it_ == 0 || !it_->next(context)) { delete it_; it_ = 0; return 0; } return it_->asDbXmlNode(context); }
21.313433
100
0.688375
972393cee5e0b965ae335d1d954c3d74207f5581
3,528
cpp
C++
src/n_angleBinaryOp.cpp
Lohult/angularNodes
2f923419b01439e6bf63bcd65b87dfc68a3e72d0
[ "MIT" ]
24
2016-09-03T23:36:56.000Z
2022-02-18T08:21:16.000Z
src/n_angleBinaryOp.cpp
Lohult/angularNodes
2f923419b01439e6bf63bcd65b87dfc68a3e72d0
[ "MIT" ]
4
2016-09-06T09:59:01.000Z
2018-01-13T19:36:39.000Z
src/n_angleBinaryOp.cpp
Lohult/angularNodes
2f923419b01439e6bf63bcd65b87dfc68a3e72d0
[ "MIT" ]
7
2017-02-16T06:13:21.000Z
2019-07-19T22:46:49.000Z
/** Copyright (c) 2016 Ryan Porter - arrayNodes You may use, distribute, or modify this code under the terms of the MIT license. */ //----------------------------------------------------------------------------- // angleUnaryOp node // // Performs a binary operation with two input values. // No Operation - Returns the input value. // Add - Returns the sum of the input values. // Subtract - Returns the difference between the input values. // Multiply - Returns the product of the input values. // Divide - Returns the quotient of the input values. // Power - Returns the exponent of the input values. //----------------------------------------------------------------------------- #include "n_angleBinaryOp.h" #include "node.h" #include <math.h> #include <maya/MAngle.h> #include <maya/MDataHandle.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnUnitAttribute.h> #include <maya/MPlug.h> #include <maya/MPxNode.h> MObject AngleBinaryOpNode::aInput1; MObject AngleBinaryOpNode::aInput2; MObject AngleBinaryOpNode::aOperation; MObject AngleBinaryOpNode::aOutput; const short NO_OP = 0; const short ADD = 1; const short SUBTRACT = 2; const short MULTIPLY = 3; const short DIVIDE = 4; const short POWER = 5; void* AngleBinaryOpNode::creator() { return new AngleBinaryOpNode(); } MStatus AngleBinaryOpNode::initialize() { MStatus status; MFnUnitAttribute u; MFnEnumAttribute e; aInput1 = u.create("input1", "i1", MFnUnitAttribute::kAngle, 0.0, &status); __CHECK_STATUS(status); MAKE_INPUT_ATTR(u); aInput2 = u.create("input2", "i2", MFnUnitAttribute::kAngle, 0.0, &status); __CHECK_STATUS(status); MAKE_INPUT_ATTR(u); aOperation = e.create("operation", "op", ADD, &status); __CHECK_STATUS(status); MAKE_INPUT_ATTR(e); e.addField("No Operation", NO_OP); e.addField("Add", ADD); e.addField("Subtract", SUBTRACT); e.addField("Multiply", MULTIPLY); e.addField("Divide", DIVIDE); e.addField("Power", POWER); aOutput = u.create("output", "o", MFnUnitAttribute::kAngle, 0.0, &status); __CHECK_STATUS(status); MAKE_OUTPUT_ATTR(u) addAttribute(aInput1); addAttribute(aInput2); addAttribute(aOperation); addAttribute(aOutput); attributeAffects(aInput1, aOutput); attributeAffects(aInput2, aOutput); attributeAffects(aOperation, aOutput); return MS::kSuccess; } MStatus AngleBinaryOpNode::compute(const MPlug& plug, MDataBlock& data) { if (plug != aOutput) { return MS::kUnknownParameter; } double input1 = data.inputValue(aInput1).asAngle().asDegrees(); double input2 = data.inputValue(aInput2).asAngle().asDegrees(); short operation = data.inputValue(aOperation).asShort(); double result = input1; switch (operation) { case ADD: result = input1 + input2; break; case SUBTRACT: result = input1 - input2; break; case MULTIPLY: result = input1 * input2; break; case DIVIDE: result = input2 == 0.0 ? 10000.0 : input1 / input2; break; case POWER: result = pow(input1, input2); break; } MDataHandle output = data.outputValue(aOutput); output.setMAngle(MAngle(result, MAngle::kDegrees)); output.setClean(); return MS::kSuccess; }
26.727273
80
0.618197
972566b7275599fa4d12f37c5ccbe4fb676cc609
2,385
cpp
C++
code/check.cpp
shercoo/TSP-Pointer_network
7ccda5d29e3ba4cfe2eb94350073936b591b61e7
[ "MIT" ]
1
2021-06-08T19:39:43.000Z
2021-06-08T19:39:43.000Z
code/check.cpp
shercoo/TSP-Pointer_network
7ccda5d29e3ba4cfe2eb94350073936b591b61e7
[ "MIT" ]
null
null
null
code/check.cpp
shercoo/TSP-Pointer_network
7ccda5d29e3ba4cfe2eb94350073936b591b61e7
[ "MIT" ]
1
2021-05-17T13:51:29.000Z
2021-05-17T13:51:29.000Z
#include <bits/stdc++.h> using namespace std; typedef long long ll; int read() { char c; int x=0,flag=1; while((c=getchar())&&(c<'0'||c>'9')) if(c=='-') flag=-1; do x=x*10+c-'0'; while((c=getchar())&&c>='0'&&c<='9'); return x*flag; } const int maxn=21; double dp[1<<maxn][maxn]; double x[maxn],y[maxn]; int pre[1<<maxn][maxn]; int vis[100]; double dist(int a,int b) { return sqrt(pow(x[a]-x[b],2)+pow(y[a]-y[b],2)); } int main() { #ifdef sherco // freopen("tmp.in","r",stdin); // freopen("tmp.out","w",stdout); #endif // freopen("tsp_5-20_train/tsp_all_len5.txt","r",stdin); // freopen("fuck1.out","w",stdout); freopen("test_data/tsp40_testdata0.txt","r",stdin); freopen("test_data/tsp40_testdata.txt","w",stdout); int n=40; int p[100]; int a[100]; for(int i=1;i<=n;i++) a[i]=i; for(int C=1;C<=10;C++){ int flag=0; for(int i=0;i<n;i++){ scanf("%lf%lf",&x[i],&y[i]); printf("%.12f %.12f ",x[i],y[i]); } char ss[10]; scanf("%s",ss); printf("%s ",ss); for(int i=0;i<=n;i++) scanf("%d",&p[i]); double sum=0; for(int i=0;i<n;i++){ sum+=dist(p[i]-1,p[i+1]-1); } int cur=1; double greedy=0,rd=0; for(int i=0;i<n-1;i++){ vis[cur]=C; int nx=0; double fuck=1e18; for(int j=1;j<=n;j++) if(vis[j]<C&&dist(cur-1,j-1)<fuck) fuck=dist(cur-1,j-1),nx=j; greedy+=dist(cur-1,nx-1); cur=nx; printf("%d ",cur); } greedy+=dist(cur-1,0); random_shuffle(a+1,a+n+1); for(int i=1;i<n;i++){ rd+=dist(a[i]-1,a[i+1]-1); } rd+=dist(a[n]-1,a[1]-1); printf("%.12f %.12f %.12f\n",sum,greedy,rd); } // for(int i=0;i<n;i++) // scanf("%lf%lf",&x[i],&y[i]); // double a=0,b=0; // for(int i=0;i<n;i++) // scanf("%d",&p[i]); // for(int i=0;i<n;i++) // a+=sqrt(pow(x[p[i]]-x[p[(i+1)%n]],2)+pow(y[p[i]]-y[p[(i+1)%n]],2)); // for(int i=0;i<n;i++) // scanf("%d",&p[i]); // for(int i=0;i<n;i++) // b+=sqrt(pow(x[p[i]]-x[p[(i+1)%n]],2)+pow(y[p[i]]-y[p[(i+1)%n]],2)); // printf("%.6f %.6f\n",a,b); return 0; }
25.37234
78
0.434801
9725f2cc945f31ed11817f4d8f9bcff7d992073b
558
hpp
C++
Classes/PlaneLayer.hpp
nickqiao/AirWar
1cd8b418a1a3ec240bc02581ecff034218939b59
[ "Apache-2.0" ]
2
2017-10-14T06:27:15.000Z
2021-11-05T20:27:28.000Z
Classes/PlaneLayer.hpp
nickqiao/AirWar
1cd8b418a1a3ec240bc02581ecff034218939b59
[ "Apache-2.0" ]
null
null
null
Classes/PlaneLayer.hpp
nickqiao/AirWar
1cd8b418a1a3ec240bc02581ecff034218939b59
[ "Apache-2.0" ]
null
null
null
// // PlaneLayer.hpp // AirWar // // Created by nick on 2017/1/19. // Copyright © 2017年 chenyuqiao. All rights reserved. // #include "cocos2d.h" USING_NS_CC; const int AIRPLANE=747; class PlaneLayer : public Layer { public: PlaneLayer(); ~PlaneLayer(); static PlaneLayer* create(); virtual bool init(); void MoveTo(Point location); void Blowup(int passScore); void RemovePlane(); public: static PlaneLayer* sharedPlane; bool isAlive; int score; };
12.976744
54
0.587814
972b50cd1f04f521e7246ec9b1ca30ac7d0280a9
25,083
cpp
C++
src/genlib/miniserver/miniserver.cpp
xiyusullos/upnpsdk
a1e280530338220a91668e6e6f2f07ccbc0c1382
[ "BSD-3-Clause" ]
null
null
null
src/genlib/miniserver/miniserver.cpp
xiyusullos/upnpsdk
a1e280530338220a91668e6e6f2f07ccbc0c1382
[ "BSD-3-Clause" ]
null
null
null
src/genlib/miniserver/miniserver.cpp
xiyusullos/upnpsdk
a1e280530338220a91668e6e6f2f07ccbc0c1382
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2000 Intel Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// // $Revision: 1.2 $ // $Date: 2001/08/15 18:17:31 $ #include "../../inc/tools/config.h" #if EXCLUDE_MINISERVER == 0 #include <arpa/inet.h> #include <netinet/in.h> #include <pthread.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/wait.h> #include <unistd.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <genlib/util/utilall.h> #include <genlib/util/util.h> #include <genlib/miniserver/miniserver.h> #include <genlib/tpool/scheduler.h> #include <genlib/tpool/interrupts.h> #include "upnp.h" #include "tools/config.h" // read timeout #define TIMEOUT_SECS 30 enum MiniServerState { MSERV_IDLE, MSERV_RUNNING, MSERV_STOPPING }; CREATE_NEW_EXCEPTION_TYPE( MiniServerReadException, BasicException, "MiniServerReadException" ) enum READ_EXCEPTION_CODE { RCODE_SUCCESS = 0, RCODE_NETWORK_READ_ERROR = -1, RCODE_MALFORMED_LINE = -2, RCODE_LENGTH_NOT_SPECIFIED = -3, RCODE_METHOD_NOT_ALLOWED = -4, RCODE_INTERNAL_SERVER_ERROR = -5, RCODE_METHOD_NOT_IMPLEMENTED = -6, RCODE_TIMEDOUT = -7, }; enum HTTP_COMMAND_TYPE { CMD_HTTP_GET, CMD_SOAP_POST, CMD_SOAP_MPOST, CMD_GENA_SUBSCRIBE, CMD_GENA_UNSUBSCRIBE, CMD_GENA_NOTIFY, CMD_HTTP_UNKNOWN, CMD_HTTP_MALFORMED }; // module vars static MiniServerCallback gGetCallback = NULL; static MiniServerCallback gSoapCallback = NULL; static MiniServerCallback gGenaCallback = NULL; static MiniServerState gMServState = MSERV_IDLE; static pthread_t gMServThread = 0; ////////////// void SetHTTPGetCallback( MiniServerCallback callback ) { gGetCallback = callback; } MiniServerCallback GetHTTPGetCallback( void ) { return gGetCallback; } void SetSoapCallback( MiniServerCallback callback ) { gSoapCallback = callback; } MiniServerCallback GetSoapCallback( void ) { return gSoapCallback; } void SetGenaCallback( MiniServerCallback callback ) { gGenaCallback = callback; } MiniServerCallback GetGenaCallback( void ) { return gGenaCallback; } class NetReader1 { public: NetReader1( int socketfd ); virtual ~NetReader1(); // throws MiniServerReadException.RCODE_TIMEDOUT int getChar( char& c ); // throws MiniServerReadException.RCODE_TIMEDOUT int getLine( xstring& s, bool& newlineNotFound ); // throws MiniServerReadException.RCODE_TIMEDOUT int readData( void* buf, size_t bufferLen ); int getMaxBufSize() const { return maxbufsize; } private: bool bufferHasData() const { return offset < buflen; } // throws MiniServerReadException.RCODE_TIMEDOUT ssize_t refillBuffer(); private: enum { MAX_BUFFER_SIZE = 1024 * 2 }; private: int sockfd; char data[MAX_BUFFER_SIZE + 1]; // extra byte for null terminator int offset; int buflen; int maxbufsize; }; NetReader1::NetReader1( int socketfd ) { sockfd = socketfd; offset = 0; maxbufsize = MAX_BUFFER_SIZE; buflen = 0; data[maxbufsize] = 0; } NetReader1::~NetReader1() { } int NetReader1::getChar( char& c ) { int status; if ( !bufferHasData() ) { status = refillBuffer(); if ( status <= 0 ) return status; if ( !bufferHasData() ) return 0; } c = data[offset]; offset++; return 1; // length of data returned } int NetReader1::getLine( xstring& s, bool& newlineNotFound ) { int startOffset; char c; int status; bool crFound; startOffset = offset; s = ""; newlineNotFound = false; crFound = false; while ( true ) { status = getChar( c ); if ( status == 0 ) { // no more chars in stream newlineNotFound = true; return s.length(); } if ( status < 0 ) { // some kind of error return status; } s += c; if ( c == 0xA ) { return s.length(); } else if ( c == 0xD ) // CR { crFound = true; } else { // wanted to see LF after CR; error if ( crFound ) { newlineNotFound = true; return s.length(); } } } return 0; } // read data int NetReader1::readData( void* buf, size_t bufferLen ) { int status; int copyLen; size_t dataLeft; // size of data left in buffer if ( bufferLen <= 0 ) return 0; // refill empty buffer if ( !bufferHasData() ) { status = refillBuffer(); if ( status <= 0 ) return status; if ( !bufferHasData() ) return 0; dataLeft = buflen; } else { dataLeft = buflen - offset; } if ( bufferLen < dataLeft ) { copyLen = bufferLen; } else { copyLen = dataLeft; } memcpy( buf, &data[offset], copyLen ); offset += copyLen; return copyLen; } // throws MiniServerReadException.RCODE_TIMEDOUT static int SocketRead( int sockfd, char* buffer, size_t bufsize, int timeoutSecs ) { int retCode; fd_set readSet; struct timeval timeout; int numRead; assert( sockfd > 0 ); assert( buffer != NULL ); assert( bufsize > 0 ); FD_ZERO( &readSet ); FD_SET( sockfd, &readSet ); timeout.tv_sec = timeoutSecs; timeout.tv_usec = 0; while ( true ) { retCode = select( sockfd + 1, &readSet, NULL, NULL, &timeout ); if ( retCode == 0 ) { // timed out MiniServerReadException e( "SocketRead(): timed out" ); e.setErrorCode( RCODE_TIMEDOUT ); throw e; } if ( retCode == -1 ) { if ( errno == EINTR ) { continue; // ignore interrupts } return retCode; // error } else { break; } } // read data numRead = read( sockfd, buffer, bufsize ); return numRead; } ssize_t NetReader1::refillBuffer() { ssize_t numRead; // old code // numRead = read( sockfd, data, maxbufsize ); /////// numRead = SocketRead( sockfd, data, maxbufsize, TIMEOUT_SECS ); if ( numRead >= 0 ) { buflen = numRead; } else { buflen = 0; } offset = 0; return numRead; } static void WriteNetData( const char* s, int sockfd ) { write( sockfd, s, strlen(s) ); } // determines type of UPNP command from request line, ln static HTTP_COMMAND_TYPE GetCommandType( const xstring& ln ) { // commands GET, POST, M-POST, SUBSCRIBE, UNSUBSCRIBE, NOTIFY xstring line = ln; int i; char c; char * getStr = "GET"; char * postStr = "POST"; char * mpostStr = "M-POST"; char * subscribeStr = "SUBSCRIBE"; char * unsubscribeStr = "UNSUBSCRIBE"; char * notifyStr = "NOTIFY"; char * pattern; HTTP_COMMAND_TYPE retCode=CMD_HTTP_UNKNOWN; try { line.toUppercase(); c = line[0]; switch (c) { case 'G': pattern = getStr; retCode = CMD_HTTP_GET; break; case 'P': pattern = postStr; retCode = CMD_SOAP_POST; break; case 'M': pattern = mpostStr; retCode = CMD_SOAP_MPOST; break; case 'S': pattern = subscribeStr; retCode = CMD_GENA_SUBSCRIBE; break; case 'U': pattern = unsubscribeStr; retCode = CMD_GENA_UNSUBSCRIBE; break; case 'N': pattern = notifyStr; retCode = CMD_GENA_NOTIFY; break; default: // unknown method throw -1; } int patLength = strlen( pattern ); for ( i = 1; i < patLength; i++ ) { if ( line[i] != pattern[i] ) throw -1; } } catch ( OutOfBoundsException& e ) { return CMD_HTTP_UNKNOWN; } catch ( int parseCode ) { if ( parseCode == -1 ) { return CMD_HTTP_UNKNOWN; } } return retCode; } static int ParseContentLength( const xstring& textLine, bool& malformed ) { xstring line; xstring asciiNum; char *pattern = "CONTENT-LENGTH"; int patlen = strlen( pattern ); int i; int contentLength; malformed = false; contentLength = -1; line = textLine; line.toUppercase(); if ( strncmp(line.c_str(), pattern, patlen) != 0 ) { // unknown header return -1; } i = patlen; try { // skip whitespace while ( line[i] == ' ' || line [i] == '\t' ) { i++; } // ":" if ( line[i] != ':' ) { throw -1; } i++; char* invalidChar = NULL; contentLength = strtol( &line[i], &invalidChar, 10 ); // anything other than crlf or whitespace after number is invalid if ( *invalidChar != '\0' ) { // see if there is an invalid number while ( *invalidChar ) { char c; c = *invalidChar; if ( !(c == ' ' || c == '\t' || c == '\r' || c == '\n') ) { // invalid char in number throw -1; } invalidChar++; } } } catch ( OutOfBoundsException& e ) { malformed = true; return -1; } catch ( int errCode ) { if ( errCode == -1 ) { malformed = true; return -1; } } return contentLength; } // throws // OutOfMemoryException // MiniServerReadException // RCODE_NETWORK_READ_ERROR // RCODE_MALFORMED_LINE // RCODE_METHOD_NOT_IMPLEMENTED // RCODE_LENGTH_NOT_SPECIFIED static void ReadRequest( int sockfd, xstring& document, HTTP_COMMAND_TYPE& command ) { NetReader1 reader( sockfd ); xstring reqLine; xstring line; bool newlineNotFound; int status; HTTP_COMMAND_TYPE cmd; int contentLength; const int BUFSIZE = 3; char buf[ BUFSIZE + 1 ]; MiniServerReadException excep; document = ""; // read request-line status = reader.getLine( reqLine, newlineNotFound ); if ( status < 0 ) { // read error excep.setErrorCode( RCODE_NETWORK_READ_ERROR ); throw excep; } if ( newlineNotFound ) { // format error excep.setErrorCode( RCODE_MALFORMED_LINE ); throw excep; } cmd = GetCommandType( reqLine ); if ( cmd == CMD_HTTP_UNKNOWN ) { // unknown or unsupported cmd excep.setErrorCode( RCODE_METHOD_NOT_IMPLEMENTED ); throw excep; } document += reqLine; contentLength = -1; // init // read headers while ( true ) { status = reader.getLine( line, newlineNotFound ); if ( status < 0 ) { // network error excep.setErrorCode( RCODE_NETWORK_READ_ERROR ); throw excep; } if ( newlineNotFound ) { // bad format excep.setErrorCode( RCODE_MALFORMED_LINE ); throw excep; } // get content-length if not obtained already if ( contentLength < 0 ) { bool malformed; contentLength = ParseContentLength( line, malformed ); if ( malformed ) { excep.setErrorCode( RCODE_MALFORMED_LINE ); throw excep; } } document += line; // done ? if ( line == "\n" || line == "\r\n" ) { break; } } // must have body for POST and M-POST msgs if ( contentLength < 0 && (cmd == CMD_SOAP_POST || cmd == CMD_SOAP_MPOST) ) { // HTTP: length reqd excep.setErrorCode( RCODE_LENGTH_NOT_SPECIFIED ); throw excep; } if ( contentLength > 0 ) { int totalBytesRead = 0; // read body while ( true ) { int bytesRead; bytesRead = reader.readData( buf, BUFSIZE ); if ( bytesRead > 0 ) { buf[ bytesRead ] = 0; // null terminate string document.appendLimited( buf, bytesRead ); totalBytesRead += bytesRead; if ( totalBytesRead >= contentLength ) { // done reading data break; } } else if ( bytesRead == 0 ) { // done break; } else { // error reading excep.setErrorCode( RCODE_NETWORK_READ_ERROR ); throw excep; } } } command = cmd; } // throws OutOfMemoryException static void HandleError( int errCode, int sockfd ) { xstring errMsg; switch (errCode) { case RCODE_NETWORK_READ_ERROR: break; case RCODE_TIMEDOUT: break; case RCODE_MALFORMED_LINE: errMsg = "400 Bad Request"; break; case RCODE_LENGTH_NOT_SPECIFIED: errMsg = "411 Length Required"; break; case RCODE_METHOD_NOT_ALLOWED: errMsg = "405 Method Not Allowed"; break; case RCODE_INTERNAL_SERVER_ERROR: errMsg = "500 Internal Server Error"; break; case RCODE_METHOD_NOT_IMPLEMENTED: errMsg = "511 Not Implemented"; break; default: DBG( UpnpPrintf( UPNP_CRITICAL, MSERV, __FILE__, __LINE__, "HandleError: unknown code %d\n", errCode ); ) break; }; // no error msg to send; done if ( errMsg.length() == 0 ) return; xstring msg; msg = "HTTP/1.1 "; msg += errMsg; msg += "\r\n\r\n"; // send msg WriteNetData( msg.c_str(), sockfd ); // dbg // sleep so that client does get connection reset //sleep( 3 ); /////// // dbg DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "http error: %s\n", msg.c_str() ); ) /////// } // throws MiniServerReadException.RCODE_METHOD_NOT_IMPLEMENTED static void MultiplexCommand( HTTP_COMMAND_TYPE cmd, const xstring& document, int sockfd ) { MiniServerCallback callback; switch ( cmd ) { case CMD_SOAP_POST: case CMD_SOAP_MPOST: callback = gSoapCallback; break; case CMD_GENA_NOTIFY: case CMD_GENA_SUBSCRIBE: case CMD_GENA_UNSUBSCRIBE: callback = gGenaCallback; break; case CMD_HTTP_GET: callback = gGetCallback; break; default: callback = NULL; } //DBG(printf("READ>>>>>>\n%s\n<<<<<<READ\n", document.c_str())); if ( callback == NULL ) { MiniServerReadException e( "callback not defined or unknown method" ); e.setErrorCode( RCODE_METHOD_NOT_IMPLEMENTED ); throw e; } callback( document.c_str(), sockfd ); } static void HandleRequest( void *args ) { int sockfd; xstring document; HTTP_COMMAND_TYPE cmd; sockfd = (long) args; try { ReadRequest( sockfd, document, cmd ); // pass data to callback MultiplexCommand( cmd, document, sockfd ); //printf( "input document:\n%s\n", document.c_str() ); } catch ( MiniServerReadException& e ) { //DBG( e.print(); ) DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "error code = %d\n", e.getErrorCode()); ) HandleError( e.getErrorCode(), sockfd ); // destroy connection close( sockfd ); } catch ( ... ) { DBG( UpnpPrintf( UPNP_CRITICAL, MSERV, __FILE__, __LINE__, "HandleRequest(): unknown error\n"); ) close( sockfd ); } } static void RunMiniServer( void* args ) { struct sockaddr_in clientAddr; int listenfd; listenfd = (long)args; gMServThread = pthread_self(); gMServState = MSERV_RUNNING; try { while ( true ) { int connectfd; socklen_t clientLen; DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "Waiting...\n" ); ) // get a client request while ( true ) { // stop server if ( gMServState == MSERV_STOPPING ) { throw -9; } connectfd = accept( listenfd, (sockaddr*) &clientAddr, &clientLen ); if ( connectfd > 0 ) { // valid connection break; } if ( connectfd == -1 && errno == EINTR ) { // interrupted -- stop? if ( gMServState == MSERV_STOPPING ) { throw -9; } else { // ignore interruption continue; } } else { xstring errStr = "Error: RunMiniServer: accept(): "; errStr = strerror( errno ); throw BasicException( errStr.c_str() ); } } int sched_stat; sched_stat = tpool_Schedule( HandleRequest, (void*)connectfd ); if ( sched_stat < 0 ) { HandleError( RCODE_INTERNAL_SERVER_ERROR, connectfd ); } //HandleRequest( (void *)connectfd ); } } catch ( GenericException& e ) { //DBG( e.print(); ) } catch ( int code ) { if ( code == -9 ) { // stop miniserver assert( gMServState == MSERV_STOPPING ); DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "Miniserver: recvd STOP signal\n"); ) close( listenfd ); gMServState = MSERV_IDLE; gMServThread = 0; } } } // returns port to which socket, sockfd, is bound. // -1 on error; check errno // > 0 means port number static int get_port( int sockfd ) { sockaddr_in sockinfo; socklen_t len; int code; int port; len = sizeof(sockinfo); code = getsockname( sockfd, (sockaddr*)&sockinfo, &len ); if ( code == -1 ) { return -1; } port = htons( sockinfo.sin_port ); DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "sockfd = %d, .... port = %d\n", sockfd, port ); ) return port; } // if listen port is 0, port is dynamically picked // returns: // on success: actual port socket is bound to // on error: a negative number UPNP_E_XXX int StartMiniServer( unsigned short listen_port ) { struct sockaddr_in serverAddr; int listenfd = 0; int success; int actual_port; int on =1; int retCode = 0; if ( gMServState != MSERV_IDLE ) { return UPNP_E_INTERNAL_ERROR; // miniserver running } try { //printf("listen port: %d\n",listen_port); listenfd = socket( AF_INET, SOCK_STREAM, 0 ); if ( listenfd <= 0 ) { throw UPNP_E_OUTOF_SOCKET; // error creating socket } bzero( &serverAddr, sizeof(serverAddr) ); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = htonl( INADDR_ANY ); serverAddr.sin_port = htons( listen_port ); //THIS IS ALLOWS US TO BIND AGAIN IMMEDIATELY //AFTER OUR SERVER HAS BEEN CLOSED //THIS MAY CAUSE TCP TO BECOME LESS RELIABLE //HOWEVER IT HAS BEEN SUGESTED FOR TCP SERVERS if (setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,&on, sizeof(int))==-1) { throw UPNP_E_SOCKET_BIND; } success = bind( listenfd, (sockaddr*)&serverAddr, sizeof(serverAddr) ); if ( success == -1 ) { throw UPNP_E_SOCKET_BIND; // bind failed } success = listen( listenfd, 10 ); if ( success == -1 ) { throw UPNP_E_LISTEN; // listen failed } actual_port = get_port( listenfd ); if ( actual_port <= 0 ) { throw UPNP_E_INTERNAL_ERROR; } success = tpool_Schedule( RunMiniServer, (void *)listenfd ); if ( success < 0 ) { throw UPNP_E_OUTOF_MEMORY; } // wait for miniserver to start while ( gMServState != MSERV_RUNNING ) { sleep(1); } retCode = actual_port; } catch ( int catchCode ) { retCode = catchCode; if ( listenfd != 0 ) { close( listenfd ); } } return retCode; } // returns 0: success; -2 if miniserver is idle int StopMiniServer( void ) { if ( gMServState == MSERV_IDLE ) return -2; gMServState = MSERV_STOPPING; // keep sending signals until server stops while ( true ) { if ( gMServState == MSERV_IDLE ) { break; } DBG( UpnpPrintf( UPNP_INFO, MSERV, __FILE__, __LINE__, "StopMiniServer(): sending interrupt\n"); ) int code = tintr_Interrupt( gMServThread ); if ( code < 0 ) { DBG( UpnpPrintf( UPNP_CRITICAL, MSERV, __FILE__, __LINE__, "%s: StopMiniServer(): interrupt failed", strerror(errno) ); ) //DBG( perror("StopMiniServer(): interrupt failed"); ) } if ( gMServState == MSERV_IDLE ) { break; } sleep( 1 ); // pause before signalling again } return 0; } #endif
23.398321
95
0.516047
972b970c9e6a636bf21a733fb3226f50233e9573
4,163
hpp
C++
sdk/boost_1_30_0/boost/integer/static_log2.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
sdk/boost_1_30_0/boost/integer/static_log2.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/boost_1_30_0/boost/integer/static_log2.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Boost integer/static_log2.hpp header file -------------------------------// // (C) Copyright Daryle Walker 2001. Permission to copy, use, modify, sell and // distribute this software is granted provided this copyright notice appears // in all copies. This software is provided "as is" without express or // implied warranty, and with no claim as to its suitability for any purpose. // See http://www.boost.org for updates, documentation, and revision history. #ifndef BOOST_INTEGER_STATIC_LOG2_HPP #define BOOST_INTEGER_STATIC_LOG2_HPP #include <boost/integer_fwd.hpp> // self include #include <boost/config.hpp> // for BOOST_STATIC_CONSTANT, etc. #include <boost/limits.hpp> // for std::numeric_limits #ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #include <boost/pending/ct_if.hpp> // for boost::ct_if<> #endif namespace boost { // Implementation details --------------------------------------------------// namespace detail { // Forward declarations template < unsigned long Val, int Place = 0, int Index = std::numeric_limits<unsigned long>::digits > struct static_log2_helper_t; #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template < unsigned long Val, int Place > struct static_log2_helper_t< Val, Place, 1 >; #else template < int Place > struct static_log2_helper_final_step; template < unsigned long Val, int Place = 0, int Index = std::numeric_limits<unsigned long>::digits > struct static_log2_helper_nopts_t; #endif // Recursively build the logarithm by examining the upper bits template < unsigned long Val, int Place, int Index > struct static_log2_helper_t { private: BOOST_STATIC_CONSTANT( int, half_place = Index / 2 ); BOOST_STATIC_CONSTANT( unsigned long, lower_mask = (1ul << half_place) - 1ul ); BOOST_STATIC_CONSTANT( unsigned long, upper_mask = ~lower_mask ); BOOST_STATIC_CONSTANT( bool, do_shift = (Val & upper_mask) != 0ul ); BOOST_STATIC_CONSTANT( unsigned long, new_val = do_shift ? (Val >> half_place) : Val ); BOOST_STATIC_CONSTANT( int, new_place = do_shift ? (Place + half_place) : Place ); BOOST_STATIC_CONSTANT( int, new_index = Index - half_place ); #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION typedef static_log2_helper_t<new_val, new_place, new_index> next_step_type; #else typedef static_log2_helper_nopts_t<new_val, new_place, new_index> next_step_type; #endif public: BOOST_STATIC_CONSTANT( int, value = next_step_type::value ); }; // boost::detail::static_log2_helper_t // Non-recursive case #ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template < unsigned long Val, int Place > struct static_log2_helper_t< Val, Place, 1 > { public: BOOST_STATIC_CONSTANT( int, value = Place ); }; // boost::detail::static_log2_helper_t #else template < int Place > struct static_log2_helper_final_step { public: BOOST_STATIC_CONSTANT( int, value = Place ); }; // boost::detail::static_log2_helper_final_step template < unsigned long Val, int Place, int Index > struct static_log2_helper_nopts_t { private: typedef static_log2_helper_t<Val, Place, Index> recursive_step_type; typedef static_log2_helper_final_step<Place> final_step_type; typedef typename ct_if<( Index != 1 ), recursive_step_type, final_step_type>::type next_step_type; public: BOOST_STATIC_CONSTANT( int, value = next_step_type::value ); }; // boost::detail::static_log2_helper_nopts_t #endif } // namespace detail // Compile-time log-base-2 evaluator class declaration ---------------------// template < unsigned long Value > struct static_log2 { BOOST_STATIC_CONSTANT( int, value = detail::static_log2_helper_t<Value>::value ); }; template < > struct static_log2< 0ul > { // The logarithm of zero is undefined. }; } // namespace boost #endif // BOOST_INTEGER_STATIC_LOG2_HPP
29.316901
88
0.675715
972c55857ab2a64081bc3d0b601fdc8136a6e8de
2,845
cpp
C++
external/openglcts/modules/glesext/draw_buffers_indexed/esextcDrawBuffersIndexedTests.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
external/openglcts/modules/glesext/draw_buffers_indexed/esextcDrawBuffersIndexedTests.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
external/openglcts/modules/glesext/draw_buffers_indexed/esextcDrawBuffersIndexedTests.cpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2015-2016 The Khronos Group Inc. * * 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. * */ /*! * \file * \brief */ /*-------------------------------------------------------------------*/ /*! * \file esextcDrawBuffersIndexedTests.cpp * \brief Test group for Draw Buffers Indexed tests */ /*-------------------------------------------------------------------*/ #include "esextcDrawBuffersIndexedTests.hpp" #include "esextcDrawBuffersIndexedBlending.hpp" #include "esextcDrawBuffersIndexedColorMasks.hpp" #include "esextcDrawBuffersIndexedCoverage.hpp" #include "esextcDrawBuffersIndexedDefaultState.hpp" #include "esextcDrawBuffersIndexedNegative.hpp" #include "esextcDrawBuffersIndexedSetGet.hpp" #include "glwEnums.hpp" namespace glcts { /** Constructor * * @param context Test context * @param glslVersion GLSL version **/ DrawBuffersIndexedTests::DrawBuffersIndexedTests(glcts::Context& context, const ExtParameters& extParams) : TestCaseGroupBase(context, extParams, "draw_buffers_indexed", "Draw Buffers Indexed Tests") { /* No implementation needed */ } /** Initializes test cases for Draw Buffers Indexed tests **/ void DrawBuffersIndexedTests::init(void) { /* Initialize base class */ TestCaseGroupBase::init(); /* Draw Buffers Indexed - 1. Coverage */ addChild(new DrawBuffersIndexedCoverage(m_context, m_extParams, "coverage", "Basic coverage test")); /* Draw Buffers Indexed - 2. Default state */ addChild( new DrawBuffersIndexedDefaultState(m_context, m_extParams, "default_state", "Default state verification test")); /* Draw Buffers Indexed - 3. Set and get */ addChild(new DrawBuffersIndexedSetGet(m_context, m_extParams, "set_get", "Setting and getting state test")); /* Draw Buffers Indexed - 4. Color masks */ addChild(new DrawBuffersIndexedColorMasks(m_context, m_extParams, "color_masks", "Masking color test")); /* Draw Buffers Indexed - 5. Blending */ addChild(new DrawBuffersIndexedBlending(m_context, m_extParams, "blending", "Blending test")); /* Draw Buffers Indexed - 6. Negative */ addChild(new DrawBuffersIndexedNegative(m_context, m_extParams, "negative", "Negative test")); } } // namespace glcts
36.012658
114
0.687873
972e40c3e8102a66fd486836e97db36718a93fd6
1,287
cpp
C++
ProducerConsumer/worker.cpp
bloodMaster/ProducerConsumer
934130b029bff0ce0f314ca65a76f8cbf9b879df
[ "MIT" ]
null
null
null
ProducerConsumer/worker.cpp
bloodMaster/ProducerConsumer
934130b029bff0ce0f314ca65a76f8cbf9b879df
[ "MIT" ]
null
null
null
ProducerConsumer/worker.cpp
bloodMaster/ProducerConsumer
934130b029bff0ce0f314ca65a76f8cbf9b879df
[ "MIT" ]
null
null
null
#include "worker.hpp" #include <iostream> #include <random> std::mutex s_mutex; std::atomic<int> Worker::s_numOfActiveProducers; std::atomic<bool> Worker::s_shouldWork = true; Worker::DataContainer Worker::s_dataContainer; const unsigned int Worker::s_maxSizeOfQueue = 100; const unsigned int Worker::s_allowedSizeForProduction = 80; std::mutex Worker::s_mutex; std::condition_variable Worker::s_producers; std::condition_variable Worker::s_consumers; void Worker:: signalHandler(int sigNum) { s_shouldWork = false; } void Worker:: start() { m_thread = std::thread(&Worker::work, this); } void Worker:: join() { m_thread.join(); } int Worker:: randNumber(int lowerBound, int upperBound) { static thread_local std::mt19937 gen; std::uniform_int_distribution<int> d(lowerBound, upperBound); return d(gen); } void Worker:: sleep() { std::this_thread::sleep_for(std::chrono::milliseconds(randNumber(0, 100))); } void Logger:: work() { while (s_shouldWork || 0 != s_numOfActiveProducers) { log(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } void Logger:: log() { std::unique_lock<std::mutex> uniqueLock(s_mutex); std::cout << "Num of elements: " << s_dataContainer.size() << "\n"; }
19.208955
77
0.685315
97314d6ac911c17d6d79f8ee95e6d033767e7c29
73,926
cpp
C++
httpendpoints.cpp
qbit-t/qb
c1fd82df3838f8526fc5e335254529ab6f953f78
[ "MIT" ]
1
2021-02-14T04:04:50.000Z
2021-02-14T04:04:50.000Z
httpendpoints.cpp
qbit-t/qb
c1fd82df3838f8526fc5e335254529ab6f953f78
[ "MIT" ]
null
null
null
httpendpoints.cpp
qbit-t/qb
c1fd82df3838f8526fc5e335254529ab6f953f78
[ "MIT" ]
1
2021-08-28T07:42:43.000Z
2021-08-28T07:42:43.000Z
#include "httprequesthandler.h" #include "httpreply.h" #include "httprequest.h" #include "log/log.h" #include "json.h" #include "tinyformat.h" #include "httpendpoints.h" #include "vm/vm.h" #include <iostream> using namespace qbit; void HttpMallocStats::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "mallocstats", "params": [ "<thread_id>", -- (string, optional) thread id "<class_index>", -- (string, optional) class to dump "<path>" -- (string, required if class provided) path to dump to ] } */ /* reply { "result": { "table": [] -- (string array) details }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters if (lParams.size() <= 1) { // param[0] size_t lThreadId = 0; // 0 if (lParams.size() == 1) { json::Value lP0 = lParams[0]; if (lP0.isString()) { if (!convert<size_t>(lP0.getString(), lThreadId)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } char lStats[204800] = {0}; #if defined(JM_MALLOC) if (!lThreadId) { _jm_threads_print_stats(lStats); } else { _jm_thread_print_stats(lThreadId, lStats, JM_ARENA_BASIC_STATS /*| JM_ARENA_CHUNK_STATS | JM_ARENA_DIRTY_BLOCKS_STATS | JM_ARENA_FREEE_BLOCKS_STATS*/, JM_ALLOC_CLASSES); } #endif std::string lValue(lStats); std::vector<std::string> lParts; boost::split(lParts, lValue, boost::is_any_of("\n\t"), boost::token_compress_on); // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); json::Value lKeyArrayObject = lKeyObject.addArray("table"); for (std::vector<std::string>::iterator lString = lParts.begin(); lString != lParts.end(); lString++) { json::Value lItem = lKeyArrayObject.newArrayItem(); lItem.setString(*lString); } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { // param[0] size_t lThreadId = 0; // 0 json::Value lP0 = lParams[0]; if (lP0.isString()) { if (!convert<size_t>(lP0.getString(), lThreadId)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] int lClassIndex = 0; // 1 json::Value lP1 = lParams[1]; if (lP0.isString()) { if (!convert<int>(lP1.getString(), lClassIndex)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] std::string lPath; // 2 json::Value lP2 = lParams[2]; if (lP2.isString()) { lPath = lP2.getString(); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // #if defined(JM_MALLOC) _jm_thread_dump_chunk(lThreadId, 0, lClassIndex, (char*)lPath.c_str()); #endif // prepare reply json::Document lReply; lReply.loadFromString("{}"); lReply.addString("result", "ok"); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetKey::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getkey", "params": [ "<address_id>" -- (string, optional) address ] } */ /* reply { "result": -- (object) address details { "address": "<address>", -- (string) address, base58 encoded "pkey": "<public_key>", -- (string) public key, hex encoded "skey": "<secret_key>", -- (string) secret key, hex encoded "seed": [] -- (string array) seed words }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lAddress; // 0 if (lParams.size()) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } // process SKeyPtr lKey; if (lAddress.size()) { PKey lPKey; if (!lPKey.fromString(lAddress)) { reply = HttpReply::stockReply("E_PKEY_INVALID", "Public key is invalid"); return; } lKey = wallet_->findKey(lPKey); if (!lKey || !lKey->valid()) { reply = HttpReply::stockReply("E_SKEY_NOT_FOUND", "Key was not found"); return; } } else { lKey = wallet_->firstKey(); if (!lKey->valid()) { reply = HttpReply::stockReply("E_SKEY_IS_ABSENT", "Key is absent"); return; } } PKey lPFoundKey = lKey->createPKey(); // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); lKeyObject.addString("address", lPFoundKey.toString()); lKeyObject.addString("pkey", lPFoundKey.toHex()); lKeyObject.addString("skey", lKey->toHex()); json::Value lKeyArrayObject = lKeyObject.addArray("seed"); for (std::vector<SKey::Word>::iterator lWord = lKey->seed().begin(); lWord != lKey->seed().end(); lWord++) { json::Value lItem = lKeyArrayObject.newArrayItem(); lItem.setString((*lWord).wordA()); } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpNewKey::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "newkey", "params": [ ... ] } */ /* reply { "result": -- (object) address details { "address": "<address>", -- (string) address, base58 encoded "pkey": "<public_key>", -- (string) public key, hex encoded "skey": "<secret_key>", -- (string) secret key, hex encoded "seed": [] -- (string array) seed words }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // std::list<std::string> lSeedWords; if (lParams.size()) { // param[0] for (int lIdx = 0; lIdx < lParams.size(); lIdx++) { // json::Value lP0 = lParams[lIdx]; if (lP0.isString()) lSeedWords.push_back(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } } // process SKeyPtr lKey = wallet_->createKey(lSeedWords); if (!lKey->valid()) { reply = HttpReply::stockReply("E_SKEY_IS_INVALID", "Key is invalid"); return; } PKey lPFoundKey = lKey->createPKey(); // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); lKeyObject.addString("address", lPFoundKey.toString()); lKeyObject.addString("pkey", lPFoundKey.toHex()); lKeyObject.addString("skey", lKey->toHex()); json::Value lKeyArrayObject = lKeyObject.addArray("seed"); for (std::vector<SKey::Word>::iterator lWord = lKey->seed().begin(); lWord != lKey->seed().end(); lWord++) { json::Value lItem = lKeyArrayObject.newArrayItem(); lItem.setString((*lWord).wordA()); } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBalance::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getbalance", "params": [ "<asset_id>" -- (string, optional) asset ] } */ /* reply { "result": "1.0", -- (string) corresponding asset balance "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lAsset; // 0 if (lParams.size()) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAsset.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } // process amount_t lScale = QBIT; if (!lAsset.isNull() && lAsset != TxAssetType::qbitAsset()) { // locate asset type EntityPtr lAssetEntity = wallet_->persistentStore()->entityStore()->locateEntity(lAsset); if (lAssetEntity && lAssetEntity->type() == Transaction::ASSET_TYPE) { TxAssetTypePtr lAssetType = TransactionHelper::to<TxAssetType>(lAssetEntity); lScale = lAssetType->scale(); } else { reply = HttpReply::stockReply("E_ASSET", "Asset type was not found"); return; } } // process double lBalance = 0.0; double lPendingBalance = 0.0; IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // main chain only IConsensus::ChainState lState = lMempool->consensus()->chainState(); if (lState == IConsensus::SYNCHRONIZED) { if (!lAsset.isNull()) { amount_t lPending = 0, lActual = 0; wallet_->balance(lAsset, lPending, lActual); lPendingBalance = ((double)lPending) / lScale; lBalance = ((double)lActual) / lScale; } else { amount_t lPending = 0, lActual = 0; wallet_->balance(TxAssetType::qbitAsset(), lPending, lActual); lPendingBalance = ((double)wallet_->pendingBalance()) / lScale; lBalance = ((double)wallet_->balance()) / lScale; } } else if (lState == IConsensus::SYNCHRONIZING) { reply = HttpReply::stockReply("E_NODE_SYNCHRONIZING", "Synchronization is in progress..."); return; } else { reply = HttpReply::stockReply("E_NODE_NOT_SYNCHRONIZED", "Not synchronized"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); lKeyObject.addString("available", strprintf(TxAssetType::scaleFormat(lScale), lBalance)); if (lPendingBalance > lBalance) lKeyObject.addString("pending", strprintf(TxAssetType::scaleFormat(lScale), lPendingBalance-lBalance)); else lKeyObject.addString("pending", strprintf(TxAssetType::scaleFormat(lScale), 0)); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpSendToAddress::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "sendtoaddress", "params": [ "<asset_id>", -- (string) asset or "*" "<address>", -- (string) address "0.1" -- (string) amount ] } */ /* reply { "result": "<tx_id>", -- (string) txid "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lAssetString; // 0 PKey lAddress; // 1 double lValue; // 2 if (lParams.size() == 3) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAssetString = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lAddress.fromString(lP1.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) { if (!convert<double>(lP2.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } uint256 lAsset; if (lAssetString == "*") lAsset = TxAssetType::qbitAsset(); else lAsset.setHex(lAssetString); // locate scale amount_t lScale = QBIT; if (!lAsset.isNull() && lAsset != TxAssetType::qbitAsset()) { // locate asset type EntityPtr lAssetEntity = wallet_->persistentStore()->entityStore()->locateEntity(lAsset); if (lAssetEntity && lAssetEntity->type() == Transaction::ASSET_TYPE) { TxAssetTypePtr lAssetType = TransactionHelper::to<TxAssetType>(lAssetEntity); lScale = lAssetType->scale(); } else { reply = HttpReply::stockReply("E_ASSET", "Asset type was not found"); return; } } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxSpend(lAsset, lAddress, (amount_t)(lValue * (double)lScale)); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_SPEND", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // all spend txs - to the main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } // we good if (lCtx) { // find and broadcast for active clients peerManager_->notifyTransaction(lCtx); } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetPeerInfo::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getpeerinfo", "params": [] } */ /* reply { "result": { "peers": [ { "id": "<peer_id>", -- (string) peer default address id (uint160) "endpoint": "address:port", -- (string) peer endpoint "outbound": true|false, -- (bool) is outbound connection "roles": "<peer_roles>", -- (string) peer roles "status": "<peer_status>", -- (string) peer status "latency": <latency>, -- (int) latency, ms "time": "<peer_time>", -- (string) peer_time, s "chains": [ { "id": "<chain_id>", -- (string) chain id ... } ] }, ... ], }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); json::Value lArrayObject = lKeyObject.addArray("peers"); // get peers std::list<IPeerPtr> lPeers; peerManager_->allPeers(lPeers); // peer manager json::Value lPeerManagerObject = lReply.addObject("manager"); lPeerManagerObject.addUInt("clients", peerManager_->clients()); lPeerManagerObject.addUInt("peers_count", lPeers.size()); for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) { // if ((*lPeer)->status() == IPeer::UNDEFINED) continue; json::Value lItem = lArrayObject.newArrayItem(); lItem.toObject(); // make object if ((*lPeer)->status() == IPeer::BANNED || (*lPeer)->status() == IPeer::POSTPONED) { lItem.addString("endpoint", (*lPeer)->key()); lItem.addString("status", (*lPeer)->statusString()); lItem.addUInt("in_queue", (*lPeer)->inQueueLength()); lItem.addUInt("out_queue", (*lPeer)->outQueueLength()); lItem.addUInt("pending_queue", (*lPeer)->pendingQueueLength()); lItem.addUInt("received_count", (*lPeer)->receivedMessagesCount()); lItem.addUInt64("received_bytes", (*lPeer)->bytesReceived()); lItem.addUInt("sent_count", (*lPeer)->sentMessagesCount()); lItem.addUInt64("sent_bytes", (*lPeer)->bytesSent()); continue; } lItem.addString("id", (*lPeer)->addressId().toHex()); lItem.addString("endpoint", (*lPeer)->key()); lItem.addString("status", (*lPeer)->statusString()); lItem.addUInt64("time", (*lPeer)->time()); lItem.addBool("outbound", (*lPeer)->isOutbound() ? true : false); lItem.addUInt("latency", (*lPeer)->latency()); lItem.addString("roles", (*lPeer)->state()->rolesString()); if ((*lPeer)->state()->address().valid()) lItem.addString("address", (*lPeer)->state()->address().toString()); lItem.addUInt("in_queue", (*lPeer)->inQueueLength()); lItem.addUInt("out_queue", (*lPeer)->outQueueLength()); lItem.addUInt("pending_queue", (*lPeer)->pendingQueueLength()); lItem.addUInt("received_count", (*lPeer)->receivedMessagesCount()); lItem.addUInt64("received_bytes", (*lPeer)->bytesReceived()); lItem.addUInt("sent_count", (*lPeer)->sentMessagesCount()); lItem.addUInt64("sent_bytes", (*lPeer)->bytesSent()); if ((*lPeer)->state()->client()) { // json::Value lDAppsArray = lItem.addArray("dapps"); for(std::vector<State::DAppInstance>::const_iterator lInstance = (*lPeer)->state()->dApps().begin(); lInstance != (*lPeer)->state()->dApps().end(); lInstance++) { json::Value lDApp = lDAppsArray.newArrayItem(); lDApp.addString("name", lInstance->name()); lDApp.addString("instance", lInstance->instance().toHex()); } } else { // json::Value lChainsObject = lItem.addArray("chains"); std::vector<State::BlockInfo> lInfos = (*lPeer)->state()->infos(); for (std::vector<State::BlockInfo>::iterator lInfo = lInfos.begin(); lInfo != lInfos.end(); lInfo++) { // json::Value lChain = lChainsObject.newArrayItem(); lChain.toObject(); // make object lChain.addString("dapp", lInfo->dApp().size() ? lInfo->dApp() : "none"); lChain.addUInt64("height", lInfo->height()); lChain.addString("chain", lInfo->chain().toHex()); lChain.addString("block", lInfo->hash().toHex()); } } } //lReply.addString("result", strprintf(QBIT_FORMAT, lBalance)); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateDApp::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createdapp", "params": [ "<address>", -- (string) owners' address "<short_name>", -- (string) dapp short name, should be unique "<description>", -- (string) dapp description "<instances_tx>", -- (short) dapp instances tx types (transaction::type) "<sharding>" -- (string, optional) static|dynamic, default = 'static' ] } */ /* reply { "result": "<tx_dapp_id>", -- (string) txid = dapp_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 std::string lShortName; // 1 std::string lDescription; // 2 Transaction::Type lInstances; // 3 std::string lSharding = "static"; // 4 if (lParams.size() == 4 || lParams.size() == 5) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lShortName = lP1.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) lDescription = lP2.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[3] json::Value lP3 = lParams[3]; if (lP3.isString()) { unsigned short lValue; if (!convert<unsigned short>(lP3.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lInstances = (Transaction::Type)lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[4] if (lParams.size() == 5) { json::Value lP4 = lParams[4]; if (lP4.isString()) lSharding = lP4.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxDApp(lAddress, lShortName, lDescription, (lSharding == "static" ? TxDApp::STATIC : TxDApp::DYNAMIC), lInstances); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_DAPP", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateShard::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createshard", "params": [ "<address>", -- (string) creators' address (not owner) "<dapp_name>", -- (string) dapp name "<short_name>", -- (string) shard short name, should be unique "<description>" -- (string) shard description ] } */ /* reply { "result": "<tx_shard_id>", -- (string) txid = shard_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 std::string lDAppName; // 1 std::string lShortName; // 2 std::string lDescription; // 3 if (lParams.size() == 4) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lDAppName = lP1.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) lShortName = lP2.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[3] json::Value lP3 = lParams[3]; if (lP3.isString()) lDescription = lP3.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxShard(lAddress, lDAppName, lShortName, lDescription); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_SHARD", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetTransaction::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "gettransaction", "params": [ "<tx_id>" -- (string) tx hash (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) tx hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "type": "<tx_type>", -- (string) tx type: COINBASE, SPEND, SPEND_PRIVATE & etc. "version": <version>, -- (int) version (0-256) "timelock: <lock_time>, -- (int64) lock time (future block) "block": "<block_id>", -- (string) block hash (id), optional "height": <height>, -- (int64) block height, optional "index": <index>, -- (int) tx block index "mempool": false|true, -- (bool) mempool presence, optional "properties": { ... -- (object) tx type-specific properties }, "in": [ { "chain": "<chain_id>", -- (string) source chain/shard hash (id) "asset": "<asset_id>", -- (string) source asset hash (id) "tx": "<tx_id>", -- (string) source tx hash (id) "index": <index>, -- (int) source tx out index "ownership": { "raw": "<hex>", -- (string) ownership script (hex) "qasm": [ -- (array, string) ownership script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ], "out": [ { "asset": "<asset_id>", -- (string) destination asset hash (id) "destination": { "raw": "<hex>", -- (string) destination script (hex) "qasm": [ -- (array, string) destination script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lTxId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lTxId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process TransactionPtr lTx; std::string lCode, lMessage; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager(); if (lStoreManager && lMempoolManager) { // uint256 lBlock; uint64_t lHeight = 0; uint64_t lConfirms = 0; uint32_t lIndex = 0; bool lCoinbase = false; bool lMempool = false; std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages(); for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) { lTx = (*lStore)->locateTransaction(lTxId); if (lTx && (*lStore)->transactionInfo(lTxId, lBlock, lHeight, lConfirms, lIndex, lCoinbase)) { break; } } // try mempool if (!lTx) { std::vector<IMemoryPoolPtr> lMempools = lMempoolManager->pools(); for (std::vector<IMemoryPoolPtr>::iterator lPool = lMempools.begin(); lPool != lMempools.end(); lPool++) { lTx = (*lPool)->locateTransaction(lTxId); if (lTx) { lMempool = true; break; } } } if (lTx) { // if (!unpackTransaction(lTx, lBlock, lHeight, lConfirms, lIndex, lCoinbase, lMempool, lReply, reply)) return; } else { reply = HttpReply::stockReply("E_TX_NOT_FOUND", "Transaction not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Transactions store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetEntity::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getentity", "params": [ "<entity_name>" -- (string) entity name ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) tx hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "type": "<tx_type>", -- (string) tx type: COINBASE, SPEND, SPEND_PRIVATE & etc. "version": <version>, -- (int) version (0-256) "timelock: <lock_time>, -- (int64) lock time (future block) "block": "<block_id>", -- (string) block hash (id), optional "height": <height>, -- (int64) block height, optional "index": <index>, -- (int) tx block index "mempool": false|true, -- (bool) mempool presence, optional "properties": { ... -- (object) tx type-specific properties }, "in": [ { "chain": "<chain_id>", -- (string) source chain/shard hash (id) "asset": "<asset_id>", -- (string) source asset hash (id) "tx": "<tx_id>", -- (string) source tx hash (id) "index": <index>, -- (int) source tx out index "ownership": { "raw": "<hex>", -- (string) ownership script (hex) "qasm": [ -- (array, string) ownership script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ], "out": [ { "asset": "<asset_id>", -- (string) destination asset hash (id) "destination": { "raw": "<hex>", -- (string) destination script (hex) "qasm": [ -- (array, string) destination script disassembly "<qasm> <p0>, ... <pn>", ... ] } } ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lName; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lName = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process TransactionPtr lTx; std::string lCode, lMessage; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager(); if (lStoreManager && lMempoolManager) { // uint256 lBlock; uint64_t lHeight = 0; uint64_t lConfirms = 0; uint32_t lIndex = 0; bool lCoinbase = false; bool lMempool = false; ITransactionStorePtr lStorage = lStoreManager->locate(MainChain::id()); EntityPtr lTx = lStorage->entityStore()->locateEntity(lName); // try mempool if (!lTx) { IMemoryPoolPtr lMainpool = lMempoolManager->locate(MainChain::id()); lTx = lMainpool->locateEntity(lName); if (lTx) { lMempool = true; } } else { lStorage->transactionInfo(lTx->id(), lBlock, lHeight, lConfirms, lIndex, lCoinbase); } if (lTx) { // if (!unpackTransaction(lTx, lBlock, lHeight, lConfirms, lIndex, lCoinbase, lMempool, lReply, reply)) return; } else { reply = HttpReply::stockReply("E_TX_NOT_FOUND", "Transaction not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Transactions store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBlock::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getblock", "params": [ "<block_id>" -- (string) block hash (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) block hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "height": <height>, -- (int64) block height "version": <version>, -- (int) version (0-256) "time: <time>, -- (int64) block time "prev": "<prev_id>", -- (string) prev block hash (id) "root": "<merkle_root_hash>", -- (string) merkle root hash "origin": "<miner_id>", -- (string) miner address id "bits": <pow_bits>, -- (int) pow bits "nonce": <nonce_counter>, -- (int) found nonce "pow": [ <int>, <int> ... <int> -- (aray) found pow cycle ], "transactions": [ { "id": "<tx_id>", -- (string) tx hash (id) "size": "<size>" -- (int) tx size } ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lBlockId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lBlockId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process BlockPtr lBlock; std::string lCode, lMessage; // height uint64_t lHeight = 0; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); if (lStoreManager) { // std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages(); for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) { lBlock = (*lStore)->block(lBlockId); if (lBlock) { (*lStore)->blockHeight(lBlockId, lHeight); break; } } if (lBlock) { // json::Value lRootObject = lReply.addObject("result"); lRootObject.addString("id", lBlock->hash().toHex()); lRootObject.addString("chain", lBlock->chain().toHex()); lRootObject.addUInt64("height", lHeight); lRootObject.addInt("version", lBlock->version()); lRootObject.addUInt64("time", lBlock->time()); lRootObject.addString("prev", lBlock->prev().toHex()); lRootObject.addString("root", lBlock->root().toHex()); lRootObject.addString("origin", lBlock->origin().toHex()); lRootObject.addInt("bits", lBlock->bits()); lRootObject.addInt("nonce", lBlock->nonce()); json::Value lPowObject = lRootObject.addArray("pow"); int lIdx = 0; for (std::vector<uint32_t>::iterator lNumber = lBlock->cycle_.begin(); lNumber != lBlock->cycle_.end(); lNumber++, lIdx++) { // json::Value lItem = lPowObject.newArrayItem(); //lItem.toObject(); //lItem.addInt("index", lIdx); //lItem.addUInt("number", *lNumber); lItem.setUInt(*lNumber); } json::Value lTransactionsObject = lRootObject.addArray("transactions"); BlockTransactionsPtr lTransactions = lBlock->blockTransactions(); for (std::vector<TransactionPtr>::iterator lTransaction = lTransactions->transactions().begin(); lTransaction != lTransactions->transactions().end(); lTransaction++) { // json::Value lItem = lTransactionsObject.newArrayItem(); lItem.toObject(); TransactionContextPtr lCtx = TransactionContext::instance(*lTransaction); lItem.addString("id", lCtx->tx()->id().toHex()); lItem.addUInt("size", lCtx->size()); } } else { reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBlockHeader::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getblock", "params": [ "<block_id>" -- (string) block hash (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) block hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "height": <height>, -- (int64) block height "version": <version>, -- (int) version (0-256) "time: <time>, -- (int64) block time "prev": "<prev_id>", -- (string) prev block hash (id) "root": "<merkle_root_hash>", -- (string) merkle root hash "origin": "<miner_id>", -- (string) miner address id "bits": <pow_bits>, -- (int) pow bits "nonce": <nonce_counter>, -- (int) found nonce "pow": [ <int>, <int> ... <int> -- (aray) found pow cycle ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lBlockId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lBlockId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process BlockPtr lBlock; std::string lCode, lMessage; // height uint64_t lHeight = 0; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); if (lStoreManager) { // std::vector<ITransactionStorePtr> lStorages = lStoreManager->storages(); for (std::vector<ITransactionStorePtr>::iterator lStore = lStorages.begin(); lStore != lStorages.end(); lStore++) { lBlock = (*lStore)->block(lBlockId); if (lBlock) { (*lStore)->blockHeight(lBlockId, lHeight); break; } } if (lBlock) { // json::Value lRootObject = lReply.addObject("result"); lRootObject.addString("id", lBlock->hash().toHex()); lRootObject.addString("chain", lBlock->chain().toHex()); lRootObject.addUInt64("height", lHeight); lRootObject.addInt("version", lBlock->version()); lRootObject.addUInt64("time", lBlock->time()); lRootObject.addString("prev", lBlock->prev().toHex()); lRootObject.addString("root", lBlock->root().toHex()); lRootObject.addString("origin", lBlock->origin().toHex()); lRootObject.addInt("bits", lBlock->bits()); lRootObject.addInt("nonce", lBlock->nonce()); json::Value lPowObject = lRootObject.addArray("pow"); int lIdx = 0; for (std::vector<uint32_t>::iterator lNumber = lBlock->cycle_.begin(); lNumber != lBlock->cycle_.end(); lNumber++, lIdx++) { // json::Value lItem = lPowObject.newArrayItem(); //lItem.toObject(); //lItem.addInt("index", lIdx); //lItem.addUInt("number", *lNumber); lItem.setUInt(*lNumber); } } else { reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block not found"); return; } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetBlockHeaderByHeight::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getblockheaderbyheight", "params": [ "<chain_id>" -- (string) chain (id) "<block_height>" -- (string) block height (id) ] } */ /* reply { "result": { "id": "<tx_id>", -- (string) block hash (id) "chain": "<chain_id>", -- (string) chain / shard hash (id) "height": <height>, -- (int64) block height "version": <version>, -- (int) version (0-256) "time: <time>, -- (int64) block time "prev": "<prev_id>", -- (string) prev block hash (id) "root": "<merkle_root_hash>", -- (string) merkle root hash "origin": "<miner_id>", -- (string) miner address id "bits": <pow_bits>, -- (int) pow bits "nonce": <nonce_counter>, -- (int) found nonce "pow": [ <int>, <int> ... <int> -- (aray) found pow cycle ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lChainId; // 0 uint64_t lBlockHeight = 0; // 1 if (lParams.size() == 2) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lChainId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (!convert<uint64_t>(lP1.getString(), lBlockHeight)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process BlockPtr lBlock; std::string lCode, lMessage; // try to lookup transaction ITransactionStoreManagerPtr lStoreManager = wallet_->storeManager(); if (lStoreManager) { // ITransactionStorePtr lStore = lStoreManager->locate(lChainId); if (!lStore) { reply = HttpReply::stockReply("E_STORE_NOT_FOUND", "Storage not found"); return; } BlockHeader lHeader; if (!lStore->blockHeader(lBlockHeight, lHeader)) { reply = HttpReply::stockReply("E_BLOCK_NOT_FOUND", "Block was not found"); return; } // json::Value lRootObject = lReply.addObject("result"); lRootObject.addString("id", lHeader.hash().toHex()); lRootObject.addString("chain", lHeader.chain().toHex()); lRootObject.addUInt64("height", lBlockHeight); lRootObject.addInt("version", lHeader.version()); lRootObject.addUInt64("time", lHeader.time()); lRootObject.addString("prev", lHeader.prev().toHex()); lRootObject.addString("root", lHeader.root().toHex()); lRootObject.addString("origin", lHeader.origin().toHex()); lRootObject.addInt("bits", lHeader.bits()); lRootObject.addInt("nonce", lHeader.nonce()); json::Value lPowObject = lRootObject.addArray("pow"); int lIdx = 0; for (std::vector<uint32_t>::iterator lNumber = lHeader.cycle_.begin(); lNumber != lHeader.cycle_.end(); lNumber++, lIdx++) { // json::Value lItem = lPowObject.newArrayItem(); //lItem.toObject(); //lItem.addInt("index", lIdx); //lItem.addUInt("number", *lNumber); lItem.setUInt(*lNumber); } } else { reply = HttpReply::stockReply("E_STOREMANAGER", "Store manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateAsset::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createasset", "params": [ "<address>", -- (string) owners' address "<short_name>", -- (string) asset short name, should be unique "<description>", -- (string) asset description "<chunk>", -- (long) asset single chunk "<scale>", -- (long) asset unit scale "<chunks>", -- (long) asset unspend chunks "<type>" -- (string, optional) asset type: limited, unlimited, pegged ] } */ /* reply { "result": "<tx_asset_id>", -- (string) txid = asset_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 std::string lShortName; // 1 std::string lDescription; // 2 amount_t lChunk; // 3 amount_t lScale; // 4 amount_t lChunks; // 5 std::string lType = "limited"; // 6 if (lParams.size() == 6 || lParams.size() == 7) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lShortName = lP1.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[2] json::Value lP2 = lParams[2]; if (lP2.isString()) lDescription = lP2.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[3] json::Value lP3 = lParams[3]; if (lP3.isString()) { amount_t lValue; if (!convert<amount_t>(lP3.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lChunk = lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[4] json::Value lP4 = lParams[4]; if (lP4.isString()) { amount_t lValue; if (!convert<amount_t>(lP4.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lScale = lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[5] json::Value lP5 = lParams[5]; if (lP5.isString()) { amount_t lValue; if (!convert<amount_t>(lP5.getString(), lValue)) { reply = HttpReply::stockReply("E_INCORRECT_VALUE_TYPE", "Incorrect parameter type"); return; } lChunks = lValue; } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[6] if (lParams.size() == 7) { json::Value lP6 = lParams[6]; if (lP6.isString()) lType = lP6.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxAssetType(lAddress, lShortName, lDescription, lChunk, lScale, lChunks, (lType == "limited" ? TxAssetType::LIMITED : TxAssetType::UNLIMITED)); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_ASSET", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpCreateAssetEmission::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "createassetemission", "params": [ "<address>", -- (string) owners' address "<asset>" -- (string) asset id ] } */ /* reply { "result": "<tx_emission_id>", -- (string) txid = emission_id "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters PKey lAddress; // 0 uint256 lAsset; // 1 if (lParams.size() == 2) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress.fromString(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // param[1] json::Value lP1 = lParams[1]; if (lP1.isString()) lAsset.setHex(lP1.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); // process std::string lCode, lMessage; TransactionContextPtr lCtx = nullptr; try { // create tx lCtx = wallet_->createTxLimitedAssetEmission(lAddress, lAsset); if (lCtx->errors().size()) { reply = HttpReply::stockReply("E_TX_CREATE_ASSET_EMISSION", *lCtx->errors().begin()); return; } // push to memory pool IMemoryPoolPtr lMempool = wallet_->mempoolManager()->locate(MainChain::id()); // dapp -> main chain if (lMempool) { // if (lMempool->pushTransaction(lCtx)) { // check for errors if (lCtx->errors().size()) { // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // error lCode = "E_TX_MEMORYPOOL"; lMessage = *lCtx->errors().begin(); lCtx = nullptr; } else if (!lMempool->consensus()->broadcastTransaction(lCtx, wallet_->firstKey()->createPKey().id())) { lCode = "E_TX_NOT_BROADCASTED"; lMessage = "Transaction is not broadcasted"; } } else { lCode = "E_TX_EXISTS"; lMessage = "Transaction already exists"; // unpack if (!unpackTransaction(lCtx->tx(), uint256(), 0, 0, 0, false, false, lReply, reply)) return; // rollback transaction wallet_->rollback(lCtx); // reset lCtx = nullptr; } } else { reply = HttpReply::stockReply("E_MEMPOOL", "Corresponding memory pool was not found"); return; } } catch(qbit::exception& ex) { reply = HttpReply::stockReply(ex.code(), ex.what()); return; } if (lCtx != nullptr) lReply.addString("result", lCtx->tx()->hash().toHex()); if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetState::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getstate", "params": [] } */ /* reply { "result": { "state": { ... } } }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lKeyObject = lReply.addObject("result"); json::Value lStateObject = lKeyObject.addObject("state"); // get peers std::list<IPeerPtr> lPeers; peerManager_->allPeers(lPeers); // peer manager lStateObject.addString("version", strprintf("%d.%d.%d.%d", QBIT_VERSION_MAJOR, QBIT_VERSION_MINOR, QBIT_VERSION_REVISION, QBIT_VERSION_BUILD)); lStateObject.addUInt("clients", peerManager_->clients()); lStateObject.addUInt("peers_count", lPeers.size()); uint64_t lInQueue = 0; uint64_t lOutQueue = 0; uint64_t lPendingQueue = 0; uint64_t lReceivedCount = 0; uint64_t lReceivedBytes = 0; uint64_t lSentCount = 0; uint64_t lSentBytes = 0; for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) { // if ((*lPeer)->status() == IPeer::UNDEFINED) continue; // if ((*lPeer)->status() == IPeer::BANNED || (*lPeer)->status() == IPeer::POSTPONED) { // lInQueue += (*lPeer)->inQueueLength(); lOutQueue += (*lPeer)->outQueueLength(); lPendingQueue += (*lPeer)->pendingQueueLength(); lReceivedCount += (*lPeer)->receivedMessagesCount(); lReceivedBytes += (*lPeer)->bytesReceived(); lSentCount += (*lPeer)->sentMessagesCount(); lSentBytes += (*lPeer)->bytesSent(); continue; } lInQueue += (*lPeer)->inQueueLength(); lOutQueue += (*lPeer)->outQueueLength(); lPendingQueue += (*lPeer)->pendingQueueLength(); lReceivedCount += (*lPeer)->receivedMessagesCount(); lReceivedBytes += (*lPeer)->bytesReceived(); lSentCount += (*lPeer)->sentMessagesCount(); lSentBytes += (*lPeer)->bytesSent(); } // lStateObject.addUInt("in_queue", lInQueue); lStateObject.addUInt("out_queue", lOutQueue); lStateObject.addUInt("pending_queue", lPendingQueue); lStateObject.addUInt("received_count", lReceivedCount); lStateObject.addUInt64("received_bytes", lReceivedBytes); lStateObject.addUInt("sent_count", lSentCount); lStateObject.addUInt64("sent_bytes", lSentBytes); // StatePtr lState = peerManager_->consensusManager()->currentState(); // json::Value lChainsObject = lStateObject.addArray("chains"); std::vector<State::BlockInfo> lInfos = lState->infos(); for (std::vector<State::BlockInfo>::iterator lInfo = lInfos.begin(); lInfo != lInfos.end(); lInfo++) { // json::Value lChain = lChainsObject.newArrayItem(); lChain.toObject(); // make object // get mempool IMemoryPoolPtr lMempool = peerManager_->memoryPoolManager()->locate(lInfo->chain()); if (lMempool) { // json::Value lMempoolObject = lChain.addObject("mempool"); size_t lTx = 0, lCandidatesTx = 0, lPostponedTx = 0; lMempool->statistics(lTx, lCandidatesTx, lPostponedTx); lMempoolObject.addUInt64("txs", lTx); lMempoolObject.addUInt64("candidates", lCandidatesTx); lMempoolObject.addUInt64("postponed", lPostponedTx); } // get consensus IConsensusPtr lConsensus = peerManager_->consensusManager()->locate(lInfo->chain()); lChain.addString("dapp", lInfo->dApp().size() ? lInfo->dApp() : "none"); lChain.addUInt64("height", lInfo->height()); lChain.addString("chain", lInfo->chain().toHex()); lChain.addString("block", lInfo->hash().toHex()); if (lConsensus) { lChain.addUInt64("time", lConsensus->currentTime()); lChain.addString("state", lConsensus->chainStateString()); } // sync job IConsensus::ChainState lState = lConsensus->chainState(); if (lState == IConsensus::SYNCHRONIZING) { SynchronizationJobPtr lJob = nullptr; for (std::list<IPeerPtr>::iterator lPeer = lPeers.begin(); lPeer != lPeers.end(); lPeer++) { // if ((*lPeer)->status() == IPeer::ACTIVE) { // SynchronizationJobPtr lNewJob = (*lPeer)->locateJob(lInfo->chain()); if (!lJob) lJob = lNewJob; else if (lNewJob && lJob && lJob->timestamp() < lNewJob->timestamp()) { lJob = lNewJob; } } } if (lJob) { json::Value lSyncObject = lChain.addObject("synchronization"); lSyncObject.addString("type", lJob->typeString()); if (lJob->type() != SynchronizationJob::PARTIAL) lSyncObject.addUInt64("remains", lJob->pendingBlocks()); } } } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpReleasePeer::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "releasepeer", "params": [ "<peer_address>" -- (string) peer IP address ] } */ /* reply { "result": "<peer_address>", -- (string) peer IP address "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lAddress; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lAddress = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); peerManager_->release(lAddress); lReply.addString("result", lAddress); lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetEntitiesCount::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getentitiescount", "params": [ "<dapp_name>" -- (string, required) dapp name ] } */ /* reply { "result": -- (object) details { ... }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters std::string lDApp; // 0 if (lParams.size()) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lDApp = lP0.getString(); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // json::Document lReply; lReply.loadFromString("{}"); json::Value lRootObject = lReply.addObject("result"); json::Value lDAppObject = lRootObject.addArray(lDApp); // std::map<uint256, uint32_t> lShardInfo; ITransactionStorePtr lStorage = peerManager_->consensusManager()->storeManager()->locate(MainChain::id()); // std::vector<ISelectEntityCountByShardsHandler::EntitiesCount> lEntitiesCount; if (lStorage->entityStore()->entityCountByDApp(lDApp, lShardInfo)) { for (std::map<uint256, uint32_t>::iterator lItem = lShardInfo.begin(); lItem != lShardInfo.end(); lItem++) { // json::Value lDAppItem = lDAppObject.newArrayItem(); lDAppItem.toObject(); lDAppItem.addString("shard", lItem->first.toHex()); lDAppItem.addUInt("count", lItem->second); } } lReply.addObject("error").toNull(); lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } void HttpGetUnconfirmedTransactions::process(const std::string& source, const HttpRequest& request, const json::Document& data, HttpReply& reply) { /* request { "jsonrpc": "1.0", "id": "curltext", "method": "getunconfirmedtxs", "params": [ "<chain_id>" -- (string) chain hash (id) ] } */ /* reply { "result": { "txs": [ "...", "..." ] }, "error": -- (object or null) error description { "code": "EFAIL", "message": "<explanation>" }, "id": "curltext" -- (string) request id } */ // id json::Value lId; if (!(const_cast<json::Document&>(data).find("id", lId) && lId.isString())) { reply = HttpReply::stockReply(HttpReply::bad_request); return; } // params json::Value lParams; if (const_cast<json::Document&>(data).find("params", lParams) && lParams.isArray()) { // extract parameters uint256 lChainId; // 0 if (lParams.size() == 1) { // param[0] json::Value lP0 = lParams[0]; if (lP0.isString()) lChainId.setHex(lP0.getString()); else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } } else { reply = HttpReply::stockReply("E_PARAMS", "Insufficient or extra parameters"); return; } // prepare reply json::Document lReply; lReply.loadFromString("{}"); json::Value lResultObject = lReply.addObject("result"); json::Value lTxsArrayObject = lResultObject.addArray("txs"); // process std::string lCode, lMessage; // try to lookup transaction IMemoryPoolManagerPtr lMempoolManager = wallet_->mempoolManager(); if (lMempoolManager) { // IMemoryPoolPtr lMempool = lMempoolManager->locate(lChainId); // if (lMempool) { // uint64_t lTotal = 0; std::list<uint256> lTxs; lMempool->selectTransactions(lTxs, lTotal, 10000 /*max*/); lResultObject.addUInt64("total", lTotal); // for (std::list<uint256>::iterator lTx = lTxs.begin(); lTx != lTxs.end(); lTx++) { // json::Value lItem = lTxsArrayObject.newArrayItem(); lItem.setString(lTx->toHex()); } } else { reply = HttpReply::stockReply("E_MEMPOOL_NOT_FOUND", "Memory pool was not found"); return; } } else { reply = HttpReply::stockReply("E_POOLMANAGER", "Pool manager not found"); return; } if (!lCode.size() && !lMessage.size()) lReply.addObject("error").toNull(); else { json::Value lError = lReply.addObject("error"); lError.addString("code", lCode); lError.addString("message", lMessage); } lReply.addString("id", lId.getString()); // pack pack(reply, lReply); // finalize finalize(reply); } else { reply = HttpReply::stockReply(HttpReply::bad_request); return; } }
29.487834
171
0.627141
9734163529bf58d4bd81ddf95bf6f89ab05f743b
1,032
cpp
C++
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
C++/05_Dynamic_Programming/MEDIUM_DECODE_WAYS.cpp
animeshramesh/interview-prep
882e8bc8b4653a713754ab31a3b08e05505be2bc
[ "Apache-2.0" ]
null
null
null
/* A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). The number of ways decoding "12" is 2. */ // https://stackoverflow.com/questions/20342462/review-an-answer-decode-ways // https://www.youtube.com/watch?v=aCKyFYF9_Bg // Solution from http://bangbingsyb.blogspot.com/2014/11/leetcode-decode-ways.html int numDecodings(string s) { if(s.empty() || s[0]<'1' || s[0]>'9') return 0; vector<int> dp(s.size()+1,0); dp[0] = dp[1] = 1; // dp[i] is the number of ways to decode str[0:i] for(int i=1; i<s.size(); i++) { if(!isdigit(s[i])) return 0; int v = (s[i-1]-'0')*10 + (s[i]-'0'); if(v<=26 && v>9) dp[i+1] += dp[i-1]; if(s[i]!='0') dp[i+1] += dp[i]; if(dp[i+1]==0) return 0; } return dp[s.size()]; }
32.25
97
0.592054
9734922a52146c96dae481fb1d6da9230ee6ff94
1,810
cpp
C++
libraries/physics/src/ContactConstraint.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
libraries/physics/src/ContactConstraint.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
libraries/physics/src/ContactConstraint.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // ContactConstraint.cpp // libraries/physcis/src // // Created by Andrew Meadows 2014.07.24 // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <SharedUtil.h> #include "ContactConstraint.h" #include "VerletPoint.h" ContactConstraint::ContactConstraint(VerletPoint* pointA, VerletPoint* pointB) : _pointA(pointA), _pointB(pointB), _strength(1.0f) { assert(_pointA != NULL && _pointB != NULL); _offset = _pointB->_position - _pointA->_position; } float ContactConstraint::enforce() { _pointB->_position += _strength * (_pointA->_position + _offset - _pointB->_position); return 0.0f; } float ContactConstraint::enforceWithNormal(const glm::vec3& normal) { glm::vec3 delta = _pointA->_position + _offset - _pointB->_position; // split delta into parallel (pDelta) and perpendicular (qDelta) components glm::vec3 pDelta = glm::dot(delta, normal) * normal; glm::vec3 qDelta = delta - pDelta; // use the relative sizes of the components to decide how much perpenducular delta to use // (i.e. dynamic friction) float lpDelta = glm::length(pDelta); float lqDelta = glm::length(qDelta); float qFactor = lqDelta > lpDelta ? (lpDelta / lqDelta - 1.0f) : 0.0f; // recombine the two components to get the final delta delta = pDelta + qFactor * qDelta; // attenuate strength by how much _offset is perpendicular to normal float distance = glm::length(_offset); float strength = _strength * ((distance > EPSILON) ? glm::abs(glm::dot(_offset, normal)) / distance : 1.0f); // move _pointB _pointB->_position += strength * delta; return strength * glm::length(delta); }
33.518519
112
0.692265
9734eb840112ee3d67af26b01b7786ba873b5526
2,839
hpp
C++
include/boost/http_proto/detail/copied_strings.hpp
alandefreitas/http_proto
dc64cbdd44048a2c06671282b736f7edacb39a42
[ "BSL-1.0" ]
6
2021-11-17T03:23:50.000Z
2021-11-25T15:58:02.000Z
include/boost/http_proto/detail/copied_strings.hpp
alandefreitas/http_proto
dc64cbdd44048a2c06671282b736f7edacb39a42
[ "BSL-1.0" ]
6
2021-11-17T16:13:52.000Z
2022-01-31T04:17:47.000Z
include/boost/http_proto/detail/copied_strings.hpp
samd2/http_proto
486729f1a68b7611f143e18c7bae8df9b908e9aa
[ "BSL-1.0" ]
3
2021-11-17T03:01:12.000Z
2021-11-17T14:14:45.000Z
// // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/CPPAlliance/http_proto // #ifndef BOOST_HTTP_PROTO_DETAIL_COPIED_STRINGS_HPP #define BOOST_HTTP_PROTO_DETAIL_COPIED_STRINGS_HPP #include <boost/http_proto/string_view.hpp> #include <functional> namespace boost { namespace http_proto { namespace detail { // Makes copies of string_view parameters as // needed when the storage for the parameters // overlap the container being modified. class basic_copied_strings { struct dynamic_buf { dynamic_buf* next; }; string_view s_; char* local_buf_; std::size_t local_remain_; dynamic_buf* dynamic_list_ = nullptr; bool is_overlapping( string_view s) const noexcept { auto const b1 = s_.data(); auto const e1 = b1 + s_.size(); auto const b2 = s.data(); auto const e2 = b2 + s.size(); auto const less_equal = std::less_equal<char const*>(); if(less_equal(e1, b2)) return false; if(less_equal(e2, b1)) return false; return true; } public: ~basic_copied_strings() { while(dynamic_list_) { auto p = dynamic_list_; dynamic_list_ = dynamic_list_->next; delete[] p; } } basic_copied_strings( string_view s, char* local_buf, std::size_t local_size) noexcept : s_(s) , local_buf_(local_buf) , local_remain_(local_size) { } string_view maybe_copy( string_view s) { if(! is_overlapping(s)) return s; if(local_remain_ >= s.size()) { std::memcpy(local_buf_, s.data(), s.size()); s = string_view( local_buf_, s.size()); local_buf_ += s.size(); local_remain_ -= s.size(); return s; } auto const n = sizeof(dynamic_buf); auto p = new dynamic_buf[1 + sizeof(n) * ((s.size() + sizeof(n) - 1) / sizeof(n))]; std::memcpy(p + 1, s.data(), s.size()); s = string_view(reinterpret_cast< char const*>(p + 1), s.size()); p->next = dynamic_list_; dynamic_list_ = p; return s; } }; class copied_strings : public basic_copied_strings { char buf_[4096]; public: copied_strings( string_view s) : basic_copied_strings( s, buf_, sizeof(buf_)) { } }; } // detail } // http_proto } // boost #endif
22.712
79
0.559352
97384c308cf5a7f11846cde620d00a08f7c3b3c2
536
cpp
C++
ALP/sequencia/L01_ex01.cpp
khrystie/fatec_ads
a5fec2c612943342f731a46814d4f6df67eb692f
[ "MIT" ]
null
null
null
ALP/sequencia/L01_ex01.cpp
khrystie/fatec_ads
a5fec2c612943342f731a46814d4f6df67eb692f
[ "MIT" ]
null
null
null
ALP/sequencia/L01_ex01.cpp
khrystie/fatec_ads
a5fec2c612943342f731a46814d4f6df67eb692f
[ "MIT" ]
null
null
null
/* Exercício: Faça um algoritmo que receba 2 números inteiros e apresente a soma desses números. */ #include <iostream> int main() { //declaração de variáveis int num1, num2; // atribuir valor 0 num1=0; num2=0; std::cout << "Programa que lê dois números inteiros e retorna o valor da soma\n"; std::cout <<"Digite o primeiro número inteiro: \n"; std::cin >> num1; std::cout <<"Digite o segundo número inteiro: \n"; std::cin >> num2; std::cout <<"A soma dos dois números inteiros é: \n" <<num1+num2; }
22.333333
95
0.652985
9738b40e93cc34db346f6f331cea0a1ca13bae6d
372
cp
C++
Lin/Mod/X11.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
2
2016-03-17T08:27:55.000Z
2020-05-02T08:42:08.000Z
Lin/Mod/X11.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
null
null
null
Lin/Mod/X11.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
null
null
null
MODULE LinX11 ["libX11.so"]; IMPORT LinLibc; TYPE Display* = INTEGER; PROCEDURE XFreeFontNames* (list: LinLibc.StrArray); PROCEDURE XListFonts* (display: Display; pattern: LinLibc.PtrSTR; maxnames: INTEGER; VAR actual_count_return: INTEGER): LinLibc.StrArray; PROCEDURE XOpenDisplay* (VAR [nil] display_name: LinLibc.PtrSTR): Display; END LinX11.
26.571429
86
0.733871
9738eda77042cec54309a95c28906a00687bea7c
8,818
cpp
C++
Classes/Helpers/AnimationHelper.cpp
funkyzooink/fresh-engine
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
[ "MIT" ]
3
2019-10-09T09:17:49.000Z
2022-03-02T17:57:05.000Z
Classes/Helpers/AnimationHelper.cpp
funkyzooink/fresh-engine
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
[ "MIT" ]
33
2019-10-08T18:45:48.000Z
2022-01-05T21:53:02.000Z
Classes/Helpers/AnimationHelper.cpp
funkyzooink/fresh-engine
de15fa6ebe1b686819b28cd92ee8a6771c4ff878
[ "MIT" ]
7
2019-10-10T11:31:58.000Z
2021-02-08T14:24:30.000Z
/**************************************************************************** Copyright (c) 2014-2019 Gabriel Heilig fresh-engine funkyzooink@gmail.com ****************************************************************************/ #include "AnimationHelper.h" #include "../GameData/Constants.h" #include "../GameData/GameConfig.h" #include "../GameData/Gamedata.h" #include "cocos2d.h" // MARK: Animation Helper void AnimationHelper::levelinfoFadeInAnimation(cocos2d::Node* node1, cocos2d::Node* node2) { auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); switch (GAMECONFIG.getLevelInfoPopupType()) { case 1: { node1->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create( 1.0F, cocos2d::Vec2(visibleSize.width / 2 - CONSTANTS.getOffset() * 2, node1->getPosition().y)), nullptr)); node2->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.0F, cocos2d::Vec2(visibleSize.width / 2 - node2->getContentSize().width / 2, node2->getPosition().y)), nullptr)); break; } default: { auto position = node1->getPosition(); node1->setPosition(position.x, visibleSize.height); node2->setVisible(true); node1->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(1.0F, position), nullptr)); break; } } } void AnimationHelper::levelInfoFadeOutAnimation(cocos2d::Node* node1, cocos2d::Node* node2) { auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); switch (GAMECONFIG.getLevelInfoPopupType()) { case 1: { node1->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.0F, cocos2d::Vec2(visibleSize.width, node1->getPosition().y)), nullptr)); node2->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.5F, cocos2d::Vec2(-visibleSize.width, node2->getPosition().y)), nullptr)); break; } default: { node2->setVisible(true); node1->runAction(cocos2d::Sequence::create( cocos2d::MoveTo::create(1.5F, cocos2d::Vec2(node1->getPosition().x, -visibleSize.height)), nullptr)); break; } } } void AnimationHelper::fadeIn(cocos2d::Node* from, cocos2d::Node* to) { auto duration = 0.8F; auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); if (to != nullptr) { to->setVisible(true); // make sure both nodes are visible auto toPosition = cocos2d::Vec2(to->getPosition().x, 0.0); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { to->setPosition(toPosition.x, visibleSize.height); to->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, toPosition), nullptr)); break; } default: { to->setPosition(toPosition); break; } } } if (from != nullptr) { from->setVisible(true); // make sure both nodes are visible auto fromPosition = cocos2d::Vec2(from->getPosition().x, -visibleSize.height); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { from->setPosition(0.0, 0.0); from->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, fromPosition), nullptr)); break; } default: { from->setPosition(fromPosition); break; } } } } void AnimationHelper::fadeOut(cocos2d::Node* from, cocos2d::Node* to) { auto duration = 0.8F; auto visibleSize = cocos2d::Director::getInstance()->getVisibleSize(); if (to != nullptr) { to->setVisible(true); // make sure both nodes are visible auto toPosition = cocos2d::Vec2(to->getPosition().x, 0.0F); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { to->setPosition(toPosition.x, -visibleSize.height); to->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, toPosition), nullptr)); break; } default: { to->setPosition(toPosition); break; } } } if (from != nullptr) { from->setVisible(true); // make sure both nodes are visible auto fromPosition = cocos2d::Vec2(from->getPosition().x, visibleSize.height); switch (GAMECONFIG.getMainSceneAnimation()) { case 1: { from->setPosition(0.0, 0.0); from->runAction(cocos2d::Sequence::create(cocos2d::MoveTo::create(duration, fromPosition), nullptr)); break; } default: { from->setPosition(fromPosition); break; } } } } cocos2d::TransitionScene* AnimationHelper::sceneTransition(cocos2d::Scene* scene) { return cocos2d::TransitionFade::create(0.2f, scene); } cocos2d::FiniteTimeAction* AnimationHelper::blinkAnimation() { float blinkDuration = 0.05F; return cocos2d::Sequence::create(cocos2d::FadeOut::create(blinkDuration), cocos2d::FadeIn::create(blinkDuration), cocos2d::FadeOut::create(blinkDuration), cocos2d::FadeIn::create(blinkDuration), nullptr); } cocos2d::Action* AnimationHelper::getActionForTag(const std::string& tag) { auto animationCache = cocos2d::AnimationCache::getInstance()->getAnimation(tag); if (animationCache == nullptr) { return nullptr; } auto animation = cocos2d::Animate::create(animationCache); auto repeatForever = cocos2d::RepeatForever::create(animation); return repeatForever; } std::map<AnimationHelper::AnimationTagEnum, std::string> AnimationHelper::initAnimations( const std::string& type, const std::map<std::string, std::vector<std::string>>& animationMap) { std::map<AnimationHelper::AnimationTagEnum, std::string> _animationEnumMap; _animationEnumMap[AnimationHelper::AnimationTagEnum::ATTACK_LEFT_ANIMATION] = type + "_attack_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::FALL_LEFT_ANIMATION] = type + "_jump_left_down"; _animationEnumMap[AnimationHelper::AnimationTagEnum::HIT_LEFT_ANIMATION] = type + "_hit_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::IDLE_LEFT_ANIMATION] = type + "_idle_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::JUMP_LEFT_ANIMATION] = type + "_jump_left_up"; _animationEnumMap[AnimationHelper::AnimationTagEnum::WALK_LEFT_ANIMATION] = type + "_walk_left"; _animationEnumMap[AnimationHelper::AnimationTagEnum::ATTACK_RIGHT_ANIMATION] = type + "_attack_right"; _animationEnumMap[AnimationHelper::AnimationTagEnum::FALL_RIGHT_ANIMATION] = type + "_jump_right_down"; _animationEnumMap[AnimationHelper::AnimationTagEnum::HIT_RIGHT_ANIMATION] = type + "_hit_right"; _animationEnumMap[AnimationHelper::AnimationTagEnum::IDLE_RIGHT_ANIMATION] = type + "_idle_right"; _animationEnumMap[AnimationHelper::AnimationTagEnum::JUMP_RIGHT_ANIMATION] = type + "_jump_right_up"; _animationEnumMap[AnimationHelper::AnimationTagEnum::WALK_RIGHT_ANIMATION] = type + "_walk_right"; cocos2d::Animation* animation = nullptr; for (auto const& entry : animationMap) { auto animationTag = type + "_" + entry.first; // TODO this needs to be the same as in animationEnumMap // TODO check if created tag is part of animationEnum otherwise abort animation = prepareVector(entry.second, 0.2F); // check times! 0.5 for staticshooter idle // check times! 0.2 for jumps falls and walking animation cocos2d::AnimationCache::getInstance()->addAnimation(animation, animationTag); } return _animationEnumMap; } cocos2d::Animation* AnimationHelper::prepareVector(const std::vector<std::string>& filenames, float duration) { cocos2d::Vector<cocos2d::SpriteFrame*> spriteVector(filenames.size()); for (const std::string& file : filenames) { cocos2d::SpriteFrame* spriteFrame = cocos2d::SpriteFrameCache::getInstance()->getSpriteFrameByName(file); spriteVector.pushBack(spriteFrame); } cocos2d::Animation* animation = cocos2d::Animation::createWithSpriteFrames(spriteVector, duration, 1); return animation; };
37.683761
118
0.612611
973baf7e8b43308470a136c4db0f0a92e28a7e8c
2,484
cpp
C++
Off-Comp.cpp
MAXIORBOY/Off-Comp
3e4884f0c5370a76c34f03e226513d30eb95812c
[ "MIT" ]
null
null
null
Off-Comp.cpp
MAXIORBOY/Off-Comp
3e4884f0c5370a76c34f03e226513d30eb95812c
[ "MIT" ]
null
null
null
Off-Comp.cpp
MAXIORBOY/Off-Comp
3e4884f0c5370a76c34f03e226513d30eb95812c
[ "MIT" ]
null
null
null
#include <time.h> #include <conio.h> #include <iostream> #include <windows.h> #include <string> using namespace std; void wait( int seconds ) { clock_t end_wait; end_wait = clock() + seconds * CLOCKS_PER_SEC; while( clock() < end_wait ) { } } void gotoxy(const int x, const int y) { HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE); COORD coord = {x, y}; SetConsoleCursorPosition(hCon, coord); } int main() { cout <<"\t\t\t\t\t\tOff-Comp"<<endl<<endl<<endl; string names[3]; names[0] = "hours"; names[1] = "minutes"; names[2] = "seconds"; string input[3]; int units[3]; string ex_zeroes[3]; int y = 11; bool input_repeat; for(int i=0; i<3; i++) { do { input_repeat = false; if (i > 0) cout <<"(Stage "<<i+1<<"/3"<<") "<<"Insert a number of "<<names[i]<<" (0-59)"<<": "; else cout <<"(Stage "<<i+1<<"/3"<<") "<<"Insert a number of "<<names[i]<<" (0-99)"<<": "; cin >> input[i]; try { units[i] = stoi(input[i]); } catch(invalid_argument& e ) { cout << "Invalid input!"<<endl<<endl; y += 3; input_repeat = true; } if (!input_repeat) { if (units[i] < 0 || (units[i] > 59 && i > 0) || (units[i] > 99 && i == 0)) { cout << "Out of range!"<<endl<<endl; y += 3; input_repeat = true; } } }while(input_repeat == true); } for(int i=3600*units[0] + 60*units[1] + units[2]; i > 0; i--) { gotoxy(0, y); for(int j=0; j<3; j++) { if (units[j] < 10) ex_zeroes[j] = "0"; else ex_zeroes[j] = ""; } cout <<"The computer will be shut down in: "<<ex_zeroes[0]<<units[0]<<":"<<ex_zeroes[1]<<units[1]<<":"<<ex_zeroes[2]<<units[2]; units[2] -= 1; if (units[2] < 0) { units[1] -= 1; if (units[1] < 0) { units[0] -= 1; units[1] += 60; } units[2] += 60; } wait( 1 ); } gotoxy(0, y); cout <<"The computer will be shut down in: 00:00:00"<<endl; system("shutdown -f -s"); getch(); }
22.581818
135
0.414251
973c113401f4674b562d4ebf3724e179531270e7
185
cpp
C++
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/language/grammars/expression07_grammar_inst.cpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#include "expression07_grammar_def.hpp" #include "iterator_typedefs.hpp" namespace stan { namespace lang { template struct expression07_grammar<pos_iterator_t>; } } // namespace stan
20.555556
53
0.8
973c1d1aef3085b665141d6b9dfc1f5600ed76b1
838
cpp
C++
Classes/Device.cpp
Tang1705/Happy-Reconstruction
2040310be4475deff0a8d251feaf32d7ba82d0ff
[ "Apache-2.0" ]
5
2021-12-13T08:48:07.000Z
2022-01-04T01:28:40.000Z
Classes/Device.cpp
xmtc56606/Reconstruction
7eadf91b397fa2067b983be1a31c9603043d1360
[ "Apache-2.0" ]
null
null
null
Classes/Device.cpp
xmtc56606/Reconstruction
7eadf91b397fa2067b983be1a31c9603043d1360
[ "Apache-2.0" ]
1
2022-03-28T06:04:34.000Z
2022-03-28T06:04:34.000Z
#include "Device.h" #include <QDebug> Device* Device::instance = nullptr; Device::Device() { vector<CameraInfo> cams = CameraPointGrey::getCameraList(); if (cams.size() != 0) { hasCamera = true; camera = Camera::NewCamera(0, cams[0].busID, triggerModeSoftware); CameraSettings camSettings; camSettings.shutter = 25; camSettings.gain = 0.0; camera->setCameraSettings(camSettings); camera->startCapture(); } projector = new ProjectorLC4500(0); if (projector->getIsRunning())hasProjector = true; } Device* Device::getInstance() { if (instance == nullptr) instance = new Device(); return instance; } Camera* Device::getCamera() { return camera; } Projector* Device::getProjector() { return projector; } bool Device::getHasCamera() { return hasCamera; } bool Device::getHasProjector() { return hasProjector; }
17.458333
68
0.711217
973fe8eaa908632171eb72d68bcb6ed1e1b0ba35
4,253
cpp
C++
test/cfgTest.cpp
arminnh/Machines-and-Computability-project
7e7be2541074ca8a177335aaad1b09394145fcf6
[ "MIT" ]
null
null
null
test/cfgTest.cpp
arminnh/Machines-and-Computability-project
7e7be2541074ca8a177335aaad1b09394145fcf6
[ "MIT" ]
null
null
null
test/cfgTest.cpp
arminnh/Machines-and-Computability-project
7e7be2541074ca8a177335aaad1b09394145fcf6
[ "MIT" ]
1
2017-01-30T19:16:19.000Z
2017-01-30T19:16:19.000Z
/* * * File Name : * * Creation Date : 21-01-2015 * Last Modified : do 22 jan 12:34:27 2015 * Created By : Bruno De Deken * */ #include "comparefiles.h" #include <string> #include <set> #include <gtest/gtest.h> #include <UTM/util.h> #include <UTM/dot.h> #include <UTM/finiteautomaton.h> #include <UTM/CFG.h> #include <UTM/CFGParser.h> #include <UTM/CFG2CNF.h> /** CFG TESTS **/ class CFGTest : public ::testing::Test { protected: CFG cfg; virtual void SetUp() { CFGParser parser("./data/cfg1Test.xml"); cfg = CFG(parser.getVariables(), parser.getTerminals(), parser.getProductionRules(), parser.getStartSymbol(), parser.getName()); } }; TEST_F(CFGTest, parser) { std::set<Symbol> vars{cfg.getVariables()}; EXPECT_EQ(vars.size(), 1); EXPECT_EQ(vars.begin()->getValue(), "P"); std::set<Symbol> ters{cfg.getTerminals()}; EXPECT_EQ(ters.size(), 2); auto it = ters.begin(); EXPECT_EQ(it->getValue(), "0"); ++it; EXPECT_EQ(it->getValue(), "1"); EXPECT_EQ(cfg.getRules().at(0).first.getValue(), "P"); EXPECT_EQ(cfg.getRules().at(0).second.size(), 3); EXPECT_EQ(cfg.getRules().at(0).second.at(0).getValue(), "0"); EXPECT_EQ(cfg.getRules().at(0).second.at(1).getValue(), "P"); EXPECT_EQ(cfg.getRules().at(0).second.at(2).getValue(), "0"); EXPECT_EQ(cfg.getRules().at(1).first.getValue(), "P"); EXPECT_EQ(cfg.getRules().at(1).second.size(), 3); EXPECT_EQ(cfg.getRules().at(1).second.at(0).getValue(), "1"); EXPECT_EQ(cfg.getRules().at(1).second.at(1).getValue(), "P"); EXPECT_EQ(cfg.getRules().at(1).second.at(2).getValue(), "1"); } TEST_F(CFGTest, checks) { EXPECT_TRUE(cfg.isConsistent()); EXPECT_FALSE(cfg.isDefinedSymbol(Symbol{"X", true})); EXPECT_FALSE(cfg.isDefinedSymbol(Symbol{"P", true})); EXPECT_TRUE(cfg.isDefinedSymbol(Symbol{"P", false})); EXPECT_FALSE(cfg.isDefinedSymbol(Symbol{"0", false})); EXPECT_TRUE(cfg.isDefinedSymbol(Symbol{"0", true})); EXPECT_TRUE(cfg.isDefinedSymbol(Symbol{"1", true})); EXPECT_FALSE(cfg.isDefinedVariable(Symbol{"T", false})); EXPECT_FALSE(cfg.isDefinedVariable(Symbol{"P", true})); EXPECT_TRUE(cfg.isDefinedVariable(Symbol{"P", false})); EXPECT_FALSE(cfg.isDefinedTerminal(Symbol{"P", false})); EXPECT_FALSE(cfg.isDefinedTerminal(Symbol{"0", false})); EXPECT_TRUE(cfg.isDefinedTerminal(Symbol{"0", true})); auto rule = *cfg.getRules().begin(); EXPECT_TRUE(cfg.isDefinedRule(rule)); rule.first = Symbol{"X", true}; EXPECT_FALSE(cfg.isDefinedRule(rule)); EXPECT_FALSE(cfg.isUsedWithinProduction(Symbol{"P", true})); EXPECT_FALSE(cfg.isUsedWithinProduction(Symbol{"0", false})); EXPECT_TRUE(cfg.isUsedWithinProduction(Symbol{"P", false})); EXPECT_TRUE(cfg.isUsedWithinProduction(Symbol{"1", true})); } TEST_F(CFGTest, methodBasics) { auto r = *cfg.getRules().begin(); auto r2 = cfg.useRule(r.second, 1, 1); EXPECT_EQ(r.second, (std::vector<Symbol>{Symbol{"0", true}, Symbol{"P", false}, Symbol{"0", true}})); EXPECT_EQ(r2, (std::vector<Symbol>{Symbol{"0", true}, Symbol{"0", true}, Symbol{"P", false}, Symbol{"0", true}, Symbol{"0", true}})); std::vector< std::pair <int, int > > rulesToUse { std::make_pair(1, 1), std::make_pair(1, 1), std::make_pair(2, 1)}; EXPECT_EQ(cfg.useRules(rulesToUse), "001P100"); } TEST_F(CFGTest, automaton) { FiniteAutomaton* fa = new FiniteAutomaton(cfg.generatePDA()); writeDotFile(fa, "result.dot"); EXPECT_TRUE(compareFiles("result.dot", "./data/expected.dot")); delete fa; } TEST_F(CFGTest, result){ CFG2CNF converter; cfg = converter(cfg); EXPECT_TRUE(cfg.isMember(std::string{"00010001000"})); EXPECT_TRUE(cfg.isMember(std::string{"00"})); EXPECT_FALSE(cfg.isMember(std::string{""})); //Empty string never alowed. EXPECT_FALSE(cfg.isMember(std::string{"0010"})); } TEST_F(CFGTest, xmlWriter) { CFGParser parser("./data/cfg1Test.xml"); CFG cfg1 = CFG(parser.getVariables(), parser.getTerminals(), parser.getProductionRules(), parser.getStartSymbol(), parser.getName()); cfg1.generateXML("result.xml"); CFGParser _parser("result.xml"); CFG cfg2 = CFG(_parser.getVariables(), _parser.getTerminals(), _parser.getProductionRules(), _parser.getStartSymbol(), _parser.getName()); EXPECT_EQ(cfg2, cfg1); }
33.226563
140
0.682577
9741c086d1b97a36b72febad8eb1f70578664ab7
2,492
cpp
C++
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
2
2015-04-17T11:28:57.000Z
2016-11-13T13:03:08.000Z
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
null
null
null
src/args_test.cpp
JoelSjogren/video-organizer
fc5a5c1a2fce39f2b9d8343c07c53108321ef260
[ "Apache-2.0" ]
null
null
null
/********************************** * args_test.cpp * **********************************/ #include "args_test.h" #include "args.h" #include "fileman.h" #include <string> using std::string; ArgsTest::ArgsTest() : Test("Args") { const char* files[] = { "Chuck.S05E01.HDTV.XviD-LOL.avi", "Community.S04E02.HDTV.x264-LOL.mp4", "subdir/Chuck.S05E02.HDTV.XviD-LOL.avi", "The.Prestige.2006.720p.Bluray.x264.anoXmous.mp4", }; const int filec = sizeof(files) / sizeof(*files); const string indir = getdir() + "input/"; const string outdir = getdir() + "output/"; { // Prepare workspace Args args; FileMan fileman(args); fileman.remove_all(getdir()); for (int i = 0; i < filec; i++) fileman.touch(indir + files[i]); fileman.dig(outdir); } { // Test 1: minimal char* argv[] = { (char*) "video-organizer", (char*) indir.c_str(), (char*) "--verbosity=-1", // suppress warnings }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, "./"); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::MOVE); EQ(args.verbosity, -1); EQ(args.recursive, false); EQ(args.include_part, false); EQ(args.clean, 0); } { // Test 2: short options char* argv[] = { (char*) "video-organizer", (char*) indir.c_str(), (char*) "-v", (char*) "-1", (char*) "-o", (char*) outdir.c_str(), (char*) "-c", (char*) "-r", (char*) "-p", }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, outdir); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::COPY); EQ(args.verbosity, -1); EQ(args.recursive, true); EQ(args.include_part, true); EQ(args.clean, 0); } { // Test 3: long options string outdirarg = "--outdir=" + outdir; // put on stack char* argv[] = { (char*) "video-organizer", (char*) "--link", (char*) indir.c_str(), (char*) "--verbosity=-1", (char*) outdirarg.c_str(), (char*) "--recursive", (char*) "--part", (char*) "--clean=3M", }; int argc = sizeof(argv) / sizeof(*argv); Args args(argc, argv); EQ(args.undo, false); EQ(args.outdir, outdir); EQ(args.infiles.size(), (unsigned) 1); EQ(args.action, Args::LINK); EQ(args.verbosity, -1); EQ(args.recursive, true); EQ(args.include_part, true); EQ(args.clean, 3*1024*1024); } }
26.795699
58
0.554575
97466246b549d44e5bfbfba129449c424b573d6e
2,501
cpp
C++
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
71
2017-12-18T10:35:41.000Z
2021-12-11T19:57:34.000Z
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
1
2017-12-19T09:31:46.000Z
2017-12-20T07:08:01.000Z
test/test_timer.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
7
2017-12-20T01:55:44.000Z
2019-12-06T12:25:55.000Z
#include <gtest/gtest.h> #include <futures/EventExecutor.h> #include <futures/Timeout.h> #include <futures/Timer.h> #include <futures/Future.h> using namespace futures; TEST(Executor, Timer) { EventExecutor ev; auto f = TimerFuture(&ev, 1) .andThen([&ev] (Unit) { std::cerr << "DONE" << std::endl; return makeOk(); }); ev.spawn(std::move(f)); ev.run(); std::cerr << "END" << std::endl; } TEST(Future, Timeout) { EventExecutor ev; auto f = makeEmpty<int>(); auto f1 = timeout(&ev, std::move(f), 1.0) .then([] (Try<int> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; return makeOk(); }); ev.spawn(std::move(f1)); ev.run(); } TEST(Future, AllTimeout) { EventExecutor ev; std::vector<BoxedFuture<int>> f; f.emplace_back(TimerFuture(&ev, 1.0) .then([] (Try<Unit> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; else std::cerr << "Timer1 done" << std::endl; return makeOk(1); }).boxed()); f.emplace_back(TimerFuture(&ev, 2.0) .then([] (Try<Unit> v) { if (v.hasException()) std::cerr << "ERROR" << std::endl; else std::cerr << "Timer2 done" << std::endl; return makeOk(2); }).boxed()); auto all = makeWhenAll(f.begin(), f.end()) .andThen([] (std::vector<int> ids) { std::cerr << "done" << std::endl; return makeOk(); }); ev.spawn(std::move(all)); ev.run(); } BoxedFuture<std::vector<int>> rwait(EventExecutor &ev, std::vector<int> &v, int n) { if (n == 0) return makeOk(std::move(v)).boxed(); return TimerFuture(&ev, 0.1) .andThen( [&ev, &v, n] (Unit) { v.push_back(n); return rwait(ev, v, n - 1); }).boxed(); } TEST(Future, RecursiveTimer) { EventExecutor ev; std::vector<int> idxes; auto w10 = rwait(ev, idxes, 10) .andThen([] (std::vector<int> idxes) { for (auto e: idxes) std::cerr << e << std::endl; return makeOk(); }); ev.spawn(std::move(w10)); ev.run(); } TEST(Future, TimerKeeper) { EventExecutor ev; auto timer = std::make_shared<TimerKeeper>(&ev, 1); auto f = [timer, &ev] (double sec) { return delay(&ev, sec) .andThen([timer] (Unit) { return TimerKeeperFuture(timer); }) .then([] (Try<Unit> err) { if (err.hasException()) { std::cerr << "ERR: " << err.exception().what() << std::endl; } else { std::cerr << "Timeout: " << (uint64_t)(EventExecutor::current()->getNow() * 1000.0) << std::endl; } return makeOk(); }); }; ev.spawn(f(0.2)); ev.spawn(f(0.4)); ev.run(); }
21.376068
102
0.580968
974aa1b66be0b4d7e57c440ac9130fdb6c4d7a61
960
cpp
C++
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
1
2021-04-19T12:10:01.000Z
2021-04-19T12:10:01.000Z
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
null
null
null
lib/Food.cpp
prakashutoledo/pacman-cpp
0d3e46bd79970d722bc83fd5aeb52a34ad6c27e5
[ "Apache-2.0" ]
null
null
null
#include "Food.h" void Food::Initilize(Position * position) { this->position = position; drawing = CreateBitmap(position); CollisionDetection::Instance()->Add(this); } Food::Food(int x, int y) { Initilize(new Position(x - FOOD_RADIUS, y - FOOD_RADIUS)); } Food::Food(Position * position) { Initilize(position); } Bitmap * Food::CreateBitmap(Position * position) { #ifdef DEBUG if (position == 0) throw new NullReferenceException("position", "Food::CreateBitmap"); #endif Bitmap * bmp = new Bitmap(2 * FOOD_RADIUS + 1, 2 * FOOD_RADIUS + 1, position->X(), position->Y()); Color * color = new Color(FOOD_COLOR_R, FOOD_COLOR_G, FOOD_COLOR_B); bmp->Clean(); bmp->DrawFilledCircle(FOOD_RADIUS, FOOD_RADIUS, FOOD_RADIUS, color); return bmp; } void Food::WasEaten() { DrawingElement::WasEaten(); Reconstruction::Instance()->FoodEaten(); }
22.857143
106
0.628125
974c5c2a8c7403ab4d50628b70c73d0b2bb150e3
2,200
hpp
C++
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
2
2019-11-13T13:57:37.000Z
2019-11-25T09:55:17.000Z
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
srcs/boxpp/boxpp/base/systems/Barrior.hpp
whoamiho1006/boxpp
5de2c5f9b2303ac6f539192f6407e9acf9144f8b
[ "MIT" ]
null
null
null
#pragma once #include <boxpp/base/BaseMacros.hpp> #include <boxpp/base/BaseTypes.hpp> #include <boxpp/base/opacities/posix.hpp> #include <boxpp/base/opacities/windows.hpp> namespace boxpp { /* Barrior is for guarding specific blocks. */ class BOXPP FBarrior { public: FASTINLINE FBarrior() { #if PLATFORM_WINDOWS w32_compat::InitializeCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_init(&__MUTEX__, nullptr); #endif } FASTINLINE ~FBarrior() { #if PLATFORM_WINDOWS w32_compat::DeleteCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_destroy(&__MUTEX__); #endif } public: /* Enter to behind of barrior. */ FASTINLINE void Enter() const { #if PLATFORM_WINDOWS if (!w32_compat::TryEnterCriticalSection(&__CS__)) w32_compat::EnterCriticalSection(&__CS__); #endif #if PLATFORM_POSIX if (pthread_mutex_trylock(&__MUTEX__)) pthread_mutex_lock(&__MUTEX__); #endif } /* Try enter to behind of barrior. */ FASTINLINE bool TryEnter() const { register bool RetVal = false; #if PLATFORM_WINDOWS RetVal = w32_compat::TryEnterCriticalSection(&__CS__); #endif #if PLATFORM_POSIX RetVal = !pthread_mutex_trylock(&__MUTEX__); #endif return RetVal; } /* Leave from behind of barrior. */ FASTINLINE void Leave() const { #if PLATFORM_WINDOWS w32_compat::LeaveCriticalSection(&__CS__); #endif #if PLATFORM_POSIX pthread_mutex_unlock(&__MUTEX__); #endif } private: #if PLATFORM_WINDOWS mutable w32_compat::CRITICAL_SECTION __CS__; #endif #if PLATFORM_POSIX mutable pthread_mutex_t __MUTEX__; #endif }; /* Barrior scope. */ class FBarriorScope { public: FASTINLINE FBarriorScope(FBarrior& Barrior) : Barrior(&Barrior) { Barrior.Enter(); } FASTINLINE FBarriorScope(const FBarrior& Barrior) : Barrior(&Barrior) { Barrior.Enter(); } FASTINLINE ~FBarriorScope() { Barrior->Leave(); } private: const FBarrior* Barrior; }; #define BOX_BARRIOR_SCOPED(BarriorInstance) \ boxpp::FBarriorScope BOX_CONCAT(__Scope_At_, __LINE__) (BarriorInstance) #define BOX_DO_WITH_BARRIOR(BarriorInstance, ...) \ if (true) { BOX_BARRIOR_SCOPED(BarriorInstance); __VA_ARGS__ } }
20.754717
73
0.735
9752b0ceb7349ca95afc55b5ed16da2d464af0a3
3,746
cpp
C++
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
1
2020-05-02T14:33:42.000Z
2020-05-02T14:33:42.000Z
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
null
null
null
test/core/vector_specialisation_test.cpp
marovira/apollo
79920864839066c4e24d87de92c36dde4a315b10
[ "BSD-3-Clause" ]
null
null
null
#include <core/vector.hpp> #include <catch2/catch.hpp> TEMPLATE_TEST_CASE( "[Vector] - specialised constructors", "[core]", float, double, int) { SECTION("Empty constructor: size 2") { core::Vector2<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); } SECTION("Empty constructor: size 3") { core::Vector3<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); REQUIRE(v.z == TestType{0}); } SECTION("Empty constructor: size 4") { core::Vector4<TestType> v; REQUIRE(v.x == TestType{0}); REQUIRE(v.y == TestType{0}); REQUIRE(v.z == TestType{0}); REQUIRE(v.w == TestType{0}); } SECTION("Uniform constructor: size 2") { core::Vector2<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); } SECTION("Uniform constructor: size 3") { core::Vector3<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); REQUIRE(v.z == TestType{1}); } SECTION("Uniform constructor: size 2") { core::Vector4<TestType> v{TestType{1}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{1}); REQUIRE(v.z == TestType{1}); REQUIRE(v.w == TestType{1}); } SECTION("Parameterised constructor: size 2") { core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); } SECTION("Parameterised constructor: size 3") { core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); REQUIRE(v.z == TestType{3}); } SECTION("Parameterised constructor: size 4") { core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v.x == TestType{1}); REQUIRE(v.y == TestType{2}); REQUIRE(v.z == TestType{3}); REQUIRE(v.w == TestType{4}); } } TEMPLATE_TEST_CASE( "[Vector] - specialised operator[]", "[core]", float, double, int) { SECTION("Non-const version: size 2") { core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); } SECTION("Const version: size 2") { const core::Vector2<TestType> v{TestType{1}, TestType{2}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); } SECTION("Non-const version: size 3") { core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); } SECTION("Const version: size 3") { const core::Vector3<TestType> v{TestType{1}, TestType{2}, TestType{3}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); } SECTION("Non-const version: size 4") { core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); REQUIRE(v[3] == TestType{4}); } SECTION("Const version: size 4") { const core::Vector4<TestType> v{ TestType{1}, TestType{2}, TestType{3}, TestType{4}}; REQUIRE(v[0] == TestType{1}); REQUIRE(v[1] == TestType{2}); REQUIRE(v[2] == TestType{3}); REQUIRE(v[3] == TestType{4}); } }
24.973333
79
0.533102
97530a740cbd510778a20901f769a6207c46fb76
2,688
cpp
C++
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
3
2021-08-07T07:01:34.000Z
2021-08-07T07:03:02.000Z
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
cpp/cpp/685. Redundant Connection II.cpp
longwangjhu/LeetCode
a5c33e8d67e67aedcd439953d96ac7f443e2817b
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/redundant-connection-ii/ // In this problem, a rooted tree is a directed graph such that, there is exactly // one node (the root) for which all other nodes are descendants of this node, plus // every node has exactly one parent, except for the root node which has no // parents. // The given input is a directed graph that started as a rooted tree with n nodes // (with distinct values from 1 to n), with one additional directed edge added. The // added edge has two different vertices chosen from 1 to n, and was not an edge // that already existed. // The resulting graph is given as a 2D-array of edges. Each element of edges is a // pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where // ui is a parent of child vi. // Return an edge that can be removed so that the resulting graph is a rooted tree // of n nodes. If there are multiple answers, return the answer that occurs last in // the given 2D-array. //////////////////////////////////////////////////////////////////////////////// // union find not work, since edge has direction may cause cycle // search for node with two parents -> edgeA, edgeB // perform union find without edgeB // -> 1) if tree is valid, return edgeB // -> 2) if found a cycle return a) edgeA or the causing edge // -> 3) return edgeB class Solution { public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { int n = edges.size(); vector<int> edgeA, edgeB; // search for node with two parents for (int i = 1; i <= n; ++i) parents[i] = 0; for (auto& edge : edges) { // (parent) edge[0] -> (child) edge[1] if (parents[edge[1]] == 0) { // new edge parents[edge[1]] = edge[0]; } else { // edge with two parents edgeA = {parents[edge[1]], edge[1]}; edgeB = edge; } } // union find without edgeB for (int i = 1; i <= n; ++i) parents[i] = i; for (auto& edge : edges) { if (edge == edgeB) continue; // skip edgeB if (!unionNodes(edge[0], edge[1])) { if (edgeA.empty()) return edge; return edgeA; } } return edgeB; } private: unordered_map<int, int> parents; int find(int x) { if (parents[x] != x) parents[x] = find(parents[x]); return parents[x]; } bool unionNodes(int x, int y) { // (parent) x -> (child) y int xP = find(x); if (xP == y) return false; // found a cycle int yP = find(y); if (xP != yP) parents[yP] = xP; return true; } };
38.4
83
0.579241
97545d9fcf31e1ca0b370f0a32ea117b6cfedd49
3,899
cpp
C++
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
170
2015-10-20T08:31:16.000Z
2021-12-01T01:47:32.000Z
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
42
2015-10-20T23:20:17.000Z
2022-03-18T05:47:08.000Z
src/astra/astra_point.cpp
Delicode/astra
2654b99102b999a15d3221b0e5a11bb5291f7689
[ "Apache-2.0" ]
83
2015-10-22T14:53:00.000Z
2021-11-04T03:09:48.000Z
// This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Orbbec 3D // // 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. // // Be excellent to each other. #include <astra_core/capi/astra_types.h> #include <astra/capi/astra_ctypes.h> #include "astra_generic_stream_api.hpp" #include <astra/capi/streams/point_capi.h> #include <astra/capi/streams/point_types.h> #include <astra/capi/streams/stream_types.h> #include <string.h> #include <cassert> #include <astra/capi/streams/image_capi.h> ASTRA_BEGIN_DECLS ASTRA_API_EX astra_status_t astra_reader_get_pointstream(astra_reader_t reader, astra_pointstream_t* pointStream) { return astra_reader_get_stream(reader, ASTRA_STREAM_COLOR, DEFAULT_SUBTYPE, pointStream); } ASTRA_API_EX astra_status_t astra_frame_get_pointframe(astra_reader_frame_t readerFrame, astra_pointframe_t* pointFrame) { return astra_reader_get_imageframe(readerFrame, ASTRA_STREAM_POINT, DEFAULT_SUBTYPE, pointFrame); } ASTRA_API_EX astra_status_t astra_frame_get_pointframe_with_subtype(astra_reader_frame_t readerFrame, astra_stream_subtype_t subtype, astra_pointframe_t* pointFrame) { return astra_reader_get_imageframe(readerFrame, ASTRA_STREAM_POINT, subtype, pointFrame); } ASTRA_API_EX astra_status_t astra_pointframe_get_frameindex(astra_pointframe_t pointFrame, astra_frame_index_t* index) { return astra_generic_frame_get_frameindex(pointFrame, index); } ASTRA_API_EX astra_status_t astra_pointframe_get_data_byte_length(astra_pointframe_t pointFrame, size_t* byteLength) { return astra_imageframe_get_data_byte_length(pointFrame, byteLength); } ASTRA_API_EX astra_status_t astra_pointframe_get_data_ptr(astra_pointframe_t pointFrame, astra_vector3f_t** data, size_t* byteLength) { void* voidData = nullptr; astra_imageframe_get_data_ptr(pointFrame, &voidData, byteLength); *data = static_cast<astra_vector3f_t*>(voidData); return ASTRA_STATUS_SUCCESS; } ASTRA_API_EX astra_status_t astra_pointframe_copy_data(astra_pointframe_t pointFrame, astra_vector3f_t* data) { return astra_imageframe_copy_data(pointFrame, data); } ASTRA_API_EX astra_status_t astra_pointframe_get_metadata(astra_pointframe_t pointFrame, astra_image_metadata_t* metadata) { return astra_imageframe_get_metadata(pointFrame, metadata); } ASTRA_END_DECLS
41.478723
108
0.595794
97545f1944b626487fa100e059cfbcfc2a64195d
129
cpp
C++
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
dependencies/physx-4.1/source/geomutils/src/pcm/GuPCMContactSphereSphere.cpp
realtehcman/-UnderwaterSceneProject
72cbd375ef5e175bed8f4e8a4d117f5340f239a4
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:d16864b0d69d3a425328f013d6bb2842892c448c6a7cdc5077078ae6564113f8 size 3329
32.25
75
0.883721
975467ff92a3e30d15262dd5d6e95dc133ef5092
1,795
cpp
C++
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/test_common/testutil.cpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
#include <ysu/crypto_lib/random_pool.hpp> #include <ysu/node/testing.hpp> #include <ysu/test_common/testutil.hpp> #include <gtest/gtest.h> #include <cstdlib> #include <numeric> using namespace std::chrono_literals; /* Convenience constants for tests which are always on the test network */ namespace { ysu::ledger_constants dev_constants (ysu::ysu_networks::ysu_dev_network); } ysu::keypair const & ysu::zero_key (dev_constants.zero_key); ysu::keypair const & ysu::dev_genesis_key (dev_constants.dev_genesis_key); ysu::account const & ysu::ysu_dev_account (dev_constants.ysu_dev_account); std::string const & ysu::ysu_dev_genesis (dev_constants.ysu_dev_genesis); ysu::account const & ysu::genesis_account (dev_constants.genesis_account); ysu::block_hash const & ysu::genesis_hash (dev_constants.genesis_hash); ysu::uint128_t const & ysu::genesis_amount (dev_constants.genesis_amount); ysu::account const & ysu::burn_account (dev_constants.burn_account); void ysu::wait_peer_connections (ysu::system & system_a) { auto wait_peer_count = [&system_a](bool in_memory) { auto num_nodes = system_a.nodes.size (); system_a.deadline_set (20s); size_t peer_count = 0; while (peer_count != num_nodes * (num_nodes - 1)) { ASSERT_NO_ERROR (system_a.poll ()); peer_count = std::accumulate (system_a.nodes.cbegin (), system_a.nodes.cend (), std::size_t{ 0 }, [in_memory](auto total, auto const & node) { if (in_memory) { return total += node->network.size (); } else { auto transaction = node->store.tx_begin_read (); return total += node->store.peer_count (transaction); } }); } }; // Do a pre-pass with in-memory containers to reduce IO if still in the process of connecting to peers wait_peer_count (true); wait_peer_count (false); }
33.240741
145
0.732591
975504aa4082edaf5699b688a1441696cf8721dc
24,484
cpp
C++
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/qt/transactiontablemodel.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011-2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #include <qt/transactiontablemodel.h> #include <qt/addresstablemodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/transactiondesc.h> #include <qt/transactionrecord.h> #include <qt/walletmodel.h> #include <core_io.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <sync.h> #include <uint256.h> #include <util/system.h> #include <validation.h> #include <QColor> #include <QDateTime> #include <QDebug> #include <QIcon> #include <QList> //金额列右对齐,包含数字 static int column_alignments[] = { /*:AlignLeft qt::AlignvCenter,/*状态*/ qt::AlignLeft qt::AlignvCenter,/*仅监视*/ /*:AlignLeft qt::AlignvCenter,/*日期*/ qt::AlignLeft qt::AlignvCenter,/*类型*/ /*:AlignLeft qt::AlignvCenter,/*地址*/ qt::AlignRight qt::AlignvCenter/*数量*/ }; //Tx型列表排序/二进制搜索的比较运算符 struct TxLessThan { bool operator()(const TransactionRecord &a, const TransactionRecord &b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const TransactionRecord &b) const { return a < b.hash; } }; //私有实施 class TransactionTablePriv { public: explicit TransactionTablePriv(TransactionTableModel *_parent) : parent(_parent) { } TransactionTableModel *parent; /*钱包的本地缓存。 *根据定义,它与cwallet的顺序相同。 *按sha256排序。 **/ QList<TransactionRecord> cachedWallet; /*从核心重新查询整个钱包。 **/ void refreshWallet(interfaces::Wallet& wallet) { qDebug() << "TransactionTablePriv::refreshWallet"; cachedWallet.clear(); { for (const auto& wtx : wallet.getWalletTxs()) { if (TransactionRecord::showTransaction()) { cachedWallet.append(TransactionRecord::decomposeTransaction(wtx)); } } } } /*逐步更新钱包模型,以同步钱包模型 和核心的那个。 调用已添加、删除或更改的事务。 **/ void updateWallet(interfaces::Wallet& wallet, const uint256 &hash, int status, bool showTransaction) { qDebug() << "TransactionTablePriv::updateWallet: " + QString::fromStdString(hash.ToString()) + " " + QString::number(status); //在模型中查找此事务的边界 QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); if(status == CT_UPDATED) { if(showTransaction && !inModel) /*tus=ct_new;/*不在模型中,但要显示,视为新的*/ 如果(!)ShowTransaction和InModel) status=ct_deleted;/*在模型中,但要隐藏,视为已删除*/ } qDebug() << " inModel=" + QString::number(inModel) + " Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) + " showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status); switch(status) { case CT_NEW: if(inModel) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is already in model"; break; } if(showTransaction) { //在钱包中查找交易 interfaces::WalletTx wtx = wallet.getWalletTx(hash); if(!wtx.tx) { qWarning() << "TransactionTablePriv::updateWallet: Warning: Got CT_NEW, but transaction is not in wallet"; break; } //添加--在正确位置插入 QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wtx); /*!to insert.isEmpty())/*仅当要插入的内容时*/ { parent->beginInsertRows(qmodelIndex(),lowerindex,lowerindex+toinsert.size()-1); int insert_idx=lowerindex; 用于(const transactionrecord&rec:toinsert) { cachedWallet.insert(插入_idx,rec); 插入_idx+=1; } parent->endinsertrows(); } } 断裂; 删除的案例: 如果(!)内模) { qwarning()<“transactionTablepriv::updateWallet:warning:got ct_deleted,but transaction is not in model”; 断裂; } //已删除--从表中删除整个事务 parent->beginremoverws(qmodelindex(),lowerindex,upperindex-1); cachedWallet.erase(下,上); parent->endremoves(); 断裂; 案例CT更新: //其他更新——不做任何事情,状态更新将处理此问题,并且只计算 //可见事务。 对于(int i=lowerindex;i<upperindex;i++) transactionrecord*rec=&cachedwallet[i]; rec->status.needsupdate=true; } 断裂; } } int siz() { 返回cachedWallet.size(); } 交易记录*索引(接口::Wallet&Wallet,int IDX) { 如果(idx>=0&&idx<cachedWallet.size()) { transactionrecord*rec=&cachedwallet[idx]; //预先获取所需的锁。这样就避免了图形用户界面 //如果核心持有锁的时间更长,则会卡住- //例如,在钱包重新扫描期间。 / / //如果需要状态更新(自上次检查以来出现块), //从钱包更新此交易的状态。否则, //只需重新使用缓存状态。 接口::wallettxstatus wtx; int数字块; Int64阻塞时间; if(wallet.trygettxstatus(rec->hash,wtx,numblocks,block_time)&&rec->statusupdateeneeded(numblocks)); rec->updateStatus(wtx,numblocks,block_time); } 返回记录; } 返回null pTR; } qString描述(interfaces::node&node,interfaces::wallet&wallet,transactionrecord*rec,int unit) { 返回事务描述::tohtml(节点、钱包、记录、单位); } qstring gettxhex(接口::wallet&wallet,transactionrecord*rec) { auto tx=wallet.gettx(rec->hash); 如果(Tx){ std::string strhex=encodehextx(*tx); 返回qstring::fromstdstring(strhex); } 返回qString(); } }; TransactionTableModel::TransactionTableModel(const platformStyle*_platformStyle,walletModel*父级): QabstractTableModel(父级) 墙模型(父) priv(新交易表priv(this)), fprocessingQueuedTransactions(假), 平台样式(_PlatformStyle) { 列<<qString()<<qString()<<tr(“日期”)<<tr(“类型”)<<tr(“标签”)<<bitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); priv->refreshwallet(walletmodel->wallet()); Connect(walletModel->getOptionsModel(),&OptionsModel::DisplayUnitChanged,this,&TransactionTableModel::UpdateDisplayUnit); subscriptOCoreginals(); } TransactionTableModel::~TransactionTableModel()。 { 取消订阅coresignals(); 删除PRIV; } /**将列标题更新为“amount(displayUnit)”,并发出headerDataChanged()信号,以便表头作出反应。*/ void TransactionTableModel::updateAmountColumnTitle() { columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit()); Q_EMIT headerDataChanged(Qt::Horizontal,Amount,Amount); } void TransactionTableModel::updateTransaction(const QString &hash, int status, bool showTransaction) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(walletModel->wallet(), updated, status, showTransaction); } void TransactionTableModel::updateConfirmations() { //自上次投票以来,出现了一些障碍。 //失效状态(确认数量)和(可能)描述 //对于所有行。qt足够智能,只实际请求 //可见行。 Q_EMIT dataChanged(index(0, Status), index(priv->size()-1, Status)); Q_EMIT dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress)); } int TransactionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const { QString status; switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)","",wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed"); break; case TransactionStatus::Abandoned: status = tr("Abandoned"); break; case TransactionStatus::Confirming: status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations); break; case TransactionStatus::Confirmed: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Conflicted: status = tr("Conflicted"); break; case TransactionStatus::Immature: status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in); break; case TransactionStatus::NotAccepted: status = tr("Generated but not accepted"); break; } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const { if(wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } return QString(); } /*在通讯簿中查找地址,如果找到,则返回标签(地址) 否则只需返回(地址) **/ QString TransactionTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label; } if(label.isEmpty() || tooltip) { description += QString(" (") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::Generated: return tr("Mined"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::Generated: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } } QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const { QString watchAddress; if (tooltip) { //通过添加“(仅监视)”标记涉及仅监视地址的事务。 watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : ""; } switch(wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: return lookupAddress(wtx->address, tooltip) + watchAddress; case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address) + watchAddress; case TransactionRecord::SendToSelf: default: return tr("(n/a)") + watchAddress; } } QVariant TransactionTableModel::addressColor(const TransactionRecord *wtx) const { //以不太明显的颜色显示不带标签的地址 switch(wtx->type) { case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if(label.isEmpty()) return COLOR_BAREADDRESS; } break; case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; default: break; } return QVariant(); } QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const { QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators); if(showUnconfirmed) { if(!wtx->status.countsForBalance) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return COLOR_TX_STATUS_OPENUNTILDATE; case TransactionStatus::Unconfirmed: return QIcon(":/icons/transaction_0"); case TransactionStatus::Abandoned: return QIcon(":/icons/transaction_abandoned"); case TransactionStatus::Confirming: switch(wtx->status.depth) { case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::Confirmed: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::Conflicted: return QIcon(":/icons/transaction_conflicted"); case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); default: return COLOR_BLACK; } } QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord *wtx) const { if (wtx->involvesWatchAddress) return QIcon(":/icons/eye"); else return QVariant(); } QString TransactionTableModel::formatTooltip(const TransactionRecord *rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if(rec->type==TransactionRecord::RecvFromOther || rec->type==TransactionRecord::SendToOther || rec->type==TransactionRecord::SendToAddress || rec->type==TransactionRecord::RecvWithAddress) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer()); switch(role) { case RawDecorationRole: switch(index.column()) { case Status: return txStatusDecoration(rec); case Watchonly: return txWatchonlyDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DecorationRole: { QIcon icon = qvariant_cast<QIcon>(index.data(RawDecorationRole)); return platformStyle->TextColorIcon(icon); } case Qt::DisplayRole: switch(index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec, true, BitcoinUnits::separatorAlways); } break; case Qt::EditRole: //编辑角色用于排序,因此返回未格式化的值 switch(index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case Watchonly: return (rec->involvesWatchAddress ? 1 : 0); case ToAddress: return formatTxToAddress(rec, true); case Amount: return qint64(rec->credit + rec->debit); } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: //对放弃的交易使用“危险”颜色 if(rec->status.status == TransactionStatus::Abandoned) { return COLOR_TX_STATUS_DANGER; } //未确认(但不未成熟),因为交易是灰色的 if(!rec->status.countsForBalance && rec->status.status != TransactionStatus::Immature) { return COLOR_UNCONFIRMED; } if(index.column() == Amount && (rec->credit+rec->debit) < 0) { return COLOR_NEGATIVE; } if(index.column() == ToAddress) { return addressColor(rec); } break; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case WatchonlyRole: return rec->involvesWatchAddress; case WatchonlyDecorationRole: return txWatchonlyDecoration(rec); case LongDescriptionRole: return priv->describe(walletModel->node(), walletModel->wallet(), rec, walletModel->getOptionsModel()->getDisplayUnit()); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return qint64(rec->credit + rec->debit); case TxHashRole: return rec->getTxHash(); case TxHexRole: return priv->getTxHex(walletModel->wallet(), rec); case TxPlainTextRole: { QString details; QDateTime date = QDateTime::fromTime_t(static_cast<uint>(rec->time)); QString txLabel = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); details.append(date.toString("M/d/yy HH:mm")); details.append(" "); details.append(formatTxStatus(rec)); details.append(". "); if(!formatTxType(rec).isEmpty()) { details.append(formatTxType(rec)); details.append(" "); } if(!rec->address.empty()) { if(txLabel.isEmpty()) details.append(tr("(no label)") + " "); else { details.append("("); details.append(txLabel); details.append(") "); } details.append(QString::fromStdString(rec->address)); details.append(" "); } details.append(formatTxAmount(rec, false, BitcoinUnits::separatorNever)); return details; } case ConfirmedRole: return rec->status.countsForBalance; case FormattedAmountRole: //用于复制/导出,因此不包括分隔符 return formatTxAmount(rec, false, BitcoinUnits::separatorNever); case StatusRole: return rec->status.status; } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case Watchonly: return tr("Whether or not a watch-only address is involved in this transaction."); case ToAddress: return tr("User-defined intent/purpose of the transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); TransactionRecord *data = priv->index(walletModel->wallet(), row); if(data) { return createIndex(row, column, priv->index(walletModel->wallet(), row)); } return QModelIndex(); } void TransactionTableModel::updateDisplayUnit() { //发出datachanged以使用当前单位更新amount列 updateAmountColumnTitle(); Q_EMIT dataChanged(index(0, Amount), index(priv->size()-1, Amount)); } //排队通知以显示非冻结进度对话框,例如用于重新扫描 struct TransactionNotification { public: TransactionNotification() {} TransactionNotification(uint256 _hash, ChangeType _status, bool _showTransaction): hash(_hash), status(_status), showTransaction(_showTransaction) {} void invoke(QObject *ttm) { QString strHash = QString::fromStdString(hash.GetHex()); qDebug() << "NotifyTransactionChanged: " + strHash + " status= " + QString::number(status); QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, strHash), Q_ARG(int, status), Q_ARG(bool, showTransaction)); } private: uint256 hash; ChangeType status; bool showTransaction; }; static bool fQueueNotifications = false; static std::vector< TransactionNotification > vQueueNotifications; static void NotifyTransactionChanged(TransactionTableModel *ttm, const uint256 &hash, ChangeType status) { //在钱包中查找交易 //确定是否显示事务(在这里确定,以便在GUI线程中不需要重新锁定) bool showTransaction = TransactionRecord::showTransaction(); TransactionNotification notification(hash, status, showTransaction); if (fQueueNotifications) { vQueueNotifications.push_back(notification); return; } notification.invoke(ttm); } static void ShowProgress(TransactionTableModel *ttm, const std::string &title, int nProgress) { if (nProgress == 0) fQueueNotifications = true; if (nProgress == 100) { fQueueNotifications = false; if (vQueueNotifications.size() > 10) //防止气球垃圾邮件,最多显示10个气球 QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true)); for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) { if (vQueueNotifications.size() - i <= 10) QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false)); vQueueNotifications[i].invoke(ttm); } std::vector<TransactionNotification >().swap(vQueueNotifications); //清楚的 } } void TransactionTableModel::subscribeToCoreSignals() { //将信号连接到钱包 m_handler_transaction_changed = walletModel->wallet().handleTransactionChanged(std::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2)); m_handler_show_progress = walletModel->wallet().handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2)); } void TransactionTableModel::unsubscribeFromCoreSignals() { //断开钱包信号 m_handler_transaction_changed->disconnect(); m_handler_show_progress->disconnect(); }
31.592258
172
0.628247
97562bbcc8ce6931c6929edab6d5e82527117d3a
4,330
cpp
C++
test/MutationTest.cpp
ATsahikian/PeProtector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
43
2016-07-30T13:50:21.000Z
2021-06-17T22:45:00.000Z
test/MutationTest.cpp
ATsahikian/pe-protector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
null
null
null
test/MutationTest.cpp
ATsahikian/pe-protector
4e005ea636a5679b82c9e58e09a0de53618896c5
[ "MIT" ]
16
2016-09-08T09:10:27.000Z
2020-06-14T00:30:59.000Z
#define BOOST_TEST_MODULE mutation test #include <boost/test/included/unit_test.hpp> #include "pe-protector/Mutation.h" using namespace NPeProtector; BOOST_AUTO_TEST_SUITE(MutationTest); // method for testing mutateCommands with Mov instruction BOOST_AUTO_TEST_CASE(testMutateCommandsMov) { // create command for testing "MOV EAX, EBX" SOperand operand1; operand1.mType = NOperand::REG32; operand1.mRegister = NRegister::EAX; SOperand operand2; operand2.mType = NOperand::REG32; operand2.mRegister = NRegister::EBX; SInstruction instruction{ NPrefix::NON, NInstruction::MOV, {operand1, operand2}}; SCommand movCommand; movCommand.mType = NCommand::INSTRUCTION; movCommand.mInstruction = instruction; std::vector<SCommand> commands = {movCommand}; // pass command "MOV EAX, EBX" mutateCommands(commands); // create instruction "PUSH EBX" SCommand pushCommand; pushCommand.mType = NCommand::INSTRUCTION; pushCommand.mInstruction.mType = NInstruction::PUSH; pushCommand.mInstruction.mOperands.push_back(operand2); // create instruction "POP EAX" SCommand popCommand; popCommand.mType = NCommand::INSTRUCTION; popCommand.mInstruction.mType = NInstruction::POP; popCommand.mInstruction.mOperands.push_back(operand1); std::vector<SCommand> expectedResult = {pushCommand, popCommand}; // compare results BOOST_TEST(expectedResult[0].mType == commands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mType == commands[0].mInstruction.mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mType == commands[0].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mRegister == commands[0].mInstruction.mOperands[0].mRegister); BOOST_TEST(expectedResult[1].mType == commands[1].mType); BOOST_TEST(expectedResult[1].mInstruction.mType == commands[1].mInstruction.mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mType == commands[1].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mRegister == commands[1].mInstruction.mOperands[0].mRegister); } // method for testing mutateCommands with Push instruction BOOST_AUTO_TEST_CASE(testMutateCommandsPush) { // create instruction "PUSH EAX" SOperand operand1; operand1.mType = NOperand::REG32; operand1.mRegister = NRegister::EAX; SInstruction instruction{NPrefix::NON, NInstruction::PUSH, {operand1}}; SCommand pushCommand; pushCommand.mType = NCommand::INSTRUCTION; pushCommand.mInstruction = instruction; std::vector<SCommand> commands = {pushCommand}; // pass instruction "PUSH EAX" mutateCommands(commands); // create instruction "SUB ESP, 4" SCommand subCommand; subCommand.mType = NCommand::INSTRUCTION; subCommand.mInstruction.mType = NInstruction::SUB; SOperand espOperand; espOperand.mType = NOperand::REG32; espOperand.mRegister = NRegister::ESP; subCommand.mInstruction.mOperands.push_back(espOperand); SOperand constOperand; constOperand.mType = NOperand::CONSTANT; constOperand.mConstant.mValue = 4; subCommand.mInstruction.mOperands.push_back(constOperand); // create instruction "MOV DWORD PTR [ESP], EAX" SCommand movCommand; movCommand.mType = NCommand::INSTRUCTION; movCommand.mInstruction.mType = NInstruction::MOV; SOperand memOperand; memOperand.mType = NOperand::MEM32; memOperand.mMemory.mRegisters.push_back(NRegister::ESP); movCommand.mInstruction.mOperands.push_back(memOperand); movCommand.mInstruction.mOperands.push_back(operand1); std::vector<SCommand> expectedResult = {subCommand, movCommand}; // compare results BOOST_TEST(expectedResult[0].mType == commands[0].mType); BOOST_TEST(expectedResult[0].mInstruction.mType == commands[0].mInstruction.mType); BOOST_TEST(expectedResult[0].mInstruction.mOperands[0].mType == commands[0].mInstruction.mOperands[0].mType); BOOST_TEST(expectedResult[1].mType == commands[1].mType); BOOST_TEST(expectedResult[1].mInstruction.mType == commands[1].mInstruction.mType); BOOST_TEST(expectedResult[1].mInstruction.mOperands[0].mType == commands[1].mInstruction.mOperands[0].mType); } BOOST_AUTO_TEST_SUITE_END();
34.365079
73
0.748037
9758a9719e4fec47c6d0eb4501ade7763f26887c
1,913
cpp
C++
openqube/testing/testatom.cpp
OpenChemistry/openqube
dc396bcf6c74cbfd9fb94201312e70bb377b0805
[ "BSD-3-Clause" ]
2
2015-05-05T19:49:55.000Z
2021-03-30T12:27:40.000Z
openqube/testing/testatom.cpp
OpenChemistry/openqube
dc396bcf6c74cbfd9fb94201312e70bb377b0805
[ "BSD-3-Clause" ]
null
null
null
openqube/testing/testatom.cpp
OpenChemistry/openqube
dc396bcf6c74cbfd9fb94201312e70bb377b0805
[ "BSD-3-Clause" ]
4
2015-01-29T16:25:12.000Z
2021-01-06T17:47:47.000Z
#include <iostream> #include <openqube/molecule.h> #include <openqube/atom.h> #include <Eigen/Geometry> using std::cout; using std::cerr; using std::endl; using OpenQube::Atom; using OpenQube::Molecule; using Eigen::Vector3d; namespace { template<typename A, typename B> void checkResult(const A& result, const B& expected, bool &error) { if (result != expected) { cerr << "Error, expected result " << expected << ", got " << result << endl; error = true; } } } short testAtomConst(const Molecule& mol, size_t index) { return mol.atom(index).atomicNumber(); } int testatom(int , char *[]) { bool error = false; cout << "Testing the atom class..." << endl; Molecule mol; Atom a = mol.addAtom(Vector3d(0.0, 1.0, 0.0), 1); checkResult(a.isValid(), true, error); checkResult(a.isHydrogen(), true, error); checkResult(a.atomicNumber(), 1, error); a.setAtomicNumber(69); checkResult(a.isHydrogen(), false, error); checkResult(a.atomicNumber(), 69, error); checkResult(a.pos(), Vector3d(0.0, 1.0, 0.0), error); a.setPos(Vector3d(1.0, 1.0, 1.0)); checkResult(a.pos(), Vector3d(1.0, 1.0, 1.0), error); Atom a2 = mol.atom(1); checkResult(a2.isValid(), false, error); checkResult(a2.isHydrogen(), false, error); a2.setAtomicNumber(1); checkResult(a2.isHydrogen(), false, error); a2.setPos(Vector3d(1.0, 1.0, 1.0)); checkResult(a2.pos(), Vector3d::Zero(), error); cout << "Number of atoms = " << mol.numAtoms() << endl; Atom carbon = mol.addAtom(Vector3d::Zero(), 6); cout << "Number of atoms = " << mol.numAtoms() << endl; const Atom carbonCopy = mol.atom(1); checkResult(carbon.atomicNumber(), carbonCopy.atomicNumber(), error); checkResult(carbon.atomicNumber(), testAtomConst(mol, 1), error); carbon.setAtomicNumber(7); checkResult(carbon.atomicNumber(), carbonCopy.atomicNumber(), error); mol.print(); return error ? 1 : 0; }
24.525641
80
0.664924
9759ce0c8aec21542ab1727ba287d9376bdd192c
606
cpp
C++
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
src/vkfw_core/gfx/vk/pipeline/ComputePipeline.cpp
dasmysh/VulkanFramework_Lib
baeaeb3158d23187f2ffa5044e32d8a5145284aa
[ "MIT" ]
null
null
null
/** * @file ComputePipeline.cpp * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2016.10.30 * * @brief Implementation of a vulkan compute pipeline object. */ #include "gfx/vk/pipeline/ComputePipeline.h" #include "gfx/vk/LogicalDevice.h" #include "core/resources/ShaderManager.h" namespace vkfw_core::gfx { ComputePipeline::ComputePipeline(const std::string& shaderStageId, gfx::LogicalDevice* device) : Resource(shaderStageId, device) { throw std::runtime_error("NOT YET IMPLEMENTED!"); } ComputePipeline::~ComputePipeline() = default; }
25.25
100
0.709571
975cebfc63316babaaa98c51f6a47676e5c47673
169
cpp
C++
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
Generic/VSC.cpp
jbat100/VirtualSoundControl
f84ba15bba4bfce579c185e04df0e1be4f419cd7
[ "MIT" ]
null
null
null
#include "VSC.h" #include <boost/date_time/posix_time/posix_time.hpp> VSC::Time VSC::CurrentTime() { return boost::posix_time::microsec_clock::universal_time(); }
18.777778
63
0.739645
975e930eb1006c6956faf01e14b61bb51426f222
6,452
hpp
C++
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
include/cbr_drivers/v4l2_driver.hpp
yamaha-bps/cbr_drivers
64e971c0a7e79c414e81fe2ac32e6360adb266eb
[ "MIT" ]
null
null
null
// Copyright Yamaha 2021 // MIT License // https://github.com/yamaha-bps/cbr_drivers/blob/master/LICENSE #ifndef CBR_DRIVERS__V4L2_DRIVER_HPP_ #define CBR_DRIVERS__V4L2_DRIVER_HPP_ #include <linux/videodev2.h> #include <atomic> #include <functional> #include <memory> #include <mutex> #include <string> #include <thread> #include <utility> #include <vector> #include <iostream> namespace cbr { class V4L2Driver { public: /** * Helper structures for interfacing with the driver */ struct buffer_t { void * pos; // memory location of buffer std::size_t len; // size in bytes }; struct format_t { std::string format; uint32_t width, height; float fps; }; enum class ctrl_type { INTEGER = V4L2_CTRL_TYPE_INTEGER, BOOLEAN = V4L2_CTRL_TYPE_BOOLEAN, MENU = V4L2_CTRL_TYPE_MENU }; struct ival_t { int32_t minimum; int32_t maximum; int32_t step; }; struct menu_entry_t { uint32_t index; std::string name; }; struct ctrl_t { uint32_t id; ctrl_type type; std::string name; int32_t def; // default value ival_t ival; // only populated for INTEGER, BOOLEAN std::vector<menu_entry_t> menu; // ony populated for MENU }; /** * @brief v4l2 driver for capturing image streams * * This driver is flexible in terms of management: a user can supply a callback * that is called on frames containing new buffers, and also custom allocation and * de-allocation functions for allocating said buffers. * * If no allocation functions are provided malloc()/free() is used. * * @param device the v4l object (default /dev/video0) * @param n_buf the number of buffers to use (default 4) */ explicit V4L2Driver(std::string device = "/dev/video0", uint32_t n_buf = 4); V4L2Driver(const V4L2Driver &) = delete; V4L2Driver & operator=(const V4L2Driver & other) = delete; V4L2Driver(V4L2Driver &&) = delete; V4L2Driver & operator=(V4L2Driver &&) = delete; ~V4L2Driver(); /** * @brief Set the callback * * NOTE: the callback should return quickly or frames will be missed * * The callback should have signature * void(const uint8_t *, const v4l2_pix_format &) * and is called on every new frame. */ template<typename T> void set_callback(T && cb) { cb_ = std::forward<T>(cb); } /** * @brief Set a custom allocator * * NOTE: Use only in conjuction with set_custom_deallocator * * The allocator should have signature * void *(std::size_t) * * The returned pointer is freed with the custom deallocator */ template<typename T> void set_custom_allocator(T && cb) { custom_alloc_ = std::forward<T>(cb); } /** * @brief Set a custom deallocator * * NOTE: Use only in conjuction with set_custom_allocator * * The deallocator should have signature * void(void *, std::size_t) */ template<typename T> void set_custom_deallocator(T && cb) { custom_dealloc_ = std::forward<T>(cb); } /** * @brief Initialize the driver and start capturing */ bool start(); /** * @brief Stop capturing and de-initialize the driver */ void stop(); /** * @brief Get current fps */ float get_fps(); /** * @brief List all formats supported by the device */ std::vector<format_t> list_formats(); /** * @brief Get active video format */ v4l2_pix_format get_format(); /** * @brief Request a format from v4l2 * * @param width desired frame pixel width * @param height desired frame pixel height * @param fps desired fps * @param fourcc desired image format in fourcc format (must be string with four characters) */ bool set_format(uint32_t width, uint32_t height, uint32_t fps, std::string fourcc = "YUYV"); /** * @brief List controls for the device */ std::vector<ctrl_t> list_controls(); /** * @brief Get control value for the device * * @param id control identifier * @returns the value of the control */ std::optional<int32_t> get_control(uint32_t id); /** * @brief Set control for the device * * @param id control identifier * @param value desired value for control * * @return the new value of the control (should be equal to value) */ bool set_control(uint32_t id, int32_t value); /** * @brief One-way uvc write * @param unit uvc unit (device-specific) * @param control_selector uvc control selector (device-specific) * @param buf buffer to send over UVC (length 384 for USB3, length 64 for USB2) */ bool uvc_set(uint8_t unit, uint8_t control_selector, std::vector<uint8_t> & buf); /** * @brief Two-way uvc communication (write followed by read) * @param unit uvc unit (device-specific) * @param control_selector uvc control selector (device-specific) * @param buf buffer to send over UVC (length 384 for USB3, length 64 for USB2) * * The result is written into buf in accordance with the device protocol */ bool uvc_set_get(uint8_t unit, uint8_t control_selector, std::vector<uint8_t> & buf); protected: /** * @brief Internal method to read the current frame format from V4L2 */ bool update_format(); /** * @brief Internal method for capturing frames */ bool capture_frame(); /** * @brief Internal method that runs in the streaming thread */ void streaming_fcn(); /** * @brief Wrapper around system ioctl call */ int xioctl(uint64_t request, void * arg); protected: uint32_t n_buf_; std::atomic<bool> running_{false}; std::mutex fd_mtx_; int fd_{0}; // file descriptor handle // user buffers that v4l writes into std::vector<buffer_t> buffers_{}; // current device configuration v4l2_pix_format fmt_cur_{}; float fps_{}; std::thread streaming_thread_; std::optional<std::function<void(const uint8_t *, const std::chrono::nanoseconds &, const v4l2_pix_format &)>> cb_{std::nullopt}; std::optional<std::function<void *(std::size_t)>> custom_alloc_{std::nullopt}; std::optional<std::function<void(void *, std::size_t)>> custom_dealloc_{std::nullopt}; }; /** * @brief Convert fourcc code to string */ inline static std::string fourcc_to_str(uint32_t fourcc) { std::string ret(' ', 4); for (uint32_t i = 0; i < 4; ++i) { ret[i] = ((fourcc >> (i * 8)) & 0xFF); } return ret; } } // namespace cbr #endif // CBR_DRIVERS__V4L2_DRIVER_HPP_
23.720588
94
0.6677
975ed7bf6d419192ca9632a124ac2c327956a8d4
3,797
cpp
C++
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
3
2018-05-18T19:06:27.000Z
2020-07-07T17:17:51.000Z
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
15
2018-04-25T17:41:36.000Z
2019-11-20T16:06:20.000Z
tests/ModulesFactoryTest.cpp
transdz/mesos-command-modules
5eba42137e33a1001fd1e1de9a2086f60eebe5bb
[ "Apache-2.0" ]
5
2018-04-03T09:12:29.000Z
2022-02-21T11:37:04.000Z
#include "ModulesFactory.hpp" #include <gtest/gtest.h> #include "CommandHook.hpp" #include "CommandIsolator.hpp" using namespace criteo::mesos; // *************************************** // **************** Hook ***************** // *************************************** TEST(ModulesFactoryTest, should_create_hook_with_correct_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("hook_slave_run_task_label_decorator_command"); var->set_value("command_slave_run_task_label_decorator"); var = parameters.add_parameter(); var->set_key("hook_slave_executor_environment_decorator_command"); var->set_value("command_slave_executor_environment_decorator"); var = parameters.add_parameter(); var->set_key("hook_slave_remove_executor_hook_command"); var->set_value("command_slave_remove_executor_hook"); std::unique_ptr<CommandHook> hook( dynamic_cast<CommandHook*>(createHook(parameters))); ASSERT_EQ(hook->runTaskLabelCommand().get(), Command("command_slave_run_task_label_decorator", 30)); ASSERT_EQ(hook->executorEnvironmentCommand().get(), Command("command_slave_executor_environment_decorator", 30)); ASSERT_EQ(hook->removeExecutorCommand().get(), Command("command_slave_remove_executor_hook", 30)); } TEST(ModulesFactoryTest, should_create_hook_with_empty_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("hook_slave_executor_environment_decorator_command"); var->set_value("command_slave_executor_environment_decorator"); std::unique_ptr<CommandHook> hook( dynamic_cast<CommandHook*>(createHook(parameters))); ASSERT_TRUE(hook->runTaskLabelCommand().isNone()); ASSERT_EQ(hook->executorEnvironmentCommand().get(), Command("command_slave_executor_environment_decorator", 30)); ASSERT_TRUE(hook->removeExecutorCommand().isNone()); } // *************************************** // ************** Isolator *************** // *************************************** TEST(ModulesFactoryTest, should_create_isolator_with_correct_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("isolator_prepare_command"); var->set_value("command_prepare"); var = parameters.add_parameter(); var->set_key("isolator_isolate_command"); var->set_value("command_isolate"); var = parameters.add_parameter(); var->set_key("isolator_cleanup_command"); var->set_value("command_cleanup"); std::unique_ptr<CommandIsolator> isolator( dynamic_cast<CommandIsolator*>(createIsolator(parameters))); ASSERT_EQ(isolator->prepareCommand().get(), Command("command_prepare", 30)); ASSERT_EQ(isolator->isolateCommand().get(), Command("command_isolate", 30)); ASSERT_EQ(isolator->cleanupCommand().get(), Command("command_cleanup", 30)); } TEST(ModulesFactoryTest, should_create_isolator_with_empty_parameters) { ::mesos::Parameters parameters; auto var = parameters.add_parameter(); var->set_key("module_name"); var->set_value("test"); var = parameters.add_parameter(); var->set_key("isolator_prepare_command"); var->set_value("command_prepare"); std::unique_ptr<CommandIsolator> isolator( dynamic_cast<CommandIsolator*>(createIsolator(parameters))); ASSERT_EQ(isolator->prepareCommand().get(), Command("command_prepare", 30)); ASSERT_TRUE(isolator->cleanupCommand().isNone()); ASSERT_TRUE(isolator->isolateCommand().isNone()); }
35.485981
78
0.709244
975fadcee50dd19822b817bae9019daf61fc3ee1
788
cc
C++
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
examples/omnet_module/src/AvensClient.cc
Hyodar/pairsim-cpp
86c1613b9bc2b0043e468abfe59fc1355619164c
[ "MIT" ]
null
null
null
#include "./XPlaneModel.h" #include "PairsimClient.h" Define_Module(PairsimClient); PairsimClient::PairsimClient() { tickTimeout = nullptr; } PairsimClient::~PairsimClient() { cancelAndDelete(tickTimeout); } void PairsimClient::initialize() { tickTimeout = new cMessage("tick"); client.setServerAddr("tcp://localhost:4001"); client.setTickDuration(std::chrono::seconds(1)); client.setModel(std::make_shared<XPlaneModel>(this)); EV << "Setup completed." << std::endl; client.setup(); scheduleAt(simTime() + (static_cast<double>(client.getTickDuration().count())) / 1000, tickTimeout); } void PairsimClient::handleMessage(cMessage *msg) { client.tick(); scheduleAt(simTime() + ((double) client.getTickDuration().count()) / 1000, msg); }
24.625
104
0.694162
9761c71959084ae5a77e0308ba2d9ced7f754c3d
27,752
cpp
C++
stp/sat/Solver.cpp
dslab-epfl/state-merging
abe500674ab3013f266836315e9c4ef18d0fb55c
[ "BSD-3-Clause" ]
null
null
null
stp/sat/Solver.cpp
dslab-epfl/state-merging
abe500674ab3013f266836315e9c4ef18d0fb55c
[ "BSD-3-Clause" ]
null
null
null
stp/sat/Solver.cpp
dslab-epfl/state-merging
abe500674ab3013f266836315e9c4ef18d0fb55c
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************************[Solver.C] MiniSat -- Copyright (c) 2003-2005, Niklas Een, Niklas Sorensson 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. **************************************************************************************************/ #include "Solver.h" #include "Sort.h" #include <cmath> namespace MINISAT { //================================================================================================= // Operations on clauses: /*_________________________________________________________________________________________________ | | newClause : (ps : const vec<Lit>&) (learnt : bool) -> [void] | | Description: | Allocate and add a new clause to the SAT solvers clause database. | | Input: | ps - The new clause as a vector of literals. | learnt - Is the clause a learnt clause? For learnt clauses, 'ps[0]' is assumed to be the | asserting literal. An appropriate 'enqueue()' operation will be performed on this | literal. One of the watches will always be on this literal, the other will be set to | the literal with the highest decision level. | | Effect: | Activity heuristics are updated. |________________________________________________________________________________________________@*/ bool Solver::newClause(const vec<Lit>& ps_, bool learnt, bool normalized) { vec<Lit> qs; if (!learnt && !normalized){ assert(decisionLevel() == 0); ps_.copyTo(qs); // Make a copy of the input vector. // Remove duplicates: sortUnique(qs); // Check if clause is satisfied: for (int i = 0; i < qs.size()-1; i++){ if (qs[i] == ~qs[i+1]) return true; } for (int i = 0; i < qs.size(); i++){ if (value(qs[i]) == l_True) return true; } // Remove false literals: int i, j; for (i = j = 0; i < qs.size(); i++) if (value(qs[i]) != l_False) qs[j++] = qs[i]; qs.shrink(i - j); } const vec<Lit>& ps = learnt || normalized ? ps_ : qs; // 'ps' is now the (possibly) reduced vector of literals. if (ps.size() == 0) return false; else if (ps.size() == 1){ assert(decisionLevel() == 0); return enqueue(ps[0]); }else{ // Allocate clause: Clause* c = Clause_new(ps, learnt); if (learnt){ // Put the second watch on the first literal with highest decision level: // (requires that this method is called at the level where the clause is asserting!) int i; for (i = 1; i < ps.size() && position(trailpos[var(ps[i])]) < trail_lim.last(); i++) ; (*c)[1] = ps[i]; (*c)[i] = ps[1]; // Bump, enqueue, store clause: claBumpActivity(*c); // (newly learnt clauses should be considered active) check(enqueue((*c)[0], c)); learnts.push(c); stats.learnts_literals += c->size(); }else{ // Store clause: clauses.push(c); stats.clauses_literals += c->size(); if (subsumption){ c->calcAbstraction(); for (int i = 0; i < c->size(); i++){ assert(!find(occurs[var((*c)[i])], c)); occurs[var((*c)[i])].push(c); n_occ[toInt((*c)[i])]++; touched[var((*c)[i])] = 1; if (heap.inHeap(var((*c)[i]))) updateHeap(var((*c)[i])); } } } // Watch clause: watches[toInt(~(*c)[0])].push(c); watches[toInt(~(*c)[1])].push(c); } return true; } // Disposes a clauses and removes it from watcher lists. NOTE! // Low-level; does NOT change the 'clauses' and 'learnts' vector. // void Solver::removeClause(Clause& c, bool dealloc) { //fprintf(stderr, "delete %d: ", _c); printClause(c); fprintf(stderr, "\n"); assert(c.mark() == 0); if (c.size() > 1){ assert(find(watches[toInt(~c[0])], &c)); assert(find(watches[toInt(~c[1])], &c)); remove(watches[toInt(~c[0])], &c); remove(watches[toInt(~c[1])], &c); } if (c.learnt()) stats.learnts_literals -= c.size(); else stats.clauses_literals -= c.size(); if (subsumption && !c.learnt()){ for (int i = 0; i < c.size(); i++){ if (dealloc){ assert(find(occurs[var(c[i])], &c)); remove(occurs[var(c[i])], &c); } n_occ[toInt(c[i])]--; updateHeap(var(c[i])); } } if (dealloc) xfree(&c); else c.mark(1); } bool Solver::satisfied(Clause& c) const { for (int i = 0; i < c.size(); i++) if (value(c[i]) == l_True) return true; return false; } bool Solver::strengthen(Clause& c, Lit l) { assert(decisionLevel() == 0); assert(c.size() > 1); assert(c.mark() == 0); assert(toInt(~c[0]) < watches.size()); assert(toInt(~c[1]) < watches.size()); assert(find(watches[toInt(~c[0])], &c)); assert(find(watches[toInt(~c[1])], &c)); assert(find(c,l)); if (c.learnt()) stats.learnts_literals -= 1; else stats.clauses_literals -= 1; if (c[0] == l || c[1] == l){ assert(find(watches[toInt(~l)], &c)); remove(c,l); remove(watches[toInt(~l)], &c); if (c.size() > 1){ assert(!find(watches[toInt(~c[1])], &c)); watches[toInt(~c[1])].push(&c); } else { assert(find(watches[toInt(~c[0])], &c)); remove(watches[toInt(~c[0])], &c); removeClause(c, false); } } else remove(c,l); assert(c.size() == 1 || find(watches[toInt(~c[0])], &c)); assert(c.size() == 1 || find(watches[toInt(~c[1])], &c)); if (subsumption){ assert(find(occurs[var(l)], &c)); remove(occurs[var(l)], &c); assert(!find(occurs[var(l)], &c)); c.calcAbstraction(); n_occ[toInt(l)]--; updateHeap(var(l)); } return c.size() == 1 ? enqueue(c[0]) : true; } //================================================================================================= // Minor methods: // Creates a new SAT variable in the solver. If 'decision_var' is cleared, variable will not be // used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result). // Var Solver::newVar(bool polarity, bool dvar) { int index; index = nVars(); watches .push(); // (list for positive literal) watches .push(); // (list for negative literal) reason .push(NULL); assigns .push(toInt(l_Undef)); trailpos .push(TrailPos(0,0)); activity .push(0); order .newVar(polarity,dvar); seen .push(0); touched .push(0); if (subsumption){ occurs .push(); n_occ .push(0); n_occ .push(0); heap .setBounds(index+1); } return index; } // Returns FALSE if immediate conflict. bool Solver::assume(Lit p) { trail_lim.push(trail.size()); return enqueue(p); } // Revert to the state at given level. void Solver::cancelUntil(int level) { if (decisionLevel() > level){ for (int c = trail.size()-1; c >= trail_lim[level]; c--){ Var x = var(trail[c]); assigns[x] = toInt(l_Undef); reason [x] = NULL; order.undo(x); } qhead = trail_lim[level]; trail.shrink(trail.size() - trail_lim[level]); trail_lim.shrink(trail_lim.size() - level); } } //================================================================================================= // Major methods: /*_________________________________________________________________________________________________ | | analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) -> [void] | | Description: | Analyze conflict and produce a reason clause. | | Pre-conditions: | * 'out_learnt' is assumed to be cleared. | * Current decision level must be greater than root level. | | Post-conditions: | * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'. | | Effect: | Will undo part of the trail, upto but not beyond the assumption of the current decision level. |________________________________________________________________________________________________@*/ void Solver::analyze(Clause* confl, vec<Lit>& out_learnt, int& out_btlevel) { int pathC = 0; int btpos = -1; Lit p = lit_Undef; // Generate conflict clause: // out_learnt.push(); // (leave room for the asserting literal) int index = trail.size()-1; do{ assert(confl != NULL); // (otherwise should be UIP) Clause& c = *confl; if (c.learnt()) claBumpActivity(c); for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){ Lit q = c[j]; if (!seen[var(q)] && position(trailpos[var(q)]) >= trail_lim[0]){ varBumpActivity(q); seen[var(q)] = 1; if (position(trailpos[var(q)]) >= trail_lim.last()) pathC++; else{ out_learnt.push(q); btpos = max(btpos, position(trailpos[var(q)])); } } } // Select next clause to look at: while (!seen[var(trail[index--])]) ; p = trail[index+1]; confl = reason[var(p)]; seen[var(p)] = 0; pathC--; }while (pathC > 0); out_learnt[0] = ~p; // Find correct backtrack level for (out_btlevel = trail_lim.size()-1; out_btlevel > 0 && trail_lim[out_btlevel-1] > btpos; out_btlevel--) ; int i, j; if (expensive_ccmin){ // Simplify conflict clause (a lot): // uint min_level = 0; for (i = 1; i < out_learnt.size(); i++) min_level |= abstractLevel(trailpos[var(out_learnt[i])]); // (maintain an abstraction of levels involved in conflict) out_learnt.copyTo(analyze_toclear); for (i = j = 1; i < out_learnt.size(); i++) if (reason[var(out_learnt[i])] == NULL || !analyze_removable(out_learnt[i], min_level)) out_learnt[j++] = out_learnt[i]; }else{ // Simplify conflict clause (a little): // out_learnt.copyTo(analyze_toclear); for (i = j = 1; i < out_learnt.size(); i++){ Clause& c = *reason[var(out_learnt[i])]; for (int k = 1; k < c.size(); k++) if (!seen[var(c[k])] && position(trailpos[var(c[k])]) >= trail_lim[0]){ out_learnt[j++] = out_learnt[i]; break; } } } stats.max_literals += out_learnt.size(); out_learnt.shrink(i - j); stats.tot_literals += out_learnt.size(); for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared) } // Check if 'p' can be removed. 'min_level' is used to abort early if visiting literals at a level that cannot be removed. // bool Solver::analyze_removable(Lit p, uint min_level) { analyze_stack.clear(); analyze_stack.push(p); int top = analyze_toclear.size(); while (analyze_stack.size() > 0){ assert(reason[var(analyze_stack.last())] != NULL); Clause& c = *reason[var(analyze_stack.last())]; analyze_stack.pop(); for (int i = 1; i < c.size(); i++){ Lit p = c[i]; TrailPos tp = trailpos[var(p)]; if (!seen[var(p)] && position(tp) >= trail_lim[0]){ if (reason[var(p)] != NULL && (abstractLevel(tp) & min_level) != 0){ seen[var(p)] = 1; analyze_stack.push(p); analyze_toclear.push(p); }else{ for (int j = top; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; analyze_toclear.shrink(analyze_toclear.size() - top); return false; } } } } return true; } /*_________________________________________________________________________________________________ | | analyzeFinal : (p : Lit) -> [void] | | Description: | Specialized analysis procedure to express the final conflict in terms of assumptions. | Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and | stores the result in 'out_conflict'. |________________________________________________________________________________________________@*/ void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict) { out_conflict.clear(); out_conflict.push(p); if (decisionLevel() == 0) return; seen[var(p)] = 1; int start = position(trailpos[var(p)]); for (int i = start; i >= trail_lim[0]; i--){ Var x = var(trail[i]); if (seen[x]){ if (reason[x] == NULL){ assert(position(trailpos[x]) >= trail_lim[0]); out_conflict.push(~trail[i]); }else{ Clause& c = *reason[x]; for (int j = 1; j < c.size(); j++) if (position(trailpos[var(c[j])]) >= trail_lim[0]) seen[var(c[j])] = 1; } seen[x] = 0; } } } /*_________________________________________________________________________________________________ | | enqueue : (p : Lit) (from : Clause*) -> [bool] | | Description: | Puts a new fact on the propagation queue as well as immediately updating the variable's value. | Should a conflict arise, FALSE is returned. | | Input: | p - The fact to enqueue | from - [Optional] Fact propagated from this (currently) unit clause. Stored in 'reason[]'. | Default value is NULL (no reason). | | Output: | TRUE if fact was enqueued without conflict, FALSE otherwise. |________________________________________________________________________________________________@*/ bool Solver::enqueue(Lit p, Clause* from) { if (value(p) != l_Undef) return value(p) != l_False; else{ assigns [var(p)] = toInt(lbool(!sign(p))); trailpos[var(p)] = TrailPos(trail.size(),decisionLevel()); reason [var(p)] = from; trail.push(p); return true; } } /*_________________________________________________________________________________________________ | | propagate : [void] -> [Clause*] | | Description: | Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned, | otherwise NULL. | | Post-conditions: | * the propagation queue is empty, even if there was a conflict. |________________________________________________________________________________________________@*/ Clause* Solver::propagate() { if (decisionLevel() == 0 && subsumption) return backwardSubsumptionCheck() ? NULL : propagate_tmpempty; Clause* confl = NULL; //fprintf(stderr, "propagate, qhead = %d, qtail = %d\n", qhead, qtail); while (qhead < trail.size()){ stats.propagations++; simpDB_props--; Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate. vec<Clause*>& ws = watches[toInt(p)]; Clause **i, **j, **end; for (i = j = (Clause**)ws, end = i + ws.size(); i != end;){ Clause& c = **i++; // Make sure the false literal is data[1]: Lit false_lit = ~p; if (c[0] == false_lit) c[0] = c[1], c[1] = false_lit; assert(c[1] == false_lit); // If 0th watch is true, then clause is already satisfied. Lit first = c[0]; if (value(first) == l_True){ *j++ = &c; }else{ // Look for new watch: for (int k = 2; k < c.size(); k++) if (value(c[k]) != l_False){ c[1] = c[k]; c[k] = false_lit; watches[toInt(~c[1])].push(&c); goto FoundWatch; } // Did not find watch -- clause is unit under assignment: *j++ = &c; if (!enqueue(first, &c)){ confl = &c; qhead = trail.size(); // Copy the remaining watches: while (i < end) *j++ = *i++; } FoundWatch:; } } ws.shrink(i - j); } return confl; } /*_________________________________________________________________________________________________ | | reduceDB : () -> [void] | | Description: | Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked | clauses are clauses that are reason to some assignment. Binary clauses are never removed. |________________________________________________________________________________________________@*/ struct reduceDB_lt { bool operator () (Clause* x, Clause* y) { return x->size() > 2 && (y->size() == 2 || x->activity() < y->activity()); } }; void Solver::reduceDB() { int i, j; double extra_lim = cla_inc / learnts.size(); // Remove any clause below this activity sort(learnts, reduceDB_lt()); for (i = j = 0; i < learnts.size() / 2; i++){ if (learnts[i]->size() > 2 && !locked(*learnts[i])) removeClause(*learnts[i]); else learnts[j++] = learnts[i]; } for (; i < learnts.size(); i++){ if (learnts[i]->size() > 2 && !locked(*learnts[i]) && learnts[i]->activity() < extra_lim) removeClause(*learnts[i]); else learnts[j++] = learnts[i]; } learnts.shrink(i - j); } /*_________________________________________________________________________________________________ | | simplifyDB : [void] -> [bool] | | Description: | Simplify the clause database according to the current top-level assigment. Currently, the only | thing done here is the removal of satisfied clauses, but more things can be put here. |________________________________________________________________________________________________@*/ bool Solver::simplifyDB(bool expensive) { assert(decisionLevel() == 0); if (!ok || propagate() != NULL) return ok = false; if (nAssigns() == simpDB_assigns || (!subsumption && simpDB_props > 0)) // (nothing has changed or preformed a simplification too recently) return true; if (subsumption){ if (expensive && !eliminate()) return ok = false; // Move this cleanup code to its own method ? int i , j; vec<Var> dirty; for (i = 0; i < clauses.size(); i++) if (clauses[i]->mark() == 1){ Clause& c = *clauses[i]; for (int k = 0; k < c.size(); k++) if (!seen[var(c[k])]){ seen[var(c[k])] = 1; dirty.push(var(c[k])); } } for (i = 0; i < dirty.size(); i++){ cleanOcc(dirty[i]); seen[dirty[i]] = 0; } for (i = j = 0; i < clauses.size(); i++) if (clauses[i]->mark() == 1) xfree(clauses[i]); else clauses[j++] = clauses[i]; clauses.shrink(i - j); } // Remove satisfied clauses: for (int type = 0; type < (subsumption ? 1 : 2); type++){ // (only scan learnt clauses if subsumption is on) vec<Clause*>& cs = type ? learnts : clauses; int j = 0; for (int i = 0; i < cs.size(); i++){ assert(cs[i]->mark() == 0); if (satisfied(*cs[i])) removeClause(*cs[i]); else cs[j++] = cs[i]; } cs.shrink(cs.size()-j); } order.cleanup(); simpDB_assigns = nAssigns(); simpDB_props = stats.clauses_literals + stats.learnts_literals; // (shouldn't depend on 'stats' really, but it will do for now) return true; } /*_________________________________________________________________________________________________ | | search : (nof_conflicts : int) (nof_learnts : int) (params : const SearchParams&) -> [lbool] | | Description: | Search for a model the specified number of conflicts, keeping the number of learnt clauses | below the provided limit. NOTE! Use negative value for 'nof_conflicts' or 'nof_learnts' to | indicate infinity. | | Output: | 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If | all variables are decision variables, this means that the clause set is satisfiable. 'l_False' | if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached. |________________________________________________________________________________________________@*/ lbool Solver::search(int nof_conflicts, int nof_learnts) { assert(ok); int backtrack_level; int conflictC = 0; vec<Lit> learnt_clause; stats.starts++; var_decay = 1 / params.var_decay; cla_decay = 1 / params.clause_decay; for (;;){ Clause* confl = propagate(); if (confl != NULL){ // CONFLICT stats.conflicts++; conflictC++; if (decisionLevel() == 0) return l_False; learnt_clause.clear(); analyze(confl, learnt_clause, backtrack_level); cancelUntil(backtrack_level); newClause(learnt_clause, true); varDecayActivity(); claDecayActivity(); }else{ // NO CONFLICT if (nof_conflicts >= 0 && conflictC >= nof_conflicts){ // Reached bound on number of conflicts: progress_estimate = progressEstimate(); cancelUntil(0); return l_Undef; } // Simplify the set of problem clauses: if (decisionLevel() == 0 && !simplifyDB()) return l_False; if (nof_learnts >= 0 && learnts.size()-nAssigns() >= nof_learnts) // Reduce the set of learnt clauses: reduceDB(); Lit next = lit_Undef; if (decisionLevel() < assumptions.size()){ // Perform user provided assumption: next = assumptions[decisionLevel()]; if (value(next) == l_False){ analyzeFinal(~next, conflict); return l_False; } }else{ // New variable decision: stats.decisions++; next = order.select(params.random_var_freq, decisionLevel()); } if (next == lit_Undef) // Model found: return l_True; check(assume(next)); } } } // Return search-space coverage. Not extremely reliable. // double Solver::progressEstimate() { double progress = 0; double F = 1.0 / nVars(); for (int i = 0; i <= decisionLevel(); i++){ int beg = i == 0 ? 0 : trail_lim[i - 1]; int end = i == decisionLevel() ? trail.size() : trail_lim[i]; progress += pow(F, i) * (end - beg); } return progress / nVars(); } // Divide all variable activities by 1e100. // void Solver::varRescaleActivity() { for (int i = 0; i < nVars(); i++) activity[i] *= 1e-100; var_inc *= 1e-100; } // Divide all constraint activities by 1e100. // void Solver::claRescaleActivity() { for (int i = 0; i < learnts.size(); i++) learnts[i]->activity() *= 1e-20; cla_inc *= 1e-20; } /*_________________________________________________________________________________________________ | | solve : (assumps : const vec<Lit>&) -> [bool] | | Description: | Top-level solve. |________________________________________________________________________________________________@*/ bool Solver::solve(const vec<Lit>& assumps) { model.clear(); conflict.clear(); if (!simplifyDB(true)) return false; double nof_conflicts = params.restart_first; double nof_learnts = nClauses() * params.learntsize_factor; lbool status = l_Undef; assumps.copyTo(assumptions); if (verbosity >= 1){ printf("==================================[MINISAT]====================================\n"); printf("| Conflicts | ORIGINAL | LEARNT | Progress |\n"); printf("| | Vars Clauses Literals | Limit Clauses Lit/Cl | |\n"); printf("===============================================================================\n"); } // Search: while (status == l_Undef){ if (verbosity >= 1) //printf("| %9d | %7d %8d | %7d %7d %8d %7.1f | %6.3f %% |\n", (int)stats.conflicts, nClauses(), (int)stats.clauses_literals, (int)nof_learnts, nLearnts(), (int)stats.learnts_literals, (double)stats.learnts_literals/nLearnts(), progress_estimate*100); printf("| %9d | %7d %8d %8d | %8d %8d %6.0f | %6.3f %% |\n", (int)stats.conflicts, order.size(), nClauses(), (int)stats.clauses_literals, (int)nof_learnts, nLearnts(), (double)stats.learnts_literals/nLearnts(), progress_estimate*100); status = search((int)nof_conflicts, (int)nof_learnts); nof_conflicts *= params.restart_inc; nof_learnts *= params.learntsize_inc; } if (verbosity >= 1) { printf("==============================================================================\n"); fflush(stdout); } if (status == l_True){ // Copy model: extendModel(); #if 1 //fprintf(stderr, "Verifying model.\n"); for (int i = 0; i < clauses.size(); i++) assert(satisfied(*clauses[i])); for (int i = 0; i < eliminated.size(); i++) assert(satisfied(*eliminated[i])); #endif model.growTo(nVars()); for (int i = 0; i < nVars(); i++) model[i] = value(i); }else{ assert(status == l_False); if (conflict.size() == 0) ok = false; } cancelUntil(0); return status == l_True; } } //end of MINISAT namespace
34.093366
263
0.543636
9765efe8e7544ab882e9e5264173796a133f3e0d
2,114
hpp
C++
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
27
2021-02-15T00:02:12.000Z
2022-03-24T04:34:17.000Z
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
2
2021-02-23T01:04:19.000Z
2022-03-24T04:38:10.000Z
include/felspar/coro/cancellable.hpp
Felspar/coro
67028cc10d7f66edc75229d4f4207cd8f6b82147
[ "BSL-1.0" ]
1
2022-02-20T09:41:09.000Z
2022-02-20T09:41:09.000Z
#pragma once #include <felspar/coro/coroutine.hpp> namespace felspar::coro { /** * Wait at the suspension point until resumed from an external location. */ class cancellable { coroutine_handle<> continuation = {}; bool signalled = false; void resume_if_needed() { if (continuation) { std::exchange(continuation, {}).resume(); } } public: /// Used externally to cancel the controlled coroutine void cancel() { signalled = true; resume_if_needed(); } bool cancelled() const noexcept { return signalled; } /// Wrap an awaitable so that an early resumption can be signalled template<typename A> auto signal_or(A coro_awaitable) { struct awaitable { A a; cancellable &b; bool await_ready() const noexcept { return b.signalled or a.await_ready(); } auto await_suspend(coroutine_handle<> h) noexcept { /// `h` is the coroutine making use of the `cancellable` b.continuation = h; return a.await_suspend(h); } auto await_resume() -> decltype(std::declval<A>().await_resume()) { if (b.signalled) { return {}; } else { return a.await_resume(); } } }; return awaitable{std::move(coro_awaitable), *this}; } /// This can be directly awaited until signalled auto operator co_await() { struct awaitable { cancellable &b; bool await_ready() const noexcept { return b.signalled; } auto await_suspend(coroutine_handle<> h) noexcept { b.continuation = h; } auto await_resume() noexcept {} }; return awaitable{*this}; } }; }
28.958904
76
0.487228
97660134541a53225eb378fe906c3d3842bd97d8
9,027
hpp
C++
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
1,513
2015-01-02T17:36:20.000Z
2022-03-21T00:10:17.000Z
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
335
2015-01-02T21:48:21.000Z
2022-01-31T23:10:46.000Z
src/common/channel/codec/redis_reply.hpp
vorjdux/ardb
8d32d36243dc2a8cbdc218f4218aa988fbcb5eae
[ "BSD-3-Clause" ]
281
2015-01-08T01:23:41.000Z
2022-03-26T12:31:41.000Z
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF *THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef REDIS_REPLY_HPP_ #define REDIS_REPLY_HPP_ #include "common.hpp" #include "types.hpp" #include <deque> #include <vector> #include <string> #define REDIS_REPLY_STRING 1 #define REDIS_REPLY_ARRAY 2 #define REDIS_REPLY_INTEGER 3 #define REDIS_REPLY_NIL 4 #define REDIS_REPLY_STATUS 5 #define REDIS_REPLY_ERROR 6 #define REDIS_REPLY_DOUBLE 1001 #define FIRST_CHUNK_FLAG 0x01 #define LAST_CHUNK_FLAG 0x02 #define STORAGE_ENGINE_ERR_OFFSET -100000 namespace ardb { namespace codec { enum ErrorCode { //STATUS_OK = 0, ERR_ENTRY_NOT_EXIST = -1000, ERR_INVALID_INTEGER_ARGS = -1001, ERR_INVALID_FLOAT_ARGS = -1002, ERR_INVALID_SYNTAX = -1003, ERR_AUTH_FAILED = -1004, ERR_NOTPERFORMED = -1005, ERR_STRING_EXCEED_LIMIT = -1006, ERR_NOSCRIPT = -1007, ERR_BIT_OFFSET_OUTRANGE = -1008, ERR_BIT_OUTRANGE = -1009, ERR_CORRUPTED_HLL_OBJECT = -1010, ERR_INVALID_HLL_STRING = -1011, ERR_SCORE_NAN = -1012, ERR_EXEC_ABORT = -1013, ERR_UNSUPPORT_DIST_UNIT = -1014, ERR_NOREPLICAS = -1015, ERR_READONLY_SLAVE = -1016, ERR_MASTER_DOWN = -1017, ERR_LOADING = -1018, ERR_NOTSUPPORTED = -1019, ERR_INVALID_ARGS = -1020, ERR_KEY_EXIST = -1021, ERR_WRONG_TYPE = -1022, ERR_OUTOFRANGE = -1023, }; enum StatusCode { STATUS_OK = 1000, STATUS_PONG = 1001, STATUS_QUEUED = 1002, STATUS_NOKEY = 1003, }; struct RedisDumpFileChunk { int64 len; uint32 flag; std::string chunk; RedisDumpFileChunk() : len(0), flag(0) { } bool IsLastChunk() { return (flag & LAST_CHUNK_FLAG) == (LAST_CHUNK_FLAG); } bool IsFirstChunk() { return (flag & FIRST_CHUNK_FLAG) == (FIRST_CHUNK_FLAG); } }; class RedisReplyPool; struct RedisReply { private: public: int type; std::string str; /* * If the type is REDIS_REPLY_STRING, and the str's length is large, * the integer value also used to identify chunk state. */ int64_t integer; std::deque<RedisReply*>* elements; RedisReplyPool* pool; //use object pool if reply is array with hundreds of elements RedisReply(); RedisReply(uint64 v); RedisReply(double v); RedisReply(const std::string& v); bool IsErr() const { return type == REDIS_REPLY_ERROR; } bool IsNil() const { return type == REDIS_REPLY_NIL; } bool IsString() const { return type == REDIS_REPLY_STRING; } bool IsArray() const { return type == REDIS_REPLY_ARRAY; } const std::string& Status(); const std::string& Error(); int64_t ErrCode() const { return integer; } void SetEmpty() { Clear(); type = 0; } double GetDouble(); const std::string& GetString() const { return str; } int64 GetInteger() const { return integer; } void SetDouble(double v); void SetInteger(int64_t v) { type = REDIS_REPLY_INTEGER; integer = v; } void SetString(const Data& v) { Clear(); if (!v.IsNil()) { type = REDIS_REPLY_STRING; v.ToString(str); } } void SetString(const std::string& v) { Clear(); type = REDIS_REPLY_STRING; str = v; } void SetErrCode(int err) { Clear(); type = REDIS_REPLY_ERROR; integer = err; } void SetErrorReason(const std::string& reason) { Clear(); type = REDIS_REPLY_ERROR; str = reason; } void SetStatusCode(int status) { Clear(); type = REDIS_REPLY_STATUS; integer = status; } void SetStatusString(const char* v) { Clear(); type = REDIS_REPLY_STATUS; str.assign(v); } void SetStatusString(const std::string& v) { Clear(); type = REDIS_REPLY_STATUS; str = v; } void SetPool(RedisReplyPool* pool); bool IsPooled() { return pool != NULL; } RedisReply& AddMember(bool tail = true); void ReserveMember(int64_t num); size_t MemberSize(); RedisReply& MemberAt(uint32 i); void Clear(); void Clone(const RedisReply& r) { Clear(); type = r.type; integer = r.integer; str = r.str; if (r.elements != NULL && !r.elements->empty()) { for (uint32 i = 0; i < r.elements->size(); i++) { RedisReply& rr = AddMember(); rr.Clone(*(r.elements->at(i))); } } } virtual ~RedisReply(); }; class RedisReplyPool { private: uint32 m_max_size; uint32 m_cursor; std::vector<RedisReply> elements; std::deque<RedisReply> pending; public: RedisReplyPool(uint32 size = 5); void SetMaxSize(uint32 size); RedisReply& Allocate(); void Clear(); }; typedef std::vector<RedisReply*> RedisReplyArray; void reply_status_string(int code, std::string& str); void reply_error_string(int code, std::string& str); void clone_redis_reply(RedisReply& src, RedisReply& dst); uint64_t living_reply_count(); } } #endif /* REDIS_REPLY_HPP_ */
32.825455
100
0.484657
976af6da8799161d7d6f8e1eb734ed3146607c60
4,092
cc
C++
content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/indexed_db/indexed_db_pre_close_task_queue.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_pre_close_task_queue.h" #include <utility> #include "base/bind.h" #include "base/metrics/histogram_macros.h" #include "base/threading/sequenced_task_runner_handle.h" #include "third_party/blink/public/common/indexeddb/indexeddb_metadata.h" #include "third_party/leveldatabase/env_chromium.h" using blink::IndexedDBDatabaseMetadata; namespace content { IndexedDBPreCloseTaskQueue::PreCloseTask::PreCloseTask(leveldb::DB* database) : database_(database) {} IndexedDBPreCloseTaskQueue::PreCloseTask::~PreCloseTask() = default; bool IndexedDBPreCloseTaskQueue::PreCloseTask::RequiresMetadata() const { return false; } void IndexedDBPreCloseTaskQueue::PreCloseTask::SetMetadata( const std::vector<blink::IndexedDBDatabaseMetadata>* metadata) {} IndexedDBPreCloseTaskQueue::IndexedDBPreCloseTaskQueue( std::list<std::unique_ptr<IndexedDBPreCloseTaskQueue::PreCloseTask>> tasks, base::OnceClosure on_complete, base::TimeDelta max_run_time, std::unique_ptr<base::OneShotTimer> timer) : tasks_(std::move(tasks)), on_done_(std::move(on_complete)), timeout_time_(max_run_time), timeout_timer_(std::move(timer)), task_runner_(base::SequencedTaskRunnerHandle::Get()) {} IndexedDBPreCloseTaskQueue::~IndexedDBPreCloseTaskQueue() = default; void IndexedDBPreCloseTaskQueue::StopForNewConnection() { if (!started_ || done_) return; DCHECK(!tasks_.empty()); while (!tasks_.empty()) { tasks_.front()->Stop(StopReason::NEW_CONNECTION); tasks_.pop_front(); } OnComplete(); } void IndexedDBPreCloseTaskQueue::Start(MetadataFetcher metadata_fetcher) { DCHECK(!started_); started_ = true; if (tasks_.empty()) { OnComplete(); return; } timeout_timer_->Start( FROM_HERE, timeout_time_, base::BindOnce(&IndexedDBPreCloseTaskQueue::StopForTimout, ptr_factory_.GetWeakPtr())); metadata_fetcher_ = std::move(metadata_fetcher); task_runner_->PostTask(FROM_HERE, base::BindOnce(&IndexedDBPreCloseTaskQueue::RunLoop, ptr_factory_.GetWeakPtr())); } void IndexedDBPreCloseTaskQueue::OnComplete() { DCHECK(started_); DCHECK(!done_); ptr_factory_.InvalidateWeakPtrs(); timeout_timer_->Stop(); done_ = true; std::move(on_done_).Run(); } void IndexedDBPreCloseTaskQueue::StopForTimout() { DCHECK(started_); if (done_) return; while (!tasks_.empty()) { tasks_.front()->Stop(StopReason::TIMEOUT); tasks_.pop_front(); } OnComplete(); } void IndexedDBPreCloseTaskQueue::StopForMetadataError( const leveldb::Status& status) { if (done_) return; LOCAL_HISTOGRAM_ENUMERATION( "WebCore.IndexedDB.IndexedDBPreCloseTaskList.MetadataError", leveldb_env::GetLevelDBStatusUMAValue(status), leveldb_env::LEVELDB_STATUS_MAX); while (!tasks_.empty()) { tasks_.front()->Stop(StopReason::METADATA_ERROR); tasks_.pop_front(); } OnComplete(); } void IndexedDBPreCloseTaskQueue::RunLoop() { if (done_) return; if (tasks_.empty()) { OnComplete(); return; } PreCloseTask* task = tasks_.front().get(); if (task->RequiresMetadata() && !task->set_metadata_was_called_) { if (!has_metadata_) { leveldb::Status status = std::move(metadata_fetcher_).Run(&metadata_); has_metadata_ = true; if (!status.ok()) { StopForMetadataError(status); return; } } task->SetMetadata(&metadata_); task->set_metadata_was_called_ = true; } bool done = task->RunRound(); if (done) { tasks_.pop_front(); if (tasks_.empty()) { OnComplete(); return; } } task_runner_->PostTask(FROM_HERE, base::BindOnce(&IndexedDBPreCloseTaskQueue::RunLoop, ptr_factory_.GetWeakPtr())); } } // namespace content
28.615385
79
0.695015
976ba55f7c4e4a84dc80156378219097dd50d09b
952
cpp
C++
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Medium/1286_Iterator_For_Combination.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
class CombinationIterator { private: int len, mask; string s; public: CombinationIterator(string characters, int combinationLength) : s(characters), len(combinationLength) { mask = (1 << characters.length()) - 1; } string next() { while(mask && __builtin_popcount(mask) != len) { mask--; } string next_combination; for(int i = 0; i < s.length(); i++) { if(mask & (1 << (s.length() - i - 1))) { next_combination.push_back(s[i]); } } mask--; return next_combination; } bool hasNext() { while(mask && __builtin_popcount(mask) != len) { mask--; } return mask; } }; /** * Your CombinationIterator object will be instantiated and called as such: * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); * string param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
28.848485
107
0.578782
976c95ec96dd46eac812664839e16ac76885907f
1,114
cpp
C++
src/vulkan_helper/image_view.cpp
LesleyLai/Vulkan-Renderer
fd03a69fbc21bfaf3177e43811d21dba634a1949
[ "Apache-2.0" ]
4
2019-04-17T17:44:23.000Z
2020-09-14T04:24:37.000Z
src/vulkan_helper/image_view.cpp
LesleyLai/Vulkan-Renderer
fd03a69fbc21bfaf3177e43811d21dba634a1949
[ "Apache-2.0" ]
3
2020-06-10T00:43:44.000Z
2020-06-10T00:59:47.000Z
src/vulkan_helper/image_view.cpp
LesleyLai/Vulkan-Renderer
fd03a69fbc21bfaf3177e43811d21dba634a1949
[ "Apache-2.0" ]
null
null
null
#include "image_view.hpp" namespace vkh { [[nodiscard]] auto create_image_view(VkDevice device, const ImageViewCreateInfo& image_view_create_info) -> beyond::expected<VkImageView, VkResult> { const VkImageViewCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = image_view_create_info.image, .viewType = image_view_create_info.view_type, .format = image_view_create_info.format, .subresourceRange = image_view_create_info.subresource_range}; VkImageView image_view = nullptr; if (auto res = vkCreateImageView(device, &create_info, nullptr, &image_view); res != VK_SUCCESS) { return beyond::unexpected(res); } return image_view; } [[nodiscard]] auto create_unique_image_view(VkDevice device, const ImageViewCreateInfo& image_view_create_info) -> beyond::expected<UniqueImageView, VkResult> { return create_image_view(device, image_view_create_info) .map([&](VkImageView image_view) { return UniqueImageView(device, image_view); }); } } // namespace vkh
30.108108
79
0.71544
976ca940c560635702dfc2c725418346a5e9e5de
3,196
cxx
C++
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
1
2022-02-16T03:48:29.000Z
2022-02-16T03:48:29.000Z
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
null
null
null
Examples/InSar/BaselineComputation.cxx
jmichel-otb/otb-insar
b6f8a7d80547ffdcf7c4d2359505ce68107cdb85
[ "Apache-2.0" ]
null
null
null
/*========================================================================= Copyright 2011 Emmanuel Christophe Contributed to ORFEO Toolbox under license Apache 2 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. =========================================================================*/ // Command line: // // ./bin/BaselineComputation ~/project/Images/TSX1_SAR__SSC______HS_S_SRA_20090212T204239_20090212T204240/TSX1_SAR__SSC______HS_S_SRA_20090212T204239_20090212T204240.xml ~/project/Images/TSX1_SAR__SSC______HS_S_SRA_20090223T204240_20090223T204241/TSX1_SAR__SSC______HS_S_SRA_20090223T204240_20090223T204241.xml #include <iomanip> #include "otbImage.h" #include "otbImageFileReader.h" #include "otbBaselineCalculator.h" #include "otbLengthOrientationBaselineFunctor.h" #include "otbPlatformPositionToBaselineCalculator.h" int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " masterImageFile slaveImageFile" << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 2 ; typedef std::complex<double> PixelType; typedef otb::Image<PixelType,Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; ReaderType::Pointer master = ReaderType::New(); ReaderType::Pointer slave = ReaderType::New(); master->SetFileName(argv[1]); slave->SetFileName(argv[2]); master->UpdateOutputInformation(); slave->UpdateOutputInformation(); typedef otb::Functor::LengthOrientationBaselineFunctor BaselineFunctorType; typedef otb::BaselineCalculator<BaselineFunctorType> BaselineCalculatorType; typedef BaselineCalculatorType::PlateformPositionToBaselineCalculatorType PlateformPositionToBaselineCalculatorType; BaselineCalculatorType::Pointer baselineCalculator = BaselineCalculatorType::New(); BaselineCalculatorType::PlateformPositionToBaselinePointer plateformPositionToBaseline = PlateformPositionToBaselineCalculatorType::New(); plateformPositionToBaseline->SetMasterPlateform(master->GetOutput()->GetImageKeywordlist()); plateformPositionToBaseline->SetSlavePlateform(slave->GetOutput()->GetImageKeywordlist()); baselineCalculator->SetPlateformPositionToBaselineCalculator(plateformPositionToBaseline); baselineCalculator->Compute(otb::Functor::LengthOrientationBaselineFunctor::Length); double row = 0; double col = 0; std::cout << "(row,col) : " << row << ", " << col << " -> Baseline : "; std::cout << baselineCalculator->EvaluateBaseline(row,col)<< std::endl; row = 1000; col = 1000; std::cout << "(row,col) : " << row << ", " << col << " -> Baseline : "; std::cout << baselineCalculator->EvaluateBaseline(row,col)<< std::endl; }
39.45679
310
0.731852
97703f3fa284c9cc26f37748d1b33de03287c40a
211
cpp
C++
Fall-17/CSE/CPP/Assignments/Basic/ASCIIValuesChart.cpp
2Dsharp/college
239fb4c85878f082529a3668544d1ad305b46170
[ "MIT" ]
1
2021-05-18T06:34:53.000Z
2021-05-18T06:34:53.000Z
Fall-17/CSE/CPP/Assignments/Basic/ASCIIValuesChart.cpp
2Dsharp/college
239fb4c85878f082529a3668544d1ad305b46170
[ "MIT" ]
null
null
null
Fall-17/CSE/CPP/Assignments/Basic/ASCIIValuesChart.cpp
2Dsharp/college
239fb4c85878f082529a3668544d1ad305b46170
[ "MIT" ]
1
2018-11-12T16:01:39.000Z
2018-11-12T16:01:39.000Z
#include <iostream> int main(){ std::cout << "ASCII "<< "Representation" << std::endl; for(int i=0;i<=127;i++){ char temp = i; std::cout << i << "\t" << temp << std::endl; } return 0; }
14.066667
56
0.492891
977424df8367635d711cef34f5ced409cc8ceeca
38,699
cpp
C++
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
114
2017-08-13T22:37:32.000Z
2022-03-25T12:28:39.000Z
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
7
2019-10-14T18:19:11.000Z
2021-06-11T09:41:52.000Z
src/saiga/opengl/glbinding/source/gl/functions-patches.cpp
no33fewi/saiga
edc873e34cd59eaf8c4a12dc7f909b4dd5e5fb68
[ "MIT" ]
18
2017-08-14T01:22:05.000Z
2022-03-12T12:35:07.000Z
#include <glbinding/gl/functions.h> #include <vector> #include <glbinding/gl/functions-patches.h> namespace gl { void glConvolutionParameteri(GLenum target, GLenum pname, GLenum params) { glConvolutionParameteri(target, pname, static_cast<GLint>(params)); } void glConvolutionParameteriEXT(GLenum target, GLenum pname, GLenum params) { glConvolutionParameteriEXT(target, pname, static_cast<GLint>(params)); } void glFogi(GLenum pname, GLenum param) { glFogi(pname, static_cast<GLint>(param)); } void glFogiv(GLenum pname, const GLenum* params) { glFogiv(pname, reinterpret_cast<const GLint*>(params)); } void glGetBufferParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetBufferParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetBufferParameterivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetBufferParameterivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetBufferParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetBufferParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetBufferParameterivARB(GLenum target, GLenum pname, GLenum* params) { glGetBufferParameterivARB(target, pname, reinterpret_cast<GLint*>(params)); } void glGetConvolutionParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetConvolutionParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetConvolutionParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetConvolutionParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetIntegerv(GLenum pname, GLenum* data) { glGetIntegerv(pname, reinterpret_cast<GLint*>(data)); } void glGetIntegeri_v(GLenum target, GLuint index, GLenum* data) { glGetIntegeri_v(target, index, reinterpret_cast<GLint*>(data)); } void glGetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLenum* params) { glGetFramebufferAttachmentParameteriv(target, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetFramebufferAttachmentParameterivEXT(GLenum target, GLenum attachment, GLenum pname, GLenum* params) { glGetFramebufferAttachmentParameterivEXT(target, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetFramebufferParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetFramebufferParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLboolean* params) { GLint params_; glGetFramebufferParameterivEXT(framebuffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetMinmaxParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetMinmaxParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetMinmaxParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetMinmaxParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedBufferParameteriv(buffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedBufferParameterivEXT(buffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedBufferParameteriv(GLuint buffer, GLenum pname, GLenum* params) { glGetNamedBufferParameteriv(buffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedBufferParameterivEXT(GLuint buffer, GLenum pname, GLenum* params) { glGetNamedBufferParameterivEXT(buffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferAttachmentParameteriv(GLuint framebuffer, GLenum attachment, GLenum pname, GLenum* params) { glGetNamedFramebufferAttachmentParameteriv(framebuffer, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferAttachmentParameterivEXT(GLuint framebuffer, GLenum attachment, GLenum pname, GLenum* params) { glGetNamedFramebufferAttachmentParameterivEXT(framebuffer, attachment, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedFramebufferParameteriv(GLuint framebuffer, GLenum pname, GLboolean* param) { GLint params_; glGetNamedFramebufferParameteriv(framebuffer, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedFramebufferParameterivEXT(GLuint framebuffer, GLenum pname, GLboolean* params) { GLint params_; glGetNamedFramebufferParameterivEXT(framebuffer, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetNamedProgramivEXT(program, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetNamedProgramivEXT(GLuint program, GLenum target, GLenum pname, GLenum* params) { glGetNamedProgramivEXT(program, target, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedRenderbufferParameteriv(GLuint renderbuffer, GLenum pname, GLenum* params) { glGetNamedRenderbufferParameteriv(renderbuffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedRenderbufferParameterivEXT(GLuint renderbuffer, GLenum pname, GLenum* params) { glGetNamedRenderbufferParameterivEXT(renderbuffer, pname, reinterpret_cast<GLint*>(params)); } void glGetNamedStringivARB(GLint namelen, const GLchar* name, GLenum pname, GLenum* params) { glGetNamedStringivARB(namelen, name, pname, reinterpret_cast<GLint*>(params)); } void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLboolean* params) { GLint params_; glGetObjectParameterivARB(obj, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetObjectParameterivARB(GLhandleARB obj, GLenum pname, GLenum* params) { glGetObjectParameterivARB(obj, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramiv(GLuint program, GLenum pname, GLboolean* params) { GLint params_; glGetProgramiv(program, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetProgramivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetProgramivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetProgramiv(GLuint program, GLenum pname, GLenum* params) { glGetProgramiv(program, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramivARB(GLenum target, GLenum pname, GLenum* params) { glGetProgramivARB(target, pname, reinterpret_cast<GLint*>(params)); } void glGetProgramResourceiv(GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum* props, GLsizei bufSize, GLsizei* length, GLenum* params) { glGetProgramResourceiv(program, programInterface, index, propCount, props, bufSize, length, reinterpret_cast<GLint*>(params)); } void glGetQueryIndexediv(GLenum target, GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetQueryIndexediv(target, index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryObjectiv(GLuint id, GLenum pname, GLboolean* params) { GLint params_; glGetQueryObjectiv(id, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryObjectivARB(GLuint id, GLenum pname, GLboolean* params) { GLint params_; glGetQueryObjectivARB(id, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryiv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetQueryiv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetQueryivARB(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetQueryivARB(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetRenderbufferParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetRenderbufferParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetRenderbufferParameterivEXT(GLenum target, GLenum pname, GLenum* params) { glGetRenderbufferParameterivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetSamplerParameterIiv(GLuint sampler, GLenum pname, GLenum* params) { glGetSamplerParameterIiv(sampler, pname, reinterpret_cast<GLint*>(params)); } void glGetSamplerParameteriv(GLuint sampler, GLenum pname, GLenum* params) { glGetSamplerParameteriv(sampler, pname, reinterpret_cast<GLint*>(params)); } void glGetShaderiv(GLuint shader, GLenum pname, GLboolean* params) { GLint params_; glGetShaderiv(shader, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetShaderiv(GLuint shader, GLenum pname, GLenum* params) { glGetShaderiv(shader, pname, reinterpret_cast<GLint*>(params)); } void glGetTexEnviv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexEnviv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexEnviv(GLenum target, GLenum pname, GLenum* params) { glGetTexEnviv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexGeniv(GLenum coord, GLenum pname, GLenum* params) { glGetTexGeniv(coord, pname, reinterpret_cast<GLint*>(params)); } void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTexLevelParameteriv(target, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLenum* params) { glGetTexLevelParameteriv(target, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameterIiv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameterIiv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameterIivEXT(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameterIivEXT(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameteriv(GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTexParameteriv(target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTexParameterIiv(GLenum target, GLenum pname, GLenum* params) { glGetTexParameterIiv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameterIivEXT(GLenum target, GLenum pname, GLenum* params) { glGetTexParameterIivEXT(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTexParameteriv(GLenum target, GLenum pname, GLenum* params) { glGetTexParameteriv(target, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTextureLevelParameteriv(texture, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLboolean* params) { GLint params_; glGetTextureLevelParameterivEXT(texture, target, level, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureLevelParameteriv(GLuint texture, GLint level, GLenum pname, GLenum* params) { glGetTextureLevelParameteriv(texture, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureLevelParameterivEXT(GLuint texture, GLenum target, GLint level, GLenum pname, GLenum* params) { glGetTextureLevelParameterivEXT(texture, target, level, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterIiv(texture, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterIivEXT(texture, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameteriv(GLuint texture, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameteriv(texture, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLboolean* params) { GLint params_; glGetTextureParameterivEXT(texture, target, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetTextureParameterIiv(GLuint texture, GLenum pname, GLenum* params) { glGetTextureParameterIiv(texture, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, GLenum* params) { glGetTextureParameterIivEXT(texture, target, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameteriv(GLuint texture, GLenum pname, GLenum* params) { glGetTextureParameteriv(texture, pname, reinterpret_cast<GLint*>(params)); } void glGetTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, GLenum* params) { glGetTextureParameterivEXT(texture, target, pname, reinterpret_cast<GLint*>(params)); } void glGetTransformFeedbackiv(GLuint xfb, GLenum pname, GLboolean* param) { GLint params_; glGetTransformFeedbackiv(xfb, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLboolean* param) { GLint params_; glGetVertexArrayIndexediv(vaobj, index, pname, &params_); param[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexArrayIndexediv(GLuint vaobj, GLuint index, GLenum pname, GLenum* param) { glGetVertexArrayIndexediv(vaobj, index, pname, reinterpret_cast<GLint*>(param)); } void glGetVertexAttribIiv(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribIiv(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribIivEXT(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribIivEXT(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribiv(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribiv(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribivARB(GLuint index, GLenum pname, GLboolean* params) { GLint params_; glGetVertexAttribivARB(index, pname, &params_); params[0] = static_cast<GLboolean>(params_ != 0); } void glGetVertexAttribIiv(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribIiv(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribIivEXT(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribIivEXT(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribiv(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribiv(index, pname, reinterpret_cast<GLint*>(params)); } void glGetVertexAttribivARB(GLuint index, GLenum pname, GLenum* params) { glGetVertexAttribivARB(index, pname, reinterpret_cast<GLint*>(params)); } void glLightModeli(GLenum pname, GLenum param) { glLightModeli(pname, static_cast<GLint>(param)); } void glLightModeliv(GLenum pname, const GLenum* params) { glLightModeliv(pname, reinterpret_cast<const GLint*>(params)); } void glMultiTexImage1DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage1DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glMultiTexImage2DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage2DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glMultiTexImage3DEXT(GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glMultiTexImage3DEXT(texunit, target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glNamedFramebufferParameteri(GLuint framebuffer, GLenum pname, GLboolean param) { glNamedFramebufferParameteri(framebuffer, pname, static_cast<GLint>(param)); } void glNamedFramebufferParameteriEXT(GLuint framebuffer, GLenum pname, GLboolean param) { glNamedFramebufferParameteriEXT(framebuffer, pname, static_cast<GLint>(param)); } void glPixelStorei(GLenum pname, GLboolean param) { glPixelStorei(pname, static_cast<GLint>(param)); } void glPixelTransferi(GLenum pname, GLboolean param) { glPixelTransferi(pname, static_cast<GLint>(param)); } void glPointParameteri(GLenum pname, GLenum param) { glPointParameteri(pname, static_cast<GLint>(param)); } void glPointParameteriv(GLenum pname, const GLenum* params) { glPointParameteriv(pname, reinterpret_cast<const GLint*>(params)); } void glProgramParameteri(GLuint program, GLenum pname, GLboolean value) { glProgramParameteri(program, pname, static_cast<GLint>(value)); } void glProgramParameteriARB(GLuint program, GLenum pname, GLboolean value) { glProgramParameteriARB(program, pname, static_cast<GLint>(value)); } void glProgramParameteriEXT(GLuint program, GLenum pname, GLboolean value) { glProgramParameteriEXT(program, pname, static_cast<GLint>(value)); } void glProgramUniform1i(GLuint program, GLint location, GLboolean v0) { glProgramUniform1i(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iEXT(GLuint program, GLint location, GLboolean v0) { glProgramUniform1iEXT(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform1iv(program, location, count, data.data()); } void glProgramUniform1ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform1ivEXT(program, location, count, data.data()); } void glProgramUniform2i(GLuint program, GLint location, GLboolean v0, GLboolean v1) { glProgramUniform2i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1) { glProgramUniform2iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform2iv(program, location, count, data.data()); } void glProgramUniform2ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform2ivEXT(program, location, count, data.data()); } void glProgramUniform3i(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glProgramUniform3i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glProgramUniform3iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform3iv(program, location, count, data.data()); } void glProgramUniform3ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform3ivEXT(program, location, count, data.data()); } void glProgramUniform4i(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glProgramUniform4i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iEXT(GLuint program, GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glProgramUniform4iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform4iv(program, location, count, data.data()); } void glProgramUniform4ivEXT(GLuint program, GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glProgramUniform4ivEXT(program, location, count, data.data()); } void glProgramUniform1i(GLuint program, GLint location, GLenum v0) { glProgramUniform1i(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iEXT(GLuint program, GLint location, GLenum v0) { glProgramUniform1iEXT(program, location, static_cast<GLint>(v0)); } void glProgramUniform1iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform1iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform1ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform1ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform2i(GLuint program, GLint location, GLenum v0, GLenum v1) { glProgramUniform2i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iEXT(GLuint program, GLint location, GLenum v0, GLenum v1) { glProgramUniform2iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glProgramUniform2iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform2iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform2ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform2ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform3i(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2) { glProgramUniform3i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iEXT(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2) { glProgramUniform3iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glProgramUniform3iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform3iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform3ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform3ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform4i(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glProgramUniform4i(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iEXT(GLuint program, GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glProgramUniform4iEXT(program, location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glProgramUniform4iv(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform4iv(program, location, count, reinterpret_cast<const GLint*>(value)); } void glProgramUniform4ivEXT(GLuint program, GLint location, GLsizei count, const GLenum* value) { glProgramUniform4ivEXT(program, location, count, reinterpret_cast<const GLint*>(value)); } void glSamplerParameterIiv(GLuint sampler, GLenum pname, const GLenum* param) { glSamplerParameterIiv(sampler, pname, reinterpret_cast<const GLint*>(param)); } void glSamplerParameteri(GLuint sampler, GLenum pname, GLenum param) { glSamplerParameteri(sampler, pname, static_cast<GLint>(param)); } void glSamplerParameteriv(GLuint sampler, GLenum pname, const GLenum* param) { glSamplerParameteriv(sampler, pname, reinterpret_cast<const GLint*>(param)); } void glTexEnvi(GLenum target, GLenum pname, GLboolean param) { glTexEnvi(target, pname, static_cast<GLint>(param)); } void glTexEnviv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexEnviv(target, pname, &params_); } void glTexEnvi(GLenum target, GLenum pname, GLenum param) { glTexEnvi(target, pname, static_cast<GLint>(param)); } void glTexEnviv(GLenum target, GLenum pname, const GLenum* params) { glTexEnviv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexGeni(GLenum coord, GLenum pname, GLenum param) { glTexGeni(coord, pname, static_cast<GLint>(param)); } void glTexGeniv(GLenum coord, GLenum pname, const GLenum* params) { glTexGeniv(coord, pname, reinterpret_cast<const GLint*>(params)); } void glTexImage1D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage1D(target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage2D(target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glTexImage3D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glTexImage3D(target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glTextureImage1DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage1DEXT(texture, target, level, static_cast<GLint>(internalformat), width, border, format, type, pixels); } void glTextureImage2DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage2DEXT(texture, target, level, static_cast<GLint>(internalformat), width, height, border, format, type, pixels); } void glTextureImage3DEXT(GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void* pixels) { glTextureImage3DEXT(texture, target, level, static_cast<GLint>(internalformat), width, height, depth, border, format, type, pixels); } void glTexParameterIiv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameterIiv(target, pname, &params_); } void glTexParameterIivEXT(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameterIivEXT(target, pname, &params_); } void glTexParameteri(GLenum target, GLenum pname, GLboolean param) { glTexParameteri(target, pname, static_cast<GLint>(param)); } void glTexParameteriv(GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTexParameteriv(target, pname, &params_); } void glTexParameterIiv(GLenum target, GLenum pname, const GLenum* params) { glTexParameterIiv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexParameterIivEXT(GLenum target, GLenum pname, const GLenum* params) { glTexParameterIivEXT(target, pname, reinterpret_cast<const GLint*>(params)); } void glTexParameteri(GLenum target, GLenum pname, GLenum param) { glTexParameteri(target, pname, static_cast<GLint>(param)); } void glTexParameteriv(GLenum target, GLenum pname, const GLenum* params) { glTexParameteriv(target, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameterIiv(GLuint texture, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterIiv(texture, pname, &params_); } void glTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterIivEXT(texture, target, pname, &params_); } void glTextureParameteri(GLuint texture, GLenum pname, GLboolean param) { glTextureParameteri(texture, pname, static_cast<GLint>(param)); } void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLboolean param) { glTextureParameteriEXT(texture, target, pname, static_cast<GLint>(param)); } void glTextureParameteriv(GLuint texture, GLenum pname, const GLboolean* param) { GLint params_ = static_cast<GLint>(param[0]); glTextureParameteriv(texture, pname, &params_); } void glTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, const GLboolean* params) { GLint params_ = static_cast<GLint>(params[0]); glTextureParameterivEXT(texture, target, pname, &params_); } void glTextureParameterIiv(GLuint texture, GLenum pname, const GLenum* params) { glTextureParameterIiv(texture, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameterIivEXT(GLuint texture, GLenum target, GLenum pname, const GLenum* params) { glTextureParameterIivEXT(texture, target, pname, reinterpret_cast<const GLint*>(params)); } void glTextureParameteri(GLuint texture, GLenum pname, GLenum param) { glTextureParameteri(texture, pname, static_cast<GLint>(param)); } void glTextureParameteriEXT(GLuint texture, GLenum target, GLenum pname, GLenum param) { glTextureParameteriEXT(texture, target, pname, static_cast<GLint>(param)); } void glTextureParameteriv(GLuint texture, GLenum pname, const GLenum* param) { glTextureParameteriv(texture, pname, reinterpret_cast<const GLint*>(param)); } void glTextureParameterivEXT(GLuint texture, GLenum target, GLenum pname, const GLenum* params) { glTextureParameterivEXT(texture, target, pname, reinterpret_cast<const GLint*>(params)); } void glUniform1i(GLint location, GLboolean v0) { glUniform1i(location, static_cast<GLint>(v0)); } void glUniform1iARB(GLint location, GLboolean v0) { glUniform1iARB(location, static_cast<GLint>(v0)); } void glUniform1iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform1iv(location, count, data.data()); } void glUniform1ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 1 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform1ivARB(location, count, data.data()); } void glUniform2i(GLint location, GLboolean v0, GLboolean v1) { glUniform2i(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iARB(GLint location, GLboolean v0, GLboolean v1) { glUniform2iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform2iv(location, count, data.data()); } void glUniform2ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 2 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform2ivARB(location, count, data.data()); } void glUniform3i(GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glUniform3i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iARB(GLint location, GLboolean v0, GLboolean v1, GLboolean v2) { glUniform3iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform3iv(location, count, data.data()); } void glUniform3ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 3 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform3ivARB(location, count, data.data()); } void glUniform4i(GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glUniform4i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iARB(GLint location, GLboolean v0, GLboolean v1, GLboolean v2, GLboolean v3) { glUniform4iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iv(GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform4iv(location, count, data.data()); } void glUniform4ivARB(GLint location, GLsizei count, const GLboolean* value) { const auto size = 4 * count; std::vector<GLint> data(size); for (auto i = 0; i < size; ++i) { data[i] = static_cast<GLint>(value[i]); } glUniform4ivARB(location, count, data.data()); } void glUniform1i(GLint location, GLenum v0) { glUniform1i(location, static_cast<GLint>(v0)); } void glUniform1iARB(GLint location, GLenum v0) { glUniform1iARB(location, static_cast<GLint>(v0)); } void glUniform1iv(GLint location, GLsizei count, const GLenum* value) { glUniform1iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform1ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform1ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform2i(GLint location, GLenum v0, GLenum v1) { glUniform2i(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iARB(GLint location, GLenum v0, GLenum v1) { glUniform2iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1)); } void glUniform2iv(GLint location, GLsizei count, const GLenum* value) { glUniform2iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform2ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform2ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform3i(GLint location, GLenum v0, GLenum v1, GLenum v2) { glUniform3i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iARB(GLint location, GLenum v0, GLenum v1, GLenum v2) { glUniform3iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2)); } void glUniform3iv(GLint location, GLsizei count, const GLenum* value) { glUniform3iv(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform3ivARB(GLint location, GLsizei count, const GLenum* value) { glUniform3ivARB(location, count, reinterpret_cast<const GLint*>(value)); } void glUniform4i(GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glUniform4i(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iARB(GLint location, GLenum v0, GLenum v1, GLenum v2, GLenum v3) { glUniform4iARB(location, static_cast<GLint>(v0), static_cast<GLint>(v1), static_cast<GLint>(v2), static_cast<GLint>(v3)); } void glUniform4iv(GLint location, GLsizei count, const GLenum* value) { glUniform4iv(location, count, reinterpret_cast<const GLint*>(value)); } } // namespace gl
29.86034
120
0.733404
97747fcdd08eedf08f3e44b1c0025a9411d18f4a
9,657
cpp
C++
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
40
2016-11-18T06:14:47.000Z
2022-03-16T14:36:21.000Z
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
null
null
null
test/actionsTest/actionForm.cpp
perara-libs/FakeInput
13d7b260634c33ced95d9e3b37780705e4036ab5
[ "MIT" ]
9
2017-01-23T01:49:41.000Z
2020-11-05T13:09:56.000Z
/** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka <uiii.dev@gmail.com> * * 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. */ #include "actionForm.hpp" #include <QHBoxLayout> #include <QVBoxLayout> #include <QLabel> #include <QStackedWidget> #include "keyboard.hpp" #include "mouse.hpp" #include "system.hpp" Q_DECLARE_METATYPE(FakeInput::KeyType); Q_DECLARE_METATYPE(FakeInput::MouseButton); Q_ENUMS(FakeInput::KeyType); Q_ENUMS(FakeInput::MouseButton); ActionForm::ActionForm(QWidget* parent): QWidget(parent) { QVBoxLayout* vbox = new QVBoxLayout(this); actionType_ = new QComboBox(this); actionType_->addItem("press & release key"); actionType_->addItem("click mouse button"); actionType_->addItem("move mouse"); actionType_->addItem("rotate wheel"); actionType_->addItem("run command"); actionType_->addItem("wait"); QWidget* keyOptions_ = new QWidget(); QWidget* mouseButtonOptions_ = new QWidget(); QWidget* mouseMotionOptions_ = new QWidget(); QWidget* mouseWheelOptions_ = new QWidget(); QWidget* commandOptions_ = new QWidget(); QWidget* waitOptions_ = new QWidget(); QHBoxLayout* keyHBox = new QHBoxLayout(); QHBoxLayout* mouseButtonHBox = new QHBoxLayout(); QHBoxLayout* mouseMotionHBox = new QHBoxLayout(); QHBoxLayout* mouseWheelHBox = new QHBoxLayout(); QHBoxLayout* commandHBox = new QHBoxLayout(); QHBoxLayout* waitHBox = new QHBoxLayout(); keySelector_ = new QComboBox(); keySelector_->addItem("A", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_A)); keySelector_->addItem("B", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_B)); keySelector_->addItem("C", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_C)); keySelector_->addItem("D", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_D)); keySelector_->addItem("E", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_E)); keySelector_->addItem("F", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_F)); keySelector_->addItem("G", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_G)); keySelector_->addItem("H", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_H)); keySelector_->addItem("I", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_I)); keySelector_->addItem("J", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_J)); keySelector_->addItem("K", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_K)); keySelector_->addItem("L", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_L)); keySelector_->addItem("M", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_M)); keySelector_->addItem("N", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_N)); keySelector_->addItem("O", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_O)); keySelector_->addItem("P", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_P)); keySelector_->addItem("Q", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Q)); keySelector_->addItem("R", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_R)); keySelector_->addItem("S", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_S)); keySelector_->addItem("T", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_T)); keySelector_->addItem("U", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_U)); keySelector_->addItem("V", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_V)); keySelector_->addItem("W", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_W)); keySelector_->addItem("X", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_X)); keySelector_->addItem("Y", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Y)); keySelector_->addItem("Z", QVariant::fromValue<FakeInput::KeyType>(FakeInput::Key_Z)); mouseButtonSelector_ = new QComboBox(); mouseButtonSelector_->addItem("Left", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Left)); mouseButtonSelector_->addItem("Middle", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Middle)); mouseButtonSelector_->addItem("Right", QVariant::fromValue<FakeInput::MouseButton>(FakeInput::Mouse_Right)); QLabel* xLabel = new QLabel("dx: "); QLabel* yLabel = new QLabel("dy: "); mouseMotionX_ = new QSpinBox(); mouseMotionX_->setSingleStep(50); mouseMotionX_->setMinimum(-10000); mouseMotionX_->setMaximum(10000); mouseMotionY_ = new QSpinBox(); mouseMotionY_->setSingleStep(50); mouseMotionY_->setMinimum(-10000); mouseMotionY_->setMaximum(10000); mouseWheelDirection_ = new QComboBox(); mouseWheelDirection_->addItem("Up"); mouseWheelDirection_->addItem("Down"); command_ = new QLineEdit(); QLabel* timeLabel = new QLabel("miliseconds: "); waitTime_ = new QSpinBox(); waitTime_->setSingleStep(50); waitTime_->setMaximum(10000); keyHBox->addWidget(keySelector_); mouseButtonHBox->addWidget(mouseButtonSelector_); mouseMotionHBox->addWidget(xLabel); mouseMotionHBox->addWidget(mouseMotionX_); mouseMotionHBox->addWidget(yLabel); mouseMotionHBox->addWidget(mouseMotionY_); mouseWheelHBox->addWidget(mouseWheelDirection_); commandHBox->addWidget(command_); waitHBox->addWidget(timeLabel); waitHBox->addWidget(waitTime_); keyOptions_->setLayout(keyHBox); mouseButtonOptions_->setLayout(mouseButtonHBox); mouseMotionOptions_->setLayout(mouseMotionHBox); mouseWheelOptions_->setLayout(mouseWheelHBox); commandOptions_->setLayout(commandHBox); waitOptions_->setLayout(waitHBox); QStackedWidget* stack = new QStackedWidget(this); stack->addWidget(keyOptions_); stack->addWidget(mouseButtonOptions_); stack->addWidget(mouseMotionOptions_); stack->addWidget(mouseWheelOptions_); stack->addWidget(commandOptions_); stack->addWidget(waitOptions_); vbox->addWidget(actionType_); vbox->addWidget(stack); vbox->addStretch(1); setLayout(vbox); connect(actionType_, SIGNAL(currentIndexChanged(int)), stack, SLOT(setCurrentIndex(int))); } QString ActionForm::addActionToSequence(FakeInput::ActionSequence& sequence) { QString infoText = ""; switch(actionType_->currentIndex()) { case 0: { FakeInput::KeyType keyType = keySelector_->itemData(keySelector_->currentIndex()).value<FakeInput::KeyType>(); FakeInput::Key key(keyType); sequence.press(key).release(key); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(key.name().c_str()); break; } case 1: { FakeInput::MouseButton mouseButton = mouseButtonSelector_ ->itemData(mouseButtonSelector_->currentIndex()) .value<FakeInput::MouseButton>(); sequence.press(mouseButton).release(mouseButton); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(mouseButtonSelector_->currentText()); break; } case 2: { sequence.moveMouse( mouseMotionX_->text().toInt(), mouseMotionY_->text().toInt() ); infoText = actionType_->currentText(); infoText.append(": [ dx: "); infoText.append(mouseMotionX_->text()); infoText.append(" ; dy: "); infoText.append(mouseMotionY_->text()); infoText.append(" ]"); break; } case 3: { infoText = actionType_->currentText(); infoText.append(": "); if(mouseWheelDirection_->currentIndex() == 0) { sequence.wheelUp(); infoText.append("Up"); } else { sequence.wheelDown(); infoText.append("Down"); } break; } case 4: { sequence.runCommand(command_->text().toAscii().data()); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(command_->text()); break; } case 5: { sequence.wait(waitTime_->text().toInt()); infoText = actionType_->currentText(); infoText.append(": "); infoText.append(waitTime_->text()); break; } default: break; } return infoText; }
40.57563
122
0.678264
977517e8392b771d384ba89083fc3b3c82cb0e5d
1,058
cpp
C++
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
joakimthun/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
16
2015-10-12T14:24:45.000Z
2021-07-20T01:56:04.000Z
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
null
null
null
src/Compiler/code_gen/builders/array_initializer_list_expression_builder.cpp
haifenghuang/Elsa
3be901149c1102d190dda1c7f3340417f03666c7
[ "MIT" ]
2
2017-11-12T01:39:09.000Z
2021-07-20T01:56:09.000Z
#include "array_initializer_list_expression_builder.h" #include "../vm_expression_visitor.h" namespace elsa { namespace compiler { void ArrayInitializerListExpressionBuilder::build(VMProgram* program, VMExpressionVisitor* visitor, ArrayInitializerListExpression* expression) { program->emit(OpCode::iconst); auto size = expression->get_values().size(); program->emit(static_cast<int>(size)); program->emit(OpCode::new_arr); auto type = expression->get_type()->get_struct_declaration_expression()->get_generic_type(); program->emit(static_cast<int>(type->get_vm_type())); auto local_index = visitor->current_scope()->create_new_local(); program->emit(OpCode::s_local); program->emit(static_cast<int>(local_index)); for (const auto& exp : expression->get_values()) { program->emit(OpCode::l_local); program->emit(static_cast<int>(local_index)); exp->accept(visitor); program->emit(OpCode::a_ele); } program->emit(OpCode::l_local); program->emit(static_cast<int>(local_index)); } } }
27.128205
145
0.721172