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
5feeb313522dbb912920abf6105287aa0f6676cb
9,638
cpp
C++
FDTD/EncodeOutput.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
FDTD/EncodeOutput.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
FDTD/EncodeOutput.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
/* * EncodeOutput.cpp * Trogdor6 * * Created by Paul Hansen on 3/23/11. * Copyright 2011 Stanford University. All rights reserved. * * This file is covered by the MIT license. See LICENSE.txt. */ #include "EncodeOutput.h" #include "SimulationDescription.h" #include "VoxelizedPartition.h" #include "operations/OutputEHDB.h" #include "rle/SupportRegion3.h" #include "rle/MergeRunlines.h" #include "Support.h" #include <vector> using namespace std; using namespace RLE; using namespace YeeUtilities; struct CallbackOutput { CallbackOutput(vector<RunlineOutput> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineOutput runline(indices[0], length); mRunlines.push_back(runline); } vector<RunlineOutput> & mRunlines; }; typedef CallbackOutput CallbackSource; struct CallbackSparseOutput { CallbackSparseOutput(vector<RunlineOutput> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineOutput runline(indices[0], length); mRunlines.push_back(runline); } vector<RunlineOutput> & mRunlines; }; struct CallbackOutputAverageTwo { CallbackOutputAverageTwo(vector<RunlineAverageTwo> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineAverageTwo runline(indices[0], indices[1], length); mRunlines.push_back(runline); } vector<RunlineAverageTwo> & mRunlines; }; struct CallbackTensorialOutput { CallbackTensorialOutput( vector<RunlineTensorialOutput> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineTensorialOutput runline(indices[0], indices[1], length); mRunlines.push_back(runline); } vector<RunlineTensorialOutput> & mRunlines; }; EncodeOutput:: EncodeOutput(const GridDescription & gridDesc, const VoxelizedPartition & vp) : mGridDesc(gridDesc), mVoxelGrid(vp) { } Pointer<OutputEHDB> EncodeOutput:: encode(const OutputDescription & outputDesc) const { Pointer<OutputEHDB> output(new OutputEHDB(outputDesc, gridDescription().dxyz(), gridDescription().dt(), gridDescription().origin())); SupportRegion3 supp, suppShifted; for (int ff = 0; ff < outputDesc.fields().size(); ff++) { const OutputField & field(outputDesc.fields().at(ff)); if (field.field() == kEE || field.field() == kHH) { if (field.ii() == field.jj()) encodeTensorialDiagonalOutput(*output, outputDesc, field); else encodeTensorialOffDiagonalOutput(*output, outputDesc, field); } else if (field.octant() == 0 || field.octant() == 7) encodeInterpolatedOutput(*output, outputDesc, field); else if (field.field() == kJ || field.field() == kM) encodeSparseOutput(*output, outputDesc, field); else encodeStandardOutput(*output, outputDesc, field); } return output; } void EncodeOutput:: encodeStandardOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); int xyz = field.ii(); const IndexArray3 & fieldIndices = voxelGrid().fieldIndices().field(field.field(), xyz); vector<RunlineOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); IndexArray3 outputIndices; restriction(fieldIndices, supp, outputIndices); IndexArray3 const* inds[] = { &outputIndices }; CallbackOutput callback(runlines); RLE::mergeOverlapping(inds, 1, callback); } output.appendField(field, runlines); } void EncodeOutput:: encodeSparseOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); int xyz = field.ii(); const IndexArray3 & fieldIndices = voxelGrid().fieldIndices().field(field.field(), xyz); vector<RunlineOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); SupportRegion3 emptyCells = supp - fieldIndices; IndexArray3 outputIndices, emptyIndices(emptyCells); restriction(fieldIndices, supp, outputIndices); IndexArray3 const* inds[] = { &outputIndices, &emptyIndices }; // this DOES work, using the standard output callback. CallbackOutput callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendField(field, runlines); } void EncodeOutput:: encodeInterpolatedOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); int xyz = field.ii(); const IndexArray3 & fieldIndices = voxelGrid().fieldIndices().field(field.field(), xyz); vector<RunlineAverageTwo> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); SupportRegion3 suppShifted; if (field.field() == kE || field.field() == kD || field.field() == kJ) { assert(field.octant() == 0); translate(supp, suppShifted, (-Vector3<std::int64_t>::unit(xyz)).asArray()); } else if (field.field() == kH || field.field() == kB || field.field() == kM) { assert(field.octant() == 7); translate(supp, suppShifted, Vector3<std::int64_t>::unit(xyz).asArray()); } else throw(std::logic_error("Bad field")); IndexArray3 outputIndices, outputIndicesShifted; restriction(fieldIndices, supp, outputIndices); restriction(fieldIndices, suppShifted, outputIndicesShifted); IndexArray3 const* inds[] = { &outputIndices, &outputIndicesShifted }; CallbackOutputAverageTwo callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendField(field, runlines); } void EncodeOutput:: encodeTensorialDiagonalOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); assert(field.field() == kEE || field.field() == kHH); int xyz = field.ii(); // These are the fields we want to output, e.g. Exx. const IndexArray3 & tensorialIndices = voxelGrid().fieldIndices().field(field.field(), xyz, xyz); vector<RunlineTensorialOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); // These are the "backup fields." For diagonal permittivities, the Exx // field is just ordinary Ex, since there are no Exy and Exz components. const IndexArray3 & vectorialIndices = (field.field() == kEE) ? voxelGrid().fieldIndices().e(xyz) : voxelGrid().fieldIndices().h(xyz); IndexArray3 mainIndices, backupIndices; restriction(tensorialIndices, supp, mainIndices); restriction(vectorialIndices, supp, backupIndices); IndexArray3 const* inds[] = { &mainIndices, &backupIndices }; CallbackTensorialOutput callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendTensorialDiagonalField(field, runlines); } void EncodeOutput:: encodeTensorialOffDiagonalOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() != field.jj()); assert(field.field() == kEE || field.field() == kHH); const IndexArray3 & tensorialIndices = voxelGrid().fieldIndices().field(field.field(), field.ii(), field.jj()); vector<RunlineTensorialOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); IndexArray3 outputIndices, emptyIndices(supp); restriction(tensorialIndices, supp, outputIndices); IndexArray3 const* inds[] = { &outputIndices, &emptyIndices }; CallbackTensorialOutput callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendTensorialOffDiagonalField(field, runlines); }
30.596825
88
0.630629
5fef168528168f3c92178c86d0dad2e17cfd3203
746
cpp
C++
codechef/lapindrome.cpp
NIKU-SINGH/problemsolving
f7dd9d065a945a2f59e84580f926d35949ce3be2
[ "MIT" ]
null
null
null
codechef/lapindrome.cpp
NIKU-SINGH/problemsolving
f7dd9d065a945a2f59e84580f926d35949ce3be2
[ "MIT" ]
1
2021-07-07T14:37:03.000Z
2021-07-07T14:39:58.000Z
codechef/lapindrome.cpp
NIKU-SINGH/problemsolving
f7dd9d065a945a2f59e84580f926d35949ce3be2
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { // your code goes here int t; cin>>t; while(t--) { string str; cin>>str; int n = str.length(); int part1freq[26] ={0}; int part2freq[26]={0}; for(int i=0;i<n/2;i++) { part1freq[str[i]-'a']++; } for(int j=(n+1)/2;j<n;j++) { part2freq[str[j]-'a']++; } int res=0; for(int i=0;i<26;i++) { if(part1freq[i] != part2freq[i]) { res++; break; } } if(res==0) cout<<"YES"<<"\n"; else cout<<"NO"<<"\n"; } return 0; }
16.217391
44
0.349866
5ff14ce2f2ce439eda50895e17a1e0e0c322c16d
773
hpp
C++
include/aikido/planner.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
include/aikido/planner.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
include/aikido/planner.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
#include "aikido/planner/PlanningResult.hpp" #include "aikido/planner/SnapPlanner.hpp" #include "aikido/planner/TrajectoryPostProcessor.hpp" #include "aikido/planner/World.hpp" #include "aikido/planner/ompl/BackwardCompatibility.hpp" #include "aikido/planner/ompl/CRRT.hpp" #include "aikido/planner/ompl/CRRTConnect.hpp" #include "aikido/planner/ompl/GeometricStateSpace.hpp" #include "aikido/planner/ompl/GoalRegion.hpp" #include "aikido/planner/ompl/MotionValidator.hpp" #include "aikido/planner/ompl/Planner.hpp" #include "aikido/planner/ompl/StateSampler.hpp" #include "aikido/planner/ompl/StateValidityChecker.hpp" #include "aikido/planner/ompl/dart.hpp" #include "aikido/planner/parabolic/ParabolicSmoother.hpp" #include "aikido/planner/parabolic/ParabolicTimer.hpp"
45.470588
57
0.818887
5ff9f69ce234ca1b3fd89957e617a022c9b3ee36
2,747
hpp
C++
R2017b/extern/include/multimedia/AudioDefs.hpp
catou93/pelican_test
23de9722c431fa0caa3c68d038de9423cfcdda80
[ "BSD-2-Clause" ]
5
2018-11-21T11:52:49.000Z
2021-04-14T03:13:31.000Z
R2017b/extern/include/multimedia/AudioDefs.hpp
catou93/pelican_test
23de9722c431fa0caa3c68d038de9423cfcdda80
[ "BSD-2-Clause" ]
3
2018-08-24T03:12:36.000Z
2019-09-29T06:21:32.000Z
R2017b/extern/include/multimedia/AudioDefs.hpp
catou93/pelican_test
23de9722c431fa0caa3c68d038de9423cfcdda80
[ "BSD-2-Clause" ]
4
2018-08-10T07:02:30.000Z
2022-03-09T07:20:16.000Z
/* * AudioDefs.h - Definitions for audio I/O * * Copyright 1995-2012 The MathWorks, Inc. */ #ifndef AUDIODEFS_H #define AUDIODEFS_H /* these follow Simulink data types, in simstruc_types.h */ typedef enum { AudioDataType_Double = 0, /* double */ AudioDataType_Single, /* float */ AudioDataType_Int8, /* char */ AudioDataType_Uint8, /* unsigned char */ AudioDataType_Int16, /* short */ AudioDataType_Uint16, /* unsigned short */ AudioDataType_Int32, /* long */ AudioDataType_Uint32, /* unsigned long */ AudioDataType_INVALID, /* bool */ AudioDataType_Int24, /* 24-bit signed */ AudioDataType_Uint24, /* 24-bit unsigned */ AudioDataType_NUM_TYPES } AudioDataType; static const int AudioDataTypeSize[] = {8,4,1,1,2,2,4,4,1,3,3}; static const int AudioDataTypeFloat[] = {1,1,0,0,0,0,0,0,0,0,0}; /* An enumeration of typical audio data types which is used on several masks. */ typedef enum { AudioDT_Invalid = 0, AudioDT_Derived = 1, AudioDT_Uint8, AudioDT_Int16, AudioDT_Int24, AudioDT_Single, AudioDT_NUM_TYPES } AudioDTE_Common; /* The default mapping from AudioDataTypes onto common audio data types */ static const AudioDTE_Common AudioDataTypeToCommonDTE[] = { AudioDT_Single, AudioDT_Single, AudioDT_Uint8, AudioDT_Uint8, AudioDT_Int16, AudioDT_Int16, AudioDT_Int24, AudioDT_Int24, AudioDT_Invalid, AudioDT_Int24, AudioDT_Int24 }; /* Mapping from common data types to Audio Data Types */ static const AudioDataType CommonDTEToAudioDataType[] = { AudioDataType_INVALID, AudioDataType_INVALID, AudioDataType_Uint8, AudioDataType_Int16, AudioDataType_Int24, AudioDataType_Single }; typedef struct { unsigned char isValid; /* zero if the file has no audio */ /* The following fields refer to the PCM format of the audio data as encoded in the file/device */ unsigned char isFloat; /* true if the samples are in floating-point format */ double sampleRate; /* audio sample rate */ int numBits; /* audio bit depth */ int numChannels; /* number of audio channels (typically 1 or two) */ /* The following fields refer to the format of the data in MATLAB/Simulink */ AudioDataType dataType; /* data type of audio samples */ int frameSize; /* number of audio samples per frame */ /* The name of the compression format, if we are writing a file */ const char* audioCompressor; /* set to NULL for none */ } MMAudioInfo; #endif /* AUDIODEFS_H */
30.865169
102
0.649072
5ffb6add8895c91cfa81e7e0f06f13ade6048f8a
2,942
cpp
C++
source/internal/logger.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
1
2016-04-26T04:16:55.000Z
2016-04-26T04:16:55.000Z
source/internal/logger.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
null
null
null
source/internal/logger.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
2
2016-04-14T16:57:03.000Z
2020-02-21T00:17:48.000Z
#include "internal/logger.hpp" #include <iostream> #include <fstream> #include <iomanip> #include <chrono> #include <ctime> // by default turn on both file and console // logging behaviors. #ifndef LIBKEEN_LOG_TO_CONSOLE # define LIBKEEN_LOG_TO_CONSOLE 1 #endif #ifndef LIBKEEN_LOG_TO_LOGFILE # define LIBKEEN_LOG_TO_LOGFILE 1 #endif namespace { std::string now() { auto now = std::chrono::system_clock::now(); auto now_time_t = std::chrono::system_clock::to_time_t(now); std::stringstream ss; ss << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %X"); return ss.str(); }} namespace libkeen { namespace internal { Logger::~Logger() { log("Logger " + mType + " is shutdown."); } Logger::Logger(const std::string& type) : mType(type) , mLogToFile(true) , mLogToConsole(true) { log("Logger " + mType + " is started."); } void Logger::log(const std::string& message) { #if LIBKEEN_LOG_TO_CONSOLE || LIBKEEN_LOG_TO_LOGFILE try { std::lock_guard<decltype(mMutex)> lock(mMutex); std::stringstream msg; msg << "[" << mType << "][" << std::this_thread::get_id() << "][" << now() << "]: " << message << std::endl; #if LIBKEEN_LOG_TO_CONSOLE if (mLogToConsole) { std::cout << msg.str(); } #endif // LIBKEEN_LOG_TO_CONSOLE #if LIBKEEN_LOG_TO_LOGFILE if (mLogToFile) { std::ofstream("libkeen.log", std::ios_base::app | std::ios_base::out) << msg.str(); } #endif // LIBKEEN_LOG_TO_LOGFILE } catch (const std::exception& ex) { std::cerr << "Logger failed: " << ex.what() << std::endl; } catch (...) { std::cerr << "Logger failed." << std::endl; } #endif } void Logger::enableLogToFile(bool on /*= true*/) { std::lock_guard<decltype(mMutex)> lock(mMutex); mLogToFile = on; } void Logger::enableLogToConsole(bool on /*= true*/) { std::lock_guard<decltype(mMutex)> lock(mMutex); mLogToConsole = on; } void Logger::pull(std::vector<LoggerRef>& container) { if (!container.empty()) container.clear(); container.push_back(loggers::debug()); container.push_back(loggers::error()); container.push_back(loggers::warn()); container.push_back(loggers::info()); } std::shared_ptr<Logger> loggers::debug() { static std::shared_ptr<Logger> debug_logger = std::make_shared<Logger>("debug"); return debug_logger; } std::shared_ptr<Logger> loggers::error() { static std::shared_ptr<Logger> error_logger = std::make_shared<Logger>("error"); return error_logger; } std::shared_ptr<Logger> loggers::warn() { static std::shared_ptr<Logger> warn_logger = std::make_shared<Logger>("warn"); return warn_logger; } std::shared_ptr<Logger> loggers::info() { static std::shared_ptr<Logger> info_logger = std::make_shared<Logger>("info"); return info_logger; } }}
22.120301
95
0.633583
5ffc113e32897d21acdfb1256f6c36cb28d1b377
4,297
cpp
C++
Project/AudioManager.cpp
OiCGame/GameJam01
7860098d235678cbe32215c733366d4fb973ea5e
[ "MIT" ]
null
null
null
Project/AudioManager.cpp
OiCGame/GameJam01
7860098d235678cbe32215c733366d4fb973ea5e
[ "MIT" ]
null
null
null
Project/AudioManager.cpp
OiCGame/GameJam01
7860098d235678cbe32215c733366d4fb973ea5e
[ "MIT" ]
null
null
null
#include "AudioManager.h" CAudioManager::CAudioManager() { } CAudioManager::~CAudioManager() { } CAudioManager& CAudioManager::Singleton(void) { static CAudioManager obj; return obj; } void CAudioManager::Play(SoundBufferKey key) { auto temp = SoundBufferAsset(key); auto it = std::find(m_pSounds.begin(), m_pSounds.end(), temp); if (it == m_pSounds.end()) { m_pSounds.push_back(temp); } // if if (temp) { temp->Play(); } // if } void CAudioManager::Play(SoundStreamBufferKey key) { auto temp = SoundStreamBufferAsset(key); auto it = std::find(m_pSounds.begin(), m_pSounds.end(), temp); if (it == m_pSounds.end()) { m_pSounds.push_back(temp); } // if if(temp){ temp->Play(); } // if } bool CAudioManager::Load(void) { if (!CSoundBufferAsset::Load(SoundBufferKey::Sound0, "shot1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if auto sound = SoundBufferAsset(SoundBufferKey::Sound0); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::boomerang, "boomerang1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::boomerang); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::shot_struck, "shot-struck1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::shot_struck); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::enemy_explosion, "enemy_explosion.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::enemy_explosion); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::player_explosion, "player_explosion.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::player_explosion); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::ok_se, "ok_se.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::ok_se); if (!CSoundBufferAsset::Load(SoundBufferKey::flash_01, "shakin1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::flash_01); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::flash_02, "shakin2.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::flash_02); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::item_get, "itemGet.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::item_get); m_pSounds.push_back(sound); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::Bgm0, "game_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if auto bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::Bgm0); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::title, "title_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::title); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::gameclear, "gameclear_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::gameclear); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::gameover, "gameover_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::gameover); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); return true; } void CAudioManager::Update(void) { for (auto sound : m_pSounds) { if (sound) { sound->Update(); } // if } // for } void CAudioManager::Release(void) { for (auto sound : m_pSounds) { if (sound) { sound->Release(); sound.reset(); } // if } // for m_pSounds.clear(); }
30.475177
92
0.695136
5ffca5a8fee1bfe85e677a558fb668dc73292ed0
472
cpp
C++
array/sumofallsubarray.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
5
2021-12-03T14:29:16.000Z
2022-02-04T09:06:37.000Z
array/sumofallsubarray.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
null
null
null
array/sumofallsubarray.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
2
2022-01-16T14:20:42.000Z
2022-01-17T06:49:01.000Z
//5 // 1 2 0 7 2 //o/p-> 1,3,3,10,12,2,2,9,11,0,7,9,7,9,2, #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int currsum=0; for (int i = 0; i < n; i++) { currsum=0; for (int j = i; j < n; j++) { currsum+=arr[j]; cout<<currsum<<","; } } return 0; }
14.30303
42
0.358051
5fff380e5006a8672a31e48f8f2f7a1f46761144
1,689
cpp
C++
ipc2/ipc2.cpp
Elexir-Stefan/ray-usermode
9a1c7d773496493482cf2e711fe1808b537db63a
[ "MIT" ]
null
null
null
ipc2/ipc2.cpp
Elexir-Stefan/ray-usermode
9a1c7d773496493482cf2e711fe1808b537db63a
[ "MIT" ]
null
null
null
ipc2/ipc2.cpp
Elexir-Stefan/ray-usermode
9a1c7d773496493482cf2e711fe1808b537db63a
[ "MIT" ]
null
null
null
#include <raykernel.h> #include <exception> #include <video/VideoStream.h> #include <processes/processes.h> #include <ipc/ipc.h> #include <sstream> using namespace Kernel; using namespace Kernel::IPC; using namespace Kernel::Processes; /** * TestFunction used as callback */ int TestFunction(int arg2, float arg3) { kout << "This function worked properly! " << arg2 << VideoStream::endl; return 666; } char* ToString(int number, char* result) { char* nPtr = result + strlen(result); std::ostringstream sin; sin << number; strcpy(nPtr, sin.str().c_str()); return result; } float AnotherTestFunction(char arg1, int arg2, int arg3) { kout << "This is another test function -- " << arg2 << " (" << arg3 << ")" << VideoStream::endl; return 1.4142f; } int UserProgramEntry(const char *arguments) { try { Sync waitForOther = Sync("dingsbums", TRUE); // Register our connection Communication::Register("andererProzess", "Wartet auf eine Verbindung"); Socket& socket = Communication::CreateSocket("dessenSocket"); socket.AddLocalCallback(int, TestFunction, int, float); socket.AddLocalCallback(char*, ToString, int, char*); socket.AddRemoteMethod(char, int, float); socket.AddRemoteMethod(float, char, int, int); try { UNUSED Plug* plug = new Plug(socket); waitForOther.Go(TRUE); } catch(IPCSetupException &e) { kout << "An error occured while registering the socket!" << VideoStream::endl; } Thread::Sleep(); // never reaches this point... return 0; } catch (IPCSetupException &e) { kout << "An error occured while setting up the communication wall." << VideoStream::endl; return -1; } }
19.870588
97
0.6791
2700c4b0db0f1c1293d72965144c99c28dd89578
1,540
cpp
C++
Accepted_The 2000's ACM-ICPC/P2783 (Robots).cpp
peneksglazami/acm-icpc-training
a3c41b65b8f8523713f9859b076f300a12c4e7f3
[ "CC0-1.0" ]
null
null
null
Accepted_The 2000's ACM-ICPC/P2783 (Robots).cpp
peneksglazami/acm-icpc-training
a3c41b65b8f8523713f9859b076f300a12c4e7f3
[ "CC0-1.0" ]
null
null
null
Accepted_The 2000's ACM-ICPC/P2783 (Robots).cpp
peneksglazami/acm-icpc-training
a3c41b65b8f8523713f9859b076f300a12c4e7f3
[ "CC0-1.0" ]
null
null
null
/*************************************************** Problem: 2783 - Robots ACM ICPC - North America - Mid Central - 2003/2004 Solved by Andrey Grigorov ***************************************************/ #include <stdio.h> #include <vector> #include <queue> using namespace std; typedef struct{ int row,col; } garbage; class Compare{ public: bool operator()(garbage a, garbage b){ return ((a.row > b.row) || ((a.row == b.row) && (a.col > b.col))); } }; int main(){ priority_queue <garbage, vector<garbage>, Compare > pq1,pq2; int r,c,rob_cnt; garbage g,cur_g; scanf("%d %d",&r,&c); while ((r != -1) || (c != -1)){ while (!pq1.empty()) pq1.pop(); while (!pq2.empty()) pq2.pop(); do{ g.row = r; g.col = c; pq1.push(g); scanf("%d %d",&r,&c); }while (r || c); rob_cnt = 0; while (!pq1.empty()){ rob_cnt++; g.row = 0; g.col = 0; while (!pq1.empty()){ cur_g = pq1.top(); pq1.pop(); if ((g.row <= cur_g.row) && (g.col <= cur_g.col)){ g = cur_g; } else pq2.push(cur_g); } while (!pq2.empty()){ pq1.push(pq2.top()); pq2.pop(); } } printf("%d\n",rob_cnt); scanf("%d %d",&r,&c); } return 0; }
24.83871
78
0.380519
dfd6b713f18b58b836b96f6fc5f669da6bc435ff
517
cpp
C++
cpp/data/grid.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
cpp/data/grid.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
cpp/data/grid.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
#include "grid.h" void Grid::binarize(ConstVecRef<float> row, VecRef<uint8_t> dst) const { for (int64_t f = 0; f < features_.size(); ++f) { dst[f] = computeBin(row[origFeatureIndex(f)], borders_[f]); } } void Grid::binarize(const Vec& x, Buffer<uint8_t>& to) const { assert(x.device().deviceType() == ComputeDeviceType::Cpu); assert(to.device().deviceType() == ComputeDeviceType::Cpu); const auto values = x.arrayRef(); const auto dst = to.arrayRef(); binarize(values, dst); }
28.722222
72
0.644101
dfd8d1e701891eb5373cf737aa8c8970666e3637
699
cpp
C++
Luogu/luogu4317.cpp
wzl19371/OI-LIfe
f7f54542d1369b5e4047fcbb2e26c1c64d22ee26
[ "MIT" ]
1
2020-10-05T02:07:52.000Z
2020-10-05T02:07:52.000Z
Luogu/luogu4317.cpp
wzl19371/OI-LIfe
f7f54542d1369b5e4047fcbb2e26c1c64d22ee26
[ "MIT" ]
null
null
null
Luogu/luogu4317.cpp
wzl19371/OI-LIfe
f7f54542d1369b5e4047fcbb2e26c1c64d22ee26
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; typedef long long ll; const ll p=10000007; ll n,f[107][107],t[107]; ll qpow(ll x,ll y){ ll ans=1; while(y){ if(y&1) ans=ans*x%p; x=x*x%p; y>>=1; } return ans; } ll dp(int n,int m){ if(m>n||!n||m<0) return 0; if(f[n][m]) return f[n][m]; if(n==m||!m) return f[n][m]=1; return f[n][m]=dp(n-1,m)+dp(n-1,m-1); } int main(){ scanf("%lld",&n); for(int i=1;i<=60;i++) for(int j=1;j<=60;j++) dp(i,j); int ct=0; for(ll i=60;i>=0;i--){ if(n&(1ll<<i)){ for(int j=1;j<=i;j++) t[ct+j]+=f[i][j]; t[++ct]++; } } ll ans=1; for(int i=1;i<=60;i++) ans=ans*qpow(i,t[i])%p; printf("%lld\n",ans); return 0; }
19.416667
57
0.492132
dfdbd34f1489377b3c0d503948724cef06abae30
389
cpp
C++
Competitive Programming/part_02/deque.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
1
2022-03-24T06:38:53.000Z
2022-03-24T06:38:53.000Z
Competitive Programming/part_02/deque.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
null
null
null
Competitive Programming/part_02/deque.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> int main(){ std::deque<int> d1; std::deque<int> d2(5, 10); std::deque<int> d3(d2); std::deque<int> d4(d2.begin(), d2.end()); int arr[] = {1,2,3,4,5}; std::deque<int> d5(arr, arr+5); for(auto &el : d5){ std::cout<<el<<" "; } if(d5.empty()){ std::cout<<"Oh No"; } d1.push_back(10); d1.push_front(20); d1.emplace_back(10); d1.emplace_front(20); }
18.52381
42
0.573265
dfdd67d54ff9a7d7661d3955809d73d17cbbd4ba
54,704
cxx
C++
ds/ds/src/ldap/client/bind.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/ds/src/ldap/client/bind.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/ds/src/ldap/client/bind.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: bind.c send a bind to an LDAP server Abstract: This module implements the LDAP ldap_bind API. Author: Andy Herron (andyhe) 08-May-1996 Anoop Anantha (AnoopA) 24-Jun-1998 Revision History: --*/ #include "precomp.h" #pragma hdrstop #include "ldapp2.hxx" BOOLEAN FailedntdsapiLoadLib = FALSE; ULONG LdapNonUnicodeBind ( LDAP *ExternalHandle, PCHAR DistName, PCHAR Cred, ULONG Method, BOOLEAN Synchronous ); ULONG LdapGetServiceNameForBind ( PLDAP_CONN Connection, struct l_timeval *Timeout, ULONG AuthMethod ); PWCHAR LdapMakeServiceNameFromHostName ( PWCHAR HostName ); // // This routine is one of the main entry points for clients calling into the // ldap API. // ULONG __cdecl ldap_simple_bindW ( LDAP *ExternalHandle, PWCHAR DistName, PWCHAR PassWord ) { ULONG err; PLDAP_CONN connection = NULL; connection = GetConnectionPointer(ExternalHandle); if (connection == NULL) { return (ULONG) -1; } err = LdapBind( connection, DistName, LDAP_AUTH_SIMPLE, PassWord, FALSE); DereferenceLdapConnection( connection ); return err; } ULONG __cdecl ldap_simple_bind_sW ( LDAP *ExternalHandle, PWCHAR DistName, PWCHAR PassWord ) { ULONG err; PLDAP_CONN connection = NULL; connection = GetConnectionPointer(ExternalHandle); if (connection == NULL) { return LDAP_PARAM_ERROR; } err = LdapBind( connection, DistName, LDAP_AUTH_SIMPLE, PassWord, TRUE); DereferenceLdapConnection( connection ); return err; } ULONG __cdecl ldap_bindW ( LDAP *ExternalHandle, PWCHAR DistName, PWCHAR Cred, ULONG Method ) { ULONG err; PLDAP_CONN connection = NULL; connection = GetConnectionPointer(ExternalHandle); if (connection == NULL) { return (ULONG) -1; } err = LdapBind( connection, DistName, Method, Cred, FALSE); DereferenceLdapConnection( connection ); return err; } ULONG __cdecl ldap_bind_sW ( LDAP *ExternalHandle, PWCHAR DistName, PWCHAR Cred, ULONG Method ) { ULONG err; PLDAP_CONN connection = NULL; connection = GetConnectionPointer(ExternalHandle); if (connection == NULL) { return LDAP_PARAM_ERROR; } err = LdapBind( connection, DistName, Method, Cred, TRUE); DereferenceLdapConnection( connection ); return err; } ULONG __cdecl ldap_simple_bind ( LDAP *ExternalHandle, PCHAR DistName, PCHAR PassWord ) { return LdapNonUnicodeBind( ExternalHandle, DistName, PassWord, LDAP_AUTH_SIMPLE, FALSE ); } ULONG __cdecl ldap_simple_bind_s ( LDAP *ExternalHandle, PCHAR DistName, PCHAR PassWord ) { return LdapNonUnicodeBind( ExternalHandle, DistName, PassWord, LDAP_AUTH_SIMPLE, TRUE ); } ULONG __cdecl ldap_bind ( LDAP *ExternalHandle, PCHAR DistName, PCHAR Cred, ULONG Method ) { return LdapNonUnicodeBind( ExternalHandle, DistName, Cred, Method, FALSE ); } ULONG __cdecl ldap_bind_s ( LDAP *ExternalHandle, PCHAR DistName, PCHAR Cred, ULONG Method ) { return LdapNonUnicodeBind( ExternalHandle, DistName, Cred, Method, TRUE ); } ULONG LdapNonUnicodeBind ( LDAP *ExternalHandle, PCHAR DistName, PCHAR Cred, ULONG Method, BOOLEAN Synchronous ) { ULONG err; PWCHAR wName = NULL; PWCHAR wPassword = NULL; PLDAP_CONN connection = NULL; connection = GetConnectionPointer(ExternalHandle); if (connection == NULL) { return (ULONG) ( Synchronous ? LDAP_PARAM_ERROR : -1 ); } err = ToUnicodeWithAlloc( DistName, -1, &wName, LDAP_UNICODE_SIGNATURE, LANG_ACP ); if (err != LDAP_SUCCESS) { goto error; } if (Method != LDAP_AUTH_SIMPLE) { wPassword = (PWCHAR) Cred; } else { err = ToUnicodeWithAlloc( Cred, -1, &wPassword, LDAP_UNICODE_SIGNATURE, LANG_ACP ); } if (err != LDAP_SUCCESS) { goto error; } err = LdapBind( connection, wName, Method, wPassword, Synchronous); error: if (wName) { ldapFree( wName, LDAP_UNICODE_SIGNATURE ); } if (Method == LDAP_AUTH_SIMPLE && wPassword) { ldapFree( wPassword, LDAP_UNICODE_SIGNATURE ); } DereferenceLdapConnection( connection ); return err; } ULONG LdapBind ( PLDAP_CONN connection, PWCHAR BindDistName, ULONG Method, PWCHAR BindCred, BOOLEAN Synchronous ) // // This routine sends a bind request to the server and optionally waits // for a reply. // // If the call is Sychronous, it returns the LDAP error code. Otherwise it // returns either -1 for failure or the LDAP message number if successful. // { ULONG err; PLDAP_REQUEST request = NULL; BOOLEAN haveLock = FALSE; BOOLEAN resetBindInProgress = FALSE; LONG messageNumber = 0; ULONG credentialLength = 0; ULONG oldVersion; struct l_timeval BindTimeout; ULONG initialBindError = LDAP_SUCCESS; BOOLEAN terminateConnection = FALSE; BOOLEAN fSentMessage = FALSE; LUID savedCurrentLogonId = {0, 0}; #if DBG ULONGLONG startTime = LdapGetTickCount(); #endif ULONG flags = ( connection->NegotiateFlags == DEFAULT_NEGOTIATE_FLAGS ) ? ( 0 ) : connection->NegotiateFlags; ASSERT(connection != NULL); err = LdapConnect( connection, NULL, FALSE ); if (err != 0) { return (ULONG) ( Synchronous ? err : -1 ); } if (!connection->WhistlerServer) { // // If this is a second bind on a connection which has signing/sealing // turned on, we must disallow it. This is by design because the server can't // handle multiple binds on a signed/sealed connection. // if (connection->CurrentSignStatus || connection->CurrentSealStatus) { LdapPrint0("Second Bind is illegal on a signed/sealed connection\n"); return LDAP_UNWILLING_TO_PERFORM; } } oldVersion = connection->publicLdapStruct.ld_version; if (( Method == LDAP_AUTH_NEGOTIATE ) || ( Method == LDAP_AUTH_DIGEST )){ // // set the connection type to LDAP v3. // connection->publicLdapStruct.ld_version = LDAP_VERSION3; } CLdapBer lber( connection->publicLdapStruct.ld_version ); // // we initially set the error state to success so that the lowest layer // can set it accurately. // SetConnectionError( connection, LDAP_SUCCESS, NULL ); IF_DEBUG(CONNECTION) { LdapPrint2( "ldap_bind called for conn 0x%x, host is %s.\n", connection, connection->publicLdapStruct.ld_host); } ACQUIRE_LOCK( &connection->StateLock ); haveLock = TRUE; if ((connection->ConcurrentBind) && (Method != LDAP_AUTH_SIMPLE)) { IF_DEBUG(CONNECTION) { LdapPrint2( "ldap_bind connection 0x%x in concurrent mode but method=0x%x\n", connection, Method); } err = LDAP_UNWILLING_TO_PERFORM; SetConnectionError( connection, err, NULL ); goto exitBind; } if (connection->ConnObjectState != ConnObjectActive) { IF_DEBUG(CONNECTION) { LdapPrint1( "ldap_bind connection 0x%x is closing.\n", connection); } err = LDAP_PARAM_ERROR; SetConnectionError( connection, err, NULL ); goto exitBind; } // // Free existing DN if we have one for the current connection // ldapFree( connection->DNOnBind, LDAP_USER_DN_SIGNATURE ); connection->DNOnBind = NULL; // // If someone sends a bind for a v2 CLDAP session, just remember the // DN for the search request and we're done. // if ((connection->UdpHandle != INVALID_SOCKET) && (connection->publicLdapStruct.ld_version == LDAP_VERSION2)) { IF_DEBUG(CONNECTION) { LdapPrint1( "ldap_bind connection 0x%x is connectionless.\n", connection); } if (BindDistName != NULL) { ULONG dnLength = strlenW( BindDistName ); if (dnLength > 0) { connection->DNOnBind = (PLDAPDN) ldapMalloc( (dnLength + 1) * sizeof(WCHAR), LDAP_USER_DN_SIGNATURE ); if (connection->DNOnBind != NULL) { CopyMemory( connection->DNOnBind, BindDistName, dnLength * sizeof(WCHAR) ); } } } err = LDAP_SUCCESS; messageNumber = -1; // if they do an async call, we need to return // an invalid msg number so they don't try to // wait on it. They'd wait a LONG time. goto exitBind; } if (connection->TcpHandle == INVALID_SOCKET) { IF_DEBUG(NETWORK_ERRORS) { LdapPrint1( "ldap_bind connection 0x%x is connectionless.\n", connection); } err = LDAP_PROTOCOL_ERROR; SetConnectionError( connection, err, NULL ); goto exitBind; } if (!connection->ConcurrentBind) { if (connection->BindInProgress == TRUE) { IF_DEBUG(API_ERRORS) { LdapPrint1( "ldap_bind connection 0x%x has bind in progress.\n", connection); } err = LDAP_LOCAL_ERROR; SetConnectionError( connection, err, NULL ); goto exitBind; } connection->BindInProgress = TRUE; } resetBindInProgress = TRUE; FreeCurrentCredentials( connection ); RELEASE_LOCK( &connection->StateLock ); haveLock = FALSE; if (( Method != LDAP_AUTH_SIMPLE ) && ( Method != LDAP_AUTH_EXTERNAL )) { if ( ! Synchronous ) { // // All of these methods must be called through // the synchronous handler routine. // err = LDAP_PARAM_ERROR; goto exitBind; } if (!LdapInitSecurity()) { IF_DEBUG(API_ERRORS) { LdapPrint1( "ldap_bind connection 0x%x failed to init security.\n", connection); } err = LDAP_LOCAL_ERROR; SetConnectionError( connection, err, NULL ); goto exitBind; } err = LDAP_AUTH_METHOD_NOT_SUPPORTED; // // Get the specific auth details set up. // if ( Method == LDAP_AUTH_SICILY ) { err = LdapTryAllMsnAuthentication( connection, BindCred ); } else if ( Method == LDAP_AUTH_NEGOTIATE ) { if (( SspiPackageNegotiate ) || (connection->PreferredSecurityPackage)) { // // Determine the service name to use for kerberos auth. // This has to be regenerated each time a bind is performed // including the autoreconnect scenario. // // AnoopA: 2/4/98 // We need to put in a timeout because we were hanging // when the server failed to respond to our searches // if (connection->publicLdapStruct.ld_timelimit != 0) { BindTimeout.tv_sec = connection->publicLdapStruct.ld_timelimit; } else { BindTimeout.tv_sec = 120; } BindTimeout.tv_usec = 0; LdapDetermineServerVersion(connection, &BindTimeout, &(connection->WhistlerServer)); if (connection->ServiceNameForBind != NULL) { ldapFree( connection->ServiceNameForBind, LDAP_SERVICE_NAME_SIGNATURE ); connection->ServiceNameForBind = NULL; } err = LdapGetServiceNameForBind( connection, &BindTimeout, Method ); IF_DEBUG(BIND) { LdapPrint1("New servicename for bind is %S\n", connection->ServiceNameForBind); } // // For LDAP_AUTH_NEGOTIATE, we expect the credentials // to be either NULL (to indicate the locally logged // on user), or to contain a SEC_WINNT_AUTH_IDENTITY // structure. // if ( (err != LDAP_OPERATIONS_ERROR) && (err != LDAP_SERVER_DOWN) && (err != LDAP_REFERRAL_V2) && (err != LDAP_TIMEOUT) ) { PWCHAR serviceNameForBind; if ((!connection->ForceHostBasedSPN) && (connection->ServiceNameForBind != NULL)) { serviceNameForBind = connection->ServiceNameForBind; } else { serviceNameForBind = LdapMakeServiceNameFromHostName(connection->HostNameW); if (!serviceNameForBind) { IF_DEBUG(OUTMEMORY) { LdapPrint1( "ldap_bind connection 0x%x couldn't allocate service name.\n", connection); } err = LDAP_NO_MEMORY; SetConnectionError( connection, err, NULL ); goto exitBind; } } // // A third party server like Netscape might support // DIGEST-MD5 but not support GSS-SPNEGO // if (SspiPackageDigest && !connection->PreferredSecurityPackage && !connection->SupportsGSS_SPNEGO && connection->SupportsDIGEST ) { flags = connection->NegotiateFlags; Method = LDAP_AUTH_DIGEST; if (serviceNameForBind != connection->ServiceNameForBind) { // must have come from LdapMakeServiceNameFromHostName ldapFree(serviceNameForBind, LDAP_SERVICE_NAME_SIGNATURE); } goto TryIndividualAuthMethods; } else { err = LdapSspiBind( connection, (connection->PreferredSecurityPackage)? connection->PreferredSecurityPackage: SspiPackageNegotiate, Method, connection->NegotiateFlags, BindDistName, serviceNameForBind, BindCred ); } initialBindError = err; if (serviceNameForBind != connection->ServiceNameForBind) { // must have come from LdapMakeServiceNameFromHostName // --> need to free it ldapFree(serviceNameForBind, LDAP_SERVICE_NAME_SIGNATURE); } } if (err == LDAP_PROTOCOL_ERROR) { // // if the server doesn't support v3, we back off to // NTLM authentication. // connection->publicLdapStruct.ld_version = LDAP_VERSION2; Method = LDAP_AUTH_NTLM; goto TryIndividualAuthMethods; } else if (err == LDAP_AUTH_METHOD_NOT_SUPPORTED) { // // if the server doesn't support v3, we back off to // NTLM authentication. // connection->publicLdapStruct.ld_version = oldVersion; Method = LDAP_AUTH_NTLM; goto TryIndividualAuthMethods; } else if (err == LDAP_TIMEOUT || err == LDAP_SERVER_DOWN) { // // The server failed to respond to our search request // Abort the bind // goto exitBind; } } } else { TryIndividualAuthMethods: // // These are the same on the wire as when // LDAP_AUTH_SICILY is used, but they skip // the package enumeration and authenticate // directly as requested. // if (connection->publicLdapStruct.ld_timelimit != 0) { BindTimeout.tv_sec = connection->publicLdapStruct.ld_timelimit; } else { BindTimeout.tv_sec = 120; } BindTimeout.tv_usec = 0; LdapDetermineServerVersion(connection, &BindTimeout, &(connection->WhistlerServer)); if ((Method == LDAP_AUTH_DPA) && (SspiPackageDpa != NULL)) { err = LdapSspiBind( connection, SspiPackageDpa, Method, flags, L"DPA", NULL, BindCred ); } else if ((Method == LDAP_AUTH_MSN) && (SspiPackageSicily != NULL)) { err = LdapSspiBind( connection, SspiPackageSicily, Method, flags, L"MSN", NULL, BindCred ); } else if ((Method == LDAP_AUTH_NTLM) && (SspiPackageNtlm != NULL)) { err = LdapSspiBind( connection, SspiPackageNtlm, Method, flags, L"NTLM", NULL, BindCred ); } else if ((Method == LDAP_AUTH_DIGEST) && (SspiPackageDigest != NULL)) { // // Read the RootDSE and also determine the SPN to use. // ldapFree( connection->ServiceNameForBind, LDAP_SERVICE_NAME_SIGNATURE ); connection->ServiceNameForBind = NULL; err = LdapGetServiceNameForBind( connection, &BindTimeout, Method ); PWCHAR serviceNameForBind = NULL; if ((!connection->ForceHostBasedSPN) && (connection->ServiceNameForBind != NULL)) { serviceNameForBind = connection->ServiceNameForBind; } else { serviceNameForBind = LdapMakeServiceNameFromHostName(connection->HostNameW); if (!serviceNameForBind) { IF_DEBUG(OUTMEMORY) { LdapPrint1( "ldap_bind connection 0x%x couldn't allocate service name.\n", connection); } err = LDAP_NO_MEMORY; SetConnectionError( connection, err, NULL ); goto exitBind; } } if (err == LDAP_SUCCESS) { err = LdapSspiBind( connection, SspiPackageDigest, Method, flags, NULL, serviceNameForBind, BindCred ); } if (serviceNameForBind != connection->ServiceNameForBind) { // must have come from LdapMakeServiceNameFromHostName // --> need to free it ldapFree(serviceNameForBind, LDAP_SERVICE_NAME_SIGNATURE); } } } } else if ( Method == LDAP_AUTH_SIMPLE ) { // // Simple authentication. // request = LdapCreateRequest( connection, LDAP_BIND_CMD ); if (request == NULL) { IF_DEBUG(OUTMEMORY) { LdapPrint1( "ldap_bind connection 0x%x couldn't allocate request.\n", connection); } err = LDAP_NO_MEMORY; SetConnectionError( connection, err, NULL ); goto exitBind; } messageNumber = request->MessageId; request->ChaseReferrals = 0; // // Make sure this no other waiting thread steals a response meant // for us. // request->Synchronous = Synchronous; // // format the bind request. // if ((connection->publicLdapStruct.ld_version == LDAP_VERSION2) || (connection->publicLdapStruct.ld_version == LDAP_VERSION3)) { // // the ldapv2 Bind message looks like this : // // [APPLICATION 0] (IMPLICIT) SEQUENCE { // version (INTEGER) // szDN (LDAPDN) // authentication CHOICE { // simple [0] OCTET STRING // [... other choices ...] // } // } err = lber.HrStartWriteSequence(); if (err != NOERROR) { SetConnectionError( connection, err, NULL ); goto exitBind; } err = lber.HrAddValue( messageNumber ); if (err != NOERROR) { SetConnectionError( connection, err, NULL ); goto exitBind; } err = lber.HrStartWriteSequence(LDAP_BIND_CMD); if (err != NOERROR) { SetConnectionError( connection, err, NULL ); goto exitBind; } err = lber.HrAddValue((LONG) connection->publicLdapStruct.ld_version); if (err != NOERROR) { SetConnectionError( connection, err, NULL ); goto exitBind; } err = lber.HrAddValue((const WCHAR *) BindDistName ); if (err != NOERROR) { SetConnectionError( connection, err, NULL ); goto exitBind; } WCHAR nullStr = L'\0'; PWCHAR credentials = BindCred; if (credentials != NULL) { credentialLength = (strlenW( credentials ) + 1) * sizeof(WCHAR); err = lber.HrAddValue((const WCHAR *) credentials, Method ); } else { credentials = &nullStr; err = lber.HrAddBinaryValue( (BYTE *) credentials, 0, Method ); } if (err != NOERROR) { SetConnectionError( connection, err, NULL ); goto exitBind; } err = lber.HrEndWriteSequence(); ASSERT(err == NOERROR); err = lber.HrEndWriteSequence(); ASSERT(err == NOERROR); } else { IF_DEBUG(API_ERRORS) { LdapPrint2( "ldap_bind connection 0x%x asked for version 0x%x.\n", connection, connection->publicLdapStruct.ld_version ); } err = LDAP_PROTOCOL_ERROR; SetConnectionError( connection, err, NULL ); goto exitBind; } // // send the bind request. // ACQUIRE_LOCK( &connection->ReconnectLock ); AddToPendingList( request, connection ); err = LdapSend( connection, &lber ); if (err != LDAP_SUCCESS) { IF_DEBUG(NETWORK_ERRORS) { LdapPrint2( "ldap_bind connection 0x%x send with error of 0x%x.\n", connection, err ); } DecrementPendingList( request, connection ); RELEASE_LOCK( &connection->ReconnectLock ); } else { fSentMessage = TRUE; RELEASE_LOCK( &connection->ReconnectLock ); if (Synchronous) { PLDAPMessage message = NULL; ULONG timeout = LDAP_BIND_TIME_LIMIT_DEFAULT; if (connection->publicLdapStruct.ld_timelimit != 0) { timeout = connection->publicLdapStruct.ld_timelimit * 1000; } err = LdapWaitForResponseFromServer( connection, request, timeout, FALSE, /// not search results &message, TRUE ); // Disable autoreconnect if (err == LDAP_SUCCESS) { if (message != NULL) { err = message->lm_returncode; } else { ASSERT( connection->ServerDown ); err = LDAP_SERVER_DOWN; IF_DEBUG(SERVERDOWN) { LdapPrint2( "ldapBind thread 0x%x has connection 0x%x as down.\n", GetCurrentThreadId(), connection ); } } IF_DEBUG(TRACE1) { LdapPrint2( "LdapBind conn 0x%x gets response of 0x%x from server.\n", connection, err ); } } else { IF_DEBUG(TRACE2) { LdapPrint2( "LdapBind conn 0x%x didn't get response from server, 0x%x.\n", connection, err ); } } if (message != NULL) { ldap_msgfree( message ); } } } } else { // // External authentication. From draft-ietf-ldapext-authmeth-04.txt, // the DN contains the Authorization Id of the following two forms: // // ; distinguished-name-based authz id. // dnAuthzId = "dn:" dn // dn = utf8string ; with syntax defined in RFC 2253 // // ; unspecified userid, UTF-8 encoded. // uAuthzId = "u:" userid // userid = utf8string ; syntax unspecified // // One of the above authzIds will be part of the credentials field in // the SASL credentials field. // ASSERT( Method == LDAP_AUTH_EXTERNAL ); if ( BindCred || (! Synchronous)) { // // You can't specify credentials in an EXTERNAL SASL bind nor // can it be called asynchronously. // err = LDAP_PARAM_ERROR; goto exitBind; } err = LdapExchangeOpaqueToken(connection, LDAP_AUTH_SASL, // auth mechanism L"EXTERNAL", // oid BindDistName, // authzId NULL, // Credentials 0, // Credential length NULL, // return data NULL, // return data in berval form NULL, // server controls NULL, // client controls (PULONG) &messageNumber,// Message Number FALSE, // Send only TRUE, // Controls are unicode &fSentMessage // did the message get sent? ); } // End of EXTERNAL auth. if (( Method == LDAP_AUTH_SIMPLE ) || ( Method == LDAP_AUTH_EXTERNAL )) { // For non-SSPI bind methods, we want to clear the security context (if any) // of the connection, in case this was a re-bind following a previous // SSPI bind. We also need to clear any signing/sealing left over from // the previous bind. We do this only if we got to the point of actually // sending the bind message to the server. if (fSentMessage) { // We save off the LUID so that, if we're reconnecting, we can later // restore the previous LUID rather than overwrite it with a new one savedCurrentLogonId = connection->CurrentLogonId; CloseCredentials( connection ); ACQUIRE_LOCK(&ConnectionListLock) if ((connection->SecureStream) && (connection->CurrentSignStatus || connection->CurrentSealStatus)) { PSECURESTREAM pTemp; pTemp = (PSECURESTREAM) connection->SecureStream; delete pTemp; connection->SecureStream = NULL; connection->CurrentSignStatus = FALSE; connection->CurrentSealStatus = FALSE; } RELEASE_LOCK(&ConnectionListLock) } } if (err == LDAP_SUCCESS) { // // save off the credentials we used to get to this server // ACQUIRE_LOCK( &connection->StateLock ); ldapFree( connection->DNOnBind, LDAP_USER_DN_SIGNATURE ); connection->DNOnBind = NULL; if (( Method == LDAP_AUTH_SIMPLE ) || ( Method == LDAP_AUTH_EXTERNAL )) { FreeCurrentCredentials(connection); if (credentialLength > 0) { // Note that we'll need up to (DES_BLOCKLEN-1) bytes of padding for RtlEncryptMemory connection->CurrentCredentials = (PWCHAR) ldapMalloc( credentialLength + 1 + (DES_BLOCKLEN-1), LDAP_CREDENTIALS_SIGNATURE ); if ( connection->CurrentCredentials != NULL ) { CopyMemory( connection->CurrentCredentials, BindCred, credentialLength ); if (GlobalUseScrambling) { ACQUIRE_LOCK( &connection->ScramblingLock ); pRtlInitUnicodeString( &connection->ScrambledCredentials, connection->CurrentCredentials); RoundUnicodeStringMaxLength(&connection->ScrambledCredentials, DES_BLOCKLEN); // // Scramble plain-text credentials // EncodeUnicodeString(&connection->ScrambledCredentials); connection->Scrambled = TRUE; RELEASE_LOCK( &connection->ScramblingLock ); } } } connection->BindMethod = Method; // save off the LUID for referral chasing if (!connection->Reconnecting) { GetCurrentLuid( &connection->CurrentLogonId ); } else { connection->CurrentLogonId = savedCurrentLogonId; } } connection->BindPerformed = TRUE; if (BindDistName != NULL) { ULONG dnLength = strlenW( BindDistName ) * sizeof(WCHAR); if (dnLength > 0) { connection->DNOnBind = (PLDAPDN) ldapMalloc( dnLength + sizeof(WCHAR), LDAP_USER_DN_SIGNATURE ); if (connection->DNOnBind != NULL) { CopyMemory( connection->DNOnBind, BindDistName, dnLength ); } } } RELEASE_LOCK( &connection->StateLock ); } exitBind: IF_DEBUG(BIND) { LdapPrint2( "ldap_bind returned err = 0x%x for connection 0x%x.\n", err, connection ); } if (resetBindInProgress == TRUE) { ldap_msgfree( connection->BindResponse ); connection->BindResponse = NULL; connection->BindInProgress = FALSE; } // // if the server returns a protocol error, RFC 2251 mandates // the client MUST close the connection as the server will // be unwilling to accept further operations. We mark // the connection as down so that future requests trigger // a disconnect/reconnect. // if ((err != LDAP_SUCCESS) && (terminateConnection == TRUE)) { if (!haveLock) { ACQUIRE_LOCK( &connection->StateLock ); } connection->HostConnectState = HostConnectStateError; if (!haveLock) { RELEASE_LOCK( &connection->StateLock ); } } if (haveLock) { RELEASE_LOCK( &connection->StateLock ); } if (! Synchronous) { if (err == LDAP_SUCCESS) { err = messageNumber; } else { err = (DWORD) -1; if (request != NULL) { CloseLdapRequest( request ); } } } else { if (request != NULL) { CloseLdapRequest( request ); } } if (request != NULL) { DereferenceLdapRequest( request ); } START_LOGGING; DSLOG((DSLOG_FLAG_TAG_CNPN,"[+][ID=0][OP=ldap_bind]")); DSLOG((0,"[DN=%ws][PA=0x%x][ST=%I64d][ET=%I64d][ER=%d][-]\n", BindDistName, Method, startTime, LdapGetTickCount(), err)); END_LOGGING; return err; } ULONG FreeCurrentCredentials ( PLDAP_CONN Connection ) { if (Connection->CurrentCredentials != NULL) { ULONG tag; if ( Connection->BindMethod == LDAP_AUTH_SIMPLE ) { tag = LDAP_CREDENTIALS_SIGNATURE; } else { tag = LDAP_SECURITY_SIGNATURE; } ldapSecureFree( Connection->CurrentCredentials, tag ); Connection->CurrentCredentials = NULL; } Connection->BindMethod = 0; if (GlobalUseScrambling) { pRtlInitUnicodeString( &Connection->ScrambledCredentials, NULL); } return LDAP_SUCCESS; } // important: must be lower-case, per RFC 2829, section 11 #define LDAP_SERVICE_PREFIX L"ldap" PWCHAR LdapMakeServiceNameFromHostName ( PWCHAR HostName ) { PWCHAR pszServiceName = NULL; if (!LoadUser32Now()) { return NULL; } pszServiceName = (PWCHAR) ldapMalloc( (strlenW(LDAP_SERVICE_PREFIX) + strlenW(HostName) + 2)*sizeof(WCHAR), LDAP_SERVICE_NAME_SIGNATURE); if (!pszServiceName) { return NULL; }; pfwsprintfW (pszServiceName, L"%s/%s", LDAP_SERVICE_PREFIX, HostName); return pszServiceName; } ULONG LdapGetServiceNameForBind ( PLDAP_CONN Connection, struct l_timeval *Timeout, ULONG AuthMethod ) { #define TEMPBUFFERSIZE 4096 PWCHAR pszSpn = NULL; DWORD pcSpnLength = TEMPBUFFERSIZE; PLDAP ldapConnection = Connection->ExternalInfo; ULONG err; PLDAPMessage results = NULL; ULONG oldChaseReferrals = Connection->publicLdapStruct.ld_options; BOOLEAN foundGSSAPI = FALSE; BOOLEAN foundGSS_SPNEGO = FALSE; BOOLEAN foundDIGEST = FALSE; USHORT PortNumber = 0; PWCHAR servicename = NULL; PWCHAR attrList[4] = { L"supportedSASLMechanisms", NULL }; // // We try to generate a service principle name if we have a fully qualified // machine name. // if ((Connection->DnsSuppliedName != NULL) && (NTDSLibraryHandle == NULL) && (!FailedntdsapiLoadLib) ){ // // Try to load ntdsapi.dll // ACQUIRE_LOCK( &LoadLibLock ); NTDSLibraryHandle = LoadSystem32LibraryA( "NTDSAPI.DLL" ); if (NTDSLibraryHandle != NULL) { pDsMakeSpnW = (FNDSMAKESPNW) GetProcAddress( NTDSLibraryHandle, "DsMakeSpnW" ); if (pDsMakeSpnW == NULL) { // // No big deal. We won't die if we don't get that function // Just don't try to load the dll again. // FailedntdsapiLoadLib = TRUE; FreeLibrary( NTDSLibraryHandle ); NTDSLibraryHandle = NULL; } } else { FailedntdsapiLoadLib = TRUE; } RELEASE_LOCK( &LoadLibLock ); } if (pDsMakeSpnW) { // // We have to decide what we want to pass in as the service name. If we // connect using an IP address, we are out of luck and end up reading // the rootDSE attribute anyway. // // AnoopA (1/27/99): I have to read the RootDSE ALWAYS to figure out if the // server is pre-GSS-SPNEGO or not. But, we will try our best to get the // servicename through DsMakeSpn and not from the RootDSE. // // // If we had a domain name, we must redirect it to the appropriate KDC by // supplying the @domain in the end. So, the new SPN will look like: // // LDAP/FQMN/FQDN@FQDN // pszSpn = (PWCHAR) ldapMalloc( TEMPBUFFERSIZE, LDAP_BUFFER_SIGNATURE ); if (!pszSpn) { goto ReadRootDSE; } if (Connection->DomainName) { LONG DomainLength = strlenW(Connection->DomainName); if (DomainLength >= TEMPBUFFERSIZE/8) { goto ReadRootDSE; } servicename = (PWCHAR)ldapMalloc( (DomainLength*2+2)* sizeof(WCHAR), LDAP_BUFFER_SIGNATURE); if (!servicename) { goto ReadRootDSE; } CopyMemory( servicename, Connection->DomainName, DomainLength * sizeof(WCHAR)); if ( (!(Connection->ResolvedGetDCFlags & DS_NDNC_FLAG)) && (AuthMethod != LDAP_AUTH_DIGEST) ) { // If binding to a non-domain naming context (NDNC), we don't // want to include the so-called DomainName (really, the NDNC name) // as a realm hint, because NDNCs aren't Kerberos realms. // It also doesn't make sense to include the realm hint in the Digest // case. *(servicename+DomainLength) = L'@'; CopyMemory( servicename + DomainLength+1, Connection->DomainName, DomainLength * sizeof(WCHAR)); } } else { servicename = Connection->DnsSuppliedName; } if ( (!((Connection->PortNumber == LDAP_PORT) || (Connection->PortNumber == LDAP_GC_PORT) || (Connection->PortNumber == LDAP_SSL_PORT) || (Connection->PortNumber == LDAP_SSL_GC_PORT))) && (AuthMethod != LDAP_AUTH_DIGEST)) { // // This connection is on a non-standard port. Include it in the SPN, unless // we're building a Digest URI (Digest doesn't take the port number) // PortNumber = Connection->PortNumber; } IF_DEBUG(BIND) { LdapPrint1("Connection->hostname is %s\n", Connection->publicLdapStruct.ld_host); LdapPrint1("Connection->DnsSuppliedNAme is %S\n ", Connection->DnsSuppliedName); LdapPrint1("Connection->DomainName is %S\n ", Connection->DomainName); } // // Note: The service class name in the SPN must be lower-case ("ldap"). // This is required by RFC 2829, section 11. W2k DCs are not case-sensitive, // however, some third-party servers are. // err = pDsMakeSpnW( LDAP_SERVICE_PREFIX, // ServiceClass servicename, // ServiceName Connection->DnsSuppliedName, // Optional InstanceName PortNumber, // PortNumber, if nonstandard NULL, // Optional referrer &pcSpnLength, // Length of buffer pszSpn // Actual buffer ); if (err == ERROR_SUCCESS) { Connection->ServiceNameForBind = ldap_dup_stringW( pszSpn, 0, LDAP_SERVICE_NAME_SIGNATURE ); IF_DEBUG(BIND) { LdapPrint2("LDAP: DsMakeSpn returned %S with error %d\n", Connection->ServiceNameForBind, err); } } } ReadRootDSE: Connection->publicLdapStruct.ld_options &= ~LDAP_OPT_CHASE_REFERRALS; Connection->publicLdapStruct.ld_options &= ~LDAP_CHASE_SUBORDINATE_REFERRALS; Connection->publicLdapStruct.ld_options &= ~LDAP_CHASE_EXTERNAL_REFERRALS; // // Ensure that we don't try to sign/seal - remember that we haven't // bound yet. // err = ldap_search_ext_sW( ldapConnection, NULL, LDAP_SCOPE_BASE, L"(objectclass=*)", attrList, 0, // attributes only NULL, // server controls NULL, // client controls Timeout, 0, // size limit &results ); if (results != NULL) { PLDAPMessage message = ldap_first_record( Connection, results, LDAP_RES_SEARCH_ENTRY ); if (message != NULL) { struct berelement *opaque = NULL; PWCHAR attribute = LdapFirstAttribute( Connection, message, (BerElement **) &opaque, TRUE ); while (attribute != NULL) { PWCHAR *values = NULL; ULONG count; if (LdapGetValues( Connection, message, attribute, FALSE, TRUE, (PVOID *) &values) != NOERROR) values = NULL; ULONG totalValues = ldap_count_valuesW( values ); if ( ldapWStringsIdentical( attribute, -1, L"supportedSASLMechanisms", -1 )) { for (count = 0; count < totalValues; count++ ) { if (ldapWStringsIdentical( values[count], -1, L"GSSAPI", -1 )) { foundGSSAPI = TRUE; IF_DEBUG(BIND) { LdapPrint1( "ldapBind found GSSAPI auth type on conn 0x%x\n", Connection); } } else if (ldapWStringsIdentical( values[count], -1, L"GSS-SPNEGO", -1 )) { foundGSS_SPNEGO = TRUE; IF_DEBUG(BIND) { LdapPrint1( "ldapBind found GSS-SPNEGO auth type on conn 0x%x\n", Connection); } } else if (ldapWStringsIdentical( values[count], -1, L"DIGEST-MD5", -1 )) { foundDIGEST = TRUE; IF_DEBUG(BIND) { LdapPrint1( "ldapBind found DIGEST auth type on conn 0x%x\n", Connection); } } } } ldap_value_freeW( values ); attribute = LdapNextAttribute( Connection, message, opaque, TRUE ); } } ldap_msgfree( results ); } Connection->publicLdapStruct.ld_options = oldChaseReferrals; if (err == LDAP_SUCCESS) { // // This must be a v3 server we are talking to. It responded successfully // to our RootDSE search // IF_DEBUG(BIND) { LdapPrint0("ldap bind: Server is v3\n"); } Connection->HighestSupportedLdapVersion = LDAP_VERSION3; if ((foundGSS_SPNEGO == FALSE) && (foundGSSAPI == FALSE)) { // // Non-AD server // IF_DEBUG(BIND) { LdapPrint0("ldap bind: Server does not support GSSAPI or GSS-SPNEGO\n"); } } else if ((foundGSS_SPNEGO == FALSE) && (foundGSSAPI == TRUE)){ // // AD Beta2 server // Connection->SupportsGSSAPI = TRUE; IF_DEBUG(BIND) { LdapPrint0("ldap bind: Server supports GSSAPI but not GSS-SPNEGO\n"); } } else if ((foundGSS_SPNEGO == TRUE) && (foundGSSAPI == FALSE)) { // // Non-AD server but it supports the negotiate package. // Connection->SupportsGSS_SPNEGO = TRUE; IF_DEBUG(BIND) { LdapPrint0("ldap bind: Server supports GSS-SPNEGO but not GSSAPI\n"); } } else if ((foundGSS_SPNEGO == TRUE) && (foundGSSAPI == TRUE)) { // // AD Beta3 server // Connection->SupportsGSS_SPNEGO = TRUE; Connection->SupportsGSSAPI = TRUE; IF_DEBUG(BIND) { LdapPrint0("ldap bind: Server supports both GSS-SPNEGO and GSSAPI\n"); } } Connection->SupportsDIGEST = foundDIGEST; } else { // // This server probably requires a bind before doing a search. // IF_DEBUG(BIND) { LdapPrint0("ldap bind: Server is v2\n"); } Connection->HighestSupportedLdapVersion = LDAP_VERSION2; } if (Connection->DomainName) { ldapFree(servicename, LDAP_BUFFER_SIGNATURE); servicename = NULL; } if (pszSpn) { ldapFree(pszSpn, LDAP_BUFFER_SIGNATURE); pszSpn = NULL; } return err; } BOOLEAN LdapAuthError( ULONG err ) { // // Returns FALSE for non authentication errors like LDAP_BUSY etc. // if (( err == LDAP_INAPPROPRIATE_AUTH ) || ( err == LDAP_INVALID_CREDENTIALS ) || ( err == LDAP_INSUFFICIENT_RIGHTS ) || ( err == LDAP_AUTH_METHOD_NOT_SUPPORTED ) || ( err == LDAP_STRONG_AUTH_REQUIRED ) || ( err == LDAP_AUTH_UNKNOWN )) { return TRUE; } return FALSE; } ULONG LdapDetermineServerVersion ( PLDAP_CONN Connection, struct l_timeval *Timeout, BOOLEAN *pfIsServerWhistler // OUT ) { PLDAP ldapConnection = Connection->ExternalInfo; ULONG err; PLDAPMessage results = NULL; ULONG oldChaseReferrals = Connection->publicLdapStruct.ld_options; PWCHAR attrList[2] = { L"supportedCapabilities", NULL }; Connection->publicLdapStruct.ld_options &= ~LDAP_OPT_CHASE_REFERRALS; Connection->publicLdapStruct.ld_options &= ~LDAP_CHASE_SUBORDINATE_REFERRALS; Connection->publicLdapStruct.ld_options &= ~LDAP_CHASE_EXTERNAL_REFERRALS; *pfIsServerWhistler = FALSE; err = ldap_search_ext_sW( ldapConnection, NULL, LDAP_SCOPE_BASE, L"(objectclass=*)", attrList, 0, // attributes only NULL, // server controls NULL, // client controls Timeout, 0, // size limit &results ); if (results != NULL) { PLDAPMessage message = ldap_first_record( Connection, results, LDAP_RES_SEARCH_ENTRY ); if (message != NULL) { struct berelement *opaque = NULL; PWCHAR attribute = LdapFirstAttribute( Connection, message, (BerElement **) &opaque, TRUE ); while (attribute != NULL) { PWCHAR *values = NULL; ULONG count; if (LdapGetValues( Connection, message, attribute, FALSE, TRUE, (PVOID *) &values) != NOERROR) values = NULL; ULONG totalValues = ldap_count_valuesW( values ); if ( ldapWStringsIdentical( attribute, -1, L"supportedCapabilities", -1 )) { for (count = 0; count < totalValues; count++ ) { if (ldapWStringsIdentical( values[count], -1, L"1.2.840.113556.1.4.1791", // Whistler w/ rebind fixes OID -1 )) { *pfIsServerWhistler = TRUE; IF_DEBUG(BIND) { LdapPrint1( "ldapBind found server is Whistler or better AD on conn 0x%x\n", Connection); } } } } ldap_value_freeW( values ); attribute = LdapNextAttribute( Connection, message, opaque, TRUE ); } } ldap_msgfree( results ); } Connection->publicLdapStruct.ld_options = oldChaseReferrals; return err; } // bind.c eof.
31.511521
142
0.464993
dfe7a9aee06726f7894b1bed816b96427f5c00d0
686
cxx
C++
templates/initmodule.cxx
lukeolson/crappy
fdd9449f7976e2a4e678db06e1b8d1a8bfef4e84
[ "BSD-3-Clause" ]
null
null
null
templates/initmodule.cxx
lukeolson/crappy
fdd9449f7976e2a4e678db06e1b8d1a8bfef4e84
[ "BSD-3-Clause" ]
null
null
null
templates/initmodule.cxx
lukeolson/crappy
fdd9449f7976e2a4e678db06e1b8d1a8bfef4e84
[ "BSD-3-Clause" ]
null
null
null
#include <Python.h> #include "crappy.h" extern "C" { #include "crappy_impl.h" static char crappy_doc[] = "Docstring for crappy."; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "crappy", NULL, -1, crappy_methods, NULL, NULL, NULL, NULL }; PyObject *PyInit_crappy(void) { PyObject *m; m = PyModule_Create(&moduledef); import_array(); return m; } #else PyMODINIT_FUNC initcrappy(void) { PyObject *m; m = Py_InitModule3("crappy", crappy_methods, crappy_doc); import_array(); if (m == NULL) { Py_FatalError("can't initialize module crappy"); } } #endif }
16.333333
61
0.639942
dfea84a2adab64773bce92477019e19b41ecd308
509
cpp
C++
source/jz28.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
source/jz28.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
source/jz28.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
#include "jz28.h" using namespace std; bool Jz28::IsMirror(TreeNode* left, TreeNode* right) { if(left == nullptr && right == nullptr) return true; else if (left == nullptr || right == nullptr || left->val != right->val) return false; // 迭代终止条件, 遍历完至少一颗树, 或者发现两颗树不是镜像. return IsMirror(left->right, right->left) && IsMirror(left->left, right->right); } bool Jz28::isSymmetric(TreeNode* root) { if (root == nullptr) return true; // 排除树为空的特殊情形 return IsMirror(root->left, root->right); }
26.789474
124
0.664047
dfeb53f30e17721692806e323e06477af45bafd9
19,834
cpp
C++
Source/Samples/79_NonoVG/NonoVG.cpp
elix22/Urho3D
99902ae2a867be0d6dbe4c575f9c8c318805ec64
[ "MIT" ]
20
2019-04-18T07:37:34.000Z
2022-02-02T21:43:47.000Z
Source/Samples/79_NonoVG/NonoVG.cpp
elix22/Urho3D
99902ae2a867be0d6dbe4c575f9c8c318805ec64
[ "MIT" ]
11
2019-10-21T13:39:41.000Z
2021-11-05T08:11:54.000Z
Source/Samples/79_NonoVG/NonoVG.cpp
elix22/Urho3D
99902ae2a867be0d6dbe4c575f9c8c318805ec64
[ "MIT" ]
1
2021-12-03T18:11:36.000Z
2021-12-03T18:11:36.000Z
// // Copyright (c) 2008-2021 the Urho3D project. // // 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 <Urho3D/Core/CoreEvents.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/GraphicsEvents.h> #include <Urho3D/Graphics/Material.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/Graphics/Octree.h> #include <Urho3D/Graphics/StaticModel.h> #include <Urho3D/Graphics/Texture2D.h> #include <Urho3D/Input/Input.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/UI/Button.h> #include <Urho3D/UI/CheckBox.h> #include <Urho3D/UI/LineEdit.h> #include <Urho3D/UI/Text.h> #include <Urho3D/UI/ToolTip.h> #include <Urho3D/UI/UI.h> #include <Urho3D/UI/UIEvents.h> #include <Urho3D/UI/Window.h> #include <Urho3D/Graphics/Technique.h> #include "NVG.h" #include "VGCanvas.h" #include "VGEvents.h" #include "VGFrameBuffer.h" #include "VGElement.h" #include "VGComponent.h" #include "NonoVG.h" #include "Demo.h" static DemoData demoData_; #include <Urho3D/DebugNew.h> URHO3D_DEFINE_APPLICATION_MAIN(NonoVG) NonoVG::NonoVG(Context* context) : Sample(context) , time_(0) { } void NonoVG::Setup() { engineParameters_[EP_RESOURCE_PATHS] = "Data;CoreData;"; engineParameters_[EP_LOG_NAME] = GetSubsystem<FileSystem>()->GetProgramDir() + GetTypeName() + ".log"; engineParameters_[EP_FULL_SCREEN] = false; engineParameters_[EP_WINDOW_WIDTH] = 1400; engineParameters_[EP_WINDOW_HEIGHT] = 1000; engineParameters_[EP_WINDOW_RESIZABLE] = true; engineParameters_[EP_WINDOW_TITLE] = GetTypeName(); context_->RegisterSubsystem(new NanoVG(context_)); VGElement::RegisterObject(context_); VGCanvas::RegisterObject(context_); VGFrameBuffer::RegisterObject(context_); VGComponent::RegisterObject(context_); } void NonoVG::Start() { // Execute base class startup Sample::Start(); uiRoot_ = GetSubsystem<UI>()->GetRoot(); // Load XML file containing default UI style sheet auto* cache = GetSubsystem<ResourceCache>(); auto* style = cache->GetResource<XMLFile>("UI/DefaultStyle.xml"); // Set the loaded style as default style uiRoot_->SetDefaultStyle(style); NanoVG* nvg = GetSubsystem<NanoVG>(); if (nvg) { nvg->Initialize(); loadDemoData(nvg, &demoData_); } CreateScene(); InitControls(); SetupViewport(); SubscribeToEvents(); // Enable OS cursor GetSubsystem<Input>()->SetMouseVisible(true); // Set the mouse mode to use in the sample Sample::InitMouseMode(MM_FREE); } void NonoVG::CreateScene() { auto* cache = GetSubsystem<ResourceCache>(); auto* graphics = GetSubsystem<Graphics>(); scene_ = new Scene(context_); // Create the Octree component to the scene. This is required before adding any drawable components, or else nothing // will show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world // coordinates; it is also legal to place objects outside the volume but their visibility can then not be checked in // a hierarchically optimizing manner scene_->CreateComponent<Octree>(); // Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a // simple plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node // larger (100 x 100 world units) Node* planeNode = scene_->CreateChild("Plane"); planeNode->SetScale(Vector3(100.0f, 1.0f, 100.0f)); auto* planeObject = planeNode->CreateComponent<StaticModel>(); planeObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl")); planeObject->SetMaterial(cache->GetResource<Material>("Materials/StoneTiled.xml")); // Create a directional light to the world so that we can see something. The light scene node's orientation controls // the light direction; we will use the SetDirection() function which calculates the orientation from a forward // direction vector. The light will use default settings (white light, no shadows) Node* lightNode = scene_->CreateChild("DirectionalLight"); lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f)); // The direction vector does not need to be normalized auto* light = lightNode->CreateComponent<Light>(); light->SetLightType(LIGHT_DIRECTIONAL); // Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct // a quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model // contains LOD levels, so the StaticModel component will automatically select the LOD level according to the view // distance (you'll see the model get simpler as it moves further away). Finally, rendering a large number of the // same object with the same material allows instancing to be used, if the GPU supports it. This reduces the amount // of CPU work in rendering the scene. const unsigned NUM_OBJECTS = 200; for (unsigned i = 0; i < NUM_OBJECTS; ++i) { Node* mushroomNode = scene_->CreateChild("Mushroom"); mushroomNode->SetPosition(Vector3(Random(90.0f) - 45.0f, 0.0f, Random(90.0f) - 45.0f)); mushroomNode->SetRotation(Quaternion(0.0f, Random(360.0f), 0.0f)); mushroomNode->SetScale(0.5f + Random(2.0f)); auto* mushroomObject = mushroomNode->CreateComponent<StaticModel>(); mushroomObject->SetModel(cache->GetResource<Model>("Models/Mushroom.mdl")); mushroomObject->SetMaterial(cache->GetResource<Material>("Materials/Mushroom.xml")); } // Create a "screen" like object for viewing the second scene. Construct it from two StaticModels, a box for the // frame and a plane for the actual view { Node* boxNode = scene_->CreateChild("ScreenBox"); boxNode->SetPosition(Vector3(0.0f, 10.0f, 0.0f)); boxNode->SetScale(Vector3(21.0f, 16.0f, 0.5f)); auto* boxObject = boxNode->CreateComponent<StaticModel>(); boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl")); boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml")); Node* screenNode = scene_->CreateChild("Screen"); screenNode->SetPosition(Vector3(0.0f, 10.0f, -0.27f)); screenNode->SetRotation(Quaternion(-90.0f, 0.0f, 0.0f)); screenNode->SetScale(Vector3(20.0f, 0.0f, 15.0f)); auto* screenObject = screenNode->CreateComponent<StaticModel>(); screenObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl")); VGFrameBuffer* vgFrameBuffer = scene_->CreateComponent<VGFrameBuffer>(); vgFrameBuffer->CreateFrameBuffer(1024, 1024); vgFrameBuffer->SetClearColor(Color(0.4, 0.4, 0.4, 1.0)); vgFrameBuffer->EnableRenderEvents(); // Create a new material from scratch, use the diffuse unlit technique, assign the render texture // as its diffuse texture, then assign the material to the screen plane object SharedPtr<Material> renderMaterial(new Material(context_)); renderMaterial->SetTechnique(0, cache->GetResource<Technique>("Techniques/DiffUnlit.xml")); renderMaterial->SetTexture(TU_DIFFUSE, vgFrameBuffer->GetRenderTarget()); // Since the screen material is on top of the box model and may Z-fight, use negative depth bias // to push it forward (particularly necessary on mobiles with possibly less Z resolution) renderMaterial->SetDepthBias(BiasParameters(-0.001f, 0.0f)); screenObject->SetMaterial(renderMaterial); } // Create a scene node for the camera, which we will move around // The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode_ = scene_->CreateChild("Camera"); cameraNode_->CreateComponent<Camera>(); // Set an initial position for the camera scene node above the plane cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -30.0f)); } void NonoVG::SetupViewport() { auto* renderer = GetSubsystem<Renderer>(); // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the // camera at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / // deferred) to use, but now we just use full screen and default render path configured in the engine command line // options SharedPtr<Viewport> viewport(new Viewport(context_, scene_, cameraNode_->GetComponent<Camera>())); renderer->SetViewport(0, viewport); } void NonoVG::InitControls() { auto* graphics = GetSubsystem<Graphics>(); NanoVG* nvg = GetSubsystem<NanoVG>(); SharedPtr<Window> window_ = InitWindow(); VGCanvas * vgCanvas = window_->CreateChild<VGCanvas>("VGCanvas"); vgCanvas->SetClearColor(Color(0.5,0.5,0.5,1.0)); window_ = InitWindow(); vgCanvas = window_->CreateChild<VGCanvas>("VGCanvas2"); vgCanvas->SetClearColor(Color(0.5, 0.5, 0.5, 1.0)); window_->SetPosition(200, 200); vgComponents_.Clear(); SharedPtr<VGComponent> vgComponent = VGComponent::Create(scene_, "vgComponentRoot"); vgComponents_.Push(vgComponent); vgComponent = vgComponent->CreateChild("vgComponentChild"); vgComponents_.Push(vgComponent); vgComponent = vgComponent->CreateChild("vgComponentChild2"); vgComponents_.Push(vgComponent); vgComponent = vgComponent->CreateChild("vgComponentChild3"); vgComponents_.Push(vgComponent); /* window_ = InitWindow(); int winSize = Min(graphics->GetWidth() / 2.0, graphics->GetHeight() / 2.0); window_->SetMinWidth(winSize); window_->SetMinHeight(winSize); window_->SetWidth(winSize); window_->SetHeight(winSize); Sprite * sprite = window_->CreateChild<Sprite>("SVGSprite"); svgTexture = nvg->LoadSVGIntoTexture("nanosvg/23_modified.svg"); sprite->SetTexture(svgTexture); window_->SetPosition(300, 300); */ } SharedPtr<Window> NonoVG::InitWindow() { // Create the Window and add it to the UI's root node /// The Window. SharedPtr<Window> window_(new Window(context_)); uiRoot_->AddChild(window_); auto* graphics = GetSubsystem<Graphics>(); // Set Window size and layout settings window_->SetMinWidth(graphics->GetWidth() / 1.5); window_->SetMinHeight(graphics->GetHeight() / 1.5); window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6)); window_->SetAlignment(HA_LEFT, VA_TOP); window_->SetName("NanoVG Window"); window_->SetMovable(true); window_->SetResizable(true); window_->SetFocusMode(FocusMode::FM_FOCUSABLE); // Create Window 'titlebar' container auto* titleBar = new UIElement(context_); titleBar->SetMinSize(0, 24); titleBar->SetMaxHeight(24); titleBar->SetVerticalAlignment(VA_TOP); titleBar->SetLayoutMode(LM_HORIZONTAL); // Create the Window title Text auto* windowTitle = new Text(context_); windowTitle->SetName("WindowTitle"); windowTitle->SetText("Hello NanoVG!"); // Create the Window's close button auto* buttonClose = new Button(context_); buttonClose->SetName("CloseButton"); // Add the controls to the title bar titleBar->AddChild(windowTitle); titleBar->AddChild(buttonClose); // Add the title bar to the Window window_->AddChild(titleBar); // Apply styles window_->SetStyleAuto(); windowTitle->SetStyleAuto(); buttonClose->SetStyle("CloseButton"); return window_; } void NonoVG::MoveCamera(float timeStep) { // Do not move if the UI has a focused element (the console) if (GetSubsystem<UI>()->GetFocusElement()) return; auto* input = GetSubsystem<Input>(); // Movement speed as world units per second const float MOVE_SPEED = 20.0f; // Mouse sensitivity as degrees per pixel const float MOUSE_SENSITIVITY = 0.1f; // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees IntVector2 mouseMove = input->GetMouseMove(); yaw_ += MOUSE_SENSITIVITY * mouseMove.x_; pitch_ += MOUSE_SENSITIVITY * mouseMove.y_; pitch_ = Clamp(pitch_, -90.0f, 90.0f); // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f)); // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed // Use the Translate() function (default local space) to move relative to the node's orientation. if (input->GetKeyDown(KEY_W)) cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_S)) cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_A)) cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * timeStep); if (input->GetKeyDown(KEY_D)) cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * timeStep); } void NonoVG::SubscribeToEvents() { // Subscribe HandleUpdate() function for processing update events SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(NonoVG, HandleUpdate)); SubscribeToEvent(E_VGRENDER, URHO3D_HANDLER(NonoVG, HandleNVGRender)); SubscribeToEvent(E_VGFBRENDER, URHO3D_HANDLER(NonoVG, HandleVGFBRender)); } void NonoVG::HandleUpdate(StringHash eventType, VariantMap& eventData) { using namespace Update; // Take the frame time step, which is stored as a float float timeStep = eventData[P_TIMESTEP].GetFloat(); time_ += timeStep; // Move the camera, scale movement with time step MoveCamera(timeStep); } void NonoVG::HandleNVGRender(StringHash eventType, VariantMap& eventData) { using namespace VGRender; VGElement* nanoVGUIElement = static_cast<VGElement*>(eventData[P_VGELEMENT].GetPtr()); IntVector2 size = nanoVGUIElement->GetSize(); String canvasName = nanoVGUIElement->GetName(); if (canvasName == "VGCanvas") { renderVGElement(nanoVGUIElement, 0, 0, size.x_, size.y_, time_, 0, &demoData_); } if (canvasName == "VGCanvas2") { RenderVGComponents(); } } void NonoVG::RenderVGComponents() { NanoVG* nvg = GetSubsystem<NanoVG>(); VGFrameBuffer* frameBuffer = nvg->GetCurrentFrameBuffer(); if (frameBuffer == nullptr) return; IntVector2 frameBufferSize = frameBuffer->GetSize(); int screenWidth = frameBufferSize.x_; int screenHeight = frameBufferSize.y_; // Urho takes the angles in degrees , as oppesed to nanovg which takes them in radians float rotation = time_ * 90; for (VGComponent * vgComponent : vgComponents_) { String name = vgComponent->GetName(); if (name == "vgComponentRoot") { float width = screenWidth * 0.04; float height = screenWidth * 0.02; float hotspot_x = width / 2.0; float hotspot_y = height / 2.0; vgComponent->BeginDraw(); NVGpaint bg = vgComponent->LinearGradient(0, 0, 60, 30, nvgRGBA(255, 255, 255, 32), nvgRGBA(0, 0, 0, 32)); vgComponent->SetPosition(screenWidth / 2.0, screenHeight/2.0); vgComponent->SetRotation(rotation); // vgComponent->SetScale(2.0f, 1.0f); vgComponent->BeginPath(); vgComponent->Ellipse(width, height); vgComponent->SetHotSpot(hotspot_x, hotspot_y); vgComponent->FillColor(nvgRGBA(0, 96, 128, 255)); vgComponent->Fill(); vgComponent->FillPaint(bg); vgComponent->Fill(); vgComponent->EndDraw(); } else if (name == "vgComponentChild") { float width = screenWidth * 0.1; float height = screenWidth * 0.1; float hotspot_x = width / 2.0; float hotspot_y = height / 2.0; vgComponent->BeginDraw(); /*position is set relative to the parent ,vgComponentRoot */ vgComponent->SetPosition(screenWidth * 0.17, screenHeight * 0.17); vgComponent->SetRotation(-2 * rotation); vgComponent->SetHotSpot(hotspot_x, hotspot_y); drawColorwheelOnVGComponent(vgComponent, 0, 0, width, height, 0); vgComponent->EndDraw(); } else if (name == "vgComponentChild2") { float width = screenWidth * 0.02; float height = screenWidth * 0.02; float hotspot_x = width / 2.0; float hotspot_y = height / 2.0; vgComponent->BeginDraw(); NVGpaint bg = vgComponent->LinearGradient(0, 0, 15, 30, nvgRGBA(255, 255, 255, 32), nvgRGBA(0, 0, 0, 32)); /*position is set relative to the parent ,vgComponentChild */ vgComponent->SetPosition(screenWidth * 0.17, screenHeight * 0.17); vgComponent->SetRotation(2 * rotation); vgComponent->BeginPath(); vgComponent->RoundedRect(width, height, 3); vgComponent->SetHotSpot(hotspot_x, hotspot_y); vgComponent->FillColor(nvgRGBA(125, 45, 200, 255)); vgComponent->Fill(); vgComponent->FillPaint(bg); vgComponent->Fill(); vgComponent->EndDraw(); } else if (name == "vgComponentChild3") { float width = screenWidth * 0.07; float height = screenWidth * 0.07; float hotspot_x = width / 2.0; float hotspot_y = height / 2.0; vgComponent->BeginDraw(); /*position is set relative to the parent ,vgComponentChild2 */ vgComponent->SetPosition(screenWidth * 0.03, screenHeight * 0.03); vgComponent->SetRotation(-rotation); NVGpaint imgPaint = vgComponent->ImagePattern(0, 0, width, height, 0, demoData_.svgImage, 1.0); vgComponent->BeginPath(); vgComponent->RoundedRect(width, width, 3); vgComponent->SetHotSpot(hotspot_x, hotspot_y); vgComponent->FillPaint(imgPaint); vgComponent->Fill(); vgComponent->EndDraw(); } } } void NonoVG::HandleVGFBRender(StringHash eventType, VariantMap& eventData) { using namespace VGFBRender; VGFrameBuffer* vgFrameBuffer = static_cast<VGFrameBuffer*>(eventData[P_VGFRAMEBUFFER].GetPtr()); IntVector2 size = vgFrameBuffer->GetSize(); renderVGFrameBuffer(vgFrameBuffer, 0, 0, size.x_, size.y_, time_, 0, &demoData_); } void NonoVG::Stop() { Sample::Stop(); NanoVG* nvg = GetSubsystem<NanoVG>(); if (nvg) { nvg->Clear(); } svgTexture.Reset(); }
38.289575
120
0.680851
dfeb8c9b4d6274e1a67b7fc3a1f69d5c8e66fb53
9,288
cc
C++
google/cloud/baremetalsolution/bare_metal_solution_connection.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
80
2017-11-24T00:19:45.000Z
2019-01-25T10:24:33.000Z
google/cloud/baremetalsolution/bare_metal_solution_connection.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
1,579
2017-11-24T01:01:21.000Z
2019-01-28T23:41:21.000Z
google/cloud/baremetalsolution/bare_metal_solution_connection.cc
GoogleCloudPlatform/google-cloud-cpp
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
[ "Apache-2.0" ]
51
2017-11-24T00:56:11.000Z
2019-01-18T20:35:02.000Z
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/baremetalsolution/v2/baremetalsolution.proto #include "google/cloud/baremetalsolution/bare_metal_solution_connection.h" #include "google/cloud/baremetalsolution/bare_metal_solution_options.h" #include "google/cloud/baremetalsolution/internal/bare_metal_solution_connection_impl.h" #include "google/cloud/baremetalsolution/internal/bare_metal_solution_option_defaults.h" #include "google/cloud/baremetalsolution/internal/bare_metal_solution_stub_factory.h" #include "google/cloud/background_threads.h" #include "google/cloud/common_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/pagination_range.h" #include <memory> namespace google { namespace cloud { namespace baremetalsolution { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN BareMetalSolutionConnection::~BareMetalSolutionConnection() = default; StreamRange<google::cloud::baremetalsolution::v2::Instance> BareMetalSolutionConnection::ListInstances( google::cloud::baremetalsolution::v2:: ListInstancesRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange<google::cloud::baremetalsolution::v2::Instance>>(); } StatusOr<google::cloud::baremetalsolution::v2::Instance> BareMetalSolutionConnection::GetInstance( google::cloud::baremetalsolution::v2::GetInstanceRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } future<StatusOr<google::cloud::baremetalsolution::v2::ResetInstanceResponse>> BareMetalSolutionConnection::ResetInstance( google::cloud::baremetalsolution::v2::ResetInstanceRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::baremetalsolution::v2::ResetInstanceResponse>>( Status(StatusCode::kUnimplemented, "not implemented")); } StreamRange<google::cloud::baremetalsolution::v2::Volume> BareMetalSolutionConnection::ListVolumes( google::cloud::baremetalsolution::v2:: ListVolumesRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange<google::cloud::baremetalsolution::v2::Volume>>(); } StatusOr<google::cloud::baremetalsolution::v2::Volume> BareMetalSolutionConnection::GetVolume( google::cloud::baremetalsolution::v2::GetVolumeRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } future<StatusOr<google::cloud::baremetalsolution::v2::Volume>> BareMetalSolutionConnection::UpdateVolume( google::cloud::baremetalsolution::v2::UpdateVolumeRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::baremetalsolution::v2::Volume>>( Status(StatusCode::kUnimplemented, "not implemented")); } StreamRange<google::cloud::baremetalsolution::v2::Network> BareMetalSolutionConnection::ListNetworks( google::cloud::baremetalsolution::v2:: ListNetworksRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange<google::cloud::baremetalsolution::v2::Network>>(); } StatusOr<google::cloud::baremetalsolution::v2::Network> BareMetalSolutionConnection::GetNetwork( google::cloud::baremetalsolution::v2::GetNetworkRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StreamRange<google::cloud::baremetalsolution::v2::SnapshotSchedulePolicy> BareMetalSolutionConnection::ListSnapshotSchedulePolicies( google::cloud::baremetalsolution::v2:: ListSnapshotSchedulePoliciesRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange<StreamRange< google::cloud::baremetalsolution::v2::SnapshotSchedulePolicy>>(); } StatusOr<google::cloud::baremetalsolution::v2::SnapshotSchedulePolicy> BareMetalSolutionConnection::GetSnapshotSchedulePolicy( google::cloud::baremetalsolution::v2:: GetSnapshotSchedulePolicyRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::cloud::baremetalsolution::v2::SnapshotSchedulePolicy> BareMetalSolutionConnection::CreateSnapshotSchedulePolicy( google::cloud::baremetalsolution::v2:: CreateSnapshotSchedulePolicyRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::cloud::baremetalsolution::v2::SnapshotSchedulePolicy> BareMetalSolutionConnection::UpdateSnapshotSchedulePolicy( google::cloud::baremetalsolution::v2:: UpdateSnapshotSchedulePolicyRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } Status BareMetalSolutionConnection::DeleteSnapshotSchedulePolicy( google::cloud::baremetalsolution::v2:: DeleteSnapshotSchedulePolicyRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::cloud::baremetalsolution::v2::VolumeSnapshot> BareMetalSolutionConnection::CreateVolumeSnapshot( google::cloud::baremetalsolution::v2::CreateVolumeSnapshotRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } future<StatusOr<google::cloud::baremetalsolution::v2::VolumeSnapshot>> BareMetalSolutionConnection::RestoreVolumeSnapshot( google::cloud::baremetalsolution::v2::RestoreVolumeSnapshotRequest const&) { return google::cloud::make_ready_future< StatusOr<google::cloud::baremetalsolution::v2::VolumeSnapshot>>( Status(StatusCode::kUnimplemented, "not implemented")); } Status BareMetalSolutionConnection::DeleteVolumeSnapshot( google::cloud::baremetalsolution::v2::DeleteVolumeSnapshotRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::cloud::baremetalsolution::v2::VolumeSnapshot> BareMetalSolutionConnection::GetVolumeSnapshot( google::cloud::baremetalsolution::v2::GetVolumeSnapshotRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StreamRange<google::cloud::baremetalsolution::v2::VolumeSnapshot> BareMetalSolutionConnection::ListVolumeSnapshots( google::cloud::baremetalsolution::v2:: ListVolumeSnapshotsRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange<google::cloud::baremetalsolution::v2::VolumeSnapshot>>(); } StatusOr<google::cloud::baremetalsolution::v2::Lun> BareMetalSolutionConnection::GetLun( google::cloud::baremetalsolution::v2::GetLunRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StreamRange<google::cloud::baremetalsolution::v2::Lun> BareMetalSolutionConnection::ListLuns( google::cloud::baremetalsolution::v2:: ListLunsRequest) { // NOLINT(performance-unnecessary-value-param) return google::cloud::internal::MakeUnimplementedPaginationRange< StreamRange<google::cloud::baremetalsolution::v2::Lun>>(); } std::shared_ptr<BareMetalSolutionConnection> MakeBareMetalSolutionConnection( Options options) { internal::CheckExpectedOptions<CommonOptionList, GrpcOptionList, BareMetalSolutionPolicyOptionList>(options, __func__); options = baremetalsolution_internal::BareMetalSolutionDefaultOptions( std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); auto stub = baremetalsolution_internal::CreateDefaultBareMetalSolutionStub( background->cq(), options); return std::make_shared< baremetalsolution_internal::BareMetalSolutionConnectionImpl>( std::move(background), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace baremetalsolution } // namespace cloud } // namespace google namespace google { namespace cloud { namespace baremetalsolution_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::shared_ptr<baremetalsolution::BareMetalSolutionConnection> MakeBareMetalSolutionConnection(std::shared_ptr<BareMetalSolutionStub> stub, Options options) { options = BareMetalSolutionDefaultOptions(std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); return std::make_shared< baremetalsolution_internal::BareMetalSolutionConnectionImpl>( std::move(background), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace baremetalsolution_internal } // namespace cloud } // namespace google
43
94
0.778208
dfeec959a6ac004088e326a95d987644c70b9f92
514
cpp
C++
2014/node.cpp
Yww729604/XidianCodeTest
bf99657fc58718f1edd2e91291420ee5e2c58d21
[ "MIT" ]
1
2022-02-05T16:37:13.000Z
2022-02-05T16:37:13.000Z
2014/node.cpp
Yww729604/XidianCodeTest
bf99657fc58718f1edd2e91291420ee5e2c58d21
[ "MIT" ]
null
null
null
2014/node.cpp
Yww729604/XidianCodeTest
bf99657fc58718f1edd2e91291420ee5e2c58d21
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef struct node { int data; string s; string t; struct node *next; }*linkList; void init(linkList &l) { int d; while(cin>>d) { linkList tempNode = (linkList)malloc(sizeof(struct node)); tempNode->data = d; tempNode->next = l; l = tempNode; } } void print(linkList l) { linkList p = l; while(p != NULL) { cout<<p->data<<" "; p = p->next; } } int main(int argc, char const *argv[]) { linkList l = NULL; init(l); print(l); return 0; }
12.536585
60
0.61284
dff59b9ba2b8df0fac9d4e7cb4fa9a32b92fe8b2
12,610
cpp
C++
cplusplus/level1_single_api/4_op_dev/1_custom_op/framework/tf_scope_fusion_pass/decode_bbox_v2_multi_pass.cpp
Dedederek/samples
31d99de20af2f7046556e0f48c4b789b99e422f8
[ "Apache-2.0" ]
25
2020-11-20T09:01:35.000Z
2022-03-29T10:35:38.000Z
cplusplus/level1_single_api/4_op_dev/1_custom_op/framework/tf_scope_fusion_pass/decode_bbox_v2_multi_pass.cpp
Dedederek/samples
31d99de20af2f7046556e0f48c4b789b99e422f8
[ "Apache-2.0" ]
5
2021-02-28T20:49:37.000Z
2022-03-04T21:50:27.000Z
cplusplus/level1_single_api/4_op_dev/1_custom_op/framework/tf_scope_fusion_pass/decode_bbox_v2_multi_pass.cpp
Dedederek/samples
31d99de20af2f7046556e0f48c4b789b99e422f8
[ "Apache-2.0" ]
16
2020-12-06T07:26:13.000Z
2022-03-01T07:51:55.000Z
/* Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Apache License Version 2.0. * You may not use this file except in compliance with the License. * * 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 * Apache License for more details at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "decode_bbox_v2_multi_pass.h" #define OP_LOGE(OP_NAME, fmt, ...) printf("[ERROR]%s,%s:%u:" #fmt "\n", __FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__) #define OP_LOGW(OP_NAME, fmt, ...) printf("[WARN]%s,%s:%u:" #fmt "\n", __FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__) #define OP_LOGI(OP_NAME, fmt, ...) printf("[INFO]%s,%s:%u:" #fmt "\n", __FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__) namespace ge { namespace { const char *const kScopeType = "DecodeBboxV2"; const char *const kScopeTypeDecodeBboxV2 = "DecodeBboxV2"; const char *const kOpType = "DecodeBboxV2"; const char *const kBoxesUnpack = "/unstack"; const char *const kBoxesDiv = "RealDiv"; const size_t kRealDivInputSize = 2; const size_t kScaleSize = 4; } // namespace std::vector<ScopeFusionPatterns> DecodeBboxV2MultiScopeFusionPass::DefinePatterns() { std::vector<ScopeFusionPatterns> patterns_list; ScopeFusionPatterns pattern; GenScopePatterns(pattern); patterns_list.push_back(pattern); return patterns_list; } void DecodeBboxV2MultiScopeFusionPass::GenScopePatterns(ScopeFusionPatterns &patterns) { std::vector<ScopePattern *> batch; ScopePattern *decode_bbox_v2_pattern = new(std::nothrow) ScopePattern(); if (decode_bbox_v2_pattern == nullptr) { OP_LOGE(kOpType, "Alloc an object failed."); return; } decode_bbox_v2_pattern->SetSubType(kScopeTypeDecodeBboxV2); decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Exp", 2, 0)); // Exp num is 2 decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Mul", 4, 0)); // Mul num is 4 decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Sub", 4, 0)); // Sub num is 4 decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("RealDiv", 0, 2)); // RealDiv num is 2*n decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Unpack", 2, 0)); // Unpack num is 2 decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Pack", 1, 0)); // Pack num is 1 decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Transpose", 3, 0)); // Transpose num is 3 decode_bbox_v2_pattern->AddNodeOpTypeFeature(NodeOpTypeFeature("Softmax", -1, 0)); // doesn't have Softmax OP_LOGI(kOpType, "Add GenScopePatterns DecodeBboxV2."); batch.push_back(decode_bbox_v2_pattern); patterns.push_back(batch); } std::string DecodeBboxV2MultiScopeFusionPass::PassName() { return std::string("DecodeBboxV2MultiScopeFusionPass"); } Status DecodeBboxV2MultiScopeFusionPass::LastMatchScopesAndOPs(shared_ptr<ScopeGraph> &scope_graph, std::vector<ScopesResult> &results) { OP_LOGI(kOpType, "LastMatchScopesAndOPs start."); if (scope_graph == nullptr) { OP_LOGE(kOpType, "Input params is nullptr."); return FAILED; } const ScopeTree *scope_tree = scope_graph->GetScopeTree(); if (scope_tree == nullptr) { OP_LOGE(kOpType, "Scope tree is nullptr."); return FAILED; } const std::vector<Scope *> &scopes = scope_tree->GetAllScopes(); for (auto &scope : scopes) { // Class ScopeTree guarantees scope is not empty. AscendString op_subtype; Status ret = scope->SubType(op_subtype); if (ret != SUCCESS) { return FAILED; } AscendString op_name; ret = scope->Name(op_name); if (ret != SUCCESS) { return FAILED; } if (op_subtype == kScopeTypeDecodeBboxV2) { OP_LOGI(kOpType, "DecodeBbox LastMatchScopesAndOPs match scope %s.", op_name.GetString()); ScopesResult result; std::vector<Scope *> result_scopes; result_scopes.push_back(scope); result.SetScopes(result_scopes); std::vector<ge::OperatorPtr> nodes; std::unordered_map<AscendString, ge::OperatorPtr> nodes_map; ret = scope->AllNodesMap(nodes_map); if (ret != SUCCESS) { return FAILED; } for (const auto &node_info : nodes_map) { nodes.emplace_back(node_info.second); } result.SetNodes(nodes); results.push_back(result); } } return (!(results.empty())) ? SUCCESS : FAILED; } namespace { Status ParseFloatFromConstNode(const ge::OperatorPtr node, float &value) { if (node == nullptr) { return FAILED; } ge::Tensor tensor; auto ret = node->GetAttr("value", tensor); if (ret != ge::GRAPH_SUCCESS) { AscendString op_name; ret = node->GetName(op_name); if (ret != ge::GRAPH_SUCCESS) { return FAILED; } OP_LOGE(kOpType, "Failed to get value from %s", op_name.GetString()); return FAILED; } uint8_t *data_addr = tensor.GetData(); value = *(reinterpret_cast<float *>(data_addr)); return SUCCESS; } Status DecodeBboxV2ParseParams(const std::vector<ge::OperatorPtr> &inside_nodes, ge::Operator *op_dest) { if (op_dest == nullptr) { OP_LOGE(kOpType, "Dest operator is nullptr."); return FAILED; } std::map<std::string, std::string> scales_const_name_map; std::map<string, ge::OperatorPtr> node_map; for (const auto &node : inside_nodes) { if (node == nullptr) { OP_LOGE(kOpType, "Inner operator is nullptr."); return FAILED; } AscendString op_type; graphStatus ret = node->GetOpType(op_type); if (ret != ge::GRAPH_SUCCESS) { return FAILED; } ge::AscendString op_name; ret = node->GetName(op_name); string str_op_name; if (op_name.GetString() != nullptr) { str_op_name = op_name.GetString(); } if (op_type == kBoxesDiv) { if (node->GetInputsSize() < kRealDivInputSize) { OP_LOGE(kOpType, "Input size of %s is invalid, which is %zu.", kBoxesDiv, node->GetInputsSize()); return FAILED; } ge::AscendString input_unpack_name0; ret = node->GetInputDesc(0).GetName(input_unpack_name0); string str_input_unpack_name0; if (input_unpack_name0.GetString() != nullptr) { str_input_unpack_name0 = input_unpack_name0.GetString(); } ge::AscendString input_unpack_name1; ret = node->GetInputDesc(1).GetName(input_unpack_name1); string str_input_unpack_name1; if (input_unpack_name1.GetString() != nullptr) { str_input_unpack_name1 = input_unpack_name1.GetString(); } if (str_input_unpack_name0.find(kBoxesUnpack) != string::npos) { scales_const_name_map.insert({str_op_name, str_input_unpack_name1}); } } node_map[str_op_name] = node; } std::vector<float> scales_list = {1.0, 1.0, 1.0, 1.0}; if (scales_const_name_map.size() != kScaleSize) { OP_LOGI(op_dest->GetName().c_str(), "Boxes doesn't need scale."); } else { size_t i = 0; for (const auto &name_pair : scales_const_name_map) { float scale_value = 1.0; auto ret = ParseFloatFromConstNode(node_map[name_pair.second], scale_value); if (ret != SUCCESS) { return ret; } scales_list[i++] = scale_value; } } op_dest->SetAttr("scales", scales_list); return SUCCESS; } } // namespace void DecodeBboxV2MultiScopeFusionPass::GenerateFusionResult(const std::vector<Scope *> &scopes, FusionScopesResult *fusion_rlt) { if (fusion_rlt == nullptr) { return; } if (scopes.size() != 1) { // not match, set fusion_rlt->SetType(kScopeInvalidType); return; } fusion_rlt->InsertInputs("transpose", {0, kFusionDisableIndex}); fusion_rlt->InsertInputs("get_center_coordinates_and_sizes/transpose", {1, kFusionDisableIndex}); fusion_rlt->InsertOutputs("transpose_1", {0}); fusion_rlt->SetType(kScopeToMultiNodes); AscendString scope_name; Status ret = scopes[0]->Name(scope_name); if (ret != SUCCESS) { return ; } std::string str_scope_name; if (scope_name != nullptr) { str_scope_name = scope_name.GetString(); } fusion_rlt->SetName(str_scope_name.substr(0, str_scope_name.length() - 1).c_str()); fusion_rlt->SetDescription(""); auto in_identity_0 = fusion_rlt->AddInnerNode("input_identity_0", "Identity"); CHECK_INNER_NODE_CONDITION(in_identity_0 != nullptr, fusion_rlt); ret = in_identity_0->InsertInput(kInputFromFusionScope, 0) .InsertOutput("inner_core_decode_bbox_v2", 0) .BuildInnerNode(); CHECK_INNER_NODE_CONDITION(ret == ge::GRAPH_SUCCESS, fusion_rlt); std::string str_attr = "input_0_identity_attr"; in_identity_0->MutableOperator()->SetAttr("key", str_attr); auto in_identity_1 = fusion_rlt->AddInnerNode("input_identity_1", "Identity"); CHECK_INNER_NODE_CONDITION(in_identity_1 != nullptr, fusion_rlt); ret = in_identity_1->InsertInput(kInputFromFusionScope, 1) .InsertOutput("inner_core_decode_bbox_v2", 1) .BuildInnerNode(); CHECK_INNER_NODE_CONDITION(ret == ge::GRAPH_SUCCESS, fusion_rlt); auto core_decode_bbox = fusion_rlt->AddInnerNode("inner_core_decode_bbox_v2", kScopeType); CHECK_INNER_NODE_CONDITION(core_decode_bbox != nullptr, fusion_rlt); ret = core_decode_bbox->InsertInput("input_identity_0", 0) .InsertInput("input_identity_1", 0) .InsertOutput("output_identity", 0) .BuildInnerNode(); CHECK_INNER_NODE_CONDITION(ret == ge::GRAPH_SUCCESS, fusion_rlt); auto parser_ret = DecodeBboxV2ParseParams(fusion_rlt->Nodes(), core_decode_bbox->MutableOperator()); CHECK_INNER_NODE_CONDITION(parser_ret == SUCCESS, fusion_rlt); auto out_identity = fusion_rlt->AddInnerNode("output_identity", "Identity"); CHECK_INNER_NODE_CONDITION(out_identity != nullptr, fusion_rlt); ret = out_identity->InsertInput("inner_core_decode_bbox_v2", 0) .InsertOutput(kOutputToFusionScope, 0) .BuildInnerNode(); CHECK_INNER_NODE_CONDITION(ret == ge::GRAPH_SUCCESS, fusion_rlt); ret = fusion_rlt->CheckInnerNodesInfo(); CHECK_INNER_NODE_CONDITION(ret == ge::GRAPH_SUCCESS, fusion_rlt); OP_LOGI(kOpType, "Set fusion multi-to-multi result successfully."); return; } REGISTER_SCOPE_FUSION_PASS("DecodeBboxV2MultiScopeFusionPass", DecodeBboxV2MultiScopeFusionPass, false); } // namespace ge
46.021898
120
0.589215
dffd810adde01422c379df331b7e6794ae00f53a
292
hpp
C++
fw/include/fw/BasicEffect.hpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
null
null
null
fw/include/fw/BasicEffect.hpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
9
2016-12-09T13:02:18.000Z
2019-09-13T09:29:18.000Z
fw/include/fw/BasicEffect.hpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
null
null
null
#pragma once #include "Effect.hpp" namespace fw { class BasicEffect: public EffectBase { public: BasicEffect(); virtual ~BasicEffect(); void create(); virtual void destroy(); virtual void begin(); virtual void end(); protected: void createShaders(); }; }
12.166667
27
0.643836
dffef375e236877eca4d7bcfdbbc268ffc6ea653
4,319
cpp
C++
nTA/Source/igui_BuildButton.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2020-05-09T20:50:12.000Z
2021-06-20T08:34:58.000Z
nTA/Source/igui_BuildButton.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
null
null
null
nTA/Source/igui_BuildButton.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2018-01-08T00:12:04.000Z
2020-06-14T10:56:50.000Z
// igui_BuildButton.cpp // \author Logan Jones ///////////////////////// \date 4/25/2002 /// \file /// \brief ... ///////////////////////////////////////////////////////////////////// #include "igui.h" #include "igui_BuildButton.h" #include "game.h" #include "snd.h" ///////////////////////////////////////////////////////////////////// // Default Construction/Destruction // igui_BuildButton::igui_BuildButton():gadget_Button() {} igui_BuildButton::~igui_BuildButton() {} // ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // igui_BuildButton::OnInitButtonImages() // \author Logan Jones /////////////////////////////////////////// \date 11/5/2002 // //=================================================================== // void igui_BuildButton::OnInitButtonImages() { theInterface->ControlBar().LoadBuildButton( this, m_CommonData, m_ButtonInfo ); } // End igui_BuildButton::OnInitButtonImages() ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // igui_BuildButton::OnRender() // \author Logan Jones ///////////////////////////////// \date 02-02-2003 // //=================================================================== // void igui_BuildButton::OnRender() { const igui_BuildOrders* pOrders = theInterface->ControlBar().m_CurrentSelection->BuildOrders(); int Amount; // Render the button first gadget_Button::OnRender(); // If the selected unit has build orders and those oreders include this item then render the amount info if( pOrders && (Amount=pOrders->Amount(m_CommonData.Name))!=0 ) { // Setup the info string depending on the amount (less than 0 indicates infinite) if( Amount>0 ) m_BuildText[0] = '+', itoa( Amount, m_BuildText+1, 10 ); else m_BuildText[0] = '~', m_BuildText[1] = '\0'; // Render the info gfx->SetCurrentFont( guiResources.Fonts.Standard ); gfx->RenderStringCenteredAt( m_ScreenPosition + std_Point(m_Size.width/2, m_Size.height-6) + (m_Pressed ? std_Point(1,1) : std_Point(0,0)), m_BuildText, TRUE, FALSE ); } } // End igui_BuildButton::OnRender() ///////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // igui_BuildButton::OnCursorMove() // \author Logan Jones ///////////////////////////////////// \date 5/1/2002 // //==================================================================== // Parameters: // std_Point& ptCursor - // DWORD dwFlags - // void igui_BuildButton::OnCursorMove( std_Point& ptCursor, DWORD dwFlags ) { // Call the default gadget_Button::OnCursorMove( ptCursor, dwFlags ); // Display the type information for the unit represented by this button theInterface->InfoBar().DisplayBuildInfo( theGame.Units.GetUnitType(m_CommonData.Name) ); } // End igui_BuildButton::OnCursorMove() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // igui_BuildButton::OnPressed() // \author Logan Jones ////////////////////////////////// \date 4/27/2002 // //==================================================================== // Parameters: // DWORD dwButton - Button that completed the press // void igui_BuildButton::OnPressed( DWORD dwButton ) { // Send the pressed message //SendMessage( m_pParent, igui_msg_BuildButtonPressed, (DWORD)(LPTSTR(m_CommonData.Name)), dwButton ); sound.PlaySound( (dwButton==1) ? guiResources.Sounds.AddBuild : guiResources.Sounds.SubBuild ); theInterface->BuildButtonPressed( m_CommonData.Name, (m_CommonData.CommonAttribs&8)!=0, dwButton==1 ); } // End igui_BuildButton::OnPressed() ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // End - igui_BuildButton.cpp // ///////////////////////////////
37.556522
114
0.447094
5f06d2639771912de5fc88bf84cdb7629ab6a5ff
471
hpp
C++
Proftaak2.4/AudioComponent.hpp
rubenwo/Proftaak2.4
c3231883cd2cd961fa1db5a27af65f36e8f3daa8
[ "MIT" ]
null
null
null
Proftaak2.4/AudioComponent.hpp
rubenwo/Proftaak2.4
c3231883cd2cd961fa1db5a27af65f36e8f3daa8
[ "MIT" ]
null
null
null
Proftaak2.4/AudioComponent.hpp
rubenwo/Proftaak2.4
c3231883cd2cd961fa1db5a27af65f36e8f3daa8
[ "MIT" ]
null
null
null
#ifndef AUDIO_COMPONENT_HPP #define AUDIO_COMPONENT_HPP #include "Component.h" #include <string> #include "SoundPlayer.hpp" class AudioComponent : public Component { public: AudioComponent(const SoundID& soundID); ~AudioComponent(); virtual void update(float elapsedTime) override; void playAudio(bool loop); void stopAudio(); private: SoundPlayer* soundPlayer; SoundID soundID; irrklang::ISound* sound; }; #endif // !AUDIO_COMPONENT_HPP
20.478261
50
0.740977
5f0b0bee274cc3e652992befca93a04e990ea2c6
18,825
cpp
C++
samples/Hello/third-party/fuzzylite/fuzzylite/src/rule/Antecedent.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
samples/Hello/third-party/fuzzylite/fuzzylite/src/rule/Antecedent.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
samples/Hello/third-party/fuzzylite/fuzzylite/src/rule/Antecedent.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
/* fuzzylite (R), a fuzzy logic control library in C++. Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved. Author: Juan Rada-Vilela, Ph.D. <jcrada@fuzzylite.com> This file is part of fuzzylite. fuzzylite is free software: you can redistribute it and/or modify it under the terms of the FuzzyLite License included with the software. You should have received a copy of the FuzzyLite License along with fuzzylite. If not, see <http://www.fuzzylite.com/license/>. fuzzylite is a registered trademark of FuzzyLite Limited. */ #include "fl/rule/Antecedent.h" #include "fl/Engine.h" #include "fl/factory/HedgeFactory.h" #include "fl/factory/FactoryManager.h" #include "fl/hedge/Any.h" #include "fl/rule/Expression.h" #include "fl/rule/Rule.h" #include "fl/term/Aggregated.h" #include "fl/variable/InputVariable.h" #include "fl/variable/OutputVariable.h" #include <stack> namespace fl { Antecedent::Antecedent() : _text(""), _expression(fl::null) { } Antecedent::~Antecedent() { _expression.reset(fl::null); } void Antecedent::setText(const std::string& text) { this->_text = text; } std::string Antecedent::getText() const { return this->_text; } Expression* Antecedent::getExpression() const { return this->_expression.get(); } void Antecedent::setExpression(Expression* expression) { this->_expression.reset(expression); } bool Antecedent::isLoaded() const { return _expression.get() != fl::null; } scalar Antecedent::activationDegree(const TNorm* conjunction, const SNorm* disjunction) const { return this->activationDegree(conjunction, disjunction, _expression.get()); } scalar Antecedent::activationDegree(const TNorm* conjunction, const SNorm* disjunction, const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + getText() + "> is not loaded", FL_AT); } const Expression::Type expression = node->type(); if (expression == Expression::Proposition) { const Proposition* proposition = static_cast<const Proposition*> (node); if (not proposition->variable->isEnabled()) { return 0.0; } if (not proposition->hedges.empty()) { //if last hedge is "Any", apply hedges in reverse order and return degree std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); if (dynamic_cast<Any*> (*rit)) { scalar result = (*rit)->hedge(fl::nan); while (++rit != proposition->hedges.rend()) { result = (*rit)->hedge(result); } return result; } } scalar result = fl::nan; Variable::Type variableType = proposition->variable->type(); if (variableType == Variable::Input) { result = proposition->term->membership(proposition->variable->getValue()); } else if (variableType == Variable::Output) { result = static_cast<OutputVariable*> (proposition->variable) ->fuzzyOutput()->activationDegree(proposition->term); } if (not proposition->hedges.empty()) { for (std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); rit != proposition->hedges.rend(); ++rit) { result = (*rit)->hedge(result); } } return result; } //if node is an operator if (expression == Expression::Operator) { const Operator* fuzzyOperator = static_cast<const Operator*> (node); if (not (fuzzyOperator->left and fuzzyOperator->right)) { std::ostringstream ex; ex << "[syntax error] left and right operands must exist"; throw Exception(ex.str(), FL_AT); } if (fuzzyOperator->name == Rule::andKeyword()) { if (not conjunction) throw Exception("[conjunction error] " "the following rule requires a conjunction operator:\n" + _text, FL_AT); return conjunction->compute( this->activationDegree(conjunction, disjunction, fuzzyOperator->left), this->activationDegree(conjunction, disjunction, fuzzyOperator->right)); } if (fuzzyOperator->name == Rule::orKeyword()) { if (not disjunction) throw Exception("[disjunction error] " "the following rule requires a disjunction operator:\n" + _text, FL_AT); return disjunction->compute( this->activationDegree(conjunction, disjunction, fuzzyOperator->left), this->activationDegree(conjunction, disjunction, fuzzyOperator->right)); } std::ostringstream ex; ex << "[syntax error] operator <" << fuzzyOperator->name << "> not recognized"; throw Exception(ex.str(), FL_AT); } else { std::ostringstream ss; ss << "[antecedent error] expected a Proposition or Operator, but found <"; if (node) ss << node->toString(); ss << ">"; throw Exception(ss.str(), FL_AT); } } Complexity Antecedent::complexity(const TNorm* conjunction, const SNorm* disjunction) const { return complexity(conjunction, disjunction, _expression.get()); } Complexity Antecedent::complexity(const TNorm* conjunction, const SNorm* disjunction, const Expression* node) const { if (not isLoaded()) { return Complexity(); } Complexity result; const Expression::Type expression = node->type(); if (expression == Expression::Proposition) { const Proposition* proposition = static_cast<const Proposition*> (node); if (not proposition->variable->isEnabled()) { return result; } if (not proposition->hedges.empty()) { //if last hedge is "Any", apply hedges in reverse order and return degree std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); if (dynamic_cast<Any*> (*rit)) { result += (*rit)->complexity(); while (++rit != proposition->hedges.rend()) { result = (*rit)->complexity(); } return result; } } Variable::Type variableType = proposition->variable->type(); if (variableType == Variable::Input) { result += proposition->term->complexity(); } else if (variableType == Variable::Output) { OutputVariable* outputVariable = static_cast<OutputVariable*> (proposition->variable); result += outputVariable->fuzzyOutput()->complexityOfActivationDegree(); } if (not proposition->hedges.empty()) { for (std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); rit != proposition->hedges.rend(); ++rit) { result += (*rit)->complexity(); } } return result; } //if node is an operator if (expression == Expression::Operator) { const Operator* fuzzyOperator = static_cast<const Operator*> (node); if (not (fuzzyOperator->left and fuzzyOperator->right)) { std::ostringstream ex; ex << "[syntax error] left and right operands must exist"; throw Exception(ex.str(), FL_AT); } if (fuzzyOperator->name == Rule::andKeyword()) { if (conjunction) { result += conjunction->complexity(); } result += complexity(conjunction, disjunction, fuzzyOperator->left) + complexity(conjunction, disjunction, fuzzyOperator->right); return result; } if (fuzzyOperator->name == Rule::orKeyword()) { if (disjunction) { result += disjunction->complexity(); } result += complexity(conjunction, disjunction, fuzzyOperator->left) + complexity(conjunction, disjunction, fuzzyOperator->right); return result; } } return Complexity(); } void Antecedent::unload() { _expression.reset(fl::null); } void Antecedent::load(const Engine* engine) { load(getText(), engine); } void Antecedent::load(const std::string& antecedent, const Engine* engine) { FL_DBG("Antecedent: " << antecedent); unload(); setText(antecedent); if (Op::trim(antecedent).empty()) { throw Exception("[syntax error] antecedent is empty", FL_AT); } /* Builds an proposition tree from the antecedent of a fuzzy rule. The rules are: 1) After a variable comes 'is', 2) After 'is' comes a hedge or a term 3) After a hedge comes a hedge or a term 4) After a term comes a variable or an operator */ Function function; std::string postfix = function.toPostfix(antecedent); FL_DBG("Postfix: " << postfix); std::stringstream tokenizer(postfix); std::string token; enum FSM { S_VARIABLE = 1, S_IS = 2, S_HEDGE = 4, S_TERM = 8, S_AND_OR = 16 }; int state = S_VARIABLE; std::stack<Expression*> expressionStack; Proposition* proposition = fl::null; try { while (tokenizer >> token) { if (state bitand S_VARIABLE) { Variable* variable = fl::null; if (engine->hasInputVariable(token)) variable = engine->getInputVariable(token); else if (engine->hasOutputVariable(token)) variable = engine->getOutputVariable(token); if (variable) { proposition = new Proposition; proposition->variable = variable; expressionStack.push(proposition); state = S_IS; FL_DBG("Token <" << token << "> is variable"); continue; } } if (state bitand S_IS) { if (token == Rule::isKeyword()) { state = S_HEDGE bitor S_TERM; FL_DBG("Token <" << token << "> is keyword"); continue; } } if (state bitand S_HEDGE) { HedgeFactory* factory = FactoryManager::instance()->hedge(); if (factory->hasConstructor(token)) { Hedge* hedge = factory->constructObject(token); proposition->hedges.push_back(hedge); if (dynamic_cast<Any*> (hedge)) { state = S_VARIABLE bitor S_AND_OR; } else { state = S_HEDGE bitor S_TERM; } FL_DBG("Token <" << token << "> is hedge"); continue; } } if (state bitand S_TERM) { if (proposition->variable->hasTerm(token)) { proposition->term = proposition->variable->getTerm(token); state = S_VARIABLE bitor S_AND_OR; FL_DBG("Token <" << token << "> is term"); continue; } } if (state bitand S_AND_OR) { if (token == Rule::andKeyword() or token == Rule::orKeyword()) { if (expressionStack.size() < 2) { std::ostringstream ex; ex << "[syntax error] logical operator <" << token << "> expects two operands," << "but found <" << expressionStack.size() << "> in antecedent"; throw Exception(ex.str(), FL_AT); } Operator* fuzzyOperator = new Operator; fuzzyOperator->name = token; fuzzyOperator->right = expressionStack.top(); expressionStack.pop(); fuzzyOperator->left = expressionStack.top(); expressionStack.pop(); expressionStack.push(fuzzyOperator); state = S_VARIABLE bitor S_AND_OR; FL_DBG("Subtree: " << fuzzyOperator->toString() << "(" << fuzzyOperator->left->toString() << ") " << "(" << fuzzyOperator->right->toString() << ")"); continue; } } //If reached this point, there was an error if ((state bitand S_VARIABLE) or (state bitand S_AND_OR)) { std::ostringstream ex; ex << "[syntax error] antecedent expected variable or logical operator, but found <" << token << ">"; throw Exception(ex.str(), FL_AT); } if (state bitand S_IS) { std::ostringstream ex; ex << "[syntax error] antecedent expected keyword <" << Rule::isKeyword() << ">, but found <" << token << ">"; throw Exception(ex.str(), FL_AT); } if ((state bitand S_HEDGE) or (state bitand S_TERM)) { std::ostringstream ex; ex << "[syntax error] antecedent expected hedge or term, but found <" << token << ">"; throw Exception(ex.str(), FL_AT); } std::ostringstream ex; ex << "[syntax error] unexpected token <" << token << "> in antecedent"; throw Exception(ex.str(), FL_AT); } if (not ((state bitand S_VARIABLE) or (state bitand S_AND_OR))) { //only acceptable final state if (state bitand S_IS) { std::ostringstream ex; ex << "[syntax error] antecedent expected keyword <" << Rule::isKeyword() << "> after <" << token << ">"; throw Exception(ex.str(), FL_AT); } if ((state bitand S_HEDGE) or (state bitand S_TERM)) { std::ostringstream ex; ex << "[syntax error] antecedent expected hedge or term after <" << token << ">"; throw Exception(ex.str(), FL_AT); } } if (expressionStack.size() != 1) { std::vector<std::string> errors; while (expressionStack.size() > 1) { Expression* expression = expressionStack.top(); expressionStack.pop(); errors.push_back(expression->toString()); delete expression; } std::ostringstream ex; ex << "[syntax error] unable to parse the following expressions in antecedent <" << Op::join(errors, " ") << ">"; throw Exception(ex.str(), FL_AT); } } catch (...) { for (std::size_t i = 0; i < expressionStack.size(); ++i) { delete expressionStack.top(); expressionStack.pop(); } throw; } setExpression(expressionStack.top()); } std::string Antecedent::toString() const { return toInfix(getExpression()); } std::string Antecedent::toPrefix(const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + _text + "> is not loaded", FL_AT); } if (not node) node = getExpression(); if (dynamic_cast<const Proposition*> (node)) { return node->toString(); } std::stringstream ss; if (const Operator * fuzzyOperator = dynamic_cast<const Operator*> (node)) { ss << fuzzyOperator->toString() << " " << toPrefix(fuzzyOperator->left) << " " << toPrefix(fuzzyOperator->right) << " "; } else { ss << "[antecedent error] unknown class of Expression <" << (node ? node->toString() : "null") << ">"; } return ss.str(); } std::string Antecedent::toInfix(const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + _text + "> is not loaded", FL_AT); } if (not node) node = getExpression(); if (dynamic_cast<const Proposition*> (node)) { return node->toString(); } std::stringstream ss; if (const Operator * fuzzyOperator = dynamic_cast<const Operator*> (node)) { ss << toInfix(fuzzyOperator->left) << " " << fuzzyOperator->toString() << " " << toInfix(fuzzyOperator->right) << " "; } else { ss << "[antecedent error] unknown class of Expression <" << (node ? node->toString() : "null") << ">"; } return ss.str(); } std::string Antecedent::toPostfix(const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + _text + "> is not loaded", FL_AT); } if (not node) node = getExpression(); if (dynamic_cast<const Proposition*> (node)) { return node->toString(); } std::stringstream ss; if (const Operator * fuzzyOperator = dynamic_cast<const Operator*> (node)) { ss << toPostfix(fuzzyOperator->left) << " " << toPostfix(fuzzyOperator->right) << " " << fuzzyOperator->toString() << " "; } else { ss << "[antecedent error] unknown class of Expression <" << (node ? node->toString() : "null") << ">"; } return ss.str(); } }
42.020089
130
0.511766
5f0b11c4cd68c112a699f2ce03244a5e7c0a8e3a
2,075
cpp
C++
cmd/qc.cpp
cbutakoff/DSI-Studio
d77dffa4526d66da421fa84f7187e85bca6bce7c
[ "BSD-3-Clause" ]
null
null
null
cmd/qc.cpp
cbutakoff/DSI-Studio
d77dffa4526d66da421fa84f7187e85bca6bce7c
[ "BSD-3-Clause" ]
null
null
null
cmd/qc.cpp
cbutakoff/DSI-Studio
d77dffa4526d66da421fa84f7187e85bca6bce7c
[ "BSD-3-Clause" ]
null
null
null
#include <QString> #include <QStringList> #include <QFileInfo> #include "program_option.hpp" #include "libs/dsi/image_model.hpp" QStringList search_files(QString dir,QString filter); std::string quality_check_src_files(QString dir) { std::ostringstream out; QStringList filenames = search_files(dir,"*.src.gz"); out << "FileName\tImage dimension\tResolution\tDWI count\tMax b-value\tB-table matched\tNeighboring DWI correlation" << std::endl; int dwi_count = 0; float max_b = 0; for(int i = 0;check_prog(i,filenames.size());++i) { out << QFileInfo(filenames[i]).baseName().toStdString() << "\t"; ImageModel handle; unique_prog(true); if (!handle.load_from_file(filenames[i].toStdString().c_str())) { out << "Cannot load SRC file" << std::endl; continue; } unique_prog(false); // output image dimension out << image::vector<3,int>(handle.voxel.dim.begin()) << "\t"; // output image resolution out << handle.voxel.vs << "\t"; // output DWI count int cur_dwi_count = 0; out << (cur_dwi_count = handle.src_bvalues.size()) << "\t"; if(i == 0) dwi_count = cur_dwi_count; // output max_b float cur_max_b = 0; out << (cur_max_b = *std::max_element(handle.src_bvalues.begin(),handle.src_bvalues.end())) << "\t"; if(i == 0) max_b = cur_max_b; // check shell structure out << (max_b == cur_max_b && cur_dwi_count == dwi_count ? "Yes\t" : "No\t"); // calculate neighboring DWI correlation out << handle.quality_control_neighboring_dwi_corr() << "\t"; out << std::endl; } return out.str(); } /** perform reconstruction */ int qc(void) { std::string file_name = po.get("source"); if(QFileInfo(file_name.c_str()).isDir()) { file_name += "\\src_report.txt"; std::ofstream out(file_name.c_str()); out << quality_check_src_files(file_name.c_str()); } return 0; }
30.514706
134
0.595663
5f0e3f2dd7ee0392eb3e547e9dc2ff6d8748df75
1,193
hpp
C++
tooling/data/prefix_splitter.hpp
victorlaurentiu/tsmp
5391ffb488d7db9555405965ede5c63800fbb71f
[ "MIT" ]
23
2021-10-30T09:32:58.000Z
2022-01-23T19:39:26.000Z
tooling/data/prefix_splitter.hpp
victorlaurentiu/tsmp
5391ffb488d7db9555405965ede5c63800fbb71f
[ "MIT" ]
null
null
null
tooling/data/prefix_splitter.hpp
victorlaurentiu/tsmp
5391ffb488d7db9555405965ede5c63800fbb71f
[ "MIT" ]
4
2021-10-31T13:05:29.000Z
2021-11-27T03:18:48.000Z
#pragma once #include "types.hpp" #include <fmt/core.h> #include <fmt/ranges.h> #include <algorithm> #include <iterator> namespace data { class prefix_splitter_t { public: prefix_splitter_t(const std::vector<record_decl_t>& records = {}, std::vector<std::string> trivial_types = {}); void add_record(record_decl_t record); const std::vector<field_decl_t>& fields() const; const std::vector<function_decl_t>& functions() const; const std::vector<record_decl_t>& records() const; static std::string strip_special_chars(std::string input); std::string render() const; private: bool has_field(const field_decl_t& field, const std::vector<field_decl_t>& field_list) const; bool has_function(const function_decl_t& function, const std::vector<function_decl_t>& function_list) const; void add_field(const field_decl_t& field); void add_function(const function_decl_t& function); bool field_list_match(const record_decl_t& lhs, const record_decl_t& rhs) const; std::vector<field_decl_t> m_fields; std::vector<function_decl_t> m_functions; std::vector<record_decl_t> m_records; std::vector<std::string> m_trivial_types; }; }
31.394737
115
0.736798
5f10a140d8b55a3b61668b65754fdce6601f3d16
2,058
hpp
C++
include/shadertoy/pre.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2020-02-23T09:33:07.000Z
2021-11-15T18:23:13.000Z
include/shadertoy/pre.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2019-08-09T15:48:07.000Z
2020-11-16T13:51:56.000Z
include/shadertoy/pre.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
3
2019-12-12T09:42:34.000Z
2020-12-14T03:56:30.000Z
#ifndef _SHADERTOY_PRE_HPP_ #define _SHADERTOY_PRE_HPP_ #include "shadertoy/shadertoy_export.h" /// Base namespace for libshadertoy namespace shadertoy { /// Definition of rendering buffers namespace buffers { struct buffer_output; class basic_buffer; class program_buffer; class toy_buffer; } /// Shader source compiler types namespace compiler { class basic_part; class template_part; class file_part; class program_template; } /// Geometry primitives namespace geometry { class basic_geometry; class screen_quad; } /// OpenGL wrapper helpers namespace gl { class null_buffer_error; class buffer; class opengl_error; class null_framebuffer_error; class framebuffer; class null_program_error; class attrib_location; class uniform_location; class program_link_error; class program_validate_error; class program; class null_query_error; class query; class null_sampler_error; class sampler; class null_renderbuffer_error; class renderbuffer; class null_shader_error; class shader_compilation_error; class shader_allocator; class shader; class null_texture_error; class texture_allocator; class texture; class null_vertex_array_error; class vertex_array; } /// Buffer input class definitions namespace inputs { class basic_input; class buffer_input; class checker_input; class error_input; class exr_input; class file_input; class image_input; class jpeg_input; class noise_input; class soil_input; } /// Swap chain member class definitions namespace members { class basic_member; class buffer_member; class screen_member; } /// Miscellaneous utilities namespace utils { } class basic_shader_inputs; class bound_inputs_base; class swap_chain; class render_context; class shader_compiler; class texture_engine; } // Include template and utilities everywhere #include "shadertoy/shadertoy_error.hpp" #include "shadertoy/size.hpp" #include "shadertoy/member_swap_policy.hpp" #endif /* _SHADERTOY_PRE_HPP_ */
17.294118
44
0.76725
5f126bb8b7c978139132b0742118e7df3dc353d8
71
cc
C++
logs/doc/02_window.cc
chanchann/Burger_client
548753124b563123a479f3e3a5a42f792001d673
[ "MIT" ]
null
null
null
logs/doc/02_window.cc
chanchann/Burger_client
548753124b563123a479f3e3a5a42f792001d673
[ "MIT" ]
null
null
null
logs/doc/02_window.cc
chanchann/Burger_client
548753124b563123a479f3e3a5a42f792001d673
[ "MIT" ]
null
null
null
/** * https://blog.csdn.net/Zhanganliu/article/details/79927310 * */
17.75
60
0.676056
5f13923f795cc5a51afee898d5e4b906cd968f74
3,048
cpp
C++
src/target_new_source.cpp
folkertvanheusden/constatus
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
[ "Apache-2.0" ]
5
2021-07-15T11:39:25.000Z
2022-02-25T06:14:58.000Z
src/target_new_source.cpp
folkertvanheusden/constatus
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
[ "Apache-2.0" ]
2
2021-09-27T11:13:42.000Z
2021-10-10T01:02:39.000Z
src/target_new_source.cpp
folkertvanheusden/constatus
7b0c42a5017bf96afcb0f34c0d4987bdc40ef2e6
[ "Apache-2.0" ]
2
2021-06-11T09:19:47.000Z
2022-02-18T22:22:01.000Z
// (C) 2017-2021 by folkert van heusden, released under Apache License v2.0 #include "config.h" #include <unistd.h> #include "target_new_source.h" #include "error.h" #include "exec.h" #include "log.h" #include "picio.h" #include "utils.h" #include "controls.h" #include "source.h" #include "view.h" #include "filter.h" #include "schedule.h" target_new_source::target_new_source(const std::string & id, const std::string & descr, source *const s, const double interval, const std::vector<filter *> *const filters, configuration_t *const cfg, const std::string & new_s_id, const std::string & new_s_descr, schedule *const sched, const bool rot90) : target(id, descr, s, "", "", "", -1, interval, filters, "", "", "", -1, cfg, false, false, sched), new_s_id(new_s_id), new_s_descr(new_s_descr), rot90(rot90) { } target_new_source::~target_new_source() { stop(); } source * target_new_source::get_new_source() { new_source_lock.lock(); if (!new_source) { log(id, LL_INFO, "Instantiating new source %s", new_s_id.c_str()); new_source = new source(new_s_id, new_s_descr, "", -1.0, nullptr, -1, -1, LL_DEBUG, 0.1, nullptr, default_failure(), new controls(), 100); } new_source_lock.unlock(); return new_source; } void target_new_source::operator()() { log(id, LL_INFO, "\"as-a-new-source\" thread started"); set_thread_name("newsrc" + new_s_id); const double fps = 1.0 / interval; video_frame *prev_frame = nullptr; uint64_t prev_ts = 0; s -> start(); for(;!local_stop_flag;) { pauseCheck(); st->track_fps(); uint64_t before_ts = get_us(); if (new_source) { video_frame *pvf = s->get_frame(false, prev_ts); if (pvf) { prev_ts = pvf->get_ts(); if (filters && !filters->empty()) { instance *inst = find_instance_by_interface(cfg, s); video_frame *temp = pvf->apply_filtering(inst, s, prev_frame, filters, nullptr); delete pvf; pvf = temp; } const bool allow_store = sched == nullptr || sched->is_on(); if (allow_store) { auto img = pvf->get_data_and_len(E_RGB); const uint8_t *data = std::get<0>(img); const size_t len = std::get<1>(img); const int w = pvf->get_w(); const int h = pvf->get_h(); if (rot90) { // rotate uint8_t *new_ = (uint8_t *)malloc(len); for(int y=0; y<h; y++) { for(int x=0; x<w; x++) { new_[x * h * 3 + y * 3 + 0] = data[y * w * 3 + x * 3 + 0]; new_[x * h * 3 + y * 3 + 1] = data[y * w * 3 + x * 3 + 1]; new_[x * h * 3 + y * 3 + 2] = data[y * w * 3 + x * 3 + 2]; } } new_source->set_size(h, w); new_source->set_frame(E_RGB, new_, len); free(new_); } else { new_source->set_size(w, h); new_source->set_frame(E_RGB, data, len); } } delete prev_frame; prev_frame = pvf; } } st->track_cpu_usage(); handle_fps(&local_stop_flag, fps, before_ts); } delete prev_frame; s -> stop(); log(id, LL_INFO, "\"as-a-new-source\" thread terminating"); }
24.983607
463
0.60794
5f1595b06f2a1d2c8efbc669cdcae259b36202f9
18,988
cpp
C++
demo/OBB/DOTA2_0/src/yolox_obb.cpp
DDGRCF/YOLOX_OBB
27b80953306492b8bc83b86b1353d8cee01ef9b6
[ "Apache-2.0" ]
39
2021-11-09T12:12:06.000Z
2022-03-28T13:45:20.000Z
demo/OBB/DOTA2_0/src/yolox_obb.cpp
DDGRCF/YOLOX_OBB
27b80953306492b8bc83b86b1353d8cee01ef9b6
[ "Apache-2.0" ]
12
2021-11-09T11:33:29.000Z
2022-03-25T17:00:14.000Z
demo/OBB/DOTA2_0/src/yolox_obb.cpp
DDGRCF/YOLOX_OBB
27b80953306492b8bc83b86b1353d8cee01ef9b6
[ "Apache-2.0" ]
1
2022-03-24T06:53:39.000Z
2022-03-24T06:53:39.000Z
#include "yolox_obb.h" #include <fstream> #include <iostream> #include <sstream> #include <numeric> #include <chrono> #include <vector> #include <dirent.h> #include <exception> #include <opencv2/opencv.hpp> // #include <xtensor/xarray.hpp> const char * input_blob_name = "input_0"; const char * output_blob_name = "output_0"; static const int num_classes = 18; static const int input_size[2] = {1024, 1024}; static const int strides[3] = {8, 16, 32}; static Logger gLogger; using namespace nvinfer1; cv::Mat static_resize(cv::Mat & img, const int resize_size[2]); void decode_outputs(float * output, std::vector<Object> & objects, const float scale, const int * origin_size, const int * input_size, const int * strides, const int & num_classes, const int num_stages=3, const float bbox_thre=0.3, const float nms_thre=0.45); void draw_objects(cv::Mat & image, const std::vector<Object> & objects, const std::string save_path = "", const bool is_save=true); float* blobFromImage(cv::Mat & img); void PutRotatedText(cv::Mat & img, char * text, const cv::RotatedRect & rotatedrect, const cv::Scalar & color, int thickness, int lineType, int baseLine); void DrawRotatedRect(cv::Mat & img, const cv::RotatedRect & rotatedrect, const cv::Scalar & color, int thickness, int lineType); void doInference(IExecutionContext & context, float * input, float * output, const int input_data_size, const int output_data_size, const int inputIndex, const int outputIndex); int main(int argc, char** argv) { char * trtModelStream(nullptr); size_t size{0}; if (argc == 6 && std::string(argv[2]) == "-i" && std::string(argv[4]) == "-s") { const std::string engine_file_path {argv[1]}; std::cout << "engine file is " << engine_file_path << std::endl; std::ifstream file(engine_file_path, std::ios::binary); if (file.good()) { file.seekg(0, file.end); size = file.tellg(); file.seekg(0, file.beg); trtModelStream = new char[size]; assert(trtModelStream); file.read(trtModelStream, size); file.close(); } } else { std::cerr << "some errors in argv" << std::endl; std::cerr << "please check argv" << std::endl; abort(); } // argv info const std::string input_path {argv[3]}; const std::string save_path {argv[5]}; std::cout << "input path is " << input_path << std::endl; std::cout << "save path is " << save_path << std::endl; std::string suffixStr = input_path.substr(input_path.find_last_of('.') + 1); // create engine and conetext IRuntime * runtime = createInferRuntime(gLogger); assert(runtime != nullptr); ICudaEngine * engine = runtime->deserializeCudaEngine(trtModelStream, size); assert(engine != nullptr); IExecutionContext * context = engine->createExecutionContext(); assert(context != nullptr); delete[] trtModelStream; // get size of input and output const int inputIndex = engine->getBindingIndex(input_blob_name); auto input_data_size = 3 * input_size[0] * input_size[1]; const int outputIndex = engine->getBindingIndex(output_blob_name); auto out_dims = engine->getBindingDimensions(outputIndex); auto output_data_size = 1; for(int j=0; j<out_dims.nbDims; ++j) output_data_size *= out_dims.d[j]; // image inference if (suffixStr == "jpg" || suffixStr == "png") { float * prob = new float[output_data_size]; std::cout << "Begin inference images ..." << std::endl; cv::Mat img = cv::imread(input_path); const int origin_size[2] = {img.rows, img.cols}; float scale_ratio = std::min(input_size[0] / (origin_size[0] * 1.0), input_size[1] / (origin_size[1] * 1.0)); cv::Mat pr_img = static_resize(img, input_size); float * blob = blobFromImage(pr_img); auto start = std::chrono::system_clock::now(); doInference(*context, blob, prob, input_data_size, output_data_size, inputIndex, outputIndex); auto end = std::chrono::system_clock::now(); std::cout << "Inference cost :" << \ std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \ "ms" << std::endl; std::vector<Object> objects; start = std::chrono::system_clock::now(); decode_outputs(prob, objects, scale_ratio, origin_size, input_size, strides, num_classes, NUM_STAGES, BBOX_THRE, NMS_THRE); end = std::chrono::system_clock::now(); std::cout << "Decode cost :" << \ std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << \ "ms" << std::endl; draw_objects(img, objects, save_path, true); delete [] blob; delete [] prob; } else if (suffixStr == "mp4" || suffixStr == "avi") { std::cout << "Begin inference videos ..." << std::endl; cv::VideoCapture capture; capture.open(input_path); if (!capture.isOpened()) { std::cout << "Can not open ..." << std::endl; return -1; } cv::Size size = cv::Size(capture.get(cv::CAP_PROP_FRAME_WIDTH), capture.get(cv::CAP_PROP_FRAME_HEIGHT)); cv::VideoWriter writer; // writer.open(save_path, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 10, size, true); writer.open(save_path, 0x7634706d, 10, size, true); cv::Mat frame; const int origin_size[2] = {size.height, size.width}; float scale_ratio = std::min(input_size[0] / origin_size[0], input_size[1] / origin_size[1]); while (capture.read(frame)) { auto start = std::chrono::system_clock::now(); float * prob = new float[output_data_size]; cv::Mat pr_img = static_resize(frame, input_size); float * blob = blobFromImage(pr_img); doInference(*context, blob, prob, input_data_size, output_data_size, inputIndex, outputIndex); std::vector<Object> objects; decode_outputs(prob, objects, scale_ratio, origin_size, input_size, strides, num_classes, NUM_STAGES, BBOX_THRE, NMS_THRE); draw_objects(frame, objects, "", false); auto end = std::chrono::system_clock::now(); int inference_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); char FPS_text[256]; sprintf(FPS_text, "FPS: %.1f", inference_time * 0.025); cv::Size label_size = cv::getTextSize(FPS_text, cv::FONT_HERSHEY_SIMPLEX, 0.4, 1, 0); cv::putText(frame, FPS_text, (cv::Point2f){10.f, 10.f + (float)label_size.height}, cv::FONT_HERSHEY_SIMPLEX, 0.4, cv::Scalar(255, 0, 0), 1); writer.write(frame); cv::waitKey(10); delete [] prob; delete [] blob; } } context->destroy(); engine->destroy(); runtime->destroy(); return 0; } void doInference(IExecutionContext & context, float * input, float * output, const int input_data_size, const int output_data_size, const int inputIndex, const int outputIndex) { const ICudaEngine & engine = context.getEngine(); assert(engine.getNbBindings() == 2); void * buffers[2]; // const int mBatchSize = engine.getMaxBatchSize(); CHECK(cudaMalloc(&buffers[inputIndex], input_data_size * sizeof(float))); CHECK(cudaMalloc(&buffers[outputIndex], output_data_size * sizeof(float))); cudaStream_t stream; CHECK(cudaStreamCreate(&stream)); CHECK(cudaMemcpyAsync(buffers[inputIndex], input, input_data_size * sizeof(float), cudaMemcpyHostToDevice, stream)); context.enqueue(1, buffers, stream, nullptr); CHECK(cudaMemcpyAsync(output, buffers[outputIndex], output_data_size * sizeof(float), cudaMemcpyDeviceToHost, stream)); cudaStreamSynchronize(stream); cudaStreamDestroy(stream); CHECK(cudaFree(buffers[inputIndex])); CHECK(cudaFree(buffers[outputIndex])); } int get_num_anchors(const int * strides, const int * size, const int num_stages) { std::vector<int> feature_size; int h = size[0]; int w = size[1]; for (int i = 0; i < num_stages; i++) feature_size.push_back(h * w / (strides[i] * strides[i])); return std::accumulate(feature_size.begin(), feature_size.end(), 0); } static void qsort_descent_inplace(std::vector<Object>& objects, int left, int right) { int i = left; int j = right; float p = objects[(left + right) / 2].prob; while (i <= j) { while (objects[i].prob > p) i++; while (objects[j].prob < p) j--; if (i <= j) { // swap std::swap(objects[i], objects[j]); i++; j--; } } #pragma omp parallel sections { #pragma omp section { if (left < j) qsort_descent_inplace(objects, left, j); } #pragma omp section { if (i < right) qsort_descent_inplace(objects, i, right); } } } static void qsort_descent_inplace(std::vector<Object>& objects) { if (objects.empty()) return; qsort_descent_inplace(objects, 0, objects.size() - 1); } void nms_sorted_bboxes(const std::vector<Object>& objects, std::vector<int>& picked, float nms_threshold) { picked.clear(); const int n = objects.size(); std::vector<float> areas(n); for (int i = 0; i < n; i++) { Object object = objects[i]; float object_width = object.rect.size.width; float object_height = object.rect.size.height; areas[i] = object_width * object_height; } for (int i = 0; i < n; i++) { const Object & a = objects[i]; int keep = 1; for (int j = 0; j < (int)picked.size(); j++) { const Object& b = objects[picked[j]]; // intersection over union std::vector<cv::Point2f> rotatedinterregion; try { cv::rotatedRectangleIntersection(a.rect, b.rect, rotatedinterregion); } catch(const char * &e) { std::cout << "there are existing boxes overrided" << std::endl; keep = 1 ; continue; } std::vector<cv::Point2f> hull; if (rotatedinterregion.size() < 3) continue; cv::convexHull(cv::Mat(rotatedinterregion), hull, true); if (hull.size() < 3) continue; float inter_area = cv::contourArea(hull); float union_area = areas[i] + areas[picked[j]] - inter_area; // float IoU = inter_area / union_area if (inter_area / union_area > nms_threshold) keep = 0; } if (keep) picked.push_back(i); } } void decode_outputs(float * output, std::vector<Object> & objects, const float scale, const int * origin_size, const int * input_size, const int * strides, const int & num_classes, const int num_stages, const float bbox_thre, const float nms_thre) { // std::vector<Object> proposals; const size_t num_anchors = get_num_anchors(strides, input_size, num_stages); const size_t out_channels = num_classes + 6; // generate grids // auto grides = xt::empty<float>(grids_shape); float * grides = new float[num_anchors * 3]; int index = 0; for (int i = 0; i < num_stages; i++) { int num_grid_y = input_size[0] / strides[i]; int num_grid_x = input_size[1] / strides[i]; for (int g1 = 0; g1 < num_grid_y; g1++) { for (int g0 = 0; g0 < num_grid_x; g0++) { grides[index * 3 + 0] = (float)g0; grides[index * 3 + 1] = (float)g1; grides[index * 3 + 2] = (float)strides[i]; index++; } } } // decodea prob std::vector<Object> proposals; for (int i = 0; i < num_anchors; i++) { Object object; float ctr_x = *(output + out_channels * i + 0); float ctr_y = *(output + out_channels * i + 1); float w = *(output + out_channels * i + 2); float h = *(output + out_channels * i + 3); float angle = *(output + out_channels * i + 4); float obj_prob = *(output + out_channels * i + 5); int class_pred = std::distance( output + out_channels * (i + 1) - num_classes, std::max_element(output + out_channels * (i + 1) - num_classes, output + out_channels * (i + 1))); float class_prob = *(output + out_channels * (i + 1) - num_classes + class_pred); float prob = obj_prob * class_prob; if (prob < bbox_thre) continue; float grid_x = grides[i * 3 + 0]; float grid_y = grides[i * 3 + 1]; float stride = grides[i * 3 + 2]; ctr_x = (ctr_x + grid_x) * stride; ctr_y = (ctr_y + grid_y) * stride; w = std::exp(w) * stride; h = std::exp(h) * stride; angle = -angle * 180 / M_PI; object.rect = (cv::RotatedRect){(cv::Point2f){ctr_x, ctr_y}, (cv::Size2f){w, h}, angle}; object.label = class_pred; object.prob = prob; proposals.push_back(object); } std::vector<int> picked; qsort_descent_inplace(proposals); nms_sorted_bboxes(proposals, picked, nms_thre); // objects.resize(picked.size()); for (int i = 0; i < picked.size(); i++) { Object object = proposals[picked[i]]; float ctr_x = object.rect.center.x / scale; float ctr_y = object.rect.center.y / scale; float width = object.rect.size.width / scale; float height = object.rect.size.height / scale; if (ctr_x < 0. || ctr_y < 0. || ctr_x > origin_size[1] || ctr_y > origin_size[0]) continue; objects.push_back( (Object){ (cv::RotatedRect){ (cv::Point2f){ctr_x, ctr_y}, (cv::Size2f){width, height}, object.rect.angle }, object.label, object.prob } ); } } cv::Mat static_resize(cv::Mat & img, const int resize_size[2]) { const int input_h = resize_size[0]; const int input_w = resize_size[1]; float r = std::min(input_w / (img.cols * 1.0), input_h / (img.rows * 1.0)); int unpad_w = r * img.cols; int unpad_h = r * img.rows; cv::Mat re(unpad_h, unpad_w, CV_8UC3); // 8UC3(uint8 and 3 channels) cv::resize(img, re, re.size()); cv::Mat out(input_h, input_w, CV_8UC3); re.copyTo(out(cv::Rect(0, 0, re.cols, re.rows))); return out; } float* blobFromImage(cv::Mat& img){ float* blob = new float[img.total()*3]; int channels = 3; int img_h = img.rows; int img_w = img.cols; for (size_t c = 0; c < channels; c++) { for (size_t h = 0; h < img_h; h++) { for (size_t w = 0; w < img_w; w++) { // cv::Vec3b的b指的是数据类型(b是8U) blob[c * img_w * img_h + h * img_w + w] = (float)img.at<cv::Vec3b>(h, w)[c]; } } } return blob; } void draw_objects( cv::Mat & image, const std::vector<Object> & objects, const std::string save_path, const bool is_save) { for (size_t i = 0; i < objects.size(); i++) { const Object & obj = objects[i]; cv::Scalar color = cv::Scalar(color_list[obj.label][0], color_list[obj.label][1], color_list[obj.label][2]); float c_mean = cv::mean(color)[0]; cv::Scalar txt_color; if (c_mean > 0.5) txt_color = cv::Scalar(0, 0, 0); else txt_color = cv::Scalar(255, 255, 255); char text[256]; DrawRotatedRect(image, obj.rect, color, 4, 8); sprintf(text, "%s %.1f%", dota20_class_names[obj.label], obj.prob); // PutRotatedText(image, text, obj.rect, txt_color, 1, 1); cv::putText(image, text, obj.rect.center, cv::FONT_HERSHEY_SIMPLEX, 0.4, txt_color, 1, 1); if (is_save) cv::imwrite(save_path, image); // cv::imshow("det_res.jpg", image); // cv::waitKey(0); } } void DrawRotatedRect(cv::Mat & img, const cv::RotatedRect & rotatedrect, const cv::Scalar & color, int thickness, int lineType) { // 提取旋转矩形的四个角点 cv::Point2f ps[4]; rotatedrect.points(ps); // 构建轮廓线 std::vector<std::vector<cv::Point>> tmpContours; // 创建一个InputArrayOfArrays 类型的点集 std::vector<cv::Point> contours; for (int i = 0; i != 4; ++i) { contours.emplace_back(cv::Point2i(ps[i])); } tmpContours.insert(tmpContours.end(), contours); // 绘制轮廓,即旋转矩形 cv::drawContours(img, tmpContours, 0, color,thickness, lineType); } void PutRotatedText(cv::Mat & img, char * text, const cv::RotatedRect & rotatedrect, const cv::Scalar & color, int thickness, int lineType, int baseLine) { cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.4, 1., &baseLine); cv::Scalar txt_bk_color = color * 0.7 * 255; cv::Point2f center = rotatedrect.center; // cv::Size2f wh = rotatedrect.size; cv::Mat img_t = cv::Mat::zeros(img.rows, img.cols, img.type()); // cv::rectangle(img_t, (cv::Rect){(cv::Point2f)(center.x - wh.width / 2.0, center.y - wh.height / 2.0 - label_size.height-1), // (cv::Size2f(label_size.width, label_size.height + baseLine))}, txt_bk_color, // thickness, lineType); cv::putText(img_t, text, cv::Point(center.x, center.y), cv::FONT_HERSHEY_SIMPLEX, 0.4, color, 1); // cv::Mat M = cv::getRotationMatrix2D(ps[0], rotatedrect.angle, 1.0); // int _len = std::max(img_t.cols, img_t.rows); // cv::warpAffine(img_t, img_t, M, cv::Size(_len, _len)); cv::addWeighted(img, 1.0, img_t, 0.6, 0., img); }
36.445298
131
0.557089
5f1a72bb9a4c910ddbe4a97a8b109b5681b1f070
4,044
cpp
C++
projector_fun/data/metaballs.cpp
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
projector_fun/data/metaballs.cpp
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
projector_fun/data/metaballs.cpp
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "metaballs.h" using namespace std; using namespace glm; namespace asdf { namespace projector_fun { metaballs_t::metaballs_t() { balls.reserve(5); balls.push_back(metaball_t{vec3{0.0f, 0.0f, 0.0f}, 50.0f}); balls.push_back(metaball_t{vec3{-100.0f, 100.0f, 0.0f}, 50.0f, vec3{20.0f, -150.0f, 0.0f}}); balls.push_back(metaball_t{vec3{280.0f, -280.0f, 0.0f}, 20.0f, vec3{100.0f, -100.0f, 0.0f}}); balls.push_back(metaball_t{vec3{0.0f, 0.0f, 0.0f}, 10.0f, vec3{100.0f, 20.0f, 0.0f}}); //pre-fill for(size_t i = 0; i < (texture_width * texture_height); ++i) { color_data[i] = clear_color; } texture = std::make_shared<texture_t>("metaball_texture", color_data, texture_width, texture_height); } vec3 metaballs_t::get_pos(const size_t x, const size_t y) const { auto halfwidth = texture_width / 2; auto halfheight = texture_height / 2; auto screenpos = texture_to_screen_space(ivec2{x, y}, ivec2{halfwidth, halfheight}); return vec3(screenpos.x, screenpos.y, 0.0f); } void metaballs_t::draw_metaballs() { //clear for(size_t i = 0; i < (texture_width * texture_height); ++i) { color_data[i] = clear_color; } for(size_t y = 0; y < texture_height; ++y) { for(size_t x = 0; x < texture_width; ++x) { float sum = 0; // Value to act as a summation of all Metaballs' fields applied to this particular pixel for(auto const& ball : balls) { sum += ball.calc(get_pos(x,y)); } draw_pixel(x, y, sum); } } // LOG("max sum: %f", max_sum); texture->write(color_data, texture_width, texture_height); } void metaballs_t::draw_pixel(const size_t x, const size_t y, const float sum) { float min_threshold = 0.99f * draw_mode != shaded; float max_threshold = 1.01f; bool should_draw = false; should_draw |= (draw_mode == hollow) && sum >= min_threshold && sum <= max_threshold; should_draw |= (draw_mode == fill) && sum >= min_threshold; should_draw |= (draw_mode == shaded) && sum >= min_threshold; should_draw |= (draw_mode == inverse) && sum <= max_threshold; if(should_draw) { auto color = COLOR_WHITE; if(draw_mode == shaded) { color = color_data[y * texture_width + x]; color += glm::min(1.0f, sum/5.0f) * COLOR_WHITE; } color_data[y * texture_width + x] = color; } } std::shared_ptr<texture_t> metaballs_t::array_to_texture() { draw_metaballs(); return std::make_shared<texture_t>("metaball test" , color_data , texture_width, texture_height); } void metaballs_t::update(float dt) { float extra_wrap_space = 0.0f; for(auto const& ball : balls) { extra_wrap_space = glm::max(ball.radius, extra_wrap_space); } extra_wrap_space *= 4; // extra_wrap_space = glm::max(texture->halfwidth, texture->halfheight); auto ball_lower_bounds = glm::vec3{-texture->halfwidth - extra_wrap_space, -texture->halfheight - extra_wrap_space, 0.0f}; auto ball_upper_bounds = glm::vec3{ texture->halfwidth + extra_wrap_space, texture->halfheight + extra_wrap_space, 0.0f}; for(auto& ball : balls) { // wrap around sides ball.position.x *= 1 - (2 * (ball.position.x > ball_upper_bounds.x || ball.position.x < ball_lower_bounds.x)); ball.position.y *= 1 - (2 * (ball.position.y > ball_upper_bounds.y || ball.position.y < ball_lower_bounds.y)); ball.position += ball.velocity * dt; } } } }
32.095238
130
0.560584
5f1c68e8389253e45e3b6f1c21c2eb39ea14d50d
6,349
cpp
C++
Products/Common/sxml_print.cpp
TrevorDArcyEvans/DivingMagpieSoftware
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
1
2021-05-27T10:27:25.000Z
2021-05-27T10:27:25.000Z
Products/Common/sxml_print.cpp
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
Products/Common/sxml_print.cpp
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "XML_XSL.h" #include "SRegistryAccess.hpp" #include "SHResult.hpp" #include "LogEvent.h" #include "SLogError.h" #include "SXML_Print.h" #include "RemoveAllCharactersInFile.h" #include "SDelayedDeleteFile.h" //------------------------------------------------------------------------ SXML_Print::SXML_Print() { Initialise(); }//SXML_Print::SXML_Print //------------------------------------------------------------------------ SXML_Print::SXML_Print ( CString sRegKey ) { Initialise(); m_RegKey = sRegKey; }//SXML_Print::SXML_Print //------------------------------------------------------------------------ // SXML_Print::Initialise // called by both constructors to set all member variables to blank SXML_Print::Initialise() { m_RegKey = _T(""); m_XSL_FileName = _T(""); m_OutputFileExt = _T(""); m_TimeOut = 10; m_RemoveChars.clear(); }//SXML_Print::Initialise //------------------------------------------------------------------------ SXML_Print::~SXML_Print() { }//SXML_Print::~SXML_Print //------------------------------------------------------------------------ // SXML_Print::AddRemoveChar // adds specified character to the end of the list of characters to remove // from output file // // parameters // cRemoveChar // character to remove from output file // this can be any character in the extended ASCII character set // ASCII 0 -255 inclusive // // returns // S_OK // always returns S_OK! HRESULT SXML_Print::AddRemoveChar ( char cRemoveChar ) { m_RemoveChars.push_back(cRemoveChar); return S_OK; }//SXML_Print::AddRemoveChar //------------------------------------------------------------------------ // SXML_Print::LoadSettings // queries registry keys for the XSL filename and the extension for the // output file. Registry key is specified by m_RegKey and string values // are read out of the following sub-keys: // // "XSL FileName" --> m_XSL_FileName // "Output FileExt" --> m_OutputFileExt // "TimeOut" --> m_TimeOut // // If m_RegKey = _T("CMIDS\\Archiver") then settings will be read out of the // following registry keys: // // [HKEY_LOCAL_MACHINE\SOFTWARE\Sigmex\CMIDS\Archiver] // "XSL FileName"="c:\\Archiver.xsl" // "Output FileExt"="html" SXML_Print::LoadSettings() { // load XSL file name & output file extension out of the registry SRegistryAccess RegAc(HKEY_LOCAL_MACHINE); m_XSL_FileName = RegAc.ReadString(m_RegKey, _T("XSL FileName" )); m_OutputFileExt = RegAc.ReadString(m_RegKey, _T("Output FileExt")); m_TimeOut = RegAc.ReadInt (m_RegKey, _T("TimeOut" ), m_TimeOut); }//SXML_Print::LoadSettings //------------------------------------------------------------------------ // SXML_Print::Print // will query the registry for an XSL file to apply to the specified XML file, // apply the XSL file and print it out to the default system printer // // parameters // sXMLFileName // fully qualified name to XML file to print out // // returns // S_OK // if successfully printed out file // otherwise // return values from IDMS_XML2XSL::Print() in XML2XSL.cpp // // notes // caller should call CWaitCursor before calling this function as we // wait for the print program to initialise and start printing before // returning HRESULT SXML_Print::Print ( CString sXMLFileName ) { HRESULT hres = S_OK; CString sOutputFileName; try { TCHAR sTempPath [MAX_PATH]; TCHAR sTempFileName[MAX_PATH]; // work out where the temporary files are GetTempPath(sizeof(sTempPath) / sizeof(TCHAR), sTempPath); // form the output file name GetTempFileName(sTempPath, _T("SXML_Print"), 0, sTempFileName); sOutputFileName = sTempFileName; // remove temp file created by GetTempFileName() DeleteFile(sTempFileName); // remove existing extension int nDotPos = sOutputFileName.Find(_T(".")); if (-1 != nDotPos) { sOutputFileName.Delete(nDotPos + 1, sOutputFileName.GetLength() - nDotPos - 1); } // then add our own extension sOutputFileName += m_OutputFileExt; // now apply the XSL transform CComPtr <IDMS_XML2XSL> pXML_XSL; CComBSTR sXML_FileName = sXMLFileName; CComBSTR sXSL_FileName = m_XSL_FileName; CComBSTR sOutput_FileName = sOutputFileName; STEST_HR(pXML_XSL.CoCreateInstance(__uuidof(DMS_XML2XSL))); STEST_HR(pXML_XSL->put_XML_FileName (sXML_FileName )); STEST_HR(pXML_XSL->put_XSL_FileName (sXSL_FileName )); STEST_HR(pXML_XSL->put_Output_FileName(sOutput_FileName)); STEST_HR(pXML_XSL->Apply_XSL_XML()); // remove all extraneous characters from the output file // before we print out for (int i = 0; i < m_RemoveChars.size (); i++) { RemoveAllCharactersInFile(::CString(sOutput_FileName), m_RemoveChars[i]); } // finally print out - whew! STEST_HR(pXML_XSL->Print()); hres = S_OK; } catch (_com_error& e) { LogEvent(_T ("Error in SXML_Print::Print: %s"), e.ErrorMessage()); hres = E_UNEXPECTED; } catch (...) { LogEvent(_T ("Unknown error in SXML_Print::Print")); hres = E_UNEXPECTED; }//try // we have to wait for print program to initialise and print out // note that there is no *real* way of waiting as we don't know what to // wait on. Thus, this is just a guess... // // We cleanup the temporary files we've created before returning // note that we do this in a separate thread so as not to block SDelayedDeleteFile::DelayedDeleteFile(sOutputFileName, m_TimeOut); return hres; }//SXML_Print::Print //------------------------------------------------------------------------
33.067708
91
0.559143
5f21d84c5ad5cc082a87ea46dcf513cbcc1485f8
165
hh
C++
src/debug.hh
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
src/debug.hh
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
src/debug.hh
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
#ifndef debug_hh_INCLUDED #define debug_hh_INCLUDED #include "string.hh" namespace Kakoune { void write_debug(const String& str); } #endif // debug_hh_INCLUDED
11.785714
36
0.775758
5f23c46d08dbd90a6786bc62dbb46ddd5bf8d734
367
cpp
C++
Exercicios/42.cpp
thiago1590/Exercicios_LinguagemC_1periodo
a7affcbb121493ef8abb556a6bdb7c28926144df
[ "MIT" ]
null
null
null
Exercicios/42.cpp
thiago1590/Exercicios_LinguagemC_1periodo
a7affcbb121493ef8abb556a6bdb7c28926144df
[ "MIT" ]
null
null
null
Exercicios/42.cpp
thiago1590/Exercicios_LinguagemC_1periodo
a7affcbb121493ef8abb556a6bdb7c28926144df
[ "MIT" ]
null
null
null
#include <stdio.h> int calculo(int anos, int meses, int dias, int result) { result = (365 * anos) + (30 * meses) + dias;} int main() { int anos, meses, dias, result,a; printf("digite sua idade em anos meses e dias"); scanf("%d %d %d", &anos, &meses, &dias); a = calculo(anos, meses, dias, result); printf(" sua idade em dias eh %d", a); return 0; }
19.315789
55
0.607629
5f245914a64789f52ed6e45ea844f1f14ffb2212
787
cpp
C++
OnitamaEngine/Source/MoveInformation/MoveInformation.cpp
CodeGorger/OnitamaEngine
641930951ce272ee4922c5dfe57cc3b25b1ed37a
[ "MIT" ]
1
2021-09-14T16:25:02.000Z
2021-09-14T16:25:02.000Z
OnitamaEngine/Source/MoveInformation/MoveInformation.cpp
CodeGorger/OnitamaEngine
641930951ce272ee4922c5dfe57cc3b25b1ed37a
[ "MIT" ]
null
null
null
OnitamaEngine/Source/MoveInformation/MoveInformation.cpp
CodeGorger/OnitamaEngine
641930951ce272ee4922c5dfe57cc3b25b1ed37a
[ "MIT" ]
null
null
null
#include "MoveInformation.h" bool MoveInformation::ParseMove(std::string inTcpMove) { if (inTcpMove.size() > 20) { //"Invalid inTcpMove string is exceeded the maximal allowed length" return false; } size_t indexOfFirstSemicolon = inTcpMove.find_first_of(";"); _cardName=inTcpMove.substr(0, indexOfFirstSemicolon); _figureStartPosition.ParseFromChessString( inTcpMove.substr(indexOfFirstSemicolon,2)); size_t indexOfFirstCharAfterSemicolon = indexOfFirstSemicolon + 2; _figureEndPosition.ParseFromChessString( inTcpMove.substr(indexOfFirstCharAfterSemicolon, 2)); _isInitialized = true; return true; } std::string MoveInformation::ToString() { return _cardName + ";" + _figureStartPosition.ToChessString() + _figureEndPosition.ToChessString(); }
22.485714
69
0.768742
5f26fe6923b37dc6264b51411b8612ec8e293614
930
cpp
C++
src/utils/dll.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2020-04-10T14:39:00.000Z
2021-02-11T15:52:16.000Z
src/utils/dll.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2019-12-17T08:50:20.000Z
2020-02-03T09:37:56.000Z
src/utils/dll.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
1
2020-08-19T03:06:52.000Z
2020-08-19T03:06:52.000Z
#include "utils/dll.hpp" #ifdef OS_WINDOWS # include "utils/system.hpp" #endif namespace utils { dll::~dll() { if (m_handle == nullptr) { return; } #if defined OS_WINDOWS FreeLibrary(m_handle); #elif defined OS_LINUX dlclose(m_handle); #endif } dll::operator bool() const { return m_handle != nullptr; } std::string dll::error() const { #if defined OS_WINDOWS return sys_last_error(); #elif defined OS_LINUX const char *error = dlerror(); if (error == nullptr) { return ""; } return error; #endif } bool dll::load(const char *dll_path) { #if defined OS_WINDOWS if (m_handle != nullptr) { FreeLibrary(m_handle); } m_handle = LoadLibrary(dll_path); #elif defined OS_LINUX if (m_handle != nullptr) { dlclose(m_handle); } m_handle = dlopen(dll_path, RTLD_NOW); #endif return m_handle != nullptr; } bool dll::load(const std::string &dll_path) { return load(dll_path.c_str()); } } // namespace utils
16.034483
45
0.692473
5f284b2ca6233ddc59b0fa0a1e7b7007d1eaf132
1,276
cpp
C++
LeetCode/2058_Find_the_Minimum_and_Maximum_Number_of_Nodes_Between_Critical_Points/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
LeetCode/2058_Find_the_Minimum_and_Maximum_Number_of_Nodes_Between_Critical_Points/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
LeetCode/2058_Find_the_Minimum_and_Maximum_Number_of_Nodes_Between_Critical_Points/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { vector<int> answer(2, -1); if (head == nullptr) return answer; int back = head->val; vector<int> tmp; int idx = 1; if (head->next == nullptr) return answer; head = head->next; while (head->next != nullptr) { if ((back < head->val && head->val > head->next->val) || (back > head->val && head->val < head->next->val)) { tmp.push_back(idx); if (tmp.size() > 1) { if (answer[0] != -1) { answer[0] = min(answer[0], tmp.back() - tmp[tmp.size()-2]); } else { answer[0] = tmp.back() - tmp[tmp.size()-2]; } answer[1] = tmp.back() - tmp[0]; } } idx++; back = head->val; head = head->next; } return answer; } };
32.717949
121
0.442006
5f285e6e670fb5b70171c74ea1cacaa09eaf22be
918
hpp
C++
include/locomotion_viewer/LocomotionViewer.hpp
ori-drs/locomotion-viewer
6569d09786743283c1be8c47ca75171c1c4aeea0
[ "Apache-2.0" ]
6
2020-04-06T10:09:14.000Z
2022-01-07T02:05:06.000Z
include/locomotion_viewer/LocomotionViewer.hpp
ori-drs/locomotion-viewer
6569d09786743283c1be8c47ca75171c1c4aeea0
[ "Apache-2.0" ]
null
null
null
include/locomotion_viewer/LocomotionViewer.hpp
ori-drs/locomotion-viewer
6569d09786743283c1be8c47ca75171c1c4aeea0
[ "Apache-2.0" ]
2
2018-12-24T12:17:26.000Z
2021-03-01T23:21:10.000Z
/* * OnlineID.h * * Created on: Feb 11, 2018 * Author: Romeo Orsolino */ #ifndef RVIZPOLYGONSTOOLS_H_ #define RVIZPOLYGONSTOOLS_H_ #include <locomotion_viewer/ThreeDim.h> #include <Eigen/Dense> #include <iostream> #include <string> #include <chrono> namespace locomotion_viewer{ using legs_colors = std::vector<rviz_visual_tools::colors>; class LocomotionViewer: public locomotion_viewer::ThreeDim { public: LocomotionViewer(std::string base_frame, std::string marker_topic, ros::NodeHandle nh); ~LocomotionViewer(); legs_colors default_legs_colors_ = {rviz_visual_tools::RED,rviz_visual_tools::GREEN,rviz_visual_tools::BLUE,rviz_visual_tools::YELLOW}; rviz_visual_tools::colors base_color_; private: }; typedef std::shared_ptr<LocomotionViewer> LocomotionViewerPtr; } // namespace locomotion_viewer #endif /* DLS_ONLINEID_H_ */
20.863636
137
0.72658
5f2b2e114fb30ce3badacb521f4de1f1ff972894
919
cpp
C++
implementations/cairo/gb_cairo_main.cpp
enthought/GraphicsBench
ec0327c480fa91c71ec52239700b808db9bb272b
[ "BSD-3-Clause" ]
null
null
null
implementations/cairo/gb_cairo_main.cpp
enthought/GraphicsBench
ec0327c480fa91c71ec52239700b808db9bb272b
[ "BSD-3-Clause" ]
null
null
null
implementations/cairo/gb_cairo_main.cpp
enthought/GraphicsBench
ec0327c480fa91c71ec52239700b808db9bb272b
[ "BSD-3-Clause" ]
null
null
null
#include "gb_cairo_lines.h" #include "gb_cairo_box_alpha.h" #include "gb_cairo_box_gradient.h" #include "gb_cairo_memmove.h" int main(int argc, char **argv) { GBCairoLineBenchmark gb_cairo_line; gb_cairo_line.init(); gb_cairo_line.app_state.load_data("../../data/gb_lines.data"); gb_cairo_line.render(); GBCairoBoxBenchmark gb_cairo_box_alpha; gb_cairo_box_alpha.init(); gb_cairo_box_alpha.app_state.load_data("../../data/gb_box_alpha.data"); gb_cairo_box_alpha.render(); GBCairoBoxGradientBenchmark gb_cairo_box_gradient; gb_cairo_box_gradient.init(); gb_cairo_box_gradient.app_state.load_data("../../data/gb_box_alpha.data"); gb_cairo_box_gradient.render(); GBCairoMemmoveBenchmark gb_cairo_memmove; gb_cairo_memmove.init(); gb_cairo_memmove.app_state.load_data("../../data/gb_box_alpha.data"); gb_cairo_memmove.render(); return 0; }
30.633333
78
0.738847
5f2b5120ad88c492e66730d7b2e7f4040ac33c62
4,850
cpp
C++
source/video/sampler.cpp
synaodev/LeviathanRacket
c70dfddf0097c7f4e902ec5de46a6eabed5a4691
[ "MIT" ]
5
2020-03-25T14:46:23.000Z
2022-02-23T01:46:26.000Z
source/video/sampler.cpp
synaodev/LeviathanRacket
c70dfddf0097c7f4e902ec5de46a6eabed5a4691
[ "MIT" ]
1
2022-01-14T00:01:48.000Z
2022-01-14T00:01:48.000Z
source/video/sampler.cpp
synaodev/LeviathanRacket
c70dfddf0097c7f4e902ec5de46a6eabed5a4691
[ "MIT" ]
2
2020-03-25T14:46:24.000Z
2020-08-21T04:33:23.000Z
#include "./sampler.hpp" #include "./gl-check.hpp" #include "../utility/logger.hpp" namespace { constexpr sint_t kWorkingUnit = GL_TEXTURE4; constexpr sint_t kMipMapTexs = 4; constexpr sint_t kTotalTexs = 80; constexpr sint_t kDimensions = 256; constexpr sint_t kTotalAtlas = 5; } sint_t sampler_t::get_working_unit() { return kWorkingUnit; } sint_t sampler_t::get_maximum_textures() { return kTotalTexs; } sint_t sampler_t::get_maximum_atlases() { return kTotalAtlas; } bool sampler_t::has_immutable_option() { return opengl_version[0] == 4 and opengl_version[1] >= 2; } void sampler_data_t::destroy() { if (id != 0) { glCheck(glBindTexture(type, 0)); glCheck(glDeleteTextures(1, &id)); id = 0; type = 0; count = 0; } } sampler_data_t sampler_allocator_t::kNullHandle {}; bool sampler_allocator_t::create(pixel_format_t format) { const glm::ivec2 texture_dims { kDimensions, kDimensions }; this->format = format; auto& t = this->texture(texture_dims); auto& s = this->atlas(texture_dims); return true; } sampler_data_t& sampler_allocator_t::texture(const glm::ivec2& dimensions) { if (dimensions.x == kDimensions and dimensions.y == kDimensions) { if (textures.id == 0) { // Save previous unit and set to working unit sint_t previous = 0; glCheck(glGetIntegerv(GL_ACTIVE_TEXTURE, &previous)); glCheck(glActiveTexture(kWorkingUnit)); uint_t handle = 0; glCheck(glGenTextures(1, &handle)); glCheck(glBindTexture(GL_TEXTURE_2D_ARRAY, handle)); if (sampler_t::has_immutable_option()) { glCheck(glTexStorage3D( GL_TEXTURE_2D_ARRAY, kMipMapTexs, gfx_t::get_pixel_format_gl_enum(format), dimensions.x, dimensions.y, kTotalTexs )); } else { glCheck(glTexImage3D( GL_TEXTURE_2D_ARRAY, 0, gfx_t::get_pixel_format_gl_enum(format), dimensions.x, dimensions.y, kTotalTexs, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr )); } glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT)); glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT)); glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)); glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); if (sampler_t::has_immutable_option()) { glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)); } else { glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); } glCheck(glBindTexture(GL_TEXTURE_2D_ARRAY, 0)); // Restore previous unit glCheck(glActiveTexture(previous)); textures.id = handle; textures.type = GL_TEXTURE_2D_ARRAY; textures.count = 0; } return textures; } synao_log("Error! Texture size must be 256x256! This one is {}x{}!\n", dimensions.x, dimensions.y); return kNullHandle; } const sampler_data_t& sampler_allocator_t::texture() const { return textures; } sampler_data_t& sampler_allocator_t::atlas(const glm::ivec2& dimensions) { if (dimensions.x == kDimensions and dimensions.y == kDimensions) { if (atlases.id == 0) { // Save previous unit and set to working unit sint_t previous = 0; glCheck(glGetIntegerv(GL_ACTIVE_TEXTURE, &previous)); glCheck(glActiveTexture(kWorkingUnit)); uint_t handle = 0; glCheck(glGenTextures(1, &handle)); glCheck(glBindTexture(GL_TEXTURE_2D_ARRAY, handle)); if (sampler_t::has_immutable_option()) { glCheck(glTexStorage3D( GL_TEXTURE_2D_ARRAY, kMipMapTexs, gfx_t::get_pixel_format_gl_enum(format), dimensions.x, dimensions.y, kTotalAtlas )); } else { glCheck(glTexImage3D( GL_TEXTURE_2D_ARRAY, 0, gfx_t::get_pixel_format_gl_enum(format), dimensions.x, dimensions.y, kTotalAtlas, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr )); } glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_REPEAT)); glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_REPEAT)); glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)); glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); if (sampler_t::has_immutable_option()) { glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR)); } else { glCheck(glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); } glCheck(glBindTexture(GL_TEXTURE_2D_ARRAY, 0)); // Restore previous unit glCheck(glActiveTexture(previous)); atlases.id = handle; atlases.type = GL_TEXTURE_2D_ARRAY; atlases.count = 0; } return atlases; } synao_log("Error! Atlas size must be 256x256! This one is {}x{}!\n", dimensions.x, dimensions.y); return kNullHandle; } const sampler_data_t& sampler_allocator_t::atlas() const { return atlases; }
30.3125
100
0.738144
5f2c025588e266c2452f1bc787d861692e79a247
2,668
hpp
C++
lib/malloy/core/detail/controller_run_result.hpp
Tectu/malloy
066adfe3ac312ac4c0b4a745603faed650400f5a
[ "MIT" ]
22
2021-04-17T17:32:14.000Z
2022-03-29T09:42:03.000Z
lib/malloy/core/detail/controller_run_result.hpp
Tectu/malloy
066adfe3ac312ac4c0b4a745603faed650400f5a
[ "MIT" ]
98
2021-04-03T18:53:19.000Z
2022-02-06T10:49:30.000Z
lib/malloy/core/detail/controller_run_result.hpp
Tectu/malloy
066adfe3ac312ac4c0b4a745603faed650400f5a
[ "MIT" ]
3
2021-05-12T15:17:11.000Z
2021-12-28T03:15:46.000Z
#pragma once #include <boost/asio/executor_work_guard.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/use_future.hpp> #include <spdlog/logger.h> #include <memory> #include <thread> #include <stdexcept> namespace malloy::detail { /** * Controller configuration. */ struct controller_config { /** * The number of worked threads for the I/O context to use. */ std::size_t num_threads = 1; /** * The logger instance to use. */ std::shared_ptr<spdlog::logger> logger; void validate() { if (!logger) throw std::logic_error{"invalid config: logger is null"}; else if (num_threads == 0) throw std::logic_error{"invalid config: cannot have 0 threads"}; }; }; template<typename T> class controller_run_result { public: controller_run_result(const controller_config& cfg, T ctrl, std::unique_ptr<boost::asio::io_context> ioc) : m_io_ctx{std::move(ioc)}, m_workguard{m_io_ctx->get_executor()}, m_ctrl{std::move(ctrl)} { // Create the I/O context threads m_io_threads.reserve(cfg.num_threads - 1); for (std::size_t i = 0; i < cfg.num_threads; i++) { m_io_threads.emplace_back( [this] { m_io_ctx->run(); }); } // Log cfg.logger->debug("starting i/o context."); } ~controller_run_result() { // Stop the `io_context`. This will cause `run()` // to return immediately, eventually destroying the // `io_context` and all of the sockets in it. m_io_ctx->stop(); // Tell the workguard that we no longer need it's service m_workguard.reset(); for (auto& thread : m_io_threads) { thread.join(); }; } /** * @brief Block until all queued async actions completed */ void run() { m_workguard.reset(); m_io_ctx->run(); } private: using workguard_t = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>; std::unique_ptr<boost::asio::io_context> m_io_ctx; workguard_t m_workguard; std::vector<std::thread> m_io_threads; T m_ctrl; // This order matters, the T may destructor need access to something related to the io context }; } // namespace malloy::detail
28.084211
115
0.53973
5f2dc3edcc7d8f849aefa87bc990ccc20f81fcb7
1,259
cpp
C++
Tree/Binary_Tree/main.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Tree/Binary_Tree/main.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Tree/Binary_Tree/main.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
#include <iostream> #include "binary_tree.cpp" #include "traverse.cpp" using namespace std; int main() { // create a tree object binaryTree tree = binaryTree(); // insert 10, 20, 30, 40, 50, 60 cout << "\nAfter adding 10..."; tree.insert_element(10); tree.print_tree(); cout << "\nAfter adding 20..."; tree.insert_element(20); tree.print_tree(); cout << "\nAfter adding 30..."; tree.insert_element(30); tree.print_tree(); cout << "\nAfter adding 40..."; tree.insert_element(40); tree.print_tree(); cout << "\nAfter adding 50..."; tree.insert_element(50); tree.print_tree(); cout << "\nAfter adding 60..."; tree.insert_element(60); tree.print_tree(); // print inorder traversal of tree cout << "\nInorder traversal of tree::\n\t"; traverse_inorder(tree); // print preorder traversal of tree cout << "\nPreorder traversal of tree::\n\t"; traverse_preorder(tree); // print postrder traversal of tree cout << "\nPostorder traversal of tree::\n\t"; traverse_postorder(tree); // print level order traversal cout << "\nLevel Order traversal of tree::\n\t"; traverse_level(tree); cout << "\n"; return 0; }
20.639344
52
0.612391
5f2ff7f49f8e5b1f37b9117542c9bfe0af6fbc11
2,113
cpp
C++
src/apps/S3DAnalyzer/widgets/widthhintlabel.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
8
2017-04-16T16:38:15.000Z
2020-04-20T03:23:15.000Z
src/apps/S3DAnalyzer/widgets/widthhintlabel.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
40
2017-04-12T17:24:44.000Z
2017-12-21T18:41:23.000Z
src/apps/S3DAnalyzer/widgets/widthhintlabel.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
6
2017-07-13T21:51:09.000Z
2021-05-18T16:22:03.000Z
#include "widthhintlabel.h" #include <gsl/gsl_util> WidthHintLabel::WidthHintLabel(QWidget* parent) : QLabel(parent) { initPixmaps(); setAlignment(Qt::AlignCenter); setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); auto&& pixmap = m_pixmaps[static_cast<int>(State::Neutral)]; setMinimumSize(pixmap->width() + 5, pixmap->height() + 4); } void WidthHintLabel::setState(State state) { setPixmap(*gsl::at(m_pixmaps, static_cast<int>(state))); update(); } void WidthHintLabel::updateHint(float ratio) { // ok this is the worst // todo: think a bit more about this // it's way worse to have more than not enough range if (inRange(0.8f, 1.0f, ratio)) { setState(State::Neutral); } else if (inRange(0.7f, 0.8f, ratio)) { setState(State::ShouldWiden); } else if (inRange(1.0f, 1.05f, ratio)) { setState(State::ShouldNarrow); } else if (inRange(0.6f, 0.7f, ratio)) { setState(State::ShouldWidenMuch); } else if (inRange(1.05f, 1.1f, ratio)) { setState(State::ShouldNarrowMuch); } else if (ratio < 0.6f) { setState(State::ShouldWidenVeryMuch); } else if (ratio >= 1.1f) { setState(State::ShouldNarrowVeryMuch); } update(); } // todo, this should be outside bool WidthHintLabel::inRange(float min, float max, float value) { return min <= value && value < max; } void WidthHintLabel::initPixmaps() { initPixmap(State::ShouldNarrowVeryMuch, ":icons/in_arrows_red.png"); initPixmap(State::ShouldNarrowMuch, ":icons/in_arrows_orange.png"); initPixmap(State::ShouldNarrow, ":icons/in_arrows_green.png"); initPixmap(State::ShouldWidenVeryMuch, ":icons/out_arrows_red.png"); initPixmap(State::ShouldWidenMuch, ":icons/out_arrows_orange.png"); initPixmap(State::ShouldWiden, ":icons/out_arrows_green.png"); initPixmap(State::Neutral, ":icons/neutral_arrows.png"); setPixmap(*m_pixmaps[static_cast<int>(State::Neutral)]); } void WidthHintLabel::initPixmap(State state, const QString& filepath) { auto pixmap = std::make_unique<QPixmap>(filepath); gsl::at(m_pixmaps, static_cast<int>(state)) = std::move(pixmap); }
33.539683
73
0.708471
5f311ccb8f94cd59ff9a022f220547b79ca01ba1
1,134
cpp
C++
OpenGL_Planetarium/Cubemap.cpp
vmkarhula/Planetarium
f99acf1c98f2789a3eae70eba69d83ab4cba2a43
[ "MIT" ]
null
null
null
OpenGL_Planetarium/Cubemap.cpp
vmkarhula/Planetarium
f99acf1c98f2789a3eae70eba69d83ab4cba2a43
[ "MIT" ]
null
null
null
OpenGL_Planetarium/Cubemap.cpp
vmkarhula/Planetarium
f99acf1c98f2789a3eae70eba69d83ab4cba2a43
[ "MIT" ]
null
null
null
#include "Cubemap.h" #include <iostream> #include "stb/stb_image.h" Cubemap::Cubemap(std::vector<std::string> paths) { glGenTextures(1, &m_GLID); glBindTexture(GL_TEXTURE_CUBE_MAP, m_GLID); int width, height, nrChannels; for (unsigned int i = 0; i < paths.size(); i++) { unsigned char* data = stbi_load(paths[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cerr << "Cubemap failed to load texture at path:" << paths[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } Cubemap::~Cubemap() { glDeleteTextures(1, &m_GLID); }
23.142857
113
0.741623
5f3d6887aeba89c27f8cd0eaa2fe4b7d778f677d
1,206
cpp
C++
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
1
2021-05-19T23:02:04.000Z
2021-05-19T23:02:04.000Z
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "bistro/bistro/cron/CrontabItem.h" #include <memory> #include <stdexcept> #include <folly/dynamic.h> #include "bistro/bistro/cron/EpochCrontabItem.h" #include "bistro/bistro/cron/StandardCrontabItem.h" // Add stateful Cron support for more robustness, see README for a design. using namespace folly; using namespace std; namespace facebook { namespace bistro { unique_ptr<const CrontabItem> CrontabItem::fromDynamic( const dynamic& d, boost::local_time::time_zone_ptr tz) { if (!d.isObject()) { throw runtime_error("CrontabItem must be an object"); } if (d.find("epoch") != d.items().end()) { return unique_ptr<CrontabItem>(new detail_cron::EpochCrontabItem(d, tz)); } return unique_ptr<CrontabItem>(new detail_cron::StandardCrontabItem(d, tz)); } string CrontabItem::getPrintable() const { throw logic_error("getPrintable not implemented"); } }}
27.409091
79
0.733002
5f3f4dbdbd0d86200cf91e34683a668528a77d4a
2,744
cpp
C++
models/Point.cpp
1Lorde/crypto
6138472c1fba850158502312001eaf6584aa255c
[ "MIT" ]
null
null
null
models/Point.cpp
1Lorde/crypto
6138472c1fba850158502312001eaf6584aa255c
[ "MIT" ]
null
null
null
models/Point.cpp
1Lorde/crypto
6138472c1fba850158502312001eaf6584aa255c
[ "MIT" ]
null
null
null
// // created by Vlad Savchuk on 11/12/2020. // #include <cmath> #include <ModularArithmetic.h> #include <NoSpecifiedEllipticCurveException.h> #include "Point.h" Point::Point(long long x, long long y) { this->name = "P"; this->x = x; this->y = y; this->ellipticCurve = nullptr; } Point::Point(std::string name, long long x, long long y) { this->name = name; this->x = x; this->y = y; } Point::Point(std::string name, long long int x, long long int y, EllipticCurve *curve) { this->name = name; this->x = x; this->y = y; this->ellipticCurve = curve; } Point operator+(Point p, Point q) { long long Xp = p.x; long long Yp = p.y; long long Xq = q.x; long long Yq = q.y; long long A, modulo; if (p.ellipticCurve != nullptr){ A = p.ellipticCurve->getA(); modulo = p.ellipticCurve->getP(); } else if (q.ellipticCurve != nullptr){ A = q.ellipticCurve->getA(); modulo = q.ellipticCurve->getP(); } else{ throw NoSpecifiedEllipticCurveException(); } long long S, Xr, Yr; if (Xp != Xq) { //condition (Xp != Xq) --> R = -(P + Q). S = (Yp - Yq) * ModularArithmetic::findInverseElement(Xp - Xq, modulo); S = ModularArithmetic::unsignedMod(S, modulo); Xr = pow(S, 2) - Xp - Xq; Yr = -Yp + S * (Xp - Xr); } else { if (Yp == -Yq) { //Condition (Yp = Yq = 0) --> P + P = O. return Point("O", 0, 0); } else if (Yp == Yq != 0) { //condition (Yp = Yq != 0) --> R = -(P + P) = -2P = -2Q. S = (3 * pow(Xp, 2) + A) * ModularArithmetic::findInverseElement(2 * Yp, modulo); S = ModularArithmetic::unsignedMod(S, modulo); Xr = pow(S, 2) - 2 * Xp; Yr = -Yp + S * (Xp - Xr); } } Xr = ModularArithmetic::unsignedMod(Xr, modulo); Yr = ModularArithmetic::unsignedMod(Yr, modulo); return Point("R", Xr, Yr, p.ellipticCurve); } Point operator*(long long k, Point p) { if (k == 0){ return Point("O", 0, 0); }else if (k == 1){ return p; }else if (k % 2 == 1){ return p + (k-1) * p; }else { return (k/2) * (p+p); } } bool Point::isOnEllipticCurve(EllipticCurve curve) { long long leftSide = ModularArithmetic::unsignedMod(pow(y, 2), curve.getP()); long long rightSide = ModularArithmetic::unsignedMod(pow(x, 3) + curve.getA() * x + curve.getB(), curve.getP()); if (leftSide == rightSide){ return true; } return false; } std::ostream &operator<<(std::ostream &os, const Point &point) { os << point.name << " = (" << point.x << ", " << point.y << ")."; return os; }
26.901961
116
0.529883
5f3f6e57bd25a9f84975ffcae87ddcc1b522466e
757
hpp
C++
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
patrykkolodziej/Explit
155a35e4b8951764e6bedb8847d3196561a4255c
[ "MIT" ]
18
2019-05-09T10:24:53.000Z
2021-05-17T04:39:47.000Z
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
danielkrupinski/Expl
74124b67361cd29dd34389d692e43df86f83d072
[ "MIT" ]
6
2019-05-09T16:26:01.000Z
2019-05-14T11:30:18.000Z
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
patrykkolodziej/Explit
155a35e4b8951764e6bedb8847d3196561a4255c
[ "MIT" ]
8
2019-05-08T17:28:24.000Z
2021-03-25T09:52:44.000Z
#pragma once #include "i_global_vars.hpp" #include "../../misc/valve/client_class.hpp" #include "../../misc/valve/i_app_system.hpp" class i_base_client_dll { public: virtual int connect(createinterfacefn app_system_factory, i_global_vars_base *p_globals) = 0; virtual int disconnect(void) = 0; virtual int init(createinterfacefn app_system_factory, i_global_vars_base *p_globals) = 0; virtual void post_init() = 0; virtual void shutdown(void) = 0; virtual void level_init_pre_entity(char const* p_map_name) = 0; virtual void level_init_post_entity() = 0; virtual void level_shutdown(void) = 0; virtual client_class* get_all_classes(void) = 0; };
42.055556
107
0.667107
5f3f78d4cc8e7c4b773fff444541a7cc366b55de
441
cpp
C++
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#include "gmLogicCvBase.hpp" namespace gm { namespace Logic { namespace Cv { Base::Base(const QString& name) : Logic::Base("cv", name) { log_trace(Log::New); this->setRunnable(true); this->setUseTimer(true); } Base::~Base() { log_trace(Log::Del); } } } }
19.173913
69
0.394558
5f414de234732722d05c50fc338e610a8d84e190
2,363
hpp
C++
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
2
2016-08-06T06:21:02.000Z
2017-01-10T05:45:13.000Z
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
1
2017-04-15T20:54:59.000Z
2017-04-15T20:54:59.000Z
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
3
2016-07-30T06:19:55.000Z
2017-02-07T01:55:05.000Z
// UDP Client Server -- send/receive UDP packets // Copyright (C) 2013 Made to Order Software Corp. // // 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef UDP_CLIENT_SERVER_H #define UDP_CLIENT_SERVER_H #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdexcept> #include <errno.h> #include <stdio.h> namespace udp_client_server { class udp_client_server_runtime_error : public std::runtime_error { public: udp_client_server_runtime_error(const char *w) : std::runtime_error(w) {} }; class udp_client { public: udp_client(const std::string& addr, int port); ~udp_client(); int get_socket() const; int get_port() const; std::string get_addr() const; int send(const char *msg, size_t size); private: int f_socket; int f_port; std::string f_addr; struct addrinfo * f_addrinfo; }; class udp_server { public: udp_server(const std::string& addr, int port); ~udp_server(); int get_socket() const; int get_port() const; std::string get_addr() const; int recv(char *msg, size_t max_size); int timed_recv(char *msg, size_t max_size, int max_wait_ms); private: int f_socket; int f_port; std::string f_addr; struct addrinfo * f_addrinfo; }; } // namespace udp_client_server #endif // UDP_CLIENT_SERVER_H
29.5375
81
0.60474
5f46daa42fe39ef1fe8b159c68bb772198b6bd95
195
hpp
C++
src/components/resource/VkMeshRes.hpp
wicast/CreviceEngine
2d49b51aad7c2c6984bccc2c0628e75dfc0462a7
[ "MIT" ]
10
2021-01-19T04:36:11.000Z
2021-09-17T08:37:21.000Z
src/components/resource/VkMeshRes.hpp
wicast/CreviceEngine
2d49b51aad7c2c6984bccc2c0628e75dfc0462a7
[ "MIT" ]
null
null
null
src/components/resource/VkMeshRes.hpp
wicast/CreviceEngine
2d49b51aad7c2c6984bccc2c0628e75dfc0462a7
[ "MIT" ]
1
2022-02-08T04:21:28.000Z
2022-02-08T04:21:28.000Z
#pragma once #include "common/Resource.h" #include "graphic/vk_render/resource/VkMesh.hpp" #include "stl/CreviceSharedPtr.h" struct VkMeshRes { RID rid; crevice::SharedPtr<VkMesh> mesh; };
17.727273
48
0.748718
5f4b0db7e754be422bc7951f5cf621ed8fab7015
3,458
cpp
C++
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
16
2017-01-11T17:28:03.000Z
2021-09-27T16:12:01.000Z
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
null
null
null
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
4
2017-03-17T02:44:32.000Z
2021-01-22T07:57:34.000Z
/************************************************************************* * * Copyright (c) 2016 The Qt Company * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include <QtGui> #include <QtWidgets> #include "clock.h" Clock::Clock(QWidget *parent) : QWidget(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint) { QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, static_cast<void (Clock::*)()>(&Clock::update)); timer->start(1000); QAction *quitAction = new QAction(tr("E&xit"), this); quitAction->setShortcut(tr("Ctrl+Q")); connect(quitAction, &QAction::triggered, qApp, &QApplication::quit); addAction(quitAction); setAttribute(Qt::WA_TranslucentBackground); setContextMenuPolicy(Qt::ActionsContextMenu); setToolTip(tr("Drag the clock with the left mouse button.\n" "Use the right mouse button to open a context menu.")); setWindowTitle(tr("Analog Clock")); } void Clock::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { dragPosition = event->globalPos() - frameGeometry().topLeft(); event->accept(); } } void Clock::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { move(event->globalPos() - dragPosition); event->accept(); } } void Clock::paintEvent(QPaintEvent *) { static const QPoint hourHand[3] = { QPoint(7, 8), QPoint(-7, 8), QPoint(0, -40) }; static const QPoint minuteHand[3] = { QPoint(7, 8), QPoint(-7, 8), QPoint(0, -70) }; QColor hourColor(191, 0, 0); QColor minuteColor(0, 0, 191, 191); int side = qMin(width(), height()); QTime time = QTime::currentTime(); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.translate(width() / 2, height() / 2); QRadialGradient gradient(0.0, 0.0, side*0.5, 0.0, 0.0); gradient.setColorAt(0.0, QColor(255, 255, 255, 255)); gradient.setColorAt(0.1, QColor(255, 255, 255, 31)); gradient.setColorAt(0.7, QColor(255, 255, 255, 31)); gradient.setColorAt(0.8, QColor(0, 31, 0, 31)); gradient.setColorAt(0.9, QColor(255, 255, 255, 255)); gradient.setColorAt(1.0, QColor(255, 255, 255, 255)); painter.setPen(QColor(0, 0, 0, 32)); painter.setBrush(gradient); painter.drawEllipse(-side/2.0 + 1, -side/2.0 + 1, side - 2, side - 2); painter.scale(side / 200.0, side / 200.0); painter.setPen(Qt::NoPen); painter.setBrush(hourColor); painter.save(); painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))); painter.drawConvexPolygon(hourHand, 3); painter.restore(); painter.setPen(hourColor); for (int i = 0; i < 12; ++i) { painter.drawLine(88, 0, 96, 0); painter.rotate(30.0); } painter.setPen(Qt::NoPen); painter.setBrush(minuteColor); painter.save(); painter.rotate(6.0 * (time.minute() + time.second() / 60.0)); painter.drawConvexPolygon(minuteHand, 3); painter.restore(); painter.setPen(minuteColor); for (int j = 0; j < 60; ++j) { if ((j % 5) != 0) painter.drawLine(92, 0, 96, 0); painter.rotate(6.0); } } QSize Clock::sizeHint() const { return QSize(200, 200); }
27.664
91
0.588201
5f4d34bace6ee9cd7d0e379eafef77ab8e33cbb0
7,687
hh
C++
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
14
2020-07-31T09:35:23.000Z
2021-11-15T11:18:35.000Z
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "utils/assert.hh" #include "utils/scoped.hh" #include "ir/ops.hh" #include "utils/symbol.hh" #include "utils/ref.hh" #define DEFAULT_SIZE (42) namespace mach { struct target; } namespace types { enum class type { INT, STRING, VOID, INVALID }; enum class signedness { INVALID, SIGNED, UNSIGNED }; struct ty { virtual ~ty() = default; ty(mach::target &target) : target_(target) {} virtual std::string to_string() const = 0; // t can be assigned to this virtual bool assign_compat(const ty *t) const = 0; // this can be cast to t virtual bool cast_compat(const ty *) const { return false; } // return the resulting type if this BINOP t is correctly typed, // nullptr otherwise. // TODO: This is where implicit type conversions would be handled virtual utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const = 0; // return the resulting type if UNARYOP this is correctly typed, // nullptr otherwise. virtual utils::ref<ty> unaryop_type(ops::unaryop unaryop) const = 0; virtual ty *clone() const = 0; virtual bool size_modifier(size_t sz) { return sz == DEFAULT_SIZE; } virtual size_t size() const { UNREACHABLE("size() on type " + to_string() + " with no size"); } virtual signedness get_signedness() const { return signedness::INVALID; } virtual void set_signedness(types::signedness) { UNREACHABLE("Trying to set signedness on type {}", to_string()); } /* * Structs and arrays have a size which is different from the size * that the codegen uses to manipulate them: they're actually * pointers */ virtual size_t assem_size() const { return size(); } mach::target &target() { return target_; } protected: mach::target &target_; }; bool operator==(const ty *ty, const type &t); bool operator!=(const ty *ty, const type &t); struct builtin_ty : public ty { builtin_ty(mach::target &target); builtin_ty(type t, signedness is_signed, mach::target &target); builtin_ty(type t, size_t size, signedness is_signed, mach::target &target); std::string to_string() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual builtin_ty *clone() const override { return new builtin_ty(ty_, size_, size_modif_, is_signed_, target_); } size_t size() const override; bool size_modifier(size_t sz) override; type ty_; virtual signedness get_signedness() const override { return is_signed_; } virtual void set_signedness(types::signedness sign) override { is_signed_ = sign; } private: builtin_ty(type t, size_t size, size_t size_modif, signedness is_signed, mach::target &target); size_t size_; size_t size_modif_; signedness is_signed_; }; struct pointer_ty : public ty { private: pointer_ty(utils::ref<ty> ty, unsigned ptr); public: pointer_ty(utils::ref<ty> ty); std::string to_string() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual pointer_ty *clone() const override { return new pointer_ty(ty_, ptr_); } virtual signedness get_signedness() const override { return ty_->get_signedness(); } size_t size() const override; size_t pointed_size() const; utils::ref<ty> ty_; unsigned ptr_; }; bool is_scalar(const ty *ty); utils::ref<ty> deref_pointer_type(utils::ref<ty> ty); bool is_integer(const ty *ty); struct composite_ty : public ty { composite_ty(mach::target &target) : ty(target) {} }; struct array_ty : public composite_ty { array_ty(utils::ref<types::ty> type, size_t n); std::string to_string() const override; size_t size() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual array_ty *clone() const override { return new array_ty(ty_, n_); } virtual signedness get_signedness() const override { return signedness::UNSIGNED; } virtual size_t assem_size() const override { return 8; } utils::ref<types::ty> ty_; size_t n_; }; struct braceinit_ty : public composite_ty { braceinit_ty(const std::vector<utils::ref<types::ty>> &types); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual braceinit_ty *clone() const override { return new braceinit_ty(types_); } std::vector<utils::ref<types::ty>> types_; }; struct struct_ty : public composite_ty { struct_ty(const symbol &name, const std::vector<symbol> &names, const std::vector<utils::ref<types::ty>> &types); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual struct_ty *clone() const override { return new struct_ty(name_, names_, types_); } virtual size_t assem_size() const override { return 8; } std::optional<size_t> member_index(const symbol &name); size_t member_offset(const symbol &name); utils::ref<ty> member_ty(const symbol &name); size_t size() const override; virtual signedness get_signedness() const override { // structs behave as pointers return signedness::UNSIGNED; } std::vector<utils::ref<types::ty>> types_; symbol name_; std::vector<symbol> names_; private: size_t size_; }; struct fun_ty : public ty { fun_ty(utils::ref<types::ty> ret_ty, const std::vector<utils::ref<types::ty>> &arg_tys, bool variadic); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual fun_ty *clone() const override { return new fun_ty(ret_ty_, arg_tys_, variadic_); } virtual signedness get_signedness() const override { return signedness::INVALID; } virtual size_t assem_size() const override { return 8; } utils::ref<types::ty> ret_ty_; std::vector<utils::ref<types::ty>> arg_tys_; bool variadic_; }; /* * The parser outputs named_ty everywhere a type is used, and they are replaced * by pointers to actual types during semantic analysis. * This is necessary because of type declarations that the parser doesn't track. */ struct named_ty : public ty { named_ty(const symbol &name, mach::target &target, size_t sz = DEFAULT_SIZE); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual named_ty *clone() const override { return new named_ty(name_, target_, sz_); } size_t size() const override; symbol name_; private: int sz_; }; utils::ref<ty> concretize_type(utils::ref<ty> &t, utils::scoped_map<symbol, utils::ref<ty>> tmap); utils::ref<fun_ty> normalize_function_pointer(utils::ref<ty> ty); } // namespace types
24.877023
80
0.712372
5f4e977688d2c5ad1e3983e8f2baa255ffa0e0e3
1,208
cpp
C++
algorithm/OPG/test/OPGTest.cpp
Zx55/compiler-principle
31c4dda19fdd7e48bbd616e29cf6f8ea28ea1b5b
[ "MIT" ]
null
null
null
algorithm/OPG/test/OPGTest.cpp
Zx55/compiler-principle
31c4dda19fdd7e48bbd616e29cf6f8ea28ea1b5b
[ "MIT" ]
null
null
null
algorithm/OPG/test/OPGTest.cpp
Zx55/compiler-principle
31c4dda19fdd7e48bbd616e29cf6f8ea28ea1b5b
[ "MIT" ]
null
null
null
/* * LexParser.h * Test of OPG Parser. * Copyright (c) zx5. All rights reserved. */ #define CATCH_CONFIG_MAIN #include <iostream> #include <fstream> #include <sstream> #include <string> #include "../OPG.h" #include "../../../include/catch.hpp" using namespace std; using namespace Compiler; const string TEST_FILE_PATH = "compiler-principle/oj/OPG/test/o"; const int TEST_FILE_TOTAL = 2; string parse(int no) { auto inFile = ifstream(TEST_FILE_PATH + to_string(no) + "/in.txt"); int t; OPG grammar; string line; stringstream ss; inFile >> grammar; auto parser = Parser(grammar); for (inFile >> t, getline(inFile, line); t != 0; --t) { getline(inFile, line); if (parser.isValiad(line)) { ss << "T\n"; } else { ss << "F\n"; } } return ss.str(); } string ans(int no) { auto ansFile = ifstream(TEST_FILE_PATH + to_string(no) + "/ans.txt"); stringstream ss; string line; while (ansFile >> line) { ss << line << "\n"; } return ss.str(); } TEST_CASE("OPG Parser", "[opg]") { for (int i = 1; i <= TEST_FILE_TOTAL; ++i) { REQUIRE(parse(i) == ans(i)); } }
19.174603
73
0.575331
5f50400050ef6c699fba96e7dd2fb852bc2ea6b4
186
cpp
C++
Dataset/Leetcode/train/58/223.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/58/223.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/58/223.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(string s) { stringstream it(s); string tmp; while (it >> tmp) { } return tmp.size(); } };
14.307692
27
0.424731
5f519bc1c25c34290477e9ce07ed8842754151f5
10,370
cpp
C++
src/audio/CBasicSound.cpp
JackCarlson/Avara
2d79f6a21855759e427e13ee2d791257bc8c8c71
[ "MIT" ]
77
2016-10-30T18:37:14.000Z
2022-02-13T05:02:55.000Z
src/audio/CBasicSound.cpp
tra/Avara
5a6b5a4f2cf29e8b2ddf7dd3f422579f37a14dab
[ "MIT" ]
135
2018-09-09T06:46:04.000Z
2022-01-29T19:33:12.000Z
src/audio/CBasicSound.cpp
tra/Avara
5a6b5a4f2cf29e8b2ddf7dd3f422579f37a14dab
[ "MIT" ]
19
2018-09-09T02:02:46.000Z
2022-03-16T08:21:08.000Z
/* Copyright ©1994-1996, Juri Munkki All rights reserved. File: CBasicSound.c Created: Friday, December 23, 1994, 10:57 Modified: Tuesday, September 3, 1996, 21:27 */ #include "CBasicSound.h" #include "CSoundHub.h" #include "CSoundMixer.h" #include <assert.h> void CBasicSound::Release() { if (itsHub) { if (motionLink) itsHub->ReleaseLink(motionLink); if (controlLink) itsHub->ReleaseLink(controlLink); itsHub->Restock(this); } } void CBasicSound::SetLoopCount(short count) { loopCount[0] = loopCount[1] = count; } void CBasicSound::SetRate(Fixed theRate) { // Not applicable } Fixed CBasicSound::GetSampleRate() { return itsMixer->samplingRate; } void CBasicSound::SetSoundLength(Fixed seconds) { int numSamples; numSamples = FMul(seconds >> 8, GetSampleRate() >> 8); numSamples -= sampleLen; if (numSamples > 0 && loopEnd > loopStart) { loopCount[0] = numSamples / (loopEnd - loopStart); loopCount[1] = loopCount[0]; } else { loopCount[0] = 0; loopCount[1] = 0; } } void CBasicSound::Start() { itsMixer->AddSound(this); } void CBasicSound::SetVolume(Fixed vol) { masterVolume = vol; volumes[0] = masterVolume >> (17 - VOLUMEBITS); volumes[1] = volumes[0]; } void CBasicSound::SetDirectVolumes(Fixed vol0, Fixed vol1) { volumes[0] = vol0 >> (17 - VOLUMEBITS); volumes[1] = vol1 >> (17 - VOLUMEBITS); } void CBasicSound::StopSound() { stopNow = true; } void CBasicSound::CheckSoundLink() { SoundLink *aLink; Fixed *s, *d; Fixed timeConversion; Fixed t; aLink = motionLink; timeConversion = itsMixer->timeConversion; s = aLink->nSpeed; d = aLink->speed; *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); s = aLink->nLoc; d = aLink->loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = aLink->loc; t = aLink->t; *d++ -= *s++ * t; *d++ -= *s++ * t; *d++ -= *s++ * t; aLink->meta = metaNoData; } void CBasicSound::SetSoundLink(SoundLink *linkPtr) { if (linkPtr) linkPtr->refCount++; if (motionLink) itsHub->ReleaseLink(motionLink); motionLink = linkPtr; } void CBasicSound::SetControlLink(SoundLink *linkPtr) { if (linkPtr) linkPtr->refCount++; if (controlLink) itsHub->ReleaseLink(controlLink); controlLink = linkPtr; } void CBasicSound::Reset() { motionLink = NULL; controlLink = NULL; itsSamples = NULL; sampleLen = 0; sampleData = NULL; loopStart = 0; loopEnd = 0; loopCount[0] = loopCount[1] = 0; stopNow = false; volumeMax = VOLUMERANGE >> 1; distanceDelay = true; } void CBasicSound::UseSamplePtr(Sample *samples, int numSamples) { currentCount[0].i = 0; currentCount[0].f = 0; currentCount[1].i = 0; currentCount[1].f = 0; sampleLen = numSamples; sampleData = samples; loopStart = 0; loopEnd = 0; loopCount[0] = loopCount[1] = 0; // Don't loop. } void CBasicSound::UseSamples(SampleHeaderHandle theSample) { if (theSample) { itsSamples = theSample; UseSamplePtr(sizeof(SampleHeader) + (Sample *)*theSample, (*theSample)->len); loopStart = (*itsSamples)->loopStart; loopEnd = (*itsSamples)->loopEnd; loopCount[0] = loopCount[1] = (*itsSamples)->loopCount; } else { UseSamplePtr(NULL, 0); } } void CBasicSound::CalculatePosition(int t) { CSoundMixer *m; SoundLink *s; short i; m = itsMixer; s = motionLink; squareAcc[0] = squareAcc[1] = 0; for (i = 0; i < 3; i++) { relPos[i] = s->loc[i] - m->motion.loc[i] + (s->speed[i] - m->motion.speed[i]) * t; FSquareAccumulate(relPos[i], squareAcc); } if (0x007Fffff < (unsigned int)squareAcc[0]) dSquare = 0x7FFFffff; else dSquare = ((squareAcc[0] & 0x00FFFFFF) << 8) | ((squareAcc[1] & 0xFF000000) >> 24); } void CBasicSound::SanityCheck() { if (loopStart == loopEnd) { loopCount[0] = loopCount[1] = 0; } } void CBasicSound::FirstFrame() { SanityCheck(); if (motionLink && distanceDelay) { int delta; if (motionLink->meta == metaNewData) CheckSoundLink(); CalculatePosition(itsMixer->frameStartTime); delta = FMul(FSqroot(squareAcc), itsMixer->distanceToSamples); currentCount[0].i -= delta; currentCount[1].i -= delta; } } void CBasicSound::CalculateMotionVolume() { Fixed rightDot; CSoundMixer *m = itsMixer; Fixed adjustedVolume; if (motionLink->meta == metaNewData) CheckSoundLink(); CalculatePosition(m->frameStartTime); if (dSquare == 0) dSquare = m->distanceAdjust >> 2; adjustedVolume = FMulDivNZ(masterVolume, m->distanceAdjust, dSquare); if (adjustedVolume > m->maxAdjustedVolume) adjustedVolume = m->maxAdjustedVolume; if (m->stereo) { distance = FSqroot(squareAcc); if (distance > 0) { rightDot = FMul(relPos[0], m->rightVector[0]); rightDot += FMul(relPos[1], m->rightVector[1]); rightDot += FMul(relPos[2], m->rightVector[2]); rightDot = FDiv(rightDot, distance); } else { rightDot = 0; // Middle, if distance = 0 } if (m->strongStereo) { // "Hard" stereo effect for loudspeakers users. // Sound position LEFT MIDDLE RIGHT // Left channel 1.0 0.5 0.0 // Right channel 0.0 0.5 1.0 volumes[0] = FMul(FIX(1) - rightDot, adjustedVolume) >> (18 - VOLUMEBITS); volumes[1] = FMul(FIX(1) + rightDot, adjustedVolume) >> (18 - VOLUMEBITS); } else { // "Soft" stereo effect for headphones users. // Sound position LEFT MIDDLE RIGHT // Left channel 1.0 0.66 0.33 // Right channel 0.33 0.66 1.0 adjustedVolume /= 3; volumes[0] = FMul(FIX(2) - rightDot, adjustedVolume) >> (18 - VOLUMEBITS); volumes[1] = FMul(FIX(2) + rightDot, adjustedVolume) >> (18 - VOLUMEBITS); // With headphones, it is irritating, if one headphone is producing // sound (pressure) and the other one is not. For these cases, the // volume of the otherwise silent channel is set to 1 to avoid the problem. if (!volumes[0] ^ !volumes[1]) { if (!volumes[0]) volumes[0] = 1; if (!volumes[1]) volumes[1] = 1; } } balance = rightDot; } else { volumes[0] = adjustedVolume >> (17 - VOLUMEBITS); volumes[1] = volumes[0]; balance = 0; } if (volumes[0] > volumeMax) volumes[0] = volumeMax; if (volumes[1] > volumeMax) volumes[1] = volumeMax; } short CBasicSound::CalcVolume(short theChannel) { if (controlLink) { if (controlLink->meta == metaSuspend) return 0; else if (controlLink->meta == metaFade) { loopCount[0] = 0; loopCount[1] = 0; } } if (motionLink && motionLink->meta == metaFade) { loopCount[0] = 0; loopCount[1] = 0; } if (currentCount[0].i <= -itsMixer->soundBufferSize) { volumes[theChannel] = 0; } else if (motionLink && theChannel == 0) { CalculateMotionVolume(); } return volumes[theChannel]; } void CBasicSound::WriteFrame(short theChannel, short volumeAllowed) { Sample *s; WordSample *d; SampleConvert *converter; int thisCount; int remaining; int baseCount = currentCount[0].i; int loopCopy = loopCount[0]; converter = &itsMixer->volumeLookup[volumeAllowed - 1]; d = itsMixer->mixTo[theChannel]; if (baseCount >= 0) { thisCount = itsMixer->soundBufferSize; } else { d -= baseCount; thisCount = itsMixer->soundBufferSize + baseCount; baseCount = 0; } do { s = sampleData + baseCount; remaining = baseCount + thisCount - loopEnd; if (loopCopy && remaining > 0) { if (loopCopy > 0) // Negative loopCount will loop forever. loopCopy--; thisCount -= remaining; baseCount = loopStart; } else { remaining = 0; } if (thisCount + baseCount > sampleLen) { thisCount = sampleLen - baseCount; remaining = 0; } assert(0 && "port asm"); /* TODO: port asm { clr.w D0 move.l converter,A0 subq.w #1,thisCount bmi.s @nothing @loop move.b (s)+,D0 move.w 0(A0,D0.w*2),D1 add.w D1,(d)+ dbra thisCount,@loop @nothing } */ thisCount = remaining; } while (thisCount); } Boolean CBasicSound::EndFrame() { if (stopNow || (motionLink && motionLink->meta == metaKillNow) || (controlLink && controlLink->meta == metaKillNow)) { stopNow = true; } else { if (controlLink && controlLink->meta == metaSuspend) { return false; } if (loopCount[0]) { int thisCount = itsMixer->soundBufferSize; int remaining; do { if (loopCount[0]) { remaining = currentCount[0].i + thisCount - loopEnd; if (remaining > 0) { if (loopCount[0] > 0) // Negative loopCount will loop forever. loopCount[0]--; currentCount[0].i = loopStart; thisCount -= remaining; } else remaining = 0; } else remaining = 0; currentCount[0].i += thisCount; thisCount = remaining; } while (thisCount); } else { currentCount[0].i += itsMixer->soundBufferSize; } } if (loopCount[0] == 0 && currentCount[0].i >= sampleLen) stopNow = true; return stopNow; }
25.73201
91
0.548987
34fc3eca1e3505b2d07896cb4ecee2a367e95d62
5,408
cpp
C++
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
null
null
null
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
1
2017-04-22T21:38:20.000Z
2017-04-22T21:38:20.000Z
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
null
null
null
#include "config.hpp" #include <iostream> #include <stdexcept> #include <spdlog/spdlog.h> #include <glad/glad.h> #include "vfs.hpp" #include "shader.hpp" namespace ORCore { static std::shared_ptr<spdlog::logger> logger; static int _programCount = 0; Shader::Shader(ShaderInfo _info): info(_info) { logger = spdlog::get("default"); init_gl(); } void Shader::init_gl() { shader = glCreateShader(info.type); std::string data {read_file(info.path)}; const char *c_str = data.c_str(); glShaderSource(shader, 1, &c_str, nullptr); glCompileShader(shader); } Shader::~Shader() { glDeleteShader(shader); } void Shader::check_error() { GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); // TODO - probably need to make a custom exception class for this.. if (status != GL_TRUE) { GLint length; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); auto logData = std::make_unique<GLchar[]>(length+1); logData[length] = '\0'; // Make sure it is null terminated. glGetShaderInfoLog(shader, length, nullptr, logData.get()); logger->error(logData.get()); throw std::runtime_error("Shader compilation failed."); } else { logger->info("Shader compiled sucessfully."); } } ShaderProgram::ShaderProgram(Shader& vertex, Shader& fragment) : m_vertex(vertex), m_fragment(fragment) { logger = spdlog::get("default"); _programCount++; m_programID = _programCount; m_program = glCreateProgram(); glAttachShader(m_program, m_vertex.shader); glAttachShader(m_program, m_fragment.shader); glLinkProgram(m_program); } ShaderProgram::~ShaderProgram() { glDeleteProgram(m_program); } int ShaderProgram::get_id() { return m_programID; } void ShaderProgram::check_error() { // We want to check the compile/link status of the shaders all at once. // At some place that isn't right after the shader compilation step. // That way the drivers can better parallelize shader compilation. m_vertex.check_error(); m_fragment.check_error(); GLint status; glGetProgramiv(m_program, GL_LINK_STATUS, &status); // TODO - probably need to make a custom exception class for this.. if (status != GL_TRUE) { GLint length; glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &length); auto logData = std::make_unique<GLchar[]>(length+1); logData[length] = '\0'; // Make sure it is null terminated. glGetProgramInfoLog(m_program, length, nullptr, logData.get()); logger->error(logData.get()); throw std::runtime_error("Shader linkage failed."); } else { logger->info("Shader linked sucessfully."); } } void ShaderProgram::use() { glUseProgram(m_program); } void ShaderProgram::disuse() { glUseProgram(0); } int ShaderProgram::vertex_attribute(std::string name) { return glGetAttribLocation(m_program, name.c_str()); } int ShaderProgram::uniform_attribute(std::string name) { return glGetUniformLocation(m_program, name.c_str()); } void ShaderProgram::set_uniform(int uniform, int value) { glUniform1i(uniform, value); } void ShaderProgram::set_uniform(int uniform, float value) { glUniform1f(uniform, value); } void ShaderProgram::set_uniform(int uniform, const glm::vec2& value) { glUniform2fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::vec3& value) { glUniform3fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::vec4& value) { glUniform4fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat2& value) { glUniformMatrix2fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat3& value) { glUniformMatrix3fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat4& value) { glUniformMatrix4fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 2>& value) { glUniform2fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 3>& value) { glUniform3fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 4>& value) { glUniform4fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 2>& value) { glUniform2iv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 3>& value) { glUniform3iv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 4>& value) { glUniform4iv(uniform, 1, &value[0]); } } // namespace ORCore
25.271028
83
0.611686
34fd456783bdd58cf5a710c3a4f029c2aeba3313
321
hpp
C++
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
4
2015-06-14T13:38:40.000Z
2020-11-07T02:29:59.000Z
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
1
2015-06-19T07:54:53.000Z
2015-11-12T10:38:21.000Z
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
3
2015-06-15T02:28:39.000Z
2018-10-18T11:02:59.000Z
// Author: Jin Qing (http://blog.csdn.net/jq0123) #ifndef RPCZ_REQUEST_HANDLER_PTR_H #define RPCZ_REQUEST_HANDLER_PTR_H #include <boost/shared_ptr.hpp> namespace rpcz { class request_handler; typedef boost::shared_ptr<request_handler> request_handler_ptr; } // namespace rpcz #endif // RPCZ_REQUEST_HANDLER_PTR_H
20.0625
63
0.797508
34ff834048322fd5351a65e34660fef871d798db
719
cc
C++
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
#include "Common.hh" #include "static-data.hh" namespace emlsp::rpc::lsp::data { #if 0 std::string const initialization_message = R"({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "trace": "on", "locale": "en_US.UTF8", "clientInfo": { "name": ")" MAIN_PROJECT_NAME R"(", "version": ")" MAIN_PROJECT_VERSION_STRING R"(" }, "capabilities": { "textDocument.documentHighlight.dynamicRegistration": true } } })"s; #endif } // namespace emlsp::rpc::lsp::data namespace emlsp::test { NOINLINE void test01() { } } // namespace emlsp::test
20.542857
76
0.513213
5502c9b9825deb1d0594bfef07db2cc22ef09594
3,642
cpp
C++
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System // Name: OverflowException // C++ Typed Name: mscorlib::System::OverflowException #include <gtest/gtest.h> #include <mscorlib/System/mscorlib_System_OverflowException.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_MethodBase.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationInfo.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { //Constructors Tests //OverflowException() TEST(mscorlib_System_OverflowException_Fixture,DefaultConstructor) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //OverflowException(mscorlib::System::String message) TEST(mscorlib_System_OverflowException_Fixture,Constructor_2) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //OverflowException(mscorlib::System::String message, mscorlib::System::Exception innerException) TEST(mscorlib_System_OverflowException_Fixture,Constructor_3) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests //Public Properties Tests // Property InnerException // Return Type: mscorlib::System::Exception // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_InnerException_Test) { } // Property HelpLink // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_HelpLink_Test) { } // Property HelpLink // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_HelpLink_Test) { } // Property HResult // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_HResult_Test) { } // Property HResult // Return Type: mscorlib::System::Int32 // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_HResult_Test) { } // Property Message // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Message_Test) { } // Property Source // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Source_Test) { } // Property Source // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_Source_Test) { } // Property StackTrace // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_StackTrace_Test) { } // Property TargetSite // Return Type: mscorlib::System::Reflection::MethodBase // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_TargetSite_Test) { } // Property Data // Return Type: mscorlib::System::Collections::IDictionary // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Data_Test) { } } }
22.7625
106
0.731466
5504cb8775368b3998df85f1df1ca63775176fd7
223
hh
C++
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
1
2020-01-06T09:43:56.000Z
2020-01-06T09:43:56.000Z
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
#pragma once #include "Statement.hh" // @TODO: Derive from something else class Decl : public Statement { MAKE_NONMOVABLE(Decl) MAKE_NONCOPYABLE(Decl) AST_NODE_NAME(Decl) protected: Decl() = default; };
18.583333
36
0.695067
550727d7b0ea51da785f910de3f02bb59e994fbc
746
hpp
C++
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
1
2021-02-19T13:02:23.000Z
2021-02-19T13:02:23.000Z
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
16
2021-02-11T04:23:48.000Z
2021-02-19T05:37:30.000Z
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../__common.hpp" namespace vs { namespace util { template<typename type> void print_arg(const type& arg) { std::cout << arg; } template<> void print_arg(const bool& arg) { std::cout << termcolor::bold << termcolor::yellow << (arg ? "true" : "false") << termcolor::reset; } template<> void print_arg(const std::string& arg) { std::cout << termcolor::magenta << "\"" << arg << "\"" << termcolor::reset; } void print_args() { } template<typename type, typename... types> void print_args(type&& arg, types&&... args) { print_arg(std::forward<type>(arg)); if constexpr (sizeof...(types)) std::cout << ", "; print_args(std::forward<types>(args)...); } } // namespace util } // namespace vs
21.941176
79
0.621984
550915e6b36470976148ac116d6c97b7a88ddbe9
1,464
hpp
C++
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2021-06-03T15:56:32.000Z
2021-06-03T15:56:32.000Z
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2015-08-05T05:51:49.000Z
2015-08-05T05:51:49.000Z
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
null
null
null
#if !defined(SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__) #define SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__ #include "parser/tokens/TokenAbstract.hpp" #include "parser/tokens/Operators.hpp" #include "parser/tokens/TokenRegex.hpp" #include "parser/tokens/TokenNameAddr.hpp" #include "parser/tokens/TokenGenericParam.hpp" #include "parser/tokens/messageheaders/TokenSIPMessageHeader_base.hpp" namespace sip0x { namespace parser { // From = ( "From" / "f" ) HCOLON from-spec // from-spec = ( name-addr / addr-spec ) *( SEMI from-param ) // from-param = tag-param / generic-param // tag-param = "tag" EQUAL token class TokenSIPMessageHeader_From : public TokenSIPMessageHeader_base < Sequence<Alternative<TokenNameAddr, TokenAddrSpec>, Occurrence<Sequence<TokenSEMI, TokenGenericParam>>> > { public: TokenSIPMessageHeader_From() : TokenSIPMessageHeader_base("From", "(From)|(f)", Sequence<Alternative<TokenNameAddr, TokenAddrSpec>, Occurrence<Sequence<TokenSEMI, TokenGenericParam>>> ( Alternative<TokenNameAddr, TokenAddrSpec>( TokenNameAddr(), TokenAddrSpec() ), Occurrence<Sequence<TokenSEMI, TokenGenericParam>> ( Sequence<TokenSEMI, TokenGenericParam>(TokenSEMI(), TokenGenericParam()), 0, -1) ) ) { } }; } } #endif // SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__
34.857143
182
0.686475
55093c0a05392e2151d3204f2e5fe7810db874f7
1,298
cpp
C++
rasprobotd/src/main.cpp
sea-kg/php-rasp-robot
c404a46c48db6e5865a47fbcd0f02d8869cc71a5
[ "MIT" ]
null
null
null
rasprobotd/src/main.cpp
sea-kg/php-rasp-robot
c404a46c48db6e5865a47fbcd0f02d8869cc71a5
[ "MIT" ]
null
null
null
rasprobotd/src/main.cpp
sea-kg/php-rasp-robot
c404a46c48db6e5865a47fbcd0f02d8869cc71a5
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <iostream> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <syslog.h> #include <QtCore> #include <QFile> #include <QString> #include "websocketserver.h" int main(int argc, char** argv) { QCoreApplication app(argc, argv); QCoreApplication a(argc, argv); QCommandLineParser parser; parser.setApplicationDescription("Rasp Robot Daemon"); parser.addHelpOption(); QCommandLineOption dbgOption(QStringList() << "d" << "debug", QCoreApplication::translate("main", "Debug output [default: off].")); parser.addOption(dbgOption); QCommandLineOption portOption(QStringList() << "p" << "port", QCoreApplication::translate("main", "Port for Rasp Robot Daemon ws [default: 1234]."), QCoreApplication::translate("main", "port"), QLatin1Literal("1234")); parser.addOption(portOption); parser.process(a); bool debug = parser.isSet(dbgOption); int port = parser.value(portOption).toInt(); WebSocketServer *server = new WebSocketServer(port, debug); QObject::connect(server, &WebSocketServer::closed, &a, &QCoreApplication::quit); return app.exec(); }
30.186047
135
0.690293
55096fa25ddc42207a712250b4c5fd9d67d95038
773
cpp
C++
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <iostream> using namespace std; int a[10], used[22][22][22]; void solve() { for (int i = 1; i <= 3; i++) { scanf("%d", &a[i]); } sort(a + 1, a + 4); memset(used, 0, sizeof(used)); for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { for (int k = 1; k <= 3; k++) { if (i != j && j != k && i != k) { if (!used[a[i]][a[j]][a[k]]) { printf("%d %d %d\n", a[i], a[j], a[k]); used[a[i]][a[j]][a[k]] = 1; } } } } } } int main() { int tests; scanf("%d", &tests); for (int i = 1; i <= tests; i++) { printf("Case #%d:\n", i); solve(); } }
22.735294
63
0.315653
550aa8d1a5439a4dfa72d97d3345ac219f405660
3,494
cpp
C++
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include <glad.h> #include <glfw3.h> #include "game.h" #include "resourceManager.h" #include <iostream> // GLFW function declerations void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // The Width of the screen const unsigned int SCREEN_WIDTH = 1080; // The height of the screen const unsigned int SCREEN_HEIGHT = 720; Game game(SCREEN_WIDTH, SCREEN_HEIGHT); int main(int argc, char* argv[]) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif glfwWindowHint(GLFW_RESIZABLE, false); GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Engine", nullptr, nullptr); glfwMakeContextCurrent(window); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // OpenGL configuration // -------------------- glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize game // --------------- game.Init(); // deltaTime variables // ------------------- float deltaTime = 0.0f; float lastFrame = 0.0f; // start game within menu state // ---------------------------- game.State = GAME_MENU; while (!glfwWindowShouldClose(window)) { // calculate delta time // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // manage user input // ----------------- game.ProcessInput(); // update game state // ----------------- game.Update(deltaTime); // render // ------ glClearColor(0.0f, 0.0f, 0.4f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); game.Render(); glfwSwapBuffers(window); } // delete all resources as loaded using the resource manager // --------------------------------------------------------- ResourceManager::Clear(); glfwTerminate(); return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // when a user presses the escape key, we set the WindowShouldClose property to true, closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) game.Keys[key] = true; else if (action == GLFW_RELEASE) game.Keys[key] = false; } } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); }
27.952
110
0.653692
550d4bfc530fd0ba42f49bed4131585a505fe65e
18,389
cc
C++
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
83
2019-12-03T08:42:15.000Z
2022-03-30T13:22:37.000Z
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
1
2021-08-06T10:40:57.000Z
2021-08-09T06:33:43.000Z
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
45
2020-05-29T03:22:48.000Z
2022-03-21T16:19:01.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any_test.proto #include "google/protobuf/any_test.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto; namespace protobuf_unittest { class TestAnyDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TestAny> _instance; } _TestAny_default_instance_; } // namespace protobuf_unittest static void InitDefaultsscc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::protobuf_unittest::_TestAny_default_instance_; new (ptr) ::protobuf_unittest::TestAny(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::protobuf_unittest::TestAny::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto}, { &scc_info_Any_google_2fprotobuf_2fany_2eproto.base,}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fany_5ftest_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_5ftest_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_5ftest_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fany_5ftest_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, int32_value_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, any_value_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, repeated_any_value_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::protobuf_unittest::TestAny)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::protobuf_unittest::_TestAny_default_instance_), }; const char descriptor_table_protodef_google_2fprotobuf_2fany_5ftest_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\036google/protobuf/any_test.proto\022\021protob" "uf_unittest\032\031google/protobuf/any.proto\"y" "\n\007TestAny\022\023\n\013int32_value\030\001 \001(\005\022\'\n\tany_va" "lue\030\002 \001(\0132\024.google.protobuf.Any\0220\n\022repea" "ted_any_value\030\003 \003(\0132\024.google.protobuf.An" "yb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_deps[1] = { &::descriptor_table_google_2fprotobuf_2fany_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_sccs[1] = { &scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_once; static bool descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_initialized = false; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto = { &descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fany_5ftest_2eproto, "google/protobuf/any_test.proto", 209, &descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_once, descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_sccs, descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_deps, 1, 1, schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_5ftest_2eproto::offsets, file_level_metadata_google_2fprotobuf_2fany_5ftest_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_5ftest_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_5ftest_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_google_2fprotobuf_2fany_5ftest_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto), true); namespace protobuf_unittest { // =================================================================== void TestAny::InitAsDefaultInstance() { ::protobuf_unittest::_TestAny_default_instance_._instance.get_mutable()->any_value_ = const_cast< PROTOBUF_NAMESPACE_ID::Any*>( PROTOBUF_NAMESPACE_ID::Any::internal_default_instance()); } class TestAny::_Internal { public: static const PROTOBUF_NAMESPACE_ID::Any& any_value(const TestAny* msg); }; const PROTOBUF_NAMESPACE_ID::Any& TestAny::_Internal::any_value(const TestAny* msg) { return *msg->any_value_; } void TestAny::clear_any_value() { if (GetArenaNoVirtual() == nullptr && any_value_ != nullptr) { delete any_value_; } any_value_ = nullptr; } void TestAny::clear_repeated_any_value() { repeated_any_value_.Clear(); } TestAny::TestAny() : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:protobuf_unittest.TestAny) } TestAny::TestAny(const TestAny& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), repeated_any_value_(from.repeated_any_value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_any_value()) { any_value_ = new PROTOBUF_NAMESPACE_ID::Any(*from.any_value_); } else { any_value_ = nullptr; } int32_value_ = from.int32_value_; // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestAny) } void TestAny::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base); ::memset(&any_value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&int32_value_) - reinterpret_cast<char*>(&any_value_)) + sizeof(int32_value_)); } TestAny::~TestAny() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestAny) SharedDtor(); } void TestAny::SharedDtor() { if (this != internal_default_instance()) delete any_value_; } void TestAny::SetCachedSize(int size) const { _cached_size_.Set(size); } const TestAny& TestAny::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base); return *internal_default_instance(); } void TestAny::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; repeated_any_value_.Clear(); if (GetArenaNoVirtual() == nullptr && any_value_ != nullptr) { delete any_value_; } any_value_ = nullptr; int32_value_ = 0; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* TestAny::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // int32 int32_value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { int32_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // .google.protobuf.Any any_value = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(mutable_any_value(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .google.protobuf.Any repeated_any_value = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(add_repeated_any_value(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 26); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool TestAny::MergePartialFromCodedStream( ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:protobuf_unittest.TestAny) for (;;) { ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 int32_value = 1; case 1: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &int32_value_))); } else { goto handle_unusual; } break; } // .google.protobuf.Any any_value = 2; case 2: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_any_value())); } else { goto handle_unusual; } break; } // repeated .google.protobuf.Any repeated_any_value = 3; case 3: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_repeated_any_value())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:protobuf_unittest.TestAny) return true; failure: // @@protoc_insertion_point(parse_failure:protobuf_unittest.TestAny) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void TestAny::SerializeWithCachedSizes( ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 int32_value = 1; if (this->int32_value() != 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->int32_value(), output); } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, _Internal::any_value(this), output); } // repeated .google.protobuf.Any repeated_any_value = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->repeated_any_value_size()); i < n; i++) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->repeated_any_value(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:protobuf_unittest.TestAny) } ::PROTOBUF_NAMESPACE_ID::uint8* TestAny::InternalSerializeWithCachedSizesToArray( ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 int32_value = 1; if (this->int32_value() != 0) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->int32_value(), target); } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( 2, _Internal::any_value(this), target); } // repeated .google.protobuf.Any repeated_any_value = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->repeated_any_value_size()); i < n; i++) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->repeated_any_value(static_cast<int>(i)), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestAny) return target; } size_t TestAny::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestAny) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.protobuf.Any repeated_any_value = 3; { unsigned int count = static_cast<unsigned int>(this->repeated_any_value_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->repeated_any_value(static_cast<int>(i))); } } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *any_value_); } // int32 int32_value = 1; if (this->int32_value() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->int32_value()); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TestAny::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestAny) GOOGLE_DCHECK_NE(&from, this); const TestAny* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TestAny>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestAny) MergeFrom(*source); } } void TestAny::MergeFrom(const TestAny& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestAny) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; repeated_any_value_.MergeFrom(from.repeated_any_value_); if (from.has_any_value()) { mutable_any_value()->PROTOBUF_NAMESPACE_ID::Any::MergeFrom(from.any_value()); } if (from.int32_value() != 0) { set_int32_value(from.int32_value()); } } void TestAny::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestAny) if (&from == this) return; Clear(); MergeFrom(from); } void TestAny::CopyFrom(const TestAny& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestAny) if (&from == this) return; Clear(); MergeFrom(from); } bool TestAny::IsInitialized() const { return true; } void TestAny::InternalSwap(TestAny* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&repeated_any_value_)->InternalSwap(CastToBase(&other->repeated_any_value_)); swap(any_value_, other->any_value_); swap(int32_value_, other->int32_value_); } ::PROTOBUF_NAMESPACE_ID::Metadata TestAny::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestAny* Arena::CreateMaybeMessage< ::protobuf_unittest::TestAny >(Arena* arena) { return Arena::CreateInternal< ::protobuf_unittest::TestAny >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
38.795359
203
0.73805
550de8d47b5f9f69b204979617fe7276bf2d5fba
11,501
cpp
C++
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
1
2020-04-29T07:29:27.000Z
2020-04-29T07:29:27.000Z
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
null
null
null
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
null
null
null
#include "node.hpp" #include "peer_conn.hpp" #include "endpoint.hpp" #include "../lib/net_handler.hpp" #include "../lib/net_client.hpp" #include <cassert> #include <iostream> using namespace sample; using namespace std; NodeApp::PeerCandidateInfo::PeerCandidateInfo(std::string host_in, int port_in, int toTry_in) : myHost(host_in), myPort(port_in), myToTry(toTry_in), myConnTryCount(0), myConnectedCount(0) { } void NodeApp::PeerInfo::setClient(std::shared_ptr<NetClientBase>& client_in) { myClient = client_in; } void NodeApp::PeerInfo::resetClient() { myClient = nullptr; } NodeApp::NodeApp() : ServerApp() { myNetHandler = new NetHandler(this); } void NodeApp::start(AppParams const & appParams_in) { // add constant peer candidates, for localhost int n = 2; for (int i = 0; i < n; ++i) { addOutPeerCandidate("localhost", 5000 + i, 1); } // add extra peer candidates if (appParams_in.extraPeers.size() > 0) { for(int i = 0; i < appParams_in.extraPeers.size(); ++i) { if (appParams_in.extraPeers[i].length() > 0) { Endpoint extraPeerEp(appParams_in.extraPeers[i]); addOutPeerCandidate(extraPeerEp.getHost(), extraPeerEp.getPort(), 1000000); } } } myNetHandler->startWithListen(appParams_in.listenPort, appParams_in.listenPortRange); } void NodeApp::listenStarted(int port) { cout << "App: Listening on port " << port << endl; myName = ":" + to_string(port); // try to connect to clients tryOutConnections(); } void NodeApp::addOutPeerCandidate(std::string host_in, int port_in, int toTry_in) { PeerCandidateInfo pc = PeerCandidateInfo(host_in, port_in, toTry_in); string key = host_in + ":" + to_string(port_in); if (myPeerCands.find(key) != myPeerCands.end()) { // already present myPeerCands[key].myToTry = toTry_in + myPeerCands[key].myConnTryCount; return; } myPeerCands[key] = pc; cout << "App: Added peer candidate " << key << " " << myPeerCands.size() << endl; //debugPrintPeerCands(); } void NodeApp::debugPrintPeerCands() { cout << "PeerCands: " << myPeerCands.size() << " "; for (auto i = myPeerCands.begin(); i != myPeerCands.end(); ++i) { cout << "[" << i->first << " " << i->second.myToTry << " " << i->second.myConnTryCount << ":" << i->second.myConnectedCount << "] "; } cout << endl; } void NodeApp::debugPrintPeers() { cout << "Peers: " << myPeers.size() << " "; for (auto i = myPeers.begin(); i != myPeers.end(); ++i) { cout << "["; if (i->myClient == nullptr) cout << "n"; else cout << i->myClient->getPeerAddr() << " " << i->myClient->getCanonPeerAddr() << " " << (i->myClient->isConnected() ? "Y" : "N") << "] "; } cout << endl; } void NodeApp::tryOutConnections() { //cout << "NodeApp::tryOutConnections" << endl; // try to connect to clients for (auto i = myPeerCands.begin(); i != myPeerCands.end(); ++i) { //cout << i->second.myOutFlag << " " << i->second.myStickyFlag << " " << i->second.myConnTryCount << " " << (i->second.myOutClient == nullptr) << " " << i->second.myEndpoint.getEndpoint() << endl; if (i->second.myConnTryCount == 0 || i->second.myConnTryCount < i->second.myToTry) { if (!isPeerConnected(i->first, true)) { // try outgoing connection ++i->second.myConnTryCount; int res = tryOutConnection(i->second.myHost, i->second.myPort); if (!res) { // success ++i->second.myConnectedCount; } } } } } bool NodeApp::isPeerConnected(string peerAddr_in, bool outDir_in) { for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myOutFlag == outDir_in) { if (i->myClient != nullptr) { if (i->myClient->getPeerAddr() == peerAddr_in || i->myClient->getCanonPeerAddr() == peerAddr_in) { return true; } } } } return false; } int NodeApp::tryOutConnection(std::string host_in, int port_in) { // exclude localhost connections to self if ((":" + to_string(port_in)) == myName) { if (host_in == "localhost" || host_in == "127.0.0.1" || host_in == "::1" || host_in == "[::1]") { //cerr << "Ignoring peer candidate to self (" << host_in << ":" << port_in << ")" << endl; return 0; } } // try outgoing connection Endpoint ep = Endpoint(host_in, port_in); string key = ep.getEndpoint(); //cout << "Trying outgoing conn to " << key << endl; auto peerout = make_shared<PeerClientOut>(this, host_in, port_in); auto peerBase = dynamic_pointer_cast<NetClientBase>(peerout); PeerInfo p; p.setClient(peerBase); p.myOutFlag = true; myPeers.push_back(p); int res = peerout->connect(); if (res) { cerr << "Error from peer connect, " << res << endl; return res; } //debugPrintPeers(); return 0; } void NodeApp::stop() { myNetHandler->stop(); } void NodeApp::inConnectionReceived(std::shared_ptr<NetClientBase>& client_in) { assert(client_in != nullptr); string cliaddr = client_in->getPeerAddr(); cout << "App: New incoming connection: " << cliaddr << endl; PeerInfo p; p.setClient(client_in); p.myOutFlag = false; myPeers.push_back(p); //debugPrintPeers(); } void NodeApp::connectionClosed(NetClientBase* client_in) { assert(client_in != nullptr); string cliaddr = client_in->getPeerAddr(); cout << "App: Connection done: " << cliaddr << " " << myPeers.size() << endl; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient != nullptr) { if (i->myClient.get() == client_in || i->myClient->getPeerAddr() == cliaddr) { cout << "Removing disconnected client " << myPeers.size() << " " << i->myClient->getPeerAddr() << endl; i->resetClient(); } } } // remove disconnected clients bool changed = true; while (changed) { changed = false; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient.get() == nullptr) { myPeers.erase(i); changed = true; break; // for } } } } void NodeApp::messageReceived(NetClientBase & client_in, BaseMessage const & msg_in) { if (msg_in.getType() != MessageType::OtherPeer) { cout << "App: Received: from " << client_in.getNicePeerAddr() << " '" << msg_in.toString() << "'" << endl; } switch (msg_in.getType()) { case MessageType::Handshake: { HandshakeMessage const & hsMsg = dynamic_cast<HandshakeMessage const &>(msg_in); //cout << "Handshake message received, '" << hsMsg.getMyAddr() << "'" << endl; if (hsMsg.getMyVersion() != "V01") { cerr << "Wrong version ''" << hsMsg.getMyVersion() << "'" << endl; client_in.close(); return; } string peerEp = client_in.getPeerAddr(); if (!isPeerConnected(peerEp, false)) { cerr << "Error: cannot find client in peers list " << peerEp << endl; return; } HandshakeResponseMessage resp("V01", myName, peerEp); client_in.sendMessage(resp); // find canonical name of this peer: host is actual connected ip, port is reported by peer int peerPort = Endpoint(peerEp).getPort(); string canonHost = Endpoint(peerEp).getHost(); int canonPort = peerPort; string reportedPeerName = hsMsg.getMyAddr(); if (reportedPeerName.substr(0, 1) != ":") { cerr << "Could not retrieve listening port of incoming peer " << client_in.getPeerAddr() << " " << reportedPeerName << endl; } else { canonPort = stoi(reportedPeerName.substr(1)); string canonEp = canonHost + ":" + to_string(canonPort); if (canonEp != peerEp) { // canonical is different cout << "Canonical peer of " << peerEp << " is " << canonEp << endl; client_in.setCanonPeerAddr(canonEp); // try to connect ougoing too (to canonical peer addr) addOutPeerCandidate(canonHost, canonPort, 1); tryOutConnections(); } } sendOtherPeers(client_in); } break; case MessageType::Ping: { PingMessage const & pingMsg = dynamic_cast<PingMessage const &>(msg_in); //cout << "Ping message received, '" << pingMsg.getText() << "'" << endl; PingResponseMessage resp("Resp_from_" + myName + "_to_" + pingMsg.getText()); client_in.sendMessage(resp); } break; case MessageType::OtherPeer: { OtherPeerMessage const & peerMsg = dynamic_cast<OtherPeerMessage const &>(msg_in); //cout << "OtherPeer message received, " << peerMsg.getHost() << ":" << peerMsg.getPort() << " " << peerMsg.toString() << endl; addOutPeerCandidate(peerMsg.getHost(), peerMsg.getPort(), 1); tryOutConnections(); } break; case MessageType::HandshakeResponse: case MessageType::PingResponse: // OK, noop break; default: assert(false); } } void NodeApp::sendOtherPeers(NetClientBase & client_in) { // send current outgoing connection addresses auto peers = getConnectedPeers(); //cout << "NodeApp::sendOtherPeers " << peers.size() << " " << client_in.getPeerAddr() << endl; for(auto i = peers.begin(); i != peers.end(); ++i) { if (!client_in.isConnected()) { return; } string ep = i->getEndpoint(); //cout << ep << " " << client_in.getPeerAddr() << endl; if (ep != client_in.getPeerAddr()) { //cout << "sendOtherPeers " << client_in.getPeerAddr() << " " << i->getEndpoint() << endl; client_in.sendMessage(OtherPeerMessage(i->getHost(), i->getPort())); } } } vector<Endpoint> NodeApp::getConnectedPeers() const { // collect in a map to discard duplicates map<string, int> peers; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient != nullptr && i->myClient->isConnected() && i->myClient->getCanonPeerAddr().length() > 0) { peers[i->myClient->getCanonPeerAddr()] = 1; } } // convert to vector vector<Endpoint> vec; for(auto i = peers.begin(); i != peers.end(); ++i) { vec.push_back(Endpoint(i->first)); } return vec; }
31.683196
204
0.536388
550ed484a943b7c9c3414be1c5063ee32f77b838
965
cpp
C++
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
//递归解法: class Solution { public: void prebintree(TreeNode * root,vector<int> &res){//记得传地址而不是传值&res if(root == nullptr) { return; } res.push_back(root->val); prebintree(root->left,res); prebintree(root->right,res); return; } vector<int> preorderTraversal(TreeNode* root) { vector <int> res; prebintree(root,res); return res; } }; //iter solution class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if(root == nullptr) return {}; vector <int> res; stack <TreeNode*> stk; stk.emplace(root); while(!stk.empty()){ TreeNode* node = stk.top(); res.emplace_back(node->val); stk.pop(); if(node->right != nullptr) stk.emplace(node->right); if(node->left != nullptr) stk.emplace(node->left); } return res; } }; //Morris 遍历
22.44186
70
0.533679
55131cf89a253821832354b7d53c2f3b0a84d1ea
436
cpp
C++
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
null
null
null
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
47
2019-12-30T22:14:04.000Z
2022-03-26T02:04:06.000Z
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
null
null
null
#include "channel/BufferWrapper.hpp" using elrond::channel::BufferWrapper; /* **************************************************************************** ************** elrond::channel::BufferWrapper Implementation *************** ****************************************************************************/ BufferWrapper::BufferWrapper(elrond::byte* const data, const elrond::sizeT length): data(data), length(length) {}
39.636364
83
0.431193
55138f897795896970b5bc19224bd50389607a67
5,112
hpp
C++
Support/Modules/GSRoot/ThreadMonitor.hpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Modules/GSRoot/ThreadMonitor.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Modules/GSRoot/ThreadMonitor.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
// ***************************************************************************** // // Declaration of ThreadMonitor class // // Module: GSRoot // Namespace: GS // Contact person: SN // // ***************************************************************************** #ifndef GS_THREADMONITOR_HPP #define GS_THREADMONITOR_HPP #pragma once // --- Includes ---------------------------------------------------------------- #include "ThreadMonitorImpl.hpp" #include "Timeout.hpp" // --- ThreadMonitor class ----------------------------------------------------- namespace GS { class ThreadMonitor { // Data members: private: ThreadMonitorImpl* m_impl; // The underlying implementation of the thread monitor // Construction / destruction: public: explicit ThreadMonitor (ThreadMonitorImpl* impl); private: ThreadMonitor (const ThreadMonitor&); // Disabled public: ~ThreadMonitor (); // Operator overloading: private: const ThreadMonitor& operator = (const ThreadMonitor&); // Disabled // Operations: public: void Acquire (); bool TryAcquire (); void Release (); ThreadMonitorState Wait (UInt32 timeout, bool interruptible); ThreadMonitorState Wait (bool interruptible); bool Notify (); bool IsInterrupted () const; bool Interrupted (); void Interrupt (); bool IsCanceled () const; bool Canceled (); void Cancel (); void BlockOn (Interruptible* blocker); }; //////////////////////////////////////////////////////////////////////////////// // ThreadMonitor inlines //////////////////////////////////////////////////////////////////////////////// // Operations //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // Acquire // ----------------------------------------------------------------------------- inline void ThreadMonitor::Acquire () { m_impl->Acquire (); } // ----------------------------------------------------------------------------- // TryAcquire // ----------------------------------------------------------------------------- inline bool ThreadMonitor::TryAcquire () { return m_impl->TryAcquire (); } // ----------------------------------------------------------------------------- // Release // ----------------------------------------------------------------------------- inline void ThreadMonitor::Release () { m_impl->Release (); } // ----------------------------------------------------------------------------- // Wait // ----------------------------------------------------------------------------- inline ThreadMonitorState ThreadMonitor::Wait (UInt32 timeout, bool interruptible) { return m_impl->Wait (timeout, interruptible); } // ----------------------------------------------------------------------------- // Wait // ----------------------------------------------------------------------------- inline ThreadMonitorState ThreadMonitor::Wait (bool interruptible) { return m_impl->Wait (interruptible); } // ----------------------------------------------------------------------------- // Notify // ----------------------------------------------------------------------------- inline bool ThreadMonitor::Notify () { return m_impl->Notify (); } // ----------------------------------------------------------------------------- // IsInterrupted // ----------------------------------------------------------------------------- inline bool ThreadMonitor::IsInterrupted () const { return m_impl->IsInterrupted (); } // ----------------------------------------------------------------------------- // Interrupted // ----------------------------------------------------------------------------- inline bool ThreadMonitor::Interrupted () { return m_impl->Interrupted (); } // ----------------------------------------------------------------------------- // Interrupt // ----------------------------------------------------------------------------- inline void ThreadMonitor::Interrupt () { m_impl->Interrupt (); } // ----------------------------------------------------------------------------- // IsCanceled // ----------------------------------------------------------------------------- inline bool ThreadMonitor::IsCanceled () const { return m_impl->IsCanceled (); } // ----------------------------------------------------------------------------- // Canceled // ----------------------------------------------------------------------------- inline bool ThreadMonitor::Canceled () { return m_impl->Canceled (); } // ----------------------------------------------------------------------------- // Cancel // ----------------------------------------------------------------------------- inline void ThreadMonitor::Cancel () { m_impl->Cancel (); } // ----------------------------------------------------------------------------- // BlockOn // ----------------------------------------------------------------------------- inline void ThreadMonitor::BlockOn (Interruptible* blocker) { m_impl->BlockOn (blocker); } } #endif // GS_THREADMONITOR_HPP
26.081633
84
0.339593
55146f745ab25defa0d51dc9e47174d30cf93ccd
8,270
hpp
C++
utility/convert.hpp
MIPS/external-parameter-framework
7f346c9058f39a533a2eaadc9ebc4001397c6ff9
[ "BSD-3-Clause" ]
null
null
null
utility/convert.hpp
MIPS/external-parameter-framework
7f346c9058f39a533a2eaadc9ebc4001397c6ff9
[ "BSD-3-Clause" ]
null
null
null
utility/convert.hpp
MIPS/external-parameter-framework
7f346c9058f39a533a2eaadc9ebc4001397c6ff9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2011-2014, 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: * * 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. * * 3. Neither the name of the copyright holder 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 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. */ #pragma once #include <limits> #include <sstream> #include <string> #include <stdint.h> #include <cmath> /* details namespace is here to hide implementation details to header end user. It * is NOT intended to be used outside. */ namespace details { /** Helper class to limit instantiation of templates */ template<typename T> struct ConvertionAllowed; /* List of allowed types for conversion */ template<> struct ConvertionAllowed<bool> {}; template<> struct ConvertionAllowed<uint64_t> {}; template<> struct ConvertionAllowed<int64_t> {}; template<> struct ConvertionAllowed<uint32_t> {}; template<> struct ConvertionAllowed<int32_t> {}; template<> struct ConvertionAllowed<uint16_t> {}; template<> struct ConvertionAllowed<int16_t> {}; template<> struct ConvertionAllowed<float> {}; template<> struct ConvertionAllowed<double> {}; template<typename T> static inline bool convertTo(const std::string &str, T &result) { /* Check that conversion to that type is allowed. * If this fails, this means that this template was not intended to be used * with this type, thus that the result is undefined. */ ConvertionAllowed<T>(); if (str.find_first_of(std::string("\r\n\t\v ")) != std::string::npos) { return false; } /* Check for a '-' in string. If type is unsigned and a - is found, the * parsing fails. This is made necessary because "-1" is read as 65535 for * uint16_t, for example */ if (str.find("-") != std::string::npos && !std::numeric_limits<T>::is_signed) { return false; } std::stringstream ss(str); /* Sadly, the stream conversion does not handle hexadecimal format, thus * check is done manually */ if (str.substr(0, 2) == "0x") { if (std::numeric_limits<T>::is_integer) { ss >> std::hex >> result; } else { /* Conversion undefined for non integers */ return false; } } else { ss >> result; } return ss.eof() && !ss.fail() && !ss.bad(); } } // namespace details /** * Convert a string to a given type. * * This template function read the value of the type T in the given string. * The function does not allow to have white spaces around the value to parse * and tries to parse the whole string, which means that if some bytes were not * read in the string, the function fails. * Hexadecimal representation (ie numbers starting with 0x) is supported only * for integral types conversions. * Result may be modified, even in case of failure. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<typename T> static inline bool convertTo(const std::string &str, T &result) { return details::convertTo<T>(str, result); } /** * Specialization for int16_t of convertTo template function. * * This function follows the same paradigm than it's generic version. * * The specific implementation is made necessary because the stlport version of * string streams is bugged and does not fail when giving overflowed values. * This specialisation can be safely removed when stlport behaviour is fixed. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<int16_t>(const std::string &str, int16_t &result) { int64_t res; if (!convertTo<int64_t>(str, res)) { return false; } if (res > std::numeric_limits<int16_t>::max() || res < std::numeric_limits<int16_t>::min()) { return false; } result = static_cast<int16_t>(res); return true; } /** * Specialization for float of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to float behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<float>(const std::string &str, float &result) { if (!details::convertTo(str, result)) { return false; } if (std::abs(result) == std::numeric_limits<float>::infinity() || result == std::numeric_limits<float>::quiet_NaN()) { return false; } return true; } /** * Specialization for double of convertTo template function. * * This function follows the same paradigm than it's generic version and is * based on it but makes furthers checks on the returned value. * * The specific implementation is made necessary because the stlport conversion * from string to double behaves differently than GNU STL: overflow produce * +/-Infinity rather than an error. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<double>(const std::string &str, double &result) { if (!details::convertTo(str, result)) { return false; } if (std::abs(result) == std::numeric_limits<double>::infinity() || result == std::numeric_limits<double>::quiet_NaN()) { return false; } return true; } /** * Specialization for boolean of convertTo template function. * * This function follows the same paradigm than it's generic version. * This function accepts to parse boolean as "0/1" or "false/true" or * "FALSE/TRUE". * The specific implementation is made necessary because the behaviour of * string streams when parsing boolean values is not sufficient to fit our * requirements. Indeed, parsing "true" will correctly parse the value, but the * end of stream is not reached which makes the ss.eof() fails in the generic * implementation. * * @param[in] str the string to parse. * @param[out] result reference to object where to store the result. * * @return true if conversion was successful, false otherwise. */ template<> inline bool convertTo<bool>(const std::string &str, bool &result) { if (str == "0" || str == "FALSE" || str == "false") { result = false; return true; } if (str == "1" || str == "TRUE" || str == "true") { result = true; return true; } return false; }
33.893443
97
0.69867
55156c345ef50bf7727bbde804a325a7ba4bd841
1,553
hpp
C++
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
18
2016-11-22T14:41:37.000Z
2020-04-22T18:16:10.000Z
/* morda - GUI framework Copyright (C) 2012-2021 Ivan Gagis <igagis@gmail.com> 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 3 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, see <http://www.gnu.org/licenses/>. */ /* ================ LICENSE END ================ */ #pragma once #include "../widget.hpp" namespace morda{ class click_proxy : virtual public widget{ bool is_pressed_ = false; bool deferred_release_ret; public: click_proxy(std::shared_ptr<morda::context> c, const treeml::forest& desc); click_proxy(const click_proxy&) = delete; click_proxy& operator=(const click_proxy&) = delete; bool on_mouse_button(const mouse_button_event& event)override; void on_hover_change(unsigned pointer_id)override; bool is_pressed()const noexcept{ return this->is_pressed_; } /** * @brief Handler for mouse press state changes. */ std::function<bool(click_proxy& w)> press_change_handler; /** * @brief Handler for clicked event. */ std::function<void(click_proxy& w)> click_handler; }; }
27.732143
79
0.714746
55164e1e221b2c4199fa953565a2f8df20edc4c7
936
cpp
C++
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
2
2015-12-26T21:20:12.000Z
2017-12-19T00:11:45.000Z
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
/* ID: <ID HERE> LANG: C++11 TASK: beads */ #include <fstream> #include <string> using namespace std; template <typename iterator> int get_stretch(iterator begin, iterator end) { auto iter = begin; auto current_type = *iter; while (iter++ != end) { if (*iter == 'w') continue; if (current_type == 'w') current_type = *iter; if (current_type != *iter) break; } return iter - begin; } int main() { ifstream cin("beads.in"); ofstream cout("beads.out"); int necklace_length; cin >> necklace_length; cin.ignore(1); string necklace; necklace.reserve(necklace_length * 2); cin >> necklace; necklace += necklace; int max_length = 0; auto iter = necklace.begin(), end = necklace.end(); auto riter = necklace.rend(), rend = necklace.rend(); while (iter != end) max_length = max(max_length, get_stretch(riter--, rend) + get_stretch(iter++, end)); cout << min(max_length, necklace_length) << endl; return 0; }
19.5
86
0.666667
5517c8062ce0660d358616c3c258be1ce9fb3327
54
hpp
C++
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
4
2021-02-03T08:53:53.000Z
2022-03-14T06:02:35.000Z
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
1
2021-09-14T17:45:34.000Z
2021-09-15T13:51:39.000Z
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
2
2021-09-09T01:21:23.000Z
2022-02-13T09:14:11.000Z
extern void HideMenuEnv(); extern void HideGameEnv();
18
26
0.777778
55184abb4520a516bff065baa04688408fb61ed1
3,525
hpp
C++
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
33
2018-07-04T09:38:12.000Z
2021-06-19T06:11:45.000Z
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
null
null
null
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
13
2018-07-01T01:55:17.000Z
2021-08-03T10:55:45.000Z
#ifndef __MASK_SKIN_HPP_ #define __MASK_SKIN_HPP_ #include "core/SSkin.h" //************************************ // 这个是 mask 遮罩 皮肤 头像 在skin.xml 里配置 需要 3个值 // src 和 imglist 一样 // mask_a 设置透明值 的rgb a // .a=3 .r=0 .g=1 .b=2 // mask 设置遮罩 图片 // <masklist name="default" src="image:default" mask_a="1" mask="image:mask_42" /> // 还提供了 //************************************ class SSkinMask: public SSkinImgList { SOUI_CLASS_NAME(SSkinMask, L"masklist") public: SSkinMask() : m_bmpMask(NULL) , m_bmpCache(NULL) , m_iMaskChannel(0) { } virtual ~SSkinMask() { } public: // protected: virtual void _Draw(IRenderTarget *pRT, LPCRECT rcDraw, DWORD dwState, BYTE byAlpha) { if(!m_pImg) return; SIZE sz = GetSkinSize(); RECT rcSrc={0,0,sz.cx,sz.cy}; if(m_bVertical) OffsetRect(&rcSrc,0, dwState * sz.cy); else OffsetRect(&rcSrc, dwState * sz.cx, 0); if(m_bmpCache) { RECT rcSrcEx = { 0, 0, m_bmpCache->Size().cx, m_bmpCache->Size().cy }; pRT->DrawBitmapEx(rcDraw, m_bmpCache, &rcSrcEx, GetExpandMode(), byAlpha); } else { RECT rcSrcEx = { 0, 0, m_pImg->Size().cx, m_pImg->Size().cy }; pRT->DrawBitmapEx(rcDraw, m_pImg, &rcSrcEx, GetExpandMode(), byAlpha); } //MakeCacheApha(pRT, rcDraw, rcSrc, byAlpha); } private: CAutoRefPtr<IBitmap> m_bmpMask; CAutoRefPtr<IBitmap> m_bmpCache; int m_iMaskChannel; // 对应 mask 的rgb a // .a=3 .r=0 .g=1 .b=2 protected: SOUI_ATTRS_BEGIN() ATTR_CUSTOM(L"src", OnAttrSrc) ATTR_INT(L"mask_a", m_iMaskChannel, FALSE) // 要先设置这个 不然就用默认 ATTR_CUSTOM(L"mask", OnAttrMask) //image.a SOUI_ATTRS_END() protected: HRESULT OnAttrSrc(const SStringW& strValue, BOOL bLoading) { m_pImg = LOADIMAGE2(strValue); if(NULL == m_pImg) return E_FAIL; if(NULL != m_bmpMask) MakeCacheApha(); return bLoading ? S_OK : S_FALSE; } HRESULT OnAttrMask(const SStringW& strValue, BOOL bLoading) { IBitmap* pImg = NULL; pImg = LOADIMAGE2(strValue); if (!pImg) { return E_FAIL; } m_bmpMask = pImg; pImg->Release(); m_bmpCache = NULL; GETRENDERFACTORY->CreateBitmap(&m_bmpCache); m_bmpCache->Init(m_bmpMask->Width(),m_bmpMask->Height()); if(NULL != m_pImg) MakeCacheApha(); return S_OK; } void MakeCacheApha() { SASSERT(m_bmpMask && m_bmpCache); CAutoRefPtr<IRenderTarget> pRTDst; GETRENDERFACTORY->CreateRenderTarget(&pRTDst, 0, 0); CAutoRefPtr<IRenderObj> pOldBmp; pRTDst->SelectObject(m_bmpCache, &pOldBmp); CRect rc(CPoint(0, 0), m_bmpCache->Size()); CRect rcSrc(CPoint(0, 0), m_pImg->Size()); pRTDst->DrawBitmapEx(rc, m_pImg, &rcSrc, GetExpandMode()); pRTDst->SelectObject(pOldBmp); //从mask的指定channel中获得alpha通道 LPBYTE pBitCache = (LPBYTE)m_bmpCache->LockPixelBits(); LPBYTE pBitMask = (LPBYTE)m_bmpMask->LockPixelBits(); LPBYTE pDst = pBitCache; LPBYTE pSrc = pBitMask + m_iMaskChannel; int nPixels = m_bmpCache->Width()*m_bmpCache->Height(); for(int i=0; i<nPixels; i++) { BYTE byAlpha = *pSrc; pSrc += 4; //源半透明,mask不透明时使用源的半透明属性 if(pDst[3] == 0xff || (pDst[3]!=0xFF &&byAlpha == 0)) {//源不透明,或者mask全透明 *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = byAlpha; } } m_bmpCache->UnlockPixelBits(pBitCache); m_bmpMask->UnlockPixelBits(pBitMask); } }; ////////////////////////////////////////////////////////////////////////// #endif // __WINFILE_ICON_SKIN_HPP_
24.143836
84
0.63461
5519511b177d6bb29e019d6aaec7cb1ec9265209
2,679
cpp
C++
vcf/VCFBuilder2/SelectionManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
vcf/VCFBuilder2/SelectionManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
vcf/VCFBuilder2/SelectionManager.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
//SelectionManager.h #include "ApplicationKit.h" #include "SelectionManager.h" #include <algorithm> using namespace VCF; using namespace VCFBuilder; SelectionManager SelectionManager::selectionMgrInstance; SelectionManager::SelectionManager() { init(); } SelectionManager::~SelectionManager() { m_scheduledControlsToBeDeleted.clear(); m_controlsToBeDeleted.clear(); } void SelectionManager::init() { INIT_EVENT_HANDLER_LIST(SelectionChanged) m_selectionContainer.initContainer( m_selectionSet ); } Enumerator<Component*>* SelectionManager::getSelectionSet() { return m_selectionContainer.getEnumerator(); } bool SelectionManager::isComponentInSelectionSet( Component* component ) { bool result = false; std::vector<Component*>::iterator found = std::find( m_selectionSet.begin(), m_selectionSet.end() , component ); result = ( found != m_selectionSet.end() ); return result; } void SelectionManager::addToSelectionSet( Component* component ) { m_selectionSet.push_back( component ); SelectionManagerEvent event( this, SELECTION_MGR_ITEM_ADDED ); fireOnSelectionChanged( &event ); } void SelectionManager::removeFromSelectionSet( Component* component ) { std::vector<Component*>::iterator found = std::find( m_selectionSet.begin(), m_selectionSet.end() , component ); if ( found != m_selectionSet.end() ) { SelectionManagerEvent event( this, SELECTION_MGR_ITEM_REMOVED ); fireOnSelectionChanged( &event ); m_selectionSet.erase( found ); } } SelectionManager* SelectionManager::getSelectionMgr() { return &SelectionManager::selectionMgrInstance; } void SelectionManager::clearSelectionSet() { SelectionManagerEvent event( this, SELECTION_MGR_ITEMS_CLEARED ); fireOnSelectionChanged( &event ); m_selectionSet.clear(); } void SelectionManager::scheduleControlForDeletion( Control* control ) { m_scheduledControlsToBeDeleted.push_back( control ); } void SelectionManager::cleanUpDeletableControls() { std::vector<Control*>::iterator it = m_scheduledControlsToBeDeleted.begin(); while ( it != m_scheduledControlsToBeDeleted.end() ) { Control* control = *it; control->setComponentState( CS_DESTROYING ); it ++; } it = m_controlsToBeDeleted.begin(); while ( it != m_controlsToBeDeleted.end() ) { Control* control = *it; delete control; control = NULL; it ++; } m_controlsToBeDeleted.clear(); it = m_scheduledControlsToBeDeleted.begin(); while ( it != m_scheduledControlsToBeDeleted.end() ) { Control* control = *it; m_controlsToBeDeleted.push_back( control ); it ++; } m_scheduledControlsToBeDeleted.clear(); }
24.577982
114
0.736096
551bf1e59d207439ecad87f4c13dd45bf661eff0
3,519
hpp
C++
3rdParty/boost/1.71.0/libs/parameter/test/deduced.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/boost/1.71.0/libs/parameter/test/deduced.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/boost/1.71.0/libs/parameter/test/deduced.hpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// Copyright Daniel Wallin 2006. // Copyright Cromwell D. Enage 2017. // 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) #ifndef BOOST_DEDUCED_060920_HPP #define BOOST_DEDUCED_060920_HPP #include <boost/parameter/config.hpp> #include "basics.hpp" #if defined(BOOST_PARAMETER_CAN_USE_MP11) #include <boost/mp11/map.hpp> #include <boost/mp11/algorithm.hpp> #else #include <boost/mpl/bool.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/for_each.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits/is_same.hpp> #endif namespace test { struct not_present_tag { }; not_present_tag not_present; template <typename E, typename ArgPack> class assert_expected { E const& _expected; ArgPack const& _args; public: assert_expected(E const& e, ArgPack const& args_) : _expected(e), _args(args_) { } template <typename T> static bool check_not_present(T const&) { #if defined(BOOST_PARAMETER_CAN_USE_MP11) static_assert( std::is_same<T,test::not_present_tag>::value , "T == test::not_present_tag" ); #else BOOST_MPL_ASSERT(( typename boost::mpl::if_< boost::is_same<T,test::not_present_tag> , boost::mpl::true_ , boost::mpl::false_ >::type )); #endif return true; } template <typename K> bool check1(K const& k, test::not_present_tag const& t, long) const { return assert_expected<E,ArgPack>::check_not_present( this->_args[k | t] ); } template <typename K, typename Expected> bool check1(K const& k, Expected const& e, int) const { return test::equal(this->_args[k], e); } template <typename K> #if defined(BOOST_PARAMETER_CAN_USE_MP11) void operator()(K&&) const #else void operator()(K) const #endif { boost::parameter::keyword<K> const& k = boost::parameter::keyword<K>::instance; BOOST_TEST(this->check1(k, this->_expected[k], 0L)); } }; template <typename E, typename A> void check0(E const& e, A const& args) { #if defined(BOOST_PARAMETER_CAN_USE_MP11) boost::mp11::mp_for_each<boost::mp11::mp_map_keys<E> >( test::assert_expected<E,A>(e, args) ); #else boost::mpl::for_each<E>(test::assert_expected<E,A>(e, args)); #endif } #if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) template <typename P, typename E, typename ...Args> void check(E const& e, Args const&... args) { test::check0(e, P()(args...)); } #else template <typename P, typename E, typename A0> void check(E const& e, A0 const& a0) { test::check0(e, P()(a0)); } template <typename P, typename E, typename A0, typename A1> void check(E const& e, A0 const& a0, A1 const& a1) { test::check0(e, P()(a0, a1)); } template <typename P, typename E, typename A0, typename A1, typename A2> void check(E const& e, A0 const& a0, A1 const& a1, A2 const& a2) { test::check0(e, P()(a0, a1, a2)); } #endif // BOOST_PARAMETER_HAS_PERFECT_FORWARDING } // namespace test #endif // include guard
26.659091
76
0.596476
55210b4c09d6343a045c00f1aab3c56a53b7accc
842
cpp
C++
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <iterator> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int d1, m1, y1; int d2, m2, y2; istream_iterator<int> iter(cin); d1 = *iter++; m1 = *iter++; y1 = *iter++; d2 = *iter++; m2 = *iter++; y2 = *iter; int factor = 0; int baseFine = 0; if (y1 > y2) { baseFine = 10000; factor = 1; } else if (y1 == y2) { if (m1 > m2) { baseFine = 500; factor = m1 - m2; } else if (m1 == m2) { if (d1 > d2) { baseFine = 15; factor = d1 - d2; } } } cout << baseFine * factor << endl; return 0; }
18.711111
80
0.465558
55258619dc7b0fa1b8366e9eafff443d00ac4825
552
cpp
C++
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
#include "classeA.hpp" classeA::classeA() { A1 = 0; A2 = 0; } classeA::~classeA(){} void classeA::MA1() { std::cout << "Metodo MA1" << std::endl; } void classeA::MA2() { std::cout << "Metodo MA2" << std::endl; } void classeA::MA3() { std::cout << "Alteração a classe A partir do clone" << std::endl; } int classeA::getA1() { return A1; } void classeA::setA1(int _a1) { A1 = _a1; } float classeA::getA2() { return A2; } void classeA::setA2(float _a2) { A2= _a2; }
12.266667
70
0.519928
55275e13b42d0b4cc60c4a191a3b7cc832f54754
152
cpp
C++
example.cpp
Bepitic/Simple-Logger
d74ee2dc5c25d45c4a2eb29856cd9c9f99c8b51f
[ "MIT" ]
null
null
null
example.cpp
Bepitic/Simple-Logger
d74ee2dc5c25d45c4a2eb29856cd9c9f99c8b51f
[ "MIT" ]
null
null
null
example.cpp
Bepitic/Simple-Logger
d74ee2dc5c25d45c4a2eb29856cd9c9f99c8b51f
[ "MIT" ]
null
null
null
#include "logger.hpp" int main(int argc, char *argv[]) { Log::Err("el sitstema ",1," Funciona"); Log::Inf(); Log::Warn(); return 0; }
13.818182
43
0.546053
552cc14700be68dce24bfb788e63b032eb9147b9
5,737
cpp
C++
wznmcmbd/CrdWznmOpx/PnlWznmOpxDetail_evals.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
wznmcmbd/CrdWznmOpx/PnlWznmOpxDetail_evals.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
wznmcmbd/CrdWznmOpx/PnlWznmOpxDetail_evals.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file PnlWznmOpxDetail_evals.cpp * job handler for job PnlWznmOpxDetail (implementation of availability/activation evaluation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 28 Nov 2020 */ // IP header --- ABOVE using namespace std; using namespace Sbecore; using namespace Xmlio; bool PnlWznmOpxDetail::evalButSaveAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButSaveActive( DbsWznm* dbswznm ) { // dirty() vector<bool> args; bool a; a = false; a = dirty; args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtSrfActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtOpkActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButOpkViewAvail( DbsWznm* dbswznm ) { // opx.opkEq(0)|(pre.ixCrdaccOpk()&pre.refVer()) vector<bool> args; bool a, b; a = false; a = (recOpx.refWznmMOppack == 0); args.push_back(a); a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPK, jref) != 0); args.push_back(a); a = false; a = (xchg->getRefPreset(VecWznmVPreset::PREWZNMREFVER, jref) != 0); args.push_back(a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a || b); return(args.back()); }; bool PnlWznmOpxDetail::evalButOpkViewActive( DbsWznm* dbswznm ) { // !opx.opkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMOppack == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalChkShdActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxfCmtActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButSqkNewAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit)&opx.sqkEq(0) vector<bool> args; bool a, b; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); return(args.back()); }; bool PnlWznmOpxDetail::evalButSqkDeleteAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit)&!opx.sqkEq(0) vector<bool> args; bool a, b; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); b = args.back(); args.pop_back(); a = args.back(); args.pop_back(); args.push_back(a && b); return(args.back()); }; bool PnlWznmOpxDetail::evalPupSqkJtiAvail( DbsWznm* dbswznm ) { // !opx.sqkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalPupSqkJtiActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalButSqkJtiEditAvail( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtSqkTitAvail( DbsWznm* dbswznm ) { // !opx.sqkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxtSqkTitActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxfSqkExaAvail( DbsWznm* dbswznm ) { // !opx.sqkEq(0) vector<bool> args; bool a; a = false; a = (recOpx.refWznmMSquawk == 0); args.push_back(a); a = args.back(); args.pop_back(); args.push_back(!a); return(args.back()); }; bool PnlWznmOpxDetail::evalTxfSqkExaActive( DbsWznm* dbswznm ) { // pre.ixCrdaccOpxIncl(edit) vector<bool> args; bool a; a = false; a = (xchg->getIxPreset(VecWznmVPreset::PREWZNMIXCRDACCOPX, jref) & VecWznmWAccess::EDIT); args.push_back(a); return(args.back()); };
20.41637
101
0.682587
552e4bb200ddc0eb455b2eca6355e0bac53347f8
13,531
cpp
C++
decoder/YAIK_Alpha.cpp
KLab/YAIK
55ecf9b8eac0b2b67c4cb52b997e81930e94f9bf
[ "MIT" ]
4
2020-05-26T02:21:35.000Z
2022-01-13T12:05:28.000Z
decoder/YAIK_Alpha.cpp
KLab/YAIK
55ecf9b8eac0b2b67c4cb52b997e81930e94f9bf
[ "MIT" ]
null
null
null
decoder/YAIK_Alpha.cpp
KLab/YAIK
55ecf9b8eac0b2b67c4cb52b997e81930e94f9bf
[ "MIT" ]
null
null
null
#include "YAIK_functions.h" // memset, memcpy #include <memory.h> /* ----------------------------------------------------------------------------- 2. Decompression technique for Alpha ----------------------------------------------------------------------------- */ bool CheckInBound2D(YAIK_Instance* pCtx, BoundingBox& bbox) { // Check that all values are POSITIVE. if ((bbox.x|bbox.y|bbox.w|bbox.h) < 0) { return false; } // Check that X0,Y0 is inside image. (Included) if ((bbox.x >= pCtx->width) || (bbox.y >= pCtx->height)) { return false; } // Check that X1,Y1 are inside image.(Excluded) if (((bbox.x+bbox.w) > pCtx->width) || ((bbox.y+bbox.h) > pCtx->height)) { return false; } } bool Decompress1BitMaskAlign8NoMask(YAIK_Instance* pCtx, BoundingBox& header_bbox, u8* data_uncompressed, u32 data_size) { BoundingBox& bbox = header_bbox; u32 width = pCtx->width; u32 height = pCtx->height; // Match file width/height if (!CheckInBound2D(pCtx, bbox)) { return false; } // Check before doing allocation. if (data_size < ((bbox.w>>3)*bbox.h)) { return false; } if ((bbox.h > 0) && (bbox.w > 0)) { //Heap Temp Allocator // [Alloc for stream decompression of size] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } // No empty surface allowed. // 8 pixel aligned. kassert((bbox.x & 7) == 0); kassert((bbox.w & 7) == 0); /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = pCtx->alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * width)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (width - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((width - (bbox.x + bbox.w))) + (((height - (endY1)) * width)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int blkCnt = stepD >> 3; // By 8 pixel each. // TODO OPTIMIZE [Could optimize loop using ptr] int endY = endY1 - 1; for (int y = bbox.y; y <= endY; y++) { // Section [....] // [TODO] Fill with bitmap 1 bit -> 8 bit. memcpy(pDst, mipmapMaskStream, stepD); int cnt = blkCnt; while (--cnt) { int v = *data_uncompressed++; *pDst++ = ((v & 0x01) << 31) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x02) << 30) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x04) << 29) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x08) << 28) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x10) << 27) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x20) << 26) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x40) << 25) >> 31; // 0 or 255 write. *pDst++ = ((v & 0x80) << 24) >> 31; // 0 or 255 write. } // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } return true; } else { return false; } } bool Decompress6BitTo8BitAlphaNoMask(YAIK_Instance* pCtx, AlphaHeader* header, bool useInverseValues, u8* data_uncompressed, u32 data_size) { BoundingBox& bbox = header->bbox; // Match file width/height if (!CheckInBound2D(pCtx, bbox)) { return false; } // Check before doing allocation. if (data_size < ((bbox.w>>3)*bbox.h)) { return false; } if ((header->bbox.h > 0) && (header->bbox.w > 0)) { u32 width = pCtx->width; u32 height = pCtx->height; // No empty surface allowed. // Heap Buffer Allocator : // [Target Buffer Mask w*h] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } u8* alphaChannel = pCtx->alphaChannel; u8* alphaMaskStream = data_uncompressed; int dstWidth = pCtx->width; /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * dstWidth)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (dstWidth - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((dstWidth - (bbox.x + bbox.w))) + (((pCtx->height - (endY1)) * dstWidth)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int endY = endY1 - 1; int state = 0; int blockPerLine = bbox.w >> 2; // div 4 kassert((bbox.w & 3) == 0); u8 workV; // TODO OPTIMIZE [Could optimize loop using ptr for Y...] for (int y = bbox.y; y <= endY; y++) { // Decompress by block of 4 pixels u8* endBlk = &alphaMaskStream[blockPerLine * 3]; if (useInverseValues) { /** Decompress single line of 4 value blocks. Stream is array of 6 bit with inverted values (0=>31, 31=>0) Value is then upscaled from 6 bit to 8 bit (proper mathematically correct : [abcdef] -> [abcdefab] => Same as (v * 255 / 31) */ while (alphaMaskStream < endBlk) { // bbaaaaaa u8 v = *alphaMaskStream++; workV = 63 - (v & 0x3F); // aaaaaa *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ccccbbbb u8 v2 = *alphaMaskStream++; workV = 63 - ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ddddddcc v = *alphaMaskStream++; workV = 63 - ((v2 >> 4) | ((v & 3) << 4)); // cc.cccc *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. workV = 63 - (v >> 2); // dddddd *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. } } else { /* Same as previous block, except that 6 bit values are NOT inverted inside the stream. */ while (alphaMaskStream < endBlk) { // bbaaaaaa u8 v = *alphaMaskStream++; workV = (v & 0x3F); // aaaaaa *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ccccbbbb u8 v2 = *alphaMaskStream++; workV = ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. // ddddddcc v = *alphaMaskStream++; workV = ((v2 >> 4) | ((v & 3) << 4)); // cc.cccc *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. workV = (v >> 2); // dddddd *pDst++ = (workV << 2) | (workV >> 4); // 6 -> 8 bit. } } // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } } return true; } bool Decompress6BitTo8BitAlphaUsingMipmapMask(YAIK_Instance* pCtx, AlphaHeader* header, bool useInverseValues, u8* data_uncompressed, u32 data_size) { if ((header->bbox.h > 0) && (header->bbox.w > 0)) { u32 width = pCtx->width; u32 height = pCtx->height; // No empty surface allowed. // Heap Buffer Allocator : // [Target Buffer Mask w*h] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } u8* alphaChannel = pCtx->alphaChannel; u8* mipmapChannel = pCtx->mipMapMask; // Different bounding box !!! u32 strideMipmap = pCtx->maskBBox.w; BoundingBox alphaBBox = header->bbox; // Tricky : mipmap parsing in mipmap space is using alpha bounding box ! u32 mipmapPos = (alphaBBox.x - pCtx->maskBBox.x) + (strideMipmap * (alphaBBox.y - pCtx->maskBBox.y)); u8* alphaMaskStream = data_uncompressed; BoundingBox bbox = header->bbox; int dstWidth = pCtx->width; /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * dstWidth)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (dstWidth - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((dstWidth - (bbox.x + bbox.w))) + (((pCtx->height - (endY1)) * dstWidth)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int endY = endY1 - 1; u8 workV; int state = 0; for (int y = bbox.y; y <= endY; y++) { u8 v,v2, writeV; int backupMipmapPos = mipmapPos; int mipmapPosE = mipmapPos + bbox.w; // [TODO] Possible optimization using left/right span if (useInverseValues) { do { u8 mipV = mipmapChannel[mipmapPos >> 3] & (1 << (mipmapPos & 7)); if (mipV == 0) { *pDst++ = 0; } else { switch (state & 3) { case 0: v = *alphaMaskStream++; workV = 63 - (v & 0x3F); // aaaaaa writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 1: v2 = *alphaMaskStream++; workV = 63 - ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 2: v = *alphaMaskStream++; workV = 63 - ((v2 >> 4) | ((v & 0x3) << 4)); // cc.cccc writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 3: workV = 63 - (v >> 2); // dddddd writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; } *pDst++ = writeV; state++; } mipmapPos++; } while (mipmapPos != mipmapPosE); } else { do { u8 mipV = mipmapChannel[mipmapPos >> 3] & (1 << (mipmapPos & 7)); if (mipV == 0) { *pDst++ = 0; } else { switch (state & 3) { case 0: v = *alphaMaskStream++; workV = (v & 0x3F); // aaaaaa writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 1: v2 = *alphaMaskStream++; workV = ((v >> 6) | ((v2 & 0xF) << 2)); // bbbb.bb writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 2: v = *alphaMaskStream++; workV = ((v2 >> 4) | ((v & 0x3) << 4)); // cc.cccc writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; case 3: workV = (v >> 2); // dddddd writeV = (workV << 2) | (workV >> 4); // 6 -> 8 bit. break; } *pDst++ = writeV; state++; } mipmapPos++; } while (mipmapPos != mipmapPosE); } mipmapPos = backupMipmapPos + strideMipmap; // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } } return true; } bool Decompress8BitTo8BitAlphaNoMask(YAIK_Instance* pCtx, AlphaHeader* header, u8* data_uncompressed, u32 data_size) { // TODO : Reuse from previous alpha stuff. // Support only through memcpy. if ((header->bbox.h > 0) && (header->bbox.w > 0)) { u32 width = pCtx->width; u32 height = pCtx->height; // No empty surface allowed. // Heap Buffer Allocator : // [Target Buffer Mask w*h] pCtx->alphaChannel = (u8*)AllocateMem(&pCtx->allocCtx, width * height); if (pCtx->alphaChannel == NULL) { return false; } u8* alphaChannel = pCtx->alphaChannel; u8* alphaMaskStream = data_uncompressed; BoundingBox bbox = header->bbox; int dstWidth = pCtx->width; /* Fill mask with optimization to the length and call count to memset and memcpy. AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA.................BBBBBBBB BBBBBB.................BBBBBBBB BBBBBB.................CCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC */ u8* pDst = alphaChannel; // Section [AAAA] int stepA = (bbox.x + (bbox.y * dstWidth)); // Section [....] int stepD = bbox.w; // Section [BBBB] int stepB = (dstWidth - bbox.w); // Section [CCCC] int endY1 = (bbox.y + bbox.h); int stepC = ((dstWidth - (bbox.x + bbox.w))) + (((pCtx->height - (endY1)) * dstWidth)); if (stepA) { memset(pDst, 0, stepA); pDst += stepA; } int endY = endY1 - 1; int state = 0; int blockPerLine = bbox.w >> 2; // div 4 kassert((bbox.w & 3) == 0); // TODO OPTIMIZE [Could optimize loop using ptr for Y...] for (int y = bbox.y; y <= endY; y++) { // Decompress by block of 4 pixels memcpy(pDst, alphaMaskStream, stepD); pDst += stepD; alphaMaskStream += stepD; // Section [BBBB] or [CCCC] (last) int stepDo = (y != endY) ? stepB : stepC; memset(pDst, 0, stepDo); pDst += stepDo; } } return true; }
30.406742
151
0.538319
552ea5a5d0dee8d6d27ee878bf7c75c1e22c1589
10,777
cpp
C++
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/evs/v2/model/SnapshotDetails.h" namespace HuaweiCloud { namespace Sdk { namespace Evs { namespace V2 { namespace Model { SnapshotDetails::SnapshotDetails() { id_ = ""; idIsSet_ = false; status_ = ""; statusIsSet_ = false; name_ = ""; nameIsSet_ = false; description_ = ""; descriptionIsSet_ = false; createdAt_ = ""; createdAtIsSet_ = false; updatedAt_ = ""; updatedAtIsSet_ = false; metadataIsSet_ = false; volumeId_ = ""; volumeIdIsSet_ = false; size_ = 0; sizeIsSet_ = false; osExtendedSnapshotAttributesprojectId_ = ""; osExtendedSnapshotAttributesprojectIdIsSet_ = false; osExtendedSnapshotAttributesprogress_ = ""; osExtendedSnapshotAttributesprogressIsSet_ = false; } SnapshotDetails::~SnapshotDetails() = default; void SnapshotDetails::validate() { } web::json::value SnapshotDetails::toJson() const { web::json::value val = web::json::value::object(); if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(statusIsSet_) { val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_); } if(nameIsSet_) { val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_); } if(descriptionIsSet_) { val[utility::conversions::to_string_t("description")] = ModelBase::toJson(description_); } if(createdAtIsSet_) { val[utility::conversions::to_string_t("created_at")] = ModelBase::toJson(createdAt_); } if(updatedAtIsSet_) { val[utility::conversions::to_string_t("updated_at")] = ModelBase::toJson(updatedAt_); } if(metadataIsSet_) { val[utility::conversions::to_string_t("metadata")] = ModelBase::toJson(metadata_); } if(volumeIdIsSet_) { val[utility::conversions::to_string_t("volume_id")] = ModelBase::toJson(volumeId_); } if(sizeIsSet_) { val[utility::conversions::to_string_t("size")] = ModelBase::toJson(size_); } if(osExtendedSnapshotAttributesprojectIdIsSet_) { val[utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id")] = ModelBase::toJson(osExtendedSnapshotAttributesprojectId_); } if(osExtendedSnapshotAttributesprogressIsSet_) { val[utility::conversions::to_string_t("os-extended-snapshot-attributes:progress")] = ModelBase::toJson(osExtendedSnapshotAttributesprogress_); } return val; } bool SnapshotDetails::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("status"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setStatus(refVal); } } if(val.has_field(utility::conversions::to_string_t("name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setName(refVal); } } if(val.has_field(utility::conversions::to_string_t("description"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("description")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDescription(refVal); } } if(val.has_field(utility::conversions::to_string_t("created_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("created_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setCreatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("updated_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("updated_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setUpdatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("metadata"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("metadata")); if(!fieldValue.is_null()) { Object refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setMetadata(refVal); } } if(val.has_field(utility::conversions::to_string_t("volume_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("volume_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVolumeId(refVal); } } if(val.has_field(utility::conversions::to_string_t("size"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("size")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setSize(refVal); } } if(val.has_field(utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOsExtendedSnapshotAttributesprojectId(refVal); } } if(val.has_field(utility::conversions::to_string_t("os-extended-snapshot-attributes:progress"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("os-extended-snapshot-attributes:progress")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOsExtendedSnapshotAttributesprogress(refVal); } } return ok; } std::string SnapshotDetails::getId() const { return id_; } void SnapshotDetails::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool SnapshotDetails::idIsSet() const { return idIsSet_; } void SnapshotDetails::unsetid() { idIsSet_ = false; } std::string SnapshotDetails::getStatus() const { return status_; } void SnapshotDetails::setStatus(const std::string& value) { status_ = value; statusIsSet_ = true; } bool SnapshotDetails::statusIsSet() const { return statusIsSet_; } void SnapshotDetails::unsetstatus() { statusIsSet_ = false; } std::string SnapshotDetails::getName() const { return name_; } void SnapshotDetails::setName(const std::string& value) { name_ = value; nameIsSet_ = true; } bool SnapshotDetails::nameIsSet() const { return nameIsSet_; } void SnapshotDetails::unsetname() { nameIsSet_ = false; } std::string SnapshotDetails::getDescription() const { return description_; } void SnapshotDetails::setDescription(const std::string& value) { description_ = value; descriptionIsSet_ = true; } bool SnapshotDetails::descriptionIsSet() const { return descriptionIsSet_; } void SnapshotDetails::unsetdescription() { descriptionIsSet_ = false; } std::string SnapshotDetails::getCreatedAt() const { return createdAt_; } void SnapshotDetails::setCreatedAt(const std::string& value) { createdAt_ = value; createdAtIsSet_ = true; } bool SnapshotDetails::createdAtIsSet() const { return createdAtIsSet_; } void SnapshotDetails::unsetcreatedAt() { createdAtIsSet_ = false; } std::string SnapshotDetails::getUpdatedAt() const { return updatedAt_; } void SnapshotDetails::setUpdatedAt(const std::string& value) { updatedAt_ = value; updatedAtIsSet_ = true; } bool SnapshotDetails::updatedAtIsSet() const { return updatedAtIsSet_; } void SnapshotDetails::unsetupdatedAt() { updatedAtIsSet_ = false; } Object SnapshotDetails::getMetadata() const { return metadata_; } void SnapshotDetails::setMetadata(const Object& value) { metadata_ = value; metadataIsSet_ = true; } bool SnapshotDetails::metadataIsSet() const { return metadataIsSet_; } void SnapshotDetails::unsetmetadata() { metadataIsSet_ = false; } std::string SnapshotDetails::getVolumeId() const { return volumeId_; } void SnapshotDetails::setVolumeId(const std::string& value) { volumeId_ = value; volumeIdIsSet_ = true; } bool SnapshotDetails::volumeIdIsSet() const { return volumeIdIsSet_; } void SnapshotDetails::unsetvolumeId() { volumeIdIsSet_ = false; } int32_t SnapshotDetails::getSize() const { return size_; } void SnapshotDetails::setSize(int32_t value) { size_ = value; sizeIsSet_ = true; } bool SnapshotDetails::sizeIsSet() const { return sizeIsSet_; } void SnapshotDetails::unsetsize() { sizeIsSet_ = false; } std::string SnapshotDetails::getOsExtendedSnapshotAttributesprojectId() const { return osExtendedSnapshotAttributesprojectId_; } void SnapshotDetails::setOsExtendedSnapshotAttributesprojectId(const std::string& value) { osExtendedSnapshotAttributesprojectId_ = value; osExtendedSnapshotAttributesprojectIdIsSet_ = true; } bool SnapshotDetails::osExtendedSnapshotAttributesprojectIdIsSet() const { return osExtendedSnapshotAttributesprojectIdIsSet_; } void SnapshotDetails::unsetosExtendedSnapshotAttributesprojectId() { osExtendedSnapshotAttributesprojectIdIsSet_ = false; } std::string SnapshotDetails::getOsExtendedSnapshotAttributesprogress() const { return osExtendedSnapshotAttributesprogress_; } void SnapshotDetails::setOsExtendedSnapshotAttributesprogress(const std::string& value) { osExtendedSnapshotAttributesprogress_ = value; osExtendedSnapshotAttributesprogressIsSet_ = true; } bool SnapshotDetails::osExtendedSnapshotAttributesprogressIsSet() const { return osExtendedSnapshotAttributesprogressIsSet_; } void SnapshotDetails::unsetosExtendedSnapshotAttributesprogress() { osExtendedSnapshotAttributesprogressIsSet_ = false; } } } } } }
25.00464
153
0.673286
55307bf0b102da1dcbeca82bac7ed73adf53a86a
8,215
cpp
C++
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
 // MFCMyProcCtlUIDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "MFCMyProcCtlUI.h" #include "MFCMyProcCtlUIDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #include <TlHelp32.h> using namespace std; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCMyProcCtlUIDlg 对话框 CMFCMyProcCtlUIDlg::CMFCMyProcCtlUIDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_MFCMYPROCCTLUI_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); hThread_refresh = NULL; //pImageList = new CImageList; //pImageList->Create(32, 32, ILC_COLOR32, 0, 1); } CMFCMyProcCtlUIDlg::~CMFCMyProcCtlUIDlg() { //delete pImageList; } void CMFCMyProcCtlUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_PROCS, m_list_procs); } BEGIN_MESSAGE_MAP(CMFCMyProcCtlUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_REFRESH_PROCS, &CMFCMyProcCtlUIDlg::OnBnClickedButtonRefreshProcs) ON_BN_CLICKED(IDC_BUTTON_ATTACH_CONTROLLER, &CMFCMyProcCtlUIDlg::OnBnClickedButtonAttachController) ON_BN_CLICKED(IDC_BUTTON_DETACH_CONTROLLER, &CMFCMyProcCtlUIDlg::OnBnClickedButtonDetachController) END_MESSAGE_MAP() // CMFCMyProcCtlUIDlg 消息处理程序 DWORD __stdcall CMFCMyProcCtlUIDlg::Thread_RefreshList(PVOID arg) { CMFCMyProcCtlUIDlg* pobj = (CMFCMyProcCtlUIDlg*)arg; if (!pobj) return ERROR_INVALID_PARAMETER; pobj->GetDlgItem(IDC_BUTTON_ATTACH_CONTROLLER)->EnableWindow(0); pobj->GetDlgItem(IDC_BUTTON_DETACH_CONTROLLER)->EnableWindow(0); pobj->GetDlgItem(IDC_BUTTON_REFRESH_PROCS)->EnableWindow(0); pobj->m_list_procs.DeleteAllItems(); HANDLE hsnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hsnap) return false; PROCESSENTRY32 pe = {0}; pe.dwSize = sizeof(PROCESSENTRY32); Process32First(hsnap, &pe); int index = 0; do { //HANDLE hProcess = // OpenProcess(pe.th32ProcessID, FALSE, PROCESS_QUERY_INFORMATION); //BOOL ok = FALSE; //if (hProcess) { // TCHAR buffer[2048] = { 0 }; DWORD size = 2047; // QueryFullProcessImageName(hProcess, 0, buffer, &size); // CloseHandle(hProcess); // HMODULE hMod = LoadLibrary(buffer); // if (hMod) { // pobj->pImageList->Add(LoadIcon(hMod, IDI_APPLICATION)); // ok = true; // } //} //if (!ok) { // pobj->pImageList->Add(LoadIcon(NULL, IDI_APPLICATION)); //} pobj->m_list_procs.InsertItem(index, to_wstring(pe.th32ProcessID).c_str()); pobj->m_list_procs.SetItemText(index, 1, pe.szExeFile); index++; } while (::Process32Next(hsnap, &pe)); ::CloseHandle(hsnap); if (pobj->cl.getopt(L"service-name")) { pobj->GetDlgItem(IDC_BUTTON_ATTACH_CONTROLLER)->EnableWindow(); pobj->GetDlgItem(IDC_BUTTON_DETACH_CONTROLLER)->EnableWindow(); } pobj->GetDlgItem(IDC_BUTTON_REFRESH_PROCS)->EnableWindow(); return 0; } BOOL CMFCMyProcCtlUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_list_procs.InsertColumn(0, L"PID", 0, 80, 0); m_list_procs.InsertColumn(1, L"Image Name", 0, 200, 0); m_list_procs.InsertItem(0, L"Loading"); m_list_procs.SetItemText(0, 1, L"Loading datas..."); //m_list_procs.SetImageList(pImageList, LVSIL_NORMAL); cl.parse(GetCommandLineW()); if (cl.getopt(L"service-name", ServiceName)) { CString wt; GetWindowText(wt); SetWindowTextW((L"[" + ServiceName + L"] - " + wt.GetBuffer()).c_str()); } try_create_reflush_thread: hThread_refresh = CreateThread(0, 0, Thread_RefreshList, this, 0, 0); if (hThread_refresh) { CloseHandle(hThread_refresh); } else { if (IDRETRY == MessageBox(L"CANNOT CREATE THREAD", 0, MB_ICONHAND | MB_RETRYCANCEL | MB_DEFBUTTON2)) goto try_create_reflush_thread; else EndDialog(-1); } return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMFCMyProcCtlUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMFCMyProcCtlUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CMFCMyProcCtlUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCMyProcCtlUIDlg::OnBnClickedButtonRefreshProcs() { try_create_reflush_thread: hThread_refresh = CreateThread(0, 0, Thread_RefreshList, this, 0, 0); if (hThread_refresh) { CloseHandle(hThread_refresh); } else { if (IDRETRY == MessageBox(L"Cannot create thread", 0, MB_ICONHAND | MB_RETRYCANCEL | MB_DEFBUTTON2)) goto try_create_reflush_thread; } } bool CMFCMyProcCtlUIDlg::CheckAdminPriv() { if (!IsRunAsAdmin()) { if (IDRETRY == MessageBoxW(L"Administrator privileges are required to " "complete this operation.\nClick [Retry] to retry as an administrator.", L"Access is Denied", MB_ICONHAND | MB_RETRYCANCEL)) { if ((INT_PTR)ShellExecuteW(m_hWnd, L"runas", s2wc(GetProgramDir()), (L"/runas "s + GetCommandLineW()).c_str(), 0, 1) > 32) EndDialog(0); } return false; } return true; } void CMFCMyProcCtlUIDlg::OnBnClickedButtonAttachController() { if (!CheckAdminPriv()) return; POSITION pos = m_list_procs.GetFirstSelectedItemPosition(); if (pos != NULL) { while (pos) { int nItem = m_list_procs.GetNextSelectedItem(pos); // nItem是所选中行的序号 CString text = m_list_procs.GetItemText(nItem, 0); DWORD pid = atol(ws2c(text.GetBuffer())); HANDLE hPipe = NULL; WCHAR pipe_name[256]{ 0 }; DWORD tmp = 0; LoadStringW(NULL, IDS_STRING_SVC_CTRLPIPE, pipe_name, 255); wcscat_s(pipe_name, L"\\"); wcscat_s(pipe_name, ServiceName.c_str()); if (::WaitNamedPipeW(pipe_name, 10000)) { #pragma warning(push) #pragma warning(disable: 6001) hPipe = ::CreateFileW(pipe_name, GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (!hPipe || hPipe == INVALID_HANDLE_VALUE) { MessageBoxW(LastErrorStrW().c_str(), NULL, MB_ICONHAND); break; } DWORD dwMode = PIPE_READMODE_MESSAGE; (VOID)SetNamedPipeHandleState( hPipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time string str = "Attach-Process-Control /pid=" + to_string(pid); ::WriteFile(hPipe, str.c_str(), (DWORD)str.length(), &tmp, NULL); auto _sub1 = [&] { MessageBox((_T("Error: "s) + ErrorCodeToString(atol(ws2s(pipe_name).c_str())) + TEXT("\nRaw data:") + pipe_name) .c_str(), 0, MB_ICONHAND); }; if (ReadFile(hPipe, pipe_name, 255, &tmp, 0)) { if (0 == wcscmp(L"0", pipe_name)) { MessageBox(ErrorCodeToString(0).c_str(), 0, MB_ICONINFORMATION); } else _sub1(); } else _sub1(); ::CloseHandle(hPipe); #pragma warning(pop) } else { MessageBoxW(ErrorCodeToStringW(ERROR_TIMEOUT).c_str(), 0, MB_ICONHAND); } } } } void CMFCMyProcCtlUIDlg::OnBnClickedButtonDetachController() { if (!CheckAdminPriv()) return; }
26.246006
79
0.709677
5530e9403ac3d0816100568113bbfd0b164ef4e4
721
cpp
C++
test/smoke/fast_fp_atomics/fast_fp_atomics.cpp
raramakr/aomp
9a224fe01ca8eff4209b8b79aa1fa15a18da65db
[ "Apache-2.0" ]
null
null
null
test/smoke/fast_fp_atomics/fast_fp_atomics.cpp
raramakr/aomp
9a224fe01ca8eff4209b8b79aa1fa15a18da65db
[ "Apache-2.0" ]
null
null
null
test/smoke/fast_fp_atomics/fast_fp_atomics.cpp
raramakr/aomp
9a224fe01ca8eff4209b8b79aa1fa15a18da65db
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<omp.h> int main() { double sum = 0.0; int n = 10000; #pragma omp target teams distribute parallel for map(tofrom:sum) for(int i = 0; i < n; i++) { #pragma omp atomic hint(AMD_safe_fp_atomics) sum+=1.0; } int err = 0; if (sum != (double) n) { printf("Error with safe fp atomics, got %lf, expected %lf", sum, (double) n); err = 1; } sum = 0.0; #pragma omp target teams distribute parallel for map(tofrom:sum) for(int i = 0; i < n; i++) { #pragma omp atomic hint(AMD_fast_fp_atomics) sum+=1.0; } if (sum != (double) n) { printf("Error with unsafe fp atomics, got %lf, expected %lf", sum, (double) n); err = 1; } return err; }
20.6
83
0.590846
5530faf5a36ee97a940185b4620737dd2bc95ae6
2,491
cpp
C++
POO/Seminar 2/S2p2claseImplicit.cpp
ParaschivAlex/FMI-Thangs
26d8a13b08344744ee6ab56f088dd4adb665980e
[ "MIT" ]
null
null
null
POO/Seminar 2/S2p2claseImplicit.cpp
ParaschivAlex/FMI-Thangs
26d8a13b08344744ee6ab56f088dd4adb665980e
[ "MIT" ]
null
null
null
POO/Seminar 2/S2p2claseImplicit.cpp
ParaschivAlex/FMI-Thangs
26d8a13b08344744ee6ab56f088dd4adb665980e
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> using namespace std; class Complex { float re,im; public: void f(); }; /* pentru orice clasa compilatorul asigura implicit - un constructor de initializare -fara parametrii, - un constructor de copiere - un operator de atribuire - un destructor -constructorul de initializare se apeleaza -cind se aloca zona de memorie pt un obiect -constructorul de copiere se apeleaza -cind se aloca zona de memorie pt un obiect si se initializeaza cu un obiect existent -operatorul de atribuire se apeleaza cind se executa operatia de atribuire -destructorul se apeleaza cind se elibereaza zona de memorie a unui obiect */ int main() { Complex C1; /* se apeleaza constructorul de initializare putem gandi ca C1.Complex()*/ Complex *p;// nu se apeleaza constructorul -nu se aloca zona pt obiect p= new Complex; // se apeleaza constructorul de initializare -se aloca zona pt obiect Complex v[2]; // se apeleaza construtorul de initializare de 2 ori Complex C2=C1; // se apeleaza constructorul de copiere // putem gandi C2.Complex(C1); p=new Complex(C1);// se apeleaza constructorul de copiere C2=C1; // se apeleaza opereatorul de atribuire -obiectele deja create // C2.operator=(C1); {Complex C3;}// se apeleaza mai intai constructorul de initializare si mai apoi destructorul // putem gandi C3.~Complex() delete p; // se apeleaza destructorul } /* constructorul de copiere si operatorul de atribuire impliciti copiaza BIT CU BIT datele obiectului sursa in datele obiectului destinatie daca scriem un constructor de initializare - nu mai exista constructor de initializare implicit daca scriem un constructor de copiere -nu mai exista -constructor de initializare implicit -constructor de copiere implicit */ /* constructorul de copiere se apeleaza 1. la declararea cu initializare ex: Complex C2=C1; 2. la transmiterea unui obiect prin valoare intr-o functie: void f(Complex op){} f(C1); 3. la intoarcerea unui obiect prin valoare dintr-o functie Complex f1(){ Complex ol; return ol;} f1(); Atentie ! -la transmiterea unui obiect prin referinta -nu se apeleaza constructorul de copiere -la intoarcerea unui obiect prin referinta -nu se apeleaza constructorul de copiere */
38.921875
125
0.69169
553345d2e3f5d662bb794c85bfdcafd0b77fc691
8,688
cpp
C++
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
/* Public Domain Curses */ #include "Qurses/curspriv.h" RCSID("$Id: util.c,v 1.71 2008/07/13 16:08:18 wmcbrine Exp $") /*man-start************************************************************** Name: util Synopsis: char *unctrl(chtype c); void filter(void); void use_env(bool x); int delay_output(int ms); int getcchar(const cchar_t *wcval, wchar_t *wch, attr_t *attrs, short *color_pair, void *opts); int setcchar(cchar_t *wcval, const wchar_t *wch, const attr_t attrs, short color_pair, const void *opts); wchar_t *wunctrl(cchar_t *wc); int PDC_mbtowc(wchar_t *pwc, const char *s, size_t n); size_t PDC_mbstowcs(wchar_t *dest, const char *src, size_t n); size_t PDC_wcstombs(char *dest, const wchar_t *src, size_t n); Description: unctrl() expands the text portion of the chtype c into a printable string. Control characters are changed to the "^X" notation; others are passed through. wunctrl() is the wide- character version of the function. filter() and use_env() are no-ops in PDCurses. delay_output() inserts an ms millisecond pause in output. getcchar() works in two modes: When wch is not NULL, it reads the cchar_t pointed to by wcval and stores the attributes in attrs, the color pair in color_pair, and the text in the wide-character string wch. When wch is NULL, getcchar() merely returns the number of wide characters in wcval. In either mode, the opts argument is unused. setcchar constructs a cchar_t at wcval from the wide-character text at wch, the attributes in attr and the color pair in color_pair. The opts argument is unused. Currently, the length returned by getcchar() is always 1 or 0. Similarly, setcchar() will only take the first wide character from wch, and ignore any others that it "should" take (i.e., combining characters). Nor will it correctly handle any character outside the basic multilingual plane (UCS-2). Return Value: unctrl() and wunctrl() return NULL on failure. delay_output() always returns OK. getcchar() returns the number of wide characters wcval points to when wch is NULL; when it's not, getcchar() returns OK or ERR. setcchar() returns OK or ERR. Portability X/Open BSD SYS V unctrl Y Y Y filter Y - 3.0 use_env Y - 4.0 delay_output Y Y Y getcchar Y setcchar Y wunctrl Y PDC_mbtowc - - - PDC_mbstowcs - - - PDC_wcstombs - - - **man-end****************************************************************/ #if __QOR_UNICODE # ifdef PDC_FORCE_UTF8 # include <string.h> # else # include <stdlib.h> # endif #endif //------------------------------------------------------------------------------ char* unctrl( chtype c ) { __QCS_FCONTEXT( "unctrl" ); static char strbuf[3] = {0, 0, 0}; chtype ic; ic = c & A_CHARTEXT; if (ic >= 0x20 && ic != 0x7f) /* normal characters */ { strbuf[0] = (char)ic; strbuf[1] = '\0'; return strbuf; } strbuf[0] = '^'; /* '^' prefix */ if (ic == 0x7f) /* 0x7f == DEL */ strbuf[1] = '?'; else /* other control */ strbuf[1] = (char)(ic + '@'); return strbuf; } //------------------------------------------------------------------------------ void filter(void) { __QCS_FCONTEXT( "filter" ); } //------------------------------------------------------------------------------ void use_env(bool x) { __QCS_FCONTEXT( "use_env" ); } //------------------------------------------------------------------------------ int delay_output(int ms) { __QCS_FCONTEXT( "delay_output" ); return napms( ms ); } #if __QOR_UNICODE //------------------------------------------------------------------------------ int getcchar( const cchar_t* wcval, wchar_t* wch, attr_t* attrs, short* color_pair, void* opts ) { __QCS_FCONTEXT( "getchar" ); if (!wcval) return ERR; if (wch) { if (!attrs || !color_pair) return ERR; *wch = (*wcval & A_CHARTEXT); *attrs = (*wcval & (A_ATTRIBUTES & ~A_COLOR)); *color_pair = PAIR_NUMBER(*wcval & A_COLOR); if (*wch) *++wch = L'\0'; return 0; } else return ((*wcval & A_CHARTEXT) != L'\0'); } //------------------------------------------------------------------------------ int setcchar( cchar_t* wcval, const wchar_t* wch, const attr_t attrs, short color_pair, const void* opts ) { __QCS_FCONTEXT( "setcchar" ); if (!wcval || !wch) return ERR; *wcval = *wch | attrs | COLOR_PAIR(color_pair); return 0; } //------------------------------------------------------------------------------ wchar_t* wunctrl( cchar_t* wc ) { __QCS_FCONTEXT( "wunctrl" ); static wchar_t strbuf[3] = {0, 0, 0}; cchar_t ic; PDC_LOG(("wunctrl() - called\n")); ic = *wc & A_CHARTEXT; if (ic >= 0x20 && ic != 0x7f) /* normal characters */ { strbuf[0] = (wchar_t)ic; strbuf[1] = L'\0'; return strbuf; } strbuf[0] = '^'; /* '^' prefix */ if (ic == 0x7f) /* 0x7f == DEL */ strbuf[1] = '?'; else /* other control */ strbuf[1] = (wchar_t)(ic + '@'); return strbuf; } //------------------------------------------------------------------------------ int PDC_mbtowc(wchar_t *pwc, const char *s, size_t n) { __QCS_FCONTEXT( "PDC_mbtowc" ); # ifdef PDC_FORCE_UTF8 wchar_t key; int i = -1; const unsigned char *string; if (!s || (n < 1)) return -1; if (!*s) return 0; string = (const unsigned char *)s; key = string[0]; /* Simplistic UTF-8 decoder -- only does the BMP, minimal validation */ if (key & 0x80) { if ((key & 0xe0) == 0xc0) { if (1 < n) { key = ((key & 0x1f) << 6) | (string[1] & 0x3f); i = 2; } } else if ((key & 0xe0) == 0xe0) { if (2 < n) { key = ((key & 0x0f) << 12) | ((string[1] & 0x3f) << 6) | (string[2] & 0x3f); i = 3; } } } else i = 1; if (i) *pwc = key; return i; # else return mbtowc(pwc, s, n); # endif } //------------------------------------------------------------------------------ size_t PDC_mbstowcs(wchar_t *dest, const char *src, size_t n) { __QCS_FCONTEXT( "PDC_mbstowcs" ); # ifdef PDC_FORCE_UTF8 size_t i = 0, len; if (!src || !dest) return 0; len = strlen(src); while (*src && i < n) { int retval = PDC_mbtowc(dest + i, src, len); if (retval < 1) return -1; src += retval; len -= retval; i++; } # else size_t i = mbstowcs(dest, src, n); # endif dest[i] = 0; return i; } //------------------------------------------------------------------------------ size_t PDC_wcstombs(char *dest, const wchar_t *src, size_t n) { __QCS_FCONTEXT( "PDC_wcstombs" ); # ifdef PDC_FORCE_UTF8 size_t i = 0; if (!src || !dest) return 0; while (*src && i < n) { chtype code = *src++; if (code < 0x80) { dest[i] = code; i++; } else if (code < 0x800) { dest[i] = ((code & 0x07c0) >> 6) | 0xc0; dest[i + 1] = (code & 0x003f) | 0x80; i += 2; } else { dest[i] = ((code & 0xf000) >> 12) | 0xe0; dest[i + 1] = ((code & 0x0fc0) >> 6) | 0x80; dest[i + 2] = (code & 0x003f) | 0x80; i += 3; } } # else size_t i = wcstombs(dest, src, n); # endif dest[i] = '\0'; return i; } #endif
26.487805
106
0.436119
553c6630e13e876b18e0421953c8a53c297bc302
3,945
hpp
C++
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
#pragma once #include <atomic> #include "../../cpu.hpp" // cacheline_size #include "../../range.hpp" #include "../auxiliary/tagged.hpp" // TaggedData #include "io_descriptors.hpp" // core::{queue_reader, queue_writer} #include <vector> template <typename T, typename size_type=unsigned> class spsc_queue { friend core::queue_reader<spsc_queue>; friend core::queue_writer<spsc_queue>; struct too_many_readers : std::exception {}; struct too_many_writers : std::exception {}; public: using value_type = T; static constexpr core::u8 max_writers = 1; static constexpr core::u8 max_readers = 1; spsc_queue(size_t size=2048) : ring(size), _size(size) { for (auto& elem : ring) { elem.tag.store(false); } } core::queue_reader<spsc_queue> reader() { if (n_readers < 1) return {*this}; else throw too_many_readers{}; } core::queue_writer<spsc_queue> writer() { if (n_writers < 1) return {*this}; else throw too_many_writers{}; } bool try_pop(T & data) { auto index = read_from + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( filled ) { data = std::move(slot.data); slot.tag.store(false, std::memory_order_release); read_from = index; return true; } return false; } bool try_push(T const& data) { auto index = write_to + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( !filled ) { slot.data = data; slot.tag.store(true, std::memory_order_release); write_to = index; return true; } return false; } bool try_push(T && data) { auto index = write_to + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( !filled ) { slot.data = std::move(data); slot.tag.store(true, std::memory_order_release); write_to = index; return true; } return false; } void push(T const& data) { constexpr size_t n_spinwaits = 1;//100000; // std::cerr << "push...\n"; for (;;) { // std::cerr << "."; for (size_t _ : core::range(n_spinwaits)) { if (try_push(data)) return; } std::this_thread::yield(); } } void close() { active.store(false, std::memory_order_release); } bool closed() const { return !active.load(std::memory_order_acquire); } bool empty() const { return write_to == read_from; } explicit operator bool () const { return !(closed() && empty()); } void print_state() const { std::cerr << "Q: [" << read_from/*.load()*/ << " -> " << write_to/*.load()*/ << "] | active: " << std::boolalpha << active.load() << "\n"; std::cerr << "[ " << bool(*this) << " ]\n"; } void debug_ring() const { for (auto i : core::range(ring.size()) ) { auto& elem = ring[i]; char sym; auto filled = elem.tag.load(); if ( filled ) sym = '#'; else sym = ' '; if ( filled ) { std::cout << "[" << sym << "| " << elem.data << "]" << " @ " << i << "/" << ring.size() << "\n"; } } } private: std::vector< core::TaggedData<T, std::atomic<bool>> > ring; const size_type _size; alignas(core::device::CPU::cacheline_size) std::atomic<bool> active {true}; alignas(core::device::CPU::cacheline_size) size_type read_from {0}; unsigned n_readers {0}; alignas(core::device::CPU::cacheline_size) size_type write_to {0}; unsigned n_writers {0}; };
26.836735
146
0.532573
553fa9919d6f85475b1ce52b5cd98398731f4ede
29,505
cpp
C++
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
1
2017-01-07T09:44:20.000Z
2017-01-07T09:44:20.000Z
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2005-2006, Hajo Kirchhoff - Lit Window Productions, http://www.litwindow.com * This file is part of the Lit Window ODBC Library. All use of this material - copying * in full or part, including in other works, using in non-profit or for-profit work * and other uses - is governed by the licence contained in the Lit Window ODBC Library * distribution, file LICENCE.TXT * $Id: binder.cpp,v 1.10 2007/10/18 11:13:17 Hajo Kirchhoff Exp $ */ #include "stdafx.h" #include <sqlext.h> #include <litwindow/dataadapter.h> #include <litwindow/logging.h> #include <boost/bind.hpp> #include <boost/spirit/include/classic.hpp> #include <boost/spirit/include/classic_actor.hpp> #include <set> #include <iomanip> #include "litwindow/odbc/statement.h" #include <boost/uuid/uuid.hpp> #define new DEBUG_NEW using boost::uuids::uuid; template <> litwindow::tstring litwindow::converter<TIME_STRUCT>::to_string(const TIME_STRUCT &v) { basic_stringstream<TCHAR> out; if (v.hour<=23 && v.minute<=59 && v.second<=59) { const TCHAR *fmt=_T("%X"); struct tm t; memset(&t, 0, sizeof(t)); t.tm_hour=v.hour; t.tm_min=v.minute; t.tm_sec=v.second; use_facet<time_put<TCHAR> >(locale()).put(out.rdbuf(), out, _T(' '), &t, fmt, fmt+sizeof(fmt)/sizeof(*fmt)); } else { out << _T("time_invalid"); } return out.str(); } namespace { using namespace boost::spirit::classic; template <typename NumberValue> bool parse_time(const litwindow::tstring &newValue, NumberValue &hours, NumberValue &minutes, NumberValue &seconds) { hours=0; minutes=0; seconds=0; return parse( newValue.begin(), newValue.end(), limit_d(0u, 23u)[uint_parser<NumberValue, 10, 1, 2>()[assign_a(hours)]] >> !( limit_d(0u, 59u)[uint_parser<NumberValue, 10, 2, 2>()[assign_a(minutes)]] >> !limit_d(0u,59u)[uint_parser<NumberValue, 10, 2, 2>()[assign_a(seconds)]] ) >> !(as_lower_d[str_p(_T("am")) | str_p(_T("pm"))]) , space_p | chset_p(_T(":.-")) ).full; } }; template <> size_t litwindow::converter<TIME_STRUCT>::from_string(const litwindow::tstring &newValue, TIME_STRUCT &v) { ios_base::iostate st = 0; struct tm t; memset(&t, 0, sizeof(t)); { basic_istringstream<TCHAR> in(newValue); use_facet<time_get<TCHAR > >(locale()).get_time(in.rdbuf(), basic_istream<TCHAR>::_Iter(0), in, st, &t); } if (st & ios_base::failbit) { size_t hours=0, minutes=0, seconds=0; if (parse_time(newValue, hours, minutes, seconds)==false) { v.hour=v.minute=v.second=0; throw lwbase_error("invalid time format"); } else { v.hour=SQLUSMALLINT(hours); v.minute=SQLUSMALLINT(minutes); v.second=SQLUSMALLINT(seconds); } } else { v.hour=t.tm_hour; v.minute=t.tm_min; v.second=t.tm_sec; } return sizeof(TIME_STRUCT); } LWL_IMPLEMENT_ACCESSOR(TIME_STRUCT) namespace litwindow { namespace odbc {; #ifndef SQL_TVARCHAR #ifdef UNICODE #define SQL_TVARCHAR SQL_WVARCHAR #else #define SQL_TVARCHAR SQL_VARCHAR #endif #endif //#region binder public interface sqlreturn binder::bind_parameter(SQLUSMALLINT position, SQLSMALLINT in_out, SQLSMALLINT c_type, SQLSMALLINT sql_type, SQLULEN column_size, SQLSMALLINT decimal_digits, SQLPOINTER buffer, SQLLEN length, SQLLEN *len_ind) { bind_task bi; data_type_info &info=bi.m_bind_info; info.m_c_type=c_type; info.m_column_size=column_size; info.m_decimal=decimal_digits; info.m_len_ind_p=len_ind; info.m_position=position; info.m_sql_type=sql_type; info.m_target_ptr=buffer; info.m_target_size=length; info.m_type=0; bi.m_by_position=position; bi.m_in_out=in_out; m_parameters.add(bi); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_parameter(const bind_task &task) { m_parameters.add(task); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_parameter(SQLUSMALLINT pposition, const accessor &a, SQLSMALLINT in_out, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_position=pposition; bi.m_in_out=in_out; m_parameters.add(bi); } return rc; } sqlreturn binder::bind_parameter(const tstring &name, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_name=name; bi.m_in_out=unknown_bind_type; m_parameters.add(bi); } return rc; } sqlreturn binder::bind_parameter(const aggregate &a, solve_nested_names_enum solver) { return bind_aggregate(a, tstring(), solver, false); } sqlreturn binder::bind_column(SQLSMALLINT col, SQLSMALLINT c_type, SQLPOINTER target_ptr, SQLINTEGER size, SQLLEN* len_ind) { bind_task bi; bi.m_bind_info.m_c_type=c_type; bi.m_bind_info.m_target_ptr=target_ptr; bi.m_bind_info.m_target_size=size; bi.m_bind_info.m_position=col; bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_position=col; m_columns.add(bi); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_column(SQLSMALLINT col, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_by_position=col; if (len_ind) bi.m_bind_info.m_len_ind_p=len_ind; m_columns.add(bi); } return rc; } sqlreturn binder::bind_column(const tstring &column_name, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_by_name=column_name; if (len_ind) bi.m_bind_info.m_len_ind_p=len_ind; m_columns.add(bi); } return rc; } sqlreturn binder::bind_column(const aggregate &a, const tstring &table, solve_nested_names_enum solver) { return bind_aggregate(a, table, solver, true); } //#endregion sqlreturn binder::build_insert_statement_and_bind(tstring &sql, const tstring &table_name, statement *bind_to) const { tstring bind_parameters; size_t i; sqlreturn rc; if (m_columns.size()>0) { size_t last_element=m_columns.size()-1; SQLUSMALLINT parameter_index=0; for (i=0; i<=last_element && rc; ++i) { const bind_task &b(m_columns.get_bind_task(i)); if (b.m_bind_info.m_len_ind_p==0 || (*b.m_bind_info.m_len_ind_p!=SQL_IGNORE && *b.m_bind_info.m_len_ind_p!=SQL_DEFAULT)) { // bind values only if they are neither SQL_IGNORE or SQL_DEFAULT if (sql.length()==0) sql=_T("INSERT INTO ")+table_name+_T(" ("); else sql+=_T(", "); sql+= b.m_by_name; bind_parameters+= bind_parameters.length()>0 ? _T(", ?") : _T(") VALUES (?"); if (bind_to) { if (b.m_bind_info.m_accessor.is_valid()) rc=bind_to->bind_parameter_accessor(++parameter_index, SQL_PARAM_INPUT, b.m_bind_info.m_accessor, b.m_bind_info.m_len_ind_p); else rc=bind_to->bind_parameter(++parameter_index, SQL_PARAM_INPUT, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } } } } if (sql.length()==0) { return sqlreturn (_T("Table has no columns or all columns are being SQL_IGNORE-d. Cannot build insert statement."), err_logic_error); } sql+=bind_parameters + _T(")"); if (rc && bind_to) bind_to->set_statement(sql); return rc; } tstring binder::make_column_name(const tstring &c_identifier) { if (c_identifier.substr(0, 2)==_T("m_")) return c_identifier.substr(2); return c_identifier; } sqlreturn binder::bind_aggregate(const aggregate &a, size_t level, const tstring &prefix, solve_nested_names_enum solver, bool bind_to_columns) { sqlreturn rc; aggregate::iterator i; for (i=a.begin(); i!=a.end() && rc.ok(); ++i) { tstring column_name(make_column_name(s2tstring(i->get_name()))); tstring full_column_name; if ((solver & use_nested_levels)!=0 && prefix.length()>0) full_column_name=prefix+m_aggregate_scope_separator_char+column_name; else full_column_name=column_name; // attempt to bind the member as it is (completely) to a column. if (bind_to_columns) rc=bind_column(full_column_name, *i); else rc=bind_parameter(full_column_name, *i); if (rc.ok()==false) { // member could not be bound directly. See if it is an aggregate itself and bind its individual members if it is. if (i->is_aggregate()) { tstring new_prefix; if (i->is_inherited() && (solver&inheritance_as_nested)==0) new_prefix=prefix; else new_prefix=full_column_name; rc=bind_aggregate(i->get_aggregate(), level+1, new_prefix, solver, bind_to_columns); } } } return rc; } /// bind an aggregate adapter to the result columns sqlreturn binder::bind_aggregate(const aggregate &a, const tstring &prefix, solve_nested_names_enum solver, bool bind_to_columns) { tstring use_name; if (is_null(prefix)) use_name=s2tstring(a.get_class_name()); else use_name=prefix; return bind_aggregate(a, 0, use_name, solver, bind_to_columns); } sqlreturn binder::get_bind_info(const accessor &a, data_type_info &p_desc) { sqlreturn rc=data_type_lookup().get(a.get_type(), p_desc); if (rc.ok()) { p_desc.m_accessor=a; p_desc.m_target_ptr=a.get_member_ptr(); if (p_desc.m_target_size==0) p_desc.m_target_size=(SQLINTEGER)a.get_sizeof(); } return rc; } sqlreturn binder::do_bind_parameter(bind_task &b, statement &s) const { const parameter *p=s.get_parameter(b.m_by_position); if (p) { if (b.m_in_out==unknown_bind_type) { b.m_in_out=p->m_bind_type; } else if (b.m_in_out!=p->m_bind_type) { return sqlreturn(_("bind type used in the statement is different from bind parameter used in the C++ source")+b.m_by_name, odbc::err_logic_error); } } // else no parameter marker in statement sqlreturn rc=s.do_bind_parameter(b.m_by_position, b.m_in_out, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); return rc; } sqlreturn binder::do_bind_column(bind_task &b, statement &s) const { sqlreturn rc=s.do_bind_column(b.m_by_position, b.m_bind_info.m_c_type, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); return rc; } /** bind all parameters in the 'to bind' list to the statement. */ sqlreturn binder::do_bind_parameters(statement &s) { return m_parameters.prepare_binding(s, false); } sqlreturn binder::do_bind_columns(statement &s) { return m_columns.prepare_binding(s, true, s.get_column_count()); } sqlreturn binder::binder_lists::reset_bind_task_state(size_t pos, SQLINTEGER len_ind) { bind_task &b(m_elements[pos]); if (len_ind==statement::use_defaults) { if (b.m_bind_info.m_helper) // use the bind helper { *b.m_bind_info.m_len_ind_p= b.m_bind_info.m_helper->get_length(b.m_bind_info); } else if (b.m_bind_info.m_accessor.is_c_vector() && // use SQL_NTS if it is a char or wchar_t vector (old style C string) ((is_type<wchar_t>(b.m_bind_info.m_type) && b.m_bind_info.m_accessor.get_sizeof()>sizeof(wchar_t)) || (is_type<char>(b.m_bind_info.m_type) && b.m_bind_info.m_accessor.get_sizeof()>sizeof(char))) ) { *b.m_bind_info.m_len_ind_p=SQL_NTS; } else // use target_size as default size { *b.m_bind_info.m_len_ind_p=b.m_bind_info.m_target_size; } } else *b.m_bind_info.m_len_ind_p=len_ind; return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::reset_states(SQLINTEGER len_ind) { size_t i; for (i=0; i<m_elements.size(); ++i) { reset_bind_task_state(i, len_ind); } return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::set_column_state(SQLUSMALLINT col, SQLLEN len_ind) { if (col>=m_index.size()) return sqlreturn(_("no such column."), odbc::err_no_such_column); *m_index[col]->m_bind_info.m_len_ind_p=len_ind; return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::put() { sqlreturn rc; size_t i; for (i=0; i<m_elements.size() && rc; ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper) { rc=b.m_bind_info.m_helper->put_data(b.m_bind_info); } } return rc; } struct reset_intermediate_buffer_pointers { reset_intermediate_buffer_pointers(const unsigned char *buffer, SQLULEN size) { begin_ptr=buffer; if (buffer) end_ptr=buffer+size; else end_ptr=0; } const unsigned char *begin_ptr, *end_ptr; void operator()(SQLPOINTER &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } void operator()(SQLINTEGER * &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } #ifdef _WIN64 void operator()(SQLLEN * &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } #endif }; sqlreturn binder::binder_lists::prepare_binding(statement &s, bool bind_as_columns, size_t columns_to_expect) { if (columns_to_expect) m_index.resize(columns_to_expect+1, 0); sqlreturn rc; m_needs_bind=false; fill(m_index.begin(), m_index.end(), static_cast<bind_task*>(0)); // the 'intermediate' buffer will be reset in this method // some pointers (cache, len_ind_p) might point into the intermediate buffer // to find and reset them, store beginning and end of the intermediate buffer reset_intermediate_buffer_pointers reset_ptrs((const unsigned char*)m_intermediate_buffer.get(), m_intermediate_buffer_size); m_intermediate_buffer_size=0; size_t i; for (i=0; i<m_elements.size(); ++i) { bind_task &b(m_elements[i]); if (m_intermediate_buffer.get()) { // reset pointers if they point into an existing intermediate buffer reset_ptrs(b.m_bind_info.m_len_ind_p); reset_ptrs(b.m_bind_info.m_target_ptr); reset_ptrs(b.m_cache); reset_ptrs(b.m_cache_len_ind_p); } if (b.m_by_position==-1) { SQLSMALLINT p; if (bind_as_columns) { p=s.find_column(b.m_by_name); } else { p=s.find_parameter(b.m_by_name); if (p!=-1) { const parameter *para=s.get_parameter(p); if (b.m_in_out==unknown_bind_type) { b.m_in_out=para->m_bind_type; } else if (b.m_in_out!=para->m_bind_type) { return sqlreturn(_("bind type used in the statement is different from bind parameter used in the C++ source")+b.m_by_name, odbc::err_logic_error); } } } if (p==-1) { return sqlreturn(tstring(_("no such "))+(bind_as_columns ? _("column ") : _("parameter "))+b.m_by_name, bind_as_columns ? err_no_such_column : err_no_such_parameter); } b.m_by_position=p; } else { tstringstream str; str << _("#:") << b.m_by_position; b.m_by_name=str.str(); } if (b.m_by_position>=(SQLSMALLINT)m_index.size()) m_index.resize(b.m_by_position+1, 0); m_index[b.m_by_position]=&m_elements[i]; b.m_bind_info.m_position=b.m_by_position; if (b.m_bind_info.m_helper) { // this is an extended binder, prepare the intermediate buffer if neccessary m_intermediate_buffer_size+=b.m_bind_info.m_helper->prepare_bind_buffer(b.m_bind_info, s, bind_as_columns ? bindto : bind_type(b.m_in_out)); } if (bind_as_columns==false && (b.m_bind_info.m_column_size==0 || b.m_bind_info.m_column_size==SQL_NTS) && b.m_bind_info.m_accessor.is_valid()) { // no column size specified. Try to calculate it. if (is_type<char>(b.m_bind_info.m_accessor)) b.m_bind_info.m_column_size=SQLUINTEGER(b.m_bind_info.m_accessor.get_sizeof()/sizeof(char)-1); else if (is_type<wchar_t>(b.m_bind_info.m_accessor)) b.m_bind_info.m_column_size=SQLUINTEGER(b.m_bind_info.m_accessor.get_sizeof()/sizeof(wchar_t)-1); } if (b.m_bind_info.m_len_ind_p==0) { m_intermediate_buffer_size+=sizeof(SQLLEN); } if (has_cache() && b.m_bind_info.m_target_size) { m_intermediate_buffer_size+=b.m_bind_info.m_target_size+sizeof(SQLLEN); } } m_intermediate_buffer.reset(m_intermediate_buffer_size>0 ? new unsigned char[m_intermediate_buffer_size] : 0); unsigned char *buffer=m_intermediate_buffer.get(); m_needs_get=m_needs_put=false; SQLULEN size_left=m_intermediate_buffer_size; for (i=0; i<m_elements.size() && rc.ok(); ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper && b.m_bind_info.m_target_ptr==0 && b.m_bind_info.m_target_size>0) { if (b.m_bind_info.m_target_size>size_left) { return sqlreturn(_("extended bind helper requesting more buffer space than is available"), odbc::err_logic_error); } b.m_bind_info.m_target_ptr=buffer; buffer+=b.m_bind_info.m_target_size; size_left-=b.m_bind_info.m_target_size; if (bind_as_columns) m_needs_put=m_needs_get=true; else { m_needs_put= b.m_in_out==SQL_PARAM_INPUT || b.m_in_out==SQL_PARAM_INPUT_OUTPUT; m_needs_get= b.m_in_out==SQL_PARAM_INPUT_OUTPUT || b.m_in_out==SQL_PARAM_OUTPUT; } } if (b.m_bind_info.m_len_ind_p==0) { b.m_bind_info.m_len_ind_p=(SQLLEN*)buffer; reset_bind_task_state(i, statement::use_defaults); //*b.m_bind_info.m_len_ind_p=b.m_bind_info.m_target_size; buffer+=sizeof(SQLLEN); size_left-=sizeof(SQLLEN); } if (has_cache() && b.m_bind_info.m_target_size) { b.m_cache=(SQLPOINTER)buffer; buffer+=b.m_bind_info.m_target_size; b.m_cache_len_ind_p=(SQLLEN*)buffer; buffer+=sizeof(SQLLEN); m_needs_get=true; size_left-=sizeof(SQLLEN)+b.m_bind_info.m_target_size; } else { b.m_cache=0; b.m_cache_len_ind_p=0; } if (b.m_bind_info.m_target_size>0 && b.m_bind_info.m_target_ptr!=0) { if (bind_as_columns) { rc=s.do_bind_column(b.m_by_position, b.m_bind_info.m_c_type, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } else { if (b.m_bind_info.m_column_size==0) m_needs_bind=true; // dynamic column size needs rebinding every time rc=s.do_bind_parameter(b.m_by_position, b.m_in_out, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } } } return rc; } void binder::binder_lists::fix_SQL_NTS_len_ind_parameter_workaround(fix_workaround_enum action) { size_t pos; for (pos=0; pos<m_elements.size(); ++pos) { bind_task &b(m_elements[pos]); if (action==set_length) { b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute=false; if (b.m_in_out!=out && b.m_bind_info.m_len_ind_p && *b.m_bind_info.m_len_ind_p==SQL_NTS) { if (b.m_bind_info.m_c_type==SQL_C_CHAR) *b.m_bind_info.m_len_ind_p=(SQLINTEGER)strlen((const char*)b.m_bind_info.m_target_ptr) * sizeof(char); else if (b.m_bind_info.m_c_type==SQL_C_WCHAR) *b.m_bind_info.m_len_ind_p=(SQLINTEGER)wcslen((const wchar_t*)b.m_bind_info.m_target_ptr) * sizeof(wchar_t); b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute=true; } } else if (action==reset_length && b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute && b.m_in_out==in) { *b.m_bind_info.m_len_ind_p=SQL_NTS; } } } void binder::fix_SQL_NTS_len_ind_parameter_workaround(fix_workaround_enum action) { m_parameters.fix_SQL_NTS_len_ind_parameter_workaround(action); } SQLSMALLINT binder::find_column_or_parameter_by_target(const binder_lists &list, const const_accessor &a) const { size_t i; for (i=0; i<list.size() && a.is_alias_of(list.get_bind_task(i).m_bind_info.m_accessor)==false; ++i) ; return i<list.size() ? list.get_bind_task(i).m_by_position : -1; } SQLSMALLINT binder::find_column_by_target(const const_accessor &a) const { return find_column_or_parameter_by_target(m_columns, a); } sqlreturn binder::do_put_parameters(statement &s) { return m_parameters.put(); } sqlreturn binder::do_get_parameters(statement &s) { return sqlreturn(SQL_ERROR); } sqlreturn binder::binder_lists::do_get_columns_or_parameters(statement &s, bool type_is_columns) { if (type_is_columns==false) DebugBreak(); //TODO: get_parameters not implemented yet!!! size_t i; sqlreturn rc; for (i=0; i<m_elements.size() && rc.ok(); ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper) { rc=b.m_bind_info.m_helper->get_data(b.m_bind_info, s); } if (b.m_cache) { memcpy(b.m_cache, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size); *b.m_cache_len_ind_p=*b.m_bind_info.m_len_ind_p; } } return rc; } sqlreturn binder::do_get_columns(statement &s) { return m_columns.do_get_columns_or_parameters(s, true); } data_type_info no_column; tstring binder::dump_columns(TCHAR quote_char) const { size_t i; tstring rc; for (i=0; i<m_columns.size(); ++i) { if (rc.length()>0) rc.append(_T(", ")); if (quote_char) rc.append(1, quote_char); rc.append(m_columns.get_bind_task(i).m_by_name); if (quote_char) rc.append(1, quote_char); } return rc; } const data_type_info &binder::get_column(SQLSMALLINT pos) const { return m_columns.is_valid_column_index(pos) ? m_columns.get_bind_task_for_column(pos)->m_bind_info : no_column; } sqlreturn binder::get_column_length(SQLSMALLINT pos, SQLLEN &value) const { const data_type_info i=get_column(pos); if (&i==&no_column) return sqlreturn(_("no such column"), odbc::err_no_such_column); else if (i.m_len_ind_p==0) return sqlreturn(_("column not bound"), odbc::err_column_not_bound); value=*i.m_len_ind_p; return sqlreturn(SQL_SUCCESS); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // look up types typedef vector<data_type_info> data_type_info_register; data_type_info_register &get_data_type_info_register() { static data_type_info_register s_map; return s_map; } data_type_info_register::const_iterator find_data_type_info(prop_t type) { data_type_info_register::const_iterator rc=find(get_data_type_info_register().begin(), get_data_type_info_register().end(), type); return rc; } void data_type_lookup::add(const data_type_info &i, const data_type_registrar *) { #ifdef REGISTER_IS_A_SET pair<data_type_info_register::iterator, bool> insertion=get_data_type_info_register().insert(i); if (insertion.second==false) { lw_err() << _("Type cannot be inserted twice! ") << litwindow::s2tstring(i.m_type->get_type_name()) << endl; } #endif get_data_type_info_register().push_back(i); } sqlreturn data_type_lookup::get(prop_t type, data_type_info &i) { data_type_info_register &the_map(get_data_type_info_register()); data_type_info_register::const_iterator data=find_data_type_info(type); if (data==the_map.end()) data=find_if(the_map.begin(), the_map.end(), boost::bind(&data_type_info::can_handle, _1, type)); if (data==the_map.end()) return sqlreturn(_("There is no registered SQL binder for type ")+s2tstring(type->get_type_name()), odbc::err_no_such_type); i=*data; return sqlreturn(SQL_SUCCESS); } data_type_info::data_type_info(prop_t type, SQLSMALLINT c_type, SQLSMALLINT sql_type, size_t col_size, extended_bind_helper *bhelper) { m_sql_type=sql_type; m_c_type=c_type; m_type=type; m_helper=bhelper; m_column_size=(SQLUINTEGER)col_size; } namespace { static register_data_type<long> tlong(SQL_C_SLONG, SQL_INTEGER); static register_data_type<int> tint(SQL_C_SLONG, SQL_INTEGER); static register_data_type<short> tshort(SQL_C_SSHORT, SQL_INTEGER); static register_data_type<unsigned long> tulong(SQL_C_ULONG, SQL_INTEGER); static register_data_type<unsigned int>tuint(SQL_C_ULONG, SQL_INTEGER); static register_data_type<unsigned short> tushort(SQL_C_USHORT, SQL_INTEGER); #define LWODBC_SQL_C_BOOL SQL_C_CHAR static register_data_type<bool> tbool(/*LWODBC_SQL_C_BOOL*/SQL_C_BIT, SQL_CHAR); static register_data_type<char> tchar(SQL_C_CHAR, SQL_VARCHAR, 0); static register_data_type<wchar_t> twchar(SQL_C_WCHAR, SQL_WVARCHAR, 0); static register_data_type<TIMESTAMP_STRUCT> ttimestampstruct(SQL_C_TIMESTAMP, SQL_TIMESTAMP); static register_data_type<float> tfloat(SQL_C_FLOAT, SQL_REAL); static register_data_type<double> tdouble(SQL_C_DOUBLE, SQL_DOUBLE); static register_data_type<double> tdouble2(SQL_C_DOUBLE, SQL_FLOAT); static register_data_type<TIME_STRUCT> ttime_struct(SQL_C_TIME, SQL_TIME); struct tuuid_bind_helper:public extended_bind_helper { // unfortunately for us, uuid stores the uuid bytes in a different order // than used by ODBC (under Windows at least) virtual SQLULEN prepare_bind_buffer(data_type_info &info, statement &s, bind_type bind_howto) const { info.m_target_ptr=0; info.m_target_size=16; return 16; } virtual sqlreturn get_data(data_type_info &info, statement &s) const { typed_accessor<uuid> a=dynamic_cast_accessor<uuid>(info.m_accessor); if (info.m_len_ind_p && (*info.m_len_ind_p==SQL_NULL_DATA || *info.m_len_ind_p==0)) { a.set(uuid()); } else { boost::uint8_t guiddata[16]; boost::uint8_t *p=guiddata; const boost::uint8_t *g=(const boost::uint8_t*)info.m_target_ptr; *p++=g[3]; *p++=g[2]; *p++=g[1]; *p++=g[0]; *p++=g[5]; *p++=g[4]; *p++=g[7]; *p++=g[6]; memcpy(p, g+8, 8); uuid temp; std::copy(guiddata+0, guiddata+16, temp.begin()); a.set(temp); } return sqlreturn(SQL_SUCCESS); } sqlreturn put_data(data_type_info &info) const { if (info.m_len_ind_p==0 || (*info.m_len_ind_p!=SQL_NULL_DATA && *info.m_len_ind_p!=SQL_DEFAULT_PARAM)) { typed_accessor<uuid> a=dynamic_cast_accessor<uuid>(info.m_accessor); if (info.m_target_size<16) return sqlreturn(_("String data right truncation (tstring)"), err_data_right_truncated, _T("22001")); uuid val(a.get()); uuid::iterator src=val.begin(); boost::uint8_t *dst=(boost::uint8_t*)info.m_target_ptr; dst[3]=*src++; dst[2]=*src++; dst[1]=*src++; dst[0]=*src++; dst[5]=*src++; dst[4]=*src++; dst[7]=*src++; dst[6]=*src++; memcpy(dst+8, src, 8); } return sqlreturn(SQL_SUCCESS); } SQLINTEGER get_length(data_type_info &info) const { return 16; } } g_uuid_bind_helper; static register_data_type<uuid> tuuid(SQL_C_GUID, SQL_GUID, 0, &g_uuid_bind_helper); struct tstring_bind_helper:public extended_bind_helper { virtual SQLULEN prepare_bind_buffer(data_type_info &info, statement &s, bind_type bind_howto) const { SQLSMALLINT pos=info.m_position; SQLULEN sz; info.m_target_ptr=0; // tell the binder we need an intermediate buffer sqlreturn rc; if (bind_howto==bindto) { if (info.m_sql_type==SQL_TVARCHAR) sz=maximum_text_column_length_retrieved; else { rc=s.get_column_size(pos, sz); if (sz==0) sz=maximum_text_column_length_retrieved; // use default maximum size } } else { if (info.m_column_size==0) { typed_const_accessor<tstring> ta=dynamic_cast_accessor<tstring>(info.m_accessor); sz=SQLINTEGER(ta.get_ptr() ? ta.get_ptr()->length() : ta.get().length()); } else sz=info.m_column_size; } sz+=1; // trailing \0 character sz*=sizeof(TCHAR); // might be unicode representation info.m_target_size=rc.ok() ? sz : 0; // tell the binder the size of the intermediate buffer return sz; } virtual sqlreturn get_data(data_type_info &info, statement &s) const { sqlreturn rc; typed_accessor<tstring> a=dynamic_cast_accessor<tstring>(info.m_accessor); if (info.m_len_ind_p && (*info.m_len_ind_p==SQL_NULL_DATA || *info.m_len_ind_p==0)) a.set(_T("")); else a.set(tstring((const TCHAR*)info.m_target_ptr)); return sqlreturn(SQL_SUCCESS); } sqlreturn put_data(data_type_info &info) const { bool data_truncated=false; // if (info.m_len_ind_p) // *info.m_len_ind_p=SQL_NTS; if (info.m_len_ind_p==0 || (*info.m_len_ind_p!=SQL_NULL_DATA && *info.m_len_ind_p!=SQL_DEFAULT_PARAM)) { typed_accessor<tstring> a=dynamic_cast_accessor<tstring>(info.m_accessor); tstring *s=a.get_ptr(); size_t required_length; if (s) { required_length=s->length()*sizeof(TCHAR)+sizeof(TCHAR); if (required_length>info.m_target_size) { required_length=info.m_target_size; data_truncated=true; } memcpy(info.m_target_ptr, s->c_str(), required_length); } else { // needs temporary tstring tstring temp; a.get(temp); required_length=temp.length()*sizeof(TCHAR)+sizeof(TCHAR); if (required_length>info.m_target_size) { required_length=info.m_target_size; data_truncated=true; } memcpy(info.m_target_ptr, temp.c_str(), required_length); } } return data_truncated ? sqlreturn(_("String data right truncation (tstring)"), err_data_right_truncated, _T("22001")) : sqlreturn(SQL_SUCCESS); } SQLINTEGER get_length(data_type_info &info) const { return SQL_NTS; } } g_tstring_bind_helper; static register_data_type<tstring> ttstring(SQL_C_TCHAR, SQL_TVARCHAR, 0, &g_tstring_bind_helper); }; }; }; using namespace std; template <> litwindow::tstring litwindow::converter<TIMESTAMP_STRUCT>::to_string(const TIMESTAMP_STRUCT &v) { tstringstream str; str << setfill(_T('0')) << setw(4) << v.year << _T('-') << setw(2) << (unsigned)v.month << _T('-') << setw(2) << (unsigned)v.day << _T(' ') << setw(2) << (unsigned)v.hour << _T(':') << setw(2) << (unsigned)v.minute << _T(':') << setw(2) << (unsigned)v.second << _T('.') << v.fraction; return str.str(); } LWL_IMPLEMENT_ACCESSOR(TIMESTAMP_STRUCT);
35
285
0.716624
55418e97647308bed166a7a209cf7c44021f8800
560
cpp
C++
main/find-triplets-with-zero-sum/find-triplets-with-zero-sum.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/find-triplets-with-zero-sum/find-triplets-with-zero-sum.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
main/find-triplets-with-zero-sum/find-triplets-with-zero-sum.cpp
EliahKagan/old-practice-snapshot
1b53897eac6902f8d867c8f154ce2a489abb8133
[ "0BSD" ]
null
null
null
/*You are required to complete the function below*/ bool findTriplets(int *const a, const int n) { sort(a, a + n); for (auto i = 0; i != n; ++i) { const auto target = -a[i]; for (auto j = 0, k = n - 1; j < k; ) { const auto cur = a[j] + a[k]; if (cur < target) ++j; else if (cur != target) --k; else if (j == i) ++j; else if (k == i) --k; else return true; } } return false; }
25.454545
51
0.376786
554449e60a821f16c728c8c7d5f120483a2d48bd
3,792
cpp
C++
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
1
2022-03-26T01:48:11.000Z
2022-03-26T01:48:11.000Z
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
null
null
null
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
null
null
null
// Example.cpp - An example of the Particle System API in OpenGL // // Copyright 1999-2006, 2022 by David K. McAllister #include "Particle/pAPI.h" using namespace PAPI; // OpenGL #include "GL/glew.h" // This needs to come after GLEW #include "GL/freeglut.h" // For C++17 execution policy to get parallelism of particle actions #include <execution> ParticleContext_t P; // A water fountain spraying upward void ComputeParticles() { // Set the state of the new particles to be generated pSourceState S; S.Velocity(PDCylinder(pVec(0.0f, -0.01f, 0.25f), pVec(0.0f, -0.01f, 0.27f), 0.021f, 0.019f)); S.Color(PDLine(pVec(0.8f, 0.9f, 1.0f), pVec(1.0f, 1.0f, 1.0f))); // Generate particles along a very small line in the nozzle P.Source(200, PDLine(pVec(0.f, 0.f, 0.f), pVec(0.f, 0.f, 0.4f)), S); P.ParticleLoop(std::execution::par_unseq, [&](Particle_t& p_) { // Gravity P.Gravity(p_, pVec(0.f, 0.f, -0.01f)); // Bounce particles off a disc of radius 5 P.Bounce(p_, 0.f, 0.5f, 0.f, PDDisc(pVec(0.f, 0.f, 0.f), pVec(0.f, 0.f, 1.f), 5.f)); // Kill particles below Z=-3 P.Sink(p_, false, PDPlane(pVec(0.f, 0.f, -3.f), pVec(0.f, 0.f, 1.f))); // Move particles to their new positions P.Move(p_, true, false); }); P.CommitKills(); } // Draw each particle as a point using vertex arrays // To draw as textured point sprites just call glEnable(GL_POINT_SPRITE) before calling this function. void DrawGroupAsPoints() { size_t cnt = P.GetGroupCount(); if (cnt < 1) return; const float* ptr; size_t flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs, up3Ofs, rvel3Ofs, upB3Ofs, mass1Ofs, data1Ofs; cnt = P.GetParticlePointer(ptr, flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs, up3Ofs, rvel3Ofs, upB3Ofs, mass1Ofs, data1Ofs); if (cnt < 1) return; glEnable(GL_POINT_SMOOTH); glPointSize(4); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, int(flstride) * sizeof(float), ptr + color3Ofs); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, int(flstride) * sizeof(float), ptr + pos3Ofs); glDrawArrays(GL_POINTS, 0, (GLsizei)cnt); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } void Draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set up the view glLoadIdentity(); gluLookAt(0, -12, 3, 0, 0, 0, 0, 0, 1); // Draw the ground glColor3ub(0, 115, 0); glPushMatrix(); glTranslatef(0, 0, -1); glutSolidCylinder(5, 1, 20, 20); glPopMatrix(); // Do what the particles do ComputeParticles(); // Draw the particles DrawGroupAsPoints(); glutSwapBuffers(); } void Reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(40, w / double(h), 1, 100); glMatrixMode(GL_MODELVIEW); } int main(int argc, char** argv) { glutInit(&argc, argv); // Make a standard 3D window glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(800, 800); glutCreateWindow("Particle Example"); glutDisplayFunc(Draw); glutIdleFunc(Draw); glutReshapeFunc(Reshape); // We want depth buffering, etc. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Make a particle group int particleHandle = P.GenParticleGroups(1, 50000); P.CurrentGroup(particleHandle); P.TimeStep(0.1f); try { glutMainLoop(); } catch (PError_t& Er) { std::cerr << "Particle API exception: " << Er.ErrMsg << std::endl; throw Er; } return 0; }
26.893617
151
0.64847
55454bd5de6af9932b41977d05db0d82cd96ccc2
6,908
cpp
C++
libraries/RTIMULib/utility/RTPressureMS5803.cpp
uutzinger/RTIMULib2-Teensy
0901af6b69399b0f107c8bf1012e6361e3029b94
[ "MIT" ]
1
2021-05-16T16:24:27.000Z
2021-05-16T16:24:27.000Z
libraries/RTIMULib/utility/RTPressureMS5803.cpp
uutzinger/RTIMULib2-Teensy
0901af6b69399b0f107c8bf1012e6361e3029b94
[ "MIT" ]
null
null
null
libraries/RTIMULib/utility/RTPressureMS5803.cpp
uutzinger/RTIMULib2-Teensy
0901af6b69399b0f107c8bf1012e6361e3029b94
[ "MIT" ]
7
2016-09-04T23:01:26.000Z
2020-05-08T06:00:46.000Z
//////////////////////////////////////////////////////////////////////////// // // This file is part of RTIMULib // // Copyright (c) 2014-2015, richards-tech // // 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. // UU: This is new driver for RTIMULib #include "RTPressureMS5803.h" RTPressureMS5803::RTPressureMS5803(RTIMUSettings *settings) : RTPressure(settings) { } RTPressureMS5803::~RTPressureMS5803() { } int RTPressureMS5803::pressureGetPollInterval() { // return (400 / 122); // available: 0.54 / 1.06 / 2.08 / 4.13 / 8.22 ms // osr 4096 takes 8.22ms return (3); } bool RTPressureMS5803::reset() // Reset device I2C { unsigned char cmd = MS5611_CMD_RESET; if (!m_settings->HALRead(m_pressureAddr, cmd, 0, 0, "Failed to reset MS5803")) { return false; } else { return true; } } bool RTPressureMS5803::pressureInit() { unsigned char cmd = MS5611_CMD_PROM; unsigned char data[2]; m_pressureAddr = m_settings->m_I2CPressureAddress; // get calibration data // skip first and last entry in PROM table // C0= 0 // C1= 44428 // C2= 40264 // C3= 27988 // C4= 27027 // C5= 32849 // C6= 28630 // C7= 5 for (int i = 0; i <= 7; i++) { if (!m_settings->HALRead(m_pressureAddr, cmd, 2, data, "Failed to read MS5803 calibration data")) return false; m_calData[i] = (((uint16_t)data[0]) << 8) | ((uint16_t)data[1]); //printf("Cal index: %d, data: %d\n", i, m_calData[i]); cmd += 2; } m_state = MS5803_STATE_IDLE; return true; } bool RTPressureMS5803::pressureRead() { uint8_t data[3]; int32_t deltaT; int32_t temperature; int64_t offset; int64_t sens; int64_t T2; int64_t offset2; int64_t sens2; bool validReadings = false; switch (m_state) { case MS5803_STATE_IDLE: // start pressure conversion with maximum precision 4096 if (!m_settings->HALWrite(m_pressureAddr, MS5611_CMD_CONV_D1, 0, 0, "Failed to start MS5803 pressure conversion")) { return false; } else { m_state = MS5803_STATE_PRESSURE; m_timer = RTMath::currentUSecsSinceEpoch(); } break; case MS5803_STATE_PRESSURE: if ((RTMath::currentUSecsSinceEpoch() - m_timer) < 9040) // need to wait 10ms until conversion complete at highest precision return false; // not time yet if (!m_settings->HALRead(m_pressureAddr, MS5611_CMD_ADC, 3, data, "Failed to read MS5803 pressure")) { return false; } m_D1 = ((uint32_t)data[0] << 16) + ((uint32_t)data[1] << 8) + (uint32_t)data[2]; //printf("D1: %ld\n", m_D1); // start temperature conversion if (!m_settings->HALWrite(m_pressureAddr, MS5611_CMD_CONV_D2, 0, 0, "Failed to start MS5803 temperature conversion")) { return false; } else { m_state = MS5803_STATE_TEMPERATURE; m_timer = RTMath::currentUSecsSinceEpoch(); } break; case MS5803_STATE_TEMPERATURE: if ((RTMath::currentUSecsSinceEpoch() - m_timer) < 9040) // takes 10ms until conversion at highest precision return false; // not time yet if (!m_settings->HALRead(m_pressureAddr, MS5611_CMD_ADC, 3, data, "Failed to read MS58031 temperature")) { return false; } m_D2 = ((uint32_t)data[0] << 16) + ((uint32_t)data[1] << 8) + (uint32_t)data[2]; //printf("D2: %ld\n", m_D2); // now calculate temperature deltaT = m_D2 - ((int32_t)m_calData[5] << 8); temperature = (((int64_t)deltaT * m_calData[6]) >> 23) + 2000; //printf("deltaT: %ld\n", deltaT); //printf("temperature: %ld\n", temperature); // do second order temperature compensation if (temperature < 2000) { // low temperature below 20C T2 = 3 * (((int64_t)deltaT * deltaT) >> 33); offset2 = 3 * ((temperature - 2000) * (temperature - 2000)) / 2; sens2 = 5 * ((temperature - 2000) * (temperature - 2000)) / 8; if (temperature < -1500) { // below -15C offset2 = offset2 + 7 * ((temperature + 1500) * (temperature + 1500)); sens2 = sens2 + 4 * ((temperature + 1500) * (temperature + 1500)); } } else { // above 20C T2 = 7 * ((uint64_t)deltaT * deltaT)/pow(2,37); offset2 = (temperature - 2000) * (temperature - 2000) / 16; sens2 = 0; } // Now bring all together and apply offsets offset = ((int64_t)m_calData[2] << 16) + (((m_calData[4] * (int64_t)deltaT)) >> 7); sens = ((int64_t)m_calData[1] << 15) + (((m_calData[3] * (int64_t)deltaT)) >> 8); //printf("T2: %lld\n", T2); //printf("offset2: %lld\n", offset2); //printf("sens2: %lld\n", sens2); temperature = temperature - T2; offset = offset - offset2; sens = sens - sens2; //printf("temperature calib: %lld\n", temperature); //printf("offset calib: %lld\n", offset); //printf("sens calib: %lld\n", sens); // now lets calculate temperature compensated pressure m_pressureData.pressure = (RTFLOAT)(((m_D1 * sens)/ 2097152 - offset) / 32768) / 10.0; m_pressureData.temperature = (RTFLOAT)temperature/100.0; m_pressureData.temperatureValid = true; m_pressureData.pressureValid = true; m_pressureData.timestamp = RTMath::currentUSecsSinceEpoch(); //printf("Temp: %f, pressure: %f\n", m_pressureData.temperature, m_pressureData.pressure); validReadings = true; m_state = MS5803_STATE_IDLE; break; } if (validReadings) { return true; } else { return false; } }
34.713568
132
0.604661
5545628e382e2f84e9ad33d63a872f72b56334fc
1,281
hpp
C++
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
3
2016-02-24T09:22:16.000Z
2021-04-06T03:04:21.000Z
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
null
null
null
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
6
2015-04-26T07:16:44.000Z
2020-11-23T06:31:07.000Z
/* * File: cql_uuid_t.hpp * Author: mc * * Created on September 26, 2013, 12:35 PM */ #ifndef CQL_UUID_HPP_ #define CQL_UUID_HPP_ #include <functional> namespace cql { class cql_uuid_t; } namespace std { // template<> // struct hash<cql::cql_uuid_t>; } namespace cql { class cql_uuid_t { public: // TODO: This is currently implemented as simple long // but soon we switch to official UUID implementation // as described here: // http://www.ietf.org/rfc/rfc4122.txt static cql_uuid_t create(); friend bool operator <(const cql_uuid_t& left, const cql_uuid_t& right); private: cql_uuid_t(unsigned long uuid): _uuid(uuid) { } unsigned long _uuid; // friend struct std::hash<cql_uuid_t>; }; } // namespace std { // template<> // struct hash<cql::cql_uuid_t> { // public: // typedef // cql::cql_uuid_t // argument_type; // typedef // size_t // result_type; // size_t // operator ()(const cql::cql_uuid_t& id) const { // return // ((id._uuid * 3169) << 16) + // ((id._uuid * 23) << 8) + // id._uuid; // } // }; // } #endif /* CQL_UUID_HPP_ */
18.042254
64
0.551132
5546642ce4eec804341472684f579415e01994e1
641
cpp
C++
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "DataExchangerP.h" namespace fvmsolver { DataExchangerP::DataExchangerP(uPtrDataPort spData) : spData_(std::move(spData)), data_(*spData_) { } void DataExchangerP::assignCurrentCellValues(size_t step) { size_t numUw_ = data_.getNumUStarW(step) - 1; size_t numUe_ = data_.getNumUStarE(step) - 1; size_t numVn_ = data_.getNumVStarN(step) - 1; size_t numVs_ = data_.getNumVStarS(step) - 1; dw_var_ = data_.get_deU(numUw_); de_var_ = data_.get_deU(numUe_); dn_var_ = data_.get_deV(numVn_); ds_var_ = data_.get_deV(numVs_); } }
27.869565
63
0.631825
554761e1a836a0c8b0f900513094b1f845556219
5,192
cpp
C++
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
#include "yphysres.h" #include "ycolshape.hpp" #include "pmem.hpp" struct ycolshapes_t { int count; ycolshape_t *pool; }; static ycolshapes_t g_ycolshapes; int ycolshape_init(int count) { size_t size_max, align_max; ycolshape_t *cs; #define FIND_SIZES(t) \ if (sizeof(t) > size_max) size_max = sizeof(t); \ if (PMEM_ALIGNOF(t) > align_max) align_max = PMEM_ALIGNOF(t); size_max = align_max = 0; FIND_SIZES(btBoxShape); FIND_SIZES(btHeightfieldTerrainShape); FIND_SIZES(btCompoundShape); FIND_SIZES(btSphereShape); #undef FIND_SIZES g_ycolshapes.count = count; g_ycolshapes.pool = (ycolshape_t*)pmem_alloc(PMEM_ALIGNOF(ycolshape_t), sizeof(ycolshape_t) * count); if (!g_ycolshapes.pool) return YPHYSRES_CANNOT_INIT; for (int i = 0; i < count; ++i ) { cs = ycolshape_get(i); cs->vacant = 1; cs->shape_box = 0; cs->shape_sphere = 0; cs->shape_hmap = 0; cs->shape_comp = 0; cs->shape_convex = 0; cs->shape = 0; cs->data = 0; cs->comp = cs->comp_children = cs->comp_next = cs->comp_prev = 0; cs->vehs = 0; cs->rbs = 0; } for (int i = 0; i < count; ++i) if (!(ycolshape_get(i)->data = (char*)pmem_alloc(align_max, size_max))) return YPHYSRES_CANNOT_INIT; return YPHYSRES_OK; } void ycolshape_done(void) { ycolshape_t *cs; if (!g_ycolshapes.pool) return; for (int i = 0; i < g_ycolshapes.count; ++i) { cs = ycolshape_get(i); if (cs->data) { ycolshape_free(cs); pmem_free(cs->data); } } pmem_free(g_ycolshapes.pool); g_ycolshapes.pool = 0; } ycolshape_t * ycolshape_get(int colshapei) { if (colshapei >= 0 && colshapei < g_ycolshapes.count) return g_ycolshapes.pool + colshapei; else return 0; } int ycolshape_free(ycolshape_t *cs) { if (cs->vacant == 1) return YPHYSRES_INVALID_CS; if (cs->comp_children || cs->vehs || cs->rbs) return YPHYSRES_CS_HAS_REFS; cs->vacant = 1; if (cs->comp) { try { cs->comp->shape_comp->removeChildShape(cs->shape); } catch (...) { return YPHYSRES_INTERNAL; } if (cs->comp->comp_children == cs) cs->comp->comp_children = cs->comp_next; if (cs->comp_prev) cs->comp_prev->comp_next = cs->comp_next; if (cs->comp_next) cs->comp_next->comp_prev = cs->comp_prev; cs->comp = 0; cs->comp_prev = 0; cs->comp_next = 0; } if (cs->shape) { try { cs->shape->~btCollisionShape(); } catch (...) { return YPHYSRES_INTERNAL; } } cs->shape = 0; cs->shape_convex = 0; cs->shape_box = 0; cs->shape_hmap = 0; cs->shape_comp = 0; return YPHYSRES_OK; } int ycolshape_alloc_box(ycolshape_t *cs, float *size) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_box = new (cs->data) btBoxShape(btVector3(size[0], size[1], size[2])); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_box; cs->shape_convex = cs->shape_box; return YPHYSRES_OK; } int ycolshape_alloc_sphere(ycolshape_t *cs, float r) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_sphere = new (cs->data) btSphereShape(r); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_sphere; cs->shape_convex = cs->shape_sphere; return YPHYSRES_OK; } int ycolshape_alloc_hmap(ycolshape_t *cs, float *hmap, int width, int length, float hmin, float hmax, float *scale) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_hmap = new (cs->data) btHeightfieldTerrainShape(width, length, hmap, 1, hmin, hmax, 1, PHY_FLOAT, false); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape_hmap->setLocalScaling(btVector3(scale[0], scale[1], scale[2])); cs->shape = cs->shape_hmap; return YPHYSRES_OK; } int ycolshape_alloc_comp(ycolshape_t *cs) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_comp = new (cs->data) btCompoundShape(); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_comp; return YPHYSRES_OK; } int ycolshape_comp_add(ycolshape_t *prt, float *matrix, ycolshape_t *chd) { if (!prt->shape_comp || !chd->shape || chd->shape_comp || chd->comp) return YPHYSRES_INVALID_CS; chd->comp = prt; chd->comp_next = prt->comp_children; if (prt->comp_children) prt->comp_children->comp_prev = chd; prt->comp_children = chd; try { btTransform tm; tm.setFromOpenGLMatrix(matrix); prt->shape_comp->addChildShape(tm, chd->shape); } catch (...) { return YPHYSRES_INTERNAL; } return YPHYSRES_OK; }
27.764706
79
0.578005
554a6cc43c83e5ad46f4ae32c3288a1875b434a5
782
cpp
C++
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "ImagingException.h" #include "Tools.h" using namespace std; using namespace Tools; ImagingException::ImagingException(HRESULT result) : error (::GetLastError()) , result (result) { DWORD flags (FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS); HMODULE source (GetModuleHandle(L"imaging.dll")); vector<wchar_t> buffer(100); ::FormatMessage ( flags // dwFlags , source // lpSource , error // dwMessageId , 0 // dwLanguageId , &buffer[0] // pBuffer , buffer.size() // nSize , NULL // Arguments ); message = ConvertToAnsi(&buffer[0]); } const char * ImagingException::what() const { return message.c_str(); }
24.4375
104
0.643223
554cc503f4f76c472445fe6d598a53bf39690230
571
cpp
C++
CONTESTS/CODEFORCES/div2 844/A.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
CONTESTS/CODEFORCES/div2 844/A.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
CONTESTS/CODEFORCES/div2 844/A.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; int vis[200]; int main() { // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); std::ios_base::sync_with_stdio(false); cin.tie(0); int k; string s; cin>>s>>k; if(k>s.size()) cout<<"impossible"<<endl; else { int cnt=0; for(int i=0; i<s.size(); i++) if(!vis[s[i]]) { vis[s[i]] =1; cnt++; } cout<<max(0, k-cnt)<<endl; } return 0; }
14.641026
45
0.436077
55500631f687f3ca724aa7dc4096cbb61ef2bf1b
1,385
cpp
C++
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
#include <gpio.h> #include <textio.h> #include <usart.h> #include <hardware/tm1637.h> #include <button.h> static const pin_t LED = PA5; static const pin_t PROBE = PA8; static const int SERIAL_USART = 2; static const pin_t SERIAL_TX = PA2; static const pin_t SERIAL_RX = PA3; static const interrupt_t SERIAL_ISR = interrupt::USART2; static const int AUX_TIMER_NO = 7; static const interrupt_t AUX_TIMER_ISR = interrupt::TIM7; using led = output_t<LED>; using probe = output_t<PROBE>; using aux = tim_t<AUX_TIMER_NO>; using disp0 = tm1637_t<4, 1, 1, PC6, PC8>; using disp1 = tm1637_t<4, 1, 2, PA11, PA12>; using disp2 = tm1637_t<4, 1, 3, PB11, PB12>; using serial = usart_t<SERIAL_USART, SERIAL_TX, SERIAL_RX>; template<typename DISPLAY> void write(float x) { char str[8]; sprintf(str, "%7.4f", x); DISPLAY::write_string(str); } int main() { led::setup(); probe::setup(); serial::setup<230400>(); interrupt::set<SERIAL_ISR>(); interrupt::enable(); printf<serial>("DRO Version 0.1\n"); disp0::setup<10000>(); disp1::setup<10000>(); disp2::setup<10000>(); for (uint16_t i = 0;; ++i) { write<disp0>(static_cast<float>(i) * 0.1239); write<disp1>(static_cast<float>(i) * 3.12378); write<disp2>(static_cast<float>(i) * 17.08); } }
23.083333
60
0.625993
5552af8f77f4820aa092974e975ca5b5c22bb4bd
2,269
cc
C++
src/sampler/random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
762
2020-01-16T02:44:50.000Z
2022-03-30T10:03:36.000Z
src/sampler/random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
161
2020-01-20T07:47:38.000Z
2022-03-11T15:19:10.000Z
src/sampler/random_sampler.cc
TheTimmy/decord
67bfd14e4ae50b2751e7b92b73c6d73df35cbdaf
[ "Apache-2.0" ]
77
2020-01-23T17:47:20.000Z
2022-03-28T10:12:19.000Z
/*! * Copyright (c) 2019 by Contributors if not otherwise specified * \file random_file_order_sampler.cc * \brief Randomly shuffle file order but not internal frame order */ #include "random_sampler.h" #include <algorithm> #include <dmlc/logging.h> namespace decord { namespace sampler { RandomSampler::RandomSampler(std::vector<int64_t> lens, std::vector<int64_t> range, int bs, int interval, int skip) : bs_(bs), curr_(0) { CHECK(range.size() % 2 == 0) << "Range (begin, end) size incorrect, expected: " << lens.size() * 2; CHECK_EQ(lens.size(), range.size() / 2) << "Video reader size mismatch with range: " << lens.size() << " vs " << range.size() / 2; // output buffer samples_.resize(bs); // visit order for shuffling visit_order_.clear(); for (size_t i = 0; i < lens.size(); ++i) { auto begin = range[i*2]; auto end = range[i*2 + 1]; if (end < 0) { // allow negative indices, e.g., -20 means total_frame - 20 end = lens[i] - end; } CHECK_GE(end, 0) << "Video{" << i << "} has range end smaller than 0: " << end; CHECK(begin < end) << "Video{" << i << "} has invalid begin and end config: " << begin << "->" << end; CHECK(end < lens[i]) << "Video{" << i <<"} has range end larger than # frames: " << lens[i]; int64_t bs_skip = bs * (1 + interval) - interval + skip; int64_t bs_length = bs_skip - skip; for (int64_t b = begin; b + bs_length < end; b += bs_skip) { int offset = 0; for (int j = 0; j < bs; ++j) { samples_[j] = std::make_pair(i, b + offset); offset += interval + 1; } visit_order_.emplace_back(samples_); } } } void RandomSampler::Reset() { // shuffle orders std::random_shuffle(visit_order_.begin(), visit_order_.end()); // reset visit idx curr_ = 0; } bool RandomSampler::HasNext() const { return curr_ < visit_order_.size(); } const Samples& RandomSampler::Next() { CHECK(HasNext()); CHECK_EQ(samples_.size(), bs_); samples_ = visit_order_[curr_++]; return samples_; } size_t RandomSampler::Size() const { return visit_order_.size(); } } // sampler } // decord
31.513889
134
0.578228
55554a9d591a8c787954592b1ccf0f098e863c22
695
cpp
C++
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2021-12-25T16:37:53.000Z
2021-12-25T16:37:53.000Z
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2022-03-07T11:46:27.000Z
2022-03-07T11:46:27.000Z
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
null
null
null
/* * SPDX-License-Identifier: MIT * Copyright (c) 2022 Jai Bellare * See <https://opensource.org/licenses/MIT/> or LICENSE.md * Project homepage: https://github.com/strangeQuark1041/samarium */ #include "Spring.hpp" namespace sm { [[nodiscard]] auto Spring::length() const noexcept -> f64 { return math::distance(p1.pos, p2.pos); } void Spring::update() noexcept { const auto vec = p2.pos - p1.pos; const auto spring = (vec.length() - rest_length) * stiffness; auto damp = Vector2::dot(vec.normalized(), p2.vel - p1.vel) * damping; const auto force = vec.with_length(spring + damp); p1.apply_force(force); p2.apply_force(-force); } } // namespace sm
26.730769
100
0.666187
55566650381b23567922169592f96bac20617ea6
948
cpp
C++
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<unsigned int>> dp(m, vector<unsigned int> (n,0)); if(obstacleGrid[0][0] == 1) return 0; dp[0][0]=1; //first row for(int i=1; i<n; i++) { if(obstacleGrid[0][i] == 0 && dp[0][i-1]==1) dp[0][i]=1; } //first column for(int i=1; i<m; i++) { if(obstacleGrid[i][0] == 0 && dp[i-1][0]==1) dp[i][0]=1; } for(int i=1; i<m; i++) { for(int j=1; j<n; j++) { if(obstacleGrid[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } };
23.7
71
0.369198