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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
06dd7d2a677392f81843b6b1412f05dd15a2bfc3 | 6,053 | cpp | C++ | bse/bsePhysics/Source/bseIsland.cpp | crisbia/bse | d549deda2761d301a67aa838743ec731c82e3c07 | [
"MIT"
] | null | null | null | bse/bsePhysics/Source/bseIsland.cpp | crisbia/bse | d549deda2761d301a67aa838743ec731c82e3c07 | [
"MIT"
] | 3 | 2021-12-02T12:52:35.000Z | 2021-12-19T20:37:35.000Z | bse/bsePhysics/Source/bseIsland.cpp | crisbia/bse | d549deda2761d301a67aa838743ec731c82e3c07 | [
"MIT"
] | null | null | null | #include "bseIsland.h"
#include "bseBody.h"
/*
Islands generation scheme:
for each body do
// skip non dynamic bodies
if !body.isDynamic continue
connectionFound = false
if body.islandID == -1 then
for each connection in body.connections do
// skip connection to non dynamic bodies
if !connection.otherBody.isDynamic then continue
if connection.otherBody.islandID != -1 then
islands[conn.otherBody.islandID].add(body)
connectionFound = true
break
end
end
end
// no island found, we need to create a new one
if !connectionFound then
islands.push_back(new Island())
islands.back().add(body)
end
end
*/
namespace bse
{
namespace phx
{
// TODO reuse islands in the islands generator, because
// they can contain hundreds of contacts and bodies, so the allocation and deallocation
// is going to be quite expensive.
// I just need to keep them until the generator is destroyed.
// TODO change the name of the generator in "manager" :)
//---------------------------------------------------------------------------------------------------------------------
Island::Island(size_t initialSize)
{
m_bodies.reserve(initialSize);
m_contacts.reserve(2*initialSize);
}
//---------------------------------------------------------------------------------------------------------------------
void Island::clear()
{
m_bodies.clear();
m_contacts.clear();
}
//---------------------------------------------------------------------------------------------------------------------
void Island::addBody(Body* body)
{
if (body!=0 && body->getCurrentIsland()!=this)
{
m_bodies.push_back(body);
body->setCurrentIsland(this);
}
}
//---------------------------------------------------------------------------------------------------------------------
int Island::computeContacts()
{
m_contacts.clear();
for (size_t iBody=0; iBody<m_bodies.size(); ++iBody)
{
Body* body = m_bodies[iBody];
const BodyInfluencesList influences = body->getBodyInfluences();
for (BodyInfluencesList::const_iterator influence=influences.begin(); influence != influences.end(); ++influence)
{
const BodyInfluence& current = (*influence);
if (current.influenceType == BSE_INFLUENCE_PRIMARY || current.other->isStatic())
{
m_contacts.push_back((*influence).contact);
}
}
}
return (int)m_contacts.size();
}
//---------------------------------------------------------------------------------------------------------------------
const ContactsList& Island::getContacts() const
{
return m_contacts;
}
//---------------------------------------------------------------------------------------------------------------------
IslandsManager::IslandsManager(size_t initialNumIslands, size_t initialIslandSize) :
m_firstAvailable(0)
{
if (initialNumIslands == 0)
initialNumIslands = 1;
if (initialIslandSize == 0)
initialIslandSize = 1;
m_islands.resize(initialNumIslands);
for (size_t i=0; i<m_islands.size(); ++i)
{
m_islands[i] = new Island(initialIslandSize);
}
}
//---------------------------------------------------------------------------------------------------------------------
IslandsManager::~IslandsManager()
{
clear();
for (size_t i=0; i<m_islands.size(); ++i)
{
delete m_islands[i];
}
}
//---------------------------------------------------------------------------------------------------------------------
void IslandsManager::clear()
{
for (size_t i=0; i<m_islands.size(); ++i)
{
m_islands[i]->clear();
}
m_firstAvailable = 0;
}
//---------------------------------------------------------------------------------------------------------------------
const IslandsList& IslandsManager::getIslands() const
{
return m_islands;
}
//---------------------------------------------------------------------------------------------------------------------
int IslandsManager::computeIslands(const BodiesList& bodies)
{
clear();
for (BodiesList::const_iterator iter=bodies.begin(); iter != bodies.end(); ++iter)
{
Body* body = (*iter);
// skip non dynamic bodies
// TODO consider kinematic ones...
if (body->isStatic()) continue;
if (body->getCurrentIsland()==0)
{
bool influenceFound = false;
const BodyInfluencesList influences = body->getBodyInfluences();
for (BodyInfluencesList::const_iterator influence=influences.begin(); influence != influences.end(); ++influence)
{
Body* other = (*influence).other;
if (other)
{
if (other->isStatic())
{
continue;
}
if (other->getCurrentIsland()!=0)
{
other->getCurrentIsland()->addBody(body);
influenceFound = true;
break;
}
}
}
// no island found, we need to create a new one
if (!influenceFound)
{
if (m_firstAvailable == m_islands.size())
m_islands.push_back(new Island());
Island* isl = m_islands[m_firstAvailable];
++m_firstAvailable;
isl->addBody(body);
// fix immediately all the connections which are not already in an island
const BodyInfluencesList influences = body->getBodyInfluences();
for (BodyInfluencesList::const_iterator influence=influences.begin(); influence != influences.end(); ++influence)
{
Body* other = (*influence).other;
if (other && !other->isStatic() && other->getCurrentIsland()==0)
{
isl->addBody(other);
}
}
}
}
}
for (size_t i = 0; i < m_islands.size(); ++i)
{
Island* island = m_islands[i];
island->computeContacts();
}
return (int)m_islands.size();
}
} // namespace phx
} // namespace bse | 29.241546 | 122 | 0.489014 | crisbia |
06dfc0582f793f5f27279eb9d1d563a42e50c592 | 8,670 | hpp | C++ | Code/Tenshi/Compiler/Project.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | null | null | null | Code/Tenshi/Compiler/Project.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | 8 | 2016-11-17T00:39:03.000Z | 2016-11-29T14:46:27.000Z | Code/Tenshi/Compiler/Project.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | null | null | null | #pragma once
#include <Collections/List.hpp>
#include <Core/String.hpp>
#include <Core/Manager.hpp>
#include "Platform.hpp"
#include "Module.hpp"
namespace Tenshi { namespace Compiler {
class MCodeGen;
// Linking target type (executable, dynamic library, static library)
enum class ELinkTarget
{
// No linking will take place
None,
// The output will be a native executable (Windows: .exe)
Executable,
// The output will be a dynamic library (Windows: .dll; Mac: .dylib; Linux: .so)
DynamicLibrary,
// The output will be a static library (.a)
StaticLibrary
};
// Environment the target is to run in
enum class ETargetEnv
{
// Text mode / terminal (e.g., server or pipeline tool)
Terminal,
// GUI mode (no default console box in Windows)
Windowed,
// Platform framework (e.g., phone or store app)
Platform
};
// Link-Time Optimization configuration
enum class ELTOConfig
{
Disabled,
Enabled
};
// Level of debugging support in compilation
enum class EDebugConfig
{
Disabled,
Enabled
};
// Level of optimization support in compilation
enum class EOptimizeConfig
{
Disabled,
PerFunction,
PerModule
};
// Settings for any given compilation
struct SCompileSettings
{
EDebugConfig Debug;
EOptimizeConfig Optimize;
inline bool DebugEnabled() const
{
return Debug != EDebugConfig::Disabled;
}
inline bool OptimizationEnabled() const
{
return Optimize != EOptimizeConfig::Disabled;
}
};
// A single compilation unit, with all relevant settings
struct SCompilation
{
typedef Ax::TList< SCompilation > List;
typedef Ax::TList< SCompilation >::Iterator Iter;
// Settings for the source file
SCompileSettings Settings;
// Input source filename
Ax::String SourceFilename;
// Optional object filename (outputs to the object file format)
Ax::String ObjectFilename;
// Optional bitcode filename (outputs to LLVM bitcode file; .bc)
Ax::String LLVMBCFilename;
// Optional IR listing filename (outputs text representation of the module's LLVM IR; .ll)
Ax::String IRListFilename;
// Optional assembly listing filename (outputs to target machine assembly representation; .s)
Ax::String ASListFilename;
// Modules referenced by this compilation (only valid while this is active)
SModule::IntrList Modules;
inline SCompilation()
: Settings()
, SourceFilename()
, ObjectFilename()
, LLVMBCFilename()
, IRListFilename()
, ASListFilename()
, Modules()
{
}
inline ~SCompilation()
{
}
bool Build();
};
// Token used when parsing the project file
struct SProjToken
{
const char * s;
const char * e;
inline bool IsQuote() const
{
return s != nullptr && *s != '\"';
}
inline bool Cmp( const char *pszCmp ) const
{
AX_ASSERT_NOT_NULL( s );
AX_ASSERT_NOT_NULL( pszCmp );
const Ax::uintptr myLen = e - s;
const Ax::uintptr n = strlen( pszCmp );
if( myLen != n ) {
return false;
}
return strncmp( s, pszCmp, n ) == 0;
}
inline bool operator==( const char *pszCmp ) const
{
return Cmp( pszCmp );
}
inline bool operator!=( const char *pszCmp ) const
{
return !Cmp( pszCmp );
}
bool Unquote( Ax::String &Dst, bool bAppend = false ) const;
};
// Diagnostic state for the project file parser
struct SProjDiagState
{
const char * pszFilename;
Ax::uint32 uLine;
const char * pszLineStart;
inline Ax::uint32 Column( const char *p ) const
{
return 1 + ( Ax::uint32 )( p - pszLineStart );
}
inline bool Error( const char *p, const char *pszError )
{
AX_ASSERT_NOT_NULL( p );
Ax::g_ErrorLog( pszFilename, uLine, Column( p ) ) += pszError;
return false;
}
inline bool Error( const char *p, const Ax::String &ErrorStr )
{
AX_ASSERT_NOT_NULL( p );
Ax::g_ErrorLog( pszFilename, uLine, Column( p ) ) += ErrorStr;
return false;
}
inline bool Error( const SProjToken &Tok, const char *pszError )
{
Ax::g_ErrorLog( pszFilename, uLine, Column( Tok.s ) ) += pszError;
return false;
}
inline bool Error( const SProjToken &Tok, const Ax::String &ErrorStr )
{
Ax::g_ErrorLog( pszFilename, uLine, Column( Tok.s ) ) += ErrorStr;
return false;
}
};
// Whether variable arguments can be used
enum class EVarArgs
{
No,
Yes
};
// Encapsulation of an individual target
class CProject
{
public:
typedef Ax::TList< CProject > List;
typedef Ax::TList< CProject >::Iterator Iter;
typedef Ax::TList< CProject * > PtrList;
typedef Ax::TList< CProject * >::Iterator PtrIter;
// Load the project's settings from a file
bool LoadFromFile( const char *pszFilename );
// Apply a single line (as though it were from a project file)
bool ApplyLine( const char *pszFilename, Ax::uint32 uLine, const char *pszLineStart, const char *pszLineEnd = nullptr );
// Build the project (returns false if it failed)
bool Build();
// Add the module to the current compilation/project
void TouchModule( SModule &Mod );
private:
friend class MProjects;
friend List;
CProject();
~CProject();
private:
friend class MCodeGen;
// Name of this project (this is mostly meaningless)
Ax::String m_Name;
// Path to the source files
Ax::String m_SourceDir;
// Path to the temporary object files
Ax::String m_ObjectDir;
// Full path to the target file
Ax::String m_TargetPath;
// Whether a prefix should be applied when setting the target path
bool m_bTargetPrefix:1;
// Whether a suffix should be applied when setting the target path
bool m_bTargetSuffix:1;
// Whether an assembly file listing should be produced
bool m_bASMList:1;
// Whether a LLVM IR file listing should be produced
bool m_bIRList:1;
// Target link type (e.g., executable)
ELinkTarget m_TargetType;
// Target environment (e.g., gui)
ETargetEnv m_TargetEnv;
// Link-time optimization (LTO) setting for this project
ELTOConfig m_LTO;
// Build information for this project
SBuildInfo m_BuildInfo;
// Current settings -- applied as the default settings when new translation units are added
SCompileSettings m_Settings;
// Compilation units
SCompilation::List m_Compilations;
// Current compilation
SCompilation * m_pCurrentCompilation;
// Modules used by this project (only valid while project is being built)
SModule::IntrList m_Modules;
AX_DELETE_COPYFUNCS(CProject);
};
// Project manager
class MProjects
{
public:
static MProjects &GetInstance();
bool AddProjectDirectory( const char *pszProjDir );
CProject &Current();
CProject *Add();
CProject *Load( const char *pszProjFile );
CProject *FindExisting( const char *pszName, const char *pszNameEnd = nullptr ) const;
inline CProject *FindExisting( const Ax::String &Name ) const
{
return FindExisting( Name.CString(), Name.CString() + Name.Len() );
}
// Remove the given project (freeing its memory) -- returns nullptr
CProject *Remove( CProject *pProj );
void Clear();
bool Build();
private:
Ax::TList< Ax::String > m_ProjectDirs;
CProject::List m_Projects;
CProject::Iter m_CurrProj;
MProjects();
~MProjects();
AX_DELETE_COPYFUNCS(MProjects);
};
static Ax::TManager< MProjects > Projects;
// Push a token to a static array of tokens
template< Ax::uintptr kNumTokens >
inline bool PushToken( SProjToken( &Tokens )[ kNumTokens ], Ax::uintptr &uIndex, const char *s, const char *e )
{
AX_ASSERT_NOT_NULL( s );
AX_ASSERT_NOT_NULL( e );
AX_ASSERT_MSG( Ax::uintptr( s ) < Ax::uintptr( e ), "Invalid token string" );
if( uIndex >= kNumTokens ) {
return false;
}
Tokens[ uIndex ].s = s;
Tokens[ uIndex ].e = e;
++uIndex;
return true;
}
// Check for a parameter in an array of parameters
template< Ax::uintptr kNumTokens >
inline bool HasParm( SProjToken( &Tokens )[ kNumTokens ], Ax::uintptr cTokens, SProjDiagState &Diag, const SProjToken &CmdTok, Ax::uintptr cParms = 1, EVarArgs VarArgs = EVarArgs::No, Ax::uintptr cMaxParms = ~Ax::uintptr( 0 ) )
{
AX_ASSERT( cTokens <= kNumTokens );
AX_ASSERT( &CmdTok >= &Tokens[0] && &CmdTok < &Tokens[kNumTokens] );
const Ax::uintptr uCmd = &CmdTok - &Tokens[0];
AX_ASSERT( uCmd < kNumTokens );
const Ax::uintptr cArgs = cTokens - uCmd - 1;
if( ( cArgs == cParms || ( VarArgs == EVarArgs::Yes && cArgs > cParms ) ) && cArgs <= cMaxParms ) {
return true;
}
if( cArgs < cParms ) {
Diag.Error( CmdTok, "Too few parameters" );
return false;
}
Diag.Error( CmdTok, "Too many parameters" );
return false;
}
}}
| 24.700855 | 228 | 0.677393 | NotKyon |
06ebf7ec5f14bcaef99d055302d23ecd80862c2d | 643 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/game/ui/TutorialArea.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 1 | 2022-03-18T17:22:09.000Z | 2022-03-18T17:22:09.000Z | include/RED4ext/Scripting/Natives/Generated/game/ui/TutorialArea.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | null | null | null | include/RED4ext/Scripting/Natives/Generated/game/ui/TutorialArea.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 1 | 2022-02-13T01:44:55.000Z | 2022-02-13T01:44:55.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/Scripting/Natives/Generated/ink/WidgetLogicController.hpp>
namespace RED4ext
{
namespace game::ui {
struct TutorialArea : ink::WidgetLogicController
{
static constexpr const char* NAME = "gameuiTutorialArea";
static constexpr const char* ALIAS = "TutorialArea";
uint8_t unk78[0x80 - 0x78]; // 78
CName bracketID; // 80
};
RED4EXT_ASSERT_SIZE(TutorialArea, 0x88);
} // namespace game::ui
using TutorialArea = game::ui::TutorialArea;
} // namespace RED4ext
| 25.72 | 76 | 0.744946 | jackhumbert |
06ec114313a6aa630fbfd8bba17b4652f84bf784 | 623 | cpp | C++ | BAC/exercises/ch10/UVa11121.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | BAC/exercises/ch10/UVa11121.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | BAC/exercises/ch10/UVa11121.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa11121 Base -2
// Rujia Liu
// 题意:已知正整数和负整数都有惟一的-2进制表示,而且不带符号位。输入整数n,输出它的-2进制表示
// 算法:按照b0, b1, ... 这样的顺序求解,每次对-2取余,然后把余数调整成0和1。
#include<cstdio>
void div_negative(int n, int m, int& q, int& r) {
q = n / m;
r = n - q * m;
while(r < 0) { r -= m; q++; }
}
int b[10];
void solve(int n) {
int k = 0, q, r;
do {
div_negative(n, -2, q, r);
b[k++] = r;
n = q;
} while(n);
for(int i = k-1; i >= 0; i--) printf("%d", b[i]);
printf("\n");
}
int main() {
int T, n, kase = 0;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
printf("Case #%d: ", ++kase);
solve(n);
}
return 0;
}
| 17.8 | 51 | 0.489567 | Anyrainel |
06f2f84d8bf40c097c7a64c438db1e020f4aa5a3 | 8,357 | cpp | C++ | Modules/PhotoacousticsLib/src/IO/mitkPAIOUtil.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/PhotoacousticsLib/src/IO/mitkPAIOUtil.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/PhotoacousticsLib/src/IO/mitkPAIOUtil.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | #include "mitkPAIOUtil.h"
#include "mitkIOUtil.h"
#include "mitkImageReadAccessor.h"
#include <string>
#include <sstream>
#include <vector>
#include "mitkPAComposedVolume.h"
#include "mitkPASlicedVolumeGenerator.h"
#include "mitkPANoiseGenerator.h"
#include "mitkPAVolumeManipulator.h"
#include <mitkProperties.h>
#include <itkDirectory.h>
#include <itksys/SystemTools.hxx>
static std::vector<int> splitString(const std::string &s, const char* delim) {
std::vector<int> elems;
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, *delim))
{
int numb;
std::stringstream(item) >> numb;
elems.push_back(numb);
}
return elems;
}
bool mitk::pa::IOUtil::DoesFileHaveEnding(std::string const &fullString, std::string const &ending) {
if (fullString.length() == 0 || ending.length() == 0 || fullString.length() < ending.length())
return false;
return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
}
mitk::pa::IOUtil::IOUtil() {}
mitk::pa::IOUtil::~IOUtil() {}
mitk::pa::Volume::Pointer mitk::pa::IOUtil::LoadNrrd(std::string filename, double blur)
{
if (filename.empty() || filename == "")
return nullptr;
mitk::Image::Pointer inputImage = mitk::IOUtil::Load<mitk::Image>(filename);
if (inputImage.IsNull())
return nullptr;
auto returnImage = Volume::New(inputImage);
VolumeManipulator::GaussianBlur3D(returnImage, blur);
return returnImage;
}
std::map<mitk::pa::IOUtil::Position, mitk::pa::Volume::Pointer>
mitk::pa::IOUtil::LoadFluenceContributionMaps(std::string foldername, double blur, int* progress, bool doLog10)
{
std::map<IOUtil::Position, Volume::Pointer> resultMap;
itk::Directory::Pointer directoryHandler = itk::Directory::New();
directoryHandler->Load(foldername.c_str());
for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
{
std::string filename = std::string(directoryHandler->GetFile(fileIndex));
if (itksys::SystemTools::FileIsDirectory(filename))
continue;
if (!DoesFileHaveEnding(filename, ".nrrd"))
continue;
size_t s = filename.find("_p");
size_t e = filename.find("Fluence", s);
std::string sub = filename.substr(s + 2, e - s - 2);
std::vector<int> coords = splitString(sub, ",");
if (coords.size() != 3)
{
MITK_ERROR << "Some of the data to read was corrupted or did not match the " <<
"naming pattern *_pN,N,NFluence*.nrrd";
mitkThrow() << "Some of the data to read was corrupted or did not match the" <<
" naming pattern *_pN,N,NFluence*.nrrd";
}
else
{
MITK_DEBUG << "Extracted coords: " << coords[0] << "|" << coords[1] << "|" << coords[2] << " from string " << sub;
Volume::Pointer nrrdFile = LoadNrrd(foldername + filename, blur);
if (doLog10)
VolumeManipulator::Log10Image(nrrdFile);
resultMap[Position{ coords[0], coords[2] }] = nrrdFile;
*progress = *progress + 1;
}
}
return resultMap;
}
int mitk::pa::IOUtil::GetNumberOfNrrdFilesInDirectory(std::string directory)
{
return GetListOfAllNrrdFilesInDirectory(directory).size();
}
std::vector<std::string> mitk::pa::IOUtil::GetListOfAllNrrdFilesInDirectory(std::string directory, bool keepFileFormat)
{
std::vector<std::string> filenames;
itk::Directory::Pointer directoryHandler = itk::Directory::New();
directoryHandler->Load(directory.c_str());
for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
{
std::string filename = std::string(directoryHandler->GetFile(fileIndex));
if (itksys::SystemTools::FileIsDirectory(filename))
continue;
if (!DoesFileHaveEnding(filename, ".nrrd"))
continue;
if (keepFileFormat)
{
filenames.push_back(filename);
}
else
{
filenames.push_back(filename.substr(0, filename.size() - 5));
}
}
return filenames;
}
std::vector<std::string> mitk::pa::IOUtil::GetAllChildfoldersFromFolder(std::string folderPath)
{
std::vector<std::string> returnVector;
itksys::Directory directoryHandler;
directoryHandler.Load(folderPath.c_str());
for (unsigned int fileIndex = 0, numFiles = directoryHandler.GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
{
std::string foldername = std::string(directoryHandler.GetFile(fileIndex));
std::string filename = folderPath + "/" + foldername;
if (itksys::SystemTools::FileIsDirectory(filename))
{
if (foldername != std::string(".") && foldername != std::string(".."))
{
MITK_INFO << filename;
returnVector.push_back(filename);
}
continue;
}
//If there is a nrrd file in the directory we assume that a bottom level directory was chosen.
if (DoesFileHaveEnding(filename, ".nrrd"))
{
returnVector.clear();
returnVector.push_back(folderPath);
return returnVector;
}
}
return returnVector;
}
mitk::pa::InSilicoTissueVolume::Pointer mitk::pa::IOUtil::LoadInSilicoTissueVolumeFromNrrdFile(std::string nrrdFile)
{
MITK_INFO << "Initializing ComposedVolume by nrrd...";
auto inputImage = mitk::IOUtil::Load<mitk::Image>(nrrdFile);
auto tissueParameters = TissueGeneratorParameters::New();
unsigned int xDim = inputImage->GetDimensions()[1];
unsigned int yDim = inputImage->GetDimensions()[0];
unsigned int zDim = inputImage->GetDimensions()[2];
tissueParameters->SetXDim(xDim);
tissueParameters->SetYDim(yDim);
tissueParameters->SetZDim(zDim);
double xSpacing = inputImage->GetGeometry(0)->GetSpacing()[1];
double ySpacing = inputImage->GetGeometry(0)->GetSpacing()[0];
double zSpacing = inputImage->GetGeometry(0)->GetSpacing()[2];
if ((xSpacing - ySpacing) > mitk::eps || (xSpacing - zSpacing) > mitk::eps || (ySpacing - zSpacing) > mitk::eps)
{
throw mitk::Exception("Cannot handle unequal spacing.");
}
tissueParameters->SetVoxelSpacingInCentimeters(xSpacing);
mitk::PropertyList::Pointer propertyList = inputImage->GetPropertyList();
mitk::ImageReadAccessor readAccess0(inputImage, inputImage->GetVolumeData(0));
auto* m_AbsorptionArray = new double[xDim*yDim*zDim];
memcpy(m_AbsorptionArray, readAccess0.GetData(), xDim*yDim*zDim * sizeof(double));
auto absorptionVolume = Volume::New(m_AbsorptionArray, xDim, yDim, zDim, xSpacing);
mitk::ImageReadAccessor readAccess1(inputImage, inputImage->GetVolumeData(1));
auto* m_ScatteringArray = new double[xDim*yDim*zDim];
memcpy(m_ScatteringArray, readAccess1.GetData(), xDim*yDim*zDim * sizeof(double));
auto scatteringVolume = Volume::New(m_ScatteringArray, xDim, yDim, zDim, xSpacing);
mitk::ImageReadAccessor readAccess2(inputImage, inputImage->GetVolumeData(2));
auto* m_AnisotropyArray = new double[xDim*yDim*zDim];
memcpy(m_AnisotropyArray, readAccess2.GetData(), xDim*yDim*zDim * sizeof(double));
auto anisotropyVolume = Volume::New(m_AnisotropyArray, xDim, yDim, zDim, xSpacing);
Volume::Pointer segmentationVolume;
if (inputImage->GetDimension() == 4)
{
mitk::ImageReadAccessor readAccess3(inputImage, inputImage->GetVolumeData(3));
auto* m_SegmentationArray = new double[xDim*yDim*zDim];
memcpy(m_SegmentationArray, readAccess3.GetData(), xDim*yDim*zDim * sizeof(double));
segmentationVolume = Volume::New(m_SegmentationArray, xDim, yDim, zDim, xSpacing);
}
return mitk::pa::InSilicoTissueVolume::New(absorptionVolume, scatteringVolume,
anisotropyVolume, segmentationVolume, tissueParameters, propertyList);
}
mitk::pa::FluenceYOffsetPair::Pointer mitk::pa::IOUtil::LoadFluenceSimulation(std::string fluenceSimulation)
{
MITK_INFO << "Adding slice...";
mitk::Image::Pointer inputImage = mitk::IOUtil::Load<mitk::Image>(fluenceSimulation);
auto yOffsetProperty = inputImage->GetProperty("y-offset");
if (yOffsetProperty.IsNull())
mitkThrow() << "No \"y-offset\" property found in fluence file!";
std::string yOff = yOffsetProperty->GetValueAsString();
MITK_INFO << "Reading y Offset: " << yOff;
#ifdef __linux__
std::replace(yOff.begin(), yOff.end(), '.', ',');
#endif // __linux__
double yOffset = std::stod(yOff);
MITK_INFO << "Converted offset " << yOffset;
return FluenceYOffsetPair::New(Volume::New(inputImage), yOffset);
}
| 34.676349 | 120 | 0.703123 | wyyrepo |
06f2fdf42fc342f4fabfa0933e662c8482f1adfb | 4,425 | cpp | C++ | src/IME/common/Preference.cpp | KwenaMashamaite/IME | c31a5cdacdc6cb30d3a4e1f4b317e0addd2e6107 | [
"MIT"
] | 9 | 2021-01-11T10:43:58.000Z | 2022-02-17T10:09:10.000Z | src/IME/common/Preference.cpp | KwenaMashamaite/IME | c31a5cdacdc6cb30d3a4e1f4b317e0addd2e6107 | [
"MIT"
] | null | null | null | src/IME/common/Preference.cpp | KwenaMashamaite/IME | c31a5cdacdc6cb30d3a4e1f4b317e0addd2e6107 | [
"MIT"
] | 5 | 2021-03-07T00:32:08.000Z | 2022-02-17T10:15:16.000Z | ////////////////////////////////////////////////////////////////////////////////
// IME - Infinite Motion Engine
//
// Copyright (c) 2020-2021 Kwena Mashamaite ([email protected])
//
// 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 "IME/common/Preference.h"
#include "IME/core/exceptions/Exceptions.h"
#include "IME/utility/DiskFileReader.h"
#include <sstream>
namespace ime {
namespace {
std::string convertToString(Preference::Type type) {
switch (type) {
case Preference::Type::Bool: return "BOOL";
case Preference::Type::String: return "STRING";
case Preference::Type::Int: return "INT";
case Preference::Type::Double: return "DOUBLE";
case Preference::Type::Float: return "FLOAT";
default:
return "UNSUPPORTED";
}
}
std::string convertToString(Preference::Type type, const Preference& pref) {
try {
switch (type) {
case Preference::Type::Bool: return std::to_string(pref.getValue<bool>());
case Preference::Type::String: return pref.getValue<std::string>();
case Preference::Type::Int: return std::to_string(pref.getValue<int>());
case Preference::Type::Double: return std::to_string(pref.getValue<double>());
case Preference::Type::Float: return std::to_string(pref.getValue<float>());
default:
return "UNSUPPORTED";
}
} catch (...) {
throw InvalidArgument("The value of '" + pref.getKey() + "' is not a '" + convertToString(type) + "'");
}
}
}
Preference::Preference(const std::string &key, Preference::Type type) :
property_{key},
type_{type}
{
if (property_.getName().empty())
throw InvalidArgument("Preference key cannot be an an empty string");
if (property_.getName().find_first_of(' ') != std::string::npos)
throw InvalidArgument("Preference key must not have whitespaces");
}
Preference::Type Preference::getType() const {
return type_;
}
const std::string &Preference::getKey() const {
return property_.getName();
}
bool Preference::hasValue() const {
return property_.hasValue();
}
void Preference::setDescription(const std::string &description) {
if (description.find_first_of('\n') != std::string::npos)
throw InvalidArgument("Preference description must not be multiline");
description_ = description;
}
const std::string &Preference::getDescription() const {
return description_;
}
void savePref(const Preference &pref, const std::string &filename) {
std::string entry{pref.getDescription().empty() ? "\n\n" : "\n\n# " + pref.getDescription() + "\n"};
entry += pref.getKey() + ":" + convertToString(pref.getType()) + "=" + convertToString(pref.getType(), pref);
auto configurations = std::stringstream{entry};
utility::DiskFileReader().writeToFile(configurations, filename, utility::WriteMode::Append);
}
}
| 43.382353 | 119 | 0.602938 | KwenaMashamaite |
06f304c1aee397cbff5bbe9e1d0e961873b9eae0 | 443 | cpp | C++ | September LeetCode Challenge/Day_24.cpp | mishrraG/100DaysOfCode | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 13 | 2020-08-10T14:06:37.000Z | 2020-09-24T14:21:33.000Z | September LeetCode Challenge/Day_24.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | null | null | null | September LeetCode Challenge/Day_24.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 1 | 2020-05-31T21:09:14.000Z | 2020-05-31T21:09:14.000Z | class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char, int>mp;
for (int i = 0; i < s.length(); i++)
{
mp[s[i]]++;
}
char x;
for (int i = 0; i < t.length(); i++)
{
if (!mp[t[i]]) {
x = t[i];
break;
}
else
mp[t[i]]--;
}
return x;
}
}; | 21.095238 | 48 | 0.334086 | mishrraG |
06f36dcb18f781b9264b1e5d2a730ba728f28ac4 | 453 | hpp | C++ | src/block.hpp | marchelzo/motherload | 6e16797d198171c1039105f3af9a4df54bd6c218 | [
"MIT"
] | 1 | 2016-12-09T08:00:01.000Z | 2016-12-09T08:00:01.000Z | src/block.hpp | marchelzo/motherload | 6e16797d198171c1039105f3af9a4df54bd6c218 | [
"MIT"
] | 1 | 2016-12-09T08:03:43.000Z | 2018-11-15T15:04:35.000Z | src/block.hpp | marchelzo/motherload | 6e16797d198171c1039105f3af9a4df54bd6c218 | [
"MIT"
] | null | null | null | #include <cstdlib>
#pragma once
enum class Ore {
COPPER,
TIN,
IRON,
SILVER,
GOLD,
RUBY,
DIAMOND,
ROCK,
NUM_ORE_TYPES,
NONE
};
class Block {
Ore ore;
bool _drilled;
bool _drillable;
public:
Block(bool);
size_t texture();
bool drillable();
bool drilled();
bool has_ore();
void drill();
void reserve();
static void load();
};
namespace ORE {
int value_of(Ore);
}
| 12.243243 | 23 | 0.565121 | marchelzo |
06f52b78d0d958cbf5abc481772fc1658500a3a5 | 194 | cpp | C++ | 2019Homeworks/20191209_2017EndTerm/6.MaxProduct.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | 8 | 2019-10-09T14:33:42.000Z | 2020-12-03T00:49:29.000Z | 2019Homeworks/20191209_2017EndTerm/6.MaxProduct.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | 2019Homeworks/20191209_2017EndTerm/6.MaxProduct.cpp | Guyutongxue/Introduction_to_Computation | 062f688fe3ffb8e29cfaf139223e4994edbf64d6 | [
"WTFPL"
] | null | null | null | #include<iostream> // Same as P4-1/9
using namespace std;
int main(){
int s=0,n,i=2,q,j=2;
for(cin>>n;s+i<=n;s+=i++);
for(i--;j++<=i;cout<<j+((q=i-n+s)?-(j<=-~q):j>i)<<" \n"[j>i]);
} | 27.714286 | 66 | 0.484536 | Guyutongxue |
06f877892408d012f4926c6eb73b5e69a9b85c60 | 3,147 | cpp | C++ | src/RotateDialog.cpp | Helios-vmg/Borderless | 8473a667cedadd08dc5d11967aff60b66773b801 | [
"BSD-2-Clause"
] | 2 | 2016-04-28T10:01:02.000Z | 2016-06-13T20:27:16.000Z | src/RotateDialog.cpp | Helios-vmg/Borderless | 8473a667cedadd08dc5d11967aff60b66773b801 | [
"BSD-2-Clause"
] | 1 | 2016-06-13T20:52:23.000Z | 2016-06-14T00:09:19.000Z | src/RotateDialog.cpp | Helios-vmg/Borderless | 8473a667cedadd08dc5d11967aff60b66773b801 | [
"BSD-2-Clause"
] | 2 | 2017-07-26T13:13:48.000Z | 2017-10-18T13:04:41.000Z | /*
Copyright (c), Helios
All rights reserved.
Distributed under a permissive license. See COPYING.txt for details.
*/
#include "RotateDialog.h"
#include "Misc.h"
#include <cmath>
#include <QMessageBox>
const double log_125 = log(1.25);
RotateDialog::RotateDialog(MainWindow &parent) :
QDialog(parent.centralWidget()),
ui(new Ui_RotateDialog),
main_window(parent),
result(false),
in_do_transform(false){
this->setModal(true);
this->ui->setupUi(this);
this->transform = parent.get_image_transform();
connect(this->ui->rotation_slider, SIGNAL(valueChanged(int)), this, SLOT(rotation_slider_changed(int)));
connect(this->ui->scale_slider, SIGNAL(valueChanged(int)), this, SLOT(scale_slider_changed(int)));
connect(this->ui->buttonBox, SIGNAL(rejected()), this, SLOT(rejected_slot()));
this->last_scale = this->original_scale = this->scale = this->main_window.get_image_zoom();
this->rotation_slider_changed(0);
this->set_scale();
this->geometry_set = false;
auto desktop = this->main_window.get_app().desktop();
auto h = 22 * desktop->logicalDpiY() / 96;
this->ui->rotation_slider->setMinimumHeight(h);
this->ui->scale_slider->setMinimumHeight(h);
auto image_size = this->main_window.get_image().size();
auto min_zoom = 1.0 / image_size.width();
auto current_min = pow(1.25, this->ui->scale_slider->minimum() / 1000.0);
if (min_zoom > current_min)
this->ui->scale_slider->setMinimum((int)ceil(log(min_zoom) / log_125 * 1000.0));
}
void RotateDialog::resizeEvent(QResizeEvent *e){
if (this->geometry_set){
QDialog::resizeEvent(e);
return;
}
this->geometry_set = true;
auto size = this->size();
size.setWidth(size.height() * 400 / 143);
this->setMinimumWidth(size.width());
this->setMinimumHeight(size.height());
this->setMaximumHeight(size.height());
this->updateGeometry();
}
void RotateDialog::do_transform(bool set_zoom){
auto scale = this->main_window.set_image_transform(this->transform * QMatrix().rotate(this->rotation));
if (!this->main_window.current_zoom_mode_is_auto() || set_zoom && !this->in_do_transform)
this->main_window.set_image_zoom(this->scale);
else{
this->in_do_transform = true;
this->scale = scale;
this->set_scale();
this->in_do_transform = false;
}
}
void RotateDialog::set_scale(){
this->ui->scale_slider->setValue((int)(log(this->scale) / log_125 * 1000.0));
this->set_scale_label();
}
void RotateDialog::rotation_slider_changed(int value){
double theta = value / 100.0;
QString s = QString::fromStdString(itoac(theta));
s += " deg";
this->ui->rotation_label->setText(s);
this->rotation = theta;
this->do_transform();
}
void RotateDialog::set_scale_label(){
QString s = QString::fromStdString(itoac(this->scale));
s += "x";
this->ui->scale_label->setText(s);
}
void RotateDialog::scale_slider_changed(int value){
double x = value / 1000.0;
this->scale = pow(1.25, x);
this->set_scale_label();
this->do_transform(true);
}
void RotateDialog::rejected_slot(){
this->rotation = 0;
this->scale = this->original_scale;
this->do_transform();
}
| 31.158416 | 106 | 0.698443 | Helios-vmg |
06fb25a25110444df4a5f2b1ec74b8e9ac82351f | 799 | cpp | C++ | Flongo/src/Platform/OpenGL/OpenGLContext.cpp | Hans-Jeiger/Flongo | 2dc99e64cd24ab4190e220f27d1ad4ba45ffd9af | [
"Apache-2.0"
] | null | null | null | Flongo/src/Platform/OpenGL/OpenGLContext.cpp | Hans-Jeiger/Flongo | 2dc99e64cd24ab4190e220f27d1ad4ba45ffd9af | [
"Apache-2.0"
] | null | null | null | Flongo/src/Platform/OpenGL/OpenGLContext.cpp | Hans-Jeiger/Flongo | 2dc99e64cd24ab4190e220f27d1ad4ba45ffd9af | [
"Apache-2.0"
] | null | null | null | #include "flopch.h"
#include "OpenGLContext.h"
#include "Flongo/Core.h"
#include "Flongo/Log.h"
#include <GLFW/glfw3.h>
#include <glad/glad.h>
namespace Flongo
{
OpenGLContext::OpenGLContext(GLFWwindow* windowHandle)
: windowHandle(windowHandle)
{
FLO_CORE_ASSERT(windowHandle, "windowHandle is null!");
}
void OpenGLContext::init()
{
glfwMakeContextCurrent(windowHandle);
int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
FLO_CORE_ASSERT(status, "Failed to initialize Glad!");
FLO_CORE_INFO("Vendor: {0}", glGetString(GL_VENDOR));
FLO_CORE_INFO("OpenGL Info:");
FLO_CORE_INFO("Renderer: {0}", glGetString(GL_RENDERER));
FLO_CORE_INFO("Version: {0}", glGetString(GL_VERSION));
}
void OpenGLContext::swapBuffers()
{
glfwSwapBuffers(windowHandle);
}
} | 23.5 | 66 | 0.740926 | Hans-Jeiger |
06fc94d0f452cd8af8f9ab9fdfea9384bc463e90 | 9,264 | hh | C++ | vm/vm/main/cached/DictionaryLike-interf.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 379 | 2015-01-02T20:27:33.000Z | 2022-03-26T23:18:17.000Z | vm/vm/main/cached/DictionaryLike-interf.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 81 | 2015-01-08T13:18:52.000Z | 2021-12-21T14:02:21.000Z | vm/vm/main/cached/DictionaryLike-interf.hh | Ahzed11/mozart2 | 4806504b103e11be723e7813be8f69e4d85875cf | [
"BSD-2-Clause"
] | 75 | 2015-01-06T09:08:20.000Z | 2021-12-17T09:40:18.000Z | class DictionaryLike {
public:
DictionaryLike(RichNode self) : _self(self) {}
DictionaryLike(UnstableNode& self) : _self(self) {}
DictionaryLike(StableNode& self) : _self(self) {}
bool isDictionary(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().isDictionary(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
bool _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::isDictionary", "isDictionary", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().isDictionary(_self, vm);
}
}
bool dictIsEmpty(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictIsEmpty(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
bool _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictIsEmpty", "dictIsEmpty", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictIsEmpty(_self, vm);
}
}
bool dictMember(VM vm, class mozart::RichNode feature) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictMember(vm, feature);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
bool _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictMember", "dictMember", feature, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictMember(_self, vm, feature);
}
}
class mozart::UnstableNode dictGet(VM vm, class mozart::RichNode feature) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictGet(vm, feature);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictGet", "dictGet", feature, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictGet(_self, vm, feature);
}
}
class mozart::UnstableNode dictCondGet(VM vm, class mozart::RichNode feature, class mozart::RichNode defaultValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictCondGet(vm, feature, defaultValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictCondGet", "dictCondGet", feature, defaultValue, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictCondGet(_self, vm, feature, defaultValue);
}
}
void dictPut(VM vm, class mozart::RichNode feature, class mozart::RichNode newValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictPut(vm, feature, newValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictPut", "dictPut", feature, newValue))
return;
}
return Interface<DictionaryLike>().dictPut(_self, vm, feature, newValue);
}
}
class mozart::UnstableNode dictExchange(VM vm, class mozart::RichNode feature, class mozart::RichNode newValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictExchange(vm, feature, newValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictExchange", "dictExchange", feature, newValue, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictExchange(_self, vm, feature, newValue);
}
}
class mozart::UnstableNode dictCondExchange(VM vm, class mozart::RichNode feature, class mozart::RichNode defaultValue, class mozart::RichNode newValue) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictCondExchange(vm, feature, defaultValue, newValue);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictCondExchange", "dictCondExchange", feature, defaultValue, newValue, ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictCondExchange(_self, vm, feature, defaultValue, newValue);
}
}
void dictRemove(VM vm, class mozart::RichNode feature) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictRemove(vm, feature);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictRemove", "dictRemove", feature))
return;
}
return Interface<DictionaryLike>().dictRemove(_self, vm, feature);
}
}
void dictRemoveAll(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictRemoveAll(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictRemoveAll", "dictRemoveAll"))
return;
}
return Interface<DictionaryLike>().dictRemoveAll(_self, vm);
}
}
class mozart::UnstableNode dictKeys(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictKeys(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictKeys", "dictKeys", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictKeys(_self, vm);
}
}
class mozart::UnstableNode dictEntries(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictEntries(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictEntries", "dictEntries", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictEntries(_self, vm);
}
}
class mozart::UnstableNode dictItems(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictItems(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictItems", "dictItems", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictItems(_self, vm);
}
}
class mozart::UnstableNode dictClone(VM vm) {
if (_self.is<Dictionary>()) {
return _self.as<Dictionary>().dictClone(vm);
} else if (_self.isTransient()) {
waitFor(vm, _self);
throw std::exception(); // not reachable
} else {
if (_self.is< ::mozart::ReflectiveEntity>()) {
class mozart::UnstableNode _result;
if (_self.as< ::mozart::ReflectiveEntity>().reflectiveCall(vm, "$intf$::DictionaryLike::dictClone", "dictClone", ::mozart::ozcalls::out(_result)))
return _result;
}
return Interface<DictionaryLike>().dictClone(_self, vm);
}
}
protected:
RichNode _self;
};
| 40.103896 | 201 | 0.635255 | Ahzed11 |
06fe339a1f9eac884c9ca0977b03760bc7013dda | 1,638 | cpp | C++ | windz/net/test/tcpclient_test1.cpp | Crystalwindz/windz | f13ea10187eb1706d1c7b31b34ce1bf458d721bd | [
"MIT"
] | null | null | null | windz/net/test/tcpclient_test1.cpp | Crystalwindz/windz | f13ea10187eb1706d1c7b31b34ce1bf458d721bd | [
"MIT"
] | null | null | null | windz/net/test/tcpclient_test1.cpp | Crystalwindz/windz | f13ea10187eb1706d1c7b31b34ce1bf458d721bd | [
"MIT"
] | null | null | null | #include "windz/base/Thread.h"
#include "windz/base/Util.h"
#include "windz/net/Channel.h"
#include "windz/net/EventLoop.h"
#include "windz/net/TcpClient.h"
#include <iostream>
#include <memory>
#include <vector>
using namespace windz;
int main(int argc, char **argv) {
EventLoop loop;
InetAddr addr("127.0.0.1", 2019);
TcpClient client(&loop, addr, "client");
auto channel = std::make_shared<Channel>(&loop, STDIN_FILENO);
client.SetConnectionCallBack([&loop, channel](const TcpConnectionPtr &conn) {
std::cout << conn->local_addr().IpPortString() << " -> " << conn->peer_addr().IpPortString()
<< (conn->connected() ? " Connect.\n" : " Disconnect.\n");
if (conn->connected()) {
std::weak_ptr<TcpConnection> weak_conn(conn);
channel->SetReadHandler([weak_conn, channel] {
auto conn = weak_conn.lock();
if (conn) {
std::string msg;
util::SetNonBlockAndCloseOnExec(STDIN_FILENO);
net::ReadFd(STDIN_FILENO, msg);
conn->Send(msg);
}
});
channel->SetErrorHandler([conn] {
conn->Send("STDIN EOF ERROR\n");
sleep(60);
});
channel->EnableRead();
} else {
channel->DisableRead();
}
});
client.SetMessageCallBack([](const TcpConnectionPtr &conn, Buffer &buffer) {
std::string msg(buffer.ReadAll());
std::cout << msg << std::flush;
});
client.EnableRetry();
client.Connect();
loop.Loop();
}
| 32.76 | 100 | 0.551893 | Crystalwindz |
06ff64fed4b79226cbc69a7c9129b5ce117d3a04 | 4,492 | cpp | C++ | src/implementation/engine/components/RigidDynamicComponent.cpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | null | null | null | src/implementation/engine/components/RigidDynamicComponent.cpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | 2 | 2022-01-18T21:31:01.000Z | 2022-01-20T21:02:09.000Z | src/implementation/engine/components/RigidDynamicComponent.cpp | LarsHagemann/OrbitEngine | 33e01efaac617c53a701f01729581932fc81e8bf | [
"MIT"
] | null | null | null | #include "implementation/engine/components/RigidDynamicComponent.hpp"
#include "implementation/misc/Logger.hpp"
#include <extensions/PxDefaultStreams.h>
#include <extensions/PxRigidActorExt.h>
#include <PxMaterial.h>
#define PX_RELEASE(x) if(x) { x->release(); x = nullptr; }
namespace orbit
{
RigidDynamicComponent::RigidDynamicComponent(GameObject* boundObject, ResourceId meshId) :
Physically(boundObject)
{
m_mesh = std::make_shared<Mesh<Vertex>>();
m_mesh->SetId(meshId);
m_mesh->Load();
}
RigidDynamicComponent::~RigidDynamicComponent()
{
ORBIT_INFO_LEVEL(ORBIT_LEVEL_DEBUG, "Releasing RigidStaticComponent");
std::vector<PxMaterial*> materials;
materials.resize(m_shape->getNbMaterials());
m_shape->getMaterials(materials.data(), materials.size());
PX_RELEASE(m_shape);
for (auto material : materials)
{
PX_RELEASE(material);
}
materials.clear();
m_bodies.clear();
m_nextId = 0;
}
void RigidDynamicComponent::Update(size_t millis)
{
for (auto& [id, body] : m_bodies)
{
if (!body->isSleeping())
{
m_transforms[id]->SetTranslation(orbit::Math<float>::PxToEigen(body->getGlobalPose().p));
m_transforms[id]->SetRotation(orbit::Math<float>::PxToEigen(body->getGlobalPose().q));
}
}
}
std::shared_ptr<RigidDynamicComponent> RigidDynamicComponent::create(GameObject* boundObject, ResourceId meshId)
{
return std::make_shared<RigidDynamicComponent>(boundObject, meshId);
}
void RigidDynamicComponent::CookBody(MaterialProperties material_p, Vector3f meshScale, size_t vertexPositionOffset)
{
const auto& vertexData = m_mesh->GetVertexBuffer();
const auto& indexData = m_mesh->GetIndexBuffer();
std::vector<Vector3f> colliderPositions;
colliderPositions.reserve(vertexData->NumVertices());
const auto stride = vertexData->GetBufferSize() / vertexData->NumVertices();
for (auto i = 0u; i < vertexData->NumVertices(); ++i)
{
auto position = vertexData->GetVertices().at(i).position;
colliderPositions.emplace_back(position);
}
PxTriangleMeshDesc meshDesc;
meshDesc.points.count = static_cast<PxU32>(colliderPositions.size());
meshDesc.points.stride = sizeof(Vector3f);
meshDesc.points.data = colliderPositions.data();
meshDesc.triangles.count = static_cast<PxU32>(indexData->NumIndices() / 3);
meshDesc.triangles.stride = 3 * sizeof(uint32_t);
meshDesc.triangles.data = indexData->GetIndices().data();
PxDefaultMemoryOutputStream writeBuffer;
PxTriangleMeshCookingResult::Enum result;
auto status = Engine::Get()->GetCooking()->cookTriangleMesh(meshDesc, writeBuffer, &result);
if (status)
{
PxDefaultMemoryInputData readBuffer(writeBuffer.getData(), writeBuffer.getSize());
auto colliderMesh = Engine::Get()->GetPhysics()->createTriangleMesh(readBuffer);
auto material = Engine::Get()->GetPhysics()->createMaterial(
material_p.staticFriction,
material_p.dynamicFriction,
material_p.restitution
);
m_geometry.triangleMesh = colliderMesh;
m_geometry.scale = PxMeshScale(Math<float>::EigenToPx3(meshScale));
m_shape = std::unique_ptr<PxShape, PxDelete<PxShape>>(ENGINE->GetPhysics()->createShape(
m_geometry,
*material,
false,
PxShapeFlag::eSCENE_QUERY_SHAPE));
}
else
{
ORBIT_ERROR("Failed to cook triangle mesh.");
}
}
unsigned RigidDynamicComponent::AddActor(std::shared_ptr<Transform> transform)
{
auto body = ENGINE->GetPhysics()->createRigidDynamic(PxTransform(
Math<float>::EigenToPx3(transform->GetCombinedTranslation()),
Math<float>::EigenToPx(Quaternionf(transform->GetCombinedRotation()))));
auto id = m_nextId++;
m_bodies[id] = std::unique_ptr<PxRigidDynamic, PxDelete<PxRigidDynamic>>(body);
m_transforms[id] = transform;
body->attachShape(*m_shape);
body->setMass(0.5f);
ENGINE->GetPhysXScene()->addActor(*body);
return id;
}
} | 37.433333 | 120 | 0.633793 | LarsHagemann |
660acd622b4db8af5a7e6b68eb959bc6070d760e | 266 | cpp | C++ | src/gameworld/gameworld/global/activity/impl/activityxingzuoyiji.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 3 | 2021-12-16T13:57:28.000Z | 2022-03-26T07:50:08.000Z | src/gameworld/gameworld/global/activity/impl/activityxingzuoyiji.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | null | null | null | src/gameworld/gameworld/global/activity/impl/activityxingzuoyiji.cpp | mage-game/metagame-xm-server | 193b67389262803fe0eae742800b1e878b5b3087 | [
"MIT"
] | 1 | 2022-03-26T07:50:11.000Z | 2022-03-26T07:50:11.000Z | #include "activityxingzuoyiji.hpp"
#include "config/logicconfigmanager.hpp"
ActivityXingzuoYiji::ActivityXingzuoYiji(ActivityManager *activity_manager)
: Activity(activity_manager, ACTIVITY_TYPE_XINGZUOYIJI)
{
}
ActivityXingzuoYiji::~ActivityXingzuoYiji()
{
}
| 16.625 | 75 | 0.823308 | mage-game |
6615746073f17a2f1e720c04a6e30c0dd63d1e22 | 239 | cpp | C++ | Atomic/AtUtf8Lit.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 4 | 2019-11-10T21:56:40.000Z | 2021-12-11T20:10:55.000Z | Atomic/AtUtf8Lit.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | null | null | null | Atomic/AtUtf8Lit.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 1 | 2019-11-11T08:38:59.000Z | 2019-11-11T08:38:59.000Z | #include "AtIncludes.h"
#include "AtUtf8Lit.h"
namespace At
{
namespace Utf8
{
namespace Lit
{
Seq const BOM { "\xEF\xBB\xBF", 3 }; // U+FEFF
Seq const Ellipsis { "\xE2\x80\xA6", 3 }; // U+2026
}
}
}
| 14.058824 | 55 | 0.535565 | denisbider |
66166a6b354ad4503185ffc58c129fa07cc8a896 | 219 | cpp | C++ | March Cook-Off 2022/Janmansh and Games.cpp | tarunbisht-24/Codechef-Contests | 8e7dcf69b839d586f4e73bc8183b8963a8cf1d50 | [
"Apache-2.0"
] | 1 | 2022-03-06T18:27:58.000Z | 2022-03-06T18:27:58.000Z | March Cook-Off 2022/Janmansh and Games.cpp | tarunbisht-24/Codechef-Contests | 8e7dcf69b839d586f4e73bc8183b8963a8cf1d50 | [
"Apache-2.0"
] | null | null | null | March Cook-Off 2022/Janmansh and Games.cpp | tarunbisht-24/Codechef-Contests | 8e7dcf69b839d586f4e73bc8183b8963a8cf1d50 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
int x,y;
cin>>x>>y;
if((x+y)&1)
cout<<"Jay"<<endl;
else
cout<<"Janmansh"<<endl;
}
return 0;
}
| 11.526316 | 28 | 0.484018 | tarunbisht-24 |
66200635a948bc973c086e585dfc52faaba9fa4f | 333 | cpp | C++ | Luogu/P3811.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3811.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | Luogu/P3811.cpp | XenonWZH/involution | 189f6ce2bbfe3a7c5d536bbd769f353e4c06e7c6 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <iostream>
const int MAXN = 3000000;
int main() {
int n, p;
std::cin >> n >> p;
static long long inv[MAXN + 1];
inv[1] = 1;
puts("1");
for(int i = 2; i <= n; i++) {
inv[i] = ((long long)p - p / i) * inv[p % i] % p;
printf("%lld\n", inv[i]);
}
return 0;
} | 17.526316 | 57 | 0.456456 | XenonWZH |
66214b60e0a23807b04b06fb548a9118d68dda53 | 6,086 | cpp | C++ | Source/D3D12/DescriptorPoolD3D12.cpp | jayrulez/NRIOOP | 375dd2e4e5a33863a84e6c8166488f1139fb2f74 | [
"MIT"
] | null | null | null | Source/D3D12/DescriptorPoolD3D12.cpp | jayrulez/NRIOOP | 375dd2e4e5a33863a84e6c8166488f1139fb2f74 | [
"MIT"
] | null | null | null | Source/D3D12/DescriptorPoolD3D12.cpp | jayrulez/NRIOOP | 375dd2e4e5a33863a84e6c8166488f1139fb2f74 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include "SharedD3D12.h"
#include "DescriptorPoolD3D12.h"
#include "DeviceD3D12.h"
#include "PipelineLayoutD3D12.h"
using namespace nri;
extern D3D12_DESCRIPTOR_HEAP_TYPE GetDescriptorHeapType(DescriptorType descriptorType);
DescriptorPoolD3D12::DescriptorPoolD3D12(DeviceD3D12& device)
: m_Device(device)
, m_DescriptorSets(device.GetStdAllocator())
{}
DescriptorPoolD3D12::~DescriptorPoolD3D12()
{
for (size_t i = 0; i < m_DescriptorSetNum; i++)
Deallocate(m_Device.GetStdAllocator(), m_DescriptorSets[i]);
}
Result DescriptorPoolD3D12::Create(const DescriptorPoolDesc& descriptorPoolDesc)
{
uint32_t descriptorHeapSize[DescriptorHeapType::MAX_NUM] = {};
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.constantBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.textureMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.storageTextureMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.bufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.storageBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.structuredBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.storageStructuredBufferMaxNum;
descriptorHeapSize[DescriptorHeapType::RESOURCE] += descriptorPoolDesc.accelerationStructureMaxNum;
descriptorHeapSize[DescriptorHeapType::SAMPLER] += descriptorPoolDesc.samplerMaxNum;
for (uint32_t i = 0; i < DescriptorHeapType::MAX_NUM; i++)
{
if (descriptorHeapSize[i])
{
ComPtr<ID3D12DescriptorHeap> descriptorHeap;
D3D12_DESCRIPTOR_HEAP_DESC desc = { (D3D12_DESCRIPTOR_HEAP_TYPE)i, descriptorHeapSize[i], D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NRI_TEMP_NODE_MASK };
HRESULT hr = ((ID3D12Device*)m_Device)->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&descriptorHeap));
if (FAILED(hr))
{
REPORT_ERROR(m_Device.GetLog(), "ID3D12Device::CreateDescriptorHeap() failed, return code %d.", hr);
return Result::FAILURE;
}
m_DescriptorHeapDescs[i].descriptorHeap = descriptorHeap;
m_DescriptorHeapDescs[i].descriptorPointerCPU = descriptorHeap->GetCPUDescriptorHandleForHeapStart().ptr;
m_DescriptorHeapDescs[i].descriptorPointerGPU = descriptorHeap->GetGPUDescriptorHandleForHeapStart().ptr;
m_DescriptorHeapDescs[i].descriptorSize = ((ID3D12Device*)m_Device)->GetDescriptorHandleIncrementSize((D3D12_DESCRIPTOR_HEAP_TYPE)i);
m_DescriptorHeaps[m_DescriptorHeapNum] = descriptorHeap;
m_DescriptorHeapNum++;
}
}
m_DescriptorSets.resize(descriptorPoolDesc.descriptorSetMaxNum);
return Result::SUCCESS;
}
void DescriptorPoolD3D12::Bind(ID3D12GraphicsCommandList* graphicsCommandList) const
{
graphicsCommandList->SetDescriptorHeaps(m_DescriptorHeapNum, m_DescriptorHeaps.data());
}
uint32_t DescriptorPoolD3D12::AllocateDescriptors(DescriptorHeapType descriptorHeapType, uint32_t descriptorNum)
{
uint32_t descriptorOffset = m_DescriptorNum[descriptorHeapType];
m_DescriptorNum[descriptorHeapType] += descriptorNum;
return descriptorOffset;
}
DescriptorPointerCPU DescriptorPoolD3D12::GetDescriptorPointerCPU(DescriptorHeapType descriptorHeapType, uint32_t offset) const
{
const DescriptorHeapDesc& descriptorHeapDesc = m_DescriptorHeapDescs[descriptorHeapType];
DescriptorPointerCPU descriptorPointer = descriptorHeapDesc.descriptorPointerCPU + offset * descriptorHeapDesc.descriptorSize;
return descriptorPointer;
}
DescriptorPointerGPU DescriptorPoolD3D12::GetDescriptorPointerGPU(DescriptorHeapType descriptorHeapType, uint32_t offset) const
{
const DescriptorHeapDesc& descriptorHeapDesc = m_DescriptorHeapDescs[descriptorHeapType];
DescriptorPointerGPU descriptorPointer = descriptorHeapDesc.descriptorPointerGPU + offset * descriptorHeapDesc.descriptorSize;
return descriptorPointer;
}
inline void DescriptorPoolD3D12::SetDebugName(const char* name)
{
MaybeUnused(name);
}
inline Result DescriptorPoolD3D12::AllocateDescriptorSets(const PipelineLayout& pipelineLayout, uint32_t setIndex, DescriptorSet** const descriptorSets, uint32_t instanceNum, uint32_t physicalDeviceMask, uint32_t variableDescriptorNum)
{
MaybeUnused(variableDescriptorNum);
if (m_DescriptorSetNum + instanceNum > m_DescriptorSets.size())
return Result::FAILURE;
const PipelineLayoutD3D12& pipelineLayoutD3D12 = (PipelineLayoutD3D12&)pipelineLayout;
const DescriptorSetMapping& descriptorSetMapping = pipelineLayoutD3D12.GetDescriptorSetMapping(setIndex);
const DynamicConstantBufferMapping& dynamicConstantBufferMapping = pipelineLayoutD3D12.GetDynamicConstantBufferMapping(setIndex);
for (uint32_t i = 0; i < instanceNum; i++)
{
DescriptorSetD3D12* descriptorSet = Allocate<DescriptorSetD3D12>(m_Device.GetStdAllocator(), m_Device, *this, descriptorSetMapping, dynamicConstantBufferMapping.constantNum);
m_DescriptorSets[m_DescriptorSetNum + i] = descriptorSet;
descriptorSets[i] = (DescriptorSet*)descriptorSet;
}
m_DescriptorSetNum += instanceNum;
return Result::SUCCESS;
}
inline void DescriptorPoolD3D12::Reset()
{
for (uint32_t i = 0; i < DescriptorHeapType::MAX_NUM; i++)
m_DescriptorNum[i] = 0;
for (uint32_t i = 0; i < m_DescriptorSetNum; i++)
Deallocate(m_Device.GetStdAllocator(), m_DescriptorSets[i]);
m_DescriptorSetNum = 0;
}
| 43.784173 | 235 | 0.781794 | jayrulez |
662382512402483c434b97928f9c85ad59240c61 | 5,374 | cpp | C++ | src/common/utils/LegacySupport.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 2,313 | 2017-03-24T16:25:28.000Z | 2022-03-31T03:00:30.000Z | src/common/utils/LegacySupport.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 952 | 2017-03-28T07:05:58.000Z | 2022-03-30T09:54:02.000Z | src/common/utils/LegacySupport.cpp | MaximMilashchenko/ComputeLibrary | 91ee4d0a9ef128b16936921470a0e3ffef347536 | [
"MIT"
] | 714 | 2017-03-24T22:21:51.000Z | 2022-03-18T19:49:57.000Z | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "src/common/utils/LegacySupport.h"
namespace arm_compute
{
namespace detail
{
namespace
{
DataType convert_to_legacy_data_type(AclDataType data_type)
{
switch(data_type)
{
case AclDataType::AclFloat32:
return DataType::F32;
case AclDataType::AclFloat16:
return DataType::F16;
case AclDataType::AclBFloat16:
return DataType::BFLOAT16;
default:
return DataType::UNKNOWN;
}
}
AclDataType convert_to_c_data_type(DataType data_type)
{
switch(data_type)
{
case DataType::F32:
return AclDataType::AclFloat32;
case DataType::F16:
return AclDataType::AclFloat16;
case DataType::BFLOAT16:
return AclDataType::AclBFloat16;
default:
return AclDataType::AclDataTypeUnknown;
}
}
TensorShape create_legacy_tensor_shape(int32_t ndims, int32_t *shape)
{
TensorShape legacy_shape{};
for(int32_t d = 0; d < ndims; ++d)
{
legacy_shape.set(d, shape[d], false);
}
return legacy_shape;
}
int32_t *create_tensor_shape_array(const TensorInfo &info)
{
const auto num_dims = info.num_dimensions();
if(num_dims <= 0)
{
return nullptr;
}
int32_t *shape_array = new int32_t[num_dims];
for(size_t d = 0; d < num_dims; ++d)
{
shape_array[d] = info.tensor_shape()[d];
}
return shape_array;
}
} // namespace
TensorInfo convert_to_legacy_tensor_info(const AclTensorDescriptor &desc)
{
TensorInfo legacy_desc;
legacy_desc.init(create_legacy_tensor_shape(desc.ndims, desc.shape), 1, convert_to_legacy_data_type(desc.data_type));
return legacy_desc;
}
AclTensorDescriptor convert_to_descriptor(const TensorInfo &info)
{
const auto num_dims = info.num_dimensions();
AclTensorDescriptor desc
{
static_cast<int32_t>(num_dims),
create_tensor_shape_array(info),
convert_to_c_data_type(info.data_type()),
nullptr,
0
};
return desc;
}
ActivationLayerInfo convert_to_activation_info(const AclActivationDescriptor &desc)
{
ActivationLayerInfo::ActivationFunction act;
switch(desc.type)
{
case AclActivationType::AclIdentity:
act = ActivationLayerInfo::ActivationFunction::IDENTITY;
break;
case AclActivationType::AclLogistic:
act = ActivationLayerInfo::ActivationFunction::LOGISTIC;
break;
case AclActivationType::AclTanh:
act = ActivationLayerInfo::ActivationFunction::TANH;
break;
case AclActivationType::AclRelu:
act = ActivationLayerInfo::ActivationFunction::RELU;
break;
case AclActivationType::AclBoundedRelu:
act = ActivationLayerInfo::ActivationFunction::BOUNDED_RELU;
break;
case AclActivationType::AclLuBoundedRelu:
act = ActivationLayerInfo::ActivationFunction::LU_BOUNDED_RELU;
break;
case AclActivationType::AclLeakyRelu:
act = ActivationLayerInfo::ActivationFunction::LEAKY_RELU;
break;
case AclActivationType::AclSoftRelu:
act = ActivationLayerInfo::ActivationFunction::SOFT_RELU;
break;
case AclActivationType::AclElu:
act = ActivationLayerInfo::ActivationFunction::ELU;
break;
case AclActivationType::AclAbs:
act = ActivationLayerInfo::ActivationFunction::ABS;
break;
case AclActivationType::AclSquare:
act = ActivationLayerInfo::ActivationFunction::SQUARE;
break;
case AclActivationType::AclSqrt:
act = ActivationLayerInfo::ActivationFunction::SQRT;
break;
case AclActivationType::AclLinear:
act = ActivationLayerInfo::ActivationFunction::LINEAR;
break;
case AclActivationType::AclHardSwish:
act = ActivationLayerInfo::ActivationFunction::HARD_SWISH;
break;
default:
return ActivationLayerInfo();
}
return ActivationLayerInfo(act, desc.a, desc.b);
}
} // namespace detail
} // namespace arm_compute
| 32.373494 | 121 | 0.673986 | MaximMilashchenko |
662c49c56d4c908d0daabaae80c328f22ebe1bc6 | 1,399 | cpp | C++ | solutions/different-ways-to-add-parentheses/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/different-ways-to-add-parentheses/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/different-ways-to-add-parentheses/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-08-30T06:53:23.000Z | 2019-08-30T06:53:23.000Z | #include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
out << '[';
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin())
out << ',';
out << *it;
}
out << ']';
return out;
}
class Solution {
vector<int> doDiffWaysToCompute(string::const_iterator begin,
string::const_iterator end) {
vector<int> result;
for (auto it = begin; it != end; ++it) {
char c = *it;
if (isdigit(c))
continue;
auto left = doDiffWaysToCompute(begin, it);
auto right = doDiffWaysToCompute(it + 1, end);
for (auto l: left) {
for (auto r: right) {
int v = 0;
switch (c) {
case '+':
v = l + r;
break;
case '-':
v = l - r;
break;
case '*':
v = l * r;
break;
default:
break;
}
result.push_back(v);
}
}
}
if (result.empty())
result.push_back(stoi(string(begin, end)));
return result;
}
public:
vector<int> diffWaysToCompute(const string& s) {
return doDiffWaysToCompute(s.begin(), s.end());
}
};
int main()
{
string input[] = {
"2", // [2]
"2+1", // [3]
"2-1-1", // [0, 2]
"2*3-4*5", // [-34, -14, -10, -10, 10]
};
Solution solution;
for (const auto& s: input) {
cout << '"' << s << "\" => " <<
solution.diffWaysToCompute(s) << endl;
}
return 0;
}
| 18.653333 | 62 | 0.531094 | locker |
662e664e38befd8ae3bd7f798b1092712bb7c15e | 2,035 | hpp | C++ | data_structure.hpp | Pumpkrin/surfer_girl | 98af7692fd81b8fc4e11c85af43adc5d0b951874 | [
"MIT"
] | null | null | null | data_structure.hpp | Pumpkrin/surfer_girl | 98af7692fd81b8fc4e11c85af43adc5d0b951874 | [
"MIT"
] | null | null | null | data_structure.hpp | Pumpkrin/surfer_girl | 98af7692fd81b8fc4e11c85af43adc5d0b951874 | [
"MIT"
] | null | null | null | #ifndef DATA_STRUCTURE_HPP
#define DATA_STRUCTURE_HPP
#include <array>
#include <iostream>
#include "TH1.h"
namespace sf_g {
template<class ... Ts> struct composite : Ts... {
void value() {
int expander[] = {0, ( static_cast<Ts&>(*this).value(), void(), 0)...};
}
};
// ------------------------------raw----------------------------------
struct raw_waveform {
int channel_id;
int event_id;
int fcr;
float baseline;
float amplitude;
float charge;
float leading_edge;
float trailing_edge;
float rate_counter;
std::array<short, 1024> sample_c;
};
struct event_data {
int event_id;
double epoch_time;
struct date_t{
int year;
int month;
int day;
} date;
struct time_t{
int hour;
int minute;
int second;
int millisecond;
} time;
int tdc;
int corrected_tdc;
int channel_count;
};
struct metadata {
int channel_count;
double sampling_period;
};
//-------------------------------------------transformed-------------------------------------------
struct waveform {
TH1D data;
};
struct linked_waveform {
TH1D data;
std::size_t channel_number;
};
struct amplitude { double amplitude; void value() const { std::cout << amplitude << '\n';} };
struct baseline { double baseline; void value() const { std::cout << baseline << '\n';} };
struct cfd_time { double time; void value() const { std::cout << time << '\n';} };
struct charge { double charge; void value() const { std::cout << charge << '\n';} };
struct rise_time { double rise_time; void value() const { std::cout << rise_time << '\n';} };
struct fall_time { double fall_time; void value() const { std::cout << fall_time << '\n';} };
struct mean { double mean; void value() const { std::cout << mean << '\n';} };
struct sigma { double sigma; void value() const { std::cout << sigma << '\n';} };
struct gamma_response{
double gamma_energy;
double deposited_energy;
};
}
#endif
| 25.123457 | 99 | 0.56855 | Pumpkrin |
662ff6c224fc697a3d838e19865d2a3c9ca65c36 | 4,921 | cpp | C++ | Backend/Networking/service.cpp | Gattic/ShmeaDB | ed698dfebde465c9e63a54ab11aac2d6ef311eed | [
"MIT"
] | 3 | 2021-07-31T15:16:39.000Z | 2022-02-07T21:12:36.000Z | Backend/Networking/service.cpp | MeeseeksLookAtMe/ShmeaDB | ed698dfebde465c9e63a54ab11aac2d6ef311eed | [
"MIT"
] | null | null | null | Backend/Networking/service.cpp | MeeseeksLookAtMe/ShmeaDB | ed698dfebde465c9e63a54ab11aac2d6ef311eed | [
"MIT"
] | 1 | 2020-05-28T02:46:43.000Z | 2020-05-28T02:46:43.000Z | // Copyright 2020 Robert Carneiro, Derek Meer, Matthew Tabak, Eric Lujan
//
// 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 "service.h"
#include "connection.h"
#include "socket.h"
using namespace GNet;
// services
#include "../../services/bad_request.h"
#include "../../services/handshake_client.h"
#include "../../services/handshake_server.h"
#include "../../services/logout_client.h"
#include "../../services/logout_server.h"
/*!
* @brief Service constructor
* @details creates a Service object and initialize timeExecuted
*/
Service::Service()
{
timeExecuted = 0;
}
/*!
* @brief Service deconstructor
* @details deconstructs a Service object
*/
Service::~Service()
{
timeExecuted = 0;
}
/*!
* @brief Run execute() asynchronusly as a Service
* @details launch new service thread (command)
* @param sockData a package of network data
* @param cConnection the current connection
*/
void Service::ExecuteService(GServer* serverInstance, const shmea::ServiceData* sockData,
Connection* cConnection)
{
// set the args to pass in
newServiceArgs* x = new newServiceArgs[sizeof(newServiceArgs)];
x->serverInstance = serverInstance;
x->cConnection = cConnection;
x->sockData = sockData;
x->sThread = new pthread_t[sizeof(pthread_t)];
// launch a new service thread
pthread_create(x->sThread, NULL, &launchService, (void*)x);
if (x->sThread)
pthread_detach(*x->sThread);
}
/*!
* @brief Launch a new service
* @details launch service wrapper
* @param y points to memory location for serviceArgs data
*/
void* Service::launchService(void* y)
{
// Helper function for pthread_create
// set the service args
newServiceArgs* x = (newServiceArgs*)y;
if (!x->serverInstance)
return NULL;
GServer* serverInstance = x->serverInstance;
// Get the command in order to tell the service what to do
x->command = x->sockData->getCommand();
if(x->command.length() == 0)//Uncomment this before commit!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return NULL;
// Connection is dead so ignore it
Connection* cConnection = x->cConnection;
if (!cConnection)
return NULL;
if (!cConnection->isFinished())
{
Service* cService = serverInstance->ServiceLookup(x->command);
if (cService)
{
// start the service
cService->StartService(x);
// execute the service
shmea::ServiceData* retData = cService->execute(x->sockData);
if(!retData)
{
serverInstance->socks->addResponseList(serverInstance, cConnection, retData);
}
// exit the service
cService->ExitService(x);
delete cService;
}
}
if (x)
delete x;
// delete the Connection
if (cConnection->isFinished())
delete cConnection;
return NULL;
}
/*!
* @brief Start a service
* @details start a service and set variables
* @param x pointer to new service arguments memory location
*/
void Service::StartService(newServiceArgs* x)
{
// set the start time
timeExecuted = time(NULL);
// Get the ip address
Connection* cConnection = x->cConnection;
shmea::GString ipAddress = "";
if (!cConnection->isFinished())
ipAddress = cConnection->getIP();
// const shmea::GString& command = x->command;
// printf("---------Service Start: %s (%s)---------\n", ipAddress.c_str(), command.c_str());
// add the thread to the connection's active thread vector
cThread = x->sThread;
}
/*!
* @brief Exit Service
* @details exit from a service
* @param x points to memory location for serviceArgs data
*/
void Service::ExitService(newServiceArgs* x)
{
// Get the ip address
Connection* cConnection = x->cConnection;
shmea::GString ipAddress = "";
if (!cConnection->isFinished())
ipAddress = cConnection->getIP();
// Set and print the execution time
timeExecuted = time(NULL) - timeExecuted;
// printf("---------Service Exit: %s (%s); %llds---------\n", ipAddress.c_str(),
// x->command.c_str(), timeExecuted);
pthread_exit(0);
}
| 28.947059 | 119 | 0.704328 | Gattic |
663225b9fb2dff4edf74c89bb3e1d5eaefac2d99 | 1,740 | cc | C++ | gui/goods_stats_t.cc | soukouki/simutrans | 758283664349afb5527db470780767abb4db8114 | [
"Artistic-1.0"
] | null | null | null | gui/goods_stats_t.cc | soukouki/simutrans | 758283664349afb5527db470780767abb4db8114 | [
"Artistic-1.0"
] | 1 | 2017-12-05T18:00:56.000Z | 2017-12-05T18:00:56.000Z | gui/goods_stats_t.cc | soukouki/simutrans | 758283664349afb5527db470780767abb4db8114 | [
"Artistic-1.0"
] | null | null | null | /*
* This file is part of the Simutrans project under the Artistic License.
* (see LICENSE.txt)
*/
#include "goods_stats_t.h"
#include "../simcolor.h"
#include "../simworld.h"
#include "../bauer/goods_manager.h"
#include "../descriptor/goods_desc.h"
#include "../dataobj/translator.h"
#include "components/gui_button.h"
#include "components/gui_colorbox.h"
#include "components/gui_label.h"
karte_ptr_t goods_stats_t::welt;
void goods_stats_t::update_goodslist(vector_tpl<const goods_desc_t*>goods, int bonus)
{
scr_size size = get_size();
remove_all();
set_table_layout(6,0);
FOR(vector_tpl<const goods_desc_t*>, wtyp, goods) {
new_component<gui_colorbox_t>(wtyp->get_color())->set_max_size(scr_size(D_INDICATOR_WIDTH, D_INDICATOR_HEIGHT));
new_component<gui_label_t>(wtyp->get_name());
const sint32 grundwert128 = (sint32)wtyp->get_value() * welt->get_settings().get_bonus_basefactor(); // bonus price will be always at least this
const sint32 grundwert_bonus = (sint32)wtyp->get_value()*(1000l+(bonus-100l)*wtyp->get_speed_bonus());
const sint32 price = (grundwert128>grundwert_bonus ? grundwert128 : grundwert_bonus);
gui_label_buf_t *lb = new_component<gui_label_buf_t>(SYSCOL_TEXT, gui_label_t::right);
lb->buf().append_money(price/300000.0);
lb->update();
lb = new_component<gui_label_buf_t>(SYSCOL_TEXT, gui_label_t::right);
lb->buf().printf("%d%%", wtyp->get_speed_bonus());
lb->update();
new_component<gui_label_t>(wtyp->get_catg_name());
lb = new_component<gui_label_buf_t>(SYSCOL_TEXT, gui_label_t::right);
lb->buf().printf("%dKg", wtyp->get_weight_per_unit());
lb->update();
}
scr_size min_size = get_min_size();
set_size(scr_size(max(size.w, min_size.w), min_size.h) );
}
| 32.222222 | 146 | 0.737931 | soukouki |
66341ff1311714c78d412efe93749a26ce9f5d89 | 17,134 | cpp | C++ | src/sdk/hl2_csgo/game/missionchooser/layout_system/tilegen_layout_system.cpp | newcommerdontblame/ionlib | 47ca829009e1529f62b2134aa6c0df8673864cf3 | [
"MIT"
] | 51 | 2016-03-18T01:48:07.000Z | 2022-03-21T20:02:02.000Z | src/game/missionchooser/layout_system/tilegen_layout_system.cpp | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | null | null | null | src/game/missionchooser/layout_system/tilegen_layout_system.cpp | senny970/AlienSwarm | c5a2d3fa853c726d040032ff2c7b90c8ed8d5d84 | [
"Unlicense"
] | 26 | 2016-03-17T21:20:37.000Z | 2022-03-24T10:21:30.000Z | //============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// Definitions for the rule- and state-based level generation system.
//
//===============================================================================
#include "MapLayout.h"
#include "Room.h"
#include "tilegen_class_factories.h"
#include "tilegen_mission_preprocessor.h"
#include "tilegen_listeners.h"
#include "tilegen_ranges.h"
#include "tilegen_layout_system.h"
#include "asw_npcs.h"
ConVar tilegen_break_on_iteration( "tilegen_break_on_iteration", "-1", FCVAR_CHEAT, "If set to a non-negative value, tilegen will break at the start of iteration #N if a debugger is attached." );
DEFINE_LOGGING_CHANNEL_NO_TAGS( LOG_TilegenLayoutSystem, "TilegenLayoutSystem", 0, LS_MESSAGE, Color( 192, 255, 192, 255 ) );
void AddListeners( CLayoutSystem *pLayoutSystem )
{
// @TODO: need a better mechanism to detect which of these listeners are required. For now, add them all.
pLayoutSystem->AddListener( new CTilegenListener_NumTilesPlaced() );
}
CTilegenState *CTilegenStateList::FindState( const char *pStateName )
{
for ( int i = 0; i < m_States.Count(); ++ i )
{
if ( Q_stricmp( pStateName, m_States[i]->GetStateName() ) == 0 )
{
return m_States[i];
}
CTilegenState *pState = m_States[i]->GetStateList()->FindState( pStateName );
if ( pState != NULL )
{
return pState;
}
}
return NULL;
}
CTilegenState *CTilegenStateList::GetNextState( CTilegenState *pState )
{
int i;
for ( i = 0; i < m_States.Count(); ++ i )
{
if ( m_States[i] == pState )
break;
}
if ( i < ( m_States.Count() - 1 ) )
{
return m_States[i + 1];
}
else if ( i == m_States.Count() )
{
// This should never happen unless there's a bug in the layout code
Log_Warning( LOG_TilegenLayoutSystem, "State %s not found in state list.\n", pState->GetStateName() );
m_pLayoutSystem->OnError();
return NULL;
}
else if ( i == ( m_States.Count() - 1 ) )
{
// We're on the last state
CTilegenStateList *pParentStateList = GetParentStateList();
if ( pParentStateList == NULL )
{
// No more states left in the layout system.
return NULL;
}
else
{
Assert( pState->GetParentState() != NULL );
return pParentStateList->GetNextState( pState->GetParentState() );
}
}
UNREACHABLE();
return NULL;
}
CTilegenStateList *CTilegenStateList::GetParentStateList()
{
if ( m_pOwnerState == NULL )
{
// No parent state implies that this state list is owned by the layout system, so there
// is no parent state list.
return NULL;
}
else if ( m_pOwnerState->GetParentState() == NULL )
{
// A parent state with a NULL parent state implies that this list is owned by a top-level
// state, so the parent state list belongs to the layout system.
return m_pLayoutSystem->GetStateList();
}
else
{
return m_pOwnerState->GetParentState()->GetStateList();
}
}
void CTilegenStateList::OnBeginGeneration()
{
for ( int i = 0; i < m_States.Count(); ++ i )
{
m_States[i]->OnBeginGeneration( m_pLayoutSystem );
}
}
CTilegenState::~CTilegenState()
{
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
delete m_Actions[i].m_pAction;
delete m_Actions[i].m_pCondition;
}
}
bool CTilegenState::LoadFromKeyValues( KeyValues *pKeyValues )
{
const char *pStateName = pKeyValues->GetString( "name", NULL );
if ( pStateName == NULL )
{
Log_Warning( LOG_TilegenLayoutSystem, "No state name found in State key values.\n" );
return false;
}
m_StateName[0] = '\0';
// @TODO: support nested state names?
// if ( pParentStateName != NULL )
// {
// Q_strncat( m_StateName, pParentStateName, MAX_TILEGEN_IDENTIFIER_LENGTH );
// Q_strncat( m_StateName, ".", MAX_TILEGEN_IDENTIFIER_LENGTH );
// }
Q_strncat( m_StateName, pStateName, MAX_TILEGEN_IDENTIFIER_LENGTH );
for ( KeyValues *pSubKey = pKeyValues->GetFirstSubKey(); pSubKey != NULL; pSubKey = pSubKey->GetNextKey() )
{
if ( Q_stricmp( pSubKey->GetName(), "action" ) == 0 )
{
if ( !ParseAction( pSubKey ) )
{
return false;
}
}
else if ( Q_stricmp( pSubKey->GetName(), "state") == 0 )
{
// Nested state
CTilegenState *pNewState = new CTilegenState( GetLayoutSystem(), this );
if ( !pNewState->LoadFromKeyValues( pSubKey ) )
{
delete pNewState;
return false;
}
m_ChildStates.AddState( pNewState );
}
}
return true;
}
void CTilegenState::ExecuteIteration( CLayoutSystem *pLayoutSystem )
{
if ( m_Actions.Count() == 0 )
{
// No actions in this state, go to the first nested state if one exists
// or move on to the next sibling state.
if ( m_ChildStates.GetStateCount() > 0 )
{
Log_Msg( LOG_TilegenLayoutSystem, "No actions found in state %s, transitioning to first child state.\n", GetStateName() );
pLayoutSystem->TransitionToState( m_ChildStates.GetState( 0 ) );
}
else
{
// Try to switch to the next sibling state.
CTilegenState *pNextState = m_ChildStates.GetParentStateList()->GetNextState( this );
if ( pNextState != NULL )
{
Log_Msg( LOG_TilegenLayoutSystem, "No actions or child states found in state %s, transitioning to next state.\n", GetStateName() );
pLayoutSystem->TransitionToState( pNextState );
}
else
{
// This must be the last state in the entire layout system.
Log_Msg( LOG_TilegenLayoutSystem, "No more states to which to transition." );
pLayoutSystem->OnFinished();
}
}
}
else
{
pLayoutSystem->GetFreeVariables()->SetOrCreateFreeVariable( "CurrentState", this );
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
if ( pLayoutSystem->ShouldStopProcessingActions() )
{
break;
}
pLayoutSystem->ExecuteAction( m_Actions[i].m_pAction, m_Actions[i].m_pCondition );
}
pLayoutSystem->GetFreeVariables()->SetOrCreateFreeVariable( "CurrentState", NULL );
}
}
void CTilegenState::OnBeginGeneration( CLayoutSystem *pLayoutSystem )
{
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
m_Actions[i].m_pAction->OnBeginGeneration( pLayoutSystem );
}
m_ChildStates.OnBeginGeneration();
}
void CTilegenState::OnStateChanged( CLayoutSystem *pLayoutSystem )
{
for ( int i = 0; i < m_Actions.Count(); ++ i )
{
m_Actions[i].m_pAction->OnStateChanged( pLayoutSystem );
}
}
bool CTilegenState::ParseAction( KeyValues *pKeyValues )
{
ITilegenAction *pNewAction = NULL;
ITilegenExpression< bool > *pCondition = NULL;
if ( CreateActionAndCondition( pKeyValues, &pNewAction, &pCondition ) )
{
AddAction( pNewAction, pCondition );
return true;
}
else
{
return false;
}
}
CLayoutSystem::CLayoutSystem() :
m_nRandomSeed( 0 ),
m_pGlobalActionState( NULL ),
m_pCurrentState( NULL ),
m_pMapLayout( NULL ),
m_ActionData( DefLessFunc( ITilegenAction *) ),
m_bLayoutError( false ),
m_bGenerating( false ),
m_nIterations( 0 )
{
m_States.SetLayoutSystem( this );
}
CLayoutSystem::~CLayoutSystem()
{
m_TilegenListeners.PurgeAndDeleteElements();
delete m_pGlobalActionState;
}
bool CLayoutSystem::LoadFromKeyValues( KeyValues *pKeyValues )
{
// Make sure all tilegen class factories have been registered.
RegisterAllTilegenClasses();
for ( KeyValues *pSubKey = pKeyValues->GetFirstSubKey(); pSubKey != NULL; pSubKey = pSubKey->GetNextKey() )
{
if ( Q_stricmp( pSubKey->GetName(), "state" ) == 0 )
{
CTilegenState *pNewState = new CTilegenState( this, NULL );
if ( !pNewState->LoadFromKeyValues( pSubKey ) )
{
delete pNewState;
return false;
}
m_States.AddState( pNewState );
}
else if ( Q_stricmp( pSubKey->GetName(), "action" ) == 0 )
{
// Global actions, executed at the beginning of every state
ITilegenAction *pNewAction = NULL;
ITilegenExpression< bool > *pCondition = NULL;
if ( CreateActionAndCondition( pSubKey, &pNewAction, &pCondition ) )
{
if ( m_pGlobalActionState == NULL )
{
m_pGlobalActionState = new CTilegenState( this, NULL );
}
m_pGlobalActionState->AddAction( pNewAction, pCondition );
}
else
{
return false;
}
}
else if ( Q_stricmp( pSubKey->GetName(), "mission_settings" ) == 0 )
{
m_nRandomSeed = pSubKey->GetInt( "RandomSeed", 0 );
}
}
return true;
}
// @TODO: add rotation/mirroring support here by adding rotation argument
bool CLayoutSystem::TryPlaceRoom( const CRoomCandidate *pRoomCandidate )
{
int nX = pRoomCandidate->m_iXPos;
int nY = pRoomCandidate->m_iYPos;
const CRoomTemplate *pRoomTemplate = pRoomCandidate->m_pRoomTemplate;
CRoom *pSourceRoom = pRoomCandidate->m_pExit ? pRoomCandidate->m_pExit->pSourceRoom : NULL;
if ( m_pMapLayout->TemplateFits( pRoomTemplate, nX, nY, false ) )
{
// This has the side-effect of attaching itself to the layout; no need to keep track of it.
CRoom *pRoom = new CRoom( m_pMapLayout, pRoomTemplate, nX, nY );
// Remove exits covered up by the room
for ( int i = m_OpenExits.Count() - 1; i >= 0; -- i )
{
CExit *pExit = &m_OpenExits[i];
if ( pExit->X >= nX && pExit->Y >= nY &&
pExit->X < nX + pRoomTemplate->GetTilesX() &&
pExit->Y < nY + pRoomTemplate->GetTilesY() )
{
m_OpenExits.FastRemove( i );
}
}
if ( pSourceRoom != NULL )
{
++ pSourceRoom->m_iNumChildren;
}
AddOpenExitsFromRoom( pRoom );
OnRoomPlaced();
GetFreeVariables()->SetOrCreateFreeVariable( "LastPlacedRoomTemplate", ( void * )pRoomTemplate );
return true;
}
return false;
}
void CLayoutSystem::TransitionToState( const char *pStateName )
{
CTilegenState *pState = m_States.FindState( pStateName );
if ( pState == NULL )
{
Log_Warning( LOG_TilegenLayoutSystem, "Tilegen state %s not found.\n", pStateName );
OnError();
}
else
{
TransitionToState( pState );
}
}
void CLayoutSystem::TransitionToState( CTilegenState *pState )
{
CTilegenState *pOldState = m_pCurrentState;
m_pCurrentState = pState;
m_CurrentIterationState.m_bStopIteration = true;
OnStateChanged( pOldState );
Log_Msg( LOG_TilegenLayoutSystem, "Transitioning to state %s.\n", pState->GetStateName() );
StopProcessingActions();
}
void CLayoutSystem::OnError()
{
m_bLayoutError = true;
m_bGenerating = false;
Log_Warning( LOG_TilegenLayoutSystem, "An error occurred during level generation.\n" );
}
void CLayoutSystem::OnFinished()
{
m_bGenerating = false;
m_CurrentIterationState.m_bStopIteration = true;
Log_Msg( LOG_TilegenLayoutSystem, "CLayoutSystem: finished layout generation.\n" );
// Temp hack to setup fixed alien spawns
// TODO: Move this into a required rule
CASWMissionChooserNPCs::InitFixedSpawns( this, m_pMapLayout );
}
void CLayoutSystem::ExecuteAction( ITilegenAction *pAction, ITilegenExpression< bool > *pCondition )
{
Assert( pAction != NULL );
// Since actions can be nested, only expose the inner-most nested action.
ITilegenAction *pOldAction = ( ITilegenAction * )GetFreeVariables()->GetFreeVariableOrNULL( "Action" );
GetFreeVariables()->SetOrCreateFreeVariable( "Action", pAction );
// Get data associated with the current action and set it to free variables
int nIndex = m_ActionData.Find( pAction );
if ( nIndex == m_ActionData.InvalidIndex() )
{
ActionData_t actionData = { 0 };
actionData.m_nNumTimesExecuted = 0;
nIndex = m_ActionData.Insert( pAction, actionData );
Assert( nIndex != m_ActionData.InvalidIndex() );
}
GetFreeVariables()->SetOrCreateFreeVariable( "NumTimesExecuted", ( void * )m_ActionData[nIndex].m_nNumTimesExecuted );
// Execute the action if the condition is met
if ( pCondition == NULL || pCondition->Evaluate( GetFreeVariables() ) )
{
// Log_Msg( LOG_TilegenLayoutSystem, "Executing action %s.\n", pAction->GetTypeName() );
pAction->Execute( this );
++ m_ActionData[nIndex].m_nNumTimesExecuted;
OnActionExecuted( pAction );
}
// Restore free variable state
GetFreeVariables()->SetOrCreateFreeVariable( "Action", pOldAction );
nIndex = m_ActionData.Find( pOldAction );
Assert( nIndex != m_ActionData.InvalidIndex() );
GetFreeVariables()->SetOrCreateFreeVariable( "NumTimesExecuted", ( void * )m_ActionData[nIndex].m_nNumTimesExecuted );
}
void CLayoutSystem::OnActionExecuted( const ITilegenAction *pAction )
{
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnActionExecuted( this, pAction, GetFreeVariables() );
}
}
void CLayoutSystem::OnRoomPlaced()
{
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnRoomPlaced( this, GetFreeVariables() );
}
}
void CLayoutSystem::OnStateChanged( const CTilegenState *pOldState )
{
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnStateChanged( this, pOldState, GetFreeVariables() );
}
m_pCurrentState->OnStateChanged( this );
}
void CLayoutSystem::BeginGeneration( CMapLayout *pMapLayout )
{
if ( m_States.GetStateCount() == 0 )
{
Log_Warning( LOG_TilegenLayoutSystem, "No states in layout system!\n" );
OnError();
return;
}
// Reset random generator
int nSeed;
m_Random = CUniformRandomStream();
if ( m_nRandomSeed != 0 )
{
nSeed = m_nRandomSeed;
}
else
{
// @TODO: this is rather unscientific, but it gets us desired randomness for now.
nSeed = RandomInt( 1, 1000000000 );
}
m_Random.SetSeed( nSeed );
Log_Msg( LOG_TilegenLayoutSystem, "Beginning generation with random seed " );
Log_Msg( LOG_TilegenLayoutSystem, Color( 255, 255, 0, 255 ), "%d.\n", nSeed );
m_bLayoutError = false;
m_bGenerating = true;
m_nIterations = 0;
m_pMapLayout = pMapLayout;
m_pCurrentState = m_States.GetState( 0 );
m_OpenExits.RemoveAll();
m_ActionData.RemoveAll();
m_FreeVariables.RemoveAll();
// Initialize with sentinel value
ActionData_t nullActionData = { 0 };
m_ActionData.Insert( NULL, nullActionData );
for ( int i = 0; i < m_TilegenListeners.Count(); ++ i )
{
m_TilegenListeners[i]->OnBeginGeneration( this, GetFreeVariables() );
}
if ( m_pGlobalActionState != NULL )
{
m_pGlobalActionState->OnBeginGeneration( this );
}
m_States.OnBeginGeneration();
GetFreeVariables()->SetOrCreateFreeVariable( "LayoutSystem", this );
GetFreeVariables()->SetOrCreateFreeVariable( "MapLayout", GetMapLayout() );
}
void CLayoutSystem::ExecuteIteration()
{
Assert( m_pCurrentState != NULL && m_pMapLayout != NULL );
const int nMaxIterations = 200;
if ( m_nIterations > nMaxIterations )
{
Log_Warning( LOG_TilegenLayoutSystem, "Exceeded %d iterations, may be in an infinite loop.\n", nMaxIterations );
OnError();
return;
}
// Debugging assistant
int nBreakOnIteration = tilegen_break_on_iteration.GetInt();
if ( nBreakOnIteration >= 0 )
{
Log_Msg( LOG_TilegenLayoutSystem, "Iteration #%d\n", m_nIterations );
}
if ( m_nIterations == nBreakOnIteration )
{
DebuggerBreakIfDebugging();
}
// Initialize state scoped to the current iteration
m_CurrentIterationState.m_bStopIteration = false;
CUtlVector< CRoomCandidate > roomCandidateList;
m_CurrentIterationState.m_pRoomCandidateList = &roomCandidateList;
// Execute global actions first, if any are present.
if ( m_pGlobalActionState != NULL )
{
m_pGlobalActionState->ExecuteIteration( this );
}
// Now process actions in the current state
if ( !ShouldStopProcessingActions() )
{
// Executing an iteration may have a number of side-effects on the layout system,
// such as placing rooms, changing state, etc.
m_pCurrentState->ExecuteIteration( this );
}
++ m_nIterations;
m_CurrentIterationState.m_pRoomCandidateList = NULL;
}
// This function adds an open exit for every un-mated exit in the given room.
// The exits are added to the grid tile where a new room would connect
// (e.g., a north exit from a room tile at (x, y) is actually added to location (x, y+1)
void CLayoutSystem::AddOpenExitsFromRoom( CRoom *pRoom )
{
const CRoomTemplate *pTemplate = pRoom->m_pRoomTemplate;
// Go through each exit in the room.
for ( int i = 0; i < pTemplate->m_Exits.Count(); ++ i )
{
const CRoomTemplateExit *pExit = pTemplate->m_Exits[i];
int nExitX, nExitY;
if ( GetExitPosition( pTemplate, pRoom->m_iPosX, pRoom->m_iPosY, i, &nExitX, &nExitY ) )
{
// If no room exists where the exit interface goes, then consider the exit open.
// NOTE: this function assumes that the caller has already verified that the template fits, which means
// that if a room exists where this exit goes, it must be a matching exit (and thus not open).
if ( !m_pMapLayout->GetRoom( nExitX, nExitY ) )
{
AddOpenExit( pRoom, nExitX, nExitY, pExit->m_ExitDirection, pExit->m_szExitTag, pExit->m_bChokepointGrowSource );
}
}
}
}
void CLayoutSystem::AddOpenExit( CRoom *pSourceRoom, int nX, int nY, ExitDirection_t exitDirection, const char *pExitTag, bool bChokepointGrowSource )
{
// Check to make sure exit isn't already in the list.
for ( int i = 0; i < m_OpenExits.Count(); ++ i )
{
const CExit *pExit = &m_OpenExits[i];
if ( pExit->X == nX && pExit->Y == nY && pExit->ExitDirection == exitDirection )
{
// Exit already exists.
Assert( pExit->pSourceRoom == pSourceRoom && Q_stricmp( pExitTag, pExit->m_szExitTag ) == 0 );
return;
}
}
m_OpenExits.AddToTail( CExit( nX, nY, exitDirection, pExitTag, pSourceRoom, bChokepointGrowSource ) );
}
| 29.288889 | 195 | 0.701938 | newcommerdontblame |
663d734fe72edfd509c99a8869846b79f2103a59 | 737 | hxx | C++ | Packages/java/nio/file/Watchable.hxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | Packages/java/nio/file/Watchable.hxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | Packages/java/nio/file/Watchable.hxx | Brandon-T/Aries | 4e8c4f5454e8c7c5cd0611b1b38b5be8186f86ca | [
"MIT"
] | null | null | null | //
// Watchable.hxx
// Aries
//
// Created by Brandon on 2018-02-25.
// Copyright © 2018 Brandon. All rights reserved.
//
#ifndef Watchable_hxx
#define Watchable_hxx
#include "Array.hxx"
#include "Object.hxx"
namespace java::nio::file
{
using java::lang::Object;
using java::nio::file::WatchEvent;
using java::nio::file::WatchKey;
using java::nio::file::WatchService;
class Watchable : public Object
{
public:
Watchable(JVM* vm, jobject instance);
WatchKey register(WatchService arg0, Array<WatchEvent::Kind>& arg1, Array<WatchEvent::Modifier>& arg2);
WatchKey register(WatchService arg0, Array<WatchEvent::Kind>& arg1);
};
}
#endif /* Watchable_hxx */
| 21.057143 | 111 | 0.654003 | Brandon-T |
663ec8c79d479b0973d36908c7f196590b3f19d6 | 574 | cpp | C++ | src/Program.cpp | bgorzsony/Kalk | 6d86027cef7d61d589e806d3017c4c4bac0701cd | [
"MIT"
] | null | null | null | src/Program.cpp | bgorzsony/Kalk | 6d86027cef7d61d589e806d3017c4c4bac0701cd | [
"MIT"
] | null | null | null | src/Program.cpp | bgorzsony/Kalk | 6d86027cef7d61d589e806d3017c4c4bac0701cd | [
"MIT"
] | null | null | null | #include "Program.h"
#include "memtrace.h"
size_t Program::cmdPtr = 0;
void Program::addNewCommand(Command * cmd) {
this->commands.push_back(cmd);
}
void Program::setCmdPtr(int v) {
v = v - 2;
if (v < -1) {
throw std::out_of_range("Wrong tag at Goto");
}
cmdPtr = v;
}
void Program::Run() {
while (this->cmdPtr != this->commands.size()) {
Command* a = this->commands[this->cmdPtr];
a->Execute();
this->cmdPtr++;
}
}
Program::~Program() {
for (auto i : this->commands) {
i->clear();
delete i;
}
} | 13.666667 | 49 | 0.559233 | bgorzsony |
66475d3b68ca2c22cbb0824b4ffece85ce5542ff | 189 | hpp | C++ | GameBird.hpp | Xnork/Flappy-Bird---Cpp | f64eada7bd27a6302abf16162795c95afb9c4323 | [
"MIT"
] | 3 | 2020-11-10T16:54:58.000Z | 2021-06-05T13:14:15.000Z | GameBird.hpp | Xnork/Flappy-Bird---Cpp | f64eada7bd27a6302abf16162795c95afb9c4323 | [
"MIT"
] | null | null | null | GameBird.hpp | Xnork/Flappy-Bird---Cpp | f64eada7bd27a6302abf16162795c95afb9c4323 | [
"MIT"
] | null | null | null | #ifndef GAMEBIRD
#define GAMEBIRD
#include <iostream>
#include <SFML/Graphics.hpp>
class GameBird
{
public:
sf::Vector2f acc = sf::Vector2f(0.f,0.f);
float angle = 0.f;
};
#endif | 13.5 | 45 | 0.677249 | Xnork |
66478fc0a7ff8787021f5f64ea1bb45407bb6154 | 182 | hh | C++ | include/device/stm32l1xx/hal/spi_d.hh | no111u3/stm32cclib | 172087dab568f1452755df6e9f8624930fc10396 | [
"Apache-2.0"
] | 24 | 2018-04-26T20:06:31.000Z | 2022-03-19T18:45:57.000Z | include/device/stm32l1xx/hal/spi_d.hh | no111u3/stm32cclib | 172087dab568f1452755df6e9f8624930fc10396 | [
"Apache-2.0"
] | null | null | null | include/device/stm32l1xx/hal/spi_d.hh | no111u3/stm32cclib | 172087dab568f1452755df6e9f8624930fc10396 | [
"Apache-2.0"
] | 9 | 2018-01-22T11:40:53.000Z | 2022-03-23T20:03:19.000Z | #ifndef SPI_D_HH
#define SPI_D_HH
namespace hal {
using spi1 = spi_d<0x40013000>;
using spi2 = spi_d<0x40003800>;
using spi3 = spi_d<0x40003c00>;
}
#endif // SPI_D_HH
| 15.166667 | 35 | 0.686813 | no111u3 |
6648a203f9f473a246049bcdee9a861e93bf0f74 | 129 | cpp | C++ | platforms/posix/src/px4/generic/generic/tone_alarm/ToneAlarmInterface.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | platforms/posix/src/px4/generic/generic/tone_alarm/ToneAlarmInterface.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | platforms/posix/src/px4/generic/generic/tone_alarm/ToneAlarmInterface.cpp | Diksha-agg/Firmware_val | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:8b3f8015d6166788ea5c3ad03dfb8f09b860a264c927e806ea111d551fe3ed21
size 2121
| 32.25 | 75 | 0.883721 | Diksha-agg |
664990c2959f6a9675929a52bb9ad8993eee0361 | 586 | hpp | C++ | libs/core/include/fcppt/range/end.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/range/end.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/range/end.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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 FCPPT_RANGE_END_HPP_INCLUDED
#define FCPPT_RANGE_END_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <iterator>
#include <fcppt/config/external_end.hpp>
namespace fcppt::range
{
/**
\brief Calls end via ADL.
\ingroup fcpptrange
*/
template <typename Range>
auto end(Range &_range)
{
using std::end;
return end(_range);
}
}
#endif
| 18.903226 | 61 | 0.725256 | freundlich |
664c7e1f325db23e84fb2456f456563f2b62094e | 3,169 | cxx | C++ | SRep/MRML/vtkSRepExportPolyDataProperties.cxx | Connor-Bowley/SlicerSkeletalRepresentation | 025eaba50173781c48040e01ccc9a10d8fdb2d56 | [
"Apache-2.0"
] | 2 | 2018-06-29T18:11:22.000Z | 2018-08-14T15:45:05.000Z | SRep/MRML/vtkSRepExportPolyDataProperties.cxx | Connor-Bowley/SlicerSkeletalRepresentation | 025eaba50173781c48040e01ccc9a10d8fdb2d56 | [
"Apache-2.0"
] | 8 | 2018-07-04T00:22:53.000Z | 2018-09-07T03:31:14.000Z | SRep/MRML/vtkSRepExportPolyDataProperties.cxx | Connor-Bowley/SlicerSkeletalRepresentation | 025eaba50173781c48040e01ccc9a10d8fdb2d56 | [
"Apache-2.0"
] | 3 | 2018-06-29T18:11:37.000Z | 2018-09-05T22:57:27.000Z | #include "vtkSRepExportPolyDataProperties.h"
#include <vtkObjectFactory.h>
//----------------------------------------------------------------------
vtkStandardNewMacro(vtkSRepExportPolyDataProperties);
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::PrintSelf(ostream& os, vtkIndent indent) {
os << indent << "vtkSRepExportPolyDataProperties {" << std::endl
<< indent << " IncludeUpSpokes: " << IncludeUpSpokes << std::endl
<< indent << " IncludeDownSpokes: " << IncludeDownSpokes << std::endl
<< indent << " IncludeCrestSpokes: " << IncludeCrestSpokes << std::endl
<< indent << " IncludeCrestCurve: " << IncludeCrestCurve << std::endl
<< indent << " IncludeSkeletalSheet: " << IncludeSkeletalSheet << std::endl
<< indent << " IncludeSkeletonToCrestConnection: " << IncludeSkeletonToCrestConnection << std::endl
<< indent << " IncludeSpine: " << IncludeSpine << std::endl
<< indent << "}";
}
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::SetSRepDataArray(vtkDataArray* name) {
if (this->SRepDataArray != name) {
this->SRepDataArray = name;
this->Modified();
}
}
//----------------------------------------------------------------------
vtkDataArray* vtkSRepExportPolyDataProperties::GetSRepDataArray() const {
return this->SRepDataArray;
}
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::SetPointTypeArrayName(const std::string& name) {
if (this->PointTypeArrayName != name) {
this->PointTypeArrayName = name;
this->Modified();
}
}
//----------------------------------------------------------------------
std::string vtkSRepExportPolyDataProperties::GetPointTypeArrayName() const {
return this->PointTypeArrayName;
}
//----------------------------------------------------------------------
void vtkSRepExportPolyDataProperties::SetLineTypeArrayName(const std::string& name) {
if (this->LineTypeArrayName != name) {
this->LineTypeArrayName = name;
this->Modified();
}
}
//----------------------------------------------------------------------
std::string vtkSRepExportPolyDataProperties::GetLineTypeArrayName() const {
return this->LineTypeArrayName;
}
//----------------------------------------------------------------------
#define SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(name) \
void vtkSRepExportPolyDataProperties::Set##name(bool include) { \
if (this->name != include) { \
this->name = include; \
this->Modified(); \
} \
} \
bool vtkSRepExportPolyDataProperties::Get##name() const { \
return this->name; \
}
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeUpSpokes)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeDownSpokes)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeCrestSpokes)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeCrestCurve)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeSkeletalSheet)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeSkeletonToCrestConnection)
SREP_EXPORT_POLY_DATA_PROPERTIES_GET_SET(IncludeSpine)
| 40.628205 | 105 | 0.592616 | Connor-Bowley |
664e0dc1e65be67a2076ac4bc7b5ed508d3dcacb | 5,593 | cpp | C++ | compiler/llvm/c_src/raw_win32_handle_ostream.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 2,939 | 2019-08-29T16:52:20.000Z | 2022-03-31T05:42:30.000Z | compiler/llvm/c_src/raw_win32_handle_ostream.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 235 | 2019-08-29T23:44:13.000Z | 2022-03-17T11:43:25.000Z | compiler/llvm/c_src/raw_win32_handle_ostream.cpp | mlwilkerson/lumen | 048df6c0840c11496e2d15aa9af2e4a8d07a6e0f | [
"Apache-2.0"
] | 95 | 2019-08-29T19:11:28.000Z | 2022-01-03T05:14:16.000Z | #if defined(_WIN32)
#include "lumen/llvm/raw_win32_handle_ostream.h"
#include "Windows/WindowsSupport.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Process.h"
raw_win32_handle_ostream::raw_win32_handle_ostream(HANDLE h, bool isStdIo,
bool shouldClose,
bool unbuffered)
: raw_pwrite_stream(unbuffered), Handle(h), ShouldClose(shouldClose) {
IsConsole = ::GetFileType(Handle) == FILE_TYPE_CHAR;
if (IsConsole) {
ShouldClose = false;
return;
}
// Get the current position
DWORD loc =
::SetFilePointer(Handle, (LONG)0, nullptr,
FILE_CURRENT) if (loc == INVALID_SET_FILE_POINTER) {
SupportsSeeking = false;
pos = 0;
}
else {
pos = static_cast<uint64_t>(loc);
}
}
raw_win32_handle_ostream::~raw_win32_handle_ostream() {
if (Handle != (HANDLE) nullptr) {
flush();
if (ShouldClose) {
if (::CloseHandle(Handle)) {
EC = std::error_code(::GetLastError());
error_detected(EC);
}
}
}
if (has_error()) {
report_fatal_error("IO failure on output stream: " + error().message(),
/*gen_crash_diag=*/false);
}
}
static bool write_console_impl(HANDLE handle, StringRef data) {
SmallVector<wchar_t, 256> wideText;
if (auto ec = sys::windows::UTF8ToUTF16(data, wideText)) return false;
// On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data
// that can be written to the console at a time.
size_t maxWriteSize = wideText.size();
if (!RunningWindows8OrGreater()) maxWriteSize = 32767;
size_t wCharsWritten = 0;
do {
size_t wCharsToWrite =
std::min(maxWriteSize, wideText.size() - wCharsWritten);
DWORD actuallyWritten;
bool success =
::WriteConsoleW(handle, &wideText[wCharsWritten], wCharsToWrite,
&actuallyWritten, /*reserved=*/nullptr);
// The most likely reason to fail is that the handle does not point to a
// console, fall back to write
if (!success) return false;
wCharsWritten += actuallyWritten;
} while (wCharsWritten != wideText.size());
return true;
}
void raw_win32_handle_ostream::write_impl(const char *ptr, size_t size) {
assert(Handle != (HANDLE) nullptr && "File already closed.");
pos += size;
if (IsConsole)
if (write_console_impl(Handle, StringRef(ptr, size))) return;
DWORD bytesWritten = 0;
bool pending = true;
do {
if (!::WriteFile(Handle, (LPCVOID)ptr, (DWORD)size, &bytesWritten,
nullptr)) {
auto err = ::GetLastError();
// Async write
if (err == ERROR_IO_PENDING) {
continue;
} else {
EC = std::error_code(err);
error_detected(EC);
break;
}
} else {
pending = false;
}
} while (pending);
}
void raw_win32_handle_ostream::close() {
assert(ShouldClose);
ShouldClose = false;
flush();
if (::CloseHandle(Handle)) {
EC = std::error_code(::GetLastError());
error_detected(EC);
}
Handle = (HANDLE) nullptr;
}
uint64_t raw_win32_handle_ostream::seek(uint64_t off) {
assert(SupportsSeeking && "Stream does not support seeking!");
flush();
LARGE_INTEGER li;
li.QuadPart = off;
li.LowPart = ::SetFilePointer(Handle, li.LowPart, &li.HighPart, FILE_BEGIN);
if (li.LowPart == INVALID_SET_FILE_POINTER) {
auto err = ::GetLastError();
if (err != NO_ERROR) {
pos = (uint64_t)-1;
li.QuadPart = -1;
error_detected(err);
return pos;
}
}
pos = li.QuadPart;
return pos;
}
void raw_win32_handle_ostream::pwrite_impl(const char *ptr, size_t size,
uint64_t offset) {
uint64_t position = tell();
seek(offset);
write(ptr, size);
seek(position);
}
size_t raw_win32_handle_ostream::preferred_buffer_size() const {
if (IsConsole) return 0;
return raw_ostream::preferred_buffer_size();
}
raw_ostream &raw_win32_handle_ostream::changeColor(enum Colors colors,
bool bold, bool bg) {
if (!ColorEnabled) return *this;
if (sys::Process::ColorNeedsFlush()) flush();
const char *colorcode =
(colors == SAVEDCOLOR)
? sys::Process::OutputBold(bg)
: sys::Process::OutputColor(static_cast<char>(colors), bold, bg);
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
// don't account colors towards output characters
pos -= len;
}
return *this;
}
raw_ostream &raw_win32_handle_ostream::resetColor() {
if (!ColorEnabled) return *this;
if (sys::Process::ColorNeedsFlush()) flush();
const char *colorcode = sys::Process::ResetColor();
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
// don't account colors towards output characters
pos -= len;
}
return *this;
}
raw_ostream &raw_win32_handle_ostream::reverseColor() {
if (!ColorEnabled) return *this;
if (sys::Process::ColorNeedsFlush()) flush();
const char *colorcode = sys::Process::OutputReverse();
if (colorcode) {
size_t len = strlen(colorcode);
write(colorcode, len);
// don't account colors towards output characters
pos -= len;
}
return *this;
}
bool raw_win32_handle_ostream::is_displayed() const { return IsConsole; }
bool raw_win32_handle_ostream::has_colors() const { return ColorEnabled; }
void raw_win32_handle_ostream::anchor() {}
#endif
| 27.825871 | 78 | 0.640086 | mlwilkerson |
59438814c22f8f8d7d5566c8df865978069e5cab | 2,768 | hpp | C++ | src/net/MultiplayerPeerNative.hpp | Faless/GDNativeNet | b4760d01ceef09a2ab15d7cab46489323f9d7239 | [
"MIT"
] | 3 | 2019-03-07T21:31:32.000Z | 2020-03-10T21:14:50.000Z | src/net/MultiplayerPeerNative.hpp | Faless/GDNativeNet | b4760d01ceef09a2ab15d7cab46489323f9d7239 | [
"MIT"
] | null | null | null | src/net/MultiplayerPeerNative.hpp | Faless/GDNativeNet | b4760d01ceef09a2ab15d7cab46489323f9d7239 | [
"MIT"
] | 1 | 2020-03-10T21:14:56.000Z | 2020-03-10T21:14:56.000Z | #ifndef MULTIPLAYER_PEER_NATIVE
#define MULTIPLAYER_PEER_NATIVE
#include <Godot.hpp>
#include <Reference.hpp>
#include <MultiplayerPeerGDNative.hpp>
#include <net/godot_net.h>
namespace godot {
namespace net {
/* Forward declare interface functions (PacketPeer) */
godot_error get_packet_bind_mp(void *, const uint8_t **, int *);
godot_error put_packet_bind_mp(void *, const uint8_t *, int);
godot_int get_available_packet_count_bind_mp(const void *);
godot_int get_max_packet_size_bind_mp(const void *);
/* Forward declare interface functions (MultiplayerPeer) */
void set_transfer_mode_bind_mp(void *, godot_int);
godot_int get_transfer_mode_bind_mp(const void *);
void set_target_peer_bind_mp(void *, godot_int); // 0 = broadcast, 1 = server, <0 = all but abs(value)
godot_int get_packet_peer_bind_mp(const void *);
godot_bool is_server_bind_mp(const void *);
void poll_bind_mp(void *);
int32_t get_unique_id_bind_mp(const void *); // Must be > 0, 1 is for server
void set_refuse_new_connections_bind_mp(void *, godot_bool);
godot_bool is_refusing_new_connections_bind_mp(const void *);
godot_int get_connection_status_bind_mp(const void *);
class MultiplayerPeerNative : public MultiplayerPeerGDNative {
GODOT_CLASS(MultiplayerPeerNative, MultiplayerPeerGDNative);
protected:
godot_net_multiplayer_peer interface = {
{3, 1},
this,
&get_packet_bind_mp,
&put_packet_bind_mp,
&get_available_packet_count_bind_mp,
&get_max_packet_size_bind_mp,
&set_transfer_mode_bind_mp,
&get_transfer_mode_bind_mp,
&set_target_peer_bind_mp, // 0 = broadcast, 1 = server, <0 = all but abs(value)
&get_packet_peer_bind_mp,
&is_server_bind_mp,
&poll_bind_mp,
&get_unique_id_bind_mp, // Must be > 0, 1 is for server
&set_refuse_new_connections_bind_mp,
&is_refusing_new_connections_bind_mp,
&get_connection_status_bind_mp,
NULL
};
public:
static void _register_methods();
void _init();
~MultiplayerPeerNative();
/* PacketPeer */
virtual godot_error get_packet(const uint8_t **r_buffer, int *r_len) = 0;
virtual godot_error put_packet(const uint8_t *p_buffer, int p_len) = 0;
virtual godot_int get_available_packet_count() const = 0;
virtual godot_int get_max_packet_size() const = 0;
/* MultiplayerPeer */
virtual void set_transfer_mode(godot_int p_mode) = 0;
virtual godot_int get_transfer_mode() const = 0;
virtual void set_target_peer(godot_int p_peer_id) = 0;
virtual int get_packet_peer() const = 0;
virtual bool is_server() const = 0;
virtual void poll() = 0;
virtual int get_unique_id() const = 0;
virtual void set_refuse_new_connections(godot_bool p_enable) = 0;
virtual bool is_refusing_new_connections() const = 0;
virtual godot_int get_connection_status() const = 0;
};
}
}
#endif // MULTIPLAYER_PEER_NATIVE
| 33.349398 | 102 | 0.781792 | Faless |
5946fdc94e10dbfd0a5c58d24cd4f04eea0be14f | 3,190 | cpp | C++ | sci/libsci/filterproc.cpp | hongsenliu/cloudland | 81a9394f6e74658141ee66557731985f80a9f6ab | [
"Apache-2.0"
] | 69 | 2019-04-17T04:03:31.000Z | 2021-11-08T10:29:54.000Z | sci/libsci/filterproc.cpp | hongsenliu/cloudland | 81a9394f6e74658141ee66557731985f80a9f6ab | [
"Apache-2.0"
] | 113 | 2019-04-13T06:46:32.000Z | 2021-11-02T01:45:06.000Z | sci/libsci/filterproc.cpp | hongsenliu/cloudland | 81a9394f6e74658141ee66557731985f80a9f6ab | [
"Apache-2.0"
] | 46 | 2019-04-17T04:03:36.000Z | 2021-09-26T13:11:37.000Z | #ifndef _PRAGMA_COPYRIGHT_
#define _PRAGMA_COPYRIGHT_
#pragma comment(copyright, "%Z% %I% %W% %D% %T%\0")
#endif /* _PRAGMA_COPYRIGHT_ */
/****************************************************************************
* Copyright (c) 2008, 2010 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0s
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
Classes: FilterProcessor
Description: Properties of class 'FilterProcessor':
input: a. a message queue
output: a. a stream
b. a message queue
action: use user-defined filter handlers to process the messages
Author: Nicole Nie
History:
Date Who ID Description
-------- --- --- -----------
02/10/09 nieyy Initial code (D153875)
****************************************************************************/
#include "filterproc.hpp"
#include <assert.h>
#include "log.hpp"
#include "exception.hpp"
#include "socket.hpp"
#include "atomic.hpp"
#include "ctrlblock.hpp"
#include "message.hpp"
#include "stream.hpp"
#include "filter.hpp"
#include "filterlist.hpp"
#include "queue.hpp"
#include "eventntf.hpp"
#include "observer.hpp"
FilterProcessor::FilterProcessor(int hndl, FilterList *flist)
: Processor(hndl), filterList(flist), filtered(false), curFilterID(SCI_FILTER_NULL)
{
name = "UpstreamFilter";
inQueue = NULL;
outQueue = NULL;
observer = NULL;
}
FilterProcessor::~FilterProcessor()
{
delete inQueue;
}
Message * FilterProcessor::read()
{
assert(inQueue);
Message *msg = NULL;
filtered = false;
msg = inQueue->consume();
return msg;
}
void FilterProcessor::process(Message * msg)
{
int id = msg->getFilterID();
if (id != SCI_FILTER_NULL) {
Filter *filter = filterList->getFilter(id);
// call user's filter handler
if (filter != NULL) {
curFilterID = id;
filtered = true;
filter->input(msg->getGroup(), msg->getContentBuf(), msg->getContentLen());
}
}
}
void FilterProcessor::write(Message * msg)
{
assert(outQueue);
if (filtered) {
inQueue->remove();
return;
}
if (observer) {
observer->notify();
}
incRefCount(msg->getRefCount());
outQueue->produce(msg);
inQueue->remove();
}
void FilterProcessor::seize()
{
setState(false);
}
int FilterProcessor::recover()
{
// TODO
return -1;
}
void FilterProcessor::clean()
{
}
void FilterProcessor::deliever(Message * msg)
{
if (observer) {
observer->notify();
}
outQueue->produce(msg);
}
int FilterProcessor::getCurFilterID()
{
return curFilterID;
}
void FilterProcessor::setInQueue(MessageQueue * queue)
{
inQueue = queue;
}
void FilterProcessor::setOutQueue(MessageQueue * queue)
{
outQueue = queue;
}
void FilterProcessor::setObserver(Observer * ob)
{
observer = ob;
}
MessageQueue * FilterProcessor::getInQueue()
{
return inQueue;
}
MessageQueue * FilterProcessor::getOutQueue()
{
return outQueue;
}
| 19.813665 | 87 | 0.619749 | hongsenliu |
594b18824959e5ef5ba9bc20d987098e72a21400 | 1,768 | cpp | C++ | Projects/AsteroidGame/Engine.cpp | TywyllSoftware/TywRenderer | 2da2ea2076d4311488b8ddb39c2fec896c98378a | [
"Unlicense"
] | 11 | 2016-11-15T20:06:19.000Z | 2021-03-31T01:04:01.000Z | Projects/AsteroidGame/Engine.cpp | TywyllSoftware/TywRenderer | 2da2ea2076d4311488b8ddb39c2fec896c98378a | [
"Unlicense"
] | 1 | 2016-11-06T23:53:05.000Z | 2016-11-07T08:06:07.000Z | Projects/AsteroidGame/Engine.cpp | TywyllSoftware/TywRenderer | 2da2ea2076d4311488b8ddb39c2fec896c98378a | [
"Unlicense"
] | 2 | 2017-09-03T11:18:46.000Z | 2019-03-10T06:27:49.000Z | #include "Engine.h"
//Renderer Includes
#include "Renderer.h"
//Event Manager
#include "EventManager.h"
//SceneManager
#include "SceneManager.h"
//Other includes
#include <string>
Engine::Engine() :m_bInitialized(false)
{
m_strApplicationName = "Set name for application";
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Initialize(int WindowWidth, int WindowsHeight, LRESULT(CALLBACK MainWindowProc)(HWND, UINT, WPARAM, LPARAM), bool bFullscreen)
{
m_pRenderer = new Renderer;
//m_pAudioComponent = new AudioComponent;
m_pEventManager = new EventManager;
m_pSceneManager = new SceneManager;
//m_pSoundManager = new SoundManager;
m_iScreenWidth = WindowWidth;
m_iScreenHeight = WindowsHeight;
//Initialize QueryPerfomance counter
QueryPerformanceCounter(&m_StartTime);
QueryPerformanceFrequency(&m_Freq);
// Initialize Renderer
if (m_pRenderer->VInitRenderer(WindowWidth, WindowsHeight, false, HandleWindowMessages));
{
}
//Everything is initialized
m_bInitialized = true;
}
void Engine::Frame()
{
}
void Engine::Shutdown()
{
if (m_bInitialized)
{
//The order of deletion is important
delete m_pSceneManager;
m_pSceneManager = nullptr;
delete m_pAudioComponent;
m_pAudioComponent = nullptr;
delete m_pRenderer;
m_pRenderer = nullptr;
delete m_pEventManager;
m_pEventManager = nullptr;
delete m_pSoundManager;
m_pSoundManager = nullptr;
//UnregisterClass(m_strApplicationName.c_str(), m_wc.hInstance);
}
}
int Engine::GetTimeInMS()
{
LARGE_INTEGER ms;
QueryPerformanceCounter(&ms);
return ((ms.QuadPart - m_StartTime.QuadPart) * 1000) / m_Freq.QuadPart;
}
void Engine::GetMousePos(float &x, float &y)
{
//POINT p;
//GetCursorPos(&p);
//ScreenToClient(m_hWnd, &p);
//x = p.x;
//y = p.y;
} | 18.040816 | 139 | 0.738688 | TywyllSoftware |
59511cd65b3f9e5c8f5c180ae9ea2048f7cc073c | 33,675 | cxx | C++ | src/DataLoaderDTU.cxx | Eruvae/data_loaders | a3a74f313be6b6fcf0c142c104ee19fd88b37e38 | [
"MIT"
] | 7 | 2020-03-17T13:18:49.000Z | 2022-03-03T17:34:16.000Z | src/DataLoaderDTU.cxx | Eruvae/data_loaders | a3a74f313be6b6fcf0c142c104ee19fd88b37e38 | [
"MIT"
] | null | null | null | src/DataLoaderDTU.cxx | Eruvae/data_loaders | a3a74f313be6b6fcf0c142c104ee19fd88b37e38 | [
"MIT"
] | 1 | 2021-09-22T12:10:06.000Z | 2021-09-22T12:10:06.000Z | #include "data_loaders/DataLoaderDTU.h"
//loguru
#define LOGURU_REPLACE_GLOG 1
#include <loguru.hpp>
//configuru
#define CONFIGURU_WITH_EIGEN 1
#define CONFIGURU_IMPLICIT_CONVERSIONS 1
#include <configuru.hpp>
using namespace configuru;
//cnpy
#include "cnpy.h"
#include <opencv2/core/eigen.hpp>
//my stuff
#include "data_loaders/DataTransformer.h"
#include "easy_pbr/Frame.h"
#include "Profiler.h"
#include "string_utils.h"
#include "numerical_utils.h"
#include "opencv_utils.h"
#include "eigen_utils.h"
#include "RandGenerator.h"
#include "easy_pbr/LabelMngr.h"
#include "UtilsGL.h"
//json
// #include "json11/json11.hpp"
//boost
namespace fs = boost::filesystem;
// using namespace er::utils;
using namespace radu::utils;
using namespace easy_pbr;
DataLoaderDTU::DataLoaderDTU(const std::string config_file):
m_is_running(false),
m_autostart(false),
m_idx_scene_to_read(0),
m_nr_resets(0),
m_rand_gen(new RandGenerator),
m_nr_scenes_read_so_far(0)
{
init_params(config_file);
if(m_autostart){
start();
}
// init_data_reading();
// start_reading_next_scene();
}
DataLoaderDTU::~DataLoaderDTU(){
m_is_running=false;
m_loader_thread.join();
}
void DataLoaderDTU::init_params(const std::string config_file){
//read all the parameters
std::string config_file_abs;
if (fs::path(config_file).is_relative()){
config_file_abs=(fs::path(PROJECT_SOURCE_DIR) / config_file).string();
}else{
config_file_abs=config_file;
}
Config cfg = configuru::parse_file(config_file_abs, CFG);
Config loader_config=cfg["loader_dtu"];
m_autostart=loader_config["autostart"];
m_read_with_bg_thread = loader_config["read_with_bg_thread"];
m_shuffle=loader_config["shuffle"];
m_subsample_factor=loader_config["subsample_factor"];
m_do_overfit=loader_config["do_overfit"];
// m_restrict_to_object= (std::string)loader_config["restrict_to_object"]; //makes it load clouds only from a specific object
m_dataset_path = (std::string)loader_config["dataset_path"]; //get the path where all the off files are
m_restrict_to_scan_idx= loader_config["restrict_to_scan_idx"];
m_load_as_shell= loader_config["load_as_shell"];
m_mode= (std::string)loader_config["mode"];
m_scene_scale_multiplier= loader_config["scene_scale_multiplier"];
}
void DataLoaderDTU::start(){
CHECK(m_scene_folders.empty()) << " The loader has already been started before. Make sure that you have m_autostart to false";
init_data_reading();
read_poses_and_intrinsics();
start_reading_next_scene();
}
void DataLoaderDTU::init_data_reading(){
if(!fs::is_directory(m_dataset_path)) {
LOG(FATAL) << "No directory " << m_dataset_path;
}
//load the corresponding file and get from there the scene that we need to read
fs::path scene_file_path= m_dataset_path/("new_"+m_mode+".lst");
std::ifstream scene_file(scene_file_path.string() );
if(!scene_file.is_open()){
LOG(FATAL) << "Could not open labels file " << scene_file_path;
}
// int nr_scenes_read=0;
for( std::string line; getline( scene_file, line ); ){
if(line.empty()){
continue;
}
std::string scan=trim_copy(line); //this scan is a string with format "scanNUMBER". We want just the number
int scan_idx=std::stoi(radu::utils::erase_substring(scan, "scan"));
VLOG(1) << "from scan line " << scan << "scan idx is " << scan_idx;
//if we want to load only one of the scans except for all of them
//push only one of the scenes
if(m_restrict_to_scan_idx>=0){
if(m_restrict_to_scan_idx==scan_idx){
m_scene_folders.push_back(m_dataset_path/scan);;
}
}else{
//push all scenes
m_scene_folders.push_back(m_dataset_path/scan);
}
// nr_scenes_read++;
}
VLOG(1) << "loaded nr of scenes " << m_scene_folders.size() << " for mode " << m_mode;
// shuffle the data if neccsary
if(m_shuffle){
unsigned seed = m_nr_resets;
auto rng_0 = std::default_random_engine(seed);
std::shuffle(std::begin(m_scene_folders), std::end(m_scene_folders), rng_0);
}
CHECK(m_scene_folders.size()!=0 ) << "We have read zero scene folders";
}
void DataLoaderDTU::start_reading_next_scene(){
CHECK(m_is_running==false) << "The loader thread is already running. Wait until the scene is finished loading before loading a new one. You can check this with finished_reading_scene()";
std::string scene_path;
if ( m_idx_scene_to_read< m_scene_folders.size()){
scene_path=m_scene_folders[m_idx_scene_to_read].string();
}
// VLOG(1) << " mode "<< m_mode << "m dof overfit" << m_do_overfit << " scnee size "<< m_scene_folders.size() << " scnee path is " << scene_path;
if(!m_do_overfit){
m_idx_scene_to_read++;
}
//start the reading
if (m_loader_thread.joinable()){
m_loader_thread.join(); //join the thread from the previous iteration of running
}
if(!scene_path.empty()){
if(m_read_with_bg_thread){
m_is_running=true;
m_loader_thread=std::thread(&DataLoaderDTU::read_scene, this, scene_path); //starts to read in another thread
}else{
read_scene(scene_path);
}
}
}
void DataLoaderDTU::read_scene(const std::string scene_path){
// VLOG(1) <<" read from path " << scene_path;
TIME_SCOPE("read_scene");
m_frames_for_scene.clear();
std::vector<fs::path> paths;
for (fs::directory_iterator itr( fs::path(scene_path)/"image"); itr!=fs::directory_iterator(); ++itr){
fs::path img_path= itr->path();
paths.push_back(img_path);
}
//shuffle the images from this scene
unsigned seed1 = m_nr_scenes_read_so_far;
auto rng_1 = std::default_random_engine(seed1);
if(m_mode=="train"){
std::shuffle(std::begin(paths), std::end(paths), rng_1);
}
//load all the scene for the chosen object
// for (fs::directory_iterator itr(scene_path); itr!=fs::directory_iterator(); ++itr){
for (size_t i=0; i<paths.size(); i++){
// fs::path img_path= itr->path();
fs::path img_path= paths[i];
//get only files that end in png
// VLOG(1) << "img_path" <<img_path;
if(img_path.filename().string().find("png")!= std::string::npos){
// VLOG(1) << "png img path " << img_path;
int img_idx=std::stoi( img_path.stem().string() );
// VLOG(1) << "img idx is " << img_idx;
Frame frame;
frame.frame_idx=img_idx;
//sets the paths and all the things necessary for the loading of images
frame.rgb_path=img_path.string();
frame.subsample_factor=m_subsample_factor;
//load the images if necessary or delay it for whne it's needed
frame.load_images=[this]( easy_pbr::Frame& frame ) -> void{ this->load_images_in_frame(frame); };
if (m_load_as_shell){
//set the function to load the images whenever it's neede
frame.is_shell=true;
}else{
frame.is_shell=false;
frame.load_images(frame);
}
// //read pose and camera params needs to be read from the camera.npz
// std::string pose_and_intrinsics_path=(fs::path(scene_path)/"cameras.npz").string();
// //read npz
// cnpy::npz_t npz_file = cnpy::npz_load( pose_and_intrinsics_path );
// cnpy::NpyArray projection_mat_array = npz_file["world_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// cnpy::NpyArray scale_array = npz_file["scale_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// // VLOG(1) << " projection_mat_array size" << projection_mat_array.shape.size();
// // VLOG(1) << " scale_array size" << scale_array.shape.size();
// // VLOG(1) << " projection_mat_array shape0 " << projection_mat_array.shape[0];
// // VLOG(1) << " projection_mat_array shape1 " << projection_mat_array.shape[1];
// // VLOG(1) << " scale_array shape0 " << scale_array.shape[0];
// // VLOG(1) << " scale_array shape1 " << scale_array.shape[1];
// //get the P matrix which containst both K and the pose
// Eigen::Affine3d P;
// double* projection_mat_data = projection_mat_array.data<double>();
// P.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(projection_mat_data);
// // VLOG(1) << "P is " << P.matrix();
// Eigen::Matrix<double,3,4> P_block = P.matrix().block<3,4>(0,0);
// // VLOG(1) << P_block;
// //get scale
// Eigen::Affine3d S;
// double* scale_array_data = scale_array.data<double>();
// S.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(scale_array_data);
// // VLOG(1) << "S is " << S.matrix();
// //Get the P_block into K and R and T as done in this line: K, R, t = cv2.decomposeProjectionMatrix(P)[:3]
// cv::Mat P_mat;
// cv::eigen2cv(P_block, P_mat);
// cv::Mat K_mat, R_mat, t_mat;
// cv::decomposeProjectionMatrix(P_mat, K_mat, R_mat, t_mat);
// // VLOG(1) << "K_Mat has size " << K_mat.rows << " " << K_mat.cols;
// // VLOG(1) << "T_Mat has size " << R_mat.rows << " " << R_mat.cols;
// // VLOG(1) << "t_Mat has size " << t_mat.rows << " " << t_mat.cols;
// Eigen::Matrix3d K, R;
// Eigen::Vector4d t_full;
// cv::cv2eigen(K_mat, K);
// cv::cv2eigen(R_mat, R);
// cv::cv2eigen(t_mat, t_full);
// K = K / K(2, 2);
// // VLOG(1) << "K is " << K;
// // VLOG(1) << "R is " << R;
// // VLOG(1) << "t_full is " << t_full;
// Eigen::Vector3d t;
// t.x()= t_full.x()/t_full.w();
// t.y()= t_full.y()/t_full.w();
// t.z()= t_full.z()/t_full.w();
// // VLOG(1) << "t is "<<t;
// // //get the pose into a mat
// Eigen::Affine3f tf_cam_world;
// tf_cam_world.linear() = R.transpose().cast<float>();
// tf_cam_world.translation() = t.cast<float>();
// // VLOG(1) << "tf_cam_world " << tf_cam_world.matrix();
// //get S
// // Eigen::Matrix3d S_block=
// Eigen::Vector3d norm_trans=S.translation();
// // VLOG(1) << "norm trans is " << norm_trans;
// Eigen::Vector3d norm_scale;
// norm_scale << S(0,0), S(1,1), S(2,2);
// // VLOG(1) << "norm scale " << norm_scale;
// tf_cam_world.translation()-=norm_trans.cast<float>();
// tf_cam_world.translation()=tf_cam_world.translation().array()/norm_scale.cast<float>().array();
// // VLOG(1) << "pose after the weird scaling " << tf_cam_world.matrix();
// //transform so the up is in the positive y for a right handed system
// // self._coord_trans_world = torch.tensor(
// // [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],
// // dtype=torch.float32,
// // )
// // Eigen::Affine3f rot_world, rot_cam;
// // rot_world.matrix()<< 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1;
// // rot_cam.matrix()<< 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1;
// // tf_cam_world= rot_world*tf_cam_world*rot_cam;
// //atteptm2
// //rotate
// Eigen::Quaternionf q = Eigen::Quaternionf( Eigen::AngleAxis<float>( -60 * M_PI / 180.0 , Eigen::Vector3f::UnitX() ) );
// Eigen::Affine3f tf_rot;
// tf_rot.setIdentity();
// tf_rot.linear()=q.toRotationMatrix();
// // tf_world_cam=tf_rot*tf_world_cam;
// tf_cam_world=tf_rot*tf_cam_world;
// //flip
// Eigen::Affine3f tf_world_cam=tf_cam_world.inverse();
// Eigen::DiagonalMatrix<float, 4> diag;
// diag.diagonal() <<1, -1, 1, 1;
// tf_world_cam.matrix()=diag*tf_world_cam.matrix()*diag;
// //flip again the x
// diag.diagonal() <<-1, 1, 1, 1;
// tf_world_cam.matrix()=tf_world_cam.matrix()*diag;
// //flip locally
// tf_cam_world=tf_world_cam.inverse();
// frame.K=K.cast<float>();
// frame.tf_cam_world=tf_cam_world.inverse();
///////////////////////////////////////just get it from the hashmap
frame.K = m_scene2frame_idx2K[scene_path][img_idx];
frame.tf_cam_world = m_scene2frame_idx2tf_cam_world[scene_path][img_idx];
if(m_subsample_factor>1){
frame.K/=m_subsample_factor;
frame.K(2,2)=1.0;
}
// if (img_idx==0){
// exit(1);
// }
// CHECK(arr.shape.size()==2) << "arr should have 2 dimensions and it has " << arr.shape.size();
// CHECK(arr.shape[1]==4) << "arr second dimension should be 4 (x,y,z,label) but it is " << arr.shape[1];
// //read intensity
// fs::path absolute_path=fs::absolute(npz_filename).parent_path();
// fs::path file_name=npz_filename.stem();
// // fs::path npz_intensity_path=absolute_path/(file_name.string()+"_i"+".npz");
// // cnpy::npz_t npz_intensity_file = cnpy::npz_load(npz_intensity_path.string());
// // cnpy::NpyArray arr_intensity = npz_intensity_file["arr_0"]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// // CHECK(arr_intensity.shape.size()==1) << "arr should have 1 dimensions and it has " << arr.shape.size();
// //copy into EigenMatrix
// int nr_points=arr.shape[0];
// MeshSharedPtr cloud=Mesh::create();
// cloud->V.resize(nr_points,3);
// cloud->V.setZero();
// cloud->L_gt.resize(nr_points,1);
// cloud->L_gt.setZero();
// // cloud->I.resize(nr_points,1);
// // cloud->I.setZero();
// double* arr_data = arr.data<double>();
// // float* arr_intensity_data = arr_intensity.data<float>(); //the intensities are as floats while xyz is double. You can check by reading the npz in python
// for(int i=0; i<nr_points*4; i=i+4){
// int row_insert=i/4;
// double x=arr_data[i];
// double y=arr_data[i+1];
// double z=arr_data[i+2];
// int label=arr_data[i+3];
// // double intensity=arr_intensity_data[row_insert];
// cloud->V.row(row_insert) << x,y,z;
// cloud->L_gt.row(row_insert) << label;
// // cloud->I.row(row_insert) << intensity;
// // VLOG(1) << "xyz is " << x << " " << y << " " << z << " " << label;
// // exit(1);
// }
//rescale things if necessary
if(m_scene_scale_multiplier>0.0){
Eigen::Affine3f tf_world_cam_rescaled = frame.tf_cam_world.inverse();
tf_world_cam_rescaled.translation()*=m_scene_scale_multiplier;
frame.tf_cam_world=tf_world_cam_rescaled.inverse();
}
m_frames_for_scene.push_back(frame);
// if(m_nr_imgs_to_read>0 && m_frames_for_scene.size()>=m_nr_imgs_to_read){
// break; //we finished reading how many images we need so we stop the thread
// }
}
}
// VLOG(1) << "loaded a scene with nr of frames " << m_frames_for_scene.size();
CHECK(m_frames_for_scene.size()!=0) << "Clouldn't load any images for this scene in path " << scene_path;
m_nr_scenes_read_so_far++;
//shuffle the images from this scene
unsigned seed = m_nr_scenes_read_so_far;
auto rng_0 = std::default_random_engine(seed);
std::shuffle(std::begin(m_frames_for_scene), std::end(m_frames_for_scene), rng_0);
m_is_running=false;
}
void DataLoaderDTU::load_images_in_frame(easy_pbr::Frame& frame){
frame.is_shell=false;
// VLOG(1) << "load image from" << frame.rgb_path ;
cv::Mat rgb_8u=cv::imread(frame.rgb_path );
if(frame.subsample_factor>1){
cv::Mat resized;
cv::resize(rgb_8u, resized, cv::Size(), 1.0/frame.subsample_factor, 1.0/frame.subsample_factor, cv::INTER_AREA);
rgb_8u=resized;
}
frame.rgb_8u=rgb_8u;
// VLOG(1) << "img type is " << radu::utils::type2string( frame.rgb_8u.type() );
frame.rgb_8u.convertTo(frame.rgb_32f, CV_32FC3, 1.0/255.0);
frame.width=frame.rgb_32f.cols;
frame.height=frame.rgb_32f.rows;
// VLOG(1) << " frame width ad height " << frame.width << " " << frame.height;
}
void DataLoaderDTU::read_poses_and_intrinsics(){
// std::unordered_map<std::string, std::unordered_map<int, Eigen::Affine3f> > m_scene2frame_idx2tf_cam_world;
// std::unordered_map<std::string, std::unordered_map<int, Eigen::Matrix3f> > m_scene2frame_idx2K;
for(size_t scene_idx; scene_idx<m_scene_folders.size(); scene_idx++){
std::string scene_path=m_scene_folders[scene_idx].string();
VLOG(1) << "reading poses and intrinsics for scene " << fs::path(scene_path).stem();
std::vector<fs::path> paths;
for (fs::directory_iterator itr( fs::path(scene_path)/"image"); itr!=fs::directory_iterator(); ++itr){
fs::path img_path= itr->path();
paths.push_back(img_path);
}
//read pose and camera params needs to be read from the camera.npz
std::string pose_and_intrinsics_path=(fs::path(scene_path)/"cameras.npz").string();
cnpy::npz_t npz_file = cnpy::npz_load( pose_and_intrinsics_path );
//load all the scene for the chosen object
// for (fs::directory_iterator itr(scene_path); itr!=fs::directory_iterator(); ++itr){
for (size_t i=0; i<paths.size(); i++){
// fs::path img_path= itr->path();
fs::path img_path= paths[i];
//get only files that end in png
// VLOG(1) << "img_path" <<img_path;
if(img_path.filename().string().find("png")!= std::string::npos){
// VLOG(1) << "png img path " << img_path;
int img_idx=std::stoi( img_path.stem().string() );
// VLOG(1) << "img idx is " << img_idx;
//read npz
cnpy::NpyArray projection_mat_array = npz_file["world_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
cnpy::NpyArray scale_array = npz_file["scale_mat_"+std::to_string(img_idx) ]; //one can obtain the keys with https://stackoverflow.com/a/53901903
// VLOG(1) << " projection_mat_array size" << projection_mat_array.shape.size();
// VLOG(1) << " scale_array size" << scale_array.shape.size();
// VLOG(1) << " projection_mat_array shape0 " << projection_mat_array.shape[0];
// VLOG(1) << " projection_mat_array shape1 " << projection_mat_array.shape[1];
// VLOG(1) << " scale_array shape0 " << scale_array.shape[0];
// VLOG(1) << " scale_array shape1 " << scale_array.shape[1];
//get the P matrix which containst both K and the pose
Eigen::Affine3d P;
double* projection_mat_data = projection_mat_array.data<double>();
P.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(projection_mat_data);
// VLOG(1) << "P is " << P.matrix();
Eigen::Matrix<double,3,4> P_block = P.matrix().block<3,4>(0,0);
// VLOG(1) << P_block;
//get scale
Eigen::Affine3d S;
double* scale_array_data = scale_array.data<double>();
S.matrix()= Eigen::Map<Eigen::Matrix<double,4,4,Eigen::RowMajor> >(scale_array_data);
// VLOG(1) << "S is " << S.matrix();
//Get the P_block into K and R and T as done in this line: K, R, t = cv2.decomposeProjectionMatrix(P)[:3]
cv::Mat P_mat;
cv::eigen2cv(P_block, P_mat);
cv::Mat K_mat, R_mat, t_mat;
cv::decomposeProjectionMatrix(P_mat, K_mat, R_mat, t_mat);
// VLOG(1) << "K_Mat has size " << K_mat.rows << " " << K_mat.cols;
// VLOG(1) << "T_Mat has size " << R_mat.rows << " " << R_mat.cols;
// VLOG(1) << "t_Mat has size " << t_mat.rows << " " << t_mat.cols;
Eigen::Matrix3d K, R;
Eigen::Vector4d t_full;
cv::cv2eigen(K_mat, K);
cv::cv2eigen(R_mat, R);
cv::cv2eigen(t_mat, t_full);
K = K / K(2, 2);
// VLOG(1) << "K is " << K;
// VLOG(1) << "R is " << R;
// VLOG(1) << "t_full is " << t_full;
Eigen::Vector3d t;
t.x()= t_full.x()/t_full.w();
t.y()= t_full.y()/t_full.w();
t.z()= t_full.z()/t_full.w();
// VLOG(1) << "t is "<<t;
// //get the pose into a mat
Eigen::Affine3f tf_world_cam;
tf_world_cam.linear() = R.transpose().cast<float>();
tf_world_cam.translation() = t.cast<float>();
// VLOG(1) << "tf_world_cam " << tf_world_cam.matrix();
//get S
// Eigen::Matrix3d S_block=
Eigen::Vector3d norm_trans=S.translation();
// VLOG(1) << "norm trans is " << norm_trans;
Eigen::Vector3d norm_scale;
norm_scale << S(0,0), S(1,1), S(2,2);
// VLOG(1) << "norm scale " << norm_scale;
tf_world_cam.translation()-=norm_trans.cast<float>();
tf_world_cam.translation()=tf_world_cam.translation().array()/norm_scale.cast<float>().array();
// VLOG(1) << "pose after the weird scaling " << tf_world_cam.matrix();
//atteptm2
//rotate
Eigen::Quaternionf q = Eigen::Quaternionf( Eigen::AngleAxis<float>( -60 * M_PI / 180.0 , Eigen::Vector3f::UnitX() ) );
Eigen::Affine3f tf_rot;
tf_rot.setIdentity();
tf_rot.linear()=q.toRotationMatrix();
// tf_world_cam=tf_rot*tf_world_cam;
tf_world_cam=tf_rot*tf_world_cam;
//flip
Eigen::Affine3f tf_cam_world=tf_world_cam.inverse();
Eigen::DiagonalMatrix<float, 4> diag;
diag.diagonal() <<1, -1, 1, 1;
tf_cam_world.matrix()=diag*tf_cam_world.matrix()*diag;
//flip again the x
diag.diagonal() <<-1, 1, 1, 1;
tf_cam_world.matrix()=tf_cam_world.matrix()*diag;
//flip locally
// tf_world_cam=tf_cam_world.inverse();
//add it to the hashmaps
m_scene2frame_idx2tf_cam_world[scene_path][img_idx]=tf_cam_world;
m_scene2frame_idx2K[scene_path][img_idx]=K.cast<float>();
}
}
}
}
bool DataLoaderDTU::finished_reading_scene(){
return !m_is_running;
}
bool DataLoaderDTU::has_data(){
return finished_reading_scene();
}
Frame DataLoaderDTU::get_random_frame(){
int random_idx=m_rand_gen->rand_int(0, m_frames_for_scene.size()-1);
// int random_idx=0;
return m_frames_for_scene[random_idx];
}
Frame DataLoaderDTU::get_frame_at_idx( const int idx){
CHECK(idx<m_frames_for_scene.size()) << "idx is out of bounds. It is " << idx << " while m_frames has size " << m_frames_for_scene.size();
Frame frame= m_frames_for_scene[idx];
return frame;
}
bool DataLoaderDTU::is_finished(){
//check if this loader has loaded everything
if(m_idx_scene_to_read<m_scene_folders.size()){
return false; //there is still more files to read
}
return true; //there is nothing more to read and nothing more in the buffer so we are finished
}
void DataLoaderDTU::reset(){
m_nr_resets++;
//reshuffle for the next epoch
if(m_shuffle){
unsigned seed = m_nr_resets;
auto rng_0 = std::default_random_engine(seed);
std::shuffle(std::begin(m_scene_folders), std::end(m_scene_folders), rng_0);
}
m_idx_scene_to_read=0;
}
int DataLoaderDTU::nr_samples(){
return m_frames_for_scene.size();
}
int DataLoaderDTU::nr_scenes(){
return m_scene_folders.size();
}
void DataLoaderDTU::set_restrict_to_scan_idx(const int scan_idx){
m_restrict_to_scan_idx=scan_idx;
}
void DataLoaderDTU::set_mode_train(){
m_mode="train";
}
void DataLoaderDTU::set_mode_test(){
m_mode="test";
}
void DataLoaderDTU::set_mode_validation(){
m_mode="val";
}
std::unordered_map<std::string, std::string> DataLoaderDTU::create_mapping_classnr2classname(){
//from https://github.com/NVIDIAGameWorks/kaolin/blob/master/kaolin/datasets/shapenet.py
std::unordered_map<std::string, std::string> classnr2classname;
classnr2classname["04379243"]="table";
classnr2classname["03211117"]="monitor";
classnr2classname["04401088"]="phone";
classnr2classname["04530566"]="watercraft";
classnr2classname["03001627"]="chair";
classnr2classname["03636649"]="lamp";
classnr2classname["03691459"]="speaker";
classnr2classname["02828884"]="bench";
classnr2classname["02691156"]="plane";
classnr2classname["02808440"]="bathtub";
classnr2classname["02871439"]="bookcase";
classnr2classname["02773838"]="bag";
classnr2classname["02801938"]="basket";
classnr2classname["02880940"]="bowl";
classnr2classname["02924116"]="bus";
classnr2classname["02933112"]="cabinet";
classnr2classname["02942699"]="camera";
classnr2classname["02958343"]="car";
classnr2classname["03207941"]="dishwasher";
classnr2classname["03337140"]="file";
classnr2classname["03624134"]="knife";
classnr2classname["03642806"]="laptop";
classnr2classname["03710193"]="mailbox";
classnr2classname["03761084"]="microwave";
classnr2classname["03928116"]="piano";
classnr2classname["03938244"]="pillow";
classnr2classname["03948459"]="pistol";
classnr2classname["04004475"]="printer";
classnr2classname["04099429"]="rocket";
classnr2classname["04256520"]="sofa";
classnr2classname["04554684"]="washer";
classnr2classname["04090263"]="rifle";
classnr2classname["02946921"]="can";
return classnr2classname;
}
Eigen::Affine3f DataLoaderDTU::process_extrinsics_line(const std::string line){
// //remove any "[" or "]" in the line
// std::string line_processed=line;
// line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), '['), line_processed.end());
// line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), ']'), line_processed.end());
// // std::vector<std::string> tokens = radu::utils::split(line_processed, " ");
// std::vector<std::string> tokens = radu::utils::split(line_processed, ",");
// float azimuth = std::stof(tokens[0]);
// float elevation = std::stof(tokens[1]);
// float distance = std::stof(tokens[3]);
// VLOG(1) << "line is " << line;
// VLOG(1) << "azimuth elev and dist " << azimuth << " " << elevation << " " << distance;
// Eigen::Affine3f tf;
// //from compute_camera_params() in https://github.com/NVIDIAGameWorks/kaolin/blob/a76a004ada95280c6a0a821678cf1b886bcb3625/kaolin/mathutils/geometry/transformations.py
// float theta = radu::utils::degrees2radians(azimuth);
// float phi = radu::utils::degrees2radians(elevation);
// float camY = distance * std::sin(phi);
// float temp = distance * std::cos(phi);
// float camX = temp * std::cos(theta);
// float camZ = temp * std::sin(theta);
// // cam_pos = np.array([camX, camY, camZ])
// Eigen::Vector3f t;
// t << camX,camY,camZ;
// Eigen::Vector3f axisZ = t;
// Eigen::Vector3f axisY = Eigen::Vector3f::UnitY();
// Eigen::Vector3f axisX = axisY.cross(axisZ);
// axisY = axisZ.cross(axisX);
// // cam_mat = np.array([axisX, axisY, axisZ])
// Eigen::Matrix3f R;
// R.col(0)=axisX;
// R.col(1)=axisY;
// R.col(2)=-axisZ;
// // l2 = np.atleast_1d(np.linalg.norm(cam_mat, 2, 1))
// // l2[l2 == 0] = 1
// // cam_mat = cam_mat / np.expand_dims(l2, 1)
// Eigen::Vector3f norm_vec=R.colwise().norm();
// VLOG(1) << "norm is " << norm_vec;
// // R=R.colwise()/norm;
// for (int i=0; i<3; i++){
// float norm=norm_vec(i);
// for (int j=0; j<3; j++){
// // R(i,j) = R(i,j)/norm;
// R(j,i) = R(j,i)/norm;
// }
// }
// norm_vec=R.colwise().norm();
// VLOG(1) << "norm is " << norm_vec;
// tf.translation() = t;
// tf.linear() = R;
// //just to make sure it's orthogonal
// // Eigen::AngleAxisf aa(R); // RotationMatrix to AxisAngle
// // R = aa.toRotationMatrix(); // AxisAngle to RotationMatrix
// // tf.linear() = R;
// Eigen::Affine3f tf_ret=tf.inverse();
// // Eigen::Affine3f tf_ret=tf;
//attempt 2 by looking at https://github.com/Xharlie/ShapenetRender_more_variation/blob/master/cam_read.py
// F_MM = 35. # Focal length
// SENSOR_SIZE_MM = 32.
// PIXEL_ASPECT_RATIO = 1. # pixel_aspect_x / pixel_aspect_y
// RESOLUTION_PCT = 100.
// SKEW = 0.
// CAM_MAX_DIST = 1.75
// CAM_ROT = np.asarray([[1.910685676922942e-15, 4.371138828673793e-08, 1.0],
// [1.0, -4.371138828673793e-08, -0.0],
// [4.371138828673793e-08, 1.0, -4.371138828673793e-08]])
float cam_max_dist=1.75;
Eigen::Matrix3f cam_rot;
cam_rot <<1.910685676922942e-15, 4.371138828673793e-08, 1.0,
1.0, -4.371138828673793e-08, -0.0,
4.371138828673793e-08, 1.0, -4.371138828673793e-08;
std::string line_processed=line;
line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), '['), line_processed.end());
line_processed.erase(std::remove(line_processed.begin(), line_processed.end(), ']'), line_processed.end());
// std::vector<std::string> tokens = radu::utils::split(line_processed, " ");
std::vector<std::string> tokens = radu::utils::split(line_processed, ",");
float az = std::stof(tokens[0]);
float el = std::stof(tokens[1]);
float distance_ratio = std::stof(tokens[3]);
// float ox = std::stof(tokens[7]);
// float oy = std::stof(tokens[8]);
// float oz = std::stof(tokens[9]);
// # Calculate rotation and translation matrices.
// # Step 1: World coordinate to object coordinate.
float sa = std::sin(radu::utils::degrees2radians(-az));
float ca = std::cos(radu::utils::degrees2radians(-az));
float se = std::sin(radu::utils::degrees2radians(-el));
float ce = std::cos(radu::utils::degrees2radians(-el));
// R_world2obj = np.transpose(np.matrix(((ca * ce, -sa, ca * se),
// (sa * ce, ca, sa * se),
// (-se, 0, ce))))
Eigen::Matrix3f R_world2obj;
R_world2obj <<ca * ce, -sa, ca * se,
sa * ce, ca, sa * se,
-se, 0, ce;
Eigen::Matrix3f trans;
trans=R_world2obj.transpose();
R_world2obj=trans;
// # Step 2: Object coordinate to camera coordinate.
// R_obj2cam = np.transpose(np.matrix(CAM_ROT))
Eigen::Matrix3f R_obj2cam=cam_rot.transpose();
Eigen::Matrix3f R_world2cam = R_obj2cam * R_world2obj;
// cam_location = np.transpose(np.matrix((distance_ratio * CAM_MAX_DIST,
// 0,
// 0)))
Eigen::Vector3f cam_location;
cam_location << distance_ratio * cam_max_dist, 0, 0;
// # print('distance', distance_ratio * CAM_MAX_DIST)
Eigen::Vector3f T_world2cam = -1 * R_obj2cam * cam_location;
// // # Step 3: Fix blender camera's y and z axis direction.
// R_camfix = np.matrix(((1, 0, 0), (0, -1, 0), (0, 0, -1)))
Eigen::Matrix3f R_camfix;
R_camfix <<1, 0, 0,
0,1,0,
0,0,-1;
R_world2cam = R_camfix * R_world2cam;
T_world2cam = R_camfix * T_world2cam;
Eigen::Affine3f tf_ret;
tf_ret.linear()=R_world2cam;
tf_ret.translation()=T_world2cam;
//rotate 90 degrees
Eigen::Affine3f tf_worldGL_worldROS;
tf_worldGL_worldROS.setIdentity();
Eigen::Matrix3f worldGL_worldROS_rot;
worldGL_worldROS_rot = Eigen::AngleAxisf(-0.5*M_PI, Eigen::Vector3f::UnitX());
tf_worldGL_worldROS.matrix().block<3,3>(0,0)=worldGL_worldROS_rot;
Eigen::Affine3f tf_worldROS_worldGL=tf_worldGL_worldROS.inverse();
Eigen::Affine3f tf_ret_cor=tf_worldGL_worldROS*tf_ret.inverse();
tf_ret=tf_ret_cor.inverse();
return tf_ret;
}
| 35.559662 | 190 | 0.586607 | Eruvae |
595508697faace165fb9f47e9acd6df3f26d71c5 | 13,262 | cpp | C++ | src/types.cpp | AmkG/hl | 8695e75389254fe881a6067ecebc70219d7dc7ff | [
"MIT"
] | 2 | 2015-11-05T01:16:28.000Z | 2021-12-20T04:30:08.000Z | src/types.cpp | AmkG/hl | 8695e75389254fe881a6067ecebc70219d7dc7ff | [
"MIT"
] | null | null | null | src/types.cpp | AmkG/hl | 8695e75389254fe881a6067ecebc70219d7dc7ff | [
"MIT"
] | null | null | null | #include "all_defines.hpp"
#include "types.hpp"
#include "processes.hpp"
#include "executors.hpp"
#include "history.hpp"
#include <iostream>
/*-----------------------------------------------------------------------------
Cons
-----------------------------------------------------------------------------*/
Object::ref Cons::len() {
int l = 1;
Object::ref next = cdr();
Object::ref p2 = next;
while (maybe_type<Cons>(next)) {
next = ::cdr(next);
p2 = ::cdr(::cdr(p2));
if(next == p2 && next != Object::nil()) return Object::to_ref(0); // fail on infinite lists
l++;
}
// !! there could be an overflow, but we don't expect to have lists so long
return Object::to_ref(l);
}
/*-----------------------------------------------------------------------------
Closure
-----------------------------------------------------------------------------*/
Closure* Closure::NewClosure(Heap & h, size_t n) {
Closure *c = h.create_variadic<Closure>(n);
c->body = Object::nil();
c->nonreusable = true;
c->kontinuation.reset();
return c;
}
Closure* Closure::NewKClosure(Heap & h, size_t n) {
Closure *c = h.lifo_create_variadic<Closure>(n);
c->body = Object::nil();
c->nonreusable = false;
c->kontinuation.reset(new History::InnerRing);
return c;
}
/*-----------------------------------------------------------------------------
HlTable
-----------------------------------------------------------------------------*/
#include"hashes.hpp"
HashingClass::HashingClass(void)
: a(0x9e3779b9), b(0x9e3779b9), c(0) { }
void HashingClass::enhash(size_t x) {
c = c ^ (uint32_t)x;
mix(a, b, c);
}
/*is-compatible hashing*/
size_t hash_is(Object::ref o) {
/*if it's not a heap object, hash directly*/
if(!is_a<Generic*>(o)) {
/*32-bit, even on 64-bit systems; shouldn't be
a problem in practice, since we don't expect hash
tables to have more than 4,294,967,296 entries.
At least not *yet*.
*/
return (size_t) int_hash((uint32_t) o.dat);
} else {
HashingClass hc;
as_a<Generic*>(o)->enhash(&hc);
return (size_t) hc.c;
}
}
inline Object::ref* HlTable::linear_lookup(Object::ref k) const {
HlArray& A = *known_type<HlArray>(impl);
for(size_t i = 0; i < pairs; ++i) {
if(::is(k, A[i * 2])) {
return &A[i * 2 + 1];
}
}
return NULL;
}
inline Object::ref* HlTable::arrayed_lookup(Object::ref k) const {
if(!is_a<int>(k)) return NULL;
HlArray& A = *known_type<HlArray>(impl);
int x = as_a<int>(k);
if(x < 0 || x >= A.size()) return NULL;
return &A[x];
}
inline Object::ref* HlTable::hashed_lookup(Object::ref k) const {
HlArray& A = *known_type<HlArray>(impl);
size_t I = hash_is(k) % A.size();
size_t J = I;
Object::ref key;
loop:
if(!A[I]) return NULL;
if(::is(k, car(A[I]))) {
return &known_type<Cons>(A[I])->cdr();
}
++I; if(I >= A.size()) I = 0;
if(J == I) return NULL; //wrapped already
goto loop;
}
Object::ref* HlTable::location_lookup(Object::ref k) const {
if(tbtype == hl_table_empty) return NULL;
switch(tbtype) {
case hl_table_linear:
return linear_lookup(k);
break;
case hl_table_arrayed:
return arrayed_lookup(k);
break;
case hl_table_hashed:
return hashed_lookup(k);
break;
}
}
/*Inserts a key-value cons pair to the correct hashed
location in the specified array.
*/
static inline void add_kv_to_array(HlArray& A, Cons& kv, size_t sz) {
size_t I = hash_is(kv.car()) % sz;
find_loop:
if(!A[I]) {
A[I] = Object::to_ref(&kv);
return;
}
++I; if(I >= sz) I = 0;
goto find_loop;
}
void HlTable::insert(Heap& hp, ProcessStack& stack) {
HlTable& T = *known_type<HlTable>(stack.top(3));
if(T.tbtype == hl_table_empty) {
/*either we become an hl_table_arrayed,
or a hl_table_linear
*/
Object::ref k = stack.top(1);
/*maybe we become arrayed*/
if(is_a<int>(k)) {
int I = as_a<int>(k);
if(I >= 0 && I < ARRAYED_LEVEL) {
HlArray& A = *hp.create_variadic<HlArray>(ARRAYED_LEVEL);
A[I] = stack.top(2);
/*need to re-read, we might have gotten GC'ed*/
HlTable& T = *known_type<HlTable>(stack.top(3));
T.impl = Object::to_ref(&A);
T.tbtype = hl_table_arrayed;
goto clean_up;
}
}
/*nah, we have to become linear*/
HlArray& A = *hp.create_variadic<HlArray>(LINEAR_LEVEL * 2);
A[0] = stack.top(1); /*key*/
A[1] = stack.top(2); /*value*/
/*need to re-read, we might have gotten GC'ed*/
HlTable& T = *known_type<HlTable>(stack.top(3));
T.impl = Object::to_ref(&A);
T.tbtype = hl_table_linear;
T.pairs = 1;
goto clean_up;
} else {
/*if the key already exists, we just have
to replace its value
*/
Object::ref* op = T.location_lookup(stack.top(1));
if(op) {
*op = stack.top(2);
goto clean_up;
}
/*not a value replacement. Well, if the given value is
nil, we don't actually insert anything
Note that this checking needs to be done after we
determine we're not replacing a value
*/
if(!stack.top(2)) goto clean_up;
/*No, we have to insert it. First figure out what to do*/
switch(T.tbtype) {
case hl_table_arrayed:
/*Can we still insert into the array?*/
if(is_a<int>(stack.top(1))) {
int k = as_a<int>(stack.top(1));
if(k >= 0) {
HlArray& A = *known_type<HlArray>(
T.impl
);
size_t sz = A.size();
if(k < sz) {
A[k] = stack.top(2);
goto clean_up;
} else if(k < sz + ARRAYED_LEVEL) {
/*copy the implementation into
a new array.
*/
HlArray& NA =
*hp.create_variadic
<HlArray>(
sz + ARRAYED_LEVEL
);
/*re-read*/
HlTable& T =
*known_type<HlTable>(
stack.top(3)
);
HlArray& OA =
*known_type<HlArray>(
T.impl
);
for(size_t i = 0; i < sz; ++i)
{
NA[i] = OA[i];
}
NA[k] = stack.top(2);
T.impl = Object::to_ref(&NA);
goto clean_up;
}
}
}
/*failed to insert... transform into hashed*/
goto transform_arrayed_to_hashed;
break;
case hl_table_linear:
/*check if there's still space*/
if(T.pairs < LINEAR_LEVEL) {
int i = T.pairs;
HlArray& A = *known_type<HlArray>(T.impl);
A[i * 2] = stack.top(1); /*key*/
A[i * 2 + 1] = stack.top(2); /*value*/
T.pairs++;
goto clean_up;
}
/*failed to insert... transform to hashed*/
goto transform_linear_to_hashed;
case hl_table_hashed:
/*first, determine if we have to re-hash*/
HlArray& A = *known_type<HlArray>(T.impl);
if(T.pairs < A.size() / 2) {
/*no re-hash, just insert*/
/*first create Cons cell for k-v pair*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
/*re-read*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
add_kv_to_array(A, *cp, A.size());
++T.pairs;
goto clean_up;
}
goto rehash;
}
}
transform_arrayed_to_hashed: {
/*decide what the new size must be*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
size_t old_size = A.size();
size_t new_size = 4 * old_size;
/*create a cons pair for the current k-v*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
stack.top(1) = Object::to_ref(cp);
/*create a new array*/
HlArray* ap = hp.create_variadic<HlArray>(new_size);
stack.top(2) = Object::to_ref(ap);
/*enhash*/
T.pairs = 0;
for(size_t i = 0; i < old_size; ++i) {
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
if(A[i]) {
Cons& newkv = *hp.create<Cons>();
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
newkv.car() = Object::to_ref((int) i);
newkv.cdr() = A[i];
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
newkv,
new_size
);
++T.pairs;
}
}
/*insert new key*/
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
*known_type<Cons>(stack.top(1)),
new_size
);
{HlTable& T = *known_type<HlTable>(stack.top(3));
++T.pairs;
/*replace implementation*/
T.impl = stack.top(2);
T.tbtype = hl_table_hashed;
}
/*clean up stack*/
stack.top(3) = cdr(stack.top(1));
stack.pop(2);
return;
}
transform_linear_to_hashed: {
/*create a cons pair for the current k-v*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
stack.top(1) = Object::to_ref(cp);
/*create a new array*/
HlArray* ap = hp.create_variadic<HlArray>(
4 * LINEAR_LEVEL
);
stack.top(2) = Object::to_ref(ap);
/*enhash*/
known_type<HlTable>(stack.top(3))->pairs = 0;
for(size_t i = 0; i < LINEAR_LEVEL; ++i) {
/*have to read it in each time, because
of GC clobbering pointers
NOTE: can probably be rearranged somewhat
*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
/*if value is non-nil, create Cons pair and insert*/
if(A[i * 2 + 1]) {
Cons& newkv = *hp.create<Cons>();
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
newkv.car() = A[i * 2];
newkv.cdr() = A[i * 2 + 1];
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
newkv,
4 * LINEAR_LEVEL
);
++T.pairs;
}
}
/*insert new key*/
add_kv_to_array(*known_type<HlArray>(stack.top(2)),
*known_type<Cons>(stack.top(1)),
4 * LINEAR_LEVEL
);
HlTable& T = *known_type<HlTable>(stack.top(3));
++T.pairs;
/*replace implementation*/
T.impl = stack.top(2);
T.tbtype = hl_table_hashed;
/*clean up stack*/
stack.top(3) = cdr(stack.top(1));
stack.pop(2);
return;
}
rehash: {
/*create a cons pair for the current k-v*/
Cons* cp = hp.create<Cons>();
cp->car() = stack.top(1);
cp->cdr() = stack.top(2);
stack.top(1) = Object::to_ref(cp);
/*create the new array*/
HlArray* NAp;
{
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
NAp = hp.create_variadic<HlArray>(A.size() * 2);
}
HlArray& NA = *NAp;
/*re-read*/
HlTable& T = *known_type<HlTable>(stack.top(3));
HlArray& A = *known_type<HlArray>(T.impl);
Cons& new_kv = *known_type<Cons>(stack.top(1));
/*rehash*/
size_t sz = NA.size();
T.pairs = 0;
for(size_t i = 0; i < A.size(); ++i) {
if(A[i] && cdr(A[i])) {
add_kv_to_array(NA, *known_type<Cons>(A[i]), sz);
++T.pairs;
}
}
/*insert new key*/
add_kv_to_array(NA, new_kv, sz);
++T.pairs;
/*replace implementation*/
T.impl = Object::to_ref(&NA);
goto clean_up;
}
clean_up:
stack.top(3) = stack.top(2);
stack.pop(2);
return;
}
/*returns the keys of a table in a list*/
void HlTable::keys(Heap& hp, ProcessStack& stack) {
/*determine the table type*/
HlTableType type;
{HlTable& t = *expect_type<HlTable>(stack.top());
type = t.tbtype;
if(type == hl_table_empty) {
stack.top() = Object::nil();
return;
}
}
/*determine the size of the HlArray implementation*/
size_t sz;
{HlTable& t = *known_type<HlTable>(stack.top());
HlArray& a = *known_type<HlArray>(t.impl);
sz = a.size();
}
/*create a temporary Cons pair
car = table
cdr = list of keys being built
why? because we want to avoid having to
push a new item on the stack. in the
future, JITted code might prefer to have
a statically-located stack; obviously a
statically-located stack would also be
statically-sized.
*/
{Cons& c = *hp.create<Cons>();
c.car() = stack.top();
stack.top() = Object::to_ref<Generic*>(&c);
}
switch(type){
case hl_table_arrayed:
for(size_t i = 0; i < sz; ++i) {
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*value valid?*/
if(a[i]) {
Cons& c = *hp.create<Cons>();
c.car() = Object::to_ref<int>(i);
c.cdr() = cdr(stack.top());
scdr(stack.top(),
Object::to_ref<Generic*>(&c)
);
}
}
stack.top() = cdr(stack.top());
return;
case hl_table_linear:
{/*have to look up pairs*/
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
size_t pairs = t.pairs;
for(size_t i = 0; i < pairs; ++i) {
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*value valid?*/
if(a[i * 2 + 1]) {
/*add a list element to the
list of keys
*/
Cons& c = *hp.create<Cons>();
c.cdr() = cdr(stack.top());
scdr(stack.top(),
Object::to_ref<Generic*>(&c)
);
/*re-read*/
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(
t.impl
);
c.car() = a[i * 2];
}
}
}
stack.top() = cdr(stack.top());
return;
case hl_table_hashed:
for(size_t i = 0; i < sz; ++i) {
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*value valid?*/
if(a[i] && cdr(a[i])) {
/*add a list element to the list of keys*/
Cons& c = *hp.create<Cons>();
c.cdr() = cdr(stack.top());
scdr(stack.top(),
Object::to_ref<Generic*>(&c)
);
/*re-read*/
HlTable& t = *known_type<HlTable>(
car(stack.top())
);
HlArray& a = *known_type<HlArray>(t.impl);
/*add the key to list of keys*/
c.car() = car(a[i]);
}
}
stack.top() = cdr(stack.top());
return;
}
}
| 25.552987 | 95 | 0.583622 | AmkG |
5956bdc5c76cb1fc482645443a7209f133144427 | 693 | cpp | C++ | EngineAlpha/EngineAlpha/EngineAlpha/Core/Scene.cpp | JFrap/Engine-Alpha | 9aac8ed609881ee62f0ec22f72331e8d23b632e7 | [
"MIT"
] | 1 | 2018-10-06T15:33:06.000Z | 2018-10-06T15:33:06.000Z | EngineAlpha/EngineAlpha/EngineAlpha/Core/Scene.cpp | JFrap/Engine-Alpha | 9aac8ed609881ee62f0ec22f72331e8d23b632e7 | [
"MIT"
] | 7 | 2019-02-24T08:50:30.000Z | 2019-03-02T15:41:01.000Z | EngineAlpha/EngineAlpha/EngineAlpha/Core/Scene.cpp | JFrap/Engine-Alpha | 9aac8ed609881ee62f0ec22f72331e8d23b632e7 | [
"MIT"
] | 2 | 2019-02-22T21:10:00.000Z | 2019-02-24T08:01:33.000Z | #include "Scene.h"
namespace alpha {
Scene::Scene() {
}
void Scene::AddGameObject(GameObject &object) {
m_gameObjects.push_back(&object);
}
void Scene::UpdateGameObjects(float dt) {
for (size_t i = 0; i < m_gameObjects.size(); i++) {
if (m_gameObjects[i])
m_gameObjects[i]->Update(dt);
else
m_gameObjectRemovalQueue.push_back(m_gameObjects[i]);
}
while (m_gameObjectRemovalQueue.size() > 0) {
m_gameObjects.erase(std::find(m_gameObjects.begin(), m_gameObjects.end(), m_gameObjectRemovalQueue[0]));
m_gameObjectRemovalQueue.erase(m_gameObjectRemovalQueue.begin());
}
}
void Scene::_SetGame(Game *game) {
MainGame = game;
}
Scene::~Scene() {
}
} | 21 | 107 | 0.689755 | JFrap |
595f49945b7c47530cfa7d8dd3069ca79db217e6 | 988 | cpp | C++ | leetcodes/RotateImage.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | null | null | null | leetcodes/RotateImage.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | null | null | null | leetcodes/RotateImage.cpp | DaechurJeong/Private_Proj | 66eec4d22372166af7f7643a9b1307ca7e5ce21a | [
"MIT"
] | 2 | 2020-04-21T23:52:31.000Z | 2020-04-24T13:37:28.000Z | #include <iostream>
#include <vector>
void rotate(std::vector<std::vector<int>>& matrix) {
int size = (int)matrix.size();
for (int i = 0; i < size / 2; ++i)
{
for (int j = i; j < size - 1 - i; ++j)
{
int tmp = matrix[i][j];
matrix[i][j] = matrix[size - 1 - j][i];
matrix[size - 1 - j][i] = matrix[size - 1 - i][size - 1 - j];
matrix[size - 1 - i][size - 1 - j] = matrix[j][size - 1 - i];
matrix[j][size - 1 - i] = tmp;
}
}
}
int main(void)
{
std::vector<int> row1{1,2,3};
std::vector<int> row2{4,5,6};
std::vector<int> row3{7,8,9};
std::vector<std::vector<int>> input{row1, row2, row3};
std::cout << "Before rotate" << std::endl;
for (auto input_idx : input) {
for (auto row : input_idx) {
std::cout << row << " ";
}
std::cout << std::endl;
}
rotate(input);
std::cout << "After rotate" << std::endl;
for (auto input_idx : input) {
for (auto row : input_idx) {
std::cout << row << " ";
}
std::cout << std::endl;
}
return 0;
} | 20.583333 | 64 | 0.538462 | DaechurJeong |
596221e05ebadf598879c2268a826139fb3ed001 | 942 | hpp | C++ | engine/include/components/component.hpp | Eduardolimr/JogoIndividual | 8671dcf2622e31df91802b7390ed0e2be84ca574 | [
"MIT"
] | 2 | 2017-03-31T17:18:45.000Z | 2017-05-15T19:19:12.000Z | engine/include/components/component.hpp | Eduardolimr/JogoIndividual | 8671dcf2622e31df91802b7390ed0e2be84ca574 | [
"MIT"
] | 4 | 2018-06-24T00:39:05.000Z | 2018-07-03T21:55:02.000Z | engine/include/components/component.hpp | Eduardolimr/JogoIndividual | 8671dcf2622e31df91802b7390ed0e2be84ca574 | [
"MIT"
] | 6 | 2017-04-03T00:12:32.000Z | 2019-01-05T14:36:22.000Z | #ifndef __ENGINE_COMPONENTS_COMPONENT__
#define __ENGINE_COMPONENTS_COMPONENT__
#include "gameobject.hpp"
namespace engine {
class Component {
friend bool GameObject::add_component(Component & component);
public:
enum class State {
enabled,
disabled,
invalid
};
Component() : m_game_object(NULL), m_state(State::invalid) {}
virtual ~Component() {}
virtual bool init() { return true; }
virtual void setup() { return; }
virtual bool shutdown() { return true; }
virtual void update() { return; }
virtual void draw() { return; }
inline State state() { return m_state; }
inline const GameObject * game_object() { return m_game_object; }
inline void enable() { m_state = State::enabled; }
inline void disable() { m_state = State::disabled; }
protected:
GameObject * m_game_object;
State m_state;
};
}
#endif
| 22.428571 | 69 | 0.63482 | Eduardolimr |
5965a4d927773765a1a0b7bd5b6a726665ed4914 | 815 | cpp | C++ | Top 20 DP gfg/egg-dropping.cpp | Pradyuman7/AwesomeDataStructuresAndAlgorithms | 6d995c7a3ce2a227733b12b1749de647c5172e8e | [
"MIT"
] | 7 | 2018-11-15T07:51:21.000Z | 2020-03-20T04:31:33.000Z | Top 20 DP gfg/egg-dropping.cpp | Pradyuman7/AwesomeDataStructuresAndAlgorithms | 6d995c7a3ce2a227733b12b1749de647c5172e8e | [
"MIT"
] | null | null | null | Top 20 DP gfg/egg-dropping.cpp | Pradyuman7/AwesomeDataStructuresAndAlgorithms | 6d995c7a3ce2a227733b12b1749de647c5172e8e | [
"MIT"
] | 3 | 2018-11-15T06:39:53.000Z | 2021-07-20T02:09:18.000Z | #include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
int e[100][100];
int E(int o,int n,int k)
{
//usleep(500000);
// cout<<"Checking for : n = "<<n<<" and k = "<<k<<endl;
int min=INT_MAX;
if(e[n][k]!=-1)
return e[n][k];
if(n==0||k==0)
{
return 0;
}
// if(n==1)
// return 1;
if(k==1)
return n;
if(n>o)
return 0;
for(int i=n;i>=1;i--)
{
int a=E(o,n-i,k);
int b=E(o,i-1,k-1);
if(min>1+max(a,b))
{
min=1+max(a,b);
}
}
//cout<<"Returning min = "<<min<<" For n = "<<n<<" and k = "<<k<<" \n***************************\n";
e[n][k]=min;
return min;
}
int main()
{
int t;
cin>>t;
for(int i=0;i<100;i++)
for(int j=0;j<100;j++)
e[i][j]=-1;
while(t--)
{
int n,k;
cin>>k>>n;
cout<<E(n,n,k)<<endl;
}
return 0;
}
| 10.584416 | 102 | 0.442945 | Pradyuman7 |
596bfcad01e09452c583978a1d27a05ccbbf5426 | 6,098 | cpp | C++ | src/cge/cge/ws_server.cpp | UMU618/liuguang | 3a5e9db8dad759c30b307223c85e0a01f09a88bd | [
"Apache-2.0"
] | 2 | 2021-08-07T10:49:17.000Z | 2022-03-30T06:40:12.000Z | src/cge/cge/ws_server.cpp | sdgdsffdsfff/liuguang | 3ec7d3c9f9fd75fa614009a99c4ecdd08ff321bc | [
"Apache-2.0"
] | null | null | null | src/cge/cge/ws_server.cpp | sdgdsffdsfff/liuguang | 3ec7d3c9f9fd75fa614009a99c4ecdd08ff321bc | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020-present Ksyun
*
* 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 "pch.h"
#include "ws_server.h"
struct ProtocolHeader {
uint32_t type : 8;
uint32_t ts : 24;
uint32_t size;
float elapsed;
};
namespace {
inline void ListenerFail(beast::error_code ec, std::string_view what) {
std::cerr << "WsListener# " << what << ": " << ec.message() << '\n';
}
inline void ListenerFail(beast::error_code ec,
const tcp::endpoint& endpoint,
std::string_view what) {
std::cerr << "WsListener# " << endpoint << " " << what << ": " << ec.message()
<< '\n';
}
inline void SessionFail(beast::error_code ec,
const tcp::endpoint& endpoint,
std::string_view what) {
std::cerr << "WsSession# " << endpoint << " " << what << ": "
<< "(#" << ec.value() << ')' << ec.message() << '\n';
}
} // namespace
#pragma region "WsServer"
WsServer::WsServer(Engine& engine, const tcp::endpoint& endpoint) noexcept
: engine_(engine), acceptor_(engine.GetIoContext()) {
beast::error_code ec;
if (acceptor_.open(endpoint.protocol(), ec)) {
ListenerFail(ec, "open");
return;
}
if (acceptor_.set_option(net::socket_base::reuse_address(true), ec)) {
ListenerFail(ec, "set_option");
return;
}
if (acceptor_.bind(endpoint, ec)) {
ListenerFail(ec, "bind");
return;
}
if (acceptor_.listen(net::socket_base::max_listen_connections, ec)) {
ListenerFail(ec, "listen");
return;
}
}
bool WsServer::Join(std::shared_ptr<WsSession> session) noexcept {
bool inserted = false;
bool first = false;
{
std::lock_guard<std::mutex> lock(session_mutex_);
first = sessions_.size() == 0;
if (first) {
sessions_.insert(session);
inserted = true;
}
}
if (first) {
engine_.EncoderRun();
} else {
// Only one websocket client
session->Stop();
}
return inserted;
}
void WsServer::Leave(std::shared_ptr<WsSession> session) noexcept {
bool last = false;
{
std::lock_guard<std::mutex> lock(session_mutex_);
if (sessions_.erase(session) > 0) {
last = sessions_.size() == 0;
}
}
if (last) {
engine_.EncoderStop();
}
}
size_t WsServer::Send(std::string&& buffer) {
std::lock_guard<std::mutex> lock(session_mutex_);
for (const auto& session : sessions_) {
// Only one websocket client
session->Write(std::move(buffer));
return 1;
}
return 0;
}
void WsServer::OnAccept(beast::error_code ec, tcp::socket socket) {
if (ec) {
return ListenerFail(ec, socket.remote_endpoint(), "accept");
}
std::cout << "Accept " << socket.remote_endpoint() << '\n';
socket.set_option(tcp::no_delay(true));
std::make_shared<WsSession>(std::move(socket), shared_from_this())->Run();
Accept();
}
#pragma endregion
#pragma region "WsSession"
void WsSession::OnRun() {
ws_.set_option(
websocket::stream_base::timeout::suggested(beast::role_type::server));
ws_.set_option(
websocket::stream_base::decorator([](websocket::response_type& res) {
res.set(http::field::sec_websocket_protocol, "webgame");
}));
ws_.async_accept(
beast::bind_front_handler(&WsSession::OnAccept, shared_from_this()));
}
void WsSession::Stop() {
if (ws_.is_open()) {
std::cout << "Closing " << ws_.next_layer().socket().remote_endpoint()
<< '\n';
ws_.async_close(
websocket::close_reason(websocket::close_code::try_again_later),
beast::bind_front_handler(&WsSession::OnAccept, shared_from_this()));
}
}
void WsSession::Write(std::string&& buffer) {
std::lock_guard<std::mutex> lock(queue_mutex_);
write_queue_.emplace(buffer);
if (write_queue_.size() > 1) {
return;
}
ws_.async_write(
net::buffer(write_queue_.front()),
beast::bind_front_handler(&WsSession::OnWrite, shared_from_this()));
}
void WsSession::OnAccept(beast::error_code ec) {
if (ec == websocket::error::closed) {
std::cout << "Close " << ws_.next_layer().socket().remote_endpoint()
<< '\n';
return;
}
if (ec) {
return SessionFail(ec, ws_.next_layer().socket().remote_endpoint(),
"accept");
}
if (!server_->Join(shared_from_this())) {
return;
}
#if _DEBUG
std::cout << __func__ << "\n";
#endif
// Write("Hello world!");
Read();
}
void WsSession::OnStop(beast::error_code ec) {
server_->Leave(shared_from_this());
}
void WsSession::OnRead(beast::error_code ec, std::size_t bytes_transferred) {
if (ec) {
server_->Leave(shared_from_this());
if (ec == websocket::error::closed) {
return;
}
return SessionFail(ec, ws_.next_layer().socket().remote_endpoint(), "read");
}
#if _DEBUG
std::cout << __func__ << ": " << bytes_transferred << '\n';
#endif
Read();
}
void WsSession::OnWrite(beast::error_code ec, std::size_t bytes_transferred) {
if (ec) {
server_->Leave(shared_from_this());
return SessionFail(ec, ws_.next_layer().socket().remote_endpoint(),
"write");
}
#if _DEBUG
if (bytes_transferred != write_queue_.front().size()) {
std::cout << "bytes_transferred: " << bytes_transferred
<< ", size: " << write_queue_.front().size() << '\n';
}
#endif
std::lock_guard<std::mutex> lock(queue_mutex_);
write_queue_.pop();
if (!write_queue_.empty()) {
ws_.async_write(
net::buffer(write_queue_.front()),
beast::bind_front_handler(&WsSession::OnWrite, shared_from_this()));
}
}
#pragma endregion
| 26.171674 | 80 | 0.631519 | UMU618 |
596fd110d5a9c88cd5826fa13c024440585ffc5c | 4,050 | cc | C++ | vowpalwabbit/config/options.cc | hex-plex/AutoMLScreenExercise | 93a58e496f584bcc4cb35b8d6280d11605a695d6 | [
"BSD-3-Clause"
] | 1 | 2015-11-12T06:11:44.000Z | 2015-11-12T06:11:44.000Z | vowpalwabbit/config/options.cc | chrinide/vowpal_wabbit | 40e1fef676ca6a461d71cf0631ab5c63d1af5d8a | [
"BSD-3-Clause"
] | null | null | null | vowpalwabbit/config/options.cc | chrinide/vowpal_wabbit | 40e1fef676ca6a461d71cf0631ab5c63d1af5d8a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.
#include "config/options.h"
#include "config/option_group_definition.h"
#include "config/option.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <stdexcept>
#include <utility>
using namespace VW::config;
std::vector<std::shared_ptr<base_option>> options_i::get_all_options()
{
std::vector<std::shared_ptr<base_option>> output_values;
std::transform(m_options.begin(), m_options.end(), std::back_inserter(output_values),
[](std::pair<const std::string, std::shared_ptr<base_option>>& kv) { return kv.second; });
return output_values;
}
std::vector<std::shared_ptr<const base_option>> VW::config::options_i::get_all_options() const
{
std::vector<std::shared_ptr<const base_option>> output_values;
output_values.reserve(m_options.size());
for (const auto& kv : m_options) { output_values.push_back(kv.second); }
return output_values;
}
// This function is called by both the const and non-const version. The const version will implicitly upgrade the
// shared_ptr to const
std::shared_ptr<base_option> internal_get_option(
const std::string& key, const std::map<std::string, std::shared_ptr<VW::config::base_option>>& options)
{
auto it = options.find(key);
if (it != options.end()) { return it->second; }
throw std::out_of_range(key + " was not found.");
}
std::shared_ptr<base_option> VW::config::options_i::get_option(const std::string& key)
{
return internal_get_option(key, m_options);
}
std::shared_ptr<const base_option> VW::config::options_i::get_option(const std::string& key) const
{
// shared_ptr can implicitly upgrade to const from non-const
return internal_get_option(key, m_options);
}
void options_i::add_and_parse(const option_group_definition& group)
{
// Add known options before parsing so impl can make use of them.
m_option_group_definitions.push_back(group);
m_option_group_dic[m_current_reduction_tint].push_back(group);
for (const auto& option : group.m_options)
{
// The last definition is kept. There was a bug where using .insert at a later pointer changed the command line but
// the previously defined option's default value was serialized into the model. This resolves that state info.
m_options[option->m_name] = option;
if (!option->m_short_name.empty())
{
assert(option->m_short_name.size() == 1);
m_short_options[option->m_short_name[0]] = option;
}
}
internal_add_and_parse(group);
group.check_one_of();
}
bool options_i::add_parse_and_check_necessary(const option_group_definition& group)
{
// Add known options before parsing so impl can make use of them.
m_option_group_definitions.push_back(group);
m_option_group_dic[m_current_reduction_tint].push_back(group);
for (const auto& option : group.m_options)
{
// The last definition is kept. There was a bug where using .insert at a later pointer changed the command line but
// the previously defined option's default value was serialized into the model. This resolves that state info.
m_options[option->m_name] = option;
if (!option->m_short_name.empty())
{
assert(option->m_short_name.size() == 1);
m_short_options[option->m_short_name[0]] = option;
}
}
internal_add_and_parse(group);
auto necessary_enabled = group.check_necessary_enabled(*this);
if (necessary_enabled) { group.check_one_of(); }
return necessary_enabled;
}
void options_i::tint(const std::string& reduction_name) { m_current_reduction_tint = reduction_name; }
void options_i::reset_tint() { m_current_reduction_tint = m_default_tint; }
std::map<std::string, std::vector<option_group_definition>> options_i::get_collection_of_options() const
{
return m_option_group_dic;
}
const std::vector<option_group_definition>& options_i::get_all_option_group_definitions() const
{
return m_option_group_definitions;
}
| 34.913793 | 119 | 0.747407 | hex-plex |
5972d8993df633d4bca13453a18a81bfe662bc06 | 2,569 | hpp | C++ | C++/include/MNRLUpCounter.hpp | tjt7a/mnrl | 0e0bcefe67b51a6084c072501a2f4495c0cedb32 | [
"BSD-3-Clause"
] | 8 | 2017-06-06T19:55:20.000Z | 2021-11-14T16:55:43.000Z | C++/include/MNRLUpCounter.hpp | tjt7a/mnrl | 0e0bcefe67b51a6084c072501a2f4495c0cedb32 | [
"BSD-3-Clause"
] | null | null | null | C++/include/MNRLUpCounter.hpp | tjt7a/mnrl | 0e0bcefe67b51a6084c072501a2f4495c0cedb32 | [
"BSD-3-Clause"
] | 4 | 2017-08-03T18:06:18.000Z | 2021-06-23T18:22:23.000Z | // Kevin Angstadt
// angstadt {at} umich.edu
//
// MNRLUpCounter Object
#ifndef MNRLUPCOUNTER_HPP
#define MNRLUPCOUNTER_HPP
#include <string>
#include <utility>
#include <vector>
#include <map>
#include "MNRLDefs.hpp"
#include "MNRLNode.hpp"
#include "MNRLReportId.hpp"
namespace MNRL {
class MNRLUpCounter : public MNRLNode {
public:
MNRLUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
MNRLDefs::EnableType enable,
bool report,
int reportId,
std::map<std::string,std::string> attributes
) : MNRLNode (
id,
enable,
report,
gen_input(),
gen_output(),
attributes
), threshold(threshold), mode(mode), reportId(new MNRLReportIdInt(reportId)) {}
MNRLUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
MNRLDefs::EnableType enable,
bool report,
std::string reportId,
std::map<std::string,std::string> attributes
) : MNRLNode (
id,
enable,
report,
gen_input(),
gen_output(),
attributes
), threshold(threshold), mode(mode), reportId(new MNRLReportIdString(reportId)) {}
MNRLUpCounter(
int threshold,
MNRLDefs::CounterMode mode,
std::string id,
MNRLDefs::EnableType enable,
bool report,
std::map<std::string,std::string> attributes
) : MNRLNode (
id,
enable,
report,
gen_input(),
gen_output(),
attributes
), threshold(threshold), mode(mode), reportId(new MNRLReportId()) {}
virtual ~MNRLUpCounter() {
delete reportId;
reportId = nullptr;
}
virtual MNRLDefs::NodeType getNodeType() { return MNRLDefs::NodeType::UPCOUNTER; }
MNRLReportId *getReportId() { return reportId; }
void setReportId(std::string &id) {
delete reportId;
reportId = nullptr;
reportId = new MNRLReportIdString(id);
}
void setReportId(int id) {
delete reportId;
reportId = nullptr;
reportId = new MNRLReportIdInt(id);
}
MNRLDefs::CounterMode getMode() { return mode; }
void setMode(MNRLDefs::CounterMode m) { mode = m; }
int getThreshold() { return threshold; }
void setThreshold(int t) { threshold = t; }
protected:
int threshold;
MNRLDefs::CounterMode mode;
MNRLReportId *reportId;
private:
static port_def gen_input() {
port_def in;
in.emplace_back(
MNRLDefs::UP_COUNTER_COUNT,
1
);
in.emplace_back(
MNRLDefs::UP_COUNTER_RESET,
1
);
return in;
}
static port_def gen_output() {
port_def outs;
outs.emplace_back(
MNRLDefs::UP_COUNTER_OUTPUT,
1
);
return outs;
}
};
}
#endif
| 20.070313 | 84 | 0.668743 | tjt7a |
597309c27f9b3bfb03eb3e308f90e84dbc6841cb | 5,704 | cpp | C++ | oshgui/Drawing/OpenGL/OpenGLTextureTarget.cpp | sdkabuser/DEADCELL-CSGO | dfcd31394c5348529b3c098640466db136b89e0c | [
"MIT"
] | 506 | 2019-03-16T08:34:47.000Z | 2022-03-29T14:08:59.000Z | OSHGui/Drawing/OpenGL/OpenGLTextureTarget.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 124 | 2019-03-17T02:54:57.000Z | 2021-03-29T01:51:05.000Z | OSHGui/Drawing/OpenGL/OpenGLTextureTarget.cpp | EternityX/oshgui-deadcell | 7c565ba7e941ec00cf9f4a2d7639eb8a363a3e9e | [
"MIT"
] | 219 | 2019-03-16T21:39:01.000Z | 2022-03-30T08:59:24.000Z | #include <GL/glew.h>
#include "OpenGLTextureTarget.hpp"
#include "OpenGLRenderer.hpp"
#include "OpenGLTexture.hpp"
namespace OSHGui
{
namespace Drawing
{
const float OpenGLTextureTarget::DefaultSize = 128.0f;
//---------------------------------------------------------------------------
//Constructor
//---------------------------------------------------------------------------
OpenGLTextureTarget::OpenGLTextureTarget(OpenGLRenderer &owner)
: OpenGLRenderTarget<TextureTarget>(owner)
{
if (!GLEW_EXT_framebuffer_object)
{
throw;
}
CreateTexture();
InitialiseRenderTexture();
DeclareRenderSize(SizeF(DefaultSize, DefaultSize));
}
//---------------------------------------------------------------------------
OpenGLTextureTarget::~OpenGLTextureTarget()
{
glDeleteFramebuffersEXT(1, &frameBuffer);
}
//---------------------------------------------------------------------------
//Getter/Setter
//---------------------------------------------------------------------------
void OpenGLTextureTarget::DeclareRenderSize(const SizeF &size)
{
if (area.GetWidth() >= size.Width && area.GetHeight() >= size.Height)
{
return;
}
SetArea(RectangleF(area.GetLocation(), owner.GetAdjustedSize(size)));
ResizeRenderTexture();
Clear();
}
//---------------------------------------------------------------------------
bool OpenGLTextureTarget::IsImageryCache() const
{
return true;
}
//---------------------------------------------------------------------------
TexturePtr OpenGLTextureTarget::GetTexture() const
{
return oglTexture;
}
//---------------------------------------------------------------------------
bool OpenGLTextureTarget::IsRenderingInverted() const
{
return true;
}
//---------------------------------------------------------------------------
//Runtime-Functions
//---------------------------------------------------------------------------
void OpenGLTextureTarget::CreateTexture()
{
oglTexture = std::static_pointer_cast<OpenGLTexture>(owner.CreateTexture());
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::Activate()
{
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFrameBuffer));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
OpenGLRenderTarget::Activate();
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::Deactivate()
{
OpenGLRenderTarget::Deactivate();
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFrameBuffer);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::Clear()
{
if (area.GetWidth() < 1 || area.GetHeight() < 1)
{
return;
}
GLfloat oldColor[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, oldColor);
GLuint previousFBO = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFBO));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFBO);
glClearColor(oldColor[0], oldColor[1], oldColor[2], oldColor[3]);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::InitialiseRenderTexture()
{
GLuint oldTexture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&oldTexture));
glGenFramebuffersEXT(1, &frameBuffer);
GLuint previousFBO = 0;
glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, reinterpret_cast<GLint*>(&previousFBO));
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(DefaultSize), static_cast<GLsizei>(DefaultSize), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, previousFBO);
oglTexture->SetOpenGLTexture(texture);
oglTexture->SetOriginalDataSize(area.GetSize());
glBindTexture(GL_TEXTURE_2D, oldTexture);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::ResizeRenderTexture()
{
GLuint oldTexture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, reinterpret_cast<GLint*>(&oldTexture));
auto sz = area.GetSize();
if (sz.Width < 1.0f || sz.Height < 1.0f)
{
sz.Width = 1.0f;
sz.Height = 1.0f;
}
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, static_cast<GLsizei>(sz.Width), static_cast<GLsizei>(sz.Height), 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
Clear();
oglTexture->SetOpenGLTexture(texture);
oglTexture->SetOriginalDataSize(sz);
glBindTexture(GL_TEXTURE_2D, oldTexture);
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::PreReset()
{
glDeleteFramebuffersEXT(1, &frameBuffer);
frameBuffer = 0;
if (oglTexture)
{
texture = 0;
oglTexture = nullptr;
}
}
//---------------------------------------------------------------------------
void OpenGLTextureTarget::PostReset()
{
if (!oglTexture)
{
CreateTexture();
}
InitialiseRenderTexture();
ResizeRenderTexture();
}
//---------------------------------------------------------------------------
}
}
| 31.340659 | 147 | 0.545757 | sdkabuser |
597813da472a1863f0d0b6aec8459c7d41afd534 | 635 | hpp | C++ | SOLVER/src/preloop/nr_field/LocalizedNrFieldPointwise.hpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | SOLVER/src/preloop/nr_field/LocalizedNrFieldPointwise.hpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | SOLVER/src/preloop/nr_field/LocalizedNrFieldPointwise.hpp | chaindl/AxiSEM-3D | 0251f301c79c676fb37792209d6e24f107773b3d | [
"MIT"
] | null | null | null | //
// LocalizedNrField.hpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 3/14/20.
// Copyright © 2020 Kuangdai Leng. All rights reserved.
//
// base class of Nr(s,z)
#ifndef LocalizedNrFieldPointwise_hpp
#define LocalizedNrFieldPointwise_hpp
#include "LocalizedNrField.hpp"
class LocalizedNr;
class LocalizedNrFieldPointwise: public LocalizedNrField {
public:
LocalizedNrFieldPointwise(const std::string &fname, double distTol);
// get nr by (s, z)
LocalizedNr getWindowsAtPoint(const eigen::DCol2 &sz) const;
// verbose
std::string verbose() const;
};
#endif /* LocalizedNrFieldPointwise_hpp */
| 21.166667 | 72 | 0.724409 | chaindl |
597c6b9aef5891ec0d6aa64ea1d757e469d937b7 | 471 | cxx | C++ | src/scenes/scene.cxx | taworn/tankman | c2662fcbc966c5897733ade524c3a3ee8f8100bf | [
"MIT"
] | null | null | null | src/scenes/scene.cxx | taworn/tankman | c2662fcbc966c5897733ade524c3a3ee8f8100bf | [
"MIT"
] | null | null | null | src/scenes/scene.cxx | taworn/tankman | c2662fcbc966c5897733ade524c3a3ee8f8100bf | [
"MIT"
] | null | null | null | /**
* @file scene.cxx
* @desc Base game scene module.
*/
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include "../game.hxx"
#include "scene.hxx"
Scene::~Scene()
{
SDL_Log("Scene::~Scene()");
}
Scene::Scene()
{
SDL_Log("Scene::Scene()");
}
bool Scene::handleKey(SDL_KeyboardEvent key)
{
SDL_Log("Scene::handleKey(%d)", key.keysym.sym);
return false;
}
void Scene::render(int timeUsed)
{
}
| 14.71875 | 50 | 0.609342 | taworn |
59884bc98e70f934e01505b0567b684f1bd99435 | 1,027 | cpp | C++ | src/fifo.cpp | mdclyburn/rfm69hcw | e8f268a07666567037c9f30309c0a9a0d392b61e | [
"BSD-3-Clause"
] | null | null | null | src/fifo.cpp | mdclyburn/rfm69hcw | e8f268a07666567037c9f30309c0a9a0d392b61e | [
"BSD-3-Clause"
] | null | null | null | src/fifo.cpp | mdclyburn/rfm69hcw | e8f268a07666567037c9f30309c0a9a0d392b61e | [
"BSD-3-Clause"
] | null | null | null | #include "fifo.h"
namespace mardev::rfm69
{
void read_fifo(uint8_t* const buffer)
{
uint8_t i = 0;
while(!fifo_is_empty())
{
buffer[i++] = read(registers::FIFO);
}
return;
}
uint8_t read_fifo(uint8_t* const buffer,
const uint8_t max_bytes)
{
uint8_t i = 0;
while(!fifo_is_empty() && i < max_bytes)
{
buffer[i++] = read(registers::FIFO);
}
return i;
}
uint8_t write_fifo(const uint8_t* const buffer,
const uint8_t size)
{
// Limit for the library is at 66 bytes (at least for now).
if (size > 66)
return 1;
// FIFO full
if (read(registers::IRQFlags2) & 128)
return 2;
// TODO: turn this into a single burst-write.
uint8_t i = 0;
while(i < size && !(read(registers::IRQFlags2) & 128))
write(registers::FIFO, buffer[i++]);
return 0;
}
}
| 21.851064 | 67 | 0.493671 | mdclyburn |
598a89796869177762430ea15e462818ece7f367 | 2,315 | cc | C++ | src/ui/SDL2/movies/fm2/record.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 349 | 2017-11-15T22:51:00.000Z | 2022-03-21T13:43:57.000Z | src/ui/SDL2/movies/fm2/record.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 12 | 2018-08-28T21:38:29.000Z | 2021-12-11T16:24:36.000Z | src/ui/SDL2/movies/fm2/record.cc | MrKOSMOS/ANESE | 8ae814d615479b1496c98033a1f5bc4da5921c6f | [
"MIT"
] | 28 | 2018-06-10T07:31:13.000Z | 2022-03-21T10:54:26.000Z | #include "record.h"
#include "nes/joy/controllers/standard.h"
#include <cassert>
#include <cstdio>
#include <cstring>
FM2_Record::~FM2_Record() {
if (this->own_file) fclose(this->file);
}
FM2_Record::FM2_Record() {
memset(&this->joy, 0, sizeof this->joy);
this->own_file = false;
this->file = nullptr;
this->enabled = false;
this->frame = 0;
}
bool FM2_Record::init(const char* filename, bool binary) {
(void)binary; // TODO: support fm2 binary format
this->own_file = false;
this->file = fopen(filename, "w");
this->enabled = bool(this->file);
return this->enabled;
}
bool FM2_Record::init(FILE* file, bool binary) {
(void)binary; // TODO: support fm2 binary format
this->own_file = false;
this->file = file;
this->enabled = bool(this->file);
return this->enabled;
}
void FM2_Record::set_joy(uint port, FM2_Controller::Type type, Memory* joy) {
assert(port < 3);
this->joy[port].type = type;
this->joy[port]._mem = joy;
}
bool FM2_Record::is_enabled() const { return this->enabled; }
void FM2_Record::output_header() {
// Output fm2 header
for (uint port = 0; port < 3; port++) {
fprintf(this->file, "port%u %u\n",
port,
uint(this->joy[port].type)
);
}
}
void FM2_Record::step_frame() {
if (this->frame == 0) {
this->output_header();
}
// Output control signal
fprintf(this->file, "|%d", 0); // TODO: implement me
// Output Controller Status
for (uint port = 0; port < 3; port++) {
switch (this->joy[port].type) {
case FM2_Controller::SI_NONE: {
fprintf(this->file, "|");
} break;
case FM2_Controller::SI_GAMEPAD: {
using namespace JOY_Standard_Button;
char buf [9];
buf[8] = '\0';
#define OUTPUT(i, btn, c) \
buf[i] = this->joy[port].standard->get_button(btn) ? c : '.';
OUTPUT(0, Right, 'R');
OUTPUT(1, Left, 'L');
OUTPUT(2, Down, 'D');
OUTPUT(3, Up, 'U');
OUTPUT(4, Start, 'T');
OUTPUT(5, Select, 'S');
OUTPUT(6, B, 'B');
OUTPUT(7, A, 'A');
#undef OUTPUT
fprintf(this->file, "|%s", buf);
} break;
}
// case FM2_Controller::SI_ZAPPER: {
// using namespace JOY_Zapper_Button;
// } break;
}
fprintf(this->file, "\n");
this->frame++;
}
| 21.635514 | 77 | 0.587473 | MrKOSMOS |
5991715fffaf08c76cdd149c62840668c4833544 | 415 | cpp | C++ | oadrtest/oadrtest/tests/scheduler/JobSlow.cpp | beroset/OpenADR-VEN-Library | 16546464fe1dc714a126474aaadf75483ec9cbc6 | [
"Apache-2.0"
] | 12 | 2016-09-21T19:07:13.000Z | 2021-12-13T06:17:36.000Z | oadrtest/oadrtest/tests/scheduler/JobSlow.cpp | beroset/OpenADR-VEN-Library | 16546464fe1dc714a126474aaadf75483ec9cbc6 | [
"Apache-2.0"
] | 3 | 2020-11-09T08:25:40.000Z | 2021-04-12T10:49:39.000Z | oadrtest/oadrtest/tests/scheduler/JobSlow.cpp | beroset/OpenADR-VEN-Library | 16546464fe1dc714a126474aaadf75483ec9cbc6 | [
"Apache-2.0"
] | 12 | 2018-06-10T10:52:56.000Z | 2020-12-08T15:47:13.000Z | //
// Created by dupes on 12/9/15.
//
#include "JobSlow.h"
JobSlow::JobSlow(MockGlobalTime *globalTime) :
m_globalTime(globalTime)
{
}
/********************************************************************************/
JobSlow::~JobSlow()
{
}
/********************************************************************************/
void JobSlow::execute(time_t now)
{
m_globalTime->setNow(now + 200);
}
| 16.6 | 82 | 0.387952 | beroset |
599f874a59e2936cc96c2b27582498ddff6eaaa0 | 2,713 | hpp | C++ | src/sglib/mappers/PairedReadMapper.hpp | BenJWard/sg | 397924c8346981a6d4726c9cac7bc9c1b623c6fb | [
"MIT"
] | null | null | null | src/sglib/mappers/PairedReadMapper.hpp | BenJWard/sg | 397924c8346981a6d4726c9cac7bc9c1b623c6fb | [
"MIT"
] | null | null | null | src/sglib/mappers/PairedReadMapper.hpp | BenJWard/sg | 397924c8346981a6d4726c9cac7bc9c1b623c6fb | [
"MIT"
] | null | null | null | //
// Created by Bernardo Clavijo (EI) on 12/05/2018.
//
#ifndef BSG_PAIREDREADMAPPER_HPP
#define BSG_PAIREDREADMAPPER_HPP
#include <map>
#include <fstream>
#include "sglib/types/MappingTypes.hpp"
#include "sglib/factories/KMerIDXFactory.h"
#include "sglib/readers/SequenceGraphReader.h"
#include "sglib/SMR.h"
#include <sglib/datastores/PairedReadsDatastore.hpp>
class PairedReadConnectivityDetail; //Forward declaration
/**
* @brief A mapper for linked reads from a PairedReadsDatastore.
*
* Supports partial remapping of unmapped reads or of a selection list.
*/
class PairedReadMapper {
const SequenceGraph & sg;
public:
PairedReadMapper(SequenceGraph &_sg, PairedReadsDatastore &_datastore) : sg(_sg),datastore(_datastore){
reads_in_node.resize(sg.nodes.size());
};
void write(std::ofstream & output_file);
void read(std::ifstream & input_file);
void map_reads(std::unordered_set<uint64_t> const & reads_to_remap={});
void remap_all_reads();
//void map_read(uint64_t readID);
void remove_obsolete_mappings();
std::vector<uint64_t> size_distribution();
void populate_orientation();
/*void remap_reads();
uint64_t process_reads_from_file(uint8_t, uint16_t, std::unordered_map<uint64_t , graphPosition> &, std::string , uint64_t, bool tags=false, std::unordered_set<uint64_t> const & reads_to_remap={});
void save_to_disk(std::string filename);
void load_from_disk(std::string filename);*/
void print_stats();
PairedReadMapper operator=(const PairedReadMapper &other);
const PairedReadsDatastore & datastore;
std::vector<std::vector<ReadMapping>> reads_in_node;
std::vector<sgNodeID_t> read_to_node;//id of the main node if mapped, set to 0 to remap on next process
//TODO: reading and writing this would simplify things??
std::vector<bool> read_direction_in_node;//0-> fw, 1->rev;
std::vector<uint64_t> rfdist;
std::vector<uint64_t> frdist;
};
/**
* @brief Analysis of all reads connecting two particular nodes.
*/
class PairedReadConnectivityDetail {
public:
PairedReadConnectivityDetail(){};
PairedReadConnectivityDetail(const PairedReadMapper & prm, sgNodeID_t source, sgNodeID_t dest);
PairedReadConnectivityDetail& operator+=(const PairedReadConnectivityDetail& rhs){
this->orientation_paircount[0] += rhs.orientation_paircount[0];
this->orientation_paircount[1] += rhs.orientation_paircount[1];
this->orientation_paircount[2] += rhs.orientation_paircount[2];
this->orientation_paircount[3] += rhs.orientation_paircount[3];
return *this;
}
uint64_t orientation_paircount[4]={0,0,0,0};
};
#endif //BSG_PAIREDREADMAPPER_HPP
| 35.697368 | 201 | 0.736454 | BenJWard |
59a3ed513c38ffda9a70045f8f21852ffc1c77b1 | 2,494 | cpp | C++ | libraries/cor_cocos2dx_mruby_interface/sources/mruby_script_engine.cpp | rmake/cor-engine | d8920325db490d19dc8c116ab8e9620fe55e9975 | [
"MIT"
] | 4 | 2015-01-13T09:55:02.000Z | 2016-09-10T03:42:23.000Z | libraries/cor_cocos2dx_mruby_interface/sources/mruby_script_engine.cpp | rmake/cor-engine | d8920325db490d19dc8c116ab8e9620fe55e9975 | [
"MIT"
] | null | null | null | libraries/cor_cocos2dx_mruby_interface/sources/mruby_script_engine.cpp | rmake/cor-engine | d8920325db490d19dc8c116ab8e9620fe55e9975 | [
"MIT"
] | 2 | 2015-01-22T02:30:29.000Z | 2021-05-10T06:56:49.000Z | #include "mruby_script_engine.h"
namespace cor
{
namespace cocos2dx_mruby_interface
{
struct MrubyScriptEngineItnl
{
CocosRefTable object_table;
mruby_interface::MrubyState mrb;
};
MrubyScriptEngine::MrubyScriptEngine() : itnl(new MrubyScriptEngineItnl())
{
ref_instance_ptr() = this;
itnl->mrb.init();
}
MrubyScriptEngine::~MrubyScriptEngine()
{
}
MrubyScriptEnginePtr& MrubyScriptEngine::ref_instance_ptr()
{
static MrubyScriptEnginePtr instance;
return instance;
}
MrubyScriptEnginePtr MrubyScriptEngine::get_instance()
{
//static MrubyScriptEngine instance;
return ref_instance_ptr();
//return &instance;
}
mruby_interface::MrubyState& MrubyScriptEngine::ref_mrb()
{
return itnl->mrb;
}
CocosRefTable& MrubyScriptEngine::ref_object_table()
{
return itnl->object_table;
}
void MrubyScriptEngine::removeScriptObjectByObject(cocos2d::Ref* obj)
{
auto r = itnl->object_table[obj];
if(auto sp = r.lock())
{
sp->release_ref();
}
itnl->object_table.erase(obj);
}
void MrubyScriptEngine::removeScriptHandler(int handler)
{
}
int MrubyScriptEngine::reallocateScriptHandler(int handler)
{
return 0;
}
int MrubyScriptEngine::executeString(const char* codes)
{
itnl->mrb.load_string(codes);
MrubyRef e = itnl->mrb.get_last_exception();
if(e.test())
{
return 1;
}
return 0;
}
int MrubyScriptEngine::executeScriptFile(const char* filename)
{
return 1;
}
int MrubyScriptEngine::executeGlobalFunction(const char* functionName)
{
return 1;
}
int MrubyScriptEngine::sendEvent(cocos2d::ScriptEvent* evt)
{
return 1;
}
bool MrubyScriptEngine::handleAssert(const char *msg)
{
return false;
}
bool MrubyScriptEngine::parseConfig(ConfigType type, const std::string& str)
{
return false;
}
}
}
| 23.528302 | 84 | 0.526063 | rmake |
59a615de4ac81e6f0bd3c62c23e17755753754cd | 3,119 | cpp | C++ | src/system.cpp | yunik1004/vcpmp | 6a17e44d2d140334215faa692db6655adacce2c8 | [
"MIT"
] | null | null | null | src/system.cpp | yunik1004/vcpmp | 6a17e44d2d140334215faa692db6655adacce2c8 | [
"MIT"
] | null | null | null | src/system.cpp | yunik1004/vcpmp | 6a17e44d2d140334215faa692db6655adacce2c8 | [
"MIT"
] | null | null | null | #include "system.hpp"
#include <iostream>
#define ARCH_X86 "x86"
#define ARCH_X64 "x64"
#define ARCH_ARM "arm"
#define ARCH_ARM64 "arm64"
#define ARCH_CURRENT "current"
#define OS_WINDOWS "windows"
#define OS_LINUX "linux"
#define OS_DARWIN "osx"
#define OS_UWP "uwp"
#define LINK_DYNAMIC "dynamic"
#define LINK_STATIC "static"
std::string VCPMP::ToStr(VCPMP::ARCH arch) {
switch (arch) {
case VCPMP::ARCH::X86: return ARCH_X86;
case VCPMP::ARCH::X64: return ARCH_X64;
case VCPMP::ARCH::ARM: return ARCH_ARM;
case VCPMP::ARCH::ARM64: return ARCH_ARM64;
default: exit(EXIT_FAILURE);
}
}
std::string VCPMP::ToStr(VCPMP::OS os) {
switch (os) {
case VCPMP::OS::WINDOWS: return OS_WINDOWS;
case VCPMP::OS::LINUX: return OS_LINUX;
case VCPMP::OS::DARWIN: return OS_DARWIN;
case VCPMP::OS::UWP: return OS_UWP;
default: exit(EXIT_FAILURE);
}
}
std::string VCPMP::ToStr(VCPMP::LINK link) {
switch (link) {
case VCPMP::LINK::DYNAMIC: return LINK_DYNAMIC;
case VCPMP::LINK::STATIC: return LINK_STATIC;
default: exit(EXIT_FAILURE);
}
}
VCPMP::ARCH VCPMP::StrToARCH(std::string str) {
if (str.compare(ARCH_X86) == 0) {
return VCPMP::ARCH::X86;
} else if (str.compare(ARCH_X64) == 0) {
return VCPMP::ARCH::X64;
} else if (str.compare(ARCH_ARM) == 0) {
return VCPMP::ARCH::ARM;
} else if (str.compare(ARCH_ARM64) == 0) {
return VCPMP::ARCH::ARM64;
} else if (str.compare(ARCH_CURRENT) == 0) {
return VCPMP::getArch();
}
return VCPMP::ARCH::ERROR;
}
VCPMP::OS VCPMP::StrToOS(std::string str) {
if (str.compare(OS_WINDOWS) == 0) {
return VCPMP::OS::WINDOWS;
} else if (str.compare(OS_LINUX) == 0) {
return VCPMP::OS::LINUX;
} else if (str.compare(OS_DARWIN) == 0) {
return VCPMP::OS::DARWIN;
} else if (str.compare(OS_UWP) == 0) {
return VCPMP::OS::UWP;
}
return VCPMP::OS::ERROR;
}
VCPMP::LINK VCPMP::StrToLINK(std::string str) {
if (str.compare(LINK_DYNAMIC) == 0) {
return VCPMP::LINK::DYNAMIC;
} else if (str.compare(LINK_STATIC) == 0) {
return VCPMP::LINK::STATIC;
}
return VCPMP::LINK::ERROR;
}
VCPMP::ARCH VCPMP::getArch() {
switch (sizeof(void*)) {
case 4: return VCPMP::ARCH::X86;
case 8: return VCPMP::ARCH::X64;
}
return VCPMP::ARCH::ERROR;
}
VCPMP::OS VCPMP::getOS() {
#if defined(_WIN32) || defined(_WIN64)
return VCPMP::OS::WINDOWS;
#elif __APPLE__ || __MACH__
return VCPMP::OS::DARWIN;
#else
return VCPMP::OS::LINUX;
#endif
}
void VCPMP::install_vcpkg_library(const char* vcpkg_root, std::string name, VCPMP::ARCH arch, VCPMP::OS os, VCPMP::LINK link) {
std::string command_str = vcpkg_root;
command_str += "/vcpkg install " + name + ":" + VCPMP::ToStr(arch) + "-" + VCPMP::ToStr(os);
if (link == VCPMP::LINK::STATIC) {
command_str += + "-" + VCPMP::ToStr(link);
}
const char* command = command_str.c_str();
system(command);
}
| 27.121739 | 127 | 0.612376 | yunik1004 |
59b031457ba8dcbacb65a4611d193ff41677c658 | 168 | hpp | C++ | libvmod/include/vmod/sf/fs/fs_FileSystem.hpp | MarioPossamato/vax | c40f0f9740643003e02fa9da6e0e986695b87ff2 | [
"MIT"
] | 6 | 2022-03-23T23:26:04.000Z | 2022-03-27T06:33:22.000Z | libvmod/include/vmod/sf/fs/fs_FileSystem.hpp | MarioPossamato/vax | c40f0f9740643003e02fa9da6e0e986695b87ff2 | [
"MIT"
] | null | null | null | libvmod/include/vmod/sf/fs/fs_FileSystem.hpp | MarioPossamato/vax | c40f0f9740643003e02fa9da6e0e986695b87ff2 | [
"MIT"
] | 6 | 2022-03-25T22:56:04.000Z | 2022-03-26T09:32:08.000Z |
#pragma once
#include <switch.h>
namespace vmod::sf::fs {
Result Initialize();
void Finalize();
Result OpenSdCardFileSystem(FsFileSystem &out_sd_fs);
} | 14 | 57 | 0.690476 | MarioPossamato |
59bb2db2c476de6bde860e3910bc3bea5bed64fa | 3,818 | cpp | C++ | ChipsEninge/02_Script/ChipsSystem/BasicFrame/GameObject.cpp | jerrypoiu/DX11_ChipsEngine2021 | a558fb0013259a380d68b66142fc48b575208980 | [
"MIT"
] | 1 | 2021-01-25T11:38:21.000Z | 2021-01-25T11:38:21.000Z | ChipsEninge/02_Script/ChipsSystem/BasicFrame/GameObject.cpp | jerrypoiu/ChipsEngine | a558fb0013259a380d68b66142fc48b575208980 | [
"MIT"
] | null | null | null | ChipsEninge/02_Script/ChipsSystem/BasicFrame/GameObject.cpp | jerrypoiu/ChipsEngine | a558fb0013259a380d68b66142fc48b575208980 | [
"MIT"
] | null | null | null | #include "ChipsSystem/BasicFrame/Scene.h"
#include "ChipsSystem/BasicFrame/AComponent.h"
#include "ChipsSystem/BasicFrame/GameObject.h"
#include "ChipsSystem/BasicFrame/Application.h"
#include "ChipsSystem/Components/BaiscComponents/Transform.h"
#include "ChipsSystem/Components/BaiscComponents/Rigidbody.h"
#include "ChipsSystem/Etc/Debug.h"
#include "ChipsSystem/Etc/LayerMask.h"
namespace ChipsEngine
{
GameObject::GameObject(string _name, string _layer, string _tag ) : m_name(_name), m_tag(_tag), m_isActive(true),
m_transfrom(nullptr), m_rigidbody(nullptr),
m_transformType(typeid(Transform)), m_rigidbodyType(typeid(Rigidbody))
{
Debug::Log("Object Create " + m_name, LOG_TYPE::CREATE_LOG);
m_layer = LayerMask::NameToLayer(_layer);
m_components.resize(0);
AddComponent<Transform>();
m_transfrom = GetComponent<Transform>();
AddComponent<Rigidbody>();
m_rigidbody = GetComponent<Rigidbody>();
}
VOID GameObject::RemoveComponent(AComponent* _component)
{
if (strcmp(_component->GetType().c_str(), "Transform") == 0
|| strcmp(_component->GetType().c_str(), "Rigidbody") == 0)
{
Debug::Log("WARNING : You can't remove \"" + _component->GetType() + "\" Compoenet.", LOG_TYPE::WARING_LOG);
return;
}
for (auto it = m_components.begin(); it != m_components.end(); it++)
{
if (it->get() == _component)
{
m_components.remove(*it);
return;
}
}
}
VOID GameObject::RemoveComponent(string _componentType)
{
if (strcmp(_componentType.c_str(), "Transform") == 0
|| strcmp(_componentType.c_str(), "Rigidbody") == 0)
{
Debug::Log("WARNING : You can't remove \"" + _componentType + "\" Compoenet.", LOG_TYPE::WARING_LOG);
return;
}
for (auto it = m_components.begin(); it != m_components.end(); it++)
{
AComponent* component = static_cast<AComponent*>(it->get());
if (component->GetType() == _componentType)
{
m_components.remove(*it);
return;
}
}
}
VOID GameObject::_Awake_()
{
}
VOID GameObject::_Update_()
{
if (m_isActive == false)
return;
for (auto const& _component : m_components)
{
_component->_Update_();
}
}
VOID GameObject::_FixedUpdate_()
{
if (m_isActive == false)
return;
for (auto const& _component : m_components)
{
_component->_FixedUpdate_();
for (auto const& _coll : m_triggerColliders)
{
_component->OnTriggerStay(_coll);
}
}
}
VOID GameObject::_Render_()
{
if (m_isActive == false)
return;
for (auto const& _component : m_components)
{
_component->_Render_();
}
}
VOID GameObject::_Release_()
{
Debug::Log("Object Delete " + m_name, LOG_TYPE::DELETE_LOG);
m_isActive = false;
m_components.clear();
this->~GameObject();
}
VOID GameObject::OnCollisionEnter(GameObject* _coll)
{
if (m_isActive == false)
return;
for (auto const& _component : m_components)
{
_component->OnCollisionEnter(_coll);
}
}
VOID GameObject::OnCollisionStay(GameObject* _coll)
{
if (m_isActive == false)
return;
for (auto const& _component : m_components)
{
_component->OnCollisionStay(_coll);
}
}
VOID GameObject::OnCollisionExit(GameObject* _coll)
{
if (m_isActive == false)
return;
for (auto const& _component : m_components)
{
_component->OnCollisionExit(_coll);
}
}
VOID GameObject::OnTriggerEnter(GameObject* _coll)
{
if (m_isActive == false)
return;
m_triggerColliders.emplace_back(_coll);
for (auto const& _component : m_components)
{
_component->OnTriggerEnter(_coll);
}
}
VOID GameObject::OnTriggerExit(GameObject* _coll)
{
if (m_isActive == false)
return;
m_triggerColliders.remove(_coll);
for (auto const& _component : m_components)
{
_component->OnTriggerExit(_coll);
}
}
} | 21.942529 | 114 | 0.673389 | jerrypoiu |
59bcd6ce5d8597e533a44861452fb7fe45b18cbc | 381 | cpp | C++ | solutions/683.k-empty-slots.285439527.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/683.k-empty-slots.285439527.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/683.k-empty-slots.285439527.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
int kEmptySlots(vector<int> &bulbs, int k) {
set<int> s;
for (int i = 0; i < bulbs.size(); i++) {
int x = bulbs[i];
auto it = s.upper_bound(x);
if (it != s.end() && *it - x == k + 1)
return i + 1;
if (it != s.begin() && x - *prev(it) == k + 1)
return i + 1;
s.insert(x);
}
return -1;
}
};
| 21.166667 | 52 | 0.44357 | satu0king |
59c0d81cfdc6dd66f38ad87d10c0b02d6146d707 | 1,514 | cpp | C++ | src/lang/expr/throwNode.cpp | dmcdougall/occa | 4cc784e86459c01c8821da0a02eea3ad4fb36ef5 | [
"MIT"
] | null | null | null | src/lang/expr/throwNode.cpp | dmcdougall/occa | 4cc784e86459c01c8821da0a02eea3ad4fb36ef5 | [
"MIT"
] | null | null | null | src/lang/expr/throwNode.cpp | dmcdougall/occa | 4cc784e86459c01c8821da0a02eea3ad4fb36ef5 | [
"MIT"
] | null | null | null | #include <occa/lang/expr/throwNode.hpp>
namespace occa {
namespace lang {
throwNode::throwNode(token_t *token_,
const exprNode &value_) :
exprNode(token_),
value(value_.clone()) {}
throwNode::throwNode(const throwNode &node) :
exprNode(node.token),
value(node.value->clone()) {}
throwNode::~throwNode() {
delete value;
}
udim_t throwNode::type() const {
return exprNodeType::throw_;
}
exprNode* throwNode::clone() const {
return new throwNode(token, *value);
}
exprNode* throwNode::endNode() {
return value->endNode();
}
void throwNode::pushChildNodes(exprNodeVector &children) {
children.push_back(value);
}
bool throwNode::safeReplaceExprNode(exprNode *currentNode, exprNode *newNode) {
if (currentNode == value) {
delete value;
value = newNode;
return true;
}
return false;
}
exprNode* throwNode::wrapInParentheses() {
return new parenthesesNode(token, *this);
}
void throwNode::print(printer &pout) const {
pout << "throw";
if (value->type() != exprNodeType::empty) {
pout << ' ' << *value;
}
}
void throwNode::debugPrint(const std::string &prefix) const {
printer pout(io::stderr);
io::stderr << prefix << "|\n"
<< prefix << "|\n"
<< prefix << "|---[";
pout << *value;
io::stderr << "] (throw)\n";
}
}
}
| 23.292308 | 83 | 0.559445 | dmcdougall |
59c4e91fd07c9db6cc4bfaa43d48f05fefc663da | 3,323 | cpp | C++ | Lab2-1/Lab2-1/main.cpp | AlexPC2/Public | 9f42f1873c72355511242680f8ebd54d03dec895 | [
"MIT"
] | null | null | null | Lab2-1/Lab2-1/main.cpp | AlexPC2/Public | 9f42f1873c72355511242680f8ebd54d03dec895 | [
"MIT"
] | null | null | null | Lab2-1/Lab2-1/main.cpp | AlexPC2/Public | 9f42f1873c72355511242680f8ebd54d03dec895 | [
"MIT"
] | null | null | null | //
// main.cpp
// Lab2-1
//
// Created by Alex Noyanov on 12.02.19.
// Copyright © 2019 Popoff Developer Studio. All rights reserved.
//
// Лабораторная 2 Задача #1
/*
Задача №1
Выполнить преобразование Фурье для функции
Период функции равен T = 2*pi
a0 = 1,
am = 0,
m
(-1) + 1
bm = _____________
pi * m
1. Проверить формулы.
2. Составить программу, которая вычисляет разложение функции f(x) для различных m определить максимальную разность между значениями функции f(x) и c помощью разложения Фурье.
3. Построить график при различных m сравнить визуально схожесть графиков исходной функции и разложения Фурье.
n
____
a0 \ |
g(t) = ____ + \ [am* cos(mx) + bm*sin(mx)]
2 /
/____|
m = 1
F(g(t)) = A/(pi*f) * sin(pi+T)
Максимальную разность среди элементов
*/
#include <iostream>
#include <math.h>
using namespace std;
double f(double x)
{
while (x > M_PI*2) {
x -= M_PI*2;
}
if(x <= M_PI)
return 1.0;
else
return 0.0;
}
/*
double pow1(int m)
{
if(m%2 == 1)
return 1;
else
return -1;
}
*/
double b(double m) // Функция b(m)
{
double bm = (pow(-1,m+1)+1)/(M_PI * m);
//double bm = (pow1(m)+1.0)/(M_PI * m);
return bm;
}
double a2(int m)
{
double sum = 0;
const double dx = 0.01;
for(double x = 0; x < M_PI*2; x += dx) {
sum += f(x)*cos(m*x)*dx;
}
double integral = sum / M_PI;
return integral;
}
double b2(int m)
{
double sum = 0;
const double dx = 0.01;
for(double x = 0; x < M_PI*2; x += dx) {
sum += f(x)*sin(m*x)*dx;
}
double integral = sum / M_PI;
return integral;
}
/*
double g1(double x, int mmax) // Функция g(x)
{
double a0 = 1.0;
double amm, bmm;
double ds;
double sum = a0 / 2.0;
for(int m = 1; m < mmax; m++)
{
amm = a2(m);
bmm = b2(m);
ds = amm*cos(m*x) + bmm*sin(m*x);
sum += ds;
}
return sum;
}
*/
double g2(double x, int mmax) // Функция g(x)
{
double a0 = 1.0;
double bm = 0;
double ds;
double sum = a0 / 2.0;
for(int m = 1; m < mmax; m++)
{
bm = b(m); // Значение b(i)
ds = bm*sin(m*x);
sum += ds;
}
return sum;
}
int main(int argc, const char * argv[])
{
double maxDelta = 0;
const int mmax = 50;
for(int i = 1; i < mmax; i++)
printf("b[%d]=%.6f = %.3f/pi\n", i, b(i), b(i)*M_PI);
printf("\n");
for(double x = 0; x <= M_PI; x+= M_PI/8) {
double gx = g2(x, mmax);
double fx = f(x);
double dfx = fx - gx;
printf("x=%.4lf | %.3lf - %.3lf = %.3lf\n", x, fx, gx, dfx);
if(dfx > maxDelta) maxDelta = dfx;
}
cout << endl << "Max delta = " << maxDelta << endl;
// double yourValue;
// double d = 0;
//
// cout << "Input m: ";
// cin >> yourValue;
// cout << "Result:" << g(yourValue, &d) << endl;
//
// cout << "Max delta:" << d << endl;
return 0;
}
| 19.898204 | 177 | 0.466446 | AlexPC2 |
59c923713c29ef240b8fb860b4f83b5ca865de35 | 844 | hpp | C++ | framework/graphics/graphics/base.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | 1 | 2018-03-01T01:05:25.000Z | 2018-03-01T01:05:25.000Z | framework/graphics/graphics/base.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | framework/graphics/graphics/base.hpp | YiJiangFengYun/vulkan-graphics-examples | e7b788b8f47dd238b08840c019940c7c52335a54 | [
"MIT"
] | null | null | null | #ifndef VG_BASE_H
#define VG_BASE_H
#include <unordered_map>
namespace vg
{
enum class BaseType
{
UNDEFINED,
VERTEX_DATA,
INDEX_DATA,
UNIFORM_BUFFER_DATA,
TEXTURE,
SHADER,
PASS,
PRE_DEPTH_PASS,
MATERIAL,
MESH,
TRANSFORM,
SCENE,
SCENE_OBJECT,
RENDERER_PASS,
RENDERER,
APP,
};
using InstanceID = uint32_t;
class Base
{
public:
Base(BaseType baseType);
virtual ~Base();
BaseType getBaseType() const;
InstanceID getID() const;
protected:
BaseType m_baseType;
InstanceID m_id;
private:
Base() = delete;
static std::unordered_map<BaseType, InstanceID> m_idCreator;
};
} //namespace kgs
#endif // !VG_BASE_H
| 15.924528 | 68 | 0.554502 | YiJiangFengYun |
59cd84a2f095c7786a1ecab691c3516a4bf334a6 | 10,075 | cc | C++ | build/x86/python/m5/internal/param_DMASequencer.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/python/m5/internal/param_DMASequencer.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/python/m5/internal/param_DMASequencer.py.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_param_DMASequencer[] = {
120,156,197,89,253,114,219,198,17,223,3,64,74,164,36,75,
178,190,252,33,91,180,93,59,172,167,18,19,39,142,211,137,
235,214,205,199,76,51,99,37,5,211,177,195,100,138,66,192,
137,4,69,2,44,112,180,205,140,52,211,169,60,109,254,235,
95,125,132,254,209,23,232,115,244,9,250,42,205,238,30,0,
66,34,157,122,218,142,36,145,167,195,98,111,239,118,247,183,
123,123,39,15,210,159,18,126,127,81,3,72,254,37,0,124,
252,8,232,1,244,5,180,4,8,41,192,95,133,131,18,196,
239,129,95,130,87,0,45,3,164,1,199,216,49,225,107,3,
194,121,30,83,134,158,201,20,1,163,42,72,11,90,37,120,
26,46,131,37,203,112,80,133,248,119,32,132,8,5,60,243,
103,192,159,133,87,40,29,59,21,22,56,11,68,172,50,177,
2,254,28,19,171,224,207,115,103,14,70,75,32,231,161,181,
64,108,173,11,40,246,46,138,93,100,177,255,36,177,62,190,
89,3,255,2,177,227,186,190,34,78,139,56,121,190,69,150,
178,148,173,114,25,90,23,179,254,74,161,191,90,232,175,21,
250,235,133,254,70,161,127,169,208,191,92,232,95,41,244,175,
22,250,155,133,254,181,66,255,58,247,81,195,139,208,221,130,
110,13,186,55,96,31,141,190,156,107,115,19,164,9,221,91,
208,186,5,18,63,55,225,24,253,226,95,44,140,248,17,143,
88,201,71,220,230,17,119,160,117,7,36,126,110,235,17,101,
104,214,215,209,215,193,191,241,167,142,190,6,53,143,205,115,
25,39,65,20,58,65,184,31,5,6,189,47,83,67,200,240,
168,153,73,33,242,17,65,228,239,192,248,240,141,20,34,71,
128,130,5,233,210,51,224,136,59,71,6,140,234,112,40,160,
107,129,111,194,33,78,83,162,5,180,5,28,27,240,141,73,
12,71,216,90,232,200,235,96,41,141,143,46,59,82,75,154,
129,163,18,28,150,160,249,236,208,32,194,65,5,226,191,193,
183,155,44,116,150,133,26,112,136,173,5,199,22,28,149,225,
41,50,33,169,91,33,245,197,179,67,212,20,41,205,186,133,
171,221,45,168,75,170,248,65,28,186,125,169,86,176,239,12,
220,216,237,59,31,63,121,220,148,191,31,202,208,147,113,189,
154,49,70,201,206,192,85,29,155,71,154,100,146,254,64,177,
196,40,148,106,14,59,251,65,232,59,253,200,31,246,164,154,
37,113,206,126,208,147,142,195,47,127,213,31,68,177,250,36,
142,163,216,38,171,50,177,23,185,249,8,178,169,215,139,18,
89,167,217,120,26,155,196,43,226,222,31,176,68,90,0,175,
150,6,251,50,241,226,96,160,208,89,90,34,113,147,180,58,
185,137,155,100,15,155,70,63,84,141,78,123,63,105,52,59,
110,44,155,29,25,54,218,178,127,127,59,138,131,118,16,110,
39,202,221,235,201,237,123,111,191,115,127,251,167,219,239,54,
246,134,65,207,111,188,252,224,253,198,96,164,58,81,216,232,
223,111,4,161,146,104,167,94,99,210,66,59,200,117,145,230,
122,17,180,157,128,181,116,58,178,55,144,241,2,81,175,208,
58,196,146,152,23,101,97,138,186,88,192,94,9,191,166,216,
52,230,196,110,64,122,122,164,59,161,204,42,226,138,156,45,
224,192,128,120,147,80,211,197,143,32,55,35,118,154,244,206,
224,119,191,38,3,105,106,215,36,44,104,226,33,35,13,33,
135,156,15,201,249,33,48,92,74,208,45,131,134,17,162,79,
227,42,30,81,139,236,36,198,64,225,22,36,127,5,52,56,
2,232,16,82,112,29,155,32,194,37,80,85,202,37,72,93,
199,9,255,200,248,108,214,105,249,187,12,18,213,9,146,232,
69,200,174,160,62,71,84,19,45,243,197,232,243,189,174,244,
84,178,133,132,175,162,97,205,115,195,48,82,53,215,247,107,
174,82,113,176,55,84,50,169,169,168,118,59,169,147,119,237,
229,12,103,185,188,209,32,195,21,97,0,113,165,31,252,192,
83,248,192,0,118,216,11,137,84,136,145,78,228,39,72,39,
17,109,169,108,90,164,34,35,71,188,16,134,144,67,172,52,
61,242,93,192,231,199,217,74,24,167,245,114,134,170,68,246,
246,85,149,1,234,38,137,195,43,33,58,99,145,4,63,119,
123,67,201,210,17,77,10,23,68,93,189,134,179,71,227,37,
210,44,51,4,107,23,70,161,63,194,197,6,222,91,180,142,
75,140,201,121,70,229,26,34,114,6,219,50,254,45,139,117,
195,179,82,28,150,51,44,82,142,84,192,72,16,41,24,16,
151,199,152,143,234,6,39,20,86,144,227,245,38,245,104,176,
189,73,205,53,106,174,83,179,149,217,224,76,13,177,112,218,
16,15,104,114,131,181,103,61,201,117,102,166,167,127,34,230,
46,143,99,14,147,104,147,98,199,160,8,27,199,142,69,9,
55,126,68,45,178,114,84,154,144,124,73,233,157,98,140,133,
81,56,97,96,80,111,28,46,108,53,123,137,172,49,155,33,
221,38,248,22,49,220,46,96,216,38,135,49,128,237,203,89,
234,116,136,67,67,215,190,74,162,74,83,204,94,163,230,198,
185,216,126,12,194,246,4,8,63,164,117,44,165,32,92,96,
240,85,241,187,100,120,102,234,144,124,131,93,57,5,62,66,
158,53,5,121,119,168,103,78,154,224,60,65,151,42,254,105,
1,116,180,86,163,168,223,46,118,70,27,164,86,17,110,27,
88,58,60,13,55,176,26,48,184,26,120,155,171,1,174,40,
184,134,211,201,221,228,252,174,59,37,178,207,190,9,235,233,
46,159,84,176,29,196,209,203,81,45,218,175,41,54,0,229,
226,135,183,147,157,219,201,135,152,101,107,143,56,191,233,60,
171,51,105,44,7,148,9,105,232,39,47,61,201,91,43,63,
57,142,78,124,14,39,65,39,221,178,17,121,107,100,93,35,
51,59,111,1,137,138,41,243,159,189,225,171,185,225,73,143,
207,104,230,42,91,221,20,27,136,178,170,224,229,57,58,253,
115,41,199,111,241,251,75,242,4,153,64,2,21,249,118,83,
47,158,245,34,13,237,159,156,64,210,89,106,101,55,112,154,
223,100,8,42,143,17,68,95,51,139,144,63,3,87,188,2,
254,4,132,17,132,66,26,33,121,64,17,40,86,136,253,183,
192,161,52,165,178,224,28,213,164,106,130,57,48,117,37,15,
152,85,23,26,159,193,119,133,56,204,202,1,51,173,105,139,
229,128,149,231,55,6,215,27,109,249,214,201,68,72,158,234,
184,9,177,233,236,54,14,237,241,126,146,87,162,152,221,207,
20,105,179,122,78,135,150,247,205,24,103,180,161,94,21,43,
70,1,61,239,80,115,47,7,142,200,104,103,181,210,45,120,
125,41,224,232,253,229,107,90,142,197,10,44,206,112,189,86,
20,146,199,73,41,139,147,123,121,156,72,222,10,95,241,9,
136,90,131,176,112,108,8,60,246,98,141,72,167,76,11,100,
9,90,101,138,40,46,239,69,26,112,34,75,127,148,44,79,
236,179,108,162,93,109,188,28,14,218,211,212,188,60,251,180,
66,206,126,216,115,251,123,190,251,136,242,104,66,147,123,89,
8,26,153,38,75,69,77,40,124,196,235,148,225,199,251,153,
70,207,207,62,165,188,15,188,167,106,77,56,128,252,200,227,
60,242,101,71,214,250,178,191,135,71,224,78,48,168,237,247,
220,54,251,204,76,53,253,60,211,84,177,211,79,215,52,201,
93,106,163,154,23,133,184,11,12,61,21,197,53,95,226,177,
80,250,181,237,26,111,33,181,32,169,185,123,248,214,245,148,
14,135,147,225,205,101,181,27,183,19,174,160,15,94,80,247,
124,124,238,56,65,24,224,193,226,57,228,219,183,62,153,230,
59,2,31,25,116,116,225,78,139,7,62,53,210,89,143,234,
27,123,135,154,31,195,185,109,28,239,165,30,78,200,144,101,
113,213,168,24,124,78,45,242,125,65,35,147,201,24,255,199,
155,196,184,190,212,74,35,189,76,156,114,134,238,35,168,173,
208,246,209,170,102,196,57,110,231,153,184,144,17,47,112,187,
200,196,165,140,184,204,237,69,38,174,100,196,85,110,215,152,
184,158,93,187,109,48,241,18,180,46,211,189,17,81,174,80,
158,153,249,95,243,12,135,230,249,4,229,209,255,53,189,216,
15,206,95,17,251,3,72,75,148,215,165,22,81,212,114,65,
167,150,174,200,78,84,69,21,249,142,231,242,84,4,59,94,
44,93,37,181,255,54,207,67,109,78,87,122,21,127,24,39,
140,201,122,255,113,174,225,49,151,106,163,85,118,171,62,90,
178,91,197,211,240,10,22,254,22,23,254,15,169,240,63,100,
115,56,134,174,253,199,224,45,229,86,161,35,122,40,95,56,
147,150,209,229,61,45,206,29,12,100,232,219,119,161,88,177,
243,235,179,199,8,37,200,239,160,80,56,153,98,21,75,244,
201,184,165,221,160,160,49,251,183,148,71,234,185,120,154,1,
254,151,12,224,117,218,190,198,91,130,253,144,26,222,4,242,
252,111,255,60,247,211,205,233,232,141,135,123,35,39,25,37,
74,246,233,208,248,38,108,88,206,241,53,64,129,166,174,77,
31,86,16,252,195,28,36,147,175,176,180,184,250,116,230,97,
18,132,109,189,22,44,223,209,82,44,249,141,153,105,18,2,
221,196,27,117,125,186,136,236,62,158,102,249,15,44,36,155,
242,127,250,172,238,77,103,231,43,218,164,231,62,151,14,86,
42,33,158,6,105,176,23,13,67,197,179,252,23,195,104,102,
66,194,15,240,48,232,57,127,249,178,39,149,156,18,172,138,
128,147,222,255,248,104,148,56,26,225,145,155,79,173,248,220,
115,156,115,42,37,126,166,55,31,125,21,136,165,132,40,99,
49,177,38,210,95,163,82,174,8,174,224,78,253,187,68,47,
148,110,28,245,41,109,148,216,188,39,44,230,241,192,119,250,
89,233,68,161,195,183,13,187,110,95,95,192,242,125,162,125,
11,210,251,29,251,173,60,174,200,140,124,52,214,215,19,152,
251,184,186,228,98,210,126,151,232,148,27,250,247,119,50,205,
118,180,102,54,226,173,169,225,109,48,3,67,106,146,175,25,
244,7,61,249,68,246,163,120,164,106,83,89,30,167,85,108,
202,116,117,42,19,190,212,247,222,124,18,155,124,255,81,47,
242,14,164,159,242,92,123,61,207,199,81,223,69,250,244,89,
112,181,169,132,229,83,239,253,152,70,173,157,162,38,50,14,
220,94,240,173,228,91,186,41,242,180,133,78,79,38,195,33,
107,132,234,62,137,124,57,97,226,199,190,31,219,110,216,150,
24,144,84,251,171,27,167,25,78,152,44,227,34,16,100,44,
138,176,113,218,116,228,226,252,137,235,218,137,50,128,99,38,
150,237,128,51,201,98,113,64,186,15,18,134,217,9,211,242,
95,97,240,249,132,152,62,101,234,107,181,71,148,215,57,84,
232,126,190,178,88,193,112,163,29,210,20,85,220,35,45,115,
126,169,98,205,207,85,172,202,140,201,23,167,11,98,197,168,
90,149,185,121,241,186,223,45,12,208,170,177,181,90,17,223,
3,166,146,52,138,
};
EmbeddedPython embedded_m5_internal_param_DMASequencer(
"m5/internal/param_DMASequencer.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/build/x86/python/m5/internal/param_DMASequencer.py",
"m5.internal.param_DMASequencer",
data_m5_internal_param_DMASequencer,
2485,
7909);
} // anonymous namespace
| 58.236994 | 105 | 0.666005 | billionshang |
59d09dc56d120e65fe8acb1a2902fcd714d6d1f0 | 1,742 | cpp | C++ | SAMP-EDGEngine/src/SAMP-EDGEngine/Server/GameMode.cpp | Desantowski/SAMP-EDGEngine | 949811bf801b1a1a76cc7cc510be749cdfdba540 | [
"MIT"
] | null | null | null | SAMP-EDGEngine/src/SAMP-EDGEngine/Server/GameMode.cpp | Desantowski/SAMP-EDGEngine | 949811bf801b1a1a76cc7cc510be749cdfdba540 | [
"MIT"
] | null | null | null | SAMP-EDGEngine/src/SAMP-EDGEngine/Server/GameMode.cpp | Desantowski/SAMP-EDGEngine | 949811bf801b1a1a76cc7cc510be749cdfdba540 | [
"MIT"
] | null | null | null | #include "SAMP-EDGEnginePCH.hpp" // PCH
// Custom includes:
#include <SAMP-EDGEngine/Server/GameMode.hpp>
#include <SAMP-EDGEngine/World/Streamer/Streamer.hpp>
namespace agdk
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IGameMode::IGameMode()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IGameMode::~IGameMode()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
SharedPtr<Player> IGameMode::newPlayerInstance(std::size_t const playerIndex_) const
{
return std::make_shared<Player>(playerIndex_);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void IGameMode::addPlayerClass(std::size_t modelIndex_, math::Vector3f const location_, float const facingAngle_, std::array<Weapon, 3> weapons_)
{
sampgdk_AddPlayerClass(modelIndex_, location_.x, location_.y, location_.z, facingAngle_,
static_cast<std::int32_t>(weapons_[0].getType()), weapons_[0].getAmmo(),
static_cast<std::int32_t>(weapons_[1].getType()), weapons_[1].getAmmo(),
static_cast<std::int32_t>(weapons_[2].getType()), weapons_[2].getAmmo());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void IGameMode::setup()
{
this->setupStreamer();
this->setupEvents();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void IGameMode::setupStreamer()
{
Streamer = std::make_unique<default_streamer::Streamer>();
}
}
| 35.55102 | 145 | 0.434558 | Desantowski |
59d50d601f627a0bf9f4ce0814160d77c9f4f94d | 18,753 | cxx | C++ | PWG/EMCAL/EMCALbase/AliEmcalESDTrackCutsGenerator.cxx | AudreyFrancisco/AliPhysics | cb36cfa7d1edcd969780e90fe6bfab5107f0f099 | [
"BSD-3-Clause"
] | null | null | null | PWG/EMCAL/EMCALbase/AliEmcalESDTrackCutsGenerator.cxx | AudreyFrancisco/AliPhysics | cb36cfa7d1edcd969780e90fe6bfab5107f0f099 | [
"BSD-3-Clause"
] | null | null | null | PWG/EMCAL/EMCALbase/AliEmcalESDTrackCutsGenerator.cxx | AudreyFrancisco/AliPhysics | cb36cfa7d1edcd969780e90fe6bfab5107f0f099 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
* Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <TString.h>
#include <TFormula.h>
#include "AliEmcalTrackSelection.h"
#include "AliEmcalESDTrackCutsGenerator.h"
#include "AliESDtrackCuts.h"
#include "TError.h"
const Int_t AliEmcalESDTrackCutsGenerator::fgkAddCutFactor = 10000;
/**
* Function to create track cuts for PWG Jet analysis
* User can select a specific set by indicating cutMode
*
* \param cutMode has 8 digits: first 4 digits additional cuts, last 4 digits standard cuts
* additional cuts are variations of standard cuts (used for hybrid track selection and QA)
* Numbering starts from 1000 For standard and additional cut numbers
*
* \return AliESDtrackCuts object
*/
AliESDtrackCuts* AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(Int_t cutMode)
{
//Get standard cuts: last 4 digits of cutMode
Int_t stdCutMode = cutMode % fgkAddCutFactor;
//Get additional cut mode: first 4 digits of cutMode
Int_t addCutMode = (int)((float)cutMode/(float)fgkAddCutFactor);
return CreateTrackCutsPWGJE(stdCutMode, addCutMode);
}
/**
* Function to create track cuts for PWG Jet analysis
* User can select a specific set by indicating cutMode
*
* \param stdCutMode standard cuts, should be one of the EStdCutMode_t enum values
* \param addCutMode additional cuts, should be one of the EAddCutMode_t enum values
*
* \return AliESDtrackCuts object
*/
AliESDtrackCuts* AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(Int_t stdCutMode, Int_t addCutMode)
{
AliESDtrackCuts* trackCuts = 0;
TString tag;
tag = SetStandardCuts(trackCuts, stdCutMode);
tag += SetAdditionalCuts(trackCuts, addCutMode);
::Info("AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE", "Created track cuts for: %s", tag.Data());
return trackCuts;
}
/**
* Function to create track cuts for PWG Jet analysis
* User can select a specific set by indicating cutMode
*
* \param stdCutMode standard cuts, should be one of the EStdCutMode_t enum values
* \param addCutMode1 additional cuts, should be one of the EAddCutMode_t enum values
* \param addCutMode2 additional cuts, should be one of the EAddCutMode_t enum values
*
* \return AliESDtrackCuts object
*/
AliESDtrackCuts* AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE(Int_t stdCutMode, Int_t addCutMode1, Int_t addCutMode2)
{
AliESDtrackCuts* trackCuts = 0;
TString tag;
tag = SetStandardCuts(trackCuts, stdCutMode);
tag += SetAdditionalCuts(trackCuts, addCutMode1);
tag += SetAdditionalCuts(trackCuts, addCutMode2);
::Info("AliEmcalESDTrackCutsGenerator::CreateTrackCutsPWGJE", "Created track cuts for: %s", tag.Data());
return trackCuts;
}
/**
* Function to set standard track cuts
* User can select a specific set by indicating stdCutMode
*
* \param trackCuts AliESDtrackCuts to be set
* \param stdCutMode has 4 digits, >= 1000
*
* \return string with track cut label
*/
TString AliEmcalESDTrackCutsGenerator::SetStandardCuts(AliESDtrackCuts*& trackCuts, Int_t stdCutMode)
{
TString tag;
if (trackCuts) {
delete trackCuts;
trackCuts = 0;
}
switch (stdCutMode) {
case kRAA2011:
{
trackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kTRUE,1);
trackCuts->SetMinNCrossedRowsTPC(120);
trackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.8);
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
trackCuts->SetMaxChi2TPCConstrainedGlobal(36);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1e10);
tag = "Global track RAA analysis QM2011 + Chi2ITS<36";
break;
}
case kGlobalTracksNCls90NoSPD:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// TPC
trackCuts->SetMinNClustersTPC(90);
trackCuts->SetMaxChi2PerClusterTPC(4);
trackCuts->SetRequireTPCStandAlone(kTRUE); //cut on NClustersTPC and chi2TPC Iter1
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
// ITS
trackCuts->SetRequireITSRefit(kTRUE);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
//reject fakes
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 100.);
tag = "Global tracks jet analysis with ITSrefit and NclsIter1=90, noSPD requirement";
break;
}
case kGlobalTracksNCls80NoSPD:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// TPC
trackCuts->SetMinNClustersTPC(80);
trackCuts->SetMaxChi2PerClusterTPC(4);
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
// ITS
trackCuts->SetRequireITSRefit(kTRUE);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
//reject fakes
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 100.);
tag = "Global tracks jet analysis with ITSrefit and Ncls=80, noSPD requirement";
break;
}
case kGlobalTracks2010NCrossRows120:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// tight global tracks
trackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(kFALSE,1);
trackCuts->SetMinNClustersTPC(0);
trackCuts->SetMinNCrossedRowsTPC(120);
trackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.1);// essentially switches it off
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
tag = "Global tracks ITSTPC2010 + NCrossedRows + loose ITS";
break;
}
case kGlobalTracksNCls70NoSPD:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// TPC
trackCuts->SetMinNClustersTPC(70);
trackCuts->SetMaxChi2PerClusterTPC(4);
trackCuts->SetRequireTPCStandAlone(kTRUE); //cut on NClustersTPC and chi2TPC Iter1
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
// ITS
trackCuts->SetRequireITSRefit(kTRUE);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
//reject fakes
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 100.);
tag = "Global tracks jet analysis with ITSrefit and NclsIter1=70, noSPD requirement";
break;
}
case kGlobalTracksNCls70NoSPDNoPtCut:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// TPC
trackCuts->SetMinNClustersTPC(70);
trackCuts->SetMaxChi2PerClusterTPC(4);
trackCuts->SetRequireTPCStandAlone(kTRUE); //cut on NClustersTPC and chi2TPC Iter1
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
// ITS
trackCuts->SetRequireITSRefit(kTRUE);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
//reject fakes
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1E+15);
tag = "Global tracks jet analysis with ITSrefit and NclsIter1=70, noSPD requirement, no upper pt cut";
break;
}
case kGlobalTracksNClsPtDepNoSPDNoPtCut:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// TPC
TFormula *f1NClustersTPCLinearPtDep = new TFormula("f1NClustersTPCLinearPtDep","70.+30./20.*x");
trackCuts->SetMinNClustersTPCPtDep(f1NClustersTPCLinearPtDep,20.);
trackCuts->SetMinNClustersTPC(70);
trackCuts->SetMaxChi2PerClusterTPC(4);
trackCuts->SetRequireTPCStandAlone(kTRUE); //cut on NClustersTPC and chi2TPC Iter1
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
// ITS
trackCuts->SetRequireITSRefit(kTRUE);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
//reject fakes
trackCuts->SetMaxChi2PerClusterITS(36);
trackCuts->SetMaxChi2TPCConstrainedGlobal(36);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1E+15);
tag = "Global tracks jet analysis with ITSrefit and NclsIter1=PtDep, noSPD requirement, no upper pt cut, golden chi2";
break;
}
case kGlobalTracks2011:
{
trackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE,1);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
trackCuts->SetMaxChi2TPCConstrainedGlobal(36);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 1E+15);
tag = "Global tracks with AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE)";
break;
}
case kGlobalTracks2011NoSPD:
{
trackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE,1);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
trackCuts->SetMaxChi2TPCConstrainedGlobal(36);
trackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kNone);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
tag = "Global tracks 2011 with AliESDtrackCuts::GetStandardITSTPCTrackCuts2011(kFALSE) and no SPD requirement";
break;
}
case kGlobalTracksNCls90NoITS:
{
trackCuts = new AliESDtrackCuts("AliESDtrackCuts");
// TPC
trackCuts->SetMinNClustersTPC(90);
trackCuts->SetMaxChi2PerClusterTPC(4);
trackCuts->SetRequireTPCStandAlone(kTRUE); //cut on NClustersTPC and chi2TPC Iter1
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMaxFractionSharedTPCClusters(0.4);
//accept secondaries
trackCuts->SetMaxDCAToVertexXY(2.4);
trackCuts->SetMaxDCAToVertexZ(3.2);
trackCuts->SetDCAToVertex2D(kTRUE);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 100.);
tag = "Global tracks jet analysis, loose cuts, NClsIter1=90, no ITS requirements";
break;
}
case kTPCOnlyTracksNCls70:
{
trackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
// trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMinNClustersTPC(70);
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 100.);
tag = "TPConly track cuts, loose cuts, NCls=70, no ITS requirements";
break;
}
case kTPCOnlyTracksNCrossRows120:
{
trackCuts = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
trackCuts->SetMinNClustersTPC(0);
trackCuts->SetMinNCrossedRowsTPC(120);
trackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.1);// essentially switches it off
trackCuts->SetEtaRange(-0.9,0.9);
trackCuts->SetPtRange(0.15, 100.);
tag = "TPConly track cuts, loose cuts, NCrossRows=120, no ITS requirements";
break;
}
default:
{
Printf("AliEmcalESDTrackCutsGenerator: standard cuts not recognized.");
break;
}
}
return tag;
}
/**
* Function to set additional track cuts on top of the standard ones
* User can select a specific set by indicating addCutMode
*
* \param trackCuts AliESDtrackCuts to be set
* \param addCutMode has 4 digits, >= 1000
*
* \return string with track cut label
*/
TString AliEmcalESDTrackCutsGenerator::SetAdditionalCuts(AliESDtrackCuts*& trackCuts, Int_t addCutMode)
{
TString tag;
switch (addCutMode) {
case kSPDAny:
{
trackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kAny);
tag += " + additonal: SPD any requirement";
break;
}
case kSPDNone:
{
trackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kNone);
tag += " + additional: w/o hits in SPD";
break;
}
case kNoITSChi2:
{
trackCuts->SetMaxChi2PerClusterITS(1E10);
tag += " + additional: maxITSChi2=1e10";
break;
}
case kNoMinTPCCls:
{
trackCuts->SetMinNClustersTPC(0);
trackCuts->SetMinNCrossedRowsTPC(0);
trackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.);
tag += " + additional: minClusters=0 minCrossedRows=0 minCrossedRowsOverFindable=0";
break;
}
case kNoITSRefit:
{
trackCuts->SetRequireITSRefit(kFALSE);
tag += " + additional: ITSrefit=kFALSE";
break;
}
case kSPDOff:
{
trackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kOff);
tag += " + additional: no SPD requirement (kOff)";
break;
}
}
return tag;
}
/**
* Helper function to steer period string into an enum type
*
* \param period String identifying a data or MC period
*
* \return enum type identifying a data or MC period
*/
AliEmcalESDTrackCutsGenerator::EDataSet_t AliEmcalESDTrackCutsGenerator::SteerDataSetFromString(TString period)
{
EDataSet_t dataSet = kUnknown;
TString strPeriod(period);
strPeriod.ToLower();
if (strPeriod == "lhc10h") {
dataSet = kLHC10h;
} else if (strPeriod == "lhc11a" || strPeriod == "lhc12a15a") {
dataSet = kLHC11a;
} else if (strPeriod == "lhc10b" || strPeriod == "lhc10c" ||
strPeriod == "lhc10d" || strPeriod == "lhc10e") {
dataSet = kLHC10bcde;
} else if (strPeriod == "lhc11a1a" || strPeriod == "lhc11a1b" ||
strPeriod == "lhc11a1c" || strPeriod == "lhc11a1d" ||
strPeriod == "lhc11a1e" || strPeriod == "lhc11a1f" ||
strPeriod == "lhc11a1g" || strPeriod == "lhc11a1h" ||
strPeriod == "lhc11a1i" || strPeriod == "lhc11a1j") {
dataSet = kLHC11a;
} else if (strPeriod == "lhc11c") {
dataSet = kLHC11c;
} else if (strPeriod == "lhc11d") {
dataSet = kLHC11d;
} else if (strPeriod == "lhc11h" || strPeriod == "lhc12a15e") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc12g") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc12") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13b") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13c") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13d") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13e") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13f") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13g") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc16q") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc16r") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc16s") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc16t") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc12a15f") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc13b4") {
dataSet = kLHC11h;
} else if (strPeriod == "lhc12a15g") {
dataSet = kLHC11d;
} else if (strPeriod == "lhc12f2a") {
dataSet = kLHC11d;
} else if (strPeriod.BeginsWith("lhc12a17")) {
dataSet = kLHC11h;
} else if (strPeriod == "lhc14a1") {
dataSet = kLHC11h;
} else if (strPeriod.BeginsWith("lhc15g6")) {
dataSet = kLHC10bcde;
} else {
::Error("AliEmcalESDTrackCutsGenerator::SteerDataSetFromString", "Dataset %s not recognized!", period.Data());
}
return dataSet;
}
/**
* Adds hybrid track cuts to an AliEmcalTrackSelection object
*
* \param trkSel AliEmcalTrackSelection object
* \param period enum type identifying a data or MC period
*/
void AliEmcalESDTrackCutsGenerator::AddHybridTrackCuts(AliEmcalTrackSelection* trkSel, EDataSet_t period)
{
switch (period) {
case kLHC11c:
case kLHC11d:
case kLHC11h:
{
AliESDtrackCuts *cutsp = CreateTrackCutsPWGJE(kGlobalTracks2011NoSPD, kSPDAny);
trkSel->AddTrackCuts(cutsp);
AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(kGlobalTracks2011NoSPD, kSPDOff);
trkSel->AddTrackCuts(hybsp);
break;
}
case kLHC10h:
case kLHC11a:
case kLHC10bcde:
{
/* hybrid track cuts*/
AliESDtrackCuts *cutsp = CreateTrackCutsPWGJE(kGlobalTracksNClsPtDepNoSPDNoPtCut, kSPDAny);
trkSel->AddTrackCuts(cutsp);
AliESDtrackCuts *hybsp = CreateTrackCutsPWGJE(kGlobalTracksNClsPtDepNoSPDNoPtCut, kSPDOff, kNoITSRefit);
trkSel->AddTrackCuts(hybsp);
break;
}
default:
{
::Error("AliEmcalESDTrackCutsGenerator::AddHybridTrackCuts", "Hybrid track cuts not available for dataset %d", period);
break;
}
}
}
/**
* Adds TPC only track cuts to an AliEmcalTrackSelection object
*
* \param trkSel AliEmcalTrackSelection object
* \param period enum type identifying a data or MC period
*/
void AliEmcalESDTrackCutsGenerator::AddTPCOnlyTrackCuts(AliEmcalTrackSelection* trkSel, EDataSet_t period)
{
switch (period) {
case kLHC11c:
case kLHC11d:
case kLHC11h:
{
AliESDtrackCuts *cutsp = CreateTrackCutsPWGJE(kTPCOnlyTracksNCls70);
trkSel->AddTrackCuts(cutsp);
break;
}
default:
{
Printf("AliEmcalESDTrackCutsGenerator::AddTPCOnlyTrackCuts: TPC only track cuts not available for dataset %d", period);
break;
}
}
}
| 30.492683 | 124 | 0.702181 | AudreyFrancisco |
59dbbd987f751c17d80fca7a13dd90ee65078e84 | 312 | cpp | C++ | src/filament_tester.cpp | Betterton-Lab/CyLaKS | 17d01e8742b8172b477dd99d254c2d0771f774d0 | [
"BSD-3-Clause"
] | null | null | null | src/filament_tester.cpp | Betterton-Lab/CyLaKS | 17d01e8742b8172b477dd99d254c2d0771f774d0 | [
"BSD-3-Clause"
] | null | null | null | src/filament_tester.cpp | Betterton-Lab/CyLaKS | 17d01e8742b8172b477dd99d254c2d0771f774d0 | [
"BSD-3-Clause"
] | null | null | null | #include "cylaks/filament_tester.hpp"
#include "cylaks/protein_tester.hpp"
void FilamentTester::Initialize(ProteinTester *proteins) {
proteins_ = proteins;
FilamentManager::proteins_ = dynamic_cast<ProteinManager *>(proteins_);
FilamentManager::SetParameters();
FilamentManager::GenerateFilaments();
}
| 28.363636 | 73 | 0.788462 | Betterton-Lab |
59de3fa528965e2c40956339db5fb3f5056a5b10 | 2,079 | cpp | C++ | Fractal/FractalPhysics/src/PhysicsBody.cpp | talislincoln/fractals | a9ed52e99b9737ce0a6bba715f61e4d122e37dd5 | [
"MIT"
] | 2 | 2016-09-22T16:11:17.000Z | 2016-09-22T16:11:55.000Z | Fractal/FractalPhysics/src/PhysicsBody.cpp | talislincoln/FractalGameEngine | a9ed52e99b9737ce0a6bba715f61e4d122e37dd5 | [
"MIT"
] | null | null | null | Fractal/FractalPhysics/src/PhysicsBody.cpp | talislincoln/FractalGameEngine | a9ed52e99b9737ce0a6bba715f61e4d122e37dd5 | [
"MIT"
] | null | null | null | #include "PhysicsBody.h"
namespace fractal {
namespace fphysics {
PhysicsBody::PhysicsBody() {
m_aabb;
m_mass = float(1.0);
m_worldCenter.load();
m_localCenter.load();
m_linearVelocity.load();
m_angularVelocity.load();
m_gravityScale = float(1.0);
//m_linearDamping = float(0.0);
//m_angularDamping = float(0.1);
m_force.load();
m_torque.load();
m_flags = 0x000000000;
m_flags |= DYNAMIC;
m_flags |= ALLOWSLEEP;
m_flags |= AWAKE;
m_flags |= ACTIVE;
}
void PhysicsBody::calculateMassData(const std::vector<PhysicsShape*> shapeList, Transform& m_localTransform) {
Matrix3 inertia = Matrix3((0.0f));
m_inverseInertiaModel = Matrix3((0.0f));
m_inverseInertiaWorld = Matrix3((0.0f));
m_inverseMass = (0.0f);
m_mass = (0.0f);
float mass = (0.0f);
if (m_flags & STATIC || m_flags & KINEMATIC)
{
m_localCenter.load();
m_worldCenter = m_localTransform.position;
return;
}
Vector3 lc;
lc.load();
for (auto& shape : shapeList)
{
if (shape->density == float(0.0))
continue;
massData md;
shape->calMass(&md);
mass += md.mass;
inertia += md.inertia;
lc += md.center * md.mass;
}
if (mass > float(0.0))
{
m_mass = mass;
m_inverseMass = float(1.0) / mass;
lc *= m_inverseMass;
Matrix3 identity;
Matrix3 outerP = Matrix3::outerProduct(lc, lc);
identity.loadIdentity();
inertia -= (identity * lc.dot(lc) - outerP) * mass;
m_inverseInertiaModel = inertia;
bool freezeX = false, freezeY = false, freezeZ = false;
if (m_flags & LOCKAXISX)
freezeX = true;
if (m_flags & LOCKAXISY)
freezeY = true;
if (m_flags & LOCKAXISZ)
freezeZ = true;
m_inverseInertiaModel.freezeRotate(freezeX, freezeY, freezeZ);
}
else
{
// Force all dynamic bodies to have some mass
m_inverseMass = float(1.0);
m_inverseInertiaModel = Matrix3(0.0f);
m_inverseInertiaWorld = Matrix3(0.0f);
}
m_localCenter = lc;
m_worldCenter = m_localTransform * (Point3)lc;
}
}
} | 22.117021 | 112 | 0.632516 | talislincoln |
59e3772f5bd2eed985a614106983ac96c6880df1 | 3,637 | cpp | C++ | src/PixelFlutSource.cpp | subject721/floodfill | f1328ac8de2f3c7988256e7cb9948f671f91a2d7 | [
"MIT"
] | null | null | null | src/PixelFlutSource.cpp | subject721/floodfill | f1328ac8de2f3c7988256e7cb9948f671f91a2d7 | [
"MIT"
] | null | null | null | src/PixelFlutSource.cpp | subject721/floodfill | f1328ac8de2f3c7988256e7cb9948f671f91a2d7 | [
"MIT"
] | null | null | null | #include "PixelFlutSource.h"
#include "DrawIF.h"
#include "DrawOperations.h"
#include <cstring>
#include <cstdlib>
PixelFlutSource::PixelFlutSource()
{
}
PixelFlutSource::~PixelFlutSource()
{
}
void PixelFlutSource::start(IDrawInterface* drawInterface)
{
_drawInterface = drawInterface;
}
void PixelFlutSource::stop()
{
}
int PixelFlutSource::handleCmd(const char* cmdIn, int cmdInLen, char* cmdOut, int cmdOutBufferSize)
{
PixelFlutCmd cmdStruct;
if(!parseCmd(cmdStruct, cmdIn, cmdInLen))
{
return -1;
}
if(cmdStruct.cmd == CMD_PX)
{
//LOG("CMD_PX %u %u %x", cmdStruct.args[0], cmdStruct.args[1], cmdStruct.args[2]);
if(cmdStruct.nargs == 3)
{
//Fucking dirty hack! But in this prealpharandomexcusewhyitmaynotbeworking version i don't give a shit!
uint8_t drawOpBuf[DRAW_PIXEL_OP_SIZE];
DrawOpDescr* drawPixelCmd = (DrawOpDescr*)drawOpBuf;
drawPixelCmd->size = DRAW_PIXEL_OP_SIZE;
drawPixelCmd->operationType = OP_DRAW_PIXEL;
DrawPixelParams* drawPixelParams = (DrawPixelParams*)drawPixelCmd->opData;
drawPixelParams->x = cmdStruct.args[0];
drawPixelParams->y = cmdStruct.args[1];
drawPixelParams->color = cmdStruct.args[2];
_drawInterface->queueDrawCmd(drawPixelCmd);
}
else if(cmdStruct.nargs == 2)
{
uint32_t pixelColor = _drawInterface->readPixel(cmdStruct.args[0], cmdStruct.args[1]);
int len = snprintf(cmdOut, cmdOutBufferSize, "PX %u %u %06x\n", cmdStruct.args[0], cmdStruct.args[1], pixelColor);
return len;
}
return 0;
}
else if(cmdStruct.cmd == CMD_SIZE)
{
uint32_t width = _drawInterface->getWidth();
uint32_t height = _drawInterface->getHeight();
int len = snprintf(cmdOut, cmdOutBufferSize, "SIZE %u %u\n", width, height);
return len;
}
return 0;
}
bool PixelFlutSource::parseCmd(PixelFlutCmd& cmdStruct, const char* cmd, int cmdInLen)
{
char tokenBuffer[TOKEN_BUFFER_SIZE];
int currentTokenLen = 0;
uint32_t currentTokenIndex = 0;
for(int charIndex = 0; charIndex < cmdInLen; charIndex++)
{
char currentChar = cmd[charIndex];
if((currentChar == ' ') || (currentChar == '\n'))
{
tokenBuffer[currentTokenLen] = '\0';
//LOG("token %d: %s", currentTokenIndex, tokenBuffer);
if(currentTokenIndex == 0)
{
int cmdType = getCmdType(tokenBuffer, currentTokenLen);
if(cmdType == -1)
return false;
cmdStruct.cmd = (PixelFLutCmdType)cmdType;
}
else
{
//Hardcoded argument parsing.
if(cmdStruct.cmd == CMD_PX)
{
switch(currentTokenIndex)
{
case 1:
{
cmdStruct.args[0] = (uint32_t)atoi(tokenBuffer);
break;
}
case 2:
{
cmdStruct.args[1] = (uint32_t)atoi(tokenBuffer);
break;
}
case 3:
{
cmdStruct.args[2] = (uint32_t)strtoul(tokenBuffer, nullptr, 16);
if(currentTokenLen == 6)
{
cmdStruct.args[2] <<= 8;
cmdStruct.args[2] |= 0xff;
}
//else if(currentTokenLen == 8)
//{
//}
break;
}
}
}
}
currentTokenLen = 0;
currentTokenIndex++;
}
else
{
tokenBuffer[currentTokenLen] = currentChar;
currentTokenLen++;
}
}
cmdStruct.nargs = currentTokenIndex - 1;
if(cmdStruct.cmd == CMD_PX)
{
if(!((currentTokenIndex == 4) || (currentTokenIndex == 3)))
return false;
}
else if(cmdStruct.cmd == CMD_SIZE)
{
if(currentTokenIndex != 1)
return false;
}
return true;
}
int PixelFlutSource::getCmdType(const char* cmdStr, int len)
{
if(strncmp(cmdStr, "PX", len) == 0)
return CMD_PX;
else if(strncmp(cmdStr, "SIZE", len) == 0)
return CMD_SIZE;
return -1;
}
| 20.432584 | 117 | 0.654111 | subject721 |
59e44037e24e1c4f559fc44ea4592bc81c6810d1 | 1,084 | cpp | C++ | codes/ZOJ/zoj3810.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/ZOJ/zoj3810.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | codes/ZOJ/zoj3810.cpp | JeraKrs/ACM | edcd61ec6764b8cd804bf1538dfde53d0ff572b5 | [
"Apache-2.0"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 105;
const char s[10][10] = {"BBBBBB", "GGRGRR", "GRRGRB", "GRGGRB", "GRGRRB", "GRGBBB"};
const char c[5] = "BGRY";
int g[maxn][maxn];
void solve (int n) {
memset(g, 0, sizeof(g));
for (int i = 0; i < n; i++)
g[0][i] = 3;
int k = (n - 1) / 2, col = 1;
for (int i = 0; i < k; i++) {
for (int j = 1; j <= i+1; j++)
g[j][i+1] = col;
for (int j = i+1; j < n; j++)
g[j][i] = col;
col = 3 - col;
}
for (int i = k; i < n; i++) {
for (int j = 2; j <= i+2; j++)
g[j][i+2] = col;
g[i+2][i+1] = col;
for (int j = i+2; j < n; j++)
g[j][i] = col;
col = 3 - col;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%c", c[g[i][j]]);
printf("\n");
}
}
int main () {
int cas, n;
scanf("%d", &cas);
while (cas--) {
scanf("%d", &n);
if (n == 1)
printf("B\n");
else if (n == 6) {
for (int i = 0; i < 6; i++)
printf("%s\n", s[i]);
} else if (n >= 5) {
solve(n);
} else
printf("No solution!\n");
}
return 0;
}
| 18.066667 | 84 | 0.447417 | JeraKrs |
59ee4c0a309f914f2733f58643d87bd17c856dd1 | 2,978 | cpp | C++ | sample.cpp | chihirokondo/wl_mpi | 33cb42e6a2649df767d1284c44d3fb11525b423e | [
"MIT"
] | 1 | 2021-03-22T04:19:17.000Z | 2021-03-22T04:19:17.000Z | sample.cpp | chihirokondo/wl_mpi | 33cb42e6a2649df767d1284c44d3fb11525b423e | [
"MIT"
] | null | null | null | sample.cpp | chihirokondo/wl_mpi | 33cb42e6a2649df767d1284c44d3fb11525b423e | [
"MIT"
] | 2 | 2020-11-27T07:40:42.000Z | 2021-03-22T04:58:18.000Z | #include <cmath>
#include <mpi.h>
#include <random>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include "include/wl_mpi.hpp"
// Sample model (classical ferro magnetic ising model)
#include "model_sample/lattice/graph.hpp"
#include "model_sample/ferro_ising.hpp"
int main(int argc, char *argv[]) {
int numprocs, myid, num_walkers_window;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// Check command line arguments.
if (argc != 5) {
if (myid == 0) {
std::cerr
<< "ERROR: Unexpected number of command line arguments!\n"
<< " Expect 6 arguments, " << argc - 1 << " were provided.\n"
<< "Syntax: " << argv[0]
<< " [arg1] [arg2] [arg3] [arg4] \n\n"
<< "Please provide the following command line arguments:\n"
<< "1. Number of walkers per window. [integer]\n"
<< "2. Random number seed. [integer]\n"
<< "3. Time limit (secs). [double]\n"
<< "4. Should execute from the top. [integer (bool)]\n"
<< std::endl;
}
MPI_Abort(MPI_COMM_WORLD, 1);
}
num_walkers_window = atoi(argv[1]);
MPIV mpiv(numprocs, myid, num_walkers_window);
// Model dependent variables.
int dim = 2;
int length = 4;
lattice::graph lat = lattice::graph::simple(dim, length);
FerroIsing model(lat);
HistoEnvManager histo_env(model.ene_min(), model.ene_max(), model.num_bins(),
true);
// Replica exchange Wang-Landau (REWL) parameters.
int check_flatness_every = 500;
double lnf = 1.0;
double lnfmin = 1e-8;
double flatness = 0.95;
double overlap = 0.75; // 0<= overlap <= 1.
int exch_every = 100;
WLParams wl_params(check_flatness_every, lnf, lnfmin, flatness, overlap,
exch_every);
std::mt19937 engine(atoi(argv[2])+mpiv.myid());
// Program control variables.
double timelimit_secs = atof(argv[3]);
bool from_the_top = atoi(argv[4]);
// REWL routine.
std::vector<double> ln_dos;
RunningState running_state = rewl<FerroIsing>(&ln_dos, &model, histo_env,
&wl_params, &mpiv, engine, timelimit_secs, from_the_top);
int result = 0;
if (running_state == RunningState::ERROR) {
result = static_cast<int>(RunningState::ERROR);
}
if ((running_state==RunningState::ALL_FINISHED) && (mpiv.myid()==0)) {
double ln_const = ln_dos[0] - std::log(2.0);
for (auto &ln_dos_i : ln_dos) {
if (ln_dos_i != 0.0) ln_dos_i -= ln_const;
}
std::ofstream ofs("ln_dos_jointed.dat", std::ios::out);
ofs << "# ferro ising model\n";
ofs << "# dim = " << dim << ", length = " << length << "\n";
ofs << "# energy\t # log_e (density of states)\n";
for (size_t i=0; i<ln_dos.size(); ++i) {
ofs << std::scientific << std::setprecision(15)
<< histo_env.GetVal(i, "mid") << "\t" << ln_dos[i] << "\n";
}
ofs << std::endl;
}
MPI_Finalize();
return result;
}
| 35.035294 | 79 | 0.622565 | chihirokondo |
59f1e062f5f292ac68b53ad179fbb1cc65347422 | 2,858 | cpp | C++ | test/TreeJobContainerTest.cpp | ywx217/elapse | d27e851b8f5744ed9bf488a421094c5653aae46e | [
"Unlicense"
] | null | null | null | test/TreeJobContainerTest.cpp | ywx217/elapse | d27e851b8f5744ed9bf488a421094c5653aae46e | [
"Unlicense"
] | null | null | null | test/TreeJobContainerTest.cpp | ywx217/elapse | d27e851b8f5744ed9bf488a421094c5653aae46e | [
"Unlicense"
] | null | null | null | #include "gtest/gtest.h"
#include <list>
#include "TreeJobContainer.hpp"
#ifdef BENCHMARK_ASIO_JOB_CONTAINER
#include "AsioJobContainer.hpp"
#endif
using namespace elapse;
#define TIME_BEGIN 1525436318156L
TEST(TreeContainer, InsertAndExpire) {
TreeJobContainer ctn;
TimeUnit now = TIME_BEGIN;
std::list<JobId> jobSequence;
for (int i = 0; i < 100; ++i, now += 100) {
jobSequence.push_back(ctn.Add(now, WrapLambdaPtr([&jobSequence](JobId id) {
ASSERT_EQ(id, jobSequence.front());
jobSequence.pop_front();
})));
}
now = TIME_BEGIN;
for (int i = 0; i < 10; ++i, now += 100) {
ASSERT_EQ(1, ctn.PopExpires(now));
}
++now;
for (int i = 10; i < 20; ++i, now += 100) {
ASSERT_EQ(1, ctn.PopExpires(now));
}
--now;
now += 100;
for (int i = 20; i < 100; i += 2, now += 200) {
ASSERT_EQ(2, ctn.PopExpires(now));
}
}
TEST(TreeContainer, Remove) {
TreeJobContainer ctn;
auto cb = [](JobId id) {};
auto id_1 = ctn.Add(1, WrapLambdaPtr(cb));
auto id_2 = ctn.Add(2, WrapLambdaPtr(cb));
auto id_3 = ctn.Add(3, WrapLambdaPtr(cb));
auto id_4 = ctn.Add(4, WrapLambdaPtr(cb));
ASSERT_TRUE(ctn.Remove(id_2));
ASSERT_FALSE(ctn.Remove(id_2));
ASSERT_EQ(2, ctn.PopExpires(3));
ASSERT_FALSE(ctn.Remove(id_3));
ASSERT_TRUE(ctn.Remove(id_4));
ASSERT_EQ(0, ctn.PopExpires(1000));
}
TEST(TreeContainer, Iterate) {
TreeJobContainer ctn;
auto cb = [](JobId id) {};
size_t counter = 0;
ctn.Add(1, WrapLambdaPtr(cb));
ctn.Add(2, WrapLambdaPtr(cb));
ctn.Add(3, WrapLambdaPtr(cb));
ctn.Add(4, WrapLambdaPtr(cb));
ctn.IterJobs([&counter](Job const& job) { ++counter; return false; });
ASSERT_EQ(1, counter);
ctn.IterJobs([&counter](Job const& job) { ++counter; return true; });
ASSERT_EQ(5, counter);
}
TEST(TreeContainer, RemoveAll) {
TreeJobContainer ctn;
auto cb = [](JobId id) {};
size_t counter = 0;
ctn.Add(1, WrapLambdaPtr(cb));
ctn.Add(2, WrapLambdaPtr(cb));
ctn.Add(3, WrapLambdaPtr(cb));
ctn.Add(4, WrapLambdaPtr(cb));
ASSERT_EQ(4, ctn.Size());
ctn.RemoveAll();
ASSERT_EQ(0, ctn.Size());
}
TEST(TreeContainer, RemoveIf) {
TreeJobContainer ctn;
auto cb = [](JobId id) {};
size_t counter = 0;
ctn.Add(1, WrapLambdaPtr(cb));
ctn.Add(2, WrapLambdaPtr(cb));
ctn.Add(3, WrapLambdaPtr(cb));
ctn.Add(4, WrapLambdaPtr(cb));
ASSERT_EQ(4, ctn.Size());
ctn.RemoveJobs([](Job const& job) { return job.id_ % 2 == 0; });
ASSERT_EQ(2, ctn.Size());
ctn.RemoveJobs([](Job const& job) { return job.id_ % 2 == 1; });
ASSERT_EQ(0, ctn.Size());
}
#ifdef BENCHMARK_ASIO_JOB_CONTAINER
TEST(Scheduler, BenchTreeJobContainer) {
TreeJobContainer ctn;
ExpireCallback cb = [](JobId id) {};
for (int i = 0; i < 1000000; ++i) {
ctn.Add(i, cb);
}
}
TEST(Scheduler, BenchAsioJobContainer) {
AsioJobContainer ctn;
ExpireCallback cb = [](JobId id) {};
for (int i = 0; i < 1000000; ++i) {
ctn.Add(i, cb);
}
}
#endif
| 24.016807 | 77 | 0.662701 | ywx217 |
59f31757a685dff137d4958a9d55680823e9831d | 9,779 | cpp | C++ | Device/Source/Unit/Datapath/Specific/MPEG/DVDPESStreamUnpacker.cpp | rerunner/STCM_driver | 8fef3dd7327812fd317fdb0e6fab8d36e345a505 | [
"BSD-3-Clause"
] | null | null | null | Device/Source/Unit/Datapath/Specific/MPEG/DVDPESStreamUnpacker.cpp | rerunner/STCM_driver | 8fef3dd7327812fd317fdb0e6fab8d36e345a505 | [
"BSD-3-Clause"
] | null | null | null | Device/Source/Unit/Datapath/Specific/MPEG/DVDPESStreamUnpacker.cpp | rerunner/STCM_driver | 8fef3dd7327812fd317fdb0e6fab8d36e345a505 | [
"BSD-3-Clause"
] | null | null | null | ///
/// @brief Extracts elementary streams from DVD PES streams
///
#include "DVDPESStreamUnpacker.h"
#include "VDR/Source/Construction/IUnitConstruction.h"
#include "Device/Interface/Unit/Video/IMPEGVideoTypes.h"
UNIT_CREATION_FUNCTION(CreateDVDPESStreamUnpackerUnit, DVDPESStreamUnpackerUnit)
STFResult DVDPESStreamUnpackerUnit::CreateVirtual(IVirtualUnit * & unit, IVirtualUnit * parent, IVirtualUnit * root)
{
unit = (IVirtualUnit*)(new VirtualDVDPESStreamUnpackerUnit(this, rangesThreshold));
if (unit)
{
STFRES_REASSERT(unit->Connect(parent, root));
}
else
STFRES_RAISE(STFRES_NOT_ENOUGH_MEMORY);
STFRES_RAISE_OK;
}
STFResult DVDPESStreamUnpackerUnit::Create(uint64 * createParams)
{
if (createParams[0] != PARAMS_DWORD || createParams[2] != PARAMS_DONE)
STFRES_RAISE(STFRES_INVALID_PARAMETERS);
rangesThreshold = createParams[1];
STFRES_RAISE_OK;
}
STFResult DVDPESStreamUnpackerUnit::Connect(uint64 localID, IPhysicalUnit * source)
{
STFRES_RAISE(STFRES_RANGE_VIOLATION);
}
STFResult DVDPESStreamUnpackerUnit::Initialize(uint64 * depUnitsParams)
{
STFRES_RAISE_OK;
}
VirtualDVDPESStreamUnpackerUnit::VirtualDVDPESStreamUnpackerUnit(DVDPESStreamUnpackerUnit * physical, uint32 rangesThreshold)
: VirtualNonthreadedStandardInOutStreamingUnit(physical, 32), streamQueue(32)
{
state = DVDPESS_PARSE_PACKHEADER_0;
outputFormatter.SetRangesThreshold(rangesThreshold);
}
STFResult VirtualDVDPESStreamUnpackerUnit::ParseBeginConfigure(void)
{
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::ParseConfigure(TAG *& tags)
{
while (tags->id)
{
STFRES_REASSERT(outputFormatter.PutTag(*tags));
tags++;
}
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::ParseCompleteConfigure(void)
{
STFRES_REASSERT(outputFormatter.CompleteTags());
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::ParsePESPacket(const VDRDataRange * ranges, uint32 num, uint32 & range, uint32 & offset)
{
uint8 value;
uint8 * pos;
uint32 size = ranges[range].size;
uint32 start, done;
while (range < num)
{
pos = ranges[range].GetStart();
size = ranges[range].size;
start = offset;
while (offset < size)
{
value = pos[offset];
switch (state)
{
case DVDPESS_PARSE_PACKHEADER_0:
if (value == 0x00)
{
state = DVDPESS_PARSE_PACKHEADER_1;
start = offset;
}
else
streamQueue.FlushRanges(this);
offset++;
break;
case DVDPESS_PARSE_PACKHEADER_1:
if (value == 0x00)
{
state = DVDPESS_PARSE_PACKHEADER_2;
}
else
{
state = DVDPESS_PARSE_PACKHEADER_0;
streamQueue.FlushRanges(this);
}
offset++;
break;
case DVDPESS_PARSE_PACKHEADER_2:
if (value == 0x01)
{
state = DVDPESS_PARSE_PACKHEADER_3;
}
else if (value == 0x00)
{
//
// we remain in this state during any size of zero group...
// We just eat byte from the start of the overlap section.
//
if (streamQueue.Size())
{
//
// Oops, we already consumed some ranges...
//
// Remove the start byte from the first overlap range
//
streamQueue.DropBytes(1, done, this);
}
else
{
//
// Remove first byte of this first range
//
start++;
}
}
else
{
state = DVDPESS_PARSE_PACKHEADER_0;
streamQueue.FlushRanges(this);
}
offset++;
break;
case DVDPESS_PARSE_PACKHEADER_3:
if (value == 0xba)
{
state = DVDPESS_PARSE_PAYLOAD;
offset++;
packetSize = 2048 - streamQueue.Size();
}
else
{
state = DVDPESS_PARSE_PACKHEADER_0;
streamQueue.FlushRanges(this);
}
break;
case DVDPESS_PARSE_PAYLOAD:
if (start + packetSize > size)
{
offset = size;
packetSize -= size - start;
}
else
{
streamQueue.AppendRange(VDRSubDataRange(ranges[range], start, packetSize), this);
start += packetSize;
offset = start;
state = DVDPESS_ANALYZE_PACKET;
STFRES_RAISE_OK;
}
break;
default:
break;
}
}
if (start < size && state != DVDPESS_PARSE_PACKHEADER_0)
{
streamQueue.AppendRange(VDRSubDataRange(ranges[range], start, size - start), this);
}
range++;
offset = 0;
}
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::AnalyzePESPacket(void)
{
uint32 headerLength;
uint32 payload, done, extra;
uint8 secondaryID, primaryID;
uint32 pesPacketOffset;
// Attention: it's possible that there is a system header upfront video
pesPacketOffset = 14; // behind pack header
if (streamQueue[pesPacketOffset + 3] == SYSTEM_HEADER_START_CODE) // system header, PES packet behind
{
headerLength = (streamQueue[pesPacketOffset + 4] << 8) + streamQueue[pesPacketOffset + 5];
pesPacketOffset += headerLength + 6; // plus system header
}
primaryID = streamQueue[pesPacketOffset + 3];
headerLength = (uint32)streamQueue[pesPacketOffset + 8] + 9;
if (primaryID == PRIVATE_STREAM_1_ID) // private stream 1
{
secondaryID = streamQueue[pesPacketOffset + headerLength] & 0xf8;
switch (secondaryID)
{
case 0x20:
case 0x28:
case 0x30:
case 0x38:
// subpicture 0x20 - 0x3F
headerLength += 1;
break;
case 0x80:
// ac3 audio
case 0x88:
// dts audio
case 0x90:
// sdds audio
headerLength += 4;
break;
case 0xa0:
// lpcm audio
//headerLength += 7;
// comment the upper line to get the LPCM Private data header
break;
}
}
payload = ((uint32)(streamQueue[pesPacketOffset + 4]) << 8) + (uint32)streamQueue[pesPacketOffset + 5] + 6 - headerLength;
streamQueue.DropBytes(pesPacketOffset + headerLength, done, this);
#if 0
if ((primaryID & 0xf0) == 0xd0)
{
streamQueue.SkipBytes(0, payload, this);
payload = 0;
}
#endif
while ((primaryID & 0xe8) == 0xc0 && payload + 9 < streamQueue.Size())
{
// An MPEG Audio Packet, we have to be extra carefull, to get the extension header with it...
primaryID = streamQueue[payload + 3];
if ((primaryID & 0xe8) == 0xc0)
{
headerLength = (uint32)streamQueue[payload + 8] + 9;
extra = ((uint32)(streamQueue[payload + 4]) << 8) + (uint32)streamQueue[payload + 5] + 6 - headerLength;
streamQueue.SkipBytes(payload, headerLength, this);
payload += extra;
}
#if 0
if ((primaryID & 0xf0) == 0xd0)
{
streamQueue.SkipBytes(payload - extra, extra, this);
payload -= extra;
}
#endif
}
streamQueue.LimitBytes(payload, this);
state = DVDPESS_DELIVER_PACKET;
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::DeliverPESPacket(void)
{
switch (state)
{
case DVDPESS_DELIVER_PACKET:
STFRES_REASSERT(outputFormatter.PutFrameStart());
state = DVDPESS_DELIVER_RANGES;
case DVDPESS_DELIVER_RANGES:
STFRES_REASSERT(streamQueue.SendRanges(&outputFormatter, this));
state = DVDPESS_DELIVER_END_TIME;
case DVDPESS_DELIVER_END_TIME:
if (endTimePending)
{
STFRES_REASSERT(outputFormatter.PutEndTime(endTime));
endTimePending = false;
}
state = DVDPESS_DELIVER_GROUP_END;
case DVDPESS_DELIVER_GROUP_END:
if (groupEndPending)
{
STFRES_REASSERT(outputFormatter.CompleteGroup(groupEndNotification));
groupEndPending = false;
}
#if 0
state = DVDPESS_DELIVER_TAGS;
case DVDPESS_DELIVER_TAGS:
while (numSentTags < numPendingTags)
{
STFRES_REASSERT(outputFormatter.PutTag(pendingTags[numSentTags]));
numSentTags++;
}
#endif
state = DVDPESS_DELIVER_GROUP_START;
case DVDPESS_DELIVER_GROUP_START:
if (groupStartPending)
{
STFRES_REASSERT(outputFormatter.BeginGroup(groupNumber, groupStartNotification, singleUnitGroup));
groupStartPending = false;
}
state = DVDPESS_DELIVER_START_TIME;
case DVDPESS_DELIVER_START_TIME:
if (startTimePending)
{
STFRES_REASSERT(outputFormatter.PutStartTime(startTime));
startTimePending = false;
}
state = DVDPESS_PARSE_PACKHEADER_0;
default:
break;
}
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::ParseRanges(const VDRDataRange * ranges, uint32 num, uint32 & range, uint32 & offset)
{
STFRES_REASSERT(this->DeliverPESPacket());
while (range < num)
{
// Only call ParseFrame if we are in the parsing state.
if (state < DVDPESS_ANALYZE_PACKET)
STFRES_REASSERT(this->ParsePESPacket(ranges, num, range, offset));
if (state == DVDPESS_ANALYZE_PACKET)
STFRES_REASSERT(this->AnalyzePESPacket());
STFRES_REASSERT(this->DeliverPESPacket());
}
STFRES_RAISE_OK;
}
STFResult VirtualDVDPESStreamUnpackerUnit::ResetParser(void)
{
if (state < DVDPESS_ANALYZE_PACKET)
{
streamQueue.FlushRanges(this);
state = DVDPESS_PARSE_PACKHEADER_0;
}
STFRES_RAISE(VirtualNonthreadedStandardInOutStreamingUnit::ResetParser());
}
STFResult VirtualDVDPESStreamUnpackerUnit::ResetInputProcessing(void)
{
if (state < DVDPESS_ANALYZE_PACKET)
{
streamQueue.FlushRanges(this);
state = DVDPESS_PARSE_PACKHEADER_0;
}
STFRES_RAISE(VirtualNonthreadedStandardInOutStreamingUnit::ResetParser());
}
STFResult VirtualDVDPESStreamUnpackerUnit::ProcessFlushing(void)
{
streamQueue.FlushRanges(this);
outputFormatter.Flush();
state = DVDPESS_PARSE_PACKHEADER_0;
STFRES_RAISE(VirtualNonthreadedStandardInOutStreamingUnit::ProcessFlushing());
}
bool VirtualDVDPESStreamUnpackerUnit::InputPending(void)
{
return state != DVDPESS_PARSE_PACKHEADER_0;
}
#if _DEBUG
STFString VirtualDVDPESStreamUnpackerUnit::GetInformation(void)
{
return STFString("DVDPESStreamUnpacker ") + STFString(physical->GetUnitID(), 8, 16);
}
#endif
| 23.063679 | 131 | 0.698026 | rerunner |
59f3ff47a06e15d1581749eae11fe190c52bfd6a | 2,236 | cpp | C++ | main.cpp | azriel91/sl_ax_main | fd34e4b27da35fdf18afcad1dfc11e36d2504545 | [
"Apache-2.0"
] | null | null | null | main.cpp | azriel91/sl_ax_main | fd34e4b27da35fdf18afcad1dfc11e36d2504545 | [
"Apache-2.0"
] | null | null | null | main.cpp | azriel91/sl_ax_main | fd34e4b27da35fdf18afcad1dfc11e36d2504545 | [
"Apache-2.0"
] | null | null | null | /*=============================================================================
Library: Silver
Copyright (c) Azriel Hoh
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 <cstdio>
#include <azriel/cppmicroservices/core/include/usGetModuleContext.h>
#include <azriel/sl_ax_engine/AutexousiousService.h>
US_USE_NAMESPACE
#ifndef US_BUILD_SHARED_LIBS
#include <azriel/cppmicroservices/core/include/usModuleImport.h>
US_IMPORT_MODULE(CppMicroServices)
US_IMPORT_MODULE(sl_core_application)
US_IMPORT_MODULE(sl_ax_engine)
US_IMPORT_MODULE(sl_ax_main)
#endif
#include "sl_ax_main/Block.h"
#include "Activator.h"
int main(int argc, char const *argv[]) {
printf(" === Auto load dirs ===\n");
auto autoLoadPaths = ModuleSettings::GetAutoLoadPaths();
for (auto path : autoLoadPaths) {
printf("auto load: %s\n", path.c_str());
}
printf("\n");
printf(" === Module Locations ===\n");
ModuleContext* mc = GetModuleContext();
auto modules = mc->GetModules();
for (auto module : modules) {
printf("%s: %s\n", module->GetName().c_str(), module->GetLocation().c_str());
}
printf("\n");
printf(" === Module Properties ===\n");
for (auto module : modules) {
printf(" == %s\n ==", module->GetName().c_str());
printf(" module.autoload_dir: %s\n", module->GetProperty("module.autoload_dir").ToString().c_str());
}
auto axServiceReferenceU = mc->GetServiceReference("sl::ax::engine::AutexousiousService");
auto axServiceMap = mc->GetService(axServiceReferenceU);
auto axService = (sl::ax::engine::AutexousiousService*) axServiceMap["sl::ax::engine::AutexousiousService"];
return axService->runApplication("sl::ax::engine::StartupActivity");
}
| 33.878788 | 109 | 0.68381 | azriel91 |
59f7427b059068377b3be5224e852a778e88a537 | 14,750 | cpp | C++ | demo/Whole-App-Acceleration/SORT/src/main.cpp | luyufan498/Vitis-AI-ZH | 262fd6e29f25ec3b7583cbde5405f5ddeb29f2d5 | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | demo/Whole-App-Acceleration/SORT/src/main.cpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | demo/Whole-App-Acceleration/SORT/src/main.cpp | wangyifan778/Vitis-AI | f61061eef7550d98bf02a171604c9a9f283a7c47 | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | ///////////////////////////////////////////////////////////////////////////////
// SORT: A Simple, Online and Realtime Tracker
//
// This is a C++ reimplementation of the open source tracker in
// https://github.com/abewley/sort
// Based on the work of Alex Bewley, [email protected], 2016
//
// Cong Ma, [email protected], 2016
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <fstream>
#include <iomanip> // to format image names using setw() and setfill()
// #include <io.h> // to check file existence using POSIX function access(). On Linux include <unistd.h>.
#include <unistd.h>
#include <set>
#include "Hungarian.h"
#include "KalmanTracker.h"
#include "opencv2/video/tracking.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "profiling.hpp"
#include "kf_xrt/kf_wrapper.h"
using namespace std;
using namespace cv;
using namespace vitis::ai;
typedef struct TrackingBox
{
int frame;
int id;
Rect_<float> box;
} TrackingBox;
// Computes IOU between two bounding boxes
double GetIOU(Rect_<float> bb_test, Rect_<float> bb_gt)
{
float in = (bb_test & bb_gt).area();
float un = bb_test.area() + bb_gt.area() - in;
if (un < DBL_EPSILON)
return 0;
return (double)(in / un);
}
// global variables for counting
int total_frames = 0;
double total_time = 0.0;
// global hardware KF accelerator enable
bool hw_kf_en;
void TestSORT(string inputDir, bool display);
int main(int argc, char **argv)
{
if (argc != 3) {
std::cout << "Usage: .exe <inputDir> <waa en>" << std::endl;
}
const std::string inputDir = argv[1];
if(atoi(argv[2])==0)
hw_kf_en = 0;
else
hw_kf_en = 1;
TestSORT(inputDir, false);
// Note: time counted here is of tracking procedure, while the running speed bottleneck is opening and parsing detectionFile.
cout << "Total Tracking took: " << total_time << " for " << total_frames << " frames or " << ((double)total_frames / (double)total_time) << " FPS" << endl;
return 0;
}
//global buffer for states and covariances
float* states_in_global = (float*)malloc(500 * 7* sizeof(float));
float* covariances_in_global = (float*)malloc(500 * 7 * 7* sizeof(float));
float* covariancesD_in_global = (float*)malloc(500 * 7* sizeof(float));
float* states_out_global = (float*)malloc(500 * 7* sizeof(float));
float* covariances_out_global = (float*)malloc(500 * 7 * 7* sizeof(float));
float* covariancesD_out_global = (float*)malloc(500 * 7* sizeof(float));
float* measurements_global = (float*)malloc(500 * 4* sizeof(float));
void sw_predict(cv::KalmanFilter kf_sw, size_t num_kf)
{
for(int n=0;n<num_kf;n++)
{
for (int i = 0; i < 7; i++) {
kf_sw.statePost.at<float>(i) = states_in_global[i+7*n];
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
kf_sw.errorCovPost.at<float>(i, j) = covariances_in_global[j + i*7 + 7*7*n];
}
}
kf_sw.predict();
for (int i = 0; i < 7; i++) {
states_out_global[i+7*n] = kf_sw.statePre.at<float>(i);
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
covariances_out_global[j + i*7 + 7*7*n] = kf_sw.errorCovPre.at<float>(i, j) ;
}
}
}
}
void sw_correct(cv::KalmanFilter kf_sw, size_t num_kf)
{
for(int n=0;n<num_kf;n++)
{
cv::Mat meas(4, 1, CV_32FC1);
for (int i = 0; i < 4; i++) {
meas.at<float>(i) = measurements_global[i+4*n];
}
for (int i = 0; i < 7; i++) {
kf_sw.statePre.at<float>(i) = states_in_global[i+7*n];
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
kf_sw.errorCovPre.at<float>(i, j) = covariances_in_global[j + i*7 + 7*7*n];
}
}
kf_sw.correct(meas);
for (int i = 0; i < 7; i++) {
states_out_global[i+7*n] = kf_sw.statePost.at<float>(i);
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
covariances_out_global[j + i*7 + 7*7*n] = kf_sw.errorCovPost.at<float>(i, j) ;
}
}
}
}
void predict(KFMOT kf_fpga, cv::KalmanFilter kf_sw, std::vector<KalmanTracker>& trackers) {
for (size_t idx = 0; idx < trackers.size(); idx++) {
auto &tracker = trackers[idx];
memcpy(states_in_global+(idx*7), tracker.getState().data, 7*sizeof(float));
memcpy(covariances_in_global+(idx*7*7), tracker.getErrorCov().data,
7*7*sizeof(float));
memcpy(covariancesD_in_global+(idx*7), tracker.getErrorCovD().data,
7*sizeof(float));
tracker.m_age += 1;
if (tracker.m_time_since_update > 0)
tracker.m_hit_streak = 0;
tracker.m_time_since_update += 1;
}
if(hw_kf_en==1)
kf_fpga.kalmanfilter_predict( (int)trackers.size(), states_in_global, covariances_in_global, covariancesD_in_global,
states_out_global, covariances_out_global, covariancesD_out_global);
else
sw_predict(kf_sw, trackers.size());
unsigned idx = 0;
for (auto it = trackers.begin(); it != trackers.end();) {
it->setState(states_out_global+idx*7);
auto Rect = it->getRect();
if (Rect.x >= 0 && Rect.y >= 0) {
it->setErrorCov(covariances_out_global+idx*7*7);
it->setErrorCovD(covariancesD_out_global+idx*7);
it++;
}
// Else remove tracker
else {
it = trackers.erase(it);
}
idx++;
}
}
void update(KFMOT kf_fpga, cv::KalmanFilter kf_sw, vector<KalmanTracker> &trackers, vector<TrackingBox> &detections,
vector<cv::Point>& matchedPairs) {
for (size_t idx = 0; idx < matchedPairs.size(); idx++) {
auto &tracker = trackers[matchedPairs[idx].x];
auto &detection = detections[matchedPairs[idx].y];
memcpy(states_in_global+(idx*7), tracker.getState().data, 7*sizeof(float));
memcpy(covariances_in_global+(idx*7*7), tracker.getErrorCov().data,
7*7*sizeof(float));
memcpy(covariancesD_in_global+(idx*7), tracker.getErrorCovD().data,
7*sizeof(float));
*(measurements_global+(idx*4)) = detection.box.x + detection.box.width / 2;
*(measurements_global+(idx*4)+1) = detection.box.y + detection.box.height / 2;
*(measurements_global+(idx*4)+2) = detection.box.area();
*(measurements_global+(idx*4)+3) = detection.box.width / detection.box.height;
tracker.m_time_since_update = 0;
tracker.m_hits += 1;
tracker.m_hit_streak += 1;
}
if(hw_kf_en==1)
kf_fpga.kalmanfilter_correct(matchedPairs.size(), states_in_global, covariances_in_global, covariancesD_in_global, measurements_global,
states_out_global, covariances_out_global, covariancesD_out_global);
else
sw_correct(kf_sw, matchedPairs.size());
int idx = 0;
for (auto matchedPair : matchedPairs) {
auto &tracker = trackers[matchedPair.x];
tracker.setState(states_out_global+idx*7);
tracker.setErrorCov(covariances_out_global+idx*7*7);
tracker.setErrorCovD(covariancesD_out_global+idx*7);
idx++;
}
}
void TestSORT(string inputDir, bool display)
{
cout << "Processing " << inputDir << "..." << endl;
// 1. read detection file
ifstream detectionFile;
string detFileName = inputDir + "/det/det.txt";
detectionFile.open(detFileName);
if (!detectionFile.is_open())
{
cerr << "Error: can not find file " << detFileName << endl;
return;
}
string detLine;
istringstream ss;
vector<TrackingBox> detData;
char ch;
float tpx, tpy, tpw, tph;
while ( getline(detectionFile, detLine) )
{
TrackingBox tb;
ss.str(detLine);
ss >> tb.frame >> ch >> tb.id >> ch;
ss >> tpx >> ch >> tpy >> ch >> tpw >> ch >> tph;
ss.str("");
tb.box = Rect_<float>(Point_<float>(tpx, tpy), Point_<float>(tpx + tpw, tpy + tph));
detData.push_back(tb);
}
detectionFile.close();
// 2. group detData by frame
int maxFrame = 0;
for (auto tb : detData) // find max frame number
{
if (maxFrame < tb.frame)
maxFrame = tb.frame;
}
vector<vector<TrackingBox>> detFrameData;
vector<TrackingBox> tempVec;
for (int fi = 0; fi < maxFrame; fi++)
{
for (auto tb : detData)
if (tb.frame == fi + 1) // frame num starts from 1
tempVec.push_back(tb);
detFrameData.push_back(tempVec);
tempVec.clear();
}
// 3. update across frames
int frame_count = 0;
int max_age = 30;
int min_hits = 3;
double iouThreshold = 0.7;
vector<KalmanTracker> trackers;
KalmanTracker::kf_count = 0; // tracking id relies on this, so we have to reset it in each seq.
// variables used in the for-loop
vector<vector<double>> iouMatrix;
vector<int> assignment;
set<int> unmatchedDetections;
set<int> unmatchedTrajectories;
set<int> allDetections;
set<int> matchedDetections;
vector<cv::Point> matchedPairs;
vector<TrackingBox> frameTrackingResult;
unsigned int trkNum = 0;
unsigned int detNum = 0;
double cycle_time = 0.0;
int64 start_time = 0;
// prepare result file.
ofstream resultsFile;
string resFileName = "output.txt";
resultsFile.open(resFileName);
if (!resultsFile.is_open())
{
cerr << "Error: can not create file " << resFileName << endl;
return;
}
KFMOT kf_fpga;
cv::KalmanFilter kf_sw;
if(hw_kf_en==1)
{
kf_fpga.kalmanfilter_init("/media/sd-mmcblk0p1/krnl_kalmanfilter.xclbin",
"kalmanfilter_accel",
0);
}
else
{
int stateNum = 7;
int measureNum = 4;
kf_sw = KalmanFilter(stateNum, measureNum, 0);
kf_sw.transitionMatrix = (Mat_<float>(stateNum, stateNum) <<
1, 0, 0, 0, 1, 0, 0,
0, 1, 0, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0, 1,
0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1);
setIdentity(kf_sw.measurementMatrix);
setIdentity(kf_sw.processNoiseCov, Scalar::all(1e-2));
setIdentity(kf_sw.measurementNoiseCov, Scalar::all(1e-1));
}
//////////////////////////////////////////////
// main loop
for (int fi = 0; fi < maxFrame; fi++)
{
total_frames++;
frame_count++;
start_time = getTickCount();
if (trackers.size() == 0) // the first frame met
{
trackers.reserve(detFrameData[fi].size());
// initialize kalman trackers using first detections.
// __TIC_SUM__(INITIALISE);
for (unsigned int i = 0; i < detFrameData[fi].size(); i++)
{
trackers.emplace_back(detFrameData[fi][i].box);
}
// __TOC_SUM__(INITIALISE);
// output the first frame detections
for (unsigned int id = 0; id < detFrameData[fi].size(); id++)
{
TrackingBox tb = detFrameData[fi][id];
resultsFile << tb.frame << "," << id + 1 << "," << tb.box.x << "," << tb.box.y << "," << tb.box.width << "," << tb.box.height << ",1,-1,-1,-1" << endl;
}
continue;
}
///////////////////////////////////////
// 3.1. get predicted locations from existing trackers.
// __TIC_SUM__(PREDICT);
predict(kf_fpga, kf_sw, trackers);
// __TOC_SUM__(PREDICT);
///////////////////////////////////////
// 3.2. associate detections to tracked object (both represented as bounding boxes)
// dets : detFrameData[fi]
trkNum = trackers.size();
detNum = detFrameData[fi].size();
iouMatrix.clear();
iouMatrix.resize(trkNum, vector<double>(detNum, 0));
// __TIC_SUM__(IOU);
for (unsigned int i = 0; i < trkNum; i++) // compute iou matrix as a distance matrix
{
auto rect = trackers[i].getRect();
for (unsigned int j = 0; j < detNum; j++)
{
// use 1-iou because the hungarian algorithm computes a minimum-cost assignment.
iouMatrix[i][j] = 1 - GetIOU(rect, detFrameData[fi][j].box);
}
}
// __TOC_SUM__(IOU);
// solve the assignment problem using hungarian algorithm.
// the resulting assignment is [track(prediction) : detection], with len=preNum
HungarianAlgorithm HungAlgo;
assignment.clear();
// __TIC_SUM__(HUNGARIAN);
HungAlgo.Solve(iouMatrix, assignment);
// __TOC_SUM__(HUNGARIAN);
// find matches, unmatched_detections and unmatched_predictions
// filter out matched with low IOU
unmatchedTrajectories.clear();
unmatchedDetections.clear();
allDetections.clear();
matchedDetections.clear();
matchedPairs.clear();
// __TIC_SUM__(IOU_THRESHOLD);
for (unsigned int n = 0; n < detNum; n++)
allDetections.insert(n);
for (unsigned int i = 0; i < trkNum; ++i) {
if (assignment[i] == -1)
unmatchedTrajectories.insert(i);
else if (1 - iouMatrix[i][assignment[i]] < iouThreshold) {
unmatchedTrajectories.insert(i);
unmatchedDetections.insert(assignment[i]);
}
else {
matchedDetections.insert(assignment[i]);
matchedPairs.emplace_back(i, assignment[i]);
}
}
set_difference(allDetections.begin(), allDetections.end(),
matchedDetections.begin(), matchedDetections.end(),
insert_iterator<set<int>>(unmatchedDetections, unmatchedDetections.begin()));
// __TOC_SUM__(IOU_THRESHOLD);
///////////////////////////////////////
// 3.3. updating trackers
// update matched trackers with assigned detections.
// each prediction is corresponding to a tracker
int detIdx, trkIdx;
// __TIC_SUM__(UPDATE);
int detIdx2, trkIdx2;
for (unsigned int i = 0; i < matchedPairs.size(); i++)
{
trkIdx2 = matchedPairs[i].x;
detIdx2 = matchedPairs[i].y;
}
update(kf_fpga, kf_sw, trackers, detFrameData[fi], matchedPairs);
// __TOC_SUM__(UPDATE);
// create and initialise new trackers for unmatched detections
// __TIC_SUM__(INITIALISE_NEW);
for (auto umd : unmatchedDetections)
{
KalmanTracker tracker = KalmanTracker(detFrameData[fi][umd].box);
trackers.push_back(tracker);
}
// __TOC_SUM__(INITIALISE_NEW);
// get trackers' output
frameTrackingResult.clear();
for (auto it = trackers.begin(); it != trackers.end();)
{
if (((*it).m_time_since_update < 1) &&
((*it).m_hit_streak >= min_hits || frame_count <= min_hits))
{
TrackingBox res;
res.box = (*it).getRect();
res.id = (*it).m_id + 1;
res.frame = frame_count;
frameTrackingResult.push_back(res);
it++;
}
else
it++;
// remove dead tracklet
if (it != trackers.end() && (*it).m_time_since_update > max_age)
it = trackers.erase(it);
}
cycle_time = (double)(getTickCount() - start_time);
total_time += cycle_time / getTickFrequency();
for (auto tb : frameTrackingResult)
resultsFile << tb.frame << "," << tb.id << "," << tb.box.x << "," << tb.box.y << "," << tb.box.width << "," << tb.box.height << ",1,-1,-1,-1" << endl;
}
resultsFile.close();
}
| 28.640777 | 156 | 0.647051 | luyufan498 |
59f7a965e8cc6205cfba71b5f7957c7c290d94ea | 3,224 | cpp | C++ | RayEngine/Source/Vulkan/VulkRootLayout.cpp | Mumsfilibaba/RayEngine | 68496966c1d7b91bc8fbdd305226ece9b9f596b2 | [
"Apache-2.0"
] | null | null | null | RayEngine/Source/Vulkan/VulkRootLayout.cpp | Mumsfilibaba/RayEngine | 68496966c1d7b91bc8fbdd305226ece9b9f596b2 | [
"Apache-2.0"
] | null | null | null | RayEngine/Source/Vulkan/VulkRootLayout.cpp | Mumsfilibaba/RayEngine | 68496966c1d7b91bc8fbdd305226ece9b9f596b2 | [
"Apache-2.0"
] | null | null | null | /*////////////////////////////////////////////////////////////
Copyright 2018 Alexander Dahlin
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
THIS SOFTWARE IS PROVIDED "AS IS". MEANING NO WARRANTY
OR SUPPORT IS PROVIDED OF ANY KIND.
In event of any damages, direct or indirect that can
be traced back to the use of this software, shall no
contributor be held liable. This includes computer
failure and or malfunction of any kind.
////////////////////////////////////////////////////////////*/
#include <RayEngine.h>
#include <Vulkan/VulkDevice.h>
#include <Vulkan/VulkRootLayout.h>
namespace RayEngine
{
namespace Graphics
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VulkRootLayout::VulkRootLayout(IDevice* pDevice, const RootLayoutDesc* pDesc)
: m_Device(nullptr),
m_Layout(VK_NULL_HANDLE),
m_Desc(),
m_References(0)
{
AddRef();
m_Device = pDevice->QueryReference<VulkDevice>();
Create(pDevice, pDesc);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
VulkRootLayout::~VulkRootLayout()
{
if (m_Layout != VK_NULL_HANDLE)
{
VkDevice vkDevice = reinterpret_cast<VulkDevice*>(m_Device)->GetVkDevice();
vkDestroyPipelineLayout(vkDevice, m_Layout, nullptr);
m_Layout = VK_NULL_HANDLE;
}
ReRelease_S(m_Device);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void VulkRootLayout::GetDesc(RootLayoutDesc * pDesc) const
{
*pDesc = m_Desc;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CounterType VulkRootLayout::Release()
{
CounterType counter = --m_References;
if (m_References < 1)
delete this;
return counter;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CounterType VulkRootLayout::AddRef()
{
return ++m_References;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void VulkRootLayout::Create(IDevice* pDevice, const RootLayoutDesc* pDesc)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.pNext = nullptr;
pipelineLayoutInfo.flags = 0;
pipelineLayoutInfo.setLayoutCount = 0;
pipelineLayoutInfo.pSetLayouts = nullptr;
pipelineLayoutInfo.pushConstantRangeCount = 0;
pipelineLayoutInfo.pPushConstantRanges = nullptr;
VkDevice vkDevice = reinterpret_cast<VulkDevice*>(pDevice)->GetVkDevice();
VkResult result = vkCreatePipelineLayout(vkDevice, &pipelineLayoutInfo, nullptr, &m_Layout);
if (result != VK_SUCCESS)
{
LOG_ERROR("Vulkan: Could not create pipelinelayout");
}
else
{
m_Desc = *pDesc;
}
}
}
} | 29.577982 | 124 | 0.531638 | Mumsfilibaba |
59fe4ef528bb118d9b1ea046656b122e246b842b | 1,852 | hpp | C++ | src/BayesDecider.hpp | Nolnocn/Bayesian-Inference | 76ee29171c6e3a4a69b752c1f68ae3fef2526f92 | [
"MIT"
] | 1 | 2021-07-07T02:45:55.000Z | 2021-07-07T02:45:55.000Z | src/BayesDecider.hpp | Nolnocn/Bayes-Classifier | 76ee29171c6e3a4a69b752c1f68ae3fef2526f92 | [
"MIT"
] | null | null | null | src/BayesDecider.hpp | Nolnocn/Bayes-Classifier | 76ee29171c6e3a4a69b752c1f68ae3fef2526f92 | [
"MIT"
] | null | null | null |
#ifndef BayesDecider_hpp
#define BayesDecider_hpp
#include <string>
#include "BayesOutcomeDefs.h"
namespace Bayes
{
// Forward dec
struct BayesObservation;
/*
* Class used to store conditions and decide on observations
*
* Only this class and BayesObservation should be used
* outside the Bayes namespace
*/
class BayesDecider
{
public:
BayesDecider( const std::string& actionName );
~BayesDecider();
// Public interface to add conditions to the decider
// TODO: "Lock" decider before use so new conditions cannot be added
void addContinuousCondition( const std::string& conditionName );
void addDiscreteCondition( const std::string& conditionName, uint32_t numValues = 2 );
// Adds an observation to the saved observations
void addObservation( const BayesObservation& obs );
// Builds data for conditions from observations
void buildStats();
// Does some Bayesian magic with the given observation
// and returns whether or not the action should be performed
bool decide( const BayesObservation& obs ) const;
// Prints data from conditions and action to console
void printData() const;
// Prints all saved observations to the console
void printObservations() const;
private:
struct Impl; // Using the PIML idiom to avoid including every other Bayes class
static const double SQRT2PI; // constant cached for convenience
// Internal functions used to perform aforementioned Bayesian magic
double calculateBayes( const BayesObservation& obs, OutcomeType outcome ) const;
double calculateGaussianDistribution( double mean, double stdDev, int x ) const;
// Checks that an observation has the same number of values as there are conditions
bool validateObservation( const BayesObservation& obs ) const;
Impl* pImpl;
};
}
#endif /* BayesDecider_hpp */
| 28.9375 | 88 | 0.74568 | Nolnocn |
94017194841b6d01072880d0bc250e49e5d54fab | 7,314 | cpp | C++ | ManagedScripts/MPhysClassMultiListClass.cpp | mpforums/RenSharp | 5b3fb8bff2a1772a82a4148bcf3e1265a11aa097 | [
"Apache-2.0"
] | 1 | 2021-10-04T02:34:33.000Z | 2021-10-04T02:34:33.000Z | ManagedScripts/MPhysClassMultiListClass.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 9 | 2019-07-03T19:19:59.000Z | 2020-03-02T22:00:21.000Z | ManagedScripts/MPhysClassMultiListClass.cpp | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 2 | 2019-08-14T08:37:36.000Z | 2020-09-29T06:44:26.000Z | /*
Copyright 2020 Neijwiert
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 "stdafx.h"
#include "MPhysClassMultiListClass.h"
#include "Imports.h"
#include "UnmanagedContainer.h"
namespace RenSharp
{
PhysClassMultiListClass::PhysClassMultiListClass()
: MultiListClass<IPhysClass ^>(IntPtr(Imports::CreatePhysClassMultiListClass()))
{
}
PhysClassMultiListClass::PhysClassMultiListClass(IntPtr pointer)
: MultiListClass<IPhysClass ^>(pointer)
{
}
IUnmanagedContainer<IMultiListClass<IPhysClass ^> ^> ^PhysClassMultiListClass::CreatePhysClassMultiListClass()
{
return gcnew UnmanagedContainer<IMultiListClass<IPhysClass ^> ^>(gcnew PhysClassMultiListClass());
}
bool PhysClassMultiListClass::Contains(IPhysClass ^obj)
{
return GenericContains(obj);
}
bool PhysClassMultiListClass::Add(IPhysClass ^obj, bool onlyOnce)
{
if (obj == nullptr || obj->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("obj");
}
return InternalPhysClassMultiListClassPointer->Add(
reinterpret_cast<::PhysClass *>(obj->PhysClassPointer.ToPointer()),
onlyOnce);
}
bool PhysClassMultiListClass::AddTail(IPhysClass ^obj, bool onlyOnce)
{
if (obj == nullptr || obj->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("obj");
}
return InternalPhysClassMultiListClassPointer->Add_Tail(
reinterpret_cast<::PhysClass *>(obj->PhysClassPointer.ToPointer()),
onlyOnce);
}
bool PhysClassMultiListClass::AddTail(IPhysClass ^obj)
{
if (obj == nullptr || obj->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("obj");
}
return InternalPhysClassMultiListClassPointer->Add_Tail(
reinterpret_cast<::PhysClass *>(obj->PhysClassPointer.ToPointer()));
}
bool PhysClassMultiListClass::AddAfter(IPhysClass ^obj, IPhysClass ^existingListMember, bool onlyOnce)
{
if (obj == nullptr || obj->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("obj");
}
else if (existingListMember == nullptr || existingListMember->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("existingListMember");
}
return InternalPhysClassMultiListClassPointer->Add_After(
reinterpret_cast<::PhysClass *>(obj->PhysClassPointer.ToPointer()),
reinterpret_cast<::PhysClass *>(existingListMember->PhysClassPointer.ToPointer()),
onlyOnce);
}
bool PhysClassMultiListClass::AddAfter(IPhysClass ^obj, IPhysClass ^existingListMember)
{
if (obj == nullptr || obj->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("obj");
}
else if (existingListMember == nullptr || existingListMember->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("existingListMember");
}
return InternalPhysClassMultiListClassPointer->Add_After(
reinterpret_cast<::PhysClass *>(obj->PhysClassPointer.ToPointer()),
reinterpret_cast<::PhysClass *>(existingListMember->PhysClassPointer.ToPointer()));
}
IPhysClass ^PhysClassMultiListClass::GetHead()
{
auto result = InternalPhysClassMultiListClassPointer->Get_Head();
if (result == nullptr)
{
return nullptr;
}
else
{
return PhysClass::CreatePhysClassWrapper(result);
}
}
IPhysClass ^PhysClassMultiListClass::PeekHead()
{
auto result = InternalPhysClassMultiListClassPointer->Peek_Head();
if (result == nullptr)
{
return nullptr;
}
else
{
return PhysClass::CreatePhysClassWrapper(result);
}
}
IPhysClass ^PhysClassMultiListClass::RemoveHead()
{
auto result = InternalPhysClassMultiListClassPointer->Remove_Head();
if (result == nullptr)
{
return nullptr;
}
else
{
return PhysClass::CreatePhysClassWrapper(result);
}
}
void PhysClassMultiListClass::ResetList()
{
InternalPhysClassMultiListClassPointer->Reset_List();
}
bool PhysClassMultiListClass::Remove(IPhysClass ^item)
{
if (item == nullptr || item->PhysClassPointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("item");
}
return InternalPhysClassMultiListClassPointer->Remove(
reinterpret_cast<::PhysClass *>(item->PhysClassPointer.ToPointer()));
}
IntPtr PhysClassMultiListClass::PhysClassMultiListClassPointer::get()
{
return IntPtr(InternalPhysClassMultiListClassPointer);
}
IUnmanagedContainer<IMultiListIterator<IPhysClass ^> ^> ^PhysClassMultiListClass::Iterator::get()
{
return PhysClassMultiListIterator::CreatePhysClassMultiListIterator(this);
}
bool PhysClassMultiListClass::InternalDestroyPointer()
{
Imports::DestroyPhysClassMultiListClass(InternalPhysClassMultiListClassPointer);
Pointer = IntPtr::Zero;
return true;
}
::MultiListClass<::PhysClass> *PhysClassMultiListClass::InternalPhysClassMultiListClassPointer::get()
{
return reinterpret_cast<::MultiListClass<::PhysClass> *>(Pointer.ToPointer());
}
PhysClassMultiListIterator::PhysClassMultiListIterator(IMultiListClass<IPhysClass ^> ^list)
{
if (list == nullptr || list->Pointer.ToPointer() == nullptr)
{
throw gcnew ArgumentNullException("list");
}
Pointer = IntPtr(Imports::CreatePhysClassMultiListIterator(
reinterpret_cast<::MultiListClass<::PhysClass> *>(list->Pointer.ToPointer())));
}
PhysClassMultiListIterator::PhysClassMultiListIterator(IntPtr pointer)
: MultiListIterator<IPhysClass ^>(pointer)
{
}
IUnmanagedContainer<IMultiListIterator<IPhysClass ^> ^> ^PhysClassMultiListIterator::CreatePhysClassMultiListIterator(
IMultiListClass<IPhysClass ^> ^list)
{
return gcnew UnmanagedContainer<IMultiListIterator<IPhysClass ^> ^>(gcnew PhysClassMultiListIterator(list));
}
IPhysClass ^PhysClassMultiListIterator::GetObj()
{
auto result = InternalPhysClassMultiListIteratorPointer->Get_Obj();
if (result == nullptr)
{
return nullptr;
}
else
{
return PhysClass::CreatePhysClassWrapper(result);
}
}
IPhysClass ^PhysClassMultiListIterator::PeekObj()
{
auto result = InternalPhysClassMultiListIteratorPointer->Peek_Obj();
if (result == nullptr)
{
return nullptr;
}
else
{
return PhysClass::CreatePhysClassWrapper(result);
}
}
void PhysClassMultiListIterator::RemoveCurrentObject()
{
InternalPhysClassMultiListIteratorPointer->Remove_Current_Object();
}
IntPtr PhysClassMultiListIterator::PhysClassMultiListIteratorPointer::get()
{
return IntPtr(InternalPhysClassMultiListIteratorPointer);
}
bool PhysClassMultiListIterator::InternalDestroyPointer()
{
Imports::DestroyPhysClassMultiListIterator(InternalPhysClassMultiListIteratorPointer);
Pointer = IntPtr::Zero;
return true;
}
::MultiListIterator<::PhysClass> *PhysClassMultiListIterator::InternalPhysClassMultiListIteratorPointer::get()
{
return reinterpret_cast<::MultiListIterator<::PhysClass> *>(Pointer.ToPointer());
}
} | 27.704545 | 119 | 0.760459 | mpforums |
9404cada7abb85c24fb038250bb09f642ac913b9 | 2,207 | cpp | C++ | EZOJ/Contests/1465/A.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 6 | 2019-09-30T16:11:00.000Z | 2021-11-01T11:42:33.000Z | EZOJ/Contests/1465/A.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-11-21T08:17:42.000Z | 2020-07-28T12:09:52.000Z | EZOJ/Contests/1465/A.cpp | sshockwave/Online-Judge-Solutions | 9d0bc7fd68c3d1f661622929c1cb3752601881d3 | [
"MIT"
] | 4 | 2017-07-26T05:54:06.000Z | 2020-09-30T13:35:38.000Z | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cctype>
using namespace std;
typedef long long lint;
#define cout cerr
#define ni (next_num<int>())
template<class T>inline T next_num(){
T i=0;char c;
while(!isdigit(c=getchar())&&c!='-');
bool neg=c=='-';
neg?c=getchar():0;
while(i=i*10-'0'+c,isdigit(c=getchar()));
return neg?-i:i;
}
template<class T1,class T2>inline void apmax(T1 &a,const T2 &b){if(a<b)a=b;}
template<class T1,class T2>inline void apmin(T1 &a,const T2 &b){if(b<a)a=b;}
template<class T>inline void mset(T a[],int v,int n){memset(a,v,n*sizeof(T));}
template<class T>inline void mcpy(T a[],T b[],int n){memcpy(a,b,n*sizeof(T));}
const int N=1000010;
lint ans=0;
namespace T{
const int E=::N<<1;
int to[E],bro[E],head[N],e=0;
bool vis[N];
int son[N],dep[N],hei[N];
int dfn[N],tim=0;
inline void init(int n){
mset(head+1,-1,n);
mset(vis+1,0,n);
dep[0]=dep[1]=0;
}
inline void ae(int u,int v){
to[e]=v,bro[e]=head[u],head[u]=e++;
}
inline void add(int u,int v){
ae(u,v),ae(v,u);
}
void dfs1(int x,int fa){
hei[x]=dep[x];
son[x]=0;
for(int i=head[x],v;~i;i=bro[i]){
if((v=to[i])==fa)continue;
dep[v]=dep[x]+1;
dfs1(v,x);
if(hei[v]>hei[x]){
hei[x]=hei[v],son[x]=v;
}
}
}
lint f[N];
void dfs2(int x,int fa,lint g[]){
dfn[x]=++tim;
lint *const f=T::f+dfn[x];
f[0]=1;
if(son[x]==0)return;
dfs2(son[x],x,g-1);
ans+=g[0];
for(int i=head[x],v;~i;i=bro[i]){
if((v=to[i])==fa||v==son[x])continue;
lint *ng=new lint[((hei[v]-dep[x])<<1)|1];
mset(ng,0,((hei[v]-dep[x])<<1)|1);
ng+=hei[v]-dep[x];
lint *const nf=T::f+tim;
dfs2(v,x,ng-1);
ans+=ng[0];
for(int d=1;d<=hei[v]-dep[x];d++){
ans+=g[d]*nf[d]+f[d]*ng[d];
g[d]+=f[d]*nf[d]+ng[d];
f[d]+=nf[d];
}
delete (ng-(hei[v]-dep[x]));
}
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("zh.in","r",stdin);
freopen("zh.out","w",stdout);
#endif
const int n=ni;
T::init(n);
for(int i=1;i<n;i++){
T::add(ni,ni);
}
T::dfs1(1,0);
{
lint *ng=new lint[(T::hei[1]<<1)|1];
mset(ng,0,(T::hei[1]<<1)|1);
ng+=T::hei[1];
T::dfs2(1,0,ng-1);
delete (ng-T::hei[1]);
}
printf("%lld\n",ans);
return 0;
}
| 22.292929 | 78 | 0.562302 | sshockwave |
9405b8c6256c4bf5cb3e9496bb27913661fc01f3 | 1,663 | cpp | C++ | benchmark/1_1/main.cpp | philong6297/modern-cpp-challenges | c3f9786aff9dd097ee1e4ec7ac65560e447c28b5 | [
"MIT"
] | null | null | null | benchmark/1_1/main.cpp | philong6297/modern-cpp-challenges | c3f9786aff9dd097ee1e4ec7ac65560e447c28b5 | [
"MIT"
] | null | null | null | benchmark/1_1/main.cpp | philong6297/modern-cpp-challenges | c3f9786aff9dd097ee1e4ec7ac65560e447c28b5 | [
"MIT"
] | null | null | null | // Copyright 2021 Long Le Phi. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
#include <cassert>
#include <cstdint>
#include <limits>
#include <numeric>
#include "benchmark/benchmark.h"
#include "problems/1_1/solution.hpp"
namespace {
using longlp::solution::Problem_1_1;
} // namespace
auto main(int32_t argc, char** argv) -> int32_t {
benchmark::RegisterBenchmark(
"BM_Iteration_Branch",
[](benchmark::State& state) {
for ([[maybe_unused]] auto _ : state) {
benchmark::DoNotOptimize(Problem_1_1::IterationWithBranches(
static_cast<uintmax_t>(state.range())));
}
})
->RangeMultiplier(10)
->Range(100, 1'000'000)
->DisplayAggregatesOnly(true);
benchmark::RegisterBenchmark(
"BM_Iteration_Branch_no_branch",
[](benchmark::State& state) {
for ([[maybe_unused]] auto _ : state) {
benchmark::DoNotOptimize(Problem_1_1::IterationWithNoBranches(
static_cast<uintmax_t>(state.range())));
}
})
->RangeMultiplier(10)
->Range(100, 1'000'000)
->DisplayAggregatesOnly(true);
benchmark::RegisterBenchmark(
"BM_No_Iteration",
[](benchmark::State& state) {
for ([[maybe_unused]] auto _ : state) {
benchmark::DoNotOptimize(
Problem_1_1::UseFormula(static_cast<uintmax_t>(state.range())));
}
})
->RangeMultiplier(10)
->Range(100, 1'000'000)
->DisplayAggregatesOnly(true);
benchmark::Initialize(&argc, argv);
if (benchmark::ReportUnrecognizedArguments(argc, argv)) {
return 1;
}
benchmark::RunSpecifiedBenchmarks();
}
| 27.716667 | 74 | 0.662057 | philong6297 |
940f9ad896fc34423013c03ef7f975751065fbbd | 7,537 | cpp | C++ | src/Server.cpp | mark-grimes/Communique | 969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a | [
"Apache-2.0"
] | null | null | null | src/Server.cpp | mark-grimes/Communique | 969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a | [
"Apache-2.0"
] | 1 | 2015-11-25T09:48:34.000Z | 2015-11-25T09:48:34.000Z | src/Server.cpp | mark-grimes/Communique | 969a2a8851ac2eb9dfc0d5c4fdd8669073ad882a | [
"Apache-2.0"
] | null | null | null | #include "communique/Server.h"
#define _WEBSOCKETPP_CPP11_STL_ // Make sure websocketpp uses c++11 features in preference to boost ones
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio.hpp>
#include <list>
#include "communique/impl/Connection.h"
#include "communique/impl/TLSHandler.h"
//
// Declaration of the pimple
//
namespace communique
{
class ServerPrivateMembers
{
public:
typedef websocketpp::server<websocketpp::config::asio_tls> server_type;
ServerPrivateMembers() : tlsHandler_(server_.get_alog()) { /*No operation besides initialiser list*/ }
server_type server_;
std::thread ioThread_;
std::list< std::shared_ptr<communique::impl::Connection> > currentConnections_;
mutable std::mutex currentConnectionsMutex_;
communique::impl::TLSHandler tlsHandler_;
void on_http( websocketpp::connection_hdl hdl );
void on_open( websocketpp::connection_hdl hdl );
void on_close( websocketpp::connection_hdl hdl );
void on_interrupt( websocketpp::connection_hdl hdl );
std::function<void(const std::string&,std::weak_ptr<communique::IConnection>)> defaultInfoHandler_;
std::function<std::string(const std::string&,std::weak_ptr<communique::IConnection>)> defaultRequestHandler_;
};
}
communique::Server::Server()
: pImple_( new ServerPrivateMembers )
{
pImple_->server_.set_access_channels(websocketpp::log::alevel::none);
//pImple_->server_.set_error_channels(websocketpp::log::elevel::all ^ websocketpp::log::elevel::info);
pImple_->server_.set_error_channels(websocketpp::log::elevel::none);
pImple_->server_.set_tls_init_handler( std::bind( &communique::impl::TLSHandler::on_tls_init, &pImple_->tlsHandler_, std::placeholders::_1 ) );
pImple_->server_.set_http_handler( std::bind( &ServerPrivateMembers::on_http, pImple_.get(), std::placeholders::_1 ) );
pImple_->server_.init_asio();
pImple_->server_.set_open_handler( std::bind( &ServerPrivateMembers::on_open, pImple_.get(), std::placeholders::_1 ) );
pImple_->server_.set_close_handler( std::bind( &ServerPrivateMembers::on_close, pImple_.get(), std::placeholders::_1 ) );
pImple_->server_.set_interrupt_handler( std::bind( &ServerPrivateMembers::on_interrupt, pImple_.get(), std::placeholders::_1 ) );
}
communique::Server::~Server()
{
try
{
stop();
}
catch(...) { /* Make sure no exceptions propagate out */ }
}
bool communique::Server::listen( size_t port )
{
try
{
if( pImple_->ioThread_.joinable() ) stop(); // If already running stop the current IO
websocketpp::lib::error_code errorCode;
websocketpp::lib::asio::error_code underlyingErrorCode;
pImple_->server_.listen(port,errorCode,&underlyingErrorCode);
if( errorCode )
{
std::string errorMessage="Communique server listen error: "+errorCode.message();
if( underlyingErrorCode ) errorMessage+=" ("+underlyingErrorCode.message()+")";
throw std::runtime_error( errorMessage );
}
pImple_->server_.start_accept();
pImple_->ioThread_=std::thread( &ServerPrivateMembers::server_type::run, &pImple_->server_ );
return true;
}
catch( std::exception& error )
{
throw;
}
catch(...)
{
throw std::runtime_error( "Unknown exception in communique::Server::listen" );
}
}
void communique::Server::stop()
{
if( pImple_->server_.is_listening() ) pImple_->server_.stop_listening();
{ // Block to limit lifetime of the lock_guard
std::lock_guard<std::mutex> myMutex( pImple_->currentConnectionsMutex_ );
for( auto& pConnection : pImple_->currentConnections_ )
{
//pImple_->server_.get_con_from_hdl(connection_hdl)->get_raw_socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both);
pConnection->close();
}
}
if( pImple_->ioThread_.joinable() ) pImple_->ioThread_.join();
}
void communique::Server::setCertificateChainFile( const std::string& filename )
{
pImple_->tlsHandler_.setCertificateChainFile(filename);
}
void communique::Server::setPrivateKeyFile( const std::string& filename )
{
pImple_->tlsHandler_.setPrivateKeyFile(filename);
}
void communique::Server::setVerifyFile( const std::string& filename )
{
pImple_->tlsHandler_.setVerifyFile(filename);
}
void communique::Server::setDiffieHellmanParamsFile( const std::string& filename )
{
pImple_->tlsHandler_.setDiffieHellmanParamsFile(filename);
}
void communique::Server::setDefaultInfoHandler( std::function<void(const std::string&)> infoHandler )
{
// Wrap in a function that drops the connection argument
pImple_->defaultInfoHandler_=std::bind( infoHandler, std::placeholders::_1 );
}
void communique::Server::setDefaultInfoHandler( std::function<void(const std::string&,std::weak_ptr<communique::IConnection>)> infoHandler )
{
pImple_->defaultInfoHandler_=infoHandler;
}
void communique::Server::setDefaultRequestHandler( std::function<std::string(const std::string&)> requestHandler )
{
// Wrap in a function that drops the connection argument
pImple_->defaultRequestHandler_=std::bind( requestHandler, std::placeholders::_1 );
}
void communique::Server::setDefaultRequestHandler( std::function<std::string(const std::string&,std::weak_ptr<communique::IConnection>)> requestHandler )
{
pImple_->defaultRequestHandler_=requestHandler;
}
std::vector<std::weak_ptr<communique::IConnection> > communique::Server::currentConnections()
{
std::lock_guard<std::mutex> myMutex( pImple_->currentConnectionsMutex_ );
return std::vector<std::weak_ptr<communique::IConnection> >( pImple_->currentConnections_.begin(), pImple_->currentConnections_.end() );
}
void communique::Server::setErrorLogLocation( std::ostream& outputStream )
{
pImple_->server_.get_elog().set_ostream( &outputStream );
}
void communique::Server::setErrorLogLevel( uint32_t level )
{
pImple_->server_.set_error_channels(level);
}
void communique::Server::setAccessLogLocation( std::ostream& outputStream )
{
pImple_->server_.get_alog().set_ostream( &outputStream );
}
void communique::Server::setAccessLogLevel( uint32_t level )
{
pImple_->server_.set_access_channels(level);
}
void communique::ServerPrivateMembers::on_http( websocketpp::connection_hdl hdl )
{
server_type::connection_ptr con = server_.get_con_from_hdl(hdl);
//con->set_body("Hello World!\n");
con->set_status(websocketpp::http::status_code::ok);
}
void communique::ServerPrivateMembers::on_open( websocketpp::connection_hdl hdl )
{
std::lock_guard<std::mutex> myMutex( currentConnectionsMutex_ );
currentConnections_.emplace_back( new communique::impl::Connection( server_.get_con_from_hdl(hdl), defaultInfoHandler_, defaultRequestHandler_ ) );
}
void communique::ServerPrivateMembers::on_close( websocketpp::connection_hdl hdl )
{
std::lock_guard<std::mutex> myMutex( currentConnectionsMutex_ );
auto pRawConnection=server_.get_con_from_hdl(hdl);
auto findResult=std::find_if( currentConnections_.begin(), currentConnections_.end(), [&pRawConnection](std::shared_ptr<communique::impl::Connection>& other){return pRawConnection==other->underlyingPointer();} );
if( findResult!=currentConnections_.end() ) currentConnections_.erase( findResult );
else std::cout << "Couldn't find connection to remove" << std::endl;
}
void communique::ServerPrivateMembers::on_interrupt( websocketpp::connection_hdl hdl )
{
std::cout << "Connection has been interrupted" << std::endl;
// auto findResult=std::find_if( currentConnections_.begin(), currentConnections_.end(), [&hdl](websocketpp::connection_hdl& other){return !other.owner_before(hdl) && !hdl.owner_before(other);} );
// if( findResult!=currentConnections_.end() ) currentConnections_.erase( findResult );
}
| 36.587379 | 213 | 0.761311 | mark-grimes |
9413d89aba0649c57c1517326033bcfa67239be6 | 6,706 | cpp | C++ | src/lib/meshes/Terrain.cpp | fluffels/vulkan-experiments | 77fc2a3510a22df277d49a6e9b86e52505768b91 | [
"MIT"
] | null | null | null | src/lib/meshes/Terrain.cpp | fluffels/vulkan-experiments | 77fc2a3510a22df277d49a6e9b86e52505768b91 | [
"MIT"
] | null | null | null | src/lib/meshes/Terrain.cpp | fluffels/vulkan-experiments | 77fc2a3510a22df277d49a6e9b86e52505768b91 | [
"MIT"
] | null | null | null | #include "Terrain.h"
Terrain::
Terrain(string path) :
IndexedMesh(),
COMPONENTS(3),
SMOOTH_PAS_COUNT(5),
_vertices(nullptr),
_normals(nullptr),
_indices(nullptr),
_width(0),
_depth(0),
_maxHeight(0),
_terrainWidth(0),
_terrainDepth(0),
_heightMap(nullptr) {
FILE* fp;
errno_t fopenCode = fopen_s(&fp, path.c_str(), "rb");
if (fopenCode != 0) {
char buffer[256];
errno_t strerrorCode = strerror_s(buffer, fopenCode);
if (strerrorCode != 0) {
throw runtime_error(buffer);
} else {
throw runtime_error("Could not load heightmap at " + path);
}
} else {
int width = 0;
int height = 0;
int channelsInFile = 0;
int desiredChannels = 1;
_heightMap = stbi_load_from_file(
fp,
&width,
&height,
&channelsInFile,
desiredChannels
);
if (_heightMap != NULL) {
_width = static_cast<unsigned>(width);
_depth = static_cast<unsigned>(height);
construct();
} else {
const char* errorMessage = stbi_failure_reason();
throw runtime_error(errorMessage);
}
}
}
Terrain::
Terrain(const Terrain &rhs) :
IndexedMesh(),
COMPONENTS(3),
SMOOTH_PAS_COUNT(5),
_vertices(NULL),
_normals(NULL),
_indices(NULL),
_width(rhs._width),
_depth(rhs._depth),
_maxHeight(0),
_terrainWidth(0),
_terrainDepth(0),
_heightMap(rhs._heightMap) {
construct();
}
const Terrain &Terrain::
operator=(Terrain &rhs) {
if (this != &rhs) {
delete[] _vertices;
delete[] _normals;
delete[] _indices;
/* TODO(jan): This is unsafe. */
this->_heightMap = rhs._heightMap;
construct();
}
return *this;
}
float Terrain::
getHeightAt(unsigned x, unsigned z) {
return getCoord(x, z)[Y];
}
void Terrain::
setHeight(unsigned x, unsigned z, float height) {
getCoord(x, z)[Y] = height;
}
float Terrain::
getMaxHeight() const {
return _maxHeight;
}
unsigned Terrain::
getWidth() const {
return _width;
}
unsigned Terrain::
getDepth() const {
return _depth;
}
float *Terrain::
getHeightArray() {
float *result = new float[_vertexCount];
float *v = getCoord(0, 0);
for (unsigned i = 0; i < (unsigned) _vertexCount; i++) {
result[i] = v[Y];
v += COMPONENTS;
}
return result;
}
const float *Terrain::
getPositions() const {
return _vertices;
}
const float *Terrain::
getNormals() const {
return _normals;
}
const unsigned *Terrain::
getIndices() const {
return _indices;
}
void Terrain::
construct() {
_vertexCount = _width * _depth;
const unsigned SIZE = (unsigned) _vertexCount * COMPONENTS;
_vertices = new float[SIZE];
_normals = new float[SIZE];
_indexCount = _vertexCount * 6;
_indices = new unsigned[_indexCount];
generateVertices();
for (unsigned i = 0; i < SMOOTH_PAS_COUNT; i++) {
smoothVertices();
}
generateNormals();
generateIndices();
}
float *Terrain::
getCoord(unsigned x, unsigned z) {
return _vertices + (z * _width * COMPONENTS) + (x * COMPONENTS);
}
float Terrain::
getPixel(unsigned x, unsigned z) {
const unsigned index = z * _width + x;
const unsigned char rawPixel = _heightMap[index];
const float normalizedPixel = rawPixel / 255.f;
return normalizedPixel;
}
void Terrain::
generateVertices() {
const float Z_DELTA = 1.0f;
const float X_DELTA = 1.0f;
unsigned index = 0;
float Zcoord = 0.0f;
float Xcoord = 0.0f;
for (unsigned z = 0; z < _depth; z++) {
Xcoord = 0.0f;
for (unsigned x = 0; x < _width; x++) {
float height = getPixel(x, z) * 64.f;
if (height > _maxHeight) _maxHeight = height;
_vertices[index++] = Xcoord;
_vertices[index++] = height;
_vertices[index++] = Zcoord;
Xcoord += X_DELTA;
}
Zcoord += Z_DELTA;
}
_terrainDepth = Zcoord;
_terrainWidth = Xcoord;
}
void Terrain::
generateNormals() {
for (unsigned z = 1; z < _depth - 1; z++) {
unsigned index = (_width * z + 1) * COMPONENTS;
float *mid = _vertices + index;
float *top = mid + _width * COMPONENTS;
float *left = mid - COMPONENTS;
float *right = mid + COMPONENTS;
float *bot = mid - _width * COMPONENTS;
for (unsigned x = 1; x < _width - 1; x++) {
vec3 m(mid[X], mid[Y], mid[Z]);
vec3 t(top[X], top[Y], top[Z]);
vec3 r(right[X], right[Y], right[Z]);
vec3 l(left[X], left[Y], left[Z]);
vec3 b(bot[X], bot[Y], bot[Z]);
vec3 v0 = t - m;
vec3 v1 = r - m;
vec3 n = normalize(cross(v0, v1));
vec3 v2 = l - m;
n = n + normalize(cross(v2, v0));
vec3 v3 = b - m;
n = n + normalize(cross(v3, v2));
n = n + normalize(cross(v1, v3));
n /= 4;
_normals[index++] = n.x;
_normals[index++] = n.y;
_normals[index++] = n.z;
mid += COMPONENTS;
top += COMPONENTS;
right += COMPONENTS;
left += COMPONENTS;
bot += COMPONENTS;
}
}
}
void Terrain::
generateIndices() {
unsigned index = 0;
for (unsigned z = 0; z < _depth - 1; z++) {
for (unsigned x = 0; x < _width - 1; x++) {
unsigned i = z * _width + x;
/* Top left square. */
_indices[index++] = i;
_indices[index++] = i + _width;
_indices[index++] = i + 1;
/* Bottom right square. */
_indices[index++] = i + 1;
_indices[index++] = i + _width;
_indices[index++] = i + 1 + _width;
}
}
}
void Terrain::
smoothVertices() {
const unsigned SAMPLE = 4;
for (unsigned z = SAMPLE; z < _depth - SAMPLE; z++) {
float *t = getCoord(SAMPLE, z + 1);
float *m = getCoord(SAMPLE, z);
float *b = getCoord(SAMPLE, z - 1);
for (unsigned x = SAMPLE; x < _width - SAMPLE; x++) {
float acc = m[Y] + (m - COMPONENTS)[Y] + (m + COMPONENTS)[Y];
acc += t[Y] + (t - COMPONENTS)[Y] + (t + COMPONENTS)[Y];
acc += b[Y] + (b - COMPONENTS)[Y] + (b + COMPONENTS)[Y];
m[Y] = acc / 9;
t += COMPONENTS;
m += COMPONENTS;
b += COMPONENTS;
}
}
}
| 24.654412 | 73 | 0.525798 | fluffels |
9418d5e12fd6ddd41053ccde892c997c9b1b6445 | 1,009 | cpp | C++ | blackbox/net/ResponseQueue.cpp | mojmir-svoboda/BlackBoxTT | 0c87b989827107695538e1bf1266c08b083dda44 | [
"MIT"
] | 11 | 2017-06-19T14:21:15.000Z | 2020-03-04T06:43:16.000Z | blackbox/net/ResponseQueue.cpp | mojmir-svoboda/BlackBoxTT | 0c87b989827107695538e1bf1266c08b083dda44 | [
"MIT"
] | null | null | null | blackbox/net/ResponseQueue.cpp | mojmir-svoboda/BlackBoxTT | 0c87b989827107695538e1bf1266c08b083dda44 | [
"MIT"
] | 3 | 2017-07-23T18:08:55.000Z | 2019-09-16T16:28:18.000Z | #include "Session.h"
#include "Server.h"
#include <blackbox/common.h>
#include <utility>
#include <memory>
#include <asio.hpp>
#include <asio/ts/buffer.hpp>
#include <asio/ts/internet.hpp>
#include <bbproto/decoder.h>
#include "commands.h"
#include <boost/lockfree/spsc_queue.hpp>
namespace bb {
ResponseQueue::ResponseQueue ()
: m_impl(new boost::lockfree::spsc_queue<PendingCommand *, boost::lockfree::capacity<128>>)
//: m_impl(new boost::lockfree::spsc_queue<std::unique_ptr<PendingCommand>, boost::lockfree::capacity<128>>)
{
}
ResponseQueue::~ResponseQueue ()
{
}
// bool ResponseQueue::Enqueue (std::unique_ptr<PendingCommand> cmd)
// {
// return m_impl->push(cmd);
// }
//
// bool ResponseQueue::Dequeue (std::unique_ptr<PendingCommand> & cmd)
// {
// return m_impl->pop(cmd);
// }
bool ResponseQueue::Enqueue(PendingCommand * cmd)
{
return m_impl->push(cmd);
}
bool ResponseQueue::Dequeue(PendingCommand * & cmd)
{
return m_impl->pop(cmd);
}
}
| 21.934783 | 110 | 0.682854 | mojmir-svoboda |
941e403224b15896608d39846bf5ab23aff0345e | 5,749 | cpp | C++ | CmnMath/sample/sample_pointcloud_pointcloud.cpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnMath/sample/sample_pointcloud_pointcloud.cpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | CmnMath/sample/sample_pointcloud_pointcloud.cpp | Khoronus/CmnUniverse | 9cf9b4297f2fcb49330126aa1047b422144045e1 | [
"MIT"
] | null | null | null | /* @file sample_math_trigonometry.hpp
* @brief Perform a sample trigonometric operations.
*
* @section LICENSE
*
* 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 AUTHOR/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.
*
* @author Various
* @bug No known bugs.
* @version 0.1.0.0
*
*/
#include <iostream>
#include "pointcloud/pointcloud_pointcloud.hpp"
#include "noise/noise_noise.hpp"
namespace
{
/** @brief It finds a peak of values in a set
*/
float find_peak(std::map<int, std::vector< std::pair< std::pair< CmnMath::algebralinear::Vector3f, CmnMath::algebralinear::Vector3f>,
std::pair<CmnMath::algebralinear::Vector3f, float> > > > &items,
float bin) {
// container with the bin points
std::map<int, std::vector<CmnMath::algebralinear::Vector3f>> m_pts;
// Show the points
for (auto it : items) {
for (auto it2 : it.second) {
//std::cout << it.first << " " << it2.first.first << " " << it2.first.second << " " << it2.second.first << " " << it2.second.second << std::endl;
m_pts[static_cast<int>(it2.first.first.z * bin)].push_back(CmnMath::algebralinear::Vector3f(it2.first.first.x, it2.first.first.y, it2.first.first.z));
}
}
//std::cout << "###########" << std::endl;
float maxval = 0;
float maxid = 0;
for (auto it : m_pts) {
//std::cout << it.first << " " << it.second.size() << std::endl;
if (it.second.size() > maxval) {
maxval = it.second.size();
maxid = it.first / bin;
}
}
return maxid;
}
CmnMath::algebralinear::Vector3f rand_point() {
return CmnMath::algebralinear::Vector3f(
static_cast<float>(rand()) / RAND_MAX,
static_cast<float>(rand()) / RAND_MAX,
static_cast<float>(rand()) / RAND_MAX);
}
/** @brief Function to test the classes and functions
*/
void test()
{
srand(time(0));
// Load items
std::map<int, std::vector< std::pair< std::pair< CmnMath::algebralinear::Vector3f, CmnMath::algebralinear::Vector3f>,
std::pair<CmnMath::algebralinear::Vector3f, float> > > > items;
for (int i = 0; i < 1000; ++i) {
items[0].push_back(std::make_pair(std::make_pair(
rand_point(), rand_point()),
std::make_pair(CmnMath::algebralinear::Vector3f(255, 0, 255), 0.1f)));
}
// modifier
std::vector<CmnMath::algebralinear::Vector3f> vpts;
vpts.push_back(CmnMath::algebralinear::Vector3f(0.6, 0.4, 2.3));
vpts.push_back(CmnMath::algebralinear::Vector3f(-1.1, -0.2, 2.4));
CmnMath::noise::Noise<CmnMath::algebralinear::Vector3f>::localized_adjustment(vpts, 0.5, 1.0, items);
vpts.clear();
vpts.push_back(CmnMath::algebralinear::Vector3f(0.8, -0.7, 2.4));
CmnMath::noise::Noise<CmnMath::algebralinear::Vector3f>::localized_adjustment(vpts, 0.7, 1.5, items);
CmnMath::noise::Noise<CmnMath::algebralinear::Vector3f>::random_noise(0.0, 0.1, items);
//Noise<CmnMath::algebralinear::Vector3f>::localized_random_noise(vpts, 0.5, 0.8, 0.1, items);
//// Show the points
//std::map<int, std::vector<CmnMath::algebralinear::Vector3f>> m_pts;
//for (auto it : items) {
// for (auto it2 : it.second) {
// std::cout << it.first << " " << it2.first.first << " " << it2.first.second << " " << it2.second.first << " " << it2.second.second << std::endl;
// m_pts[static_cast<int>(it2.first.first.z * 10)].push_back(CmnMath::algebralinear::Vector3f(it2.first.first.x, it2.first.first.y, it2.first.first.z));
// }
//}
//std::cout << "###########" << std::endl;
//for (auto it : m_pts) {
// std::cout << it.first << " " << it.second.size() << std::endl;
//}
std::vector<float> vavg, vmode, vmode_peak;
// https://stackoverflow.com/questions/11062804/measuring-the-runtime-of-a-c-code
auto start = std::chrono::system_clock::now();
// find the peak
float peak = find_peak(items, 10);
std::cout << "peak: " << peak << std::endl;
int num_iterations = 5;
for (int k = 0; k < num_iterations; ++k) {
float dAvg = CmnMath::pointcloud::EstimateHeight<CmnMath::algebralinear::Vector3f>::average(5000, items[0]);
float dMode = CmnMath::pointcloud::EstimateHeight<CmnMath::algebralinear::Vector3f>::mode(5000, 1000, items[0]);
float dModeP = CmnMath::pointcloud::EstimateHeight<CmnMath::algebralinear::Vector3f>::mode(5000, 1000, items[0], peak, 0.2);
vavg.push_back(dAvg);
vmode.push_back(dMode);
vmode_peak.push_back(dModeP);
}
auto end = std::chrono::system_clock::now();
// this constructs a duration object using milliseconds
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
CmnMath::CMN_64F mean = 0, stdev = 0;
CmnMath::statistics::classic::SeriesAnalysis<float>::mean_var(vavg, mean, stdev);
std::cout << "dAvg: " << mean << " " << stdev << std::endl;
CmnMath::statistics::classic::SeriesAnalysis<float>::mean_var(vmode, mean, stdev);
std::cout << "dMode: " << mean << " " << stdev << std::endl;
CmnMath::statistics::classic::SeriesAnalysis<float>::mean_var(vmode_peak, mean, stdev);
std::cout << "dModeP: " << mean << " " << stdev << std::endl;
std::cout << "et(ms): " << elapsed.count() / num_iterations << std::endl;
}
} // namespace
/** main
*/
int main(int argc, char *argv[])
{
std::cout << "Test pointcloud" << std::endl;
test();
return 0;
} | 39.108844 | 154 | 0.678901 | Khoronus |
941f9574a275a4e910e05e0542e5010e18b71ca9 | 12,633 | hpp | C++ | ryoanji/src/ryoanji/cpu/multipole.hpp | nknk567/SPH-EXA | 1d51f444eeb8662192465b40f5893fd92045729e | [
"MIT"
] | null | null | null | ryoanji/src/ryoanji/cpu/multipole.hpp | nknk567/SPH-EXA | 1d51f444eeb8662192465b40f5893fd92045729e | [
"MIT"
] | null | null | null | ryoanji/src/ryoanji/cpu/multipole.hpp | nknk567/SPH-EXA | 1d51f444eeb8662192465b40f5893fd92045729e | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2021 CSCS, ETH Zurich
* 2021 University of Basel
*
* 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.
*/
/*! @file
* @brief implements elementary gravity data structures for octree nodes
*
* @author Sebastian Keller <[email protected]>
*
* See for example Hernquist 1987, Performance Characteristics of Tree Codes,
* https://ui.adsabs.harvard.edu/abs/1987ApJS...64..715H
*/
#pragma once
#include <cmath>
#include "cstone/util/tuple.hpp"
#include "ryoanji/types.h"
namespace ryoanji
{
template <class T>
using CartesianQuadrupole = util::array<T, 8>;
template<class MType>
struct IsCartesian : public stl::integral_constant<size_t, MType{}.size() == CartesianQuadrupole<float>{}.size()>
{
};
//! @brief CartesianQuadrupole index names
struct Cqi
{
enum IndexNames
{
mass = 0,
qxx = 1,
qxy = 2,
qxz = 3,
qyy = 4,
qyz = 5,
qzz = 6
};
};
/*! @brief Compute the monopole and quadruple moments from particle coordinates
*
* @tparam T1 float or double
* @tparam T2 float or double
* @tparam T3 float or double
* @param[in] x x coordinate array
* @param[in] y y coordinate array
* @param[in] z z coordinate array
* @param[in] m masses array
* @param[in] numParticles number of particles to read from coordinate arrays
* @param[out] gv output quadrupole
*/
template<class T1, class T2, class T3>
void particle2Multipole(const T1* x,
const T1* y,
const T1* z,
const T2* m,
LocalIndex first,
LocalIndex last,
const Vec3<T1>& center,
CartesianQuadrupole<T3>& gv)
{
gv = T3(0);
if (first == last) { return; }
for (LocalIndex i = first; i < last; ++i)
{
T1 xx = x[i];
T1 yy = y[i];
T1 zz = z[i];
T1 m_i = m[i];
T1 rx = xx - center[0];
T1 ry = yy - center[1];
T1 rz = zz - center[2];
gv[Cqi::mass] += m_i;
gv[Cqi::qxx] += rx * rx * m_i;
gv[Cqi::qxy] += rx * ry * m_i;
gv[Cqi::qxz] += rx * rz * m_i;
gv[Cqi::qyy] += ry * ry * m_i;
gv[Cqi::qyz] += ry * rz * m_i;
gv[Cqi::qzz] += rz * rz * m_i;
}
T1 traceQ = gv[Cqi::qxx] + gv[Cqi::qyy] + gv[Cqi::qzz];
// remove trace
gv[Cqi::qxx] = 3 * gv[Cqi::qxx] - traceQ;
gv[Cqi::qyy] = 3 * gv[Cqi::qyy] - traceQ;
gv[Cqi::qzz] = 3 * gv[Cqi::qzz] - traceQ;
gv[Cqi::qxy] *= 3;
gv[Cqi::qxz] *= 3;
gv[Cqi::qyz] *= 3;
}
template<class T>
void moveExpansionCenter(Vec3<T> Xold, Vec3<T> Xnew, CartesianQuadrupole<T>& gv)
{
Vec3<T> dX = Xold - Xnew;
T rx = dX[0];
T ry = dX[1];
T rz = dX[2];
gv[Cqi::qxx] = gv.qxx - rx * rx * gv[Cqi::mass];
gv[Cqi::qxy] = gv.qxy - rx * ry * gv[Cqi::mass];
gv[Cqi::qxz] = gv.qxz - rx * rz * gv[Cqi::mass];
gv[Cqi::qyy] = gv.qyy - ry * ry * gv[Cqi::mass];
gv[Cqi::qyz] = gv.qyz - ry * rz * gv[Cqi::mass];
gv[Cqi::qzz] = gv.qzz - rz * rz * gv[Cqi::mass];
T traceQ = gv[Cqi::qxx] + gv[Cqi::qyy] + gv[Cqi::qzz];
// remove trace
gv[Cqi::qxx] = 3 * gv[Cqi::qxx] - traceQ;
gv[Cqi::qyy] = 3 * gv[Cqi::qyy] - traceQ;
gv[Cqi::qzz] = 3 * gv[Cqi::qzz] - traceQ;
gv[Cqi::qxy] *= 3;
gv[Cqi::qxz] *= 3;
gv[Cqi::qyz] *= 3;
}
/*! @brief compute a single particle-particle gravitational interaction
*
* @tparam T1 float or double
* @tparam T2 float or double
* @param tx target x coord
* @param ty target y coord
* @param tz target z coord
* @param th target h smoothing length
* @param sx source x coord
* @param sy source y coord
* @param sz source z coord
* @param sh source h coord
* @param sm source mass
* @return tuple(ax, ay, az, ugrav)
*/
template<class T1, class T2>
HOST_DEVICE_FUN inline __attribute__((always_inline)) util::tuple<T1, T1, T1, T1>
particle2Particle(T1 tx, T1 ty, T1 tz, T2 th, T1 sx, T1 sy, T1 sz, T2 sh, T2 sm)
{
T1 rx = sx - tx;
T1 ry = sy - ty;
T1 rz = sz - tz;
T1 r_2 = rx * rx + ry * ry + rz * rz;
T1 r = std::sqrt(r_2);
T1 r_minus1 = 1.0 / r;
T1 r_minus2 = r_minus1 * r_minus1;
T1 mEffective = sm;
T1 h_ts = th + sh;
if (r < h_ts)
{
// apply mass softening correction
T1 vgr = r / h_ts;
mEffective *= vgr * vgr * vgr;
}
T1 Mr_minus3 = mEffective * r_minus1 * r_minus2;
return {Mr_minus3 * rx, Mr_minus3 * ry, Mr_minus3 * rz, -Mr_minus3 * r_2};
}
/*! @brief direct gravity calculation with particle-particle interactions
*
* @tparam T1 float or double
* @tparam T2 float or double
* @param[in] tx target particle x coordinate
* @param[in] ty target particle y coordinate
* @param[in] tz target particle z coordinate
* @param[in] hi target particle smoothing length
* @param[in] sx source particle x coordinates
* @param[in] sy source particle y coordinates
* @param[in] sz source particle z coordinates
* @param[in] h source particle smoothing lengths
* @param[in] m source particle masses
* @param[in] numSources number of source particles
* @return tuple(ax, ay, az, ugrav)
*
* Computes direct particle-particle gravitational interaction according to
*
* vec(a_t) = - sum_{j} m_j / (r_tj^2 + eps2)^(3/2)) * (r_t - r_j)
*
* Notes:
* - Source particles MUST NOT contain the target. If the source is a cell that contains the target,
* the target must be located and this function called twice, with all particles before target and
* all particles that follow it.
*/
template<class T1, class T2>
HOST_DEVICE_FUN util::tuple<T1, T1, T1, T1> particle2Particle(T1 tx,
T1 ty,
T1 tz,
T2 hi,
const T1* sx,
const T1* sy,
const T1* sz,
const T2* h,
const T2* m,
LocalIndex numSources)
{
T1 axLoc = 0;
T1 ayLoc = 0;
T1 azLoc = 0;
T1 uLoc = 0;
#if defined(__llvm__) || defined(__clang__)
#pragma clang loop vectorize(enable)
#endif
for (LocalIndex j = 0; j < numSources; ++j)
{
auto [ax_, ay_, az_, u_] = particle2Particle(tx, ty, tz, hi, sx[j], sy[j], sz[j], h[j], m[j]);
axLoc += ax_;
ayLoc += ay_;
azLoc += az_;
uLoc += u_;
}
return {axLoc, ayLoc, azLoc, uLoc};
}
/*! @brief apply gravitational interaction with a multipole to a particle
*
* @tparam T1 float or double
* @tparam T2 float or double
* @param[in] tx target particle x coordinate
* @param[in] ty target particle y coordinate
* @param[in] tz target particle z coordinate
* @param[in] multipole multipole source
* @param[inout] ugrav location to add gravitational potential to
* @return tuple(ax, ay, az, u)
*
* Note: contribution is added to output
*
* Direct implementation of the formulae in Hernquist, 1987 (complete reference in file docstring):
*
* monopole: -M/r^3 * vec(r)
* quadrupole: Q*vec(r) / r^5 - 5/2 * vec(r)*Q*vec(r) * vec(r) / r^7
*/
template<class T1, class T2>
HOST_DEVICE_FUN inline util::tuple<T1, T1, T1, T1> multipole2Particle(T1 tx, T1 ty, T1 tz, const Vec3<T1>& center,
const CartesianQuadrupole<T2>& multipole)
{
T2 rx = tx - center[0];
T2 ry = ty - center[1];
T2 rz = tz - center[2];
T2 r_2 = rx * rx + ry * ry + rz * rz;
T2 r_minus1 = T2(1) / std::sqrt(r_2);
T2 r_minus2 = r_minus1 * r_minus1;
T2 r_minus5 = r_minus2 * r_minus2 * r_minus1;
T2 Qrx = rx * multipole[Cqi::qxx] + ry * multipole[Cqi::qxy] + rz * multipole[Cqi::qxz];
T2 Qry = rx * multipole[Cqi::qxy] + ry * multipole[Cqi::qyy] + rz * multipole[Cqi::qyz];
T2 Qrz = rx * multipole[Cqi::qxz] + ry * multipole[Cqi::qyz] + rz * multipole[Cqi::qzz];
T2 rQr = rx * Qrx + ry * Qry + rz * Qrz;
// rQr quad-term mono-term
// | |
T2 rQrAndMonopole = (T2(-2.5) * rQr * r_minus5 - multipole[Cqi::mass] * r_minus1) * r_minus2;
// Qr Quad-term
return {r_minus5 * Qrx + rQrAndMonopole * rx,
r_minus5 * Qry + rQrAndMonopole * ry,
r_minus5 * Qrz + rQrAndMonopole * rz,
-(multipole[Cqi::mass] * r_minus1 + T2(0.5) * r_minus5 * rQr)};
}
/*! @brief add a multipole contribution to the composite multipole
*
* @tparam T float or double
* @param[inout] composite the composite multipole
* @param[in] dX distance vector between composite and added expansion center
* @param[in] addend the multipole to add
*
* Implements formula (2.5) from Hernquist 1987 (parallel axis theorem)
*/
template<class T>
void addQuadrupole(CartesianQuadrupole<T>& composite, Vec3<T> dX, const CartesianQuadrupole<T>& addend)
{
T rx = dX[0];
T ry = dX[1];
T rz = dX[2];
T rx_2 = rx * rx;
T ry_2 = ry * ry;
T rz_2 = rz * rz;
T r_2 = (rx_2 + ry_2 + rz_2) * (1.0 / 3.0);
T ml = addend[Cqi::mass] * 3;
composite[Cqi::mass] += addend[Cqi::mass];
composite[Cqi::qxx] += addend[Cqi::qxx] + ml * (rx_2 - r_2);
composite[Cqi::qxy] += addend[Cqi::qxy] + ml * rx * ry;
composite[Cqi::qxz] += addend[Cqi::qxz] + ml * rx * rz;
composite[Cqi::qyy] += addend[Cqi::qyy] + ml * (ry_2 - r_2);
composite[Cqi::qyz] += addend[Cqi::qyz] + ml * ry * rz;
composite[Cqi::qzz] += addend[Cqi::qzz] + ml * (rz_2 - r_2);
}
/*! @brief Combine multipoles into a single multipole
*
* @tparam T float or double
* @tparam MType Spherical multipole, quadrupole or octopole
* @param[in] begin first index into @p sourceCenter and @p Multipole to aggregate
* @param[in] end last index
* @param[in] Xout the expansion (com) center of the output multipole
* @param[in] Xsrc input multipole expansion (com) centers
* @param[in] Msrc input multipoles
* @param[out] Mout the aggregated output multipole
*/
template<class T, class MType, std::enable_if_t<MType{}.size() == CartesianQuadrupole<T>{}.size(), int> = 0>
void multipole2Multipole(int begin, int end, const Vec4<T>& Xout, const Vec4<T>* Xsrc, const MType* Msrc, MType& Mout)
{
Mout = 0;
for (int i = begin; i < end; i++)
{
const MType& Mi = Msrc[i];
Vec4<T> Xi = Xsrc[i];
Vec3<T> dX = makeVec3(Xout - Xi);
addQuadrupole(Mout, dX, Mi);
}
}
template<class MType, std::enable_if_t<IsCartesian<MType>{}, int> = 0>
HOST_DEVICE_FUN MType normalize(const MType& multipole)
{
return multipole;
}
} // namespace ryoanji
| 34.99446 | 118 | 0.5583 | nknk567 |
9420ea738bac4733be3fcbc985c4c52e585e2a93 | 37,587 | hpp | C++ | 2 - MaxPooled Net/3 - SCAMP5 implementation/fc_weights.hpp | brouwa/CNNs-on-FPSPs | 71bcc2335e6d71ad21ba66e04a651d4db218356d | [
"MIT"
] | 1 | 2021-02-23T21:53:30.000Z | 2021-02-23T21:53:30.000Z | 2 - MaxPooled Net/3 - SCAMP5 implementation/fc_weights.hpp | brouwa/CNNs-on-FPSPs | 71bcc2335e6d71ad21ba66e04a651d4db218356d | [
"MIT"
] | 1 | 2020-11-13T19:08:27.000Z | 2020-11-13T19:08:27.000Z | 2 - MaxPooled Net/3 - SCAMP5 implementation/fc_weights.hpp | brouwa/CNNs-on-FPSPs | 71bcc2335e6d71ad21ba66e04a651d4db218356d | [
"MIT"
] | 1 | 2021-03-04T10:17:01.000Z | 2021-03-04T10:17:01.000Z | /*
* fc_weights.hpp
*
* Created on: Jul 4, 2019
* Author: Benoît GUILLARD
*/
#ifndef FC_WEIGHTS_HPP_
#define FC_WEIGHTS_HPP_
// Re-trained fully connected weight values
inline void fc_1(int in[32], int out[50]){
out[0] =
in[0]*(-76) +
in[1]*(14) +
in[2]*(125) +
in[3]*(-20) +
in[4]*(-11) +
in[5]*(8) +
in[6]*(3) +
in[7]*(4) +
in[8]*(-95) +
in[9]*(22) +
in[10]*(25) +
in[11]*(27) +
in[12]*(-50) +
in[13]*(-28) +
in[14]*(22) +
in[15]*(32) +
in[16]*(-20) +
in[17]*(31) +
in[18]*(-184) +
in[19]*(206) +
in[20]*(-35) +
in[21]*(10) +
in[22]*(-35) +
in[23]*(-92) +
in[24]*(-21) +
in[25]*(-64) +
in[26]*(52) +
in[27]*(-85) +
in[28]*(32) +
in[29]*(14) +
in[30]*(6) +
in[31]*(59) +
(-113);
out[1] =
in[0]*(20) +
in[1]*(-17) +
in[2]*(-11) +
in[3]*(-65) +
in[4]*(-66) +
in[5]*(-24) +
in[6]*(11) +
in[7]*(-4) +
in[8]*(-145) +
in[9]*(44) +
in[10]*(-56) +
in[11]*(-21) +
in[12]*(-332) +
in[13]*(-100) +
in[14]*(47) +
in[15]*(83) +
in[16]*(-21) +
in[17]*(12) +
in[18]*(33) +
in[19]*(-71) +
in[20]*(67) +
in[21]*(-1) +
in[22]*(105) +
in[23]*(29) +
in[24]*(11) +
in[25]*(15) +
in[26]*(-28) +
in[27]*(1) +
in[28]*(-29) +
in[29]*(20) +
in[30]*(-11) +
in[31]*(44) +
(-5);
out[2] =
in[0]*(21) +
in[1]*(-13) +
in[2]*(16) +
in[3]*(-8) +
in[4]*(-21) +
in[5]*(-24) +
in[6]*(10) +
in[7]*(-21) +
in[8]*(-8) +
in[9]*(-11) +
in[10]*(10) +
in[11]*(-9) +
in[12]*(-23) +
in[13]*(-7) +
in[14]*(-26) +
in[15]*(-6) +
in[16]*(-15) +
in[17]*(1) +
in[18]*(-3) +
in[19]*(-20) +
in[20]*(3) +
in[21]*(-23) +
in[22]*(-7) +
in[23]*(-19) +
in[24]*(8) +
in[25]*(-11) +
in[26]*(24) +
in[27]*(14) +
in[28]*(-25) +
in[29]*(12) +
in[30]*(-27) +
in[31]*(-6) +
(0);
out[3] =
in[0]*(-85) +
in[1]*(7) +
in[2]*(12) +
in[3]*(-21) +
in[4]*(-262) +
in[5]*(49) +
in[6]*(4) +
in[7]*(-23) +
in[8]*(-52) +
in[9]*(-15) +
in[10]*(6) +
in[11]*(20) +
in[12]*(41) +
in[13]*(32) +
in[14]*(57) +
in[15]*(-31) +
in[16]*(54) +
in[17]*(1) +
in[18]*(-245) +
in[19]*(26) +
in[20]*(27) +
in[21]*(-59) +
in[22]*(75) +
in[23]*(-126) +
in[24]*(70) +
in[25]*(-42) +
in[26]*(-98) +
in[27]*(-9) +
in[28]*(44) +
in[29]*(-12) +
in[30]*(-44) +
in[31]*(26) +
(248);
out[4] =
in[0]*(-184) +
in[1]*(8) +
in[2]*(61) +
in[3]*(-47) +
in[4]*(111) +
in[5]*(-6) +
in[6]*(-118) +
in[7]*(-11) +
in[8]*(151) +
in[9]*(45) +
in[10]*(88) +
in[11]*(-28) +
in[12]*(-66) +
in[13]*(33) +
in[14]*(-57) +
in[15]*(-5) +
in[16]*(-28) +
in[17]*(32) +
in[18]*(17) +
in[19]*(0) +
in[20]*(40) +
in[21]*(41) +
in[22]*(70) +
in[23]*(79) +
in[24]*(-24) +
in[25]*(-20) +
in[26]*(35) +
in[27]*(34) +
in[28]*(17) +
in[29]*(0) +
in[30]*(51) +
in[31]*(-65) +
(-201);
out[5] =
in[0]*(-153) +
in[1]*(54) +
in[2]*(81) +
in[3]*(3) +
in[4]*(90) +
in[5]*(5) +
in[6]*(53) +
in[7]*(-15) +
in[8]*(-190) +
in[9]*(-96) +
in[10]*(-106) +
in[11]*(26) +
in[12]*(217) +
in[13]*(-9) +
in[14]*(63) +
in[15]*(-71) +
in[16]*(29) +
in[17]*(11) +
in[18]*(18) +
in[19]*(-53) +
in[20]*(56) +
in[21]*(-13) +
in[22]*(49) +
in[23]*(-21) +
in[24]*(-10) +
in[25]*(-43) +
in[26]*(89) +
in[27]*(-163) +
in[28]*(-67) +
in[29]*(13) +
in[30]*(-29) +
in[31]*(65) +
(-32);
out[6] =
in[0]*(-12) +
in[1]*(-7) +
in[2]*(-101) +
in[3]*(-3) +
in[4]*(-230) +
in[5]*(18) +
in[6]*(-212) +
in[7]*(-18) +
in[8]*(-23) +
in[9]*(34) +
in[10]*(155) +
in[11]*(-25) +
in[12]*(59) +
in[13]*(-14) +
in[14]*(-40) +
in[15]*(53) +
in[16]*(4) +
in[17]*(5) +
in[18]*(-123) +
in[19]*(-93) +
in[20]*(62) +
in[21]*(-25) +
in[22]*(78) +
in[23]*(26) +
in[24]*(14) +
in[25]*(-35) +
in[26]*(115) +
in[27]*(-50) +
in[28]*(13) +
in[29]*(-7) +
in[30]*(-30) +
in[31]*(7) +
(148);
out[7] =
in[0]*(36) +
in[1]*(20) +
in[2]*(-27) +
in[3]*(24) +
in[4]*(129) +
in[5]*(-2) +
in[6]*(22) +
in[7]*(2) +
in[8]*(-118) +
in[9]*(61) +
in[10]*(-297) +
in[11]*(-64) +
in[12]*(119) +
in[13]*(17) +
in[14]*(6) +
in[15]*(8) +
in[16]*(33) +
in[17]*(-11) +
in[18]*(-14) +
in[19]*(-3) +
in[20]*(1) +
in[21]*(-15) +
in[22]*(32) +
in[23]*(-98) +
in[24]*(23) +
in[25]*(38) +
in[26]*(-76) +
in[27]*(-43) +
in[28]*(0) +
in[29]*(-15) +
in[30]*(25) +
in[31]*(56) +
(-7);
out[8] =
in[0]*(10) +
in[1]*(50) +
in[2]*(92) +
in[3]*(20) +
in[4]*(-103) +
in[5]*(8) +
in[6]*(-13) +
in[7]*(1) +
in[8]*(-103) +
in[9]*(35) +
in[10]*(-88) +
in[11]*(3) +
in[12]*(25) +
in[13]*(-14) +
in[14]*(-9) +
in[15]*(-61) +
in[16]*(-3) +
in[17]*(16) +
in[18]*(157) +
in[19]*(65) +
in[20]*(86) +
in[21]*(-22) +
in[22]*(15) +
in[23]*(25) +
in[24]*(16) +
in[25]*(32) +
in[26]*(9) +
in[27]*(-111) +
in[28]*(-4) +
in[29]*(-3) +
in[30]*(40) +
in[31]*(105) +
(-292);
out[9] =
in[0]*(-54) +
in[1]*(-14) +
in[2]*(-6) +
in[3]*(-21) +
in[4]*(-55) +
in[5]*(-6) +
in[6]*(10) +
in[7]*(-1) +
in[8]*(-53) +
in[9]*(13) +
in[10]*(182) +
in[11]*(5) +
in[12]*(-76) +
in[13]*(-44) +
in[14]*(-38) +
in[15]*(0) +
in[16]*(-2) +
in[17]*(17) +
in[18]*(106) +
in[19]*(25) +
in[20]*(-50) +
in[21]*(-18) +
in[22]*(-12) +
in[23]*(4) +
in[24]*(-18) +
in[25]*(-48) +
in[26]*(54) +
in[27]*(-71) +
in[28]*(34) +
in[29]*(45) +
in[30]*(3) +
in[31]*(54) +
(270);
out[10] =
in[0]*(-121) +
in[1]*(-36) +
in[2]*(-137) +
in[3]*(-33) +
in[4]*(-64) +
in[5]*(31) +
in[6]*(40) +
in[7]*(44) +
in[8]*(-124) +
in[9]*(0) +
in[10]*(10) +
in[11]*(36) +
in[12]*(-79) +
in[13]*(29) +
in[14]*(-10) +
in[15]*(-23) +
in[16]*(-62) +
in[17]*(29) +
in[18]*(-325) +
in[19]*(-130) +
in[20]*(17) +
in[21]*(18) +
in[22]*(-9) +
in[23]*(16) +
in[24]*(12) +
in[25]*(0) +
in[26]*(-33) +
in[27]*(59) +
in[28]*(35) +
in[29]*(-58) +
in[30]*(13) +
in[31]*(3) +
(92);
out[11] =
in[0]*(53) +
in[1]*(74) +
in[2]*(92) +
in[3]*(-4) +
in[4]*(-21) +
in[5]*(-46) +
in[6]*(-107) +
in[7]*(1) +
in[8]*(-174) +
in[9]*(33) +
in[10]*(-12) +
in[11]*(22) +
in[12]*(41) +
in[13]*(18) +
in[14]*(-40) +
in[15]*(-31) +
in[16]*(-9) +
in[17]*(-30) +
in[18]*(-60) +
in[19]*(8) +
in[20]*(-86) +
in[21]*(50) +
in[22]*(16) +
in[23]*(-52) +
in[24]*(-5) +
in[25]*(21) +
in[26]*(0) +
in[27]*(28) +
in[28]*(85) +
in[29]*(-58) +
in[30]*(37) +
in[31]*(-3) +
(39);
out[12] =
in[0]*(-59) +
in[1]*(16) +
in[2]*(-1) +
in[3]*(-8) +
in[4]*(-48) +
in[5]*(17) +
in[6]*(63) +
in[7]*(-21) +
in[8]*(-94) +
in[9]*(-14) +
in[10]*(-68) +
in[11]*(1) +
in[12]*(121) +
in[13]*(72) +
in[14]*(-104) +
in[15]*(-5) +
in[16]*(7) +
in[17]*(-3) +
in[18]*(-232) +
in[19]*(-19) +
in[20]*(62) +
in[21]*(-20) +
in[22]*(-93) +
in[23]*(18) +
in[24]*(53) +
in[25]*(-11) +
in[26]*(-93) +
in[27]*(-38) +
in[28]*(-1) +
in[29]*(53) +
in[30]*(-18) +
in[31]*(-11) +
(162);
out[13] =
in[0]*(27) +
in[1]*(12) +
in[2]*(-11) +
in[3]*(-10) +
in[4]*(10) +
in[5]*(17) +
in[6]*(-15) +
in[7]*(22) +
in[8]*(9) +
in[9]*(-19) +
in[10]*(13) +
in[11]*(-3) +
in[12]*(10) +
in[13]*(-20) +
in[14]*(-19) +
in[15]*(-26) +
in[16]*(11) +
in[17]*(-7) +
in[18]*(-27) +
in[19]*(6) +
in[20]*(8) +
in[21]*(-23) +
in[22]*(17) +
in[23]*(5) +
in[24]*(-17) +
in[25]*(-25) +
in[26]*(22) +
in[27]*(-12) +
in[28]*(-21) +
in[29]*(-12) +
in[30]*(-8) +
in[31]*(23) +
(0);
out[14] =
in[0]*(84) +
in[1]*(-25) +
in[2]*(77) +
in[3]*(15) +
in[4]*(26) +
in[5]*(17) +
in[6]*(48) +
in[7]*(-39) +
in[8]*(23) +
in[9]*(-19) +
in[10]*(-105) +
in[11]*(-15) +
in[12]*(43) +
in[13]*(8) +
in[14]*(55) +
in[15]*(29) +
in[16]*(8) +
in[17]*(-7) +
in[18]*(-461) +
in[19]*(53) +
in[20]*(-35) +
in[21]*(15) +
in[22]*(-3) +
in[23]*(-27) +
in[24]*(-8) +
in[25]*(2) +
in[26]*(41) +
in[27]*(117) +
in[28]*(16) +
in[29]*(-45) +
in[30]*(-29) +
in[31]*(-12) +
(250);
out[15] =
in[0]*(37) +
in[1]*(105) +
in[2]*(-28) +
in[3]*(5) +
in[4]*(-229) +
in[5]*(6) +
in[6]*(63) +
in[7]*(-20) +
in[8]*(56) +
in[9]*(-22) +
in[10]*(-19) +
in[11]*(-33) +
in[12]*(18) +
in[13]*(4) +
in[14]*(4) +
in[15]*(-26) +
in[16]*(41) +
in[17]*(-1) +
in[18]*(15) +
in[19]*(-66) +
in[20]*(-23) +
in[21]*(15) +
in[22]*(-64) +
in[23]*(12) +
in[24]*(9) +
in[25]*(-15) +
in[26]*(-11) +
in[27]*(-177) +
in[28]*(6) +
in[29]*(15) +
in[30]*(-75) +
in[31]*(-32) +
(49);
out[16] =
in[0]*(-24) +
in[1]*(14) +
in[2]*(-3) +
in[3]*(-29) +
in[4]*(12) +
in[5]*(-12) +
in[6]*(10) +
in[7]*(-10) +
in[8]*(-24) +
in[9]*(-15) +
in[10]*(7) +
in[11]*(23) +
in[12]*(-9) +
in[13]*(-28) +
in[14]*(-10) +
in[15]*(-19) +
in[16]*(4) +
in[17]*(-12) +
in[18]*(20) +
in[19]*(2) +
in[20]*(-28) +
in[21]*(-25) +
in[22]*(-4) +
in[23]*(-5) +
in[24]*(-12) +
in[25]*(13) +
in[26]*(8) +
in[27]*(11) +
in[28]*(20) +
in[29]*(-11) +
in[30]*(-9) +
in[31]*(21) +
(-2);
out[17] =
in[0]*(-55) +
in[1]*(-19) +
in[2]*(-144) +
in[3]*(20) +
in[4]*(-2) +
in[5]*(-58) +
in[6]*(76) +
in[7]*(-90) +
in[8]*(39) +
in[9]*(13) +
in[10]*(23) +
in[11]*(-10) +
in[12]*(25) +
in[13]*(71) +
in[14]*(-13) +
in[15]*(-21) +
in[16]*(3) +
in[17]*(18) +
in[18]*(-3) +
in[19]*(1) +
in[20]*(38) +
in[21]*(-32) +
in[22]*(101) +
in[23]*(225) +
in[24]*(-32) +
in[25]*(-8) +
in[26]*(55) +
in[27]*(74) +
in[28]*(-5) +
in[29]*(23) +
in[30]*(7) +
in[31]*(-163) +
(42);
out[18] =
in[0]*(72) +
in[1]*(-3) +
in[2]*(15) +
in[3]*(-24) +
in[4]*(-63) +
in[5]*(-23) +
in[6]*(-21) +
in[7]*(24) +
in[8]*(-26) +
in[9]*(-2) +
in[10]*(80) +
in[11]*(-15) +
in[12]*(-129) +
in[13]*(-50) +
in[14]*(111) +
in[15]*(45) +
in[16]*(6) +
in[17]*(16) +
in[18]*(-77) +
in[19]*(25) +
in[20]*(9) +
in[21]*(-17) +
in[22]*(-1) +
in[23]*(-70) +
in[24]*(2) +
in[25]*(-20) +
in[26]*(-10) +
in[27]*(-29) +
in[28]*(5) +
in[29]*(-38) +
in[30]*(31) +
in[31]*(-42) +
(328);
out[19] =
in[0]*(56) +
in[1]*(-42) +
in[2]*(-134) +
in[3]*(25) +
in[4]*(-214) +
in[5]*(35) +
in[6]*(14) +
in[7]*(16) +
in[8]*(-204) +
in[9]*(27) +
in[10]*(-21) +
in[11]*(-11) +
in[12]*(-233) +
in[13]*(18) +
in[14]*(2) +
in[15]*(42) +
in[16]*(-11) +
in[17]*(-34) +
in[18]*(-176) +
in[19]*(15) +
in[20]*(159) +
in[21]*(0) +
in[22]*(113) +
in[23]*(178) +
in[24]*(-8) +
in[25]*(-7) +
in[26]*(19) +
in[27]*(42) +
in[28]*(21) +
in[29]*(-44) +
in[30]*(13) +
in[31]*(-73) +
(33);
out[20] =
in[0]*(183) +
in[1]*(-28) +
in[2]*(-68) +
in[3]*(8) +
in[4]*(-125) +
in[5]*(71) +
in[6]*(-12) +
in[7]*(58) +
in[8]*(-42) +
in[9]*(-170) +
in[10]*(-3) +
in[11]*(46) +
in[12]*(-106) +
in[13]*(45) +
in[14]*(-14) +
in[15]*(-9) +
in[16]*(-3) +
in[17]*(-32) +
in[18]*(-254) +
in[19]*(97) +
in[20]*(-1) +
in[21]*(-46) +
in[22]*(60) +
in[23]*(34) +
in[24]*(-28) +
in[25]*(-2) +
in[26]*(-34) +
in[27]*(1) +
in[28]*(12) +
in[29]*(-53) +
in[30]*(7) +
in[31]*(48) +
(103);
out[21] =
in[0]*(-26) +
in[1]*(34) +
in[2]*(2) +
in[3]*(7) +
in[4]*(-350) +
in[5]*(47) +
in[6]*(-10) +
in[7]*(15) +
in[8]*(194) +
in[9]*(46) +
in[10]*(-37) +
in[11]*(-15) +
in[12]*(-121) +
in[13]*(-69) +
in[14]*(56) +
in[15]*(-9) +
in[16]*(-26) +
in[17]*(-11) +
in[18]*(15) +
in[19]*(-121) +
in[20]*(43) +
in[21]*(16) +
in[22]*(-76) +
in[23]*(-29) +
in[24]*(-54) +
in[25]*(7) +
in[26]*(15) +
in[27]*(72) +
in[28]*(-17) +
in[29]*(22) +
in[30]*(-53) +
in[31]*(15) +
(-115);
out[22] =
in[0]*(-51) +
in[1]*(33) +
in[2]*(47) +
in[3]*(-35) +
in[4]*(-145) +
in[5]*(19) +
in[6]*(-39) +
in[7]*(46) +
in[8]*(16) +
in[9]*(-12) +
in[10]*(-15) +
in[11]*(-51) +
in[12]*(23) +
in[13]*(-7) +
in[14]*(50) +
in[15]*(45) +
in[16]*(9) +
in[17]*(-20) +
in[18]*(-148) +
in[19]*(1) +
in[20]*(45) +
in[21]*(33) +
in[22]*(93) +
in[23]*(-20) +
in[24]*(14) +
in[25]*(40) +
in[26]*(24) +
in[27]*(16) +
in[28]*(-68) +
in[29]*(18) +
in[30]*(-96) +
in[31]*(-81) +
(-97);
out[23] =
in[0]*(55) +
in[1]*(29) +
in[2]*(61) +
in[3]*(41) +
in[4]*(-21) +
in[5]*(8) +
in[6]*(-9) +
in[7]*(-6) +
in[8]*(56) +
in[9]*(-6) +
in[10]*(-20) +
in[11]*(34) +
in[12]*(-8) +
in[13]*(-18) +
in[14]*(32) +
in[15]*(-45) +
in[16]*(0) +
in[17]*(-3) +
in[18]*(104) +
in[19]*(-5) +
in[20]*(75) +
in[21]*(-59) +
in[22]*(-62) +
in[23]*(113) +
in[24]*(30) +
in[25]*(11) +
in[26]*(-95) +
in[27]*(-147) +
in[28]*(-6) +
in[29]*(-26) +
in[30]*(-28) +
in[31]*(211) +
(106);
out[24] =
in[0]*(-28) +
in[1]*(4) +
in[2]*(-53) +
in[3]*(-13) +
in[4]*(52) +
in[5]*(-10) +
in[6]*(-8) +
in[7]*(-35) +
in[8]*(90) +
in[9]*(-53) +
in[10]*(109) +
in[11]*(16) +
in[12]*(31) +
in[13]*(36) +
in[14]*(-9) +
in[15]*(30) +
in[16]*(-1) +
in[17]*(11) +
in[18]*(79) +
in[19]*(41) +
in[20]*(-229) +
in[21]*(29) +
in[22]*(-28) +
in[23]*(56) +
in[24]*(-48) +
in[25]*(-13) +
in[26]*(57) +
in[27]*(116) +
in[28]*(16) +
in[29]*(17) +
in[30]*(-25) +
in[31]*(-51) +
(-7);
out[25] =
in[0]*(-415) +
in[1]*(34) +
in[2]*(-182) +
in[3]*(-32) +
in[4]*(18) +
in[5]*(0) +
in[6]*(7) +
in[7]*(69) +
in[8]*(-16) +
in[9]*(21) +
in[10]*(-8) +
in[11]*(-9) +
in[12]*(-24) +
in[13]*(-5) +
in[14]*(8) +
in[15]*(-17) +
in[16]*(-29) +
in[17]*(-34) +
in[18]*(-60) +
in[19]*(-72) +
in[20]*(72) +
in[21]*(11) +
in[22]*(-12) +
in[23]*(-37) +
in[24]*(-15) +
in[25]*(-6) +
in[26]*(60) +
in[27]*(-139) +
in[28]*(33) +
in[29]*(21) +
in[30]*(-46) +
in[31]*(-125) +
(378);
out[26] =
in[0]*(2) +
in[1]*(-6) +
in[2]*(4) +
in[3]*(-4) +
in[4]*(5) +
in[5]*(-3) +
in[6]*(-24) +
in[7]*(-30) +
in[8]*(21) +
in[9]*(-21) +
in[10]*(16) +
in[11]*(8) +
in[12]*(-22) +
in[13]*(0) +
in[14]*(7) +
in[15]*(1) +
in[16]*(-7) +
in[17]*(-8) +
in[18]*(1) +
in[19]*(2) +
in[20]*(-26) +
in[21]*(-20) +
in[22]*(7) +
in[23]*(20) +
in[24]*(-9) +
in[25]*(0) +
in[26]*(-22) +
in[27]*(6) +
in[28]*(23) +
in[29]*(0) +
in[30]*(-15) +
in[31]*(7) +
(-5);
out[27] =
in[0]*(15) +
in[1]*(57) +
in[2]*(47) +
in[3]*(-3) +
in[4]*(28) +
in[5]*(72) +
in[6]*(33) +
in[7]*(30) +
in[8]*(-173) +
in[9]*(12) +
in[10]*(-13) +
in[11]*(-30) +
in[12]*(153) +
in[13]*(-33) +
in[14]*(-32) +
in[15]*(4) +
in[16]*(-3) +
in[17]*(-24) +
in[18]*(-47) +
in[19]*(73) +
in[20]*(123) +
in[21]*(-40) +
in[22]*(-112) +
in[23]*(-10) +
in[24]*(18) +
in[25]*(22) +
in[26]*(-31) +
in[27]*(127) +
in[28]*(50) +
in[29]*(27) +
in[30]*(-56) +
in[31]*(-171) +
(156);
out[28] =
in[0]*(-33) +
in[1]*(4) +
in[2]*(-99) +
in[3]*(18) +
in[4]*(-59) +
in[5]*(17) +
in[6]*(23) +
in[7]*(-69) +
in[8]*(70) +
in[9]*(9) +
in[10]*(-147) +
in[11]*(-31) +
in[12]*(-18) +
in[13]*(8) +
in[14]*(-28) +
in[15]*(-62) +
in[16]*(-28) +
in[17]*(-13) +
in[18]*(223) +
in[19]*(-57) +
in[20]*(13) +
in[21]*(-21) +
in[22]*(84) +
in[23]*(33) +
in[24]*(-78) +
in[25]*(33) +
in[26]*(126) +
in[27]*(-14) +
in[28]*(-21) +
in[29]*(0) +
in[30]*(55) +
in[31]*(-27) +
(240);
out[29] =
in[0]*(-229) +
in[1]*(55) +
in[2]*(-19) +
in[3]*(-8) +
in[4]*(-9) +
in[5]*(-8) +
in[6]*(26) +
in[7]*(-7) +
in[8]*(-118) +
in[9]*(56) +
in[10]*(27) +
in[11]*(-10) +
in[12]*(76) +
in[13]*(25) +
in[14]*(-3) +
in[15]*(54) +
in[16]*(24) +
in[17]*(-4) +
in[18]*(-9) +
in[19]*(-59) +
in[20]*(-33) +
in[21]*(9) +
in[22]*(13) +
in[23]*(18) +
in[24]*(51) +
in[25]*(3) +
in[26]*(-93) +
in[27]*(49) +
in[28]*(0) +
in[29]*(-13) +
in[30]*(-41) +
in[31]*(99) +
(-83);
out[30] =
in[0]*(-72) +
in[1]*(-19) +
in[2]*(22) +
in[3]*(11) +
in[4]*(-112) +
in[5]*(0) +
in[6]*(-235) +
in[7]*(-147) +
in[8]*(6) +
in[9]*(-10) +
in[10]*(-58) +
in[11]*(8) +
in[12]*(-22) +
in[13]*(5) +
in[14]*(-27) +
in[15]*(10) +
in[16]*(-8) +
in[17]*(9) +
in[18]*(-95) +
in[19]*(-1) +
in[20]*(-155) +
in[21]*(-27) +
in[22]*(-196) +
in[23]*(-15) +
in[24]*(-5) +
in[25]*(37) +
in[26]*(-14) +
in[27]*(-10) +
in[28]*(50) +
in[29]*(-44) +
in[30]*(41) +
in[31]*(-27) +
(398);
out[31] =
in[0]*(152) +
in[1]*(14) +
in[2]*(233) +
in[3]*(17) +
in[4]*(42) +
in[5]*(-25) +
in[6]*(-13) +
in[7]*(-50) +
in[8]*(71) +
in[9]*(11) +
in[10]*(-15) +
in[11]*(9) +
in[12]*(-108) +
in[13]*(-12) +
in[14]*(-19) +
in[15]*(55) +
in[16]*(47) +
in[17]*(-43) +
in[18]*(-95) +
in[19]*(47) +
in[20]*(13) +
in[21]*(22) +
in[22]*(20) +
in[23]*(-37) +
in[24]*(-14) +
in[25]*(10) +
in[26]*(13) +
in[27]*(-49) +
in[28]*(22) +
in[29]*(9) +
in[30]*(-14) +
in[31]*(-67) +
(-130);
out[32] =
in[0]*(-33) +
in[1]*(23) +
in[2]*(63) +
in[3]*(-17) +
in[4]*(-38) +
in[5]*(-12) +
in[6]*(-25) +
in[7]*(24) +
in[8]*(-128) +
in[9]*(44) +
in[10]*(-55) +
in[11]*(-31) +
in[12]*(66) +
in[13]*(3) +
in[14]*(-30) +
in[15]*(36) +
in[16]*(10) +
in[17]*(1) +
in[18]*(77) +
in[19]*(34) +
in[20]*(46) +
in[21]*(-24) +
in[22]*(40) +
in[23]*(-12) +
in[24]*(-1) +
in[25]*(35) +
in[26]*(-14) +
in[27]*(-7) +
in[28]*(27) +
in[29]*(-42) +
in[30]*(22) +
in[31]*(20) +
(465);
out[33] =
in[0]*(38) +
in[1]*(-8) +
in[2]*(-27) +
in[3]*(53) +
in[4]*(-16) +
in[5]*(5) +
in[6]*(100) +
in[7]*(-4) +
in[8]*(14) +
in[9]*(-14) +
in[10]*(27) +
in[11]*(3) +
in[12]*(64) +
in[13]*(-24) +
in[14]*(-28) +
in[15]*(-43) +
in[16]*(26) +
in[17]*(-46) +
in[18]*(-128) +
in[19]*(-47) +
in[20]*(-51) +
in[21]*(13) +
in[22]*(-94) +
in[23]*(37) +
in[24]*(-20) +
in[25]*(-8) +
in[26]*(-15) +
in[27]*(98) +
in[28]*(-23) +
in[29]*(35) +
in[30]*(-10) +
in[31]*(146) +
(219);
out[34] =
in[0]*(-75) +
in[1]*(-15) +
in[2]*(-11) +
in[3]*(20) +
in[4]*(-117) +
in[5]*(-18) +
in[6]*(28) +
in[7]*(18) +
in[8]*(-71) +
in[9]*(-8) +
in[10]*(28) +
in[11]*(-27) +
in[12]*(108) +
in[13]*(18) +
in[14]*(-52) +
in[15]*(74) +
in[16]*(-19) +
in[17]*(14) +
in[18]*(-332) +
in[19]*(23) +
in[20]*(-19) +
in[21]*(-28) +
in[22]*(-58) +
in[23]*(-33) +
in[24]*(-35) +
in[25]*(-10) +
in[26]*(80) +
in[27]*(-56) +
in[28]*(-7) +
in[29]*(78) +
in[30]*(-2) +
in[31]*(18) +
(-6);
out[35] =
in[0]*(99) +
in[1]*(-6) +
in[2]*(52) +
in[3]*(6) +
in[4]*(50) +
in[5]*(-5) +
in[6]*(-34) +
in[7]*(-27) +
in[8]*(-77) +
in[9]*(32) +
in[10]*(-30) +
in[11]*(6) +
in[12]*(16) +
in[13]*(-35) +
in[14]*(22) +
in[15]*(-40) +
in[16]*(36) +
in[17]*(-13) +
in[18]*(-127) +
in[19]*(-55) +
in[20]*(-92) +
in[21]*(34) +
in[22]*(-130) +
in[23]*(28) +
in[24]*(20) +
in[25]*(-38) +
in[26]*(-166) +
in[27]*(-46) +
in[28]*(-23) +
in[29]*(-2) +
in[30]*(37) +
in[31]*(31) +
(334);
out[36] =
in[0]*(6) +
in[1]*(-4) +
in[2]*(-8) +
in[3]*(-8) +
in[4]*(13) +
in[5]*(-17) +
in[6]*(17) +
in[7]*(-16) +
in[8]*(-2) +
in[9]*(-25) +
in[10]*(-8) +
in[11]*(22) +
in[12]*(-25) +
in[13]*(-8) +
in[14]*(-11) +
in[15]*(-4) +
in[16]*(-5) +
in[17]*(-14) +
in[18]*(4) +
in[19]*(-7) +
in[20]*(-14) +
in[21]*(-15) +
in[22]*(9) +
in[23]*(23) +
in[24]*(-15) +
in[25]*(-9) +
in[26]*(-7) +
in[27]*(-11) +
in[28]*(-24) +
in[29]*(-14) +
in[30]*(-25) +
in[31]*(13) +
(0);
out[37] =
in[0]*(97) +
in[1]*(36) +
in[2]*(-37) +
in[3]*(-1) +
in[4]*(26) +
in[5]*(-36) +
in[6]*(-39) +
in[7]*(-68) +
in[8]*(-9) +
in[9]*(-65) +
in[10]*(37) +
in[11]*(-5) +
in[12]*(10) +
in[13]*(43) +
in[14]*(-79) +
in[15]*(-6) +
in[16]*(27) +
in[17]*(33) +
in[18]*(-10) +
in[19]*(65) +
in[20]*(-33) +
in[21]*(-25) +
in[22]*(-53) +
in[23]*(-53) +
in[24]*(-13) +
in[25]*(60) +
in[26]*(56) +
in[27]*(48) +
in[28]*(-2) +
in[29]*(4) +
in[30]*(30) +
in[31]*(-77) +
(-121);
out[38] =
in[0]*(-107) +
in[1]*(-39) +
in[2]*(171) +
in[3]*(-2) +
in[4]*(-64) +
in[5]*(-5) +
in[6]*(-58) +
in[7]*(68) +
in[8]*(14) +
in[9]*(18) +
in[10]*(23) +
in[11]*(-12) +
in[12]*(50) +
in[13]*(23) +
in[14]*(10) +
in[15]*(38) +
in[16]*(-30) +
in[17]*(19) +
in[18]*(-129) +
in[19]*(7) +
in[20]*(49) +
in[21]*(4) +
in[22]*(10) +
in[23]*(-68) +
in[24]*(6) +
in[25]*(21) +
in[26]*(-21) +
in[27]*(3) +
in[28]*(-62) +
in[29]*(4) +
in[30]*(28) +
in[31]*(46) +
(-370);
out[39] =
in[0]*(187) +
in[1]*(48) +
in[2]*(6) +
in[3]*(24) +
in[4]*(148) +
in[5]*(-7) +
in[6]*(-4) +
in[7]*(-105) +
in[8]*(10) +
in[9]*(14) +
in[10]*(-53) +
in[11]*(14) +
in[12]*(8) +
in[13]*(-12) +
in[14]*(-60) +
in[15]*(-95) +
in[16]*(37) +
in[17]*(-33) +
in[18]*(123) +
in[19]*(7) +
in[20]*(-3) +
in[21]*(13) +
in[22]*(78) +
in[23]*(26) +
in[24]*(6) +
in[25]*(-9) +
in[26]*(-17) +
in[27]*(-142) +
in[28]*(22) +
in[29]*(43) +
in[30]*(22) +
in[31]*(140) +
(90);
out[40] =
in[0]*(8) +
in[1]*(5) +
in[2]*(22) +
in[3]*(7) +
in[4]*(16) +
in[5]*(-32) +
in[6]*(16) +
in[7]*(-52) +
in[8]*(31) +
in[9]*(-1) +
in[10]*(-100) +
in[11]*(-28) +
in[12]*(2) +
in[13]*(-24) +
in[14]*(-1) +
in[15]*(-14) +
in[16]*(7) +
in[17]*(5) +
in[18]*(147) +
in[19]*(-37) +
in[20]*(-125) +
in[21]*(-17) +
in[22]*(-104) +
in[23]*(8) +
in[24]*(7) +
in[25]*(-11) +
in[26]*(8) +
in[27]*(-59) +
in[28]*(16) +
in[29]*(19) +
in[30]*(-9) +
in[31]*(30) +
(521);
out[41] =
in[0]*(208) +
in[1]*(-42) +
in[2]*(48) +
in[3]*(-14) +
in[4]*(67) +
in[5]*(-23) +
in[6]*(19) +
in[7]*(27) +
in[8]*(141) +
in[9]*(-1) +
in[10]*(-50) +
in[11]*(26) +
in[12]*(-85) +
in[13]*(-8) +
in[14]*(23) +
in[15]*(-20) +
in[16]*(-66) +
in[17]*(28) +
in[18]*(-34) +
in[19]*(59) +
in[20]*(-49) +
in[21]*(29) +
in[22]*(-28) +
in[23]*(-60) +
in[24]*(-18) +
in[25]*(-78) +
in[26]*(-30) +
in[27]*(-63) +
in[28]*(-28) +
in[29]*(45) +
in[30]*(-13) +
in[31]*(56) +
(227);
out[42] =
in[0]*(-17) +
in[1]*(-17) +
in[2]*(6) +
in[3]*(-48) +
in[4]*(-121) +
in[5]*(0) +
in[6]*(15) +
in[7]*(69) +
in[8]*(40) +
in[9]*(30) +
in[10]*(-33) +
in[11]*(4) +
in[12]*(-53) +
in[13]*(7) +
in[14]*(12) +
in[15]*(-49) +
in[16]*(-19) +
in[17]*(35) +
in[18]*(-146) +
in[19]*(96) +
in[20]*(43) +
in[21]*(-17) +
in[22]*(52) +
in[23]*(10) +
in[24]*(-91) +
in[25]*(-15) +
in[26]*(68) +
in[27]*(54) +
in[28]*(4) +
in[29]*(27) +
in[30]*(15) +
in[31]*(126) +
(227);
out[43] =
in[0]*(-231) +
in[1]*(-23) +
in[2]*(-37) +
in[3]*(7) +
in[4]*(-26) +
in[5]*(13) +
in[6]*(22) +
in[7]*(-43) +
in[8]*(-36) +
in[9]*(34) +
in[10]*(-34) +
in[11]*(-33) +
in[12]*(-39) +
in[13]*(-41) +
in[14]*(-28) +
in[15]*(20) +
in[16]*(9) +
in[17]*(-36) +
in[18]*(-217) +
in[19]*(-8) +
in[20]*(-65) +
in[21]*(11) +
in[22]*(-141) +
in[23]*(-47) +
in[24]*(17) +
in[25]*(77) +
in[26]*(44) +
in[27]*(-28) +
in[28]*(-6) +
in[29]*(10) +
in[30]*(-25) +
in[31]*(-23) +
(-325);
out[44] =
in[0]*(58) +
in[1]*(-70) +
in[2]*(1) +
in[3]*(62) +
in[4]*(39) +
in[5]*(18) +
in[6]*(35) +
in[7]*(-106) +
in[8]*(-404) +
in[9]*(-18) +
in[10]*(17) +
in[11]*(14) +
in[12]*(3) +
in[13]*(-16) +
in[14]*(25) +
in[15]*(-46) +
in[16]*(23) +
in[17]*(-40) +
in[18]*(102) +
in[19]*(-81) +
in[20]*(52) +
in[21]*(-11) +
in[22]*(-83) +
in[23]*(29) +
in[24]*(30) +
in[25]*(-21) +
in[26]*(-8) +
in[27]*(17) +
in[28]*(-11) +
in[29]*(23) +
in[30]*(-24) +
in[31]*(2) +
(273);
out[45] =
in[0]*(14) +
in[1]*(-23) +
in[2]*(-24) +
in[3]*(-24) +
in[4]*(1) +
in[5]*(-2) +
in[6]*(11) +
in[7]*(-3) +
in[8]*(-74) +
in[9]*(-11) +
in[10]*(-32) +
in[11]*(20) +
in[12]*(65) +
in[13]*(-4) +
in[14]*(-27) +
in[15]*(-1) +
in[16]*(-8) +
in[17]*(26) +
in[18]*(97) +
in[19]*(60) +
in[20]*(55) +
in[21]*(-18) +
in[22]*(118) +
in[23]*(-69) +
in[24]*(-14) +
in[25]*(-13) +
in[26]*(-22) +
in[27]*(-45) +
in[28]*(-12) +
in[29]*(72) +
in[30]*(34) +
in[31]*(16) +
(-404);
out[46] =
in[0]*(17) +
in[1]*(1) +
in[2]*(21) +
in[3]*(11) +
in[4]*(9) +
in[5]*(-22) +
in[6]*(-24) +
in[7]*(8) +
in[8]*(-15) +
in[9]*(-7) +
in[10]*(-26) +
in[11]*(18) +
in[12]*(12) +
in[13]*(-5) +
in[14]*(15) +
in[15]*(-7) +
in[16]*(-2) +
in[17]*(-8) +
in[18]*(19) +
in[19]*(-13) +
in[20]*(12) +
in[21]*(-21) +
in[22]*(9) +
in[23]*(-6) +
in[24]*(-15) +
in[25]*(-9) +
in[26]*(-3) +
in[27]*(20) +
in[28]*(-13) +
in[29]*(-29) +
in[30]*(-21) +
in[31]*(-7) +
(-4);
out[47] =
in[0]*(48) +
in[1]*(-11) +
in[2]*(154) +
in[3]*(-11) +
in[4]*(-65) +
in[5]*(13) +
in[6]*(-41) +
in[7]*(27) +
in[8]*(-64) +
in[9]*(15) +
in[10]*(-81) +
in[11]*(-38) +
in[12]*(158) +
in[13]*(27) +
in[14]*(26) +
in[15]*(-64) +
in[16]*(-29) +
in[17]*(31) +
in[18]*(6) +
in[19]*(136) +
in[20]*(150) +
in[21]*(-44) +
in[22]*(85) +
in[23]*(-66) +
in[24]*(16) +
in[25]*(-3) +
in[26]*(-67) +
in[27]*(-150) +
in[28]*(-31) +
in[29]*(29) +
in[30]*(27) +
in[31]*(-48) +
(238);
out[48] =
in[0]*(153) +
in[1]*(-5) +
in[2]*(134) +
in[3]*(15) +
in[4]*(-8) +
in[5]*(-9) +
in[6]*(51) +
in[7]*(9) +
in[8]*(-187) +
in[9]*(-29) +
in[10]*(39) +
in[11]*(-24) +
in[12]*(124) +
in[13]*(-156) +
in[14]*(29) +
in[15]*(48) +
in[16]*(28) +
in[17]*(-16) +
in[18]*(30) +
in[19]*(41) +
in[20]*(37) +
in[21]*(-29) +
in[22]*(9) +
in[23]*(8) +
in[24]*(65) +
in[25]*(26) +
in[26]*(37) +
in[27]*(-45) +
in[28]*(-33) +
in[29]*(-2) +
in[30]*(26) +
in[31]*(-12) +
(-153);
out[49] =
in[0]*(-70) +
in[1]*(-11) +
in[2]*(15) +
in[3]*(9) +
in[4]*(71) +
in[5]*(32) +
in[6]*(-98) +
in[7]*(-103) +
in[8]*(93) +
in[9]*(1) +
in[10]*(-25) +
in[11]*(31) +
in[12]*(-72) +
in[13]*(22) +
in[14]*(77) +
in[15]*(-22) +
in[16]*(-17) +
in[17]*(3) +
in[18]*(-21) +
in[19]*(-9) +
in[20]*(78) +
in[21]*(17) +
in[22]*(127) +
in[23]*(59) +
in[24]*(-1) +
in[25]*(12) +
in[26]*(-55) +
in[27]*(84) +
in[28]*(8) +
in[29]*(-73) +
in[30]*(-19) +
in[31]*(41) +
(55);
}
inline void fc_2(int in[50], int out[10]){
out[0] =
in[0]*(14) +
in[1]*(6) +
in[2]*(-22) +
in[3]*(35) +
in[4]*(51) +
in[5]*(-53) +
in[6]*(-182) +
in[7]*(-7) +
in[8]*(-26) +
in[9]*(-49) +
in[10]*(-12) +
in[11]*(-37) +
in[12]*(-7) +
in[13]*(31) +
in[14]*(-8) +
in[15]*(40) +
in[16]*(29) +
in[17]*(-40) +
in[18]*(-54) +
in[19]*(-44) +
in[20]*(-1028) +
in[21]*(19) +
in[22]*(-7) +
in[23]*(6) +
in[24]*(-42) +
in[25]*(-55) +
in[26]*(14) +
in[27]*(-27) +
in[28]*(11) +
in[29]*(-7) +
in[30]*(-97) +
in[31]*(-62) +
in[32]*(-8) +
in[33]*(-3) +
in[34]*(-39) +
in[35]*(-11) +
in[36]*(-9) +
in[37]*(0) +
in[38]*(33) +
in[39]*(-14) +
in[40]*(-85) +
in[41]*(-32) +
in[42]*(-3) +
in[43]*(-6) +
in[44]*(28) +
in[45]*(58) +
in[46]*(-7) +
in[47]*(12) +
in[48]*(25) +
in[49]*(-53) +
(-21320);
out[1] =
in[0]*(-40) +
in[1]*(27) +
in[2]*(21) +
in[3]*(14) +
in[4]*(9) +
in[5]*(-14) +
in[6]*(-121) +
in[7]*(-33) +
in[8]*(-104) +
in[9]*(2) +
in[10]*(5) +
in[11]*(-15) +
in[12]*(-44) +
in[13]*(-28) +
in[14]*(9) +
in[15]*(25) +
in[16]*(23) +
in[17]*(-22) +
in[18]*(-13) +
in[19]*(-63) +
in[20]*(-321) +
in[21]*(-43) +
in[22]*(-13) +
in[23]*(-72) +
in[24]*(-36) +
in[25]*(-12) +
in[26]*(-11) +
in[27]*(3) +
in[28]*(22) +
in[29]*(41) +
in[30]*(-52) +
in[31]*(-37) +
in[32]*(11) +
in[33]*(-50) +
in[34]*(0) +
in[35]*(29) +
in[36]*(2) +
in[37]*(0) +
in[38]*(-29) +
in[39]*(47) +
in[40]*(26) +
in[41]*(1) +
in[42]*(49) +
in[43]*(6) +
in[44]*(-106) +
in[45]*(-69) +
in[46]*(-15) +
in[47]*(72) +
in[48]*(-1) +
in[49]*(-40) +
(38749);
out[2] =
in[0]*(-11) +
in[1]*(7) +
in[2]*(-20) +
in[3]*(-28) +
in[4]*(12) +
in[5]*(6) +
in[6]*(-93) +
in[7]*(-40) +
in[8]*(12) +
in[9]*(22) +
in[10]*(-8) +
in[11]*(-33) +
in[12]*(-42) +
in[13]*(5) +
in[14]*(-1) +
in[15]*(30) +
in[16]*(2) +
in[17]*(10) +
in[18]*(-29) +
in[19]*(-36) +
in[20]*(-840) +
in[21]*(-44) +
in[22]*(-22) +
in[23]*(-27) +
in[24]*(-2) +
in[25]*(41) +
in[26]*(-17) +
in[27]*(19) +
in[28]*(-32) +
in[29]*(19) +
in[30]*(-82) +
in[31]*(-11) +
in[32]*(-19) +
in[33]*(-11) +
in[34]*(-26) +
in[35]*(-37) +
in[36]*(-15) +
in[37]*(-42) +
in[38]*(42) +
in[39]*(-2) +
in[40]*(-46) +
in[41]*(12) +
in[42]*(-6) +
in[43]*(14) +
in[44]*(40) +
in[45]*(7) +
in[46]*(14) +
in[47]*(-40) +
in[48]*(-38) +
in[49]*(-16) +
(-11896);
out[3] =
in[0]*(31) +
in[1]*(-13) +
in[2]*(-17) +
in[3]*(-57) +
in[4]*(4) +
in[5]*(6) +
in[6]*(-62) +
in[7]*(-41) +
in[8]*(-29) +
in[9]*(-29) +
in[10]*(10) +
in[11]*(20) +
in[12]*(-35) +
in[13]*(11) +
in[14]*(10) +
in[15]*(-21) +
in[16]*(-14) +
in[17]*(-35) +
in[18]*(24) +
in[19]*(7) +
in[20]*(-110) +
in[21]*(8) +
in[22]*(-25) +
in[23]*(-16) +
in[24]*(-13) +
in[25]*(-29) +
in[26]*(1) +
in[27]*(-44) +
in[28]*(-52) +
in[29]*(13) +
in[30]*(18) +
in[31]*(-41) +
in[32]*(8) +
in[33]*(-4) +
in[34]*(-6) +
in[35]*(-44) +
in[36]*(11) +
in[37]*(-5) +
in[38]*(8) +
in[39]*(-11) +
in[40]*(19) +
in[41]*(-23) +
in[42]*(-15) +
in[43]*(26) +
in[44]*(-26) +
in[45]*(29) +
in[46]*(11) +
in[47]*(-21) +
in[48]*(-14) +
in[49]*(-7) +
(-921);
out[4] =
in[0]*(-31) +
in[1]*(30) +
in[2]*(14) +
in[3]*(-43) +
in[4]*(-30) +
in[5]*(-1) +
in[6]*(1) +
in[7]*(21) +
in[8]*(25) +
in[9]*(-41) +
in[10]*(-1) +
in[11]*(-6) +
in[12]*(5) +
in[13]*(29) +
in[14]*(12) +
in[15]*(-11) +
in[16]*(6) +
in[17]*(5) +
in[18]*(-13) +
in[19]*(-61) +
in[20]*(-20) +
in[21]*(0) +
in[22]*(-10) +
in[23]*(-16) +
in[24]*(6) +
in[25]*(26) +
in[26]*(5) +
in[27]*(-25) +
in[28]*(13) +
in[29]*(2) +
in[30]*(25) +
in[31]*(-23) +
in[32]*(-45) +
in[33]*(-33) +
in[34]*(-27) +
in[35]*(-6) +
in[36]*(27) +
in[37]*(-3) +
in[38]*(-52) +
in[39]*(12) +
in[40]*(-77) +
in[41]*(22) +
in[42]*(-11) +
in[43]*(-41) +
in[44]*(-2) +
in[45]*(-16) +
in[46]*(10) +
in[47]*(-28) +
in[48]*(-37) +
in[49]*(17) +
(-5652);
out[5] =
in[0]*(-3) +
in[1]*(-13) +
in[2]*(13) +
in[3]*(-25) +
in[4]*(-15) +
in[5]*(-12) +
in[6]*(-48) +
in[7]*(2) +
in[8]*(-17) +
in[9]*(11) +
in[10]*(-26) +
in[11]*(0) +
in[12]*(-21) +
in[13]*(-1) +
in[14]*(43) +
in[15]*(11) +
in[16]*(9) +
in[17]*(-36) +
in[18]*(14) +
in[19]*(0) +
in[20]*(-45) +
in[21]*(0) +
in[22]*(4) +
in[23]*(0) +
in[24]*(-44) +
in[25]*(-49) +
in[26]*(-20) +
in[27]*(-49) +
in[28]*(-45) +
in[29]*(-32) +
in[30]*(6) +
in[31]*(13) +
in[32]*(25) +
in[33]*(21) +
in[34]*(-11) +
in[35]*(-2) +
in[36]*(-4) +
in[37]*(-3) +
in[38]*(8) +
in[39]*(-24) +
in[40]*(34) +
in[41]*(-37) +
in[42]*(0) +
in[43]*(-7) +
in[44]*(-39) +
in[45]*(40) +
in[46]*(16) +
in[47]*(-2) +
in[48]*(-28) +
in[49]*(-14) +
(-7859);
out[6] =
in[0]*(18) +
in[1]*(-1) +
in[2]*(-10) +
in[3]*(-50) +
in[4]*(-24) +
in[5]*(-20) +
in[6]*(-582) +
in[7]*(18) +
in[8]*(-10) +
in[9]*(-82) +
in[10]*(-53) +
in[11]*(-35) +
in[12]*(25) +
in[13]*(21) +
in[14]*(-36) +
in[15]*(16) +
in[16]*(20) +
in[17]*(-46) +
in[18]*(-82) +
in[19]*(-7) +
in[20]*(-934) +
in[21]*(22) +
in[22]*(-28) +
in[23]*(-45) +
in[24]*(6) +
in[25]*(-6) +
in[26]*(-8) +
in[27]*(-40) +
in[28]*(3) +
in[29]*(-11) +
in[30]*(-57) +
in[31]*(3) +
in[32]*(-1) +
in[33]*(10) +
in[34]*(-48) +
in[35]*(31) +
in[36]*(28) +
in[37]*(-20) +
in[38]*(-31) +
in[39]*(-17) +
in[40]*(-4) +
in[41]*(-26) +
in[42]*(34) +
in[43]*(24) +
in[44]*(-41) +
in[45]*(-52) +
in[46]*(-9) +
in[47]*(31) +
in[48]*(5) +
in[49]*(-43) +
(17341);
out[7] =
in[0]*(23) +
in[1]*(-8) +
in[2]*(-14) +
in[3]*(11) +
in[4]*(34) +
in[5]*(-3) +
in[6]*(-68) +
in[7]*(-31) +
in[8]*(2) +
in[9]*(11) +
in[10]*(-7) +
in[11]*(-15) +
in[12]*(8) +
in[13]*(-10) +
in[14]*(-19) +
in[15]*(-27) +
in[16]*(0) +
in[17]*(3) +
in[18]*(-39) +
in[19]*(-62) +
in[20]*(15) +
in[21]*(-41) +
in[22]*(39) +
in[23]*(-66) +
in[24]*(-26) +
in[25]*(-13) +
in[26]*(11) +
in[27]*(-2) +
in[28]*(-23) +
in[29]*(-7) +
in[30]*(-43) +
in[31]*(-36) +
in[32]*(34) +
in[33]*(27) +
in[34]*(-31) +
in[35]*(-20) +
in[36]*(-24) +
in[37]*(18) +
in[38]*(-9) +
in[39]*(-7) +
in[40]*(-93) +
in[41]*(-21) +
in[42]*(-38) +
in[43]*(-19) +
in[44]*(12) +
in[45]*(-24) +
in[46]*(-8) +
in[47]*(1) +
in[48]*(-53) +
in[49]*(36) +
(12408);
out[8] =
in[0]*(5) +
in[1]*(2) +
in[2]*(-11) +
in[3]*(-34) +
in[4]*(1) +
in[5]*(-30) +
in[6]*(-85) +
in[7]*(1) +
in[8]*(40) +
in[9]*(-58) +
in[10]*(16) +
in[11]*(29) +
in[12]*(-47) +
in[13]*(6) +
in[14]*(0) +
in[15]*(7) +
in[16]*(-34) +
in[17]*(-35) +
in[18]*(-35) +
in[19]*(-32) +
in[20]*(-181) +
in[21]*(-21) +
in[22]*(-17) +
in[23]*(-27) +
in[24]*(14) +
in[25]*(-29) +
in[26]*(17) +
in[27]*(-28) +
in[28]*(-32) +
in[29]*(-21) +
in[30]*(-56) +
in[31]*(-20) +
in[32]*(-65) +
in[33]*(3) +
in[34]*(31) +
in[35]*(-26) +
in[36]*(-8) +
in[37]*(-9) +
in[38]*(9) +
in[39]*(-5) +
in[40]*(27) +
in[41]*(-30) +
in[42]*(17) +
in[43]*(-33) +
in[44]*(2) +
in[45]*(-6) +
in[46]*(-15) +
in[47]*(-19) +
in[48]*(-18) +
in[49]*(-26) +
(-16309);
out[9] =
in[0]*(27) +
in[1]*(40) +
in[2]*(-2) +
in[3]*(-42) +
in[4]*(-11) +
in[5]*(-47) +
in[6]*(-25) +
in[7]*(-10) +
in[8]*(0) +
in[9]*(-33) +
in[10]*(0) +
in[11]*(1) +
in[12]*(20) +
in[13]*(22) +
in[14]*(29) +
in[15]*(-14) +
in[16]*(12) +
in[17]*(-4) +
in[18]*(-45) +
in[19]*(-49) +
in[20]*(-245) +
in[21]*(-15) +
in[22]*(-21) +
in[23]*(-17) +
in[24]*(-2) +
in[25]*(-19) +
in[26]*(19) +
in[27]*(-14) +
in[28]*(-39) +
in[29]*(-30) +
in[30]*(49) +
in[31]*(-46) +
in[32]*(-9) +
in[33]*(-36) +
in[34]*(-19) +
in[35]*(-20) +
in[36]*(30) +
in[37]*(-26) +
in[38]*(29) +
in[39]*(52) +
in[40]*(-86) +
in[41]*(-52) +
in[42]*(1) +
in[43]*(-36) +
in[44]*(-20) +
in[45]*(-13) +
in[46]*(-3) +
in[47]*(-31) +
in[48]*(-7) +
in[49]*(24) +
(2658);
}
#endif /* FC_WEIGHTS_HPP_ */
| 16.779911 | 44 | 0.329156 | brouwa |
942129a8633c59263f489a8e2a0a503085954125 | 636 | hpp | C++ | include/sp/algo/nn/config.hpp | thorigin/sp | a837b4fcb5b7184591585082012942bbdb8f11f9 | [
"FSFAP"
] | null | null | null | include/sp/algo/nn/config.hpp | thorigin/sp | a837b4fcb5b7184591585082012942bbdb8f11f9 | [
"FSFAP"
] | null | null | null | include/sp/algo/nn/config.hpp | thorigin/sp | a837b4fcb5b7184591585082012942bbdb8f11f9 | [
"FSFAP"
] | null | null | null | /**
* Copyright (C) Omar Thor <[email protected]> - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*
* Written by Omar Thor <[email protected]>, 2017
*/
#ifndef SP_ALGO_NN_CONFIG_HPP
#define SP_ALGO_NN_CONFIG_HPP
#include <cmath>
#include "sp/config.hpp"
SP_ALGO_NN_NAMESPACE_BEGIN
#ifndef NN_FLOAT_TYPE
#define NN_FLOAT_TYPE std::float_t
#endif
#ifndef SP_ALGO_NN_RANDOM_GENERATOR
#define SP_ALGO_NN_RANDOM_GENERATOR std::mt19937
#endif
using float_t = NN_FLOAT_TYPE;
SP_ALGO_NN_NAMESPACE_END
#endif /* SP_ALGO_NN_CONFIG_HPP */
| 19.875 | 75 | 0.779874 | thorigin |
942b7a2a4945141ddc9dac7b8aa3403257e91cb9 | 525 | cpp | C++ | http/src/EHttpMethod.cpp | developkits/CxxMina | 705734fccc5ef87c7faa385b77cd1e67c46c5c75 | [
"Apache-2.0"
] | 7 | 2016-08-25T14:22:36.000Z | 2020-05-25T17:27:51.000Z | http/src/EHttpMethod.cpp | developkits/CxxMina | 705734fccc5ef87c7faa385b77cd1e67c46c5c75 | [
"Apache-2.0"
] | 1 | 2018-07-11T12:37:55.000Z | 2018-07-12T00:05:33.000Z | http/src/EHttpMethod.cpp | developkits/CxxMina | 705734fccc5ef87c7faa385b77cd1e67c46c5c75 | [
"Apache-2.0"
] | 2 | 2017-06-09T01:22:36.000Z | 2021-09-29T16:27:58.000Z | /*
* EHttpMethod.cpp
*
* Created on: 2017-1-4
* Author: [email protected]
*/
#include "../inc/EHttpMethod.hh"
namespace efc {
namespace eio {
EHttpMethod EHttpMethod::GET("GET");
EHttpMethod EHttpMethod::HEAD("HEAD");
EHttpMethod EHttpMethod::POST("POST");
EHttpMethod EHttpMethod::PUT("PUT");
EHttpMethod EHttpMethod::DELETE("DELETE");
EHttpMethod EHttpMethod::OPTIONS("OPTIONS");
EHttpMethod EHttpMethod::TRACE("TRACE");
EHttpMethod EHttpMethod::CONNECT("CONNECT");
} /* namespace eio */
} /* namespace efc */
| 21.875 | 44 | 0.710476 | developkits |
942cfb9e5f2cb3eb58bc2f8300704fb1b333e30c | 1,571 | cc | C++ | sdios/src/ram_dsm/main.cc | NeoLeMarc/sdios | 24630c16dfabab008891a354e2f49088d0d0a369 | [
"BSD-2-Clause"
] | null | null | null | sdios/src/ram_dsm/main.cc | NeoLeMarc/sdios | 24630c16dfabab008891a354e2f49088d0d0a369 | [
"BSD-2-Clause"
] | null | null | null | sdios/src/ram_dsm/main.cc | NeoLeMarc/sdios | 24630c16dfabab008891a354e2f49088d0d0a369 | [
"BSD-2-Clause"
] | null | null | null | //
// File: src/ram_dsm/main.cc
//
// Description: RAM-DataspaceManager
//
#include <l4/thread.h>
#include <l4/sigma0.h>
#include <l4io.h>
#include <sdi/types.h>
#include <sdi/sdi.h>
#include <idl4glue.h>
#include <if/iflocator.h>
#include <if/iflogging.h>
#include "ram_dsm.h"
L4_ThreadId_t sigma0_id = L4_nilthread;
// Bitmap to store available state
// calculate bitmap size via RAM size / 4KB (page size) / 32 (bits per word)
#define AVAILABLE_BITMAP_SIZE 256
L4_Word_t available[AVAILABLE_BITMAP_SIZE];
int main () {
printf ("[RAM-DSM] is alive\n");
// Initiate sigma0_id
L4_KernelInterfacePage_t * kip = (L4_KernelInterfacePage_t *)
L4_GetKernelInterface ();
sigma0_id = L4_GlobalId (kip->ThreadInfo.X.UserBase, 1);
// Try to get whole memory from sigma0
// We are starting at 1 MB, because we do
// not want to fiddle around with architecture
// specific stuff like EBDA etc. IO-DSM has to
// take this memory later.
for (L4_Word_t i = 0x01000UL; i < 0x02000UL; i++) {
// page size is 2^12 byte
if (!L4_IsNilFpage(L4_Sigma0_GetAny(L4_nilthread, 12, L4_FpageLog2(i << 12, 12)))) {
// 2^5 bits per word
available[i >> 5] |= (1UL << (i & 0x1fUL));
}
}
// Start BI-ELF-Loader
bielfloader_server(available);
printf("[RAM-DSM] Oooooooops, your ELF-Loader just died!\n");
/* Start Pager */
// printf("Starting pager...\n");
// pager_server();
// printf("Oooops, your pager just died!\n");
/* Spin forever */
while (42);
return 0;
}
| 25.33871 | 90 | 0.644812 | NeoLeMarc |
942dcee35ec86a7347eb0d231e13e9479d5012f1 | 495 | cpp | C++ | src/storm/color.cpp | vanderlokken/storm | 462a783fb780b290149acf0d75c4b3b837a97325 | [
"MIT"
] | 2 | 2016-11-17T20:48:08.000Z | 2018-04-28T22:41:12.000Z | src/storm/color.cpp | vanderlokken/storm | 462a783fb780b290149acf0d75c4b3b837a97325 | [
"MIT"
] | null | null | null | src/storm/color.cpp | vanderlokken/storm | 462a783fb780b290149acf0d75c4b3b837a97325 | [
"MIT"
] | 1 | 2016-10-19T03:07:58.000Z | 2016-10-19T03:07:58.000Z | #include <storm/color.h>
namespace storm {
const Color Color::Black( 0, 0, 0, 1 );
const Color Color::White( 1, 1, 1, 1 );
const Color Color::BlackTransparent( 0, 0, 0, 0 );
const Color Color::WhiteTransparent( 1, 1, 1, 0 );
const CompressedColor CompressedColor::Black( 0xFF000000 );
const CompressedColor CompressedColor::White( 0xFFFFFFFF );
const CompressedColor CompressedColor::BlackTransparent( 0x00000000 );
const CompressedColor CompressedColor::WhiteTransparent( 0x00FFFFFF );
}
| 27.5 | 70 | 0.751515 | vanderlokken |
942e3878f2d7cebe5475cec7a58bcb83566ca817 | 1,662 | cpp | C++ | cEpiabm/test/sweeps/test_household_sweep.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | 11 | 2021-12-02T15:24:02.000Z | 2022-03-10T14:02:13.000Z | cEpiabm/test/sweeps/test_household_sweep.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | 119 | 2021-11-24T13:56:48.000Z | 2022-03-30T11:52:07.000Z | cEpiabm/test/sweeps/test_household_sweep.cpp | SABS-R3-Epidemiology/epiabm | 8eb83fd2de84104f6f77929e3771095f7b033ddc | [
"BSD-3-Clause"
] | 3 | 2022-01-13T03:05:19.000Z | 2022-03-11T22:00:17.000Z |
#include "sweeps/household_sweep.hpp"
#include "population_factory.hpp"
#include "../catch/catch.hpp"
#include "helpers.hpp"
#include <random>
using namespace epiabm;
TEST_CASE("sweeps/household_sweep: test initialize household_sweep", "[HouseholdSweep]")
{
HouseholdSweepPtr subject = std::make_shared<HouseholdSweep>();
}
TEST_CASE("sweeps/household_sweep: test household_sweep bind_population", "[HouseholdSweep]")
{
HouseholdSweepPtr subject = std::make_shared<HouseholdSweep>();
PopulationPtr population = PopulationFactory().makePopulation(5, 5, 1000);
bind_households(population, 500);
population->initialize();
REQUIRE_NOTHROW(subject->bind_population(population));
}
TEST_CASE("sweeps/household_sweep: test household_sweep run sweep", "[HouseholdSweep]")
{
HouseholdSweepPtr subject = std::make_shared<HouseholdSweep>();
PopulationPtr population = PopulationFactory().makePopulation(5, 5, 1000);
bind_households(population, 500);
random_seed(population, 10, InfectionStatus::InfectASympt, 5);
population->initialize();
REQUIRE_NOTHROW(subject->bind_population(population));
for (int i = 0; i < 10; i++)
REQUIRE_NOTHROW((*subject)(static_cast<unsigned short>(i)));
}
TEST_CASE("sweeps/household_sweep: test destructor", "[HouseholdSweep]")
{
{
SweepInterface* i = new HouseholdSweep();
[[maybe_unused]] HouseholdSweep* subject = dynamic_cast<HouseholdSweep*>(i);
delete i;
i = nullptr;
subject = nullptr;
}
{
SweepInterface* i = new SweepInterface();
i->operator()(0);
delete i;
i = nullptr;
}
}
| 29.678571 | 93 | 0.699759 | Saketkr21 |
943e2ed2ddc9cfa963d6f34b837c34775cec3719 | 123 | cpp | C++ | lab2.2/errorProcess.cpp | mengguanya/Elementary-Computer-Architecture-Lab | 38167d54f9af8af0fade1ff38dd8adb795db476f | [
"MIT"
] | null | null | null | lab2.2/errorProcess.cpp | mengguanya/Elementary-Computer-Architecture-Lab | 38167d54f9af8af0fade1ff38dd8adb795db476f | [
"MIT"
] | null | null | null | lab2.2/errorProcess.cpp | mengguanya/Elementary-Computer-Architecture-Lab | 38167d54f9af8af0fade1ff38dd8adb795db476f | [
"MIT"
] | null | null | null | #include"errorProcess.h"
#include"Inst.h"
void openElfError(FILE* elfFile) {
}
void instAddrError(ADDR addr) {
} | 13.666667 | 35 | 0.682927 | mengguanya |
9446fd5576f98b99736acbf0ca162971723d07d3 | 755 | hpp | C++ | src/mlt/models/transformers/zero_components_analysis.hpp | fedeallocati/MachineLearningToolkit | 8614ee2c8c5211a3eefceb10a50576e0485cefd9 | [
"MIT"
] | 6 | 2015-08-31T11:43:19.000Z | 2018-07-22T11:03:47.000Z | src/mlt/models/transformers/zero_components_analysis.hpp | fedeallocati/MachineLearningToolkit | 8614ee2c8c5211a3eefceb10a50576e0485cefd9 | [
"MIT"
] | null | null | null | src/mlt/models/transformers/zero_components_analysis.hpp | fedeallocati/MachineLearningToolkit | 8614ee2c8c5211a3eefceb10a50576e0485cefd9 | [
"MIT"
] | null | null | null | #ifndef MLT_MODELS_TRANSFORMERS_ZERO_COMPONENTS_ANALYSIS_HPP
#define MLT_MODELS_TRANSFORMERS_ZERO_COMPONENTS_ANALYSIS_HPP
#include "principal_components_analysis_impl.hpp"
namespace mlt {
namespace models {
namespace transformers {
class ZeroComponentsAnalysis : public PrincipalComponentsAnalysisImpl<ZeroComponentsAnalysis> {
public:
explicit ZeroComponentsAnalysis() : PrincipalComponentsAnalysisImpl(true) {}
Result transform(Features input) const {
assert(_fitted);
return _components * PrincipalComponentsAnalysisImpl<Self>::transform(input);
}
Features inverse_transform(Result input) const {
assert(_fitted);
return PrincipalComponentsAnalysisImpl::inverse_transform(_components.transpose() * input);
}
};
}
}
}
#endif | 29.038462 | 96 | 0.81457 | fedeallocati |
944c92e249ad5fa1251777c70bb60692378a8bbe | 2,673 | cpp | C++ | tools/editor/source/command/standard/modifyDepth.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | 6 | 2015-04-21T11:30:52.000Z | 2020-04-29T00:10:04.000Z | tools/editor/source/command/standard/modifyDepth.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | tools/editor/source/command/standard/modifyDepth.cpp | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | #include <string>
#include "pixelboost/maths/boundingBox.h"
#include "command/standard/modifyDepth.h"
#include "core/uidHelpers.h"
#include "project/entity.h"
#include "project/project.h"
#include "project/record.h"
#include "project/schema.h"
#include "view/entity/entity.h"
#include "view/level.h"
#include "core.h"
#include "view.h"
Command* ModifyDepthCommand::Create()
{
return new ModifyDepthCommand();
}
std::string ModifyDepthCommand::GetStaticName()
{
return "modifyDepth";
}
ModifyDepthCommand::ModifyDepthCommand()
{
}
ModifyDepthCommand::~ModifyDepthCommand()
{
}
std::string ModifyDepthCommand::GetName()
{
return ModifyDepthCommand::GetStaticName();
}
bool ModifyDepthCommand::CanUndo()
{
return false;
}
bool ModifyDepthCommand::Do(std::string& returnString)
{
Core* core = Core::Instance();
Level* level = View::Instance()->GetLevel();
Selection& selection = core->GetSelection();
pb::BoundingBox selectionBounds;
const Selection::Entities& entities = selection.GetSelection();
float selectionMin = +INFINITY;
float selectionMax = -INFINITY;
for (Selection::Entities::const_iterator it = entities.begin(); it != entities.end(); ++it)
{
ViewEntity* entity = level->GetEntityById(it->first);
selectionBounds.Expand(entity->GetBoundingBox());
selectionMin = glm::min(selectionMin, entity->GetPosition().z);
selectionMax = glm::max(selectionMax, entity->GetPosition().z);
}
float offset = 0.f;
bool modify = false;
float otherMin = +INFINITY;
float otherMax = -INFINITY;
Level::EntityList boundsEntities = level->GetEntitiesInBounds(selectionBounds);
for (Level::EntityList::iterator it = boundsEntities.begin(); it != boundsEntities.end(); ++it)
{
ViewEntity* entity = *it;
if (!selection.IsSelected(GenerateSelectionUid(entity->GetUid())))
{
modify = true;
otherMin = glm::min(otherMin, entity->GetPosition().z);
otherMax = glm::max(otherMax, entity->GetPosition().z);
}
}
if (IsArgumentSet("f"))
{
offset = (otherMax + 1.f) - selectionMin;
} else if (IsArgumentSet("b"))
{
offset = (otherMin - 1.f) - selectionMax;
}
if (modify && offset != 0.f)
{
for (Selection::Entities::const_iterator it = entities.begin(); it != entities.end(); ++it)
{
ViewEntity* entity = level->GetEntityById(it->first);
entity->Transform(glm::vec3(0,0,offset));
entity->CommitTransform();
}
}
return true;
}
| 25.216981 | 99 | 0.632997 | pixelballoon |
944fbb889b970c185bf1c36d8ce933caa50fb773 | 822 | hpp | C++ | src/aspell-60/common/error.hpp | reydajp/build-spell | a88ffbb9ffedae3f20933b187c95851e47e0e4c3 | [
"MIT"
] | 31 | 2016-11-08T05:13:02.000Z | 2022-02-23T19:13:01.000Z | src/aspell-60/common/error.hpp | reydajp/build-spell | a88ffbb9ffedae3f20933b187c95851e47e0e4c3 | [
"MIT"
] | 6 | 2017-01-17T20:21:55.000Z | 2021-09-02T07:36:18.000Z | src/aspell-60/common/error.hpp | reydajp/build-spell | a88ffbb9ffedae3f20933b187c95851e47e0e4c3 | [
"MIT"
] | 5 | 2017-07-11T11:10:55.000Z | 2022-02-14T01:55:16.000Z | /* This file is part of The New Aspell
* Copyright (C) 2001-2002 by Kevin Atkinson under the GNU LGPL
* license version 2.0 or 2.1. You should have received a copy of the
* LGPL license along with this library if you did not you can find it
* at http://www.gnu.org/. */
#ifndef ASPELL_ERROR__HPP
#define ASPELL_ERROR__HPP
namespace acommon {
struct ErrorInfo;
struct Error {
const char * mesg; // expected to be allocated with malloc
const ErrorInfo * err;
Error() : mesg(0), err(0) {}
Error(const Error &);
Error & operator=(const Error &);
~Error();
bool is_a(const ErrorInfo * e) const;
};
struct ErrorInfo {
const ErrorInfo * isa;
const char * mesg;
unsigned int num_parms;
const char * parms[3];
};
}
#endif /* ASPELL_ERROR__HPP */
| 21.631579 | 74 | 0.647202 | reydajp |
944fd654a145a501e39a490b0cbe8956d80ae612 | 2,743 | cpp | C++ | src/dfm/nodestore/impl/DatabaseRotatingImp.cpp | dfm-official/dfm | 97f133aa87b17c760b90f2358d6ba10bc7ad9d1f | [
"ISC"
] | null | null | null | src/dfm/nodestore/impl/DatabaseRotatingImp.cpp | dfm-official/dfm | 97f133aa87b17c760b90f2358d6ba10bc7ad9d1f | [
"ISC"
] | null | null | null | src/dfm/nodestore/impl/DatabaseRotatingImp.cpp | dfm-official/dfm | 97f133aa87b17c760b90f2358d6ba10bc7ad9d1f | [
"ISC"
] | null | null | null |
#include <ripple/nodestore/impl/DatabaseRotatingImp.h>
#include <ripple/app/ledger/Ledger.h>
#include <ripple/protocol/HashPrefix.h>
namespace ripple {
namespace NodeStore {
DatabaseRotatingImp::DatabaseRotatingImp(
std::string const& name,
Scheduler& scheduler,
int readThreads,
Stoppable& parent,
std::unique_ptr<Backend> writableBackend,
std::unique_ptr<Backend> archiveBackend,
Section const& config,
beast::Journal j)
: DatabaseRotating(name, parent, scheduler, readThreads, config, j)
, pCache_(std::make_shared<TaggedCache<uint256, NodeObject>>(
name, cacheTargetSize, cacheTargetAge, stopwatch(), j))
, nCache_(std::make_shared<KeyCache<uint256>>(
name, stopwatch(), cacheTargetSize, cacheTargetAge))
, writableBackend_(std::move(writableBackend))
, archiveBackend_(std::move(archiveBackend))
{
if (writableBackend_)
fdLimit_ += writableBackend_->fdlimit();
if (archiveBackend_)
fdLimit_ += archiveBackend_->fdlimit();
}
std::unique_ptr<Backend>
DatabaseRotatingImp::rotateBackends(
std::unique_ptr<Backend> newBackend)
{
auto oldBackend {std::move(archiveBackend_)};
archiveBackend_ = std::move(writableBackend_);
writableBackend_ = std::move(newBackend);
return oldBackend;
}
void
DatabaseRotatingImp::store(NodeObjectType type, Blob&& data,
uint256 const& hash, std::uint32_t seq)
{
#if RIPPLE_VERIFY_NODEOBJECT_KEYS
assert(hash == sha512Hash(makeSlice(data)));
#endif
auto nObj = NodeObject::createObject(type, std::move(data), hash);
pCache_->canonicalize(hash, nObj, true);
getWritableBackend()->store(nObj);
nCache_->erase(hash);
storeStats(nObj->getData().size());
}
bool
DatabaseRotatingImp::asyncFetch(uint256 const& hash,
std::uint32_t seq, std::shared_ptr<NodeObject>& object)
{
object = pCache_->fetch(hash);
if (object || nCache_->touch_if_exists(hash))
return true;
Database::asyncFetch(hash, seq, pCache_, nCache_);
return false;
}
void
DatabaseRotatingImp::tune(int size, std::chrono::seconds age)
{
pCache_->setTargetSize(size);
pCache_->setTargetAge(age);
nCache_->setTargetSize(size);
nCache_->setTargetAge(age);
}
void
DatabaseRotatingImp::sweep()
{
pCache_->sweep();
nCache_->sweep();
}
std::shared_ptr<NodeObject>
DatabaseRotatingImp::fetchFrom(uint256 const& hash, std::uint32_t seq)
{
Backends b = getBackends();
auto nObj = fetchInternal(hash, *b.writableBackend);
if (! nObj)
{
nObj = fetchInternal(hash, *b.archiveBackend);
if (nObj)
{
getWritableBackend()->store(nObj);
nCache_->erase(hash);
}
}
return nObj;
}
}
}
| 25.165138 | 71 | 0.689391 | dfm-official |
94524131c04cd329a7467cb20148df5e865a809b | 5,707 | hpp | C++ | Math/Geometry.hpp | GlynnJKW/Stratum | ddc55796f3207fe3df23c455c6304cb72aebcb02 | [
"MIT"
] | 2 | 2019-10-01T22:55:47.000Z | 2019-10-04T20:25:29.000Z | Math/Geometry.hpp | Shmaug/vkCAVE | e502aedaf172047557f0454acb170a46b9d350f8 | [
"MIT"
] | null | null | null | Math/Geometry.hpp | Shmaug/vkCAVE | e502aedaf172047557f0454acb170a46b9d350f8 | [
"MIT"
] | null | null | null | #pragma once
#include <Math/Math.hpp>
struct Sphere {
float3 mCenter;
float mRadius;
inline Sphere() : mCenter(float3()), mRadius(0) {}
inline Sphere(const float3& center, float radius) : mCenter(center), mRadius(radius) {}
};
struct AABB {
float3 mMin;
float3 mMax;
AABB() : mMin(float3()), mMax(float3()) {}
AABB(const float3& min, const float3& max) : mMin(min), mMax(max) {}
AABB(const AABB& aabb) : mMin(aabb.mMin), mMax(aabb.mMax) {}
AABB(const AABB& aabb, const float4x4& transform) : AABB(aabb) {
*this *= transform;
}
inline float3 Center() const { return (mMax + mMin) * .5f; }
inline float3 Extents() const { return (mMax - mMin) * .5f; }
inline bool Intersects(const float3& point) const {
float3 e = (mMax - mMin) * .5f;
float3 s = point - (mMax + mMin) * .5f;
return
(s.x <= e.x && s.x >= -e.x) &&
(s.y <= e.y && s.y >= -e.y) &&
(s.z <= e.z && s.z >= -e.z);
}
inline bool Intersects(const Sphere& sphere) const {
float3 e = (mMax - mMin) * .5f;
float3 s = sphere.mCenter - (mMax + mMin) * .5f;
float3 delta = e - s;
float sqDist = 0.0f;
for (int i = 0; i < 3; i++) {
if (s[i] < -e[i]) sqDist += delta[i];
if (s[i] > e[i]) sqDist += delta[i];
}
return sqDist <= sphere.mRadius * sphere.mRadius;
}
inline bool Intersects(const AABB& aabb) const {
// for each i in (x, y, z) if a_min(i) > b_max(i) or b_min(i) > a_max(i) then return false
bool dx = (mMin.x > aabb.mMax.x) || (aabb.mMin.x > mMax.x);
bool dy = (mMin.y > aabb.mMax.y) || (aabb.mMin.y > mMax.y);
bool dz = (mMin.z > aabb.mMax.z) || (aabb.mMin.z > mMax.z);
return !(dx || dy || dz);
}
inline bool Intersects(const float4 frustum[6]) const {
float3 center = Center();
float3 extent = Extents();
for (uint32_t i = 0; i < 6; i++) {
float r = dot(extent, abs(frustum[i].xyz));
float d = dot(center, frustum[i].xyz) - frustum[i].w;
if (d <= -r) return false;
}
return true;
}
inline void Encapsulate(const float3& p) {
mMin = min(mMin, p);
mMax = max(mMax, p);
}
inline void Encapsulate(const AABB& aabb) {
mMin = min(aabb.mMin, mMin);
mMax = max(aabb.mMax, mMax);
}
inline AABB operator *(const float4x4& transform) {
return AABB(*this, transform);
}
inline AABB operator *=(const float4x4& transform) {
float3 corners[8]{
mMax, // 1,1,1
float3(mMin.x, mMax.y, mMax.z), // 0,1,1
float3(mMax.x, mMax.y, mMin.z), // 1,1,0
float3(mMin.x, mMax.y, mMin.z), // 0,1,0
float3(mMax.x, mMin.y, mMax.z), // 1,0,1
float3(mMin.x, mMin.y, mMax.z), // 0,0,1
float3(mMax.x, mMin.y, mMin.z), // 1,0,0
mMin, // 0,0,0
};
for (uint32_t i = 0; i < 8; i++)
corners[i] = (transform * float4(corners[i], 1)).xyz;
mMin = corners[0];
mMax = corners[0];
for (uint32_t i = 1; i < 8; i++) {
mMin = min(mMin, corners[i]);
mMax = max(mMax, corners[i]);
}
return *this;
}
};
struct Ray {
float3 mOrigin;
float3 mDirection;
inline Ray() : mOrigin(float3()), mDirection(float3(0,0,1)) {};
inline Ray(const float3& ro, const float3& rd) : mOrigin(ro), mDirection(rd) {};
inline float Intersect(const float4& plane) const {
return -(dot(mOrigin, plane.xyz) + plane.w) / dot(mDirection, plane.xyz);
}
inline float Intersect(const float3& planeNormal, const float3& planePoint) const {
return -dot(mOrigin - planePoint, planeNormal) / dot(mDirection, planeNormal);
}
inline bool Intersect(const AABB& aabb, float2& t) const {
float3 id = 1.f / mDirection;
float3 pmin = (aabb.mMin - mOrigin) * id;
float3 pmax = (aabb.mMax - mOrigin) * id;
float3 mn, mx;
mn.x = id.x >= 0.f ? pmin.x : pmax.x;
mn.y = id.y >= 0.f ? pmin.y : pmax.y;
mn.z = id.z >= 0.f ? pmin.z : pmax.z;
mx.x = id.x >= 0.f ? pmax.x : pmin.x;
mx.y = id.y >= 0.f ? pmax.y : pmin.y;
mx.z = id.z >= 0.f ? pmax.z : pmin.z;
t = float2(fmaxf(fmaxf(mn.x, mn.y), mn.z), fminf(fminf(mx.x, mx.y), mx.z));
return t.y > t.x;
}
inline bool Intersect(const Sphere& sphere, float2& t) const {
float3 pq = mOrigin - sphere.mCenter;
float a = dot(mDirection, mDirection);
float b = 2 * dot(pq, mDirection);
float c = dot(pq, pq) - sphere.mRadius * sphere.mRadius;
float d = b * b - 4 * a * c;
if (d < 0.f) return false;
d = sqrt(d);
t = -.5f * float2(b + d, b - d) / a;
return true;
}
inline bool Intersect(float3 v0, float3 v1, float3 v2, float3* tuv) const {
// http://jcgt.org/published/0002/01/05/paper.pdf
v0 -= mOrigin;
v1 -= mOrigin;
v2 -= mOrigin;
float3 rd = mDirection;
float3 ad = abs(mDirection);
uint32_t largesti = 0;
if (ad[largesti] < ad[1]) largesti = 1;
if (ad[largesti] < ad[2]) largesti = 2;
float idz;
float2 rdz;
if (largesti == 0) {
v0 = float3(v0.y, v0.z, v0.x);
v1 = float3(v1.y, v1.z, v1.x);
v2 = float3(v2.y, v2.z, v2.x);
idz = 1.f / rd.x;
rdz = float2(rd.y, rd.z) * idz;
} else if (largesti == 1) {
v0 = float3(v0.z, v0.x, v0.y);
v1 = float3(v1.z, v1.x, v1.y);
v2 = float3(v2.z, v2.x, v2.y);
idz = 1.f / rd.y;
rdz = float2(rd.z, rd.x) * idz;
} else {
idz = 1.f / rd.z;
rdz = float2(rd.x, rd.y) * idz;
}
v0 = float3(v0.x - v0.z * rdz.x, v0.y - v0.z * rdz.y, v0.z * idz);
v1 = float3(v1.x - v1.z * rdz.x, v1.y - v1.z * rdz.y, v1.z * idz);
v2 = float3(v2.x - v2.z * rdz.x, v2.y - v2.z * rdz.y, v2.z * idz);
float u = v2.x * v1.y - v2.y * v1.x;
float v = v0.x * v2.y - v0.y * v2.x;
float w = v1.x * v0.y - v1.y * v0.x;
if ((u < 0 || v < 0 || w < 0) && (u > 0 || v > 0 || w > 0)) return false;
float det = u + v + w;
if (det == 0) return false; // co-planar
float t = u * v0.z + v * v1.z + w * v2.z;
if (tuv) *tuv = float3(t, u, v) / det;
return true;
}
}; | 29.569948 | 92 | 0.574382 | GlynnJKW |
94550e3ee33e359fa7324f280541daf2b1d3a1e7 | 2,967 | hpp | C++ | src/Backend.hpp | VetoProjects/ShaderSandbox | 5ee34badb690cff611f105fbe9bc56e7ca219515 | [
"MIT"
] | 2 | 2015-01-26T17:17:14.000Z | 2015-02-07T18:07:51.000Z | src/Backend.hpp | VetoProjects/ShaderSandbox | 5ee34badb690cff611f105fbe9bc56e7ca219515 | [
"MIT"
] | null | null | null | src/Backend.hpp | VetoProjects/ShaderSandbox | 5ee34badb690cff611f105fbe9bc56e7ca219515 | [
"MIT"
] | 1 | 2019-12-19T15:06:45.000Z | 2019-12-19T15:06:45.000Z | #ifndef BACKEND_HPP
#define BACKEND_HPP
#include <QDesktopServices>
#include <QUrl>
#include "SettingsBackend.hpp"
#include "SettingsWindow.hpp"
#include "LiveThread.hpp"
#include "Instances/IInstance.hpp"
using namespace Instances;
/**
* @brief The Backend class
*
* The heart and soul of the eidtors functionality.
* Is connected to all the other parts of the application
* (through SIGNALs as well as references) and keeps track
* of all the windows and code evaluation threads that are created
* and deleted.
*/
class Backend : public QObject
{
Q_OBJECT
public:
static QDir directoryOf(const QString&) noexcept;
explicit Backend(QObject *parent = 0);
~Backend();
void addInstance(IInstance *, bool = true) noexcept;
void childExited(IInstance *, QString) noexcept;
bool isLast() noexcept;
bool removeInstance(IInstance*, bool = true) noexcept;
bool removeInstance(int, bool = true) noexcept;
void removeSettings(IInstance*) noexcept;
void removeSettings(int) noexcept;
void saveAllSettings() noexcept;
void saveSettings(IInstance *, QString) noexcept;
QHash<QString, QVariant> getSettings(IInstance *) noexcept;
QHash<QString, QVariant> getSettings(int id) noexcept;
int nextID() noexcept;
QList<int> loadIds() noexcept;
QVariant getSetting(QString key, QVariant defaultValue = QVariant()) noexcept;
Q_SIGNALS:
void warningSignal(QWidget*, QString);
void closeAction();
void saveAction();
void showResults(const QString &);
void childDoSaveSettings();
public Q_SLOTS:
void settingsWindowRequested(IInstance*) noexcept;
void openHelp(IInstance *) noexcept;
void instanceClosing(IInstance *) noexcept;
void instanceDestroyed(QObject*) noexcept;
void instanceRunCode(IInstance *) noexcept;
void instanceStopCode(IInstance *) noexcept;
void instanceChangedSetting(IInstance *, const QString &key, const QVariant &value) noexcept;
void instanceRequestSetting(IInstance *, const QString &key, QVariant &value) noexcept;
void instanceChangedSettings(IInstance *, const QHash<QString, QVariant> &) noexcept;
void instanceRequestSettings(IInstance *, QHash<QString, QVariant> &) noexcept;
void instanceLoadModel(IInstance*, const QString &, const QVector3D &, const QVector3D &, const QVector3D &) noexcept;
// void instanceRemoveID(IInstance *instance);
void childSaidCloseAll() noexcept;
void getExecutionResults(GlLiveThread*, QString) noexcept;
void getError(GlLiveThread*, QString) noexcept;
void getVertexError(GlLiveThread*, QString, int) noexcept;
void getFragmentError(GlLiveThread*, QString, int) noexcept;
private:
void runGlFile(IInstance *) noexcept;
void terminateThread(long id) noexcept;
void saveIDs() noexcept;
QList<int> ids;
QHash<long, std::shared_ptr<IInstance>> instances;
QHash<long, std::shared_ptr<LiveThread>> threads;
};
#endif // BACKEND_HPP
| 35.746988 | 122 | 0.738456 | VetoProjects |
9458b9e8951239ec7dae718a1eb5b1b4c3c2560c | 551 | cpp | C++ | src/components/player.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | src/components/player.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | src/components/player.cpp | wareya/kotareci | 14c87d1364d442456f93cebe73a288f85b79ba74 | [
"Libpng"
] | null | null | null | #include "gamecomponents.hpp"
#include "player.hpp"
namespace Sys
{
Player::Player(entityid_t myEntity, const char * name) : Component(myEntity), character(nullptr), name(name), myself(false)
{
spawntimer = -1;
Players.add(this);
puts("MAKING A PLAYER");
}
Player::~Player()
{
delete character;
Players.remove(this);
}
void Player::spawn(double x, double y)
{
if(!character)
character = new Character(entityID, x, y);
}
Collection<Player> Players;
}
| 22.958333 | 127 | 0.593466 | wareya |
94618d4bccdcb327d8e6bea600a3a3d5b95fe3f8 | 902 | cpp | C++ | Engine/resourcemodelselect.cpp | vadkasevas/BAS | 657f62794451c564c77d6f92b2afa9f5daf2f517 | [
"MIT"
] | 302 | 2016-05-20T12:55:23.000Z | 2022-03-29T02:26:14.000Z | Engine/resourcemodelselect.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 9 | 2016-07-21T09:04:50.000Z | 2021-05-16T07:34:42.000Z | Engine/resourcemodelselect.cpp | chulakshana/BAS | 955f5a41bd004bcdd7d19725df6ab229b911c09f | [
"MIT"
] | 113 | 2016-05-18T07:48:37.000Z | 2022-02-26T12:59:39.000Z | #include "resourcemodelselect.h"
#include "every_cpp.h"
namespace BrowserAutomationStudioFramework
{
ResourceModelSelect::ResourceModelSelect(QObject *parent) :
ResourceModelAbstract(parent)
{
Type = Combo;
}
QStringList ResourceModelSelect::GetValues()
{
return Values;
}
void ResourceModelSelect::SetValues(const QStringList& val)
{
Values = val;
}
QList<int> ResourceModelSelect::GetSelected()
{
return Selected;
}
void ResourceModelSelect::SetSelected(const QList<int>& val)
{
Selected = val;
}
QString ResourceModelSelect::GetTypeId()
{
return QString("Select");
}
ResourceModelSelect::SelectType ResourceModelSelect::GetSelectType()
{
return Type;
}
void ResourceModelSelect::SetSelectType(SelectType val)
{
Type = val;
}
}
| 20.976744 | 72 | 0.63969 | vadkasevas |
946276e2f18418d699aca9429a5b2ba553f9896d | 7,477 | cpp | C++ | language-extensions/R/src/RParamContainer.cpp | rabryst/sql-server-language-extensions | a6a25890d1c3e449537eaaafab706c6c1e8b51cb | [
"MIT"
] | 82 | 2019-05-24T00:36:57.000Z | 2022-02-21T23:51:46.000Z | language-extensions/R/src/RParamContainer.cpp | rabryst/sql-server-language-extensions | a6a25890d1c3e449537eaaafab706c6c1e8b51cb | [
"MIT"
] | 20 | 2019-07-05T06:12:28.000Z | 2022-03-31T20:48:30.000Z | language-extensions/R/src/RParamContainer.cpp | rabryst/sql-server-language-extensions | a6a25890d1c3e449537eaaafab706c6c1e8b51cb | [
"MIT"
] | 35 | 2019-05-24T01:44:07.000Z | 2022-02-28T13:29:44.000Z | //**************************************************************************************************
// RExtension : A language extension implementing the SQL Server
// external language communication protocol for R.
// Copyright (C) 2020 Microsoft Corporation.
//
// This file is part of RExtension.
//
// RExtension 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.
//
// RExtension 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 RExtension. If not, see <https://www.gnu.org/licenses/>.
//
// @File: RParamContainer.cpp
//
// Purpose:
// RExtension input/output parameters wrappers, along with the container consolidating them.
//
//**************************************************************************************************
#include "Common.h"
#include "RParam.h"
#include "RParamContainer.h"
using namespace std;
//--------------------------------------------------------------------------------------------------
// Function map - maps a ODBC C data type to the appropriate param creator
//
const RParamContainer::CreateParamFnMap RParamContainer::sm_FnCreateParamMap =
{
{static_cast<SQLSMALLINT>(SQL_C_SLONG),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLINTEGER, Rcpp::IntegerVector, int, SQL_C_SLONG>>)},
{static_cast<SQLSMALLINT>(SQL_C_SBIGINT),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLBIGINT, Rcpp::NumericVector, double, SQL_C_SBIGINT>>)},
{static_cast<SQLSMALLINT>(SQL_C_FLOAT),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLREAL, Rcpp::NumericVector, double, SQL_C_FLOAT>>)},
{static_cast<SQLSMALLINT>(SQL_C_DOUBLE),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLDOUBLE, Rcpp::NumericVector, double, SQL_C_DOUBLE>>)},
{static_cast<SQLSMALLINT>(SQL_C_SSHORT),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLSMALLINT, Rcpp::IntegerVector, int, SQL_C_SSHORT>>)},
{static_cast<SQLSMALLINT>(SQL_C_UTINYINT),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLCHAR, Rcpp::IntegerVector, int, SQL_C_UTINYINT>>)},
{static_cast<SQLSMALLINT>(SQL_C_BIT),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RParamTemplate<SQLCHAR, Rcpp::LogicalVector, int, SQL_C_BIT>>)},
{static_cast<SQLSMALLINT>(SQL_C_CHAR),
static_cast<fnCreateParam>(&RParamContainer::CreateParam<RCharacterParam<char, SQLCHAR>>)},
{static_cast<SQLSMALLINT>(SQL_C_WCHAR),
static_cast<fnCreateParam>(&RParamContainer::CreateParam<RCharacterParam<char16_t, SQLWCHAR>>)},
{static_cast<SQLSMALLINT>(SQL_C_BINARY),
static_cast<fnCreateParam>(&RParamContainer::CreateParam<RRawParam>)},
{static_cast<SQLSMALLINT>(SQL_C_TYPE_DATE),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RDateTimeParam<SQL_DATE_STRUCT, Rcpp::DateVector, Rcpp::Date>>)},
{static_cast<SQLSMALLINT>(SQL_C_TYPE_TIMESTAMP),
static_cast<fnCreateParam>(&RParamContainer::CreateParam
<RDateTimeParam<SQL_TIMESTAMP_STRUCT, Rcpp::DatetimeVector, Rcpp::Datetime>>)},
{static_cast<SQLSMALLINT>(SQL_C_NUMERIC),
static_cast<fnCreateParam>(&RParamContainer::CreateParam<RNumericParam>)},
};
//--------------------------------------------------------------------------------------------------
// Name: RParamContainer::Init
//
// Description:
// Initialize this container with the number of parameters.
//
void RParamContainer::Init(SQLSMALLINT paramsNumber)
{
LOG("RParamContainer::Init");
m_params.resize(paramsNumber);
}
//--------------------------------------------------------------------------------------------------
// Name: RParamContainer::AddParamToEmbeddedR
//
// Description:
// Creates an RParam object containing an RcppVector, assigns the parameter name to this
// RcppVector so that the underlying R object can be accessed via this parameter name in the
// embedded R environment.
// Eventually, adds the RParam to m_params for future use.
// Creation is done by calling the respective constructor based on the datatype.
//
void RParamContainer::AddParamToEmbeddedR(
SQLUSMALLINT paramNumber,
const SQLCHAR *paramName,
SQLSMALLINT paramNameLength,
SQLSMALLINT dataType,
SQLULEN paramSize,
SQLSMALLINT decimalDigits,
SQLPOINTER paramValue,
SQLINTEGER strLen_or_Ind,
SQLSMALLINT inputOutputType)
{
LOG("RParamContainer::AddParamToEmbeddedR");
CreateParamFnMap::const_iterator it = sm_FnCreateParamMap.find(dataType);
if (it == sm_FnCreateParamMap.end())
{
throw runtime_error("Unsupported parameter type encountered when creating param #"
+ to_string(paramNumber));
}
(this->*it->second)(
paramNumber,
paramName,
paramNameLength,
dataType,
paramSize,
decimalDigits,
paramValue,
strLen_or_Ind,
inputOutputType);
}
//--------------------------------------------------------------------------------------------------
// Name: RParamContainer::CreateParam
//
// Description:
// Creates an RParam object, adds the parameter with paramValue for given dataType
// to the Embedded R environment and stores it in m_params for future use.
//
template<class RParamType>
void RParamContainer::CreateParam(
SQLUSMALLINT paramNumber,
const SQLCHAR *paramName,
SQLSMALLINT paramNameLength,
SQLSMALLINT dataType,
SQLULEN paramSize,
SQLSMALLINT decimalDigits,
SQLPOINTER paramValue,
SQLINTEGER strLen_or_Ind,
SQLSMALLINT inputOutputType)
{
LOG("RParamContainer::CreateParam");
unique_ptr<RParam> paramToBeAdded =
make_unique<RParamType>(
paramNumber,
paramName,
paramNameLength,
dataType,
paramSize,
decimalDigits,
paramValue,
strLen_or_Ind,
inputOutputType);
RInside* embeddedREnvPtr = REnvironment::EmbeddedREnvironment();
(*embeddedREnvPtr)[paramToBeAdded.get()->Name().c_str()] =
static_cast<RParamType*>(
paramToBeAdded.get())->RcppVector();
Logger::LogRVariable(paramToBeAdded.get()->Name());
m_params[paramNumber] = std::move(paramToBeAdded);
}
//--------------------------------------------------------------------------------------------------
// Name: RParamContainer::GetParamValueAndStrLenInd
//
// Description:
// For the given paramNumber, calls RetriveValueAndStrLenOrInd() to retrieve the value from R and
// returns it via paramValue. Return the strLenOrInd as well.
//
void RParamContainer::GetParamValueAndStrLenInd(
SQLUSMALLINT paramNumber,
SQLPOINTER *paramValue,
SQLINTEGER *strLen_or_Ind)
{
LOG("RParamContainer::GetParamValueAndStrLenInd");
if (m_params[paramNumber] == nullptr)
{
throw runtime_error("InitParam not called for param #" + to_string(paramNumber));
}
RParam *param = m_params[paramNumber].get();
if (param->InputOutputType() < SQL_PARAM_INPUT_OUTPUT)
{
throw runtime_error("Requested param #" + to_string(paramNumber) +
" is not initialized as an output parameter");
}
// Retrieve the value from R
//
param->RetrieveValueAndStrLenInd();
*paramValue = param->Value();
*strLen_or_Ind = param->StrLenOrInd();
}
| 35.947115 | 100 | 0.6956 | rabryst |
9462f806e416cf8bea8ec122a7810f8366adfcdf | 5,006 | cpp | C++ | test/rules/constrictor_ruleset_test.cpp | TheApX/battlesnake-engine-cpp | 05053f06ecc631f037417bd0d897b28f48dfe07d | [
"MIT"
] | 3 | 2021-07-05T22:42:26.000Z | 2021-07-29T12:14:43.000Z | test/rules/constrictor_ruleset_test.cpp | TheApX/battlesnake-engine-cpp | 05053f06ecc631f037417bd0d897b28f48dfe07d | [
"MIT"
] | 2 | 2021-07-12T00:11:57.000Z | 2021-09-04T19:11:38.000Z | test/rules/constrictor_ruleset_test.cpp | TheApX/battlesnake-engine-cpp | 05053f06ecc631f037417bd0d897b28f48dfe07d | [
"MIT"
] | null | null | null | #include "battlesnake/rules/constrictor_ruleset.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace battlesnake {
namespace rules {
namespace {
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::Field;
using ::testing::IsFalse;
using ::testing::IsTrue;
using ::testing::Lt;
template <class M>
auto SnakeHealthIs(M m) {
return Field(&Snake::health, m);
}
template <class M>
auto SnakeBodyIs(const M& m) {
return Field(&Snake::body, m);
}
class ConstrictorRulesetTest : public testing::Test {
protected:
std::vector<SnakeId> CreateSnakeIds(int n, StringPool& pool) {
std::vector<SnakeId> result;
result.reserve(n);
for (int i = 0; i < n; ++i) {
result.push_back(pool.Add("Snake" + std::to_string(n)));
}
return result;
}
};
TEST_F(ConstrictorRulesetTest, Sanity) {
ConstrictorRuleset ruleset;
BoardState state = ruleset.CreateInitialBoardState(0, 0, {});
EXPECT_THAT(state.width, Eq(0));
EXPECT_THAT(state.height, Eq(0));
EXPECT_THAT(state.snakes, ElementsAre());
BoardState new_state{};
ruleset.CreateNextBoardState(state, {}, 0, new_state);
EXPECT_THAT(new_state.width, Eq(0));
EXPECT_THAT(new_state.height, Eq(0));
EXPECT_THAT(new_state.snakes, ElementsAre());
EXPECT_THAT(ruleset.IsGameOver(new_state), IsTrue());
}
TEST_F(ConstrictorRulesetTest, NoFoodInitially) {
ConstrictorRuleset ruleset;
StringPool pool;
BoardState state = ruleset.CreateInitialBoardState(11, 11,
{
pool.Add("snake1"),
pool.Add("snake2"),
});
EXPECT_THAT(state.Food(), ElementsAre());
}
class ConstrictorCreateNextBoardStateTest : public ConstrictorRulesetTest {};
TEST_F(ConstrictorCreateNextBoardStateTest, KeepsHealth) {
StringPool pool;
BoardState initial_state{
.width = kBoardSizeSmall,
.height = kBoardSizeSmall,
.snakes = SnakesVector::Create({
Snake{
.id = pool.Add("one"),
.body = SnakeBody::Create({
Point{1, 1},
Point{1, 2},
Point{1, 3},
}),
.health = 100,
},
}),
};
// Disable spawning random food so that it doesn't interfere with tests.
ConstrictorRuleset ruleset(StandardRuleset::Config{.food_spawn_chance = 0});
BoardState state{};
ruleset.CreateNextBoardState(
initial_state, SnakeMovesVector::Create({{pool.Add("one"), Move::Down}}),
1, state);
// Health shouldn't decrease.
EXPECT_THAT(state.snakes, ElementsAre(SnakeHealthIs(Eq(100))));
}
TEST_F(ConstrictorCreateNextBoardStateTest, GrowsSnake) {
StringPool pool;
BoardState initial_state{
.width = kBoardSizeSmall,
.height = kBoardSizeSmall,
.snakes = SnakesVector::Create({
Snake{
.id = pool.Add("one"),
.body = SnakeBody::Create({
Point{1, 1},
Point{1, 2},
Point{1, 3},
}),
.health = 100,
},
}),
};
// Disable spawning random food so that it doesn't interfere with tests.
ConstrictorRuleset ruleset(StandardRuleset::Config{.food_spawn_chance = 0});
BoardState state{};
ruleset.CreateNextBoardState(
initial_state, SnakeMovesVector::Create({{pool.Add("one"), Move::Down}}),
1, state);
// Body should grow.
EXPECT_THAT(state.snakes, ElementsAre(SnakeBodyIs(ElementsAreArray({
Point{1, 0},
Point{1, 1},
Point{1, 2},
Point{1, 2},
}))));
}
TEST_F(ConstrictorCreateNextBoardStateTest, DoesnGrowInitialSnake) {
StringPool pool;
BoardState initial_state{
.width = kBoardSizeSmall,
.height = kBoardSizeSmall,
.snakes = SnakesVector::Create({
Snake{
.id = pool.Add("one"),
.body = SnakeBody::Create({
Point{1, 1},
Point{1, 1},
Point{1, 1},
}),
.health = 100,
},
}),
};
// Disable spawning random food so that it doesn't interfere with tests.
ConstrictorRuleset ruleset(StandardRuleset::Config{.food_spawn_chance = 0});
BoardState state{};
ruleset.CreateNextBoardState(
initial_state, SnakeMovesVector::Create({{pool.Add("one"), Move::Down}}),
1, state);
// Body shouldn't grow.
EXPECT_THAT(state.snakes, ElementsAre(SnakeBodyIs(ElementsAreArray({
Point{1, 0},
Point{1, 1},
Point{1, 1},
}))));
}
} // namespace
} // namespace rules
} // namespace battlesnake
| 28.936416 | 79 | 0.571314 | TheApX |
9463985d3a5965cf52c7570db3c4457fba14df66 | 379 | cpp | C++ | libmuscle/cpp/src/libmuscle/logger.cpp | DongweiYe/muscle3 | 0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0 | [
"Apache-2.0"
] | 11 | 2018-03-12T10:43:46.000Z | 2020-06-01T10:58:56.000Z | libmuscle/cpp/src/libmuscle/logger.cpp | DongweiYe/muscle3 | 0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0 | [
"Apache-2.0"
] | 85 | 2018-03-03T15:10:56.000Z | 2022-03-18T14:05:14.000Z | libmuscle/cpp/src/libmuscle/logger.cpp | DongweiYe/muscle3 | 0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0 | [
"Apache-2.0"
] | 6 | 2018-03-12T10:47:11.000Z | 2022-02-03T13:44:07.000Z | #include <libmuscle/logger.hpp>
namespace libmuscle { namespace impl {
Logger::Logger(std::string const & instance_id, MMPClient & manager)
: instance_id_(instance_id)
, manager_(manager)
, remote_level_(LogLevel::WARNING)
{}
void Logger::set_remote_level(LogLevel level) {
remote_level_ = level;
}
void Logger::append_args_(std::ostringstream & s) {}
} }
| 18.95 | 68 | 0.71504 | DongweiYe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.