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
272bd67d4ec53667ae654159aebdca7a03c5a766
2,666
hpp
C++
P-ART/HashTable.hpp
yuhao-su/RECIPE-TEST
43eda6df8afe29a3eeefdda7b78f6c61d0c38073
[ "Apache-2.0" ]
null
null
null
P-ART/HashTable.hpp
yuhao-su/RECIPE-TEST
43eda6df8afe29a3eeefdda7b78f6c61d0c38073
[ "Apache-2.0" ]
null
null
null
P-ART/HashTable.hpp
yuhao-su/RECIPE-TEST
43eda6df8afe29a3eeefdda7b78f6c61d0c38073
[ "Apache-2.0" ]
null
null
null
#include <cstdlib> #include <atomic> static inline void lock(bool* lkp) { while(!__sync_bool_compare_and_swap(lkp, 0, 1)){ } } static inline void unlock(bool* lkp) { *(lkp) = 0; } static inline bool try_lock(bool* lkp) { return __sync_bool_compare_and_swap(lkp, 0, 1); } const uint64_t CACHE_KEY_MASK = 0xffffffUL; class HashTable { private: struct HashItem { std::atomic<uint64_t> t_key; void* addr; bool lock; }; HashItem *items; uint64_t size; public: void insert(const uint64_t tree_key, void* node_addr) const{ uint64_t h_key = tree_key % this->size; lock(&this->items[h_key].lock); this->items[h_key].t_key = tree_key; this->items[h_key].addr = node_addr; unlock(&this->items[h_key].lock); } void* find(const uint64_t tree_key) const{ uint64_t h_key = tree_key % this->size; void* ret_addr; if (tree_key != items[h_key].t_key.load(std::memory_order_acquire)) ret_addr = NULL; else ret_addr = items[h_key].addr; if (tree_key != items[h_key].t_key.load(std::memory_order_release)) ret_addr = NULL; return ret_addr; } HashItem* get_ptr(const uint64_t tree_key) const{ uint64_t h_key = tree_key % this->size; return items + h_key; } bool check(const uint64_t tree_key) const{ uint64_t h_key = tree_key % this->size; return (tree_key == items[h_key].t_key.load(std::memory_order_relaxed)); } HashTable(int size) { this->items = new HashItem[size]; this->size = size; } ~HashTable() { delete [] items; } }; class HashTableUnsafe { private: typedef volatile void* HashItem; uint64_t size; public: HashItem *items; void insert(const uint64_t tree_key, void* node_addr) const{ uint64_t h_key = tree_key % this->size; this->items[h_key] = node_addr; } volatile void* find(const uint64_t tree_key) const{ uint64_t h_key = tree_key % this->size; return items[h_key]; } HashItem* get_ptr(const uint64_t tree_key) const{ uint64_t h_key = tree_key % this->size; return items + h_key; } bool check(const uint64_t tree_key) const{ uint64_t h_key = tree_key % this->size; return (items[h_key] != NULL); } HashTableUnsafe(int size) { this->items = (HashItem*)aligned_alloc(64, sizeof(HashItem) * size); this->size = size; memset(this->items, 0, size * sizeof(HashItem)); } ~HashTableUnsafe() { free(items); } };
26.929293
80
0.607652
yuhao-su
273145b94560f24ca3759a3c5e522abc375befa1
639
cpp
C++
Operating Systems - C++/Assignment1/hw1.cpp
lameimpala/university-code-samples
dc81154ab6350ddd3c19cb2917c840d4e79eaa2f
[ "Unlicense" ]
null
null
null
Operating Systems - C++/Assignment1/hw1.cpp
lameimpala/university-code-samples
dc81154ab6350ddd3c19cb2917c840d4e79eaa2f
[ "Unlicense" ]
null
null
null
Operating Systems - C++/Assignment1/hw1.cpp
lameimpala/university-code-samples
dc81154ab6350ddd3c19cb2917c840d4e79eaa2f
[ "Unlicense" ]
null
null
null
/* CSCI 480-2 Assignment 1 Reid Wixom z1693990 Due on February 14, 2017 Purpose This program utilizes a class named 'Processor' which handles querying system files to answer questions. Execution ./hw1.exe [filename] [filename] points to /cpu/cpuinfo by default */ #include <string> #include <iostream> #include "Processor.h" using namespace std; int main(int argc, char* argv[]) { Processor P; string defaultPath = "/proc/cpuinfo"; cout << P.getPartA((argv[1]) ? argv[1] : defaultPath); cout << P.getPartB(); cout << P.getPartC(); cout << P.getPartD(); }
19.363636
65
0.629108
lameimpala
27319f293d47c9e5ace28724dcedca551fdbae89
7,313
cpp
C++
src/UnitTest.Library.Desktop/WorldScopeEntityTest.cpp
jnighlight/DataDrivenGameEngine
10720cd2606cc75dac95213ff453bf3320ae3050
[ "MIT" ]
null
null
null
src/UnitTest.Library.Desktop/WorldScopeEntityTest.cpp
jnighlight/DataDrivenGameEngine
10720cd2606cc75dac95213ff453bf3320ae3050
[ "MIT" ]
null
null
null
src/UnitTest.Library.Desktop/WorldScopeEntityTest.cpp
jnighlight/DataDrivenGameEngine
10720cd2606cc75dac95213ff453bf3320ae3050
[ "MIT" ]
null
null
null
#include "pch.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Library { class FooEntity : public Entity { public: virtual FooEntity::~FooEntity() {}; void FooEntity::Update(WorldState& worldState) override { UNREFERENCED_PARAMETER(worldState); } }; CONCRETE_FACTORY(FooEntity, Entity) } namespace UnitTestLibraryDesktop { using namespace Library; TEST_CLASS(WorldScopeEntityTest) { private: static _CrtMemState sStartMemState; public: std::string mEntityName; std::string mSectorName; std::string mWorldName; Library::FooEntityFactory* fooEntFact; TEST_METHOD_INITIALIZE(setup) { mEntityName = "entity"; mSectorName = "sector"; mWorldName = "world"; fooEntFact = new Library::FooEntityFactory(); Library::Factory<Library::Entity>::Add(fooEntFact); { Library::WorldState test1; Library::World test2; Library::Sector test3; Library::Entity test4; } #ifdef _DEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); _CrtMemCheckpoint(&sStartMemState); #endif } TEST_METHOD_CLEANUP(Cleanup) { #ifdef _DEBUG _CrtMemState endMemState, diffMemState; _CrtMemCheckpoint(&endMemState); if (_CrtMemDifference(&diffMemState, &sStartMemState, &endMemState)) { _CrtMemDumpStatistics(&diffMemState); Assert::Fail(L"Memory Leaks!"); } Library::Factory<Library::Entity>::Remove(fooEntFact); delete fooEntFact; #endif } TEST_METHOD(Entity_Constructor) { Entity entity; } TEST_METHOD(Entity_Name) { Entity entity; entity.SetName(mEntityName); Assert::AreEqual(mEntityName, entity.GetName()); } TEST_METHOD(Entity_Sector) { Sector sector; Entity* entityThing = new Entity(); Assert::IsNull(entityThing->GetSector()); entityThing->SetSector(&sector); Assert::IsNotNull(entityThing->GetSector()); Assert::IsTrue(sector == *entityThing->GetSector()); } //TODO: This is a noop for now, so...just covering it TEST_METHOD(Entity_Update) { Entity entity; WorldState worldState; entity.Update(worldState); } TEST_METHOD(Entity_Copy) { std::string entityNameCopy = mEntityName; entityNameCopy.append("Copy"); Entity entity; entity.SetName(mEntityName); Assert::AreEqual(mEntityName, entity.GetName()); Entity entityCreateCopy = entity; Assert::AreEqual(entityNameCopy, entityCreateCopy.GetName()); Entity entityOverwriteCopy; entityOverwriteCopy = entity; Assert::AreEqual(entityNameCopy, entityOverwriteCopy.GetName()); } TEST_METHOD(Entity_Move) { Entity entity; entity.SetName(mEntityName); Entity entity2; entity2.SetName(mEntityName); Assert::AreEqual(mEntityName, entity.GetName()); Entity entityCreateMove = std::move(entity); Assert::AreEqual(mEntityName, entityCreateMove.GetName()); Entity entityOverwriteMove; entityOverwriteMove = std::move(entity); Assert::AreEqual(mEntityName, entityOverwriteMove.GetName()); } TEST_METHOD(Entity_Move_InSector) { Sector sector; Entity* entity = new Entity(); entity->SetName(mEntityName); entity->SetSector(&sector); Entity* entity2= new Entity(); entity2->SetName(mEntityName); entity2->SetSector(&sector); Assert::AreEqual(mEntityName, entity->GetName()); Entity* entityCreateMove = new Entity(std::move(*entity)); Assert::AreEqual(mEntityName, entityCreateMove->GetName()); Entity* entityOverwriteMove = new Entity(); (*entityOverwriteMove) = std::move(*entity2); Assert::AreEqual(mEntityName, entityOverwriteMove->GetName()); delete entity; delete entity2; } TEST_METHOD(Sector_Copy) { std::string sectorNameCopy = mSectorName; sectorNameCopy.append("Copy"); Sector sector; sector.SetName(mSectorName); Assert::AreEqual(mSectorName, sector.GetName()); Sector sectorCreateCopy = sector; Assert::AreEqual(sectorNameCopy, sectorCreateCopy.GetName()); Sector sectorOverwriteCopy; sectorOverwriteCopy = sector; Assert::AreEqual(sectorNameCopy, sectorOverwriteCopy.GetName()); } TEST_METHOD(Sector_Move) { Sector sector; sector.SetName(mSectorName); Sector sector2; sector2.SetName(mSectorName); Assert::AreEqual(mSectorName, sector.GetName()); Sector sectorCreateMove = std::move(sector); Assert::AreEqual(mSectorName, sectorCreateMove.GetName()); Sector sectorOverwriteMove; sectorOverwriteMove = std::move(sector); Assert::AreEqual(mSectorName, sectorOverwriteMove.GetName()); } TEST_METHOD(Sector_Move_InSector) { World world; Sector* sector = new Sector(); sector->SetName(mSectorName); sector->SetWorld(&world); Sector* sector2= new Sector(); sector2->SetName(mSectorName); sector2->SetWorld(&world); Assert::AreEqual(mSectorName, sector->GetName()); Sector* sectorCreateMove = new Sector(std::move(*sector)); Assert::AreEqual(mSectorName, sectorCreateMove->GetName()); Sector* sectorOverwriteMove = new Sector(); (*sectorOverwriteMove) = std::move(*sector2); Assert::AreEqual(mSectorName, sectorOverwriteMove->GetName()); delete sector; delete sector2; } TEST_METHOD(Sector_Update) { Sector sector; sector.SetName("sector"); sector.CreateEntity("FooEntity", "Entity1"); WorldState worldState; sector.Update(worldState); //This doesn't do anything yet, so basically just checking it runs right } TEST_METHOD(World_Constructor) { World world; Datum& defaultSectors = world.GetSectors(); Assert::AreEqual(0u, defaultSectors.Size()); } TEST_METHOD(World_Name) { World world; std::string worldName = "worldName"; world.SetName(worldName); Assert::AreEqual(worldName, world.GetName()); } TEST_METHOD(World_CreateSectors) { World world; std::string sectorName = "newSector"; Sector& defaultSector = world.CreateSector(sectorName); Assert::AreEqual(sectorName, defaultSector.GetName()); Datum& defaultSectors = world.GetSectors(); Assert::AreEqual(1u, defaultSectors.Size()); } TEST_METHOD(World_CopyConstructors) { World world; world.SetName("bob"); world.CreateSector("Sector1"); World worldCopy = world; Datum& defaultSectorsCopy = worldCopy.GetSectors(); Assert::AreEqual(1u, defaultSectorsCopy.Size()); World worldOverwrite; worldOverwrite = world; Datum& defaultSectorsOverwrite = worldOverwrite.GetSectors(); Assert::AreEqual(1u, defaultSectorsOverwrite.Size()); } TEST_METHOD(World_MoveConstructors) { World world; world.SetName("bob"); world.CreateSector("Sector1"); World worldCopy = std::move(world); World world2; world2.SetName("bob"); world2.CreateSector("Sector1"); Datum& defaultSectorsCopy = worldCopy.GetSectors(); Assert::AreEqual(1u, defaultSectorsCopy.Size()); World worldOverwrite; worldOverwrite = std::move(world2); Datum& defaultSectorsOverwrite = worldOverwrite.GetSectors(); Assert::AreEqual(1u, defaultSectorsOverwrite.Size()); } TEST_METHOD(World_Update) { World world; world.SetName("bob"); world.CreateSector("World1"); WorldState worldState; world.Update(worldState); //This doesn't do anything yet, so basically just checking it runs right } }; _CrtMemState WorldScopeEntityTest::sStartMemState; }
25.75
102
0.719267
jnighlight
27391c994b566c4bd8e607729ccd8f96c8d2440b
14,636
hpp
C++
sdl/Hypergraph/BestPathString.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Hypergraph/BestPathString.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Hypergraph/BestPathString.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** \file sequences of symbols, or a formatted string from that, for terminal yields of a best path tree. */ #ifndef HYP__BESTPATHSTRING_JG201254_HPP #define HYP__BESTPATHSTRING_JG201254_HPP #pragma once #include <sdl/Config/Init.hpp> #include <sdl/Hypergraph/BestPath.hpp> #include <sdl/Hypergraph/GetString.hpp> #include <sdl/Util/AcceptString.hpp> #include <sdl/Util/Equal.hpp> #include <sdl/Util/SpaceToken.hpp> #include <sdl/Util/StringBuilder.hpp> #include <sdl/Util/WordToPhrase.hpp> #include <sdl/LexicalCast.hpp> #include <boost/variant/static_visitor.hpp> #include <functional> namespace sdl { namespace Hypergraph { typedef sdl::function<void(Syms&, IVocabulary*)> SymsRewrite; struct IdentitySymsRewrite { void operator()(Syms&, IVocabulary*) const {} }; inline SymsRewrite identitySymsRewrite() { return SymsRewrite(IdentitySymsRewrite()); } unsigned const kReserveForBestPathString = 500; template <class Arc> void appendBestPathStringForDeriv(Util::StringBuilder& out, DerivationPtr const& deriv, IHypergraph<Arc> const& hg, DerivationStringOptions const& opts = DerivationStringOptions(kUnquoted), bool printWeight = false) { if (printWeight) out(deriv->weightForArc<Arc>())(' '); textFromDeriv(out, deriv, hg, opts); } template <class Arc> Util::StringBuilder& bestPathString(Util::StringBuilder& out, IHypergraph<Arc> const& hg, BestPathOptions const& bestPathOpts = BestPathOptions(), DerivationStringOptions const& opts = DerivationStringOptions(kUnquoted), bool printWeight = false, char const* fallbackIfNoDerivation = "[no derivation exists]") { DerivationPtr deriv = bestPath(hg, bestPathOpts); if (!deriv) return out(fallbackIfNoDerivation); else { out.reserve(kReserveForBestPathString); appendBestPathStringForDeriv(out, deriv, hg, opts, printWeight); return out; } } template <class Arc> std::string bestPathString(IHypergraph<Arc> const& hg, BestPathOptions const& bestPathOpts = BestPathOptions(), DerivationStringOptions const& opts = DerivationStringOptions(kUnquoted), bool printWeight = false, char const* fallbackIfNoDerivation = "[no derivation exists]") { DerivationPtr deriv = bestPath(hg, bestPathOpts); if (!deriv) return fallbackIfNoDerivation; else { Util::StringBuilder out(kReserveForBestPathString); appendBestPathStringForDeriv(out, deriv, hg, opts, printWeight); return out.str(); } } template <class Arc> Syms& bestPathSymsAppend(Syms& syms, IHypergraph<Arc> const& hg, BestPathOptions const& bestPathOpts = BestPathOptions(), WhichSymbolOptions const& opts = WhichSymbolOptions()) { return symsFromDerivAppend(syms, bestPath(hg, bestPathOpts), hg, opts); } template <class Arc> Syms& bestPathSymsAppend(Syms& syms, FeatureValue& cost, IHypergraph<Arc> const& hg, BestPathOptions const& bestPathOpts = BestPathOptions(), WhichSymbolOptions const& opts = WhichSymbolOptions()) { Derivation::DerivAndWeight<Arc> derivWeight(bestDerivWeight(hg, bestPathOpts)); if (derivWeight.deriv) { cost = derivWeight.weight.value_; symsFromDerivAppend(syms, derivWeight.deriv, hg, opts); } else cost = std::numeric_limits<FeatureValue>::infinity(); return syms; } template <class Arc> Syms bestPathSyms(IHypergraph<Arc> const& hg, BestPathOptions const& bestPathOpts = BestPathOptions()) { Syms syms; bestPathSymsAppend(syms, hg, bestPathOpts); return syms; } template <class Arc> std::string nbestString(IHypergraph<Arc> const& hg, unsigned nbest, BestPathOutOptions opt = BestPathOutOptions()) { opt.nbest = nbest; std::ostringstream out; opt.out_nbest(out, hg); return out.str(); } // Simplified interface (without best path options): template <class Arc> std::string bestPathString(IHypergraph<Arc> const& hg, DerivationStringOptions const& opts, bool printWeight = false) { return bestPathString(hg, BestPathOptions(), opts, printWeight); } // Prints best weight and the associated string. template <class Arc> std::string bestPathStringWeighted(IHypergraph<Arc> const& hg, BestPathOptions const& bestPathOpts = BestPathOptions(), DerivationStringOptions const& opts = DerivationStringOptions()) { return bestPathString(hg, bestPathOpts, opts, true); } struct ToStringVisitor : public boost::static_visitor<> { ToStringVisitor(std::string& outString, FeatureValue& cost, SymsRewrite const& symsRewrite, DerivationStringOptions const& stringOpt = DerivationStringOptions(kUnquoted, "")) : cost(cost), outString(outString), symsRewrite(symsRewrite), stringOpt(stringOpt) {} FeatureValue& cost; template <class T> void operator()(shared_ptr<T>& pData) const { (*this)(*pData); } void operator()(std::string const& str) const { outString = str; } /** 1-best string only (no weight / features) */ template <class Arc> void operator()(Hypergraph::IHypergraph<Arc> const& hg) const { using namespace Hypergraph; BestPathOptions bestPathOpts; Syms tokens; bestPathSymsAppend(tokens, cost, hg, bestPathOpts); IVocabulary* voc = hg.getVocabulary().get(); if (symsRewrite) symsRewrite(tokens, voc); outString = textFromSyms(tokens, *voc, stringOpt); } std::string& outString; SymsRewrite symsRewrite; DerivationStringOptions stringOpt; }; struct AcceptBestOptions : NbestPathOptions, Util::SpaceTokenOptions { template <class Config> void configure(Config& config) { Util::SpaceTokenOptions::configure(config); NbestPathOptions::configure(config); config.is("AcceptBestOptions"); config("string-cost", &stringCost).init((FeatureValue)1)("cost to use if pipeline has string output"); config("nbest-for-cost", &nbestForCost) .init(false)("use nbest rank (1, 2, ...) instead of path cost or string-cost"); config("detok", &detok) .init(true)( "treat hg output as single string (detokenized using hg-string opts), or multiple strings if " "'space-token' splits them"); config("hg-string", &hgString) .verbose()("if detok, use this to convert hypergraph path to single string"); } AcceptBestOptions() { hgString.setChars(); Config::inits(this); } FeatureValue stringCost; bool nbestForCost; DerivationStringOptions hgString; bool detok; FeatureValue costMaybeNbest(NbestId n, FeatureValue cost) const { return nbestForCost ? (FeatureValue)n : cost; } }; /** replace escSpace token -> space token. */ struct SymStrReplace { bool enabled() const { return !escSpace.empty(); } std::string escSpace; SymStrReplace(std::string const& escSpace = Util::kEscSpace) : escSpace(escSpace) {} void operator()(Syms& syms, IVocabulary* vocab) const { Sym const esc = vocab->sym(escSpace, kTerminal); if (esc) std::replace(syms.begin(), syms.end(), esc, vocab->add(Util::kSpace, kTerminal)); } }; /** replace escSpace token -> space token, given vocabulary in advance */ struct SymReplace { bool enabled() const { return escSpace; } Sym escSpace; Sym space; SymReplace(IVocabulary* vocab, std::string const& escSpaceStr = Util::kEscSpace, std::string const& spaceStr = Util::kSpace) : escSpace(escSpaceStr.empty() ? NoSymbol : vocab->sym(escSpaceStr, kTerminal)) , space(vocab->add(spaceStr, kTerminal)) {} void operator()(Syms& syms, IVocabulary*) const { if (escSpace) std::replace(syms.begin(), syms.end(), escSpace, space); } }; struct SymReplaceCache { bool enabled() const { return !escSpaceStr.empty(); } IVocabulary* vocab; Sym escSpace, space; std::string escSpaceStr, spaceStr; SymReplaceCache(std::string const& escSpaceStr = Util::kEscSpace, IVocabulary* vocab = 0, std::string const& spaceStr = Util::kSpace) : vocab(vocab), escSpaceStr(escSpaceStr), spaceStr(spaceStr) { initSyms(); } void operator()(Syms& syms, IVocabulary* vocab_) const { const_cast<SymReplaceCache&>(*this).maybeInitSyms(vocab_); replace(syms); } void reset(IVocabulary* v) { vocab = v; initSyms(); } void replace(Syms& syms) const { if (escSpace) std::replace(syms.begin(), syms.end(), escSpace, space); } private: void maybeInitSyms(IVocabulary* vocab_) { assert(vocab_); if (vocab_ != vocab) { vocab = vocab_; initSyms(); } } void initSyms() { if (vocab && !escSpaceStr.empty()) { escSpace = vocab->sym(escSpaceStr, kTerminal); space = vocab->add(spaceStr, kTerminal); } else { escSpace = NoSymbol; } } }; struct AcceptStringVisitor : public boost::static_visitor<> { /** \param *skipOriginalWord is a string that is skipped if it's an nbest output (the whole sentence is just that word), and must be stable against modifications to your vocabulary (i.e. you need to pass address of a *copy* of voc->str(id). if skipOriginalWord is null then the nbests are unfiltered */ AcceptStringVisitor(std::string const* skipOriginalWord, Util::IAcceptString const& accept, AcceptBestOptions const& options = AcceptBestOptions(), SymsRewrite const& symsRewrite = identitySymsRewrite(), unsigned* nAccepted = 0) : skipOriginalWord(skipOriginalWord) , options(options) , accept(accept) , symsRewrite(symsRewrite) , voc() , skipOriginalSym(NoSymbol) , nAccepted(nAccepted) {} std::string const* skipOriginalWord; AcceptBestOptions const& options; SymsRewrite symsRewrite; Util::IAcceptString const& accept; mutable Sym skipOriginalSym; unsigned* nAccepted; void countAccepted() const { if (nAccepted) ++*nAccepted; } template <class T> void operator()(shared_ptr<T>& pData) const { (*this)(*pData); } /// for runPipeline string output. bool operator()(std::string const& str) const { if (skipOriginalWord && str == *skipOriginalWord) return false; accept(str); countAccepted(); return accept.finishPhrase(options.costMaybeNbest(1, options.stringCost)); } /// for runPipeline hg output. remember to catch EmptySetException so you can /// indicate that no paths were accepted template <class Arc> void operator()(Hypergraph::IHypergraph<Arc> const& hg) const { using namespace Hypergraph; voc = hg.getVocabulary().get(); skipOriginalSym = skipOriginalWord ? voc->addTerminal(*skipOriginalWord) : NoSymbol; hgBase = &hg; SDL_DEBUG(Hypergraph.BestPathString, "RunPipeline visitor for Translitate etc. computing " << options.nbest << "-best for hg:\n " << hg); options.visit_nbest(hg, *this, Hypergraph::kThrowEmptySetException); } /// for visit_nbest for runPipeline hg output. to help compiler, we needed to template on Weight instead of /// Arc template <class Weight> bool operator()(Hypergraph::DerivationPtr const& deriv, Weight const& weight, NbestId n) const { assert(voc); assert(deriv); Syms tokens; // TODO: unnecessary copy - visit symsFromDerivAppend(tokens, deriv, static_cast<IHypergraph<ArcTpl<Weight>> const&>(*hgBase), options.hgString); if (symsRewrite) symsRewrite(tokens, voc); if (!options.detok) { if (!skipOriginalSym || !(tokens.size() == 1 && tokens[0] == skipOriginalSym)) accept.phrase(tokens, *voc); } else { Util::StringBuilder wordBuf; // we may have to concatenate several tokens into one std::string const& spaceToken = options.spaceToken; if (spaceToken.empty()) { textFromSyms(wordBuf, tokens, *voc, options.hgString); if (skipOriginalWord) { SDL_DEBUG(xmt.RunPipeline.runPipelineToStrings, "'" << wordBuf << "' vs original '" << *skipOriginalWord << " equal=" << (wordBuf == *skipOriginalWord)); if (wordBuf == *skipOriginalWord) return true; // continue nbests } accept(wordBuf); // single token result } else { // split into several tokens Sym const spaceSym = voc->add(spaceToken, kTerminal); Psym begin = tokens.begin(), end = tokens.end(); Psym word0 = begin; unsigned nSpaceSep = 0; for (Psym i = begin; i < end; ++i) { if (*i == spaceSym) if (word0 < i) { // nonempty token-slice ++nSpaceSep; wordBuf.clear(); textFromSyms(wordBuf, SymSlice(word0, i), *voc, options.hgString); accept(wordBuf); word0 = i + 1; } } if (word0 < end) { wordBuf.clear(); textFromSyms(wordBuf, SymSlice(word0, end), *voc, options.hgString); if (!nSpaceSep && skipOriginalWord) { SDL_DEBUG(xmt.RunPipeline.runPipelineToStrings, "single word '" << wordBuf << "' vs original '" << *skipOriginalWord << " equal=" << (wordBuf == *skipOriginalWord)); if (wordBuf == *skipOriginalWord) return true; // continue nbests } accept(wordBuf); } } } FeatureValue const cost = deriv->weight<Weight>().value_; countAccepted(); return accept.finishPhrase(options.costMaybeNbest(n + 1, cost)); // 1-best has index 0 // TODO: might want a separate indicator for preferring e.g. 1-best to // original but not 2-best, or else use log(1/(n+1)) } private: mutable IVocabulary* voc; mutable HypergraphBase const* hgBase; }; }} #endif
36.59
115
0.662134
sdl-research
274200ae203ee2dad78f5246c20420d430b50edd
4,101
cpp
C++
rute/qt_cpp/auto/margins.cpp
emoon/Rute
b8981fa9fb0508691399b0aa9a565686ebcc0a69
[ "Apache-2.0", "MIT" ]
42
2018-05-04T08:57:57.000Z
2021-11-08T13:05:23.000Z
rute/qt_cpp/auto/margins.cpp
emoon/Rute
b8981fa9fb0508691399b0aa9a565686ebcc0a69
[ "Apache-2.0", "MIT" ]
18
2018-05-31T12:11:35.000Z
2021-02-08T04:14:55.000Z
rute/qt_cpp/auto/margins.cpp
emoon/ui_gen
b8981fa9fb0508691399b0aa9a565686ebcc0a69
[ "Apache-2.0", "MIT" ]
2
2019-04-17T04:54:15.000Z
2021-03-19T17:38:05.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // This file is auto-generated by rute_gen. DO NOT EDIT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "../rute_base.h" #include "../rute_manual.h" #include <QMargins> #include "margins_ffi.h" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static bool margins_is_null(struct RUBase* self_c) { WRMargins* qt_value = (WRMargins*)self_c; auto ret_value = qt_value->isNull(); return ret_value; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int margins_left(struct RUBase* self_c) { WRMargins* qt_value = (WRMargins*)self_c; auto ret_value = qt_value->left(); return ret_value; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int margins_top(struct RUBase* self_c) { WRMargins* qt_value = (WRMargins*)self_c; auto ret_value = qt_value->top(); return ret_value; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int margins_right(struct RUBase* self_c) { WRMargins* qt_value = (WRMargins*)self_c; auto ret_value = qt_value->right(); return ret_value; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int margins_bottom(struct RUBase* self_c) { WRMargins* qt_value = (WRMargins*)self_c; auto ret_value = qt_value->bottom(); return ret_value; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void margins_set_left(struct RUBase* self_c, int left) { WRMargins* qt_value = (WRMargins*)self_c; qt_value->setLeft(left); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void margins_set_top(struct RUBase* self_c, int top) { WRMargins* qt_value = (WRMargins*)self_c; qt_value->setTop(top); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void margins_set_right(struct RUBase* self_c, int right) { WRMargins* qt_value = (WRMargins*)self_c; qt_value->setRight(right); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void margins_set_bottom(struct RUBase* self_c, int bottom) { WRMargins* qt_value = (WRMargins*)self_c; qt_value->setBottom(bottom); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static struct RUMargins create_margins( struct RUBase* priv_data, RUDeleteCallback delete_callback, void* private_user_data) { auto ctl = generic_create_func_with_delete<struct RUMargins, WRMargins>(priv_data, delete_callback, private_user_data); ctl.all_funcs = &s_margins_all_funcs; return ctl; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void destroy_margins(struct RUBase* priv_data) { destroy_generic<WRMargins>(priv_data); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct RUMarginsFuncs s_margins_funcs = { destroy_margins, margins_is_null, margins_left, margins_top, margins_right, margins_bottom, margins_set_left, margins_set_top, margins_set_right, margins_set_bottom, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct RUMarginsAllFuncs s_margins_all_funcs = { &s_margins_funcs, };
35.051282
123
0.405023
emoon
2747466f400285cc761eba800c2816ccce45f122
1,284
cpp
C++
sdk/core/azure-core/test/ut/extendable_enumeration_test.cpp
JinmingHu-MSFT/azure-sdk-for-cpp
933486385a54a5a09a7444dbd823425f145ad75a
[ "MIT" ]
1
2022-01-19T22:54:41.000Z
2022-01-19T22:54:41.000Z
sdk/core/azure-core/test/ut/extendable_enumeration_test.cpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
sdk/core/azure-core/test/ut/extendable_enumeration_test.cpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include <azure/core/internal/extendable_enumeration.hpp> #include <gtest/gtest.h> #include <string> using namespace Azure::Core; class MyEnum : public Azure::Core::_internal::ExtendableEnumeration<MyEnum> { public: MyEnum(std::string initialValue) : ExtendableEnumeration(std::move(initialValue)) {} MyEnum() = default; static const MyEnum Value1; static const MyEnum Value2; static const MyEnum Value3; }; const MyEnum MyEnum::Value1("Value1"); const MyEnum MyEnum::Value2("Value2"); const MyEnum MyEnum::Value3("Value3"); TEST(ExtendableEnumeration, BasicTests) { { MyEnum enum1 = MyEnum::Value1; EXPECT_EQ(enum1, MyEnum::Value1); } { MyEnum enumToTest(MyEnum::Value2); EXPECT_NE(enumToTest, MyEnum::Value3); } { MyEnum enumVal; GTEST_LOG_(INFO) << enumVal.ToString(); } { MyEnum enumVal(MyEnum::Value3); EXPECT_EQ(enumVal.ToString(), "Value3"); } { MyEnum enumVal(MyEnum::Value1); MyEnum enumVal2(enumVal); EXPECT_EQ(enumVal, enumVal2); } { MyEnum enumVal(MyEnum::Value1); MyEnum enumVal2; EXPECT_EQ(enumVal, MyEnum::Value1); enumVal2 = enumVal; EXPECT_EQ(enumVal, enumVal2); } }
22.137931
86
0.696262
JinmingHu-MSFT
2747c4ce09ea82240ca76b6ef6eec2a9c77ed3b2
148
cpp
C++
kernel/src/program.cpp
pradosh-arduino/pradoshOS
b7c2a8b238261fc61460e609fd8352aa62b5f32e
[ "MIT" ]
9
2021-11-17T10:27:18.000Z
2022-03-16T09:43:24.000Z
kernel/src/program.cpp
pradosh-arduino/pradoshOS
b7c2a8b238261fc61460e609fd8352aa62b5f32e
[ "MIT" ]
1
2022-03-17T08:31:05.000Z
2022-03-28T02:50:59.000Z
kernel/src/program.cpp
pradosh-arduino/pradoshOS
b7c2a8b238261fc61460e609fd8352aa62b5f32e
[ "MIT" ]
1
2021-12-21T09:49:02.000Z
2021-12-21T09:49:02.000Z
#include "mtask.h" extern "C" void programASM(); void program(){ lock_scheduler(); schedule(); unlock_scheduler(); programASM(); }
14.8
29
0.628378
pradosh-arduino
274abdcb400bdaf7c6b3f288d1f934a8b0911318
2,031
cpp
C++
samples/RenderTargets/Source/Main.cpp
bitsauce/NibbleSauce3D
79792388eaad659c241a292c470ee9fa6413d354
[ "MIT" ]
null
null
null
samples/RenderTargets/Source/Main.cpp
bitsauce/NibbleSauce3D
79792388eaad659c241a292c470ee9fa6413d354
[ "MIT" ]
null
null
null
samples/RenderTargets/Source/Main.cpp
bitsauce/NibbleSauce3D
79792388eaad659c241a292c470ee9fa6413d354
[ "MIT" ]
1
2021-04-25T09:58:46.000Z
2021-04-25T09:58:46.000Z
#include <Sauce/Sauce.h> using namespace sauce; class RenderTargetsGame : public Game { RenderTarget2D *m_renderTarget; RenderTarget2D *m_renderTarget2; Texture2DRef m_texture; public: void onStart(GameEvent *e) { GraphicsContext *graphicsContext = getWindow()->getGraphicsContext(); m_renderTarget = graphicsContext->createRenderTarget(128, 128); m_renderTarget2 = graphicsContext->createRenderTarget(128, 128); m_texture = Texture2DRef(getWindow()->getGraphicsContext()->createTexture(Pixmap("Image.png"))); Game::onStart(e); } void onDraw(DrawEvent *e) { GraphicsContext *graphicsContext = e->getGraphicsContext(); graphicsContext->setTexture(0); graphicsContext->pushRenderTarget(m_renderTarget2); graphicsContext->clear(GraphicsContext::COLOR_BUFFER); graphicsContext->pushRenderTarget(m_renderTarget); graphicsContext->clear(GraphicsContext::COLOR_BUFFER); graphicsContext->setTexture(m_texture); graphicsContext->drawRectangle(0, 0, 64, 64, Color::White, TextureRegion(0.5,0.5,0.9,0.9)); graphicsContext->popRenderTarget(); graphicsContext->drawRectangle(64, 0, 64, 64, Color(0, 255, 0, 255)); graphicsContext->popRenderTarget(); m_renderTarget->getTexture()->exportToFile("../RenderTarget.png"); graphicsContext->drawRectangle(0, 0, graphicsContext->getWidth(), graphicsContext->getHeight(), Color(127, 127, 127, 255)); graphicsContext->setTexture(m_renderTarget->getTexture()); graphicsContext->drawRectangle(0, 0, 128, 128); graphicsContext->setTexture(m_renderTarget2->getTexture()); graphicsContext->drawRectangle(0, 0, 128, 128); graphicsContext->setTexture(m_renderTarget->getTexture()); graphicsContext->drawRectangle(300, 300, 64, 64); Game::onDraw(e); } }; int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) { GameDesc desc; desc.name = "RenderTargets Sample"; desc.workingDirectory = "../Data"; desc.flags = SAUCE_WINDOW_RESIZABLE; desc.graphicsBackend = SAUCE_OPENGL_3; RenderTargetsGame game; return game.run(desc); }
32.758065
125
0.754801
bitsauce
274bd5416727fdd152318c5929a28dedbeb4a6d4
1,375
cpp
C++
src/mod/robot/standable_heads.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
33
2016-02-18T04:27:53.000Z
2022-01-15T18:59:53.000Z
src/mod/robot/standable_heads.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2018-01-10T18:41:38.000Z
2020-10-01T13:34:53.000Z
src/mod/robot/standable_heads.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
14
2017-08-06T23:02:49.000Z
2021-08-24T00:24:16.000Z
#include "mod.h" #include "util/scope.h" #include "stub/gamerules.h" #include "stub/tfplayer.h" namespace Mod::Robot::Standable_Heads { RefCount rc_TFPlayerThink; DETOUR_DECL_MEMBER(void, CTFPlayer_TFPlayerThink) { SCOPED_INCREMENT(rc_TFPlayerThink); DETOUR_MEMBER_CALL(CTFPlayer_TFPlayerThink)(); } DETOUR_DECL_MEMBER(void, CTFPlayer_ApplyAbsVelocityImpulse, const Vector *v1) { auto player = reinterpret_cast<CTFPlayer *>(this); if (rc_TFPlayerThink > 0 && v1->z == 100.0f && TFGameRules()->IsMannVsMachineMode()) { CBaseEntity *groundent = player->GetGroundEntity(); if (groundent != nullptr && groundent->IsPlayer()) { return; } } DETOUR_MEMBER_CALL(CTFPlayer_ApplyAbsVelocityImpulse)(v1); } class CMod : public IMod { public: CMod() : IMod("Robot:Standable_Heads") { MOD_ADD_DETOUR_MEMBER(CTFPlayer_TFPlayerThink, "CTFPlayer::TFPlayerThink"); MOD_ADD_DETOUR_MEMBER(CTFPlayer_ApplyAbsVelocityImpulse, "CTFPlayer::ApplyAbsVelocityImpulse"); } }; CMod s_Mod; ConVar cvar_enable("sig_robot_standable_heads", "0", FCVAR_NOTIFY, "Mod: remove the sliding force that prevents players from standing on robots' heads", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool()); }); }
28.061224
99
0.704
fugueinheels
274c366cb552ef6604cf69aa7cb0255b76ae1ec9
3,011
hpp
C++
descriptors/rsd.hpp
vbillys/pose-estimation
e1b57da68d9c961358a6f8fd37706ed521c5c256
[ "MIT" ]
63
2017-03-30T23:56:47.000Z
2022-03-20T10:30:32.000Z
descriptors/rsd.hpp
vbillys/pose-estimation
e1b57da68d9c961358a6f8fd37706ed521c5c256
[ "MIT" ]
2
2017-07-10T14:14:50.000Z
2020-07-10T10:08:04.000Z
descriptors/rsd.hpp
aviate/pose-estimation
e1b57da68d9c961358a6f8fd37706ed521c5c256
[ "MIT" ]
15
2017-03-30T23:56:52.000Z
2021-10-12T12:08:20.000Z
#pragma once #include <pcl/features/rsd.h> #include "../types.h" #include "../parameter.h" #include "../featuredescription.hpp" #include "../utils.hpp" namespace PoseEstimation { /** #include "../utils.hpp" * @brief Feature Description using Radius-based Surface Descriptor (RSD) */ template<typename PointT> class RSDFeatureDescriptor : public FeatureDescriptor<PointT, pcl::PrincipalRadiiRSD> { public: typedef pcl::PrincipalRadiiRSD DescriptorType; RSDFeatureDescriptor() : FeatureDescriptor<PointT, DescriptorType>() { typename pcl::search::KdTree<PointT>::Ptr kdtree(new pcl::search::KdTree<PointT>); _rsd.setSearchMethod(kdtree); } virtual void describe(PC<PointT> &pc, const typename pcl::PointCloud<PointT>::Ptr &keypoints, const PclNormalCloud::Ptr &normals, pcl::PointCloud<DescriptorType>::Ptr &features) { _rsd.setInputCloud(keypoints); _rsd.setInputNormals(normals); _rsd.setRadiusSearch(pc.resolution() * searchRadius.value<float>()); _rsd.setPlaneRadius(pc.resolution() * planeRadius.value<float>()); _rsd.setSaveHistograms(saveHistograms.value<bool>()); typename pcl::search::KdTree<PointT>::Ptr kdtree(new pcl::search::KdTree<PointT>); _rsd.setSearchMethod(kdtree); kdtree->setInputCloud(keypoints); _rsd.setSearchSurface(keypoints); Logger::tic("RSD Feature Extraction"); _rsd.compute(*features); Logger::toc("RSD Feature Extraction"); } static ParameterCategory argumentCategory; PARAMETER_CATEGORY_GETTER(argumentCategory) static Parameter saveHistograms; static Parameter searchRadius; static Parameter planeRadius; private: pcl::RSDEstimation<PointT, NormalType, DescriptorType> _rsd; }; template<typename PointT> ParameterCategory RSDFeatureDescriptor<PointT>::argumentCategory( "RSD", "Feature description using Radius-based Surface Descriptor (RSD)", PipelineModuleType::FeatureDescriptor); template<typename PointT> Parameter RSDFeatureDescriptor<PointT>::saveHistograms = Parameter( "RSD", "save_hist", (bool)false, "Whether to save histograms"); template<typename PointT> Parameter RSDFeatureDescriptor<PointT>::searchRadius = Parameter( "RSD", "search_r", (float)5.0f, "Search radius for finding neighbors", { std::make_shared<VariableConstraint>( ParameterConstraintType::GreaterThan, "pc_normal_nn") }); template<typename PointT> Parameter RSDFeatureDescriptor<PointT>::planeRadius = Parameter( "RSD", "plane_r", (float)30.0f, "Maximum radius, above which everything can be considered planar (should be 10-20 times RSD_search_r)"); }
37.6375
148
0.647957
vbillys
27526103430b6e891e83753413540e0d771ddc63
3,808
hpp
C++
src/common/make-unique.hpp
bsc-ssrg/NORNS
4fd2d181019eceadb8b1b04a94e3756476326239
[ "MIT" ]
2
2019-11-11T11:34:56.000Z
2020-12-08T02:13:48.000Z
src/common/make-unique.hpp
bsc-ssrg/NORNS
4fd2d181019eceadb8b1b04a94e3756476326239
[ "MIT" ]
null
null
null
src/common/make-unique.hpp
bsc-ssrg/NORNS
4fd2d181019eceadb8b1b04a94e3756476326239
[ "MIT" ]
null
null
null
/************************************************************************* * Copyright (C) 2017-2019 Barcelona Supercomputing Center * * Centro Nacional de Supercomputacion * * All rights reserved. * * * * This file is part of NORNS, a service that allows other programs to * * start, track and manage asynchronous transfers of data resources * * between different storage backends. * * * * See AUTHORS file in the top level directory for information regarding * * developers and contributors. * * * * This software was developed as part of the EC H2020 funded project * * NEXTGenIO (Project ID: 671951). * * www.nextgenio.eu * * * * 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 __MAKE_UNIQUE_HPP__ #define __MAKE_UNIQUE_HPP__ #include <memory> // since C++11 doesn't offer make_unique, we borrow the template definition // from C++14 (see https://isocpp.org/files/papers/N3656.txt) namespace std { template<class T> struct _Unique_if { typedef unique_ptr<T> _Single_object; }; template<class T> struct _Unique_if<T[]> { typedef unique_ptr<T[]> _Unknown_bound; }; template<class T, size_t N> struct _Unique_if<T[N]> { typedef void _Known_bound; }; template<class T, class... Args> typename _Unique_if<T>::_Single_object make_unique(Args&&... args) { return unique_ptr<T>(new T(std::forward<Args>(args)...)); } template<class T> typename _Unique_if<T>::_Unknown_bound make_unique(size_t n) { typedef typename remove_extent<T>::type U; return unique_ptr<T>(new U[n]()); } template<class T, class... Args> typename _Unique_if<T>::_Known_bound make_unique(Args&&...) = delete; } #endif /* __MAKE_UNIQUE_HPP__ */
49.454545
75
0.508666
bsc-ssrg
2753b2c79c89beed8c6ae3d91178e3abc861104c
1,207
cpp
C++
Dynamic Programming/SPOJ M3TILE/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
1
2020-03-05T09:09:36.000Z
2020-03-05T09:09:36.000Z
Dynamic Programming/SPOJ M3TILE/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
null
null
null
Dynamic Programming/SPOJ M3TILE/Code.cpp
adelnobel/Training-for-ACM-ICPC-problems
8030d24ab3ce1f50821b22647bf9195b41f932b1
[ "MIT" ]
null
null
null
#include <cstring> #include <algorithm> #include <functional> #include <vector> #include <map> #include <set> #include <fstream> #include <stdio.h> #include <iostream> #include <string> #include <sstream> #include <cmath> #include <queue> using namespace std; int arr[31][8]; int n, tot; int solve(int y, int mask) { if(y > n) { if(mask == 0) return 1; return 0; } if(arr[y][mask] != -1) return arr[y][mask]; int val; if(mask == 0) { val = solve(y+1, 4) + solve(y+1, 7) + solve(y+1, 1); } else if(mask == 7) { val = solve(y+1, 0); } else if(mask == 1 ) { val = solve(y+1, 6) + solve(y+1, 0); } else if(mask == 6) { val = solve(y+1, 1); } else if(mask == 4) { val = solve(y+1, 0) + solve(y+1, 3); } else if(mask == 3) { val = solve(y+1, 4); } arr[y][mask] = val; return val; } int main() { while(1) { memset(arr, -1, sizeof(arr)); scanf("%d", &n); if(n == -1) break; tot = solve(1, 0); printf("%d\n", tot); } return 0; }
15.474359
60
0.444905
adelnobel
2754756f8bf2f8290f42b63f91c2f5a47a8fc2e8
1,250
cpp
C++
Leetcode/Day040/last_lex_substr.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day040/last_lex_substr.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day040/last_lex_substr.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
/* first solution (slow but simple) string_view:? The idea is always to store a pair of pointer-to-first-element and size of some existing data array or string. Such a view-handle class could be passed around cheaply by value and would offer cheap substringing operations (which can be implemented as simple pointer increments and size adjustments). */ class Solution { public: string lastSubstring(string_view s) { string_view ans=""; for(int i=0; i<s.length(); i++) { if(s.substr(i) > ans ) ans=s.substr(i); } return (string)ans; } }; // optimized solution class Solution { public: string lastSubstring(string s) { int n = s.length(); int i=0,j=i+1,k=0; while(j+k<n) { //keep checking if(s[i+k] == s[j+k]) k++; //discard the first string else if(s[i+k] < s[j+k]) { i=j; j++; k=0; } //discard the latter string else { j=j+k+1; k=0; } } return s.substr(i); } };
21.551724
111
0.4784
SujalAhrodia
275a0511389b782b772b9814035ef0f653abad82
861
cpp
C++
Game/Scorpio/src/PhysicsSimulation/PS_EulerIntegrator.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Scorpio/src/PhysicsSimulation/PS_EulerIntegrator.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Scorpio/src/PhysicsSimulation/PS_EulerIntegrator.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include "PS_EulerIntegrator.h" PS_EulerIntegrator::PS_EulerIntegrator(void) { } PS_EulerIntegrator::~PS_EulerIntegrator() { } void PS_EulerIntegrator::prepare(size_t count, const PS_Mass* masses, const PS_Motion* motions) { mForces.resize(count, PS_Force::ZERO); } void PS_EulerIntegrator::update(PS_Scalar dt, const PS_ForceFields& forceFields, size_t count, const PS_Mass* masses, PS_Motion* motions) { PS_Force* forces = &mForces.front(); applyForces(forceFields, count, masses, motions, forces); for (size_t i = 0; i < count; ++i) { motions[i].velocity += (forces[i].internal + forces[i].external) * (masses[i].invertMass * dt); motions[i].position += motions[i].velocity * dt; } }
26.90625
103
0.59698
hackerlank
275e38506dee3dc090ef320fba3ace26c8219c4d
428
cpp
C++
practice/231-power-of-two/LeetCode_231_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
practice/231-power-of-two/LeetCode_231_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
practice/231-power-of-two/LeetCode_231_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
/** 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 示例 1: 输入: 1 输出: true 解释: 20 = 1 示例 2: 输入: 16 输出: true 解释: 24 = 16 示例 3: 输入: 218 输出: false 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/power-of-two 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 题解见我的博客 https://www.todayios.com/bit-operation/ * */ class Solution { public: bool isPowerOfTwo(int n) { if (n > 0 && (n & (n - 1)) == 0) return true; return false; } };
12.969697
56
0.61215
manajay
2768b58d8fb23940622e0aded98666695794580e
313
cpp
C++
source/entrypoint.cpp
KaixoCode/Collecto
2d71294c85a906b2c2099a10116389c90ff1beab
[ "MIT" ]
null
null
null
source/entrypoint.cpp
KaixoCode/Collecto
2d71294c85a906b2c2099a10116389c90ff1beab
[ "MIT" ]
null
null
null
source/entrypoint.cpp
KaixoCode/Collecto
2d71294c85a906b2c2099a10116389c90ff1beab
[ "MIT" ]
null
null
null
#include "Controller.hpp" // -------------------------------------------------------------------------- \\ // --------------------------- Entry Point ---------------------------------- \\ // -------------------------------------------------------------------------- \\ void main() { Controller _c; _c.Run(); }
28.454545
80
0.175719
KaixoCode
2769a1b7463a7e8a326925731c3696e0068df4cc
4,977
cpp
C++
ChronicleLogger/src/main/com/sowrov/util/logsystem/format/Html.cpp
sowrov/ChronicleLogger
50678be7e2987211ab976d105fcd8549e5b8744b
[ "Apache-2.0" ]
1
2020-03-05T10:36:48.000Z
2020-03-05T10:36:48.000Z
ChronicleLogger/src/main/com/sowrov/util/logsystem/format/Html.cpp
sowrov/ChronicleLogger
50678be7e2987211ab976d105fcd8549e5b8744b
[ "Apache-2.0" ]
null
null
null
ChronicleLogger/src/main/com/sowrov/util/logsystem/format/Html.cpp
sowrov/ChronicleLogger
50678be7e2987211ab976d105fcd8549e5b8744b
[ "Apache-2.0" ]
null
null
null
#include "Html.h" namespace com { namespace sowrov { namespace util { namespace logsystem { namespace format { std::string Html::getIntroFormat() { std::string intro = "<html><head><title>"; intro += Calendar::getCalendar ().getFormattedDate ("D d F Y H:i:s"); intro += "</title><style type=\"text/css\">\ <!--\ table, td\ {\ border-color: #000;\ }\ \ table\ {\ margin:auto;\ table-layout: fixed;\ border-width: 1px;\ border-spacing: 0;\ border-collapse: collapse;\ width: 90%;\ }\ \ td\ {\ margin: 0;\ padding: 4px;\ border-width: 1px 1px 0 0;\ }\ a:link, a:visited, a:hover {\ color:#FF3333;\ }\ \ #headRow {\ background-color:#000033;\ color:#FFFFCC;\ font-size:large;\ }\ \ .fatalError{\ background-color:#660000;\ color:#009900;\ word-wrap:break-word;\ }\ \ .error{\ background-color:#003366;\ color:#9999CC;\ word-wrap:break-word;\ }\ \ .warning{\ background-color:#663366;\ color:#FFCCCC;\ word-wrap:break-word;\ }\ \ .info{\ background-color:#FFFFCC;\ color:#000000;\ word-wrap:break-word;\ }\ \ .debug{\ background-color:#CCFFCC;\ color:#000000;\ word-wrap:break-word;\ }\ \ .endRow {\ background-color:#CCCCFF;\ }\ \ .timestamp{\ font-size: 0.7em;\ text-align:right;\ font-style:normal;\ }\ -->\ </style>\ \ <script type=\"text/javascript\">\ \ function OnOffSwitch(className){\ var allClassName = ['fatalError', 'error', 'warning', 'info', 'debug'];\ for (var it=0; it<allClassName.length; it++) {\ if (allClassName[it]==className || className=='') {\ OnOff(allClassName[it], true);\ }\ else {\ OnOff(allClassName[it], false);\ }\ }\ }\ \ function OnOff (className, boolVal) {\ var rows = document.getElementsByClassName(className);\ for(var i=0; i<rows.length; i++){\ if (boolVal == true) {\ rows[i].style.display = '';\ }\ else {\ rows[i].style.display = 'none';\ }\ }\ }\ </script></head><body><center><h1>Chronicle Logger</h1><sub>Compile time: "; intro += __DATE__; intro += ", "; intro += __TIME__; intro += "</sub></center>"; intro += "<div style='margin:auto; width: 90%'>\ <a href='javascript:void(0)' onclick='OnOffSwitch(\"\")'>Show All</a>|\ <a href='javascript:void(0)' onclick='OnOffSwitch(\"fatalError\")'>Show Fatal Only</a>|\ <a href='javascript:void(0)' onclick='OnOffSwitch(\"error\")'>Show Error Only</a>|\ <a href='javascript:void(0)' onclick='OnOffSwitch(\"warning\")'>Show Warning Only</a>|\ <a href='javascript:void(0)' onclick='OnOffSwitch(\"info\")'>Show Information Only</a>|\ <a href='javascript:void(0)' onclick='OnOffSwitch(\"debug\")'>Show Debug Only</a>\ </div>\ <table border='3'; cellpadding='5px'>\ <tr id='headRow'>\ <th width='50%'>Filepath</th>\ <th width='30%' >Function():LineNo</th>\ <th width='20%' >Timestamp</th>\ </tr>"; return intro; } std::string Html::getFinalFormat() { Calendar::getCalendar ().updateCalender (); std::string text ="<tr class='endRow'>\ <td colspan='3'>Application Terminated at: "; text += Calendar::getCalendar ().getFormattedDate ("d F Y H:i:s"); text += "</td> </tr> </table> </body> </html>"; return text; } std::string Html::getFormat(std::string className, std::string message, int lineNo, std::string functionName, std::string fileName) { char lineStr [10]; sprintf(lineStr, "%d", lineNo); std::string text = "<tr class='"+className+"'> \ <td width='50%' > <a href='"+fileName+"'>"+fileName+"</a></td>\ <td width='30%'>"+functionName+"(): "+lineStr+"</td>\ <td width='20%' class='timestamp'>"+ Calendar::getCalendar ().getFormattedDate ("d F Y H:i:s")+ "</td>\ </tr>\ <tr class='"+className+"'>\ <td colspan='3' width='100%'>"+message+"</td>\ </tr>"; return text; } std::string Html::getFatalFormat(std::string str, int lineNo, std::string functionName, std::string fileName ) { Calendar::getCalendar ().updateCalender (); return this->getFormat ("fatalError", str, lineNo, functionName, fileName); } std::string Html::getCriticalFormat(std::string str, int lineNo, std::string functionName, std::string fileName ) { Calendar::getCalendar ().updateCalender (); return this->getFormat ("error", str, lineNo, functionName, fileName);; } std::string Html::getWarningFormat(std::string str, int lineNo, std::string functionName, std::string fileName ) { Calendar::getCalendar ().updateCalender (); return this->getFormat ("warning", str, lineNo, functionName, fileName); } std::string Html::getInfoFormat(std::string str, int lineNo, std::string functionName, std::string fileName ) { Calendar::getCalendar ().updateCalender (); return this->getFormat ("info", str, lineNo, functionName, fileName); } std::string Html::getDebugFormat(std::string str, int lineNo, std::string functionName, std::string fileName ) { Calendar::getCalendar ().updateCalender (); return this->getFormat ("debug", str, lineNo, functionName, fileName); } } } } } }
26.194737
134
0.63693
sowrov
276bdc8e3a736de42366e4038a7ba0bd733e1a38
1,942
hpp
C++
include/openpose/utilities/profiler.hpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
717
2018-10-31T16:52:42.000Z
2022-03-31T16:13:47.000Z
include/openpose/utilities/profiler.hpp
Mainvooid/openpose
e4a021228b5949150c9446e31ec9f36f0f50a21c
[ "DOC", "MIT-CMU" ]
48
2018-11-08T12:16:43.000Z
2020-08-10T00:24:50.000Z
include/openpose/utilities/profiler.hpp
Mainvooid/openpose
e4a021228b5949150c9446e31ec9f36f0f50a21c
[ "DOC", "MIT-CMU" ]
180
2018-10-31T18:41:33.000Z
2022-03-27T23:49:06.000Z
#ifndef OPENPOSE_UTILITIES_PROFILER_HPP #define OPENPOSE_UTILITIES_PROFILER_HPP #include <string> #include <openpose/core/macros.hpp> // Enable PROFILER_ENABLED on Makefile.config in order to use this function. Otherwise nothing will be outputted. // How to use - example: // For GPU - It can only be applied in the main.cpp file: // Profiler::profileGpuMemory(__LINE__, __FUNCTION__, __FILE__); // For time: // // ... inside continuous loop ... // const auto profilerKey = Profiler::timerInit(__LINE__, __FUNCTION__, __FILE__); // // functions to do... // Profiler::timerEnd(profilerKey); // Profiler::printAveragedTimeMsOnIterationX(profilerKey, __LINE__, __FUNCTION__, __FILE__, NUMBER_ITERATIONS); namespace op { class OP_API Profiler { public: static unsigned long long DEFAULT_X; // Non-thread safe, it must be performed at the beginning of the code before any parallelization occurs static void setDefaultX(const unsigned long long defaultX); static const std::string timerInit(const int line, const std::string& function, const std::string& file); static void timerEnd(const std::string& key); static void printAveragedTimeMsOnIterationX(const std::string& key, const int line, const std::string& function, const std::string& file, const unsigned long long x = DEFAULT_X); static void printAveragedTimeMsEveryXIterations(const std::string& key, const int line, const std::string& function, const std::string& file, const unsigned long long x = DEFAULT_X); static void profileGpuMemory(const int line, const std::string& function, const std::string& file); }; } #endif // OPENPOSE_UTILITIES_PROFILER_HPP
42.217391
115
0.647786
meiwanlanjun
276d637d707c22088359eb3ceecf2e402d9aca07
794
cpp
C++
Source/WarpX_py.cpp
ablelly/WarpX
fd031b1cfcb1827a5cd6a4d905fe0ded76693411
[ "BSD-3-Clause-LBNL" ]
1
2019-11-14T19:27:03.000Z
2019-11-14T19:27:03.000Z
Source/WarpX_py.cpp
ablelly/WarpX
fd031b1cfcb1827a5cd6a4d905fe0ded76693411
[ "BSD-3-Clause-LBNL" ]
40
2019-08-30T15:49:07.000Z
2022-03-09T00:57:09.000Z
Source/WarpX_py.cpp
ablelly/WarpX
fd031b1cfcb1827a5cd6a4d905fe0ded76693411
[ "BSD-3-Clause-LBNL" ]
4
2020-04-20T22:29:45.000Z
2020-05-26T21:00:52.000Z
#include <WarpX_py.H> extern "C" { WARPX_CALLBACK_PY_FUNC_0 warpx_py_afterinit = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_beforeEsolve = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_afterEsolve = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_beforedeposition = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_afterdeposition = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_particlescraper = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_particleloader = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_beforestep = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_afterstep = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_afterrestart = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_particleinjection = nullptr; WARPX_CALLBACK_PY_FUNC_0 warpx_py_appliedfields = nullptr; }
39.7
66
0.826196
ablelly
276d7a0b38fb6c95d07b4ece92492bda8e71d159
1,157
cpp
C++
verify/verify-yosupo-ds/yosupo-point-add-rectangle-sum-abstruct-range-tree.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
69
2020-11-06T05:21:42.000Z
2022-03-29T03:38:35.000Z
verify/verify-yosupo-ds/yosupo-point-add-rectangle-sum-abstruct-range-tree.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
21
2020-07-25T04:47:12.000Z
2022-02-01T14:39:29.000Z
verify/verify-yosupo-ds/yosupo-point-add-rectangle-sum-abstruct-range-tree.test.cpp
NachiaVivias/library
73091ddbb00bc59328509c8f6e662fea2b772994
[ "CC0-1.0" ]
9
2020-11-06T11:55:10.000Z
2022-03-20T04:45:31.000Z
#define PROBLEM "https://judge.yosupo.jp/problem/point_add_rectangle_sum" #include "../../template/template.hpp" #include "../../data-structure-2d/abstract-range-tree.hpp" #include "../../data-structure/binary-indexed-tree.hpp" #include "../../misc/compress.hpp" #include "../../misc/fastio.hpp" using namespace Nyaan; void Nyaan::solve() { using BIT = BinaryIndexedTree<ll>; auto nw = [](int n) { return new BIT(n); }; auto add = [](BIT& bit, int i, ll a) { bit.add(i, a); }; auto sum = [](BIT& bit, int i, int j) { return bit.sum(j - 1) - bit.sum(i - 1); }; auto mrg = [](ll a, ll b) { return a + b; }; RangeTree<BIT, int, ll> rtree(nw, add, sum, mrg, 0); int N, Q; rd(N, Q); vector<int> X(N), Y(N), W(N), c(Q), s(Q), t(Q), u(Q), v(Q); rep(i, N) { rd(X[i], Y[i], W[i]); rtree.add_point(X[i], Y[i]); } rep(i, Q) { rd(c[i], s[i], t[i], u[i]); if (c[i]) rd(v[i]); else rtree.add_point(s[i], t[i]); } rtree.build(); rep(i, N) { rtree.add(X[i], Y[i], W[i]); } rep(i, Q) { if (c[i]) { out(rtree.sum(s[i], t[i], u[i], v[i])); } else rtree.add(s[i], t[i], u[i]); } }
26.906977
73
0.522904
NachiaVivias
2776c904a2808e0d0569acc89a474c47ad01434d
1,507
hpp
C++
src/GameObjects/projectile.hpp
toni-lyttinen/spacedude3
d06a4f80f29a4a88056250d66e63b59e8523c434
[ "MIT" ]
2
2020-01-21T15:05:43.000Z
2020-01-25T17:00:55.000Z
src/GameObjects/projectile.hpp
tlmoni/spacedude3
d06a4f80f29a4a88056250d66e63b59e8523c434
[ "MIT" ]
null
null
null
src/GameObjects/projectile.hpp
tlmoni/spacedude3
d06a4f80f29a4a88056250d66e63b59e8523c434
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include "gameobject.hpp" struct Bullet { std::string texture; RectHitbox hitbox; int type; float max_speed; float acceleration; float damage; PhysicsVector origin; }; const static Bullet plasma = {"src/Textures/bullet.png", RectHitbox(20.f, 20.f), BULLET, 30.f, 0.4f, 15, PhysicsVector(10, 10)}; const static Bullet rock = {"src/Textures/rock.png", RectHitbox(17.f, 17.f), BULLET, 30.f, 1.5f, 10, PhysicsVector(9, 9)}; const static Bullet pellet = {"src/Textures/pellet.png", RectHitbox(20.f, 20.f), BULLET, 30.f, 1.7f, 80, PhysicsVector(10, 10)}; const static Bullet heal = {"src/Textures/heal.png", RectHitbox(20.f, 20.f), BULLET, 0.0f, 0.01f, 0, PhysicsVector(10, 10)}; const static Bullet skull = {"src/Textures/skull.png", RectHitbox(33.f, 33.f), BULLET, 15.f, 0.1f, 50, PhysicsVector(17, 17)}; /* Abstract parent class for all projectile */ class Projectile : public GameObject { public: /* Constructor */ Projectile(PhysicsVector pos, int owner, Bullet bullet = plasma) : GameObject(pos, bullet.texture, bullet.hitbox, bullet.type, bullet.max_speed, bullet.acceleration, bullet.damage), owner_(owner) { SetOrigin(bullet.origin.x, bullet.origin.y); } /* Destructor */ ~Projectile() = default; /* Check if player is colliding with items and change movement according to that */ bool CheckCollisions(std::vector<GameObject*> objects); int GetOwner() { return owner_; } private: int owner_; };
36.756098
128
0.693431
toni-lyttinen
27781a44849e2750b62069a2e104de4eb6ac2729
1,993
hpp
C++
src/constants.hpp
kewin1983/transient-pipeline-flow
4ffe0b61d3d40d9bcb82a3743b2c2e403521835d
[ "MIT" ]
1
2021-03-26T03:30:07.000Z
2021-03-26T03:30:07.000Z
src/constants.hpp
kewin1983/transient-pipeline-flow
4ffe0b61d3d40d9bcb82a3743b2c2e403521835d
[ "MIT" ]
null
null
null
src/constants.hpp
kewin1983/transient-pipeline-flow
4ffe0b61d3d40d9bcb82a3743b2c2e403521835d
[ "MIT" ]
null
null
null
#pragma once #include <cmath> /*! * This namespace contains a lot of useful constants. */ namespace constants { //! The ratio of a circle's circumference to its diameter. static const double pi = 4.0*std::atan(1.0); //! The zero point of the Kelvin scale [degrees C]. static const double kelvin = 273.15; //! Standard atmoshperic pressure [Pa]. static const double standardAtmosphere = 101325; //! Convert Kelvin to Rankine [Ra/K]. static const double kelvinToRankine = 9.0/5.0; //! Standard temperature [K]. //! From Gassco.no (https://www.gassco.no/en/our-activities/what-is-natural-gas/glossary/). static const double standardTemperature = kelvin + 15; //! Standard pressure [Pa]. //! From Gassco.no (https://www.gassco.no/en/our-activities/what-is-natural-gas/glossary/). static const double standardPressure = 101325; //! Universal gas constant [J/(K mol)]. static const double gasConstant = 8.3144598; // [J/mol K] == [m3 Pa /mol K] //! Universal gas constant [BTU/(R lbmol)] static const double gasConstantBTU = 1.98588; //! Convert Pascal to psf (pound force per square foot) [psf/Pa]. static const double pascalToPoundForcePerSquareFoot = 0.3048*0.3048/4.4482216152605; // 4.448.. is lbf to Newton, 0.3048 is foot to meter //! Convert foot pound-force to Joule static const double footPoundForce = 1.355817948; // joule //! Convert slugs to kilogram static const double slug = 14.5939; // kg //! Convert degrees Rankine to degrees Kelvin static const double rankine = 5.0/9.0; // Kelvin //! Convert ft.lbf/slug.R to J/(kg K) (the unit of specific heat capacity) static const double footPoundForcePerSlugRankine = footPoundForce/(slug*rankine); // J/(kg K) //! The molar mass of air [g/mol]. //! Used for calculating specific gravity. static const double molarMassOfAir = 28.967; // [g/mol] reference for calculating specific gravity }
38.326923
141
0.678374
kewin1983
277b8d26262480bf35b11b120d90411d563f7df1
539
hh
C++
tests/opbox/unit/support/default_config_string.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
tests/opbox/unit/support/default_config_string.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
tests/opbox/unit/support/default_config_string.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #ifndef FAODEL_DEFAULT_CONFIG_STRING_HH #define FAODEL_DEFAULT_CONFIG_STRING_HH std::string default_config_string = R"EOF( )EOF"; std::string multitest_config_string = R"EOF( # for finishSoft lunasa.lazy_memory_manager malloc lunasa.eager_memory_manager malloc )EOF"; #endif //FAODEL_DEFAULT_SERIAL_SETTINGS_HH
20.730769
76
0.784787
faodel
277e30b013a2c1c3d376d600dca003632d1672b6
2,990
cpp
C++
src/StressTool/StressTool.cpp
Stormancer/sample-server-app
4a91e8e728ead7149b34444ea43217ce47f92529
[ "MIT" ]
1
2021-07-16T15:00:39.000Z
2021-07-16T15:00:39.000Z
src/StressTool/StressTool.cpp
Stormancer/sample-server-app
4a91e8e728ead7149b34444ea43217ce47f92529
[ "MIT" ]
null
null
null
src/StressTool/StressTool.cpp
Stormancer/sample-server-app
4a91e8e728ead7149b34444ea43217ce47f92529
[ "MIT" ]
null
null
null
// StressTool.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit. // #define NOMINMAX #include <iostream> #include "Worker.h" #include "Timer.h" struct Stats { double avg; double max; double min; double successRate; }; Stats stats(std::vector<StressTool::Result> results) { double acc = 0; double count = 0; double min = std::numeric_limits<double>::max(); double max = std::numeric_limits<double>::min(); for (auto v : results) { if (v.success) { acc += v.duration; count++; if (min > v.duration) { min = v.duration; } if (max < v.duration) { max = v.duration; } } } Stats stats; stats.avg = acc / count; stats.max = max; stats.min = min; stats.successRate = count / results.size(); return stats; } int main() { for (int l=0; l < 1000; l++) { int concurrentWorkers = 10; std::vector<pplx::task<StressTool::Result>> tasks; Timer timer; timer.start(); for (int i = 0; i < concurrentWorkers; i++) { auto result = pplx::create_task([i]() { StressTool::ConnectionWorker worker; return worker.run(i); }); tasks.push_back(result); } timer.stop(); std::cout << "startup time : " << timer.getElapsedTimeInMilliSec() << "ms\n"; timer.start(); auto results = pplx::when_all(tasks.begin(), tasks.end()).get(); timer.stop(); std::cout << "execution time : " << timer.getElapsedTimeInMilliSec() << "ms\n"; auto result = stats(results); std::cout << "success rate : " << result.successRate * 100 << "%\n"; std::cout << "avg : " << result.avg << "ms\n"; std::cout << "min : " << result.min << "ms\n"; std::cout << "max : " << result.max << "ms\n"; } std::string _; std::getline(std::cin, _); } // Exécuter le programme : Ctrl+F5 ou menu Déboguer > Exécuter sans débogage // Déboguer le programme : F5 ou menu Déboguer > Démarrer le débogage // Astuces pour bien démarrer : // 1. Utilisez la fenêtre Explorateur de solutions pour ajouter des fichiers et les gérer. // 2. Utilisez la fenêtre Team Explorer pour vous connecter au contrôle de code source. // 3. Utilisez la fenêtre Sortie pour voir la sortie de la génération et d'autres messages. // 4. Utilisez la fenêtre Liste d'erreurs pour voir les erreurs. // 5. Accédez à Projet > Ajouter un nouvel élément pour créer des fichiers de code, ou à Projet > Ajouter un élément existant pour ajouter des fichiers de code existants au projet. // 6. Pour rouvrir ce projet plus tard, accédez à Fichier > Ouvrir > Projet et sélectionnez le fichier .sln.
30.510204
182
0.566221
Stormancer
959ba0553179756cb6956e7fad7691b3c61e99cc
2,127
hpp
C++
stok_contracts/contracts/eosio.stok/include/eosio.stok/eosio.stok.hpp
eoseoul/eosio.stok
cf7bab0b8e171791e3d43fb4870bdfe7ab89fa5b
[ "MIT" ]
null
null
null
stok_contracts/contracts/eosio.stok/include/eosio.stok/eosio.stok.hpp
eoseoul/eosio.stok
cf7bab0b8e171791e3d43fb4870bdfe7ab89fa5b
[ "MIT" ]
null
null
null
stok_contracts/contracts/eosio.stok/include/eosio.stok/eosio.stok.hpp
eoseoul/eosio.stok
cf7bab0b8e171791e3d43fb4870bdfe7ab89fa5b
[ "MIT" ]
null
null
null
/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosio/asset.hpp> #include <eosio/eosio.hpp> #include <string> namespace eosiosystem { class system_contract; } namespace eosio { using std::string; class [[eosio::contract("eosio.stok")]] token : public contract { public: using contract::contract; [[eosio::action]] void create( name issuer, asset maximum_supply_st, asset maximum_supply_ut); [[eosio::action]] void issue( name issuer, asset quant_st, asset quant_ut, string memo ); [[eosio::action]] void transfer( name issuer, int64_t creditor_id, asset quant_st, asset quant_ut, string memo ); [[eosio::action]] void retire( name issuer, int64_t creditor_id, asset quant_st, asset quant_ut, string memo ); [[eosio::action]] void clear( name issuer, int64_t creditor_id, asset quant_st, asset quant_ut, string repayment, string bond_yield, string expr_yield, string memo); private: struct [[eosio::table]] account { int64_t creditor_id; asset balance_st; asset balance_ut; string repayment; string bond_yield; string expr_yield; uint64_t primary_key()const { return creditor_id; } }; struct [[eosio::table]] currency_stats { asset supply_st; asset supply_ut; asset max_supply_st; asset max_supply_ut; name issuer; uint64_t primary_key()const { return issuer.value; } }; typedef eosio::multi_index< "accounts"_n, account > accounts; typedef eosio::multi_index< "stat"_n, currency_stats > stats; void add_balance( name issuer, int64_t creditor, asset quant_st, asset quant_ut ); }; } /// namespace eosio
27.623377
105
0.550071
eoseoul
959d81edd183bb9a596cbea777ff1aa0d4e7b3bc
5,875
cpp
C++
test/test-window-function.cpp
rimio/specgram
4b9517a148bcd6f47cc2f20a83355093811cc04b
[ "MIT" ]
4
2020-12-29T21:52:57.000Z
2022-02-07T09:44:37.000Z
test/test-window-function.cpp
rimio/specgram
4b9517a148bcd6f47cc2f20a83355093811cc04b
[ "MIT" ]
24
2020-12-29T20:23:09.000Z
2021-11-01T14:01:20.000Z
test/test-window-function.cpp
rimio/specgram
4b9517a148bcd6f47cc2f20a83355093811cc04b
[ "MIT" ]
1
2021-09-22T12:39:59.000Z
2021-09-22T12:39:59.000Z
/* * Copyright (c) 2020-2021 Vasile Vilvoiu <vasi@vilvoiu.ro> * * specgram is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #include "test.hpp" #include "../src/window-function.hpp" #include <list> static std::vector<WindowFunctionType> ALL_WF_TYPES { WindowFunctionType::kBlackman, WindowFunctionType::kHamming, WindowFunctionType::kHann, WindowFunctionType::kNuttall, WindowFunctionType::kNone }; static constexpr double EPSILON = 1e-7; void run_tests(const std::list<std::vector<double>>& tests, WindowFunctionType type) { for (const auto& test : tests) { /* create window */ auto win = WindowFunction::Build(type, test.size()); /* create identity input */ ComplexWindow input(test.size()); for (auto& i : input) { i = 1.0; } /* apply */ auto out = win->Apply(input); EXPECT_EQ(out.size(), test.size()); /* check */ for (size_t i = 0; i < test.size(); i++) { EXPECT_LE(std::abs(out[i] - test[i]), EPSILON); } } } TEST(TestWindowFunction, FactoryWrongType) { EXPECT_THROW_MATCH(auto ret = WindowFunction::Build((WindowFunctionType)999, 10), std::runtime_error, "unknown window function"); } TEST(TestWindowFunction, TypeBlackman) { /* np.blackman */ std::list<std::vector<double>> tests; tests.push_back( { 1.0 }); tests.push_back( { -1.38777878e-17, -1.38777878e-17 }); tests.push_back( { -1.38777878e-17, 1.00000000e+00, -1.38777878e-17 }); tests.push_back( { -1.38777878e-17, 3.40000000e-01, 1.00000000e+00, 3.40000000e-01, -1.38777878e-17 }); tests.push_back({ -1.38777878e-17, 5.08696327e-02, 2.58000502e-01, 6.30000000e-01, 9.51129866e-01, 9.51129866e-01, 6.30000000e-01, 2.58000502e-01, 5.08696327e-02, -1.38777878e-17 }); tests.push_back({ -1.38777878e-17, 6.31911916e-03, 2.69872981e-02, 6.64466094e-02, 1.30000000e-01, 2.21308445e-01, 3.40000000e-01, 4.80127490e-01, 6.30000000e-01, 7.73553391e-01, 8.93012702e-01, 9.72244945e-01, 1.00000000e+00, 9.72244945e-01, 8.93012702e-01, 7.73553391e-01, 6.30000000e-01, 4.80127490e-01, 3.40000000e-01, 2.21308445e-01, 1.30000000e-01, 6.64466094e-02, 2.69872981e-02, 6.31911916e-03, -1.38777878e-17 }); run_tests(tests, WindowFunctionType::kBlackman); } TEST(TestWindowFunction, TypeHamming) { /* np.hamming */ std::list<std::vector<double>> tests; tests.push_back( { 1.0 }); tests.push_back( { 0.08, 0.08 }); tests.push_back( { 0.08, 1. , 0.08 }); tests.push_back( { 0.08, 0.54, 1. , 0.54, 0.08 }); tests.push_back( { 0.08 , 0.18761956, 0.46012184, 0.77 , 0.97225861, 0.97225861, 0.77 , 0.46012184, 0.18761956, 0.08 }); tests.push_back( { 0.08 , 0.09567412, 0.14162831, 0.21473088, 0.31 , 0.42094324, 0.54 , 0.65905676, 0.77 , 0.86526912, 0.93837169, 0.98432588, 1. , 0.98432588, 0.93837169, 0.86526912, 0.77 , 0.65905676, 0.54 , 0.42094324, 0.31 , 0.21473088, 0.14162831, 0.09567412, 0.08 }); run_tests(tests, WindowFunctionType::kHamming); } TEST(TestWindowFunction, TypeHann) { /* np.hanning */ std::list<std::vector<double>> tests; tests.push_back( { 1.0 }); tests.push_back( { 0., 0. }); tests.push_back( { 0., 1., 0. }); tests.push_back( { 0. , 0.5, 1. , 0.5, 0. }); tests.push_back( { 0. , 0.11697778, 0.41317591, 0.75 , 0.96984631, 0.96984631, 0.75 , 0.41317591, 0.11697778, 0. }); tests.push_back( { 0. , 0.01703709, 0.0669873 , 0.14644661, 0.25 , 0.37059048, 0.5 , 0.62940952, 0.75 , 0.85355339, 0.9330127 , 0.98296291, 1. , 0.98296291, 0.9330127 , 0.85355339, 0.75 , 0.62940952, 0.5 , 0.37059048, 0.25 , 0.14644661, 0.0669873 , 0.01703709, 0. }); run_tests(tests, WindowFunctionType::kHann); } TEST(TestWindowFunction, TypeNuttall) { /* scipy.signal.nuttall */ /* NOTE: Nuttall4c from https://holometer.fnal.gov/GH_FFT.pdf */ std::list<std::vector<double>> tests; tests.push_back( { 1. }); tests.push_back( { 0.0003628, 0.0003628 }); tests.push_back( { 3.628e-04, 1.000e+00, 3.628e-04 }); tests.push_back( { 3.628000e-04, 2.269824e-01, 1.000000e+00, 2.269824e-01, 3.628000e-04 }); tests.push_back( { 3.62800000e-04, 1.78909987e-02, 1.55596126e-01, 5.29229800e-01, 9.33220225e-01, 9.33220225e-01, 5.29229800e-01, 1.55596126e-01, 1.78909987e-02, 3.62800000e-04 }); tests.push_back( { 3.62800000e-04, 1.84696229e-03, 8.24150804e-03, 2.52055665e-02, 6.13345000e-02, 1.26199203e-01, 2.26982400e-01, 3.64367322e-01, 5.29229800e-01, 7.01958233e-01, 8.55521792e-01, 9.61914112e-01, 1.00000000e+00, 9.61914112e-01, 8.55521792e-01, 7.01958233e-01, 5.29229800e-01, 3.64367322e-01, 2.26982400e-01, 1.26199203e-01, 6.13345000e-02, 2.52055665e-02, 8.24150804e-03, 1.84696229e-03, 3.62800000e-04 }); run_tests(tests, WindowFunctionType::kNuttall); } TEST(TestWindowFunction, TypeNone) { EXPECT_EQ(WindowFunction::Build(WindowFunctionType::kNone, 1), nullptr); EXPECT_EQ(WindowFunction::Build(WindowFunctionType::kNone, 10), nullptr); }
43.843284
90
0.573447
rimio
95a689c4b863d71f1f66bdafa9d52396ad7db715
1,150
cpp
C++
t/60-merged-option.cpp
ih8celery/liboptparse
60d323718eae934be2da42a5dbf6a64cb2353966
[ "MIT" ]
3
2018-06-20T14:57:19.000Z
2018-09-27T11:41:01.000Z
t/60-merged-option.cpp
ih8celery/libcmdparse
60d323718eae934be2da42a5dbf6a64cb2353966
[ "MIT" ]
null
null
null
t/60-merged-option.cpp
ih8celery/libcmdparse
60d323718eae934be2da42a5dbf6a64cb2353966
[ "MIT" ]
null
null
null
/** * \file 60-merged-option.cpp * \author Adam Marshall (ih8celery) * \brief test the use of merged options */ #define WANT_TEST_EXTRAS #include <tap++.h> #include "cmdparse.h" using namespace TAP; using namespace cli; int main() { Command cmd; Info info; cmd.configure("merged_opt"); cmd.option("d|-due?", "due"); cmd.option("a", "awe"); cmd.option("--afd", "AFD"); cmd.option("f*", "file"); plan(6); char ** argv = new char*[6]; argv[0] = (char *)"--afd"; argv[1] = (char *)"f"; argv[2] = (char *)":d"; argv[3] = (char *)"-due"; argv[4] = (char *)"--afd"; argv[5] = (char *)"--afd"; info = cmd.parse(argv, 2); ok(info.has("file"), "found file argument"); ok(info.count("file") == 2, "file argument twice"); ok(info.count("awe") == 1, "found awe argument once"); ok(info.count("due") == 1, "found due argument once"); argv += 2; TRY_NOT_OK(cmd.parse(argv, 2), "merged option may not be repeated excessively"); argv += 2; info = cmd.parse(argv, 2); ok(info.count("AFD"), "option named AFD found once"); argv -= 4; delete [] argv; done_testing(); return exit_status(); }
19.491525
82
0.586957
ih8celery
95a8b06db8ec20151c319e31f3996d5a29473036
33,263
cpp
C++
3dc/avp/savegame.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/savegame.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
3dc/avp/savegame.cpp
Melanikus/AvP
9d61eb974a23538e32bf2ef1b738643a018935a0
[ "BSD-3-Clause" ]
null
null
null
#include "3dc.h" #include "inline.h" #include "module.h" #include "strategy_def.h" #include "gamedef.h" #include "bh_types.h" #include "compiled_shapes.h" #include "dynblock.h" #include "bh_alien.h" #include "pvisible.h" #include "bh_predator.h" #include "bh_xeno.h" #include "bh_paq.h" #include "bh_queen.h" #include "bh_marine.h" #include "bh_facehugger.h" #include "bh_debris.h" #include "bh_placed_hierarchy.h" #include "plat_shp.h" #include "psnd.h" #include "lighting.h" #include "pldnet.h" #include "bh_dummy.h" #include "bh_videoscreen.h" #include "bh_platform_lift.h" #include "bh_lift_door.h" #include "game_statistics.h" #include "user_profile.h" #include "savegame.h" #include "huffman.hpp" #include "fmvCutscenes.h" #define UseLocalAssert TRUE #include "ourasert.h" #include <assert.h> extern void NewOnScreenMessage(char *messagePtr); extern void GetFilenameForSaveSlot(int i, char *filenamePtr); void ScanSaveSlots(void); void RestartLevel(); extern void StartFMVAtFrame(int number, int frame); extern void GetFMVInformation(int *messageNumberPtr, int *frameNumberPtr); extern bool unlimitedSaves; static struct { char* BufferStart; char* BufferPos; int BufferSize; int BufferSpaceLeft; int BufferSpaceUsed; } SaveInfo = {0,0,0,0,0}; static struct { char* BufferStart; char* BufferPos; int BufferSize; int BufferSpaceLeft; } LoadInfo = {0,0,0,0}; int LoadGameRequest = SAVELOAD_REQUEST_NONE; //slot number of game to be loaded int SaveGameRequest = SAVELOAD_REQUEST_NONE; //slot number of game to be saved #define NUM_SAVES_FOR_EASY_MODE 8 #define NUM_SAVES_FOR_MEDIUM_MODE 4 #define NUM_SAVES_FOR_HARD_MODE 2 int NumberOfSavesLeft; static void SaveStrategies(); static void LoadStrategy(SAVE_BLOCK_STRATEGY_HEADER* header); static void SaveDeadStrategies(); static void LoadDeadStrategy(SAVE_BLOCK_HEADER* block); static void LoadMiscGlobalStuff(SAVE_BLOCK_HEADER* header); static void SaveMiscGlobalStuff(); /*---------------------------------------------** ** externs for all the load and save functions ** **---------------------------------------------*/ extern void LoadStrategy_LiftDoor(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_LiftDoor(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_ProxDoor(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_ProxDoor(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_SwitchDoor(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_SwitchDoor(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PlatformLift(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PlatformLift(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_BinarySwitch(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_BinarySwitch(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_LinkSwitch(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_LinkSwitch(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Generator(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Generator(STRATEGYBLOCK* sbPtr); extern void LoadHiveSettings(SAVE_BLOCK_HEADER* header); extern void SaveHiveSettings(); extern void LoadStrategy_InanimateObject(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_InanimateObject(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_LightFx(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_LightFx(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PlacedSound(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PlacedSound(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Message(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Message(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_MissionComplete(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_MissionComplete(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_TrackObject(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_TrackObject(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Fan(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Fan(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PlacedLight(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PlacedLight(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_VideoScreen(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_VideoScreen(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_DeathVolume(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_DeathVolume(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_ParticleGenerator(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_ParticleGenerator(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_SelfDestruct(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_SelfDestruct(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Alien(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Alien(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Corpse(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Corpse(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_FaceHugger(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_FaceHugger(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Marine(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Marine(STRATEGYBLOCK* sbPtr); extern void LoadMarineSquadState(SAVE_BLOCK_HEADER* header); extern void SaveMarineSquadState(); extern void LoadStrategy_PlacedHierarchy(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PlacedHierarchy(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Predator(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Predator(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Xenoborg(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Xenoborg(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Queen(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Queen(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Player(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Player(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Autogun(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Autogun(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_HierarchicalDebris(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_HierarchicalDebris(STRATEGYBLOCK* sbPtr); extern void Load_Decals(SAVE_BLOCK_HEADER* header); extern void Save_Decals(); extern void Load_Particles(SAVE_BLOCK_HEADER* header); extern void Save_Particles(); extern void Load_VolumetricExplosions(SAVE_BLOCK_HEADER* header); extern void Save_VolumetricExplosions(); extern void Load_PheromoneTrails(SAVE_BLOCK_HEADER* header); extern void Save_PheromoneTrails(); extern void Load_LightElements(SAVE_BLOCK_HEADER* header); extern void Save_LightElements(); extern void Load_MessageHistory(SAVE_BLOCK_HEADER* header); extern void Save_MessageHistory(); extern void LoadStrategy_Grenade(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Grenade(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_FlareGrenade(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_FlareGrenade(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_ProxGrenade(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_ProxGrenade(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Rocket(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Rocket(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PPPlasmaBolt(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PPPlasmaBolt(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PredatorEnergyBolt(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PredatorEnergyBolt(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PulseGrenade(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PulseGrenade(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_ClusterGrenade(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_ClusterGrenade(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Molotov(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Molotov(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_PredatorDisc(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_PredatorDisc(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_SpearBolt(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_SpearBolt(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Grapple(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Grapple(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_Debris(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Debris(STRATEGYBLOCK* sbPtr); extern void LoadLevelHeader(SAVE_BLOCK_HEADER* header); extern void SaveLevelHeader(); extern void Load_WeaponsCGlobals(SAVE_BLOCK_HEADER* header); extern void Save_WeaponsCGlobals(); extern void Load_SoundState_NoRef(SAVE_BLOCK_HEADER* header); extern void Save_SoundsWithNoReference(); extern void LoadStrategy_Frisbee(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_Frisbee(STRATEGYBLOCK* sbPtr); extern void LoadStrategy_FrisbeeEnergyBolt(SAVE_BLOCK_STRATEGY_HEADER* header); extern void SaveStrategy_FrisbeeEnergyBolt(STRATEGYBLOCK* sbPtr); extern int DebuggingCommandsActive; /*-----------------------------------------------------** ** end of externs for all the load and save functions ** **-----------------------------------------------------*/ extern void DisplaySavesLeft(); /* Functions for converting between ai modules and their indeces. They don't really belong here , but they are only used by loading/saving at the moment. */ struct aimodule * GetPointerFromAIModuleIndex(int index) { if (index>=0 && index<AIModuleArraySize) { return &AIModuleArray[index]; } else { return NULL; } } int GetIndexFromAIModulePointer(struct aimodule* module) { if(module) return module->m_index; else return -1; } void* GetPointerForSaveBlock(unsigned int size) { void* retPointer; //see if we need to enlarge the buffer to allow for this block if(size > SaveInfo.BufferSpaceLeft) { //need more space int spaceNeeded = SaveInfo.BufferSpaceUsed + size; //buffer incremented in lots of 100000 bytes (more or less) int newBufferSize = ((spaceNeeded /100000)+1)*100000; //allocate the memory SaveInfo.BufferStart = (char*) realloc(SaveInfo.BufferStart,newBufferSize); assert(SaveInfo.BufferStart); //correct the position etc. SaveInfo.BufferPos = SaveInfo.BufferStart + SaveInfo.BufferSpaceUsed; SaveInfo.BufferSpaceLeft += (newBufferSize - SaveInfo.BufferSize); SaveInfo.BufferSize = newBufferSize; } //get the pointer to the next part of the save buffer retPointer = (void*)SaveInfo.BufferPos; SaveInfo.BufferSpaceUsed += size; SaveInfo.BufferSpaceLeft -= size; SaveInfo.BufferPos += size; return retPointer; } static void InitSaveGame() { SaveInfo.BufferPos = SaveInfo.BufferStart; SaveInfo.BufferSpaceLeft = SaveInfo.BufferSize; SaveInfo.BufferSpaceUsed = 0; } static BOOL SaveGameAllowed() { PLAYER_STATUS *playerStatusPtr; //can't save in multiplayer (or skirmish) if(AvP.Network != I_No_Network) return FALSE; //check player's state if(!Player) return FALSE; if(!Player->ObStrategyBlock) return FALSE; if(!Player->ObStrategyBlock->SBdataptr) return FALSE; playerStatusPtr = (PLAYER_STATUS*)Player->ObStrategyBlock->SBdataptr; //player must be alive , and not face hugged if(!playerStatusPtr->IsAlive) return FALSE; if(playerStatusPtr->MyFaceHugger) return FALSE; //cheating? if(DebuggingCommandsActive || CheatMode_Active!=CHEATMODE_NONACTIVE) { NewOnScreenMessage(GetTextString(TEXTSTRING_SAVEGAME_NOTALLOWED)); return FALSE; } //now check the number of saves left //first some validation if (NumberOfSavesLeft < 0) NumberOfSavesLeft = 0; switch(AvP.Difficulty) { case I_Easy : if(NumberOfSavesLeft > NUM_SAVES_FOR_EASY_MODE) NumberOfSavesLeft = NUM_SAVES_FOR_EASY_MODE; break; case I_Medium : if(NumberOfSavesLeft > NUM_SAVES_FOR_MEDIUM_MODE) NumberOfSavesLeft = NUM_SAVES_FOR_MEDIUM_MODE; break; case I_Hard : case I_Impossible : if(NumberOfSavesLeft > NUM_SAVES_FOR_HARD_MODE) NumberOfSavesLeft = NUM_SAVES_FOR_HARD_MODE; break; } if (!unlimitedSaves) { if (!NumberOfSavesLeft) { NewOnScreenMessage(GetTextString(TEXTSTRING_SAVEGAME_NOSAVESLEFT)); return FALSE; } NumberOfSavesLeft--; } //saving is allowed then return TRUE; } void SaveGame() { char filename[MAX_PATH]; HANDLE file; DWORD bytes_written; int headerLength; HuffmanPackage *packagePtr; //make sure there is a save request if(SaveGameRequest == SAVELOAD_REQUEST_NONE) return; if(SaveGameRequest<0 || SaveGameRequest>=NUMBER_OF_SAVE_SLOTS) { SaveGameRequest = SAVELOAD_REQUEST_NONE; return; } //check that we are allowed to save at this point if(!SaveGameAllowed()) { //cancel request SaveGameRequest = SAVELOAD_REQUEST_NONE; return; } InitSaveGame(); SaveLevelHeader(); headerLength = SaveInfo.BufferSpaceUsed; SaveDeadStrategies(); SaveStrategies(); SaveHiveSettings(); SaveMarineSquadState(); SaveMiscGlobalStuff(); Save_SoundsWithNoReference(); //save particles etc. Save_Decals(); Save_Particles(); Save_VolumetricExplosions(); Save_PheromoneTrails(); Save_LightElements(); Save_MessageHistory(); Save_WeaponsCGlobals(); //get the filename GetFilenameForSaveSlot(SaveGameRequest,filename); //clear the save request SaveGameRequest = SAVELOAD_REQUEST_NONE; //write the file file = avp_CreateFile(filename,GENERIC_WRITE, 0, 0, CREATE_ALWAYS,FILE_FLAG_RANDOM_ACCESS, 0); if (file == INVALID_HANDLE_VALUE) { GLOBALASSERT("Error saving file"==0); return; } WriteFile(file,SaveInfo.BufferStart,headerLength,&bytes_written,0); // bjd - check cast ok packagePtr = HuffmanCompression(reinterpret_cast<unsigned char*>(SaveInfo.BufferStart+headerLength), SaveInfo.BufferSpaceUsed-headerLength); WriteFile(file, packagePtr, packagePtr->CompressedDataSize+sizeof(HuffmanPackage), &bytes_written, 0); CloseHandle(file); NewOnScreenMessage(GetTextString(TEXTSTRING_SAVEGAME_GAMESAVED)); DisplaySavesLeft(); } static void EndLoadGame() { if (LoadInfo.BufferStart) { DeallocateMem(LoadInfo.BufferStart); } LoadInfo.BufferStart = NULL; LoadInfo.BufferPos = NULL; LoadInfo.BufferSize = 0; LoadInfo.BufferSpaceLeft = 0; } extern SAVE_SLOT_HEADER SaveGameSlot[]; extern int AlienEpisodeToPlay; extern int MarineEpisodeToPlay; extern int PredatorEpisodeToPlay; BOOL ValidateLevelForLoadGameRequest(SAVE_SLOT_HEADER* save_slot) { //see if we will need to change level if(save_slot->Species != AvP.PlayerType) return FALSE; //probably need to reload if in cheat mode if(CheatMode_Active!=CHEATMODE_NONACTIVE) return FALSE; switch(save_slot->Species) { case I_Marine : if(save_slot->Episode != MarineEpisodeToPlay) return FALSE;; break; case I_Alien : if(save_slot->Episode != AlienEpisodeToPlay) return FALSE; break; case I_Predator : if(save_slot->Episode != PredatorEpisodeToPlay) return FALSE; break; } //certainly need to change level if in multiplayer (or skirmish) if(AvP.Network != I_No_Network) return FALSE; return TRUE; } void LoadSavedGame() { SAVE_SLOT_HEADER* save_slot; char filename[MAX_PATH]; HANDLE file; BOOL terminal_error = FALSE; unsigned int bytes_read; if(LoadGameRequest == SAVELOAD_REQUEST_NONE) return; if(LoadGameRequest<0 || LoadGameRequest>=NUMBER_OF_SAVE_SLOTS) { LoadGameRequest = SAVELOAD_REQUEST_NONE; return; } //get the save_slot save_slot = &SaveGameSlot[LoadGameRequest]; //make sure the slot is being used ScanSaveSlots(); if(!save_slot->SlotUsed) return; ///make sure we're on the right level etc. if(!ValidateLevelForLoadGameRequest(save_slot)) { AvP.MainLoopRunning = FALSE; return; } { extern int GlobalFrameCounter; if(!GlobalFrameCounter) return; } //set the difficulty level and restart the level AvP.Difficulty = static_cast<enum gamedifficulty>(save_slot->Difficulty); RestartLevel(); //get the filename for the save slot GetFilenameForSaveSlot(LoadGameRequest,filename); //we can now clear the load request LoadGameRequest = SAVELOAD_REQUEST_NONE; //load the file file = avp_CreateFile(filename,GENERIC_READ, 0, 0, OPEN_EXISTING,FILE_FLAG_RANDOM_ACCESS, 0); if(file==INVALID_HANDLE_VALUE) { //failed to load EndLoadGame(); return; } LoadInfo.BufferSize = GetFileSize(file, 0); if (!LoadInfo.BufferSize) { CloseHandle(file); EndLoadGame(); return; } //allocate buffer , and read file into memory LoadInfo.BufferStart = (char*) AllocateMem(LoadInfo.BufferSize); ReadFile(file,LoadInfo.BufferStart,LoadInfo.BufferSize,(LPDWORD)&bytes_read,0); CloseHandle(file); LoadInfo.BufferPos = LoadInfo.BufferStart; LoadInfo.BufferSpaceLeft = LoadInfo.BufferSize; // attempt to access level header { //read the next header SAVE_BLOCK_HEADER* header = (SAVE_BLOCK_HEADER*) LoadInfo.BufferPos; if(header->size>LoadInfo.BufferSpaceLeft) { //oh dear, dodgy file GLOBALASSERT("Invalid save game header size"==0); terminal_error = TRUE; } else { //go to the next header LoadInfo.BufferPos += header->size; LoadInfo.BufferSpaceLeft -= header->size; switch(header->type) { case SaveBlock_MainHeader : LoadLevelHeader(header); break; default: GLOBALASSERT("Unrecognized save block type"==0); terminal_error = TRUE; break; } } } if (!terminal_error) { if (!strncmp (LoadInfo.BufferPos, "REBCRIF1", 8)) { char *uncompressedBufferPtr = (char*)HuffmanDecompress((HuffmanPackage*)(LoadInfo.BufferPos)); LoadInfo.BufferSpaceLeft = ((HuffmanPackage*)LoadInfo.BufferPos)->UncompressedDataSize; DeallocateMem(LoadInfo.BufferStart); LoadInfo.BufferStart=uncompressedBufferPtr; LoadInfo.BufferPos = LoadInfo.BufferStart; } else { terminal_error = TRUE; } } //go through loading things while(LoadInfo.BufferSpaceLeft && !terminal_error) { //read the next header SAVE_BLOCK_HEADER* header = (SAVE_BLOCK_HEADER*) LoadInfo.BufferPos; if(header->size>LoadInfo.BufferSpaceLeft) { //oh dear, dodgy file GLOBALASSERT("Invalid save game header size"==0); terminal_error = TRUE; break; } //go to the next header LoadInfo.BufferPos += header->size; LoadInfo.BufferSpaceLeft -= header->size; switch(header->type) { case SaveBlock_MainHeader : LoadLevelHeader(header); break; case SaveBlock_DeadStrategy : LoadDeadStrategy(header); break; case SaveBlock_Strategy : LoadStrategy((SAVE_BLOCK_STRATEGY_HEADER*) header); break; case SaveBlock_Track : //all these should be used up by the various strategy loaders GLOBALASSERT("Unexpected track save block"==0); break; case SaveBlock_Hierarchy : //all these should be used up by the various strategy loaders GLOBALASSERT("Unexpected hierarchy save block"==0); break; case SaveBlock_HierarchySection : //all these should be used up by the various strategy loaders GLOBALASSERT("Unexpected hierarchy section save block"==0); break; case SaveBlock_HierarchyTween : //all these should be used up by the various strategy loaders GLOBALASSERT("Unexpected hierarchy tween save block"==0); break; case SaveBlock_HierarchyDecals : //all these should be used up by the various strategy loaders GLOBALASSERT("Unexpected hierarchy decal save block"==0); break; case SaveBlock_HierarchyDelta : //all these should be used up by the various strategy loaders GLOBALASSERT("Unexpected hierarchy delta save block"==0); break; case SaveBlock_GlobalHive : LoadHiveSettings(header); break; case SaveBlock_MiscGlobal : LoadMiscGlobalStuff(header); break; case SaveBlock_MarineSquad : LoadMarineSquadState(header); break; case SaveBlock_Particles : Load_Particles(header); break; case SaveBlock_Decals : Load_Decals(header); break; case SaveBlock_PheromoneTrail : Load_PheromoneTrails(header); break; case SaveBlock_VolumetricExplosions : Load_VolumetricExplosions(header); break; case SaveBlock_LightElements : Load_LightElements(header); break; case SaveBlock_MessageHistory : Load_MessageHistory(header); break; case SaveBlock_WeaponsCGlobals : Load_WeaponsCGlobals(header); break; case SaveBlock_SoundState : Load_SoundState_NoRef(header); break; default : GLOBALASSERT("Unrecognized save block type"==0); terminal_error = TRUE; break; } } if(terminal_error) { //the save file was screwed , restart the level to be on the safe side RestartLevel(); NewOnScreenMessage(GetTextString(TEXTSTRING_SAVEGAME_ERRORLOADING)); } EndLoadGame(); RemoveDestroyedStrategyBlocks(); //make sure all the containing modules are set properly { int sbIndex = 0; STRATEGYBLOCK *sbPtr; /* loop thro' the strategy block list, looking for objects that need to have their visibilities managed ... */ while(sbIndex < NumActiveStBlocks) { sbPtr = ActiveStBlockList[sbIndex++]; if(sbPtr->maintainVisibility && sbPtr->DynPtr) { MODULE* newModule; newModule = ModuleFromPosition(&(sbPtr->DynPtr->Position), (sbPtr->containingModule)); if(newModule) sbPtr->containingModule = newModule; } } } AllNewModuleHandler(); DoObjectVisibilities(); ResetFrameCounter(); if(!terminal_error) { NewOnScreenMessage(GetTextString(TEXTSTRING_SAVEGAME_GAMELOADED)); DisplaySavesLeft(); } } SAVE_BLOCK_HEADER* GetNextBlockIfOfType(SAVE_BLOCK_TYPE type) { SAVE_BLOCK_HEADER* header; GLOBALASSERT(LoadInfo.BufferPos); if(LoadInfo.BufferSpaceLeft==0) { //no more blocks left return 0; } //look at the next header in the buffer header = (SAVE_BLOCK_HEADER*) LoadInfo.BufferPos; if(header->size>LoadInfo.BufferSpaceLeft) { //oh dear, dodgy file GLOBALASSERT("Invalid save game header size"==0); return 0; } //see if the header is of the type that we are after if(header->type == type) { //okay , advance the buffer position , and return this header LoadInfo.BufferPos += header->size; LoadInfo.BufferSpaceLeft -= header->size; return header; } else { //out of luck return 0; } } static void SaveStrategies() { int i; for(i=0;i<NumActiveStBlocks;i++) { STRATEGYBLOCK* sbPtr = ActiveStBlockList[i]; switch(sbPtr->I_SBtype) { case I_BehaviourMarinePlayer : SaveStrategy_Player(sbPtr); break; case I_BehaviourLiftDoor : SaveStrategy_LiftDoor(sbPtr); break; case I_BehaviourProximityDoor : SaveStrategy_ProxDoor(sbPtr); break; case I_BehaviourSwitchDoor : SaveStrategy_SwitchDoor(sbPtr); break; case I_BehaviourPlatform : SaveStrategy_PlatformLift(sbPtr); break; case I_BehaviourBinarySwitch : SaveStrategy_BinarySwitch(sbPtr); break; case I_BehaviourLinkSwitch : SaveStrategy_LinkSwitch(sbPtr); break; case I_BehaviourGenerator : SaveStrategy_Generator(sbPtr); break; case I_BehaviourInanimateObject : SaveStrategy_InanimateObject(sbPtr); break; case I_BehaviourLightFX : SaveStrategy_LightFx(sbPtr); break; case I_BehaviourPlacedSound : SaveStrategy_PlacedSound(sbPtr); break; case I_BehaviourMessage : SaveStrategy_Message(sbPtr); break; case I_BehaviourMissionComplete : SaveStrategy_MissionComplete(sbPtr); break; case I_BehaviourTrackObject : SaveStrategy_TrackObject(sbPtr); break; case I_BehaviourFan : SaveStrategy_Fan(sbPtr); break; case I_BehaviourPlacedLight : SaveStrategy_PlacedLight(sbPtr); break; case I_BehaviourVideoScreen : SaveStrategy_VideoScreen(sbPtr); break; case I_BehaviourSelfDestruct : SaveStrategy_SelfDestruct(sbPtr); break; case I_BehaviourParticleGenerator : SaveStrategy_ParticleGenerator(sbPtr); break; case I_BehaviourDeathVolume : SaveStrategy_DeathVolume(sbPtr); break; case I_BehaviourAlien : SaveStrategy_Alien(sbPtr); break; case I_BehaviourNetCorpse : SaveStrategy_Corpse(sbPtr); break; case I_BehaviourFaceHugger : SaveStrategy_FaceHugger(sbPtr); break; case I_BehaviourMarine : SaveStrategy_Marine(sbPtr); break; case I_BehaviourPlacedHierarchy : SaveStrategy_PlacedHierarchy(sbPtr); break; case I_BehaviourPredator : SaveStrategy_Predator(sbPtr); break; case I_BehaviourXenoborg : SaveStrategy_Xenoborg(sbPtr); break; case I_BehaviourQueenAlien : SaveStrategy_Queen(sbPtr); break; case I_BehaviourAutoGun : SaveStrategy_Autogun(sbPtr); break; case I_BehaviourHierarchicalFragment : SaveStrategy_HierarchicalDebris(sbPtr); break; case I_BehaviourGrenade : SaveStrategy_Grenade(sbPtr); break; case I_BehaviourFlareGrenade : SaveStrategy_FlareGrenade(sbPtr); break; case I_BehaviourProximityGrenade : SaveStrategy_ProxGrenade(sbPtr); break; case I_BehaviourRocket : SaveStrategy_Rocket(sbPtr); break; case I_BehaviourPPPlasmaBolt : SaveStrategy_PPPlasmaBolt(sbPtr); break; case I_BehaviourPredatorEnergyBolt : SaveStrategy_PredatorEnergyBolt(sbPtr); break; case I_BehaviourFrisbeeEnergyBolt : SaveStrategy_FrisbeeEnergyBolt(sbPtr); break; case I_BehaviourPulseGrenade : SaveStrategy_PulseGrenade(sbPtr); break; case I_BehaviourClusterGrenade : SaveStrategy_ClusterGrenade(sbPtr); break; case I_BehaviourMolotov : SaveStrategy_Molotov(sbPtr); break; case I_BehaviourPredatorDisc_SeekTrack : SaveStrategy_PredatorDisc(sbPtr); break; case I_BehaviourSpeargunBolt : SaveStrategy_SpearBolt(sbPtr); break; case I_BehaviourGrapplingHook : SaveStrategy_Grapple(sbPtr); break; case I_BehaviourFragment : SaveStrategy_Debris(sbPtr); break; case I_BehaviourFrisbee : SaveStrategy_Frisbee(sbPtr); break; default: ; } } } static void LoadStrategy(SAVE_BLOCK_STRATEGY_HEADER* header) { switch(header->bhvr_type) { case I_BehaviourMarinePlayer : LoadStrategy_Player(header); break; case I_BehaviourLiftDoor : LoadStrategy_LiftDoor(header); break; case I_BehaviourProximityDoor : LoadStrategy_ProxDoor(header); break; case I_BehaviourSwitchDoor : LoadStrategy_SwitchDoor(header); break; case I_BehaviourPlatform : LoadStrategy_PlatformLift(header); break; case I_BehaviourBinarySwitch : LoadStrategy_BinarySwitch(header); break; case I_BehaviourLinkSwitch : LoadStrategy_LinkSwitch(header); break; case I_BehaviourGenerator : LoadStrategy_Generator(header); break; case I_BehaviourInanimateObject : LoadStrategy_InanimateObject(header); break; case I_BehaviourLightFX : LoadStrategy_LightFx(header); break; case I_BehaviourPlacedSound : LoadStrategy_PlacedSound(header); break; case I_BehaviourMessage : LoadStrategy_Message(header); break; case I_BehaviourMissionComplete : LoadStrategy_MissionComplete(header); break; case I_BehaviourTrackObject : LoadStrategy_TrackObject(header); break; case I_BehaviourFan : LoadStrategy_Fan(header); break; case I_BehaviourPlacedLight : LoadStrategy_PlacedLight(header); break; case I_BehaviourVideoScreen : LoadStrategy_VideoScreen(header); break; case I_BehaviourSelfDestruct : LoadStrategy_SelfDestruct(header); break; case I_BehaviourParticleGenerator : LoadStrategy_ParticleGenerator(header); break; case I_BehaviourDeathVolume : LoadStrategy_DeathVolume(header); break; case I_BehaviourAlien : LoadStrategy_Alien(header); break; case I_BehaviourNetCorpse : LoadStrategy_Corpse(header); break; case I_BehaviourFaceHugger : LoadStrategy_FaceHugger(header); break; case I_BehaviourMarine : LoadStrategy_Marine(header); break; case I_BehaviourPlacedHierarchy : LoadStrategy_PlacedHierarchy(header); break; case I_BehaviourPredator : LoadStrategy_Predator(header); break; case I_BehaviourXenoborg : LoadStrategy_Xenoborg(header); break; case I_BehaviourQueenAlien : LoadStrategy_Queen(header); break; case I_BehaviourAutoGun : LoadStrategy_Autogun(header); break; case I_BehaviourHierarchicalFragment : LoadStrategy_HierarchicalDebris(header); break; case I_BehaviourGrenade : LoadStrategy_Grenade(header); break; case I_BehaviourFlareGrenade : LoadStrategy_FlareGrenade(header); break; case I_BehaviourProximityGrenade : LoadStrategy_ProxGrenade(header); break; case I_BehaviourRocket : LoadStrategy_Rocket(header); break; case I_BehaviourPPPlasmaBolt : LoadStrategy_PPPlasmaBolt(header); break; case I_BehaviourPredatorEnergyBolt : LoadStrategy_PredatorEnergyBolt(header); break; case I_BehaviourFrisbeeEnergyBolt : LoadStrategy_FrisbeeEnergyBolt(header); break; case I_BehaviourPulseGrenade : LoadStrategy_PulseGrenade(header); break; case I_BehaviourClusterGrenade : LoadStrategy_ClusterGrenade(header); break; case I_BehaviourMolotov : LoadStrategy_Molotov(header); break; case I_BehaviourPredatorDisc_SeekTrack : LoadStrategy_PredatorDisc(header); break; case I_BehaviourSpeargunBolt : LoadStrategy_SpearBolt(header); break; case I_BehaviourGrapplingHook : LoadStrategy_Grapple(header); break; case I_BehaviourFragment : LoadStrategy_Debris(header); break; case I_BehaviourFrisbee : LoadStrategy_Frisbee(header); break; default: ; } } /*------------------------------------** ** Loading and saving dead strategies ** **------------------------------------*/ typedef struct dead_strategy_save_block { SAVE_BLOCK_HEADER header; char SBname[SB_NAME_LENGTH]; }DEAD_STRATEGY_SAVE_BLOCK; static void SaveDeadStrategies() { extern STRATEGYBLOCK FreeStBlockData[]; int i; STRATEGYBLOCK* sbPtr = &FreeStBlockData[0]; //search for all the strategies that existed at the start , and have been destroyed for(i=0;i<maxstblocks;i++ , sbPtr++) { if(sbPtr->SBflags.destroyed_but_preserved) { DEAD_STRATEGY_SAVE_BLOCK* block; GET_SAVE_BLOCK_POINTER(DEAD_STRATEGY_SAVE_BLOCK, block); block->header.type = SaveBlock_DeadStrategy; block->header.size = sizeof(*block); COPY_NAME(block->SBname,sbPtr->SBname); } } } static void LoadDeadStrategy(SAVE_BLOCK_HEADER* header) { DEAD_STRATEGY_SAVE_BLOCK* block = (DEAD_STRATEGY_SAVE_BLOCK*) header; STRATEGYBLOCK* sbPtr = FindSBWithName(block->SBname); if(sbPtr) { DestroyAnyStrategyBlock(sbPtr); } } /*--------------------------------------------------------------------------------** ** Loading and saving miscellaneos global rubbish that has nowhere else to live ** **--------------------------------------------------------------------------------*/ extern unsigned int IncrementalSBname; extern int PlayersMaxHeightWhilstNotInContactWithGround; typedef struct misc_global_save_block { SAVE_BLOCK_HEADER header; unsigned int IncrementalSBname; AvP_GameStats CurrentGameStatistics; int PlayersMaxHeightWhilstNotInContactWithGround; int NumberOfSavesLeft; int FMV_MessageNumber; int FMV_FrameNumber; }MISC_GLOBAL_SAVE_BLOCK; static void LoadMiscGlobalStuff(SAVE_BLOCK_HEADER* header) { MISC_GLOBAL_SAVE_BLOCK* block; block = (MISC_GLOBAL_SAVE_BLOCK*) header; if(block->header.size != sizeof(*block)) return; IncrementalSBname = block->IncrementalSBname; CurrentGameStatistics = block->CurrentGameStatistics; PlayersMaxHeightWhilstNotInContactWithGround = block->PlayersMaxHeightWhilstNotInContactWithGround; NumberOfSavesLeft = block-> NumberOfSavesLeft; StartFMVAtFrame(block->FMV_MessageNumber,block->FMV_FrameNumber); } static void SaveMiscGlobalStuff() { MISC_GLOBAL_SAVE_BLOCK* block; block = static_cast<MISC_GLOBAL_SAVE_BLOCK*>(GetPointerForSaveBlock(sizeof(*block))); //fill in the header block->header.type = SaveBlock_MiscGlobal; block->header.size = sizeof(*block); block->IncrementalSBname = IncrementalSBname; block->CurrentGameStatistics = CurrentGameStatistics; block->PlayersMaxHeightWhilstNotInContactWithGround = PlayersMaxHeightWhilstNotInContactWithGround; block->NumberOfSavesLeft = NumberOfSavesLeft; GetFMVInformation(&block->FMV_MessageNumber,&block->FMV_FrameNumber); } extern void DisplaySavesLeft() { char text [100]; sprintf(text, "%s: %d", GetTextString(TEXTSTRING_SAVEGAME_SAVESLEFT), NumberOfSavesLeft); NewOnScreenMessage(text); } extern void ResetNumberOfSaves() { switch(AvP.Difficulty) { case I_Easy : NumberOfSavesLeft = NUM_SAVES_FOR_EASY_MODE; break; case I_Medium : NumberOfSavesLeft = NUM_SAVES_FOR_MEDIUM_MODE; break; case I_Hard : case I_Impossible : NumberOfSavesLeft = NUM_SAVES_FOR_HARD_MODE; break; default: break; } }
24.767684
141
0.759312
Melanikus
95ae9fea11011ae96794eb16b7cf9972115530ca
807
cpp
C++
src/chapter_07_concurrency/problem_062_parallel_minmax_with_threads.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_07_concurrency/problem_062_parallel_minmax_with_threads.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_07_concurrency/problem_062_parallel_minmax_with_threads.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
#include "chapter_07_concurrency/problem_062_parallel_minmax_with_threads.h" #include "parallel_minmax.h" #include <ostream> #include <vector> void problem_62_main(std::ostream& os) { parallel_minmax( os, [](auto first, auto last) { return tmcppc::algorithm::thread::parallel_min(first, last); }, [](auto first, auto last) { return tmcppc::algorithm::thread::parallel_max(first, last); } ); } // Parallel min and max element algorithms using threads // // Implement general-purpose parallel algorithms that find the minimum value and, respectively, the maximum value in a given range. // The parallelism should be implemented using threads, although the number of concurrent threads is an implementation detail. void problem_62_main() { problem_62_main(std::cout); }
35.086957
131
0.739777
rturrado
95afe1b3093151b40e79f796de05d780d4aae00e
14,529
cpp
C++
gui/ctrl/std_dialogs.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
gui/ctrl/std_dialogs.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
gui/ctrl/std_dialogs.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
/** * @copyright (c) 2016-2021 Ing. Buero Rothfuss * Riedlinger Str. 8 * 70327 Stuttgart * Germany * http://www.rothfuss-web.de * * @author <a href="mailto:armin@rothfuss-web.de">Armin Rothfuss</a> * * Project gui++ lib * * @brief standard dialogs * * @license MIT license. See accompanying file LICENSE. */ // -------------------------------------------------------------------------- // // Library includes // #include <gui/ctrl/std_dialogs.h> namespace gui { namespace ctrl { namespace detail { // -------------------------------------------------------------------------- template<> GUIPP_CTRL_EXPORT core::rectangle std_multi_input_dialog_size<core::os::ui_t::desktop> (const core::rectangle&, std::size_t n, unsigned dimension) { return core::rectangle(300, 200, 400, static_cast<core::size::type>(80 + n * dimension)); } template<> GUIPP_CTRL_EXPORT core::rectangle std_path_open_dialog_size<core::os::ui_t::desktop> (const core::rectangle&) { return win::window::screen_area() / 3 * 2; } template<> GUIPP_CTRL_EXPORT core::rectangle std_message_dialog_size<core::os::ui_t::desktop> (const core::rectangle&) { return core::rectangle(300, 200, 400, 170); } template<> GUIPP_CTRL_EXPORT core::rectangle std_yes_no_dialog_size<core::os::ui_t::desktop> (const core::rectangle& area) { return std_message_dialog_size<core::os::ui_t::desktop>(area); } template<> GUIPP_CTRL_EXPORT core::rectangle std_input_dialog_size<core::os::ui_t::desktop> (const core::rectangle&) { return core::rectangle(300, 200, 400, 125); } template<> GUIPP_CTRL_EXPORT core::rectangle std_file_save_dialog_size<core::os::ui_t::desktop> (const core::rectangle& area) { return std_path_open_dialog_size<core::os::ui_t::desktop>(area); } //----------------------------------------------------------------------------- template<> GUIPP_CTRL_EXPORT core::rectangle std_multi_input_dialog_size<core::os::ui_t::mobile> (const core::rectangle& /*area*/, std::size_t n, unsigned dimension) { return win::window::screen_area().shrinked({ 20, 20 }).with_height(static_cast<core::size::type>(80 + n * dimension)); } template<> GUIPP_CTRL_EXPORT core::rectangle std_path_open_dialog_size<core::os::ui_t::mobile> (const core::rectangle&) { return win::window::screen_area(); } template<> GUIPP_CTRL_EXPORT core::rectangle std_message_dialog_size<core::os::ui_t::mobile> (const core::rectangle&) { return win::window::screen_area().shrinked({ 30, 100 }); } template<> GUIPP_CTRL_EXPORT core::rectangle std_yes_no_dialog_size<core::os::ui_t::mobile> (const core::rectangle& area) { return std_message_dialog_size<core::os::ui_t::mobile>(area); } template<> GUIPP_CTRL_EXPORT core::rectangle std_input_dialog_size<core::os::ui_t::mobile> (const core::rectangle&) { return win::window::screen_area().shrinked({ 30, 100 }); } template<> GUIPP_CTRL_EXPORT core::rectangle std_file_save_dialog_size<core::os::ui_t::mobile> (const core::rectangle& area) { return std_path_open_dialog_size<core::os::ui_t::mobile>(area); } //----------------------------------------------------------------------------- } // namespace detail //----------------------------------------------------------------------------- yes_no_dialog::yes_no_dialog () { content_view.get_layout().set_center(layout::lay(message_view)); } void yes_no_dialog::create (win::overlapped_window& parent, const std::string& title, const std::string& message, const std::string& yes_label, const std::string& no_label, const core::rectangle& rect, std::function<yes_no_action> action) { super::create(parent, title, yes_label, no_label, rect, action); message_view.create(super::content_view, message); } void yes_no_dialog::show (win::overlapped_window& parent) { super::run_modal(parent, { win::hot_key_action{ core::hot_key(core::keys::escape, core::state::none), [&] () { action(*this, false); super::end_modal(); } }, win::hot_key_action{ core::hot_key(core::keys::right, core::state::none), [&] () { super::shift_focus(false); } }, win::hot_key_action{ core::hot_key(core::keys::left, core::state::none), [&] () { super::shift_focus(true); } } }); } void yes_no_dialog::ask (win::overlapped_window& parent, const std::string& title, const std::string& message, const std::string& yes_label, const std::string& no_label, std::function<yes_no_action> action) { yes_no_dialog dialog; dialog.create(parent, title, message, yes_label, no_label, detail::std_yes_no_dialog_size<>(parent.geometry()), action); dialog.show(parent); } //----------------------------------------------------------------------------- message_dialog::message_dialog () { content_view.get_layout().set_center(layout::lay(message_view)); } void message_dialog::create (win::overlapped_window& parent, const std::string& title, const std::string& message, const std::string& ok_label, const core::rectangle& rect) { super::create(parent, title, rect, {ok_label}, [&] (win::overlapped_window&, int) { end_modal(); }); message_view.create(content_view, message); } void message_dialog::show (win::overlapped_window& parent, const std::string& title, const std::string& message, const std::string& ok_label) { message_dialog dialog; dialog.create(parent, title, message, ok_label, detail::std_message_dialog_size<>(parent.geometry())); dialog.super::show(parent); } //----------------------------------------------------------------------------- input_dialog::input_dialog () { super::content_view.get_layout().add(layout::lay(label)); super::content_view.get_layout().add(layout::lay(edit)); } void input_dialog::create (win::overlapped_window& parent, const std::string& title, const std::string& message, const std::string& initial, const std::string& ok_label, const std::string& cancel_label, const core::rectangle& rect, std::function<input_action> action) { super::create(parent, title, rect, {cancel_label, ok_label}, [&, action] (win::overlapped_window& dlg, int i) { if (i == 1) { action(dlg, edit.get_text()); } }); label.create(super::content_view, message); edit.create(super::content_view, initial); } void input_dialog::ask (win::overlapped_window& parent, const std::string& title, const std::string& message, const std::string& initial, const std::string& ok_label, const std::string& cancel_label, std::function<input_action> action) { input_dialog dialog; dialog.create(parent, title, message, initial, ok_label, cancel_label, detail::std_input_dialog_size<>(parent.geometry()), action); dialog.show(parent); } //----------------------------------------------------------------------------- std::function<create_subdirectory> make_create_subdirectory_fn (const std::string& title, const std::string& message, const std::string& initial, const std::string& ok_label, const std::string& cancel_label) { return [=] (win::overlapped_window& parent, const sys_fs::path& parent_dir) -> bool { bool return_value = false; input_dialog::ask(parent, title, message, initial, ok_label, cancel_label, [&] (win::overlapped_window&, const std::string& t) { return_value = sys_fs::create_directory(parent_dir / t); }); return return_value; }; } std::function<create_subdirectory> make_default_create_subdirectory_fn () { return make_create_subdirectory_fn("Create directory", "Create new sub-directory", "", "Create", "Cancel"); } //----------------------------------------------------------------------------- dir_tree_view::dir_tree_view (create_subdirectory_fn fn) : fn(fn) { init(); } dir_tree_view::dir_tree_view (dir_tree_view&& rhs) : super(std::move(rhs)) , header(std::move(rhs.header)) , view(std::move(rhs.view)) , add_button(std::move(rhs.add_button)) , fn(std::move(rhs.fn)) {} void dir_tree_view::init () { get_layout().set_header_and_body(layout::lay(header), layout::lay(view)); header.set_background(color::very_very_light_gray); header.on_paint(draw::paint([&] (draw::graphics& graph) { core::rectangle r = client_geometry(); graph.fill(draw::rectangle(r), get_background()); draw::frame::raised_relief(graph, r); })); if (fn) { add_button.set_foreground(color::black); header.get_layout().add(layout::lay(add_button)); add_button.on_clicked([&] () { if (view->has_selection()) { auto parent_dir = view->get_item(view->get_selection().get_first_index()).path; if (fn(super::get_overlapped_window(), parent_dir)) { view->update_node_list(); } } }); } } void dir_tree_view::set_create_subdirectory_fn (create_subdirectory_fn fn_) { fn = fn_; } void dir_tree_view::create (win::container& parent, const core::rectangle& r) { init(); super::create(clazz::get(), parent, r); header.create(*this); view.create(*this); add_button.create(header); } //----------------------------------------------------------------------------- file_save_dialog::file_save_dialog (create_subdirectory_fn fn) : super(dir_file_view(fn)) {} void file_save_dialog::create (win::overlapped_window& parent, const std::string& title, const std::string& default_name, const std::string& name_label, const std::string& ok_label, const std::string& cancel_label, const core::rectangle& rect, std::function<file_selected> action) { auto& dir_tree = content_view.first.view.view; auto& files = content_view.second; content_view.init([&, action] (win::overlapped_window& dlg, const sys_fs::path& path) { set_visible(false); end_modal(); action(dlg, path); }); files.list->on_selection_changed([&] (event_source) { input_line.init_text(files.get_selected_path().filename().string()); }); top_view.get_layout().set_center(layout::lay(input_line)); top_view.get_layout().set_left(layout::lay(input_label)); get_layout().set_top(layout::lay(top_view)); super::create(parent, title, rect, {cancel_label, ok_label}, [&, action] (win::overlapped_window& dlg, int btn) { if (1 == btn) { if (dir_tree.has_selection()) { int idx = dir_tree.get_selection().get_first_index(); sys_fs::path path = dir_tree.get_item(idx).path; path /= input_line.get_text(); action(dlg, path); } } }); top_view.create(*this, core::rectangle(0, 0, 100, 100)); input_label.create(top_view, name_label, core::rectangle(0, 0, 100, 100)); input_line.create(top_view, default_name, core::rectangle(0, 0, 100, 100)); content_view.set_split_pos(0.3); top_view.set_background(color::very_very_light_gray); sys_fs::path current = sys_fs::current_path(); dir_tree.set_roots(fs::get_all_root_file_infos()); for (auto next = current; next.has_root_path() && (next != next.root_path()); next = next.parent_path()) { dir_tree.add_open_node(next); } dir_tree.add_open_node(current.root_path()); dir_tree.update_node_list(); dir_tree.select_node(current); files.set_path(current); } void file_save_dialog::show (win::overlapped_window& parent, const std::string& title, const std::string& default_name, const std::string& name_label, const std::string& ok_label, const std::string& cancel_label, std::function<file_selected> action, create_subdirectory_fn fn) { file_save_dialog dialog(fn); dialog.create(parent, title, default_name, name_label, ok_label, cancel_label, detail::std_file_save_dialog_size<>(parent.geometry()), action); dialog.super::show(parent); } //----------------------------------------------------------------------------- } // ctrl } // gui
40.358333
162
0.527015
r3dl3g
95b0af0fd0dcf58558a4436ff5802b7fae3edc04
79
cpp
C++
cppcheck/data/c_files/81.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
2
2022-03-23T12:16:20.000Z
2022-03-31T06:19:40.000Z
cppcheck/data/c_files/81.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
cppcheck/data/c_files/81.cpp
awsm-research/LineVul
246baf18c1932094564a10c9b81efb21914b2978
[ "MIT" ]
null
null
null
bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); }
15.8
42
0.632911
awsm-research
95c70abfe86f45087ff11e71a2ed265c2c81e27d
2,730
hh
C++
src/GSPH/Policies/PureReplaceFieldList.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/GSPH/Policies/PureReplaceFieldList.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
17
2020-01-05T08:41:46.000Z
2020-09-18T00:08:32.000Z
src/GSPH/Policies/PureReplaceFieldList.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // PureReplaceFieldList -- replaces one fieldlists values with those of // another specified by its key // // J.M. Pearl 2022 //----------------------------------------------------------------------------// #ifndef __Spheral_PureReplaceFieldList_hh__ #define __Spheral_PureReplaceFieldList_hh__ #include "DataBase/FieldListUpdatePolicyBase.hh" namespace Spheral { template<typename Dimension, typename ValueType> class PureReplaceFieldList: public FieldListUpdatePolicyBase<Dimension, ValueType> { public: //--------------------------- Public Interface ---------------------------// // Useful typedefs typedef typename FieldListUpdatePolicyBase<Dimension, ValueType>::KeyType KeyType; // Constructors, destructor. explicit PureReplaceFieldList(const KeyType& derivFieldListKey); PureReplaceFieldList(const KeyType& derivFieldListKey, const std::string& depend0); PureReplaceFieldList(const KeyType& derivFieldListKey, const std::string& depend0, const std::string& depend1); PureReplaceFieldList(const KeyType& derivFieldListKey, const std::string& depend0, const std::string& depend1, const std::string& depend2); PureReplaceFieldList(const KeyType& derivFieldListKey, const std::string& depend0, const std::string& depend1, const std::string& depend2, const std::string& depend3); PureReplaceFieldList(const KeyType& derivFieldListKey, const std::string& depend0, const std::string& depend1, const std::string& depend2, const std::string& depend3, const std::string& depend4); PureReplaceFieldList(const KeyType& derivFieldListKey, const std::string& depend0, const std::string& depend1, const std::string& depend2, const std::string& depend3, const std::string& depend4, const std::string& depend5); virtual ~PureReplaceFieldList(); // Overload the methods describing how to update FieldLists. virtual void update(const KeyType& key, State<Dimension>& state, StateDerivatives<Dimension>& derivs, const double multiplier, const double t, const double dt) override; // Equivalence. virtual bool operator==(const UpdatePolicyBase<Dimension>& rhs) const; private: //--------------------------- Private Interface ---------------------------// const KeyType mReplaceKey; PureReplaceFieldList(); PureReplaceFieldList(const PureReplaceFieldList& rhs); PureReplaceFieldList& operator=(const PureReplaceFieldList& rhs); }; } #else // Forward declaration. namespace Spheral { template<typename Dimension, typename ValueType> class PureReplaceFieldList; } #endif
43.333333
225
0.672894
jmikeowen
95cb7d81d7bfdeb835c76c529c37cbd9f95d214b
188
hpp
C++
Server/include/conn/Connection.hpp
BartekBanachowicz/distributed-matrix-multiplication
af9022284bc364640414973b0e6dee4b5a6373bc
[ "MIT" ]
null
null
null
Server/include/conn/Connection.hpp
BartekBanachowicz/distributed-matrix-multiplication
af9022284bc364640414973b0e6dee4b5a6373bc
[ "MIT" ]
null
null
null
Server/include/conn/Connection.hpp
BartekBanachowicz/distributed-matrix-multiplication
af9022284bc364640414973b0e6dee4b5a6373bc
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <conn/Type.hpp> namespace mm_server::conn { struct Connection { Type type = Type::unassigned; std::string address; }; }
13.428571
37
0.62234
BartekBanachowicz
95d5535cfa001fd4e859fa243fc413192a221ec9
5,472
cpp
C++
src/core/imported/rdf/rdfg/src/rdfg.cpp
GPUOpen-Drivers/pal
bcec463efe5260776d486a5e3da0c549bc0a75d2
[ "MIT" ]
268
2017-12-22T11:03:10.000Z
2022-03-31T15:37:31.000Z
src/core/imported/rdf/rdfg/src/rdfg.cpp
GPUOpen-Drivers/pal
bcec463efe5260776d486a5e3da0c549bc0a75d2
[ "MIT" ]
79
2017-12-22T12:26:52.000Z
2022-03-30T13:06:30.000Z
src/core/imported/rdf/rdfg/src/rdfg.cpp
GPUOpen-Drivers/pal
bcec463efe5260776d486a5e3da0c549bc0a75d2
[ "MIT" ]
92
2017-12-22T12:21:16.000Z
2022-03-29T22:34:17.000Z
/* *********************************************************************************************************************** * * Copyright (c) 2021 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 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 <cli11/CLI11.hpp> #include <json/json.hpp> #include "IO.h" namespace { std::vector<std::byte> ConvertArrayToBytes(const nlohmann::json& object) { if (! object.is_array()) { throw std::runtime_error("Object must be an array."); } std::vector<std::byte> result; result.reserve(object.size()); for (const auto& element : object) { std::byte b; if (element.is_number_unsigned()) { const auto v = element.get<std::uint32_t>(); if (v > 255) { throw std::runtime_error("Byte array values must be within 0..255"); } b = static_cast<std::byte>(v); } else if (element.is_number_integer()) { const auto v = element.get<std::int32_t>(); if (v < 0 || v > 255) { throw std::runtime_error("Byte array values must be within 0..255"); } b = static_cast<std::byte>(v); } else { throw std::runtime_error("Byte array must consist of integer numbers only."); } result.push_back(b); } return result; } int CreateChunkFile(const std::string& input, const std::string& output, const bool verbose) { auto inputStream = rdf::Stream::OpenFile(input.c_str()); std::vector<char> buffer(inputStream.GetSize()); inputStream.Read(buffer.size(), buffer.data()); auto outputStream = rdf::Stream::CreateFile(output.c_str()); rdf::ChunkFileWriter writer(outputStream); nlohmann::json config = nlohmann::json::parse(buffer.begin(), buffer.end()); for (const auto& chunk : config["chunks"]) { const auto id = chunk["id"].get<std::string>(); int version = 1; if (chunk.contains("version")) { version = chunk["version"].get<int>(); } rdfCompression compression = rdfCompressionNone; if (chunk.contains("compression")) { const auto c = chunk["compression"].get<std::string>(); if (c == "zstd" || c == "zstandard") { compression = rdfCompressionZstd; } } if (chunk.contains("header")) { const auto header = ConvertArrayToBytes(chunk["header"]); writer.BeginChunk(id.c_str(), header.size(), header.data(), compression, version); if (verbose) { std::cout << "Begin chunk: '" << id << "' with header, compression: " << compression << ", version: " << version << "\n"; } } else { writer.BeginChunk(id.c_str(), 0, nullptr, compression, version); if (verbose) { std::cout << "Begin chunk: '" << id << "' without header, compression: " << compression << ", version: " << version << "\n"; } } if (chunk.contains("data")) { const auto data = ConvertArrayToBytes(chunk["data"]); writer.AppendToChunk(data.size(), data.data()); if (verbose) { std::cout << "Writing data" << "\n"; } } writer.EndChunk(); if (verbose) { std::cout << "End chunk: '" << id << "'" << "\n"; } } writer.Close(); return 0; } } // namespace int main(int argc, char* argv[]) { CLI::App app{"RDFG 1.0"}; std::string input, output; bool verbose = false; auto createChunkFile = app.add_subcommand("create", "Create a chunk file from the provided input"); createChunkFile->add_option("input", input)->required(); createChunkFile->add_option("output", output)->required(); createChunkFile->add_flag("-v,--verbose", verbose); CLI11_PARSE(app, argc, argv); try { if (*createChunkFile) { return CreateChunkFile(input, output, verbose); } } catch (const std::exception& ex) { std::cerr << ex.what() << std::endl; } return 0; }
32.963855
120
0.552814
GPUOpen-Drivers
95d98baa7b1353c2b43c127d3ab27c82591d2496
127
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/Cwise_times_equal.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/Cwise_times_equal.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/Cwise_times_equal.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:a4b326b5770327f2e387ada112e34935d3142a19898ce83a28cb9d9d783811e5 size 55
31.75
75
0.88189
initialz
95dfc67653c8b1d38e15cadd7b238cefebd3bf69
2,217
cpp
C++
practical_2/main.cpp
40330977/Games_Engineering_1
3a01f8fb31707cdabe657a7900992b8624ec38b7
[ "MIT" ]
null
null
null
practical_2/main.cpp
40330977/Games_Engineering_1
3a01f8fb31707cdabe657a7900992b8624ec38b7
[ "MIT" ]
null
null
null
practical_2/main.cpp
40330977/Games_Engineering_1
3a01f8fb31707cdabe657a7900992b8624ec38b7
[ "MIT" ]
null
null
null
#include <iostream> #include <SFML/Graphics.hpp> #include "ship.h" #include "bullet.h" #include "game.h" using namespace sf; using namespace std; sf::Texture spritesheet; sf::Sprite invader; std::vector<Ship *> ships; Player *player = new Player(); //void Load(); //const int gameWidth = 800; //const int gameHeight = 600; //int invaders_rows = 5; //int invaders_columns = 12; float r1, c1; void Load() { if (!spritesheet.loadFromFile("C:/Users/40330977/Desktop/Games_Engineering_1/res/invaders_sheet.png")) { cerr << "Failed to load spritesheet!" << std::endl; spritesheet.loadFromFile("C:/Users/Roddy/Desktop/Games_Engineering_1/res/invaders_sheet.png"); } /*invader.setTexture(spritesheet); invader.setTextureRect(sf::IntRect(0, 0, 32, 32));*/ /*Invader* inv = new Invader(sf::IntRect(0, 0, 32, 32), { 100,100 }); ships.push_back(inv);*/ for (int r = 0; r < invaders_rows; ++r) { auto rect = IntRect(0, 0, 32, 32); for (int c = 0; c < invaders_columns; ++c) { r1 = 100 + r * 30; c1 = 100 + c * 30; Vector2f position = {r1 , c1 }; auto inv = new Invader(rect, position); ships.push_back(inv); } } } void Update(RenderWindow &window) { // Update Everything static Clock clock; float dt = clock.restart().asSeconds(); // check and consume events Event event; while (window.pollEvent(event)) { if (event.type == Event::Closed) { window.close(); return; } } // Quit Via ESC Key if (Keyboard::isKeyPressed(Keyboard::Escape)) { window.close(); } for (auto &s : ships) { s->Update(dt); } player->Update(dt); /*for (auto &b : bullets) { b->Update(dt); }*/ /*if (Keyboard::isKeyPressed(Keyboard::D)) { bullets->Fire(player->getPosition(), false); } bullets[bulletpointer].Update(dt);*/ Bullet::Update(dt); } void Render(RenderWindow &window) { // Draw Everything window.draw(*player); for (const auto s : ships) { window.draw(*s); } Bullet::Render(window); } int main() { RenderWindow window(VideoMode(gameWidth, gameHeight), "SPACE INVADERS"); Load(); while (window.isOpen()) { window.clear(); Update(window); Render(window); window.display(); } return 0; } /*void firer() { Fire() }*/
18.788136
105
0.644114
40330977
95e03477843c64cc266c3ed2526d625bcd91774a
94
cpp
C++
cppevents/src/subject.cpp
rcktscnc/examples
e46b154eac17405a3bc8fc401150692e74559c6d
[ "MIT" ]
null
null
null
cppevents/src/subject.cpp
rcktscnc/examples
e46b154eac17405a3bc8fc401150692e74559c6d
[ "MIT" ]
null
null
null
cppevents/src/subject.cpp
rcktscnc/examples
e46b154eac17405a3bc8fc401150692e74559c6d
[ "MIT" ]
null
null
null
#include <subject.h> util::lambda_event<std::string, const std::string&> Subject::on_request;
31.333333
72
0.755319
rcktscnc
95e072ffb7f9663cf31f5b25802362e929955853
13,139
cpp
C++
src/gui/selection_details_widget/net_details_widget.cpp
citypw/hal
c906c8fc34b8623533725d240aebcbce2d5a1c68
[ "MIT" ]
null
null
null
src/gui/selection_details_widget/net_details_widget.cpp
citypw/hal
c906c8fc34b8623533725d240aebcbce2d5a1c68
[ "MIT" ]
null
null
null
src/gui/selection_details_widget/net_details_widget.cpp
citypw/hal
c906c8fc34b8623533725d240aebcbce2d5a1c68
[ "MIT" ]
1
2020-01-09T23:38:55.000Z
2020-01-09T23:38:55.000Z
#include "selection_details_widget/net_details_widget.h" #include "gui_globals.h" #include "netlist/gate.h" #include "netlist/module.h" #include "netlist/net.h" #include <QHeaderView> #include <QLabel> #include <QScrollArea> #include <QTableWidget> #include <QTableWidgetItem> #include <QTreeWidget> #include <QTreeWidgetItem> #include <QVBoxLayout> net_details_widget::net_details_widget(QWidget* parent) : QWidget(parent) { m_current_id = 0; m_content_layout = new QVBoxLayout(this); m_content_layout->setContentsMargins(0, 0, 0, 0); m_content_layout->setSpacing(0); m_content_layout->setAlignment(Qt::AlignTop); m_tree_row_layout = new QHBoxLayout(); m_content_layout->setContentsMargins(0, 0, 0, 0); m_content_layout->setSpacing(0); m_general_table = new QTableWidget(this); m_general_table->horizontalHeader()->setStretchLastSection(true); m_general_table->horizontalHeader()->hide(); m_general_table->verticalHeader()->hide(); m_general_table->setColumnCount(2); m_general_table->setRowCount(3);//removed modules item temporary, may even be final //m_general_table->setStyleSheet("QTableWidget {background-color : rgb(31, 34, 35);}"); QFont font("Iosevka"); font.setBold(true); font.setPixelSize(13); //m_item_deleted_label = new QLabel(this); //m_item_deleted_label->setText("Currently selected item has been removed. Please consider relayouting the Graph."); //m_item_deleted_label->setWordWrap(true); //m_item_deleted_label->setAlignment(Qt::AlignmentFlag::AlignTop); //m_item_deleted_label->setHidden(true); //m_content_layout->addWidget(m_item_deleted_label); QTableWidgetItem* name_item = new QTableWidgetItem("Name:"); name_item->setFlags(Qt::ItemIsEnabled); // name_item->setTextColor(Qt::red); name_item->setFont(font); m_general_table->setItem(0, 0, name_item); QTableWidgetItem* type_item = new QTableWidgetItem("Type:"); type_item->setFlags(Qt::ItemIsEnabled); type_item->setFont(font); m_general_table->setItem(1, 0, type_item); QTableWidgetItem* id_item = new QTableWidgetItem("ID :"); id_item->setFlags(Qt::ItemIsEnabled); id_item->setFont(font); m_general_table->setItem(2, 0, id_item); //QTableWidgetItem* module_item = new QTableWidgetItem("modules:"); id_item->setFlags(Qt::ItemIsEnabled); id_item->setFont(font); //m_general_table->setItem(3, 0, module_item); m_name_item = new QTableWidgetItem(); m_name_item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable); m_general_table->setItem(0, 1, m_name_item); m_type_item = new QTableWidgetItem(); m_type_item->setFlags(Qt::ItemIsEnabled); m_general_table->setItem(1, 1, m_type_item); m_id_item = new QTableWidgetItem(); m_id_item->setFlags(Qt::ItemIsEnabled); m_general_table->setItem(2, 1, m_id_item); m_module_item = new QTableWidgetItem(); m_module_item->setFlags(Qt::ItemIsEnabled); m_general_table->setItem(3, 1, m_module_item); m_general_table->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); m_general_table->verticalHeader()->setDefaultSectionSize(16); // m_general_table->resizeRowsToContents(); m_general_table->resizeColumnToContents(0); m_general_table->setShowGrid(false); m_general_table->setFocusPolicy(Qt::NoFocus); m_general_table->setFrameStyle(QFrame::NoFrame); m_general_table->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_general_table->setFixedHeight(m_general_table->verticalHeader()->length()); m_content_layout->addWidget(m_general_table); m_container_layout = new QVBoxLayout(this); m_container_layout->setContentsMargins(0, 0, 0, 0); m_container_layout->setSpacing(0); m_container_layout->setAlignment(Qt::AlignTop); m_container = new QWidget(this); m_container->setLayout(m_container_layout); m_container->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); m_tree_widget = new QTreeWidget(this); m_tree_widget->setFrameStyle(QFrame::NoFrame); m_tree_widget->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents); m_tree_widget->header()->hide(); m_tree_widget->setSelectionMode(QAbstractItemView::NoSelection); m_tree_widget->setFocusPolicy(Qt::NoFocus); m_tree_widget->headerItem()->setText(0, ""); m_tree_widget->headerItem()->setText(1, ""); m_tree_widget->headerItem()->setText(2, ""); //m_tree_widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_tree_widget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_tree_widget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_tree_widget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); m_tree_widget->header()->setStretchLastSection(false); m_tree_widget->header()->setSectionResizeMode(QHeaderView::ResizeToContents); m_tree_row_layout->addWidget(m_tree_widget); m_tree_row_layout->addSpacerItem(new QSpacerItem(1,1, QSizePolicy::Expanding, QSizePolicy::Minimum)); m_container_layout->addLayout(m_tree_row_layout); connect(m_tree_widget, &QTreeWidget::itemClicked, this, &net_details_widget::on_treewidget_item_clicked); m_scroll_area = new QScrollArea(this); m_scroll_area->setFrameStyle(QFrame::NoFrame); m_scroll_area->setWidgetResizable(true); m_scroll_area->setWidget(m_container); m_content_layout->addWidget(m_scroll_area); m_src_pin = new QTreeWidgetItem(m_tree_widget); m_src_pin->setExpanded(true); m_dst_pins = new QTreeWidgetItem(m_tree_widget); m_dst_pins->setExpanded(true); connect(&g_netlist_relay, &netlist_relay::net_removed, this, &net_details_widget::handle_net_removed); connect(&g_netlist_relay, &netlist_relay::net_name_changed, this, &net_details_widget::handle_net_name_changed); connect(&g_netlist_relay, &netlist_relay::net_src_changed, this, &net_details_widget::handle_net_src_changed); connect(&g_netlist_relay, &netlist_relay::net_dst_added, this, &net_details_widget::handle_net_dst_added); connect(&g_netlist_relay, &netlist_relay::net_dst_removed, this, &net_details_widget::handle_net_dst_removed); connect(&g_netlist_relay, &netlist_relay::gate_name_changed, this, &net_details_widget::handle_gate_name_changed); } net_details_widget::~net_details_widget() { delete m_name_item; delete m_type_item; delete m_id_item; delete m_src_pin; delete m_dst_pins; } void net_details_widget::update(u32 net_id) { m_current_id = net_id; if (m_current_id == 0) return; auto n = g_netlist->get_net_by_id(net_id); if(!n) return; //get name m_name_item->setText(QString::fromStdString(n->get_name())); //get net type QString n_type = "Standard"; if (g_netlist->is_global_input_net(n)) n_type = "Input"; else if (g_netlist->is_global_output_net(n)) n_type = "Output"; m_type_item->setText(n_type); //get id m_id_item->setText(QString::number(n->get_id())); //get modules QString module_text = ""; m_module_item->setText(module_text); //get src pin for (auto item : m_src_pin->takeChildren()) delete item; auto src_pin = n->get_src(); if (src_pin.get_gate() != nullptr) { auto src_pin_type = src_pin.get_pin_type(); if (!src_pin_type.empty()) { QTreeWidgetItem* item = new QTreeWidgetItem(m_src_pin); m_src_pin->setText(0, "1 Source Pin"); item->setText(0, QString::fromStdString(src_pin_type)); item->setText(1, QChar(0x2b05)); item->setForeground(1, QBrush(QColor(114, 140, 0), Qt::SolidPattern)); item->setText(2, QString::fromStdString(src_pin.get_gate()->get_name())); item->setData(2, Qt::UserRole, src_pin.get_gate()->get_id()); } } else { m_src_pin->setText(0, "No Source Pin"); } //get destination pins for (auto item : m_dst_pins->takeChildren()) delete item; m_dst_pins->setText(0, ""); if (!g_netlist->is_global_output_net(n)) { auto dsts_pins = n->get_dsts(); QString dst_text = QString::number(dsts_pins.size()) + " Destination Pins"; if (dsts_pins.size() == 1) dst_text.chop(1); m_dst_pins->setText(0, dst_text); for (auto dst_pin : dsts_pins) { auto dst_pin_type = dst_pin.get_pin_type(); QTreeWidgetItem* item = new QTreeWidgetItem(m_dst_pins); item->setText(0, QString::fromStdString(dst_pin_type)); item->setText(1, QChar(0x27a1)); item->setForeground(1, QBrush(QColor(114, 140, 0), Qt::SolidPattern)); item->setText(2, QString::fromStdString(dst_pin.get_gate()->get_name())); item->setData(2, Qt::UserRole, dst_pin.get_gate()->get_id()); } } m_general_table->setHidden(false); m_scroll_area->setHidden(false); //m_item_deleted_label->setHidden(true); // m_tree_widget->resizeColumnToContents(0); // m_tree_widget->resizeColumnToContents(1); // m_tree_widget->resizeColumnToContents(2); } void net_details_widget::handle_item_expanded(QTreeWidgetItem* item) { Q_UNUSED(item) } void net_details_widget::handle_item_collapsed(QTreeWidgetItem* item) { Q_UNUSED(item) } void net_details_widget::on_treewidget_item_clicked(QTreeWidgetItem* item, int column) { auto gate_id = item->data(2, Qt::UserRole).toInt(); auto pin = item->text(0).toStdString(); if (m_dst_pins == item->parent() && column == 2) { std::shared_ptr<gate> clicked_gate = g_netlist->get_gate_by_id(gate_id); if (!clicked_gate) return; g_selection_relay.clear(); g_selection_relay.m_selected_gates.insert(clicked_gate->get_id()); g_selection_relay.m_focus_type = selection_relay::item_type::gate; g_selection_relay.m_focus_id = clicked_gate->get_id(); g_selection_relay.m_subfocus = selection_relay::subfocus::left; auto pins = clicked_gate->get_input_pins(); auto index = std::distance(pins.begin(), std::find(pins.begin(), pins.end(), pin)); g_selection_relay.m_subfocus_index = index; g_selection_relay.relay_selection_changed(this); } else if (m_src_pin == item->parent() && column == 2) { std::shared_ptr<gate> clicked_gate = g_netlist->get_gate_by_id(gate_id); if (!clicked_gate) return; g_selection_relay.clear(); g_selection_relay.m_selected_gates.insert(clicked_gate->get_id()); g_selection_relay.m_focus_type = selection_relay::item_type::gate; g_selection_relay.m_focus_id = clicked_gate->get_id(); g_selection_relay.m_subfocus = selection_relay::subfocus::right; auto pins = clicked_gate->get_output_pins(); auto index = std::distance(pins.begin(), std::find(pins.begin(), pins.end(), pin)); g_selection_relay.m_subfocus_index = index; g_selection_relay.relay_selection_changed(this); } } void net_details_widget::handle_net_removed(const std::shared_ptr<net> n) { if(m_current_id == n->get_id()) { m_general_table->setHidden(true); m_scroll_area->setHidden(true); } } void net_details_widget::handle_net_name_changed(const std::shared_ptr<net> n) { if(m_current_id == n->get_id()) m_name_item->setText(QString::fromStdString(n->get_name())); } void net_details_widget::handle_net_src_changed(const std::shared_ptr<net> n) { if(m_current_id == n->get_id()) update(m_current_id); } void net_details_widget::handle_net_dst_added(const std::shared_ptr<net> n, const u32 dst_gate_id) { Q_UNUSED(dst_gate_id); if(m_current_id == n->get_id()) update(m_current_id); } void net_details_widget::handle_net_dst_removed(const std::shared_ptr<net> n, const u32 dst_gate_id) { Q_UNUSED(dst_gate_id); if(m_current_id == n->get_id()) update(m_current_id); } void net_details_widget::handle_gate_name_changed(const std::shared_ptr<gate> g) { Q_UNUSED(g) if (m_current_id == 0) return; bool update_needed = false; //current net auto n = g_netlist->get_net_by_id(m_current_id); //check if current net is in netlist (m_current_id is unassigned if netlist details widget hasn't been shown once) if(!g_netlist->is_net_in_netlist(n)) return; //check if renamed gate is src of the currently shown net if(n->get_src().get_gate()->get_id() == m_current_id) update_needed = true; //check if renamed gate is a dst of the currently shown net if(!update_needed) { for(auto e : n->get_dsts()) { if(e.get_gate()->get_id() == m_current_id) { update_needed = true; break; } } } if(update_needed) update(m_current_id); }
34.216146
120
0.690464
citypw
95e361c29eb913675d83f9c703d85280ce907cba
3,840
cpp
C++
Source/GA/GAPowerUp.cpp
JackHarb89/ga2014
2d63e0f423ede52071605039a64eed4db792cb43
[ "Apache-2.0" ]
1
2015-04-09T20:19:27.000Z
2015-04-09T20:19:27.000Z
Source/GA/GAPowerUp.cpp
JackHarb89/ga2014
2d63e0f423ede52071605039a64eed4db792cb43
[ "Apache-2.0" ]
null
null
null
Source/GA/GAPowerUp.cpp
JackHarb89/ga2014
2d63e0f423ede52071605039a64eed4db792cb43
[ "Apache-2.0" ]
null
null
null
#include "GA.h" #include "GAPowerUp.h" #include "GACharacter.h" #include "GAAudioManager.h" #include "Net/UnrealNetwork.h" AGAPowerUp::AGAPowerUp(const class FPostConstructInitializeProperties& PCIP) : Super(PCIP) { IsInit = false; IsPowerUpActive = false; EffectRadius = 1000; IsAffectingAll = false; IsAffectingOne = false; // Replicate to Server / Clients bReplicates = true; bAlwaysRelevant = true; PrimaryActorTick.bCanEverTick = true; } void AGAPowerUp::Tick(float DeltaTime){ Super::Tick(DeltaTime); if(!IsInit) InitPowerUp(); ReduceCoolDown(DeltaTime); } void AGAPowerUp::InitPowerUp(){ if (Role == ROLE_Authority){ if (IsRandomPowerUp){ PowerUpType = (TEnumAsByte<EGAPowerUp::Type>) FMath::RandRange(1, 2); } IsInit = true; } } void AGAPowerUp::ReduceCoolDown(float DeltaTime){ if (Role == ROLE_Authority){ if (!IsPowerUpActive){ CurrentCoolDown -= DeltaTime; if (CurrentCoolDown <= 0){ PowerUpFinishedCoolDown(); IsPowerUpActive = true; } } } } void AGAPowerUp::OnRep_IsPowerUpActive(){ if (IsPowerUpActive){ PowerUpFinishedCoolDown(); } else{ PowerUpTaken(); for (TActorIterator<AGAAudioManager> ActorItr(GetWorld()); ActorItr; ++ActorItr){ (*ActorItr)->PowerUpTaken(this); } } } void AGAPowerUp::ReceiveActorBeginOverlap(class AActor* OtherActor){ Super::ReceiveActorBeginOverlap(OtherActor); if (OtherActor->ActorHasTag("Player") && IsPowerUpActive){ ActivatePowerUpEffect(OtherActor); } } void AGAPowerUp::ActivatePowerUpEffect(class AActor* OtherActor){ if (Role < ROLE_Authority){ ServerActivatePowerUpEffect(OtherActor); } else{ if (IsAffectingAll){ for (TActorIterator<AGACharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr){ if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){ ActorItr->HealPlayer(HealAmount); } else { ActorItr->ActivatePowerUp(PowerUpType, EffectDuration); } } } else if (IsAffectingOne){ if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){ ((AGACharacter*)OtherActor)->HealPlayer(HealAmount); } else { ((AGACharacter*)OtherActor)->ActivatePowerUp(PowerUpType, EffectDuration); } } else{ for (TActorIterator<AGACharacter> ActorItr(GetWorld()); ActorItr; ++ActorItr){ if (FVector::Dist(ActorItr->GetActorLocation(), GetActorLocation()) <= EffectRadius){ if (PowerUpType == EGAPowerUp::Type::GAHealthBoost){ ActorItr->HealPlayer(HealAmount); } else { ActorItr->ActivatePowerUp(PowerUpType, EffectDuration); } } } } CurrentCoolDown = CoolDown; IsPowerUpActive = false; PowerUpTaken(); for (TActorIterator<AGAAudioManager> ActorItr(GetWorld()); ActorItr; ++ActorItr){ (*ActorItr)->PowerUpTaken(this); } if (IsRandomPowerUp){ PowerUpType = (TEnumAsByte<EGAPowerUp::Type>) FMath::RandRange(1, 2); } } } bool AGAPowerUp::ServerActivatePowerUpEffect_Validate(class AActor* OtherActor){return true;} void AGAPowerUp::ServerActivatePowerUpEffect_Implementation(class AActor* OtherActor){ActivatePowerUpEffect(OtherActor);} // Replicates Replicated Attributes void AGAPowerUp::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const{ Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AGAPowerUp, IsAffectingOne); DOREPLIFETIME(AGAPowerUp, IsAffectingAll); DOREPLIFETIME(AGAPowerUp, IsPowerUpActive); DOREPLIFETIME(AGAPowerUp, PowerUpType); DOREPLIFETIME(AGAPowerUp, IsRandomPowerUp); DOREPLIFETIME(AGAPowerUp, HealAmount); DOREPLIFETIME(AGAPowerUp, CoolDown); DOREPLIFETIME(AGAPowerUp, EffectDuration); DOREPLIFETIME(AGAPowerUp, CurrentCoolDown); DOREPLIFETIME(AGAPowerUp, EffectRadius); }
27.234043
122
0.710156
JackHarb89
95ec51983ce99aaaf24d5de3db3adf3945136adc
1,220
cpp
C++
src/euler/046.cpp
mikf/euler
2d202c51518b9383731417ffc70cfb71980b1822
[ "Unlicense" ]
1
2015-04-11T20:52:30.000Z
2015-04-11T20:52:30.000Z
src/euler/046.cpp
mikf/euler
2d202c51518b9383731417ffc70cfb71980b1822
[ "Unlicense" ]
null
null
null
src/euler/046.cpp
mikf/euler
2d202c51518b9383731417ffc70cfb71980b1822
[ "Unlicense" ]
null
null
null
#include "euler.h" #include "math/primes.h" #include "util/range.h" #include <array> using namespace util; using namespace math; // It was proposed by Christian Goldbach that every odd composite number can be // written as the sum of a prime and twice a square. // // 9 = 7 + 2 × 1^2 // 15 = 7 + 2 × 2^2 // 21 = 3 + 2 × 3^2 // 25 = 7 + 2 × 3^2 // 27 = 19 + 2 × 2^2 // 33 = 31 + 2 × 1^2 // // It turns out that the conjecture was false. // // What is the smallest odd composite that cannot be written as the sum of a // prime and twice a square? enum { limit = 10000 }; typedef std::array<bool, limit> array_t; void fill_array(array_t & num) { int n; for(auto p : primes()) { if(p >= limit) return; for(auto i : range<1, limit>()) { n = p + 2*i*i; if(n >= limit) break; num[n] = true; } } } std::string euler046() { array_t num {false}; fill_array(num); for(std::size_t i = 3; i < limit; i += 2) { if(not num[i] and not is_prime(i)) return std::to_string(i); } return "0"; } static bool reg_ = euler::set("46", euler046);
20.677966
79
0.527869
mikf
95ecda8aca6846c47981609cdaac10e2d3d768ed
166
cc
C++
build/x86/python/m5/internal/param_InvalidateGenerator.i_init.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/python/m5/internal/param_InvalidateGenerator.i_init.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86_MESI_Two_Level/python/m5/internal/param_InvalidateGenerator.i_init.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" extern "C" { void init_param_InvalidateGenerator(); } EmbeddedSwig embed_swig_param_InvalidateGenerator(init_param_InvalidateGenerator);
20.75
82
0.813253
billionshang
95ed620dedca8c3757674b9d11e426bf4fb8c919
5,478
hpp
C++
include/assets/metadata/MeshMetadata.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
5
2018-07-03T17:05:43.000Z
2020-02-03T00:23:46.000Z
include/assets/metadata/MeshMetadata.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
include/assets/metadata/MeshMetadata.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
// The IYFEngine // // Copyright (C) 2015-2018, Manvydas Šliamka // // 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. #ifndef MESHMETADATA_HPP #define MESHMETADATA_HPP #include "assets/metadata/MetadataBase.hpp" namespace iyf { class MeshMetadata : public MetadataBase { public: inline MeshMetadata() : MetadataBase(AssetType::Mesh) {} inline MeshMetadata(FileHash fileHash, const Path& sourceAsset, FileHash sourceFileHash, bool systemAsset, const std::vector<std::string>& tags, std::uint16_t meshFormatVersion, std::uint8_t numSubMeshes, bool hasBonesVal, bool indices32Bit, std::uint32_t vertexCount, std::uint32_t indexCount, std::uint32_t skeletonKey, std::uint8_t boneCount, std::uint8_t numColorChannels, std::uint8_t numUVSets) : MetadataBase(AssetType::Mesh, fileHash, sourceAsset, sourceFileHash, systemAsset, tags, true), numSubMeshes(numSubMeshes), hasBonesVal(hasBonesVal), indices32Bit(indices32Bit), numColorChannels(numColorChannels), vertexCount(vertexCount), indexCount(indexCount), skeletonKey(skeletonKey), meshFormatVersion(meshFormatVersion), boneCount(boneCount), numUVSets(numUVSets) {} inline std::uint8_t getSubmeshCount() const { return numSubMeshes; } inline bool hasBones() const { return hasBonesVal; } inline std::uint32_t getVertexCount() const { return vertexCount; } inline std::uint32_t getIndexCount() const { return indexCount; } inline std::uint32_t getSkeletonKey() const { return skeletonKey; } inline std::uint8_t getBoneCount() const { return boneCount; } inline bool uses32BitIndices() const { return indices32Bit; } inline std::uint16_t getMeshFormatVersion() const { return meshFormatVersion; } inline std::uint8_t getColorChannelCount() const { return numColorChannels; } inline std::uint8_t getUVSetCount() const { return numUVSets; } virtual std::uint16_t getLatestSerializedDataVersion() const final override; virtual void displayInImGui() const final override; friend bool operator!=(const MeshMetadata& a, const MeshMetadata& b) { return !(a == b); } friend bool operator==(const MeshMetadata& a, const MeshMetadata& b) { return a.equals(b) && (a.numSubMeshes == b.numSubMeshes) && (a.hasBonesVal == b.hasBonesVal) && (a.indices32Bit == b.indices32Bit) && (a.numColorChannels == b.numColorChannels) && (a.vertexCount == b.vertexCount) && (a.indexCount == b.indexCount) && (a.skeletonKey == b.skeletonKey) && (a.meshFormatVersion == b.meshFormatVersion) && (a.boneCount == b.boneCount) && (a.numUVSets == b.numUVSets); } private: virtual void serializeImpl(Serializer& fw, std::uint16_t version) const final override; virtual void deserializeImpl(Serializer& fr, std::uint16_t version) final override; virtual void serializeJSONImpl(PrettyStringWriter& pw, std::uint16_t version) const final override; virtual void deserializeJSONImpl(JSONObject& jo, std::uint16_t version) final override; std::uint8_t numSubMeshes; bool hasBonesVal; bool indices32Bit; std::uint8_t numColorChannels; std::uint32_t vertexCount; std::uint32_t indexCount; std::uint32_t skeletonKey; std::uint16_t meshFormatVersion; std::uint8_t boneCount; std::uint8_t numUVSets; }; } #endif /* MESHMETADATA_HPP */
38.307692
108
0.654984
manvis
95f126b7246e8e060d8c92783e8a66ed6839b1d4
2,380
cpp
C++
src/Discovery.cpp
moostrik/ofxVimba
ba34a2da27eb4d1fe418e27b29889fb71351cf02
[ "MIT" ]
null
null
null
src/Discovery.cpp
moostrik/ofxVimba
ba34a2da27eb4d1fe418e27b29889fb71351cf02
[ "MIT" ]
null
null
null
src/Discovery.cpp
moostrik/ofxVimba
ba34a2da27eb4d1fe418e27b29889fb71351cf02
[ "MIT" ]
1
2022-01-28T15:49:19.000Z
2022-01-28T15:49:19.000Z
#include "Discovery.h" using namespace ofxVimba; Discovery::Discovery() : logger("Discovery"), system(System::getInstance()){}; Discovery::~Discovery() { stop(); } bool Discovery::start() { if (!SP_ISNULL(observer)) return true; if (!system->isAvailable()) { logger.error("Failed to set up discovery, system unavailable"); return false; } logger.setScope(reqID); SP_SET(observer, new Observer(*this, reqID)); auto error = system->getAPI().RegisterCameraListObserver(observer); if (error != VmbErrorSuccess) { logger.error("Failed to set up connection listener", error); SP_RESET(observer); return false; } logger.notice("Listening for camera to connect"); return true; } bool Discovery::stop() { if (SP_ISNULL(observer)) return true; auto error = system->getAPI().UnregisterCameraListObserver(observer); if (error != VmbErrorSuccess) { logger.error("Failed to remove connection listener", error); return false; } logger.notice("Stopped listening for connection changes"); logger.clearScope(); SP_RESET(observer); return true; } bool Discovery::restart() { return stop() && start(); } void Discovery::Observer::discover() { if (!system->isAvailable()) { logger.error( "Failed to retrieve current camera list, system is unavailable"); return; } AVT::VmbAPI::CameraPtrVector cameras; auto err = system->getAPI().GetCameras(cameras); if (err != VmbErrorSuccess) { logger.error("Failed to retrieve current camera list"); return; } // Make sure we discover all the camera's at boot for (auto &camera : cameras) { process(camera, AVT::VmbAPI::UpdateTriggerPluggedIn); } } void Discovery::Observer::process(AVT::VmbAPI::CameraPtr camera, AVT::VmbAPI::UpdateTriggerType reason) { auto device = std::make_shared<Device>(camera); // Make sure the provided filter matched the camera if (reqID != DISCOVERY_ANY_ID && device->getId() != reqID) return; // Publish the event switch (reason) { case AVT::VmbAPI::UpdateTriggerPluggedOut: ofNotifyEvent(discovery.onLost, device, &discovery); break; case AVT::VmbAPI::UpdateTriggerPluggedIn: ofNotifyEvent(discovery.onFound, device, &discovery); break; default: ofNotifyEvent(discovery.onUpdate, device, &discovery); break; } };
27.356322
78
0.680252
moostrik
95f2e59cb10f0abbdb9086c92fdbcd7542559025
3,075
cc
C++
atmosphere/measurement/measured_atmosphere_test.cc
IanMaquignaz/clear-sky-models
a8168f6b17b817c0fd76eb819f01a75be728f3b8
[ "BSD-3-Clause" ]
78
2016-12-28T05:05:03.000Z
2022-03-21T21:54:44.000Z
atmosphere/measurement/measured_atmosphere_test.cc
IanMaquignaz/clear-sky-models
a8168f6b17b817c0fd76eb819f01a75be728f3b8
[ "BSD-3-Clause" ]
4
2017-11-25T00:34:19.000Z
2020-09-30T13:02:27.000Z
atmosphere/measurement/measured_atmosphere_test.cc
IanMaquignaz/clear-sky-models
a8168f6b17b817c0fd76eb819f01a75be728f3b8
[ "BSD-3-Clause" ]
22
2017-04-25T14:36:06.000Z
2022-03-21T21:54:58.000Z
/** Copyright (c) 2015 Eric Bruneton All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "atmosphere/measurement/measured_atmosphere.h" #include <string> #include "test/test_case.h" class TestMeasuredAtmosphere : public dimensional::TestCase { public: template<typename T> TestMeasuredAtmosphere(const std::string& name, T test) : TestCase("TestMeasuredAtmosphere " + name, static_cast<Test>(test)) {} void TestLoadKiderData() { MeasuredAtmosphere atmosphere( "atmosphere/measurement/testdata", "2013-05-27", "11", "45", 1.0 * deg, 2.0* deg, "", false /* compute_azimuth_from_data */); SpectralRadiance sr1 = atmosphere.GetSkyRadiance(0 * m, 1 * deg, 2 * deg, (90.0 - 12.1151) * deg, (360.0 - 326.25) * deg)(400.0 * nm); SpectralRadiance sr2 = atmosphere.GetSkyRadiance(0 * m, 1 * deg, 2 * deg, (90.0 - 53.3665) * deg, (360.0 - 67.5) * deg)(400.0 * nm); SpectralRadiance sr3 = atmosphere.GetSkyRadiance(0 * m, 1 * deg, 2 * deg, (90.0 - 53.3665) * deg, (360.0 - 225.0) * deg)(400.0 * nm); SpectralRadiance sr4 = atmosphere.GetSkyRadiance(0 * m, 1 * deg, 2 * deg, (90.0 - 12.1151) * deg, (360.0 - 225.0) * deg)(400.0 * nm); ExpectNear(29, sr1.to(watt_per_square_meter_per_sr_per_nm), 1e-3); ExpectNear(59, sr2.to(watt_per_square_meter_per_sr_per_nm), 1e-3); ExpectNear(66, sr3.to(watt_per_square_meter_per_sr_per_nm), 1e-3); ExpectNear(20, sr4.to(watt_per_square_meter_per_sr_per_nm), 1e-3); } }; namespace { TestMeasuredAtmosphere loadkiderdata( "loadkiderdata", &TestMeasuredAtmosphere::TestLoadKiderData); } // anonymous namespace
45.895522
79
0.734959
IanMaquignaz
2501ab5ba286ec1983407e0257a9a59a3be056b0
355
hpp
C++
Code/include/OE/Misc/MatrixStack.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
21
2018-06-26T16:37:36.000Z
2022-01-11T01:19:42.000Z
Code/include/OE/Misc/MatrixStack.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
null
null
null
Code/include/OE/Misc/MatrixStack.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
3
2019-10-01T14:10:50.000Z
2021-11-19T20:30:18.000Z
#ifndef MISC_MAXTRIX_STACK_HPP #define MISC_MAXTRIX_STACK_HPP #include "OE/Misc/BaseStack.hpp" #include "OE/Math/Mat4.hpp" namespace OrbitEngine { namespace Misc { class MatrixStack : public BaseStack<Math::Mat4> { protected: Math::Mat4 nextStack(const Math::Mat4& old, const Math::Mat4& added) override { return old * added; }; }; } } #endif
22.1875
81
0.732394
mlomb
2504c1b82713e4a3e41321d0090575c5da771c5a
2,639
hpp
C++
libbrufs/include/BuildInfo.hpp
cmpsb/brufs
83a9cc296653f99042190e968a1499b3191dc8d2
[ "MIT" ]
null
null
null
libbrufs/include/BuildInfo.hpp
cmpsb/brufs
83a9cc296653f99042190e968a1499b3191dc8d2
[ "MIT" ]
null
null
null
libbrufs/include/BuildInfo.hpp
cmpsb/brufs
83a9cc296653f99042190e968a1499b3191dc8d2
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-2018 Luc Everse <luc@wukl.net> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include "Version.hpp" #include "Vector.hpp" #include "String.hpp" namespace Brufs { /** * A struct describing the library's build information, such as the version and any * compile-time configuration flags. */ struct BuildInfo { /** * The version of the library. */ Version version; /** * Any compile-time flags, including the build type and whether the build was executed from * a git repository. */ Vector<String> flags; /** * The datetime the library was built. */ String build_date; /** * The name of the most recent git tag. * If the build was not executed from a git repository, this contains an empty string. */ String git_tag; /** * The name of the git branch. * If the build was not executed from a git repository, this contains an empty string. */ String git_branch; /** * The hash of the most recent git commit. * If the build was not executed from a git repository, this contains an empty string. */ String git_commit; bool is_from_git() const { return this->flags.contains("git"); } bool is_dirty() const { return this->flags.contains("dirty"); } bool is_debug() const { return this->flags.contains("debug"); } bool is_release() const { return this->flags.contains("release"); } /** * Returns the compile-time build info of the library. * * @return the info */ static BuildInfo get(); }; }
31.416667
95
0.687761
cmpsb
25082270c7544b1f5f851861b7ba42e440180e9d
506
cpp
C++
Cpp/1642.furthest-buiding-you-can-reach.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
1
2015-12-19T23:05:35.000Z
2015-12-19T23:05:35.000Z
Cpp/1642.furthest-buiding-you-can-reach.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
Cpp/1642.furthest-buiding-you-can-reach.cpp
zszyellow/leetcode
2ef6be04c3008068f8116bf28d70586e613a48c2
[ "MIT" ]
null
null
null
class Solution { public: int furthestBuilding(vector<int>& heights, int bricks, int ladders) { priority_queue<int, vector<int>, greater<int>> pq; for (int i = 0; i < heights.size()-1; ++i) { int diff = heights[i+1] - heights[i]; if (diff > 0) pq.push(diff); if (pq.size() > ladders) { bricks -= pq.top(); pq.pop(); } if (bricks < 0) return i; } return heights.size()-1; } };
31.625
73
0.472332
zszyellow
25086c8647ad5945c4095538770a4f18427f0835
5,278
cc
C++
src/exapi/okex/RestRequest.cc
XFone/exapi
05660e8b27dfa75aa0996342ee5b6b253b09c477
[ "Apache-2.0" ]
1
2020-04-11T06:06:40.000Z
2020-04-11T06:06:40.000Z
src/exapi/okex/RestRequest.cc
XFone/exapi
05660e8b27dfa75aa0996342ee5b6b253b09c477
[ "Apache-2.0" ]
null
null
null
src/exapi/okex/RestRequest.cc
XFone/exapi
05660e8b27dfa75aa0996342ee5b6b253b09c477
[ "Apache-2.0" ]
null
null
null
/* * $Id: $ * * RestRequest class implementation for OKex * * Copyright (c) 2014-2018 Zerone.IO . All rights reserved. * * $Log: $ * */ #include "Base.h" #include "Log.h" #include "Trace.h" #include "DumpFunc.h" #include "JsonUtils.h" #include "HttpRestClient.h" #include "detail/RestClientImpl_restbed.ipp" using namespace exapi; #ifdef USE_OPENSSL #include <openssl/md5.h> #endif static std::shared_ptr<restbed::Settings> _okex_settings; std::shared_ptr<RestRequest> RestRequest::CreateBuilder(const char *domain, HTTP_PROTOCOL protocol, HTTP_METHOD method, const char *path) { const char *proto_str = ((protocol == HTTP_PROTOCOL_HTTP) ? "HTTP" : "HTTPS"); const char *method_str = ((method == METHOD_GET) ? "GET" : "POST"); auto req = std::make_shared<RestRequest>( /* domain */); req->set_host(domain); req->set_protocol(proto_str); req->set_port((protocol == HTTP_PROTOCOL_HTTPS) ? 443 : 80); //req->set_version(1.1); req->set_path(path); req->set_method(method_str); req->add_header("Host", req->get_host()); //req->add_header("Accept", "text/html,application/json,application/xml,*/*"); //req->add_header("User-Agent", "Mozilla/5.0 (exapi; rv:1.0.0) exapi"); //req->add_header("Connection", "keep-alive"); if (_okex_settings == nullptr) { auto ssl_settings = std::make_shared<restbed::SSLSettings>(); //ssl_settings->set_certificate_authority_pool(restbed::Uri( "file://certificates", restbed::Uri::Relative)); //ssl_settings->set_http_disabled(true); //ssl_settings->set_tlsv12_enabled(true); ssl_settings->set_default_workarounds_enabled(true); _okex_settings = std::make_shared<restbed::Settings>(); _okex_settings->set_ssl_settings(ssl_settings); } return req; } RestRequest & RestRequest::Init() { AddHeader("Accept", "*/*"); //AddHeader("ContentType", "application/x-www-form-urlencoded"); return *this; } std::string RestRequest::SendSync(std::shared_ptr<RestRequest> &req) { std::string body; LOGFILE(LOG_DEBUG, "SendSync: %s '%s%s'", req->get_method().c_str(), req->get_host().c_str(), req->get_path().c_str()); try { TRACE(7, "<<<\n%s\n<<<", restbed::String::to_string(restbed::Http::to_bytes(req)).c_str()); req->m_sent_time = std::chrono::steady_clock::now(); auto rsp = restbed::Http::sync(req /*, _okex_settings */); (void)ParseReponse(rsp, body); } catch (std::system_error ex) { LOGFILE(LOG_ERROR, "SendSync: throws exception '%s'", ex.what()); } return body; } int RestRequest::SendAsync(std::shared_ptr<RestRequest> &req, const std::function<void (const std::shared_ptr<restbed::Request>, const std::shared_ptr<restbed::Response>)> &callback) { LOGFILE(LOG_DEBUG, "SendAsync: %s '%s%s'", req->get_method().c_str(), req->get_host().c_str(), req->get_path().c_str()); try { TRACE(7, "<<<\n%s\n<<<", restbed::String::to_string(restbed::Http::to_bytes(req)).c_str()); req->m_sent_time = std::chrono::steady_clock::now(); restbed::Http::async(req, callback /*, _okex_settings */); } catch (std::system_error ex) { LOGFILE(LOG_ERROR, "SendAsync: throws exception '%s'", ex.what()); } return 0; } std::string & RestRequest::ParseReponse(const std::shared_ptr<restbed::Response> &rsp, std::string &body) { // TODO // StatsLatency(rsp, std::chrono::steady_clock::now(), req->m_sent_time); LOGFILE(LOG_DEBUG, "Response: HTTP/%1.1f %d %s", rsp->get_version(), rsp->get_status_code(), rsp->get_status_message().data()); TRACE_IF(8, { auto headers = rsp->get_headers(); for (const auto header : headers) { _trace_impl(8, " Header| %s: %s", header.first.data(), header.second.data()); } }); if (rsp->has_header("Transfer-Encoding")) { restbed::Http::fetch( "\r\n", rsp); // TRACE(8, " fetching delimiter"); } else { auto length = rsp->get_header("Content-Length", 0); restbed::Http::fetch(length, rsp); // TRACE(8, " fetching length %d", length); } TRACE(7, ">>>\n%s\n>>>", restbed::String::to_string(restbed::Http::to_bytes(rsp)).c_str()); rsp->get_body(body, nullptr); TRACE_IF(8, { _trace_impl(8, " Body | Length: %d", body.size()); dump_frame("", " |", body.c_str(), body.size()); }); return body; } RestRequest & RestRequest::Sign(const std::string &secret_key) { unsigned char md[MD5_DIGEST_LENGTH]; char strMd5[2 * MD5_DIGEST_LENGTH + 1]; // AddParam("secret_key", secret_key); std::string params; for (const auto qp : this->get_query_parameters()) { params += restbed::Uri::encode_parameter(qp.first) + "=" + restbed::Uri::encode_parameter(qp.second) + "&"; } params += "secret_key="; params += secret_key; (void)MD5((const unsigned char *)params.c_str(), params.size(), md); // output in upper case for (int n = 0; n < MD5_DIGEST_LENGTH; n++) { sprintf(&strMd5[n << 1], "%02X", md[n]); } AddParam("sign", strMd5); return *this; }
29.819209
124
0.616142
XFone
25131105a35af07b15da8a84e14c0c77966ac966
951
hh
C++
CaloReco/inc/CaloPulseCache.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
CaloReco/inc/CaloPulseCache.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
CaloReco/inc/CaloPulseCache.hh
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
#ifndef CaloPulseCache_HH #define CaloPulseCache_HH #include "ConditionsService/inc/CalorimeterCalibrations.hh" #include <vector> #include <string> namespace mu2e { class CaloPulseCache { public: CaloPulseCache(); ~CaloPulseCache() {}; void initialize(); double evaluate(double x); const std::vector<double>& cache() {return cache_;} double cache(int i) {return cache_.at(i);} double cacheSize() {return cacheSize_;} double deltaT() {return deltaT_;} double factor() {return factor_;} double step() {return step_;} private: std::vector<double> cache_; double cacheSize_; double deltaT_; double factor_; double step_; }; } #endif
23.195122
74
0.504732
bonventre
2515e6be572b70e77fa5b63453caeb2d6fe283de
1,216
cpp
C++
src/sampapi/0.3.7-R3-1/CAudio.cpp
kin4stat/SAMP-API
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
[ "MIT" ]
25
2020-01-02T06:13:58.000Z
2022-03-15T12:23:04.000Z
src/sampapi/0.3.7-R3-1/CAudio.cpp
kin4stat/SAMP-API
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
[ "MIT" ]
null
null
null
src/sampapi/0.3.7-R3-1/CAudio.cpp
kin4stat/SAMP-API
94eb9a0d8218038b7ea0c1132e37b6420e576dbf
[ "MIT" ]
29
2019-07-07T15:37:03.000Z
2022-02-23T18:36:16.000Z
/* This is a SAMP (0.3.7-R3) API project file. Developer: LUCHARE <luchare.dev@gmail.com> See more here https://github.com/LUCHARE/SAMP-API Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved. */ #include "sampapi/0.3.7-R3-1/CAudio.h" SAMPAPI_BEGIN_V037R3_1 int CAudio::GetRadioStation() { return ((int(__thiscall*)(CAudio*))GetAddress(0xA1AE0))(this); } void CAudio::StartRadio(int nStation) { ((void(__thiscall*)(CAudio*, int))GetAddress(0xA1B10))(this, nStation); } void CAudio::StopRadio() { ((void(__thiscall*)(CAudio*))GetAddress(0xA1B30))(this); } float CAudio::GetRadioVolume() { return ((float(__thiscall*)(CAudio*))GetAddress(0xA1B50))(this); } void CAudio::StopOutdoorAmbienceTrack() { ((void(__thiscall*)(CAudio*))GetAddress(0xA1B60))(this); } void CAudio::SetOutdoorAmbienceTrack(int nSound) { ((void(__thiscall*)(CAudio*, int))GetAddress(0xA1B70))(this, nSound); } bool CAudio::IsOutdoorAmbienceTrackDisabled() { return ((bool(__thiscall*)(CAudio*))GetAddress(0xA1C70))(this); } void CAudio::Play(int nSound, CVector location) { ((void(__thiscall*)(CAudio*, int, CVector))GetAddress(0xA1B90))(this, nSound, location); } SAMPAPI_END
25.87234
92
0.708882
kin4stat
25161296d9797000ef0ce7470c3df6f98ec192cc
1,284
cpp
C++
SLL/base.cpp
ddeflyer/CodeExamples
5f8951f394025c263a5090f4c9c6e88026a571b2
[ "Apache-2.0" ]
null
null
null
SLL/base.cpp
ddeflyer/CodeExamples
5f8951f394025c263a5090f4c9c6e88026a571b2
[ "Apache-2.0" ]
null
null
null
SLL/base.cpp
ddeflyer/CodeExamples
5f8951f394025c263a5090f4c9c6e88026a571b2
[ "Apache-2.0" ]
null
null
null
#include "base.hpp" #include <iostream> template <typename T> void SinglyLinkedList<T>::pretty_print() { std::shared_ptr<typename SinglyLinkedList<T>::element> curr_ele = this->head; while (curr_ele) { std::cout << curr_ele->value << "\n"; curr_ele = curr_ele->next; } } template <typename T> void SinglyLinkedList<T>::add_head(T& element) { auto new_head = std::make_shared<SinglyLinkedList<T>::element>(); // using the '=' copy overload if exists... new_head->value = element; if (!this->head) { // This is the first element added this->tail = new_head; } // Set the new_head's next to the old head new_head->next = this->head; this->head = new_head; } template <typename T> void SinglyLinkedList<T>::add_tail(T& element) { auto new_tail = std::make_shared<SinglyLinkedList<T>::element>(); // using the '=' copy overload if exists... new_tail->value = element; if (!this->tail) { // Since this is the first new value, set head to be the new element this->head = new_tail; } else { // Set the old tail's next to the new element this->tail->next = new_tail; } // Set the tail to the new value this->tail = new_tail; } // So that we get the templates generated template class SinglyLinkedList<int>;
22.526316
79
0.665109
ddeflyer
2516ec480e66bb2f10d8984dcbe30143d50a2130
65
cpp
C++
Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSFloatingCombatTextData.cpp
ajbetteridge/ue4-rts
d7923fa694f6b6a04d8301a65019f85512fcb359
[ "MIT" ]
3
2020-08-24T03:36:07.000Z
2021-12-28T03:40:02.000Z
Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSFloatingCombatTextData.cpp
ajbetteridge/ue4-rts
d7923fa694f6b6a04d8301a65019f85512fcb359
[ "MIT" ]
null
null
null
Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSFloatingCombatTextData.cpp
ajbetteridge/ue4-rts
d7923fa694f6b6a04d8301a65019f85512fcb359
[ "MIT" ]
1
2019-10-20T10:08:29.000Z
2019-10-20T10:08:29.000Z
#include "RTSPluginPCH.h" #include "RTSFloatingCombatTextData.h"
21.666667
38
0.815385
ajbetteridge
2518b47eee18e22b4b8c2914ad012ed02e8387e6
956
cpp
C++
src/ntfs_streams/shaker.cpp
shtirlitz-dev/ntfs_file_stream
a537efcf7e6ec9b8807c74d3bea2c82a4255719c
[ "MIT" ]
2
2020-02-25T11:00:47.000Z
2021-12-30T11:44:04.000Z
src/ntfs_streams/shaker.cpp
shtirlitz-dev/ntfs_file_stream
a537efcf7e6ec9b8807c74d3bea2c82a4255719c
[ "MIT" ]
null
null
null
src/ntfs_streams/shaker.cpp
shtirlitz-dev/ntfs_file_stream
a537efcf7e6ec9b8807c74d3bea2c82a4255719c
[ "MIT" ]
null
null
null
#include "pch.h" #include "shaker.h" #include <utility> Shaker::Shaker(const uint8_t* key20) { for (int i = 0; i < 32; ++i) enc_seq[i] = i; // shuffle uint8_t k; // current key byte int bits = 0; // remaining bits in k; for (int i = 0; i < 32; ++i) { int n = 0; if (bits >= 5) { n = k; k >>= 5; bits -= 5; } else { n = bits ? k : 0; k = *key20++; n |= (k << bits); k >>= (5 - bits); bits += 3; } n &= 0x1F; if (n != i) std::swap(enc_seq[i], enc_seq[n]); } // reverse for (int i = 0; i < 32; ++i) dec_seq[enc_seq[i]] = i; } void Shaker::encrypt(const uint8_t *in32, uint8_t *out32) // can encode in-place { uint8_t bfr[32]; memcpy(bfr, in32, 32); for (int i = 0; i < 32; ++i) out32[i] = bfr[enc_seq[i]]; } void Shaker::decrypt(const uint8_t *in32, uint8_t *out32) // can decode in-place { uint8_t bfr[32]; memcpy(bfr, in32, 32); for (int i = 0; i < 32; ++i) out32[i] = bfr[dec_seq[i]]; }
18.037736
80
0.533473
shtirlitz-dev
2519ccf5e254205ab5d2bc97f14a12a5c01e82b7
213
cpp
C++
fcpp/palindromes_count1.cpp
iddoroshenko/Team-Reference-document-ICPC-2019
6c2146e2598ccf91d556201c4672063344ba0aae
[ "MIT" ]
null
null
null
fcpp/palindromes_count1.cpp
iddoroshenko/Team-Reference-document-ICPC-2019
6c2146e2598ccf91d556201c4672063344ba0aae
[ "MIT" ]
null
null
null
fcpp/palindromes_count1.cpp
iddoroshenko/Team-Reference-document-ICPC-2019
6c2146e2598ccf91d556201c4672063344ba0aae
[ "MIT" ]
1
2020-01-10T19:53:06.000Z
2020-01-10T19:53:06.000Z
vector<int> d1 (n); int l=0, r=-1; for (int i=0; i<n; ++i) { int k = (i>r ? 0 : min (d1[l+r-i], r-i)) + 1; while (i+k < n && i-k >= 0 && s[i+k] == s[i-k]) ++k; d1[i] = k--; if (i+k > r) l = i-k, r = i+k; }
23.666667
54
0.380282
iddoroshenko
2520ed840bbe7ea76ba22ed5ff776b592118b930
6,320
cpp
C++
tests/gvar/src_pers/PersTst_src.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
13
2015-02-26T22:46:18.000Z
2020-03-24T11:53:06.000Z
tests/gvar/src_pers/PersTst_src.cpp
PacificBiosciences/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
5
2016-02-25T17:08:19.000Z
2018-01-20T15:24:36.000Z
tests/gvar/src_pers/PersTst_src.cpp
TonyBrewer/OpenHT
63898397de4d303ba514d88b621cc91367ffe2a6
[ "BSD-3-Clause" ]
12
2015-04-13T21:39:54.000Z
2021-01-15T01:00:13.000Z
#include "Ht.h" #include "PersTst.h" // Test global variable references // Test 1R/1W (same module) // 1. tst: MifWr+InstRd (tst) // 2. tst: InstWr+InstRd (tst) // 3. tst: MifWr+InstRd (tst3) // 4. tst: InstWr+InstRd (tst3) // Test 1R/1W (two modules) // 5. tst: MifWr tst2: InstRd (tst) // 6. tst: InstWr tst2: InstRd (tst) // 7. tst: MifWr tst2: InstRd (tst2) // 8. tst: InstWr tst2: InstRd (tst2) // 9. tst: MifWr tst2: InstRd (tst3) // 10. tst: InstWr tst2: InstRd (tst3) // Test 1R/2W (same module) // 11. tst: MifWr+InstWr+InstRd (tst) // 12. tst: MifWr+InstWr+InstRd (tst3) // Test 1R/2W (two modules) // 1. tst: InstWr+InstRd tst2: MifWr (tst) // 1. tst: MifWr+InstRd tst2: InstWr (tst) // 1. tst: InstWr+InstRd tst2: InstWr (tst) // 1. tst: MifWr+InstRd tst2: MifWr (tst) // 1. tst: InstWr+InstRd tst2: MifWr (tst2) // 1. tst: MifWr+InstRd tst2: InstWr (tst2) // 1. tst: InstWr+InstRd tst2: InstWr (tst2) // 1. tst: MifWr+InstRd tst2: MifWr (tst2) // 1. tst: InstWr+InstRd tst2: MifWr (tst3) // 1. tst: MifWr+InstRd tst2: InstWr (tst3) // 1. tst: InstWr+InstRd tst2: InstWr (tst3) // 1. tst: MifWr+InstRd tst2: MifWr (tst3) // Test 1R/2W (three modules) // 1. tst: InstRd tst2: InstWr tst3: InstWr (tst) // 1. tst: InstRd tst2: MifWr tst3: InstWr (tst) // 1. tst: InstRd tst2: InstWr tst3: MifWr (tst) // 1. tst: InstRd tst2: MifWr tst3: MifWr (tst) // 1. tst: InstRd tst2: InstWr tst3: InstWr (tst2) // 1. tst: InstRd tst2: MifWr tst3: InstWr (tst2) // 1. tst: InstRd tst2: InstWr tst3: MifWr (tst2) // 1. tst: InstRd tst2: MifWr tst3: MifWr (tst2) // 1. tst: InstRd tst2: InstWr tst3: InstWr (tst3) // 1. tst: InstRd tst2: MifWr tst3: InstWr (tst3) // 1. tst: InstRd tst2: InstWr tst3: MifWr (tst3) // 1. tst: InstRd tst2: MifWr tst3: MifWr (tst3) // 1. tst: InstRd tst2: InstWr tst3: InstWr (tst4) // 1. tst: InstRd tst2: MifWr tst3: InstWr (tst4) // 1. tst: InstRd tst2: InstWr tst3: MifWr (tst4) // 1. tst: InstRd tst2: MifWr tst3: MifWr (tst4) // 1. Test 2R/1W (two modules) // 1. tst: InstRd tst2: InstRd+InstWr (tst) // 1. tst: InstRd tst2: InstRd+MifWr (tst) // 1. tst: InstRd tst2: InstRd+InstWr (tst2) // 1. tst: InstRd tst2: InstRd+MifWr (tst2) // 1. tst: InstRd tst2: InstRd+InstWr (tst3) // 1. tst: InstRd tst2: InstRd+MifWr (tst3) // 1. Test 2R/1W (three modules) // 1. tst: InstRd tst2: InstRd tst3: InstWr (tst) // 1. tst: InstRd tst2: InstRd tst3: MifWr (tst) // 1. tst: InstRd tst2: InstRd tst3: InstWr (tst2) // 1. tst: InstRd tst2: InstRd tst3: MifWr (tst2) // 1. tst: InstRd tst2: InstRd tst3: InstWr (tst3) // 1. tst: InstRd tst2: InstRd tst3: MifWr (tst3) // 1. tst: InstRd tst2: InstRd tst3: InstWr (tst4) // 1. tst: InstRd tst2: InstRd tst3: MifWr (tst4) // Test 2R/2W (two modules) // 2. tst: InstWr+InstRd tst2: InstWr+InstRd (tst) // 2. tst: InstWr+InstRd tst2: MifWr+InstRd (tst) // 2. tst: MifWr+InstRd tst2: InstWr+InstRd (tst) // 2. tst: MifWr+InstRd tst2: MifWr+InstRd (tst) // 2. tst: InstWr+InstRd tst2: InstWr+InstRd (tst3) // 2. tst: InstWr+InstRd tst2: MifWr+InstRd (tst3) // 2. tst: MifWr+InstRd tst2: InstWr+InstRd (tst3) // 2. tst: MifWr+InstRd tst2: MifWr+InstRd (tst3) // Test 2R/2W (three modules) // 2. tst: InstWr+InstRd tst2: InstWr tst3: InstRd (tst) // 2. tst: InstWr+InstRd tst2: MifWr tst3: InstRd (tst) // 2. tst: MifWr+InstRd tst2: InstWr tst3: InstRd (tst) // 2. tst: MifWr+InstRd tst2: MifWr tst3: InstRd (tst) // 2. tst: InstWr+InstRd tst2: InstWr tst3: InstRd (tst2) // 2. tst: InstWr+InstRd tst2: MifWr tst3: InstRd (tst2) // 2. tst: MifWr+InstRd tst2: InstWr tst3: InstRd (tst2) // 2. tst: MifWr+InstRd tst2: MifWr tst3: InstRd (tst2) // 2. tst: InstWr+InstRd tst2: InstWr tst3: InstRd (tst4) // 2. tst: InstWr+InstRd tst2: MifWr tst3: InstRd (tst4) // 2. tst: MifWr+InstRd tst2: InstWr tst3: InstRd (tst4) // 2. tst: MifWr+InstRd tst2: MifWr tst3: InstRd (tst4) // Test 2R/2W (four modules) // 2. tst: InstWr tst2: InstWr tst3: InstRd tst4 InstRd (tst) // 2. tst: InstWr tst2: MifWr tst3: InstRd tst4 InstRd (tst) // 2. tst: MifWr tst2: InstWr tst3: InstRd tst4 InstRd (tst) // 2. tst: MifWr tst2: MifWr tst3: InstRd tst4 InstRd (tst) // 2. tst: InstWr tst2: InstWr tst3: InstRd tst4 InstRd (tst3) // 2. tst: InstWr tst2: MifWr tst3: InstRd tst4 InstRd (tst3) // 2. tst: MifWr tst2: InstWr tst3: InstRd tst4 InstRd (tst3) // 2. tst: MifWr tst2: MifWr tst3: InstRd tst4 InstRd (tst3) // 2. tst: InstWr tst2: InstWr tst3: InstRd tst4 InstRd (tst5) // 2. tst: InstWr tst2: MifWr tst3: InstRd tst4 InstRd (tst5) // 2. tst: MifWr tst2: InstWr tst3: InstRd tst4 InstRd (tst5) // 2. tst: MifWr tst2: MifWr tst3: InstRd tst4 InstRd (tst5) void CPersTst::PersTst() { if (PR_htValid) { switch (PR_htInst) { case TST_READ: { if (ReadMemBusy()) { HtRetry(); break; } P_err = 0; P_gvarAddr = 0; ReadMem_gvar(P_memAddr, P_gvarAddr, P_gvarAddr, 0); ReadMemPause(TST_CHK); } break; case TST_CHK: { if (SendCallBusy_tst2()) { HtRetry(); break; } if (GR_gvar[0].data != 0xdeadbeef00001234ULL) { HtAssert(0, 0); P_err += 1; } SendCall_tst2(TST_CALL, P_memAddr, P_err); } break; case TST_CALL: { if (SendCallBusy_tst3()) { HtRetry(); break; } SendCall_tst3(TST_RTN, P_memAddr); } break; case TST_RTN: { if (SendReturnBusy_htmain()) { HtRetry(); break; } SendReturn_htmain(P_err); } break; default: assert(0); } } }
37.176471
72
0.559019
TonyBrewer
25302d625293e3357e779dce8e54237f98337450
10,075
cc
C++
test/test_ampfat.cc
Ampless/afat
23c76c28e85941cb26d8e6ec5a12a407fa96e7b9
[ "BSD-3-Clause" ]
null
null
null
test/test_ampfat.cc
Ampless/afat
23c76c28e85941cb26d8e6ec5a12a407fa96e7b9
[ "BSD-3-Clause" ]
null
null
null
test/test_ampfat.cc
Ampless/afat
23c76c28e85941cb26d8e6ec5a12a407fa96e7b9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012-2013, Nathan Dumont * Copyright (c) 2021, Chris Häußler * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the author 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 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. * * This file is part of the Gristle FAT16/32 compatible filesystem driver. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <ampfat.hh> #include <block.hh> #include <block_drivers/block_pc.hh> #include <partition.hh> /************************************************************** * Filesystem image structure: * * root /+-> ROFILE.TXT * +-> DIR1 * +-> NORMAL.TXT *************************************************************/ /************************************************************** * Error codes to test for on fat_open(); * * [EACCES] - write on a read only file * [EISDIR] - write access to a directory * [ENAMETOOLONG] - file path is too long * [ENFILE] - too many files are open * [ENOENT] - no file with that name or empty filename * [ENOSPC] - write to a full volume * [ENOTDIR] - part of subpath is not a directory but a file * [EROFS] - write access to file on read-only filesystem * [EINVAL] - mode is not valid **************************************************************/ int test_open(int p) { int i; int v; const char *desc[] = {"Test O_WRONLY on a read only file.", "Test O_RDWR on a read only file.", "Test O_RDONLY on a read only file.", "Test O_WRONLY on a directory.", "Test O_RDWR on a directory.", "Test O_RDONLY on a directory.", "Test O_WRONLY on a missing file.", "Test O_RDWR on a missing file.", "Test O_RDONLY on a missing file.", "Test O_WRONLY on a path with file as non terminal member.", "Test O_RDWR on a path with file as non terminal member.", "Test O_RDONLY on a path with a file as non terminal member.", }; const char *filename[] = {"/ROFILE.TXT", "/ROFILE.TXT", "/ROFILE.TXT", "/DIR1", "/DIR1", "/DIR1", "/MISSING.TXT", "/MISSING.TXT", "/MISSING.TXT", "/ROFILE.TXT/NONE.TXT", "/ROFILE.TXT/NONE.TXT", "/ROFILE.TXT/NONE.TXT", }; const int flags[] = {O_WRONLY, O_RDWR, O_RDONLY, O_WRONLY, O_RDWR, O_RDONLY, O_WRONLY, O_RDWR, O_RDONLY, O_WRONLY, O_RDWR, O_RDONLY, }; const int result[] = {EACCES, EACCES, 0, EISDIR, EISDIR, 0, ENOENT, ENOENT, ENOENT, ENOTDIR, ENOTDIR, ENOTDIR, }; const int cases = 12; int rerrno; for(i=0;i<cases;i++) { printf("[%4d] Testing %s", p++, desc[i]); v = fat_open(filename[i], flags[i], 0, &rerrno); if(rerrno == result[i]) { printf(" [ ok ]\n"); } else { printf(" [fail]\n expected (%d) %s\n got (%d) %s\n", result[i], strerror(result[i]), rerrno, strerror(-rerrno)); } if(v > -1) { fat_close(v, &rerrno); if(rerrno != 0) { printf("fat_close returned %d (%s)\n", rerrno, strerror(rerrno)); } } } return p; } extern struct fat_info fatfs; extern FileS file_num[]; int main(int argc, char *argv[]) { int p = 0; int rerrno = 0; int result; int parts; uint8_t temp[512]; struct partition *part_list; if(argc < 2) { printf("Please specify a disk image to work on.\n"); exit(-2); } block_pc_set_image_name(argv[1]); // int v; printf("Running FAT tests...\n\n"); printf("[%4d] start block device emulation...", p++); printf(" %d\n", block_init()); printf("[%4d] mount filesystem, FAT32", p++); result = fat_mount(0, block_get_volume_size(), PART_TYPE_FAT32); printf(" %d\n", result); if(result != 0) { // mounting failed. // try listing the partitions block_read(0, temp); parts = read_partition_table(temp, block_get_volume_size(), &part_list); printf("Found %d valid partitions.\n", parts); if(parts > 0) { result = fat_mount(part_list[0].start, part_list[0].length, part_list[0].type); } if(result != 0) { printf("Mount failed\n"); exit(-2); } } printf("Part type = %02X\n", fatfs.type); // p = test_open(p); int fd; int i; char block_o_data[1024]; uint32_t temp_uint = 0xDEADBEEF; memset(block_o_data, 0x42, 1024); // printf("Open\n"); // fd = fat_open("/newfile.txt", O_WRONLY | O_CREAT, 0777, &rerrno); // printf("fd = %d, errno=%d (%s)\n", fd, rerrno, strerror(rerrno)); // if(fd > -1) { // printf("Write\n"); // fat_write(fd, "Hello World\n", 12, &rerrno); // printf("errno=%d (%s)\n", rerrno, strerror(rerrno)); // printf("Close\n"); // fat_close(fd, &rerrno); // printf("errno=%d (%s)\n", rerrno, strerror(rerrno)); // } // printf("Open\n"); // fd = fat_open("/newfile.png", O_WRONLY | O_CREAT, 0777, &rerrno); // printf("fd = %d, errno=%d (%s)\n", fd, rerrno, strerror(rerrno)); // if(fd > -1) { // fp = fopen("gowrong_draft1.png", "rb"); // fseek(fp, 0, SEEK_END); // len = ftell(fp); // d = malloc(len); // fseek(fp, 0, SEEK_SET); // fread(d, 1, len, fp); // fclose(fp); // printf("Write PNG\n"); // fat_write(fd, d, len, &rerrno); // printf("errno=%d (%s)\n", rerrno, strerror(rerrno)); // printf("Close\n"); // fat_close(fd, &rerrno); // printf("errno=%d (%s)\n", rerrno, strerror(rerrno)); // } printf("errno = (%d) %s\n", rerrno, strerror(rerrno)); result = fat_mkdir("/foo", 0777, &rerrno); printf("mkdir /foo: %d (%d) %s\n", result, rerrno, strerror(rerrno)); result = fat_mkdir("/foo/bar", 0777, &rerrno); printf("mkdir /foo/bar: %d (%d) %s\n", result, rerrno, strerror(rerrno)); result = fat_mkdir("/web", 0777, &rerrno); printf("mkdir /web: %d (%d) %s\n", result, rerrno, strerror(rerrno)); if((fd = fat_open("/foo/bar/file.html", O_WRONLY | O_CREAT, 0777, &rerrno)) == -1) { printf("Couldn't open file (%d) %s\n", rerrno, strerror(rerrno)); exit(-1); } for(i=0;i<20;i++) { // printf("fd.cluster = %d\n", file_num[fd].full_first_cluster); if(fat_write(fd, block_o_data, 1024, &rerrno) == -1) { printf("Error writing to new file (%d) %s\n", rerrno, strerror(rerrno)); } } if(fat_close(fd, &rerrno)) { printf("Error closing file (%d) %s\n", rerrno, strerror(rerrno)); } printf("Open directory\n"); if((fd = fat_open("/foo/bar", O_RDONLY, 0777, &rerrno)) < 0) { printf("Failed to open directory (%d) %s\n", rerrno, strerror(rerrno)); exit(-1); } struct dirent de; while(!fat_get_next_dirent(fd, &de, &rerrno)) { printf("%s\n", de.d_name); } printf("Directory read failed. (%d) %s\n", rerrno, strerror(rerrno)); if(fat_close(fd, &rerrno)) { printf("Error closing directory, (%d) %s\n", rerrno, strerror(rerrno)); } if(fat_open("/web/version.txt", O_RDONLY, 0777, &rerrno) < 0) { printf("Error opening missing file (%d) %s\n", rerrno, strerror(rerrno)); } else { printf("success! opened non existent file for reading.\n"); } printf("Trying to write a big file.\n"); if((fd = fat_open("big_file.bin", O_WRONLY | O_CREAT, 0777, &rerrno))) { printf("Error opening a file for writing.\n"); } for(i=0;i<1024 * 1024 * 10;i++) { if((i & 0xfff) == 0) printf("Written %d bytes\n", i * 4); fat_write(fd, &temp_uint, 4, &rerrno); } fat_close(fd, &rerrno); // result = fat_rmdir("/foo/bar", &rerrno); // printf("rmdir /foo/bar: %d (%d) %s\n", result, rerrno, strerror(rerrno)); // // result = fat_rmdir("/foo", &rerrno); // printf("rmdir /foo: %d (%d) %s\n", result, rerrno, strerror(rerrno)); block_pc_snapshot_all("writenfs.img"); exit(0); }
34.268707
121
0.544318
Ampless
2530948c30a58f72cc1b3a3bd113ffce47d81109
4,243
cpp
C++
src/UiCtlPanelIcon.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
14
2020-06-27T18:51:41.000Z
2022-03-30T18:20:02.000Z
src/UiCtlPanelIcon.cpp
codenamecpp/GLKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
1
2020-06-07T09:48:11.000Z
2020-06-07T09:48:11.000Z
src/UiCtlPanelIcon.cpp
codenamecpp/GrimLandsKeeper
a2207e2a459a254cbc703306ef92a09ecf714090
[ "MIT" ]
2
2020-08-27T09:38:10.000Z
2021-08-12T01:17:30.000Z
#include "pch.h" #include "UiCtlPanelIcon.h" #include "GuiButton.h" #include "GuiWidget.h" #include "GuiEvent.h" #include "GuiHelpers.h" #include "GuiPictureBox.h" #include "TexturesManager.h" #include "ScenarioDefs.h" UiCtlPanelIcon::UiCtlPanelIcon(GuiWidget* control) : mControl(control) { debug_assert(mControl); if (mControl == nullptr) return; debug_assert(mControl->mTemplateClassName == UiTemplateId_CtlPanelIcon); // bind mControl->SetActionsContext(this); mControl->SetVisible(true); mControl->SetEnabled(true); UpdateState(); // get textures if (GuiPictureBox* pictureBox = GetPictureBox("icon")) { mPicture = pictureBox->mTexture; } debug_assert(mPicture); if (GuiPictureBox* pictureBox = GetPictureBox("active_overlay")) { mActiveOverlay = pictureBox->mTexture; } debug_assert(mActiveOverlay); } UiCtlPanelIcon::~UiCtlPanelIcon() { if (mControl) // unbind { debug_assert(mControl->mActionsContext == this); mControl->SetActionsContext(nullptr); mControl = nullptr; mPicture = nullptr; mActiveOverlay = nullptr; } } void UiCtlPanelIcon::SetNullContext() { mRoomDefinition = nullptr; mObjectDefinition = nullptr; } void UiCtlPanelIcon::SetContext(RoomDefinition* roomDefinition) { SetNullContext(); mRoomDefinition = roomDefinition; if (mRoomDefinition && mRoomDefinition->mGuiIconResource.IsDefined()) { Texture2D* texture = gTexturesManager.GetTexture2D(mRoomDefinition->mGuiIconResource.mResourceName); SetPicture(texture); } debug_assert(mRoomDefinition); } void UiCtlPanelIcon::SetContext(GameObjectDefinition* objectDefinition) { SetNullContext(); mObjectDefinition = objectDefinition; if (mObjectDefinition && mObjectDefinition->mGuiIconResource.IsDefined()) { Texture2D* texture = gTexturesManager.GetTexture2D(mObjectDefinition->mGuiIconResource.mResourceName); SetPicture(texture); } debug_assert(mObjectDefinition); } void UiCtlPanelIcon::SetActiveState(bool isActive) { if (mActiveState == isActive) return; mActiveState = isActive; UpdateState(); } void UiCtlPanelIcon::SetAvailableState(bool isAvailable) { if (mAvailableState == isAvailable) return; mAvailableState = isAvailable; UpdateState(); } bool UiCtlPanelIcon::ResolveCondition(const GuiWidget* source, const cxx::unique_string& name, bool& isTrue) { static cxx::unique_string id_active("active"); static cxx::unique_string id_available("available"); if (name == id_active) { isTrue = IsActiveState(); return true; } if (name == id_available) { isTrue = IsAvailableState(); return true; } return false; } void UiCtlPanelIcon::UpdateState() { static const cxx::unique_string id_change_state("on_change_state"); if (mControl) { GuiEvent eventData(mControl, id_change_state); mControl->mActions.PerformActions(eventData); } } GuiPictureBox* UiCtlPanelIcon::GetPictureBox(const std::string& name) const { if (mControl == nullptr) return nullptr; if (GuiWidget* target = mControl->SearchForChild(name)) { GuiPictureBox* pictureBox = target->CastToWidgetClass<GuiPictureBox>(); return pictureBox; } return nullptr; } void UiCtlPanelIcon::SetPicture(Texture2D* texture) { if (mPicture == texture) return; if (GuiPictureBox* pictureBox = GetPictureBox("icon")) { pictureBox->SetTexture(texture); mPicture = pictureBox->mTexture; return; } debug_assert(false); } void UiCtlPanelIcon::SetActiveOverlay(Texture2D* texture) { if (mActiveOverlay == texture) return; if (GuiPictureBox* pictureBox = GetPictureBox("active_overlay")) { pictureBox->SetTexture(texture); mActiveOverlay = pictureBox->mTexture; return; } debug_assert(false); }
24.812865
111
0.650955
codenamecpp
2538ad693284afde82b730d555e1d289f6293119
2,523
cpp
C++
Libs/Widgets/ctkCheckableComboBoxEventPlayer.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
515
2015-01-13T05:42:10.000Z
2022-03-29T03:10:01.000Z
Libs/Widgets/ctkCheckableComboBoxEventPlayer.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
425
2015-01-06T05:28:38.000Z
2022-03-08T19:42:18.000Z
Libs/Widgets/ctkCheckableComboBoxEventPlayer.cpp
kraehlit/CTK
6557c5779d20b78f501f1fd6ce1063d0f219cca6
[ "Apache-2.0" ]
341
2015-01-08T06:18:17.000Z
2022-03-29T21:47:49.000Z
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt 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. =========================================================================*/ // QT includes #include <QDebug> // CTK includes #include "ctkCheckableComboBox.h" #include "ctkCheckableComboBoxEventPlayer.h" // ---------------------------------------------------------------------------- ctkCheckableComboBoxEventPlayer::ctkCheckableComboBoxEventPlayer(QObject *parent) : pqWidgetEventPlayer(parent) { } // ---------------------------------------------------------------------------- bool ctkCheckableComboBoxEventPlayer::playEvent(QObject *Object, const QString &Command, const QString &Arguments, bool &Error) { if(Command != "check_indexes" && Command != "uncheck_indexes") { return false; } // const int value = Arguments.toInt(); if(ctkCheckableComboBox* const object = qobject_cast<ctkCheckableComboBox*>(Object)) { if(Command == "check_indexes") { QStringList Args = Arguments.split(" "); foreach (QString Arg, Args) { const int value = Arg.toInt(); QModelIndex index = object->checkableModel()->index(value, 0); object->setCheckState(index, Qt::Checked); object->update(); } return true; } if(Command == "uncheck_indexes") { QStringList Args = Arguments.split(" "); foreach (QString Arg, Args) { const int value = Arg.toInt(); QModelIndex index = object->checkableModel()->index(value, 0); object->setCheckState(index, Qt::Unchecked); object->update(); } return true; } } qCritical() << "calling set_checkable/set_unchecked_all on unhandled type " << Object; Error = true; return true; }
30.768293
88
0.550535
kraehlit
253afc2de1e8651c9c11b46b49e5ee4496a17265
280
cpp
C++
740-delete-and-earn/740-delete-and-earn.cpp
gupabhi100/Leetcode-
a0bb35c57efb17dc2c5105287582b4f680eacf82
[ "MIT" ]
null
null
null
740-delete-and-earn/740-delete-and-earn.cpp
gupabhi100/Leetcode-
a0bb35c57efb17dc2c5105287582b4f680eacf82
[ "MIT" ]
null
null
null
740-delete-and-earn/740-delete-and-earn.cpp
gupabhi100/Leetcode-
a0bb35c57efb17dc2c5105287582b4f680eacf82
[ "MIT" ]
null
null
null
class Solution { public: int deleteAndEarn(vector<int>& nums) { vector<int> freq(100001, 0); vector<int> dp(100001, 0); for (auto i : nums) freq[i]++; dp[1] = freq[1]; for (int i=2; i<100001; i++) dp[i] = max(dp[i-2]+i*freq[i], dp[i-1]); return dp[100000]; } };
18.666667
44
0.575
gupabhi100
25412176c36e9d7bf64723913dc8f9eeafe78540
1,389
hpp
C++
packages/monte_carlo/collision/native/src/MonteCarlo_CoherentScatteringDistributionFactory.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/collision/native/src/MonteCarlo_CoherentScatteringDistributionFactory.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/collision/native/src/MonteCarlo_CoherentScatteringDistributionFactory.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_CoherentScatteringDistributionFactory.hpp //! \author Alex Robinson //! \brief The coherent scattering distribution factory base class decl. //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_COHERENT_SCATTERING_DISTRIBUTION_FACTORY_HPP #define MONTE_CARLO_COHERENT_SCATTERING_DISTRIBUTION_FACTORY_HPP // Trilinos Includes #include <Teuchos_RCP.hpp> // FRENSIE Includes #include "MonteCarlo_CoherentScatteringDistribution.hpp" namespace MonteCarlo{ //! The coherent scattering distribution factory base class class CoherentScatteringDistributionFactory { public: //! Create a Thompson distribution static void createThompsonDistribution( Teuchos::RCP<const CoherentScatteringDistribution>& coherent_distribution ); private: // The default Thompson distribution static Teuchos::RCP<const CoherentScatteringDistribution> s_thompson_distribution; }; } // end MonteCarlo namespace #endif // end MONTE_CARLO_COHERENT_SCATTERING_DISTRIBUTION_FACTORY_HPP //---------------------------------------------------------------------------// // end MonteCarlo_CoherentScatteringDistributionFactory.hpp //---------------------------------------------------------------------------//
30.866667
79
0.614831
lkersting
8583c6e22ef47140b1e2ff3e088c8453326c855c
11,720
hpp
C++
include/sdl2pp/window.hpp
NathanSWard/sdl2pp
fdf9b009f845957451f16a463c3bb03f890a4d16
[ "Unlicense" ]
null
null
null
include/sdl2pp/window.hpp
NathanSWard/sdl2pp
fdf9b009f845957451f16a463c3bb03f890a4d16
[ "Unlicense" ]
null
null
null
include/sdl2pp/window.hpp
NathanSWard/sdl2pp
fdf9b009f845957451f16a463c3bb03f890a4d16
[ "Unlicense" ]
null
null
null
#pragma once #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #include "enums.hpp" #include "shapes.hpp" #include "surface.hpp" #include "util.hpp" #include <array> #include <cstdint> #include <optional> #include <span> #include <string_view> namespace sdl2 { /** * @brief A wrapper around an SDL_Window structure. */ class window { SDL_Window* window_; public: /** * @brief Explicit constructor for the SDL2 C API. * @param window The SDL_Window to take ownership of. */ constexpr explicit window(SDL_Window* window) noexcept : window_(window) {} /** * @brief Copy constructor deleted. */ window(window const&) = delete; /** * @brief Copy assignment deleted. */ window& operator=(window const&) = delete; /** * @brief Move assignment deleted. */ window& operator=(window&&) = delete; /** * @brief Move constructor * @param other The window object to move in this window. */ constexpr window(window&& other) noexcept : window_(std::exchange(other.window_, nullptr)) {} /** * @brief Construct a window. * @param title The title of the window. * @param xy The position of the window. * @param wh The width/height of the window. * @param flgs The window flag specifications. */ window(null_term_string title, xy<int> xy, wh<int> wh, window_flags flgs) noexcept; /** * @brief The destructor. */ ~window() noexcept; /** * @brief Destroy the underlying window object. * @note Accessing the window after this functional call is UB. */ void destroy() noexcept; /** * @brief Get a pointer to the underlying SDL representation. * @return A pointer to the underlying SDL_Window. */ constexpr auto native_handle() const noexcept { return window_; } /** * @brief Checks if the window is in a valid state. * @return True if valid, false if not. */ constexpr explicit operator bool() const noexcept { return window_ != nullptr; } /** * @brief Checks if the window is in a valid state. * @return True if valid, false if not. */ constexpr bool is_ok() const noexcept { return window_ != nullptr; } /** * @brief An xy position denoting a centered window. */ static constexpr xy<int> pos_centered{SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED}; /** * @brief An xy position denoting an undefined window position. */ static constexpr xy<int> pos_undefined{SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED}; /** * @brief Construct a window from another. * @param other The window object to copy data from. * @return An optional window if successfully created. * @note This copy operation has an explicit name to avoid unnecessary copying due to a copy constructor call. */ static window copy(window const& other) noexcept; /** * @brief Gets the size of the window's borders. * @return An optional borders size if this is supported on the platform. */ std::optional<tlbr<int>> borders_size() noexcept; /** * @brief Get the brightness (gamma multiplier) of the window. * @return The current brightness of the window. */ float brightness() const noexcept; //SDL_GetWindowData /** * @brief The display index of the window. * @return The index or -1 on error. */ int display_index() const noexcept; /** * @brief Get the display mode to use when a window is visible at fullscreen. * @return An optional SDL_DisplayMode if the call succeeded. */ std::optional<SDL_DisplayMode> display_mode() const noexcept; /** * @brief Get the window flags used to create this window. * @return The window flags enum. */ window_flags flags() const noexcept; // SDL_GetWindowFromID /** * @brief Get the gamma ramp for the display that owns this window. * @return rgb<> struct containing the translation tables for thier respective channels. */ rgb<std::array<std::uint16_t, 256>> gamma_ramp() const noexcept; /** * @brief Check if this window is grabbed. * @return A bool denoting if this window is grabbed. */ bool is_grabbed() const noexcept; /** * @brief Get this window's id. * @return The window's id. */ std::uint32_t id() const noexcept; /** * @brief Get the maximum size of the window. * @return The maximum size of the window. */ wh<int> maximum_size() const noexcept; /** * @brief Get the minimum size of the window. * @return The minimum size of the window. */ wh<int> minimum_size() const noexcept; /** * @brief Get the opacticy of the window. * @return The opacity of the window. */ float opacity() const noexcept; /** * @brief The the pixel format of the window. * @return the pixel format of the window. */ pixel_format_enum pixel_format() const noexcept; /** * @brief The the current position of the window. * @return The x/y cords of the window. */ xy<int> position() const noexcept; /** * @brief Get the current size of the window. * @return The width and height of the window. */ wh<int> size() const noexcept; // SDL_GetWindowSurface - TODO /** * @brief Get the current title of the window. * @return The title of the window. */ std::string_view title() const noexcept; /** * @brief Get driver specific information about the window. * @return A SLD_SysWMinfo struct or an empty optional if this operation is not supported. */ std::optional<SDL_SysWMinfo> wm_info() const noexcept; /** * @brief Hide the window. */ void hide() noexcept; /** * @brief Maximize the size of the window. */ void maximize() noexcept; /** * @brief Minimize the size of the window. */ void minimize() noexcept; /** * @brief Raise this window above other windows and set the input focus. */ void raise() noexcept; /** * @brief Restores the size and position of a minimized/maximized window. */ void restore() noexcept; /** * @brief Change the border state of a window. * @param borderer A bool denoting if the window should be bordered. */ void set_bordered(bool const bordered) noexcept; /** * @brief Change the brightness of a window. * @param brightness The new brightness values for the window. */ bool set_brightness(float const brightness) noexcept; // SDL_SetWindowData /** * @brief Sets the display mode to use when the window is at fullscreen. * @param dm The SDL_DisplayMode strut denoting the window's new display mode. * @return True if succeeded, false if failed. */ bool set_display_mode(SDL_DisplayMode const& dm) noexcept; /** * @brief Set the window's display mode to use the current dimensions and the desktop refresh rate. * @return True if succeeded, false if failed. */ bool set_display_mode() noexcept; /** * @brief Set the window's fullscreen property. * @param flags The fullscreen enum type. * @return True if succeeded, false if failed. */ bool set_fullscreen(fullscreen_flags const flags) noexcept; /** * @brief Set the gamma ramp for the display that owns this window. * @param r The translation table for the red channel. * @param g The translation table for the green channel. * @param b The translation table for the blue channel. * @return True if succeeded, false if failed. */ bool set_gamma_ramp(std::span<std::uint16_t const, 256> const r, std::span<std::uint16_t const, 256> const g, std::span<std::uint16_t const, 256> const b) noexcept; /** * @brief Change the grabbed state of the window. * @param grabbed The bool denoting if the window should be grabbed. */ void set_grabbed(bool grabbed = true) noexcept; /** * @brief Provides a callback that decides if a window region has special properties. * @param fn A callable triggered when doing a hit-test. * @return True if succeeded, false if failed. * @note Function must have the signature `SDL_HitTestResult(window&, point<int>)` */ bool set_hit_test(function_ref<SDL_HitTestResult(window&, point<int>)> const fn) noexcept; /** * @brief Provides a callback that decides if a window region has special properties. * @param fn A callable triggered when doing a hit-test. * @return True if succeeded, false if failed. * @note Function must have the signature `SDL_HitTestResult(window const&, point<int>)` */ bool set_hit_test(function_ref<SDL_HitTestResult(window const&, point<int>)> const fn) noexcept; /** * @brief Set the icon for a window. * @param s A surface to use as the icon. */ void set_icon(surface const& s) noexcept; /** * @brief Explicitly set input focus to this window. * @return True if succeeded, false if failed. */ bool set_input_focus() noexcept; /** * @brief Set the maximum size of the window. * @param wh The maximum size. */ void set_maximum_size(wh<int> wh) noexcept; /** * @brief Set the minimum size of the window. * @param wh The minimum size. */ void set_minimum_size(wh<int> const wh) noexcept; /** * @brief Set this window as a modal for another window. * @param parent The parent window for this window. * @return True if succeeded, false if failed. */ bool set_modal_for(window const& parent) noexcept; /** * @brief Set the opacity of the window. * @param opacity The new opacity value. * @return True if succeeded, false if failed. * @note The provided opacity is clamped between (0.f, 1.f) */ bool set_opacity(float const opacity) noexcept; /** * @brief Set the position of the window. * @param xy The new position. */ void set_position(xy<int> const xy) noexcept; /** * @brief Set if the window is resizable. * @param resizable A bool denoting if the window is resizable. */ void set_resizable(bool const resizable) noexcept; /** * @brief Set the current size of the window. * @param wh The new size. */ void set_size(wh<int> const wh) noexcept; /** * @brief Set the title of the window. * @param title The window's new title. */ void set_title(null_term_string const title) noexcept; /** * @brief Displays a simple modal message box. * @param flags The mesage box enum flags. * @param title Message box's title. * @param message Message box's message. * @return True if succeeded, false if failed. */ bool show_simple_message_box(message_box_flags const flags, null_term_string const title, null_term_string const message) noexcept; /** * @brief Shows the window. */ void show() noexcept; /** * @brief Copies the dinow surface to the screen. * @return True if succeeded, false if failed. */ bool update_surface() noexcept; /** * @brief Copy areas of the window surface to the screen. * @param rects The areas of the surface to copy. * @return True if succeeded, false if failed. */ bool update_surface_rects(std::span<rect<int> const> const rects) noexcept; }; } // namespace sdl2
29.59596
135
0.637372
NathanSWard
8589c6b3475d6201acddd28a2c98a5662b2a1c77
6,505
cpp
C++
qws/src/gui/QColorDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
42
2015-02-16T19:29:16.000Z
2021-07-25T11:09:03.000Z
qws/src/gui/QColorDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
1
2017-11-23T12:49:25.000Z
2017-11-23T12:49:25.000Z
qws/src/gui/QColorDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
5
2015-10-15T21:25:30.000Z
2017-11-22T13:18:24.000Z
///////////////////////////////////////////////////////////////////////////// // // File : QColorDialog.cpp // Copyright : (c) David Harley 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:02:04 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <wchar.h> #include <qtc_wrp_core.h> #include <qtc_wrp_gui.h> #include <qtc_subclass.h> #ifndef dhclassheader #define dhclassheader #include <qpointer.h> #include <dynamicqhandler.h> #include <DhOther_gui.h> #include <DhAutohead_gui.h> #endif extern "C" { QTCEXPORT(unsigned int,qtc_QColorDialog_customColor)(int x1) { return (unsigned int) QColorDialog::customColor((int)x1); } QTCEXPORT(int,qtc_QColorDialog_customCount)() { return (int) QColorDialog::customCount(); } QTCEXPORT(void*,qtc_QColorDialog_getColor)() { QColor * tc = new QColor(QColorDialog::getColor()); return (void*)(tc); } QTCEXPORT(void*,qtc_QColorDialog_getColor1)(void* x1) { QColor * tc = new QColor(QColorDialog::getColor((const QColor&)(*(QColor*)x1))); return (void*)(tc); } QTCEXPORT(void*,qtc_QColorDialog_getColor2)(void* x1, void* x2) { QObject*tx2 = *((QPointer<QObject>*)x2); if ((tx2!=NULL)&&((QObject *)tx2)->property(QTC_PROP).isValid()) tx2 = ((QObject*)(((qtc_DynamicQObject*)tx2)->parent())); QColor * tc = new QColor(QColorDialog::getColor((const QColor&)(*(QColor*)x1), (QWidget*)tx2)); return (void*)(tc); } QTCEXPORT(unsigned int,qtc_QColorDialog_getRgba)() { return (unsigned int) QColorDialog::getRgba(); } QTCEXPORT(unsigned int,qtc_QColorDialog_getRgba1)(unsigned int x1) { return (unsigned int) QColorDialog::getRgba((QRgb)x1); } QTCEXPORT(void,qtc_QColorDialog_setCustomColor)(int x1, unsigned int x2) { return (void) QColorDialog::setCustomColor((int)x1, (QRgb)x2); } QTCEXPORT(void,qtc_QColorDialog_setStandardColor)(int x1, unsigned int x2) { return (void) QColorDialog::setStandardColor((int)x1, (QRgb)x2); } QTCEXPORT(void,qtc_QColorDialog_addAction)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QColorDialog*)tx0)->addAction((QAction*)tx1); } QTCEXPORT(void,qtc_QColorDialog_move)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->move((const QPoint&)(*(QPoint*)x1)); } QTCEXPORT(void,qtc_QColorDialog_move_qth)(void* x0, int x1_x, int x1_y) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QPoint tx1(x1_x, x1_y); ((QColorDialog*)tx0)->move(tx1); } QTCEXPORT(void,qtc_QColorDialog_move1)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->move((int)x1, (int)x2); } QTCEXPORT(void,qtc_QColorDialog_repaint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->repaint(); } QTCEXPORT(void,qtc_QColorDialog_repaint1)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->repaint((const QRegion&)(*(QRegion*)x1)); } QTCEXPORT(void,qtc_QColorDialog_repaint2)(void* x0, int x1, int x2, int x3, int x4) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->repaint((int)x1, (int)x2, (int)x3, (int)x4); } QTCEXPORT(void,qtc_QColorDialog_resize)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->resize((const QSize&)(*(QSize*)x1)); } QTCEXPORT(void,qtc_QColorDialog_resize_qth)(void* x0, int x1_w, int x1_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tx1(x1_w, x1_h); ((QColorDialog*)tx0)->resize(tx1); } QTCEXPORT(void,qtc_QColorDialog_resize1)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->resize((int)x1, (int)x2); } QTCEXPORT(void,qtc_QColorDialog_setGeometry)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->setGeometry((const QRect&)(*(QRect*)x1)); } QTCEXPORT(void,qtc_QColorDialog_setGeometry_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QRect tx1(x1_x, x1_y, x1_w, x1_h); ((QColorDialog*)tx0)->setGeometry(tx1); } QTCEXPORT(void,qtc_QColorDialog_setGeometry1)(void* x0, int x1, int x2, int x3, int x4) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->setGeometry((int)x1, (int)x2, (int)x3, (int)x4); } QTCEXPORT(void,qtc_QColorDialog_setMouseTracking)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QColorDialog*)tx0)->setMouseTracking((bool)x1); } }
40.65625
124
0.655496
keera-studios
858a4f4519b745398dee15976fe27c8611c258fb
11,383
hpp
C++
libraries/protocol/include/deip/protocol/config.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
1
2021-08-16T12:44:43.000Z
2021-08-16T12:44:43.000Z
libraries/protocol/include/deip/protocol/config.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
null
null
null
libraries/protocol/include/deip/protocol/config.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
2
2021-08-16T12:44:46.000Z
2021-12-31T17:09:45.000Z
/* * Copyright (c) 2016 Steemit, Inc., and contributors. */ // clang-format off #pragma once #define DAYS_TO_SECONDS(X) (60*60*24*X) #define DEIP_BLOCKCHAIN_VERSION ( version(0, 1, 0) ) #define DEIP_BLOCKCHAIN_HARDFORK_VERSION ( hardfork_version( DEIP_BLOCKCHAIN_VERSION ) ) #define DEIP_ADDRESS_PREFIX "DEIP" #define DEIP_MIN_AUTH_THRESHOLD uint16_t(1) #ifdef IS_TEST_NET #define DEIP_SYMBOL (uint64_t(3) | (uint64_t('T') << 8) | (uint64_t('E') << 16) | (uint64_t('S') << 24) | (uint64_t('T') << 32) | (uint64_t('S') << 40)) ///< DEIP with 3 digits of precision #define DEIP_USD_SYMBOL (uint64_t(2) | (uint64_t('U') << 8) | (uint64_t('S') << 16) | (uint64_t('D') << 24)) ///< USD MOCK with 2 digits of precision #define DEIP_CASHOUT_WINDOW_SECONDS (60*60) /// 1 hr #define DEIP_UPVOTE_LOCKOUT (fc::minutes(5)) #define DEIP_OWNER_AUTH_RECOVERY_PERIOD fc::seconds(60) #define DEIP_ACCOUNT_RECOVERY_REQUEST_EXPIRATION_PERIOD fc::seconds(12) #define DEIP_OWNER_UPDATE_LIMIT fc::seconds(0) #define DEIP_OWNER_AUTH_HISTORY_TRACKING_START_BLOCK_NUM 1 #define DEIP_REWARDS_INITIAL_SUPPLY asset( 1000000, DEIP_SYMBOL ) #define DEIP_REWARDS_INITIAL_SUPPLY_PERIOD_IN_DAYS 5 #define DEIP_GUARANTED_REWARD_SUPPLY_PERIOD_IN_DAYS 2 #define DEIP_REWARD_INCREASE_THRESHOLD_IN_DAYS 3 #define DEIP_ADJUST_REWARD_PERCENT 5 #define DEIP_HARDFORK_REQUIRED_WITNESSES 1 #define DEIP_REGULAR_CONTENT_ACTIVITY_WINDOW_DURATION 300 #define DEIP_FINAL_RESULT_ACTIVITY_WINDOW_DURATION 600 #define DEIP_BREAK_BETWEEN_REGULAR_ACTIVITY_ROUNDS_DURATION 300 #define DEIP_BREAK_BETWEEN_FINAL_ACTIVITY_ROUNDS_DURATION 600 #else // IS LIVE DEIP NETWORK #define DEIP_SYMBOL (uint64_t(3) | (uint64_t('D') << 8) | (uint64_t('E') << 16) | (uint64_t('I') << 24) | (uint64_t('P') << 32)) ///< DEIP with 3 digits of precision #define DEIP_USD_SYMBOL (uint64_t(2) | (uint64_t('U') << 8) | (uint64_t('S') << 16) | (uint64_t('D') << 24)) ///< USD MOCK with 2 digits of precision #define DEIP_CASHOUT_WINDOW_SECONDS (60*60*24*7) /// 7 days #define DEIP_UPVOTE_LOCKOUT (fc::hours(12)) #define DEIP_OWNER_AUTH_RECOVERY_PERIOD fc::days(30) #define DEIP_ACCOUNT_RECOVERY_REQUEST_EXPIRATION_PERIOD fc::days(1) #define DEIP_OWNER_UPDATE_LIMIT fc::minutes(60) #define DEIP_OWNER_AUTH_HISTORY_TRACKING_START_BLOCK_NUM 3186477 #define DEIP_REWARDS_INITIAL_SUPPLY asset( 2300000000, DEIP_SYMBOL ) #define DEIP_REWARDS_INITIAL_SUPPLY_PERIOD_IN_DAYS (2 * 365) #define DEIP_GUARANTED_REWARD_SUPPLY_PERIOD_IN_DAYS 30 #define DEIP_REWARD_INCREASE_THRESHOLD_IN_DAYS 100 #define DEIP_ADJUST_REWARD_PERCENT 5 #define DEIP_HARDFORK_REQUIRED_WITNESSES 17 // 17 of the 21 dpos witnesses (20 elected and 1 virtual time) required for hardfork. This guarantees 75% participation on all subsequent rounds. #endif #define DEIP_MIN_ACCOUNT_CREATION_FEE asset( 0, DEIP_SYMBOL ) #define DEIP_MIN_DISCIPLINE_SUPPLY_PER_BLOCK 1 #define DEIP_BLOCK_INTERVAL 3 #define DEIP_BLOCKS_PER_YEAR (365*24*60*60/DEIP_BLOCK_INTERVAL) #define DEIP_BLOCKS_PER_DAY (24*60*60/DEIP_BLOCK_INTERVAL) #define DEIP_BLOCKS_PER_WEEK (DEIP_BLOCKS_PER_DAY * 7) #define DEIP_BLOCKS_PER_HOUR (60*60/DEIP_BLOCK_INTERVAL) #define DEIP_START_VESTING_BLOCK (DEIP_BLOCKS_PER_DAY * 7) #define DEIP_START_MINER_VOTING_BLOCK (DEIP_BLOCKS_PER_DAY * 30) #define DEIP_NUM_INIT_DELEGATES 1 #define DEIP_MAX_VOTED_WITNESSES 20 #define DEIP_MAX_RUNNER_WITNESSES 1 #define DEIP_MAX_WITNESSES (DEIP_MAX_VOTED_WITNESSES+DEIP_MAX_RUNNER_WITNESSES) #define DEIP_WITNESS_MISSED_BLOCKS_THRESHOLD DEIP_BLOCKS_PER_DAY/2 #define DEIP_MAX_TIME_UNTIL_EXPIRATION (60*60) // seconds, aka: 1 hour #define DEIP_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*365*3) // 3 years TEMP #define DEIP_MAX_PROPOSAL_NESTED_STAGE 3 #define DEIP_RECENT_ENTITY_LIFETIME_SEC (DEIP_MAX_PROPOSAL_NESTED_STAGE * DEIP_MAX_PROPOSAL_LIFETIME_SEC) + DEIP_BLOCK_INTERVAL // must be greater than TaPoS check round #define DEIP_MAX_MEMO_SIZE 2048 #define DEIP_MAX_TITLE_SIZE 255 #define DEIP_MAX_PROXY_RECURSION_DEPTH 4 #define DEIP_COMMON_TOKENS_WITHDRAW_INTERVALS_PRE_HF_16 104 #define DEIP_COMMON_TOKENS_WITHDRAW_INTERVALS 13 #define DEIP_COMMON_TOKENS_WITHDRAW_INTERVAL_SECONDS (60*60*24*7) /// 1 week per interval #define DEIP_MAX_WITHDRAW_ROUTES 10 #define DEIP_SAVINGS_WITHDRAW_TIME (fc::days(3)) #define DEIP_SAVINGS_WITHDRAW_REQUEST_LIMIT 100 #define DEIP_VOTE_REGENERATION_SECONDS (5*60*60*24) // 5 day #define DEIP_MAX_VOTE_CHANGES 5 #define DEIP_REVERSE_AUCTION_WINDOW_SECONDS (60*30) /// 30 minutes #define DEIP_MIN_VOTE_INTERVAL_SEC 3 #define DEIP_VOTE_DUST_THRESHOLD (50000000) #define DEIP_MIN_REPLY_INTERVAL (fc::seconds(20)) // 20 seconds #define DEIP_MAX_ACCOUNT_WITNESS_VOTES 30 #define DEIP_PERCENT_DECIMALS 2 #define DEIP_100_PERCENT 10000 #define DEIP_1_PERCENT (DEIP_100_PERCENT/100) #define DEIP_1_TENTH_PERCENT (DEIP_100_PERCENT/1000) #define DEIP_REVIEW_REQUIRED_POWER_PERCENT (0 * DEIP_1_PERCENT) #define DEIP_REVIEW_VOTE_SPREAD_DENOMINATOR 10 #define DEIP_LIMIT_DISCIPLINE_SUPPLIES_PER_GRANTOR 5 #define DEIP_LIMIT_DISCIPLINE_SUPPLIES_LIST_SIZE DEIP_LIMIT_DISCIPLINE_SUPPLIES_PER_GRANTOR #define DEIP_REVIEWER_INFLUENCE_FACTOR double(1.0) #define DEIP_CURATOR_INFLUENCE_FACTOR double(1.0) #define DEIP_CURATOR_INFLUENCE_BONUS int64_t(10) // demo #define DEIP_INFLATION_RATE_START_PERCENT (978) // Fixes block 7,000,000 to 9.5% #define DEIP_INFLATION_RATE_STOP_PERCENT (95) // 0.95% #define DEIP_INFLATION_NARROWING_PERIOD (250000) // Narrow 0.01% every 250k blocks #define DEIP_CONTRIBUTION_REWARD_PERCENT (97*DEIP_1_PERCENT) //97% of inflation, 9.215% inflation #define DEIP_REVIEW_REWARD_POOL_SHARE_PERCENT (5*DEIP_1_PERCENT) #define DEIP_CURATORS_REWARD_SHARE_PERCENT (5*DEIP_1_PERCENT) #define DEIP_REFERENCES_REWARD_SHARE_PERCENT (10*DEIP_1_PERCENT) #define DEIP_BANDWIDTH_CHECK_DISABLED true #define DEIP_BANDWIDTH_AVERAGE_WINDOW_SECONDS (60*60*24*7) ///< 1 week #define DEIP_BANDWIDTH_PRECISION (uint64_t(1000000)) ///< 1 million #define DEIP_MAX_RESERVE_RATIO (20000) #define DEIP_CREATE_ACCOUNT_WITH_DEIP_MODIFIER 30 #define DEIP_CREATE_ACCOUNT_DELEGATION_RATIO 5 #define DEIP_CREATE_ACCOUNT_DELEGATION_TIME fc::days(30) #define DEIP_MINING_REWARD asset( 1000, DEIP_SYMBOL ) #define DEIP_MIN_CONTENT_REWARD DEIP_MINING_REWARD #define DEIP_MIN_CURATE_REWARD DEIP_MINING_REWARD #define DEIP_MIN_PRODUCER_REWARD DEIP_MINING_REWARD #define DEIP_MIN_POW_REWARD DEIP_MINING_REWARD #define DEIP_RECENT_RSHARES_DECAY_RATE (fc::days(15)) // note, if redefining these constants make sure calculate_claims doesn't overflow // 5ccc e802 de5f // int(expm1( log1p( 1 ) / BLOCKS_PER_YEAR ) * 2**DEIP_APR_PERCENT_SHIFT_PER_BLOCK / 100000 + 0.5) // we use 100000 here instead of 10000 because we end up creating an additional 9x for vesting #define DEIP_APR_PERCENT_MULTIPLY_PER_BLOCK ( (uint64_t( 0x5ccc ) << 0x20) \ | (uint64_t( 0xe802 ) << 0x10) \ | (uint64_t( 0xde5f ) ) \ ) // chosen to be the maximal value such that DEIP_APR_PERCENT_MULTIPLY_PER_BLOCK * 2**64 * 100000 < 2**128 #define DEIP_APR_PERCENT_SHIFT_PER_BLOCK 87 #define DEIP_APR_PERCENT_MULTIPLY_PER_ROUND ( (uint64_t( 0x79cc ) << 0x20 ) \ | (uint64_t( 0xf5c7 ) << 0x10 ) \ | (uint64_t( 0x3480 ) ) \ ) #define DEIP_APR_PERCENT_SHIFT_PER_ROUND 83 // We have different constants for hourly rewards // i.e. hex(int(math.expm1( math.log1p( 1 ) / HOURS_PER_YEAR ) * 2**DEIP_APR_PERCENT_SHIFT_PER_HOUR / 100000 + 0.5)) #define DEIP_APR_PERCENT_MULTIPLY_PER_HOUR ( (uint64_t( 0x6cc1 ) << 0x20) \ | (uint64_t( 0x39a1 ) << 0x10) \ | (uint64_t( 0x5cbd ) ) \ ) // chosen to be the maximal value such that DEIP_APR_PERCENT_MULTIPLY_PER_HOUR * 2**64 * 100000 < 2**128 #define DEIP_APR_PERCENT_SHIFT_PER_HOUR 77 // These constants add up to GRAPHENE_100_PERCENT. Each GRAPHENE_1_PERCENT is equivalent to 1% per year APY // *including the corresponding 9x vesting rewards* #define DEIP_CONTENT_APR_PERCENT 3875 #define DEIP_PRODUCER_APR_PERCENT 750 #define DEIP_POW_APR_PERCENT 750 #define DEIP_MIN_PAYOUT (asset(5, DEIP_SYMBOL)) #define DEIP_MIN_ACCOUNT_NAME_LENGTH 3 #define DEIP_MAX_ACCOUNT_NAME_LENGTH 40 #define DEIP_MAX_WITNESS_URL_LENGTH 2048 #define DEIP_MAX_SHARE_SUPPLY int64_t(1000000000000000ll) #define DEIP_MAX_SIG_CHECK_DEPTH 2 #define DEIP_MAX_TRANSACTION_SIZE (1024*64) #define DEIP_MIN_BLOCK_SIZE_LIMIT (DEIP_MAX_TRANSACTION_SIZE) #define DEIP_MAX_BLOCK_SIZE (DEIP_MAX_TRANSACTION_SIZE*DEIP_BLOCK_INTERVAL*2000) #define DEIP_MAX_FEED_AGE_SECONDS (60*60*24*7) // 7 days #define DEIP_MIN_FEEDS (DEIP_MAX_WITNESSES/3) /// protects the network from conversions before price has been established #define DEIP_MIN_UNDO_HISTORY 10 #define DEIP_MAX_UNDO_HISTORY 10000 #define DEIP_EXPERTISE_CLAIM_AMOUNT 5000 #define DEIP_DEFAULT_EXPERTISE_AMOUNT int64_t(2500) #define DEIP_MIN_TRANSACTION_EXPIRATION_LIMIT (DEIP_BLOCK_INTERVAL * 5) // 5 transactions per block #define DEIP_IRREVERSIBLE_THRESHOLD (75 * DEIP_1_PERCENT) #define VIRTUAL_SCHEDULE_LAP_LENGTH ( fc::uint128::max_value() ) #define DEIP_REGISTRAR_ACCOUNT_NAME "regacc" #define DEIP_INITIAL_DELEGATE_ACCOUNT_NAME "initdelegate" #define DEIP_MIN_NUMBER_OF_REVIEW_CRITERIAS 3 #define DEIP_MIN_REVIEW_CRITERIA_SCORE 1 #define DEIP_MAX_REVIEW_CRITERIA_SCORE 5 #define DEIP_MIN_POSITIVE_REVIEW_SCORE 8 #define DEIP_COMMON_DISCIPLINE_ID "6c4bb3bcf1a88e3b51de88576d592f1f980c5bbb" /** * Reserved Account IDs with special meaning */ ///@{ /// Represents the canonical account for specifying you will vote for directly (as opposed to a proxy) #define DEIP_PROXY_TO_SELF_ACCOUNT "" #define DEIP_API_BULK_FETCH_LIMIT 10000 ///@} // clang-format on
47.827731
194
0.685672
DEIPworld
85924ac19abbb0bec4d2afbe86a3eaeaed975a8f
6,538
cpp
C++
Game/Level/StaticObject.cpp
RMDarth/Chewman-Vulkan
7ebd3fb378b78c67844055c5bf1dc51c54a48324
[ "MIT" ]
65
2019-10-22T01:06:07.000Z
2022-03-26T14:41:28.000Z
Game/Level/StaticObject.cpp
heitaoflower/Chewman-Vulkan
dfd4d8b4e58b8a01e5f41f256795ec6e0d2b633e
[ "MIT" ]
9
2019-09-24T15:51:14.000Z
2021-08-19T09:52:03.000Z
Game/Level/StaticObject.cpp
heitaoflower/Chewman-Vulkan
dfd4d8b4e58b8a01e5f41f256795ec6e0d2b633e
[ "MIT" ]
6
2020-01-31T08:51:14.000Z
2021-01-08T05:49:47.000Z
// Chewman Vulkan game // Copyright (c) 2018-2019, Igor Barinov // Licensed under the MIT License #include "StaticObject.h" #include "GameMap.h" #include "GameUtils.h" #include "SVE/Engine.h" #include "SVE/SceneManager.h" #include <glm/gtc/matrix_transform.hpp> #include <Game/Game.h> namespace Chewman { namespace { StaticObjectType getObjectType(char symbolType) { switch (symbolType) { case 'J': return StaticObjectType::Tomb; case 'V': return StaticObjectType::Volcano; case 'D': return StaticObjectType::Dragon; case 'Z': return StaticObjectType::Pot; case 'Y': return StaticObjectType::Mouth; } assert(!"Unknown static object"); return StaticObjectType::Tomb; } std::shared_ptr<SVE::MeshEntity> getStaticObjectEntity(StaticObjectType type) { std::string meshName; std::string materialName; const auto& graphicSettings = Game::getInstance()->getGraphicsManager().getSettings(); switch (type) { case StaticObjectType::Tomb: meshName = "tomb"; materialName = "TombMaterial"; break; case StaticObjectType::Volcano: meshName = "volcano"; materialName = graphicSettings.effectSettings != EffectSettings::Low ? "VolcanoMaterial" : "VolcanoLowMaterial"; break; case StaticObjectType::Dragon: meshName = "dragon"; materialName = "DragonMaterial"; break; case StaticObjectType::Pot: meshName = "pot"; materialName = graphicSettings.effectSettings != EffectSettings::Low ? "PotMaterial" : "PotLowMaterial"; break; case StaticObjectType::Mouth: meshName = "throat"; materialName = "ThroatMaterial"; break; } auto staticMeshEntity = std::make_shared<SVE::MeshEntity>(meshName); staticMeshEntity->setMaterial(materialName); return staticMeshEntity; } } // anon namespace StaticObject::StaticObject(GameMap* gameMap, glm::ivec2 startPos, char symbolType, char rotation) : StaticObject(gameMap, startPos, getObjectType(symbolType), rotation) { } StaticObject::StaticObject(GameMap* gameMap, glm::ivec2 startPos, StaticObjectType type, char rotation) : _type(type) { auto* engine = SVE::Engine::getInstance(); bool isHorizontal = rotation == '2' || rotation == '4'; auto position = getWorldPos(startPos.x, startPos.y, 0.0f); switch (_type) { case StaticObjectType::Tomb: position -= isHorizontal ? glm::vec3(CellSize * 0.5f, 0.0, -CellSize * 1.5f) : glm::vec3(CellSize * -0.5f, 0.0, -CellSize * 0.5f); break; case StaticObjectType::Volcano: position += glm::vec3(CellSize * 0.5f, 0.0, CellSize * 1.5f); break; case StaticObjectType::Dragon: position += glm::vec3(CellSize * 0.0f, 0.0, CellSize * 1.0f); break; case StaticObjectType::Pot: position += glm::vec3(CellSize * 0.0f, 0.0, CellSize * 1.0f); break; case StaticObjectType::Mouth: position -= isHorizontal ? glm::vec3(CellSize * 0.5f, 0.0, -CellSize * 1.5f) : glm::vec3(CellSize * -0.5f, 0.0, -CellSize * 0.5f); break; } _rootNode = engine->getSceneManager()->createSceneNode(); auto transform = glm::translate(glm::mat4(1), position); switch (_type) { case StaticObjectType::Tomb: transform = glm::rotate(transform, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); transform = glm::rotate(transform, glm::radians(90.0f * (rotation - '1')), glm::vec3(0.0f, 0.0f, 1.0f)); break; case StaticObjectType::Volcano: transform = glm::rotate(transform, glm::radians(-90.0f * (rotation - '1')), glm::vec3(0.0f, 1.0f, 0.0f)); break; case StaticObjectType::Mouth: transform = glm::rotate(transform, glm::radians(-90.0f * (rotation - '0')), glm::vec3(0.0f, 1.0f, 0.0f)); break; case StaticObjectType::Dragon: transform = glm::translate(transform, glm::vec3(0.0f, 1.5f, 0.0f)); transform = glm::rotate(transform, glm::radians(-90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); transform = glm::rotate(transform, glm::radians(-90.0f * (rotation - '1')), glm::vec3(0.0f, 0.0f, 1.0f)); break; case StaticObjectType::Pot: transform = glm::translate(transform, glm::vec3(0.0f, 1.3f, 0.0f)); transform = glm::rotate(transform, glm::radians(90.0f), glm::vec3(1.0f, 0.0f, 0.0f)); transform = glm::rotate(transform, glm::radians(-90.0f * (rotation - '1')), glm::vec3(0.0f, 0.0f, 1.0f)); break; } _rootNode->setNodeTransformation(transform); gameMap->mapNode->attachSceneNode(_rootNode); auto objectEntity = getStaticObjectEntity(type); _rootNode->attachEntity(std::move(objectEntity)); } StaticObjectType StaticObject::getType() const { return _type; } void StaticObject::update(float deltaTime) { // update animated models? } CellType StaticObject::getCellType(char type) { switch (getObjectType(type)) { case StaticObjectType::Tomb: return CellType::InvisibleWallWithFloor; case StaticObjectType::Volcano: return CellType::InvisibleWallWithFloor; case StaticObjectType::Dragon: return CellType::InvisibleWallWithFloor; case StaticObjectType::Pot: return CellType::Liquid; case StaticObjectType::Mouth: return CellType::InvisibleWallEmpty; } return CellType::InvisibleWallWithFloor; } std::pair<size_t, size_t> StaticObject::getSize(char type, char rotation) { switch (getObjectType(type)) { case StaticObjectType::Tomb: if (rotation == '1' || rotation == '3') return {2, 4}; return {4, 2}; case StaticObjectType::Volcano: return { 4, 4 }; case StaticObjectType::Dragon: return { 3, 3 }; case StaticObjectType::Pot: return { 3, 3 }; case StaticObjectType::Mouth: if (rotation == '1' || rotation == '3') return {2, 4}; return {4, 2}; } assert(!"Incorrect type"); return {0, 0}; } } // namespace Chewman
33.187817
124
0.596666
RMDarth
859684dd686a0f5f8e89deeae650eb9275255a91
279
hpp
C++
Axis/Util/UniqueFile.hpp
hannes-harnisch/Axis
8d57527c855d751ca5267ebcc4ab5d137b4fc51c
[ "MIT" ]
3
2022-02-09T14:59:31.000Z
2022-02-15T21:24:19.000Z
Axis/Util/UniqueFile.hpp
hannes-harnisch/Axis
8d57527c855d751ca5267ebcc4ab5d137b4fc51c
[ "MIT" ]
null
null
null
Axis/Util/UniqueFile.hpp
hannes-harnisch/Axis
8d57527c855d751ca5267ebcc4ab5d137b4fc51c
[ "MIT" ]
null
null
null
#pragma once #include <cstdio> #include <memory> namespace ax { struct FileCloser { void operator()(FILE* file) const { if(file != stdout && file != stderr && file != stdin) std::fclose(file); } }; using UniqueFile = std::unique_ptr<std::FILE, FileCloser>; }
14.684211
59
0.634409
hannes-harnisch
859eed2ff05bb0febf5dccd1eeaa69849df0c39c
170
cpp
C++
chapter 7/exercise /q2.cpp
realme72/beginning
9c6c5abaf675a53f88552dbc7fbf44c6bc94087c
[ "MIT" ]
2
2018-07-01T07:39:44.000Z
2020-05-17T07:26:26.000Z
chapter 7/exercise /q2.cpp
realme72/beginning
9c6c5abaf675a53f88552dbc7fbf44c6bc94087c
[ "MIT" ]
null
null
null
chapter 7/exercise /q2.cpp
realme72/beginning
9c6c5abaf675a53f88552dbc7fbf44c6bc94087c
[ "MIT" ]
null
null
null
#include <stdio.h> int func(int a,int b); int main() { printf("%d\n",func(3,8)); return 0; } int func(int a,int b) { if(a>b) return 1000; return a+func(a+1,b); }
10.625
26
0.582353
realme72
859eee3aac32fe1aa6906db5da3b536a2f615dfc
197
cpp
C++
src/Core/p2/iMemMgr.cpp
stravant/bfbbdecomp
2126be355a6bb8171b850f829c1f2731c8b5de08
[ "OLDAP-2.7" ]
1
2021-01-05T11:28:55.000Z
2021-01-05T11:28:55.000Z
src/Core/p2/iMemMgr.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
null
null
null
src/Core/p2/iMemMgr.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
1
2022-03-30T15:15:08.000Z
2022-03-30T15:15:08.000Z
#include "iMemMgr.h" #include <types.h> // func_800C6360 #pragma GLOBAL_ASM("asm/Core/p2/iMemMgr.s", "iMemInit__Fv") // func_800C646C #pragma GLOBAL_ASM("asm/Core/p2/iMemMgr.s", "iMemExit__Fv")
19.7
59
0.730964
stravant
85a12aba0247ffd375be571961b20fbf6448870d
819
hpp
C++
gloom/src/overkill/graphics_internal/VertexArray.hpp
Stektpotet/gloom
fcb6e031d573be029dd829d8e4fc0a97feb22687
[ "MIT" ]
null
null
null
gloom/src/overkill/graphics_internal/VertexArray.hpp
Stektpotet/gloom
fcb6e031d573be029dd829d8e4fc0a97feb22687
[ "MIT" ]
null
null
null
gloom/src/overkill/graphics_internal/VertexArray.hpp
Stektpotet/gloom
fcb6e031d573be029dd829d8e4fc0a97feb22687
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <unordered_map> #include <set> #include "../gfx.h" #include "VertexLayout.hpp" class VertexArray { public: VertexArray(); inline bool valid() const { return id != 0; } inline GLuint ID() const { return id; } inline void bind() const { GFX_GL_CALL(glBindVertexArray(id)); } static inline void unbind() { GFX_GL_CALL(glBindVertexArray(0)); } inline void clear() { GFX_DEBUG("VAO (%d) deleting...", id); glDeleteVertexArrays(1, &id); } private: GLuint id = 0; //std::unordered_map<GLuint> buffers(); std::unordered_map<VertexLayout*, std::set<VertexBuffer>> layouts; //list layouts, let buffers subscribe to one of them //std::vector<VertexLayout> layouts; };
21.552632
71
0.614164
Stektpotet
85a19a7ffebb252504016bcc1c0cfc1c8d49c976
318
hh
C++
Engine/spcImgLoader/imgloaderexport.hh
marcellfischbach/SpiceEngine
e25e1e4145b7afaea9179bb8e33e4d184bd407c4
[ "BSD-3-Clause" ]
null
null
null
Engine/spcImgLoader/imgloaderexport.hh
marcellfischbach/SpiceEngine
e25e1e4145b7afaea9179bb8e33e4d184bd407c4
[ "BSD-3-Clause" ]
1
2021-09-09T12:51:56.000Z
2021-09-09T12:51:56.000Z
Engine/spcImgLoader/imgloaderexport.hh
marcellfischbach/SpiceEngine
e25e1e4145b7afaea9179bb8e33e4d184bd407c4
[ "BSD-3-Clause" ]
null
null
null
#pragma once #ifdef SPC_WIN32 #pragma warning( disable : 4530) #pragma warning( disable : 4577) #ifdef SPC_IMGLOADER_EXPORT #define SPC_IMGLOADER_API __declspec(dllexport) #else #define SPC_IMGLOADER_API __declspec(dllimport) #endif #pragma warning( disable : 4251 ) #else #define SPC_IMGLOADER_API #endif
12.230769
47
0.773585
marcellfischbach
85ab6cc2da48ed398ab6b075e5c1322d88e8fb78
494
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/parameter/aux_/preprocessor/nullptr.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
ReactNativeFrontend/ios/Pods/boost/boost/parameter/aux_/preprocessor/nullptr.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
ReactNativeFrontend/ios/Pods/boost/boost/parameter/aux_/preprocessor/nullptr.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// Copyright Cromwell D. Enage 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_PARAMETER_AUX_PREPROCESSOR_NULLPTR_HPP #define BOOST_PARAMETER_AUX_PREPROCESSOR_NULLPTR_HPP #include <boost/config.hpp> #if defined(BOOST_NO_CXX11_NULLPTR) #define BOOST_PARAMETER_AUX_PP_NULLPTR 0 #else #define BOOST_PARAMETER_AUX_PP_NULLPTR nullptr #endif #endif // include guard
26
61
0.815789
Harshitha91
85b1b81d117df35d9173d9d95c947baa3da1ed2a
532
hpp
C++
include/hydro/hydro.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
include/hydro/hydro.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
include/hydro/hydro.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #ifndef HVM_CORE #define HVM_CORE #include "../../src/vm/HvmEnv.hpp" #include "cli.hpp" #include "hydro_native.hpp" #define HVM_VERSION "0.1.0" #endif /* HVM_CORE */
24.181818
50
0.368421
shockazoid
85b5bd3bb8f7baa70835979541b1636f1fefec08
5,663
cpp
C++
Developments/solidity-develop/test/ExecutionFramework.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
Developments/solidity-develop/test/ExecutionFramework.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
Developments/solidity-develop/test/ExecutionFramework.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2016 * Framework for executing contracts and testing them using RPC. */ #include <cstdlib> #include <boost/test/framework.hpp> #include <libdevcore/CommonIO.h> #include <test/ExecutionFramework.h> #include <boost/algorithm/string/replace.hpp> using namespace std; using namespace dev; using namespace dev::test; namespace // anonymous { h256 const EmptyTrie("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"); string getIPCSocketPath() { string ipcPath = dev::test::Options::get().ipcPath; if (ipcPath.empty()) BOOST_FAIL("ERROR: ipcPath not set! (use --ipcpath <path> or the environment variable ETH_TEST_IPC)"); return ipcPath; } } ExecutionFramework::ExecutionFramework() : m_rpc(RPCSession::instance(getIPCSocketPath())), m_optimize(dev::test::Options::get().optimize), m_showMessages(dev::test::Options::get().showMessages), m_sender(m_rpc.account(0)) { m_rpc.test_rewindToBlock(0); } std::pair<bool, string> ExecutionFramework::compareAndCreateMessage( bytes const& _result, bytes const& _expectation ) { if (_result == _expectation) return std::make_pair(true, std::string{}); std::string message = "Invalid encoded data\n" " Result Expectation\n"; auto resultHex = boost::replace_all_copy(toHex(_result), "0", "."); auto expectedHex = boost::replace_all_copy(toHex(_expectation), "0", "."); for (size_t i = 0; i < std::max(resultHex.size(), expectedHex.size()); i += 0x40) { std::string result{i >= resultHex.size() ? string{} : resultHex.substr(i, 0x40)}; std::string expected{i > expectedHex.size() ? string{} : expectedHex.substr(i, 0x40)}; message += (result == expected ? " " : " X ") + result + std::string(0x41 - result.size(), ' ') + expected + "\n"; } return make_pair(false, message); } void ExecutionFramework::sendMessage(bytes const& _data, bool _isCreation, u256 const& _value) { if (m_showMessages) { if (_isCreation) cout << "CREATE " << m_sender.hex() << ":" << endl; else cout << "CALL " << m_sender.hex() << " -> " << m_contractAddress.hex() << ":" << endl; if (_value > 0) cout << " value: " << _value << endl; cout << " in: " << toHex(_data) << endl; } RPCSession::TransactionData d; d.data = "0x" + toHex(_data); d.from = "0x" + toString(m_sender); d.gas = toHex(m_gas, HexPrefix::Add); d.gasPrice = toHex(m_gasPrice, HexPrefix::Add); d.value = toHex(_value, HexPrefix::Add); if (!_isCreation) { d.to = dev::toString(m_contractAddress); BOOST_REQUIRE(m_rpc.eth_getCode(d.to, "latest").size() > 2); // Use eth_call to get the output m_output = fromHex(m_rpc.eth_call(d, "latest"), WhenError::Throw); } string txHash = m_rpc.eth_sendTransaction(d); m_rpc.test_mineBlocks(1); RPCSession::TransactionReceipt receipt(m_rpc.eth_getTransactionReceipt(txHash)); m_blockNumber = u256(receipt.blockNumber); if (_isCreation) { m_contractAddress = Address(receipt.contractAddress); BOOST_REQUIRE(m_contractAddress); string code = m_rpc.eth_getCode(receipt.contractAddress, "latest"); m_output = fromHex(code, WhenError::Throw); } if (m_showMessages) { cout << " out: " << toHex(m_output) << endl; cout << " tx hash: " << txHash << endl; } m_gasUsed = u256(receipt.gasUsed); m_logs.clear(); for (auto const& log: receipt.logEntries) { LogEntry entry; entry.address = Address(log.address); for (auto const& topic: log.topics) entry.topics.push_back(h256(topic)); entry.data = fromHex(log.data, WhenError::Throw); m_logs.push_back(entry); } } void ExecutionFramework::sendEther(Address const& _to, u256 const& _value) { RPCSession::TransactionData d; d.data = "0x"; d.from = "0x" + toString(m_sender); d.gas = toHex(m_gas, HexPrefix::Add); d.gasPrice = toHex(m_gasPrice, HexPrefix::Add); d.value = toHex(_value, HexPrefix::Add); d.to = dev::toString(_to); string txHash = m_rpc.eth_sendTransaction(d); m_rpc.test_mineBlocks(1); } size_t ExecutionFramework::currentTimestamp() { auto latestBlock = m_rpc.eth_getBlockByNumber("latest", false); return size_t(u256(latestBlock.get("timestamp", "invalid").asString())); } size_t ExecutionFramework::blockTimestamp(u256 _number) { auto latestBlock = m_rpc.eth_getBlockByNumber(toString(_number), false); return size_t(u256(latestBlock.get("timestamp", "invalid").asString())); } Address ExecutionFramework::account(size_t _i) { return Address(m_rpc.accountCreateIfNotExists(_i)); } bool ExecutionFramework::addressHasCode(Address const& _addr) { string code = m_rpc.eth_getCode(toString(_addr), "latest"); return !code.empty() && code != "0x"; } u256 ExecutionFramework::balanceAt(Address const& _addr) { return u256(m_rpc.eth_getBalance(toString(_addr), "latest")); } bool ExecutionFramework::storageEmpty(Address const& _addr) { h256 root(m_rpc.eth_getStorageRoot(toString(_addr), "latest")); BOOST_CHECK(root); return root == EmptyTrie; }
29.494792
104
0.70475
jansenbarabona
85b6c729067df7094d1065298dd1895670dabb04
3,522
inl
C++
Library/Sources/Stroika/Foundation/IO/Network/HTTP/Cookie.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/IO/Network/HTTP/Cookie.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/IO/Network/HTTP/Cookie.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_IO_Network_HTTP_Cookie_inl_ #define _Stroika_Foundation_IO_Network_HTTP_Cookie_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ namespace Stroika::Foundation::IO::Network::HTTP { /* ******************************************************************************** ********************************** HTTP::Cookie ******************************** ******************************************************************************** */ inline Cookie::Cookie (const String& name, const String& value) : KeyValuePair<String, String>{name, value} { } inline String HTTP::Cookie::ToString () const { return As<String> (); } #if __cpp_impl_three_way_comparison < 201907 inline bool operator== (const Cookie& lhs, const Cookie& rhs) { // clang-format off return lhs.fKey == rhs.fKey and lhs.fValue == rhs.fValue and lhs.fExpires == rhs.fExpires and lhs.fMaxAge == rhs.fMaxAge and lhs.fDomain == rhs.fDomain and lhs.fPath == rhs.fPath and lhs.fSecure == rhs.fSecure and lhs.fHttpOnly == rhs.fHttpOnly and lhs.fOtherAttributes == rhs.fOtherAttributes ; // clang-format on } inline bool operator!= (const Cookie& lhs, const Cookie& rhs) { return not(lhs == rhs); } #endif /* ******************************************************************************** ******************************** HTTP::CookieList ****************************** ******************************************************************************** */ inline CookieList::CookieList (const CookieList& src) : CookieList{} { fCookieDetails_ = src.fCookieDetails_; } inline CookieList::CookieList (CookieList&& src) : CookieList{} { fCookieDetails_ = move (src.fCookieDetails_); } inline CookieList::CookieList (const Mapping<String, String>& basicCookies) : CookieList{} { this->cookies = basicCookies; } inline CookieList::CookieList (const Collection<Cookie>& cookieDetails) : CookieList{} { fCookieDetails_ = cookieDetails; } inline CookieList& CookieList::operator= (const CookieList& rhs) { this->fCookieDetails_ = rhs.fCookieDetails_; return *this; } inline String HTTP::CookieList::ToString () const { return EncodeForCookieHeader (); } #if __cpp_impl_three_way_comparison >= 201907 inline bool CookieList::operator== (const CookieList& rhs) const { return Traversal::Iterable<Cookie>::SequentialEqualsComparer<>{}(fCookieDetails_, rhs.fCookieDetails_); } #endif #if __cpp_impl_three_way_comparison < 201907 inline bool operator== (const CookieList& lhs, const CookieList& rhs) { return Traversal::Iterable<Cookie>::SequentialEqualsComparer<>{}(lhs.fCookieDetails_, rhs.fCookieDetails_); } inline bool operator!= (const CookieList& lhs, const CookieList& rhs) { return not(lhs == rhs); } #endif } #endif /*_Stroika_Foundation_IO_Network_HTTP_Cookie_inl_*/
33.865385
115
0.509938
SophistSolutions
85bca9ce08d3a8a8d75f442430522d43f89be4b3
2,344
cc
C++
sdk/src/utils/FileSystemUtils.cc
OpenInspur/inspur-oss-cpp-sdk
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
[ "Apache-2.0" ]
null
null
null
sdk/src/utils/FileSystemUtils.cc
OpenInspur/inspur-oss-cpp-sdk
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
[ "Apache-2.0" ]
null
null
null
sdk/src/utils/FileSystemUtils.cc
OpenInspur/inspur-oss-cpp-sdk
a0932232aaf46aab7c5a2079f72d80cc5d634ba2
[ "Apache-2.0" ]
null
null
null
#include <string> #include <map> #include <ctime> #include <iostream> #include <inspurcloud/oss/Types.h> #include "FileSystemUtils.h" #include <inspurcloud/oss/Const.h> #ifdef _WIN32 #include <direct.h> #include <io.h> #include <sys/stat.h> #define oss_access(a) ::_access((a), 0) #define oss_mkdir(a) ::_mkdir(a) #define oss_rmdir(a) ::_rmdir(a) #define oss_stat _stat64 #else #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #define oss_access(a) ::access(a, 0) #define oss_mkdir(a) ::mkdir((a), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) #define oss_rmdir(a) ::rmdir(a) #define oss_stat stat #endif using namespace InspurCloud::OSS; bool InspurCloud::OSS::CreateDirectory(const std::string &folder) { std::string folder_builder; std::string sub; sub.reserve(folder.size()); for (auto it = folder.begin(); it != folder.end(); ++it) { const char c = *it; sub.push_back(c); if (c == PATH_DELIMITER || it == folder.end() - 1) { folder_builder.append(sub); if (oss_access(folder_builder.c_str()) != 0) { if (oss_mkdir(folder_builder.c_str()) != 0) { return false; } } sub.clear(); } } return true; } bool InspurCloud::OSS::IsDirectoryExist(std::string folder) { if (folder[folder.length() - 1] != PATH_DELIMITER && folder[folder.length() - 1] != '/') { folder += PATH_DELIMITER; } return !oss_access(folder.c_str()); } bool InspurCloud::OSS::RemoveDirectory(const std::string &folder) { return !oss_rmdir(folder.c_str()); } bool InspurCloud::OSS::RemoveFile(const std::string &filepath) { int ret = ::remove(filepath.c_str()); return !ret; } bool InspurCloud::OSS::RenameFile(const std::string &from, const std::string &to) { return !::rename(from.c_str(), to.c_str()); } bool InspurCloud::OSS::GetPathLastModifyTime(const std::string & path, time_t &t) { struct oss_stat buf; auto filename = path.c_str(); #if defined(_WIN32) && _MSC_VER < 1900 std::string tmp; if (!path.empty() && (path.rbegin()[0] == PATH_DELIMITER)) { tmp = path.substr(0, path.size() - 1); filename = tmp.c_str(); } #endif if (oss_stat(filename, &buf) != 0) return false; t = buf.st_mtime; return true; }
26.337079
94
0.619881
OpenInspur
85c2bad0effbba401a4515e4912a8c43fc69df8e
1,688
cpp
C++
vui/src/application.cpp
vastamat/vulkan_interface
f4cb382d8943fb11fd24080310a568bffae3ea47
[ "MIT" ]
null
null
null
vui/src/application.cpp
vastamat/vulkan_interface
f4cb382d8943fb11fd24080310a568bffae3ea47
[ "MIT" ]
null
null
null
vui/src/application.cpp
vastamat/vulkan_interface
f4cb382d8943fb11fd24080310a568bffae3ea47
[ "MIT" ]
null
null
null
#include "application.h" #include "graphics.h" #include "window.h" #include "vulkan_renderer.h" #include "timer.h" #include <thread> // Variable Render frame limiter (runs as quick as possible with a set limit) // Must be more than the fixed update, or the sleep will disrupt the fixed timer constexpr int c_MillisPerSecond = 1000; constexpr float c_DesiredRenderFPS = 60.0f; constexpr float c_DesiredRenderFrameMS = c_MillisPerSecond / c_DesiredRenderFPS; vui::Application::Application() { m_Graphics = std::make_shared<Graphics>(); m_MainWindow = std::make_shared<Window>("Vulkan Sandbox", 1280, 720); m_Renderer = std::make_shared<VulkanRenderer>(*m_MainWindow); } void vui::Application::Run() { Timer updateTimer; bool ShouldQuit = false; while (!ShouldQuit) { // float delta = updateTimer.GetElapsedMilli(); updateTimer.Renew(); ShouldQuit = Update(/*delta*/); Render(); float elapsed = updateTimer.GetElapsedMilli(); if (elapsed < c_DesiredRenderFrameMS) { std::this_thread::sleep_for(std::chrono::duration<float, std::milli>( c_DesiredRenderFrameMS - elapsed)); } } } bool vui::Application::Update() { if (m_MainWindow->m_Keyboard.IsKeyJustPressed(vui::KeyCode::Tab)) { printf("Pressed Tab \n"); } if (m_MainWindow->m_Keyboard.IsKeyJustReleased(vui::KeyCode::Tab)) { printf("Released Tab \n"); } // if (m_MainWindow->m_Keyboard.IsKeyHeldDown(vui::KeyCode::Tab)) // { // printf("Holding down Tab \n"); // } return m_MainWindow->ProcessInput(); } void vui::Application::Render() { }
25.19403
81
0.658175
vastamat
85ca0aab118f2a78bf25023241c16507e0001e59
6,607
cc
C++
src/detective.cc
nih-at/ckmame
6315a1e14532f0eb1c64a27c3fb1657f4cb5e39f
[ "BSD-3-Clause" ]
8
2018-01-17T21:21:24.000Z
2020-10-19T18:30:45.000Z
src/detective.cc
nih-at/ckmame
6315a1e14532f0eb1c64a27c3fb1657f4cb5e39f
[ "BSD-3-Clause" ]
2
2018-12-11T06:12:35.000Z
2021-06-20T09:28:44.000Z
src/detective.cc
nih-at/ckmame
6315a1e14532f0eb1c64a27c3fb1657f4cb5e39f
[ "BSD-3-Clause" ]
2
2018-09-18T23:45:22.000Z
2020-02-27T18:32:47.000Z
/* detective.c -- list files from zip archive with headers skipped Copyright (C) 2007-2014 Dieter Baron and Thomas Klausner This file is part of ckmame, a program to check rom sets for MAME. The authors can be contacted at <ckmame@nih.at> 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. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 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 <cerrno> #include <cinttypes> #include <cstring> #include "config.h" #include "compat.h" #include "error.h" #include "globals.h" #include "Hashes.h" #include "RomDB.h" #include "Stats.h" const char *usage = "Usage: %s [-hV] [-C types] [-D dbfile] [--detector detector] zip-archive [...]\n"; const char help_head[] = "detective (" PACKAGE ") by Dieter Baron and" " Thomas Klausner\n\n"; const char help[] = "\n" " -h, --help display this help message\n" " -V, --version display version number\n" " -C, --hash-types types specify hash types to compute (default: all)\n" " -D, --db dbfile use mame-db dbfile\n" " --detector xml-file use header detector\n" " -u, --roms-unzipped ROMs are files on disk, not contained in zip archives\n" "\n" "Report bugs to " PACKAGE_BUGREPORT ".\n"; const char version_string[] = "detective (" PACKAGE " " VERSION ")\n" "Copyright (C) 2007-2014 Dieter Baron and Thomas Klausner\n" PACKAGE " comes with ABSOLUTELY NO WARRANTY, to the extent permitted by law.\n"; #define OPTIONS "hC:DuV" enum { OPT_DETECTOR = 256 }; struct option options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'V'}, {"db", 1, 0, 'D'}, {"detector", 1, 0, OPT_DETECTOR}, {"hash-types", 1, 0, 'C'}, {"roms-unzipped", 0, 0, 'u'}, {NULL, 0, 0, 0}, }; static int print_archive(const char *, int); static void print_checksums(const Hashes *, int); int main(int argc, char **argv) { const char *dbname; char *detector_name; int c, i, ret; int hashtypes; setprogname(argv[0]); DetectorPtr detector; hashtypes = -1; dbname = getenv("MAMEDB"); if (dbname == NULL) dbname = RomDB::default_name.c_str(); detector_name = NULL; roms_unzipped = false; opterr = 0; while ((c = getopt_long(argc, argv, OPTIONS, options, 0)) != EOF) { switch (c) { case 'h': fputs(help_head, stdout); printf(usage, getprogname()); fputs(help, stdout); exit(0); case 'V': fputs(version_string, stdout); exit(0); case 'C': hashtypes = Hashes::types_from_string(optarg); if (hashtypes == 0) { fprintf(stderr, "%s: illegal hash types '%s'\n", getprogname(), optarg); exit(1); } break; case 'D': dbname = optarg; break; case 'u': roms_unzipped = true; break; case OPT_DETECTOR: detector_name = optarg; break; default: fprintf(stderr, usage, getprogname()); exit(1); } } if (argc == optind) { fprintf(stderr, usage, getprogname()); exit(1); } try { if (detector_name) { #if defined(HAVE_LIBXML2) if ((detector = Detector::parse(detector_name)) == NULL) { myerror(ERRSTR, "cannot parse detector '%s'", detector_name); exit(1); } #else myerror(ERRDEF, "mkmamedb was built without XML support, detectors not available"); #endif } try { auto ddb = std::make_unique<RomDB>(dbname, DBH_READ); if (detector == NULL) { detector = ddb->detectors.begin()->second; } if (hashtypes == -1) { hashtypes = ddb->hashtypes(TYPE_ROM); } } catch (std::exception &e) { if (detector == 0) { // TODO: catch exception for unsupported database version and report differently myerror(0, "can't open database '%s': %s", dbname, strerror(errno)); exit(1); } } ret = 0; for (i = optind; i < argc; i++) ret |= print_archive(argv[i], hashtypes); return ret ? 1 : 0; } catch (const std::exception &exception) { fprintf(stderr, "%s: unexpected error: %s\n", getprogname(), exception.what()); exit(1); } } static int print_archive(const char *fname, int hashtypes) { int ret; auto archive = Archive::open(fname, TYPE_ROM, FILE_NOWHERE, ARCHIVE_FL_NOCACHE); if (!archive) { return -1; } printf("%s\n", archive->name.c_str()); ret = 0; for (size_t i = 0; i < archive->files.size(); i++) { bool use_detector = false; if (!archive->file_ensure_hashes(i, hashtypes)) { ret = -1; continue; } auto &file = archive->files[i]; if (file.size_hashes_are_set(true)) { use_detector = true; } printf("\tfile %-12s size %7" PRIu64, file.name.c_str(), file.get_size(use_detector)); print_checksums(&file.get_hashes(use_detector), hashtypes); if (use_detector) { printf(" (header skipped)"); } printf("\n"); } return ret; } static void print_checksums(const Hashes *hashes, int hashtypes) { int i; for (i = 1; i <= Hashes::TYPE_MAX; i <<= 1) { if (hashes->has_type(i) && (hashtypes & i)) { printf(" %s %s", Hashes::type_name(i).c_str(), hashes->to_string(i).c_str()); } } }
29.627803
175
0.621462
nih-at
85ce995fd726e30eea6ed78df7b1fdaa5b661d23
7,856
cpp
C++
Src/webbase/WebKitSensorConnector.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/webbase/WebKitSensorConnector.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/webbase/WebKitSensorConnector.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "WebKitSensorConnector.h" WebKitSensorConnector::WebKitSensorConnector(Palm::SensorType aSensorType, Palm::fnSensorDataCallback aDataCB, Palm::fnSensorErrorCallback aErrCB, void *pUserData) : m_PalmSensorType(aSensorType) , m_DataCB(aDataCB) , m_ErrCB(aErrCB) , m_UserData(pUserData) { #if defined (TARGET_DEVICE) m_NYXSensorType = WebKitToNYX(aSensorType); // Create the sensor m_Sensor = NYXConnectorBase::getSensor(m_NYXSensorType, this); // Immediately switch-off the sensor, as NYX starts sending the NYX data immediately off(); #endif } WebKitSensorConnector::~WebKitSensorConnector() { #if defined (TARGET_DEVICE) if (m_Sensor) { m_Sensor->scheduleDeletion(); } m_Sensor = 0; #endif } WebKitSensorConnector* WebKitSensorConnector::createSensor(Palm::SensorType aType, Palm::fnSensorDataCallback aDataCB, Palm::fnSensorErrorCallback aErrCB, void *pUserData) { WebKitSensorConnector *pWebKitSensor = 0; #if defined (TARGET_DEVICE) if ((aDataCB) && (aErrCB)) { NYXConnectorBase::Sensor nyxSensorType = WebKitToNYX(aType); if (NYXConnectorBase::SensorIllegal != nyxSensorType) { pWebKitSensor = new WebKitSensorConnector(aType, aDataCB, aErrCB, pUserData); } } #endif return pWebKitSensor; } #if defined (TARGET_DEVICE) NYXConnectorBase::Sensor WebKitSensorConnector::WebKitToNYX(Palm::SensorType aSensorType) { NYXConnectorBase::Sensor mappedSensor = NYXConnectorBase::SensorIllegal; switch(aSensorType) { case Palm::SensorAcceleration: { mappedSensor = NYXConnectorBase::SensorAcceleration; break; } case Palm::SensorOrientation: { mappedSensor = NYXConnectorBase::SensorOrientation; break; } case Palm::SensorShake: { mappedSensor = NYXConnectorBase::SensorShake; break; } case Palm::SensorBearing: { mappedSensor = NYXConnectorBase::SensorBearing; break; } case Palm::SensorALS: { mappedSensor = NYXConnectorBase::SensorALS; break; } case Palm::SensorAngularVelocity: { mappedSensor = NYXConnectorBase::SensorAngularVelocity; break; } case Palm::SensorGravity: { mappedSensor = NYXConnectorBase::SensorGravity; break; } case Palm::SensorLinearAcceleration: { mappedSensor = NYXConnectorBase::SensorLinearAcceleration; break; } case Palm::SensorMagneticField: { mappedSensor = NYXConnectorBase::SensorMagneticField; break; } case Palm::SensorScreenProximity: { mappedSensor = NYXConnectorBase::SensorScreenProximity; break; } case Palm::SensorRotation: { mappedSensor = NYXConnectorBase::SensorRotation; break; } case Palm::SensorLogicalDeviceOrientation: { mappedSensor = NYXConnectorBase::SensorLogicalDeviceOrientation; break; } case Palm::SensorLogicalDeviceMotion: { mappedSensor = NYXConnectorBase::SensorLogicalMotion; break; } default: { g_critical("[%s : %d] : Mustn't have reached here : Sensor Type : [%d]", __PRETTY_FUNCTION__, __LINE__, aSensorType); break; } } return mappedSensor; } NYXConnectorBase::SensorReportRate WebKitSensorConnector::WebKitToNYX(Palm::SensorRate aRate) { NYXConnectorBase::SensorReportRate mappedRate = NYXConnectorBase::SensorReportRateDefault; switch(aRate) { case Palm::RATE_DEFAULT: { mappedRate = NYXConnectorBase::SensorReportRateDefault; break; } case Palm::RATE_LOW: { mappedRate = NYXConnectorBase::SensorReportRateLow; break; } case Palm::RATE_MEDIUM: { mappedRate = NYXConnectorBase::SensorReportRateMedium; break; } case Palm::RATE_HIGH: { mappedRate = NYXConnectorBase::SensorReportRateHigh; break; } case Palm::RATE_HIGHEST: { mappedRate = NYXConnectorBase::SensorReportRateHighest; break; } default: { g_critical("[%s : %d] : Mustn't have reached here : Sensor Type : Sensor Type.", __PRETTY_FUNCTION__, __LINE__); break; } } return mappedRate; } void WebKitSensorConnector::NYXDataAvailable (NYXConnectorBase::Sensor aSensorType) { if ((NYXConnectorBase::SensorIllegal != aSensorType) && (m_Sensor) && (m_DataCB)) { std::string jsonData = m_Sensor->toJSONString(); m_DataCB(m_PalmSensorType, jsonData, m_UserData); } } #endif bool WebKitSensorConnector::on() { bool bRetValue = false; #if defined (TARGET_DEVICE) if (m_Sensor) { bRetValue = m_Sensor->on(); if (!bRetValue) { g_critical("[%s : %d] : Critical Error Occurred while trying to turn the sensor on : Sensor Type : [%d]", __PRETTY_FUNCTION__, __LINE__, m_NYXSensorType); } } #endif return bRetValue; } bool WebKitSensorConnector::off() { bool bRetValue = false; #if defined (TARGET_DEVICE) if (m_Sensor) { bRetValue = m_Sensor->off(); if (!bRetValue) { g_critical("[%s : %d] : Critical Error Occurred while trying to turn the sensor off : Sensor Type : [%d]", __PRETTY_FUNCTION__, __LINE__, m_NYXSensorType); } } #endif return bRetValue; } bool WebKitSensorConnector::setRate(Palm::SensorRate aRate) { bool bRetValue = false; #if defined (TARGET_DEVICE) if (m_Sensor) { NYXConnectorBase::SensorReportRate sensorRate = WebKitToNYX(aRate); if ((NYXConnectorBase::SensorReportRateUnknown != sensorRate) && (NYXConnectorBase::SensorReportRateCount != sensorRate)) { bRetValue = m_Sensor->setRate(sensorRate); if (!bRetValue) { g_critical("[%s : %d] : Critical Error Occurred while trying to set the sensor rate : Sensor Type : [%d]", __PRETTY_FUNCTION__, __LINE__, m_NYXSensorType); } } } #endif return bRetValue; } std::string WebKitSensorConnector::getSupportedSensors() { std::string strSensorList = ""; #if defined (TARGET_DEVICE) strSensorList = NYXConnectorBase::getSupportedSensors(true); if (strSensorList.empty()) { g_critical("[%s : %d] : Critical Error Occurred while trying to get the Sensor List: Sensor Type", __PRETTY_FUNCTION__, __LINE__); } #endif return strSensorList; } void WebKitSensorConnector::CallErrorCB(std::string aMsg) { #if defined (TARGET_DEVICE) if ((m_Sensor) && (m_ErrCB)) { m_ErrCB(m_PalmSensorType, aMsg, m_UserData); } #endif }
25.26045
171
0.627164
ericblade
85d67506cfdcf85dcc9a8a6dec3be654b96bd84f
821
cpp
C++
kernel/gdt/gdt.cpp
Andrej123456789/LockOS
5b95088146ec9c64a575ac099f6d09ccc0fe935b
[ "MIT" ]
25
2021-11-23T12:29:18.000Z
2022-02-28T17:32:21.000Z
kernel/gdt/gdt.cpp
ringwormGO-organization/ringOS
5b95088146ec9c64a575ac099f6d09ccc0fe935b
[ "MIT" ]
25
2021-11-18T09:08:52.000Z
2022-03-18T12:01:37.000Z
kernel/gdt/gdt.cpp
Andrej123456789/ringOS
46848843c41396e7e5c5cb82b5f0f784b3c8ffc9
[ "MIT" ]
4
2021-12-05T14:59:13.000Z
2022-01-22T13:24:16.000Z
#include "gdt.hpp" void create_descriptor() { uint32_t base; uint32_t limit; uint16_t flag; uint64_t descriptor; // Create the high 32 bit segment descriptor = limit & 0x000F0000; // set limit bits 19:16 descriptor |= (flag << 8) & 0x00F0FF00; // set type, p, dpl, s, g, d/b, l and avl fields descriptor |= (base >> 16) & 0x000000FF; // set base bits 23:16 descriptor |= base & 0xFF000000; // set base bits 31:24 // Shift by 32 to allow for low part of segment descriptor <<= 32; // Create the low 32 bit segment descriptor |= base << 16; // set base bits 15:0 descriptor |= limit & 0x0000FFFF; // set limit bits 15:0 e9_printf("GDT descriptor: 0x%.16llX\n", descriptor); }
31.576923
101
0.571255
Andrej123456789
85e3050699b0d283afe20e2c292a925f493b6341
9,816
hpp
C++
src/unit_cell/atom_symmetry_class.hpp
simonpp/SIRIUS
f4b5c4810af2a3ea1e67992d65750535227da84b
[ "BSD-2-Clause" ]
1
2019-05-10T08:48:55.000Z
2019-05-10T08:48:55.000Z
src/unit_cell/atom_symmetry_class.hpp
simonpintarelli/SIRIUS
f4b5c4810af2a3ea1e67992d65750535227da84b
[ "BSD-2-Clause" ]
null
null
null
src/unit_cell/atom_symmetry_class.hpp
simonpintarelli/SIRIUS
f4b5c4810af2a3ea1e67992d65750535227da84b
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** \file atom_symmetry_class.hpp * * \brief Contains declaration and partial implementation of sirius::Atom_symmetry_class class. */ #ifndef __ATOM_SYMMETRY_CLASS_HPP__ #define __ATOM_SYMMETRY_CLASS_HPP__ #include "atom_type.hpp" #include "linalg/eigensolver.hpp" namespace sirius { /// Data and methods specific to the symmetry class of the atom. /** Atoms transforming into each other under symmetry opeartions belong to the same symmetry class. They have the * same spherical part of the on-site potential and, as a consequence, the same radial functions. */ class Atom_symmetry_class { private: /// Symmetry class id in the range [0, N_class). int id_; /// List of atoms of this class. std::vector<int> atom_id_; /// Pointer to atom type. Atom_type const& atom_type_; /// Spherical part of the effective potential. /** Used by the LAPW radial solver. */ std::vector<double> spherical_potential_; /// List of radial functions for the LAPW basis. /** This array stores all the radial functions (AW and LO) and their derivatives. Radial derivatives of functions * are multiplied by \f$ x \f$.\n * 1-st dimension: index of radial point \n * 2-nd dimension: index of radial function \n * 3-nd dimension: 0 - function itself, 1 - radial derivative r*(du/dr) */ sddk::mdarray<double, 3> radial_functions_; /// Surface derivatives of AW radial functions. sddk::mdarray<double, 2> surface_derivatives_; /// Spherical part of radial integral. sddk::mdarray<double, 2> h_spherical_integrals_; /// Overlap integrals. sddk::mdarray<double, 3> o_radial_integrals_; /// Overlap integrals for IORA relativistic treatment. sddk::mdarray<double, 2> o1_radial_integrals_; /// Spin-orbit interaction integrals. sddk::mdarray<double, 3> so_radial_integrals_; /// Core charge density. /** All-electron core charge density of the LAPW method. It is recomputed on every SCF iteration due to the change of effective potential. */ std::vector<double> ae_core_charge_density_; /// Core eigen-value sum. double core_eval_sum_{0}; /// Core leakage. double core_leakage_{0}; /// list of radial descriptor sets used to construct augmented waves mutable std::vector<radial_solution_descriptor_set> aw_descriptors_; /// list of radial descriptor sets used to construct local orbitals mutable std::vector<local_orbital_descriptor> lo_descriptors_; /// Generate radial functions for augmented waves void generate_aw_radial_functions(relativity_t rel__); /// Generate local orbital raidal functions void generate_lo_radial_functions(relativity_t rel__); /// Orthogonalize the radial functions. void orthogonalize_radial_functions(); public: /// Constructor Atom_symmetry_class(int id_, Atom_type const& atom_type_); /// Set the spherical component of the potential /** Atoms belonging to the same symmetry class have the same spherical potential. */ void set_spherical_potential(std::vector<double> const& vs__); /// Generate APW and LO radial functions. void generate_radial_functions(relativity_t rel__); void sync_radial_functions(Communicator const& comm__, int const rank__); void sync_radial_integrals(Communicator const& comm__, int const rank__); void sync_core_charge_density(Communicator const& comm__, int const rank__); /// Check if local orbitals are linearly independent std::vector<int> check_lo_linear_independence(double etol__); /// Dump local orbitals to the file for debug purposes void dump_lo(); /// Find core states and generate core density. void generate_core_charge_density(relativity_t core_rel__); /// Find linearization energy. void find_enu(relativity_t rel__); void write_enu(pstdout& pout) const; /// Generate radial overlap and SO integrals /** In the case of spin-orbit interaction the following integrals are computed: * \f[ * \int f_{p}(r) \Big( \frac{1}{(2 M c)^2} \frac{1}{r} \frac{d V}{d r} \Big) f_{p'}(r) r^2 dr * \f] * * Relativistic mass M is defined as * \f[ * M = 1 - \frac{1}{2 c^2} V * \f] */ void generate_radial_integrals(relativity_t rel__); /// Get m-th order radial derivative of AW functions at the MT surface. inline double aw_surface_deriv(int l__, int order__, int dm__) const { RTE_ASSERT(dm__ <= 2); int idxrf = atom_type_.indexr().index_by_l_order(l__, order__); return surface_derivatives_(dm__, idxrf); } /// Set surface derivative of AW radial functions. inline void aw_surface_deriv(int l__, int order__, int dm__, double deriv__) { RTE_ASSERT(dm__ <= 2); int idxrf = atom_type_.indexr().index_by_l_order(l__, order__); surface_derivatives_(dm__, idxrf) = deriv__; } /// Return symmetry class id. inline int id() const { return id_; } /// Add atom id to the current class. inline void add_atom_id(int atom_id__) { atom_id_.push_back(atom_id__); } /// Return number of atoms belonging to the current symmetry class. inline int num_atoms() const { return static_cast<int>(atom_id_.size()); } inline int atom_id(int idx) const { return atom_id_[idx]; } /// Get a value of the radial functions. inline double radial_function(int ir, int idx) const { return radial_functions_(ir, idx, 0); } /// Set radial function. inline void radial_function(int idx__, std::vector<double> f__) { for (int ir = 0; ir < this->atom_type().num_mt_points(); ir++) { radial_functions_(ir, idx__, 0) = f__[ir]; } } /// Set radial function derivative r*(du/dr). inline void radial_function_derivative(int idx__, std::vector<double> f__) { for (int ir = 0; ir < this->atom_type().num_mt_points(); ir++) { radial_functions_(ir, idx__, 1) = f__[ir]; } } inline double h_spherical_integral(int i1, int i2) const { return h_spherical_integrals_(i1, i2); } inline double const& o_radial_integral(int l, int order1, int order2) const { return o_radial_integrals_(l, order1, order2); } inline void set_o_radial_integral(int l, int order1, int order2, double oint__) { o_radial_integrals_(l, order1, order2) = oint__; } inline double const& o1_radial_integral(int xi1__, int xi2__) const { return o1_radial_integrals_(xi1__, xi2__); } inline void set_o1_radial_integral(int idxrf1__, int idxrf2__, double val__) { o1_radial_integrals_(idxrf1__, idxrf2__) = val__; } inline double so_radial_integral(int l, int order1, int order2) const { return so_radial_integrals_(l, order1, order2); } inline double ae_core_charge_density(int ir) const { RTE_ASSERT(ir >= 0 && ir < (int)ae_core_charge_density_.size()); return ae_core_charge_density_[ir]; } inline Atom_type const& atom_type() const { return atom_type_; } inline double core_eval_sum() const { return core_eval_sum_; } inline double core_leakage() const { return core_leakage_; } inline int num_aw_descriptors() const { return static_cast<int>(aw_descriptors_.size()); } inline radial_solution_descriptor_set& aw_descriptor(int idx__) const { return aw_descriptors_[idx__]; } inline int num_lo_descriptors() const { return static_cast<int>(lo_descriptors_.size()); } inline local_orbital_descriptor& lo_descriptor(int idx__) const { return lo_descriptors_[idx__]; } inline void set_aw_enu(int l, int order, double enu) { aw_descriptors_[l][order].enu = enu; } inline double get_aw_enu(int l, int order) const { return aw_descriptors_[l][order].enu; } inline void set_lo_enu(int idxlo, int order, double enu) { lo_descriptors_[idxlo].rsd_set[order].enu = enu; } inline double get_lo_enu(int idxlo, int order) const { return lo_descriptors_[idxlo].rsd_set[order].enu; } }; } // namespace sirius #endif // __ATOM_SYMMETRY_CLASS_H__
32.39604
117
0.687653
simonpp
85e4e7a1af47cb3868fc4915c8817bfeb154ba15
39,760
cpp
C++
ortc/services/cpp/services_DHKeyDomain.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2016-10-12T09:16:32.000Z
2016-10-13T03:49:47.000Z
ortc/services/cpp/services_DHKeyDomain.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
2
2017-11-24T09:18:45.000Z
2017-11-24T09:20:53.000Z
ortc/services/cpp/services_DHKeyDomain.cpp
ortclib/ortclib-services-cpp
f770d97044b1ffbff04b61fa1488eedc8ddc66e4
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2014, Hookflash Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ #include <ortc/services/internal/services_DHKeyDomain.h> #include <ortc/services/IHelper.h> #include <cryptopp/osrng.h> #include <cryptopp/nbtheory.h> #include <zsLib/XML.h> #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_UNKNOWN "https://meta.ortclib.org/dh/modp/uknown" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_1024 "https://meta.ortclib.org/dh/modp/1024" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_1538 "https://meta.ortclib.org/dh/modp/1538" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_2048 "https://meta.ortclib.org/dh/modp/2048" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_3072 "https://meta.ortclib.org/dh/modp/3072" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_4096 "https://meta.ortclib.org/dh/modp/4096" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_6144 "https://meta.ortclib.org/dh/modp/6144" #define ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_8192 "https://meta.ortclib.org/dh/modp/8192" namespace ortc { namespace services { ZS_DECLARE_SUBSYSTEM(ortc_services) } } namespace ortc { namespace services { namespace internal { using CryptoPP::AutoSeededRandomPool; using CryptoPP::Integer; using CryptoPP::ModularExponentiation; using CryptoPP::ByteQueue; using namespace zsLib::XML; //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark (helpers) #pragma mark struct DHPrecompiledValues { const char *mP; const char *mQ; const char *mG; }; static DHPrecompiledValues sDHPrecompiles[] = { // 0 = unknown {NULL, NULL, NULL}, // 1 = 1024 { "B6CAF6732082AF5A55182304B6C211DC82549F4273E01855" "DAC955AE5672A5C507BDDEB5147EC0FA341F3673E2FD80C3" "558DBA64E75ADE49C812D064D6681DDF08E98A6A966451E4" "B079F649FE9138A62C19FAD2CC9A754D6D2FE661CA634B95" "DEE06F86C2FFB976A39310FEA0FFCF09D6BFDA0FF9F2BD63" "FA1E928CB95C2ECF", "5B657B39904157AD2A8C11825B6108EE412A4FA139F00C2A" "ED64AAD72B3952E283DEEF5A8A3F607D1A0F9B39F17EC061" "AAC6DD3273AD6F24E40968326B340EEF8474C5354B3228F2" "583CFB24FF489C53160CFD69664D3AA6B697F330E531A5CA" "EF7037C3617FDCBB51C9887F507FE784EB5FED07FCF95EB1" "FD0F49465CAE1767", "02" }, // 2 = 1538 { "9A5F5E8F6CF7CCCC3104044E4F4A9F9520740FB2A8F0AFFC" "EC39C7315EF507F26B59213BD3151B8A5CE0CB9756F86BC2" "5E6FDF307F67EE3EC27441CC50ADEEB8F280B9134D35FFC0" "4607091A873456AD442B8B737EC2C794D97BB3B6F562AC17" "B74C620F1D750FEF2B4CE3B21712E610E71C584F87599203" "47EAA9EB739C20202BB18D932EAD1A3FE855955AF55D17F0" "CE4570F29DB07AFBBE86F76D7B5D31DAB0F6760D6D37AA86" "2704307C089A98C1CBF5153F371E0CE37E18B12647C400B3", "4D2FAF47B67BE6661882022727A54FCA903A07D9547857FE" "761CE398AF7A83F935AC909DE98A8DC52E7065CBAB7C35E1" "2F37EF983FB3F71F613A20E62856F75C79405C89A69AFFE0" "2303848D439A2B56A215C5B9BF6163CA6CBDD9DB7AB1560B" "DBA631078EBA87F795A671D90B897308738E2C27C3ACC901" "A3F554F5B9CE101015D8C6C997568D1FF42ACAAD7AAE8BF8" "6722B8794ED83D7DDF437BB6BDAE98ED587B3B06B69BD543" "1382183E044D4C60E5FA8A9F9B8F0671BF0C589323E20059", "03" }, // 3 = 2048 { "E81724A6683F5C98638A243EA698DC03D7CE089AE426D286" "0D506A34FDD0F9E9FBC8285A822377553F342FDA4EE14F5B" "5CA5014F6B0638F5B8B3A904A639C6B7ACE6E0462770954D" "34AC065C115813C67152DE611FC2ED388962A9E73EF29C33" "E9C6D568B045F69F5D9C8582CFBA0B20DE5D25B21FB79E95" "F60640287BF711C6E79B7ACFC12DA9812F6073A21EC7559F" "C3E46B502F2BAFE28657A2676D71FB9BCA4197D45A5AE690" "17E1E62F4D484E1151F485DC217560342F5DA4CD9A87996A" "2D006595D95D9C82316A87F57E4F0A3C2465A3BC5034013A" "DAACEC2242BA8BED1B21141E975CA90448EF413CCEF88CF4" "D8BFB21630714239B6FFC58296CC0243", "740B9253341FAE4C31C5121F534C6E01EBE7044D72136943" "06A8351A7EE87CF4FDE4142D4111BBAA9F9A17ED2770A7AD" "AE5280A7B5831C7ADC59D482531CE35BD673702313B84AA6" "9A56032E08AC09E338A96F308FE1769C44B154F39F794E19" "F4E36AB45822FB4FAECE42C167DD05906F2E92D90FDBCF4A" "FB0320143DFB88E373CDBD67E096D4C097B039D10F63AACF" "E1F235A81795D7F1432BD133B6B8FDCDE520CBEA2D2D7348" "0BF0F317A6A42708A8FA42EE10BAB01A17AED266CD43CCB5" "168032CAECAECE4118B543FABF27851E1232D1DE281A009D" "6D567611215D45F68D908A0F4BAE54822477A09E677C467A" "6C5FD90B1838A11CDB7FE2C14B660121", "03" }, // 4 = 3072 { "B8429FE19BC51E678D050B7473535E745E125A3376490300" "F97A102A7547615A2DA92C7894C3FC74A66D19501FADA3DF" "B36C8DE9F9CAD54EE1AF716296FBACCE9844B7FA230AA114" "DAD48C983319115B96E4AF3534E39117E658B82D4CBDFE6F" "9A215C8BB69B291B452E7C96FAEF775D9F063E6199607B8B" "3766C355F5908E68346A75A50589F641BBDB88014001E002" "6FCC93AF4FC98D25712C986D66BC5875943412B85DCAB59F" "B496FCF4A9CE75E7B669B72895EB3599839E3F1D0AB73618" "C07654A90EE9EE5C90937647CFAFED689297CF9CCF010F02" "BADD2598A32DA14B752478D582A146883C2BD7848B2D1C6B" "6EF57319268CD20118C27DA01FAD39C4C4208B394AEDE0C6" "A28CB2D3A13F9C522ECEE7846E16FAF21DB5944FDD92119B" "637F2303BA8490D5E3A5B45795C022B79C2DE3C11AC90EE5" "393091E2C0F80F093DEFEE8D7B33F412106BC5957DB8439D" "BEA9502139C51B0EE383B34E11676D70CDC90FBADF8779CA" "A5B77344EC9A8585CF22056925C2C76EE8D5A7747E73E1D3", "5C214FF0CDE28F33C68285BA39A9AF3A2F092D19BB248180" "7CBD08153AA3B0AD16D4963C4A61FE3A53368CA80FD6D1EF" "D9B646F4FCE56AA770D7B8B14B7DD6674C225BFD1185508A" "6D6A464C198C88ADCB72579A9A71C88BF32C5C16A65EFF37" "CD10AE45DB4D948DA2973E4B7D77BBAECF831F30CCB03DC5" "9BB361AAFAC847341A353AD282C4FB20DDEDC400A000F001" "37E649D7A7E4C692B8964C36B35E2C3ACA1A095C2EE55ACF" "DA4B7E7A54E73AF3DB34DB944AF59ACCC1CF1F8E855B9B0C" "603B2A548774F72E4849BB23E7D7F6B4494BE7CE67808781" "5D6E92CC5196D0A5BA923C6AC150A3441E15EBC245968E35" "B77AB98C934669008C613ED00FD69CE26210459CA576F063" "51465969D09FCE29176773C2370B7D790EDACA27EEC908CD" "B1BF9181DD42486AF1D2DA2BCAE0115BCE16F1E08D648772" "9C9848F1607C07849EF7F746BD99FA090835E2CABEDC21CE" "DF54A8109CE28D8771C1D9A708B3B6B866E487DD6FC3BCE5" "52DBB9A2764D42C2E79102B492E163B7746AD3BA3F39F0E9", "03" }, // 5 = 4096 { "C35D11CEC8070891839277F96F9D94BB4C72993B198016E9" "3A4AC49B12F0467B918677BA30D13FA60876C48804A529AA" "B44233344AF70425556A7E1139A5C976C38AD084FA9DF6A4" "0FA1EA011D59A719D37DFBA0440AE76CEC7A762BD9B61AEB" "F598C4002D38166FF5B06717B15CDF8CF6115E623625EEAB" "28AE8A973573379F60927E791A6E3532BF6AEA831F175992" "87A3A382844F3343AEFA8C1E7FF529813872B093B0E6586C" "73FA32DB5709B12A3EE0953EAA5360E5470807C164594801" "9FBDFBB371B3670F6708474570C9E7CC916BD7C12E40546E" "97DE33715C2EAE3409C7DD7FBEB8519C88E2CC315019A00B" "8B4FEB6F876A771F2FEEBBC2E7C19C61BD9B8EBF372FC1BC" "341C24ACD6F0C9386238AED9069177F5732B29CA5F279E9A" "90B9CC9D54992EF488653918E537A941D0A104FC9FA1ABEA" "56157930033CDF1CFFD128E86471518F1AAA773862A44564" "C4B6DB4D2CF839AFF8578656A7805C68206A242A963F1209" "446D581DA6BF948259E60BCF3A394C0285C633892741A1E1" "DC81C35B38CADBF4720FFBB7E1A2153F210A18771AC43170" "AA49DC7104C5E1FFFFB279516C98F39F8056DB2B80666B3B" "1AF2D84D6BB95DB8F36F2B92DD27E9E3B1BDB2C48B2EACE1" "D3D7ABD8EB2BA81C48142A4EC764E3427760330F3AC271E8" "8B157201D185B0DA13925F6AF5AB6CA3141BAFE9A8460A13" "FFAE77AD2629480F", "61AE88E764038448C1C93BFCB7CECA5DA6394C9D8CC00B74" "9D25624D8978233DC8C33BDD18689FD3043B6244025294D5" "5A21199A257B8212AAB53F089CD2E4BB61C568427D4EFB52" "07D0F5008EACD38CE9BEFDD0220573B6763D3B15ECDB0D75" "FACC6200169C0B37FAD8338BD8AE6FC67B08AF311B12F755" "9457454B9AB99BCFB0493F3C8D371A995FB575418F8BACC9" "43D1D1C1422799A1D77D460F3FFA94C09C395849D8732C36" "39FD196DAB84D8951F704A9F5529B072A38403E0B22CA400" "CFDEFDD9B8D9B387B38423A2B864F3E648B5EBE097202A37" "4BEF19B8AE17571A04E3EEBFDF5C28CE44716618A80CD005" "C5A7F5B7C3B53B8F97F75DE173E0CE30DECDC75F9B97E0DE" "1A0E12566B78649C311C576C8348BBFAB99594E52F93CF4D" "485CE64EAA4C977A44329C8C729BD4A0E850827E4FD0D5F5" "2B0ABC98019E6F8E7FE894743238A8C78D553B9C315222B2" "625B6DA6967C1CD7FC2BC32B53C02E34103512154B1F8904" "A236AC0ED35FCA412CF305E79D1CA60142E319C493A0D0F0" "EE40E1AD9C656DFA3907FDDBF0D10A9F90850C3B8D6218B8" "5524EE388262F0FFFFD93CA8B64C79CFC02B6D95C033359D" "8D796C26B5DCAEDC79B795C96E93F4F1D8DED96245975670" "E9EBD5EC7595D40E240A152763B271A13BB019879D6138F4" "458AB900E8C2D86D09C92FB57AD5B6518A0DD7F4D4230509" "FFD73BD69314A407", "02" }, // 6 = 6144 { "A36434E66E419F3BFBBBEB1B1E19C4F33A95B7BC436195EF" "01B04EFB48468421ADDE224DCD9AC862C2304471B32FEA9E" "B86AC936A4E33034C6680302713212A1075CA95278C4E9D4" "9C3633AF87C0E7A8C7DD4476A0CFD3B9CECD02FF8604D858" "FBB4723596364A63FEA9BA9F7EB7D703CD4B03E92944177F" "4AE48AF50D76F2D75412866D884B3E589497A782380C4688" "137DBCEC58BDFA6FD79E426DF8BE0AC46C87DBE3D88D3812" "F6693CD273A7945B843CFFBA2DDF5D7E1242CA96D0175C99" "2BB8B72047DF955C83F57336433BCD0F8BABE3D7366760F7" "4BE32EC8D4FC92684CA6705522BE6153460910FB58B7B17C" "805B31051F1352ADB081381E645AF824D6547F03824B9027" "1B7CED5205DE3361761272F04F71BAD3858DCF145B96DC59" "0223CE318A211785F35219D0F43760A7FFCA5FF4C26D1423" "0EA0883A571908AEE491CB4DAB3D234339F84F8124374EEE" "EEF5081278E1DB90208A266C8C529A54766CE5B3562F05A5" "FFC618EB0000B04FDA6291BFC57104EAE64AB1350F157C84" "D0F8D24023B857E22B784B53AEF2E502B39362924E644553" "68CE0479DA26956BF31DC61B9CD0279F7116DCD5C3CEE6AA" "2E9FB56C4635517E58DE5E39114A51AA107B84B825A69477" "781B27EC2C4E069B7CD1108C69186CA1C6F012C0963C1A3A" "7F87F81C83D2AC8B3B8106EF5998C319B96EAD1B2CC61C4F" "19DC774F97F06015E185A2C3812F4FB10AC3FC113A699C95" "69533B98CDEB398BD791CA2237ACADD27C32A5C088C26298" "DCCD62F79976FE9C7BC4535CB01201B9AB422B6E27EFD66F" "AEFD2262452FE0BF318B7B94118B697053B72BC78283C47B" "DE1B1638607B25D7B668721E1BE49B65D5459433709B5E77" "846EF1B2E33FC5871899E8EB5A95939B31A5D4356D78F0B8" "0C0D29BA939E92646BEEA020F4952051C080C2885697FB18" "41C36E1AD0124F14CCA34A92C9124F08048D6D237BC6EFE4" "B1D4849774DF25A049D9A63C8248A4712F166F6159E05554" "E62FAEF95E06005EEF3EB3B7F3BC074CFE727746A5CB6EBB" "DD46A17FB3723E62B9B56D0D9AFB63DA1D22C40E7EF1332B", "51B21A733720CF9DFDDDF58D8F0CE2799D4ADBDE21B0CAF7" "80D8277DA4234210D6EF1126E6CD643161182238D997F54F" "5C35649B5271981A633401813899095083AE54A93C6274EA" "4E1B19D7C3E073D463EEA23B5067E9DCE766817FC3026C2C" "7DDA391ACB1B2531FF54DD4FBF5BEB81E6A581F494A20BBF" "A572457A86BB796BAA094336C4259F2C4A4BD3C11C062344" "09BEDE762C5EFD37EBCF2136FC5F05623643EDF1EC469C09" "7B349E6939D3CA2DC21E7FDD16EFAEBF0921654B680BAE4C" "95DC5B9023EFCAAE41FAB99B219DE687C5D5F1EB9B33B07B" "A5F197646A7E49342653382A915F30A9A304887DAC5BD8BE" "402D98828F89A956D8409C0F322D7C126B2A3F81C125C813" "8DBE76A902EF19B0BB09397827B8DD69C2C6E78A2DCB6E2C" "8111E718C5108BC2F9A90CE87A1BB053FFE52FFA61368A11" "8750441D2B8C84577248E5A6D59E91A19CFC27C0921BA777" "777A84093C70EDC81045133646294D2A3B3672D9AB1782D2" "FFE30C7580005827ED3148DFE2B882757325589A878ABE42" "687C692011DC2BF115BC25A9D779728159C9B149273222A9" "B467023CED134AB5F98EE30DCE6813CFB88B6E6AE1E77355" "174FDAB6231AA8BF2C6F2F1C88A528D5083DC25C12D34A3B" "BC0D93F61627034DBE688846348C3650E37809604B1E0D1D" "3FC3FC0E41E956459DC08377ACCC618CDCB7568D96630E27" "8CEE3BA7CBF8300AF0C2D161C097A7D88561FE089D34CE4A" "B4A99DCC66F59CC5EBC8E5111BD656E93E1952E04461314C" "6E66B17BCCBB7F4E3DE229AE580900DCD5A115B713F7EB37" "D77E91312297F05F98C5BDCA08C5B4B829DB95E3C141E23D" "EF0D8B1C303D92EBDB34390F0DF24DB2EAA2CA19B84DAF3B" "C23778D9719FE2C38C4CF475AD4AC9CD98D2EA1AB6BC785C" "060694DD49CF493235F750107A4A9028E04061442B4BFD8C" "20E1B70D6809278A6651A549648927840246B691BDE377F2" "58EA424BBA6F92D024ECD31E41245238978B37B0ACF02AAA" "7317D77CAF03002F779F59DBF9DE03A67F393BA352E5B75D" "EEA350BFD9B91F315CDAB686CD7DB1ED0E9162073F789995", "03" }, // 7 = 8192 { "B28A3519440287B15B84ACDBDA263FCD423859654D8051DF" "F8636526CB3057E81002DBAD7BD6BE122D57F8A330032F56" "BC95047CD35546E7BBD4D17BEEAE9FCF4642FA010C292868" "5BD3837A2DF3AC8BE5C500B3462F6545BE251B0AEA037D37" "267221ED07E7F7DBF5F7C4886174932CFB3B46B6CACB6BB7" "DAD31BD96DC8A7E81B9920384378E09DBA8A9838151C057D" "B2CC18229CB241447FEF4FF15866120421A5A4878E6CD263" "782DAC9FA25D192401AEEBACCF8E21411EFFBD8B5F57FD7A" "4DC7696211381BA1D90ED989123FB9E74C77137852392269" "9FB8AD7D178EB98D575DF0CAC6B9F4B4B4BC698C80348EB7" "1CE68EDC003F4FD8F5888C45C32806C5BB65CF747F1ECCEC" "D8F1B353BB2F9044550840BE14900543E6978F521A329597" "9189815A26757E624890C02729513236EAF00387F4479DF0" "A6EDAE7354E13C1D09F922EA5F8A9CB357F3EE9989962BB2" "2DDA93A807DB70495DFDFC657F7781D3AA261BF31C00B54F" "73062597CB72CB6BD8F0E6E8B1CD1ADEBBEAEBFB87907050" "4BE9C5B3B3B12FA0EF12C31D63D36F6960078C6E8EC844EC" "06406BAE50524BDE42713083F02A5988489936BF9CF3D08A" "8A215F7A6BD8DAAB186DC17DDA7F8EB207582947C333C80E" "DA6BD2497451AFFB761273A5BF300488220EDF2A4CFE4F6A" "4A303CC851FE116FA5567558008504D3DA46F96E5D70ADAE" "08386C41BEEE7CCF54CB383E0EFC72513ABB593E844263A2" "F05FA615AB0B7FA3157AFE3CB08C9202996A293C446935F8" "7272C03FC8685361FCEE0E031E0A650410C0F842E00D5383" "A5E247602D5801746D95C07ADA9E66B70F9473F7282DB362" "079309429A2CAB24D66D4CCE5E06E3119557AA1C5FB4B9BF" "B89390D2F051827A896B9D978B1406D74BBC78BC8E4F631C" "D7C812692C5BEEC99DA40420682ED3A12AC3E0CE57CA1091" "4AC37C7C348382A55706C57A85B7E7C7EAF117FA8AF0F1F4" "56EBFE2B2C7C025ACD9A3E821F58AC7290F5754FEBFBA816" "C326EDBC14B212FFEDCD4F22A5C6F7EEEB84951413E7E157" "DCB9A702603E8EFADC6CA125A227D4185D54663F0B4C38E0" "20B406C4CE305FF5FB27E3513F616FE0ED8C7F76553824BC" "A3559D41FA96C73919013103341D30A3E2A835689A2D01B7" "F986E740614E2728E9F659A6874C8CD5A0E71FAC381E25D6" "3A2221EBA6839C1BB205F7A94AC6C579D2A1B862FD9D0E87" "DE0DF24FF4E04C1235B608E5FFDE7D0FE55D8D938E51C125" "2EEFE98F9E6800F875302BFACAD7AE9390B7A09FDA7968EC" "3A5E5784DD9738F38085FB82A4B62C9A40964C414FD7002E" "4CED0337FA02D8FB824DDA3249CE5C3868760E8E032A6A9A" "306A6EEA8C135EC37FF6C30DA9675D9EAC8F383CE8CD98F8" "11442C052041DBEAC2EBFD34CF6BCCBAC85271AEC770FD06" "410473A634D133158C2C15A9F787677B", "59451A8CA20143D8ADC2566DED131FE6A11C2CB2A6C028EF" "FC31B29365982BF408016DD6BDEB5F0916ABFC51980197AB" "5E4A823E69AAA373DDEA68BDF7574FE7A3217D0086149434" "2DE9C1BD16F9D645F2E28059A317B2A2DF128D857501BE9B" "933910F683F3FBEDFAFBE24430BA49967D9DA35B6565B5DB" "ED698DECB6E453F40DCC901C21BC704EDD454C1C0A8E02BE" "D9660C114E5920A23FF7A7F8AC33090210D2D243C7366931" "BC16D64FD12E8C9200D775D667C710A08F7FDEC5AFABFEBD" "26E3B4B1089C0DD0EC876CC4891FDCF3A63B89BC291C9134" "CFDC56BE8BC75CC6ABAEF865635CFA5A5A5E34C6401A475B" "8E73476E001FA7EC7AC44622E1940362DDB2E7BA3F8F6676" "6C78D9A9DD97C8222A84205F0A4802A1F34BC7A90D194ACB" "C8C4C0AD133ABF312448601394A8991B757801C3FA23CEF8" "5376D739AA709E0E84FC91752FC54E59ABF9F74CC4CB15D9" "16ED49D403EDB824AEFEFE32BFBBC0E9D5130DF98E005AA7" "B98312CBE5B965B5EC78737458E68D6F5DF575FDC3C83828" "25F4E2D9D9D897D07789618EB1E9B7B4B003C63747642276" "032035D7282925EF21389841F8152CC4244C9B5FCE79E845" "4510AFBD35EC6D558C36E0BEED3FC75903AC14A3E199E407" "6D35E924BA28D7FDBB0939D2DF98024411076F95267F27B5" "25181E6428FF08B7D2AB3AAC00428269ED237CB72EB856D7" "041C3620DF773E67AA659C1F077E39289D5DAC9F422131D1" "782FD30AD585BFD18ABD7F1E584649014CB5149E22349AFC" "3939601FE43429B0FE7707018F05328208607C217006A9C1" "D2F123B016AC00BA36CAE03D6D4F335B87CA39FB9416D9B1" "03C984A14D1655926B36A6672F037188CAABD50E2FDA5CDF" "DC49C8697828C13D44B5CECBC58A036BA5DE3C5E4727B18E" "6BE40934962DF764CED20210341769D09561F0672BE50848" "A561BE3E1A41C152AB8362BD42DBF3E3F5788BFD457878FA" "2B75FF15963E012D66CD1F410FAC5639487ABAA7F5FDD40B" "619376DE0A59097FF6E6A79152E37BF775C24A8A09F3F0AB" "EE5CD381301F477D6E365092D113EA0C2EAA331F85A61C70" "105A036267182FFAFD93F1A89FB0B7F076C63FBB2A9C125E" "51AACEA0FD4B639C8C8098819A0E9851F1541AB44D1680DB" "FCC373A030A7139474FB2CD343A6466AD0738FD61C0F12EB" "1D1110F5D341CE0DD902FBD4A56362BCE950DC317ECE8743" "EF06F927FA7026091ADB0472FFEF3E87F2AEC6C9C728E092" "9777F4C7CF34007C3A9815FD656BD749C85BD04FED3CB476" "1D2F2BC26ECB9C79C042FDC1525B164D204B2620A7EB8017" "2676819BFD016C7DC126ED1924E72E1C343B07470195354D" "183537754609AF61BFFB6186D4B3AECF56479C1E7466CC7C" "08A216029020EDF56175FE9A67B5E65D642938D763B87E83" "208239D31A68998AC6160AD4FBC3B3BD", "03" }, // 8 = end of list {NULL, NULL, NULL}, }; //------------------------------------------------------------------------- static size_t toIndex(IDHKeyDomain::KeyDomainPrecompiledTypes length) { switch (length) { case IDHKeyDomain::KeyDomainPrecompiledType_Unknown: return 0; case IDHKeyDomain::KeyDomainPrecompiledType_1024: return 1; case IDHKeyDomain::KeyDomainPrecompiledType_1538: return 2; case IDHKeyDomain::KeyDomainPrecompiledType_2048: return 3; case IDHKeyDomain::KeyDomainPrecompiledType_3072: return 4; case IDHKeyDomain::KeyDomainPrecompiledType_4096: return 5; case IDHKeyDomain::KeyDomainPrecompiledType_6144: return 6; case IDHKeyDomain::KeyDomainPrecompiledType_8192: return 7; } return 0; } //------------------------------------------------------------------------- static IDHKeyDomain::KeyDomainPrecompiledTypes fromIndex(size_t index) { switch (index) { case 0: return IDHKeyDomain::KeyDomainPrecompiledType_Unknown; case 1: return IDHKeyDomain::KeyDomainPrecompiledType_1024; case 2: return IDHKeyDomain::KeyDomainPrecompiledType_1538; case 3: return IDHKeyDomain::KeyDomainPrecompiledType_2048; case 4: return IDHKeyDomain::KeyDomainPrecompiledType_3072; case 5: return IDHKeyDomain::KeyDomainPrecompiledType_4096; case 6: return IDHKeyDomain::KeyDomainPrecompiledType_6144; case 7: return IDHKeyDomain::KeyDomainPrecompiledType_8192; } return IDHKeyDomain::KeyDomainPrecompiledType_Unknown; } //----------------------------------------------------------------------- static Log::Params slog(const char *message) { return Log::Params(message, "stack::DHKeyDomain"); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHKeyDomain #pragma mark //----------------------------------------------------------------------- DHKeyDomain::DHKeyDomain(const make_private &) { ZS_LOG_DEBUG(log("created")) } //----------------------------------------------------------------------- DHKeyDomain::~DHKeyDomain() { if(isNoop()) return; ZS_LOG_DEBUG(log("destroyed")) } //----------------------------------------------------------------------- DHKeyDomainPtr DHKeyDomain::convert(IDHKeyDomainPtr publicKey) { return ZS_DYNAMIC_PTR_CAST(DHKeyDomain, publicKey); } //----------------------------------------------------------------------- DHKeyDomainPtr DHKeyDomain::convert(ForDHPrivateKeyPtr object) { return ZS_DYNAMIC_PTR_CAST(DHKeyDomain, object); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHKeyDomain => IDHKeyDomain #pragma mark //----------------------------------------------------------------------- ElementPtr DHKeyDomain::toDebug(IDHKeyDomainPtr keyDomain) { if (!keyDomain) return ElementPtr(); return convert(keyDomain)->toDebug(); } //----------------------------------------------------------------------- DHKeyDomainPtr DHKeyDomain::generate(size_t keySizeInBits) { DHKeyDomainPtr pThis(make_shared<DHKeyDomain>(make_private{})); AutoSeededRandomPool rnd; pThis->mDH.AccessGroupParameters().GenerateRandomWithKeySize(rnd, static_cast<unsigned int>(keySizeInBits)); ZS_THROW_UNEXPECTED_ERROR_IF(!pThis->validate()) // why would we generate something that doesn't pass?? ZS_LOG_DEBUG(pThis->debug("generated key domain")) return pThis; } //----------------------------------------------------------------------- DHKeyDomainPtr DHKeyDomain::loadPrecompiled( KeyDomainPrecompiledTypes precompiledKey, bool validate ) { size_t index = toIndex(precompiledKey); const char *pStr = sDHPrecompiles[index].mP; const char *qStr = sDHPrecompiles[index].mQ; const char *gStr = sDHPrecompiles[index].mG; if ((!pStr) || (!qStr) || (!gStr)) { ZS_LOG_ERROR(Detail, slog("precompiled key is not valid") + ZS_PARAM("length", precompiledKey)) return DHKeyDomainPtr(); } Integer p((String("0x") + pStr).c_str()); Integer q((String("0x") + qStr).c_str()); Integer g((String("0x") + gStr).c_str()); SecureByteBlock resultP(p.MinEncodedSize()); SecureByteBlock resultQ(q.MinEncodedSize()); SecureByteBlock resultG(g.MinEncodedSize()); p.Encode(resultP, resultP.SizeInBytes()); q.Encode(resultQ, resultQ.SizeInBytes()); g.Encode(resultG, resultG.SizeInBytes()); DHKeyDomainPtr pThis = load(resultP, resultQ, resultG, validate); ZS_THROW_BAD_STATE_IF(!pThis) // this can't fail ZS_LOG_DEBUG(pThis->log("loading predefined key domain") + ZS_PARAM("length", precompiledKey) + ZS_PARAM("p", pStr) + ZS_PARAM("q", qStr) + ZS_PARAM("g", gStr)) return pThis; } //----------------------------------------------------------------------- IDHKeyDomain::KeyDomainPrecompiledTypes DHKeyDomain::getPrecompiledType() const { SecureByteBlock p; SecureByteBlock q; SecureByteBlock g; save(p, q, g); String pStr = IHelper::convertToHex(p, true); String qStr = IHelper::convertToHex(q, true); String gStr = IHelper::convertToHex(g, true); for (size_t index = 0; true; ++index) { KeyDomainPrecompiledTypes type = fromIndex(index); const char *pCompare = sDHPrecompiles[index].mP; const char *qCompare = sDHPrecompiles[index].mQ; const char *gCompare = sDHPrecompiles[index].mG; if ((pCompare) && (qCompare) && (gCompare)) { if (pStr != pCompare) continue; if (qStr != qCompare) continue; if (gStr != gCompare) continue; ZS_LOG_TRACE(log("found match to precompiled key") + ZS_PARAM("precompiled key", toNamespace(type))) return type; } if (KeyDomainPrecompiledType_Last == type) { break; } } ZS_LOG_TRACE(log("did not find match to any precompiled key")) return KeyDomainPrecompiledType_Unknown; } //----------------------------------------------------------------------- DHKeyDomainPtr DHKeyDomain::load( const SecureByteBlock &inP, const SecureByteBlock &inQ, const SecureByteBlock &inG, bool validate ) { DHKeyDomainPtr pThis(make_shared<DHKeyDomain>(make_private{})); try { Integer p(inP, inP.SizeInBytes()); Integer q(inQ, inQ.SizeInBytes()); Integer g(inG, inG.SizeInBytes()); pThis->mDH.AccessGroupParameters().Initialize(p, q, g); if (validate) { if (!pThis->validate()) { ZS_LOG_ERROR(Debug, pThis->log("failed to load key domain") + ZS_PARAM("p", IHelper::convertToHex(inP, true)) + ZS_PARAM("q", IHelper::convertToHex(inQ, true)) + ZS_PARAM("g", IHelper::convertToHex(inG, true))) return DHKeyDomainPtr(); } } } catch (CryptoPP::Exception &e) { ZS_LOG_ERROR(Basic, pThis->log("cryptography library threw an exception") + ZS_PARAM("what", e.what())) return DHKeyDomainPtr(); } ZS_LOG_DEBUG(pThis->debug("loaded key domain")) return pThis; } //----------------------------------------------------------------------- void DHKeyDomain::save( SecureByteBlock &outP, SecureByteBlock &outQ, SecureByteBlock &outG ) const { Integer p = mDH.GetGroupParameters().GetModulus(); Integer q = mDH.GetGroupParameters().GetSubgroupOrder(); Integer g = mDH.GetGroupParameters().GetGenerator(); outP.CleanNew(p.MinEncodedSize()); outQ.CleanNew(q.MinEncodedSize()); outG.CleanNew(g.MinEncodedSize()); p.Encode(outP, outP.SizeInBytes()); q.Encode(outQ, outQ.SizeInBytes()); g.Encode(outG, outG.SizeInBytes()); ZS_LOG_TRACE(debug("save called")) } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHKeyDomain => IDHKeyDomainForDHPrivateKey #pragma mark //----------------------------------------------------------------------- DHKeyDomain::DH &DHKeyDomain::getDH() const { return mDH; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark DHKeyDomain => (internal) #pragma mark //----------------------------------------------------------------------- Log::Params DHKeyDomain::log(const char *message) const { ElementPtr objectEl = Element::create("stack::DHKeyDomain"); IHelper::debugAppend(objectEl, "id", mID); return Log::Params(message, objectEl); } //----------------------------------------------------------------------- Log::Params DHKeyDomain::debug(const char *message) const { return Log::Params(message, toDebug()); } //----------------------------------------------------------------------- ElementPtr DHKeyDomain::toDebug() const { ElementPtr resultEl = Element::create("stack::DHKeyDomain"); Integer p = mDH.GetGroupParameters().GetModulus(); Integer q = mDH.GetGroupParameters().GetSubgroupOrder(); Integer g = mDH.GetGroupParameters().GetGenerator(); SecureByteBlock outP(p.MinEncodedSize()); SecureByteBlock outQ(q.MinEncodedSize()); SecureByteBlock outG(g.MinEncodedSize()); p.Encode(outP, outP.SizeInBytes()); q.Encode(outQ, outQ.SizeInBytes()); g.Encode(outG, outG.SizeInBytes()); IHelper::debugAppend(resultEl, "id", mID); IHelper::debugAppend(resultEl, "p", IHelper::convertToHex(outP, true)); IHelper::debugAppend(resultEl, "q", IHelper::convertToHex(outQ, true)); IHelper::debugAppend(resultEl, "g", IHelper::convertToHex(outG, true)); IHelper::debugAppend(resultEl, "p bit-count", p.BitCount()); IHelper::debugAppend(resultEl, "q bit-count", q.BitCount()); IHelper::debugAppend(resultEl, "g bit-count", g.BitCount()); return resultEl; } //----------------------------------------------------------------------- bool DHKeyDomain::validate() const { ZS_LOG_DEBUG(log("validating key domain")) try { AutoSeededRandomPool rnd; if(!mDH.GetGroupParameters().ValidateGroup(rnd, 3)) { ZS_LOG_ERROR(Detail, log("failed to validate key domain")) return false; } Integer p = mDH.GetGroupParameters().GetModulus(); Integer q = mDH.GetGroupParameters().GetSubgroupOrder(); Integer g = mDH.GetGroupParameters().GetGenerator(); Integer v = ModularExponentiation(g, q, p); if(v != Integer::One()) { ZS_LOG_ERROR(Detail, log("failed to verify order of the subgroup")) } } catch (CryptoPP::Exception &e) { ZS_LOG_ERROR(Basic, log("cryptography library threw an exception") + ZS_PARAM("what", e.what())) return false; } return true; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- #pragma mark #pragma mark IDHKeyDomainFactory #pragma mark //----------------------------------------------------------------------- IDHKeyDomainFactory &IDHKeyDomainFactory::singleton() { return DHKeyDomainFactory::singleton(); } //----------------------------------------------------------------------- DHKeyDomainPtr IDHKeyDomainFactory::generate(size_t keySizeInBits) { if (this) {} return DHKeyDomain::generate(keySizeInBits); } //----------------------------------------------------------------------- DHKeyDomainPtr IDHKeyDomainFactory::loadPrecompiled( IDHKeyDomain::KeyDomainPrecompiledTypes precompiledKey, bool validate ) { if (this) {} return DHKeyDomain::loadPrecompiled(precompiledKey, validate); } //----------------------------------------------------------------------- DHKeyDomainPtr IDHKeyDomainFactory::load( const SecureByteBlock &p, const SecureByteBlock &q, const SecureByteBlock &g, bool validate ) { if (this) {} return DHKeyDomain::load(p, q, g, validate); } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- //------------------------------------------------------------------------- #pragma mark #pragma mark IDHKeyDomain #pragma mark //------------------------------------------------------------------------- const char *IDHKeyDomain::toNamespace(KeyDomainPrecompiledTypes length) { switch (length) { case KeyDomainPrecompiledType_Unknown: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_UNKNOWN; case KeyDomainPrecompiledType_1024: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_1024; case KeyDomainPrecompiledType_1538: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_1538; case KeyDomainPrecompiledType_2048: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_2048; case KeyDomainPrecompiledType_3072: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_3072; case KeyDomainPrecompiledType_4096: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_4096; case KeyDomainPrecompiledType_6144: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_6144; case KeyDomainPrecompiledType_8192: return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_8192; } return ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_UNKNOWN; } //------------------------------------------------------------------------- IDHKeyDomain::KeyDomainPrecompiledTypes IDHKeyDomain::fromNamespace(const char *inNamespace) { if (!inNamespace) return KeyDomainPrecompiledType_Unknown; if ('\0' == *inNamespace) return KeyDomainPrecompiledType_Unknown; if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_1024)) { return KeyDomainPrecompiledType_1024; } if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_1538)) { return KeyDomainPrecompiledType_1538; } if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_2048)) { return KeyDomainPrecompiledType_2048; } if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_3072)) { return KeyDomainPrecompiledType_3072; } if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_4096)) { return KeyDomainPrecompiledType_4096; } if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_6144)) { return KeyDomainPrecompiledType_6144; } if (0 == strcmp(inNamespace, ORTC_SERVICES_DH_KEY_DOMAIN_NAMESPACE_8192)) { return KeyDomainPrecompiledType_8192; } return KeyDomainPrecompiledType_Unknown; } //------------------------------------------------------------------------- ElementPtr IDHKeyDomain::toDebug(IDHKeyDomainPtr keyDomain) { return internal::DHKeyDomain::toDebug(keyDomain); } //------------------------------------------------------------------------- IDHKeyDomainPtr IDHKeyDomain::generate(size_t keySizeInBits) { return internal::IDHKeyDomainFactory::singleton().generate(keySizeInBits); } //------------------------------------------------------------------------- IDHKeyDomainPtr IDHKeyDomain::loadPrecompiled( KeyDomainPrecompiledTypes precompiledKey, bool validate ) { return internal::IDHKeyDomainFactory::singleton().loadPrecompiled(precompiledKey, validate); } //------------------------------------------------------------------------- IDHKeyDomainPtr IDHKeyDomain::load( const SecureByteBlock &p, const SecureByteBlock &q, const SecureByteBlock &g, bool validate ) { return internal::IDHKeyDomainFactory::singleton().load(p, q, g, validate); } } }
45.44
224
0.617329
ortclib
85e775ca102104c226b60ec5f0442c1e88b31b1d
820
cpp
C++
iceoryx_utils/source/cxx/helplets.cpp
surendra210/iceoryx
f964c2435f65585784b2d77af0ce39f88670fb36
[ "Apache-2.0" ]
null
null
null
iceoryx_utils/source/cxx/helplets.cpp
surendra210/iceoryx
f964c2435f65585784b2d77af0ce39f88670fb36
[ "Apache-2.0" ]
null
null
null
iceoryx_utils/source/cxx/helplets.cpp
surendra210/iceoryx
f964c2435f65585784b2d77af0ce39f88670fb36
[ "Apache-2.0" ]
1
2020-04-06T04:56:24.000Z
2020-04-06T04:56:24.000Z
#include "iceoryx_utils/cxx/helplets.hpp" namespace iox { namespace cxx { void* alignedAlloc(const uint64_t alignment, const uint64_t size) noexcept { // -1 == since the max alignment addition is alignment - 1 otherwise the // memory is already aligned and we have to do nothing uint64_t memory = reinterpret_cast<uint64_t>(malloc(size + alignment + sizeof(void*) - 1)); if (memory == 0) { return nullptr; } uint64_t alignedMemory = align(memory + sizeof(void*), alignment); reinterpret_cast<void**>(alignedMemory)[-1] = reinterpret_cast<void*>(memory); return reinterpret_cast<void*>(alignedMemory); } void alignedFree(void* const memory) { if (memory != nullptr) { free(reinterpret_cast<void**>(memory)[-1]); } } } // namespace cxx } // namespace iox
26.451613
95
0.678049
surendra210
85ead77ea53a923e8bf2340f8691d7658f844f7c
479
cc
C++
unit_tests/test_hash_table.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
2
2019-03-22T05:01:03.000Z
2020-05-07T11:26:03.000Z
unit_tests/test_hash_table.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
unit_tests/test_hash_table.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
// Copyright (c) 2019, MaiHD. All right reversed. // License: Unlicensed #include <riku/hash_table.h> #include "./unit_test.h" TEST_CASE("HashTable", "[hash_table]") { HashTable<int> hash_table; REQUIRE(hash_table.set(10, 10)); REQUIRE(hash_table.set(11, 10)); REQUIRE(hash_table.set(12, 10)); REQUIRE(hash_table.set(13, 10)); REQUIRE(hash_table.set(14, 10)); int value; REQUIRE(hash_table.try_get(14, &value)); REQUIRE(value == 10); }
23.95
49
0.655532
maihd
85f19483070af937ed75b8f665717cf6aee2daab
932
hpp
C++
tmpl/stack5assign.hpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
tmpl/stack5assign.hpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
tmpl/stack5assign.hpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
/* The following code example is taken from the book * "Object-Oriented Programming in C++" * by Nicolai M. Josuttis, Wiley, 2002 * * (C) Copyright Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ template <typename T> template <typename T2> Stack<T>& Stack<T>::operator= (const Stack<T2>& op2) { if ((void*)this == (void*)&op2) { // assignment to itself? return *this; } Stack<T2> tmp(op2); // create a copy of the assigned stack elems.clear(); // remove existing elements while (!tmp.empty()) { // copy all elements elems.push_front(tmp.top()); tmp.pop(); } return *this; }
33.285714
75
0.633047
angusoutlook
85f817c640d1d8ffefc8eceef637c85ec48697db
1,771
cpp
C++
gp/core/GameEngine.cpp
kymani37299/GraphicsPlayground
f39eac719d7473d2c99255c7a600d52507921728
[ "MIT" ]
null
null
null
gp/core/GameEngine.cpp
kymani37299/GraphicsPlayground
f39eac719d7473d2c99255c7a600d52507921728
[ "MIT" ]
null
null
null
gp/core/GameEngine.cpp
kymani37299/GraphicsPlayground
f39eac719d7473d2c99255c7a600d52507921728
[ "MIT" ]
null
null
null
#include "GameEngine.h" #include <chrono> #include "Common.h" #include "core/Window.h" #include "core/Renderer.h" #include "core/Controller.h" #include "core/Loading.h" #include "gfx/GfxDevice.h" namespace GP { LoadingThread* g_LoadingThread; PoisonPillTask* PoisonPillTask::s_Instance = nullptr; GameEngine::GameEngine() { m_Renderer = new Renderer(); m_Controller = new Controller(); g_LoadingThread = new LoadingThread(); } GameEngine::~GameEngine() { delete g_LoadingThread; delete m_Renderer; delete m_Controller; } void GameEngine::UpdateDT() { static auto t_before = std::chrono::high_resolution_clock::now(); auto t_now = std::chrono::high_resolution_clock::now(); m_DT = std::chrono::duration<float, std::milli>(t_now - t_before).count(); t_before = t_now; } void GameEngine::Run() { Window* wnd = Window::Get(); ASSERT(wnd->IsRunning(), "Trying to run an engine without a window!"); GameLoop(); m_FirstFrame = false; while (wnd->IsRunning()) { WindowInput::InputFrameBegin(); GameLoop(); WindowInput::InputFrameEnd(); } } void GameEngine::Reset() { if (g_LoadingThread) g_LoadingThread->ResetAndWait(); m_Renderer->Reset(); } void GameEngine::GameLoop() { UpdateDT(); Window::Get()->Update(m_DT); m_Controller->UpdateInput(m_DT); m_Renderer->Update(m_DT); m_Renderer->RenderIfShould(); Logger::Get()->DispatchLogs(); } namespace Input { bool IsKeyPressed(unsigned int key) { return WindowInput::IsKeyPressed(key); } bool IsKeyJustPressed(unsigned int key) { return WindowInput::IsKeyJustPressed(key); } Vec2 GetMousePos() { return WindowInput::GetMousePos(); } Vec2 GetMouseDelta() { return WindowInput::GetMouseDelta(); } } }
18.642105
76
0.689441
kymani37299
c803a5fbdef106b5d5e4328258d52d493bcdd90a
532
cpp
C++
tests/filesystem/get_umask.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
tests/filesystem/get_umask.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
tests/filesystem/get_umask.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
#include <sys/types.h> #include <sys/stat.h> #include <filesystem.h> #include "get_umask.h" using fs::get_umask; START_TEST(should_get_umask) { mode_t m(get_umask()); mode_t expected(umask(0)); fail_unless(m == expected, "value 1"); umask(expected); get_umask(); m = get_umask(); fail_unless(m == expected, "value 2"); } END_TEST namespace fs { namespace test { TCase* create_get_umask_tcase() { TCase* tcase(tcase_create("fs::get_umask")); tcase_add_test(tcase, should_get_umask); return tcase; } } // test } // fs
16.121212
45
0.699248
sugawaray
659fab3988ab51597ab3392e29f2e90b410c6056
990
cpp
C++
luogu/problems/P3174.cpp
songhn233/ACM_Steps
6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe
[ "CC0-1.0" ]
1
2020-08-10T21:40:21.000Z
2020-08-10T21:40:21.000Z
luogu/problems/P3174.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
luogu/problems/P3174.cpp
songhn233/Algorithm-Packages
56d6f3c2467c175ab8a19b82bdfb25fc881e2206
[ "CC0-1.0" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=600050; int n,m; int f[maxn]; int head[maxn],num,ans; struct node{ int v,nex; }e[maxn]; inline int read() { int x=0,t=1;char ch=getchar(); while(ch>'9'||ch<'0'){if(ch=='-')t=-1;ch=getchar();} while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar(); return x*t; } void add(int u,int v) { e[++num].nex=head[u]; e[num].v=v; head[u]=num; } void dfs(int u,int fa) { f[u]=1; int temp=0,maxx=0,smaxx=0; for(int i=head[u];i;i=e[i].nex) { int v=e[i].v; if(v==fa) continue; temp++; dfs(v,u); if(f[v]>maxx) { smaxx=maxx; maxx=f[v]; } else if(f[v]>smaxx) smaxx=f[v]; } if(temp>=1) f[u]+=maxx+temp-1; if(temp==1) ans=max(ans,f[u]); if(temp>=2) ans=max(ans,max(f[u],maxx+smaxx+temp-1+(u==1?0:1))); } int main() { n=read(),m=read(); for(int i=1;i<=n-1;i++) { int x,y; x=read(),y=read(); add(x,y),add(y,x); } dfs(1,0); cout<<ans<<endl; return 0; }
16.229508
65
0.566667
songhn233
65a60c1e7871a26a1b12748387f5dce3eec8f220
956
cpp
C++
c++/leetcode/0463-Island_Perimeter-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0463-Island_Perimeter-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0463-Island_Perimeter-E.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 463 Island Perimeter // https://leetcode.com/problems/island-perimeter // version: 1; create time: 2020-02-08 15:48:08; class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int perimeter = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j] == 1) { constexpr int offsets[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; for (int k = 0; k < 4; ++k) { int ii = offsets[k][0] + i; int jj = offsets[k][1] + j; if (ii < 0 || ii >= grid.size() || jj < 0 || jj >= grid[0].size()) { ++perimeter; } else { perimeter += grid[ii][jj] != 1; } } } } } return perimeter; } };
34.142857
92
0.365063
levendlee
65a733433c0e7f437e72975fca0ce5767a723e03
3,391
cpp
C++
src/plugins/dbusmanager/tasks.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/dbusmanager/tasks.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/dbusmanager/tasks.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "tasks.h" #include <QAbstractItemModel> #include <interfaces/ijobholder.h> #include <interfaces/iinfo.h> #include <interfaces/core/icoreproxy.h> #include <interfaces/core/ipluginsmanager.h> #include "core.h" namespace LeechCraft { namespace DBusManager { Tasks::Tasks (QObject *parent) : QObject (parent) { } QStringList Tasks::GetHolders () const { QObjectList plugins = Core::Instance ().GetProxy ()-> GetPluginsManager ()->GetAllCastableRoots<IJobHolder*> (); QStringList result; Q_FOREACH (QObject *plugin, plugins) result << qobject_cast<IInfo*> (plugin)->GetName (); return result; } int Tasks::RowCount (const QString& name) const { QObjectList plugins = Core::Instance ().GetProxy ()-> GetPluginsManager ()->GetAllCastableRoots<IJobHolder*> (); Q_FOREACH (QObject *plugin, plugins) { if (qobject_cast<IInfo*> (plugin)->GetName () != name) continue; QAbstractItemModel *model = qobject_cast<IJobHolder*> (plugin)->GetRepresentation (); return model->rowCount (); } throw tr ("Not found job holder %1.") .arg (name); } QVariantList Tasks::GetData (const QString& name, int r, int role) const { QObjectList plugins = Core::Instance ().GetProxy ()-> GetPluginsManager ()->GetAllCastableRoots<IJobHolder*> (); Q_FOREACH (QObject *plugin, plugins) { if (qobject_cast<IInfo*> (plugin)->GetName () != name) continue; QAbstractItemModel *model = qobject_cast<IJobHolder*> (plugin)->GetRepresentation (); QVariantList result; for (int i = 0, size = model->columnCount (); i < size; ++i) result << model->index (r, i).data (role); return result; } throw tr ("Not found job holder %1.") .arg (name); } } }
33.91
78
0.688293
MellonQ
65aa362ec6d9b7d97a8d5eb1893a58dc4d2a3ddd
894
cpp
C++
arti_base_control/test/test_wheel.cpp
ARTI-Robots/base_control
858edf33452ee6058b77299dc0e32ea7d7028778
[ "BSD-2-Clause" ]
null
null
null
arti_base_control/test/test_wheel.cpp
ARTI-Robots/base_control
858edf33452ee6058b77299dc0e32ea7d7028778
[ "BSD-2-Clause" ]
null
null
null
arti_base_control/test/test_wheel.cpp
ARTI-Robots/base_control
858edf33452ee6058b77299dc0e32ea7d7028778
[ "BSD-2-Clause" ]
null
null
null
// // Created by abuchegger on 08.07.18. // #include <gtest/gtest.h> #include <cmath> #include <memory> #include <arti_base_control/steering.h> #include <arti_base_control/wheel.h> TEST(WheelTest, SimpleFrontWheelTest) { const arti_base_control::Wheel wheel(1.0, 0.0, 0.0, 0.5, std::make_shared<arti_base_control::IdealAckermannSteering>(0.0)); EXPECT_DOUBLE_EQ(2.0, wheel.computeWheelVelocity(1.0, 0.0, 0.0, 0.0)); EXPECT_DOUBLE_EQ(2.0 * std::sqrt(2.0), wheel.computeWheelVelocity(1.0, 1.0, 0.0, 0.0)); EXPECT_DOUBLE_EQ(2.0 * std::sqrt(2.0), wheel.computeWheelVelocity(1.0, -1.0, 0.0, 0.0)); EXPECT_DOUBLE_EQ(-2.0 * std::sqrt(2.0), wheel.computeWheelVelocity(-1.0, 1.0, 0.0, 0.0)); EXPECT_DOUBLE_EQ(-2.0 * std::sqrt(2.0), wheel.computeWheelVelocity(-1.0, -1.0, 0.0, 0.0)); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.76
125
0.695749
ARTI-Robots
65acad13067b8ba75d80e2e38ed286736746ad85
840
cpp
C++
lib/test/AddressTest.cpp
glbwsk/oop
7856a909bfdd197dc13c0f6945ef9c6e00aaa889
[ "MIT" ]
1
2020-07-02T17:16:29.000Z
2020-07-02T17:16:29.000Z
lib/test/AddressTest.cpp
glbwsk/oop
7856a909bfdd197dc13c0f6945ef9c6e00aaa889
[ "MIT" ]
null
null
null
lib/test/AddressTest.cpp
glbwsk/oop
7856a909bfdd197dc13c0f6945ef9c6e00aaa889
[ "MIT" ]
1
2021-05-28T13:13:19.000Z
2021-05-28T13:13:19.000Z
#include <boost/test/unit_test.hpp> #include "Address.hpp" /* Unit tests for Adress.hpp */ /* correct */ BOOST_AUTO_TEST_SUITE( AddressSuiteCorrect ) BOOST_AUTO_TEST_CASE( ctor_default ) { Address newAddress1; BOOST_CHECK_EQUAL( newAddress1.getStreet(), "null" ); BOOST_CHECK_EQUAL( newAddress1.getCity(), "null" ); BOOST_CHECK_EQUAL( newAddress1.getPostalCode(), "null" ); BOOST_CHECK_EQUAL( newAddress1.getApartmentNum(), 0 ); } BOOST_AUTO_TEST_CASE( ctor ) { Address newAdress1( "ulica", "miasto", "11-235", 5 ); BOOST_CHECK_EQUAL( newAdress1.getStreet(), "ulica" ); BOOST_CHECK_EQUAL( newAdress1.getCity(), "miasto" ); BOOST_CHECK_EQUAL( newAdress1.getPostalCode(), "11-235" ); BOOST_CHECK_EQUAL( newAdress1.getApartmentNum(), 5 ); } BOOST_AUTO_TEST_SUITE_END()
28.965517
63
0.695238
glbwsk
65ba7bd9b3e2f7083f5f5fc2ffa8c9d9f3c1a275
1,258
cc
C++
examples/boil/test/test.cc
BvB93/noodles
7547471baa18a11b8020c017388a7e208d194ef4
[ "Apache-2.0" ]
22
2016-07-26T20:42:08.000Z
2022-02-08T16:04:25.000Z
examples/boil/test/test.cc
BvB93/noodles
7547471baa18a11b8020c017388a7e208d194ef4
[ "Apache-2.0" ]
71
2015-12-24T18:44:32.000Z
2022-02-11T11:31:08.000Z
examples/boil/test/test.cc
BvB93/noodles
7547471baa18a11b8020c017388a7e208d194ef4
[ "Apache-2.0" ]
8
2016-12-22T10:14:28.000Z
2020-06-05T21:01:51.000Z
#include "test.hh" #include <iostream> #include <sstream> int __assert_fail(std::string const &expr, std::string const &file, int lineno) { std::ostringstream oss; oss << file << ":" << lineno << ": Assertion failed: " << expr; throw oss.str(); return 0; } std::unique_ptr<std::map<std::string, Test const *>> Test::_instances; Test::imap &Test::instances() { if (not _instances) _instances = std::unique_ptr<imap>(new imap); return *_instances; } bool run_test(Test const *unit) { bool pass; try { pass = (*unit)(); } catch (char const *e) { pass = false; std::cerr << "failure: " << e << std::endl; } catch (std::string const &e) { pass = false; std::cerr << "failure: " << e << std::endl; } if (pass) { std::cerr << "\033[62G[\033[32mpassed\033[m]\n"; } else { std::cerr << "\033[62G[\033[31mfailed\033[m]\n"; } return pass; } void Test::all(bool should_break) { for (auto &kv : instances()) { std::cerr << "[test \033[34;1m" << kv.first << "\033[m]\n"; if (not run_test(kv.second) and should_break) break; } } Test::Test(std::string const &name_, std::function<bool ()> const &code_): _name(name_), code(code_) { instances()[_name] = this; } Test::~Test() { instances().erase(_name); }
20.290323
79
0.605723
BvB93
65bc96015615bc4e8c669184bd1bb2b8efb0839d
2,237
cpp
C++
src/pd/dm300.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
src/pd/dm300.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
src/pd/dm300.cpp
mtribiere/Pixel-dungeon-CPP
ed930aaeefd1f08eed73ced928acae6e1fe34fa4
[ "MIT" ]
null
null
null
#include "dm300.h" #include "mobsprite.h" #include "dungeon.h" #include "statistics.h" #include "terrain.h" #include "glog.h" #include "cellemitter.h" #include "speck.h" #include "gamescene.h" #include "hero.h" CharSprite* DM300::Sprite() { return new DM300Sprite(); } Mob* DM300::CreateDM300() { return new DM300(); } DM300::DM300() { name = Dungeon::depth == Statistics::deepestFloor ? "DM-300" : "DM-350"; //spriteClass = DM300Sprite.class; HP = HT = 200; EXP = 30; _defenseSkill = 18; //loot = new RingOfThorns().random(); lootChance = 0.333f; } int DM300::damageRoll() { return Random::NormalIntRange(18, 24); } bool DM300::act() { //GameScene.add(Blob.seed(pos, 30, ToxicGas.class)); return Mob::act(); } void DM300::move(int step) { Mob::move(step); if (Dungeon::level->map[step] == Terrain::INACTIVE_TRAP && HP < HT) { HP += Random::Int(1, HT - HP); //sprite->emitter()->burst(ElmoParticle.FACTORY, 5); if (Dungeon::visible[step] && Dungeon::hero->isAlive()) { GLog::n("DM-300 repairs itself!"); } } int cells[] = { step - 1, step + 1, step - Level::WIDTH, step + Level::WIDTH, step - 1 - Level::WIDTH, step - 1 + Level::WIDTH, step + 1 - Level::WIDTH, step + 1 + Level::WIDTH }; int cell = cells[Random::Int(sizeof(cells)/sizeof(int))]; if (Dungeon::visible[cell]) { CellEmitter::get(cell)->start(Speck::factory(Speck::ROCK), 0.07f, 10); Camera::mainCamera->shake(3, 0.7f); //Sample.INSTANCE.play(Assets.SND_ROCKS); if (Level::water[cell]) { GameScene::ripple(cell); } else if (Dungeon::level->map[cell] == Terrain::EMPTY) { Level::set(cell, Terrain::EMPTY_DECO); GameScene::updateMap(cell); } } Char* ch = Actor::findChar(cell); if (ch != NULL && ch != this) { //Buff.prolong(ch, Paralysis.class, 2); } } void DM300::die(const std::string& cause) { Mob::die(cause); GameScene::bossSlain(); //Dungeon::level->drop(new SkeletonKey(), pos).sprite.drop(); //Badges::validateBossSlain(); yell("Mission failed. Shutting down."); } void DM300::notice() { Mob::notice(); yell("Unauthorised personnel detected."); }
20.153153
74
0.604828
mtribiere
65c6c290347b74ee5c793d221cf5b1185a7ff330
4,131
hpp
C++
lib/include/drivers/spi/detail/write_dma.hpp
niclasberg/asfw
f836de1c0d6350541e3253863dedab6a3eb81df7
[ "MIT" ]
null
null
null
lib/include/drivers/spi/detail/write_dma.hpp
niclasberg/asfw
f836de1c0d6350541e3253863dedab6a3eb81df7
[ "MIT" ]
null
null
null
lib/include/drivers/spi/detail/write_dma.hpp
niclasberg/asfw
f836de1c0d6350541e3253863dedab6a3eb81df7
[ "MIT" ]
null
null
null
#pragma once #include "async/receiver.hpp" #include "async/sender.hpp" #include "async/scheduler.hpp" #include "drivers/dma/dma_concepts.hpp" #include "drivers/dma/dma_signal.hpp" #include "../spi_error.hpp" #include <array> #include "delegate.hpp" #include "reg/bit_is_set.hpp" namespace drivers::spi::detail { template<class SpiX, class DataType, class TransferFactory, class R> class WriteDmaOperation { struct DmaEventHandler { void operator()(dma::DmaSignal signal) { switch (signal) { case dma::DmaSignal::TRANSFER_COMPLETE: op_.setBuffer0Next(); break; case dma::DmaSignal::TRANSFER_COMPLETE_MEMORY1: op_.setBuffer1Next(); break; default: break; } } WriteDmaOperation & op_; }; using DmaTransfer = dma::DmaTransferType<TransferFactory, DmaEventHandler>; public: template<class TransferFactory2, class R2> WriteDmaOperation(TransferFactory2 && transferFactory, R2 && receiver, DataType * buffer0, DataType * buffer1) : transfer_(static_cast<TransferFactory2&&>(transferFactory)(DmaEventHandler{*this})) , receiver_(static_cast<R2&&>(receiver)) , buffer0_{buffer0} , buffer1_{buffer1} { } void start() { if (!transfer_.start()) { async::setError(std::move(receiver_), SpiError::BUSY); return; } reg::set(SpiX{}, board::spi::CR2::TXDMAEN); } void stop() { reg::clear(SpiX{}, board::spi::CR2::TXDMAEN); transfer_.stop(); async::setDone(std::move(receiver_)); } private: void setBuffer0Next() { auto & s = async::getScheduler(receiver_); s.postFromISR({memFn<&WriteDmaOperation::setBuffer0NextImpl>, *this}); } void setBuffer1Next() { auto & s = async::getScheduler(receiver_); s.postFromISR({memFn<&WriteDmaOperation::setBuffer1NextImpl>, *this}); } void setBuffer0NextImpl() { async::setSignal(receiver_, buffer0_); } void setBuffer1NextImpl() { async::setSignal(receiver_, buffer1_); } DmaTransfer transfer_; R receiver_; DataType * buffer0_; DataType * buffer1_; }; template<class SpiX, class DataType, dma::DmaTransferFactory TransferFactory> struct WriteDmaSender { template<template<typename...> class Variant, template<typename...> class Tuple> using value_types = Variant<Tuple<>>; template<template<typename...> class Variant> using signal_types = Variant<DataType *>; template<template<typename...> class Variant> using error_types = Variant<SpiError>; template<class R> auto connect(R && receiver) && -> WriteDmaOperation<SpiX, DataType, TransferFactory, std::remove_cvref_t<R>> { return {std::move(_transferFactory), static_cast<R&&>(receiver), buffer0_, buffer1_}; } TransferFactory _transferFactory; DataType * buffer0_; DataType * buffer1_; }; template<class SpiX, dma::DmaLike Dma, class DataType> auto writeDoubleBufferedDma(SpiX spiX, Dma & dmaDevice, DataType * data[2], std::uint32_t size) { auto transferFactory = dmaDevice.transferDoubleBuffered( dma::MemoryAddressPair(reinterpret_cast<std::uint32_t>(data[0]), reinterpret_cast<std::uint32_t>(data[1])), dma::PeripheralAddress(spiX.getAddress(board::spi::DR::_Offset{})), size); return WriteDmaSender<SpiX, DataType, decltype(transferFactory)>{ std::move(transferFactory), data[0], data[1] }; } }
30.6
119
0.567417
niclasberg
65cc1feeba9da9203c3d9f35aeca46d8f72c56e8
2,437
cpp
C++
DesignPatern/src/Behavioral/Visitor/file_visitor.cpp
behnamasadi/design_pattern
461d5bf75f5528ef9f01102299c0387b623d0d7c
[ "BSD-3-Clause" ]
3
2019-07-20T06:22:32.000Z
2020-05-31T07:49:06.000Z
DesignPatern/src/Behavioral/Visitor/file_visitor.cpp
behnamasadi/design_pattern
461d5bf75f5528ef9f01102299c0387b623d0d7c
[ "BSD-3-Clause" ]
null
null
null
DesignPatern/src/Behavioral/Visitor/file_visitor.cpp
behnamasadi/design_pattern
461d5bf75f5528ef9f01102299c0387b623d0d7c
[ "BSD-3-Clause" ]
1
2020-05-31T02:00:08.000Z
2020-05-31T02:00:08.000Z
#include <iostream> #include <vector> class AbstractDispatcher; // Forward declare AbstractDispatcher class File { // Parent class for the elements (ArchivedFile, SplitFile and // ExtractedFile) public: // This function accepts an object of any class derived from // AbstractDispatcher and must be implemented in all derived classes virtual void Accept(AbstractDispatcher& dispatcher) = 0; }; // Forward declare specific elements (files) to be dispatched class ArchivedFile; class SplitFile; class ExtractedFile; class AbstractDispatcher { // Declares the interface for the dispatcher public: // Declare overloads for each kind of a file to dispatch virtual void Dispatch(ArchivedFile& file) = 0; virtual void Dispatch(SplitFile& file) = 0; virtual void Dispatch(ExtractedFile& file) = 0; }; class ArchivedFile : public File { // Specific element class #1 public: // Resolved at runtime, it calls the dispatcher's overloaded function, // corresponding to ArchivedFile. void Accept(AbstractDispatcher& dispatcher) override { dispatcher.Dispatch(*this); } }; class SplitFile : public File { // Specific element class #2 public: // Resolved at runtime, it calls the dispatcher's overloaded function, // corresponding to SplitFile. void Accept(AbstractDispatcher& dispatcher) override { dispatcher.Dispatch(*this); } }; class ExtractedFile : public File { // Specific element class #3 public: // Resolved at runtime, it calls the dispatcher's overloaded function, // corresponding to ExtractedFile. void Accept(AbstractDispatcher& dispatcher) override { dispatcher.Dispatch(*this); } }; class Dispatcher : public AbstractDispatcher { // Implements dispatching of all // kind of elements (files) public: void Dispatch(ArchivedFile&) override { std::cout << "dispatching ArchivedFile" << std::endl; } void Dispatch(SplitFile&) override { std::cout << "dispatching SplitFile" << std::endl; } void Dispatch(ExtractedFile&) override { std::cout << "dispatching ExtractedFile" << std::endl; } }; int main() { ArchivedFile archived_file; SplitFile split_file; ExtractedFile extracted_file; std::vector<File*> files = { &archived_file, &split_file, &extracted_file, }; Dispatcher dispatcher; for (File* file : files) { file->Accept(dispatcher); } }
27.077778
75
0.704555
behnamasadi
65d338d6ab14ae8801e0e50658e11f0462e1f430
176
cpp
C++
sources/main.cpp
LemuriiL/Lab8HTTP-Part2
858a86294f2edbf38c45f6d5b8335d49ef18ea89
[ "MIT" ]
null
null
null
sources/main.cpp
LemuriiL/Lab8HTTP-Part2
858a86294f2edbf38c45f6d5b8335d49ef18ea89
[ "MIT" ]
null
null
null
sources/main.cpp
LemuriiL/Lab8HTTP-Part2
858a86294f2edbf38c45f6d5b8335d49ef18ea89
[ "MIT" ]
null
null
null
// Copyright 2021 LemuriiL <nice.duble@mail.ru> #include <Client.hpp> int main(int argc, [[maybe_unused]] char **argv) { Client A(argc, argv); return A.clientRequest(); }
22
50
0.6875
LemuriiL
65d41b74fb202447f45e4e7d4f8b06628d4c7734
4,546
cpp
C++
lmeditor/src/app/states/gui.cpp
Lawrencemm/LM-Engine
9c5e59e64e2a5a24c347538fa49046ab5a88d1f5
[ "MIT" ]
40
2020-03-13T06:12:11.000Z
2022-01-16T21:05:34.000Z
lmeditor/src/app/states/gui.cpp
Lawrencemm/LM-Engine
9c5e59e64e2a5a24c347538fa49046ab5a88d1f5
[ "MIT" ]
31
2020-02-09T06:25:12.000Z
2021-12-31T04:37:08.000Z
lmeditor/src/app/states/gui.cpp
Lawrencemm/LM-Engine
9c5e59e64e2a5a24c347538fa49046ab5a88d1f5
[ "MIT" ]
2
2020-03-13T06:12:12.000Z
2020-11-21T15:41:17.000Z
#include "../app.h" #include <lmeditor/model/selection.h> #include <lmlib/variant_visitor.h> #include <lmng/name.h> #include <lmtk/char_field.h> namespace lmeditor { bool editor_app::gui_state::handle( editor_app &app, lmtk::input_event const &input_event) { if ( input_event >> lm::variant_visitor{ [&](lmtk::key_down_event const &key_down_event) { if (key_down_event.input_state.key_state.alt()) { if ( key_down_event.input_state.key_state.shift() && app.visible_components.front() != app.main_component) { unsigned width_change{0}; switch (key_down_event.key) { case lmpl::key_code::L: width_change = 5; break; case lmpl::key_code::J: width_change = -5; break; default: break; } if (width_change) { auto new_size = app.visible_components.front()->get_size(); new_size.width += width_change; app.visible_components.front()->set_rect( app.visible_components.front()->get_position(), new_size); app.refit_visible_components(); return true; } } auto found_mapping = app.key_code_view_map.find(key_down_event.key); if (found_mapping != app.key_code_view_map.end()) { app.toggle_component(found_mapping->second); return true; } } switch (key_down_event.key) { case lmpl::key_code::F1: app.change_state(modal_state{app.create_command_help()}); return true; case lmpl::key_code::P: if (key_down_event.input_state.key_state.control()) { app.change_state( modal_state{app.create_simulation_selector()}); return true; } return false; case lmpl::key_code::R: if (key_down_event.input_state.key_state.control()) { app.change_state(modal_state{app.create_player()}); return true; } return false; case lmpl::key_code::S: if (key_down_event.input_state.key_state.control()) { app.change_state(modal_state{app.create_map_saver()}); return true; } return false; case lmpl::key_code::B: if (key_down_event.input_state.key_state.control()) { auto selected_entity = get_selection(app.map); if (selected_entity == entt::null) return false; if (key_down_event.input_state.key_state.shift()) { app.change_state(modal_state{app.create_pose_loader()}); return true; } app.change_state(modal_state{app.create_pose_saver( lmng::get_name(app.map, selected_entity))}); return true; } return false; default: return false; } }, [](auto) { return false; }, }) return true; return app.visible_components.front()->handle(input_event); } editor_app::gui_state::gui_state(editor_app &app) {} bool editor_app::gui_state::add_to_frame(editor_app &app, lmgl::iframe *frame) { for (auto &ppanel : app.visible_components) { ppanel->update( app.resources.renderer.get(), app.resources.resource_sink, app.resource_cache, app.resources.input_state); ppanel->add_to_frame(frame); } app.active_component_border->add_to_frame(frame); return false; } void editor_app::gui_state::move_resources( lmgl::irenderer *renderer, lmgl::resource_sink &resource_sink) { } } // namespace lmeditor
31.79021
80
0.481082
Lawrencemm
65dd99af9cfd4a51ce7538639e44547cb1d1ff16
9,100
cc
C++
src/router/inputoutputqueued/Router.cc
hkustliqi/SuperSim
7cff887d485b784c99b37b78a7adaedb4fde8da6
[ "Apache-2.0" ]
null
null
null
src/router/inputoutputqueued/Router.cc
hkustliqi/SuperSim
7cff887d485b784c99b37b78a7adaedb4fde8da6
[ "Apache-2.0" ]
null
null
null
src/router/inputoutputqueued/Router.cc
hkustliqi/SuperSim
7cff887d485b784c99b37b78a7adaedb4fde8da6
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 "router/inputoutputqueued/Router.h" #include <cassert> #include <cmath> #include "network/RoutingAlgorithmFactory.h" #include "congestion/CongestionStatusFactory.h" #include "router/inputoutputqueued/Ejector.h" #include "router/inputoutputqueued/InputQueue.h" #include "router/inputoutputqueued/OutputQueue.h" namespace InputOutputQueued { Router::Router( const std::string& _name, const Component* _parent, u32 _id, const std::vector<u32>& _address, u32 _numPorts, u32 _numVcs, MetadataHandler* _metadataHandler, std::vector<RoutingAlgorithmFactory*>* _routingAlgorithmFactories, Json::Value _settings) : ::Router(_name, _parent, _id, _address, _numPorts, _numVcs, _metadataHandler, _settings) { // determine the size of credits creditSize_ = numVcs_ * (u32)std::ceil( (f64)gSim->cycleTime(Simulator::Clock::CHANNEL) / (f64)gSim->cycleTime(Simulator::Clock::CORE)); // queue depths and pipeline control u32 inputQueueDepth = _settings["input_queue_depth"].asUInt(); assert(inputQueueDepth > 0); assert(_settings.isMember("vca_swa_wait") && _settings["vca_swa_wait"].isBool()); bool vcaSwaWait = _settings["vca_swa_wait"].asBool(); u32 outputQueueDepth = _settings["output_queue_depth"].asUInt(); assert(outputQueueDepth > 0); // create a congestion status device congestionStatus_ = CongestionStatusFactory::createCongestionStatus( "CongestionStatus", this, this, _settings["congestion_status"]); // create crossbar and schedulers crossbar_ = new Crossbar( "Crossbar", this, numPorts_ * numVcs_, numPorts_ * numVcs_, Simulator::Clock::CORE, _settings["crossbar"]); vcScheduler_ = new VcScheduler( "VcScheduler", this, numPorts_ * numVcs_, numPorts_ * numVcs_, Simulator::Clock::CORE, _settings["vc_scheduler"]); crossbarScheduler_ = new CrossbarScheduler( "CrossbarScheduler", this, numPorts_ * numVcs_, numPorts_ * numVcs_, numPorts_ * numVcs_, 0, Simulator::Clock::CORE, _settings["crossbar_scheduler"]); // set the congestion status to watch the credits of the main scheduler crossbarScheduler_->addCreditWatcher(congestionStatus_); // create routing algorithms, input queues, link to routing algorithm, // crossbar, and schedulers routingAlgorithms_.resize(numPorts_ * numVcs_); inputQueues_.resize(numPorts_ * numVcs_, nullptr); for (u32 port = 0; port < numPorts_; port++) { for (u32 vc = 0; vc < numVcs_; vc++) { u32 vcIdx = vcIndex(port, vc); // initialize the credit count in the CrossbarScheduler crossbarScheduler_->initCreditCount(vcIdx, outputQueueDepth); // create the name suffix std::string nameSuffix = "_" + std::to_string(port) + "_" + std::to_string(vc); // routing algorithm std::string rfname = "RoutingAlgorithm" + nameSuffix; RoutingAlgorithm* rf = _routingAlgorithmFactories->at(vc)-> createRoutingAlgorithm(rfname, this, this, port); routingAlgorithms_.at(vcIdx) = rf; // compute the client index (same for VC alloc, SW alloc, and Xbar) u32 clientIndex = vcIdx; // input queue std::string iqName = "InputQueue" + nameSuffix; InputQueue* iq = new InputQueue( iqName, this, this, inputQueueDepth, port, numVcs_, vc, vcaSwaWait, rf, vcScheduler_, clientIndex, crossbarScheduler_, clientIndex, crossbar_, clientIndex); inputQueues_.at(vcIdx) = iq; // register the input queue with VC and crossbar schedulers vcScheduler_->setClient(clientIndex, iq); crossbarScheduler_->setClient(clientIndex, iq); } } // output queues, schedulers, and crossbar outputQueues_.resize(numPorts_ * numVcs_, nullptr); outputCrossbarSchedulers_.resize(numPorts_, nullptr); outputCrossbars_.resize(numPorts_, nullptr); ejectors_.resize(numPorts_, nullptr); for (u32 port = 0; port < numPorts_; port++) { // output port switch allocator std::string outputCrossbarSchedulerName = "OutputCrossbarScheduler_" + std::to_string(port); outputCrossbarSchedulers_.at(port) = new CrossbarScheduler( outputCrossbarSchedulerName, this, numVcs_, numVcs_, 1, port * numVcs_, Simulator::Clock::CHANNEL, _settings["output_crossbar_scheduler"]); // set the congestion status to watch the credits of the output scheduler outputCrossbarSchedulers_.at(port)->addCreditWatcher(congestionStatus_); // output crossbar std::string outputCrossbarName = "OutputCrossbar_" + std::to_string(port); outputCrossbars_.at(port) = new Crossbar( outputCrossbarName, this, numVcs_, 1, Simulator::Clock::CHANNEL, _settings["output_crossbar"]); // ejector std::string ejName = "Ejector_" + std::to_string(port); ejectors_.at(port) = new Ejector(ejName, this, port); outputCrossbars_.at(port)->setReceiver(0, ejectors_.at(port), 0); // queues for (u32 vc = 0; vc < numVcs_; vc++) { // initialize the credit count in the OutputCrossbarScheduler outputCrossbarSchedulers_.at(port)->initCreditCount(vc, inputQueueDepth); // create the name suffix std::string nameSuffix = "_" + std::to_string(port) + "_" + std::to_string(vc); // compute the client indexes u32 clientIndexOut = vc; // sw alloc and output crossbar u32 clientIndexMain = vcIndex(port, vc); // main crossbar // output queue std::string oqName = "OutputQueue" + nameSuffix; OutputQueue* oq = new OutputQueue( oqName, this, outputQueueDepth, port, vc, outputCrossbarSchedulers_.at(port), clientIndexOut, outputCrossbars_.at(port), clientIndexOut, crossbarScheduler_, clientIndexMain); outputQueues_.at(clientIndexMain) = oq; // register the output queue with switch allocator outputCrossbarSchedulers_.at(port)->setClient(clientIndexOut, oq); // register the output queue as the main crossbar receiver crossbar_->setReceiver(clientIndexMain, oq, 0); } } // allocate slots for I/O channels inputChannels_.resize(numPorts_, nullptr); outputChannels_.resize(numPorts_, nullptr); } Router::~Router() { delete congestionStatus_; delete vcScheduler_; delete crossbarScheduler_; delete crossbar_; for (u32 vc = 0; vc < (numPorts_ * numVcs_); vc++) { delete routingAlgorithms_.at(vc); delete inputQueues_.at(vc); delete outputQueues_.at(vc); } for (u32 port = 0; port < numPorts_; port++) { delete outputCrossbarSchedulers_.at(port); delete outputCrossbars_.at(port); delete ejectors_.at(port); } } void Router::setInputChannel(u32 _port, Channel* _channel) { assert(inputChannels_.at(_port) == nullptr); inputChannels_.at(_port) = _channel; _channel->setSink(this, _port); } Channel* Router::getInputChannel(u32 _port) const { return inputChannels_.at(_port); } void Router::setOutputChannel(u32 _port, Channel* _channel) { assert(outputChannels_.at(_port) == nullptr); outputChannels_.at(_port) = _channel; _channel->setSource(this, _port); } Channel* Router::getOutputChannel(u32 _port) const { return outputChannels_.at(_port); } void Router::receiveFlit(u32 _port, Flit* _flit) { u32 vc = _flit->getVc(); InputQueue* iq = inputQueues_.at(vcIndex(_port, vc)); iq->receiveFlit(0, _flit); // give to metadata handler for router packet arrival if (_flit->isHead()) { packetArrival(_flit->packet()); } } void Router::receiveCredit(u32 _port, Credit* _credit) { while (_credit->more()) { u32 vc = _credit->getNum(); outputCrossbarSchedulers_.at(_port)->incrementCreditCount(vc); } delete _credit; } void Router::sendCredit(u32 _port, u32 _vc) { dbgprintf("sending credit on port %u vc %u", _port, _vc); // ensure there is an outgoing credit for the next time slot assert(_vc < numVcs_); Credit* credit = inputChannels_.at(_port)->getNextCredit(); if (credit == nullptr) { credit = new Credit(creditSize_); inputChannels_.at(_port)->setNextCredit(credit); } // mark the credit with the specified VC credit->putNum(_vc); } void Router::sendFlit(u32 _port, Flit* _flit) { assert(outputChannels_.at(_port)->getNextFlit() == nullptr); outputChannels_.at(_port)->setNextFlit(_flit); } f64 Router::congestionStatus(u32 _port, u32 _vc) const { return congestionStatus_->status(_port, _vc); } } // namespace InputOutputQueued
36.25498
79
0.705934
hkustliqi
65de98f78a21794106a94efe619f9eb38e4b70ef
4,575
hpp
C++
src/elx_conv_wino_trans_weights.hpp
weizix/Deep-learning-math-kernel-research
383db01893d81872e2129a8c060dbe61934910d8
[ "Apache-2.0" ]
33
2019-06-13T00:45:58.000Z
2021-12-15T08:17:21.000Z
src/elx_conv_wino_trans_weights.hpp
uyongw/Deep-learning-math-kernel-research
6d65b8f2df7ab6d6db8f02066dae8bc59691ae58
[ "Apache-2.0" ]
2
2019-09-19T04:31:05.000Z
2019-10-21T10:16:00.000Z
src/elx_conv_wino_trans_weights.hpp
uyongw/Deep-learning-math-kernel-research
6d65b8f2df7ab6d6db8f02066dae8bc59691ae58
[ "Apache-2.0" ]
25
2019-08-30T05:39:36.000Z
2022-03-17T04:32:14.000Z
#pragma once #include "euler.hpp" #include "el_def.hpp" #include "el_utils.hpp" #include "elx_conv.hpp" #include "kernel/elk_conv_wino.hpp" #include "kernel/elk_conv_wino_2x2_3x3_weights.hxx" #include "kernel/elk_conv_wino_3x3_3x3_weights.hxx" #include "kernel/elk_conv_wino_4x4_3x3_weights.hxx" #include "kernel/elk_conv_wino_5x5_3x3_weights.hxx" namespace euler { template <typename TweightsType, typename WeightsType, int I, int A, int K, int V> class elx_conv_wino_trans_weights_base { public: using op_type = float; elx_conv_wino_trans_weights_base() {} virtual ~elx_conv_wino_trans_weights_base() {} void setup(elx_param_t *conv_ep) { ep = conv_ep; mthr_ = ep->nthreads; weights_is_bfmt_ = ep->weights_fmt == OIhw16i16o; weights_as_bfmt_ = ep->input_fmt == oihw && ep->weights_as_blocked; bind_kernel_functions(); } protected: void bind_kernel_functions() { ker_trans_weights_ = elk_conv_wino_trans_weights<op_type, WeightsType, I, A, K, V>::execute; } elx_param_t *ep = nullptr; decltype(elk_conv_wino_trans_weights< op_type, WeightsType, I, A, K, V>::execute) *ker_trans_weights_; inline void __execute_blocked(TweightsType *__restrict tweights, WeightsType *__restrict weights, int O4); inline void __execute_oihw(TweightsType *__restrict tweights, WeightsType *__restrict weights, int O4); inline void __execute_hwio(TweightsType *__restrict tweights, WeightsType *__restrict weights, int O4); inline void __execute_blocked(TweightsType *__restrict tweights, WeightsType *__restrict weights, int _I4, int _O4); inline void __execute_oihw(TweightsType *__restrict tweights, WeightsType *__restrict weights, int _I4, int _O4); inline void __execute_hwio(TweightsType *__restrict tweights, WeightsType *__restrict weights, int _I4, int _O4); inline void __execute_post(TweightsType * __restrict tweights, op_type at[A][A][V][V], int _O4, int _I4, int _O3, int _I3, int _O1, int _I2, int _O); bool weights_is_bfmt_, weights_as_bfmt_; int mthr_; }; template <typename TweightsType, typename WeightsType, int I, int A, int K, int V> class elx_conv_wino_trans_weights_t : public elx_conv_wino_trans_weights_base<TweightsType, WeightsType, I, A, K, V> { public: using super = elx_conv_wino_trans_weights_base<TweightsType, WeightsType, I, A, K, V>; using op_type = typename super::op_type; public: elx_conv_wino_trans_weights_t() {} virtual ~elx_conv_wino_trans_weights_t() {} void execute(TweightsType *__restrict tweights, WeightsType *__restrict weights, int O4 = 1); void execute(TweightsType *__restrict tweights, WeightsType *__restrict weights, int _I4, int _O4); void operator () (TweightsType *__restrict tweights, WeightsType *__restrict weights, int O4 = 1) { execute(tweights, weights, O4); } void operator() (TweightsType *__restrict tweights, WeightsType *__restrict weights, int _I4, int _O4) { execute(tweights, weights, _I4, _O4); } protected: using super::ep; using super::ker_trans_weights_; using super::weights_is_bfmt_; using super::weights_as_bfmt_; using super::mthr_; }; template <typename WeightsType, int I, int A, int K, int V> class elx_conv_wino_trans_weights_t<int8_t, WeightsType, I, A, K, V> : public elx_conv_wino_trans_weights_base<float, WeightsType, I, A, K, V> { public: using TweightsType = float; using super = elx_conv_wino_trans_weights_base<float, WeightsType, I, A, K, V>; using op_type = typename super::op_type; public: elx_conv_wino_trans_weights_t() {} virtual ~elx_conv_wino_trans_weights_t() {} void execute(float *__restrict tweights_scale, float *__restrict tweights_shift, int8_t *__restrict t_input_s8, TweightsType *__restrict t_input, WeightsType *__restrict input, int O4); void operator () (float *__restrict tweights_scale, float *__restrict tweights_shift, int8_t *__restrict t_input_s8, TweightsType *__restrict t_input, WeightsType *__restrict input, int O4) { execute(tweights_scale, tweights_shift, t_input_s8, t_input, input, O4); } inline void quantization(float *__restrict tweights_scale, float *__restrict tweights_shift, int8_t *__restrict tweights_s8, TweightsType *__restrict tweights, int O4); protected: using super::ep; using super::ker_trans_weights_; using super::weights_is_bfmt_; using super::weights_as_bfmt_; using super::mthr_; }; } // namespace euler
32.21831
82
0.738798
weizix
65deaa11ff9f18bed58c8a1da8da4bd74dfcd015
462
hpp
C++
shapes/Thing.hpp
PabloMorenoUm/Projekt
ebd5b4bfbd5da0e86ade850ce0cd701e8eff2e83
[ "MIT" ]
null
null
null
shapes/Thing.hpp
PabloMorenoUm/Projekt
ebd5b4bfbd5da0e86ade850ce0cd701e8eff2e83
[ "MIT" ]
9
2021-06-30T14:58:40.000Z
2021-08-22T22:36:31.000Z
shapes/Thing.hpp
PabloMorenoUm/Projekt
ebd5b4bfbd5da0e86ade850ce0cd701e8eff2e83
[ "MIT" ]
null
null
null
// // Created by Pablo Moreno Um on 22.07.21. // #ifndef PROJEKT_THING_HPP #define PROJEKT_THING_HPP #include "Basic.hpp" class Thing: public Basic { protected: sf::Vector2f m_Position; void setPosition(const float& posX, const float& posY); public: Thing(); Thing(const float &posX, const float &posY, const std::string &filename); const sf::Sprite &getSprite() const; sf::FloatRect getBounds() const; }; #endif //PROJEKT_THING_HPP
20.086957
77
0.701299
PabloMorenoUm
65ebcf03b15d0b9a4a8e3199da0aab79e039dfb2
1,443
cpp
C++
src/hybrid_a_star_planner.cpp
JialiangHan/path_planner
2a995f6527872e6bd0e3fe6c9a6e0e2744a2de29
[ "BSD-3-Clause" ]
null
null
null
src/hybrid_a_star_planner.cpp
JialiangHan/path_planner
2a995f6527872e6bd0e3fe6c9a6e0e2744a2de29
[ "BSD-3-Clause" ]
null
null
null
src/hybrid_a_star_planner.cpp
JialiangHan/path_planner
2a995f6527872e6bd0e3fe6c9a6e0e2744a2de29
[ "BSD-3-Clause" ]
null
null
null
#include <pluginlib/class_list_macros.h> #include "hybrid_a_star_planner.h" // register this planner as a BaseGlobalPlanner plugin PLUGINLIB_EXPORT_CLASS(HybridAStar::HybridAStarPlanner, nav_core::BaseGlobalPlanner) using namespace std; // Default Constructor namespace HybridAStar { HybridAStarPlanner::HybridAStarPlanner() { } HybridAStarPlanner::HybridAStarPlanner(std::string name, costmap_2d::Costmap2DROS *costmap_ros) { initialize(name, costmap_ros); } void HybridAStarPlanner::initialize(std::string name, costmap_2d::Costmap2DROS *costmap_ros) { } bool HybridAStarPlanner::makePlan(const geometry_msgs::PoseStamped &start, const geometry_msgs::PoseStamped &goal, std::vector<geometry_msgs::PoseStamped> &plan) { plan.push_back(start); for (int i = 0; i < 20; i++) { geometry_msgs::PoseStamped new_goal = goal; tf::Quaternion goal_quat = tf::createQuaternionFromYaw(1.54); new_goal.pose.position.x = -2.5 + (0.05 * i); new_goal.pose.position.y = -3.5 + (0.05 * i); new_goal.pose.orientation.x = goal_quat.x(); new_goal.pose.orientation.y = goal_quat.y(); new_goal.pose.orientation.z = goal_quat.z(); new_goal.pose.orientation.w = goal_quat.w(); plan.push_back(new_goal); } plan.push_back(goal); return true; } };
30.0625
165
0.656272
JialiangHan