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
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
int64
1
48.5k
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
int64
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
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
312d41d25311b474d2ed730983e75152652e32a4
7,304
cpp
C++
SmartRally/SCBW/api.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
8
2015-04-03T16:50:59.000Z
2021-01-06T17:12:29.000Z
SmartRally/SCBW/api.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-03T18:10:56.000Z
2016-02-18T05:04:21.000Z
SmartRally/SCBW/api.cpp
idmontie/gptp
14d68e5eac84c2f3085ac25a7fff31a07ea387f6
[ "0BSD" ]
6
2015-04-04T04:37:33.000Z
2018-04-09T09:03:50.000Z
#include "api.h" #include "scbwdata.h" #include <SCBW/UnitFinder.h> #include <algorithm> #include <cassert> #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> namespace scbw { const u32 Func_PrintText = 0x0048CD30; void printText(const char* text, u32 color) { if (!text) return; DWORD gtc = GetTickCount() + 7000; __asm { PUSHAD PUSH 0 ;//unknown MOV eax, text PUSH gtc PUSH color CALL Func_PrintText POPAD } } const u32 Func_PlaySound = 0x0048ED50; void playSound(u32 sfxId, const CUnit *sourceUnit) { __asm { PUSHAD PUSH 0 PUSH 1 MOV ESI, sourceUnit MOV EBX, sfxId CALL Func_PlaySound POPAD } } const u32 Func_ShowErrorMessageWithSfx = 0x0048EE30; void showErrorMessageWithSfx(u32 playerId, u32 statTxtId, u32 sfxId) { __asm { PUSHAD MOV ESI, sfxId MOV EDI, statTxtId MOV EBX, playerId CALL Func_ShowErrorMessageWithSfx POPAD } } // Logically equivalent to function @ 0x004C36F0 const char* getStatTxtTblString(u16 index) { if (index == 0) return NULL; else if (index <= **statTxtTbl) return (char*)(*statTxtTbl) + (*statTxtTbl)[index]; else return ""; } u32 getUnitOverlayAdjustment(const CUnit* const unit) { if (Unit::BaseProperty[unit->id] & UnitProperty::MediumOverlay) return 1; else if (Unit::BaseProperty[unit->id] & UnitProperty::LargeOverlay) return 2; else return 0; } //-------- Weapon related --------// //Identical to function @ 0x00475CE0 bool canWeaponTargetUnit(u8 weaponId, const CUnit *target, const CUnit *attacker) { if (weaponId >= WEAPON_TYPE_COUNT) return false; if (target == NULL) return Weapon::TargetFlags[weaponId].terrain; if (target->status & UnitStatus::Invincible) return false; const TargetFlag tf = Weapon::TargetFlags[weaponId]; const u32 targetProps = Unit::BaseProperty[target->id]; if ((target->status & UnitStatus::InAir) ? !tf.air : !tf.ground) return false; if (tf.mechanical && !(targetProps & UnitProperty::Mechanical)) return false; if (tf.organic && !(targetProps & UnitProperty::Organic)) return false; if (tf.nonBuilding && (targetProps & UnitProperty::Building)) return false; if (tf.nonRobotic && (targetProps & UnitProperty::RoboticUnit)) return false; if (tf.orgOrMech && !(targetProps & (UnitProperty::Organic | UnitProperty::Mechanical))) return false; if (tf.playerOwned && target->playerId != attacker->playerId) return false; return true; } const u32 Func_FireUnitWeapon = 0x00479C90; void fireUnitWeapon(CUnit* unit, u8 weaponId) { if (weaponId >= WEAPON_TYPE_COUNT) return; u32 _weaponId = weaponId; __asm { PUSHAD PUSH _weaponId MOV ESI, unit CALL Func_FireUnitWeapon POPAD } } const u32 Func_CreateUnitAtPos = 0x004CD360; //AKA createUnitXY() CUnit* createUnitAtPos(u16 unitType, u16 playerId, u32 x, u32 y) { if (unitType >= UNIT_TYPE_COUNT) return NULL; CUnit* unit; __asm { PUSHAD MOV CX, unitType MOV AX, playerId PUSH y PUSH x CALL Func_CreateUnitAtPos MOV unit, EAX POPAD } return unit; } const u32 Func_CanBeEnteredBy = 0x004E6E00; //AKA CanEnterTransport() bool canBeEnteredBy(const CUnit* transport, const CUnit* unit) { u32 result; __asm { PUSHAD MOV EAX, transport PUSH unit CALL Func_CanBeEnteredBy MOV result, EAX POPAD } return result != 0; } //-------- isUnderDarkSwarm() --------// class DarkSwarmFinderProc: public UnitFinderCallbackMatchInterface { public: bool match(const CUnit *unit) { return unit->id == UnitId::Spell_DarkSwarm; } }; bool isUnderDarkSwarm(const CUnit *unit) { static UnitFinder darkSwarmFinder; static DarkSwarmFinderProc dsFinder; darkSwarmFinder.search(unit->getLeft(), unit->getTop(), unit->getRight(), unit->getBottom()); return darkSwarmFinder.getFirst(dsFinder) != NULL; } // Improved code from BWAPI's include/BWAPI/Position.h: getApproxDistance() // Logically same as function @ 0x0040C360 u32 getDistanceFast(s32 x1, s32 y1, s32 x2, s32 y2) { int dMax = abs(x1 - x2), dMin = abs(y1 - y2); if (dMax < dMin) std::swap(dMax, dMin); if (dMin <= (dMax >> 2)) return dMax; return (dMin * 3 >> 3) + (dMin * 3 >> 8) + dMax - (dMax >> 4) - (dMax >> 6); } u8 getUpgradeLevel(const u8 playerId, const u8 upgradeId) { assert(playerId < PLAYER_COUNT); assert(upgradeId < 61); if (upgradeId < 46) return Upgrade::CurrentUpgSc->level[playerId][upgradeId]; else return Upgrade::CurrentUpgBw->level[playerId][upgradeId - 46]; } u32 getSupplyAvailable(u8 playerId, u8 raceId) { assert(raceId <= 2); assert(playerId < 12); u32 supplyProvided; if (isCheatEnabled(CheatFlags::FoodForThought)) supplyProvided = raceSupply[raceId].max[playerId]; else supplyProvided = raceSupply[raceId].provided[playerId]; return supplyProvided - raceSupply[raceId].used[playerId]; } u8 getRaceId(u16 unitId) { assert(unitId < UNIT_TYPE_COUNT); GroupFlag ugf = Unit::GroupFlags[unitId]; if (ugf.isZerg) return 0; else if (ugf.isTerran) return 1; else if (ugf.isProtoss) return 2; else return 4; } const u32 Func_GetGroundHeightAtPos = 0x004BD0F0; u32 getGroundHeightAtPos(s32 x, s32 y) { u32 height; __asm { PUSHAD MOV EAX, y MOV ECX, x CALL Func_GetGroundHeightAtPos MOV height, EAX POPAD } return height; } void refreshScreen(int left, int top, int right, int bottom) { left >>= 4; right = (right + 15) >> 4; top >>= 4; bottom = (bottom + 15) >> 4; if (left > right) std::swap(left, right); if (top > bottom) std::swap(top, bottom); //Rect out of bounds if (left >= 40 || right < 0 || top >= 30 || bottom < 0) return; left = std::max(left, 0); right = std::min(right, 40 - 1); top = std::max(top, 0); bottom = std::min(bottom, 30 - 1); for (int y = top; y <= bottom; ++y) memset(&refreshRegions[40 * y + left], 1, right - left + 1); } void refreshScreen() { memset(refreshRegions, 1, 1200); } //Logically equivalent to function @ 0x004C36C0 void refreshConsole() { u32* const bCanUpdateCurrentButtonSet = (u32*) 0x0068C1B0; u8* const bCanUpdateSelectedUnitPortrait = (u8*) 0x0068AC74; u8* const bCanUpdateStatDataDialog = (u8*) 0x0068C1F8; u32* const someDialogUnknown = (u32*) 0x0068C1E8; u32* const unknown2 = (u32*) 0x0068C1EC; *bCanUpdateCurrentButtonSet = 1; *bCanUpdateSelectedUnitPortrait = 1; *bCanUpdateStatDataDialog = 1; *someDialogUnknown = 0; *unknown2 = 0; } u16 random() { if (*IS_IN_GAME_LOOP) { *lastRandomNumber = 22695477 * (*lastRandomNumber) + 1; return (*lastRandomNumber >> 16) % 32768; //Make a number between 0 and 32767 } else return 0; } u32 randBetween(u32 min, u32 max) { assert(min <= max); return min + ((max - min + 1) * random() >> 15); } } //scbw
24.928328
96
0.638828
idmontie
312dac6c9463b0fbf8db138b6b3babc03dda13dd
3,467
cpp
C++
Kyrie/Hotkeys.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Kyrie/Hotkeys.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
Kyrie/Hotkeys.cpp
wangxh1007/ddmk
a6ff276d96b663e71b3ccadabc2d92c50c18ebac
[ "Zlib" ]
null
null
null
#include "Hotkeys.h" void Hotkeys_TogglePause(BYTE * state) { static bool execute = true; BYTE keys[] = { DIK_LCONTROL, DIK_D, }; uint8 keysDown = 0; for (uint8 i = 0; i < countof(keys); i++) { if (state[keys[i]] & 0x80) { keysDown++; } } if (keysDown == countof(keys)) { if (execute) { pause = !pause; PostMessageA(mainWindow, DM_PAUSE, 0, 0); execute = false; } } else { execute = true; } } // // // // // // // // // // // // // // // // // //// add save check! // //void Hotkeys::Exit(BYTE * buffer) //{ // static bool execute = true; // BYTE keys[] = // { // DIK_LALT, // DIK_F4, // }; // uint8 keysDown = 0; // for (uint8 i = 0; i < countof(keys); i++) // { // if (buffer[keys[i]] & 0x80) // { // keysDown++; // } // } // if (keysDown == countof(keys)) // { // if (execute) // { // PostMessageA(mainWindow, WM_QUIT, 0, 0); // execute = false; // } // } // else // { // execute = true; // } //} // // // // // // // // // // // //void Hotkeys::MenuController(BYTE * state) //{ // using namespace System::Input; // using namespace Game::Actor; // BYTE * gamepadAddr = *(BYTE **)(me32.modBaseAddr + 0xF2432C); // if (!gamepadAddr) // { // return; // } // if (InControl()) // { // return; // } // DWORD off[MAX_ACTOR] = // { // 0x3C, // 0x308, // 0x5D4, // 0x8A0 // }; // DWORD map[][2] = // { // { MTF_GAMEPAD_START, DIK_ESCAPE }, // { MTF_GAMEPAD_DPAD_UP, DIK_UP }, // { MTF_GAMEPAD_DPAD_RIGHT, DIK_RIGHT }, // { MTF_GAMEPAD_DPAD_DOWN, DIK_DOWN }, // { MTF_GAMEPAD_DPAD_LEFT, DIK_LEFT }, // { MTF_GAMEPAD_LEFT_SHOULDER, DIK_N }, // { MTF_GAMEPAD_RIGHT_SHOULDER, DIK_SPACE }, // { MTF_GAMEPAD_Y, DIK_Y }, // { MTF_GAMEPAD_B, DIK_B }, // { MTF_GAMEPAD_A, DIK_A }, // { MTF_GAMEPAD_X, DIK_X }, // { MTF_GAMEPAD_LEFT_STICK_UP, DIK_UP }, // { MTF_GAMEPAD_LEFT_STICK_RIGHT, DIK_RIGHT }, // { MTF_GAMEPAD_LEFT_STICK_DOWN, DIK_DOWN }, // { MTF_GAMEPAD_LEFT_STICK_LEFT, DIK_LEFT } // }; // for (uint8 device = ACTOR_TWO; device < MAX_ACTOR; device++) // { // DWORD & buttons = *(DWORD *)(gamepadAddr + off[device] + 0x15C); // for (uint8 index = 0; index < countof(map); index++) // { // uint32 button = map[index][0]; // uint32 key = map[index][1]; // if (buttons & button) // { // state[key] = 0x80; // } // } // } //} // //void Hotkeys::StartCameraController(BYTE * state) //{ // using namespace System::Input; // using namespace Game::Actor; // BYTE * gamepadAddr = *(BYTE **)(me32.modBaseAddr + 0xF2432C); // if (!gamepadAddr) // { // return; // } // if (!InControl()) // { // return; // } // DWORD off[MAX_ACTOR] = // { // 0x3C, // 0x308, // 0x5D4, // 0x8A0 // }; // DWORD map[][2] = // { // { MTF_GAMEPAD_START, DIK_ESCAPE }, // { MTF_GAMEPAD_RIGHT_STICK_UP, DIK_UP }, // { MTF_GAMEPAD_RIGHT_STICK_RIGHT, DIK_RIGHT }, // { MTF_GAMEPAD_RIGHT_STICK_DOWN, DIK_DOWN }, // { MTF_GAMEPAD_RIGHT_STICK_LEFT, DIK_LEFT } // }; // for (uint8 device = ACTOR_TWO; device < MAX_ACTOR; device++) // { // DWORD & buttons = *(DWORD *)(gamepadAddr + off[device] + 0x15C); // for (uint8 index = 0; index < countof(map); index++) // { // uint32 button = map[index][0]; // uint32 key = map[index][1]; // if (buttons & button) // { // state[key] = 0x80; // } // } // } //}
18.343915
68
0.535622
wangxh1007
3138d4f99c8879d5211428906f83da19686e91d5
11,753
cc
C++
pdb/src/executionServer/sources/physicalAlgorithms/PDBShuffleForJoinAlgorithm.cc
SeraphL/plinycompute
7788bc2b01d83f4ff579c13441d0ba90734b54a2
[ "Apache-2.0" ]
3
2019-05-04T05:17:30.000Z
2020-02-21T05:01:59.000Z
pdb/src/executionServer/sources/physicalAlgorithms/PDBShuffleForJoinAlgorithm.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
3
2020-02-20T19:50:46.000Z
2020-06-25T14:31:51.000Z
pdb/src/executionServer/sources/physicalAlgorithms/PDBShuffleForJoinAlgorithm.cc
dcbdan/plinycompute
a6f1c8ac8f75c09615f08752c82179f33cfc6d89
[ "Apache-2.0" ]
5
2019-02-19T23:17:24.000Z
2020-08-03T01:08:04.000Z
// // Created by dimitrije on 5/7/19. // #include <ComputePlan.h> #include <PDBCatalogClient.h> #include <physicalAlgorithms/PDBShuffleForJoinAlgorithm.h> #include <ExJob.h> #include <PDBStorageManagerBackend.h> #include <PDBPageNetworkSender.h> #include <ShuffleJoinProcessor.h> #include <PDBPageSelfReceiver.h> #include <GenericWork.h> #include <memory> pdb::PDBShuffleForJoinAlgorithm::PDBShuffleForJoinAlgorithm(const std::vector<PDBPrimarySource> &primarySource, const AtomicComputationPtr &finalAtomicComputation, const pdb::Handle<pdb::PDBSinkPageSetSpec> &intermediate, const pdb::Handle<pdb::PDBSinkPageSetSpec> &sink, const std::vector<pdb::Handle<PDBSourcePageSetSpec>> &secondarySources, const pdb::Handle<pdb::Vector<PDBSetObject>> &setsToMaterialize) : PDBPhysicalAlgorithm(primarySource, finalAtomicComputation, sink, secondarySources, setsToMaterialize), intermediate(intermediate) { } pdb::PDBPhysicalAlgorithmType pdb::PDBShuffleForJoinAlgorithm::getAlgorithmType() { return ShuffleForJoin; } bool pdb::PDBShuffleForJoinAlgorithm::setup(std::shared_ptr<pdb::PDBStorageManagerBackend> &storage, Handle<pdb::ExJob> &job, const std::string &error) { // init the plan ComputePlan plan(std::make_shared<LogicalPlan>(job->tcap, *job->computations)); logicalPlan = plan.getPlan(); // init the logger logger = make_shared<PDBLogger>("ShuffleJoinPipeAlgorithm" + std::to_string(job->computationID)); /// 0. Make the intermediate page set // get the sink page set auto intermediatePageSet = storage->createAnonymousPageSet(intermediate->pageSetIdentifier); // did we manage to get a sink page set? if not the setup failed if (intermediatePageSet == nullptr) { return false; } /// 1. Init the shuffle queues pageQueues = std::make_shared<std::vector<PDBPageQueuePtr>>(); for(int i = 0; i < job->numberOfNodes; ++i) { pageQueues->emplace_back(std::make_shared<PDBPageQueue>()); } /// 2. Create the page set that contains the shuffled join side pages for this node // get the receive page set auto recvPageSet = storage->createFeedingAnonymousPageSet(std::make_pair(sink->pageSetIdentifier.first, sink->pageSetIdentifier.second), job->numberOfProcessingThreads, job->numberOfNodes); // make sure we can use them all at the same time recvPageSet->setUsagePolicy(PDBFeedingPageSetUsagePolicy::KEEP_AFTER_USED); // did we manage to get a page set where we receive this? if not the setup failed if(recvPageSet == nullptr) { return false; } /// 3. Create the self receiver to forward pages that are created on this node and the network senders to forward pages for the other nodes auto myMgr = storage->getFunctionalityPtr<PDBBufferManagerInterface>(); senders = std::make_shared<std::vector<PDBPageNetworkSenderPtr>>(); for(unsigned i = 0; i < job->nodes.size(); ++i) { // check if it is this node or another node if(job->nodes[i]->port == job->thisNode->port && job->nodes[i]->address == job->thisNode->address) { // make the self receiver selfReceiver = std::make_shared<pdb::PDBPageSelfReceiver>(pageQueues->at(i), recvPageSet, myMgr); } else { // make the sender auto sender = std::make_shared<PDBPageNetworkSender>(job->nodes[i]->address, job->nodes[i]->port, job->numberOfProcessingThreads, job->numberOfNodes, storage->getConfiguration()->maxRetries, logger, std::make_pair(sink->pageSetIdentifier.first, sink->pageSetIdentifier.second), pageQueues->at(i)); // setup the sender, if we fail return false if(!sender->setup()) { return false; } // make the sender senders->emplace_back(sender); } } /// 4. Initialize the sources // we put them here std::vector<PDBAbstractPageSetPtr> sourcePageSets; sourcePageSets.reserve(sources.size()); // initialize them for(int i = 0; i < sources.size(); i++) { sourcePageSets.emplace_back(getSourcePageSet(storage, i)); } /// 5. Initialize all the pipelines // get the number of worker threads from this server's config int32_t numWorkers = storage->getConfiguration()->numThreads; // check that we have at least one worker per primary source if(numWorkers < sources.size()) { return false; } /// 6. Figure out the source page set joinShufflePipelines = std::make_shared<std::vector<PipelinePtr>>(); for (uint64_t pipelineIndex = 0; pipelineIndex < job->numberOfProcessingThreads; ++pipelineIndex) { /// 6.1. Figure out what source to use // figure out what pipeline auto pipelineSource = pipelineIndex % sources.size(); // grab these thins from the source we need them bool swapLHSandRHS = sources[pipelineSource].swapLHSandRHS; const pdb::String &firstTupleSet = sources[pipelineSource].firstTupleSet; // get the source computation auto srcNode = logicalPlan->getComputations().getProducingAtomicComputation(firstTupleSet); // go grab the source page set PDBAbstractPageSetPtr sourcePageSet = sourcePageSets[pipelineSource]; // did we manage to get a source page set? if not the setup failed if(sourcePageSet == nullptr) { return false; } /// 6.2. Figure out the parameters of the pipeline // figure out the join arguments auto joinArguments = getJoinArguments (storage); // if we could not create them we are out of here if(joinArguments == nullptr) { return false; } // get catalog client auto catalogClient = storage->getFunctionalityPtr<PDBCatalogClient>(); // empty computations parameters std::map<ComputeInfoType, ComputeInfoPtr> params = {{ComputeInfoType::PAGE_PROCESSOR, plan.getProcessorForJoin(finalTupleSet, job->numberOfNodes, job->numberOfProcessingThreads, *pageQueues, myMgr)}, {ComputeInfoType::JOIN_ARGS, joinArguments}, {ComputeInfoType::SHUFFLE_JOIN_ARG, std::make_shared<ShuffleJoinArg>(swapLHSandRHS)}, {ComputeInfoType::SOURCE_SET_INFO, getSourceSetArg(catalogClient, pipelineSource)}}; /// 6.3. Build the pipeline // build the join pipeline auto pipeline = plan.buildPipeline(firstTupleSet, /* this is the TupleSet the pipeline starts with */ finalTupleSet, /* this is the TupleSet the pipeline ends with */ sourcePageSet, intermediatePageSet, params, job->numberOfNodes, job->numberOfProcessingThreads, 20, pipelineIndex); // store the join pipeline joinShufflePipelines->push_back(pipeline); } return true; } bool pdb::PDBShuffleForJoinAlgorithm::run(std::shared_ptr<pdb::PDBStorageManagerBackend> &storage) { // success indicator atomic_bool success; success = true; /// 1. Run the self receiver, // create the buzzer atomic_int selfRecDone; selfRecDone = 0; PDBBuzzerPtr selfRefBuzzer = make_shared<PDBBuzzer>([&](PDBAlarm myAlarm, atomic_int &cnt) { // did we fail? if (myAlarm == PDBAlarm::GenericError) { success = false; } // we are done here cnt = 1; }); // run the work { // make the work PDBWorkPtr myWork = std::make_shared<pdb::GenericWork>([&selfRecDone, this](PDBBuzzerPtr callerBuzzer) { // run the receiver if(selfReceiver->run()) { // signal that the run was successful callerBuzzer->buzz(PDBAlarm::WorkAllDone, selfRecDone); } else { // signal that the run was unsuccessful callerBuzzer->buzz(PDBAlarm::GenericError, selfRecDone); } }); // run the work storage->getWorker()->execute(myWork, selfRefBuzzer); } /// 2. Run the senders // create the buzzer atomic_int sendersDone; sendersDone = 0; PDBBuzzerPtr sendersBuzzer = make_shared<PDBBuzzer>([&](PDBAlarm myAlarm, atomic_int &cnt) { // did we fail? if (myAlarm == PDBAlarm::GenericError) { success = false; } // we are done here cnt++; }); // go through each sender and run them for(auto &sender : *senders) { // make the work PDBWorkPtr myWork = std::make_shared<pdb::GenericWork>([&sendersDone, sender, this](PDBBuzzerPtr callerBuzzer) { // run the sender if(sender->run()) { // signal that the run was successful callerBuzzer->buzz(PDBAlarm::WorkAllDone, sendersDone); } else { // signal that the run was unsuccessful callerBuzzer->buzz(PDBAlarm::GenericError, sendersDone); } }); // run the work storage->getWorker()->execute(myWork, sendersBuzzer); } /// 3. Run the join pipelines // create the buzzer atomic_int joinCounter; joinCounter = 0; PDBBuzzerPtr joinBuzzer = make_shared<PDBBuzzer>([&](PDBAlarm myAlarm, atomic_int &cnt) { // did we fail? if (myAlarm == PDBAlarm::GenericError) { success = false; } // increment the count cnt++; }); // here we get a worker per pipeline and run all the shuffle join side pipelines. for (int workerID = 0; workerID < joinShufflePipelines->size(); ++workerID) { // get a worker from the server PDBWorkerPtr worker = storage->getWorker(); // make the work PDBWorkPtr myWork = std::make_shared<pdb::GenericWork>([&joinCounter, &success, workerID, this](const PDBBuzzerPtr& callerBuzzer) { try { // run the pipeline (*joinShufflePipelines)[workerID]->run(); } catch (std::exception &e) { // log the error this->logger->error(e.what()); // we failed mark that we have success = false; } // signal that the run was successful callerBuzzer->buzz(PDBAlarm::WorkAllDone, joinCounter); }); // run the work worker->execute(myWork, joinBuzzer); } // wait until all the shuffle join side pipelines have completed while (joinCounter < joinShufflePipelines->size()) { joinBuzzer->wait(); } // ok they have finished now push a null page to each of the preagg queues for(auto &queue : *pageQueues) { queue->enqueue(nullptr); } // wait while we are running the receiver while(selfRecDone == 0) { selfRefBuzzer->wait(); } // wait while we are running the senders while(sendersDone < senders->size()) { sendersBuzzer->wait(); } return true; } void pdb::PDBShuffleForJoinAlgorithm::cleanup() { // invalidate everything pageQueues = nullptr; joinShufflePipelines = nullptr; logger = nullptr; selfReceiver = nullptr; senders = nullptr; intermediate = nullptr; logicalPlan = nullptr; }
33.389205
204
0.619246
SeraphL
31390bcffbdf28b9d44ba490470b8574a59720ab
1,801
hpp
C++
Sources/inc/Chest.hpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
null
null
null
Sources/inc/Chest.hpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
null
null
null
Sources/inc/Chest.hpp
Tifox/Grog-Knight
377a661286cda7ee3b2b2d0099641897938c2f8f
[ "Apache-2.0" ]
null
null
null
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * File: Chest.cpp * Creation: 2015-08-27 04:44 * Vincent Rey <[email protected]> */ #ifndef __Chest__ # define __Chest__ # include "Elements.hpp" # include "../../Tools/jsoncpp/include/json/json.h" class Chest: public Elements { public: Chest(void); ~Chest(void); void spawn(void); void displayInterface(void); void removeInterface(void); void displayChestContent(void); void ReceiveMessage(Message *m); void makeChoices(void); void updateItems(void); int isUsed(void); void reset(void); std::map<int, std::string> getItems(void); int getGold(void); void applySave(std::map<std::string, Json::Value> save); int isSpawn; private: void _makeItUsed(void); std::list<HUDActor *> _interfaceElem; std::map<int, std::string> _chestItems; std::map<int, HUDActor*> _img; std::list<HUDActor *> _choices; HUDActor * _choicePointer; HUDActor* _target; int _isUsed; int _gold; }; # endif
27.287879
63
0.696835
Tifox
3139228b1dcdfdcb70c36df002aceff8611d5b4b
3,521
hpp
C++
hydra/vulkan/rect2D.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
2
2016-09-15T22:29:46.000Z
2017-11-30T11:16:12.000Z
hydra/vulkan/rect2D.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
hydra/vulkan/rect2D.hpp
tim42/hydra
dfffd50a2863695742c0c6122a505824db8be7c3
[ "MIT" ]
null
null
null
// // file : rect2D.hpp // in : file:///home/tim/projects/hydra/hydra/vulkan/rect2D.hpp // // created by : Timothée Feuillet // date: Sat Aug 13 2016 11:12:20 GMT+0200 (CEST) // // // Copyright (c) 2016 Timothée Feuillet // // 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. // #ifndef __N_934928149373630529_3118821077_RECT2D_HPP__ #define __N_934928149373630529_3118821077_RECT2D_HPP__ #include <vulkan/vulkan.h> #include <glm/glm.hpp> namespace neam { namespace hydra { namespace vk { /// \brief Wraps a vulkan rect2D class rect2D { public: /// \brief Create a rect2D rect2D(const glm::ivec2 &offset, const glm::uvec2 &size) : rect { {offset.x, offset.y}, {size.x, size.y} } {} /// \brief Copy constructor rect2D(const rect2D &o) : rect(o.rect) {} /// \brief Copy operator rect2D &operator = (const rect2D &o) { rect = o.rect; return *this;} /// \brief Copy constructor rect2D(const VkRect2D &o) : rect(o) {} /// \brief Copy operator rect2D &operator = (const VkRect2D &o) { rect = o; return *this;} /// \brief Return the offset glm::ivec2 get_offset() const { return glm::ivec2(rect.offset.x, rect.offset.y); } /// \brief Set the offset void set_offset(const glm::ivec2 &offset) { rect.offset.x = offset.x; rect.offset.y = offset.y; } /// \brief Return the end offset glm::ivec2 get_end_offset() const { return glm::ivec2(rect.offset.x + rect.extent.width, rect.offset.y + rect.extent.height); } /// \brief Translate the offset by displ void translate_offset(const glm::ivec2 &displ) { set_offset(get_offset() + displ); } /// \brief Return the size glm::uvec2 get_size() const { return glm::uvec2(rect.extent.width, rect.extent.height); } /// \brief Set the size void set_size(const glm::uvec2 &size) { rect.extent.width = size.x; rect.extent.height = size.y; } /// \brief Grow / shrink the size of the rect by dt void grow_size(const glm::ivec2 &dt) { set_size(static_cast<glm::ivec2>(get_size()) + dt); } public: // advanced /// \brief Yield a VkRect2D operator const VkRect2D &() const { return rect; } private: VkRect2D rect; }; } // namespace vk } // namespace hydra } // namespace neam #endif // __N_934928149373630529_3118821077_RECT2D_HPP__
40.011364
137
0.6572
tim42
3140b75af71b7541ee489e9658b9bfe426340af6
6,905
cpp
C++
test/system2/station/wxglade_out.cpp
khantkyawkhaung/robot-monitor
3614dc0cf804138c81f6800fb5ec443bff709dbd
[ "MIT" ]
1
2021-04-06T04:11:58.000Z
2021-04-06T04:11:58.000Z
test/system2/station/wxglade_out.cpp
khantkyawkhaung/robot-monitor
3614dc0cf804138c81f6800fb5ec443bff709dbd
[ "MIT" ]
null
null
null
test/system2/station/wxglade_out.cpp
khantkyawkhaung/robot-monitor
3614dc0cf804138c81f6800fb5ec443bff709dbd
[ "MIT" ]
1
2019-12-26T09:01:16.000Z
2019-12-26T09:01:16.000Z
// -*- C++ -*- // // generated by wxGlade 0.9.4 on Tue Jun 15 15:13:10 2021 // // Example for compiling a single file project under Linux using g++: // g++ MyApp.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp // // Example for compiling a multi file project under Linux using g++: // g++ main.cpp $(wx-config --libs) $(wx-config --cxxflags) -o MyApp Dialog1.cpp Frame1.cpp // #include "wxglade_out.h" // begin wxGlade: ::extracode // end wxGlade MyFrame::MyFrame(wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style): wxFrame(parent, id, title, pos, size, wxDEFAULT_FRAME_STYLE) { // begin wxGlade: MyFrame::MyFrame SetSize(wxSize(380, 430)); construct_user(); frame_menubar = new wxMenuBar(); wxMenu *wxglade_tmp_menu; wxMenuItem *wxglade_tmp_item; wxglade_tmp_menu = new wxMenu(); wxglade_tmp_item = wxglade_tmp_menu->Append(wxID_ANY, wxT("Exit"), wxEmptyString); Bind(wxEVT_MENU, &MyFrame::onMenuExit, this, wxglade_tmp_item->GetId()); frame_menubar->Append(wxglade_tmp_menu, wxT("File")); wxglade_tmp_menu = new wxMenu(); /*wxMenu* menuPort = new wxMenu(); wxglade_tmp_item = menuPort->Append(wxID_ANY, wxT("/dev/ttyACM0"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuPort, this, wxglade_tmp_item->GetId());*/ wxglade_tmp_menu->Append(ID_MENU_PORT, wxT("Port"), menuPort, wxEmptyString); wxMenu* menuBaudrate = new wxMenu(); menuBaudrate->Append(ID_B9600, wxT("9600"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuBaudrate, this, ID_B9600); menuBaudrate->Append(ID_B19200, wxT("19200"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuBaudrate, this, ID_B19200); menuBaudrate->Append(ID_B38400, wxT("38400"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuBaudrate, this, ID_B38400); menuBaudrate->Append(ID_B57600, wxT("57600"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuBaudrate, this, ID_B57600); menuBaudrate->Append(ID_B74880, wxT("74880"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuBaudrate, this, ID_B74880); menuBaudrate->Append(ID_B115200, wxT("115200"), wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &MyFrame::onMenuBaudrate, this, ID_B115200); wxglade_tmp_menu->Append(ID_MENU_BAUDRATE, wxT("Baudrate"), menuBaudrate, wxEmptyString); wxglade_tmp_menu->Append(ID_MENU_CONNECT, wxT("Connect"), wxEmptyString); Bind(wxEVT_MENU, &MyFrame::onMenuConnect, this, ID_MENU_CONNECT); wxglade_tmp_menu->Append(ID_MENU_DISCONNECT, wxT("Disconnect"), wxEmptyString); Bind(wxEVT_MENU, &MyFrame::onMenuDisconnect, this, ID_MENU_DISCONNECT); frame_menubar->Append(wxglade_tmp_menu, wxT("Tools")); wxglade_tmp_menu = new wxMenu(); wxglade_tmp_item = wxglade_tmp_menu->Append(wxID_ANY, wxT("About"), wxEmptyString); Bind(wxEVT_MENU, &MyFrame::onMenuAbout, this, wxglade_tmp_item->GetId()); frame_menubar->Append(wxglade_tmp_menu, wxT("Help")); SetMenuBar(frame_menubar); /*lblAccelX = new wxStaticText(this, wxID_ANY, wxT("Accel-X")); lblAccelY = new wxStaticText(this, wxID_ANY, wxT("Accel-Y")); lblAccelZ = new wxStaticText(this, wxID_ANY, wxT("Accel-Z")); lblGyroX = new wxStaticText(this, wxID_ANY, wxT("Gyro-X")); lblGyroY = new wxStaticText(this, wxID_ANY, wxT("Gyro-Y")); lblGyroZ = new wxStaticText(this, wxID_ANY, wxT("Gyro-Z")); lblMagX = new wxStaticText(this, wxID_ANY, wxT("Mag-X")); lblMagY = new wxStaticText(this, wxID_ANY, wxT("Mag-Y")); lblMagZ = new wxStaticText(this, wxID_ANY, wxT("Mag-Z")); btnCaliAccel = new wxButton(this, wxID_ANY, wxT("Calibrate Accel")); btnCaliGyro = new wxButton(this, wxID_ANY, wxT("Calibrate Gyro")); btnCaliMag = new wxButton(this, wxID_ANY, wxT("Calirate Mag")); txtEcho = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE); lblPortStatus = new wxStaticText(this, wxID_ANY, wxT("Not connected"), wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT); lblPortAddress = new wxStaticText(this, wxID_ANY, wxT("n/a"));*/ wxglade_tmp_menu = menuPort->GetParent(); wxglade_tmp_menu->Enable(ID_MENU_PORT, false); wxglade_tmp_menu->Enable(ID_MENU_CONNECT, false); wxglade_tmp_menu->Enable(ID_MENU_DISCONNECT, false); set_properties(); do_layout(); // end wxGlade } void MyFrame::set_properties() { // begin wxGlade: MyFrame::set_properties SetTitle(wxT("frame")); wxIcon _icon; _icon.CopyFromBitmap(rmGetIcon()); SetIcon(_icon); // end wxGlade } void MyFrame::do_layout() { // begin wxGlade: MyFrame::do_layout wxBoxSizer* sizer_1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* sizer_8 = new wxBoxSizer(wxHORIZONTAL); wxStaticBoxSizer* sizer_7 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wxT("Messages")), wxHORIZONTAL); wxBoxSizer* sizer_2 = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* sizer_4 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* sizer_10 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* sizer_9 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* sizer_3 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* sizer_6 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* sizer_5 = new wxBoxSizer(wxVERTICAL); sizer_5->Add(lblAccelX, 0, 0, 0); sizer_5->Add(lblAccelY, 0, 0, 0); sizer_5->Add(lblAccelZ, 0, wxALL, 0); sizer_3->Add(sizer_5, 2, wxEXPAND, 0); sizer_6->Add(lblGyroX, 0, 0, 0); sizer_6->Add(lblGyroY, 0, 0, 0); sizer_6->Add(lblGyroZ, 0, 0, 0); sizer_3->Add(sizer_6, 3, wxEXPAND, 0); sizer_2->Add(sizer_3, 1, wxALL|wxEXPAND, 5); sizer_9->Add(lblMagX, 0, 0, 0); sizer_9->Add(lblMagY, 0, 0, 0); sizer_9->Add(lblMagZ, 0, 0, 0); sizer_4->Add(sizer_9, 2, wxEXPAND, 0); sizer_10->Add(btnCaliAccel, 0, wxALL, 1); sizer_10->Add(btnCaliGyro, 0, wxALL, 1); sizer_10->Add(btnCaliMag, 0, wxALL, 1); sizer_4->Add(sizer_10, 3, wxEXPAND, 0); sizer_2->Add(sizer_4, 1, wxALL|wxEXPAND, 5); sizer_1->Add(sizer_2, 3, wxALL|wxEXPAND, 0); sizer_7->Add(txtEcho, 1, wxEXPAND, 0); sizer_1->Add(sizer_7, 2, wxEXPAND|wxTOP, 5); sizer_8->Add(lblPortStatus, 0, 0, 0); sizer_8->Add(20, 16, 1, 0, 0); sizer_8->Add(lblPortAddress, 0, 0, 0); sizer_1->Add(sizer_8, 0, wxEXPAND|wxTOP, 5); SetSizer(sizer_1); Layout(); // end wxGlade } BEGIN_EVENT_TABLE(MyFrame, wxFrame) // begin wxGlade: MyFrame::event_table // end wxGlade END_EVENT_TABLE(); // wxGlade: add MyFrame event handlers class MyApp: public wxApp { public: bool OnInit(); }; IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { wxInitAllImageHandlers(); MyFrame* frame = new MyFrame(NULL, wxID_ANY, wxEmptyString); SetTopWindow(frame); frame->Show(); return true; }
41.347305
125
0.69819
khantkyawkhaung
3143216dc67187d043e04da952cf88e2c867b403
7,252
cc
C++
test/objectreference.cc
blagoev/node-addon-api
89e62a9154b6057ed086a227db25caf26ac8c92a
[ "MIT" ]
13
2019-06-18T14:30:56.000Z
2021-04-25T06:06:52.000Z
test/objectreference.cc
shudingbo/node-addon-api
4d816183daadd1fec9411f9a3c566b098059e02b
[ "MIT" ]
12
2020-09-04T20:01:51.000Z
2020-12-07T20:43:29.000Z
test/objectreference.cc
shudingbo/node-addon-api
4d816183daadd1fec9411f9a3c566b098059e02b
[ "MIT" ]
1
2020-05-26T15:14:43.000Z
2020-05-26T15:14:43.000Z
/* ObjectReference can be used to create references to Values that are not Objects by creating a blank Object and setting Values to it. Subclasses of Objects can only be set using an ObjectReference by first casting it as an Object. */ #include "napi.h" using namespace Napi; ObjectReference weak; ObjectReference persistent; ObjectReference reference; ObjectReference casted_weak; ObjectReference casted_persistent; ObjectReference casted_reference; // info[0] is the key, which can be either a string or a number. // info[1] is the value. // info[2] is a flag that differentiates whether the key is a // C string or a JavaScript string. void SetObjects(const CallbackInfo& info) { Env env = info.Env(); HandleScope scope(env); weak = Weak(Object::New(env)); weak.SuppressDestruct(); persistent = Persistent(Object::New(env)); persistent.SuppressDestruct(); reference = Reference<Object>::New(Object::New(env), 2); reference.SuppressDestruct(); if (info[0].IsString()) { if (info[2].As<String>() == String::New(env, "javascript")) { weak.Set(info[0].As<String>(), info[1]); persistent.Set(info[0].As<String>(), info[1]); reference.Set(info[0].As<String>(), info[1]); } else { weak.Set(info[0].As<String>().Utf8Value(), info[1]); persistent.Set(info[0].As<String>().Utf8Value(), info[1]); reference.Set(info[0].As<String>().Utf8Value(), info[1]); } } else if (info[0].IsNumber()) { weak.Set(info[0].As<Number>(), info[1]); persistent.Set(info[0].As<Number>(), info[1]); reference.Set(info[0].As<Number>(), info[1]); } } void SetCastedObjects(const CallbackInfo& info) { Env env = info.Env(); HandleScope scope(env); Array ex = Array::New(env); ex.Set((uint32_t)0, String::New(env, "hello")); ex.Set(1, String::New(env, "world")); ex.Set(2, String::New(env, "!")); casted_weak = Weak(ex.As<Object>()); casted_weak.SuppressDestruct(); casted_persistent = Persistent(ex.As<Object>()); casted_persistent.SuppressDestruct(); casted_reference = Reference<Object>::New(ex.As<Object>(), 2); casted_reference.SuppressDestruct(); } // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. Value GetFromValue(const CallbackInfo& info) { Env env = info.Env(); if (info[0].As<String>() == String::New(env, "weak")) { if (weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { return weak.Value(); } } else if (info[0].As<String>() == String::New(env, "persistent")) { return persistent.Value(); } else { return reference.Value(); } } // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. // info[1] is the key, and it be either a String or a Number. Value GetFromGetter(const CallbackInfo& info) { Env env = info.Env(); if (info[0].As<String>() == String::New(env, "weak")) { if (weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { if (info[1].IsString()) { return weak.Get(info[1].As<String>().Utf8Value()); } else if (info[1].IsNumber()) { return weak.Get(info[1].As<Number>().Uint32Value()); } } } else if (info[0].As<String>() == String::New(env, "persistent")) { if (info[1].IsString()) { return persistent.Get(info[1].As<String>().Utf8Value()); } else if (info[1].IsNumber()) { return persistent.Get(info[1].As<Number>().Uint32Value()); } } else { if (info[0].IsString()) { return reference.Get(info[0].As<String>().Utf8Value()); } else if (info[0].IsNumber()) { return reference.Get(info[0].As<Number>().Uint32Value()); } } return String::New(env, "Error: Reached end of getter"); } // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. Value GetCastedFromValue(const CallbackInfo& info) { Env env = info.Env(); if (info[0].As<String>() == String::New(env, "weak")) { if (casted_weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { return casted_weak.Value(); } } else if (info[0].As<String>() == String::New(env, "persistent")) { return casted_persistent.Value(); } else { return casted_reference.Value(); } } // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. // info[1] is the key and it must be a Number. Value GetCastedFromGetter(const CallbackInfo& info) { Env env = info.Env(); if (info[0].As<String>() == String::New(env, "weak")) { if (casted_weak.IsEmpty()) { return String::New(env, "No Referenced Value"); } else { return casted_weak.Get(info[1].As<Number>()); } } else if (info[0].As<String>() == String::New(env, "persistent")) { return casted_persistent.Get(info[1].As<Number>()); } else { return casted_reference.Get(info[1].As<Number>()); } } // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. Number UnrefObjects(const CallbackInfo& info) { Env env = info.Env(); uint32_t num; if (info[0].As<String>() == String::New(env, "weak")) { num = weak.Unref(); } else if (info[0].As<String>() == String::New(env, "persistent")) { num = persistent.Unref(); } else if (info[0].As<String>() == String::New(env, "references")) { num = reference.Unref(); } else if (info[0].As<String>() == String::New(env, "casted weak")) { num = casted_weak.Unref(); } else if (info[0].As<String>() == String::New(env, "casted persistent")) { num = casted_persistent.Unref(); } else { num = casted_reference.Unref(); } return Number::New(env, num); } // info[0] is a flag to determine if the weak, persistent, or // multiple reference ObjectReference is being requested. Number RefObjects(const CallbackInfo& info) { Env env = info.Env(); uint32_t num; if (info[0].As<String>() == String::New(env, "weak")) { num = weak.Ref(); } else if (info[0].As<String>() == String::New(env, "persistent")) { num = persistent.Ref(); } else if (info[0].As<String>() == String::New(env, "references")) { num = reference.Ref(); } else if (info[0].As<String>() == String::New(env, "casted weak")) { num = casted_weak.Ref(); } else if (info[0].As<String>() == String::New(env, "casted persistent")) { num = casted_persistent.Ref(); } else { num = casted_reference.Ref(); } return Number::New(env, num); } Object InitObjectReference(Env env) { Object exports = Object::New(env); exports["setCastedObjects"] = Function::New(env, SetCastedObjects); exports["setObjects"] = Function::New(env, SetObjects); exports["getCastedFromValue"] = Function::New(env, GetCastedFromValue); exports["getFromGetter"] = Function::New(env, GetFromGetter); exports["getCastedFromGetter"] = Function::New(env, GetCastedFromGetter); exports["getFromValue"] = Function::New(env, GetFromValue); exports["unrefObjects"] = Function::New(env, UnrefObjects); exports["refObjects"] = Function::New(env, RefObjects); return exports; }
33.114155
77
0.648511
blagoev
3155bb2ed2b8ac5eb3a124bc203f890c61631e2f
3,176
cpp
C++
src/prod/src/ServiceModel/management/FaultAnalysisService/Chaos/ChaosTargetFilter.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
1
2018-03-15T02:09:21.000Z
2018-03-15T02:09:21.000Z
src/prod/src/ServiceModel/management/FaultAnalysisService/Chaos/ChaosTargetFilter.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
src/prod/src/ServiceModel/management/FaultAnalysisService/Chaos/ChaosTargetFilter.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace Naming; using namespace ServiceModel; using namespace std; using namespace Management::FaultAnalysisService; StringLiteral const TraceComponent("ChaosTargetFilter"); ChaosTargetFilter::ChaosTargetFilter() : nodeTypeInclusionList_() , applicationInclusionList_() { } ChaosTargetFilter::ChaosTargetFilter(ChaosTargetFilter && other) : nodeTypeInclusionList_(move(other.nodeTypeInclusionList_)) , applicationInclusionList_(move(other.applicationInclusionList_)) { } ErrorCode ChaosTargetFilter::FromPublicApi( FABRIC_CHAOS_TARGET_FILTER const & publicFilter) { if(publicFilter.NodeTypeInclusionList != nullptr) { // NodeTypeInclusionList StringList::FromPublicApi(*publicFilter.NodeTypeInclusionList, nodeTypeInclusionList_); } if(publicFilter.ApplicationInclusionList != nullptr) { // ApplicationInclusionList StringList::FromPublicApi(*publicFilter.ApplicationInclusionList, applicationInclusionList_); } return ErrorCode::Success(); } ErrorCode ChaosTargetFilter::ToPublicApi( __in Common::ScopedHeap & heap, __out FABRIC_CHAOS_TARGET_FILTER & result) const { auto publicNodeTypeInclusionList = heap.AddItem<FABRIC_STRING_LIST>(); StringList::ToPublicAPI(heap, nodeTypeInclusionList_, publicNodeTypeInclusionList); result.NodeTypeInclusionList = publicNodeTypeInclusionList.GetRawPointer(); auto publicApplicationInclusionList = heap.AddItem<FABRIC_STRING_LIST>(); StringList::ToPublicAPI(heap, applicationInclusionList_, publicApplicationInclusionList); result.ApplicationInclusionList = publicApplicationInclusionList.GetRawPointer(); return ErrorCode::Success(); } ErrorCode ChaosTargetFilter::Validate() const { if (nodeTypeInclusionList_.empty() && applicationInclusionList_.empty()) { return ErrorCode(ErrorCodeValue::InvalidArgument, wformatString("{0}", FASResource::GetResources().ChaosTargetFilterSpecificationNotFound)); } int maximumNumberOfNodeTypesInChaosTargetFilter = ServiceModelConfig::GetConfig().MaxNumberOfNodeTypesInChaosTargetFilter; if (!nodeTypeInclusionList_.empty() && nodeTypeInclusionList_.size() > maximumNumberOfNodeTypesInChaosTargetFilter) { return ErrorCode(ErrorCodeValue::EntryTooLarge, wformatString("{0}", FASResource::GetResources().ChaosNodeTypeInclusionListTooLong)); } int maximumNumberOfApplicationsInChaosTargetFilter = ServiceModelConfig::GetConfig().MaxNumberOfApplicationsInChaosTargetFilter; if (!applicationInclusionList_.empty() && applicationInclusionList_.size() > maximumNumberOfApplicationsInChaosTargetFilter) { return ErrorCode(ErrorCodeValue::EntryTooLarge, wformatString("{0}", FASResource::GetResources().ChaosApplicationInclusionListTooLong)); } return ErrorCode::Success(); }
37.364706
148
0.756612
AnthonyM
3155e10af3c1704e0df9dfbdde68de005ebd019d
3,457
cpp
C++
src/util/ObjLoader.cpp
Daniel-F-Parker/pt-three-ways
f3f576495468a2701f2a036943f425b52f5874eb
[ "MIT" ]
166
2019-04-30T16:19:34.000Z
2022-03-28T12:36:39.000Z
src/util/ObjLoader.cpp
Daniel-F-Parker/pt-three-ways
f3f576495468a2701f2a036943f425b52f5874eb
[ "MIT" ]
3
2019-10-12T05:34:43.000Z
2021-12-16T22:32:22.000Z
src/util/ObjLoader.cpp
Daniel-F-Parker/pt-three-ways
f3f576495468a2701f2a036943f425b52f5874eb
[ "MIT" ]
20
2019-04-30T19:43:27.000Z
2022-03-03T18:41:25.000Z
#include "ObjLoader.h" #include <algorithm> #include <fstream> #include <string> double impl::asDouble(std::string_view sv) { return std::stod(std::string(sv)); // This is dreadful } int impl::asInt(std::string_view sv) { return std::stoi(std::string(sv)); // This is dreadful } size_t impl::asIndex(std::string_view sv, size_t max) { auto res = std::stol(std::string(sv)); return res < 0 ? res + max : res - 1; } std::unordered_map<std::string, MaterialSpec> impl::loadMaterials(std::istream &in) { using namespace std::literals; if (!in) throw std::runtime_error("Bad input stream"); in.exceptions(std::ios_base::badbit); std::unordered_map<std::string, MaterialSpec> result; MaterialSpec *curMat{}; int illum = 2; Vec3 ambientColour; auto flushMat = [&] { if (!curMat) return; if (illum == 3) { curMat->reflectivity = ambientColour.length(); } curMat = nullptr; }; parse(in, [&](std::string_view command, const std::vector<std::string_view> &params) { if (command == "newmtl"sv) { flushMat(); if (params.size() != 1) throw std::runtime_error("Wrong number of params for newmtl"); curMat = &result.emplace(std::string(params[0]), MaterialSpec{}).first->second; return true; } else if (command == "Ke"sv) { if (!curMat) throw std::runtime_error("Unexpected Ke"); if (params.size() != 3) throw std::runtime_error("Wrong number of params for Ke"); curMat->emission = Vec3(asDouble(params[0]), asDouble(params[1]), asDouble(params[2])); return true; } else if (command == "Kd"sv) { if (!curMat) throw std::runtime_error("Unexpected Kd"); if (params.size() != 3) throw std::runtime_error("Wrong number of params for Kd"); curMat->diffuse = Vec3(asDouble(params[0]), asDouble(params[1]), asDouble(params[2])); return true; } else if (command == "Ka"sv) { if (!curMat) throw std::runtime_error("Unexpected Ka"); if (params.size() != 3) throw std::runtime_error("Wrong number of params for Ka"); ambientColour = Vec3(asDouble(params[0]), asDouble(params[1]), asDouble(params[2])); return true; } else if (command == "Ni"sv) { if (!curMat) throw std::runtime_error("Unexpected Ni"); if (params.size() != 1) throw std::runtime_error("Wrong number of params for Ni"); curMat->indexOfRefraction = asDouble(params[0]); return true; } else if (command == "Ns"sv) { if (!curMat) throw std::runtime_error("Unexpected Ns"); if (params.size() != 1) throw std::runtime_error("Wrong number of params for Ns"); // Values seem to be in the range [0, 1000], where higher is a tighter // specular highlight. This is an empirical hack. auto val = asDouble(params[0]) / 100; curMat->reflectionConeAngleRadians = M_PI * std::clamp(1 - val, 0.0, 1.0); return true; } else if (command == "illum"sv) { if (!curMat) throw std::runtime_error("Unexpected illum"); if (params.size() != 1) throw std::runtime_error("Wrong number of params for illum"); illum = asInt(params[0]); return true; } else if (command == "Ks"sv || command == "d"sv) { // Ignored return true; } return false; }); flushMat(); return result; }
31.715596
80
0.601388
Daniel-F-Parker
3159dcc072cfe7603a0b898331bb25d20e8ec184
9,599
cpp
C++
test/saber/amd/test_saber_func_activation_AMD.cpp
vin-huang/Anakin
8fc4b82ebaf974a6e052fe3690e41d678de4aa03
[ "Apache-2.0" ]
null
null
null
test/saber/amd/test_saber_func_activation_AMD.cpp
vin-huang/Anakin
8fc4b82ebaf974a6e052fe3690e41d678de4aa03
[ "Apache-2.0" ]
null
null
null
test/saber/amd/test_saber_func_activation_AMD.cpp
vin-huang/Anakin
8fc4b82ebaf974a6e052fe3690e41d678de4aa03
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 Anakin Authors, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <vector> #include "saber/core/context.h" #include "saber/funcs/activation.h" #include "test_saber_func_AMD.h" #include "saber/core/tensor_op.h" #include "saber/saber_funcs_param.h" #include "saber/saber_types.h" #include <vector> using namespace anakin::saber; typedef Tensor<X86, AK_FLOAT, NCHW> TensorHf4; typedef Tensor<AMD, AK_FLOAT, NCHW> TensorDf4; typedef TargetWrapper<AMD> API; template <typename Tensor> void print_tensor_shape(std::string name, Tensor &t0) { LOG(INFO) << name << " valid shape is [" << t0.valid_shape()[0] << ", " << t0.valid_shape()[1] << ", " << t0.valid_shape()[2] << ", " << t0.valid_shape()[3] << "]."; LOG(INFO) << name << " real shape is [" << t0.shape()[0] << ", " << t0.shape()[1] << ", " << t0.shape()[2] << ", " << t0.shape()[3] << "]."; LOG(INFO) << name << " offset is [" << t0.offset()[0] << ", " << t0.offset()[1] << ", " << t0.offset()[2] << ", " << t0.offset()[3] << "]."; } void test_active(std::vector<TensorDf4*> &inputs, std::vector<TensorDf4*> &outputs, int stride, int pad, int slope, TensorDf4 &bias, anakin::saber::ImplEnum impl, int warm_iter, int iter, Context<AMD> &ctx1, SaberTimer<AMD> &t_device) { ActivationParam<TensorDf4> param(Active_relu, slope); Activation<AMD, AK_FLOAT> activation; activation.compute_output_shape(inputs, outputs, param); //MUST USE "valid_shape()" outputs[0]->re_alloc(outputs[0]->valid_shape()); SABER_CHECK(activation.init(inputs, outputs, param, SPECIFY, impl, ctx1)); for(int i=0; i < warm_iter; i++) activation(inputs, outputs, param, ctx1); clFinish(ctx1.get_compute_stream()); Env<AMD>::start_record(); for(int i=0 ;i < iter; i++) { t_device.start(ctx1); activation(inputs, outputs, param, ctx1); t_device.end(ctx1); } Env<AMD>::stop_record(); clFlush(ctx1.get_compute_stream()); clFinish(ctx1.get_compute_stream()); } typedef struct ProblemConfigType { std::string ConfigName; int N; int W, H; int C, K; float NegSlope; //for conv_relu }T_ProblemConfig; void Activation_Host(TensorHf4* out_host, TensorHf4& in_host, T_ProblemConfig* problemConfig) { int negSlope = problemConfig->NegSlope; int size_in = problemConfig->N * problemConfig->C * problemConfig->H * problemConfig->W; for (int i = 0; i < size_in; i++) { out_host->mutable_data()[i] = in_host.data()[i] > 0 ? in_host.data()[i] : in_host.data()[i] * negSlope; } } TEST(TestSaberFuncAMD, test_activation) { std::list<T_ProblemConfig*> problemConfigList; T_ProblemConfig * problemConfig; TensorDf4 in; TensorHf4 in_host; TensorDf4 bias; TensorDf4 out; TensorHf4 out_host; //to store the result from device TensorHf4 out_golden_host; //to store the result from cpu calculation /* // ====================================================================== // problem config conv12: // ====================================================================== problemConfig = new T_ProblemConfig(); problemConfig->ConfigName = "Relu12"; problemConfig->N = 1; //batch problemConfig->W = 224; //width problemConfig->H = 224; //height problemConfig->C = 64; //channel problemConfig->K = 64; //kernels problemConfig->NegSlope = 2; problemConfigList.push_back(problemConfig); // ====================================================================== // problem config conv22: // ====================================================================== problemConfig = new T_ProblemConfig(); problemConfig->ConfigName = "Relu22"; problemConfig->N = 1; //batch problemConfig->W = 112; //width problemConfig->H = 112; //height problemConfig->C = 128; //channel problemConfig->K = 128; //kernels problemConfig->NegSlope = 2; problemConfigList.push_back(problemConfig); // ====================================================================== // problem config conv33: // ====================================================================== problemConfig = new T_ProblemConfig(); problemConfig->ConfigName = "Relu33"; problemConfig->N = 1; //batch problemConfig->W = 56; //width problemConfig->H = 56; //height problemConfig->C = 256; //channel problemConfig->K = 256; //kernels problemConfig->NegSlope = 2; problemConfigList.push_back(problemConfig); // ====================================================================== // problem config conv43: // ====================================================================== problemConfig = new T_ProblemConfig(); problemConfig->ConfigName = "Relu43"; problemConfig->N = 1; //batch problemConfig->W = 28; //width problemConfig->H = 28; //height problemConfig->C = 512; //channel problemConfig->K = 512; //kernels problemConfig->NegSlope = 2; problemConfigList.push_back(problemConfig); // ====================================================================== // problem config conv53: // ====================================================================== problemConfig = new T_ProblemConfig(); problemConfig->ConfigName = "Relu53"; problemConfig->N = 1; //batch problemConfig->W = 14; //width problemConfig->H = 14; //height problemConfig->C = 512; //channel problemConfig->K = 512; //kernels problemConfig->NegSlope = 2; problemConfigList.push_back(problemConfig); */ // ====================================================================== // problem config conv53: // ====================================================================== problemConfig = new T_ProblemConfig(); problemConfig->ConfigName = "4096C"; problemConfig->N = 1; //batch problemConfig->W = 1; //width problemConfig->H = 1; //height problemConfig->C = 4096; //channel problemConfig->K = 4096; //kernels problemConfig->NegSlope = 2; problemConfigList.push_back(problemConfig); Context<AMD> ctx1(0, 1, 1); API::stream_t amd_cstream = ctx1.get_compute_stream(); LOG(INFO) << "Total " << problemConfigList.size() << " problems..."; SaberTimer<AMD> t_device; SaberTimer<AMD> t_host; //Begin loop for (auto p : problemConfigList) { //TODO: get the problem and solve it... LOG(INFO) << "Problem: " << p->ConfigName; Env<AMD>::set_tag(p->ConfigName.c_str()); //allocate input buffer in.re_alloc({p->N, p->C, p->H, p->W}); in_host.re_alloc({p->N, p->C, p->H, p->W}); //assign default value to input buffer fill_tensor_device_rand(in, -1.f, 1.f); in_host.copy_from(in); std::vector<TensorDf4*> input_v, output_v; input_v.push_back(&in); output_v.push_back(&out); //wait for device ready clFlush(amd_cstream); clFinish(amd_cstream); test_active(input_v, output_v, 1, 1, p->NegSlope, bias, SABER_IMPL, warm_iter, iter, ctx1, t_device); print_tensor_shape("in", in); print_tensor_shape("out", out); //wait for device ready clFlush(amd_cstream); clFinish(amd_cstream); out_host.re_alloc(out.shape()); out_host.copy_from(out); //test result in host side. t_host.start(ctx1); out_golden_host.re_alloc(out.shape()); Activation_Host(&out_golden_host, in_host, p); t_host.end(ctx1); //LOG(INFO) << "PRINT DEVICE TENSOR: img"; //print_tensor_device(img); //sleep(2); //LOG(INFO) << "PRINT DEVICE TENSOR: out"; //print_tensor_device(out); //sleep(2); //LOG(INFO) << "PRINT HOST TENSOR: out"; //print_tensor_host(out_golden_host); //sleep(2); double max_r, max_d; tensor_cmp_host(out_host.data(), out_golden_host.data(), out_host.size(), max_r, max_d); LOG(INFO) << "ConfigName = " << p->ConfigName << "cmp result: max_r = " << max_r << " max_d = " << max_d; LOG(INFO) << "cmp elapse time: device( best : " <<t_device.get_best_ms() <<" ms , average : " << t_device.get_average_ms() << " ms) : host(" << t_host.get_average_ms() << " ms)"; } Env<AMD>::pop(); } int main(int argc, const char** argv) { anakin::saber::Env<AMD>::env_init(); //anakin::saber::Env<X86>::env_init(); // initial logger //logger::init(argv[0]); InitTest(); RUN_ALL_TESTS(argv[0]); return 0; }
35.420664
186
0.546411
vin-huang
315ba1f51a51fb7205726bf7db0ff5f0286d4f87
4,260
cpp
C++
Manipulator.cpp
gligneul/Bump-Mapping-Demo
a41ba1ee277c5151d4e075bd81a08b0baafb9db2
[ "MIT" ]
1
2020-05-09T03:27:17.000Z
2020-05-09T03:27:17.000Z
Manipulator.cpp
gligneul/Bump-Mapping-Demo
a41ba1ee277c5151d4e075bd81a08b0baafb9db2
[ "MIT" ]
null
null
null
Manipulator.cpp
gligneul/Bump-Mapping-Demo
a41ba1ee277c5151d4e075bd81a08b0baafb9db2
[ "MIT" ]
1
2020-06-25T12:16:50.000Z
2020-06-25T12:16:50.000Z
/* * The MIT License (MIT) * * Copyright (c) 2016 Gabriel de Quadros Ligneul * * 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 <iostream> #include <algorithm> #include <cmath> #include <glm/gtx/transform.hpp> #include <GL/gl.h> #include "Manipulator.h" Manipulator::Manipulator() : reference_(0, 0, 0), matrix_(1.0), operation_(Operation::kNone), x_(0), y_(0), v_(0, 0, 0), invertX_(false), invertY_(false), ball_size_(2.0f) { } glm::mat4 Manipulator::GetMatrix(const glm::vec3& look_dir) { glm::vec3 manip_dir = glm::vec3(0, 0, -1); if (glm::length(look_dir - manip_dir) < 0.01) return glm::translate(reference_) * matrix_ * glm::translate(-reference_); glm::vec3 w = glm::cross(look_dir, manip_dir); float theta = asin(glm::length(w)); return glm::translate(reference_) * glm::rotate(-theta, w) * matrix_ * glm::rotate(theta, w) * glm::translate(-reference_); } void Manipulator::SetReferencePoint(float x, float y, float z) { reference_ = glm::vec3(x, y, z); } void Manipulator::SetInvertAxis(bool invertX, bool invertY) { invertX_ = invertX; invertY_ = invertY; } void Manipulator::MouseClick(int button, int pressed, int x, int y) { SetOperation<0, Operation::kRotation>(button, pressed, x, y); SetOperation<1, Operation::kZoom>(button, pressed, x, y); } void Manipulator::MouseMotion(int x, int y) { if (operation_ == Operation::kNone) return; if (operation_ == Operation::kRotation) { glm::vec3 v = computeSphereCoordinates(x, y); glm::vec3 w = glm::cross(v_, v); float theta = asin(glm::length(w)) * ball_size_; if (theta != 0) matrix_ = glm::rotate(theta, w) * matrix_; v_ = v; } else if (operation_ == Operation::kZoom) { int vp[4]; glGetIntegerv(GL_VIEWPORT, vp); float dy = y - y_; float f = dy / vp[3]; float scale = 1 + kZoomScale * f; matrix_ = glm::scale(glm::vec3(scale, scale, scale)) * matrix_; } x_ = x; y_ = y; } template<int k_button, Manipulator::Operation k_operation> void Manipulator::SetOperation(int button, int pressed, int x, int y) { if (button == k_button) { if (pressed == 1 && operation_ == Operation::kNone) { operation_ = k_operation; x_ = x; y_ = y; v_ = computeSphereCoordinates(x, y); } else if (pressed == 0 && operation_ == k_operation) { operation_ = Operation::kNone; } } } glm::vec3 Manipulator::computeSphereCoordinates(int x, int y) { int vp[4]; glGetIntegerv(GL_VIEWPORT, vp); const float w = vp[2]; const float h = vp[3]; if (invertX_) x = w - x; if (invertY_) y = h - y; const float radius = std::min(w / 2.0f, h / 2.0f) * ball_size_; float vx = (x - w / 2.0f) / radius; float vy = (h - y - h / 2.0f) / radius; float vz = 0; const float dist = hypot(vx, vy); if (dist > 1.0f) { vx /= dist; vy /= dist; } else { vz = sqrt(1 - vx * vx - vy * vy); } return glm::vec3(vx, vy, vz); }
30.647482
81
0.619718
gligneul
3168b7db7aa96c8d25222a94a9d48d76bf5cd535
2,372
hpp
C++
test/include/gtest_basisforminimumfrobeniusnormmodel.hpp
snowpac/snowpac
ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305
[ "BSD-2-Clause" ]
3
2019-08-04T20:18:00.000Z
2021-06-22T23:50:27.000Z
test/include/gtest_basisforminimumfrobeniusnormmodel.hpp
snowpac/snowpac
ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305
[ "BSD-2-Clause" ]
null
null
null
test/include/gtest_basisforminimumfrobeniusnormmodel.hpp
snowpac/snowpac
ff4c6a83e01fc4ef6a78cf9ff9bf9358f972b305
[ "BSD-2-Clause" ]
null
null
null
#include "gtest/gtest.h" #include "MonomialBasisForMinimumFrobeniusNormModel.hpp" //-------------------------------------------------------------------------------- class Wrapper_MonomialBasisForMinimumFrobeniusNormModel { public: int basisformfnmodel_test1 ( ) { int dim = 2; MonomialBasisForMinimumFrobeniusNormModel basis( dim ); std::vector<double> node( dim ); std::vector< std::vector<double> > nodes; for ( int j = 0; j < dim; ++j ) node.at(j) = 0e0; nodes.push_back( node ); for ( int i = 0; i < dim; ++i ) { for ( int j = 0; j < dim; ++j ) node.at(j) = 0e0; node.at(i) = 1e0; nodes.push_back( node ); for ( int j = 0; j < dim; ++j ) node.at(j) = 0e0; node.at(i) = -1e0; nodes.push_back( node ); } for ( int j = 0; j < dim; ++j ) node.at(j) = -1e-1; node.at(0) = 1e-2; nodes.push_back( node ); basis.compute_basis_coefficients ( nodes ); std::vector<double> basis_evaluations; int test_passed = 1; for ( unsigned int i = 0; i < nodes.size(); ++i ) { basis_evaluations = basis.evaluate( nodes[i] ); for ( unsigned int j = 0; j < nodes.size(); ++j ) { if ( j == i && fabs( basis_evaluations.at(j) - 1e0 ) > 1e-6 ) { std::cout << "Something is wrong at node " << i << " and basis " << j << std::endl; std::cout << "Error in evaluation = " << basis_evaluations.at(j) - 1e0 << std::endl; test_passed = 0; } if ( j != i && fabs( basis_evaluations.at(j) - 0e0 ) > 1e-6 ) { std::cout << "Something is wrong at node " << i << " and basis " << j << std::endl; std::cout << "Error in evaluation = " << basis_evaluations.at(j) - 1e0 << std::endl; test_passed = 0; } } } return test_passed; } }; //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- TEST ( MonomialBasisForMinimumFrobeniusNormModelTest, basisformfnmodel_test1 ) { Wrapper_MonomialBasisForMinimumFrobeniusNormModel W; EXPECT_EQ( 1, W.basisformfnmodel_test1() ); } //--------------------------------------------------------------------------------
34.376812
96
0.46543
snowpac
316d4ea4ab5a2e01527f46aefddfb99a9b64db8b
877
cpp
C++
homework3.7/homework3.7.cpp
Valero4ca/individual-tasks
04aa20f3363543d4602ada0625aa99198f04dfac
[ "MIT" ]
null
null
null
homework3.7/homework3.7.cpp
Valero4ca/individual-tasks
04aa20f3363543d4602ada0625aa99198f04dfac
[ "MIT" ]
null
null
null
homework3.7/homework3.7.cpp
Valero4ca/individual-tasks
04aa20f3363543d4602ada0625aa99198f04dfac
[ "MIT" ]
null
null
null
#include <iostream> int main() { setlocale(LC_ALL, "RUS"); int** M, strnum; int m_size,sum=0; std::cout << "Введите размер матрицы:"; std::cin >> m_size; srand(time(0)); M = new int* [m_size]; for (int i = 0; i < m_size; i++) { M[i] = new int[m_size]; for (int j = 0; j < m_size; j++) { M[i][j] = 1 + rand() % 10; } } for (int i = 0; i < m_size; i++) { for (int j = 0; j < m_size; j++) { std::cout << M[i][j] << " "; } std::cout << std::endl; } int min = 11; for (int i = 0; i < m_size; i++) { for (int j = 0; j < m_size; j++) { if (M[i][j] < min) { min = M[i][j]; strnum = i; } } } std::cout << "Минимальное число: " << min << std::endl; std::cout << "Номер строки: " << strnum << std::endl; for (int i = 0; i < m_size; i++) { sum += M[strnum][i]; } std::cout << "Сумма элементов строки:" << sum; }
15.945455
56
0.477765
Valero4ca
3177781186d170db4889c23cee98e2bf158e71d0
6,309
cpp
C++
src/apps/src/example_slam.cpp
smarc-project/bathymetric_slam
87bc336eee9d978b75a588fccdbbc2d3c1c0edc7
[ "BSD-3-Clause" ]
2
2020-03-03T09:20:06.000Z
2021-06-01T02:59:41.000Z
src/apps/src/example_slam.cpp
smarc-project/bathymetric_slam
87bc336eee9d978b75a588fccdbbc2d3c1c0edc7
[ "BSD-3-Clause" ]
null
null
null
src/apps/src/example_slam.cpp
smarc-project/bathymetric_slam
87bc336eee9d978b75a588fccdbbc2d3c1c0edc7
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2019 Ignacio Torroba ([email protected]) * * 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. */ #include <fstream> #include <sstream> #include <iostream> #include <algorithm> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <cereal/archives/binary.hpp> #include "data_tools/std_data.h" #include "data_tools/benchmark.h" #include "submaps_tools/cxxopts.hpp" #include "submaps_tools/submaps.hpp" #include "registration/utils_visualization.hpp" #include "registration/gicp_reg.hpp" #include "graph_optimization/graph_construction.hpp" #include "graph_optimization/ceres_optimizer.hpp" #include "bathy_slam/bathy_slam.hpp" using namespace Eigen; using namespace std; using namespace g2o; int main(int argc, char** argv){ // Inputs std::string path_str, output_str, auvlib_cereal, simulation; cxxopts::Options options("MyProgram", "Graph SLAM solver for bathymetric maps"); options.add_options() ("help", "Print help") ("input_dataset", "Input batymetric survey as a cereal file or folder with .pdc submaps", cxxopts::value(path_str)) ("simulation", "(yes/no). Simulation data from Gazebo (.pdc submaps)", cxxopts::value(simulation)) ("auvlib_cereal", "(yes/no). Cereal output from AUVLib or from this solver", cxxopts::value(auvlib_cereal)) ("output_cereal", "Output graph in cereal format", cxxopts::value(output_str)); auto result = options.parse(argc, argv); if (result.count("help")) { cout << options.help({ "", "Group" }) << endl; exit(0); } if(output_str.empty()){ output_str = "output_cereal.cereal"; } boost::filesystem::path output_path(output_str); string outFilename = "graph_corrupted.g2o"; // G2O output file // Parse submaps from cereal file SubmapsVec submaps_gt; boost::filesystem::path submaps_path(path_str); std::cout << "Input data " << boost::filesystem::basename(submaps_path) << std::endl; if(simulation == "yes"){ submaps_gt = readSubmapsInDir(submaps_path.string()); } else{ if(auvlib_cereal == "yes"){ std_data::pt_submaps ss = std_data::read_data<std_data::pt_submaps>(submaps_path); submaps_gt = parseSubmapsAUVlib(ss); } else{ std::ifstream is(boost::filesystem::basename(submaps_path) + ".cereal", std::ifstream::binary); { cereal::BinaryInputArchive iarchive(is); iarchive(submaps_gt); } } // Voxelization of submaps PointCloudT::Ptr cloud_ptr (new PointCloudT); pcl::UniformSampling<PointT> us_filter; us_filter.setInputCloud (cloud_ptr); us_filter.setRadiusSearch(0.1); for(SubmapObj& submap_i: submaps_gt){ *cloud_ptr = submap_i.submap_pcl_; us_filter.setInputCloud(cloud_ptr); us_filter.filter(*cloud_ptr); submap_i.submap_pcl_ = *cloud_ptr; } } // Benchmark GT benchmark::track_error_benchmark benchmark("auv_data"); PointsT gt_map = pclToMatrixSubmap(submaps_gt); PointsT gt_track = trackToMatrixSubmap(submaps_gt); benchmark.add_ground_truth(gt_map, gt_track); ceres::optimizer::saveOriginalTrajectory(submaps_gt); // Save original graph and AUV trajectory // Visualization PCLVisualizer viewer ("SLAM viewer"); SubmapsVisualizer visualizer(viewer); // GICP reg for submaps SubmapRegistration gicp_reg; // Graph constructor GraphConstructor graph_obj; google::InitGoogleLogging(argv[0]); // Create SLAM solver and run offline BathySlam* slam_solver = new BathySlam(graph_obj, gicp_reg, viewer, visualizer); SubmapsVec submaps_reg = slam_solver->runOffline(submaps_gt); // Save graph to cereal file std::cout << "Output cereal: " << boost::filesystem::basename(output_path) << std::endl; std::ofstream os(boost::filesystem::basename(output_path) + ".cereal", std::ofstream::binary); { cereal::BinaryOutputArchive oarchive(os); oarchive(submaps_reg); os.close(); } // Visualize optimized solution visualizer.plotPoseGraphCeres(submaps_reg); while(!viewer.wasStopped ()){ viewer.spinOnce (); } viewer.resetStoppedFlag(); // Benchmark Optimized PointsT opt_map = pclToMatrixSubmap(submaps_reg); PointsT opt_track = trackToMatrixSubmap(submaps_reg); benchmark.add_benchmark(opt_map, opt_track, "optimized"); benchmark.print_summary(); // Plot initial and optimized trajectories std::string command_str = "./plot_results.py --initial_poses poses_original.txt " "--corrupted_poses poses_corrupted.txt --optimized_poses poses_optimized.txt"; const char *command = command_str.c_str(); system(command); delete(slam_solver); return 0; }
42.918367
758
0.707719
smarc-project
317799301f217304b5b834efac4932ee6a50649d
24,524
cc
C++
src/mlio/csv_reader.cc
babak2520/ml-io
87bedf9537959260723ed0419a0803c76e015ef5
[ "Apache-2.0" ]
69
2019-10-14T18:55:50.000Z
2022-02-28T05:50:39.000Z
src/mlio/csv_reader.cc
cbalioglu/ml-io
d79a895c3fe5e10f0f832cfdcee5a73058abb7c7
[ "Apache-2.0" ]
18
2019-11-16T12:45:40.000Z
2022-01-29T03:47:52.000Z
src/mlio/csv_reader.cc
cbalioglu/ml-io
d79a895c3fe5e10f0f832cfdcee5a73058abb7c7
[ "Apache-2.0" ]
16
2019-10-24T22:35:51.000Z
2021-09-03T18:23:04.000Z
/* * Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ #include "mlio/csv_reader.h" #include <atomic> #include <exception> #include <stdexcept> #include <tuple> #include <type_traits> #include <utility> #include <fmt/format.h> #include <tbb/tbb.h> #include "mlio/cpu_array.h" #include "mlio/csv_record_tokenizer.h" #include "mlio/data_reader.h" #include "mlio/data_reader_error.h" #include "mlio/data_stores/data_store.h" #include "mlio/example.h" #include "mlio/instance.h" #include "mlio/instance_batch.h" #include "mlio/logger.h" #include "mlio/memory/memory_slice.h" #include "mlio/record_readers/csv_record_reader.h" #include "mlio/record_readers/record.h" #include "mlio/record_readers/record_error.h" #include "mlio/record_readers/record_reader.h" #include "mlio/span.h" #include "mlio/streams/input_stream.h" #include "mlio/streams/utf8_input_stream.h" #include "mlio/tensor.h" using mlio::detail::Csv_record_reader; using mlio::detail::Csv_record_tokenizer; namespace mlio { inline namespace abi_v1 { struct Csv_reader::Decoder_state { explicit Decoder_state(const Csv_reader &r, std::vector<Intrusive_ptr<Tensor>> &t) noexcept; const Csv_reader *reader; std::vector<Intrusive_ptr<Tensor>> *tensors; bool warn_bad_instance; bool error_bad_example; }; template<typename Col_iter> class Csv_reader::Decoder { public: explicit Decoder(Decoder_state &state, Csv_record_tokenizer &tokenizer, Col_iter col_beg, Col_iter col_end) : state_{&state}, tokenizer_{&tokenizer}, col_beg_{col_beg}, col_end_{col_end} {} bool decode(std::size_t row_idx, const Instance &instance); private: Decoder_state *state_; Csv_record_tokenizer *tokenizer_; Col_iter col_beg_; Col_iter col_end_; }; Csv_reader::Csv_reader(Data_reader_params params, Csv_params csv_params) : Parallel_data_reader{std::move(params)}, params_{std::move(csv_params)} { column_names_ = params_.column_names; } Csv_reader::~Csv_reader() { stop(); } void Csv_reader::reset() noexcept { Parallel_data_reader::reset(); should_read_header = true; } Intrusive_ptr<Record_reader> Csv_reader::make_record_reader(const Data_store &store) { auto stream = make_utf8_stream(store.open_read(), params_.encoding); auto reader = make_intrusive<Csv_record_reader>(std::move(stream), params_); if (params_.header_row_index) { // Check if the caller did not explicitly specified the column // names and requested us to infer them from the header. if (column_names_.empty()) { read_names_from_header(store, *reader); } else if (should_read_header || !params_.has_single_header) { skip_to_header_row(*reader); // Discard the header row. reader->read_record(); } should_read_header = false; } return std::move(reader); } void Csv_reader::read_names_from_header(const Data_store &store, Record_reader &reader) { skip_to_header_row(reader); try { std::optional<Record> hdr = reader.read_record(); if (hdr == std::nullopt) { return; } Csv_record_tokenizer tokenizer{params_, hdr->payload()}; while (tokenizer.next()) { std::string name; if (params_.name_prefix.empty()) { name = tokenizer.value(); } else { name = params_.name_prefix + tokenizer.value(); } column_names_.emplace_back(std::move(name)); } } catch (const Corrupt_record_error &) { std::throw_with_nested(Schema_error{fmt::format( "The header row of the data store '{0}' cannot be read. See nested exception for details.", store.id())}); } // If the header row was blank, we treat it as a single column with // an blank name. if (column_names_.empty()) { column_names_.emplace_back(params_.name_prefix); } } void Csv_reader::skip_to_header_row(Record_reader &reader) { std::size_t header_idx = *params_.header_row_index; for (std::size_t i = 0; i < header_idx; i++) { std::optional<Record> record = reader.read_record(); if (record == std::nullopt) { return; } } } Intrusive_ptr<const Schema> Csv_reader::infer_schema(const std::optional<Instance> &instance) { // If we don't have any data rows and if the store has no header or // explicit column names, we have no way to infer the schema. if (instance == std::nullopt && column_names_.empty()) { return {}; } infer_column_types(instance); set_or_validate_column_names(instance); apply_column_type_overrides(); return init_parsers_and_make_schema(); } void Csv_reader::infer_column_types(const std::optional<Instance> &instance) { // If we don't have any data rows, assume that all fields are of the // default data type or of type string. if (instance == std::nullopt) { column_types_.reserve(column_names_.size()); for (std::size_t i = 0; i < column_names_.size(); i++) { Data_type dt{}; if (params_.default_data_type == std::nullopt) { dt = Data_type::string; } else { dt = *params_.default_data_type; } column_types_.emplace_back(dt); } } else { try { Csv_record_tokenizer tokenizer{params_, instance->bits()}; while (tokenizer.next()) { Data_type dt{}; if (params_.default_data_type == std::nullopt) { dt = infer_data_type(tokenizer.value()); } else { dt = *params_.default_data_type; } column_types_.emplace_back(dt); } } catch (const Corrupt_record_error &) { std::throw_with_nested(Schema_error{fmt::format( "The schema of the data store '{0}' cannot be inferred. See nested exception for details.", instance->data_store().id())}); } } } void Csv_reader::set_or_validate_column_names(const std::optional<Instance> &instance) { if (column_names_.empty()) { column_names_.reserve(column_types_.size()); for (std::size_t idx = 1; idx <= column_types_.size(); idx++) { std::string name{}; if (params_.name_prefix.empty()) { name = fmt::to_string(idx); } else { name = params_.name_prefix + fmt::to_string(idx); } column_names_.emplace_back(std::move(name)); } } else { if (column_names_.size() != column_types_.size()) { throw Schema_error{fmt::format( "The number of columns ({3:n}) read from the row #{1:n} in the data store '{0}' does not match the number of headers ({2:n}).", instance->data_store().id(), instance->index(), column_names_.size(), column_types_.size())}; } } } void Csv_reader::apply_column_type_overrides() { std::size_t num_columns = column_names_.size(); auto idx_beg = tbb::counting_iterator<std::size_t>(0); auto idx_end = tbb::counting_iterator<std::size_t>(num_columns); auto name_beg = column_names_.begin(); auto name_end = column_names_.end(); auto type_beg = column_types_.begin(); auto type_end = column_types_.end(); auto col_beg = tbb::make_zip_iterator(idx_beg, name_beg, type_beg); auto col_end = tbb::make_zip_iterator(idx_end, name_end, type_end); // Override column types by index. auto idx_overrides = params_.column_types_by_index; for (auto col_pos = col_beg; col_pos < col_end; ++col_pos) { auto idx_type_pos = idx_overrides.find(std::get<0>(*col_pos)); if (idx_type_pos != idx_overrides.end()) { std::get<2>(*col_pos) = idx_type_pos->second; idx_overrides.erase(idx_type_pos); } } // Throw an error if there are leftover indices. if (!idx_overrides.empty()) { std::vector<std::size_t> leftover_indices{}; leftover_indices.reserve(idx_overrides.size()); for (auto &pr : idx_overrides) { leftover_indices.emplace_back(pr.first); } throw std::invalid_argument{fmt::format( "The column types cannot be set. The following column indices are out of range: {0}", fmt::join(leftover_indices, ", "))}; } // Override column types by name. auto name_overrides = params_.column_types; for (auto col_pos = col_beg; col_pos < col_end; ++col_pos) { auto name_type_pos = name_overrides.find(std::get<1>(*col_pos)); if (name_type_pos != name_overrides.end()) { std::get<2>(*col_pos) = name_type_pos->second; name_overrides.erase(name_type_pos); } } // Throw an error if there are leftover names. if (!name_overrides.empty()) { std::vector<std::string> leftover_names{}; leftover_names.reserve(name_overrides.size()); for (auto &pr : name_overrides) { leftover_names.emplace_back(pr.first); } throw std::invalid_argument{fmt::format( "The column types cannot be set. The following columns are not found in the dataset: {0}", fmt::join(leftover_names, ", "))}; } } Intrusive_ptr<const Schema> Csv_reader::init_parsers_and_make_schema() { std::size_t batch_size = params().batch_size; std::vector<Attribute> attrs{}; std::size_t num_columns = column_names_.size(); column_ignores_.reserve(num_columns); column_parsers_.reserve(num_columns); auto idx_beg = tbb::counting_iterator<std::size_t>(0); auto idx_end = tbb::counting_iterator<std::size_t>(num_columns); auto name_beg = column_names_.begin(); auto name_end = column_names_.end(); auto type_beg = column_types_.begin(); auto type_end = column_types_.end(); auto col_beg = tbb::make_zip_iterator(idx_beg, name_beg, type_beg); auto col_end = tbb::make_zip_iterator(idx_end, name_end, type_end); std::unordered_map<std::string, std::size_t> name_counts{}; for (auto col_pos = col_beg; col_pos < col_end; ++col_pos) { std::string name = std::get<1>(*col_pos); if (should_skip(std::get<0>(*col_pos), name)) { column_ignores_.emplace_back(1); column_parsers_.emplace_back(nullptr); continue; } Data_type dt = std::get<2>(*col_pos); column_ignores_.emplace_back(0); column_parsers_.emplace_back(make_parser(dt, params_.parser_options)); if (params_.dedupe_column_names) { // Keep count of column names. If the key already exists, // create a new name by appending an underscore plus count. // Since this new name might also exist, iterate until we // can insert the new name. auto [pos, inserted] = name_counts.try_emplace(name, 0); while (!inserted) { name.append("_").append(fmt::to_string(pos->second++)); std::tie(pos, inserted) = name_counts.try_emplace(name, 0); } pos->second++; } attrs.emplace_back(std::move(name), dt, Size_vector{batch_size, 1}); } try { return make_intrusive<Schema>(attrs); } catch (const std::invalid_argument &) { std::unordered_set<std::string_view> tmp{}; for (auto &attr : attrs) { if (auto pr = tmp.emplace(attr.name()); !pr.second) { throw Schema_error{fmt::format( "The dataset contains more than one column with the name '{0}'.", *pr.first)}; } } throw; } } bool Csv_reader::should_skip(std::size_t index, const std::string &name) const noexcept { auto uci = params_.use_columns_by_index; if (!uci.empty()) { if (uci.find(index) == uci.end()) { return true; } } auto ucn = params_.use_columns; if (!ucn.empty()) { if (ucn.find(name) == ucn.end()) { return true; } } return false; } Intrusive_ptr<Example> Csv_reader::decode(const Instance_batch &batch) const { auto tensors = make_tensors(batch.size()); Decoder_state state{*this, tensors}; std::size_t num_instances = batch.instances().size(); constexpr std::size_t cut_off = 10'000'000; bool should_run_serial = // If bad example handling mode is pad, we cannot parallelize // decoding as good records must be stacked together without // any gap in between. params().bad_example_handling == Bad_example_handling::pad || params().bad_example_handling == Bad_example_handling::pad_warn || // If the number of values (e.g. integers, floating-points) we // need to decode is below the cut-off threshold, avoid parallel // execution; otherwise the threading overhead will potentially // slow down the performance. column_names_.size() * num_instances < cut_off; std::optional<std::size_t> num_instances_read{}; if (should_run_serial) { num_instances_read = decode_ser(state, batch); } else { num_instances_read = decode_prl(state, batch); } // Check if we failed to decode the example and return a null // pointer if that is the case. if (num_instances_read == std::nullopt) { if (params().bad_example_handling == Bad_example_handling::skip_warn) { logger::warn("The example #{0:n} has been skipped as it had at least one bad instance.", batch.index()); } return nullptr; } if (num_instances != *num_instances_read) { if (params().bad_example_handling == Bad_example_handling::pad_warn) { logger::warn("The example #{0:n} has been padded as it had {1:n} bad instance(s).", batch.index(), num_instances - *num_instances_read); } } auto example = make_intrusive<Example>(schema(), std::move(tensors)); example->padding = batch.size() - *num_instances_read; return example; } std::vector<Intrusive_ptr<Tensor>> Csv_reader::make_tensors(std::size_t batch_size) const { std::vector<Intrusive_ptr<Tensor>> tensors{}; tensors.reserve(column_types_.size() - column_ignores_.size()); auto type_beg = column_types_.begin(); auto type_end = column_types_.end(); auto ignore_beg = column_ignores_.begin(); auto ignore_end = column_ignores_.end(); auto col_beg = tbb::make_zip_iterator(type_beg, ignore_beg); auto col_end = tbb::make_zip_iterator(type_end, ignore_end); for (auto col_pos = col_beg; col_pos < col_end; ++col_pos) { // Check if we should skip this column. if (std::get<1>(*col_pos) != 0) { continue; } Size_vector shape{batch_size, 1}; Data_type dt = std::get<0>(*col_pos); std::unique_ptr<Device_array> arr = make_cpu_array(dt, batch_size); tensors.emplace_back(make_intrusive<Dense_tensor>(std::move(shape), std::move(arr))); } return tensors; } auto Csv_reader::make_column_iterators() const noexcept { std::size_t num_columns = column_names_.size(); auto col_idx_beg = tbb::counting_iterator<std::size_t>(0); auto col_idx_end = tbb::counting_iterator<std::size_t>(num_columns); auto name_beg = column_names_.begin(); auto name_end = column_names_.end(); auto type_beg = column_types_.begin(); auto type_end = column_types_.end(); auto ignore_beg = column_ignores_.begin(); auto ignore_end = column_ignores_.end(); auto parser_beg = column_parsers_.begin(); auto parser_end = column_parsers_.end(); auto col_beg = tbb::make_zip_iterator(col_idx_beg, name_beg, type_beg, ignore_beg, parser_beg); auto col_end = tbb::make_zip_iterator(col_idx_end, name_end, type_end, ignore_end, parser_end); return std::make_pair(col_beg, col_end); } std::optional<std::size_t> Csv_reader::decode_ser(Decoder_state &state, const Instance_batch &batch) const { std::size_t row_idx = 0; Csv_record_tokenizer tokenizer{params_}; auto [col_beg, col_end] = make_column_iterators(); for (const Instance &instance : batch.instances()) { Decoder<decltype(col_beg)> decoder{state, tokenizer, col_beg, col_end}; if (decoder.decode(row_idx, instance)) { row_idx++; } else { // If the user requested to skip the example in case of an // error, shortcut the loop and return immediately. if (params().bad_example_handling == Bad_example_handling::skip || params().bad_example_handling == Bad_example_handling::skip_warn) { return {}; } if (params().bad_example_handling != Bad_example_handling::pad && params().bad_example_handling != Bad_example_handling::pad_warn) { throw std::invalid_argument{"The specified bad example handling is invalid."}; } } } return row_idx; } std::optional<std::size_t> Csv_reader::decode_prl(Decoder_state &state, const Instance_batch &batch) const { std::atomic_bool skip_example{}; std::size_t num_instances = batch.instances().size(); auto row_idx_beg = tbb::counting_iterator<std::size_t>(0); auto row_idx_end = tbb::counting_iterator<std::size_t>(num_instances); auto instance_beg = batch.instances().begin(); auto instance_end = batch.instances().end(); auto range_beg = tbb::make_zip_iterator(row_idx_beg, instance_beg); auto range_end = tbb::make_zip_iterator(row_idx_end, instance_end); tbb::blocked_range<decltype(range_beg)> range{range_beg, range_end}; auto worker = [this, &state, &skip_example](auto &sub_range) { Csv_record_tokenizer tokenizer{params_}; // Both GCC and clang have trouble handling structured bindings // in lambdas. auto iter_pair = make_column_iterators(); using Col_iter = std::remove_reference_t<decltype(std::get<0>(iter_pair))>; Col_iter col_beg = std::get<0>(iter_pair); Col_iter col_end = std::get<1>(iter_pair); for (auto instance_zip : sub_range) { // Both GCC and clang have a bug that prevents using class // template argument deduction (CTAD) with nested types. Decoder<Col_iter> decoder{state, tokenizer, col_beg, col_end}; if (!decoder.decode(std::get<0>(instance_zip), std::get<1>(instance_zip))) { // If we failed to decode the instance, we can terminate // the task right away and skip this example. if (params().bad_example_handling == Bad_example_handling::skip || params().bad_example_handling == Bad_example_handling::skip_warn) { skip_example = true; return; } throw std::invalid_argument{"The specified bad example handling is invalid."}; } } }; tbb::parallel_for(range, worker, tbb::auto_partitioner{}); if (skip_example) { return {}; } return num_instances; } Csv_reader::Decoder_state::Decoder_state(const Csv_reader &r, std::vector<Intrusive_ptr<Tensor>> &t) noexcept : reader{&r} , tensors{&t} , warn_bad_instance{r.warn_bad_instances()} , error_bad_example{r.params().bad_example_handling == Bad_example_handling::error} {} template<typename Col_iter> bool Csv_reader::Decoder<Col_iter>::decode(std::size_t row_idx, const Instance &instance) { auto col_pos = col_beg_; auto tsr_pos = state_->tensors->begin(); tokenizer_->reset(instance.bits()); while (tokenizer_->next()) { if (col_pos == col_end_) { break; } // Check if we should skip this column. if (std::get<3>(*col_pos) != 0) { ++col_pos; continue; } // Check if we truncated the field. if (tokenizer_->truncated()) { auto h = state_->reader->params_.max_field_length_handling; if (h == Max_field_length_handling::treat_as_bad || h == Max_field_length_handling::truncate_warn) { const std::string &name = std::get<1>(*col_pos); auto msg = fmt::format( "The column '{2}' of the row #{1:n} in the data store '{0}' is too long. Its truncated value is '{3:.64}'.", instance.data_store().id(), instance.index(), name, tokenizer_->value()); if (h == Max_field_length_handling::truncate_warn) { logger::warn(msg); } else { if (state_->warn_bad_instance || state_->error_bad_example) { if (state_->warn_bad_instance) { logger::warn(msg); } if (state_->error_bad_example) { throw Invalid_instance_error{msg}; } } return false; } } else if (h != Max_field_length_handling::truncate) { throw std::invalid_argument{ "The specified maximum field length handling is invalid."}; } } const Parser &parser = std::get<4>(*col_pos); auto &dense_tensor = static_cast<Dense_tensor &>(**tsr_pos); Parse_result r = parser(tokenizer_->value(), dense_tensor.data(), row_idx); if (r == Parse_result::ok) { ++col_pos; ++tsr_pos; continue; } if (state_->warn_bad_instance || state_->error_bad_example) { const std::string &name = std::get<1>(*col_pos); Data_type dt = std::get<2>(*col_pos); auto msg = fmt::format( "The column '{2}' of the row #{1:n} in the data store '{0}' cannot be parsed as {3}. Its string value is '{4:.64}'.", instance.data_store().id(), instance.index(), name, dt, tokenizer_->value()); if (state_->warn_bad_instance) { logger::warn(msg); } if (state_->error_bad_example) { throw Invalid_instance_error{msg}; } } return false; } // Make sure we read all columns and there are no remaining fields. if (col_pos == col_end_ && tokenizer_->eof()) { return true; } if (state_->warn_bad_instance || state_->error_bad_example) { std::size_t num_columns = state_->reader->column_names_.size(); std::size_t num_actual_cols = std::get<0>(*col_pos); while (tokenizer_->next()) { num_actual_cols++; } if (col_pos == col_end_) { num_actual_cols++; } auto msg = fmt::format( "The row #{1:n} in the data store '{0}' has {2:n} column(s) while it is expected to have {3:n} column(s).", instance.data_store().id(), instance.index(), num_actual_cols, num_columns); if (state_->warn_bad_instance) { logger::warn(msg); } if (state_->error_bad_example) { throw Invalid_instance_error{msg}; } } return false; } } // namespace abi_v1 } // namespace mlio
32.310935
143
0.609852
babak2520
317cc3e33bfe480ffda502a1aa3ef5a5871e5334
414
hpp
C++
include/IOHandling/CommandLineUI.hpp
wndouglas/SudokuSolverNew
a4e57e97979932ef1ad390cbd0497ee1b603e6eb
[ "MIT" ]
null
null
null
include/IOHandling/CommandLineUI.hpp
wndouglas/SudokuSolverNew
a4e57e97979932ef1ad390cbd0497ee1b603e6eb
[ "MIT" ]
null
null
null
include/IOHandling/CommandLineUI.hpp
wndouglas/SudokuSolverNew
a4e57e97979932ef1ad390cbd0497ee1b603e6eb
[ "MIT" ]
null
null
null
#ifndef COMMAND_LINE_UI_HPP #define COMMAND_LINE_UI_HPP #include "UserInterface.hpp" #include <string> namespace SSLib { class CommandLineUI : public UserInterface { public: void Run(); CommandLineUI(std::string filePath, int numRows = 9, int numCols = 9); private: class CommandLineUiImpl; std::unique_ptr<CommandLineUiImpl> pCommandLineUiImpl; }; } #endif
18.818182
78
0.68599
wndouglas
31834871849006fc4dafb514529e24550e26dbf8
614
hpp
C++
ext/src/java/security/Key.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/security/Key.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/security/Key.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/security/fwd-POI.hpp> #include <java/io/Serializable.hpp> struct java::security::Key : public virtual ::java::io::Serializable { static constexpr int64_t serialVersionUID { int64_t(6603384152749567654LL) }; virtual ::java::lang::String* getAlgorithm() = 0; virtual ::int8_tArray* getEncoded() = 0; virtual ::java::lang::String* getFormat() = 0; // Generated static ::java::lang::Class *class_(); };
27.909091
97
0.701954
pebble2015
31848105b9355983fc77e0ad53a2a1c44562324c
2,412
hpp
C++
lab2/demo/computer.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
2
2015-10-08T15:07:07.000Z
2017-09-17T10:08:36.000Z
lab2/demo/computer.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
lab2/demo/computer.hpp
zaychenko-sergei/oop-ki13
97405077de1f66104ec95c1bb2785bc18445532d
[ "MIT" ]
null
null
null
#ifndef _COMPUTER_HPP_ #define _COMPUTER_HPP_ //************************************************************************ #include <string> #include <vector> //************************************************************************ class Employee; //************************************************************************ class Computer { /*-----------------------------------------------------------------*/ public: /*-----------------------------------------------------------------*/ enum Architecture { _32Bit, _64Bit }; /*-----------------------------------------------------------------*/ Computer ( int _inventoryID , Architecture _architecture , const std::string & _processorModel , int _ramGigabytes ); int getInventoryID () const; Architecture getArchitecture () const; const std::string & getProcessorModel () const; int getRamGigabytes () const; int getUsersCount () const; const Employee & getUser ( int _index ) const; void addUser ( const Employee & _user ); /*-----------------------------------------------------------------*/ private: /*-----------------------------------------------------------------*/ Computer ( const Computer & ); Computer & operator = ( const Computer & ); /*-----------------------------------------------------------------*/ const int m_inventoryID; const Architecture m_architecture; const std::string m_processorModel; const int m_ramGigabytes; std::vector< const Employee * > m_users; /*-----------------------------------------------------------------*/ }; //************************************************************************ inline int Computer::getInventoryID () const { return m_inventoryID; } //************************************************************************ inline Computer::Architecture Computer::getArchitecture () const { return m_architecture; } //************************************************************************ inline const std::string & Computer::getProcessorModel () const { return m_processorModel; } //************************************************************************ inline int Computer::getRamGigabytes () const { return m_ramGigabytes; } //************************************************************************ #endif // _COMPUTER_HPP_
22.333333
74
0.366086
zaychenko-sergei
318770274b1a4fb28b8406e557a30ca0780742ed
15,945
cpp
C++
src/joedb/io/Interpreter.cpp
Remi-Coulom/joedb
adb96600d9c2dd796684a5fee8f969c3e9fef456
[ "MIT" ]
89
2015-11-19T17:32:54.000Z
2021-12-14T18:52:09.000Z
src/joedb/io/Interpreter.cpp
Remi-Coulom/joedb
adb96600d9c2dd796684a5fee8f969c3e9fef456
[ "MIT" ]
7
2017-01-18T16:00:38.000Z
2021-12-25T20:55:04.000Z
src/joedb/io/Interpreter.cpp
Remi-Coulom/joedb
adb96600d9c2dd796684a5fee8f969c3e9fef456
[ "MIT" ]
9
2015-11-21T03:29:27.000Z
2021-10-03T14:49:08.000Z
#include "joedb/Writable.h" #include "joedb/is_identifier.h" #include "joedb/io/Interpreter.h" #include "joedb/interpreter/Database.h" #include "joedb/io/dump.h" #include "joedb/io/json.h" #include "joedb/io/Interpreter_Dump_Writable.h" #include "joedb/io/SQL_Dump_Writable.h" #include "joedb/io/type_io.h" #include "joedb/journal/diagnostics.h" #include "type_io.h" #include <iostream> #include <sstream> #include <ctime> #include <iomanip> namespace joedb { //////////////////////////////////////////////////////////////////////////// Type Readonly_Interpreter::parse_type //////////////////////////////////////////////////////////////////////////// ( std::istream &in, std::ostream &out ) const { std::string type_name; in >> type_name; if (type_name == "references") { std::string table_name; in >> table_name; Table_Id table_id = readable.find_table(table_name); if (table_id) return Type::reference(table_id); } #define TYPE_MACRO(type, return_type, type_id, read, write)\ if (type_name == #type_id)\ return Type::type_id(); #define TYPE_MACRO_NO_REFERENCE #include "joedb/TYPE_MACRO.h" throw Exception("unknown type"); } //////////////////////////////////////////////////////////////////////////// Table_Id Readonly_Interpreter::parse_table //////////////////////////////////////////////////////////////////////////// ( std::istream &in, std::ostream &out ) const { std::string table_name; in >> table_name; Table_Id table_id = readable.find_table(table_name); if (!table_id) { std::ostringstream error; error << "No such table: " << table_name; throw Exception(error.str()); } return table_id; } //////////////////////////////////////////////////////////////////////////// void Readonly_Interpreter::after_command //////////////////////////////////////////////////////////////////////////// ( std::ostream &out, int64_t line_number, const std::string &line, const Exception *exception ) const { if (exception) { std::ostringstream error; error << exception->what(); error << "\nLine " << line_number << ": " << line << '\n'; if (rethrow) throw Exception(error.str()); else out << "Error: " << error.str(); } else if (echo) out << "OK: " << line << '\n'; } //////////////////////////////////////////////////////////////////////////// void Interpreter::update_value //////////////////////////////////////////////////////////////////////////// ( std::istream &in, Table_Id table_id, Record_Id record_id, Field_Id field_id ) { switch(readable.get_field_type(table_id, field_id).get_type_id()) { case Type::Type_Id::null: throw Exception("bad field"); #define TYPE_MACRO(type, return_type, type_id, read_method, write_method)\ case Type::Type_Id::type_id:\ {\ type value = joedb::read_##type_id(in);\ writable.update_##type_id(table_id, record_id, field_id, value);\ }\ break; #include "joedb/TYPE_MACRO.h" } } //////////////////////////////////////////////////////////////////////////// bool Readonly_Interpreter::process_command //////////////////////////////////////////////////////////////////////////// ( const std::string &command, std::istream &iss, std::ostream &out ) { if (command.empty() || command[0] == '#') ///////////////////////////////// return true; else if (command == "table") ////////////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); size_t max_column_width = 25; { size_t w; if (iss >> w) max_column_width = w; } size_t start = 0; size_t length = 0; iss >> start >> length; if (table_id) { const auto &fields = readable.get_fields(table_id); std::map<Field_Id, size_t> column_width; for (auto field: fields) { size_t width = field.second.size(); column_width[field.first] = width; } // // Store values in strings to determine column widths // std::map<Field_Id, std::vector<std::string>> columns; std::vector<Record_Id> id_column; size_t rows = 0; const Record_Id last_record_id = readable.get_last_record_id(table_id); for (Record_Id record_id = 1; record_id <= last_record_id; record_id++) if ( readable.is_used(table_id, record_id) && (length == 0 || (record_id >= start && record_id < start + length)) ) { rows++; id_column.emplace_back(record_id); for (auto field: fields) { std::ostringstream ss; switch (readable.get_field_type(table_id, field.first).get_type_id()) { case Type::Type_Id::null: break; #define TYPE_MACRO(type, return_type, type_id, R, W)\ case Type::Type_Id::type_id:\ write_##type_id(ss, readable.get_##type_id(table_id, record_id, field.first));\ break; #include "joedb/TYPE_MACRO.h" } ss.flush(); { std::string s = ss.str(); const size_t width = utf8_display_size(s); if (column_width[field.first] < width) column_width[field.first] = width; columns[field.first].emplace_back(std::move(s)); } } } // // Determine table width // size_t id_width = 0; { std::ostringstream ss; ss << last_record_id; ss.flush(); id_width = ss.str().size(); } size_t table_width = id_width; for (auto field: fields) { if (max_column_width && column_width[field.first] > max_column_width) column_width[field.first] = max_column_width; table_width += column_width[field.first] + 1; } // // Table header // out << std::string(table_width, '-') << '\n'; out << std::string(id_width, ' '); for (auto field: fields) { const auto type = readable.get_field_type(table_id, field.first).get_type_id(); out << ' '; write_justified ( out, field.second, column_width[field.first], type == Type::Type_Id::string ); } out << '\n'; out << std::string(table_width, '-') << '\n'; // // Table data // for (size_t i = 0; i < rows; i++) { out << std::setw(int(id_width)) << id_column[i]; for (auto field: fields) { const auto type = readable.get_field_type(table_id, field.first).get_type_id(); out << ' '; write_justified ( out, columns[field.first][i], column_width[field.first], type == Type::Type_Id::string ); } out << '\n'; } } } else if (command == "schema") ///////////////////////////////////////////// { Interpreter_Dump_Writable dump_writable(out); dump(readable, dump_writable, true); } else if (command == "dump") /////////////////////////////////////////////// { Interpreter_Dump_Writable dump_writable(out); dump(readable, dump_writable); } else if (command == "sql") //////////////////////////////////////////////// { SQL_Dump_Writable dump_writable(out); dump(readable, dump_writable); } else if (command == "json") /////////////////////////////////////////////// { bool use_base64 = false; iss >> use_base64; write_json(out, readable, use_base64); } else if (command == "help") /////////////////////////////////////////////// { out << '\n'; out << "Commands unrelated to the database\n"; out << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; out << " about\n"; out << " help\n"; out << " quit\n"; out << " echo on|off\n"; out << '\n'; out << "Displaying data\n"; out << "~~~~~~~~~~~~~~~\n"; out << " table <table_name> [<max_column_width>] [start] [length]\n"; out << " schema\n"; out << " dump\n"; out << " sql\n"; out << " json [<base64>]\n"; out << '\n'; } else if (command == "about") ////////////////////////////////////////////// { about_joedb(out); } else if (command == "echo") /////////////////////////////////////////////// { std::string parameter; iss >> parameter; if (parameter == "on") set_echo(true); else if (parameter == "off") set_echo(false); } else if (command == "quit") /////////////////////////////////////////////// return false; else throw Exception("Unknown command. For a list of available commands, try \"help\"."); return true; } //////////////////////////////////////////////////////////////////////////// bool Interpreter::process_command //////////////////////////////////////////////////////////////////////////// ( const std::string &command, std::istream &iss, std::ostream &out ) { if (command == "help") //////////////////////////////////////////////////// { Readonly_Interpreter::process_command(command, iss, out); out << "Logging\n"; out << "~~~~~~~\n"; out << " timestamp [<stamp>] (if no value is given, use current time)\n"; out << " comment \"<comment_string>\"\n"; out << " valid_data\n"; out << " checkpoint\n"; out << '\n'; out << "Data definition\n"; out << "~~~~~~~~~~~~~~~\n"; out << " create_table <table_name>\n"; out << " drop_table <table_name>\n"; out << " rename_table <old_table_name> <new_table_name>\n"; out << " add_field <table_name> <field_name> <type>\n"; out << " drop_field <table_name> <field_name>\n"; out << " rename_field <table_name> <old_field_name> <new_field_name>\n"; out << " custom <custom_name>\n"; out << '\n'; out << " <type> may be:\n"; out << " string,\n"; out << " int8, int16, int32, int64,\n"; out << " float32, float64,\n"; out << " boolean,\n"; out << " references <table_name>\n"; out << '\n'; out << "Data manipulation\n"; out << "~~~~~~~~~~~~~~~~~\n"; out << " insert_into <table_name> <record_id>\n"; out << " insert_vector <table_name> <record_id> <size>\n"; out << " update <table_name> <record_id> <field_name> <value>\n"; out << " update_vector <table_name> <record_id> <field_name> <N> <v_1> ... <v_N>\n"; out << " delete_from <table_name> <record_id>\n"; out << '\n'; } else if (command == "create_table") /////////////////////////////////////// { std::string table_name; iss >> table_name; writable.create_table(table_name); } else if (command == "drop_table") ///////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); writable.drop_table(table_id); } else if (command == "rename_table") /////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); std::string new_name; iss >> new_name; writable.rename_table(table_id, new_name); } else if (command == "add_field") ////////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); std::string field_name; iss >> field_name; Type type = parse_type(iss, out); if (type.get_type_id() != Type::Type_Id::null) writable.add_field(table_id, field_name, type); } else if (command == "drop_field") //////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); std::string field_name; iss >> field_name; Field_Id field_id = readable.find_field(table_id, field_name); writable.drop_field(table_id, field_id); } else if (command == "rename_field") ////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); std::string field_name; iss >> field_name; Field_Id field_id = readable.find_field(table_id, field_name); std::string new_field_name; iss >> new_field_name; writable.rename_field(table_id, field_id, new_field_name); } else if (command == "custom") //////////////////////////////////////////// { std::string name; iss >> name; writable.custom(name); } else if (command == "comment") /////////////////////////////////////////// { const std::string comment = joedb::read_string(iss); writable.comment(comment); } else if (command == "timestamp") ///////////////////////////////////////// { int64_t timestamp = 0; iss >> timestamp; if (iss.fail()) timestamp = std::time(nullptr); writable.timestamp(timestamp); } else if (command == "valid_data") //////////////////////////////////////// { writable.valid_data(); } else if (command == "checkpoint") //////////////////////////////////////// { writable.checkpoint(Commit_Level::no_commit); } else if (command == "insert_into") /////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); Record_Id record_id = 0; iss >> record_id; if (record_id == 0) record_id = readable.get_last_record_id(table_id) + 1; writable.insert_into(table_id, record_id); if (iss.good()) for (const auto &field: readable.get_fields(table_id)) { update_value(iss, table_id, record_id, field.first); if (iss.fail()) throw Exception("failed parsing value"); } } else if (command == "insert_vector") ///////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); Record_Id record_id = 0; Record_Id size = 0; iss >> record_id >> size; writable.insert_vector(table_id, record_id, size); } else if (command == "update") //////////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); Record_Id record_id = 0; iss >> record_id; std::string field_name; iss >> field_name; Field_Id field_id = readable.find_field(table_id, field_name); update_value(iss, table_id, record_id, field_id); } else if (command == "update_vector") ///////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); Record_Id record_id = 0; iss >> record_id; std::string field_name; iss >> field_name; Field_Id field_id = readable.find_field(table_id, field_name); Record_Id size = 0; iss >> size; if (max_record_id != 0 && size >= max_record_id) throw Exception("vector is too big"); else { switch(readable.get_field_type(table_id, field_id).get_type_id()) { case Type::Type_Id::null: throw Exception("bad field"); break; #define TYPE_MACRO(type, return_type, type_id, R, W)\ case Type::Type_Id::type_id:\ {\ std::vector<type> v(size);\ for (size_t i = 0; i < size; i++)\ v[i] = joedb::read_##type_id(iss);\ writable.update_vector_##type_id(table_id, record_id, field_id, size, &v[0]);\ }\ break; #include "joedb/TYPE_MACRO.h" } } } else if (command == "delete_from") //////////////////////////////////////// { const Table_Id table_id = parse_table(iss, out); Record_Id record_id = 0; iss >> record_id; writable.delete_from(table_id, record_id); } else return Readonly_Interpreter::process_command(command, iss, out); return true; } //////////////////////////////////////////////////////////////////////////// void Readonly_Interpreter::main_loop //////////////////////////////////////////////////////////////////////////// ( std::istream &in, std::ostream &out ) { int64_t line_number = 0; std::string line; while(std::getline(in, line)) { line_number++; std::istringstream iss(line); std::string command; iss >> command; try { const bool again = process_command(command, iss, out); after_command(out, line_number, line, nullptr); if (!again) break; } catch (const Exception &e) { after_command(out, line_number, line, &e); } } } //////////////////////////////////////////////////////////////////////////// void Interpreter::main_loop //////////////////////////////////////////////////////////////////////////// ( std::istream &in, std::ostream &out ) { Readonly_Interpreter::main_loop(in, out); writable.checkpoint(Commit_Level::no_commit); } }
28.022847
88
0.521229
Remi-Coulom
31878ed65ea5acdc653dc9a8e9b966babfa48bc8
989
cpp
C++
Source/UnrealDevMenu/Private/Adapter/DevMenuAdapterInt_DevMenuParam.cpp
laycnc/UnrealDevMenu
a41d31b6f28e2b4c81d830f743fb7a8948a00a83
[ "MIT" ]
null
null
null
Source/UnrealDevMenu/Private/Adapter/DevMenuAdapterInt_DevMenuParam.cpp
laycnc/UnrealDevMenu
a41d31b6f28e2b4c81d830f743fb7a8948a00a83
[ "MIT" ]
null
null
null
Source/UnrealDevMenu/Private/Adapter/DevMenuAdapterInt_DevMenuParam.cpp
laycnc/UnrealDevMenu
a41d31b6f28e2b4c81d830f743fb7a8948a00a83
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Adapter/DevMenuAdapterInt_DevMenuParam.h" #include "DevMenuSubsystem.h" #include "DevParamSubsystem.h" UDevMenuAdapterInt_DevMenuParam::UDevMenuAdapterInt_DevMenuParam( const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } // 値が設定された void UDevMenuAdapterInt_DevMenuParam::SetValue_Implementation( UDevMenuSubsystem* InSubsystem, int32 NewValue) const { UDevParamSubsystem* DevParamSystem = UDevParamSubsystem::Get(InSubsystem); if ( DevParamSystem ) { DevParamSystem->SetValueByInt32(ParamId, NewValue); } } // 値の取得 int32 UDevMenuAdapterInt_DevMenuParam::GetValue_Implementation( UDevMenuSubsystem* InSubsystem) const { int32 Result = 0; UDevParamSubsystem* DevParamSystem = UDevParamSubsystem::Get(InSubsystem); if ( DevParamSystem ) { DevParamSystem->GetValueByInt32(ParamId, Result); } return Result; }
27.472222
78
0.766431
laycnc
318eddaca0d233835aca06f80ce0c75a00611230
20,248
cc
C++
computer_vision/focus_lane_detection/InversePerspectiveMapping.cc
rajnikant1010/EVAutomation
a9e27e8916fd6dfc060dac1496a3b2f327ef6322
[ "BSD-2-Clause" ]
3
2019-06-13T02:41:49.000Z
2021-02-13T15:42:36.000Z
computer_vision/focus_lane_detection/InversePerspectiveMapping.cc
rajnikant1010/EVAutomation
a9e27e8916fd6dfc060dac1496a3b2f327ef6322
[ "BSD-2-Clause" ]
null
null
null
computer_vision/focus_lane_detection/InversePerspectiveMapping.cc
rajnikant1010/EVAutomation
a9e27e8916fd6dfc060dac1496a3b2f327ef6322
[ "BSD-2-Clause" ]
8
2017-02-24T02:17:28.000Z
2021-04-22T08:25:00.000Z
/*** * \file InversePerspectiveMapping.cc * \author Mohamed Aly <[email protected]> * \date 11/29/2006 */ #include "InversePerspectiveMapping.hh" #include "CameraInfoOpt.h" #include <iostream> #include <math.h> #include <assert.h> #include <list> using namespace std; #include <cv.h> #include <highgui.h> namespace LaneDetector { #define VP_PORTION 0.05 /* We are assuming the world coordinate frame center is at the camera, the ground plane is at height -h, the X-axis is going right, the Y-axis is going forward, the Z-axis is going up. The camera is looking forward with optical axis in direction of Y-axis, with possible pitch angle (above or below the Y-axis) and yaw angle (left or right). The camera coordinates have the same center as the world, but the Xc-axis goes right, the Yc-axis goes down, and the Zc-axis (optical cxis) goes forward. The uv-plane of the image is such that u is horizontal going right, v is vertical going down. The image coordinates uv are such that the pixels are at half coordinates i.e. first pixel is (.5,.5) ...etc where the top-left point is (0,0) i.e. the tip of the first pixel is (0,0) */ /** * This function returns the Inverse Perspective Mapping * of the input image, assuming a flat ground plane, and * given the camera parameters. * * \param inImage the input image * \param outImage the output image in IPM * \param ipmInfo the returned IPM info for the transformation * \param focalLength focal length (in x and y direction) * \param cameraInfo the camera parameters * \param outPoints indices of points outside the image */ void mcvGetIPM(const CvMat* inImage, CvMat* outImage, IPMInfo *ipmInfo, const CameraInfo *cameraInfo, list<CvPoint> *outPoints) { //check input images types //CvMat inMat, outMat; //cvGetMat(inImage, &inMat); //cvGetMat(outImage, &outMat); //cout << CV_MAT_TYPE(inImage->type) << " " << CV_MAT_TYPE(FLOAT_MAT_TYPE) << " " << CV_MAT_TYPE(INT_MAT_TYPE)<<"\n"; if (!(CV_ARE_TYPES_EQ(inImage, outImage) && (CV_MAT_TYPE(inImage->type)==CV_MAT_TYPE(FLOAT_MAT_TYPE) || (CV_MAT_TYPE(inImage->type)==CV_MAT_TYPE(INT_MAT_TYPE))))) { cerr << "Unsupported image types in mcvGetIPM"; exit(1); } //get size of input image FLOAT u, v; v = inImage->height; u = inImage->width; //get the vanishing point FLOAT_POINT2D vp; vp = mcvGetVanishingPoint(cameraInfo); vp.y = MAX(0, vp.y); //vp.y = 30; //get extent of the image in the xfyf plane FLOAT_MAT_ELEM_TYPE eps = ipmInfo->vpPortion * v;//VP_PORTION*v; ipmInfo->ipmLeft = MAX(0, ipmInfo->ipmLeft); ipmInfo->ipmRight = MIN(u-1, ipmInfo->ipmRight); ipmInfo->ipmTop = MAX(vp.y+eps, ipmInfo->ipmTop); ipmInfo->ipmBottom = MIN(v-1, ipmInfo->ipmBottom); FLOAT_MAT_ELEM_TYPE uvLimitsp[] = {vp.x, ipmInfo->ipmRight, ipmInfo->ipmLeft, vp.x, ipmInfo->ipmTop, ipmInfo->ipmTop, ipmInfo->ipmTop, ipmInfo->ipmBottom}; //{vp.x, u, 0, vp.x, //vp.y+eps, vp.y+eps, vp.y+eps, v}; CvMat uvLimits = cvMat(2, 4, FLOAT_MAT_TYPE, uvLimitsp); /* // **** Debug ***** // print camera info printf("\nCamera info\n"); printf("Yaw: %f\n",cameraInfo->yaw); printf("Pitch: %f\n",cameraInfo->pitch); printf("Focal Length x: %f\n",cameraInfo->focalLength.x); printf("Focal Length y: %f\n",cameraInfo->focalLength.y); printf("Optical Center x: %f\n",cameraInfo->opticalCenter.x); printf("Optical Center y: %f\n",cameraInfo->opticalCenter.y); printf("Camera Heigth: %f\n",cameraInfo->cameraHeight); printf("Vanishing point x: %f\n",vp.x); printf("Vanishing point y: %f\n",vp.y); // **** Debug ***** // print IPM info printf("\nIPM info\n"); printf("VP Portion: %f\n",ipmInfo->vpPortion); printf("IPM Left: %f\n",ipmInfo->ipmLeft); printf("IPM Right: %f\n",ipmInfo->ipmRight); printf("IPM Top: %f\n",ipmInfo->ipmTop); printf("IPM Bottom: %f\n",ipmInfo->ipmBottom); //printf("\nImage Frame: uvLimits\n"); //printf("%f\t%f\t%f\t%f\t\n",uvLimitsp[0],uvLimitsp[1],uvLimitsp[2],uvLimitsp[3]); //printf("%f\t%f\t%f\t%f\t\n",uvLimitsp[4],uvLimitsp[5],uvLimitsp[6],uvLimitsp[7]); SHOW_MAT(&uvLimits, "uvLImits"); CvMat* debugDisp = cvCloneMat(inImage); CvPoint test = CvPoint(int(vp.x),int(ipmInfo->ipmRight)); //cvCircle(debugDisp, CvPoint(int(vp.x),int(ipmInfo->ipmTop)), 3, CV_RGB(255,255,0), 1,8,0); cvCircle(debugDisp, CvPoint(int(ipmInfo->ipmRight),int(ipmInfo->ipmTop)), 3, CV_RGB(255,255,0), 1,8,0); cvCircle(debugDisp, CvPoint(int(ipmInfo->ipmLeft),int(ipmInfo->ipmTop)), 3, CV_RGB(255,255,0), 1,8,0); cvCircle(debugDisp, CvPoint(int(vp.x),int(ipmInfo->ipmBottom)), 3, CV_RGB(255,255,0), 1,8,0); //cvCircle(debugDisp, CvPoint(int(vp.x),int(vp.y)), 3, CV_RGB(255,255,0), 1,8,0); SHOW_IMAGE(debugDisp,"uvLimits",10); char key = cvWaitKey(0); */ //get these points on the ground plane CvMat * xyLimitsp = cvCreateMat(2, 4, FLOAT_MAT_TYPE); CvMat xyLimits = *xyLimitsp; mcvTransformImage2Ground(&uvLimits, &xyLimits,cameraInfo); //SHOW_MAT(xyLimitsp, "xyLImits"); //get extent on the ground plane CvMat row1, row2; cvGetRow(&xyLimits, &row1, 0); cvGetRow(&xyLimits, &row2, 1); double xfMax, xfMin, yfMax, yfMin; cvMinMaxLoc(&row1, (double*)&xfMin, (double*)&xfMax, 0, 0, 0); cvMinMaxLoc(&row2, (double*)&yfMin, (double*)&yfMax, 0, 0, 0); INT outRow = outImage->height; INT outCol = outImage->width; FLOAT_MAT_ELEM_TYPE stepRow = (yfMax-yfMin)/outRow; FLOAT_MAT_ELEM_TYPE stepCol = (xfMax-xfMin)/outCol; //construct the grid to sample CvMat *xyGrid = cvCreateMat(2, outRow*outCol, FLOAT_MAT_TYPE); INT i, j; FLOAT_MAT_ELEM_TYPE x, y; //fill it with x-y values on the ground plane in world frame for (i=0, y=yfMax-.5*stepRow; i<outRow; i++, y-=stepRow) for (j=0, x=xfMin+.5*stepCol; j<outCol; j++, x+=stepCol) { CV_MAT_ELEM(*xyGrid, FLOAT_MAT_ELEM_TYPE, 0, i*outCol+j) = x; CV_MAT_ELEM(*xyGrid, FLOAT_MAT_ELEM_TYPE, 1, i*outCol+j) = y; } //get their pixel values in image frame CvMat *uvGrid = cvCreateMat(2, outRow*outCol, FLOAT_MAT_TYPE); mcvTransformGround2Image(xyGrid, uvGrid, cameraInfo); //now loop and find the nearest pixel value for each position //that's inside the image, otherwise put it zero FLOAT_MAT_ELEM_TYPE ui, vi; //get mean of the input image CvScalar means = cvAvg(inImage); double mean = means.val[0]; //generic loop to work for both float and int matrix types #define MCV_GET_IPM(type) \ for (i=0; i<outRow; i++) \ for (j=0; j<outCol; j++) \ { \ /*get pixel coordiantes*/ \ ui = CV_MAT_ELEM(*uvGrid, FLOAT_MAT_ELEM_TYPE, 0, i*outCol+j); \ vi = CV_MAT_ELEM(*uvGrid, FLOAT_MAT_ELEM_TYPE, 1, i*outCol+j); \ /*check if out-of-bounds*/ \ /*if (ui<0 || ui>u-1 || vi<0 || vi>v-1) \*/ \ if (ui<ipmInfo->ipmLeft || ui>ipmInfo->ipmRight || \ vi<ipmInfo->ipmTop || vi>ipmInfo->ipmBottom) \ { \ CV_MAT_ELEM(*outImage, type, i, j) = (type)mean; \ } \ /*not out of bounds, then get nearest neighbor*/ \ else \ { \ /*Bilinear interpolation*/ \ if (ipmInfo->ipmInterpolation == 0) \ { \ int x1 = int(ui), x2 = int(ui+1); \ int y1 = int(vi), y2 = int(vi+1); \ float x = ui - x1, y = vi - y1; \ float val = CV_MAT_ELEM(*inImage, type, y1, x1) * (1-x) * (1-y) + \ CV_MAT_ELEM(*inImage, type, y1, x2) * x * (1-y) + \ CV_MAT_ELEM(*inImage, type, y2, x1) * (1-x) * y + \ CV_MAT_ELEM(*inImage, type, y2, x2) * x * y; \ CV_MAT_ELEM(*outImage, type, i, j) = (type)val; \ } \ /*nearest-neighbor interpolation*/ \ else \ CV_MAT_ELEM(*outImage, type, i, j) = \ CV_MAT_ELEM(*inImage, type, int(vi+.5), int(ui+.5)); \ } \ if (outPoints && \ (ui<ipmInfo->ipmLeft+10 || ui>ipmInfo->ipmRight-10 || \ vi<ipmInfo->ipmTop || vi>ipmInfo->ipmBottom-2) )\ outPoints->push_back(cvPoint(j, i)); \ } if (CV_MAT_TYPE(inImage->type)==FLOAT_MAT_TYPE) { MCV_GET_IPM(FLOAT_MAT_ELEM_TYPE) } else { MCV_GET_IPM(INT_MAT_ELEM_TYPE) } //return the ipm info ipmInfo->xLimits[0] = CV_MAT_ELEM(*xyGrid, FLOAT_MAT_ELEM_TYPE, 0, 0); ipmInfo->xLimits[1] = CV_MAT_ELEM(*xyGrid, FLOAT_MAT_ELEM_TYPE, 0, (outRow-1)*outCol+outCol-1); ipmInfo->yLimits[1] = CV_MAT_ELEM(*xyGrid, FLOAT_MAT_ELEM_TYPE, 1, 0); ipmInfo->yLimits[0] = CV_MAT_ELEM(*xyGrid, FLOAT_MAT_ELEM_TYPE, 1, (outRow-1)*outCol+outCol-1); ipmInfo->xScale = 1/stepCol; ipmInfo->yScale = 1/stepRow; ipmInfo->width = outCol; ipmInfo->height = outRow; //clean cvReleaseMat(&xyLimitsp); cvReleaseMat(&xyGrid); cvReleaseMat(&uvGrid); } /** * Transforms points from the image frame (uv-coordinates) * into the real world frame on the ground plane (z=-height) * * \param inPoints input points in the image frame * \param outPoints output points in the world frame on the ground * (z=-height) * \param cemaraInfo the input camera parameters * */ void mcvTransformImage2Ground(const CvMat *inPoints, CvMat *outPoints, const CameraInfo *cameraInfo) { //add two rows to the input points CvMat *inPoints4 = cvCreateMat(inPoints->rows+2, inPoints->cols, cvGetElemType(inPoints)); //copy inPoints to first two rows CvMat inPoints2, inPoints3, inPointsr4, inPointsr3; cvGetRows(inPoints4, &inPoints2, 0, 2); cvGetRows(inPoints4, &inPoints3, 0, 3); cvGetRow(inPoints4, &inPointsr3, 2); cvGetRow(inPoints4, &inPointsr4, 3); cvSet(&inPointsr3, cvRealScalar(1)); cvCopy(inPoints, &inPoints2); //create the transformation matrix float c1 = cos(cameraInfo->pitch); float s1 = sin(cameraInfo->pitch); float c2 = cos(cameraInfo->yaw); float s2 = sin(cameraInfo->yaw); float matp[] = { -cameraInfo->cameraHeight*c2/cameraInfo->focalLength.x, cameraInfo->cameraHeight*s1*s2/cameraInfo->focalLength.y, (cameraInfo->cameraHeight*c2*cameraInfo->opticalCenter.x/ cameraInfo->focalLength.x)- (cameraInfo->cameraHeight *s1*s2* cameraInfo->opticalCenter.y/ cameraInfo->focalLength.y) - cameraInfo->cameraHeight *c1*s2, cameraInfo->cameraHeight *s2 /cameraInfo->focalLength.x, cameraInfo->cameraHeight *s1*c2 /cameraInfo->focalLength.y, (-cameraInfo->cameraHeight *s2* cameraInfo->opticalCenter.x /cameraInfo->focalLength.x)-(cameraInfo->cameraHeight *s1*c2* cameraInfo->opticalCenter.y /cameraInfo->focalLength.y) - cameraInfo->cameraHeight *c1*c2, 0, cameraInfo->cameraHeight *c1 /cameraInfo->focalLength.y, (-cameraInfo->cameraHeight *c1* cameraInfo->opticalCenter.y / cameraInfo->focalLength.y) + cameraInfo->cameraHeight *s1, 0, -c1 /cameraInfo->focalLength.y, (c1* cameraInfo->opticalCenter.y /cameraInfo->focalLength.y) - s1, }; CvMat mat = cvMat(4, 3, CV_32FC1, matp); //multiply cvMatMul(&mat, &inPoints3, inPoints4); //divide by last row of inPoints4 for (int i=0; i<inPoints->cols; i++) { float div = CV_MAT_ELEM(inPointsr4, float, 0, i); CV_MAT_ELEM(*inPoints4, float, 0, i) = CV_MAT_ELEM(*inPoints4, float, 0, i) / div ; CV_MAT_ELEM(*inPoints4, float, 1, i) = CV_MAT_ELEM(*inPoints4, float, 1, i) / div; } //put back the result into outPoints cvCopy(&inPoints2, outPoints); //clear cvReleaseMat(&inPoints4); } /** * Transforms points from the ground plane (z=-h) in the world frame * into points on the image in image frame (uv-coordinates) * * \param inPoints 2xN array of input points on the ground in world coordinates * \param outPoints 2xN output points in on the image in image coordinates * \param cameraInfo the camera parameters * */ void mcvTransformGround2Image(const CvMat *inPoints, CvMat *outPoints, const CameraInfo *cameraInfo) { //add two rows to the input points CvMat *inPoints3 = cvCreateMat(inPoints->rows+1, inPoints->cols, cvGetElemType(inPoints)); //copy inPoints to first two rows CvMat inPoints2, inPointsr3; cvGetRows(inPoints3, &inPoints2, 0, 2); cvGetRow(inPoints3, &inPointsr3, 2); cvSet(&inPointsr3, cvRealScalar(-cameraInfo->cameraHeight)); cvCopy(inPoints, &inPoints2); //create the transformation matrix float c1 = cos(cameraInfo->pitch); float s1 = sin(cameraInfo->pitch); float c2 = cos(cameraInfo->yaw); float s2 = sin(cameraInfo->yaw); float matp[] = { cameraInfo->focalLength.x * c2 + c1*s2* cameraInfo->opticalCenter.x, -cameraInfo->focalLength.x * s2 + c1*c2* cameraInfo->opticalCenter.x, - s1 * cameraInfo->opticalCenter.x, s2 * (-cameraInfo->focalLength.y * s1 + c1* cameraInfo->opticalCenter.y), c2 * (-cameraInfo->focalLength.y * s1 + c1* cameraInfo->opticalCenter.y), -cameraInfo->focalLength.y * c1 - s1* cameraInfo->opticalCenter.y, c1*s2, c1*c2, -s1 }; CvMat mat = cvMat(3, 3, CV_32FC1, matp); //multiply cvMatMul(&mat, inPoints3, inPoints3); //divide by last row of inPoints4 for (int i=0; i<inPoints->cols; i++) { float div = CV_MAT_ELEM(inPointsr3, float, 0, i); CV_MAT_ELEM(*inPoints3, float, 0, i) = CV_MAT_ELEM(*inPoints3, float, 0, i) / div ; CV_MAT_ELEM(*inPoints3, float, 1, i) = CV_MAT_ELEM(*inPoints3, float, 1, i) / div; } //put back the result into outPoints cvCopy(&inPoints2, outPoints); //clear cvReleaseMat(&inPoints3); } /** * Computes the vanishing point in the image plane uv. It is * the point of intersection of the image plane with the line * in the XY-plane in the world coordinates that makes an * angle yaw clockwise (form Y-axis) with Y-axis * * \param cameraInfo the input camera parameter * * \return the computed vanishing point in image frame * */ FLOAT_POINT2D mcvGetVanishingPoint(const CameraInfo *cameraInfo) { //get the vp in world coordinates FLOAT_MAT_ELEM_TYPE vpp[] = {sin(cameraInfo->yaw)/cos(cameraInfo->pitch), cos(cameraInfo->yaw)/cos(cameraInfo->pitch), 0}; CvMat vp = cvMat(3, 1, FLOAT_MAT_TYPE, vpp); //transform from world to camera coordinates // //rotation matrix for yaw FLOAT_MAT_ELEM_TYPE tyawp[] = {cos(cameraInfo->yaw), -sin(cameraInfo->yaw), 0, sin(cameraInfo->yaw), cos(cameraInfo->yaw), 0, 0, 0, 1}; CvMat tyaw = cvMat(3, 3, FLOAT_MAT_TYPE, tyawp); //rotation matrix for pitch FLOAT_MAT_ELEM_TYPE tpitchp[] = {1, 0, 0, 0, -sin(cameraInfo->pitch), -cos(cameraInfo->pitch), 0, cos(cameraInfo->pitch), -sin(cameraInfo->pitch)}; CvMat transform = cvMat(3, 3, FLOAT_MAT_TYPE, tpitchp); //combined transform cvMatMul(&transform, &tyaw, &transform); // //transformation from (xc, yc) in camra coordinates // to (u,v) in image frame // //matrix to shift optical center and focal length FLOAT_MAT_ELEM_TYPE t1p[] = { cameraInfo->focalLength.x, 0, cameraInfo->opticalCenter.x, 0, cameraInfo->focalLength.y, cameraInfo->opticalCenter.y, 0, 0, 1}; CvMat t1 = cvMat(3, 3, FLOAT_MAT_TYPE, t1p); //combine transform cvMatMul(&t1, &transform, &transform); //transform cvMatMul(&transform, &vp, &vp); // //clean and return // FLOAT_POINT2D ret; ret.x = cvGetReal1D(&vp, 0); ret.y = cvGetReal1D(&vp, 1); return ret; } /** * Converts a point from IPM pixel coordinates into world coordinates * * \param point in/out point * \param ipmInfo the ipm info from mcvGetIPM * */ void mcvPointImIPM2World(FLOAT_POINT2D *point, const IPMInfo *ipmInfo) { //x-direction point->x /= ipmInfo->xScale; point->x += ipmInfo->xLimits[0]; //y-direction point->y /= ipmInfo->yScale; point->y = ipmInfo->yLimits[1] - point->y; } /** * Converts from IPM pixel coordinates into world coordinates * * \param inMat input matrix 2xN * \param outMat output matrix 2xN * \param ipmInfo the ipm info from mcvGetIPM * */ void mcvTransformImIPM2Ground(const CvMat *inMat, CvMat* outMat, const IPMInfo *ipmInfo) { CvMat *mat; mat = outMat; if(inMat != mat) { cvCopy(inMat, mat); } //work on the x-direction i.e. first row CvMat row; cvGetRow(mat, &row, 0); cvConvertScale(&row, &row, 1./ipmInfo->xScale, ipmInfo->xLimits[0]); //work on y-direction cvGetRow(mat, &row, 1); cvConvertScale(&row, &row, -1./ipmInfo->yScale, ipmInfo->yLimits[1]); } /** * Converts from IPM pixel coordinates into Image coordinates * * \param inMat input matrix 2xN * \param outMat output matrix 2xN * \param ipmInfo the ipm info from mcvGetIPM * \param cameraInfo the camera info * */ void mcvTransformImIPM2Im(const CvMat *inMat, CvMat* outMat, const IPMInfo *ipmInfo, const CameraInfo *cameraInfo) { //convert to world coordinates mcvTransformImIPM2Ground(inMat, outMat, ipmInfo); //convert to image coordinates mcvTransformGround2Image(outMat, outMat, cameraInfo); } /** * Initializes the cameraInfo structure with data read from the conf file * * \param fileName the input camera conf file name * \param cameraInfo the returned camera parametrs struct * */ void mcvInitCameraInfo (char * const fileName, CameraInfo *cameraInfo) { //parsed camera data CameraInfoParserInfo camInfo; //read the data assert(cameraInfoParser_configfile(fileName, &camInfo, 0, 1, 1)==0); //init the strucure cameraInfo->focalLength.x = camInfo.focalLengthX_arg; cameraInfo->focalLength.y = camInfo.focalLengthY_arg; cameraInfo->opticalCenter.x = camInfo.opticalCenterX_arg; cameraInfo->opticalCenter.y = camInfo.opticalCenterY_arg; cameraInfo->cameraHeight = camInfo.cameraHeight_arg; cameraInfo->pitch = camInfo.pitch_arg * CV_PI/180; cameraInfo->yaw = camInfo.yaw_arg * CV_PI/180; cameraInfo->imageWidth = camInfo.imageWidth_arg; cameraInfo->imageHeight = camInfo.imageHeight_arg; } /** * Scales the cameraInfo according to the input image size * * \param cameraInfo the input/return structure * \param size the input image size * */ void mcvScaleCameraInfo (CameraInfo *cameraInfo, CvSize size) { //compute the scale factor double scaleX = size.width/cameraInfo->imageWidth; double scaleY = size.height/cameraInfo->imageHeight; //scale cameraInfo->imageWidth = size.width; cameraInfo->imageHeight = size.height; cameraInfo->focalLength.x *= scaleX; cameraInfo->focalLength.y *= scaleY; cameraInfo->opticalCenter.x *= scaleX; cameraInfo->opticalCenter.y *= scaleY; } /** * Gets the extent of the image on the ground plane given the camera parameters * * \param cameraInfo the input camera info * \param ipmInfo the IPM info containing the extent on ground plane: * xLimits & yLimits only are changed * */ void mcvGetIPMExtent(const CameraInfo *cameraInfo, IPMInfo *ipmInfo ) { //get size of input image FLOAT u, v; v = cameraInfo->imageHeight; u = cameraInfo->imageWidth; //get the vanishing point FLOAT_POINT2D vp; vp = mcvGetVanishingPoint(cameraInfo); vp.y = MAX(0, vp.y); //get extent of the image in the xfyf plane FLOAT_MAT_ELEM_TYPE eps = VP_PORTION*v; FLOAT_MAT_ELEM_TYPE uvLimitsp[] = {vp.x, u, 0, vp.x, vp.y+eps, vp.y+eps, vp.y+eps, v}; CvMat uvLimits = cvMat(2, 4, FLOAT_MAT_TYPE, uvLimitsp); //get these points on the ground plane CvMat * xyLimitsp = cvCreateMat(2, 4, FLOAT_MAT_TYPE); CvMat xyLimits = *xyLimitsp; mcvTransformImage2Ground(&uvLimits, &xyLimits,cameraInfo); //SHOW_MAT(xyLimitsp, "xyLImits"); //get extent on the ground plane CvMat row1, row2; cvGetRow(&xyLimits, &row1, 0); cvGetRow(&xyLimits, &row2, 1); double xfMax, xfMin, yfMax, yfMin; cvMinMaxLoc(&row1, (double*)&xfMin, (double*)&xfMax, 0, 0, 0); cvMinMaxLoc(&row2, (double*)&yfMin, (double*)&yfMax, 0, 0, 0); //return ipmInfo->xLimits[0] = xfMin; ipmInfo->xLimits[1] = xfMax; ipmInfo->yLimits[1] = yfMax; ipmInfo->yLimits[0] = yfMin; } } // namespace LaneDetector
33.084967
120
0.667375
rajnikant1010
318f1ac70f9e7a90c3d39152e6033b511bec486b
3,013
hpp
C++
src/cpu/aarch64/jit_op_imm_check.hpp
Takumi-Honda/oneDNN
7550f71b8fc6ea582b11d2c459e2df1aa605322b
[ "Apache-2.0" ]
1
2020-12-24T02:32:43.000Z
2020-12-24T02:32:43.000Z
src/cpu/aarch64/jit_op_imm_check.hpp
Takumi-Honda/oneDNN
7550f71b8fc6ea582b11d2c459e2df1aa605322b
[ "Apache-2.0" ]
null
null
null
src/cpu/aarch64/jit_op_imm_check.hpp
Takumi-Honda/oneDNN
7550f71b8fc6ea582b11d2c459e2df1aa605322b
[ "Apache-2.0" ]
1
2020-08-19T06:15:19.000Z
2020-08-19T06:15:19.000Z
#ifndef JIT_OP_IMM_CHECK_HPP #define JIT_OP_IMM_CHECK_HPP #define ADDMAX 4095 #define LDRMAX 255 #define LDRMIN (-256) #define STRMAX 255 #define STRMIN (-256) #define LD1RWMAX 252 #define LD1WMIN (-8) #define LD1WMAX 7 #define PRFMMAX 32760 #define PRFMMIN 0 #define PRFWMAX 31 #define PRFWMIN (-32) namespace dnnl { namespace impl { namespace cpu { namespace aarch64 { // Load a vector register from a memory address generated by a 64-bit scalar base, // plus an immediate offset in the range -256 to 255 which is multiplied // by the current vector register size in bytes. This instruction is unpredicated. template <typename T> bool ldr_imm_check(T ofs) { int vlen = cpu_isa_traits<sve_512>::vlen; int vlen_shift = cpu_isa_traits<sve_512>::vlen_shift; int shifted_ofs = ofs >> vlen_shift; return ((shifted_ofs) <= LDRMAX) && (shifted_ofs >= LDRMIN) && ((ofs % vlen) == 0); } // Store a vector register to a memory address generated by a 64-bit scalar base, // plus an immediate offset in the range -256 to 255 which is multiplied // by the current vector register size in bytes. This instruction is unpredicated. template <typename T> bool str_imm_check(T ofs) { int vlen = cpu_isa_traits<sve_512>::vlen; int vlen_shift = cpu_isa_traits<sve_512>::vlen_shift; int shifted_ofs = ofs >> vlen_shift; return ((shifted_ofs) <= STRMAX) && (shifted_ofs >= STRMIN) && ((ofs % vlen) == 0); } // Load a single unsigned word from a memory address generated by a 64-bit scalar // base address plus an immediate offset which is a multiple of 4 in the range 0 to 252. template <typename T> bool ld1rw_imm_check(T ofs) { return ((ofs & 0x3) == 0) && (ofs <= LD1RWMAX) && (ofs >= 0); } template <typename T> bool ld1w_imm_check(T ofs) { int vlen = cpu_isa_traits<sve_512>::vlen; int vlen_shift = cpu_isa_traits<sve_512>::vlen_shift; int shifted_ofs = ofs >> vlen_shift; return ((shifted_ofs) <= LD1WMAX) && (shifted_ofs >= LD1WMIN) && ((ofs % vlen) == 0); } template <typename T> bool st1w_imm_check(T ofs) { int vlen = cpu_isa_traits<sve_512>::vlen; int vlen_shift = cpu_isa_traits<sve_512>::vlen_shift; int shifted_ofs = ofs >> vlen_shift; return ((shifted_ofs) <= LD1WMAX) && (shifted_ofs >= LD1WMIN) && ((ofs % vlen) == 0); } // Is the optional positive immediate byte offset, // a multiple of 8 in the range 0 to 32760, defaulting to 0 // and encoded in the "imm12" field as <pimm>/8. template <typename T> bool prfm_imm_check(T ofs) { return (ofs <= PRFMMAX) && (ofs >= PRFMMIN) && ((ofs & 0x7) == 0); } template <typename T> bool prfw_imm_check(T ofs) { int vlen = cpu_isa_traits<sve_512>::vlen; int vlen_shift = cpu_isa_traits<sve_512>::vlen_shift; int shifted_ofs = ofs >> vlen_shift; return (shifted_ofs <= PRFWMAX) && (shifted_ofs >= PRFWMIN) && ((ofs % vlen) == 0); } } // namespace aarch64 } // namespace cpu } // namespace impl } // namespace dnnl #endif
32.75
88
0.683372
Takumi-Honda
318ff375d0b7119fc9bc578c0109671aafb739d0
911
hpp
C++
include/util/font.hpp
Sokolmish/coursework_1
94422cc11ab46da4f09d7f0dae67c7a111935582
[ "MIT" ]
2
2021-03-30T20:20:01.000Z
2022-01-08T21:46:39.000Z
include/util/font.hpp
Sokolmish/coursework_1
94422cc11ab46da4f09d7f0dae67c7a111935582
[ "MIT" ]
null
null
null
include/util/font.hpp
Sokolmish/coursework_1
94422cc11ab46da4f09d7f0dae67c7a111935582
[ "MIT" ]
null
null
null
#ifndef __FONT_H__ #define __FONT_H__ #include "glew.hpp" #include <string> #include <map> #include <glm/vec3.hpp> #include "shader.hpp" class Font { private: struct Character { int width, height; int bearingX, bearingY; GLuint advance; int atlasX, atlasY; }; struct RawChar { Font::Character ch; uint8_t *buff; }; std::map<GLchar, Font::Character> characters; GLuint texture; GLuint VAO, VBO; uint32_t atlasWidth; uint32_t atlasHeight; uint32_t tileWidth; uint32_t tileHeight; uint8_t *atlas; public: Font(const std::string &path, uint32_t width, uint32_t height); ~Font(); void RenderText(const Shader &s, const std::string &text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color) const; void ShowAtlas(int x, int y, int width, int height) const; }; #endif
21.690476
122
0.628979
Sokolmish
3192eceaf08713fcc7b6289ccf24958444f58147
101
cpp
C++
NFComm/NFEventProcessPlugin/dllmain.cpp
lindianyin/NoahGameFrame
2ba0949b142c5b0ffb411423c9a7b321a1f01ee7
[ "Apache-2.0" ]
null
null
null
NFComm/NFEventProcessPlugin/dllmain.cpp
lindianyin/NoahGameFrame
2ba0949b142c5b0ffb411423c9a7b321a1f01ee7
[ "Apache-2.0" ]
null
null
null
NFComm/NFEventProcessPlugin/dllmain.cpp
lindianyin/NoahGameFrame
2ba0949b142c5b0ffb411423c9a7b321a1f01ee7
[ "Apache-2.0" ]
1
2018-07-15T07:30:03.000Z
2018-07-15T07:30:03.000Z
#include "NFComm/NFPluginModule/NFPlatform.h" #if NF_PLATFORM == NF_PLATFORM_WIN #endif
11.222222
46
0.70297
lindianyin
31971dd13ffab9e73faf7dc620d2cee92627fab8
2,683
cpp
C++
Game/interfaces/objectmanager.cpp
Moppa5/pirkanmaan-valloitus
725dd1a9ef29dcd314faa179124541618dc8e5bf
[ "MIT" ]
3
2020-10-30T13:26:34.000Z
2020-12-08T13:21:34.000Z
Game/interfaces/objectmanager.cpp
Moppa5/pirkanmaan-valloitus
725dd1a9ef29dcd314faa179124541618dc8e5bf
[ "MIT" ]
15
2020-12-10T18:13:20.000Z
2021-06-08T10:37:51.000Z
Game/interfaces/objectmanager.cpp
Moppa5/pirkanmaan-valloitus
725dd1a9ef29dcd314faa179124541618dc8e5bf
[ "MIT" ]
null
null
null
#include "objectmanager.hh" #include "iostream" namespace Game { ObjectManager::ObjectManager() { } ObjectManager::~ObjectManager() { } std::vector<std::shared_ptr<Course::TileBase> > ObjectManager::getTiles( const std::vector<Course::Coordinate> &coordinates) { std::vector<std::shared_ptr<Course::TileBase>> tiles; for(std::shared_ptr<Course::TileBase> tile : tiles_){ for(auto coordinate : coordinates){ if(tile->getCoordinate() == coordinate){ tiles.push_back(tile); } } } return tiles; } std::vector<std::shared_ptr<Course::TileBase> > ObjectManager::getTiles() { return tiles_; } std::shared_ptr<Course::TileBase> ObjectManager::getTile( const Course::ObjectId &id) { for(std::shared_ptr<Course::TileBase> tile : tiles_){ if(tile->ID == id){ return tile; } } return nullptr; } std::shared_ptr<Course::TileBase> ObjectManager::getTile( const Course::Coordinate &coordinate) { for(std::shared_ptr<Course::TileBase> tile : tiles_){ if(tile->getCoordinate() == coordinate){ return tile; } } return nullptr; } void ObjectManager::addTiles(const std::vector <std::shared_ptr<Course::TileBase> > &tiles) { // Loop over tiles for(auto tile : tiles){ tiles_.push_back(tile); } } void ObjectManager::addBuilding(const std::shared_ptr <Course::BuildingBase> &building) { buildings_.push_back(building); } void ObjectManager::removeBuilding(const std::shared_ptr <Course::BuildingBase> &building) { std::shared_ptr<Course::TileBase> tile = getTile(building->getCoordinate()); tile->removeBuilding(building); for(unsigned int i=0; i<buildings_.size(); i++){ if(buildings_.at(i) == building) { buildings_.erase(buildings_.begin() + i); return; } } throw Course::KeyError("Building not found"); } void ObjectManager::addWorker(const std::shared_ptr <Course::WorkerBase> &worker) { workers_.push_back(worker); } void ObjectManager::removeWorker(const std::shared_ptr <Course::WorkerBase> &worker) { std::shared_ptr<Course::TileBase> tile = getTile(worker->getCoordinate()); for(unsigned int i=0; i<workers_.size(); i++){ if(workers_.at(i) == worker) { tile->removeWorker(worker); workers_.erase(workers_.begin() + i); return; } } throw Course::KeyError("Worker not found"); } }
23.955357
80
0.597838
Moppa5
31981524703aae7356068ccd7dac566cca992780
3,270
hpp
C++
include/tudocomp/io/InputRestrictions.hpp
JZentgraf/tudocomp
3a4522e3089716e4483b935e74aaae56cc547589
[ "ECL-2.0", "Apache-2.0" ]
17
2017-03-04T13:04:49.000Z
2021-12-03T06:58:20.000Z
include/tudocomp/io/InputRestrictions.hpp
JZentgraf/tudocomp
3a4522e3089716e4483b935e74aaae56cc547589
[ "ECL-2.0", "Apache-2.0" ]
27
2016-01-22T18:31:37.000Z
2021-11-27T10:50:40.000Z
include/tudocomp/io/InputRestrictions.hpp
JZentgraf/tudocomp
3a4522e3089716e4483b935e74aaae56cc547589
[ "ECL-2.0", "Apache-2.0" ]
16
2017-03-14T12:46:51.000Z
2021-06-25T18:19:50.000Z
#pragma once #include <tudocomp/util.hpp> namespace tdc {namespace io { /// Describes a set of restrictions placed on input data. /// /// Restrictions include illigal bytes in the input (called escape bytes here), /// and wether the input needs to be null terminated. class InputRestrictions { std::vector<uint8_t> m_escape_bytes; bool m_null_terminate; inline void sort_and_dedup() { std::sort(m_escape_bytes.begin(), m_escape_bytes.end()); m_escape_bytes.erase(std::unique(m_escape_bytes.begin(), m_escape_bytes.end()), m_escape_bytes.end()); } friend inline InputRestrictions operator|(const InputRestrictions& a, const InputRestrictions& b); public: inline InputRestrictions(const std::vector<uint8_t>& escape_bytes = {}, bool null_terminate = false): m_escape_bytes(escape_bytes), m_null_terminate(null_terminate) { sort_and_dedup(); } inline const std::vector<uint8_t>& escape_bytes() const { return m_escape_bytes; } inline bool null_terminate() const { return m_null_terminate; } inline bool has_no_escape_restrictions() const { return m_escape_bytes.empty(); } inline bool has_no_restrictions() const { return has_no_escape_restrictions() && (m_null_terminate == false); } inline bool has_escape_restrictions() const { return !has_no_escape_restrictions(); } inline bool has_restrictions() const { return !has_no_restrictions(); } }; inline std::ostream& operator<<(std::ostream& o, const InputRestrictions& v) { o << "{ escape_bytes: " << vec_to_debug_string(v.escape_bytes()) << ", null_termination: " << (v.null_terminate() ? "true" : "false") << " }"; return o; } /// Merges two InpuTrestrictions to a combined set of restrictions. inline InputRestrictions operator|(const InputRestrictions& a, const InputRestrictions& b) { // Yes, kind of overkill here... std::vector<uint8_t> merged; merged.insert(merged.end(), a.escape_bytes().begin(), a.escape_bytes().end()); merged.insert(merged.end(), b.escape_bytes().begin(), b.escape_bytes().end()); auto r = InputRestrictions { merged, a.null_terminate() || b.null_terminate(), }; r.sort_and_dedup(); return r; } /// Merges two InpuTrestrictions to a combined set of restrictions. inline InputRestrictions& operator|=(InputRestrictions& a, const InputRestrictions& b) { a = a | b; return a; } inline bool operator==(const InputRestrictions& lhs, const InputRestrictions& rhs) { return lhs.escape_bytes() == rhs.escape_bytes() && lhs.null_terminate() == rhs.null_terminate(); } inline bool operator!=(const InputRestrictions& lhs, const InputRestrictions& rhs) { return !(lhs == rhs); } }}
33.030303
114
0.587462
JZentgraf
3198d5e8d73fa515aa353645b272ea1ba168f86d
4,026
hpp
C++
example/p0059/ring_span.hpp
breese/trial.circular
8b8269c1ba90f1cb3c7a8970a27ccb149069ed24
[ "BSL-1.0" ]
5
2020-06-06T20:33:43.000Z
2020-11-03T01:21:20.000Z
example/p0059/ring_span.hpp
breese/trial.circular
8b8269c1ba90f1cb3c7a8970a27ccb149069ed24
[ "BSL-1.0" ]
null
null
null
example/p0059/ring_span.hpp
breese/trial.circular
8b8269c1ba90f1cb3c7a8970a27ccb149069ed24
[ "BSL-1.0" ]
null
null
null
#ifndef TRIAL_CIRCULAR_EXAMPLE_P0056_RING_SPAN_HPP #define TRIAL_CIRCULAR_EXAMPLE_P0056_RING_SPAN_HPP /////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2019 Bjorn Reese <[email protected]> // // 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) // /////////////////////////////////////////////////////////////////////////////// #include <trial/circular/span.hpp> namespace trial { namespace circular { namespace example { // Implementation of P0059R4 std::experimental::ring_span // See http://wg21.link/P0059 template <typename T> struct null_popper { null_popper() noexcept = default; void operator()(T&) const noexcept { } }; template <typename T> struct default_popper { default_popper() noexcept = default; T operator()(T& value) const noexcept(std::is_nothrow_move_constructible<T>::value) { return std::move(value); } }; template <typename T> struct copy_popper { explicit copy_popper(T&& value) noexcept(std::is_nothrow_move_constructible<T>::value) : copy(std::move(value)) { } T operator()(T& value) const noexcept(std::is_nothrow_move_constructible<T>::value && std::is_nothrow_copy_assignable<T>::value) { T old = std::move(value); value = copy; return old; } T copy; }; template <typename T, typename Popper = default_popper<T>> class ring_span : private circular::span<T> { using super = typename circular::span<T>; public: using type = ring_span<T, Popper>; using value_type = typename super::value_type; using size_type = typename super::size_type; using pointer = typename super::pointer; using reference = typename super::reference; using const_reference = typename super::const_reference; using iterator = typename super::iterator; using const_iterator = typename super::const_iterator; template <typename ContiguousIterator> ring_span(ContiguousIterator begin, ContiguousIterator end, Popper popper = Popper()) noexcept(std::is_nothrow_move_constructible<Popper>::value) : super(begin, end), popper(std::move(popper)) { } template <typename ContiguousIterator> ring_span(ContiguousIterator begin, ContiguousIterator end, ContiguousIterator first, size_type length, Popper popper = Popper()) noexcept(std::is_nothrow_move_constructible<Popper>::value) : super(begin, end, first, length), popper(std::move(popper)) { } ring_span(ring_span&&) = default; ring_span& operator=(ring_span&&) = default; using super::empty; using super::full; using super::size; using super::capacity; using super::front; using super::back; using super::begin; using super::end; using super::cbegin; using super::cend; using super::push_back; template <typename... Args> void emplace_back(Args&&... args) noexcept(std::is_nothrow_constructible<value_type, Args...>::value && std::is_nothrow_move_assignable<value_type>::value) { super::push_back(value_type(std::forward<Args>(args)...)); } // C++14 auto return type auto pop_front() noexcept(noexcept(std::declval<Popper>().operator()(std::declval<value_type&>()))) { auto& old_front = super::front(); super::remove_front(); // Element still lingers in storage return popper(old_front); } void swap(type& other) noexcept(detail::is_nothrow_swappable<Popper>::value) { using std::swap; swap(static_cast<super&>(*this), static_cast<super&>(other)); swap(popper, other.popper); } private: Popper popper; }; } // namespace example } // namespace circular } // namespace trial #endif // TRIAL_CIRCULAR_EXAMPLE_P0056_RING_SPAN_HPP
27.387755
159
0.640586
breese
3199d2e8bfa8ea1a9ef38b0d80c947b8c92e8272
656
hpp
C++
pomdog/input/win32/keyboard_win32.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
163
2015-03-16T08:42:32.000Z
2022-01-11T21:40:22.000Z
pomdog/input/win32/keyboard_win32.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
17
2015-04-12T20:57:50.000Z
2020-10-10T10:51:45.000Z
pomdog/input/win32/keyboard_win32.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
21
2015-04-12T20:45:11.000Z
2022-01-14T20:50:16.000Z
// Copyright mogemimi. Distributed under the MIT license. #pragma once #include "pomdog/application/system_events.hpp" #include "pomdog/input/keyboard.hpp" #include "pomdog/input/keyboard_state.hpp" #include "pomdog/platform/win32/prerequisites_win32.hpp" namespace pomdog::detail::win32 { class KeyboardWin32 final : public Keyboard { public: KeyboardState GetState() const override; void HandleMessage(const SystemEvent& event); private: KeyboardState keyboardState; }; void TranslateKeyboardEvent(const RAWKEYBOARD& keyboard, const std::shared_ptr<EventQueue<SystemEvent>>& eventQueue) noexcept; } // namespace pomdog::detail::win32
26.24
126
0.785061
mogemimi
31a01022b3a4ce12140b792b71e99a0ecef3d0f6
3,099
cpp
C++
ncnn/segment.cpp
russelldj/BiSeNet
d29fa741ad5275fab9e1bfc237b02811acf73b98
[ "MIT" ]
966
2018-12-13T12:11:18.000Z
2022-03-31T14:13:55.000Z
ncnn/segment.cpp
russelldj/BiSeNet
d29fa741ad5275fab9e1bfc237b02811acf73b98
[ "MIT" ]
214
2019-01-25T10:06:24.000Z
2022-03-22T01:55:28.000Z
ncnn/segment.cpp
russelldj/BiSeNet
d29fa741ad5275fab9e1bfc237b02811acf73b98
[ "MIT" ]
247
2019-03-04T11:39:06.000Z
2022-03-30T05:45:56.000Z
#include "net.h" #include "mat.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <random> #include <algorithm> #include <stdio.h> #include <vector> using std::string; using std::vector; using cv::Mat; vector<vector<uint8_t>> get_color_map(); void inference(); int main(int argc, char** argv) { inference(); return 0; } void inference() { bool use_fp16 = false; // load model ncnn::Net mod; #if NCNN_VULKAN int gpu_count = ncnn::get_gpu_count(); if (gpu_count <= 0) { fprintf(stderr, "we do not have gpu device\n"); return; } mod.opt.use_vulkan_compute = 1; mod.set_vulkan_device(1); #endif mod.load_param("../models/model_v2_sim.param"); mod.load_model("../models/model_v2_sim.bin"); mod.opt.use_fp16_packed = use_fp16; mod.opt.use_fp16_storage = use_fp16; mod.opt.use_fp16_arithmetic = use_fp16; // load image, and copy to ncnn mat int oH{1024}, oW{2048}, n_classes{19}; float mean[3] = {0.3257f, 0.3690f, 0.3223f}; float var[3] = {0.2112f, 0.2148f, 0.2115f}; cv::Mat im = cv::imread("../../example.png"); if (im.empty()) { fprintf(stderr, "cv::imread failed\n"); return; } ncnn::Mat inp = ncnn::Mat::from_pixels_resize( im.data, ncnn::Mat::PIXEL_BGR, im.cols, im.rows, oW, oH); for (float &el : mean) el *= 255.; for (float &el : var) el = 1. / (255. * el); inp.substract_mean_normalize(mean, var); // set input, run, get output ncnn::Extractor ex = mod.create_extractor(); // ex.set_num_threads(1); #if NCNN_VULKAN ex.set_vulkan_compute(true); #endif ex.input("input_image", inp); ncnn::Mat out; ex.extract("preds", out); // output is nchw, as onnx, where here n=1 // generate colorful output, and dump vector<vector<uint8_t>> color_map = get_color_map(); Mat pred(cv::Size(oW, oH), CV_8UC3); for (int i{0}; i < oH; ++i) { uint8_t *ptr = pred.ptr<uint8_t>(i); for (int j{0}; j < oW; ++j) { // compute argmax int idx, offset, argmax{0}; float max; idx = i * oW + j; offset = oH * oW; max = out[idx]; for (int k{1}; k < n_classes; ++k) { idx += offset; if (max < out[idx]) { max = out[idx]; argmax = k; } } // color the result ptr[0] = color_map[argmax][0]; ptr[1] = color_map[argmax][1]; ptr[2] = color_map[argmax][2]; ptr += 3; } } cv::imwrite("out.png", pred); } vector<vector<uint8_t>> get_color_map() { vector<vector<uint8_t>> color_map(256, vector<uint8_t>(3)); std::minstd_rand rand_eng(123); std::uniform_int_distribution<uint8_t> u(0, 255); for (int i{0}; i < 256; ++i) { for (int j{0}; j < 3; ++j) { color_map[i][j] = u(rand_eng); } } return color_map; }
26.262712
72
0.557922
russelldj
31a5987c73a51102dece38f015f90ac9238528f9
1,773
cpp
C++
bench/seidel_2d.cpp
dongchen-coder/locMarkov
584f06a3ca257d156be44a9f604df2850a42b436
[ "MIT" ]
null
null
null
bench/seidel_2d.cpp
dongchen-coder/locMarkov
584f06a3ca257d156be44a9f604df2850a42b436
[ "MIT" ]
null
null
null
bench/seidel_2d.cpp
dongchen-coder/locMarkov
584f06a3ca257d156be44a9f604df2850a42b436
[ "MIT" ]
null
null
null
#include "./utility/mc_kth.h" int TSTEPS; int N; #define A_OFFSET 0 void seidel_2d_trace(double* A) { int t, i, j; vector<int> idx; for (t = 0; t <= TSTEPS - 1; t++) for (i = 1; i<= N - 2; i++) for (j = 1; j <= N - 2; j++) { idx.clear(); idx.push_back(t); idx.push_back(i); idx.push_back(j); A[i * N + j] = (A[(i-1) * N + j-1] + A[(i-1) * N + j] + A[(i-1) * N + j+1] + A[i * N + j-1] + A[i * N + j] + A[i * N + j+1] + A[(i+1) * N + j-1] + A[(i+1) * N + j] + A[(i+1) * N + j+1]) / 9.0; rtTmpAccess(A_OFFSET + (i-1) * N + j-1, 0, 0, idx); rtTmpAccess(A_OFFSET + (i-1) * N + j, 1, 0, idx); rtTmpAccess(A_OFFSET + (i-1) * N + j+1, 2, 0, idx); rtTmpAccess(A_OFFSET + i * N + j-1, 3, 0, idx); rtTmpAccess(A_OFFSET + i * N + j, 4, 0, idx); rtTmpAccess(A_OFFSET + i * N + j+1, 5, 0, idx); rtTmpAccess(A_OFFSET + (i+1) * N + j-1, 6, 0, idx); rtTmpAccess(A_OFFSET + (i+1) * N + j, 7, 0, idx); rtTmpAccess(A_OFFSET + (i+1) * N + j+1, 8, 0, idx); rtTmpAccess(A_OFFSET + i * N + j, 9, 0, idx); } } int main(int argc, char* argv[]) { if (argc != 3) { cout << "This benchmark needs 2 loop bounds" << endl; return 0; } for (int i = 1; i < argc; i++) { if (!isdigit(argv[i][0])) { cout << "arguments must be integer" << endl; return 0; } } N = stoi(argv[1]); TSTEPS = stoi(argv[2]); double* A = (double *)malloc(N * N * sizeof(double)); seidel_2d_trace(A); string name(argv[0]); size_t found = name.find_last_of("/\\") + 1; string conf = name.substr(found, name.size()-found) + "_" + to_string(N) + "_" + to_string(TSTEPS); dumpRIHistogram(conf); predictionWithBmc(conf); return 0; }
29.55
196
0.494078
dongchen-coder
31a798947c457f546920712973a23c2661e6c0de
25,601
cpp
C++
src/drivers/ddragon.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-01-25T20:16:33.000Z
2021-01-25T20:16:33.000Z
src/drivers/ddragon.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-05-24T20:28:35.000Z
2021-05-25T14:44:54.000Z
src/drivers/ddragon.cpp
PSP-Archive/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
null
null
null
/* Double Dragon, Double Dragon (bootleg) & Double Dragon II By Carlos A. Lozano & Rob Rosenbrock Help to do the original drivers from Chris Moore Sprite CPU support and additional code by Phil Stroffolino Sprite CPU emulation, vblank support, and partial sound code by Ernesto Corvi. Dipswitch to dd2 by Marco Cassili. High Score support by Roberto Fresca. TODO: - Find the original MCU code so original Double Dragon ROMs can be supported NOTES: The OKI M5205 chip 0 sampling rate is 8000hz (8khz). The OKI M5205 chip 1 sampling rate is 4000hz (4khz). Until the ADPCM interface is updated to be able to use multiple sampling rates, all samples currently play at 8khz. */ #include "driver.h" #include "vidhrdw/generic.h" #include "m6809/m6809.h" #include "z80/z80.h" /* from vidhrdw */ extern unsigned char *dd_videoram; extern int dd_scrollx_hi, dd_scrolly_hi; extern unsigned char *dd_scrollx_lo; extern unsigned char *dd_scrolly_lo; int dd_vh_start(void); void dd_vh_stop(void); void dd_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); void dd_background_w( int offset, int val ); extern unsigned char *dd_spriteram; extern int dd2_video; /* end of extern code & data */ /* private globals */ static int dd_sub_cpu_busy; static int sprite_irq, sound_irq, ym_irq; /* end of private globals */ static void dd_init_machine( void ) { sprite_irq = M6809_INT_NMI; sound_irq = M6809_INT_IRQ; ym_irq = M6809_INT_FIRQ; dd2_video = 0; dd_sub_cpu_busy = 0x10; } static void dd2_init_machine( void ) { sprite_irq = Z80_NMI_INT; sound_irq = Z80_NMI_INT; ym_irq = -1000; dd2_video = 1; dd_sub_cpu_busy = 0x10; } static void dd_bankswitch_w( int offset, int data ) { unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region]; dd_scrolly_hi = ( ( data & 0x02 ) << 7 ); dd_scrollx_hi = ( ( data & 0x01 ) << 8 ); if ( ( data & 0x10 ) == 0x10 ) { dd_sub_cpu_busy = 0x00; } else if ( dd_sub_cpu_busy == 0x00 ) cpu_cause_interrupt( 1, sprite_irq ); cpu_setbank( 1,&RAM[ 0x10000 + ( 0x4000 * ( ( data >> 5 ) & 7 ) ) ] ); } static void dd_forcedIRQ_w( int offset, int data ) { cpu_cause_interrupt( 0, M6809_INT_IRQ ); } static int port4_r( int offset ) { int port = readinputport( 4 ); return port | dd_sub_cpu_busy; } static int dd_spriteram_r( int offset ){ return dd_spriteram[offset]; } static void dd_spriteram_w( int offset, int data ) { if ( cpu_getactivecpu() == 1 && offset == 0 ) dd_sub_cpu_busy = 0x10; dd_spriteram[offset] = data; } static void cpu_sound_command_w( int offset, int data ) { soundlatch_w( offset, data ); cpu_cause_interrupt( 2, sound_irq ); } static void dd_adpcm_w(int offset,int data) { static int start[2],end[2]; int chip = offset & 1; offset >>= 1; switch (offset) { case 3: break; case 2: start[chip] = data & 0x7f; break; case 1: end[chip] = data & 0x7f; break; case 0: ADPCM_play( chip, 0x10000*chip + start[chip]*0x200, (end[chip]-start[chip])*0x400); break; } } static int dd_adpcm_status_r( int offset ) { return ( ADPCM_playing( 0 ) + ( ADPCM_playing( 1 ) << 1 ) ); } static struct MemoryReadAddress readmem[] = { { 0x0000, 0x1fff, MRA_RAM }, { 0x2000, 0x2fff, dd_spriteram_r, &dd_spriteram }, { 0x3000, 0x37ff, MRA_RAM }, { 0x3800, 0x3800, input_port_0_r }, { 0x3801, 0x3801, input_port_1_r }, { 0x3802, 0x3802, port4_r }, { 0x3803, 0x3803, input_port_2_r }, { 0x3804, 0x3804, input_port_3_r }, { 0x3805, 0x3fff, MRA_RAM }, { 0x4000, 0x7fff, MRA_BANK1 }, { 0x8000, 0xffff, MRA_ROM }, { -1 } /* end of table */ }; static struct MemoryWriteAddress writemem[] = { { 0x0000, 0x0fff, MWA_RAM }, { 0x1000, 0x11ff, paletteram_xxxxBBBBGGGGRRRR_split1_w, &paletteram }, { 0x1200, 0x13ff, paletteram_xxxxBBBBGGGGRRRR_split2_w, &paletteram_2 }, { 0x1400, 0x17ff, MWA_RAM }, { 0x1800, 0x1fff, MWA_RAM, &videoram }, { 0x2000, 0x2fff, dd_spriteram_w }, { 0x3000, 0x37ff, dd_background_w, &dd_videoram }, { 0x3800, 0x3807, MWA_RAM }, { 0x3808, 0x3808, dd_bankswitch_w }, { 0x3809, 0x3809, MWA_RAM, &dd_scrollx_lo }, { 0x380a, 0x380a, MWA_RAM, &dd_scrolly_lo }, { 0x380b, 0x380b, MWA_RAM }, { 0x380c, 0x380d, MWA_RAM }, { 0x380e, 0x380e, cpu_sound_command_w }, { 0x380f, 0x380f, dd_forcedIRQ_w }, { 0x3810, 0x3fff, MWA_RAM }, { 0x4000, 0xffff, MWA_ROM }, { -1 } /* end of table */ }; static struct MemoryWriteAddress dd2_writemem[] = { { 0x0000, 0x17ff, MWA_RAM }, { 0x1800, 0x1fff, MWA_RAM, &videoram }, { 0x2000, 0x2fff, dd_spriteram_w }, { 0x3000, 0x37ff, dd_background_w, &dd_videoram }, { 0x3800, 0x3807, MWA_RAM }, { 0x3808, 0x3808, dd_bankswitch_w }, { 0x3809, 0x3809, MWA_RAM, &dd_scrollx_lo }, { 0x380a, 0x380a, MWA_RAM, &dd_scrolly_lo }, { 0x380b, 0x380b, MWA_RAM }, { 0x380c, 0x380d, MWA_RAM }, { 0x380e, 0x380e, cpu_sound_command_w }, { 0x380f, 0x380f, dd_forcedIRQ_w }, { 0x3810, 0x3bff, MWA_RAM }, { 0x3c00, 0x3dff, paletteram_xxxxBBBBGGGGRRRR_split1_w, &paletteram }, { 0x3e00, 0x3fff, paletteram_xxxxBBBBGGGGRRRR_split2_w, &paletteram_2 }, { 0x4000, 0xffff, MWA_ROM }, { -1 } /* end of table */ }; static struct MemoryReadAddress sub_readmem[] = { { 0x0000, 0x0fff, MRA_RAM }, { 0x8000, 0x8fff, dd_spriteram_r }, { 0xc000, 0xffff, MRA_ROM }, { -1 } /* end of table */ }; static struct MemoryWriteAddress sub_writemem[] = { { 0x0000, 0x0fff, MWA_RAM }, { 0x8000, 0x8fff, dd_spriteram_w }, { 0xc000, 0xffff, MWA_ROM }, { -1 } /* end of table */ }; static struct MemoryReadAddress sound_readmem[] = { { 0x0000, 0x0fff, MRA_RAM }, { 0x1000, 0x1000, soundlatch_r }, { 0x1800, 0x1800, dd_adpcm_status_r }, { 0x2800, 0x2801, YM2151_status_port_0_r }, { 0x8000, 0xffff, MRA_ROM }, { -1 } /* end of table */ }; static struct MemoryWriteAddress sound_writemem[] = { { 0x0000, 0x0fff, MWA_RAM }, { 0x2800, 0x2800, YM2151_register_port_0_w }, { 0x2801, 0x2801, YM2151_data_port_0_w }, { 0x3800, 0x3807, dd_adpcm_w }, { 0x8000, 0xffff, MWA_ROM }, { -1 } /* end of table */ }; static struct MemoryReadAddress dd2_sub_readmem[] = { { 0x0000, 0xbfff, MRA_ROM }, { 0xc000, 0xcfff, dd_spriteram_r }, { 0xd000, 0xffff, MRA_RAM }, { -1 } /* end of table */ }; static struct MemoryWriteAddress dd2_sub_writemem[] = { { 0x0000, 0xbfff, MWA_ROM }, { 0xc000, 0xcfff, dd_spriteram_w }, { 0xd000, 0xffff, MWA_RAM }, { -1 } /* end of table */ }; static struct MemoryReadAddress dd2_sound_readmem[] = { { 0x0000, 0x7fff, MRA_ROM }, { 0x8000, 0x87ff, MRA_RAM }, { 0x8801, 0x8801, YM2151_status_port_0_r }, { 0x9800, 0x9800, OKIM6295_status_0_r }, { 0xA000, 0xA000, soundlatch_r }, { -1 } /* end of table */ }; static struct MemoryWriteAddress dd2_sound_writemem[] = { { 0x0000, 0x7fff, MWA_ROM }, { 0x8000, 0x87ff, MWA_RAM }, { 0x8800, 0x8800, YM2151_register_port_0_w }, { 0x8801, 0x8801, YM2151_data_port_0_w }, { 0x9800, 0x9800, OKIM6295_data_0_w }, { -1 } /* end of table */ }; /* bit 0x10 is sprite CPU busy signal */ #define COMMON_PORT4 PORT_START \ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN3 ) \ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON3 ) \ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON3 | IPF_PLAYER2 ) \ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_VBLANK ) \ PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN ) \ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) \ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) \ PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN ) #define COMMON_INPUT_PORTS PORT_START \ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY ) \ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY ) \ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) \ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) \ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) \ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) \ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START1 ) \ PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START2 ) \ PORT_START \ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_PLAYER2 ) \ PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_PLAYER2 ) \ PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 | IPF_PLAYER2 ) \ PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 ) \ PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 ) \ PORT_START \ PORT_DIPNAME( 0x07, 0x07, "Coin A", IP_KEY_NONE ) \ PORT_DIPSETTING( 0x00, "4 Coins/1 Credit" ) \ PORT_DIPSETTING( 0x01, "3 Coins/1 Credit" ) \ PORT_DIPSETTING( 0x02, "2 Coins/1 Credit" ) \ PORT_DIPSETTING( 0x07, "1 Coin/1 Credit" ) \ PORT_DIPSETTING( 0x06, "1 Coin/2 Credits" ) \ PORT_DIPSETTING( 0x05, "1 Coin/3 Credits" ) \ PORT_DIPSETTING( 0x04, "1 Coin/4 Credits" ) \ PORT_DIPSETTING( 0x03, "1 Coin/5 Credits" ) \ PORT_DIPNAME( 0x38, 0x38, "Coin B", IP_KEY_NONE ) \ PORT_DIPSETTING( 0x00, "4 Coins/1 Credit" ) \ PORT_DIPSETTING( 0x08, "3 Coins/1 Credit" ) \ PORT_DIPSETTING( 0x10, "2 Coins/1 Credit" ) \ PORT_DIPSETTING( 0x38, "1 Coin/1 Credit" ) \ PORT_DIPSETTING( 0x30, "1 Coin/2 Credits" ) \ PORT_DIPSETTING( 0x28, "1 Coin/3 Credits" ) \ PORT_DIPSETTING( 0x20, "1 Coin/4 Credits" ) \ PORT_DIPSETTING( 0x18, "1 Coin/5 Credits" ) \ PORT_DIPNAME( 0x40, 0x40, "Screen Orientation", IP_KEY_NONE ) \ PORT_DIPSETTING( 0x00, "On" ) \ PORT_DIPSETTING( 0x40, "Off") \ PORT_DIPNAME( 0x80, 0x80, "Screen Reverse", IP_KEY_NONE ) \ PORT_DIPSETTING( 0x00, "On" ) \ PORT_DIPSETTING( 0x80, "Off") INPUT_PORTS_START( dd1_input_ports ) COMMON_INPUT_PORTS PORT_START /* DSW1 */ PORT_DIPNAME( 0x03, 0x03, "Difficulty", IP_KEY_NONE ) PORT_DIPSETTING( 0x02, "Easy") PORT_DIPSETTING( 0x03, "Normal") PORT_DIPSETTING( 0x01, "Hard") PORT_DIPSETTING( 0x00, "Very Hard") PORT_DIPNAME( 0x04, 0x04, "Attract Mode Sound", IP_KEY_NONE ) PORT_DIPSETTING( 0x00, "Off" ) PORT_DIPSETTING( 0x04, "On") PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_DIPNAME( 0x30, 0x30, "Bonus Life", IP_KEY_NONE ) PORT_DIPSETTING( 0x10, "20K") PORT_DIPSETTING( 0x00, "40K" ) PORT_DIPSETTING( 0x30, "30K and every 60K") PORT_DIPSETTING( 0x20, "40K and every 80K" ) PORT_DIPNAME( 0xc0, 0xc0, "Lives", IP_KEY_NONE ) PORT_DIPSETTING( 0xc0, "2") PORT_DIPSETTING( 0x80, "3" ) PORT_DIPSETTING( 0x40, "4") PORT_BITX( 0, 0x00, IPT_DIPSWITCH_SETTING | IPF_CHEAT, "Infinite", IP_KEY_NONE, IP_JOY_NONE, 0 ) COMMON_PORT4 INPUT_PORTS_END INPUT_PORTS_START( dd2_input_ports ) COMMON_INPUT_PORTS PORT_START /* DSW1 */ PORT_DIPNAME( 0x03, 0x03, "Difficulty", IP_KEY_NONE ) PORT_DIPSETTING( 0x02, "Easy") PORT_DIPSETTING( 0x03, "Normal") PORT_DIPSETTING( 0x01, "Medium") PORT_DIPSETTING( 0x00, "Hard") PORT_DIPNAME( 0x04, 0x04, "Attract Mode Sound", IP_KEY_NONE ) PORT_DIPSETTING( 0x00, "Off" ) PORT_DIPSETTING( 0x04, "On") PORT_DIPNAME( 0x08, 0x08, "Hurricane Kick", IP_KEY_NONE ) PORT_DIPSETTING( 0x00, "Easy" ) PORT_DIPSETTING( 0x08, "Normal") PORT_DIPNAME( 0x30, 0x30, "Timer", IP_KEY_NONE ) PORT_DIPSETTING( 0x20, "80" ) PORT_DIPSETTING( 0x30, "70") PORT_DIPSETTING( 0x10, "65") PORT_DIPSETTING( 0x00, "60" ) PORT_DIPNAME( 0xc0, 0xc0, "Lives", IP_KEY_NONE ) PORT_DIPSETTING( 0xc0, "1") PORT_DIPSETTING( 0x80, "2" ) PORT_DIPSETTING( 0x40, "3") PORT_DIPSETTING( 0x00, "4") COMMON_PORT4 INPUT_PORTS_END #undef COMMON_INPUT_PORTS #undef COMMON_PORT4 #define CHAR_LAYOUT( name, num ) \ static struct GfxLayout name = \ { \ 8,8, /* 8*8 chars */ \ num, /* 'num' characters */ \ 4, /* 4 bits per pixel */ \ { 0, 2, 4, 6 }, /* plane offset */ \ { 1, 0, 65, 64, 129, 128, 193, 192 }, \ { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, \ 32*8 /* every char takes 32 consecutive bytes */ \ }; #define TILE_LAYOUT( name, num, planeoffset ) \ static struct GfxLayout name = \ { \ 16,16, /* 16x16 chars */ \ num, /* 'num' characters */ \ 4, /* 4 bits per pixel */ \ { planeoffset*8+0, planeoffset*8+4, 0,4 }, /* plane offset */ \ { 3, 2, 1, 0, 16*8+3, 16*8+2, 16*8+1, 16*8+0, \ 32*8+3,32*8+2 ,32*8+1 ,32*8+0 ,48*8+3 ,48*8+2 ,48*8+1 ,48*8+0 }, \ { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, \ 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, \ 64*8 /* every char takes 64 consecutive bytes */ \ }; CHAR_LAYOUT( char_layout, 1024 ) /* foreground chars */ TILE_LAYOUT( tile_layout, 2048, 0x20000 ) /* background tiles */ TILE_LAYOUT( sprite_layout, 2048*2, 0x40000 ) /* sprites */ static struct GfxDecodeInfo gfxdecodeinfo[] = { { 1, 0xc0000, &char_layout, 0, 8 }, /* 8x8 text */ { 1, 0x40000, &sprite_layout, 128, 8 }, /* 16x16 sprites */ { 1, 0x00000, &tile_layout, 256, 8 }, /* 16x16 background tiles */ { -1 } }; CHAR_LAYOUT( dd2_char_layout, 2048 ) /* foreground chars */ TILE_LAYOUT( dd2_sprite_layout, 2048*3, 0x60000 ) /* sprites */ /* background tiles encoding for dd2 is the same as dd1 */ static struct GfxDecodeInfo dd2_gfxdecodeinfo[] = { { 1, 0x00000, &dd2_char_layout, 0, 8 }, /* 8x8 chars */ { 1, 0x50000, &dd2_sprite_layout, 128, 8 }, /* 16x16 sprites */ { 1, 0x10000, &tile_layout, 256, 8 }, /* 16x16 background tiles */ { -1 } }; static void dd_irq_handler(void) { cpu_cause_interrupt( 2, ym_irq ); } static struct YM2151interface ym2151_interface = { 1, /* 1 chip */ 3582071, /* seems to be the standard */ { 60 }, { dd_irq_handler } }; static struct ADPCMinterface adpcm_interface = { 2, /* 2 channels */ 8000, /* 8000Hz playback */ 4, /* memory region 4 */ 0, /* init function */ { 50, 50 } }; static struct OKIM6295interface okim6295_interface = { 1, /* 1 chip */ 8000, /* frequency (Hz) */ { 4 }, /* memory region */ { 15 } }; static int dd_interrupt(void) { return ( M6809_INT_FIRQ | M6809_INT_NMI ); } static struct MachineDriver ddragon_machine_driver = { /* basic machine hardware */ { { CPU_M6309, 3579545, /* 3.579545 Mhz */ 0, readmem,writemem,0,0, dd_interrupt,1 }, { CPU_HD63701, /* we're missing the code for this one */ 12000000 / 3, /* 4 Mhz */ 2, sub_readmem,sub_writemem,0,0, ignore_interrupt,0 }, { CPU_M6809 | CPU_AUDIO_CPU, 3579545, /* 3.579545 Mhz */ 3, sound_readmem,sound_writemem,0,0, ignore_interrupt,0 /* irq on command */ } }, 60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 100, /* heavy interleaving to sync up sprite<->main cpu's */ dd_init_machine, /* video hardware */ 32*8, 32*8,{ 1*8, 31*8-1, 2*8, 30*8-1 }, gfxdecodeinfo, 384, 384, 0, VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE, 0, dd_vh_start, dd_vh_stop, dd_vh_screenrefresh, /* sound hardware */ /*SOUND_SUPPORTS_STEREO*/0,0,0,0, { { SOUND_YM2151_ALT, &ym2151_interface }, { SOUND_ADPCM, &adpcm_interface } } }; static struct MachineDriver ddragonb_machine_driver = { /* basic machine hardware */ { { CPU_M6309, 3579545, /* 3.579545 Mhz */ 0, readmem,writemem,0,0, dd_interrupt,1 }, { CPU_M6809, 12000000 / 3, /* 4 Mhz */ 2, sub_readmem,sub_writemem,0,0, ignore_interrupt,0 }, { CPU_M6809 | CPU_AUDIO_CPU, 3579545, /* 3.579545 Mhz */ 3, sound_readmem,sound_writemem,0,0, ignore_interrupt,0 /* irq on command */ } }, 60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 2, /* 100 heavy interleaving to sync up sprite<->main cpu's */ dd_init_machine, /* video hardware */ 32*8, 32*8,{ 1*8, 31*8-1, 2*8, 30*8-1 }, gfxdecodeinfo, 384, 384, 0, VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE, 0, dd_vh_start, dd_vh_stop, dd_vh_screenrefresh, /* sound hardware */ /*SOUND_SUPPORTS_STEREO*/0,0,0,0, { { SOUND_YM2151_ALT, &ym2151_interface }, { SOUND_ADPCM, &adpcm_interface } } }; static struct MachineDriver ddragon2_machine_driver = { /* basic machine hardware */ { { CPU_M6309, 3579545, /* 3.579545 Mhz */ 0, readmem,dd2_writemem,0,0, dd_interrupt,1 }, { CPU_Z80, 12000000 / 3, /* 4 Mhz */ 2, /* memory region */ dd2_sub_readmem,dd2_sub_writemem,0,0, ignore_interrupt,0 }, { CPU_Z80 | CPU_AUDIO_CPU, 3579545, /* 3.579545 Mhz */ 3, /* memory region */ dd2_sound_readmem,dd2_sound_writemem,0,0, ignore_interrupt,0 } }, 60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 100, /* heavy interleaving to sync up sprite<->main cpu's */ dd2_init_machine, /* video hardware */ 32*8, 32*8,{ 1*8, 31*8-1, 2*8, 30*8-1 }, dd2_gfxdecodeinfo, 384, 384, 0, VIDEO_TYPE_RASTER | VIDEO_MODIFIES_PALETTE, 0, dd_vh_start, dd_vh_stop, dd_vh_screenrefresh, /* sound hardware */ /*SOUND_SUPPORTS_STEREO*/0,0,0,0, { { SOUND_YM2151_ALT, &ym2151_interface }, { SOUND_OKIM6295, &okim6295_interface } } }; /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( ddragon_rom ) ROM_REGION(0x28000) /* 64k for code + bankswitched memory */ ROM_LOAD( "a_m2_d02.bin", 0x08000, 0x08000, 0x668dfa19 ) ROM_LOAD( "a_k2_d03.bin", 0x10000, 0x08000, 0x5779705e ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "a_h2_d04.bin", 0x18000, 0x08000, 0x3bdea613 ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "a_g2_d05.bin", 0x20000, 0x08000, 0x728f87b9 ) /* banked at 0x4000-0x8000 */ ROM_REGION_DISPOSE(0xC8000) /* temporary space for graphics (disposed after conversion) */ ROM_LOAD( "a_a2_d06.bin", 0xC0000, 0x08000, 0x7a8b8db4 ) /* 0,1,2,3 */ /* text */ ROM_LOAD( "b_c5_d09.bin", 0x00000, 0x10000, 0x7c435887 ) /* 0,1 */ /* tiles */ ROM_LOAD( "b_a5_d10.bin", 0x10000, 0x10000, 0xc6640aed ) /* 0,1 */ /* tiles */ ROM_LOAD( "b_c7_d19.bin", 0x20000, 0x10000, 0x5effb0a0 ) /* 2,3 */ /* tiles */ ROM_LOAD( "b_a7_d20.bin", 0x30000, 0x10000, 0x5fb42e7c ) /* 2,3 */ /* tiles */ ROM_LOAD( "b_r7_d11.bin", 0x40000, 0x10000, 0x574face3 ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_p7_d12.bin", 0x50000, 0x10000, 0x40507a76 ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_m7_d13.bin", 0x60000, 0x10000, 0xbb0bc76f ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_l7_d14.bin", 0x70000, 0x10000, 0xcb4f231b ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_j7_d15.bin", 0x80000, 0x10000, 0xa0a0c261 ) /* 2,3 */ /* sprites */ ROM_LOAD( "b_h7_d16.bin", 0x90000, 0x10000, 0x6ba152f6 ) /* 2,3 */ /* sprites */ ROM_LOAD( "b_f7_d17.bin", 0xA0000, 0x10000, 0x3220a0b6 ) /* 2,3 */ /* sprites */ ROM_LOAD( "b_d7_d18.bin", 0xB0000, 0x10000, 0x65c7517d ) /* 2,3 */ /* sprites */ ROM_REGION(0x10000) /* sprite cpu */ /* missing mcu code */ /* currently load the audio cpu code in this location */ /* because otherwise mame will loop indefinately in cpu_run */ ROM_LOAD( "a_s2_d01.bin", 0x08000, 0x08000, 0x9efa95bb ) ROM_REGION(0x10000) /* audio cpu */ ROM_LOAD( "a_s2_d01.bin", 0x08000, 0x08000, 0x9efa95bb ) ROM_REGION(0x20000) /* adpcm samples */ ROM_LOAD( "a_s6_d07.bin", 0x00000, 0x10000, 0x34755de3 ) ROM_LOAD( "a_r6_d08.bin", 0x10000, 0x10000, 0x904de6f8 ) ROM_END ROM_START( ddragonb_rom ) ROM_REGION(0x28000) /* 64k for code + bankswitched memory */ ROM_LOAD( "ic26", 0x08000, 0x08000, 0xae714964 ) ROM_LOAD( "a_k2_d03.bin", 0x10000, 0x08000, 0x5779705e ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "ic24", 0x18000, 0x08000, 0xdbf24897 ) /* banked at 0x4000-0x8000 */ ROM_LOAD( "ic23", 0x20000, 0x08000, 0x6c9f46fa ) /* banked at 0x4000-0x8000 */ ROM_REGION_DISPOSE(0xc8000) /* temporary space for graphics (disposed after conversion) */ ROM_LOAD( "a_a2_d06.bin", 0xC0000, 0x08000, 0x7a8b8db4 ) /* 0,1,2,3 */ /* text */ ROM_LOAD( "b_c5_d09.bin", 0x00000, 0x10000, 0x7c435887 ) /* 0,1 */ /* tiles */ ROM_LOAD( "b_a5_d10.bin", 0x10000, 0x10000, 0xc6640aed ) /* 0,1 */ /* tiles */ ROM_LOAD( "b_c7_d19.bin", 0x20000, 0x10000, 0x5effb0a0 ) /* 2,3 */ /* tiles */ ROM_LOAD( "b_a7_d20.bin", 0x30000, 0x10000, 0x5fb42e7c ) /* 2,3 */ /* tiles */ ROM_LOAD( "b_r7_d11.bin", 0x40000, 0x10000, 0x574face3 ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_p7_d12.bin", 0x50000, 0x10000, 0x40507a76 ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_m7_d13.bin", 0x60000, 0x10000, 0xbb0bc76f ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_l7_d14.bin", 0x70000, 0x10000, 0xcb4f231b ) /* 0,1 */ /* sprites */ ROM_LOAD( "b_j7_d15.bin", 0x80000, 0x10000, 0xa0a0c261 ) /* 2,3 */ /* sprites */ ROM_LOAD( "b_h7_d16.bin", 0x90000, 0x10000, 0x6ba152f6 ) /* 2,3 */ /* sprites */ ROM_LOAD( "b_f7_d17.bin", 0xA0000, 0x10000, 0x3220a0b6 ) /* 2,3 */ /* sprites */ ROM_LOAD( "b_d7_d18.bin", 0xB0000, 0x10000, 0x65c7517d ) /* 2,3 */ /* sprites */ ROM_REGION(0x10000) /* sprite cpu */ ROM_LOAD( "ic38", 0x0c000, 0x04000, 0x6a6a0325 ) ROM_REGION(0x10000) /* audio cpu */ ROM_LOAD( "a_s2_d01.bin", 0x08000, 0x08000, 0x9efa95bb ) ROM_REGION(0x20000) /* adpcm samples */ ROM_LOAD( "a_s6_d07.bin", 0x00000, 0x10000, 0x34755de3 ) ROM_LOAD( "a_r6_d08.bin", 0x10000, 0x10000, 0x904de6f8 ) ROM_END ROM_START( ddragon2_rom ) ROM_REGION(0x28000) /* region#0: 64k for code */ ROM_LOAD( "26a9-04.bin", 0x08000, 0x8000, 0xf2cfc649 ) ROM_LOAD( "26aa-03.bin", 0x10000, 0x8000, 0x44dd5d4b ) ROM_LOAD( "26ab-0.bin", 0x18000, 0x8000, 0x49ddddcd ) ROM_LOAD( "26ac-02.bin", 0x20000, 0x8000, 0x097eaf26 ) ROM_REGION_DISPOSE(0x110000) /* region#1: graphics (disposed after conversion) */ ROM_LOAD( "26a8-0.bin", 0x00000, 0x10000, 0x3ad1049c ) /* 0,1,2,3 */ /* text */ ROM_LOAD( "26j4-0.bin", 0x10000, 0x20000, 0xa8c93e76 ) /* 0,1 */ /* tiles */ ROM_LOAD( "26j5-0.bin", 0x30000, 0x20000, 0xee555237 ) /* 2,3 */ /* tiles */ ROM_LOAD( "26j0-0.bin", 0x50000, 0x20000, 0xdb309c84 ) /* 0,1 */ /* sprites */ ROM_LOAD( "26j1-0.bin", 0x70000, 0x20000, 0xc3081e0c ) /* 0,1 */ /* sprites */ ROM_LOAD( "26af-0.bin", 0x90000, 0x20000, 0x3a615aad ) /* 0,1 */ /* sprites */ ROM_LOAD( "26j2-0.bin", 0xb0000, 0x20000, 0x589564ae ) /* 2,3 */ /* sprites */ ROM_LOAD( "26j3-0.bin", 0xd0000, 0x20000, 0xdaf040d6 ) /* 2,3 */ /* sprites */ ROM_LOAD( "26a10-0.bin", 0xf0000, 0x20000, 0x6d16d889 ) /* 2,3 */ /* sprites */ ROM_REGION(0x10000) /* region#2: sprite CPU 64kb (Upper 16kb = 0) */ ROM_LOAD( "26ae-0.bin", 0x00000, 0x10000, 0xea437867 ) ROM_REGION(0x10000) /* region#3: music CPU, 64kb */ ROM_LOAD( "26ad-0.bin", 0x00000, 0x8000, 0x75e36cd6 ) ROM_REGION(0x40000) /* region#4: adpcm */ ROM_LOAD( "26j6-0.bin", 0x00000, 0x20000, 0xa84b2a29 ) ROM_LOAD( "26j7-0.bin", 0x20000, 0x20000, 0xbc6a48d5 ) ROM_END static int ddragonb_hiload(void) { unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region]; /* check if the hi score table has already been initialized */ if ((RAM[0x0e73] == 0x02) && (RAM[0x0e76] == 0x27) && (RAM[0x0023] == 0x02)) { void *f; if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0)) != 0) { osd_fread(f,&RAM[0x0e73],6*5); RAM[0x0023] = RAM[0x0e73]; RAM[0x0024] = RAM[0x0e74]; RAM[0x0025] = RAM[0x0e75]; osd_fclose(f); } return 1; } else return 0; /* we can't load the hi scores yet */ } static void ddragonb_hisave(void) { void *f; unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region]; if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1)) != 0) { osd_fwrite(f,&RAM[0x0e73],6*5); osd_fclose(f); } } static int ddragon2_hiload(void) { unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region]; /* check if the hi score table has already been initialized */ if ((RAM[0x0f91] == 0x02) && (RAM[0x0f94] == 0x25) && (RAM[0x0023] == 0x02)) { void *f; if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,0)) != 0) { osd_fread(f,&RAM[0x0f91],6*5); RAM[0x0023] = RAM[0x0f91]; RAM[0x0024] = RAM[0x0f92]; RAM[0x0025] = RAM[0x0f93]; osd_fclose(f); } return 1; } else return 0; /* we can't load the hi scores yet */ } static void ddragon2_hisave(void) { void *f; unsigned char *RAM = Machine->memory_region[Machine->drv->cpu[0].memory_region]; if ((f = osd_fopen(Machine->gamedrv->name,0,OSD_FILETYPE_HIGHSCORE,1)) != 0) { osd_fwrite(f,&RAM[0x0f91],6*5); osd_fclose(f); } } struct GameDriver ddragon_driver = { __FILE__, 0, "ddragon", "Double Dragon", "1987", "bootleg?", "Carlos A. Lozano\nRob Rosenbrock\nChris Moore\nPhil Stroffolino\nErnesto Corvi", GAME_NOT_WORKING, &ddragon_machine_driver, 0, ddragon_rom, 0, 0, 0, 0, dd1_input_ports, 0, 0, 0, ORIENTATION_DEFAULT, ddragonb_hiload, ddragonb_hisave }; struct GameDriver ddragonb_driver = { __FILE__, &ddragon_driver, "ddragonb", "Double Dragon (bootleg)", "1987", "bootleg", "Carlos A. Lozano\nRob Rosenbrock\nChris Moore\nPhil Stroffolino\nErnesto Corvi\n", 0, &ddragonb_machine_driver, 0, ddragonb_rom, 0, 0, 0, 0, dd1_input_ports, 0, 0, 0, ORIENTATION_DEFAULT, ddragonb_hiload, ddragonb_hisave }; struct GameDriver ddragon2_driver = { __FILE__, 0, "ddragon2", "Double Dragon 2", "1988", "Technos", "Carlos A. Lozano\nRob Rosenbrock\nPhil Stroffolino\nErnesto Corvi\n", 0, &ddragon2_machine_driver, 0, ddragon2_rom, 0, 0, 0, 0, dd2_input_ports, 0, 0, 0, ORIENTATION_DEFAULT, ddragon2_hiload, ddragon2_hisave };
28.508909
106
0.66349
pierrelouys
b3b1c6cd8b0c19f45ef96384553f6f32f80319b4
33,662
cxx
C++
test/vr/vr_emulator.cxx
lintianfang/cleaning_cobotics
26ccba618aec0b1176fcfc889e95ed5320ccbe75
[ "BSD-3-Clause" ]
1
2020-07-26T10:54:41.000Z
2020-07-26T10:54:41.000Z
test/vr/vr_emulator.cxx
lintianfang/cleaning_cobotics
26ccba618aec0b1176fcfc889e95ed5320ccbe75
[ "BSD-3-Clause" ]
null
null
null
test/vr/vr_emulator.cxx
lintianfang/cleaning_cobotics
26ccba618aec0b1176fcfc889e95ed5320ccbe75
[ "BSD-3-Clause" ]
null
null
null
#include "vr_emulator.h" #include <cgv/math/ftransform.h> #include <cgv/math/pose.h> #include <cgv/utils/scan.h> #include <cgv/gui/key_event.h> #include <cgv/gui/trigger.h> #include <cgv_reflect_types/math/fvec.h> #include <cgv_reflect_types/math/quaternion.h> #include <cg_vr/vr_server.h> #include <cgv/utils/convert_string.h> #include <cg_gamepad/gamepad_server.h> const float Body_height = 1740.0f; const float Eye_height = 1630.0f; const float Chin_height = 1530.0f; const float Shoulder_height = 1425.0f; const float Shoulder_breadth = 485.0f; const float Arm_span = 1790.0f; const float Arm_length = 790.0f; const float Hip_width = 360.0f; const float Hip_height = 935.0f; const float Elbow_height = 1090.0f; const float Hand_height = 755.0f; const float Reach_Upwards = 2060.0f; const float Pupillary_distance = 63.0f; vr_emulated_kit::mat3x4 vr_emulated_kit::construct_pos_matrix(const quat& orientation, const vec3& position) { mat3 R; orientation.put_matrix(R); mat3x4 P; P.set_col(0, R.col(0)); P.set_col(1, R.col(1)); P.set_col(2, R.col(2)); P.set_col(3, position); return P; } vr_emulated_kit::mat4 vr_emulated_kit::construct_homogeneous_matrix(const quat& orientation, const vec3& position) { mat3 R; orientation.put_matrix(R); mat4 H; H.set_col(0, vec4(R(0, 0), R(1, 0), R(2, 0), 0)); H.set_col(1, vec4(R(0, 1), R(1, 1), R(2, 1), 0)); H.set_col(2, vec4(R(0, 2), R(1, 2), R(2, 2), 0)); H.set_col(3, vec4(position(0), position(1), position(2), 1.0f)); return H; } vr_emulated_kit::vec3 vr_emulated_kit::get_body_direction() const { vec3 up_dir; vec3 x_dir, z_dir; driver->put_x_direction(&x_dir(0)); driver->put_up_direction(&up_dir(0)); z_dir = cross(x_dir, up_dir); return -sin(body_direction)*x_dir + cos(body_direction)*z_dir; } void vr_emulated_kit::compute_state_poses() { float scale = body_height / Body_height; vec3 up_dir; vec3 x_dir, z_dir; driver->put_x_direction(&x_dir(0)); driver->put_up_direction(&up_dir(0)); z_dir = cross(x_dir, up_dir); mat4 T_body; T_body.set_col(0, vec4(cos(body_direction)*x_dir + sin(body_direction)*z_dir, 0)); T_body.set_col(1, vec4(up_dir, 0)); T_body.set_col(2, vec4(-sin(body_direction)*x_dir + cos(body_direction)*z_dir,0)); T_body.set_col(3, vec4(body_position, 1)); mat4 T_hip = cgv::math::translate4<float>(vec3(0,scale*Hip_height,0))* cgv::math::rotate4<float>(-60*hip_parameter, vec3(1, 0, 0)); mat4 T_head = cgv::math::translate4<float>(vec3(0, scale*(Chin_height - Hip_height), 0))* cgv::math::rotate4<float>(-90*gear_parameter, vec3(0, 1, 0)); mat4 R; hand_orientation[0].put_homogeneous_matrix(R); mat4 T_left = cgv::math::translate4<float>( scale*vec3((-Shoulder_breadth + Arm_length * hand_position[0](0)), Shoulder_height - Hip_height + Arm_length * hand_position[0](1), Arm_length*hand_position[0](2)))*R; hand_orientation[1].put_homogeneous_matrix(R); mat4 T_right = cgv::math::translate4<float>( scale*vec3(+(Shoulder_breadth + Arm_length * hand_position[1](0)), Shoulder_height - Hip_height + Arm_length * hand_position[1](1), Arm_length*hand_position[1](2)))*R; set_pose_matrix(T_body*T_hip*T_head, state.hmd.pose); set_pose_matrix(T_body*T_hip*T_left, state.controller[0].pose); set_pose_matrix(T_body*T_hip*T_right, state.controller[1].pose); for (int i = 0; i < 2; ++i) { if (!tracker_enabled[i]) { state.controller[2 + i].status = vr::VRS_DETACHED; continue; } mat4 T = construct_homogeneous_matrix(tracker_orientations[i], tracker_positions[i]); switch (tracker_attachments[i]) { case TA_HEAD: T = T_body * T_hip*T_head*T; break; case TA_LEFT_HAND: T = T_body * T_hip*T_left*T; break; case TA_RIGHT_HAND: T = T_body * T_hip*T_right*T; break; } set_pose_matrix(T, state.controller[2 + i].pose); state.controller[2 + i].status = vr::VRS_TRACKED; } } vr_emulated_kit::vr_emulated_kit(float _body_direction, const vec3& _body_position, float _body_height, unsigned _width, unsigned _height, vr::vr_driver* _driver, void* _handle, const std::string& _name, bool _ffb_support, bool _wireless) : gl_vr_display(_width, _height, _driver, _handle, _name, _ffb_support, _wireless) { body_position = _body_position; body_direction=_body_direction; body_height = _body_height; hip_parameter= 0; gear_parameter = 0; fovy = 90; hand_position[0] = vec3(0, -0.5f, -0.2f); hand_position[1] = vec3(0, -0.5f, -0.2f); hand_orientation[0] = quat(1, 0, 0, 0); hand_orientation[1] = quat(1, 0, 0, 0); state.hmd.status = vr::VRS_TRACKED; state.controller[0].status = vr::VRS_TRACKED; state.controller[1].status = vr::VRS_TRACKED; tracker_enabled[0] = tracker_enabled[1] = true; tracker_positions[0] = vec3(0.2f, 1.2f, 0.0f); tracker_positions[1] = vec3(-0.2f, 1.2f, 0.0f); tracker_orientations[0] = tracker_orientations[1] = quat(0.71f,-0.71f,0,0); tracker_attachments[0] = tracker_attachments[1] = TA_WORLD; compute_state_poses(); } const std::vector<std::pair<int, int> >& vr_emulated_kit::get_controller_throttles_and_sticks(int controller_index) const { static std::vector<std::pair<int, int> > throttles_and_sticks; if (throttles_and_sticks.empty()) { // add stick throttles_and_sticks.push_back(std::pair<int, int>(0, 1)); // add trigger throttle throttles_and_sticks.push_back(std::pair<int, int>(2, -1)); } return throttles_and_sticks; } const std::vector<std::pair<float, float> >& vr_emulated_kit::get_controller_throttles_and_sticks_deadzone_and_precision(int controller_index) const { static std::vector<std::pair<float, float> > deadzone_and_precision; if (deadzone_and_precision.empty()) { deadzone_and_precision.push_back(std::pair<float, float>(0.1f, 0.01f)); deadzone_and_precision.push_back(std::pair<float, float>(0.0f, 0.2f)); } return deadzone_and_precision; } void vr_emulated_kit::set_pose_matrix(const mat4& H, float* pose) const { pose[0] = H(0, 0); pose[1] = H(1, 0); pose[2] = H(2, 0); pose[3] = H(0, 1); pose[4] = H(1, 1); pose[5] = H(2, 1); pose[6] = H(0, 2); pose[7] = H(1, 2); pose[8] = H(2, 2); pose[9] = H(0, 3); pose[10] = H(1, 3); pose[11] = H(2, 3); } bool vr_emulated_kit::query_state_impl(vr::vr_kit_state& state, int pose_query) { compute_state_poses(); state = this->state; const vr_emulator* vr_em_ptr = dynamic_cast<const vr_emulator*>(get_driver()); if (vr_em_ptr) { // transform state with coordinate transformation mat34 coordinate_transform; vr_em_ptr->coordinate_rotation.put_matrix(reinterpret_cast<mat3&>(coordinate_transform)); reinterpret_cast<vec3&>(coordinate_transform(0, 3)) = vr_em_ptr->coordinate_displacement; cgv::math::pose_transform(coordinate_transform, reinterpret_cast<mat34&>(state.hmd.pose[0])); for (int i = 0; i < 4; ++i) cgv::math::pose_transform(coordinate_transform, reinterpret_cast<mat34&>(state.controller[i].pose[0])); } return true; } bool vr_emulated_kit::set_vibration(unsigned controller_index, float low_frequency_strength, float high_frequency_strength) { state.controller[controller_index].vibration[0] = low_frequency_strength; state.controller[controller_index].vibration[1] = high_frequency_strength; return has_force_feedback(); } void vr_emulated_kit::put_eye_to_head_matrix(int eye, float* pose_matrix) const { float scale = body_height / Body_height; set_pose_matrix( cgv::math::translate4<float>( scale*vec3(float(eye - 0.5f)*Pupillary_distance, Eye_height - Chin_height, -Pupillary_distance) ), pose_matrix ); } void vr_emulated_kit::put_projection_matrix(int eye, float z_near, float z_far, float* projection_matrix, const float*) const { reinterpret_cast<mat4&>(*projection_matrix) = cgv::math::perspective4<float>(fovy, float(width)/height, z_near, z_far); } void vr_emulated_kit::submit_frame() { } /// vr_emulator::vr_emulator() : cgv::base::node("vr_emulator") { current_kit_index = -1; interaction_mode = IM_BODY; left_ctrl = right_ctrl = up_ctrl = down_ctrl = false; home_ctrl = end_ctrl = pgup_ctrl = pgdn_ctrl = false; installed = true; body_speed = 1.0f; body_position = vec3(0, 0, 1); body_height = 1.75f; body_direction = 0; screen_width = 640; screen_height = 480; ffb_support = true; wireless = false; counter = 0; coordinate_rotation = quat(0.866f, 0.0f, 0.5f, 0.0f); coordinate_displacement = vec3(0.0f, 1.0f, 2.0f); ref_reference_state("vr_emulator_base_01").status = vr::VRS_TRACKED; mat3& ref_ori_1 = reinterpret_cast<mat3&>(*ref_reference_state("vr_emulator_base_01").pose); base_orientations.push_back(quat(cgv::math::rotate3<float>(vec3(-20.0f, 45.0f, 0)))); base_positions.push_back(vec3(1.0f, 2.0f, 1.0f)); base_serials.push_back("vr_emulator_base_01"); base_orientations.push_back(quat(cgv::math::rotate3<float>(vec3(-20.0f, -45.0f, 0)))); base_positions.push_back(vec3(-1.0f, 2.0f, 1.0f)); base_serials.push_back("vr_emulator_base_02"); update_reference_states(); connect(cgv::gui::get_animation_trigger().shoot, this, &vr_emulator::timer_event); } /// update a single renference state or all from base_orientations, base_positions and base_serials void vr_emulator::update_reference_states(int i) { int ib = i, ie = i + 1; if (i == -1) { ib = 0; ie = (int)base_serials.size(); } mat34 coordinate_transform = pose_construct(coordinate_rotation, coordinate_displacement); for (int k = ib; k < ie; ++k) { auto& pose = reinterpret_cast<mat34&>(ref_reference_state(base_serials[k]).pose[0]); ref_reference_state(base_serials[k]).status = vr::VRS_TRACKED; base_orientations[k].put_matrix(pose_orientation(pose)); pose_position(pose) = base_positions[k]; pose_transform(coordinate_transform, pose); } } void vr_emulator::timer_event(double t, double dt) { if (current_kit_index >= 0 && current_kit_index < (int)kits.size()) { switch (interaction_mode) { case IM_BODY: if (left_ctrl || right_ctrl) { if (is_alt) kits[current_kit_index]->body_position -= (float)(left_ctrl ? -dt : dt) * cross(kits[current_kit_index]->get_body_direction(), vec3(0, 1, 0)); else kits[current_kit_index]->body_direction += 3 * (float)(left_ctrl ? -dt : dt); update_all_members(); post_redraw(); } if (up_ctrl || down_ctrl) { kits[current_kit_index]->body_position -= (float)(down_ctrl ? -dt : dt) * kits[current_kit_index]->get_body_direction(); update_all_members(); post_redraw(); } if (home_ctrl || end_ctrl) { kits[current_kit_index]->gear_parameter += (float)(home_ctrl ? -dt : dt); if (kits[current_kit_index]->gear_parameter < -1) kits[current_kit_index]->gear_parameter = -1; else if (kits[current_kit_index]->gear_parameter > 1) kits[current_kit_index]->gear_parameter = 1; update_all_members(); post_redraw(); } if (pgup_ctrl || pgdn_ctrl) { kits[current_kit_index]->hip_parameter += (float)(pgup_ctrl ? -dt : dt); if (kits[current_kit_index]->hip_parameter < -1) kits[current_kit_index]->hip_parameter = -1; else if (kits[current_kit_index]->hip_parameter > 1) kits[current_kit_index]->hip_parameter = 1; update_all_members(); post_redraw(); } break; case IM_LEFT_HAND: case IM_RIGHT_HAND: case IM_TRACKER_1: case IM_TRACKER_2: case IM_BASE_1: case IM_BASE_2: case IM_BASE_3: case IM_BASE_4: { quat* orientation_ptr = 0; vec3* position_ptr = 0; if (interaction_mode < IM_BASE_1) { orientation_ptr = &kits[current_kit_index]->hand_orientation[interaction_mode - 1]; position_ptr = &kits[current_kit_index]->hand_position[interaction_mode - 1]; } else { uint32_t i = interaction_mode - IM_BASE_1; orientation_ptr = &base_orientations[i]; position_ptr = &base_positions[i]; } if (left_ctrl || right_ctrl) { if (is_alt) (*position_ptr)[0] += 0.3f * (float)(left_ctrl ? -dt : dt); else *orientation_ptr = quat(vec3(0, 1, 0), (float)(right_ctrl ? -dt : dt))*(*orientation_ptr); update_all_members(); post_redraw(); } if (up_ctrl || down_ctrl) { if (is_alt) (*position_ptr)[1] += 0.3f * (float)(down_ctrl ? -dt : dt); else *orientation_ptr = quat(vec3(1, 0, 0), (float)(up_ctrl ? -dt : dt))*(*orientation_ptr); update_all_members(); post_redraw(); } if (pgup_ctrl || pgdn_ctrl) { if (is_alt) (*position_ptr)[2] += 0.3f * (float)(pgup_ctrl ? -dt : dt); else *orientation_ptr = quat(vec3(0, 0, 1), (float)(pgup_ctrl ? -dt : dt))*(*orientation_ptr); update_all_members(); post_redraw(); } if (interaction_mode >= IM_BASE_1) { if (is_alt) on_set(position_ptr); else on_set(orientation_ptr); } break; } } } } /// void vr_emulator::on_set(void* member_ptr) { if (member_ptr == &current_kit_index) { while (current_kit_index >= (int)kits.size()) add_new_kit(); } if (!base_serials.empty()) { for (int i = 0; i < (int)base_serials.size(); ++i) if (member_ptr >= &base_orientations[i] && member_ptr < &base_orientations[i]+1 || member_ptr >= &base_positions[i] && member_ptr < &base_positions[i]+1) update_reference_states(i); } update_member(member_ptr); post_redraw(); } /// return name of driver std::string vr_emulator::get_driver_name() const { return name; } /// return whether driver is installed bool vr_emulator::is_installed() const { return installed; } bool vr_emulator::gamepad_connected = false; void vr_emulator::add_new_kit() { if (!gamepad_connected) { gamepad_connected = true; cgv::gui::connect_gamepad_server(); } ++counter; void* handle = 0; (unsigned&)handle = counter; vr_emulated_kit* new_kit = new vr_emulated_kit(body_direction, body_position, body_height, screen_width, screen_height, this, handle, std::string("vr_emulated_kit[") + cgv::utils::to_string(counter) + "]", ffb_support, wireless); kits.push_back(new_kit); register_vr_kit(handle, new_kit); if (current_kit_index == -1) { current_kit_index = kits.size() - 1; update_member(&current_kit_index); } cgv::gui::ref_vr_server().check_device_changes(cgv::gui::trigger::get_current_time()); post_recreate_gui(); } /// scan all connected vr kits and return a vector with their ids std::vector<void*> vr_emulator::scan_vr_kits() { std::vector<void*> result; if (is_installed()) for (auto kit_ptr : kits) result.push_back(kit_ptr->get_device_handle()); return result; } /// scan all connected vr kits and return a vector with their ids vr::vr_kit* vr_emulator::replace_by_index(int& index, vr::vr_kit* new_kit_ptr) { if (!is_installed()) return 0; for (auto kit_ptr : kits) { if (index == 0) { replace_vr_kit(kit_ptr->get_device_handle(), new_kit_ptr); return kit_ptr; } else --index; } return 0; } /// scan all connected vr kits and return a vector with their ids bool vr_emulator::replace_by_pointer(vr::vr_kit* old_kit_ptr, vr::vr_kit* new_kit_ptr) { if (!is_installed()) return false; for (auto kit_ptr : kits) { if (kit_ptr == old_kit_ptr) { replace_vr_kit(kit_ptr->get_device_handle(), new_kit_ptr); return true; } } return false; } /// put a 3d up direction into passed array void vr_emulator::put_up_direction(float* up_dir) const { reinterpret_cast<vec3&>(*up_dir) = vec3(0, 1, 0); } /// return the floor level relativ to the world origin float vr_emulator::get_floor_level() const { return 0; } /// return height of action zone in meters float vr_emulator::get_action_zone_height() const { return 2.5f; } /// return a vector of floor points defining the action zone boundary as a closed polygon void vr_emulator::put_action_zone_bounary(std::vector<float>& boundary) const { boundary.resize(18); for (unsigned i = 0; i < 6; ++i) { float angle = float(2 * M_PI*i / 6); vec3 pi(1.5f*cos(angle), 0, 2.5f*sin(angle)); reinterpret_cast<vec3&>(boundary[3 * i]) = pi; } } bool vr_emulator::check_for_button_toggle(cgv::gui::key_event& ke, int controller_index, vr::VRButtonStateFlags button, float touch_x, float touch_y) { if (current_kit_index == -1) return false; if (current_kit_index >= (int)kits.size()) return false; if (ke.get_action() != cgv::gui::KA_PRESS) return false; if (ke.get_modifiers() == cgv::gui::EM_SHIFT) { kits[current_kit_index]->state.controller[controller_index].axes[0] = touch_x; kits[current_kit_index]->state.controller[controller_index].axes[1] = touch_y; } else kits[current_kit_index]->state.controller[controller_index].button_flags ^= button; update_all_members(); return true; } bool vr_emulator::handle_ctrl_key(cgv::gui::key_event& ke, bool& fst_ctrl, bool* snd_ctrl_ptr) { if (current_kit_index == -1) return false; if (snd_ctrl_ptr && (ke.get_modifiers() & cgv::gui::EM_SHIFT) != 0) { *snd_ctrl_ptr = (ke.get_action() != cgv::gui::KA_RELEASE); update_member(snd_ctrl_ptr); } else { fst_ctrl = (ke.get_action() != cgv::gui::KA_RELEASE); update_member(&fst_ctrl); } is_alt = (ke.get_action() != cgv::gui::KA_RELEASE) && ((ke.get_modifiers() & cgv::gui::EM_ALT) != 0); update_member(&is_alt); return true; } /// overload and implement this method to handle events bool vr_emulator::handle(cgv::gui::event& e) { if (e.get_kind() != cgv::gui::EID_KEY) return false; cgv::gui::key_event& ke = static_cast<cgv::gui::key_event&>(e); switch (ke.get_key()) { case 'N' : if (ke.get_action() == cgv::gui::KA_PRESS && ke.get_modifiers() == cgv::gui::EM_CTRL + cgv::gui::EM_ALT) { add_new_kit(); return true; } return check_for_button_toggle(ke, 1, vr::VRF_BUTTON0, 0, -1); case '0': case '1': case '2': case '3': if (ke.get_modifiers() == cgv::gui::EM_SHIFT) { if (ke.get_action() != cgv::gui::KA_RELEASE) { current_kit_index = ke.get_key() - '0'; if (current_kit_index >= (int)kits.size()) current_kit_index = -1; update_member(&current_kit_index); } return true; } else if (ke.get_modifiers() == 0) { interaction_mode = InteractionMode(IM_BODY + ke.get_key() - '0'); update_member(&interaction_mode); return true; } break; case '5': case '6': case '7': case '8': interaction_mode = InteractionMode(IM_BODY + ke.get_key() - '0'); update_member(&interaction_mode); return true; case 'W': return check_for_button_toggle(ke, 0, vr::VRF_MENU, 0, 1); case 'X': return check_for_button_toggle(ke, 0, vr::VRF_BUTTON0, 0, -1); case 'Q': return check_for_button_toggle(ke, 0, vr::VRF_BUTTON1, -1, 1); case 'E': return check_for_button_toggle(ke, 0, vr::VRF_BUTTON2, 1, 1); case 'C': return check_for_button_toggle(ke, 0, vr::VRF_BUTTON3, 1, -1); case 'A': return check_for_button_toggle(ke, 0, vr::VRF_STICK_TOUCH, -1, 0); case 'S': return check_for_button_toggle(ke, 0, vr::VRF_STICK, 0, 0); case 'D': return check_for_button_toggle(ke, 0, vr::VRButtonStateFlags(0), 1, 0); case 'Y': return check_for_button_toggle(ke, 0, vr::VRButtonStateFlags(0), -1, -1); case 'I': return check_for_button_toggle(ke, 1, vr::VRF_MENU, 0, 1); case 'O': return check_for_button_toggle(ke, 1, vr::VRF_BUTTON1, 1, 1); case 'U': return check_for_button_toggle(ke, 1, vr::VRF_BUTTON2, -1, 1); case 'B': return check_for_button_toggle(ke, 1, vr::VRF_BUTTON3, -1, -1); case 'J': return check_for_button_toggle(ke, 1, vr::VRF_STICK, 0, 0); case 'K': return check_for_button_toggle(ke, 1, vr::VRF_STICK_TOUCH, 1, 0); case 'H': return check_for_button_toggle(ke, 1, vr::VRButtonStateFlags(0), -1, 0); case 'M': return check_for_button_toggle(ke, 1, vr::VRButtonStateFlags(0), 1, -1); case cgv::gui::KEY_Left: case cgv::gui::KEY_Num_4: return handle_ctrl_key(ke, left_ctrl, &home_ctrl); case cgv::gui::KEY_Right: case cgv::gui::KEY_Num_6: return handle_ctrl_key(ke, right_ctrl, &end_ctrl); case cgv::gui::KEY_Up: case cgv::gui::KEY_Num_8: return handle_ctrl_key(ke, up_ctrl, &pgup_ctrl); case cgv::gui::KEY_Down: case cgv::gui::KEY_Num_2: return handle_ctrl_key(ke, down_ctrl, &pgdn_ctrl); case cgv::gui::KEY_Home: case cgv::gui::KEY_Num_7: return handle_ctrl_key(ke, home_ctrl); case cgv::gui::KEY_End: case cgv::gui::KEY_Num_1: return handle_ctrl_key(ke, end_ctrl); case cgv::gui::KEY_Page_Up: case cgv::gui::KEY_Num_9: return handle_ctrl_key(ke, pgup_ctrl); case cgv::gui::KEY_Page_Down: case cgv::gui::KEY_Num_3: return handle_ctrl_key(ke, pgdn_ctrl); } return false; } /// overload to stream help information to the given output stream void vr_emulator::stream_help(std::ostream& os) { os << "vr_emulator:\n" << " Ctrl-Alt-N to create vr kit indexed from 0\n" << " Shift-<0-3> to select to be controlled vr kit (unselect if key's kit not exits)\n" << " <0-8> select <body|left hand|right hand|tracker 1|tracker 2|base 1|base 2|base 3|base 4> for control\n" << " body: <up|down> .. move, <left|right> .. turn, <pgup|pgdn> .. bend, \n" << " <home|end> .. gear, <alt>+<left|right> .. side step\n" << " hand&tracker: <left|right|up|down|pgdn|pgup> .. rotate or with <alt> translate\n" << " <W|X|Q|E|C|A|S:I|N|O|U|B|K|J> to toggle left:right controller buttons\n" << " <Shift>-<QWE:ASD:YXC>|<UIO:HJK:BNM> to set left:right controller touch xy to -1|0|+1\n" << std::endl; } /// return the type name std::string vr_emulator::get_type_name() const { return "vr_emulator"; } /// overload to show the content of this object void vr_emulator::stream_stats(std::ostream& os) { static std::string i_modes("body,left hand,right hand,tracker 1,tracker 2,base 1, base 2,base 3, base 4"); os << "vr_emulator: [" << cgv::utils::get_element(i_modes, (int)interaction_mode, ',') << "]" << std::endl; } /// bool vr_emulator::init(cgv::render::context& ctx) { return true; } /// this method is called in one pass over all drawables before the draw method void vr_emulator::init_frame(cgv::render::context& ctx) { } /// void vr_emulator::draw(cgv::render::context&) { for (auto kit_ptr : kits) { } } /// this method is called in one pass over all drawables after drawing void vr_emulator::finish_frame(cgv::render::context&) { } /// bool vr_emulator::self_reflect(cgv::reflect::reflection_handler& srh) { bool res = srh.reflect_member("current_kit_index", current_kit_index) && srh.reflect_member("installed", installed) && srh.reflect_member("create_body_direction", body_direction) && srh.reflect_member("create_body_position", body_position) && srh.reflect_member("body_height", body_height) && srh.reflect_member("screen_height", screen_height) && srh.reflect_member("screen_width", screen_width) && srh.reflect_member("wireless", wireless) && srh.reflect_member("ffb_support", ffb_support); if (res && current_kit_index != -1 && current_kit_index < (int)kits.size()) { vr_emulated_kit* kit_ptr = kits[current_kit_index]; res = srh.reflect_member("body_direction", kit_ptr->body_direction) && srh.reflect_member("body_height", kit_ptr->body_height) && srh.reflect_member("hip_parameter", kit_ptr->hip_parameter) && srh.reflect_member("gear_parameter", kit_ptr->gear_parameter) && srh.reflect_member("fovy", kit_ptr->fovy) && srh.reflect_member("body_position", kit_ptr->body_position) && srh.reflect_member("left_hand_position", kit_ptr->hand_position[0]) && srh.reflect_member("right_hand_position", kit_ptr->hand_position[1]) && srh.reflect_member("tracker_1_position", kit_ptr->tracker_positions[0]) && srh.reflect_member("tracker_2_position", kit_ptr->tracker_positions[1]) && srh.reflect_member("tracker_1_enabled", kit_ptr->tracker_enabled[0]) && srh.reflect_member("tracker_2_enabled", kit_ptr->tracker_enabled[1]) && srh.reflect_member("tracker_1_orientation", kit_ptr->tracker_orientations[0]) && srh.reflect_member("tracker_2_orientation", kit_ptr->tracker_orientations[1]) && srh.reflect_member("left_hand_orientation", kit_ptr->hand_orientation[0]) && srh.reflect_member("right_hand_orientation", kit_ptr->hand_orientation[1]) && srh.reflect_member("tracker_1_attachment", (int&)kit_ptr->tracker_attachments[0]) && srh.reflect_member("tracker_2_attachment", (int&)kit_ptr->tracker_attachments[1]); } return res; } void vr_emulator::create_trackable_gui(const std::string& name, vr::vr_trackable_state& ts) { add_decorator(name, "heading", "level=3"); add_member_control(this, "status", ts.status, "dropdown", "enums='detached,attached,tracked'"); if (begin_tree_node("pose", ts.pose[0], false, "level=3")) { align("\a"); add_view("x.x", ts.pose[0], "value", "w=50;step=0.0001", " "); add_view("x.y", ts.pose[1], "value", "w=50;step=0.0001", " "); add_view("x.z", ts.pose[2], "value", "w=50;step=0.0001"); add_view("y.x", ts.pose[3], "value", "w=50;step=0.0001", " "); add_view("y.y", ts.pose[4], "value", "w=50;step=0.0001", " "); add_view("y.z", ts.pose[5], "value", "w=50;step=0.0001"); add_view("z.x", ts.pose[6], "value", "w=50;step=0.0001", " "); add_view("z.y", ts.pose[7], "value", "w=50;step=0.0001", " "); add_view("z.z", ts.pose[8], "value", "w=50;step=0.0001"); add_view("0.x", ts.pose[9], "value", "w=50;step=0.0001", " "); add_view("0.y", ts.pose[10], "value", "w=50;step=0.0001", " "); add_view("0.z", ts.pose[11], "value", "w=50;step=0.0001"); align("\b"); end_tree_node(ts.pose[0]); } } void vr_emulator::create_controller_gui(int i, vr::vr_controller_state& cs) { create_trackable_gui(std::string("controller") + cgv::utils::to_string(i), cs); /// a unique time stamp for fast test whether state changed add_view("time_stamp", cs.time_stamp); add_member_control(this, "touch.x", cs.axes[0], "value_slider", "min=-1;max=1;ticks=true"); add_member_control(this, "touch.y", cs.axes[1], "value_slider", "min=-1;max=1;ticks=true"); add_member_control(this, "trigger", cs.axes[2], "value_slider", "min=0;max=1;ticks=true"); add_view("axes[3]", cs.axes[3], "value", "w=50", " "); add_view("axes[4]", cs.axes[4], "value", "w=50", " "); add_view("axes[5]", cs.axes[5], "value", "w=50"); add_view("axes[6]", cs.axes[6], "value", "w=50", " "); add_view("axes[7]", cs.axes[7], "value", "w=50"); add_view("vibration[0]", cs.vibration[0], "value", "w=50", " "); add_view("[1]", cs.vibration[1], "value", "w=50"); } void vr_emulator::create_tracker_gui(vr_emulated_kit* kit, int i) { if (begin_tree_node(std::string("tracker_") + cgv::utils::to_string(i+1), kit->tracker_enabled[i], false, "level=3")) { add_member_control(this, "enabled", kit->tracker_enabled[i], "check"); add_member_control(this, "attachment", kit->tracker_attachments[i], "dropdown", "enums='world,head,left hand,right hand'"); add_decorator("position", "heading", "level=3"); add_gui("position", kit->tracker_positions[i], "vector", "gui_type='value_slider';options='min=-3;max=3;step=0.0001;ticks=true'"); add_decorator("orientation", "heading", "level=3"); add_gui("orientation", reinterpret_cast<vec4&>(kit->tracker_orientations[i]), "direction", "gui_type='value_slider';options='min=-1;max=1;step=0.0001;ticks=true'"); end_tree_node(kit->tracker_enabled[i]); } } /// void vr_emulator::create_gui() { add_decorator("vr emulator", "heading", "level=2"); add_member_control(this, "installed", installed, "check"); if (begin_tree_node("base and calib", coordinate_rotation, false, "level=2")) { align("\a"); add_decorator("coordinate transform", "heading", "level=3"); add_gui("coordinate_rotation", reinterpret_cast<vec4&>(coordinate_rotation), "direction", "options='min=-1;max=1;step=0.0001;ticks=true'"); add_gui("coordinate_displacement", coordinate_displacement, "", "options='min=-2;max=2;step=0.0001;ticks=true'"); add_decorator("base stations", "heading", "level=3"); for (uint32_t i = 0; i < base_serials.size(); ++i) { add_member_control(this, "serial", base_serials[i]); add_gui("orientation", reinterpret_cast<vec4&>(base_orientations[i]), "direction", "options='min=-1;max=1;step=0.0001;ticks=true'"); add_gui("position", base_positions[i], "", "options='min=-2;max=2;step=0.0001;ticks=true'"); } align("\b"); end_tree_node(coordinate_rotation); } if (begin_tree_node("create kit", screen_width, false, "level=2")) { align("\a"); add_member_control(this, "screen_width", screen_width, "value_slider", "min=320;max=1920;ticks=true"); add_member_control(this, "screen_height", screen_height, "value_slider", "min=240;max=1920;ticks=true"); add_member_control(this, "ffb_support", ffb_support, "toggle", "w=90", " "); add_member_control(this, "wireless", wireless, "toggle", "w=90"); add_gui("body_position", body_position, "", "options='min=-1;max=1;step=0.0001;ticks=true'"); add_member_control(this, "body_direction", body_direction, "min=0;max=6.3;ticks=true"); add_member_control(this, "body_height", body_height, "min=1.2;max=2.0;step=0.001;ticks=true"); connect_copy(add_button("create new kit")->click, cgv::signal::rebind(this, &vr_emulator::add_new_kit)); align("\b"); end_tree_node(screen_width); } add_view("current_kit", current_kit_index, "", "w=50", " "); add_member_control(this, "mode", interaction_mode, "dropdown", "w=100;enums='body,left hand,right hand,tracker 1,tracker 2,base 1, base 2,base 3, base 4'"); add_member_control(this, "alt", is_alt, "toggle", "w=15", " "); add_member_control(this, "L", left_ctrl, "toggle", "w=15", " "); add_member_control(this, "R", right_ctrl, "toggle", "w=15", " "); add_member_control(this, "U", up_ctrl, "toggle", "w=15", " "); add_member_control(this, "D", down_ctrl, "toggle", "w=15", " "); add_member_control(this, "H", home_ctrl, "toggle", "w=15", " "); add_member_control(this, "E", end_ctrl, "toggle", "w=15", " "); add_member_control(this, "P", pgup_ctrl, "toggle", "w=15", " "); add_member_control(this, "p", pgdn_ctrl, "toggle", "w=15"); for (unsigned i = 0; i < kits.size(); ++i) { if (begin_tree_node(kits[i]->get_name(), *kits[i], true, "level=2")) { align("\a"); add_view("buttons left", kits[i]->fovy, "", "w=0", ""); add_gui("button_flags", kits[i]->state.controller[0].button_flags, "bit_field_control", "enums='ME=1,B0=2,B1=4,B2=8,B3=16,TO=32,ST=64';options='w=18;tooltip=\"" "MEnu button<W> \nButton 0 (Grip) <X>\nButton 1 <Q>\nButton 2 <E>\n" "Button 3 <C>\nstick TOuch <A>\nSTick press <S>\"';" "align='';gui_type='toggle'"); align(" "); add_view("touch xy", kits[i]->state.controller[0].axes[0], "", "w=18", ""); add_view("", kits[i]->state.controller[0].axes[1], "", "w=18"); add_view("buttons right", kits[i]->fovy, "", "w=0", ""); add_gui("button_flags", kits[i]->state.controller[1].button_flags, "bit_field_control", "enums='ME=1,B0=2,B1=4,B2=8,B3=16,TO=32,ST=64';options='w=18;tooltip=\"" "MEnu button<I> \nButton 0 (Grip) <N>\nButton 1 <O>\nButton 2 <U>\n" "Button 3 <B>\nstick TOuch <K>\nSTick press <J>\"';" "align='';gui_type='toggle'"); align(" "); add_view("touch xy", kits[i]->state.controller[1].axes[0], "", "w=18", ""); add_view("", kits[i]->state.controller[1].axes[1], "", "w=18"); add_member_control(this, "fovy", kits[i]->fovy, "value_slider", "min=30;max=180;ticks=true;log=true"); if (begin_tree_node("body pose", kits[i]->body_position, false, "level=3")) { align("\a"); add_decorator("body position", "heading", "level=3"); add_gui("body_position", kits[i]->body_position, "", "options='min=-5;max=5;ticks=true'"); add_member_control(this, "body_direction", kits[i]->body_direction, "value_slider", "min=0;max=6.3;ticks=true"); add_member_control(this, "body_height", kits[i]->body_height, "value_slider", "min=1.2;max=2.0;ticks=true"); add_member_control(this, "hip_parameter", kits[i]->hip_parameter, "value_slider", "min=-1;max=1;step=0.0001;ticks=true"); add_member_control(this, "gear_parameter", kits[i]->gear_parameter, "value_slider", "min=-1;max=1;step=0.0001;ticks=true"); for (int j = 0; j < 2; ++j) { if (begin_tree_node(j == 0 ? "left hand" : "right hand", kits[i]->hand_position[j], false, "level=3")) { align("\a"); add_decorator("position", "heading", "level=3"); add_gui("position", kits[i]->hand_position[j], "vector", "gui_type='value_slider';options='min=-3;max=3;step=0.0001;ticks=true'"); add_decorator("orientation", "heading", "level=3"); add_gui("orientation", reinterpret_cast<vec4&>(kits[i]->hand_orientation[j]), "direction", "gui_type='value_slider';options='min=-1;max=1;step=0.0001;ticks=true'"); align("\b"); end_tree_node(kits[i]->hand_position[j]); } } align("\b"); end_tree_node(kits[i]->body_position); } create_tracker_gui(kits[i], 0); create_tracker_gui(kits[i], 1); if (begin_tree_node("state", kits[i]->state.controller[0].pose[1], false, "level=3")) { align("\a"); if (begin_tree_node("hmd", kits[i]->state.hmd.pose[0], false, "level=3")) { align("\a"); create_trackable_gui("hmd", kits[i]->state.hmd); align("\b"); end_tree_node(kits[i]->state.hmd.pose[1]); } for (unsigned ci = 0; ci < 2; ++ci) { if (begin_tree_node((ci==0?"left controller":"right controller"), kits[i]->state.controller[ci], false, "level=3")) { align("\a"); create_controller_gui(ci, kits[i]->state.controller[ci]); align("\b"); end_tree_node(kits[i]->state.controller[ci]); } } align("\b"); end_tree_node(kits[i]->state.controller[0].pose[1]); } align("\b"); end_tree_node(*kits[i]); } } } struct register_driver_and_object { register_driver_and_object(const std::string& options) { vr_emulator* vr_emu_ptr = new vr_emulator(); vr::register_driver(vr_emu_ptr); register_object(base_ptr(vr_emu_ptr), options); } }; register_driver_and_object vr_emu_reg("vr_test");
38.295791
238
0.690007
lintianfang
b3b72217ed5fa497f0f2907df96208ad90276ed9
1,142
cpp
C++
src/mainproc.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/mainproc.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/mainproc.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#include "mainproc.hpp" #include "object/scene/mgr.hpp" #include "output.hpp" #include "sharedata.hpp" #include "effect/if.hpp" #include "imgui_sdl2.hpp" #include "spine/src/profiler.hpp" namespace rev { // ---------------- MainProc ---------------- const bool detail::c_pauseDefault = false; bool MainProc::runU(const Duration delta) { bool cont; { SpiProfile(Scene_Update); cont = mgr_scene.onUpdate(); } if(cont) { auto lk = g_system_shared.lockC(); if(auto fx = lk->fx.lock()) { const auto w = lk->window.lock(); lk.unlock(); SpiProfile(Draw); fx->beginTask(); mgr_gui.newFrame(fx, *w, delta); { SpiProfile(Scene_Draw); mgr_scene.onDraw(*fx); } mgr_gui.endFrame(); fx->endTask(); } return true; } return false; } bool MainProc::onPause() { LogR(Verbose, "OnPause"); return mgr_scene.onPause(); } void MainProc::onResume() { LogR(Verbose, "OnResume"); mgr_scene.onResume(); } void MainProc::onStop() { LogR(Verbose, "OnStop"); mgr_scene.onStop(); } void MainProc::onReStart() { LogR(Verbose, "OnRestart"); mgr_scene.onReStart(); } }
20.763636
46
0.623468
degarashi
b3c588d96f55fef4285cdaec68f40b3cc79245b0
445
cpp
C++
src/main/cpp/ExpandedTemplates.cpp
DaltonMcCart/csc232-lab04
f1bcacb6b006f968c3a3c1f3dc59ec1c242e162d
[ "MIT" ]
null
null
null
src/main/cpp/ExpandedTemplates.cpp
DaltonMcCart/csc232-lab04
f1bcacb6b006f968c3a3c1f3dc59ec1c242e162d
[ "MIT" ]
null
null
null
src/main/cpp/ExpandedTemplates.cpp
DaltonMcCart/csc232-lab04
f1bcacb6b006f968c3a3c1f3dc59ec1c242e162d
[ "MIT" ]
null
null
null
/** * CSC232 - Data Structures with C++ * Missouri State University, Fall 2017 * * @file ExpandedTemplates.cpp * @authors Jim Daehn <[email protected]> */ #include "ArrayBag.cpp" #include "BumpStrategy.cpp" #include "DoublingStrategy.cpp" #include "ResizableArrayBag.cpp" template class ResizableArrayBag<int>; template class ResizableArrayBag<double>; template class DoublingStrategy<int>; template class BumpStrategy<double>;
26.176471
48
0.768539
DaltonMcCart
b3c6d50bf36856ccc0ce2c27888f8178a1235900
3,383
cpp
C++
src/tdme/network/udpclient/NIOUDPClientMessage.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
src/tdme/network/udpclient/NIOUDPClientMessage.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
src/tdme/network/udpclient/NIOUDPClientMessage.cpp
mahula/tdme2
0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64
[ "BSD-3-Clause" ]
null
null
null
#include <tdme/network/udpclient/NIOUDPClientMessage.h> #include <string.h> #include <string> #include <sstream> #include <tdme/network/udpclient/NIOUDPClient.h> #include <tdme/utils/Console.h> #include <tdme/utils/Time.h> #include <tdme/utils/IntEncDec.h> using tdme::network::udpclient::NIOUDPClientMessage; using std::ios_base; using std::string; using std::stringstream; using std::to_string; using tdme::network::udpclient::NIOUDPClient; using tdme::utils::Console; using tdme::utils::Time; using tdme::utils::IntEncDec; NIOUDPClientMessage* NIOUDPClientMessage::parse(const char message[512], const size_t bytes) { // decode header MessageType messageType = MessageType::MESSAGETYPE_NONE; switch(message[0]) { case 'A': messageType = MessageType::MESSAGETYPE_ACKNOWLEDGEMENT; break; case 'C': messageType = MessageType::MESSAGETYPE_CONNECT; break; case 'M': messageType = MessageType::MESSAGETYPE_MESSAGE; break; default: Console::println("NIOUDPClientMessage::parse(): invalid message type: '" + (string() + message[0]) + "' (" + to_string(message[0]) + ")"); return nullptr; } uint32_t clientId; uint32_t messageId; uint32_t retries; IntEncDec::decodeInt(string(&message[1], 6), clientId); IntEncDec::decodeInt(string(&message[7], 6), messageId); IntEncDec::decodeInt(string(&message[13], 1), retries); // decode data stringstream* frame = nullptr; if (bytes > 14) { frame = new stringstream(); frame->write(&message[14], bytes - 14); } return new NIOUDPClientMessage(messageType, clientId, messageId, retries, frame); } NIOUDPClientMessage::NIOUDPClientMessage(const MessageType messageType, const uint32_t clientId, const uint32_t messageId, const uint8_t retries, stringstream* frame) : messageType(messageType), clientId(clientId), messageId(messageId), retries(retries), frame(frame) { time = Time::getCurrentMillis(); } NIOUDPClientMessage::~NIOUDPClientMessage() { if (frame != nullptr) delete frame; } const uint64_t NIOUDPClientMessage::getTime() { return time; } const NIOUDPClientMessage::MessageType NIOUDPClientMessage::getMessageType() { return messageType; } const uint32_t NIOUDPClientMessage::getClientId() { return clientId; } const uint32_t NIOUDPClientMessage::getMessageId() { return messageId; } const int64_t NIOUDPClientMessage::getRetryTime() { return NIOUDPClient::getRetryTime(retries); } const uint8_t NIOUDPClientMessage::getRetryCount() { return retries; } void NIOUDPClientMessage::retry() { retries++; } stringstream* NIOUDPClientMessage::getFrame() { return frame; } void NIOUDPClientMessage::generate(char message[512], size_t& bytes) { string datagram; switch(messageType) { case MESSAGETYPE_ACKNOWLEDGEMENT: datagram+= 'A'; break; case MESSAGETYPE_CONNECT: datagram+= 'C'; break; case MESSAGETYPE_MESSAGE : datagram+= 'M'; break; default: // FIXME break; } string retriesEncoded; string clientIdEncoded; string messageIdEncoded; IntEncDec::encodeInt(retries, retriesEncoded); IntEncDec::encodeInt(clientId, clientIdEncoded); IntEncDec::encodeInt(messageId, messageIdEncoded); datagram+= clientIdEncoded; datagram+= messageIdEncoded; datagram+= retriesEncoded[retriesEncoded.length()]; if (frame != nullptr) { datagram+= frame->str(); } bytes = datagram.size(); memcpy(message, datagram.c_str(), bytes); }
25.246269
168
0.74431
mahula
b3cfdefdb3ad4981889009e76ba8632698a7e9a0
1,506
hpp
C++
src/graphics/Texture.hpp
Nephet/CPP_project
1ae2890611e190ea44f403afa7fe9658c5147f4e
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
src/graphics/Texture.hpp
Nephet/CPP_project
1ae2890611e190ea44f403afa7fe9658c5147f4e
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
src/graphics/Texture.hpp
Nephet/CPP_project
1ae2890611e190ea44f403afa7fe9658c5147f4e
[ "libtiff", "Libpng", "BSD-3-Clause" ]
null
null
null
/* Arrogance Engine: a simple SDL/OpenGL game engine for Desktop and Android. Copyright (C) 2012 William James Dyce 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/>. */ #ifndef TEXTURE_HPP_INCLUDED #define TEXTURE_HPP_INCLUDED #include "SDL.h" // Needed for SDL_Surface #include "opengl.h" // Needed for GLuint #include "../math/V2.hpp" // Needed for iV2 #include "../math/Rect.hpp" // Needed for iRect class Texture { /// ATTRIBUTES private: GLuint handle; bool loaded; iRect area; // size of the texture /// METHODS public: // constructors, destructors Texture(); int load(const char* filename); int from_surface(SDL_Surface* surface); int unload(); ~Texture(); // accessors iRect getArea() const; GLuint getHandle() const; void draw(const fRect* source_pointer, const fRect* destination_pointer, float angle = 0.0); }; #endif // TEXTURE_HPP_INCLUDED
28.415094
74
0.720452
Nephet
b3d155968502bfb85abdacca972fdd40e0033df1
261
cpp
C++
src/hal/DummyLogicOutput.cpp
MarcelGehrig2/eeros-vt1
c1a8fa5329c98a89b97af2738bb6a674b6890704
[ "Apache-2.0" ]
null
null
null
src/hal/DummyLogicOutput.cpp
MarcelGehrig2/eeros-vt1
c1a8fa5329c98a89b97af2738bb6a674b6890704
[ "Apache-2.0" ]
null
null
null
src/hal/DummyLogicOutput.cpp
MarcelGehrig2/eeros-vt1
c1a8fa5329c98a89b97af2738bb6a674b6890704
[ "Apache-2.0" ]
null
null
null
#include <eeros/hal/DummyLogicOutput.hpp> using namespace eeros::hal; DummyLogicOutput::DummyLogicOutput(std::string id) : PeripheralOutput<bool>(id) { } bool DummyLogicOutput::get() { return value; } void DummyLogicOutput::set(bool val) { value = val; }
18.642857
83
0.739464
MarcelGehrig2
b3d3d81061efa2e2e73c2031648ebd4c46dbbfa1
4,524
cpp
C++
Service_Create_Description.cpp
srlemke/Oficina
5460191cf8f46351ac7f33c35798cb2ebb45c2f9
[ "MIT" ]
null
null
null
Service_Create_Description.cpp
srlemke/Oficina
5460191cf8f46351ac7f33c35798cb2ebb45c2f9
[ "MIT" ]
null
null
null
Service_Create_Description.cpp
srlemke/Oficina
5460191cf8f46351ac7f33c35798cb2ebb45c2f9
[ "MIT" ]
1
2017-08-25T16:21:10.000Z
2017-08-25T16:21:10.000Z
#include "Service_Create_Description.h" #include "ui_Service_Create_Description.h" #include "System_Services_and_Info.h" #include "QMessageBox" #include "QSqlQueryModel" #include "QSqlQuery" #include "QSqlError" #include "QSettings" Service_Create_Description::Service_Create_Description(QWidget *parent) : QDialog(parent), ui(new Ui::Service_Create_Description) { ui->setupUi(this); LoadSettings(); ui->line_Short_Description->setFocus(); } Service_Create_Description::~Service_Create_Description() { SaveSettings(); delete ui; } bool Service_Create_Description::Verify_Empty_Fields_On_Form() { if (ui->txt_Full_Description->toPlainText() == "" || ui->line_Short_Description->text() == "" ) { QMessageBox::warning(this, tr("Error!"), tr("All fields need to be filled!")); ui->line_Short_Description->setFocus(); return false; } //Only returns true if all the fields are filled. return true; } QString Service_Create_Description::getClientid() const { return clientid; } void Service_Create_Description::setClientid(const QString &value) { clientid = value; } QString Service_Create_Description::getCarID() const { return CarID; } void Service_Create_Description::setCarID(const QString &value) { CarID = value; } QString Service_Create_Description::getServiceID() const { return ServiceID; } void Service_Create_Description::setServiceID(const QString &value) { ServiceID = value; } void Service_Create_Description::on_txt_Full_Description_textChanged() //Check limit for 1000k chars// { const int max_size = 1000; if(ui->txt_Full_Description->toPlainText().length() > max_size){ ui->txt_Full_Description->setPlainText(System_Services_and_Info::Check_Text_Size(max_size, ui->txt_Full_Description->toPlainText())); //Warn the user: QMessageBox::warning(this, tr("Warning!"), tr("Keep the text shorter then %1 chars.").arg(max_size)); //Put cursor back to the end of the text// QTextCursor cursor = ui->txt_Full_Description->textCursor(); cursor.setPosition(ui->txt_Full_Description->document()->characterCount() - 1); ui->txt_Full_Description->setTextCursor(cursor); } } void Service_Create_Description::on_buttonBox_accepted() { if(Verify_Empty_Fields_On_Form()){ QSqlQuery query; query.prepare("INSERT INTO Service (Service_Client_id, Service_Client_Carid, Service_Short_Description, Service_Description, Service_Hour_Cost, Service_Hours_Duration)" "VALUES (:Service_Client_id, :Service_Client_Carid, :Service_Short_Description, :Service_Description, :Service_Hour_Cost, :Service_Hours_Duration )"); query.bindValue(":Service_Client_id", clientid); query.bindValue(":Service_Client_Carid", CarID); //System_Services_and_Info System_Services_and_Info; query.bindValue(":Service_Hour_Cost", System_Services_and_Info::Get_Current_Hour_Cost()); query.bindValue(":Service_Short_Description", ui->line_Short_Description->text()); query.bindValue(":Service_Description", ui->txt_Full_Description->toPlainText()); if (query.exec() == false){ QMessageBox::critical(this, tr("Error!"), query.lastError().text() + " class Service_Create_Description::on_btn_Salvar_clicked() "); }else{ ui->line_Short_Description->setFocus(); QMessageBox::information(this, tr("Success!"), tr("Service registered on this Client's Car.\n\n" "Now we will return to the previous screen on which this new Service " "is available for use, there you can add used Parts, update it and do" "all changes that you need while doing the 'Hard Work' ")); close(); } } } void Service_Create_Description::on_buttonBox_rejected() { close(); } void Service_Create_Description::LoadSettings() { QSettings setting("bedi1982","Oficina"); setting.beginGroup("Service_Create_Description"); QRect myrect = setting.value("position").toRect(); setGeometry(myrect); setting.endGroup(); } void Service_Create_Description::SaveSettings() { QSettings setting("bedi1982","Oficina"); setting.beginGroup("Service_Create_Description"); setting.setValue("position",this->geometry()); setting.endGroup(); }
33.264706
176
0.68855
srlemke
b3d7795fde867a52ea2d1d16c1600f8ca4112b10
1,506
cpp
C++
aws-cpp-sdk-networkmanager/source/model/ListConnectPeersRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-networkmanager/source/model/ListConnectPeersRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-networkmanager/source/model/ListConnectPeersRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/networkmanager/model/ListConnectPeersRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::NetworkManager::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; ListConnectPeersRequest::ListConnectPeersRequest() : m_coreNetworkIdHasBeenSet(false), m_connectAttachmentIdHasBeenSet(false), m_maxResults(0), m_maxResultsHasBeenSet(false), m_nextTokenHasBeenSet(false) { } Aws::String ListConnectPeersRequest::SerializePayload() const { return {}; } void ListConnectPeersRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_coreNetworkIdHasBeenSet) { ss << m_coreNetworkId; uri.AddQueryStringParameter("coreNetworkId", ss.str()); ss.str(""); } if(m_connectAttachmentIdHasBeenSet) { ss << m_connectAttachmentId; uri.AddQueryStringParameter("connectAttachmentId", ss.str()); ss.str(""); } if(m_maxResultsHasBeenSet) { ss << m_maxResults; uri.AddQueryStringParameter("maxResults", ss.str()); ss.str(""); } if(m_nextTokenHasBeenSet) { ss << m_nextToken; uri.AddQueryStringParameter("nextToken", ss.str()); ss.str(""); } }
22.477612
70
0.692563
perfectrecall
b3e4eabc9ed73b28a0fa0faca70c16898beba9a9
3,974
cc
C++
plugins/lpcm/Decoder.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
75
2015-04-26T11:22:07.000Z
2022-02-12T17:18:37.000Z
plugins/lpcm/Decoder.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
7
2016-05-31T21:56:01.000Z
2019-09-15T06:25:28.000Z
plugins/lpcm/Decoder.cc
bsdelf/mous
eb59b625d0ba8236f3597ae6015d9215cef922cf
[ "BSD-2-Clause" ]
19
2015-09-23T01:50:15.000Z
2022-02-12T17:18:41.000Z
#include <inttypes.h> #include <fstream> #include <cstring> using namespace std; #include <plugin/DecoderProto.h> using namespace mous; #include "Common.h" #define SAMPLES_PER_BLOCK 200; namespace { struct Self { ifstream input_stream; WavHeader wav_header; size_t raw_data_offset = 0; size_t raw_data_length = 0; int sample_length = 0; int block_length = 0; char* block_buffer = nullptr; size_t block_index = 0; size_t total_blocks = 0; uint64_t duration = 0; }; } static void* Create() { auto self = new Self; memset(&self->wav_header, 0, sizeof(WavHeader)); return self; } static void Destroy(void* ptr) { Close(ptr); delete SELF; } static ErrorCode Open(void* ptr, const char* url) { SELF->input_stream.open(url, ios::binary); if (!SELF->input_stream.is_open()) { return ErrorCode::DecoderFailedToOpen; } SELF->input_stream.seekg(0, ios::beg); SELF->input_stream.read(reinterpret_cast<char*>(&SELF->wav_header), sizeof(WavHeader)); if (memcmp(SELF->wav_header.riff_id, "RIFF", 4) != 0 || memcmp(SELF->wav_header.riff_type, "WAVE", 4) != 0 || memcmp(SELF->wav_header.format_id, "fmt ", 4) != 0) { SELF->input_stream.close(); return ErrorCode::DecoderFailedToInit; } SELF->raw_data_offset = sizeof(WavHeader); SELF->raw_data_length = SELF->wav_header.data_chunk_length; SELF->sample_length = SELF->wav_header.channels * SELF->wav_header.bits_per_sample / 8.f; SELF->block_length = SELF->sample_length * SAMPLES_PER_BLOCK; SELF->block_buffer = new char[SELF->block_length]; SELF->block_index = 0; SELF->total_blocks = (SELF->raw_data_length + SELF->block_length - 1) / SELF->block_length; SELF->duration = static_cast<double>(SELF->raw_data_length) / (SELF->wav_header.bits_per_sample / 8 * SELF->wav_header.channels) / SELF->wav_header.sample_rate * 1000; return ErrorCode::Ok; } static void Close(void* ptr) { SELF->input_stream.close(); memset(&SELF->wav_header, 0, sizeof(WavHeader)); if (SELF->block_buffer) { delete[] SELF->block_buffer; SELF->block_buffer = nullptr; } } static ErrorCode DecodeUnit(void* ptr, char* data, uint32_t* used, uint32_t* unit_count) { SELF->input_stream.read(data, SELF->block_length); *used = SELF->input_stream.gcount(); *unit_count = 1; return ErrorCode::Ok; } static ErrorCode SetUnitIndex(void* ptr, uint64_t index) { if ((size_t)index > SELF->total_blocks) { return ErrorCode::DecoderOutOfRange; } SELF->block_index = index; SELF->input_stream.seekg(SELF->raw_data_offset + SELF->block_index*SELF->block_length, ios::beg); return ErrorCode::Ok; } static uint32_t GetMaxBytesPerUnit(void* ptr) { return SELF->block_length; } static uint64_t GetUnitIndex(void* ptr) { return SELF->block_index; } static uint64_t GetUnitCount(void* ptr) { return SELF->total_blocks; } static AudioMode GetAudioMode(void* ptr) { return SELF->wav_header.channels == 1 ? AudioMode::Mono : AudioMode::Stereo; } static int32_t GetChannels(void* ptr) { return SELF->wav_header.channels; } static int32_t GetBitsPerSample(void* ptr) { return SELF->wav_header.bits_per_sample; } static int32_t GetSampleRate(void* ptr) { return SELF->wav_header.sample_rate; } static int32_t GetBitRate(void* ptr) { return SELF->wav_header.avg_bytes_per_sec / 1024; } static uint64_t GetDuration(void* ptr) { return SELF->duration; } static const BaseOption** GetOptions(void* ptr) { (void) ptr; return nullptr; } static const char** GetSuffixes(void* ptr) { (void) ptr; static const char* suffixes[] { "wav", nullptr }; return suffixes; } static const char** GetEncodings(void* ptr) { (void) ptr; static const char* encodings[] { "lpcm", nullptr }; return encodings; }
26.317881
101
0.672874
bsdelf
b3eeee7a52016d38c834cd157e131d417bb2bd27
503
cpp
C++
11.14-conditionalExplicit2/main.cpp
andreasfertig/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
107
2021-04-13T12:43:06.000Z
2022-03-30T05:07:16.000Z
11.14-conditionalExplicit2/main.cpp
jessesimpson/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
1
2021-04-13T12:59:30.000Z
2021-04-13T13:02:55.000Z
11.14-conditionalExplicit2/main.cpp
jessesimpson/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
29
2021-04-13T18:07:03.000Z
2022-03-28T13:44:01.000Z
// Copyright (c) Andreas Fertig. // SPDX-License-Identifier: MIT #include <type_traits> struct B {}; struct A { A() = default; explicit A(const B&) {} operator B() const { return {}; }; }; template<typename T> struct Wrapper { template<typename U> explicit(not std::is_convertible_v<U, T>) Wrapper(const U&); }; void Fun(Wrapper<A> a) {} template<typename T> template<typename U> Wrapper<T>::Wrapper(const U&) {} int main() { Fun(A{}); // Fun(B{}); // #A Does not compile anymore }
16.225806
62
0.640159
andreasfertig
b3efe4877963bfd472b8285c831409d0ae8fbf9f
71
cpp
C++
lib/cmake/Qt5Positioning/Qt5Positioning_QGeoPositionInfoSourceFactoryPoll_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5Positioning/Qt5Positioning_QGeoPositionInfoSourceFactoryPoll_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
lib/cmake/Qt5Positioning/Qt5Positioning_QGeoPositionInfoSourceFactoryPoll_Import.cpp
samlior/Qt5.15.0-rc2-static-macosx10.15
b9a1698a9a44baefbf3aa258af2ef487f12beff0
[ "blessing" ]
null
null
null
#include <QtPlugin> Q_IMPORT_PLUGIN(QGeoPositionInfoSourceFactoryPoll)
23.666667
50
0.887324
samlior
b3f26fd221d93d345ba4f0d9062817accd73e191
27,164
cpp
C++
src/rpcpopnode.cpp
POPChainFoundation/PopChain-Original
a99f5fbdf6ca96a281491482530c20a4c5915492
[ "MIT" ]
20
2018-04-28T06:38:05.000Z
2018-07-28T04:44:42.000Z
src/rpcpopnode.cpp
POPChainFoundation/PopChain-Original
a99f5fbdf6ca96a281491482530c20a4c5915492
[ "MIT" ]
2
2018-05-15T15:14:36.000Z
2018-05-18T00:51:48.000Z
src/rpcpopnode.cpp
POPChainFoundation/PopChain-Original
a99f5fbdf6ca96a281491482530c20a4c5915492
[ "MIT" ]
7
2018-05-15T12:28:19.000Z
2018-08-23T04:59:39.000Z
// // Copyright (c) 2017-2018 The Popchain Core Developers #include "activepopnode.h" #include "popsend.h" #include "init.h" #include "main.h" #include "popnode-payments.h" #include "popnode-sync.h" #include "popnodeconfig.h" #include "popnodeman.h" #include "rpcserver.h" #include "util.h" #include "utilmoneystr.h" #include <fstream> #include <iomanip> #include <univalue.h> void EnsureWalletIsUnlocked(); UniValue getpoolinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getpoolinfo\n" "Returns an object containing mixing pool related information.\n"); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("state", darkSendPool.GetStateString())); obj.push_back(Pair("mixing_mode", fPrivateSendMultiSession ? "multi-session" : "normal")); obj.push_back(Pair("queue", darkSendPool.GetQueueSize())); obj.push_back(Pair("entries", darkSendPool.GetEntriesCount())); obj.push_back(Pair("status", darkSendPool.GetStatus())); if (darkSendPool.pSubmittedToPopnode) { obj.push_back(Pair("outpoint", darkSendPool.pSubmittedToPopnode->vin.prevout.ToStringShort())); obj.push_back(Pair("addr", darkSendPool.pSubmittedToPopnode->addr.ToString())); } if (pwalletMain) { obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup)); obj.push_back(Pair("warnings", pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING ? "WARNING: keypool is almost depleted!" : "")); } return obj; } UniValue privatesend(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw std::runtime_error( "privatesend \"command\"\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "\nAvailable commands:\n" " start - Start mixing\n" " stop - Stop mixing\n" " reset - Reset mixing\n" + HelpRequiringPassphrase()); if(params[0].get_str() == "start") { if (pwalletMain->IsLocked(true)) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if(fPopNode) return "Mixing is not supported from popnodes"; fEnablePrivateSend = true; bool result = darkSendPool.DoAutomaticDenominating(); return "Mixing " + (result ? "started successfully" : ("start failed: " + darkSendPool.GetStatus() + ", will retry")); } if(params[0].get_str() == "stop") { fEnablePrivateSend = false; return "Mixing was stopped"; } if(params[0].get_str() == "reset") { darkSendPool.ResetPool(); return "Mixing was reset"; } return "Unknown command, please see \"help privatesend\""; } // Popchain DevTeam UniValue popnode(const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) { strCommand = params[0].get_str(); } if (strCommand == "start-many") throw JSONRPCError(RPC_INVALID_PARAMETER, "DEPRECATED, please use start-all instead"); if (fHelp || (strCommand != "start" && strCommand != "start-alias" && strCommand != "start-all" && strCommand != "start-missing" && strCommand != "start-disabled" && strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "debug" && strCommand != "genkey" && strCommand != "connect" && strCommand != "outputs" && strCommand != "status")) throw std::runtime_error( "popnode \"command\"... ( \"passphrase\" )\n" "Set of commands to execute popnode related actions\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "2. \"passphrase\" (string, optional) The wallet passphrase\n" "\nAvailable commands:\n" " count - Print number of all known popnodes (optional: 'ps')\n" " debug - Print popnode status\n" " genkey - Generate new popnodeprivkey\n" " outputs - Print popnode compatible outputs\n" " start - Start local Hot popnode configured in pop.conf\n" " start-alias - Start single remote popnode by assigned alias configured in popnode.conf\n" " start-<mode> - Start remote popnodes configured in popnode.conf (<mode>: 'all', 'missing', 'disabled')\n" " status - Print popnode status information\n" " list - Print list of all known popnodes (see popnodelist for more info)\n" " list-conf - Print popnode.conf in JSON format\n" ); if (strCommand == "list") { UniValue newParams(UniValue::VARR); // forward params but skip "list" for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return popnodelist(newParams, fHelp); } if(strCommand == "connect") { if (params.size() < 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Popnode address required"); std::string strAddress = params[1].get_str(); CService addr = CService(strAddress); CNode *pnode = ConnectNode((CAddress)addr, NULL); if(!pnode) throw JSONRPCError(RPC_INTERNAL_ERROR, strprintf("Couldn't connect to popnode %s", strAddress)); return "successfully connected"; } if (strCommand == "count") { if (params.size() > 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Too many parameters"); if (params.size() == 1) return mnodeman.size(); std::string strMode = params[1].get_str(); if (strMode == "ps") return mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); if (strMode == "enabled") return mnodeman.CountEnabled(); } if (strCommand == "debug") { if(activePopnode.nState != ACTIVE_POPNODE_INIT || !popnodeSync.IsBlockchainSynced()) return activePopnode.GetStatus(); CTxIn vin; CPubKey pubkey; CKey key; if(!pwalletMain || !pwalletMain->GetPopnodeVinAndKeys(vin, pubkey, key)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing popnode input, please look at the documentation for instructions on popnode creation"); return activePopnode.GetStatus(); } if (strCommand == "start") { if(!fPopNode) throw JSONRPCError(RPC_INTERNAL_ERROR, "You must set popnode=1 in the configuration"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } if(activePopnode.nState != ACTIVE_POPNODE_STARTED){ activePopnode.nState = ACTIVE_POPNODE_INIT; // TODO: consider better way activePopnode.ManageState(); } return activePopnode.GetStatus(); } if (strCommand == "start-alias") { if (params.size() < 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Please specify an alias"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } std::string strAlias = params[1].get_str(); bool fFound = false; UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", strAlias)); BOOST_FOREACH(CPopnodeConfig::CPopnodeEntry mne, popnodeConfig.getEntries()) { if(mne.getAlias() == strAlias) { fFound = true; std::string strError; CPopnodeBroadcast mnb; bool fResult = CPopnodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if(fResult) { mnodeman.UpdatePopnodeList(mnb); mnb.Relay(); } else { statusObj.push_back(Pair("errorMessage", strError)); } mnodeman.NotifyPopnodeUpdates(); break; } } if(!fFound) { statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Could not find alias in config. Verify with list-conf.")); } return statusObj; } if (strCommand == "start-all" || strCommand == "start-missing" || strCommand == "start-disabled") { { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } if((strCommand == "start-missing" || strCommand == "start-disabled") && !popnodeSync.IsPopnodeListSynced()) { throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "You can't use this command until popnode list is synced"); } int nSuccessful = 0; int nFailed = 0; UniValue resultsObj(UniValue::VOBJ); BOOST_FOREACH(CPopnodeConfig::CPopnodeEntry mne, popnodeConfig.getEntries()) { std::string strError; CTxIn vin = CTxIn(uint256S(mne.getTxHash()), uint32_t(atoi(mne.getOutputIndex().c_str()))); CPopnode *pmn = mnodeman.Find(vin); CPopnodeBroadcast mnb; if(strCommand == "start-missing" && pmn) continue; if(strCommand == "start-disabled" && pmn && pmn->IsEnabled()) continue; bool fResult = CPopnodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb); UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", mne.getAlias())); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if (fResult) { nSuccessful++; mnodeman.UpdatePopnodeList(mnb); mnb.Relay(); } else { nFailed++; statusObj.push_back(Pair("errorMessage", strError)); } resultsObj.push_back(Pair("status", statusObj)); } mnodeman.NotifyPopnodeUpdates(); UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Successfully started %d popnodes, failed to start %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "genkey") { CKey secret; secret.CreateNewKey(false); return CBitcoinSecret(secret).ToString(); } if (strCommand == "list-conf") { UniValue resultObj(UniValue::VOBJ); BOOST_FOREACH(CPopnodeConfig::CPopnodeEntry mne, popnodeConfig.getEntries()) { CTxIn vin = CTxIn(uint256S(mne.getTxHash()), uint32_t(atoi(mne.getOutputIndex().c_str()))); CPopnode *pmn = mnodeman.Find(vin); std::string strStatus = pmn ? pmn->GetStatus() : "MISSING"; UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("alias", mne.getAlias())); mnObj.push_back(Pair("address", mne.getIp())); mnObj.push_back(Pair("privateKey", mne.getPrivKey())); mnObj.push_back(Pair("txHash", mne.getTxHash())); mnObj.push_back(Pair("outputIndex", mne.getOutputIndex())); mnObj.push_back(Pair("status", strStatus)); resultObj.push_back(Pair("popnode", mnObj)); } return resultObj; } if (strCommand == "outputs") { // Find possible candidates std::vector<COutput> vPossibleCoins; pwalletMain->AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_1000); UniValue obj(UniValue::VOBJ); BOOST_FOREACH(COutput& out, vPossibleCoins) { obj.push_back(Pair(out.tx->GetHash().ToString(), strprintf("%d", out.i))); } return obj; } if (strCommand == "status") { if (!fPopNode) throw JSONRPCError(RPC_INTERNAL_ERROR, "This is not a popnode"); UniValue mnObj(UniValue::VOBJ); mnObj.push_back(Pair("vin", activePopnode.vin.ToString())); mnObj.push_back(Pair("service", activePopnode.service.ToString())); CPopnode mn; if(mnodeman.Get(activePopnode.vin, mn)) { mnObj.push_back(Pair("payee", CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString())); } mnObj.push_back(Pair("status", activePopnode.GetStatus())); return mnObj; } return NullUniValue; } // Popchain DevTeam UniValue popnodelist(const UniValue& params, bool fHelp) { std::string strMode = "status"; std::string strFilter = ""; if (params.size() >= 1) strMode = params[0].get_str(); if (params.size() == 2) strFilter = params[1].get_str(); if (fHelp || ( strMode != "activeseconds" && strMode != "addr" && strMode != "lastseen" && strMode != "protocol" && strMode != "rank" && strMode != "status")) { throw std::runtime_error( "popnodelist ( \"mode\" \"filter\" )\n" "Get a list of popnodes in different modes\n" "\nArguments:\n" "1. \"mode\" (string, optional/required to use filter, defaults = status) The mode to run list in\n" "2. \"filter\" (string, optional) Filter results. Partial match by outpoint by default in all modes,\n" " additional matches in some modes are also available\n" "\nAvailable modes:\n" " activeseconds - Print number of seconds popnode recognized by the network as enabled\n" " (since latest issued \"popnode start/start-many/start-alias\")\n" " addr - Print ip address associated with a popnode (can be additionally filtered, partial match)\n" " lastseen - Print timestamp of when a popnode was last seen on the network\n" " protocol - Print protocol of a popnode (can be additionally filtered, exact match))\n" " rank - Print rank of a popnode based on current block\n" " status - Print popnode status: PRE_ENABLED / ENABLED / EXPIRED / WATCHDOG_EXPIRED / NEW_START_REQUIRED /\n" " UPDATE_REQUIRED / POSE_BAN / OUTPOINT_SPENT (can be additionally filtered, partial match)\n" ); } UniValue obj(UniValue::VOBJ); if (strMode == "rank") { std::vector<std::pair<int, CPopnode> > vPopnodeRanks = mnodeman.GetPopnodeRanks(); BOOST_FOREACH(PAIRTYPE(int, CPopnode)& s, vPopnodeRanks) { std::string strOutpoint = s.second.vin.prevout.ToStringShort(); if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, s.first)); } } else { std::vector<CPopnode> vPopnodes = mnodeman.GetFullPopnodeVector(); BOOST_FOREACH(CPopnode& mn, vPopnodes) { std::string strOutpoint = mn.vin.prevout.ToStringShort(); if (strMode == "activeseconds") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, (int64_t)(mn.lastPing.sigTime - mn.sigTime))); } else if (strMode == "addr") { std::string strAddress = mn.addr.ToString(); if (strFilter !="" && strAddress.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strAddress)); } else if (strMode == "lastseen") { if (strFilter !="" && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, (int64_t)mn.lastPing.sigTime)); } else if (strMode == "protocol") { if (strFilter !="" && strFilter != strprintf("%d", mn.nProtocolVersion) && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, (int64_t)mn.nProtocolVersion)); } else if (strMode == "status") { std::string strStatus = mn.GetStatus(); if (strFilter !="" && strStatus.find(strFilter) == std::string::npos && strOutpoint.find(strFilter) == std::string::npos) continue; obj.push_back(Pair(strOutpoint, strStatus)); } } } return obj; } bool DecodeHexVecMnb(std::vector<CPopnodeBroadcast>& vecMnb, std::string strHexMnb) { if (!IsHex(strHexMnb)) return false; std::vector<unsigned char> mnbData(ParseHex(strHexMnb)); CDataStream ssData(mnbData, SER_NETWORK, PROTOCOL_VERSION); try { ssData >> vecMnb; } catch (const std::exception&) { return false; } return true; } UniValue popnodebroadcast(const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "create-alias" && strCommand != "create-all" && strCommand != "decode" && strCommand != "relay")) throw std::runtime_error( "popnodebroadcast \"command\"... ( \"passphrase\" )\n" "Set of commands to create and relay popnode broadcast messages\n" "\nArguments:\n" "1. \"command\" (string or set of strings, required) The command to execute\n" "2. \"passphrase\" (string, optional) The wallet passphrase\n" "\nAvailable commands:\n" " create-alias - Create single remote popnode broadcast message by assigned alias configured in popnode.conf\n" " create-all - Create remote popnode broadcast messages for all popnodes configured in popnode.conf\n" " decode - Decode popnode broadcast message\n" " relay - Relay popnode broadcast message to the network\n" + HelpRequiringPassphrase()); if (strCommand == "create-alias") { // wait for reindex and/or import to finish if (fImporting || fReindex) throw JSONRPCError(RPC_INTERNAL_ERROR, "Wait for reindex and/or import to finish"); if (params.size() < 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Please specify an alias"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } bool fFound = false; std::string strAlias = params[1].get_str(); UniValue statusObj(UniValue::VOBJ); std::vector<CPopnodeBroadcast> vecMnb; statusObj.push_back(Pair("alias", strAlias)); BOOST_FOREACH(CPopnodeConfig::CPopnodeEntry mne, popnodeConfig.getEntries()) { if(mne.getAlias() == strAlias) { fFound = true; std::string strError; CPopnodeBroadcast mnb; bool fResult = CPopnodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb, true); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if(fResult) { vecMnb.push_back(mnb); CDataStream ssVecMnb(SER_NETWORK, PROTOCOL_VERSION); ssVecMnb << vecMnb; statusObj.push_back(Pair("hex", HexStr(ssVecMnb.begin(), ssVecMnb.end()))); } else { statusObj.push_back(Pair("errorMessage", strError)); } break; } } if(!fFound) { statusObj.push_back(Pair("result", "not found")); statusObj.push_back(Pair("errorMessage", "Could not find alias in config. Verify with list-conf.")); } return statusObj; } if (strCommand == "create-all") { // wait for reindex and/or import to finish if (fImporting || fReindex) throw JSONRPCError(RPC_INTERNAL_ERROR, "Wait for reindex and/or import to finish"); { LOCK(pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); } std::vector<CPopnodeConfig::CPopnodeEntry> mnEntries; mnEntries = popnodeConfig.getEntries(); int nSuccessful = 0; int nFailed = 0; UniValue resultsObj(UniValue::VOBJ); std::vector<CPopnodeBroadcast> vecMnb; BOOST_FOREACH(CPopnodeConfig::CPopnodeEntry mne, popnodeConfig.getEntries()) { std::string strError; CPopnodeBroadcast mnb; bool fResult = CPopnodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb, true); UniValue statusObj(UniValue::VOBJ); statusObj.push_back(Pair("alias", mne.getAlias())); statusObj.push_back(Pair("result", fResult ? "successful" : "failed")); if(fResult) { nSuccessful++; vecMnb.push_back(mnb); } else { nFailed++; statusObj.push_back(Pair("errorMessage", strError)); } resultsObj.push_back(Pair("status", statusObj)); } CDataStream ssVecMnb(SER_NETWORK, PROTOCOL_VERSION); ssVecMnb << vecMnb; UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Successfully created broadcast messages for %d popnodes, failed to create %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); returnObj.push_back(Pair("detail", resultsObj)); returnObj.push_back(Pair("hex", HexStr(ssVecMnb.begin(), ssVecMnb.end()))); return returnObj; } if (strCommand == "decode") { if (params.size() != 2) throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'popnodebroadcast decode \"hexstring\"'"); std::vector<CPopnodeBroadcast> vecMnb; if (!DecodeHexVecMnb(vecMnb, params[1].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Popnode broadcast message decode failed"); int nSuccessful = 0; int nFailed = 0; int nDos = 0; UniValue returnObj(UniValue::VOBJ); BOOST_FOREACH(CPopnodeBroadcast& mnb, vecMnb) { UniValue resultObj(UniValue::VOBJ); if(mnb.CheckSignature(nDos)) { nSuccessful++; resultObj.push_back(Pair("vin", mnb.vin.ToString())); resultObj.push_back(Pair("addr", mnb.addr.ToString())); resultObj.push_back(Pair("pubKeyCollateralAddress", CBitcoinAddress(mnb.pubKeyCollateralAddress.GetID()).ToString())); resultObj.push_back(Pair("pubKeyPopnode", CBitcoinAddress(mnb.pubKeyPopnode.GetID()).ToString())); resultObj.push_back(Pair("vchSig", EncodeBase64(&mnb.vchSig[0], mnb.vchSig.size()))); resultObj.push_back(Pair("sigTime", mnb.sigTime)); resultObj.push_back(Pair("protocolVersion", mnb.nProtocolVersion)); resultObj.push_back(Pair("nLastDsq", mnb.nLastDsq)); UniValue lastPingObj(UniValue::VOBJ); lastPingObj.push_back(Pair("vin", mnb.lastPing.vin.ToString())); lastPingObj.push_back(Pair("blockHash", mnb.lastPing.blockHash.ToString())); lastPingObj.push_back(Pair("sigTime", mnb.lastPing.sigTime)); lastPingObj.push_back(Pair("vchSig", EncodeBase64(&mnb.lastPing.vchSig[0], mnb.lastPing.vchSig.size()))); resultObj.push_back(Pair("lastPing", lastPingObj)); } else { nFailed++; resultObj.push_back(Pair("errorMessage", "Popnode broadcast signature verification failed")); } returnObj.push_back(Pair(mnb.GetHash().ToString(), resultObj)); } returnObj.push_back(Pair("overall", strprintf("Successfully decoded broadcast messages for %d popnodes, failed to decode %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); return returnObj; } if (strCommand == "relay") { if (params.size() < 2 || params.size() > 3) throw JSONRPCError(RPC_INVALID_PARAMETER, "popnodebroadcast relay \"hexstring\" ( fast )\n" "\nArguments:\n" "1. \"hex\" (string, required) Broadcast messages hex string\n" "2. fast (string, optional) If none, using safe method\n"); std::vector<CPopnodeBroadcast> vecMnb; if (!DecodeHexVecMnb(vecMnb, params[1].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Popnode broadcast message decode failed"); int nSuccessful = 0; int nFailed = 0; bool fSafe = params.size() == 2; UniValue returnObj(UniValue::VOBJ); // verify all signatures first, bailout if any of them broken BOOST_FOREACH(CPopnodeBroadcast& mnb, vecMnb) { UniValue resultObj(UniValue::VOBJ); resultObj.push_back(Pair("vin", mnb.vin.ToString())); resultObj.push_back(Pair("addr", mnb.addr.ToString())); int nDos = 0; bool fResult; if (mnb.CheckSignature(nDos)) { if (fSafe) { fResult = mnodeman.CheckMnbAndUpdatePopnodeList(NULL, mnb, nDos); } else { mnodeman.UpdatePopnodeList(mnb); mnb.Relay(); fResult = true; } mnodeman.NotifyPopnodeUpdates(); } else fResult = false; if(fResult) { nSuccessful++; resultObj.push_back(Pair(mnb.GetHash().ToString(), "successful")); } else { nFailed++; resultObj.push_back(Pair("errorMessage", "Popnode broadcast signature verification failed")); } returnObj.push_back(Pair(mnb.GetHash().ToString(), resultObj)); } returnObj.push_back(Pair("overall", strprintf("Successfully relayed broadcast messages for %d popnodes, failed to relay %d, total %d", nSuccessful, nFailed, nSuccessful + nFailed))); return returnObj; } return NullUniValue; }
39.540029
191
0.579664
POPChainFoundation
b3f4c206d7fa5261ceede5e32247d22886c44204
2,385
cc
C++
elements/grid/linktestreceiver.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/grid/linktestreceiver.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/grid/linktestreceiver.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
/* * linktestreceiver.{cc,hh} -- receive and print link test packets * Douglas S. J. De Couto * * Copyright (c) 1999-2002 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include <click/args.hh> #include <clicknet/ether.h> #include <click/error.hh> #include "linktestreceiver.hh" #include "linktester.hh" #include "airoinfo.hh" CLICK_DECLS LinkTestReceiver::LinkTestReceiver() : _ai(0) { } LinkTestReceiver::~LinkTestReceiver() { } int LinkTestReceiver::configure(Vector<String> &conf, ErrorHandler *errh) { return Args(conf, this, errh) .read_p("AIROINFO", reinterpret_cast<Element *&>(_ai)) .complete(); } int LinkTestReceiver::initialize(ErrorHandler *) { return 0; } Packet * LinkTestReceiver::simple_action(Packet *p) { click_ether *eh = (click_ether *) p->data(); if (htons(eh->ether_type) != LinkTester::ETHERTYPE) return p; EtherAddress src(eh->ether_shost); EtherAddress dst(eh->ether_dhost); bool res = false; int dbm, quality; if (_ai) res = _ai->get_signal_info(src, dbm, quality); if (!_ai || !res) dbm = quality = -1; res = false; int avg_over_sec, avg_over_minute, max_over_minute; if (_ai) res = _ai->get_noise(avg_over_sec, avg_over_minute, max_over_minute); if (!_ai || !res) avg_over_sec = avg_over_minute = max_over_minute = -1; LinkTester::payload_t *payload = (LinkTester::payload_t *) (eh + 1); click_chatter("%p{timestamp},%u.%06u,%p{ether_ptr},%p{ether_ptr},%hu,%d,%u,%u\n", &p->timestamp_anno(), ntohl(payload->tx_sec), ntohl(payload->tx_usec), &src, &dst, ntohs(payload->size), payload->before ? 1 : 0, ntohl(payload->iteration), ntohl(payload->seq_no)); return p; } ELEMENT_REQUIRES(userlevel) EXPORT_ELEMENT(LinkTestReceiver)
26.797753
83
0.716981
MacWR
b3f826ae7c02e1f54afd80f7e631f3e8a504861f
1,361
cpp
C++
exercicio15/exercicio15/exercicio15.cpp
LucasRafaelBalduino/exercicio
411d4f0f87c70fcf6a216dcfc86089ee190b481e
[ "MIT" ]
1
2019-11-27T17:37:42.000Z
2019-11-27T17:37:42.000Z
exercicio15/exercicio15/exercicio15.cpp
LucasRafaelBalduino/exercicio
411d4f0f87c70fcf6a216dcfc86089ee190b481e
[ "MIT" ]
null
null
null
exercicio15/exercicio15/exercicio15.cpp
LucasRafaelBalduino/exercicio
411d4f0f87c70fcf6a216dcfc86089ee190b481e
[ "MIT" ]
null
null
null
// exercicio15.cpp : Este arquivo contém a função 'main'. A execução do programa começa e termina ali. // #include "pch.h" #include <iostream> // Dados um inteiro x e um inteiro não - negativo n, calcular x n int LerNumero() { printf_s("Digite um numero: \n"); int numero; scanf_s("%d", &numero); return numero; } void Calculo() { int numero = LerNumero(); int potencia = LerNumero(); int resultado; if (potencia > 0) { resultado = pow(numero, potencia); printf_s("Resultado: %d\n", resultado); } else { printf_s("O potenciado nao pode ser negativo"); } } int main() { Calculo(); } // Executar programa: Ctrl + F5 ou Menu Depurar > Iniciar Sem Depuração // Depurar programa: F5 ou menu Depurar > Iniciar Depuração // Dicas para Começar: // 1. Use a janela do Gerenciador de Soluções para adicionar/gerenciar arquivos // 2. Use a janela do Team Explorer para conectar-se ao controle do código-fonte // 3. Use a janela de Saída para ver mensagens de saída do build e outras mensagens // 4. Use a janela Lista de Erros para exibir erros // 5. Ir Para o Projeto > Adicionar Novo Item para criar novos arquivos de código, ou Projeto > Adicionar Item Existente para adicionar arquivos de código existentes ao projeto // 6. No futuro, para abrir este projeto novamente, vá para Arquivo > Abrir > Projeto e selecione o arquivo. sln
31.651163
178
0.713446
LucasRafaelBalduino
b6000e7132dceeb5c6a2e995611586bfdd517272
28,103
cxx
C++
gui/CameraView.cxx
quantumech3/TeleSculptor
921bf6911052ec77ac1cb15885cc49a90e473a61
[ "BSD-3-Clause" ]
1
2021-05-25T23:13:21.000Z
2021-05-25T23:13:21.000Z
gui/CameraView.cxx
quantumech3/TeleSculptor
921bf6911052ec77ac1cb15885cc49a90e473a61
[ "BSD-3-Clause" ]
null
null
null
gui/CameraView.cxx
quantumech3/TeleSculptor
921bf6911052ec77ac1cb15885cc49a90e473a61
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2017-2018 by Kitware, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name Kitware, Inc. nor the names of any 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 AUTHORS 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. */ #include "CameraView.h" #include "ui_CameraView.h" #include "am_CameraView.h" #include "ActorColorButton.h" #include "DataArrays.h" #include "FeatureOptions.h" #include "FieldInformation.h" #include "GroundControlPointsWidget.h" #include "ImageOptions.h" #include "RulerWidget.h" #include "vtkMaptkFeatureTrackRepresentation.h" #include <vital/types/feature_track_set.h> #include <vital/types/landmark_map.h> #include <vital/types/track.h> #include <vtkCamera.h> #include <vtkCellArray.h> #include <vtkDoubleArray.h> #include <vtkGenericOpenGLRenderWindow.h> #include <vtkImageActor.h> #include <vtkImageData.h> #include <vtkInteractorStyleRubberBand2D.h> #include <vtkMatrix4x4.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkUnsignedCharArray.h> #include <vtkUnsignedIntArray.h> #include <qtMath.h> #include <qtUiState.h> #include <QCheckBox> #include <QFormLayout> #include <QMenu> #include <QTimer> #include <QToolButton> #include <QWidgetAction> QTE_IMPLEMENT_D_FUNC(CameraView) /////////////////////////////////////////////////////////////////////////////// //BEGIN miscelaneous helpers using namespace LandmarkArrays; namespace // anonymous { //----------------------------------------------------------------------------- struct LandmarkData { kwiver::vital::rgb_color color; double elevation; unsigned observations; }; //----------------------------------------------------------------------------- class ResidualsOptions : public QWidget { public: ResidualsOptions(QString const& settingsGroup, QWidget* parent); ~ResidualsOptions() override; void setDefaultInlierColor(QColor const&); void setDefaultOutlierColor(QColor const&); ActorColorButton* const inlierColorButton; ActorColorButton* const outlierColorButton; QCheckBox* const inlierCheckbox; qtUiState uiState; }; //----------------------------------------------------------------------------- ResidualsOptions::ResidualsOptions( QString const& settingsGroup, QWidget* parent) : QWidget(parent), inlierColorButton(new ActorColorButton(this)), outlierColorButton(new ActorColorButton(this)), inlierCheckbox(new QCheckBox(this)) { auto const layout = new QFormLayout(this); layout->addRow("Inlier Color", this->inlierColorButton); layout->addRow("Outlier Color", this->outlierColorButton); layout->addRow("Inliers Only", this->inlierCheckbox); this->inlierColorButton->persist(this->uiState, settingsGroup + "/InlierColor"); this->outlierColorButton->persist(this->uiState, settingsGroup + "/OutlierColor"); this->uiState.mapChecked(settingsGroup + "/Inlier", this->inlierCheckbox); this->uiState.restore(); } //----------------------------------------------------------------------------- ResidualsOptions::~ResidualsOptions() { this->uiState.save(); } //----------------------------------------------------------------------------- void ResidualsOptions::setDefaultInlierColor(QColor const& color) { this->inlierColorButton->setColor(color); this->uiState.restore(); } //----------------------------------------------------------------------------- void ResidualsOptions::setDefaultOutlierColor(QColor const& color) { this->outlierColorButton->setColor(color); this->uiState.restore(); } } // namespace <anonymous> //END miscelaneous helpers /////////////////////////////////////////////////////////////////////////////// //BEGIN CameraViewPrivate definition //----------------------------------------------------------------------------- class CameraViewPrivate { public: struct VertexCloud { VertexCloud(); void clear(); vtkNew<vtkPoints> points; vtkNew<vtkCellArray> verts; vtkNew<vtkPolyData> data; vtkNew<vtkPolyDataMapper> mapper; vtkNew<vtkActor> actor; }; struct PointCloud : VertexCloud { PointCloud(); void addPoint(double x, double y, double z); }; struct SegmentCloud : VertexCloud { SegmentCloud(); void addSegment(double x1, double y1, double z1, double x2, double y2, double z2); }; struct LandmarkCloud : PointCloud { LandmarkCloud(); void addPoint(double x, double y, double z, LandmarkData const& data); void clear(); vtkNew<vtkUnsignedCharArray> colors; vtkNew<vtkUnsignedIntArray> observations; vtkNew<vtkDoubleArray> elevations; }; void setPopup(QAction* action, QMenu* menu); void setPopup(QAction* action, QWidget* widget); void setTransforms(int imageHeight); void updateFeatures(CameraView* q); Ui::CameraView UI; Am::CameraView AM; vtkNew<vtkRenderer> renderer; vtkSmartPointer<vtkRenderWindow> renderWindow; vtkNew<vtkImageActor> imageActor; vtkNew<vtkImageData> emptyImage; vtkNew<vtkMaptkFeatureTrackRepresentation> featureRep; vtkNew<vtkMatrix4x4> transformMatrix; LandmarkCloud landmarks; SegmentCloud residualsInlier; SegmentCloud residualsOutlier; QHash<kwiver::vital::landmark_id_t, LandmarkData> landmarkData; PointOptions* landmarkOptions; ResidualsOptions* residualsOptions; GroundControlPointsWidget* registrationPointsWidget; GroundControlPointsWidget* groundControlPointsWidget; RulerWidget* rulerWidget; double imageBounds[6]; EditMode editMode = EditMode::None; bool cameraValid = false; bool featuresDirty = false; bool renderQueued = false; }; //END CameraViewPrivate definition /////////////////////////////////////////////////////////////////////////////// //BEGIN geometry helpers //----------------------------------------------------------------------------- CameraViewPrivate::VertexCloud::VertexCloud() { this->data->SetPoints(this->points); this->mapper->SetInputData(this->data); this->actor->SetMapper(this->mapper); this->actor->GetProperty()->SetPointSize(2); } //----------------------------------------------------------------------------- void CameraViewPrivate::VertexCloud::clear() { this->verts->Reset(); this->points->Reset(); this->points->Modified(); this->verts->Modified(); } //----------------------------------------------------------------------------- CameraViewPrivate::PointCloud::PointCloud() { this->data->SetVerts(this->verts); } //----------------------------------------------------------------------------- void CameraViewPrivate::PointCloud::addPoint(double x, double y, double z) { auto const vid = this->points->InsertNextPoint(x, y, z); this->verts->InsertNextCell(1); this->verts->InsertCellPoint(vid); this->points->Modified(); this->verts->Modified(); } //----------------------------------------------------------------------------- CameraViewPrivate::SegmentCloud::SegmentCloud() { this->data->SetVerts(this->verts); this->data->SetLines(this->verts); } //----------------------------------------------------------------------------- void CameraViewPrivate::SegmentCloud::addSegment( double x1, double y1, double z1, double x2, double y2, double z2) { auto const vid1 = this->points->InsertNextPoint(x1, y1, z1); auto const vid2 = this->points->InsertNextPoint(x2, y2, z2); this->verts->InsertNextCell(2); this->verts->InsertCellPoint(vid1); this->verts->InsertCellPoint(vid2); this->points->Modified(); this->verts->Modified(); } //----------------------------------------------------------------------------- CameraViewPrivate::LandmarkCloud::LandmarkCloud() { this->colors->SetName(TrueColor); this->colors->SetNumberOfComponents(3); this->observations->SetName(Observations); this->observations->SetNumberOfComponents(1); this->elevations->SetName(Elevation); this->elevations->SetNumberOfComponents(1); this->data->GetPointData()->AddArray(this->colors); this->data->GetPointData()->AddArray(this->observations); this->data->GetPointData()->AddArray(this->elevations); } //----------------------------------------------------------------------------- void CameraViewPrivate::LandmarkCloud::clear() { this->VertexCloud::clear(); this->colors->Reset(); this->observations->Reset(); this->elevations->Reset(); this->colors->Modified(); this->observations->Modified(); this->elevations->Modified(); } //----------------------------------------------------------------------------- void CameraViewPrivate::LandmarkCloud::addPoint( double x, double y, double z, LandmarkData const& data) { this->PointCloud::addPoint(x, y, z); this->colors->InsertNextValue(data.color.r); this->colors->InsertNextValue(data.color.g); this->colors->InsertNextValue(data.color.b); this->observations->InsertNextValue(data.observations); this->elevations->InsertNextValue(data.elevation); this->colors->Modified(); this->observations->Modified(); this->elevations->Modified(); } //END geometry helpers /////////////////////////////////////////////////////////////////////////////// //BEGIN CameraViewPrivate implementation //----------------------------------------------------------------------------- void CameraViewPrivate::setPopup(QAction* action, QMenu* menu) { auto const widget = this->UI.toolBar->widgetForAction(action); auto const button = qobject_cast<QToolButton*>(widget); if (button) { button->setPopupMode(QToolButton::MenuButtonPopup); button->setMenu(menu); } } //----------------------------------------------------------------------------- void CameraViewPrivate::setPopup(QAction* action, QWidget* widget) { auto const parent = action->parentWidget(); auto const proxy = new QWidgetAction(parent); proxy->setDefaultWidget(widget); auto const menu = new QMenu(parent); menu->addAction(proxy); this->setPopup(action, menu); } //----------------------------------------------------------------------------- void CameraViewPrivate::setTransforms(int imageHeight) { vtkMatrix4x4* xf = this->transformMatrix; xf->Identity(); xf->SetElement(1, 1, -1.0); xf->SetElement(1, 3, imageHeight); this->featureRep->GetActivePointsWithDescActor()->SetUserMatrix(xf); this->featureRep->GetActivePointsWithoutDescActor()->SetUserMatrix(xf); this->featureRep->GetTrailsWithDescActor()->SetUserMatrix(xf); this->featureRep->GetTrailsWithoutDescActor()->SetUserMatrix(xf); this->landmarks.actor->SetUserMatrix(xf); this->residualsInlier.actor->SetUserMatrix(xf); this->residualsOutlier.actor->SetUserMatrix(xf); } //----------------------------------------------------------------------------- void CameraViewPrivate::updateFeatures(CameraView* q) { if (!this->featuresDirty) { this->featuresDirty = true; QMetaObject::invokeMethod(q, "updateFeatures", Qt::QueuedConnection); } } //END CameraViewPrivate implementation /////////////////////////////////////////////////////////////////////////////// //BEGIN CameraView //----------------------------------------------------------------------------- CameraView::CameraView(QWidget* parent, Qt::WindowFlags flags) : QWidget(parent, flags), d_ptr(new CameraViewPrivate) { QTE_D(); // Set up UI d->UI.setupUi(this); d->AM.setupActions(d->UI, this); d->renderWindow = vtkSmartPointer<vtkGenericOpenGLRenderWindow>::New(); auto const viewMenu = new QMenu(this); viewMenu->addAction(d->UI.actionViewReset); viewMenu->addAction(d->UI.actionViewResetFullExtents); d->setPopup(d->UI.actionViewReset, viewMenu); auto const imageOptions = new ImageOptions("CameraView/Image", this); imageOptions->addActor(d->imageActor); d->setPopup(d->UI.actionShowFrameImage, imageOptions); connect(imageOptions, &ImageOptions::modified, this, &CameraView::render); auto const featureOptions = new FeatureOptions{d->featureRep, "CameraView/FeaturePoints", this}; d->setPopup(d->UI.actionShowFeatures, featureOptions); connect(featureOptions, &FeatureOptions::modified, this, &CameraView::render); d->landmarkOptions = new PointOptions("CameraView/Landmarks", this); d->landmarkOptions->setDefaultColor(Qt::magenta); d->landmarkOptions->addActor(d->landmarks.actor); d->landmarkOptions->addMapper(d->landmarks.mapper); d->setPopup(d->UI.actionShowLandmarks, d->landmarkOptions); connect(d->landmarkOptions, &PointOptions::modified, this, &CameraView::render); auto const registrationMenu = new QMenu(this); registrationMenu->addAction(d->UI.actionComputeCamera); d->setPopup(d->UI.actionPlaceEditCRP, registrationMenu); d->registrationPointsWidget = new GroundControlPointsWidget(this); d->registrationPointsWidget->setColor({128, 224, 255}); d->registrationPointsWidget->setSelectedColor({64, 192, 255}); d->registrationPointsWidget->setTransformMatrix(d->transformMatrix); connect(d->UI.actionPlaceEditCRP, &QAction::toggled, this, &CameraView::pointPlacementEnabled); connect(d->UI.actionComputeCamera, &QAction::triggered, this, &CameraView::cameraComputationRequested, Qt::QueuedConnection); d->groundControlPointsWidget = new GroundControlPointsWidget(this); d->groundControlPointsWidget->setTransformMatrix(d->transformMatrix); d->rulerWidget = new RulerWidget(this); d->rulerWidget->setTransformMatrix(d->transformMatrix); d->rulerWidget->setComputeDistance(false); d->residualsOptions = new ResidualsOptions("CameraView/Residuals", this); d->residualsOptions->setDefaultInlierColor(QColor(255, 128, 0)); d->residualsOptions->setDefaultOutlierColor(QColor(0, 128, 255)); d->residualsOptions->inlierColorButton->addActor(d->residualsInlier.actor); d->residualsOptions->outlierColorButton->addActor(d->residualsOutlier.actor); d->setPopup(d->UI.actionShowResiduals, d->residualsOptions); this->setOutlierResidualsVisible( d->residualsOptions->inlierCheckbox->isChecked()); connect(d->residualsOptions->inlierColorButton, &ActorColorButton::colorChanged, this, &CameraView::render); connect(d->residualsOptions->outlierColorButton, &ActorColorButton::colorChanged, this, &CameraView::render); connect(d->residualsOptions->inlierCheckbox, &QCheckBox::toggled, this, &CameraView::setOutlierResidualsVisible); // Connect actions this->addAction(d->UI.actionViewReset); this->addAction(d->UI.actionViewResetFullExtents); this->addAction(d->UI.actionShowFeatures); this->addAction(d->UI.actionShowLandmarks); this->addAction(d->UI.actionShowResiduals); connect(d->UI.actionViewReset, &QAction::triggered, this, &CameraView::resetView); connect(d->UI.actionViewResetFullExtents, &QAction::triggered, this, &CameraView::resetViewToFullExtents); connect(d->UI.actionShowFrameImage, &QAction::toggled, this, &CameraView::setImageVisible); connect(d->UI.actionShowFeatures, &QAction::toggled, featureOptions, &FeatureOptions::setFeaturesWithDescVisible); connect(d->UI.actionShowFeatures, &QAction::toggled, featureOptions, &FeatureOptions::setFeaturesWithoutDescVisible); connect(d->UI.actionShowLandmarks, &QAction::toggled, this, &CameraView::setLandmarksVisible); connect(d->UI.actionShowResiduals, &QAction::toggled, this, &CameraView::setResidualsVisible); // Set up ortho view d->renderer->GetActiveCamera()->ParallelProjectionOn(); d->renderer->GetActiveCamera()->SetClippingRange(1.0, 3.0); d->renderer->GetActiveCamera()->SetPosition(0.0, 0.0, 2.0); // Set up render pipeline d->renderer->SetBackground(0, 0, 0); d->renderWindow->AddRenderer(d->renderer); #if VTK_VERSION_MAJOR < 9 d->UI.renderWidget->SetRenderWindow(d->renderWindow); #else d->UI.renderWidget->setRenderWindow(d->renderWindow); #endif // Set interactor #if VTK_VERSION_MAJOR < 9 auto renderInteractor = d->UI.renderWidget->GetInteractor(); #else auto renderInteractor = d->UI.renderWidget->interactor(); #endif vtkNew<vtkInteractorStyleRubberBand2D> is; renderInteractor->SetInteractorStyle(is); d->registrationPointsWidget->setInteractor(renderInteractor); d->groundControlPointsWidget->setInteractor(renderInteractor); d->rulerWidget->setInteractor(renderInteractor); // Set up actors d->renderer->AddActor(d->featureRep->GetActivePointsWithDescActor()); d->renderer->AddActor(d->featureRep->GetActivePointsWithoutDescActor()); d->renderer->AddActor(d->featureRep->GetTrailsWithDescActor()); d->renderer->AddActor(d->featureRep->GetTrailsWithoutDescActor()); d->renderer->AddActor(d->landmarks.actor); d->renderer->AddActor(d->residualsInlier.actor); d->renderer->AddActor(d->residualsOutlier.actor); d->renderer->AddViewProp(d->imageActor); d->imageActor->SetPosition(0.0, 0.0, -0.5); // Enable antialising by default d->renderer->UseFXAAOn(); // Create "dummy" image data for use when we have no "real" image d->emptyImage->SetExtent(0, 0, 0, 0, 0, 0); d->emptyImage->AllocateScalars(VTK_UNSIGNED_CHAR, 1); d->emptyImage->SetScalarComponentFromDouble(0, 0, 0, 0, 0.0); this->setImageData(nullptr, QSize{1, 1}); } //----------------------------------------------------------------------------- CameraView::~CameraView() { } //----------------------------------------------------------------------------- void CameraView::setBackgroundColor(QColor const& color) { QTE_D(); d->renderer->SetBackground(color.redF(), color.greenF(), color.blueF()); this->render(); } //----------------------------------------------------------------------------- void CameraView::setImagePath(QString const& path) { QTE_D(); d->UI.labelImagePath->setText(path); } //----------------------------------------------------------------------------- void CameraView::setImageData(vtkImageData* data, QSize dimensions) { QTE_D(); if (!data) { // If no image given, clear current image and replace with "empty" image d->imageActor->SetInputData(d->emptyImage); d->imageBounds[0] = 0.0; d->imageBounds[1] = dimensions.width() - 1; d->imageBounds[2] = 0.0; d->imageBounds[3] = dimensions.height() - 1; d->imageBounds[4] = 0.0; d->imageBounds[5] = 0.0; d->setTransforms(dimensions.height()); } else { // Set data on image actor d->imageActor->SetInputData(data); d->imageActor->Update(); d->imageActor->GetBounds(d->imageBounds); auto const h = d->imageBounds[3] + 1 - d->imageBounds[2]; d->setTransforms(qMax(0, static_cast<int>(h))); } this->render(); } //----------------------------------------------------------------------------- void CameraView::setActiveCamera(kwiver::arrows::vtk::vtkKwiverCamera* camera) { QTE_D(); auto const valid = (camera != nullptr); if (valid != d->cameraValid) { d->cameraValid = valid; this->setEditMode(d->editMode); } } //----------------------------------------------------------------------------- void CameraView::setActiveFrame(kwiver::vital::frame_id_t frame) { QTE_D(); d->featureRep->SetActiveFrame(frame); this->render(); } //----------------------------------------------------------------------------- void CameraView::setLandmarksData(kwiver::vital::landmark_map const& lm) { QTE_D(); auto const& landmarks = lm.landmarks(); auto const defaultColor = kwiver::vital::rgb_color{}; auto haveColor = false; auto maxObservations = unsigned{0}; auto minZ = qInf(), maxZ = -qInf(); auto autoMinZ = qInf(), autoMaxZ = -qInf(); std::vector<double> zValues; foreach (auto const& lmi, landmarks) { auto const z = lmi.second->loc()[2]; auto const& color = lmi.second->color(); auto const observations = lmi.second->observations(); auto const ld = LandmarkData{color, z, observations}; d->landmarkData.insert(lmi.first, ld); haveColor = haveColor || (color != defaultColor); maxObservations = qMax(maxObservations, observations); minZ = qMin(minZ, z); maxZ = qMax(maxZ, z); zValues.push_back(z); } if (!zValues.empty()) { // Set the range to cover the middle 90% of the data std::sort(zValues.begin(), zValues.end()); auto const n = zValues.size(); // index at 5% of the data auto const i = n / 20; autoMinZ = zValues[i]; autoMaxZ = zValues[n - 1 - i]; } auto fields = QHash<QString, FieldInformation>{}; fields.insert("Elevation", FieldInformation{Elevation, {minZ, maxZ}, {autoMinZ, autoMaxZ}}); if (maxObservations) { auto const upper = static_cast<double>(maxObservations); fields.insert("Observations", FieldInformation{Observations, {0.0, upper}, {0.0, upper}}); } d->landmarkOptions->setTrueColorAvailable(haveColor); d->landmarkOptions->setDataFields(fields); } //----------------------------------------------------------------------------- void CameraView::addFeatureTrack(kwiver::vital::track const& track) { QTE_D(); auto const id = track.id(); foreach (auto const& state, track) { auto const& fts = std::dynamic_pointer_cast<kwiver::vital::feature_track_state>(state); if ( !fts ) { continue; } auto const& loc = fts->feature->loc(); if (fts->descriptor) { d->featureRep->AddTrackWithDescPoint( id, state->frame(), loc[0], loc[1]); } else { d->featureRep->AddTrackWithoutDescPoint( id, state->frame(), loc[0], loc[1]); } } d->updateFeatures(this); } //----------------------------------------------------------------------------- void CameraView::addLandmark( kwiver::vital::landmark_id_t id, double x, double y) { QTE_D(); d->landmarks.addPoint(x, y, 0.0, d->landmarkData.value(id)); } //----------------------------------------------------------------------------- void CameraView::addResidual( kwiver::vital::track_id_t id, double x1, double y1, double x2, double y2, bool inlier) { QTE_D(); Q_UNUSED(id) if (inlier) { d->residualsInlier.addSegment(x1, y1, -0.3, x2, y2, -0.3); } else { d->residualsOutlier.addSegment(x1, y1, -0.2, x2, y2, -0.2); } } //----------------------------------------------------------------------------- void CameraView::clearLandmarks() { QTE_D(); d->landmarks.clear(); } //----------------------------------------------------------------------------- void CameraView::clearResiduals() { QTE_D(); d->residualsInlier.clear(); d->residualsOutlier.clear(); } //----------------------------------------------------------------------------- void CameraView::clearFeatureTracks() { QTE_D(); d->featureRep->ClearTrackData(); d->updateFeatures(this); } //----------------------------------------------------------------------------- void CameraView::setImageVisible(bool state) { QTE_D(); d->imageActor->SetVisibility(state); this->render(); } //----------------------------------------------------------------------------- void CameraView::setLandmarksVisible(bool state) { QTE_D(); d->landmarks.actor->SetVisibility(state); this->render(); } //----------------------------------------------------------------------------- void CameraView::setResidualsVisible(bool state) { QTE_D(); d->residualsInlier.actor->SetVisibility(state); d->residualsOutlier.actor->SetVisibility(state && !d->residualsOptions->inlierCheckbox->isChecked()); this->render(); } //----------------------------------------------------------------------------- void CameraView::setOutlierResidualsVisible(bool state) { QTE_D(); bool overallState = d->residualsInlier.actor->GetVisibility(); d->residualsOutlier.actor->SetVisibility(overallState && !state); this->render(); } //----------------------------------------------------------------------------- void CameraView::resetView() { QTE_D(); double renderAspect[2]; d->renderer->GetAspect(renderAspect); auto const w = d->imageBounds[1] - d->imageBounds[0]; auto const h = d->imageBounds[3] - d->imageBounds[2]; auto const a = w / h; auto const s = 0.5 * h * qMax(a / renderAspect[0], 1.0); d->renderer->ResetCamera(d->imageBounds); d->renderer->GetActiveCamera()->SetParallelScale(s); this->render(); } //----------------------------------------------------------------------------- void CameraView::resetViewToFullExtents() { QTE_D(); d->renderer->ResetCamera(); this->render(); } //----------------------------------------------------------------------------- void CameraView::updateFeatures() { QTE_D(); if (d->featuresDirty) { d->featureRep->Update(); this->render(); d->featuresDirty = false; } } //----------------------------------------------------------------------------- GroundControlPointsWidget* CameraView::groundControlPointsWidget() const { QTE_D(); return d->groundControlPointsWidget; } //----------------------------------------------------------------------------- GroundControlPointsWidget* CameraView::registrationPointsWidget() const { QTE_D(); return d->registrationPointsWidget; } //----------------------------------------------------------------------------- RulerWidget* CameraView::rulerWidget() const { QTE_D(); return d->rulerWidget; } //----------------------------------------------------------------------------- void CameraView::render() { QTE_D(); if (!d->renderQueued) { QTimer::singleShot(0, this, [d]() { d->renderWindow->Render(); d->renderQueued = false; }); } } //----------------------------------------------------------------------------- void CameraView::enableAntiAliasing(bool enable) { QTE_D(); d->renderer->SetUseFXAA(enable); this->render(); } //----------------------------------------------------------------------------- void CameraView::setEditMode(EditMode mode) { QTE_D(); d->editMode = mode; d->groundControlPointsWidget->enableWidget( mode == EditMode::GroundControlPoints && d->cameraValid); d->registrationPointsWidget->enableWidget( mode == EditMode::CameraRegistrationPoints); d->UI.actionPlaceEditCRP->setChecked( mode == EditMode::CameraRegistrationPoints); } //----------------------------------------------------------------------------- void CameraView::clearGroundControlPoints() { QTE_D(); d->groundControlPointsWidget->clearPoints(); d->registrationPointsWidget->clearPoints(); this->render(); } //END CameraView
29.488982
80
0.605985
quantumech3
b6032e4f09510093be59c500f1a63805270743c0
11,087
hpp
C++
engine/primitives/vector_prims.hpp
Venkster123/Zhetapi
9a034392c06733c57d892afde300e90c4b7036f9
[ "MIT" ]
27
2020-06-05T15:39:31.000Z
2022-01-07T05:03:01.000Z
engine/primitives/vector_prims.hpp
Venkster123/Zhetapi
9a034392c06733c57d892afde300e90c4b7036f9
[ "MIT" ]
1
2021-02-12T04:51:40.000Z
2021-02-12T04:51:40.000Z
engine/primitives/vector_prims.hpp
Venkster123/Zhetapi
9a034392c06733c57d892afde300e90c4b7036f9
[ "MIT" ]
4
2021-02-12T04:39:55.000Z
2021-11-15T08:00:06.000Z
#ifndef VECTOR_PRIMITIVES_H_ #define VECTOR_PRIMITIVES_H_ namespace zhetapi { /** * @brief Default vector constructor. */ template <class T> Vector <T> ::Vector() : Matrix <T> () {} /** * @brief Size constructor. Components are initialized to 0 or the default value * of T. * * @param len size of the vector. */ template <class T> Vector <T> ::Vector(size_t len) : Matrix <T> (len, 1) {} /** * @brief Size constructor. Each component is initialized to def. * * @param rs the number of rows (size) of the vector. * @param def the value each component is initialized to. */ template <class T> Vector <T> ::Vector(size_t rs, T def) : Matrix <T> (rs, 1, def) {} #ifdef __AVR /** * @brief Size constructor. Each component is evaluated from a function which * depends on the index. * * @param rs the number of rows (size) of the vector. * @param gen a pointer to the function that generates the coefficients. */ template <class T> Vector <T> ::Vector(size_t rs, T (*gen)(size_t)) : Matrix <T> (rs, 1, gen) {} /** * @brief Size constructor. Each component is evaluated from a function which * depends on the index. * * @param rs the number of rows (size) of the vector. * @param gen a pointer to the function that generates pointers to the * coefficients. */ template <class T> Vector <T> ::Vector(size_t rs, T *(*gen)(size_t)) : Matrix <T> (rs, 1, gen) {} #endif template <class T> Vector <T> ::Vector(size_t rs, T *ref, bool slice) : Matrix <T> (rs, 1, ref, slice) {} /** * @brief Copy constructor. * * @param other the reference vector (to be copied from). */ template <class T> Vector <T> ::Vector(const Vector &other) : Matrix <T> (other.size(), 1, T()) { for (size_t i = 0; i < this->_size; i++) this->_array[i] = other._array[i]; } template <class T> Vector <T> ::Vector(const Matrix <T> &other) : Matrix <T> (other.get_rows(), 1, T()) { for (size_t i = 0; i < this->_size; i++) this->_array[i] = other[0][i]; } // Assignment operators template <class T> Vector <T> &Vector <T> ::operator=(const Vector <T> &other) { if (this != &other) { this->clear(); this->_array = new T[other._size]; this->_size = other._size; for (size_t i = 0; i < this->_size; i++) this->_array[i] = other._array[i]; this->_dims = 1; this->_dim = new size_t[1]; this->_dim[0] = this->_size; } return *this; } template <class T> Vector <T> &Vector <T> ::operator=(const Matrix <T> &other) { if (this != &other) { *this = Vector(other.get_rows(), T()); for (size_t i = 0; i < this->_size; i++) this->_array[i] = other[0][i]; } return *this; } /** * Safety getter function. * * TODO: eliminate this somehow */ template <class T> inline size_t Vector <T> ::get_cols() const { return 1; } /** * @brief Indexing operator. * * @param i the specified index. * * @return the \f$i\f$th component of the vector. */ template <class T> __cuda_dual__ inline T &Vector <T> ::operator[](size_t i) { return this->_array[i]; } /** * @brief Indexing operator. * * @param i the specified index. * * @return the \f$i\f$th component of the vector. */ template <class T> __cuda_dual__ inline const T &Vector <T> ::operator[](size_t i) const { return this->_array[i]; } /** * @brief Indexing function. * * @param i the specified index. * * @return the \f$i\f$th component of the vector. */ template <class T> __cuda_dual__ inline T &Vector <T> ::get(size_t i) { return this->_array[i]; } /** * @brief Indexing function. * * @param i the specified index. * * @return the \f$i\f$th component of the vector. */ template <class T> __cuda_dual__ inline const T &Vector <T> ::get(size_t i) const { return this->_array[i]; } /** * @return the first component of the vector (index 0). */ template <class T> T &Vector <T> ::x() { if (this->_size < 1) throw index_out_of_bounds(); return this->_array[0]; } /** * @return the second component of the vector (index 1). */ template <class T> T &Vector <T> ::y() { if (this->_size < 2) throw index_out_of_bounds(); return this->_array[1]; } /** * @return the third component of the vector (index 2). */ template <class T> T &Vector <T> ::z() { if (this->_size < 3) throw index_out_of_bounds(); return this->_array[2]; } /** * @return the first component of the vector (index 0). */ template <class T> const T &Vector <T> ::x() const { if (this->_size < 1) throw index_out_of_bounds(); return this->_array[0]; } /** * @return the second component of the vector (index 1). */ template <class T> const T &Vector <T> ::y() const { if (this->_size < 2) throw index_out_of_bounds(); return this->_array[1]; } /** * @return the third component of the vector (index 2). */ template <class T> const T &Vector <T> ::z() const { if (this->_size < 3) throw index_out_of_bounds(); return this->_array[2]; } /** * @brief Returns the argument of the vector. Assumes that the vector has at * least two components. * * @return the argument of the vector in radians (the angle at which the vector * is pointing to). */ template <class T> T Vector <T> ::arg() const { return atan2(y(), x()); } /** * @brief The minimum component of the vector. * * @return the smallest component, \f$\min v_i.\f$ */ template <class T> T Vector <T> ::min() const { T mn = this->_array[0]; for (size_t j = 1; j < this->_size; j++) { if (mn > this->_array[j]) mn = this->_array[j]; } return mn; } /** * @brief The maximum component of the vector. * * @return the largest component, \f$\max v_i.\f$ */ template <class T> T Vector <T> ::max() const { T mx = this->_array[0]; for (size_t j = 1; j < this->_size; j++) { if (mx < this->_array[j]) mx = this->_array[j]; } return mx; } /** * @brief The index of the smallest component: essentially argmin. * * @return the index of the smallest component. */ template <class T> size_t Vector <T> ::imin() const { size_t i = 0; for (size_t j = 1; j < this->_size; j++) { if (this->_array[i] > this->_array[j]) i = j; } return i; } /** * @brief The index of the largest component: essentially argmax. * * @return the index of the largest component. */ template <class T> size_t Vector <T> ::imax() const { size_t i = 0; for (size_t j = 1; j < this->_size; j++) { if (this->_array[i] < this->_array[j]) i = j; } return i; } /** * @brief Normalizes the components of the vector (the modified vector will have * unit length). */ template <class T> void Vector <T> ::normalize() { T dt = this->norm(); for (size_t i = 0; i < this->_size; i++) (*this)[i] /= dt; } // TODO: rename these functions (or add): they imply modification (also add const) // TODO: use memcpy later template <class T> Vector <T> Vector <T> ::append_above(const T &x) const { T *arr = new T[this->_size + 1]; arr[0] = x; for (size_t i = 0; i < this->_size; i++) arr[i + 1] = this->_array[i]; return Vector(this->_size + 1, arr, false); } template <class T> Vector <T> Vector <T> ::append_below(const T &x) { T *arr = new T[this->_size + 1]; for (size_t i = 0; i < this->_size; i++) arr[i] = this->_array[i]; arr[this->_size] = x; return Vector(this->_size + 1, arr, false); } template <class T> Vector <T> Vector <T> ::remove_top() { T *arr = new T[this->_size - 1]; for (size_t i = 1; i < this->_size; i++) arr[i - 1] = this->_array[i]; return Vector(this->_size - 1, arr, false); } template <class T> Vector <T> Vector <T> ::remove_bottom() { T *arr = new T[this->_size - 1]; for (size_t i = 0; i < this->_size - 1; i++) arr[i] = this->_array[i]; return Vector(this->_size - 1, arr, false); } // Non-member operators template <class T> Vector <T> operator+(const Vector <T> &a, const Vector <T> &b) { Vector <T> out = a; out += b; return out; } template <class T> Vector <T> operator-(const Vector <T> &a, const Vector <T> &b) { Vector <T> out = a; out -= b; return out; } template <class T> Vector <T> operator*(const Vector <T> &a, const T &b) { Vector <T> out = a; for (size_t i = 0; i < a.size(); i++) out[i] *= b; return out; } template <class T> Vector <T> operator*(const T &b, const Vector <T> &a) { Vector <T> out = a; for (size_t i = 0; i < a.size(); i++) out[i] *= b; return out; } template <class T> Vector <T> operator/(const Vector <T> &a, const T &b) { Vector <T> out = a; for (size_t i = 0; i < a.size(); i++) out[i] /= b; return out; } template <class T> Vector <T> operator/(const T &b, const Vector <T> &a) { Vector <T> out = a; for (size_t i = 0; i < a.size(); i++) out[i] /= b; return out; } // Static methods template <class T> Vector <T> Vector <T> ::one(size_t size) { return Vector <T> (size, T(1)); } template <class T> Vector <T> Vector <T> ::rarg(double r, double theta) { return Vector <T> {r * cos(theta), r * sin(theta)}; } // Non-member functions template <class F, class T> T max(F ftn, const Vector <T> &values) { T max = ftn(values[0]); size_t n = values.size(); for (size_t i = 1; i < n; i++) { T k = ftn(values[i]); if (k > max) max = k; } return max; } template <class F, class T> T min(F ftn, const Vector <T> &values) { T min = ftn(values[0]); size_t n = values.size(); for (size_t i = 1; i < n; i++) { T k = ftn(values[i]); if (k < min) min = k; } return min; } template <class F, class T> T argmax(F ftn, const Vector <T> &values) { T max = values[0]; size_t n = values.size(); for (size_t i = 1; i < n; i++) { if (ftn(values[i]) > ftn(max)) max = values[i]; } return max; } template <class F, class T> T argmin(F ftn, const Vector <T> &values) { T min = values[0]; size_t n = values.size(); for (size_t i = 1; i < n; i++) { if (ftn(values[i]) < ftn(min)) min = values[i]; } return min; } template <class T> Vector <T> cross(const Vector <T> &a, const Vector <T> &b) { // Switch between 2 and 3 assert((a._size == 3) && (a._size == 3)); return Vector <T> { a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] }; } template <class T> Vector <T> concat(const Vector <T> &a, const Vector <T> &b) { T *arr = new T[a._dim[0] + b._dim[0]]; for (size_t i = 0; i < a.size(); i++) arr[i] = a[i]; for (size_t i = 0; i < b.size(); i++) arr[a.size() + i] = b[i]; return Vector <T> (a.size() + b.size(), arr); } template <class T, class ... U> Vector <T> concat(const Vector <T> &a, const Vector <T> &b, U ... args) { return concat(concat(a, b), args...); } template <class T> T inner(const Vector <T> &a, const Vector <T> &b) { T acc = 0; assert(a.size() == b.size()); for (size_t i = 0; i < a._size; i++) acc += a[i] * b[i]; return acc; } template <class T, class U> T inner(const Vector <T> &a, const Vector <U> &b) { T acc = 0; assert(a.size() == b.size()); for (size_t i = 0; i < a._size; i++) acc += (T) (a[i] * b[i]); // Cast the result return acc; } // Externally defined methods template <class T> Vector <T> Tensor <T> ::cast_to_vector() const { // Return a slice-vector return Vector <T> (_size, _array); } } #endif
18.447587
82
0.603409
Venkster123
b6034d816e5d5dc4609714006cc4d0016ebcfcee
4,891
cpp
C++
src/SerialPort.cpp
Nodens-LOTGA/CircuitTester
23438f49651f537c43cd78f64e61c2a5024ec8c8
[ "MIT" ]
null
null
null
src/SerialPort.cpp
Nodens-LOTGA/CircuitTester
23438f49651f537c43cd78f64e61c2a5024ec8c8
[ "MIT" ]
null
null
null
src/SerialPort.cpp
Nodens-LOTGA/CircuitTester
23438f49651f537c43cd78f64e61c2a5024ec8c8
[ "MIT" ]
null
null
null
#include "SerialPort.h" #include <QDebug> SerialPort::~SerialPort() { close(); } bool SerialPort::open(std::string portName, bool overlapped, BaudRate baud, DataBits dataBits) { if (opened) return (true); hComm = CreateFile(portName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, overlapped ? FILE_FLAG_OVERLAPPED : 0, 0); if (hComm == INVALID_HANDLE_VALUE || hComm == NULL) { qDebug() << "Failed to open serial port."; return false; } COMMTIMEOUTS timeouts{}; timeouts.ReadIntervalTimeout = overlapped ? MAXDWORD : 25; timeouts.ReadTotalTimeoutConstant = overlapped ? 0 : 1; timeouts.ReadTotalTimeoutMultiplier = overlapped ? 0 : 1; timeouts.WriteTotalTimeoutMultiplier = overlapped ? 0 : 1; timeouts.WriteTotalTimeoutConstant = 25; SetCommTimeouts(hComm, &timeouts); if (overlapped) { overlappedRead = overlappedWrite = OVERLAPPED{}; overlappedRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); overlappedWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); } DCB dcb{}; dcb.DCBlength = sizeof(dcb); GetCommState(hComm, &dcb); dcb.BaudRate = static_cast<DWORD>(baud); dcb.ByteSize = static_cast<DWORD>(dataBits); if (overlapped) { if (overlappedRead.hEvent == NULL || overlappedWrite.hEvent == NULL) { DWORD dwError = GetLastError(); if (overlappedRead.hEvent != NULL) CloseHandle(overlappedRead.hEvent); if (overlappedWrite.hEvent != NULL) CloseHandle(overlappedWrite.hEvent); CloseHandle(hComm); qDebug("Failed to setup serial port. Error: %i", dwError); return false; } } if (!SetCommState(hComm, &dcb) || !SetupComm(hComm, 1000, 1000)) { DWORD dwError = GetLastError(); CloseHandle(hComm); qDebug("Failed to setup serial port. Error: %i", dwError); return false; } else qDebug() << "Port was opened."; opened = true; this->overlapped = overlapped; this->portName = portName; this->baudRate = baud; this->dataBits = dataBits; return opened; } bool SerialPort::close() { if (!opened || hComm == NULL || hComm == INVALID_HANDLE_VALUE) return true; qDebug() << "Port was closed."; if (overlappedRead.hEvent != NULL) CloseHandle(overlappedRead.hEvent); if (overlappedWrite.hEvent != NULL) CloseHandle(overlappedWrite.hEvent); CloseHandle(hComm); opened = false; hComm = NULL; return true; } bool SerialPort::reopen() { close(); return open(portName, overlapped, baudRate, dataBits); } int SerialPort::write(const unsigned char *buffer, int size) { if (!opened || hComm == NULL || hComm == INVALID_HANDLE_VALUE) return 0; BOOL bWriteStat; DWORD dwBytesWritten; if (overlapped) { bWriteStat = WriteFile(hComm, buffer, (DWORD)size, &dwBytesWritten, &overlappedWrite); if (!bWriteStat && (GetLastError() == ERROR_IO_PENDING)) { if (WaitForSingleObject(overlappedWrite.hEvent, 1000)) dwBytesWritten = 0; else { GetOverlappedResult(hComm, &overlappedWrite, &dwBytesWritten, FALSE); overlappedWrite.Offset += dwBytesWritten; } } } else { WriteFile(hComm, buffer, (DWORD)size, &dwBytesWritten, NULL); } return (int)dwBytesWritten; } int SerialPort::read(unsigned char *buffer, int limit) { if (!opened || hComm == NULL || hComm == INVALID_HANDLE_VALUE) return 0; if (overlapped) { BOOL bReadStatus; DWORD dwBytesRead, dwErrorFlags; COMSTAT ComStat; DWORD dwEventMask; if (!SetCommMask(hComm, EV_RXCHAR)) return 0; if (!WaitCommEvent(hComm, &dwEventMask, &overlappedRead)) if (GetLastError() != ERROR_IO_PENDING) return 0; switch (WaitForSingleObject(overlappedRead.hEvent, 1000)) { case WAIT_OBJECT_0: break; default: return 0; } ClearCommError(hComm, &dwErrorFlags, &ComStat); if (!ComStat.cbInQue) return 0; dwBytesRead = (DWORD)ComStat.cbInQue; if (limit < (int)dwBytesRead) dwBytesRead = (DWORD)limit; bReadStatus = ReadFile(hComm, buffer, dwBytesRead, &dwBytesRead, &overlappedRead); if (!bReadStatus) { if (GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(overlappedRead.hEvent, 2000); return (int)dwBytesRead; } return 0; } return (int)dwBytesRead; } else { DWORD dwEventMask, dwBytesRead; int count{}; if (!SetCommMask(hComm, EV_RXCHAR)) return 0; if (WaitCommEvent(hComm, &dwEventMask, NULL)) { unsigned char szBuf; do { if (ReadFile(hComm, &szBuf, sizeof(szBuf), &dwBytesRead, NULL) != 0) { if (dwBytesRead > 0) { buffer[count++] = szBuf; } } else return 0; } while (dwBytesRead > 0 && count < limit); } return (int)count; } }
28.271676
78
0.645471
Nodens-LOTGA
b604aae12b49d34359b1ea993537d4fcfcb00837
14,347
cpp
C++
src/consensus/concord_commands_handler.cpp
jagveer-loky/concord
50d5e0d1b51f075935d868fa069c6d5e40573728
[ "Apache-2.0" ]
74
2019-09-16T11:05:10.000Z
2021-11-08T10:26:53.000Z
src/consensus/concord_commands_handler.cpp
jagveer-loky/concord
50d5e0d1b51f075935d868fa069c6d5e40573728
[ "Apache-2.0" ]
27
2019-10-15T22:08:01.000Z
2021-04-29T13:18:12.000Z
src/consensus/concord_commands_handler.cpp
jagveer-loky/concord
50d5e0d1b51f075935d868fa069c6d5e40573728
[ "Apache-2.0" ]
19
2019-09-15T08:59:45.000Z
2021-07-28T22:47:50.000Z
// Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Shim between generic KVB and Concord-specific commands handlers. #include "concord_commands_handler.hpp" #include "hash_defs.h" #include "time/time_contract.hpp" #include <opentracing/tracer.h> #include <prometheus/counter.h> #include <vector> using com::vmware::concord::ErrorResponse; using com::vmware::concord::TimeRequest; using com::vmware::concord::TimeResponse; using com::vmware::concord::TimeSample; using concordUtils::BlockId; using concordUtils::SetOfKeyValuePairs; using concordUtils::Sliver; using google::protobuf::Timestamp; namespace concord { namespace consensus { ConcordCommandsHandler::ConcordCommandsHandler( const concord::config::ConcordConfiguration &config, const concord::config::ConcordConfiguration &node_config, const concord::storage::blockchain::ILocalKeyValueStorageReadOnly &storage, concord::storage::blockchain::IBlocksAppender &appender, std::shared_ptr<concord::utils::IPrometheusRegistry> prometheus_registry) : logger_(log4cplus::Logger::getInstance( "concord.consensus.ConcordCommandsHandler")), metadata_storage_(storage), storage_(storage), command_handler_counters_{prometheus_registry->createCounterFamily( "concord_command_handler_operation_counters_total", "counts how many operations the command handler has done", {})}, written_blocks_{prometheus_registry->createCounter( command_handler_counters_, {{"layer", "ConcordCommandsHandler"}, {"operation", "written_blocks"}})}, appender_(appender) { if (concord::time::IsTimeServiceEnabled(config)) { time_ = std::unique_ptr<concord::time::TimeContract>( new concord::time::TimeContract(storage_, config)); } } int ConcordCommandsHandler::execute(uint16_t client_id, uint64_t sequence_num, uint8_t flags, uint32_t request_size, const char *request_buffer, uint32_t max_response_size, char *response_buffer, uint32_t &out_response_size) { executing_bft_sequence_num_ = sequence_num; bool read_only = flags & bftEngine::MsgFlag::READ_ONLY_FLAG; // bool pre_execute = flags & bftEngine::MsgFlag::PRE_PROCESS_FLAG; bool has_pre_executed = flags & bftEngine::MsgFlag::HAS_PRE_PROCESSED_FLAG; request_.Clear(); response_.Clear(); request_context_.reset(nullptr); auto tracer = opentracing::Tracer::Global(); std::unique_ptr<opentracing::Span> execute_span; bool result; if ((!has_pre_executed && request_.ParseFromArray(request_buffer, request_size)) || (has_pre_executed && parseFromPreExecutionResponse(request_buffer, request_size, request_))) { request_context_ = std::make_unique<ConcordRequestContext>(); request_context_->client_id = client_id; request_context_->sequence_num = sequence_num; request_context_->max_response_size = max_response_size; if (request_.has_trace_context()) { std::istringstream tc_stream(request_.trace_context()); auto trace_context = tracer->Extract(tc_stream); if (trace_context.has_value()) { execute_span = tracer->StartSpan( "execute", {opentracing::ChildOf(trace_context.value().get())}); } else { LOG4CPLUS_WARN(logger_, "Command has corrupted trace context"); execute_span = tracer->StartSpan("execute"); } } else { LOG4CPLUS_DEBUG(logger_, "Command is missing trace context"); execute_span = tracer->StartSpan("execute"); } if (time_ && request_.has_time_request() && request_.time_request().has_sample()) { if (!read_only) { auto time_update_span = tracer->StartSpan( "time_update", {opentracing::ChildOf(&execute_span->context())}); TimeRequest tr = request_.time_request(); TimeSample ts = tr.sample(); if (!(time_->SignaturesEnabled()) && ts.has_source() && ts.has_time()) { time_->Update(ts.source(), client_id, ts.time()); } else if (ts.has_source() && ts.has_time() && ts.has_signature()) { std::vector<uint8_t> signature(ts.signature().begin(), ts.signature().end()); time_->Update(ts.source(), client_id, ts.time(), &signature); } else { LOG4CPLUS_WARN( logger_, "Time Sample is missing:" << " [" << (ts.has_source() ? " " : "X") << "] source" << " [" << (ts.has_time() ? " " : "X") << "] time" << (time_->SignaturesEnabled() ? (string(" [") + (ts.has_signature() ? " " : "X") + "] signature") : "")); } } else { LOG4CPLUS_INFO(logger_, "Ignoring time sample sent in read-only command"); } } // Stashing this span in our state, so that if the subclass calls addBlock, // we can use it as the parent for the add_block span. addBlock_parent_span = tracer->StartSpan( "sub_execute", {opentracing::ChildOf(&execute_span->context())}); result = Execute(request_, flags, time_.get(), *addBlock_parent_span.get(), response_); // Manually stopping the span after execute. addBlock_parent_span.reset(); if (time_ && request_.has_time_request()) { TimeRequest tr = request_.time_request(); if (time_->Changed()) { // We had a sample that updated the time contract, and the execution of // the rest of the command did not write its state. What should we do? if (result) { if (!read_only) { // WriteEmptyBlock is going to call addBlock, and we need to tell it // what tracing span to use as its parent. addBlock_parent_span = std::move(execute_span); // The state machine might have had no commands in the request. Go // ahead and store just the time update. WriteEmptyBlock(time_.get()); // Reclaim control of the addBlock_span. execute_span = std::move(addBlock_parent_span); // Create an empty time response, so that out_response_size is not // zero. response_.mutable_time_response(); } else { // If this happens, there is a bug above. Either the logic ignoring // the update in this function is broken, or the subclass's Execute // function modified timeContract_. Log an error for us to deal // with, but otherwise ignore. LOG4CPLUS_ERROR( logger_, "Time Contract was modified during read-only operation"); ErrorResponse *err = response_.add_error_response(); err->set_description( "Ignoring time update during read-only operation"); // Also reset the time contract now, so that the modification is not // accidentally written during the next command. time_->Reset(); } } else { LOG4CPLUS_WARN(logger_, "Ignoring time update because Execute failed."); ErrorResponse *err = response_.add_error_response(); err->set_description( "Ignoring time update because state machine execution failed"); } } { // scope for time_response_span auto time_response_span = tracer->StartSpan( "time_response", {opentracing::ChildOf(&execute_span->context())}); if (tr.return_summary()) { TimeResponse *tp = response_.mutable_time_response(); Timestamp *sum = new Timestamp(time_->GetTime()); tp->set_allocated_summary(sum); } if (tr.return_samples()) { TimeResponse *tp = response_.mutable_time_response(); for (auto &s : time_->GetSamples()) { TimeSample *ts = tp->add_sample(); ts->set_source(s.first); Timestamp *t = new Timestamp(s.second.time); ts->set_allocated_time(t); if (s.second.signature) { ts->set_signature(s.second.signature->data(), s.second.signature->size()); } } } } } else if (!time_ && request_.has_time_request()) { ErrorResponse *err = response_.add_error_response(); err->set_description("Time service is disabled."); } } else { ErrorResponse *err = response_.add_error_response(); err->set_description("Unable to parse concord request"); // "true" means "resending this request is unlikely to change the outcome" result = true; } // Don't bother timing serialization of the response if we didn't successfully // parse the request. std::unique_ptr<opentracing::Span> serialize_span = execute_span == nullptr ? nullptr : tracer->StartSpan("serialize", {opentracing::ChildOf(&execute_span->context())}); if (response_.ByteSizeLong() == 0) { LOG4CPLUS_ERROR(logger_, "Request produced empty response."); ErrorResponse *err = response_.add_error_response(); err->set_description("Request produced empty response."); } if (response_.SerializeToArray(response_buffer, max_response_size)) { out_response_size = response_.GetCachedSize(); } else { size_t response_size = response_.ByteSizeLong(); LOG4CPLUS_ERROR( logger_, "Cannot send response to a client request: Response is too large " "(size of this response: " + std::to_string(response_size) + ", maximum size allowed for this response: " + std::to_string(max_response_size) + ")."); response_.Clear(); ErrorResponse *err = response_.add_error_response(); err->set_description( "Concord could not send response: Response is too large (size of this " "response: " + std::to_string(response_size) + ", maximum size allowed for this response: " + std::to_string(max_response_size) + ")."); if (response_.SerializeToArray(response_buffer, max_response_size)) { out_response_size = response_.GetCachedSize(); } else { // This case should never occur; we intend to enforce a minimum buffer // size for the communication buffer size that Concord-BFT is configured // with, and this minimum should be significantly higher than the size of // this error messsage. LOG4CPLUS_FATAL( logger_, "Cannot send error response indicating response is too large: The " "error response itself is too large (error response size: " + std::to_string(response_.ByteSizeLong()) + ", maximum size allowed for this response: " + std::to_string(max_response_size) + ")."); // This will cause the replica to halt. out_response_size = 0; } } return result ? 0 : 1; } bool ConcordCommandsHandler::HasPreExecutionConflicts( const com::vmware::concord::PreExecutionResult &pre_execution_result) const { const auto &read_set = pre_execution_result.read_set(); const auto &write_set = pre_execution_result.write_set(); const uint read_set_version = pre_execution_result.read_set_version(); const BlockId current_block_id = storage_.getLastBlock(); // pessimistically assume there is a conflict bool has_conflict = true; // check read set for conflicts for (const auto &k : read_set.keys()) { const Sliver key{std::string{k}}; storage_.mayHaveConflictBetween(key, read_set_version + 1, current_block_id, has_conflict); if (has_conflict) { return true; } } // check write set for conflicts for (const auto &kv : write_set.kv_writes()) { const auto &k = kv.key(); const Sliver key{std::string{k}}; storage_.mayHaveConflictBetween(key, read_set_version + 1, current_block_id, has_conflict); if (has_conflict) { return true; } } // the read and write set are free of conflicts return false; } bool ConcordCommandsHandler::parseFromPreExecutionResponse( const char *request_buffer, uint32_t request_size, com::vmware::concord::ConcordRequest &request) { // transform the ConcordResponse produced by pre-execution into a // ConcordRequest for seamless integration into the rest of the execution // flow com::vmware::concord::ConcordResponse pre_execution_response; if (pre_execution_response.ParseFromArray(request_buffer, request_size) && pre_execution_response.has_pre_execution_result()) { auto *pre_execution_result = request.mutable_pre_execution_result(); pre_execution_result->MergeFrom( pre_execution_response.pre_execution_result()); return true; } else { return false; } } concordUtils::Status ConcordCommandsHandler::addBlock( const concord::storage::SetOfKeyValuePairs &updates, concord::storage::blockchain::BlockId &out_block_id) { auto add_block_span = addBlock_parent_span->tracer().StartSpan( "add_block", {opentracing::ChildOf(&addBlock_parent_span->context())}); // The IBlocksAppender interface specifies that updates must be const, but we // need to add items here, so we have to make a copy and work with that. In // the future, maybe we can figure out how to either make updates non-const, // or allow addBlock to take a list of const sets. SetOfKeyValuePairs amended_updates(updates); if (time_) { if (time_->Changed()) { amended_updates.insert(time_->Serialize()); } amended_updates.insert(time_->SerializeSummarizedTime()); } amended_updates[metadata_storage_.getKey()] = metadata_storage_.serialize(executing_bft_sequence_num_); concordUtils::Status status = appender_.addBlock(amended_updates, out_block_id); if (!status.isOK()) { return status; } written_blocks_.Increment(); return status; } } // namespace consensus } // namespace concord
39.306849
80
0.643828
jagveer-loky
b60c6f9fe24da8d32dbd8e243006841eb7425cf8
15,861
cpp
C++
examples/mnist/widget.cpp
eidelen/EidNN
80999b1228eda4cab70b060bdaa6d257f8143bb1
[ "MIT" ]
3
2021-05-14T15:03:03.000Z
2021-12-05T08:31:38.000Z
examples/mnist/widget.cpp
eidelen/EidNN
80999b1228eda4cab70b060bdaa6d257f8143bb1
[ "MIT" ]
null
null
null
examples/mnist/widget.cpp
eidelen/EidNN
80999b1228eda4cab70b060bdaa6d257f8143bb1
[ "MIT" ]
3
2020-08-13T15:44:05.000Z
2021-06-07T16:16:53.000Z
#include "widget.h" #include "ui_widget.h" #include "layer.h" #include "helpers.h" #include <limits> #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" #include <QPixmap> #include <QImage> #include <QMutexLocker> #include <QStringListModel> #include <QChart> #include <QChartView> #include <QFileDialog> Widget::Widget(QWidget* parent) : QMainWindow(parent), ui(new Ui::Widget), m_sr_L2(0), m_sr_MAX(0), m_progress_training_testing(0), m_progress_learning(0), m_progress_validation(0) { ui->setupUi(this); QtCharts::QChart* trainingCostChart = new QtCharts::QChart( ); trainingCostChart->legend()->hide(); m_trainingSetCost = new QtCharts::QLineSeries( ); trainingCostChart->addSeries( m_trainingSetCost ); m_RCXAxis = new QtCharts::QValueAxis(); m_RCXAxis->setTitleText("Epoch"); m_RCXAxis->setLabelFormat("%d"); m_RCXAxis->setRange(0,1); trainingCostChart->addAxis(m_RCXAxis, Qt::AlignBottom); m_RCYAxis = new QtCharts::QValueAxis(); m_RCYAxis->setTitleText("Cost"); m_RCYAxis->setRange(0, 0.1); trainingCostChart->addAxis(m_RCYAxis, Qt::AlignLeft); m_trainingSetCost->attachAxis(m_RCXAxis); m_trainingSetCost->attachAxis(m_RCYAxis); ui->trainingerror_chart->setChart(trainingCostChart); ui->trainingerror_chart->setRenderHint(QPainter::Antialiasing); // create chart QtCharts::QChart *chart = new QtCharts::QChart( ); chart->legend()->hide(); m_plotData_classification = new QtCharts::QLineSeries( ); m_plotData_classification->append(0,0); m_trainingSuccess = new QtCharts::QLineSeries( ); m_trainingSuccess->append(0,0); chart->addSeries( m_plotData_classification ); chart->addSeries( m_trainingSuccess ); m_XAxis = new QtCharts::QValueAxis(); m_XAxis->setTitleText("Epoch"); m_XAxis->setLabelFormat("%d"); m_XAxis->setRange(0,10); chart->addAxis(m_XAxis, Qt::AlignBottom); m_YAxis = new QtCharts::QValueAxis(); m_YAxis->setTitleText("Success rate"); m_YAxis->setRange(0, 100); chart->addAxis(m_YAxis, Qt::AlignLeft); m_plotData_classification->attachAxis(m_XAxis); m_plotData_classification->attachAxis(m_YAxis); m_trainingSuccess->attachAxis(m_XAxis); m_trainingSuccess->attachAxis(m_YAxis); ui->progressChart->setChart( chart ); ui->progressChart->setRenderHint(QPainter::Antialiasing); QtCharts::QChart* testCostChart = new QtCharts::QChart( ); testCostChart->legend()->hide(); m_testSetCost = new QtCharts::QLineSeries( ); testCostChart->addSeries( m_testSetCost ); m_TCXAxis = new QtCharts::QValueAxis(); m_TCXAxis->setTitleText("Epoch"); m_TCXAxis->setLabelFormat("%d"); m_TCXAxis->setRange(0,1); testCostChart->addAxis(m_TCXAxis, Qt::AlignBottom); m_TCYAxis = new QtCharts::QValueAxis(); m_TCYAxis->setTitleText("Cost"); m_TCYAxis->setRange(0, 0.1); testCostChart->addAxis(m_TCYAxis, Qt::AlignLeft); m_testSetCost->attachAxis(m_TCXAxis); m_testSetCost->attachAxis(m_TCYAxis); ui->testerror_chart->setChart(testCostChart); ui->testerror_chart->setRenderHint(QPainter::Antialiasing); prepareSamples(); m_currentIdx = 0; displayTestMNISTImage( m_currentIdx ); connect( ui->formerSample, &QPushButton::pressed, [=]( ) { if( m_currentIdx == 0 ) m_currentIdx = m_data->getNumberOfTestSamples() - 1; else m_currentIdx--; displayTestMNISTImage( m_currentIdx ); }); connect( ui->nextSample, &QPushButton::pressed, [=]( ) { if( m_currentIdx == m_data->getNumberOfTestSamples() - 1 ) m_currentIdx = 0; else m_currentIdx++; displayTestMNISTImage( m_currentIdx ); }); connect( ui->learnPB, &QPushButton::pressed, [=]( ) { doNNLearning(); }); connect( ui->failedSampleList, &QListWidget::itemSelectionChanged, [=]( ) { int currentitem = ui->failedSampleList->currentRow(); if( currentitem >= 0 && currentitem < m_failedSamples.size() ) { size_t failedIdx = m_failedSamples.at( currentitem ); displayTestMNISTImage(failedIdx); } }); connect( ui->softmax, &QCheckBox::toggled, [=]() { m_net->setSoftmaxOutput( ui->softmax->isChecked() ); }); connect( ui->regCB, &QCheckBox::toggled, [=]() { ui->regLambdaSB->setEnabled(ui->regCB->isChecked()); setRegularizationFunction(); }); connect( ui->regLambdaSB, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), [=]() { setRegularizationFunction(); }); connect( ui->resetBtn, &QPushButton::pressed, [=]( ) { if( !m_net->isOperationInProgress() ) { m_net->resetWeights(); } }); connect( this, SIGNAL(readyForValidation()), this, SLOT(doNNValidation())); connect( this, SIGNAL(readyForTrainingTesting()), this, SLOT(doNNTesting())); connect( this, SIGNAL(readyForLearning()), this, SLOT(doNNLearning())); connect( ui->loadNNBtn, SIGNAL(pressed()), this, SLOT(loadNN())); connect( ui->saveNNBtn, SIGNAL(pressed()), this, SLOT(saveNN())); m_uiUpdaterTimer = new QTimer( this ); connect(m_uiUpdaterTimer, SIGNAL(timeout()), this, SLOT(updateUi())); m_uiUpdaterTimer->start( 100 ); } Widget::~Widget() { // Note: Since smartpointers are used, objects get deleted automatically. delete ui; delete m_data; } void Widget::prepareSamples() { m_data = new MnistDataInput(); m_batchin = DataInput::getInputData(m_data->m_training); m_batchout = DataInput::getOutputData(m_data->m_training); m_testin = DataInput::getInputData(m_data->m_test); m_testout = DataInput::getOutputData(m_data->m_test); // print lables std::cout << "Lables: " << std::endl; for( auto dl : m_data->m_lables ) { std::cout << dl.second.lable << " -> [" << dl.second.output.transpose() << "]" << std::endl; } // validate sample data DataInput::DataInputValidation div = m_data->validateData(); if( div.valid ) { // prepare network std::vector<unsigned int> map; map.push_back(div.inputDataLength); map.push_back(30); map.push_back(div.outputDataLength); m_net.reset(new Network(map)); m_net->setObserver(this); m_net_validation.reset(new Network(*(m_net.get()))); m_net_training_testing.reset(new Network(*(m_net.get()))); } else { std::cerr << "Invalid sample data" << std::endl; std::exit(-1); } } void Widget::displayTestMNISTImage( const size_t& idx ) { DataElement sample = m_data->getTestImageAsPixelValues(idx); bool repAvailable = false; Eigen::MatrixXd imgMatrix = m_data->representation(sample.input, &repAvailable); if( repAvailable ) { QImage img(imgMatrix.cols(), imgMatrix.rows(), QImage::Format_RGB32); for (int h = 0; h < imgMatrix.rows(); h++) { for (int w = 0; w < imgMatrix.cols(); w++) { uint8_t pixValue = imgMatrix(h,w); img.setPixel(w, h, qRgb(pixValue, pixValue, pixValue)); } } ui->imgLable->setPixmap(QPixmap::fromImage(img.scaled(100, 100))); ui->imgLable->show(); } ui->testlable->setText( "Lable: " + QString::number(sample.lable, 10) ); if( !m_net_validation->isOperationInProgress() ) { // feedforward m_net_validation->feedForward(m_data->m_test.at(idx).input); Eigen::MatrixXd activationSignal = m_net_validation->getOutputActivation(); QString actStr; actStr.sprintf("Activation: [ %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f]", activationSignal(0,0), activationSignal(1,0), activationSignal(2,0), activationSignal(3,0), activationSignal(4,0), activationSignal(5,0), activationSignal(6,0), activationSignal(7,0), activationSignal(8,0), activationSignal(9,0)); ui->activationLable->setText(actStr); unsigned long maxM, maxN; double maxVal; Helpers::maxElement(activationSignal, maxM, maxN, maxVal); QString classificationStr; classificationStr.sprintf("Classification: %lu", maxM); ui->classificationLable->setText( classificationStr ); } } void Widget::updateUi() { QString testingRes; testingRes.sprintf("Test result L2 = %.2f%%, MaxIdx = %.2f%%", m_sr_L2*100.0, m_sr_MAX * 100.0 ); ui->resultLable->setText(testingRes); ui->learingProgress->setValue( int(round(m_progress_learning * 100.0)) ); ui->testingTrainingProgress->setValue( int(round(m_progress_training_testing * 100.0)) ); ui->validationProgress->setValue( int(round(m_progress_validation * 100.0)) ); QMutexLocker locker( &m_uiLock ); int currentSelectedRow = ui->failedSampleList->currentRow(); ui->failedSampleList->clear(); for( size_t i : m_failedSamples ) { QString str; str.sprintf("idx = %lu", i ); ui->failedSampleList->addItem( str ); } if( currentSelectedRow >= 0 && currentSelectedRow < m_failedSamples.size() ) ui->failedSampleList->setCurrentRow(currentSelectedRow); double current_X_AxisMax = m_XAxis->max(); if( m_plotData_classification->count() >= current_X_AxisMax ) { m_XAxis->setRange(current_X_AxisMax-10,current_X_AxisMax+10); // value axis scaling min max // axis scaling : 10 values double min_Class; double max_Class; getMinMaxYValue(m_plotData_classification,4,min_Class,max_Class); double min_L2; double max_L2; getMinMaxYValue(m_trainingSuccess,4,min_L2,max_L2); double lower = std::max(std::min(min_Class,min_L2)*0.95, 0.0); double upper = std::min(std::max(max_Class,max_L2)*1.2, 100.0); m_YAxis->setRange(lower,upper); } if( m_testSetCost->count() > 0 ) { m_TCXAxis->setRange(0, m_testSetCost->count()); double min_TYVal; double max_TYVal; getMinMaxYValue(m_testSetCost, m_testSetCost->count(), min_TYVal, max_TYVal); m_TCYAxis->setRange(0, max_TYVal); } if( m_trainingSetCost->count() > 0 ) { m_RCXAxis->setRange(0, m_trainingSetCost->count()); double min_RYVal; double max_RYVal; getMinMaxYValue(m_trainingSetCost, m_trainingSetCost->count(), min_RYVal, max_RYVal); m_RCYAxis->setRange(0, max_RYVal); } ui->resetBtn->setEnabled( !m_net->isOperationInProgress()) ; } void Widget::doNNLearning() { double learningRate = ui->learingRateSB->value(); m_net->setCostFunction( getCurrentSelectedCostFunction() ); m_net->stochasticGradientDescentAsync(m_batchin, m_batchout, 10, learningRate, NETID_TRAINING ); } void Widget::doNNTesting() { m_net_training_testing->testNetworkAsync( m_batchin, m_batchout, 0.50, NETID_TRAINING_TESTING); } void Widget::doNNValidation() { m_net_validation->testNetworkAsync( m_testin, m_testout, 0.50, NETID_VALIDATION); } void Widget::networkOperationProgress( const NetworkOperationId & opId, const NetworkOperationStatus &opStatus, const double &progress, const int& userId ) { if( opId == NetworkOperationCallback::OpStochasticGradientDescent ) { m_progress_learning = progress; if( opStatus == NetworkOperationCallback::OpResultOk ) { // only overwrite if no operation ongoing on validation net if( ! m_net_validation->isOperationInProgress() ) { m_net_validation.reset( new Network( *(m_net.get())) ); emit readyForValidation(); } // only overwrite if no operation ongoing on training testing net if( ! m_net_training_testing->isOperationInProgress() ) { m_net_training_testing.reset( new Network( *(m_net.get())) ); emit readyForTrainingTesting(); } if( ui->keepLearingCB->isChecked() ) emit readyForLearning(); } } else if( opId == NetworkOperationCallback::OpTestNetwork ) { if( userId == NETID_VALIDATION ) m_progress_validation = progress; else if( userId == NETID_TRAINING_TESTING ) m_progress_training_testing = progress; } } void Widget::networkTestResults( const double& successRateEuclidean, const double& successRateMaxIdx, const double& averageCost, const std::vector<std::size_t>& failedSamplesIdx, const int& userId ) { QMutexLocker locker( &m_uiLock ); if( userId == NETID_VALIDATION ) { m_sr_L2 = successRateEuclidean; m_sr_MAX = successRateMaxIdx; m_failedSamples = failedSamplesIdx; m_plotData_classification->append(m_plotData_classification->count(), successRateMaxIdx * 100); m_testSetCost->append(m_testSetCost->count(), averageCost); std::cout << "Test success: L2 = " << m_sr_L2 * 100.0 << "%, MAX = " << m_sr_MAX * 100.0 << "%" << std::endl; std::cout << "AVG TEST COST = " << averageCost << std::endl; } else if( userId == NETID_TRAINING_TESTING ) { m_trainingSuccess->append( m_trainingSuccess->count(), successRateMaxIdx * 100); m_trainingSetCost->append( m_trainingSetCost->count(), averageCost ); std::cout << "Training success: L2 = " << successRateEuclidean*100.0 << "%, MAX = " << successRateMaxIdx * 100.0 << "%" << std::endl; std::cout << "AVG TRAINING COST = " << averageCost << std::endl; } } void Widget::loadNN() { QString path = QFileDialog::getOpenFileName(this, "Open neuronal network"); if( path.compare("") != 0 ) { m_net.reset( Network::load( path.toStdString() ) ); m_net->setObserver( this ); m_net->setCostFunction( Network::CrossEntropy ); ui->softmax->setChecked(m_net->isSoftmaxOutputEnabled()); m_net_validation.reset( new Network( *(m_net.get())) ); m_net_training_testing.reset( new Network( *(m_net.get())) ); emit readyForValidation(); emit readyForTrainingTesting(); } } void Widget::saveNN() { QString path = QFileDialog::getSaveFileName(this, "Save neuronal network"); if( path.compare("") != 0 ) m_net->save( path.toStdString() ); } Network::ECostFunction Widget::getCurrentSelectedCostFunction() { int selectedIdx = ui->costFunctionCombo->currentIndex(); if( selectedIdx == 0 ) { return Network::CrossEntropy; } else { return Network::Quadratic; } } void Widget::getMinMaxYValue(const QtCharts::QLineSeries* series, const uint& nbrEntries, double& min, double& max) { min = std::numeric_limits<double>::max(); max = std::numeric_limits<double>::min(); for( int i = series->count()-nbrEntries; i < series->count(); i++ ) { if( i >= 0 ) { if( series->at(i).y() < min ) { min = series->at(i).y(); } if( series->at(i).y() > max ) { max = series->at(i).y(); } } } } void Widget::setRegularizationFunction() { std::shared_ptr<Regularization> reg(new Regularization(Regularization::RegularizationMethod::NoneRegularization, 1)); if( ui->regCB->isChecked() ) reg.reset( new Regularization(Regularization::RegularizationMethod::WeightDecay, ui->regLambdaSB->value()) ); m_net->setRegularizationMethod(reg); std::cout << "Set regularization method: " << reg->toString() << " lambda: " << reg->m_lamda << std::endl; }
34.18319
145
0.638421
eidelen
b60d25eb5bb86b963f49ce82ecbb875f12ea1490
282
cpp
C++
sources/templates/main_variadic.cpp
zussel/cpp-overview
8a2f1ae7504ad2bb2a1ce8b284bb8a2fee448dbf
[ "MIT" ]
null
null
null
sources/templates/main_variadic.cpp
zussel/cpp-overview
8a2f1ae7504ad2bb2a1ce8b284bb8a2fee448dbf
[ "MIT" ]
null
null
null
sources/templates/main_variadic.cpp
zussel/cpp-overview
8a2f1ae7504ad2bb2a1ce8b284bb8a2fee448dbf
[ "MIT" ]
null
null
null
#include <iostream> template<typename T> T adder(T v) { return v; } template<typename T, typename... Args> T adder(T first, Args... args) { return first + adder(args...); } int main() { std::cout << "1 + 2 + 3 + 8 + 7 = " << adder(1, 2, 3, 8, 7) << "\n"; return 0; }
15.666667
72
0.542553
zussel
b60e8294133f1846ffb00d0bc1e5015955d7e28f
10,680
cpp
C++
Maple/src/Game.cpp
Bentzkast/Maple
8137dd2c91a9ee7460ca524c87bbedadee271f9e
[ "Apache-2.0" ]
null
null
null
Maple/src/Game.cpp
Bentzkast/Maple
8137dd2c91a9ee7460ca524c87bbedadee271f9e
[ "Apache-2.0" ]
null
null
null
Maple/src/Game.cpp
Bentzkast/Maple
8137dd2c91a9ee7460ca524c87bbedadee271f9e
[ "Apache-2.0" ]
null
null
null
#include "Game.h" #include "MainMenu.h" #include "Game_Internal.h" #include <stdio.h> #include <memory.h> // TODO WIN / LOSE(x) CONDITION.... // TODO SIMPLE BOSSS // TODO MAIN MENU // TODO SOUND // TODO enemy projectile... struct Player { Vec2 pos, vel, acc, half_size; float fire_rate; float timer; int hit_points; }; struct Projectile { Vec2 pos, vel, acc, half_size; }; struct Enemy { Vec2 pos, vel, acc, half_size; float fire_rate; float timer; int hit_points; }; internal Game_State active_game_state = GS_MAIN_MENU; const int PROJECTILE_CAP = 60; const int ENEMY_CAP = 60; internal float left_kill_barrier = -1000; internal float right_kill_barrier = 2000; internal Player player = { 0 }; internal Projectile projectiles_player_array[PROJECTILE_CAP] = { 0 }; internal int active_projectile_player = 0; internal Vec2 player_world_offset = { 0 }; internal Enemy enemies_array[ENEMY_CAP] = { 0 }; internal Projectile projectiles_enemy_array[PROJECTILE_CAP] = { 0 }; internal int active_projectile_enemies = 0; internal int spawned_enemy = 0; internal float enemy_wave_spawn_timer = 0; internal float enemy_wave_spawn_rate = 0; internal int enemy_wave_count = 0; void GameStart() { // Init asset MainMenuStart(); active_game_state = GS_MAIN_MENU; } void GamePlayStart() { printf("Loading Game play...."); // Initialize game play... player.pos = { 500,500 }; player.half_size = { 15,10 }; player.fire_rate = .257f; player.hit_points = 5; player_world_offset = { 0 }; memset(projectiles_player_array, 0, sizeof(projectiles_player_array[0]) * count(projectiles_player_array)); active_projectile_player = 0; memset(enemies_array, 0, sizeof(enemies_array[0]) * count(enemies_array)); memset(projectiles_enemy_array, 0, sizeof(projectiles_enemy_array[0]) * count(projectiles_enemy_array)); active_projectile_enemies = 0; spawned_enemy = 0; enemy_wave_spawn_timer = 0; enemy_wave_spawn_rate = 8.f; enemy_wave_count = 0; // Spawn A wave.... // TODO continuos spawning... EnemyWaveCreate(10); } // TODO maybe instead of seperate spawn routine..., over load this one.... void EnemyWaveCreate(int wavesize) { for (int i = 0; i < wavesize; i++) { // random spawning... enemies_array[spawned_enemy].pos.y = UtilsRandInt(20, 650); enemies_array[spawned_enemy].pos.x = UtilsRandInt(1280, 1800); enemies_array[spawned_enemy].vel.x = -UtilsRandInt(100, 200); enemies_array[spawned_enemy].half_size = Vec2{ 20,10 }; enemies_array[spawned_enemy].hit_points = 1; enemies_array[spawned_enemy].fire_rate = 0.75f; spawned_enemy++; } enemy_wave_count++; } void EnemyBossCreate(int level) { enemies_array[spawned_enemy].pos = Vec2 { 1500, 360 }; enemies_array[spawned_enemy].vel.x = -50; enemies_array[spawned_enemy].half_size = Vec2{ 70,50 }; enemies_array[spawned_enemy].hit_points = 30; enemies_array[spawned_enemy].fire_rate = 0.75f; spawned_enemy++; } Game_State GamePlaySimulate(float delta_time) { player_world_offset.x += delta_time * .5f; Vec2 screen_sector = { 0 }; RendererDrawColorSet(200, 200, 200, 255); //UtilsSeedSet(1000); for (screen_sector.y = 0; screen_sector.y < (720 / 20); screen_sector.y++) { for (screen_sector.x = 0; screen_sector.x < (1280 / 30); screen_sector.x++) { UtilsSeedSet((((uint32_t)(screen_sector.x) + (uint32_t)player_world_offset.x & 0xFFFF) << 16) | ((uint32_t)screen_sector.y + (uint32_t)player_world_offset.y & 0xFFFF)); float offset_x = player_world_offset.x - (uint32_t)player_world_offset.x; if (UtilsRandInt(0, 20) == 1) { RendererRectDraw( Vec2{ ((screen_sector.x - (player_world_offset.x - (int)player_world_offset.x)) * 30.f),// - , screen_sector.y * 20.f }, { 1, 1}); } } } // Inputs..... player.acc = { 0 }; if (InputKeyStateGet(K_LEFT) == KS_Hold) { player.acc.x = -8000; } if (InputKeyStateGet(K_RIGHT) == KS_Hold) { player.acc.x = 8000; } if (InputKeyStateGet(K_UP) == KS_Hold) { player.acc.y = -8000; } if (InputKeyStateGet(K_DOWN) == KS_Hold) { player.acc.y = 8000; } // player update.... player.acc = UtilsVecSub(player.acc, UtilsVecScale(player.vel, 10.f)); player.vel = UtilsVecAdd(player.vel, UtilsVecScale(player.acc, delta_time)); player.pos = UtilsVecAdd(UtilsVecAdd(player.pos, UtilsVecScale(player.vel, delta_time)), UtilsVecScale(player.acc, .5f * delta_time * delta_time)); // Player shootting.... if (player.timer < player.fire_rate) { player.timer += delta_time; } if (InputKeyStateGet(K_FIRE1) == KS_Hold && player.timer >= player.fire_rate) { printf("FIRE TIMER:%f\n", player.timer); // spawn new projectile from pool // FIRE routine... projectiles_player_array[active_projectile_player].pos = player.pos; projectiles_player_array[active_projectile_player].acc.x = 6000; projectiles_player_array[active_projectile_player].vel.x = 300; active_projectile_player++; player.timer = 0; } RendererDrawColorSet(239, 116, 45, 255); // ORANGE... // Enemies Enemy* active_enemy_array[20] = { 0 }; int active_enemy = 0; for (Enemy* enemy = enemies_array; enemy != (enemies_array + spawned_enemy); enemy++) { enemy->pos = UtilsVecAdd(enemy->pos, UtilsVecScale(enemy->vel, delta_time)); // In screen if (enemy->pos.x < 1280 && enemy->pos.x > 0 && enemy->hit_points > 0) { active_enemy_array[active_enemy] = enemy; active_enemy++; RendererRectDraw(enemy->pos, enemy->half_size); // shoot stuff // FIRE routine if (enemy->timer < enemy->fire_rate) { enemy->timer += delta_time; } if (enemy->timer >= enemy->fire_rate) { projectiles_enemy_array[active_projectile_enemies].acc.x = -1500; projectiles_enemy_array[active_projectile_enemies].vel.x = -100; projectiles_enemy_array[active_projectile_enemies].pos = enemy->pos; active_projectile_enemies++; enemy->timer = 0; } } } RendererDrawColorSet(200, 200, 20, 255); // YELLOW // projectile movement and draw for (int i = 0; i < active_projectile_player; i++) { projectiles_player_array[i].vel = UtilsVecAdd(projectiles_player_array[i].vel, UtilsVecScale(projectiles_player_array[i].acc, delta_time)); Vec2 desired_pos = UtilsVecAdd(projectiles_player_array[i].pos, UtilsVecScale(projectiles_player_array[i].vel, delta_time)); bool destroy_projectile = false; if (projectiles_player_array[i].pos.x > right_kill_barrier || projectiles_player_array[i].pos.x < left_kill_barrier) { destroy_projectile = true; } else { for (int e = 0; e < active_enemy; e++) { if (CollisionForceCheck(projectiles_player_array[i].pos, &desired_pos, projectiles_player_array[i].vel, Vec2{ 7.5,2.5 }, active_enemy_array[e]->pos, active_enemy_array[e]->half_size)) { destroy_projectile = true; // this could happen multiple time in this round, ie 2 enemy 1 shout.,.. // reduce enemy hit point... active_enemy_array[e]->hit_points -= 1; } } } projectiles_player_array[i].pos = desired_pos; RendererRectDraw(projectiles_player_array[i].pos, Vec2{ 7.5,2.5 }); // Last thing to do or weird teleport behaviour if (destroy_projectile) { projectiles_player_array[i] = projectiles_player_array[active_projectile_player - 1]; active_projectile_player--; projectiles_player_array[active_projectile_player] = { 0 }; } } RendererDrawColorSet(220, 20, 20, 255); // RED for (int i = 0; i < active_projectile_enemies; i++) { Projectile * projectile = projectiles_enemy_array + i; projectile->vel = UtilsVecAdd(projectile->vel, UtilsVecScale(projectile->acc, delta_time)); Vec2 desired_pos = UtilsVecAdd(projectile->pos, UtilsVecScale(projectile->vel, delta_time)); bool destroy_projectile = false; if (projectile->pos.x > right_kill_barrier || projectile->pos.x < left_kill_barrier) { destroy_projectile = true; } else { // Check collision with player... if (CollisionForceCheck(projectile->pos, &desired_pos, projectile->vel, Vec2{ 7.5,2.5 }, player.pos, player.half_size)) { destroy_projectile = true; // this could happen multiple time in this round, ie 2 enemy 1 shout.,.. // reduce player hit point... player.hit_points -= 1; } } projectile->pos = desired_pos; RendererRectDraw(projectile->pos, Vec2{ 7.5,2.5 }); // Last thing to do or weird teleport behaviour if (destroy_projectile) { projectiles_enemy_array[i] = projectiles_enemy_array[active_projectile_enemies - 1]; active_projectile_enemies--; projectiles_enemy_array[active_projectile_enemies] = { 0 }; } } // Check overlap... for( int i = 0; i < active_enemy; i++) { if (CollisionOverlapCheck(player.pos, player.half_size, active_enemy_array[i]->pos, active_enemy_array[i]->half_size)) { player.hit_points--; } } //TODO KILL & recycle enemy... for (int i = 0; i < spawned_enemy; i++) { if (enemies_array[i].hit_points <= 0 || enemies_array[i].pos.x > right_kill_barrier || enemies_array[i].pos.x < left_kill_barrier) { enemies_array[i] = enemies_array[spawned_enemy - 1]; spawned_enemy--; enemies_array[spawned_enemy] = { 0 }; } } //printf("[Deltatime] %f\n", delta_time); //printf("[LehmerRandom] %d\n", UtilsRandInt(1,10)); // TODO PERF CONSOLE... printf("[active_projectile/cap] %d / %d", active_projectile_player, PROJECTILE_CAP); printf("[active_enemy/spawned_enemy/cap] %d / %d / %d\n", active_enemy,spawned_enemy,ENEMY_CAP); RendererDrawColorSet(20, 200, 20, 255); // GREEN RendererRectDraw(player.pos, player.half_size); if(enemy_wave_spawn_timer < enemy_wave_spawn_rate) enemy_wave_spawn_timer += delta_time; if (enemy_wave_spawn_timer >= enemy_wave_spawn_rate) { EnemyWaveCreate(UtilsRandInt(5, 10)); enemy_wave_spawn_timer = 0; } if (enemy_wave_count == 3) { EnemyBossCreate(0); enemy_wave_count = 0; } // Check player dead if (player.hit_points <= 0) { return GS_MAIN_MENU; } return GS_GAMEPLAY; } void GameSimulate(float delta_time) { Game_State next_game_state = active_game_state; switch (active_game_state) { case GS_MAIN_MENU: { next_game_state = MainMenuSimulate(delta_time); } break; case GS_GAMEPLAY: { next_game_state = GamePlaySimulate(delta_time); } break; case GS_EXIT: { WindowClose(); } break; default: // TODO better logging printf("ERROR!!!! Invalid / unhandled Game state"); break; } if (active_game_state != next_game_state) { switch (next_game_state) { case GS_MAIN_MENU: { MainMenuStart(); } break; case GS_GAMEPLAY: { GamePlayStart(); } break; case GS_EXIT: { printf("Exiting next game"); } break; default: // TODO better logging printf("ERROR!!!! Invalid / unhandled Game state"); break; } } active_game_state = next_game_state; }
30.340909
189
0.712734
Bentzkast
b60f4ea2efe14b1a10c9d41c0286932807d983de
1,782
cpp
C++
examples/plugin_test.cpp
Tomasu/LuaGlue
9db477ef1447048822042164445c2f5d027b37d8
[ "Zlib" ]
36
2015-01-19T09:31:42.000Z
2021-06-16T02:52:31.000Z
examples/plugin_test.cpp
Tomasu/LuaGlue
9db477ef1447048822042164445c2f5d027b37d8
[ "Zlib" ]
3
2015-01-13T01:29:56.000Z
2017-05-25T14:55:18.000Z
examples/plugin_test.cpp
Tomasu/LuaGlue
9db477ef1447048822042164445c2f5d027b37d8
[ "Zlib" ]
5
2015-08-23T05:33:07.000Z
2017-09-21T19:36:40.000Z
#include <LuaGlue/LuaGlue.h> #ifndef _WIN32 #include <dlfcn.h> #endif #include <errno.h> #include <string.h> #include "LuaPluginBase.h" #ifdef _WIN32 #include <windows.h> #define RTLD_LAZY 0 static void *dlopen(const char *filename, int) { return (void *)LoadLibrary(filename); } static const char *dlerror(void) { static char err[2048]; DWORD lastError = GetLastError(); DWORD fmtError = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), err, sizeof(err), 0); if(!fmtError) return "unknown error"; return err; } static void *dlsym(void *handle, const char *symbol) { return (void *)GetProcAddress((HMODULE)handle, symbol); } static int dlclose(void *handle) { return !FreeLibrary((HMODULE)handle); } #endif int main(int, char **) { LuaGlue *g = nullptr; void *mod = nullptr; g = new LuaGlue; mod = dlopen("./libplugin.so", RTLD_LAZY); if(!mod) { printf("failed to load libplugin.so: %s\n", dlerror()); return -1; } auto create_fn = (LuaPluginCreateFunction)dlsym(mod, "CreatePlugin"); auto destroy_fn = (LuaPluginDestroyFunction)dlsym(mod, "DestroyPlugin"); LuaPluginBase *plugin = create_fn(g); if(!plugin) { printf("failed to create plugin\n"); dlclose(mod); delete g; return -1; } if(!plugin->bind(g)) { printf("failed to bind plugin\n"); destroy_fn(g, plugin); dlclose(mod); delete g; return -1; } g->open().glue(); g->setGlobal("plugin", (LuaPluginBase*)mod); if(!g->doFile("plugin_test.lua")) { printf("failed to run plugin_test.lua\n"); printf("err: %s\n", g->lastError().c_str()); destroy_fn(g, plugin); dlclose(mod); delete g; return -1; } destroy_fn(g, plugin); dlclose(mod); delete g; return 0; }
18.757895
168
0.682941
Tomasu
b60fc1b93deef1cc856287ed80cc8cacdb810d95
4,181
hpp
C++
utf_conv.hpp
iwongdotcn/string_utils
66ac546cdc5cb69b3504ad45ce343fb43124c763
[ "MIT" ]
1
2020-09-11T08:21:26.000Z
2020-09-11T08:21:26.000Z
utf_conv.hpp
iwongdotcn/string_utils
66ac546cdc5cb69b3504ad45ce343fb43124c763
[ "MIT" ]
null
null
null
utf_conv.hpp
iwongdotcn/string_utils
66ac546cdc5cb69b3504ad45ce343fb43124c763
[ "MIT" ]
null
null
null
#ifndef BASIC_STRING_UTILS_UTF_CONV_HPP_HEADER #define BASIC_STRING_UTILS_UTF_CONV_HPP_HEADER #ifdef _MSC_VER #pragma once #endif // _MSC_VER #include "config.hpp" #include <cstring> #include <string> #include <locale> #include <codecvt> #if defined(_WIN32) || defined(_WINDOWS) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <Windows.h> #endif NAMESPACE_BEGIN inline int locale_is_utf8() { static int ret = 2; if (ret == 2) { #if defined(_WIN32) || defined(_WINDOWS) ret = GetACP() == CP_UTF8; #else char* s; ret = 1; // assumme UTF-8 if no locale if (((s = getenv("LC_CTYPE")) && *s) || ((s = getenv("LC_ALL")) && *s) || ((s = getenv("LANG")) && *s)) { ret = (strstr(s, "utf") || strstr(s, "UTF")); } #endif } return ret; } inline std::wstring utf8_to_unicode(std::string const& str) { #ifdef _WIN32 int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0); if (len <= 0) { return std::wstring(); } std::wstring result(len, 0); len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &result[0], len); while (!result.empty() && !result.back()) result.pop_back(); return result; #else size_t src_len = str.size(); if (src_len == 0) { return std::wstring(); } std::wstring_convert<std::codecvt_utf8<wchar_t>> conv; return conv.from_bytes(str); #endif } inline std::string unicode_to_utf8(std::wstring const& str) { #ifdef _WIN32 int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, nullptr, 0, nullptr, nullptr); if (len <= 0) { return std::string(); } std::string result(len, 0); len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, &result[0], len, nullptr, nullptr); while (!result.empty() && !result.back()) result.pop_back(); return result; #else size_t src_len = str.size(); if (src_len == 0) { return std::string(); } std::wstring_convert<std::codecvt_utf8<wchar_t>> conv; return conv.to_bytes(str); #endif } inline std::wstring ansi_to_unicode(std::string const& str) { const char* source = str.c_str(); size_t source_len = str.length(); if (source_len == 0) { return std::wstring(); } size_t dest_len = 0; #if defined(_WIN32) || defined(_WINDOWS) UINT cp = ::GetACP(); dest_len = ::MultiByteToWideChar(cp, 0, source, static_cast<int>(source_len), 0, 0); #else setlocale(LC_ALL, ""); dest_len = mbstowcs(nullptr, source, source_len); #endif std::wstring dest(dest_len, L'\0'); #if defined(_WIN32) || defined(_WINDOWS) ::MultiByteToWideChar(cp, 0, source, -1, &dest[0], static_cast<int>(dest_len)); #else mbstowcs(&dest[0], source, source_len); #endif return dest; } inline std::string unicode_to_ansi(std::wstring const& str) { size_t source_len = str.size(); if (source_len <= 0) { return std::string(); } const wchar_t* source = str.c_str(); size_t dest_len = 0; #if defined(_WIN32) || defined(_WINDOWS) UINT cp = ::GetACP(); dest_len = ::WideCharToMultiByte(cp, 0, source, static_cast<int>(source_len), 0, 0, 0, 0); #else setlocale(LC_ALL, ""); dest_len = wcstombs(nullptr, source, source_len); #endif std::string dest(dest_len, '\0'); #if defined(_WIN32) || defined(_WINDOWS) ::WideCharToMultiByte(cp, 0, source, -1, &dest[0], static_cast<int>(dest_len), 0, 0); #else dest_len = wcstombs(&dest[0], source, dest_len); #endif return dest; } inline std::string utf8_to_ansi(std::string const& str) { if (!locale_is_utf8()) { std::wstring temp = utf8_to_unicode(str); std::string dest = unicode_to_ansi(temp); return dest; } else { std::string dest(str); return dest; } } inline std::string ansi_to_utf8(std::string const& str) { if (!locale_is_utf8()) { std::wstring temp = ansi_to_unicode(str); std::string dest = unicode_to_utf8(temp); return dest; } else { std::string dest(str); return dest; } } #ifdef USE_UTFCPP inline bool is_valid_utf8(std::string const& str) { return utf8::is_valid(str.begin(), str.end()); } inline bool starts_with_bom(std::string const& str) { return utf8::starts_with_bom(str.begin(), str.end()); } #endif NAMESPACE_END #endif // BASIC_STRING_UTILS_UTF_CONV_HPP_HEADER
25.035928
91
0.66563
iwongdotcn
b6100e7641bf19bb2faab2f1c7e842c7984a6623
3,666
cpp
C++
tiny-test/BinaryBufferTests.cpp
aizuon/tiny-coin
cfe1ae680bc95db855e554a12ffc3adf948b6f8b
[ "MIT" ]
1
2021-05-07T03:21:50.000Z
2021-05-07T03:21:50.000Z
tiny-test/BinaryBufferTests.cpp
aizuon/tiny-coin
cfe1ae680bc95db855e554a12ffc3adf948b6f8b
[ "MIT" ]
null
null
null
tiny-test/BinaryBufferTests.cpp
aizuon/tiny-coin
cfe1ae680bc95db855e554a12ffc3adf948b6f8b
[ "MIT" ]
null
null
null
#include "pch.hpp" #include <cstdint> #include <string> #include <vector> #include "../tiny-lib/BinaryBuffer.hpp" #include "gtest/gtest.h" TEST(BinaryBufferTest, PrimitiveReadWrite) { BinaryBuffer buffer; bool b_real = true; buffer.Write(b_real); bool b_read = false; ASSERT_TRUE(buffer.Read(b_read)); EXPECT_EQ(b_real, b_read); uint8_t u8 = 3; buffer.Write(u8); uint8_t u8_read = 0; ASSERT_TRUE(buffer.Read(u8_read)); EXPECT_EQ(u8, u8_read); int8_t i8 = -5; buffer.Write(i8); int8_t i8_read = 0; ASSERT_TRUE(buffer.Read(i8_read)); EXPECT_EQ(i8, i8_read); uint16_t u16 = 10000; buffer.Write(u16); uint16_t u16_read = 0; ASSERT_TRUE(buffer.Read(u16_read)); EXPECT_EQ(u16, u16_read); int16_t i16 = -5000; buffer.Write(i16); int16_t i16_read = 0; ASSERT_TRUE(buffer.Read(i16_read)); EXPECT_EQ(i16, i16_read); uint32_t ui32 = 7000000; buffer.Write(ui32); uint32_t ui32_read = 0; ASSERT_TRUE(buffer.Read(ui32_read)); EXPECT_EQ(ui32, ui32_read); int32_t i32 = -3000000; buffer.Write(i32); int32_t i32_read = 0; ASSERT_TRUE(buffer.Read(i32_read)); EXPECT_EQ(i32, i32_read); uint64_t ui64 = 4000000000; buffer.Write(ui64); uint64_t ui64_read = 0; ASSERT_TRUE(buffer.Read(ui64_read)); EXPECT_EQ(ui64, ui64_read); int64_t i64 = -2000000000; buffer.Write(i64); int64_t i64_read = 0; ASSERT_TRUE(buffer.Read(i64_read)); EXPECT_EQ(i64, i64_read); } TEST(BinaryBufferTest, StringReadWrite) { BinaryBuffer buffer; std::string str = "foo"; buffer.Write(str); std::string str_read; ASSERT_TRUE(buffer.Read(str_read)); EXPECT_EQ(str, str_read); } TEST(BinaryBufferTest, VectorReadWrite) { BinaryBuffer buffer; std::vector<uint8_t> u8 = {3, 5, 7, 9, 11, 55, 75}; buffer.Write(u8); std::vector<uint8_t> u8_read; ASSERT_TRUE(buffer.Read(u8_read)); EXPECT_EQ(u8, u8_read); std::vector<int8_t> i8 = {-6, -14, -32, -44, -65, -77, -99, -102}; buffer.Write(i8); std::vector<int8_t> i8_read; ASSERT_TRUE(buffer.Read(i8_read)); EXPECT_EQ(i8, i8_read); std::vector<uint16_t> u16 = {10000, 20000, 30000, 40000, 50000}; buffer.Write(u16); std::vector<uint16_t> u16_read; ASSERT_TRUE(buffer.Read(u16_read)); EXPECT_EQ(u16, u16_read); std::vector<int16_t> i16 = {-5000, -6000, -7000, -8000, -9000, -10000}; buffer.Write(i16); std::vector<int16_t> i16_read; ASSERT_TRUE(buffer.Read(i16_read)); EXPECT_EQ(i16, i16_read); std::vector<uint32_t> ui32 = {7000000, 8000000, 9000000}; buffer.Write(ui32); std::vector<uint32_t> ui32_read; ASSERT_TRUE(buffer.Read(ui32_read)); EXPECT_EQ(ui32, ui32_read); std::vector i32 = {-3000000, -4000000, -5000000}; buffer.Write(i32); std::vector<int32_t> i32_read; ASSERT_TRUE(buffer.Read(i32_read)); EXPECT_EQ(i32, i32_read); std::vector<uint64_t> ui64 = {4000000000, 5000000000, 6000000000}; buffer.Write(ui64); std::vector<uint64_t> ui64_read; ASSERT_TRUE(buffer.Read(ui64_read)); EXPECT_EQ(ui64, ui64_read); std::vector<int64_t> i64 = {-2000000000, -5000000000, -8000000000}; buffer.Write(i64); std::vector<int64_t> i64_read; ASSERT_TRUE(buffer.Read(i64_read)); EXPECT_EQ(i64, i64_read); } TEST(BinaryBufferTest, VectorConstructor) { std::vector<uint8_t> vec{2, 3, 4, 5}; BinaryBuffer buffer(vec); const uint8_t new_value = 6; vec.push_back(new_value); EXPECT_NE(vec, buffer.GetBuffer()); EXPECT_EQ(vec.size(), buffer.GetWriteOffset() + 1); buffer.Write(new_value); EXPECT_EQ(vec, buffer.GetBuffer()); } TEST(BinaryBufferTest, GrowthPolicy) { BinaryBuffer buffer; const std::string str = "foo"; buffer.Write(str); buffer.Write(str); auto& buffer_vec = buffer.GetBuffer(); EXPECT_NE(buffer_vec.size(), buffer_vec.max_size()); }
22.9125
72
0.719585
aizuon
b6146fc4aa8e95e4568155b9fb4c3b880ceb22cb
2,432
inl
C++
src/FiniteDeque/FiniteDeque/src/FiniteDeque.inl
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
3
2019-11-26T05:33:47.000Z
2020-05-18T06:49:41.000Z
src/FiniteDeque/FiniteDeque/src/FiniteDeque.inl
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
src/FiniteDeque/FiniteDeque/src/FiniteDeque.inl
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
#ifndef _FINITE_DEQUE_H__ #define _FINITE_DEQUE_H__ #include "FiniteDeque.h" template <class Type> FiniteDeque<Type>::FiniteDeque() : m_finite(0) { } template <class Type> void FiniteDeque<Type>::setFinite(size_t num, FiniteType finiteType) { m_finite = num; m_finiteType = finiteType; } template <class Type> bool FiniteDeque<Type>::push_back(const Type& element) { bool result = false; switch (m_finiteType) { case FINITE: { if (FiniteDeque<Type>::size() >= m_finite) { result = true; break; } std::deque<Type>::push_back(element); } break; case FLOW: { while (FiniteDeque<Type>::size() >= m_finite) { std::deque<Type>::pop_front(); result = true; } std::deque<Type>::push_back(element); } break; default: break; } return result; } template <class Type> bool FiniteDeque<Type>::push_front(const Type& element) { bool result = false; switch (m_finiteType) { case FINITE: { if (FiniteDeque<Type>::size() >= m_finite) { result = true; break; } std::deque<Type>::push_front(element); } break; case FLOW: { while (FiniteDeque<Type>::size() >= m_finite) { std::deque<Type>::pop_back(); result = true; } std::deque<Type>::push_front(element); } break; default: break; } return result; } template <class Type> bool FiniteDeque<Type>::emplace_back(const Type& element) { bool result = false; switch (m_finiteType) { case FINITE: { if (FiniteDeque<Type>::size() >= m_finite) { result = true; break; } std::deque<Type>::emplace_back(element); } break; case FLOW: { while (FiniteDeque<Type>::size() >= m_finite) { std::deque<Type>::pop_front(); result = true; } std::deque<Type>::emplace_back(element); } break; default: break; } return result; } template <class Type> bool FiniteDeque<Type>::emplace_front(const Type& element) { bool result = false; switch (m_finiteType) { case FINITE: { if (FiniteDeque<Type>::size() >= m_finite) { result = true; break; } std::deque<Type>::emplace_front(element); } break; case FLOW: { while (FiniteDeque<Type>::size() >= m_finite) { std::deque<Type>::pop_back(); result = true; } std::deque<Type>::emplace_front(element); } break; default: break; } return result; } #endif
16.544218
69
0.611431
xylsxyls
b61720910476b352dcf98ca52864274266f6f4dd
602
cpp
C++
2.Easy/evenOrOddNumberOfFactors.cpp
vachan-maker/Edabit-Solutions
b8598f15b981b58d42bf5220042b7e0e576bb668
[ "MIT" ]
36
2020-09-25T15:03:23.000Z
2020-10-08T14:25:53.000Z
2.Easy/evenOrOddNumberOfFactors.cpp
vachan-maker/Edabit-Solutions
b8598f15b981b58d42bf5220042b7e0e576bb668
[ "MIT" ]
212
2020-09-25T13:15:59.000Z
2020-10-12T20:35:05.000Z
2.Easy/evenOrOddNumberOfFactors.cpp
vachan-maker/Edabit-Solutions
b8598f15b981b58d42bf5220042b7e0e576bb668
[ "MIT" ]
240
2020-09-25T13:20:02.000Z
2020-10-12T04:20:47.000Z
/* Problem-Task : This function will return "even" if a number has an even number of factors and "odd" if a number has an odd number of factors. * Problem Link : https://edabit.com/challenge/zaHon4mMJJorEhBXx */ #include <iostream> using namespace std; char *factor_group(int n) { int i, c = 0; for (i = 1; i <= n; ++i) if (n % i == 0) c++; if (c % 2 == 0) return "even"; return "odd"; } int main() { cout << factor_group(33) << endl; //factor_group(33) ➞ "even" cout << factor_group(36) << endl; //factor_group(36) ➞ "odd" return 0; }
24.08
144
0.578073
vachan-maker
b61a190ffee6254de7e211a1039c5640f5564eb8
3,408
cpp
C++
Modules/ZeroMQSink/src/ZeroMQSink.cpp
slashdotted/PomaPure
c469efba9813b4b897129cff9699983c3f90b24b
[ "BSD-3-Clause" ]
2
2017-12-11T01:07:45.000Z
2021-08-21T20:57:04.000Z
Modules/ZeroMQSink/src/ZeroMQSink.cpp
slashdotted/PomaPure
c469efba9813b4b897129cff9699983c3f90b24b
[ "BSD-3-Clause" ]
null
null
null
Modules/ZeroMQSink/src/ZeroMQSink.cpp
slashdotted/PomaPure
c469efba9813b4b897129cff9699983c3f90b24b
[ "BSD-3-Clause" ]
1
2017-08-29T17:53:20.000Z
2017-08-29T17:53:20.000Z
/* * Copyright (C)2015,2016,2017 Amos Brocco ([email protected]) * Scuola Universitaria Professionale della * Svizzera Italiana (SUPSI) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Scuola Universitaria Professionale della Svizzera * Italiana (SUPSI) 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 <COPYRIGHT HOLDER> 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. */ #include "ZeroMQSink.h" DEFAULT_EXPORT_ALL(ZeroMQSink, "ZeroMQ Sink module", "", false) ZeroMQSink::ZeroMQSink(const std::string& mid) : poma::Module<ZeroMQSink, PomaDataType>(mid) {} ZeroMQSink::ZeroMQSink(const ZeroMQSink& o) : poma::Module<ZeroMQSink, PomaDataType>(o.m_module_id), m_sink_address {o.m_sink_address} { if (o.m_socket != nullptr) { initialize(); } } ZeroMQSink& ZeroMQSink::operator=(const ZeroMQSink& o) { if (m_socket != nullptr) { delete m_socket; } m_sink_address = o.m_sink_address; initialize(); return *this; } ZeroMQSink::~ZeroMQSink() { if (m_socket != nullptr) { delete m_socket; } } void ZeroMQSink::setup_cli(boost::program_options::options_description& desc) const { boost::program_options::options_description ZeroMQSink("0MQ sink options"); ZeroMQSink.add_options() ("sinkaddress", boost::program_options::value<std::string>()->default_value("tcp://localhost:7467"), "0MQ sink socket address"); desc.add(ZeroMQSink); } void ZeroMQSink::process_cli(boost::program_options::variables_map& vm) { m_sink_address = vm["sinkaddress"].as<std::string>(); } void ZeroMQSink::initialize() { m_socket = new zmq::socket_t {m_context, ZMQ_REQ}; m_socket->connect(m_sink_address.c_str()); } void ZeroMQSink::on_incoming_data(PomaPacketType& dta, const std::string& channel) { dta.m_properties.put("zeromq.channel", channel); std::string data; serialize(dta, data); s_send(*m_socket, data); std::string ack{s_recv(*m_socket)}; assert(ack == "ACK"); submit_data(dta); }
37.866667
134
0.713908
slashdotted
b61ec93041dd9c79cd9dcd68f7e4f7b83d0c00fc
2,835
cpp
C++
src/DataStructureOutput.cpp
evan1026/LLVM_middleend_template
95b375d9772fdf99c6b25ea098d25bbbafb9cbc3
[ "MIT" ]
null
null
null
src/DataStructureOutput.cpp
evan1026/LLVM_middleend_template
95b375d9772fdf99c6b25ea098d25bbbafb9cbc3
[ "MIT" ]
null
null
null
src/DataStructureOutput.cpp
evan1026/LLVM_middleend_template
95b375d9772fdf99c6b25ea098d25bbbafb9cbc3
[ "MIT" ]
null
null
null
#include "DataStructureOutput.hpp" static int indent = 0; llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const std::vector<llvm::CallInst*>& callInsts) { os << "[\n"; ++indent; for(llvm::CallInst* callInst : callInsts) { for (int i = 0; i < indent; ++i) { os << " "; } os << *callInst << ",\n"; } --indent; for (int i = 0; i < indent; ++i) { os << " "; } os << "]\n"; return os; } llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const std::unordered_set<llvm::CallInst*>& callInsts) { os << "[\n"; ++indent; for(llvm::CallInst* callInst : callInsts) { for (int i = 0; i < indent; ++i) { os << " "; } os << *callInst << ",\n"; } --indent; for (int i = 0; i < indent; ++i) { os << " "; } os << "]\n"; return os; } llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const MAP_TYPE& map) { os << "{\n"; ++indent; for (auto it = map.begin(); it != map.end(); ++it) { for (int i = 0; i < indent; ++i) { os << " "; } os << *it->first << ": " << it->second << "\n"; } --indent; for (int i = 0; i < indent; ++i) { os << " "; } os << "}\n"; return os; } void printBitVector(llvm::raw_ostream& os, const llvm::SmallBitVector& bitVector, const std::vector<llvm::Value*>& instructions) { llvm::SmallBitVector resizedBitVector = bitVector; resizedBitVector.resize(instructions.size()); for (size_t i = 0; i < instructions.size(); ++i) { if (resizedBitVector.test(i)) { os << " " << *instructions[i] << "\n"; } } } static void printHeader(llvm::raw_ostream& os, const std::string& name) { os << "***************** " << name << "\n{\n"; } static void printFooter(llvm::raw_ostream& os) { os << "}\n**************************************\n"; } void printGenKillSets(llvm::raw_ostream& os, const llvm::Value* callInst, const CatDataDependencies& dataDeps, const std::vector<llvm::Value*>& instructions) { os << "INSTRUCTION: " << *callInst << "\n"; printHeader(os, "GEN"); printBitVector(os, dataDeps.genSet, instructions); printFooter(os); printHeader(os, "KILL"); printBitVector(os, dataDeps.killSet, instructions); printFooter(os); os << "\n\n\n"; } void printInOutSets(llvm::raw_ostream& os, const llvm::Value* callInst, const CatDataDependencies& dataDeps, const std::vector<llvm::Value*>& instructions) { os << "INSTRUCTION: " << *callInst << "\n"; printHeader(os, "IN"); printBitVector(os, dataDeps.inSet, instructions); printFooter(os); printHeader(os, "OUT"); printBitVector(os, dataDeps.outSet, instructions); printFooter(os); os << "\n\n\n"; }
29.226804
159
0.536155
evan1026
b624e105a36a3a5472f30f8ae3cb23f6e6c71a25
2,056
hpp
C++
src/entity-system/factories/entities/entity-instance-builder-factory/EntityInstanceBuilderFactory.hpp
inexorgame/entity-system
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
19
2018-10-11T09:19:48.000Z
2020-04-19T16:36:58.000Z
src/entity-system/factories/entities/entity-instance-builder-factory/EntityInstanceBuilderFactory.hpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
132
2018-07-28T12:30:54.000Z
2020-04-25T23:05:33.000Z
src/entity-system/factories/entities/entity-instance-builder-factory/EntityInstanceBuilderFactory.hpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
3
2019-03-02T16:19:23.000Z
2020-02-18T05:15:29.000Z
#pragma once #include "entity-system/builders/entities/entity-instance-builder/EntityInstanceBuilder.hpp" #include "entity-system/managers/entities/entity-instance-manager/EntityInstanceManager.hpp" #include "entity-system/managers/entities/entity-type-manager/EntityTypeManager.hpp" namespace inexor::entity_system { /// These using instructions help to shorten the following code. using EntityInstanceBuilderPtr = std::shared_ptr<EntityInstanceBuilder>; using EntityInstanceManagerPtr = std::shared_ptr<EntityInstanceManager>; using EntityTypeManagerPtr = std::shared_ptr<EntityTypeManager>; /// @class EntityInstanceBuilderFactory /// @brief A factory for getting a builder for creating entity instances. /// @note For more information on the builder software pattern see /// https://en.wikipedia.org/wiki/Factory_method_pattern /// https://en.wikipedia.org/wiki/Builder_pattern class EntityInstanceBuilderFactory { public: /// @brief Constructor. /// @param entity_instance_manager A shared pointer entity instance manager. /// @param entity_type_manager A shared pointer to the entity type manager. EntityInstanceBuilderFactory(EntityInstanceManagerPtr entity_instance_manager, EntityTypeManagerPtr entity_type_manager); /// @brief Destructor. ~EntityInstanceBuilderFactory(); /// @brief Initialization of the manager. void init(); /// @brief Returns a new instance of a builder. /// @return A std::shared pointer to the entity instance builder. EntityInstanceBuilderPtr get_builder(); /// @brief Returns a new instance of a builder. /// @return A std::shared pointer to the entity instance builder. EntityInstanceBuilderPtr get_builder(const std::string &entity_type_name); private: /// The entity instance manager. EntityInstanceManagerPtr entity_instance_manager; /// The entity type manager. EntityTypeManagerPtr entity_type_manager; /// The mutex of this class. std::mutex entity_instance_builder_factory; }; } // namespace inexor::entity_system
38.792453
125
0.773346
inexorgame
b625d8c177cfe5f2aecfeb988e5372c52709bf09
7,554
hpp
C++
src/SFML/Network/UdpSocket.hpp
frc3512/Robot-2016
a3f8b6f6c9cb9f7ddddc7f05581178dc3494ae86
[ "BSD-3-Clause" ]
null
null
null
src/SFML/Network/UdpSocket.hpp
frc3512/Robot-2016
a3f8b6f6c9cb9f7ddddc7f05581178dc3494ae86
[ "BSD-3-Clause" ]
null
null
null
src/SFML/Network/UdpSocket.hpp
frc3512/Robot-2016
a3f8b6f6c9cb9f7ddddc7f05581178dc3494ae86
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2012 Laurent Gomila ([email protected]) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// /* !!! THIS IS AN EXTREMELY ALTERED AND PURPOSE-BUILT VERSION OF SFML !!! * This distribution is designed to possess only a limited subset of the * original library's functionality and to only build on VxWorks 6.3. * The original distribution of this software has many more features and * supports more platforms. */ #ifndef SFML_UDPSOCKET_HPP #define SFML_UDPSOCKET_HPP #include <vector> #include "../../SFMLNetwork/Socket.hpp" namespace sf { class IpAddress; class Packet; //////////////////////////////////////////////////////////// /// \brief Specialized socket using the UDP protocol /// //////////////////////////////////////////////////////////// class UdpSocket : public Socket { public: //////////////////////////////////////////////////////////// // Constants //////////////////////////////////////////////////////////// enum { MaxDatagramSize = 65507 ///< The maximum number of bytes that can be sent in a single UDP datagram }; //////////////////////////////////////////////////////////// /// \brief Default constructor /// //////////////////////////////////////////////////////////// UdpSocket(); //////////////////////////////////////////////////////////// /// \brief Get the port to which the socket is bound locally /// /// If the socket is not bound to a port, this function /// returns 0. /// /// \return Port to which the socket is bound /// /// \see bind /// //////////////////////////////////////////////////////////// unsigned short getLocalPort() const; //////////////////////////////////////////////////////////// /// \brief Bind the socket to a specific port /// /// Binding the socket to a port is necessary for being /// able to receive data on that port. /// You can use the special value Socket::AnyPort to tell the /// system to automatically pick an available port, and then /// call getLocalPort to retrieve the chosen port. /// /// \param port Port to bind the socket to /// /// \return Status code /// /// \see unbind, getLocalPort /// //////////////////////////////////////////////////////////// Status bind(unsigned short port); //////////////////////////////////////////////////////////// /// \brief Unbind the socket from the local port to which it is bound /// /// The port that the socket was previously using is immediately /// available after this function is called. If the /// socket is not bound to a port, this function has no effect. /// /// \see bind /// //////////////////////////////////////////////////////////// void unbind(); //////////////////////////////////////////////////////////// /// \brief Send raw data to a remote peer /// /// Make sure that \a size is not greater than /// UdpSocket::MaxDatagramSize, otherwise this function will /// fail and no data will be sent. /// /// \param data Pointer to the sequence of bytes to send /// \param size Number of bytes to send /// \param remoteAddress Address of the receiver /// \param remotePort Port of the receiver to send the data to /// /// \return Status code /// /// \see receive /// //////////////////////////////////////////////////////////// Status send(const void* data, std::size_t size, const IpAddress& remoteAddress, unsigned short remotePort); //////////////////////////////////////////////////////////// /// \brief Receive raw data from a remote peer /// /// In blocking mode, this function will wait until some /// bytes are actually received. /// Be careful to use a buffer which is large enough for /// the data that you intend to receive, if it is too small /// then an error will be returned and *all* the data will /// be lost. /// /// \param data Pointer to the array to fill with the received bytes /// \param size Maximum number of bytes that can be received /// \param received This variable is filled with the actual number of bytes received /// \param remoteAddress Address of the peer that sent the data /// \param remotePort Port of the peer that sent the data /// /// \return Status code /// /// \see send /// //////////////////////////////////////////////////////////// Status receive(void* data, std::size_t size, std::size_t& received, IpAddress& remoteAddress, unsigned short& remotePort); //////////////////////////////////////////////////////////// /// \brief Send a formatted packet of data to a remote peer /// /// Make sure that the packet size is not greater than /// UdpSocket::MaxDatagramSize, otherwise this function will /// fail and no data will be sent. /// /// \param packet Packet to send /// \param remoteAddress Address of the receiver /// \param remotePort Port of the receiver to send the data to /// /// \return Status code /// /// \see receive /// //////////////////////////////////////////////////////////// Status send(Packet& packet, const IpAddress& remoteAddress, unsigned short remotePort); //////////////////////////////////////////////////////////// /// \brief Receive a formatted packet of data from a remote peer /// /// In blocking mode, this function will wait until the whole packet /// has been received. /// /// \param packet Packet to fill with the received data /// \param remoteAddress Address of the peer that sent the data /// \param remotePort Port of the peer that sent the data /// /// \return Status code /// /// \see send /// //////////////////////////////////////////////////////////// Status receive(Packet& packet, IpAddress& remoteAddress, unsigned short& remotePort); private: //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// std::vector<char> m_buffer; ///< Temporary buffer holding the received data in Receive(Packet) }; } // namespace sf #endif // SFML_UDPSOCKET_HPP
37.211823
106
0.507678
frc3512
b627d88716f820ac3de46b722fd83f2422b71366
1,902
hpp
C++
include/codegen/include/Zenject/MemoryPoolSettings.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/MemoryPoolSettings.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/MemoryPoolSettings.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: Zenject.PoolExpandMethods #include "Zenject/PoolExpandMethods.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.MemoryPoolSettings class MemoryPoolSettings : public ::Il2CppObject { public: // public System.Int32 InitialSize // Offset: 0x10 int InitialSize; // public System.Int32 MaxSize // Offset: 0x14 int MaxSize; // public Zenject.PoolExpandMethods ExpandMethod // Offset: 0x18 Zenject::PoolExpandMethods ExpandMethod; // Get static field: static public readonly Zenject.MemoryPoolSettings Default static Zenject::MemoryPoolSettings* _get_Default(); // Set static field: static public readonly Zenject.MemoryPoolSettings Default static void _set_Default(Zenject::MemoryPoolSettings* value); // public System.Void .ctor(System.Int32 initialSize, System.Int32 maxSize, Zenject.PoolExpandMethods expandMethod) // Offset: 0xFABF5C static MemoryPoolSettings* New_ctor(int initialSize, int maxSize, Zenject::PoolExpandMethods expandMethod); // static private System.Void .cctor() // Offset: 0xFABF9C static void _cctor(); // public System.Void .ctor() // Offset: 0xFABF28 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static MemoryPoolSettings* New_ctor(); }; // Zenject.MemoryPoolSettings } DEFINE_IL2CPP_ARG_TYPE(Zenject::MemoryPoolSettings*, "Zenject", "MemoryPoolSettings"); #pragma pack(pop)
38.816327
119
0.712934
Futuremappermydud
b62a3f3b71ae94493aa8736fea27f9f64c4ad082
4,472
cpp
C++
src/plugins/opencv/sequence.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
1
2020-10-06T08:40:10.000Z
2020-10-06T08:40:10.000Z
src/plugins/opencv/sequence.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
null
null
null
src/plugins/opencv/sequence.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
null
null
null
#include "sequence.h" #include "tools.h" namespace possumwood { namespace opencv { Sequence::Sequence(std::size_t size) : m_sequence(size) { } Sequence Sequence::clone() const { Sequence result; for(auto& f : m_sequence) result.add(f->clone()); return result; } Sequence::Item& Sequence::add(const cv::Mat& frame, const Item::Meta& meta) { // check for consistency if(!m_sequence.empty()) if(frame.rows != m_sequence.front()->rows || frame.cols != m_sequence.front()->cols || frame.type() != m_sequence.front()->type()) throw std::runtime_error("Adding an inconsistent frame to a sequence!"); // TODO: more details m_sequence.push_back(Item(frame, meta)); return m_sequence.back(); } bool Sequence::isValid() const { for(auto& f : m_sequence) if(f->rows != m_sequence.front()->rows || f->cols != m_sequence.front()->cols || f->type() != m_sequence.front()->type()) return false; return true; } bool Sequence::empty() const { return m_sequence.empty(); } std::size_t Sequence::size() const { return m_sequence.size(); } int Sequence::type() const { if(m_sequence.empty()) return 0; return m_sequence.front()->type(); } int Sequence::depth() const { if(m_sequence.empty()) return 0; return m_sequence.front()->depth(); } int Sequence::channels() const { if(m_sequence.empty()) return 0; return m_sequence.front()->channels(); } int Sequence::rows() const { if(m_sequence.empty()) return 0; return m_sequence.front()->rows; } int Sequence::cols() const { if(m_sequence.empty()) return 0; return m_sequence.front()->cols; } Sequence::iterator Sequence::begin() { return m_sequence.begin(); } Sequence::iterator Sequence::end() { return m_sequence.end(); } Sequence::const_iterator Sequence::begin() const { return m_sequence.begin(); } Sequence::const_iterator Sequence::end() const { return m_sequence.end(); } const Sequence::Item& Sequence::front() const { return m_sequence.front(); } const Sequence::Item& Sequence::back() const { return m_sequence.back(); } Sequence::Item& Sequence::operator[](std::size_t index) { assert(index < m_sequence.size()); return m_sequence[index]; } const Sequence::Item& Sequence::operator[](std::size_t index) const { assert(index < m_sequence.size()); return m_sequence[index]; } bool Sequence::operator==(const Sequence& f) const { return m_sequence == f.m_sequence; } bool Sequence::operator!=(const Sequence& f) const { return m_sequence != f.m_sequence; } /////////////// Sequence::Item::Item() { } Sequence::Item::Item(const cv::Mat& m, const Meta& meta) : m_mat(m), m_meta(meta) { } Sequence::Item::Meta& Sequence::Item::meta() { return m_meta; } const Sequence::Item::Meta& Sequence::Item::meta() const { return m_meta; } bool Sequence::Item::operator==(const Item& i) const { return m_mat.ptr() == i->ptr(); } bool Sequence::Item::operator!=(const Item& i) const { return m_mat.ptr() != i->ptr(); } ///////////// bool Sequence::Item::Meta::empty() const { return m_meta.empty(); } float Sequence::Item::Meta::operator[](const std::string& key) const { auto it = m_meta.find(key); if(it != m_meta.end()) return it->second; return 0.0f; } float& Sequence::Item::Meta::operator[](const std::string& key) { return m_meta[key]; } Sequence::Item::Meta::const_iterator Sequence::Item::Meta::begin() const { return m_meta.begin(); } Sequence::Item::Meta::const_iterator Sequence::Item::Meta::end() const { return m_meta.end(); } Sequence::Item::Meta Sequence::Item::Meta::merge(const Meta& m1, const Meta& m2) { Sequence::Item::Meta result = m2; for(auto& m : m1) result[m.first] = m.second; return result; } ///////////// std::ostream& operator<<(std::ostream& out, const Sequence& seq) { if(seq.empty()) out << "Empty sequence" << std::endl; else if(seq.size() == 1) out << "A sequence with 1 frame, " << opencv::type2str((*seq[0]).type()) << ", " << (*seq[0]).cols << "x" << (*seq[0]).rows << std::endl; else out << "A sequence of " << seq.size() << " frames, " << opencv::type2str((*seq[0]).type()) << ", " << (*seq[0]).cols << "x" << (*seq[0]).rows << std::endl; unsigned ctr = 0; for(auto& f : seq) { out << " [" << ctr << "] ->"; if(f.meta().empty()) out << " no metadata" << std::endl; else { for(auto& m : f.meta()) out << " " << m.first << "=" << m.second; out << std::endl; } ++ctr; } return out; } } // namespace opencv } // namespace possumwood
21.814634
107
0.641324
LIUJUN-liujun
b6303d475cc78d399e938beb0558a1fab6ca533b
2,170
cpp
C++
dynamic/ejudge/visual_path.cpp
odanchen/cpp
1354481220a52ee9140b15bbaac6c6e8569fd93f
[ "MIT" ]
2
2021-09-28T14:03:23.000Z
2022-01-28T14:39:18.000Z
dynamic/ejudge/visual_path.cpp
odanchen/cpp
1354481220a52ee9140b15bbaac6c6e8569fd93f
[ "MIT" ]
null
null
null
dynamic/ejudge/visual_path.cpp
odanchen/cpp
1354481220a52ee9140b15bbaac6c6e8569fd93f
[ "MIT" ]
null
null
null
#include<iostream> using namespace::std; void fill_border(int size, int matrix[][252]) { int row = 0, col = 0; for (row = 0, col = 0; col <= size + 1; col++) matrix[row][col] = 2000; for (row = 0, col = size + 1; row <= size + 1; row++) matrix[row][col] = 2000; for (row = 0, col = 0; row <= size + 1; row++) matrix[row][col] = 2000; for (row = size + 1, col = 0; col <= size + 1; col++) matrix[row][col] = 2000; } void fill_matrix(int &size, int matrix[][252]) { cin >> size; fill_border(size, matrix); for (int row = 1; row <= size; row++) { string S; cin >> S; for (int col = 1; col <= size; col++) { matrix[row][col] = S[col - 1] - '0'; } } } void process_matrix(int size, int matrix[][252]) { for (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) { if (row != 1 || col != 1) { matrix[row][col] = min(matrix[row - 1][col], matrix[row][col - 1]) + matrix[row][col]; } } } } void mark_route(int size, int matrix[][252]) { int row = size, col = size; while(row != 1 || col != 1) { matrix[row][col] = '#'; if (matrix[row - 1][col] > matrix[row][col - 1]) col--; else row--; } matrix[1][1] = '#'; } void fill_visual_matrix(int size, int matrix[][252]) { for (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) { if (matrix[row][col] != '#') { matrix[row][col] = '.'; } } } } void print_matrix(int size, int matrix[][252]) { for (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) cout << (char)matrix[row][col]; cout << '\n'; } } int main() { int matrix[252][252], size; fill_matrix(size, matrix); process_matrix(size, matrix); mark_route(size, matrix); fill_visual_matrix(size, matrix); print_matrix(size, matrix); }
20.666667
102
0.45023
odanchen
ac09c0d4f8bedb90a410b981cb2dda44a3fc9f56
2,964
cpp
C++
main/mac/SslHelp.cpp
semmerson/hycast
683f10a6a8b47501ecf4f2e619e7b64c039f4f1c
[ "Apache-2.0" ]
null
null
null
main/mac/SslHelp.cpp
semmerson/hycast
683f10a6a8b47501ecf4f2e619e7b64c039f4f1c
[ "Apache-2.0" ]
12
2017-03-29T21:39:38.000Z
2017-12-07T18:09:09.000Z
main/mac/SslHelp.cpp
semmerson/hycast
683f10a6a8b47501ecf4f2e619e7b64c039f4f1c
[ "Apache-2.0" ]
2
2018-06-29T16:57:13.000Z
2020-09-28T20:03:29.000Z
/** * SSL helper functions. * * File: SslHelp.cpp * Created on: Mar 29, 2021 * Author: Steven R. Emmerson <[email protected]> * * Copyright 2021 University Corporation for Atmospheric Research * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SslHelp.h" #include <openssl/err.h> #include <openssl/rand.h> #include <cerrno> #include <fcntl.h> #include <stdexcept> #include <system_error> #include <unistd.h> namespace SslHelp { /** * Initializes the OpenSSL pseudo-random number generator (PRNG). * * @param[in] numBytes Number of bytes from "/dev/random" to initialize * the PRNG with * @throws std::system_error Couldn't open "/dev/random" * @throws std::system_error `read(2)` failure * @throws std::runtime_error `RAND_bytes()` failure */ void initRand(const int numBytes) { int fd = ::open("/dev/random", O_RDONLY); if (fd < 0) throw std::system_error(errno, std::generic_category(), "open() failure"); try { unsigned char bytes[numBytes]; for (size_t n = numBytes; n;) { auto nread = ::read(fd, bytes, n); if (nread == -1) throw std::system_error(errno, std::generic_category(), "initRand(): read() failure"); n -= nread; } if (RAND_bytes(bytes, numBytes) == 0) throw std::runtime_error("RAND_bytes() failure. " "Code=" + std::to_string(ERR_get_error())); ::close(fd); } // `fd` open catch (const std::exception& ex) { ::close(fd); throw; } } void throwExcept(CodeQ& codeQ) { if (!codeQ.empty()) { OpenSslErrCode code = codeQ.front(); codeQ.pop(); try { throwExcept(codeQ); throw std::runtime_error(ERR_reason_error_string(code)); } catch (const std::exception& ex) { std::throw_with_nested(std::runtime_error( ERR_reason_error_string(code))); } } } void throwOpenSslError(const std::string& msg) { CodeQ codeQ; for (OpenSslErrCode code = ERR_get_error(); code; code = ERR_get_error()) codeQ.push(code); try { throwExcept(codeQ); throw std::runtime_error(msg); } catch (const std::runtime_error& ex) { std::throw_with_nested(std::runtime_error(msg)); } } } // Namespace
27.192661
79
0.604926
semmerson
ac0c25ddeb48078ccc2743e4b6bf88518a064b3e
615
cpp
C++
chp1/prg_exercise1.cpp
ja8eer/C-PRIME-PLUS-6th-edi-
8682e1c5b4183a706589265a52ad89673103d8c9
[ "Apache-2.0" ]
null
null
null
chp1/prg_exercise1.cpp
ja8eer/C-PRIME-PLUS-6th-edi-
8682e1c5b4183a706589265a52ad89673103d8c9
[ "Apache-2.0" ]
null
null
null
chp1/prg_exercise1.cpp
ja8eer/C-PRIME-PLUS-6th-edi-
8682e1c5b4183a706589265a52ad89673103d8c9
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////// //Write a C++ program that displays your name// //and address (or if you value your privacy, // //a fictitious name and address). // ///////////////////////////created by jabeer/// privacy, a fictitious name and address). #include<iostream> using namespace std; int main(){ cout<<"enter you name :"; char name[20]; cin>>name; cout<<"enter your age :"; int age; cin>>age; cout<<"enter your house name :"; char house[30]; cin>>house; cout<<"your name is "<<name<<endl; cout<<"your age is "<<age<<endl; cout<<"your house name is "<<house<<endl; }
24.6
47
0.569106
ja8eer
ac0c66b546d311777d74a8920814dd819e9589fa
464
cpp
C++
LeetCode/FindSmallestLetterGreaterThanTarget.cpp
CRAZYGEEKS04/competitive-programming-1
f27b8a718761b7bfeb8ff9e294398ca1a294cb5d
[ "MIT" ]
1
2020-10-12T07:09:03.000Z
2020-10-12T07:09:03.000Z
LeetCode/FindSmallestLetterGreaterThanTarget.cpp
gauravsingh58/competitive-programming
fa5548f435cdf2aa059e1d6ab733885790c6a592
[ "MIT" ]
1
2020-10-10T16:14:54.000Z
2020-10-10T16:14:54.000Z
LeetCode/FindSmallestLetterGreaterThanTarget.cpp
gauravsingh58/competitive-programming
fa5548f435cdf2aa059e1d6ab733885790c6a592
[ "MIT" ]
null
null
null
class Solution { public: char nextGreatestLetter(vector<char>& letters, char target) { int lo = 0, hi = letters.size() - 1; if(letters[hi] <= target) return letters[0]; while(hi - lo > 1) { int mid = lo + (hi - lo) / 2; if(letters[mid] > target) hi = mid; else lo = mid; } return (letters[lo] > target ? letters[lo] : letters[hi]); } };
29
66
0.459052
CRAZYGEEKS04
ac0e7f894d80e4555b9c780c844cc817b0d3eb69
843
cpp
C++
fdistance.cpp
MrBlu1204/CPP-Programs
3fce7d86d988cef4f000a0045bd0a299018ad4f2
[ "Apache-2.0" ]
1
2020-10-31T11:16:39.000Z
2020-10-31T11:16:39.000Z
fdistance.cpp
MrBlu1204/CPP-Programs
3fce7d86d988cef4f000a0045bd0a299018ad4f2
[ "Apache-2.0" ]
null
null
null
fdistance.cpp
MrBlu1204/CPP-Programs
3fce7d86d988cef4f000a0045bd0a299018ad4f2
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; class dist { int km; int m; int cm; public: void setvalue() { cout<<"Enter km: "; cin>>km; cout<<"Enter m: "; cin>>m; cout<<"Enter cm: "; cin>>cm; } friend dist operator+(dist &, dist &); void display() { cout<<km<<"kilometers, "<<m<<"meters & "<<cm<<"centimeters\n"; } }; dist operator+(dist & a, dist & b) { dist temp; temp.km=a.km +b.km+((a.m+b.m+((a.cm+b.cm)/100))/1000); temp.m=(a.m+b.m+((a.cm+b.cm)/100))%1000; temp.cm=(a.cm+b.cm)%100; return(temp); } int main() { dist d1,d2,d3; cout<<"Enter Distance 1:\n"; d1.setvalue(); cout<<"Enter Distance 2:\n"; d2.setvalue(); d3=d1+d2; cout<<"Distance 1= "; d1.display(); cout<<"Distance 2= "; d2.display(); cout<<"Distance 3(sum of distance 1 and 2) is "; d3.display(); return 0; }
15.611111
65
0.561091
MrBlu1204
ac0f429c4a1e6ed5d47e12898a784aba48899e3f
3,457
cpp
C++
libs/libSocketHandler/src/SocketHandler.cpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
libs/libSocketHandler/src/SocketHandler.cpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
libs/libSocketHandler/src/SocketHandler.cpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
#include "SocketHandler.hpp" #include <iostream> using boost::asio::ip::tcp; void sendSocketTcp(boost::asio::ip::tcp::socket* socket_, char* data, int nbBytes, boost::system::error_code* err) { boost::asio::const_buffers_1 buff(data, nbBytes); boost::asio::write(*socket_, buff, *err); } void readSocketTcp(boost::asio::ip::tcp::socket* socket_, char* data, int nbBytes, boost::system::error_code* err) { boost::asio::mutable_buffers_1 buff(data, nbBytes); boost::asio::read(*socket_, buff, boost::asio::transfer_all(), *err); } Server::Server(int port) { m_port = port; m_initDone=false; threadInit = new std::thread(&Server::initServer, this); } void Server::initServer() { creatServerTcp(m_port); m_initDone=true; } Server::~Server() { delete m_socketTcp; } void Server::creatServerTcp(int port) { tcp::acceptor acceptor_(m_ioService, tcp::endpoint(tcp::v4(), port)); m_socketTcp=new tcp::socket(m_ioService); acceptor_.accept(*m_socketTcp); } bool Server::send(std::string& data) { if(!m_initDone) { std::cout << "Server: No connection" << std::endl; return false; } int nbBytes = data.size(); sendSocketTcp(m_socketTcp, (char*)&nbBytes, sizeof(int), &m_error); if(m_error) { std::cerr << "send failed: " << m_error.message() << std::endl; return false; } sendSocketTcp(m_socketTcp, (char*)&data[0], nbBytes, &m_error); if(m_error) { std::cerr << "send failed: " << m_error << std::endl; return false; } return true; } bool Server::receive(std::string& data) { int nbBytes=0; readSocketTcp(m_socketTcp, (char*)&nbBytes, sizeof(int), &m_error); data.resize(nbBytes); if(m_error) { std::cerr << "receive failed: " << m_error.message() << std::endl; return false; } readSocketTcp(m_socketTcp, &data[0], nbBytes, &m_error); if(m_error) { std::cerr << "receive failed: " << m_error.message() << std::endl; return false; } return true; } Client::Client(std::string& ip, int port) { m_ipServer = ip; m_port = port; creatClientTcp(m_port, m_ipServer); } Client::~Client() { delete m_socketTcp; } void Client::creatClientTcp(int port, std::string& ip) { boost::system::error_code error; m_socketTcp=new tcp::socket(m_ioService); m_socketTcp->connect( tcp::endpoint( boost::asio::ip::address::from_string(ip), port ), error); while(error) { m_socketTcp->connect( tcp::endpoint( boost::asio::ip::address::from_string(ip), port ), error); std::this_thread::sleep_for(std::chrono::milliseconds((int)(1000))); // if(error) // std::cerr << "Client connect failed: " << error.message() << std::endl; } } bool Client::send(std::string& data) { int nbBytes = data.size(); sendSocketTcp(m_socketTcp, (char*)&nbBytes, sizeof(int), &m_error); if(m_error) { std::cerr << "send failed: " << m_error.message() << std::endl; return false; } sendSocketTcp(m_socketTcp, (char*)&data[0], nbBytes, &m_error); if(m_error) { std::cerr << "send failed: " << m_error << std::endl; return false; } return true; } bool Client::receive(std::string& data) { int nbBytes=0; readSocketTcp(m_socketTcp, (char*)&nbBytes, sizeof(int), &m_error); data.resize(nbBytes); if(m_error) { std::cerr << "receive failed: " << m_error.message() << std::endl; return false; } readSocketTcp(m_socketTcp, &data[0], nbBytes, &m_error); if(m_error) { std::cerr << "receive failed: " << m_error.message() << std::endl; return false; } return true; }
18.89071
114
0.667342
maxDcb
ac1397a0911572fcaa3f4b7500815e82355ee492
2,072
cpp
C++
modules/type/complex/linalg/unit/scalar/det.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/type/complex/linalg/unit/scalar/det.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/type/complex/linalg/unit/scalar/det.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #define NT2_UNIT_MODULE "nt2 linalg toolbox - det" #include <nt2/table.hpp> #include <nt2/include/functions/det.hpp> #include <nt2/include/functions/eye.hpp> #include <nt2/include/constants/one.hpp> #include <nt2/include/constants/mone.hpp> #include <nt2/include/constants/eps.hpp> #include <nt2/include/constants/ten.hpp> #include <nt2/include/constants/oneo_10.hpp> #include <nt2/include/functions/binomial.hpp> #include <nt2/include/functions/kms.hpp> #include <nt2/include/functions/cons.hpp> #include <nt2/table.hpp> #include <nt2/sdk/unit/tests/ulp.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/complex/meta/as_complex.hpp> NT2_TEST_CASE_TPL(det, NT2_REAL_TYPES) { typedef typename nt2::meta::as_complex<T>::type cT; using nt2::det; using nt2::tag::det_; nt2::table<cT> n = nt2::eye(10, 10, nt2::meta::as_<cT>()); NT2_TEST_ULP_EQUAL(det(n), nt2::One<cT>(), 0); NT2_TEST_ULP_EQUAL(det(n+n), cT(1024), 0); n(10, 10) = cT(10); NT2_TEST_ULP_EQUAL(det(n), nt2::Ten<cT>(), 0); NT2_TEST_ULP_EQUAL(det(n+n), nt2::Ten<T>()*cT(1024), 0); n(10, 10) = cT(-1); NT2_TEST_ULP_EQUAL(det(n), nt2::Mone<cT>(), 0); NT2_TEST_ULP_EQUAL(det(n+n), cT(-1024), 0); nt2::table<cT> bi = nt2::binomial(4, nt2::meta::as_<T>()); NT2_TEST_ULP_EQUAL(det(bi), cT(64), 1); nt2::table<cT> k = nt2::kms<T>(4); NT2_TEST_ULP_EQUAL(det(k), cT(0.421875), 1); nt2::table<cT> z = nt2::cons(nt2::of_size(2, 2), cT(1, 1), cT(0, 1), cT(1, 0), cT(1, -1)); NT2_TEST_ULP_EQUAL(det(z), cT(2, -1), 1); }
40.627451
80
0.594595
psiha
ac146da0e4596b5cb2e4e1707fe9d5c588d7e5f4
1,235
cpp
C++
Sources/Post/Filters/FilterLensflare.cpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
Sources/Post/Filters/FilterLensflare.cpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
Sources/Post/Filters/FilterLensflare.cpp
dreadris/Acid
1af276edce8e6481c44d475633bf69266e16ed87
[ "MIT" ]
null
null
null
#include "FilterLensflare.hpp" #include "Scenes/Scenes.hpp" namespace acid { FilterLensflare::FilterLensflare(const Pipeline::Stage &pipelineStage) : PostFilter(pipelineStage, {"Shaders/Post/Default.vert", "Shaders/Post/Lensflare.frag"}) { } void FilterLensflare::Render(const CommandBuffer &commandBuffer) { // Updates uniforms. m_pushScene.Push("sunPosition", m_sunPosition); m_pushScene.Push("displaySize", m_pipeline.GetRenderArea().GetExtent()); m_pushScene.Push("worldHeight", m_sunHeight); // Updates descriptors. m_descriptorSet.Push("PushScene", m_pushScene); m_descriptorSet.Push("samplerMaterial", GetAttachment("samplerMaterial", "material")); PushConditional("writeColour", "samplerColour", "resolved", "diffuse"); if (!m_descriptorSet.Update(m_pipeline)) { return; } // Draws the object. m_pipeline.BindPipeline(commandBuffer); m_descriptorSet.BindDescriptor(commandBuffer, m_pipeline); m_pushScene.BindPush(commandBuffer, m_pipeline); vkCmdDraw(commandBuffer, 3, 1, 0, 0); } void FilterLensflare::SetSunPosition(const Vector3f &sunPosition) { auto camera = Scenes::Get()->GetCamera(); m_sunPosition = Matrix4::Project(sunPosition, camera->GetViewMatrix(), camera->GetProjectionMatrix()); } }
32.5
103
0.77004
dreadris
ac16cdb7393b7c760b45a1a33629464792337225
1,053
cpp
C++
cpp/211.cpp
kylekanos/project-euler-1
af7089356a4cea90f8ef331cfdc65e696def6140
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
cpp/211.cpp
kylekanos/project-euler-1
af7089356a4cea90f8ef331cfdc65e696def6140
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
cpp/211.cpp
kylekanos/project-euler-1
af7089356a4cea90f8ef331cfdc65e696def6140
[ "BSD-2-Clause-FreeBSD" ]
1
2019-09-17T00:55:58.000Z
2019-09-17T00:55:58.000Z
#include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cstdlib> #include <climits> #include <cmath> #include <bitset> #include <vector> #include <queue> #include <stack> #include <set> #include <map> #define REP(i,a) for(int i=0;i<(a);i++) #define FOR(i,a,b) for(int i=(a);i<(b);i++) #define MAX(a,b) ((a)>(b)?(a):(b)) #define MAX3(a,b,c) MAX(MAX(a,b),c) #define MAX4(a,b,c,d) MAX(MAX3(a,b,c),d) #define MIN(a,b) ((a)<(b)?(a):(b)) #define MIN3(a,b,c) MIN(MIN(a,b),c) #define MIN4(a,b,c,d) MIN(MIN3(a,b,c),d) #define SZ size() #define PB push_back using namespace std; typedef unsigned long long ull; typedef vector<ull> VE; const int N = 64000000; VE divsum(N,1); bool psquare(ull n) { ull root = round(sqrt(n)); return root*root==n; } int main() { for (ull i=2; i<N; i++) { for (int j=i; j<N; j+=i) { ull old = divsum[j]; divsum[j] += i*i; } } ull total = 0; FOR(i,1,N) if (psquare(divsum[i])) total += i; cout << total << endl; return 0; }
21.06
50
0.580247
kylekanos
ac1989b73c95b81b0bd91d6e6e093431ef887e33
3,045
cp
C++
Win32/Sources/Support/Text/CSetNumberEdit.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Win32/Sources/Support/Text/CSetNumberEdit.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Win32/Sources/Support/Text/CSetNumberEdit.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // CSetNumberEdit.cpp : implementation file // #include "CSetNumberEdit.h" ///////////////////////////////////////////////////////////////////////////// // CSetNumberEdit CSetNumberEdit::CSetNumberEdit() { } CSetNumberEdit::~CSetNumberEdit() { } BEGIN_MESSAGE_MAP(CSetNumberEdit, CNumberEdit) //{{AFX_MSG_MAP(CSetNumberEdit) ON_WM_MOVE() ON_WM_ENABLE() ON_WM_SHOWWINDOW() ON_WM_CHAR() //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CSetNumberEdit::Create(const RECT& rect, CWnd* pParentWnd, UINT nID, UINT nSpinID, bool read_only) { mVisible = false; // Do default first BOOL result = CNumberEdit::Create(rect, pParentWnd, nID, read_only); // Create spinner CRect copyRect = rect; copyRect.left = rect.right; copyRect.right = copyRect.left + 8; copyRect.top += 2; copyRect.bottom -= 2; mSpinner.Create(WS_CHILD | WS_VISIBLE | UDS_SETBUDDYINT | UDS_NOTHOUSANDS | UDS_ALIGNRIGHT, copyRect, pParentWnd, nSpinID); mSpinner.SetBuddy(this); return result; } ///////////////////////////////////////////////////////////////////////////// // CSetNumberEdit message handlers // Control moved void CSetNumberEdit::OnMove(int x, int y) { // Do default CNumberEdit::OnMove(x, y); // Adjust to move to rhs of edit control #if 0 CRect rect; GetWindowRect(rect); x += rect.Width() - 8; y -= 2; // Move spinner mSpinner.SetWindowPos(nil, x, y, 8, rect.Height() - 2, SWP_NOZORDER); #else mSpinner.SetBuddy(this); // Must hide again if (!mVisible) mSpinner.ShowWindow(SW_HIDE); #endif } // Control enabled void CSetNumberEdit::OnEnable(BOOL bEnable) { // Do default CNumberEdit::OnEnable(bEnable); // Enable spinner mSpinner.EnableWindow(bEnable); } // Control show/hide void CSetNumberEdit::OnShowWindow(BOOL bShow, UINT nStatus) { mVisible = bShow; // Do default CNumberEdit::OnShowWindow(bShow, nStatus); // Explicit show/hide spinner only if ShowWindow called for edit control (nStatus == 0) if (!nStatus) mSpinner.ShowWindow(bShow); } void CSetNumberEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if (nChar == VK_RETURN) { // Send command to parent GetParent()->SendMessage(WM_COMMAND, GetDlgCtrlID()); } else CNumberEdit::OnChar(nChar, nRepCnt, nFlags); }
24.36
125
0.656814
mulberry-mail
ac20fe6380d7bb68f1a290a43cc3092e8589b68d
285
cpp
C++
Baekjoon/14467.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/14467.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/14467.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main(void) { vector<int> arr(11, -1); int n, num, p, cnt = 0; cin >> n; while (n--) { cin >> num >> p; if (arr[num] == -1) arr[num] = p; else if (arr[num] != p) arr[num] = p, cnt++; } cout << cnt; }
14.25
25
0.512281
Twinparadox
ac260938e056f0c9ce33acde01b024231d5195c1
3,643
cc
C++
src/mlio/streams/file_input_stream.cc
babak2520/ml-io
87bedf9537959260723ed0419a0803c76e015ef5
[ "Apache-2.0" ]
69
2019-10-14T18:55:50.000Z
2022-02-28T05:50:39.000Z
src/mlio/streams/file_input_stream.cc
cbalioglu/ml-io
d79a895c3fe5e10f0f832cfdcee5a73058abb7c7
[ "Apache-2.0" ]
18
2019-11-16T12:45:40.000Z
2022-01-29T03:47:52.000Z
src/mlio/streams/file_input_stream.cc
cbalioglu/ml-io
d79a895c3fe5e10f0f832cfdcee5a73058abb7c7
[ "Apache-2.0" ]
16
2019-10-24T22:35:51.000Z
2021-09-03T18:23:04.000Z
/* * Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ #include "mlio/streams/file_input_stream.h" // IWYU pragma: associated #include <algorithm> #include <system_error> #include <utility> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include "mlio/detail/error.h" #include "mlio/detail/path.h" #include "mlio/logger.h" #include "mlio/streams/stream_error.h" using mlio::detail::current_error_code; namespace mlio { inline namespace abi_v1 { File_input_stream::File_input_stream(std::string path) : path_{std::move(path)} { detail::validate_file_path(path_); fd_ = ::open(path_.c_str(), O_RDONLY | O_CLOEXEC); if (fd_ == -1) { throw std::system_error{current_error_code(), "The file cannot be opened."}; } #ifdef MLIO_PLATFORM_LINUX int r = ::posix_fadvise(fd_.get(), 0, 0, POSIX_FADV_SEQUENTIAL); if (r != 0) { logger::warn("The read-ahead size of the file '{0}' cannot be increased.", path_); } #endif } std::size_t File_input_stream::read(Mutable_memory_span destination) { check_if_closed(); if (destination.empty()) { return 0; } ssize_t num_bytes_read = ::read(fd_.get(), destination.data(), destination.size()); if (num_bytes_read == -1) { throw std::system_error{current_error_code(), "The file cannot be read."}; } return static_cast<std::size_t>(num_bytes_read); } void File_input_stream::seek(std::size_t position) { check_if_closed(); auto offset = static_cast<::off_t>(std::min(position, size())); ::off_t o = ::lseek(fd_.get(), offset, SEEK_SET); if (o == -1) { std::error_code err = current_error_code(); const char *msg{}; if (err == std::errc::invalid_seek) { msg = "The file is not seekable."; } else { msg = "The position in the file cannot be set."; } throw std::system_error{err, msg}; } } void File_input_stream::close() noexcept { fd_ = {}; } std::size_t File_input_stream::size() const { check_if_closed(); if (size_ == 0) { struct ::stat buf = {}; if (::fstat(fd_.get(), &buf) == -1) { throw std::system_error{current_error_code(), "The size of the file cannot be retrieved."}; } size_ = static_cast<std::size_t>(buf.st_size); } return size_; } std::size_t File_input_stream::position() const { check_if_closed(); ::off_t o = ::lseek(fd_.get(), 0, SEEK_CUR); if (o == -1) { std::error_code err = current_error_code(); const char *msg{}; if (err == std::errc::invalid_seek) { msg = "The file is not seekable."; } else { msg = "The position in the file cannot be retrieved."; } throw std::system_error{err, msg}; } return static_cast<std::size_t>(o); } void File_input_stream::check_if_closed() const { if (fd_.is_open()) { return; } throw Stream_error{"The input stream is closed."}; } } // namespace abi_v1 } // namespace mlio
25.475524
90
0.624485
babak2520
ac2691ec4348b79ddd634ec380ba89adc1d216a8
2,256
cpp
C++
algorithmforcpp/backtracking/rat_maze.cpp
ilvcr/cpplgproject
d3dc492b37c3754e35669eee2dd96d83de63ead4
[ "Apache-2.0" ]
null
null
null
algorithmforcpp/backtracking/rat_maze.cpp
ilvcr/cpplgproject
d3dc492b37c3754e35669eee2dd96d83de63ead4
[ "Apache-2.0" ]
null
null
null
algorithmforcpp/backtracking/rat_maze.cpp
ilvcr/cpplgproject
d3dc492b37c3754e35669eee2dd96d83de63ead4
[ "Apache-2.0" ]
null
null
null
/************************************************************************* > File Name: rat_maze.cpp > Author: yoghourt->ilvcr > Mail: [email protected] @@ [email protected] > Created Time: 2018年07月18日 星期三 14时24分11秒 > Description: A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down. In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination. ************************************************************************/ #include<iostream> using namespace std; #define size 4 int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size]){ if((currposrow == size-1) && (currposcol == size)){ soln[currposrow][currposcol] = 1; for(int i=0; i < size; ++i){ for(int j=0; j < size; ++j){ cout << soln[i][j]; } cout << endl; } return 1; } else{ soln[currposrow][currposcol] = 1; /*if there exist a solution by moving one step ahead in a collumn*/ if((currposcol<size-1) && maze[currposrow][currposcol+1]==1 && solveMaze(currposrow,currposcol+1,maze,soln)){ return 1; } /*// if there exists a solution by moving one step ahead in a row*/ if((currposrow<size-1) && maze[currposrow+1][currposcol]==1 && solveMaze(currposrow+1,currposcol,maze,soln)){ return 1; } /*the backtracking part*/ soln[currposrow][currposcol] = 0; return 0; } } int main(argc, char* argv[]){ int maze[size][size]={ {1,0,1,0}, {1,0,1,1}, {1,0,0,1}, {1,1,1,1} }; int soln[size][size]; for(int i=0; i < size; ++i){ for(int j=0; j < size; ++j){ soln[i][j] = 0; } } int currposrow = 0; int currposcol = 0; solveMaze(currposrow, currposcol, maze, soln); return 0; }
26.541176
86
0.525709
ilvcr
ac29df4cd00fcd043e9a7b30349bfc560a33b0df
2,787
cpp
C++
app/src/main/cpp/mixing/MixingIO.cpp
atikur-rabbi/fast-mixer
7b471e102aacb9cdf75af5c7775d18d10e584ff1
[ "CC0-1.0" ]
47
2020-07-16T21:21:37.000Z
2022-03-02T00:18:00.000Z
app/src/main/cpp/mixing/MixingIO.cpp
iftenet/fast-mixer
9e834d6ebed0b1dd63fe8688f8bf614e19a8467f
[ "CC0-1.0" ]
1
2020-09-29T06:48:22.000Z
2020-10-10T17:40:50.000Z
app/src/main/cpp/mixing/MixingIO.cpp
iftenet/fast-mixer
9e834d6ebed0b1dd63fe8688f8bf614e19a8467f
[ "CC0-1.0" ]
10
2020-07-19T10:07:21.000Z
2022-02-11T07:03:20.000Z
// // Created by asalehin on 9/9/20. // #include "MixingIO.h" #include "../utils/Utils.h" MixingIO::MixingIO() { Player* player = new Player(); mPlayer.reset(move(player)); } shared_ptr<FileDataSource> MixingIO::readFile(string filename, int fd) { AudioProperties targetProperties{ .channelCount = MixingStreamConstants::mChannelCount, .sampleRate = MixingStreamConstants::mSampleRate }; return shared_ptr<FileDataSource> { FileDataSource::newFromCompressedFile(filename.c_str(), fd, targetProperties), [](FileDataSource *source) { delete source; } }; } shared_ptr<BufferedDataSource> MixingIO::createClipboardDataSource(vector<float>& clipboard) { AudioProperties targetProperties{ .channelCount = MixingStreamConstants::mChannelCount, .sampleRate = MixingStreamConstants::mSampleRate }; return shared_ptr<BufferedDataSource> { BufferedDataSource::newFromClipboard(clipboard, targetProperties), [](BufferedDataSource *source) { delete source; } }; } void MixingIO::setPlaying(bool isPlaying) { mPlayer->setPlaying(isPlaying); } void MixingIO::clearPlayerSources() { mPlayer->resetPlayHead(); mPlayer->clearSources(); } void MixingIO::addSource(string key, shared_ptr<DataSource> source) { mPlayer->addSource(key, source); syncPlayHeads(); } void MixingIO::addSourceMap(map<string, shared_ptr<DataSource>> playMap) { mPlayer->addSourceMap(playMap); syncPlayHeads(); } bool MixingIO::writeSourcesToFile(map<string, shared_ptr<DataSource>> playMap, int fd) { MixedAudioWriter mixedAudioWriter(playMap); return mixedAudioWriter.writeToFile(fd); } void MixingIO::syncPlayHeads() { mPlayer->syncPlayHeads(); } void MixingIO::read_playback(float *targetData, int32_t numSamples) { mPlayer->renderAudio(targetData, numSamples); } void MixingIO::setStopPlaybackCallback(function<void()> stopPlaybackCallback) { mStopPlaybackCallback = stopPlaybackCallback; mPlayer->setPlaybackCallback(stopPlaybackCallback); } int MixingIO::getTotalSampleFrames() { if (mPlayer) { return mPlayer->getTotalSampleFrames(); } return 0; } int MixingIO::getCurrentPlaybackProgress() { return mPlayer->getPlayHead(); } void MixingIO::setPlayHead(int position) { mPlayer->setPlayHead(position); } void MixingIO::setPlayerBoundStart(int64_t boundStart) { mPlayer->setPlayerBoundStart(boundStart); } void MixingIO::setPlayerBoundEnd(int64_t boundEnd) { mPlayer->setPlayerBoundEnd(boundEnd); } void MixingIO::resetPlayerBoundStart() { mPlayer->resetPlayerBoundStart(); } void MixingIO::resetPlayerBoundEnd() { mPlayer->resetPlayerBoundEnd(); }
25.805556
94
0.714747
atikur-rabbi
ac2aeb03bd5834c7947e636aee57ef97b5e4d8ba
5,340
cpp
C++
src/plugins/firebase/util.cpp
bmcbarron/flutter-pi
8a6796c813aea282c6d40bebb9d1f7641bf1dc45
[ "MIT" ]
null
null
null
src/plugins/firebase/util.cpp
bmcbarron/flutter-pi
8a6796c813aea282c6d40bebb9d1f7641bf1dc45
[ "MIT" ]
null
null
null
src/plugins/firebase/util.cpp
bmcbarron/flutter-pi
8a6796c813aea282c6d40bebb9d1f7641bf1dc45
[ "MIT" ]
null
null
null
#include "util.h" #include <inttypes.h> #include <sys/syscall.h> #include <unistd.h> #include <cassert> long gettid() { return syscall(SYS_gettid); } #define INDENT_STRING " " int __stdPrint(std_value *value, int indent) { switch (value->type) { case kStdPreEncoded: fprintf(stderr, "encoded(type=%d,size=%d)", value->uint8array[0], value->size); break; case kStdNull: fprintf(stderr, "null"); break; case kStdTrue: fprintf(stderr, "true"); break; case kStdFalse: fprintf(stderr, "false"); break; case kStdInt32: fprintf(stderr, "%" PRIi32, value->int32_value); break; case kStdInt64: fprintf(stderr, "%" PRIi64, value->int64_value); break; case kStdFloat64: fprintf(stderr, "%lf", value->float64_value); break; case kStdString: case kStdLargeInt: fprintf(stderr, "\"%s\"", value->string_value); break; case kStdUInt8Array: fprintf(stderr, "(uint8_t) ["); for (int i = 0; i < value->size; i++) { fprintf(stderr, "0x%02X", value->uint8array[i]); if (i + 1 != value->size) fprintf(stderr, ", "); } fprintf(stderr, "]"); break; case kStdInt32Array: fprintf(stderr, "(int32_t) ["); for (int i = 0; i < value->size; i++) { fprintf(stderr, "%" PRIi32, value->int32array[i]); if (i + 1 != value->size) fprintf(stderr, ", "); } fprintf(stderr, "]"); break; case kStdInt64Array: fprintf(stderr, "(int64_t) ["); for (int i = 0; i < value->size; i++) { fprintf(stderr, "%" PRIi64, value->int64array[i]); if (i + 1 != value->size) fprintf(stderr, ", "); } fprintf(stderr, "]"); break; case kStdFloat64Array: fprintf(stderr, "(double) ["); for (int i = 0; i < value->size; i++) { fprintf(stderr, "%f", value->float64array[i]); if (i + 1 != value->size) fprintf(stderr, ", "); } fprintf(stderr, "]"); break; case kStdList: if (value->size == 0) { fprintf(stderr, "[]"); } else { fprintf(stderr, "[\n"); for (int i = 0; i < value->size; i++) { fprintf(stderr, "%.*s", indent + 2, INDENT_STRING); __stdPrint(&(value->list[i]), indent + 2); if (i + 1 != value->size) fprintf(stderr, ",\n"); } fprintf(stderr, "\n%.*s]", indent, INDENT_STRING); } break; case kStdMap: if (value->size == 0) { fprintf(stderr, "{}"); } else { fprintf(stderr, "{\n"); for (int i = 0; i < value->size; i++) { fprintf(stderr, "%.*s", indent + 2, INDENT_STRING); __stdPrint(&(value->keys[i]), indent + 2); fprintf(stderr, ": "); __stdPrint(&(value->values[i]), indent + 2); if (i + 1 != value->size) fprintf(stderr, ",\n"); } fprintf(stderr, "\n%.*s}", indent, INDENT_STRING); } break; default: break; } return 0; } int stdPrint(std_value *value, int indent) { fprintf(stderr, "%.*s", indent, INDENT_STRING); __stdPrint(value, indent); fprintf(stderr, "\n"); return 0; } namespace firebase { using ::val; std::unique_ptr<Value> val(const Variant &value) { switch (value.type()) { case Variant::Type::kTypeNull: return val(); case Variant::Type::kTypeInt64: return val(value.int64_value()); case Variant::Type::kTypeDouble: return val(value.double_value()); case Variant::Type::kTypeBool: return val(value.bool_value()); case Variant::Type::kTypeStaticString: return val(value.string_value()); case Variant::Type::kTypeMutableString: return val(value.string_value()); case Variant::Type::kTypeVector: { auto result = std::make_unique<ValueList>(); for (auto const &v : value.vector()) { result->add(val(v)); } return result; } case Variant::Type::kTypeMap: { auto result = std::make_unique<ValueMap>(); for (auto const &[k, v] : value.map()) { result->add(val(k), val(v)); // auto vk = val(k); // auto vv = val(v); // result->add(vk, vv); } return result; } } fprintf(stderr, "Error converting Variant type: %d\n", value.type()); return val(); } } // namespace firebase std::optional<firebase::Variant> as_variant(std_value *value) { switch (value->type) { case kStdNull: return firebase::Variant::Null(); case kStdInt32: return firebase::Variant::FromInt64(value->int32_value); case kStdInt64: return firebase::Variant::FromInt64(value->int64_value); case kStdFloat64: return firebase::Variant::FromDouble(value->float64_value); case kStdTrue: return firebase::Variant::True(); case kStdFalse: return firebase::Variant::False(); case kStdString: return firebase::Variant::MutableStringFromStaticString(value->string_value); case kStdMap: { auto result = firebase::Variant::EmptyMap(); for (int i = 0; i < value->size; ++i) { auto k = as_variant(&(value->keys[i])); auto v = as_variant(&(value->values[i])); assert(k && v); result.map()[*k] = *v; } return result; } } return std::nullopt; } std::optional<firebase::Variant> get_variant(std_value *args, char *key) { auto result = stdmap_get_str(args, key); if (result == nullptr) { return std::nullopt; } return as_variant(result); }
27.106599
83
0.588202
bmcbarron
ac3a57e78215357414f45e0fff0f3ca171d38dbc
1,460
hpp
C++
src/single_thread_rlnc_benchmark/benchmark/write_result.hpp
AgileCloudLab/single-threaded-rlnc-benchmark
914c18cf408d62f7294f796f386e98740d6fc83d
[ "MIT" ]
null
null
null
src/single_thread_rlnc_benchmark/benchmark/write_result.hpp
AgileCloudLab/single-threaded-rlnc-benchmark
914c18cf408d62f7294f796f386e98740d6fc83d
[ "MIT" ]
null
null
null
src/single_thread_rlnc_benchmark/benchmark/write_result.hpp
AgileCloudLab/single-threaded-rlnc-benchmark
914c18cf408d62f7294f796f386e98740d6fc83d
[ "MIT" ]
null
null
null
#pragma once #include "result.hpp" #include "../readers/config.hpp" #include <string> #include <sstream> #include <ctime> #include <iostream> #include <fstream> namespace standard_encoder { namespace benchmark { std::string generate_path(std::string result_path, std::string experiment_name, readers::config& config) { std::time_t t = std::time(nullptr); auto timestamp = static_cast<uint64_t>(t); std::stringstream ss; ss << result_path << "/" << timestamp << "_" << experiment_name << "_" << config.threads() << "_" << config.generation_size() << "_" << config.symbol_size(); // Cast the content of ss to a string return ss.str(); } std::string convert_to_json_array(std::vector<result> results) { std::stringstream stream; stream << "[" << std::endl; for (uint32_t i = 0; i < results.size(); ++i) { stream << results.at(i).to_json_string(); if (i != results.size() - 1) { stream << ","; } stream << std::endl; } stream << "]"; return stream.str(); } bool write_results(std::string file_path, std::vector<result> results) { std::ofstream result_file; result_file.open(file_path); result_file << convert_to_json_array(results); result_file.close(); return true; } } }
23.934426
108
0.557534
AgileCloudLab
ac3b15e8ee1531880f947fabf73ac11f76d28d6f
1,204
cpp
C++
contests/leetcode-133/b.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
23
2020-03-30T05:44:56.000Z
2021-09-04T16:00:57.000Z
contests/leetcode-133/b.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
1
2020-05-10T15:04:05.000Z
2020-06-14T01:21:44.000Z
contests/leetcode-133/b.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
6
2020-03-30T05:45:04.000Z
2020-08-13T10:01:39.000Z
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } class Solution { public: vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) { auto c = [r0, c0](pair<int, int> &pp1, pair<int, int> &pp2) -> bool{ int d1 = abs(pp1.first - r0) + abs(pp1.second - c0); int d2 = abs(pp2.first - r0) + abs(pp2.second - c0); return d1 < d2; }; vector<pair<int, int> > vec; for (int i = 0; i < R; ++i) for (int j = 0; j < C; ++j) vec.push_back(make_pair(i, j)); sort(vec.begin(), vec.end(), c); vector<vector<int> > ans; for (int i = 1; i < R * C; ++i){ vector<int> aa; aa.push_back(vec[i].first); aa.push_back(vec[i].second); ans.push_back(aa); } return ans; } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
25.617021
76
0.480897
Nightwish-cn
ac3cbec66042da19af26e2c3beb4897c0af24b74
34,855
cpp
C++
Core/burn/drv/galaxian/gal_gfx.cpp
atship/FinalBurn-X
3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d
[ "Apache-2.0" ]
17
2018-05-24T05:20:45.000Z
2021-12-24T07:27:22.000Z
Core/burn/drv/galaxian/gal_gfx.cpp
atship/FinalBurn-X
3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d
[ "Apache-2.0" ]
6
2019-01-21T10:55:02.000Z
2021-02-19T18:47:56.000Z
Core/burn/drv/galaxian/gal_gfx.cpp
atship/FinalBurn-X
3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d
[ "Apache-2.0" ]
5
2019-01-21T00:45:00.000Z
2021-07-20T08:34:22.000Z
#include "gal.h" GalRenderBackground GalRenderBackgroundFunction; GalCalcPalette GalCalcPaletteFunction; GalDrawBullet GalDrawBulletsFunction; GalExtendTileInfo GalExtendTileInfoFunction; GalExtendSpriteInfo GalExtendSpriteInfoFunction; GalRenderFrame GalRenderFrameFunction; UINT8 GalFlipScreenX; UINT8 GalFlipScreenY; UINT8 *GalGfxBank; UINT8 GalPaletteBank; UINT8 GalSpriteClipStart; UINT8 GalSpriteClipEnd; UINT8 FroggerAdjust; UINT8 GalBackgroundRed; UINT8 GalBackgroundGreen; UINT8 GalBackgroundBlue; UINT8 GalBackgroundEnable; UINT8 SfxTilemap; UINT8 GalOrientationFlipX; UINT8 GalColourDepth; UINT8 DarkplntBulletColour; UINT8 DambustrBgColour1; UINT8 DambustrBgColour2; UINT8 DambustrBgPriority; UINT8 DambustrBgSplitLine; UINT8 *RockclimTiles; UINT16 RockclimScrollX; UINT16 RockclimScrollY; // Graphics decode helpers INT32 CharPlaneOffsets[2] = { 0, 0x4000 }; INT32 CharXOffsets[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; INT32 CharYOffsets[8] = { 0, 8, 16, 24, 32, 40, 48, 56 }; INT32 SpritePlaneOffsets[2] = { 0, 0x4000 }; INT32 SpriteXOffsets[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71 }; INT32 SpriteYOffsets[16] = { 0, 8, 16, 24, 32, 40, 48, 56, 128, 136, 144, 152, 160, 168, 176, 184 }; // Tile extend helpers void UpperExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code += 0x100; } void PiscesExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code |= GalGfxBank[0] << 8; } void Batman2ExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { if (*Code & 0x80) *Code |= GalGfxBank[0] << 8; } void GmgalaxExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code |= GalGfxBank[0] << 9; } void MooncrstExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { if (GalGfxBank[2] && (*Code & 0xc0) == 0x80) *Code = (*Code & 0x3f) | (GalGfxBank[0] << 6) | (GalGfxBank[1] << 7) | 0x0100; } void MoonqsrExtendTileInfo(UINT16 *Code, INT32*, INT32 Attr, INT32) { *Code |= (Attr & 0x20) << 3; } void SkybaseExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code |= GalGfxBank[2] << 8; } void JumpbugExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { if ((*Code & 0xc0) == 0x80 && (GalGfxBank[2] & 0x01)) *Code += 128 + ((GalGfxBank[0] & 0x01) << 6) + ((GalGfxBank[1] & 0x01) << 7) + ((~GalGfxBank[4] & 0x01) << 8); } void FroggerExtendTileInfo(UINT16*, INT32 *Colour, INT32, INT32) { *Colour = ((*Colour >> 1) & 0x03) | ((*Colour << 2) & 0x04); } void MshuttleExtendTileInfo(UINT16 *Code, INT32*, INT32 Attr, INT32) { *Code |= (Attr & 0x30) << 4; } void Fourin1ExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code |= Fourin1Bank << 8; } void MarinerExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32 x) { UINT8 *Prom = GalProm + 0x120; *Code |= (Prom[x] & 0x01) << 8; } void MimonkeyExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code |= (GalGfxBank[0] << 8) | (GalGfxBank[1] << 9); } void DambustrExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32 x) { if (GalGfxBank[0] == 0) { *Code |= 0x300; } else { if (x == 28) { *Code |= 0x300; } else { *Code &= 0xff; } } } void Ad2083ExtendTileInfo(UINT16 *Code, INT32 *Colour, INT32 Attr, INT32) { INT32 Bank = Attr & 0x30; *Code |= (Bank << 4); *Colour |= ((Attr & 0x40) >> 3); } void RacknrolExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32 x) { UINT8 Bank = GalGfxBank[x] & 7; *Code |= Bank << 8; } void BagmanmcExtendTileInfo(UINT16 *Code, INT32*, INT32, INT32) { *Code |= GalGfxBank[0] << 9; } // Sprite extend helpers void UpperExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code += 0x40; } void PiscesExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= GalGfxBank[0] << 6; } void GmgalaxExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= (GalGfxBank[0] << 7) | 0x40; } void MooncrstExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { if (GalGfxBank[2] && (*Code & 0x30) == 0x20) *Code = (*Code & 0x0f) | (GalGfxBank[0] << 4) | (GalGfxBank[1] << 5) | 0x40; } void MoonqsrExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= (Base[2] & 0x20) << 1; } void SkybaseExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= GalGfxBank[2] << 6; } void RockclimExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { if (GalGfxBank[2]) *Code |= 0x40; } void JumpbugExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { if ((*Code & 0x30) == 0x20 && (GalGfxBank[2] & 0x01) != 0) *Code += 32 + ((GalGfxBank[0] & 0x01) << 4) + ((GalGfxBank[1] & 0x01) << 5) + ((~GalGfxBank[4] & 0x01) << 6); } void FroggerExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16*, UINT8 *Colour) { *Colour = ((*Colour >> 1) & 0x03) | ((*Colour << 2) & 0x04); } void CalipsoExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8 *xFlip, UINT8 *yFlip, UINT16 *Code, UINT8*) { *Code = Base[1]; *xFlip = 0; *yFlip = 0; } void MshuttleExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= (Base[2] & 0x30) << 2; } void Fourin1ExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= Fourin1Bank << 6; } void DkongjrmExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8 *xFlip, UINT8*, UINT16 *Code, UINT8*) { *Code = (Base[1] & 0x7f) | 0x80; *xFlip = 0; } void MimonkeyExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= (GalGfxBank[0] << 6) | (GalGfxBank[1] << 7); } void Ad2083ExtendSpriteInfo(const UINT8 *Base, INT32*, INT32*, UINT8 *xFlip, UINT8*, UINT16 *Code, UINT8*) { *Code = (Base[1] & 0x7f) | ((Base[2] & 0x30) << 2); *xFlip = 0; } void BagmanmcExtendSpriteInfo(const UINT8*, INT32*, INT32*, UINT8*, UINT8*, UINT16 *Code, UINT8*) { *Code |= (GalGfxBank[0] << 7) | 0x40; } // Hardcode a Galaxian PROM for any games that are missing a PROM dump void HardCodeGalaxianPROM() { GalProm[0x00]= 0x00; GalProm[0x01]= 0x00; GalProm[0x02]= 0x00; GalProm[0x03]= 0xf6; GalProm[0x04]= 0x00; GalProm[0x05]= 0x16; GalProm[0x06]= 0xc0; GalProm[0x07]= 0x3f; GalProm[0x08]= 0x00; GalProm[0x09]= 0xd8; GalProm[0x0a]= 0x07; GalProm[0x0b]= 0x3f; GalProm[0x0c]= 0x00; GalProm[0x0d]= 0xc0; GalProm[0x0e]= 0xc4; GalProm[0x0f]= 0x07; GalProm[0x10]= 0x00; GalProm[0x11]= 0xc0; GalProm[0x12]= 0xa0; GalProm[0x13]= 0x07; GalProm[0x14]= 0x00; GalProm[0x15]= 0x00; GalProm[0x16]= 0x00; GalProm[0x17]= 0x07; GalProm[0x18]= 0x00; GalProm[0x19]= 0xf6; GalProm[0x1a]= 0x07; GalProm[0x1b]= 0xf0; GalProm[0x1c]= 0x00; GalProm[0x1d]= 0x76; GalProm[0x1e]= 0x07; GalProm[0x1f]= 0xc6; } void HardCodeMooncrstPROM() { GalProm[0x00]= 0x00; GalProm[0x01]= 0x7a; GalProm[0x02]= 0x36; GalProm[0x03]= 0x07; GalProm[0x04]= 0x00; GalProm[0x05]= 0xf0; GalProm[0x06]= 0x38; GalProm[0x07]= 0x1f; GalProm[0x08]= 0x00; GalProm[0x09]= 0xc7; GalProm[0x0a]= 0xf0; GalProm[0x0b]= 0x3f; GalProm[0x0c]= 0x00; GalProm[0x0d]= 0xdb; GalProm[0x0e]= 0xc6; GalProm[0x0f]= 0x38; GalProm[0x10]= 0x00; GalProm[0x11]= 0x36; GalProm[0x12]= 0x07; GalProm[0x13]= 0xf0; GalProm[0x14]= 0x00; GalProm[0x15]= 0x33; GalProm[0x16]= 0x3f; GalProm[0x17]= 0xdb; GalProm[0x18]= 0x00; GalProm[0x19]= 0x3f; GalProm[0x1a]= 0x57; GalProm[0x1b]= 0xc6; GalProm[0x1c]= 0x00; GalProm[0x1d]= 0xc6; GalProm[0x1e]= 0x3f; GalProm[0x1f]= 0xff; } // Pallet generation #define RGB_MAXIMUM 224 #define MAX_NETS 3 #define MAX_RES_PER_NET 18 #define Combine2Weights(tab,w0,w1) ((INT32)(((tab)[0]*(w0) + (tab)[1]*(w1)) + 0.5)) #define Combine3Weights(tab,w0,w1,w2) ((INT32)(((tab)[0]*(w0) + (tab)[1]*(w1) + (tab)[2]*(w2)) + 0.5)) static double ComputeResistorWeights(INT32 MinVal, INT32 MaxVal, double Scaler, INT32 Count1, const INT32 *Resistances1, double *Weights1, INT32 PullDown1, INT32 PullUp1, INT32 Count2, const INT32 *Resistances2, double *Weights2, INT32 PullDown2, INT32 PullUp2, INT32 Count3, const INT32 *Resistances3, double *Weights3, INT32 PullDown3, INT32 PullUp3) { INT32 NetworksNum; INT32 ResCount[MAX_NETS]; double r[MAX_NETS][MAX_RES_PER_NET]; double w[MAX_NETS][MAX_RES_PER_NET]; double ws[MAX_NETS][MAX_RES_PER_NET]; INT32 r_pd[MAX_NETS]; INT32 r_pu[MAX_NETS]; double MaxOut[MAX_NETS]; double *Out[MAX_NETS]; INT32 i, j, n; double Scale; double Max; NetworksNum = 0; for (n = 0; n < MAX_NETS; n++) { INT32 Count, pd, pu; const INT32 *Resistances; double *Weights; switch (n) { case 0: { Count = Count1; Resistances = Resistances1; Weights = Weights1; pd = PullDown1; pu = PullUp1; break; } case 1: { Count = Count2; Resistances = Resistances2; Weights = Weights2; pd = PullDown2; pu = PullUp2; break; } case 2: default: { Count = Count3; Resistances = Resistances3; Weights = Weights3; pd = PullDown3; pu = PullUp3; break; } } if (Count > 0) { ResCount[NetworksNum] = Count; for (i = 0; i < Count; i++) { r[NetworksNum][i] = 1.0 * Resistances[i]; } Out[NetworksNum] = Weights; r_pd[NetworksNum] = pd; r_pu[NetworksNum] = pu; NetworksNum++; } } for (i = 0; i < NetworksNum; i++) { double R0, R1, Vout, Dst; for (n = 0; n < ResCount[i]; n++) { R0 = (r_pd[i] == 0) ? 1.0 / 1e12 : 1.0 / r_pd[i]; R1 = (r_pu[i] == 0) ? 1.0 / 1e12 : 1.0 / r_pu[i]; for (j = 0; j < ResCount[i]; j++) { if (j == n) { if (r[i][j] != 0.0) R1 += 1.0 / r[i][j]; } else { if (r[i][j] != 0.0) R0 += 1.0 / r[i][j]; } } R0 = 1.0/R0; R1 = 1.0/R1; Vout = (MaxVal - MinVal) * R0 / (R1 + R0) + MinVal; Dst = (Vout < MinVal) ? MinVal : (Vout > MaxVal) ? MaxVal : Vout; w[i][n] = Dst; } } j = 0; Max = 0.0; for (i = 0; i < NetworksNum; i++) { double Sum = 0.0; for (n = 0; n < ResCount[i]; n++) Sum += w[i][n]; MaxOut[i] = Sum; if (Max < Sum) { Max = Sum; j = i; } } if (Scaler < 0.0) { Scale = ((double)MaxVal) / MaxOut[j]; } else { Scale = Scaler; } for (i = 0; i < NetworksNum; i++) { for (n = 0; n < ResCount[i]; n++) { ws[i][n] = w[i][n] * Scale; (Out[i])[n] = ws[i][n]; } } return Scale; } void GalaxianCalcPalette() { static const INT32 RGBResistances[3] = {1000, 470, 220}; double rWeights[3], gWeights[3], bWeights[2]; ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0); // Colour PROM for (INT32 i = 0; i < 32; i++) { UINT8 Bit0, Bit1, Bit2, r, g, b; Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2); r = Combine3Weights(rWeights, Bit0, Bit1, Bit2); Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5); g = Combine3Weights(gWeights, Bit0, Bit1, Bit2); Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],6); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],7); b = Combine2Weights(bWeights, Bit0, Bit1); GalPalette[i] = BurnHighCol(r, g, b, 0); } // Stars for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) { INT32 Bits, r, g, b; INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff}; Bits = (i >> 0) & 0x03; r = Map[Bits]; Bits = (i >> 2) & 0x03; g = Map[Bits]; Bits = (i >> 4) & 0x03; b = Map[Bits]; GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0); } // Bullets for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_BULLETS - 1; i++) { GalPalette[i + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0xff, 0); } GalPalette[GAL_PALETTE_NUM_COLOURS_BULLETS - 1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0x00, 0); } void RockclimCalcPalette() { static const INT32 RGBResistances[3] = {1000, 470, 220}; double rWeights[3], gWeights[3], bWeights[2]; ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0); // Colour PROM for (INT32 i = 0; i < 64; i++) { UINT8 Bit0, Bit1, Bit2, r, g, b; Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2); r = Combine3Weights(rWeights, Bit0, Bit1, Bit2); Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5); g = Combine3Weights(gWeights, Bit0, Bit1, Bit2); Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],6); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],7); b = Combine2Weights(bWeights, Bit0, Bit1); GalPalette[i] = BurnHighCol(r, g, b, 0); } // Stars for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) { INT32 Bits, r, g, b; INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff}; Bits = (i >> 0) & 0x03; r = Map[Bits]; Bits = (i >> 2) & 0x03; g = Map[Bits]; Bits = (i >> 4) & 0x03; b = Map[Bits]; GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0); } // Bullets for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_BULLETS - 1; i++) { GalPalette[i + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0xff, 0); } GalPalette[GAL_PALETTE_NUM_COLOURS_BULLETS - 1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0x00, 0); } void MarinerCalcPalette() { GalaxianCalcPalette(); for (INT32 i = 0; i < 16; i++) { INT32 b = 0x0e * BIT(i, 0) + 0x1f * BIT(i, 1) + 0x43 * BIT(i, 2) + 0x8f * BIT(i, 3); GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, b, 0); } } void StratgyxCalcPalette() { GalaxianCalcPalette(); for (INT32 i = 0; i < 8; i++) { INT32 r = BIT(i, 0) * 0x7c; INT32 g = BIT(i, 1) * 0x3c; INT32 b = BIT(i, 2) * 0x47; GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(r, g, b, 0); } } void RescueCalcPalette() { GalaxianCalcPalette(); for (INT32 i = 0; i < 128; i++) { INT32 b = i * 2; GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, b, 0); } } void MinefldCalcPalette() { RescueCalcPalette(); for (INT32 i = 0; i < 128; i++) { INT32 r = (INT32)(i * 1.5); INT32 g = (INT32)(i * 0.75); INT32 b = i / 2; GalPalette[i + 128 + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(r, g, b, 0); } } void DarkplntCalcPalette() { static const INT32 RGBResistances[3] = {1000, 470, 220}; double rWeights[3], gWeights[3], bWeights[2]; ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0); // Colour PROM for (INT32 i = 0; i < 32; i++) { UINT8 Bit0, Bit1, Bit2, r, g, b; Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2); r = Combine3Weights(rWeights, Bit0, Bit1, Bit2); g = 0; Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5); b = Combine2Weights(bWeights, Bit0, Bit1); GalPalette[i] = BurnHighCol(r, g, b, 0); } // Stars for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) { INT32 Bits, r, g, b; INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff}; Bits = (i >> 0) & 0x03; r = Map[Bits]; Bits = (i >> 2) & 0x03; g = Map[Bits]; Bits = (i >> 4) & 0x03; b = Map[Bits]; GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0); } // Bullets GalPalette[0 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xef, 0x00, 0x00, 0); GalPalette[1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0x00, 0x00, 0xef, 0); } void DambustrCalcPalette() { static const INT32 RGBResistances[3] = {1000, 470, 220}; double rWeights[3], gWeights[3], bWeights[2]; ComputeResistorWeights(0, RGB_MAXIMUM, -1.0, 3, &RGBResistances[0], rWeights, 470, 0, 3, &RGBResistances[0], gWeights, 470, 0, 2, &RGBResistances[1], bWeights, 470, 0); // Colour PROM for (INT32 i = 0; i < 32; i++) { UINT8 Bit0, Bit1, Bit2, r, g, b; Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],0); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],1); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],2); b = Combine3Weights(rWeights, Bit0, Bit1, Bit2); Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],3); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],4); Bit2 = BIT(GalProm[i + (GalPaletteBank * 0x20)],5); r = Combine3Weights(gWeights, Bit0, Bit1, Bit2); Bit0 = BIT(GalProm[i + (GalPaletteBank * 0x20)],6); Bit1 = BIT(GalProm[i + (GalPaletteBank * 0x20)],7); g = Combine2Weights(bWeights, Bit0, Bit1); GalPalette[i] = BurnHighCol(r, g, b, 0); } // Stars for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_STARS; i++) { INT32 Bits, r, g, b; INT32 Map[4] = {0x00, 0x88, 0xcc, 0xff}; Bits = (i >> 0) & 0x03; r = Map[Bits]; Bits = (i >> 2) & 0x03; g = Map[Bits]; Bits = (i >> 4) & 0x03; b = Map[Bits]; GalPalette[i + GAL_PALETTE_STARS_OFFSET] = BurnHighCol(r, g, b, 0); } // Bullets for (INT32 i = 0; i < GAL_PALETTE_NUM_COLOURS_BULLETS - 1; i++) { GalPalette[i + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0xff, 0); } GalPalette[GAL_PALETTE_NUM_COLOURS_BULLETS - 1 + GAL_PALETTE_BULLETS_OFFSET] = BurnHighCol(0xff, 0xff, 0x00, 0); for (INT32 i = 0; i < 8; i++) { INT32 r = BIT(i, 0) * 0x47; INT32 g = BIT(i, 1) * 0x47; INT32 b = BIT(i, 2) * 0x4f; GalPalette[i + GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(r, g, b, 0); } } #undef RGB_MAXIMUM #undef MAX_NETS #undef MAX_RES_PER_NET #undef Combine_2Weights #undef Combine_3Weights // Background and Stars rendering void GalaxianDrawBackground() { if (GalStarsEnable) GalaxianRenderStarLayer(); } void RockclimDrawBackground() { INT32 mx, my, Code, Colour, x, y, TileIndex = 0; for (my = 0; my < 32; my++) { for (mx = 0; mx < 64; mx++) { Code = GalVideoRam2[TileIndex]; Colour = 0; x = 8 * mx; y = 8 * my; x -= RockclimScrollX & 0x1ff; y -= RockclimScrollY & 0xff; if (x < -8) x += 512; if (y < -8) y += 256; y -= 16; if (x > 8 && x < (nScreenWidth - 8) && y > 8 && y < (nScreenHeight - 8)) { Render8x8Tile(pTransDraw, Code, x, y, Colour, 4, 32, RockclimTiles); } else { Render8x8Tile_Clip(pTransDraw, Code, x, y, Colour, 4, 32, RockclimTiles); } TileIndex++; } } } void JumpbugDrawBackground() { if (GalStarsEnable) JumpbugRenderStarLayer(); } void FroggerDrawBackground() { GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, 0x47, 0); if (GalFlipScreenX) { for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = nScreenWidth - 1; x > 128 - 8; x--) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET; } } } else { for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = 0; x < 128 + 8; x++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET; } } } } void TurtlesDrawBackground() { GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(GalBackgroundRed * 0x55, GalBackgroundGreen * 0x47, GalBackgroundBlue * 0x55, 0); for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = 0; x < nScreenWidth; x++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET; } } } void ScrambleDrawBackground() { GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, 0x56, 0); if (GalBackgroundEnable) { for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = 0; x < nScreenWidth; x++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET; } } } if (GalStarsEnable) ScrambleRenderStarLayer(); } void AnteaterDrawBackground() { GalPalette[GAL_PALETTE_BACKGROUND_OFFSET] = BurnHighCol(0, 0, 0x56, 0); if (GalBackgroundEnable) { if (GalFlipScreenX) { for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = nScreenWidth - 1; x > 256 - 56; x--) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET; } } } else { for (INT32 y = 0; y < nScreenHeight; y++) { for (INT32 x = 0; x < 56; x++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET; } } } } } void MarinerDrawBackground() { UINT8 *BgColourProm = GalProm + 0x20; INT32 x; if (GalFlipScreenX) { for (x = 0; x < 32; x++) { INT32 Colour; if (x == 0) { Colour = 0; } else { Colour = BgColourProm[0x20 + x - 1]; } INT32 xStart = 8 * (31 - x); for (INT32 sy = 0; sy < nScreenHeight; sy++) { for (INT32 sx = xStart; sx < xStart + 8; sx++) { pTransDraw[(sy * nScreenWidth) + sx] = GAL_PALETTE_BACKGROUND_OFFSET + Colour; } } } } else { for (x = 0; x < 32; x++) { INT32 Colour; if (x == 31) { Colour = 0; } else { Colour = BgColourProm[x + 1]; } INT32 xStart = x * 8; for (INT32 sy = 0; sy < nScreenHeight; sy++) { for (INT32 sx = xStart; sx < xStart + 8; sx++) { pTransDraw[(sy * nScreenWidth) + sx] = GAL_PALETTE_BACKGROUND_OFFSET + Colour; } } } } if (GalStarsEnable) MarinerRenderStarLayer(); } void StratgyxDrawBackground() { UINT8 *BgColourProm = GalProm + 0x20; for (INT32 x = 0; x < 32; x++) { INT32 xStart, Colour = 0; if ((~BgColourProm[x] & 0x02) && GalBackgroundRed) Colour |= 0x01; if ((~BgColourProm[x] & 0x02) && GalBackgroundGreen) Colour |= 0x02; if ((~BgColourProm[x] & 0x01) && GalBackgroundBlue) Colour |= 0x04; if (GalFlipScreenX) { xStart = 8 * (31 - x); } else { xStart = 8 * x; } for (INT32 sy = 0; sy < nScreenHeight; sy++) { for (INT32 sx = xStart; sx < xStart + 8; sx++) { pTransDraw[(sy * nScreenWidth) + sx] = GAL_PALETTE_BACKGROUND_OFFSET + Colour; } } } } void RescueDrawBackground() { if (GalBackgroundEnable) { INT32 x; for (x = 0; x < 128; x++) { for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + x; } } for (x = 0; x < 120; x++) { for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + (x + 128)] = GAL_PALETTE_BACKGROUND_OFFSET + x + 8; } } for (x = 0; x < 8; x++) { for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + (x + 248)] = GAL_PALETTE_BACKGROUND_OFFSET; } } } if (GalStarsEnable) RescueRenderStarLayer(); } void MinefldDrawBackground() { if (GalBackgroundEnable) { INT32 x; for (x = 0; x < 128; x++) { for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + x; } } for (x = 0; x < 120; x++) { for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + (x + 128)] = GAL_PALETTE_BACKGROUND_OFFSET + x + 128; } } for (x = 0; x < 8; x++) { for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + (x + 248)] = GAL_PALETTE_BACKGROUND_OFFSET; } } } if (GalStarsEnable) RescueRenderStarLayer(); } void DambustrDrawBackground() { INT32 xClipStart = GalFlipScreenX ? 254 - DambustrBgSplitLine : 0; INT32 xClipEnd = GalFlipScreenX ? 0 : 254 - DambustrBgSplitLine; for (INT32 x = 0; x < 256 - DambustrBgSplitLine; x++) { if (DambustrBgPriority && (x < xClipStart || x > xClipEnd)) continue; for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + ((GalFlipScreenX) ? DambustrBgColour2 : DambustrBgColour1); } } for (INT32 x = 255; x > 256 - DambustrBgSplitLine; x--) { if (DambustrBgPriority && (x < xClipStart || x > xClipEnd)) continue; for (INT32 y = 0; y < nScreenHeight; y++) { pTransDraw[(y * nScreenWidth) + x] = GAL_PALETTE_BACKGROUND_OFFSET + ((GalFlipScreenX) ? DambustrBgColour1 : DambustrBgColour2); } } if (GalStarsEnable && !DambustrBgPriority) GalaxianRenderStarLayer(); } // Char Layer rendering static void GalRenderBgLayer(UINT8 *pVideoRam) { INT32 mx, my, Attr, Colour, x, y, TileIndex = 0, RamPos; UINT16 Code; for (my = 0; my < 32; my++) { for (mx = 0; mx < 32; mx++) { RamPos = TileIndex & 0x1f; Code = pVideoRam[TileIndex]; Attr = GalSpriteRam[(RamPos * 2) + 1]; Colour = Attr & ((GalColourDepth == 3) ? 0x03 : 0x07); if (GalExtendTileInfoFunction) GalExtendTileInfoFunction(&Code, &Colour, Attr, RamPos); if (SfxTilemap) { x = 8 * my; y = 8 * mx; } else { x = 8 * mx; y = 8 * my; } y -= 16; if (GalFlipScreenX) x = nScreenWidth - 8 - x; if (GalFlipScreenY) y = nScreenHeight - 8 - y; INT32 px, py; UINT32 nPalette = Colour << GalColourDepth; for (py = 0; py < 8; py++) { for (px = 0; px < 8; px++) { UINT8 c = GalChars[(Code * 64) + (py * 8) + px]; if (GalFlipScreenX) c = GalChars[(Code * 64) + (py * 8) + (7 - px)]; if (GalFlipScreenY) c = GalChars[(Code * 64) + ((7 - py) * 8) + px]; if (GalFlipScreenX && GalFlipScreenY) c = GalChars[(Code * 64) + ((7 - py) * 8) + (7 - px)]; if (c) { INT32 xPos = x + px; INT32 yPos = y + py; if (SfxTilemap) { if (GalFlipScreenX) { xPos += GalScrollVals[mx]; } else { xPos -= GalScrollVals[mx]; } if (xPos < 0) xPos += 256; if (xPos > 255) xPos -= 256; } else { if (GalFlipScreenY) { yPos += GalScrollVals[mx]; } else { yPos -= GalScrollVals[mx]; } if (yPos < 0) yPos += 256; if (yPos > 255) yPos -= 256; } if (GalOrientationFlipX) { xPos = nScreenWidth - 1 - xPos; } if (yPos >= 0 && yPos < nScreenHeight) { UINT16* pPixel = pTransDraw + (yPos * nScreenWidth); if (xPos >= 0 && xPos < nScreenWidth) { pPixel[xPos] = c | nPalette; } } } } } TileIndex++; } } } // Sprite Rendering static void GalRenderSprites(const UINT8 *SpriteBase) { INT32 SprNum; INT32 ClipOfs = GalFlipScreenX ? 16 : 0; INT32 xMin = GalSpriteClipStart - ClipOfs; INT32 xMax = GalSpriteClipEnd - ClipOfs + 1; for (SprNum = 7; SprNum >= 0; SprNum--) { const UINT8 *Base = &SpriteBase[SprNum * 4]; UINT8 Base0 = FroggerAdjust ? ((Base[0] >> 4) | (Base[0] << 4)) : Base[0]; INT32 sy = 240 - (Base0 - (SprNum < 3)); UINT16 Code = Base[1] & 0x3f; UINT8 xFlip = Base[1] & 0x40; UINT8 yFlip = Base[1] & 0x80; UINT8 Colour = Base[2] & ((GalColourDepth == 3) ? 0x03 : 0x07); INT32 sx = Base[3]; if (GalExtendSpriteInfoFunction) GalExtendSpriteInfoFunction(Base, &sx, &sy, &xFlip, &yFlip, &Code, &Colour); if (GalFlipScreenX) { sx = 242 - sx; xFlip = !xFlip; } if (sx < xMin || sx > xMax) continue; if (GalFlipScreenY) { sy = 240 - sy; yFlip = !yFlip; } sy -= 16; if (GalOrientationFlipX) { sx = 242 - 1 - sx; xFlip = !xFlip; } if (sx > 16 && sx < (nScreenWidth - 16) && sy > 16 && sy < (nScreenHeight - 16)) { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } else { Render16x16Tile_Mask_FlipX(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } else { Render16x16Tile_Mask(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } } } else { if (xFlip) { if (yFlip) { Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } else { Render16x16Tile_Mask_FlipX_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } } else { if (yFlip) { Render16x16Tile_Mask_FlipY_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } else { Render16x16Tile_Mask_Clip(pTransDraw, Code, sx, sy, Colour, GalColourDepth, 0, 0, GalSprites); } } } } } // Bullet rendering static inline void GalDrawPixel(INT32 x, INT32 y, INT32 Colour) { if (y >= 0 && y < nScreenHeight && x >= 0 && x < nScreenWidth) { pTransDraw[(y * nScreenWidth) + x] = Colour; } } void GalaxianDrawBullets(INT32 Offs, INT32 x, INT32 y) { x -= 4; GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); } void TheendDrawBullets(INT32 Offs, INT32 x, INT32 y) { x -= 4; GalPalette[GAL_PALETTE_BULLETS_OFFSET + 7] = BurnHighCol(0xff, 0x00, 0xff, 0); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); GalDrawPixel(x++, y, GAL_PALETTE_BULLETS_OFFSET + Offs); } void ScrambleDrawBullets(INT32, INT32 x, INT32 y) { x -= 6; GalDrawPixel(x, y, GAL_PALETTE_BULLETS_OFFSET + 7); } void MoonwarDrawBullets(INT32, INT32 x, INT32 y) { x -= 6; GalPalette[GAL_PALETTE_BULLETS_OFFSET + 7] = BurnHighCol(0xef, 0xef, 0x97, 0); GalDrawPixel(x, y, GAL_PALETTE_BULLETS_OFFSET + 7); } void MshuttleDrawBullets(INT32, INT32 x, INT32 y) { GalPalette[GAL_PALETTE_BULLETS_OFFSET + 0] = BurnHighCol(0xff, 0xff, 0xff, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 1] = BurnHighCol(0xff, 0xff, 0x00, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 2] = BurnHighCol(0x00, 0xff, 0xff, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 3] = BurnHighCol(0x00, 0xff, 0x00, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 4] = BurnHighCol(0xff, 0x00, 0xff, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 5] = BurnHighCol(0xff, 0x00, 0x00, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 6] = BurnHighCol(0x00, 0x00, 0xff, 0); GalPalette[GAL_PALETTE_BULLETS_OFFSET + 7] = BurnHighCol(0x00, 0x00, 0x00, 0); --x; GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4); --x; GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4); --x; GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4); --x; GalDrawPixel(x, y, ((x & 0x40) == 0) ? GAL_PALETTE_BULLETS_OFFSET + + ((x >> 2) & 7) : GAL_PALETTE_BULLETS_OFFSET + + 4); } void DarkplntDrawBullets(INT32, INT32 x, INT32 y) { if (GalFlipScreenX) x++; x -= 6; GalDrawPixel(x, y, GAL_PALETTE_BULLETS_OFFSET + DarkplntBulletColour); } void DambustrDrawBullets(INT32 Offs, INT32 x, INT32 y) { INT32 Colour; if (GalFlipScreenX) x++; x -= 6; for (INT32 i = 0; i < 2; i++) { if (Offs < 16) { Colour = GAL_PALETTE_BULLETS_OFFSET + 7; y--; } else { Colour = GAL_PALETTE_BULLETS_OFFSET; x--; } } GalDrawPixel(x, y, Colour); } static void GalDrawBullets(const UINT8 *Base) { for (INT32 y = 0; y < nScreenHeight; y++) { UINT8 Shell = 0xff; UINT8 Missile = 0xff; UINT8 yEff; INT32 Which; yEff = (GalFlipScreenY) ? (y + 16 - 1) ^ 255 : y + 16 - 1; for (Which = 0; Which < 3; Which++) { if ((UINT8)(Base[Which * 4 + 1] + yEff) == 0xff) Shell = Which; } yEff = (GalFlipScreenY) ? (y + 16) ^ 255 : y + 16; for (Which = 3; Which < 8; Which++) { if ((UINT8)(Base[Which * 4 + 1] + yEff) == 0xff) { if (Which != 7) { Shell = Which; } else { Missile = Which; } } } if (Shell != 0xff) GalDrawBulletsFunction(Shell, (GalOrientationFlipX) ? Base[Shell * 4 + 3] : 255 - Base[Shell * 4 + 3], y); if (Missile != 0xff) GalDrawBulletsFunction(Missile, (GalOrientationFlipX) ? Base[Missile * 4 + 3] : 255 - Base[Missile * 4 + 3], y); } } // Render a frame void GalDraw() { if (GalRenderFrameFunction) { GalRenderFrameFunction(); } else { BurnTransferClear(); GalCalcPaletteFunction(); if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); GalRenderBgLayer(GalVideoRam); GalRenderSprites(&GalSpriteRam[0x40]); if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0x60]); BurnTransferCopy(GalPalette); } } void DkongjrmRenderFrame() { BurnTransferClear(); GalCalcPaletteFunction(); if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); GalRenderBgLayer(GalVideoRam); GalRenderSprites(&GalSpriteRam[0x40]); GalRenderSprites(&GalSpriteRam[0x60]); GalRenderSprites(&GalSpriteRam[0xc0]); GalRenderSprites(&GalSpriteRam[0xe0]); if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0x60]); BurnTransferCopy(GalPalette); } void DambustrRenderFrame() { BurnTransferClear(); GalCalcPaletteFunction(); if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); GalRenderBgLayer(GalVideoRam); GalRenderSprites(&GalSpriteRam[0x40]); if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0x60]); if (DambustrBgPriority) { if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); memset(GalVideoRam2, 0x20, 0x400); for (INT32 i = 0; i < 32; i++) { INT32 Colour = GalSpriteRam[(i << 1) | 1] & 7; if (Colour > 3) { for (INT32 j = 0; j < 32; j++) GalVideoRam2[(32 * j) + i] = GalVideoRam[(32 * j) + i]; } } GalRenderBgLayer(GalVideoRam2); } BurnTransferCopy(GalPalette); } void FantastcRenderFrame() { BurnTransferClear(); GalCalcPaletteFunction(); if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); GalRenderBgLayer(GalVideoRam); GalRenderSprites(&GalSpriteRam[0x40]); if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0xc0]); BurnTransferCopy(GalPalette); } void TimefgtrRenderFrame() { BurnTransferClear(); GalCalcPaletteFunction(); if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); GalRenderBgLayer(GalVideoRam); GalRenderSprites(&GalSpriteRam[0x040]); // MAME renders different sprite ram areas depending on screen-area - necessary? GalRenderSprites(&GalSpriteRam[0x140]); GalRenderSprites(&GalSpriteRam[0x240]); GalRenderSprites(&GalSpriteRam[0x340]); if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0xc0]); BurnTransferCopy(GalPalette); } void ScramblerRenderFrame() { BurnTransferClear(); GalCalcPaletteFunction(); if (GalRenderBackgroundFunction) GalRenderBackgroundFunction(); GalRenderBgLayer(GalVideoRam); GalRenderSprites(&GalSpriteRam[0xc0]); if (GalDrawBulletsFunction) GalDrawBullets(&GalSpriteRam[0xe0]); BurnTransferCopy(GalPalette); }
26.770353
352
0.634887
atship
ac3daf335b0abcbfae8f308c03102d18ca19722a
8,174
cpp
C++
src/componentLib/websocketServer/WebsocketServer.cpp
tangtgithub/common_robotframe
f098d688bde1d2b2d5d6fac430c98b952621b7c1
[ "MIT" ]
5
2021-07-21T11:38:09.000Z
2021-11-26T03:16:09.000Z
src/componentLib/websocketServer/WebsocketServer.cpp
tangtgithub/common_robotframe
f098d688bde1d2b2d5d6fac430c98b952621b7c1
[ "MIT" ]
null
null
null
src/componentLib/websocketServer/WebsocketServer.cpp
tangtgithub/common_robotframe
f098d688bde1d2b2d5d6fac430c98b952621b7c1
[ "MIT" ]
null
null
null
#include "WebsocketServer.h" #include <sys/prctl.h> #include <chrono> #include "websocketServerCommon.h" #include "UdpServerWs.h" #include "UdpClientWs.h" WebsocketServer::WebsocketServer() : m_sessionid(0) { m_server.set_access_channels(websocketpp::log::alevel::none); m_server.init_asio(); m_server.set_open_handler(bind(&WebsocketServer::onOpen, this, ::_1)); m_server.set_close_handler(bind(&WebsocketServer::onClose, this, ::_1)); m_server.set_message_handler(bind(&WebsocketServer::onMessage, this, ::_1, ::_2)); } WebsocketServer::~WebsocketServer() { } void WebsocketServer::onOpen(connection_hdl hdl) { ConnectionData data; { std::lock_guard<std::mutex> guard(m_connectMutex); if (m_connections.size() > 10) { m_server.close(hdl, 0, "timeout"); SPDLOG_ERROR("too much connection,forbid new connect.close this connection"); return; } data.sessionid = ++m_sessionid; data.timeLastHeart = time(NULL); if (m_sessionid >= 60) m_sessionid = 0; m_connections[hdl] = data; SPDLOG_INFO("connect success,sessionid:{}", m_sessionid); } if(m_onOpenCb) { m_onOpenCb(data.sessionid); } } void WebsocketServer::onClose(connection_hdl hdl) { try { std::lock_guard<std::mutex> guard(m_connectMutex); ConnectionData data = getDataFromConnHandle(hdl); SPDLOG_INFO("close connection success,sessionid:{}", data.sessionid); m_connections.erase(hdl); if (m_onCloseCb) m_onCloseCb(data.sessionid); } catch (std::invalid_argument &info) { SPDLOG_INFO("close connection success"); } catch (...) { SPDLOG_ERROR("other error"); } } ConnectionData WebsocketServer::getDataFromConnHandle(connection_hdl hdl) { auto it = m_connections.find(hdl); if (it == m_connections.end()) { // this connection is not in the list. This really shouldn't happen // and probably means something else is wrong. throw std::invalid_argument("No data available for session"); } return it->second; } connection_hdl WebsocketServer::getHandleFromSessionId(int sessionId) { for (auto it = m_connections.begin(); it != m_connections.end(); it++) { if (it->second.sessionid == sessionId) return it->first; } throw std::invalid_argument("No data available for session"); } void WebsocketServer::onMessage(connection_hdl hdl, message_ptr msg) { MsgHandler msgHandler; try { ConnectionData data; { std::lock_guard<std::mutex> guard(m_connectMutex); data = getDataFromConnHandle(hdl); } memcpy(&msgHandler, &data, sizeof(ConnectionData)); msgHandler.msg = msg->get_payload(); std::lock_guard<std::mutex> guard(m_msgMutex); m_msgs.push_back(msgHandler); cvMsg.notify_all(); //Debug << "通知处理线程收到数据\n"; } catch (std::invalid_argument &info) { //nonexistent SPDLOG_ERROR("warn:receive unexpected info,connection abnormal"); } catch (...) { SPDLOG_ERROR("other error"); } } int WebsocketServer::startServer() { std::thread recvThread(&WebsocketServer::run, this); std::thread monitorThread(&WebsocketServer::monitorHeart, this); std::thread handleMsgThread(&WebsocketServer::handleMsg, this); std::thread serverIpThread(&WebsocketServer::serverIpBroadcast, this); recvThread.detach(); monitorThread.detach(); handleMsgThread.detach(); serverIpThread.detach(); return SUCCESS; } void WebsocketServer::serverIpBroadcast() { prctl(PR_SET_NAME, "serverIpBroadcast"); UdpClient udpClient; UdpServer udpServer; udpClient.initClient(kServerBroadcastPort); udpServer.initServer(kAppBroadcastPort); while (1) { char buf[100] = { 0 }; char sendBuf[] = "res_server_ip"; std::string strIp; if (udpServer.readData(buf, sizeof(buf) - 1, strIp)) { continue; } if (!strncmp(buf, "query_server_ip", sizeof("query_server_ip"))) { udpClient.writeData(sendBuf, static_cast<int>(strlen(sendBuf)), strIp, kServerBroadcastPort); SPDLOG_INFO("receive query_server_ip,send res_server_ip"); } } } int WebsocketServer::run() { try { m_server.set_reuse_addr(true); m_server.listen(12236); // Start the server accept loop m_server.start_accept(); // Start the ASIO io_service run loop m_server.run(); } catch (websocketpp::exception const& e) { std::cout << e.what() << std::endl; return FAILURE; } catch (...) { SPDLOG_ERROR("other exception"); return FAILURE; } return FAILURE; } void WebsocketServer::monitorHeart() { prctl(PR_SET_NAME, "websocketSerMonitorHeart"); time_t now; while (1) { now = time(nullptr); { std::lock_guard<std::mutex> guard(m_connectMutex); for (auto it = m_connections.begin(); it != m_connections.end();) { if (now - it->second.timeLastHeart > 20)//超时未收到心跳,关闭连接 { SPDLOG_ERROR("heartbeat timeout,close connection,sessionid:{}", it->second.sessionid); m_server.pause_reading(it->first); m_server.close(it->first, 0, "timeout"); if (m_onCloseCb) m_onCloseCb(it->second.sessionid); m_connections.erase(it++); } else it++; } } sleep(5); } } void WebsocketServer::handleMsg() { prctl(PR_SET_NAME, "websocketSerMsgHandle"); while (1) { MsgHandler msgHandler; { std::unique_lock<std::mutex> lock(m_msgMutex); while (m_msgs.empty()) { cvMsg.wait(lock); } auto x = m_msgs.front(); msgHandler.connData.sessionid = x.connData.sessionid; msgHandler.msg = x.msg; m_msgs.pop_front(); } if (m_onMsgCb) m_onMsgCb(msgHandler.connData.sessionid, msgHandler.msg); } } /* * 功能:发送消息给ws客户端 * 参数: * 备注:如果需要打印发送的消息请填正确填写type,否则可不传递type值 * 示例:sendMsg(1000,"hello",11011)//打印发送的消息 * 示例:sendMsg(1000,"hello")//不打印发送的消息 */ void WebsocketServer::sendMsg(int sessionId, std::string& res, int type) { int idAct = sessionId / kMultiplyNum; connection_hdl hdl; SPDLOG_DEBUG("res to app/screen,msg={}", res); if (type != 0) { if (res.size() < 700) { SPDLOG_INFO("res to app/screen,msg={}", res); } else { SPDLOG_INFO("res to app/screen,msg= The first 300 characters: {}", res.substr(0, 300)); SPDLOG_INFO("res to app/screen,msg= The last 300 characters: {}", res.substr(res.size() - 301, 300)); } } try { std::lock_guard<std::mutex> guard(m_connectMutex); hdl = getHandleFromSessionId(idAct); m_server.send(hdl, res, websocketpp::frame::opcode::value::text); } catch (std::invalid_argument& info) { SPDLOG_ERROR("unrecognized sessionId,sessionId{} type {},msg{}", sessionId, type, info.what()); } catch (std::exception& e) { SPDLOG_ERROR("websocketpp-send:{}", e.what()); } catch (...) { SPDLOG_ERROR("websocketpp-send error"); } } void WebsocketServer::sendMsg2AllSessions(std::string& res) { SPDLOG_DEBUG("res to app/screen,msg={}", res); try { std::lock_guard<std::mutex> guard(m_connectMutex); for (const auto& kv : m_connections) { m_server.send(kv.first, res, websocketpp::frame::opcode::value::text); } } catch (std::exception& e) { SPDLOG_ERROR("websocketpp-send:{}", e.what()); } catch (...) { SPDLOG_ERROR("websocketpp-send error"); } }
25.867089
114
0.596036
tangtgithub
ac3f4f2db1413e6bb9307ec9355a83fe890d468a
4,665
cpp
C++
src/sources/colorschemes.cpp
Amuwa/TeXpen
d0d7ae74463f88980beb8ceb2958182ac2df021e
[ "MIT" ]
5
2019-03-04T08:47:52.000Z
2022-01-28T12:53:55.000Z
src/sources/colorschemes.cpp
Amuwa/TeXpen
d0d7ae74463f88980beb8ceb2958182ac2df021e
[ "MIT" ]
3
2019-02-22T05:41:49.000Z
2020-03-16T13:37:23.000Z
src/sources/colorschemes.cpp
Amuwa/TeXpen
d0d7ae74463f88980beb8ceb2958182ac2df021e
[ "MIT" ]
7
2019-02-22T06:04:13.000Z
2022-01-28T12:54:15.000Z
// Copyright (C) 2013 Alex-97 // This file is part of textpad-editor. // // textpad-editor 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. // // textpad-editor 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 textpad-editor. If not, see <http://www.gnu.org/licenses/>. #include "headers/mainwindow.h" #include <QAction> QString commentColor="#aaffaa"; void MainWindow::CreateStyle(int SelectedTheme) { Settings.ColorScheme = SelectedTheme; QString Color; QString BackgroundColor; QString SelectionColor; QString SelectionBackgroundColor; QString StyleSheet; switch (Settings.ColorScheme) { case 1: // This is the "Console" theme Color = "rgb(200, 200, 200)"; BackgroundColor = "#000000"; SelectionColor = "#000000"; SelectionBackgroundColor = "rgb(200, 200, 200)"; commentColor="#ddcc88"; ConsoleColor->setChecked(true); break; case 2: // This is the "Dusk" theme Color = ""; BackgroundColor = ""; SelectionColor = ""; SelectionBackgroundColor = ""; DuskColor->setChecked(true); commentColor="#2aff3a"; break; case 3: // This is the "Hacker" theme Color = "#00CC00"; BackgroundColor = "#000000"; SelectionColor = "#000000"; SelectionBackgroundColor = "#00CC00"; commentColor="#ff22ed"; HackerColor->setChecked(true); break; case 4: // This is the "Light" theme Color = "#000000"; BackgroundColor = "rgb(240, 240, 240)"; SelectionColor = "rgb(200, 200, 200)"; SelectionBackgroundColor = "rgb(40, 40, 40)"; LightColor->setChecked(true); commentColor="#11ff0a"; break; case 5: // This is the "Navy" theme Color = "rgb(237, 247, 241)"; BackgroundColor = "rgb(16, 28, 42)"; SelectionColor = "rgb(237, 247, 241)"; SelectionBackgroundColor = "rgb(24, 97, 129)"; commentColor="#4aff4a"; NavyColor->setChecked(true); break; case 6: // This is the "Night" theme Color = "rgb(234, 234, 234)"; BackgroundColor = "rgb(63, 63, 63)"; SelectionColor = "rgb(63, 63, 63)"; SelectionBackgroundColor = "rgb(206, 255, 132)"; commentColor="#8aff8f"; NightColor->setChecked(true); break; case 7: // This is the "Normal" theme Color.clear(); BackgroundColor.clear(); SelectionColor.clear(); SelectionBackgroundColor.clear(); commentColor="#66ff66"; NormalColor->setChecked(true); break; case 8: // This is the "Paper" theme Color = "#000000"; BackgroundColor = "rgb(248, 248, 248)"; SelectionColor = "#000000"; SelectionBackgroundColor = "rgb(206, 255, 132)"; commentColor="#66ff66"; PaperColor->setChecked(true); break; } QString StyleSheet2; if (SelectedTheme != 7) { // Create the stylesheet with the selected values StyleSheet = ("QPlainTextEdit {" "color: " + Color + ";" "background-color: " + BackgroundColor + ";" "selection-color: " + SelectionColor + ";" "selection-background-color: " + SelectionBackgroundColor + ";" "};" ); StyleSheet2 = ( "QTreeWidget {" "color: " + Color + ";" "background-color: " + BackgroundColor + ";" "selection-color: " + SelectionColor + ";" "selection-background-color: " + SelectionBackgroundColor + ";" "};" ); } else if (SelectedTheme == 7) { // Use the system style (Normal Color) StyleSheet.clear(); StyleSheet2.clear(); } TextEdit->setThemeId(Settings.ColorScheme); TextEdit->setStyleSheet(StyleSheet); structure->setStyleSheet(StyleSheet2); if(highlighter!=NULL){ highlighter->useTheme(Settings.ColorScheme); highlighter->rehighlight(); } }
33.321429
85
0.576849
Amuwa
ac3f94d6da833e652b1681c6e1dbc0f5049e3f5b
2,141
cpp
C++
src/amos/overlap.cpp
mariokostelac/asqg2afg
c40862046f04241c9091b5c55e53486953d4d67a
[ "MIT" ]
null
null
null
src/amos/overlap.cpp
mariokostelac/asqg2afg
c40862046f04241c9091b5c55e53486953d4d67a
[ "MIT" ]
3
2015-03-25T16:03:14.000Z
2015-03-28T10:42:17.000Z
src/amos/overlap.cpp
mariokostelac/asqg2afg
c40862046f04241c9091b5c55e53486953d4d67a
[ "MIT" ]
null
null
null
#include "overlap.h" using std::endl; namespace AMOS { Overlap::Overlap(const uint32_t r1, const uint32_t r2, const char adj, const int32_t ahg, const int32_t bhg, const int32_t scr) :read1(r1), read2(r2), adjacency(adj), a_hang(ahg), b_hang(bhg), score(scr) {} // from http://sourceforge.net/p/amos/mailman/message/19965222/. // // read a -------------------|--------------> bhang // read b ahang ---------------|---------------> // // read a -ahang ---------------|---------------> // read b -------------------|--------------> -bhang Overlap::Overlap(const uint32_t r1, const uint32_t r2, bool second_complement, const int32_t start1, const int32_t end1, const int32_t len1, const int32_t start2, const int32_t end2, const int32_t len2, const int32_t scr) :read1(r1), read2(r2), score(scr) { adjacency = second_complement ? 'I' : 'N'; int overlap_len_a = end1 - start1; int overlap_len_b = end2 - start2; int a_not_matching = len1 - overlap_len_a; int b_not_matching = len2 - overlap_len_b; if (start1 == 0 && end1 == len1) { // first contained a_hang = -start2; b_hang = len2 - end2; } else if (start2 == 0 && end2 == len2) { // second contained a_hang = start1; b_hang = -(len1 - end1); } else if (end1 == len1) { // first case from the comment a_hang = a_not_matching; b_hang = b_not_matching; } else if (end2 == len2) { // second case from the comment a_hang = -b_not_matching; b_hang = -a_not_matching; } else { fprintf(stderr, "%d %d %d, %d %d %d %c\n", start1, end1, len1, start2, end2, len2, adjacency); assert(false); } } ostream& operator << (ostream &o, const AMOS::Overlap& overlap) { o << "{OVL" << endl; o << "adj:" << overlap.adjacency << endl; o << "rds:" << overlap.read1 << "," << overlap.read2 << endl; o << "ahg:" << overlap.a_hang << endl; o << "bhg:" << overlap.b_hang << endl; o << "scr:" << overlap.score << endl; o << "}" << endl; return o; } }
33.453125
129
0.543204
mariokostelac
ac42f53847260c7eee0dc2492ba4bd3de38128c4
1,311
cpp
C++
Source/Collections/collectionspritesheetmodel.cpp
erayzesen/turquoise2D
33bd2e85169bba4c82c388c1619b2de55065eb7b
[ "Zlib" ]
13
2020-05-24T23:52:48.000Z
2020-12-01T02:43:03.000Z
Source/Collections/collectionspritesheetmodel.cpp
erayzesen/turquoise2D
33bd2e85169bba4c82c388c1619b2de55065eb7b
[ "Zlib" ]
3
2020-05-26T22:19:49.000Z
2020-12-01T09:31:25.000Z
Source/Collections/collectionspritesheetmodel.cpp
erayzesen/turquoise2D
33bd2e85169bba4c82c388c1619b2de55065eb7b
[ "Zlib" ]
3
2020-05-26T01:35:20.000Z
2020-05-26T13:51:07.000Z
#include "collectionspritesheetmodel.h" CollectionSpriteSheetModel::CollectionSpriteSheetModel(QObject *parent) : QStandardItemModel(parent) { } void CollectionSpriteSheetModel::setTarget(QString targetPath) { this->clear(); SpriteSheet *spriteSheet=new SpriteSheet(targetPath); QPixmap resourceImage(spriteSheet->resourceImagePath); for(int i=0;i<spriteSheet->frame.keys().count();i++){ //nss is a QStandartItem object QStandardItem *nss=new QStandardItem(); nss->setText(spriteSheet->frame.keys().at(i)); QPixmap iconImage=resourceImage.copy(spriteSheet->frame[spriteSheet->frame.keys().at(i)]); iconImage=iconImage.scaled(48,48,Qt::KeepAspectRatio); QIcon itemIcon(iconImage); nss->setIcon(itemIcon); nss->setDragEnabled(true); nss->setEditable(false); nss->setData(targetPath+"?frameName="+spriteSheet->frame.keys().at(i)); this->appendRow(nss); } } QMimeData *CollectionSpriteSheetModel::mimeData(const QModelIndexList &indexes) const { QList<QUrl> urls; for (int i=0; i<indexes.count(); i++){ QString data=this->data(indexes.at(i),Qt::UserRole+1).toString(); urls << QUrl(data); } QMimeData *data = new QMimeData(); data->setUrls(urls); return data; }
32.775
100
0.680397
erayzesen
ac44114138b8698bbe2b2385d2e2863ee32d543c
5,391
hpp
C++
src/gDeadCodeDeletion.hpp
lyj-514328/T1010
f6bd5a75b249abb63f5023f205ead28b133b3dbc
[ "Apache-2.0" ]
null
null
null
src/gDeadCodeDeletion.hpp
lyj-514328/T1010
f6bd5a75b249abb63f5023f205ead28b133b3dbc
[ "Apache-2.0" ]
null
null
null
src/gDeadCodeDeletion.hpp
lyj-514328/T1010
f6bd5a75b249abb63f5023f205ead28b133b3dbc
[ "Apache-2.0" ]
null
null
null
#ifndef GDEADCODEDELETION_HPP #define GDEADCODEDELETION_HPP #include <queue> #include "globalPolicyExecutor.hpp" using namespace std; class GDeadCodeDeletion: public GlobalPolicyExecutor { public: GDeadCodeDeletion(); ~GDeadCodeDeletion(); void runOptimizer(void); void printInfoOfOptimizer(void); bool runOptimizer(FunctionBlock* block, FuncPropertyGetter* funcPropertyGetter);//运行优化器 }; GDeadCodeDeletion::GDeadCodeDeletion(/* args */) { m_name = "死代码删除器"; } GDeadCodeDeletion::~GDeadCodeDeletion() { } void GDeadCodeDeletion::printInfoOfOptimizer(void) { } //TODO //删掉的变量名字也得抹去或者存起来 bool GDeadCodeDeletion::runOptimizer(FunctionBlock* block, FuncPropertyGetter* funcPropertyGetter) { //得到没有使用的节点 m_block = block; vector<BasicBlock*>& basicBlocks = m_block->getBasicBlocks(); unordered_map<string,SsaSymb*>& uName2SsaSymbs = m_block->getUName2SsaSymbs(); unordered_map<string,SsaSymb*>& tName2SsaSymbs = m_block->getTName2SsaSymbs(); queue<SsaSymb*> deadSymbList; while(!deadSymbList.empty())deadSymbList.pop(); unordered_map<string,SsaSymb*>::iterator it = uName2SsaSymbs.begin(); for(;it != uName2SsaSymbs.end();it++) { if(it->second->useTimes != 0)continue; deadSymbList.push(it->second); } it = tName2SsaSymbs.begin(); for(;it != tName2SsaSymbs.end();it++) { if(it->second->useTimes != 0)continue; deadSymbList.push(it->second); } //开始拓扑 vector<string> needDeleteVarList; needDeleteVarList.clear(); while(!deadSymbList.empty()) { SsaSymb* needDelVar = deadSymbList.front(); needDeleteVarList.push_back(needDelVar->name); deadSymbList.pop(); SsaTac* needDelTac = needDelVar->defPoint; switch(needDelTac->type) { case TAC_ADD: case TAC_SUB: case TAC_MUL: case TAC_DIV: case TAC_EQ: case TAC_MOD: case TAC_NE: case TAC_LT: case TAC_LE: case TAC_GT: case TAC_GE: case TAC_OR: case TAC_AND: if((needDelTac->second->type == SYM_VAR && needDelTac->second->name[0] == 'u') || needDelTac->second->name[0] == 't') { needDelTac->second->useTimes--; if(needDelTac->second->useTimes == 0) deadSymbList.push(needDelTac->second); //删掉 needDelTac->first 中对这个的使用链 deleteUseSsaTac(needDelTac->secondPoint); needDelTac->secondPoint = NULL; } if((needDelTac->third->type == SYM_VAR && needDelTac->third->name[0] == 'u') || needDelTac->third->name[0] == 't') { needDelTac->third->useTimes--; if(needDelTac->third->useTimes == 0) deadSymbList.push(needDelTac->third); //删掉 needDelTac->first 中对这个的使用链 deleteUseSsaTac(needDelTac->thirdPoint); needDelTac->thirdPoint = NULL; } needDelTac->type = TAC_UNDEF; break; case TAC_NEG: case TAC_POSI: case TAC_NOT: case TAC_COPY: if((needDelTac->second->type == SYM_VAR && needDelTac->second->name[0] == 'u') || needDelTac->second->name[0] == 't') { needDelTac->second->useTimes--; if(needDelTac->second->useTimes == 0) deadSymbList.push(needDelTac->second); //删掉 needDelTac->first 中对这个的使用链 deleteUseSsaTac(needDelTac->secondPoint); needDelTac->secondPoint = NULL; } needDelTac->type = TAC_UNDEF; break; case TAC_FORMAL: //什么也不做 break; case TAC_INSERT: { for(uint i = 0;i < needDelTac->functionSymb.size();i++) { //u0d0问题,为什么他的functionSymb2Tac[i]不为空呢 if(needDelTac->functionSymb2Tac[i]==NULL)continue; SsaSymb* varSymb = needDelTac->functionSymb[i]; if((varSymb->type == SYM_VAR && varSymb->name[0] == 'u') || varSymb->name[0] == 't') { varSymb->useTimes--; if(varSymb->useTimes == 0) deadSymbList.push(varSymb); //删掉 needDelTac->first 中对这个的使用链 deleteUseSsaTac(needDelTac->functionSymb2Tac[i]); needDelTac->functionSymb2Tac[i] = NULL; } } } needDelTac->type = TAC_UNDEF; break; case TAC_CALL: needDelTac->first = NULL; break; } } bool isOptimize = false; //清理垃圾 for(uint i = 0;i < basicBlocks.size();i++) { basicBlocks[i]->cleanDirtyTac(); } for(uint i = 0;i < needDeleteVarList.size();i++) { isOptimize = true; if(needDeleteVarList[i].c_str()[0] == 't') tName2SsaSymbs.erase(needDeleteVarList[i]); else uName2SsaSymbs.erase(needDeleteVarList[i]); } return isOptimize; } #endif
32.089286
82
0.540716
lyj-514328
ac44e91b8a2bed7692721a99119874dd88c0d31d
4,360
cc
C++
test/testsupport/file_utils_override.cc
shishuo365/webrtc
96e60852faaa8ab4cf6477fa92c80a434921625d
[ "BSD-3-Clause" ]
1
2016-06-23T01:26:53.000Z
2016-06-23T01:26:53.000Z
test/testsupport/file_utils_override.cc
shishuo365/webrtc
96e60852faaa8ab4cf6477fa92c80a434921625d
[ "BSD-3-Clause" ]
null
null
null
test/testsupport/file_utils_override.cc
shishuo365/webrtc
96e60852faaa8ab4cf6477fa92c80a434921625d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/testsupport/file_utils_override.h" #include <limits.h> #include <stdio.h> #if defined(WEBRTC_WIN) #include <direct.h> #include <tchar.h> #include <windows.h> #include <algorithm> #include <codecvt> #include <locale> #include "Shlwapi.h" #include "WinDef.h" #include "rtc_base/win32.h" #define GET_CURRENT_DIR _getcwd #else #include <unistd.h> #define GET_CURRENT_DIR getcwd #endif #if defined(WEBRTC_IOS) #include "test/testsupport/ios_file_utils.h" #endif #if defined(WEBRTC_MAC) #include "test/testsupport/mac_file_utils.h" #endif #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "rtc_base/arraysize.h" #include "rtc_base/checks.h" #include "rtc_base/string_utils.h" #include "rtc_base/strings/string_builder.h" namespace webrtc { namespace test { std::string DirName(absl::string_view path); bool CreateDir(absl::string_view directory_name); namespace internal { namespace { #if defined(WEBRTC_WIN) const absl::string_view kPathDelimiter = "\\"; #elif !defined(WEBRTC_IOS) const absl::string_view kPathDelimiter = "/"; #endif #if defined(WEBRTC_ANDROID) // This is a special case in Chrome infrastructure. See // base/test/test_support_android.cc. const absl::string_view kAndroidChromiumTestsRoot = "/sdcard/chromium_tests_root/"; #endif #if !defined(WEBRTC_IOS) const absl::string_view kResourcesDirName = "resources"; #endif } // namespace // Finds the WebRTC src dir. // The returned path always ends with a path separator. absl::optional<std::string> ProjectRootPath() { #if defined(WEBRTC_ANDROID) return std::string(kAndroidChromiumTestsRoot); #elif defined WEBRTC_IOS return IOSRootPath(); #elif defined(WEBRTC_MAC) std::string path; GetNSExecutablePath(&path); std::string exe_dir = DirName(path); // On Mac, tests execute in out/Whatever, so src is two levels up except if // the test is bundled (which our tests are not), in which case it's 5 levels. return DirName(DirName(exe_dir)) + std::string(kPathDelimiter); #elif defined(WEBRTC_POSIX) char buf[PATH_MAX]; ssize_t count = ::readlink("/proc/self/exe", buf, arraysize(buf)); if (count <= 0) { RTC_DCHECK_NOTREACHED() << "Unable to resolve /proc/self/exe."; return absl::nullopt; } // On POSIX, tests execute in out/Whatever, so src is two levels up. std::string exe_dir = DirName(absl::string_view(buf, count)); return DirName(DirName(exe_dir)) + std::string(kPathDelimiter); #elif defined(WEBRTC_WIN) wchar_t buf[MAX_PATH]; buf[0] = 0; if (GetModuleFileNameW(NULL, buf, MAX_PATH) == 0) return absl::nullopt; std::string exe_path = rtc::ToUtf8(std::wstring(buf)); std::string exe_dir = DirName(exe_path); return DirName(DirName(exe_dir)) + std::string(kPathDelimiter); #endif } std::string OutputPath() { #if defined(WEBRTC_IOS) return IOSOutputPath(); #elif defined(WEBRTC_ANDROID) return std::string(kAndroidChromiumTestsRoot); #else absl::optional<std::string> path_opt = ProjectRootPath(); RTC_DCHECK(path_opt); std::string path = *path_opt + "out"; if (!CreateDir(path)) { return "./"; } return path + std::string(kPathDelimiter); #endif } std::string WorkingDir() { #if defined(WEBRTC_ANDROID) return std::string(kAndroidChromiumTestsRoot); #else char path_buffer[FILENAME_MAX]; if (!GET_CURRENT_DIR(path_buffer, sizeof(path_buffer))) { fprintf(stderr, "Cannot get current directory!\n"); return "./"; } else { return std::string(path_buffer); } #endif } std::string ResourcePath(absl::string_view name, absl::string_view extension) { #if defined(WEBRTC_IOS) return IOSResourcePath(name, extension); #else absl::optional<std::string> path_opt = ProjectRootPath(); RTC_DCHECK(path_opt); rtc::StringBuilder os(*path_opt); os << kResourcesDirName << kPathDelimiter << name << "." << extension; return os.Release(); #endif } } // namespace internal } // namespace test } // namespace webrtc
27.25
80
0.730734
shishuo365
ac473557fd6afa3f80b11a1141f3ea757486d66a
1,203
hpp
C++
source/framework/benchmark/include/lue/framework/benchmark/algorithm_benchmark_result.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/benchmark/include/lue/framework/benchmark/algorithm_benchmark_result.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/benchmark/include/lue/framework/benchmark/algorithm_benchmark_result.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include "lue/framework/core/define.hpp" #include <array> #include <vector> namespace lue { namespace benchmark { class AlgorithmBenchmarkResult { public: using Shape = std::vector<Count>; AlgorithmBenchmarkResult()=default; explicit AlgorithmBenchmarkResult( Shape const& shape_in_partitions); template< Rank rank> explicit AlgorithmBenchmarkResult( std::array<Count, rank> const& shape_in_partitions): _shape_in_partitions{ shape_in_partitions.begin(), shape_in_partitions.end()} { } AlgorithmBenchmarkResult(AlgorithmBenchmarkResult const&)=default; AlgorithmBenchmarkResult(AlgorithmBenchmarkResult&&)=default; ~AlgorithmBenchmarkResult()=default; AlgorithmBenchmarkResult& operator=(AlgorithmBenchmarkResult const&)=default; AlgorithmBenchmarkResult& operator=(AlgorithmBenchmarkResult&&)=default; Shape const& shape_in_partitions () const; private: Shape _shape_in_partitions; }; } // namespace benchmark } // namespace lue
21.872727
85
0.645054
computationalgeography
ac4859011e0e731ce97983050e202023a458652c
2,056
cpp
C++
sp/src/game/client/fmod/fmodmanager.cpp
fuzzzzzz/jurassic-life
3105fe79977460c57c433cb960e91783d47626ed
[ "Unlicense" ]
1
2016-08-30T07:01:29.000Z
2016-08-30T07:01:29.000Z
sp/src/game/client/fmod/fmodmanager.cpp
fuzzzzzz/jurassic-life-code
3105fe79977460c57c433cb960e91783d47626ed
[ "Unlicense" ]
null
null
null
sp/src/game/client/fmod/fmodmanager.cpp
fuzzzzzz/jurassic-life-code
3105fe79977460c57c433cb960e91783d47626ed
[ "Unlicense" ]
3
2015-03-09T22:40:35.000Z
2019-02-17T16:15:44.000Z
#include "cbase.h" #include "FMODManager.h" #include "fmod_errors.h" #include <string> using namespace FMOD; EventSystem *pEventSystem; Event *pEvent = NULL; FMOD_RESULT result; CFMODManager gFMODMng; CFMODManager* FMODManager() { return &gFMODMng; } void ERRCHECK(FMOD_RESULT result) { if (result != FMOD_OK) { Warning("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result)); } } CFMODManager::CFMODManager() { } CFMODManager::~CFMODManager() { } // Starts FMOD void CFMODManager::InitFMOD( void ) { ERRCHECK(result = FMOD::EventSystem_Create(&pEventSystem)); ERRCHECK(result = pEventSystem->init(64, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL)); std::string path = engine->GetGameDirectory(); path += "\\"; DevMsg("FMOD path %s\n",path.c_str()); ERRCHECK(result = pEventSystem->setMediaPath(path.c_str())); } // Stops FMOD void CFMODManager::ExitFMOD( void ) { ERRCHECK(result = pEventSystem->release()); } bool CFMODManager::LoadDesignerFile(const char *filename) { if (m_sCurrentFile != filename) { m_sCurrentFile = filename; DevMsg("FMOD file : %s\n",filename); pEventSystem->unload(); ERRCHECK(result = pEventSystem->load(filename, 0, 0)); pEventSystem->update(); return result != 0; } return false; } void CFMODManager::UnloadDesignerFile() { pEventSystem->unload(); } bool CFMODManager::SetEvent(const char *eventName) { if (pEvent) pEvent->stop(); m_sCurrentEvent = eventName; ERRCHECK(result = pEventSystem->getEvent(eventName, FMOD_EVENT_DEFAULT, &pEvent)); if (pEvent) pEvent->start(); pEventSystem->update(); return true; } bool CFMODManager::SetParameter(const char *name, float value) { if (pEvent) { FMOD::EventParameter *param; //float param_min, param_max; ERRCHECK(result = pEvent->getParameter(name, &param)); //ERRCHECK(result = param->getRange(&param_min, &param_max)); ERRCHECK(result = param->setValue(value)); pEventSystem->update(); return true; } return false; } void CFMODManager::Stop() { if (pEvent) pEvent->stop(); }
18.522523
88
0.700389
fuzzzzzz
ac4ec0560a82acb465041daa6ed4e3bbf5303817
7,854
cpp
C++
examples/timelines/mainwindow.cpp
minimoog/QTweetLib
e8c62faccd38c694dcfc7a5d3e55982cf7daaffc
[ "Apache-2.0" ]
43
2015-02-27T07:55:10.000Z
2022-02-20T13:37:48.000Z
examples/timelines/mainwindow.cpp
minimoog/QTweetLib
e8c62faccd38c694dcfc7a5d3e55982cf7daaffc
[ "Apache-2.0" ]
3
2015-11-25T18:05:37.000Z
2019-07-24T19:58:32.000Z
examples/timelines/mainwindow.cpp
minimoog/QTweetLib
e8c62faccd38c694dcfc7a5d3e55982cf7daaffc
[ "Apache-2.0" ]
14
2015-01-29T18:50:58.000Z
2019-12-31T07:35:39.000Z
/* Copyright 2010 Antonie Jovanoski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include <QNetworkAccessManager> #include <QTimer> #include <QDateTime> #include "mainwindow.h" #include "ui_mainwindow.h" #include "oauthtwitter.h" #include "qtweethometimeline.h" #include "qtweetmentions.h" #include "qtweetusertimeline.h" #include "qtweetdirectmessages.h" #include "qtweetstatus.h" #include "qtweetdmstatus.h" #include "qtweetuser.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_sinceidHomeTimeline = 0; m_sinceidMentions = 0; m_sinceidUserTimeline = 0; m_sinceidDirectMessages = 0; m_oauthTwitter = new OAuthTwitter(this); m_oauthTwitter->setNetworkAccessManager(new QNetworkAccessManager(this)); connect(m_oauthTwitter, SIGNAL(authorizeXAuthFinished()), this, SLOT(xauthFinished())); connect(m_oauthTwitter, SIGNAL(authorizeXAuthError()), this, SLOT(xauthError())); m_timer = new QTimer(this); m_timer->setInterval(60000); connect(m_timer, SIGNAL(timeout()), this, SLOT(timerTimeOut())); connect(ui->authorizePushButton, SIGNAL(clicked()), this, SLOT(authorizeButtonClicked())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } void MainWindow::authorizeButtonClicked() { m_oauthTwitter->authorizeXAuth(ui->usernameLineEdit->text(), ui->passwordLineEdit->text()); } void MainWindow::xauthFinished() { ui->statusBar->showMessage("xauth succesfull"); m_timer->start(); timerTimeOut(); } void MainWindow::xauthError() { ui->statusBar->showMessage("xauth failed"); } void MainWindow::timerTimeOut() { QTweetHomeTimeline *homeTimeline = new QTweetHomeTimeline(m_oauthTwitter, this); homeTimeline->fetch(m_sinceidHomeTimeline); connect(homeTimeline, SIGNAL(parsedStatuses(QList<QTweetStatus>)), this, SLOT(homeTimelineStatuses(QList<QTweetStatus>))); QTweetMentions *mentions = new QTweetMentions(m_oauthTwitter, this); mentions->fetch(m_sinceidMentions); connect(mentions, SIGNAL(parsedStatuses(QList<QTweetStatus>)), this, SLOT(mentionsStatuses(QList<QTweetStatus>))); QTweetUserTimeline *userTimeline = new QTweetUserTimeline(m_oauthTwitter, this); userTimeline->fetch(0, QString(), m_sinceidUserTimeline); connect(userTimeline, SIGNAL(parsedStatuses(QList<QTweetStatus>)), this, SLOT(userTimelineStatuses(QList<QTweetStatus>))); QTweetDirectMessages *dmTimeline = new QTweetDirectMessages(m_oauthTwitter, this); dmTimeline->fetch(m_sinceidDirectMessages); connect(dmTimeline, SIGNAL(parsedDirectMessages(QList<QTweetDMStatus>)), this, SLOT(directMessages(QList<QTweetDMStatus>))); } void MainWindow::homeTimelineStatuses(const QList<QTweetStatus> &statuses) { QTweetHomeTimeline *homeTimeline = qobject_cast<QTweetHomeTimeline*>(sender()); if (homeTimeline) { if (statuses.count()) { //order is messed up, but this is just example foreach (const QTweetStatus& status, statuses) { ui->homeTimelineTextEdit->append("id: " + QString::number(status.id())); ui->homeTimelineTextEdit->append("text: " + status.text()); ui->homeTimelineTextEdit->append("created: " + status.createdAt().toString()); QTweetUser userinfo = status.user(); ui->homeTimelineTextEdit->append("screen name: " + userinfo.screenName()); ui->homeTimelineTextEdit->append("user id: " + QString::number(userinfo.id())); //is it retweet? QTweetStatus rtStatus = status.retweetedStatus(); if (rtStatus.id()) { ui->homeTimelineTextEdit->append("retweet text: " + rtStatus.text()); } ui->homeTimelineTextEdit->append("----------------------------------------"); } m_sinceidHomeTimeline = statuses.at(0).id(); } homeTimeline->deleteLater(); } } void MainWindow::mentionsStatuses(const QList<QTweetStatus> &statuses) { QTweetMentions *mentions = qobject_cast<QTweetMentions*>(sender()); if (mentions) { if (statuses.count()) { foreach (const QTweetStatus& status, statuses) { ui->mentionsTextEdit->append("id: " + QString::number(status.id())); ui->mentionsTextEdit->append("text: " + status.text()); ui->mentionsTextEdit->append("created: " + status.createdAt().toString()); QTweetUser userinfo = status.user(); ui->mentionsTextEdit->append("screen name: " + userinfo.screenName()); ui->mentionsTextEdit->append("user id: " + QString::number(userinfo.id())); ui->mentionsTextEdit->append("----------------------------------------"); } m_sinceidMentions = statuses.at(0).id(); } mentions->deleteLater(); } } void MainWindow::userTimelineStatuses(const QList<QTweetStatus> &statuses) { QTweetUserTimeline *userTimeline = qobject_cast<QTweetUserTimeline*>(sender()); if (userTimeline) { if (statuses.count()) { //order is messed up, but this is just example foreach (const QTweetStatus& status, statuses) { ui->userTimelineTextEdit->append("id: " + QString::number(status.id())); ui->userTimelineTextEdit->append("text: " + status.text()); ui->userTimelineTextEdit->append("created: " + status.createdAt().toString()); QTweetUser userinfo = status.user(); ui->userTimelineTextEdit->append("screen name: " + userinfo.screenName()); ui->userTimelineTextEdit->append("user id: " + QString::number(userinfo.id())); ui->userTimelineTextEdit->append("----------------------------------------"); } m_sinceidUserTimeline = statuses.at(0).id(); } userTimeline->deleteLater(); } } void MainWindow::directMessages(const QList<QTweetDMStatus> &directMessages) { QTweetDirectMessages *dmTimeline = qobject_cast<QTweetDirectMessages*>(sender()); if (dmTimeline) { if (directMessages.count()) { foreach (const QTweetDMStatus& message, directMessages) { ui->directMessagesTextEdit->append("id: " + QString::number(message.id())); ui->directMessagesTextEdit->append("text: " + message.text()); ui->directMessagesTextEdit->append("created: " + message.createdAt().toString()); ui->directMessagesTextEdit->append("sender: " + message.senderScreenName()); ui->directMessagesTextEdit->append("sender id: " + QString::number(message.senderId())); ui->directMessagesTextEdit->append("----------------------------------------"); } m_sinceidDirectMessages = directMessages.at(0).id(); } } dmTimeline->deleteLater(); }
35.378378
104
0.640183
minimoog
ac535f91559ae32147aa093d38dd8501dc35413a
5,346
cpp
C++
src/libs/qlib/qradio.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qradio.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qradio.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QRadio - radio buttons * 18-06-97: Created! * (C) MarketGraph/RVG */ #include <qlib/radio.h> #include <qlib/canvas.h> #include <qlib/event.h> #include <qlib/app.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <limits.h> #include <time.h> #include <qlib/debug.h> DEBUG_ENABLE #define QBSW 4 // Shadow size #define BOXSIZE 16 // Checkbox size #define BOXSPACE 4 // Space between box & text QRadio::QRadio(QWindow *parent,QRect *ipos,string itext,int igroup) : QWindow(parent,ipos->x,ipos->y,ipos->wid,ipos->hgt) { //printf("QRadio ctor, text=%p this=%p\n",itext,this); //printf("button '%s'\n",itext); // Shadow lines colText=new QColor(0,0,0); font=app->GetSystemFont(); if(itext) text=qstrdup(itext); else text=0; group=igroup; // Size check so it fits text if(text) { Size(font->GetWidth(text)+BOXSPACE+BOXSIZE,font->GetHeight(text)); //pos.wid=font->GetWidth(text)+BOXSPACE+BOXSIZE; //pos.hgt=font->GetHeight(text); //if(pos.hgt<BOXSIZE)pos.hgt=BOXSIZE; } state=DISARMED; chkState=0; // No shortcut key scKey=0; scMod=0; eventType=QEVENT_CLICK; Create(); // Take minimal amount of events // Include keystrokes because a shortcut key may be assigned to each button Catch(CF_BUTTONPRESS|CF_BUTTONRELEASE|CF_KEYPRESS); //printf("QRadio ctor RET\n"); } QRadio::~QRadio() { } void QRadio::SetText(string ntext) { if(text)qfree(text); text=qstrdup(ntext); } void QRadio::SetTextColor(QColor *col) { colText->SetRGBA(col->GetR(),col->GetG(),col->GetB(),col->GetA()); } void QRadio::SetState(bool yn) { chkState=yn; } void QRadio::Paint(QRect *r) { QRect rr; int sw=4; // Shadow width/height Restore(); // Paint insides //cv->Insides(pos.x,pos.y,BOXSIZE,BOXSIZE); //qdbg("inside\n"); #ifdef OBS // Paint border if(state==ARMED) cv->Inline(pos.x,pos.y,BOXSIZE,BOXSIZE); else cv->Outline(pos.x,pos.y,BOXSIZE,BOXSIZE); #endif QRect pos; GetPos(&pos); pos.x=0; pos.y=0; pos.y+=2; // Offset for SGI cv->SetColor(80,80,80); cv->Rectfill(pos.x+4,pos.y+0,4,1); cv->Rectfill(pos.x+2,pos.y+1,1,3); cv->Rectfill(pos.x+1,pos.y+2,3,1); cv->Rectfill(pos.x+0,pos.y+4,1,4); cv->Rectfill(pos.x+1,pos.y+9,1,1); cv->Rectfill(pos.x+2,pos.y+10,2,1); cv->Rectfill(pos.x+4,pos.y+11,5,1); cv->Rectfill(pos.x+9,pos.y+1,1,1); cv->Rectfill(pos.x+10,pos.y+2,1,2); cv->Rectfill(pos.x+11,pos.y+4,1,5); cv->Rectfill(pos.x+9,pos.y+9,1,1); cv->Rectfill(pos.x+10,pos.y+9,1,1); cv->SetColor(0,0,0); cv->Rectfill(pos.x+3,pos.y+1,6,1); cv->Rectfill(pos.x+2,pos.y+2,1,1); cv->Rectfill(pos.x+9,pos.y+2,1,1); cv->Rectfill(pos.x+1,pos.y+3,1,6); cv->Rectfill(pos.x+2,pos.y+9,1,1); cv->SetColor(255,255,255); cv->Rectfill(pos.x+4,pos.y+12,5,1); cv->Rectfill(pos.x+9,pos.y+11,2,1); cv->Rectfill(pos.x+11,pos.y+9,1,2); cv->Rectfill(pos.x+12,pos.y+4,1,5); cv->SetColor(255,255,255); cv->Rectfill(pos.x+4,pos.y+2,5,9); cv->Rectfill(pos.x+3,pos.y+3,7,7); cv->Rectfill(pos.x+2,pos.y+4,9,5); if(chkState!=0) { // Hilite dot cv->SetColor(80,80,80); cv->Rectfill(pos.x+5,pos.y+3,3,7); cv->Rectfill(pos.x+3,pos.y+5,7,3); cv->SetColor(0,0,0); cv->Rectfill(pos.x+4,pos.y+4,5,5); } pos.y-=2; //skip_shadow2: // Draw text if any if(text) { int tx,ty,twid,thgt; cv->SetColor(colText); cv->SetFont(font); // Align just outside rect thgt=font->GetHeight(); twid=font->GetWidth(text); tx=pos.x+BOXSIZE+BOXSPACE; ty=(pos.hgt-thgt)/2+pos.y; /*printf("twid=%d, hgt=%d, x=%d, y=%d (pos=%d,%d %dx%d)\n", twid,thgt,tx,ty,pos.x,pos.y,pos.wid,pos.hgt);*/ cv->Text(text,tx,ty); //skip_text:; } //qdbg(" paint RET\n"); } // Events bool QRadio::EvButtonPress(int button,int x,int y) { //qdbg("QRadio::EvButtonPress\n"); state=ARMED; Paint(); //Focus(TRUE); return TRUE; } bool QRadio::EvButtonRelease(int button,int x,int y) { QEvent e; QWindow *w; int i; //qdbg("QRadio::EvButtonRelease, this=%p\n",this); if(state==DISARMED)return FALSE; state=DISARMED; // Deselect other radio buttons belonging to this group for(i=0;;i++) { w=app->GetWindowManager()->GetWindowN(i); if(!w)break; if(!strcmp(w->ClassName(),"radio")) // RTTI? { QRadio *r=(QRadio*)w; if(r->GetGroup()==group) { r->SetState(0); r->Paint(); } } } // Select this one chkState=1; Paint(); //Focus(FALSE); // Generate click event e.type=eventType; e.win=this; app->GetWindowManager()->PushEvent(&e); return TRUE; } bool QRadio::EvKeyPress(int key,int x,int y) { //printf("QRadio keypress $%x @%d,%d\n",key,x,y); if(scKey==key) { // Simulate button press EvButtonPress(1,x,y); QNap(CLK_TCK/50); // Make sure it shows EvButtonRelease(1,x,y); return TRUE; // Eat the event } return FALSE; } // Behavior void QRadio::ShortCut(int key,int mod) { //printf("shortcut %x %x\n",key,mod); scKey=key; scMod=mod; } void QRadio::SetEventType(int eType) // If eType==0, normal click events are generated // Otherwise, special 'eType' events are generated // eType must be a user event { if(eType==0) { eventType=QEVENT_CLICK; } else { QASSERT_V(eType>=QEVENT_USER); // Button event type eventType=eType; } }
22.944206
77
0.628133
3dhater
ac577bc5604480c2e4d50d1da27b24dfba807e77
1,312
hpp
C++
include/nbdl/detail/wrap_promise.hpp
ricejasonf/nbdl
ae63717c96ab2c36107bc17b2b00115f96e9d649
[ "BSL-1.0" ]
47
2016-06-20T01:41:24.000Z
2021-11-16T10:53:27.000Z
include/nbdl/detail/wrap_promise.hpp
ricejasonf/nbdl
ae63717c96ab2c36107bc17b2b00115f96e9d649
[ "BSL-1.0" ]
21
2015-11-12T23:05:47.000Z
2019-07-17T19:01:40.000Z
include/nbdl/detail/wrap_promise.hpp
ricejasonf/nbdl
ae63717c96ab2c36107bc17b2b00115f96e9d649
[ "BSL-1.0" ]
6
2015-11-12T21:23:29.000Z
2019-05-09T17:54:25.000Z
// // Copyright Jason Rice 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 NBDL_DETAIL_WRAP_PROMISE_HPP #define NBDL_DETAIL_WRAP_PROMISE_HPP #include <nbdl/fwd/detail/wrap_promise.hpp> #include <nbdl/promise.hpp> #include <nbdl/fwd/detail/promise_join.hpp> #include <boost/hana/core/is_a.hpp> #include <stdexcept> #include <utility> namespace nbdl::detail { namespace hana = boost::hana; // Implicity wraps functions // and pipes // with the promise interface. template <typename X> auto wrap_promise_fn::operator()(X&& x) const { if constexpr(hana::is_a<promise_tag, X>()) { return std::forward<X>(x); } else { auto temp = std::forward<X>(x); //?? return nbdl::promise([fn = std::move(temp)](auto&& resolver, auto&& ...args) { using Return = decltype(fn(std::forward<decltype(args)>(args)...)); // handle void edge case if constexpr(std::is_void<Return>::value) { fn(std::forward<decltype(args)>(args)...); resolver.resolve(); } else { resolver.resolve(fn(std::forward<decltype(args)>(args)...)); } }); } }; } #endif
23.854545
82
0.622713
ricejasonf
ac61ce543c9bb87ada9d46abdb4d10bacb997906
32,116
cpp
C++
OS2.1/CPinti/core/core.cpp
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
1
2021-05-05T20:42:24.000Z
2021-05-05T20:42:24.000Z
OS2.1/CPinti/core/core.cpp
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
null
null
null
OS2.1/CPinti/core/core.cpp
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
null
null
null
/* ============================================= == CPinti ---> Gestionnaire de threads == ============================================= Developpe entierement par Sebastien FAVIER Description Module permettant la commutation des threads en se basant sur le PIT Creation 17/05/2018 Mise a jour 22/01/2019 */ #include <iostream> #include <stdlib.h> #include <string.h> #include <time.h> #include <dos.h> #include <signal.h> #include <math.h> #include <cstdio> #include <unistd.h> #include <cstdlib> #include <stdio.h> #include <dpmi.h> #include "debug.h" #include "Func_cpi.h" #include "core.h" // #include "leakchk.h" extern "C" long cpc_clean (); namespace cpinti { namespace gestionnaire_tache { void IamInLive() { // Ne pas calculer si le CPU est en evaluation if(EVALUATION_CPU == false) { begin_SectionCritique(); // Cette fonction met a jour les cycles CPU // ce qui permet d'estimer avec une precision de 60% // de la charge du CPU InLiveCompteur++; if(InLiveCompteur > 27483600) // unsigned long InLiveCompteur = 0; // On reinitialise pour eviter les plantages // Ceci permet d'economiser du temps CPU saut_comptage++; if(saut_comptage > 24) { saut_comptage = 0; time(&Temps_Actuel); Temps_total = difftime(Temps_Actuel, Temps_Depart); if(Temps_total >= 1) // Si 1 seconde { NombreCycles = InLiveCompteur; InLiveCompteur = 0; // On reset le compteur time(&Temps_Depart); } } end_SectionCritique(); } } void eval_cycle_cpu() { // Permet d'evaluer le CPU de maniere breve en 1 seconde // Notifier pour ne pas fausser le resultat EVALUATION_CPU = true; time(&Temps_Actuel); time(&Temps_Depart); InLiveCompteur = 0; while(Temps_total <= 1) { InLiveCompteur++; if(InLiveCompteur > 27483600) // unsigned long if(InLiveCompteur > 27483600) // unsigned long break; // On reinitialise pour eviter les plantages doevents(1); time(&Temps_Actuel); Temps_total = difftime(Temps_Actuel, Temps_Depart); } // Recuperer le nombre MAX de cycles NombreCyles_MAX = (InLiveCompteur * 3) - (InLiveCompteur / 4); // 3 car il y a 3 ImInLive() EVALUATION_CPU = false; } unsigned long get_cycle_MAX_cpu() { if(NombreCyles_MAX <= 0) NombreCyles_MAX = 10; return NombreCyles_MAX; } unsigned long get_cycle_cpu() { if(NombreCycles > NombreCyles_MAX) return NombreCyles_MAX; else if(NombreCycles <= 0) return 0; else return NombreCycles; } volatile long SectionCritique_RECURSIF = 0; void begin_SectionCritique() { // Rendre le systeme non interruptible SECTION_CRITIQUE = true; disable(); // Plus on l'appel plus il faudra le remonter pour finir la scope SectionCritique_RECURSIF++; } void end_SectionCritique() { // Rendre le systeme interruptible SectionCritique_RECURSIF--; // Rendre interruptible quand le compteur sera a zero if(SectionCritique_RECURSIF <=0) { SectionCritique_RECURSIF = 0; SECTION_CRITIQUE = false; enable(); } } bool state_SectionCritique() { // Retourner l'etat de la section critique return SECTION_CRITIQUE; } bool initialiser_Multitache() { // Initialiser le multitasking void* test = malloc(123); cpinti_dbg::CPINTI_DEBUG("Preparation du multitache en cours.", "Preparating multitask in progress. ", "core::gestionnaire_tache", "initialiser_Multitache()", Ligne_saute, Alerte_surbrille, Date_avec, Ligne_r_normal); time(&Temps_Depart); // Interdire toutes interruptions begin_SectionCritique(); // Allouer un espace memoire pour chaque threads for(long index_id = 0; index_id <= MAX_THREAD-1; index_id++) { Liste_Threads[index_id].Etat_Thread = _ARRETE; Liste_Threads[index_id].Priorite = 0; Liste_Threads[index_id].KID = 0; Liste_Threads[index_id].OID = 0; Liste_Threads[index_id].UID = 0; Liste_Threads[index_id].PID = 0; // strncpy((char*) Liste_Threads[index_id].Nom_Thread, (const char*) '\0', 32); } /*** Creer un thread principal "Thread_Updater" ***/ cpinti_dbg::CPINTI_DEBUG("Creation du thread principal 'Thread_Updater'...", "Creating main thread 'Thread_Updater'...", "core::gestionnaire_tache", "initialiser_Multitache()", Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal); // Incremente le nombre de threads Nombre_Threads++; // Priorite Liste_Threads[0].Priorite = _PRIORITE_THRD_FAIBLE; // Son numero de TID (Thread IDentifiant) Liste_Threads[0].TID = 0; // Etat en execution (A modifier en PAUSE) Liste_Threads[0].Etat_Thread = _EN_EXECUTION; Liste_Threads[0].DM_arret = false; long toto = 0; pthread_create(&Liste_Threads->thread, NULL, Thread_Updater, (void*) &toto); // std::string offset_fonction = std::to_string((unsigned long) Thread_Updater); cpinti_dbg::CPINTI_DEBUG(" [OK] TID:0. Fonction offset 0x" + std::to_string((unsigned long) Thread_Updater), " [OK] TID:0. Offset function 0x" + std::to_string((unsigned long) Thread_Updater), "", "", Ligne_saute, Alerte_validation, Date_sans, Ligne_r_normal); // Reexecuter le scheduler normalement end_SectionCritique(); Thread_en_cours = 0; Interruption_Timer(0); // Retourner l'ID return true; } bool fermer_core() { unsigned long nombre_threads = 0; // Cette fonction permet de fermer le core en terminant tous les threads for(unsigned long boucle = 1; boucle < MAX_THREAD; boucle++) { // Si le thread n'est pas arrete ou n'est pas zombie on ferme if(Liste_Threads[boucle].Etat_Thread != _ARRETE) if(Liste_Threads[boucle].Etat_Thread != _ZOMBIE) { nombre_threads++; supprimer_Thread(boucle, false); } } std::string nombre_threads_STR = std::to_string((unsigned long) nombre_threads); cpinti_dbg::CPINTI_DEBUG("Signal de fermeture envoye aux " + nombre_threads_STR + " thread(s). Attente", "Closing signal sent to " + nombre_threads_STR + " threads(s). Waiting", "", "", Ligne_saute, Alerte_avertissement, Date_sans, Ligne_r_normal); fflush(stdout); // On attend un peut usleep(1500000); fflush(stdout); // Bloquer tout autres interruptions ENTRER_SectionCritique(); unsigned long Nombre_Zombie = check_Thread_zombie(true, true); std::string Nombre_Zombie_STR = std::to_string((unsigned long) Nombre_Zombie); cpinti_dbg::CPINTI_DEBUG(Nombre_Zombie_STR + " thread(s) zombies ferme(s) sur " + nombre_threads_STR, Nombre_Zombie_STR + " zombies thread(s) closed on " + nombre_threads_STR, "", "", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); puts("Bye from kernel\n"); // cpc_clean(); // Activer les interruptions materiel enable(); exit(0); return true; } /******** PROCESSUS ********/ unsigned long get_EtatProcessus(unsigned long PID) { // Obtenir l'etat d'un processus return Liste_Processus[PID].Etat_Processus; } void set_EtatProcessus(unsigned long PID, unsigned long Etat) { // Definir l'etat d'un processus Liste_Processus[PID].Etat_Processus = Etat; } unsigned long get_NombreProcessus() { // Retourner le nombre de threads en cours return Nombre_Processus; } unsigned long ajouter_Processus(const char* NomProcessus) { // Cette fonction permet de creer un processus pour heberger des threads std::string NomProcessus_STR = NomProcessus; // Si on atteint le nombre maximum de processus if(Nombre_Processus >= MAX_PROCESSUS) { std::string nombre_processus_STR = std::to_string((unsigned long) MAX_PROCESSUS); cpinti_dbg::CPINTI_DEBUG("[ERREUR] Impossible d'attribuer un nouveau PID. Le nombre est fixe a " + nombre_processus_STR + " processus maximum.", "[ERROR] Unable to attrib new PID. The maximal process number value is " + nombre_processus_STR, "", "", Ligne_saute, Alerte_erreur, Date_avec, Ligne_r_normal); return 0; } cpinti_dbg::CPINTI_DEBUG("Creation du processus '" + NomProcessus_STR + "'...", "Creating process '" + NomProcessus_STR + "'...", "core::gestionnaire_tache", "ajouter_Processus()", Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal); unsigned long Nouveau_PID = 0; // Rechercher un emplacement ID vide for(unsigned long b = 1; b <= MAX_PROCESSUS; b++) { if(Liste_Processus[b].PID == 0) { Nouveau_PID = b; break; } } if(Nouveau_PID == 0) { std::string nombre_threads_STR = std::to_string((unsigned long) MAX_THREAD); cpinti_dbg::CPINTI_DEBUG(" [ERREUR] Impossible d'attribuer un nouveau PID. Aucune zone memoire libere", " [ERROR] Unable to attrib new PID. No free memory", "", "", Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal); return 0; } // Incremente le nombre de processus Nombre_Processus++; // Nom du processus strncpy((char*) Liste_Processus[Nouveau_PID].Nom_Processus, NomProcessus, 32); // Son numero de TID (Thread IDentifiant) Liste_Processus[Nouveau_PID].PID = Nouveau_PID; // Etat en execution Liste_Processus[Nouveau_PID].Etat_Processus = _EN_EXECUTION; std::string Nouveau_PID_STR = std::to_string((unsigned long) Nouveau_PID); cpinti_dbg::CPINTI_DEBUG(" [OK] PID " + Nouveau_PID_STR + ".", " [OK] PID " + Nouveau_PID_STR + ".", "", "", Ligne_saute, Alerte_validation, Date_sans, Ligne_r_normal); // Retourner l'ID return Nouveau_PID; } bool supprimer_Processus(unsigned long pid, bool force) { // Cette fonction permet de signaler l'arret d'un processus // et donc de tous ses threads // si force=true volatile long compteur_thread = 0; if(pid == 0) return false; // std::string pid_STR = std::to_string((unsigned long) pid); if (Liste_Processus[pid].Etat_Processus == _ARRETE) { cpinti_dbg::CPINTI_DEBUG("Le processus " + std::to_string((unsigned long) pid) + " est deja arrete", "Process " + std::to_string((unsigned long) pid) + " is already stopped", "", "", Ligne_saute, Alerte_avertissement, Date_sans, Ligne_r_normal); } else if (Liste_Processus[pid].Etat_Processus == _EN_ARRET) { cpinti_dbg::CPINTI_DEBUG("Arret du processus " + std::to_string((unsigned long) pid) + " deja signale", "Process stopping " + std::to_string((unsigned long) pid) + " is already signaled", "", "", Ligne_saute, Alerte_avertissement, Date_sans, Ligne_r_normal); } else { cpinti_dbg::CPINTI_DEBUG("Arret du processus PID " + std::to_string((unsigned long) pid) + " en cours...", "Stopping process PID " + std::to_string((unsigned long) pid) + " in progress", "core::gestionnaire_tache", "supprimer_Processus()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); // Mettre le processus en etat STOP = 0 Liste_Processus[pid].Etat_Processus = _EN_ARRET; // Signaler l'arret a tous les threads heberges for(unsigned long tid = 1; tid < MAX_THREAD; tid++) { // Si le thread est bien heberge dans le processus if(Liste_Processus[pid].Threads_Enfant[tid] == true) { // Attendre 1ms entre chaque signalements usleep(100); // On signale l'arret du thread supprimer_Thread(tid, false); // Compter le nombre de threads signales compteur_thread++; } // Dans tous les cas on met a FALSE Liste_Processus[pid].Threads_Enfant[tid] = false; } cpinti_dbg::CPINTI_DEBUG("P4", "P4", "", "", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); // Attendre 10ms pour etre SAFE // usleep(1000); cpinti_dbg::CPINTI_DEBUG("P5", "P5", "", "", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); if(compteur_thread > 0) { // std::string compteur_thread_STR = std::to_string(compteur_thread); // Declarer le processus mort (On conserve certaines infos pour le debug) cpinti_dbg::CPINTI_DEBUG("Un signal d'arret a ete envoye a " + std::to_string(compteur_thread) + " thread(s)", "Stopping signal has been sent to " + std::to_string(compteur_thread) + " thread(s)", "core::gestionnaire_tache", "supprimer_Processus()", Ligne_saute, Alerte_ok, Date_avec, Ligne_r_normal); } else { cpinti_dbg::CPINTI_DEBUG("Aucun threads heberge dans le processus. Hm.. parfait!", "Nothing hosted threads in the process. Hm.. perfect!", "core::gestionnaire_tache", "supprimer_Processus()", Ligne_saute, Alerte_ok, Date_avec, Ligne_r_normal); } // Declarer le processus mort (On conserve certaines infos pour le debug) cpinti_dbg::CPINTI_DEBUG("Envoi d'un signal d'arret au processus (Attente de la fermeture des threads) ...", "Sending stopping signal to process (Waiting threads closing) ...", "core::gestionnaire_tache", "supprimer_Processus()", Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal); if(Liste_Processus[pid].Nom_Processus != NULL) memset(Liste_Processus[pid].Nom_Processus, 0, 32); // free(Liste_Processus[pid].Nom_Processus); Liste_Processus[pid].Etat_Processus = _ARRETE; Liste_Processus[pid].PID = 0; cpinti_dbg::CPINTI_DEBUG(" [OK]", " [OK]", "", "", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); } Nombre_Processus--; cpinti_dbg::CPINTI_DEBUG("Processus " + std::to_string((unsigned long) pid) + " supprime!", "Process " + std::to_string((unsigned long) pid) + " deleted!", "core::gestionnaire_tache", "supprimer_Processus()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); return true; } /******** THREADS ********/ unsigned long get_EtatThread(unsigned long TID) { return Liste_Threads[TID].Etat_Thread; } void set_EtatThread(unsigned long TID, unsigned long Etat) { Liste_Threads[TID].Etat_Thread = Etat; } const char* get_NomThread(unsigned long TID) { return (const char*) Liste_Threads[TID].Nom_Thread; } unsigned long get_NombreThreads() { // Retourner le nombre de threads en cours return Nombre_Threads; } unsigned long get_NombreTimer() { // Retourner le nombre de timer executes return Nombre_Timer; } unsigned long get_ThreadEnCours() { // Retourner la thread en cours return Thread_en_cours; } unsigned long ajouter_Thread(void* (* Fonction) (void* arg), const char* NomThread, unsigned long pid, long Priorite, unsigned long Arguments) { // Cette fonction permet d'ajouter une thread (Thread) unsigned long Nouveau_TID = 0; // std::string NomThread_STR = NomThread; // Si on atteint le nombre maximum de threads if(Nombre_Threads >= MAX_THREAD) { // std::string nombre_threads_STR = std::to_string((unsigned long) MAX_THREAD); cpinti_dbg::CPINTI_DEBUG("[ERREUR] Impossible d'attribuer un nouveau TID. Le nombre est fixe a " + std::to_string(MAX_THREAD) + " thread(s) maximum.", "[ERROR] Unable to attrib new TID. The maximal thread(s) number value is " + std::to_string(MAX_THREAD), "", "ajouter_Thread()", Ligne_saute, Alerte_erreur, Date_avec, Ligne_r_normal); return 0; } std::string pid_STR = std::to_string((unsigned long) pid); cpinti_dbg::CPINTI_DEBUG("Creation du thread '" + std::string(NomThread) + "' dans le processus " + pid_STR + "...", "Creating thread '" + std::string(NomThread) + "' in the process " + pid_STR + "...", "core::gestionnaire_tache", "ajouter_Thread()", Ligne_reste, Alerte_action, Date_avec, Ligne_r_normal); // Si le processus n'existe pas if(Liste_Processus[pid].PID != pid) { cpinti_dbg::CPINTI_DEBUG(" [ERREUR] Le PID " + pid_STR + " n'existe pas. Impossible d'heberger un nouveau thread.", " [ERROR] PID " + pid_STR + " not exist. Unable to host the new thread.", "", "ajouter_Thread()", Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal); return 0; } ENTRER_SectionCritique(); // Rechercher un emplacement ID vide for(unsigned long b = 1; b <= MAX_THREAD; b++) { if(Liste_Threads[b].PID == 0) { Nouveau_TID = b; break; } } if(Nouveau_TID == 0) { cpinti_dbg::CPINTI_DEBUG(" [ERREUR] Impossible d'attribuer un nouveau TID. Aucune zone memoire libere", " [ERROR] Unable to attrib new TID. No free memory", "core::gestionnaire_tache", "ajouter_Thread()", Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal); SORTIR_SectionCritique(); return 0; } // Incremente le nombre de threads Nombre_Threads++; // Nom du thread strncpy((char*) Liste_Threads[Nouveau_TID].Nom_Thread, NomThread, 30); // Corriger les priorites if(Liste_Threads[Thread_en_cours].Priorite < 2) Priorite = 2; else if(Liste_Threads[Thread_en_cours].Priorite > MAX_CYCLES) Priorite = MAX_CYCLES; // Priorite Liste_Threads[Nouveau_TID].Priorite = Priorite; // Son numero de PID (Processus IDentifiant) Liste_Threads[Nouveau_TID].PID = pid; // Son numero de TID (Thread IDentifiant) Liste_Threads[Nouveau_TID].TID = Nouveau_TID; // Etat en execution (A modifier en PAUSE) Liste_Threads[Nouveau_TID].Etat_Thread = _EN_EXECUTION; // NE pas demander d'arret, ca serai un peu con Liste_Threads[Nouveau_TID].DM_arret = false; // Point d'entree Liste_Threads[Nouveau_TID]._eip = (unsigned long*) &Fonction; // Incrire le thread dans le processsus Liste_Processus[pid].Threads_Enfant[Nouveau_TID] = true; // Mettre a jour le TID dans l'adresse memoire ptr_Update_TID(Arguments, Nouveau_TID); // Creer le thread pthread_create(&Liste_Threads[Nouveau_TID].thread, NULL, *Fonction, (void*) Arguments); // Liste_Threads[Nouveau_TID].PTID = (unsigned long) &Liste_Threads[Nouveau_TID].thread; // std::string offset_fonction_STR = std::to_string((unsigned long) Fonction); // std::string tid_STR = std::to_string((unsigned long) Nouveau_TID); cpinti_dbg::CPINTI_DEBUG(" [OK] TID:" + std::to_string((unsigned long) Nouveau_TID) + ". Fonction offset 0x" + std::to_string((unsigned long) Fonction), " [OK] TID:" + std::to_string((unsigned long) Nouveau_TID) + ". Offset function 0x" + std::to_string((unsigned long) Fonction), "", "", Ligne_saute, Alerte_validation, Date_sans, Ligne_r_normal); SORTIR_SectionCritique(); Thread_en_cours = Nouveau_TID; Interruption_Timer(0); // Retourner l'ID return Nouveau_TID; } unsigned long check_Thread_zombie(bool liberer, bool debug) { // Cette fonction permet de detecter tous les thread zombie // et selon la variable "liberer" il enclanche la liberation memoire du thread unsigned long compteur_zombie = 0; // Retourner le nombre de threads zombie return compteur_zombie; } bool free_Thread_zombie(unsigned long tid) { // Cette fonction permet de supprimer un thread zombie // Un thread zombie conserve encore sa segmentation memoire // conserve dans le registre ESP, son point execution EIP // et autres registres. Cette fonction va tout supprimer et // liberer l'index TID! return true; } bool supprimer_Thread(unsigned long tid, bool force) { // Cette fonction permet de signaler l'arret d'un thread // si force=true // std::string tid_STR = std::to_string((unsigned long) tid); // std::string pid_STR = std::to_string((unsigned long) Liste_Threads[tid].PID); if(force == true) { Nombre_Threads--; // std::string Nombre_Threads_STR = std::to_string((unsigned long) Nombre_Threads); // std::string NomThread_STR = std::string(Liste_Threads[tid].Nom_Thread); cpinti_dbg::CPINTI_DEBUG("Suppression du thread '" + std::string(Liste_Threads[tid].Nom_Thread) + "' TID:" + std::to_string((unsigned long) tid) + " PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID) + ". " + std::to_string((unsigned long) Nombre_Threads) + " thread(s) restant(s)", "Deleting thread '" + std::string(Liste_Threads[tid].Nom_Thread) + "' TID:" + std::to_string((unsigned long) tid) + " PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID) + ". " + std::to_string((unsigned long) Nombre_Threads) + "remaining thread(s)", "core::gestionnaire_tache", "supprimer_Thread()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); if(Liste_Threads[tid].Nom_Thread != NULL) memset(Liste_Threads[tid].Nom_Thread, 0, 30); // free(Liste_Threads[tid].Nom_Thread); Liste_Threads[tid].Priorite = 0; Liste_Processus[Liste_Threads[tid].PID].Threads_Enfant[tid] = false; Liste_Threads[tid].PID = 0; Liste_Threads[tid].TID = 0; Liste_Threads[tid].Etat_Thread = _ARRETE; // Liste_Threads[tid].DM_arret = false; Liste_Threads[tid]._eip = NULL; // Quitter le thread pthread_exit(&Liste_Threads[tid].thread); } else { cpinti_dbg::CPINTI_DEBUG("Envoi d'un signal d'arret au thread '" + std::to_string((unsigned long) tid) + "' PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID), "Sending stopping signal to thread '" + std::to_string((unsigned long) tid) + "' PID:" + std::to_string((unsigned long) Liste_Threads[tid].PID), "core::gestionnaire_tache", "supprimer_Thread()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); // Ce changement d'etat va provoquer un arret "automatique" du thread // Au bout de quelques secondes le thread va passer en mode "zombie" set_EtatThread(tid, _EN_ARRET); Liste_Threads[tid].DM_arret = true; doevents(1000); } return true; } static bool Alterner = false; static bool Executer = false; void Interruption_Timer(long Priorite) { if(state_SectionCritique() == false) { begin_SectionCritique(); // Si il a excute le nombre de cycle/priorite on reloop Liste_Threads[Thread_en_cours].Priorite_count++; // Correctif (En cas de corruption, eviter un SIGFPE) if(Liste_Threads[Thread_en_cours].Priorite < 2) Liste_Threads[Thread_en_cours].Priorite = 2; else if(Liste_Threads[Thread_en_cours].Priorite > MAX_CYCLES) Liste_Threads[Thread_en_cours].Priorite = MAX_CYCLES; if(Liste_Threads[Thread_en_cours].Priorite_count >= (MAX_CYCLES / Liste_Threads[Thread_en_cours].Priorite)) { Liste_Threads[Thread_en_cours].Priorite_count = 0; Executer = true; Alterner = false; } // Liste_Threads[Thread_en_cours].Priorite_count++; // if(Liste_Threads[Thread_en_cours].Priorite_count >= Liste_Threads[Thread_en_cours].Priorite) // { // Liste_Threads[Thread_en_cours].Priorite_count = 0; // Executer = true; // Alterner = false; // } if(Alterner == true) { Alterner = false; end_SectionCritique(); __dpmi_yield(); begin_SectionCritique(); } else Alterner = true; if(Executer == true) { unsigned long Precedent = Thread_en_cours; Alterner = true; Executer = false; // fprintf(stdout, " ****** SWITCH ! %u -->", Thread_en_cours); end_SectionCritique(); if(Liste_Threads[Thread_en_cours].DM_arret == true) { cpinti_dbg::CPINTI_DEBUG("Thread zombie TID:" + std::to_string(Thread_en_cours) + " Dernier essais : " + std::to_string(Liste_Threads[Thread_en_cours].Zombie_Count) + "/" + std::to_string(_ZOMBIE_ESSAI) + " .", "Zombie Thread TID:" + std::to_string(Thread_en_cours) + " Last chance : " + std::to_string(Liste_Threads[Thread_en_cours].Zombie_Count) + "/" + std::to_string(_ZOMBIE_ESSAI) + " .", "core::gestionnaire_tache", "Interruption_Timer()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); // Ah il a repondu il s'est termine tout seul, on arrete! if(Liste_Threads[Thread_en_cours].Etat_Thread == _ARRETE) { Liste_Threads[Thread_en_cours].DM_arret = false; cpinti_dbg::CPINTI_DEBUG("Oh! Le zombie s'est reveille et s'est auto-detruit!", "Oh! The zombie awoke and self-destructed!", "core::gestionnaire_tache", "Interruption_Timer()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); } if(Liste_Threads[Thread_en_cours].Zombie_Count >= _ZOMBIE_ESSAI) { // Declarer le thread en ZOMBIE Liste_Threads[Thread_en_cours].Etat_Thread = _ZOMBIE; cpinti_dbg::CPINTI_DEBUG("Thread TID:" + std::to_string(Thread_en_cours) + " declare ZOMBIE. Bannissement du scheduler.", "Zombie Thread TID:" + std::to_string(Thread_en_cours) + " declared ZOMBIE. Ban from scheduler.", "core::gestionnaire_tache", "Interruption_Timer()", Ligne_saute, Alerte_ok, Date_sans, Ligne_r_normal); // Adieu thread! On t'a surement aime! while(true) { usleep(5000000); // bloquer le thread 5 secondes a l'infinit } } else { Liste_Threads[Thread_en_cours].Zombie_Count++; // 6 Cycles avant son arret, on enleve un thread if(Liste_Threads[Thread_en_cours].Zombie_Count == _ZOMBIE_ESSAI - 6) Nombre_Threads--; } } usleep(10); begin_SectionCritique(); Thread_en_cours = Precedent; } end_SectionCritique(); } } void switch_context() { // Cette fonction permet de switcher de thread en thread return; /** S'il y a pas de threads, inutile d'aller plus loin **/ if(Thread_en_cours == 0) if(Nombre_Threads < 1) return; /** On bloque le scheduler **/ begin_SectionCritique(); /** Sauvegarder le contexte actuel **/ if(SAUVEGARDER_CONTEXTE(Thread_en_cours) == true) return; /** Chercher le prochain thread a executer **/ Thread_en_cours = SCHEDULER(Thread_en_cours); /** On reexcute le scheduler normalement **/ end_SectionCritique(); /** Et on restaure le prochain thread **/ RESTAURER_CONTEXTE(Thread_en_cours); } unsigned long SCHEDULER(unsigned long ancien) { // SCHEDULER : Cette fonction permet de selectionner // le prochain thread a executer unsigned long nouveau = ancien; unsigned long compteur_ = 0; while(true) { nouveau++; compteur_++; // Si on depasse le nombre on repart de zero if(nouveau >= MAX_THREAD) nouveau = 0; if(Liste_Threads[nouveau].Etat_Thread != _ARRETE) if(Liste_Threads[nouveau].Etat_Thread != _ZOMBIE) return nouveau; if(compteur_ > MAX_THREAD*2) break; } cpinti_dbg::CPINTI_DEBUG("Oups.. Tous les threads sont a l'arret", "Oops.. All threads are stopped", "core::gestionnaire_tache", "SCHEDULER()", Ligne_saute, Alerte_erreur, Date_sans, Ligne_r_normal); return 0; } bool SAUVEGARDER_CONTEXTE(unsigned long Thread_ID) { // Cette fonction permet de sauvegarder les registres d'un thread // Si le thread est pas vide if(Liste_Threads[Thread_ID].Etat_Thread != _ARRETE) if(Liste_Threads[Thread_ID].Etat_Thread != _ZOMBIE) { // Reexecuter le scheduler normalement end_SectionCritique(); // Recuperer les info (registres...) du thread actuel if (setjmp(Liste_Threads[Thread_ID].Buffer_Thread) == 1) { return true; } // On bloque le scheduler courant begin_SectionCritique(); } return false; } void RESTAURER_CONTEXTE(unsigned long Thread_ID) { // Cette fonction permet de restaurer les registres d'un thread longjmp(Liste_Threads[Thread_ID].Buffer_Thread, 1); } void loop_MAIN() { // Cette fonction permet creer un point de terminaison du main en executant // la premiere thread Thread_en_cours = 0; longjmp(Liste_Threads[0].Buffer_Thread, 1); } /************************** TIMER **************************/ bool initialiser_PIT(long frequence, long Intervalle_INTERNE) { // Cette fonction permet de reprogrammer l'intervalle du PIT // -1:Pas de modification de la frequence // 0:Frequence MAX par defaut // >0:Modification de la frequence d'horloge du PIT (Max:65535) if(frequence == 0) { outportb(0x43, 0x36); outportb(0x40, 0); outportb(0x40, 0); } else if ((frequence > 0) && frequence <= 65535) { outportb(0x43, 0x36); outportb(0x40, ((1193180L / frequence) & 0x00ff)); outportb(0x40, (((1193180L / frequence) >> 8) & 0x00ff)); } // Modification du clock de la routine interne __djgpp_clock_tick_interval = Intervalle_INTERNE; return true; } unsigned long ajouter_Timer(unsigned long fonction) { // Cette fonction permet d'ajouter un Timer // Si on atteint le nombre maximum de timers if(Nombre_Timer >= MAX_TIMERS) { // (" ERREUR : Nombre maximum de timer autorise est de %d.", MAX_TIMERS); return 0; } // NE PAS laisser le scheduler switcher pendant cette operation begin_SectionCritique(); // Incremente le nombre de timers Nombre_Timer++; // Initialise l'instance a zero instance_Timer[Nombre_Timer].it_interval.tv_sec = 0; instance_Timer[Nombre_Timer].it_interval.tv_usec = 0; instance_Timer[Nombre_Timer].it_value.tv_sec = 0; instance_Timer[Nombre_Timer].it_value.tv_usec = 0; // Definir le timer signal(SIGALRM, (void (*)(int)) fonction); setitimer(ITIMER_REAL, &instance_Timer[Nombre_Timer], NULL); // Reexecuter le scheduler normalement end_SectionCritique(); // Retourner l'ID return Nombre_Timer; } bool demarrer_SCHEDULER(unsigned long id_TIMER, long temps_us) { // Cette fonction permet de demarrer le scheduling d'un timer // en definissant le temps en intervalle en micro-secondes // s'il y en a pas, retour! if(Nombre_Timer < 1) return false; // Definir l'intervalle instance_Timer[id_TIMER].it_interval.tv_sec = 0; instance_Timer[id_TIMER].it_interval.tv_usec = temps_us; instance_Timer[id_TIMER].it_value.tv_sec = 0; instance_Timer[id_TIMER].it_value.tv_usec = temps_us; // On envoie tout ca setitimer(ITIMER_REAL, &instance_Timer[id_TIMER], NULL); return true; } bool stop_SCHEDULER(long id_TIMER) { // Cette fonction permet d'arreter le scheduler // Initialise l'instance a zero instance_Timer[id_TIMER].it_interval.tv_sec = 0; instance_Timer[id_TIMER].it_interval.tv_usec = 0; instance_Timer[id_TIMER].it_value.tv_sec = 0; instance_Timer[id_TIMER].it_value.tv_usec = 0; // On envoie tout ca setitimer(ITIMER_REAL, &instance_Timer[id_TIMER], NULL); return true; } } // namespace } // namespace cpinti void Interruption_Timer(long signal) { // fprintf(stdout, " **CORE 3\n"); cpinti::gestionnaire_tache::Interruption_Timer(signal); // fprintf(stdout, " **CORE 3.1\n"); }
29.30292
299
0.649053
Cwc-Test
ac6530658c67e15a634ead0ae3d492090da6389a
928
cpp
C++
EglCpp/Sources/Reflection/Reflectable.cpp
Egliss/EglCppBase
94d24b6e5e91da880833237a879138760ae9c669
[ "MIT" ]
null
null
null
EglCpp/Sources/Reflection/Reflectable.cpp
Egliss/EglCppBase
94d24b6e5e91da880833237a879138760ae9c669
[ "MIT" ]
2
2020-08-04T18:14:51.000Z
2020-08-06T19:19:11.000Z
EglCpp/Sources/Reflection/Reflectable.cpp
Egliss/EglCppBase
94d24b6e5e91da880833237a879138760ae9c669
[ "MIT" ]
null
null
null
#include "pch.h" #include "Reflectable.hpp" #include "DynamicType.hpp" #include "../Utility/StringUtility.hpp" using namespace Egliss::Reflection; void Reflectable::Validate(int typeId) { if (this->TryFastValidate(typeId)) return; if (DynamicTypeManager::Find(typeId) == nullptr) throw std::exception(StringUtility::Format("inputed type id({0}) not found", typeId).c_str()); if (DynamicTypeManager::Find(TypeId) == nullptr) throw std::exception(StringUtility::Format("instance saved type id({0}) not found", TypeId).c_str()); auto text = StringUtility::Format("instance saved type id is {0}({1}) but, input type is {2}({3}). please check deriver type's constructor.", DynamicTypeManager::TypeOf(typeId).name, DynamicTypeManager::TypeOf(typeId).id, DynamicTypeManager::TypeOf(TypeId).name, DynamicTypeManager::TypeOf(TypeId).id ); throw std::exception(text.c_str()); }
37.12
142
0.704741
Egliss
ac661674fe1f088ca7613e2efe04fdfb86e9aff5
2,632
hpp
C++
src/util/position.hpp
BruJu/AdventOfCode
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
1
2020-12-11T13:37:06.000Z
2020-12-11T13:37:06.000Z
src/util/position.hpp
BruJu/AdventOfCode2020
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
null
null
null
src/util/position.hpp
BruJu/AdventOfCode2020
a9161649882429bc1f995424544ce4cdafb69caa
[ "WTFPL", "MIT" ]
null
null
null
#pragma once #include <optional> namespace bj { enum class Direction { Left, Right, Top, Down }; inline std::optional<Direction> to_direction_from_lrtd(const char symbol, const char * symbols) { if (symbol == symbols[0]) return Direction::Left; if (symbol == symbols[1]) return Direction::Right; if (symbol == symbols[2]) return Direction::Top; if (symbol == symbols[3]) return Direction::Down; return std::nullopt; } // Sortable position struct Position { int x = 0; int y = 0; [[nodiscard]] bool operator<(const Position & rhs) const { if (x < rhs.x) return true; if (x > rhs.x) return false; if (y < rhs.y) return true; if (y > rhs.y) return false; return false; } [[nodiscard]] bool operator==(const Position & rhs) const { return x == rhs.x && y == rhs.y; } [[nodiscard]] bool operator!=(const Position & rhs) const { return !(*this == rhs); } void move(Direction direction) { switch (direction) { case Direction::Left: x -= 1; break; case Direction::Right: x += 1; break; case Direction::Top: y -= 1; break; case Direction::Down: y += 1; break; } } template<typename Consumer> void for_each_neighbour(Consumer c) const { for (Direction d : { Direction::Left, Direction::Right, Direction::Down, Direction::Top }) { Position copy = *this; copy.move(d); c(copy); } } [[nodiscard]] std::vector<bj::Position> get_8_neighbours() const { std::vector<bj::Position> retval; for (int x_ = -1 ; x_ <= 1 ; ++x_) { for (int y_ = -1 ; y_ <= 1 ; ++y_) { if (y_ == 0 && x_ == 0) continue; retval.push_back(Position { x + x_, y + y_ }); }} return retval; } }; struct Rectangle { int left; int right; int top; int bottom; Rectangle(int left, int top, int right, int bottom) : left(left), right(right), top(top), bottom(bottom) {} template <typename Consumer> void for_each_position(Consumer consumer) const { for (int i = left ; i <= right ; ++i) { for (int j = top ; j <= bottom ; ++j) { consumer(Position { i, j }); } } } }; }
30.252874
104
0.483283
BruJu
ac686e97ae6b511f157d50c84dc1f9f1c9a4358e
2,077
cpp
C++
N0023-Merge-k-Sorted-Lists/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
N0023-Merge-k-Sorted-Lists/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
N0023-Merge-k-Sorted-Lists/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
2
2022-01-25T05:31:31.000Z
2022-02-26T07:22:23.000Z
// // main.cpp // LeetCode-Solution // // Created by Loyio Hex on 3/1/22. // #include <iostream> #include <chrono> #include <vector> #include <queue> using namespace std; using namespace std::chrono; 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: struct Node_status { int val; ListNode *ptr; bool operator < (const Node_status &rhs) const { return val > rhs.val; } }; priority_queue<Node_status> que; ListNode* mergeKLists(vector<ListNode*>& lists) { for (auto node: lists) { if(node) que.push({node->val, node}); } ListNode head, *tail = &head; while (!que.empty()){ auto f = que.top(); que.pop(); tail->next = f.ptr; tail = tail->next; if (f.ptr->next){ que.push({f.ptr->next->val, f.ptr->next}); } } return head.next; } }; int main(int argc, const char * argv[]) { auto start = high_resolution_clock::now(); // Main Start vector<vector<int>> lists_num = {{1, 4, 5}, {1, 3, 4}, {2, 6}}; ListNode *p, *res; vector<ListNode*> lists(lists_num.size()); for (int i = 0; i < lists_num.size(); ++i) { p = nullptr; for (int j = 0; j < lists_num[i].size(); ++j) { if(!p){ lists[i] = p = new ListNode(lists_num[i][j]); }else{ p->next = new ListNode(lists_num[i][j]); p = p->next; } } } Solution solution; res = solution.mergeKLists(lists); while(res){ cout << res->val << endl; res = res->next; } // Main End auto stop = high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << endl << "Runnig time : " << duration.count() << "ms;" << endl; return 0; }
24.72619
74
0.512277
loyio
ac6b40c405ccda93eb67fc725d373fc6c4d51f63
262
hpp
C++
examples/trivial/trivial.hpp
dcblack/systemc-complete
b018b76254de95673a4294052317d23a6325918b
[ "RSA-MD" ]
1
2021-06-03T15:19:51.000Z
2021-06-03T15:19:51.000Z
examples/trivial/trivial.hpp
dcblack/systemc-complete
b018b76254de95673a4294052317d23a6325918b
[ "RSA-MD" ]
null
null
null
examples/trivial/trivial.hpp
dcblack/systemc-complete
b018b76254de95673a4294052317d23a6325918b
[ "RSA-MD" ]
null
null
null
//FILE: trivial.hpp #ifndef TRIVIAL_HPP #define TRIVIAL_HPP #include <systemc> struct Trivial_module : sc_core::sc_module { Trivial_module( sc_core::sc_module_name instance ); ~Trivial_module( void ) = default; private: void main_thread( void ); }; #endif
20.153846
53
0.751908
dcblack
ac720042415480b1a9f4c26d9f4197ffe6e1c59f
15,344
cpp
C++
src/graph/Graph.cpp
AvocadoML/Avocado
9595cc5994d916f0ecb24873a5afa98437977fb5
[ "Apache-2.0" ]
null
null
null
src/graph/Graph.cpp
AvocadoML/Avocado
9595cc5994d916f0ecb24873a5afa98437977fb5
[ "Apache-2.0" ]
null
null
null
src/graph/Graph.cpp
AvocadoML/Avocado
9595cc5994d916f0ecb24873a5afa98437977fb5
[ "Apache-2.0" ]
null
null
null
/* * Graph.cpp * * Created on: Feb 16, 2021 * Author: Maciej Kozarzewski */ #include <Avocado/graph/Graph.hpp> #include <Avocado/graph/GraphNode.hpp> #include <Avocado/core/Device.hpp> #include <Avocado/core/Context.hpp> #include <Avocado/core/Scalar.hpp> #include <Avocado/layers/Input.hpp> #include <Avocado/utils/json.hpp> #include <Avocado/inference/calibration.hpp> #include <algorithm> namespace { template<typename T> int indexOf(const std::vector<T> &vec, T value) { for (size_t i = 0; i < vec.size(); i++) if (vec[i] == value) return i; return -1; } template<typename T> void removeByIndex(std::vector<T> &vec, size_t idx) { if (idx < vec.size()) vec.erase(vec.begin() + idx); } template<typename T> void removeByValue(std::vector<T> &vec, T value) { removeByIndex(vec, indexOf(vec, value)); } } namespace avocado { Graph::Graph(Device device) : m_context(device) { } Device Graph::device() const noexcept { return m_context.device(); } DataType Graph::dtype() const noexcept { return m_datatype; } const Context& Graph::context() const noexcept { return m_context; } GraphNodeID Graph::addInput(const Shape &shape) { return add_node(Input(shape), { }); } GraphNodeID Graph::add(const Layer &layer, GraphNodeID node) { return add_node(layer, { node }); } GraphNodeID Graph::add(const Layer &layer, std::initializer_list<GraphNodeID> nodes) { if (nodes.size() == 0) throw LogicError(METHOD_NAME, "nodes list must not be empty"); return add_node(layer, nodes); } void Graph::addOutput(GraphNodeID node, const LossFunction &loss) { m_output_nodes.push_back(get_node(node)); m_losses.push_back(std::unique_ptr<LossFunction>(loss.clone())); m_targets.push_back(nullptr); bool successfully_combined = m_losses.back()->tryCombineWith(get_node(node)->getLayer()); if (successfully_combined) get_node(node)->bypassDuringBackward(); } void Graph::addOutput(GraphNodeID node) { m_output_nodes.push_back(get_node(node)); m_losses.push_back(nullptr); m_targets.push_back(nullptr); } const Tensor& Graph::getInput(int index) const { return m_input_nodes.at(index)->getOutputTensor(); } const Tensor& Graph::getOutput(int index) const { return m_output_nodes.at(index)->getOutputTensor(); } const Tensor& Graph::getGradient(int index) const { return m_output_nodes.at(index)->getGradientTensor(); } const Tensor& Graph::getTarget(int index) const { if (not isTrainable()) throw LogicError(METHOD_NAME, "Graph is not trainable"); if (m_targets.at(index) == nullptr) throw UninitializedObject(METHOD_NAME, "target tensor was not initialized"); return *(m_targets.at(index)); } Tensor& Graph::getInput(int index) { return m_input_nodes.at(index)->getOutputTensor(); } Tensor& Graph::getOutput(int index) { return m_output_nodes.at(index)->getOutputTensor(); } Tensor& Graph::getGradient(int index) { return m_output_nodes.at(index)->getGradientTensor(); } Tensor& Graph::getTarget(int index) { if (m_targets.at(index) == nullptr) m_targets.at(index) = std::make_unique<Tensor>(getOutput(index).shape(), dtype(), device()); return *(m_targets.at(index)); } Shape Graph::getInputShape(int index) const { return m_input_nodes.at(index)->getOutputShape(); } Shape Graph::getOutputShape(int index) const { return m_output_nodes.at(index)->getOutputShape(); } int Graph::numberOfInputs() const noexcept { return static_cast<int>(m_input_nodes.size()); } int Graph::numberOfOutputs() const noexcept { return static_cast<int>(m_output_nodes.size()); } int Graph::maxBatchSize() const { if (numberOfInputs() == 0) return 0; else return getOutputShape().firstDim(); } void Graph::moveTo(Device newDevice) { if (newDevice == device()) return; m_context = Context(newDevice); for (size_t i = 0; i < m_layers.size(); i++) m_layers[i]->changeContext(m_context); for (size_t i = 0; i < m_nodes.size(); i++) m_nodes[i]->moveTo(newDevice); if (m_backup_tensor != nullptr) m_backup_tensor->moveTo(newDevice); for (size_t i = 0; i < m_targets.size(); i++) if (m_targets[i] != nullptr) m_targets[i]->moveTo(newDevice); } void Graph::setInputShape(const Shape &shape) { setInputShape(std::vector<Shape>( { shape })); } void Graph::setInputShape(const std::vector<Shape> &list) { for (int i = 0; i < numberOfInputs(); i++) m_input_nodes[i]->getLayer().setInputShape(list[i]); for (size_t i = 0; i < m_nodes.size(); i++) m_nodes[i]->resolveInputShapes(); m_backup_tensor = nullptr; } void Graph::setOptimizer(const Optimizer &optimizer) { if (not isTrainable()) throw LogicError(METHOD_NAME, "Graph is not trainable"); for (size_t i = 0; i < m_layers.size(); i++) m_layers[i]->setOptimizer(optimizer); } void Graph::setRegularizer(const Regularizer &regularizer) { if (not isTrainable()) throw LogicError(METHOD_NAME, "Graph is not trainable"); for (size_t i = 0; i < m_layers.size(); i++) m_layers[i]->setRegularizer(regularizer); } void Graph::init() { for (size_t i = 0; i < m_layers.size(); i++) m_layers[i]->init(); } void Graph::forward(int batchSize) { for (size_t i = 0; i < m_nodes.size(); i++) m_nodes[i]->forward(batchSize); } void Graph::backward(int batchSize) { if (not isTrainable()) throw LogicError(METHOD_NAME, "Graph is not trainable"); if (m_backup_tensor == nullptr) create_backup_tensor(); for (size_t i = 0; i < m_nodes.size(); i++) m_nodes[i]->prepareForBackward(); for (size_t i = 0; i < m_targets.size(); i++) { Shape tmp(getTarget(i).shape()); tmp[0] = batchSize; Tensor gradient = getGradient(i).view(tmp); Tensor output = getOutput(i).view(tmp); Tensor target = getTarget(i).view(tmp); m_losses[i]->getGradient(context(), gradient, output, target); } for (int i = static_cast<int>(m_nodes.size()) - 1; i >= 0; i--) m_nodes[i]->backward(batchSize, *m_backup_tensor); } std::vector<Scalar> Graph::getLoss(int batchSize) { if (not isTrainable()) throw LogicError(METHOD_NAME, "Graph is not trainable"); std::vector<Scalar> result(numberOfOutputs()); for (size_t i = 0; i < m_targets.size(); i++) { Shape tmp(getTarget(i).shape()); tmp[0] = batchSize; Tensor output = getOutput(i).view(tmp); Tensor target = getTarget(i).view(tmp); result[i] = m_losses[i]->getLoss(context(), output, target); } return result; } void Graph::learn() { if (not isTrainable()) throw LogicError(METHOD_NAME, "Graph is not trainable"); for (int i = 0; i < numberOfLayers(); i++) m_layers[i]->learn(); } void Graph::print() const { for (size_t i = 0; i < m_nodes.size(); i++) { GraphNode *node = m_nodes[i].get(); std::cout << i << ' ' << m_nodes[i]->getLayer().name() << " (" << m_nodes[i]->getLayer().getNonlinearity() << ") : " << node->getOutputShape() << " : {"; for (int j = 0; j < node->numberOfInputs(); j++) { if (j != 0) std::cout << ','; std::cout << index_of_node(node->getInputNode(j)); } std::cout << "} -> {"; for (int j = 0; j < node->numberOfOutputs(); j++) { if (j != 0) std::cout << ','; std::cout << index_of_node(node->getOutputNode(j)); } std::cout << "}\n"; } for (size_t i = 0; i < m_output_nodes.size(); i++) std::cout << "Output:" << i << " : {" << index_of_node(m_output_nodes[i]) << "} : " << m_output_nodes[i]->getOutputShape() << std::endl; } void Graph::makeNonTrainable() { for (int i = 0; i < numberOfLayers(); i++) { getLayer(i).getWeights().setTrainable(false); getLayer(i).getBias().setTrainable(false); } for (int i = 0; i < numberOfNodes(); i++) getNode(i).makeNonTrainable(); } bool Graph::isTrainable() const noexcept { return m_targets.size() == m_output_nodes.size(); } void Graph::calibrate(inference::CalibrationTable &table) const { for (size_t i = 0; i < m_nodes.size(); i++) { size_t indeOfLayer = index_of_layer(&(m_nodes[i]->getLayer())); table.getHistogram(indeOfLayer).collectStatistics(m_nodes[i]->getOutputTensor()); } } int Graph::numberOfLayers() const noexcept { return static_cast<int>(m_layers.size()); } const Layer& Graph::getLayer(int index) const { return *(m_layers.at(index)); } Layer& Graph::getLayer(int index) { return *(m_layers.at(index)); } int Graph::numberOfNodes() const noexcept { return static_cast<int>(m_nodes.size()); } const GraphNode& Graph::getNode(int index) const { return *(m_nodes.at(index)); } GraphNode& Graph::getNode(int index) { return *(m_nodes.at(index)); } GraphNodeID Graph::getNodeID(const GraphNode *node) const noexcept { return index_of_node(node); } void Graph::clear() { m_context = Context(); m_layers.clear(); m_nodes.clear(); m_losses.clear(); m_targets.clear(); m_input_nodes.clear(); m_output_nodes.clear(); m_backup_tensor.reset(); m_datatype = DataType::FLOAT32; } Json Graph::save(SerializedObject &binary_data) const { Json result; result["losses"] = Json(JsonType::Array); for (size_t i = 0; i < m_losses.size(); i++) result["losses"][i] = m_losses[i]->serialize(binary_data); result["layers"] = Json(JsonType::Array); for (int i = 0; i < numberOfLayers(); i++) { Json tmp = getLayer(i).getConfig(); tmp.append(getLayer(i).saveParameters(binary_data)); result["layers"][i] = tmp; } result["nodes"] = Json(JsonType::Array); for (int i = 0; i < static_cast<int>(m_nodes.size()); i++) result["nodes"][i] = save_node(m_nodes[i].get()); return result; } void Graph::load(const Json &json, const SerializedObject &binary_data) { clear(); const Json &losses = json["losses"]; for (int i = 0; i < losses.size(); i++) { m_losses.push_back(loadLossFunction(losses[i], binary_data)); m_targets.push_back(nullptr); } const Json &layers = json["layers"]; for (int i = 0; i < layers.size(); i++) { m_layers.push_back(loadLayer(layers[i], binary_data)); m_layers.back()->changeContext(m_context); } const Json &nodes = json["nodes"]; for (int i = 0; i < nodes.size(); i++) load_node(nodes[i]); for (int i = 0; i < numberOfLayers(); i++) getLayer(i).loadParameters(layers[i], binary_data); } GraphNodeID Graph::add_node(const Layer &layer, const std::vector<GraphNodeID> &inputs) { m_layers.push_back(std::unique_ptr<Layer>(layer.clone(layer.getConfig()))); m_layers.back()->changeContext(m_context); std::vector<GraphNode*> tmp(inputs.size()); for (size_t i = 0; i < inputs.size(); i++) tmp[i] = get_node(inputs[i]); m_nodes.push_back(std::make_unique<GraphNode>(m_layers.back().get(), tmp)); if (m_nodes.back()->isInputNode()) m_input_nodes.push_back(m_nodes.back().get()); return static_cast<GraphNodeID>(m_nodes.size() - 1); } void Graph::insert_node_with_layer(std::unique_ptr<Layer> &&new_layer, const std::vector<GraphNode*> &inputs, const std::vector<GraphNode*> &outputs) { int last_of_input = 0; for (size_t i = 0; i < inputs.size(); i++) { int tmp = index_of_node(inputs[i]); if (tmp == -1) throw LogicError(METHOD_NAME, "no such node in this graph"); last_of_input = std::max(last_of_input, tmp); } int first_of_output = numberOfNodes(); for (size_t i = 0; i < outputs.size(); i++) { int tmp = index_of_node(outputs[i]); if (tmp == -1) throw LogicError(METHOD_NAME, "no such node in this graph"); first_of_output = std::min(first_of_output, tmp); } if (last_of_input > first_of_output) throw LogicError(METHOD_NAME, "insertion would form a cycle"); std::unique_ptr<GraphNode> tmp = std::make_unique<GraphNode>(new_layer.get(), inputs); GraphNode::link(tmp.get(), outputs); m_nodes.insert(m_nodes.begin() + last_of_input + 1, std::move(tmp)); new_layer->changeContext(m_context); m_layers.push_back(std::move(new_layer)); } void Graph::remove_node(GraphNode *node) { auto index_in_input_nodes = std::find(m_input_nodes.begin(), m_input_nodes.end(), node); auto index_in_output_nodes = std::find(m_output_nodes.begin(), m_output_nodes.end(), node); if (index_in_input_nodes != m_input_nodes.end()) { if (node->numberOfOutputs() > 1) throw LogicError(METHOD_NAME, "trying to remove input node"); else *index_in_input_nodes = node->getOutputNode(0); } if (index_in_output_nodes != m_output_nodes.end()) { if (node->numberOfInputs() > 1) throw LogicError(METHOD_NAME, "trying to remove output node"); else *index_in_output_nodes = node->getInputNode(0); } node->removeAllLinks(); removeByIndex(m_layers, index_of_layer(&(node->getLayer()))); removeByIndex(m_nodes, index_of_node(node)); } std::unique_ptr<Layer> Graph::replaceLayer(int index, const Layer &newLayer) { std::unique_ptr<Layer> result = std::move(m_layers[index]); m_layers[index] = std::unique_ptr<Layer>(newLayer.clone(newLayer.getConfig())); m_layers[index]->changeContext(m_context); std::vector<Shape> tmp; for (int i = 0; i < result->numberOfInputs(); i++) tmp.push_back(result->getInputShape(i)); m_layers[index]->setInputShape(tmp); for (size_t i = 0; i < m_nodes.size(); i++) if (&(m_nodes[i]->getLayer()) == result.get()) m_nodes[i]->replaceLayer(m_layers[index].get()); return result; } void Graph::create_backup_tensor() { int tmp = 0; for (size_t i = 0; i < m_nodes.size(); i++) tmp = std::max(tmp, m_nodes[i]->getBackupStorage()); m_backup_tensor = std::make_unique<Tensor>(Shape( { tmp }), dtype(), device()); } Json Graph::save_node(const GraphNode *node) const { Json result; result["is_input_node"] = node->isInputNode(); result["is_output_node"] = node->isOutputNode(); result["layer_id"] = index_of_layer(&(node->getLayer())); result["input_nodes"] = Json(JsonType::Array); for (int i = 0; i < node->numberOfInputs(); i++) result["input_nodes"][i] = index_of_node(node->getInputNode(i)); return result; } void Graph::load_node(const Json &json) { Layer *layer = m_layers[static_cast<int>(json["layer_id"])].get(); std::vector<GraphNode*> inputs; for (int i = 0; i < json["input_nodes"].size(); i++) inputs.push_back(m_nodes[static_cast<int>(json["input_nodes"][i])].get()); m_nodes.push_back(std::make_unique<GraphNode>(layer, inputs)); if (json["is_input_node"]) m_input_nodes.push_back(m_nodes.back().get()); if (json["is_output_node"]) m_output_nodes.push_back(m_nodes.back().get()); } int Graph::index_of_node(const GraphNode *node) const noexcept { for (size_t i = 0; i < m_nodes.size(); i++) if (m_nodes[i].get() == node) return i; return -1; } int Graph::index_of_layer(const Layer *layer) const noexcept { for (size_t i = 0; i < m_layers.size(); i++) if (m_layers[i].get() == layer) return i; return -1; } const GraphNode* Graph::get_node(GraphNodeID index) const { if (index < 0 || index >= numberOfNodes()) throw IndexOutOfBounds(METHOD_NAME, "index", index, numberOfNodes()); return m_nodes[index].get(); } GraphNode* Graph::get_node(GraphNodeID index) { if (index < 0 || index >= numberOfNodes()) throw IndexOutOfBounds(METHOD_NAME, "index", index, numberOfNodes()); return m_nodes[index].get(); } } /* namespace avocado */
28.362292
139
0.666449
AvocadoML
ac7378987845f7a3a7f24f79ea8ccfb093cd3c64
1,321
cpp
C++
Server/Canasta/server.cpp
vivibau/CanastaCSharpOld
2aadde306450837244b6ec4364d9156e076322b0
[ "MIT" ]
null
null
null
Server/Canasta/server.cpp
vivibau/CanastaCSharpOld
2aadde306450837244b6ec4364d9156e076322b0
[ "MIT" ]
null
null
null
Server/Canasta/server.cpp
vivibau/CanastaCSharpOld
2aadde306450837244b6ec4364d9156e076322b0
[ "MIT" ]
1
2020-06-04T14:13:04.000Z
2020-06-04T14:13:04.000Z
/*#include <iostream> using namespace std; int main() { return 0; } */ #include <stdio.h> #include <stdlib.h> #include <vector> #include <iostream> #include "TCPAcceptor.h" #include "Game.h" #include "Parser.h" #include "Includes.h" int main(int argc, char** argv) { /* if (argc < 2 || argc > 4) { printf("usage: server <port>\n"); exit(1); } */ TCPStream* stream = NULL; TCPAcceptor* acceptor = NULL; std::vector<Game*> games; srand(time(NULL)); // acceptor = new TCPAcceptor(atoi(argv[1])); acceptor = new TCPAcceptor(3291); if (acceptor->start() == 0) { while (1) { stream = acceptor->accept(); if (stream != NULL) { ssize_t len; char line[1024]; while ((len = stream->receive(line, sizeof(line))) > 0) { Parser* parser = new Parser(line, len); parser->parseData(); parser->updateGame(games); std::string response = parser->getResponse(); stream->send(response.c_str(), response.length()); if (parser) delete(parser); } delete stream; } } // if (acceptor) delete(acceptor); } exit(0); }
22.016667
73
0.500379
vivibau
ac794c9c6de51b32a5e62cafbdec641c9b9d6e1a
3,725
cpp
C++
options/posix/generic/grp-stubs.cpp
CPL-1/mlibc
0726f99c28629e4fc7730d8897909e0cdb5b2545
[ "MIT" ]
null
null
null
options/posix/generic/grp-stubs.cpp
CPL-1/mlibc
0726f99c28629e4fc7730d8897909e0cdb5b2545
[ "MIT" ]
null
null
null
options/posix/generic/grp-stubs.cpp
CPL-1/mlibc
0726f99c28629e4fc7730d8897909e0cdb5b2545
[ "MIT" ]
null
null
null
#include <grp.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <bits/ensure.h> #include <mlibc/debug.hpp> namespace { thread_local group global_entry; template<typename F> void walk_segments(frg::string_view line, char delimiter, F fn) { size_t s = 0; while(true) { size_t d = line.find_first(':', s); if(d == size_t(-1)) break; auto chunk = line.sub_string(s, d - s); fn(chunk); s = d + 1; } if(line[s]) { auto chunk = line.sub_string(s, line.size() - s); fn(chunk); } } bool extract_entry(frg::string_view line, group *entry) { __ensure(!entry->gr_name); __ensure(!entry->gr_mem); frg::string_view segments[5]; // Parse the line into exactly 4 segments. size_t s = 0; int n; for(n = 0; n < 4; n++) { size_t d = line.find_first(':', s); if(d == size_t(-1)) break; segments[n] = line.sub_string(s, d - s); s = d + 1; } if(line.find_first(':', s) != size_t(-1)) return false; segments[n] = line.sub_string(s, line.size() - s); n++; if(n < 4) return false; // segments[1] is the password; it is not exported to struct group. // The other segments are consumed below. // TODO: Handle strndup() and malloc() failure. auto name = strndup(segments[0].data(), segments[0].size()); __ensure(name); auto gid = segments[2].to_number<int>(); if(!gid) return false; size_t n_members = 0; walk_segments(segments[3], ',', [&] (frg::string_view) { n_members++; }); auto members = reinterpret_cast<char **>(malloc(sizeof(char *) * (n_members + 1))); __ensure(members); size_t k = 0; walk_segments(segments[3], ',', [&] (frg::string_view m) { members[k] = strndup(m.data(), m.size()); __ensure(members[k]); k++; }); members[k] = nullptr; entry->gr_name = name; entry->gr_gid = *gid; entry->gr_mem = members; return true; } void clear_entry(group *entry) { free(entry->gr_name); if(entry->gr_mem) { for(size_t i = 0; entry->gr_mem[i]; i++) free(entry->gr_mem[i]); free(entry->gr_mem); } entry->gr_name = nullptr; entry->gr_mem = nullptr; } template<typename C> group *walk_file(C cond) { auto file = fopen("/etc/group", "r"); if(!file) return nullptr; char line[512]; while(fgets(line, 512, file)) { clear_entry(&global_entry); if(!extract_entry(line, &global_entry)) continue; if(cond(&global_entry)) { fclose(file); return &global_entry; } } fclose(file); errno = ESRCH; return nullptr; } } void endgrent(void) { __ensure(!"Not implemented"); __builtin_unreachable(); } struct group *getgrent(void) { __ensure(!"Not implemented"); __builtin_unreachable(); } struct group *getgrgid(gid_t gid) { return walk_file([&] (group *entry) { return entry->gr_gid == gid; }); } int getgrgid_r(gid_t, struct group *, char *, size_t, struct group **) { __ensure(!"Not implemented"); __builtin_unreachable(); } struct group *getgrnam(const char *name) { return walk_file([&] (group *entry) { return !strcmp(entry->gr_name, name); }); } int getgrnam_r(const char *, struct group *, char *, size_t, struct group **) { __ensure(!"Not implemented"); __builtin_unreachable(); } void setgrent(void) { __ensure(!"Not implemented"); __builtin_unreachable(); } int setgroups(size_t size, const gid_t *list) { __ensure(!"Not implemented"); __builtin_unreachable(); } int initgroups(const char *user, gid_t group) { __ensure(!"Not implemented"); __builtin_unreachable(); } int putgrent(const struct group *, FILE *) { __ensure(!"Not implemented"); __builtin_unreachable(); } struct group *fgetgrent(FILE *) { __ensure(!"Not implemented"); __builtin_unreachable(); }
21.783626
85
0.640537
CPL-1